def test_get_spikes(self): """ test for get spikes :return: """ p.setup(timestep=0.1, min_delay=1.0, max_delay=14.40) n_neurons = 200 # number of neurons in each population p.set_number_of_neurons_per_core("IF_curr_exp", n_neurons / 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 } populations = list() projections = list() weight_to_spike = 2.0 delay = 1.7 loop_connections = list() for i in range(0, n_neurons): single_connection = (i, ((i + 1) % n_neurons), weight_to_spike, delay) loop_connections.append(single_connection) injection_connection = [(0, 0, weight_to_spike, 1)] spike_array = {'spike_times': [[0]]} populations.append( p.Population(n_neurons, p.IF_curr_exp, cell_params_lif, label='pop_1')) populations.append( p.Population(1, p.SpikeSourceArray, spike_array, label='inputSpikes_1')) projections.append( p.Projection(populations[0], populations[0], p.FromListConnector(loop_connections))) projections.append( p.Projection(populations[1], populations[0], p.FromListConnector(injection_connection))) populations[0].record_v() populations[0].record_gsyn() populations[0].record() p.run(500) spikes = populations[0].getSpikes(compatible_output=True) pre_recorded_spikes = [[0, 3.5], [1, 6.7], [2, 9.9], [3, 13.1], [4, 16.3], [5, 19.5], [6, 22.7], [7, 25.9], [8, 29.1], [9, 32.3], [10, 35.5], [11, 38.7], [12, 41.9], [13, 45.1], [14, 48.3], [15, 51.5], [16, 54.7], [17, 57.9], [18, 61.1], [19, 64.3], [20, 67.5], [21, 70.7], [22, 73.9], [23, 77.1], [24, 80.3], [25, 83.5], [26, 86.7], [27, 89.9], [28, 93.1], [29, 96.3], [30, 99.5], [31, 102.7], [32, 105.9], [33, 109.1], [34, 112.3], [35, 115.5], [36, 118.7], [37, 121.9], [38, 125.1], [39, 128.3], [40, 131.5], [41, 134.7], [42, 137.9], [43, 141.1], [44, 144.3], [45, 147.5], [46, 150.7], [47, 153.9], [48, 157.1], [49, 160.3], [50, 163.5], [51, 166.7], [52, 169.9], [53, 173.1], [54, 176.3], [55, 179.5], [56, 182.7], [57, 185.9], [58, 189.1], [59, 192.3], [60, 195.5]] p.end() for spike_element, read_element in zip(spikes, pre_recorded_spikes): self.assertEqual(round(spike_element[0], 1), round(read_element[0], 1)) self.assertEqual(round(spike_element[1], 1), round(read_element[1], 1))
for x_ind in range(input_size): for y_ind in range(output_size): weights = w1[x_ind][y_ind] #weights = w1[x_ind] #for i in range(w.shape[1]): if weights > 0: conn_list_exci.append((x_ind, y_ind, weights, 1.)) elif weights < 0: conn_list_inhi.append((x_ind, y_ind, weights, 1.)) #print output_size pop_out = p.Population(output_size, p.IF_curr_exp, cell_params_lif) if len(conn_list_exci) > 0: connections['e2e'] = p.Projection( pop_in, pop_out, p.FromListConnector(conn_list_exci), label='excitatory') if len(conn_list_inhi) > 0: connections['i2i'] = p.Projection( pop_in, pop_out, p.FromListConnector(conn_list_inhi), label='inhibitory') #connection=p.Projection(pop_in, pop_out,AllToAllConnector(weights = pos_w), target='excitatory') #connection=p.Projection(pop_in, pop_out,AllToAllConnector(weights = neg_w), target='inhibitory') pop_list.append(pop_out) pop_in = pop_out except EOFError: pass pop_out.record()
def run_test(w_list, cell_para, spike_source_data): #Du.set_trace() pop_list = [] p.setup(timestep=1.0, min_delay=1.0, max_delay=3.0) #input poisson layer input_size = w_list[0].shape[0] #print w_list[0].shape[0] #print w_list[1].shape[0] list = [] for j in range(input_size): list.append(spike_source_data[j]) pop_in = p.Population(input_size, p.SpikeSourceArray, {'spike_times': list}) pop_list.append(pop_in) #for j in range(input_size): #pop_in[j].spike_times = spike_source_data[j] #pop_in = p.Population(input_size, p.SpikeSourceArray, {'spike_times' : []}) #for j in range(input_size): # pop_in[j].spike_times = spike_source_data[j] #pop_list.append(pop_in) #count =0 #print w_list[0].shape[0] for w in w_list: input_size = w.shape[0] #count = count+1 #print count output_size = w.shape[1] #pos_w = np.copy(w) #pos_w[pos_w < 0] = 0 #neg_w = np.copy(w) #neg_w[neg_w > 0] = 0 conn_list_exci = [] conn_list_inhi = [] #k_size=in_size-out_size+1 for x_ind in range(input_size): for y_ind in range(output_size): weights = w[x_ind][y_ind] #for i in range(w.shape[1]): if weights > 0: conn_list_exci.append((x_ind, y_ind, weights, 1.)) elif weights < 0: conn_list_inhi.append((x_ind, y_ind, weights, 1.)) #print output_size pop_out = p.Population(output_size, p.IF_curr_exp, cell_para) if len(conn_list_exci) > 0: p.Projection(pop_in, pop_out, p.FromListConnector(conn_list_exci), target='excitatory') if len(conn_list_inhi) > 0: p.Projection(pop_in, pop_out, p.FromListConnector(conn_list_inhi), target='inhibitory') #p.Projection(pop_in, pop_out, p.AllToAllConnector(weights = pos_w), target='excitatory') #p.Projection(pop_in, pop_out, p.AllToAllConnector(weights = neg_w), target='inhibitory') pop_list.append(pop_out) pop_in = pop_out pop_out.record() run_time = np.ceil(np.max(spike_source_data)[0] / 1000.) * 1000 #print run_time p.run(run_time) spikes = pop_out.getSpikes(compatible_output=True) return spikes
# Connect key spike injector to breakout population p.Projection(key_input, breakout_pop, p.OneToOneConnector(weights=2)) # Create visualiser visualiser = spinn_breakout.Visualiser(UDP_PORT, key_input_connection, x_res=X_RESOLUTION, y_res=Y_RESOLUTION, x_bits=X_BITS, y_bits=Y_BITS) direction_population = p.Population(3, p.IF_curr_exp, cell_params_lif) p.Projection( direction_population, breakout_pop, p.FromListConnector([(1, 1, weight_to_spike, delay), (2, 2, weight_to_spike, delay)])) ## Code to implement https://trello.com/c/rLwRIOxq/111-hard-coded-breakout follows on_ids = get_on_neuron_ids() off_ids = get_off_neuron_ids() no_paddle_on_ids = on_ids[:-1, :] only_paddle_on_ids = on_ids[-1, :] only_paddle_off_ids = off_ids[-1, :] paddle_presence_weight = .7 ball_presence_weight = .7 # Create all needed populations ball_position = p.Population(GAME_WIDTH // pool_size, p.IF_curr_exp, cell_params_lif,
projections = list() weight_to_spike = 2.0 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, 1)] 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')) 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() populations[0].record() p.run(1000) v = None gsyn = None spikes = None #v = populations[0].get_v(compatible_output=True) #gsyn = populations[0].get_gsyn(compatible_output=True) spikes = populations[0].getSpikes(compatible_output=True)
# Create a connection from the injector into the populations Frontend.Projection(injector_forward, pop_forward, Frontend.OneToOneConnector(weights=weight_to_spike)) Frontend.Projection(injector_backward, pop_backward, Frontend.OneToOneConnector(weights=weight_to_spike)) # Synfire chain connections where each neuron is connected to its next neuron # NOTE: there is no recurrent connection so that each chain stops once it # reaches the end loop_forward = list() loop_backward = list() for i in range(0, n_neurons - 1): loop_forward.append((i, (i + 1) % n_neurons, weight_to_spike, 3)) loop_backward.append(((i + 1) % n_neurons, i, weight_to_spike, 3)) Frontend.Projection(pop_forward, pop_forward, Frontend.FromListConnector(loop_forward)) Frontend.Projection(pop_backward, pop_backward, Frontend.FromListConnector(loop_backward)) # record spikes from the synfire chains so that we can read off valid results # in a safe way afterwards, and verify the behavior pop_forward.record() pop_backward.record() # Activate the sending of live spikes ExternalDevices.activate_live_output_for(pop_forward, database_notify_host="localhost", database_notify_port_num=19996) ExternalDevices.activate_live_output_for(pop_backward, database_notify_host="localhost", database_notify_port_num=19996)
def test_get_gsyn(self): """ test that tests the getting of gsyn from a pre determined recording :return: """ p.setup(timestep=1, min_delay=1.0, max_delay=14.40) n_neurons = 10 # number of neurons in each population runtime = 50 p.set_number_of_neurons_per_core("IF_curr_exp", n_neurons / 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 } populations = list() projections = list() weight_to_spike = 2.0 delay = 1.7 loop_connections = list() for i in range(0, n_neurons): single_connection = (i, ((i + 1) % n_neurons), weight_to_spike, delay) loop_connections.append(single_connection) injection_connection = [(0, 0, weight_to_spike, 1)] spike_array = {'spike_times': [[0]]} populations.append(p.Population(n_neurons, p.IF_curr_exp, cell_params_lif, label='pop_1')) populations.append(p.Population(1, p.SpikeSourceArray, spike_array, label='inputSpikes_1')) projections.append(p.Projection(populations[0], populations[0], p.FromListConnector(loop_connections))) projections.append(p.Projection(populations[1], populations[0], p.FromListConnector(injection_connection))) populations[0].record_v() populations[0].record_gsyn() populations[0].record() p.run(runtime) gsyn = populations[0].get_gsyn(compatible_output=True) current_file_path = os.path.dirname(os.path.abspath(__file__)) current_file_path = os.path.join(current_file_path, "gsyn.data") pre_recorded_data = p.utility_calls.read_in_data_from_file( current_file_path, 0, n_neurons, 0, runtime) p.end() for spike_element, read_element in zip(gsyn, pre_recorded_data): self.assertEqual(round(spike_element[0], 1), round(read_element[0], 1)) self.assertEqual(round(spike_element[1], 1), round(read_element[1], 1)) self.assertEqual(round(spike_element[2], 1), round(read_element[2], 1))
def test_something(self): #!/usr/bin/python import pylab import spynnaker.pyNN as p p.setup(timestep=1.0, min_delay=1.0, max_delay=144.0) nNeurons = 200 # number of neurons in each population p.set_number_of_neurons_per_core("IF_curr_exp", nNeurons / 2) cell_params_lif = { 'cm': 0.25, # nF '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 = 2.0 delay = 17 loop_connections = list() for i in range(0, nNeurons): single_connection = (i, ((i + 1) % nNeurons), weight_to_spike, delay) loop_connections.append(single_connection) injection_connection = [(0, 0, weight_to_spike, 1)] spike_array = {'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, spike_array, label='inputSpikes_1')) projections.append( p.Projection(populations[0], populations[0], p.FromListConnector(loop_connections))) projections.append( p.Projection(populations[1], populations[0], p.FromListConnector(injection_connection))) populations[0].record_v() #populations[0].record_gsyn() #populations[0].record(visualiser_mode=p.VISUALISER_MODES.RASTER) p.run(5000) v = None gsyn = None spikes = None v = populations[0].get_v(compatible_output=True) #assert(v == ) #gsyn = populations[0].get_gsyn(compatible_output=True) #spikes = populations[0].getSpikes(compatible_output=True) if spikes is not None: print spikes pylab.figure() pylab.plot([i[1] for i in spikes], [i[0] for i in spikes], ".") pylab.xlabel('Time/ms') pylab.ylabel('spikes') pylab.title('spikes') pylab.show() else: print "No spikes received" # Make some graphs if v is not None: ticks = len(v) / nNeurons pylab.figure() pylab.xlabel('Time/ms') pylab.ylabel('v') pylab.title('v') for pos in range(0, nNeurons, 20): v_for_neuron = v[pos * ticks:(pos + 1) * ticks] pylab.plot([i[1] for i in v_for_neuron], [i[2] for i in v_for_neuron]) pylab.show() if gsyn is not None: ticks = len(gsyn) / nNeurons pylab.figure() pylab.xlabel('Time/ms') pylab.ylabel('gsyn') pylab.title('gsyn') for pos in range(0, nNeurons, 20): gsyn_for_neuron = gsyn[pos * ticks:(pos + 1) * ticks] pylab.plot([i[1] for i in gsyn_for_neuron], [i[2] for i in gsyn_for_neuron]) pylab.show() p.end(stop_on_board=True)
def test_print_spikes(self): machine_time_step = 0.1 p.setup(timestep=machine_time_step, min_delay=1.0, max_delay=14.40) n_neurons = 20 # number of neurons in each population p.set_number_of_neurons_per_core("IF_curr_exp", n_neurons / 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 } populations = list() projections = list() weight_to_spike = 2.0 delay = 1.7 loop_connections = list() for i in range(0, n_neurons): single_connection = (i, ((i + 1) % n_neurons), weight_to_spike, delay) loop_connections.append(single_connection) injection_connection = [(0, 0, weight_to_spike, 1)] spike_array = {'spike_times': [[0]]} populations.append( p.Population(n_neurons, p.IF_curr_exp, cell_params_lif, label='pop_1')) populations.append( p.Population(1, p.SpikeSourceArray, spike_array, label='inputSpikes_1')) projections.append( p.Projection(populations[0], populations[0], p.FromListConnector(loop_connections))) projections.append( p.Projection(populations[1], populations[0], p.FromListConnector(injection_connection))) populations[0].record_v() populations[0].record_gsyn() populations[0].record() p.run(500) spikes = populations[0].getSpikes(compatible_output=True) current_file_path = os.path.dirname(os.path.abspath(__file__)) current_file_path = os.path.join(current_file_path, "spikes.data") spike_file = populations[0].printSpikes(current_file_path) spike_reader = p.utility_calls.read_spikes_from_file( current_file_path, min_atom=0, max_atom=n_neurons, min_time=0, max_time=500) read_in_spikes = spike_reader.spike_times p.end() os.remove(current_file_path) for spike_element, read_element in zip(spikes, read_in_spikes): self.assertEqual(round(spike_element[0], 1), round(read_element[0], 1)) self.assertEqual(round(spike_element[1], 1), round(read_element[1], 1))
# 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.IZK_curr_exp, 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')) projections.append( p.Projection(populations[4], populations[0], p.FromListConnector(cond_injection_connection))) projections.append( p.Projection(populations[4], populations[1], p.FromListConnector(curr_injection_connection))) projections.append( p.Projection(populations[4], populations[2], p.FromListConnector(izk_injection_connection))) 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)))
#TrianSpikeON = BuildTrainingSpike(order,1) in_spike = BuildTrainingSpike_with_noise(order, 1, 198) #print TrianSpikeON spikeArrayOn = {'spike_times': in_spike} ON_pop = sim.Population(prepop_size, sim.SpikeSourceArray, spikeArrayOn, label='inputSpikes_On') post_pop = sim.Population(postpop_size, sim.IF_curr_exp, cell_params_lif, label='post_1') connectionsOn = sim.Projection( ON_pop, post_pop, sim.FromListConnector(convert_weights_to_list(weights_import, delay))) #inhibitory between the neurons connection_I = sim.Projection(post_pop, post_pop, sim.AllToAllConnector( weights=15, delays=1, allow_self_connections=False), target='inhibitory') ON_pop.record() post_pop.record() sim.run(simtime) # == Get the Simulated Data =================================================
def __init__(self): # initial call to set up the front end (pynn requirement) Frontend.setup(timestep=1.0, min_delay=1.0, max_delay=144.0) # neurons per population and the length of runtime in ms for the # simulation, as well as the expected weight each spike will contain self.n_neurons = 100 run_time = 100000 weight_to_spike = 2.0 # neural parameters of the IF_curr model used to respond to injected # spikes. # (cell params for a synfire chain) 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 } ################################## # Parameters for the injector population. This is the minimal set of # parameters required, which is for a set of spikes where the key is # not important. Note that a virtual key *will* be assigned to the # population, and that spikes sent which do not match this virtual key # will be dropped; however, if spikes are sent using 16-bit keys, they # will automatically be made to match the virtual key. The virtual # key assigned can be obtained from the database. ################################## cell_params_spike_injector = { # 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': 12345 } ################################## # Parameters for the injector population. Note that each injector # needs to be given a different port. The virtual key is assigned # here, rather than being allocated later. As with the above, spikes # injected need to match this key, and this will be done automatically # with 16-bit keys. ################################## cell_params_spike_injector_with_key = { # 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(self.n_neurons, Frontend.IF_curr_exp, cell_params_lif, label='pop_forward') pop_backward = Frontend.Population(self.n_neurons, Frontend.IF_curr_exp, cell_params_lif, label='pop_backward') # Create injection populations injector_forward = Frontend.Population( self.n_neurons, ExternalDevices.SpikeInjector, cell_params_spike_injector_with_key, label='spike_injector_forward') injector_backward = Frontend.Population( self.n_neurons, ExternalDevices.SpikeInjector, cell_params_spike_injector, label='spike_injector_backward') # Create a connection from the injector into the populations Frontend.Projection( injector_forward, pop_forward, Frontend.OneToOneConnector(weights=weight_to_spike)) Frontend.Projection( injector_backward, pop_backward, Frontend.OneToOneConnector(weights=weight_to_spike)) # Synfire chain connections where each neuron is connected to its next # neuron # NOTE: there is no recurrent connection so that each chain stops once # it reaches the end loop_forward = list() loop_backward = list() for i in range(0, self.n_neurons - 1): loop_forward.append( (i, (i + 1) % self.n_neurons, weight_to_spike, 3)) loop_backward.append( ((i + 1) % self.n_neurons, i, weight_to_spike, 3)) Frontend.Projection(pop_forward, pop_forward, Frontend.FromListConnector(loop_forward)) Frontend.Projection(pop_backward, pop_backward, Frontend.FromListConnector(loop_backward)) # record spikes from the synfire chains so that we can read off valid # results in a safe way afterwards, and verify the behavior pop_forward.record() pop_backward.record() # Activate the sending of live spikes ExternalDevices.activate_live_output_for( pop_forward, database_notify_host="localhost", database_notify_port_num=19996) ExternalDevices.activate_live_output_for( pop_backward, database_notify_host="localhost", database_notify_port_num=19996) # set up gui from multiprocessing import Process p = Process(target=GUI, args=[self.n_neurons]) p.start() # Run the simulation on spiNNaker Frontend.run(run_time) # Retrieve spikes from the synfire chain population spikes_forward = pop_forward.getSpikes() spikes_backward = pop_backward.getSpikes() # If there are spikes, plot using matplotlib if len(spikes_forward) != 0 or len(spikes_backward) != 0: pylab.figure() if len(spikes_forward) != 0: pylab.plot([i[1] for i in spikes_forward], [i[0] for i in spikes_forward], "b.") if len(spikes_backward) != 0: pylab.plot([i[1] for i in spikes_backward], [i[0] for i in spikes_backward], "r.") pylab.ylabel('neuron id') pylab.xlabel('Time/ms') pylab.title('spikes') pylab.show() else: print "No spikes received" # Clear data structures on spiNNaker to leave the machine in a clean # state for future executions Frontend.end() p.join()
def _connect_spike_sources(self, retinae=None, verbose=False): if verbose: print "INFO: Connecting Spike Sources to Network." global _retina_proj_l, _retina_proj_r # left is 0--dimensionRetinaY-1; right is dimensionRetinaY--dimensionRetinaY*2-1 connListRetLBlockerL = [] connListRetLBlockerR = [] connListRetRBlockerL = [] connListRetRBlockerR = [] for y in range(0, self.dim_y): connListRetLBlockerL.append( (y, y, self.cell_params['synaptic']['wSaB'], self.cell_params['synaptic']['dSaB'])) connListRetLBlockerR.append( (y, y + self.dim_y, self.cell_params['synaptic']['wSzB'], self.cell_params['synaptic']['dSzB'])) connListRetRBlockerL.append( (y, y, self.cell_params['synaptic']['wSzB'], self.cell_params['synaptic']['dSzB'])) connListRetRBlockerR.append( (y, y + self.dim_y, self.cell_params['synaptic']['wSaB'], self.cell_params['synaptic']['dSaB'])) retinaLeft = retinae['left'].pixel_columns retinaRight = retinae['right'].pixel_columns pixel = 0 for row in _retina_proj_l: for pop in row: ps.Projection(retinaLeft[pixel], self.network[pop][1], ps.OneToOneConnector( weights=self.cell_params['synaptic']['wSC'], delays=self.cell_params['synaptic']['dSC']), target='excitatory') ps.Projection(retinaLeft[pixel], self.network[pop][0], ps.FromListConnector(connListRetLBlockerL), target='excitatory') ps.Projection(retinaLeft[pixel], self.network[pop][0], ps.FromListConnector(connListRetLBlockerR), target='inhibitory') pixel += 1 pixel = 0 for col in _retina_proj_r: for pop in col: ps.Projection(retinaRight[pixel], self.network[pop][1], ps.OneToOneConnector( weights=self.cell_params['synaptic']['wSC'], delays=self.cell_params['synaptic']['dSC']), target='excitatory') ps.Projection(retinaRight[pixel], self.network[pop][0], ps.FromListConnector(connListRetRBlockerR), target='excitatory') ps.Projection(retinaRight[pixel], self.network[pop][0], ps.FromListConnector(connListRetRBlockerL), target='inhibitory') pixel += 1 # configure for the live input streaming if desired if not (retinae['left'].use_prerecorded_input and retinae['right'].use_prerecorded_input): from spynnaker_external_devices_plugin.pyNN.connections.spynnaker_live_spikes_connection import \ SpynnakerLiveSpikesConnection all_retina_labels = retinaLeft.labels + retinaRight.labels self.live_connection_sender = SpynnakerLiveSpikesConnection( receive_labels=None, local_port=19999, send_labels=all_retina_labels) # this callback will be executed right after simulation.run() has been called. If simply a while True # is put there, the main thread will stuck there and will not complete the simulation. # One solution might be to start a thread/process which runs a "while is_running:" loop unless the main thread # sets the "is_running" to False. self.live_connection_sender.add_start_callback( all_retina_labels[0], self.start_injecting) import DVSReader as dvs # the port numbers might well be wrong self.dvs_stream_left = dvs.DVSReader( port=0, label=retinaLeft.label, live_connection=self.live_connection_sender) self.dvs_stream_right = dvs.DVSReader( port=1, label=retinaRight.label, live_connection=self.live_connection_sender) # start the threads, i.e. start reading from the DVS. However, nothing will be sent to the SNN. # See start_injecting self.dvs_stream_left.start() self.dvs_stream_right.start()
def _interconnect_neurons_inhexc(self, network, verbose=False): assert network is not None, \ "ERROR: Network is not initialised! Interconnecting for inhibitory and excitatory patterns failed." if verbose and self.cell_params['topological']['radius_i'] < self.dim_x: print "WARNING: Bad radius of inhibition. Uniquness constraint cannot be satisfied." if verbose and 0 <= self.cell_params['topological'][ 'radius_e'] > self.dim_x: print "WARNING: Bad radius of excitation. " # create lists with inhibitory along the Retina Right projective line nbhoodInhL = [] nbhoodInhR = [] nbhoodExcX = [] nbhoodEcxY = [] # used for the triangular form of the matrix in order to remain within the square if verbose: print "INFO: Generating inhibitory and excitatory connectivity patterns." # generate rows limiter = self.max_disparity - self.min_disparity + 1 ensembleIndex = 0 while ensembleIndex < len(network): if ensembleIndex / (self.max_disparity - self.min_disparity + 1) > \ (self.dim_x - self.min_disparity) - (self.max_disparity - self.min_disparity) - 1: limiter -= 1 if limiter == 0: break nbhoodInhL.append( [ensembleIndex + disp for disp in range(0, limiter)]) ensembleIndex += limiter ensembleIndex = len(network) # generate columns nbhoodInhR = [[x] for x in nbhoodInhL[0]] shiftGlob = 0 for x in nbhoodInhL[1:]: shiftGlob += 1 shift = 0 for e in x: if (shift + 1) % (self.max_disparity - self.min_disparity + 1) == 0: nbhoodInhR.append([e]) else: nbhoodInhR[shift + shiftGlob].append(e) shift += 1 # generate all diagonals for diag in map(None, *nbhoodInhL): sublist = [] for elem in diag: if elem is not None: sublist.append(elem) nbhoodExcX.append(sublist) # generate all y-axis excitation for x in range(0, self.dim_y): for e in range(1, self.cell_params['topological']['radius_e'] + 1): if x + e < self.dim_y: nbhoodEcxY.append( (x, x + e, self.cell_params['synaptic']['wCCe'], self.cell_params['synaptic']['dCCe'])) if x - e >= 0: nbhoodEcxY.append( (x, x - e, self.cell_params['synaptic']['wCCe'], self.cell_params['synaptic']['dCCe'])) # Store these lists as global parameters as they can be used to quickly match the spiking collector neuron # with the corresponding pixel xy coordinates (same_disparity_indices) # TODO: think of a better way to encode pixels: closed form formula would be perfect # These are also used when connecting the spike sources to the network! (retina_proj_l, retina_proj_r) global _retina_proj_l, _retina_proj_r, same_disparity_indices _retina_proj_l = nbhoodInhL _retina_proj_r = nbhoodInhR same_disparity_indices = nbhoodExcX if verbose: print "INFO: Connecting neurons for internal excitation and inhibition." for row in nbhoodInhL: for pop in row: for nb in row: if nb != pop: ps.Projection( network[pop][1], network[nb][1], ps.OneToOneConnector( weights=self.cell_params['synaptic']['wCCi'], delays=self.cell_params['synaptic']['dCCi']), target='inhibitory') for col in nbhoodInhR: for pop in col: for nb in col: if nb != pop: ps.Projection( network[pop][1], network[nb][1], ps.OneToOneConnector( weights=self.cell_params['synaptic']['wCCi'], delays=self.cell_params['synaptic']['dCCi']), target='inhibitory') for diag in nbhoodExcX: for pop in diag: for nb in range( 1, self.cell_params['topological']['radius_e'] + 1): if diag.index(pop) + nb < len(diag): ps.Projection( network[pop][1], network[diag[diag.index(pop) + nb]][1], ps.OneToOneConnector( weights=self.cell_params['synaptic']['wCCe'], delays=self.cell_params['synaptic']['dCCe']), target='excitatory') if diag.index(pop) - nb >= 0: ps.Projection( network[pop][1], network[diag[diag.index(pop) - nb]][1], ps.OneToOneConnector( weights=self.cell_params['synaptic']['wCCe'], delays=self.cell_params['synaptic']['dCCe']), target='excitatory') for ensemble in network: ps.Projection(ensemble[1], ensemble[1], ps.FromListConnector(nbhoodEcxY), target='excitatory')
def start_sim(self,sim_time): #simulation setup self.simtime = sim_time sim.setup(timestep=self.setup_cond["timestep"], min_delay=self.setup_cond["min_delay"], max_delay=self.setup_cond["max_delay"]) #initialise the neuron population spikeArrayOn = {'spike_times': self.in_spike} pre_pop = sim.Population(self.pre_pop_size, sim.SpikeSourceArray, spikeArrayOn, label='inputSpikes_On') post_pop= sim.Population(self.post_pop_size,sim.IF_curr_exp, self.cell_params_lif, label='post_1') stdp_model = sim.STDPMechanism(timing_dependence=sim.SpikePairRule(tau_plus= self.stdp_param["tau_plus"], tau_minus= self.stdp_param["tau_minus"], nearest=True), weight_dependence=sim.MultiplicativeWeightDependence(w_min= self.stdp_param["w_min"], w_max= self.stdp_param["w_max"], A_plus= self.stdp_param["A_plus"], A_minus= self.stdp_param["A_minus"])) #initialise connectiviity of neurons #exitatory connection between pre-synaptic and post-synaptic neuron population if(self.inhibitory_spike_mode): connectionsOn = sim.Projection(pre_pop, post_pop, sim.AllToAllConnector(weights = self.I_syn_weight,delays=1, allow_self_connections=False), target='inhibitory') else: if(self.STDP_mode): if(self.allsameweight): connectionsOn = sim.Projection(pre_pop, post_pop, sim.AllToAllConnector(weights = self.E_syn_weight,delays=1), synapse_dynamics=sim.SynapseDynamics(slow=stdp_model),target='excitatory') else: connectionsOn = sim.Projection(pre_pop, post_pop, sim.FromListConnector(self.conn_list), synapse_dynamics=sim.SynapseDynamics(slow=stdp_model),target='excitatory') else: if(self.allsameweight): connectionsOn = sim.Projection(pre_pop, post_pop, sim.AllToAllConnector(weights = self.E_syn_weight,delays=1), target='excitatory') else: connectionsOn = sim.Projection(pre_pop, post_pop, sim.FromListConnector(self.conn_list), target='excitatory') #sim.Projection.setWeights(self.E_syn_weight) #inhibitory between the neurons post-synaptic neuron population connection_I = sim.Projection(post_pop, post_pop, sim.AllToAllConnector(weights = self.I_syn_weight,delays=1, allow_self_connections=False), target='inhibitory') pre_pop.record() post_pop.record() post_pop.record_v() sim.run(self.simtime) self.pre_spikes = pre_pop.getSpikes(compatible_output=True) self.post_spikes = post_pop.getSpikes(compatible_output=True) self.post_spikes_v = post_pop.get_v(compatible_output=True) self.trained_weights = connectionsOn.getWeights(format='array') sim.end() #print self.conn_list #print self.trained_weights '''scipy.io.savemat('trained_weight.mat',{'initial_weight':self.init_weights, 'trained_weight':self.trained_weights })''' scipy.io.savemat('trained_weight0.mat',{'trained_weight':self.trained_weights })
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 equiv of parrot popultions for closed loop calculation pop_forward_parrot = Frontend.Population( n_neurons, Frontend.IF_curr_exp, cell_params_lif, label='pop_forward_parrot') pop_backward_parrot = Frontend.Population( n_neurons, Frontend.IF_curr_exp, cell_params_lif, label='pop_backward_parrot') # Create injection populations injector_forward = Frontend.Population( 2, ExternalDevices.SpikeInjector, {"port": 19344}, label='spike_injector_forward') # Create a connection from the injector into the populations Frontend.Projection(injector_forward, pop_forward, Frontend.FromListConnector([(0, 0, weight_to_spike, 3)])) Frontend.Projection(injector_forward, pop_backward, Frontend.FromListConnector([(1, 99, weight_to_spike, 3)])) # Synfire chain connections where each neuron is connected to its next neuron # NOTE: there is no recurrent connection so that each chain stops once it # reaches the end loop_forward = list() loop_backward = list() for i in range(0, n_neurons - 1): loop_forward.append((i, (i + 1) % n_neurons, weight_to_spike, 3)) loop_backward.append(((i + 1) % n_neurons, i, weight_to_spike, 3)) Frontend.Projection(pop_forward, pop_forward, Frontend.FromListConnector(loop_forward)) Frontend.Projection(pop_backward, pop_backward, Frontend.FromListConnector(loop_backward)) # Add links to the parrot populations for closed loop calculations
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(nNeurons, p.IF_curr_exp, cell_params_lif, label='pop_2')) populations.append( p.Population(1, p.SpikeSourceArray, spikeArray, label='inputSpikes_1')) #populations[0].set_mapping_constraint({"x": 1, "y": 0}) 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() populations[0].record() p.run(1000) v = None gsyn = None spikes = None '''' weights = projections[0].getWeights()
'v_rest': -65.0, 'v_thresh': -50.0 } # create synfire populations (if cur exp) pop_forward = Frontend.Population(n_neurons, Frontend.IF_curr_exp, cell_params_lif, label='pop_forward') # Create injection populations injector_forward = Frontend.Population(1, Frontend.SpikeSourceArray, {'spike_times': [[0]]}, label='spike_playback_forward') # Create a connection from the injector into the populations Frontend.Projection(injector_forward, pop_forward, Frontend.FromListConnector([(0, 0, weight_to_spike, 1)])) # Synfire chain connections where each neuron is connected to its next neuron # NOTE: there is no recurrent connection so that each chain stops once it # reaches the end loop_forward = list() for i in range(0, n_neurons - 1): loop_forward.append((i, (i + 1) % n_neurons, weight_to_spike, 3)) Frontend.Projection(pop_forward, pop_forward, Frontend.FromListConnector(loop_forward)) # record spikes from the synfire chains so that we can read off valid results # in a safe way afterwards, and verify the behavior pop_forward.record() # Activate the sending of live spikes ExternalDevices.activate_live_output_for(pop_forward, database_notify_host="localhost", database_notify_port_num=19996)
# First it's necessary to find which POS neurons are EXCITATORY and which ones are INHIBITORY: temp_exc_pos = (numpy.array([indices_pos_exc == i for i in exc_neuron_idx])).sum(axis=0) exc2exc = numpy.arange( len(indices_pos_exc))[temp_exc_pos == 1] # excitatory ones exc2inh = numpy.arange( len(indices_pos_exc))[temp_exc_pos == 0] # inhibitory ones # EXC2EXC indices_pre_exc_e2e = [(numpy.abs(exc_neuron_idx - i)).argmin() for i in indices_pre_exc[exc2exc]] indices_pos_exc_e2e = [(numpy.abs(exc_neuron_idx - i)).argmin() for i in indices_pos_exc[exc2exc]] connections_exc2exc = sim.FromListConnector(conn_list=zip( indices_pre_exc_e2e, indices_pos_exc_e2e, weights_pre_exc[exc2exc], [0.0] * len(exc2exc))) sim.Projection(pop_lsm_exc, pop_lsm_exc, connections_exc2exc, label="EXC2EXC_conn", target='excitatory') # EXC2INH indices_pre_exc_e2i = [(numpy.abs(inh_neuron_idx - i)).argmin() for i in indices_pre_exc[exc2inh]] indices_pos_exc_e2i = [(numpy.abs(inh_neuron_idx - i)).argmin() for i in indices_pos_exc[exc2inh]] connections_exc2inh = sim.FromListConnector(conn_list=zip( indices_pre_exc_e2i, indices_pos_exc_e2i, weights_pre_exc[exc2inh], [0.0] *
for ii in range(0,len(argw)): pylab.plot(argw[ii][3]+200*ii,argw[ii][0]+argw[ii][1]*16,".") pylab.title('raster plot of Virtual Retina Neuron Population') pylab.show() raster_plot() #Let us only use the ON events TrianSpikeON = BuildTrainingSpike(order,1) #print TrianSpikeON spikeArrayOn = {'spike_times': TrianSpikeON} ON_pop = sim.Population(prepop_size, sim.SpikeSourceArray, spikeArrayOn, label='inputSpikes_On') post_pop= sim.Population(postpop_size,sim.IF_curr_exp, cell_params_lif, label='post_1') connectionsOn = sim.Projection(ON_pop, post_pop, sim.FromListConnector( convert_weights_to_list(weights_import, delay))) #inhibitory between the neurons connection_I = sim.Projection(post_pop, post_pop, sim.AllToAllConnector( weights = 15,delays=1,allow_self_connections=False), target='inhibitory') post_pop.record() sim.run(simtime) # == Get the Simulated Data ================================================= post_spikes = post_pop.getSpikes(compatible_output=True) sim.end() def GetFiringPattern(spike,low,high): spikeT = np.transpose(spike) time_stamp = spikeT[1]
spikeArray = {'spike_times': [[0]]} for i in range(0, n_pops): populations.append( p.Population(nNeurons, p.IF_curr_exp, cell_params_lif, label='pop_{}'.format(i))) populations.append( p.Population(1, p.SpikeSourceArray, spikeArray, label='inputSpikes_1')) for i in range(0, n_pops): projections.append( p.Projection(populations[i], populations[i], p.FromListConnector(connections))) projections.append( p.Projection(populations[i], populations[((i + 1) % n_pops)], p.FromListConnector(pop_jump_connection))) projections.append( p.Projection(populations[n_pops], populations[0], p.FromListConnector(injectionConnection))) #populations[0].record_v() #populations[0].record_gsyn() for pop_index in range(0, n_pops): populations[pop_index].record() p.run(25000)
stdp_model = sim.STDPMechanism( timing_dependence=sim.SpikePairRule(tau_plus=50.0, tau_minus=50.0), weight_dependence=sim.AdditiveWeightDependence( w_min=0.0, w_max=instant_spike_weight, A_plus=0.000001, A_minus=1.0), dendritic_delay_fraction=1.0) synapse_dynamics = sim.SynapseDynamics(slow=stdp_model) else: synapse_dynamics = None # Create connector proj = sim.Projection(neurons, neurons, sim.FromListConnector(conn_list), synapse_dynamics=synapse_dynamics, target="excitatory") # Stimulate stim neuron stim = sim.Population(1, sim.SpikeSourceArray, {"spike_times": [2.0]}, label="stim") sim.Projection( stim, neurons, sim.FromListConnector([ (0, get_neuron_index(stim_x, stim_y, cost_image.shape[0]), instant_spike_weight, 1.0) ])) # Run network