def _create_devices(self, group): """Create a Brian recording device.""" clock = simulator.state.simclock if self.variable == 'spikes': devices = [brian.SpikeMonitor(group, record=self.recorded)] elif self.variable == 'v': devices = [ brian.StateMonitor(group, 'v', record=True, clock=clock) ] elif self.variable == 'gsyn': example_cell = list(self.recorded)[0] varname = example_cell.celltype.synapses['excitatory'] device1 = brian.StateMonitor(group, varname, record=True, clock=clock) varname = example_cell.celltype.synapses['inhibitory'] device2 = brian.StateMonitor(group, varname, record=True, clock=clock) devices = [device1, device2] else: devices = [ brian.StateMonitor(group, self.variable, record=self.recorded, clock=clock) ] for device in devices: simulator.state.add(device) return devices
def test_yang2009(): tmax = 0.1 ts = np.arange(0, tmax, 10e-3) ws = _double_exp_recovery_synapse(ts=ts, k=0.6, U=0.47, tau_fast=26e-3, tau_slow=1) anf_trains = pd.DataFrame([ { 'cf': 100, 'duration': tmax, 'spikes': ts, 'type': 'hsr' }, { 'cf': 100, 'duration': tmax, 'spikes': ts + 2e-3, 'type': 'hsr' }, ]) anfs = cn.ANFs(anf_trains) gbcs = cn.GBCs_RothmanManis2003(cfs=[100], convergences=(2, 0, 0), endbulb_class='yang2009') gbcs.connect_anfs(anfs, weights=(1, 0, 0)) for obj in gbcs.brian_objects: if isinstance(obj, brian.Synapses): synapses = obj g_syn = brian.StateMonitor( synapses, 'g_syn', record=[1] # `1' because the 2nd synapse # (index=1) gets the first ANF while # (randomly) connection ANF ) g_syn_tot = brian.StateMonitor(gbcs.group, 'g_syn_tot', record=True) net = brian.Network(gbcs.brian_objects, anfs.brian_objects, g_syn, g_syn_tot) net.run(tmax * second, report='text', report_period=1) g_syn_interp = interpolate.interp1d(g_syn.times, g_syn.values[0]) g_syn_tot_interp = interpolate.interp1d(g_syn_tot.times, g_syn_tot.values[0]) npt.assert_array_almost_equal(g_syn_interp(ts), ws) npt.assert_array_almost_equal(g_syn_tot_interp(ts), ws)
def record(self): self.i_state_monitor = brian.StateMonitor( self.cell_list[0].parent.brian_group[self.indices[0]], 'i_inj', record=0, when='start') simulator.state.network.add(self.i_state_monitor)
def _create_devices(self, group): """Create a Brian recording device.""" # By default, StateMonitor has when='end', i.e. the value recorded at # the end of the timestep is associated with the time at the start of the step, # This is different to the PyNN semantics (i.e. the value at the end of # the step is associated with the time at the end of the step.) clock = simulator.state.simclock if self.variable == 'spikes': devices = [brian.SpikeMonitor(group, record=True)] elif self.variable == 'v': devices = [ brian.StateMonitor(group, 'v', record=True, clock=clock, when='start') ] elif self.variable == 'gsyn': example_cell = list(self.recorded)[0] varname = example_cell.celltype.synapses['excitatory'] device1 = brian.StateMonitor(group, varname, record=True, clock=clock, when='start') varname = example_cell.celltype.synapses['inhibitory'] device2 = brian.StateMonitor(group, varname, record=True, clock=clock, when='start') devices = [device1, device2] else: devices = [ brian.StateMonitor(group, self.variable, record=True, clock=clock, when='start') ] for device in devices: simulator.state.add(device) return devices
def main(): tmax = 50e-3 # second cn.set_fs(40e3) # Hz # anf_trains are normally generated by something like # cochlea.run_zilany2009() anf_trains = pd.DataFrame([ {'spikes': np.array([10e-3, 30e-3]), 'duration': tmax}, {'spikes': np.array([20e-3, 40e-3]), 'duration': tmax}, ]) # Generate ANF and GBC groups anfs = cn.make_anf_group(anf_trains) gbcs = cn.make_gbc_group(10) # Connect ANFs and GBCs synapses = brian.Connection( anfs, gbcs, 'ge_syn', ) synapses.connect_random( anfs, gbcs, p=0.5, fixed=True, weight=1e-6*siemens ) # Monitors for the GBCs spikes = brian.SpikeMonitor(gbcs) voltages = brian.StateMonitor(gbcs, 'vm', record=True) # Run the simulation cn.run( duration=tmax, objects=[anfs, gbcs, synapses, spikes, voltages] ) # Present the results print(spikes.spikes) fig, ax = plt.subplots(2,1) plt.sca(ax[0]) brian.raster_plot(spikes) plt.sca(ax[1]) voltages.plot() plt.show()
def _create_device(self, group, variable): """Create a Brian recording device.""" # By default, StateMonitor has when='end', i.e. the value recorded at # the end of the timestep is associated with the time at the start of the step, # This is different to the PyNN semantics (i.e. the value at the end of # the step is associated with the time at the end of the step.) clock = simulator.state.network.clock if variable == 'spikes': self._devices[variable] = brian.SpikeMonitor(group, record=self.recorded) else: varname = self.population.celltype.state_variable_translations[variable]['translated_name'] self._devices[variable] = brian.StateMonitor(group, varname, record=self.recorded, clock=clock, when='start', timestep=int(round(self.sampling_interval/simulator.state.dt))) simulator.state.network.add(self._devices[variable])
def _create_device(self, group, variable): """Create a Brian recording device.""" # By default, StateMonitor has when='end', i.e. the value recorded at # the end of the timestep is associated with the time at the start of the step, # This is different to the PyNN semantics (i.e. the value at the end of # the step is associated with the time at the end of the step.) clock = simulator.state.simclock if variable == 'spikes': self._devices[variable] = brian.SpikeMonitor(group, record=self.recorded) else: if variable == 'v': varname = 'v' elif variable == 'gsyn_exc': varname = self.population.celltype.synapses['excitatory'] elif variable == 'gsyn_inh': varname = self.population.celltype.synapses['inhibitory'] self._devices[variable] = brian.StateMonitor(group, varname, record=self.recorded, clock=clock, when='start') simulator.state.add(self._devices[variable])
#eq1+=brian.Equations('g_ch : 1') #uncomment this to make it work eq1+=brian.Equations('dc0/dt=-1 :volt') eq1+=brian.Equations('gmax :1') g1=brian.NeuronGroup(1, model=eq1) eq2=brian.Equations('dv/dt=-v+gch*(erev-v): volt') eq2+=brian.Equations('erev :1') eq2+=brian.Equations('gch :1') g2=brian.NeuronGroup(1, model=eq2) #g1.g_ch = brian.linked_var(g1, 'g') #uncomment this to make it work g2.gch = brian.linked_var(g1, 'g') #comment this to make it work #g2.gch = brian.linked_var(g1, 'g_ch') #uncomment this to make it work s1=brian.StateMonitor(g1, 'g', record=0) s2=brian.StateMonitor(g1, 'c0', record=0) s3=brian.StateMonitor(g2, 'v', record=0) s4=brian.StateMonitor(g2, 'gch', record=0) s5=brian.StateMonitor(g1, 'gmax', record=0) #initialize g1.g=0.0 #commenting this ALONE will make it work #g1.g_ch=0.0 #uncomment this to make it work g1.gmax=2.0 g2.erev=2.0 n=brian.Network() n.add(g1)
def run_sim(ffExcInputMult=None, ffInhInputMult=None): """Run the cond-based LIF neuron simulation. Takes a few minutes to construct network and run Parameters ---------- ffExcInputMult: scalar: FF input magnitude to E cells. multiply ffInputV by this value and connect to E cells ffInhInputMult: scalar: FF input magnitude to I cells. Returns ------- outDict - spike times, records of continuous values from simulation """ # use helper to get input timecourses (ffInputV, condAddV) = create_input_vectors( doDebugPlot=False) # multiplied by scalars below # setup initial state stT = time.time() brian.set_global_preferences(usecodegen=True) brian.set_global_preferences(useweave=True) brian.set_global_preferences(usecodegenweave=True) brian.clear(erase=True, all=True) brian.reinit_default_clock() clk = brian.Clock(dt=0.05 * ms) ################ # create neurons, define connections neurNetwork = brian.NeuronGroup(nNet, model=eqs, threshold=vthresh, reset=vrest, refractory=absRefractoryMs * msecond, order=1, compile=True, freeze=False, clock=clk) # create neuron pools neurCE = neurNetwork.subgroup(nExc) neurCI = neurNetwork.subgroup(nInh) connCE = brian.Connection(neurCE, neurNetwork, 'ge') connCI = brian.Connection(neurCI, neurNetwork, 'gi') print('n cells: %d, nE,I %d,%d, %s, absRefractoryMs: %d' % (nNet, nExc, nInh, repr(clk), absRefractoryMs)) # connect the network to itself connCE.connect_random(neurCE, neurNetwork, internalSparseness, weight=connENetWeight) connCI.connect_random(neurCI, neurNetwork, internalSparseness, weight=connINetWeight) # connect inputs that change spont rate assert ( spontAddRate <= 0 ), 'Spont add rate should be negative - convention: neg, excite inhibitory cells' spontAddNInpSyn = 100 nTotalSpontNeurons = (spontAddNInpSyn * nInh * 0.02) neurSpont = brian.PoissonGroup(nTotalSpontNeurons, -1.0 * spontAddRate * Hz) connCSpont = brian.Connection(neurSpont, neurCI, 'ge') connCSpont.connect_random( p=spontAddNInpSyn * 1.0 / nTotalSpontNeurons, weight=connENetWeight, # match internal excitatory strengths fixed=True) # connect the feedforward visual (poisson) inputs to excitatory cells (ff E) ffExcInputNInpSyn = 100 nTotalFfNeurons = (ffExcInputNInpSyn * ffExcInputNTargs * 0.02 ) # one pop of input cells for both E and I FF _ffExcInputV = ffExcInputMult * np.abs(a_(ffInputV).copy()) assert (np.all( _ffExcInputV >= 0)), 'Negative FF rates are rectified to zero' neurFfExcInput = brian.PoissonGroup( nTotalFfNeurons, lambda t: _ffExcInputV[int(t * 1000)] * Hz) connCFfExcInput = brian.Connection(neurFfExcInput, neurNetwork, 'ge') connCFfExcInput.connect_random(neurFfExcInput, neurCE[0:ffExcInputNTargs], ffExcInputNInpSyn * 1.0 / nTotalFfNeurons, weight=connENetWeight, fixed=True) # connect the feedforward visual (poisson) inputs to inhibitory cells (ff I) ffInhInputNInpSyn = 100 _ffInhInputV = ffInhInputMult * np.abs(ffInputV.copy()) assert (np.all( _ffInhInputV >= 0)), 'Negative FF rates are rectified to zero' neurFfInhInput = brian.PoissonGroup( nTotalFfNeurons, lambda t: _ffInhInputV[int(t * 1000)] * Hz) connCFfInhInput = brian.Connection(neurFfInhInput, neurNetwork, 'ge') connCFfInhInput.connect_random( neurFfInhInput, neurCI[0:ffInhInputNTargs], ffInhInputNInpSyn * 1.0 / nTotalFfNeurons, # sparseness weight=connENetWeight, fixed=True) # connect added step (ChR2) conductance to excitatory cells condAddAmp = 4.0 gAdd = brian.TimedArray(condAddAmp * condAddV, dt=1 * ms) print('Adding conductance for %d cells (can be slow): ' % len(condAddNeurNs), end=' ') for (iN, tN) in enumerate(condAddNeurNs): neurCE[tN].gAdd = gAdd print('done') # Initialize using some randomness so all neurons don't start in same state. # Alternative: initialize with constant values, give net extra 100-300ms to evolve from initial state. neurNetwork.v = (brian.randn(1) * 5.0 - 65) * mvolt neurNetwork.ge = brian.randn(nNet) * 1.5 + 4 neurNetwork.gi = brian.randn(nNet) * 12 + 20 # Record continuous variables and spikes monSTarg = brian.SpikeMonitor(neurNetwork) if contRecNs is not None: contRecClock = brian.Clock(dt=contRecStepMs * ms) monVTarg = brian.StateMonitor(neurNetwork, 'v', record=contRecNs, clock=contRecClock) monGETarg = brian.StateMonitor(neurNetwork, 'ge', record=contRecNs, clock=contRecClock) monGAddTarg = brian.StateMonitor(neurNetwork, 'gAdd', record=contRecNs, clock=contRecClock) monGITarg = brian.StateMonitor(neurNetwork, 'gi', record=contRecNs, clock=contRecClock) # construct brian.Network before running (so brian explicitly knows what to update during run) netL = [ neurNetwork, connCE, connCI, monSTarg, neurFfExcInput, connCFfExcInput, neurFfInhInput, connCFfInhInput, neurSpont, connCSpont ] if contRecNs is not None: # noinspection PyUnboundLocalVariable netL.append([monVTarg, monGETarg, monGAddTarg, monGITarg]) # cont monitors net = brian.Network(netL) print("Network construction time: %3.1f seconds" % (time.time() - stT)) # run print("Simulation running...") sys.stdout.flush() start_time = time.time() net.run(simRunTimeS * second, report='text', report_period=30.0 * second) durationS = time.time() - start_time print("Simulation time: %3.1f seconds" % durationS) outNTC = collections.namedtuple( 'outNTC', 'vm ge gadd gi clockDtS clockStartS clockEndS spiketimes contRecNs') outNTC.__new__.__defaults__ = (None, ) * len( outNTC._fields) # default to None outNT = outNTC(clockDtS=float(monSTarg.clock.dt), clockStartS=float(monSTarg.clock.start), clockEndS=float(monSTarg.clock.end), spiketimes=a_(monSTarg.spiketimes.values(), dtype='O'), contRecNs=contRecNs) if contRecNs is not None: outNT = outNT._replace(vm=monVTarg.values, ge=monGETarg.values, gadd=monGAddTarg.values, gi=monGITarg.values) return outNT
def fft_std(delta_u, run_num, new_connectivity, osc, rep): #bn.seed(int(time.time())) bn.reinit_default_clock() #bn.seed(1412958308+2) bn.defaultclock.dt = 0.5 * bn.ms #============================================================================== # Define constants for the model. #============================================================================== fft_file = './std_fft_p20_' rate_file = './std_rate_p20_' print delta_u print run_num print new_connectivity print rep if osc: T = 5.5 * bn.second else: T = 2.5 * bn.second n_tsteps = T / bn.defaultclock.dt fft_start = 0.5 * bn.second / bn.defaultclock.dt # Time window for the FFT computation ro = 1.2 * bn.Hz SEE1 = 1.0 SEE2 = 1.0 qee1 = 1.00 # Fraction of NMDA receptors for e to e connections qee2 = 0.00 qie1 = 1.00 # Fraction of NMDA receptors for e to i connections qie2 = 0.00 uee1 = 0.2 - delta_u uee2 = 0.2 + delta_u uie1 = 0.2 uie2 = 0.2 trec1 = 1000.0 * bn.ms trec2 = 1000.0 * bn.ms k = 0.65 #Jeo_const = 1.0#*bn.mV # Base strength of o (external) to e connections Ne = 3200 # number of excitatory neurons Ni = 800 # number of inhibitory neurons No = 20000 # number of external neurons N = Ne + Ni pcon = 0.2 # probability of connection Jee = 10.0 / (Ne * pcon) Jie = 10.0 / (Ne * pcon) Jii = k * 10.0 / (Ni * pcon) Jei = k * 10.0 / (Ni * pcon) Jeo = 1.0 El = -60.0 * bn.mV # leak reversal potential Vreset = -52.0 * bn.mV # reversal potential Vthresh = -40.0 * bn.mV # spiking threshold tref = 2.0 * bn.ms # refractory period te = 20.0 * bn.ms # membrane time constant of excitatory neurons ti = 10.0 * bn.ms # membrane time constant of inhibitory neruons tee_ampa = 10.0 * bn.ms # time const of ampa currents at excitatory neurons tee_nmda = 100.0 * bn.ms # time const of nmda currents at excitatory neurons tie_ampa = 10.0 * bn.ms # time const of ampa currents at inhibitory neurons tie_nmda = 100.0 * bn.ms # time const of nmda currents at inhibitory neurons tii_gaba = 10.0 * bn.ms # time const of GABA currents at inhibitory neurons tei_gaba = 10.0 * bn.ms # time const of GABA currents at excitatory neurons teo_input = 100.0 * bn.ms #============================================================================== # Define model structure #============================================================================== model = ''' dV/dt = (-(V-El)+J_ampa1*I_ampa1+J_nmda1*I_nmda1+J_ampa2*I_ampa2+J_nmda2*I_nmda2-J_gaba*I_gaba+J_input*I_input+eta)/tm : bn.volt dI_ampa1/dt = -I_ampa1/t_ampa : bn.volt dI_nmda1/dt = -I_nmda1/t_nmda : bn.volt dI_ampa2/dt = -I_ampa2/t_ampa : bn.volt dI_nmda2/dt = -I_nmda2/t_nmda : bn.volt dI_gaba/dt = -I_gaba/t_gaba : bn.volt dI_input/dt = (-I_input+mu)/t_input : bn.volt dx1/dt = (1-x1)/t1_rec : 1 dx2/dt = (1-x2)/t2_rec : 1 u1 : 1 t1_rec : bn.second u2 : 1 t2_rec : bn.second mu : bn.volt eta : bn.volt J_ampa1 : 1 J_nmda1 : 1 J_ampa2 : 1 J_nmda2 : 1 J_gaba : 1 J_input : 1 tm : bn.second t_ampa : bn.second t_nmda : bn.second t_gaba : bn.second t_input : bn.second ''' P_reset = "V=-52*bn.mV;x1+=-u1*x1;x2+=-u2*x2" Se_model = ''' we_ampa1 : bn.volt we_nmda1 : bn.volt we_ampa2 : bn.volt we_nmda2 : bn.volt ''' Se_pre = ('I_ampa1 += x1_pre*we_ampa1', 'I_nmda1 += x1_pre*we_nmda1', 'I_ampa2 += x2_pre*we_ampa2', 'I_nmda2 += x2_pre*we_nmda2') Si_model = ''' wi_gaba : bn.volt ''' Si_pre = 'I_gaba += wi_gaba' So_model = ''' wo_input : bn.volt ''' So_pre = 'I_input += wo_input' #============================================================================== # Define populations #============================================================================== P = bn.NeuronGroup(N, model, threshold=Vthresh, reset=P_reset, refractory=tref) Pe = P[0:Ne] Pe.tm = te Pe.t_ampa = tee_ampa Pe.t_nmda = tee_nmda Pe.t_gaba = tei_gaba Pe.t_input = teo_input Pe.I_ampa1 = 0 * bn.mV Pe.I_nmda1 = 0 * bn.mV Pe.I_ampa2 = 0 * bn.mV Pe.I_nmda2 = 0 * bn.mV Pe.I_gaba = 0 * bn.mV Pe.I_input = 0 * bn.mV Pe.V = (np.random.rand(Pe.V.size) * 12 - 52) * bn.mV Pe.x1 = 1.0 Pe.x2 = 1.0 Pe.u1 = uee1 Pe.u2 = uee2 Pe.t1_rec = trec1 Pe.t2_rec = trec2 Pi = P[Ne:(Ne + Ni)] Pi.tm = ti Pi.t_ampa = tie_ampa Pi.t_nmda = tie_nmda Pi.t_gaba = tii_gaba Pi.t_input = teo_input Pi.I_ampa1 = 0 * bn.mV Pi.I_nmda1 = 0 * bn.mV Pi.I_ampa2 = 0 * bn.mV Pi.I_nmda2 = 0 * bn.mV Pi.I_gaba = 0 * bn.mV Pi.I_input = 0 * bn.mV Pi.V = (np.random.rand(Pi.V.size) * 12 - 52) * bn.mV Pi.x1 = 1.0 Pi.x2 = 1.0 Pi.u1 = 0.0 Pi.u2 = 0.0 Pi.t1_rec = 1.0 Pi.t2_rec = 1.0 Pe.J_ampa1 = Jee * (1 - qee1) #*SEE1 Pe.J_nmda1 = Jee * qee1 #*SEE1 Pe.J_ampa2 = Jee * (1 - qee2) #*SEE2 Pe.J_nmda2 = Jee * qee2 #*SEE2 Pi.J_ampa1 = Jie * (1 - qie2) #*SEE2 Pi.J_nmda1 = Jie * qie2 #*SEE2 Pi.J_ampa2 = Jie * (1 - qie1) #*SEE1 Pi.J_nmda2 = Jie * qie1 #*SEE1 Pe.J_gaba = Jei Pi.J_gaba = Jii Pe.J_input = Jeo Pi.J_input = Jeo #============================================================================== # Define inputs #============================================================================== if osc: Pe.mu = 12.0 * bn.mV holder = np.zeros((n_tsteps, )) t_freq = np.linspace(0, 10, n_tsteps) fo = 0.2 # Smallest frequency in the signal fe = 10.0 # Largest frequency in the signal F = int(fe / 0.2) for m in range(1, F + 1): holder = holder + np.cos(2 * np.pi * m * fo * t_freq - m * (m - 1) * np.pi / F) holder = holder / np.max(holder) Pe.eta = bn.TimedArray(0.0 * bn.mV * holder) #, dt=0.5*bn.ms) Background_eo = bn.PoissonInput(Pe, N=1000, rate=1.05 * bn.Hz, weight=0.2 * bn.mV, state='I_input') Background_io = bn.PoissonInput(Pi, N=1000, rate=1.0 * bn.Hz, weight=0.2 * bn.mV, state='I_input') Pi.mu = 0 * bn.mV Pi.eta = 0 * bn.mV #, dt=0.5*bn.ms) Po = bn.PoissonGroup(No, rates=0 * bn.Hz) else: Background_eo = bn.PoissonInput(Pe, N=1000, rate=1.05 * bn.Hz, weight=0.2 * bn.mV, state='I_input') Background_io = bn.PoissonInput(Pi, N=1000, rate=1.0 * bn.Hz, weight=0.2 * bn.mV, state='I_input') holder_pe = np.zeros((n_tsteps, )) time_steps = np.linspace(0, T / bn.second, n_tsteps) holder_pe[time_steps < 0.5] = 0.0 * bn.mV holder_pe[time_steps >= 0.5] = 6.0 * bn.mV #25 holder_pe[time_steps > 1.5] = 0.0 * bn.mV #25 Pe.mu = bn.TimedArray(holder_pe) def firing_function(t, ro): if t > 0.5 * bn.second and t < 3.5 * bn.second: return 0.0 * bn.Hz else: return 0.0 * bn.Hz Pe.eta = 0 * bn.mV #, dt=0.5*bn.ms) Pi.mu = 0.0 * bn.mV Pi.eta = 0 * bn.mV #, dt=0.5*bn.ms) Po = bn.PoissonGroup(No, rates=lambda t: firing_function(t, ro)) #============================================================================== # Define synapses #============================================================================== See1 = bn.Synapses(Pe, Pe, model=Se_model, pre=Se_pre) See2 = bn.Synapses(Pe, Pe, model=Se_model, pre=Se_pre) Sie1 = bn.Synapses(Pe, Pi, model=Se_model, pre=Se_pre) Sie2 = bn.Synapses(Pe, Pi, model=Se_model, pre=Se_pre) Sei = bn.Synapses(Pi, Pe, model=Si_model, pre=Si_pre) Sii = bn.Synapses(Pi, Pi, model=Si_model, pre=Si_pre) Seo = bn.Synapses(Po, Pe, model=So_model, pre=So_pre) #============================================================================== # Define random connections #============================================================================== if new_connectivity: See1.connect_random(Pe, Pe, sparseness=pcon / 2.0) See2.connect_random(Pe, Pe, sparseness=pcon / 2.0) Sie1.connect_random(Pe, Pi, sparseness=pcon / 2.0) Sie2.connect_random(Pe, Pi, sparseness=pcon / 2.0) Sii.connect_random(Pi, Pi, sparseness=pcon) Sei.connect_random(Pi, Pe, sparseness=pcon) Seo.connect_random(Po, Pe, sparseness=pcon) print 'Saving' See1.save_connectivity('./See1_connections_std_saver_p20_' + str(run_num)) See2.save_connectivity('./See2_connections_std_saver_p20_' + str(run_num)) Sie1.save_connectivity('./Sie1_connections_std_saver_p20_' + str(run_num)) Sie2.save_connectivity('./Sie2_connections_std_saver_p20_' + str(run_num)) Sii.save_connectivity('./Sii_connections_std_saver_p20_' + str(run_num)) Sei.save_connectivity('./Sei_connections_std_saver_p20_' + str(run_num)) Seo.save_connectivity('./Seo_connections_std_saver_p20_' + str(run_num)) else: print 'Loading' See1.load_connectivity('./See1_connections_std_saver_p20_' + str(run_num)) See2.load_connectivity('./See2_connections_std_saver_p20_' + str(run_num)) Sie1.load_connectivity('./Sie1_connections_std_saver_p20_' + str(run_num)) Sie2.load_connectivity('./Sie2_connections_std_saver_p20_' + str(run_num)) Sii.load_connectivity('./Sii_connections_std_saver_p20_' + str(run_num)) Sei.load_connectivity('./Sei_connections_std_saver_p20_' + str(run_num)) Seo.load_connectivity('./Seo_connections_std_saver_p20_' + str(run_num)) See1.we_ampa1 = SEE1 * 1.0 * bn.mV / tee_ampa See1.we_nmda1 = SEE1 * 1.0 * bn.mV / tee_nmda See1.we_ampa2 = 0.0 * bn.mV / tee_ampa See1.we_nmda2 = 0.0 * bn.mV / tee_nmda See2.we_ampa1 = 0.0 * bn.mV / tee_ampa See2.we_nmda1 = 0.0 * bn.mV / tee_nmda See2.we_ampa2 = SEE2 * 1.0 * bn.mV / tee_ampa See2.we_nmda2 = SEE2 * 1.0 * bn.mV / tee_nmda Sie1.we_ampa1 = 0.0 * bn.mV / tie_ampa Sie1.we_nmda1 = 0.0 * bn.mV / tie_nmda Sie1.we_ampa2 = SEE1 * 1.0 * bn.mV / tie_ampa Sie1.we_nmda2 = SEE1 * 1.0 * bn.mV / tie_nmda Sie2.we_ampa1 = SEE2 * 1.0 * bn.mV / tie_ampa Sie2.we_nmda1 = SEE2 * 1.0 * bn.mV / tie_nmda Sie2.we_ampa2 = 0.0 * bn.mV / tie_ampa Sie2.we_nmda2 = 0.0 * bn.mV / tie_nmda Sei.wi_gaba = 1.0 * bn.mV / tei_gaba Sii.wi_gaba = 1.0 * bn.mV / tii_gaba Seo.wo_input = 1.0 * bn.mV / teo_input #============================================================================== # Define monitors #============================================================================== Pe_mon_V = bn.StateMonitor(Pe, 'V', timestep=10, record=True) Pe_mon_eta = bn.StateMonitor(Pe, 'eta', timestep=1, record=True) Pe_mon_ampa1 = bn.StateMonitor(Pe, 'I_ampa1', timestep=1, record=True) Pe_mon_nmda1 = bn.StateMonitor(Pe, 'I_nmda1', timestep=1, record=True) Pe_mon_ampa2 = bn.StateMonitor(Pe, 'I_ampa2', timestep=1, record=True) Pe_mon_nmda2 = bn.StateMonitor(Pe, 'I_nmda2', timestep=1, record=True) Pe_mon_gaba = bn.StateMonitor(Pe, 'I_gaba', timestep=1, record=True) Pe_mon_input = bn.StateMonitor(Pe, 'I_input', timestep=10, record=True) See1_mon_x = bn.StateMonitor(Pe, 'x1', timestep=10, record=True) See2_mon_x = bn.StateMonitor(Pe, 'x2', timestep=10, record=True) Pe_ratemon = bn.PopulationRateMonitor(Pe, bin=10.0 * bn.ms) Pi_ratemon = bn.PopulationRateMonitor(Pi, bin=10.0 * bn.ms) #============================================================================== # Run model #============================================================================== timer = 0 * bn.second t_start = time.time() bn.run(T, report='graphical') timer = timer + T print '-------------------------------------------------------' print 'Time is ' + str(timer) + ' seconds' t_end = time.time() print 'Time to compute last ' +str(T)+' seconds is: ' + \ str(t_end - t_start) + ' seconds' print '-------------------------------------------------------\n' Pe_mon_ampa1_vals = Pe.J_ampa1[0] * np.mean(Pe_mon_ampa1.values.T, axis=1) Pe_mon_nmda1_vals = Pe.J_nmda1[0] * np.mean(Pe_mon_nmda1.values.T, axis=1) Pe_mon_ampa2_vals = Pe.J_ampa2[0] * np.mean(Pe_mon_ampa2.values.T, axis=1) Pe_mon_nmda2_vals = Pe.J_nmda2[0] * np.mean(Pe_mon_nmda2.values.T, axis=1) Pe_mon_ampa_vals = Pe_mon_ampa1_vals + Pe_mon_ampa2_vals Pe_mon_nmda_vals = Pe_mon_nmda1_vals + Pe_mon_nmda2_vals Pe_mon_gaba_vals = Pe.J_gaba[0] * np.mean(Pe_mon_gaba.values.T, axis=1) Pe_mon_input_vals = Pe.J_input[0] * np.mean(Pe_mon_input.values.T, axis=1) Pe_mon_V_vals = np.mean(Pe_mon_V.values.T, axis=1) Pe_mon_all_vals = Pe_mon_ampa_vals + Pe_mon_nmda_vals - Pe_mon_gaba_vals See1_mon_x_vals = np.mean(See1_mon_x.values.T, axis=1) See2_mon_x_vals = np.mean(See2_mon_x.values.T, axis=1) #============================================================================== # Save into a Matlab file #============================================================================== if osc: Pe_output = Pe.J_ampa1[0]*Pe_mon_ampa1.values+Pe.J_nmda1[0]*Pe_mon_nmda1.values + \ Pe.J_ampa2[0]*Pe_mon_ampa2.values+Pe.J_nmda2[0]*Pe_mon_nmda2.values-Pe.J_gaba[0]*Pe_mon_gaba.values Pe_output = Pe_output[:, fft_start:, ] Pe_V = Pe_mon_V.values[:, fft_start:, ] Pe_glut = Pe.J_ampa1[0]*Pe_mon_ampa1.values+Pe.J_nmda1[0]*Pe_mon_nmda1.values + \ Pe.J_ampa2[0]*Pe_mon_ampa2.values+Pe.J_nmda2[0]*Pe_mon_nmda2.values Pe_glut = Pe_glut[:, fft_start:, ] Pe_gaba = Pe.J_gaba[0] * Pe_mon_gaba.values Pe_gaba = Pe_gaba[:, fft_start:, ] Pe_input = Pe_mon_eta[:, fft_start:, ] T_step = bn.defaultclock.dt holder = { 'Pe_output': Pe_output, 'Pe_input': Pe_input, 'Pe_V': Pe_V, 'Pe_glut': Pe_glut, 'Pe_gaba': Pe_gaba, 'T_step': T_step } scipy.io.savemat(fft_file + 'delta_u' + str(delta_u) + '_' + str(rep), mdict=holder) else: holder = { 'Pe_rate': Pe_ratemon.rate, 'Pe_time': Pe_ratemon.times, 'uee1': uee1, 'uee2': uee2, 'uie1': uie1, 'uie2': uie2 } scipy.io.savemat(rate_file + 'delta_q_' + str(delta_u) + '_' + str(run_num) + 'rep' + str(rep), mdict=holder) bn.clear(erase=True, all=True)
output_neurons.ge = 0 print "v0 = ", v0 print "u0 = ", u0 for i in range(len(Sa)): Sa[i][:, :] = True Sa[i].w[:] = '8.04*(0.3+0.8*rand())*br.mV' Sa[i].delay = '(4)*ms' Sb[:, :] = True Sb.w[:] = '9.0*(0.1+0.2*rand())*br.mV' Sb.delay = '(4)*ms' #print "n.v0, n.u0 = ", hidden_neurons.v, ", ", hidden_neurons.u M = br.StateMonitor(output_neurons, 'ge', record=0) Mv = br.StateMonitor(output_neurons, 'v', record=0) Mu = br.StateMonitor(output_neurons, 'u', record=0) N = br.StateMonitor(liquid_neurons[0], 'ge', record=0) Nv = br.StateMonitor(liquid_neurons[0], 'v', record=0) Nu = br.StateMonitor(liquid_neurons[0], 'u', record=0) S_in = br.SpikeMonitor(input_neurons, record=True) S_hidden = [] #pudb.set_trace() for i in range(len(hidden_neurons)): S_hidden.append(br.SpikeMonitor(hidden_neurons[i], record=True)) S_out = br.SpikeMonitor(output_neurons, record=True)
def __init__(self, input_dim, output_dim, dtype, input_scaling=100, input_conn_frac=.5, dt=1, we_scaling=2, wi_scaling=.5, we_sparseness=.1, wi_sparseness=.1): super(BrianIFReservoirNode, self).__init__(input_dim=input_dim, output_dim=output_dim, dtype=dtype) self.taum = 20 * brian.ms self.taue = 5 * brian.ms self.taui = 10 * brian.ms self.Vt = 15 * brian.mV self.Vr = 0 * brian.mV self.frac_e = .75 self.input_scaling = input_scaling self.input_conn_frac = input_conn_frac self.dt = dt self.we_scaling = we_scaling self.wi_scaling = wi_scaling self.we_sparseness = we_sparseness self.wi_sparseness = wi_sparseness self.eqs = brian.Equations(''' dV/dt = (I-V+ge-gi)/self.taum : volt dge/dt = -ge/self.taue : volt dgi/dt = -gi/self.taui : volt I: volt ''') self.G = brian.NeuronGroup(N=output_dim, model=self.eqs, threshold=self.Vt, reset=self.Vr) self.Ge = self.G.subgroup(int(scipy.floor( output_dim * self.frac_e))) # Excitatory neurons self.Gi = self.G.subgroup( int(scipy.floor(output_dim * (1 - self.frac_e)))) self.internal_conn = brian.Connection(self.G, self.G) self.we = self.we_scaling * scipy.random.rand(len(self.Ge), len( self.G)) * brian.nS self.wi = self.wi_scaling * scipy.random.rand(len(self.Ge), len( self.G)) * brian.nS self.Ce = brian.Connection(self.Ge, self.G, 'ge', sparseness=self.we_sparseness, weight=self.we) self.Ci = brian.Connection(self.Gi, self.G, 'gi', sparseness=self.wi_sparseness, weight=self.wi) #self.internal_conn.connect(self.G, self.G, self.w_res) self.Mv = brian.StateMonitor(self.G, 'V', record=True, timestep=10) self.Ms = brian.SpikeMonitor(self.G, record=True) self.w_in = self.input_scaling * (scipy.random.rand( self.output_dim, self.input_dim)) * (scipy.random.rand( self.output_dim, self.input_dim) < self.input_conn_frac) self.network = brian.Network(self.G, self.Ce, self.Ci, self.Ge, self.Gi, self.Mv, self.Ms)
def run(duration, objects, **kwargs): """Run a brian simulation This is a convenience function to easily run a brian network while also offering a flexible way of introducing Monitors. Parameters ---------- duration : float Duration of the simulation in seconds. objects : list A collection of Brian objects to be simulated. export_dict : dict A dictionary of state trace to export. The Key gives the neuron group to read the state from and the value is a list of strings naming the state variables. {neuron1:['v', 'n']} for example would create state monitors for the variables v and n of neuron1 **kwargs : Further kwargs ar passed to the brian network run function Returns ------- If export_dict is given as a kwarg, The function this dictionary where the keys has been replaced by a pandas.DataFrame that contains the time and value treaces of the requested variables. """ import pandas # Reset brian defaultclock brian.defaultclock.t = 0 * second # If export_dict is given, create a number # of State Monitors for the requested variables monitor_objects = [] monitor_dict = {} if "export_dict" in kwargs: export_dict = kwargs.pop("export_dict") for o, l in export_dict.iteritems(): monitor_dict[o] = [] for i in l: monitor = brian.StateMonitor(o, i, record=True) monitor_dict[o].append(monitor) monitor_objects.append(monitor) net = brian.Network(objects + monitor_objects) kwargs.setdefault('report', 'text') kwargs.setdefault('report_period', 1) net.run(duration * second, **kwargs) for o, l in monitor_dict.iteritems(): pds_dict = {} for i, m in enumerate(l): var_name = export_dict[o][i] data = m.values pds_dict[var_name] = list(data) pds_dict['time'] = len(data) * [m.times] pds_frame = pandas.DataFrame(pds_dict) monitor_dict[o] = pds_frame return monitor_dict
def fft_nostd(qee, run_num, new_connectivity, osc, rep): #bn.seed(int(time.time())) # bn.seed(1412958308+2) bn.reinit_default_clock() bn.defaultclock.dt = 0.5 * bn.ms #============================================================================== # Define constants for the model. #============================================================================== fft_file = './nostd_fft_p20_' rate_file = './nostd_rate_p20_' if osc: T = 8.0 * bn.second else: T = 3.5 * bn.second n_tsteps = T / bn.defaultclock.dt fft_start = 3.0 * bn.second / bn.defaultclock.dt # Time window for the FFT computation #run_num = 10 ro = 1.2 * bn.Hz #============================================================================== # Need to do all others besides 0.2 and 0.5 #============================================================================== print qee print run_num print new_connectivity print rep qie = 0.3 # Fraction of NMDA receptors for e to i connections k = 0.65 Jeo_const = 1.0 #*bn.mV # Base strength of o (external) to e connections Ne = 3200 # number of excitatory neurons Ni = 800 # number of inhibitory neurons No = 2000 # number of external neurons N = Ne + Ni pcon = 0.2 # probability of connection Jee = 5.0 / (Ne * pcon) Jie = 5.0 / (Ne * pcon) Jii = k * 5.0 / (Ni * pcon) Jei = k * 5.0 / (Ni * pcon) Jeo = 1.0 El = -60.0 * bn.mV # leak reversal potential Vreset = -52.0 * bn.mV # reversal potential Vthresh = -40.0 * bn.mV # spiking threshold tref = 2.0 * bn.ms # refractory period te = 20.0 * bn.ms # membrane time constant of excitatory neurons ti = 10.0 * bn.ms # membrane time constant of inhibitory neruons tee_ampa = 10.0 * bn.ms # time const of ampa currents at excitatory neurons tee_nmda = 100.0 * bn.ms # time const of nmda currents at excitatory neurons tie_ampa = 10.0 * bn.ms # time const of ampa currents at inhibitory neurons tie_nmda = 100.0 * bn.ms # time const of nmda currents at inhibitory neurons tii_gaba = 10.0 * bn.ms # time const of GABA currents at inhibitory neurons tei_gaba = 10.0 * bn.ms # time const of GABA currents at excitatory neurons teo_input = 100.0 * bn.ms #============================================================================== # Define model structure #============================================================================== model = ''' dV/dt = (-(V-El)+J_ampa*I_ampa+J_nmda*I_nmda-J_gaba*I_gaba+J_input*I_input+eta+eta_corr)/tm : bn.volt dI_ampa/dt = -I_ampa/t_ampa : bn.volt dI_nmda/dt = -I_nmda/t_nmda : bn.volt dI_gaba/dt = -I_gaba/t_gaba : bn.volt dI_input/dt = (-I_input+mu)/t_input : bn.volt J_ampa : 1 J_nmda : 1 J_gaba : 1 J_input : 1 mu : bn.volt eta : bn.volt eta_corr : bn.volt tm : bn.second t_ampa : bn.second t_nmda : bn.second t_gaba : bn.second t_input : bn.second ''' P_reset = "V=-52*bn.mV" Se_model = ''' we_ampa : bn.volt we_nmda : bn.volt ''' Se_pre = ('I_ampa += we_ampa', 'I_nmda += we_nmda') Si_model = ''' wi_gaba : bn.volt ''' Si_pre = 'I_gaba += wi_gaba' So_model = ''' wo_input : bn.volt ''' So_pre = 'I_input += wo_input' #============================================================================== # Define populations #============================================================================== P = bn.NeuronGroup(N, model, threshold=Vthresh, reset=P_reset, refractory=tref) Pe = P[0:Ne] Pe.tm = te Pe.t_ampa = tee_ampa Pe.t_nmda = tee_nmda Pe.t_gaba = tei_gaba Pe.t_input = teo_input Pe.I_ampa = 0 * bn.mV Pe.I_nmda = 0 * bn.mV Pe.I_gaba = 0 * bn.mV Pe.I_input = 0 * bn.mV Pe.V = (np.random.rand(Pe.V.size) * 12 - 52) * bn.mV Pi = P[Ne:(Ne + Ni)] Pi.tm = ti Pi.t_ampa = tie_ampa Pi.t_nmda = tie_nmda Pi.t_gaba = tii_gaba Pi.t_input = teo_input Pi.I_ampa = 0 * bn.mV Pi.I_nmda = 0 * bn.mV Pi.I_gaba = 0 * bn.mV Pi.I_input = 0 * bn.mV Pi.V = (np.random.rand(Pi.V.size) * 12 - 52) * bn.mV Pe.J_ampa = Jee * (1 - qee) #*SEE1 Pe.J_nmda = Jee * qee #*SEE1 Pi.J_ampa = Jie * (1 - qie) #*SEE1 Pi.J_nmda = Jie * qie #*SEE1 Pe.J_gaba = Jei Pi.J_gaba = Jii Pe.J_input = Jeo Pi.J_input = Jeo #============================================================================== # Define inputs #============================================================================== if osc: Pe.mu = 2.0 * bn.mV holder = np.zeros((n_tsteps, )) t_freq = np.linspace(0, 10, n_tsteps) fo = 0.2 # Smallest frequency in the signal fe = 10.0 # Largest frequency in the signal F = int(fe / 0.2) for m in range(1, F + 1): holder = holder + np.cos(2 * np.pi * m * fo * t_freq - m * (m - 1) * np.pi / F) holder = holder / np.max(holder) Pe.eta = bn.TimedArray(0.0 * bn.mV * holder) #, dt=0.5*bn.ms) Pe.eta_corr = 0 * bn.mV Background_eo = bn.PoissonInput(Pe, N=1000, rate=1.0 * bn.Hz, weight=0.2 * bn.mV, state='I_input') Background_io = bn.PoissonInput(Pi, N=1000, rate=1.05 * bn.Hz, weight=0.2 * bn.mV, state='I_input') Pi.mu = 0 * bn.mV Pi.eta = 0 * bn.mV #, dt=0.5*bn.ms) Pi.eta_corr = 0 * bn.mV Po = bn.PoissonGroup(No, rates=0 * bn.Hz) else: Background_eo = bn.PoissonInput(Pe, N=1000, rate=1.0 * bn.Hz, weight=0.2 * bn.mV, state='I_input') Background_io = bn.PoissonInput(Pi, N=1000, rate=1.05 * bn.Hz, weight=0.2 * bn.mV, state='I_input') holder_pe = np.zeros((n_tsteps, )) time_steps = np.linspace(0, T / bn.second, n_tsteps) holder_pe[time_steps < 0.5] = 0.0 * bn.mV holder_pe[time_steps >= 0.5] = 3.0 * bn.mV # 35.0/Jeo *bn.mV #25 Pe.mu = bn.TimedArray(holder_pe) def firing_function(t, ro): if t > 0.5 * bn.second and t < 3.5 * bn.second: return 0.0 * bn.Hz else: return 0.0 * bn.Hz # Pe.mu = 0*bn.mV Pe.eta = 0 * bn.mV #, dt=0.5*bn.ms) Pi.mu = 0.0 * bn.mV Pi.eta = 0 * bn.mV #, dt=0.5*bn.ms) Po = bn.PoissonGroup(No, rates=lambda t: firing_function(t, ro)) #============================================================================== # Define synapses #============================================================================== See = bn.Synapses(Pe, Pe, model=Se_model, pre=Se_pre) Sie = bn.Synapses(Pe, Pi, model=Se_model, pre=Se_pre) Sei = bn.Synapses(Pi, Pe, model=Si_model, pre=Si_pre) Sii = bn.Synapses(Pi, Pi, model=Si_model, pre=Si_pre) Seo = bn.Synapses(Po, Pe, model=So_model, pre=So_pre) #============================================================================== # Define monitors #============================================================================== Pe_mon_V = bn.StateMonitor(Pe, 'V', timestep=1, record=True) Pe_mon_eta = bn.StateMonitor(Pe, 'eta', timestep=1, record=True) Pe_mon_ampa = bn.StateMonitor(Pe, 'I_ampa', timestep=1, record=True) Pe_mon_nmda = bn.StateMonitor(Pe, 'I_nmda', timestep=1, record=True) Pe_mon_gaba = bn.StateMonitor(Pe, 'I_gaba', timestep=1, record=True) Pe_ratemon = bn.PopulationRateMonitor(Pe, bin=10.0 * bn.ms) #============================================================================== # Define random connections #============================================================================== if new_connectivity: See.connect_random(Pe, Pe, sparseness=pcon) Sie.connect_random(Pe, Pi, sparseness=pcon) Sii.connect_random(Pi, Pi, sparseness=pcon) Sei.connect_random(Pi, Pe, sparseness=pcon) Seo.connect_random(Po, Pe, sparseness=pcon) print 'Saving' See.save_connectivity('./See_connections_nostd_saver_p20' + str(run_num)) Sie.save_connectivity('./Sie_connections_nostd_saver_p20' + str(run_num)) Sii.save_connectivity('./Sii_connections_nostd_saver_p20' + str(run_num)) Sei.save_connectivity('./Sei_connections_nostd_saver_p20' + str(run_num)) Seo.save_connectivity('./Seo_connections_nostd_saver_p20' + str(run_num)) else: print 'Loading' See.load_connectivity('./See_connections_nostd_saver_p20' + str(run_num)) Sie.load_connectivity('./Sie_connections_nostd_saver_p20' + str(run_num)) Sii.load_connectivity('./Sii_connections_nostd_saver_p20' + str(run_num)) Sei.load_connectivity('./Sei_connections_nostd_saver_p20' + str(run_num)) Seo.load_connectivity('./Seo_connections_nostd_saver_p20' + str(run_num)) See.we_ampa = 1.0 * bn.mV / tee_ampa See.we_nmda = 1.0 * bn.mV / tee_nmda Sie.we_ampa = 1.0 * bn.mV / tie_ampa Sie.we_nmda = 1.0 * bn.mV / tie_nmda Sei.wi_gaba = 1.0 * bn.mV / tei_gaba Sii.wi_gaba = 1.0 * bn.mV / tii_gaba Seo.wo_input = 1.0 * bn.mV / teo_input #============================================================================== # Run model #============================================================================== timer = 0 * bn.second t_start = time.time() bn.run(T, report='graphical') timer = timer + T print '-------------------------------------------------------' print 'Time is ' + str(timer) + ' seconds' t_end = time.time() print 'Time to compute last ' +str(T)+' seconds is: ' + \ str(t_end - t_start) + ' seconds' print '-------------------------------------------------------\n' #============================================================================== # Save into a Matlab file #============================================================================== if osc: Pe_output = Pe.J_ampa[0] * Pe_mon_ampa.values + Pe.J_nmda[ 0] * Pe_mon_nmda.values - Pe.J_gaba[0] * Pe_mon_gaba.values Pe_output = Pe_output[:, fft_start:, ] Pe_glut = Pe.J_ampa[0] * Pe_mon_ampa.values + Pe.J_nmda[ 0] * Pe_mon_nmda.values Pe_glut = Pe_glut[:, fft_start:, ] Pe_gaba = Pe.J_gaba[0] * Pe_mon_gaba.values[:, fft_start:, ] Pe_V = Pe_mon_V.values[:, fft_start:, ] Pe_input = Pe_mon_eta[:, fft_start:, ] T_step = bn.defaultclock.dt holder = { 'Pe_output': Pe_output, 'Pe_input': Pe_input, 'Pe_V': Pe_V, 'Pe_glut': Pe_glut, 'Pe_gaba': Pe_gaba, 'T_step': T_step } scipy.io.savemat(fft_file + 'qee' + str(qee) + '_' + str(rep), mdict=holder) else: holder = {'Pe_rate': Pe_ratemon.rate, 'Pe_time': Pe_ratemon.times} scipy.io.savemat(rate_file + 'qee_' + str(qee) + '_' + str(run_num) + 'rep' + str(rep), mdict=holder)