def excitatory_neurons(n_neurons, params): neuron_params = { 'v_thresh_e': params['v_thresh_e'], 'v_reset_e': params['v_reset_e'], 'v_rest': params['v_rest_e'], 'tc_v': params['tc_v_ex'], 'e_ex': params['e_ex_ex'], 'e_in': params['e_in_ex'], 'tc_ge': params['tc_ge'], 'tc_gi': params['tc_gi'], 'tc_theta': params['tc_theta'], 'theta_coef': params['theta_coef'], 'max_theta': params['max_theta'], 'min_theta': params['min_theta'], 'offset': params['offset'] } neurons = b2.NeuronGroup( N=n_neurons, model=eqs.neuron_eqs_e, threshold=eqs.thresh_e, refractory=params['refrac_e'], reset=eqs.reset_e, namespace=neuron_params, method='euler' # automatically suggested by Brian ) neurons.v = params['v_rest_e'] neurons.theta = \ np.ones((n_neurons)) * params['offset'] neurons.theta_mod = np.ones((n_neurons)) return neurons
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
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 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 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)
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 run_brian_sim(stim, dt, init_values, param_dict, method = 'exact'): # Model specification eqs = brian2.Equations("") eqs += brian2.Equations("dV/dt = 1 / C * (Ie(t) + I_0 + I_1 - G * (V - El)) : volt (unless refractory)") eqs += brian2.Equations("dTh_s/dt = -b_s * Th_s : volt (unless refractory)") eqs += brian2.Equations("dTh_v/dt = a_v * (V - El) - b_v * (Th_v - Th_inf) : volt (unless refractory)") eqs += brian2.Equations("dI_0/dt = -k_0 * I_0 : amp (unless refractory)") eqs += brian2.Equations("dI_1/dt = -k_1 * I_1 : amp (unless refractory)") reset = "" reset = "\n".join([reset, "V = a_r * V + b_r"]) reset = "\n".join([reset, "Th_s = Th_s + a_s"]) reset = "\n".join([reset, "Th_v = Th_v"]) reset = "\n".join([reset, "I_0 = R_0 * I_0 * exp(-k_0 * (t_ref - dt)) + A_0"]) reset = "\n".join([reset, "I_1 = R_1 * I_1 * exp(-k_1 * (t_ref - dt)) + A_1"]) threshold = "V > Th_v + Th_s" refractory = param_dict['t_ref'] Ie = brian2.TimedArray(stim, dt=dt) nrn = brian2.NeuronGroup(1, eqs, method=method, reset=reset, threshold=threshold, refractory=refractory, namespace=param_dict) nrn.V = init_values['V'] * brian2.units.volt nrn.Th_s = init_values['Th_s'] * brian2.units.volt nrn.Th_v = init_values['Th_v'] * brian2.units.volt nrn.I_0 = init_values['I_0'] * brian2.units.amp nrn.I_1 = init_values['I_1'] * brian2.units.amp monvars = ['V','Th_s','Th_v','I_0','I_1',] mon = brian2.StateMonitor(nrn, monvars, record=True) num_step = len(stim) brian2.defaultclock.dt = dt brian2.run(num_step * dt) return (mon.t / brian2.units.second, mon.V[0] / brian2.units.volt, mon.Th_s[0] / brian2.units.volt, mon.Th_v[0] / brian2.units.volt, mon.I_0[0] / brian2.units.amp, mon.I_1[0] / brian2.units.amp, )
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 __init__(self, v_rest=-70, v_reset=-65, firing_threshold=-50, membrane_resistance=10, membrane_time_scale=8, abs_refractory_period=2): V_REST = v_rest * bs.mV V_RESET = v_reset * bs.mV FIRING_THRESHOLD = firing_threshold * bs.mV MEMBRANE_RESISTANCE = membrane_resistance * bs.Mohm MEMBRANE_TIME_SCALE = membrane_time_scale * bs.ms ABSOLUTE_REFRACTORY_PERIOD = 2.0 * bs.ms eqs = """ dv/dt = ( -(v-V_REST) + MEMBRANE_RESISTANCE * input_current(t,i) ) / MEMBRANE_TIME_SCALE : volt (unless refractory) """ reset_eq = "v=V_RESET" threshold_eq = "v > FIRING_THRESHOLD" self.neuron = bs.NeuronGroup(1, model=eqs, reset=reset_eq, threshold=threshold_eq, refractory=ABSOLUTE_REFRACTORY_PERIOD, method="linear") self.neuron.v = v_rest
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 simulate_WORM_neuron(input_current, simulation_time=5 * b2.ms, v_leak=V_LEAK, g_leak=G_LEAK, c_m=C_M, rest_pot=R_POT, tau=MEMBRANE_TIME_SCALE, f_t=FIRING_THRESHOLD): # differential equation of neuron model eqs = """ dv/dt = ( g_leak * (v_leak - v) + input_current(t,i) ) / c_m : volt """ # LIF neuron using Brian2 library neuron = b2.NeuronGroup(2, model=eqs, threshold='v>f_t', method="linear") neuron.v = rest_pot # set initial value # monitoring membrane potential of neuron and injecting current state_monitor = b2.StateMonitor(neuron, ["v"], record=True) S = b2.Synapses(neuron, neuron, model='w : volt', on_pre='v += w') S.connect(i=0, j=1) S.w = 0.01 * b2.mV # run the simulation b2.run(simulation_time) return state_monitor
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))
def simulate_LIF_neuron(input_current, simulation_time=5. * b2.ms, dt=0.01, v_rest=-70 * b2.mV, v_reset=-65 * b2.mV, firing_threshold=-50 * b2.mV, membrane_resistance=10. * b2.Mohm, membrane_time_scale=8. * b2.ms, abs_refractory_period=2.0 * b2.ms): b2.defaultclock.dt = dt * b2.ms # differential equation of Leaky Integrate-and-Fire model # eqs = """ # dv/dt = # ( -(v-v_rest) + membrane_resistance * input_current(t,i) ) / membrane_time_scale : volt (unless refractory) # """ eqs = """ dv/dt = ( -(v-v_rest) + membrane_resistance * input_current ) / membrane_time_scale : volt (unless refractory) """ neuron = b2.NeuronGroup(1, model=eqs, reset="v=v_reset", threshold="v>firing_threshold", refractory=abs_refractory_period, method="exact") # "euler" / "exact" neuron.v = v_rest # set initial value network = b2.core.network.Network(neuron) # run before for compiling (JIT compile time out of timing) #network.run(simulation_time, profile=True) spike_monitor = b2.SpikeMonitor(neuron) network.add(spike_monitor) neuron.v = v_rest #start_wallclock = time.time() #start_cpu = time.clock() # timer() network.run(simulation_time, profile=True) #end_cpu = time.clock() # timer() #end_wallclock = time.time() #time_elapsed_wallclock = end_wallclock - start_wallclock #time_elapsed_cpu = end_cpu - start_cpu b2.device.build(directory='output', clean=True, compile=True, run=True, debug=False) print("\n") print("brian2 profiling summary (listed by time consumption):\n") print(b2.profiling_summary()) return spike_monitor, network.get_profiling_info( ) # time_elapsed_wallclock, time_elapsed_cpu,
def set_model(name: str, num_neurons=N_FITS, params=None) -> Tuple[dict, b2.NeuronGroup]: """Create a brian2 model with parameters. :param name: Model name to set :param num_neurons: Number of neurons to set :param params: Optional overwride of parameters if each cell should be unique :return: parameters, and model group """ if not params: params = get_saved_params(name=name) model = get_generic_model() model += "I: amp (constant)\n" group = b2.NeuronGroup(num_neurons, model, method='euler', dt=0.001 * b2.ms) group.v = -50 * b2.mV group.I = 0 * b2.amp # set a control parameter even through not used for param_name, param_value in params.items(): group.__setattr__(param_name, param_value) return params, group
def _make_neuron(self): """Sets the self.neuron attribute.""" # neuron parameters pars = { "g_1": 4.4 * (1 / b2.mV), "g_2": 8 * (1 / b2.mV), "g_L": 2, "V_1": 120 * b2.mV, "V_2": -84 * b2.mV, "V_L": -60 * b2.mV, "phi": 0.06666667, "R": 100 * b2.Gohm, } # forming the neuron model using differential equations eqs = """ I = input_current(t,i) : amp winf = (0.5*mV)*( 1 + tanh((v-12*mV)/(17*mV)) ) : volt tau = (1*ms)/cosh((v-12*mV)/(2*17*mV)) : second m = (0.5*mV)*(1+tanh((v+1.2*mV)/(18*mV))) : volt dv/dt = (-g_1*m*(v-V_1) - g_2*w*(v-V_2) - g_L*(v-V_L) \ + I*R)/(20*ms) : volt dw/dt = phi*(winf-w)/tau : volt """ self.neuron = b2.NeuronGroup(1, eqs, method="euler") self.neuron.v = pars["V_L"] self.neuron.namespace.update(pars)
def brian_poisson(rate, duration_ms, dt=1 * ms, n=1): """ :param rate: :param duration_ms: :param dt: :param n: :return: """ q = b2.units.fundamentalunits.Quantity if not isinstance(rate, q): if np.isscalar(rate): rate = rate * Hz else: rate = np.array(rate) * Hz if not isinstance(duration_ms, q): if np.isscalar(duration_ms): duration_ms = duration_ms * ms else: duration_ms = np.array(duration_ms) * ms neuron = b2.NeuronGroup(n, "rate : Hz", threshold='rand()<rate*dt', dt=dt) neuron.rate = rate spikes = b2.SpikeMonitor(neuron, record=True) b2.run(duration_ms) if n == 1: trains = spikes.spike_trains()[0] / dt else: trains = [train / dt for train in spikes.spike_trains().values()] return trains
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 make_neuron_group(self, n): neuron_pop = b2.NeuronGroup(n, model=self.get_neuron_equations(), namespace=self.get_neuron_parameters(), reset=self.get_reset_statements(), threshold=self.get_threshold_condition(), refractory=self.get_refractory_period()) return neuron_pop
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
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
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
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
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
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
def run(TSTOP=250, group_size=100, g_time=150, neuron_n=1000, linear=True, ext_w=0.2, inh_w=0.2): """Run a simulation and return the resulting spiketrain""" # Basic equation of the model eq = """dv/dt = -gamma*v + I0 : volt Ie : volt Ii : volt """ thetaU = 16 * mV tauM = 8 * ms gamma = 1 / tauM I0 = 17.6 * mV / tauM #Build the group of neuron to use G = br2.NeuronGroup(neuron_n, threshold="v>thetaU", reset="v=0*mV", method='euler', model=eq) #Record the spikes from this group spikes = br2.SpikeMonitor(G) #Build stimulation stim = br2.SpikeGeneratorGroup(1, [0], [g_time]*ms - br2.defaultclock.dt) stim_syn = br2.Synapses(stim, G, on_pre="v += 2*thetaU") stim_syn.connect(i=0, j=np.arange(group_size)) br2.magic_network.schedule = ['start', 'groups', 'synapses', 'thresholds', 'resets', 'end'] connections = np.random.rand(1000, 1000) < 0.3 exc_or_inh = np.random.rand(1000, 1000) < 0.5 exc_i, exc_j = (connections & exc_or_inh).nonzero() inh_i, inh_j = (connections & ~exc_or_inh).nonzero() if linear: G.run_regularly(''' v += Ie + Ii Ie = 0*mV Ii = 0*mV ''', when='after_synapses') else: G.run_regularly(''' v += clip(Ie, 0*mV, 2*mV) + clip(2*(Ie-2*mV), 0*mV, 4*mV) + Ii Ie = 0*mV Ii = 0*mV ''', when='after_synapses') dt = br2.defaultclock.dt exc_syn = br2.Synapses(G, G, on_pre='Ie += %s*mV' % (ext_w), delay=5*ms-dt) inh_syn = br2.Synapses(G, G, on_pre='Ii -= %s*mV' % (inh_w), delay=5*ms-dt) exc_syn.connect(i=exc_i, j=exc_j) inh_syn.connect(i=inh_i, j=inh_j) #Set random initial conditions G.v = np.random.rand(neuron_n) * 16 * mV br2.run(TSTOP * ms) return spikes
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 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
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
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)
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