def simulate(pool, tstop=1000, vinit=-55): ''' simulation control Parameters ---------- cell: NEURON cell cell for simulation tstop: int (ms) simulation time vinit: int (mV) initialized voltage ''' h.finitialize(vinit) for i in pool: cell = pc.gid2cell(i) balance(cell) if h.cvode.active(): h.cvode.active() else: h.fcurrent() h.frecord_init() h.tstop = tstop h.v_init = vinit pc.set_maxstep(0.5) h.stdinit() pc.psolve(tstop)
def simulate(pool, tstop=50000, vinit=-55): ''' simulation control Parameters ---------- cell: NEURON cell cell for simulation tstop: int (ms) simulation time vinit: int (mV) initialized voltage ''' h.finitialize(vinit) for i in pool: cell = pc.gid2cell(i) balance(cell) if h.cvode.active(): h.cvode.active() else: h.fcurrent() h.frecord_init() h.tstop = tstop h.v_init = vinit pc.set_maxstep(0.5) h.stdinit() pc.psolve(tstop)
def FiringOnset(leftI, rightI, precision, apc, stim, T, fr_set): import neuron from neuron import h from I_proc import stimulate while ((rightI - leftI) > precision * max([abs(rightI), abs(leftI)])): print("leftI is %f, rightI is %f" % (leftI, rightI)) print("rightI-leftI: %f , precision: %f \n" % ((rightI - leftI), precision)) h.finitialize() h.fcurrent() h.frecord_init() apc.n = 0 mean = (leftI + rightI) / 2 print('mean is %f' % (mean)) h.stim = stimulate([0, stim, mean]) h.tstop = T h.run() fr = apc.n / float(T / 1000) print('fr is %f' % (fr)) if (fr <= fr_set): leftI = mean # If the firing rate is too small, we will replace lowerbound with middle point else: rightI = mean # If the firing rate is too large, we will replace upperbound with middle point if fr_set > 0: return rightI else: return leftI
def go(): h.dt = 0.1 h.celsius = celsius h.finitialize(v_init) #neuron.init() # params: RERE, RETCa, ***RETCb, TCRE, PYPY, PYIN, INPYa, ***INPYb, PYRE, PYTC, TCPY, TCIN assign_synapses(RERE * 0.2, RETCa * 0.02, RETCb * 0.04, TCRE * 0.2, PYPY * 0.6, PYIN * 0.2, INPYa * gabaapercent * 0.15, INPYb * gababpercent * 0.03, PYRE * 1.2, PYTC * 0.01, TCPY * 1.2, TCIN * 0.4) #assign_synapses(gRERE_GABAA, gRETC_GABAA, gRETC_GABAB, gTCRE_AMPA, gPYPY_AMPA, gPYIN_AMPA, gINPY_GABAA, gINPY_GABAB, gPYRE_AMPA, gPYTC_AMPA, gTCPY_AMPA, gTCIN_AMPA) h.fcurrent() h.cvode.re_init() h.frecord_init() printPYinfo(0) printINinfo(0) printTCinfo(0) printREinfo(0) printWeight(0) field.append(0) while h.t < tstop: h.fadvance() field.append(xfield(230, fielddist, watchneuron))
def DetermineStdI(leftStd, rightStd, precision_std, apc, mean, stim, tau, dt, T, fr_set, seednumber): import neuron from neuron import h from I_proc import stimulate while ((rightStd - leftStd) > precision_std * max([abs(rightStd), abs(leftStd)])): if leftStd == 0 and rightStd < 1e-7: break return rightStd print("leftStd is %f, rightStd is %f" % (leftStd, rightStd)) print("rightStd-leftStd: %f , precision_std: %f \n" % ((rightStd - leftStd), precision_std)) h.finitialize() h.fcurrent() h.frecord_init() apc.n = 0 std = (leftStd + rightStd) / 2 print('std for test is %f' % (std)) h.stim = stimulate([1, stim, mean, std, tau, dt, T, seednumber]) h.tstop = T h.run() fr = apc.n / float(T / 1000) print('fr is %f' % (fr)) if (fr <= fr_set): leftStd = std else: rightStd = std return std
def initialise(self, vrest=-65): """ Initialise the model, to launch before each simulations """ for sec in h.allsec(): h.finitialize(vrest, sec) h.fcurrent(sec) h.frecord_init()
def simulation(model, tau, posNa, T, threshold, stim_mean, stim_std, frequency, dt=0.025, seednumber=1): ''' simulation(object) -> va (axonal voltage at the AP initiation site in mV) Simulate the neuron model based on model setup and stimulus parameters. Parameters: Meanings [Example Values] model: model name ['Brette'] tau: correlation time of stimulus (ms) [5] posNa: position of sodium channels (um) [20] T: duration of stimulus and simulation (ms) [20000] threshold: axonal reset voltage for finishing spikes (mV) [-23] stim_mean: mean of stochastic stimulus (nA) [0.0185] stim_std: std of stochastic stimulus (nA) [0.046] dt: time step of model simulation (ms) [0.025] seednumber: random seed number for stimulus generation [1] ''' import os, sys from neuron import h from math import pi import numpy as np # Load parameters into NEURON. h('dt=%f'%(dt)) h('posNa=%f'%(posNa)) h('threshold=%f'%(threshold)) # Set up neuron model. h.load_file('nrngui.hoc') # Load nrngui. h.load_file('../Models/%s/Neuron.hoc'%(model)) # Load hoc file of neuron model. h('access soma') h('objref APgen, stimulus, stim, vAIS, vSoma') h('axon APgen = new NetCon(&v(posNa/axon_L), sodiumchan,threshold,0,0)') # Define action potential generation. h('axon {sodiumchan.loc(posNa/axon_L)}') # Insert sodium channels in axon. # Set up stimulus. h.stimulus = h.IClamp(0.5) # Stimulus is injected in the middle of soma. h.stimulus.dur = T # duration of simulus h.stim = h.Vector() sinwave = 0.01*np.sin(2*pi*frequency*np.arange(int(T/dt))*dt/1000.0) # NEW!! sinewave h.stim.from_python(sinwave) # Generate the stimulus with the OU process. # !!! h('stim.play(&stimulus.amp, dt)') # Axonal voltage recording h.vAIS = h.Vector(int(T/dt)) h.vSoma = h.Vector(int(T/dt)) h('vAIS.record(&axon.v(posNa/axon_L))') # Axonal voltage is recorded at the position of sodium channels. h('vSoma.record(&soma.v(0.5))') h.tstop = T # duration of simulation # Initiate model simulation h.finitialize() h.frecord_init() h.run() va = h.vAIS.to_python() # Convert NEURON vector to numpy array. vs = h.vSoma.to_python() return va, vs
def runsim(): t0 = time.time() # clock start time pc.set_maxstep( 10) # sets the default max solver step in ms (purposefully large) for elec in lelec: elec.setup() elec.LFPinit() h.finitialize( ) # initialize cells to -65 mV, after all the NetCon delays have been specified if pcID == 0: for tt in range(0, int(h.tstop), printdt): h.cvode.event(tt, prsimtime) # print time callbacks h.fcurrent() h.frecord_init( ) # set state variables if they have been changed since h.finitialize pc.psolve(h.tstop) # actual simulation - run the solver pc.barrier() # these calls aggregate data across procs/nodes pc.allreduce(dp_rec_L2, 1) pc.allreduce( dp_rec_L5, 1) # combine dp_rec on every node, 1=add contributions together for elec in lelec: elec.lfp_final() net.aggregate_currents( ) # aggregate the currents independently on each proc # combine net.current{} variables on each proc pc.allreduce(net.current['L5Pyr_soma'], 1) pc.allreduce(net.current['L2Pyr_soma'], 1) pc.barrier() # write time and calculated dipole to data file only if on the first proc # only execute this statement on one proc savedat(p, pcID, t_vec, dp_rec_L2, dp_rec_L5, net) for elec in lelec: print('end; t_vec.size()', t_vec.size(), 'elec.lfp_t.size()', elec.lfp_t.size()) if pcID == 0: if debug: print("Simulation run time: %4.4f s" % (time.time() - t0)) if debug: print("Simulation directory is: %s" % ddir.dsim) if paramrw.find_param(doutf['file_param'], 'save_spec_data') or usingOngoingInputs( doutf['file_param']): runanalysis(p, doutf['file_param'], doutf['file_dpl_norm'], doutf['file_spec']) # run spectral analysis if paramrw.find_param(doutf['file_param'], 'save_figs'): savefigs(ddir, p, p_exp) # save output figures pc.barrier() # make sure all done in case multiple trials
def prun(runState): h.stdinit() if runState == 1: pnm.psolve(h.tstop / 2.) savestate() else: restorestate() h.frecord_init() pnm.psolve(h.tstop) pspike()
def simulate(cell, tstop=400, vinit=-55): ''' simulation control Parameters ---------- cell: NEURON cell cell for simulation tstop: int (ms) simulation time vinit: int (mV) initialized voltage ''' h.finitialize(vinit) balance(cell) if h.cvode.active(): h.cvode.active() else: h.fcurrent() h.frecord_init() h.tstop = tstop h.v_init = vinit h.run() if cell.numofmodel == 9 or cell.numofmodel == 10 or cell.numofmodel == 12: running_ = 1 if cell.numofmodel == 9: dl = 0 d_t = 60000 elif cell.numofmodel == 10: dl = 1000 d_t = 40 else: dl = 800 d_t = 10 h.stdinit() for n in range(3): cell.x_application = cell.x_application + dl if n == 0: cell.dl = 5000 cell.x_application = 0 print(cell.x_application) else: cell.dl = 30050 cell.x_application = -400 cell.distance() for item in cell.diffs: item.tx1 = h.t + 5 # item.initial = 0#item.atp # if n == 0: # item.c0cleft = 0.01#item.c0cleft # else: item.c0cleft = item.c0cleft item.h = cell.distances.get(cell.diffusions.get(item)) h.continuerun(h.t + d_t) h.continuerun(h.t + 500)
def reset(self): print("Simulation initialization.") h.initnrn() h.frecord_init() h.finitialize(self.init_v * mV) if self.init_sleep > 0: print("sleep before run for: %s seconds" % self.init_sleep) time.sleep(self.init_sleep) if self.warmup > 0: h.dt = self.warmup / 10 h.continuerun(self.warmup * ms) h.dt = self.dt
def min_sim(self): """ Launch a minimal simulation to test the model and determine its resting potential empirically """ for sec in h.allsec(): h.finitialize(-65, sec) h.fcurrent(sec) h.frecord_init() while h.t < 200: # Launch a simulation h.fadvance() # Record the soma voltage after this minimal stimulation to find v_rest soma = getattr(h, "soma") self.vrest = getattr(soma, "v")
def min_sim(self, TSTOP=100): """ Launch a minimal simulation to test the model and determine its resting potential empirically """ vrec = h.Vector() vrec.record(self.soma(0.5)._ref_v) for sec in h.allsec(): h.finitialize(-65, sec) h.fcurrent(sec) h.frecord_init() while h.t < TSTOP: #Launch a simulation h.fadvance() vrest = np.array(vrec)[-1] return vrest
def run(self, cell, cmd, temp=22, dt=0.025): """ Run a single current-clamp recording on *section*. Parameters: cell : Cell The Cell instance to test. IClamp will be attached to cell.soma(0.5). cmd : array Array of current command values temp : temperature of simulation (22) dt : timestep of simulation (0.025) """ self.reset() self.cell = cell self.current_cmd = cmd self.dt = dt self.temp = temp tend = len(cmd) * dt # Configure IClamp istim = h.iStim(0.5, sec=cell.soma) istim.delay = 0 istim.dur = 1e9 # these actually do not matter... istim.iMax = 0.0 i_stim = h.Vector(cmd) i_stim.play(istim._ref_i, h.dt, 0) # Connect recording vectors self['vm'] = cell.soma(0.5)._ref_v self['i_inj'] = istim._ref_i self['time'] = h._ref_t # GO h.dt = dt h.celsius = temp h.tstop = tend cell.initialize() h.frecord_init() while h.t < h.tstop: h.fadvance()
def simulate(cell, tstop=1500, vinit=-55): ''' simulation control Parameters ---------- cell: NEURON cell cell for simulation tstop: int (ms) simulation time vinit: int (mV) initialized voltage ''' h.finitialize(vinit) balance(cell) if h.cvode.active(): h.cvode.active() else: h.fcurrent() h.frecord_init() h.tstop = tstop h.v_init = vinit h.run()
def simulate(cell, tstop=500, vinit=-60): ''' simulation control Parameters ---------- cell: NEURON cell cell for simulation tstop: int (ms) simulation time vinit: int (mV) initialized voltage ''' h.finitialize(vinit) balance(cell) if h.cvode.active(): h.cvode.active() else: h.fcurrent() h.frecord_init() h.tstop = tstop h.v_init = vinit h.run()
def run_neuron_simulator(warmup=2000, dt_warmup=10, dt_sim=0.1, t_start=0, t_stop=600, v_init=-60): h.cvode.active(0) dt = 0.1 h.steps_per_ms = 1.0 / dt h.finitialize(v_init) h.t = -warmup h.secondorder = 0 h.dt = dt_warmup while h.t < -100: h.fadvance() h.secondorder = 2 h.t = 0 h.dt = dt_sim """Setup run control for -100 to 1500""" h.frecord_init() # Necessary after changing t to restart the vectors while h.t < t_stop: h.fadvance()
"""Initialization for -2000 to -100""" h.cvode.active(0) dt = 0.1 h.steps_per_ms = 1.0 / dt h.finitialize(-60) h.t = -2000 h.secondorder = 0 h.dt = 10 while h.t < -100: h.fadvance() h.secondorder = 2 h.t = 0 h.dt = 0.1 """Setup run control for -100 to 1500""" h.frecord_init() # Necessary after changing t to restart the vectors while h.t < 600: h.fadvance() print("Done Running") tuned_save_file_name = (str(nw) + "_data_paradigm_local-pattern" + "-separation_run_scale_seed_" + str(run).zfill(3) + '_' + str(input_scale).zfill(3) + '_' + str(seed)) nw.shelve_network(savedir, tuned_save_file_name) fig = nw.plot_aps(time=600) tuned_fig_file_name = (str(nw) + "_spike-plot_paradigm_local-pattern" + "-separation_run_scale_seed_" + str(run).zfill(3) + '_' + str(input_scale).zfill(3) + '_' + str(seed)) nw.save_ap_fig(fig, savedir, tuned_fig_file_name)
def simulation(model, tau, posNa, T, stim_mean, stim_std, dt=0.025, seednumber=1, stim_type='OU', amplitude=[0], frequency=[0], electrode_place='soma'): ''' simulation(object) -> va (axonal voltage at the AP initiation site in mV) Simulate the neuron model based on model setup and stimulus parameters. Parameters: Meanings [Example Values] model: model name ['GE_diam_0'] tau: correlation time of stimulus (ms) [5] posNa: AP initiation site on axon (um) [47] T: duration of stimulus and simulation (ms) [20000] stim_mean: mean of stochastic stimulus (nA) [0.0] stim_std: std of stochastic stimulus (nA) [0.0346] dt: time step of model simulation (ms) [0.025] seednumber: random seed number for stimulus generation [1] stim_type: type of stimulus ['OU'] amplitude: amplitude of the sinusoidal signal in unit of stim_std [0.1] frequency: frequency of the sinusoidal signal added to background noise (Hz) [1, 2, 5, 10, 20, ..., 1000] electrode_place: the place of the input stimulus ['soma'] ''' import os, sys from neuron import h # Load parameters into NEURON. h('dt=%f' % (dt)) h('posNa=%f' % (posNa)) # Set up neuron model. h.load_file('nrngui.hoc') # Load nrngui. h('objref cell') # create neuron model h.load_file('../Models/%s/%s.hoc' % (model, model)) exec('h.cell = h.%s()' % (model)) h.cell.create_model() h.cell.biophys() h('v_init = -90') # initial voltage h('objref stimulus, stim, vAIS') if electrode_place == 'soma': h.stimulus = h.IClamp(0.5) else: h.stimulus = h.IClamp(h.cell.axon[0](0.94)) h.stimulus.dur = T h.stim = h.Vector() h.stim.from_python( stimulate([ stim_mean, stim_std, tau, dt, T, seednumber, stim_type, amplitude, frequency ])) # Generate the stimulus with the OU process. h('stim.play(&stimulus.amp, dt)') h.finitialize() h.frecord_init() # Axonal voltage recording h.vAIS = h.Vector(int(T / dt)) h.vAIS.record( h.cell.axon[0](h.posNa / h.cell.axon[0].L)._ref_v ) # Axonal voltage is recorded on the AIS with a distance of posNa. Total length of AIS is L. # h.vAIS.record(h.cell.soma[0](0.5)._ref_v) h.tstop = T # duration of simulation # Initiate model simulation h.finitialize() h.frecord_init() h.run() va = h.vAIS.to_python() # Convert NEURON vector to numpy array. return va
for prs, post in np.genfromtxt("../se.ssv").astype(int): scons.append(h.NetCon(S[prs].s, E[post].cell)) sys.stderr.write("====== Network Created! =======\n") for econ in econs: econ.weight[0], econ.delay = excw, excd for icon in icons: icon.weight[0], icon.delay = inhw, inhd for scon in scons: scon.weight[0], scon.delay = stmw, stmd h.dt = 0.1 h.finitialize() h.fcurrent() h.frecord_init() endbuild = time.time() while h.t < 1000.: h.fadvance() endsimulate = time.time() print("Building time : %.2f s" % (endbuild - startbuild)) print("Simulation time : %.2f s" % (endsimulate - endbuild)) print("Time step : %.2f ms" % (h.dt)) spkse = np.array([(x, ni) for ni, nE in enumerate(E) for x in list(np.array(nE.spk))]) spksi = np.array([(x, ni + Ne + 100) for ni, nI in enumerate(I)
def pyDentate(input_grid_out, seed_2, n_traj, dur_ms): savedir = os.getcwd() input_scale = 1000 seed_3 = seed_2 + 150 #seed_3 for network generation & simulation # Where to search for nrnmech.dll file. Must be adjusted for your machine. # dll_files = [("C:\\Users\\DanielM\\Repos\\models_dentate\\" # "dentate_gyrus_Santhakumar2005_and_Yim_patterns\\" # "dentategyrusnet2005\\nrnmech.dll"), # "C:\\Users\\daniel\\Repos\\nrnmech.dll", # ("C:\\Users\\Holger\\danielm\\models_dentate\\" # "dentate_gyrus_Santhakumar2005_and_Yim_patterns\\" # "dentategyrusnet2005\\nrnmech.dll"), # ("C:\\Users\\Daniel\\repos\\" # "dentate_gyrus_Santhakumar2005_and_Yim_patterns\\" # "dentategyrusnet2005\\nrnmech.dll"), # ("/home/baris/Python/mechs_7-6_linux/" # "x86_64/.libs/libnrnmech.so")] # for x in dll_files: # if os.path.isfile(x): # dll_dir = x # print("DLL loaded from: " + dll_dir) # h.nrn_load_dll(dll_dir) #number of cells n_grid = 200 n_granule = 2000 n_mossy = 60 n_basket = 24 n_hipp = 24 np.random.seed(seed_3) # seed_3 for connections in the network # Randomly choose target cells for the GridCell lines gauss_gc = stats.norm(loc=1000, scale=input_scale) gauss_bc = stats.norm(loc=12, scale=(input_scale / float(n_granule)) * n_basket) pdf_gc = gauss_gc.pdf(np.arange(n_granule)) pdf_gc = pdf_gc / pdf_gc.sum() pdf_bc = gauss_bc.pdf(np.arange(n_basket)) pdf_bc = pdf_bc / pdf_bc.sum() GC_indices = np.arange(n_granule) start_idc = np.random.randint(0, n_granule - 1, size=n_grid) PP_to_GCs = [] for x in start_idc: curr_idc = np.concatenate((GC_indices[x:n_granule], GC_indices[0:x])) PP_to_GCs.append( np.random.choice(curr_idc, size=100, replace=False, p=pdf_gc)) PP_to_GCs = np.array(PP_to_GCs) BC_indices = np.arange(n_basket) start_idc = np.array(((start_idc / float(n_granule)) * 24), dtype=int) PP_to_BCs = [] for x in start_idc: curr_idc = np.concatenate((BC_indices[x:24], BC_indices[0:x])) PP_to_BCs.append( np.random.choice(curr_idc, size=1, replace=False, p=pdf_bc)) PP_to_BCs = np.array(PP_to_BCs) # generate temporal patterns out of grid cell act profiles as an input for pyDentate # input_grid_out = inhom_poiss(par_traj, n_traj, dt_s=0.0001, seed=seed_2) np.random.seed(seed_3) #seed_3 again for network generation & simulation granule_output = np.empty((n_granule, n_traj), dtype=np.ndarray) mossy_output = np.empty((n_mossy, n_traj), dtype=np.ndarray) basket_output = np.empty((n_basket, n_traj), dtype=np.ndarray) hipp_output = np.empty((n_hipp, n_traj), dtype=np.ndarray) for trj in range(n_traj): nw = net_tunedrev.TunedNetwork(seed_3, input_grid_out[:, trj], PP_to_GCs, PP_to_BCs) # Attach voltage recordings to all cells nw.populations[0].voltage_recording(range(n_granule)) nw.populations[1].voltage_recording(range(n_mossy)) nw.populations[2].voltage_recording(range(n_basket)) nw.populations[3].voltage_recording(range(n_hipp)) # Run the model """Initialization for -2000 to -100""" h.cvode.active(0) dt = 0.1 h.steps_per_ms = 1.0 / dt h.finitialize(-60) h.t = -2000 h.secondorder = 0 h.dt = 10 while h.t < -100: h.fadvance() h.secondorder = 2 h.t = 0 h.dt = 0.1 """Setup run control for -100 to 1500""" h.frecord_init() # Necessary after changing t to restart the vectors while h.t < dur_ms: h.fadvance() print("Done Running") granule_output[:, trj] = np.array( [cell[0].as_numpy() for cell in nw.populations[0].ap_counters]) # mossy_output[:,trj] = np.array([cell[0].as_numpy() for cell in nw.populations[1].ap_counters]) # basket_output[:,trj] = np.array([cell[0].as_numpy() for cell in nw.populations[2].ap_counters]) # hipp_output[:,trj] = np.array([cell[0].as_numpy() for cell in nw.populations[3].ap_counters]) return granule_output, mossy_output, basket_output, hipp_output
def simulate(): h.frecord_init() h.tstop = tstop h.run()
def simulate(tau_facil, tau_rec, stim_freq, celltype, tau_1=0.3, tau_2=0.6, u0=0.078, sampling_interval=0.5, v_clamp=-70.42, sec='proxd'): """Simulates a frequency stimulation of the tmgexp2syn meachnism onto a neuron and measure the conductance at the soma. Parameters ---------- tau_facil : numeric facilitation time constant of the tmgexp2syn mechanism tau_rec : numeric recovery time constant of the tmgexp2syn mechanism stim_freq : numeric stimulation frequency in Hz celltype : ouropy.GenNeuron A class that inherits from ouropy.GenNeuron tau_1 : numeric Synaptic rise time tau_2 : numeric Synaptic decay time u0 : float The u0 parameters as specified in tmgexp2syn sampling_interval : numeric The sampling interval in ms v_clamp : numeric Holding potential of the Returns ------- peaks_norm : ndarray Peak conductances normalized to first peak garr_norm : ndarray Conductance array normalized to first peak """ # Resolve simulation hyperparameters left_pad, right_pad = 50, 100 # in ms simdur = left_pad + right_pad + 10 * (1000 / stim_freq) # Create cell mycell = celltype() # Create synapse syn = h.tmgexp2syn(mycell.get_segs_by_name(sec)[0](0.5)) syn.tau_1 = tau_1 syn.tau_2 = tau_2 syn.tau_facil = tau_facil syn.tau_rec = tau_rec syn.u0 = u0 syn.e = 0 # Create stimulation stim_period_ms = 1000 / stim_freq stim = h.NetStim() stim.interval = stim_period_ms stim.start = left_pad stim.number = 10 nc = h.NetCon(stim, syn) nc.weight[0] = 0.001 # Create voltage clamp c = h.SEClamp(mycell.soma(0.5)) c.dur1 = simdur c.amp1 = v_clamp c.rs = 0.1 # Create recording vector ivec = h.Vector() ivec.record(c._ref_i) # Start simulation sample_period_ms = sampling_interval h.cvode.active(0) h.finitialize(-70.42) h.t = -2000 h.secondorder = 0 h.dt = 10 while h.t < -100: h.fadvance() h.secondorder = 0 h.t = 0 h.dt = sample_period_ms h.steps_per_ms = 1.0 / h.dt h.frecord_init() # Necessary after changing t to restart the vectors while h.t < simdur: h.fadvance() # Get Peaks from output iarr = np.array(ivec) garr = (iarr - iarr[0:50].mean()) / v_clamp stim_dtp = int(np.around(stim.interval / sampling_interval)) pad_dtp = int(left_pad / sampling_interval) t_stim = np.arange(pad_dtp, stim_dtp * 11 + pad_dtp, stim_dtp) #dtp_stim = np.array(t_stim / sampling_interval, dtype=np.int) dtp_stim = np.array(t_stim, dtype=np.int) gvec_split = np.array(np.split(garr, dtp_stim)[1:-1]) peaks = gvec_split.max(axis=1) peaks_norm = peaks / peaks[0] garr_norm = garr / peaks[0] return peaks_norm, garr_norm
def _simulate_single_trial(net): """Simulate one trial.""" from .parallel import rank, nhosts, pc, cvode from neuron import h h.load_file("stdrun.hoc") # Now let's simulate the dipole if rank == 0: print("running on %d cores" % nhosts) # global variables, should be node-independent h("dp_total_L2 = 0.") h("dp_total_L5 = 0.") # Set tstop before instantiating any classes h.tstop = net.params['tstop'] h.dt = net.params['dt'] # simulation duration and time-step h.celsius = net.params['celsius'] # 37.0 - set temperature # We define the arrays (Vector in numpy) for recording the signals t_vec = h.Vector() t_vec.record(h._ref_t) # time recording dp_rec_L2 = h.Vector() dp_rec_L2.record(h._ref_dp_total_L2) # L2 dipole recording dp_rec_L5 = h.Vector() dp_rec_L5.record(h._ref_dp_total_L5) # L5 dipole recording net.move_cells_to_pos() # position cells in 2D grid # sets the default max solver step in ms (purposefully large) pc.set_maxstep(10) # initialize cells to -65 mV, after all the NetCon # delays have been specified h.finitialize() def prsimtime(): print('Simulation time: {0} ms...'.format(round(h.t, 2))) printdt = 10 if rank == 0: for tt in range(0, int(h.tstop), printdt): cvode.event(tt, prsimtime) # print time callbacks h.fcurrent() # set state variables if they have been changed since h.finitialize h.frecord_init() # actual simulation - run the solver pc.psolve(h.tstop) pc.barrier() # these calls aggregate data across procs/nodes pc.allreduce(dp_rec_L2, 1) # combine dp_rec on every node, 1=add contributions together pc.allreduce(dp_rec_L5, 1) # aggregate the currents independently on each proc net.aggregate_currents() # combine net.current{} variables on each proc pc.allreduce(net.current['L5Pyr_soma'], 1) pc.allreduce(net.current['L2Pyr_soma'], 1) pc.barrier() # get all nodes to this place before continuing dpl_data = np.c_[np.array(dp_rec_L2.to_python()) + np.array(dp_rec_L5.to_python()), np.array(dp_rec_L2.to_python()), np.array(dp_rec_L5.to_python())] pc.gid_clear() pc.done() dpl = Dipole(np.array(t_vec.to_python()), dpl_data) if rank == 0: if net.params['save_dpl']: dpl.write('rawdpl.txt') dpl.baseline_renormalize(net.params) dpl.convert_fAm_to_nAm() dpl.scale(net.params['dipole_scalefctr']) dpl.smooth(net.params['dipole_smooth_win'] / h.dt) return dpl, net.spiketimes.to_python(), net.spikegids.to_python()
def __call__(self, input_spikes, bin_size=10, el=1): """ Launch a simulation of a given time with a binary event happening or not in each time bin Parameters ---------- input_spikes: 2-D numpy array of Bool contain the occurence or not of an event. Each line is a set of signals and each column corresponds to a time bin bin_size: float the size of a time bin in ms. el: float elementary weight, it will scale all the weights Comments -------- It seems that when multiple go method are done it does not change the output vector. """ # Set the time to 0 h.t = 0 try: weights = self.weights*el where_what = self.input_locations assert len(self.weights) == len(self.input_locations) except AttributeError: return "Weights or the input_locations not set. Simulation aborted" except AssertionError: print("Weights or the input_locations not match. Set default w") self.weights = np.ones(len(self.input_locations)) # Test if signal and stimulation match. try: assert len(input_spikes) == len(self.input_locations) except AssertionError: print(self.where_what) print(input_spikes) print("Number of input neuron does not match number of synapses") print("Aborting simulation") return # Set the input spike time self.tstims = bin2time(input_spikes, bin_size) self.TSTOP = bin_size * input_spikes.shape[1] tstims = self.tstims # This is to prevent remanescence of the synapse # Otherwise you can become crazy!! if len(self.syn) >= 1: for key in self.syn.keys(): del self.syn[key] # Set the inputs for i, tstim in enumerate(tstims): self.add_stim(where_what[i], name='Stream'+str(i), tstim=tstim, w=weights[i]) # Set the initial membrane potential if not hasattr(self, 'vrest'): self.min_sim() # Record Time record_time = h.Vector() record_time.record(h._ref_t) # Record Voltage self.record_v() # Set the time at zero h.t = 0 # ReInitialise the sections for sec in h.allsec(): h.finitialize(self.vrest, sec) h.fcurrent(sec) h.frecord_init() # Launch a simulation with or without adding spikes if self.spike: # Need to hasck the recording of the data self.data['soma'] = [[]] self.data['soma'][0].append(h.soma.v) refrac_abs = 200 threshold = -40 spk = False refrac = 0 h.t = 0 while h.t < self.TSTOP: h.fadvance() # Spike if voltage cross threshold and no refractoriness if h.soma.v >= threshold and not refrac: h.soma.v = 20 spk = True # If the neuron spiked add one to the refractory period if spk: refrac += 1 # Put the soma back to a reset voltage if refrac == 2: h.soma.v = threshold - 10 # Reset the absolute refrac period if refrac >= refrac_abs: refrac = 0 spk = False self.data['soma'][0].append(h.soma.v) else: while h.t < self.TSTOP: h.fadvance() # Copy time into a vector self.rec_t = np.array(record_time)