Exemple #1
0
def simulate(tau):
    b2.start_scope()

    if standalone_mode:
        b2.get_device().reinit()
        b2.get_device().activate(build_on_run=False, directory=directory_name)

    net = b2.Network()
    P = b2.PoissonGroup(num_inputs, rates=input_rate)
    G = b2.NeuronGroup(1, eqs, threshold='v>1', reset='v=0', method='euler')
    S = b2.Synapses(P, G, on_pre='v += weight')
    S.connect()
    M = b2.SpikeMonitor(G)
    net.add(P)
    net.add(G)
    net.add(S)
    net.add(M)

    net.run(1000 * b2.ms)

    if standalone_mode:
        b2.get_device().build(directory=directory_name,
                              compile=True,
                              run=True,
                              debug=False)

    return M
def main4():
    # Incorporation of refractory period
    bs.start_scope()

    tau = 10 * bs.ms
    # the (unless refractory) is necessary
    # refer to the documentation for more detail
    eqs = '''
    dv/dt = (1-v)/tau : 1 (unless refractory)
    '''
    equation = bs.Equations(eqs)
    # conditions for spiking models
    threshold = 'v>0.8'
    reset = 'v = -0.8'
    refractory = 5 * bs.ms
    G = bs.NeuronGroup(1, eqs, threshold=threshold, reset=reset, method='exact', refractory=refractory)

    state_monitor = bs.StateMonitor(G, 'v', record=0)
    spike_monitor = bs.SpikeMonitor(G)

    bs.run(50 * bs.ms)
    plt.plot(state_monitor.t / bs.ms, state_monitor.v[0])
    plt.xlabel('Time (ms)')
    plt.ylabel('v')
    plt.show()
def test_ExportDevice_options():
    """
    Test the run and build options of ExportDevice
    """
    # test1
    set_device('exporter')
    grp = NeuronGroup(10, 'eqn = 1:1', method='exact')
    run(100 * ms)
    _ = StateMonitor(grp, 'eqn', record=False)
    with pytest.raises(RuntimeError):
        run(100 * ms)

    # test2
    device.reinit()
    with pytest.raises(RuntimeError):
        device.build()

    # test3
    start_scope()
    net = Network()
    set_device('exporter', build_on_run=False)
    grp = NeuronGroup(10, 'eqn = 1:1', method='exact')
    net.add(grp)
    net.run(10 * ms)
    pogrp = PoissonGroup(10, rates=10 * Hz)
    net.add(pogrp)
    net.run(10 * ms)
    mon = StateMonitor(grp, 'eqn', record=False)
    net.add(mon)
    net.run(10 * ms)
    device.build()
    device.reinit()
Exemple #4
0
def main1():
    # adding different weights per synapse
    # ex0 distance-dependent connectivity function=
    # important for a lot neurons that have weaker inhibitory/excitatory connections as the distances get wider
    bs.start_scope()
    n_neurons = 30
    neuron_spacing = 50 * bs.umetre
    width = n_neurons / 4.0 * neuron_spacing

    G = bs.NeuronGroup(n_neurons, 'x:metre')
    G.x = 'i*neuron_spacing'

    # All synapses are connected (excluding self-connections)
    S = bs.Synapses(G, G, 'w:1')
    S.connect(condition='i!=j')

    # basically, any variable you use in the definition of equations is usable as an actual variable in code and vice versa
    # therefore, even if the variable width is labelled as not being used, it actually is lol
    S.w = 'exp(-(x_pre-x_post)**2/(2*width**2))'

    # visualise_connectivity(S)
    plt.clf()

    plt.scatter(S.x_pre / bs.um, S.x_post / bs.um, S.w * 20)
    plt.xlabel('source neuron position (um)')
    plt.ylabel('Target neuron position (um)')
    plt.show()
def test_synapse_init():
    # check initializations validity for synapse variables
    start_scope()
    set_device('exporter')
    eqn = 'dv/dt = -v/tau :1'
    tau = 1 * ms
    w = 1
    P = NeuronGroup(5, eqn, method='euler', threshold='v>0.8')
    Q = NeuronGroup(10, eqn, method='euler', threshold='v>0.9')
    S = Synapses(P, Q, 'g :1', on_pre='v += w')
    S.connect()
    # allowable
    S.g['i>10'] = 10
    S.g[-1] = -1
    S.g[10000] = 'rand() + w + w'
    mon = StateMonitor(S, 'g', record=[0, 1])
    run(1 * ms)
    # not allowable
    with pytest.raises(NotImplementedError):
        S.g[0:1000] = -1
        run(0.5 * ms)
    with pytest.raises(NotImplementedError):
        S.g[0:1] = 'rand() + 10'
        run(0.25 * ms)
    with pytest.raises(NotImplementedError):
        _ = StateMonitor(S, 'g', S.g[0:10])
    device.reinit()
