Ejemplo n.º 1
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()
def collect_and_run(NTWK, verbose=False, INTERMEDIATE_INSTRUCTIONS=[]):
    """
    /!\ When you add a new object, THINK ABOUT ADDING IT TO THE COLLECTION !  /!\
    """
    NTWK['dt'], NTWK['tstop'] = NTWK['Model']['dt'], NTWK['Model']['tstop']
    brian2.defaultclock.dt = NTWK['dt'] * brian2.ms
    net = brian2.Network(brian2.collect())
    OBJECT_LIST = []
    for key in [
            'POPS', 'REC_SYNAPSES', 'RASTER', 'POP_ACT', 'VMS', 'ISYNe',
            'ISYNi', 'GSYNe', 'GSYNi', 'PRE_SPIKES', 'PRE_SYNAPSES'
    ]:
        if key in NTWK.keys():
            net.add(NTWK[key])
    if verbose:
        print('running simulation [...]')

    current_t = 0
    for instrct in INTERMEDIATE_INSTRUCTIONS:
        # we run the simulation until that instruction
        tdur = instrct['time'] - current_t
        net.run(tdur * brian2.ms)
        # execute instruction:
        instrct['function'](NTWK)
        current_t = instrct['time']
    net.run((NTWK['tstop'] - current_t) * brian2.ms)
    if verbose:
        print('-> done !')
    return net
Ejemplo n.º 3
0
def neuron_sim(stim_V=0.8):
    """simulating the neuron using brian2 library"""
    # initiate stimuli timing
    stimulus = br2.TimedArray(
        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, stim_V, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        dt=100 * br2.ms)
    # initiating neurons
    eqs = '''
    dv/dt =  (-v + stimulus(t)-0.1*rand()) / tau  : 1
    tau : second
    '''
    # creating neuron group
    G = br2.NeuronGroup(10, eqs, dt=0.2 * br2.ms)
    # creating different tau's for the neuron model
    G.tau = np.linspace(10, 100, 10) * br2.ms
    # defining state monitor to record voltage
    M = br2.StateMonitor(G, 'v', record=True)
    # creating network
    net = br2.Network(G, M)
    # storing initial state
    net.store()
    # np array to contain data
    data = np.zeros(shape=(10, 10000, 4))
    # producing four repetitions
    for trial in range(4):
        net.restore()  # Restore the initial state
        net.run(2 * br2.second)
        # store the results
        data[:, :, trial] = M.v

    return data
Ejemplo n.º 4
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
Ejemplo n.º 5
0
    def make_classification_network(self, number_of_stimuli, network_name):
        if network_name not in self.networks:
            network_size = number_of_stimuli * self.number_of_neurons
            count_mat = np.zeros((int(self.stimulus_duration / ms * 10), network_size), int)
            target = b2.NeuronGroup(N=number_of_stimuli, model=self.eqs, threshold='v>threshold', reset='v=0',
                                    namespace={'tau': self.tau, 'threshold': self.threshold})
            driving = b2.SpikeGeneratorGroup(N=network_size,
                                             indices=[0], times=[0 * ms])
            # counts = b2.TimedArray(values=_count_mat, dt=b2.defaultclock.dt)
            synapses = b2.Synapses(source=driving, target=target,
                                   model='w: 1', on_pre='v+=w*counts(t, i)')
            i = np.arange(network_size)
            j = np.repeat(range(number_of_stimuli), self.number_of_neurons)
            synapses.connect(j=j, i=i)
            synapses.w = np.tile(self.weights, reps=number_of_stimuli)

            spikes = b2.SpikeMonitor(target, record=True)
            voltage = b2.StateMonitor(target, 'v', record=True)

            net = b2.Network([target, driving, synapses, spikes, voltage])
            net.store()
            self.networks[network_name] = dict(net=net,
                                               count_mat=count_mat,
                                               synapses=synapses,
                                               v_mon=voltage,
                                               spike_mon=spikes,
                                               number_of_stimuli=number_of_stimuli,
                                               driving=driving)
        else:
            self.networks[network_name]['synapses'].w = np.tile(self.weights, reps=number_of_stimuli)
Ejemplo n.º 6
0
 def calculate_input_seqs(self):
     """
     Calculating input sequence based on the video input.
     """
     b2.set_device('cpp_standalone',
                   directory=os.path.join(
                       self.output_folder,
                       'Input_cpp_run' + self.output_file_suffix))
     # inputdt = b2.defaultclock.dt
     spikemons = []
     n0 = len(self.i_patterns[0].T)
     frames = self.frames
     factor = self.factor
     # tmp_group = b2.NeuronGroup(n0, 'rate = frames(t,i)*factor : Hz', threshold='b2.rand()<rate*dt')
     tmp_group = b2.NeuronGroup(n0,
                                'rate = frames(t,i)*factor : Hz',
                                threshold='rand()<rate*dt')
     tmp_network = b2.Network()
     tmp_network.add(tmp_group)
     tmp_mon = b2.SpikeMonitor(tmp_group)
     tmp_network.add(tmp_mon)
     spikemons.append(tmp_mon)
     if self.BaseLine == 0 * second:
         tmp_network.run(self.duration, report='text')
     else:
         tmp_network.run(self.BaseLine)
         tmp_network.run(self.duration - self.BaseLine)
     self.save_input_sequence(
         spikemons,
         os.path.join(self.output_folder,
                      'input' + self.output_file_suffix))
     shutil.rmtree(
         os.path.join(self.output_folder,
                      'Input_cpp_run' + self.output_file_suffix))
