def setUp(self):
        """Generate the neuron model code"""
        nest_path = nest.ll_api.sli_func("statusdict/prefix ::")

        # generate the "jit" model (co-generated neuron and synapse), that does not rely on ArchivingNode
        to_nest(input_path=["models/neurons/iaf_psc_exp.nestml", "models/synapses/stdp_nn_pre_centered.nestml"],
                target_path="/tmp/nestml-jit",
                logging_level="INFO",
                module_name="nestml_jit_module",
                suffix="_nestml",
                codegen_opts={"neuron_parent_class": "StructuralPlasticityNode",
                              "neuron_parent_class_include": "structural_plasticity_node.h",
                              "neuron_synapse_pairs": [{"neuron": "iaf_psc_exp",
                                                        "synapse": "stdp_nn_pre_centered",
                                                        "post_ports": ["post_spikes"]}]})

        install_nest("/tmp/nestml-jit", nest_path)

        # generate the "non-jit" model, that relies on ArchivingNode
        to_nest(input_path="models/neurons/iaf_psc_exp.nestml",
                target_path="/tmp/nestml-non-jit",
                logging_level="INFO",
                module_name="nestml_non_jit_module",
                suffix="_nestml_non_jit",
                codegen_opts={"neuron_parent_class": "ArchivingNode",
                              "neuron_parent_class_include": "archiving_node.h"})
        install_nest("/tmp/nestml-non-jit", nest_path)
    def setUp(self):
        """Generate the model code"""
        nest_path = nest.ll_api.sli_func("statusdict/prefix ::")

        # generate the "jit" model (co-generated neuron and synapse), that does not rely on ArchivingNode
        to_nest(input_path=[
            "tests/nest_tests/resources/iaf_psc_exp_resolution_test.nestml",
            os.path.join(
                os.path.realpath(
                    os.path.join(os.path.dirname(__file__), "..", "valid",
                                 "CoCoResolutionLegallyUsed.nestml")))
        ],
                target_path="target",
                logging_level="INFO",
                module_name="nestmlmodule",
                suffix="_nestml",
                codegen_opts={
                    "neuron_parent_class":
                    "StructuralPlasticityNode",
                    "neuron_parent_class_include":
                    "structural_plasticity_node.h",
                    "neuron_synapse_pairs": [{
                        "neuron":
                        "iaf_psc_exp_resolution_test",
                        "synapse":
                        "CoCoResolutionLegallyUsed"
                    }]
                })
        install_nest("target", nest_path)
Example #3
0
def compile_modules(modules, recompile=False, config=CONFIGURED, logger=LOG):
    # ...unless we need to first compile it:
    from pynestml.frontend.pynestml_frontend import install_nest
    if not os.path.exists(config.MODULES_BLDS_DIR):
        logger.info("Creating MODULES_BLDS_DIR: %s" % config.MODULES_BLDS_DIR)
        os.makedirs(config.MODULES_BLDS_DIR)
    for module in ensure_list(modules):
        logger.info("Compiling %s..." % module)
        module_bld_dir = os.path.join(config.MODULES_BLDS_DIR, module)
        logger.info("from in build_interfaces directory %s..." %
                    module_bld_dir)
        if not os.path.exists(module_bld_dir) or recompile:
            source_path = os.path.join(config.MODULES_DIR, module)
            logger.info("copying sources from %s\ninto %s..." %
                        (source_path, module_bld_dir))
            shutil.copytree(source_path, module_bld_dir)
        logger.info("Running compilation...")
        install_nest(module_bld_dir, config.NEST_PATH)
        if os.path.isfile(os.path.join(config.MODULES_BLDS_DIR, module + "module.so")) and \
            os.path.isfile(os.path.join(config.MODULES_BLDS_DIR, "lib" + module + "module.so")):
            logger.info("DONE compiling %s!" % module)
        else:
            logger.warn(
                "Something seems to have gone wrong with compiling %s!" %
                module)
Example #4
0
    def setUp(self):
        """Generate the neuron model code"""
        nest_path = nest.ll_api.sli_func("statusdict/prefix ::")

        to_nest(input_path="models/synapses/noisy_synapse.nestml",
                target_path="/tmp/nestml-noisy-synapse",
                logging_level="INFO",
                module_name="nestml_noisy_synapse_module",
                suffix="_nestml")
        install_nest("/tmp/nestml-noisy-synapse", nest_path)
Example #5
0
def install(data):

  # save nestml models to files
  filename = os.path.join(models_path, data['neuron'])
  data_nestml_format = converter.json_to_nestml_format(data)
  converter.write_file(filename, data_nestml_format)

  to_nest(models_path, build_path, module_name='nestmlmodule')
  install_nest(build_path, nest_install_dir)

  return {'data': data}
Example #6
0
    def simulate_OU_noise_neuron(self, resolution):
        '''
        Simulates a single neuron with OU noise conductances.

        Parameters
        ----------
        resolution : float
            Resolution of the NEST simulation

        Returns
        -------
        dict
            State of the multimeter, which is connected to the neuron.
        tuple
            Tuple with the NEST id of the simulated neuron

        '''
        seed = np.random.randint(0, 2**32 - 1)
        print('seed: {}'.format(seed))
        nest.SetKernelStatus({
            'resolution': resolution,
            'grng_seed': seed,
            'rng_seeds': [seed + 1]
        })

        input_path = os.path.join(
            os.path.realpath(
                os.path.join(os.path.dirname(__file__), "..", "..", "models",
                             "hh_cond_exp_destexhe.nestml")))
        nest_path = nest.ll_api.sli_func("statusdict/prefix ::")
        target_path = 'target'
        logging_level = 'INFO'
        module_name = 'nestmlmodule'
        store_log = False
        suffix = '_nestml'
        dev = True
        to_nest(input_path, target_path, logging_level, module_name, store_log,
                suffix, dev)
        install_nest(target_path, nest_path)
        nest.set_verbosity("M_ALL")

        nest.Install('nestmlmodule')
        neuron = nest.Create('hh_cond_exp_destexhe_nestml')

        multi = nest.Create('multimeter',
                            params={
                                'record_from': self.record_from,
                                'interval': resolution
                            })

        nest.Connect(multi, neuron)
        nest.Simulate(500000)

        return multi.get("events"), neuron