Exemple #6
0
def main8():
    # using generator syntax to create connections
    bs.start_scope()

    n_neurons = 10
    G = bs.NeuronGroup(n_neurons, 'v:1')

    S = bs.Synapses(G, G)
    """
            i : int, ndarray of int, optional
            The presynaptic neuron indices (in the form of an index or an array
            of indices). Must be combined with ``j`` argument.
        j : int, ndarray of int, str, optional
            The postsynaptic neuron indices. It can be an index or array of
            indices if combined with the ``i`` argument, or it can be a string
            generator expression.
    """
    # the above is the reason why j="i" works but not i = "j"
    # only j can take in string. i has to take in int, or ndarray of int
    S.connect(j='i', skip_if_invalid=True)

    # You can also do it the following way
    # S.connect(condition = 'i==j', skip_if_invalid=True)

    visualise_connectivity(S)
def main1():
    bs.start_scope()
    tau = 10 * bs.ms
    # equations must end with : unit
    # unit is the SI unit of that variable
    # the unit is 1 since the number "1" is unitless
    # v represents voltage, but we just keep it unitless for simplicity
    # 1/s not part of the unit since the unit represents the unit of the variable itself
    # rather than the unit of the equation
    eqs = '''
    dv/dt = (1-v)/tau: 1
    '''

    G = bs.NeuronGroup(1, model=eqs, method='exact')
    # record : bool, sequence of ints
    #     Which indices to record, nothing is recorded for ``False``,
    #     everything is recorded for ``True`` (warning: may use a great deal of
    #     memory), or a specified subset of indices.
    M = bs.StateMonitor(G, 'v', record=0)
    print('Before v = %s' % G.v[0])
    bs.run(100 * bs.ms)  # runs the simulation for 100ms
    print('After v = %s' % G.v[0])

    plt.plot(M.t / bs.ms, M.v[0])
    plt.xlabel('Time (ms)')
    plt.ylabel('v')
    plt.show()
def main3():
    # Adding Spikes
    bs.start_scope()

    tau = 10 * bs.ms
    eqs = '''
    dv/dt = (1-v)/tau : 1
    '''

    # conditions for spiking models
    threshold = 'v>0.8'
    reset = 'v = -0.8'
    G = bs.NeuronGroup(1, eqs, threshold=threshold, reset=reset, method='exact')

    M = bs.StateMonitor(G, 'v', record=0)
    bs.run(50 * bs.ms)
    plt.plot(M.t / bs.ms, M.v[0])
    plt.xlabel('Time (ms)')
    plt.ylabel('v')
    plt.show()

    # you can also add spike monitor
    spike_monitor = bs.SpikeMonitor(G)

    bs.run(50 * bs.ms)

    print(f"Spike Times: {spike_monitor.t[:]}")
def test_poissoninput():
    """
    Test collect_PoissonInput()
    """
    # test 1
    start_scope()
    v_th = 1 * volt
    grp = NeuronGroup(10, 'dv/dt = (v_th - v)/(10*ms) :volt', method='euler',
                      threshold='v>100*mV', reset='v=0*mV')
    poi = PoissonInput(grp, 'v', 10, 1*Hz, 'v_th * rand() + 1*mV')
    poi_dict = collect_PoissonInput(poi, get_local_namespace(0))
    assert poi_dict['target'] == grp.name
    assert poi_dict['rate'] == 1*Hz
    assert poi_dict['N'] == 10
    assert poi_dict['target_var'] == 'v'
    assert poi_dict['when'] == poi.when
    assert poi_dict['order'] == poi.order
    assert poi_dict['clock'] == poi.clock.dt
    assert poi_dict['identifiers']['v_th'] == v_th
    # test 2
    grp2 = NeuronGroup(10, 'dv_1_2_3/dt = (v_th - v_1_2_3)/(10*ms) :volt',
                       method='euler', threshold='v_1_2_3>v_th',
                       reset='v_1_2_3=-v_th')
    poi2 = PoissonInput(grp2, 'v_1_2_3', 0, 0*Hz, v_th)
    poi_dict = collect_PoissonInput(poi2, get_local_namespace(0))
    assert poi_dict['target'] == grp2.name
    assert poi_dict['rate'] == 0*Hz
    assert poi_dict['N'] == 0
    assert poi_dict['target_var'] == 'v_1_2_3'
    with pytest.raises(KeyError):
        poi_dict['identifiers']