Ejemplo n.º 7
0
def simulate_STN_cell(par, par_sim):

    num = par['num']
    input_current = par['i_ext']

    eqs = '''
    I_ext = input_current(t, i): amp 

    minf = 1/(1+exp(-(vs-thetam*mV)/(sigmam*mV))) : 1
    hinf = 1/(1+exp(-(vs-thetah*mV)/(sigmah*mV))) : 1 
    ninf = 1/(1+exp(-(vs-thetan*mV)/(sigman*mV))) : 1
    ainf = 1/(1+exp(-(vs-thetaa*mV)/(sigmaa*mV))) : 1
    binf = 1/(1+exp((r-thetab)/sigmab))-1/(1+exp(-thetab/sigmab)) : 1
    rinf = 1/(1+exp(-(vs-thetar*mV)/(sigmar*mV))) : 1
    sinf = 1/(1+exp(-(vs-thetas*mV)/(sigmas*mV))) : 1
    taun = taun0+taun1/(1+exp(-(vs-thn*mV)/(sigmant*mV))) : second
    tauh = tauh0+tauh1/(1+exp(-(vs-thh*mV)/(sigmaht*mV))) : second
    taur = taur0+taur1/(1+exp(-(vs-thr*mV)/(sigmart*mV))) : second

    il = gl * (vs - vl) : amp
    ina = gna * minf ** 3 * h * (vs - vna) : amp
    ik = gk * n ** 4 * (vs - vk) : amp
    iahp = gahp * ca / (ca + k1) * (vs - vk) : amp 
    ica = gca * sinf ** 2 * (vs - vca) : amp 
    it = gt * ainf ** 3 * binf ** 2 * (vs - vca) : amp 

    dh/dt  = phi * (hinf - h) / tauh  : 1
    dn/dt  = phi * (ninf - n) / taun  : 1
    dr/dt  = phir * (rinf - r) / taur : 1
    dca/dt = eps * ((-ica - it)/pA - kca* ca) : 1    #! pA
    membrane_Im = -(il + ina + ik + it + ica + iahp) + I_ext  : amp
        
    dvs/dt = membrane_Im/C : volt
    '''

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

    neuron.vs = par['v0']
    neuron.h = "hinf"
    neuron.n = "ninf"
    neuron.r = "rinf"
    neuron.ca = 0

    st_mon = b2.StateMonitor(neuron, ["vs", "I_ext"], record=True)

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

    return st_mon
Ejemplo n.º 8
0
    def make_model(self):
        # Determine the simulation
        if self.clamp_type == 'current':
            eqs_input = '''I_inj = inj_input(t) : amp'''

        elif self.clamp_type == 'dynamic':
            eqs_input = '''I_exc = g_exc(t) * (Er_e - v) : amp
                    I_inh = g_inh(t) * (Er_i - v) : amp
                    I_inj = I_exc + I_inh : amp'''
        tracking = ['v', 'I_inj']

        # Model the neuron with differential equations
        eqs = '''
                # Activation gates Na channel
                m = 1. / (1. + exp(-(v - Vh) / k)) : 1
                Vh = 3.223725 * k - 62.615488*mV : volt

                # Inactivation gates Na channel
                dh/dt = 5. * (alpha_h * (1 - h)- beta_h * h) : 1
                alpha_h = 0.07 * exp(-(v + 58.*mV) / (20.*mV))/ms : Hz
                beta_h = 1. / (exp(-0.1/mV * (v + 28.*mV)) + 1.)/ms : Hz

                # Activation gates K channel
                dn/dt = 5. * (alpha_n * (1. - n) - beta_n * n) : 1
                alpha_n = 0.01/mV * 10*mV / exprel(-(v + 34.*mV) / (10.*mV))/ms : Hz
                beta_n = 0.125 * exp(-(v + 44.*mV) / (80.*mV))/ms : Hz

                # Activation gates K3.1 channel
                dn3/dt = alphan3 * (1. - n3) - betan3 * n3 : 1
                alphan3 = (1. / exp(((param * ((-0.029 * v + (1.9*mV))/mV)))))/ms : Hz
                betan3 = (1. / exp(((param * ((0.021 * v + (1.1*mV))/mV)))))/ms : Hz

                # Currents
                I_leak = -gL * (v - EL) : amp
                I_Na = -gNa * m**3 * h * (v - ENa) : amp
                I_K = -gK * n**4 * (v - EK) : amp
                I_K3 = -gK3 * n3**4 * (v - EK) : amp
                dv/dt = (I_leak + I_Na + I_K + I_K3 + I_inj) / Cm : volt
             '''

        # Neuron & parameter initialization
        neuron = b2.NeuronGroup(1,
                                model=eqs + eqs_input,
                                method='exponential_euler',
                                threshold='m > 0.5',
                                refractory=2 * b2.ms,
                                reset=None,
                                dt=self.dt * b2.ms)
        neuron.v = -65 * b2.mV

        # Track the parameters during simulation
        self.M = b2.StateMonitor(neuron, tracking, record=True)
        self.S = b2.SpikeMonitor(neuron, record=True)
        self.neuron = neuron

        net = b2.Network(neuron)
        net.add(self.M, self.S)
        self.network = net
