def run_simple_split(): sim.setup(0.1, time_scale_factor=1) sim.set_number_of_neurons_per_core(sim.IF_curr_exp, 16) # Note, this next one is ignored on one-to-one Poisson sources sim.set_number_of_neurons_per_core(sim.SpikeSourcePoisson, 10) one_to_one_source = sim.Population(50, sim.SpikeSourcePoisson(rate=10000), additional_parameters={ "seed": 0, "splitter": SplitterPoissonDelegate() }) rand_source = sim.Population(50, sim.SpikeSourcePoisson(rate=10), additional_parameters={ "seed": 1, "splitter": SplitterSliceLegacy() }) rand_source.record("spikes") target = sim.Population( 50, sim.IF_curr_exp(), additional_parameters={ "splitter": SplitterAbstractPopulationVertexNeuronsSynapses(3) }) target.record(["spikes", "packets-per-timestep"]) sim.Projection(one_to_one_source, target, sim.OneToOneConnector(), sim.StaticSynapse(weight=0.01)) sim.Projection(rand_source, target, sim.OneToOneConnector(), sim.StaticSynapse(weight=2.0)) sim.run(1000) source_spikes = [ s.magnitude for s in rand_source.get_data("spikes").segments[0].spiketrains ] target_spikes = [ s.magnitude for s in target.get_data("spikes").segments[0].spiketrains ] target_ppts = (numpy.nonzero( numpy.sum([ s.magnitude for s in target.get_data("packets-per-timestep"). segments[0].filter(name='packets-per-timestep')[0] ], axis=1))[0] - 1) / 10 sim.end() # The only actual spikes received should be from the random source all_source_spikes = numpy.unique( numpy.sort(numpy.concatenate(source_spikes))) assert (numpy.allclose(all_source_spikes, target_ppts)) # A target spike should be caused by a source spike (though not all sources # will cause a target spike) for s, t in zip(source_spikes, target_spikes): assert (len(t) <= len(s))
def run_script(): n_neurons = 500 simtime = SIMTIME sim.setup(timestep=1) pop_1 = sim.Population(n_neurons, sim.IF_curr_exp(), label="pop_1") input1 = sim.Population(1, sim.SpikeSourceArray(spike_times=[0]), label="input") sim.Projection(input1, pop_1, sim.AllToAllConnector(), synapse_type=sim.StaticSynapse(weight=5, delay=1)) input2 = sim.Population(n_neurons, sim.SpikeSourcePoisson( rate=100.0, seed=1), label="Stim_Exc") sim.Projection(input2, pop_1, sim.OneToOneConnector(), synapse_type=sim.StaticSynapse(weight=5, delay=1)) pop_1.record(['spikes', 'v', 'gsyn_exc', 'gsyn_inh']) sim.run(simtime) neo = pop_1.get_data() spikes = neo.segments[0].spiketrains v = neo.segments[0].filter(name='v')[0] exc = neo.segments[0].filter(name='gsyn_exc')[0] inh = neo.segments[0].filter(name='gsyn_inh')[0] sim.end() return spikes, v, exc, inh
def do_run(seed=None): sim.setup(timestep=1.0, min_delay=1.0, max_delay=1.0) simtime = 1000 if seed is None: pg_pop1 = sim.Population(2, sim.SpikeSourcePoisson(rate=10.0, start=0, duration=simtime), label="pg_pop1") pg_pop2 = sim.Population(2, sim.SpikeSourcePoisson(rate=10.0, start=0, duration=simtime), label="pg_pop2") else: pg_pop1 = sim.Population(2, sim.SpikeSourcePoisson(rate=10.0, start=0, duration=simtime, seed=seed), label="pg_pop1") pg_pop2 = sim.Population(2, sim.SpikeSourcePoisson(rate=10.0, start=0, duration=simtime, seed=seed + 1), label="pg_pop2") pg_pop1.record("spikes") pg_pop2.record("spikes") sim.run(simtime) neo = pg_pop1.get_data("spikes") spikes1 = neo_convertor.convert_spikes(neo) neo = pg_pop2.get_data("spikes") spikes2 = neo_convertor.convert_spikes(neo) sim.end() return (spikes1, spikes2)
def test_set_spikes_indexes(self): sim.setup(timestep=1) if_curr = sim.Population(5, sim.IF_curr_exp()) recorder = if_curr._vertex._neuron_recorder ssa = sim.Population( 5, sim.SpikeSourceArray(spike_times=[0])) ssp = sim.Population(5, sim.SpikeSourcePoisson(rate=100.0, seed=1)) if_curr.record("spikes", indexes=[1, 2, 4]) ssa.record("spikes", indexes=[1, 2, 4]) ssp.record("spikes", indexes=[1, 2, 4]) self.assertListEq(["spikes"], if_curr._get_all_recording_variables()) assert recorder._indexes["spikes"] == [1, 2, 4]
def test_set_spikes(self): sim.setup(timestep=1) if_curr = sim.Population(1, sim.IF_curr_exp()) self.assertListEq([], if_curr._get_all_recording_variables()) ssa = sim.Population( 1, sim.SpikeSourceArray(spike_times=[0])) ssp = sim.Population(2, sim.SpikeSourcePoisson(rate=100.0, seed=1)) if_curr.record("spikes") self.assertListEq(["spikes"], if_curr._get_all_recording_variables()) ssa.record("spikes") ssp.record("spikes") sim.end()
def no_reset(self): p.setup(1.0) inp = p.Population(100, p.SpikeSourcePoisson(rate=100), label="input") inp.record("spikes") p.run(100) spikes1 = inp.spinnaker_get_data('spikes') inp.set(rate=10) p.run(100) spikes2 = inp.spinnaker_get_data('spikes') assert len(spikes1) > (len(spikes2) - len(spikes1)) * 5 p.end()
def test_set_spikes_interval(self): sim.setup(timestep=1) if_curr = sim.Population(1, sim.IF_curr_exp()) recorder = if_curr._vertex._neuron_recorder self.assertListEq([], if_curr._get_all_recording_variables()) ssa = sim.Population( 1, sim.SpikeSourceArray(spike_times=[0])) ssp = sim.Population(2, sim.SpikeSourcePoisson(rate=100.0, seed=1)) if_curr.record("spikes", sampling_interval=2) ssa.record("spikes", sampling_interval=2) ssp.record("spikes", sampling_interval=2) self.assertListEq(["spikes"], if_curr._get_all_recording_variables()) assert recorder.get_neuron_sampling_interval("spikes") == 2
def run_forever_not_recorded(): sim.setup(1.0) stim = sim.Population(1, sim.SpikeSourcePoisson(rate=10.0)) pop = sim.Population(255, sim.IF_curr_exp(tau_syn_E=1.0), label="pop") sim.Projection( stim, pop, sim.AllToAllConnector(), sim.StaticSynapse(weight=20.0)) conn = DatabaseConnection( start_resume_callback_function=start_callback, stop_pause_callback_function=stop_callback, local_port=None) SpynnakerExternalDevicePluginManager.add_database_socket_address( conn.local_ip_address, conn.local_port, None) sim.external_devices.run_forever() sim.end()
def test_set_spikes_indexes(self): sim.setup(timestep=1) if_curr = sim.Population(5, sim.IF_curr_exp()) recorder = if_curr._vertex.neuron_recorder ssa = sim.Population(5, sim.SpikeSourceArray(spike_times=[0])) ssp = sim.Population(5, sim.SpikeSourcePoisson(rate=100.0), additional_parameters={"seed": 1}) if_curr[1, 2, 4].record("spikes") ssa[1, 2, 4].record("spikes") ssp[1, 2, 4].record("spikes") self.assertCountEqual(["spikes"], if_curr._recorder.get_all_recording_variables()) assert recorder._indexes["spikes"] == [1, 2, 4]
def variable_rate_reset(): """ Test the ways of changing rates and ensure that they don't change the\ results """ p.setup(1.0) pop = p.Population(100, p.extra_models.SpikeSourcePoissonVariable( rates=[1, 10, 100], starts=[0, 1000, 2000]), additional_parameters={"seed": 0}) pop_2 = p.Population(100, p.SpikeSourcePoisson(rate=1), additional_parameters={ "seed": 0, "max_rate": 100 }) pop.record("spikes") pop_2.record("spikes") p.run(1000) spikes_pop_2_1 = pop_2.get_data("spikes") nump = [s.magnitude for s in spikes_pop_2_1.segments[0].spiketrains] numpy.savetxt("spikesp2_1.txt", nump[0]) pop_2.set(rate=10) p.run(1000) spikes_pop_2_2 = pop_2.get_data("spikes") nump = [s.magnitude for s in spikes_pop_2_2.segments[0].spiketrains] numpy.savetxt("spikesp2_2.txt", nump[0]) pop_2.set(rate=100) p.run(1000) p.reset() p.run(3000) spikes_pop = pop.get_data("spikes") spikes_pop_2 = pop_2.get_data("spikes") p.end() spikes_1 = [s.magnitude for s in spikes_pop.segments[0].spiketrains] spikes_2 = [s.magnitude for s in spikes_pop.segments[1].spiketrains] spikes_p_2 = [s.magnitude for s in spikes_pop_2.segments[0].spiketrains] print(spikes_1) numpy.savetxt("spikes1.txt", spikes_1[0]) print(spikes_2) numpy.savetxt("spikes2.txt", spikes_2[0]) print(spikes_p_2) numpy.savetxt("spikesp2.txt", spikes_p_2[0]) for s1, s2, s3 in zip(spikes_1, spikes_2, spikes_p_2): assert (numpy.array_equal(s1, s2)) assert (numpy.array_equal(s2, s3))
def test_set_spikes(self): sim.setup(timestep=1) if_curr = sim.Population(1, sim.IF_curr_exp()) self.assertCountEqual([], if_curr._recorder.get_all_recording_variables()) ssa = sim.Population(1, sim.SpikeSourceArray(spike_times=[0])) ssp = sim.Population(2, sim.SpikeSourcePoisson(rate=100.0), additional_parameters={"seed": 1}) if_curr.record("spikes") self.assertCountEqual(["spikes"], if_curr._recorder.get_all_recording_variables()) ssa.record("spikes") ssp.record("spikes") sim.end()
def test_set_all(self): sim.setup(timestep=1) if_curr = sim.Population(1, sim.IF_curr_exp()) ssa = sim.Population(1, sim.SpikeSourceArray(spike_times=[0])) ssp = sim.Population(2, sim.SpikeSourcePoisson(rate=100.0), additional_parameters={"seed": 1}) if_curr.record("all") self.assertListEq(["spikes", "v", "gsyn_inh", "gsyn_exc"], if_curr._get_all_recording_variables()) ssa.record("all") self.assertListEq(["spikes"], ssa._get_all_recording_variables()) ssp.record("all") self.assertListEq(["spikes"], ssp._get_all_recording_variables()) sim.end()
def check_rates(self, rates, seconds, seed): n_neurons = 100 sim.setup(timestep=1.0) inputs = {} for rate in rates: input = sim.Population(n_neurons, sim.SpikeSourcePoisson(rate), label='inputSpikes_{}'.format(rate), additional_parameters={"seed": seed}) input.record("spikes") inputs[rate] = input sim.run(seconds * 1000) for rate in rates: self.check_spikes(n_neurons, inputs[rate], rate * seconds) sim.end()
def do_run(split, seed=None): p.setup(1.0) if split: p.set_number_of_neurons_per_core(p.SpikeSourcePoisson, 27) p.set_number_of_neurons_per_core(p.IF_curr_exp, 22) inp = p.Population(100, p.SpikeSourcePoisson(rate=100, seed=seed), label="input") pop = p.Population(100, p.IF_curr_exp, {}, label="pop") p.Projection(inp, pop, p.OneToOneConnector(), synapse_type=p.StaticSynapse(weight=5)) pop.record("spikes") inp.record("spikes") p.run(100) inp.set(rate=10) # pop.set("cm", 0.25) pop.set(tau_syn_E=1) p.run(100) pop_spikes1 = pop.spinnaker_get_data('spikes') inp_spikes1 = inp.spinnaker_get_data('spikes') p.reset() inp.set(rate=0) pop.set(i_offset=1.0) vs = p.RandomDistribution("uniform", [-65.0, -55.0], rng=NumpyRNG(seed=seed)) pop.initialize(v=vs) p.run(100) pop_spikes2 = pop.spinnaker_get_data('spikes') inp_spikes2 = inp.spinnaker_get_data('spikes') p.end() return (pop_spikes1, inp_spikes1, pop_spikes2, inp_spikes2)
def do_run(): p.setup(1.0) inp = p.Population(100, p.SpikeSourcePoisson(rate=2, seed=417), label="input") inp.record("spikes") p.run(100) p.reset() inp.set(rate=30) p.run(100) p.end()
def test_levels(rates=(500, 1000), weights=(0.005, 0.0005)): counter = 0 receive_pop = [] spike_input = [] p.setup(timestep=1, min_delay=1, max_delay=127) p.set_number_of_neurons_per_core(p.IF_cond_exp, 10) for rate in rates: for weight in weights: pop_size = 10 receive_pop.append(p.Population(pop_size, p.IF_cond_exp( ))) #, label="receive_pop{}-{}".format(rate, weight))) receive_pop[counter].record(['spikes', 'v']) #["spikes"]) # Connect key spike injector to input population spike_input.append( p.Population(pop_size, p.SpikeSourcePoisson(rate=rate)) ) #, label="input_connect{}-{}".format(rate, weight))) p.Projection(spike_input[counter], receive_pop[counter], p.OneToOneConnector(), p.StaticSynapse(weight=weight)) print "reached here 1" runtime = 11000 counter += 1 p.run(runtime) print "reached here 2" for i in range(counter): weight_index = i % len(weights) rate_index = (i - weight_index) / len(weights) print weight_index print rate_index # for j in range(receive_pop_size): spikes = receive_pop[i].get_data('spikes').segments[0].spiketrains v = receive_pop[i].get_data('v').segments[0].filter(name='v')[0] plt.figure("rate = {} - weight = {}".format(rates[rate_index], weights[weight_index])) Figure(Panel(spikes, xlabel="Time (ms)", ylabel="nID", xticks=True), Panel(v, ylabel="Membrane potential (mV)", yticks=True)) plt.show() # End simulation p.end()
def do_run(): p.setup(1.0) inp = p.Population(100, p.SpikeSourcePoisson(rate=2), label="input", additional_parameters={"seed": 417}) inp.record("spikes") p.run(100) p.reset() inp.set(rate=30) p.run(100) p.end()
def mission_impossible_2(): sim.setup(0.1, time_scale_factor=1) # Can't do structural on multiple synapse cores source = sim.Population(1, sim.SpikeSourcePoisson(rate=10)) pop = sim.Population(128, sim.IF_curr_exp(), additional_parameters={ "splitter": SplitterAbstractPopulationVertexNeuronsSynapses(2) }) sim.Projection( source, pop, sim.FromListConnector([]), sim.StructuralMechanismStatic(sim.RandomSelection(), sim.DistanceDependentFormation(), sim.RandomByWeightElimination(0.5))) with pytest.raises(SynapticConfigurationException): sim.run(100)
def test_set_v(self): sim.setup(timestep=1) if_curr = sim.Population(1, sim.IF_curr_exp()) ssa = sim.Population(1, sim.SpikeSourceArray(spike_times=[0])) ssp = sim.Population(2, sim.SpikeSourcePoisson(rate=100.0), additional_parameters={"seed": 1}) if_curr.record("v") try: ssa.record("v") except Exception as e: self.assertEqual( "This population does not support the recording of v!", str(e)) try: ssp.record("v") except Exception as e: self.assertEqual( "This population does not support the recording of v!", str(e)) sim.end()
def test_set_v(self): sim.setup(timestep=1) if_curr = sim.Population(1, sim.IF_curr_exp()) ssa = sim.Population(1, sim.SpikeSourceArray(spike_times=[0])) ssp = sim.Population(2, sim.SpikeSourcePoisson(rate=100.0), additional_parameters={"seed": 1}) if_curr.record("v") # SpikeSourceArray must throw if asked to record voltage with self.assertRaises(Exception) as e: ssa.record("v") self.assertEqual( "This population does not support the recording of v!", str(e.exception)) # SpikeSourcePoisson must throw if asked to record voltage with self.assertRaises(Exception) as e: ssp.record("v") self.assertEqual( "This population does not support the recording of v!", str(e.exception)) sim.end()
def poisson_live_rates(self): self._saved_label_init = None self._saved_vertex_size = None self._saved_run_time_ms = None self._saved_machine_timestep_ms = None self._saved_label_set = None self._saved_label_stop = None def init(label, vertex_size, run_time_ms, machine_timestep_ms): self._saved_label_init = label self._saved_vertex_size = vertex_size self._saved_run_time_ms = run_time_ms self._saved_machine_timestep_ms = machine_timestep_ms def set_rates(label, conn): time.sleep(1.0) conn.set_rates(label, [(i, 50) for i in range(50)]) self._saved_label_set = label def stop(label, _conn): self._saved_label_stop = label n_neurons = 100 timestep = 1.0 runtime = 2000 sim.setup(timestep=timestep) sim.set_number_of_neurons_per_core(sim.SpikeSourcePoisson, 75) pop_label = "pop_to_control" pop = sim.Population(n_neurons, sim.SpikeSourcePoisson(rate=0.0), label=pop_label, additional_parameters={"max_rate": 50.0}) pop.record("spikes") conn = sim.external_devices.SpynnakerPoissonControlConnection( poisson_labels=[pop_label], local_port=None) conn.add_start_resume_callback(pop_label, set_rates) conn.add_init_callback(pop_label, init) conn.add_pause_stop_callback(pop_label, stop) with self.assertRaises(ConfigurationException): conn.add_receive_callback(pop_label, stop) sim.external_devices.add_database_socket_address( conn.local_ip_address, conn.local_port, None) sim.external_devices.add_poisson_live_rate_control(pop) sim.run(runtime) neo = pop.get_data("spikes") spikes = neo.segments[0].spiketrains sim.end() count_0_49 = 0 for a_spikes in spikes[0:50]: count_0_49 += len(a_spikes) count_50_99 = 0 for a_spikes in spikes[50:100]: count_50_99 += len(a_spikes) tolerance = math.sqrt(50.0) self.assertAlmostEqual(50.0, count_0_49 / 50.0, delta=tolerance) self.assertEqual(count_50_99, 0.0) self.assertEqual(self._saved_label_set, pop_label) self.assertEqual(self._saved_label_init, pop_label) self.assertEqual(self._saved_label_stop, pop_label) self.assertEqual(self._saved_machine_timestep_ms, timestep) self.assertEqual(self._saved_vertex_size, n_neurons) self.assertEqual(self._saved_run_time_ms, runtime)
def do_run(seed=None): random.seed(seed) # SpiNNaker setup sim.setup(timestep=1.0, min_delay=1.0, max_delay=10.0) # +-------------------------------------------------------------------+ # | General Parameters | # +-------------------------------------------------------------------+ # Population parameters model = sim.IF_curr_exp cell_params = { 'cm': 0.25, 'i_offset': 0.0, 'tau_m': 10.0, 'tau_refrac': 2.0, 'tau_syn_E': 2.5, 'tau_syn_I': 2.5, 'v_reset': -70.0, 'v_rest': -65.0, 'v_thresh': -55.4 } # Other simulation parameters e_rate = 200 in_rate = 350 n_stim_test = 5 n_stim_pairing = 10 dur_stim = 20 pop_size = 40 ISI = 150. start_test_pre_pairing = 200. start_pairing = 1500. start_test_post_pairing = 700. simtime = start_pairing + start_test_post_pairing + \ ISI*(n_stim_pairing + n_stim_test) + 550. # let's make it 5000 # Initialisations of the different types of populations IAddPre = [] IAddPost = [] # +-------------------------------------------------------------------+ # | Creation of neuron populations | # +-------------------------------------------------------------------+ # Neuron populations pre_pop = sim.Population(pop_size, model(**cell_params)) post_pop = sim.Population(pop_size, model(**cell_params)) # Test of the effect of activity of the pre_pop population on the post_pop # population prior to the "pairing" protocol : only pre_pop is stimulated for i in range(n_stim_test): IAddPre.append( sim.Population( pop_size, sim.SpikeSourcePoisson(rate=in_rate, start=start_test_pre_pairing + ISI * (i), duration=dur_stim, seed=random.randint(0, 100000000)))) # Pairing protocol : pre_pop and post_pop are stimulated with a 10 ms # difference for i in range(n_stim_pairing): IAddPre.append( sim.Population( pop_size, sim.SpikeSourcePoisson(rate=in_rate, start=start_pairing + ISI * (i), duration=dur_stim, seed=random.randint(0, 100000000)))) IAddPost.append( sim.Population( pop_size, sim.SpikeSourcePoisson(rate=in_rate, start=start_pairing + ISI * (i) + 10., duration=dur_stim, seed=random.randint(0, 100000000)))) # Test post pairing : only pre_pop is stimulated # (and should trigger activity in Post) for i in range(n_stim_test): start = start_pairing + ISI * n_stim_pairing + \ start_test_post_pairing + ISI * i IAddPre.append( sim.Population( pop_size, sim.SpikeSourcePoisson(rate=in_rate, start=start, duration=dur_stim, seed=random.randint(0, 100000000)))) # Noise inputs INoisePre = sim.Population(pop_size, sim.SpikeSourcePoisson(rate=e_rate, start=0, duration=simtime, seed=random.randint( 0, 100000000)), label="expoisson") INoisePost = sim.Population(pop_size, sim.SpikeSourcePoisson(rate=e_rate, start=0, duration=simtime, seed=random.randint( 0, 100000000)), label="expoisson") # +-------------------------------------------------------------------+ # | Creation of connections | # +-------------------------------------------------------------------+ # Connection parameters JEE = 3. # Connection type between noise poisson generator and # excitatory populations ee_connector = sim.OneToOneConnector() # Noise projections sim.Projection(INoisePre, pre_pop, ee_connector, receptor_type='excitatory', synapse_type=sim.StaticSynapse(weight=JEE * 0.05)) sim.Projection(INoisePost, post_pop, ee_connector, receptor_type='excitatory', synapse_type=sim.StaticSynapse(weight=JEE * 0.05)) # Additional Inputs projections for i in range(len(IAddPre)): sim.Projection(IAddPre[i], pre_pop, ee_connector, receptor_type='excitatory', synapse_type=sim.StaticSynapse(weight=JEE * 0.05)) for i in range(len(IAddPost)): sim.Projection(IAddPost[i], post_pop, ee_connector, receptor_type='excitatory', synapse_type=sim.StaticSynapse(weight=JEE * 0.05)) # Plastic Connections between pre_pop and post_pop stdp_model = sim.STDPMechanism( timing_dependence=sim.SpikePairRule(tau_plus=20., tau_minus=50.0, A_plus=0.02, A_minus=0.02), weight_dependence=sim.AdditiveWeightDependence(w_min=0, w_max=0.9)) rng = NumpyRNG(seed=seed, parallel_safe=True) plastic_projection = \ sim.Projection(pre_pop, post_pop, sim.FixedProbabilityConnector( p_connect=0.5, rng=rng), synapse_type=stdp_model) # +-------------------------------------------------------------------+ # | Simulation and results | # +-------------------------------------------------------------------+ # Record spikes and neurons' potentials pre_pop.record(['v', 'spikes']) post_pop.record(['v', 'spikes']) # Run simulation sim.run(simtime) weights = plastic_projection.get('weight', 'list') pre_spikes = neo_convertor.convert_spikes(pre_pop.get_data('spikes')) post_spikes = neo_convertor.convert_spikes(post_pop.get_data('spikes')) # End simulation on SpiNNaker sim.end() return (pre_spikes, post_spikes, weights)
'tau_syn_E': tauSyn, 'tau_syn_I': tauSyn, 'i_offset': 0.9 } # Set-up pynn Populations E_pop = pynn.Population(N_E, pynn.IF_curr_exp(**exc_cell_params), label="E_pop") I_pop = pynn.Population(N_I, pynn.IF_curr_exp(**inh_cell_params), label="I_pop") Poiss_ext_E = pynn.Population(N_E, pynn.SpikeSourcePoisson(rate=10.0), label="Poisson_pop_E") Poiss_ext_I = pynn.Population(N_I, pynn.SpikeSourcePoisson(rate=10.0), label="Poisson_pop_I") # Connectors E_conn = pynn.FixedProbabilityConnector(epsilon) I_conn = pynn.FixedProbabilityConnector(epsilon) # Use random delays for the external noise and # set the inital membrance voltage below the resting potential # to avoid the overshoot of activity in the beginning of the simulation rng = NumpyRNG(seed=1) delay_distr = RandomDistribution('uniform', low=1.0, high=16.0, rng=rng) Ext_conn = pynn.OneToOneConnector()
def run_script(simtime, n_neurons, run_split=1, record_spikes=False, spike_rate=None, spike_rec_indexes=None, spike_get_indexes=None, record_v=False, v_rate=None, v_rec_indexes=None, v_get_indexes=None, record_exc=False, exc_rate=None, exc_rec_indexes=None, exc_get_indexes=None, record_inh=False, inh_rate=None, inh_rec_indexes=None, inh_get_indexes=None, file_prefix=""): sim.setup(timestep=1) pop_1 = sim.Population(n_neurons, sim.IF_curr_exp(), label="pop_1") input1 = sim.Population(1, sim.SpikeSourceArray(spike_times=[0]), label="input") sim.Projection(input1, pop_1, sim.AllToAllConnector(), synapse_type=sim.StaticSynapse(weight=5, delay=1)) input2 = sim.Population(n_neurons, sim.SpikeSourcePoisson(rate=100.0), label="Stim_Exc", additional_parameters={"seed": 1}) sim.Projection(input2, pop_1, sim.OneToOneConnector(), synapse_type=sim.StaticSynapse(weight=5, delay=1)) if record_spikes: if spike_rec_indexes is None: pop_1.record(['spikes'], sampling_interval=spike_rate) else: view = PopulationView(pop_1, spike_rec_indexes) view.record(['spikes'], sampling_interval=spike_rate) if record_v: if v_rec_indexes is None: pop_1.record(['v'], sampling_interval=v_rate) else: view = PopulationView(pop_1, v_rec_indexes) view.record(['v'], sampling_interval=v_rate) if record_exc: if exc_rec_indexes is None: pop_1.record(['gsyn_exc'], sampling_interval=exc_rate) else: view = PopulationView(pop_1, exc_rec_indexes) view.record(['gsyn_exc'], sampling_interval=exc_rate) if record_inh: if inh_rec_indexes is None: pop_1.record(['gsyn_inh'], sampling_interval=inh_rate) else: view = PopulationView(pop_1, inh_rec_indexes) view.record(['gsyn_inh'], sampling_interval=inh_rate) for i in range(run_split): sim.run(simtime / run_split) if record_spikes: if spike_get_indexes is None: neo = pop_1.get_data("spikes") else: view = PopulationView(pop_1, spike_get_indexes) neo = view.get_data("spikes") spikes = neo.segments[0].spiketrains spike_file = os.path.join(current_file_path, file_prefix + "spikes.csv") write_spikes(spikes, spike_file) else: spikes = None if record_v: if v_get_indexes is None: neo = pop_1.get_data("v") else: view = PopulationView(pop_1, v_get_indexes) neo = view.get_data("v") v = neo.segments[0].filter(name='v')[0] v_file = os.path.join(current_file_path, file_prefix + "v.csv") numpy.savetxt(v_file, v, delimiter=',') else: v = None if record_exc: if exc_get_indexes is None: neo = pop_1.get_data('gsyn_exc') else: view = PopulationView(pop_1, exc_get_indexes) neo = view.get_data('gsyn_exc') exc = neo.segments[0].filter(name='gsyn_exc')[0] exc_file = os.path.join(current_file_path, file_prefix + "exc.csv") numpy.savetxt(exc_file, exc, delimiter=',') else: exc = None if record_inh: if inh_get_indexes is None: neo = pop_1.get_data('gsyn_inh') else: view = PopulationView(pop_1, inh_get_indexes) neo = view.get_data('gsyn_inh') inh = neo.segments[0].filter(name='gsyn_inh')[0] inh_file = os.path.join(current_file_path, file_prefix + "inh.csv") numpy.savetxt(inh_file, inh, delimiter=',') else: inh = None sim.end() return spikes, v, exc, inh
p.StaticSynapse(weight=0.09)) null_pop.record(['spikes', 'v', 'gsyn_exc']) # null_pop.record(['spikes', 'v']) # null_pops = [] # for i in range(4*number_of_bins): # null_pops.append(p.Population(1, p.IF_cond_exp(), # label='null {}'.format(i))) # null_pops[i].record(['spikes', 'v']) # p.Projection(pendulum, null_pops[i], # p.FromListConnector([[i, 0, weight, 1]])) arm_collection = [] # input_spikes = [] rate = 5 print('rate = ', rate) input_spikes = p.Population(force_increments, p.SpikeSourcePoisson(rate=rate)) p.Projection(input_spikes, pendulum, p.AllToAllConnector(), p.StaticSynapse()) weight = 0.1 label = '64 0.55' from_list_conn_left = [[0, 0, weight, 1], [6, 0, weight, 1], [3, 0, weight, 1], [11, 0, weight, 1]] from_list_conn_right = [[2, 0, weight, 1], [8, 0, weight, 1], [5, 0, weight, 1], [9, 0, weight, 1]] left = 0 right = 1 from_list_conn_out = [[0, left, weight, 1], [6, left, weight, 1], [3, left, weight, 1], [11, left, weight, 1], [2, right, weight, 1], [8, right, weight, 1], [5, right, weight, 1], [9, right, weight, 1]] output_pop = p.Population( outputs, p.IF_cond_exp(
def spinn_net(): np.random.seed(272727) global output_labels global input_labels p.setup(timestep=1.0, min_delay=1, max_delay=60) p.set_number_of_neurons_per_core(p.IF_cond_exp, 64) n_pop_labels = [] n_pop_list = [] n_proj_list = [] spike_source_list = [] if offset != 0: for i in range(2): del output_labels[0] for i in range(2): del input_labels[0] for i in range(no_neuron_pops): #set up the input as a live spike source if i < 2: n_pop_labels.append("Input_pop{}".format(i)) input_labels.append("Input_pop{}".format(i)) n_pop_list.append( p.Population(pop_sizes[i], p.SpikeSourcePoisson(rate=poisson_rate), label=n_pop_labels[i])) n_pop_list[i].record(["spikes"]) p.external_devices.add_poisson_live_rate_control( n_pop_list[i], database_notify_port_num=(160+offset)) #set up output pop elif i < 4: n_pop_labels.append("Output_pop{}".format(i)) output_labels.append("Output_pop{}".format(i)) n_pop_list.append(p.Population(pop_sizes[i], p.IF_cond_exp(), label=n_pop_labels[i])) p.external_devices.activate_live_output_for( n_pop_list[i], database_notify_port_num=(180+offset), port=(17000+offset)) spike_source_list.append(p.Population(pop_sizes[i], p.SpikeSourcePoisson(rate=0.0), label="source ".format(n_pop_labels[i]))) n_pop_list[i].record(["spikes", "v"]) #set up all other populations else: n_pop_labels.append("neuron{}".format(i)) n_pop_list.append(p.Population(pop_sizes[i], p.IF_cond_exp(), label=n_pop_labels[i])) spike_source_list.append(p.Population(pop_sizes[i], p.SpikeSourcePoisson(rate=0.0), label="source ".format(n_pop_labels[i]))) n_pop_list[i].record(["spikes", "v"]) poisson_control = p.external_devices.SpynnakerPoissonControlConnection( poisson_labels=input_labels, local_port=(160+offset)) poisson_control.add_start_callback(n_pop_list[0].label, from_list_poisson) # poisson_control.add_start_callback(n_pop_list[1].label, poisson_setting) # poisson_control.add_start_callback(n_pop_list[0].label, poisson_threading) live_connection = p.external_devices.SpynnakerLiveSpikesConnection( receive_labels=output_labels, local_port=(180+offset)) live_connection.add_receive_callback(n_pop_labels[2], receive_spikes) live_connection.add_receive_callback(n_pop_labels[3], receive_spikes) # weight_mu = 0.015 # weight_sdtev = 0.05 # delay_mu = 40 # delay_sdtev = 5 for i in range(no_neuron_pops): np.random.seed(272727) weights = RandomDistribution("normal_clipped", mu=weight_mu[i], sigma=weight_stdev[i], low=0, high=np.inf) delays = RandomDistribution("normal_clipped", mu=delay_mu[i], sigma=delay_stdev[i], low=1, high=55) synapse = p.StaticSynapse(weight=weights, delay=delays) for j in range(2, no_neuron_pops): print "\npop = {}({}) connecting to {}".format(i,pop_sizes[i],j) if connect_prob_ex[i][j-2] > 1e-10: print "ex = {}\tin = {}".format(connect_prob_ex[i][j-2], connect_prob_in[i][j-2]) print "\tweight mu = {}\t stdev = {}".format(weight_mu[i], weight_stdev[i]) print "\tdelay mu = {}\t stdev = {}".format(delay_mu[i], delay_stdev[i]) n_proj_list.append( p.Projection(n_pop_list[i], n_pop_list[j], p.FixedProbabilityConnector(connect_prob_ex[i][j-2]),#p.OneToOneConnector(),# synapse, receptor_type="excitatory")) n_proj_list.append( p.Projection(n_pop_list[i], n_pop_list[j], p.FixedProbabilityConnector(connect_prob_in[i][j-2]),#p.OneToOneConnector(),# synapse, receptor_type="inhibitory")) # n_proj_list.append(p.Projection(n_pop_list[i], n_pop_list[j], # p.FixedProbabilityConnector(1), # synapse, receptor_type="inhibitory")) run = 0 p.run(duration/timeScaleFactor) print "finished 1st" run = 1 p.reset() p.run(duration/timeScaleFactor) total_v = list() spikes = list() v = list() spikes.append(n_pop_list[0].get_data("spikes")) spikes.append(n_pop_list[1].get_data("spikes")) for j in range(2,no_neuron_pops): spikes.append(n_pop_list[j].get_data("spikes")) v.append(n_pop_list[j].get_data("v")) Figure( # raster plot of the presynaptic neuron spike times Panel(spikes[0].segments[0].spiketrains, yticks=True, markersize=2, xlim=(0, duration)), Panel(spikes[1].segments[0].spiketrains, yticks=True, markersize=2, xlim=(0, duration)), Panel(spikes[2].segments[0].spiketrains, yticks=True, markersize=2, xlim=(0, duration)), Panel(spikes[3].segments[0].spiketrains, yticks=True, markersize=2, xlim=(0, duration)), # Panel(spikes[4].segments[0].spiketrains, # yticks=True, markersize=2, xlim=(0, duration)), # Panel(spikes[no_neuron_pops-2].segments[0].spiketrains, # yticks=True, markersize=2, xlim=(0, duration)), # Panel(spikes[no_neuron_pops-1].segments[0].spiketrains, # yticks=True, markersize=2, xlim=(0, duration)), title="Raster plot", annotations="Simulated with {}".format(p.name()) ) plt.show() Figure( #membrane voltage plots Panel(v[0].segments[0].filter(name='v')[0], ylabel="Membrane potential (mV)", yticks=True, xlim=(0, duration)), Panel(v[1].segments[0].filter(name='v')[0], ylabel="Membrane potential (mV)", yticks=True, xlim=(0, duration)), Panel(v[2].segments[0].filter(name='v')[0], ylabel="Membrane potential (mV)", yticks=True, xlim=(0, duration)), Panel(v[3].segments[0].filter(name='v')[0], ylabel="Membrane potential (mV)", yticks=True, xlim=(0, duration)), # Panel(v[4].segments[0].filter(name='v')[0], # ylabel="Membrane potential (mV)", yticks=True, xlim=(0, duration)), # Panel(v[no_neuron_pops-4].segments[0].filter(name='v')[0], # ylabel="Membrane potential (mV)", yticks=True, xlim=(0, duration)), # Panel(v[no_neuron_pops-3].segments[0].filter(name='v')[0], # ylabel="Membrane potential (mV)", yticks=True, xlim=(0, duration)), title="Membrane voltage plot", ) plt.show() # p.reset() p.end() poisson_control.close() live_connection.close() print "finished run"
# Create an excitatory population with 80% of the neurons and # an inhibitory population with 20% of the neurons. pop_exc = sim.Population(n_exc, sim.IF_curr_exp(), label="Excitatory") pop_inh = sim.Population(n_inh, sim.IF_curr_exp(), label="Inhibitory") # Create excitatory poisson stimulation population with 80% # of the neurons and # an inhibitory poisson stimulation population with 20% of the neurons, # both with a rate of 1000Hz # TODO RATE? if rng is None: seed = None else: seed = int(rng.next() * 1000) stim_exc = sim.Population(n_exc, sim.SpikeSourcePoisson(rate=1000.0, seed=seed), label="Stim_Exc") if rng is None: seed = None else: seed = int(rng.next() * 1000) stim_inh = sim.Population(n_inh, sim.SpikeSourcePoisson(rate=1000.0, seed=int(rng.next() * 1000)), label="Stim_Inh") # Create a one-to-one excitatory connection # from the excitatory poisson stimulation population # to the excitatory population with a weight of 0.1nA and a delay of 1.0ms # TODO values
import spynnaker8 as sim import pyNN.utility.plotting as plot import matplotlib.pyplot as plt from pyNN.random import RandomDistribution n_neurons = 1000 n_exc = int(round(n_neurons * 0.8)) n_inh = int(round(n_neurons * 0.2)) simtime = 1000 sim.setup(timestep=0.1) pop_exc = sim.Population(n_exc, sim.IF_curr_exp(), label="Excitatory") pop_inh = sim.Population(n_inh, sim.IF_curr_exp(), label="Inhibitory") stim_exc = sim.Population(n_exc, sim.SpikeSourcePoisson(rate=10.0), label="Stim_Exc") stim_inh = sim.Population(n_inh, sim.SpikeSourcePoisson(rate=10.0), label="Stim_Inh") synapse_exc = sim.StaticSynapse(weight=0.2, delay=2.0) synapse_inh = sim.StaticSynapse(weight=-1.0, delay=2.0) sim.Projection(pop_exc, pop_exc, sim.FixedProbabilityConnector(0.1), synapse_type=synapse_exc, receptor_type="excitatory") sim.Projection(pop_exc, pop_inh, sim.FixedProbabilityConnector(0.1),
# === Parameters =============================================================== n_neurons = 3 # number of neurons in each population for the Spiking Neural Network in this example timestamp = 1.0 # simulate the network with 1.0 ms time steps sim_time = 100 # total simulation time # === Configure the simulator ================================================== sim.setup(timestamp) # === Build the network ======================================================== # Presynaptic population - Input layer - Stimuli pop_input = sim.Population(n_neurons, sim.SpikeSourcePoisson(rate=100, duration=sim_time), label='pop_input') # Synapse value as weight = 5.0 nA, delay = 1 ms static_synapse = sim.StaticSynapse(weight=5.0, delay=1) # I - IF_cond_exp Population pop_cond_exp = sim.Population(n_neurons, sim.IF_cond_exp, {}, label='if_cond_exp') sim.Projection(pop_input, pop_cond_exp, sim.OneToOneConnector(), synapse_type=static_synapse) # II - IF_curr_exp Population pop_curr_exp = sim.Population(n_neurons,
def test_agent(arm1, arm2): arm = [arm1, arm2] print "arm = ", arm connections = read_agent() p.setup(timestep=1.0, min_delay=1, max_delay=127) p.set_number_of_neurons_per_core(p.IF_cond_exp, 100) bandit = p.Population(len(arm), Bandit(arm, exposure_time, reward_based=reward, label='bandit_pop')) [in2e, in2i, e_size, e2e, e2i, i_size, i2e, i2i, e2out, i2out] = connections if e_size > 0: excite = p.Population(e_size, p.IF_cond_exp(), label='excite_pop') excite_noise = p.Population(e_size, p.SpikeSourcePoisson(rate=noise_rate)) p.Projection(excite_noise, excite, p.OneToOneConnector(), p.StaticSynapse(weight=noise_weight), receptor_type='excitatory') excite.record('spikes') if i_size > 0: inhib = p.Population(i_size, p.IF_cond_exp(), label='inhib_pop') inhib_noise = p.Population(i_size, p.SpikeSourcePoisson(rate=noise_rate)) p.Projection(inhib_noise, inhib, p.OneToOneConnector(), p.StaticSynapse(weight=noise_weight), receptor_type='excitatory') inhib.record('spikes') if len(in2e) != 0: p.Projection(bandit, excite, p.FromListConnector(in2e), receptor_type='excitatory') # p.Projection(starting_pistol, excite, p.FromListConnector(in2e), # receptor_type='excitatory') if len(in2i) != 0: p.Projection(bandit, inhib, p.FromListConnector(in2i), receptor_type='excitatory') # p.Projection(starting_pistol, inhib, p.FromListConnector(in2i), # receptor_type='excitatory') if len(e2e) != 0: p.Projection(excite, excite, p.FromListConnector(e2e), receptor_type='excitatory') if len(e2i) != 0: p.Projection(excite, inhib, p.FromListConnector(e2i), receptor_type='excitatory') if len(i2e) != 0: p.Projection(inhib, excite, p.FromListConnector(i2e), receptor_type='inhibitory') if len(i2i) != 0: p.Projection(inhib, inhib, p.FromListConnector(i2i), receptor_type='inhibitory') if len(e2out) != 0: p.Projection(excite, bandit, p.FromListConnector(e2out), receptor_type='excitatory') if len(i2out) != 0: p.Projection(inhib, bandit, p.FromListConnector(i2out), receptor_type='inhibitory') simulator = get_simulator() p.run(runtime) scores = get_scores(game_pop=bandit, simulator=simulator) print scores print arm e_spikes = excite.get_data('spikes').segments[0].spiketrains i_spikes = inhib.get_data('spikes').segments[0].spiketrains # v = receive_pop[i].get_data('v').segments[0].filter(name='v')[0] plt.figure("[{}, {}] - {}".format(arm1, arm2, scores)) Figure( Panel(e_spikes, xlabel="Time (ms)", ylabel="nID", xticks=True), Panel(i_spikes, xlabel="Time (ms)", ylabel="nID", xticks=True) ) plt.show() p.end()