def test_custom_events_neurongroup():

    start_scope()
    grp = NeuronGroup(10,
                      'dvar/dt = (100 - var) / tau_n : 1',
                      events={'test_event': 'var > 70'},
                      method='exact')
    tau_n = 10 * ms
    grp.thresholder['test_event'].clock.dt = 10 * ms
    neuron_dict = collect_NeuronGroup(grp, get_local_namespace(0))

    custom_event = neuron_dict['events']['test_event']
    thresholder = custom_event['threshold']

    assert thresholder['code'] == 'var > 70'
    assert thresholder['when'] == grp.thresholder['test_event'].when
    assert thresholder['order'] == grp.thresholder['test_event'].order
    assert thresholder['dt'] == 10 * ms

    with pytest.raises(KeyError):
        neuron_dict['events']['spike']
        custom_event['reset']
        custom_event['refractory']

    # check with reset
    grp.run_on_event('test_event', 'var = -10')
    neuron_dict = collect_NeuronGroup(grp, get_local_namespace(0))
    custom_event = neuron_dict['events']['test_event']
    resetter = custom_event['reset']

    assert resetter['code'] == 'var = -10'
    assert resetter['when'] == grp.resetter['test_event'].when
    assert resetter['order'] == grp.resetter['test_event'].order
    assert resetter['dt'] == thresholder['dt']
Exemple #11
0
def simulate_Thl_cell_fig3(par, par_sim):
    num = par_sim['num']
    i_sensory_motor = par_sim['I_sm']

    # b2.set_device('cpp_standalone')
    b2.start_scope()

    eqs = b2.Equations('''    
    minfthl = 1/(1+exp(-(vt-thtmthl*mV)/(sigmthl*mV))): 1
    hinfthl =  1/(1+exp((vt-thththl*mV)/(sighthl*mV))): 1
    pinfthl = 1/(1+exp(-(vt-thtpthl*mV)/(sigpthl*mV))) :1
    rinfthl = 1/(1+exp((vt-thtrthl*mV)/(sigrthl*mV))) :1
    ahthl =  ah0thl*exp(-(vt-thtahthl*mV)/(sigahthl*mV)) :1
    bhthl =  bh0thl/(1+exp(-(vt-thtbhthl*mV)/(sigbhthl*mV))) :1
    tauhthl =  1/(ahthl+bhthl) *ms :second
    taurthl = taur0thl+taur1thl*exp(-(vt-thtrtauthl*mV)/(sigrtauthl*mV)) :second

    ilthl=glthl*(vt-vlthl):amp
    inathl=gnathl*minfthl*minfthl*minfthl*hthl*(vt-vnathl) :amp
    ikthl=gkthl*((0.75*(1-hthl))**4)*(vt-vkthl) :amp
    itthl=gtthl*pinfthl*pinfthl*rthl*(vt-vtthl) :amp
    iextthl:amp

    tmp_thl1 = sin(2*pi*(t-dsmthl)/tmsmthl) :1
    tmp_thl2 = sin(2*pi*(t-dsmthl+wsmthl)/tmsmthl) :1
    ym_thl1=1/(1+exp(-tmp_thl1/sigym)):1
    ym_thl2=1/(1+exp(-tmp_thl2/sigym)):1
    ithl_sm=imsmthl*ym_thl1*(1-ym_thl2) :amp
    
    membrane_Ithl = -(ilthl+inathl+ikthl+itthl)+iextthl+ithl_sm:amp    
    drthl/dt=phirthl*(rinfthl-rthl)/taurthl :1
    dhthl/dt=phihthl*(hinfthl-hthl)/tauhthl :1 
    dvt/dt = membrane_Ithl/cmthl : volt
    ''')

    neuron = b2.NeuronGroup(
        num,
        eqs,
        method=par_sim['integration_method'],
        dt=par_sim['dt'],
        threshold='vt>-55*mV',
        refractory='vt>-55*mV',
        namespace=par,
    )

    neuron.vt = par['v0']
    neuron.hthl = "hinfthl"
    neuron.rthl = "rinfthl"
    neuron.iextthl = par['iext']

    state_monitor = b2.StateMonitor(neuron, ["vt", "ithl_sm"], record=True)

    net = b2.Network(neuron)
    net.add(state_monitor)
    net.run(par_sim['simulation_time'])

    return state_monitor
Exemple #12
0
def echo_spike(p, tStim, tTot):
    start_scope()
    prefs.codegen.target = "numpy"

    ################################
    # Compute properties
    ################################
    dvInpSpike = p['nu_DV']   # Voltage increase per noise spike
    dvExcSpike = p['LIF_DV']  # Voltage increase per lateral spike
    # dvExcSpike = p['LIF_T_0'] / (1.0 * p['N'] * p['p_conn'])  # Voltage increase per lateral spike

    print("typical spike threshold", p['LIF_T_0'])
    print("typical potential change per noise spike", dvInpSpike)
    print("typical potential change per lateral spike", dvExcSpike)

    ################################
    # Create input population
    ################################
    nTStimPost = int(tTot / tStim) - 1  # After input switched off, 0-input will be repeated nTStimPost*tStim timesteps
    patternInp = (np.random.uniform(0, 1, p['N']) < p['nu_p']).astype(int)
    pattern0 = np.zeros(p['N'])
    rates_all = np.array([patternInp] + [pattern0]*nTStimPost) * p['nu_FREQ']
    rateTimedArray = TimedArray(rates_all, dt=tStim)
    gInp = PoissonGroup(p['N'], rates="rateTimedArray(t, i)")
    # gInp = PoissonGroup(p['N'], p['nu_FREQ'])

    ################################
    # Create reservoir population
    ################################
    gExc = brian2wrapper.NeuronGroupLIF(p['N'], p['LIF_V_0'], p['LIF_T_0'], p['LIF_V_TAU'])

    ################################
    # Create synapses
    ################################
    sInpExc = Synapses(gInp, gExc, on_pre='v_post += dvInpSpike', method='exact')
    sExcExc = Synapses(gExc, gExc, on_pre='v_post += dvExcSpike', method='exact')

    ################################
    # Connect synapses
    ################################
    # * Input and LIF one-to-one
    # * LIF neurons to each other sparsely
    sInpExc.connect(j='i')
    sExcExc.connect(p=p['p_conn'])

    ################################
    # Init Monitors
    ################################
    #spikemonInp = SpikeMonitor(gInp)
    spikemonExc = SpikeMonitor(gExc)

    ################################
    # Run simulation
    ################################
    run(tTot)

    return np.array(spikemonExc.i), np.array(spikemonExc.t)
def test_run_simulation_runtime(setup):
    net, dt, duration = setup
    start_scope()

    rts = RuntimeSimulator()
    rts.initialize(net, var_init=None)

    rts.run(duration, {'g': 100, 'E': 10}, ['g', 'E'])
    I = getattr(rts.networks['fit']['monitor'], 'I')
    assert_equal(np.shape(I), (1, duration / dt))
Exemple #14
0
def main6():
    # connecting only the neighbouring neurons
    bs.start_scope()

    n_neurons = 10
    G = bs.NeuronGroup(n_neurons, 'v:1')

    S = bs.Synapses(G, G)
    # connect only if the neuron is less than 4 spaces and the neuron index isnt the same
    S.connect(condition='abs(i-j)<4 and i!=j')
    visualise_connectivity(S)
Exemple #15
0
def test_initialize_simulation_standalone(setup):
    start_scope()
    net, _, _ = setup
    sas = CPPStandaloneSimulator()
    assert_raises(TypeError, sas.initialize)
    assert_raises(TypeError, sas.initialize, net)
    assert_raises(KeyError, sas.initialize, empty_net, None)
    wrong_net = Network(NeuronGroup(1, model, name='neurons2'))
    assert_raises(Exception, sas.initialize, wrong_net, None)

    sas.initialize(net, var_init=None, name='test')
    assert (isinstance(sas.networks['test'], Network))
def test_initialize_simulation_runtime(setup):
    net, dt, duration = setup
    start_scope()
    rts = RuntimeSimulator()
    assert_raises(TypeError, rts.initialize)

    rts.initialize(net, var_init=None)
    assert (isinstance(rts.networks['fit'], Network))
    assert_raises(KeyError, rts.initialize, empty_net, None)
    wrong_net = Network(NeuronGroup(1, model, name='neurons2'))
    assert_raises(Exception, rts.initialize, wrong_net, None)
    assert_raises(TypeError, rts.initialize, Network)