Ejemplo n.º 9
0
    def plot_fi_curve(self,
                      min_current=0 * pA,
                      max_current=1 * nA,
                      step_size=10 * pA,
                      max_rate=None,
                      plot=True):

        # Compute current steps
        steps = np.arange(min_current, max_current, step_size) * amp
        N_steps = len(steps)

        # Prepare params and eqs
        neuron_parameters = self.neuron_parameters
        refractory_period = neuron_parameters['refractory_period']
        eqs = self.get_membrane_equation(substitute_ad_hoc={
            'EXT_CURRENTS': '+ I_ext',
            'EXT_CURRENTS_EQS': 'I_ext : amp'
        })

        # Create a neuron group
        neurons = b2.NeuronGroup(N_steps,
                                 model=eqs,
                                 namespace=neuron_parameters,
                                 reset=self.reset_statements,
                                 threshold=self.threshold_condition,
                                 refractory=refractory_period,
                                 method=self.integration_method)

        # Set initial values
        initial_values = self.get_initial_values()
        neurons.set_states(initial_values)
        neurons.I_ext = 0 * pA

        # Set what to monitor
        #state_monitor = b2.StateMonitor(neurons, self.get_states_to_monitor(), record=True)
        spike_monitor = b2.SpikeMonitor(neurons)

        # Run the simulation
        net = b2.Network(neurons, spike_monitor)
        net.run(500 * ms)

        # Add step current
        neurons.I_ext = steps
        net.run(1000 * ms)

        counts = spike_monitor.count

        # Plot/return the f-I curve
        if plot is True:
            plt.plot(steps / pA, counts)
            plt.title('f-I curve')
            plt.ylabel('Firing rate [Hz]')
            plt.xlabel('Current [pA]')
            if max_rate is not None:
                plt.ylim([0, max_rate])
            plt.show()
        else:
            return counts
Ejemplo n.º 10
0
def simulate_GPe_cell(par_g, par_sim):

    num = par_g['num']
    input_current = par_g['i_ext']
    b2.defaultclock.dt = par_sim['dt']

    eqs = '''
    i_extg = input_current(t, i): amp

    ainfg = 1 / (1 + exp(-(vg - thetaag*mV) / (sigag*mV))) : 1
    sinfg = 1 / (1 + exp(-(vg - thetasg*mV) / (sigsg*mV))) : 1
    rinfg = 1 / (1 + exp(-(vg - thetarg*mV) / (sigrg*mV))) : 1
    minfg = 1 / (1 + exp(-(vg - thetamg*mV) / (sigmg*mV))) : 1
    ninfg = 1 / (1 + exp(-(vg - thetang*mV) / (signg*mV))) : 1
    hinfg = 1 / (1 + exp(-(vg - thetahg*mV) / (sighg*mV))) : 1
    taung = taun0g + taun1g / (1 + exp(-(vg - thngt*mV) / (sng*mV))) : second
    tauhg = tauh0g + tauh1g / (1 + exp(-(vg - thhgt*mV) / (shg*mV))) : second

    itg = gtg * (ainfg ** 3) * rg * (vg - vcag) : amp
    inag = gnag * (minfg ** 3) * hg * (vg - vnag) : amp
    ikg = gkg * (ng ** 4) * (vg - vkg) : amp
    iahpg = gahpg * (vg - vkg) * cag / (cag + k1g) : amp
    icag = gcag * (sinfg ** 2) * (vg - vcag) : amp
    ilg = glg * (vg - vlg) : amp

    membrane_Im =  -(itg + inag + ikg + iahpg + icag + ilg) + i_extg : amp
    dhg/dt = phihg*(hinfg-hg)/tauhg : 1
    dng/dt = phing*(ninfg-ng)/taung : 1
    drg/dt = phig*(rinfg-rg)/taurg  : 1
    dcag/dt= epsg*((-icag-itg)/pA - kcag*cag) : 1  #! pA 

    dvg/dt = membrane_Im / C : volt
    '''

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

    neuron.vg = par_g['v0']
    neuron.hg = "hinfg"
    neuron.ng = "ninfg"
    neuron.rg = "rinfg"
    neuron.cag = 0
    # neuron.i_extg = par_g['iapp']

    st_mon = b2.StateMonitor(neuron, ["vg", 'i_extg'], record=True)

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

    return st_mon
