def run_test(w_list, cell_para, spike_source_data): 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] 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) for w in w_list: pos_w = np.copy(w) pos_w[pos_w < 0] = 0 neg_w = np.copy(w) neg_w[neg_w > 0] = 0 output_size = w.shape[1] pop_out = p.Population(output_size, p.IF_curr_exp, cell_para) 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 p.run(run_time) spikes = pop_out.getSpikes(compatible_output=True) return spikes
def two_neuron_example( current=1000.0, time_simulation=2000.0, weight=0.4, neuron_parameters={"v_rest": -50.0, "cm": 1, "tau_m": 20.0, "tau_refrac": 5.0, "v_thresh": -40.0, "v_reset": -50.0}, ): sim.setup(timestep=0.1, min_delay=0.1) pulse = sim.DCSource(amplitude=current, start=0.0, stop=time_simulation) pre = sim.Population(1, sim.IF_curr_exp(**neuron_parameters)) pre.record("spikes") pulse.inject_into(pre) sim.run(time_simulation) # rates in Hz rate_pre = len(pre.get_data("spikes").segments[0].spiketrains[0]) / time_simulation * 1000.0 sim.end() return rate_pre
def scnn_test(cell_params_lif, l_cnn, w_cnn, num_test, test, max_rate, dur_test, silence): p.setup(timestep=1.0, min_delay=1.0, max_delay=3.0) L = l_cnn random.seed(0) input_size = L[0][1] pops_list = [] pops_list.append( init_inputlayer(input_size, test[:num_test, :], max_rate, dur_test, silence)) print('SCNN constructing...') for l in range(len(w_cnn)): pops_list.append( construct_layer(cell_params_lif, pops_list[l], L[l + 1][0], L[l + 1][1], w_cnn[l])) result = pops_list[-1][0] result.record(['v', 'spikes']) # new print('SCNN running...') p.run((dur_test + silence) * num_test) spike_result = result.getSpikes(compatible_output=True) #spike_result = result.get_spike_counts(gather=True) #tuple datta #spike_result = result.get_data('spikes') p.end() print('analysing...') spike_result_count = count_spikes(spike_result, 10, num_test, dur_test, silence) print("spike_result_count : ", spike_result_count) predict = np.argmax(spike_result_count, axis=0) print("predict : ", predict) # prob = np.exp(spike_result_count)/np.sum(np.exp(spike_result_count), axis=0) return predict, spike_result
def sim_neuron(rate): neuron_parameters={ 'v_rest' : -50.0, 'cm' : 1, 'tau_m' : 20.0, 'tau_syn_E' : 5.0, 'tau_syn_I' : 5.0, 'v_reset' : -50.0, 'v_thresh' : 10000000000000000000000000000000000000000000000000000000000000000000000.0, 'e_rev_E' : 0.0, 'e_rev_I' : -100, } time_simulation = 100000 # don't choose to small number in order to get good statistics weight = 0.1 # is this value allreight sim.setup(timestep=0.1, min_delay=0.1) pois_exc = sim.SpikeSourcePoisson(duration=time_simulation,start=0.0,rate=rate) # generate poisson rate stimulus pois_inh = sim.SpikeSourcePoisson(duration=time_simulation,start=0.0,rate=rate) # generate poisson rate stimulus exc = sim.Population(1, cellclass=pois_exc) # simulate excitatory cell inh = sim.Population(1, cellclass=pois_inh) # simulate inhibitory cell rec = sim.Population(1, sim.IF_cond_exp(**neuron_parameters)) # simulate receiving neuron sim.Projection(exc, rec, connector=sim.OneToOneConnector(),synapse_type=sim.StaticSynapse(weight=weight),receptor_type='excitatory') # connect excitatory neuron to receiver sim.Projection(inh, rec, connector=sim.OneToOneConnector(),synapse_type=sim.StaticSynapse(weight=weight),receptor_type='inhibitory') # connect inhibitory neuron to receiver rec.record('v') # record membrane potential rec.record('gsyn_exc') # record excitatory conductance rec.record('gsyn_inh') # record inhibitory conductance sim.run(time_simulation) # start simulation return rec.get_data('v').segments[0].analogsignalarrays[0], rec.get_data('gsyn_exc').segments[0].analogsignalarrays[0], rec.get_data('gsyn_inh').segments[0].analogsignalarrays[0] # return membrane potential, excitatory conductance, inhibitory conductance
def run_sim(ncell): print "Cells: ", ncell setup0 = time.time() sim.setup(timestep=0.1) hh_cell_type = sim.HH_cond_exp() hh = sim.Population(ncell, hh_cell_type) pulse = sim.DCSource(amplitude=0.5, start=20.0, stop=80.0) pulse.inject_into(hh) hh.record('v') setup1 = time.time() t0 = time.time() sim.run(100.0) v = hh.get_data() sim.end() t1 = time.time() setup_total = setup1 - setup0 run_total = t1 - t0 print "Setup: ", setup_total print "Run: ", run_total print "Total sim time: ", setup_total + run_total return run_total
def train_weights(feature_dir): """ Trains the basic recognizer weights such that they respond to the features found in the directory feature_dir. This function runs a sim.start() - sim.end() "session". Arguments: `feature_dir`: The directory where the features are stored as images Returns: A pair of weight and feature image dictionaries of the following type: weights_dict :: feature name string -> (weights, shape) feature_imgs_dict :: feature name string -> feature image """ sim.setup() weights_dict = {} # feature name string -> (weights, shape) feature_imgs_dict = {} # feature name string -> feature image for training_img in plb.Path(feature_dir).iterdir(): feature_np_array = cv2.imread(training_img.as_posix(), cv2.CV_8U) feature_imgs_dict[training_img.stem] = feature_np_array weights = recognizer_weights_from(feature_np_array) weights_dict[training_img.stem] = (weights, feature_np_array.shape) sim.end() return (weights_dict, feature_imgs_dict)
def main(): # setup timestep of simulation and minimum and maximum synaptic delays setup(timestep=simulationTimestep, min_delay=minSynapseDelay, max_delay=maxSynapseDelay) # create a spike sources retinaLeft = createSpikeSource("Retina Left") retinaRight = createSpikeSource("Retina Right") # create network and attach the spike sources network = createCooperativeNetwork(retinaLeft=retinaLeft, retinaRight=retinaRight) # run simulation for time in milliseconds print "Simulation started..." run(simulationTime) print "Simulation ended." # plot results from itertools import repeat numberOfLayersToPlot = 4 layers = zip(repeat(network, numberOfLayersToPlot), range(1, numberOfLayersToPlot+1), repeat(False, numberOfLayersToPlot)) customLayers = [(network, 20, False),(network, 40, False),(network, 60, False),(network, 80, False)] for proc in range(0, numberOfLayersToPlot): p = Process(target=plotSimulationResults, args=customLayers[proc]) p.start() # finalise program and simulation end()
def run_test(w_list, cell_para, spike_source_data): 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] 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) for w in w_list: pos_w = np.copy(w) pos_w[pos_w < 0] = 0 neg_w = np.copy(w) neg_w[neg_w > 0] = 0 output_size = w.shape[1] pop_out = p.Population(output_size, p.IF_curr_exp, cell_para) 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 p.run(run_time) spikes = pop_out.getSpikes(compatible_output=True) return spikes
def main(args): setup(timestep=0.1) random_image = np.random.rand(2,2) size = random_image.size input_population_arr = Population(random_image.size, SpikeSourceArray, {'spike_times': [0 for i in range(0, random_image.size)]}) cell_params = {'tau_refrac': 2.0, 'v_thresh': -50.0, 'tau_syn_E': 2.0, 'tau_syn_I': 2.0} output_population = Population(1, IF_curr_alpha, cell_params, label="output") projection = Projection(input_population_arr, output_population, AllToAllConnector()) projection.setWeights(1.0) input_population_arr.record('spikes') output_population.record('spikes') tstop = 1000.0 run(tstop) output_population.write_data("simpleNetwork_output.pkl",'spikes') input_population_arr.write_data("simpleNetwork_input.pkl",'spikes') #output_population.print_v("simpleNetwork.v") end()
def setUp(self): import pyNN.nest as sim self.nest = sim.nest sim.setup(timestep=0.1, spike_precision="on_grid") self.sim = sim
def setUp(self): sim.setup() self.p1 = sim.Population(7, sim.IF_cond_exp()) self.p2 = sim.Population(4, sim.IF_cond_exp()) self.p3 = sim.Population(5, sim.IF_curr_alpha()) self.syn_rnd = sim.StaticSynapse(weight=0.123, delay=0.5) self.syn_a2a = sim.StaticSynapse(weight=0.456, delay=0.4) self.random_connect = sim.FixedNumberPostConnector(n=2) self.all2all = sim.AllToAllConnector()
def setUp(self): sim.setup() self.p = sim.Population( 4, sim.IF_cond_exp( **{ 'tau_m': 12.3, 'cm': lambda i: 0.987 + 0.01 * i, 'i_offset': np.array([-0.21, -0.20, -0.19, -0.18]) }))
def test_setup(self): sim.setup(timestep=0.05, min_delay=0.1, max_delay=1.0, verbosity='debug', spike_precision='off_grid', recording_precision=4, threads=2, rng_seeds=[873465, 3487564]) ks = nest.GetKernelStatus() self.assertEqual(ks['resolution'], 0.05) self.assertEqual(ks['local_num_threads'], 2) self.assertEqual(ks['rng_seeds'], (873465, 3487564)) #self.assertEqual(ks['min_delay'], 0.1) #self.assertEqual(ks['max_delay'], 1.0) self.assertTrue(ks['off_grid_spiking'])
def test_ticket240(): nest = pyNN.nest nest.setup(threads=4) parameters = {'Tau_m': 17.0} p1 = nest.Population(4, nest.IF_curr_exp()) p2 = nest.Population(5, nest.native_cell_type("ht_neuron")(**parameters)) conn = nest.AllToAllConnector() syn = nest.StaticSynapse(weight=1.0) prj = nest.Projection(p1, p2, conn, syn, receptor_type='AMPA') # This should be a nonstandard receptor type but I don't know of one to use. connections = prj.get(('weight',), format='list') assert len(connections) > 0
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_brain(): """ Initializes PyNN with the minimal neuronal network """ sim.setup(timestep=0.1, min_delay=0.1, max_delay=20.0, threads=1, rng_seeds=[1234]) # Following parameters were taken from the husky braitenberg brain experiment (braitenberg.py) SENSORPARAMS = { 'cm': 0.025, 'v_rest': -60.5, 'tau_m': 10., 'e_rev_E': 0.0, 'e_rev_I': -75.0, 'v_reset': -60.5, 'v_thresh': -60.0, 'tau_refrac': 10.0, 'tau_syn_E': 2.5, 'tau_syn_I': 2.5 } SYNAPSE_PARAMS = { "weight": 0.5e-4, "delay": 20.0, 'U': 1.0, 'tau_rec': 1.0, 'tau_facil': 1.0 } cell_class = sim.IF_cond_alpha(**SENSORPARAMS) # Define the network structure: 2 neurons (1 sensor and 1 actors) population = sim.Population(size=2, cellclass=cell_class) synapse_type = sim.TsodyksMarkramSynapse(**SYNAPSE_PARAMS) connector = sim.AllToAllConnector() # Connect neurons sim.Projection(presynaptic_population=population[0:1], postsynaptic_population=population[1:2], connector=connector, synapse_type=synapse_type, receptor_type='excitatory') sim.initialize(population, v=population.get('v_rest')) return population
def two_neuron_example( current=1000.0, time_simulation=2000., weight=0.4, neuron_parameters={ 'v_rest' : -65.0, 'cm' : 0.1, 'tau_m' : 1.0, 'tau_refrac' : 2.0, 'tau_syn_E' : 10.0, 'tau_syn_I' : 10.0, 'i_offset' : 0.0, 'v_reset' : -65.0, 'v_thresh' : -50.0, }, ): """ Connects to neurons with corresponding parameters. The first is stimulated via current injection while the second receives the other one's spikes. """ sim.setup(timestep=0.1, min_delay=0.1) pulse = sim.DCSource(amplitude=current, start=0.0, stop=time_simulation) pre = sim.Population(1, sim.IF_curr_exp(**neuron_parameters)) post = sim.Population(1, sim.IF_curr_exp(**neuron_parameters)) pre.record('spikes') post.record('spikes') sim.Projection(pre, post, connector=sim.OneToOneConnector(), synapse_type=sim.StaticSynapse(weight=weight), receptor_type='excitatory') pulse.inject_into(pre) sim.run(time_simulation) # rates in Hz rate_pre = len(pre.get_data('spikes').segments[0].spiketrains[0])\ / time_simulation * 1000. rate_post = len(post.get_data('spikes').segments[0].spiketrains[0])\ / time_simulation * 1000. sim.end() return rate_pre, rate_post
def __init__(self, N, cell_params,col_params,sim_params, graph=None, le=1., li=1., velocity=None): self.mpi_print("Creation of the layer ...") self.velocity = velocity self.scaling = 0.06 # width, in mm, of one column self.timestep=sim_params['dt'] if velocity is None: max_delay = self.timestep else: max_delay = numpy.sqrt(2)*N*self.scaling/self.velocity self.mpi_print("Timestep is %g ms, max delay has been set to %g ms" %(self.timestep, max_delay)) self.node_id = sim.setup(self.timestep, max_delay=max_delay) self.N = N self.blocs = numpy.array([Column(cell_params,col_params) for i in xrange(N**2)]) self.blocs = self.blocs.reshape(N,N) self.recordings = [] self.le = le self.li = li self.w_E = self.blocs[0,0].w_E self.w_I = self.blocs[0,0].w_I self.Ne = len(self.blocs[0,0].exc) self.Ni = len(self.blocs[0,0].inh) self.graph=graph if self.graph!=None: self.conn_graph = cg.OneColGraph(self.graph) self.mpi_print("A layer of size %d x %d x %d = %d cells has been built" %(self.N, self.N, self.Ne+self.Ni, (self.Ne+self.Ni) * self.N**2)) self.conn_graph.make_layer_nodes( range(self.get_exc_from_blocks(self.graph).first_id,self.get_exc_from_blocks(self.graph).last_id+1) , range(self.get_inh_from_blocks(self.graph).first_id,self.get_inh_from_blocks(self.graph).last_id+1) )
def test_setup(self): sim.setup(timestep=0.05, min_delay=0.1, max_delay=1.0, verbosity='debug', spike_precision='off_grid', recording_precision=4, threads=2, rng_seed=873465) ks = nest.GetKernelStatus() self.assertEqual(ks['resolution'], 0.05) self.assertEqual(ks['local_num_threads'], 2) self.assertEqual(ks['rng_seed'], 873465) #self.assertEqual(ks['min_delay'], 0.1) #self.assertEqual(ks['max_delay'], 1.0) self.assertEqual(sim.state.spike_precision, "off_grid")
def test_record_native_model(): if not have_nest: raise SkipTest nest = pyNN.nest from pyNN.random import RandomDistribution init_logging(logfile=None, debug=True) nest.setup() parameters = {'tau_m': 17.0} n_cells = 10 p1 = nest.Population(n_cells, nest.native_cell_type("ht_neuron")(**parameters)) p1.initialize(V_m=-70.0, Theta=-50.0) p1.set(theta_eq=-51.5) #assert_arrays_equal(p1.get('theta_eq'), -51.5*numpy.ones((10,))) assert_equal(p1.get('theta_eq'), -51.5) print(p1.get('tau_m')) p1.set(tau_m=RandomDistribution('uniform', low=15.0, high=20.0)) print(p1.get('tau_m')) current_source = nest.StepCurrentSource( times=[50.0, 110.0, 150.0, 210.0], amplitudes=[0.01, 0.02, -0.02, 0.01]) p1.inject(current_source) p2 = nest.Population( 1, nest.native_cell_type("poisson_generator")(rate=200.0)) print("Setting up recording") p2.record('spikes') p1.record('V_m') connector = nest.AllToAllConnector() syn = nest.StaticSynapse(weight=0.001) prj_ampa = nest.Projection(p2, p1, connector, syn, receptor_type='AMPA') tstop = 250.0 nest.run(tstop) vm = p1.get_data().segments[0].analogsignals[0] n_points = int(tstop / nest.get_time_step()) + 1 assert_equal(vm.shape, (n_points, n_cells)) assert vm.max() > 0.0 # should have some spikes
def main(argv): rospy.init_node('SNN', disable_signals=True) nest.setup(timestep=TIME_STEP) parser = create_argument_parser() n = parser.parse_args() #world = World() #network, actor_network, braitenberg = NetworkBuilder.braitenberg_deep_network(number_middle_layers=1, number_neurons_per_layer=5, image_topic='/spiky/retina_image') #network, actor_network = NetworkBuilder.braitenberg_network(image_topic='/spiky/binary_image') network, actor_network, braitenberg = NetworkBuilder.braitenberg_deep_network_parallel(number_middle_layers=1, number_neurons_per_layer=5) world = BraitenbergSupervisedWorld(braitenberg) learner = ReinforcementLearner(network, world, BETA_SIGMA, SIGMA, TAU, NUM_TRACE_STEPS, 2, DISCOUNT_FACTOR, TIME_STEP, LEARNING_RATE) agent = SnnAgent(timestep=TIME_STEP, simduration=5, learner=learner, should_learn=True, network=network, actor_network=actor_network) n.plot = False if n.plot: plotter = NetworkPlotter(agent, plot_steps=20) n.log = True if n.log: logger = NetworkLogger(agent, network, log_period=60) n.cockpit = True if n.cockpit: cockpit_view = cockpit.CockpitViewModel(network, agent) while True: # Inject frame to network and start simulation agent.step() if n.plot: plotter.update() if n.log: logger.log() if n.cockpit: cockpit_view.update()
def test_record_native_model(): nest = pyNN.nest from pyNN.random import RandomDistribution from pyNN.utility import init_logging init_logging(logfile=None, debug=True) nest.setup() parameters = {'Tau_m': 17.0} n_cells = 10 p1 = nest.Population(n_cells, nest.native_cell_type("ht_neuron"), parameters) p1.initialize('V_m', -70.0) p1.initialize('Theta', -50.0) p1.set('Theta_eq', -51.5) assert_equal(p1.get('Theta_eq'), [-51.5] * 10) print p1.get('Tau_m') p1.rset('Tau_m', RandomDistribution('uniform', [15.0, 20.0])) print p1.get('Tau_m') current_source = nest.StepCurrentSource({ 'times': [50.0, 110.0, 150.0, 210.0], 'amplitudes': [0.01, 0.02, -0.02, 0.01] }) p1.inject(current_source) p2 = nest.Population(1, nest.native_cell_type("poisson_generator"), {'rate': 200.0}) print "Setting up recording" p2.record() p1._record('V_m') connector = nest.AllToAllConnector(weights=0.001) prj_ampa = nest.Projection(p2, p1, connector, target='AMPA') tstop = 250.0 nest.run(tstop) n_points = int(tstop / nest.get_time_step()) + 1 assert_equal(p1.recorders['V_m'].get().shape, (n_points * n_cells, 3)) id, t, v = p1.recorders['V_m'].get().T assert v.max() > 0.0 # should have some spikes
def ready(self): sim.setup(timestep=1.) # set up spike sources self.spike_source = sim.Population(self.n_spike_source, sim.SpikeSourceArray(), label='spike sources') # set up hidden neurons self.hidden_neurons = sim.Population(self.n_hidden_neurons, self.cell_type(**self.parameters), label='hidden neurons') # set up output neurons self.output_neurons = sim.Population(self.n_output_neurons, self.cell_type_out(**self.parameters_out), label='output neurons') self.output_neurons.set(I_e=1.0, V_th=1500.0) ## new new new # build connections self.connection_in = sim.Projection(self.spike_source, self.hidden_neurons, sim.FromListConnector(self.connection_in_list)) self.connection_hidden = sim.Projection(self.hidden_neurons, self.hidden_neurons, sim.FromListConnector(self.connection_hidden_list)) self.connection_out = sim.Projection(self.hidden_neurons, self.output_neurons, sim.FromListConnector(self.connection_out_list)) self.output_neurons.record('spikes') self.hidden_neurons.record('spikes')
def _reset(self, seed): ''' Reset simulator and seed the PRNGs. Parameters ---------- seed: PRNG seed value. ''' sim.end() sim.setup() # Set PRNG seed values: if seed is None: seed = rnd.randint(10**10) seed = 2 * seed rnd.seed(seed) self._rng = sim.NumpyRNG(seed=seed + 1)
def test_native_stdp_model(): nest = pyNN.nest from pyNN.utility import init_logging init_logging(logfile=None, debug=True) nest.setup() p1 = nest.Population(10, nest.IF_cond_exp()) p2 = nest.Population(10, nest.SpikeSourcePoisson()) stdp_params = {'Wmax': 50.0, 'lambda': 0.015, 'weight': 0.001} stdp = nest.native_synapse_type("stdp_synapse")(**stdp_params) connector = nest.AllToAllConnector() prj = nest.Projection(p2, p1, connector, receptor_type='excitatory', synapse_type=stdp)
def test_native_stdp_model(): nest = pyNN.nest from pyNN.utility import init_logging init_logging(logfile=None, debug=True) nest.setup() p1 = nest.Population(10, nest.IF_cond_exp) p2 = nest.Population(10, nest.SpikeSourcePoisson) stdp_params = {'Wmax': 50.0, 'lambda': 0.015} stdp = nest.NativeSynapseDynamics("stdp_synapse", stdp_params) connector = nest.AllToAllConnector(weights=0.001) prj = nest.Projection(p2, p1, connector, target='excitatory', synapse_dynamics=stdp)
def test_record_native_model(): if not have_nest: raise SkipTest nest = pyNN.nest from pyNN.random import RandomDistribution init_logging(logfile=None, debug=True) nest.setup() parameters = {'tau_m': 17.0} n_cells = 10 p1 = nest.Population(n_cells, nest.native_cell_type("ht_neuron")(**parameters)) p1.initialize(V_m=-70.0, Theta=-50.0) p1.set(theta_eq=-51.5) #assert_arrays_equal(p1.get('theta_eq'), -51.5*numpy.ones((10,))) assert_equal(p1.get('theta_eq'), -51.5) print(p1.get('tau_m')) p1.set(tau_m=RandomDistribution('uniform', low=15.0, high=20.0)) print(p1.get('tau_m')) current_source = nest.StepCurrentSource(times=[50.0, 110.0, 150.0, 210.0], amplitudes=[0.01, 0.02, -0.02, 0.01]) p1.inject(current_source) p2 = nest.Population(1, nest.native_cell_type("poisson_generator")(rate=200.0)) print("Setting up recording") p2.record('spikes') p1.record('V_m') connector = nest.AllToAllConnector() syn = nest.StaticSynapse(weight=0.001) prj_ampa = nest.Projection(p2, p1, connector, syn, receptor_type='AMPA') tstop = 250.0 nest.run(tstop) vm = p1.get_data().segments[0].analogsignals[0] n_points = int(tstop / nest.get_time_step()) + 1 assert_equal(vm.shape, (n_points, n_cells)) assert vm.max() > 0.0 # should have some spikes
def test(): if not HAVE_H5PY and HAVE_NEST: raise SkipTest sim.setup() p1 = sim.Population(10, sim.IF_cond_exp(v_rest=-65, tau_m=lambda i: 10 + 0.1 * i, cm=RD('normal', (0.5, 0.05))), label="population_one") p2 = sim.Population(20, sim.IF_curr_alpha(v_rest=-64, tau_m=lambda i: 11 + 0.1 * i), label="population_two") prj = sim.Projection(p1, p2, sim.FixedProbabilityConnector(p_connect=0.5), synapse_type=sim.StaticSynapse(weight=RD( 'uniform', [0.0, 0.1]), delay=0.5), receptor_type='excitatory') net = Network(p1, p2, prj) export_to_sonata(net, "tmp_serialization_test", overwrite=True) net2 = import_from_sonata("tmp_serialization_test/circuit_config.json", sim) for orig_population in net.populations: imp_population = net2.get_component(orig_population.label) assert orig_population.size == imp_population.size for name in orig_population.celltype.default_parameters: assert_array_almost_equal(orig_population.get(name), imp_population.get(name), 12) w1 = prj.get('weight', format='array') prj2 = net2.get_component(asciify(prj.label).decode('utf-8') + "-0") w2 = prj2.get('weight', format='array') assert_array_almost_equal(w1, w2, 12)
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 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]) 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) #
def scnn_test(l_cnn, w_cnn, num_test, test, max_rate, dur_test, silence): p.setup(timestep=1.0, min_delay=1.0, max_delay=3.0) L = l_cnn random.seed(0) input_size = L[0][1] pops_list = [] pops_list.append(init_inputlayer(input_size, test[:num_test, :], max_rate, dur_test, silence)) for l in range(len(w_cnn)): pops_list.append(construct_layer(pops_list[l], L[l+1][0], L[l+1][1], w_cnn[l])) result = pops_list[-1][0] result.record() p.run((dur_test+silence)*num_test) spike_result = result.getSpikes(compatible_output=True) p.end() spike_result_count = count_spikes(spike_result, 10, num_test, dur_test, silence) predict = np.argmax(spike_result_count, axis=0) # prob = np.exp(spike_result_count)/np.sum(np.exp(spike_result_count), axis=0) return predict
def execute(conf, train, test): """Execute a supervised pyNN experiment. Args: conf (addict.Dict): The configuration object of the whole experiment. train: Training data test: Testing data Returns: Outputs that have been produced by the execution. """ pynn.setup() net = conf.network blocks = net.blocks # only support one block for now b = blocks[0] model = pynn_model.Model(pynn, b) model.train(train) model.predict(test)
def test_record_native_model(): nest = pyNN.nest from pyNN.random import RandomDistribution from pyNN.utility import init_logging init_logging(logfile=None, debug=True) nest.setup() parameters = {'Tau_m': 17.0} n_cells = 10 p1 = nest.Population(n_cells, nest.native_cell_type("ht_neuron"), parameters) p1.initialize('V_m', -70.0) p1.initialize('Theta', -50.0) p1.set('Theta_eq', -51.5) assert_equal(p1.get('Theta_eq'), [-51.5]*10) print p1.get('Tau_m') p1.rset('Tau_m', RandomDistribution('uniform', [15.0, 20.0])) print p1.get('Tau_m') current_source = nest.StepCurrentSource({'times' : [50.0, 110.0, 150.0, 210.0], 'amplitudes' : [0.01, 0.02, -0.02, 0.01]}) p1.inject(current_source) p2 = nest.Population(1, nest.native_cell_type("poisson_generator"), {'rate': 200.0}) print "Setting up recording" p2.record() p1._record('V_m') connector = nest.AllToAllConnector(weights=0.001) prj_ampa = nest.Projection(p2, p1, connector, target='AMPA') tstop = 250.0 nest.run(tstop) n_points = int(tstop/nest.get_time_step()) + 1 assert_equal(p1.recorders['V_m'].get().shape, (n_points*n_cells, 3)) id, t, v = p1.recorders['V_m'].get().T assert v.max() > 0.0 # should have some spikes
def main(): # setup timestep of simulation and minimum and maximum synaptic delays setup(timestep=simulationTimestep, min_delay=minSynapseDelay, max_delay=maxSynapseDelay, threads=4) # create a spike sources retinaLeft = createSpikeSource("Retina Left") retinaRight = createSpikeSource("Retina Right") # create network and attach the spike sources network = createCooperativeNetwork(retinaLeft=retinaLeft, retinaRight=retinaRight) # run simulation for time in milliseconds print "Simulation started..." run(simulationTime) print "Simulation ended." # plot results plotSimulationResults(network, 1, False) # finalise program and simulation end()
def test(): sim.setup() p1 = sim.Population(10, sim.IF_cond_exp( v_rest=-65, tau_m=lambda i: 10 + 0.1*i, cm=RD('normal', (0.5, 0.05))), label="population_one") p2 = sim.Population(20, sim.IF_curr_alpha( v_rest=-64, tau_m=lambda i: 11 + 0.1*i), label="population_two") prj = sim.Projection(p1, p2, sim.FixedProbabilityConnector(p_connect=0.5), synapse_type=sim.StaticSynapse(weight=RD('uniform', [0.0, 0.1]), delay=0.5), receptor_type='excitatory') net = Network(p1, p2, prj) export_to_sonata(net, "tmp_serialization_test", overwrite=True) net2 = import_from_sonata("tmp_serialization_test/circuit_config.json", sim) for orig_population in net.populations: imp_population = net2.get_component(orig_population.label) assert orig_population.size == imp_population.size for name in orig_population.celltype.default_parameters: assert_array_almost_equal(orig_population.get(name), imp_population.get(name), 12) w1 = prj.get('weight', format='array') prj2 = net2.get_component(asciify(prj.label).decode('utf-8') + "-0") w2 = prj2.get('weight', format='array') assert_array_almost_equal(w1, w2, 12)
def scnn_test(l_cnn, w_cnn, num_test, test, max_rate, dur_test, silence): p.setup(timestep=1.0, min_delay=1.0, max_delay=3.0) L = l_cnn random.seed(0) input_size = L[0][1] pops_list = [] pops_list.append( init_inputlayer(input_size, test[:num_test, :], max_rate, dur_test, silence)) for l in range(len(w_cnn)): pops_list.append( construct_layer(pops_list[l], L[l + 1][0], L[l + 1][1], w_cnn[l])) result = pops_list[-1][0] result.record() p.run((dur_test + silence) * num_test) spike_result = result.getSpikes(compatible_output=True) p.end() spike_result_count = count_spikes(spike_result, 10, num_test, dur_test, silence) predict = np.argmax(spike_result_count, axis=0) # prob = np.exp(spike_result_count)/np.sum(np.exp(spike_result_count), axis=0) return predict
def _run_microcircuit(plot_filename, conf): import plotting import logging simulator = conf['simulator'] # we here only need nest as simulator, simulator = 'nest' import pyNN.nest as sim # prepare simulation logging.basicConfig() # extract parameters from config file master_seed = conf['params_dict']['nest']['master_seed'] layers = conf['layers'] pops = conf['pops'] plot_spiking_activity = conf['plot_spiking_activity'] raster_t_min = conf['raster_t_min'] raster_t_max = conf['raster_t_max'] frac_to_plot = conf['frac_to_plot'] record_corr = conf['params_dict']['nest']['record_corr'] tau_max = conf['tau_max'] # Numbers of neurons from which to record spikes n_rec = helper_functions.get_n_rec(conf) sim.setup(**conf['simulator_params'][simulator]) if simulator == 'nest': n_vp = sim.nest.GetKernelStatus('total_num_virtual_procs') if sim.rank() == 0: print 'n_vp: ', n_vp print 'master_seed: ', master_seed sim.nest.SetKernelStatus({'print_time': False, 'dict_miss_is_error': False, 'grng_seed': master_seed, 'rng_seeds': range(master_seed + 1, master_seed + n_vp + 1), 'data_path': conf['system_params'] \ ['output_path']}) import network # result of export-files results = [] # create network start_netw = time.time() n = network.Network(sim) # contains the GIDs of the spike detectors and voltmeters needed for # retrieving filenames later device_list = n.setup(sim, conf) end_netw = time.time() if sim.rank() == 0: print 'Creating the network took ', end_netw - start_netw, ' s' # simulate if sim.rank() == 0: print "Simulating..." start_sim = time.time() sim.run(conf['simulator_params'][simulator]['sim_duration']) end_sim = time.time() if sim.rank() == 0: print 'Simulation took ', end_sim - start_sim, ' s' # extract filename from device_list (spikedetector/voltmeter), # gid of neuron and thread. merge outputs from all threads # into a single file which is then added to the task output. for dev in device_list: label = sim.nest.GetStatus(dev)[0]['label'] gid = sim.nest.GetStatus(dev)[0]['global_id'] # use the file extension to distinguish between spike and voltage # output extension = sim.nest.GetStatus(dev)[0]['file_extension'] if extension == 'gdf': # spikes data = np.empty((0, 2)) elif extension == 'dat': # voltages data = np.empty((0, 3)) for thread in xrange(conf['simulator_params']['nest']['threads']): filenames = glob.glob(conf['system_params']['output_path'] + '%s-*%d-%d.%s' % (label, gid, thread, extension)) assert( len(filenames) == 1), 'Multiple input files found. Use a clean output directory.' data = np.vstack([data, np.loadtxt(filenames[0])]) # delete original files os.remove(filenames[0]) order = np.argsort(data[:, 1]) data = data[order] outputfile_name = 'collected_%s-%d.%s' % (label, gid, extension) outputfile = open(outputfile_name, 'w') # the outputfile should have same format as output from NEST. # i.e., [int, float] for spikes and [int, float, float] for voltages, # hence we write it line by line and assign the corresponding filetype if extension == 'gdf': # spikes for line in data: outputfile.write('%d\t%.3f\n' % (line[0], line[1])) outputfile.close() filetype = 'application/vnd.juelich.nest.spike_times' elif extension == 'dat': # voltages for line in data: outputfile.write( '%d\t%.3f\t%.3f\n' % (line[0], line[1], line[2])) outputfile.close() filetype = 'application/vnd.juelich.nest.analogue_signal' res = (outputfile_name, filetype) results.append(res) if record_corr and simulator == 'nest': start_corr = time.time() if sim.nest.GetStatus(n.corr_detector, 'local')[0]: print 'getting count_covariance on rank ', sim.rank() cov_all = sim.nest.GetStatus( n.corr_detector, 'count_covariance')[0] delta_tau = sim.nest.GetStatus(n.corr_detector, 'delta_tau')[0] cov = {} for target_layer in np.sort(layers.keys()): for target_pop in pops: target_index = conf['structure'][target_layer][target_pop] cov[target_index] = {} for source_layer in np.sort(layers.keys()): for source_pop in pops: source_index = conf['structure'][ source_layer][source_pop] cov[target_index][source_index] = \ np.array(list( cov_all[target_index][source_index][::-1]) + list(cov_all[source_index][target_index][1:])) f = open(conf['system_params'][ 'output_path'] + '/covariances.dat', 'w') print >>f, 'tau_max: ', tau_max print >>f, 'delta_tau: ', delta_tau print >>f, 'simtime: ', conf['simulator_params'][ simulator]['sim_duration'], '\n' for target_layer in np.sort(layers.keys()): for target_pop in pops: target_index = conf['structure'][target_layer][target_pop] for source_layer in np.sort(layers.keys()): for source_pop in pops: source_index = conf['structure'][ source_layer][source_pop] print >>f, target_layer, target_pop, '-', source_layer, source_pop print >>f, 'n_events_target: ', sim.nest.GetStatus( n.corr_detector, 'n_events')[0][target_index] print >>f, 'n_events_source: ', sim.nest.GetStatus( n.corr_detector, 'n_events')[0][source_index] for i in xrange(len(cov[target_index][source_index])): print >>f, cov[target_index][source_index][i] print >>f, '' f.close() # add file covariances.dat into bundle res_cov = ('covariances.dat', 'text/plain') results.append(res_cov) end_corr = time.time() print "Writing covariances took ", end_corr - start_corr, " s" if plot_spiking_activity and sim.rank() == 0: plotting.plot_raster_bars(raster_t_min, raster_t_max, n_rec, frac_to_plot, n.pops, conf['system_params']['output_path'], plot_filename, conf) res_plot = (plot_filename, 'image/png') results.append(res_plot) sim.end() return results
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]
def setup(): pynn.reset() pynn.setup()
# from hbp_nrp_cle.brainsim import simulator as sim import numpy as np import logging import nest # from .resources import Variables as Var import pyNN.nest as sim from pyNN.nest import * from hbp_nrp_excontrol.logs import clientLogger import h5py logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) nest.ResetKernel() sim.setup(threads=1) """ Initializes PyNN with the neuronal network that has to be simulated """ # R-STDP parameters # Minimum weight value w_max = 6000. # Maximum weight value w_min = -6000. # Maximum initial random value w0_max = 700. # Minimum initial random value w0_min = -200. # Time constant of reward signal in ms tau_n_out = 5. # 200. tau_n_hidden = 5. # 200.
def setup(): pynn.setup()
def simulator_setup(): sim.setup(min_delay=0.1, max_delay=1.0) dirty_fixes_before_simulation()
""" Two Fruit Test Fruits: 1: Banana, 0; 2: Apple, 0. Chair: 1: 2 """ import pyNN.nest as sim from monkeyProblem import MonekyProblem sim.setup(timestep=1.0,min_delay=1.0,max_delay=1.0, debug=0) #mp = MonekyProblem(sim, "spinnaker") mp = MonekyProblem(sim, "nest") mp.narc.addFact("chairAt", (2,)) mp.narc.addFact("fruit", ("banana",0)) mp.narc.addFact("fruit", ("apple",0)) mp.narc.apply() sim.run(200) mp.printSpikes() sim.end()
from time import time from sys import argv, exit from pyNN.nest import setup, nest if len(argv) != 3: print "usage: nest_RandomConvergentConnect_scaling.py <num_neurons> <num_procs>" exit() n = int(argv[1]) np = int(argv[2]) setup(timestep=0.1, min_delay=0.1, max_delay=4.0) pop = nest.Create("iaf_neuron", n) # measure random connectivity start = time() for neuron in pop: nest.RandomConvergentConnect(pop, [neuron], int(n*0.1)) rank = nest.Rank() nc = nest.GetKernelStatus("num_connections") t = time() - start print "nest RandomConvergentConnect nocsa %i %i %f 0.0 %f %i %i" % (n, nc, t, t, rank, np) #import nest.visualization as vis #vis.plot_network(pop.all_cells, "nest_RandomConvergentConnect_scaling.pdf")
column.SetFeedforwardDendrite(1000.0) sim.run(1000) spikes = column.FetchSpikes().segments[0] print('Spikes after: {}'.format(spikes)) LOG.info('Test complete.') def test_column_inhibition(): """ Checks if only a single cell fires in the column """ LOG.info('Testing inter-column inhibition...') # reset the simulator sim.reset() LOG.info('Test complete.') if __name__ == '__main__': # setup the simulator sim.setup() # run tests #test_default_params() test_column_input() #test_column_inhibition()
help='Simulation time', metavar='50') parser.add_argument('--scales', default=[1.0, 0.71, 0.5, 0.35], nargs='+', type=float, help='A list of image scales for which to create\ layers. Defaults to [1, 0.71, 0.5, 0.35]') parser.add_argument('--threads', default=1, type=int) args = parser.parse_args() training_path = plb.Path(args.training_dir) imgs = [(filename.stem, cv2.imread(filename.as_posix(), cv2.CV_8UC1))\ for filename in sorted(training_path.glob('*.png'))] sim.setup(threads=args.threads) layer_collection = {} print('Create S1 layers') t1 = time.clock() layer_collection['S1'] =\ nw.create_gabor_input_layers_for_scales(imgs[0][1], args.scales) nw.create_cross_layer_inhibition(layer_collection['S1']) print('S1 layer creation took {} s'.format(time.clock() - t1)) print('Create C1 layers') t1 = time.clock() layer_collection['C1'] = nw.create_C1_layers(layer_collection['S1'], args.refrac_c1) nw.create_local_inhibition(layer_collection['C1'])
synapseParams = { 'tau_plus' : tauSyn, 'tau_minus_stdp' : tauSyn, 'Wmax' : weightMax * 1e3, # NEST uses different units than PyNN (nS instead of muS) 'configbit_0' : [0, 0, 1, 1], # set e_cc, e_ca, e_ac, e_aa 'configbit_1' : [1, 1, 0, 0], 'a_thresh_th' : aThresh * 2, 'a_thresh_tl' : aThresh, 'lookuptable_0' : lutCausal, 'lookuptable_1' : lutAnticausal, 'lookuptable_2' : range(16), # should not occur #'synapses_per_driver' : 50, #'driver_readout_time' : 15.0, #'reset_pattern' : 6 * [1], # reset a_c and a_a after weight update } pynn.setup() #generate stimuli 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
def test_run_0( self, ): # see https://github.com/NeuralEnsemble/PyNN/issues/191 sim.setup(timestep=0.123, min_delay=0.246) sim.run(0) self.assertEqual(sim.get_current_time(), 0.0)
def run(a_state): output_base = "out/" spike_count_filename = "gpi_spike_count.dat" weight_filename = conn_filename # filename, from which the cortex - striatum connections are read spike_count_full_filename = output_base + spike_count_filename #active_state = int(sys.argv[1]) active_state = a_state #Model of the basal ganglia D1 and D1 pathways. States and actions are populations coded. pyNN.utility.init_logging(None, debug=True) sim.setup(time_step) # cell class for all neurons in the network # (on HMF can be one of IF_cond_exp, EIF_cond_exp_isfa_ista) cellclass = sim.IF_cond_exp # ############# # POPULATIONS # ############# #CORTEX input population: N states, poisson inputs #?assemblies of m_actions populations or dictionnary of populations? #STRIATUM 2 populations of M actions, D1 and D2 #GPi/SNr 1 population of M actions, baseline firing rate driven by external poisson inputs cortex = [ sim.Population(n_cortex_cells, cellclass, neuron_parameters, label="CORTEX_{}".format(i)) for i in xrange(n_states)] cortex_assembly = sim.Assembly( *cortex, label="CORTEX") # independent Poisson input to cortex populations. # /active_state/ determines, which population receives # a different firing rate cortex_input = [] for i in xrange(n_states): if i == active_state: rate = active_state_rate else: rate = inactive_state_rate new_input = sim.Population( n_cortex_cells, sim.SpikeSourcePoisson, {'rate': rate}, label="STATE_INPUT_" + str(i)) sim.Projection( new_input, cortex[i], sim.OneToOneConnector(), sim.StaticSynapse(weight=cortex_input_weight, delay=cortex_input_delay) ) cortex_input.append(new_input) #print 'cortex ok' # striatum: # exciatatory populations striatum_d1 = [ sim.Population(n_msns, cellclass, neuron_parameters, label="D1_{}".format(i)) for i in xrange(m_actions)] # inhibitory populations striatum_d2 = [ sim.Population(n_msns, cellclass, neuron_parameters, label="D2_{}".format(i)) for i in xrange(m_actions)] # Striatum D2->D2 and D1->D1 lateral inhibition for lat_inh_source in xrange(m_actions): for lat_inh_target in xrange(m_actions): if lat_inh_source == lat_inh_target: continue sim.Projection( striatum_d1[lat_inh_source], striatum_d1[lat_inh_target], sim.FixedProbabilityConnector( d1_lat_inh_prob), sim.StaticSynapse( weight=d1_lat_inh_weight, delay=d1_lat_inh_delay), receptor_type="inhibitory", label="d1_lateral_inhibition_{}_{}".format( lat_inh_source, lat_inh_target)) sim.Projection( striatum_d2[lat_inh_source], striatum_d2[lat_inh_target], sim.FixedProbabilityConnector( d2_lat_inh_prob), sim.StaticSynapse( weight=d2_lat_inh_weight, delay=d2_lat_inh_delay), receptor_type="inhibitory", label="d2_lateral_inhibition_{}_{}".format( lat_inh_source, lat_inh_target)) striatum_assembly = sim.Assembly( *(striatum_d1 + striatum_d2), label="STRIATUM") #gids_cortex= [] #gids_d1= [] #gids_d2= [] #for s in xrange(n_states): # gids_cortex.append([gid for gid in cortex_assembly.get_population("CORTEX_"+str(s)).all()]) #for a in xrange(m_actions): # gids_d1.append([gid1 for gid1 in striatum_assembly.get_population("D1_"+str(a)).all()]) # gids_d2.append([gid2 for gid2 in striatum_assembly.get_population("D2_"+str(a)).all()]) #for i in xrange(0,3): # print i, 'len cortex ', len(gids_cortex[i]), 'unique ', len(np.unique(gids_cortex[i])) # print i, 'len d1', len(gids_d1[i]), 'unique ', len(np.unique(gids_d1[i])) # print i, 'len d2', len(gids_d2[i]), 'unique ', len(np.unique(gids_d2[i])) #print "striatum ok" #for i in xrange(0,3): # print np.unique(gids_cortex[i]) # gids_cortex[i][:]-=3 #if init: # init_w(gids_cortex, gids_d1, gids_d2) # cortex - striatum connection, all-to-all using loaded weights cs = sim.Projection( cortex_assembly, striatum_assembly, #sim.AllToAllConnector(), #sim.StaticSynapse( # weight=wd1, # delay=ctx_strd1_delay)) sim.FromFileConnector( weight_filename)) gpi = [ sim.Population(n_gpi, cellclass, neuron_parameters, label="GPI_{}".format(i)) for i in xrange(m_actions) ] gpi_assembly = sim.Assembly( *gpi, label="GPi") # external Poisson input to GPi gpi_input = sim.Population( m_actions * n_gpi, sim.SpikeSourcePoisson, dict( duration=sim_duration, rate=gpi_external_rate, start=0.), label="GPI_EXT_INPUT") sim.Projection( gpi_input, gpi_assembly, sim.OneToOneConnector(), sim.StaticSynapse( weight=gpi_external_weight, delay= gpi_external_delay)) # striatum - gpi connections for i in xrange(m_actions): gpi_p = sim.Projection( striatum_d1[i], gpi[i], sim.FixedProbabilityConnector(d1_gpi_prob), sim.StaticSynapse( weight=d1_gpi_weight, delay = d1_gpi_delay)) sim.Projection( striatum_d2[i], gpi[i], sim.FixedProbabilityConnector(d2_gpi_prob), sim.StaticSynapse(weight=d2_gpi_weight, delay=d2_gpi_delay), #target="inhibitory") receptor_type="inhibitory") #print gpi_p.get('weight', format='list') cortex_assembly.record('spikes') striatum_assembly.record('spikes') gpi_assembly.record('spikes') #print 'sim start' sim.run(sim_duration) sim.end() label = "CORTEX_0" #print 'cortex get pop', cortex_assembly.get_population(label) #print 'cortex describe', cortex_assembly.describe() #cortex_assembly.write_data("spikes") #cortex_assembly.get_population(label).write_data("spikes") #spikes = gpi_assembly #get_data("spikes", gather=True) # print "getdata spikes", spikes # print 'spikes.segment', spikes.segments #print 'spikes.segments.SpikeTrains', spikes.segments.spike #save_spikes(cortex_assembly, output_base, "cortex.dat") #save_spikes(striatum_d1, output_base, "striatum_d1.dat") #save_spikes(striatum_d2, output_base, "striatum_d2.dat") #save_spikes(gpi, output_base, "gpi.dat") #output_rates = np.array( # [len(i.getSpikes()) for i in gpi]) #np.savetxt(spike_count_full_filename, output_rates) # for seg in cortex_assembly.segments: # print("Analyzing segment %d" % seg.index) # stlist = [st - st.t_start for st in seg.spiketrains] # plt.figure() # count, bins = np.histogram(stlist) # plt.bar(bins[:-1], count, width=bins[1] - bins[0]) # plt.title("PSTH in segment %d" % seg.index) cortex_mean_spikes = np.zeros(n_states) gpi_mean_spikes = np.zeros(m_actions) d1_mean_spikes = np.zeros(m_actions) d2_mean_spikes = np.zeros(m_actions) for i in xrange(n_states): cortex_mean_spikes[i] = cortex_assembly.get_population("CORTEX_"+str(i)).mean_spike_count() for i in xrange(m_actions): gpi_mean_spikes[i] = gpi_assembly.get_population("GPI_"+str(i)).mean_spike_count() d1_mean_spikes[i] = striatum_assembly.get_population("D1_"+str(i)).mean_spike_count() d2_mean_spikes[i] = striatum_assembly.get_population("D2_"+str(i)).mean_spike_count() print 'CORTEX ', cortex_mean_spikes print 'D1', d1_mean_spikes print 'D2', d2_mean_spikes return gpi_mean_spikes
def setUp(self): sim.setup() self.p = sim.Population(4, sim.IF_cond_exp(**{'tau_m': 12.3, 'cm': lambda i: 0.987 + 0.01 * i, 'i_offset': numpy.array([-0.21, -0.20, -0.19, -0.18])}))
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
def tearDown(self): sim.setup(verbosity='error')
#snn_filepath = layers_path+'/iris_bias_constraint_nest' # simulation variables num_to_test = 30 #case_to_test = 2 num_classes = 10 duration = 100 dt = 1 rescale_fac = 1000 num_timesteps = duration / dt results = np.empty((num_to_test, 3)) # simulation setup import pyNN.nest as sim sim.setup(timestep=dt) # cell parameters cellparams = { 'v_thresh': 1.0, 'v_reset': 0.0, 'v_rest': 0.0, 'e_rev_E': 10.0, 'e_rev_I': -10.0, 'i_offset': 0.0, 'cm': 0.09, 'tau_m': 1000.0, 'tau_syn_E': 0.01, 'tau_syn_I': 0.01, 'tau_refrac': 0.0 }
help="number of horizontal suplots") args = parser.parse_args() import matplotlib as mpl if not args.save: mpl.use('GtkAgg') import matplotlib.pyplot as plt import matplotlib.gridspec as gs from htm.temporal_memory import TemporalMemory class ConnectivityDataError(BaseException): pass # set up PyNN pynn.setup(threads=4) # load stimulus and connectivity files try: connections = np.load('connectivity.npy') stimulus = np.load('stimulus.npy')[:args.steps] labels = np.load('labels.npy')[:args.steps] except IOError, e: raise ConnectivityDataError("Could not find connectivity and/or stimulus data. Please run the `extract.py` script first!") # initialize temporal memory params = addict.Dict() params.config.n_columns = args.columns params.config.n_cells = args.cells tm = TemporalMemory(params)
def test_run_0(self, ): # see https://github.com/NeuralEnsemble/PyNN/issues/191 sim.setup(timestep=0.123, min_delay=0.246) sim.run(0) self.assertEqual(sim.get_current_time(), 0.0)