Exemple #17
0
def main7():
    # using generator syntax to create connections
    bs.start_scope()

    n_neurons = 10
    G = bs.NeuronGroup(n_neurons, 'v:1')

    S = bs.Synapses(G, G)
    # connect only if the neuron is less than 4 spaces and the neuron index isnt the same
    # skip in invalid is needed here since on the edge connections, the i+4 goes over bound and causes error
    S.connect(j='k for k in range(i-3, i+4) if i != k', skip_if_invalid=True)
    visualise_connectivity(S)
Exemple #18
0
def main4(plot=True):
    # what if we want to keep the input spike exactly the same throughout different taus?
    # Solution: We run PoissonGroup once, store all the spikes, and use the stored spikes across the multiple runs
    bs.start_scope()
    num_inputs = 100
    input_rate = 10 * bs.Hz
    w = 0.1
    tau_range = bs.linspace(1, 10, 30) * bs.ms
    output_rates = []

    P = bs.PoissonGroup(num_inputs, rates=input_rate)
    p_monitor = bs.SpikeMonitor(P)

    one_second = 1 * bs.second
    """
    Note that in the code above, we created Network objects. 
    The reason is that in the loop, if we just called run it would try to simulate all the objects, 
    including the Poisson neurons P, and we only want to run that once. 
    We use Network to specify explicitly which objects we want to include.
    """
    net = bs.Network(P, p_monitor)
    net.run(one_second)

    # keeps a copy of the spikes that are generated by the PoissonGroup during that explicit run earlier
    spikes_i = p_monitor.i
    spikes_t = p_monitor.t

    # Construct network that we run each time
    sgg = bs.SpikeGeneratorGroup(num_inputs, spikes_i, spikes_t)
    eqs = '''
    dv/dt = -v/tau : 1
    '''
    G = bs.NeuronGroup(1, eqs, threshold='v>1', reset='v=0', method='exact')
    S = bs.Synapses(sgg, G, on_pre='v += w')
    S.connect()  # fully connected network
    g_monitor = bs.SpikeMonitor(G)

    # store the current state of the network
    net = bs.Network(sgg, G, S, g_monitor)
    net.store()

    for tau in tau_range:
        net.restore()
        net.run(one_second)
        output_rates.append(g_monitor.num_spikes / bs.second)
    if plot:
        plt.clf()
        plt.plot(tau_range / bs.ms, output_rates)
        plt.xlabel(r'$\tau$ (ms)')
        plt.ylabel('Firing Rate (spikes/s)')
        # there is much less noise compared to before where we used different PoissonGroup everytime
        plt.show()
Exemple #19
0
def test_magic_scope():
    '''
    Check that `start_scope` works as expected.
    '''
    G1 = NeuronGroup(1, 'v:1', name='G1')
    G2 = NeuronGroup(1, 'v:1', name='G2')
    objs1 = {obj.name for obj in collect()}
    start_scope()
    G3 = NeuronGroup(1, 'v:1', name='G3')
    G4 = NeuronGroup(1, 'v:1', name='G4')
    objs2 = {obj.name for obj in collect()}
    assert objs1=={'G1', 'G2'}
    assert objs2=={'G3', 'G4'}
Exemple #20
0
def main5():
    # the effect of probability in connections
    bs.start_scope()

    n_neurons = 10
    G = bs.NeuronGroup(n_neurons, model='v:1')

    for p in [0.1, 0.5, 1.0]:
        S = bs.Synapses(G, G)
        # connect neurons that do not have the same index with probability p
        S.connect(condition='i!=j', p=p)
        visualise_connectivity(S)
        plt.suptitle('p = ' + str(p))