Example #7
0
def nestml_to_nest_extension_module():
    r"""Generate the neuron model code"""
    nest_path = nest.ll_api.sli_func("statusdict/prefix ::")

    # generate the "jit" model (co-generated neuron and synapse), that does not rely on ArchivingNode
    to_nest(input_path=["models/neurons/iaf_psc_delta.nestml", "models/synapses/stdp_synapse.nestml"],
            target_path="/tmp/nestml-jit",
            logging_level="INFO",
            module_name="nestml_jit_module",
            suffix="_nestml",
            codegen_opts={"neuron_parent_class": "StructuralPlasticityNode",
                          "neuron_parent_class_include": "structural_plasticity_node.h",
                          "neuron_synapse_pairs": [{"neuron": "iaf_psc_delta",
                                                    "synapse": "stdp",
                                                    "post_ports": ["post_spikes"]}]})
    install_nest("/tmp/nestml-jit", nest_path)
    nest.Install("nestml_jit_module")
Example #8
0
    def test_for_and_while_loop(self):
        files = ["ForLoop.nestml", "WhileLoop.nestml"]
        input_path = [
            os.path.join(
                os.path.realpath(
                    os.path.join(os.path.dirname(__file__), "resources", s)))
            for s in files
        ]
        nest_path = nest.ll_api.sli_func("statusdict/prefix ::")
        target_path = 'target'
        logging_level = 'INFO'
        module_name = 'nestmlmodule'
        store_log = False
        suffix = '_nestml'
        dev = True
        to_nest(input_path, target_path, logging_level, module_name, store_log,
                suffix, dev)
        install_nest(target_path, nest_path)
        nest.set_verbosity("M_ALL")

        nest.ResetKernel()
        nest.Install("nestmlmodule")

        nrn = nest.Create("for_loop_nestml")
        mm = nest.Create('multimeter')
        mm.set({"record_from": ["V_m"]})

        nest.Connect(mm, nrn)

        nest.Simulate(5.0)

        v_m = mm.get("events")["V_m"]
        np.testing.assert_almost_equal(v_m[-1], 16.6)

        nest.ResetKernel()
        nrn = nest.Create("while_loop_nestml")

        mm = nest.Create('multimeter')
        mm.set({"record_from": ["y"]})

        nest.Connect(mm, nrn)

        nest.Simulate(5.0)
        y = mm.get("events")["y"]
        np.testing.assert_almost_equal(y[-1], 5.011)
Example #9
0
    def setUp(self):
        """Generate the neuron model code"""
        nest_path = nest.ll_api.sli_func("statusdict/prefix ::")

        to_nest(input_path=["models/neurons/iaf_psc_delta.nestml",
                            "tests/resources/synapse_event_priority_test.nestml",
                            "tests/resources/synapse_event_inv_priority_test.nestml"],
                target_path="/tmp/nestml-synapse-event-priority-test",
                logging_level="INFO",
                module_name="nestml_module",
                suffix="_nestml",
                codegen_opts={"neuron_parent_class": "StructuralPlasticityNode",
                              "neuron_parent_class_include": "structural_plasticity_node.h",
                              "neuron_synapse_pairs": [{"neuron": "iaf_psc_delta",
                                                        "synapse": "synapse_event_priority_test",
                                                        "post_ports": ["post_spikes"]},
                                                       {"neuron": "iaf_psc_delta",
                                                        "synapse": "synapse_event_inv_priority_test",
                                                        "post_ports": ["post_spikes"]}]})
        install_nest("/tmp/nestml-synapse-event-priority-test", nest_path)
    def test_recordable_variables(self):
        input_path = os.path.join(os.path.realpath(os.path.join(
            os.path.dirname(__file__), "resources", "RecordableVariables.nestml")))
        nest_path = nest.ll_api.sli_func("statusdict/prefix ::")
        target_path = "target"
        logging_level = "INFO"
        module_name = "nestmlmodule"
        store_log = False
        suffix = "_nestml"
        dev = True
        to_nest(input_path, target_path, logging_level, module_name, store_log, suffix, dev)
        install_nest(target_path, nest_path)
        nest.set_verbosity("M_ALL")

        nest.ResetKernel()
        nest.Install(module_name)

        neuron = nest.Create("recordable_variables_nestml")
        sg = nest.Create("spike_generator", params={"spike_times": [20., 80.]})
        nest.Connect(sg, neuron)

        mm = nest.Create('multimeter', params={'record_from': ['V_ex', 'V_m', 'V_abs', 'I_kernel__X__spikes'],
                                               'interval': 0.1})
        nest.Connect(mm, neuron)

        nest.Simulate(100.)

        # Get the recordable variables
        events = nest.GetStatus(mm)[0]["events"]
        V_reset = nest.GetStatus(neuron, "V_reset")
        V_m = events["V_m"]
        self.assertIsNotNone(V_m)

        V_abs = events["V_abs"]
        self.assertIsNotNone(V_abs)

        np.testing.assert_allclose(V_m, V_abs + V_reset)

        V_ex = events["V_ex"]
        np.testing.assert_almost_equal(V_ex[-1], -10)
Example #11
0
    def generate_all_models(self):
        nest_path = nest.ll_api.sli_func("statusdict/prefix ::")
        all_synapse_models = [s[:-7] for s in list(os.walk("models/synapses"))[0][2] if s[-7:] == ".nestml"]
        to_nest(input_path=["models"],
                target_path="/tmp/nestml-allmodels",
                logging_level="INFO",
                module_name="nestml_allmodels_module",
                suffix="_nestml",
                codegen_opts={"neuron_parent_class": "StructuralPlasticityNode",
                              "neuron_parent_class_include": "structural_plasticity_node.h",
                              "neuron_synapse_pairs": [{"neuron": "iaf_psc_exp",
                                                        "synapse": "neuromodulated_stdp",
                                                        "post_ports": ["post_spikes"],
                                                        "vt_ports": ["mod_spikes"]},
                                                       {"neuron": "iaf_psc_exp",
                                                        "synapse": "stdp",
                                                        "post_ports": ["post_spikes"]},
                                                       {"neuron": "iaf_psc_delta",
                                                        "synapse": "stdp_triplet",
                                                        "post_ports": ["post_spikes"]},
                                                       {"neuron": "iaf_psc_delta",
                                                        "synapse": "stdp_triplet_nn",
                                                        "post_ports": ["post_spikes"]},
                                                       {"neuron": "iaf_psc_exp",
                                                        "synapse": "stdp_nn_symm",
                                                        "post_ports": ["post_spikes"]},
                                                       {"neuron": "iaf_psc_exp",
                                                        "synapse": "stdp_nn_restr_symm",
                                                        "post_ports": ["post_spikes"]},
                                                       {"neuron": "iaf_psc_exp_dend",
                                                        "synapse": "third_factor_stdp",
                                                        "post_ports": ["post_spikes",
                                                                       ["I_post_dend", "I_dend"]]},
                                                       {"neuron": "iaf_psc_exp",
                                                        "synapse": "stdp_nn_pre_centered",
                                                        "post_ports": ["post_spikes"]}]})

        install_nest("/tmp/nestml-allmodels", nest_path)
