def test_get_multi_dipole_potential00(self): neuron.h('forall delete_section()') soma = neuron.h.Section(name='soma') dend1 = neuron.h.Section(name='dend1') dend2 = neuron.h.Section(name='dend2') dend3 = neuron.h.Section(name='dend3') dend4 = neuron.h.Section(name='dend4') dend5 = neuron.h.Section(name='dend5') dend1.connect(soma(0.5), 0) dend2.connect(dend1(1.0), 0) dend3.connect(dend2(1.0), 0) dend4.connect(dend3(1.0), 0) dend5.connect(dend4(1.0), 0) morphology = neuron.h.SectionList() morphology.wholetree() electrode_locs = np.array([[0., 0., 10000.]]) cell, electrode = cell_w_synapse_from_sections_w_electrode(morphology, electrode_locs) sigma = 0.3 t_point = 0 MD_inf = LFPy.InfiniteVolumeConductor(sigma) pot_MD = MD_inf.get_multi_dipole_potential(cell, electrode_locs) pot_cb = electrode.LFP np.testing.assert_almost_equal(pot_MD, pot_cb) np.testing.assert_allclose(pot_MD, pot_cb, rtol=1E-4)
def initModel(h,par,vecpar,recpar, verbose): ''' Initializes the model. Creates the axon and so on. ''' passValuesToNeuron(par,verb=verbose) h('{load_file("MRGnodeHFS.hoc")}') passValuesToNeuron(vecpar,[a for a in vecpar.keys()],verb=verbose) #h('{load_file("nrngui.hoc")}') #h('{load_proc("nrnmainmenu")}') h('{buildModel()}') if verbose: print("Passed parameters and built model.") # insert recorders and record action potential timestamps! segmentsToRecordV = []; segmentsNames = [int(h.intrinsicNode), int(h.HFSreferenceNode), int(h.axonnodes-1)] #segments to record for ii in segmentsNames: segmentsToRecordV.append(h.node[ii](0.5)) rec = None for ii in range(0,len(segmentsToRecordV)): rec = insertRecorders(segmentsToRecordV[ii],{'node'+str(segmentsNames[ii]):'_ref_v'},rec) h.node[int(h.axonnodes-1)].push() apc = h.APCount(h.node[int(h.axonnodes-1)](0.5)) apc.thresh = 0 rec['apc'] = h.Vector() apc.record(rec['apc']) #rec['electrodeWaveform'] = h.rec_electrode if verbose: print("Inserted recorders and APCount. Returning recorders.") ########################################################################## return rec
def passive_soma(quad, show=False): """ Creates the model with basic pyramidal passive properties. """ # Load the hoc into neuron h('xopen(%s)' %quad.hocfile) h.load_file('stdrun.hoc') seclist = list(h.allsec()) for sec in seclist: sec.insert('pas') sec.Ra = 200. # Current injection into soma or tip soma_sec = return_soma_seg(quad, h) stim_loc = 0. stim = h.IClamp(stim_loc, sec=soma_sec) stim.delay = 1 # ms stim.dur = 1 # ms stim.amp = 20 # nA # Run sim and record data (v, labels) = ez_record(h) # PyNeuron to record all compartments t, I = h.Vector(), h.Vector() t.record(h._ref_t) I.record(stim._ref_i) h.init() h.tstop = 10 # s? h.run() v = ez_convert(v) # Convert v to numpy 2D array # If show, plot, else just return v if show:
def setup_sections(self): start = h.startsw() ################################################### # set up sections self.sections = [] # old style, but it is need for section_name in hoc h(self.section_def_template % (self.name, len(self.tree))) for sec in h.allsec(): self.sections.append(sec) ################################################### # connect sections for i,sec in enumerate(self.sections): parent = self.tree[i] #print "%d to %d" % (i, tree[i]) if(parent != 0): sec.connect(self.sections[parent-1], 1, 0) self.num_compartment = 0 for sec in h.allsec(): self.num_compartment += 1 self.setup_time += h.startsw() - start
def alloc_synapse_ff(self,r,post_syn,cellind,k,gidn,i): NCELL=self.NCELL SIZE=self.SIZE COMM = self.COMM RANK=self.RANK #from neuron import h h=self.h pc=h.ParallelContext() polarity = 0 polarity=int(h.Cell[int(cellind)].polarity) if polarity==1: #TODO pickle load the graphs here instead of making them manually. self.ecm[i][gidn] = self.ecm[i][gidn] + 1 self.ecg.add_edge(i,gidn,weight=r/0.4) assert np.sum(self.ecm)!=0 else: self.icm[i][gidn] = self.icm[i][gidn] + 1 self.icg.add_edge(i,gidn,weight=r/0.4) assert np.sum(self.icm)!=0 #TODO Add other edge attributes like secnames etc. print post_syn h('objref syn_') h(post_syn) syn_=h.syn_ h.syn_.cid=i h.Cell[cellind].ampalist.append(h.syn_) h.Cell[cellind].div.append(k['gid']) h.Cell[cellind].gvpre.append(k['gid']) nc=pc.gid_connect(k['gid'],syn_) nc.threshold = -20 nc.delay=1+r/0.4 nc.weight[0]=r/0.4 self.nclist.append(nc)
def test_current_balance_synapse_at_section_end(): h('synapse.loc(0)') cell.initialize(dt=0.025) t, I = cell.integrate(1) coord = cell.get_seg_coords() assert (np.abs(total_current(coord, I))<1e-6).all()
def test_current_balance_synapse_in_segment(): h('synapse.loc(0.1)') h('soma {insert pas}') cell.initialize(dt=0.025) t, I = cell.integrate(1) coord = cell.get_seg_coords() assert (np.abs(total_current(coord, I))<1e-6).all()
def useSTDP(self, mechanism, parameters, ddf): """ Set this connection to use spike-timing-dependent plasticity. `mechanism` -- the name of an NMODL mechanism that modifies synaptic weights based on the times of pre- and post-synaptic spikes. `parameters` -- a dictionary containing the parameters of the weight- adjuster mechanism. `ddf` -- dendritic delay fraction. If ddf=1, the synaptic delay `d` is considered to occur entirely in the post-synaptic dendrite, i.e., the weight adjuster receives the pre- synaptic spike at the time of emission, and the post- synaptic spike a time `d` after emission. If ddf=0, the synaptic delay is considered to occur entirely in the pre-synaptic axon. """ self.ddf = ddf self.weight_adjuster = getattr(h, mechanism)(0.5) self.pre2wa = state.parallel_context.gid_connect(int(self.source), self.weight_adjuster) self.pre2wa.threshold = self.nc.threshold self.pre2wa.delay = self.nc.delay * (1-ddf) self.pre2wa.weight[0] = 1 # directly create NetCon as wa is on the same machine as the post-synaptic cell self.post2wa = h.NetCon(self.target._cell.source, self.weight_adjuster, sec=self.target._cell.source_section) self.post2wa.threshold = 1 self.post2wa.delay = self.nc.delay * ddf self.post2wa.weight[0] = -1 for name, value in parameters.items(): setattr(self.weight_adjuster, name, value) # setpointer i = len(h.plastic_connections) h.plastic_connections.append(self) h('setpointer plastic_connections._[%d].weight_adjuster.wsyn, plastic_connections._[%d].nc.weight' % (i,i))
def test_calc_potential_from_multi_dipoles01(self): neuron.h('forall delete_section()') soma = neuron.h.Section(name='soma') dend1 = neuron.h.Section(name='dend1') dend2 = neuron.h.Section(name='dend2') dend1.connect(soma(0.5), 0) dend2.connect(dend1(1.0), 0) morphology = neuron.h.SectionList() morphology.wholetree() radii = [300, 400, 500, 600] sigmas = [0.3, 1.5, 0.015, 0.3] electrode_locs = np.array([[0., 0., 290.], [10., 90., 300.], [-90, 50., 400.], [110.3, -100., 500.]]) cell = cell_w_synapse_from_sections(morphology) t_point = -1 MD_4s = LFPy.FourSphereVolumeConductor(radii, sigmas, electrode_locs) dipoles, dipole_locs = cell.get_multi_current_dipole_moments() p = dipoles[:,t_point,:] Np = p.shape[0] Nt = 1 Ne = electrode_locs.shape[0] pot_MD = MD_4s.calc_potential_from_multi_dipoles(cell)[:,t_point] pot_sum = np.zeros((Ne, Nt)) for i in range(Np): dip = np.array([p[i]]) dip_loc = dipole_locs[i] fs = LFPy.FourSphereVolumeConductor(radii, sigmas, electrode_locs) pot = fs.calc_potential(dip, dip_loc) pot_sum += pot pot_sum = pot_sum.reshape(4) np.testing.assert_almost_equal(pot_MD, pot_sum) np.testing.assert_allclose(pot_MD, pot_sum, rtol=1E-4)
def test_point_process_coord(): h('synapse.loc(0.15)') h('access soma') x, y, z = cell.get_pp_coord(h.synapse) assert x == 1.5 assert y == 0 assert z == 0
def test_get_point_processes(): h('synapse.loc(0.15)') h('access soma') pps = cell.get_point_processes() assert len(pps)==1 assert pps[0][0].same(h.synapse) assert pps[0][1] == 1.5
def load_morphology(filename): swc = h.Import3d_SWC_read() swc.input(filename) imprt = h.Import3d_GUI(swc, 0) h("objref this") imprt.instantiate(h.this)
def _do_callback(self): if callable(self._callable): self._callable() else: h(self._callable) if self._thread is not None: self.start()
def create_head(self, neck, head_vol, big_spine): """Create the head of the spine and populate it with the right channels""" name_sec = self.id + "_head" h("create " + name_sec) head = getattr(h, name_sec) if big_spine: head.L = 1 head.diam = 1.175 r = head.diam/2. self.head_vol = math.pi * r * r * head.L else: head.L = 0.5 head.diam = math.sqrt(head_vol / (head.L * math.pi) ) * 2 self.Ra = 150.0 head.nseg = 1 head.connect(neck) #head.insert("pas") head.insert("kir") head.insert("can") head.insert("caq") head.insert("car") head.insert("skkca") h.factors_caltrack() head.insert("caltrack") h.factors_catrack() head.insert("catrack") return head
def alloc_synapse(self,r,h,sec,seg,cellind,secnames,k,i,gidn): ''' Allocate a synaptic cleft from exhuastive collision detection. ''' NCELL=self.NCELL SIZE=self.SIZE COMM = self.COMM RANK=self.RANK from neuron import h pc=h.ParallelContext() h=self.h self.visited[i][gidn] = self.visited[i][gidn] + 1 if r < 2.5: #2.5 micro metres. polarity = 0 polarity=int(h.Cell[int(cellind)].polarity) h('objref syn_') if int(polarity) == int(0): post_syn = secnames + ' ' + 'syn_ = new FastInhib(' + str(seg.x) + ')' #post_syn = secnames + ' ' + 'syn_ = new GABAa(' + str(seg.x) + ')' self.icm[i][gidn] = self.icm[i][gidn] + 1 self.icg.add_edge(i,gidn,weight=r/0.4) self.icg[i][gidn]['post_loc']=secnames self.icg[i][gidn]['pre_loc']=k['secnames'] assert np.sum(self.icm)!=0 else: if (k['gid']%2==0): #TODO Find standard open source brain affiliated code for NMDA synapse post_syn = secnames + ' ' + 'syn_ = new AmpaNmda(' + str(seg.x) + ')' self.ecm[i][gidn] = self.ecm[i][gidn] + 1 self.ecg.add_edge(i,gidn,weight=r/0.4) self.ecg[i][gidn]['post_loc']=secnames self.ecg[i][gidn]['pre_loc']=k['secnames'] self.seclists.append(secnames) assert np.sum(self.ecm)!=0 else: #TODO Find standard open source brain affiliated code for NMDA synapse post_syn = secnames + ' ' + 'syn_ = new ExpSid(' + str(seg.x) + ')' self.ecm[i][gidn] = self.ecm[i][gidn] + 1 self.ecg.add_edge(i,gidn,weight=r/0.4) self.ecg[i][gidn]['post_loc']=secnames self.ecg[i][gidn]['pre_loc']=k['secnames'] self.seclists.append(secnames) assert np.sum(self.ecm)!=0 h(post_syn) print post_syn self.synapse_list.append((r,post_syn,cellind,k,gidn,i)) syn_=h.syn_ h.syn_.cid=i h.Cell[cellind].ampalist.append(h.syn_) h.Cell[cellind].div.append(k['gid']) h.Cell[cellind].gvpre.append(k['gid']) nc=pc.gid_connect(k['gid'],syn_) nc.threshold = -20 nc.delay=1+r/0.4 nc.weight[0]=r/0.4 self.nclist.append(nc)
def measure_fi (gid, pop_name, v_init, env, cell_dict={}): biophys_cell = init_biophys_cell(env, pop_name, gid, register_cell=False, cell_dict=cell_dict) hoc_cell = biophys_cell.hoc_cell soma = list(hoc_cell.soma)[0] h.dt = 0.025 prelength = 1000.0 mainlength = 2000.0 tstop = prelength+mainlength stimdur = 1000.0 stim1 = h.IClamp(soma(0.5)) stim1.delay = prelength stim1.dur = stimdur stim1.amp = 0.2 h('objref tlog, Vlog, spikelog') h.tlog = h.Vector() h.tlog.record (h._ref_t) h.Vlog = h.Vector() h.Vlog.record (soma(0.5)._ref_v) h.spikelog = h.Vector() nc = biophys_cell.spike_detector nc.record(h.spikelog) h.tstop = tstop frs = [] stim_amps = [stim1.amp] for it in range(1, 9): neuron_utils.simulate(v_init, prelength, mainlength) logger.info("fi_test: stim1.amp = %g spikelog.size = %d\n" % (stim1.amp, h.spikelog.size())) stim1.amp = stim1.amp + 0.1 stim_amps.append(stim1.amp) frs.append(h.spikelog.size()) h.spikelog.clear() h.tlog.clear() h.Vlog.clear() results = {'FI_curve_amplitude': np.asarray(stim_amps, dtype=np.float32), 'FI_curve_frequency': np.asarray(frs, dtype=np.float32) } env.synapse_attributes.del_syn_id_attr_dict(gid) if gid in env.biophys_cells[pop_name]: del env.biophys_cells[pop_name][gid] return results
def test_Network_04(self): cellParameters = dict( morphology=os.path.join(LFPy.__path__[0], 'test', 'ball_and_sticks_w_lists.hoc'), templatefile=os.path.join(LFPy.__path__[0], 'test', 'ball_and_stick_template.hoc'), templatename='ball_and_stick_template', templateargs=None, passive=True, dt=2**-3, tstop=100, delete_sections=False, ) synapseParameters = dict(idx=0, syntype='Exp2Syn', weight=0.002, tau1=0.1, tau2=0.1, e=0) populationParameters = dict( CWD=None, CELLPATH=None, Cell=LFPy.NetworkCell, cell_args = cellParameters, pop_args = dict( radius=100, loc=0., scale=20.), rotation_args = dict(x=0, y=0), POP_SIZE = 1, name = 'test', ) networkParameters = dict( dt=2**-3, tstart=0., tstop=100., v_init=-70., celsius=6.3, OUTPUTPATH='tmp_testNetworkPopulation' ) # set up network = LFPy.Network(**networkParameters) network.create_population(**populationParameters) cell = network.populations['test'].cells[0] # create synapses synlist = [] numsynapses = 2 for i in range(numsynapses): synlist.append(LFPy.Synapse(cell=cell, **synapseParameters)) synlist[-1].set_spike_times(np.array([10+(i*10)])) network.simulate() # test that the input results in the correct amount of PSPs np.testing.assert_equal(ss.argrelextrema(cell.somav, np.greater)[0].size, numsynapses) # clean up network.pc.gid_clear() os.system('rm -r tmp_testNetworkPopulation') neuron.h('forall delete_section()')
def conduct_parallel_NEURON(population_name, last_point, N_index_glob, N_index, Ampl_scale, t_steps, n_segments, dt, tstop, n_pulse, v_init, output): os.chdir("..") # nodes=[] # for point_inx in range(n_segments): # nodes_point_in_time=np.load(os.environ['PATIENTDIR']+'/Points_in_time/Signal_t_conv'+str(point_inx+N_index*n_segments+last_point)+'.npy') #get solution for each compartment in time for one neuron # nodes.append(nodes_point_in_time*(1000)*Ampl_scale) #convert to mV # nodes=np.asarray(nodes) # nodes = nodes.ravel() # # V_art=np.zeros((n_segments,t_steps),float) # # for i in range(n_segments): # V_art[i,:]=nodes[(i*t_steps):((i*t_steps)+t_steps)] #to distinguish axons in different populations, we indexed them with the global index of the last compartment axon_in_time = np.load(os.environ['PATIENTDIR'] + '/Axons_in_time/Signal_t_conv' + str(n_segments - 1 + N_index * n_segments + last_point) + '.npy') V_art = np.zeros((n_segments, t_steps), float) for i in range(n_segments): V_art[i, :] = axon_in_time[i, :] * (-1000) * Ampl_scale #convert to mV #only if we want to save potential in time on axons #np.save('Field_on_axons_in_time/'+str(population_name)+'axon_'+str(N_index_glob), V_art) os.chdir("Axon_files/") n.h('{load_file("axon4pyfull.hoc")}') n.h.deletenodes() n.h.createnodes() n.h.dependent_var() n.h.initialize() n.h.setupAPWatcher_0() # 'left' end of axon n.h.setupAPWatcher_1() # 'right' end of axon n.h.dt = dt n.h.tstop = tstop n.h.n_pulse = n_pulse n.h.v_init = v_init for i in range(0, V_art.shape[0]): n.h.wf[i] = n.h.Vector(V_art[ i, :]) # feed the potential in time for compartment i to NEURON n.h.stimul() n.h.run() spike = n.h.stoprun - 0.5 if spike == 0.5: return output.put([N_index_glob, N_index]) else: return output.put([N_index_glob, -1])
def _setup_plasticity(self, synapse_type, parameters): """ Set this connection to use spike-timing-dependent plasticity. `mechanism` -- the name of an NMODL mechanism that modifies synaptic weights based on the times of pre- and post-synaptic spikes. `parameters` -- a dictionary containing the parameters of the weight- adjuster mechanism. """ mechanism = synapse_type.model self.weight_adjuster = getattr(h, mechanism)(0.5) if synapse_type.postsynaptic_variable == 'spikes': parameters['allow_update_on_post'] = int( False) # for compatibility with NEST self.ddf = parameters.pop('dendritic_delay_fraction') # If ddf=1, the synaptic delay # `d` is considered to occur entirely in the post-synaptic # dendrite, i.e., the weight adjuster receives the pre- # synaptic spike at the time of emission, and the post- # synaptic spike a time `d` after emission. If ddf=0, the # synaptic delay is considered to occur entirely in the # pre-synaptic axon. elif synapse_type.postsynaptic_variable is None: self.ddf = 0 else: raise NotImplementedError( "Only post-synaptic-spike-dependent mechanisms available for now." ) self.pre2wa = state.parallel_context.gid_connect( int(self.presynaptic_cell), self.weight_adjuster) self.pre2wa.threshold = self.nc.threshold self.pre2wa.delay = self.nc.delay * (1 - self.ddf) if self.pre2wa.delay > 1e-9: self.pre2wa.delay -= 1e-9 # we subtract a small value so that the synaptic weight gets updated before it is used. if synapse_type.postsynaptic_variable == 'spikes': # directly create NetCon as wa is on the same machine as the post-synaptic cell self.post2wa = h.NetCon( self.postsynaptic_cell._cell.source, self.weight_adjuster, sec=self.postsynaptic_cell._cell.source_section) self.post2wa.threshold = 1 self.post2wa.delay = self.nc.delay * self.ddf self.post2wa.weight[0] = -1 self.pre2wa.weight[0] = 1 else: self.pre2wa.weight[0] = self.nc.weight[0] parameters.pop('x', None) # for the Tsodyks-Markram model parameters.pop( 'y', None) # would be better to actually use these initial values for name, value in parameters.items(): setattr(self.weight_adjuster, name, value) if mechanism == 'TsodyksMarkramWA': # or could assume that any weight_adjuster parameter called "tau_syn" should be set like this self.weight_adjuster.tau_syn = self.nc.syn().tau # setpointer i = len(h.plastic_connections) h.plastic_connections.append(self) h('setpointer plastic_connections._[%d].weight_adjuster.wsyn, plastic_connections._[%d].nc.weight' % (i, i))
def _setup_plasticity(self, synapse_type, parameters): """ Set this connection to use spike-timing-dependent plasticity. `mechanism` -- the name of an NMODL mechanism that modifies synaptic weights based on the times of pre- and post-synaptic spikes. `parameters` -- a dictionary containing the parameters of the weight- adjuster mechanism. """ mechanism = synapse_type.model self.weight_adjuster = getattr(h, mechanism)(0.5) if synapse_type.postsynaptic_variable == "spikes": parameters["allow_update_on_post"] = int(False) # for compatibility with NEST self.ddf = parameters.pop("dendritic_delay_fraction") # If ddf=1, the synaptic delay # `d` is considered to occur entirely in the post-synaptic # dendrite, i.e., the weight adjuster receives the pre- # synaptic spike at the time of emission, and the post- # synaptic spike a time `d` after emission. If ddf=0, the # synaptic delay is considered to occur entirely in the # pre-synaptic axon. elif synapse_type.postsynaptic_variable is None: self.ddf = 0 else: raise NotImplementedError("Only post-synaptic-spike-dependent mechanisms available for now.") self.pre2wa = state.parallel_context.gid_connect(int(self.presynaptic_cell), self.weight_adjuster) self.pre2wa.threshold = self.nc.threshold self.pre2wa.delay = self.nc.delay * (1 - self.ddf) if self.pre2wa.delay > 1e-9: self.pre2wa.delay -= ( 1e-9 ) # we subtract a small value so that the synaptic weight gets updated before it is used. if synapse_type.postsynaptic_variable == "spikes": # directly create NetCon as wa is on the same machine as the post-synaptic cell self.post2wa = h.NetCon( self.postsynaptic_cell._cell.source, self.weight_adjuster, sec=self.postsynaptic_cell._cell.source_section, ) self.post2wa.threshold = 1 self.post2wa.delay = self.nc.delay * self.ddf self.post2wa.weight[0] = -1 self.pre2wa.weight[0] = 1 else: self.pre2wa.weight[0] = self.nc.weight[0] parameters.pop("x", None) # for the Tsodyks-Markram model parameters.pop("y", None) # would be better to actually use these initial values for name, value in parameters.items(): setattr(self.weight_adjuster, name, value) if ( mechanism == "TsodyksMarkramWA" ): # or could assume that any weight_adjuster parameter called "tau_syn" should be set like this self.weight_adjuster.tau_syn = self.nc.syn().tau # setpointer i = len(h.plastic_connections) h.plastic_connections.append(self) h("setpointer plastic_connections._[%d].weight_adjuster.wsyn, plastic_connections._[%d].nc.weight" % (i, i))
def __init__(self): """ Create an `FinitializeHandler` object in Hoc, which will call the `_initialize()` method when NEURON is initialized. """ h('objref initializer') h.initializer = self self.fih = h.FInitializeHandler(1, "initializer._initialize()") self.clear()
def record_spiketimes(sec, pos=0.5, threshold=-20.0): if not hasattr(h, 'nil'): h('objref nil') sec.push() nc = h.NetCon(sec(0.5)._ref_v, h.nil, threshold, 0.0, 1.0) h.pop_section() vec = h.Vector() nc.record(vec) return nc, vec
def hoc_execute_quiet(arg): with open(os.devnull, 'wb') as null: fd = sys.stdout.fileno() keep = os.dup(fd) sys.stdout.flush() os.dup2(null.fileno(), fd) h(arg) sys.stdout.flush() os.dup2(keep, fd)
def destroy(self): """ Takes care that neuron objects and python objects reffering to the cell are destroyed. At this point it actually destroys all the sections. """ neuron.h('objref tuft') super(self.__class__, self).destroy()
def reinit_diam(sec, diam_bounds): """ For a node associated with a hoc section that is a tapered cylinder, every time the spatial resolution of the section (nseg) is changed, the section diameters must be reinitialized. This method checks the node's content dictionary for diameter boundaries and recalibrates the hoc section associated with this node. """ if diam_bounds is not None: diam1, diam2 = diam_bounds h(f'diam(0:1)={diam1}:{diam2}', sec=sec)
def connectgjs(env): rank = int(env.pc.id()) nhosts = int(env.pc.nhost()) datasetPath = os.path.join(env.datasetPrefix, env.datasetName) gapjunctions = env.gapjunctions if env.gapjunctionsFile is None: gapjunctionsFilePath = None else: gapjunctionsFilePath = os.path.join(datasetPath, env.gapjunctionsFile) if gapjunctions is not None: h('objref gjlist') h.gjlist = h.List() if env.verbose: if env.pc.id() == 0: print gapjunctions datasetPath = os.path.join(env.datasetPrefix, env.datasetName) (graph, a) = bcast_graph(env.comm, gapjunctionsFilePath, attributes=True) ggid = 2e6 for name in gapjunctions.keys(): if env.verbose: if env.pc.id() == 0: print "*** Creating gap junctions %s" % name prj = graph[name] attrmap = a[name] weight_attr_idx = attrmap['Weight'] + 1 dstbranch_attr_idx = attrmap['Destination Branch'] + 1 dstsec_attr_idx = attrmap['Destination Section'] + 1 srcbranch_attr_idx = attrmap['Source Branch'] + 1 srcsec_attr_idx = attrmap['Source Section'] + 1 for destination in sorted(prj.keys()): edges = prj[destination] sources = edges[0] weights = edges[weight_attr_idx] dstbranches = edges[dstbranch_attr_idx] dstsecs = edges[dstsec_attr_idx] srcbranches = edges[srcbranch_attr_idx] srcsecs = edges[srcsec_attr_idx] for i in range(0, len(sources)): source = sources[i] srcbranch = srcbranches[i] srcsec = srcsecs[i] dstbranch = dstbranches[i] dstsec = dstsecs[i] weight = weights[i] if env.pc.gid_exists(source): h.mkgap(env.pc, h.gjlist, source, srcbranch, srcsec, ggid, ggid + 1, weight) if env.pc.gid_exists(destination): h.mkgap(env.pc, h.gjlist, destination, dstbranch, dstsec, ggid + 1, ggid, weight) ggid = ggid + 2 del graph[name]
def test_ste(): m1 = model() # one state ste with two self transitions var = m1["s"](0.5)._ref_v thresh1 = h.ref(-50) thresh2 = h.ref(-10) result = [] ste = h.StateTransitionEvent(1) ste.transition(0, 0, var, thresh1, (act, (1, m1, thresh1, result))) ste.transition(0, 0, var, thresh2, (act, (2, m1, thresh2, result))) fih = h.FInitializeHandler((on_finit, (ste, result))) run(5) print("final v=%g" % m1["s"](0.5).v) chk_result(2, result, m1) h.cvode_active(1) run(20) chk_result(2, result, m1) h.cvode_active(1) h.cvode.condition_order(2) run(5) chk_result(2, result, m1) h.cvode.condition_order(1) h.cvode_active(0) # ste associated with point process del fih, ste ste = h.StateTransitionEvent(2, m1["ic"]) fih = h.FInitializeHandler((on_finit, (ste, result))) run(5) # transition with hoc callback h("""proc foo() { printf("foo called at t=%g\\n", t) }""") thresh3 = h.ref(-30) ste.transition(0, 0, var, thresh3, "foo()") run(5) # transition with hoc callback in hoc object h(""" begintemplate FooSTEtest objref this proc foo() { printf("foo in %s called at t=%g\\n", this, t) } endtemplate FooSTEtest """) thresh4 = h.ref(-20) obj = h.FooSTEtest() ste.transition(0, 0, var, thresh4, "foo()", obj) run(5) del ste, fih assert h.List("StateTransitionEvent").count() == 0 assert h.List("FInitializeHandler").count() == 0
def test_Network_01(self): cellParameters = dict( morphology=os.path.join(LFPy.__path__[0], 'test', 'ball_and_sticks_w_lists.hoc'), templatefile=os.path.join(LFPy.__path__[0], 'test', 'ball_and_stick_template.hoc'), templatename='ball_and_stick_template', templateargs=None, passive=False, dt=2**-3, tstop=100, delete_sections=False, ) populationParameters = dict( CWD=None, CELLPATH=None, Cell=LFPy.NetworkCell, cell_args=cellParameters, pop_args=dict(radius=100, loc=0., scale=20.), rotation_args=dict(x=0, y=0), POP_SIZE=4, name='test', ) networkParameters = dict(dt=2**-3, tstart=0., tstop=100., v_init=-65., celsius=6.3, OUTPUTPATH='tmp_testNetworkPopulation') # set up network = LFPy.Network(**networkParameters) network.create_population(**populationParameters) connectivity = network.get_connectivity_rand(pre='test', post='test', connprob=0.5) # connect and run sim network.connect(pre='test', post='test', connectivity=connectivity) SPIKES, LFP, P = network.simulate(rec_current_dipole_moment=True) # test output for population in network.populations.values(): for cell in population.cells: self.assertTrue(np.all(cell.somav == network.v_init)) self.assertTrue(np.all(P['test'] == 0.)) self.assertTrue(P.shape[0] == cell.somav.size) self.assertTrue(len(LFP) == 0) network.pc.gid_clear() os.system('rm -r tmp_testNetworkPopulation') for population in network.populations.values(): for cell in population.cells: cell.strip_hoc_objects() neuron.h('forall delete_section()')
def run_single_test(cell_params, input_array, input_idx, hold_potential, use_channels, sim_idx): cell_params.update({ 'v_init': hold_potential, 'custom_fun': [active_declarations], # will execute this function 'custom_fun_args': [{ 'use_channels': use_channels, 'hold_potential': hold_potential }] }) neuron.h('forall delete_section()') cell = LFPy.Cell(**cell_params) noiseVec = neuron.h.Vector(input_array) i = 0 syn = None for sec in cell.allseclist: for seg in sec: if i == input_idx: print "Input i" \ "nserted in ", sec.name() syn = neuron.h.ISyn(seg.x, sec=sec) i += 1 if type(syn) == type(None): raise RuntimeError("Wrong stimuli index") syn.dur = 1E9 syn.delay = 0 noiseVec.play(syn._ref_amp, cell.timeres_NEURON) figfolder = 'verifications' if not os.path.isdir(figfolder): os.mkdir(figfolder) sim_params = {'rec_vmem': True, 'rec_imem': True, 'rec_variables': []} cell.simulate(**sim_params) simfolder = 'simresults' if not os.path.isdir(simfolder): os.mkdir(simfolder) simname = join(simfolder, '%d' % input_idx) if len(use_channels) == 0: simname += '_passive' else: for ion in use_channels: simname += '_%s' % ion simname += '_%+d' % hold_potential simname += '_sim_%d' % sim_idx savedata(cell, simname, input_idx) # recreate_Hu_figs(cell, input_idx, idx_list, cell_params, figfolder) plot_resonances(cell, input_idx, 0.01, [0, 460, 565, 451, 728, 303], cell_params, figfolder) del cell del noiseVec del syn
def insert_glutamate_stim(cell, section = 'apic[63]', site = 0.5): gmaxS=20 neuron.h('access %s' %section) glut_syn = neuron.h.glutamate(site) glut_syn.delay = 50 glut_syn.ntar = 1 glut_syn.gmax = gmaxS glut_syn.Nspike=2 glut_syn.Tspike=20 return glut_syn
def create_graphs(): h('objref py') h.py = h.PythonObject() # lets Hoc access Python h.nrnmainmenu() h.nrncontrolmenu() h.steps_per_ms = 1.0/DT # adding graphs for id in NEURONS_TO_PLOT: addgraph(-80, 40, "py.neurons[%d]._cell.seg.v" % id, 4)
def insert_glutamate_stim(cell, section="apic[63]", site=0.5): gmaxS = 10 neuron.h("access %s" % section) glut_syn = neuron.h.glutamate(site) glut_syn.delay = 50 glut_syn.ntar = 1.3 glut_syn.gmax = gmaxS glut_syn.Nspike = 3 glut_syn.Tspike = 20 return glut_syn
def compare_diam(filename, param_list=None): """Change distal dendrite's diameter""" diam_list = param_list if not diam_list: diam_list = [0.5, 1, 1.5, 2] print("diam_list:{}".format(diam_list)) load_file(filename) for diam in diam_list: h("""ldend.diam = {}""".format(diam)) save_run("{}_{}".format(filename, diam))
def hoc_setup(): with open(os.devnull, 'wb') as null: fd = sys.stdout.fileno() keep = os.dup(fd) sys.stdout.flush() os.dup2(null.fileno(), fd) neuron.h('load_file("stdrun.hoc")') sys.stdout.flush() os.dup2(keep, fd)
def test_soma(): h("""create soma""") assert h.soma is not None h.soma.L = 5.6419 h.soma.diam = 5.6419 assert h.soma.L == 5.6419 assert h.soma.diam == 5.6419
def query_neuron(lst, model_file): # MOCKUP h.load_file(model_file) values = [] aa = 0 for item in lst: h('aa = ' + item) val = float(h.aa) values.append(val) print(f"par is {item} values is {val}") return values
def getOrig(fileName): nrn.h.paramsFile = fileName nrn.h.psize = 1 nrn.h("pmat = new Matrix(psize, nparams)") nrn.h("readMatrix(paramsFile, pmat)") nrn.h("runMatrix(pmat,stims)") nrn.h("print matOut") nrn.h("matOut = matOut.to_vector()") orig_volts = nrn.h.matOut.to_python() return orig_volts
def setpointers(self): self.caller.interpCoordinates.getSecRefs() print("hello") for sec in h.allsec(): if h.ismembrane("xtra", sec=sec) and h.ismembrane("extracellular", sec=sec): # print(sec) # should be a way to do this without resortin to this ugly str coding but fine for now neuron.h("for (x,0){ setpointer ex_xtra(x), e_extracellular(x) }")
def __init__(self): ############################# MORPHOLOGY ############################## h("GJ = 1") # 0 for no gap-junctions between GoCs # 0 or 1, GJ must be set prior to loading network.hoc h.xopen("network.hoc") # Within it is the function Goc() which # below are the components set as attribute to this python class self.GrC = h.GrC # len(h.GrC) -> 8100 self.GoC = h.GoC # len(h.GoC) -> 225 self.MF = h.fiber # len(h.fiber) -> 900
def get_ggn(fname): with h5.File(fname, 'r') as fd: ggn_model = fd['/celltemplate'].value.decode('utf-8') cellname = [line for line in ggn_model.split('\n') if 'begintemplate' in line] rest = cellname[0].partition('begintemplate')[-1] cellname = rest.split()[0] if not hasattr(h, cellname): h(ggn_model) return eval('h.{}()'.format(cellname))
def test_soma(): h('''create soma''') assert h.soma is not None h.soma.L = 5.6419 h.soma.diam = 5.6419 assert h.soma.L == 5.6419 assert h.soma.diam == 5.6419
def __init__(self): self.x = self.y = self.z = 0 hoc_file = "..\\mn_geometries\\burke_mn_2 - Copy" hoc_command = "{xopen(" + hoc_command + ")}" h(hoc_command) self.build_topology() self.build_subsets() self.define_geometry() self.define_biophysics()
def show_plot(quad): """ Plot the thing. """ h('xopen(quad.hocfile)') plt.figure(figsize=(7,7)) shapeax = plt.subplot(111, projection='3d') shapeax.view_init(75,66) shapeplot(h,shapeax) plt.show() return
def test_Network_01(self): cellParameters = dict( morphology=os.path.join(LFPy.__path__[0], 'test', 'ball_and_sticks_w_lists.hoc'), templatefile=os.path.join(LFPy.__path__[0], 'test', 'ball_and_stick_template.hoc'), templatename='ball_and_stick_template', templateargs=None, passive=False, dt=2**-3, tstop=100, delete_sections=False, ) populationParameters = dict( CWD=None, CELLPATH=None, Cell=LFPy.NetworkCell, cell_args = cellParameters, pop_args = dict( radius=100, loc=0., scale=20.), rotation_args = dict(x=0, y=0), POP_SIZE = 4, name = 'test', ) networkParameters = dict( dt=2**-3, tstart=0., tstop=100., v_init=-65., celsius=6.3, OUTPUTPATH='tmp_testNetworkPopulation' ) # set up network = LFPy.Network(**networkParameters) network.create_population(**populationParameters) connectivity = network.get_connectivity_rand(pre='test', post='test', connprob=0.5) # connect and run sim network.connect(pre='test', post='test', connectivity=connectivity) SPIKES, LFP, P = network.simulate(rec_current_dipole_moment=True) # test output for population in network.populations.values(): for cell in population.cells: self.assertTrue(np.all(cell.somav == network.v_init)) self.assertTrue(np.all(P['test'] == 0.)) self.assertTrue(P.shape[0] == cell.somav.size) self.assertTrue(len(LFP) == 0) network.pc.gid_clear() os.system('rm -r tmp_testNetworkPopulation') neuron.h('forall delete_section()')
def insertchans(): h.tstop = 1e3 for vals in thalDict.values(): for ce in vals['cel']: ce.soma[0].insert('hh2nafjr') ce.soma[0].gnabar_hh2nafjr = 0.0 for ce in thalDict['RE']['cel']: sec = ce.soma[0] for mech in it2l: ce.soma[0].insert(mech) h('%s.gcabar_%s = 0.0' % (str(sec), mech))
def measure_passive (gid, pop_name, v_init, env, prelength=1000.0, mainlength=2000.0, stimdur=500.0, cell_dict={}): biophys_cell = init_biophys_cell(env, pop_name, gid, register_cell=False, cell_dict=cell_dict) hoc_cell = biophys_cell.hoc_cell h.dt = env.dt tstop = prelength+mainlength soma = list(hoc_cell.soma)[0] stim1 = h.IClamp(soma(0.5)) stim1.delay = prelength stim1.dur = stimdur stim1.amp = -0.1 h('objref tlog, Vlog') h.tlog = h.Vector() h.tlog.record (h._ref_t) h.Vlog = h.Vector() h.Vlog.record (soma(0.5)._ref_v) h.tstop = tstop Rin = h.rn(hoc_cell) neuron_utils.simulate(v_init, prelength, mainlength) ## compute membrane time constant vrest = h.Vlog.x[int(h.tlog.indwhere(">=",prelength-1))] vmin = h.Vlog.min() vmax = vrest ## the time it takes the system's step response to reach 1-1/e (or ## 63.2%) of the peak value amp23 = 0.632 * abs (vmax - vmin) vtau0 = vrest - amp23 tau0 = h.tlog.x[int(h.Vlog.indwhere ("<=", vtau0))] - prelength results = {'Rin': np.asarray([Rin], dtype=np.float32), 'vmin': np.asarray([vmin], dtype=np.float32), 'vmax': np.asarray([vmax], dtype=np.float32), 'vtau0': np.asarray([vtau0], dtype=np.float32), 'tau0': np.asarray([tau0], dtype=np.float32) } env.synapse_attributes.del_syn_id_attr_dict(gid) if gid in env.biophys_cells[pop_name]: del env.biophys_cells[pop_name][gid] return results
def __init__(self): h("objref cvode") # initialize multiple order variable time step h("cvode = new CVode()" ) # integration method as it is called in hoc file h.xopen("start.hoc") # nsyn1 = 4 at line 11 # ncells = 1 at line 79 # nmossy = 4 at line 80 # Notice that one should try to have nmossy = nsyn1 =/= NumSyn (synapse/MF) self.cell = h.GrCell[0] # len(h.GrCell) -> 1 self.mossy = h.Mossy # len(h.Mossy) -> 4
def setparams(params): params_copy = params.copy() keys = params.keys() for ikey in range(0, len(keys)): params_copy[keys[ikey]] = params[keys[ikey]] * defVals[keys[ikey]] print "setparams: params_copy = " + str(params_copy) for ikey in range(0, len(keys)): key = keys[ikey] print(key + " = " + str(params_copy[key])) h(key + " = " + str(params_copy[key])) h("tfunk()")
def get_tempdata_address(double_escaped=0): h('systype = unix_mac_pc()') if h.systype == 3: if double_escaped: tempdata_address = '..\\\\..\\\\tempdata\\\\' else: tempdata_address = '..\\..\\tempdata\\' else: tempdata_address = "../tempdata/" return tempdata_address
def make_cells(self,cell_list): ''' Distribute cells across the hosts in a Round robin distribution (circular dealing of cells) https://en.wikipedia.org/wiki/Round-robin ''' #import neuron #from neuron import h coords = [0 for i in xrange(0,3)]#define list as a local variable. h('objref py') h('py = new PythonObject()') NCELL=self.NCELL SIZE=self.SIZE RANK=self.RANK pc=h.ParallelContext() h('objref tvec, gidvec') h('gidvec = new Vector()') h('tvec = new Vector()') assert len(cell_list)!=0 d = { x: y for x,y in enumerate(cell_list)} itergids = iter( (d[i][3],i) for i in range(RANK, NCELL, SIZE) ) #Create a dictionary, where keys are soma centre coordinates to check for two cells occupying the same position. #since dictionary keys have to be unique should throw error once two cell somas occupy exactly the same coordinates. #TODO keep rank0 free of cells, such that all the memory associated with that CPU is free for graph theory related objects. #This would require an iterator such as the following. for (j,i) in itergids: has_cells=1#RANK specific attribute simplifies later code. cell = h.mkcell(j) self.names_list[i]=j print cell, j,i cell.geom_nseg() cell.gid1=i cell.name=j # Populate the dictionary with appropriate keys for the sanity check. #excitatory neuron. #self.test_cell(d[i]) if 'pyramid' in d[i]: cell.pyr() cell.polarity=1 #inhibitory neuron. else: cell.basket() cell.polarity=0 #8 lines of trailing code is drawn from. #http://neuron.yale.edu/neuron/static/docs/neuronpython/ballandstick5.html pc.set_gid2node(i,RANK) nc = cell.connect2target(None) pc.cell(i, nc) # Associate the cell with this host and gid #### Record spikes of this cell pc.spike_record(i, self.tvec, self.gidvec) assert None!=pc.gid2cell(i) self.celldict[i]=cell self.cells.append(cell)
def create_reduced_cell(soma_cable, has_apical, original_cell, model_obj_name, new_cable_properties, new_cables_nsegs, subtrees_xs): h("objref reduced_cell") h("reduced_cell = new " + model_obj_name + "()") create_sections_in_hoc("soma", 1, "reduced_cell") soma = original_cell.soma[0] if original_cell.soma.hname()[-1] == ']' else original_cell.soma append_to_section_lists("soma[0]", "somatic", "reduced_cell") if has_apical: # creates reduced apical cable if apical subtree existed create_sections_in_hoc("apic", 1, "reduced_cell") apic = h.reduced_cell.apic[0] num_of_basal_subtrees = len(new_cable_properties) - 1 cable_params = new_cable_properties[0] nseg = new_cables_nsegs[0] apply_params_to_section("apic[0]", "apical", "reduced_cell", apic, cable_params, nseg) apic.connect(soma, subtrees_xs[0], 0) else: apic = None num_of_basal_subtrees = len(new_cable_properties) # creates reduced basal cables create_sections_in_hoc("dend", num_of_basal_subtrees, "reduced_cell") basals = [h.reduced_cell.dend[i] for i in range(num_of_basal_subtrees)] for i in range(num_of_basal_subtrees): if has_apical: index_in_reduced_cables_dimensions = i + 1 else: index_in_reduced_cables_dimensions = i cable_params = new_cable_properties[index_in_reduced_cables_dimensions] nseg = new_cables_nsegs[index_in_reduced_cables_dimensions] apply_params_to_section("dend[" + str(i) + "]", "basal", "reduced_cell", basals[i], cable_params, nseg) basals[i].connect(soma, subtrees_xs[index_in_reduced_cables_dimensions], 0) # create cell python template cell = Neuron(h.reduced_cell) cell.soma = original_cell.soma cell.apic = apic return cell, basals
def get_mn_geom_address(double_escaped = 0): h('systype = unix_mac_pc()') if h.systype == 3: if double_escaped: mn_geom_address = '..\\\\mn_geometries\\\\' else: mn_geom_address = '..\\mn_geometries\\' else: mn_geom_address = "mn_geometries/" return mn_geom_address
def get_tempdata_address(double_escaped = 0): h('systype = unix_mac_pc()') if h.systype == 3: if double_escaped: tempdata_address = '..\\\\..\\\\tempdata\\\\' else: tempdata_address = '..\\..\\tempdata\\' else: tempdata_address = "../tempdata/" return tempdata_address
def get_mn_geom_address(double_escaped=0): h('systype = unix_mac_pc()') if h.systype == 3: if double_escaped: mn_geom_address = '..\\\\mn_geometries\\\\' else: mn_geom_address = '..\\mn_geometries\\' else: mn_geom_address = "mn_geometries/" return mn_geom_address
def set_params_all_active(hobj, params_file_name): """Configure a neuron after the cell morphology has been loaded""" with open(params_file_name) as biophys_params_file: biophys_params = json.load(biophys_params_file) passive = biophys_params['passive'][0] genome = biophys_params['genome'] conditions = biophys_params['conditions'][0] # Set fixed passive properties for sec in hobj.all: sec.Ra = passive['ra'] sec.insert('pas') # Insert channels and set parameters for p in genome: section_array = p["section"] mechanism = p["mechanism"] param_name = p["name"] param_value = float(p["value"]) if section_array == "glob": h(p["name"] + " = %g " % p["value"]) else: if hasattr(hobj, section_array): if mechanism != "": print 'Adding mechanism %s to %s' % (mechanism, section_array) for section in getattr(hobj, section_array): if h.ismembrane(str(mechanism), sec=section) != 1: section.insert(mechanism) print 'Setting %s to %.6g in %s' % (param_name, param_value, section_array) for section in getattr(hobj, section_array): setattr(section, param_name, param_value) # Set reversal potentials for erev in conditions['erev']: erev_section_array = erev["section"] ek = float(erev["ek"]) ena = float(erev["ena"]) print 'Setting ek to %.6g and ena to %.6g in %s' % (ek, ena, erev_section_array) if hasattr(hobj, erev_section_array): for section in getattr(hobj, erev_section_array): if h.ismembrane("k_ion", sec=section) == 1: setattr(section, 'ek', ek) if h.ismembrane("na_ion", sec=section) == 1: setattr(section, 'ena', ena) else: print "Warning: can't set erev for %s, section array doesn't exist" % erev_section_array
def plot_m_types(ax, PSET, colors, section=['dend', 'apic'], spacing=300, linewidths=0.05): '''draw comparison plot of each individual morphology''' CWD=PSET.CWD CELLPATH=PSET.CELLPATH n_segs = [] areas = [] for i, data in enumerate(PSET.populationParameters): NRN = data["me_type"] os.chdir(os.path.join(CWD, CELLPATH, NRN)) cell = NetworkCell(**PSET.cellParameters[NRN]) cell.set_pos(x=i*spacing, y=0, z=data['pop_args']['loc']) cell.set_rotation(x=np.pi/2) print(NRN, cell.zstart.min(), cell.zmid.min(), cell.zend.min(), cell.zstart.max(), cell.zmid.max(), cell.zend.max()) n_segs += [cell.totnsegs] areas += [cell.area[cell.get_idx(section)].sum()] zips = [] for x, z in cell.get_idx_polygons(projection=('x', 'z')): zips.append(list(zip(x, z))) polycol = PolyCollection(zips, edgecolors=colors[i], linewidths=linewidths, facecolors=colors[i], label=NRN, ) ax.add_collection(polycol) os.chdir(CWD) axis = ax.axis(ax.axis('tight')) # draw lines showing the layer boundaries ax.hlines(np.r_[0., -PSET.layer_data['thickness'].cumsum()][:4], axis[0], axis[1]-300, 'k', lw=0.5) ax.hlines(np.r_[0., -PSET.layer_data['thickness'].cumsum()][4:], axis[0], axis[1], 'k', lw=0.5) # annotate hlines with values for z in np.r_[0., -PSET.layer_data['thickness'].cumsum()]: ax.text(axis[0], z, r'$z={}$'.format(int(z)) + '$\mu$m', ha='right', va='center') ax.set_yticks(PSET.layer_data['center']) ax.set_yticklabels(PSET.layer_data['layer']) ax.set_xticks(np.arange(PSET.populationParameters.size)*spacing) ax.set_xticklabels(PSET.populationParameters['m_type'], rotation='vertical') ax.axis(ax.axis('equal')) ax.set_title('m-types') neuron.h("forall delete_section()") return n_segs, areas
def test_axial_currents(): h('soma {insert pas}') isim = h.IClamp(1, sec=h.cable) isim.delay = 0 isim.dur = 1 isim.amp = 2 #nA h.cable.Ra = 0.1 cell.initialize(0.1) t, imem_density, iax_density = cell.integrate(0.2, i_axial=True) coord = cell.get_seg_coords() iax = iax_density*coord['diam'][None,:]**2*1e-8/4.*h.PI #mA assert np.abs(iax[-1,1]*1e6 - isim.amp)<0.1*isim.amp
def insert(pat, chan): """Insert the pattern into segments """ global nchan chanName, expr = chan for sec in topology.nodes(): secName = sec.hname() if pat.match(secName): expr = expr.replace('r', str(topology.node[sec]['r'])) g = eval(expr) print("|- Inserting {} into {} with conductance: {} uS".format( chanName, secName, g) ) chan = sec.insert(chanName) h('gmax=%s' % (g)) nchan += 1
def main(): h.load_file("multisplit.hoc") h('{nrn_load_dll("../specials/x86_64/.libs/libnrnmech.so")}') tstop = 1000 pc = h.ParallelContext() start = h.startsw() ###################################################### # load model cell = load_model("./1056.swc") ###################################################### # generate mcomplex.dat lb = h.MyLoadBalance() lb.ExperimentalMechComplex() #save_mcomplex(lb) pc.barrier() ###################################################### # set up multi split cplx = h.multisplit(lb) pc.multisplit() pc.set_maxstep(10) ###################################################### # set stim and record of v stim = set_iclamp("CellSwc[0].Dend[2000]", pc) vec_t = h.Vector() vec_t.record(h._ref_t) vec_v = set_vec_v("CellSwc[0].Dend[100]", pc) setup_time = h.startsw() - start ###################################################### # run simulation start = h.startsw() h.stdinit() pc.psolve(tstop) pc.barrier() calc_time = h.startsw() - start ###################################################### # disp info show_result(pc, setup_time, calc_time, cplx) #show_section() #if(vec_v != 0): # show_plot(vec_t, vec_v) pc.done()