Ejemplo n.º 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
Ejemplo n.º 12
0
def simulate_HH_neuron(I_e, simulation_time):
    """A Hodgkin-Huxley neuron implemented in Brian2.

    Args:
        I_e: Input current injected into the HH neuron
        simulation_time (float): Simulation time [seconds]

    Returns:
        StateMonitor: Brian2 StateMonitor with recorded field "vm"
    """

    # neuron parameters
    El = -59. * b2.mV
    EK = -82. * b2.mV
    ENa = 45. * b2.mV
    gl = 0.3 * b2.msiemens
    gK = 36. * b2.msiemens
    gNa = 120. * b2.msiemens
    C = 1. * b2.ufarad

    # forming HH model with differential equations
    eqs = """
    membrane_Im = I_e + gNa*m**3*h*(ENa-vm) + \
        gl*(El-vm) + gK*n**4*(EK-vm) : amp
    
    alphan = 0.01/mV * (-60.0*mV - vm) / (exp((-60.0*mV - vm) / (10.0*mV)) - 1.0)/ms: Hz
    alpham = (vm + 45.0*mV) / (10.0*mV) / (1.0 - exp(-(vm + 45.0*mV) / (10.0*mV)))/ms : Hz
    alphah = 0.07*exp(-(vm + 70.*mV)/(20.*mV))/ms : Hz
    
    betan = 0.125 * exp(-(vm + 70.0*mV) / (80.0*mV))/ms: Hz
    betam = 4.0 * exp(-(vm + 70.0*mV) / (18.0*mV))/ms: Hz
    betah = 1. / (exp(-(vm + 40.0*mV) / (10.0*mV)) + 1.0)/ms : Hz
    
    dn/dt = alphan*(1-n)-betan*n : 1
    dm/dt = alpham*(1-m)-betam*m : 1
    dh/dt = alphah*(1-h)-betah*h : 1
    
    dvm/dt = membrane_Im/C : volt
    """

    neuron = b2.NeuronGroup(1, eqs, method="exponential_euler")

    # parameter initialization [come from x_inf(v) {x:m,n,h}]
    neuron.vm = -70. * b2.mV
    neuron.m = 0.05
    neuron.h = 0.60
    neuron.n = 0.32

    # tracking parameters
    st_mon = b2.StateMonitor(neuron, "vm", record=True)

    # running the simulation
    hh_net = b2.Network(neuron)
    hh_net.add(st_mon)
    hh_net.run(simulation_time)

    return st_mon
Ejemplo n.º 13
0
def simulate_FSI_cell(par, par_sim):

    pid = os.getpid()
    b2.set_device('cpp_standalone', directory=join(
        "output", f"standalone-{pid}"))
    b2.get_device().reinit()
    b2.get_device().activate(
        directory=join("output", f"standalone-{pid}"))

    num = par['num']
    input_current = par['i_ext']

    eqs = '''
    Iapp = input_current(t, i): amp 

    m_inf = 1.0/(1.0+exp(-(vf+24*mV)/(11.5*mV))):1
    h_inf = 1.0/(1.0+exp(-(vf+58.3*mV)/(-6.7*mV))):1
    n_inf = 1.0/(1.0+exp(-(vf+12.4*mV)/(6.8*mV))):1
    a_inf = 1.0/(1.0+exp(-(vf+50*mV)/(20.*mV))):1
    b_inf = 1.0/(1.0+exp(-(vf+70*mV)/(-6.*mV))):1
    tau_h=0.5*ms+14.0*ms/(1.0+exp(-(vf+60*mV)/(-12.*mV))):second
    tau_n=(0.087*ms+11.4*ms/(1.0+exp(-(vf+14.6*mV)/(-8.6*mV))))
         *(0.087+11.4/(1.0+exp(-(vf-1.3*mV)/(18.7*mV)))) :second

    membrain_Im = -gNa*m_inf**3 *h*(vf-50*mV)
                  -gK*(n**power_n)*(vf+90*mV)
                  -gL*(vf+70*mV)-gA*a**3*b*(vf+90*mV)+Iapp:amp
    dh/dt=(h_inf-h)/tau_h :1
    dn/dt=(n_inf-n)/tau_n :1
    da/dt=(a_inf-a)/(2.*ms) :1
    db/dt=(b_inf-b)/(150.*ms) :1
    dvf/dt=membrain_Im/Cm :volt
    '''

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

    neuron.vf = par['v0']
    neuron.h = "h_inf"
    neuron.n = "n_inf"
    neuron.a = "a_inf"
    neuron.b = "b_inf"

    st_mon = b2.StateMonitor(neuron, ["vf", "Iapp"], record=True)

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

    return st_mon
