def fetch_soma_sec(section_name): cell_model = 'Hayton.hoc' h.load_file(cell_model) cell = h.L5PC soma = cell.soma[0] exec('sec = cell.' + section_name) return soma, sec
def __init__(self, sim_vars, dt=0.1): h.load_file('stdrun.hoc') self.dt = dt self.sim_time = 300 # this will be rewritten in set_SEClamp h.celsius = 22 #load known/default parameters params = yaml.load(open('params_example_start.yaml')) soma = h.Section(name='soma') soma.L = 15 soma.diam = 15 soma.cm = 1 soma.insert('Narsg') #set known/default parameters for p in params['Channel']: cmd = 'soma(0.5).%s_Narsg = %s' % (p, params['Channel'][p]) exec(cmd) #assign passed variables for sv in sim_vars: cmd = 'soma(0.5).%s_Narsg = %s' % (sv, sim_vars[sv]) exec(cmd) self.recording_section = soma self.soma = soma
def importCell (fileName, cellName, cellArgs = None): h.initnrn() if cellArgs is None: cellArgs = [] # Define as empty list if not otherwise defined ''' Import cell from HOC template or python file into framework format (dict of sections, with geom, topol, mechs, syns)''' if fileName.endswith('.hoc'): h.load_file(fileName) if isinstance(cellArgs, dict): cell = getattr(h, cellName)(**cellArgs) # create cell using template, passing dict with args else: cell = getattr(h, cellName)(*cellArgs) # create cell using template, passing list with args elif fileName.endswith('.py'): filePath,fileNameOnly = os.path.split(fileName) # split path from filename if filePath not in sys.path: # add to path if not there (need to import module) sys.path.insert(0, filePath) moduleName = fileNameOnly.split('.py')[0] # remove .py to obtain module name exec('import ' + moduleName + ' as tempModule') in globals(), locals() # import module dynamically modulePointer = tempModule if isinstance(cellArgs, dict): cell = getattr(modulePointer, cellName)(**cellArgs) # create cell using template, passing dict with args else: cell = getattr(modulePointer, cellName)(*cellArgs) # create cell using template, passing list with args sys.path.remove(filePath) else: print "File name should be either .hoc or .py file" return secDic, secListDic, synMechs = getCellParams(cell) return secDic, secListDic, synMechs
def coarse(hoc_filename,cube_length,save_filename): # INPUT: NEURON .hoc filename to import (str), voxel cube side length (fl/str for gcd), name of file to create for mesh output (str) # >> cube_length: 'gcd' (gcd of box dims) OR floating-point (must be common factor of all box dims) # This function reads in NEURON data and passes their info to # coarse_gen(), then associates the tets of the STEPS Tetmesh object returned # to the NEURON sections which exist inside of them. # Returns a tet_hoc dictionary -- tet_hoc[tet_index] = [encapsulated hoc section references] -- as well as the Tetmesh object ## GET HOC SECTION INFO ## h.load_file(hoc_filename) allp = [[],[],[]] for s in h.allsec(): for j in range(int(h.n3d())): allp[0].append(h.x3d(j)) allp[1].append(h.y3d(j)) allp[2].append(h.z3d(j)) maxl = [max(allp[0]),max(allp[1]),max(allp[2])] minl = [min(allp[0]),min(allp[1]),min(allp[2])] bdim = [ maxl[0] - minl[0], maxl[1] - minl[1], maxl[2] - minl[2] ] print "dims: ", bdim print "mins: ", minl ## CREATE COARSE MESH ## if (cube_length == 'gcd'): gcd = fractions.gcd(fractions.gcd(bdim[0],bdim[1]),fractions.gcd(bdim[2],bdim[1])) print "GCD: ", gcd cube_length = gcd sm = coarse_gen(cube_length,bdim,minl,save_filename) ## ASSOCIATE HOC SECTIONS WITH THEIR TETS ## tet_hoc = tet_associate(sm[0]) return tet_hoc, sm[0]
def load_hoc_model(self, model_dir, hoc_file): """Load an hoc files. It compiles the mod before loading the hoc.""" try: os.path.isfile(os.path.join (model_dir, hoc_file)) except IOError: logger.error("Not existing file: %s" %e.value) old_dir = os.path.abspath(os.getcwd()) logger.info("Path changed to %s" %(os.path.abspath(model_dir))) if model_dir != '' : os.chdir(model_dir) try: # Add all mod files into current directory self.find_mod_files() # If windows if os.name == 'nt': self.windows_compile_mod_files('.') from neuron import h h.nrn_load_dll('./nrnmech.dll') else: # Anything else. call(['nrnivmodl']) import neuron neuron.load_mechanisms('.') # Auto loading. Not needed anymore. from neuron import gui # to not freeze neuron gui from neuron import h logger.info("Loading model in %s from %s"%(model_dir, hoc_file)) h.load_file(hoc_file) except Exception as e: logger.warning("Error running model: " + e.message) logger.info("Path changed back to %s" %old_dir) os.chdir(old_dir) return True
def simulation(tstop, with_time = False): """ runs the simulation and returns the current and time vectors as Numpy arrays """ h.load_file('stdrun.hoc') h.v_init = -70 h.tstop = tstop VC_patch.dur1 = tstop # define vectors current = h.Vector() current.record(VC_patch._ref_i) if with_time is True: time = h.Vector() time.record(h._ref_t) h.run() if with_time is True: return (time, np.array(current)*1000.) else: return np.array(current)*1000.
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 run(tstop=1000, dt=0, V=-65): h.load_file('stdrun.hoc') #h.finitialize(V) if dt > 0: h.dt = dt h.tstop = tstop h.run()
def enable_threads(self, n_threads, multisplit_on=True): """Enable threads in neuron Using the parall Neuron""" h.load_file('parcom.hoc') pc =h.ParallelComputeTool() pc.nthread(n_threads, 1) if multisplit_on: pc.multisplit(1)
def multisplit(): h.load_file("parcom.hoc") parcom = h.ParallelComputeTool() parcom.multisplit(1) if settings.rank == 0: lb = parcom.lb print ('multisplit rank 0: %d pieces Load imbalance %.1f%%' % (lb.npiece, (lb.thread_cxbal_ -1)*100))
def _load_geom(self, filename): """Load the geometry of the model""" h5f = tables.openFile(filename) node = "/%s/%s" %(self.geometry_root, self.geometry_node_name) geom = h5f.getNode(node) # List check for legacy code xml_data = None geom_data = geom.read() if isinstance(geom_data, list): xml_data = geom_data[0] # get the string. else: xml_data = geom_data # The node is directly a string logger.debug(type (xml_data)) logger.debug("xml_data is a list: %s" %isinstance(xml_data, list)) tmp_file = 'temp.xml' f = open(tmp_file, 'w') f.write(xml_data) f.close() # import rdxml # This has to go ASAP they fix NEURON install h.load_file('celbild.hoc') cb = h.CellBuild(0) cb.manage.neuroml(tmp_file) cb.cexport(1) os.remove(tmp_file)
def set_up(self): h.load_file(1, 'NEURON_stuff/HayStuff/set_up_passive.hoc') # structuring the sections for sec in h.L5PC.basal: self.secs["basal"].append(sec) for sec in h.L5PC.somatic: self.secs["soma"].append(sec) for sec in h.L5PC.axonal: self.secs["axon"].append(sec) hoc_tuft = h.SectionList() hoc_tuft.subtree(sec=h.L5PC.apic[36]) hoc_trunk = h.SectionList() for sec in h.L5PC.apical: hoc_trunk.append(sec=sec) for sec in hoc_tuft: if sec.name() != h.L5PC.apic[36].name(): self.secs["tuft"].append(sec) for sec in self.secs["tuft"]: hoc_trunk.remove(sec=sec) for sec in hoc_trunk: self.secs["trunk"].append(sec) hoc_tuft = None # making sure the object gets destroyed. self.bifurcation_info = (self.sections("trunk")[36].name(), 1)
def __init__(self,f_name, El, Rm, Ra, Cm, min_distance = 0., convert_to_3pt_soma = True): """ El is the reversal potential of the leak conductance. Rm is the input resistance of the cell, in MOhm. Cm is the membrane capacitance. Ra is the axial resistance of the cell. All three variables are dictionaries, with the following keys: dend - value to be used for the dendrites soma - value to be used for the soma axon - value to be used for the axon """ h.load_file('stdlib.hoc') # contains the notorious lambda rule # the path of the SWC file if convert_to_3pt_soma: self.swc_filename = '.'.join(f_name.split('.')[:-1]) + '_converted.swc' convert_morphology(f_name, self.swc_filename) else: self.swc_filename = f_name # parameters self.El = El self.Rm = Rm self.Ra = Ra self.Cm = Cm self.min_distance = min_distance self.load_morphology() self.compute_measures() self.insert_passive_mech() self.insert_active_mech()
def main(): soma = h.Section() soma.insert('pas') soma.L = 100 soma.diam = 100 weight_min = 0.005 weight_max = 0.05 mu = (np.log(weight_min)+np.log(weight_max))/2 sigma = (np.log(weight_max)-mu)/3 weights = np.sort(np.exp(np.random.normal(mu,sigma,size=200))) synapses = [AMPASynapse(soma, 0.5, 0, w) for w in weights] for i,syn in enumerate(synapses): syn.set_presynaptic_spike_times([10+i*50]) rec = {} for lbl in 't','v','g': rec[lbl] = h.Vector() rec['t'].record(h._ref_t) rec['v'].record(soma(0.5)._ref_v) rec['g'].record(syn.syn._ref_g) h.load_file('stdrun.hoc') h.v_init = -70 h.celsius = 37 h.tstop = len(weights)*50 + 100 h.run() import pylab as p p.subplot(2,1,1) p.plot(rec['t'],rec['v'],'k') p.ylabel('Voltage (mV)') p.subplot(2,1,2) p.plot(rec['t'],rec['g'],'r') p.xlabel('Time (ms)') p.ylabel('Conductance (uS)') p.show()
def instantiate_swc(filename): """load an swc file and instantiate it""" h.load_file('stdgui.hoc') h.load_file('import3d.hoc') cell = h.Import3d_SWC_read() cell.input(filename) i3d = h.Import3d_GUI(cell, 0) i3d.instantiate(None) return i3d
def ivcurve(mechanism_name, i_type, vmin=-100, vmax=100, deltav=1, transient_time=50, test_time=50, rs=1, vinit=-665): """ Returns the (peak) current-voltage relationship for an ion channel. Args: mechanism_name = name of the mechanism (e.g. hh) i_type = which current to monitor (e.g. ik, ina) vmin = minimum voltage step to test vmax = maximum voltage step to test deltav = increment of voltage transient_time = how long to ignore for initial conditions to stabilize (ms) test_time = duration of the voltage clamp tests (ms) rs = resistance of voltage clamp in MOhm vinit = initialization voltage Returns: i = iterable of peak currents (in mA/cm^2) v = iterable of corresponding test voltages Note: The initialization potential (vinit) may affect the result. For example, consider the Hodgkin-Huxley sodium channel; a large fraction are inactivated at rest. Using a strongly hyperpolarizing vinit will uninactivate many channels, leading to more current. """ from neuron import h import numpy h.load_file('stdrun.hoc') sec = h.Section() sec.insert(mechanism_name) sec.L = 1 sec.diam = 1 seclamp = h.SEClamp(sec(0.5)) seclamp.amp1 = vinit seclamp.dur1 = transient_time seclamp.dur2 = test_time seclamp.rs = rs i_record = h.Vector() i_record.record(sec(0.5).__getattribute__('_ref_' + i_type)) result_i = [] result_v = numpy.arange(vmin, vmax, deltav) for test_v in result_v: seclamp.amp2 = test_v h.finitialize(vinit) h.continuerun(transient_time) num_transient_points = len(i_record) h.continuerun(test_time + transient_time) i_record2 = i_record.as_numpy()[num_transient_points:] baseline_i = i_record2[0] i_record_shift = i_record2 - baseline_i max_i = max(i_record_shift) min_i = min(i_record_shift) peak_i = max_i if abs(max_i) > abs(min_i) else min_i peak_i += baseline_i result_i.append(peak_i) return result_i, result_v
def generate_solinas2010(): # Load a shor version of the Start.hoc file # that does not run the sim # it saves the network structure to the Sim_data dir if not os.path.exists('SimData'): os.mkdir('SimData') from neuron import h h.load_file('Start_test.hoc')
def run(self, v_init=-60, tstop=20000., dt=0.1, cvode=True, ga_use_half=False): ''' Simulates this cell and all desired vectors are recorded. Uses fixed or variable timestep depending on the `cvode=` boolean. Parameters: ---------- v_init : int, float The starting voltage of the simulation. tstop : int, float The maximum time of integration dt : float The desired integration step. cvode : bool Selects variable time step integration. Default is False. ga_use_half : bool Will only use the 2nd have of recordings for GA ''' h.load_file('stdrun.hoc') h.v_init = v_init h.tstop = tstop h.dt = dt #set the recording into the vecs dictionary #the _ref dictionary contain the hoc object attribute references for key in self._ref.keys(): #This makes sure we overwrite any vectors if we already ran a sim if isinstance(self.vecs['time'], np.ndarray): self.vecs[key] = h.Vector() self.vecs[key].record(self._ref[key]) else: self.vecs[key].record(self._ref[key]) if cvode: solver = h.CVode() solver.active(1) h.finitialize(h.v_init) solver.solve(h.tstop) else: h.CVode().active(0) h.finitialize() for t in range(0, int(h.tstop/h.dt)): h.fadvance() for key, val in self.vecs.iteritems(): self.vecs[key] = np.array(val) if ga_use_half: for key, val in self.vecs.iteritems(): self.vecs[key] = val[(val.size)/2:] return self.vecs
def __init__(self): self.groups = {} # self.vecRefs = [] # self.synVecRefs = [] self.refs = {} self.results_root = 'results' self.geometry_root = 'geometry' self.geometry_node_name = 'geom' # Load the std run for NEURON h.load_file("stdrun.hoc")
def find_vrest(h, section_name): h.load_file("stdrun.hoc") tstop = 100 h.dt = dt = 0.1 soma, sec = fetch_soma_sec(section_name) h.init() h.cvode.re_init() t_vec, soma_vm, sec_vm = record(soma, sec) h.execute('tstop = 100') h.run() vrest = np.array(sec_vm)[-1] return vrest
def custom_cable(length=526., tiprad=1.4, somarad=15.4, inj=1.2, tinj=1., injloc=1., Ra=35.4): """ Simulate a simple passive current injection. Length=um, rads=um, inj=nA, tinj=ms, injloc=1 (tip). Recorded from all 11 segments. """ # Set up model h.load_file('stdrun.hoc') cell = h.Section() cell.nseg = 11 # It is a good idea to have nseg be an odd number cell.Ra = 35.4 # Ohm*cm cell.insert('pas') # Create structure h.pt3dadd(0,0,0,somarad,sec=cell) h.pt3dadd(length,0,0,tiprad,sec=cell) stim = h.IClamp(injloc, sec=cell) stim.delay = 5 # ms stim.dur = tinj # ms stim.amp = inj # nA print("Stim: %.2f nA, %.2f ms, at location %.2f" %(stim.amp, stim.dur, injloc)) # Segment positions, equall spaced from 0 to 1 seg_positions = np.linspace(0,1,cell.nseg) # Use toolbox to record v # ez_record records v in all compartments by default (v,v_labels) = ez_record(h) # Manually record time and current t, I = h.Vector(), h.Vector() t.record(h._ref_t) I.record(stim._ref_i) # Run the simulation h.init() h.tstop = 30 h.run() # Use toolbox convert v into a numpy 2D array v = ez_convert(v) # Plotting options fig = plt.figure() for i in range(cell.nseg): t = [v[u][i] for u in range(len(v))] ax = fig.add_subplot(cell.nseg, 1, i+1) ax.plot(t) plt.show() return h, v
def create_NRN_from_SWC(file_name,**kwargs) : global rs """ Create a passive multi-compartmental model in pyNRN from an SWC file """ swc_tree = btstructs.STree() swc_tree.read_SWC_tree_from_file(file_name) nodes = swc_tree.get_nodes() rs = nodes[1].get_content()['p3d'].y sections = {} h.load_file("stdlib.hoc") # contains the lambda rule for node in nodes : sections.update({node.get_index(): \ _make_section(node,node.get_index,sections,**kwargs)}) return sections
def passive_cable(stimloc=1., stimdur=5., show=False): """ This simulates a pulse injected into a simple passive cable. """ # Set up model h.load_file('stdrun.hoc') cell = h.Section() cell.nseg = 11 # It is a good idea to have nseg be an odd number cell.Ra = 35.4 # Ohm*cm cell.insert('pas') # create 3d structure h.pt3dadd(0,0,0,1.0,sec=cell) h.pt3dadd(1732,1732,1732,1.0,sec=cell) # Specify current injection stim = h.IClamp(stimloc,sec=cell) # Stim @ 1th end of segment stim.delay = 5 # ms stim.dur = stimdur # ms stim.amp = 0.2 # nA print("Stim: %.2f nA, %.2f ms, at location %.2f" %(stim.amp, stim.dur, stimloc)) # Segment positions, equall spaced from 0 to 1 seg_positions = np.linspace(0,1,cell.nseg) # Use toolbox to record v # ez_record records v in all compartments by default (v,v_labels) = ez_record(h) # Manually record time and current t, I = h.Vector(), h.Vector() t.record(h._ref_t) I.record(stim._ref_i) # Run the simulation h.init() h.tstop = 30 h.run() # Use toolbox convert v into a numpy 2D array v = ez_convert(v) # Plotting options if show: fig = plt.figure() for i in range(cell.nseg): t = [v[u][i] for u in range(len(v))] ax = fig.add_subplot(cell.nseg, 1, i+1) ax.plot(t) plt.show() return h, v
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()
def _load_geometry(self): '''Load the morphology-file in NEURON''' try: h.sec_counted = 0 except LookupError: h('sec_counted = 0') #import the morphology, try and determine format fileEnding = self.morphology.split('.')[-1] if fileEnding == 'hoc' or fileEnding == 'HOC': h.load_file(1, self.morphology) elif fileEnding == 'py': geom_func = imp.load_source('shape_3D', self.morphology) geom_func.shape_3D(self) else: neuron.h('objref this') if fileEnding == 'asc' or fileEnding == 'ASC': Import = h.Import3d_Neurolucida3() if not self.verbose: Import.quiet = 1 elif fileEnding == 'swc' or fileEnding == 'SWC': Import = h.Import3d_SWC_read() elif fileEnding == 'xml' or fileEnding == 'XML': Import = h.Import3d_MorphML() else: raise ValueError('%s is not a recognised morphology file format!' ).with_traceback( 'Should be either .hoc, .asc, .swc, .xml!' %self.morphology) #assuming now that morphologies file is the correct format try: Import.input(self.morphology) except: if not hasattr(neuron, 'neuroml'): raise Exception('Can not import, try and copy the ' + \ 'nrn/share/lib/python/neuron/neuroml ' + \ 'folder into %s' % neuron.__path__[0]) else: raise Exception('something wrong with file, see output') try: imprt = neuron.h.Import3d_GUI(Import, 0) except: raise Exception('See output, try to correct the file') imprt.instantiate(neuron.h.this) h.define_shape() self._create_sectionlists()
def __init__(self): self.dbs = DBS() self.nucleus = Nucleus(ptsFile='data/stn.pts', trisFile='data/stn.tri', name='Subthalamic Nucleus', color= (0.75, 0.75, 0.75)) nrn.load_file("stn.hoc") self.neuron = Cell(name='stn') self.neuron.move([0, 0, -2000]) # edit scaling --> 5 # edit xyz --> 0,0,-2000 #cell.move([0,0,-2000]) self.aximuth = 36 self.elevation = 57 self.distance = 6103 self.focalpoint = array([-4480, 5135, -4373]) self.reset_roll = False
def trivial_ecs(scale): from neuron import h, crxd as rxd import numpy import warnings warnings.simplefilter("ignore", UserWarning) h.load_file('stdrun.hoc') tstop = 10 if scale: #variable step case h.CVode().active(True) h.CVode().event(tstop) else: #fixed step case h.dt = 0.1 sec = h.Section() #NEURON requires at least 1 section # enable extracellular RxD rxd.options.enable.extracellular = True # simulation parameters dx = 1.0 # voxel size L = 9.0 # length of initial cube Lecs = 21.0 # lengths of ECS # define the extracellular region extracellular = rxd.Extracellular(-Lecs/2., -Lecs/2., -Lecs/2., Lecs/2., Lecs/2., Lecs/2., dx=dx, volume_fraction=0.2, tortuosity=1.6) # define the extracellular species k_rxd = rxd.Species(extracellular, name='k', d=2.62, charge=1, atolscale=scale, initial=lambda nd: 1.0 if abs(nd.x3d) <= L/2. and abs(nd.y3d) <= L/2. and abs(nd.z3d) <= L/2. else 0.0) # record the concentration at (0,0,0) ecs_vec = h.Vector() ecs_vec.record(k_rxd[extracellular].node_by_location(0, 0, 0)._ref_value) h.finitialize() h.continuerun(tstop) #run the simulation # compare with previous solution ecs_vec.sub(h.Vector(trivial_ecs_data[scale])) ecs_vec.abs() if ecs_vec.sum() > 1e-9: return -1 return 0
def main(): fixedInput = {'probability': 0.5, 'spikeTimes': [100,215]} neurons = [KhaliqRaman(i) for i in range(2)] for n in neurons: n.addFixedInput(fixedInput['probability'], fixedInput['spikeTimes']) n.addPoissonInputs(clusterSize=5, stimulusProps={'frequency': 0.1, 'noise': 1.}) n.addSomaticVoltageRecorder() time = h.Vector() time.record(h._ref_t) h.load_file('stdrun.hoc') h.tstop = 400 h.run() for n in neurons: #print('Neuron [%d] emitted %d spikes.' % (n.ID, len(n.spikeTimes))) saveNeuron('neuron.h5', n)
def __init__(self, hocfile, sec_id): """ Arguments: hocfile -- hoc file containing a hoc template with CA3 morphology sec_id -- index of the dendrite section containing the synapse """ h.load_file( hocfile ) mycell = h.CA3PCTopology() self.soma = mycell.soma self.dend = mycell.dend self.allsec = h.SectionList() self.allsec.wholetree(sec = self.soma) for sec in self.allsec: try: get_nseg( mysec = sec) # check if distance is zero! except ZeroDivisionError: print("Duplicate 3D coordinate in "), sec.name() # insert passive properties sec.insert('pas') sec.cm = 1 # in microF/cm**2 sec.Ra = 194 # in Ohms*cm sec.g_pas = 1/164e3 # in Ohms*cm**2 # apply lambda rule (Hines & Carnevale, 2001) AC_length = h.lambda_f(100, sec = sec) sec.nseg = int((sec.L/(0.1*AC_length)+0.999)/2)*2 + 1 # 3 segments for spatial grid of the soma self.soma.nseg = 3 # apply my custom spatial discretization to the dendrite/s # that contains the putative synaptic/s contact/s if sec_id>0: for i in sec_id: synsec = self.dend[i] synsec.nseg = get_nseg(mysec = synsec) else: synsec = self.dend[sec_id] synsec.nseg = get_nseg(mysec = synsec)
def _save_geom(self, h5file_holder): """Store the NeuroML in the geometry table""" # writing the NeuroML model h.define_shape() # We need the 3D points h.load_file('mview.hoc') modelView = h.ModelView(0) modelXml = h.ModelViewXML(modelView) tmp_file = 'temp.xml' modelXml.xportLevel1(tmp_file) xml_data = '' with open(tmp_file, 'r') as f: xml_data = f.read() geom_group = h5file_holder.createGroup('/', self.geometry_root) h5file_holder.createArray(geom_group, self.geometry_node_name, xml_data) os.remove(tmp_file)
###################################################################################### # MODIFIED HISTORY # 2015.04.30 This code is eddited for al_V2 from neuron import h import neuron as nrn import os.path import numpy as np import csv import operator import random import swc nrn.load_mechanisms("./mod") h.load_file("../input/swc/CellSwc_Ver2.hoc") def CalcDistance(cmpt1, cmpt2): #cmpt means compartment cmpt1.push() sr1 = h.SectionRef(sec=cmpt1) x1 = h.x3d(0.5) y1 = h.y3d(0.5) z1 = h.z3d(0.5) h.pop_section() cmpt2.push() sr2 = h.SectionRef(sec=cmpt2) x2 = h.x3d(0.5) y2 = h.y3d(0.5)
from neuron import h h.load_file('stdlib.hoc') #for h.lambda_f import random import math class adelta(object): ''' bio-axon class with parameters: axon parameters from: https://senselab.med.yale.edu/ModelDB/ShowModel.cshtml?model=3810&file=/MRGaxon/MRGaxon.hoc#tabs-2 number: number of nodes of Ranvier ''' def __init__(self, number): PI = 3.14 #topological parameters self.coordinates = dict() self.distances = dict() self.x_application = 7800 self.number = number self.axonnodes = number + 1 self.paranodes1 = 2 * number self.paranodes2 = 2 * number self.axoninter = 6 * number #morphological parameters self.fiberD = 5.0 self.paralength1 = 5 self.nodelength = 3 space_p1 = 0.002 space_p2 = 0.004
# -*- coding: utf-8 -*- from __future__ import (print_function, division, absolute_import, unicode_literals) from neuron import h, load_mechanisms import netutils as nu load_mechanisms('mod_files') # load the model dll files h.load_file("stdrun.hoc") # load the standard run libraries h.load_file("hoc_files/cobacell.hoc") # load the cell model h.load_file( "hoc_files/ranstream.hoc") # to give each cell its own sequence generator class COBANet(nu.BaseNet): """ A random network based on the COBA network from Vogels and Abbott 2005 from the HOC implementation of Brette et al 2007 """ def __init__(self, NCELL=4000, make_cell_fcn=h.CobaCell, inhibitory=20, ex_con=2, inh_con=2, syn_delay=0, stim_delay=1, ampa_gmax=0.006, gaba_gmax=0.067,
from Purkinje import Purkinje from neuron import h import multiprocessing import numpy as np #fixed time step only Fixed_step = h.CVode() Fixed_step.active(0) #the model does not work with the variable time step! #Instantiation of the cell template cell = Purkinje() #this code discover the number of cores available in a CPU and activate the multisplit to use them all. cores = multiprocessing.cpu_count() h.load_file("parcom.hoc") p = h.ParallelComputeTool() p.change_nthread(cores, 1) p.multisplit(1) print('cores' + str(cores)) #Neuron control menu h.nrncontrolmenu() #Voltage graph h('load_file("vm.ses")') #soma cell.soma.pcabar_Cav2_1 = 0 #dend
from __future__ import division from neuron import h from neuron import gui import matplotlib.pyplot as plt import numpy as np plt.ion() ##=================== creating cell object =========================== h.load_file("import3d.hoc") morphology_file = "morphologies/cell1.asc" h.load_file("models/L5PCbiophys3.hoc") h.load_file("models/L5PCtemplate.hoc") L5PC = h.L5PCtemplate(morphology_file) ##==================== create synapses =========================== #NMDA synapse NMDA_synapse = h.ProbAMPANMDA2_RATIO(0.5, sec=L5PC.soma[0]) NMDA_netstim = h.NetStim(0.5, sec=L5PC.soma[0]) NMDA_netcons = h.NetCon(NMDA_netstim, NMDA_synapse) NMDA_synapse.tau_r_AMPA = 0.33 NMDA_synapse.tau_d_AMPA = 1 NMDA_synapse.e = 0 NMDA_synapse.mgVoltageCoeff = 0.08 NMDA_netstim.number = 1 NMDA_netstim.noise = 0 NMDA_netstim.start = 100 NMDA_netcons.weight[0] = 0.9
import numpy as np from neuron import h from matplotlib import pyplot as plt h.load_file('simulationcode/BAC_firing_short.hoc') h(''' objref tuftica access L5PC.apic[siteVec[0]] tuftica = new Vector() cvode.record(&ica(siteVec[1]),tuftica,tvec)''') allisyn = np.arange(0, 0.502, 0.02) alldt = np.arange(-20, 21, 1) integral = np.zeros((alldt.size, allisyn.size)) fig, axes = plt.subplots(2, alldt.size, sharex='all', sharey='row', figsize=(16, 8)) burst = np.zeros([alldt.size, allisyn.size]) nspikes = np.zeros([alldt.size, allisyn.size]) for i in range(alldt.size): for j in range(allisyn.size): dt = alldt[i] isyn = allisyn[j] h.st1.amp = 1.8 h.st1.dur = 3 h.syn1.imax = isyn h.syn1.onset = 295 + dt
''' PyNeuron tutorial. Create two basic conductance-based models and connect them via a synapse ''' import neuron from neuron import h import numpy as np from pylab import * h.load_file("stdrun.hoc") # for run control # create two cells cell1 = h.Section() cell1.insert('hh') cell2 = h.Section() cell2.insert('hh') trec = h.Vector() trec.record(h._ref_t) # record time vrec1 = h.Vector() vrec1.record(cell1(0.5)._ref_v) # record voltage from cell1 vrec2 = h.Vector() vrec2.record(cell2(0.5)._ref_v) # record voltage from cell 2 # drive cell 1 with a current and connect to cell 2 via a synapse ic = h.IClamp(cell1(0.5)) # check "help(h.IClamp)" ic.delay = 5 #ms ic.dur = 25 #ms ic.amp = 5 # nA, 5 -> 1 spike, 10 -> regular firing