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 exercise1(v_rest = 65.0): ssp = p.Population(1, cellclass=p.SpikeSourcePoisson) ssp.set('rate', 30.) ssp.record() n = p.Population(1, cellclass=p.IF_cond_exp) n.record_v() n.record() n.record_gsyn() n.set('v_rest', v_rest) prj = p.Projection(ssp, n, target="excitatory", method=p.AllToAllConnector()) prj.setWeights(0.001) p.run(1000) gsyn = n.get_gsyn() pot = n.get_v() spikes = ssp.getSpikes() plot(pot[:,1], pot[:,2]) plot(spikes[:,1], [max(pot[:,2])]*len(spikes), '|', color='r', markersize=20.0) xlabel('Time/ms') ylabel('Membrane potential/mV') title('EPSPs after excitatory postsynaptic signal') plot(gsyn[:,1], gsyn[:,2]) plot(spikes[:,1], [0]*len(spikes), '|', color='r', markersize=20.0) xlabel('Time/ms') ylabel('Membrane potential/mV') title('Excitatory conductance') savefig('../output/day5figure2.png') return pot, gsyn, spikes
def exercise4_iandf(): startTime = time.clock() hugs = p.Population(1, cellclass=p.IF_cond_exp) dcsource = p.DCSource(amplitude=0.9, start=100., stop=100000) dcsource.inject_into(hugs) p.run(100000.) print(time.clock() - startTime)
def run_simulation(parameters, plot_figure=False): """ """ import pyNN.neuron as sim timestamp = datetime.now() model = build_model(**parameters["network"]) if "full_filename" in parameters["experiment"]: xml_file = os.path.splitext(parameters["experiment"]["full_filename"])[0] + ".xml" else: xml_file = "{}.xml".format(parameters["experiment"]["base_filename"]) model.write(xml_file) print("Exported model to file {}".format(xml_file)) sim.setup(timestep=parameters["experiment"]["timestep"]) print("Building network") net = Network(sim, xml_file) if plot_figure: stim = net.populations["Ext"] stim[:100].record('spikes') exc = net.populations["Exc"] exc.sample(50).record("spikes") exc.sample(1).record(["nrn_v", "syn_a"]) inh = net.populations["Inh"] inh.sample(50).record("spikes") inh.sample(1).record(["nrn_v", "syn_a"]) else: ##all = net.assemblies["All"] ##all.sample(parameters["experiment"]["n_record"]).record("spikes") net.populations["Ext"].sample(parameters["experiment"]["n_record"]).record("spikes") ## debugging print("Running simulation") t_stop = parameters["experiment"]["duration"] pb = SimulationProgressBar(t_stop/80, t_stop) sim.run(t_stop, callbacks=[pb]) print("Handling data") data = {} if plot_figure: data["stim"] = stim.get_data().segments[0] data["exc"] = exc.get_data().segments[0] data["inh"] = inh.get_data().segments[0] else: if "full_filename" in parameters["experiment"]: filename = parameters["experiment"]["full_filename"] else: filename = "{}_nineml_{:%Y%m%d%H%M%S}.h5".format(parameters["experiment"]["base_filename"], timestamp) print("Writing data to {}".format(filename)) ##all.write_data(filename) ## debugging net.populations["Ext"].write_data(filename) sim.end() return data
def model_network(param_dict): """ This model network consists of a spike source and a neuron (IF_curr_alpha). The spike rate of the source and the weight can be specified in the param_dict. Returns the number of spikes fired during 1000 ms of simulation. Parameters: param_dict - dictionary with keys rate - the rate of the spike source (spikes/second) weight - weight of the connection source -> neuron Returns: dictionary with keys: source_rate - the rate of the spike source weight - weight of the connection source -> neuron neuron_rate - spike rate of the neuron """ #set up the network import pyNN.neuron as sim sim.setup(dt=0.01, min_delay=1., max_delay=1., debug=False, quit_on_end=False) weight = param_dict['weight'] import NeuroTools.stgen as stgen stgen = stgen.StGen() spiketrain = stgen.poisson_generator(param_dict['rate'], t_stop=1000.) source = sim.Population(1, sim.SpikeSourceArray, {'spike_times': spiketrain.spike_times}) neuron = sim.Population(1, sim.IF_cond_alpha) sim.Projection(source, neuron, method=sim.OneToOneConnector(weights=param_dict['weight'], delays=1.)) #set recorder neuron.record() neuron.record_v() #run the simulation sim.run(1001.) sim.end() # count the number of spikes spikes = neuron.getSpikes() numspikes = len(spikes) # return everything, including the input parameters return { 'source_rate': param_dict['rate'], 'weight': param_dict['weight'], 'neuron_rate': numspikes }
def run_simulation(parameters, plot_figure=False): """ """ timestamp = datetime.now() model = build_model(**parameters["network"]) if "full_filename" in parameters["experiment"]: xml_file = parameters["experiment"]["full_filename"].replace( ".h5", ".xml") else: xml_file = "{}.xml".format(parameters["experiment"]["base_filename"]) model.write(xml_file) print("Exported model to file {}".format(xml_file)) sim.setup() print("Building network") net = Network(sim, xml_file) if plot_figure: stim = net.populations["Ext"] stim[:100].record('spikes') exc = net.populations["Exc"] exc.sample(50).record("spikes") exc.sample(3).record(["nrn_v", "syn_a"]) inh = net.populations["Inh"] inh.sample(50).record("spikes") inh.sample(3).record(["nrn_v", "syn_a"]) else: all = net.assemblies["All"] all.sample(parameters["experiment"]["n_record"]).record("spikes") print("Running simulation") t_stop = parameters["experiment"]["duration"] pb = SimulationProgressBar(t_stop / 80, t_stop) sim.run(t_stop, callbacks=[pb]) print("Handling data") data = {} if plot_figure: data["stim"] = stim.get_data().segments[0] data["exc"] = exc.get_data().segments[0] data["inh"] = inh.get_data().segments[0] else: if "full_filename" in parameters["experiment"]: filename = parameters["experiment"]["full_filename"] else: filename = "{}_nineml_{:%Y%m%d%H%M%S}.h5".format( parameters["experiment"]["base_filename"], timestamp) print("Writing data to {}".format(filename)) all.write_data(filename) sim.end() return data
def testSpikeRecording(self): # We test the mean spike count by checking if the rate of the poissonian sources are # close to 20 Hz. Then we also test how the spikes are saved self.pop1.record() self.pop3.record() simtime = 1000.0 neuron.run(simtime) #self.pop1.printSpikes("temp_neuron.ras", gather=True) rate = self.pop1.meanSpikeCount()*1000/simtime if neuron.rank() == 0: # only on master node assert (20*0.8 < rate) and (rate < 20*1.2), "rate is %s" % rate rate = self.pop3.meanSpikeCount()*1000/simtime self.assertEqual(rate, 0.0)
def testPotentialRecording(self): """Population.record_v() and Population.print_v(): not a full test, just checking # there are no Exceptions raised.""" rng = random.NumpyRNG(123) v_reset = -65.0 v_thresh = -50.0 uniformDistr = random.RandomDistribution(rng=rng, distribution='uniform', parameters=[v_reset, v_thresh]) self.pop2.randomInit(uniformDistr) self.pop2.record_v([self.pop2[0,0], self.pop2[1,1]]) simtime = 10.0 neuron.running = False neuron.run(simtime) self.pop2.print_v("temp_neuron.v", gather=True, compatible_output=True)
def testRecordWithSpikeTimesGreaterThanSimTime(self): """ If a `SpikeSourceArray` is initialized with spike times greater than the simulation time, only those spikes that actually occurred should be written to file or returned by getSpikes(). """ spike_times = numpy.arange(10.0, 200.0, 10.0) spike_source = neuron.Population(1, neuron.SpikeSourceArray, {'spike_times': spike_times}) spike_source.record() neuron.run(100.0) spikes = spike_source.getSpikes() spikes = spikes[:,1] if neuron.rank() == 0: self.assert_( max(spikes) == 100.0, str(spikes) )
def model_network(param_dict): """ This model network consists of a spike source and a neuron (IF_curr_alpha). The spike rate of the source and the weight can be specified in the param_dict. Returns the number of spikes fired during 1000 ms of simulation. Parameters: param_dict - dictionary with keys rate - the rate of the spike source (spikes/second) weight - weight of the connection source -> neuron Returns: dictionary with keys: source_rate - the rate of the spike source weight - weight of the connection source -> neuron neuron_rate - spike rate of the neuron """ #set up the network import pyNN.neuron as sim sim.setup(dt = 0.01, min_delay = 1., max_delay = 1., debug = False, quit_on_end = False) weight = param_dict['weight'] import NeuroTools.stgen as stgen stgen = stgen.StGen() spiketrain = stgen.poisson_generator(param_dict['rate'], t_stop = 1000.) source = sim.Population(1, sim.SpikeSourceArray, {'spike_times':spiketrain.spike_times}) neuron = sim.Population(1, sim.IF_cond_alpha) sim.Projection(source, neuron, method = sim.OneToOneConnector(weights = param_dict['weight'], delays = 1.)) #set recorder neuron.record() neuron.record_v() #run the simulation sim.run(1001.) sim.end() # count the number of spikes spikes = neuron.getSpikes() numspikes = len(spikes) # return everything, including the input parameters return {'source_rate':param_dict['rate'], 'weight':param_dict['weight'], 'neuron_rate':numspikes }
def run_simulation(parameters, plot_figure=False): """ """ import pyNN.neuron as sim timestamp = datetime.now() model = build_model(**parameters["network"]) if "full_filename" in parameters["experiment"]: xml_file = parameters["experiment"]["full_filename"].replace( ".h5", ".xml") else: xml_file = "{}.xml".format(parameters["experiment"]["base_filename"]) model.write(xml_file) print("Exported model to file {}".format(xml_file)) sim.setup() print("Building network") net = Network(sim, xml_file) stim = net.populations["Ext"] stim.record('spikes') exc = net.populations["Exc"] exc.record("spikes") exc[:3].record(["nrn_v", "syn_a"]) print("Running simulation") t_stop = parameters["experiment"]["duration"] pb = SimulationProgressBar(t_stop / 80, t_stop) sim.run(t_stop, callbacks=[pb]) print("Handling data") data = {} if plot_figure: data["stim"] = stim.get_data().segments[0] data["exc"] = exc.get_data().segments[0] data["exc"].annotate(simulator="lib9ML with pyNN.neuron") else: if "full_filename" in parameters["experiment"]: filename = parameters["experiment"]["full_filename"] else: filename = "{}_nineml_{:%Y%m%d%H%M%S}.pkl".format( parameters["experiment"]["base_filename"], timestamp) print("Writing data to {}".format(filename)) exc.write_data(filename) sim.end() return data
def run_simulation(parameters, plot_figure=False): """ """ import pyNN.neuron as sim timestamp = datetime.now() model = build_model(**parameters["network"]) if "full_filename" in parameters["experiment"]: xml_file = parameters["experiment"]["full_filename"].replace(".h5", ".xml") else: xml_file = "{}.xml".format(parameters["experiment"]["base_filename"]) model.write(xml_file) print("Exported model to file {}".format(xml_file)) sim.setup() print("Building network") net = Network(sim, xml_file) stim = net.populations["Ext"] stim.record('spikes') exc = net.populations["Exc"] exc.record("spikes") n_record = int(parameters["experiment"]["n_record"]) exc[:n_record].record(["nrn_v", "syn_a"]) print("Running simulation") t_stop = parameters["experiment"]["duration"] pb = SimulationProgressBar(t_stop/80, t_stop) sim.run(t_stop, callbacks=[pb]) print("Handling data") data = {} if plot_figure: data["stim"] = stim.get_data().segments[0] data["exc"] = exc.get_data().segments[0] data["exc"].annotate(simulator="lib9ML with pyNN.neuron") else: if "full_filename" in parameters["experiment"]: filename = parameters["experiment"]["full_filename"] else: filename = "{}_nineml_{:%Y%m%d%H%M%S}.pkl".format(parameters["experiment"]["base_filename"], timestamp) print("Writing data to {}".format(filename)) exc.write_data(filename) sim.end() return data
def exercise3(): p.setup(quit_on_end=False, timestep=0.01) iandf = p.Population(1, cellclass=p.IF_cond_exp) dcsource = p.DCSource(amplitude=1.0, start=100.0, stop=1000.0) dcsource.inject_into(iandf) iandf.record() iandf.record_v() p.run(1200.0) pot = iandf.get_v() spikes = iandf.getSpikes() plot(pot[:, 1], pot[:, 2], color="b") plot(spikes[:, 1], [-60] * len(spikes), ".", color="r") line = axhline(y=-60, xmin=0, xmax=len(pot[:, 1]), color="r") xlabel("Time/ms") ylabel("Current/mV") savefig("../output/day4_figure3.png") show()
def run_simulation(parameters, plot_figure=False): """ """ timestamp = datetime.now() dt = 0.1 seed = parameters["experiment"]["seed"] sim.setup(timestep=dt) print("Building network") stim, exc, inh = build_network(sim, seed=seed, **parameters["network"]) if plot_figure: stim[:100].record('spikes') exc.sample(50).record("spikes") exc.sample(3).record("nrn_v") inh.sample(50).record("spikes") inh.sample(3).record("nrn_v") else: all = exc + inh all.sample(parameters["experiment"]["n_record"]).record("spikes") print("Running simulation") t_stop = parameters["experiment"]["duration"] pb = SimulationProgressBar(t_stop/80, t_stop) sim.run(t_stop, callbacks=[pb]) print("Handling data") data = {} if plot_figure: data["stim"] = stim.get_data().segments[0] data["exc"] = exc.get_data().segments[0] data["inh"] = inh.get_data().segments[0] else: if "full_filename" in parameters["experiment"]: filename = parameters["experiment"]["full_filename"] else: filename = "{}_ninemlpartial_{:%Y%m%d%H%M%S}.h5".format(parameters["experiment"]["base_filename"], timestamp) print("Writing data to {}".format(filename)) all.write_data(filename) sim.end() return data
def exercise4_curve(tau_refrac): hugs = p.Population(1, cellclass=p.IF_cond_exp) hugs.set("tau_refrac", tau_refrac) start = 100. stop = 1100. frequency = [] currentSpace = linspace(0.1,5.0,50) for current in currentSpace: hugs.record() hugs.record_v() dcsource = p.DCSource(amplitude=current, start=start, stop=stop) dcsource.inject_into(hugs) p.run(1100.) spikes = hugs.getSpikes() frequency.append(len(spikes) / (stop - start)) print(current, frequency[-1]) p.reset() return currentSpace, frequency
def sim(trial): global direction global inspikes global outspikes global outspikes2 global outvolts direction=0 #print direction p.reset() #for direction in dirs: for n in range(len(neuron)): neuron[n].set('spike_times',DATA[direction][n][trial]) p.run(2000) outspikes=[0,0] outspikes2=[] outvolts=[] for i,o in enumerate(out): outspikes[i]=o.get_spike_counts().values()[0] outspikes2.append(o.getSpikes()) outvolts.append(o.get_v()) inspikes=[0,0,0,0,0] for i,n in enumerate(neuron): inspikes[i]=n.get_spike_counts().values()[0] """ fig = figure() ax = fig.add_subplot(1,1,1) hold(True) for i in range(nout): ax.plot(outspikes2[i][:,1],i*ones_like(outspikes2[i][:,1]),'b|') ax.set_ylim(-6,5) for i in range(nneurons): # ax.plot(DATA[direction][i][trial],-1-i*ones_like(DATA[direction][i][trial]),'r|') inspikes2=neuron[i].getSpikes() ax.plot(inspikes2,-1-i*ones_like(inspikes2),'r|') #ax2=fig.add_subplot(2,1,2) #ax2.plot(outvolts[0][:,1],outvolts[0][:,2]) """ return inspikes,outspikes
def exercise3(): figure(figsize=(10,6)) p.setup(quit_on_end=False, timestep=0.01) iandf = p.Population(1, cellclass=p.IF_cond_exp) dcsource = p.DCSource(amplitude=1., start=100., stop=1000.) dcsource.inject_into(iandf) iandf.record() iandf.record_v() p.run(1200.) pot = iandf.get_v() spikes = iandf.getSpikes() plt = plot(pot[:,1], pot[:,2], color='b') spks = plot(spikes[:,1], [-49]*len(spikes), '.', color='r') legend((plt, spks), ('Membrane potential', 'Spike times')) xlabel('Time/ms') ylabel('Current/mV') title('Integrate and fire model neuron') savefig('../output/day4_figure3.png') show()
def exercise2(): hugs = p.Population(1, cellclass=p.HH_cond_exp) start = 100.0 stop = 1100.0 frequency = [] currentSpace = linspace(0.1, 10, 100) for current in currentSpace: hugs.record() hugs.record_v() dcsource = p.DCSource(amplitude=current, start=start, stop=stop) dcsource.inject_into(hugs) p.run(1100.0) spikes = hugs.getSpikes() frequency.append(len(spikes) / (stop - start)) p.reset() plot(currentSpace, frequency) xlabel("Current/nA") ylabel("Frequency/kHz") savefig("../output/day4_figure2.png") show()
def exercise1(): hugs = p.Population(1, cellclass=p.HH_cond_exp) dcsource = p.DCSource(amplitude=1.0, start=100.0, stop=600) dcsource.inject_into(hugs) hugs.record() hugs.record_v() p.run(1000.0) pot = hugs.get_v() spikes = hugs.getSpikes() plot(pot[:, 1], pot[:, 2]) plot(spikes[:, 1], [-40] * len(spikes), ".", color="r") line = axhline(y=-40, xmin=0, xmax=len(pot[:, 1]), color="r") xlabel("Time/ms") ylabel("Current/mV") savefig("../output/day4_figure1.png") show()
def exercise1(): figure(figsize=(10,6)) hugs = p.Population(1, cellclass=p.HH_cond_exp) dcsource = p.DCSource(amplitude=1., start=100., stop=600) dcsource.inject_into(hugs) hugs.record() hugs.record_v() p.run(1000.) pot = hugs.get_v() spikes = hugs.getSpikes() plt = plot(pot[:,1], pot[:,2]) spks = plot(spikes[:,1], [52]*len(spikes), 'D', color='r') xlabel('Time/ms') ylabel('Current/mV') legend((plt, spks), ('Membrane potential', 'Spike times')) title('Hodgkin-Huxley model neuron') savefig('../output/day4_figure1.png') show()
def exercise5(tau_m, v_thresh=-55.0): hugs = p.Population(1, cellclass=p.IF_cond_exp) hugs.set("tau_refrac", 2.0) hugs.set("tau_m", tau_m) hugs.set("v_thresh", v_thresh) start = 100.0 stop = 400.0 dcsource = p.DCSource(amplitude=0.95, start=start, stop=stop) dcsource.inject_into(hugs) hugs.record() hugs.record_v() p.run(500.0) pot = hugs.get_v() spikes = hugs.getSpikes() p.reset() return pot, spikes, (stop - start)
def exercise2(): figure(figsize=(10,6)) hugs = p.Population(1, cellclass=p.HH_cond_exp) start = 100. stop = 1100. frequency = [] currentSpace = linspace(0.1,10,100) for current in currentSpace: hugs.record() hugs.record_v() dcsource = p.DCSource(amplitude=current, start=start, stop=stop) dcsource.inject_into(hugs) p.run(1100.) spikes = hugs.getSpikes() frequency.append(len(spikes) / (stop - start)) p.reset() plot(currentSpace, frequency) title('Current-frequency diagram for a HH model neuron') xlabel('Current/nA') ylabel('Frequency/kHz') savefig('../output/day4_figure2.png') show()
def t4(): print 'Loading Forth XML File (iaf-2coba-Model)' print '----------------------------------------' component = readers.XMLReader.read_component( Join(tenml_dir, 'iaf_2coba.10ml'), component_name='iaf') writers.XMLWriter.write(component, '/tmp/nineml_toxml4.xml', ) model = readers.XMLReader.read_component(Join(tenml_dir, 'iaf_2coba.10ml')) from nineml.abstraction_layer.flattening import flatten from nineml.abstraction_layer.component_modifiers import ComponentModifier flatcomponent = flatten(model, componentname='iaf_2coba') ComponentModifier.close_analog_port(component=flatcomponent, port_name='iaf_iSyn', value='0') writers.XMLWriter.write(flatcomponent, '/tmp/nineml_out_iaf_2coba.9ml') import pyNN.neuron as sim from pyNN.utility import init_logging init_logging(None, debug=True) sim.setup(timestep=0.1, min_delay=0.1) print 'Attempting to simulate From Model:' print '----------------------------------' celltype_cls = pyNNml.nineml_celltype_from_model( name="iaf_2coba", nineml_model=flatcomponent, synapse_components=[ pyNNml.CoBaSyn(namespace='cobaExcit', weight_connector='q'), pyNNml.CoBaSyn(namespace='cobaInhib', weight_connector='q'), ] ) parameters = { 'iaf.cm': 1.0, 'iaf.gl': 50.0, 'iaf.taurefrac': 5.0, 'iaf.vrest': -65.0, 'iaf.vreset': -65.0, 'iaf.vthresh': -50.0, 'cobaExcit.tau': 2.0, 'cobaInhib.tau': 5.0, 'cobaExcit.vrev': 0.0, 'cobaInhib.vrev': -70.0, } parameters = ComponentFlattener.flatten_namespace_dict(parameters) cells = sim.Population(1, celltype_cls, parameters) cells.initialize('iaf_V', parameters['iaf_vrest']) cells.initialize('tspike', -1e99) # neuron not refractory at start cells.initialize('regime', 1002) # temporary hack input = sim.Population(2, sim.SpikeSourcePoisson, {'rate': 100}) connector = sim.OneToOneConnector(weights=1.0, delays=0.5) conn = [sim.Projection(input[0:1], cells, connector, target='cobaExcit'), sim.Projection(input[1:2], cells, connector, target='cobaInhib')] cells._record('iaf_V') cells._record('cobaExcit_g') cells._record('cobaInhib_g') cells._record('cobaExcit_I') cells._record('cobaInhib_I') cells.record() sim.run(100.0) cells.recorders['iaf_V'].write("Results/nineml_neuron.V", filter=[cells[0]]) cells.recorders['cobaExcit_g'].write("Results/nineml_neuron.g_exc", filter=[cells[0]]) cells.recorders['cobaInhib_g'].write("Results/nineml_neuron.g_inh", filter=[cells[0]]) cells.recorders['cobaExcit_I'].write("Results/nineml_neuron.g_exc", filter=[cells[0]]) cells.recorders['cobaInhib_I'].write("Results/nineml_neuron.g_inh", filter=[cells[0]]) t = cells.recorders['iaf_V'].get()[:, 1] v = cells.recorders['iaf_V'].get()[:, 2] gInh = cells.recorders['cobaInhib_g'].get()[:, 2] gExc = cells.recorders['cobaExcit_g'].get()[:, 2] IInh = cells.recorders['cobaInhib_I'].get()[:, 2] IExc = cells.recorders['cobaExcit_I'].get()[:, 2] import pylab pylab.subplot(311) pylab.ylabel('Voltage') pylab.plot(t, v) pylab.subplot(312) pylab.ylabel('Conductance') pylab.plot(t, gInh) pylab.plot(t, gExc) pylab.subplot(313) pylab.ylabel('Current') pylab.plot(t, IInh) pylab.plot(t, IExc) pylab.suptitle("From Tree-Model Pathway") pylab.show() sim.end()
prjE_E = sim.Projection(poissonE_E, popE, method=myconn, target='excitatory') prjE_I = sim.Projection(poissonE_I, popI, method=myconn, target='excitatory') prjI_E = sim.Projection(poissonI_E, popE, method=myconn, target='inhibitory') prjI_I = sim.Projection(poissonI_I, popI, method=myconn, target='inhibitory') ## Record the spikes ## popE.record(to_file=False) popI.record(to_file=False) printTimer("Time for setup part") ###################### RUN PART ########################### ## Run the simulation without inter-connection ## printMessage("Now running without inter-lattice connections.") sim.run(int(tinit)) printTimer("Time for first half of run") # Lower the external network "ghost" processes according to how many connections of that # type were added. poissonI_E.rate = rateI_E * (connectionsI_E - NumOfConI_E) poissonI_I.rate = rateI_I * (connectionsI_I - NumOfConI_I) poissonE_E.rate = rateE_E * (connectionsE_E - NumOfConE_E) poissonE_I.rate = rateE_I * (connectionsE_I - NumOfConE_I) # Prepare the connectors # myConnectorE_E = LatticeConnector(weights=globalWeight, dist_factor=distanceFactor, noise_factor=noiseFactor, n=NumOfConE_E)
prjE_E = sim.Projection(poissonE_E, popE, method=myconn, target='excitatory') prjE_I = sim.Projection(poissonE_I, popI, method=myconn, target='excitatory') prjI_E = sim.Projection(poissonI_E, popE, method=myconn, target='inhibitory') prjI_I = sim.Projection(poissonI_I, popI, method=myconn, target='inhibitory') ## Record the spikes ## popE.record(to_file=False) popI.record(to_file=False) printTimer("Time for setup part") ###################### RUN PART ########################### ## Run the simulation without inter-connection ## printMessage("Now running without inter-lattice connections.") sim.run(int(tinit)) printTimer("Time for first half of run") # Lower the external network "ghost" processes according to how many connections of that # type were added. poissonI_E.rate = rateI_E * (connectionsI_E - NumOfConI_E) poissonI_I.rate = rateI_I * (connectionsI_I - NumOfConI_I) poissonE_E.rate = rateE_E * (connectionsE_E - NumOfConE_E) poissonE_I.rate = rateE_I * (connectionsE_I - NumOfConE_I) # Prepare the connectors # myConnectorE_E = LatticeConnector(weights=globalWeight, dist_factor=distanceFactor, noise_factor=noiseFactor, n=NumOfConE_E) myConnectorE_I = LatticeConnector(weights=globalWeight, dist_factor=distanceFactor,
A_plus=0.003, A_minus=0.005))) prj1 = p.Projection(ss1,tn, method=p.AllToAllConnector(), synapse_dynamics=syndyn) prj2 = p.Projection(ss2,tn, method=p.AllToAllConnector(), synapse_dynamics=syndyn) weight = 0.04 prj1.setWeights(weight) prj2.setWeights(weight) times = numpy.ones(2000)*10. # 2000 * 10 ms = 20000 ms prj1_weights = numpy.zeros_like(times) prj2_weights = numpy.zeros_like(times) for i,t in enumerate(times): p.run(t) prj1_weights[i] = prj1.getWeights()[0] prj2_weights[i] = prj2.getWeights()[0] spikes = tn.getSpikes() figure() plot(numpy.cumsum(times), prj1_weights, label='prj1', color='blue') plot(numpy.cumsum(times), prj2_weights, label='prj2', color='red') plot(spikes, [0.04]*len(spikes), '|', color='black', markersize=10.0) plot(st1, [0.042]*len(st1), '|', color='blue', markersize=10.0) plot(st2, [0.042]*len(st2), '|', color='red', markersize=10.0) ax = gca() ax.set_ylabel('weight [nA]') ax.set_xlabel('time [ms]') legend()
n, sim.SpikeSourceArray(spike_times=generate_spike_times)) spike_source.record('spikes') cells.record('spikes') cells[0:2].record('m') syn = sim.StaticSynapse(weight=w, delay=syn_delay) input_conns = sim.Projection(spike_source, cells, sim.FixedProbabilityConnector(0.5), syn, receptor_type="default") # === Run simulation =========================================================== sim.run(simtime) filename = normalized_filename("Results", "nrn_artificial_cell", "pkl", "neuron", sim.num_processes()) cells.write_data(filename, annotations={'script_name': __file__}) print("Mean firing rate: ", cells.mean_spike_count() * 1000.0 / simtime, "Hz") plot_figure = True if plot_figure: from pyNN.utility.plotting import Figure, Panel figure_filename = filename.replace("pkl", "png") data = cells.get_data().segments[0] m = data.filter(name="m")[0] Figure(Panel(m, ylabel="Membrane potential (dimensionless)",
def run(plot_and_show=True): import sys from os.path import abspath, realpath, join import nineml root = abspath(join(realpath(nineml.__path__[0]), "../../..")) sys.path.append(join(root, "lib9ml/python/examples/AL")) sys.path.append(join(root, "code_generation/nmodl")) from nineml.abstraction_layer.example_models import get_hierachical_iaf_2coba from nineml.abstraction_layer.flattening import ComponentFlattener import pyNN.neuron as sim import pyNN.neuron.nineml as pyNNml from pyNN.utility import init_logging init_logging(None, debug=True) sim.setup(timestep=0.1, min_delay=0.1) testModel = get_hierachical_iaf_2coba() celltype_cls = pyNNml.nineml_celltype_from_model( name="iaf_2coba", nineml_model=testModel, synapse_components=[ pyNNml.CoBaSyn( namespace='cobaExcit', weight_connector='q'), pyNNml.CoBaSyn( namespace='cobaInhib', weight_connector='q'), ] ) parameters = { 'iaf.cm': 1.0, 'iaf.gl': 50.0, 'iaf.taurefrac': 5.0, 'iaf.vrest': -65.0, 'iaf.vreset': -65.0, 'iaf.vthresh': -50.0, 'cobaExcit.tau': 2.0, 'cobaInhib.tau': 5.0, 'cobaExcit.vrev': 0.0, 'cobaInhib.vrev': -70.0, } parameters = ComponentFlattener.flatten_namespace_dict(parameters) cells = sim.Population(1, celltype_cls, parameters) cells.initialize('iaf_V', parameters['iaf_vrest']) cells.initialize('tspike', -1e99) # neuron not refractory at start cells.initialize('regime', 1002) # temporary hack input = sim.Population(2, sim.SpikeSourcePoisson, {'rate': 100}) connector = sim.OneToOneConnector(weights=1.0, delays=0.5) # connector = sim.OneToOneConnector(weights=20.0, delays=0.5) conn = [sim.Projection(input[0:1], cells, connector, target='cobaExcit'), sim.Projection(input[1:2], cells, connector, target='cobaInhib')] cells._record('iaf_V') cells._record('cobaExcit_g') cells._record('cobaInhib_g') cells._record('regime') cells.record() sim.run(100.0) cells.recorders['iaf_V'].write("Results/nineml_neuron.V", filter=[cells[0]]) cells.recorders['regime'].write("Results/nineml_neuron.regime", filter=[cells[0]]) cells.recorders['cobaExcit_g'].write("Results/nineml_neuron.g_exc", filter=[cells[0]]) cells.recorders['cobaInhib_g'].write("Results/nineml_neuron.g_inh", filter=[cells[0]]) t = cells.recorders['iaf_V'].get()[:, 1] v = cells.recorders['iaf_V'].get()[:, 2] regime = cells.recorders['regime'].get()[:, 2] gInh = cells.recorders['cobaInhib_g'].get()[:, 2] gExc = cells.recorders['cobaExcit_g'].get()[:, 2] if plot_and_show: import pylab pylab.subplot(311) pylab.plot(t, v) pylab.subplot(312) pylab.plot(t, gInh) pylab.plot(t, gExc) pylab.subplot(313) pylab.plot(t, regime) pylab.ylim((999, 1005)) pylab.suptitle("From Tree-Model Pathway") pylab.show() sim.end()
""" from plot_helper import plot_current_source import pyNN.neuron as sim sim.setup() population = sim.Population(30, sim.IF_cond_exp(tau_m=10.0)) population[27:28].record_v() steps = sim.StepCurrentSource(times=[50.0, 110.0, 150.0, 210.0], amplitudes=[0.4, 0.6, -0.2, 0.2]) steps.inject_into(population[(6, 11, 27)]) steps._record() sim.run(250.0) t, i_inj = steps._get_data() v = population.get_data().segments[0].analogsignals[0] plot_current_source( t, i_inj, v, #v_range=(-66, -49), v_ticks=(-66, -64, -62, -60), i_range=(-0.3, 0.7), i_ticks=(-0.2, 0.0, 0.2, 0.4, 0.6), t_range=(0, 250))
fpc = sim.FixedProbabilityConnector(0.02, rng=NumpyRNG(seed=854)) connections = sim.Projection(input, output, fpc, synapse_type=stdp, receptor_type='excitatory') connections.set(eta=0.0003) output.record(['spikes', 'v']) sim.run(simTimeFin - simTimeIni) print("\n\nETA: input to output:") print connections.get('eta', format='list') print("\n\ninput to output:") print connections.get('weight', format='list') data = output.get_data().segments[0] popSpikes = output.get_data('spikes')
""" import pyNN.neuron as sim import pylab as pl from quantities import nA sim.setup(timestep=0.01) cell = sim.Population(1, sim.HH_cond_exp()) step_current = sim.DCSource(start=20.0, stop=150.0) step_current.inject_into(cell) cell.record('v') for amp in [-0.2, 0.1]: step_current.amplitude = amp sim.run(200.0) sim.reset(annotations={"amplitude": amp*nA}) data = cell.get_data() sim.end() for segment in data.segments: vm = segment.analogsignalarrays[0] pl.plot(vm.times, vm, linewidth=2, label=str(segment.annotations["amplitude"])) pl.legend(loc=0, fontsize=16) pl.xlabel("Time (%s)" % vm.times.units._dimensionality, fontsize=16) pl.ylabel("Membrane potential (%s)" % vm.units._dimensionality, fontsize=16) pl.tick_params(labelsize=16)
""" """ from plot_helper import plot_current_source import pyNN.neuron as sim sim.setup() population = sim.Population(30, sim.IF_cond_exp(tau_m=10.0)) population[27:28].record_v() steps = sim.StepCurrentSource(times=[50.0, 110.0, 150.0, 210.0], amplitudes=[0.4, 0.6, -0.2, 0.2]) steps.inject_into(population[(6, 11, 27)]) steps._record() sim.run(250.0) t, i_inj = steps._get_data() v = population.get_data().segments[0].analogsignalarrays[0] plot_current_source(t, i_inj, v, #v_range=(-66, -49), v_ticks=(-66, -64, -62, -60), i_range=(-0.3, 0.7), i_ticks=(-0.2, 0.0, 0.2, 0.4, 0.6), t_range=(0, 250))
## # Setup and run a simulation. Note there is no current injection into the neuron. # All cells in the network are in a quiescent state, so its not a surprise that xthere are no spikes ## neurons = all_cells sim = pyNN.neuron arange = np.arange import re neurons.record(['v', 'spikes']) # , 'u']) neurons.initialize(v=-65.0, u=-14.0) # === Run the simulation ===================================================== sim.run(15509.0) data = neurons.get_data().segments[0] with open('pickles/qi.p', 'wb') as f: pickle.dump(data, f) ''' from pyNN.utility.plotting import Figure, Panel, comparison_plot, plot_spiketrains data = neurons.get_data().segments[0] v = data.filter(name="v") for i in v: Figure( Panel(i, ylabel="Membrane potential (mV)", xticks=True, xlabel="Time (ms)", yticks=True), #Panel(u, ylabel="u variable (units?)"), annotations="Simulated with" )
connector = sim.OneToOneConnector(weights=1.0, delays=0.5) conn = [ sim.Projection(input[0:1], cells, connector, target='nmda'), sim.Projection(input[0:1], cells, connector, target='cobaExcit'), ] cells._record('iaf_V') cells._record('nmda_g') cells._record('cobaExcit_g') cells.record() sim.run(100.0) cells.recorders['iaf_V'].write("Results/nineml_neuron.V", filter=[cells[0]]) cells.recorders['nmda_g'].write("Results/nineml_neuron.g_nmda", filter=[cells[0]]) cells.recorders['cobaExcit_g'].write("Results/nineml_neuron.g_cobaExcit", filter=[cells[0]]) t = cells.recorders['iaf_V'].get()[:, 1] v = cells.recorders['iaf_V'].get()[:, 2] gNMDA = cells.recorders['nmda_g'].get()[:, 2] gExcit = cells.recorders['cobaExcit_g'].get()[:, 2] import pylab pylab.subplot(211) pylab.plot(t, v)
def run(argv): """ Runs the simulation script from the provided arguments """ import nineml from pype9.exceptions import Pype9UsageError import neo.io import time import logging logger = logging.getLogger('PyPe9') args = parser.parse_args(argv) seed = time.time() if args.seed is None else args.seed if args.simulator == 'neuron': from pype9.neuron import Network, CellMetaClass, simulation_controller # @UnusedImport @IgnorePep8 elif args.simulator == 'nest': from pype9.nest import Network, CellMetaClass, simulation_controller # @Reimport @IgnorePep8 else: raise Pype9UsageError( "Unrecognised simulator '{}', (available 'neuron' or 'nest')" .format(args.simulator)) if isinstance(args.model, nineml.Document): min_delay = 0.1 # FIXME: Should add as method to Network class max_delay = 10.0 else: min_delay = args.timestep max_delay = args.timestep * 2 if isinstance(args.model, nineml.Network): if args.simulator == 'neuron': from pyNN.neuron import run, setup # @UnusedImport else: from pyNN.nest import run, setup # @Reimport # Reset the simulator setup(min_delay=min_delay, max_delay=max_delay, timestep=args.timestep, rng_seeds_seed=seed) # Construct the network print "Constructing '{}' network".format(args.model.name) network = Network(args.model, build_mode=args.build_mode) print "Finished constructing the '{}' network".format(args.model.name) for record_name, _, _ in args.record: pop_name, port_name = record_name.split('.') network[pop_name].record(port_name) print "Running the simulation".format() run(args.simtime) for record_name, filename, name in args.record: pop_name, port_name = record_name.split('.') seg = network[pop_name].get_data().segments[0] data[filename] = seg # FIXME: not implemented else: assert isinstance(args.model, (nineml.DynamicsProperties, nineml.Dynamics)) model = args.model # Override properties passed as options if args.prop: props_dict = dict((parm, float(val) * parse_units(unts)) for parm, val, unts in args.prop) props = nineml.DynamicsProperties( model.name + '_props', model, props_dict) component_class = model elif isinstance(model, nineml.DynamicsProperties): props = model component_class = model.component_class else: raise Pype9UsageError( "Specified model {} is not a dynamics properties object and " "no properties supplied to simulate command via --prop option" .format(model)) # Get the init_regime init_regime = args.init_regime if init_regime is None: if component_class.num_regimes == 1: init_regime = next(component_class.regimes).name else: raise Pype9UsageError( "Need to specify initial regime as dynamics has more than " "one '{}'".format("', '".join( r.name for r in component_class.regimes))) # Build cell class Cell = CellMetaClass(component_class, name=model.name, init_regime=init_regime, build_mode=args.build_mode, default_properties=props) # Create cell cell = Cell() init_state = dict((sv, float(val) * parse_units(units)) for sv, val, units in args.init_value) if set(cell.state_variable_names) != set(init_state.iterkeys()): raise Pype9UsageError( "Need to specify an initial value for each state in the model," " missing '{}'".format( "', '".join(set(cell.state_variable_names) - set(init_state.iterkeys())))) cell.set_state(init_state) # Play inputs for port_name, fname, _ in args.play: port = component_class.receive_port(port_name) seg = neo.io.PickleIO(filename=fname).read()[0] if port.communicates == 'event': signal = seg.spiketrains[0] else: signal = seg.analogsignals[0] # Input is an event train or analog signal cell.play(port_name, signal) # Set up recorders for port_name, _, _ in args.record: cell.record(port_name) # Run simulation simulation_controller.run(args.time) # Collect data into Neo Segments fnames = set(r[1] for r in args.record) data_segs = {} for fname in fnames: data_segs[fname] = neo.Segment( description="Simulation of '{}' cell".format(model.name)) for port_name, fname, _ in args.record: data = cell.recording(port_name) if isinstance(data, neo.AnalogSignal): data_segs[fname].analogsignals.append(data) else: data_segs[fname].spiketrains.append(data) # Write data to file for fname, data_seg in data_segs.iteritems(): neo.io.PickleIO(fname).write(data_seg) logger.info("Simulated '{}' for {} ms".format(model.name, args.time))
sim.setup() pyr_parameters= {'cm': 0.25, 'tau_m': 20.0, 'v_rest': -60, 'v_thresh': -50, 'tau_refrac': refractory_period, 'v_reset': -60, 'v_spike': -50.0, 'a': 1.0, 'b': 0.005, 'tau_w': 600, 'delta_T': 2.5, 'tau_syn_E': 5.0, 'e_rev_E': 0.0, 'tau_syn_I': 10.0, 'e_rev_I': -80 } pyrcell = sim.Population(1, sim.EIF_cond_exp_isfa_ista(**pyr_parameters)) step_current = sim.DCSource(start=20.0, stop=80.0) step_current.inject_into(pyrcell) pyrcell.record('v') print(pyrcell.celltype.recordable) for amp in (-0.2, -0.1, 0.0, 0.1, 0.2,0.3,0.4,0.5): step_current.amplitude = amp sim.run(150.0) sim.reset(annotations={"amplitude": amp * nA}) data = pyrcell.get_data() sim.end() for segment in data.segments: vm = segment.analogsignals[0] plt.plot(vm.times, vm, label=str(segment.annotations["amplitude"])) plt.legend(loc="upper left") plt.xlabel("Time (%s)" % vm.times.units._dimensionality) plt.ylabel("Membrane potential (%s)" % vm.units._dimensionality) plt.show()
nineml_cell_type('Poisson', read("../sources/Poisson.xml")['Poisson'], {})(rate=rate)) stim.initialize(t_next=numpy.random.exponential(1000 / rate)) weight = 0.1 delay = 0.5 prj = sim.Projection(stim, p, sim.AllToAllConnector(), sim.StaticSynapse(weight=weight, delay=delay), receptor_type='excitatory') stim.record('spikes') p.record('v') sim.run(t_stop) nrn_data = p.get_data().segments[0] stim_data = stim.get_data().segments[0] print("Expected spike count: {}".format(t_stop * rate / 1000)) print("Actual spike count: {}".format(stim.mean_spike_count())) Figure( Panel(stim_data.spiketrains, markersize=0.5, xlim=(0, t_stop)), Panel(nrn_data.filter(name='v')[0], yticks=True, xlim=(0, t_stop), xticks=True, xlabel="Time (ms)"), ).save("test_poisson_generator.png")
def run(plot_and_show=True): import sys from os.path import abspath, realpath, join import numpy import nineml root = abspath(join(realpath(nineml.__path__[0]), "../../..")) sys.path.append(join(root, "lib9ml/python/examples/AL")) sys.path.append(join(root, "code_generation/nmodl")) sys.path.append(join(root, "code_generation/nest2")) #from nineml.abstraction_layer.example_models import get_hierachical_iaf_3coba from nineml.abstraction_layer.testing_utils import TestableComponent from nineml.abstraction_layer.flattening import ComponentFlattener import pyNN.neuron as sim import pyNN.neuron.nineml as pyNNml from pyNN.utility import init_logging init_logging(None, debug=True) sim.setup(timestep=0.1, min_delay=0.1) #test_component = get_hierachical_iaf_3coba() test_component = TestableComponent('hierachical_iaf_3coba')() from nineml.abstraction_layer.writers import DotWriter DotWriter.write(test_component, 'test1.dot') from nineml.abstraction_layer.writers import XMLWriter XMLWriter.write(test_component, 'iaf_3coba.xml') celltype_cls = pyNNml.nineml_celltype_from_model( name="iaf_3coba", nineml_model=test_component, synapse_components=[ pyNNml.CoBaSyn(namespace='AMPA', weight_connector='q'), pyNNml.CoBaSyn(namespace='GABAa', weight_connector='q'), pyNNml.CoBaSyn(namespace='GABAb', weight_connector='q'), ]) parameters = { 'iaf.cm': 1.0, 'iaf.gl': 50.0, 'iaf.taurefrac': 5.0, 'iaf.vrest': -65.0, 'iaf.vreset': -65.0, 'iaf.vthresh': -50.0, 'AMPA.tau': 2.0, 'GABAa.tau': 5.0, 'GABAb.tau': 50.0, 'AMPA.vrev': 0.0, 'GABAa.vrev': -70.0, 'GABAb.vrev': -95.0, } parameters = ComponentFlattener.flatten_namespace_dict(parameters) cells = sim.Population(1, celltype_cls, parameters) cells.initialize('iaf_V', parameters['iaf_vrest']) cells.initialize('tspike', -1e99) # neuron not refractory at start cells.initialize('regime', 1002) # temporary hack 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'), sim.Projection(input[1:2], cells, connector, target='GABAa'), sim.Projection(input[2:3], cells, connector, target='GABAb') ] cells._record('iaf_V') cells._record('AMPA_g') cells._record('GABAa_g') cells._record('GABAb_g') cells.record() sim.run(100.0) cells.recorders['iaf_V'].write("Results/nineml_neuron.V", filter=[cells[0]]) cells.recorders['AMPA_g'].write("Results/nineml_neuron.g_exc", filter=[cells[0]]) cells.recorders['GABAa_g'].write("Results/nineml_neuron.g_gabaA", filter=[cells[0]]) cells.recorders['GABAb_g'].write("Results/nineml_neuron.g_gagaB", filter=[cells[0]]) t = cells.recorders['iaf_V'].get()[:, 1] v = cells.recorders['iaf_V'].get()[:, 2] gInhA = cells.recorders['GABAa_g'].get()[:, 2] gInhB = cells.recorders['GABAb_g'].get()[:, 2] gExc = cells.recorders['AMPA_g'].get()[:, 2] if plot_and_show: import pylab pylab.subplot(211) pylab.plot(t, v) pylab.ylabel('voltage [mV]') pylab.suptitle("AMPA, GABA_A, GABA_B") pylab.subplot(212) pylab.plot(t, gInhA, label='GABA_A') pylab.plot(t, gInhB, label='GABA_B') pylab.plot(t, gExc, label='AMPA') pylab.ylabel('conductance [nS]') pylab.xlabel('t [ms]') pylab.legend() pylab.show() sim.end()
def t4(): print 'Loading Forth XML File (iaf-2coba-Model)' print '----------------------------------------' component = readers.XMLReader.read_component(Join(tenml_dir, 'iaf_2coba.10ml'), component_name='iaf') writers.XMLWriter.write( component, '/tmp/nineml_toxml4.xml', ) model = readers.XMLReader.read_component(Join(tenml_dir, 'iaf_2coba.10ml')) from nineml.abstraction_layer.flattening import flatten from nineml.abstraction_layer.dynamics.utils.modifiers import ( DynamicsModifier) flatcomponent = flatten(model, componentname='iaf_2coba') DynamicsModifier.close_analog_port(component=flatcomponent, port_name='iaf_iSyn', value='0') writers.XMLWriter.write(flatcomponent, '/tmp/nineml_out_iaf_2coba.9ml') import pyNN.neuron as sim from pyNN.utility import init_logging init_logging(None, debug=True) sim.setup(timestep=0.1, min_delay=0.1) print 'Attempting to simulate From Model:' print '----------------------------------' celltype_cls = pyNNml.nineml_celltype_from_model( name="iaf_2coba", nineml_model=flatcomponent, synapse_components=[ pyNNml.CoBaSyn(namespace='cobaExcit', weight_connector='q'), pyNNml.CoBaSyn(namespace='cobaInhib', weight_connector='q'), ]) parameters = { 'iaf.cm': 1.0, 'iaf.gl': 50.0, 'iaf.taurefrac': 5.0, 'iaf.vrest': -65.0, 'iaf.vreset': -65.0, 'iaf.vthresh': -50.0, 'cobaExcit.tau': 2.0, 'cobaInhib.tau': 5.0, 'cobaExcit.vrev': 0.0, 'cobaInhib.vrev': -70.0, } parameters = ComponentFlattener.flatten_namespace_dict(parameters) cells = sim.Population(1, celltype_cls, parameters) cells.initialize('iaf_V', parameters['iaf_vrest']) cells.initialize('tspike', -1e99) # neuron not refractory at start cells.initialize('regime', 1002) # temporary hack input = sim.Population(2, sim.SpikeSourcePoisson, {'rate': 100}) connector = sim.OneToOneConnector(weights=1.0, delays=0.5) conn = [ sim.Projection(input[0:1], cells, connector, target='cobaExcit'), sim.Projection(input[1:2], cells, connector, target='cobaInhib') ] cells._record('iaf_V') cells._record('cobaExcit_g') cells._record('cobaInhib_g') cells._record('cobaExcit_I') cells._record('cobaInhib_I') cells.record() sim.run(100.0) cells.recorders['iaf_V'].write("Results/nineml_neuron.V", filter=[cells[0]]) cells.recorders['cobaExcit_g'].write("Results/nineml_neuron.g_exc", filter=[cells[0]]) cells.recorders['cobaInhib_g'].write("Results/nineml_neuron.g_inh", filter=[cells[0]]) cells.recorders['cobaExcit_I'].write("Results/nineml_neuron.g_exc", filter=[cells[0]]) cells.recorders['cobaInhib_I'].write("Results/nineml_neuron.g_inh", filter=[cells[0]]) t = cells.recorders['iaf_V'].get()[:, 1] v = cells.recorders['iaf_V'].get()[:, 2] gInh = cells.recorders['cobaInhib_g'].get()[:, 2] gExc = cells.recorders['cobaExcit_g'].get()[:, 2] IInh = cells.recorders['cobaInhib_I'].get()[:, 2] IExc = cells.recorders['cobaExcit_I'].get()[:, 2] import pylab pylab.subplot(311) pylab.ylabel('Voltage') pylab.plot(t, v) pylab.subplot(312) pylab.ylabel('Conductance') pylab.plot(t, gInh) pylab.plot(t, gExc) pylab.subplot(313) pylab.ylabel('Current') pylab.plot(t, IInh) pylab.plot(t, IExc) pylab.suptitle("From Tree-Model Pathway") pylab.show() sim.end()
def validate(): global direction global inspikes global outspikes global outspikes2 global outvolts global prj prj = [] for i in range(nneurons): for j in range(nout): prj.append(p.Projection(neurons[i], out[j], target="excitatory",method=p.AllToAllConnector())) prj[-1].setWeights(initweight) goodWeights = pickle.load(open("goodWeightsFile.pkl")) for i, pr in enumerate(prj): print goodWeights[i], pr pr.setWeights(goodWeights[i]) print "Validating..." # set inputs for ntrial in range(ntrials, ntrials+nindependents): for direction in dirs: print "Checking direction:", direction, ", trial:", ntrial+1 print "Reading data:" trainingset = [DATA[direction][nneuron][ntrial] for nneuron in range(nneurons)] trainingset = [trainingset[i][startstimulus < trainingset[i]] for i in range(nneurons)] trainingset = [trainingset[i][trainingset[i] < endstimulus] for i in range(nneurons)] #import pdb; pdb.set_trace() # run simulation p.reset() for o in out: o.record() o.record_v() for i, neuron in enumerate(neurons): neuron.set('spike_times', trainingset[i]) #neuron[nneuron].set('spike_times',arange(1,1901,100)) neuron.record() p.run(2000) outSpikeTimes = [[] for i in range(nout)] outvolts = [[] for i in range(nout)] ## plot spike trains #fig = figure() #hold(True) #ax = fig.add_subplot(1,1,1) #title("Direction "+str(direction)+", Trial "+str(ntrial+1)) for j, o in enumerate(out): spikes = list(o.getSpikes()[:,1]) #print j, spikes, len(spikes), type(spikes) outSpikeTimes[j] = spikes outvolts[j] = o.get_v() #print j, outSpikeTimes[j], len(outSpikeTimes[j]) #ax.plot(outSpikeTimes[j], [j]*len(outSpikeTimes[j]), 'b|', markersize = 20.) inspikes=[0 for i in range(nneurons)] outspikes=[0 for i in range(nout)] outspikes2=[] outvolts=[] for i,o in enumerate(out): outspikes[i] = o.get_spike_counts().values()[0] #outspikes2.append(o.getSpikes()) outvolts.append(o.get_v()) print "outspikes:", outspikes for i,neuron in enumerate(neurons): inspikes[i] = neurons[i].get_spike_counts().values()[0] #print inspikes[i] def check(): global direction global inspikes global outspikes global outspikes2 global outvolts print "Learning..." #----------------------------------------------------- def printWeights(): global direction global inspikes global outspikes global outspikes2 global outvolts global prj print "outspikes:", outspikes adjust=0.02 negadjust=0.02 nmax=inspikes.index(max(inspikes)) if (outspikes[0]<outspikes[1]) and (direction==dirs[1]): print 'correct 0' elif (outspikes[0]>outspikes[1]) and (direction==dirs[0]): print 'correct 3' elif (outspikes[0]>=outspikes[1]) and (direction==dirs[1]): print 'wrong 0' elif (outspikes[0]<=outspikes[1]) and (direction==dirs[0]): print 'wrong 3' else: print 'no 5' print printWeights() #----------------------------------------------------- for p in prj: currentWeight = p.getWeights()[0] print direction, ntrial, p, currentWeight check()
print "Reading data:" trainingset = [DATA[direction][nneuron][ntrial] for nneuron in range(nneurons)] trainingset = [trainingset[i][startstimulus < trainingset[i]] for i in range(nneurons)] trainingset = [trainingset[i][trainingset[i] < endstimulus] for i in range(nneurons)] # run simulation p.reset() for o in out: o.record() o.record_v() for i, neuron in enumerate(neurons): neuron.set('spike_times', trainingset[i]) #neuron[nneuron].set('spike_times',arange(1,1901,100)) neuron.record() p.run(2000) outSpikeTimes = [[] for i in range(nout)] outvolts = [[] for i in range(nout)] ## plot spike trains #fig = figure() #hold(True) #ax = fig.add_subplot(1,1,1) #title("Direction "+str(direction)+", Trial "+str(ntrial+1)) for j, o in enumerate(out): spikes = list(o.getSpikes()[:,1]) #print j, spikes, len(spikes), type(spikes) outSpikeTimes[j] = spikes outvolts[j] = o.get_v() print "--------------------------------" #print j, outSpikeTimes[j], len(outSpikeTimes[j])
def simulate(): global direction global inspikes global outspikes global outspikes2 global outvolts global prj print "Simulating..." # set inputs for ntrial in range(ntrials): for direction in dirs: print "Training direction:", direction, ", trial:", ntrial+1 print "Reading data:" trainingset = [DATA[direction][nneuron][ntrial] for nneuron in range(nneurons)] trainingset = [trainingset[i][startstimulus < trainingset[i]] for i in range(nneurons)] trainingset = [trainingset[i][trainingset[i] < endstimulus] for i in range(nneurons)] # run simulation p.reset() for o in out: o.record() o.record_v() for i, neuron in enumerate(neurons): neuron.set('spike_times', trainingset[i]) #neuron[nneuron].set('spike_times',arange(1,1901,100)) neuron.record() p.run(2000) outSpikeTimes = [[] for i in range(nout)] outvolts = [[] for i in range(nout)] ## plot spike trains #fig = figure() #hold(True) #ax = fig.add_subplot(1,1,1) #title("Direction "+str(direction)+", Trial "+str(ntrial+1)) for j, o in enumerate(out): spikes = list(o.getSpikes()[:,1]) #print j, spikes, len(spikes), type(spikes) outSpikeTimes[j] = spikes outvolts[j] = o.get_v() print "--------------------------------" #print j, outSpikeTimes[j], len(outSpikeTimes[j]) #ax.plot(outSpikeTimes[j], [j]*len(outSpikeTimes[j]), 'b|', markersize = 20.) inspikes=[0 for i in range(nneurons)] outspikes=[0 for i in range(nout)] outspikes2=[] outvolts=[] for i,o in enumerate(out): outspikes[i] = o.get_spike_counts().values()[0] #outspikes2.append(o.getSpikes()) outvolts.append(o.get_v()) for i,neuron in enumerate(neurons): inspikes[i] = neurons[i].get_spike_counts().values()[0] #print inspikes[i] def learn(): global direction global inspikes global outspikes global outspikes2 global outvolts print "Learning..." #----------------------------------------------------- def updateWeights(): global direction global inspikes global outspikes global outspikes2 global outvolts global prj print "outspikes:", outspikes print "Updating..." adjust=0.02 negadjust=0.02 nmax=inspikes.index(max(inspikes)) if (outspikes[0]<outspikes[1]) and (direction==dirs[1]): prj[2*nmax+1].setWeights(prj[2*nmax+1].getWeights()[0]+adjust) print 'correct 0' print "Updated to:", prj[2*nmax+1].getWeights() elif (outspikes[0]>outspikes[1]) and (direction==dirs[0]): prj[2*nmax+0].setWeights(prj[2*nmax+0].getWeights()[0]+adjust) print 'correct 3' print "Updated to:", prj[2*nmax+0].getWeights() elif (outspikes[0]>=outspikes[1]) and (direction==dirs[1]): print 'wrong 0' prj[2*nmax+0].setWeights(max(0,prj[2*nmax+0].getWeights()[0]-negadjust)) print "Updated to:", prj[2*nmax+0].getWeights() elif (outspikes[0]<=outspikes[1]) and (direction==dirs[0]): prj[2*nmax+1].setWeights(max(0,prj[2*nmax+1].getWeights()[0]-negadjust)) print 'wrong 3' print "Updated to:", prj[2*nmax+1].getWeights() else: print 'no 5' print updateWeights() #----------------------------------------------------- for p in prj: currentWeight = p.getWeights()[0] print direction, ntrial, p, currentWeight learn() goodWeights = [pr.getWeights() for i, pr in enumerate(prj)] print "goodWeights:", goodWeights pickle.dump(goodWeights, open("goodWeightsFile.pkl", "wb"))
return gen() assert generate_spike_times(0).max() > simtime spike_source = sim.Population(n, sim.SpikeSourceArray(spike_times=generate_spike_times)) spike_source.record('spikes') cells.record('spikes') cells[0:2].record('m') syn = sim.StaticSynapse(weight=w, delay=syn_delay) input_conns = sim.Projection(spike_source, cells, sim.FixedProbabilityConnector(0.5), syn, receptor_type="default") # === Run simulation =========================================================== sim.run(simtime) filename = normalized_filename("Results", "small_network", "pkl", "neuron", sim.num_processes()) cells.write_data(filename, annotations={'script_name': __file__}) print("Mean firing rate: ", cells.mean_spike_count() * 1000.0 / simtime, "Hz") plot_figure = True if plot_figure: from pyNN.utility.plotting import Figure, Panel figure_filename = filename.replace("pkl", "png") data = cells.get_data().segments[0] m = data.filter(name="m")[0] Figure( Panel(m, ylabel="Membrane potential (dimensionless)", yticks=True, ylim=(0,1)),
from pyNN import neuron as p #p.setup(1.0) p.setup(timestep=1.0, min_delay=1.0) #cell_params = {'cm': 0.25, 'tau_m': 10.0, 'tau_refrac': 2.0, 'tau_syn_E': 2.5, 'tau_syn_I': 2.5, 'v_reset': -70.0, 'v_rest': -65.0, 'v_thresh': -55.0 } #cell_params = {'a':0.1779222, 'b':-5e-09, 'c':-59.52801, 'd':0.1531787, v_init=-'73.32355','i_offset':0}#, u_init, i_offset} #pop = p.Population(NETSIZE, p.IF_curr_exp(i_offset=0)) neuron_type = p.Izhikevich() #cell_params) pop = p.Population(NETSIZE, neuron_type) #for ind in pop: print(p.connect) pop.record("spikes") p.run(100) pop.set(i_offset=1.0) p.run(100) pop.set(i_offset=0.0) p.run(100) spikes = pop.get_data("spikes") p.end() #p.setup(1.0) #pop = sim.Population(100, sim.IZKCurrExp(cell_params)) print(spikes) # In[ ]: #nldf['From']
def sim_runner(wgf): wg = wgf import pyNN.neuron as sim nproc = sim.num_processes() node = sim.rank() print(nproc) import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import matplotlib as mpl mpl.rcParams.update({'font.size':16}) #import mpi4py #threads = sim.rank() threads = 1 rngseed = 98765 parallel_safe = False #extra = {'threads' : threads} import os import pandas as pd import sys import numpy as np from pyNN.neuron import STDPMechanism import copy from pyNN.random import RandomDistribution, NumpyRNG import pyNN.neuron as neuron from pyNN.neuron import h from pyNN.neuron import StandardCellType, ParameterSpace from pyNN.random import RandomDistribution, NumpyRNG from pyNN.neuron import STDPMechanism, SpikePairRule, AdditiveWeightDependence, FromListConnector, TsodyksMarkramSynapse from pyNN.neuron import Projection, OneToOneConnector from numpy import arange import pyNN from pyNN.utility import get_simulator, init_logging, normalized_filename import random import socket #from neuronunit.optimization import get_neab import networkx as nx sim = pyNN.neuron # Get some hippocampus connectivity data, based on a conversation with # academic researchers on GH: # https://github.com/Hippocampome-Org/GraphTheory/issues?q=is%3Aissue+is%3Aclosed # scrape hippocamome connectivity data, that I intend to use to program neuromorphic hardware. # conditionally get files if they don't exist. path_xl = '_hybrid_connectivity_matrix_20171103_092033.xlsx' if not os.path.exists(path_xl): os.system('wget https://github.com/Hippocampome-Org/GraphTheory/files/1657258/_hybrid_connectivity_matrix_20171103_092033.xlsx') xl = pd.ExcelFile(path_xl) dfEE = xl.parse() dfEE.loc[0].keys() dfm = dfEE.as_matrix() rcls = dfm[:,:1] # real cell labels. rcls = rcls[1:] rcls = { k:v for k,v in enumerate(rcls) } # real cell labels, cast to dictionary import pickle with open('cell_names.p','wb') as f: pickle.dump(rcls,f) import pandas as pd pd.DataFrame(rcls).to_csv('cell_names.csv', index=False) filtered = dfm[:,3:] filtered = filtered[1:] rng = NumpyRNG(seed=64754) delay_distr = RandomDistribution('normal', [2, 1e-1], rng=rng) weight_distr = RandomDistribution('normal', [45, 1e-1], rng=rng) sanity_e = [] sanity_i = [] EElist = [] IIlist = [] EIlist = [] IElist = [] for i,j in enumerate(filtered): for k,xaxis in enumerate(j): if xaxis == 1 or xaxis == 2: source = i sanity_e.append(i) target = k if xaxis ==-1 or xaxis == -2: sanity_i.append(i) source = i target = k index_exc = list(set(sanity_e)) index_inh = list(set(sanity_i)) import pickle with open('cell_indexs.p','wb') as f: returned_list = [index_exc, index_inh] pickle.dump(returned_list,f) import numpy a = numpy.asarray(index_exc) numpy.savetxt('pickles/'+str(k)+'excitatory_nunber_labels.csv', a, delimiter=",") import numpy a = numpy.asarray(index_inh) numpy.savetxt('pickles/'+str(k)+'inhibitory_nunber_labels.csv', a, delimiter=",") for i,j in enumerate(filtered): for k,xaxis in enumerate(j): if xaxis==1 or xaxis == 2: source = i sanity_e.append(i) target = k delay = delay_distr.next() weight = 1.0 if target in index_inh: EIlist.append((source,target,delay,weight)) else: EElist.append((source,target,delay,weight)) if xaxis==-1 or xaxis == -2: sanity_i.append(i) source = i target = k delay = delay_distr.next() weight = 1.0 if target in index_exc: IElist.append((source,target,delay,weight)) else: IIlist.append((source,target,delay,weight)) internal_conn_ee = sim.FromListConnector(EElist) ee = internal_conn_ee.conn_list ee_srcs = ee[:,0] ee_tgs = ee[:,1] internal_conn_ie = sim.FromListConnector(IElist) ie = internal_conn_ie.conn_list ie_srcs = set([ int(e[0]) for e in ie ]) ie_tgs = set([ int(e[1]) for e in ie ]) internal_conn_ei = sim.FromListConnector(EIlist) ei = internal_conn_ei.conn_list ei_srcs = set([ int(e[0]) for e in ei ]) ei_tgs = set([ int(e[1]) for e in ei ]) internal_conn_ii = sim.FromListConnector(IIlist) ii = internal_conn_ii.conn_list ii_srcs = set([ int(e[0]) for e in ii ]) ii_tgs = set([ int(e[1]) for e in ii ]) for e in internal_conn_ee.conn_list: assert e[0] in ee_srcs assert e[1] in ee_tgs for i in internal_conn_ii.conn_list: assert i[0] in ii_srcs assert i[1] in ii_tgs ml = len(filtered[1])+1 pre_exc = [] post_exc = [] pre_inh = [] post_inh = [] rng = NumpyRNG(seed=64754) delay_distr = RandomDistribution('normal', [2, 1e-1], rng=rng) plot_EE = np.zeros(shape=(ml,ml), dtype=bool) plot_II = np.zeros(shape=(ml,ml), dtype=bool) plot_EI = np.zeros(shape=(ml,ml), dtype=bool) plot_IE = np.zeros(shape=(ml,ml), dtype=bool) for i in EElist: plot_EE[i[0],i[1]] = int(0) #plot_ss[i[0],i[1]] = int(1) if i[0]!=i[1]: # exclude self connections plot_EE[i[0],i[1]] = int(1) pre_exc.append(i[0]) post_exc.append(i[1]) assert len(pre_exc) == len(post_exc) for i in IIlist: plot_II[i[0],i[1]] = int(0) if i[0]!=i[1]: plot_II[i[0],i[1]] = int(1) pre_inh.append(i[0]) post_inh.append(i[1]) for i in IElist: plot_IE[i[0],i[1]] = int(0) if i[0]!=i[1]: # exclude self connections plot_IE[i[0],i[1]] = int(1) pre_inh.append(i[0]) post_inh.append(i[1]) for i in EIlist: plot_EI[i[0],i[1]] = int(0) if i[0]!=i[1]: plot_EI[i[0],i[1]] = int(1) pre_exc.append(i[0]) post_exc.append(i[1]) plot_excit = plot_EI + plot_EE plot_inhib = plot_IE + plot_II assert len(pre_inh) == len(post_inh) num_exc = [ i for i,e in enumerate(plot_excit) if sum(e) > 0 ] num_inh = [ y for y,i in enumerate(plot_inhib) if sum(i) > 0 ] # the network is dominated by inhibitory neurons, which is unusual for modellers. assert num_inh > num_exc assert np.sum(plot_inhib) > np.sum(plot_excit) assert len(num_exc) < ml assert len(num_inh) < ml # # Plot all the Projection pairs as a connection matrix (Excitatory and Inhibitory Connections) import pickle with open('graph_inhib.p','wb') as f: pickle.dump(plot_inhib,f, protocol=2) import pickle with open('graph_excit.p','wb') as f: pickle.dump(plot_excit,f, protocol=2) #with open('cell_names.p','wb') as f: # pickle.dump(rcls,f) import pandas as pd pd.DataFrame(plot_EE).to_csv('ee.csv', index=False) import pandas as pd pd.DataFrame(plot_IE).to_csv('ie.csv', index=False) import pandas as pd pd.DataFrame(plot_II).to_csv('ii.csv', index=False) import pandas as pd pd.DataFrame(plot_EI).to_csv('ei.csv', index=False) from scipy.sparse import coo_matrix m = np.matrix(filtered[1:]) bool_matrix = np.add(plot_excit,plot_inhib) with open('bool_matrix.p','wb') as f: pickle.dump(bool_matrix,f, protocol=2) if not isinstance(m, coo_matrix): m = coo_matrix(m) Gexc_ud = nx.Graph(plot_excit) avg_clustering = nx.average_clustering(Gexc_ud)#, nodes=None, weight=None, count_zeros=True)[source] rc = nx.rich_club_coefficient(Gexc_ud,normalized=False) print('This graph structure as rich as: ',rc[0]) gexc = nx.DiGraph(plot_excit) gexcc = nx.betweenness_centrality(gexc) top_exc = sorted(([ (v,k) for k, v in dict(gexcc).items() ]), reverse=True) in_degree = gexc.in_degree() top_in = sorted(([ (v,k) for k, v in in_degree.items() ])) in_hub = top_in[-1][1] out_degree = gexc.out_degree() top_out = sorted(([ (v,k) for k, v in out_degree.items() ])) out_hub = top_out[-1][1] mean_out = np.mean(list(out_degree.values())) mean_in = np.mean(list(in_degree.values())) mean_conns = int(mean_in + mean_out/2) k = 2 # number of neighbouig nodes to wire. p = 0.25 # probability of instead wiring to a random long range destination. ne = len(plot_excit)# size of small world network small_world_ring_excit = nx.watts_strogatz_graph(ne,mean_conns,0.25) k = 2 # number of neighbouring nodes to wire. p = 0.25 # probability of instead wiring to a random long range destination. ni = len(plot_inhib)# size of small world network small_world_ring_inhib = nx.watts_strogatz_graph(ni,mean_conns,0.25) nproc = sim.num_processes() nproc = 8 host_name = socket.gethostname() node_id = sim.setup(timestep=0.01, min_delay=1.0)#, **extra) print("Host #%d is on %s" % (node_id + 1, host_name)) rng = NumpyRNG(seed=64754) #pop_size = len(num_exc)+len(num_inh) #num_exc = [ i for i,e in enumerate(plot_excit) if sum(e) > 0 ] #num_inh = [ y for y,i in enumerate(plot_inhib) if sum(i) > 0 ] #pop_exc = sim.Population(len(num_exc), sim.Izhikevich(a=0.02, b=0.2, c=-65, d=8, i_offset=0)) #pop_inh = sim.Population(len(num_inh), sim.Izhikevich(a=0.02, b=0.25, c=-65, d=2, i_offset=0)) #index_exc = list(set(sanity_e)) #index_inh = list(set(sanity_i)) all_cells = sim.Population(len(index_exc)+len(index_inh), sim.Izhikevich(a=0.02, b=0.2, c=-65, d=8, i_offset=0)) #all_cells = None #all_cells = pop_exc + pop_inh pop_exc = sim.PopulationView(all_cells,index_exc) pop_inh = sim.PopulationView(all_cells,index_inh) #print(pop_exc) #print(dir(pop_exc)) for pe in pop_exc: print(pe) #import pdb pe = all_cells[pe] #pdb.set_trace() #pe = all_cells[i] r = random.uniform(0.0, 1.0) pe.set_parameters(a=0.02, b=0.2, c=-65+15*r, d=8-r**2, i_offset=0) #pop_exc.append(pe) #pop_exc = sim.Population(pop_exc) for pi in index_inh: pi = all_cells[pi] #print(pi) #pi = all_cells[i] r = random.uniform(0.0, 1.0) pi.set_parameters(a=0.02+0.08*r, b=0.25-0.05*r, c=-65, d= 2, i_offset=0) #pop_inh.append(pi) #pop_inh = sim.Population(pop_inh) ''' for pe in pop_exc: r = random.uniform(0.0, 1.0) pe.set_parameters(a=0.02, b=0.2, c=-65+15*r, d=8-r**2, i_offset=0) for pi in pop_inh: r = random.uniform(0.0, 1.0) pi.set_parameters(a=0.02+0.08*r, b=0.25-0.05*r, c=-65, d= 2, i_offset=0) ''' NEXC = len(num_exc) NINH = len(num_inh) exc_syn = sim.StaticSynapse(weight = wg, delay=delay_distr) assert np.any(internal_conn_ee.conn_list[:,0]) < ee_srcs.size prj_exc_exc = sim.Projection(all_cells, all_cells, internal_conn_ee, exc_syn, receptor_type='excitatory') prj_exc_inh = sim.Projection(all_cells, all_cells, internal_conn_ei, exc_syn, receptor_type='excitatory') inh_syn = sim.StaticSynapse(weight = wg, delay=delay_distr) delay_distr = RandomDistribution('normal', [1, 100e-3], rng=rng) prj_inh_inh = sim.Projection(all_cells, all_cells, internal_conn_ii, inh_syn, receptor_type='inhibitory') prj_inh_exc = sim.Projection(all_cells, all_cells, internal_conn_ie, inh_syn, receptor_type='inhibitory') inh_distr = RandomDistribution('normal', [1, 2.1e-3], rng=rng) def prj_change(prj,wg): prj.setWeights(wg) prj_change(prj_exc_exc,wg) prj_change(prj_exc_inh,wg) prj_change(prj_inh_exc,wg) prj_change(prj_inh_inh,wg) def prj_check(prj): for w in prj.weightHistogram(): for i in w: print(i) prj_check(prj_exc_exc) prj_check(prj_exc_inh) prj_check(prj_inh_exc) prj_check(prj_inh_inh) #print(rheobase['value']) #print(float(rheobase['value']),1.25/1000.0) '''Old values that worked noise = sim.NoisyCurrentSource(mean=0.85/1000.0, stdev=5.00/1000.0, start=0.0, stop=2000.0, dt=1.0) pop_exc.inject(noise) #1000.0 pA noise = sim.NoisyCurrentSource(mean=1.740/1000.0, stdev=5.00/1000.0, start=0.0, stop=2000.0, dt=1.0) pop_inh.inject(noise) #1750.0 pA ''' noise = sim.NoisyCurrentSource(mean=0.74/1000.0, stdev=4.00/1000.0, start=0.0, stop=2000.0, dt=1.0) pop_exc.inject(noise) #1000.0 pA noise = sim.NoisyCurrentSource(mean=1.440/1000.0, stdev=4.00/1000.0, start=0.0, stop=2000.0, dt=1.0) pop_inh.inject(noise) ## # Setup and run a simulation. Note there is no current injection into the neuron. # All cells in the network are in a quiescent state, so its not a surprise that xthere are no spikes ## sim = pyNN.neuron arange = np.arange import re all_cells.record(['v','spikes']) # , 'u']) all_cells.initialize(v=-65.0, u=-14.0) # === Run the simulation ===================================================== tstop = 2000.0 sim.run(tstop) data = None data = all_cells.get_data().segments[0] #print(len(data.analogsignals[0].times)) with open('pickles/qi'+str(wg)+'.p', 'wb') as f: pickle.dump(data,f) # make data none or else it will grow in a loop all_cells = None data = None noise = None
exc = net.populations["Exc"] exc.sample(50).record("spikes") exc.sample(3).record(["nrn_v", "syn_a"]) inh = net.populations["Inh"] inh.sample(50).record("spikes") inh.sample(3).record(["nrn_v", "syn_a"]) else: all_neurons = net.assemblies["All"] # all.sample(50).record("spikes") all_neurons.record("spikes") print("Running simulation") t_stop = args.limits[1] pb = SimulationProgressBar(t_stop / 80, t_stop) sim.run(t_stop, callbacks=[pb]) print("Handling data") if args.plot: stim_data = stim.get_data().segments[0] exc_data = exc.get_data().segments[0] inh_data = inh.get_data().segments[0] else: all_neurons.write_data("brunel_network_alpha_%s.h5" % args.case) sim.end() def instantaneous_firing_rate(segment, begin, end): """Computed in bins of 0.1 ms """ bins = np.arange(begin, end, 0.1)
nineml_cell_type('Poisson', read("../sources/Poisson.xml")['Poisson'], {})( rate=[0.5*nu_thresh, nu_thresh, 2*nu_thresh, 0.0])) prj1 = sim.Projection(stim, p1, sim.OneToOneConnector(), sim.StaticSynapse(weight=w_eff, delay=delay), receptor_type='syn') prj2 = sim.Projection(stim, p2, sim.OneToOneConnector(), sim.StaticSynapse(weight=w_eff, delay=delay), receptor_type='syn') p1.record(['nrn_v', 'syn_a', 'syn_b']) p2.record(['nrn_v', 'syn_a', 'syn_b']) sim.run(t_stop) v_m1 = p1.get_data().segments[0].filter(name='nrn_v')[0] v_m2 = p2.get_data().segments[0].filter(name='nrn_v')[0] # NEST simulation nest.ResetKernel() nest.SetKernelStatus({"resolution": dt, "print_time": True, 'local_num_threads': 1}) neuron_params = {"C_m": 1000*cell_parameters["nrn_tau"]/cell_parameters["nrn_R"], "tau_m": cell_parameters["nrn_tau"], "tau_syn_ex": cell_parameters["syn_tau"], "tau_syn_in": cell_parameters["syn_tau"],
def run(plot_and_show=True): import sys from os.path import abspath, realpath, join import numpy import nineml root = abspath(join(realpath(nineml.__path__[0]), "../../..")) sys.path.append(join(root, "lib9ml/python/examples/AL")) sys.path.append(join(root, "code_generation/nmodl")) sys.path.append(join(root, "code_generation/nest2")) #from nineml.abstraction_layer.example_models import get_hierachical_iaf_3coba from nineml.abstraction_layer.testing_utils import TestableComponent from nineml.abstraction_layer.flattening import ComponentFlattener import pyNN.neuron as sim import pyNN.neuron.nineml as pyNNml from pyNN.utility import init_logging init_logging(None, debug=True) sim.setup(timestep=0.1, min_delay=0.1) #test_component = get_hierachical_iaf_3coba() test_component = TestableComponent('hierachical_iaf_3coba')() from nineml.abstraction_layer.writers import DotWriter DotWriter.write(test_component, 'test1.dot') from nineml.abstraction_layer.writers import XMLWriter XMLWriter.write(test_component, 'iaf_3coba.xml') celltype_cls = pyNNml.nineml_celltype_from_model( name = "iaf_3coba", nineml_model = test_component, synapse_components = [ pyNNml.CoBaSyn( namespace='AMPA', weight_connector='q' ), pyNNml.CoBaSyn( namespace='GABAa', weight_connector='q' ), pyNNml.CoBaSyn( namespace='GABAb', weight_connector='q' ), ] ) parameters = { 'iaf.cm': 1.0, 'iaf.gl': 50.0, 'iaf.taurefrac': 5.0, 'iaf.vrest': -65.0, 'iaf.vreset': -65.0, 'iaf.vthresh': -50.0, 'AMPA.tau': 2.0, 'GABAa.tau': 5.0, 'GABAb.tau': 50.0, 'AMPA.vrev': 0.0, 'GABAa.vrev': -70.0, 'GABAb.vrev': -95.0, } parameters = ComponentFlattener.flatten_namespace_dict( parameters ) cells = sim.Population(1, celltype_cls, parameters) cells.initialize('iaf_V', parameters['iaf_vrest']) cells.initialize('tspike', -1e99) # neuron not refractory at start cells.initialize('regime', 1002) # temporary hack 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'), sim.Projection(input[1:2], cells, connector, target='GABAa'), sim.Projection(input[2:3], cells, connector, target='GABAb')] cells._record('iaf_V') cells._record('AMPA_g') cells._record('GABAa_g') cells._record('GABAb_g') cells.record() sim.run(100.0) cells.recorders['iaf_V'].write("Results/nineml_neuron.V", filter=[cells[0]]) cells.recorders['AMPA_g'].write("Results/nineml_neuron.g_exc", filter=[cells[0]]) cells.recorders['GABAa_g'].write("Results/nineml_neuron.g_gabaA", filter=[cells[0]]) cells.recorders['GABAb_g'].write("Results/nineml_neuron.g_gagaB", filter=[cells[0]]) t = cells.recorders['iaf_V'].get()[:,1] v = cells.recorders['iaf_V'].get()[:,2] gInhA = cells.recorders['GABAa_g'].get()[:,2] gInhB = cells.recorders['GABAb_g'].get()[:,2] gExc = cells.recorders['AMPA_g'].get()[:,2] if plot_and_show: import pylab pylab.subplot(211) pylab.plot(t,v) pylab.ylabel('voltage [mV]') pylab.suptitle("AMPA, GABA_A, GABA_B") pylab.subplot(212) pylab.plot(t,gInhA,label='GABA_A') pylab.plot(t,gInhB, label='GABA_B') pylab.plot(t,gExc, label='AMPA') pylab.ylabel('conductance [nS]') pylab.xlabel('t [ms]') pylab.legend() pylab.show() sim.end()
""" """ from plot_helper import plot_current_source import pyNN.neuron as sim sim.setup() population = sim.Population(30, sim.IF_cond_exp(tau_m=10.0)) population[0:1].record_v() noise = sim.NoisyCurrentSource(mean=1.5, stdev=1.0, start=50.0, stop=450.0, dt=1.0) population.inject(noise) noise._record() sim.run(500.0) t, i_inj = noise._get_data() v = population.get_data().segments[0].analogsignals[0] plot_current_source(t, i_inj, v, v_range=(-66, -48), v_ticks=(-65, -60, -55, -50), i_range=(-3, 5), i_ticks=range(-2, 6, 2), t_range=(0, 500))
def std_pynn_simulation(test_component, parameters, initial_values, synapse_components, records, plot=True, sim_time=100., synapse_weights=1.0, syn_input_rate=100): from nineml.abstraction_layer.flattening import ComponentFlattener import pyNN.neuron as sim import pyNN.neuron.nineml as pyNNml from pyNN.neuron.nineml import CoBaSyn from pyNN.utility import init_logging init_logging(None, debug=True) sim.setup(timestep=0.01, min_delay=0.1) synapse_components_ML = [CoBaSyn(namespace=ns, weight_connector=wc) for (ns, wc) in synapse_components] celltype_cls = pyNNml.nineml_celltype_from_model( name=test_component.name, nineml_model=test_component, synapse_components=synapse_components_ML, ) parameters = ComponentFlattener.flatten_namespace_dict(parameters) initial_values = ComponentFlattener.flatten_namespace_dict(initial_values) cells = sim.Population(1, celltype_cls, parameters) # Set Initial Values: for state, state_initial_value in initial_values.iteritems(): cells.initialize(state, state_initial_value) # For each synapse type, create a spike source: if synapse_components: input = sim.Population( len(synapse_components), sim.SpikeSourcePoisson, {'rate': syn_input_rate}) connector = sim.OneToOneConnector(weights=synapse_weights, delays=0.5) conn = [] for i, (ns, weight_connector) in enumerate(synapse_components): proj = sim.Projection(input[i:i + 1], cells, connector, target=ns), conn.append(proj) # Setup the Records: for record in records: cells.record(record.what) cells.record('spikes') # Run the simulation: sim.run(sim_time) if len(records) == 0: assert False # Write the Results to a file: cells.write_data("Results/nineml.pkl") # Plot the values: results = cells.get_data().segments[0] # Create a list of the tags: tags = [] for record in records: if not record.tag in tags: tags.append(record.tag) # Plot the graphs: if plot: import pylab nGraphs = len(tags) # Plot the Records: for graphIndex, tag in enumerate(tags): pylab.subplot(nGraphs, 1, graphIndex + 1) for r in records: if r.tag != tag: continue trace = results.filter(name=r.what)[0] pylab.plot(trace.times, trace, label=r.label) pylab.ylabel(tag) pylab.legend() # Plot the spikes: # pylab.subplot(nGraphs,1, len(tags)+1) # t_spikes = cells[0:1].getSpikes()[:1] # pylab.plot( [1,3],[1,3],'x' ) # print t_spikes # if t_spikes: # pylab.scatter( t_spikes, t_spikes ) # Add the X axis to the last plot: pylab.xlabel('t [ms]') # pylab.suptitle("From Tree-Model Pathway") pylab.show() sim.end() return results
import pyNN.neuron as sim # can of course replace `nest` with `neuron`, `brian`, etc. import matplotlib.pyplot as plt from quantities import nA sim.setup() cell = sim.Population(1, sim.HH_cond_exp()) step_current = sim.DCSource(start=20.0, stop=80.0) step_current.inject_into(cell) cell.record('v') for amp in (-0.2, -0.1, 0.0, 0.1, 0.2): step_current.amplitude = amp sim.run(100.0) sim.reset(annotations={"amplitude": amp * nA}) data = cell.get_data() sim.end() for segment in data.segments: vm = segment.analogsignals[0] plt.plot(vm.times, vm, label=str(segment.annotations["amplitude"])) plt.legend(loc="upper left") plt.xlabel("Time (%s)" % vm.times.units._dimensionality) plt.ylabel("Membrane potential (%s)" % vm.units._dimensionality) plt.show()
exc = net.populations["Exc"] exc.sample(50).record("spikes") exc.sample(3).record(["nrn_V", "syn_A"]) inh = net.populations["Inh"] inh.sample(50).record("spikes") inh.sample(3).record(["nrn_V", "syn_A"]) else: all = net.assemblies["All neurons"] #all.sample(50).record("spikes") all.record("spikes") print("Running simulation") t_stop = plot_limits[1] pb = SimulationProgressBar(t_stop / 80, t_stop) sim.run(t_stop, callbacks=[pb]) print("Handling data") if plot_figure: stim_data = stim.get_data().segments[0] exc_data = exc.get_data().segments[0] inh_data = inh.get_data().segments[0] else: all.write_data("brunel_network_alpha_%s.h5" % case) sim.end() def instantaneous_firing_rate(segment, begin, end): """Computed in bins of 0.1 ms """ bins = np.arange(begin, end, 0.1)