def inhibitory_connect(layers, source, dest1, dest2, dest3, weight): sim.Projection(layers[source].population, layers[dest1].population, sim.OneToOneConnector(), sim.StaticSynapse(weight=weight)) sim.Projection(layers[source].population, layers[dest2].population, sim.OneToOneConnector(), sim.StaticSynapse(weight=weight)) sim.Projection(layers[source].population, layers[dest3].population, sim.OneToOneConnector(), sim.StaticSynapse(weight=weight))
def set_distal_connections(self, connections): for src, tgt, sgm in connections: soma = pynn.PopulationView(self.soma, [int(src)]) segment = pynn.PopulationView(self.distal, [2 * int(tgt) + int(sgm)]) pynn.Projection(soma, segment, pynn.OneToOneConnector(weights=0.014))
def connect(self): # connect populations self.injection = pynn.Projection(self.sources, self.columns, pynn.FixedProbabilityConnector( 0.02, weights=0.0033 * 2), target='excitatory', rng=pynn.random.NumpyRNG(seed=5337)) self.recurrent_excitation = pynn.Projection( self.columns, self.columns, pynn.OneToOneConnector(weights=0.01 * 2), target='excitatory') self.lateral_inhibition = pynn.Projection( self.columns, self.columns, pynn.DistanceDependentProbabilityConnector('d < 10', weights=0.004 * 2), target='inhibitory', rng=pynn.random.NumpyRNG(seed=5337)) self.global_inhibition = pynn.Projection( self.inhibitory_pool, self.columns, pynn.FixedProbabilityConnector(0.8, weights=0.0012 * 2), target='inhibitory', rng=pynn.random.NumpyRNG(seed=5337)) self.forward_inhibition = pynn.Projection( self.sources, self.inhibitory_pool, pynn.FixedProbabilityConnector(0.8, weights=0.0035), target='excitatory', rng=pynn.random.NumpyRNG(seed=5337))
def test_ticket244(): nest = pyNN.nest nest.setup(threads=4) p1 = nest.Population(4, nest.IF_curr_exp()) p1.record('spikes') poisson_generator = nest.Population(3, nest.SpikeSourcePoisson(rate=1000.0)) conn = nest.OneToOneConnector() syn = nest.StaticSynapse(weight=1.0) nest.Projection(poisson_generator, p1.sample(3), conn, syn, receptor_type="excitatory") nest.run(15) p1.get_data()
def create_corner_layer_for(input_layers): shape = input_layers[0].shape total_output_neurons = np.prod(shape) output_population = sim.Population(total_output_neurons, sim.IF_curr_exp(), label='corner') for layer in input_layers: sim.Projection(layer.population, output_population, sim.OneToOneConnector(), sim.StaticSynapse(weight=1., delay=0.5)) return Layer(output_population, shape)
def connect(self): n_cells = self.parameters.config.n_cells n_segments = self.parameters.config.n_segments # connect populations pynn.Projection(self.distal_input, self.distal, pynn.OneToOneConnector(weights=0.025)) for i in range(self.parameters.config.n_columns): # get "compartments" for all cells in this column inhibitions = self.inhibitory[i * n_cells:(i + 1) * n_cells] somas = self.soma[i * n_cells:(i + 1) * n_cells] proximal_input = pynn.PopulationView(self.proximal_input, [i]) # set up connections with columnar symmetry pynn.Projection(inhibitions, somas, pynn.DistanceDependentProbabilityConnector( 'd>=1', weights=0.2), target='SYN_2') # 4 pynn.Projection(proximal_input, somas, pynn.AllToAllConnector(weights=0.08), target='SYN_1') # 1 pynn.Projection(proximal_input, inhibitions, pynn.AllToAllConnector(weights=0.042)) # 2 for j in range(self.parameters.config.n_cells): # get "compartments" for this specific cell segments = self.distal[i * n_cells * n_segments + j * n_segments:i * n_cells * n_segments + (j + 1) * n_segments] inhibition = pynn.PopulationView(self.inhibitory, [i * n_cells + j]) soma = pynn.PopulationView(self.soma, [i * n_cells + j]) # set up connections with cellular symmetry pynn.Projection(segments, inhibition, pynn.AllToAllConnector(weights=0.15), target='inhibitory') # 3 pynn.Projection(segments, soma, pynn.AllToAllConnector(weights=0.15), target='SYN_3') # 3
def connect(self): """Setup connections between populations""" params = self.parameters.projections # generate weights with normal distributed jitter and set up stimulus w = params.stimulus.weight + np.random.normal( 0, params.stimulus.jitter, len(self.columns)) stimulus_connector = pynn.OneToOneConnector(weights=w) pynn.Projection(self.stimulus, self.columns, stimulus_connector) # projection to accumulate/count the number of active columns accumulation_connector = pynn.AllToAllConnector( weights=params.accumulation.weight) pynn.Projection(self.columns, self.kill_switch, accumulation_connector) # projection to inhibit all columns inhibition_connector = pynn.AllToAllConnector( weights=params.inhibition.weight) pynn.Projection(self.kill_switch, self.columns, inhibition_connector, target='inhibitory') # forward inhibition forward_inhibition_connector = pynn.FixedProbabilityConnector( params.forward_inhibition.probability, weights=params.forward_inhibition.weight) pynn.Projection(self.stimulus, self.columns, forward_inhibition_connector, target='inhibitory') # calculate connectivity matrix n_columns = self.parameters.populations.columns.size n_inputs = self.parameters.config.input_size self.connections = (np.random.uniform(0, 1, n_columns * n_inputs) > 0.60).reshape(len(self.columns), n_inputs).astype(np.int64) self.permanences = np.random.normal(.3, .05, n_columns * n_inputs).reshape( len(self.columns), n_inputs)
def test_callback(data_input): global message message = data_input.actual.positions msg_list = list(message) #msg_list[0] = int(message[0].encode('hex'),16) #for i in #msg_list = int(message.encode('hex'),16) #print('============= Received image data.',message) rospy.loginfo('=====received data %r', msg_list[0]) timer = Timer() dt = 0.1 p.setup(timestep=dt) # 0.1ms pop_1 = p.Population(1, p.IF_curr_exp, {}, label="pop_1") #input = p.Population(1, p.SpikeSourceArray, {'spike_times': [[0,3,6]]}, label='input') input = p.Population(1, p.SpikeSourcePoisson, {'rate': (msg_list[0] + 1.6) * 100}) stat_syn = p.StaticSynapse(weight=50.0, delay=1) input_proj = p.Projection(input, pop_1, p.OneToOneConnector(), synapse_type=stat_syn, receptor_type='excitatory') pop_1.record(['v', 'spikes']) p.run(10) pop_1_data = pop_1.get_data() spikes = pop_1_data.segments[0].spiketrains[0] mean_rate = int(gaussian_convolution(spikes, dt)) rospy.loginfo('=====mean_rate %r', mean_rate) # mean_rate = 64 rate_command = mean_rate # rate coding of the spike train ''' pub = rospy.Publisher('/cmd_vel_mux/input/teleop', Twist, queue_size=10) # construct the output command command = Twist() command.linear.x = rate_command*0.02 command.angular.z = rate_command/50000. pub.publish(command) ''' pub = rospy.Publisher('/arm_controller/follow_joint_trajectory/goal', FollowJointTrajectoryActionGoal, queue_size=10) command = FollowJointTrajectoryActionGoal() command.header.stamp = rospy.Time.now() command.goal.trajectory.joint_names = ['elbow'] point = JointTrajectoryPoint() point.positions = [rate_command / 10] point.time_from_start = rospy.Duration(1) command.goal.trajectory.points.append(point) pub.publish(command) rospy.loginfo('=====send command %r', command.goal.trajectory.points[0]) fig_settings = { 'lines.linewidth': 0.5, 'axes.linewidth': 0.5, 'axes.labelsize': 'small', 'legend.fontsize': 'small', 'font.size': 8 } plt.rcParams.update(fig_settings) fig1 = plt.figure(1, figsize=(6, 8)) def plot_spiketrains(segment): for spiketrain in segment.spiketrains: y = np.ones_like(spiketrain) * spiketrain.annotations['source_id'] plt.plot(spiketrain, y, '.') plt.ylabel(segment.name) plt.setp(plt.gca().get_xticklabels(), visible=False) def plot_signal(signal, index, colour='b'): label = "Neuron %d" % signal.annotations['source_ids'][index] plt.plot(signal.times, signal[:, index], colour, label=label) plt.ylabel("%s (%s)" % (signal.name, signal.units._dimensionality.string)) plt.setp(plt.gca().get_xticklabels(), visible=False) plt.legend() print("now plotting the network---------------") rospy.loginfo('--------now plotting---------------') n_panels = sum(a.shape[1] for a in pop_1_data.segments[0].analogsignalarrays) + 2 plt.subplot(n_panels, 1, 1) plot_spiketrains(pop_1_data.segments[0]) panel = 3 for array in pop_1_data.segments[0].analogsignalarrays: for i in range(array.shape[1]): plt.subplot(n_panels, 1, panel) plot_signal(array, i, colour='bg'[panel % 2]) panel += 1 plt.xlabel("time (%s)" % array.times.units._dimensionality.string) plt.setp(plt.gca().get_xticklabels(), visible=True) #
# cells.initialize('regime', 1002) # temporary hack cells.initialize('Regime9ML', 1.0) # temporary hack # from numpy import r input = sim.Population(3, sim.SpikeSourceArray) numpy.random.seed(12345) input[0].spike_times = numpy.add.accumulate( numpy.random.exponential(1000.0 / 100.0, size=1000)) input[1].spike_times = numpy.add.accumulate( numpy.random.exponential(1000.0 / 20.0, size=1000)) input[2].spike_times = numpy.add.accumulate( numpy.random.exponential(1000.0 / 50.0, size=1000)) connector = sim.OneToOneConnector(weights=1.0, delays=0.5) conn = [ sim.Projection(input[0:1], cells, connector, target='AMPA_spikeinput'), sim.Projection(input[1:2], cells, connector, target='GABAa_spikeinput'), sim.Projection(input[2:3], cells, connector, target='GABAb_spikeinput') ] cells._record('iaf_V') cells._record('AMPA_g') cells._record('GABAa_g') cells._record('GABAb_g') cells.record() sim.run(100.0)
V1 = network.get_population("V1LayerToPlot") V2 = network.get_population("V2LayerToPlot") V4Bright = network.get_population("V4Brightness") V4Dark = network.get_population("V4Darkness") LGNBright.record("spikes") LGNDark.record("spikes") V1.record("spikes") V2.record("spikes") V4Bright.record("spikes") V4Dark.record("spikes") if inputPoisson: LGNBrightInput = sim.Population(ImageNumPixelRows * ImageNumPixelColumns, sim.SpikeSourcePoisson()) LGNDarkInput = sim.Population(ImageNumPixelRows * ImageNumPixelColumns, sim.SpikeSourcePoisson()) sim.Projection(LGNBrightInput, LGNBright, sim.OneToOneConnector(), sim.StaticSynapse(weight=connections['brightInputToLGN'])) sim.Projection(LGNDarkInput, LGNDark, sim.OneToOneConnector(), sim.StaticSynapse(weight=connections['darkInputToLGN'])) if numSegmentationLayers > 1: if useSurfaceSegmentation: SurfaceSegmentationOff = network.get_population( "SurfaceSegmentationOff") SurfaceSegmentationOn = network.get_population("SurfaceSegmentationOn") if useBoundarySegmentation: BoundarySegmentationOff = network.get_population( "BoundarySegmentationOff") BoundarySegmentationOn = network.get_population( "BoundarySegmentationOn") network.get_population("BoundarySegmentationOnInter3").inject( sim.DCSource(amplitude=constantInput, start=0.0, stop=simTime))
sim.IF_cond_alpha(**cell_params), label="inhib_pop") spike_source_1 = sim.Population( 1, sim.SpikeSourceArray(spike_times=spike_time_for_id_1)) spike_source_2 = sim.Population( 1, sim.SpikeSourceArray(spike_times=spike_time_for_id_2)) spike_source_3 = sim.Population( 1, sim.SpikeSourceArray(spike_times=spike_time_for_id_3)) spike_source_4 = sim.Population( 1, sim.SpikeSourceArray(spike_times=spike_time_for_id_4)) spike_source_9 = sim.Population( 1, sim.SpikeSourceArray(spike_times=spike_time_for_id_9)) spike_2_conn_for_1 = sim.Projection(spike_source_1, cann_pop[1:2], sim.OneToOneConnector(), sim.StaticSynapse(weight=0.002, delay=0.1)) spike_2_conn_for_2 = sim.Projection(spike_source_2, cann_pop[2:3], sim.OneToOneConnector(), sim.StaticSynapse(weight=0.002, delay=0.1)) spike_2_conn_for_3 = sim.Projection(spike_source_3, cann_pop[3:4], sim.OneToOneConnector(), sim.StaticSynapse(weight=0.002, delay=0.1)) spike_2_conn_for_4 = sim.Projection(spike_source_4, cann_pop[4:5], sim.OneToOneConnector(), sim.StaticSynapse(weight=0.002, delay=0.1)) spike_2_conn_for_9 = sim.Projection(spike_source_9, cann_pop[9:10], sim.OneToOneConnector(), sim.StaticSynapse(weight=0.002, delay=0.1)) cann_2_cann = sim.Projection(
#generate_spike_times = [[0], [500], [1000], [1500], [2000], [2500], [3000], # [3500], [4000], [4500]] #, [5000]] #spike_source = sim.Population(n_neurons, # sim.SpikeSourceArray( # spike_times = generate_spike_times)) spike_source = sim.Population( n_neurons, sim.SpikeSourceArray(spike_times=[0, 1000, 3000])) # populations and projections layer_1 = sim.Population(n_neurons, sim.IF_curr_alpha(), label="layer_1") ''' layer_2 = sim.Population(n_neurons, sim.IF_curr_alpha(), label = "layer_2") ''' proj_src_2_l1 = sim.Projection(spike_source, layer_1, sim.OneToOneConnector()) ''' proj_l1_2_l2 = sim.Projection(layer_1, layer_2, sim.OneToOneConnector()) ''' sim.run(sim_time) layer_1.record(('spikes', 'v')) #layer_2.record(['spikes', 'v']) #layer_1.record(['v', 'spikes']) #layer_2.record(['v', 'spikes']) # plot the spikes data_1 = layer_1.get_data().segments[0] vm = data_1.filter(name="v") Figure(Panel(vm, ylabel="Memb. Pot."),
''' #output poission pop = p.Population( num_output, p.SpikeSourcePoisson, { 'rate': MIN_rate, #test_x[i], 'start': (epo * num_epo + i) * (dur_train + silence), 'duration': dur_train }) temp_popv = p.PopulationView(pop, np.nonzero(train_y[ind])[0]) temp_popv.set('rate', teaching_rate) TeachingPoission.append(pop) #print ImagePoission[10].get('start') ee_connector = p.OneToOneConnector(weights=3.0) for i in range(num_train * num_epo * 1): p.Projection(ImagePoission[i], pop_input, ee_connector, target='excitatory') pop_output = p.Population(num_output, p.IF_curr_exp, cell_params_lif) weight_max = 1.3 stdp_model = p.STDPMechanism( timing_dependence=p.SpikePairRule(tau_plus=10., tau_minus=10.0), weight_dependence=p.MultiplicativeWeightDependence(w_min=0.0, w_max=weight_max, A_plus=0.01, A_minus=0.01) #AdditiveWeightDependence
label='Background Noise') background_noise_to_exc = simulator.Projection( noise_population, cortical_neurons_exc, simulator.AllToAllConnector(), noise_syn) background_noise_to_inh = simulator.Projection( noise_population, cortical_neurons_inh, simulator.AllToAllConnector(), noise_syn) else: # If correlated is False, all cortical neurons receive independent noise noise_population_exc = simulator.Population( Ncell_exc**2, noise_model, label='Background Noise to Exc') noise_population_inh = simulator.Population( Ncell_inh**2, noise_model, label='Background Noise to Inh') background_noise_to_exc = simulator.Projection( noise_population_exc, cortical_neurons_exc, simulator.OneToOneConnector(), noise_syn) background_noise_to_inh = simulator.Projection( noise_population_inh, cortical_neurons_inh, simulator.OneToOneConnector(), noise_syn) ############################# ## Thalamo-Cortical connections ############################# # Sample random phases and orientations phases_space = np.linspace(-180, 180, 20) orientation_space = np.linspace(-90, 90, 20) phases_exc = np.random.rand(Ncell_exc**2) * 360 # Phases continium #phases_exc = np.random.choice(phases_space, Ncell_exc*2) # Phases discrete
spike_times = spike_input)) neg_spike_src = sim.Population(1, sim.SpikeSourceArray( spike_times = neg_spike_times)) #spike_2_conn_for_1 = sim.Projection(spike_source_1, hd_cann_pop[1:2], sim.OneToOneConnector(), # sim.StaticSynapse(weight = 0.002, delay = 0.1)) #spike_2_conn_for_2 = sim.Projection(spike_source_2, hd_cann_pop[2:3], sim.OneToOneConnector(), # sim.StaticSynapse(weight = 0.002, delay = 0.1)) spike_2_conn_for_3 = sim.Projection(hd_spike_src, hd_cann_pop[3:4], sim.AllToAllConnector(), sim.StaticSynapse(weight = 0.002, delay = 0.1)) #spike_2_conn_for_4 = sim.Projection(spike_source_4, hd_cann_pop[4:5], sim.OneToOneConnector(), # sim.StaticSynapse(weight = 0.002, delay = 0.1)) #spike_2_conn_for_9 = sim.Projection(spike_source_9, hd_cann_pop[9:10], sim.OneToOneConnector(), # sim.StaticSynapse(weight = 0.002, delay = 0.1)) pos_spikes = sim.Projection(pos_spike_src, pos_rot_conj[3:4], sim.OneToOneConnector(), sim.StaticSynapse(weight = 0.2, delay = 0.1)) neg_spikes = sim.Projection(neg_spike_src, neg_rot_conj[4:5], sim.OneToOneConnector(), sim.StaticSynapse(weight = 0.2, delay = 0.1)) # Connections/ Projections hd_cann_2_hd_cann = sim.Projection(hd_cann_pop, hd_cann_pop, sim.FromListConnector(hd_cann_connector, column_names=["weight"]), sim.StaticSynapse(weight = 0.0001, delay = 75)) hd_cann_2_inh = sim.Projection(hd_cann_pop, inhib_pop, sim.AllToAllConnector(), sim.StaticSynapse(weight = 0.02, delay = 0.1), receptor_type = "excitatory")
def create_brain(): """ Initializes PyNN with the neuronal network that has to be simulated for the experiment """ GR_PARAMS = {'cm': 0.002, 'v_rest': -70.0, 'tau_m': 100.0, 'e_rev_E': 0.0, 'e_rev_I': -75.0, 'v_reset': -70.0, 'v_thresh': -40.0, 'tau_refrac': 1.0, 'tau_syn_E': 0.5, 'tau_syn_I': 2.0} GO_PARAMS = {'cm': 0.002, 'v_rest': -70.0, 'tau_m': 100.0, 'e_rev_E': 0.0, 'e_rev_I': -75.0, 'v_reset': -70.0, 'v_thresh': -40.0, 'tau_refrac': 1.0, 'tau_syn_E': 0.5, 'tau_syn_I': 2.0} PC_PARAMS = {'C_m': 0.314, 'g_L': 0.012, 'E_L': -70.0, 'E_ex': 0.0, 'E_in': -75.0, 'e_cs': 0.0, 'V_reset': -70.0, 'V_th': -52.0, 't_ref': 1.0, 'tau_syn_ex': 0.85, 'tau_syn_in': 5.45, 'tau_syn_cs': 0.85} VN_PARAMS = {'C_m': 0.002, 'g_L': 0.0002, 'E_L': -70.0, 'E_ex': 0.0, 'E_in': -80.0, 'e_ts': 0.0, 'V_reset': -70.5, 'V_th': -40.0, 't_ref': 1.0, 'tau_syn_ex': 0.5, 'tau_syn_in': 7.0, 'tau_syn_ts': 0.85, 'tau_cos': 10.0, 'exponent': 2.0} ##THIS MODULE CAN BE DOWNLOADED FROM https://github.com/jgarridoalcazar/SpikingCerebellum/ #try: # nest.Install('cerebellummodule') #except nest.NESTError: # pass parrot_neuron = sim.native_cell_type('parrot_neuron') # Create MF population MF_population = sim.Population(num_MF_neurons,parrot_neuron,{},label='MFLayer') # Create GOC population GOC_population = sim.Population(num_GOC_neurons,sim.IF_cond_alpha(**GO_PARAMS),label='GOCLayer') # Create MF-GO connections mf_go_connections = sim.Projection(MF_population, GOC_population, sim.OneToOneConnector(), sim.StaticSynapse(delay=1.0, weight=mf_go_weights)) # Create GrC population GC_population = sim.Population(num_GC_neurons,sim.IF_cond_alpha(**GR_PARAMS),label='GCLayer') # Random distribution for synapses delays and weights delay_distr = RandomDistribution('uniform', (1.0, 10.0), rng=NumpyRNG(seed=85524)) weight_distr_MF = RandomDistribution('uniform', (mf_gc_weights*0.8, mf_gc_weights*1.2), rng=NumpyRNG(seed=85524)) weight_distr_GO = RandomDistribution('uniform', (go_gc_weights*0.8, go_gc_weights*1.2), rng=NumpyRNG(seed=24568)) # Create MF-GC and GO-GC connections float_num_MF_neurons = float (num_MF_neurons) for i in range (num_MF_neurons): GC_medium_index = int(round((i / float_num_MF_neurons) * num_GC_neurons)) GC_lower_index = GC_medium_index - 40 GC_upper_index = GC_medium_index + 60 if(GC_lower_index < 0): GC_lower_index = 0 elif(GC_upper_index > num_GC_neurons): GC_upper_index = num_GC_neurons if(GC_lower_index < GC_medium_index): GO_GC_con1 = sim.Projection(sim.PopulationView(GOC_population, range(i, i+1)), sim.PopulationView(GC_population, range(GC_lower_index, GC_medium_index)), sim.AllToAllConnector(), sim.StaticSynapse(delay=delay_distr, weight=weight_distr_GO)) MF_GC_con2 = sim.Projection(sim.PopulationView(MF_population, range(i, i+1)), sim.PopulationView(GC_population, range(GC_medium_index, GC_medium_index + 20)), sim.AllToAllConnector(), sim.StaticSynapse(delay=delay_distr, weight=weight_distr_MF)) if((GC_medium_index + 20) < GC_upper_index): GO_GC_con3 = sim.Projection(sim.PopulationView(GOC_population, range(i, i+1)), sim.PopulationView(GC_population, range(GC_medium_index + 20, GC_upper_index)), sim.AllToAllConnector(), sim.StaticSynapse(delay=delay_distr, weight=weight_distr_GO)) # Create PC population (THIS MODEL HAS BEEN DEFINED IN THE CEREBELLUMMODULE PACKAGE: https://github.com/jgarridoalcazar/SpikingCerebellum/) pc_neuron = sim.native_cell_type('iaf_cond_exp_cs') PC_population = sim.Population(num_PC_neurons,pc_neuron(**PC_PARAMS),label='PCLayer') # Create VN population (THIS MODEL HAS BEEN DEFINED IN THE CEREBELLUMMODULE PACKAGE: https://github.com/jgarridoalcazar/SpikingCerebellum/) vn_neuron = sim.native_cell_type('iaf_cond_exp_cos') VN_population = sim.Population(num_VN_neurons,vn_neuron(**VN_PARAMS),label='VNLayer') # Create IO population IO_population = sim.Population(num_IO_neurons,parrot_neuron,{},label='IOLayer') # Create MF-VN learning rule (THIS MODEL HAS BEEN DEFINED IN THE CEREBELLUMMODULE PACKAGE: https://github.com/jgarridoalcazar/SpikingCerebellum/) stdp_cos = sim.native_synapse_type('stdp_cos_synapse')(**{'weight':mf_vn_weights, 'delay':1.0, 'exponent': 2.0, 'tau_cos': 5.0, 'A_plus': 0.0000009, 'A_minus': 0.00001, 'Wmin': 0.0005, 'Wmax': 0.007}) # Create MF-VN connections mf_vn_connections = sim.Projection(MF_population, VN_population, sim.AllToAllConnector(), receptor_type='AMPA', # synapse_type = sim.StaticSynapse(delay=1.0, weight=mf_vn_weights)) synapse_type = stdp_cos) # Create PC-VN connections pc_vn_connections = sim.Projection(PC_population, VN_population, sim.OneToOneConnector(), receptor_type='GABA', synapse_type = sim.StaticSynapse(delay=1.0, weight=pc_vn_weights)) # This second synapse with "receptor_type=TEACHING_SIGNAL" propagates the learning signals that drive the plasticity mechanisms in MF-VN synapses pc_vn_connections = sim.Projection(PC_population, VN_population, sim.OneToOneConnector(), receptor_type='TEACHING_SIGNAL', synapse_type = sim.StaticSynapse(delay=1.0, weight=0.0)) # Create MF-VN learning rule (THIS MODEL HAS BEEN DEFINED IN THE CEREBELLUMMODULE PACKAGE: https://github.com/jgarridoalcazar/SpikingCerebellum/) stdp_syn = sim.native_synapse_type('stdp_sin_synapse')(**{'weight':gc_pc_weights, 'delay':1.0, 'exponent': 10, 'peak': 100.0, 'A_plus': 0.000014, 'A_minus': 0.00008, 'Wmin': 0.000, 'Wmax': 0.010}) # Create GC-PC connections gc_pc_connections = sim.Projection(GC_population, PC_population, sim.AllToAllConnector(), receptor_type='AMPA', # synapse_type = sim.StaticSynapse(delay=1.0, weight=gc_pc_weights)) synapse_type = stdp_syn) # Create IO-PC connections. This synapse with "receptor_type=COMPLEX_SPIKE" propagates the learning signals that drive the plasticity mechanisms in GC-PC synapses io_pc_connections = sim.Projection(IO_population, PC_population, sim.OneToOneConnector(), receptor_type='COMPLEX_SPIKE', synapse_type = sim.StaticSynapse(delay=1.0, weight=io_pc_weights)) # Group all neural layers population = MF_population + GOC_population + GC_population + PC_population + VN_population + IO_population # Set Vm to resting potential # sim.initialize(PC_population, V_m=PC_population.get('E_L')) # sim.initialize(VN_population, V_m=VN_population.get('E_L')) return population
def create_S2_layers(C1_layers: Dict[float, Sequence[Layer]], feature_size, s2_prototype_cells, refrac_s2=.1, stdp=True, inhibition=True)\ -> Dict[float, List[Layer]]: """ Creates all prototype S2 layers for all sizes. Parameters: `layers_dict`: A dictionary containing for each size a list of C1 layers, for each feature one `feature_size`: `s2_prototype_cells`: `refrac_s2`: `stdp`: Returns: A dictionary containing for each size a list of different S2 layers, for each prototype one. """ f_s = feature_size initial_weight = 25 / (f_s * f_s) weight_rng = rnd.RandomDistribution('normal', mu=initial_weight, sigma=initial_weight / 20) i_offset_rng = rnd.RandomDistribution('normal', mu=.5, sigma=.45) weights = list( map(lambda x: weight_rng.next() * 1000, range(4 * f_s * f_s))) S2_layers = {} i_offsets = list( map(lambda x: i_offset_rng.next(), range(s2_prototype_cells))) ndicts = list(map(lambda x: {}, range(s2_prototype_cells))) ondicts = list(map(lambda x: {}, range(s2_prototype_cells))) omdicts = list(map(lambda x: {}, range(s2_prototype_cells))) for size, layers in C1_layers.items(): n, m = how_many_squares_in_shape(layers[0].shape, (f_s, f_s), f_s) if stdp: l_i_offsets = [list(map(lambda x: rnd.RandomDistribution('normal', mu=i_offsets[i], sigma=.25).next(), range(n * m)))\ for i in range(s2_prototype_cells)] else: l_i_offsets = np.zeros((s2_prototype_cells, n * m)) print('S2 Shape', n, m) layer_list = list( map( lambda i: Layer( sim.Population(n * m, sim.IF_curr_exp(i_offset=l_i_offsets[i], tau_refrac=refrac_s2), structure=space.Grid2D(aspect_ratio=m / n), label=str(i)), (n, m)), range(s2_prototype_cells))) for S2_layer in layer_list: for C1_layer in layers: S2_layer.projections[C1_layer.population.label] =\ connect_layer_to_layer(C1_layer, S2_layer, (f_s, f_s), f_s, [[w] for w in weights[:f_s * f_s]], stdp=stdp, initial_weight=initial_weight, ndicts=ndicts, ondicts=ondicts, omdicts=omdicts) S2_layers[size] = layer_list # Set the labels of the shared connections if stdp: t = time.clock() print('Set shared labels') for s2_label_dicts in [ndicts, ondicts, omdicts]: for i in range(s2_prototype_cells): w_iter = weights.__iter__() for label, (source, target) in s2_label_dicts[i].items(): conns = nest.GetConnections(source=source, target=target) nest.SetStatus(conns, { 'label': label, 'weight': w_iter.__next__() }) print('Setting labels took', time.clock() - t) if inhibition: # Create inhibitory connections between the S2 cells # First between the neurons of the same layer... inh_weight = -10 inh_delay = .1 print('Create S2 self inhibitory connections') for layer_list in S2_layers.values(): for layer in layer_list: sim.Projection( layer.population, layer.population, sim.AllToAllConnector(allow_self_connections=False), sim.StaticSynapse(weight=inh_weight, delay=inh_delay)) # ...and between the layers print('Create S2 cross-scale inhibitory connections') for i in range(s2_prototype_cells): for layer_list1 in S2_layers.values(): for layer_list2 in S2_layers.values(): if layer_list1[i] != layer_list2[i]: sim.Projection( layer_list1[i].population, layer_list2[i].population, sim.AllToAllConnector(), sim.StaticSynapse(weight=inh_weight, delay=inh_delay)) if stdp: # Create the inhibition between different prototype layers print('Create S2 cross-prototype inhibitory connections') for layer_list in S2_layers.values(): for layer1 in layer_list: for layer2 in layer_list: if layer1 != layer2: sim.Projection( layer1.population, layer2.population, sim.OneToOneConnector(), sim.StaticSynapse(weight=inh_weight - 1, delay=inh_delay)) return S2_layers
def run_retina(params): """Run the retina using the specified parameters.""" print "Setting up simulation" timer = Timer() timer.start() # start timer on construction pyNN.setup(timestep=params['dt'], max_delay=params['syn_delay'], threads=params['threads'], rng_seeds=params['kernelseeds']) N = params['N'] phr_ON = pyNN.Population((N, N), pyNN.native_cell_type('dc_generator')()) phr_OFF = pyNN.Population((N, N), pyNN.native_cell_type('dc_generator')()) noise_ON = pyNN.Population( (N, N), pyNN.native_cell_type('noise_generator')(mean=0.0, std=params['noise_std'])) noise_OFF = pyNN.Population( (N, N), pyNN.native_cell_type('noise_generator')(mean=0.0, std=params['noise_std'])) phr_ON.set(start=params['simtime'] / 4, stop=params['simtime'] / 4 * 3, amplitude=params['amplitude'] * params['snr']) phr_OFF.set(start=params['simtime'] / 4, stop=params['simtime'] / 4 * 3, amplitude=-params['amplitude'] * params['snr']) # target ON and OFF populations v_init = params['parameters_gc'].pop('Vinit') out_ON = pyNN.Population((N, N), pyNN.native_cell_type('iaf_cond_exp_sfa_rr')( **params['parameters_gc'])) out_OFF = pyNN.Population((N, N), pyNN.native_cell_type('iaf_cond_exp_sfa_rr')( **params['parameters_gc'])) out_ON.initialize(v=v_init) out_OFF.initialize(v=v_init) #print "Connecting the network" retina_proj_ON = pyNN.Projection(phr_ON, out_ON, pyNN.OneToOneConnector()) retina_proj_ON.set(weight=params['weight']) retina_proj_OFF = pyNN.Projection(phr_OFF, out_OFF, pyNN.OneToOneConnector()) retina_proj_OFF.set(weight=params['weight']) noise_proj_ON = pyNN.Projection(noise_ON, out_ON, pyNN.OneToOneConnector()) noise_proj_ON.set(weight=params['weight']) noise_proj_OFF = pyNN.Projection(noise_OFF, out_OFF, pyNN.OneToOneConnector()) noise_proj_OFF.set(weight=params['weight']) out_ON.record('spikes') out_OFF.record('spikes') # reads out time used for building buildCPUTime = timer.elapsedTime() print "Running simulation" timer.start() # start timer on construction pyNN.run(params['simtime']) simCPUTime = timer.elapsedTime() out_ON_DATA = out_ON.get_data().segments[0] out_OFF_DATA = out_OFF.get_data().segments[0] print "\nRetina Network Simulation:" print(params['description']) print "Number of Neurons : ", N**2 print "Output rate (ON) : ", out_ON.mean_spike_count(), \ "spikes/neuron in ", params['simtime'], "ms" print "Output rate (OFF) : ", out_OFF.mean_spike_count(), \ "spikes/neuron in ", params['simtime'], "ms" print "Build time : ", buildCPUTime, "s" print "Simulation time : ", simCPUTime, "s" return out_ON_DATA, out_OFF_DATA
stimSpikes = np.arange(stimInterval, (stimNoSpikes + 0.5) * stimInterval, stimInterval) measureSpikes = stimSpikes + delayStimMeasure stim = pynn.Population(1, pynn.SpikeSourceArray, {'spike_times': stimSpikes}) measure = pynn.Population(1, pynn.SpikeSourceArray, {'spike_times': measureSpikes}) #create neuron neuron = pynn.Population(1, pynn.IF_cond_exp) #init and import custom NEST synapse model pynn.nest.SetDefaults(synapseModel, synapseParams) stdpModel = pynn.NativeSynapseDynamics(synapseModel) #connect stimuli connStim = pynn.OneToOneConnector(weights=stimWeight) connMeasure = pynn.OneToOneConnector(weights=measureWeight) pynn.Projection(stim, neuron, connStim, target='excitatory') prj = pynn.Projection(measure, neuron, connMeasure, synapse_dynamics=stdpModel, target='excitatory') #record spike times and membrane potential neuron.record() neuron.record_v() connSTDP = pynn.nest.FindConnections(measure) weightList = [] aCausalList = []
} sim.setup() neuron1 = sim.Population(n, sim.IF_cond_alpha(**cell_params), label="neuron1") neuron2 = sim.Population(n, sim.IF_cond_alpha(**cell_params), label="neuron2") spike_times = [1000., 2000.] spike_source = sim.Population(1, sim.SpikeSourceArray(spike_times=spike_times)) conn = sim.Projection(spike_source, neuron1[spiky:spiky + 1], sim.AllToAllConnector(), sim.StaticSynapse(weight=0.002, delay=1.)) n2n_conn = sim.Projection(neuron1, neuron2, sim.OneToOneConnector(), sim.StaticSynapse(weight=0.002, delay=1.)) spike_source.record('spikes') neuron1.record(('v', 'spikes')) neuron2.record(('v', 'spikes')) sim.run(5000.0) #print neuron1.get_spike_counts() from pyNN.utility.plotting import Figure, Panel data1 = neuron1.get_data().segments[0] data2 = neuron1.get_data().segments[0] vm = data1.filter(name="v")[0] Figure(Panel(vm, ylabel="Membrane potential (mV)", yticks=True),
def estimate_kb(cell_params_lif): cell_para = copy.deepcopy(cell_params_lif) random.seed(0) p.setup(timestep=1.0, min_delay=1.0, max_delay=16.0) run_s = 10. runtime = 1000. * run_s max_rate = 1000. ee_connector = p.OneToOneConnector(weights=1.0, delays=2.0) pop_list = [] pop_output = [] pop_source = [] x = np.arange(0., 1.01, 0.1) count = 0 trail = 10 for i in x: for j in range(trail): #trails for average pop_output.append(p.Population(1, p.IF_curr_exp, cell_para)) poisson_spikes = mu.poisson_generator(i * max_rate, 0, runtime) pop_source.append( p.Population(1, p.SpikeSourceArray, {'spike_times': poisson_spikes})) p.Projection(pop_source[count], pop_output[count], ee_connector, target='excitatory') pop_output[count].record() count += 1 count = 0 for i in x: cell_para['i_offset'] = i pop_list.append(p.Population(1, p.IF_curr_exp, cell_para)) pop_list[count].record() count += 1 pop_list[count - 1].record_v() p.run(runtime) rate_I = np.zeros(count) rate_P = np.zeros(count) rate_P_max = np.zeros(count) rate_P_min = np.ones(count) * 1000. for i in range(count): spikes = pop_list[i].getSpikes(compatible_output=True) rate_I[i] = len(spikes) / run_s for j in range(trail): spikes = pop_output[i * trail + j].getSpikes(compatible_output=True) spike_num = len(spikes) / run_s rate_P[i] += spike_num if spike_num > rate_P_max[i]: rate_P_max[i] = spike_num if spike_num < rate_P_min[i]: rate_P_min[i] = spike_num rate_P[i] /= trail ''' #plot_spikes(spikes, 'Current = 10. mA') plt.plot(x, rate_I, label='current',) plt.plot(x, rate_P, label='Poisson input') plt.fill_between(x, rate_P_min, rate_P_max, facecolor = 'green', alpha=0.3) ''' x0 = np.where(rate_P > 1.)[0][0] x1 = 4 k = (rate_P[x1] - rate_P[x0]) / (x[x1] - x[x0]) ''' plt.plot(x, k*(x-x[x0])+rate_P[x0], label='linear') plt.legend(loc='upper left', shadow=True) plt.grid('on') plt.show() ''' p.end() return k, x[x0], rate_P[x0]
inp = sim.Population( 1, sim.SpikeSourcePoisson(duration=simparams['duration'], rate=simparams['input_rate'])) inp.label = 'input cell' outp = sim.Population(1, sim.IF_curr_exp, cellparams=cellparams) outp.label = 'output cell' inp.record('spikes') outp.record(['v', 'spikes']) synapse = sim.StaticSynapse(weight=1, delay=simparams['delay']) connector = sim.OneToOneConnector() connection = sim.Projection(inp, outp, connector, synapse) def report_time(t): print("Time: {}".format(t)) return t + simparams['dt'] par = 'i_offset' for p in [0.01]: outp.set(**{par: p}) cellparams[par] = p outp.initialize(v=cellparams['v_rest']) sim.run(simparams['duration'], callbacks=[report_time]) sim.reset(annotations={par: p})
def __init__(self, sim_params=None, cell_params=None, verbose=True): ''' Parameters : Stimulus, Population, Synapses, Recording, Running ''' self.verbose = verbose self.sim_params = sim_params self.cell_params = cell_params sim.setup() #spike_precision='on_grid')#timestep = .1) N_inh = int(sim_params['nb_neurons'] * sim_params['p']) #total pop * proportion of inhib self.spike_source = sim.Population( N_inh, sim.SpikeSourcePoisson(rate=sim_params['input_rate'], duration=sim_params['simtime'] / 2)) #orientation stimulus, see bottom section of notebook angle = 1. * np.arange(N_inh) rates = self.tuning_function(angle, sim_params['angle_input'] / 180. * N_inh, sim_params['b_input'], N_inh) rates /= rates.mean() rates *= sim_params['input_rate'] for i, cell in enumerate(self.spike_source): cell.set_parameters(rate=rates[i]) #neuron model selection if sim_params['neuron_model'] == 'IF_cond_alpha': model = sim.IF_cond_alpha #LIF with nice dynamics else: model = sim.IF_cond_exp #LIF with exp dynamics #populations E_neurons = sim.Population( N_inh, model(**cell_params), initial_values={ 'v': rnd('uniform', (sim_params['v_init_min'], sim_params['v_init_max'])) }, label="Excitateurs") I_neurons = sim.Population( int(sim_params['nb_neurons'] - N_inh), model(**cell_params), initial_values={ 'v': rnd('uniform', (sim_params['v_init_min'], sim_params['v_init_max'])) }, label="Inhibiteurs") #input to excitatories input_exc = sim.Projection( self.spike_source, E_neurons, sim.OneToOneConnector(), sim.StaticSynapse(weight=sim_params['w_input_exc'], delay=sim_params['s_input_exc'])) #loop through connections type and use associated params, can be a bit slow conn_types = ['exc_inh', 'inh_exc', 'exc_exc', 'inh_inh'] #connection types ''' self.proj = self.set_synapses(conn_types = conn_types, sim_params =sim_params, E_neurons = E_neurons, I_neurons = I_neurons, N_inh = N_inh) ''' #Multi threading support NE MARCHE PAS LAISSER LE NJOBS EN 1 self.proj = Parallel(n_jobs=1, backend='multiprocessing')( delayed(self.set_synapses)(conn_type, sim_params=sim_params, E_neurons=E_neurons, I_neurons=I_neurons, N_inh=N_inh, conn_types=conn_types, verbose=verbose) for conn_type in range(len(conn_types))) if verbose: print('Done building synapses !') #record self.spike_source.record('spikes') E_neurons.record('spikes') I_neurons.record('spikes') #run if verbose: print('Running simulation..') sim.run(sim_params['simtime']) if verbose: print('Done running !') #get the spikes self.E_spikes = E_neurons #.get_data().segments[0] self.I_spikes = I_neurons #.get_data().segments[0] self.P_spikes = self.spike_source #.get_data().segments[0]
plt.interactive(False) sim.setup(0.1) neurons = sim.Population(64, sim.IF_curr_exp, {}, label="neurons") print(neurons.celltype.recordable) params = { 'rate': 10000.0, # Mean spike frequency (Hz) 'start': 0.0, # Start time (ms) 'duration': 1e10 # Duration of spike sequence (ms) } input = sim.Population(64, sim.SpikeSourcePoisson(**params), label="input") input_proj = sim.Projection( input, neurons, sim.OneToOneConnector(), receptor_type='excitatory' ) ##https://github.com/NeuralEnsemble/PyNN/issues/273 def twoDto1D(x): return (8 * x[0] + x[1]) def oneDto2D(n): return np.array([int(n / 8.), int(n - 8 * (int(n / 8.)))]) def plot_spiketrains(segment): for spiketrain in segment.spiketrains: y = np.ones_like(spiketrain) * spiketrain.annotations['source_id'] plt.plot(spiketrain, y, '.')