Пример #1
0
def run_sim(ncell):

    print "Cells: ", ncell

    setup0 = time.time()

    sim.setup(timestep=0.1)

    hh_cell_type = sim.HH_cond_exp()

    hh = sim.Population(ncell, hh_cell_type)

    pulse = sim.DCSource(amplitude=0.5, start=20.0, stop=80.0)
    pulse.inject_into(hh)

    hh.record('v')

    setup1 = time.time()

    t0 = time.time()

    sim.run(100.0)

    v = hh.get_data()

    sim.end()

    t1 = time.time()

    setup_total = setup1 - setup0
    run_total = t1 - t0
    print "Setup: ", setup_total
    print "Run: ", run_total
    print "Total sim time: ", setup_total + run_total
    return run_total
def run_simulation(parameters, plot_figure=False):
    """

    """
    import pyNN.neuron as sim

    timestamp = datetime.now()
    model = build_model(**parameters["network"])
    if "full_filename" in parameters["experiment"]:
        xml_file = os.path.splitext(parameters["experiment"]["full_filename"])[0] + ".xml"
    else:
        xml_file = "{}.xml".format(parameters["experiment"]["base_filename"])
    model.write(xml_file)
    print("Exported model to file {}".format(xml_file))

    sim.setup(timestep=parameters["experiment"]["timestep"])

    print("Building network")
    net = Network(sim, xml_file)

    if plot_figure:
        stim = net.populations["Ext"]
        stim[:100].record('spikes')
        exc = net.populations["Exc"]
        exc.sample(50).record("spikes")
        exc.sample(1).record(["nrn_v", "syn_a"])
        inh = net.populations["Inh"]
        inh.sample(50).record("spikes")
        inh.sample(1).record(["nrn_v", "syn_a"])
    else:
        ##all = net.assemblies["All"]
        ##all.sample(parameters["experiment"]["n_record"]).record("spikes")
        net.populations["Ext"].sample(parameters["experiment"]["n_record"]).record("spikes")  ## debugging

    print("Running simulation")
    t_stop = parameters["experiment"]["duration"]
    pb = SimulationProgressBar(t_stop/80, t_stop)
    sim.run(t_stop, callbacks=[pb])

    print("Handling data")
    data = {}
    if plot_figure:
        data["stim"] = stim.get_data().segments[0]
        data["exc"] = exc.get_data().segments[0]
        data["inh"] = inh.get_data().segments[0]
    else:
        if "full_filename" in parameters["experiment"]:
            filename = parameters["experiment"]["full_filename"]
        else:
            filename = "{}_nineml_{:%Y%m%d%H%M%S}.h5".format(parameters["experiment"]["base_filename"],
                                                             timestamp)
        print("Writing data to {}".format(filename))
        ##all.write_data(filename)  ## debugging
        net.populations["Ext"].write_data(filename)

    sim.end()
    return data
def model_network(param_dict):
    """
    This model network consists of a spike source and a neuron (IF_curr_alpha). 
    The spike rate of the source and the weight can be specified in the 
    param_dict. Returns the number of spikes fired during 1000 ms of simulation.
    
    Parameters:
    param_dict - dictionary with keys
                 rate - the rate of the spike source (spikes/second)
                 weight - weight of the connection source -> neuron
                 
    Returns:
    dictionary with keys:
        source_rate - the rate of the spike source
        weight - weight of the connection source -> neuron
        neuron_rate - spike rate of the neuron
    """
    #set up the network
    import pyNN.neuron as sim
    sim.setup(dt=0.01,
              min_delay=1.,
              max_delay=1.,
              debug=False,
              quit_on_end=False)

    weight = param_dict['weight']

    import NeuroTools.stgen as stgen
    stgen = stgen.StGen()
    spiketrain = stgen.poisson_generator(param_dict['rate'], t_stop=1000.)
    source = sim.Population(1, sim.SpikeSourceArray,
                            {'spike_times': spiketrain.spike_times})
    neuron = sim.Population(1, sim.IF_cond_alpha)
    sim.Projection(source,
                   neuron,
                   method=sim.OneToOneConnector(weights=param_dict['weight'],
                                                delays=1.))

    #set recorder
    neuron.record()
    neuron.record_v()

    #run the simulation
    sim.run(1001.)
    sim.end()

    # count the number of spikes
    spikes = neuron.getSpikes()
    numspikes = len(spikes)

    # return everything, including the input parameters
    return {
        'source_rate': param_dict['rate'],
        'weight': param_dict['weight'],
        'neuron_rate': numspikes
    }