Ejemplo n.º 14
0
def simulate_HH_neuron(input_current, simulation_time):
    """A Hodgkin-Huxley neuron implemented in Brian2.

    Args:
        input_current (TimedArray): Input current injected into the HH neuron
        simulation_time (float): Simulation time [seconds]

    Returns:
        StateMonitor: Brian2 StateMonitor with recorded fields
        ["vm", "I_e", "m", "n", "h"]
    """

    # neuron parameters
    El = 10.6 * b2.mV
    EK = -12 * b2.mV
    ENa = 115 * b2.mV
    gl = 0.3 * b2.msiemens
    gK = 36 * b2.msiemens
    gNa = 120 * b2.msiemens
    C = 1 * b2.ufarad

    # forming HH model with differential equations
    eqs = """
    I_e = input_current(t,i) : amp
    membrane_Im = I_e + gNa*m**3*h*(ENa-vm) + \
        gl*(El-vm) + gK*n**4*(EK-vm) : amp
    alphah = .07*exp(-.05*vm/mV)/ms    : Hz
    alpham = .1*(25*mV-vm)/(exp(2.5-.1*vm/mV)-1)/mV/ms : Hz
    alphan = .01*(10*mV-vm)/(exp(1-.1*vm/mV)-1)/mV/ms : Hz
    betah = 1./(1+exp(3.-.1*vm/mV))/ms : Hz
    betam = 4*exp(-.0556*vm/mV)/ms : Hz
    betan = .125*exp(-.0125*vm/mV)/ms : Hz
    dh/dt = alphah*(1-h)-betah*h : 1
    dm/dt = alpham*(1-m)-betam*m : 1
    dn/dt = alphan*(1-n)-betan*n : 1
    dvm/dt = membrane_Im/C : volt
    """

    neuron = b2.NeuronGroup(1, eqs, method="exponential_euler")

    # parameter initialization
    neuron.vm = 0
    neuron.m = 0.05
    neuron.h = 0.60
    neuron.n = 0.32

    # tracking parameters
    st_mon = b2.StateMonitor(neuron, ["vm", "I_e", "m", "n", "h"], record=True)

    # running the simulation
    hh_net = b2.Network(neuron)
    hh_net.add(st_mon)
    hh_net.run(simulation_time)

    return st_mon
Ejemplo n.º 15
0
    def set_variables(self, neurons):
        self.add_tag('Brian2_embedding')
        brian2.defaultclock.dt = 1 * ms

        eqs = self.get_init_attr('eqs', '')

        self.G = brian2.NeuronGroup(
            100, eqs, method='euler')  #this is a Biran2 NeuronGroup!
        self.net = brian2.Network(self.G)  #this is a Biran2 Network!

        self.G.v = (np.random.rand(100) + 1) * mV
        self.G.tau = 100 * ms
Ejemplo n.º 16
0
 def clear(self):
     self.recorders = set([])
     self.id_counter = 0
     self.current_sources = []
     self.segment_counter = -1
     if self.network:
         for item in self.network.sorted_objects:
             del item
         del self.network
     self.network = brian2.Network()
     self.network.clock = brian2.Clock(0.1 * ms)
     self.running = False
     self.reset()
Ejemplo n.º 17
0
    def __init__(self, *args):

        def flatten(obj):
            if isinstance(obj, Iterable):
                array = []
                for x in obj:
                    array.extend(flatten(x))
                return array
            else:
                return [obj]

        self.brian_items = [x.brian for x in flatten(list(args))]
        self.brian = b.Network(self.brian_items)
Ejemplo n.º 18
0
    def simulate_neuron(self,
                        I_stim=input_factory.get_zero_current(),
                        simulation_time=1000 * ms,
                        **kwargs):
        """
        Simulate/stimulate the neuron

        :param I_stim: input stimulus (use the input_factory to create the stimulus)
        :param simulation_time: duration (usually in milliseconds, eg. 3000*ms)
        :param kwargs: custom neuron parameters can be given as arguments
        :return: b2.StateMonitor, b2.SpikeMonitor
        """

        neuron_parameters = dict(
            self.neuron_parameters
        )  # Make a copy of parameters; otherwise will change object params
        neuron_parameters.update(kwargs)
        refractory_period = neuron_parameters['refractory_period']

        stim_string = '+ I_stim(t,i)'
        old_model_defns = dict(self.full_model_defns)
        self.add_model_definition('EXT_CURRENTS', stim_string)
        eqs = self.get_membrane_equation()
        self.full_model_defns = old_model_defns

        # Create a neuron group
        neuron = b2.NeuronGroup(1,
                                model=eqs,
                                namespace=neuron_parameters,
                                reset=self.reset_statements,
                                threshold=self.threshold_condition,
                                refractory=refractory_period,
                                method=self.integration_method)

        # Set initial values
        initial_values = self.get_initial_values()
        neuron.set_states(initial_values)

        # Set what to monitor
        state_monitor = b2.StateMonitor(neuron,
                                        self.get_states_to_monitor(),
                                        record=True)
        spike_monitor = b2.SpikeMonitor(neuron)

        # Run the simulation
        net = b2.Network(neuron, state_monitor, spike_monitor)
        net.run(simulation_time)

        return state_monitor, spike_monitor