Example #12
0
    def test_vectors(self):
        input_path = os.path.join(os.path.realpath(os.path.join(os.path.dirname(__file__), "resources", "Vectors.nestml")))
        nest_path = nest.ll_api.sli_func("statusdict/prefix ::")
        target_path = 'target'
        logging_level = 'INFO'
        module_name = 'nestmlmodule'
        store_log = False
        suffix = '_nestml'
        dev = True
        to_nest(input_path, target_path, logging_level, module_name, store_log, suffix, dev)
        install_nest(target_path, nest_path)
        nest.set_verbosity("M_ALL")

        nest.ResetKernel()
        nest.Install("nestmlmodule")

        neuron = nest.Create("vectors_nestml")
        multimeter = nest.Create('multimeter')
        recordables = list()
        recordables.extend(["G_IN_" + str(i + 1) for i in range(0, 20)])
        recordables.extend(["G_EX_" + str(i + 1) for i in range(0, 10)])
        recordables.append("V_m")
        multimeter.set({"record_from": recordables})
        nest.Connect(multimeter, neuron)

        nest.Simulate(2.0)

        events = multimeter.get("events")
        g_in = events["G_IN_1"]
        g_ex = events["G_EX_2"]
        print("g_in: {}, g_ex: {}".format(g_in, g_ex))
        np.testing.assert_almost_equal(g_in[-1], 11.)
        np.testing.assert_almost_equal(g_ex[-1], -2.)

        v_m = multimeter.get("events")["V_m"]
        print("V_m: {}".format(v_m))
        np.testing.assert_almost_equal(v_m[-1], -0.3)
Example #13
0
    def setUp(self):
        """generate code for neuron and synapse and build NEST user module"""
        nest_path = nest.ll_api.sli_func("statusdict/prefix ::")

        to_nest(input_path=[
            "models/neurons/iaf_psc_exp.nestml",
            "models/synapses/neuromodulated_stdp.nestml"
        ],
                target_path="/tmp/nestml-jit",
                logging_level="INFO",
                module_name="nestml_jit_module",
                suffix="_nestml",
                codegen_opts={
                    "neuron_parent_class":
                    "StructuralPlasticityNode",
                    "neuron_parent_class_include":
                    "structural_plasticity_node.h",
                    "neuron_synapse_pairs": [{
                        "neuron": "iaf_psc_exp",
                        "synapse": "neuromodulated_stdp",
                        "post_ports": ["post_spikes"],
                        "vt_ports": ["mod_spikes"]
                    }]
                })
        install_nest("/tmp/nestml-jit", nest_path)

        to_nest(input_path="models/neurons/iaf_psc_exp.nestml",
                target_path="/tmp/nestml-non-jit",
                logging_level="INFO",
                module_name="nestml_non_jit_module",
                suffix="_nestml_non_jit",
                codegen_opts={
                    "neuron_parent_class": "ArchivingNode",
                    "neuron_parent_class_include": "archiving_node.h"
                })
        install_nest("/tmp/nestml-non-jit", nest_path)
def nestml_to_nest_extension_module():
    """Generate the neuron model code"""
    nest_path = nest.ll_api.sli_func("statusdict/prefix ::")

    to_nest(input_path=[
        "models/neurons/iaf_psc_delta.nestml",
        "models/synapses/stdp_triplet_naive.nestml"
    ],
            target_path="/tmp/nestml-triplet-stdp",
            logging_level="INFO",
            module_name="nestml_triplet_pair_module",
            suffix="_nestml",
            codegen_opts={
                "neuron_parent_class":
                "StructuralPlasticityNode",
                "neuron_parent_class_include":
                "structural_plasticity_node.h",
                "neuron_synapse_pairs": [{
                    "neuron": "iaf_psc_delta",
                    "synapse": "stdp_triplet",
                    "post_ports": ["post_spikes"]
                }]
            })
    install_nest("/tmp/nestml-triplet-stdp", nest_path)
Example #15
0
import os
import nest
import shutil

from pynestml.frontend.pynestml_frontend import to_nest, install_nest

input_path = str(
    os.path.realpath(
        os.path.join(os.path.dirname(__file__), 'PrintVariables.nestml')))
nest_path = nest.ll_api.sli_func("statusdict/prefix ::")
target_path = '../target'
logging_level = 'INFO'
module_name = 'nestmlmodule'
store_log = False
suffix = '_nestml'
dev = True

to_nest(input_path, target_path, logging_level, module_name, store_log, suffix,
        dev)
install_nest(target_path, nest_path)
nest.set_verbosity("M_ALL")

nest.ResetKernel()
nest.Install(module_name)

neuron = nest.Create("print_variable_nestml")
nest.Simulate(0.1)

if os.path.exists(target_path):
    shutil.rmtree(target_path)
Example #16
0
    def test_terub_gpe(self):

        if not os.path.exists("target"):
            os.makedirs("target")

        input_path = os.path.join(
            os.path.realpath(
                os.path.join(os.path.dirname(__file__), "../models",
                             "terub_gpe.nestml")))
        target_path = "target"
        module_name = 'terub_gpe_module'
        nest_path = "/home/abolfazl/prog/nest-build/"
        suffix = '_nestml'

        if 1:
            to_nest(input_path=input_path,
                    target_path=target_path,
                    logging_level="INFO",
                    suffix=suffix,
                    module_name=module_name)

            install_nest(target_path, nest_path)

        nest.Install(module_name)
        model = "terub_gpe_nestml"

        dt = 0.01
        t_simulation = 2000.0
        nest.SetKernelStatus({"resolution": dt})

        neuron = nest.Create(model)
        parameters = nest.GetDefaults(model)

        if 0:
            for i in parameters:
                print(i, parameters[i])

        nest.SetStatus(neuron, {'I_e': 0.0})
        multimeter = nest.Create("multimeter")
        nest.SetStatus(multimeter, {
            "withtime": True,
            "record_from": ["V_m"],
            "interval": dt
        })
        spikedetector = nest.Create("spike_detector",
                                    params={
                                        "withgid": True,
                                        "withtime": True
                                    })
        nest.Connect(multimeter, neuron)
        nest.Connect(neuron, spikedetector)
        nest.Simulate(t_simulation)

        dmm = nest.GetStatus(multimeter)[0]
        Voltages = dmm["events"]["V_m"]
        tv = dmm["events"]["times"]
        dSD = nest.GetStatus(spikedetector, keys='events')[0]
        spikes = dSD['senders']
        ts = dSD["times"]

        firing_rate = len(spikes) / t_simulation * 1000
        print("firing rate is ", firing_rate)
        expected_value = np.abs(firing_rate - 14)
        tolerance_value = 3  # Hz

        # self.assertLessEqual(expected_value, tolerance_value)

        if TEST_PLOTS:

            fig, ax = plt.subplots(2, figsize=(8, 4), sharex=True)
            ax[0].plot(tv, Voltages, lw=2, color="k")
            ax[1].plot(ts, spikes, 'ko')
            ax[1].set_xlabel("Time [ms]")
            ax[1].set_xlim(0, t_simulation)
            ax[1].set_ylabel("Spikes")
            ax[0].set_ylabel("v [ms]")
            # ax[0].set_ylim(-100, 50)

            for i in ts:
                ax[0].axvline(x=i, lw=1., ls="--", color="gray")

            plt.savefig("resources/terub_gpe.png")