def run_simulation(parameters, plot_figure=False):
    """

    """
    timestamp = datetime.now()
    model = build_model(**parameters["network"])
    if "full_filename" in parameters["experiment"]:
        xml_file = parameters["experiment"]["full_filename"].replace(
            ".h5", ".xml")
    else:
        xml_file = "{}.xml".format(parameters["experiment"]["base_filename"])
    model.write(xml_file)
    print("Exported model to file {}".format(xml_file))

    sim.setup()

    print("Building network")
    net = Network(sim, xml_file)

    if plot_figure:
        stim = net.populations["Ext"]
        stim[:100].record('spikes')
        exc = net.populations["Exc"]
        exc.sample(50).record("spikes")
        exc.sample(3).record(["nrn_v", "syn_a"])
        inh = net.populations["Inh"]
        inh.sample(50).record("spikes")
        inh.sample(3).record(["nrn_v", "syn_a"])
    else:
        all = net.assemblies["All"]
        all.sample(parameters["experiment"]["n_record"]).record("spikes")

    print("Running simulation")
    t_stop = parameters["experiment"]["duration"]
    pb = SimulationProgressBar(t_stop / 80, t_stop)
    sim.run(t_stop, callbacks=[pb])

    print("Handling data")
    data = {}
    if plot_figure:
        data["stim"] = stim.get_data().segments[0]
        data["exc"] = exc.get_data().segments[0]
        data["inh"] = inh.get_data().segments[0]
    else:
        if "full_filename" in parameters["experiment"]:
            filename = parameters["experiment"]["full_filename"]
        else:
            filename = "{}_nineml_{:%Y%m%d%H%M%S}.h5".format(
                parameters["experiment"]["base_filename"], timestamp)
        print("Writing data to {}".format(filename))
        all.write_data(filename)

    sim.end()
    return data
def model_network(param_dict):
    """
    This model network consists of a spike source and a neuron (IF_curr_alpha). 
    The spike rate of the source and the weight can be specified in the 
    param_dict. Returns the number of spikes fired during 1000 ms of simulation.
    
    Parameters:
    param_dict - dictionary with keys
                 rate - the rate of the spike source (spikes/second)
                 weight - weight of the connection source -> neuron
                 
    Returns:
    dictionary with keys:
        source_rate - the rate of the spike source
        weight - weight of the connection source -> neuron
        neuron_rate - spike rate of the neuron
    """ 
    #set up the network
    import pyNN.neuron as sim
    sim.setup(dt = 0.01,  min_delay = 1.,  max_delay = 1.,  debug = False,  
              quit_on_end = False)
    
    weight = param_dict['weight']
    
    import NeuroTools.stgen as stgen
    stgen = stgen.StGen()
    spiketrain = stgen.poisson_generator(param_dict['rate'], t_stop = 1000.)
    source = sim.Population(1, sim.SpikeSourceArray,  
                            {'spike_times':spiketrain.spike_times})
    neuron = sim.Population(1, sim.IF_cond_alpha)
    sim.Projection(source, neuron, 
                   method = sim.OneToOneConnector(weights = param_dict['weight'], 
                                                  delays = 1.))
    
    #set recorder
    neuron.record()
    neuron.record_v()
    
    #run the simulation
    sim.run(1001.)
    sim.end()
    
    # count the number of spikes
    spikes = neuron.getSpikes()
    numspikes = len(spikes)
    
    # return everything, including the input parameters
    return {'source_rate':param_dict['rate'], 
            'weight':param_dict['weight'], 
            'neuron_rate':numspikes }
def run_simulation(parameters, plot_figure=False):
    """

    """
    import pyNN.neuron as sim

    timestamp = datetime.now()
    model = build_model(**parameters["network"])
    if "full_filename" in parameters["experiment"]:
        xml_file = parameters["experiment"]["full_filename"].replace(
            ".h5", ".xml")
    else:
        xml_file = "{}.xml".format(parameters["experiment"]["base_filename"])
    model.write(xml_file)
    print("Exported model to file {}".format(xml_file))

    sim.setup()

    print("Building network")
    net = Network(sim, xml_file)

    stim = net.populations["Ext"]
    stim.record('spikes')
    exc = net.populations["Exc"]
    exc.record("spikes")
    exc[:3].record(["nrn_v", "syn_a"])

    print("Running simulation")
    t_stop = parameters["experiment"]["duration"]
    pb = SimulationProgressBar(t_stop / 80, t_stop)
    sim.run(t_stop, callbacks=[pb])

    print("Handling data")
    data = {}
    if plot_figure:
        data["stim"] = stim.get_data().segments[0]
        data["exc"] = exc.get_data().segments[0]
        data["exc"].annotate(simulator="lib9ML with pyNN.neuron")
    else:
        if "full_filename" in parameters["experiment"]:
            filename = parameters["experiment"]["full_filename"]
        else:
            filename = "{}_nineml_{:%Y%m%d%H%M%S}.pkl".format(
                parameters["experiment"]["base_filename"], timestamp)
        print("Writing data to {}".format(filename))
        exc.write_data(filename)

    sim.end()
    return data