Ejemplo n.º 19
0
    def __init__(self, xmax, ymax, rmax, dvsSignal):
        self.xmax = xmax
        self.ymax = ymax
        self.rmax = rmax
        #self.rmin = 2
        self.dvsSignal = dvsSignal
        self.v_update = 0.5 * brian2.mvolt

        self.group = snn.snn(self.xmax, self.ymax, self.rmax)
        self.network_op = brian2.NetworkOperation(self.update_func,
                                                  dt=100 * brian2.ms)
        #self.synapses = snn.inhibition(self.group)
        self.spikeM = brian2.SpikeMonitor(self.group)
        self.network = brian2.Network(self.group, self.network_op,
                                      self.spikeM)  #, self.synapses)
Ejemplo n.º 20
0
    def make_model(self):
        # Determine the simulation
        if self.clamp_type == 'current':
            eqs_input = '''I_inj = inj_input(t) : amp'''

        elif self.clamp_type == 'dynamic':
            eqs_input = '''I_exc = g_exc(t) * (Er_e - v) : amp
                    I_inh = g_inh(t) * (Er_i - v) : amp
                    I_inj = I_exc + I_inh : amp'''
        tracking = ['v', 'I_inj']

        # Model the neuron with differential equations
        eqs = '''
            Vh_m = 3.583881 * k_m - 53.294454*mV : volt
            m = 1 / (1 + exp(-(v - Vh_m) / k_m)) : 1
            h = 1 / (1 + exp((v - Vh_h) / k_h)) : 1

            alpha_n = (0.032 * 5. / exprel((15. -v/mV + VT/mV) / 5.))/ms : Hz
            beta_n = (0.5 * exp((10. - v/mV + VT/mV) / 40.))/ms : Hz
            dn/dt = alpha_n * (1 - n) - beta_n * n : 1

            I_leak = -gL * (v - EL) : amp
            I_Na = -gNa * m**3 * h * (v - ENa) : amp
            I_K = -gK * n**4 * (v - EK) : amp

            dv/dt = (I_leak + I_Na + I_K + I_inj) / Cm : volt
            '''

        # Neuron & parameter initialization
        neuron = b2.NeuronGroup(1,
                                model=eqs + eqs_input,
                                method='exponential_euler',
                                threshold='m > 0.5',
                                refractory=2 * b2.ms,
                                reset=None,
                                dt=self.dt * b2.ms)
        neuron.v = -65 * b2.mV

        # Track the parameters during simulation
        self.M = b2.StateMonitor(neuron, tracking, record=True)
        self.S = b2.SpikeMonitor(neuron, record=True)
        self.neuron = neuron

        net = b2.Network(neuron)
        net.add(self.M, self.S)
        self.network = net
def simulate_exponential_IF_neuron(tau=MEMBRANE_TIME_SCALE_tau,
                                   R=MEMBRANE_RESISTANCE_R,
                                   v_rest=V_REST,
                                   v_reset=V_RESET,
                                   v_rheobase=RHEOBASE_THRESHOLD_v_rh,
                                   v_spike=FIRING_THRESHOLD_v_spike,
                                   delta_T=SHARPNESS_delta_T,
                                   I_stim=input_factory.get_zero_current(),
                                   simulation_time=200 * b2.ms):
    """
    Implements the dynamics of the exponential Integrate-and-fire model

    Args:
        tau (Quantity): Membrane time constant
        R (Quantity): Membrane resistance
        v_rest (Quantity): Resting potential
        v_reset (Quantity): Reset value (vm after spike)
        v_rheobase (Quantity): Rheobase threshold
        v_spike (Quantity) : voltage threshold for the spike condition
        delta_T (Quantity): Sharpness of the exponential term
        I_stim (TimedArray): Input current
        simulation_time (Quantity): Duration for which the model is simulated

    Returns:
        (voltage_monitor, spike_monitor):
        A b2.StateMonitor for the variable "v" and a b2.SpikeMonitor
    """

    eqs = """
    dv/dt = (-(v-v_rest) +delta_T*exp((v-v_rheobase)/delta_T)+ R * I_stim(t,i))/(tau) : volt
    """
    neuron = b2.NeuronGroup(1,
                            model=eqs,
                            reset="v=v_reset",
                            threshold="v>v_spike",
                            method="euler")
    neuron.v = v_rest
    # monitoring membrane potential of neuron and injecting current
    voltage_monitor = b2.StateMonitor(neuron, ["v"], record=True)
    spike_monitor = b2.SpikeMonitor(neuron)

    # run the simulation
    net = b2.Network(neuron, voltage_monitor, spike_monitor)
    net.run(simulation_time)

    return voltage_monitor, spike_monitor