Exemple #21
0
def main2():
    # setting synaptic weight
    bs.start_scope()
    n_neurons = 3
    eqs = '''
    dv/dt = (I-v)/tau : 1 (unless refractory)
    I : 1
    tau: second
    '''
    threshold = 'v>1'
    reset = 'v = 0'
    refractory = 10 * bs.ms
    G = bs.NeuronGroup(N=n_neurons,
                       model=eqs,
                       threshold=threshold,
                       reset=reset,
                       method='exact',
                       refractory=refractory)

    G.I = [2, 0, 0]  # represents the I in eqs
    # driving current should be bigger than the threshold, otherwise it wont spike at all

    # I = 0 means that the voltage wont change since there is no driving current
    G.tau = [10, 100, 100] * bs.ms  # represents the tau in eqs
    # unlike last time, the tau is defined with the neuron so we see the effects of different values

    #     model : `str`, `Equations`, optional
    #         The model equations for the synapses.
    # you need to set this as model= in Synapses in order to incorporate weight
    synapse_model = 'w : 1'

    # So in total, what this model says is that whenever two neurons in G are connected by a synapse,
    # when the source neuron fires a spike the target neuron will have its value of v increased by 0.2.
    S = bs.Synapses(source=G,
                    target=G,
                    model=synapse_model,
                    on_pre='v_post +=  w')
    S.connect(i=0, j=[1, 2])
    # So this will give a synaptic connection from 0 to 1 with weight 0.2=0.2*1 and from 0 to 2 with weight 0.4=0.2*2.
    S.w = 'j*0.2'

    state_monitor = bs.StateMonitor(G, 'v', record=True)
    bs.run(100 * bs.ms)

    plt.plot(state_monitor.t / bs.ms, state_monitor.v[0], label='Neuron 0')
    plt.plot(state_monitor.t / bs.ms, state_monitor.v[1], label='Neuron 1')
    plt.plot(state_monitor.t / bs.ms, state_monitor.v[2], label='Neuron 2')
    plt.xlabel('Time (ms)')
    plt.ylabel('v')
    plt.legend()
    plt.show()
def test_synapse_connect_generator():
    # connector test 3
    start_scope()
    set_device('exporter', build_on_run=False)
    tau = 1 * ms
    eqn = 'dv/dt = (1 - v)/tau :1'
    Source = NeuronGroup(10, eqn, method='exact', threshold='v>0.9')
    S1 = Synapses(Source, Source)
    nett2 = Network(Source, S1)
    S1.connect(j='k for k in range(0, i+1)')
    nett2.run(1 * ms)
    connect3 = device.runs[0]['initializers_connectors'][0]
    assert connect3['j'] == 'k for k in range(0, i+1)'
    device.reinit()
def test_run_simulation_runtime_var_init(setup):
    _, dt, duration = setup
    start_scope()

    neurons = NeuronGroup(1, model2, name='neurons')
    monitor = StateMonitor(neurons, 'v', record=True, name='statemonitor')
    net = Network(neurons, monitor)

    rts = RuntimeSimulator()
    rts.initialize(net, var_init={'v': -60 * mV})

    rts.run(duration, {'gL': 100, 'C': 10}, ['gL', 'C'], iteration=0)
    v = getattr(rts.statemonitor, 'v')
    assert_equal(np.shape(v), (1, duration / dt))
Exemple #24
0
def main1():
    bs.start_scope()
    # Parameters
    area = 20000 * bs.umetre**2
    Cm = 1 * bs.ufarad * bs.cm**-2 * area
    gl = 5e-5 * bs.siemens * bs.cm**-2 * area
    El = -65 * bs.mV
    EK = -90 * bs.mV
    ENa = 50 * bs.mV
    g_na = 100 * bs.msiemens * bs.cm**-2 * area
    g_kd = 30 * bs.msiemens * bs.cm**-2 * area
    VT = -63 * bs.mV

    # HH stands for Hudgkin-Huxley
    eqs_HH = '''
    dv/dt = (gl*(El-v) - g_na*(m*m*m)*h*(v-ENa) - g_kd*(n*n*n*n)*(v-EK) + I)/Cm : volt
    
    dm/dt = 0.32*(mV**-1)*(13.*mV-v+VT)/
        (exp((13.*mV-v+VT)/(4.*mV))-1.)/ms*(1-m)-0.28*(mV**-1)*(v-VT-40.*mV)/
        (exp((v-VT-40.*mV)/(5.*mV))-1.)/ms*m : 1
        
    dn/dt = 0.032*(mV**-1)*(15.*mV-v+VT)/
        (exp((15.*mV-v+VT)/(5.*mV))-1.)/ms*(1.-n)-.5*exp((10.*mV-v+VT)/(40.*mV))/ms*n : 1
        
    dh/dt = 0.128*exp((17.*mV-v+VT)/(18.*mV))/ms*(1.-h)-4./(1+exp((40.*mV-v+VT)/(5.*mV)))/ms*h : 1
    
    I : amp
    '''

    group = bs.NeuronGroup(1,
                           eqs_HH,
                           threshold='v > -40*mV',
                           refractory='v > -40*mV',
                           method='exponential_euler')
    group.v = El
    state_monitor = bs.StateMonitor(group, 'v', record=True)
    spike_monitor = bs.SpikeMonitor(group, variables='v')
    plt.figure(figsize=(9, 4))
    for l in range(5):
        group.I = bs.rand() * 50 * bs.nA
        bs.run(10 * bs.ms)
        bs.axvline(l * 10, ls='--', c='k')
    bs.axhline(El / bs.mV, ls='-', c='lightgray', lw=3)
    state_time = state_monitor.t
    spike_time = spike_monitor.t
    plt.plot(state_time / bs.ms, spike_monitor.v[0] / bs.mV, '-b')
    plt.plot(spike_time / bs.ms, spike_monitor.v / bs.mV, 'ob')
    plt.xlabel('Time (ms)')
    plt.ylabel('v (mV)')
    plt.show()