def run_simulation(parameters, plot_figure=False):
    """

    """
    import pyNN.neuron as sim

    timestamp = datetime.now()
    model = build_model(**parameters["network"])
    if "full_filename" in parameters["experiment"]:
        xml_file = parameters["experiment"]["full_filename"].replace(".h5", ".xml")
    else:
        xml_file = "{}.xml".format(parameters["experiment"]["base_filename"])
    model.write(xml_file)
    print("Exported model to file {}".format(xml_file))

    sim.setup()

    print("Building network")
    net = Network(sim, xml_file)

    stim = net.populations["Ext"]
    stim.record('spikes')
    exc = net.populations["Exc"]
    exc.record("spikes")
    n_record = int(parameters["experiment"]["n_record"])
    exc[:n_record].record(["nrn_v", "syn_a"])

    print("Running simulation")
    t_stop = parameters["experiment"]["duration"]
    pb = SimulationProgressBar(t_stop/80, t_stop)
    sim.run(t_stop, callbacks=[pb])

    print("Handling data")
    data = {}
    if plot_figure:
        data["stim"] = stim.get_data().segments[0]
        data["exc"] = exc.get_data().segments[0]
        data["exc"].annotate(simulator="lib9ML with pyNN.neuron")
    else:
        if "full_filename" in parameters["experiment"]:
            filename = parameters["experiment"]["full_filename"]
        else:
            filename = "{}_nineml_{:%Y%m%d%H%M%S}.pkl".format(parameters["experiment"]["base_filename"],
                                                              timestamp)
        print("Writing data to {}".format(filename))
        exc.write_data(filename)

    sim.end()
    return data
Пример #8
0
def run_simulation(parameters, plot_figure=False):
    """

    """
    timestamp = datetime.now()
    dt = 0.1

    seed = parameters["experiment"]["seed"]
    sim.setup(timestep=dt)

    print("Building network")
    stim, exc, inh = build_network(sim, seed=seed, **parameters["network"])

    if plot_figure:
        stim[:100].record('spikes')
        exc.sample(50).record("spikes")
        exc.sample(3).record("nrn_v")
        inh.sample(50).record("spikes")
        inh.sample(3).record("nrn_v")
    else:
        all = exc + inh
        all.sample(parameters["experiment"]["n_record"]).record("spikes")

    print("Running simulation")
    t_stop = parameters["experiment"]["duration"]
    pb = SimulationProgressBar(t_stop/80, t_stop)
    sim.run(t_stop, callbacks=[pb])

    print("Handling data")
    data = {}
    if plot_figure:
        data["stim"] = stim.get_data().segments[0]
        data["exc"] = exc.get_data().segments[0]
        data["inh"] = inh.get_data().segments[0]
    else:
        if "full_filename" in parameters["experiment"]:
            filename = parameters["experiment"]["full_filename"]
        else:
            filename = "{}_ninemlpartial_{:%Y%m%d%H%M%S}.h5".format(parameters["experiment"]["base_filename"],
                                                                              timestamp)
        print("Writing data to {}".format(filename))
        all.write_data(filename)

    sim.end()
    return data
Пример #9
0
import pyNN.neuron as sim  # can of course replace `nest` with `neuron`, `brian`, etc.
import matplotlib.pyplot as plt
from quantities import nA

sim.setup()

cell = sim.Population(1, sim.HH_cond_exp())
step_current = sim.DCSource(start=20.0, stop=80.0)
step_current.inject_into(cell)

cell.record('v')

for amp in (-0.2, -0.1, 0.0, 0.1, 0.2):
    step_current.amplitude = amp
    sim.run(100.0)
    sim.reset(annotations={"amplitude": amp * nA})

data = cell.get_data()

sim.end()

for segment in data.segments:
    vm = segment.analogsignals[0]
    plt.plot(vm.times, vm,
             label=str(segment.annotations["amplitude"]))
plt.legend(loc="upper left")
plt.xlabel("Time (%s)" % vm.times.units._dimensionality)
plt.ylabel("Membrane potential (%s)" % vm.units._dimensionality)

plt.show()
Пример #10
0
cells.record()

sim.run(100.0)

cells.recorders['iaf_V'].write("Results/nineml_neuron.V", filter=[cells[0]])
cells.recorders['nmda_g'].write("Results/nineml_neuron.g_nmda", filter=[cells[0]])
cells.recorders['cobaExcit_g'].write("Results/nineml_neuron.g_cobaExcit", filter=[cells[0]])


t = cells.recorders['iaf_V'].get()[:, 1]
v = cells.recorders['iaf_V'].get()[:, 2]
gNMDA = cells.recorders['nmda_g'].get()[:, 2]
gExcit = cells.recorders['cobaExcit_g'].get()[:, 2]

import pylab

pylab.subplot(211)
pylab.plot(t, v)
pylab.ylabel('voltage [mV]')
pylab.subplot(212)
pylab.plot(t, gNMDA, label='g-NMDA')
pylab.plot(t, gExcit, label='g-Excitatory Synapse')
pylab.ylabel('conductance [nS]')
pylab.xlabel('t [ms]')
pylab.legend()

pylab.suptitle("From Tree-Model Pathway")
pylab.show()

sim.end()
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()
def run(plot_and_show=True):
    import sys
    from os.path import abspath, realpath, join
    import numpy
    import nineml

    root = abspath(join(realpath(nineml.__path__[0]), "../../.."))
    sys.path.append(join(root, "lib9ml/python/examples/AL"))
    sys.path.append(join(root, "code_generation/nmodl"))     
    sys.path.append(join(root, "code_generation/nest2"))       
               

    #from nineml.abstraction_layer.example_models import  get_hierachical_iaf_3coba
    from nineml.abstraction_layer.testing_utils import TestableComponent
    from nineml.abstraction_layer.flattening import  ComponentFlattener

    import pyNN.neuron as sim
    import pyNN.neuron.nineml as pyNNml

    from pyNN.utility import init_logging


    init_logging(None, debug=True)
    sim.setup(timestep=0.1, min_delay=0.1)


    #test_component = get_hierachical_iaf_3coba()
    test_component = TestableComponent('hierachical_iaf_3coba')()

    from nineml.abstraction_layer.writers import DotWriter
    DotWriter.write(test_component, 'test1.dot')
    

    from nineml.abstraction_layer.writers import XMLWriter
    XMLWriter.write(test_component, 'iaf_3coba.xml')


    celltype_cls = pyNNml.nineml_celltype_from_model(
                                            name = "iaf_3coba",
                                            nineml_model = test_component,
                                            synapse_components = [
                                                pyNNml.CoBaSyn( namespace='AMPA',  weight_connector='q' ),
                                                pyNNml.CoBaSyn( namespace='GABAa',  weight_connector='q' ),
                                                pyNNml.CoBaSyn( namespace='GABAb',  weight_connector='q' ),
                                                       ]
                                            )

    parameters = {
        'iaf.cm': 1.0,
        'iaf.gl': 50.0,
        'iaf.taurefrac': 5.0,
        'iaf.vrest': -65.0,
        'iaf.vreset': -65.0,
        'iaf.vthresh': -50.0,
        'AMPA.tau': 2.0,
        'GABAa.tau': 5.0,
        'GABAb.tau': 50.0,
        'AMPA.vrev': 0.0,
        'GABAa.vrev': -70.0,
        'GABAb.vrev': -95.0,

    }


    parameters = ComponentFlattener.flatten_namespace_dict( parameters )


    cells = sim.Population(1, celltype_cls, parameters)
    cells.initialize('iaf_V', parameters['iaf_vrest'])
    cells.initialize('tspike', -1e99) # neuron not refractory at start
    cells.initialize('regime', 1002) # temporary hack

    input = sim.Population(3, sim.SpikeSourceArray)

    numpy.random.seed(12345)
    input[0].spike_times = numpy.add.accumulate(numpy.random.exponential(1000.0/100.0, size=1000))
    input[1].spike_times = numpy.add.accumulate(numpy.random.exponential(1000.0/20.0, size=1000))
    input[2].spike_times = numpy.add.accumulate(numpy.random.exponential(1000.0/50.0, size=1000))

    connector = sim.OneToOneConnector(weights=1.0, delays=0.5)


    conn = [sim.Projection(input[0:1], cells, connector, target='AMPA'),
            sim.Projection(input[1:2], cells, connector, target='GABAa'),
            sim.Projection(input[2:3], cells, connector, target='GABAb')]


    cells._record('iaf_V')
    cells._record('AMPA_g')
    cells._record('GABAa_g')
    cells._record('GABAb_g')
    cells.record()

    sim.run(100.0)

    cells.recorders['iaf_V'].write("Results/nineml_neuron.V", filter=[cells[0]])
    cells.recorders['AMPA_g'].write("Results/nineml_neuron.g_exc", filter=[cells[0]])
    cells.recorders['GABAa_g'].write("Results/nineml_neuron.g_gabaA", filter=[cells[0]])
    cells.recorders['GABAb_g'].write("Results/nineml_neuron.g_gagaB", filter=[cells[0]])


    t = cells.recorders['iaf_V'].get()[:,1]
    v = cells.recorders['iaf_V'].get()[:,2]
    gInhA = cells.recorders['GABAa_g'].get()[:,2]
    gInhB = cells.recorders['GABAb_g'].get()[:,2]
    gExc = cells.recorders['AMPA_g'].get()[:,2]

    if plot_and_show:
        import pylab
        pylab.subplot(211)
        pylab.plot(t,v)
        pylab.ylabel('voltage [mV]')
        pylab.suptitle("AMPA, GABA_A, GABA_B")
        pylab.subplot(212)
        pylab.plot(t,gInhA,label='GABA_A')
        pylab.plot(t,gInhB, label='GABA_B')
        pylab.plot(t,gExc, label='AMPA')
        pylab.ylabel('conductance [nS]')
        pylab.xlabel('t [ms]')
        pylab.legend()

        pylab.show()

    sim.end()
