def get_distances(mycell, save=False): """ mycell -- cell object fname -- path and filename of the file to save Returns an array with the id, segment and distance from the soma every segment in the cell object """ from neuron import h import numpy as np array = np.empty((0,3)) mydist = list() if save is True: fp = open('distances.txt','w') h.distance(0, 0.5, sec=mycell.soma) for sec in mycell.allsec: mystring = sec.name() sec_id = mystring.split('.')[-1] for seg in sec: dist = h.distance(seg.x, sec=seg.sec) mydist.append(float(dist)) array = np.append(array, [[sec_id, float(seg.x), dist]], axis=0) if save is True: fp.write("%4s\t%2.4f\t%2.4f\n"%(sec_id, float(seg.x), dist)) if save is True: fp.close() return array
def initialize(): global Epas h.celsius = celsius for sec in h.soma: h.distance() for sec in h.allsec(): sec.v = Epas sec.e_pas = Epas sec.insert("pas") sec.e_pas = Epas sec.g_pas = 1/Rm sec.Ra = rall sec.cm = cap sec.gnabar_hh2 = 0 sec.gkbar_hh2 = 0 dist = h.distance(0.5) # sec.gcabar_it2 = gcat_func(dist) sec.gcabar_it2 = gcat for sec in h.soma: sec.gnabar_hh2 = gna sec.gkbar_hh2 = gkdr # sec.gcabar_it2 = 0.1054*gcat sec.gcabar_it2 = gcat h.finitialize() h.fcurrent() cvode.re_init()
def distribute_channels(self, as1, as2, d3, a4, a5, a6, a7, g8, factors=None): h.distance(sec=self.soma) dmax = self._max_dist() for sec in self.allseclist: if sec.name().find(as1) >= 0: for seg in sec: dist = h.distance(seg.x, sec=sec) val = calculate_distribution(d3, dist, a4, a5, a6, a7, g8) cmd = 'seg.%s = %g' % (as2, val) exec(cmd) #names = ['mVhalf_naf', 'hVhalf_naf', 'mSlope_naf', 'hSlope_naf'] names = ['taum_naf', 'tauh_naf', 'taun_naf'] if factors: for i, factor in enumerate(factors): print('updating factors! ', factors, factor, names[i]) # add minus here if running with slope and half activation; cmd = 'seg.%s = %g' % (names[i], -factor) cmd = 'seg.%s = %g' % (names[i], factor) exec(cmd)
def fix_axon_allactive_granule(hobj): """Replace reconstructed axon with a stub Parameters ---------- hobj: instance of a Biophysical template NEURON's cell object """ # find the start and end diameter of the original axon, this is different from the perisomatic cell model # where diameter == 1. axon_diams = [hobj.axon[0].diam, hobj.axon[0].diam] h.distance(sec=hobj.soma[0]) # need this to set all distances relative to soma (not sure if from center?) for sec in hobj.all: section_name = sec.name().split(".")[1][:4] if section_name == 'axon': for seg in sec: if h.distance(seg.x) > 60: axon_diams[1] = sec.diam #if h.distance(0.5, sec) > 60: # axon_diams[1] = sec.diam for sec in hobj.axon: h.delete_section(sec=sec) h.execute('create axon[2]', hobj) for index, sec in enumerate(hobj.axon): sec.L = 30 sec.diam = axon_diams[index] # 1 hobj.axonal.append(sec=sec) hobj.all.append(sec=sec) # need to remove this comment hobj.axon[0].connect(hobj.soma[0], 1.0, 0) hobj.axon[1].connect(hobj.axon[0], 1.0, 0) h.define_shape()
def rec_along_longest_branch(): """ Record membrane current and potential along the longest branch. The vectors will be filled only after the neuron simulation is run as the vectors are :class:`Vector`. Data is gathered directly from neuron and not LFPy. Treversal of the longest branch is done usingn :class:`neuron:SectionRef` and :class:`neuron:SectionRef.child()` :returns: * :class:`neuron:Vector` -- List of membrane potentials. * :class:`neuron:Vector` -- List of membrane currents. * :class:`neuron:Vector` -- Time vector. * :class:`~numpy.ndarray` -- Position of recording sites. Example: .. code-block:: python v_vec_list, i_vec_list, t_vec, rec_pos = rec_along_longest_branch() h.run() """ sr = h.SectionRef() # Start the distance calculation from the root section. h.distance(0, 0.5, sec=sr.root) path, dist = _longest_path(sr) return _walk_path(sr, path)
def save_inputs(graph, sim): cells = graph.get_local_cells() cell = cells[list(cells.keys())[0]] h.distance(sec=cell.hobj.soma[0]) sec_types = [] weights = [] dists = [] names = [] cons = cell.connections() for c in cons: con = c._connector syn = con.syn() weights.append(float(syn.initW)) seg = con.postseg() fullsecname = seg.sec.name() names.append(fullsecname) #import pdb; pdb.set_trace() dists.append(float(h.distance(seg))) sec_types.append(fullsecname.split(".")[1][:4]) df = pd.DataFrame() df["Distance"] = dists df["Conductance"] = weights df["Type"] = sec_types df["Name"] = names df.to_csv("Inputs.csv")
def _set_biophysics(self, sections): "Set the biophysics for the cell." # neuron syntax is used to set values for mechanisms # sec.gbar_mech = x sets value of gbar for mech to x for all segs # in a section. This method is significantly faster than using # a for loop to iterate over all segments to set mech values # If value depends on distance from the soma. Soma is set as # origin by passing cell.soma as a sec argument to h.distance() # Then iterate over segment nodes of dendritic sections # and set attribute depending on h.distance(seg.x), which returns # distance from the soma to this point on the CURRENTLY ACCESSED # SECTION!!! h.distance(sec=self._nrn_sections['soma']) for sec_name, section in sections.items(): sec = self._nrn_sections[sec_name] for mech_name, p_mech in section.mechs.items(): sec.insert(mech_name) for attr, val in p_mech.items(): if hasattr(val, '__call__'): sec.push() for seg in sec: setattr(seg, attr, val(h.distance(seg.x))) h.pop_section() else: setattr(sec, attr, val)
def distKV(self): for sec in self.soma: sec.gbar_kv = somaKv for sec in self.basals: h.distance(0, 0.5, sec=self.soma) for seg in sec.allseg(): dist = h.distance(seg.x, sec=sec) gKVlin = somaKv + mKV * dist if (gKVlin > gKVmax): gKVlin = gKVmax print("Setting basal GKV to maximum ", gKVmax, " at distance ", dist, " in basal dendrite", sec.name()) elif (gKVlin < 0): gKVlin = 0 print("Setting basal GKV to zero at distance ", dist, " in basal dendrite ", sec.name()) sec(seg.x).gbar_kv = gKVlin for sec in self.axon: sec.gbar_kv = axonKv for sec in self.apical: sec.gbar_kv = somaKv
def initialize(Tdist): global Epas h.celsius = celsius for sec in h.soma: h.distance() for sec in h.allsec(): sec.v = Epas sec.e_pas = Epas sec.insert("pas") sec.e_pas = Epas sec.g_pas = 1/Rm sec.Ra = rall sec.cm = cap sec.gnabar_hh2 = 0 sec.gkbar_hh2 = 0 for seg in sec: if Tdist == 1: seg.gcabar_it2 = gcat if Tdist == 2: seg.gcabar_it2 = gcat * (1 + 0.04 * (h.distance(0) + sec.L * seg.x)) * 0.10539397661220173 for sec in h.soma: sec.gnabar_hh2 = gna sec.gkbar_hh2 = gkdr if Tdist == 1: seg.gcabar_it2 = gcat if Tdist == 2: seg.gcabar_it2 = gcat * 0.10539397661220173 h.finitialize() h.fcurrent() cvode.re_init()
def set_seg_props(self): """Set segment properties which are invariant for all cell using this morphology""" seg_type = [] seg_area = [] seg_x = [] seg_dist = [] seg_length = [] h.distance(sec=self.hobj.soma[0]) # measure distance relative to the soma for sec in self.hobj.all: fullsecname = sec.name() sec_type = fullsecname.split(".")[1][:4] # get sec name type without the cell name sec_type_swc = self.sec_type_swc[sec_type] # convert to swc code for seg in sec: seg_area.append(h.area(seg.x)) seg_x.append(seg.x) seg_length.append(sec.L/sec.nseg) seg_type.append(sec_type_swc) # record section type in a list seg_dist.append(h.distance(seg.x)) # distance to the center of the segment self.seg_prop = {} self.seg_prop['type'] = np.array(seg_type) self.seg_prop['area'] = np.array(seg_area) self.seg_prop['x'] = np.array(seg_x) self.seg_prop['dist'] = np.array(seg_dist) self.seg_prop['length'] = np.array(seg_length) self.seg_prop['dist0'] = self.seg_prop['dist'] - self.seg_prop['length']/2 self.seg_prop['dist1'] = self.seg_prop['dist'] + self.seg_prop['length']/2
def _max_dist(self, axon_excluding=True): h.distance(sec=self.soma) dmax = 0 for sec in self.allseclist: if axon_excluding and sec.name().find('axon') == 0: continue dmax = max(dmax, h.distance(1, sec=sec)) return dmax
def randSecWeight(obj, medSeg, part, num): allLen = [] for i in range(len(obj)): allLen.append(obj[i].L) randSecList = [0 for i in range(num)] h.distance(sec=obj[medSeg]) # define distance measure from medSeg # draw from cumulative length a seg for syn x = np.sum( allLen[:medSeg]) + (np.random.rand(num) - 0.5) * np.sum(allLen) / part j = 0 farbug = 0 while j < num: # redraw boundary crossers if x[j] < 0 or x[j] > np.sum(allLen): x[j] = np.sum(allLen[:medSeg]) + (np.random.rand() - 0.5) * np.sum(allLen) / part continue # find sec for i in range(len(obj)): if x[j] < np.sum(allLen[:i + 1]): randSecList[j] = i break # check that sec is sufficiently close to medseg if h.distance(obj[randSecList[j]](1)) > sum( allLen ) / part and farbug < 5: #obj[medSeg].L+obj[randSecList[j]].L:# x[j] = np.sum(allLen[:medSeg]) + (np.random.rand() - 0.5) * np.sum(allLen) / part farbug += 1 continue j += 1 farbug = 0 return randSecList
def create_neuron(): """ creates an active neuron, with sigmoid decay of gnabar_hh in the dendrites """ neuron = Neuron(ApicalBasalActive) # ** Passive Passive(neuron) # see in Kole et al., 2008 for axon in neuron.axon: axon.g_pas = 1 / 15e3 axon.Ra = 100.0 axon.cm = 0.9 # ** Active # Active properties in Soma neuron.soma.gnabar_hh = 0.040 # active custom-distribution of Na and K h.distance(sec=neuron.soma) neuron.get_Active().activatedendrites(fsec_apical, fsec_basal) # change active properties of the axon # see in Kole et al., 2008 for axon in neuron.axon: axon.insert("hh") axon.gnabar_hh = 0.250 return neuron
def set_ca_parameters(self, gsca, git2, gkca, eca): h.distance(sec=self.soma, seg=0) for sec in neuron.h.allsec(): sec.insert('sca') sec.insert('cad2') sec.insert('kca') for seg in sec: seg.eca = eca #print seg.eca if not sec == self.soma: sec.insert('it2') dist = fromtodistance(self.soma(0.5), seg) if (dist > 500 and dist < 750): seg.gcabar_it2 = git2 seg.gbar_sca = gsca * 3 seg.gbar_kca = gkca else: seg.gcabar_it2 = 0 seg.gbar_sca = gsca seg.gbar_kca = gkca else: for seg in sec: seg.gbar_sca = gsca * 2 seg.gbar_kca = gkca * 2
def inject_current(tstop, section, soma=True, st_amp=None): """ simulates a current injection in the section1 and records in section 1 and 2 IT DOES NOT WORK PROPERTLY!!!! """ if st_amp is not None: stim_amp = st_amp else: stim_amp = 4 if soma is True: stim_sec = section.cell().mysoma record_sec = section else: stim_sec = section record_sec = section.cell().mysoma h.distance(sec=stim_sec) print h.distance(0, sec=record_sec) stim = h.IClamp(0.5, sec=stim_sec) stim.amp = stim_amp stim.dur = 2.0 stim.delay = 1 mylist = [stim_sec, record_sec] myvector = simulate_voltage(tstop, list_seg=mylist) fig = figure() ax = fig.add_subplot(111) ax.plot(myvector[0].time, myvector[0].voltage, "r") ax.plot(myvector[1].time, myvector[1].voltage, "k") show()
def seg_section_distance(self,seg,root_section=None): """ Returns the distance between each segment of section, and the root_section """ if not root_section:root_section=self.root h.distance(0, root_section(0.5).x, sec=root_section) return h.distance(seg.x, sec=seg.sec)
def find_parent_seg(join, sdict, objects): if not join: return None elif join[0] not in objects: pseg = sdict[( join[0]._x0, join[0]._y0, join[0]._z0, join[0]._x1, join[0]._y1, join[0]._z1, )] # better be all in same cell; so just set root once h.distance(0, h.SectionRef(sec=pseg.sec).root(0)) closest = h.distance(pseg) # any other possible instance? for item in join: if item not in objects: s = sdict[(item._x0, item._y0, item._z0, item._x1, item._y1, item._z1)] d = h.distance(s) if d < closest: pseg = s closest = d return pseg
def initialize(self, sim): self._get_gids(sim) self._save_sim_data(sim) # TODO: get section by name and/or list of section ids # Build segment/section list for gid in self._local_gids: sec_list = [] seg_list = [] cell = sim.net.get_cell_gid(gid) cell.store_segments() h.distance(sec=cell.hobj.soma[0]) for sec_id, sec in enumerate(cell.get_sections()): sec_name = sec.name().split(".")[1][:4] for seg in sec: # TODO: Make sure the seg has the recorded variable(s) if self._sections == 'all' or sec_name in self._sections: sec_list.append(sec_id) seg_list.append(seg.x) self._seg_obj_dict[gid].append(seg) self._var_recorder.add_cell(gid, sec_list, seg_list) self._var_recorder.initialize(sim.n_steps, sim.nsteps_block)
def modify_morphology(section_dict, cellname): for key, sec_list in section_dict.items(): for sec in sec_list: sec.nseg = 11 for sec in section_dict['basal']: for i in xrange(int(nrn.n3d())): nrn.pt3dchange(i, 0.76) for sec in section_dict['oblique_dendrites']: for i in xrange(int(nrn.n3d())): nrn.pt3dchange(i, 0.73) if cellname == 'n120': apic_root_segment = 'apic[9]' elif cellname == 'c12861': apic_root_segment = 'apic[92]' else: raise RuntimeError("Not known cellname!") nrn.distance() apic_tuft_root_diam = None apic_tuft_root_dist = None for sec in section_dict['apic_trunk']: npts = int(nrn.n3d()) cummulative_L = 0 for i in xrange(npts): if not i == 0: delta_x = (nrn.x3d(i) - nrn.x3d(i - 1))**2 delta_y = (nrn.y3d(i) - nrn.y3d(i - 1))**2 delta_z = (nrn.z3d(i) - nrn.z3d(i - 1))**2 cummulative_L += np.sqrt(delta_x + delta_y + delta_z) dist_from_soma = nrn.distance(0) + cummulative_L diam = 3.5 - 4.7e-3 * dist_from_soma # print diam, nrn.diam3d(i) nrn.pt3dchange(i, diam) if sec.name() == apic_root_segment: apic_tuft_root_diam = nrn.diam3d(npts - 1) apic_tuft_root_dist = nrn.distance(1.) longest_tuft_branch = find_longest_tuft_branch(section_dict, apic_tuft_root_dist) tuft_smallest_diam = 0.3 for sec in section_dict['apic_tuft']: npts = int(nrn.n3d()) cummulative_L = 0 start_dist_from_tuft_root = nrn.distance(0.0) - apic_tuft_root_dist for i in xrange(npts): if not i == 0: delta_x = (nrn.x3d(i) - nrn.x3d(i - 1))**2 delta_y = (nrn.y3d(i) - nrn.y3d(i - 1))**2 delta_z = (nrn.z3d(i) - nrn.z3d(i - 1))**2 cummulative_L += np.sqrt(delta_x + delta_y + delta_z) dist_from_root = start_dist_from_tuft_root + cummulative_L diam = apic_tuft_root_diam - dist_from_root/longest_tuft_branch * (apic_tuft_root_diam - tuft_smallest_diam) # print nrn.diam3d(i), diam nrn.pt3dchange(i, diam, sec=sec)
def _distribute_channel(self, mech, mech_param, sections='apic', soma_name='soma', dist_type='abs', s3=None, s4=None, s5=None, s6=None, s7=None): """ This function is rewrited to Python from Hay2011 L5PCTemplate.hoc file, proc distribute_channels() :param sections: :param soma_name: :param dist_type: 'abs' - absolute [default] 'lin' - linear 'sigm' - sigmoidal 'exp' - exponential :return: """ soma = self.filter_secs(soma_name, as_list=True) if len(soma) != 1: raise LookupError( "Central section for channel distribution must be only one for name %s, " "but found %s sections containing this name." % (soma_name, len(soma))) soma = soma[0] secs = self.filter_secs(name=sections, as_list=True) max_dist = max([h.distance(soma(0.5).hoc, s(1).hoc) for s in secs]) for sec in secs: for x in sec.hoc: dist = h.distance(soma(0.5).hoc, x) dist_norm = dist / max_dist if dist_type == 'lin': val = s3 + dist_norm * s4 elif dist_type == 'sigm': ex = np.exp((dist_norm - s5) / s6) sigmoid = s4 / (1 + ex) val = s3 + sigmoid elif dist_type == 'exp': val = s3 + s6 * np.exp(s4 * (dist_norm - s5)) elif dist_type == 'abs': if s5 < dist < s6: val = s3 else: val = s4 else: raise ValueError( "The only allowed dist_type are abs,lin,sigm,exp, but provided %s" % dist_type) val *= s7 mech_obj = getattr(x, mech) setattr(mech_obj, mech_param, val)
def dist_between(h,seg1,seg2): """ Calculates the distance between two segments. I stole this function from a post by Michael Hines on the NEURON forum (www.neuron.yale.edu/phpbb/viewtopic.php?f=2&t=2114) """ h.distance(0, seg1.x, sec=seg1.sec) return h.distance(seg2.x, sec=seg2.sec)
def recalculate_channel_densities(self): # See Keren et al. 2009 h.distance(sec=self.soma) for sec in self.apicaltree_list: for seg in sec: seg.gbar_kfast = self.soma(0.5).gbar_kfast * math.exp(-h.distance(seg.x)/self.decay_kfast) seg.gbar_kslow = self.soma(0.5).gbar_kslow * math.exp(-h.distance(seg.x)/self.decay_kslow)
def dist_between(h, seg1, seg2): """ Calculates the distance between two segments. I stole this function from a post by Michael Hines on the NEURON forum (www.neuron.yale.edu/phpbb/viewtopic.php?f=2&t=2114) """ h.distance(0, seg1.x, sec=seg1.sec) return h.distance(seg2.x, sec=seg2.sec)
def dist_between(h,seg1,seg2): """ Calculates the distance between two segments. Adapted from a post by Michael Hines on the NEURON forum (www.neuron.yale.edu/phpbb/viewtopic.php?f=2&t=2114) Note: In NEURON 7.7+, you can just do return h.distance(seg1, seg2) """ h.distance(0, seg1) return h.distance(seg2)
def updated_HNN_dends(self): # set dend biophysics specified in Pyr() # self.pyr_biophys_dends() self.soma.gkbar_hh2 += self.p_all['L5Pyr_dend_gkbar_hh2'] # set dend biophysics not specified in Pyr() for key in self.dends: # Insert 'hh2' mechanism self.dends[key].insert('hh2') # self.dends[key].gkbar_hh2 = self.p_all['L5Pyr_dend_gkbar_hh2'] self.dends[key].gl_hh2 = self.p_all['L5Pyr_dend_gl_hh2'] # self.dends[key].gnabar_hh2 = self.p_all['L5Pyr_dend_gnabar_hh2'] self.dends[key].el_hh2 = self.p_all['L5Pyr_dend_el_hh2'] # Insert 'ca' mechanims # Units: pS/um^2 self.dends[key].insert('ca') # self.dends[key].gbar_ca = self.p_all['L5Pyr_dend_gbar_ca'] # Insert 'cad' mechanism self.dends[key].insert('cad') self.dends[key].taur_cad = self.p_all['L5Pyr_dend_taur_cad'] # Insert 'kca' mechanism self.dends[key].insert('kca') self.dends[key].gbar_kca = self.p_all['L5Pyr_dend_gbar_kca'] # Insert 'km' mechansim # Units: pS/um^2 self.dends[key].insert('km') self.dends[key].gbar_km = self.p_all['L5Pyr_dend_gbar_km'] # insert 'cat' mechanism self.dends[key].insert('cat') self.dends[key].gbar_cat = self.p_all['L5Pyr_dend_gbar_cat'] # insert 'ar' mechanism self.dends[key].insert('ar') # set gbar_ar # Value depends on distance from the soma. Soma is set as # origin by passing self.soma as a sec argument to h.distance() # Then iterate over segment nodes of dendritic sections # and set gbar_ar depending on h.distance(seg.x), which returns # distance from the soma to this point on the CURRENTLY ACCESSED # SECTION!!! h.distance(sec=self.soma) for key in self.dends: self.dends[key].push() for seg in self.dends[key]: seg.gbar_ar = self.p_all['L5Pyr_dend_gbar_ar'] * np.exp( 3e-3 * h.distance(seg.x)) # 3e-3 self.__insert_distributed_channels(seg) h.pop_section()
def make_sections(self): SWC_types_inverse = {v:k for k,v in SWC_types.iteritems()} # load the tree structure that represents the morphology self.tree = btmorph.STree2() self.tree.read_SWC_tree_from_file(self.swc_filename,types=range(10)) print('There are %d nodes in the full representation of the morphology.' % len(self.tree.get_nodes())) # all the sections self.sections = [] sections_map = {} # describes how sections are connected self.sections_connections = [] # a (temporary) list of all the sections that make up the apical dendrites self.apical = [] # parse the tree for node in self.tree: if node is self.tree.root: section = h.Section(name='{0}_{1}'.format(SWC_types_inverse[node.content['p3d'].type],node.index)) self.sections.append(section) sections_map[node.index] = len(self.sections)-1 h.pt3dclear(sec=section) self.soma.append(section) elif len(node.children) == 1 and len(node.parent.children) > 1: # the parent of the current node is a branching point: start a new section section = h.Section(name='{0}_{1}'.format(SWC_types_inverse[node.content['p3d'].type],node.index)) self.sections.append(section) self.sections_connections.append((len(self.sections)-1,sections_map[node.parent.index])) sections_map[node.index] = len(self.sections)-1 h.pt3dclear(sec=section) # assign it to the proper region swc_type = node.content['p3d'].type if swc_type == SWC_types['soma']: self.soma.append(section) h.distance(sec=soma[0]) elif swc_type == SWC_types['axon']: self.axon.append(section) elif swc_type == SWC_types['basal']: self.basal.append(section) elif swc_type == SWC_types['apical']: self.apical.append(section) else: import pdb; pdb.set_trace() else: sections_map[node.index] = sections_map[node.parent.index] section = self.sections[sections_map[node.parent.index]] xyz = node.content['p3d'].xyz h.pt3dadd(float(xyz[0]),float(xyz[1]),float(xyz[2]),2*float(node.content['p3d'].radius),sec=section) # now that we have built all the sections we can subdivide those in the apical # dendrite in proximal and distal h.distance(sec=self.soma[0]) for sec in self.apical: if h.distance(0.5, sec=sec) < self.parameters['proximal_limit']: self.proximal.append(sec) else: self.distal.append(sec)
def distance_to_soma(self, section): if section.name() == h.soma.name(): return 0 * pq.um h.distance(sec=h.soma) distance = h.distance(0.5, sec=section) # make sure the distance is to 0.5 in soma if list(chain(self.sec_names["axon"], self.sec_names["basal"])).__contains__(section.name()): distance = distance + (h.soma.L/2) else: distance = distance - (h.soma.L/2) return distance * pq.um
def _create_AIS(self): """Replica of "Replace axon" in: https://bluepyopt.readthedocs.io/en/latest/_modules/bluepyopt/ephys/morphologies.html#Morphology """ temp = [] for sec in h.allsec(): if sec.name().find('axon') >= 0: temp.append(sec) # specify diameter based on blu if len(temp) == 0: ais_diams = [1, 1] elif len(temp) == 1: ais_diams = [temp[0].diam, temp[0].diam] else: ais_diams = [temp[0].diam, temp[0].diam] # Define origin of distance function h.distance(0, 0.5, sec=self.soma) for section in h.allsec(): if section.name().find('axon') >= 0: # If distance to soma is larger than 60, store diameter if h.distance(1, 0.5, sec=section) > 60: ais_diams[1] = section.diam break # delete old axon for section in temp: h.delete_section(sec=section) # Create new axon sections a0 = h.Section(name='axon[0]') a1 = h.Section(name='axon[1]') # populate axonlist for sec in h.allsec(): if sec.name().find('axon') >= 0: self.axonlist.append(sec=sec) # connect axon sections to soma and eachother a0.connect(self.soma) a1.connect(a0) # set axon params for index, section in enumerate([a0,a1]): section.nseg = 1 section.L = 30 section.diam = ais_diams[index] # this line is needed to prevent garbage collection of axon self.axon = [a0,a1] logger.debug('Replace axon with AIS')
def set_seg_props(self): """Set segment properties which are invariant for all cell using this morphology""" seg_type = [] seg_area = [] seg_x = [] seg_dist = [] seg_length = [] h.distance( sec=self.hobj.soma[0]) # measure distance relative to the soma for sec in self.hobj.all: fullsecname = sec.name() sec_type = fullsecname.split( ".")[1][:4] # get sec name type without the cell name sec_type_swc = self.sec_type_swc[sec_type] # convert to swc code for seg in sec: seg_area.append(h.area(seg.x)) seg_x.append(seg.x) seg_length.append(sec.L / sec.nseg) seg_type.append(sec_type_swc) # record section type in a list seg_dist.append(h.distance( seg.x)) # distance to the center of the segment ''' for sec in self.hobj.all: sec_name = sec.name() segs = [s for s in sec] seg_len = sec.L / sec.nseg print sec_name, sec.L, len(segs),':', for s in segs: seg_dist = h.distance(s.x) print '[{} - {} - {}]'.format(seg_dist-seg_len/2, seg_dist, seg_dist+seg_len/2), # print h.distance(s.x), #print s.x, print '({})'.format(sec.L/sec.nseg) #print ' ', #for s in segs: # print '[{} - {}]'.format() #print sec.name(), '-', len([s for s in sec]) ''' self.seg_prop = {} self.seg_prop['type'] = np.array(seg_type) self.seg_prop['area'] = np.array(seg_area) self.seg_prop['x'] = np.array(seg_x) self.seg_prop['dist'] = np.array(seg_dist) self.seg_prop['length'] = np.array(seg_length) self.seg_prop[ 'dist0'] = self.seg_prop['dist'] - self.seg_prop['length'] / 2 self.seg_prop[ 'dist1'] = self.seg_prop['dist'] + self.seg_prop['length'] / 2
def get_valid_dendrites(pv_cell, min_max_distance): origin = h.distance(0, 0.0, sec=pv_cell.root) possible_dends = set() for dend in pv_cell.dendrites: for seg in dend: distance = h.distance(seg.x, sec=dend) if np.logical_and(distance > min_max_distance[0], distance < min_max_distance[1]): possible_dends.add(dend) possible_dends = [dend for dend in possible_dends] return possible_dends
def biophys_passive(section_dict, **kwargs): Vrest = -80 if not 'hold_potential' in kwargs else kwargs['hold_potential'] rm_dict = {'somatic': 90000., 'axonal_IS': 90000., 'axonal_hillock': 90000., 'myelinated_axonal': 1.0e6, 'basal': 90000., 'apic_trunk': 90000., 'oblique_dendrites': 90000., 'apic_tuft': 20000., } cm_dict = {'somatic': 1.5, 'axonal_IS': 1.5, 'axonal_hillock': 1.5, 'myelinated_axonal': 0.04, 'basal': 1.5, 'apic_trunk': 1.5, 'oblique_dendrites': 1.5, 'apic_tuft': 1.5, } area_of_spine = lambda diam_head, diam_neck, length_neck: np.pi * (diam_head**2 + diam_neck * length_neck - 0.25 * diam_neck**2) spine_factors = {'somatic': 1, 'axonal_IS': 1, 'axonal_hillock': 1, 'myelinated_axonal': 1, 'basal': 1 + 1.26 * area_of_spine(0.45, 0.15, 0.45), 'apic_trunk': 1 + 1.27 * area_of_spine(0.45, 0.15, 0.45), 'oblique_dendrites': 1 + 1.43 * area_of_spine(0.45, 0.15, 0.45), 'apic_tuft': 1 + 0.6 * area_of_spine(0.56, 0.15, 0.45)} nrn.distance() for key, sec_list in section_dict.items(): for sec in sec_list: sec.insert('pas') sec.e_pas = Vrest sec.Ra = 100. sec.g_pas = 1./rm_dict[key] sec.cm = cm_dict[key] if key == 'apic_trunk': for seg in sec: spine_corr = spine_factors[key] if nrn.distance(seg.x) > 100 else 1. # print sec.name(), nrn.distance(seg.x), spine_corr elif key == 'basal': for seg in sec: spine_corr = spine_factors[key] if nrn.distance(seg.x) > 20 else 1. # print sec.name(), nrn.distance(seg.x), spine_corr else: spine_corr = spine_factors[key] sec.g_pas *= spine_corr sec.cm *= spine_corr
def distance_to_dend(self, section): dend = h.apic[10] if section.name() == dend.name(): return 0 * pq.um h.distance(sec=dend) distance = h.distance(0.5, sec=section) # make sure the distance is to 0.5 in dend section if self.secs_names["tuft"].__contains__(section.name()): distance = distance - (dend.L/2) else: distance = distance + (dend.L/2) return distance * pq.um
def set_apicg (self): h.distance(0,0.5,sec=self.soma) # middle of soma is origin for distance self.nexusdist = nexusdist = 300.0 self.h_gbar_tuftm = h_gbar_tuftm = h_gbar_tuft / gbar_h self.h_lambda = h_lambda = nexusdist / log(h_gbar_tuftm) for sec in self.apic: self.set_calprops(sec) for seg in sec: d = h.distance(seg.x,sec=sec) if d <= nexusdist: seg.gbar_ih = gbar_h * exp(d/h_lambda) else: seg.gbar_ih = h_gbar_tuft self.apic[1].gcalbar_cal = cal_gcalbar * calginc # middle apical dend gets more iL
def distribute_channels(self, as1, as2, d3, a4, a5, a6, a7, g8): h.distance(sec=self.soma) for sec in self.allseclist: # if right cellular compartment (axon, soma or dend) if sec.name().find(as1) >= 0: for seg in sec: dist = h.distance(seg.x, sec=sec) val = calculate_distribution(d3, dist, a4, a5, a6, a7, g8) cmd = 'seg.%s = %g' % (as2, val) exec(cmd)
def set_apicg (self): h.distance(0,0.5,sec=self.soma) # middle of soma is origin for distance self.nexusdist = nexusdist = 300.0 self.h_gbar_tuftm = h_gbar_tuftm = h_gbar_tuft / gbar_h self.h_lambda = h_lambda = nexusdist / log(h_gbar_tuftm) for sec in self.apic: self.set_calprops(sec) for seg in sec: d = h.distance(seg.x,sec=sec) if d <= nexusdist: seg.gbar_ih = gbar_h * exp(d/h_lambda) else: seg.gbar_ih = h_gbar_tuft sec.gbar_nax = gbar_nax * nax_gbar_dendm self.apic[1].gcalbar_cal = cal_gcalbar * calginc # middle apical dend gets more iL
def set_kap_parameters(self, gkapbar, Ekap): h.distance(sec=self.soma) for sec in neuron.h.allsec(): sec.insert('kap') if not sec == self.soma: for seg in sec: dist = fromtodistance(self.soma(0.5), seg) if dist > 500: dist = 500 seg.gkabar_kap = gkapbar * (1 + dist / (500 / self.slope)) seg.ek = Ekap else: self.soma.gkabar_kap = gkapbar
def make_seg_df(cell): seg_locs = cell.morphology.seg_coords['p05'] px = seg_locs[0] py = seg_locs[1] pz = seg_locs[2] df = pd.DataFrame() i = 0 j = 0 lens = [] diams = [] bmtk_ids = [] sec_ids = [] full_names = [] xs = [] parts = [] distances = [] elec_distances = [] h.distance(sec=cell.hobj.soma[0]) zz = h.Impedance() zz.loc(cell.hobj.soma[0](0.5)) zz.compute(25, 1) for sec in cell.hobj.all: for seg in sec: lens.append(seg.sec.L) diams.append(seg.sec.diam) distances.append(h.distance(seg)) bmtk_ids.append(i) xs.append(seg.x) fullsecname = sec.name() sec_ids.append(int(fullsecname.split("[")[2].split("]")[0])) sec_type = fullsecname.split(".")[1][:4] parts.append(sec_type) full_names.append(str(seg)) elec_distances.append(zz.ratio(seg)) j += 1 i += 1 df["BMTK ID"] = bmtk_ids df["X"] = xs df["Type"] = parts df["Sec ID"] = sec_ids df["Distance"] = distances df["Section_L"] = lens df["Section_diam"] = diams df["Coord X"] = px df["Coord Y"] = py df["Coord Z"] = pz df["Elec_distance"] = elec_distances df.to_csv("Segments.csv", index=False)
def get_uncaging_rois_per_dendrite(pv_cell, possible_dends, roi_area_micron, min_max_distance): # let's roll with ~ 30 µM area - should be really 20? u_exp_locations = {} u_exp_distances = {} early_distance_limits = {} for dend in possible_dends: #print dend.name() segs = [ seg for seg in dend if np.logical_and( h.distance(seg.x, sec=dend) > min_max_distance[0], h.distance(seg.x, sec=dend) < min_max_distance[1]) ] distances = [h.distance(seg.x, sec=dend) for seg in segs] tot_distance = h.distance(segs[-1].x, sec=dend) - h.distance(segs[0].x, sec=dend) n_locs = int(np.rint(tot_distance / roi_area_micron) ) # 35 is the region over which we are uncaging here here #print(n_locs) if n_locs: # trying to find uncaging locations per loaction #print tot_distance, 'total distance,', distances[0], distances[-1] #print n_locs, 'location/s' for i in range(n_locs): key = dend.name() + '_' + str(i) lower_threshold = distances[0] + ((i) * (tot_distance / n_locs)) upper_threshold = distances[0] + ((i + 1) * (tot_distance / n_locs)) #print('***',lower_threshold, upper_threshold) #eary_distance_limits[key] = ('min:', lower_threshold,'max:', upper_threshold, (upper_threshold-lower_threshold)) early_distance_limits[key] = ( lower_threshold, upper_threshold ) # these basically should specify where the syanpses can go segs_for_exp, distances_for_exp = [], [] for i, seg in enumerate(segs): if np.logical_and(distances[i] >= lower_threshold, distances[i] <= upper_threshold): segs_for_exp.append( seg ) # seg and distances are in sync, to check print line below #print(distances[i], h.distance(seg.x, sec = dend)) #print(seg.x) distances_for_exp.append(distances[i]) # not using u_exp_locations[key] = segs_for_exp u_exp_distances[key] = distances_for_exp # not using #print(distances_for_exp) #print(len(u_exp_locations.keys()), ' areas') print(u_exp_distances['jc_tree2_adend2[12]_0']) #print(list(zip(u_exp_locations['jc_tree2_adend2[8]_0'],u_exp_distances['jc_tree2_adend2[8]_0']))) return u_exp_locations, early_distance_limits # u_exp_locations are the segements that correspond to the locations - seem correct
def insert_Ih(self): self.parameters['ih']['gbar_soma'] for sec in self.soma: sec.insert('hd') sec.ghdbar_hd = self.parameters['ih']['gbar_soma'] * PSUM2_TO_SCM2 # sigmoidally increasing Ih in the dendrites. # see Poirazi et al., 2003, Neuron h.distance(sec=self.soma[0]) for sec in it.chain(self.proximal,self.distal): sec.insert('hd') for seg in sec: seg.hd.ghdbar = self.compute_gbar_at_position(h.distance(seg.x,sec=sec), self.parameters['ih']) if DEBUG: print('gbar Ih @ x = %g: %g' % (h.distance(seg.x,sec=sec),seg.hd.ghdbar))
def Biophys1(cell_prop): ''' Set parameters for cells from the Allen Cell Types database Prior to setting parameters will replace the axon with the stub ''' morphology_file_name = str(cell_prop['morphology_file']) hobj = h.Biophys1(morphology_file_name) fix_axon_allactive(hobj) #fix_axon(hobj) # set_params_peri(hobj, cell_prop.model_params) set_params(hobj, cell_prop.model_params) def calc_density_exp(dist): # FILL IN HERE g_max = 2.84922026765e-07 density = g_max * (-0.8696 + 2.087 * np.exp((dist) * 0.0031)) #return dist return density targeted_sections = ['apic'] # only apply to these types of segements h.distance( sec=hobj.soma[0] ) # need this to set all distances relative to soma (not sure if from center?) for sec in hobj.all: sec_type = sec.name().split(".")[1][:4] if sec_type in targeted_sections: # sec.insert('Ih_mod') # insert channel mechanics for seg in sec: dist = h.distance(seg.x) sec_density = calc_density_exp( dist) # calculate the channel density setattr(seg, 'gbar_Ih_mod', sec_density) # 0.0166428509042) for sec in hobj.all: sec_type = sec.name().split(".")[1][:4] if sec_type == 'axon': continue # print the distance! #if sec_type in targeted_sections: print sec.name() for seg in sec: print h.distance(seg.x), seg.gbar_Ih_mod return hobj
def save_connections(graph, sim): """Saves Connections.csv based on the given network. Parameters ---------- graph : BioNetwork the network that the connections are retrieved from sim : BioSimulator the simulation about to be run (not used in this function) """ cells = graph.get_local_cells() cell = cells[list(cells.keys())[0]] h.distance(sec=cell.hobj.soma[0]) #Makes the distances correct. sec_types = [] #soma, apic, or dend weights = [] #scaled conductances (initW) dists = [] #distance from soma node_ids = [ ] #node id within respective node population (exc, prox_inh, dist_inh) names = [] #full NEURON str representation of postsynaptic segment source_pops = [] #node population release_probs = [] #propability of release. for c in cell.connections(): con = c._connector source = c.source_node syn = con.syn() seg = con.postseg() fullsecname = seg.sec.name() source_pops.append(source._population) node_ids.append(source._node_id) weights.append(float(syn.initW)) release_probs.append(float(syn.P_0)) names.append(str(seg)) sec_types.append(fullsecname.split(".")[1][:4]) dists.append(float(h.distance(seg))) df = pd.DataFrame() df["Node ID"] = node_ids df["Distance"] = dists df["Conductance"] = weights df["Type"] = sec_types df["Name"] = names df["Source Population"] = source_pops df["Release Probability"] = release_probs df.to_csv("Connections.csv", index=False)
def get_distance(sec_list, dendritic, axonal): h.distance() distances = [] axon_dists = [] dend_dists = [] for curr_sec in sec_list: curr_dist = h.distance(0.5) distances.append(curr_dist) for curr_sec in dendritic: curr_dist = h.distance(0.5) dend_dists.append(curr_dist) for curr_sec in axonal: curr_dist = h.distance(0.5) axon_dists.append(curr_dist) return distances, axon_dists, dend_dists
def inject_soma(mycell): """ calculate the AP attenuation vs distance after somatic injection """ stim = h.IClamp(0.5, sec = mycell.soma) stim.delay = 0.1 stim.dur = 2.5 stim.amp = 4.0 # set zero distance h.distance(sec = mycell.soma) # Recording: AP waveforms from basal and apical sections basal_seg = list() for sec in mycell.allbasalsec: for seg in sec: basal_seg.append(seg) myvectors_basal = simulate_voltage(5, basal_seg) apical_seg = list() for sec in mycell.allapicalsec: for seg in sec: apical_seg.append(seg) myvectors_apical = simulate_voltage(5, apical_seg) # Plotting peak vs distance peak, dist = list(), list() for sec, vectors in izip(mycell.allbasalsec, myvectors_basal): voltage = vectors.voltage peak.append(np.max(voltage) - voltage[0]) dist.append(-h.distance(0, sec=sec)) peaka, dista = list(), list() for sec, vectors in izip(mycell.allapicalsec, myvectors_apical): voltage = vectors.voltage peak.append(np.max(voltage) - voltage[0]) dist.append(h.distance(0, sec=sec)) plt.plot(dist, peak,'o', markerfacecolor='red') plt.plot(dista, peaka, 'o', markerfacecolor='red') #plt.xlim(xmin=-100, xmax=400) #plt.ylim(ymax=110, ymin=0) plt.show()
def create_lists(vec): for sec in h.allsec(): vec['d_sec'].append(h.distance(1)) vec['diam_sec'].append(sec.diam) rec0 = h.Vector() rec0.record(sec(0.5)._ref_v) vec['V_sec'].append(rec0) rec_Ca = h.Vector() rec_Ca.record(sec(0.5)._ref_Cai) vec['CaConc_sec'].append(rec_Ca) for seg in sec: vec['d_seg'].append(h.distance(0) + sec.L * seg.x) vec['diam_seg'].append(seg.diam) vec['gc'].append(seg.gcabar_it2) rec = h.Vector() rec.record(seg._ref_v) vec['V_seg'].append(rec) rec1 = h.Vector() rec1.record(seg._ref_Cai) vec['CaConc_seg'].append(rec1) return vec
def _longest_path(sec_ref, path=[]): length = 0 ret_path = [] if len(sec_ref.child) == 0: length = h.distance(1, sec=sec_ref.sec) ret_path = path else: for idx, sec in enumerate(sec_ref.child): child_path = path[:] child_path.append(idx) sr = h.SectionRef(sec=sec) p, l = _longest_path(sr, child_path) if l > length: length = l ret_path = p return ret_path, length
def insert_fast_Na_and_delayed_rectifier_K(self): self.parameters['nat'] # sodium and potassium in the soma and axon (if present) if self.has_axon: sections = [sec for sec in it.chain(self.soma,self.axon)] else: sections = self.soma for sec in sections: sec.insert('hh2') sec.ena = 55 sec.ek = -90 if sec in self.soma: sec.vtraub_hh2 += self.parameters['nat']['vtraub_offset_soma'] sec.gnabar_hh2 = self.parameters['nat']['gbar_soma'] * PSUM2_TO_SCM2 sec.gkbar_hh2 = self.parameters['kdr']['gbar_soma'] * PSUM2_TO_SCM2 if self.has_axon: if sec is self.axon[0]: sec.gnabar_hh2 = self.parameters['nat']['gbar_hillock'] * PSUM2_TO_SCM2 sec.vtraub_hh2 += self.parameters['nat']['vtraub_offset_hillock'] elif sec is self.axon[1]: sec.gnabar_hh2 = self.parameters['nat']['gbar_ais'] * PSUM2_TO_SCM2 sec.vtraub_hh2 += self.parameters['nat']['vtraub_offset_ais'] elif sec in self.axon: sec.gnabar_hh2 = self.parameters['nat']['gbar_soma'] * PSUM2_TO_SCM2 sec.vtraub_hh2 += self.parameters['nat']['vtraub_offset_soma'] # sodium and potassium in the dendrites if len(self.basal) > 0: h.distance(sec=self.soma[0]) if 'max_dist' in self.parameters['nat']: max_dist_Na = self.parameters['nat']['max_dist'] else: max_dist_Na = h.distance(1, sec=self.basal[-1]) if 'max_dist' in self.parameters['kdr']: max_dist_K = self.parameters['kdr']['max_dist'] else: max_dist_K = h.distance(1, sec=self.basal[-1]) for sec in self.basal: sec.insert('hh2') sec.ena = 55 sec.ek = -90 sec.vtraub_hh2 += self.parameters['nat']['vtraub_offset_soma'] for seg in sec: dst = h.distance(seg.x,sec=sec) seg.hh2.gnabar = self.compute_gbar_at_position(dst, self.parameters['nat'], max_dist_Na) seg.hh2.gkbar = self.compute_gbar_at_position(dst, self.parameters['kdr'], max_dist_K) if DEBUG: print('gbar INa @ x = %g: %g' % (dst,seg.hh2.gnabar)) print('gbar IK @ x = %g: %g' % (dst,seg.hh2.gkbar)) if len(self.proximal)+len(self.distal) > 0: if 'max_dist' in self.parameters['nat']: max_dist_Na = self.parameters['nat']['max_dist'] else: max_dist_Na = h.distance(1, sec=self.distal[-1]) if 'max_dist' in self.parameters['kdr']: max_dist_K = self.parameters['kdr']['max_dist'] else: max_dist_K = h.distance(1, sec=self.distal[-1]) for sec in it.chain(self.proximal,self.distal): sec.insert('hh2') sec.ena = 55 sec.ek = -90 sec.vtraub_hh2 += self.parameters['nat']['vtraub_offset_soma'] for seg in sec: dst = h.distance(seg.x,sec=sec) seg.hh2.gnabar = self.compute_gbar_at_position(dst, self.parameters['nat'], max_dist_Na) seg.hh2.gkbar = self.compute_gbar_at_position(dst, self.parameters['kdr'], max_dist_K) if DEBUG: print('gbar INa @ x = %g: %g' % (dst,seg.hh2.gnabar)) print('gbar IK @ x = %g: %g' % (dst,seg.hh2.gkbar))
sec.gkabar_kap=h.KMULTP sec.ek=-90 sec.insert('pas') sec.e_pas=h.Vrest sec.g_pas=1/h.RmDend sec.Ra = h.RaAll sec.cm = h.CmDend h('objref apicalList') #apical h('apicalList = new SectionList()') h('for i=0,134 dend[i] apicalList.append') for sec in h.apicalList: h.soma h.distance(0,0) sec.insert('pas') sec.e_pas=h.Vrest sec.g_pas=1/h.RmDend sec.Ra=h.RaAll sec.cm=h.CmDend sec.insert('ds') if sec.diam>0.5 and h.distance()<500: #if sec.diam>0.5: #sec.insert('hd') #sec.ghdbar_hd=h.ghd sec.insert('na3') sec.ar_na3=0.7 sec.gbar_na3=h.gna sec.insert('kdr') sec.ek=-90
from CA3neuron import Neuron from CA3biophysics import Passive, ApicalBasalActive # ========================================================================= # Distance dependent functions (to calculate gnabar_hh) # ========================================================================= def inv_sigmoid(x, Vo, plateau, d50, p): """ inverse sigmoid equation, x is distance """ return ((Vo - plateau) - (Vo - plateau) / (1 + e ** (-(x - d50) * p))) + plateau # inv_sigmoid as a function of only distance fdistance = lambda x: inv_sigmoid(x, 0.08, 0.01, 110.0, 0.04) # let fdistance to take the segment as an argument fsec_apical = lambda section: fdistance(h.distance(0, sec=section)) # fsec_basal = lambda sec: 0.01 fsec_basal = lambda sec: 0.02 def create_neuron(): """ creates an active neuron, with sigmoid decay of gnabar_hh in the dendrites """ neuron = Neuron(ApicalBasalActive) # ** Passive Passive(neuron) # see in Kole et al., 2008 for axon in neuron.axon: axon.g_pas = 1 / 15e3
def distance_to_main_bifurcation(self, section, position=0.5): dend = self.section(self.bifurcation_info[0]) h.distance(0,self.bifurcation_info[1],sec=dend) distance = h.distance(position, sec=section) return distance * pq.um
def fromtodistance(origin_segment, to_segment): h.distance(0, origin_segment.x, sec=origin_segment.sec) return h.distance(to_segment.x, sec=to_segment.sec)
def voltage_deflection(neuron, amp=-0.5, dur=500, delay=100): stim = h.IClamp(neuron.soma[0](0.5)) stim.amp = amp stim.dur = dur stim.delay = delay rec_t = h.Vector() rec_t.record(h._ref_t) recorders = [] soma_idx = [] basal_idx = [] proximal_idx = [] distal_idx = [] cnt = 0 distances = [] h.distance(sec=neuron.soma[0]) for sec in it.chain(neuron.soma,neuron.basal,neuron.proximal,neuron.distal): for seg in sec: rec = h.Vector() rec.record(seg._ref_v) recorders.append(rec) dst = h.distance(seg.x, sec=sec) if sec in neuron.soma: soma_idx.append(cnt) elif sec in neuron.basal: basal_idx.append(cnt) dst *= -1 elif sec in neuron.proximal: proximal_idx.append(cnt) elif sec in neuron.distal: distal_idx.append(cnt) distances.append(dst) cnt += 1 soma_idx = np.array(soma_idx) basal_idx = np.array(basal_idx) proximal_idx = np.array(proximal_idx) distal_idx = np.array(distal_idx) CA3.utils.run(tend=stim.dur+stim.delay+100, V0=-70, temperature=36) idx = np.where(np.array(rec_t) < stim.dur + stim.delay)[0][-1] voltages = [] for rec in recorders: voltages.append(rec[idx]) distances = np.array(distances) voltages = np.array(voltages) soma = {'distances': distances[soma_idx], 'voltages': voltages[soma_idx]} if len(basal_idx) > 1: m = np.min(distances[basal_idx]) M = np.max(distances[basal_idx]) basal = {'distances': (distances[basal_idx]-m)/(M-m), 'voltages': voltages[basal_idx]} else: basal = {'distances': [0.5], 'voltages': voltages[basal_idx]} if len(proximal_idx) > 1: m = np.min(distances[proximal_idx]) M = np.max(distances[proximal_idx]) proximal = {'distances': (distances[proximal_idx]-m)/(M-m), 'voltages': voltages[proximal_idx]} else: proximal = {'distances': [0.5], 'voltages': voltages[proximal_idx]} if len(distal_idx) > 1: m = np.min(distances[distal_idx]) M = np.max(distances[distal_idx]) distal = {'distances': (distances[distal_idx]-m)/(M-m), 'voltages': voltages[distal_idx]} else: distal = {'distances': [0.5], 'voltages': voltages[distal_idx]} stim.amp = 0 del stim return distances,voltages,soma,basal,proximal,distal
def distance_to_soma(self, section, position=0.5): soma = self.soma h.distance(0,0.5,sec=soma) distance = h.distance(position, sec=section) return distance * pq.um
def distance(origin, end, x=0.5): h.distance(sec=origin) return h.distance(x, sec=end)
mysyn.tonset = 0.5 # ms mysyn.tau0 = 0.2 # ms mysyn.tau1 = 2.5 # ms mysyn.gmax = 300e-6 # in uS #------------------------------------------------------------------------- # Voltage-clamp at the soma # set soma as zero distance # insert a synapse at the soma #------------------------------------------------------------------------- VClamp = h.SEClamp(0.5, sec= mycell.soma) VClamp.rs = 0.1 # MegaOhms VClamp.amp1 = v_init # see global variables VClamp.dur1 = tstop # see global variables h.distance(0, 0.5, sec = mycell.soma) # set soma as origin # see in synapse.mod mysyn = h.synapse(0.5, sec = mycell.soma) mysyn.tonset = 2.5 # ms mysyn.tau0 = 0.2 # ms mysyn.gmax = 300e-6 # in microSiemens #------------------------------------------------------------------------- # Define simulation #------------------------------------------------------------------------- h.load_file('stdrun.hoc') # setup simulation h.tstop = tstop # see global variables h.v_init = v_init # see global variables current = h.Vector() current.record(VClamp._ref_i)
def test(): rall = 113 # axial resistance cap = 1.1 # membrane capacitance Rm = 45000.0 # membrane resistance ## INSERT ION CHANNELS: for sec in h.allsec(): sec.insert("pas") sec.e_pas = Epas sec.g_pas = 1/Rm sec.Ra = rall sec.cm = cap sec.insert("Cad") sec.insert("it2") sec.insert("hh2") sec.ena = 50 # Reversal potential for sodium sec.ek = -90 # Reversal potential for potassium ################################################################## # Channel densities gna = 0.04 # S/cm2 gkdr = 0.04 gcat = 0.0001 ################################################################### ## INSERT STIMULATION ELECTRODES stim = h.IClamp(h.soma(0.5)) # stim = h.IClamp(h.dend[99](0.5)) stim.delay = 1000 stim.dur = 10 stim.amp = 0#.25 #nA ################################################################### ## INSERT SYNAPSES syn = h.Exp2Syn(h.dend[99](1)) # Sum of exp's syn.tau1 = 0.5 # Rise (ms) syn.tau2 = 2 # Decay (ms) syn.e = 10 # Reversal # pot. s = h.NetStim(0.5) s.start = 1000 # start for distal synapses s.number = 1 s.noise = 0 nc = h.NetCon(s,syn,sec = sec) nc.weight[0] = 0.015 # syn1 = h.Exp2Syn(h.dend[83](1)) # Sum of exp's # syn1.tau1 = 0.5 # Rise (ms) # syn1.tau2 = 2 # Decay (ms) # syn1.e = 10 # Reversal # pot. # s1 = h.NetStim(0.5) # s1.start = 1100 # start for distal synapses # s1.number = 1 # s1.noise = 0 # nc1 = h.NetCon(s1,syn1,sec = sec) # nc1.weight[0] = 0.05 ################################################################# # Split the morphology up in a suitable number of segments freq = 50 h.geom_nseg(freq) tot = 0 for sec in h.allsec(): tot += sec.nseg h.distance() print "total # of segments (50Hz):", tot ################################################################## # INITIALIZE gcat_func = lambda dist : 0.1054*gcat*(1 + 0.04*dist) def initialize(): global Epas h.celsius = celsius for sec in h.soma: h.distance() for sec in h.allsec(): sec.v = Epas sec.e_pas = Epas sec.insert("pas") sec.e_pas = Epas sec.g_pas = 1/Rm sec.Ra = rall sec.cm = cap sec.gnabar_hh2 = 0 sec.gkbar_hh2 = 0 dist = h.distance(0.5) # sec.gcabar_it2 = gcat_func(dist) sec.gcabar_it2 = gcat for sec in h.soma: sec.gnabar_hh2 = gna sec.gkbar_hh2 = gkdr # sec.gcabar_it2 = 0.1054*gcat sec.gcabar_it2 = gcat h.finitialize() h.fcurrent() cvode.re_init() initialize() vec ={} for var in 't', 'd_sec', 'd_seg', 'diam_sec','gc','diam_seg','stim_curr': vec[var] = h.Vector() for var in 'V_sec', 'V_seg', 'CaConc_sec','CaConc_seg': vec[var] = h.List() def create_lists(vec): for sec in h.allsec(): vec['d_sec'].append(h.distance(1)) vec['diam_sec'].append(sec.diam) rec0 = h.Vector() rec0.record(sec(0.5)._ref_v) vec['V_sec'].append(rec0) rec_Ca = h.Vector() rec_Ca.record(sec(0.5)._ref_Cai) vec['CaConc_sec'].append(rec_Ca) for seg in sec: vec['d_seg'].append(h.distance(0) + sec.L * seg.x) vec['diam_seg'].append(seg.diam) vec['gc'].append(seg.gcabar_it2) rec = h.Vector() rec.record(seg._ref_v) vec['V_seg'].append(rec) rec1 = h.Vector() rec1.record(seg._ref_Cai) vec['CaConc_seg'].append(rec1) return vec ##################################### create_lists(vec) # run the simulation vec['t'].record(h._ref_t) # vec['current'].record(VC_patch._ref_i) vec['stim_curr'].record(stim._ref_i) h.load_file("stdrun.hoc") h.tstop = 2500 # Simulation time h.t = -500 h.run() return vec
def test(Tdist, inputcond): rall = 113 # axial resistance cap = 1.1 # membrane capacitance Rm = 45000.0 # membrane resistance ## INSERT ION CHANNELS: for sec in h.allsec(): sec.insert("pas") sec.e_pas = Epas sec.g_pas = 1/Rm sec.Ra = rall sec.cm = cap sec.insert("Cad") sec.insert("it2") sec.insert("hh2") sec.ena = 50 # Reversal potential for sodium sec.ek = -90 # Reversal potential for potassium ################################################################## # Channel densities gna = 0.18 # S/cm2 gkdr = 0.4 gcat = 1.e-4 if inputcond == 1: wsyn = 0 iamp = 0.25 if inputcond == 2: wsyn = 0.015 iamp = 0 if inputcond == 3: wsyn = 0 iamp = 0.25 gna = 0 ################################################################### ## INSERT STIMULATION ELECTRODES stim = h.IClamp(.5) stim.delay = 1000 stim.dur = 10 stim.amp = iamp ################################################################### ## INSERT SYNAPSES syn = h.Exp2Syn(h.dend[99](1)) # Sum of exp's syn.tau1 = 0.5 # Rise syn.tau2 = 2 # Decay syn.e = 10 # Reversal # pot s = h.NetStim(0.5) s.start = 1000 # start for distal synapses s.number = 1 s.noise = 0 nc = h.NetCon(s,syn,sec = sec) nc.weight[0] = wsyn ################################################################# # for sec in h.soma: freq = 50 h.geom_nseg(freq) tot = 0 for sec in h.allsec(): tot += sec.nseg h.distance() print "total # of segments (50Hz):", tot ################################################################## # INITIALIZE def initialize(Tdist): global Epas h.celsius = celsius for sec in h.soma: h.distance() for sec in h.allsec(): sec.v = Epas sec.e_pas = Epas sec.insert("pas") sec.e_pas = Epas sec.g_pas = 1/Rm sec.Ra = rall sec.cm = cap sec.gnabar_hh2 = 0 sec.gkbar_hh2 = 0 for seg in sec: if Tdist == 1: seg.gcabar_it2 = gcat if Tdist == 2: seg.gcabar_it2 = gcat * (1 + 0.04 * (h.distance(0) + sec.L * seg.x)) * 0.10539397661220173 for sec in h.soma: sec.gnabar_hh2 = gna sec.gkbar_hh2 = gkdr if Tdist == 1: seg.gcabar_it2 = gcat if Tdist == 2: seg.gcabar_it2 = gcat * 0.10539397661220173 h.finitialize() h.fcurrent() cvode.re_init() initialize(Tdist) vec ={} for var in 't', 'd_sec', 'd_seg', 'diam_sec','gc','diam_seg','stim_curr': vec[var] = h.Vector() for var in 'V_sec', 'V_seg', 'CaConc_sec','CaConc_seg': vec[var] = h.List() def create_lists(vec): for sec in h.allsec(): vec['d_sec'].append(h.distance(1)) vec['diam_sec'].append(sec.diam) rec0 = h.Vector() rec0.record(sec(0.5)._ref_v) vec['V_sec'].append(rec0) rec_Ca = h.Vector() rec_Ca.record(sec(0.5)._ref_Cai) vec['CaConc_sec'].append(rec_Ca) for seg in sec: vec['d_seg'].append(h.distance(0) + sec.L * seg.x) vec['diam_seg'].append(seg.diam) vec['gc'].append(seg.gcabar_it2) rec = h.Vector() rec.record(seg._ref_v) vec['V_seg'].append(rec) rec1 = h.Vector() rec1.record(seg._ref_Cai) vec['CaConc_seg'].append(rec1) return vec ##################################### create_lists(vec) # run the simulation vec['t'].record(h._ref_t) # vec['current'].record(VC_patch._ref_i) vec['stim_curr'].record(stim._ref_i) h.load_file("stdrun.hoc") h.tstop = 2500 # Simulation time h.t = -500 h.run() return vec
from CA3neuron import Neuron from CA3biophysics import ApicalBasalActive from CA3simulations import simulate_voltage #========================================================================= # Distance dependent functions (to calculate gnabar_hh) #========================================================================= def inv_sigmoid(x, Vo, plateau, d50, p): """ inverse sigmoid equation, x is distance """ return ((Vo-plateau)-(Vo-plateau)/(1+e**(-(x-d50)*p)) ) + plateau # inv_sigmoid as a function of only distance fdistance = lambda x:inv_sigmoid(x, Vo=0.8, plateau=0.01, d50=110., p=0.04) # let fdistance to take the segment as an argument fsec_apical = lambda section : fdistance( h.distance(0, sec=section) ) #fsec_basal = lambda sec: 0.01 fsec_basal = lambda sec: 0.02 # morphology and biophysics neuron = Neuron(ApicalBasalActive) h.distance(sec=neuron.soma) neuron.get_Active().activatedendrites(fsec_apical, fsec_basal) neuron.soma.gnabar_hh = 0.0 #========================================================================= # Instrumentation: current injection #========================================================================= stim = h.IClamp(0.5, sec = neuron.dend[112])
from CA3neuron import Neuron from CA3biophysics import ApicalBasalActive from CA3simulations import simulate_voltage #========================================================================= # Distance dependent functions (to calculate gnabar_hh) #========================================================================= def inv_sigmoid(x, Vo, plateau, d50, p): """ inverse sigmoid equation, x is distance """ return ((Vo-plateau)-(Vo-plateau)/(1+e**(-(x-d50)*p)) ) + plateau # inv_sigmoid as a function of only distance fdistance = lambda x:inv_sigmoid(x, 0.04, 0.01, 110., 0.04) # let fdistance to take the segment as an argument fsec_apical = lambda section : fdistance( h.distance(0, sec=section) ) #fsec_basal = lambda sec: 0.01 fsec_basal = lambda sec: 0.02 #========================================================================= # Morphology and Biophysics #========================================================================= # construct a CA3 neuron with active condutances only in soma neuron = Neuron(ApicalBasalActive) # somatic active default conductances # set zero point in soma h.distance(sec=neuron.soma) neuron.get_Active().activatedendrites(fapical = fsec_apical, fbasal=fsec_basal) #=========================================================================
def distance(mysec): """ returns the distance of the segment to the soma """ mysoma = mysec.cell().soma h.distance(sec = mysoma) return h.distance(0, sec = mysec)