def test_ExportDevice_unsupported():
    """
    Test whether unsupported objects for standard format export
    are raising Error
    """
    start_scope()
    set_device('exporter')
    eqn = '''
    v = 1 :1
    g :1
    '''
    G = NeuronGroup(1, eqn)
    _ = PoissonInput(G, 'g', 1, 1 * Hz, 1)
    # with pytest.raises(NotImplementedError):
    run(10 * ms)
Exemple #26
0
def main3():
    # introducing delay
    bs.start_scope()
    n_neurons = 3
    eqs = '''
    dv/dt = (I-v)/tau : 1 (unless refractory)
    I : 1
    tau: second
    '''
    threshold = 'v>1'
    reset = 'v = 0'
    refractory = 10 * bs.ms
    G = bs.NeuronGroup(N=n_neurons,
                       model=eqs,
                       threshold=threshold,
                       reset=reset,
                       method='exact',
                       refractory=refractory)

    G.I = [2, 0, 0]  # represents the I in eqs
    # driving current should be bigger than the threshold, otherwise it wont spike at all

    # I = 0 means that the voltage wont change since there is no driving current
    G.tau = [10, 100, 100] * bs.ms  # represents the tau in eqs
    # unlike last time, the tau is defined with the neuron so we see the effects of different values

    synapse_model = 'w : 1'

    # So in total, what this model says is that whenever two neurons in G are connected by a synapse,
    # when the source neuron fires a spike the target neuron will have its value of v increased by 0.2.
    S = bs.Synapses(source=G,
                    target=G,
                    model=synapse_model,
                    on_pre='v_post +=  w')
    S.connect(i=0, j=[1, 2])
    S.w = 'j*0.2'
    S.delay = 'j*2*ms'

    state_monitor = bs.StateMonitor(G, 'v', record=True)
    bs.run(100 * bs.ms)

    plt.plot(state_monitor.t / bs.ms, state_monitor.v[0], label='Neuron 0')
    plt.plot(state_monitor.t / bs.ms, state_monitor.v[1], label='Neuron 1')
    plt.plot(state_monitor.t / bs.ms, state_monitor.v[2], label='Neuron 2')
    plt.xlabel('Time (ms)')
    plt.ylabel('v')
    plt.legend()
    plt.show()
Exemple #27
0
def main4():
    # more complex connectivity
    bs.start_scope()
    n_neurons = 3
    tau = 100 * bs.ms
    eqs = '''
    dv/dt = (I-v)/tau : 1 (unless refractory)
    I : 1
    '''
    threshold = 'v>1'
    reset = 'v = 0'
    refractory = 10 * bs.ms

    G = bs.NeuronGroup(N=n_neurons,
                       model=eqs,
                       threshold=threshold,
                       reset=reset,
                       method='exact',
                       refractory=refractory)

    G.I = [2, 0, 0]
    synapse_model = 'w : 1'

    #         p : float, str, optional
    #             The probability to create ``n`` synapses wherever the ``condition``
    #             evaluates to true. Cannot be used with generator syntax for ``j``.
    S = bs.Synapses(source=G,
                    target=G,
                    model=synapse_model,
                    on_pre='v_post +=  w')
    S.connect(condition='i!=j', p=0.5)
    S.w = 'j*0.2'

    state_monitor = bs.StateMonitor(G, 'v', record=True)
    bs.run(100 * bs.ms)

    plt.plot(state_monitor.t / bs.ms, state_monitor.v[0], label='Neuron 0')
    plt.plot(state_monitor.t / bs.ms, state_monitor.v[1], label='Neuron 1')
    plt.plot(state_monitor.t / bs.ms, state_monitor.v[2], label='Neuron 2')
    plt.xlabel('Time (ms)')
    plt.ylabel('v')
    plt.legend()
    plt.show()

    visualise_connectivity(S=S)
