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
    }
Example #2
0
def build_network(sim, order=1000, epsilon=0.1, delay=1.5, J=0.1, theta=20.0,
                  tau=20.0, tau_syn=0.1, tau_refrac=2.0, v_reset=10.0,
                  R=1.5, g=5, eta=2, seed=None):

    NE = 4 * order
    NI = 1 * order
    CE = int(epsilon * NE)  # number of excitatory synapses per neuron
    CI = int(epsilon * NI)  # number of inhibitory synapses per neuron

    CMem = tau/R

    J_unit = psp_height(tau, R, tau_syn)
    J_ex  = J / J_unit
    J_in  = -g * J_ex

    nu_th = theta / (J_ex * CE * R * tau_syn)
    nu_ex = eta * nu_th
    p_rate = 1000.0 * nu_ex * CE

    assert seed is not None
    rng = NumpyRNG(seed)

    neuron_params = {
        "nrn_tau": tau,
        "nrn_v_threshold": theta,
        "nrn_refractory_period": tau_refrac,
        "nrn_v_reset": v_reset,
        "nrn_R": R,
        "syn_tau": tau_syn
    }

    celltype = Dynamics(name='iaf',
                        subnodes={'nrn': read("sources/BrunelIaF.xml")['BrunelIaF'],
                                  'syn': read("sources/AlphaPSR.xml")['AlphaPSR']})
    celltype.connect_ports('syn.i_synaptic', 'nrn.i_synaptic')

    exc = sim.Population(NE, nineml_cell_type('BrunelIaF', celltype, {'syn': 'syn_weight'})(**neuron_params))
    inh = sim.Population(NI, nineml_cell_type('BrunelIaF', celltype, {'syn': 'syn_weight'})(**neuron_params))
    all = exc + inh
    all.initialize(v=RandomDistribution('uniform', (0.0, theta), rng=rng))

    stim = sim.Population(NE + NI, nineml_cell_type('Poisson', read("sources/Poisson.xml")['Poisson'], {})(rate=p_rate))

    print("Connecting network")

    exc_synapse = sim.StaticSynapse(weight=J_ex, delay=delay)
    inh_synapse = sim.StaticSynapse(weight=J_in, delay=delay)

    input_connections = sim.Projection(stim, all, sim.OneToOneConnector(), exc_synapse, receptor_type="syn")
    exc_connections = sim.Projection(exc, all, sim.FixedNumberPreConnector(n=CE), exc_synapse, receptor_type="syn")  # check is Pre not Post
    inh_connections = sim.Projection(inh, all, sim.FixedNumberPreConnector(n=CI), inh_synapse, receptor_type="syn")

    return stim, exc, inh
Example #3
0
 def testSaveAndLoad(self):
     prj1 = neuron.Projection(self.source33, self.target33, neuron.OneToOneConnector())
     prj1.setDelays(1)
     prj1.setWeights(1.234)
     prj1.saveConnections("connections.tmp", gather=False)
     if neuron.num_processes() > 1:
         distributed = True
     else:
         distributed = False
     prj2 = neuron.Projection(self.source33, self.target33, neuron.FromFileConnector("connections.tmp",
                                                                                     distributed=distributed))
     w1 = []; w2 = []; d1 = []; d2 = []
     # For a connections scheme saved and reloaded, we test if the connections, their weights and their delays
     # are equal.
     for c1,c2 in zip(prj1.connections, prj2.connections):
         w1.append(c1.nc.weight[0])
         w2.append(c2.nc.weight[0])
         d1.append(c1.nc.delay)
         d2.append(c2.nc.delay)
     assert (w1 == w2), 'w1 = %s\nw2 = %s' % (w1, w2)
     assert (d1 == d2), 'd1 = %s\nd2 = %s' % (d1, d2)
Example #4
0
]

inh_spike_times = [
    6000 + 750,
    6000 + 1000,
    6000 + 1020,
    6000 + 1040,
    6000 + 1250,
]

stimulus_exc = sim.Population(1, sim.SpikeSourceArray,
                              {'spike_times': exc_spike_times})
stimulus_inh = sim.Population(1, sim.SpikeSourceArray,
                              {'spike_times': inh_spike_times})

connector = sim.OneToOneConnector()
ext_syn = sim.StaticSynapse(weight=2.925)

projections = [
    sim.Projection(stimulus_exc,
                   top_3_hubs,
                   connector,
                   ext_syn,
                   receptor_type='excitatory'),
    sim.Projection(stimulus_inh,
                   top_3_hubs,
                   connector,
                   ext_syn,
                   receptor_type='inhibitory'),
]
Example #5
0
    'nmda.beta': 3.57  # mM
}


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(1, sim.SpikeSourcePoisson, {'rate': 100})

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


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


cells._record('iaf_V')
cells._record('nmda_g')
cells._record('cobaExcit_g')
cells.record()

sim.run(100.0)
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()
Example #7
0
# some random seeds which are different everytime
# and different for each node.
#seeds = numpy.arange(numberOfNodes) + int((time.time()*100)%2**32)
# seeds which are same every time, different for each node
seeds = numpy.arange(numberOfNodes)

# bcast, as we can't be sure each node has the same time, and therefore
# different seeds.  This way, all nodes get the list from rank=0.
seeds = MPI.COMM_WORLD.bcast(seeds)

#rng = NumpyRNG(seed=seeds[rank], parallel_safe=False, rank=rank,
#               num_processes=numberOfNodes)

#nest.SetKernelStatus({'rng_seeds': list(seeds)})

myconn = sim.OneToOneConnector(weights=globalWeight, delays=dt)

prjE_E = sim.Projection(poissonE_E, popE, method=myconn, target='excitatory')
prjE_I = sim.Projection(poissonE_I, popI, method=myconn, target='excitatory')

prjI_E = sim.Projection(poissonI_E, popE, method=myconn, target='inhibitory')
prjI_I = sim.Projection(poissonI_I, popI, method=myconn, target='inhibitory')

## Record the spikes ##
popE.record(to_file=False)
popI.record(to_file=False)
printTimer("Time for setup part")


###################### RUN PART ###########################
## Run the simulation without inter-connection ##
Example #8
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()
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
Example #10
0
 def testOneToOne(self):
     """For all connections created with "OneToOne" ..."""
     prj = neuron.Projection(self.source33, self.target33, neuron.OneToOneConnector())
     assert len(prj.connections) == len(self.target33.local_cells), prj.connections
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()