• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python neuron.setup函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中pyNN.neuron.setup函数的典型用法代码示例。如果您正苦于以下问题:Python setup函数的具体用法?Python setup怎么用?Python setup使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了setup函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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()
开发者ID:NeuralEnsemble,项目名称:PyNN,代码行数:9,代码来源:test_neuron.py


示例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
开发者ID:INCF,项目名称:NineML_demo_2016,代码行数:57,代码来源:brunel_network_nineml.py


示例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 }
开发者ID:JuergenNeubauer,项目名称:NeuroTools,代码行数:50,代码来源:parameter_search_example.py


示例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
开发者ID:INCF,项目名称:NineML_demo_2016,代码行数:49,代码来源:simple_network_nineml.py


示例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()
开发者ID:gittenberg,项目名称:NeuronaleProzesse2011,代码行数:17,代码来源:day4exercise1.py


示例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()
开发者ID:nebw,项目名称:NeuronaleProzesse2011,代码行数:19,代码来源:day4exercise1.py


示例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()
开发者ID:gittenberg,项目名称:NeuronaleProzesse2011,代码行数:29,代码来源:01createDATA.py


示例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':
开发者ID:nebw,项目名称:NeuronaleProzesse2011_Project,代码行数:31,代码来源:network.py


示例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)
开发者ID:NeuralEnsemble,项目名称:PyNN,代码行数:5,代码来源:test_neuron.py


示例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)
开发者ID:NeuralEnsemble,项目名称:PyNN,代码行数:3,代码来源:test_neuron.py


示例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()
开发者ID:iraikov,项目名称:nineml,代码行数:100,代码来源:testLoadingOfNewObjectModel.py


示例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]])

#.........这里部分代码省略.........
开发者ID:apdavison,项目名称:nineml,代码行数:101,代码来源:example_modular_iaf_3coba_to_pynn.py


示例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'),
    ]
)
开发者ID:apdavison,项目名称:nineml,代码行数:31,代码来源:example_modular_iaf_nmda_to_pynn.py


示例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")
#.........这里部分代码省略.........
开发者ID:apdavison,项目名称:nineml,代码行数:101,代码来源:simulate_pynn_neuron.py


示例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',
开发者ID:agravier,项目名称:pynn,代码行数:31,代码来源:nineml_neuron.py


示例16: run

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
#.........这里部分代码省略.........
开发者ID:tclose,项目名称:PyPe9,代码行数:101,代码来源:simulate.py


示例17:


from pyNN.random import RandomDistribution, NumpyRNG
import pyNN.neuron as sim
from pyNN.utility import get_script_args, Timer, ProgressBar, init_logging, normalized_filename
from auxRoutines import *


simTimeIni = 0
simTimeFin = 1000
timeBoundKernel = 400
timeStep = 0.1


sim.setup(timestep=timeStep, min_delay=0.5)


weightInhibToInhibSynapses = 0.03 	# [uS]






tau_m 		= 20.0	# [ms]
cm 		= 0.2 	# [nF]
v_rest 		= -60.0	# [mV]
v_thresh 	= -50.0 # [mV]
tau_syn_E 	= 5.0	# [ms]
tau_syn_I 	= 10.0	# [ms]
e_rev_E 	= 0.0	# [mV]
开发者ID:ChristophMetzner,项目名称:VogelsEtAl2011,代码行数:29,代码来源:test_filteringSpikeTrain.py


示例18: run

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()
开发者ID:apdavison,项目名称:nineml,代码行数:95,代码来源:example_modular_iaf_2coba_to_pynn.py


示例19:

import pyNN.neuron as sim  # can of course replace `neuron` with `nest`, `brian`, etc.
import matplotlib.pyplot as plt
import numpy as np

sim.setup(timestep=0.01)
p_in = sim.Population(10, sim.SpikeSourcePoisson(rate=10.0), label="input")
p_out = sim.Population(10, sim.EIF_cond_exp_isfa_ista(), label="AdExp neurons")

syn = sim.StaticSynapse(weight=0.05)
random = sim.FixedProbabilityConnector(p_connect=0.5)
connections = sim.Projection(p_in, p_out, random, syn, receptor_type='excitatory')

p_in.record('spikes')
p_out.record('spikes')                    # record spikes from all neurons
p_out[0:2].record(['v', 'w', 'gsyn_exc'])  # record other variables from first two neurons

sim.run(500.0)

spikes_in = p_in.get_data()
data_out = p_out.get_data()

fig_settings = {
    'lines.linewidth': 0.5,
    'axes.linewidth': 0.5,
    'axes.labelsize': 'small',
    'legend.fontsize': 'small',
    'font.size': 8
}
plt.rcParams.update(fig_settings)
plt.figure(1, figsize=(6, 8))
开发者ID:HBPNeurorobotics,项目名称:PyNN,代码行数:30,代码来源:neo_example.py


示例20: weight

# === Define parameters ========================================================

n = 20      # Number of cells
w = 0.1  # synaptic weight (dimensionless)
cell_params = {
    'tau'    : 20.0,   # (ms)
    'refrac' : 2.0,    # (ms)
}
dt         = 0.1           # (ms)
syn_delay  = 1.0           # (ms)
input_rate = 50.0          # (Hz)
simtime    = 1000.0        # (ms)

# === Build the network ========================================================

sim.setup(timestep=dt, max_delay=syn_delay)

cells = sim.Population(n, sim.IntFire1(**cell_params),
                       initial_values={'m': rnd('uniform', (0.0, 1.0))},
                       label="cells")

number = int(2 * simtime * input_rate / 1000.0)
numpy.random.seed(26278342)


def generate_spike_times(i):
    gen = lambda: Sequence(numpy.add.accumulate(numpy.random.exponential(1000.0 / input_rate, size=number)))
    if hasattr(i, "__len__"):
        return [gen() for j in i]
    else:
        return gen()
开发者ID:NeuralEnsemble,项目名称:PyNN,代码行数:31,代码来源:nrn_artificial_cell.py



注:本文中的pyNN.neuron.setup函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python parameters.LazyArray类代码示例发布时间:2022-05-25
下一篇:
Python neuron.run函数代码示例发布时间:2022-05-25
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap