Beispiel #1
0
    def test_simulation_theory(self):
        reset_brian2()

        t = 3000 * ms
        dt = 0.01 * ms
        n = 100

        alpha = 0.5

        poisson = MFPoissonPopulation(n, n * 10 * Hz)
        pop = MFLinearPopulation(
            n, {
                PP.GM: 10 * nsiemens,
                PP.VL: 0 * mV,
                PP.CM: 5 * nfarad,
                PP.VTHR: 0 * mV,
                PP.VRES: 0 * mV,
                PP.TAU_RP: 15 * ms
            })
        syn = MFLinear3TSInput(
            poisson, pop, {
                IP.GM: 10 * nsiemens,
                IP.VREV: 0 * mvolt,
                IP.TAU: 0 * ms,
                IP.TAU_RISE: 2 * ms,
                IP.TAU_D1: 20 * ms,
                IP.TAU_D2: 30 * ms,
                IP.ALPHA: alpha
            })

        system = MFSystem(pop, poisson)

        solver = MFSolver.rates_voltages(system, solver='mse')
        solver.run()
        theory = syn.g_dyn() / syn.origin.n

        print(syn.brian2)

        m1 = StateMonitor(syn.brian2,
                          syn.post_variable_name[0],
                          record=range(100))
        m2 = StateMonitor(syn.brian2,
                          syn.post_variable_name[1],
                          record=range(100))
        m3 = StateMonitor(syn.brian2,
                          syn.post_variable_name[2],
                          record=range(100))
        m4 = StateMonitor(syn.brian2,
                          syn.post_variable_name[3],
                          record=range(100))
        defaultclock.dt = dt

        net = system.collect_brian2_network(m1, m2, m3, m4)
        net.run(t)

        stable_t = int(t / dt * 0.1)
        simulation_1 = m1.__getattr__(syn.post_variable_name[0])[:, stable_t:]
        simulation_mean_1 = np.mean(simulation_1)
        simulation_2 = m2.__getattr__(syn.post_variable_name[1])[:, stable_t:]
        simulation_mean_2 = np.mean(simulation_2)
        simulation_3 = m3.__getattr__(syn.post_variable_name[2])[:, stable_t:]
        simulation_mean_3 = np.mean(simulation_3)
        simulation_4 = m4.__getattr__(syn.post_variable_name[3])[:, stable_t:]
        simulation_mean_4 = np.mean(simulation_4)

        simulation_mean = alpha * simulation_mean_1 + (
            1 - alpha) * simulation_mean_2 + -alpha * simulation_mean_3 - (
                1 - alpha) * simulation_mean_4

        assert np.isclose(theory, simulation_mean, rtol=0.5, atol=0.5)
def test_ExportDevice_basic():
    """
    Test the components and structure of the dictionary exported
    by ExportDevice
    """
    start_scope()
    set_device('exporter')

    grp = NeuronGroup(10,
                      'dv/dt = (1-v)/tau :1',
                      method='exact',
                      threshold='v > 0.5',
                      reset='v = 0',
                      refractory=2 * ms)
    tau = 10 * ms
    rate = '1/tau'
    grp.v['i > 2 and i < 5'] = -0.2
    pgrp = PoissonGroup(10, rates=rate)
    smon = SpikeMonitor(pgrp)
    smon.active = False
    netobj = Network(grp, pgrp, smon)
    netobj.run(100 * ms)
    dev_dict = device.runs
    # check the structure and components in dev_dict
    assert dev_dict[0]['duration'] == 100 * ms
    assert dev_dict[0]['inactive'][0] == smon.name
    components = dev_dict[0]['components']
    assert components['spikemonitor'][0]
    assert components['poissongroup'][0]
    assert components['neurongroup'][0]
    initializers = dev_dict[0]['initializers_connectors']
    assert initializers[0]['source'] == grp.name
    assert initializers[0]['variable'] == 'v'
    assert initializers[0]['index'] == 'i > 2 and i < 5'
    # TODO: why not a Quantity type?
    assert initializers[0]['value'] == '-0.2'
    with pytest.raises(KeyError):
        initializers[0]['identifiers']
    device.reinit()

    start_scope()
    set_device('exporter', build_on_run=False)
    tau = 10 * ms
    v0 = -70 * mV
    vth = 800 * mV
    grp = NeuronGroup(10,
                      'dv/dt = (v0-v)/tau :volt',
                      method='exact',
                      threshold='v > vth',
                      reset='v = v0',
                      refractory=2 * ms)
    v0 = -80 * mV
    grp.v[:] = 'v0 + 2 * mV'
    smon = StateMonitor(grp, 'v', record=True)
    smon.active = False
    net = Network(grp, smon)
    net.run(10 * ms)  # first run
    v0 = -75 * mV
    grp.v[3:8] = list(range(3, 8)) * mV
    smon.active = True
    net.run(20 * ms)  # second run
    v_new = -5 * mV
    grp.v['i >= 5'] = 'v0 + v_new'
    v_new = -10 * mV
    grp.v['i < 5'] = 'v0 - v_new'
    spikemon = SpikeMonitor(grp)
    net.add(spikemon)
    net.run(5 * ms)  # third run
    dev_dict = device.runs
    # check run1
    assert dev_dict[0]['duration'] == 10 * ms
    assert dev_dict[0]['inactive'][0] == smon.name
    components = dev_dict[0]['components']
    assert components['statemonitor'][0]
    assert components['neurongroup'][0]
    initializers = dev_dict[0]['initializers_connectors']
    assert initializers[0]['source'] == grp.name
    assert initializers[0]['variable'] == 'v'
    assert initializers[0]['index']
    assert initializers[0]['value'] == 'v0 + 2 * mV'
    assert initializers[0]['identifiers']['v0'] == -80 * mV
    with pytest.raises(KeyError):
        initializers[0]['identifiers']['mV']
    # check run2
    assert dev_dict[1]['duration'] == 20 * ms
    initializers = dev_dict[1]['initializers_connectors']
    assert initializers[0]['source'] == grp.name
    assert initializers[0]['variable'] == 'v'
    assert (initializers[0]['index'] == grp.indices[slice(3, 8, None)]).all()
    assert (initializers[0]['value'] == list(range(3, 8)) * mV).all()
    with pytest.raises(KeyError):
        dev_dict[1]['inactive']
        initializers[1]['identifiers']
    # check run3
    assert dev_dict[2]['duration'] == 5 * ms
    with pytest.raises(KeyError):
        dev_dict[2]['inactive']
    assert dev_dict[2]['components']['spikemonitor']
    initializers = dev_dict[2]['initializers_connectors']
    assert initializers[0]['source'] == grp.name
    assert initializers[0]['variable'] == 'v'
    assert initializers[0]['index'] == 'i >= 5'
    assert initializers[0]['value'] == 'v0 + v_new'
    assert initializers[0]['identifiers']['v0'] == -75 * mV
    assert initializers[0]['identifiers']['v_new'] == -5 * mV
    assert initializers[1]['index'] == 'i < 5'
    assert initializers[1]['value'] == 'v0 - v_new'
    assert initializers[1]['identifiers']['v_new'] == -10 * mV
    with pytest.raises(IndexError):
        initializers[2]
        dev_dict[3]
    device.reinit()
Beispiel #3
0
#I_Gate = 1
# Current input / Zap frequency-sweep parameters
I_Bias = 0 * pA
I_Zap_Max = 0 * pA
sweepdur = 1 * second
#sweepdur_ms = 960*ms
#f_max = 100*Hz
f_max = 2000 * Hz
f_min = 1 * Hz
m1000 = (f_max - f_min) / (2 * (sweepdur - defaultclock.dt))
t_settle = 50 * ms
t_bias = 450 * ms
#zap1000_0p96 = I_Zap_Max * sin(2*pi*(m1000*(t - t_settle) + f_min) * (t - t_settle));

#M = StateMonitor(lsonGrp, 'v', record=True)
M = StateMonitor(lsonGrp, ['v', 'I'], record=True)
run(t_settle, report='text')  # Go to rest

I_Bias = 9. * pA
run(t_bias, report='text')  # Equilibrate to I_Bias
IBiasStr = 'IBias' + str(int(I_Bias / pA)) + 'pA'

I_Zap_Max = 1. * pA
run(sweepdur, report='text')  # Apply Zap current
IZapMaxStr = 'IZapMax' + str(int(I_Zap_Max / pA)) + 'pA'

I_Zap_Max = 0. * pA
run(100 * ms, report='text')

fftStart = round((t_settle + t_bias) / defaultclock.dt)
fftStop = round((t_settle + t_bias + sweepdur) / defaultclock.dt)
lsonSynI = Synapses(gbCoSpkGenGrp, lsonGrp, 
                 model='''dg_i/dt = -g_i/tausI : siemens (clock-driven)
                          gs_i_post = g_i : siemens (summed)''',
                 on_pre='g_i += w_ilson*siemens',
                 method = 'exact')
lsonSynI.connect(i=np.arange(nGbcsCoPerLson), j=0)

#lsonSynE = Synapses(sbIpSpkGenGrp, lsonGrp, 
#                 model='''dg_e/dt = -g_e/tausE : siemens (clock-driven)
#                          gs_e_post = g_e : siemens (summed)''',
#                 on_pre='g_e += w_elson*siemens',
#                 method = 'exact')
#lsonSynE.connect(i=np.arange(nSbcsIpPerLson), j=0)

lsonSpks = SpikeMonitor(lsonGrp)
lsonState = StateMonitor(lsonGrp, ['gs_e','Is_e','gs_i','Is_i','v'], record=True)

run(50*ms, report='text')

plt.plot(lsonState.t / ms, lsonState[0].gs_e / nS)
plt.xlabel('t (ms)')
plt.ylabel('gs_e (nS)')
plt.show()

plt.plot(lsonState.t / ms, lsonState[0].Is_e / pA)
plt.xlabel('t (ms)')
plt.ylabel('Is_e (pA)')
plt.show()

plt.plot(lsonState.t / ms, lsonState[0].gs_i / nS)
plt.xlabel('t (ms)')
Beispiel #5
0
def run_net(tr):

    # prefs.codegen.target = 'numpy'
    # prefs.codegen.target = 'cython'
    set_device('cpp_standalone',
               directory='./builds/%.4d' % (tr.v_idx),
               build_on_run=False)

    print("Started process with id ", str(tr.v_idx))

    T = tr.T1 + tr.T2 + tr.T3

    namespace = tr.netw.f_to_dict(short_names=True, fast_access=True)
    namespace['idx'] = tr.v_idx

    defaultclock.dt = tr.netw.sim.dt

    GExc = NeuronGroup(
        N=tr.N_e,
        model=tr.condlif_sig,
        threshold=tr.nrnEE_thrshld,
        reset=tr.nrnEE_reset,  #method=tr.neuron_method,
        namespace=namespace)
    GInh = NeuronGroup(
        N=tr.N_i,
        model=tr.condlif_sig,
        threshold='V > Vt',
        reset='V=Vr_i',  #method=tr.neuron_method,
        namespace=namespace)

    # set initial thresholds fixed, init. potentials uniformly distrib.
    GExc.sigma, GInh.sigma = tr.sigma_e, tr.sigma_i
    GExc.Vt, GInh.Vt = tr.Vt_e, tr.Vt_i
    GExc.V , GInh.V  = np.random.uniform(tr.Vr_e/mV, tr.Vt_e/mV,
                                         size=tr.N_e)*mV, \
                       np.random.uniform(tr.Vr_i/mV, tr.Vt_i/mV,
                                         size=tr.N_i)*mV

    print("need to fix?")
    synEE_pre_mod = mod.synEE_pre
    synEE_post_mod = mod.synEE_post

    if tr.PInp_mode == 'pool':
        PInp = PoissonGroup(tr.NPInp, rates=tr.PInp_rate, namespace=namespace)
        sPN = Synapses(target=GExc,
                       source=PInp,
                       model=tr.poisson_mod,
                       on_pre='gfwd_post += a_EPoi',
                       namespace=namespace)

        sPN_src, sPN_tar = generate_N_connections(N_tar=tr.N_e,
                                                  N_src=tr.NPInp,
                                                  N=tr.NPInp_1n)

    elif tr.PInp_mode == 'indep':
        PInp = PoissonGroup(tr.N_e, rates=tr.PInp_rate, namespace=namespace)
        sPN = Synapses(target=GExc,
                       source=PInp,
                       model=tr.poisson_mod,
                       on_pre='gfwd_post += a_EPoi',
                       namespace=namespace)
        sPN_src, sPN_tar = range(tr.N_e), range(tr.N_e)

    sPN.connect(i=sPN_src, j=sPN_tar)

    if tr.PInp_mode == 'pool':
        PInp_inh = PoissonGroup(tr.NPInp_inh,
                                rates=tr.PInp_inh_rate,
                                namespace=namespace)
        sPNInh = Synapses(target=GInh,
                          source=PInp_inh,
                          model=tr.poisson_mod,
                          on_pre='gfwd_post += a_EPoi',
                          namespace=namespace)
        sPNInh_src, sPNInh_tar = generate_N_connections(N_tar=tr.N_i,
                                                        N_src=tr.NPInp_inh,
                                                        N=tr.NPInp_inh_1n)

    elif tr.PInp_mode == 'indep':

        PInp_inh = PoissonGroup(tr.N_i,
                                rates=tr.PInp_inh_rate,
                                namespace=namespace)
        sPNInh = Synapses(target=GInh,
                          source=PInp_inh,
                          model=tr.poisson_mod,
                          on_pre='gfwd_post += a_EPoi',
                          namespace=namespace)
        sPNInh_src, sPNInh_tar = range(tr.N_i), range(tr.N_i)

    sPNInh.connect(i=sPNInh_src, j=sPNInh_tar)

    if tr.stdp_active:
        synEE_pre_mod = '''%s 
                            %s''' % (synEE_pre_mod, mod.synEE_pre_STDP)
        synEE_post_mod = '''%s 
                            %s''' % (synEE_post_mod, mod.synEE_post_STDP)

    if tr.synEE_rec:
        synEE_pre_mod = '''%s 
                            %s''' % (synEE_pre_mod, mod.synEE_pre_rec)
        synEE_post_mod = '''%s 
                            %s''' % (synEE_post_mod, mod.synEE_post_rec)

    # E<-E advanced synapse model, rest simple
    SynEE = Synapses(
        target=GExc,
        source=GExc,
        model=tr.synEE_mod,
        on_pre=synEE_pre_mod,
        on_post=synEE_post_mod,
        #method=tr.synEE_method,
        namespace=namespace)
    SynIE = Synapses(target=GInh,
                     source=GExc,
                     on_pre='ge_post += a_ie',
                     namespace=namespace)
    SynEI = Synapses(target=GExc,
                     source=GInh,
                     on_pre='gi_post += a_ei',
                     namespace=namespace)
    SynII = Synapses(target=GInh,
                     source=GInh,
                     on_pre='gi_post += a_ii',
                     namespace=namespace)

    if tr.strct_active:
        sEE_src, sEE_tar = generate_full_connectivity(tr.N_e, same=True)
        SynEE.connect(i=sEE_src, j=sEE_tar)
        SynEE.syn_active = 0

    else:
        srcs_full, tars_full = generate_full_connectivity(tr.N_e, same=True)
        SynEE.connect(i=srcs_full, j=tars_full)
        SynEE.syn_active = 0

    sIE_src, sIE_tar = generate_connections(tr.N_i, tr.N_e, tr.p_ie)
    sEI_src, sEI_tar = generate_connections(tr.N_e, tr.N_i, tr.p_ei)
    sII_src, sII_tar = generate_connections(tr.N_i, tr.N_i, tr.p_ii, same=True)

    SynIE.connect(i=sIE_src, j=sIE_tar)
    SynEI.connect(i=sEI_src, j=sEI_tar)
    SynII.connect(i=sII_src, j=sII_tar)

    tr.f_add_result('sIE_src', sIE_src)
    tr.f_add_result('sIE_tar', sIE_tar)
    tr.f_add_result('sEI_src', sEI_src)
    tr.f_add_result('sEI_tar', sEI_tar)
    tr.f_add_result('sII_src', sII_src)
    tr.f_add_result('sII_tar', sII_tar)

    SynEE.a = tr.a_ee

    SynEE.insert_P = tr.insert_P
    SynEE.p_inactivate = tr.p_inactivate

    # make synapse active at beginning
    SynEE.run_regularly(tr.synEE_p_activate, dt=T, when='start', order=-100)

    # synaptic scaling
    if tr.netw.config.scl_active:
        SynEE.summed_updaters['Asum_post']._clock = Clock(
            dt=tr.dt_synEE_scaling)
        SynEE.run_regularly(tr.synEE_scaling,
                            dt=tr.dt_synEE_scaling,
                            when='end')

    # intrinsic plasticity
    if tr.netw.config.it_active:
        GExc.h_ip = tr.h_ip
        GExc.run_regularly(tr.intrinsic_mod, dt=tr.it_dt, when='end')

    # structural plasticity
    if tr.netw.config.strct_active:
        if tr.strct_mode == 'zero':
            if tr.turnover_rec:
                strct_mod = '''%s 
                                %s''' % (tr.strct_mod, tr.turnover_rec_mod)
            else:
                strct_mod = tr.strct_mod

            SynEE.run_regularly(strct_mod, dt=tr.strct_dt, when='end')

        elif tr.strct_mode == 'thrs':
            if tr.turnover_rec:
                strct_mod_thrs = '''%s 
                                %s''' % (tr.strct_mod_thrs,
                                         tr.turnover_rec_mod)
            else:
                strct_mod_thrs = tr.strct_mod_thrs

            SynEE.run_regularly(strct_mod_thrs, dt=tr.strct_dt, when='end')

    # -------------- recording ------------------

    #run(tr.sim.preT)

    GExc_recvars = []
    if tr.memtraces_rec:
        GExc_recvars.append('V')
    if tr.vttraces_rec:
        GExc_recvars.append('Vt')
    if tr.getraces_rec:
        GExc_recvars.append('ge')
    if tr.gitraces_rec:
        GExc_recvars.append('gi')
    if tr.gfwdtraces_rec:
        GExc_recvars.append('gfwd')

    GInh_recvars = GExc_recvars

    GExc_stat = StateMonitor(GExc,
                             GExc_recvars,
                             record=[0, 1, 2],
                             dt=tr.GExc_stat_dt)
    GInh_stat = StateMonitor(GInh,
                             GInh_recvars,
                             record=[0, 1, 2],
                             dt=tr.GInh_stat_dt)

    SynEE_recvars = []
    if tr.synee_atraces_rec:
        SynEE_recvars.append('a')
    if tr.synee_Apretraces_rec:
        SynEE_recvars.append('Apre')
    if tr.synee_Aposttraces_rec:
        SynEE_recvars.append('Apost')

    SynEE_stat = StateMonitor(SynEE,
                              SynEE_recvars,
                              record=range(tr.n_synee_traces_rec),
                              when='end',
                              dt=tr.synEE_stat_dt)

    GExc_spks = SpikeMonitor(GExc)
    GInh_spks = SpikeMonitor(GInh)
    PInp_spks = SpikeMonitor(PInp)

    GExc_rate = PopulationRateMonitor(GExc)
    GInh_rate = PopulationRateMonitor(GInh)
    PInp_rate = PopulationRateMonitor(PInp)

    if tr.synee_a_nrecpoints == 0:
        SynEE_a_dt = 10 * tr.sim.T2
    else:
        SynEE_a_dt = tr.sim.T2 / tr.synee_a_nrecpoints
    SynEE_a = StateMonitor(SynEE, ['a', 'syn_active'],
                           record=range(tr.N_e * (tr.N_e - 1)),
                           dt=SynEE_a_dt,
                           when='end',
                           order=100)

    net = Network(GExc, GInh, PInp, sPN, sPNInh, SynEE, SynEI, SynIE, SynII,
                  GExc_stat, GInh_stat, SynEE_stat, SynEE_a, GExc_spks,
                  GInh_spks, PInp_spks, GExc_rate, GInh_rate, PInp_rate,
                  PInp_inh)

    spks_recorders = [GExc_spks, GInh_spks, PInp_spks]
    stat_recorders = [SynEE_stat, GExc_stat, GInh_stat]
    rate_recorders = [GExc_rate, GInh_rate, PInp_rate]

    for rcc in spks_recorders:
        rcc.active = False
    for rcc in stat_recorders:
        rcc.active = False
    for rcc in rate_recorders:
        rcc.active = False

    for rcc in stat_recorders:
        rcc.active = True
    if tr.rates_rec:
        for rcc in rate_recorders:
            rcc.active = True
    if tr.spks_rec:
        GExc_spks.active = True
        GInh_spks.active = True
        PInp_spks.active = True

    net.run(tr.sim.T1, report='text')

    for rcc in spks_recorders:
        rcc.active = False
    for rcc in stat_recorders:
        rcc.active = False
    for rcc in rate_recorders:
        rcc.active = False

    # print('''Hack solution: Simulate single timestep
    #          to avoid missing simulation chunks''')
    # net.run(tr.dt)

    for time_step in range(int(tr.sim.T2 / (100 * second))):
        net.run(100 * second, report='text')

    for rcc in stat_recorders:
        rcc.active = True
    if tr.rates_rec:
        for rcc in rate_recorders:
            rcc.active = True
    if tr.spks_rec:
        GExc_spks.active = True
        GInh_spks.active = True
        PInp_spks.active = True

    net.run(tr.sim.T3, report='text')
    SynEE_a.record_single_timestep()

    device.build(directory='builds/%.4d' % (tr.v_idx), clean=True)

    # save monitors as raws in build directory
    raw_dir = 'builds/%.4d/raw/' % (tr.v_idx)

    if not os.path.exists(raw_dir):
        os.makedirs(raw_dir)

    with open(raw_dir + 'namespace.p', 'wb') as pfile:
        pickle.dump(namespace, pfile)

    with open(raw_dir + 'gexc_stat.p', 'wb') as pfile:
        pickle.dump(GExc_stat.get_states(), pfile)
    with open(raw_dir + 'ginh_stat.p', 'wb') as pfile:
        pickle.dump(GInh_stat.get_states(), pfile)

    with open(raw_dir + 'synee_stat.p', 'wb') as pfile:
        pickle.dump(SynEE_stat.get_states(), pfile)
    with open(raw_dir + 'synee_a.p', 'wb') as pfile:
        pickle.dump(SynEE_a.get_states(), pfile)

    with open(raw_dir + 'gexc_spks.p', 'wb') as pfile:
        pickle.dump(GExc_spks.get_states(), pfile)
    with open(raw_dir + 'ginh_spks.p', 'wb') as pfile:
        pickle.dump(GInh_spks.get_states(), pfile)
    with open(raw_dir + 'pinp_spks.p', 'wb') as pfile:
        pickle.dump(PInp_spks.get_states(), pfile)

    with open(raw_dir + 'gexc_rate.p', 'wb') as pfile:
        pickle.dump(GExc_rate.get_states(), pfile)
        if tr.rates_rec:
            pickle.dump(GExc_rate.smooth_rate(width=25 * ms), pfile)
    with open(raw_dir + 'ginh_rate.p', 'wb') as pfile:
        pickle.dump(GInh_rate.get_states(), pfile)
        if tr.rates_rec:
            pickle.dump(GInh_rate.smooth_rate(width=25 * ms), pfile)
    with open(raw_dir + 'pinp_rate.p', 'wb') as pfile:
        pickle.dump(PInp_rate.get_states(), pfile)
        if tr.rates_rec:
            pickle.dump(PInp_rate.smooth_rate(width=25 * ms), pfile)

    # ----------------- add raw data ------------------------
    fpath = 'builds/%.4d/' % (tr.v_idx)

    from pathlib import Path

    Path(fpath + 'turnover').touch()
    turnover_data = np.genfromtxt(fpath + 'turnover', delimiter=',')
    os.remove(fpath + 'turnover')

    with open(raw_dir + 'turnover.p', 'wb') as pfile:
        pickle.dump(turnover_data, pfile)

    Path(fpath + 'spk_register').touch()
    spk_register_data = np.genfromtxt(fpath + 'spk_register', delimiter=',')
    os.remove(fpath + 'spk_register')

    with open(raw_dir + 'spk_register.p', 'wb') as pfile:
        pickle.dump(spk_register_data, pfile)

    # ---------------- create the powerlaw fit ---------------

    # if len(turnover_data) > 10:

    #     _lt, _dt = extract_lifetimes(turnover_data, tr.N_e,
    #                                  with_starters=True)
    #     life_t, death_t = _lt*second, _dt*second

    #     if len(life_t)>25:
    #         fit_wstart = powerlaw.Fit(life_t/ms, discrete=True)

    #     _lt, _dt = extract_lifetimes(turnover_data, tr.N_e,
    #                                  with_starters=False)
    #     life_t, death_t = _lt*second, _dt*second

    #     if len(life_t)>25:
    #         fit_nostart = powerlaw.Fit(life_t/ms, discrete=True)

    #         with open(raw_dir+'powerlaw_fit.p', 'wb') as pfile:
    #             pickle.dump({'fit_wstart': fit_wstart,
    #                          'fit_nostart': fit_nostart}, pfile)

    # -----------------  clean up  ---------------------------
    shutil.rmtree('builds/%.4d/results/' % (tr.v_idx))

    # ---------------- plot results --------------------------

    #os.chdir('./analysis/file_based/')

    from analysis.overview_fb import overview_figure
    overview_figure('builds/%.4d' % (tr.v_idx), namespace)

    from analysis.synw_fb import synw_figure
    synw_figure('builds/%.4d' % (tr.v_idx), namespace)

    from analysis.synw_log_fb import synw_log_figure
    synw_log_figure('builds/%.4d' % (tr.v_idx), namespace)

    from analysis.turnover_fb import turnover_figure
    turnover_figure('builds/%.4d' % (tr.v_idx), namespace, fit=False)

    from analysis.turnover_fb import turnover_figure
    turnover_figure('builds/%.4d' % (tr.v_idx), namespace, fit=True)
Beispiel #6
0
and thus 

w ~ (vmax - v) / (n - 1)
'''

start_scope()

A = 5
nNeuron = 20
period = 100*ms
tau = 5*ms
eqs = '''
dv/dt = (I-v)/tau : 1
I = A * floor(0.5 + sin(2 * pi * t / period)) : 1
'''

group1 = NeuronGroup(nNeuron, eqs, threshold='v>1', reset='v=0', method='euler')
monitor1 = StateMonitor(group1, variables=True, record=True)
syn1 = Synapses(group1, group1, on_pre='v_post += 1 / (nNeuron - 1)')
syn1.connect(condition='i != j')

run(500*ms)

plt.figure()
plt.plot(monitor1.t/ms, np.mean(monitor1.v, axis=0), label='v')
plt.plot(monitor1.t/ms, monitor1.I[0], label='I')
plt.xlabel('Time (ms)')
plt.ylabel('v')
plt.legend(loc='best')
plt.show()
from brian2 import NeuronGroup, StateMonitor
from brian2 import second, ms

N = NeuronGroup(2,
                """
    tau : second
    sigma : 1
    dy/dt = -y/tau + sqrt(2*sigma**2/tau)*xi : 1
    """,
                method="euler")

N.tau = np.array([1, 0.1]) * second
N.sigma = np.array([0.1, 0.31622])
N.y = 1

M = StateMonitor(N, "y", record=True)

run(10 * second)

plt.plot(M.t / second,
         M.y[1],
         color="red",
         label=r"$\tau$=0.1 s, $\sigma$=0.31622")
plt.plot(M.t / second, M.y[0], color="k", label=r"$\tau$=1 s, $\sigma$=0.1")

plt.xlim(0, 10)
plt.ylim(-1.1, 1.1)

plt.xlabel("time (sec)")
plt.ylabel("Ornstein-Uhlenbeck process")
Beispiel #8
0
def test_from_papers_example():
    """
    Test Izhikevich_2007 example
    `brian2.readthedocs.io/en/stable/examples/frompapers.Izhikevich_2007.html`
    """
    set_device('markdown', build_on_run=False)
    # Parameters
    simulation_duration = 6 * second
    # Neurons
    taum = 10*ms
    Ee = 0*mV
    vt = -54*mV
    vr = -60*mV
    El = -74*mV
    taue = 5*ms

    # STDP
    taupre = 20*ms
    taupost = taupre
    gmax = .01
    dApre = .01
    dApost = -dApre * taupre / taupost * 1.05
    dApost *= gmax
    dApre *= gmax

    # Dopamine signaling
    tauc = 1000*ms
    taud = 200*ms
    taus = 1*ms
    epsilon_dopa = 5e-3

    # Setting the stage

    # Stimuli section
    input_indices = array([0, 1, 0, 1, 1, 0,
                           0, 1, 0, 1, 1, 0])
    input_times = array([500,  550, 1000, 1010, 1500, 1510,
                         3500, 3550, 4000, 4010, 4500, 4510])*ms
    input = SpikeGeneratorGroup(2, input_indices, input_times)

    neurons = NeuronGroup(2, '''dv/dt = (ge * (Ee-vr) + El - v) / taum : volt
                                dge/dt = -ge / taue : 1''',
                          threshold='v>vt', reset='v = vr',
                          method='exact')
    neurons.v = vr
    neurons_monitor = SpikeMonitor(neurons)

    synapse = Synapses(input, neurons,
                       model='''s: volt''',
                       on_pre='v += s')
    synapse.connect(i=[0, 1], j=[0, 1])
    synapse.s = 100. * mV

    # STDP section
    synapse_stdp = Synapses(neurons, neurons,
                    model='''mode: 1
                            dc/dt = -c / tauc : 1 (clock-driven)
                            dd/dt = -d / taud : 1 (clock-driven)
                            ds/dt = mode * c * d / taus : 1 (clock-driven)
                            dApre/dt = -Apre / taupre : 1 (event-driven)
                            dApost/dt = -Apost / taupost : 1 (event-driven)''',
                    on_pre='''ge += s
                            Apre += dApre
                            c = clip(c + mode * Apost, -gmax, gmax)
                            s = clip(s + (1-mode) * Apost, -gmax, gmax)
                            ''',
                    on_post='''Apost += dApost
                            c = clip(c + mode * Apre, -gmax, gmax)
                            s = clip(s + (1-mode) * Apre, -gmax, gmax)
                            ''',
                    method='euler'
                           )
    synapse_stdp.connect(i=0, j=1)
    synapse_stdp.mode = 0
    synapse_stdp.s = 1e-10
    synapse_stdp.c = 1e-10
    synapse_stdp.d = 0
    synapse_stdp_monitor = StateMonitor(synapse_stdp, ['s', 'c', 'd'],
                                        record=[0])
    # Dopamine signaling section
    dopamine_indices = array([0, 0, 0])
    dopamine_times = array([3520, 4020, 4520])*ms
    dopamine = SpikeGeneratorGroup(1, dopamine_indices, dopamine_times)
    dopamine_monitor = SpikeMonitor(dopamine)
    reward = Synapses(dopamine, synapse_stdp, model='''''',
                      on_pre='''d_post += epsilon_dopa''',
                      method='exact')
    reward.connect()

    # Simulation
    # Classical STDP
    synapse_stdp.mode = 0
    run(simulation_duration/2)
    # Dopamine modulated STDP
    synapse_stdp.mode = 1
    run(simulation_duration/2)
    device.build()
    md_str = device.md_text
    assert _markdown_lint(md_str)
    device.reinit()
Beispiel #9
0
def test_common_example():
    """
    Test COBAHH (brian2.readthedocs.io/en/stable/examples/COBAHH.html)
    """

    set_device('markdown')

    # Parameters
    area = 20000*umetre**2
    Cm = (1*ufarad*cm**-2) * area
    gl = (5e-5*siemens*cm**-2) * area

    El = -60*mV
    EK = -90*mV
    ENa = 50*mV
    g_na = (100*msiemens*cm**-2) * area
    g_kd = (30*msiemens*cm**-2) * area
    VT = -63*mV
    # Time constants
    taue = 5*ms
    taui = 10*ms
    # Reversal potentials
    Ee = 0*mV
    Ei = -80*mV
    we = 6*nS  # excitatory synaptic weight
    wi = 67*nS  # inhibitory synaptic weight

    # The model
    eqs = Equations('''
    dv/dt = (gl*(El-v)+ge*(Ee-v)+gi*(Ei-v)-
            g_na*(m*m*m)*h*(v-ENa)-
            g_kd*(n*n*n*n)*(v-EK))/Cm : volt
    dm/dt = alpha_m*(1-m)-beta_m*m : 1
    dn/dt = alpha_n*(1-n)-beta_n*n : 1
    dh/dt = alpha_h*(1-h)-beta_h*h : 1
    dge/dt = -ge*(1./taue) : siemens
    dgi/dt = -gi*(1./taui) : siemens
    alpha_m = 0.32*(mV**-1)*4*mV/exprel((13.0*mV-v+VT)/(4*mV))/ms : Hz
    beta_m = 0.28*(mV**-1)*5*mV/exprel((v-VT-40*mV)/(5*mV))/ms : Hz
    alpha_h = 0.128*exp((17*mV-v+VT)/(18.0*mV))/ms : Hz
    beta_h = 4./(1+exp((40*mV-v+VT)/(5*mV)))/ms : Hz
    alpha_n = 0.032*(mV**-1)*5*mV/exprel((15.*mV-v+VT)/(5.*mV))/ms : Hz
    beta_n = .5*exp((10*mV-v+VT)/(40.*mV))/ms : Hz
    ''')

    P = NeuronGroup(4000, model=eqs, threshold='v>-20*mV', refractory=3*ms,
                    method='exponential_euler')
    Pe = P[:3200]
    Pi = P[3200:]
    Ce = Synapses(Pe, P, on_pre='ge+=we')
    Ci = Synapses(Pi, P, on_pre='gi+=wi')
    Ce.connect(p=0.02)
    Ci.connect(p=0.02)

    # Initialization
    P.v = 'El + (randn() * 5 - 5)*mV'
    P.ge = '(randn() * 1.5 + 4) * 10.*nS'
    P.gi = '(randn() * 12 + 20) * 10.*nS'

    # Record a few traces
    trace = StateMonitor(P, 'v', record=[1, 10, 100])
    run(1 * second)
    md_str = device.md_text
    assert _markdown_lint(md_str)
    device.reinit()
Beispiel #10
0
    fill_value=10,
    dtype=np.int)*ms

# DrivingGroup.tau = [10, 5, 100]*ms

OutputGroup = NeuronGroup(1, eqs, threshold='v>2', reset='v = 0', method='exact')
OutputGroup.I = [0]
OutputGroup.tau = [100]*ms

# Comment these two lines out to see what happens without Synapses
S = Synapses(DrivingGroup, OutputGroup, on_pre='v_post += 0.2')
S.connect(i=np.arange(9), j=0)
# S.connect(i=0, j=2)
# S.connect(i=1, j=2)

DrivingMonitor = StateMonitor(DrivingGroup, 'v', record=True)
OutputMonitor = StateMonitor(OutputGroup, 'v', record=True)

def visualise_connectivity(S):
    Ns = len(S.source)
    Nt = len(S.target)
    plt.figure(figsize=(3, 6))
    # plt.subplot(121)
    plt.plot(np.zeros(Ns), np.arange(Ns), 'ok', ms=10)
    plt.plot(np.ones(Nt), np.arange(Nt), 'ok', ms=10)
    for i, j in zip(S.i, S.j):
        plt.plot([0, 1], [i, j], '-k')
    # plt.xticks([0, 1], ['Source', 'Target'])
    # plt.ylabel('Neuron no.')
    plt.xlim(-0.1, 1.1)
    plt.ylim(-1, max(Ns, Nt))
Beispiel #11
0
        c = np.sqrt((diff[0]**2) + (diff[1]**2))
        distance = np.sqrt((c**2) + (diff[2]**2))

        return -distance


if __name__ == '__main__':
    TIMESTEP = 10

    # Define NN
    nn = BrianLIFAgent(input_size=100,
                       hidden_size=10,
                       output_size=4,
                       namespace={'tau': 10 * ms})
    nn.build()
    state_in = StateMonitor(nn.inp, variables='v', record=True)
    nn.add(state_in)
    state_out = StateMonitor(nn.output, variables='v', record=True)
    nn.add(state_out)

    fig_in = None
    fig_out = None

    handler = SpikeEventHandler(output=[])
    nn.add_spike_handler(nn.output, handler=handler)

    nn.init_network(duration=TIMESTEP * ms)

    # Define Robot
    MAX_SPEED = 6.28
    robo = DistanceRewardRobotSim(camera="camera")
# =============================================================================
# EXTERNAL STIMULUS/SYNAPSES
S1 = Synapses(EXT1, P_E, model='w : 1', on_pre='s_ext1 += w', method='euler')
S1.connect(j='i') # one-to-one
S1.w[:] = 1

S2 = Synapses(EXT2, P_E, model='w : 1', on_pre='s_ext2 += w', method='euler')
S2.connect(j='i') # one-to-one
S2.w[:] = 0

# =============================================================================


# =============================================================================

M = StateMonitor(P_E, ('v_soma', 'v_dend1', 'v_dend2'), record=True)

# SIMULATION RUNNING
net = Network(collect())
net.add(M)
net.run(simtime, report='stdout')


# =============================================================================
# A N A L Y S I S    o f    t h e    S I M U L A T I O N
# =============================================================================
plt.figure(1)
plt.plot(M.t/ms, M[0].v_soma, label='soma')
plt.plot(M.t/ms, M[0].v_dend1, label='dend1')
plt.plot(M.t/ms, M[0].v_dend2, label='dend2')
plt.xlabel("Time [ms]")
Beispiel #13
0
def run_net(tr):

    # prefs.codegen.target = 'numpy'
    # prefs.codegen.target = 'cython'
    if tr.n_threads > 1:
        prefs.devices.cpp_standalone.openmp_threads = tr.n_threads

    set_device('cpp_standalone',
               directory='./builds/%.4d' % (tr.v_idx),
               build_on_run=False)

    # set brian 2 and numpy random seeds
    seed(tr.random_seed)
    np.random.seed(tr.random_seed + 11)

    print("Started process with id ", str(tr.v_idx))

    T = tr.T1 + tr.T2 + tr.T3 + tr.T4 + tr.T5

    namespace = tr.netw.f_to_dict(short_names=True, fast_access=True)
    namespace['idx'] = tr.v_idx

    defaultclock.dt = tr.netw.sim.dt

    # collect all network components dependent on configuration
    # (e.g. poisson vs. memnoise) and add them to the Brian 2
    # network object later
    netw_objects = []

    if tr.external_mode == 'memnoise':
        neuron_model = tr.condlif_memnoise
    elif tr.external_mode == 'poisson':
        raise NotImplementedError
        #neuron_model = tr.condlif_poisson

    if tr.syn_cond_mode == 'exp':
        neuron_model += tr.syn_cond_EE_exp
        print("Using EE exp mode")
    elif tr.syn_cond_mode == 'alpha':
        neuron_model += tr.syn_cond_EE_alpha
        print("Using EE alpha mode")
    elif tr.syn_cond_mode == 'biexp':
        neuron_model += tr.syn_cond_EE_biexp
        namespace['invpeakEE'] = (tr.tau_e / tr.tau_e_rise) ** \
            (tr.tau_e_rise / (tr.tau_e - tr.tau_e_rise))
        print("Using EE biexp mode")

    if tr.syn_cond_mode_EI == 'exp':
        neuron_model += tr.syn_cond_EI_exp
        print("Using EI exp mode")
    elif tr.syn_cond_mode_EI == 'alpha':
        neuron_model += tr.syn_cond_EI_alpha
        print("Using EI alpha mode")
    elif tr.syn_cond_mode_EI == 'biexp':
        neuron_model += tr.syn_cond_EI_biexp
        namespace['invpeakEI'] = (tr.tau_i / tr.tau_i_rise) ** \
            (tr.tau_i_rise / (tr.tau_i - tr.tau_i_rise))
        print("Using EI biexp mode")

    GExc = NeuronGroup(
        N=tr.N_e,
        model=neuron_model,
        threshold=tr.nrnEE_thrshld,
        reset=tr.nrnEE_reset,  #method=tr.neuron_method,
        name='GExc',
        namespace=namespace)
    GInh = NeuronGroup(
        N=tr.N_i,
        model=neuron_model,
        threshold='V > Vt',
        reset='V=Vr_i',  #method=tr.neuron_method,
        name='GInh',
        namespace=namespace)

    if tr.external_mode == 'memnoise':
        # GExc.mu, GInh.mu = [0.*mV] + (tr.N_e-1)*[tr.mu_e], tr.mu_i
        # GExc.sigma, GInh.sigma = [0.*mV] + (tr.N_e-1)*[tr.sigma_e], tr.sigma_i
        GExc.mu, GInh.mu = tr.mu_e, tr.mu_i
        GExc.sigma, GInh.sigma = tr.sigma_e, tr.sigma_i

    GExc.Vt, GInh.Vt = tr.Vt_e, tr.Vt_i
    GExc.V , GInh.V  = np.random.uniform(tr.Vr_e/mV, tr.Vt_e/mV,
                                         size=tr.N_e)*mV, \
                       np.random.uniform(tr.Vr_i/mV, tr.Vt_i/mV,
                                         size=tr.N_i)*mV

    netw_objects.extend([GExc, GInh])

    if tr.external_mode == 'poisson':

        if tr.PInp_mode == 'pool':
            PInp = PoissonGroup(tr.NPInp,
                                rates=tr.PInp_rate,
                                namespace=namespace,
                                name='poissongroup_exc')
            sPN = Synapses(target=GExc,
                           source=PInp,
                           model=tr.poisson_mod,
                           on_pre='gfwd_post += a_EPoi',
                           namespace=namespace,
                           name='synPInpExc')

            sPN_src, sPN_tar = generate_N_connections(N_tar=tr.N_e,
                                                      N_src=tr.NPInp,
                                                      N=tr.NPInp_1n)

        elif tr.PInp_mode == 'indep':
            PInp = PoissonGroup(tr.N_e,
                                rates=tr.PInp_rate,
                                namespace=namespace)
            sPN = Synapses(target=GExc,
                           source=PInp,
                           model=tr.poisson_mod,
                           on_pre='gfwd_post += a_EPoi',
                           namespace=namespace,
                           name='synPInp_inhInh')
            sPN_src, sPN_tar = range(tr.N_e), range(tr.N_e)

        sPN.connect(i=sPN_src, j=sPN_tar)

        if tr.PInp_mode == 'pool':

            PInp_inh = PoissonGroup(tr.NPInp_inh,
                                    rates=tr.PInp_inh_rate,
                                    namespace=namespace,
                                    name='poissongroup_inh')

            sPNInh = Synapses(target=GInh,
                              source=PInp_inh,
                              model=tr.poisson_mod,
                              on_pre='gfwd_post += a_EPoi',
                              namespace=namespace)

            sPNInh_src, sPNInh_tar = generate_N_connections(N_tar=tr.N_i,
                                                            N_src=tr.NPInp_inh,
                                                            N=tr.NPInp_inh_1n)

        elif tr.PInp_mode == 'indep':

            PInp_inh = PoissonGroup(tr.N_i,
                                    rates=tr.PInp_inh_rate,
                                    namespace=namespace)

            sPNInh = Synapses(target=GInh,
                              source=PInp_inh,
                              model=tr.poisson_mod,
                              on_pre='gfwd_post += a_EPoi',
                              namespace=namespace)

            sPNInh_src, sPNInh_tar = range(tr.N_i), range(tr.N_i)

        sPNInh.connect(i=sPNInh_src, j=sPNInh_tar)

        netw_objects.extend([PInp, sPN, PInp_inh, sPNInh])

    if tr.syn_noise:

        if tr.syn_noise_type == 'additive':
            synEE_mod = '''%s 
                           %s''' % (tr.synEE_noise_add, tr.synEE_mod)

            synEI_mod = '''%s 
                           %s''' % (tr.synEE_noise_add, tr.synEE_mod)

        elif tr.syn_noise_type == 'multiplicative':
            synEE_mod = '''%s 
                           %s''' % (tr.synEE_noise_mult, tr.synEE_mod)

            synEI_mod = '''%s 
                           %s''' % (tr.synEE_noise_mult, tr.synEE_mod)

    else:
        synEE_mod = '''%s 
                       %s''' % (tr.synEE_static, tr.synEE_mod)

        synEI_mod = '''%s 
                       %s''' % (tr.synEE_static, tr.synEE_mod)

    if tr.scl_active:
        synEE_mod = '''%s
                       %s''' % (synEE_mod, tr.synEE_scl_mod)
        synEI_mod = '''%s
                       %s''' % (synEI_mod, tr.synEI_scl_mod)

    if tr.syn_cond_mode == 'exp':
        synEE_pre_mod = mod.synEE_pre_exp
    elif tr.syn_cond_mode == 'alpha':
        synEE_pre_mod = mod.synEE_pre_alpha
    elif tr.syn_cond_mode == 'biexp':
        synEE_pre_mod = mod.synEE_pre_biexp

    synEE_post_mod = mod.syn_post

    if tr.stdp_active:
        synEE_pre_mod = '''%s 
                            %s''' % (synEE_pre_mod, mod.syn_pre_STDP)
        synEE_post_mod = '''%s 
                            %s''' % (synEE_post_mod, mod.syn_post_STDP)

    if tr.synEE_rec:
        synEE_pre_mod = '''%s 
                            %s''' % (synEE_pre_mod, mod.synEE_pre_rec)
        synEE_post_mod = '''%s 
                            %s''' % (synEE_post_mod, mod.synEE_post_rec)

    # E<-E advanced synapse model
    SynEE = Synapses(target=GExc,
                     source=GExc,
                     model=synEE_mod,
                     on_pre=synEE_pre_mod,
                     on_post=synEE_post_mod,
                     namespace=namespace,
                     dt=tr.synEE_mod_dt)

    if tr.istdp_active and tr.istdp_type == 'dbexp':

        if tr.syn_cond_mode_EI == 'exp':
            EI_pre_mod = mod.synEI_pre_exp
        elif tr.syn_cond_mode_EI == 'alpha':
            EI_pre_mod = mod.synEI_pre_alpha
        elif tr.syn_cond_mode_EI == 'biexp':
            EI_pre_mod = mod.synEI_pre_biexp

        synEI_pre_mod = '''%s 
                            %s''' % (EI_pre_mod, mod.syn_pre_STDP)
        synEI_post_mod = '''%s 
                            %s''' % (mod.syn_post, mod.syn_post_STDP)

    elif tr.istdp_active and tr.istdp_type == 'sym':

        if tr.syn_cond_mode_EI == 'exp':
            EI_pre_mod = mod.synEI_pre_sym_exp
        elif tr.syn_cond_mode_EI == 'alpha':
            EI_pre_mod = mod.synEI_pre_sym_alpha
        elif tr.syn_cond_mode_EI == 'biexp':
            EI_pre_mod = mod.synEI_pre_sym_biexp

        synEI_pre_mod = '''%s 
                            %s''' % (EI_pre_mod, mod.syn_pre_STDP)
        synEI_post_mod = '''%s 
                            %s''' % (mod.synEI_post_sym, mod.syn_post_STDP)

    if tr.istdp_active and tr.synEI_rec:

        synEI_pre_mod = '''%s 
                            %s''' % (synEI_pre_mod, mod.synEI_pre_rec)
        synEI_post_mod = '''%s 
                            %s''' % (synEI_post_mod, mod.synEI_post_rec)

    if tr.istdp_active:
        SynEI = Synapses(target=GExc,
                         source=GInh,
                         model=synEI_mod,
                         on_pre=synEI_pre_mod,
                         on_post=synEI_post_mod,
                         namespace=namespace,
                         dt=tr.synEE_mod_dt)

    else:
        model = '''a : 1
                   syn_active : 1'''
        SynEI = Synapses(target=GExc,
                         source=GInh,
                         model=model,
                         on_pre='gi_post += a',
                         namespace=namespace)

    #other simple
    SynIE = Synapses(target=GInh,
                     source=GExc,
                     on_pre='ge_post += a_ie',
                     namespace=namespace)

    SynII = Synapses(target=GInh,
                     source=GInh,
                     on_pre='gi_post += a_ii',
                     namespace=namespace)

    sEE_src, sEE_tar = generate_full_connectivity(tr.N_e, same=True)
    SynEE.connect(i=sEE_src, j=sEE_tar)
    SynEE.syn_active = 0
    SynEE.taupre, SynEE.taupost = tr.taupre, tr.taupost

    if tr.istdp_active and tr.istrct_active:
        print('istrct active')
        sEI_src, sEI_tar = generate_full_connectivity(Nsrc=tr.N_i,
                                                      Ntar=tr.N_e,
                                                      same=False)
        SynEI.connect(i=sEI_src, j=sEI_tar)
        SynEI.syn_active = 0

    else:
        print('istrct not active')
        if tr.weight_mode == 'init':
            sEI_src, sEI_tar = generate_connections(tr.N_e, tr.N_i, tr.p_ei)
            # print('Index Zero will not get inhibition')
            # sEI_src, sEI_tar = np.array(sEI_src), np.array(sEI_tar)
            # sEI_src, sEI_tar = sEI_src[sEI_tar > 0],sEI_tar[sEI_tar > 0]

        elif tr.weight_mode == 'load':

            fpath = os.path.join(tr.basepath, tr.weight_path)

            with open(fpath + 'synei_a.p', 'rb') as pfile:
                synei_a_init = pickle.load(pfile)

            sEI_src, sEI_tar = synei_a_init['i'], synei_a_init['j']

        SynEI.connect(i=sEI_src, j=sEI_tar)

    if tr.istdp_active:
        SynEI.taupre, SynEI.taupost = tr.taupre_EI, tr.taupost_EI

    sIE_src, sIE_tar = generate_connections(tr.N_i, tr.N_e, tr.p_ie)
    sII_src, sII_tar = generate_connections(tr.N_i, tr.N_i, tr.p_ii, same=True)

    SynIE.connect(i=sIE_src, j=sIE_tar)
    SynII.connect(i=sII_src, j=sII_tar)

    tr.f_add_result('sEE_src', sEE_src)
    tr.f_add_result('sEE_tar', sEE_tar)
    tr.f_add_result('sIE_src', sIE_src)
    tr.f_add_result('sIE_tar', sIE_tar)
    tr.f_add_result('sEI_src', sEI_src)
    tr.f_add_result('sEI_tar', sEI_tar)
    tr.f_add_result('sII_src', sII_src)
    tr.f_add_result('sII_tar', sII_tar)

    if tr.syn_noise:
        SynEE.syn_sigma = tr.syn_sigma
        SynEE.run_regularly('a = clip(a,0,amax)',
                            when='after_groups',
                            name='SynEE_noise_clipper')

    if tr.syn_noise and tr.istdp_active:
        SynEI.syn_sigma = tr.syn_sigma
        SynEI.run_regularly('a = clip(a,0,amax)',
                            when='after_groups',
                            name='SynEI_noise_clipper')

    SynEE.insert_P = tr.insert_P
    SynEE.p_inactivate = tr.p_inactivate
    SynEE.stdp_active = 1
    print('Setting maximum EE weight threshold to ', tr.amax)
    SynEE.amax = tr.amax

    if tr.istdp_active:
        SynEI.insert_P = tr.insert_P_ei
        SynEI.p_inactivate = tr.p_inactivate_ei
        SynEI.stdp_active = 1
        SynEI.amax = tr.amax

    SynEE.syn_active, SynEE.a = init_synapses('EE', tr)
    SynEI.syn_active, SynEI.a = init_synapses('EI', tr)

    # recording of stdp in T4
    SynEE.stdp_rec_start = tr.T1 + tr.T2 + tr.T3
    SynEE.stdp_rec_max = tr.T1 + tr.T2 + tr.T3 + tr.stdp_rec_T

    if tr.istdp_active:
        SynEI.stdp_rec_start = tr.T1 + tr.T2 + tr.T3
        SynEI.stdp_rec_max = tr.T1 + tr.T2 + tr.T3 + tr.stdp_rec_T

    # synaptic scaling
    if tr.netw.config.scl_active:

        if tr.syn_scl_rec:
            SynEE.scl_rec_start = tr.T1 + tr.T2 + tr.T3
            SynEE.scl_rec_max = tr.T1 + tr.T2 + tr.T3 + tr.scl_rec_T
        else:
            SynEE.scl_rec_start = T + 10 * second
            SynEE.scl_rec_max = T

        if tr.sig_ATotalMax == 0.:
            GExc.ANormTar = tr.ATotalMax
        else:
            GExc.ANormTar = np.random.normal(loc=tr.ATotalMax,
                                             scale=tr.sig_ATotalMax,
                                             size=tr.N_e)

        SynEE.summed_updaters['AsumEE_post']._clock = Clock(
            dt=tr.dt_synEE_scaling)
        synee_scaling = SynEE.run_regularly(tr.synEE_scaling,
                                            dt=tr.dt_synEE_scaling,
                                            when='end',
                                            name='synEE_scaling')

    if tr.istdp_active and tr.netw.config.iscl_active:

        if tr.syn_iscl_rec:
            SynEI.scl_rec_start = tr.T1 + tr.T2 + tr.T3
            SynEI.scl_rec_max = tr.T1 + tr.T2 + tr.T3 + tr.scl_rec_T
        else:
            SynEI.scl_rec_start = T + 10 * second
            SynEI.scl_rec_max = T

        if tr.sig_iATotalMax == 0.:
            GExc.iANormTar = tr.iATotalMax
        else:
            GExc.iANormTar = np.random.normal(loc=tr.iATotalMax,
                                              scale=tr.sig_iATotalMax,
                                              size=tr.N_e)

        SynEI.summed_updaters['AsumEI_post']._clock = Clock(
            dt=tr.dt_synEE_scaling)

        synei_scaling = SynEI.run_regularly(tr.synEI_scaling,
                                            dt=tr.dt_synEE_scaling,
                                            when='end',
                                            name='synEI_scaling')

    # # intrinsic plasticity
    # if tr.netw.config.it_active:
    #     GExc.h_ip = tr.h_ip
    #     GExc.run_regularly(tr.intrinsic_mod, dt = tr.it_dt, when='end')

    # structural plasticity
    if tr.netw.config.strct_active:
        if tr.strct_mode == 'zero':
            if tr.turnover_rec:
                strct_mod = '''%s 
                                %s''' % (tr.strct_mod, tr.turnover_rec_mod)
            else:
                strct_mod = tr.strct_mod

            strctplst = SynEE.run_regularly(strct_mod,
                                            dt=tr.strct_dt,
                                            when='end',
                                            name='strct_plst_zero')

        elif tr.strct_mode == 'thrs':
            if tr.turnover_rec:
                strct_mod_thrs = '''%s 
                                %s''' % (tr.strct_mod_thrs,
                                         tr.turnover_rec_mod)
            else:
                strct_mod_thrs = tr.strct_mod_thrs

            strctplst = SynEE.run_regularly(strct_mod_thrs,
                                            dt=tr.strct_dt,
                                            when='end',
                                            name='strct_plst_thrs')

    if tr.istdp_active and tr.netw.config.istrct_active:
        if tr.strct_mode == 'zero':
            if tr.turnover_rec:
                strct_mod_EI = '''%s 
                                   %s''' % (tr.strct_mod,
                                            tr.turnoverEI_rec_mod)
            else:
                strct_mod_EI = tr.strct_mod

            strctplst_EI = SynEI.run_regularly(strct_mod_EI,
                                               dt=tr.strct_dt,
                                               when='end',
                                               name='strct_plst_EI')

        elif tr.strct_mode == 'thrs':
            raise NotImplementedError

    netw_objects.extend([SynEE, SynEI, SynIE, SynII])

    # keep track of the number of active synapses
    sum_target = NeuronGroup(1, 'c : 1 (shared)', dt=tr.csample_dt)

    sum_model = '''NSyn : 1 (constant)
                   c_post = (1.0*syn_active_pre)/NSyn : 1 (summed)'''
    sum_connection = Synapses(target=sum_target,
                              source=SynEE,
                              model=sum_model,
                              dt=tr.csample_dt,
                              name='get_active_synapse_count')
    sum_connection.connect()
    sum_connection.NSyn = tr.N_e * (tr.N_e - 1)

    if tr.adjust_insertP:
        # homeostatically adjust growth rate
        growth_updater = Synapses(sum_target, SynEE)
        growth_updater.run_regularly('insert_P_post *= 0.1/c_pre',
                                     when='after_groups',
                                     dt=tr.csample_dt,
                                     name='update_insP')
        growth_updater.connect(j='0')

        netw_objects.extend([sum_target, sum_connection, growth_updater])

    if tr.istdp_active and tr.istrct_active:

        # keep track of the number of active synapses
        sum_target_EI = NeuronGroup(1, 'c : 1 (shared)', dt=tr.csample_dt)

        sum_model_EI = '''NSyn : 1 (constant)
                          c_post = (1.0*syn_active_pre)/NSyn : 1 (summed)'''
        sum_connection_EI = Synapses(target=sum_target_EI,
                                     source=SynEI,
                                     model=sum_model_EI,
                                     dt=tr.csample_dt,
                                     name='get_active_synapse_count_EI')
        sum_connection_EI.connect()
        sum_connection_EI.NSyn = tr.N_e * tr.N_i

        if tr.adjust_EI_insertP:
            # homeostatically adjust growth rate
            growth_updater_EI = Synapses(sum_target_EI, SynEI)
            growth_updater_EI.run_regularly('insert_P_post *= 0.1/c_pre',
                                            when='after_groups',
                                            dt=tr.csample_dt,
                                            name='update_insP_EI')
            growth_updater_EI.connect(j='0')

            netw_objects.extend(
                [sum_target_EI, sum_connection_EI, growth_updater_EI])

    # -------------- recording ------------------

    GExc_recvars = []
    if tr.memtraces_rec:
        GExc_recvars.append('V')
    if tr.vttraces_rec:
        GExc_recvars.append('Vt')
    if tr.getraces_rec:
        GExc_recvars.append('ge')
    if tr.gitraces_rec:
        GExc_recvars.append('gi')
    if tr.gfwdtraces_rec and tr.external_mode == 'poisson':
        GExc_recvars.append('gfwd')

    GInh_recvars = GExc_recvars

    GExc_stat = StateMonitor(GExc,
                             GExc_recvars,
                             record=list(range(tr.nrec_GExc_stat)),
                             dt=tr.GExc_stat_dt)
    GInh_stat = StateMonitor(GInh,
                             GInh_recvars,
                             record=list(range(tr.nrec_GInh_stat)),
                             dt=tr.GInh_stat_dt)

    # SynEE stat
    SynEE_recvars = []
    if tr.synee_atraces_rec:
        SynEE_recvars.append('a')
    if tr.synee_activetraces_rec:
        SynEE_recvars.append('syn_active')
    if tr.synee_Apretraces_rec:
        SynEE_recvars.append('Apre')
    if tr.synee_Aposttraces_rec:
        SynEE_recvars.append('Apost')

    SynEE_stat = StateMonitor(SynEE,
                              SynEE_recvars,
                              record=range(tr.n_synee_traces_rec),
                              when='end',
                              dt=tr.synEE_stat_dt)

    if tr.istdp_active:
        # SynEI stat
        SynEI_recvars = []
        if tr.synei_atraces_rec:
            SynEI_recvars.append('a')
        if tr.synei_activetraces_rec:
            SynEI_recvars.append('syn_active')
        if tr.synei_Apretraces_rec:
            SynEI_recvars.append('Apre')
        if tr.synei_Aposttraces_rec:
            SynEI_recvars.append('Apost')

        SynEI_stat = StateMonitor(SynEI,
                                  SynEI_recvars,
                                  record=range(tr.n_synei_traces_rec),
                                  when='end',
                                  dt=tr.synEI_stat_dt)
        netw_objects.append(SynEI_stat)

    if tr.adjust_insertP:

        C_stat = StateMonitor(sum_target,
                              'c',
                              dt=tr.csample_dt,
                              record=[0],
                              when='end')
        insP_stat = StateMonitor(SynEE,
                                 'insert_P',
                                 dt=tr.csample_dt,
                                 record=[0],
                                 when='end')
        netw_objects.extend([C_stat, insP_stat])

    if tr.istdp_active and tr.adjust_EI_insertP:

        C_EI_stat = StateMonitor(sum_target_EI,
                                 'c',
                                 dt=tr.csample_dt,
                                 record=[0],
                                 when='end')
        insP_EI_stat = StateMonitor(SynEI,
                                    'insert_P',
                                    dt=tr.csample_dt,
                                    record=[0],
                                    when='end')
        netw_objects.extend([C_EI_stat, insP_EI_stat])

    GExc_spks = SpikeMonitor(GExc)
    GInh_spks = SpikeMonitor(GInh)

    GExc_rate = PopulationRateMonitor(GExc)
    GInh_rate = PopulationRateMonitor(GInh)

    if tr.external_mode == 'poisson':
        PInp_spks = SpikeMonitor(PInp)
        PInp_rate = PopulationRateMonitor(PInp)
        netw_objects.extend([PInp_spks, PInp_rate])

    if tr.synee_a_nrecpoints == 0 or tr.sim.T2 == 0 * second:
        SynEE_a_dt = 2 * (tr.T1 + tr.T2 + tr.T3 + tr.T4 + tr.T5)
    else:
        SynEE_a_dt = tr.sim.T2 / tr.synee_a_nrecpoints

        # make sure that choice of SynEE_a_dt does lead
        # to execessively many recordings - this can
        # happen if t1 >> t2.
        estm_nrecs = int(T / SynEE_a_dt)
        if estm_nrecs > 3 * tr.synee_a_nrecpoints:
            print('''Estimated number of EE weight recordings (%d)
            exceeds desired number (%d), increasing 
            SynEE_a_dt''' % (estm_nrecs, tr.synee_a_nrecpoints))

            SynEE_a_dt = T / tr.synee_a_nrecpoints

    SynEE_a = StateMonitor(SynEE, ['a', 'syn_active'],
                           record=range(tr.N_e * (tr.N_e - 1)),
                           dt=SynEE_a_dt,
                           when='end',
                           order=100)

    if tr.istrct_active:
        record_range = range(tr.N_e * tr.N_i)
    else:
        record_range = range(len(sEI_src))

    if tr.synei_a_nrecpoints > 0 and tr.sim.T2 > 0 * second:
        SynEI_a_dt = tr.sim.T2 / tr.synei_a_nrecpoints

        estm_nrecs = int(T / SynEI_a_dt)
        if estm_nrecs > 3 * tr.synei_a_nrecpoints:
            print('''Estimated number of EI weight recordings
            (%d) exceeds desired number (%d), increasing 
            SynEI_a_dt''' % (estm_nrecs, tr.synei_a_nrecpoints))

            SynEI_a_dt = T / tr.synei_a_nrecpoints

        SynEI_a = StateMonitor(SynEI, ['a', 'syn_active'],
                               record=record_range,
                               dt=SynEI_a_dt,
                               when='end',
                               order=100)

        netw_objects.append(SynEI_a)

    netw_objects.extend([
        GExc_stat, GInh_stat, SynEE_stat, SynEE_a, GExc_spks, GInh_spks,
        GExc_rate, GInh_rate
    ])

    if (tr.synEEdynrec
            and (2 * tr.syndynrec_npts * tr.syndynrec_dt < tr.sim.T2)):
        SynEE_dynrec = StateMonitor(SynEE, ['a'],
                                    record=range(tr.N_e * (tr.N_e - 1)),
                                    dt=tr.syndynrec_dt,
                                    name='SynEE_dynrec',
                                    when='end',
                                    order=100)
        SynEE_dynrec.active = False
        netw_objects.extend([SynEE_dynrec])

    if (tr.synEIdynrec
            and (2 * tr.syndynrec_npts * tr.syndynrec_dt < tr.sim.T2)):
        SynEI_dynrec = StateMonitor(SynEI, ['a'],
                                    record=record_range,
                                    dt=tr.syndynrec_dt,
                                    name='SynEI_dynrec',
                                    when='end',
                                    order=100)
        SynEI_dynrec.active = False
        netw_objects.extend([SynEI_dynrec])

    net = Network(*netw_objects)

    def set_active(*argv):
        for net_object in argv:
            net_object.active = True

    def set_inactive(*argv):
        for net_object in argv:
            net_object.active = False

    ### Simulation periods

    # --------- T1 ---------
    # initial recording period,
    # all recorders active

    T1T3_recorders = [
        GExc_spks, GInh_spks, SynEE_stat, GExc_stat, GInh_stat, GExc_rate,
        GInh_rate
    ]

    if tr.istdp_active:
        T1T3_recorders.append(SynEI_stat)

    set_active(*T1T3_recorders)

    if tr.external_mode == 'poisson':
        set_active(PInp_spks, PInp_rate)

    net.run(tr.sim.T1, report='text', report_period=300 * second, profile=True)

    # --------- T2 ---------
    # main simulation period
    # only active recordings are:
    #   1) turnover 2) C_stat 3) SynEE_a

    set_inactive(*T1T3_recorders)

    if tr.T2_spks_rec:
        set_active(GExc_spks, GInh_spks)

    if tr.external_mode == 'poisson':
        set_inactive(PInp_spks, PInp_rate)

    run_T2_syndynrec(net, tr, netw_objects)

    # --------- T3 ---------
    # second recording period,
    # all recorders active

    set_active(*T1T3_recorders)

    if tr.external_mode == 'poisson':
        set_active(PInp_spks, PInp_rate)

    run_T3_split(net, tr)

    # --------- T4 ---------
    # record STDP and scaling weight changes to file
    # through the cpp models

    set_inactive(*T1T3_recorders)

    if tr.external_mode == 'poisson':
        set_inactive(PInp_spks, PInp_rate)

    run_T4(net, tr)

    # --------- T5 ---------
    # freeze network and record Exc spikes
    # for cross correlations

    if tr.scl_active:
        synee_scaling.active = False
    if tr.istdp_active and tr.netw.config.iscl_active:
        synei_scaling.active = False
    if tr.strct_active:
        strctplst.active = False
    if tr.istdp_active and tr.istrct_active:
        strctplst_EI.active = False
    SynEE.stdp_active = 0
    if tr.istdp_active:
        SynEI.stdp_active = 0

    set_active(GExc_rate, GInh_rate)
    set_active(GExc_spks, GInh_spks)

    run_T5(net, tr)

    SynEE_a.record_single_timestep()
    if tr.synei_a_nrecpoints > 0 and tr.sim.T2 > 0. * second:
        SynEI_a.record_single_timestep()

    device.build(directory='builds/%.4d' % (tr.v_idx),
                 clean=True,
                 compile=True,
                 run=True,
                 debug=False)

    # -----------------------------------------

    # save monitors as raws in build directory
    raw_dir = 'builds/%.4d/raw/' % (tr.v_idx)

    if not os.path.exists(raw_dir):
        os.makedirs(raw_dir)

    with open(raw_dir + 'namespace.p', 'wb') as pfile:
        pickle.dump(namespace, pfile)

    with open(raw_dir + 'gexc_stat.p', 'wb') as pfile:
        pickle.dump(GExc_stat.get_states(), pfile)
    with open(raw_dir + 'ginh_stat.p', 'wb') as pfile:
        pickle.dump(GInh_stat.get_states(), pfile)

    with open(raw_dir + 'synee_stat.p', 'wb') as pfile:
        pickle.dump(SynEE_stat.get_states(), pfile)

    if tr.istdp_active:
        with open(raw_dir + 'synei_stat.p', 'wb') as pfile:
            pickle.dump(SynEI_stat.get_states(), pfile)

    if ((tr.synEEdynrec or tr.synEIdynrec)
            and (2 * tr.syndynrec_npts * tr.syndynrec_dt < tr.sim.T2)):

        if tr.synEEdynrec:
            with open(raw_dir + 'syneedynrec.p', 'wb') as pfile:
                pickle.dump(SynEE_dynrec.get_states(), pfile)
        if tr.synEIdynrec:
            with open(raw_dir + 'syneidynrec.p', 'wb') as pfile:
                pickle.dump(SynEI_dynrec.get_states(), pfile)

    with open(raw_dir + 'synee_a.p', 'wb') as pfile:
        SynEE_a_states = SynEE_a.get_states()
        if tr.crs_crrs_rec:
            SynEE_a_states['i'] = list(SynEE.i)
            SynEE_a_states['j'] = list(SynEE.j)
        pickle.dump(SynEE_a_states, pfile)

    if tr.synei_a_nrecpoints > 0 and tr.sim.T2 > 0. * second:
        with open(raw_dir + 'synei_a.p', 'wb') as pfile:
            SynEI_a_states = SynEI_a.get_states()
            if tr.crs_crrs_rec:
                SynEI_a_states['i'] = list(SynEI.i)
                SynEI_a_states['j'] = list(SynEI.j)
            pickle.dump(SynEI_a_states, pfile)

    if tr.adjust_insertP:
        with open(raw_dir + 'c_stat.p', 'wb') as pfile:
            pickle.dump(C_stat.get_states(), pfile)

        with open(raw_dir + 'insP_stat.p', 'wb') as pfile:
            pickle.dump(insP_stat.get_states(), pfile)

    if tr.istdp_active and tr.adjust_EI_insertP:
        with open(raw_dir + 'c_EI_stat.p', 'wb') as pfile:
            pickle.dump(C_EI_stat.get_states(), pfile)

        with open(raw_dir + 'insP_EI_stat.p', 'wb') as pfile:
            pickle.dump(insP_EI_stat.get_states(), pfile)

    with open(raw_dir + 'gexc_spks.p', 'wb') as pfile:
        pickle.dump(GExc_spks.get_states(), pfile)
    with open(raw_dir + 'ginh_spks.p', 'wb') as pfile:
        pickle.dump(GInh_spks.get_states(), pfile)

    if tr.external_mode == 'poisson':
        with open(raw_dir + 'pinp_spks.p', 'wb') as pfile:
            pickle.dump(PInp_spks.get_states(), pfile)

    with open(raw_dir + 'gexc_rate.p', 'wb') as pfile:
        pickle.dump(GExc_rate.get_states(), pfile)
        if tr.rates_rec:
            pickle.dump(GExc_rate.smooth_rate(width=25 * ms), pfile)
    with open(raw_dir + 'ginh_rate.p', 'wb') as pfile:
        pickle.dump(GInh_rate.get_states(), pfile)
        if tr.rates_rec:
            pickle.dump(GInh_rate.smooth_rate(width=25 * ms), pfile)

    if tr.external_mode == 'poisson':
        with open(raw_dir + 'pinp_rate.p', 'wb') as pfile:
            pickle.dump(PInp_rate.get_states(), pfile)
            if tr.rates_rec:
                pickle.dump(PInp_rate.smooth_rate(width=25 * ms), pfile)

    # ----------------- add raw data ------------------------
    fpath = 'builds/%.4d/' % (tr.v_idx)

    from pathlib import Path

    Path(fpath + 'turnover').touch()
    turnover_data = np.genfromtxt(fpath + 'turnover', delimiter=',')
    os.remove(fpath + 'turnover')

    with open(raw_dir + 'turnover.p', 'wb') as pfile:
        pickle.dump(turnover_data, pfile)

    Path(fpath + 'turnover_EI').touch()
    turnover_EI_data = np.genfromtxt(fpath + 'turnover_EI', delimiter=',')
    os.remove(fpath + 'turnover_EI')

    with open(raw_dir + 'turnover_EI.p', 'wb') as pfile:
        pickle.dump(turnover_EI_data, pfile)

    Path(fpath + 'spk_register').touch()
    spk_register_data = np.genfromtxt(fpath + 'spk_register', delimiter=',')
    os.remove(fpath + 'spk_register')

    with open(raw_dir + 'spk_register.p', 'wb') as pfile:
        pickle.dump(spk_register_data, pfile)

    Path(fpath + 'spk_register_EI').touch()
    spk_register_EI_data = np.genfromtxt(fpath + 'spk_register_EI',
                                         delimiter=',')
    os.remove(fpath + 'spk_register_EI')

    with open(raw_dir + 'spk_register_EI.p', 'wb') as pfile:
        pickle.dump(spk_register_EI_data, pfile)

    Path(fpath + 'scaling_deltas').touch()
    scaling_deltas_data = np.genfromtxt(fpath + 'scaling_deltas',
                                        delimiter=',')
    os.remove(fpath + 'scaling_deltas')

    with open(raw_dir + 'scaling_deltas.p', 'wb') as pfile:
        pickle.dump(scaling_deltas_data, pfile)

    Path(fpath + 'scaling_deltas_EI').touch()
    scaling_deltas_data = np.genfromtxt(fpath + 'scaling_deltas_EI',
                                        delimiter=',')
    os.remove(fpath + 'scaling_deltas_EI')

    with open(raw_dir + 'scaling_deltas_EI.p', 'wb') as pfile:
        pickle.dump(scaling_deltas_data, pfile)

    with open(raw_dir + 'profiling_summary.txt', 'w+') as tfile:
        tfile.write(str(profiling_summary(net)))

    # --------------- cross-correlations ---------------------

    if tr.crs_crrs_rec:

        GExc_spks = GExc_spks.get_states()
        synee_a = SynEE_a_states
        wsize = 100 * pq.ms

        for binsize in [1 * pq.ms, 2 * pq.ms, 5 * pq.ms]:

            wlen = int(wsize / binsize)

            ts, idxs = GExc_spks['t'], GExc_spks['i']
            idxs = idxs[ts > tr.T1 + tr.T2 + tr.T3 + tr.T4]
            ts = ts[ts > tr.T1 + tr.T2 + tr.T3 + tr.T4]
            ts = ts - (tr.T1 + tr.T2 + tr.T3 + tr.T4)

            sts = [
                neo.SpikeTrain(ts[idxs == i] / second * pq.s,
                               t_stop=tr.T5 / second * pq.s)
                for i in range(tr.N_e)
            ]

            crs_crrs, syn_a = [], []

            for f, (i, j) in enumerate(zip(synee_a['i'], synee_a['j'])):
                if synee_a['syn_active'][-1][f] == 1:

                    crs_crr, cbin = cch(BinnedSpikeTrain(sts[i],
                                                         binsize=binsize),
                                        BinnedSpikeTrain(sts[j],
                                                         binsize=binsize),
                                        cross_corr_coef=True,
                                        border_correction=True,
                                        window=(-1 * wlen, wlen))

                    crs_crrs.append(list(np.array(crs_crr).T[0]))
                    syn_a.append(synee_a['a'][-1][f])

            fname = 'crs_crrs_wsize%dms_binsize%fms_full' % (wsize / pq.ms,
                                                             binsize / pq.ms)

            df = {
                'cbin': cbin,
                'crs_crrs': np.array(crs_crrs),
                'syn_a': np.array(syn_a),
                'binsize': binsize,
                'wsize': wsize,
                'wlen': wlen
            }

            with open('builds/%.4d/raw/' % (tr.v_idx) + fname + '.p',
                      'wb') as pfile:
                pickle.dump(df, pfile)

        GInh_spks = GInh_spks.get_states()
        synei_a = SynEI_a_states
        wsize = 100 * pq.ms

        for binsize in [1 * pq.ms, 2 * pq.ms, 5 * pq.ms]:

            wlen = int(wsize / binsize)

            ts_E, idxs_E = GExc_spks['t'], GExc_spks['i']
            idxs_E = idxs_E[ts_E > tr.T1 + tr.T2 + tr.T3 + tr.T4]
            ts_E = ts_E[ts_E > tr.T1 + tr.T2 + tr.T3 + tr.T4]
            ts_E = ts_E - (tr.T1 + tr.T2 + tr.T3 + tr.T4)

            ts_I, idxs_I = GInh_spks['t'], GInh_spks['i']
            idxs_I = idxs_I[ts_I > tr.T1 + tr.T2 + tr.T3 + tr.T4]
            ts_I = ts_I[ts_I > tr.T1 + tr.T2 + tr.T3 + tr.T4]
            ts_I = ts_I - (tr.T1 + tr.T2 + tr.T3 + tr.T4)

            sts_E = [
                neo.SpikeTrain(ts_E[idxs_E == i] / second * pq.s,
                               t_stop=tr.T5 / second * pq.s)
                for i in range(tr.N_e)
            ]

            sts_I = [
                neo.SpikeTrain(ts_I[idxs_I == i] / second * pq.s,
                               t_stop=tr.T5 / second * pq.s)
                for i in range(tr.N_i)
            ]

            crs_crrs, syn_a = [], []

            for f, (i, j) in enumerate(zip(synei_a['i'], synei_a['j'])):
                if synei_a['syn_active'][-1][f] == 1:

                    crs_crr, cbin = cch(BinnedSpikeTrain(sts_I[i],
                                                         binsize=binsize),
                                        BinnedSpikeTrain(sts_E[j],
                                                         binsize=binsize),
                                        cross_corr_coef=True,
                                        border_correction=True,
                                        window=(-1 * wlen, wlen))

                    crs_crrs.append(list(np.array(crs_crr).T[0]))
                    syn_a.append(synei_a['a'][-1][f])

            fname = 'EI_crrs_wsize%dms_binsize%fms_full' % (wsize / pq.ms,
                                                            binsize / pq.ms)

            df = {
                'cbin': cbin,
                'crs_crrs': np.array(crs_crrs),
                'syn_a': np.array(syn_a),
                'binsize': binsize,
                'wsize': wsize,
                'wlen': wlen
            }

            with open('builds/%.4d/raw/' % (tr.v_idx) + fname + '.p',
                      'wb') as pfile:
                pickle.dump(df, pfile)

    # -----------------  clean up  ---------------------------
    shutil.rmtree('builds/%.4d/results/' % (tr.v_idx))
    shutil.rmtree('builds/%.4d/static_arrays/' % (tr.v_idx))
    shutil.rmtree('builds/%.4d/brianlib/' % (tr.v_idx))
    shutil.rmtree('builds/%.4d/code_objects/' % (tr.v_idx))

    # ---------------- plot results --------------------------

    #os.chdir('./analysis/file_based/')

    if tr.istdp_active:
        from src.analysis.overview_winh import overview_figure
        overview_figure('builds/%.4d' % (tr.v_idx), namespace)
    else:
        from src.analysis.overview import overview_figure
        overview_figure('builds/%.4d' % (tr.v_idx), namespace)

    from src.analysis.synw_fb import synw_figure
    synw_figure('builds/%.4d' % (tr.v_idx), namespace)
    if tr.istdp_active:
        synw_figure('builds/%.4d' % (tr.v_idx), namespace, connections='EI')

    from src.analysis.synw_log_fb import synw_log_figure
    synw_log_figure('builds/%.4d' % (tr.v_idx), namespace)
    if tr.istdp_active:
        synw_log_figure('builds/%.4d' % (tr.v_idx),
                        namespace,
                        connections='EI')
Beispiel #14
0
spikemon_retina = SpikeMonitor(retina, name='spikemon_retina')

# Monitor the spiking activity of the populations of simple neurons
neurons_spikes = []
for k in range(num_orientations):
    neurons_spikes.append(
        SpikeMonitor(populations[k], name='spikemon_pop_' + str(k)))

# Monitor current activity of a single neuron per population
# Useful to debug the model or some parameters
ind = num_neurons_sub_pop / 2
neurons_states = []
for k in range(num_orientations):
    neurons_states.append(
        StateMonitor(populations[k],
                     variables=["Iin", "Imem"],
                     record=ind,
                     name='statemon_pop_' + str(k)))

# Monitor current activity of a single synapse per population
# Useful to debug the model or some parameters
ind = (num_neurons_sub_pop * kernel_size**2) / 2
synapse_states = []
for k in range(num_orientations):
    synapse_states.append(
        StateMonitor(synapses[k],
                     variables=["Ie_syn", "Ii_syn"],
                     record=ind,
                     name='statemon_syn_' + str(k)))

Net.add(retina, populations, synapses, spikemon_retina, neurons_spikes,
        neurons_states, synapse_states)
Beispiel #15
0
def lson(lsoInputSpkFileTuple, temp_degC=37):

    defaultclock.dt = 0.02 * ms  # for better precision

    neuron_type = 'type2'  # medium speed membrane f0 88-130Hz CF 6kHz
    #temp_degC=37.
    Vrest = -63.6 * mV  # resting potential for type2 from RM2003

    nLsons = 1  # number of LSO neurons

    nGbcsCo = 4
    #    nGbcsIp = 4
    #    nSbcsCo = 4
    nSbcsIp = 4

    #    nSbcs = 4
    #    nAnfsPerSbc = 3
    #    nGbcs = 4
    #    nAnfsPerGbc=30

    nAnfsPerInputFile = 40

    nGbcsCoPerLson = 8  # Gjoni et al. 2018
    nSbcsIpPerLson = 40  # Gjoni et al. 2018

    #    sbCoSpkFile = inputSpkFileTuple[0]
    #    sbIpSpkFile = lsoInputSpkFileTuple[1]
    #    gbCoSpkFile = lsoInputSpkFileTuple[2]
    #    gbIpSpkFile = inputSpkFileTuple[3]
    anCoSpkFile = lsoInputSpkFileTuple[0]
    anIpSpkFile = lsoInputSpkFileTuple[1]

    #    sbCoIdxSpktimeArray = np.loadtxt(sbCoSpkFile)
    #    sbCoCellIndices = sbCoIdxSpktimeArray[:, 0].astype(int)
    #    sbCoSpkTimes = sbCoIdxSpktimeArray[:, 1] * ms
    #    sbCoSpkGenGrp = SpikeGeneratorGroup(nSbcsCo, sbCoCellIndices, sbCoSpkTimes)

    gbCoIdxSpktimeArray = np.loadtxt(anCoSpkFile)
    gbCoCellIndices = gbCoIdxSpktimeArray[:, 0].astype(int)
    # For now, spiketimes from Zilany AN in SECONDS, so * 1000*ms
    gbCoSpkTimes = gbCoIdxSpktimeArray[:, 1] * 1000. * ms
    gbCoSpkGenGrp = SpikeGeneratorGroup(nAnfsPerInputFile, gbCoCellIndices,
                                        gbCoSpkTimes)

    sbIpIdxSpktimeArray = np.loadtxt(anIpSpkFile)
    sbIpCellIndices = sbIpIdxSpktimeArray[:, 0].astype(int)
    # For now, spiketimes from Zilany AN in SECONDS, so * 1000*ms
    sbIpSpkTimes = sbIpIdxSpktimeArray[:, 1] * 1000. * ms
    sbIpSpkGenGrp = SpikeGeneratorGroup(nAnfsPerInputFile, sbIpCellIndices,
                                        sbIpSpkTimes)

    #    gbIpIdxSpktimeArray = np.loadtxt(gbIpSpkFile)
    #    gbIpCellIndices = gbIpIdxSpktimeArray[:, 0].astype(int)
    #    gbIpSpkTimes = gbIpIdxSpktimeArray[:, 1] * ms
    #    gbIpSpkGenGrp = SpikeGeneratorGroup(nGbcsIp, gbIpCellIndices, gbIpSpkTimes)

    #    anfIdxSpktimeArray = np.loadtxt(anfSpkFile)
    #    anfIndices = anfIdxSpktimeArray[:, 0].astype(int)
    #    nANF = 132
    #    #anfSpkTimes = [i * second for i in anfIdxSpktimeArray[:, 1]]
    #    anfSpkTimes = anfIdxSpktimeArray[:, 1] * 1000*ms
    #    anfSpkGeneratorGrp = SpikeGeneratorGroup(nANF, anfIndices, anfSpkTimes)

    # Membrane and Ion-Channel parameters
    C = 12 * pF
    EH = -43 * mV
    EK = -70 * mV  # -77*mV in mod file
    EL = -65 * mV
    ENa = 55 * mV  # 55*mV in RM2003; 50*mv by Brette
    nf = 0.85  # proportion of n vs p kinetics
    zss = 0.5  # steady state inactivation of glt
    # default temp_degC = 37., human body temperature in degree celcius
    # q10 for ion-channel time-constants (RM2003, p.3106):
    q10 = 3.**((temp_degC - 22.) / 10.)
    # q10 for ion-channel gbar parameters (RM2003, p.3106):
    q10gbar = 2.**((temp_degC - 22.) / 10.)
    # hcno current (octopus cell)
    frac = 0.0
    qt = 4.5**((temp_degC - 33.) / 10.)
    # Synaptic parameters:
    Es_e = 0. * mV
    tausE = 0.5 * ms
    Es_i = -90 * mV
    tausI = 1.0 * ms
    '''Synaptic weights are unitless according to Brian2.
    The effective unit is siemens, so they can work in amp, volt, siemens eqns.
    We multiply synaptic weight w_e by unit siemens when adding it to g_e.
    We use a local variable w_e for synaptic weight rather than the standard w:'''
    w_elson = 5e-9
    w_ilson = 50e-9  # 6e-9 @ 200Hz; 12e-9 @ 600 Hz
    '''Here's why:
    The synapses sbc3SynE.w synaptic weight references the Same State Variable as 
    as the neuron group sbc3Grp.w (klt activation w).
    Update sbc3Grp.w, and you set sbc3SynE.w to same value, and vice versa.
    This way klt activation and synaptic weight are identical and quite ridiculous.
    So use a local variable other than w for the synaptic weight!'''

    # Maximal conductances of different cell types in nS
    maximal_conductances = dict(
        type1c=(1000, 150, 0, 0, 0.5, 0, 2),
        type1t=(1000, 80, 0, 65, 0.5, 0, 2),
        type12=(1000, 150, 20, 0, 2, 0, 2),
        type21=(1000, 150, 35, 0, 3.5, 0, 2),
        type2=(1000, 150, 200, 0, 20, 0, 2),
        type2gLTH2x=(1000, 150, 400, 0, 40, 0, 2),
        type2gLTH0p5x=(1000, 150, 100, 0, 10, 0, 2),
        type2o=(1000, 150, 600, 0, 0, 40, 2)  # octopus cell
    )
    gnabar, gkhtbar, gkltbar, gkabar, ghbar, gbarno, gl = [
        x * nS for x in maximal_conductances[neuron_type]
    ]

    # Classical Na channel
    eqs_na = """
    ina = gnabar*m**3*h*(ENa-v) : amp
    dm/dt=q10*(minf-m)/mtau : 1
    dh/dt=q10*(hinf-h)/htau : 1
    minf = 1./(1+exp(-(vu + 38.) / 7.)) : 1
    hinf = 1./(1+exp((vu + 65.) / 6.)) : 1
    mtau =  ((10. / (5*exp((vu+60.) / 18.) + 36.*exp(-(vu+60.) / 25.))) + 0.04)*ms : second
    htau =  ((100. / (7*exp((vu+60.) / 11.) + 10.*exp(-(vu+60.) / 25.))) + 0.6)*ms : second
    """

    # KHT channel (delayed-rectifier K+)
    eqs_kht = """
    ikht = gkhtbar*(nf*n**2 + (1-nf)*p)*(EK-v) : amp
    dn/dt=q10*(ninf-n)/ntau : 1
    dp/dt=q10*(pinf-p)/ptau : 1
    ninf = (1 + exp(-(vu + 15) / 5.))**-0.5 : 1
    pinf =  1. / (1 + exp(-(vu + 23) / 6.)) : 1
    ntau = ((100. / (11*exp((vu+60) / 24.) + 21*exp(-(vu+60) / 23.))) + 0.7)*ms : second
    ptau = ((100. / (4*exp((vu+60) / 32.) + 5*exp(-(vu+60) / 22.))) + 5)*ms : second
    """

    # Ih channel (subthreshold adaptive, non-inactivating)
    eqs_ih = """
    ih = ghbar*r*(EH-v) : amp
    dr/dt=q10*(rinf-r)/rtau : 1
    rinf = 1. / (1+exp((vu + 76.) / 7.)) : 1
    rtau = ((100000. / (237.*exp((vu+60.) / 12.) + 17.*exp(-(vu+60.) / 14.))) + 25.)*ms : second
    """

    # KLT channel (low threshold K+)
    eqs_klt = """
    iklt = gkltbar*w**4*z*(EK-v) : amp
    dw/dt=q10*(winf-w)/wtau : 1
    dz/dt=q10*(zinf-z)/ztau : 1
    winf = (1. / (1 + exp(-(vu + 48.) / 6.)))**0.25 : 1
    zinf = zss + ((1.-zss) / (1 + exp((vu + 71.) / 10.))) : 1
    wtau = ((100. / (6.*exp((vu+60.) / 6.) + 16.*exp(-(vu+60.) / 45.))) + 1.5)*ms : second
    ztau = ((1000. / (exp((vu+60.) / 20.) + exp(-(vu+60.) / 8.))) + 50)*ms : second
    """

    # Ka channel (transient K+)
    eqs_ka = """
    ika = gkabar*a**4*b*c*(EK-v): amp
    da/dt=q10*(ainf-a)/atau : 1
    db/dt=q10*(binf-b)/btau : 1
    dc/dt=q10*(cinf-c)/ctau : 1
    ainf = (1. / (1 + exp(-(vu + 31) / 6.)))**0.25 : 1
    binf = 1. / (1 + exp((vu + 66) / 7.))**0.5 : 1
    cinf = 1. / (1 + exp((vu + 66) / 7.))**0.5 : 1
    atau =  ((100. / (7*exp((vu+60) / 14.) + 29*exp(-(vu+60) / 24.))) + 0.1)*ms : second
    btau =  ((1000. / (14*exp((vu+60) / 27.) + 29*exp(-(vu+60) / 24.))) + 1)*ms : second
    ctau = ((90. / (1 + exp((-66-vu) / 17.))) + 10)*ms : second
    """

    # Leak
    eqs_leak = """
    ileak = gl*(EL-v) : amp
    """

    # h current for octopus cells
    eqs_hcno = """
    ihcno = gbarno*(h1*frac + h2*(1-frac))*(EH-v) : amp
    dh1/dt=(hinfno-h1)/tau1 : 1
    dh2/dt=(hinfno-h2)/tau2 : 1
    hinfno = 1./(1+exp((vu+66.)/7.)) : 1
    tau1 = bet1/(qt*0.008*(1+alp1))*ms : second
    tau2 = bet2/(qt*0.0029*(1+alp2))*ms : second
    alp1 = exp(1e-3*3*(vu+50)*9.648e4/(8.315*(273.16+temp_degC))) : 1
    bet1 = exp(1e-3*3*0.3*(vu+50)*9.648e4/(8.315*(273.16+temp_degC))) : 1 
    alp2 = exp(1e-3*3*(vu+84)*9.648e4/(8.315*(273.16+temp_degC))) : 1
    bet2 = exp(1e-3*3*0.6*(vu+84)*9.648e4/(8.315*(273.16+temp_degC))) : 1
    """

    eqs = """
    dv/dt = (ileak + ina + ikht + iklt + ika + ih + ihcno + I + Is_e + Is_i)/C : volt
    Is_e = gs_e * (Es_e - v) : amp
    gs_e : siemens
    Is_i = gs_i * (Es_i - v) : amp
    gs_i : siemens
    vu = v/mV : 1  # unitless v
    I : amp
    """
    #Added Is_i to RM2003

    eqs += eqs_leak + eqs_ka + eqs_na + eqs_ih + eqs_klt + eqs_kht + eqs_hcno

    lsonGrp = NeuronGroup(nLsons,
                          eqs,
                          method='exponential_euler',
                          threshold='v > -30*mV',
                          refractory='v > -45*mV')
    #gbcGrp.I = 2500.0*pA
    lsonGrp.I = 0.0 * pA
    # Initialize model near v_rest with no inputs
    lsonGrp.v = Vrest
    #vu = EL/mV # unitless v
    vu = lsonGrp.v / mV  # unitless v
    lsonGrp.m = 1. / (1 + exp(-(vu + 38.) / 7.))
    lsonGrp.h = 1. / (1 + exp((vu + 65.) / 6.))
    lsonGrp.n = (1 + exp(-(vu + 15) / 5.))**-0.5
    lsonGrp.p = 1. / (1 + exp(-(vu + 23) / 6.))
    lsonGrp.r = 1. / (1 + exp((vu + 76.) / 7.))
    lsonGrp.w = (1. / (1 + exp(-(vu + 48.) / 6.)))**0.25
    lsonGrp.z = zss + ((1. - zss) / (1 + exp((vu + 71.) / 10.)))
    lsonGrp.a = (1. / (1 + exp(-(vu + 31) / 6.)))**0.25
    lsonGrp.b = 1. / (1 + exp((vu + 66) / 7.))**0.5
    lsonGrp.c = 1. / (1 + exp((vu + 66) / 7.))**0.5
    lsonGrp.h1 = 1. / (1 + exp((vu + 66.) / 7.))
    lsonGrp.h2 = 1. / (1 + exp((vu + 66.) / 7.))
    #lsonGrp.gs_e = 0.0*siemens

    #netGbcEq = Network(gbcGrp, report='text')
    #netGbcEq.run(50*ms, report='text')

    lsonSynI = Synapses(gbCoSpkGenGrp,
                        lsonGrp,
                        model='''dg_i/dt = -g_i/tausI : siemens (clock-driven)
                              gs_i_post = g_i : siemens (summed)''',
                        on_pre='g_i += w_ilson*siemens',
                        method='exact')
    lsonSynI.connect(i=np.arange(nGbcsCoPerLson), j=0)

    lsonSynE = Synapses(sbIpSpkGenGrp,
                        lsonGrp,
                        model='''dg_e/dt = -g_e/tausE : siemens (clock-driven)
                              gs_e_post = g_e : siemens (summed)''',
                        on_pre='g_e += w_elson*siemens',
                        method='exact')
    lsonSynE.connect(i=np.arange(nSbcsIpPerLson), j=0)

    lsonSpks = SpikeMonitor(lsonGrp)
    lsonState = StateMonitor(lsonGrp, ['v', 'gs_e'], record=True)

    run(300 * ms, report='text')

    # Console Output Won't Clear from Script
    # Memory issue with so many repeated simulations:
    # Comment out the plt commands
    #plt.plot(lsonState.t / ms, lsonState[0].v / mV)
    #plt.xlabel('t (ms)')
    #plt.ylabel('v (mV)')
    #plt.show()

    # Output file - EIPD in output filename. Spiketimes in file
    EPhsStrCo = anCoSpkFile[35:39]
    EPhsStrIp = anIpSpkFile[35:39]
    if (EPhsStrCo[0] == 'N'):
        EPhsIntCo = -1 * int(EPhsStrCo[1:4])
    else:
        EPhsIntCo = int(EPhsStrCo[0:3])
    if (EPhsStrIp[0] == 'N'):
        EPhsIntIp = -1 * int(EPhsStrIp[1:4])
    else:
        EPhsIntIp = int(EPhsStrIp[0:3])
#    EIPD = (EPhsIntCo - EPhsIntIp) % 360
    EIPDint = (EPhsIntCo - EPhsIntIp)  # unwrapped Envelope IPD
    #EIPDstr = str(EIPDint)
    if (EIPDint == 15):
        EIPDstr = 'EIPDP015'
    elif (EIPDint == 30):
        EIPDstr = 'EIPDP030'
    elif (EIPDint == 45):
        EIPDstr = 'EIPDP045'
    elif (EIPDint == 60):
        EIPDstr = 'EIPDP060'
    elif (EIPDint == 75):
        EIPDstr = 'EIPDP075'
    elif (EIPDint == 90):
        EIPDstr = 'EIPDP090'
    elif (EIPDint == -15):
        EIPDstr = 'EIPDN015'
    elif (EIPDint == -30):
        EIPDstr = 'EIPDN030'
    elif (EIPDint == -45):
        EIPDstr = 'EIPDN045'
    elif (EIPDint == -60):
        EIPDstr = 'EIPDN060'
    elif (EIPDint == -75):
        EIPDstr = 'EIPDN075'
    elif (EIPDint == -90):
        EIPDstr = 'EIPDN090'
    elif (EIPDint > 0):
        EIPDstr = 'EIPDP' + str(EIPDint)
    elif (EIPDint < 0):
        EIPDstr = 'EIPDN' + str(-EIPDint)
    elif (EIPDint == 0):
        EIPDstr = 'EIPDP000'

#    if (EIPDint < 0):
#        EIPDstr = EIPDstr.replace('-','N')

# Synaptic parameters in output filename
    if (abs(round(tausE / ms) - (tausE / ms)) < 0.1):
        Te = str(round(tausE / ms))
    else:
        Te = str(tausE / ms)
    Te = Te.replace('.', 'p')

    if (abs(round(w_elson / 1e-9) - (w_elson / 1e-9)) < 0.1):
        We = str(round(w_elson / 1e-9))
    else:
        We = str(w_elson / 1e-9)
    We = We.replace('.', 'p')

    if (abs(round(tausI / ms) - (tausI / ms)) < 0.1):
        Ti = str(round(tausI / ms))
    else:
        Ti = str(tausI / ms)
    Ti = Ti.replace('.', 'p')

    if (abs(round(w_ilson / 1e-9) - (w_ilson / 1e-9)) < 0.1):
        Wi = str(round(w_ilson / 1e-9))
    else:
        Wi = str(w_ilson / 1e-9)
    Wi = Wi.replace('.', 'p')

    lsonSpkFile = 'Lso2SpT' + anCoSpkFile[6:13] + anCoSpkFile[16:21] + anCoSpkFile[
        24:
        31] + 'Te' + Te + 'We' + We + 'Ti' + Ti + 'Wi' + Wi + EIPDstr + 'C' + anCoSpkFile[
            46:48] + anCoSpkFile[31:33] + anCoSpkFile[35:39] + anCoSpkFile[53:]
    file0 = open(lsonSpkFile, 'w')
    for index in range(len(lsonSpks.t)):
        file0.write(
            str(lsonSpks.i[index]) + " " + str(lsonSpks.t[index] / ms) + '\n')
    file0.close()

    return (lsonGrp, lsonSpks, lsonState)


# end of mkgbcs
Beispiel #16
0
def main():  # pragma: no cover
    from brian2 import start_scope, mvolt, ms, NeuronGroup, StateMonitor, run
    import matplotlib.pyplot as plt
    import neo
    import quantities as pq

    start_scope()

    # Izhikevich neuron parameters.
    a = 0.02 / ms
    b = 0.2 / ms
    c = -65 * mvolt
    d = 6 * mvolt / ms
    I = 4 * mvolt / ms

    # Standard Izhikevich neuron equations.
    eqs = """
  dv/dt = 0.04*v**2/(ms*mvolt) + (5/ms)*v + 140*mvolt/ms - u + I : volt
  du/dt = a*((b*v) - u) : volt/second
  """

    reset = """
  v = c
  u += d
  """

    # Setup and run simulation.
    G = NeuronGroup(1, eqs, threshold='v>30*mvolt', reset='v = -70*mvolt')
    G.v = -65 * mvolt
    G.u = b * G.v
    M = StateMonitor(G, 'v', record=True)
    run(300 * ms)

    # Store results in neo format.
    vm = neo.core.AnalogSignal(M.v[0], units=pq.V, sampling_period=0.1 * pq.ms)

    # Plot results.
    plt.figure()
    plt.plot(vm.times * 1000, vm * 1000)  # Plot mV and ms instead of V and s.
    plt.xlabel('Time (ms)')
    plt.ylabel('mv')

    # Save results.
    iom = neo.io.PyNNNumpyIO('spike_extraction_test_data')
    block = neo.core.Block()
    segment = neo.core.Segment()
    segment.analogsignals.append(vm)
    block.segments.append(segment)
    iom.write(block)

    # Load results.
    iom2 = neo.io.PyNNNumpyIO('spike_extraction_test_data.npz')
    data = iom2.read()
    vm = data[0].segments[0].analogsignals[0]

    # Plot results.
    # The two figures should match.
    plt.figure()
    plt.plot(vm.times * 1000, vm * 1000)  # Plot mV and ms instead of V and s.
    plt.xlabel('Time (ms)')
    plt.ylabel('mv')
    synPropsI = getattr(synapsePropsList, DLInt1SynapsePropsI)
    dlint1.addSynapse(synName="InhJO",
                      sourceNG=JO.JOSGG,
                      **exp2Syn,
                      synParsInits=synPropsI,
                      synStateInits=exp2SynStateInits,
                      sourceInd=0,
                      destInd=0)

net = Network()
net.add(JO.JOSGG)
dlint1.addToNetwork(net)

if DLInt1SynapsePropsE:
    gEMonitor = StateMonitor(dlint1.incomingSynapses["ExiJO"],
                             "g_ExiJO",
                             record=True)
    net.add(gEMonitor)

if DLInt1SynapsePropsI:
    gIMonitor = StateMonitor(dlint1.incomingSynapses["InhJO"],
                             "g_InhJO",
                             record=True)
    net.add(gIMonitor)

defaultclock.dt = simStepSize
totalSimDur = simDuration + simSettleTime
net.run(totalSimDur, report='text')

simT, memV = dlint1.getMemVTrace()
spikeTimes = dlint1.getSpikes()
Beispiel #18
0
            "ylim": [0, 20],
            "xlim": [0, 500],
            "xtickstep": 50,
        },
    },
}

fig, axes = plt.subplots(3)

for ax, (panel, p) in zip(axes, parameters.items()):

    neuron = get_neuron(**p["neuron"])
    stimulus = get_stimulus(**p["stimulus"])
    synapses = get_synapses(stimulus, neuron, **p["synapse"])

    state_monitor_neuron = StateMonitor(neuron, ["v"], record=True)

    run(p["simulation"]["duration"])

    ax.plot(
        state_monitor_neuron.t / ms,
        state_monitor_neuron[0].v / mV,
        label=p["plot"]["title"],
    )

    ax.set_xlim(*p["plot"]["xlim"])
    ax.set_ylim(*p["plot"]["ylim"])
    ax.set_ylabel("mV")
    ax.set_xlabel("Time (ms)")

    ax.set_xticks(
Beispiel #19
0
def lson(lsoInputSpkFileTuple, temp_degC=37):

    defaultclock.dt = 0.02 * ms  # for better precision

    neuron_type = 'type2gLTH0p5x'  # medium speed membrane, nominal f0 88Hz
    Vrest = -63.6 * mV  # resting potential for type2 from RM2003

    nLsons = 1  # number of LSO neurons

    # As in Wang & Colburn (2012), the LSO model has simplified inputs.
    # Spike times from model auditory nerve fibers represent inputs
    # driven by the cochlear nucleus: contralateral inhibitory inputs
    # driven by globular bushy cells via the MNTB, and ipsilateral
    # excitatory inputs from spherical bushy cells.

    nAnfsPerInputFile = 40

    nGbcsCoPerLson = 8  # Gjoni et al. 2018
    nSbcsIpPerLson = 40  # Gjoni et al. 2018

    #sbIpSpkFile = lsoInputSpkFileTuple[1]
    #gbCoSpkFile = lsoInputSpkFileTuple[2]
    anCoSpkFile = lsoInputSpkFileTuple[0]
    anIpSpkFile = lsoInputSpkFileTuple[1]

    gbCoIdxSpktimeArray = np.loadtxt(anCoSpkFile)
    gbCoCellIndices = gbCoIdxSpktimeArray[:, 0].astype(int)
    # For now, spiketimes from Zilany AN in SECONDS, so * 1000*ms
    gbCoSpkTimes = gbCoIdxSpktimeArray[:, 1] * 1000. * ms
    gbCoSpkGenGrp = SpikeGeneratorGroup(nAnfsPerInputFile, gbCoCellIndices,
                                        gbCoSpkTimes)

    sbIpIdxSpktimeArray = np.loadtxt(anIpSpkFile)
    sbIpCellIndices = sbIpIdxSpktimeArray[:, 0].astype(int)
    # For now, spiketimes from Zilany AN in SECONDS, so * 1000*ms
    sbIpSpkTimes = sbIpIdxSpktimeArray[:, 1] * 1000. * ms
    sbIpSpkGenGrp = SpikeGeneratorGroup(nAnfsPerInputFile, sbIpCellIndices,
                                        sbIpSpkTimes)

    # Membrane and Ion-Channel parameters
    C = 12 * pF
    EH = -43 * mV
    EK = -70 * mV  # -77*mV in mod file
    EL = -65 * mV
    ENa = 55 * mV  # 55*mV in RM2003; 50*mv by Brette
    nf = 0.85  # proportion of n vs p kinetics
    zss = 0.5  # steady state inactivation of glt
    # default temp_degC = 37., human body temperature in degree celcius
    # q10 for ion-channel time-constants (RM2003, p.3106):
    q10 = 3.**((temp_degC - 22.) / 10.)
    # q10 for ion-channel gbar parameters (RM2003, p.3106):
    q10gbar = 2.**((temp_degC - 22.) / 10.)
    # hcno current (octopus cell)
    frac = 0.0
    qt = 4.5**((temp_degC - 33.) / 10.)
    # Synaptic parameters:
    Es_e = 0. * mV
    tausE = 1.0 * ms
    Es_i = -90 * mV
    tausI = 2.0 * ms
    '''Synaptic weights are unitless according to Brian2.
    The effective unit is siemens, so they can work in amp, volt, siemens eqns.
    We multiply synaptic weight w_e by unit siemens when adding it to g_e.
    We use a local variable w_e for synaptic weight rather than the standard w:'''
    w_elson = 3e-9
    w_ilson = 30e-9  # 6e-9 @ 200Hz; 12e-9 @ 600 Hz
    '''Here's why:
    The synapses sbc3SynE.w synaptic weight references the Same State Variable as 
    as the neuron group sbc3Grp.w (klt activation w).
    Update sbc3Grp.w, and you set sbc3SynE.w to same value, and vice versa.
    This way klt activation and synaptic weight are identical and quite ridiculous.
    So use a local variable other than w for the synaptic weight!'''

    # Maximal conductances of different cell types in nS
    maximal_conductances = dict(
        type1c=(1000, 150, 0, 0, 0.5, 0, 2),
        type1t=(1000, 80, 0, 65, 0.5, 0, 2),
        type12=(1000, 150, 20, 0, 2, 0, 2),
        type21=(1000, 150, 35, 0, 3.5, 0, 2),
        type2=(1000, 150, 200, 0, 20, 0, 2),
        type2g2x=(2000, 300, 400, 0, 40, 0, 2),
        type2g1p5x=(1000, 150, 300, 0, 30, 0, 2),
        type2g1p2x=(1200, 180, 240, 0, 24, 0, 2),
        type2gLTH0p5x=(1000, 150, 100, 0, 10, 0, 2),
        type2o=(1000, 150, 600, 0, 0, 40, 2)  # octopus cell
    )
    gnabar, gkhtbar, gkltbar, gkabar, ghbar, gbarno, gl = [
        x * nS for x in maximal_conductances[neuron_type]
    ]

    # Classical Na channel
    eqs_na = """
    ina = gnabar*m**3*h*(ENa-v) : amp
    dm/dt=q10*(minf-m)/mtau : 1
    dh/dt=q10*(hinf-h)/htau : 1
    minf = 1./(1+exp(-(vu + 38.) / 7.)) : 1
    hinf = 1./(1+exp((vu + 65.) / 6.)) : 1
    mtau =  ((10. / (5*exp((vu+60.) / 18.) + 36.*exp(-(vu+60.) / 25.))) + 0.04)*ms : second
    htau =  ((100. / (7*exp((vu+60.) / 11.) + 10.*exp(-(vu+60.) / 25.))) + 0.6)*ms : second
    """

    # KHT channel (delayed-rectifier K+)
    eqs_kht = """
    ikht = gkhtbar*(nf*n**2 + (1-nf)*p)*(EK-v) : amp
    dn/dt=q10*(ninf-n)/ntau : 1
    dp/dt=q10*(pinf-p)/ptau : 1
    ninf = (1 + exp(-(vu + 15) / 5.))**-0.5 : 1
    pinf =  1. / (1 + exp(-(vu + 23) / 6.)) : 1
    ntau = ((100. / (11*exp((vu+60) / 24.) + 21*exp(-(vu+60) / 23.))) + 0.7)*ms : second
    ptau = ((100. / (4*exp((vu+60) / 32.) + 5*exp(-(vu+60) / 22.))) + 5)*ms : second
    """

    # Ih channel (subthreshold adaptive, non-inactivating)
    eqs_ih = """
    ih = ghbar*r*(EH-v) : amp
    dr/dt=q10*(rinf-r)/rtau : 1
    rinf = 1. / (1+exp((vu + 76.) / 7.)) : 1
    rtau = ((100000. / (237.*exp((vu+60.) / 12.) + 17.*exp(-(vu+60.) / 14.))) + 25.)*ms : second
    """

    # KLT channel (low threshold K+)
    eqs_klt = """
    iklt = gkltbar*w**4*z*(EK-v) : amp
    dw/dt=q10*(winf-w)/wtau : 1
    dz/dt=q10*(zinf-z)/ztau : 1
    winf = (1. / (1 + exp(-(vu + 48.) / 6.)))**0.25 : 1
    zinf = zss + ((1.-zss) / (1 + exp((vu + 71.) / 10.))) : 1
    wtau = ((100. / (6.*exp((vu+60.) / 6.) + 16.*exp(-(vu+60.) / 45.))) + 1.5)*ms : second
    ztau = ((1000. / (exp((vu+60.) / 20.) + exp(-(vu+60.) / 8.))) + 50)*ms : second
    """

    # Ka channel (transient K+)
    eqs_ka = """
    ika = gkabar*a**4*b*c*(EK-v): amp
    da/dt=q10*(ainf-a)/atau : 1
    db/dt=q10*(binf-b)/btau : 1
    dc/dt=q10*(cinf-c)/ctau : 1
    ainf = (1. / (1 + exp(-(vu + 31) / 6.)))**0.25 : 1
    binf = 1. / (1 + exp((vu + 66) / 7.))**0.5 : 1
    cinf = 1. / (1 + exp((vu + 66) / 7.))**0.5 : 1
    atau =  ((100. / (7*exp((vu+60) / 14.) + 29*exp(-(vu+60) / 24.))) + 0.1)*ms : second
    btau =  ((1000. / (14*exp((vu+60) / 27.) + 29*exp(-(vu+60) / 24.))) + 1)*ms : second
    ctau = ((90. / (1 + exp((-66-vu) / 17.))) + 10)*ms : second
    """

    # Leak
    eqs_leak = """
    ileak = gl*(EL-v) : amp
    """

    # h current for octopus cells
    eqs_hcno = """
    ihcno = gbarno*(h1*frac + h2*(1-frac))*(EH-v) : amp
    dh1/dt=(hinfno-h1)/tau1 : 1
    dh2/dt=(hinfno-h2)/tau2 : 1
    hinfno = 1./(1+exp((vu+66.)/7.)) : 1
    tau1 = bet1/(qt*0.008*(1+alp1))*ms : second
    tau2 = bet2/(qt*0.0029*(1+alp2))*ms : second
    alp1 = exp(1e-3*3*(vu+50)*9.648e4/(8.315*(273.16+temp_degC))) : 1
    bet1 = exp(1e-3*3*0.3*(vu+50)*9.648e4/(8.315*(273.16+temp_degC))) : 1 
    alp2 = exp(1e-3*3*(vu+84)*9.648e4/(8.315*(273.16+temp_degC))) : 1
    bet2 = exp(1e-3*3*0.6*(vu+84)*9.648e4/(8.315*(273.16+temp_degC))) : 1
    """

    eqs = """
    dv/dt = (ileak + ina + ikht + iklt + ika + ih + ihcno + I + Is_e + Is_i)/C : volt
    Is_e = gs_e * (Es_e - v) : amp
    gs_e : siemens
    Is_i = gs_i * (Es_i - v) : amp
    gs_i : siemens
    vu = v/mV : 1  # unitless v
    I : amp
    """
    #Added Is_i to RM2003

    eqs += eqs_leak + eqs_ka + eqs_na + eqs_ih + eqs_klt + eqs_kht + eqs_hcno

    lsonGrp = NeuronGroup(nLsons,
                          eqs,
                          method='exponential_euler',
                          threshold='v > -30*mV',
                          refractory='v > -45*mV')
    lsonGrp.I = 0.0 * pA
    # Initialize model near v_rest with no inputs
    lsonGrp.v = Vrest
    vu = lsonGrp.v / mV  # unitless v
    lsonGrp.m = 1. / (1 + exp(-(vu + 38.) / 7.))
    lsonGrp.h = 1. / (1 + exp((vu + 65.) / 6.))
    lsonGrp.n = (1 + exp(-(vu + 15) / 5.))**-0.5
    lsonGrp.p = 1. / (1 + exp(-(vu + 23) / 6.))
    lsonGrp.r = 1. / (1 + exp((vu + 76.) / 7.))
    lsonGrp.w = (1. / (1 + exp(-(vu + 48.) / 6.)))**0.25
    lsonGrp.z = zss + ((1. - zss) / (1 + exp((vu + 71.) / 10.)))
    lsonGrp.a = (1. / (1 + exp(-(vu + 31) / 6.)))**0.25
    lsonGrp.b = 1. / (1 + exp((vu + 66) / 7.))**0.5
    lsonGrp.c = 1. / (1 + exp((vu + 66) / 7.))**0.5
    lsonGrp.h1 = 1. / (1 + exp((vu + 66.) / 7.))
    lsonGrp.h2 = 1. / (1 + exp((vu + 66.) / 7.))
    #lsonGrp.gs_e = 0.0*siemens

    lsonSynI = Synapses(gbCoSpkGenGrp,
                        lsonGrp,
                        model='''dg_i/dt = -g_i/tausI : siemens (clock-driven)
                              gs_i_post = g_i : siemens (summed)''',
                        on_pre='g_i += w_ilson*siemens',
                        method='exact')
    lsonSynI.connect(i=np.arange(nGbcsCoPerLson), j=0)

    lsonSynE = Synapses(sbIpSpkGenGrp,
                        lsonGrp,
                        model='''dg_e/dt = -g_e/tausE : siemens (clock-driven)
                              gs_e_post = g_e : siemens (summed)''',
                        on_pre='g_e += w_elson*siemens',
                        method='exact')
    lsonSynE.connect(i=np.arange(nSbcsIpPerLson), j=0)

    lsonSpks = SpikeMonitor(lsonGrp)
    lsonState = StateMonitor(lsonGrp, ['v', 'gs_e'], record=True)

    run(8150 * ms, report='text')

    plt.plot(lsonState.t / ms, lsonState[0].v / mV)
    #plt.plot(gbcState.t / ms, gbcState[0].gs_e)
    #plt.plot(gSynEState.t / ms, gSynEState[0].gs_e_post)
    #plt.plot(gSynEState.t / ms, gSynEState[0].g_e)

    plt.xlabel('t (ms)')
    plt.ylabel('v (mV)')
    plt.show()

    dBSPLStrCo = anCoSpkFile[28:30]
    dBSPLStrIp = anIpSpkFile[28:30]
    dBSPLCo = int(dBSPLStrCo)
    dBSPLIp = int(dBSPLStrIp)
    IIDdB = dBSPLCo - dBSPLIp
    if (IIDdB >= 0):
        IIDdBStr = 'IIDP' + str(IIDdB).zfill(2) + 'dBSPL'
    elif (IIDdB < 0):
        IIDdBStr = 'IIDN' + str(-IIDdB).zfill(2) + 'dBSPL'

    # Synaptic parameters in output filename
    if (abs(round(tausE / ms) - (tausE / ms)) < 0.1):
        Te = str(round(tausE / ms))
    else:
        #Te = str(tausE/ms)
        Te = str(round(10 * tausE / ms) / 10.)
    Te = Te.replace('.', 'p')

    if (abs(round(w_elson / 1e-9) - (w_elson / 1e-9)) < 0.1):
        We = str(round(w_elson / 1e-9))
    else:
        #We = str(w_elson/1e-9)
        We = str(round(10 * w_elson / 1e-9) / 10)
    We = We.replace('.', 'p')

    if (abs(round(tausI / ms) - (tausI / ms)) < 0.1):
        Ti = str(round(tausI / ms))
    else:
        Ti = str(tausI / ms)
    Ti = Ti.replace('.', 'p')

    if (abs(round(w_ilson / 1e-9) - (w_ilson / 1e-9)) < 0.1):
        Wi = str(round(w_ilson / 1e-9))
    else:
        Wi = str(w_ilson / 1e-9)
    Wi = Wi.replace('.', 'p')

    # CaCF, Te We Ti Wi, IID, SPLdBiNNcDD, .txt
    lsonSpkFile = 'Lso2zSpTms' + anCoSpkFile[
        10:
        17] + 'Te' + Te + 'We' + We + 'Ti' + Ti + 'Wi' + Wi + IIDdBStr + 'co' + dBSPLStrCo + 'ip' + dBSPLStrIp + anCoSpkFile[
            35:]
    file0 = open(lsonSpkFile, 'w')
    for index in range(len(lsonSpks.t)):
        file0.write(
            str(lsonSpks.i[index]) + " " + str(lsonSpks.t[index] / ms) + '\n')
    file0.close()

    return (lsonGrp, lsonSpks, lsonState)


# end of mkgbcs
Beispiel #20
0
def run_net(tr):

    # prefs.codegen.target = 'numpy'
    # prefs.codegen.target = 'cython'
    set_device('cpp_standalone', directory='./builds/%.4d'%(tr.v_idx),
               build_on_run=False)

    print("Started process with id ", str(tr.v_idx))

    namespace = tr.netw.f_to_dict(short_names=True, fast_access=True)
    namespace['idx'] = tr.v_idx

    defaultclock.dt = tr.netw.sim.dt

    GExc = NeuronGroup(N=tr.N_e, model=tr.condlif_sig,
                       threshold=tr.nrnEE_thrshld,
                       reset=tr.nrnEE_reset, #method=tr.neuron_method,
                       namespace=namespace)
    GInh = NeuronGroup(N=tr.N_i, model=tr.condlif_sig,
                       threshold ='V > Vt',
                       reset='V=Vr_i', #method=tr.neuron_method,
                       namespace=namespace)

    # set initial thresholds fixed, init. potentials uniformly distrib.
    GExc.sigma, GInh.sigma = tr.sigma_e, tr.sigma_i
    GExc.Vt, GInh.Vt = tr.Vt_e, tr.Vt_i
    GExc.V , GInh.V  = np.random.uniform(tr.Vr_e/mV, tr.Vt_e/mV,
                                         size=tr.N_e)*mV, \
                       np.random.uniform(tr.Vr_i/mV, tr.Vt_i/mV,
                                         size=tr.N_i)*mV

    synEE_pre_mod = mod.synEE_pre
    synEE_post_mod = mod.synEE_post

    if tr.stdp_active:
        synEE_pre_mod  = '''%s 
                            %s''' %(synEE_pre_mod, mod.synEE_pre_STDP)
        synEE_post_mod = '''%s 
                            %s''' %(synEE_post_mod, mod.synEE_post_STDP)

    
    if tr.synEE_rec:
        synEE_pre_mod  = '''%s 
                            %s''' %(synEE_pre_mod, mod.synEE_pre_rec)
        synEE_post_mod = '''%s 
                            %s''' %(synEE_post_mod, mod.synEE_post_rec)

        
    # E<-E advanced synapse model, rest simple
    SynEE = Synapses(target=GExc, source=GExc, model=tr.synEE_mod,
                     on_pre=synEE_pre_mod, on_post=synEE_post_mod,
                     #method=tr.synEE_method,
                     namespace=namespace)
    SynIE = Synapses(target=GInh, source=GExc, on_pre='ge_post += a_ie',
                     namespace=namespace)
    SynEI = Synapses(target=GExc, source=GInh, on_pre='gi_post += a_ei',
                     namespace=namespace)
    SynII = Synapses(target=GInh, source=GInh, on_pre='gi_post += a_ii',
                     namespace=namespace)

    

    if tr.strct_active:
        sEE_src, sEE_tar = generate_full_connectivity(tr.N_e, same=True)
        SynEE.connect(i=sEE_src, j=sEE_tar)
        SynEE.syn_active = 0

    else:
        srcs_full, tars_full = generate_full_connectivity(tr.N_e, same=True)
        SynEE.connect(i=srcs_full, j=tars_full)
        SynEE.syn_active = 0


    sIE_src, sIE_tar = generate_connections(tr.N_i, tr.N_e, tr.p_ie)
    sEI_src, sEI_tar = generate_connections(tr.N_e, tr.N_i, tr.p_ei)
    sII_src, sII_tar = generate_connections(tr.N_i, tr.N_i, tr.p_ii,
                                            same=True)

    SynIE.connect(i=sIE_src, j=sIE_tar)
    SynEI.connect(i=sEI_src, j=sEI_tar)
    SynII.connect(i=sII_src, j=sII_tar)
        
    tr.f_add_result('sIE_src', sIE_src)
    tr.f_add_result('sIE_tar', sIE_tar)
    tr.f_add_result('sEI_src', sEI_src)
    tr.f_add_result('sEI_tar', sEI_tar)
    tr.f_add_result('sII_src', sII_src)
    tr.f_add_result('sII_tar', sII_tar)

    if tr.strct_active:
        SynEE.a = 0
    else:
        SynEE.a = tr.a_ee
        
    SynEE.insert_P = tr.insert_P


    # make synapse active at beginning
    if not tr.strct_active:
        SynEE.run_regularly(tr.synEE_p_activate, dt=tr.T, when='start',
                            order=-100)

    # synaptic scaling
    if tr.netw.config.scl_active:
        SynEE.summed_updaters['Asum_post']._clock = Clock(
            dt=tr.dt_synEE_scaling)
        SynEE.run_regularly(tr.synEE_scaling, dt = tr.dt_synEE_scaling,
                            when='end')

    # intrinsic plasticity
    if tr.netw.config.it_active:
        GExc.h_ip = tr.h_ip
        GExc.run_regularly(tr.intrinsic_mod, dt = tr.it_dt, when='end')

    # structural plasticity
    if tr.netw.config.strct_active:
        SynEE.run_regularly(tr.strct_mod, dt = tr.strct_dt, when='end')

    # -------------- recording ------------------        

    #run(tr.sim.preT)

    GExc_recvars = []
    if tr.memtraces_rec:
        GExc_recvars.append('V')
    if tr.vttraces_rec:
        GExc_recvars.append('Vt')
    if tr.getraces_rec:
        GExc_recvars.append('ge')
    if tr.gitraces_rec:
        GExc_recvars.append('gi')

    GInh_recvars = GExc_recvars
    
    GExc_stat = StateMonitor(GExc, GExc_recvars, record=[0,1,2],
                             dt=tr.GExc_stat_dt)
    GInh_stat = StateMonitor(GInh, GInh_recvars, record=[0,1,2],
                             dt=tr.GInh_stat_dt)
    

    SynEE_recvars = []
    if tr.synee_atraces_rec:
        SynEE_recvars.append('a')
    if tr.synee_Apretraces_rec:
        SynEE_recvars.append('Apre')
    if tr.synee_Aposttraces_rec:
        SynEE_recvars.append('Apost')

    SynEE_stat = StateMonitor(SynEE, SynEE_recvars,
                              record=range(tr.n_synee_traces_rec),
                              when='end', dt=tr.synEE_stat_dt)

    GExc_spks = SpikeMonitor(GExc)    
    GInh_spks = SpikeMonitor(GInh)

    
    SynEE_a = StateMonitor(SynEE, ['a','syn_active'],
                           record=range(tr.N_e*(tr.N_e-1)),
                           dt=tr.sim.T/10., when='end', order=100)

    
    run(tr.sim.T, report='text')
    SynEE_a.record_single_timestep()
    device.build(directory='../builds/%.4d'%(tr.v_idx))

        
    tr.v_standard_result = Brian2MonitorResult

    tr.f_add_result('GExc_stat', GExc_stat)
    tr.f_add_result('SynEE_stat', SynEE_stat)
    print("Saving exc spikes...   ", GExc_spks.get_states()['N'])
    tr.f_add_result('GExc_spks', GExc_spks)
    tr.f_add_result('GInh_stat', GInh_stat)
    print("Saving inh spikes...   ", GInh_spks.get_states()['N'])
    tr.f_add_result('GInh_spks', GInh_spks)
    tr.f_add_result('SynEE_a', SynEE_a)


    # ----------------- add raw data ------------------------
    fpath = '../builds/%.4d/'%(tr.v_idx)

    from pathlib import Path

    Path(fpath+'turnover').touch()
    turnover_data = np.genfromtxt(fpath+'turnover',delimiter=',')
    tr.f_add_result('turnover', turnover_data)
    os.remove(fpath+'turnover')

    Path(fpath+'spk_register').touch()
    spk_register_data = np.genfromtxt(fpath+'spk_register',delimiter=',')
    tr.f_add_result('spk_register', spk_register_data)
    os.remove(fpath+'spk_register')