def test_initial_value(self): sim.setup(timestep=1.0) pop = sim.Population(5, sim.IF_curr_exp(), label="pop_1") self.assertEqual([-65, -65, -65, -65, -65], pop.get_initial_value("v")) view = PopulationView(pop, [1, 3], label="Odds") view2 = PopulationView(pop, [1, 2], label="OneTwo") view_iv = view.initial_values self.assertEqual(3, len(view_iv)) self.assertEqual([-65, -65], view_iv["v"]) view.initialize(v=-60) self.assertEqual([-65, -60, -65, -60, -65], pop.get_initial_value("v")) self.assertEqual([-60, -60], view.initial_values["v"]) self.assertEqual([-60, -65], view2.initial_values["v"]) rand_distr = RandomDistribution("uniform", parameters_pos=[-65.0, -55.0], rng=NumpyRNG(seed=85524)) view.initialize(v=rand_distr) self.assertEqual([-64.43349869042906, -63.663421790102184], view.initial_values["v"]) view.initialize(v=lambda i: -65 + i / 10.0) self.assertEqual([-64.9, -64.7], view.initial_values["v"]) sim.end()
def test_view_of_view(self): n_neurons = 10 sim.setup(timestep=1.0) pop_1 = sim.Population(n_neurons, sim.IF_curr_exp(), label="pop_1") view1 = PopulationView(pop_1, [1, 3, 5, 7, 9], label="Odds") view2 = PopulationView(view1, [1, 3], label="AlternativeOdds") # Not a normal way to access but good to test self.assertEqual((3, 7), view2._indexes) self.assertEqual(view2.parent, view1) self.assertEqual(view1.grandparent, pop_1) self.assertEqual(view2.grandparent, pop_1) cells = view2.all_cells self.assertEqual(3, cells[0].id) self.assertEqual(7, cells[1].id) self.assertEqual(3, view1.id_to_index(7)) self.assertEqual([3, 0], view1.id_to_index([7, 1])) self.assertEqual(1, view2.id_to_index(7)) view3 = view1[1:3] self.assertEqual((3, 5), view3._indexes) view4 = view1.sample(2) self.assertEqual(2, len(view4._indexes)) sim.end()
def do_run(nNeurons): p.setup(timestep=1.0, min_delay=1.0) cell_params_lif_in = { 'tau_m': 333.33, 'cm': 208.33, 'v': [0.0, 0.0146789550781, 0.029296875, 0.0438842773438, 0.0584106445312], 'v_rest': 0.1, 'v_reset': 0.0, 'v_thresh': 1.0, 'tau_syn_E': 1, 'tau_syn_I': 2, 'tau_refrac': 2.5, 'i_offset': 3.0 } pop1 = p.Population(nNeurons, p.IF_curr_exp, cell_params_lif_in, label='pop_0') pop1.record("v") pop1.record("gsyn_exc") pop1.record("spikes") p.run(100) neo = pop1.get_data(["v", "spikes", "gsyn_exc"]) v = neo_convertor.convert_data(neo, name="v") gsyn = neo_convertor.convert_data(neo, name="gsyn_exc") spikes = neo_convertor.convert_spikes(neo) p.end() return (v, gsyn, spikes)
def do_run(n_neurons, n_cores, i_offset2, i_offset3): p.setup(timestep=1.0, min_delay=1.0) p.set_number_of_neurons_per_core(p.IF_curr_exp, n_neurons / n_cores) cell_params_lif = { 'cm': 0.25, 'i_offset': 0.0, 'tau_m': 20.0, 'tau_refrac': 2.0, 'tau_syn_E': 5.0, 'tau_syn_I': 5.0, 'v_reset': -70.0, 'v_rest': -65.0, 'v_thresh': -50.0 } populations = list() populations.append( p.Population(n_neurons, p.IF_curr_exp, cell_params_lif, label='pop_1')) populations[0].record("spikes") p.run(100) populations[0].set(i_offset=i_offset2) p.run(100) populations[0].set(i_offset=i_offset3) p.run(100) neo = populations[0].get_data() p.end() return neo
def multi_board_spike_output(self): TestMultiBoardSpikeOutput.counts = dict() try: p.setup(1.0, n_chips_required=((48 * 2) + 1)) machine = p.get_machine() except ConfigurationException as oops: if "Failure to detect machine of " in str(oops): raise SkipTest( "You Need at least 3 boards to run this test") from oops labels = list() for chip in machine.ethernet_connected_chips: # print("Adding population on {}, {}".format(chip.x, chip.y)) label = "{}, {}".format(chip.x, chip.y) labels.append(label) pop = p.Population( 10, p.SpikeSourceArray(spike_times=[i for i in range(100)]), label=label) pop.add_placement_constraint(chip.x, chip.y) e.activate_live_output_for(pop) TestMultiBoardSpikeOutput.counts[label] = 0 live_output = e.SpynnakerLiveSpikesConnection( receive_labels=labels, local_port=None) p.external_devices.add_database_socket_address( live_output.local_ip_address, live_output.local_port, None) for label in labels: live_output.add_receive_callback( label, TestMultiBoardSpikeOutput.spike_receiver) p.run(250) live_output.close() p.end() for label in labels: # print("Received {} of 1000 spikes from {}".format( # TestMultiBoardSpikeOutput.counts[label], label)) self.assertEqual(TestMultiBoardSpikeOutput.counts[label], 1000)
def multi_board_spike_output(self): TestMultiBoardSpikeOutput.counts = dict() p.setup(1.0, n_chips_required=((48 * 2) + 1)) try: machine = p.get_machine() except ConfigurationException as ex: raise SkipTest(ex) labels = list() pops = list() for chip in machine.ethernet_connected_chips: # print("Adding population on {}, {}".format(chip.x, chip.y)) label = "{}, {}".format(chip.x, chip.y) spike_cells = {"spike_times": [i for i in range(100)]} pop = p.Population(10, p.SpikeSourceArray(**spike_cells), label=label) pop.add_placement_constraint(chip.x, chip.y) labels.append(label) pops.append(pop) TestMultiBoardSpikeOutput.counts[label] = 0 live_output = p.external_devices.SpynnakerLiveSpikesConnection( receive_labels=labels, local_port=None) for label, pop in zip(labels, pops): p.external_devices.activate_live_output_for( pop, database_notify_port_num=live_output.local_port) live_output.add_receive_callback( label, TestMultiBoardSpikeOutput.spike_receiver) p.run(1000) p.end() for label in labels: # print("Received {} of 1000 spikes from {}".format( # TestMultiBoardSpikeOutput.counts[label], label)) self.assertEqual(TestMultiBoardSpikeOutput.counts[label], 1000)
def build_page_rank_graph(self, vertices, edges, atoms_per_core=None, page_rank_kwargs=None): """Create a sPyNNaker simulation graph from the Page Rank input graph. Maps the graph to sPyNNaker. :return: None """ # Pre-processing, compute inbound / outbound edges for each node n_neurons = len(vertices) outgoing_edges_count = [0] * n_neurons incoming_edges_count = [0] * n_neurons for src, tgt in edges: outgoing_edges_count[src] += 1 incoming_edges_count[tgt] += 1 # Vertices self._model = p.Population( n_neurons, Page_Rank(rank_init=1. / n_neurons, incoming_edges_count=incoming_edges_count, outgoing_edges_count=outgoing_edges_count, **(page_rank_kwargs or {})), label="page_rank") if atoms_per_core: p.set_number_of_neurons_per_core(atoms_per_core) # Edges p.Projection(self._model, self._model, p.FromListConnector(edges), synapse_type=SynapseDynamicsNoOp())
def test_recordable_spike_injector(): p.setup(1.0) pop = p.Population(n_neurons, p.external_devices.SpikeInjector(), label="input") pop.record("spikes") connection = p.external_devices.SpynnakerLiveSpikesConnection( send_labels=["input"]) connection.add_start_callback("input", _inject) p.run(10000) spikes = pop.get_data("spikes").segments[0].spiketrains p.end() spike_trains = dict() for spiketrain in spikes: i = spiketrain.annotations['source_index'] if __name__ == "__main__": if n_spikes[i] != len(spiketrain): print("Incorrect number of spikes, expected {} but got {}:". format(n_spikes[i], len(spiketrain))) print(spiketrain) else: assert n_spikes[i] == len(spiketrain) spike_trains[i] = spiketrain for (index, count) in iteritems(n_spikes): if __name__ == "__main__": if index not in spike_trains: print( "Neuron {} should have spiked {} times but didn't".format( index, count)) else: assert index in spike_trains
def variable_rate_100us(): """ Test that the source works at 0.1ms timesteps """ rates = [1, 10, 100] starts = [0, 1000, 1500] ends = [1000, 1500, 2000] p.setup(0.1) pop = p.Population(100, p.extra_models.SpikeSourcePoissonVariable( rates=rates, starts=starts), additional_parameters={"seed": 0}) pop.record("spikes") run_time = 2000 p.run(run_time) spikes = pop.get_data("spikes").segments[0].spiketrains p.end() n_spikes = dict() for i in range(len(spikes)): for rate, start, end in zip(rates, starts, ends): rate_spikes = spikes[i][(spikes[i] >= start) & (spikes[i] < end)] if (rate, start, end) not in n_spikes: n_spikes[rate, start, end] = len(rate_spikes) else: n_spikes[rate, start, end] += len(rate_spikes) for rate, start, end in n_spikes: expected = (rate / 1000.0) * (end - start) tolerance = scipy.stats.poisson.ppf(0.99, expected) - expected n_spikes_rate = n_spikes[rate, start, end] / 100.0 print("Received {} spikes, expected {} spikes" " (with tolerance {}) for rate {}" " for duration {}".format(n_spikes_rate, expected, tolerance, rate, (end - start))) assert (n_spikes_rate >= (expected - tolerance)) assert (n_spikes_rate <= (expected + tolerance))
def connect_it_up(visual_input, motor_output, connections, width, length): visual_connections, motor_conn = connections layers = len(motor_conn) all_pops = [] hidden_pops = [] for layer in range(layers): motor_conn_e, motor_conn_i = motor_conn[layer] # hidden_pop = sim.Population(width * length, sim.IF_curr_exp(), label="hidden_pop_{}".format(layer)) # hidden_pops.append(hidden_pop) for i in range(width * length): hidden_pop = sim.Population(1, sim.IF_curr_exp(tau_refrac=3), label="hidden_pop_{}_{}".format( layer, i)) if simulate: hidden_pop.record(["spikes", "v"]) hidden_pops.append(hidden_pop) list_of_lists = segment_hidden_pop(visual_connections[layer], width, length, False) for i in range(len(list_of_lists)): split_the_from_list(visual_input, hidden_pops[i], list_of_lists[i]) list_of_lists = segment_hidden_pop(motor_conn_e, width, length, True) for i in range(len(list_of_lists)): split_the_from_list(hidden_pops[i], motor_output, list_of_lists[i]) list_of_lists = segment_hidden_pop(motor_conn_i, width, length, True) for i in range(len(list_of_lists)): split_the_from_list(hidden_pops[i], motor_output, list_of_lists[i], receptor_type="inhibitory") # split_the_from_list(visual_input, hidden_pop, visual_connections[layer]) # split_the_from_list(hidden_pop, motor_output, motor_conn_e) # split_the_from_list(hidden_pops[layer], motor_output, motor_conn_i, receptor_type="inhibitory") all_pops.append(hidden_pops) print "finished connecting" return all_pops
def do_run(plot): p.setup(timestep=1.0, min_delay=1.0, max_delay=144.0) p.set_number_of_neurons_per_core(p.IF_cond_exp, 100) # Experiment Parameters rng = pyNN.random.NumpyRNG(seed=124578) n_groups = 6 # Number of Synfire Groups n_exc = 100 # Number of excitatory neurons per group n_inh = 25 # Number of inhibitory neurons per group sim_duration = 500. # defining the initial pulse-packet pp_a = 5 # Nr of pulses in the packet pp_sigma = 5.0 # sigma of pulse-packet pp_start = 50. # start = center of pulse-packet # Neuron Parameters as in Kremkow et al. paper cell_params = {'cm': 0.290, # nF 'tau_m': 290.0/29.0, # pF / nS = ms 'v_rest': -70.0, # mV 'v_thresh': -57.0, # mV 'tau_syn_E': 1.5, # ms 'tau_syn_I': 10.0, # ms 'tau_refrac': 2.0, # ms 'v_reset': -70.0, # mV 'e_rev_E': 0.0, # mV 'e_rev_I': -75.0, # mV } weight_exc = 0.001 # uS weight for excitatory to excitatory connections weight_inh = 0.002 # uS weight for inhibitory to excitatory connections # list of excitatory populations exc_pops = [] # list of inhibitory populations inh_pops = [] # and Assembly of all populations all_populations = [] # Create Groups print("Creating ", n_groups, " SynfireGroups") for group_index in range(n_groups): # create the excitatory Population exc_pop = p.Population(n_exc, p.IF_cond_exp(**cell_params), label=("pop_exc_%s" % group_index)) exc_pops.append(exc_pop) # append to excitatory populations all_populations += [exc_pop] # and to the Assembly # create the inhibitory Population inh_pop = p.Population(n_inh, p.IF_cond_exp(**cell_params), label=("pop_inh_%s" % group_index)) inh_pops.append(inh_pop) all_populations += [inh_pop] # connect Inhibitory to excitatory Population p.Projection(inh_pop, exc_pop, p.AllToAllConnector(), synapse_type=p.StaticSynapse(weight=weight_inh, delay=8.), receptor_type='inhibitory') # Create Stimulus and connect it to first group print("Create Stimulus Population") # We create a Population of SpikeSourceArrays of the same dimension # as excitatory neurons in a synfire group pop_stim = p.Population(n_exc, p.SpikeSourceArray({}), label="pop_stim") # We create a normal distribution around pp_start with sigma = pp_sigma rd = pyNN.random.RandomDistribution('normal', [pp_start, pp_sigma]) all_spiketimes = [] # for each cell in the population, we take pp_a values from the # random distribution for cell in range(len(pop_stim)): spiketimes = [] for pulse in range(pp_a): spiketimes.append(rd.next()) # draw from the random distribution spiketimes.sort() all_spiketimes.append(spiketimes) # convert into a numpy array all_spiketimes = numpy.array(all_spiketimes) # 'topographic' setting of parameters. # all_spiketimes must have the same dimension as the Population pop_stim.set(spike_times=all_spiketimes) # Connect Groups with the subsequent ones print("Connecting Groups with subsequent ones") for group_index in range(n_groups-1): p.Projection(exc_pops[group_index % n_groups], exc_pops[(group_index+1) % n_groups], p.FixedNumberPreConnector(60, rng=rng, with_replacement=True), synapse_type=p.StaticSynapse(weight=weight_exc, delay=10.), receptor_type='excitatory') p.Projection(exc_pops[group_index % n_groups], inh_pops[(group_index+1) % n_groups], p.FixedNumberPreConnector(60, rng=rng, with_replacement=True), synapse_type=p.StaticSynapse(weight=weight_exc, delay=10.), receptor_type='excitatory') # Make another projection for testing that connects to itself p.Projection(exc_pops[1], exc_pops[1], p.FixedNumberPreConnector(60, rng=rng, allow_self_connections=False), synapse_type=p.StaticSynapse(weight=weight_exc, delay=10.), receptor_type='excitatory') # Connect the Stimulus to the first group print("Connecting Stimulus to first group") p.Projection(pop_stim, inh_pops[0], p.FixedNumberPreConnector(20, rng=rng), synapse_type=p.StaticSynapse(weight=weight_exc, delay=20.), receptor_type='excitatory') p.Projection(pop_stim, exc_pops[0], p.FixedNumberPreConnector(60, rng=rng), synapse_type=p.StaticSynapse(weight=weight_exc, delay=20.), receptor_type='excitatory') # Recording spikes pop_stim.record('spikes') for pop in all_populations: pop.record('spikes') # Run print("Run the simulation") p.run(sim_duration) # Get data print("Simulation finished, now collect all spikes and plot them") stim_spikes = pop_stim.spinnaker_get_data('spikes') stim_spikes[:, 0] -= n_exc # collect all spikes and make a raster_plot spklist_exc = [] spklist_inh = [] for group in range(n_groups): EXC_spikes = exc_pops[group].spinnaker_get_data('spikes') INH_spikes = inh_pops[group].spinnaker_get_data('spikes') EXC_spikes[:, 0] += group*(n_exc+n_inh) INH_spikes[:, 0] += group*(n_exc+n_inh) + n_exc spklist_exc += EXC_spikes.tolist() spklist_inh += INH_spikes.tolist() # Plot if plot: pylab.figure() pylab.plot([i[1] for i in spklist_exc], [i[0] for i in spklist_exc], "r.") pylab.plot([i[1] for i in spklist_inh], [i[0] for i in spklist_inh], "b.") pylab.plot([i[1] for i in stim_spikes], [i[0] for i in stim_spikes], "k.") pylab.xlabel('Time/ms') pylab.ylabel('spikes') pylab.title('spikes') for group in range(n_groups): pylab.axhline(y=(group+1)*(n_exc+n_inh), color="lightgrey") pylab.axhline(y=(group+1)*(n_exc+n_inh)-n_inh, color="lightgrey") pylab.axhline(y=0, color="grey", linewidth=1.5) pylab.show() p.end() return stim_spikes, spklist_exc, spklist_inh
def do_run(nNeurons): p.setup(timestep=1.0, min_delay=1.0, max_delay=144.0) p.set_number_of_neurons_per_core(p.IF_curr_exp, nNeurons / 2) cell_params_lif = {'cm': 0.25, 'i_offset': 0.0, 'tau_m': 20.0, 'tau_refrac': 2.0, 'tau_syn_E': 5.0, 'tau_syn_I': 5.0, 'v_reset': -70.0, 'v_rest': -65.0, 'v_thresh': -50.0 } p.set_number_of_neurons_per_core(p.IF_cond_exp, nNeurons / 2) cell_params_cond = {'cm': 0.25, 'i_offset': 0.0, 'tau_m': 20.0, 'tau_refrac': 2.0, 'tau_syn_E': 5.0, 'tau_syn_I': 5.0, 'v_reset': -70.0, 'v_rest': -65.0, 'v_thresh': -50.0, 'e_rev_E': 0., 'e_rev_I': -80. } p.set_number_of_neurons_per_core(p.Izhikevich, 100) cell_params_izk = {'a': 0.02, 'b': 0.2, 'c': -65, 'd': 8, 'v_init': -75, 'u_init': 0, 'tau_syn_E': 2, 'tau_syn_I': 2, 'i_offset': 0 } populations = list() projections = list() current_weight_to_spike = 2.0 cond_weight_to_spike = 0.035 delay = 17 # different strangths of connection curr_injection_connection = [(0, 0, current_weight_to_spike, delay)] cond_injection_connection = [(0, 0, cond_weight_to_spike, delay)] izk_injection_connection = [(0, 0, current_weight_to_spike, delay)] sinkConnection = [(0, 0, 0, 1)] # spike time spikeArray = {'spike_times': [[0]]} # curr set up populations.append(p.Population(nNeurons, p.IF_cond_exp, cell_params_cond, label='pop_cond')) # cond setup populations.append(p.Population(nNeurons, p.IF_curr_exp, cell_params_lif, label='pop_curr')) # izk setup populations.append(p.Population(nNeurons, p.Izhikevich, cell_params_izk, label='izk pop')) # sink pop for spikes to go to (otherwise they are not recorded as firing) populations.append(p.Population(nNeurons, p.IF_curr_exp, cell_params_lif, label='sink_pop')) populations.append(p.Population(1, p.SpikeSourceArray, spikeArray, label='inputSpike')) pop = p.Projection(populations[4], populations[0], p.FromListConnector(cond_injection_connection)) projections.append(pop) pop = p.Projection(populations[4], populations[1], p.FromListConnector(curr_injection_connection)) projections.append(pop) pop = p.Projection(populations[4], populations[2], p.FromListConnector(izk_injection_connection)) projections.append(pop) projections.append(p.Projection(populations[2], populations[3], p.FromListConnector(sinkConnection))) projections.append(p.Projection(populations[1], populations[3], p.FromListConnector(sinkConnection))) projections.append(p.Projection(populations[0], populations[3], p.FromListConnector(sinkConnection))) # record stuff for cond populations[0].record("v") populations[0].record("gsyn_exc") populations[0].record("spikes") # record stuff for curr populations[1].record("v") populations[1].record("gsyn_exc") populations[1].record("spikes") # record stuff for izk populations[2].record("v") populations[2].record("gsyn_exc") populations[2].record("spikes") p.run(500) # get cond neo = populations[0].get_data(["v", "spikes", "gsyn_exc"]) cond_v = neo_convertor.convert_data(neo, name="v") cond_gsyn = neo_convertor.convert_data(neo, name="gsyn_exc") cond_spikes = neo_convertor.convert_spikes(neo) # get curr neo = populations[1].get_data(["v", "spikes", "gsyn_exc"]) curr_v = neo_convertor.convert_data(neo, name="v") curr_gsyn = neo_convertor.convert_data(neo, name="gsyn_exc") curr_spikes = neo_convertor.convert_spikes(neo) # get izk neo = populations[1].get_data(["v", "spikes", "gsyn_exc"]) izk_v = neo_convertor.convert_data(neo, name="v") izk_gsyn = neo_convertor.convert_data(neo, name="gsyn_exc") izk_spikes = neo_convertor.convert_spikes(neo) p.end() return (cond_v, cond_gsyn, cond_spikes, curr_v, curr_gsyn, curr_spikes, izk_v, izk_gsyn, izk_spikes)
'v_reset': -70.0, 'v_rest': -65.0, 'v_thresh': -55.4 } # SpiNNaker setup sim.setup(timestep=1.0, min_delay=1.0, max_delay=10.0) # Sweep times and frequencies projections = [] sim_time = 0 for t in delta_t: projections.append([]) for f in frequencies: # Neuron populations pre_pop = sim.Population(1, model(**cell_params)) post_pop = sim.Population(1, model(**cell_params)) # Stimulating populations pre_times = generate_fixed_frequency_test_data(f, start_time - 1, num_pairs + 1) post_times = generate_fixed_frequency_test_data( f, start_time + t, num_pairs) pre_stim = sim.Population( 1, sim.SpikeSourceArray(spike_times=[pre_times])) post_stim = sim.Population( 1, sim.SpikeSourceArray(spike_times=[post_times])) # Update simulation time sim_time = max(sim_time, max(max(pre_times), max(post_times)) + 100)
def create_grid(n, label, dx=1.0, dy=1.0): grid_structure = p.Grid2D(dx=dx, dy=dy, x0=0.0, y0=0.0) return p.Population(n * n, p.IF_curr_exp(**cell_params_lif), structure=grid_structure, label=label)
def _build_populations(self): """ Build Populations Two options are available for the building process: #.) Rebuild The spiking network is flattend and no time-sclices of spiketrains are accomplished This Rebuild option is afforded to receive spikes for training a deeper layer, to train the SVM classifier or for applying the testset to the network #.) Train_Layer For this instance, only two populations have to be built: the first population represents the time-scliced input (that is the over time windowed kernel); the second population is the respective kernel that are trained with STDP Rule """ if self.rc.rebuild == True: self.rc.logging.info('Mode = Rebuild') if self.rc.train_layer: # training mode, load train set self.total_simtime = self.rc.size_train_set * SIM_INTERVAL rebuild_layers = self.rc.train_layer - 1 # number of layers to rebuild elif self.rc.train_svm: self.total_simtime = self.rc.size_train_set * SIM_INTERVAL rebuild_layers = self.model.number_layers else: # load test set self.total_simtime = self.rc.size_test_set * SIM_INTERVAL rebuild_layers = self.model.number_layers self.populations = [] size_input = reduce(lambda x, y: x * y, self.model.input_tensor) spiketrains = algorithms.input_flattend_spikes( self.X_train, self.model.input_tensor, self.model.layers[1].shape) pop = s.Population(size_input, s.SpikeSourceArray(spike_times=spiketrains), label="input_neurons") self.populations.append(pop) for i in xrange(1, rebuild_layers + 1): # remember [1,x[ -> x is excluded try: CELLS_LAYER = eval("REBUILD_LAYER_{}".format(i)) self.rc.logging.info("REBUILD_LAYER_{}".format(i)) except: raise NotImplementedError("Parameters for Layer {} \ not found in parameters.py".format(i)) size_layer = reduce(lambda x, y: x * y, self.model.tensors[i]) # size_layer = reduce(lambda x,y: x*y, TENSOR_LAYER_1) self.rc.logging.info("Size Layer {} = {}".format( i, size_layer)) self.populations.append( s.Population(size_layer, s.IF_curr_exp(**CELLS_LAYER), label="neurons_layer_{}".format(i))) if self.rc.args.debug: print("DEBUG (_build_populations) - Input Layer Spiketrains ") for i, sp in enumerate(spiketrains): print("{} - {}".format(i, sp)) elif self.rc.train_layer: """ Train a layer with STDP Rule only two populations have to be built on SpiNNaker: #.) Population that generates spikes #.) Post-Neurons which kernels are trained with STDP mechanism before this code is executed, the spike times for the generated spikes must be determined and passed to the network (deepspikes parameter) """ layer = self.rc.train_layer tensor_prev = self.model.tensors[layer - 1] tensor = self.model.tensors[layer] neurons_post = tensor[2] / tensor_prev[2] stride = self.model.layers[layer].stride kernel_shape = self.model.layers[layer].shape # calculate number of strides per input pattern windows = ( (tensor_prev[0] - tensor[0]) / stride + 1)**2 * tensor_prev[2] self.total_simtime = self.rc.size_train_set * SIM_INTERVAL * windows self.rc.logging.info('Mode = Train layer {}'.format(layer)) number_pre_neurons = kernel_shape[0] * kernel_shape[1] if layer == 1: spiketrains = algorithms.input_windowed_spikes( self.X_train, self.model.input_tensor, kernel_shape, stride) else: # layer > 1, take previously calculated spikes spiketrains = self.deep_spikes try: CELLS = eval("TRAIN_LAYER_{}".format(layer)) except: raise NotImplementedError( "Parameters for Layer {} not found in parameters.py". format(i + 1)) self.neurons_input = s.Population( number_pre_neurons, s.SpikeSourceArray(spike_times=spiketrains), label="input_neurons") self.neurons_layer = s.Population( neurons_post, s.IF_curr_exp(**CELLS), label="neurons_train_layer_{}".format(layer)) else: self.rc.logging.critical('failed to build populations') raise RuntimeError("failed to build populations ") self.rc.logging.info('Successfully built populations')
def test_asview(self): sim.setup(timestep=1.0) pop = sim.Population(4, sim.IF_curr_exp(), label=LABEL) cell = pop[2] cell.as_view()
def do_run(nNeurons, neurons_per_core): p.setup(timestep=1.0, min_delay=1.0, max_delay=32.0) p.set_number_of_neurons_per_core(p.IF_curr_exp, neurons_per_core) nPopulations = 62 cell_params_lif = {'cm': 0.25, 'i_offset': 0.0, 'tau_m': 20.0, 'tau_refrac': 2.0, 'tau_syn_E': 5.0, 'tau_syn_I': 5.0, 'v_reset': -70.0, 'v_rest': -65.0, 'v_thresh': -50.0} populations = list() projections = list() weight_to_spike = 1.5 delay = 5 for i in range(0, nPopulations): populations.append(p.Population(nNeurons, p.IF_curr_exp, cell_params_lif, label='pop_' + str(i))) # print("++++++++++++++++") # print("Added population %s" % (i)) # print("o-o-o-o-o-o-o-o-") synapse_type = p.StaticSynapse(weight=weight_to_spike, delay=delay) for i in range(0, nPopulations): projections.append(p.Projection(populations[i], populations[(i + 1) % nPopulations], p.OneToOneConnector(), synapse_type=synapse_type, label="Projection from pop {} to pop " "{}".format(i, (i + 1) % nPopulations))) # print("++++++++++++++++++++++++++++++++++++++++++++++++++++") # print("Added projection from population %s to population %s" \ # % (i, (i + 1) % nPopulations)) # print("----------------------------------------------------") # from pprint import pprint as pp # pp(projections) spikeArray = {'spike_times': [[0]]} populations.append(p.Population(1, p.SpikeSourceArray, spikeArray, label='inputSpikes_1')) projections.append(p.Projection(populations[-1], populations[0], p.AllToAllConnector(), synapse_type=synapse_type)) for i in range(0, nPopulations): populations[i].record("v") populations[i].record("gsyn_exc") populations[i].record("spikes") p.run(1500) '''' weights = projections[0].getWeights() delays = projections[0].getDelays() ''' neo = populations[0].get_data(["v", "spikes", "gsyn_exc"]) v = neo_convertor.convert_data(neo, name="v") gsyn = neo_convertor.convert_data(neo, name="gsyn_exc") spikes = neo_convertor.convert_spikes(neo) p.end() return (v, gsyn, spikes)
def do_run(nNeurons): p.setup(timestep=0.1, min_delay=1.0, max_delay=7.5) p.set_number_of_neurons_per_core(p.IF_curr_exp, 100) cell_params_lif = { 'cm': 0.25, 'i_offset': 0.0, 'tau_m': 20.0, 'tau_refrac': 2.0, 'tau_syn_E': 6, 'tau_syn_I': 6, 'v_reset': -70.0, 'v_rest': -65.0, 'v_thresh': -55.4 } populations = list() projections = list() weight_to_spike = 12 injection_delay = 1 delay = 1 spikeArray = {'spike_times': [[0, 10, 20, 30]]} populations.append( p.Population(1, p.SpikeSourceArray, spikeArray, label='pop_0')) populations.append( p.Population(nNeurons, p.IF_curr_exp, cell_params_lif, label='pop_1')) populations.append( p.Population(nNeurons, p.IF_curr_exp, cell_params_lif, label='pop_2')) connector = p.AllToAllConnector() synapse_type = p.StaticSynapse(weight=weight_to_spike, delay=injection_delay) projections.append( p.Projection(populations[0], populations[1], connector, synapse_type=synapse_type)) connector = p.OneToOneConnector() synapse_type = p.StaticSynapse(weight=weight_to_spike, delay=delay) projections.append( p.Projection(populations[1], populations[2], connector, synapse_type=synapse_type)) populations[1].record("v") populations[1].record("spikes") p.run(100) neo = populations[1].get_data(["v", "spikes"]) v = neo_convertor.convert_data(neo, name="v") spikes = neo_convertor.convert_spikes(neo) p.end() return (v, spikes)
def structural_shared(): p.setup(1.0) pre_spikes = numpy.array(range(0, 10, 2)) A_plus = 0.01 A_minus = 0.01 tau_plus = 20.0 tau_minus = 20.0 w_min = 0.0 w_max = 5.0 w_init = 5.0 delay_init = 2.0 stim = p.Population(1, p.SpikeSourceArray(pre_spikes), label="stim") pop = p.Population(1, p.IF_curr_exp(), label="pop") pop_2 = p.Population(1, p.IF_curr_exp(), label="pop_2") pop_3 = p.Population(1, p.IF_curr_exp(), label="pop_3") pop_4 = p.Population(1, p.IF_curr_exp(), label="pop_4") pop.record("spikes") pop_2.record("spikes") struct_pl_static = p.StructuralMechanismStatic( partner_selection=p.LastNeuronSelection(), formation=p.DistanceDependentFormation([1, 1], 1.0), elimination=p.RandomByWeightElimination(2.0, 0, 0), f_rew=1000, initial_weight=w_init, initial_delay=delay_init, s_max=1, seed=0, weight=0.0, delay=1.0) struct_pl_stdp = p.StructuralMechanismSTDP( partner_selection=p.LastNeuronSelection(), formation=p.DistanceDependentFormation([1, 1], 0.0), elimination=p.RandomByWeightElimination(4.0, 1.0, 1.0), timing_dependence=p.SpikePairRule( tau_plus, tau_minus, A_plus, A_minus), weight_dependence=p.AdditiveWeightDependence(w_min, w_max), f_rew=1000, initial_weight=2.0, initial_delay=5.0, s_max=1, seed=0, weight=0.0, delay=1.0) proj = p.Projection( stim, pop, p.FromListConnector([]), struct_pl_static) proj_2 = p.Projection( stim, pop_2, p.FromListConnector([]), struct_pl_static) proj_3 = p.Projection( stim, pop_3, p.FromListConnector([(0, 0)]), struct_pl_stdp) proj_4 = p.Projection( stim, pop_4, p.FromListConnector([(0, 0)]), struct_pl_stdp) p.Projection(pop_3, pop_4, p.AllToAllConnector(), p.StaticSynapse(weight=1, delay=3)) p.run(10) conns = list(proj.get(["weight", "delay"], "list")) conns_2 = list(proj_2.get(["weight", "delay"], "list")) conns_3 = list(proj_3.get(["weight", "delay"], "list")) conns_4 = list(proj_4.get(["weight", "delay"], "list")) p.end() print(conns) print(conns_2) print(conns_3) print(conns_4) assert(len(conns) == 1) assert(tuple(conns[0]) == (0, 0, w_init, delay_init)) assert(len(conns_2) == 1) assert(tuple(conns_2[0]) == (0, 0, w_init, delay_init)) assert(len(conns_3) == 0) assert(len(conns_4) == 0)
def create_projections(n, w, d): projections = list() for i in range(n): singleConnection = ((i, i, w, d)) projections.append(singleConnection) return projections cochlea_pop = p.Population( size=64, cellclass=p.external_devices.ExternalCochleaDevice( spinnaker_link_id=0, board_address=None, cochlea_key=0x200, cochlea_n_channels=p.external_devices.ExternalCochleaDevice. CHANNELS_64, cochlea_type=p.external_devices.ExternalCochleaDevice.TYPE_MONO, cochlea_polarity=p.external_devices.ExternalCochleaDevice. POLARITY_MERGED), label="ExternalCochlea") middle_pop = p.Population(4, p.IF_curr_exp, cell_params_lif, label='middle_pop') out_pop = p.Population(4, p.IF_curr_exp, cell_params_lif, label='out_layer') #p.Projection(cochlea_pop, out_pop, p.FromListConnector(create_projections(4, 1.2, 1.0)))
# The port on which the spiNNaker machine should listen for packets. # Packets to be injected should be sent to this port on the spiNNaker # machine 'port': 12346, # This is the base key to be used for the injection, which is used to # allow the keys to be routed around the spiNNaker machine. This # assignment means that 32-bit keys must have the high-order 16-bit # set to 0x7; This will automatically be prepended to 16-bit keys. 'virtual_key': 0x70000, } # create synfire populations (if cur exp) pop_forward = Frontend.Population(n_neurons, Frontend.IF_curr_exp(**cell_params_lif), label='pop_forward') pop_backward = Frontend.Population(n_neurons, Frontend.IF_curr_exp(**cell_params_lif), label='pop_backward') # Create injection populations injector_forward = Frontend.Population( n_neurons, Frontend.external_devices.SpikeInjector( **cell_params_spike_injector_with_key), label='spike_injector_forward') injector_backward = Frontend.Population( n_neurons, Frontend.external_devices.SpikeInjector(**cell_params_spike_injector), label='spike_injector_backward')
# Set the number of neurons to simulate n_neurons = 1 # Set the i_offset current i_offset = 0.0 # Set the weight of input spikes weight = 2.0 # Set the times at which to input a spike spike_times = range(0, run_time, 100) p.setup(time_step) spikeArray = {"spike_times": spike_times} input_pop = p.Population(1, p.SpikeSourceArray(**spikeArray), label="input") myModelCurrExpParams = {"my_parameter": -70.0, "i_offset": i_offset} my_model_pop = p.Population(1, My_Model_Curr_Exp(**myModelCurrExpParams), label="my_model_pop") p.Projection(input_pop, my_model_pop, p.OneToOneConnector(), receptor_type='excitatory', synapse_type=p.StaticSynapse(weight=weight)) myModelCurrMySynapseTypeParams = { "my_parameter": -70.0, "i_offset": i_offset, "my_ex_synapse_parameter": 0.5
def test_is_local(self): sim.setup(timestep=1.0) pop_1 = sim.Population(N_NEURONS, sim.IF_curr_exp(), label=LABEL) cells = pop_1.all_cells assert pop_1.is_local(2) == cells[2].local sim.end()
populations = list() projections = list() weight_to_spike = 2.0 delay = 17 loopConnections = list() for i in range(0, nNeurons): singleConnection = ((i, (i + 1) % nNeurons, weight_to_spike, delay)) loopConnections.append(singleConnection) injectionConnection = [(0, 0)] spikeArray = {'spike_times': [[0]]} populations.append( p.Population(nNeurons, p.extra_models.IF_curr_dual_exp(**cell_params_lif), label='pop_1')) populations.append( p.Population(1, p.SpikeSourceArray(**spikeArray), label='inputSpikes_1')) projections.append( p.Projection(populations[0], populations[0], p.FromListConnector(loopConnections), p.StaticSynapse(weight=weight_to_spike, delay=delay))) projections.append( p.Projection(populations[1], populations[0], p.FromListConnector(injectionConnection), p.StaticSynapse(weight=weight_to_spike, delay=1))) populations[0].record(['v', 'gsyn_exc', 'gsyn_inh', 'spikes'])
def main(): minutes = 0 seconds = 30 milliseconds = 0 run_time = minutes * 60 * 1000 + seconds * 1000 + milliseconds weight_to_spike = 4. model = sim.IF_curr_exp cell_params = { 'cm': 0.25, # nF '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 } # Available resolutions # 16, 32, 64, 128 mode = ExternalDvsEmulatorDevice.MODE_64 cam_res = int(mode) cam_fps = 90 frames_per_saccade = cam_fps / 3 - 1 polarity = ExternalDvsEmulatorDevice.MERGED_POLARITY output_type = ExternalDvsEmulatorDevice.OUTPUT_TIME history_weight = 1.0 behaviour = VirtualCam.BEHAVE_ATTENTION # vcam = VirtualCam("./mnist", behaviour=behaviour, fps=cam_fps, # resolution=cam_res, frames_per_saccade=frames_per_saccade) cam_params = { 'mode': mode, 'polarity': polarity, 'threshold': 12, 'adaptive_threshold': False, 'fps': cam_fps, 'inhibition': False, 'output_type': output_type, 'save_spikes': "./spikes_from_cam.pickle", 'history_weight': history_weight, 'device_id': 0, # for an OpenCV webcam device #'device_id': 'path/to/video/file', # to encode pre-recorded video #'device_id': vcam, } if polarity == ExternalDvsEmulatorDevice.MERGED_POLARITY: num_neurons = 2 * (cam_res**2) else: num_neurons = cam_res**2 sim.setup(timestep=1.0, min_delay=1.0, max_delay=10.0) target = sim.Population(num_neurons, model, cell_params) stimulation = sim.Population(num_neurons, DvsEmulatorDevice, cam_params, label="Webcam population") connector = sim.OneToOneConnector() sim.Projection(stimulation, target, connector, synapse_type=sim.StaticSynapse(weight=weight_to_spike)) target.record("spikes") sim.run(run_time) # spikes = target.getSpikes(compatible_output=True) target_neo = target.get_data(variables=["spikes"]) spikes = target_neo.segments[0].spiketrains sim.end() #stimulation._vertex.stop() print("Raster plot of the spikes that Spinnaker echoed back") fig = pylab.figure() spike_times = [spike_time for (neuron_id, spike_time) in spikes] spike_ids = [neuron_id for (neuron_id, spike_time) in spikes] pylab.plot(spike_times, spike_ids, ".", markerfacecolor="None", markeredgecolor="Blue", markersize=3) pylab.show()
n_neurons = 5 # 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 ======================================================== spikeArray = {'spike_times': [[0], [1], [13], [45], [93]]} # in ms # Presynaptic population - Input layer - Stimuli pop_input = sim.Population( n_neurons, sim.SpikeSourceArray, spikeArray, # sim.SpikeSourcePoisson(), #(rate=1, duration=sim_time), label='pop_input') # Postsynaptic population """ Notes: * Interesting property about this neuron model: voltage_based_synapses = True * Initial voltage value = -70.0 """ pop_output = sim.Population(n_neurons, sim.Izhikevich(), label='pop_output') sim.Projection(pop_input, pop_output, sim.OneToOneConnector(), sim.StaticSynapse(weight=20.0, delay=2)) # == Instrument the network ====================================================
def do_run(plot): p.setup(timestep=1.0) cell_params_lif = { 'cm': 0.25, 'i_offset': 0.0, 'tau_m': 20.0, 'tau_refrac': 2.0, 'tau_syn_E': 5.0, 'tau_syn_I': 5.0, 'v_reset': -70.0, 'v_rest': -65.0, 'v_thresh': -50.0 } def create_grid(n, label, dx=1.0, dy=1.0): grid_structure = p.Grid2D(dx=dx, dy=dy, x0=0.0, y0=0.0) return p.Population(n * n, p.IF_curr_exp(**cell_params_lif), structure=grid_structure, label=label) # Parameters n = 5 weight_to_spike = 2.0 delay = 2 runtime = 1000 p.set_number_of_neurons_per_core(p.IF_curr_exp, 100) # Network population small_world = create_grid(n, 'small_world') # SpikeInjector injectionConnection = [(0, 0)] spikeArray = {'spike_times': [[0]]} inj_pop = p.Population(1, p.SpikeSourceArray(**spikeArray), label='inputSpikes_1') # Injector projection p.Projection(inj_pop, small_world, p.FromListConnector(injectionConnection), p.StaticSynapse(weight=weight_to_spike, delay=delay)) # Connectors degree = 2.0 rewiring = 0.4 rng = NumpyRNG(seed=1) small_world_connector = p.SmallWorldConnector(degree, rewiring, rng=rng) # Projection for small world grid sw_pro = p.Projection(small_world, small_world, small_world_connector, p.StaticSynapse(weight=2.0, delay=5)) small_world.record(['v', 'spikes']) p.run(runtime) v = small_world.get_data('v') spikes = small_world.get_data('spikes') weights = sw_pro.get('weight', 'list') if plot: # pylint: disable=no-member Figure( # raster plot of the presynaptic neuron spike times Panel(spikes.segments[0].spiketrains, yticks=True, markersize=0.2, xlim=(0, runtime), xticks=True), # membrane potential of the postsynaptic neuron Panel(v.segments[0].filter(name='v')[0], ylabel="Membrane potential (mV)", data_labels=[small_world.label], yticks=True, xlim=(0, runtime), xticks=True), title="Simple small world connector", annotations="Simulated with {}".format(p.name())) plt.show() p.end() return v, spikes, weights
def potentiation_and_depression(self): p.setup(1) runtime = 100 initial_run = 1000 # to negate any initial conditions # STDP parameters a_plus = 0.1 a_minus = 0.0375 tau_plus = 20 tau_minus = 64 plastic_delay = 1 initial_weight = 0.05 max_weight = 0.1 min_weight = 0 pre_spikes = [10, 50] extra_spikes = [30] for i in range(len(pre_spikes)): pre_spikes[i] += initial_run for i in range(len(extra_spikes)): extra_spikes[i] += initial_run # Spike source to send spike via plastic synapse pre_pop = p.Population(1, p.SpikeSourceArray, {'spike_times': pre_spikes}, label="pre") # Spike source to send spike via static synapse to make # post-plastic-synapse neuron fire extra_pop = p.Population(1, p.SpikeSourceArray, {'spike_times': extra_spikes}, label="extra") # Post-plastic-synapse population post_pop = p.Population(1, p.IF_cond_exp(), label="post") # Create projections p.Projection(pre_pop, post_pop, p.OneToOneConnector(), p.StaticSynapse(weight=0.1, delay=1), receptor_type="excitatory") p.Projection(extra_pop, post_pop, p.OneToOneConnector(), p.StaticSynapse(weight=0.1, delay=1), receptor_type="excitatory") syn_plas = p.STDPMechanism( timing_dependence=p.extra_models.SpikeNearestPairRule( tau_plus=tau_plus, tau_minus=tau_minus, A_plus=a_plus, A_minus=a_minus), weight_dependence=p.AdditiveWeightDependence(w_min=min_weight, w_max=max_weight), weight=initial_weight, delay=plastic_delay) plastic_synapse = p.Projection(pre_pop, post_pop, p.OneToOneConnector(), synapse_type=syn_plas, receptor_type='excitatory') # Record the spikes post_pop.record("spikes") # Run p.run(initial_run + runtime) # Get the weights weights = plastic_synapse.get('weight', 'list', with_address=False) # Get the spikes post_spikes = numpy.array( # pylint: disable=no-member post_pop.get_data('spikes').segments[0].spiketrains[0].magnitude) # End the simulation as all information gathered p.end() # Get the spikes and time differences that will be considered by # the simulation (as the last pre-spike will be considered differently) pre_spikes = numpy.array(pre_spikes) last_pre_spike = pre_spikes[-1] considered_post_spikes = post_spikes[post_spikes < last_pre_spike] considered_post_spikes += plastic_delay potentiation_times = list() depression_times = list() for time in pre_spikes: post_times = considered_post_spikes[considered_post_spikes > time] if len(post_times) > 0: last_time = post_times[0] potentiation_times.append(time - last_time) post_times = considered_post_spikes[considered_post_spikes < time] if len(post_times) > 0: last_time = post_times[-1] depression_times.append(last_time - time) potentiation_times = numpy.array(potentiation_times) depression_times = numpy.array(depression_times) # Work out the weight according to the rules potentiations = max_weight * a_plus * numpy.exp( (potentiation_times / tau_plus)) depressions = max_weight * a_minus * numpy.exp( (depression_times / tau_minus)) new_weight_exact = \ initial_weight + numpy.sum(potentiations) - numpy.sum(depressions) # print("Pre neuron spikes at: {}".format(pre_spikes)) # print("Post-neuron spikes at: {}".format(post_spikes)) target_spikes = [1013, 1032, 1051, 1056] self.assertListEqual(list(post_spikes), target_spikes) # print("New weight exact: {}".format(new_weight_exact)) # print("New weight SpiNNaker: {}".format(weights)) self.assertTrue(numpy.allclose(weights, new_weight_exact, rtol=0.001))
rates_on = rates_on.reshape(rates_on.shape[0], N_layer).T.astype(float) possible_indices = np.arange(rates_on.shape[1]) choices = np.random.choice(possible_indices, number_of_slots, replace=True) rates_on_mask = (rates_on[:, choices] > 0).astype(float) final_rates_on = rates_on_mask * args.fixed_signal_value + f_base # Input population source_column.append( sim.Population(N_layer, SpikeSourcePoissonVariable, { 'rates': final_rates_on, 'starts': slots_starts, 'durations': durations }, label="Variable-rate Poisson spike source # " + str(number))) # Neuron populations target_column.append( sim.Population(N_layer, model, cell_params, label="TARGET_POP # " + str(number))) # Setting up connectivity ff_connections.append( sim.Projection( source_column[number],
def do_run(nNeurons): p.setup(timestep=1.0, min_delay=1.0, max_delay=32.0) p.set_number_of_neurons_per_core(p.IF_curr_exp, 100) cm = list() i_off = list() tau_m = list() tau_re = list() tau_syn_e = list() tau_syn_i = list() v_reset = list() v_rest = list() v_thresh = list() for atom in range(0, nNeurons): cm.append(0.25) i_off.append(0.0) tau_m.append(10.0) tau_re.append(2.0) tau_syn_e.append(0.5) tau_syn_i.append(0.5) v_reset.append(-65.0) v_rest.append(-65.0) v_thresh.append(-64.4) gbar_na_distr = RandomDistribution('normal', (20.0, 2.0), rng=NumpyRNG(seed=85524)) cell_params_lif = { 'cm': cm, 'i_offset': i_off, 'tau_m': tau_m, 'tau_refrac': tau_re, 'tau_syn_E': tau_syn_e, 'tau_syn_I': tau_syn_i, 'v_reset': v_reset, 'v_rest': v_rest, 'v_thresh': v_thresh } populations = list() projections = list() weight_to_spike = 2 delay = 1 connections = list() for i in range(0, nNeurons): singleConnection = (i, ((i + 1) % nNeurons), weight_to_spike, delay) connections.append(singleConnection) injectionConnection = [(0, 0, weight_to_spike, delay)] spikeArray = {'spike_times': [[0]]} populations.append( p.Population(nNeurons, p.IF_curr_exp, cell_params_lif, label='pop_1')) populations.append( p.Population(1, p.SpikeSourceArray, spikeArray, label='inputSpikes_1')) populations[0].set(cm=0.25) populations[0].set(cm=cm) populations[0].set(tau_m=tau_m, v_thresh=v_thresh) populations[0].set(i_offset=gbar_na_distr) populations[0].set(i_offset=i_off) projections.append( p.Projection(populations[0], populations[0], p.FromListConnector(connections))) projections.append( p.Projection(populations[1], populations[0], p.FromListConnector(injectionConnection))) populations[0].record("v") populations[0].record("gsyn_exc") populations[0].record("spikes") p.run(100) neo = populations[0].get_data(["v", "spikes", "gsyn_exc"]) p.end() return neo