def run_simulation(run_params, neurons, connections, monitors, run_id):
    """
    Run the simulation using all the objects created so far.
    """

    net = b2.Network()
    for group in neurons:
        net.add(neurons[group])
    for connection in connections:
        net.add(connections[connection])
    for mon_type in monitors:
        for neuron_group in monitors[mon_type]:
            net.add(monitors[mon_type][neuron_group])

    net.run(run_params['run_time'], report='text')

    return net
Ejemplo n.º 23
0
def collect_and_run(NTWK, verbose=False):
    """
    collecting all the Brian2 objects and running the simulation
    """
    NTWK['dt'], NTWK['tstop'] = NTWK['Model']['dt'], NTWK['Model']['tstop']
    brian2.defaultclock.dt = NTWK['dt'] * brian2.ms
    net = brian2.Network(brian2.collect())
    OBJECT_LIST = []
    for key in [
            'POPS', 'REC_SYNAPSES', 'RASTER', 'POP_ACT', 'VMS', 'PRE_SPIKES',
            'PRE_SYNAPSES'
    ]:
        if key in NTWK.keys():
            net.add(NTWK[key])

    print('running simulation [...]')
    net.run(NTWK['tstop'] * brian2.ms)
    return net
Ejemplo n.º 24
0
    def simulate_neuron(self,
                        I_stim=input_factory.get_zero_current(),
                        simulation_time=1000 * ms,
                        **kwargs):

        neuron_parameters = dict(
            self.neuron_parameters
        )  # Make a copy of parameters; otherwise will change object params
        neuron_parameters.update(kwargs)
        refractory_period = neuron_parameters['refractory_period']

        #eqs = self.get_membrane_equation(substitute_ad_hoc={'EXT_CURRENTS': '+ I_stim(t,i)'})
        stim_string = '+ I_stim(t,i)'
        old_model_defns = dict(self.full_model_defns)
        self.add_model_definition('EXT_CURRENTS', stim_string)
        eqs = self.get_membrane_equation()
        self.full_model_defns = old_model_defns

        # Create a neuron group
        neuron = b2.NeuronGroup(1,
                                model=eqs,
                                namespace=neuron_parameters,
                                reset=self.reset_statements,
                                threshold=self.threshold_condition,
                                refractory=refractory_period,
                                method=self.integration_method)

        # Set initial values
        initial_values = self.get_initial_values()
        neuron.set_states(initial_values)

        # Set what to monitor
        state_monitor = b2.StateMonitor(neuron,
                                        self.get_states_to_monitor(),
                                        record=True)
        spike_monitor = b2.SpikeMonitor(neuron)

        # Run the simulation
        net = b2.Network(neuron, state_monitor, spike_monitor)
        net.run(simulation_time)

        return state_monitor, spike_monitor
Ejemplo n.º 25
0
 def make_plot_network(self):
     count_mat = np.zeros((int(self.stimulus_duration / ms * 10), self.number_of_neurons), int)
     target = b2.NeuronGroup(N=1, model=self.eqs, threshold='v>threshold', reset='v=0',
                             namespace={'tau': self.tau, 'threshold': self.threshold})
     driving = b2.SpikeGeneratorGroup(N=self.number_of_neurons,
                                      indices=[0], times=[0 * ms])
     synapses = b2.Synapses(source=driving, target=target,
                            model='w: 1', on_pre='v+=w*counts(t, i)')
     synapses.connect(i=range(number_of_neurons), j=[0] * number_of_neurons)
     synapses.w = self.weights
     spikes = b2.SpikeMonitor(target, record=True)
     voltage = b2.StateMonitor(target, 'v', record=True)
     net = b2.Network([target, driving, synapses, spikes, voltage])
     net.store()
     self.networks['plot'] = dict(net=net,
                                  synapses=synapses,
                                  count_mat=count_mat,
                                  v_mon=voltage,
                                  spike_mon=spikes,
                                  driving=driving)
Ejemplo n.º 26
0
    def collect_brian2_network(self, *more_objects: b2.BrianObject):
        for net in b2.Network.__instances__():
            if self.ref == net().name:
                logger.warning(
                    'before recollecting the same network, you need to call reset_lazyness to clean up'
                )
                break

        net = b2.Network(*more_objects, name=self.ref)

        for p in self.populations:
            net.add(p.brian2)

            for i in p.inputs:
                net.add(i.brian2)

            for n in p.noises:
                net.add(n.brian2)

        return net
