def plot_C1_spikes(C1_layers: Dict[float, Sequence[nw.Layer]], image_name: str, clear=False, out_dir_name='plots/C1') -> None: """ Plots the spikes of the layers in the given dictionary Arguments: `C1_layers`: The C1 layers `image_name`: The name of the image that will be written. This string will be a part of the actual plot file name. `out_dir_name`: The directory where to save the plots """ spike_panels = [] for size, layers in C1_layers.items(): spike_panels = [] for layer in layers: out_data = layer.population.get_data(clear=clear).segments[0] spike_panels.append(plt.Panel(out_data.spiketrains, xticks=True, yticks=True, xlabel='{}, {} scale layer'.format(\ layer.population.label, size))) plt.Figure(*spike_panels).save('{}/C1_{}_{}_scale.png'.format(\ out_dir_name, image_name, size))
def plot_S2_spikes(S2_layers: Dict[float, Sequence[nw.Layer]], image_name: str, s2_prototype_cells: int, out_dir_name='plots/S2')\ -> None: """ Plots the S2 spikes Parameters: `S2_layers`: A dictionary with the S2 layers `image_name`: The name of the image that will be written. This string will be a part of the actual plot file name. `s2_prototype_cells`: The number of S2 prototype cells `out_dir_name`: The top level directory where to save the plots """ for i in range(s2_prototype_cells): spike_panels = [] for size, layer_list in S2_layers.items(): layer = layer_list[i] out_data = layer.population.get_data().segments[0] spike_panels.append(plt.Panel(out_data.spiketrains, xticks=True, yticks=True, xlabel='{}, scale {}, prototype {}'.format(image_name, size, i))) spike_panels.append(plt.Panel(out_data.filter(name='v')[0], xticks=True, yticks=True, xlabel='{}, scale {}, prototype {}'.format(image_name, size, i))) plt.Figure(*spike_panels).save('{}/{}/S2_{}_prototype{}.png'.format(\ out_dir_name, i, image_name, i))
def test(spikeTimes, trained_weights,label): #spikeTimes = extractSpikes(sample) runTime = int(max(max(spikeTimes)))+100 ########################################## sim.setup(timestep=1) pre_pop = sim.Population(input_size, sim.SpikeSourceArray, {'spike_times': spikeTimes}, label="pre_pop") post_pop = sim.Population(output_size, sim.IF_curr_exp , cell_params_lif, label="post_pop") if len(trained_weights) > input_size: weigths = [[0 for j in range(output_size)] for i in range(input_size)] #np array? size 1024x25 k=0 for i in range(input_size): for j in range(output_size): weigths[i][j] = trained_weights[k] k += 1 else: weigths = trained_weights connections = [] #k = 0 for n_pre in range(input_size): # len(untrained_weights) = input_size for n_post in range(output_size): # len(untrained_weight[0]) = output_size; 0 or any n_pre #connections.append((n_pre, n_post, weigths[n_pre][n_post]*(wMax), __delay__)) connections.append((n_pre, n_post, weigths[n_pre][n_post]*(wMax)/max(trained_weights), __delay__)) # #k += 1 prepost_proj = sim.Projection(pre_pop, post_pop, sim.FromListConnector(connections), synapse_type=sim.StaticSynapse(), receptor_type='excitatory') # no more learning !! #inhib_proj = sim.Projection(post_pop, post_pop, sim.AllToAllConnector(), synapse_type=sim.StaticSynapse(weight=inhibWeight, delay=__delay__), receptor_type='inhibitory') # no more lateral inhib post_pop.record(['v', 'spikes']) sim.run(runTime) neo = post_pop.get_data(['v', 'spikes']) spikes = neo.segments[0].spiketrains v = neo.segments[0].filter(name='v')[0] f1=pplt.Figure( # plot voltage pplt.Panel(v, ylabel="Membrane potential (mV)", xticks=True, yticks=True, xlim=(0, runTime+100)), # raster plot pplt.Panel(spikes, xlabel="Time (ms)", xticks=True, yticks=True, markersize=2, xlim=(0, runTime+100)), title='Test with label ' + str(label), annotations='Test with label ' + str(label) ) f1.save('plot/'+str(trylabel)+str(label)+'_test.png') f1.fig.texts=[] print("Weights:{}".format(prepost_proj.get('weight', 'list'))) weight_list = [prepost_proj.get('weight', 'list'), prepost_proj.get('weight', format='list', with_address=False)] #predict_label= sim.end() return spikes
v_neo = pop.get_data(variables=["v"]) v = v_neo.segments[0].filter(name='v')[0] print v print "shape" print v.shape sim.end() plot.Figure( splot.SpynnakerPanel(v, ylabel="Pop[0] Membrane potential (mV)", data_labels=[pop.label], xticks=True, yticks=True, xlim=(0, simtime)), plot.Panel(v, ylabel="Pop[0] Membrane potential (mV)", data_labels=[pop.label], xticks=True, yticks=True, xlim=(0, simtime)), # plot spikes splot.SpynnakerPanel(spikes, yticks=True, xticks=True, markersize=5, xlim=(0, simtime)), title="Simple Example", annotations="Simulated with {}".format(sim.name())) plt.show()
def train(spikeTimes,untrained_weights=None): organisedStim = {} labelSpikes = [] #spikeTimes = generate_data() #for j in range(5): # labelSpikes #labelSpikes[label] = [(input_len-1)*v_co+1,(input_len-1)*v_co*2+1,(input_len-1)*v_co*3+1,] if untrained_weights == None: untrained_weights = RandomDistribution('uniform', low=wMin, high=wMaxInit).next(input_size*output_size) #untrained_weights = RandomDistribution('normal_clipped', mu=0.1, sigma=0.05, low=wMin, high=wMaxInit).next(input_size*output_size) untrained_weights = np.around(untrained_weights, 3) #saveWeights(untrained_weights, 'untrained_weightssupmodel1traj') print ("init!") print "length untrained_weights :", len(untrained_weights) if len(untrained_weights)>input_size: training_weights = [[0 for j in range(output_size)] for i in range(input_size)] #np array? size 1024x25 k=0 for i in range(input_size): for j in range(output_size): training_weights[i][j] = untrained_weights[k] k += 1 else: training_weights = untrained_weights connections = [] for n_pre in range(input_size): # len(untrained_weights) = input_size for n_post in range(output_size): # len(untrained_weight[0]) = output_size; 0 or any n_pre connections.append((n_pre, n_post, training_weights[n_pre][n_post], __delay__)) #index runTime = int(max(max(spikeTimes))/3)+100 ##################### sim.setup(timestep=1) #def populations layer1=sim.Population(input_size,sim.SpikeSourceArray, {'spike_times': spikeTimes},label='inputspikes') layer2=sim.Population(output_size,sim.IF_curr_exp,cellparams=cell_params_lif,label='outputspikes') #supsignal=sim.Population(output_size,sim.SpikeSourceArray, {'spike_times': labelSpikes},label='supersignal') #def learning rule stdp = sim.STDPMechanism( weight=untrained_weights, #weight=0.02, # this is the initial value of the weight #delay="0.2 + 0.01*d", timing_dependence=sim.SpikePairRule(tau_plus=tauPlus, tau_minus=tauMinus,A_plus=aPlus, A_minus=aMinus), #weight_dependence=sim.MultiplicativeWeightDependence(w_min=wMin, w_max=wMax), weight_dependence=sim.AdditiveWeightDependence(w_min=wMin, w_max=wMax), #weight_dependence=sim.AdditiveWeightDependence(w_min=0, w_max=0.4), dendritic_delay_fraction=1.0) #def projections #stdp_proj = sim.Projection(layer1, layer2, sim.FromListConnector(connections), synapse_type=stdp) stdp_proj = sim.Projection(layer1, layer2, sim.AllToAllConnector(), synapse_type=stdp) inhibitory_connections = sim.Projection(layer2, layer2, sim.AllToAllConnector(allow_self_connections=False), synapse_type=sim.StaticSynapse(weight=inhibWeight, delay=__delay__), receptor_type='inhibitory') #stim_proj = sim.Projection(supsignal, layer2, sim.OneToOneConnector(), # synapse_type=sim.StaticSynapse(weight=stimWeight, delay=__delay__)) layer1.record(['spikes']) layer2.record(['v','spikes']) #supsignal.record(['spikes']) sim.run(runTime) print("Weights:{}".format(stdp_proj.get('weight', 'list'))) weight_list = [stdp_proj.get('weight', 'list'), stdp_proj.get('weight', format='list', with_address=False)] neo = layer2.get_data(["spikes", "v"]) spikes = neo.segments[0].spiketrains v = neo.segments[0].filter(name='v')[0] #neostim = supsignal.get_data(["spikes"]) #spikestim = neostim.segments[0].spiketrains neoinput= layer1.get_data(["spikes"]) spikesinput = neoinput.segments[0].spiketrains plt.close('all') pplt.Figure( pplt.Panel(spikesinput,xticks=True, yticks=True, markersize=2, xlim=(0,runTime),xlabel='(a) Spikes of Input Layer'), #pplt.Panel(spikestim, xticks=True, yticks=True, markersize=2, xlim=(0,runTime),xlabel='(c) Spikes of Supervised Layer'), pplt.Panel(spikes, xticks=True, xlabel="(b) Spikes of Output Layer", yticks=True, markersize=2, xlim=(0,runTime)), pplt.Panel(v, ylabel="Membrane potential (mV)", xticks=True, yticks=True, xlim=(0,runTime),xlabel='(c) Membrane Potential of Output Layer\nTime (ms)'), title="Two Training", annotations="Twoway Training" ).save('SNN_DVS_un/plot_for_twoway/'+str(trylabel)+'_training.png') #plt.hist(weight_list[1], bins=100) plt.close('all') plt.hist([weight_list[1][0:input_size], weight_list[1][input_size:input_size*2], weight_list[1][input_size*2:]], bins=20, label=['neuron 0', 'neuron 1', 'neuron 2'], range=(0, wMax)) plt.title('weight distribution') plt.xlabel('Weight value') plt.ylabel('Weight count') #plt.show() #plt.show() sim.end() return weight_list[1]
print "post_weights" line_properties = [{'color': 'red'}, {'color': 'blue'}] plot.Figure( # plot spikes plot.Panel(pre_spikes, post_spikes, yticks=True, xticks=True, markersize=5, xlim=(0, simtime), line_properties=line_properties), plot.Panel(pre_spikes, yticks=True, xticks=True, markersize=5, xlim=(0, simtime), color='red', data_labels=["pre"]), plot.Panel(post_spikes, yticks=True, xticks=True, markersize=5, xlim=(0, simtime), color='blue', data_labels=["post"]), title="Balanced Random Network Example", annotations="Simulated with {}".format(sim.name())) plt.show()
Projection(stimulus, neuron_models.get('granule'), OneToOneConnector(), ss) #for i in neuron_models.values(): # i.record(['v']) neuron_models.get('golgi').record(['spikes', 'v']) run(TOT_DURATION) pop_1 = neuron_models.get('golgi') #data1 = pop_gr.get_data(variables=["v"]) neo = pop_1.get_data(variables=["spikes", "v"]) spikes = neo.segments[0].spiketrains v = neo.segments[0].filter(name='v')[0] #Figure(Panel(g_data.get_data('spikes')), title="Prova") #print(data1) simtime = 10 plot.Figure( # plot voltage for first ([0]) neuron plot.Panel(v[0], ylabel="Membrane potential (mV)", data_labels=[pop_1.label], yticks=True, xlim=(0, simtime)), # plot spikes (or in this case spike) #plot.Panel(spikes, yticks=True, xlim=(0, simtime)), #title="Simple Example", #annotations="Simulated with {}".format(name()) ) matplotlib.show()
conn_stim = sim.OneToOneConnector() synapse_stim = sim.StaticSynapse(weight=2.0, delay=delays) sim.Projection(stim_exc, pop_exc, conn_stim, synapse_type=synapse_stim, receptor_type="excitatory") sim.Projection(stim_inh, pop_inh, conn_stim, synapse_type=synapse_stim, receptor_type="excitatory") pop_exc.initialize( v=RandomDistribution("uniform", parameters_pos=[-65.0, -55.0])) pop_inh.initialize( v=RandomDistribution("uniform", parameters_pos=[-65.0, -55.0])) pop_exc.record("spikes") sim.run(simtime) neo = pop_exc.get_data(variables=["spikes"]) spikes = neo.segments[0].spiketrains plot.Figure( # plot spikes plot.Panel(spikes, yticks=True, markersize=5, xlim=(0, simtime)), title="Balanced Random Network Example", annotations="Simulated with {}".format(sim.name())) plt.show()
print i, spike v_exc = neo_exc.segments[0].filter(name='v')[0] neo_inh = pop_inh.get_data(variables=["spikes"]) spikes_inh = neo_inh.segments[0].spiketrains print "spikes_inh" for i in range(n_inh): for spike in spikes_inh[i]: print i, spike plot.Figure( # plot spikes splot.SpynnakerPanel(spikes_exc, yticks=True, markersize=5, xlim=(0, simtime), data_labels=[pop_exc.label]), splot.SpynnakerPanel(spikes_inh, yticks=True, markersize=5, xlim=(0, simtime), data_labels=[pop_inh.label]), splot.SpynnakerPanel(v_exc, ylabel="Pop[0] Membrane potential (mV)", data_labels=[pop_exc.label], xticks=True, yticks=True, xlim=(0, simtime)), title="Balanced Random Cortel-like", annotations="Simulated with {}".format(sim.name())) plt.show()
#print(spikes) v.append(neo[i].segments[0].filter(name='v')[0]) #print (v) sim.end() path = './results/{}/'.format(int(time.time())) for i in range(len(pops)): plot.Figure( # plot voltage for first ([0]) neuron plot.Panel(v[i], ylabel="Membrane potential (mV)", data_labels=[pops[i].label], yticks=True, xlim=(0, SIMTIME)), # plot spikes (or in this case spike) plot.Panel(spikes[i], yticks=True, markersize=3, xlim=(0, SIMTIME)), title="Simple Example", annotations="Simulated with {}".format( sim.name())).save(path + 'figure_{}.png'.format(i)) plt.show() np.savez(file='inputspikes', arr_0=spikes[0]) np.savez(file='pot1', arr_0=v[1]) np.savez(file='pot2', arr_0=v[2]) output_spikes = spikes[2] output_spike_counts = [ output_spikes[i].size for i in range(len(output_spikes))
def lancement_sim(cellSourceSpikes, path, weight_input=0, weight_inter=0, max_time=800000, TIME_STEP=TIME_STEP, input_n=input_n, nb_neuron_int=nb_neuron_int, nb_neuron_out=nb_neuron_out, delay=delay, p_conn_in_int=p_conn_in_int, p_conn_int_out=p_conn_int_out, v_tresh=v_tresh): simulator = 'spinnaker' # le max_delay doit être inférieur à 14*time_step sim.setup(timestep=TIME_STEP, min_delay=delay, max_delay=delay * 2) randoms = np.random.rand(100, 1) #defining network topology lif_curr_exp_params = { 'cm': 1.0, # The capacitance of the LIF neuron in nano-Farads 'tau_m': 20.0, # The time-constant of the RC circuit, in milliseconds 'tau_refrac': 5.0, # The refractory period, in milliseconds 'v_reset': -65.0, # The voltage to set the neuron at immediately after a spike 'v_rest': -65.0, # The ambient rest voltage of the neuron 'v_thresh': -(v_tresh), # The threshold voltage at which the neuron will spike 'tau_syn_E': 5.0, # The excitatory input current decay time-constant 'tau_syn_I': 5.0, # The inhibitory input current decay time-constant 'i_offset': 0.0, # A base input current to add each timestep } # Population d'entrée avec comme source le SpikeSourceArray en paramètre Input = sim.Population(input_n, sim.SpikeSourceArray(spike_times=cellSourceSpikes), label="Input") Input.record("spikes") # Définition des types de neurones et des couches intermédiaire, de sortie, ainsi que celle contenant le neurone de l'attention LIF_Intermediate = sim.IF_curr_exp(**lif_curr_exp_params) Intermediate = sim.Population(nb_neuron_int, LIF_Intermediate, label="Intermediate") Intermediate.record(("spikes", "v")) LIF_Output = sim.IF_curr_exp(**lif_curr_exp_params) Output = sim.Population(nb_neuron_out, LIF_Output, label="Output") Output.record(("spikes", "v")) LIF_delayer = sim.IF_curr_exp(**lif_curr_exp_params) Delay_n = sim.Population(1, LIF_delayer, label="Delay") Delay_n.record(("spikes", "v")) # set the stdp mechanisim parameters, we are going to use stdp in both connections between (input-intermediate) adn (intermediate-output) python_rng = NumpyRNG(seed=98497627) delay = delay # (ms) synaptic time delay #A_minus # définition des connexions entre couches de neurones entrée <=> intermédiaire, intermédiaire <=> sortie # vérificatio pour savoir si on est dans le cas de la première simulation par défault ou si on doit injecter les poids if ((weight_input != 0) or (weight_inter != 0)): # cas ou l'on inject les poids Conn_input_inter = sim.Projection( Input, Intermediate, # Le fromListConnector pour injecter les poids connector=sim.FromListConnector(weight_input), receptor_type="excitatory", label="Connection input to intermediate", # des synapses static pour "suprimer" l'apprentissage synapse_type=sim.StaticSynapse()) Conn_inter_output = sim.Projection( Intermediate, Output, # pre and post population connector=sim.FromListConnector(weight_inter), receptor_type="excitatory", label="Connection intermediate to output", synapse_type=sim.StaticSynapse()) else: # cas par défault Conn_input_inter = sim.Projection( Input, Intermediate, connector=sim.FixedProbabilityConnector( p_conn_in_int, allow_self_connections=False), synapse_type=sim.StaticSynapse( weight=RandomDistribution('normal', (3, 2.9), rng=python_rng)), receptor_type="excitatory", label="Connection input to intermediate") Conn_inter_output = sim.Projection( Intermediate, Output, # pre and post population connector=sim.FixedProbabilityConnector( p_conn_int_out, allow_self_connections=False), synapse_type=sim.StaticSynapse( weight=RandomDistribution('normal', (3, 2.9), rng=python_rng)), receptor_type="excitatory", label="Connection intermediate to output") # définition des connexions inhibitrices des couches intermédiaire et de sortie FixedInhibitory_WTA = sim.StaticSynapse(weight=6) WTA_INT = sim.Projection( Intermediate, Intermediate, connector=sim.AllToAllConnector(allow_self_connections=False), synapse_type=FixedInhibitory_WTA, receptor_type="inhibitory", label="Connection WTA") WTA_OUT = sim.Projection( Output, Output, connector=sim.AllToAllConnector(allow_self_connections=False), synapse_type=FixedInhibitory_WTA, receptor_type="inhibitory", label="Connection WTA") # Connexion avec le neurone de l'attention FixedInhibitory_delayer = sim.StaticSynapse(weight=2) Delay_out = sim.Projection( Delay_n, Output, connector=sim.AllToAllConnector(allow_self_connections=False), synapse_type=FixedInhibitory_delayer, receptor_type="inhibitory", label="Connection WTA") Delay_inter = sim.Projection( Intermediate, Delay_n, connector=sim.AllToAllConnector(allow_self_connections=False), synapse_type=FixedInhibitory_delayer, receptor_type="inhibitory", label="Connection WTA") # On précise le nombre de neurone par coeurs au cas ou sim.set_number_of_neurons_per_core(sim.IF_curr_exp, 255) # on arrondie le temps de simulation, sinon avec les callbacks, on a une boucle infinie pour des temps d'arrêts plus précis que la fréquence des callbacks simtime = ceil(max_time) try: #lancement de la simulation sim.run(simtime) #récupération des infos sur les spike des trois couches neo = Output.get_data(variables=["spikes", "v"]) spikes = neo.segments[0].spiketrains #print(spikes) v = neo.segments[0].filter(name='v')[0] neo_in = Input.get_data(variables=["spikes"]) spikes_in = neo_in.segments[0].spiketrains #print(spikes_in) neo_intermediate = Intermediate.get_data(variables=["spikes", "v"]) spikes_intermediate = neo_intermediate.segments[0].spiketrains #print(spikes_intermediate) v_intermediate = neo_intermediate.segments[0].filter(name='v')[0] #print(v_intermediate) sim.reset() sim.end() except: # Si la simulation fail, on set ces deux variables à zéros pour gérer l'erreur dans le script principal v = 0 spikes = 0 # Création et sauvegarde des graphs des graphs si la simluation s'est bien passée, + envoie des sorties de la fonction if (isinstance(spikes, list) and isinstance(v, AnalogSignal)): plot.Figure( # plot voltage for first ([0]) neuron plot.Panel(v, ylabel="Membrane potential (mV)", data_labels=[Output.label], yticks=True, xlim=(0, simtime)), # plot spikes (or in this case spike) plot.Panel(spikes, yticks=True, markersize=5, xlim=(0, simtime)), title="Spiking activity of the output layer during test", annotations="Simulated with {}".format(sim.name())).save( "./Generated_data/tests/" + path + "/output_layer_membrane_voltage_and_spikes.png") plot.Figure( # plot voltage for first ([0]) neuron plot.Panel(v_intermediate, ylabel="Membrane potential (mV)", data_labels=[Output.label], yticks=True, xlim=(0, simtime)), # plot spikes (or in this case spike) plot.Panel(spikes_intermediate, yticks=True, markersize=5, xlim=(0, simtime)), title="Spiking activity of the intermediate layer during test", annotations="Simulated with {}".format(sim.name())).save( "./Generated_data/tests/" + path + "/intermediate_layer_membrane_voltage_and_spikes.png") return v, spikes else: print( "simulation failed with parameters : (l'affichage des paramètres ayant causés le disfonctionnement de la simulation sera traitée à une date ultérieur, merci!)" ) return 0, 0
sim.run(simtime) pre_neo = pre_pop.get_data(variables=["spikes"]) pre_spikes = pre_neo.segments[0].spiketrains post_neo = post_pop.get_data(variables=["spikes"]) post_spikes = post_neo.segments[0].spiketrains print stdp_projection.getWeights() sim.end() line_properties = [{ 'color': 'red', 'markersize': 5 }, { 'color': 'blue', 'markersize': 2 }] plot.Figure( # plot spikes plot.Panel(pre_spikes, post_spikes, yticks=True, xlim=(0, simtime), line_properties=line_properties), title="STDP Network Example", annotations="Simulated with {}".format(sim.name())) plt.show()
def run_testset_sequence(sim, simtime, filepaths, labels, in_pop, out_pop, pops, no_gaps, pause_between_samples, eventframe_width): """ Function to feed a sequence of samples at once into spiNNaker. Between samples pauses are introduced into the input spiketrains to let the membrane potentials go to zero before applying the next sample :param sim: pyNN simulator object :param simtime: number of simulation timesteps :param filepaths: filepaths of all test samples :param labels: labels of the samples :param in_pop: input population :param out_pop: output population :param pops: populations for measurements :param no_gaps: remove gaps/phases with no events in the DVS samples :param pause_between_samples: pause between each sample is introduced to let membrane potentials decay to zero :param eventframe_width: combine eventframe_width events with consecutive timesteps into the same simultation step """ nr_samples = len(filepaths) input_spikes, starttimes, tot_simtime, durations = generate_input_sample_spikes(filepaths, no_gaps, pause_between_samples, in_pop.size, simtime, eventframe_width) in_pop.set(spike_times=input_spikes) sim.run(tot_simtime) #neo = out_pop.get_data(variables= neo = [] spikes = [] v = [] for i in range(len(pops)): neo.append(pops[i].get_data(variables=["spikes", "v"])) spikes.append(neo[i].segments[0].spiketrains) v.append(neo[i].segments[0].filter(name='v')[0]) sim.end() path = './results/{}/'.format(int(time.time())) for i in range(len(pops)): plot.Figure( # plot voltage for first ([0]) neuron plot.Panel(v[i], ylabel="Membrane potential (mV)", data_labels=[pops[i].label], yticks=True, xlim=(0, tot_simtime)), # plot spikes (or in this case spike) plot.Panel(spikes[i], yticks=True, markersize=3, xlim=(0, tot_simtime)), title="Simple Example", annotations="Simulated with {}".format(sim.name()) ).save(path + 'figure_{}.png'.format(i)) np.savez(file='inputspikes', arr_0=spikes[0]) np.savez(file='pot1', arr_0=v[0]) np.savez(file='pot2', arr_0=v[1]) correct_class_predictions = [0, 0, 0, 0] nr_class_samples = [0, 0, 0, 0] start_index = [0, 0, 0, 0] for i in range(nr_samples): output_spike_counts = [0, 0, 0, 0] for out_neuron, spiketrain in enumerate(neo[len(pops)-1].segments[0].spiketrains): if start_index[out_neuron] >= spiketrain.size-1: continue for k, spiketime in enumerate(spiketrain[start_index[out_neuron]:]): next_start_index = k + start_index[out_neuron] if spiketime < starttimes[i] + simtime: output_spike_counts[out_neuron] += 1 else: break start_index[out_neuron] = next_start_index prediction = np.argmax(output_spike_counts) label = labels[i] if prediction == label: correct_class_predictions[label] += 1 nr_class_samples[label] += 1 correct_predictions = np.sum(correct_class_predictions) print('NR. OF SAMPLES: {}'.format(nr_samples)) print("ACCURACY: {}".format(float(correct_predictions)/nr_samples)) class_accuracies = np.array(correct_class_predictions) / np.array(nr_class_samples, dtype=float) print("CLASS ACCURACIES N L C R: {} {} {} {}".format(class_accuracies[0], class_accuracies[1], class_accuracies[2], class_accuracies[3]))
spikesoutput = neooutput.segments[0].spiketrains plt.close('all') pplt.Figure( pplt.Panel(v, ylabel="Membrane potential (mV)", xticks=True, yticks=True, xlim=(0, runTime)), pplt.Panel(spikesinput, xticks=True, yticks=True, markersize=2, xlim=(0, runTime)), pplt.Panel(spikesoutput, xticks=True, yticks=True, markersize=2, xlim=(0, runTime)), #pplt.Panel(spikestim, xticks=True, yticks=True, markersize=2, xlim=(0,runTime)), pplt.Panel(spikes, xticks=True, xlabel="Time (ms)", yticks=True, markersize=2, xlim=(0, runTime)), title="Training", annotations="Training").save('testplot/training4.png') sim.end()
def main(config): # For some weird opencv/matplotlib bug, need to call matplotlib before opencv plt.plot([1, 2, 3]) plt.close('all') if config['video']: spikes_pos, spikes_neg, cam_res, sim_time = read_spikes_from_video( config['input']) else: cam_res = 32 dvs = DVS_Emulator(cam_res, config) dvs.read_video_source() spikes_pos, spikes_neg = dvs.split_pos_neg_spikes() cam_res = dvs.cam_res sim_time = dvs.sim_time if config['output_file']: dvs.save_output(config['output_file']) #### Display input spikes if config['vis']: if config['video']: vis_spikes = populate_debug_times_from_video( spikes_pos, spikes_neg, cam_res, sim_time) image_slice_viewer(vis_spikes) else: image_slice_viewer(dvs.tuple_to_numpy(), step=dvs.time_bin_ms) n_neurons = cam_res * cam_res sim.setup(timestep=1.0, min_delay=1.0, max_delay=10.0) sim.set_number_of_neurons_per_core(sim.IF_curr_exp, 120) ########################################################## #### Some values for the network # Some values for the network exc_weight = config['exc_weight'] exc_delay = config['exc_delay'] inh_weight = config['inh_weight'] inh_delay = config['inh_delay'] shapes_weight = config['shapes_weight'] shapes_delay = config['shapes_delay'] down_size = config['down_size'] ########################################################## #### Set the first layers of the network # SpikeSourceArray for the positive polarity of the DVS stimulus_pos = sim.Population(n_neurons, sim.SpikeSourceArray(spike_times=spikes_pos), label='stimulus_pos') stimulus_pos.record(['spikes']) # SpikeSourceArray for the negative polarity of the DVS stimulus_neg = sim.Population(n_neurons, sim.SpikeSourceArray(spike_times=spikes_neg), label='stimulus_neg') #################################################################################################################### #### RECEPTIVE FIELDS #################################################################################################################### ########################################################## #### Horizontal receptive field horizontal_layer = sim.Population(n_neurons / (down_size * down_size), sim.IF_curr_exp(), label='horizontal_layer') pos_connections = [] neg_connections = [] for x in range(0, cam_res, down_size): for y in range(0, cam_res, down_size): pos_connections += horizontal_connectivity_pos( cam_res, x, y, cam_res / down_size) neg_connections += horizontal_connectivity_neg( cam_res, x, y, cam_res / down_size) sim.Projection(stimulus_pos, horizontal_layer, sim.FromListConnector(pos_connections), \ receptor_type='excitatory', synapse_type=sim.StaticSynapse(weight=exc_weight, delay=exc_delay)) sim.Projection(stimulus_neg, horizontal_layer, sim.FromListConnector(neg_connections), \ receptor_type='inhibitory', synapse_type=sim.StaticSynapse(weight=inh_weight, delay=inh_delay)) horizontal_layer.record(['spikes']) ########################################################## #### Vertical receptive field vertical_layer = sim.Population(n_neurons / (down_size * down_size), sim.IF_curr_exp(), label='vertical_layer') pos_connections = [] neg_connections = [] for x in range(0, cam_res, down_size): for y in range(0, cam_res, down_size): pos_connections += vertical_connectivity_pos( cam_res, x, y, cam_res / down_size) neg_connections += vertical_connectivity_neg( cam_res, x, y, cam_res / down_size) sim.Projection(stimulus_pos, vertical_layer, sim.FromListConnector(pos_connections), \ receptor_type='excitatory', synapse_type=sim.StaticSynapse(weight=exc_weight, delay=exc_delay)) sim.Projection(stimulus_neg, vertical_layer, sim.FromListConnector(neg_connections), \ receptor_type='inhibitory', synapse_type=sim.StaticSynapse(weight=inh_weight, delay=inh_delay)) vertical_layer.record(['spikes']) ########################################################## #### Left diagonal receptive field left_diag_layer = sim.Population(n_neurons / (down_size * down_size), sim.IF_curr_exp(), label='left_diag_layer') pos_connections = [] neg_connections = [] for x in range(0, cam_res, down_size): for y in range(0, cam_res, down_size): pos_connections += left_diagonal_connectivity_pos( cam_res, x, y, cam_res / down_size) neg_connections += left_diagonal_connectivity_neg( cam_res, x, y, cam_res / down_size) sim.Projection(stimulus_pos, left_diag_layer, sim.FromListConnector(pos_connections), \ receptor_type='excitatory', synapse_type=sim.StaticSynapse(weight=exc_weight, delay=exc_delay)) sim.Projection(stimulus_neg, left_diag_layer, sim.FromListConnector(neg_connections), \ receptor_type='inhibitory', synapse_type=sim.StaticSynapse(weight=inh_weight, delay=inh_delay)) left_diag_layer.record(['spikes']) ########################################################## #### Right diagonal receptive field right_diag_layer = sim.Population(n_neurons / (down_size * down_size), sim.IF_curr_exp(), label='right_diag_layer') pos_connections = [] neg_connections = [] for x in range(0, cam_res, down_size): for y in range(0, cam_res, down_size): pos_connections += right_diagonal_connectivity_pos( cam_res, x, y, cam_res / down_size) neg_connections += right_diagonal_connectivity_neg( cam_res, x, y, cam_res / down_size) sim.Projection(stimulus_pos, right_diag_layer, sim.FromListConnector(pos_connections), \ receptor_type='excitatory', synapse_type=sim.StaticSynapse(weight=exc_weight, delay=exc_delay)) sim.Projection(stimulus_neg, right_diag_layer, sim.FromListConnector(neg_connections), \ receptor_type='inhibitory', synapse_type=sim.StaticSynapse(weight=inh_weight, delay=inh_delay)) right_diag_layer.record(['spikes']) #################################################################################################################### #### SHAPES DETECTORS #################################################################################################################### inhibition_exc_w = 3 inhibition_delay = 1 ########################################################## #### Square shape detector square_layer = sim.Population(n_neurons / (down_size * down_size), sim.IF_curr_exp(), label='square_layer') # The sides of the square are of length 2 * stride + 1 stride = 2 connections = [] for x in range(0, cam_res, down_size): for y in range(0, cam_res, down_size): connections += hor_connections(cam_res / down_size, x, y, stride, cam_res / down_size, shapes_weight, shapes_delay) sim.Projection(horizontal_layer, square_layer, sim.FromListConnector(connections, column_names=['pre', 'post', 'weight', 'delay']), \ receptor_type='excitatory', synapse_type=sim.StaticSynapse(weight=shapes_weight, delay=shapes_delay)) connections = [] for x in range(0, cam_res, down_size): for y in range(0, cam_res, down_size): connections += vert_connections(cam_res / down_size, x, y, stride, cam_res / down_size, shapes_weight, shapes_delay) sim.Projection(vertical_layer, square_layer, sim.FromListConnector(connections, column_names=['pre', 'post', 'weight', 'delay']), \ receptor_type='excitatory', synapse_type=sim.StaticSynapse(weight=shapes_weight, delay=shapes_delay)) # Lateral inhibition lateral_inh_connections = [] for i in range(0, n_neurons / (down_size * down_size)): for j in range(0, n_neurons / (down_size * down_size)): if i != j: lateral_inh_connections.append((i, j)) sim.Projection(square_layer, square_layer, sim.FromListConnector(lateral_inh_connections), \ receptor_type='inhibitory', synapse_type=sim.StaticSynapse(weight=inhibition_exc_w, delay=inhibition_delay)) ########################################################## #### Diamond shape detector diamond_layer = sim.Population(n_neurons / (down_size * down_size), sim.IF_curr_exp(), label='diamond_layer') # The sides of the diamond are of length 2 * stride + 1 stride = 2 connections = [] for x in range(0, cam_res, down_size): for y in range(0, cam_res, down_size): connections += left_diag_connections(cam_res / down_size, x, y, stride, cam_res / down_size, shapes_weight, shapes_delay) sim.Projection(left_diag_layer, diamond_layer, sim.FromListConnector(connections, column_names=['pre', 'post', 'weight', 'delay']), \ receptor_type='excitatory', synapse_type=sim.StaticSynapse(weight=shapes_weight, delay=shapes_delay)) connections = [] for x in range(0, cam_res / down_size): for y in range(0, cam_res / down_size): connections += right_diag_connections(cam_res / down_size, x, y, stride, cam_res / down_size, shapes_weight, shapes_delay) sim.Projection(right_diag_layer, diamond_layer, sim.FromListConnector(connections, column_names=['pre', 'post', 'weight', 'delay']), \ receptor_type='excitatory', synapse_type=sim.StaticSynapse(weight=shapes_weight, delay=shapes_delay)) # Lateral inhibition lateral_inh_connections = [] for i in range(0, n_neurons / (down_size * down_size)): for j in range(0, n_neurons / (down_size * down_size)): if i != j: lateral_inh_connections.append((i, j)) sim.Projection(diamond_layer, diamond_layer, sim.FromListConnector(lateral_inh_connections), \ receptor_type='inhibitory', synapse_type=sim.StaticSynapse(weight=inhibition_exc_w, delay=inhibition_delay)) # ########################################################## # #### Inhibition between shapes # shapes_inhibition = [] # for i in range(0, n_neurons / (down_size * down_size)): # shapes_inhibition.append((i, i)) # sim.Projection(square_layer, diamond_layer, sim.FromListConnector(shapes_inhibition), \ # receptor_type='inhibitory', synapse_type=sim.StaticSynapse(weight=10, delay=1)) # sim.Projection(diamond_layer, square_layer, sim.FromListConnector(shapes_inhibition), \ # receptor_type='inhibitory', synapse_type=sim.StaticSynapse(weight=3, delay=1)) square_layer.record(['spikes']) diamond_layer.record(['spikes']) ########################################################## #### Run the simulation sim.run(sim_time) # neo = stimulus_pos.get_data(variables=['spikes']) # stimulus_pos_spikes = neo.segments[0].spiketrains neo = horizontal_layer.get_data(variables=['spikes']) horizontal_spikes = neo.segments[0].spiketrains neo = vertical_layer.get_data(variables=['spikes']) vertical_spikes = neo.segments[0].spiketrains neo = left_diag_layer.get_data(variables=['spikes']) left_diag_spikes = neo.segments[0].spiketrains neo = right_diag_layer.get_data(variables=['spikes']) right_diag_spikes = neo.segments[0].spiketrains neo = square_layer.get_data(variables=['spikes']) square_spikes = neo.segments[0].spiketrains neo = diamond_layer.get_data(variables=['spikes']) diamond_spikes = neo.segments[0].spiketrains sim.end() ########################################################## #### Plot the receptive fields # line_properties = [{'color': 'red', 'markersize': 2}, {'color': 'blue', 'markersize': 2}] plot.Figure( # plot.Panel(v, ylabel="Membrane potential (mV)", data_labels=[test_neuron.label], yticks=True, xlim=(0, sim_time)), # plot.Panel(pos_spikes, ylabel='Neuron idx', yticks=True, xticks=True, markersize=5, xlim=(0, sim_time)),#, \ # xlim=(0, sim_time), line_properties=line_properties), # plot spikes (or in this case spike) # plot.Panel(stimulus_pos_spikes, ylabel='Neuron idx', yticks=True, xlabel='Pos', xticks=True, markersize=2, xlim=(0, sim_time)), plot.Panel(horizontal_spikes, ylabel='Neuron idx', yticks=True, xlabel='Horizontal', xticks=True, markersize=2, xlim=(0, sim_time)), plot.Panel(vertical_spikes, ylabel='Neuron idx', yticks=True, xlabel='Vertical', xticks=True, markersize=2, xlim=(0, sim_time)), plot.Panel(left_diag_spikes, ylabel='Neuron idx', yticks=True, xlabel='Left diagonal', xticks=True, markersize=2, xlim=(0, sim_time)), plot.Panel(right_diag_spikes, ylabel='Neuron idx', yticks=True, xlabel='Right diagonal', xticks=True, markersize=2, xlim=(0, sim_time)), title='Receptive fields', annotations='Simulated with {}\n {}'.format(sim.name(), config['input'])) plt.show() plot.Figure(plot.Panel(square_spikes, ylabel='Neuron idx', yticks=True, xlabel='Square shape', xticks=True, markersize=2, xlim=(0, sim_time)), plot.Panel(diamond_spikes, ylabel='Neuron idx', yticks=True, xlabel='Diamond shape', xticks=True, markersize=2, xlim=(0, sim_time)), title='Shape detector', annotations='Simulated with {}\n {}'.format( sim.name(), config['input'])) plt.show() if not config['dont_save']: # Process spiketrains for each shape spiking_times_square = shape_spikes_bin(square_spikes) spiking_times_diamond = shape_spikes_bin(diamond_spikes) if config['webcam']: save_video(config, dvs.video_writer_path, [spiking_times_square, spiking_times_diamond], stride, ['r', 'y']) else: save_video(config, config['input'], [spiking_times_square, spiking_times_diamond], stride, ['r', 'y'])
thread0 = threading.Thread(target=send_random_right_press_spikes_thread) thread1 = threading.Thread(target=send_random_right_release_spikes_thread) thread2 = threading.Thread(target=send_random_left_press_spikes_thread) thread3 = threading.Thread(target=send_random_left_release_spikes_thread) thread4 = threading.Thread(target=send_random_jump_press_spikes_thread) thread5 = threading.Thread(target=send_random_jump_release_spikes_thread) thread0.start() thread1.start() thread2.start() thread3.start() thread4.start() thread5.start() sim.run(13000) neo = pre_pop.get_data(variables=["spikes", "v"]) spikes2 = neo.segments[0].spiketrains v2 = neo.segments[0].filter(name='v')[0] sim.end() plot.Figure(plot.Panel(v2, ylabel="Membrane potential (mV)", data_labels=['controls'], yticks=True), plot.Panel(spikes2, yticks=True, markersize=5), title="Simple Example", annotations="Simulated with {}".format(sim.name())) plt.show()
pop_1 = sim.Population(2, sim.IF_curr_exp(), label="pop_1") # Consisting of two input source neurons ...with default parameters Have the # first input neuron spike at time 0.0ms and the second spike at time 1.0ms. input = sim.Population(2, sim.SpikeSourceArray(spike_times=[[0], [1]]), label="input") input_proj = sim.Projection(input, pop_1, sim.OneToOneConnector(), synapse_type=sim.StaticSynapse(weight=5, delay=2)) # Record and plot the spikes received against time. pop_1.record(["spikes"]) sim.run(simtime) neo = pop_1.get_data(variables=["spikes"]) spikes = neo.segments[0].spiketrains print spikes sim.end() plot.Figure( # plot spikes (or in this case spike) plot.Panel(spikes, yticks=True, xticks=True, markersize=5, xlim=(0, simtime)), title="Simple Example", annotations="Simulated with {}".format(sim.name())) plt.show()
out_pop.record(["spikes", "v"]) p.external_devices.activate_live_output_to(out_pop, cochlea_pop) #---runing simulation ---# p.run(t) neo = out_pop.get_data(variables=["spikes", "v"]) spikes = neo.segments[0].spiketrains print spikes v = neo.segments[0].filter(name='v')[0] print v #--- Finish simulation ---# p.end() #--- Variables for saving spikes ---# plot.Figure( # plot voltage for first ([0]) neuron plot.Panel(v, ylabel="Membrane potential (mV)", data_labels=[out_pop.label], yticks=True, xlim=(0, t)), # plot spikes (or in this case spike) plot.Panel(spikes, yticks=True, markersize=5, xlim=(0, t)), title="Simple Example", annotations="Simulated with {}".format(p.name())) plt.show()
def lancement_sim(cellSourceSpikes, max_time=800000, path="default", TIME_STEP=TIME_STEP, input_n=input_n, nb_neuron_int=nb_neuron_int, nb_neuron_out=nb_neuron_out, delay=delay, p_conn_in_int=p_conn_in_int, p_conn_int_out=p_conn_int_out, a_minus=0.6, a_plus=0.6, tau_minus=12.0, tau_plus=10.0, v_tresh=10.0): simulator = 'spinnaker' sim.setup(timestep=TIME_STEP, min_delay=delay, max_delay=delay * 2) randoms = np.random.rand(100, 1) lif_curr_exp_params = { 'cm': 1.0, # The capacitance of the LIF neuron in nano-Farads 'tau_m': 20.0, # The time-constant of the RC circuit, in milliseconds 'tau_refrac': 5.0, # The refractory period, in milliseconds 'v_reset': -65.0, # The voltage to set the neuron at immediately after a spike 'v_rest': -65.0, # The ambient rest voltage of the neuron 'v_thresh': -(v_tresh), # The threshold voltage at which the neuron will spike 'tau_syn_E': 5.0, # The excitatory input current decay time-constant 'tau_syn_I': 5.0, # The inhibitory input current decay time-constant 'i_offset': 0.0, # A base input current to add each timestep } Input = sim.Population(input_n, sim.SpikeSourceArray(spike_times=cellSourceSpikes), label="Input") Input.record("spikes") LIF_Intermediate = sim.IF_curr_exp(**lif_curr_exp_params) Intermediate = sim.Population(nb_neuron_int, LIF_Intermediate, label="Intermediate") Intermediate.record(("spikes", "v")) LIF_Output = sim.IF_curr_exp(**lif_curr_exp_params) Output = sim.Population(nb_neuron_out, LIF_Output, label="Output") Output.record(("spikes", "v")) LIF_delayer = sim.IF_curr_exp(**lif_curr_exp_params) Delay_n = sim.Population(1, LIF_delayer, label="Delay") Delay_n.record(("spikes", "v")) python_rng = NumpyRNG(seed=98497627) delay = delay # (ms) synaptic time delay # Définition du fonctionnement de la stdp stdp_proj = sim.STDPMechanism( timing_dependence=sim.SpikePairRule(tau_plus=tau_plus, tau_minus=tau_minus, A_plus=a_plus, A_minus=a_minus), weight_dependence=sim.AdditiveWeightDependence(w_min=0.1, w_max=6), weight=RandomDistribution('normal', (3, 2.9), rng=python_rng), delay=delay) Conn_input_inter = sim.Projection( Input, Intermediate, connector=sim.FixedProbabilityConnector(p_conn_in_int, allow_self_connections=False), # synapse type set avec la définition de la stdp pour l'aprentsissage synapse_type=stdp_proj, receptor_type="excitatory", label="Connection input to intermediate") # second projection with stdp Conn_inter_output = sim.Projection( Intermediate, Output, # pre and post population connector=sim.FixedProbabilityConnector(p_conn_int_out, allow_self_connections=False), synapse_type=stdp_proj, receptor_type="excitatory", label="Connection intermediate to output") FixedInhibitory_WTA = sim.StaticSynapse(weight=6) WTA_INT = sim.Projection( Intermediate, Intermediate, connector=sim.AllToAllConnector(allow_self_connections=False), synapse_type=FixedInhibitory_WTA, receptor_type="inhibitory", label="Connection WTA") WTA_OUT = sim.Projection( Output, Output, connector=sim.AllToAllConnector(allow_self_connections=False), synapse_type=FixedInhibitory_WTA, receptor_type="inhibitory", label="Connection WTA") FixedInhibitory_delayer = sim.StaticSynapse(weight=2) Delay_out = sim.Projection( Delay_n, Output, connector=sim.AllToAllConnector(allow_self_connections=False), synapse_type=FixedInhibitory_delayer, receptor_type="inhibitory", label="Connection WTA") Delay_inter = sim.Projection( Intermediate, Delay_n, connector=sim.AllToAllConnector(allow_self_connections=False), synapse_type=FixedInhibitory_delayer, receptor_type="inhibitory", label="Connection WTA") sim.set_number_of_neurons_per_core(sim.IF_curr_exp, 255) # Définition des callbacks pour la récupération de l'écart-type sur les connexions entrée-intermédiaire, intermédiaire-sortie weight_recorder1 = WeightRecorder(sampling_interval=1000.0, projection=Conn_input_inter) weight_recorder2 = WeightRecorder(sampling_interval=1000.0, projection=Conn_inter_output) simtime = ceil(max_time) # Initialisation des tableaux pour la récupération des poids weights_int = [] weights_out = [] try: sim.run(simtime, callbacks=[weight_recorder1, weight_recorder2]) neo = Output.get_data(variables=["spikes", "v"]) spikes = neo.segments[0].spiketrains #print(spikes) v = neo.segments[0].filter(name='v')[0] weights_int = Conn_input_inter.get(["weight"], format="list") neo_in = Input.get_data(variables=["spikes"]) spikes_in = neo_in.segments[0].spiketrains #print(spikes_in) neo_intermediate = Intermediate.get_data(variables=["spikes", "v"]) spikes_intermediate = neo_intermediate.segments[0].spiketrains #print(spikes_intermediate) v_intermediate = neo_intermediate.segments[0].filter(name='v')[0] #print(v_intermediate) weights_out = Conn_inter_output.get(["weight"], format="list") sim.reset() sim.end() except: v = 0 spikes = 0 if (isinstance(spikes, list) and isinstance(v, AnalogSignal)): # Récupération des écart-types standard_deviation_out = weight_recorder2.get_standard_deviations() standard_deviation_int = weight_recorder1.get_standard_deviations() t = np.arange(0., max_time, 1.) # Création et sauvegarde des graphs sur les spikes et écart-types savePath = "./Generated_data/training/" + path + "/intermediate_layer_standard_deviation.png" plt.plot(standard_deviation_int) plt.xlabel("callbacks tick (1s)") plt.ylabel("standard deviation of the weights( wmax=6, wmin=0.1 )") plt.savefig(savePath) plt.clf() savePath = "./Generated_data/training/" + path + "/output_layer_standard_deviation.png" plt.plot(standard_deviation_out) plt.xlabel("callbacks tick") plt.ylabel("standard deviation ( wmax=6, wmin=0.1 )") plt.savefig(savePath) plt.clf() savePath = "./Generated_data/training/" + path + "/output_layer_membrane_voltage_and_spikes.png" plot.Figure( # plot voltage for first ([0]) neuron plot.Panel(v, ylabel="Membrane potential (mV)", data_labels=[Output.label], yticks=True, xlim=(0, simtime)), # plot spikes (or in this case spike) plot.Panel(spikes, yticks=True, markersize=5, xlim=(0, simtime)), title="Spiking activity of the output layer during training", annotations="Simulated with {}".format(sim.name())).save(savePath) savePath = "./Generated_data/training/" + path + "/intermediate_layer_membrane_voltage_and_spikes.png" plot.Figure( # plot voltage for first ([0]) neuron plot.Panel(v_intermediate, ylabel="Membrane potential (mV)", data_labels=[Output.label], yticks=True, xlim=(0, simtime)), # plot spikes (or in this case spike) plot.Panel(spikes_intermediate, yticks=True, markersize=5, xlim=(0, simtime)), title="Spiking activity of the intermediate layer during training", annotations="Simulated with {}".format(sim.name())).save(savePath) return v, spikes, weights_int, weights_out else: print( "simulation failed with parmaters parameters : (l'affichage des paramètres ayant causés le disfonctionnement de la simulation sera traitée à une date ultérieur, merci!)" ) return 0, 0, 0, 0