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)
예제 #3
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)
예제 #4
0
파일: model.py 프로젝트: jougs/nest-server
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}
예제 #5
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
예제 #6
0
    def test_custom_templates_with_synapse(self):
        models = [
            "neurons/iaf_psc_delta.nestml",
            "synapses/stdp_triplet_naive.nestml"
        ]
        input_paths = [
            os.path.join(
                os.path.realpath(
                    os.path.join(
                        os.path.dirname(__file__),
                        os.path.join(os.pardir, os.pardir, "models", fn))))
            for fn in models
        ]
        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

        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"]
            }],
            "templates": {
                "path":
                'point_neuron',
                "model_templates": {
                    "neuron":
                    ['NeuronClass.cpp.jinja2', 'NeuronHeader.h.jinja2'],
                    "synapse": ['SynapseHeader.h.jinja2']
                },
                "module_templates": [
                    'setup/CMakeLists.txt.jinja2',
                    'setup/ModuleHeader.h.jinja2',
                    'setup/ModuleClass.cpp.jinja2'
                ]
            }
        }

        neuron_model_name = "iaf_psc_delta_nestml__with_stdp_triplet_nestml"
        synapse_model_name = "stdp_triplet_nestml__with_iaf_psc_delta_nestml"

        to_nest(input_paths, target_path, logging_level, module_name,
                store_log, suffix, dev, codegen_opts)
        install_nest(target_path, nest_path)
        nest.set_verbosity("M_ALL")
예제 #7
0
 def test_from_objects(self):
     input_path = os.path.join(os.path.dirname(__file__), 'resources', 'CommentTest.nestml')
     target_path = os.path.join('target')
     logging_level = 'INFO'
     module_name = 'module'
     store_log = False
     suffix = ''
     dev = True
     to_nest(input_path, target_path, logging_level, module_name, store_log, suffix, dev)
     self.assertTrue(os.path.isfile(os.path.join(FrontendConfiguration.get_target_path(), 'CMakeLists.txt')))
     self.assertTrue(os.path.isfile(os.path.join(FrontendConfiguration.get_target_path(), 'commentTest.cpp')))
     self.assertTrue(os.path.isfile(os.path.join(FrontendConfiguration.get_target_path(), 'commentTest.h')))
     self.assertTrue(os.path.isfile(os.path.join(FrontendConfiguration.get_target_path(), 'module.cpp')))
     self.assertTrue(os.path.isfile(os.path.join(FrontendConfiguration.get_target_path(), 'module.h')))
예제 #8
0
    def test_custom_templates(self):
        input_path = os.path.join(
            os.path.realpath(
                os.path.join(
                    os.path.dirname(__file__),
                    os.path.join(os.pardir, os.pardir, "models", "neurons",
                                 "iaf_psc_exp.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

        codegen_opts = {
            "templates": {
                "path":
                'point_neuron',
                "model_templates": {
                    "neuron":
                    ['NeuronClass.cpp.jinja2', 'NeuronHeader.h.jinja2'],
                    "synapse": ['SynapseHeader.h.jinja2']
                },
                "module_templates": [
                    'setup/CMakeLists.txt.jinja2',
                    'setup/ModuleHeader.h.jinja2',
                    'setup/ModuleClass.cpp.jinja2'
                ]
            }
        }

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

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

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

        nest.Connect(mm, nrn)

        nest.Simulate(5.0)
예제 #9
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")
예제 #10
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)
예제 #11
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)
예제 #12
0
    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)
예제 #13
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)
예제 #14
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)
예제 #15
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)
예제 #17
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
예제 #20
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")
예제 #21
0
    def test_custom_templates_with_synapse(self):
        models = [
            os.path.join("neurons", "iaf_psc_delta.nestml"),
            os.path.join("synapses", "stdp_triplet_naive.nestml")
        ]
        input_paths = [
            os.path.join(
                os.path.realpath(
                    os.path.join(
                        os.path.dirname(__file__),
                        os.path.join(os.pardir, os.pardir, "models", fn))))
            for fn in models
        ]
        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

        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"]
            }],
            "templates": {
                "path":
                'point_neuron',
                "model_templates": {
                    "neuron":
                    ['NeuronClass.cpp.jinja2', 'NeuronHeader.h.jinja2'],
                    "synapse": ['SynapseHeader.h.jinja2']
                },
                "module_templates": [
                    'setup/CMakeLists.txt.jinja2',
                    'setup/ModuleHeader.h.jinja2',
                    'setup/ModuleClass.cpp.jinja2'
                ]
            }
        }

        neuron_model_name = "iaf_psc_delta_nestml__with_stdp_triplet_nestml"
        synapse_model_name = "stdp_triplet_nestml__with_iaf_psc_delta_nestml"

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

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

        neurons = nest.Create(neuron_model_name, 2)
        weight_recorder = nest.Create('weight_recorder')
        nest.CopyModel(synapse_model_name, synapse_model_name + "_rec",
                       {'weight_recorder': weight_recorder[0]})
        mm = nest.Create('multimeter')
        mm.set({"record_from": ["V_m"]})

        nest.Connect(neurons[0],
                     neurons[1],
                     syn_spec={'synapse_model': synapse_model_name + "_rec"})
        nest.Connect(mm, neurons[0])

        nest.Simulate(5.0)
예제 #22
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)
예제 #23
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")
예제 #24
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])
예제 #25
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)
예제 #26
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()
예제 #27
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)
예제 #28
0
    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."
예제 #29
0
    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")
예제 #30
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)