def t4():
    print 'Loading Forth XML File (iaf-2coba-Model)'
    print '----------------------------------------'
    component = readers.XMLReader.read_component(Join(tenml_dir,
                                                      'iaf_2coba.10ml'),
                                                 component_name='iaf')
    writers.XMLWriter.write(
        component,
        '/tmp/nineml_toxml4.xml',
    )
    model = readers.XMLReader.read_component(Join(tenml_dir, 'iaf_2coba.10ml'))

    from nineml.abstraction_layer.flattening import flatten
    from nineml.abstraction_layer.dynamics.utils.modifiers import (
        DynamicsModifier)

    flatcomponent = flatten(model, componentname='iaf_2coba')
    DynamicsModifier.close_analog_port(component=flatcomponent,
                                       port_name='iaf_iSyn',
                                       value='0')

    writers.XMLWriter.write(flatcomponent, '/tmp/nineml_out_iaf_2coba.9ml')

    import pyNN.neuron as sim
    from pyNN.utility import init_logging

    init_logging(None, debug=True)
    sim.setup(timestep=0.1, min_delay=0.1)
    print 'Attempting to simulate From Model:'
    print '----------------------------------'
    celltype_cls = pyNNml.nineml_celltype_from_model(
        name="iaf_2coba",
        nineml_model=flatcomponent,
        synapse_components=[
            pyNNml.CoBaSyn(namespace='cobaExcit', weight_connector='q'),
            pyNNml.CoBaSyn(namespace='cobaInhib', weight_connector='q'),
        ])

    parameters = {
        'iaf.cm': 1.0,
        'iaf.gl': 50.0,
        'iaf.taurefrac': 5.0,
        'iaf.vrest': -65.0,
        'iaf.vreset': -65.0,
        'iaf.vthresh': -50.0,
        'cobaExcit.tau': 2.0,
        'cobaInhib.tau': 5.0,
        'cobaExcit.vrev': 0.0,
        'cobaInhib.vrev': -70.0,
    }

    parameters = ComponentFlattener.flatten_namespace_dict(parameters)

    cells = sim.Population(1, celltype_cls, parameters)
    cells.initialize('iaf_V', parameters['iaf_vrest'])
    cells.initialize('tspike', -1e99)  # neuron not refractory at start
    cells.initialize('regime', 1002)  # temporary hack

    input = sim.Population(2, sim.SpikeSourcePoisson, {'rate': 100})

    connector = sim.OneToOneConnector(weights=1.0, delays=0.5)

    conn = [
        sim.Projection(input[0:1], cells, connector, target='cobaExcit'),
        sim.Projection(input[1:2], cells, connector, target='cobaInhib')
    ]

    cells._record('iaf_V')
    cells._record('cobaExcit_g')
    cells._record('cobaInhib_g')
    cells._record('cobaExcit_I')
    cells._record('cobaInhib_I')
    cells.record()

    sim.run(100.0)

    cells.recorders['iaf_V'].write("Results/nineml_neuron.V",
                                   filter=[cells[0]])
    cells.recorders['cobaExcit_g'].write("Results/nineml_neuron.g_exc",
                                         filter=[cells[0]])
    cells.recorders['cobaInhib_g'].write("Results/nineml_neuron.g_inh",
                                         filter=[cells[0]])
    cells.recorders['cobaExcit_I'].write("Results/nineml_neuron.g_exc",
                                         filter=[cells[0]])
    cells.recorders['cobaInhib_I'].write("Results/nineml_neuron.g_inh",
                                         filter=[cells[0]])

    t = cells.recorders['iaf_V'].get()[:, 1]
    v = cells.recorders['iaf_V'].get()[:, 2]
    gInh = cells.recorders['cobaInhib_g'].get()[:, 2]
    gExc = cells.recorders['cobaExcit_g'].get()[:, 2]
    IInh = cells.recorders['cobaInhib_I'].get()[:, 2]
    IExc = cells.recorders['cobaExcit_I'].get()[:, 2]

    import pylab
    pylab.subplot(311)
    pylab.ylabel('Voltage')
    pylab.plot(t, v)

    pylab.subplot(312)
    pylab.ylabel('Conductance')
    pylab.plot(t, gInh)
    pylab.plot(t, gExc)

    pylab.subplot(313)
    pylab.ylabel('Current')
    pylab.plot(t, IInh)
    pylab.plot(t, IExc)

    pylab.suptitle("From Tree-Model Pathway")
    pylab.show()

    sim.end()
