Example #1
0
import pyNN.brian as sim
from pyNN.random import (NumpyRNG, RandomDistribution)
#import matplotlib.pyplot as plt
import numpy as np

sim.setup(timestep=0.01)
'''
Synapse types
'''
#=====Fixed synaptic weight=====
syn = sim.StaticSynapse(weight=0.04, delay=0.5)
#random
w = RandomDistribution('gamma', [10, 0.004], rng=NumpyRNG(seed=4242))
syn = sim.StaticSynapse(weight=w, delay=0.5)
#specify parameters as a function of the distance- um
syn = sim.StaticSynapse(weight=w, delay="0.2 + 0.01*d")

#=====Short-term synaptic plasticity=====
depressing_synapse = sim.TsodyksMarkramSynapse(weight=w,
                                               delay=0.2,
                                               U=0.5,
                                               tau_rec=800.0,
                                               tau_facil=0.0)
tau_rec = RandomDistribution('normal', [100.0, 10.0])
facilitating_synapse = sim.TsodyksMarkramSynapse(weight=w,
                                                 delay=0.5,
                                                 U=0.04,
                                                 tau_rec=tau_rec)

#=====Spike-timing-dependent plasticity=====
def do_run(Neurons, sim_time, record, seed=None):
    """

    :param Neurons: Number of Neurons
    :type Neurons: int
    :param sim_time: times for run
    :type sim_time: int
    :param record: If True will aks for spikes to be recorded
    :type record: bool
    """
    g = 5.0
    eta = 2.0
    delay = 2.0
    epsilon = 0.1

    tau_m = 20.0  # ms (20ms will give a FR of 20hz)
    tau_ref = 2.0
    v_reset = 10.0
    v_th = 20.0
    v_rest = 0.0
    tau_syn = 1.0

    n_e = int(round(Neurons * 0.8))
    n_i = int(round(Neurons * 0.2))

    c_e = n_e * 0.1

    # Excitatory and inhibitory weights
    j_e = 0.1
    j_i = -g * j_e

    # The firing rate of a neuron in the external pop
    # is the product of eta time the threshold rate
    # the steady state firing rate which is
    # needed to bring a neuron to threshold.
    nu_ex = eta * v_th / (j_e * c_e * tau_m)

    # population rate of the whole external population.
    # With CE neurons the pop rate is simply the product
    # nu_ex*c_e  the factor 1000.0 changes the units from
    # spikes per ms to spikes per second.
    p_rate = 1000.0 * nu_ex * c_e
    print("Rate is: %f HZ" % (p_rate / 1000))

    # Neural Parameters
    pynn.setup(timestep=1.0, min_delay=1.0, max_delay=16.0)

    # Makes it easy to scale up the number of cores
    pynn.set_number_of_neurons_per_core(pynn.IF_curr_exp, 100)
    pynn.set_number_of_neurons_per_core(pynn.SpikeSourcePoisson, 100)

    exc_cell_params = {
        'cm': 1.0,  # pf
        'tau_m': tau_m,
        'tau_refrac': tau_ref,
        'v_rest': v_rest,
        'v_reset': v_reset,
        'v_thresh': v_th,
        'tau_syn_E': tau_syn,
        'tau_syn_I': tau_syn,
        'i_offset': 0.9
    }

    inh_cell_params = {
        'cm': 1.0,  # pf
        'tau_m': tau_m,
        'tau_refrac': tau_ref,
        'v_rest': v_rest,
        'v_reset': v_reset,
        'v_thresh': v_th,
        'tau_syn_E': tau_syn,
        'tau_syn_I': tau_syn,
        'i_offset': 0.9
    }

    # Set-up pynn Populations
    e_pop = pynn.Population(n_e, pynn.IF_curr_exp(**exc_cell_params),
                            label="e_pop")

    i_pop = pynn.Population(n_i, pynn.IF_curr_exp, inh_cell_params,
                            label="i_pop")

    if seed is None:
        poisson_ext_e = pynn.Population(
            n_e, pynn.SpikeSourcePoisson(rate=10.0),
            label="Poisson_pop_E")
        poisson_ext_i = pynn.Population(
            n_i, pynn.SpikeSourcePoisson(rate=10.0),
            label="Poisson_pop_I")
    else:
        poisson_ext_e = pynn.Population(
            n_e, pynn.SpikeSourcePoisson(rate=10.0),
            label="Poisson_pop_E", additional_parameters={"seed": seed})
        poisson_ext_i = pynn.Population(
            n_i, pynn.SpikeSourcePoisson(rate=10.0),
            label="Poisson_pop_I", additional_parameters={"seed": seed+1})

    # Connectors
    e_conn = pynn.FixedProbabilityConnector(epsilon)
    i_conn = pynn.FixedProbabilityConnector(epsilon)

    # Use random delays for the external noise and
    # set the initial membrane voltage below the resting potential
    # to avoid the overshoot of activity in the beginning of the simulation
    rng = NumpyRNG(seed=seed)
    delay_distr = RandomDistribution('uniform', [1.0, 16.0], rng=rng)
    ext_conn = pynn.OneToOneConnector()

    uniform_distr = RandomDistribution('uniform', [-10, 0], rng=rng)
    e_pop.initialize(v=uniform_distr)
    i_pop.initialize(v=uniform_distr)

    # Projections
    pynn.Projection(
        presynaptic_population=e_pop, postsynaptic_population=e_pop,
        connector=e_conn, receptor_type="excitatory",
        synapse_type=pynn.StaticSynapse(weight=j_e, delay=delay_distr))
    pynn.Projection(
        presynaptic_population=i_pop, postsynaptic_population=e_pop,
        connector=i_conn, receptor_type="inhibitory",
        synapse_type=pynn.StaticSynapse(weight=j_i, delay=delay))
    pynn.Projection(
        presynaptic_population=e_pop, postsynaptic_population=i_pop,
        connector=e_conn, receptor_type="excitatory",
        synapse_type=pynn.StaticSynapse(weight=j_e, delay=delay_distr))
    pynn.Projection(
        presynaptic_population=i_pop, postsynaptic_population=i_pop,
        connector=i_conn, receptor_type="inhibitory",
        synapse_type=pynn.StaticSynapse(weight=j_i, delay=delay))

    pynn.Projection(
        presynaptic_population=poisson_ext_e, postsynaptic_population=e_pop,
        connector=ext_conn, receptor_type="excitatory",
        synapse_type=pynn.StaticSynapse(weight=j_e * 10, delay=delay_distr))
    pynn.Projection(
        presynaptic_population=poisson_ext_i, postsynaptic_population=i_pop,
        connector=ext_conn, receptor_type="excitatory",
        synapse_type=pynn.StaticSynapse(weight=j_e * 10, delay=delay_distr))

    # Record stuff
    if record:
        e_pop.record('spikes')
        poisson_ext_e.record('spikes')

    pynn.run(sim_time)

    esp = None
    s = None

    if record:
        esp = e_pop.get_data('spikes')
        s = poisson_ext_e.get_data('spikes')

    pynn.end()

    return esp, s, n_e
Example #3
0
simulator_name = get_script_args(1)[0]
sim = import_module("pyNN.%s" % simulator_name)

from pyNN.random import NumpyRNG, RandomDistribution

init_logging(None, debug=True)

seed = 764756387
rng = NumpyRNG(seed=seed, parallel_safe=True)
tstop = 1000.0 # ms
input_rate = 100.0 # Hz
cell_params = {'tau_refrac': 2.0,  # ms
               'v_thresh':  -50.0, # mV
               'tau_syn_E':  2.0,  # ms
               'tau_syn_I':  2.0,  # ms
               'tau_m': RandomDistribution('uniform', [18.0, 22.0], rng=rng)
}
n_record = 3

node = sim.setup(timestep=0.025, min_delay=1.0, max_delay=1.0, debug=True, quit_on_end=False)
print "Process with rank %d running on %s" % (node, socket.gethostname())

print "[%d] Creating populations" % node
n_spikes = int(2*tstop*input_rate/1000.0)
spike_times = numpy.add.accumulate(rng.next(n_spikes, 'exponential',
                                            [1000.0/input_rate], mask_local=False))

