def test_terub_stn(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_stn.nestml"))) target_path = "target" module_name = 'terub_stn_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_stn_nestml" dt = 0.01 t_simulation = 1000.0 nest.SetKernelStatus({"resolution": dt}) neurons = nest.Create(model, 2) parameters = nest.GetDefaults(model) if 0: for i in parameters: print(i, parameters[i]) # nest.SetStatus(neurons, {'I_e': 0.0}) for neuron in neurons: nest.SetStatus([neuron], {'V_m': -65.0 + rand() * 10.0 - 5.0}) nest.SetStatus([neuron], {'I_e': 0.0 + rand() * 10.0 - 5.0}) nest.Connect([neurons[0]], [neurons[1]]) multimeter = nest.Create("multimeter", 2) nest.SetStatus(multimeter, { "withtime": True, "record_from": ["V_m"], "interval": dt }) spikedetector = nest.Create("spike_detector", params={ "withgid": True, "withtime": True }) nest.Connect(multimeter, neurons, "one_to_one") nest.Connect(neurons, spikedetector) nest.Simulate(t_simulation) dmm = nest.GetStatus(multimeter, keys='events')[0] Voltages = dmm["V_m"] tv = dmm["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) for i in range(2): 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)) 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].legend() # ax[0].set_ylim(-100, 50) # for i in ts: # ax[0].axvline(x=i, lw=1., ls="--", color="gray") plt.savefig("resources/terub_stn.png")
def run_post_trace_test_nest_(self, show_all_nest_trace_samples=False): nest.set_verbosity("M_WARNING") nest.ResetKernel() nest.SetKernelStatus({'resolution': self.resolution_}) wr = nest.Create('weight_recorder') nest.CopyModel("stdp_synapse", "stdp_synapse_rec", { "weight_recorder": wr, "weight": 1. }) # create spike_generators with these times pre_sg_ps = nest.Create("spike_generator", params={ "spike_times": self.pre_spike_times_, 'precise_times': True }) post_sg_ps = nest.Create("spike_generator", params={ "spike_times": self.post_spike_times_, 'precise_times': True }) # create parrot neurons and connect spike_generators pre_parrot_ps = nest.Create("parrot_neuron_ps") post_parrot_ps = nest.Create("parrot_neuron_ps", params={"tau_minus": self.tau_minus_}) nest.Connect(pre_sg_ps, pre_parrot_ps, syn_spec={"delay": self.delay_}) nest.Connect(post_sg_ps, post_parrot_ps, syn_spec={"delay": self.delay_}) # create spike recorder --- debugging only spikes = nest.Create("spike_recorder") nest.Connect(pre_parrot_ps + post_parrot_ps, spikes) # connect both parrot neurons with a stdp synapse onto port 1 # thereby spikes transmitted through the stdp connection are # not repeated postsynaptically. nest.Connect(pre_parrot_ps, post_parrot_ps, syn_spec={ 'synapse_model': 'stdp_synapse_rec', 'receptor_type': 1, 'delay': self.delay_ }) # get STDP synapse syn_ps = nest.GetConnections(source=pre_parrot_ps, synapse_model="stdp_synapse_rec") print("[py] Total simulation time: " + str(self.sim_time_) + " ms") n_steps = int(np.ceil(self.sim_time_ / self.delay_)) trace_nest = [] trace_nest_t = [] t = nest.GetKernelStatus("time") trace_nest_t.append(t) post_tr = nest.GetStatus(post_parrot_ps)[0]['post_trace'] trace_nest.append(post_tr) for step in range(n_steps): print("\n[py] simulating for " + str(self.delay_) + " ms") nest.Simulate(self.delay_) t = nest.GetKernelStatus("time") nearby_pre_spike = np.any( np.abs(t - np.array(self.pre_spike_times_) - self.delay_) < self.resolution_ / 2.) if show_all_nest_trace_samples or nearby_pre_spike: trace_nest_t.append(t) post_tr = nest.GetStatus(post_parrot_ps)[0]['post_trace'] trace_nest.append(post_tr) print("[py] Received NEST trace: " + str(post_tr) + " at time t = " + str(t)) return trace_nest_t, trace_nest
fig = plt.figure(facecolor=face, edgecolor=edge, figsize=fig_size) dt = 1e-3 sigma = [0.0, 0.1, 0.2] dE = [0.0, 0.004, 0.008] T = numpy.linspace(0, 200, int(200/dt) - 1) for i in range(9): c = i % 3 r = int(i / 3) D1, D2, mm = build_network(sigma[r], dt) ########################################################################### # First using build_network the network is build and the handles of # the decision units and the multimeter are stored in `D1`, `D2` and `mm` nest.Simulate(100.0) D1.mu = 1. + dE[c] D2.mu = 1. - dE[c] nest.Simulate(100.0) ######################################################################## # The network is simulated using ``Simulate``, which takes the desired # simulation time in milliseconds and advances the network state by # this amount of time. After an initial period in the absence of evidence # for either decision, evidence is given by changing the state of each senders = mm.get('events', 'senders') voltages = mm.get('events', 'rate') ######################################################################## # The activity values ('voltages') are read out by the multimeter
def simulate(T): nest.Simulate(float(T))
# conn = nest.GetConnections([neurons[i]]) # print nest.GetStatus(conn, ['source', 'target']) nest.Connect(multimeters, neurons, 'one_to_one') nest.Connect(neurons, spikedetector) # print nest.GetDefaults('iaf_cond_alpha')['recordables'] params = nest.GetDefaults('iaf_psc_alpha') # print params # for i, j in zip(params.keys(), params.values()): # print i, j # print("iaf_cond_alpha recordables: {0}".format( # nest.GetDefaults("iaf_cond_alpha")["recordables"])) nest.Simulate(200.0) # time in ms fig = pl.figure(figsize=(6, 5)) gs1 = gridspec.GridSpec(4, 1, hspace=0.0) axs = [] axs.append(fig.add_subplot(gs1[:3])) axs.append(fig.add_subplot(gs1[3], sharex=axs[0])) # fig, ax = pl.subplots(2, figsize=(6, 5), sharex=True) for i in range(N): dmm = nest.GetStatus(multimeters)[i] Vms = dmm["events"]["V_m"] gex = dmm["events"][""] ts = dmm["events"]["times"] axs[0].plot(ts, Vms)
############################################################################### # We connect devices and neurons and start the simulation. for indx in range(len(pg)): nest.Connect(pg[indx], n, syn_spec={ 'weight': float(J[indx]), 'delay': 0.1 }) nest.Connect(pg[indx], n_free, syn_spec={'weight': J[indx]}) nest.Connect(vm, n_free) nest.Connect(n, sr) nest.Simulate(simtime) ############################################################################### # Here we read out the recorded membrane potential. The first 500 steps are # omitted so initial transients do not perturb our results. We then print the # results from theory and simulation. v_free = vm.get('events', 'V_m')[500:-1] print('mean membrane potential (actual / calculated): {0} / {1}'.format( np.mean(v_free), mu * 1000)) print('variance (actual / calculated): {0} / {1}'.format( np.var(v_free), sigma2 * 1e6)) print('firing rate (actual / calculated): {0} / {1}'.format( nest.GetStatus(sr, 'n_events')[0] / (n_neurons * simtime * ms), r))
def deltaW(synapse_type, synapse_params, delta_t_range, weights, delay): """Simulate weight change of a given synapse type for a range of weights and presynaptic spike times. Parameters ---------- synapse_type : str Type of synapse, must specify a valid NEST synapse model. synapse_params : dict Parameter of the synapse. Note: receptor_type has to be set to 1. delta_t_range : numpy.ndarray or list List or array of presynaptic spike times weights : numpy.ndarray or list List or array of (initial) synaptic weights delay : float Delay of the synapse Returns ------- tuple of lists Tuple with first item = delta_t_range and second item = change of synaptic weight induced by plasiticty """ post_spike = 250.0 deltaw = np.zeros((weights.size, delta_t_range.size)) for i, weight in enumerate(weights): for j, delta_t in enumerate(delta_t_range): nest.ResetKernel() nest.SetKernelStatus({ "total_num_virtual_procs": 1, "resolution": 0.1 }) nest.set_verbosity("M_FATAL") synapse_params["weight"] = weight nest.SetDefaults(synapse_type, synapse_params) spike_generator_pre = nest.Create("spike_generator") spike_generator_post = nest.Create("spike_generator") parrot_pre = nest.Create("parrot_neuron") parrot_post = nest.Create( "parrot_neuron", params={"tau_minus": synapse_params["tau_plus"]}) nest.Connect(spike_generator_pre, parrot_pre) nest.Connect(spike_generator_post, parrot_post) nest.Connect(parrot_pre, parrot_post, syn_spec={"synapse_model": synapse_type}) pre_spike_times = [post_spike - delta_t, post_spike + 1000.0] post_spike_times = [post_spike] nest.SetStatus(spike_generator_pre, {"spike_times": pre_spike_times}) nest.SetStatus(spike_generator_post, {"spike_times": post_spike_times}) nest.Simulate(pre_spike_times[-1] + 10.0) new_weight = nest.GetStatus( nest.GetConnections(parrot_pre, parrot_post), "weight")[0] deltaw[i][j] = new_weight - synapse_params["weight"] return delta_t_range, deltaw
def _run(self): logger.info("Starting simulation") nest.Simulate(s_to_ms(total_simulation_time))
def test_terub_stn(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", "terub_stn.nestml"))) target_path = "target" module_name = "terub_stn_module" suffix = "_nestml" generate_nest_target(input_path, target_path=target_path, logging_level="INFO", suffix=suffix, module_name=module_name) nest.Install(module_name) model = "terub_stn_nestml" dt = 0.01 t_simulation = 1000.0 nest.SetKernelStatus({"resolution": dt}) neuron = nest.Create(model) parameters = nest.GetDefaults(model) neuron.set({"I_e": 10.0}) multimeter = nest.Create("multimeter") multimeter.set({"record_from": ["V_m"], "interval": dt}) spike_recorder = nest.Create("spike_recorder") nest.Connect(multimeter, neuron) nest.Connect(neuron, spike_recorder) nest.Simulate(t_simulation) dmm = nest.GetStatus(multimeter)[0] 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 - 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("terub_stn.png")
def test_setstatus_combinations(self, dt=0.1): sg_01 = nest.Create('spike_generator', 1, {'spike_times': [10.]}) sg_02 = nest.Create('spike_generator', 1, {'spike_times': [15.]}) sg_11 = nest.Create('spike_generator', 1, {'spike_times': [10.]}) sg_12 = nest.Create('spike_generator', 1, {'spike_times': [15.]}) # set status with individual calls for each receptor and compartment n_neat_0 = nest.Create('cm_default') n_neat_0.compartments = [{ "parent_idx": -1, "params": SP }, { "parent_idx": 0, "params": DP[0] }] n_neat_0.receptors = [{ "comp_idx": 0, "receptor_type": "GABA" }, { "comp_idx": 1, "receptor_type": "AMPA" }] nest.Connect(sg_01, n_neat_0, syn_spec={ 'synapse_model': 'static_synapse', 'weight': .1, 'receptor_type': 0 }) nest.Connect(sg_02, n_neat_0, syn_spec={ 'synapse_model': 'static_synapse', 'weight': .1, 'receptor_type': 1 }) # set status with single call n_neat_1 = nest.Create('cm_default') nest.SetStatus( n_neat_1, { "compartments": [{ "parent_idx": -1, "params": SP }, { "parent_idx": 0, "params": DP[0] }], "receptors": [{ "comp_idx": 0, "receptor_type": "GABA" }, { "comp_idx": 1, "receptor_type": "AMPA" }] }) nest.Connect(sg_11, n_neat_1, syn_spec={ 'synapse_model': 'static_synapse', 'weight': .1, 'receptor_type': 0 }) nest.Connect(sg_12, n_neat_1, syn_spec={ 'synapse_model': 'static_synapse', 'weight': .1, 'receptor_type': 1 }) m_neat_0 = nest.Create('multimeter', 1, { 'record_from': ['v_comp0'], 'interval': dt }) nest.Connect(m_neat_0, n_neat_0) m_neat_1 = nest.Create('multimeter', 1, { 'record_from': ['v_comp0'], 'interval': dt }) nest.Connect(m_neat_1, n_neat_1) nest.Simulate(100.) events_neat_0 = nest.GetStatus(m_neat_0, 'events')[0] events_neat_1 = nest.GetStatus(m_neat_1, 'events')[0] self.assertTrue( np.allclose(events_neat_0['v_comp0'], events_neat_1['v_comp0']))
LLBN, EBN, IBN, OPN = saccade_generator_single_side() # Create and connect devices stimuli = nest.Create('dc_generator', num_stims) nest.SetStatus(stimuli, stim_dict) spike_detector = nest.Create('spike_detector', 1) nest.Connect(stimuli, LLBN, 'all_to_all') nest.Connect(EBN, spike_detector) spike_detector = nest.Create('spike_detector', 1) names = ['LLBN', 'EBN', 'IBN', 'OPN'] nest.Connect(EBN, spike_detector) nest.Simulate(stim_times[-1] + 400.) # Evaluate performance of spiking saccade generator spike_times = nest.GetStatus(spike_detector, 'events')[0]['times'] saccadic_sizes = saccadic_size_single_side(stim_times, spike_times) error = stim_sizes - saccadic_sizes mse = np.sqrt((error**2).mean()) # Plot results plt.figure() plt.title(f'Evaluation of saccade generation, RMSE : {mse}') plt.plot(stim_times, stim_sizes, label='Target displacement') plt.plot(stim_times, saccadic_sizes,
def test_spike_transmission(self, dt=.01): dt = 0.1 nest.ResetKernel() nest.SetKernelStatus(dict(resolution=dt)) soma_params = { 'C_m': 1.0, 'g_C': 0.1, 'g_L': 0.1, 'e_L': -70.0, } n_neat_0 = nest.Create('cm_default') nest.SetStatus( n_neat_0, {"compartments": { "parent_idx": -1, "params": soma_params }}) n_neat_1 = nest.Create('cm_default') nest.SetStatus( n_neat_1, {"compartments": { "parent_idx": -1, "params": soma_params }}) nest.SetStatus(n_neat_1, {"receptors": { "comp_idx": 0, "receptor_type": "AMPA" }}) syn_idx = 0 nest.Connect(n_neat_0, n_neat_1, syn_spec={ 'synapse_model': 'static_synapse', 'weight': .1, 'receptor_type': syn_idx }) dc = nest.Create('dc_generator', {'amplitude': 2.0}) nest.Connect(dc, n_neat_0, syn_spec={ 'synapse_model': 'static_synapse', 'weight': 1., 'receptor_type': 0 }) m_neat_0 = nest.Create('multimeter', 1, { 'record_from': ['v_comp0'], 'interval': dt }) nest.Connect(m_neat_0, n_neat_0) m_neat_1 = nest.Create('multimeter', 1, { 'record_from': ['v_comp0'], 'interval': dt }) nest.Connect(m_neat_1, n_neat_1) nest.Simulate(100.) events_neat_0 = nest.GetStatus(m_neat_0, 'events')[0] events_neat_1 = nest.GetStatus(m_neat_1, 'events')[0] self.assertTrue(np.any(events_neat_0['v_comp0'] != soma_params['e_L'])) self.assertTrue(np.any(events_neat_1['v_comp0'] != soma_params['e_L']))
def test_continuerun(self, dt=0.1): recordables = [ 'v_comp0', 'v_comp1', 'g_r_GABA_0', 'g_d_GABA_0', 'g_r_AMPA_1', 'g_d_AMPA_1' ] # case 1: continuous simulation nest.ResetKernel() nest.SetKernelStatus(dict(resolution=dt)) n_neat = nest.Create('cm_default') nest.SetStatus( n_neat, { "compartments": [{ "parent_idx": -1, "params": SP }, { "parent_idx": 0, "params": DP[0] }], "receptors": [{ "comp_idx": 0, "receptor_type": "GABA" }, { "comp_idx": 1, "receptor_type": "AMPA" }] }) sg_1 = nest.Create('spike_generator', 1, {'spike_times': [10.]}) sg_2 = nest.Create('spike_generator', 1, {'spike_times': [15.]}) nest.Connect(sg_1, n_neat, syn_spec={ 'synapse_model': 'static_synapse', 'weight': .1, 'receptor_type': 0 }) nest.Connect(sg_2, n_neat, syn_spec={ 'synapse_model': 'static_synapse', 'weight': .1, 'receptor_type': 1 }) m_neat = nest.Create('multimeter', 1, { 'record_from': recordables, 'interval': 1. }) nest.Connect(m_neat, n_neat) nest.Simulate(100.) events_neat_0 = nest.GetStatus(m_neat, 'events')[0] # case 2: two nest.Simulate() calls nest.ResetKernel() nest.SetKernelStatus(dict(resolution=dt)) n_neat = nest.Create('cm_default') nest.SetStatus( n_neat, { "compartments": [{ "parent_idx": -1, "params": SP }, { "parent_idx": 0, "params": DP[0] }], "receptors": [{ "comp_idx": 0, "receptor_type": "GABA" }, { "comp_idx": 1, "receptor_type": "AMPA" }] }) sg_1 = nest.Create('spike_generator', 1, {'spike_times': [10.]}) sg_2 = nest.Create('spike_generator', 1, {'spike_times': [15.]}) nest.Connect(sg_1, n_neat, syn_spec={ 'synapse_model': 'static_synapse', 'weight': .1, 'receptor_type': 0 }) nest.Connect(sg_2, n_neat, syn_spec={ 'synapse_model': 'static_synapse', 'weight': .1, 'receptor_type': 1 }) m_neat = nest.Create('multimeter', 1, { 'record_from': recordables, 'interval': 1. }) nest.Connect(m_neat, n_neat) nest.Simulate(12.) nest.Simulate(88.) events_neat_1 = nest.GetStatus(m_neat, 'events')[0] for key in recordables: assert np.allclose(events_neat_0[key], events_neat_1[key])
def test_error_handling(self): # test double root n_neat = nest.Create('cm_default') with self.assertRaisesRegex( nest.kernel.NESTError, "UnknownCompartment in SLI function SetStatus_id: " "Compartment 0 , the root, " "has already been instantiated."): n_neat.compartments = [{ "parent_idx": -1, "params": SP }, { "parent_idx": -1, "params": SP }] # test undefined parent compartment n_neat = nest.Create('cm_default') with self.assertRaisesRegex( nest.kernel.NESTError, "UnknownCompartment in SLI function SetStatus_id: " "Compartment 15 does not exist in tree, " "but was specified as a parent."): n_neat.compartments = [{ "parent_idx": -1, "params": SP }, { "parent_idx": 15, "params": SP }] # test undefined compartment when adding receptor n_neat = nest.Create('cm_default') n_neat.compartments = {"parent_idx": -1, "params": SP} with self.assertRaisesRegex( nest.kernel.NESTError, "UnknownCompartment in SLI function SetStatus_id: " "Compartment 12 does not exist in tree."): n_neat.receptors = {"comp_idx": 12, "receptor_type": "GABA"} # test simulate without adding compartments n_neat = nest.Create('cm_default') with self.assertRaisesRegex( nest.kernel.NESTError, "UnknownCompartment in SLI function Simulate_d: " "Compartment 0 does not exist in tree, " "meaning that no compartments have been added."): nest.Simulate(10.) # test connection port out of range for current input n_neat = nest.Create('cm_default') n_neat.compartments = [{ "parent_idx": -1, "params": SP }, { "parent_idx": 0, "params": SP }] dc = nest.Create('dc_generator', {'amplitude': 2.0}) with self.assertRaisesRegex( nest.kernel.NESTError, r"UnknownPort in SLI function Connect_g_g_D_D: " r"Port with id 3 does not exist. Valid current " r"receptor ports for cm_default are in \[0, 2\[."): nest.Connect(dc, n_neat, syn_spec={ 'synapse_model': 'static_synapse', 'weight': 1., 'receptor_type': 3 }) # test connection port out of range for spike input n_neat = nest.Create('cm_default') n_neat.compartments = {"parent_idx": -1, "params": SP} n_neat.receptors = [{ "comp_idx": 0, "receptor_type": "GABA" }, { "comp_idx": 0, "receptor_type": "GABA" }, { "comp_idx": 0, "receptor_type": "GABA" }] sg = nest.Create('spike_generator', 1, {'spike_times': [10.]}) with self.assertRaisesRegex( nest.kernel.NESTError, r"UnknownPort in SLI function Connect_g_g_D_D: " r"Port with id 3 does not exist. Valid spike " r"receptor ports for cm_default are in \[0, 3\[."): nest.Connect(sg, n_neat, syn_spec={ 'synapse_model': 'static_synapse', 'weight': 1., 'receptor_type': 3 }) # test connection with unknown recordable n_neat = nest.Create('cm_default') n_neat.compartments = {"parent_idx": -1, "params": SP} mm = nest.Create('multimeter', 1, { 'record_from': ['v_comp1'], 'interval': 1. }) with self.assertRaisesRegex( nest.kernel.NESTError, "IllegalConnection in SLI function Connect_g_g_D_D: " "Creation of connection is not possible because:\n" "Cannot connect with unknown recordable v_comp1"): nest.Connect(mm, n_neat) # test adding compartments and receptors twice n_neat = nest.Create('cm_default') n_neat.compartments = {"parent_idx": -1, "params": SP} n_neat.receptors = {"comp_idx": 0, "receptor_type": "GABA"} with self.assertRaisesRegex( nest.kernel.NESTError, "\'compartments\' is already defined for this model"): n_neat.compartments = {"parent_idx": 0, "params": SP} with self.assertRaisesRegex( nest.kernel.NESTError, "\'receptors\' is already defined for this model"): n_neat.receptors = {"comp_idx": 0, "receptor_type": "GABA"}
def train(self, img_array, label): # nest.ResetKernel() # for i in range(self.input_layer_size): # nest.SetStatus([self.input_neurons[i]],{"rate":np.float(img_array[i] / 255.0 * self.base_frequency)}) nest.SetStatus(self.input_neurons, [{ "rate": i / 255.0 * self.base_frequency } for i in img_array]) start_time = time.time() nest.Simulate(self.sim_time) end_time = time.time() print(" Nest Simulate Time:", end_time - start_time, "s") start_time = time.time() sd_status_output = nest.GetStatus(self.spike_dectector_output) sd_status_hidden = nest.GetStatus(self.spike_dectector_hidden) # hidden_error is backpropagated from output layer hidden_error = np.zeros(self.hidden_layer_size) for output_neuron_id in range(self.output_layer_size): # z_j = 1 , check r_i ksai = 0.0 if (output_neuron_id == label): if (sd_status_output[output_neuron_id]["n_events"] == 0): ksai = 1.0 else: if (sd_status_output[output_neuron_id]["n_events"] != 0): ksai = -1.0 for hidden_neuron_id in range(self.hidden_layer_size): spike_sum = sd_status_hidden[hidden_neuron_id]["n_events"] delta_weight = self.learning_rate * spike_sum * ksai conn = nest.GetConnections( [self.hidden_neurons[hidden_neuron_id]], [self.output_neurons[output_neuron_id]]) old_weight = nest.GetStatus(conn)[0]["weight"] nest.SetStatus(conn, params={"weight": old_weight + delta_weight}) hidden_error[hidden_neuron_id] += ksai * old_weight for hidden_neuron_id in range(self.hidden_layer_size): if (sd_status_hidden[hidden_neuron_id]["n_events"] > 0): for input_neuron_id in range(self.input_layer_size): sigma_s_j = nest.GetStatus([ self.input_neurons[input_neuron_id] ])[0]['rate'] * self.sim_time delta_weight = self.learning_rate * hidden_error[ hidden_neuron_id] * sigma_s_j conn = nest.GetConnections( [self.input_neurons[input_neuron_id]], [self.hidden_neurons[hidden_neuron_id]]) old_weight = nest.GetStatus(conn)[0]["weight"] nest.SetStatus( conn, params={"weight": old_weight + delta_weight}) max_index = 0 total_spikes = sd_status_output[max_index]["n_events"] events = [sd_status_output[max_index]["n_events"]] for output_neuron_id in range(1, self.output_layer_size): if (sd_status_output[output_neuron_id]["n_events"] > sd_status_output[max_index]["n_events"]): max_index = output_neuron_id total_spikes += sd_status_output[output_neuron_id]["n_events"] events.append(sd_status_output[output_neuron_id]["n_events"]) if (total_spikes == 0): possiblity = 1 else: possiblity = sd_status_output[max_index]["n_events"] / total_spikes end_time = time.time() print(" Weight Update Time:", end_time - start_time, "s") # print(max_index,",",possiblity) print(" output events:", events) return (max_index, possiblity)
nest.Connect(Mm[t_pop], n_gids, {'rule': 'one_to_one'}) # connect hyperpolarizing generators to first recorded PY neuron if t_pop == 0: nest.Connect(gen_R_basic, [n_gids[0]], {'rule': 'all_to_all'}, {'receptor_type': syns['curr']}) nest.Connect(gen_R_pulse, [n_gids[0]], {'rule': 'all_to_all'}, {'receptor_type': syns['curr']}) ############################################# ##### SIMULATE ########################### ############################################# nest.Simulate(sim_time) ########################################### #### SAVE DATA ################# ########################################### # prepare multimeter data for saving Mm_raw = [] for t_pop in [0]: #range(2): Mm_raw += [[]] mm_id = 0 for mm in Mm[t_pop]: data = nest.GetStatus([mm])[0]['events'] temp = {'V_m': data['V_m_s']} temp['times'] = data['times']
'phi': np.pi / 2. }]) m = nest.Create('multimeter', n=2, params={ 'interval': 0.1, 'withgid': False, 'record_from': ['rate'] }) s = nest.Create('spike_detector', n=2, params={'withgid': False}) nest.Connect(m, g, 'one_to_one') nest.Connect(g, s, 'one_to_one') print nest.GetStatus(m) nest.Simulate(200) ''' After simulating, the spikes are extracted from the `spike_detector` using `GetStatus` and plots are created with panels for the PST and ISI histograms. ''' colors = ['b', 'g'] for j in range(2): ev = nest.GetStatus([m[j]])[0]['events'] t = ev['times'] r = ev['rate'] sp = nest.GetStatus([s[j]])[0]['events']['times']
'rule': 'fixed_indegree', 'indegree': c_i }, { 'model': 'plastic-synapse', 'weight': { 'distribution': 'uniform', 'low': w_min_i, 'high': w_max_i }, 'delay': delay }) nest.Connect(nodes_i, nodes_i, syn_spec='sel_exc') nest.Connect(nodes_e[:N_rec], spikes_e) nest.Connect(voltmeter, nodes_e[90:91]) nest.Simulate(tsim) #plt.subplot(2,1,1) nest.raster_plot.from_device(spikes_e, hist=True) #x1 = np.linspace(0.0, 5.0) #y2 = np.cos(2 * np.pi * x1) #plt.subplot(2,1,1) #plt.plot(x1, y2) #plt.subplot(2,1,2) plt.figure() nest.voltage_trace.from_device(voltmeter) plt.show() ##PSD
def simulate(): """ Runs a single simulation, parameters taken from upper scope """ nest.ResetKernel() nest.SetKernelStatus({ "resolution": PSET.dt, "print_time": True, "overwrite_files": True, 'grng_seed': PSET.nest_seed }) np.random.seed(PSET.numpy_seed) random.seed(PSET.random_seed) print("Building network") ## Set parameters for neurons and poisson generator nest.SetDefaults("iaf_psc_delta", neuron_params) nest.SetDefaults("poisson_generator", {"rate": p_rate}) ## Create all neurons and recorders # local populations nodes_ex = nest.Create("iaf_psc_delta", PSET.NE) nodes_in = nest.Create("iaf_psc_delta", PSET.NI) # external population noise = nest.Create("poisson_generator") # spike recorders espikes = nest.Create("spike_detector") ispikes = nest.Create("spike_detector") print("first exc node: {}".format(nodes_ex[0])) print("first inh node: {}".format(nodes_in[0])) ## Set initial membrane voltages to random values between 0 and threshold nest.SetStatus(nodes_ex, "V_m", np.random.rand(len(nodes_ex)) * neuron_params["V_th"]) nest.SetStatus(nodes_in, "V_m", np.random.rand(len(nodes_in)) * neuron_params["V_th"]) ## Spike recording parameters nest.SetStatus(espikes, [{ "label": os.path.join(PSET.savefolder, 'nest_output', PSET.ps_id, label + "-EX"), "withtime": True, "withgid": True, "to_file": PSET.save_spikes, }]) nest.SetStatus(ispikes, [{ "label": os.path.join(PSET.savefolder, 'nest_output', PSET.ps_id, label + "-IN"), "withtime": True, "withgid": True, "to_file": PSET.save_spikes, }]) ## Set synaptic weights nest.CopyModel("static_synapse", "excitatory", { "weight": PSET.J, 'delay': PSET.delay }) nest.CopyModel("static_synapse", "inhibitory", { "weight": -PSET.J * PSET.g, 'delay': PSET.delay }) ## Connect 'external population' poisson generator to local neurons nest.Connect(noise, nodes_ex, 'all_to_all', "excitatory") nest.Connect(noise, nodes_in, 'all_to_all', "excitatory") ## Record spikes to be saved from a subset of each population nest.Connect(nodes_ex, espikes, 'all_to_all', 'excitatory') nest.Connect(nodes_in, ispikes, 'all_to_all', 'excitatory') ## Connect local populations conn_params_ex = {'rule': 'fixed_indegree', 'indegree': PSET.CE} nest.Connect(nodes_ex, nodes_ex + nodes_in, conn_params_ex, 'excitatory') conn_params_in = {'rule': 'fixed_indegree', 'indegree': PSET.CI} nest.Connect(nodes_in, nodes_ex + nodes_in, conn_params_in, 'inhibitory') endbuild = time.time() nest.Simulate(PSET.simtime) endsimulate = time.time() ## Calculate firing rate events_ex = nest.GetStatus(espikes, "n_events")[0] events_in = nest.GetStatus(ispikes, "n_events")[0] rate_ex = events_ex / PSET.simtime * 1000.0 / PSET.N_neurons rate_in = events_in / PSET.simtime * 1000.0 / PSET.N_neurons build_time = endbuild - startbuild sim_time = endsimulate - endbuild print('Build time: %.1f' % build_time) print('Sim time: %.1f' % sim_time) print('Excitatory firing rate: %.1f' % rate_ex) print('Inhibitory firing rate: %.1f' % rate_in) ## Get sample spikes for saving ex_events = nest.GetStatus(espikes, 'events')[0] in_events = nest.GetStatus(ispikes, 'events')[0] # ex_spikes = np.stack((ex_events['senders'], ex_events['times'])).T # in_spikes = np.stack((in_events['senders'], in_events['times'])).T ## Get population firing histograms for calculating LFP ex_hist_times = ex_events['times'] in_hist_times = in_events['times'] hist_bins_1 = np.arange(PSET.simtime + 2, dtype=np.float32) - 0.5 ex_hist, _ = np.histogram(ex_hist_times, bins=hist_bins_1) in_hist, _ = np.histogram(in_hist_times, bins=hist_bins_1) with h5py.File(output_file, 'w') as f: if PSET.predict_LFP: d_diff = int(PSET['delay'] - 1.5) # to shift kernel with delay LFP = np.empty([6, len(ex_hist)]) for i in range(6): LFP[i] = np.convolve(ex_hist, ex_kernel[i] * PSET.J, mode='same') +np.convolve( in_hist, in_kernel[i] * PSET.g * PSET.J, mode='same') dset = f.create_dataset('data', data=LFP) # f.create_dataset('ex_spikes', data=ex_spikes) # f.create_dataset('in_spikes', data=in_spikes) f.create_dataset('ex_hist', data=ex_hist) f.create_dataset('in_hist', data=in_hist) print('Complete')
"model": "syn_exci", "delay": delay_dict[2], "weight": gbar_E * skip_weights, }, ) for stim_i in range(num_stimulus) ] #### else: #### print("you typed in the wrong network name") exit() """ simulate with extra time for stimuli to be set """ nest.Simulate(sim_time + t_onset) """ save the data """ # only when the simulation time is short if sim_time < short_threshold: spike_times = [] spike_senders = [] for mod_i in range(module_depth): data_spike = nest.GetStatus(spike_device[mod_i], "events")[0] spike_times.append( data_spike["times"] ) # list of spike times with each component repr. layer spike_senders.append(data_spike["senders"]) if len(sys.argv) > 8:
nest.Connect(m, iaf) m_9ml = nest.Create('multimeter', params={ 'withtime': True, 'interval': 0.1, 'record_from': ['V_m', 'g_ex', 'g_in', 'Regime9ML'] }) nest.Connect(m_9ml, iaf9ml) # simulate t1 = time.time() nest.Simulate(tsim * 1000) t2 = time.time() print "Elapsed: ", t2 - t1, " seconds." # get iaf spike output spikes = nest.GetStatus(spike_detector, 'events')[0]['times'] espikes = spikes.astype(float) data = nest.GetStatus(m)[0]['events'] data_9ml = nest.GetStatus(m_9ml)[0]['events'] t = data["times"] g_in = data["g_in"] g_in_9ml = data_9ml["g_in"]
def simulate(self): """ Simulates the microcircuit.""" nest.Simulate(self.sim_dict['t_sim'])
}) nest.Connect(pg_inh, neuron, syn_spec={ 'model': 'static_synapse', 'weight': w_inh }) nest.Connect(pg_ext, neuron, syn_spec={ 'model': 'static_synapse', 'weight': w_exc }) nest.Connect(neuron, sd_post) nest.Simulate(100000.0) # simulate 100 s, determine weight distribution connections = nest.GetConnections(inputs) weights = np.array(nest.GetStatus(connections, 'weight')) sim_time = 100000.0 rec_step = 1000.0 # record weights in steps of 1 s for t in np.arange(rec_step, sim_time + rec_step, rec_step): nest.Simulate(rec_step) connections = nest.GetConnections(inputs) weights = np.append(weights, nest.GetStatus(connections, 'weight')) weight_dists.append( np.histogram(weights, bins=50, range=[0.0, 2.0 * w_exc], normed=True)[0])
v_r = -60. v_t = -40. v_peak = 35. I_e = 60.0 params = { 'a': a, 'b_1': b, 'b_2': b, 'c': c, 'C_m': C, 'd': d, 'k': k, 'V_b': v_b, 'V_peak': v_peak, 'V_r': v_r, 'V_t': v_t, 'I_e': I_e } nest.SetStatus(n, params) nest.Connect(mm, n) nest.Simulate(1000) status_mm = nest.GetStatus(mm) v_m = status_mm[0]['events']['V_m'] times = status_mm[0]['events']['times'] pylab.plot(times, v_m) pylab.show()
The connection from neuron 1 to neuron 3 has a stochastic quantal_stp_synapse. ''' nest.Connect([neuron[0]], [neuron[2]], syn_spec="quantal_stp_synapse") ''' The voltmeter will show us the synaptic responses in neurons 2 and 3. ''' voltmeter = nest.Create("voltmeter", 2) nest.SetStatus(voltmeter, {"withgid": True, "withtime": True}) ''' One dry run to bring all synapses into their rest state. The default initialization does not achieve this. In large network simulations this problem does not show, but in small simulations like this, we would see it. ''' nest.SetStatus([neuron[0]], "I_e", 376.0) nest.Simulate(500.0) nest.SetStatus([neuron[0]], "I_e", 0.0) nest.Simulate(1000.0) ''' Only now do we connect the voltmeter to the neurons. ''' nest.Connect([voltmeter[0]], [neuron[1]]) nest.Connect([voltmeter[1]], [neuron[2]]) ''' This loop runs over the n_trials trials and performs a standard protocol of a high-rate response, followed by a pause and then a recovery response. ''' for t in range(n_trials): nest.SetStatus([neuron[0]], "I_e", 376.0) nest.Simulate(500.0) nest.SetStatus([neuron[0]], "I_e", 0.0)
def activity_simulation(net, pop, sim_duration=sim_duration): ''' Execute activity simulation on the generated graph -------------------------------------------------- Input : net : nngt generated graph with model pop : neurons population sim_duration : time (s) duration of simulation Output : activity graphs ''' if (nngt.get_config('with_nest')) and (simulate_activity is True): print("SIMULATE ACTIVITY") import nngt.simulation as ns import nest nest.ResetKernel() nest.SetKernelStatus({'local_num_threads': 14}) nest.SetKernelStatus({'resolution': .5}) gids = net.to_nest() # nngt.simulation.randomize_neural_states(net, {"w": ("uniform", 0, 200), # "V_m": ("uniform", -70., -40.)}) nngt.simulation.randomize_neural_states(net, { "w": ("normal", 50., 5.), "V_m": ("uniform", -80., -50.) }) # add noise to the excitatory neurons excs = list(gids) # ns.set_noise(excs, 10., 2.) # ns.set_poisson_input(gids, rate=3500., syn_spec={"weight": 34.}) target_rate = 25. average_degree = net.edge_nb() / float(net.node_nb()) syn_rate = target_rate / average_degree print("syn_rate", syn_rate) print("avg_deg", average_degree) ns.set_minis(net, base_rate=syn_rate, weight_fraction=.4, gids=gids) vm, vs = ns.monitor_nodes([1, 10], "voltmeter") recorders, records = ns.monitor_groups(pop.keys(), net) nest.Simulate(sim_duration) if plot_activity is True: print("Plot raster") ns.plot_activity(vm, vs, network=net, show=False) ns.plot_activity(recorders, records, network=net, show=False, hist=True) plt.show() if animation_movie is True: print("Process animation") anim = nngt.plot.AnimationNetwork(recorders, net, resolution=0.1, interval=20, decimate=-1) # ~ anim.save_movie("structured_bursting.mp4", fps=2, start=650., # ~ stop=1500, interval=20) # ~ anim.save_movie("structured_bursting.mp4", fps=5, num_frames=50) anim.save_movie("structured_bursting.mp4", fps=15, interval=10) if save_spikes is True: print("Save sikes of neurons") nngt.simulation.save_spikes("spikes_output.dat")
spike_detector_right = nest.Create('spike_detector', 1) spike_detector_left = nest.Create('spike_detector', 1) spike_detector_up = nest.Create('spike_detector', 1) spike_detector_down = nest.Create('spike_detector', 1) # connect devices nest.Connect(dc_generator_right, right_llbn) nest.Connect(dc_generator_up, up_llbn) nest.Connect(left_ebn, spike_detector_left) nest.Connect(right_ebn, spike_detector_right) nest.Connect(up_ebn, spike_detector_up) nest.Connect(down_ebn, spike_detector_down) # simulate nest.Simulate(stim_time + 400.) spike_times_left = nest.GetStatus(spike_detector_left, 'events')[0]['times'] spike_times_right = nest.GetStatus(spike_detector_right, 'events')[0]['times'] spike_times_up = nest.GetStatus(spike_detector_up, 'events')[0]['times'] spike_times_down = nest.GetStatus(spike_detector_down, 'events')[0]['times'] # obtain saccade size saccade_size_left = saccadic_size_single_side([stim_time], spike_times_left, maximal_saccade_size) saccade_size_right = saccadic_size_single_side([stim_time], spike_times_right, maximal_saccade_size) saccade_size_up = saccadic_size_single_side([stim_time], spike_times_up, maximal_saccade_size) saccade_size_down = saccadic_size_single_side([stim_time], spike_times_down, maximal_saccade_size)
"alpha": alpha, "lambda": 0.1, "Wmax": 2.0 * w_exc }) nest.Connect(pg_exc, inputs, "all_to_all", { "weight": 1.0, "delay": 1.0, "model": "static_synapse" }) nest.Connect(pg_inh, neuron, "all_to_all", { "weight": w_inh, "delay": 1.0, "model": "static_synapse" }) nest.Connect(pg_ext, neuron, "all_to_all", { "weight": w_exc, "delay": 1.0, "model": "static_synapse" }) nest.Connect(inputs, neuron, "all_to_all", { "weight": w_exc, "delay": 1.0, "model": "stdp_synapse" }) # STDP nest.Simulate(1) conn = nest.GetConnections(inputs) weights = nest.GetStatus(conn, "weight") print(weights)
def test_facetshw_stdp(self): nest.ResetKernel() modelName = 'stdp_facetshw_synapse_hom' # homogeneous parameters for all synapses Wmax = 100.0 # see *.cpp file of synapse model and Pfeil et al. 2012 for LUT # configuration lut_0 = [2, 3, 4, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 14, 15] lut_1 = [0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 11, 12, 13] lut_2 = range(16) # identity config_0 = [0, 0, 1, 0] config_1 = [0, 1, 0, 0] reset_pattern = 6 * [1] # reset all # individual parameters for each synapse # reached every 36 runs (e^(-10/20) = 21.83510375) lut_th_causal = 21.835 lut_th_acausal = lut_th_causal # other parameters startWeight = 0 # as digital value [0, 1, ..., 15] tau = 20.0 timeBetweenPairs = 100.0 # frequency_of_pairs = 10Hz => delta_t(+) = 10ms, delta_t(-) = 90ms delay = 5.0 spikesIn = np.arange(10.0, 60000.0, timeBetweenPairs) synapseDict = { 'tau_plus': tau, 'tau_minus_stdp': tau, 'Wmax': Wmax, 'synapses_per_driver': 50, 'driver_readout_time': 15.0, 'lookuptable_0': lut_0, 'lookuptable_1': lut_1, 'lookuptable_2': lut_2, 'configbit_0': config_0, 'configbit_1': config_1, 'reset_pattern': reset_pattern, 'a_thresh_th': lut_th_causal, 'a_thresh_tl': lut_th_acausal } # build network stim = nest.Create('spike_generator') neuronA = nest.Create('parrot_neuron') neuronB = nest.Create('parrot_neuron') nest.SetStatus(stim, [{'spike_times': spikesIn}]) nest.SetDefaults(modelName, synapseDict) # check if GetDefaults returns same values as have been set synapseDictGet = nest.GetDefaults(modelName) for key in synapseDict.keys(): self.assertTrue( all(np.atleast_1d(synapseDictGet[key] == synapseDict[key]))) nest.Connect(stim, neuronA) nest.Connect(neuronA, neuronB, syn_spec={ 'weight': float(startWeight) / 15.0 * Wmax, 'delay': delay, 'synapse_model': modelName }) nest.Simulate(50.0) weightTrace = [] for run in range(len(spikesIn)): nest.Simulate(timeBetweenPairs) connections = nest.GetConnections(neuronA) if (connections.get('synapse_model') == modelName): weightTrace.append([ run, connections.get('weight'), connections.get('a_causal'), connections.get('a_acausal') ]) # analysis weightTrace = np.array(weightTrace) # just before theoretical updates weightTraceMod36pre = weightTrace[35::36] # just after theoretical updates weightTraceMod36 = weightTrace[::36] weightIndex = int(startWeight) for i in range(len(weightTraceMod36pre)): # check weight value before update # (after spike pair with index 35, 71, ...) self.assertTrue( np.allclose(weightTraceMod36pre[i][1], 1.0 / 15.0 * weightIndex * Wmax, atol=1e-6)) weightIndex = lut_0[weightIndex] weightIndex = int(startWeight) for i in range(len(weightTraceMod36)): # check weight value after update # (after spike pair with index 0, 36, 72, ...) self.assertTrue( np.allclose(weightTraceMod36[i][1], 1.0 / 15.0 * weightIndex * Wmax, atol=1e-6)) # check charge on causal capacitor self.assertTrue( np.allclose(weightTraceMod36[i][2], np.ones_like(weightTraceMod36[i][2]) * np.exp(-2 * delay / tau), atol=1e-6)) weightIndex = lut_0[weightIndex] # check charge on anti-causal capacitor after each pair for i in range(len(weightTrace) - 1): # TODO: global params self.assertTrue( np.allclose(weightTrace[i, 3], ((i % 36) + 1) * np.exp(-(timeBetweenPairs - 2 * delay) / tau), atol=1e-6))
'tau_m': tau_m, 'c_1': 0.0, 'c_2': 2. * m_x, 'c_3': 1.0 }) n1 = nest.Create("ginzburg_neuron") nest.SetDefaults("mcculloch_pitts_neuron", {'theta': 0.5, 'tau_m': tau_m}) n2 = nest.Create("mcculloch_pitts_neuron") nest.Connect(n1, n2, syn_spec={"weight": 1.0}) nest.Connect(n1, csd, syn_spec={"receptor_type": 0}) nest.Connect(n2, csd, syn_spec={"receptor_type": 1}) nest.Simulate(T) stat = nest.GetStatus(csd)[0] c = stat["count_covariance"] m = np.zeros(2, dtype=float) for i in range(2): m[i] = c[i][i][int(tau_max / h)] * (h / T) print('mean activities =', m) cmat = np.zeros((2, 2, int(2 * tau_max / h) + 1), dtype=float) for i in range(2): for j in range(2): cmat[i, j] = c[i][j] * (h / T) - m[i] * m[j]