本文整理汇总了Python中pyNN.neuron.setup函数的典型用法代码示例。如果您正苦于以下问题:Python setup函数的具体用法?Python setup怎么用?Python setup使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了setup函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: setUp
def setUp(self):
sim.setup()
self.p1 = sim.Population(7, sim.IF_cond_exp())
self.p2 = sim.Population(4, sim.IF_cond_exp())
self.p3 = sim.Population(5, sim.IF_curr_alpha())
self.syn1 = sim.StaticSynapse(weight=0.123, delay=0.5)
self.syn2 = sim.StaticSynapse(weight=0.456, delay=0.4)
self.random_connect = sim.FixedNumberPostConnector(n=2)
self.all2all = sim.AllToAllConnector()
示例2: run_simulation
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
示例3: model_network
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 }
示例4: run_simulation
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
示例5: exercise3
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()
示例6: exercise3
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()
示例7: range
import scipy.io as io
from pylab import *
import numpy as np
import pyNN.neuron as p
p.setup(timestep=0.1)
p.reset()
import NeuroTools.stgen as nts
# initialise DATA
data1 = io.loadmat('/home/bude/k0018000/NEUROprojekt/bootstrap_joe093-3-C3-MO.mat')['GDFcell'][0]
data2 = io.loadmat('/home/bude/k0018000/NEUROprojekt/bootstrap_joe108-7-C3-MO.mat')['GDFcell'][0]
data3 = io.loadmat('/home/bude/k0018000/NEUROprojekt/bootstrap_joe112-5-C3-MO.mat')['GDFcell'][0]
data4 = io.loadmat('/home/bude/k0018000/NEUROprojekt/bootstrap_joe112-6-C3-MO.mat')['GDFcell'][0]
data5 = io.loadmat('/home/bude/k0018000/NEUROprojekt/bootstrap_joe145-4-C3-MO.mat')['GDFcell'][0]
data = [data1, data2, data3, data4, data5]
ndirections = 6
nneurons = 5
ntrials = 30
DATA = [[[array([]) for i in range(ntrials)] for i in range(nneurons)] for i in range(ndirections)]
for i in range(ndirections):
for j in range(nneurons):
for k in range(ntrials):
DATA[i][j][k]=data[j][i][data[j][i][:,0]==k+1,1]
DATA[i][j][k].sort()
示例8: range
data_list.append(scp.loadmat('../data_peak/bootstrap_joe108-7-C3-MO(1).mat'))
data_list.append(scp.loadmat('../data_peak/bootstrap_joe112-5-C3-MO.mat'))
data_list.append(scp.loadmat('../data_peak/bootstrap_joe112-6-C3-MO.mat'))
data_list.append(scp.loadmat('../data_peak/bootstrap_joe145-4-C3-MO.mat'))
elif data_set == 'average':
data_list.append(scp.loadmat('../data_av/bootstrap_joe097-5-C3-MO.mat'))
data_list.append(scp.loadmat('../data_av/bootstrap_joe108-4-C3-MO.mat'))
data_list.append(scp.loadmat('../data_av/bootstrap_joe108-7-C3-MO.mat'))
data_list.append(scp.loadmat('../data_av/bootstrap_joe147-1-C3-MO.mat'))
data_list.append(scp.loadmat('../data_av/bootstrap_joe151-1-C3-MO.mat'))
return data_list
#########INITIALIZATION##############################################################################################
p.setup(timestep = timestep)
data_list = load_data(data_set_config)
#convert data to internal data representation
data = []
for list in data_list:
direction_list = []
data.append(direction_list)
for direction in range(0,6):
trial_list = []
direction_list.append(trial_list)
for trial in range(1,36):
if data_set_config == 'peak':
trial_list.append(list['GDFcell'][0][direction][list['GDFcell'][0][direction][:,0] == trial][:,1])
elif data_set_config == 'average':
示例9: test_setup_with_cvode
def test_setup_with_cvode(self):
sim.setup(timestep=0.05, min_delay=0.1, max_delay=1.0,
use_cvode=True, rtol=1e-2, atol=2e-6)
self.assertEqual(h.dt, 0.05)
self.assertEqual(simulator.state.cvode.rtol(), 1e-2)
示例10: test_setup
def test_setup(self):
sim.setup(timestep=0.05, min_delay=0.1, max_delay=1.0)
self.assertEqual(h.dt, 0.05)
示例11: t4
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()
示例12: run
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]])
#.........这里部分代码省略.........
示例13: abspath
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_nmda
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_nmda()
celltype_cls = pyNNml.nineml_celltype_from_model(
name="iaf_nmda",
nineml_model=testModel,
synapse_components=[
pyNNml.CoBaSyn(
namespace='nmda', weight_connector='weight'),
pyNNml.CoBaSyn(
namespace='cobaExcit', weight_connector='q'),
]
)
示例14: std_pynn_simulation
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")
#.........这里部分代码省略.........
示例15: init_logging
"""
Example of using a cell type defined in 9ML with pyNN.neuron
"""
import sys
import nineml
import pyNN.neuron as sim
from pyNN.neuron.nineml import nineml_cell_type
from pyNN.utility import init_logging
from copy import deepcopy
init_logging(None, debug=True)
sim.setup(timestep=0.1, min_delay=0.1, max_delay=2.0)
# Get come models to work with
from nineml.examples.AL import leaky_iaf
from nineml.examples.AL import coba_synapse
celltype_cls = nineml_cell_type("if_cond_exp",
leaky_iaf.c1,
inhibitory=coba_synapse.c1,
excitatory=deepcopy(coba_synapse.c1),
port_map={
'excitatory': [('V', 'V'), ('Isyn', 'Isyn')],
'inhibitory': [('V', 'V'), ('Isyn', 'Isyn')]
},
weight_variables={
'excitatory': 'q',