def _build_model(self, traj, brian_list, network_dict): """Builds the neuron groups from `traj`. Adds the neuron groups to `brian_list` and `network_dict`. """ model = traj.parameters.model # Create the equations for both models eqs_dict = self._build_model_eqs(traj) # Create inhibitory neurons eqs_i = eqs_dict['i'] neurons_i = NeuronGroup(N=model.N_i, model=eqs_i, threshold=model.V_th, reset=model.reset_func, refractory=model.refractory, freeze=True, compile=True, method='Euler') # Create excitatory neurons eqs_e = eqs_dict['e'] neurons_e = NeuronGroup(N=model.N_e, model=eqs_e, threshold=model.V_th, reset=model.reset_func, refractory=model.refractory, freeze=True, compile=True, method='Euler') # Set the bias terms neurons_e.mu = rand( model.N_e) * (model.mu_e_max - model.mu_e_min) + model.mu_e_min neurons_i.mu = rand( model.N_i) * (model.mu_i_max - model.mu_i_min) + model.mu_i_min # Set initial membrane potentials neurons_e.V = rand(model.N_e) neurons_i.V = rand(model.N_i) # Add both groups to the `brian_list` and the `network_dict` brian_list.append(neurons_i) brian_list.append(neurons_e) network_dict['neurons_e'] = neurons_e network_dict['neurons_i'] = neurons_i
def initialize_neurongroup(self): # Add 'refractory' parameter on the CPU only if not self.use_gpu: if self.max_refractory is not None: refractory = 'refractory' self.model.add_param('refractory', second) else: refractory = self.refractory else: if self.max_refractory is not None: refractory = 0 * ms else: refractory = self.refractory # Must recompile the Equations : the functions are not transfered after pickling/unpickling self.model.compile_functions() self.group = NeuronGroup(self.neurons, model=self.model, reset=self.reset, threshold=self.threshold, refractory=refractory, max_refractory=self.max_refractory, method=self.method, clock=Clock(dt=self.dt)) if self.initial_values is not None: for param, value in self.initial_values.iteritems(): self.group.state(param)[:] = value
def generate_data(): g = NeuronGroup(1, model=equations, reset=0, threshold=1) g.I = TimedArray(input, dt=.1 * ms) g.tau = 25 * ms g.R = 3e9 SpM = SpikeMonitor(g) StM = StateMonitor(g, 'V', record=True) net = Network(g, SpM, StM) net.run(1 * second) return StM.values[0], SpM.spikes
def build(self, traj, brian_list, network_dict): if not self.pre_built: eqs = Equations(traj.model, tau=traj.tau) ng = NeuronGroup(traj.N, eqs, threshold=traj.threshold, reset=traj.reset, refractory=traj.refr) ng.v0 = traj.v00 brian_list.append(ng) network_dict['group'] = ng
def fun(sigma, args): """ This function computes the mean firing rate of a LIF neuron with white noise input current (OU process with threshold). """ if not isscalar(sigma): raise Exception('sigma must be a scalar') N = args['N'] tau = args['tau'] model = args['model'] reset = args['reset'] threshold = args['threshold'] duration = args['duration'] G = NeuronGroup(N, model=model, reset=reset, threshold=threshold) M = SpikeCounter(G) net = Network(G, M) net.run(duration) r = M.nspikes * 1.0 / N return r
def test_stim_pyramidal_impact(): simulation_clock = Clock(dt=.5 * ms) trial_duration = 1 * second dcs_start_time = .5 * second stim_levels = [-8, -6, -4, -2, -1, -.5, -.25, 0, .25, .5, 1, 2, 4, 6, 8] voltages = np.zeros(len(stim_levels)) for idx, stim_level in enumerate(stim_levels): print('testing stim_level %.3fpA' % stim_level) eqs = exp_IF(default_params.C, default_params.gL, default_params.EL, default_params.VT, default_params.DeltaT) # AMPA conductance - recurrent input current eqs += exp_synapse('g_ampa_r', default_params.tau_ampa, siemens) eqs += Current('I_ampa_r=g_ampa_r*(E-vm): amp', E=default_params.E_ampa) # AMPA conductance - background input current eqs += exp_synapse('g_ampa_b', default_params.tau_ampa, siemens) eqs += Current('I_ampa_b=g_ampa_b*(E-vm): amp', E=default_params.E_ampa) # AMPA conductance - task input current eqs += exp_synapse('g_ampa_x', default_params.tau_ampa, siemens) eqs += Current('I_ampa_x=g_ampa_x*(E-vm): amp', E=default_params.E_ampa) # Voltage-dependent NMDA conductance eqs += biexp_synapse('g_nmda', default_params.tau1_nmda, default_params.tau2_nmda, siemens) eqs += Equations('g_V = 1/(1+(Mg/3.57)*exp(-0.062 *vm/mV)) : 1 ', Mg=default_params.Mg) eqs += Current('I_nmda=g_V*g_nmda*(E-vm): amp', E=default_params.E_nmda) # GABA-A conductance eqs += exp_synapse('g_gaba_a', default_params.tau_gaba_a, siemens) eqs += Current('I_gaba_a=g_gaba_a*(E-vm): amp', E=default_params.E_gaba_a) eqs += InjectedCurrent('I_dcs: amp') group = NeuronGroup(1, model=eqs, threshold=-20 * mV, refractory=pyr_params.refractory, reset=default_params.Vr, compile=True, freeze=True, clock=simulation_clock) group.C = pyr_params.C group.gL = pyr_params.gL @network_operation(clock=simulation_clock) def inject_current(c): if simulation_clock.t > dcs_start_time: group.I_dcs = stim_level * pA monitor = StateMonitor(group, 'vm', simulation_clock, record=True) net = Network(group, monitor, inject_current) net.run(trial_duration, report='text') voltages[idx] = monitor.values[0, -1] * 1000 voltages = voltages - voltages[7] plt.figure() plt.plot(stim_levels, voltages) plt.xlabel('Stimulation level (pA)') plt.ylabel('Voltage Change (mV)') plt.show()
def runsim(neuron_model, # sim params dt, simtime, prerun, monitors, recvars, # stimulation params fstim, r0_bg, r0_stim, stim_starts, stim_stops, stim_odors, stim_amps, stim_start_var, # network params beeid, N_glu, N_KC, ORNperGlu, PNperKC, PN_I0, LN_I0, # network weights wi, wORNLN, wORNPN, wPNKC, # default params V0min, inh_struct=None, Winh=None, timestep=500, report=None): np.random.seed() #needed for numpy/brian when runing parallel sims define_default_clock(dt=dt) inh_on_off = 0 if (wi == 0) or (wi is None) or (wORNLN is None) else 1 ######################### NEURONGROUPS ######################### NG = dict() # ORN Input # For each glumerolus, random temporal response jitter can be added. # The jitter is added to the response onset. Maximum jitter is given by stim_start_var. # stim_start_jittered is a vector containing the jittered stim start tims # orn_activation returns a booolean vector of stim presence given time t # Total ORN rate: Baseline componenent equal for all units, # and individual activationa. jitter = np.random.uniform(0,stim_start_var,N_glu) stim_tun = lambda odorN: fstim(N_glu=N_glu, odorN=odorN) * r0_stim orn_activation = lambda t: np.sum([ a*stim_tun(odorN=o)*np.logical_and(np.greater(t,prerun+stim_start+jitter), np.less(t,prerun+stim_stop)) for stim_start,stim_stop,o,a in zip(stim_starts, stim_stops, stim_odors, stim_amps)], 0) orn_rates = lambda t: np.repeat(r0_bg + orn_activation(t),repeats = ORNperGlu) NG['ORN'] = PoissonGroup(ORNperGlu*N_glu, rates=orn_rates) NG['PN'] = NeuronGroup(N_glu, **neuron_model) NG['LN'] = NeuronGroup(N_glu*inh_on_off, **neuron_model) if 'KC' in monitors: NG['KC'] = NeuronGroup(N_KC, **neuron_model) ######################### CONNECTIONS ######################### c = dict() c['ORNPN'] = Connection(NG['ORN'],NG['PN'],'ge') for i in np.arange(N_glu): c['ORNPN'].connect_full(NG['ORN'].subgroup(ORNperGlu),NG['PN'][i],weight=wORNPN) if inh_on_off: print('-- inhibiting --',wi) c['ORNLN'] = Connection(NG['ORN'],NG['LN'],'ge') c['LNPN'] = Connection(NG['LN'],NG['PN'],'gi',weight=(wi*35)/N_glu) for i in np.arange(N_glu): c['ORNLN'].connect_full(NG['ORN'][ i*ORNperGlu : (i+1)*ORNperGlu ], NG['LN'][i], weight = wORNLN) if inh_struct: c['LNPN'].connect(NG['LN'],NG['PN'],Winh) if 'KC' in monitors: c['KC'] = Connection(NG['PN'],NG['KC'],'ge') c['KC'].connect_random(NG['PN'],NG['KC'],p=PNperKC/float(N_glu),weight=wPNKC,seed=beeid) ######################### INITIAL VALUES ######################### VT = neuron_model['threshold'] NG['PN'].vm = np.random.uniform(V0min,VT,size=len(NG['PN'])) if inh_on_off: NG['LN'].vm= np.random.uniform(V0min,VT,size=len(NG['LN'])) if 'KC' in monitors: NG['KC'].vm= np.random.uniform(V0min,VT,size=len(NG['KC'])) net = Network(NG.values(), c.values()) #### Compensation currents ### NG['PN'].I0 = PN_I0 NG['LN'].I0 = LN_I0 ########################################################################## ######################### PRE-RUN ######################### net.run(prerun) ######################### MONITORS ######################### spmons = [SpikeMonitor(NG[mon], record=True) for mon in monitors] net.add(spmons) if len(recvars) > 0: mons = [MultiStateMonitor(NG[mon], vars=recvars, record=True, timestep=timestep) for mon in monitors] net.add(mons) else: mons = None ######################### RUN ######################### net = run(simtime, report=report) out_spikes = dict( (monitors[i],np.array(sm.spikes)) for i,sm in enumerate(spmons) ) if mons is not None: out_mons = dict( (mon,dict((var,statemon.values) for var,statemon in m.iteritems())) for mon,m in zip(monitors,mons)) else: out_mons = None #subtract the prerun from spike times, if there are any for spikes in out_spikes.itervalues(): if len(spikes) != 0: spikes[:,1] -= prerun return out_spikes, out_mons
def run_simulation(realizations=1, trials=1, t=3000 * ms, alpha=1, ree=1, k=50, winlen = 50 * ms, verbose=True, t_stim = 0): """ Run the whole simulation with the specified parameters. All model parameter are set in the function. Keyword arguments: :param realizations: number of repititions of the whole simulation, number of network instances :param trials: number of trials for network instance :param t: simulation time :param alpha: scaling factor for number of neurons in the network :param ree: clustering coefficient :param k: number of clusters :param t_stim : duration of stimulation of a subset of clusters :param winlen: length of window in ms :param verbose: plotting flag :return: numpy matrices with spike times """ # The equations defining our neuron model eqs_string = ''' dV/dt = (mu - V)/tau + x: volt dx/dt = -1.0/tau_2*(x - y/tau_1) : volt/second dy/dt = -y/tau_1 : volt mu : volt tau: second tau_2: second tau_1: second ''' # Model parameters n_e = int(4000 * alpha) # number of exc neurons n_i = int(1000 * alpha) # number of inh neurons tau_e = 15 * ms # membrane time constant (for excitatory synapses) tau_i = 10 * ms # membrane time constant (for inhibitory synapses) tau_syn_2_e = 3 * ms # exc synaptic time constant tau2 in paper tau_syn_2_i = 2 * ms # inh synaptic time constant tau2 in paper tau_syn_1 = 1 * ms # exc/inh synaptic time constant tau1 in paper vt = -50 * mV # firing threshold vr = -65 * mV # reset potential dv = vt - vr # delta v refrac = 5 * ms # absolute refractory period # scale the weights to ensure same variance in the inputs wee = 0.024 * dv * np.sqrt(1. / alpha) wie = 0.014 * dv * np.sqrt(1. / alpha) wii = -0.057 * dv * np.sqrt(1. / alpha) wei = -0.045 * dv * np.sqrt(1. / alpha) # Connection probability p_ee = 0.2 p_ii = 0.5 p_ie = 0.5 p_ei = 0.5 # determine probs for inside and outside of clusters p_in, p_out = get_cluster_connection_probs(ree, k, p_ee) mu_min_e, mu_max_e = 1.1, 1.2 mu_min_i, mu_max_i = 1.0, 1.05 # increase cluster weights if there are clusters wee_cluster = wee if p_in == p_out else 1.9 * wee # define numpy array for data storing all_data = np.zeros((realizations, trials, n_e+n_i, int(t/winlen)//2)) for realization in range(realizations): # clear workspace to make sure that is a new realization of the network clear(True, True) reinit() # set up new random bias parameter for every type of neuron mu_e = vr + np.random.uniform(mu_min_e, mu_max_e, n_e) * dv # bias for excitatory neurons mu_i = vr + np.random.uniform(mu_min_i, mu_max_i, n_i) * dv # bias for excitatory neurons # Let's create an equation object from our string and parameters model_eqs = Equations(eqs_string) # Let's create 5000 neurons all_neurons = NeuronGroup(N=n_e + n_i, model=model_eqs, threshold=vt, reset=vr, refractory=refrac, freeze=True, method='Euler', compile=True) # Divide the neurons into excitatory and inhibitory ones neurons_e = all_neurons[0:n_e] neurons_i = all_neurons[n_e:n_e + n_i] # set the bias neurons_e.mu = mu_e neurons_i.mu = mu_i neurons_e.tau = tau_e neurons_i.tau = tau_i neurons_e.tau_2 = tau_syn_2_e neurons_i.tau_2 = tau_syn_2_i all_neurons.tau_1 = tau_syn_1 # set up connections connections = Connection(all_neurons, all_neurons, 'y') # do the cluster connection like cross validation: cluster neuron := test idx; other neurons := train idx kf = KFold(n=n_e, n_folds=k) for idx_out, idx_in in kf: # idx_out holds all other neurons; idx_in holds all cluster neurons # connect current cluster to itself connections.connect_random(all_neurons[idx_in[0]:idx_in[-1]], all_neurons[idx_in[0]:idx_in[-1]], sparseness=p_in, weight=wee_cluster) # connect current cluster to other neurons connections.connect_random(all_neurons[idx_in[0]:idx_in[-1]], all_neurons[idx_out[0]:idx_out[-1]], sparseness=p_out, weight=wee) # connect all excitatory to all inhibitory, irrespective of clustering connections.connect_random(all_neurons[0:n_e], all_neurons[n_e:(n_e + n_i)], sparseness=p_ie, weight=wie) # connect all inhibitory to all excitatory connections.connect_random(all_neurons[n_e:(n_e + n_i)], all_neurons[0:n_e], sparseness=p_ei, weight=wei) # connect all inhibitory to all inhibitory connections.connect_random(all_neurons[n_e:(n_e + n_i)], all_neurons[n_e:(n_e + n_i)], sparseness=p_ii, weight=wii) # set up spike monitors spike_mon_e = SpikeMonitor(neurons_e) spike_mon_i = SpikeMonitor(neurons_i) # set up network with monitors network = Network(all_neurons, connections, spike_mon_e, spike_mon_i) # run this network for some number of trials, every time with for trial in range(trials): # different initial values all_neurons.V = vr + (vt - vr) * np.random.rand(len(all_neurons)) * 1.4 # Calibration phase # run for the first half of the time to let the neurons adapt network.run(t/2) # reset monitors to start recording phase spike_mon_i.reinit() spike_mon_e.reinit() # stimulation if duration is given # define index variable for the stimulation possibility (is 0 for stimulation time=0) t_stim_idx = int(t_stim / (winlen/ms)) if not(t_stim==0): # Stimulation phase, increase input to subset of clusters all_neurons[:400].mu += 0.07 * dv network.run(t_stim * ms, report='text') # set back to normal all_neurons[:400].mu -= 0.07 * dv # save data all_data[realization, trial, :n_e, :t_stim_idx] = spikes_counter(spike_mon_e, winlen) all_data[realization, trial, n_e:, :t_stim_idx] = spikes_counter(spike_mon_i, winlen) # reset monitors spike_mon_e.reinit() spike_mon_i.reinit() # run the remaining time of the simulation network.run((t/2) - t_stim*ms, report='text') # save results all_data[realization, trial, :n_e, t_stim_idx:] = spikes_counter(spike_mon_e, winlen) all_data[realization, trial, n_e:, t_stim_idx:] = spikes_counter(spike_mon_i, winlen) if verbose: plt.ion() plt.figure() raster_plot(spike_mon_e) plt.title('Excitatory neurons') spike_mon_e.reinit() spike_mon_i.reinit() return all_data
from brian import log_level_debug log_level_debug() set_global_preferences(useweave=True,usecodegen=True,usecodegenweave=True,usenewpropagate=True,usecstdp=True) from matplotlib.pyplot import plot, show, subplot params = {} params["t_Nr"] = 2*ms params["t_Nf"] = 80*ms params["t_AMPA"] = 5*ms simclock = Clock(dt=0.01*ms) input=NeuronGroup(2,model='dv/dt=1/(10*ms):1', threshold=1, reset=0,clock=simclock) neurons = NeuronGroup(1, model="""dv/dt=(NMDAo+AMPAo-v)/(10*ms) : 1 NMDAo : 1 AMPAo : 1""", freeze = True,clock=simclock) ampadyn = ''' dAMPAoS/dt = -AMPAoS/t_AMPA : 1 AMPAi = AMPAoS AMPAo = AMPAoS / (t_AMPA /msecond) : 1 ''' nmdadyn = ''' dNMDAoS/dt = (1/t_Nr)*(Nnor*NMDAi-NMDAoS) : 1 dNMDAi/dt = -(1/t_Nf)*NMDAi : 1 Nnor = (t_Nf/t_Nr)**((t_Nr)/(t_Nf - t_Nr)) : 1 Nscal = (t_Nf/msecond)**(t_Nf/(t_Nf - t_Nr))/(t_Nr/msecond)**(t_Nr/(t_Nf - t_Nr)) : 1