Example #17
0
    def test_fir_filter(self):
        nestml_model_file = 'FIR_filter.nestml'
        nestml_model_name = 'fir_filter_nestml'
        target_path = '/tmp/fir-filter'
        logging_level = 'INFO'
        module_name = 'nestmlmodule'
        store_log = False
        suffix = '_nestml'
        dev = True

        # Generate the NEST code
        input_path = os.path.join(os.path.realpath(os.path.join(os.path.dirname(__file__), 'resources', nestml_model_file)))
        nest_path = nest.ll_api.sli_func("statusdict/prefix ::")
        to_nest(input_path, target_path, logging_level, module_name, store_log, suffix, dev)
        install_nest(target_path, nest_path)

        t_sim = 101.
        resolution = 0.1

        nest.set_verbosity("M_ALL")
        nest.Install(module_name)

        nest.ResetKernel()

        # Create a fir_filter node
        neuron = nest.Create(nestml_model_name, {"N": 256})

        # Create a spike generator
        spikes = [1.0, 1.0, 1.5, 1.5, 1.5, 6.7, 10.0, 10.5, 10.5, 10.5, 10.5, 11.3, 11.3, 11.4, 11.4, 20., 22.5, 30.,
                  40., 42., 42., 42., 50.5, 50.5, 75., 88., 93., 93.]
        sg = nest.Create("spike_generator", params={"spike_times": spikes})
        nest.Connect(sg, neuron, syn_spec=dict(delay=resolution))

        # Get N (order of the filter)
        n = nest.GetStatus(neuron, "N")[0]
        print("N: {}".format(n))

        # Set filter coefficients
        h = self.generate_filter_coefficients(n)
        nest.SetStatus(neuron, {"h": h})
        print("h: ", h)

        # Multimeter
        multimeter = nest.Create('multimeter')
        nest.SetStatus(multimeter, {'interval': resolution})
        multimeter.set({"record_from": ["y"]})  # output of the filter
        nest.Connect(multimeter, neuron)

        # Spike recorder
        sr = nest.Create("spike_recorder")
        nest.Connect(sg, sr)
        nest.Connect(neuron, sr)

        # Simulate
        nest.Simulate(t_sim)

        # Record from multimeter
        events = multimeter.get("events")
        y = events["y"]
        times = events["times"]
        spike_times = nest.GetStatus(sr, keys='events')[0]['times']

        # Scipy filtering
        spikes, bin_edges = np.histogram(spike_times, np.arange(0, t_sim, resolution))
        output = scipy.signal.lfilter(h, 1, spikes)

        # Plots
        if TEST_PLOTS:
            self.plot_output(spike_times, times, y, title='FIR FILTER (NESTML)',
                             filename='fir_filter_output_nestml.png')
            self.plot_output(spike_times, bin_edges[1:], output, title='FIR FILTER (scipy)',
                             filename='fir_filter_output_scipy.png')

        np.testing.assert_allclose(y, output)
Example #18
0
    def test_multisynapse(self):
        input_path = os.path.join(
            os.path.realpath(
                os.path.join(os.path.dirname(__file__), "resources",
                             "iaf_psc_exp_multisynapse.nestml")))
        nest_path = "/home/travis/nest_install"
        target_path = 'target'
        logging_level = 'INFO'
        module_name = 'nestmlmodule'
        store_log = False
        suffix = '_nestml'
        dev = True
        to_nest(input_path, target_path, logging_level, module_name, store_log,
                suffix, dev)
        install_nest(target_path, nest_path)
        nest.set_verbosity("M_ALL")

        nest.ResetKernel()
        nest.Install(module_name)

        # network construction

        neuron = nest.Create("iaf_psc_exp_multisynapse_neuron_nestml")

        sg = nest.Create("spike_generator", params={"spike_times": [20., 80.]})
        nest.Connect(sg,
                     neuron,
                     syn_spec={
                         "receptor_type": 1,
                         "weight": 1000.,
                         "delay": 0.1
                     })

        sg2 = nest.Create("spike_generator",
                          params={"spike_times": [40., 60.]})
        nest.Connect(sg2,
                     neuron,
                     syn_spec={
                         "receptor_type": 2,
                         "weight": 1000.,
                         "delay": 0.1
                     })

        sg3 = nest.Create("spike_generator",
                          params={"spike_times": [30., 70.]})
        nest.Connect(sg3,
                     neuron,
                     syn_spec={
                         "receptor_type": 3,
                         "weight": 500.,
                         "delay": 0.1
                     })

        mm = nest.Create('multimeter',
                         params={
                             'record_from': [
                                 'I_kernel1__X__spikes1',
                                 'I_kernel2__X__spikes2',
                                 'I_kernel3__X__spikes3'
                             ],
                             'interval':
                             0.1
                         })
        nest.Connect(mm, neuron)

        vm_1 = nest.Create('voltmeter')
        nest.Connect(vm_1, neuron)

        # simulate

        nest.Simulate(125.)

        # analysis
        V_m_timevec = nest.GetStatus(vm_1)[0]["events"]["times"]
        V_m = nest.GetStatus(vm_1)[0]["events"]["V_m"]
        mm = nest.GetStatus(mm)[0]["events"]
        MAX_ABS_ERROR = 1E-6
        print("Final V_m = " + str(V_m[-1]))
        assert abs(V_m[-1] - -72.89041451202348) < MAX_ABS_ERROR

        if TEST_PLOTS:

            fig, ax = plt.subplots(nrows=4)

            ax[0].plot(V_m_timevec, V_m, label="V_m")
            ax[0].set_ylabel("voltage")

            ax[1].plot(mm["times"],
                       mm["I_kernel1__X__spikes1"],
                       label="I_kernel1")
            ax[1].set_ylabel("current")

            ax[2].plot(mm["times"],
                       mm["I_kernel2__X__spikes2"],
                       label="I_kernel2")
            ax[2].set_ylabel("current")

            ax[3].plot(mm["times"],
                       mm["I_kernel3__X__spikes3"],
                       label="I_kernel3")
            ax[3].set_ylabel("current")

            for _ax in ax:
                _ax.legend(loc="upper right")
                _ax.set_xlim(0., 125.)
                _ax.grid(True)

            for _ax in ax[:-1]:
                _ax.set_xticklabels([])

            ax[-1].set_xlabel("time")

            plt.show()