def run_simulation(tau_I):

    br.start_scope()


    tau_E = 10*br.ms
    #tau_I = 10*br.ms
    M_EE = 1.25
    M_EI = -1
    M_IE = 1
    M_II = 0
    gamma_E = -10*br.Hz
    gamma_I = 10*br.Hz

    equ1 = '''
    dv_E/dt = (-v_E + (M_EE*v_E + M_EI*v_I - gamma_E))/tau_E : Hz 
    v_I : Hz (linked)
    '''

    equ2 = '''
    dv_I/dt = (-v_I + (M_IE*v_E + M_II*v_I - gamma_I))/tau_I : Hz
    v_E : Hz (linked)
    '''

    G1 = br.NeuronGroup(1, equ1, method = 'euler')
    G2 = br.NeuronGroup(1, equ2, method = 'euler')
    
    
    G1.v_E = 50 *br.Hz
    G2.v_I = 50 *br.Hz
    
    
    G2.v_E = br.linked_var(G1, 'v_E' )
    G1.v_I = br.linked_var(G2, 'v_I' )


    statemon1 = br.StateMonitor(G1, ['v_I', 'v_E'], record=True)
    #statemon2 = br.StateMonitor(G2, ['dv_I/dt', 'dv_E/dt'], record=True)


    br.run(1000*br.ms)

    
    return statemon1
def test_synapse_connect_ij():
    # connector test 2
    start_scope()
    set_device('exporter', build_on_run=False)
    tau = 10 * ms
    eqn = 'dv/dt = (1 - v)/tau :1'
    my_prob = -1
    Source = NeuronGroup(10, eqn, method='exact', threshold='v>0.9')
    S1 = Synapses(Source, Source)
    nett = Network(Source, S1)
    S1.connect(i=[0, 1], j=[1, 2], p='my_prob')
    nett.run(1 * ms)
    connect2 = device.runs[0]['initializers_connectors'][0]
    assert connect2['i'] == [0, 1]
    assert connect2['j'] == [1, 2]
    assert connect2['identifiers']['my_prob'] == -1
    with pytest.raises(KeyError):
        connect2['condition']
    device.reinit()
Exemple #30
0
def main1():
    #  checking effect of synaptic connectipn
    bs.start_scope()
    n_neurons = 2
    eqs = '''
    dv/dt = (I-v)/tau : 1 (unless refractory)
    I : 1
    tau: second
    '''
    threshold = 'v>1'
    reset = 'v = 0'
    refractory = 10 * bs.ms
    G = bs.NeuronGroup(N=n_neurons,
                       model=eqs,
                       threshold=threshold,
                       reset=reset,
                       method='exact',
                       refractory=refractory)

    G.I = [2, 0]  # represents the I in eqs
    # driving current should be bigger than the threshold, otherwise it wont spike at all

    # I = 0 means that the voltage wont change since there is no driving current
    G.tau = [10, 100] * bs.ms  # represents the tau in eqs
    # unlike last time, the tau is defined with the neuron so we see the effects of different values

    # So in total, what this model says is that whenever two neurons in G are connected by a synapse,
    # when the source neuron fires a spike the target neuron will have its value of v increased by 0.2.
    S = bs.Synapses(source=G, target=G, on_pre='v_post +=  0.2')
    # calling just S.connect() without any parameters just connects every source neuron with every target neuron
    # fully connected
    S.connect(i=0, j=1)
    visualise_connectivity(S)
    state_monitor = bs.StateMonitor(G, 'v', record=True)
    bs.run(100 * bs.ms)

    plt.plot(state_monitor.t / bs.ms, state_monitor.v[0], label='Neuron 0')
    plt.plot(state_monitor.t / bs.ms, state_monitor.v[1], label='Neuron 1')
    plt.xlabel('Time (ms)')
    plt.ylabel('v')
    plt.legend()
    plt.show()
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')