input_population  = sim.Population(10, sim.SpikeSourceArray(spike_times=spike_times), label="input")
output_population = sim.Population(20, sim.IF_curr_exp(**cell_params), label="output")
print "[%d] input_population cells: %s" % (node, input_population.local_cells)
print "[%d] output_population cells: %s" % (node, output_population.local_cells)
def train(untrained_weights=None):
    organisedStim = {}
    labelSpikes = []
    Data = generate_data()
    spikeTimes=Data[0]
    labelSpikes=Data[1]
    '''
    for i in range(output_size):
        labelSpikes.append([])
        labelSpikes[i] = [i*input_len*v_co*5+(input_len-1)*v_co+1,
                            i*input_len*v_co*5+(input_len-1)*v_co*2+1,
                            i*input_len*v_co*5+(input_len-1)*v_co*3+1]
    '''
        #for j in range(5):
        #    labelSpikes
        
    #labelSpikes[label] = [(input_len-1)*v_co+1,(input_len-1)*v_co*2+1,(input_len-1)*v_co*3+1,]
    
    
    if untrained_weights == None:
        untrained_weights = RandomDistribution('uniform', low=wMin, high=wMaxInit).next(input_size*output_size)
        #untrained_weights = RandomDistribution('normal_clipped', mu=0.1, sigma=0.05, low=wMin, high=wMaxInit).next(input_size*output_size)
        untrained_weights = np.around(untrained_weights, 3)
        #saveWeights(untrained_weights, 'untrained_weightssupmodel1traj')
        print ("init!")

    print "length untrained_weights :", len(untrained_weights)

    if len(untrained_weights)>input_size:
        training_weights = [[0 for j in range(output_size)] for i in range(input_size)] #np array? size 1024x25
        k=0
        for i in range(input_size):
            for j in range(output_size):
                training_weights[i][j] = untrained_weights[k]
                k += 1
    else:
        training_weights = untrained_weights

    connections = []
    for n_pre in range(input_size): # len(untrained_weights) = input_size
        for n_post in range(output_size): # len(untrained_weight[0]) = output_size; 0 or any n_pre
            connections.append((n_pre, n_post, training_weights[n_pre][n_post], __delay__)) #index
    runTime = int(max(max(spikeTimes)))+100
    #####################
    sim.setup(timestep=1)
    #def populations
    layer1=sim.Population(input_size,sim.SpikeSourceArray, {'spike_times': spikeTimes},label='inputspikes')
    layer2=sim.Population(output_size,sim.IF_curr_exp,cellparams=cell_params_lif,label='outputspikes')
    supsignal=sim.Population(output_size,sim.SpikeSourceArray, {'spike_times': labelSpikes},label='supersignal')

    #def learning rule
    stdp = sim.STDPMechanism(
                            weight=untrained_weights,
                            #weight=0.02,  # this is the initial value of the weight
                            #delay="0.2 + 0.01*d",
                            timing_dependence=sim.SpikePairRule(tau_plus=tauPlus, tau_minus=tauMinus,A_plus=aPlus, A_minus=aMinus),
                            #weight_dependence=sim.MultiplicativeWeightDependence(w_min=wMin, w_max=wMax),
                            weight_dependence=sim.AdditiveWeightDependence(w_min=wMin, w_max=wMax),
                            #weight_dependence=sim.AdditiveWeightDependence(w_min=0, w_max=0.4),
                            dendritic_delay_fraction=1.0)
    #def projections

    #stdp_proj = sim.Projection(layer1, layer2, sim.FromListConnector(connections), synapse_type=stdp)
    stdp_proj = sim.Projection(layer1, layer2, sim.AllToAllConnector(), synapse_type=stdp)
    '''
    inhibitory_connections = sim.Projection(layer2, layer2, sim.AllToAllConnector(allow_self_connections=False), 
                                            synapse_type=sim.StaticSynapse(weight=inhibWeight, delay=__delay__), 
                                            receptor_type='inhibitory')
    '''
    stim_proj = sim.Projection(supsignal, layer2, sim.OneToOneConnector(), 
                                synapse_type=sim.StaticSynapse(weight=stimWeight, delay=__delay__))
    
    layer1.record(['spikes'])

    layer2.record(['v','spikes'])
    supsignal.record(['spikes'])
    #sim.run(runTime)
    sim.run(400)
    trained=stdp_proj.get('weight', format='list', with_address=False)
    stdp_proj = sim.Projection(layer1, layer2, sim.AllToAllConnector(), sim.StaticSynapse(weight=trained, delay=__delay__))
    sim.run(800)
    print("Weights:{}".format(stdp_proj.get('weight', 'list')))

    weight_list = [stdp_proj.get('weight', 'list'), stdp_proj.get('weight', format='list', with_address=False)]
    neo = layer2.get_data(["spikes", "v"])
    spikes = neo.segments[0].spiketrains
    v = neo.segments[0].filter(name='v')[0]
    neostim = supsignal.get_data(["spikes"])
    spikestim = neostim.segments[0].spiketrains
    neoinput= layer1.get_data(["spikes"])
    spikesinput = neoinput.segments[0].spiketrains

    plt.close('all')
    pplt.Figure(
    pplt.Panel(v, ylabel="Membrane potential (mV)", xticks=True, yticks=True, xlim=(0,runTime),xlabel='(a) Membrane Potential of Output Layer'),
    pplt.Panel(spikesinput,xticks=True, yticks=True, markersize=2, xlim=(0,runTime),xlabel='(b) Spikes of Input Layer'),
    pplt.Panel(spikestim, xticks=True, yticks=True, markersize=2, xlim=(0,runTime),xlabel='(c) Spikes of Supervised Layer'),
    pplt.Panel(spikes, xticks=True, xlabel="(d) Spikes of Output Layer\nTime (ms)", yticks=True, markersize=2, xlim=(0,runTime)),
    title="Multiple_car Training without noise",
    annotations="Multiple_car Training without noise"
                ).save('plot1/'+str(trylabel)+'_training.png')
    #plt.hist(weight_list[1], bins=100)
    
    plt.close('all')
    plt.hist([weight_list[1][0:input_size], weight_list[1][input_size:input_size*2], weight_list[1][input_size*2:]], bins=20, label=['neuron 0', 'neuron 1', 'neuron 2'], range=(0, wMax))
    plt.title('weight distribution')
    plt.xlabel('Weight value')
    plt.ylabel('Weight count')
    #plt.show()
    #plt.show()
                
    sim.end()
    return weight_list[1]
def do_run(nNeurons):

    p.setup(timestep=1.0, min_delay=1.0, max_delay=32.0)

    p.set_number_of_neurons_per_core(p.IF_curr_exp, 100)

    cm = list()
    i_off = list()
    tau_m = list()
    tau_re = list()
    tau_syn_e = list()
    tau_syn_i = list()
    v_reset = list()
    v_rest = list()
    v_thresh = list()

    for atom in range(0, nNeurons):
        cm.append(0.25)
        i_off.append(0.0)
        tau_m.append(10.0)
        tau_re.append(2.0)
        tau_syn_e.append(0.5)
        tau_syn_i.append(0.5)
        v_reset.append(-65.0)
        v_rest.append(-65.0)
        v_thresh.append(-64.4)

    gbar_na_distr = RandomDistribution('normal', (20.0, 2.0),
                                       rng=NumpyRNG(seed=85524))

    cell_params_lif = {
        'cm': cm,
        'i_offset': i_off,
        'tau_m': tau_m,
        'tau_refrac': tau_re,
        'tau_syn_E': tau_syn_e,
        'tau_syn_I': tau_syn_i,
        'v_reset': v_reset,
        'v_rest': v_rest,
        'v_thresh': v_thresh
    }

    populations = list()
    projections = list()

    weight_to_spike = 2
    delay = 1

    connections = list()
    for i in range(0, nNeurons):
        singleConnection = (i, ((i + 1) % nNeurons), weight_to_spike, delay)
        connections.append(singleConnection)

    injectionConnection = [(0, 0, weight_to_spike, delay)]
    spikeArray = {'spike_times': [[0]]}
    populations.append(
        p.Population(nNeurons, p.IF_curr_exp, cell_params_lif, label='pop_1'))
    populations.append(
        p.Population(1, p.SpikeSourceArray, spikeArray, label='inputSpikes_1'))

    populations[0].set(cm=0.25)
    populations[0].set(cm=cm)
    populations[0].set(tau_m=tau_m, v_thresh=v_thresh)
    populations[0].set(i_offset=gbar_na_distr)
    populations[0].set(i_offset=i_off)

    projections.append(
        p.Projection(populations[0], populations[0],
                     p.FromListConnector(connections)))
    projections.append(
        p.Projection(populations[1], populations[0],
                     p.FromListConnector(injectionConnection)))

    populations[0].record("v")
    populations[0].record("gsyn_exc")
    populations[0].record("spikes")

    p.run(100)

    neo = populations[0].get_data(["v", "spikes", "gsyn_exc"])

    p.end()

    return neo
#================================================================================================
# Populations
#================================================================================================
input_pops=[]
# input_spikes = [10.]
input_pop = sim.Population(number_of_inputs,sim.SpikeSourceArray(spike_times=input_spikes),label="an_pop_input")

# cd_pop = sim.Population(n_b,sim.extra_models.Izhikevich_cond,bushy_params_cond,label="fixed_weight_scale_cond_1")
# cd_pop_2 = sim.Population(n_b,sim.extra_models.Izhikevich_cond,bushy_params_cond,label="fixed_weight_scale_cond_2")
cd_pop = sim.Population(n_b,sim.IF_cond_exp,bushy_params_cond,label="fixed_weight_scale_cond_1")

cd_pop.record("all")
#================================================================================================
# Projections
#================================================================================================
n_an_b_connections = RandomDistribution('uniform',[2.,5.])
w2s_b = 5.#
av_an_b = w2s_b/5.
an_b_weight = RandomDistribution('normal_clipped',[av_an_b,0.1*av_an_b,0,av_an_b*2.])
an_b_list, max_dist = normal_dist_connection_builder(number_of_inputs, n_b, RandomDistribution,
                                                     conn_num=n_an_b_connections, dist=1.,
                                                     sigma=1., conn_weight=an_b_weight, delay=timestep,
                                                     normalised_space=pop_size, get_max_dist=True)

# sim.Projection(input_pop,cd_pop,sim.FromListConnector([(0,0)]),synapse_type=sim.StaticSynapse(weight=w2s_b))
sim.Projection(input_pop, cd_pop, sim.FromListConnector(an_b_list),
                                       synapse_type=sim.StaticSynapse())

# sim.Projection(input_pop, cd_pop_2, sim.FromListConnector(an_b_list),
#                                        synapse_type=sim.StaticSynapse())
Example #7
0
    n_exc, celltype(**cell_params), label="Excitatory_Cells")
inh_cells = p.Population(
    n_inh, celltype(**cell_params), label="Inhibitory_Cells")
exc_conn = None
ext_stim = None
if benchmark == "COBA":
    ext_stim = p.Population(
        20, p.SpikeSourcePoisson(rate=rate, duration=stim_dur),
        label="expoisson")
    rconn = 0.01
    ext_conn = p.FixedProbabilityConnector(rconn)
    ext_stim.record("spikes")