Example #19
0
"""Install adaptive LIF neuron using nestml"""

import nest
from pynestml.frontend.pynestml_frontend import to_nest, install_nest
NEST_SIMULATOR_INSTALL_LOCATION = nest.ll_api.sli_func("statusdict/prefix ::")
to_nest(input_path="adapt_lif.nestml",
        target_path="/tmp/nestml-component",
        logging_level="ERROR")
install_nest("/tmp/nestml-component", NEST_SIMULATOR_INSTALL_LOCATION)
Example #20
0
from os import system
from pynestml.frontend.pynestml_frontend import to_nest, install_nest

to_nest(input_path=".",
        target_path="../tmp/module",
        logging_level="INFO",
        module_name="tmp_nestml_module",
        suffix="_nestml")

install_nest("../tmp/module",
             "/home/abolfazl/prog/install-dir/nest-simulator-2.18.0_build")
Example #21
0
    def test_terub_stn_multisyn(self):

        model_name = "terub_stn_multisyn"

        if not os.path.exists("target"):
            os.makedirs("target")

        input_path = os.path.join(
            os.path.realpath(
                os.path.join(os.path.dirname(__file__), "../models",
                             "{}.nestml".format(model_name))))
        target_path = "target"
        module_name = '{}_module'.format(model_name)
        nest_path = "/home/abolfazl/prog/nest-build/"
        suffix = '_nestml'

        if 1:  #! compile
            to_nest(input_path=input_path,
                    target_path=target_path,
                    logging_level="INFO",
                    suffix=suffix,
                    module_name=module_name)

            install_nest(target_path, nest_path)

        nest.Install(module_name)
        model = "{}_nestml".format(model_name)

        dt = 0.01
        t_simulation = 1500.0
        nest.SetKernelStatus({"resolution": dt})

        neuron1 = nest.Create(model, 1)
        neuron2 = nest.Create(model, 1)
        # parameters = nest.GetDefaults(model)

        # if 0:
        #     for i in parameters:
        #         print(i, parameters[i])

        for neuron in neuron1 + neuron2:
            nest.SetStatus([neuron], {'I_e': 0.0 + rand() * 20.0 - 20})
            nest.SetStatus([neuron], {'V_m': -65.0 + rand() * 10. - 5.})

        nest.Connect(neuron1, neuron2, syn_spec={"receptor_type": 1})  # AMPA
        nest.Connect(neuron1, neuron2, syn_spec={"receptor_type": 2})  # NMDA
        nest.Connect(neuron1, neuron2, syn_spec={"receptor_type": 3})  # GABAA
        nest.Connect(neuron1, neuron2, syn_spec={"receptor_type": 4})  # GABAB

        record_from = [
            "V_m", "I_syn_ampa", "I_syn_nmda", "I_syn_gaba_a", "I_syn_gaba_b"
        ]

        multimeter = nest.Create("multimeter", 2)
        nest.SetStatus(multimeter, {
            "withtime": True,
            "record_from": record_from,
            "interval": dt
        })
        spikedetector = nest.Create("spike_detector",
                                    params={
                                        "withgid": True,
                                        "withtime": True
                                    })
        nest.Connect(multimeter, neuron1 + neuron2, "one_to_one")
        nest.Connect(neuron1 + neuron2, spikedetector)
        nest.Simulate(t_simulation)

        dSD = nest.GetStatus(spikedetector, keys='events')[0]
        spikes = dSD['senders']

        firing_rate = len(spikes) / t_simulation * 1000
        print("firing rate is ", firing_rate / 2)

        def plot_data(index=[0]):

            fig, ax = plt.subplots(3, figsize=(10, 6), sharex=True)
            for i in index:
                dmm = nest.GetStatus(multimeter, keys='events')[i]
                Voltages = dmm["V_m"]
                tv = dmm["times"]
                ax[0].plot(tv, Voltages, lw=1, label=str(i + 1))

            labels = ["ampa", "nmda", "gaba_a", "gaba_b"]
            j = 0
            dmm = nest.GetStatus(multimeter)[1]
            tv = dmm['events']["times"]
            for i in record_from[1:]:
                g = dmm["events"][i]
                ax[1].plot(tv, g, lw=2, label=labels[j])
                j += 1

            dSD = nest.GetStatus(spikedetector, keys='events')[0]
            spikes = dSD['senders']
            ts = dSD["times"]

            ax[2].plot(ts, spikes, 'ko', ms=3)
            ax[2].set_xlabel("Time [ms]")
            ax[2].set_xlim(0, t_simulation)
            ax[2].set_ylabel("Spikes")
            ax[0].set_title("recording from PSP")
            ax[0].set_ylabel("v [ms]")
            ax[1].set_ylabel("I_syn")
            ax[1].legend(frameon=False, loc="upper right")
            ax[0].legend()

            plt.savefig(join("resources", "terub_stn_multisyn.png"), dpi=150)
            # plt.show()

        plot_data(index=[0, 1])
    def test_logarithmic_function(self):
        MAX_SSE = 1E-12

        input_path = os.path.join(
            os.path.realpath(
                os.path.join(os.path.dirname(__file__), "resources")))
        nest_path = nest.ll_api.sli_func("statusdict/prefix ::")
        target_path = 'target'
        logging_level = 'INFO'
        module_name = 'nestmlmodule'
        store_log = False
        suffix = '_nestml'
        dev = True
        to_nest(input_path, target_path, logging_level, module_name, store_log,
                suffix, dev)
        install_nest(target_path, nest_path)
        nest.set_verbosity("M_ALL")

        nest.ResetKernel()
        nest.Install("nestmlmodule")

        nrn = nest.Create("logarithm_function_test_nestml")
        mm = nest.Create('multimeter')

        ln_state_specifier = 'ln_state'
        log10_state_specifier = 'log10_state'
        mm.set(
            {"record_from": [ln_state_specifier, log10_state_specifier, "x"]})

        nest.Connect(mm, nrn)

        nest.Simulate(100.0)

        timevec = mm.get("events")["x"]
        ln_state_ts = mm.get("events")[ln_state_specifier]
        log10_state_ts = mm.get("events")[log10_state_specifier]
        ref_ln_state_ts = np.log(timevec - 1)
        ref_log10_state_ts = np.log10(timevec - 1)

        assert np.all((ln_state_ts - ref_ln_state_ts)**2 < MAX_SSE)
        assert np.all((log10_state_ts - ref_log10_state_ts)**2 < MAX_SSE)

        # test that expected failure occurs

        nest.ResetKernel()
        nrn = nest.Create("logarithm_function_test_invalid_nestml")

        mm = nest.Create('multimeter')

        ln_state_specifier = 'ln_state'
        log10_state_specifier = 'log10_state'
        mm.set(
            {"record_from": [ln_state_specifier, log10_state_specifier, "x"]})

        nest.Connect(mm, nrn)

        nest.Simulate(100.0)

        timevec = mm.get("events")["x"]
        ln_state_ts = mm.get("events")[ln_state_specifier]
        log10_state_ts = mm.get("events")[log10_state_specifier]
        ref_ln_state_ts = np.log(timevec - 1)
        ref_log10_state_ts = np.log10(timevec - 1)

        assert not np.all((ln_state_ts - ref_ln_state_ts)**2 < MAX_SSE)
        assert not np.all((log10_state_ts - ref_log10_state_ts)**2 < MAX_SSE)
    def test_biexp_synapse(self):
        input_path = os.path.join(
            os.path.realpath(
                os.path.join(os.path.dirname(__file__), "resources",
                             "BiexponentialPostSynapticResponse.nestml")))
        nest_path = "/home/travis/nest_install"
        target_path = 'target'
        logging_level = 'INFO'
        module_name = 'nestmlmodule'
        store_log = False
        suffix = '_nestml'
        dev = True
        to_nest(input_path, target_path, logging_level, module_name, store_log,
                suffix, dev)
        install_nest(target_path, nest_path)
        nest.set_verbosity("M_ALL")

        nest.ResetKernel()
        nest.Install(module_name)

        # network construction

        neuron = nest.Create("biexp_postsynaptic_response_nestml")

        sg = nest.Create("spike_generator", params={"spike_times": [10., 30.]})
        nest.Connect(sg,
                     neuron,
                     syn_spec={
                         "receptor_type": 1,
                         "weight": 1000.,
                         "delay": 0.1
                     })

        sg2 = nest.Create("spike_generator",
                          params={"spike_times": [20., 40.]})
        nest.Connect(sg2,
                     neuron,
                     syn_spec={
                         "receptor_type": 2,
                         "weight": 1000.,
                         "delay": 0.1
                     })

        sg3 = nest.Create("spike_generator",
                          params={"spike_times": [25., 45.]})
        nest.Connect(sg3,
                     neuron,
                     syn_spec={
                         "receptor_type": 3,
                         "weight": 1000.,
                         "delay": 0.1
                     })

        sg4 = nest.Create("spike_generator",
                          params={"spike_times": [35., 55.]})
        nest.Connect(sg3,
                     neuron,
                     syn_spec={
                         "receptor_type": 4,
                         "weight": 1000.,
                         "delay": 0.1
                     })

        i_1 = nest.Create('multimeter',
                          params={
                              'record_from': [
                                  'g_gap__X__spikeGap', 'g_ex__X__spikeExc',
                                  'g_in__X__spikeInh', 'g_GABA__X__spikeGABA'
                              ],
                              'interval':
                              .1
                          })
        nest.Connect(i_1, neuron)

        vm_1 = nest.Create('voltmeter')
        nest.Connect(vm_1, neuron)

        # simulate

        nest.Simulate(125.)

        # analysis

        vm_1 = nest.GetStatus(vm_1)[0]["events"]
        i_1 = nest.GetStatus(i_1)[0]["events"]
        if TEST_PLOTS:
            self.plot(vm_1, i_1)

        # verification
        final_v_m = vm_1["V_m"][-1]
        print("final V_m = " + str(final_v_m))
        MAX_ABS_ERROR = 1E-6
        assert abs(final_v_m - -64.2913308548727) < MAX_ABS_ERROR
