def setUp(self): nest.ResetKernel() nest.SetKernelStatus({"total_num_virtual_procs": 4}) nest.ResetNetwork() nest.set_verbosity('M_DEBUG') self.sim_time = 10000 self.sim_step = 100 nest.SetKernelStatus( {'structural_plasticity_update_interval': self.sim_time + 1}) self.se_integrator = [] self.sim_steps = None self.ca_nest = None self.ca_python = None self.se_nest = None self.se_python = None # build self.pop = nest.Create('iaf_psc_alpha', 10) local_nodes = nest.GetNodes([0], {'model': 'iaf_psc_alpha'}, True) self.local_nodes = local_nodes[0] self.spike_detector = nest.Create('spike_detector') nest.Connect(self.pop, self.spike_detector, 'all_to_all') noise = nest.Create('poisson_generator') nest.SetStatus(noise, {"rate": 800000.0}) nest.Connect(noise, self.pop, 'all_to_all')
def setUp(self): nest.ResetKernel() nest.SetKernelStatus({"total_num_virtual_procs": 4}) nest.ResetNetwork() nest.set_verbosity('M_DEBUG') self.sim_time = 10000 self.sim_step = 100 nest.SetKernelStatus( {'structural_plasticity_update_interval': self.sim_time + 1}) self.se_integrator = [] self.sim_steps = None self.ca_nest = None self.ca_python = None self.se_nest = None self.se_python = None # build self.pop = nest.Create('iaf_psc_alpha', 10) self.local_nodes = nest.GetNodes([0], {'model': 'iaf_psc_alpha'}, True)[0] self.spike_detector = nest.Create('spike_detector') nest.Connect(self.pop, self.spike_detector, 'all_to_all') noise = nest.Create('poisson_generator') nest.SetStatus(noise, {"rate": 800000.0}) nest.Connect(noise, self.pop, 'all_to_all')
def setUp(self): """Set up the test.""" nest.set_verbosity('M_WARNING') nest.ResetKernel() # settings self.dendritic_delay = 1.0 self.decay_duration = 5.0 self.synapse_model = "vogels_sprekeler_synapse" self.syn_spec = { "model": self.synapse_model, "delay": self.dendritic_delay, "weight": 5.0, "eta": 0.001, "alpha": 0.1, "tau": 20., "Kplus": 0.0, "Wmax": 15., } # setup basic circuit self.pre_neuron = nest.Create("parrot_neuron") self.post_neuron = nest.Create("parrot_neuron") nest.Connect(self.pre_neuron, self.post_neuron, syn_spec=self.syn_spec)
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 __init__(self, dt, nthreads): # adj, N, dt, tau_syn_ex, delay, nthreads): self.name = self.__class__.__name__ nest.ResetKernel() nest.set_verbosity('M_WARNING') self.dt = dt # self.delay = delay # self.adj = adj # self.N = N # self.tau_syn_ex = tau_syn_ex nest.SetKernelStatus({ 'resolution': self.dt, 'local_num_threads': nthreads, "data_path": self.data_path, "overwrite_files": True, "print_time": False, }) msd = 1000 # master seed n_vp = nest.GetKernelStatus('total_num_virtual_procs') msdrange1 = range(msd, msd + n_vp) self.pyrngs = [np.random.RandomState(s) for s in msdrange1] msdrange2 = range(msd + n_vp + 1, msd + 1 + 2 * n_vp) nest.SetKernelStatus({'grng_seed': msd + n_vp, 'rng_seeds': msdrange2})
def single_neuron(spike_times, sim_duration): nest.set_verbosity('M_WARNING') # reduce NEST output nest.ResetKernel() # reset simulation kernel # create LIF neuron with exponential synaptic currents neuron = nest.Create('iaf_psc_exp') # create a voltmeter voltmeter = nest.Create('voltmeter', params={'interval': 0.1}) # create a spike generator spikegenerator = nest.Create('spike_generator') # ... and let it spike at predefined times nest.SetStatus(spikegenerator, {'spike_times': spike_times}) # connect spike generator and voltmeter to the neuron nest.Connect(spikegenerator, neuron) nest.Connect(voltmeter, neuron) # run simulation for sim_duration nest.Simulate(sim_duration) # read out recording time and voltage from voltmeter times = nest.GetStatus(voltmeter)[0]['events']['times'] voltage = nest.GetStatus(voltmeter)[0]['events']['V_m'] # plot results plt.plot(times, voltage) plt.xlabel('Time (ms)') plt.ylabel('Membrane potential (mV)') filename = 'single_neuron.png' plt.savefig(filename, dpi=300)
def run_simulation(): """Performs a simulation, including network construction""" # open log file with Logger(params['log_file']) as logger: nest.ResetKernel() nest.set_verbosity(M_INFO) logger.log(str(memory_thisjob()) + ' # virt_mem_0') sr = build_network(logger) tic = time.time() nest.Simulate(params['presimtime']) PreparationTime = time.time() - tic logger.log(str(memory_thisjob()) + ' # virt_mem_after_presim') logger.log(str(PreparationTime) + ' # presim_time') tic = time.time() nest.Simulate(params['simtime']) SimCPUTime = time.time() - tic logger.log(str(memory_thisjob()) + ' # virt_mem_after_sim') logger.log(str(SimCPUTime) + ' # sim_time') if params['record_spikes']: logger.log(str(compute_rate(sr)) + ' # average rate') print(nest.GetKernelStatus())
def test_ConnectNeuronsWithClopathSynapse(self): """Ensures that the restriction to supported neuron models works.""" nest.set_verbosity('M_WARNING') # Specify supported models supported_models = [ 'aeif_psc_delta_clopath', 'hh_psc_alpha_clopath', ] # Connect supported models with Clopath synapse for nm in supported_models: nest.ResetKernel() n = nest.Create(nm, 2) nest.Connect(n, n, {"rule": "all_to_all"}, {"model": "clopath_synapse"}) # Compute not supported models not_supported_models = [n for n in nest.Models(mtype='nodes') if n not in supported_models] # Ensure that connecting not supported models fails for nm in not_supported_models: nest.ResetKernel() n = nest.Create(nm, 2) # try to connect with clopath_rule with self.assertRaises(nest.kernel.NESTError): nest.Connect(n, n, {"rule": "all_to_all"}, {"model": "clopath_synapse"})
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 __init__(self, dt, nthreads): self.name = self.__class__.__name__ nest.ResetKernel() nest.set_verbosity('M_QUIET') if not os.path.exists(self.data_path): os.makedirs(self.data_path) nest.SetKernelStatus({ "resolution": dt, "print_time": False, "overwrite_files": True, "data_path": self.data_path, "local_num_threads": nthreads }) np.random.seed(125472) # Create and seed RNGs msd = 1000 # master seed n_vp = nest.GetKernelStatus('total_num_virtual_procs') msdrange1 = range(msd, msd + n_vp) self.pyrngs = [np.random.RandomState(s) for s in msdrange1] msdrange2 = range(msd + n_vp + 1, msd + 1 + 2 * n_vp) nest.SetKernelStatus({'grng_seed': msd + n_vp, 'rng_seeds': msdrange2})
def setUp(self): nest.set_verbosity('M_WARNING') nest.ResetKernel() # settings self.dendritic_delay = 1.0 self.decay_duration = 5.0 self.synapse_model = "stdp_triplet_synapse" self.syn_spec = { "synapse_model": self.synapse_model, "delay": self.dendritic_delay, # set receptor 1 postsynaptically, to not generate extra spikes "receptor_type": 1, "weight": 5.0, "tau_plus": 16.8, "tau_plus_triplet": 101.0, "Aplus": 0.1, "Aminus": 0.1, "Aplus_triplet": 0.1, "Aminus_triplet": 0.1, "Kplus": 0.0, "Kplus_triplet": 0.0, "Wmax": 100.0, } self.post_neuron_params = { "tau_minus": 33.7, "tau_minus_triplet": 125.0, } # setup basic circuit self.pre_neuron = nest.Create("parrot_neuron") self.post_neuron = nest.Create("parrot_neuron", 1, params=self.post_neuron_params) nest.Connect(self.pre_neuron, self.post_neuron, syn_spec=self.syn_spec)
def setUp(self): nest.ResetKernel() nest.set_verbosity('M_ERROR') nest.total_num_virtual_procs = 4 nest.rng_seed = 1 self.sim_time = 10000.0 self.sim_step = 100 nest.structural_plasticity_update_interval = self.sim_time + 1 self.se_integrator = [] self.sim_steps = None self.ca_nest = None self.ca_python = None self.se_nest = None self.se_python = None # build self.pop = nest.Create('iaf_psc_alpha', 10) self.spike_recorder = nest.Create('spike_recorder') nest.Connect(self.pop, self.spike_recorder, 'all_to_all') noise = nest.Create('poisson_generator') nest.SetStatus(noise, {"rate": 800000.0}) nest.Connect(noise, self.pop, 'all_to_all')
def setUp(self): # test parameter self.rtol = 0.05 # neuron parameters self.neuron_params = {'mu': 1.5, 'sigma': 0.5, 'tau': 5.} # simulation parameters self.simtime = 10000. self.dt = 0.1 self.tstart = 10. * self.neuron_params['tau'] nest.set_verbosity('M_WARNING') nest.ResetKernel() nest.SetKernelStatus( {'resolution': self.dt, 'use_wfr': False, 'print_time': True}) # set up rate neuron and devices self.rate_neuron_ipn = nest.Create( 'lin_rate_ipn', params=self.neuron_params) self.rate_neuron_opn = nest.Create( 'lin_rate_opn', params=self.neuron_params) self.multimeter = nest.Create( "multimeter", params={'record_from': ['rate', 'noise'], 'interval': self.dt, 'start': self.tstart}) # record rates and noise nest.Connect( self.multimeter, self.rate_neuron_ipn + self.rate_neuron_opn)
def test_multiple_poisson_generators(self): """Invariable number of spikes with multiple poisson generators""" local_num_threads = 4 time_simulation = 100 num_neurons = 1 num_pg = 50 num_iterations = 50 num_spikes = [] for i in range(num_iterations): nest.ResetKernel() nest.SetKernelStatus({'local_num_threads': local_num_threads}) nest.set_verbosity('M_WARNING') print('num iter {:>5d}/{}'.format(i+1, num_iterations), end='\r') parrots = nest.Create('parrot_neuron', num_neurons) poisson_generator = nest.Create('poisson_generator', num_pg) poisson_generator.rate = 2000. nest.Connect(poisson_generator, parrots, 'all_to_all') nest.Simulate(time_simulation) num_spikes.append(nest.GetKernelStatus('local_spike_counter')) self.assertEqual(len(np.unique(num_spikes)), 1)
def setUp(self): nest.ResetKernel() nest.set_verbosity('M_ERROR') self.num_procs = 1 if mpi_test: self.comm = MPI.COMM_WORLD self.rank = self.comm.Get_rank() assert(nest.Rank() == self.rank) self.num_procs = 2 self.exclude_synapse_model = [ 'stdp_dopamine_synapse', 'stdp_dopamine_synapse_lbl', 'stdp_dopamine_synapse_hpc', 'stdp_dopamine_synapse_hpc_lbl', 'rate_connection_instantaneous', 'rate_connection_instantaneous_lbl', 'rate_connection_delayed', 'rate_connection_delayed_lbl', 'gap_junction', 'gap_junction_lbl', 'diffusion_connection', 'diffusion_connection_lbl', 'clopath_synapse', 'clopath_synapse_lbl' ]
def setUp(self): nest.set_verbosity('M_WARNING') nest.ResetKernel() # settings self.dendritic_delay = 1.0 self.decay_duration = 5.0 self.synapse_model = "stdp_triplet_synapse" self.syn_spec = { "model": self.synapse_model, "delay": self.dendritic_delay, "receptor_type": 1, # set receptor 1 post-synaptically, to not generate extra spikes "weight": 5.0, "tau_plus": 16.8, "tau_plus_triplet": 101.0, "Aplus": 0.1, "Aminus": 0.1, "Aplus_triplet": 0.1, "Aminus_triplet": 0.1, "Kplus": 0.0, "Kplus_triplet": 0.0, "Wmax": 100.0, } self.post_neuron_params = { "tau_minus": 33.7, "tau_minus_triplet": 125.0, } # setup basic circuit self.pre_neuron = nest.Create("parrot_neuron") self.post_neuron = nest.Create("parrot_neuron", 1, params=self.post_neuron_params) nest.Connect(self.pre_neuron, self.post_neuron, syn_spec=self.syn_spec)
def setUp(self): # test parameter to compare analytic solution to simulation self.rtol = 1.0 # test parameters self.N = 100 self.rate_ex = 1.5 * 1e4 self.J = 0.1 # simulation parameters self.simtime = 500. self.dt = 0.1 self.start = 200. nest.set_verbosity('M_WARNING') nest.ResetKernel() nest.SetKernelStatus( {'resolution': self.dt, 'use_wfr': False, 'print_time': True}) # set up driven integrate-and-fire neuron self.iaf_psc_delta = nest.Create( 'iaf_psc_delta', self.N) # , params={"C_m": 1.0}) self.poisson_generator = nest.Create( 'poisson_generator', params={'rate': self.rate_ex}) nest.Connect(self.poisson_generator, self.iaf_psc_delta, syn_spec={'weight': self.J, 'delay': self.dt}) self.spike_detector = nest.Create( "spike_detector", params={'start': self.start}) nest.Connect( self.iaf_psc_delta, self.spike_detector) # set up driven siegert neuron neuron_status = nest.GetStatus(self.iaf_psc_delta)[0] siegert_params = {'tau_m': neuron_status['tau_m'], 't_ref': neuron_status['t_ref'], 'theta': neuron_status['V_th'] - neuron_status['E_L'], 'V_reset': neuron_status['V_reset'] - neuron_status['E_L']} self.siegert_neuron = nest.Create( 'siegert_neuron', params=siegert_params) self.siegert_drive = nest.Create( 'siegert_neuron', 1, params={'mean': self.rate_ex}) J_mu_ex = neuron_status['tau_m'] * 1e-3 * self.J J_sigma_ex = neuron_status['tau_m'] * 1e-3 * self.J ** 2 syn_dict = {'drift_factor': J_mu_ex, 'diffusion_factor': J_sigma_ex, 'model': 'diffusion_connection'} nest.Connect( self.siegert_drive, self.siegert_neuron, syn_spec=syn_dict) self.multimeter = nest.Create( "multimeter", params={'record_from': ['rate'], 'interval': self.dt}) nest.Connect( self.multimeter, self.siegert_neuron)
def __init__(self, L, N, kernel_name, kernel_params=None): ''' Construct a test object. Parameters ---------- L : Side length of area / volume. N : Number of nodes. kernel_name : Name of kernel to use. kernel_params: Dict with params to update. ''' nest.set_verbosity('M_FATAL') SpatialTester.__init__(self, L=L, N=N) assert kernel_name == 'gaussian', 'Currently, only a Gaussian kernel' \ 'is supported by this implementation of the CSA.' self._kernel = lambda D: (self._params['c'] + self._params['p_center'] * np.e**-((D - self._params['mean'])**2 / (2. * self._params['sigma']**2))) default_params = { 'p_center': 1., 'sigma': self._L / 4., 'mean': 0., 'c': 0. } self._params = default_params if kernel_params is not None: assert kernel_params.keys() == ['sigma'], \ 'Only valid kernel parameter is "sigma".' self._params.update(kernel_params)
def setUp(self): nest.ResetKernel() nest.set_verbosity('M_ERROR') self.num_procs = 1 if mpi_test: self.comm = MPI.COMM_WORLD self.rank = self.comm.Get_rank() assert(nest.Rank() == self.rank) self.num_procs = 2 self.exclude_synapse_model = [ 'stdp_dopamine_synapse', 'stdp_dopamine_synapse_lbl', 'stdp_dopamine_synapse_hpc', 'stdp_dopamine_synapse_hpc_lbl', 'rate_connection_instantaneous', 'rate_connection_instantaneous_lbl', 'rate_connection_delayed', 'rate_connection_delayed_lbl', 'gap_junction', 'gap_junction_lbl', 'diffusion_connection', 'diffusion_connection_lbl', 'clopath_synapse', 'clopath_synapse_lbl', 'clopath_synapse_hpc' ]
def setupSimulation(self): """Set up the simulation.""" print("[INFO] Setting up simulation.") # NEST stuff nest.ResetKernel() nest.set_verbosity('M_INFO') nest.EnableStructuralPlasticity() nest.SetKernelStatus( { 'resolution': self.dt } ) nest.SetStructuralPlasticityStatus( { 'structural_plasticity_update_interval': self.spUpdateInterval, } ) self.setupSPSynapses() self.setupLayered() self.setupSpikeRecorders() self.calciumFile = open(self.calciumFileName, 'w') self.synapticElementsFile = open(self.synapticElementsFileName, 'w') print("[INFO] Setup complete.")
def test_ConnectNeuronsWithClopathSynapse(self): """Ensures that the restriction to supported neuron models works.""" nest.set_verbosity('M_WARNING') supported_models = [ 'aeif_psc_delta_clopath', 'hh_psc_alpha_clopath', ] # Connect supported models with Clopath synapse for nm in supported_models: nest.ResetKernel() n = nest.Create(nm, 2) nest.Connect(n, n, {"rule": "all_to_all"}, {"synapse_model": "clopath_synapse"}) # Ensure that connecting not supported models fails for nm in [n for n in nest.node_models if n not in supported_models]: nest.ResetKernel() n = nest.Create(nm, 2) # try to connect with clopath_rule with self.assertRaises(nest.kernel.NESTError): nest.Connect(n, n, {"rule": "all_to_all"}, {"synapse_model": "clopath_synapse"})
def __init__(self, N_s, N_t, p, e_min=5): ''' Construct a test object. Parameters ---------- N_s : Number of nodes in source population. N_t : Number of nodes in target population. p : Connection probability. e_min : Minimum expected number of observations in each bin. ''' nest.set_verbosity('M_FATAL') FPCTester.__init__(self, N_s=N_s, N_t=N_t, p=p, e_min=e_min) self._L = 1. maskdict = { 'rectangular': { 'lower_left': [-self._L / 2.] * 2, 'upper_right': [self._L / 2.] * 2 } } kernel = self._p self._conndict = { 'connection_type': 'divergent', 'mask': maskdict, 'kernel': kernel }
def setUp(self): """ Clean up and initialize NEST before each test. """ # test parameter to compare analytic solution to simulation self.rtol = 1e-1 # parameters of driven integrate-and-fire neurons self.N = 50 lif_params = { "V_th": -55., "V_reset": -70., "E_L": -70., "tau_m": 10.0, "t_ref": 2.0, "C_m": 250. } self.lif_params = lif_params # simulation parameters rng_seed = 123456 self.simtime = 600. self.dt = 0.01 self.start = 100. # reset kernel nest.set_verbosity("M_WARNING") nest.ResetKernel() nest.resolution = self.dt nest.use_wfr = False nest.rng_seed = rng_seed
def RunSimulation(): nest.set_verbosity(M_INFO) logger = Logger() logger.log('{} # virt_mem_0'.format(memory_thisjob())) # ----------------------- Network Construction ----------------------------- BuildNetwork(logger) # ---------------- Initial simulation: rig and calibrate ------------------- tic = time.time() nest.Prepare() nest.Run(params['inisimtime']) InitializationTime = time.time() - tic logger.log('{} # init_time'.format(InitializationTime)) logger.log('{} # virt_mem_after_init'.format(memory_thisjob())) # ----------------------- Cleanup and output ------------------------------- nest.Cleanup() logger.log('{} # num_neurons'.format(logger_params['num_nodes'])) logger.log('{} # num_connections'.format( nest.GetKernelStatus('num_connections'))) logger.log('{} # min_delay'.format(nest.GetKernelStatus('min_delay'))) logger.log('{} # max_delay'.format(nest.GetKernelStatus('max_delay')))
def __init__(self, dt, nthreads=1): self.name = self.__class__.__name__ nest.ResetKernel() nest.set_verbosity('M_QUIET') self.dt = dt # parameters = nest.GetDefaults(self.stn_model_name) # for i in parameters: # print(i, parameters[i]) if not os.path.exists(self.data_path): os.makedirs(self.data_path) nest.SetKernelStatus({ "resolution": dt, "print_time": False, "overwrite_files": True, "data_path": self.data_path, "local_num_threads": nthreads }) np.random.seed(2) # Create and seed RNGs master_seed = 1000 # master seed n_vp = nest.GetKernelStatus('total_num_virtual_procs') master_seed_range1 = range(master_seed, master_seed + n_vp) self.pyrngs = [np.random.RandomState(s) for s in master_seed_range1] master_seed_range2 = range(master_seed + n_vp + 1, master_seed + 1 + 2 * n_vp) nest.SetKernelStatus({ 'grng_seed': master_seed + n_vp, 'rng_seeds': master_seed_range2 })
def __init__(self, input_neurons_theta_size, input_neurons_theta_dot_size, liquid_neurons_size, readout_neurons_tau1_size, readout_neurons_tau2_size, output_layer_weight=100.0, thread_num=-1): # Don't make any nest nodes or connections before this line! nest.SetKernelStatus({ "local_num_threads": thread_num if thread_num > 0 else multiprocessing.cpu_count() }) nest.set_verbosity("M_ERROR") # suppress trivial messages self.total_sim_time = 0.0 self.tau1 = np.zeros(readout_neurons_tau1_size) self.tau2 = np.zeros(readout_neurons_tau2_size) self.output_layer_weight = output_layer_weight self.lsm = lsm.Lsm(input_neurons_theta_size, input_neurons_theta_dot_size, liquid_neurons_size, readout_neurons_tau1_size, readout_neurons_tau2_size, output_layer_weight=self.output_layer_weight)
def run_simulation(): '''Performs a simulation, including network construction''' # open log file with Logger(params['log_file']) as logger: nest.ResetKernel() nest.set_verbosity(M_INFO) logger.log(str(memory_thisjob()) + ' # virt_mem_0') sdet = build_network(logger) tic = time.time() nest.Simulate(params['presimtime']) PreparationTime = time.time() - tic logger.log(str(memory_thisjob()) + ' # virt_mem_after_presim') logger.log(str(PreparationTime) + ' # presim_time') tic = time.time() nest.Simulate(params['simtime']) SimCPUTime = time.time() - tic logger.log(str(memory_thisjob()) + ' # virt_mem_after_sim') logger.log(str(SimCPUTime) + ' # sim_time') if params['record_spikes']: logger.log(str(compute_rate(sdet)) + ' # average rate') print(nest.GetKernelStatus())
def test_targets(self): nest.ResetKernel() nest.set_verbosity('M_ALL') # Testing with 2 MPI processes nest.SetKernelStatus({'resolution': 0.1, 'total_num_virtual_procs': 2}) # Update the SP interval nest.EnableStructuralPlasticity() nest.SetKernelStatus({ 'structural_plasticity_update_interval': 1000., }) growth_curve = { 'growth_curve': "gaussian", 'growth_rate': 0.0001, # Beta (elements/ms) 'continuous': False, 'eta': 0.1, 'eps': 0.7, } structural_p_elements_E = { 'Den_ex': growth_curve, 'Den_in': growth_curve, 'Axon_ex': growth_curve } neuronDict = { 'V_m': -60., 't_ref': 5.0, 'V_reset': -60., 'V_th': -50., 'C_m': 200., 'E_L': -60., 'g_L': 10., 'E_ex': 0., 'E_in': -80., 'tau_syn_ex': 5., 'tau_syn_in': 10., 'I_e': 220. } nest.SetDefaults("iaf_cond_exp", neuronDict) neuronsE = nest.Create('iaf_cond_exp', 1, {'synaptic_elements': structural_p_elements_E}) # synapses synDictE = { 'synapse_model': 'static_synapse', 'weight': 3., 'pre_synaptic_element': 'Axon_ex', 'post_synaptic_element': 'Den_ex' } nest.SetKernelStatus( {'structural_plasticity_synapses': { 'synapseEE': synDictE, }}) try: nest.Simulate(200 * 1000) except Exception: print(sys.exc_info()[0]) self.fail("Exception during simulation")
def __setup(self, sim_time=500.): """Setup the simulation :sim_time: time for each simulation phase :file_prefix: output file prefix :returns: nothing """ nest.ResetKernel() # http://www.nest-simulator.org/sli/setverbosity/ nest.set_verbosity('M_INFO') nest.SetKernelStatus({ 'resolution': self.dt, 'local_num_threads': 1, 'overwrite_files': True }) # Since I've patched NEST, this doesn't actually update connectivity # But, it's required to ensure that synaptic elements are connected # correctly when I form or delete new connections nest.EnableStructuralPlasticity() nest.CopyModel("iaf_cond_exp", "tif_neuronE") nest.SetDefaults('tif_neuronE', self.neuronDict) # do the bits self.__create_neurons() self.__get_optimal_activity() self.__grow_initial_elements() self.__return_activity_to_hom() self.__prepare_hypotheses()
def setUp(self): # test parameter self.rtol = 0.05 # neuron parameters self.neuron_params = {'mu': 1.5, 'sigma': 0.5, 'tau': 5.} # simulation parameters self.simtime = 10000. self.dt = 0.1 self.tstart = 10. * self.neuron_params['tau'] nest.set_verbosity('M_WARNING') nest.ResetKernel() nest.SetKernelStatus({ 'resolution': self.dt, 'use_wfr': False, 'print_time': True }) # set up rate neuron and devices self.rate_neuron_ipn = nest.Create('lin_rate_ipn', params=self.neuron_params) self.rate_neuron_opn = nest.Create('lin_rate_opn', params=self.neuron_params) self.multimeter = nest.Create("multimeter", params={ 'record_from': ['rate', 'noise'], 'interval': self.dt, 'start': self.tstart }) # record rates and noise nest.Connect(self.multimeter, self.rate_neuron_ipn + self.rate_neuron_opn)
def test_spike_multiplicity_pre(self): """Multiplicity of presynpatic spikes is correcly reproduced""" """ TODO add here true spike multiplicity. right now this just sends multiple spikes in the same timestep""" nest.set_verbosity("M_WARNING") nest.ResetKernel() nest.SetKernelStatus({"resolution": 1.}) # set pre and postsynaptic spike times delay = 1. # delay for connections # set the correct real spike times for generators (correcting for # delays) pre_times = [100. - delay, 200. - delay] post_times = [150. - delay] # create parrot neurons and connect spike_generators self.pre_parrot = nest.Create("parrot_neuron", 1) self.post_parrot = nest.Create("parrot_neuron", 1) # create spike_generators with these times pre_spikes = nest.Create("spike_generator", 1, {"spike_times": pre_times}) post_spikes = nest.Create("spike_generator", 1, {"spike_times": post_times}) # connect twice nest.Connect(pre_spikes, self.pre_parrot, syn_spec={"delay": delay}) nest.Connect(pre_spikes, self.pre_parrot, syn_spec={"delay": delay}) nest.Connect(post_spikes, self.post_parrot, syn_spec={"delay": delay}) pars = {'p_fail': 0., 'n_pot_conns': 1, 'tau': 10.} nest.CopyModel('stdp_structpl_synapse_hom', 'testsyn', pars) syn_spec = { "model": "testsyn", "receptor_type": 1, } conn_spec = { "rule": "all_to_all", } # two syns, different number of potential conns nest.Connect(self.pre_parrot, self.post_parrot, syn_spec=syn_spec, conn_spec=conn_spec) syn = nest.GetConnections(source=self.pre_parrot, synapse_model="testsyn") nest.Simulate(150.) syn_defaults = nest.GetDefaults('testsyn') val_exp = 1. / syn_defaults['tau'] * 2. val = nest.GetStatus(syn)[0]['r_jk'][0] self.assertAlmostEqualDetailed( val_exp, val, "Multiple presynaptic spikes not treated properly")
def test_set_verbosity(self): levels = [('M_ALL', 0), ('M_DEBUG', 5), ('M_STATUS', 7), ('M_INFO', 10), ('M_DEPRECATED', 18), ('M_WARNING', 20), ('M_ERROR', 30), ('M_FATAL', 40), ('M_QUIET', 100)] for level, code in levels: nest.set_verbosity(level) verbosity = nest.get_verbosity() self.assertEqual(verbosity, code)
def setUp(self): nest.ResetKernel() nest.set_verbosity('M_ERROR') self.exclude_synapse_model = [ 'stdp_dopamine_synapse', 'stdp_dopamine_synapse_lbl', 'stdp_dopamine_synapse_hpc', 'stdp_dopamine_synapse_hpc_lbl', 'gap_junction', 'gap_junction_lbl' ]
def test_targets(self): nest.ResetKernel() nest.set_verbosity('M_ALL') # Testing with 2 MPI processes nest.SetKernelStatus( { 'resolution': 0.1, 'total_num_virtual_procs': 2 } ) # Update the SP interval nest.EnableStructuralPlasticity() nest.SetStructuralPlasticityStatus({ 'structural_plasticity_update_interval': 100, }) growth_curve = { 'growth_curve': "gaussian", 'growth_rate': 0.0001, # Beta (elements/ms) 'continuous': False, 'eta': 0.1, 'eps': 0.7, } structural_p_elements_E = { 'Den_ex': growth_curve, 'Den_in': growth_curve, 'Axon_ex': growth_curve } neuronDict = {'V_m': -60., 't_ref': 5.0, 'V_reset': -60., 'V_th': -50., 'C_m': 200., 'E_L': -60., 'g_L': 10., 'E_ex': 0., 'E_in': -80., 'tau_syn_ex': 5., 'tau_syn_in': 10., 'I_e': 220.} nest.SetDefaults("iaf_cond_exp", neuronDict) neuronsE = nest.Create('iaf_cond_exp', 1, { 'synaptic_elements': structural_p_elements_E}) # synapses synDictE = {'model': 'static_synapse', 'weight': 3., 'pre_synaptic_element': 'Axon_ex', 'post_synaptic_element': 'Den_ex'} nest.SetStructuralPlasticityStatus({ 'structural_plasticity_synapses': { 'synapseEE': synDictE, } }) try: nest.Simulate(200 * 1000) except: print(sys.exc_info()[0]) self.fail("Exception during simulation")
def __init__(self, actor, num_input=8, num_output=2, neuron_labels: List[str] = []): """ Create and connect a nest network :param initial: :param num_input: :param num_output: :return: """ self.actor = actor # note that the order does not reflect the internal nest order self.neur_ids_parrot = [] self.neur_ids_out: List[int] = [] self.neur_ids_core: np.ndarray # the neurons which are used for wiring (except spike generators) self.neur_ids_ex = [] # includes input self.neur_ids_hidden_in = [ ] # ids of the free (not in population) in hidden layer self.neur_ids_hidden_ex = [ ] # ids of the free (not in population) in hidden layer # store connected pairs (source, target) for reconnecting, order different from nest self.conns: np.ndarray self.conns_in: np.ndarray self.conns_ex: np.ndarray # redundance in nest format/indexing self.conns_nest: SynapseCollection = [] # contains all stdp synapses self.conns_nest_ex: SynapseCollection = [] self.conns_nest_in: SynapseCollection = [] self.populations_nest: List[NodeCollection] = [] self.neurons_nest_ex: NodeCollection = [] self.neurons_nest_in: NodeCollection = [] self.neurons_nest: NodeCollection = [] self.neurons_input: NodeCollection = [] self.cycles_to_reconnect = 2 # counts the cycles till a reconnect (structural plasticity) happens self.num_input = num_input self.num_output = num_output self.last_num_spikes = [ ] # record the number of spikes in this trial to only get new spikes for each out population self.multimeter = None self.synapsecontingent = 1 self.spike_detector = None self.spike_detectors_populations = [] # log self.lastweights: Weightstorage = [ ] # only stores last entries for restoring in next episode, order like nest connections self.neuron_labels: List[str] = neuron_labels # after initalizing fields construct nest.set_verbosity("M_WARNING") self.rebuild(True) print("Training " + str(len(self.conns_nest)) + " weights")
def test_rate_copy_model(self): # neuron parameters neuron_params = {'tau': 5., 'sigma': 0.} drive = 1.5 weight = 0.5 # simulation parameters simtime = 100. dt = 0.001 nest.set_verbosity('M_WARNING') nest.ResetKernel() nest.SetKernelStatus( {'resolution': dt, 'use_wfr': True, 'print_time': False}) # set up rate neuron network rate_neuron_drive = nest.Create( 'lin_rate_ipn', params={'mu': drive, 'sigma': 0.}) rate_neuron_1 = nest.Create( 'lin_rate_ipn', params=neuron_params) rate_neuron_2 = nest.Create( 'lin_rate_ipn', params=neuron_params) multimeter = nest.Create( 'multimeter', params={ 'record_from': ['rate'], 'precision': 10, 'interval': dt}) # create new connection nest.CopyModel('rate_connection_instantaneous', 'rate_connection_new') # record rates and connect neurons neurons = rate_neuron_1 + rate_neuron_2 nest.Connect( multimeter, neurons, 'all_to_all', {'delay': 10.}) nest.Connect(rate_neuron_drive, rate_neuron_1, 'all_to_all', {'model': 'rate_connection_instantaneous', 'weight': weight}) nest.Connect(rate_neuron_drive, rate_neuron_2, 'all_to_all', {'model': 'rate_connection_new', 'weight': weight}) # simulate nest.Simulate(simtime) # make sure rates are identical events = nest.GetStatus(multimeter)[0]['events'] senders = events['senders'] rate_1 = np.array(events['rate'][np.where(senders == rate_neuron_1)]) rate_2 = np.array(events['rate'][np.where(senders == rate_neuron_2)]) assert(np.sum(np.abs(rate_2 - rate_1)) < 1e-12)
def __nest_init(self): nest.ResetKernel() # nest.SetKernelStatus({"local_num_threads": 4}) nest.set_verbosity('M_ERROR') nest.CopyModel("iaf_psc_alpha", "input_neuron", params={"V_th": -68., "t_ref": 20.}) nest.CopyModel("iaf_psc_alpha", "output_neuron", params={"V_th": -67., "t_ref": 300.}) # 具体参数待调整 nest.CopyModel("iaf_psc_alpha", "memory_neuron") nest.CopyModel("iaf_psc_alpha", "wn_neuron")
def setUpNetwork(self, conn_dict=None, syn_dict=None, N1=None, N2=None): if N1 is None: N1 = self.N1 if N2 is None: N2 = self.N2 self.pop1 = nest.Create('iaf_psc_alpha', N1) self.pop2 = nest.Create('iaf_psc_alpha', N2) nest.set_verbosity('M_FATAL') nest.Connect(self.pop1, self.pop2, conn_dict, syn_dict)
def _nest_start_(n_cores=n_cores): nest.ResetKernel() nest.SetKernelStatus({ "resolution": dt, "print_time": True, "overwrite_files": True, 'local_num_threads': n_cores }) nest.set_verbosity("M_WARNING")
def build_and_connect_nodes(self, sigma, theta): """ sets up an erfc neuron and spin detector. """ nest.set_verbosity('M_WARNING') nest.ResetKernel() self.neuron = nest.Create('erfc_neuron', 1, {'sigma': sigma, 'theta': theta}) self.detector = nest.Create('spin_detector', 1) nest.Connect(self.neuron, self.detector)
def do_the_nest_simulation(self): """ This function is where calls to NEST reside. Returns the generated pre- and post spike sequences and the resulting weight established by STDP. """ nest.set_verbosity('M_WARNING') nest.ResetKernel() nest.resolution = self.resolution presynaptic_neuron, postsynaptic_neuron = nest.Create( "parrot_neuron", 2, params=self.neuron_parameters) generators = nest.Create( "poisson_generator", 2, params=({"rate": self.presynaptic_firing_rate, "stop": (self.simulation_duration - self.hardcoded_trains_length)}, {"rate": self.postsynaptic_firing_rate, "stop": (self.simulation_duration - self.hardcoded_trains_length)})) presynaptic_generator = generators[0] postsynaptic_generator = generators[1] spike_senders = nest.Create( "spike_generator", 2, params=({"spike_times": self.hardcoded_pre_times + self.simulation_duration - self.hardcoded_trains_length}, {"spike_times": self.hardcoded_post_times + self.simulation_duration - self.hardcoded_trains_length}) ) pre_spike_generator = spike_senders[0] post_spike_generator = spike_senders[1] # The recorder is to save the randomly generated spike trains. spike_recorder = nest.Create("spike_recorder") nest.Connect(presynaptic_generator + pre_spike_generator, presynaptic_neuron, syn_spec={"synapse_model": "static_synapse"}) nest.Connect(postsynaptic_generator + post_spike_generator, postsynaptic_neuron, syn_spec={"synapse_model": "static_synapse"}) nest.Connect(presynaptic_neuron + postsynaptic_neuron, spike_recorder, syn_spec={"synapse_model": "static_synapse"}) # The synapse of interest itself nest.Connect(presynaptic_neuron, postsynaptic_neuron, syn_spec=self.synapse_parameters) plastic_synapse_of_interest = nest.GetConnections(synapse_model=self.synapse_parameters["synapse_model"]) nest.Simulate(self.simulation_duration) all_spikes = nest.GetStatus(spike_recorder, keys='events')[0] pre_spikes = all_spikes['times'][all_spikes['senders'] == presynaptic_neuron.tolist()[0]] post_spikes = all_spikes['times'][all_spikes['senders'] == postsynaptic_neuron.tolist()[0]] weight = nest.GetStatus(plastic_synapse_of_interest, keys='weight')[0] return (pre_spikes, post_spikes, weight)
def setUpNetwork(self, conn_dict=None, syn_dict=None, N1=None, N2=None): if N1 == None: N1 = self.N1 if N2 == None: N2 = self.N2 self.pop1 = nest.Create('iaf_neuron', N1) self.pop2 = nest.Create('iaf_neuron', N2) nest.set_verbosity('M_FATAL') nest.Connect(self.pop1, self.pop2, conn_dict, syn_dict)
def run_protocol(self, dt): """Set up a network with pre-post spike pairings with t_post - t_pre = dt""" nest.set_verbosity("M_WARNING") nest.ResetKernel() # set pre and postsynaptic spike times delay = 1. # delay for connections dspike = 100. # ISI # set the correct real spike times for generators (correcting for delays) pre_times = [100., 100. + dspike] post_times = [k+dt for k in pre_times] # create spike_generators with these times pre_spikes = nest.Create("spike_generator", 1, {"spike_times": pre_times}) post_spikes = nest.Create("spike_generator", 1, {"spike_times": post_times}) # create parrot neurons and connect spike_generators pre_parrot = nest.Create("parrot_neuron", 1) post_parrot = nest.Create("parrot_neuron", 1) nest.Connect(pre_spikes, pre_parrot, syn_spec={"delay": delay}) nest.Connect(post_spikes, post_parrot, syn_spec={"delay": delay}) # create spike detector spikes = nest.Create("spike_detector") nest.Connect(pre_parrot, spikes) nest.Connect(post_parrot, spikes) # connect both parrot neurons with a stdp synapse onto port 1 # thereby spikes transmitted through the stdp connection are # not repeated postsynaptically. syn_spec = { "model": "stdp_synapse", "receptor_type": 1, # set receptor 1 postsynaptically, to not generate extra spikes } conn_spec = { "rule": "one_to_one", } nest.Connect(pre_parrot, post_parrot, syn_spec=syn_spec, conn_spec=conn_spec) # get STDP synapse and weight before protocol syn = nest.GetConnections(source=pre_parrot, synapse_model="stdp_synapse") syn_status = nest.GetStatus(syn)[0] w_pre = syn_status['weight'] last_time = max(pre_times[-1], post_times[-1]) nest.Simulate(last_time + 2 * delay) # get weight post protocol syn_status = nest.GetStatus(syn)[0] w_post = syn_status['weight'] return w_pre, w_post
def create_network(network_obj, weight, JENoise, noise_rate, resolution=0.1, verbose=True, print_time=False): ncells = network_obj['ncells'] ncons = network_obj['ncons'] if verbose: print "Constructing NEST network of %i nodes and %i connections." % ( ncells, ncons) nest.ResetKernel() nthreads = cpu_count() if verbose: nest.set_verbosity('M_INFO') else: nest.set_verbosity('M_ERROR') nest.SetKernelStatus(dict(local_num_threads=nthreads, resolution=0.1, print_time=print_time, overwrite_files=True)) neuron_params = dict(C_m=1.0, tau_m=20.0, t_ref=2.0, E_L=0.0, V_th=20.0) nest.SetDefaults("iaf_neuron", neuron_params) neuronsE = nest.Create("iaf_neuron", n=ncells) # save GID offset of first neuron - this has the advantage that the output # later will be independent of the point at which the neurons were created GIDoffset = neuronsE[0] espikes = nest.Create("spike_detector") nest.ConvergentConnect(neuronsE, espikes) noise = nest.Create("poisson_generator", n=1, params=dict(rate=noise_rate)) # Warning: delay is overwritten later if weights are given! nest.SetDefaults("tsodyks_synapse", dict(delay=1.5, tau_rec=500., tau_fac=0., U=0.3)) nest.CopyModel("tsodyks_synapse", "exc", dict(weight=weight)) nest.CopyModel("static_synapse", "poisson", dict(weight=JENoise)) # every neuron gets the same noisy input??? nest.DivergentConnect(noise, neuronsE, model="poisson") for node in network_obj['nodes']: presyn_index = node['id'] postsyn_indices = node['connectedTo'] nest.DivergentConnect( [neuronsE[presyn_index]], # from, list of len 1 [neuronsE[ii] for ii in postsyn_indices], # to, list model='exc', # synapse model ) return ncells, ncons, neuronsE, espikes, noise, GIDoffset
def nestSetup(self): """Common nest stuff.""" # NEST stuff nest.ResetKernel() nest.set_verbosity('M_INFO') nest.SetKernelStatus( { 'resolution': self.dt } )
def setUp(self): nest.ResetKernel() nest.set_verbosity("M_ERROR") self.exclude_synapse_model = [ "stdp_dopamine_synapse", "stdp_dopamine_synapse_lbl", "stdp_dopamine_synapse_hpc", "stdp_dopamine_synapse_hpc_lbl", "gap_junction", "gap_junction_lbl", ]
def test_ParrotNeuronIncomingMultiplicity(self): """ Check parrot_neuron heeds multiplicity information in incoming spikes. This test relies on the fact that poisson_generator transmits multiple spikes during a time step using multiplicity, and that these spikes are delivered directly, i.e., without multiplicity- unrolling in send_remote(). We create a high-rate poisson_generator. If parrot_neuron ignored multiplicity, it would only transmit one spike per time step. We chain two parrot_neurons to check against any loss. Note: Even though we test parrot_neuron_ps, we drive it with the plain poisson_generator, since only that generator uses multiplicity. """ # set up source spike generator, as well as parrot neurons h = 0.1 # ms rate = 1000000. # spikes / s delay = 1. # ms t_base = 1000. # ms t_sim = t_base + 3 * delay # after t_sim, spikes from t_base arrived spikes_expected = rate * t_base / 1000. spikes_std = math.sqrt(spikes_expected) # if the test is to be meaningful we must expect signficantly more # spikes than time steps assert spikes_expected - 3 * spikes_std > 10. * t_sim / h, \ "Internal inconsistency: too few spikes." nest.set_verbosity('M_WARNING') nest.ResetKernel() nest.SetKernelStatus({ 'resolution': h, 'grng_seed': 123, 'rng_seeds': [456] }) source = nest.Create('poisson_generator', params={'rate': rate}) parrots = nest.Create('parrot_neuron_ps', 2) detect = nest.Create('spike_detector', params={'precise_times': True}) nest.Connect(source, parrots[:1], syn_spec={'delay': delay}) nest.Connect(parrots[:1], parrots[1:], syn_spec={'delay': delay}) nest.Connect(parrots[1:], detect) nest.Simulate(_round_up(t_sim)) n_spikes = nest.GetStatus(detect)[0]['n_events'] assert n_spikes > spikes_expected - 3 * spikes_std, \ "parrot_neuron loses spikes." assert n_spikes < spikes_expected + 3 * spikes_std, \ "parrot_neuron adds spikes."
def single_neuron_task(spike_times, sim_duration): ''' Task Manifest Version: 1 Full Name: single_neuron_task Caption: Single neuron Author: NEST Developers Description: | This script simulates a neuron stimulated by spikes with predefined times and creates a plot of the membrane potential trace. Simulator: NEST (http://nest-simulator.org) Categories: - NEST Compatible_queues: ['cscs_viz', 'cscs_bgq', 'epfl_viz'] Accepts: spike_times: type: list(double) description: Spike times in ms at which the neuron is stimulated (e.g., [10, 50]). sim_duration: type: double description: Simulation duration in ms (e.g., 100). Returns: res: image/png ''' nest.set_verbosity('M_WARNING') # reduce NEST output nest.ResetKernel() # reset simulation kernel # create LIF neuron with exponential synaptic currents neuron = nest.Create('iaf_psc_exp') # create a voltmeter voltmeter = nest.Create('voltmeter', params={'interval': 0.1}) # create a spike generator spikegenerator = nest.Create('spike_generator') # ... and let it spike at predefined times nest.SetStatus(spikegenerator, {'spike_times': spike_times}) # connect spike generator and voltmeter to the neuron nest.Connect(spikegenerator, neuron) nest.Connect(voltmeter, neuron) # run simulation for sim_duration nest.Simulate(sim_duration) # read out recording time and voltage from voltmeter times = nest.GetStatus(voltmeter)[0]['events']['times'] voltage = nest.GetStatus(voltmeter)[0]['events']['V_m'] # plot results plt.plot(times, voltage) plt.xlabel('Time (ms)') plt.ylabel('Membrane potential (mV)') filename = 'single_neuron_task.png' plt.savefig(filename, dpi=300) return single_neuron_task.task.uri.save_file(mime_type='image/png', src_path=filename, dst_path=filename)
def prepare_simulation(self): nest.ResetKernel() nest.set_verbosity('M_ERROR') ''' We set global kernel parameters. Here we define the resolution for the simulation, which is also the time resolution for the update of the synaptic elements. ''' nest.SetKernelStatus( { 'resolution': self.dt } ) ''' Set Structural Plasticity synaptic update interval which is how often the connectivity will be updated inside the network. It is important to notice that synaptic elements and connections change on different time scales. ''' nest.SetStructuralPlasticityStatus({ 'structural_plasticity_update_interval': self.update_interval, }) ''' Now we define Structural Plasticity synapses. In this example we create two synapse models, one for excitatory and one for inhibitory synapses. Then we define that excitatory synapses can only be created between a pre synaptic element called 'Axon_ex' and a post synaptic element called Den_ex. In a similar manner, synaptic elements for inhibitory synapses are defined. ''' nest.CopyModel('static_synapse', 'synapse_ex') nest.SetDefaults('synapse_ex', {'weight': self.psc_e, 'delay': 1.0}) nest.CopyModel('static_synapse', 'synapse_in') nest.SetDefaults('synapse_in', {'weight': self.psc_i, 'delay': 1.0}) nest.SetStructuralPlasticityStatus({ 'structural_plasticity_synapses': { 'synapse_ex': { 'model': 'synapse_ex', 'post_synaptic_element': 'Den_ex', 'pre_synaptic_element': 'Axon_ex', }, 'synapse_in': { 'model': 'synapse_in', 'post_synaptic_element': 'Den_in', 'pre_synaptic_element': 'Axon_in', }, } })
def setUp(self): nest.set_verbosity('M_WARNING') nest.ResetKernel() # set up source spike generator, as well as parrot neurons self.spike_time = 1. self.delay = .2 self.source = nest.Create("spike_generator", 1, {"spike_times": [self.spike_time]}) self.parrot = nest.Create('parrot_neuron') self.spikes = nest.Create("spike_detector") # record source and parrot spikes nest.Connect(self.source, self.spikes) nest.Connect(self.parrot, self.spikes)
def compute_transfer(self, i_mean=(400.0, 900.0, 50.0), i_std=(0.0, 600.0, 50.0)): ''' We loop through all possible combinations of (I_mean, I_sigma) and measure the output rate of the neuron. ''' self.i_range = numpy.arange(*i_mean) self.std_range = numpy.arange(*i_std) self.rate = numpy.zeros((self.i_range.size, self.std_range.size)) nest.set_verbosity('M_WARNING') for n, i in enumerate(self.i_range): print('I = {0}'.format(i)) for m, std in enumerate(self.std_range): self.rate[n, m] = self.output_rate(i, std)
def test_set_verbosity(self): levels = [('M_ALL', 0), ('M_DEBUG', 5), ('M_STATUS', 7), ('M_INFO', 10), ('M_DEPRECATED', 18), ('M_WARNING', 20), ('M_ERROR', 30), ('M_FATAL', 40), ('M_QUIET', 100) ] for level, code in levels: nest.set_verbosity(level) verbosity = nest.get_verbosity() self.assertEqual(verbosity, code)
def test_SynapseFunctionWithAeifModel(self): """Ensure that spikes are properly processed""" nest.set_verbosity('M_WARNING') nest.ResetKernel() # Create neurons and devices nrns = nest.Create('aeif_psc_delta_clopath', 2, {'V_m': -70.6}) prrt_nrn = nest.Create('parrot_neuron', 1) spike_times = [10.0] sg = nest.Create('spike_generator', 1, {'spike_times': spike_times}) mm = nest.Create('multimeter', params={ 'record_from': ['V_m'], 'interval': 1.0}) nest.Connect(sg, prrt_nrn) nest.Connect(mm, nrns) # Connect one neuron with static connection conn_dict = {'rule': 'all_to_all'} static_syn_dict = {'model': 'static_synapse', 'weight': 2.0, 'delay': 1.0} nest.Connect(prrt_nrn, nrns[0:1], conn_dict, static_syn_dict) # Connect one neuron with Clopath stdp connection cl_stdp_syn_dict = {'model': 'clopath_synapse', 'weight': 2.0, 'delay': 1.0} nest.Connect(prrt_nrn, nrns[1:2], conn_dict, cl_stdp_syn_dict) # Simulation nest.Simulate(20.) # Evaluation data = nest.GetStatus(mm) senders = data[0]['events']['senders'] voltages = data[0]['events']['V_m'] vm1 = voltages[np.where(senders == 1)] vm2 = voltages[np.where(senders == 2)] # Compare results for static synapse and Clopath stdp synapse self.assertTrue(np.allclose(vm1, vm2, rtol=1e-5)) # Check that a spike with weight 2.0 is processes properly # in the aeif_psc_delta_clopath model self.assertTrue(np.isclose(vm2[11]-vm2[10], 2.0, rtol=1e-5))
def setUp(self): nest.ResetKernel() nest.set_verbosity('M_ERROR') self.num_procs = 1 if mpi_test: self.comm = MPI.COMM_WORLD self.rank = self.comm.Get_rank() assert(nest.Rank() == self.rank) self.num_procs = 2 self.exclude_synapse_model = [ 'stdp_dopamine_synapse', 'stdp_dopamine_synapse_lbl', 'stdp_dopamine_synapse_hpc', 'stdp_dopamine_synapse_hpc_lbl', 'gap_junction', 'gap_junction_lbl', ]
def setUp(self): nest.set_verbosity('M_WARNING') nest.ResetKernel() # setting up the neuron and the generators self.neuron = nest.Create('iaf_psc_alpha', params={'V_reset': -65.0}) self.t_origin = 5.0 self.t_start = 2.5 self.t_stop = 40.0 self.t_next = 25.0 self.i_amp = 500.0 self.i_off = 50.0 self.ac = nest.Create('ac_generator', 1, params={'amplitude': self.i_amp, 'offset': self.i_off, 'frequency': 50.0, 'phase': 45.0, 'origin': self.t_origin, 'start': self.t_start, 'stop': self.t_stop}) nest.Connect(self.ac, self.neuron) self.dc = nest.Create('dc_generator', 1, params={'amplitude': self.i_amp, 'origin': self.t_origin, 'start': self.t_start, 'stop': self.t_stop}) nest.Connect(self.dc, self.neuron) times = [self.t_start, self.t_next] currents = [self.i_amp / 4, self.i_amp / 2] params = {'amplitude_times': times, 'amplitude_values': currents, 'origin': self.t_origin, 'start': self.t_start, 'stop': self.t_stop} self.step = nest.Create("step_current_generator", 1, params) nest.Connect(self.step, self.neuron) self.noise = nest.Create('noise_generator', 1, params={'mean': self.i_amp, 'std': 0.0, 'dt': 0.1, 'std_mod': 0.0, 'phase': 45.0, 'frequency': 50.0, 'origin': self.t_origin, 'start': self.t_start, 'stop': self.t_stop}) nest.Connect(self.noise, self.neuron)
def setUp(self): nest.ResetKernel() nest.set_verbosity('M_INFO') self.exclude_synapse_model = [ 'stdp_dopamine_synapse', 'stdp_dopamine_synapse_lbl', 'stdp_dopamine_synapse_hpc', 'stdp_dopamine_synapse_hpc_lbl', 'gap_junction', 'gap_junction_lbl', 'diffusion_connection', 'diffusion_connection_lbl', 'rate_connection_instantaneous', 'rate_connection_instantaneous_lbl', 'rate_connection_delayed', 'rate_connection_delayed_lbl' ]
def test_ParrotNeuronIncomingMultiplicity(self): """ Check parrot_neuron heeds multiplicity information in incoming spikes. This test relies on the fact that poisson_generator transmits multiple spikes during a time step using multiplicity, and that these spikes are delivered directly, i.e., without multiplicity- unrolling in send_remote(). We create a high-rate poisson_generator. If parrot_neuron ignored multiplicity, it would only transmit one spike per time step. We chain two parrot_neurons to check against any loss. """ # set up source spike generator, as well as parrot neurons h = 0.1 # ms rate = 1000000.0 # spikes / s delay = 1.0 # ms t_base = 1000.0 # ms t_sim = t_base + 3 * delay # after t_sim, spikes from t_base arrived spikes_expected = rate * t_base / 1000.0 spikes_std = math.sqrt(spikes_expected) # if the test is to be meaningful we must expect signficantly more # spikes than time steps assert spikes_expected - 3 * spikes_std > 10.0 * t_sim / h, "Internal inconsistency: too few spikes." nest.set_verbosity("M_WARNING") nest.ResetKernel() nest.SetKernelStatus({"resolution": h, "grng_seed": 123, "rng_seeds": [456]}) source = nest.Create("poisson_generator", params={"rate": rate}) parrots = nest.Create("parrot_neuron", 2) detect = nest.Create("spike_detector") nest.Connect(source, parrots[:1], syn_spec={"delay": delay}) nest.Connect(parrots[:1], parrots[1:], syn_spec={"delay": delay}) nest.Connect(parrots[1:], detect) nest.Simulate(t_sim) n_spikes = nest.GetStatus(detect)[0]["n_events"] assert n_spikes > spikes_expected - 3 * spikes_std, "parrot_neuron loses spikes." assert n_spikes < spikes_expected + 3 * spikes_std, "parrot_neuron adds spikes."