Пример #14
0
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()
Пример #15
0
def run(plot_and_show=True):
    import sys
    from os.path import abspath, realpath, join
    import numpy
    import nineml

    root = abspath(join(realpath(nineml.__path__[0]), "../../.."))
    sys.path.append(join(root, "lib9ml/python/examples/AL"))
    sys.path.append(join(root, "code_generation/nmodl"))
    sys.path.append(join(root, "code_generation/nest2"))

    #from nineml.abstraction_layer.example_models import  get_hierachical_iaf_3coba
    from nineml.abstraction_layer.testing_utils import TestableComponent
    from nineml.abstraction_layer.flattening import ComponentFlattener

    import pyNN.neuron as sim
    import pyNN.neuron.nineml as pyNNml

    from pyNN.utility import init_logging

    init_logging(None, debug=True)
    sim.setup(timestep=0.1, min_delay=0.1)

    #test_component = get_hierachical_iaf_3coba()
    test_component = TestableComponent('hierachical_iaf_3coba')()

    from nineml.abstraction_layer.writers import DotWriter
    DotWriter.write(test_component, 'test1.dot')

    from nineml.abstraction_layer.writers import XMLWriter
    XMLWriter.write(test_component, 'iaf_3coba.xml')

    celltype_cls = pyNNml.nineml_celltype_from_model(
        name="iaf_3coba",
        nineml_model=test_component,
        synapse_components=[
            pyNNml.CoBaSyn(namespace='AMPA', weight_connector='q'),
            pyNNml.CoBaSyn(namespace='GABAa', weight_connector='q'),
            pyNNml.CoBaSyn(namespace='GABAb', weight_connector='q'),
        ])

    parameters = {
        'iaf.cm': 1.0,
        'iaf.gl': 50.0,
        'iaf.taurefrac': 5.0,
        'iaf.vrest': -65.0,
        'iaf.vreset': -65.0,
        'iaf.vthresh': -50.0,
        'AMPA.tau': 2.0,
        'GABAa.tau': 5.0,
        'GABAb.tau': 50.0,
        'AMPA.vrev': 0.0,
        'GABAa.vrev': -70.0,
        'GABAb.vrev': -95.0,
    }

    parameters = ComponentFlattener.flatten_namespace_dict(parameters)

    cells = sim.Population(1, celltype_cls, parameters)
    cells.initialize('iaf_V', parameters['iaf_vrest'])
    cells.initialize('tspike', -1e99)  # neuron not refractory at start
    cells.initialize('regime', 1002)  # temporary hack

    input = sim.Population(3, sim.SpikeSourceArray)

    numpy.random.seed(12345)
    input[0].spike_times = numpy.add.accumulate(
        numpy.random.exponential(1000.0 / 100.0, size=1000))
    input[1].spike_times = numpy.add.accumulate(
        numpy.random.exponential(1000.0 / 20.0, size=1000))
    input[2].spike_times = numpy.add.accumulate(
        numpy.random.exponential(1000.0 / 50.0, size=1000))

    connector = sim.OneToOneConnector(weights=1.0, delays=0.5)

    conn = [
        sim.Projection(input[0:1], cells, connector, target='AMPA'),
        sim.Projection(input[1:2], cells, connector, target='GABAa'),
        sim.Projection(input[2:3], cells, connector, target='GABAb')
    ]

    cells._record('iaf_V')
    cells._record('AMPA_g')
    cells._record('GABAa_g')
    cells._record('GABAb_g')
    cells.record()

    sim.run(100.0)

    cells.recorders['iaf_V'].write("Results/nineml_neuron.V",
                                   filter=[cells[0]])
    cells.recorders['AMPA_g'].write("Results/nineml_neuron.g_exc",
                                    filter=[cells[0]])
    cells.recorders['GABAa_g'].write("Results/nineml_neuron.g_gabaA",
                                     filter=[cells[0]])
    cells.recorders['GABAb_g'].write("Results/nineml_neuron.g_gagaB",
                                     filter=[cells[0]])

    t = cells.recorders['iaf_V'].get()[:, 1]
    v = cells.recorders['iaf_V'].get()[:, 2]
    gInhA = cells.recorders['GABAa_g'].get()[:, 2]
    gInhB = cells.recorders['GABAb_g'].get()[:, 2]
    gExc = cells.recorders['AMPA_g'].get()[:, 2]

    if plot_and_show:
        import pylab
        pylab.subplot(211)
        pylab.plot(t, v)
        pylab.ylabel('voltage [mV]')
        pylab.suptitle("AMPA, GABA_A, GABA_B")
        pylab.subplot(212)
        pylab.plot(t, gInhA, label='GABA_A')
        pylab.plot(t, gInhB, label='GABA_B')
        pylab.plot(t, gExc, label='AMPA')
        pylab.ylabel('conductance [nS]')
        pylab.xlabel('t [ms]')
        pylab.legend()

        pylab.show()

    sim.end()
	STN_LFP_Block = neo.Block(name='STN_LFP')
	STN_LFP_seg = neo.Segment(name='segment_0')
	STN_LFP_Block.segments.append(STN_LFP_seg)
	STN_LFP_signal = neo.AnalogSignal(STN_LFP, units='mV', t_start=0*pq.ms, sampling_rate=pq.Quantity(simulator.state.dt, '1/ms'))
	STN_LFP_seg.analogsignals.append(STN_LFP_signal)
	
	w = neo.io.NeoMatlabIO(filename="/Simulation_Output_Results/"+simulation_label+"/STN_LFP.mat") 
	w.write_block(STN_LFP_Block)
	
	# Write LFP AMPA and GABAa conmponents to file
	STN_LFP_AMPA_Block = neo.Block(name='STN_LFP_AMPA')
	STN_LFP_AMPA_seg = neo.Segment(name='segment_0')
	STN_LFP_AMPA_Block.segments.append(STN_LFP_AMPA_seg)
	STN_LFP_AMPA_signal = neo.AnalogSignal(STN_LFP_AMPA, units='mV', t_start=0*pq.ms, sampling_rate=pq.Quantity(simulator.state.dt, '1/ms'))
	STN_LFP_AMPA_seg.analogsignals.append(STN_LFP_AMPA_signal)
	w = neo.io.NeoMatlabIO(filename="/Simulation_Output_Results/"+simulation_label+"/STN_LFP_AMPA.mat") 
	w.write_block(STN_LFP_AMPA_Block)
	
	STN_LFP_GABAa_Block = neo.Block(name='STN_LFP_GABAa')
	STN_LFP_GABAa_seg = neo.Segment(name='segment_0')
	STN_LFP_GABAa_Block.segments.append(STN_LFP_GABAa_seg)
	STN_LFP_GABAa_signal = neo.AnalogSignal(STN_LFP_GABAa, units='mV', t_start=0*pq.ms, sampling_rate=pq.Quantity(simulator.state.dt, '1/ms'))
	STN_LFP_GABAa_seg.analogsignals.append(STN_LFP_GABAa_signal)
	w = neo.io.NeoMatlabIO(filename="/Simulation_Output_Results/"+simulation_label+"/STN_LFP_GABAa.mat") 
	w.write_block(STN_LFP_GABAa_Block)
	"""

    print("Steady State Simulation Done!")

    end()
Пример #17
0
def std_pynn_simulation(test_component, parameters, initial_values,
                        synapse_components, records, plot=True, sim_time=100.,
                        synapse_weights=1.0, syn_input_rate=100):

    from nineml.abstraction_layer.flattening import ComponentFlattener

    import pyNN.neuron as sim
    import pyNN.neuron.nineml as pyNNml
    from pyNN.neuron.nineml import CoBaSyn

    from pyNN.utility import init_logging

    init_logging(None, debug=True)
    sim.setup(timestep=0.01, min_delay=0.1)

    synapse_components_ML = [CoBaSyn(namespace=ns,  weight_connector=wc)
                             for (ns, wc) in synapse_components]

    celltype_cls = pyNNml.nineml_celltype_from_model(
        name=test_component.name,
        nineml_model=test_component,
        synapse_components=synapse_components_ML,
    )

    parameters = ComponentFlattener.flatten_namespace_dict(parameters)
    initial_values = ComponentFlattener.flatten_namespace_dict(initial_values)

    cells = sim.Population(1, celltype_cls, parameters)

    # Set Initial Values:
    for state, state_initial_value in initial_values.iteritems():
        cells.initialize(state, state_initial_value)

    # For each synapse type, create a spike source:
    if synapse_components:
        input = sim.Population(
            len(synapse_components), sim.SpikeSourcePoisson,
            {'rate': syn_input_rate})
        connector = sim.OneToOneConnector(weights=synapse_weights, delays=0.5)

        conn = []
        for i, (ns, weight_connector) in enumerate(synapse_components):
            proj = sim.Projection(input[i:i + 1], cells, connector, target=ns),
            conn.append(proj)

    # Setup the Records:
    for record in records:
        cells.record(record.what)

    cells.record('spikes')

    # Run the simulation:
    sim.run(sim_time)

    if len(records) == 0:
        assert False

    # Write the Results to a file:
    cells.write_data("Results/nineml.pkl")

    # Plot the values:

    results = cells.get_data().segments[0]

    # Create a list of the tags:
    tags = []
    for record in records:
        if not record.tag in tags:
            tags.append(record.tag)

    # Plot the graphs:
    if plot:
        import pylab
        nGraphs = len(tags)

        # Plot the Records:
        for graphIndex, tag in enumerate(tags):
            pylab.subplot(nGraphs, 1, graphIndex + 1)

            for r in records:
                if r.tag != tag:
                    continue
                trace = results.filter(name=r.what)[0]
                pylab.plot(trace.times, trace, label=r.label)

            pylab.ylabel(tag)
            pylab.legend()

        # Plot the spikes:
        # pylab.subplot(nGraphs,1, len(tags)+1)
        # t_spikes = cells[0:1].getSpikes()[:1]
        # pylab.plot( [1,3],[1,3],'x'  )
        # print t_spikes
        # if t_spikes:
        #    pylab.scatter( t_spikes, t_spikes )

        # Add the X axis to the last plot:
        pylab.xlabel('t [ms]')

        # pylab.suptitle("From Tree-Model Pathway")
        pylab.show()

    sim.end()

    return results
Пример #18
0
        self.assertEqual(native_cell.esyn.e, native_cell.e_e)
        self.assertEqual(native_cell.esyn.U, U)
        self.assertRaises(AttributeError, lambda x: native_cell.isyn.U, None)
        native_cell.use_Tsodyks_Markram_synapses(
            'inhibitory', U, tau_rec, tau_facil, u0)
        self.assertEqual(native_cell.isyn.tau, native_cell.tau_i)
        self.assertEqual(native_cell.isyn.e, native_cell.e_i)
        self.assertEqual(native_cell.isyn.U, U)

class LoadMechanismsTest(unittest.TestCase):
    
    def test_load_mechanisms(self):
        self.assertRaises(Exception, neuron.simulator.load_mechanisms, path="/dev/null")    

        
class SetupTest(unittest.TestCase):
    
    def test_cvode(self):
        neuron.setup(use_cvode=True)
        
        
if __name__ == "__main__":
    if '-python' in sys.argv:
        sys.argv.remove('-python')
    for arg in sys.argv:
        if 'bin/nrniv' in arg:
            sys.argv.remove(arg)
    neuron.setup()
    unittest.main()
    neuron.end()
    
Пример #19
0
#cell_params = {'a':0.1779222, 'b':-5e-09, 'c':-59.52801, 'd':0.1531787, v_init=-'73.32355','i_offset':0}#, u_init, i_offset}

#pop = p.Population(NETSIZE, p.IF_curr_exp(i_offset=0))
neuron_type = p.Izhikevich()  #cell_params)
pop = p.Population(NETSIZE, neuron_type)
#for ind in pop:
print(p.connect)

pop.record("spikes")
p.run(100)
pop.set(i_offset=1.0)
p.run(100)
pop.set(i_offset=0.0)
p.run(100)
spikes = pop.get_data("spikes")
p.end()

#p.setup(1.0)
#pop = sim.Population(100, sim.IZKCurrExp(cell_params))

print(spikes)

# In[ ]:

#nldf['From']

#nldf.index('Granule')
#df = nldf[nldf['Name']==3]

#you'll likely need a user for authentication
#user = '******'