def compile_modules(modules, recompile=False, config=CONFIGURED, logger=LOG):
    """Function to compile NEST modules.
       Arguments:
        modules: a sequence (list, tuple) of NEST modules' names (strings).
        recompile: (bool) flag to recompile a module that is already compiled. Default = False.
        config: configuration class instance. Default: imported default CONFIGURED object.
        logger: logger object. Default: local LOG object.
    """
    # ...unless we need to first compile it:
    logger.info("Preparing MYMODULES_BLD_DIR: %s" % config.MYMODULES_BLD_DIR)
    safe_makedirs(config.MYMODULES_BLD_DIR)
    lib_path = os.path.join(os.environ["NEST_INSTALL_DIR"], "lib", "nest")
    include_path = os.path.join(os.environ["NEST_INSTALL_DIR"], "include")
    for module in ensure_list(modules):
        modulemodule = module + "module"
        module_bld_dir = os.path.join(config.MYMODULES_BLD_DIR, module)
        solib_file = os.path.join(module_bld_dir, modulemodule + ".so")
        dylib_file = os.path.join(module_bld_dir, "lib" + modulemodule + ".dylib")
        include_file = os.path.join(module_bld_dir, modulemodule + ".h")
        installed_solib_file = os.path.join(lib_path, os.path.basename(solib_file))
        installed_dylib_file = os.path.join(lib_path, os.path.basename(dylib_file))
        module_include_path = os.path.join(include_path, modulemodule)
        installed_h_file = os.path.join(module_include_path, modulemodule + ".h")
        if not os.path.isfile(solib_file) \
                or not os.path.isfile(dylib_file) \
                    or not os.path.isfile(include_file) \
                        or recompile:
            # If any of the .so, .dylib or .h files don't exist,
            # or if the user requires recompilation,
            # proceed with recompilation:
            if os.path.exists(module_bld_dir):
                # Delete any pre-compiled built files:
                shutil.rmtree(module_bld_dir)
            # Create a  module build directory and copy there the source files:
            source_path = os.path.join(config.MYMODULES_DIR, module)
            logger.info("Copying module sources from %s\ninto %s..." % (source_path, module_bld_dir))
            shutil.copytree(source_path, module_bld_dir)
            # Now compile:
            logger.info("Compiling %s..." % module)
            logger.info("in build directory %s..." % module_bld_dir)
            success_message = "DONE compiling and installing %s!" % module
            from pynestml.frontend.pynestml_frontend import install_nest
            install_nest(module_bld_dir, config.NEST_PATH)
            logger.info("Compiling finished without errors...")
        else:
            logger.info("Installing precompiled module %s..." % module)
            success_message = "DONE installing precompiled module %s!" % module
            # Just copy the .h, .so, and .dylib files to the appropriate NEST build paths:
            shutil.copyfile(solib_file, installed_solib_file)
            shutil.copyfile(solib_file, installed_dylib_file)
            safe_makedirs(include_path)
            shutil.copyfile(os.path.join(module_bld_dir, modulemodule + ".h"), installed_h_file)
        installed_files = {}
        for file in [installed_solib_file, installed_dylib_file, installed_h_file]:
            installed_files[file] = os.path.isfile(file)
        if all(installed_files.values()):
            logger.info(success_message)
        else:
            logger.warn("Something seems to have gone wrong with compiling and/or installing %s!"
                        "\n Installed files (not) found (True (False) respectively)!:\n%s"
                        % (module, str(installed_files)))
    def test_non_linear_dendrite(self):
        MAX_SSE = 1E-12

        I_dend_alias_name = 'I_dend'  # synaptic current
        I_dend_internal_name = 'I_kernel2__X__I_2'  # alias for the synaptic current

        input_path = os.path.join(
            os.path.realpath(
                os.path.join(os.path.dirname(__file__), "resources")),
            "iaf_psc_exp_nonlineardendrite.nestml")
        nest_path = nest.ll_api.sli_func("statusdict/prefix ::")
        target_path = 'target'
        logging_level = 'INFO'
        module_name = 'nestmlmodule'
        store_log = False
        suffix = '_nestml'
        dev = True
        to_nest(input_path, target_path, logging_level, module_name, store_log,
                suffix, dev)
        install_nest(target_path, nest_path)
        nest.set_verbosity("M_ALL")

        nest.ResetKernel()
        nest.Install("nestmlmodule")

        nrn = nest.Create("iaf_psc_exp_nonlineardendrite_nestml")

        sg = nest.Create("spike_generator",
                         params={"spike_times": [10., 20., 30.]})
        nest.Connect(sg,
                     nrn,
                     syn_spec={
                         "receptor_type": 2,
                         "weight": 30.,
                         "delay": 1.
                     })

        mm = nest.Create('multimeter')
        mm.set({
            "record_from": [
                I_dend_alias_name, I_dend_internal_name, 'V_m',
                'dend_curr_enabled', 'I_dend_ap'
            ]
        })
        nest.Connect(mm, nrn)

        nest.Simulate(100.0)

        timevec = mm.get("events")["times"]
        I_dend_alias_ts = mm.get("events")[I_dend_alias_name]
        I_dend_internal_ts = mm.get("events")[I_dend_internal_name]

        if TEST_PLOTS:
            fig, ax = plt.subplots(3, 1)
            ax[0].plot(timevec, I_dend_alias_ts, label="aliased I_dend_syn")
            ax[0].plot(timevec,
                       I_dend_internal_ts,
                       label="internal I_dend_syn")
            ax[0].legend()
            ax_ = ax[0].twinx()
            ax_.plot(timevec, mm.get("events")["dend_curr_enabled"])
            ax_.set_ylabel("dend_curr_enabled")
            ax[1].plot(timevec, mm.get("events")["I_dend_ap"])
            ax[1].set_ylabel("I_dend_AP")
            ax[2].plot(timevec, mm.get("events")["V_m"], label="V_m")
            for _ax in ax:
                _ax.legend()
                _ax.grid()
            plt.ylabel("Dendritic current $I_{dend}$")
            plt.suptitle("Reset of synaptic integration after dendritic spike")
            plt.savefig("/tmp/nestml_triplet_stdp_test.png")

        assert np.all(
            I_dend_alias_ts == I_dend_internal_ts
        ), "Variable " + str(
            I_dend_alias_name
        ) + " and (internal) variable " + str(
            I_dend_internal_name
        ) + " should measure the same thing, but discrepancy in values occurred."

        tidx = np.argmin((timevec - 40)**2)
        assert mm.get("events")["I_dend_ap"][
            tidx] > 0., "Expected a dendritic action potential around t = 40 ms, but dendritic action potential current is zero"
        assert mm.get("events")["dend_curr_enabled"][
            tidx] == 0., "Dendritic synaptic current should be disabled during dendritic action potential"
        tidx_ap_end = tidx + np.where(
            mm.get("events")["dend_curr_enabled"][tidx:] == 1.)[0][0]
        assert np.all(
            I_dend_alias_ts[tidx_ap_end:] == 0.
        ), "After dendritic spike, dendritic current should be reset to 0 and stay at 0."
