def InstallBCPNN(on_milner=False, on_beskow=False): ''' This function installs the BCPNN Synapse by Phil Tully. The optional parameter passed, indicate whether this is on Supercomputer Milner (True) or Beskow or my local machine (False) ''' if ('milner' in os.getcwd()): on_milner = True if ('klemming' in os.getcwd()): on_beskow = True if (not 'bcpnn_synapse' in nest.Models('synapses')): if on_beskow: nest.sr( '(/cfs/klemming/nobackup/f/fiebig/170501_Beskow_BCPNN/share/nest/sli) addpath' ) nest.Install( '/cfs/klemming/nobackup/f/fiebig/170501_Beskow_BCPNN/lib/nest/pt_module' ) elif on_milner: nest.sr( '(/cfs/milner/scratch/f/fiebig/140408_Milner_BCPNN/share/nest/sli) addpath' ) nest.Install( '/cfs/milner/scratch/f/fiebig/140408_Milner_BCPNN/lib/nest/pt_module' ) else: try: nest.Install('pt_module') except: nest.Install('pt_module')
def install_module(path, sli_path, model_to_exist='my_aeif_cond_exp'): if not model_to_exist in nest.Models(): if sli_path != '': nest.sr('(' + sli_path + ') addpath') #nest.Install(path) # Solves weird problem that I need to load it twice # only on my wheezy debian try: nest.Install(path) #always fails in Nest 2.4.X except: nest.Install(path) #running twice fixes Nest 2.4.X print '...successful'
def main(): RESOLUTION = s_to_ms(0.001) SIMULATION_TIME = s_to_ms(0.5) N_STEPS = int(SIMULATION_TIME / RESOLUTION) TRACE_LENGTH = N_STEPS + 1 nest.ResetKernel() nest.SetKernelStatus({"resolution": RESOLUTION}) nest.Install("sporemodule") nest.sli_func('InitSynapseUpdater', N_STEPS, 0) proxy = nest.Create("reward_in_proxy") nest.SetStatus(proxy, {'port_name': 'in', 'delay': 0.0}) nest.Simulate(SIMULATION_TIME) traces = nest.GetStatus(proxy, ("trace"))[0] for i, trace in enumerate(traces): assert len(trace) == TRACE_LENGTH # NEST-inherent delay of one timestep forces first value to be unchanged assert trace[0] == 0.0, "Buffer on NEST side is initialized with 0." assert trace[N_STEPS] == 0.0, "Unused value is zero" # [0.0, received values ..., 0.0], #elements = N_STEPS + 1 values = np.array(list(map(s_to_ms, trace[1:N_STEPS]))) expect = np.arange(0.0, SIMULATION_TIME, RESOLUTION)[:-1] + s_to_ms(float(i)) assert np.allclose(values, expect), "{}\n{}".format(values, expect)
def __init__(self, dt): self.name = self.__class__.__name__ if not os.path.exists(self.data_path): os.makedirs(self.data_path) nest.ResetKernel() nest.set_verbosity('M_QUIET') self.dt = dt self.model = "{}_nestml".format(self.model_name) nest.Install(self.module_name) # parameters = nest.GetDefaults(self.model) # for i in parameters: # print(i, parameters[i]) nest.SetKernelStatus({ "resolution": dt, "print_time": False, "overwrite_files": True, "data_path": self.data_path, "local_num_threads": self.nthreads })
def setUp(self): """Generate the neuron model code""" # nest.Install("nestml_jit_module") # return 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")
def test_nest_instantiability(self): # N.B. all models are assumed to have been already built (see .travis.yml) nest.ResetKernel() nest.set_verbosity("M_ALL") nest.Install("nestml_allmodels_module") models = nest.Models(mtype="nodes") neuron_models = [ m for m in models if str(nest.GetDefaults(m, "element_type")) == "neuron" ] _neuron_models = strip_suffix(neuron_models, "_neuron") nestml_unit_test_models = [ neuron_model_name for neuron_model_name in _neuron_models if neuron_model_name.endswith("_nestml") ] nest.ResetKernel() for neuron_model in nestml_unit_test_models: print("Instantiating neuron model: " + str(neuron_model)) nest.Create(neuron_model) nest.Simulate(100.)
def load_libraries(self, name, url, **kwargs): # @UnusedVariable install_dir = self.get_install_dir(name, url) lib_dir = os.path.join(install_dir, 'lib') add_lib_path(lib_dir) # Add module install directory to NEST path nest.sli_run('({}) addpath'.format( os.path.join(install_dir, 'share', 'sli'))) # Install nest module nest.Install(name + 'Module')
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
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")))) target_path = "target" target_platform = "NEST2" logging_level = "INFO" module_name = "nestmlmodule" suffix = "_nestml" codegen_opts = { "neuron_parent_class_include": "archiving_node.h", "neuron_parent_class": "Archiving_Node", "templates": { "path": os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, "pynestml", "codegeneration", "resources_nest", "point_neuron_nest2"), "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" ] } } generate_target(input_path, target_platform, target_path, logging_level=logging_level, module_name=module_name, suffix=suffix, codegen_opts=codegen_opts) nest.set_verbosity("M_ALL") nest.ResetKernel() nest.Install("nestmlmodule") nrn = nest.Create("iaf_psc_exp_nestml") mm = nest.Create("multimeter") nest.SetStatus(mm, {"record_from": ["V_m"]}) nest.Connect(mm, nrn) nest.Simulate(5.0)
def test_nest_integration(self): # N.B. all models are assumed to have been already built (see .travis.yml) nest.ResetKernel() nest.set_verbosity("M_ALL") nest.Install("nestml_allmodels_module") models = [] models.append(("iaf_psc_delta", "iaf_psc_delta_nestml", None, 1E-3)) models.append(("iaf_psc_exp", "iaf_psc_exp_nestml", None, .01)) models.append(("iaf_psc_alpha", "iaf_psc_alpha_nestml", None, 1E-3)) models.append(("iaf_cond_exp", "iaf_cond_exp_nestml", 1E-3, 1E-3)) models.append(("iaf_cond_alpha", "iaf_cond_alpha_nestml", 1E-3, 1E-3)) models.append(("iaf_cond_beta", "iaf_cond_beta_nestml", 1E-3, 1E-3, {"tau_rise_ex": 2., "tau_decay_ex": 10., "tau_rise_in": 2., "tau_decay_in": 10.}, {"tau_syn_rise_E": 2., "tau_syn_decay_E": 10., "tau_syn_rise_I": 2., "tau_syn_decay_I": 10.})) # XXX: TODO: does not work yet when tau_rise = tau_fall (numerical singularity occurs in the propagators) models.append(("izhikevich", "izhikevich_nestml", 1E-3, 1)) # large tolerance because NEST Simulator model does not use GSL solver, but simple forward Euler models.append(("hh_psc_alpha", "hh_psc_alpha_nestml", 1E-3, 1E-3)) models.append(("iaf_chxk_2008", "iaf_chxk_2008_nestml", 1E-3, 1E-3)) models.append(("aeif_cond_exp", "aeif_cond_exp_nestml", 1.e-3, 1E-3)) models.append(("aeif_cond_alpha", "aeif_cond_alpha_nestml", 1.e-3, 1E-3)) # -------------- # XXX: TODO! # models.append(("hh_cond_exp_traub", "hh_cond_exp_traub_nestml", 1.e-3, 1E-3)) # models.append(("ht_neuron", "hill_tononi_nestml", None, 1E-3)) # models.append(("iaf_cond_exp_sfa_rr", "iaf_cond_exp_sfa_rr_nestml", 1.e-3, 1E-3)) # models.append(("iaf_tum_2000", "iaf_tum_2000_nestml", None, 0.01)) # models.append(("mat2_psc_exp", "mat2_psc_exp_nestml", None, 0.1)) for model in models: reference = model[0] testant = model[1] gsl_error_tol = model[2] tolerance = model[3] if len(model) > 4: nest_ref_model_opts = model[4] else: nest_ref_model_opts = None if len(model) > 5: custom_model_opts = model[5] else: custom_model_opts = None self._test_model(reference, testant, gsl_error_tol, tolerance, nest_ref_model_opts, custom_model_opts) self._test_model_subthreshold(reference, testant, gsl_error_tol, tolerance, nest_ref_model_opts, custom_model_opts) all_models = [s[:-7] for s in list(os.walk("models"))[0][2] if s[-7:] == ".nestml"] self.generate_models_documentation(models, all_models)
def load_module(modname): err = "DynamicModuleManagementError in Install: Module '{0:s}' is " + \ "loaded already." try: nest.Install(modname) except nest.NESTError as ex: err_modname = err.format(modname) if ex.args[0] == err_modname: pass # module already loaded else: raise ex
def test_recordable_variables(self): input_path = os.path.join( os.path.realpath( os.path.join(os.path.dirname(__file__), "resources", "RecordableVariables.nestml"))) target_path = "target" logging_level = "INFO" module_name = "nestmlmodule" suffix = "_nestml" generate_nest_target(input_path, target_path=target_path, logging_level=logging_level, module_name=module_name, suffix=suffix) 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)
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)
def ensure_visionary_nest_model_available(model): """Try to load nest and try to install 'visionarymodule'. Return value indicates if nest and the specified model is available afterwards. """ try: import nest except ImportError: return False if model not in nest.Models(): try: nest.Install("visionarymodule") except nest.pynestkernel.NESTError: return False return model in nest.Models()
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)
def test_neuron_synapse_multithreading(self): pre_spike_times = np.array([2., 4., 7., 8., 12., 13., 19., 23., 24., 28., 29., 30., 33., 34., 35., 36., 38., 40., 42., 46., 51., 53., 54., 55., 56., 59., 63., 64., 65., 66., 68., 72., 73., 76., 79., 80., 83., 84., 86., 87., 90., 95.]) post_spike_times = np.array([4., 5., 6., 7., 10., 11., 12., 16., 17., 18., 19., 20., 22., 23., 25., 27., 29., 30., 31., 32., 34., 36., 37., 38., 39., 42., 44., 46., 48., 49., 50., 54., 56., 57., 59., 60., 61., 62., 67., 74., 76., 79., 80., 81., 83., 88., 93., 94., 97., 99.]) nest.set_verbosity("M_ALL") nest.ResetKernel() nest.Install(self.neuron_synapse_module) nest.SetKernelStatus({'resolution': 0.1, 'local_num_threads': self.number_of_threads}) wr = nest.Create('weight_recorder') nest.CopyModel(self.neuron_synapse_synapse_model, "stdp_nestml_rec", {"weight_recorder": wr[0], "w": 1., "the_delay": 1., "receptor_type": 0}) # Spike generators pre_sg = nest.Create("spike_generator", 2, params={"spike_times": pre_spike_times}) post_sg = nest.Create("spike_generator", 2, params={"spike_times": post_spike_times, 'allow_offgrid_times': True}) pre_neuron = nest.Create(self.neuron_synapse_neuron_model, 2) post_neuron = nest.Create(self.neuron_synapse_neuron_model, 2) sr_pre = nest.Create("spike_recorder") sr_post = nest.Create("spike_recorder") mm = nest.Create("multimeter", params={"record_from": ["V_m"]}) nest.Connect(pre_sg, pre_neuron, "one_to_one", syn_spec={"delay": 1.}) nest.Connect(post_sg, post_neuron, "one_to_one", syn_spec={"delay": 1., "weight": 9999.}) nest.Connect(pre_neuron, post_neuron, "all_to_all", syn_spec={'synapse_model': 'stdp_nestml_rec'}) nest.Connect(mm, post_neuron) nest.Connect(pre_neuron, sr_pre) nest.Connect(post_neuron, sr_post) nest.Simulate(100.) V_m = nest.GetStatus(mm, "events")[0]["V_m"] print(V_m) np.testing.assert_almost_equal(V_m[-4], -59.17946541)
def simulate_OU_noise_neuron(self, resolution): r""" 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, "rng_seed": seed + 1}) input_path = os.path.join(os.path.realpath(os.path.join(os.path.dirname(__file__), "..", "..", "models", "neurons", "hh_cond_exp_destexhe.nestml"))) target_path = "target" logging_level = "INFO" module_name = "nestmlmodule" suffix = "_nestml" generate_nest_target(input_path, target_path=target_path, logging_level=logging_level, module_name=module_name, suffix=suffix) 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
def __init__(self): super(_State, self).__init__() try: nest.Install('pynn_extensions') self.extensions_loaded = True except nest.kernel.NESTError as err: self.extensions_loaded = False self.initialized = False self.optimize = False self.spike_precision = "off_grid" self.verbosity = "error" self._cache_num_processes = nest.GetKernelStatus( )['num_processes'] # avoids blocking if only some nodes call num_processes # do the same for rank? # allow NEST to erase previously written files (defaut with all the other simulators) nest.SetKernelStatus({'overwrite_files': True}) self.tempdirs = [] self.recording_devices = [] self.populations = [] # needed for reset self.stale_connection_cache = False
def test_vectors(self): input_path = os.path.join( os.path.realpath( os.path.join(os.path.dirname(__file__), "resources", "Vectors.nestml"))) target_path = "target" logging_level = "INFO" module_name = "nestmlmodule" suffix = "_nestml" generate_nest_target(input_path, target_path=target_path, logging_level=logging_level, module_name=module_name, suffix=suffix) 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)
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] target_path = "target" logging_level = "INFO" module_name = "nestmlmodule" suffix = "_nestml" generate_nest_target(input_path, target_path=target_path, logging_level=logging_level, module_name=module_name, suffix=suffix) 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)
def test_neuron_multithreading(self): nest.set_verbosity("M_ALL") nest.ResetKernel() nest.Install(self.neuron_module) nest.SetKernelStatus({'resolution': 0.1, 'local_num_threads': self.number_of_threads}) spike_times = np.arange(10, 100, 9).astype(np.float) sg = nest.Create('spike_generator', params={'spike_times': spike_times}) n = nest.Create(self.neuron_model, 5) nest.Connect(sg, n) multimeter = nest.Create('multimeter', params={"record_from": ["V_m"]}) nest.Connect(multimeter, n) nest.Simulate(1000.) events = multimeter.get("events") v_m = events["V_m"] np.testing.assert_almost_equal(v_m[-1], -70.)
def install_module(module_name): """Install module in NEST using nest.Install() and catch errors. Even after resetting the kernel, NEST throws a NESTError (rather than a) warning when the module is already loaded. I couldn't find a way to test whether the module is already installed so this function catches the error if the module is already installed by matching the error message. """ import nest try: nest.Install(module_name) except nest.NESTError as exception: if 'loaded already' in str(exception): print(f'\nModule {module_name} is already loaded.') return if ('could not be opened' in str(exception) and 'file not found' in str(exception)): print(f'\nModule {module_name} could not be loaded. Did you' f' compile and install the extension module?') raise exception raise
def restart_kernel(_nest_seed=None, _np_seed=None): global nest_seed, np_seed nest.ResetKernel() nest.SetKernelStatus({'local_num_threads': params.sim.n_threads}) nest.SetKernelStatus({'resolution': params.sim.step}) try: nest.Install('izhikevich_cond_module') except: pass # Random number generation N_vp = nest.GetKernelStatus(['total_num_virtual_procs'])[0] nest_seed = nest_seed + N_vp + 2 if _nest_seed is None else _nest_seed np_seed = nest_seed + N_vp if _np_seed is None else _np_seed pyrngs = [ np.random.RandomState(s) for s in range(nest_seed, nest_seed + N_vp) ] nest.SetKernelStatus({'rng_seeds': range(nest_seed, nest_seed + N_vp)}) nest.SetKernelStatus({'grng_seed': nest_seed + N_vp + 1}) np.random.seed(np_seed)
def setup_nest(grng_seed, rng_seed, resolution): """ Setup NEST multithreading and seeds, and load swtamodule. """ try: nest.Install('swtamodule') except nest.NESTError as ex: err = "DynamicModuleManagementError in Install: Module 'swtamodule' is loaded already." if ex.args[0] == err: pass else: raise ex print("seeeeeeeds", grng_seed, rng_seed) nest.ResetKernel() nest.SetKernelStatus({ 'grng_seed': grng_seed, 'rng_seeds': [rng_seed], 'resolution': resolution * 1000. }) nest.set_verbosity('M_FATAL')
def test_resolution_function(self): nest.set_verbosity("M_ALL") nest.ResetKernel() nest.Install("nestmlmodule") models = nest.Models(mtype="nodes") neuron_models = [ m for m in models if str(nest.GetDefaults(m, "element_type")) == "neuron" ] print(neuron_models) pre = nest.Create("iaf_psc_exp", 100) post = nest.Create( "iaf_psc_exp_resolution_test_nestml__with_CoCoResolutionLegallyUsed_nestml" ) nest.Connect( pre, post, "all_to_all", syn_spec={ 'synapse_model': "CoCoResolutionLegallyUsed_nestml__with_iaf_psc_exp_resolution_test_nestml" }) nest.Simulate(100.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)
import numpy as np from scipy.io import loadmat import nest from . import gc_neurons from .gc_net import GridCellNetwork from .place_input import PlaceCellInput from .place_cells import UniformBoxPlaceCells from simtools.storage import DataStorage logger = logging.getLogger(__name__) gcnLogger = logging.getLogger('{0}.{1}'.format(__name__, "NestGridCellNetwork")) nest.Install('gridcellsmodule') class PosInputs(object): '''Data representing animal position input.''' def __init__(self, pos_x, pos_y, pos_dt): self.pos_x = pos_x self.pos_y = pos_y self.pos_dt = pos_dt def __str__(self): res = ("PosInputs:\n pos_x: {0}\n pos_y: {1}\n " "pos_dt: {2}".format(self.pos_x, self.pos_y, self.pos_dt)) return res
import math import nest import pylab as plt nest.Install("stdpmodule") nest.set_verbosity("M_WARNING") nest.ResetKernel() def generateSpikes(neuron, times): """Trigger spike to given neuron at specified times.""" delay = 1.0 gen = nest.Create("spike_generator", 1, {"spike_times": [t - delay for t in times]}) nest.Connect(gen, neuron, syn_spec={"delay": delay}) # settings syn_spec = { "weight": 5.0, "tau_plus": 16.8, "tau_plus_triplet": 101.0, "tau_minus": 33.7, "tau_minus_triplet": 125.0, "Aplus": 0.1, "Aminus": 0.1, "Aplus_triplet": 0.1, "Aminus_triplet": 0.1, "Kplus": 0.0, "Kplus_triplet": 0.0, "Kminus": 0.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")
import nest import os os.environ['LD_LIBRARY_PATH'] = '/home/ubuntu/.local' nest.Install('myModels') import time from numpy import exp import numpy as np import h5py as h5py import os import json import hashlib class ChunkError(Exception): pass class BuildError(Exception): pass class adLIFNet(object): """ Network of LIF neurons. inspired by Gewaltig et al. 2012""" built = False connected = False verbose = False # threads = 7 # dt = float(0.5) # the resolution in ms for the clock-based