def plotGraphOfMembranePotential(network=None): assert network is not None, "Network is not initialised." from pyNN.utility import normalized_filename filename = normalized_filename("Results", "cell_type_demonstration", "pkl", "nest") cells = network.get_population("Cell Output Population of Network") inhL = network.get_population("Inhibitory Population of Left Retina") inhR = network.get_population("Inhibitory Population of Right Retina") from pyNN.utility.plotting import Figure, Panel figure_filename = filename.replace("pkl", "png") Figure( Panel(cells.get_data().segments[0].filter(name='v')[0], ylabel="Membrane potential (mV)", xlabel="Time (ms)", data_labels=[cells.label], yticks=True, xticks=True, ylim=(-110, -40)), Panel(inhL.get_data().segments[0].filter(name='v')[0], ylabel="Membrane potential (mV)", xlabel="Time (ms)", data_labels=[inhL.label], yticks=True, xticks=True, ylim=(-110, -40)), Panel(inhR.get_data().segments[0].filter(name='v')[0], ylabel="Membrane potential (mV)", xlabel="Time (ms)", data_labels=[inhR.label], yticks=True, xticks=True, ylim=(-110, -40)), title="Cooperative Network" ).save(figure_filename) print "Graph is saved under the name: {0}".format(figure_filename)
# === Print the synaptic weight matrices ===================================== weights_python = projection_python.get("weight", format="array") weights_native = projection_native.get("weight", format="array") print(weights_python) print(weights_native) # === Run the simulation ===================================================== sim.run(100.0) sim.end() # === Optionally, plot the synaptic weight matrices ========================== if options.plot_figure: from pyNN.utility import normalized_filename from pyNN.utility.plotting import Figure, Panel filename = normalized_filename("Results", "random_numbers", "png", options.simulator) # where there is no connection, the weight matrix contains NaN # for plotting purposes, we replace NaN with zero. weights_python[numpy.isnan(weights_python)] = 0 weights_native[numpy.isnan(weights_native)] = 0 Figure( Panel(weights_python, cmap='gray_r', xlabel="Python RNG"), Panel(weights_native, cmap='gray_r', xlabel="Native RNG"), annotations="Simulated with %s" % options.simulator.upper() ).save(filename) print(filename)
""" Simple test of injecting time-varying current into a cell Andrew Davison, UNIC, CNRS May 2009 $Id$ """ from pyNN.utility import get_script_args, normalized_filename simulator_name = get_script_args(1)[0] exec("from pyNN.%s import *" % simulator_name) setup() cell = create(IF_curr_exp(v_thresh=-55.0, tau_refrac=5.0)) current_source = StepCurrentSource(times=[50.0, 110.0, 150.0, 210.0], amplitudes=[0.4, 0.6, -0.2, 0.2]) cell.inject(current_source) filename = normalized_filename("Results", "StepCurrentSource", "pkl", simulator_name) record('v', cell, filename, annotations={'script_name': __file__}) run(250.0) end()
MyProgressBar(10.0, 1000.0), SetRate(p, rate_generator, interval) ]) # === Retrieve recorded data, and count the spikes in each interval ========== data = p.get_data().segments[0] all_spikes = np.hstack([st.magnitude for st in data.spiketrains]) spike_counts = [((all_spikes >= x) & (all_spikes < x + interval)).sum() for x in range(0, 1000, interval)] expected_spike_counts = [ p.size * rate * interval / 1000.0 for rate in range(0, 100, rate_increment) ] print("\nActual spike counts: {}".format(spike_counts)) print("Expected mean spike counts: {}".format(expected_spike_counts)) if options.plot_figure: Figure(Panel(data.spiketrains, xlabel="Time (ms)", xticks=True, markersize=0.5), title="Incrementally updated SpikeSourceArrays", annotations="Simulated with %s" % options.simulator.upper()).save( normalized_filename("Results", "update_spike_source_array", "png", options.simulator)) sim.end()
projections[label] = sim.Projection(spike_source, populations[label], connector, receptor_type='inhibitory', synapse_type=synapse_types[label]) spike_source.record('spikes') # === Run the simulation ===================================================== sim.run(400.0) # === Save the results, optionally plot a figure ============================= for label, p in populations.items(): filename = normalized_filename("Results", "stochastic_tsodyksmarkram_%s" % label, "pkl", options.simulator) p.write_data(filename, annotations={'script_name': __file__}) if options.plot_figure: from pyNN.utility.plotting import Figure, Panel #figure_filename = normalized_filename("Results", "stochastic_tsodyksmarkram", # "png", options.simulator) figure_filename = "Results/stochastic_tsodyksmarkram_{}.png".format(options.simulator) panels = [] for variable in ('gsyn_inh',): # 'v'): for population in sorted(populations.values(), key=lambda p: p.label): panels.append( Panel(population.get_data().segments[0].filter(name=variable)[0], data_labels=[population.label], yticks=True), )
# === Run simulation =========================================================== print "%d Running simulation..." % node_id sim.run(tstop) simCPUTime = timer.diff() E_count = exc_cells.mean_spike_count() I_count = inh_cells.mean_spike_count() # === Print results to file ==================================================== print "%d Writing data to file..." % node_id exc_cells.write_data(normalized_filename( "Results", "VAbenchmarks_%s_exc" % options.benchmark, "pkl", options.simulator, np), annotations={'script_name': __file__}) inh_cells.write_data(normalized_filename( "Results", "VAbenchmarks_%s_inh" % options.benchmark, "pkl", options.simulator, np), annotations={'script_name': __file__}) writeCPUTime = timer.diff() connections = "%d e→e %d e→i %d i→e %d i→i" % ( connections['e2e'].size(), connections['e2i'].size(), connections['i2e'].size(), connections['i2i'].size()) if node_id == 0: print "\n--- Vogels-Abbott Network Simulation ---" print "Nodes : %d" % np
for pixel in range(0, dimensionRetinaX): for disp in range(disparityMin, disparityMax+1): # connect each pixel with as many cells on the same row as disparity values allow. Weight and delay are set to 1 and 0 respectively. indexInNetworkLayer = pixel*dimensionRetinaX + pixel - disp*dimensionRetinaX if indexInNetworkLayer < 0: break connectionPaternRetinaRight.append((pixel, indexInNetworkLayer, 0.189, 0.2)) print connectionPaternRetinaRight connectionRetinaLeft = Projection(retinaLeft, oneNeuralLayer, FromListConnector(connectionPaternRetinaLeft), StaticSynapse(), receptor_type='excitatory') connectionRetinaRight = Projection(retinaRight, oneNeuralLayer, FromListConnector(connectionPaternRetinaRight), StaticSynapse(), receptor_type='excitatory') run(200.0) # plot results filename = normalized_filename("Results", "cell_type_demonstration", "pkl", "nest") oneNeuralLayer.write_data(filename, annotations={'script_name': __file__}) retinaLeft.write_data(filename, annotations={'script_name': __file__}) retinaRight.write_data(filename, annotations={'script_name': __file__}) cellActivity = oneNeuralLayer.get_data().segments[0] retinaLeftActivity = retinaLeft.get_data().segments[0] retinaRightActivity = retinaRight.get_data().segments[0] # from pyNN.utility.plotting import Figure, Panel # figure_filename = filename.replace("pkl", "png") # Figure(Panel(cellActivity.spiketrains, xlabel="Time (ms)", xticks=True, yticks=True), # Panel(cellActivity.filter(name='v')[0], ylabel="Membrane potential (mV)", yticks=True, ylim=(-66, -48)), # Panel(retinaLeftActivity.spiketrains, xlabel="Time (ms)", xticks=True, yticks=True), # Panel(retinaRightActivity.spiketrains, xlabel="Time (ms)", xticks=True, yticks=True), # title="Simple CoNet", annotations="Simulated with NEST").save(figure_filename)
10, sim.SpikeSourceArray(spike_times=spike_times), label="input") output_population = sim.Population(20, sim.IF_curr_exp(**cell_params), label="output") print "[%d] input_population cells: %s" % (node, input_population.local_cells) print "[%d] output_population cells: %s" % (node, output_population.local_cells) print "tau_m =", output_population.get('tau_m') print "[%d] Connecting populations" % node connector = sim.FixedProbabilityConnector(0.5, rng=rng) syn = sim.StaticSynapse(weight=1.0) projection = sim.Projection(input_population, output_population, connector, syn) filename = normalized_filename("Results", "simpleRandomNetwork", "conn", simulator_name, sim.num_processes()) projection.save('connections', filename) print connection_plot(projection.get('weight', format='array')) input_population.record('spikes') output_population.record('spikes') output_population.sample(n_record, rng).record('v') print "[%d] Running simulation" % node sim.run(tstop) print "[%d] Writing spikes and Vm to disk" % node filename = normalized_filename("Results", "simpleRandomNetwork_output", "pkl", simulator_name, sim.num_processes()) output_population.write_data(filename, annotations={'script_name': __file__}) ##input_population.write_data('%s_input.h5' % file_stem)
print("Height of first EPSP:") for population in all_neurons.populations: # retrieve the recorded data vm = population.get_data().segments[0].filter(name='v')[0] # take the data between the first and second incoming spikes vm12 = vm.time_slice(spike_times[0] * ms, spike_times[1] * ms) # calculate and print the EPSP height for channel in (0, 1): v_init = vm12[:, channel][0] height = vm12[:, channel].max() - v_init print(" {:<30} at {}: {}".format(population.label, v_init, height)) # === Save the results, optionally plot a figure ============================= filename = normalized_filename("Results", "synaptic_input", "pkl", options.simulator) all_neurons.write_data(filename, annotations={'script_name': __file__}) if options.plot_figure: from pyNN.utility.plotting import Figure, Panel figure_filename = filename.replace("pkl", "png") Figure( Panel(cuba_exp.get_data().segments[0].filter(name='v')[0], ylabel="Membrane potential (mV)", data_labels=[cuba_exp.label], yticks=True, ylim=(-66, -50)), Panel(cuba_alpha.get_data().segments[0].filter(name='v')[0], data_labels=[cuba_alpha.label], yticks=True, ylim=(-66, -50)), Panel(coba_exp.get_data().segments[0].filter(name='v')[0], data_labels=[coba_exp.label], yticks=True, ylim=(-66, -50)), Panel(coba_alpha.get_data().segments[0].filter(name='v')[0], data_labels=[coba_alpha.label], yticks=True, ylim=(-66, -50)),
print("delta_v = ", neurons.get('delta_v')) print("tau_eta = ", neurons.get('tau_eta')) print("a_gamma = ", neurons.get('a_gamma')) electrode = sim.DCSource(**parameters['stimulus']) electrode.inject_into(neurons) neurons.record(['v', 'i_eta', 'v_t']) # === Run the simulation ===================================================== sim.run(t_stop) # === Save the results, optionally plot a figure ============================= filename = normalized_filename("Results", "gif_neuron", "pkl", options.simulator, sim.num_processes()) neurons.write_data(filename, annotations={'script_name': __file__}) if options.plot_figure: from pyNN.utility.plotting import Figure, Panel figure_filename = filename.replace("pkl", "png") data = neurons.get_data().segments[0] v = data.filter(name="v")[0] v_t = data.filter(name="v_t")[0] i_eta = data.filter(name="i_eta")[0] Figure(Panel(v, ylabel="Membrane potential (mV)", yticks=True, ylim=[-66, -52]), Panel(v_t, ylabel="Threshold (mV)", yticks=True), Panel(i_eta,
electrode = sim.DCSource(start=2.0, stop=92.0, amplitude=0.014) electrode.inject_into(neurons[2:3]) neurons.record(['v']) #, 'u']) neurons.initialize(v=-70.0, u=-14.0) # === Run the simulation ===================================================== sim.run(100.0) # === Save the results, optionally plot a figure ============================= filename = normalized_filename("Results", "Izhikevich", "pkl", options.simulator, sim.num_processes()) neurons.write_data(filename, annotations={'script_name': __file__}) if options.plot_figure: from pyNN.utility.plotting import Figure, Panel figure_filename = filename.replace("pkl", "png") data = neurons.get_data().segments[0] v = data.filter(name="v")[0] #u = data.filter(name="u")[0] Figure( Panel(v, ylabel="Membrane potential (mV)", xticks=True, xlabel="Time (ms)", data_labels=[options.simulator.upper()], yticks=True), #Panel(u, ylabel="u variable (units?)"), ).save(figure_filename) print(figure_filename)
def report_time(t): print "The time is %gms" % t return t + 500 sim.run(t_stop, callbacks=[report_time]) scipy.io.savemat('weights.mat', { 'la':connections.get('weight', format='list', with_address=True), 'ln':connections.get('weight', format='list', with_address=False), 'aa':connections.get('weight', format='array', with_address=True), 'an':connections.get('weight', format='array', with_address=False) }) # === Save the results, optionally plot a figure ============================= filename = normalized_filename("Results", "ball_trajectories", "pkl", options.simulator) p2.write_data(filename, annotations={'script_name': __file__}) presynaptic_data = p1.get_data().segments[0] postsynaptic_data = p2.get_data().segments[0] print("Post-synaptic spike times: %s" % postsynaptic_data.spiketrains[0]) if options.plot_figure: from pyNN.utility.plotting import Figure, Panel, DataTable figure_filename = filename.replace("pkl", "png") Figure( # raster plot of the presynaptic neuron spike times Panel(presynaptic_data.spiketrains, yticks=True, markersize=0.2, xlim=((episodes-10)*(t_stop/episodes), t_stop)), Panel(postsynaptic_data.spiketrains, yticks=True, markersize=0.2, xlim=((episodes-10)*(t_stop/episodes), t_stop)),
projections[label] = sim.Projection(spike_source, populations[label], connector, receptor_type='inhibitory', synapse_type=synapse_types[label]) spike_source.record('spikes') # === Run the simulation ===================================================== sim.run(200.0) # === Save the results, optionally plot a figure ============================= for label, p in populations.items(): filename = normalized_filename("Results", "tsodyksmarkram_%s" % label, "pkl", options.simulator) p.write_data(filename, annotations={'script_name': __file__}) if options.plot_figure: from pyNN.utility.plotting import Figure, Panel figure_filename = normalized_filename("Results", "tsodyksmarkram", "png", options.simulator) panels = [] for variable in ('gsyn_inh', 'v'): for population in populations.values(): panels.append( Panel(population.get_data().segments[0].filter(name=variable)[0], data_labels=[population.label], yticks=True), ) # add ylabel to top panel in each group
'v_reset': -70.0, 'e_rev_E': 0., 'e_rev_I': -80. }) spike_sourceE = create(SpikeSourceArray, {'spike_times': [float(i) for i in range(5, 105, 10)]}) spike_sourceI = create( SpikeSourceArray, {'spike_times': [float(i) for i in range(155, 255, 10)]}) connE = connect(spike_sourceE, ifcell, weight=0.006, receptor_type='excitatory', delay=2.0) connI = connect(spike_sourceI, ifcell, weight=0.02, receptor_type='inhibitory', delay=4.0) filename = normalized_filename("Results", "IF_cond_exp", "pkl", simulator_name) record(['v', 'gsyn_exc', 'gsyn_inh'], ifcell, filename, annotations={'script_name': __file__}) run(200.0) end()
projections[label].initialize(a=synapse_types[label].parameter_space['n'], u=synapse_types[label].parameter_space['U']) spike_source.record('spikes') if "nest" in sim.__name__: print(sim.nest.GetStatus([projections['depressing, n=5'].nest_connections[0]])) # === Run the simulation ===================================================== sim.run(400.0) # === Save the results, optionally plot a figure ============================= for label, p in populations.items(): filename = normalized_filename("Results", "multiquantal_synapses_%s" % label, "pkl", options.simulator) p.write_data(filename, annotations={'script_name': __file__}) if options.plot_figure: from pyNN.utility.plotting import Figure, Panel #figure_filename = normalized_filename("Results", "multiquantal_synapses", # "png", options.simulator) figure_filename = "Results/multiquantal_synapses_{}.png".format(options.simulator) data = {} for label in synapse_types: data[label] = populations[label].get_data().segments[0] gsyn = data[label].filter(name='gsyn_inh')[0] gsyn_mean = neo.AnalogSignal(gsyn.mean(axis=1).reshape(-1, 1), sampling_rate=gsyn.sampling_rate,
print("tau_eta = ", neurons.get('tau_eta')) print("a_gamma = ", neurons.get('a_gamma')) electrode = sim.DCSource(**parameters['stimulus']) electrode.inject_into(neurons) neurons.record(['v', 'i_eta', 'v_t']) # === Run the simulation ===================================================== sim.run(t_stop) # === Save the results, optionally plot a figure ============================= filename = normalized_filename("Results", "gif_neuron", "pkl", options.simulator, sim.num_processes()) neurons.write_data(filename, annotations={'script_name': __file__}) if options.plot_figure: from pyNN.utility.plotting import Figure, Panel figure_filename = filename.replace("pkl", "png") data = neurons.get_data().segments[0] v = data.filter(name="v")[0] v_t = data.filter(name="v_t")[0] i_eta = data.filter(name="i_eta")[0] Figure( Panel(v, ylabel="Membrane potential (mV)", yticks=True, ylim=[-66, -52]), Panel(v_t, ylabel="Threshold (mV)", yticks=True), Panel(i_eta, ylabel="i_eta (nA)", xticks=True,
return [gen() for j in i] else: return gen() assert generate_spike_times(0).max() > simtime spike_source = Population(n, SpikeSourceArray(spike_times=generate_spike_times)) spike_source.record("spikes") cells.record("spikes") cells[0:1].record("v") input_conns = Projection(spike_source, cells, AllToAllConnector(), StaticSynapse()) input_conns.setWeights(w) input_conns.setDelays(syn_delay) # === Run simulation =========================================================== run(simtime) # spike_source.write_data("Results/small_network_input_np%d_%s.pkl" % (num_processes(), simulator_name)) filename = normalized_filename("Results", "small_network", "pkl", simulator_name, num_processes()) cells.write_data(filename, annotations={"script_name": __file__}) print "Mean firing rate: ", cells.mean_spike_count() * 1000.0 / simtime, "Hz" # === Clean up and quit ======================================================== end()
rate_generator = iter(range(0, 100, rate_increment)) sim.run(1000, callbacks=[ MyProgressBar(10.0, 1000.0), SetRate(p, rate_generator, interval) ]) # === Retrieve recorded data, and count the spikes in each interval ========== data = p.get_data().segments[0] all_spikes = np.hstack([st.magnitude for st in data.spiketrains]) spike_counts = [((all_spikes >= x) & (all_spikes < x + interval)).sum() for x in range(0, 1000, interval)] expected_spike_counts = [ p.size * rate * interval / 1000.0 for rate in range(0, 100, rate_increment) ] print("\nActual spike counts: {}".format(spike_counts)) print("Expected mean spike counts: {}".format(expected_spike_counts)) if options.plot_figure: Figure(Panel(data.spiketrains, xlabel="Time (ms)", xticks=True), title="Time varying Poisson spike trains", annotations="Simulated with %s" % options.simulator.upper()).save( normalized_filename("Results", "varying_poisson", "png", options.simulator)) sim.end()
label="IF_cond_exp_gsfa_grr") izh = sim.Population(1, sim.Izhikevich(i_offset=0.01), label="Izhikevich") all_neurons = cuba_exp + hh + adexp + adapt + izh all_neurons.record('v') adexp.record('w') izh.record('u') # === Run the simulation ===================================================== sim.run(100.0) # === Save the results, optionally plot a figure ============================= filename = normalized_filename("Results", "cell_type_demonstration", "pkl", options.simulator) all_neurons.write_data(filename, annotations={'script_name': __file__}) if options.plot_figure: from pyNN.utility.plotting import Figure, Panel figure_filename = filename.replace("pkl", "png") Figure(Panel(cuba_exp.get_data().segments[0].filter(name='v')[0], ylabel="Membrane potential (mV)", data_labels=[cuba_exp.label], yticks=True, ylim=(-66, -48)), Panel(hh.get_data().segments[0].filter(name='v')[0], ylabel="Membrane potential (mV)", data_labels=[hh.label], yticks=True, ylim=(-100, 60)),
# === Create four cells and inject current into each one ===================== cells = sim.Population(4, sim.IF_curr_exp(v_thresh=-55.0, tau_refrac=5.0, tau_m=10.0)) current_sources = [sim.DCSource(amplitude=0.5, start=50.0, stop=400.0), sim.StepCurrentSource(times=[50.0, 210.0, 250.0, 410.0], amplitudes=[0.4, 0.6, -0.2, 0.2]), sim.ACSource(start=50.0, stop=450.0, amplitude=0.2, offset=0.1, frequency=10.0, phase=180.0), sim.NoisyCurrentSource(mean=0.5, stdev=0.2, start=50.0, stop=450.0, dt=1.0)] for cell, current_source in zip(cells, current_sources): cell.inject(current_source) filename = normalized_filename("Results", "current_injection", "pkl", options.simulator) sim.record('v', cells, filename, annotations={'script_name': __file__}) # === Run the simulation ===================================================== sim.run(500.0) # === Save the results, optionally plot a figure ============================= vm = cells.get_data().segments[0].filter(name="v")[0] sim.end() if options.plot_figure: from pyNN.utility.plotting import Figure, Panel from quantities import mV
populations[label], connector, receptor_type='inhibitory', synapse_type=synapse_types[label]) spike_source.record('spikes') # === Run the simulation ===================================================== sim.run(400.0) # === Save the results, optionally plot a figure ============================= for label, p in populations.items(): filename = normalized_filename("Results", "stochastic_comparison_%s" % label, "pkl", options.simulator) p.write_data(filename, annotations={'script_name': __file__}) if options.plot_figure: from pyNN.utility.plotting import Figure, Panel #figure_filename = normalized_filename("Results", "stochastic_comparison", # "png", options.simulator) figure_filename = "Results/stochastic_comparison_{}.png".format( options.simulator) data = {} for label in synapse_types: data[label] = populations[label].get_data().segments[0] if 'stochastic' in label: gsyn = data[label].filter(name='gsyn_inh')[0]
def test_record_with_filename(sim): """ Test to ensure that Simulator and Population recording work properly The following 12 scenarios are explored: Note: var1 = "spikes", var2 = "v" 1) sim.record() i) cell[0] a) 2 parameters (2vars) (scenario 1) b) parameter1 (var1) (scenario 2) c) parameter2 (var2) (scenario 3) ii) cell[1] a) 2 parameters (2vars) (scenario 4) b) parameter1 (var1) (scenario 5) c) parameter2 (var2) (scenario 6) iii) population a) 2 parameters (2vars) (scenario 7) b) parameter1 (var1) (scenario 8) c) parameter2 (var2) (scenario 9) 2) pop.record() - always records for a population; not a single cell a) 2 parameters (2vars) (scenario 10) b) parameter1 (var1) (scenario 11) c) parameter2 (var2) (scenario 12) cf Issues #449, #490, #491 """ # START ***** defining methods needed for test ***** def get_file_data(filename): # method to access pickled file and retrieve data data = [] with (open(filename, "rb")) as openfile: while True: try: data.append(pickle.load(openfile)) except EOFError: break return data def eval_num_cells(data): # scan data object to evaluate number of cells; returns 4 values # nCells : # of cells in analogsignals (if "v" recorded) # nspikes1: # of spikes in first recorded cell # nspikes2: # of spikes in second recorded cell (if exists) # -- if any parameter absent, return -1 as its value # annot_bool # true if specified annotation exists; false otherwise try: nCells = data[0].segments[0].analogsignals[0].shape[1] except: nCells = -1 try: nspikes1 = data[0].segments[0].spiketrains[0].shape[0] except: nspikes1 = -1 try: nspikes2 = data[0].segments[0].spiketrains[1].shape[0] except: nspikes2 = -1 if 'script_name' in data[0].annotations.keys(): annot_bool = True else: annot_bool = False return (nCells, nspikes1, nspikes2, annot_bool) # END ***** defining methods needed for test ***** sim_dt = 0.1 sim.setup(min_delay=1.0, timestep=sim_dt) # creating a population of two cells; only cell[0] gets stimulus # hence only cell[0] will have entries for spiketrains cells = sim.Population(2, sim.IF_curr_exp(v_thresh=-55.0, tau_refrac=5.0)) steady = sim.DCSource(amplitude=2.5, start=25.0, stop=75.0) cells[0].inject(steady) # specify appropriate filenames for output files filename_sim_cell1_2vars = normalized_filename("Results", "sim_cell1_2vars", "pkl", sim.__name__) filename_sim_cell1_var1 = normalized_filename("Results", "sim_cell1_var1", "pkl", sim.__name__) filename_sim_cell1_var2 = normalized_filename("Results", "sim_cell1_var2", "pkl", sim.__name__) filename_sim_cell2_2vars = normalized_filename("Results", "sim_cell2_2vars", "pkl", sim.__name__) filename_sim_cell2_var1 = normalized_filename("Results", "sim_cell2_var1", "pkl", sim.__name__) filename_sim_cell2_var2 = normalized_filename("Results", "sim_cell2_var2", "pkl", sim.__name__) filename_sim_popl_2vars = normalized_filename("Results", "sim_popl_2vars", "pkl", sim.__name__) filename_sim_popl_var1 = normalized_filename("Results", "sim_popl_var1", "pkl", sim.__name__) filename_sim_popl_var2 = normalized_filename("Results", "sim_popl_var2", "pkl", sim.__name__) filename_rec_2vars = normalized_filename("Results", "rec_2vars", "pkl", sim.__name__) filename_rec_var1 = normalized_filename("Results", "rec_var1", "pkl", sim.__name__) filename_rec_var2 = normalized_filename("Results", "rec_var2", "pkl", sim.__name__) # instruct pynn to record as per above scenarios sim.record(["spikes", "v"], cells[0], filename_sim_cell1_2vars, annotations={'script_name': __file__}) sim.record(["spikes"], cells[0], filename_sim_cell1_var1, annotations={'script_name': __file__}) sim.record(["v"], cells[0], filename_sim_cell1_var2, annotations={'script_name': __file__}) sim.record(["spikes", "v"], cells[1], filename_sim_cell2_2vars, annotations={'script_name': __file__}) sim.record(["spikes"], cells[1], filename_sim_cell2_var1, annotations={'script_name': __file__}) sim.record(["v"], cells[1], filename_sim_cell2_var2, annotations={'script_name': __file__}) sim.record(["spikes", "v"], cells, filename_sim_popl_2vars, annotations={'script_name': __file__}) sim.record(["spikes"], cells, filename_sim_popl_var1, annotations={'script_name': __file__}) sim.record(["v"], cells, filename_sim_popl_var2, annotations={'script_name': __file__}) cells.record(["spikes", "v"], to_file=filename_rec_2vars) cells.record(["spikes"], to_file=filename_rec_var1) cells.record(["v"], to_file=filename_rec_var2) sim.run(100.0) sim.end() # retrieve data from the created files, and perform appropriate checks # scenario 1 nCells, nspikes1, nspikes2, annot_bool = eval_num_cells( get_file_data(filename_sim_cell1_2vars)) assert_true(nCells == 1) assert_true(nspikes1 > 0) assert_true(nspikes2 == -1) assert_true(annot_bool) # scenario 2 nCells, nspikes1, nspikes2, annot_bool = eval_num_cells( get_file_data(filename_sim_cell1_var1)) assert_true(nCells == -1) assert_true(nspikes1 > 0) assert_true(nspikes2 == -1) assert_true(annot_bool) # scenario 3 nCells, nspikes1, nspikes2, annot_bool = eval_num_cells( get_file_data(filename_sim_cell1_var2)) assert_true(nCells == 1) assert_true(nspikes1 == -1) assert_true(nspikes2 == -1) assert_true(annot_bool) # scenario 4 nCells, nspikes1, nspikes2, annot_bool = eval_num_cells( get_file_data(filename_sim_cell2_2vars)) assert_true(nCells == 1) assert_true(nspikes1 == 0) assert_true(nspikes2 == -1) assert_true(annot_bool) # scenario 5 nCells, nspikes1, nspikes2, annot_bool = eval_num_cells( get_file_data(filename_sim_cell2_var1)) assert_true(nCells == -1) assert_true(nspikes1 == 0) assert_true(nspikes2 == -1) assert_true(annot_bool) # scenario 6 nCells, nspikes1, nspikes2, annot_bool = eval_num_cells( get_file_data(filename_sim_cell2_var2)) assert_true(nCells == 1) assert_true(nspikes1 == -1) assert_true(nspikes2 == -1) assert_true(annot_bool) # scenario 7 nCells, nspikes1, nspikes2, annot_bool = eval_num_cells( get_file_data(filename_sim_popl_2vars)) assert_true(nCells == 2) assert_true(nspikes1 > 0) assert_true(nspikes2 == 0) assert_true(annot_bool) # scenario 8 nCells, nspikes1, nspikes2, annot_bool = eval_num_cells( get_file_data(filename_sim_popl_var1)) assert_true(nCells == -1) assert_true(nspikes1 > 0) assert_true(nspikes2 == 0) assert_true(annot_bool) # scenario 9 nCells, nspikes1, nspikes2, annot_bool = eval_num_cells( get_file_data(filename_sim_popl_var2)) assert_true(nCells == 2) assert_true(nspikes1 == -1) assert_true(nspikes2 == -1) assert_true(annot_bool) # scenario 10 nCells, nspikes1, nspikes2, annot_bool = eval_num_cells( get_file_data(filename_rec_2vars)) assert_true(nCells == 2) assert_true(nspikes1 > 0) assert_true(nspikes2 == 0) assert_true(annot_bool) # scenario 11 nCells, nspikes1, nspikes2, annot_bool = eval_num_cells( get_file_data(filename_rec_var1)) assert_true(nCells == -1) assert_true(nspikes1 > 0) assert_true(nspikes2 == 0) assert_true(annot_bool) # scenario 12 nCells, nspikes1, nspikes2, annot_bool = eval_num_cells( get_file_data(filename_rec_var2)) assert_true(nCells == 2) assert_true(nspikes1 == -1) assert_true(nspikes2 == -1) assert_true(annot_bool)
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(('v', 'gsyn_exc')) syn = sim.StaticSynapse(weight=w, delay=syn_delay) input_conns = sim.Projection(spike_source, cells, sim.FixedProbabilityConnector(0.5), syn) # === Run simulation =========================================================== sim.run(simtime) filename = normalized_filename("Results", "small_network", "pkl", options.simulator, sim.num_processes()) cells.write_data(filename, annotations={'script_name': __file__}) print("Mean firing rate: ", cells.mean_spike_count() * 1000.0 / simtime, "Hz") if options.plot_figure: from pyNN.utility.plotting import Figure, Panel figure_filename = filename.replace("pkl", "png") data = cells.get_data().segments[0] vm = data.filter(name="v")[0] gsyn = data.filter(name="gsyn_exc")[0] Figure( Panel(vm, ylabel="Membrane potential (mV)"), Panel(gsyn, ylabel="Synaptic conductance (uS)"), Panel(data.spiketrains, xlabel="Time (ms)", xticks=True), annotations="Simulated with %s" % options.simulator.upper()
t_stop=t_stop, title='(S) Inhibition-induced spiking') # == Sub-plot T: Inhibition-induced bursting ================================ ''' Modifying parameter d from -2.0 to -0.7 in order to reproduce Fig. 1 ''' t_stop = 350.0 run_simulation(a=-0.026, b=-1.0, c=-45.0, d=-0.7, v_init=-63.8, waveform=pulse(0.075, [50], 200, t_stop, baseline=0.08), t_stop=t_stop, title='(T) Inhibition-induced bursting') # == Export figure in PNG format ============================================ filename = normalized_filename("results", "izhikevich2004", "png", options.simulator) try: os.makedirs(os.path.dirname(filename)) except OSError: pass fig.savefig(filename) print("\n Simulation complete. Results can be seen in figure at %s\n" % (filename))
projections[label] = sim.Projection(spike_source, populations[label], connector, receptor_type='inhibitory', synapse_type=synapse_types[label]) spike_source.record('spikes') # === Run the simulation ===================================================== sim.run(200.0) # === Save the results, optionally plot a figure ============================= for label, p in populations.items(): filename = normalized_filename("Results", "stochastic_synapses_%s" % label, "pkl", options.simulator) p.write_data(filename, annotations={'script_name': __file__}) if options.plot_figure: from pyNN.utility.plotting import Figure, Panel figure_filename = normalized_filename("Results", "stochastic_synapses_", "png", options.simulator) panels = [] for variable in ('gsyn_inh', 'v'): for population in populations.values(): panels.append( Panel( population.get_data().segments[0].filter(name=variable)[0], data_labels=[population.label], yticks=True), ) # add ylabel to top panel in each group
return t + self.interval class MyProgressBar(object): def __init__(self, interval, t_stop): self.interval = interval self.t_stop = t_stop self.pb = ProgressBar(width=int(t_stop / interval), char=".") def __call__(self, t): self.pb(t / self.t_stop) return t + self.interval sim.setup() p = sim.Population(50, sim.SpikeSourcePoisson()) p.record("spikes") rate_generator = iter(range(0, 100, 20)) progress_bar = ProgressBar() sim.run(1000, callbacks=[MyProgressBar(10.0, 1000.0), SetRate(p, rate_generator, 200.0)]) data = p.get_data().segments[0] Figure(Panel(data.spiketrains, xlabel="Time (ms)", xticks=True), title="Time varying Poisson spike trains").save( normalized_filename("Results", "varying_poisson", "png", args.simulator) ) sim.end()
""" Simple test of injecting various types of current into a cell """ import sys from pyNN.utility import get_script_args, normalized_filename simulator_name = get_script_args(1)[0] exec("from pyNN.%s import *" % simulator_name) setup() filename = normalized_filename("Results", "NoisyCurrentInput", "pkl", simulator_name) cells = Population(3, IF_curr_exp(v_thresh=-55.0, tau_refrac=5.0)) mean=0.55 stdev=0.1 start=50.0 stop=125.0 steady = DCSource(amplitude=mean, start=start, stop=stop) cells[0].inject(steady) noise1 = NoisyCurrentSource(mean=mean, stdev=stdev, start=start, stop=stop, dt=10) cells[1].inject(noise1) acsource = ACSource(start=start, stop=stop, amplitude=mean, offset=0.0, frequency=100.0, phase=0.0) cells[2].inject(acsource) record('v', cells, filename, annotations={'script_name': __file__})
return [gen() for j in i] else: return gen() assert generate_spike_times(0).max() > simtime spike_source = sim.Population(n_cells, sim.SpikeSourceArray(spike_times=generate_spike_times)) connections = sim.Projection(spike_source, cells, sim.FixedProbabilityConnector(0.5), sim.StaticSynapse(weight='1/(1+d)', delay=0.5) ) print "weights:" print str(connections.get('weight', format='array')).replace('nan', ' . ') print "delays:" print str(connections.get('delay', format='array')).replace('nan', ' . ') cells.record(['spikes', 'v']) sim.run(100.0) filename = normalized_filename("Results", "inhomogeneous_network", "pkl", args.simulator_name) cells.write_data(filename, annotations={'script_name': __file__}) print "Mean firing rate: ", cells.mean_spike_count()*1000.0/sim.get_current_time(), "Hz" sim.end()
populations[label], connector, receptor_type='inhibitory', synapse_type=synapse_types[label]) spike_source.record('spikes') # === Run the simulation ===================================================== sim.run(400.0) # === Save the results, optionally plot a figure ============================= for label, p in populations.items(): filename = normalized_filename("Results", "stochastic_tsodyksmarkram_%s" % label, "pkl", options.simulator) p.write_data(filename, annotations={'script_name': __file__}) if options.plot_figure: from pyNN.utility.plotting import Figure, Panel #figure_filename = normalized_filename("Results", "stochastic_tsodyksmarkram", # "png", options.simulator) figure_filename = "Results/stochastic_tsodyksmarkram_{}.png".format( options.simulator) panels = [] for variable in ('gsyn_inh', ): # 'v'): for population in sorted(populations.values(), key=lambda p: p.label): panels.append( Panel( population.get_data().segments[0].filter(name=variable)[0],
""" Test of the EIF_cond_alpha_isfa_ista model Andrew Davison, UNIC, CNRS December 2007 """ from pyNN.utility import get_script_args, normalized_filename simulator_name = get_script_args(1)[0] exec("from pyNN.%s import *" % simulator_name) setup(timestep=0.01, min_delay=0.1, max_delay=4.0, debug=True) ifcell = create( EIF_cond_alpha_isfa_ista(i_offset=1.0, tau_refrac=2.0, v_spike=-40)) print ifcell[0].get_parameters() filename = normalized_filename("Results", "EIF_cond_alpha_isfa_ista", "pkl", simulator_name) record('v', ifcell, filename, annotations={'script_name': __file__}) run(200.0) end()
t_stop = 350.0 run_simulation(a=-0.02, b=-1.0, c=-60.0, d=8.0, v_init=-63.8, waveform=pulse(0.075, [50], 170, # 200 in original t_stop, baseline=0.08), t_stop=t_stop, title='(S) Inhibition-induced spiking') # == Sub-plot T: Inhibition-induced bursting ================================ ''' Modifying parameter d from -2.0 to -0.7 in order to reproduce Fig. 1 ''' t_stop = 350.0 run_simulation(a=-0.026, b=-1.0, c=-45.0, d=-0.7, v_init=-63.8, waveform=pulse(0.075, [50], 200, t_stop, baseline=0.08), t_stop=t_stop, title='(T) Inhibition-induced bursting') # == Export figure in PNG format ============================================ filename = normalized_filename("results", "izhikevich2004", "png", options.simulator) try: os.makedirs(os.path.dirname(filename)) except OSError: pass fig.savefig(filename) print("\n Simulation complete. Results can be seen in figure at %s\n"%(filename))
weight_dependence=AdditiveWeightDependence( w_min=0, w_max=0.04), weight=0.024, delay=0.2) print "####" pprint(stdp_model.translations) connection_method = AllToAllConnector() prj = Projection(p1, p2, connection_method, synapse_type=stdp_model) p1.record('spikes') p2.record(('spikes', 'v', 'gsyn_exc')) t = [] w = [] for i in range(60): t.append(run(1.0)) w.extend(prj.get('weight', format='list', with_address=False)) #p1.write_data("Results/simple_STDP_1_%s.pkl" % sim_name) filename = normalized_filename("Results", "simple_STDP", "pkl", sim_name, num_processes()) p2.write_data(filename, annotations={'script_name': __file__}) print w f = open("Results/simple_STDP_%s.w" % sim_name, 'w') f.write("\n".join([str(ww) for ww in w])) f.close() end()
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)", yticks=True, ylim=(0, 1)), Panel(data.spiketrains, xlabel="Time (ms)", xticks=True),
projections[label] = sim.Projection(spike_source, populations[label], connector, receptor_type='inhibitory', synapse_type=synapse_types[label]) spike_source.record('spikes') # === Run the simulation ===================================================== sim.run(400.0) # === Save the results, optionally plot a figure ============================= for label, p in populations.items(): filename = normalized_filename("Results", "stochastic_comparison_%s" % label, "pkl", options.simulator) p.write_data(filename, annotations={'script_name': __file__}) if options.plot_figure: from pyNN.utility.plotting import Figure, Panel #figure_filename = normalized_filename("Results", "stochastic_comparison", # "png", options.simulator) figure_filename = "Results/stochastic_comparison_{}.png".format(options.simulator) data = {} for label in synapse_types: data[label] = populations[label].get_data().segments[0] if 'stochastic' in label: gsyn = data[label].filter(name='gsyn_inh')[0] gsyn_mean = neo.AnalogSignal(gsyn.mean(axis=1).reshape(-1, 1),
sampling_period=self.interval * ms, channel_index=numpy.arange(len(self._weights[0])), name="weight", ) weight_recorder = WeightRecorder(sampling_interval=1.0, projection=connections) # === Run the simulation ===================================================== sim.run(t_stop, callbacks=[weight_recorder]) # === Save the results, optionally plot a figure ============================= filename = normalized_filename("Results", "simple_stdp", "pkl", options.simulator) p2.write_data(filename, annotations={"script_name": __file__}) presynaptic_data = p1.get_data().segments[0] postsynaptic_data = p2.get_data().segments[0] print("Post-synaptic spike times: %s" % postsynaptic_data.spiketrains[0]) weights = weight_recorder.get_weights() final_weights = numpy.array(weights[-1]) deltas = delta_t * numpy.arange(n // 2, -n // 2, -1) print("Final weights: %s" % final_weights) plasticity_data = DataTable(deltas, final_weights) if options.fit_curve:
print("%d Running simulation..." % node_id) sim.run(tstop) simCPUTime = timer.diff() E_count = exc_cells.mean_spike_count() I_count = inh_cells.mean_spike_count() # === Print results to file ==================================================== print("%d Writing data to file..." % node_id) filename = normalized_filename("Results", "VAbenchmarks_%s_exc" % options.benchmark, "pkl", options.simulator, np) exc_cells.write_data(filename, annotations={'script_name': __file__}) inh_cells.write_data(filename.replace("exc", "inh"), annotations={'script_name': __file__}) writeCPUTime = timer.diff() if options.use_views or options.use_assembly: connections = "%d e→e,i %d i→e,i" % (connections['exc'].size(), connections['inh'].size()) else: connections = u"%d e→e %d e→i %d i→e %d i→i" % ( connections['e2e'].size(), connections['e2i'].size(), connections['i2e'].size(), connections['i2i'].size())
units='nA', sampling_period=self.interval * ms, channel_index=numpy.arange( len(self._weights[0])), name="weight") weight_recorder = WeightRecorder(sampling_interval=1.0, projection=connections) # === Run the simulation ===================================================== sim.run(t_stop, callbacks=[weight_recorder]) # === Save the results, optionally plot a figure ============================= filename = normalized_filename("Results", "simple_stdp", "pkl", options.simulator) p2.write_data(filename, annotations={'script_name': __file__}) presynaptic_data = p1.get_data().segments[0] postsynaptic_data = p2.get_data().segments[0] print("Post-synaptic spike times: %s" % postsynaptic_data.spiketrains[0]) weights = weight_recorder.get_weights() final_weights = numpy.array(weights[-1]) deltas = delta_t * numpy.arange(n // 2, -n // 2, -1) print("Final weights: %s" % final_weights) plasticity_data = DataTable(deltas, final_weights) if options.fit_curve: def double_exponential(t, t0, w0, wp, wn, tau):
print("Height of first EPSP:") for population in all_neurons.populations: # retrieve the recorded data vm = population.get_data().segments[0].filter(name='v')[0] # take the data between the first and second incoming spikes vm12 = vm.time_slice(spike_times[0] * ms, spike_times[1] * ms) # calculate and print the EPSP height for channel in (0, 1): v_init = vm12[:, channel][0] height = vm12[:, channel].max() - v_init print(" {:<30} at {}: {}".format(population.label, v_init, height)) # === Save the results, optionally plot a figure ============================= filename = normalized_filename("Results", "synaptic_input", "pkl", 'NEST') all_neurons.write_data(filename, annotations={'script_name': __file__}) from pyNN.utility.plotting import Figure, Panel figure_filename = filename.replace("pkl", "png") Figure( Panel(cuba_exp.get_data().segments[0].filter(name='v')[0], ylabel="Membrane potential (mV)", data_labels=[cuba_exp.label], yticks=True, ylim=(-66, -50)), Panel(cuba_alpha.get_data().segments[0].filter(name='v')[0], data_labels=[cuba_alpha.label], yticks=True, ylim=(-66, -50)), Panel(coba_exp.get_data().segments[0].filter(name='v')[0], data_labels=[coba_exp.label], yticks=True, ylim=(-66, -50)), Panel(coba_alpha.get_data().segments[0].filter(name='v')[0], data_labels=[coba_alpha.label], yticks=True, ylim=(-66, -50)), Panel(v_step.get_data().segments[0].filter(name='v')[0],
stdev=noise_std, start=1.0, stop=Trec_ms, dt=1.0) noise.inject_into(neurons) neurons.record(['v', 'u']) neurons.initialize(v=-70.0, u=-14.0) # === Run the simulation ===================================================== sim.run(Trec_ms) # === Save the results, optionally plot a figure ============================= filename = normalized_filename("Results", "Izhikevich", "pkl", options.simulator, sim.num_processes()) if options.plot_figure: from pyNN.utility.plotting import Figure, Panel figure_filename = filename.replace("pkl", "pdf") data = neurons.get_data().segments[0] v = data.filter(name="v")[0] u = data.filter(name="u")[0] Figure( Panel(v, ylabel="Membrane potential (mV)", xticks=True, xlabel="Time (ms)", yticks=True), Panel(u, ylabel="Recovery variable (mV)",
# === Run simulation =========================================================== print("%d Running simulation..." % node_id) sim.run(tstop) simCPUTime = timer.diff() E_count = exc_cells.mean_spike_count() I_count = inh_cells.mean_spike_count() # === Print results to file ==================================================== print("%d Writing data to file..." % node_id) filename = normalized_filename("Results", "VAbenchmarks_%s_exc" % options.benchmark, "pkl", options.simulator, np) exc_cells.write_data(filename, annotations={'script_name': __file__}) inh_cells.write_data(filename.replace("exc", "inh"), annotations={'script_name': __file__}) writeCPUTime = timer.diff() if options.use_views or options.use_assembly: connections = "%d e→e,i %d i→e,i" % (connections['exc'].size(), connections['inh'].size()) else: connections = u"%d e→e %d e→i %d i→e %d i→i" % (connections['e2e'].size(), connections['e2i'].size(), connections['i2e'].size(), connections['i2i'].size())
""" Test of the EIF_cond_alpha_isfa_ista model Andrew Davison, UNIC, CNRS December 2007 $Id$ """ from pyNN.utility import get_script_args, normalized_filename simulator_name = get_script_args(1)[0] exec("from pyNN.%s import *" % simulator_name) setup(timestep=0.01,min_delay=0.1,max_delay=4.0,debug=True) ifcell = create(EIF_cond_alpha_isfa_ista(i_offset=1.0, tau_refrac=2.0, v_spike=-40)) print ifcell[0].get_parameters() filename = normalized_filename("Results", "EIF_cond_alpha_isfa_ista", "pkl", simulator_name) record('v', ifcell, filename, annotations={'script_name': __file__}) run(200.0) end()
spike_source.record('spikes') if "nest" in sim.__name__: print( sim.nest.GetStatus( [projections['depressing, n=5'].nest_connections[0]])) # === Run the simulation ===================================================== sim.run(400.0) # === Save the results, optionally plot a figure ============================= for label, p in populations.items(): filename = normalized_filename("Results", "multiquantal_synapses_%s" % label, "pkl", options.simulator) p.write_data(filename, annotations={'script_name': __file__}) if options.plot_figure: from pyNN.utility.plotting import Figure, Panel #figure_filename = normalized_filename("Results", "multiquantal_synapses", # "png", options.simulator) figure_filename = "Results/multiquantal_synapses_{}.png".format( options.simulator) data = {} for label in synapse_types: data[label] = populations[label].get_data().segments[0] gsyn = data[label].filter(name='gsyn_inh')[0] gsyn_mean = neo.AnalogSignal(gsyn.mean(axis=1).reshape(-1, 1),
rate = 100.0 setup(timestep=0.1, min_delay=0.2, max_delay=1.0) cell_params = {'tau_refrac': 2.0, 'v_thresh': [-50.0, -48.0] , 'tau_syn_E': 2.0, 'tau_syn_I': 2.0} output_population = Population(2, IF_curr_alpha(**cell_params), label="output") number = int(2*tstop*rate/1000.0) numpy.random.seed(26278342) spike_times = numpy.add.accumulate(numpy.random.exponential(1000.0/rate, size=number)) assert spike_times.max() > tstop print spike_times.min() input_population = Population(1, SpikeSourceArray(spike_times=spike_times), label="input") projection = Projection(input_population, output_population, AllToAllConnector(), StaticSynapse(weight=1.0)) input_population.record('spikes') output_population.record(('spikes', 'v')) run(tstop) filename = normalized_filename("Results", "simpleNetwork_output", "pkl", simulator_name) output_population.write_data(filename, annotations={'script_name': __file__}) ##input_population.write_data("Results/simpleNetwork_input_%s.h5" % simulator_name) end()
sim.DCSource(amplitude=0.5, start=50.0, stop=400.0), sim.StepCurrentSource(times=[50.0, 210.0, 250.0, 410.0], amplitudes=[0.4, 0.6, -0.2, 0.2]), sim.ACSource(start=50.0, stop=450.0, amplitude=0.2, offset=0.1, frequency=10.0, phase=180.0), sim.NoisyCurrentSource(mean=0.5, stdev=0.2, start=50.0, stop=450.0, dt=1.0) ] for cell, current_source in zip(cells, current_sources): cell.inject(current_source) filename = normalized_filename("Results", "current_injection", "pkl", options.simulator) sim.record("v", cells, filename, annotations={"script_name": __file__}) # ===Run the simulation ====================================================== sim.run(500.0) # ===Save the results, optionally plot a figure ============================== vm = cells.get_data().segments[0].filter(name="v")[0] sim.end() if options.plot_figure: from pyNN.utility.plotting import Figure, Panel from quantities import mV figure_filename = filename.replace("pkl", "png")
dataset_size = np.shape(x_test)[0] print('starting simulation') sim.run(time_per_image * nb_images) print('stopping simulation') # === Save the results, optionally plot a figure =============================== if (fashion_mnist): save_dir = "ResultsFashionMNIST" else: save_dir = "ResultsMNIST" filename = normalized_filename(save_dir, "input", "pkl", options.simulator) input.write_data(filename, annotations={'script_name': __file__}) filename = normalized_filename(save_dir, "hidden", "pkl", options.simulator) hidden.write_data(filename, annotations={'script_name': __file__}) filename = normalized_filename(save_dir, "output", "pkl", options.simulator) output.write_data(filename, annotations={'script_name': __file__}) if options.plot_figure: from pyNN.utility.plotting import Figure, Panel figure_filename = filename.replace("pkl", "png") Figure( Panel(hidden.get_data().segments[0].spiketrains, ylabel="Membrane potential (mV)", yticks=True,
all_neurons = cuba_exp + hh + adexp + adapt + izh all_neurons.record('v') adexp.record('w') izh.record('u') # === Run the simulation ===================================================== sim.run(100.0) # === Save the results, optionally plot a figure ============================= filename = normalized_filename("Results", "cell_type_demonstration", "pkl", options.simulator) all_neurons.write_data(filename, annotations={'script_name': __file__}) if options.plot_figure: from pyNN.utility.plotting import Figure, Panel figure_filename = filename.replace("pkl", "png") Figure( Panel(cuba_exp.get_data().segments[0].filter(name='v')[0], ylabel="Membrane potential (mV)", data_labels=[cuba_exp.label], yticks=True, ylim=(-66, -48)), Panel(hh.get_data().segments[0].filter(name='v')[0], ylabel="Membrane potential (mV)", data_labels=[hh.label], yticks=True, ylim=(-100, 60)), Panel(adexp.get_data().segments[0].filter(name='v')[0], ylabel="Membrane potential (mV)", data_labels=[adexp.label], yticks=True, ylim=(-75, -40)),
projections[label] = sim.Projection(spike_source, populations[label], connector, receptor_type='inhibitory', synapse_type=synapse_types[label]) spike_source.record('spikes') # === Run the simulation ===================================================== sim.run(200.0) # === Save the results, optionally plot a figure ============================= for label, p in populations.items(): filename = normalized_filename("Results", "tsodyksmarkram_%s" % label, "pkl", options.simulator) p.write_data(filename, annotations={'script_name': __file__}) if options.plot_figure: from pyNN.utility.plotting import Figure, Panel figure_filename = normalized_filename("Results", "tsodyksmarkram", "png", options.simulator) panels = [] for variable in ('gsyn_inh', 'v'): for population in populations.values(): panels.append( Panel( population.get_data().segments[0].filter(name=variable)[0], data_labels=[population.label], yticks=True), ) # add ylabel to top panel in each group
stdp_model = STDPMechanism(timing_dependence=SpikePairRule(tau_plus=20.0, tau_minus=20.0), weight_dependence=AdditiveWeightDependence(w_min=0, w_max=0.04, A_plus=0.01, A_minus=0.012), weight=0.024, delay=0.2) print "####" pprint(stdp_model.translations) connection_method = AllToAllConnector() prj = Projection(p1, p2, connection_method, synapse_type=stdp_model) p1.record('spikes') p2.record(('spikes', 'v', 'gsyn_exc')) t = [] w = [] for i in range(60): t.append(run(1.0)) w.extend(prj.get('weight', format='list', with_address=False)) #p1.write_data("Results/simple_STDP_1_%s.pkl" % sim_name) filename = normalized_filename("Results", "simple_STDP", "pkl", sim_name, num_processes()) p2.write_data(filename, annotations={'script_name': __file__}) print w f = open("Results/simple_STDP_%s.w" % sim_name, 'w') f.write("\n".join([str(ww) for ww in w])) f.close() end()
connector = FromListConnector([ (0, 1, w, syn_delay), (0, 2, w, syn_delay), (0, 4, w, syn_delay), (1, 0, w, syn_delay), (1, 1, w, syn_delay), (1, 3, w, syn_delay), (1, 4, w, syn_delay), (2, 3, w, syn_delay), (3, 0, w, syn_delay), (3, 2, w, syn_delay), (4, 2, w, syn_delay), ]) input_conns = Projection(spike_source, cells, connector, StaticSynapse()) # === Run simulation =========================================================== run(simtime) #spike_source.write_data("Results/small_network_input_np%d_%s.pkl" % (num_processes(), simulator_name)) filename = normalized_filename("Results", "specific_network", "pkl", simulator_name, num_processes()) cells.write_data(filename, annotations={'script_name': __file__}) print("Mean firing rate: ", cells.mean_spike_count() * 1000.0 / simtime, "Hz") # === Clean up and quit ======================================================== end()
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)), Panel(data.spiketrains, xlabel="Time (ms)", xticks=True),
Andrew Davison, UNIC, CNRS May 2006 """ from pyNN.utility import get_script_args, normalized_filename simulator_name = get_script_args(1)[0] exec("from pyNN.%s import *" % simulator_name) setup(timestep=0.1, min_delay=0.1, max_delay=4.0) ifcell = create(IF_cond_exp, {'i_offset' : 0.1, 'tau_refrac': 3.0, 'v_thresh' : -51.0, 'tau_syn_E' : 2.0, 'tau_syn_I': 5.0, 'v_reset' : -70.0, 'e_rev_E' : 0., 'e_rev_I' : -80.}) spike_sourceE = create(SpikeSourceArray, {'spike_times': [float(i) for i in range(5,105,10)]}) spike_sourceI = create(SpikeSourceArray, {'spike_times': [float(i) for i in range(155,255,10)]}) connE = connect(spike_sourceE, ifcell, weight=0.006, receptor_type='excitatory', delay=2.0) connI = connect(spike_sourceI, ifcell, weight=0.02, receptor_type='inhibitory', delay=4.0) filename = normalized_filename("Results", "IF_cond_exp", "pkl", simulator_name) record(['v', 'gsyn_exc', 'gsyn_inh'], ifcell, filename, annotations={'script_name': __file__}) run(200.0) end()
def issue_449_490_491(sim): """ Test to ensure that Simulator and Population recording work properly The following 12 scenarios are explored: Note: var1 = "spikes", var2 = "v" 1) sim.record() i) cell[0] a) 2 parameters (2vars) (scenario 1) b) parameter1 (var1) (scenario 2) c) parameter2 (var2) (scenario 3) ii) cell[1] a) 2 parameters (2vars) (scenario 4) b) parameter1 (var1) (scenario 5) c) parameter2 (var2) (scenario 6) iii) population a) 2 parameters (2vars) (scenario 7) b) parameter1 (var1) (scenario 8) c) parameter2 (var2) (scenario 9) 2) pop.record() - always records for a population; not a single cell a) 2 parameters (2vars) (scenario 10) b) parameter1 (var1) (scenario 11) c) parameter2 (var2) (scenario 12) """ # START ***** defining methods needed for test ***** def get_file_data(filename): # method to access pickled file and retrieve data data = [] with (open(filename, "rb")) as openfile: while True: try: data.append(pickle.load(openfile)) except EOFError: break return data def eval_num_cells(data): # scan data object to evaluate number of cells; returns 4 values # nCells : # of cells in analogsignals (if "v" recorded) # nspikes1: # of spikes in first recorded cell # nspikes2: # of spikes in second recorded cell (if exists) # -- if any parameter absent, return -1 as its value # annot_bool # true if specified annotation exists; false otherwise try: nCells = data[0].segments[0].analogsignals[0].shape[1] except: nCells = -1 try: nspikes1 = data[0].segments[0].spiketrains[0].shape[0] except: nspikes1 = -1 try: nspikes2 = data[0].segments[0].spiketrains[1].shape[0] except: nspikes2 = -1 if 'script_name' in data[0].annotations.keys(): annot_bool = True else: annot_bool = False return (nCells, nspikes1, nspikes2, annot_bool) # END ***** defining methods needed for test ***** sim_dt = 0.1 sim.setup(min_delay=1.0, timestep = sim_dt) # creating a population of two cells; only cell[0] gets stimulus # hence only cell[0] will have entries for spiketrains cells = sim.Population(2, sim.IF_curr_exp(v_thresh=-55.0, tau_refrac=5.0)) steady = sim.DCSource(amplitude=2.5, start=25.0, stop=75.0) cells[0].inject(steady) # specify appropriate filenames for output files filename_sim_cell1_2vars = normalized_filename("Results", "sim_cell1_2vars", "pkl", sim) filename_sim_cell1_var1 = normalized_filename("Results", "sim_cell1_var1", "pkl", sim) filename_sim_cell1_var2 = normalized_filename("Results", "sim_cell1_var2", "pkl", sim) filename_sim_cell2_2vars = normalized_filename("Results", "sim_cell2_2vars", "pkl", sim) filename_sim_cell2_var1 = normalized_filename("Results", "sim_cell2_var1", "pkl", sim) filename_sim_cell2_var2 = normalized_filename("Results", "sim_cell2_var2", "pkl", sim) filename_sim_popl_2vars = normalized_filename("Results", "sim_popl_2vars", "pkl", sim) filename_sim_popl_var1 = normalized_filename("Results", "sim_popl_var1", "pkl", sim) filename_sim_popl_var2 = normalized_filename("Results", "sim_popl_var2", "pkl", sim) filename_rec_2vars = normalized_filename("Results", "rec_2vars", "pkl", sim) filename_rec_var1 = normalized_filename("Results", "rec_var1", "pkl", sim) filename_rec_var2 = normalized_filename("Results", "rec_var2", "pkl", sim) # instruct pynn to record as per above scenarios sim.record(["spikes", "v"], cells[0], filename_sim_cell1_2vars, annotations={'script_name': __file__}) sim.record(["spikes"], cells[0], filename_sim_cell1_var1, annotations={'script_name': __file__}) sim.record(["v"], cells[0], filename_sim_cell1_var2, annotations={'script_name': __file__}) sim.record(["spikes", "v"], cells[1], filename_sim_cell2_2vars, annotations={'script_name': __file__}) sim.record(["spikes"], cells[1], filename_sim_cell2_var1, annotations={'script_name': __file__}) sim.record(["v"], cells[1], filename_sim_cell2_var2, annotations={'script_name': __file__}) sim.record(["spikes", "v"], cells, filename_sim_popl_2vars, annotations={'script_name': __file__}) sim.record(["spikes"], cells, filename_sim_popl_var1, annotations={'script_name': __file__}) sim.record(["v"], cells, filename_sim_popl_var2, annotations={'script_name': __file__}) cells.record(["spikes", "v"], to_file=filename_rec_2vars) cells.record(["spikes"], to_file=filename_rec_var1) cells.record(["v"], to_file=filename_rec_var2) sim.run(100.0) sim.end() # retrieve data from the created files, and perform appropriate checks # scenario 1 nCells, nspikes1, nspikes2, annot_bool = eval_num_cells(get_file_data(filename_sim_cell1_2vars)) assert_true (nCells == 1) assert_true (nspikes1 > 0) assert_true (nspikes2 == -1) assert_true (annot_bool) # scenario 2 nCells, nspikes1, nspikes2, annot_bool = eval_num_cells(get_file_data(filename_sim_cell1_var1)) assert_true (nCells == -1) assert_true (nspikes1 > 0) assert_true (nspikes2 == -1) assert_true (annot_bool) # scenario 3 nCells, nspikes1, nspikes2, annot_bool = eval_num_cells(get_file_data(filename_sim_cell1_var2)) assert_true (nCells == 1) assert_true (nspikes1 == -1) assert_true (nspikes2 == -1) assert_true (annot_bool) # scenario 4 nCells, nspikes1, nspikes2, annot_bool = eval_num_cells(get_file_data(filename_sim_cell2_2vars)) assert_true (nCells == 1) assert_true (nspikes1 == 0) assert_true (nspikes2 == -1) assert_true (annot_bool) # scenario 5 nCells, nspikes1, nspikes2, annot_bool = eval_num_cells(get_file_data(filename_sim_cell2_var1)) assert_true (nCells == -1) assert_true (nspikes1 == 0) assert_true (nspikes2 == -1) assert_true (annot_bool) # scenario 6 nCells, nspikes1, nspikes2, annot_bool = eval_num_cells(get_file_data(filename_sim_cell2_var2)) assert_true (nCells == 1) assert_true (nspikes1 == -1) assert_true (nspikes2 == -1) assert_true (annot_bool) # scenario 7 nCells, nspikes1, nspikes2, annot_bool = eval_num_cells(get_file_data(filename_sim_popl_2vars)) assert_true (nCells == 2) assert_true (nspikes1 > 0) assert_true (nspikes2 == 0) assert_true (annot_bool) # scenario 8 nCells, nspikes1, nspikes2, annot_bool = eval_num_cells(get_file_data(filename_sim_popl_var1)) assert_true (nCells == -1) assert_true (nspikes1 > 0) assert_true (nspikes2 == 0) assert_true (annot_bool) # scenario 9 nCells, nspikes1, nspikes2, annot_bool = eval_num_cells(get_file_data(filename_sim_popl_var2)) assert_true (nCells == 2) assert_true (nspikes1 == -1) assert_true (nspikes2 == -1) assert_true (annot_bool) # scenario 10 nCells, nspikes1, nspikes2, annot_bool = eval_num_cells(get_file_data(filename_rec_2vars)) assert_true (nCells == 2) assert_true (nspikes1 > 0) assert_true (nspikes2 == 0) assert_true (annot_bool) # scenario 11 nCells, nspikes1, nspikes2, annot_bool = eval_num_cells(get_file_data(filename_rec_var1)) assert_true (nCells == -1) assert_true (nspikes1 > 0) assert_true (nspikes2 == 0) assert_true (annot_bool) # scenario 12 nCells, nspikes1, nspikes2, annot_bool = eval_num_cells(get_file_data(filename_rec_var2)) assert_true (nCells == 2) assert_true (nspikes1 == -1) assert_true (nspikes2 == -1) assert_true (annot_bool)
n_spikes = int(2*tstop*input_rate/1000.0) spike_times = numpy.add.accumulate(rng.next(n_spikes, 'exponential', {'beta': 1000.0/input_rate}, mask_local=False)) input_population = sim.Population(10, sim.SpikeSourceArray(spike_times=spike_times), label="input") output_population = sim.Population(20, sim.IF_curr_exp(**cell_params), label="output") print("[%d] input_population cells: %s" % (node, input_population.local_cells)) print("[%d] output_population cells: %s" % (node, output_population.local_cells)) print("tau_m =", output_population.get('tau_m')) print("[%d] Connecting populations" % node) connector = sim.FixedProbabilityConnector(0.5, rng=rng) syn = sim.StaticSynapse(weight=1.0) projection = sim.Projection(input_population, output_population, connector, syn) filename = normalized_filename("Results", "simpleRandomNetwork", "conn", simulator_name, sim.num_processes()) projection.save('connections', filename) input_population.record('spikes') output_population.record('spikes') output_population.sample(n_record, rng).record('v') print("[%d] Running simulation" % node) sim.run(tstop) print("[%d] Writing spikes and Vm to disk" % node) filename = normalized_filename("Results", "simpleRandomNetwork_output", "pkl", simulator_name, sim.num_processes()) output_population.write_data(filename, annotations={'script_name': __file__}) ##input_population.write_data('%s_input.h5' % file_stem) spike_counts = output_population.get_spike_counts()
weight=0.01, delay=0.5), } populations = {} projections = {} for label in 'static', 'depressing', 'facilitating': populations[label] = sim.Population(1, sim.IF_cond_exp(e_rev_I=-75, tau_syn_I=5.0), label=label) populations[label].record(['v', 'gsyn_inh']) projections[label] = sim.Projection(spike_source, populations[label], connector, receptor_type='inhibitory', synapse_type=synapse_types[label]) spike_source.record('spikes') sim.run(200.0) for label, p in populations.items(): filename = normalized_filename("Results", "tsodyksmarkram_%s" % label, "pkl", simulator_name) p.write_data(filename, annotations={'script_name': __file__}) print spike_source.get_data('spikes') sim.end()
else: return gen() assert generate_spike_times(0).max() > simtime spike_source = sim.Population(n_cells, sim.SpikeSourceArray(spike_times=generate_spike_times)) connections = sim.Projection(spike_source, cells, sim.FixedProbabilityConnector(0.5), sim.StaticSynapse(weight='1/(1+d)', delay=0.5) ) print("weights:") print(str(connections.get('weight', format='array')).replace('nan', ' . ')) print("delays:") print(str(connections.get('delay', format='array')).replace('nan', ' . ')) cells.record(['spikes', 'v']) sim.run(100.0) filename = normalized_filename("Results", "inhomogeneous_network", "pkl", args.simulator_name) cells.write_data(filename, annotations={'script_name': __file__}) print("Mean firing rate: ", cells.mean_spike_count() * 1000.0 / sim.get_current_time(), "Hz") sim.end()
from quantities import ms print("Height of first EPSP:") for population in all_neurons.populations: # retrieve the recorded data vm = population.get_data().segments[0].filter(name='v')[0] # take the data between the first and second incoming spikes vm12 = vm.time_slice(spike_times[0] * ms, spike_times[1] * ms) # calculate and print the EPSP height for channel in (0, 1): v_init = vm12[:, channel][0] height = vm12[:, channel].max() - v_init print(" {:<30} at {}: {}".format(population.label, v_init, height)) # === Save the results, optionally plot a figure ============================= filename = normalized_filename("Results", "synaptic_input", "pkl", options.simulator) all_neurons.write_data(filename, annotations={'script_name': __file__}) if options.plot_figure: from pyNN.utility.plotting import Figure, Panel figure_filename = filename.replace("pkl", "png") Figure(Panel(cuba_exp.get_data().segments[0].filter(name='v')[0], ylabel="Membrane potential (mV)", data_labels=[cuba_exp.label], yticks=True, ylim=(-66, -50)), Panel(cuba_alpha.get_data().segments[0].filter(name='v')[0], data_labels=[cuba_alpha.label], yticks=True, ylim=(-66, -50)), Panel(coba_exp.get_data().segments[0].filter(name='v')[0],
""" Simple test of injecting noisy current into a cell """ import sys from pyNN.utility import get_script_args, normalized_filename simulator_name = get_script_args(1)[0] exec("from pyNN.%s import *" % simulator_name) setup() filename = normalized_filename("Results", "NoisyCurrentInput", "pkl", simulator_name) cells = Population(4, IF_curr_exp(v_thresh=-55.0, tau_refrac=5.0)) mean=0.55 stdev=0.1 start=50.0 stop=450.0 steady = DCSource(amplitude=mean, start=start, stop=stop) cells[0].inject(steady) noise1 = NoisyCurrentSource(mean=mean, stdev=stdev, start=start, stop=stop, dt=1.0) cells[1].inject(noise1) #record('i', noise0, filename) noise2 = NoisyCurrentSource(mean=mean, stdev=stdev, start=start, stop=stop, dt=5) cells[2].inject(noise2)
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)), Panel(data.spiketrains, xlabel="Time (ms)", xticks=True), annotations="Simulated with NEURON" ).save(figure_filename)