Example #26
0
    def test_wb_cond_exp(self):

        if not os.path.exists("target"):
            os.makedirs("target")

        input_path = os.path.join(
            os.path.realpath(
                os.path.join(os.path.dirname(__file__), "../../models",
                             "wb_cond_exp.nestml")))
        target_path = "target"
        module_name = 'nestmlmodule'
        nest_path = "/home/travis/nest_install"
        suffix = '_nestml'

        to_nest(input_path=input_path,
                target_path=target_path,
                logging_level="INFO",
                suffix=suffix,
                module_name=module_name)

        install_nest(target_path, nest_path)

        nest.Install(module_name)
        model = "wb_cond_exp_nestml"

        dt = 0.01
        t_simulation = 1000.0
        nest.SetKernelStatus({"resolution": dt})

        neuron = nest.Create(model)
        parameters = nest.GetDefaults(model)

        neuron.set({'I_e': 75.0})
        multimeter = nest.Create("multimeter")
        multimeter.set({"record_from": ["V_m"], "interval": dt})
        spikedetector = nest.Create("spike_detector")
        nest.Connect(multimeter, neuron)
        nest.Connect(neuron, spikedetector)
        nest.Simulate(t_simulation)

        dmm = nest.GetStatus(multimeter)[0]
        Voltages = dmm["events"]["V_m"]
        tv = dmm["events"]["times"]
        dSD = nest.GetStatus(spikedetector, keys='events')[0]
        spikes = dSD['senders']
        ts = dSD["times"]

        firing_rate = len(spikes) / t_simulation * 1000
        print("firing rate is ", firing_rate)
        expected_value = np.abs(firing_rate - 50)
        tolerance_value = 5  # Hz

        if TEST_PLOTS:
            fig, ax = plt.subplots(2, figsize=(8, 6), sharex=True)
            ax[0].plot(tv, Voltages, lw=2, color="k")
            ax[1].plot(ts, spikes, 'ko')
            ax[1].set_xlabel("Time [ms]")
            ax[1].set_xlim(0, t_simulation)
            ax[1].set_ylabel("Spikes")
            ax[0].set_ylabel("v [ms]")
            ax[0].set_ylim(-100, 50)

            for i in ts:
                ax[0].axvline(x=i, lw=1., ls="--", color="gray")

            plt.savefig("resources/wb_cond_exp.png")
            # plt.show()

        self.assertLessEqual(expected_value, tolerance_value)
Example #27
0
import os

from pynestml.frontend.pynestml_frontend import to_nest, install_nest

# folder