def simulate(tau):
    # These two lines are needed to start a new standalone simulation:
    b2.device.reinit()
    b2.device.activate()

    eqs = '''
    dv/dt = -v/tau : 1
    '''

    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, G, S, M])

    net.run(1000 * b2.ms)

    return M
Ejemplo n.º 28
0
 def make_train_network(self, batch_size, network_name):
     if network_name not in self.networks:
         network_size = batch_size * self.number_of_neurons
         target = b2.NeuronGroup(N=network_size, model=self.eqs,
                                 namespace={'tau': self.tau})
         driving = b2.SpikeGeneratorGroup(N=network_size,
                                          indices=[0], times=[0 * ms])
         count_mat = np.zeros((int(self.stimulus_duration / ms * 10), network_size), int)
         synapses = b2.Synapses(driving, target, 'w: 1', on_pre='v+=1*counts(t, i)')
         synapses.connect(condition='i==j')
         synapses.w = np.tile(self.weights, reps=batch_size)
         voltage = b2.StateMonitor(target, 'v', record=True)
         net = b2.Network([target, driving, synapses, voltage])
         net.store()
         self.networks[network_name] = dict(net=net,
                                            count_mat=count_mat,
                                            synapses=synapses,
                                            v_mon=voltage,
                                            number_of_stimuli=batch_size,
                                            driving=driving)
     else:
         self.networks[network_name]['synapses'].w = np.tile(self.weights, reps=batch_size)
Ejemplo n.º 29
0
def network_sim():
    # this line resets Brian's object tracking system, without it, the simulation will crash when run a second time
    # bb.core.tracking.InstanceFollower.instance_sets = defaultdict(bb.core.tracking.InstanceTrackerSet)
    bb.start_scope()
    if faster_run:
        bb.get_device().reinit()
        bb.get_device().activate(build_on_run=False,
                                 directory='PETH_standalone')

    network = bb.Network()
    Pe = bb.NeuronGroup(20000,
                        eqs_exc,
                        threshold='v > -50 * mV',
                        reset='v = -60 * mV',
                        refractory=2. * ms,
                        method='euler',
                        namespace=params)
    # Pi = bb.NeuronGroup(5000, eqs_inh, threshold='v > -50 * mV',
    #                          reset='v = -60 * mV', refractory=2. * ms, method='euler',
    #                          namespace=params)
    C_ee = bb.Synapses(Pe, Pe, model='w:siemens', on_pre='ge+=w')
    #C_ie = bb.Synapses(Pe, Pi, model='w:siemens', on_pre='ge+=w')

    i = np.random.randint(20000)
    j = np.random.randint(20000)
    C_ee.connect(i=i, j=j)
    C_ee.w = params['g_ee']
    network.add(Pe)
    network.add(C_ee)
    network.run(1 * second)

    if faster_run:
        bb.get_device().build(directory='PETH_standalone',
                              compile=True,
                              run=True,
                              debug=False)

    return network
Ejemplo n.º 30
0
def simulate(runtime=0.5*b2.second, N=1):
    b2.start_scope()

    namespace['sigma'] = 2 * b2.mV
    namespace['tau_m_E'] = namespace['C_m_E'] / namespace['g_m_E']
    # I_1 = -2*b2.namp
    # I_2 = -20*b2.namp
    I_1 = namespace['g_m_E'] * (namespace['V_L'] - (2.5*b2.mV + namespace['V_thr']))
    I_2 = namespace['g_m_E'] * (namespace['V_L'] - (-2.5*b2.mV + namespace['V_thr']))

    eqn = """
    dV/dt = (- g_m_E * (V - V_L) - I) / C_m_E + sigma*xi*tau_m_E**-0.5: volt (unless refractory)
    I : amp
    """
    N1 = b2.NeuronGroup(
        N, eqn, threshold='V>V_thr',
        reset='V = V_reset',
        refractory=namespace['tau_rp_E'],
        method='euler')
    N1.V = namespace['V_reset']
    N1.I = I_1

    N2 = b2.NeuronGroup(
        N, eqn, threshold='V>V_thr',
        reset='V = V_reset',
        refractory=namespace['tau_rp_E'],
        method='euler')
    N2.V = namespace['V_reset']
    N2.I = I_2
    
    st1 = b2.StateMonitor(N1, variables='V', record=True, name='st1')
    st2 = b2.StateMonitor(N2, variables='V', record=True, name='st2')
    sp1 = b2.SpikeMonitor(N1, name='sp1')
    sp2 = b2.SpikeMonitor(N2, name='sp2')

    net = b2.Network(b2.collect())
    net.run(runtime, namespace=namespace, report='stdout')
    return net