print("%s Initialising membrane potential to random values..." % node_id)
rng = NumpyRNG(seed=rngseed, parallel_safe=parallel_safe)
uniformDistr = RandomDistribution('uniform', [v_reset, v_thresh], rng=rng)
exc_cells.set(v=uniformDistr)
inh_cells.set(v=uniformDistr)

print("%s Connecting populations..." % node_id)
exc_conn = p.FixedProbabilityConnector(pconn, rng=rng)
inh_conn = p.FixedProbabilityConnector(pconn, rng=rng)

connections = {
    'e2e': p.Projection(
        exc_cells, exc_cells, exc_conn, receptor_type='excitatory',
        synapse_type=p.StaticSynapse(weight=w_exc, delay=delay)),
    'e2i': p.Projection(
        exc_cells, inh_cells, exc_conn, receptor_type='excitatory',
        synapse_type=p.StaticSynapse(weight=w_exc, delay=delay)),
    'i2e': p.Projection(
# With CE neurons the pop rate is simply the product
# nu_ex*C_E  the factor 1000.0 changes the units from
# spikes per ms to spikes per second.
p_rate = 1000.0 * nu_ex * C_E 

print "Rate is: %f HZ" % (p_rate/1000)
# Neural Parameters
pynn.setup(timestep=1.0,min_delay=1.0,max_delay=16.0)

if simulator_Name == "spiNNaker":
    pynn.set_number_of_neurons_per_core("IF_curr_exp", 100)
    pynn.set_number_of_neurons_per_core("SpikeSourcePoisson", 100)

rng = NumpyRNG(seed=1)

v_distr_exc = RandomDistribution('uniform', [-10.0, 0.0], rng)
v_distr_inh = RandomDistribution('uniform', [-10.0, 0.0], rng)

exc_cell_params ={
    'cm': 1.0, # pf
    'tau_m': tau_m,
    'tau_refrac':  tau_ref,
    'v_rest': v_rest,
    'v_reset': v_reset,
    'v_thresh': V_th,
    'tau_syn_E'  : tauSyn,
    'tau_syn_I'  : tauSyn,
    #'v_init': [  v_distr_exc.next() for i in range(N_E)],
    'i_offset': 0.9
}
Example #9
0
def do_run(seed=None):
    simulator_name = 'spiNNaker'

    timer = Timer()

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

    parallel_safe = True

    n = 1500  # number of cells
    # number of excitatory cells:number of inhibitory cells
    r_ei = 4.0
    pconn = 0.02  # connection probability

    dt = 1  # (ms) simulation timestep
    tstop = 200  # (ms) simulaton duration
    delay = 1

    # Cell parameters
    area = 20000.  # (µm²)
    tau_m = 20.  # (ms)
    cm = 1.  # (µF/cm²)
    g_leak = 5e-5  # (S/cm²)
    e_leak = -49.  # (mV)
    v_thresh = -50.  # (mV)
    v_reset = -60.  # (mV)
    t_refrac = 5.  # (ms) (clamped at v_reset)
    # (mV) 'mean' membrane potential,  for calculating CUBA weights
    v_mean = -60.
    tau_exc = 5.  # (ms)
    tau_inh = 10.  # (ms)
    # (nS) #Those weights should be similar to the COBA weights
    g_exc = 0.27
    # (nS) # but the delpolarising drift should be taken into account
    g_inh = 4.5
    e_rev_exc = 0.  # (mV)
    e_rev_inh = -80.  # (mV)

    # === Calculate derived parameters ===============================

    area *= 1e-8  # convert to cm²
    cm *= area * 1000  # convert to nF
    r_m = 1e-6 / (g_leak * area)  # membrane resistance in MΩ
    assert tau_m == cm * r_m  # just to check

    # number of excitatory cells
    n_exc = int(round((n * r_ei / (1 + r_ei))))
    n_inh = n - n_exc  # number of inhibitory cells

    celltype = p.IF_curr_exp
    # (nA) weight of excitatory synapses
    w_exc = 1e-3 * g_exc * (e_rev_exc - v_mean)
    w_inh = 1e-3 * g_inh * (e_rev_inh - v_mean)  # (nA)
    assert w_exc > 0
    assert w_inh < 0

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

    p.setup(timestep=dt, min_delay=delay, max_delay=delay)

    if simulator_name == 'spiNNaker':
        # this will set 100 neurons per core
        p.set_number_of_neurons_per_core(p.IF_curr_exp, 100)
        # this will set 50 neurons per core
        p.set_number_of_neurons_per_core(p.IF_cond_exp, 50)

    # node_id = 1
    # np = 1

    # host_name = socket.gethostname()

    cell_params = {
        'tau_m': tau_m,
        'tau_syn_E': tau_exc,
        'tau_syn_I': tau_inh,
        'v_rest': e_leak,
        'v_reset': v_reset,
        'v_thresh': v_thresh,
        'cm': cm,
        'tau_refrac': t_refrac,
        'i_offset': 0
    }

    timer.start()

    exc_cells = p.Population(n_exc,
                             celltype,
                             cell_params,
                             label="Excitatory_Cells")
    inh_cells = p.Population(n_inh,
                             celltype,
                             cell_params,
                             label="Inhibitory_Cells")
    rng = NumpyRNG(seed=seed, parallel_safe=parallel_safe)
    uniform_distr = RandomDistribution('uniform', [v_reset, v_thresh], rng=rng)
    exc_cells.initialize(v=uniform_distr)
    inh_cells.initialize(v=uniform_distr)

    exc_conn = p.FixedProbabilityConnector(pconn, rng=rng)
    synapse_exc = p.StaticSynapse(weight=w_exc, delay=delay)
    inh_conn = p.FixedProbabilityConnector(pconn, rng=rng)
    synapse_inh = p.StaticSynapse(weight=w_inh, delay=delay)

    connections = dict()
    connections['e2e'] = p.Projection(exc_cells,
                                      exc_cells,
                                      exc_conn,
                                      synapse_type=synapse_exc,
                                      receptor_type='excitatory')
    connections['e2i'] = p.Projection(exc_cells,
                                      inh_cells,
                                      exc_conn,
                                      synapse_type=synapse_exc,
                                      receptor_type='excitatory')
    connections['i2e'] = p.Projection(inh_cells,
                                      exc_cells,
                                      inh_conn,
                                      synapse_type=synapse_inh,
                                      receptor_type='inhibitory')
    connections['i2i'] = p.Projection(inh_cells,
                                      inh_cells,
                                      inh_conn,
                                      synapse_type=synapse_inh,
                                      receptor_type='inhibitory')

    # === Setup recording ==============================
    exc_cells.record("spikes")

    # === Run simulation ================================
    p.run(tstop)

    exc_spikes = exc_cells.get_data("spikes")

    exc_cells.write_data(neo_path, "spikes")

    p.end()

    return exc_spikes
    # t_pops[td] = sim.Population(n_sub_t, sim.IF_cond_exp, t_stellate_lif_params,
    #                                        label="t_stellate_fixed_weight_scale_cond")

    t_pops[td].record("all")
# cd_pop = sim.Population(target_pop_size,sim.extra_models.Izhikevich_cond,t_stellate_izk_class_2_params,label="fixed_weight_scale_cond")

# cd_pop.record("all")
#================================================================================================
# Projections
#================================================================================================
# connection_dicts_file = np.load(input_directory+'/cn_{}an_fibres_{}ears_connectivity.npz'.format
#                         (n_fibres,n_ears))
# connection_dicts = connection_dicts_file['connection_dicts']

w2s_t = 12.  #50.#15.#0.4#1.6#0.4#0.1# 0.8#0.5#0.25#0.1#0.3#0.1#0.7
n_an_t_connections = RandomDistribution('uniform', [4., 6.])
av_an_t = w2s_t / 5.
# an_t_weight = RandomDistribution('uniform',[0,av_an_t*2])
# an_t_weight = RandomDistribution('uniform',[av_an_t/5.,av_an_t*2])
an_t_weight = RandomDistribution('normal_clipped',
                                 [av_an_t, 0.1 * av_an_t, 0, av_an_t * 2.])
an_t_master, max_dist = normal_dist_connection_builder(
    n_fibres,
    n_t,
    RandomDistribution,
    conn_num=n_an_t_connections,
    dist=1.,
    sigma=1.,
    conn_weight=an_t_weight,
    normalised_space=pop_size,
    get_max_dist=True,
Example #11
0
# sim.set_number_of_neurons_per_core(sim.SpikeSourceArray,128)

#================================================================================================
# Populations
#================================================================================================
# input_pop = sim.Population(number_of_inputs,sim.SpikeSourceArray(spike_times=input_spikes),label="an_pop_input")
# t_pop = sim.Population(n_t,sim.IF_cond_exp,t_stellate_params_cond,label="t_fixed_weight_scale_cond")
# t_pop.record(["spikes"])
# d_pop = sim.Population(n_d,sim.IF_cond_exp,d_stellate_params_cond,label="d_fixed_weight_scale_cond")
# d_pop.record(["spikes"])

#================================================================================================
# AN --> CN Projections
#================================================================================================
w2s_t = 0.7
n_an_t_connections = RandomDistribution('uniform', [4., 6.])
av_an_t = w2s_t / 5.
# an_t_weight = RandomDistribution('uniform',[0,av_an_t])
an_t_weight = RandomDistribution('normal_clipped',
                                 [av_an_t, 0.1 * av_an_t, 0, av_an_t * 2.])
an_t_list = normal_dist_connection_builder(number_of_inputs,
                                           n_t,
                                           RandomDistribution,
                                           conn_num=n_an_t_connections,
                                           dist=1.,
                                           sigma=1.,
                                           conn_weight=an_t_weight)
# an_t_projection = sim.Projection(input_pop,t_pop,sim.FromListConnector(an_t_list),synapse_type=sim.StaticSynapse())
input_pops, t_pops, an_t_projs, m_pre = sub_pop_builder_inter(
    sim, n_t, sim.IF_cond_exp, t_stellate_params_cond, "SSA", input_spikes,
    "an_input", "t_stellate", an_t_list)
Example #12
0
def scenario4(sim):
    """
    Network with spatial structure
    """
    init_logging(logfile=None, debug=True)
    sim.setup()
    rng = NumpyRNG(seed=76454, parallel_safe=False)

    input_layout = RandomStructure(boundary=Cuboid(width=500.0,
                                                   height=500.0,
                                                   depth=100.0),
                                   origin=(0, 0, 0),
                                   rng=rng)
    inputs = sim.Population(
        100,
        sim.SpikeSourcePoisson(
            rate=RandomDistribution('uniform', [3.0, 7.0], rng=rng)),
        structure=input_layout,
        label="inputs")
    output_layout = Grid3D(aspect_ratioXY=1.0,
                           aspect_ratioXZ=5.0,
                           dx=10.0,
                           dy=10.0,
                           dz=10.0,
                           x0=0.0,
                           y0=0.0,
                           z0=200.0)
    outputs = sim.Population(
        200,
        sim.EIF_cond_exp_isfa_ista(),
        initial_values={
            'v': RandomDistribution('normal', [-65.0, 5.0], rng=rng),
            'w': RandomDistribution('normal', [0.0, 1.0], rng=rng)
        },
        structure=output_layout,  # 10x10x2 grid
        label="outputs")
    logger.debug("Output population positions:\n %s", outputs.positions)
    DDPC = sim.DistanceDependentProbabilityConnector
    input_connectivity = DDPC("0.5*exp(-d/100.0)", rng=rng)
    recurrent_connectivity = DDPC("sin(pi*d/250.0)**2", rng=rng)
    depressing = sim.TsodyksMarkramSynapse(weight=RandomDistribution(
        'normal', (0.1, 0.02), rng=rng),
                                           delay="0.5 + d/100.0",
                                           U=0.5,
                                           tau_rec=800.0,
                                           tau_facil=0.0)
    facilitating = sim.TsodyksMarkramSynapse(weight=0.05,
                                             delay="0.2 + d/100.0",
                                             U=0.04,
                                             tau_rec=100.0,
                                             tau_facil=1000.0)
    input_connections = sim.Projection(inputs,
                                       outputs,
                                       input_connectivity,
                                       receptor_type='excitatory',
                                       synapse_type=depressing,
                                       space=Space(axes='xy'),
                                       label="input connections")
    recurrent_connections = sim.Projection(
        outputs,
        outputs,
        recurrent_connectivity,
        receptor_type='inhibitory',
        synapse_type=facilitating,
        space=Space(periodic_boundaries=(
            (-100.0, 100.0), (-100.0, 100.0), None
        )),  # should add "calculate_boundaries" method to Structure classes
        label="recurrent connections")
    outputs.record('spikes')
    outputs.sample(10, rng=rng).record('v')
    sim.run(1000.0)
    data = outputs.get_data()
    sim.end()
    return data
Example #13
0
def scenario1(sim):
    """
    Balanced network of integrate-and-fire neurons.
    """
    cell_params = {
        'tau_m': 20.0,
        'tau_syn_E': 5.0,
        'tau_syn_I': 10.0,
        'v_rest': -60.0,
        'v_reset': -60.0,
        'v_thresh': -50.0,
        'cm': 1.0,
        'tau_refrac': 5.0,
        'e_rev_E': 0.0,
        'e_rev_I': -80.0
    }
    stimulation_params = {'rate': 100.0, 'duration': 50.0}
    n_exc = 80
    n_inh = 20
    n_input = 20
    rngseed = 98765
    parallel_safe = True
    n_threads = 1
    pconn_recurr = 0.02
    pconn_input = 0.01
    tstop = 1000.0
    delay = 0.2
    dt = 0.1
    weights = {
        'excitatory': 4.0e-3,
        'inhibitory': 51.0e-3,
        'input': 0.1,
    }

    sim.setup(timestep=dt, min_delay=dt, threads=n_threads)
    all_cells = sim.Population(n_exc + n_inh,
                               sim.IF_cond_exp(**cell_params),
                               label="All cells")
    cells = {
        'excitatory':
        all_cells[:n_exc],
        'inhibitory':
        all_cells[n_exc:],
        'input':
        sim.Population(n_input,
                       sim.SpikeSourcePoisson(**stimulation_params),
                       label="Input")
    }

    rng = NumpyRNG(seed=rngseed, parallel_safe=parallel_safe)
    uniform_distr = RandomDistribution(
        'uniform', [cell_params['v_reset'], cell_params['v_thresh']], rng=rng)
    all_cells.initialize(v=uniform_distr)

    connections = {}
    for name, pconn, receptor_type in (
        ('excitatory', pconn_recurr, 'excitatory'),
        ('inhibitory', pconn_recurr, 'inhibitory'),
        ('input', pconn_input, 'excitatory'),
    ):
        connector = sim.FixedProbabilityConnector(pconn, rng=rng)
        syn = sim.StaticSynapse(weight=weights[name], delay=delay)
        connections[name] = sim.Projection(cells[name],
                                           all_cells,
                                           connector,
                                           syn,
                                           receptor_type=receptor_type,
                                           label=name)

    all_cells.record('spikes')
    cells['excitatory'][0:2].record('v')
    assert_equal(cells['excitatory'][0:2].grandparent, all_cells)

    sim.run(tstop)

    E_count = cells['excitatory'].mean_spike_count()
    I_count = cells['inhibitory'].mean_spike_count()
    print "Excitatory rate        : %g Hz" % (E_count * 1000.0 / tstop, )
    print "Inhibitory rate        : %g Hz" % (I_count * 1000.0 / tstop, )
    sim.end()
Example #14
0
        print "%d Initialising the simulator with single thread..." % (rank)

    # Small function to display information only on node 1
    def nprint(s):
        if (rank == 0):
            print s

    timer.start()  # start timer on construction

    print "%d Setting up random number generator" % rank
    rng = NumpyRNG(kernelseed, parallel_safe=True)

    # Initialising membrane potential to random values
    vrest_sd = 5
    vrest_distr = RandomDistribution('uniform', [
        Vrest_Pyr - numpy.sqrt(3) * vrest_sd,
        Vrest_Pyr + numpy.sqrt(3) * vrest_sd
    ], rng)

    Pyr_net = []

    for sp in range(NP):
        print "%d Creating pyramidal cell population %d  with %d neurons." % (
            rank, sp, N_Pyr)
        Pyr_subnet = Population((N_Pyr, ), IF_cond_exp, cell_params_Pyr)
        for cell in Pyr_subnet:
            vrest_rval = vrest_distr.next(1)
            cell.set_parameters(v_rest=vrest_rval)
        Pyr_net.append(Pyr_subnet)

    print "%d Creating basket cell population with %d neurons." % (rank, N_Bas)
    Bas_net = Population((N_Bas, ), IF_cond_exp, cell_params_Bas)
def callback(data_input):

    #====================================================================
    # Unpacking the Joint Angle Message
    #====================================================================
    global message
    message = data_input.degree
    rospy.loginfo('=====> received joint angle in degree %r', message)
    print message

    if type(message) != int:
    	input_rates = list(message)
	n_input_neurons = len(input_rates)  
    else:
	input_rates = message
	n_input_neurons = 1
	

    #msg_list= [int(msg.encode('hex'),16) for msg in message]
    

    timer = Timer()
    dt = 0.1
    p.setup(timestep=dt) # 0.1ms


    #====================================================================
    # Defining the LSM
    #====================================================================

    n_res=2000
    w_exc_b=0.2
    w_inh_b=-0.8
    rout_w_exc=20
    rout_w_inh=-80

    n_readout_neurons   = 2
    n_reservoir_neurons = n_res
    n_res = n_reservoir_neurons
    exc_rate            = 0.8 # percentage of excitatory neurons in reservoir

    n_exc = int(round(n_reservoir_neurons*exc_rate))
    n_inh = n_reservoir_neurons-n_exc
    izh_celltype = p.native_cell_type('izhikevich')
    if_celltype = p.IF_curr_exp
    celltype = if_celltype
    
    spike_source = p.native_cell_type('poisson_generator')
    inp_pop=p.Population(n_input_neurons*10,spike_source,{'rate':input_rates})
    
    exc_cells = p.Population(n_exc, celltype, label="Excitatory_Cells")
    inh_cells = p.Population(n_inh, celltype, label="Inhibitory_Cells")

    # initialize with a uniform random distributin
    # use seeding for reproducability
    rngseed = 98766987
    parallel_safe = True
    rng = NumpyRNG(seed=rngseed, parallel_safe=parallel_safe)

    unifDistr = RandomDistribution('uniform', (-70,-65), rng=rng)
    inh_cells.initialize('V_m',unifDistr)
    exc_cells.initialize('V_m',unifDistr)
    
    readout_neurons = p.Population(2, celltype, label="readout_neuron")
    
    inp_weight=3.
    inp_delay =1

    inp_weight_distr = RandomDistribution('normal', [inp_weight, 1e-3], rng=rng)

    # connect each input neuron to 30% of the reservoir neurons
    inp_conn = p.FixedProbabilityConnector(p_connect=0.3,weights =inp_weight_distr, delays=inp_delay)

    connections = {}
    connections['inp2e'] = p.Projection(inp_pop, exc_cells, inp_conn)
    connections['inp2i'] = p.Projection(inp_pop, inh_cells, inp_conn)

    pconn = 0.01      # sparse connection probability

    # scale the weights w.r.t. the network to keep it stable
    w_exc = w_exc_b/np.sqrt(n_res)      # nA
    w_inh = w_inh_b/np.sqrt(n_res)      # nA
    
    delay_exc = 1      # defines how long (ms) the synapse takes for transmission
    delay_inh = 1

    weight_distr_exc = RandomDistribution('normal', [w_exc, 1/n_res], rng=rng)
    weight_distr_inh = RandomDistribution('normal', [w_inh, 1/n_res], rng=rng)
    exc_conn = p.FixedProbabilityConnector(pconn, weights=weight_distr_exc, delays=delay_exc)
    inh_conn = p.FixedProbabilityConnector(pconn, weights=weight_distr_inh, delays=delay_inh)

    connections['e2e'] = p.Projection(exc_cells, exc_cells, exc_conn, target='excitatory')
    connections['e2i'] = p.Projection(exc_cells, inh_cells, exc_conn, target='excitatory')
    connections['i2e'] = p.Projection(inh_cells, exc_cells, inh_conn, target='inhibitory')
    connections['i2i'] = p.Projection(inh_cells, inh_cells, inh_conn, target='inhibitory')
    
    
    
    rout_conn_exc = p.AllToAllConnector(weights=rout_w_exc, delays=delay_exc)
    rout_conn_inh = p.AllToAllConnector(weights=rout_w_inh, delays=delay_exc)

    
    

    connections['e2rout'] = p.Projection(exc_cells, readout_neurons, rout_conn_exc, target='excitatory')
    connections['i2rout'] = p.Projection(inh_cells, readout_neurons, rout_conn_inh, target='inhibitory')
    
    readout_neurons.record()
    exc_cells.record()
    inh_cells.record()
    inp_pop.record()
    
    
    p.run(20)

    r_spikes = readout_neurons.getSpikes()
    exc_spikes = exc_cells.getSpikes()
    inh_spikes = inh_cells.getSpikes()
    inp_spikes = inp_pop.getSpikes()

    rospy.loginfo('=====> shape of r_spikes %r', np.shape(r_spikes))

    #====================================================================
    # Compute Readout Spike Rates
    #====================================================================
    
  
    alpha_rates = alpha_decoding(r_spikes,dt)
    mean_rates  = mean_decoding(r_spikes,dt)

    #====================================================================
    # Publish Readout Rates
    #====================================================================

    # TODO: error handling if r_spikes is empty
    pub = rospy.Publisher('/alpha_readout_rates', Pop_List, queue_size=10)
    alpha_readout_rates = Pop_List
    alpha_readout_rates = alpha_rates
    pub.publish(alpha_readout_rates)

    pub = rospy.Publisher('/mean_readout_rates', Pop_List, queue_size=10)
    mean_readout_rates = Pop_List
    mean_readout_rates = mean_rates
    pub.publish(mean_readout_rates)
Example #16
0
def simulate(sim, rng, setup_kwargs):
    sim.setup(timestep=dt, **setup_kwargs)

    # Brian was performing synaptic input with ge*(Ee-vr)
    # Ee = 0 so infact Vr is being treated as an input resistance and therefore C = tau_m / v_rest = 10*10^-3 / 60*10^6 = 0.17*10^-9

    # Weight dependences to test
    weight_dependences = [
        sim.AdditiveWeightDependence(w_min=0.0, w_max=g_max),
        sim.MultiplicativeWeightDependence(w_min=0.0, w_max=g_max)
    ]

    # Create a neural population to stimulate using each weight dependence
    neural_pops = [
        sim.Population(
            num_neurons,
            sim.IF_curr_exp(v_rest=-74.0,
                            v_reset=-60.0,
                            v_thresh=-54.0,
                            tau_syn_E=5.0,
                            tau_syn_I=5.0,
                            tau_m=10.0,
                            cm=0.17)) for _ in weight_dependences
    ]

    # Create poisson source to stimulate both populations
    ex_poisson = sim.Population(num_ex_synapses,
                                sim.SpikeSourcePoisson(rate=15.0))

    # Record spikes from each population
    for n in neural_pops:
        n.record("spikes")

    a_plus = 0.01
    a_minus = 1.05 * a_plus

    # Create weight distribution
    weight_dist = RandomDistribution("uniform", low=0, high=g_max, rng=rng)

    # Create STDP projections with correct weight dependence between poisson source and each neural population
    projections = [
        sim.Projection(ex_poisson,
                       n,
                       sim.AllToAllConnector(),
                       sim.STDPMechanism(timing_dependence=sim.SpikePairRule(
                           tau_plus=20.0,
                           tau_minus=20.00,
                           A_plus=a_plus,
                           A_minus=a_minus),
                                         weight_dependence=w,
                                         weight=weight_dist,
                                         delay=dt,
                                         dendritic_delay_fraction=1.0),
                       receptor_type="excitatory")
        for n, w in zip(neural_pops, weight_dependences)
    ]
    # Simulate
    sim.run(duration)

    # Download weights
    weights = [
        np.asarray(p.get("weight", format="list", with_address=False))
        for p in projections
    ]

    # Download spikes
    data = [n.get_data() for n in neural_pops]

    # End simulation
    sim.end()

    # Return learned weights and data
    return weights, data
print(IF_cond_exp.default_parameters)
'''
populations
'''
#tec_cells=create(thalamocortical_type,n=100)
#tc_cells = Population(100, thalamocortical_type)
#ctx_cells = Population(500, cortical_type)

from pyNN.space import Grid2D, RandomStructure, Sphere
tc_cells = Population(100,
                      thalamocortical_type,
                      structure=RandomStructure(boundary=Sphere(radius=200.0)),
                      initial_values={'v': -70.0},
                      label="Thalamocortical neurons")
from pyNN.random import RandomDistribution
v_init = RandomDistribution('uniform', (-70.0, -60.0))
ctx_cells = Population(500,
                       cortical_type,
                       structure=Grid2D(dx=10.0, dy=10.0),
                       initial_values={'v': v_init},
                       label="Cortical neurons")
'''
view
'''
id = ctx_cells[47]  # the 48th neuron in a Population
view = ctx_cells[:80]  # the first eighty neurons
view = ctx_cells[::2]  # every second neuron
view = ctx_cells[45, 91, 7]  # a specific set of neurons
view = ctx_cells.sample(50,
                        rng=NumpyRNG(seed=6538))  # select 50 neurons at random
print(view.parent.label)
Example #18
0
    def setup(self, sim, conf):

        # extract parameters
        pyseed = conf['params_dict']['nest']['pyseed']
        parallel_safe = conf['params_dict']['nest']['parallel_safe']
        input_type = conf['params_dict']['nest']['input_type']
        layers = conf['layers']
        pops = conf['pops']
        bg_rate = conf['bg_rate']
        w_mean = conf['w_mean']
        K_scaling = conf['params_dict']['nest']['K_scaling']
        N_scaling = conf['params_dict']['nest']['N_scaling']
        n_record = conf['params_dict']['nest']['n_record']
        neuron_model = conf['neuron_model']
        tau_max = conf['tau_max']
        record_corr = conf['params_dict']['nest']['record_corr']
        n_layers = conf['n_layers']
        n_pops_per_layer = conf['n_pops_per_layer']
        V0_mean = conf['V0_mean']
        n_record_v = conf['params_dict']['nest']['n_record_v']
        record_v = conf['params_dict']['nest']['record_v']
        record_fraction = conf['params_dict']['nest']['record_fraction']
        thalamic_input = conf['thalamic_input']
        w_rel = conf['w_rel']
        w_rel_234 = conf['w_rel_234']
        simulator = conf['simulator']
        N_full = conf['N_full']
        K_ext = conf['K_ext']
        tau_syn_E = conf['neuron_params']['tau_syn_E']
        v_thresh = conf['neuron_params']['v_thresh']
        v_rest = conf['neuron_params']['v_rest']
        neuron_params = conf['neuron_params']
        thal_params = conf['thal_params']
        structure = conf['structure']
        d_mean = conf['d_mean']
        d_sd = conf['d_sd']
        frac_record_v = conf['params_dict']['nest']['frac_record_v']
        n_rec = helper_functions.get_n_rec(conf)

        # if parallel_safe=False, PyNN offsets the seeds by 1 for each rank
        script_rng = NumpyRNG(seed=pyseed, parallel_safe=parallel_safe)

        # Compute DC input before scaling
        if input_type == 'DC':
            self.DC_amp = {}
            for target_layer in layers:
                self.DC_amp[target_layer] = {}
                for target_pop in pops:
                    self.DC_amp[target_layer][target_pop] = bg_rate * \
                        K_ext[target_layer][target_pop] * \
                        w_mean * tau_syn_E / 1000.
        else:
            self.DC_amp = {
                'L23': {
                    'E': 0.,
                    'I': 0.
                },
                'L4': {
                    'E': 0.,
                    'I': 0.
                },
                'L5': {
                    'E': 0.,
                    'I': 0.
                },
                'L6': {
                    'E': 0.,
                    'I': 0.
                }
            }

        # In-degrees of the full-scale and scaled models
        K_full = scaling.get_indegrees(conf)
        self.K = K_scaling * K_full

        self.K_ext = {}
        for layer in layers:
            self.K_ext[layer] = {}
            for pop in pops:
                self.K_ext[layer][pop] = K_scaling * K_ext[layer][pop]

        self.w = helper_functions.create_weight_matrix(conf)
        # Network scaling
        if K_scaling != 1:
            self.w, self.w_ext, self.DC_amp = scaling.adjust_w_and_ext_to_K(
                K_full, K_scaling, self.w, self.DC_amp, conf)
        else:
            self.w_ext = w_mean

        Vthresh = {}
        for layer in layers:
            Vthresh[layer] = {}
            for pop in pops:
                Vthresh[layer][pop] = v_thresh

        # Initial membrane potential distributions
        # The original study used V0_mean = -58 mV, V0_sd = 5 mV.
        # This is adjusted here to any changes in v_rest and scaling of V.
        V0_mean = {}
        V0_sd = {}
        for layer in layers:
            V0_mean[layer] = {}
            V0_sd[layer] = {}
            for pop in pops:
                V0_mean[layer][pop] = (v_rest + Vthresh[layer][pop]) / 2.
                V0_sd[layer][pop] = (Vthresh[layer][pop] - v_rest) / 3.

        V_dist = {}
        for layer in layers:
            V_dist[layer] = {}
            for pop in pops:
                V_dist[layer][pop] = RandomDistribution(
                    'normal', [V0_mean[layer][pop], V0_sd[layer][pop]],
                    rng=script_rng)

        model = getattr(sim, neuron_model)

        if record_corr and simulator == 'nest':
            # Create correlation recording device
            sim.nest.SetDefaults('correlomatrix_detector', {'delta_tau': 0.5})
            self.corr_detector = sim.nest.Create('correlomatrix_detector')
            sim.nest.SetStatus(
                self.corr_detector, {
                    'N_channels': n_layers * n_pops_per_layer,
                    'tau_max': tau_max,
                    'Tstart': tau_max,
                })

        if sim.rank() == 0:
            print 'neuron_params:', conf['neuron_params']
            print 'K: ', self.K
            print 'K_ext: ', self.K_ext
            print 'w: ', self.w
            print 'w_ext: ', self.w_ext
            print 'DC_amp: ', self.DC_amp
            print 'V0_mean: '
            for layer in layers:
                for pop in pops:
                    print layer, pop, V0_mean[layer][pop]
            print 'n_rec:'
            for layer in layers:
                for pop in pops:
                    print layer, pop, n_rec[layer][pop]
                    if not record_fraction and n_record > \
                       int(round(N_full[layer][pop] * N_scaling)):
                        print 'Note that requested number of neurons to record',
                        print 'exceeds ', layer, pop, ' population size'

        # Create cortical populations
        self.pops = {}
        global_neuron_id = 1
        self.base_neuron_ids = {}
        # list containing the GIDs of recording devices, needed for output
        # bundle
        device_list = []
        for layer in layers:
            self.pops[layer] = {}
            for pop in pops:
                cellparams = neuron_params

                self.pops[layer][pop] = sim.Population(int(
                    round(N_full[layer][pop] * N_scaling)),
                                                       model,
                                                       cellparams=cellparams,
                                                       label=layer + pop)
                this_pop = self.pops[layer][pop]

                # Provide DC input in the current-based case
                # DC input is assumed to be absent in the conductance-based
                # case
                this_pop.set('i_offset', self.DC_amp[layer][pop])

                self.base_neuron_ids[this_pop] = global_neuron_id
                global_neuron_id += len(this_pop) + 2

                this_pop.initialize('v', V_dist[layer][pop])

                # Spike recording
                sd = sim.nest.Create('spike_detector',
                                     params={
                                         'label':
                                         'spikes_{0}{1}'.format(layer, pop),
                                         'withtime':
                                         True,
                                         'withgid':
                                         True,
                                         'to_file':
                                         True
                                     })
                device_list.append(sd)
                sim.nest.Connect(list(this_pop[0:n_rec[layer][pop]].all_cells),
                                 sd)

                # Membrane potential recording
                if record_v:
                    if record_fraction:
                        n_rec_v = round(this_pop.size * frac_record_v)
                    else:
                        n_rec_v = n_record_v
                    vm = sim.nest.Create('voltmeter',
                                         params={
                                             'label':
                                             'voltages_{0}{1}'.format(
                                                 layer, pop),
                                             'withtime':
                                             True,
                                             'withgid':
                                             True,
                                             'to_file':
                                             True
                                         })
                    device_list.append(vm)
                    sim.nest.Connect(vm, list(this_pop[0:n_rec_v]))

                # Correlation recording
                if record_corr and simulator == 'nest':
                    index = structure[layer][pop]
                    sim.nest.SetDefaults('static_synapse',
                                         {'receptor_type': index})
                    sim.nest.Connect(list(this_pop.all_cells),
                                     self.corr_detector)
                    sim.nest.SetDefaults('static_synapse',
                                         {'receptor_type': 0})

        if thalamic_input:
            self.thalamic_population = sim.nest.Create('parrot_neuron',
                                                       thal_params['n_thal'])
            # create and connect a poisson generator for stimulating the
            # thalamic population
            thal_pg = sim.nest.Create('poisson_generator',
                                      params={'rate': thal_params['rate'],
                                              'start': thal_params['start'],
                                              'stop': thal_params['start'] \
                                              + thal_params['duration']})
            sim.nest.Connect(thal_pg, self.thalamic_population)

        possible_targets_curr = ['inhibitory', 'excitatory']

        # Connect
        for target_layer in layers:
            for target_pop in pops:
                target_index = structure[target_layer][target_pop]
                this_target_pop = self.pops[target_layer][target_pop]
                w_ext = self.w_ext
                # External inputs
                if input_type == 'poisson':
                    rate = bg_rate * self.K_ext[target_layer][target_pop]
                    if simulator == 'nest':
                        # create only a single Poisson generator for each
                        # population, since the native NEST implementation sends
                        # independent spike trains to all targets
                        if sim.rank() == 0:
                            print 'connecting Poisson generator to',
                            print target_layer, target_pop

                        pg = sim.nest.Create('poisson_generator',
                                             params={'rate': rate})

                        conn_dict = {'rule': 'all_to_all'}
                        syn_dict = {
                            'model': 'static_synapse',
                            'weight': 1000. * w_ext,
                            'delay': d_mean['E']
                        }
                        sim.nest.Connect(pg, list(this_target_pop.all_cells),
                                         conn_dict, syn_dict)

                if thalamic_input:
                    if sim.rank() == 0:
                        print 'creating thalamic connections to ', target_layer,
                        print target_pop
                    C_thal = thal_params['C'][target_layer][target_pop]
                    n_target = N_full[target_layer][target_pop]
                    K_thal = round(np.log(1 - C_thal) / \
                                   np.log(
                                       (n_target * thal_params['n_thal'] - 1.) /
                                       (n_target * thal_params['n_thal']))) / \
                             n_target * K_scaling

                    target_neurons = list(this_target_pop.all_cells)
                    n_syn = int(round(K_thal * len(target_neurons)))
                    conn_dict = {'rule': 'fixed_total_number', 'N': n_syn}
                    syn_dict = {'model': 'static_synapse',
                                'weight': {'distribution': 'normal_clipped',
                                           'mu': 1000. * w_ext,
                                           'sigma': 1000. * w_rel * w_ext},
                                'delay': {'distribution': 'normal_clipped',
                                          'low': conf['simulator_params'] \
                                                     [simulator]['min_delay'],
                                          'mu': d_mean['E'],
                                          'sigma': d_sd['E']}}
                    sim.nest.Connect(self.thalamic_population, target_neurons,
                                     conn_dict, syn_dict)

                # Recurrent inputs
                for source_layer in layers:
                    for source_pop in pops:
                        source_index = structure[source_layer][source_pop]
                        this_source_pop = self.pops[source_layer][source_pop]
                        weight = self.w[target_index][source_index]

                        possible_targets_curr[int((np.sign(weight) + 1) / 2)]

                        if sim.rank() == 0:
                            print 'creating connections from ', source_layer + \
                                source_pop + ' to ' + target_layer + target_pop

                        if source_pop == 'E' and source_layer == 'L4' and \
                           target_layer == 'L23' and target_pop == 'E':
                            w_sd = weight * w_rel_234
                        else:
                            w_sd = abs(weight * w_rel)

                        connectivity.FixedTotalNumberConnect(
                            sim, this_source_pop, this_target_pop,
                            self.K[target_index][source_index], weight, w_sd,
                            d_mean[source_pop], d_sd[source_pop], conf)

        return device_list
Example #19
0
EI_connections = Projection(popI, popE,
                            FixedProbabilityConnector(p_connect=plocal),
                            StaticSynapse(weight=wEI_alpha, delay=d))
II_connections = Projection(popI, popI,
                            FixedProbabilityConnector(p_connect=plocal),
                            StaticSynapse(weight=wII_alpha, delay=d))

# Stimulus
amplitudeV = 10.1  #[mV]
pulse = DCSource(amplitude=amplitudeV / R, start=300.0, stop=320.0)
pulse.inject_into(popE)

# initial conditions
kernelseed = 5456532
rng = NumpyRNG(kernelseed, parallel_safe=True)
uniformDistr = RandomDistribution('uniform', low=Vrest, high=Vt, rng=rng)
initialize(popE, v=uniformDistr)
initialize(popI, v=uniformDistr)

# Record
popE.record('spikes')
popI.record('spikes')
popE.record(['v'])  # record other variables from first two neurons
popI.record(['v'])  # record other variables from first two neurons

# Run
run(duration)

# Store spikes
spikesE_in = popE.get_data()
spikesI_in = popI.get_data()
def scenario3(sim):
    """
    Simple feed-forward network network with additive STDP. The second half of
    the presynaptic neurons fires faster than the second half, so their
    connections should be potentiated more.
    """

    init_logging(logfile=None, debug=True)
    second = 1000.0
    duration = 10
    tau_m = 20  # ms
    cm = 1.0  # nF
    v_reset = -60
    cell_parameters = dict(
        tau_m=tau_m,
        cm=cm,
        v_rest=-70,
        e_rev_E=0,
        e_rev_I=-70,
        v_thresh=-54,
        v_reset=v_reset,
        tau_syn_E=5,
        tau_syn_I=5,
    )
    g_leak = cm / tau_m  # µS

    w_min = 0.0 * g_leak
    w_max = 0.05 * g_leak

    r1 = 5.0
    r2 = 40.0

    sim.setup()
    pre = sim.Population(100, sim.SpikeSourcePoisson())
    post = sim.Population(10, sim.IF_cond_exp())

    pre.set(duration=duration * second)
    pre.set(start=0.0)
    pre[:50].set(rate=r1)
    pre[50:].set(rate=r2)
    assert_equal(pre[49].rate, r1)
    assert_equal(pre[50].rate, r2)
    post.set(**cell_parameters)
    post.initialize(v=RandomDistribution('normal', mu=v_reset, sigma=5.0))

    stdp = sim.STDPMechanism(
        sim.SpikePairRule(tau_plus=20.0,
                          tau_minus=20.0,
                          A_plus=0.01,
                          A_minus=0.01),
        sim.AdditiveWeightDependence(w_min=w_min, w_max=w_max),
        #dendritic_delay_fraction=0.5))
        dendritic_delay_fraction=1)

    connections = sim.Projection(pre,
                                 post,
                                 sim.AllToAllConnector(),
                                 synapse_type=stdp,
                                 receptor_type='excitatory')

    initial_weight_distr = RandomDistribution('uniform', low=w_min, high=w_max)
    connections.randomizeWeights(initial_weight_distr)
    initial_weights = connections.get('weight', format='array', gather=False)
    # assert initial_weights.min() >= w_min
    # assert initial_weights.max() < w_max
    # assert initial_weights[0, 0] != initial_weights[1, 0]

    pre.record('spikes')
    post.record('spikes')
    post[0:1].record('v')

    sim.run(duration * second)

    actual_rate = pre.mean_spike_count() / duration
    expected_rate = (r1 + r2) / 2
    errmsg = "actual rate: %g  expected rate: %g" % (actual_rate,
                                                     expected_rate)
    assert abs(actual_rate - expected_rate) < 1, errmsg
    #assert abs(pre[:50].mean_spike_count()/duration - r1) < 1
    #assert abs(pre[50:].mean_spike_count()/duration- r2) < 1
    final_weights = connections.get('weight', format='array', gather=False)
    assert initial_weights[0, 0] != final_weights[0, 0]

    try:
        import scipy.stats
    except ImportError:
        raise SkipTest
    t, p = scipy.stats.ttest_ind(initial_weights[:50, :].flat,
                                 initial_weights[50:, :].flat)
    assert p > 0.05, p
    t, p = scipy.stats.ttest_ind(final_weights[:50, :].flat,
                                 final_weights[50:, :].flat)
    assert p < 0.01, p
    assert final_weights[:50, :].mean() < final_weights[50:, :].mean()
    sim.end()
    return initial_weights, final_weights, pre, post, connections
Example #21
0
    def __init__(self, name, sim, rng,
                 e_cell_model, i_cell_model,
                 e_cell_params, i_cell_params,
                 e_cell_flush_time, e_cell_mean_firing_rate,
                 stim_spike_times, wta, background_weight, stim_weight, simtime,
                 record_bias, record_spikes, record_membrane):

        # Cache recording flags
        self.record_bias = record_bias
        self.record_spikes = record_spikes
        self.record_membrane = record_membrane
        self.wta = wta

        logger.info("Creating HCU:%s" % name)

        logger.debug("Membrane potentials uniformly distributed between %g mV and %g mV." % (-80, U0))
        membrane_voltage_distribution = RandomDistribution("uniform", low=-80.0, high=U0, rng=rng)

        logger.debug("Background noise rate %g Hz." % (p_rate))

        logger.debug("Creating excitatory population with %d neurons." % (NE))
        self.e_cells = sim.Population(NE, e_cell_model(**e_cell_params),
                                      label="%s - e_cells" % name)
        self.e_cells.initialize(v=membrane_voltage_distribution)

        # Set e cell mean firing rate
        self.e_cells.spinnaker_config.mean_firing_rate = e_cell_mean_firing_rate

        # Set flush time
        self.e_cells.spinnaker_config.flush_time = e_cell_flush_time

        # **YUCK** record spikes actually entirely ignores
        # sampling interval but throws exception if it is not set
        if self.record_spikes:
            self.e_cells.record("spikes", sampling_interval=100.0)

        if self.record_bias:
            self.e_cells.record("bias", sampling_interval=100.0)

        if self.record_membrane:
            self.e_cells.record("v", sampling_interval=100.0)

        e_poisson = sim.Population(NE, sim.SpikeSourcePoisson(rate=p_rate, duration=simtime),
                                   label="%s - e_poisson" % name)

        logger.debug("Creating background->E AMPA connection weight %g nA." % (background_weight))
        sim.Projection(e_poisson, self.e_cells,
                       sim.OneToOneConnector(),
                       sim.StaticSynapse(weight=background_weight, delay=delay),
                       receptor_type="excitatory")

        if self.wta:
            logger.debug("Creating inhibitory population with %d neurons." % (NI))
            self.i_cells = sim.Population(NI, i_cell_model, i_cell_params,
                                          label="%s - i_cells" % name)
            self.i_cells.initialize(v=membrane_voltage_distribution)

            # Inhibitory cells generally fire at a low rate
            self.i_cells.spinnaker_config.mean_firing_rate = 5.0

            if self.record_spikes:
                self.i_cells.record("spikes")

            i_poisson = sim.Population(NI, sim.SpikeSourcePoisson(rate=p_rate, duration=simtime),
                                       label="%s - i_poisson" % name)

            logger.debug("Creating I->E GABA connection with connection probability %g, weight %g nA and delay %g ms." % (epsilon, JI, delay))
            I_to_E = sim.Projection(self.i_cells, self.e_cells,
                                    sim.FixedProbabilityConnector(p_connect=epsilon, rng=rng),
                                    sim.StaticSynapse(weight=JI, delay=delay),
                                    receptor_type="inhibitory")

            logger.debug("Creating E->I AMPA connection with connection probability %g, weight %g nA and delay %g ms." % (epsilon, JE, delay))
            sim.Projection(self.e_cells, self.i_cells,
                           sim.FixedProbabilityConnector(p_connect=epsilon, rng=rng),
                           sim.StaticSynapse(weight=JE, delay=delay),
                           receptor_type="excitatory")

            logger.debug("Creating I->I GABA connection with connection probability %g, weight %g nA and delay %g ms." % (epsilon, JI, delay))
            sim.Projection(self.i_cells, self.i_cells,
                           sim.FixedProbabilityConnector(p_connect=epsilon, rng=rng),
                           sim.StaticSynapse(weight=JI, delay=delay),
                           receptor_type="inhibitory")

            logger.debug("Creating background->I AMPA connection weight %g nA." % (background_weight))
            sim.Projection(i_poisson, self.i_cells,
                           sim.OneToOneConnector(),
                           sim.StaticSynapse(weight=background_weight, delay=delay),
                           receptor_type="excitatory")

        # Create a spike source capable of stimulating entirely excitatory population
        stim_spike_source = sim.Population(NE, sim.SpikeSourceArray(spike_times=stim_spike_times))

        # Connect one-to-one to excitatory neurons
        sim.Projection(stim_spike_source, self.e_cells,
                       sim.OneToOneConnector(),
                       sim.StaticSynapse(weight=stim_weight, delay=delay),
                       receptor_type="excitatory")
Example #22
0
weight_exc = 0.1
weight_inh = -5.0 * weight_exc
weight_input = 0.001

pop_input = p.Population(100, p.SpikeSourcePoisson(rate=0), label="Input")

pop_exc = p.Population(n_exc, p.IF_curr_exp, label="Excitatory",
                       additional_parameters={"spikes_per_second": 100})
pop_inh = p.Population(n_inh, p.IF_curr_exp, label="Inhibitory",
                       additional_parameters={"spikes_per_second": 100})
stim_exc = p.Population(
    n_exc, p.SpikeSourcePoisson(rate=1000.0), label="Stim_Exc")
stim_inh = p.Population(
    n_inh, p.SpikeSourcePoisson(rate=1000.0), label="Stim_Inh")

delays_exc = RandomDistribution(
    "normal_clipped", mu=1.5, sigma=0.75, low=1.0, high=14.4)
weights_exc = RandomDistribution(
    "normal_clipped", mu=weight_exc, sigma=0.1, low=0, high=numpy.inf)
conn_exc = p.FixedProbabilityConnector(0.1)
synapse_exc = p.StaticSynapse(weight=weights_exc, delay=delays_exc)
delays_inh = RandomDistribution(
    "normal_clipped", mu=0.75, sigma=0.375, low=1.0, high=14.4)
weights_inh = RandomDistribution(
    "normal_clipped", mu=weight_inh, sigma=0.1, low=-numpy.inf, high=0)
conn_inh = p.FixedProbabilityConnector(0.1)
synapse_inh = p.StaticSynapse(weight=weights_inh, delay=delays_inh)
p.Projection(
    pop_exc, pop_exc, conn_exc, synapse_exc, receptor_type="excitatory")
p.Projection(
    pop_exc, pop_inh, conn_exc, synapse_exc, receptor_type="excitatory")
p.Projection(
Example #23
0
#stdp_model = p.STDPMechanism( timing_dependence = p.RecurrentRule(accumulator_depression = -6, accumulator_potentiation = 6, mean_pre_window = 10.0, mean_post_window = 10.0), weight_dependence = p.SimpleMultiplicativeWeightDependence(potentiation_multiplier = 1.3, depression_multiplier = 1.3))
stdp_model = p.STDPMechanism(
    timing_dependence=p.RecurrentRule(accumulator_depression=-6,
                                      accumulator_potentiation=6,
                                      mean_pre_window=10.0,
                                      mean_post_window=10.0),
    weight_dependence=p.MultiplicativeWeightDependence(w_min=0.0,
                                                       w_max=16.0,
                                                       A_plus=0.4,
                                                       A_minus=0.4))

rng = NumpyRNG(seed=1)
ext_delay_distr = RandomDistribution('normal',
                                     parameters=[1.5, 0.75],
                                     rng=rng,
                                     boundaries=[0.1, 9.9],
                                     constrain='redraw')
inh_delay_distr = RandomDistribution('normal',
                                     parameters=[0.75, 0.375],
                                     rng=rng,
                                     boundaries=[0.1, 9.9],
                                     constrain='redraw')
delay_distr_recurrent = RandomDistribution('uniform', [2.0, 8.0], rng=rng)
weight_distr_ffwd = RandomDistribution('uniform', [0.5, 1.25], rng=rng)
weight_distr_recurrent = RandomDistribution('uniform', [0.1, 0.2], rng=rng)

projections.append(
    p.Projection(populations[stimulus],
                 populations[excit],
                 p.AllToAllConnector(weights=baseline_excit_weight,
Example #24
0
    def all(self):
        return self.all_cells

    @property
    def size(self):
        return self.all_cells.size


p1 = MockPopulation(100)
p2 = MockPopulation(100)

rng = NumpyRNG(8569552)

weight_sources = [
    0.1,
    RandomDistribution('uniform', (0, 1), rng),
    numpy.arange(0.0, 1.0, 1e-4).reshape(100, 100), "exp(-(d*d)/1e4)"
]

for weight_source in weight_sources:
    connector = FixedProbabilityConnector(p_connect=0.3,
                                          allow_self_connections=True,
                                          weights=weight_source,
                                          delays=0.2)
    prj = MockProjection(p1, p2, rng)
    connector.connect(prj)
    connector = AllToAllConnector(allow_self_connections=True,
                                  weights=weight_source,
                                  delays=0.2)
    prj = MockProjection(p1, p2, rng)
    connector.connect(prj)
import numpy as np
import matplotlib.pyplot as plt

N_e = 75  # number of excitatory neurons
N_i = 25  # number of inhibitatory neurons
Exc_in = 32  # number of excitatory inputs
Inh_in = 32  # number of inhibitatory inputs
# No_inp = {'exc': 32, 'inh': 32}

run_time = 500  # define the simulation time

# ==========generate OR read in the input spikes data=====================
noSpikes = 20  # number of spikes per chanel per simulation run
stimSpikes = RandomDistribution(
    'uniform', low=0, high=run_time, rng=NumpyRNG(seed=72386)
).next(
    [Exc_in + Inh_in, noSpikes]
)  # generate a time uniform distributed signal with Exc_in + Inh_in chanels and noSpikes for each chanel
# todo: 64 chanel represents different data

sim.setup()  # start buiding up the network topology

# ==========create the input signal neuron population==================
# form the Exc_in chanels excitatory inputs as a assembly Inhinp
for i in range(Exc_in):
    if i == 0:
        Excinp = sim.Population(
            1, sim.SpikeSourceArray(spike_times=stimSpikes[i, :]))
    else:
        spike_source = sim.Population(
            1, sim.SpikeSourceArray(spike_times=stimSpikes[i, :]))
Example #26
0

timer.start()  # start timer on construction

print "%d Setting up random number generator" % rank
rng = NumpyRNG(kernelseed, parallel_safe=True)

print "%d Creating excitatory population with %d neurons." % (rank, NE)
E_net = Population(NE, IF_curr_alpha, cell_params, label="E_net")

print "%d Creating inhibitory population with %d neurons." % (rank, NI)
I_net = Population(NI, IF_curr_alpha, cell_params, label="I_net")

print "%d Initialising membrane potential to random values between %g mV and %g mV." % (
    rank, U0, theta)
uniformDistr = RandomDistribution('uniform', [U0, theta], rng)
E_net.initialize('v', uniformDistr)
I_net.initialize('v', uniformDistr)

print "%d Creating excitatory Poisson generator with rate %g spikes/s." % (
    rank, p_rate)
expoisson = Population(NE, SpikeSourcePoisson, {'rate': p_rate}, "expoisson")

print "%d Creating inhibitory Poisson generator with the same rate." % rank
inpoisson = Population(NI, SpikeSourcePoisson, {'rate': p_rate}, "inpoisson")

# Record spikes
print "%d Setting up recording in excitatory population." % rank
E_net.record(Nrec)
E_net[[0, 1]].record_v()
Example #27
0
        # group the populations into an assembly
        all_cells = exc_cells + inh_cells

if options.benchmark == "COBA":
    ext_stim = sim.Population(20,
                              sim.SpikeSourcePoisson(rate=rate,
                                                     duration=stim_dur),
                              label="expoisson")
    rconn = 0.01
    ext_conn = sim.FixedProbabilityConnector(rconn)
    ext_syn = sim.StaticSynapse(weight=0.1)

print("%s Initialising membrane potential to random values..." % node_id)
rng = NumpyRNG(seed=rngseed, parallel_safe=parallel_safe)
uniformDistr = RandomDistribution('uniform',
                                  low=v_reset,
                                  high=v_thresh,
                                  rng=rng)
if options.use_views:
    all_cells.initialize(v=uniformDistr)
else:
    exc_cells.initialize(v=uniformDistr)
    inh_cells.initialize(v=uniformDistr)

print("%s Connecting populations..." % node_id)
progress_bar = ProgressBar(width=20)
if options.use_csa:
    connector = sim.CSAConnector(csa.cset(csa.random(pconn)))
else:
    connector = sim.FixedProbabilityConnector(pconn,
                                              rng=rng,
                                              callback=progress_bar)
pattern2_stim 		= Population(numOfNeuronsPattern2_stim		, cell_type, label='pattern2_stim')

patternIntersection 	= Population(numOfNeuronsPatternIntersection	, cell_type, label='patternIntersection')

controlPopulation	= Population(numOfNeuronsControl		, cell_type, label='controlPop')


stimulus = Population(1000, SpikeSourcePoisson(rate=100.0))


print("-> DONE")
print("----------------------------------------------------------------------")
print("---------- Initialising membrane potential to random values ----------")
print("----------------------------------------------------------------------")

rand_distr = RandomDistribution('uniform', (v_reset, v_thresh), rng=NumpyRNG(seed=85524))

excPopulation.initialize(v=rand_distr)
inhibPopulation.initialize(v=rand_distr)
pattern1.initialize(v=rand_distr)
pattern1_stim.initialize(v=rand_distr)
pattern2.initialize(v=rand_distr)
pattern2_stim.initialize(v=rand_distr)
patternIntersection.initialize(v=rand_distr)
controlPopulation.initialize(v=rand_distr)

print("-> DONE")

# allow self-connections??

# what are the initial conditions??
Example #29
0
                               stop=duration)
    popE[i].inject(noise)

# Noise on inhibitory neurons
stdNoiseI = (sigmaV / R) * (tauI_m**0.5) / (dt**0.5)
for i in range(nAreas * NI):
    noise = NoisyCurrentSource(mean=0,
                               stdev=stdNoiseI,
                               start=0.0,
                               stop=duration)
    popI[i].inject(noise)

# paramters for initial conditions
kernelseed = 5456532
rng = NumpyRNG(kernelseed, parallel_safe=True)
uniformDistr = RandomDistribution('uniform', low=Vrest, high=Vt, rng=rng)
initialize(popE, v=uniformDistr)
initialize(popI, v=uniformDistr)

# Separate population in population views
popEList = []
popIList = []

# Store projections
EE = []
IE = []
EI = []
II = []
EElongRange = []
IElongRange = []
for i in range(nAreas):
start_time_1 = 0.00
stop_time_1 = 150.00
rate_1 = 100  # unit Hz

# second period signal
start_time_2 = stop_time_1
stop_time_2 = 350
rate_2 = 200

# third period signal
start_time_3 = stop_time_2
stop_time_3 = 500.00
rate_3 = 100  # unit Hz

spike_times_1 = RandomDistribution('uniform', (start_time_1, stop_time_1),
                                   rng=NumpyRNG(seed=72386)).next(
                                       int((stop_time_1 - start_time_1) *
                                           rate_1 * 1e-3))

spike_times_2 = RandomDistribution('uniform', (start_time_2, stop_time_2),
                                   rng=NumpyRNG(seed=72389)).next(
                                       int((stop_time_2 - start_time_2) *
                                           rate_2 * 1e-3))

spike_times_3 = RandomDistribution('uniform', (start_time_3, stop_time_3),
                                   rng=NumpyRNG(seed=72389)).next(
                                       int((stop_time_3 - start_time_3) *
                                           rate_3 * 1e-3))

print type(spike_times_1)
spike_time = np.concatenate((spike_times_1, spike_times_2, spike_times_3),
                            axis=0)