home = os.path.expanduser("~")
folder = os.path.dirname(__file__)
root = os.path.abspath(folder if folder else ".")
target = root + "/build"

# build

to_nest(logging_level='ERROR',
        input_path=root,
        target_path=target,
        module_name="energy_module")

# install

import nest

nest_file = nest.__file__

pos = nest_file.find("/lib")

install_nest(target, nest_file[:pos])
    def test_traub_cond_multisyn(self):

        if not os.path.exists("target"):
            os.makedirs("target")

        input_path = os.path.join(
            os.path.realpath(
                os.path.join(os.path.dirname(__file__), "../../models/neurons",
                             "traub_cond_multisyn.nestml")))
        target_path = "target"
        module_name = 'nestmlmodule'
        nest_path = nest.ll_api.sli_func("statusdict/prefix ::")
        suffix = '_nestml'

        to_nest(input_path=input_path,
                target_path=target_path,
                logging_level="INFO",
                suffix=suffix,
                module_name=module_name)

        install_nest(target_path, nest_path)

        nest.Install("nestmlmodule")
        model = "traub_cond_multisyn_nestml"

        dt = 0.01
        t_simulation = 1000.0
        nest.SetKernelStatus({"resolution": dt})

        neuron1 = nest.Create(model, 1)
        neuron1.set({'I_e': 100.0})

        neuron2 = nest.Create(model)
        neuron2.set({"tau_AMPA_1": 0.1, "tau_AMPA_2": 2.4, "AMPA_g_peak": 0.1})

        multimeter = nest.Create("multimeter", 2)
        multimeter[0].set({"record_from": ["V_m"], "interval": dt})
        record_from = [
            "V_m", "I_syn_ampa", "I_syn_nmda", "I_syn_gaba_a", "I_syn_gaba_b"
        ]
        multimeter[1].set({"record_from": record_from, "interval": dt})
        # {'AMPA': 1, 'NMDA': 2, 'GABA_A': 3, 'GABA_B': 4}
        nest.Connect(neuron1, neuron2, syn_spec={"receptor_type": 1})  # AMPA
        nest.Connect(neuron1, neuron2, syn_spec={"receptor_type": 2})  # NMDA
        nest.Connect(neuron1, neuron2, syn_spec={"receptor_type": 3})  # GABAA
        nest.Connect(neuron1, neuron2, syn_spec={"receptor_type": 4})  # GABAB

        nest.Connect(multimeter[0], neuron1, "one_to_one")
        nest.Connect(multimeter[1], neuron2)

        spike_recorder = nest.Create("spike_recorder")
        nest.Connect(neuron1, spike_recorder)
        nest.Simulate(t_simulation)

        dmm = nest.GetStatus(multimeter)[1]
        Voltages = dmm["events"]["V_m"]
        tv = dmm["events"]["times"]

        dSD = nest.GetStatus(spike_recorder, keys='events')[0]
        spikes = dSD['senders']
        ts = dSD["times"]

        firing_rate = len(spikes) / t_simulation * 1000
        print("firing rate is ", firing_rate)
        expected_value = np.abs(firing_rate - 40)
        tolerance_value = 5  # Hz

        self.assertLessEqual(expected_value, tolerance_value)

        if TEST_PLOTS:

            fig, ax = plt.subplots(3, figsize=(8, 6), sharex=True)
            ax[0].plot(tv, Voltages, lw=2, label=str(2))
            labels = ["ampa", "nmda", "gaba_a", "gaba_b"]
            j = 0
            for i in record_from[1:]:
                g = dmm["events"][i]
                ax[1].plot(tv, g, lw=2, label=labels[j])
                j += 1

            ax[2].plot(ts, spikes, 'k.')
            ax[2].set_xlabel("Time [ms]")
            ax[2].set_xlim(0, t_simulation)
            ax[2].set_ylabel("Spikes")
            ax[0].set_title("recording from PSP")
            ax[0].set_ylabel("v [ms]")
            ax[1].set_ylabel("I_syn")
            ax[1].legend(frameon=False, loc="upper right")

            plt.savefig("traub_cond_multisyn.png")
Example #29
0
    def test_multisynapse(self):
        input_path = os.path.join(os.path.realpath(os.path.join(os.path.dirname(__file__), "..", "resources", "iaf_psc_exp_multisynapse.nestml")))
        nest_path = "/home/travis/nest_install"
        target_path = 'target'
        logging_level = 'INFO'
        module_name = 'nestmlmodule'
        store_log = False
        suffix = '_nestml'
        dev = True
        to_nest(input_path, target_path, logging_level, module_name, store_log, suffix, dev)
        install_nest(target_path, nest_path)
        nest.set_verbosity("M_ALL")

        nest.ResetKernel()
        nest.Install("nestmlmodule")

        # network construction

        neuron = nest.Create("iaf_psc_exp_multisynapse_neuron_nestml")

        sg = nest.Create("spike_generator", params={"spike_times": [20., 80.]})
        nest.Connect(sg, neuron, syn_spec={"receptor_type" : 1, "weight": 1000., "delay": 0.1})

        sg2 = nest.Create("spike_generator", params={"spike_times": [40., 60.]})
        nest.Connect(sg2, neuron, syn_spec={"receptor_type" : 2, "weight": 1000., "delay": 0.1})

        sg3 = nest.Create("spike_generator", params={"spike_times": [30., 70.]})
        nest.Connect(sg3, neuron, syn_spec={"receptor_type" : 3, "weight": 500., "delay": 0.1})

        i_1 = nest.Create('multimeter', params={'record_from': ['I_shape', 'I_shape2', 'I_shape3'], 'interval': 0.1})
        nest.Connect(i_1, neuron)

        vm_1 = nest.Create('voltmeter')
        nest.Connect(vm_1, neuron)

        # simulate

        nest.Simulate(125.)

        # analysis

        if TEST_PLOTS:
            vm_1 = vm_1.get("events")
            i_1 = i_1.get("events")

            fig, ax = plt.subplots(nrows=4)

            ax[0].plot(vm_1["times"], vm_1["V_m"], label="V_m")
            ax[0].set_ylabel("voltage")

            ax[1].plot(i_1["times"], i_1["I_shape"], label="I_shape")
            ax[1].set_ylabel("current")

            ax[2].plot(i_1["times"], i_1["I_shape2"], label="I_shape2")
            ax[2].set_ylabel("current")

            ax[3].plot(i_1["times"], i_1["I_shape3"], label="I_shape3")
            ax[3].set_ylabel("current")

            for _ax in ax:
                _ax.legend(loc="upper right")
                _ax.set_xlim(0., 125.)
                _ax.grid(True)

            for _ax in ax[:-1]:
                _ax.set_xticklabels([])

            ax[-1].set_xlabel("time")

            plt.show()