<commit_before>from builtins import zip
import os.path
import tempfile
import shutil
from pype9.cmd import plot, simulate
import neo
import ninemlcatalog
if __name__ == '__main__':
    from pype9.utils.testing import DummyTestCase as TestCase  # @UnusedImport
else:
    from unittest import TestCase  # @Reimport
    import matplotlib
    matplotlib.use('Agg')  # So DISPLAY environment variable doesn't need to be
import matplotlib.pyplot as plt  # @IgnorePep8
import matplotlib.image as img  # @IgnorePep8
import matplotlib.patches as mp  # @IgnorePep8
from pype9.utils.testing import test_cache  # @IgnorePep8


class TestPlot(TestCase):

    recorded_pops = ('Exc', 'Inh')

    isyn_amp = (100.0, 'pA')
    isyn_onset = (50.0, 'ms')
    isyn_init = (0.0, 'pA')
    t_stop = 100.0
    dt = 0.001

    rec_t_start = (1.0, 'ms')

    subVb_colour = '#ff7f0e'

    def setUp(self):
        try:
            # Try to make a cache dir so the signals don't need to be
            # regenerated each time
            self.work_dir = os.path.join(test_cache, 'cmd', 'plot')
            self.cached = True
        except OSError:
            self.work_dir = tempfile.mkdtemp()
            self.cached = False
        if not os.path.exists(self.work_dir):
            os.makedirs(self.work_dir)
        self.ref_single_cell_path = os.path.join(self.work_dir,
                                                 'single_cell_ref.png')
        self.ref_network_path = os.path.join(self.work_dir,
                                             'network_ref.png')
        self.cell_input_path = os.path.join(self.work_dir, 'plot_i.neo.pkl')
        self.cell_signal_path = os.path.join(self.work_dir, 'plot_v.neo.pkl')
        self.network_signal_path = os.path.join(self.work_dir, 'exc.neo.pkl')

    def tearDown(self):
        if not self.cached:
            shutil.rmtree(self.work_dir)

    def test_single_cell_plot(self, show=False):
        if not os.path.exists(self.cell_signal_path):
            # Generate test signal
            if not os.path.exists(self.cell_input_path):
                # First simulate input signal to have something to play into
                # izhikevich cell
                argv = ("//input/StepCurrent#StepCurrent nest {t_stop} {dt} "
                        "--record current_output {out_path} {rec_t_start}"
                        "--prop amplitude {amp} "
                        "--prop onset {onset} "
                        "--init_value current_output {init} "
                        "--build_mode force"
                        .format(out_path=self.cell_input_path,
                                rec_t_start='{} {}'.format(*self.rec_t_start),
                                t_stop=self.t_stop, dt=self.dt,
                                amp='{} {}'.format(*self.isyn_amp),
                                onset='{} {}'.format(*self.isyn_onset),
                                init='{} {}'.format(*self.isyn_init)))
                # Run input signal simulation
                simulate.run(argv.split())
            argv = (
                "//neuron/Izhikevich#SampleIzhikevichFastSpiking "
                "nest {} 0.01"
                "--record V {} "
                "--init_value U 1.625 pA "
                "--init_value V -65.0 mV "
                "--play iSyn {in_path} "
                "--init_regime subVb "
                "--build_name IzhikevichFastSpikingPlotVersion ".format(
                    self.t_stop, self.cell_signal_path,
                    in_path=self.cell_input_path))
            simulate.run(argv.split())
        # Run plotting command
        out_path = '{}/single_cell.png'.format(self.work_dir)
        argv = ("{in_path} --save {out_path} --dims 5 5 "
                "--resolution 100.0 {hide}"
                .format(in_path=self.cell_signal_path, out_path=out_path,
                        name='v', hide=('' if show else '--hide')))
        plot.run(argv.split())
        image = img.imread(out_path)
        self._ref_single_cell_plot()
        ref_image = img.imread(self.ref_single_cell_path)
        self.assertEqual(image.shape, ref_image.shape)
        self.assertTrue(
            (image == ref_image).all(),
            "Ploted single cell data using 'plot' command (saved to '{}') did "
            "not match loaded image from '{}'"
            .format(out_path, self.ref_single_cell_path))

    def test_network_plot(self):
        if not os.path.exists(self.network_signal_path):
            # Generate test signal
            brunel_ai = ninemlcatalog.load(<commit_msg>test_cmds now pass on Py3<commit_after>from builtins import zip
import os.path
import tempfile
import shutil
from pype9.cmd import plot, simulate
import neo
import ninemlcatalog
if __name__ == '__main__':
    from pype9.utils.testing import DummyTestCase as TestCase  # @UnusedImport
else:
    from unittest import TestCase  # @Reimport
    import matplotlib
    matplotlib.use('Agg')  # So DISPLAY environment variable doesn't need to be
import matplotlib.pyplot as plt  # @IgnorePep8
import matplotlib.image as img  # @IgnorePep8
import matplotlib.patches as mp  # @IgnorePep8
from pype9.utils.testing import test_cache  # @IgnorePep8


class TestPlot(TestCase):

    recorded_pops = ('Exc', 'Inh')

    isyn_amp = (100.0, 'pA')
    isyn_onset = (50.0, 'ms')
    isyn_init = (0.0, 'pA')
    t_stop = 100.0
    dt = 0.001

    rec_t_start = (1.0, 'ms')

    subVb_colour = '#ff7f0e'

    def setUp(self):
        try:
            # Try to make a cache dir so the signals don't need to be
            # regenerated each time
            self.work_dir = os.path.join(test_cache, 'cmd', 'plot')
            self.cached = True
        except OSError:
            self.work_dir = tempfile.mkdtemp()
            self.cached = False
        if not os.path.exists(self.work_dir):
            os.makedirs(self.work_dir)
        self.ref_single_cell_path = os.path.join(self.work_dir,
                                                 'single_cell_ref.png')
        self.ref_network_path = os.path.join(self.work_dir,
                                             'network_ref.png')
        self.cell_input_path = os.path.join(self.work_dir, 'plot_i.neo.pkl')
        self.cell_signal_path = os.path.join(self.work_dir, 'plot_v.neo.pkl')
        self.network_signal_path = os.path.join(self.work_dir, 'exc.neo.pkl')

    def tearDown(self):
        if not self.cached:
            shutil.rmtree(self.work_dir)

    def test_single_cell_plot(self, show=False):
        if not os.path.exists(self.cell_signal_path):
            # Generate test signal
            if not os.path.exists(self.cell_input_path):
                # First simulate input signal to have something to play into
                # izhikevich cell
                argv = ("//input/StepCurrent#StepCurrent nest {t_stop} {dt} "
                        "--record current_output {out_path} {rec_t_start} "
                        "--prop amplitude {amp} "
                        "--prop onset {onset} "
                        "--init_value current_output {init} "
                        "--build_mode force"
                        .format(out_path=self.cell_input_path,
                                rec_t_start='{} {}'.format(*self.rec_t_start),
                                t_stop=self.t_stop, dt=self.dt,
                                amp='{} {}'.format(*self.isyn_amp),
                                onset='{} {}'.format(*self.isyn_onset),
                                init='{} {}'.format(*self.isyn_init)))
                # Run input signal simulation
                simulate.run(argv.split())
            argv = (
                "//neuron/Izhikevich#SampleIzhikevichFastSpiking "
                "nest {} 0.01 "
                "--record V {} "
                "--init_value U 1.625 pA "
                "--init_value V -65.0 mV "
                "--play iSyn {in_path} "
                "--init_regime subVb "
                "--build_version Plot ".format(
                    self.t_stop, self.cell_signal_path,
                    in_path=self.cell_input_path))
            simulate.run(argv.split())
        # Run plotting command
        out_path = '{}/single_cell.png'.format(self.work_dir)
        argv = ("{in_path} --save {out_path} --dims 5 5 "
                "--resolution 100.0 {hide}"
                .format(in_path=self.cell_signal_path, out_path=out_path,
                        name='v', hide=('' if show else '--hide')))
        plot.run(argv.split())
        image = img.imread(out_path)
        self._ref_single_cell_plot()
        ref_image = img.imread(self.ref_single_cell_path)
        self.assertEqual(image.shape, ref_image.shape)
        self.assertTrue(
            (image == ref_image).all(),
            "Ploted single cell data using 'plot' command (saved to '{}') did "
            "not match loaded image from '{}'"
            .format(out_path, self.ref_single_cell_path))

    def test_network_plot(self):
        if not os.path.exists(self.network_signal_path):
            # Generate test signal
            brunel_ai = ninemlcatalog.load(
{'fraction_non_alphanumeric': 0.11087980716555275, 'fraction_numerical': 0.009751287389065411, 'mean_word_length': 1.7485697079193014, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '787484', 'n_tokens_mistral': 2878, 'n_tokens_neox': 2729, 'n_words': 587}