Exemple #1
0
    def calc_tx(self):
        """ Set the fractional illumionation for all sections which have chanrhod
        density mechanisms """
        from numpy import sqrt, sinh, cosh, arccos, tan, array, dot, isnan, pi
        self.interpxyz()

        # !All units should be in um
        #---------------------------------------------------------------------------
        # Location of each segment
        #---------------------------------------------------------------------------
        seg_xyz = []
        for sec in h.allsec():
            #if h.ismembrane('chanrhod', sec=sec):
            if h.ismembrane('chanrhod', sec=sec):
                for seg in sec:
                    xyz = seg.x_chanrhod, seg.y_chanrhod, seg.z_chanrhod
                    seg_xyz.append(xyz)
        seg_xyz = array(seg_xyz)
        Tx = self.find_illumination(seg_xyz[:,0],seg_xyz[:,1],seg_xyz[:,2])
        #---------------------------------------------------------------------------
        # Set Tx_chanrhod
        #---------------------------------------------------------------------------
        ii = 0
        #for sec in h.allsec():
            #if h.ismembrane('chanrhod', sec=sec):
                #for seg in sec:
                    #seg.Tx_chanrhod = Tx[ii]
                    #ii+=1
        for sec in h.allsec():
            if h.ismembrane('chanrhod', sec=sec):
                for seg in sec:
                    seg.Tx_chanrhod = Tx[ii]
                    ii+=1
Exemple #2
0
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
Exemple #3
0
def check_values():
    """
  Verify that target values are equal to source values.
  """
    values = {}
    for gid, c in model[0].items():
        vi = c.soma(.5).v
        if (h.ismembrane("extracellular", sec=c.soma)):
            vi += c.soma(.5).vext[0]
        values[gid] = {
            'v': vi,
            'nai': c.soma(.5).nai,
            'amp': c.ic.amp,
            'amp1': c.vc.amp1,
            'amp2': c.vc.amp2
        }
    x = pc.py_gather(values, 0)
    if rank == 0:
        values = {}
        for v in x:
            values.update(v)
        ncell = len(values)
        for gid in values:
            v1 = values[gid]
            v2 = values[(gid + ncell - 1) % ncell]
            assert (v1['v'] == v2['amp'])
            assert (v1['v'] == v2['amp1'])
            assert (v1['nai'] == v2['amp2'])
Exemple #4
0
 def area_in_list(self,seclist):
     area = 0
     for sec in seclist:
         if h.ismembrane('chanrhod',sec = sec):
             for seg in sec:
                 area += h.area(seg.x, sec=sec) # um2
     return area
Exemple #5
0
    def pos_lfp(self):
        ## Calculate the average LFP of select cells in the network,
        ##  only including cells whose somata are within maxEDist
        ##  microns of the (x,y,z) recording electrode location

        vlfp = 0.

        for pop_name in self.celltypes:
            lfp_ids = self.lfp_ids[pop_name]
            lfp_coeffs = self.lfp_coeffs[pop_name]
            ## Iterate over all cell types
            for i in range(0, int(lfp_ids.size())):
                ## Iterate over the cells chosen for the LFP computation
                gid = lfp_ids.x[i]
                cell = self.pc.gid2cell(gid)

                for sec in list(cell.all):
                    if h.ismembrane('extracellular', sec=sec):
                        j = 0
                        for seg in sec:
                            vlfp = vlfp + (seg._ref_i_membrane[0] * lfp_coeffs.o(i).x[j])
                            j = j + 1

        meanlfp = self.pc.allreduce(vlfp, 1)
        return meanlfp
Exemple #6
0
def check_values():
    """
    Verify that target values are equal to source values.
    """
    values = {}
    for gid, c in model[0].items():
        vi = c.soma(0.5).v
        if h.ismembrane("extracellular", sec=c.soma):
            vi += c.soma(0.5).vext[0]
        values[gid] = {
            "v": vi,
            "nai": c.soma(0.5).nai,
            "amp": c.ic.amp,
            "amp1": c.vc.amp1,
            "amp2": c.vc.amp2,
        }
    x = pc.py_gather(values, 0)
    if rank == 0:
        values = {}
        for v in x:
            values.update(v)
        ncell = len(values)
        for gid in values:
            v1 = values[gid]
            v2 = values[(gid + ncell - 1) % ncell]
            assert v1["v"] == v2["amp"]
            assert v1["v"] == v2["amp1"]
            assert v1["nai"] == v2["amp2"]
Exemple #7
0
    def interpxyz(self):
        """
        Equivalent methods interpxyz and setrx from the xtra mechanism available on the NEURON website from Ted Carnevale
        Setrx has been modified to integrate the use of multipolar electrodes

        interpolated data, spaced at regular intervals

        Returns:

        """

        # First, need to interpolate centers unto all compartments; from interpxyz.hoc
        for sec in self.allseclist:

            if h.ismembrane('xtra', sec=sec):

                nn = int(h.n3d(sec=sec))
                xx = h.Vector(nn)
                yy = h.Vector(nn)
                zz = h.Vector(nn)
                length = h.Vector(nn)

                # for ii in xrange(nn):
                for ii in range(nn):
                    xx.x[ii] = h.x3d(ii, sec=sec)
                    yy.x[ii] = h.y3d(ii, sec=sec)
                    zz.x[ii] = h.z3d(ii, sec=sec)
                    length.x[ii] = h.arc3d(ii, sec=sec)

                # to use Vector class's .interpolate() must first scale the independent variable i.e. normalize length along centroid
                length.div(length.x[nn - 1])
                # initialize the destination "independent" vector
                rr = h.Vector(sec.nseg + 2)
                rr.indgen(1. / sec.nseg)
                rr.sub(1. / (2. * sec.nseg))
                rr.x[0] = 0.
                rr.x[sec.nseg + 1] = 1.

                # length contains the normalized distances of the pt3d points along the centroid of the section.
                # These are spaced at irregular intervals.
                # range contains the normalized distances of the nodes along the centroid of the section.
                # These are spaced at regular intervals.

                # Ready to interpolate.
                xint = h.Vector(sec.nseg + 2)
                yint = h.Vector(sec.nseg + 2)
                zint = h.Vector(sec.nseg + 2)
                xint.interpolate(rr, length, xx)
                yint.interpolate(rr, length, yy)
                zint.interpolate(rr, length, zz)

                # for each node, assign the xyz values to x_xtra, y_xtra, z_xtra
                # don't bother computing coords of the 0 and 1 ends
                # also avoid writing coords of the 1 end into the last internal node's coords
                for ii in range(1, sec.nseg + 1):
                    xr = rr.x[ii]
                    sec(xr).x_xtra = xint.x[ii]
                    sec(xr).y_xtra = yint.x[ii]
                    sec(xr).z_xtra = zint.x[ii]
Exemple #8
0
 def illuminated_area_in_list(self,seclist,Tx_threshold = 0.001):
     area = 0
     for sec in seclist:
         if h.ismembrane('chanrhod',sec = sec):
             for seg in sec:
                 if seg.Tx_chanrhod>Tx_threshold:
                     area += h.area(seg.x, sec=sec) # um2
     return area
Exemple #9
0
def make_uniform(Vrest):
    """ Makes the cell uniform. Doesn't really work for INaP yet,
    since it is way to strong it seems
    """
    nrn.t = 0

    nrn.finitialize(Vrest)
    nrn.fcurrent()

    for sec in nrn.allsec():
        for seg in sec:
            seg.e_pas = seg.v
            if nrn.ismembrane("na_ion"):
                seg.e_pas += seg.ina/seg.g_pas
            if nrn.ismembrane("k_ion"):
                seg.e_pas += seg.ik/seg.g_pas
            if nrn.ismembrane("ca_ion"):
                seg.e_pas += seg.ica/seg.g_pas
            if nrn.ismembrane("Ih_BK_prox"):
                seg.e_pas += seg.ih_Ih_BK_prox/seg.g_pas
            if nrn.ismembrane("Ih_BK_dist"):
                seg.e_pas += seg.ih_Ih_BK_dist/seg.g_pas
            if nrn.ismembrane("Ih_BK_prox_frozen"):
                seg.e_pas += seg.ih_Ih_BK_prox_frozen/seg.g_pas
            if nrn.ismembrane("Ih_BK_dist_frozen"):
                seg.e_pas += seg.ih_Ih_BK_dist_frozen/seg.g_pas
    def current_balancein(self):
        """ This is a translation from Poirazi's current-balancein.hoc code
        """
        h.finitialize(-48.9)  # min 42
        #        h.finitialize(-70.7)
        h.fcurrent()

        for sec in self.all:
            if h.ismembrane('na_ion'):
                sec.e_pas = sec.v + sec.ina / sec.g_pas
            if h.ismembrane('k_ion'):
                sec.e_pas = sec.e_pas + sec.ik / sec.g_pas
            if h.ismembrane('ca_ion'):
                sec.e_pas = sec.e_pas + sec.ica / sec.g_pas
            if h.ismembrane('h'):
                sec.e_pas = sec.e_pas + sec.ihi / sec.g_pas

        h.fcurrent()
Exemple #11
0
 def channels_in_list(self,seclist):
     channels = 0
     for sec in seclist:
         if h.ismembrane('chanrhod',sec = sec):
             for seg in sec:
                 rho  = seg.channel_density_chanrhod/1e8 # 1/cm2 --> 1/um2
                 area = h.area(seg.x, sec=sec) # um2
                 n = rho * area
                 channels += n
     return channels
Exemple #12
0
 def get_icat(self):
     """ Determine the total amount of channelrhodopsin current in the cell
     """
     icat = 0
     for sec in h.allsec():
         if h.ismembrane('chanrhod', sec=sec):
             for seg in sec:
                 i = seg.icat_chanrhod  # (mA/cm2)
                 area = h.area(seg.x, sec=sec) / 1e8  # cm2
                 icat += area * i  # mA
     return icat
Exemple #13
0
 def get_closestsection(self):
     """ Find the closest chanrhod+ section """
     closest_sec=None
     closest_sec_distance=1e9
     for sec in h.allsec():
         #if h.ismembrane('chanrhod', sec = sec):
         if h.ismembrane('chanrhod', sec = sec):
             sec_distance = self.get_distance(sec)
             if sec_distance<closest_sec_distance:
                 closest_sec=sec
                 closest_sec_distance=sec_distance
     return closest_sec
Exemple #14
0
 def open_channels_in_list(self,seclist):
     open_channels = 0
     for sec in seclist:
         if h.ismembrane('chanrhod', sec = sec):
             for seg in sec:
                 rho  = seg.channel_density_chanrhod/1e8 # 1/cm2 --> 1/um2
                 area = h.area(seg.x, sec=sec) # um2
                 try:
                     f_open = seg.o2_chanrhod + seg.o1_chanrhod # open fraction # 4 state model
                 except:
                     f_open = seg.o1_chanrhod # open fraction # 3 state model
                 n = f_open * rho * area
                 open_channels += n
     return open_channels
Exemple #15
0
 def init_once(self):
     for sec in self.all:  #forall within an object just accesses the sections belonging to the object
         sec.insert('pas')  # passive
         sec.insert(
             'savedist'
         )  # mechanism to keep track of distance from soma even after multisplit
         sec.insert('ih')  # h-current in Ih_kole.mod
         sec.insert('nax')  # Na current
         sec.insert('kdr')  # K delayed rectifier current
         sec.insert('kap')  # K-A current
         sec.insert('k_ion')
         sec.insert('na_ion')
         if not (h.ismembrane('ih', sec=sec)):
             print sec
     self.setallprop()
     self.addapicchan()
     self.apicchanprop()
     self.addbasalchan()
     self.basalchanprop()
     # spiny:
     #	for i=2, 102 apic[i] spiny.append()
     #	for i=0, 68 dend[i] spiny.append()
     # Skips first two apicals
     for i in range(len(self.apic)):
         if (i != 0) and (i != 1):
             self.apic[i].cm = spinecapfactor * self.apic[
                 i].cm  # spinecapfactor * cm
             self.apic[
                 i].g_pas = spinecapfactor / rm  # spinecapfactor * (1.0/rm)
     for sec in self.dend:
         sec.cm = spinecapfactor * sec.cm
         sec.g_pas = spinecapfactor / rm
     self.optimize_nseg()
     self.setgbarnaxd()
     self.setgbarkapd()  # kap in apic,basal dends
     self.setgbarkdrd()  # kdr in apic,basal dends
     self.sethgbar()  # distributes HCN conductance
     for sec in self.soma:
         sec.insert('kdmc')
         sec.insert('ca_ion')
         sec.insert('cadad')
         sec.insert('cal')
         sec.insert('can')
         sec.insert('kBK')
     self.setsomag()
     # axon has I_KD, and more I_Na, I_KA, I_KDR, and no I_h
     # K-D current in soma and axon only
     for sec in self.axon:
         sec.insert('kdmc')
     self.setaxong()
Exemple #16
0
 def interpxyz(self):
     """ interpolated data, spaced at regular intervals
     """
             # First, need to interpolate centers unto all compartments; from interpxyz.hoc
     for sec in h.allsec():
         #if h.ismembrane('chanrhod',sec=sec):
         if h.ismembrane('chanrhod',sec=sec):
             nn = h.n3d(sec=sec).__int__()
             xx = h.Vector(nn)
             yy = h.Vector(nn)
             zz = h.Vector(nn)
             length = h.Vector(nn)
             for ii in range(nn):
                 xx.x[ii] = h.x3d(ii,sec=sec)
                 yy.x[ii] = h.y3d(ii,sec=sec)
                 zz.x[ii] = h.z3d(ii,sec=sec)
                 length.x[ii] = h.arc3d(ii,sec=sec)
             # to use Vector class's .interpolate() must first scale the
             # independent variable i.e. normalize length along centroid
             length.div(length.x[nn-1])
             # initialize the destination "independent" vector
             rr = h.Vector(sec.nseg+2)
             rr.indgen(1./sec.nseg)
             rr.sub(1./(2.*sec.nseg))
             rr.x[0]=0.
             rr.x[sec.nseg+1]=1.
             # length contains the normalized distances of the pt3d points
             # along the centroid of the section.  These are spaced at
             # irregular intervals.
             # range contains the normalized distances of the nodes along the
             # centroid of the section.  These are spaced at regular intervals.
             # Ready to interpolate.
             xint = h.Vector(sec.nseg+2)
             yint = h.Vector(sec.nseg+2)
             zint = h.Vector(sec.nseg+2)
             xint.interpolate(rr, length, xx)
             yint.interpolate(rr, length, yy)
             zint.interpolate(rr, length, zz)
             # for each node, assign the xyz values to x_xtra, y_xtra, z_xtra
             # don't bother computing coords of the 0 and 1 ends
             # also avoid writing coords of the 1 end into the last internal node's coords
             for ii in range(1,sec.nseg+1):
                 xr = rr.x[ii]
                 #sec(xr).x_chanrhod = xint.x[ii]
                 #sec(xr).y_chanrhod = yint.x[ii]
                 #sec(xr).z_chanrhod = zint.x[ii]
                 sec(xr).x_chanrhod = xint.x[ii]
                 sec(xr).y_chanrhod = yint.x[ii]
                 sec(xr).z_chanrhod = zint.x[ii]
Exemple #17
0
    def set_nax_ina_vectors(self, sections):
        """
        Sets vectors for recording of Na channel-mediated sodium current from sections in the list.

        Parameters
        ----------
        sections : list
            the list containing the names of sections
        """
        for sec in self.CA1.all:
            if sec.hname().split('.')[1] in sections and h.ismembrane('nax',
                                                                      sec=sec):
                na_vecs = []
                for seg in sec.allseg():
                    vec = h.Vector().record(seg._ref_ina_nax)
                    na_vec = RecordingVector(section=sec.hname(),
                                             segment_x=seg.x,
                                             vec=vec)
                    na_vecs.append(na_vec)
                self.ina_vecs[sec.hname().split('.')[1]] = na_vecs
Exemple #18
0
    def set_cal2_ica_vectors(self, sections):
        """
        Sets vectors for recording of CaL channel-mediated calcium current from sections in the list.

        Parameters
        ----------
        sections : list
            the list containing the names of sections
        """
        for sec in self.CA1.all:
            if sec.hname().split('.')[1] in sections and h.ismembrane('cal',
                                                                      sec=sec):
                cal2_ica_vecs = []
                for seg in sec.allseg():
                    vec = h.Vector().record(seg._ref_ica_cal)
                    cal2_ica_vec = RecordingVector(section=sec.hname(),
                                                   segment_x=seg.x,
                                                   vec=vec)
                    cal2_ica_vecs.append(cal2_ica_vec)
                self.cal2_ica_vecs[sec.hname().split('.')[1]] = cal2_ica_vecs
Exemple #19
0
    def setup_lfp_coeffs(self):

        ex, ey, ez = self.epoint
        for pop_name in self.celltypes:

            lfp_ids = self.lfp_ids[pop_name]
            lfp_types = self.lfp_types[pop_name]
            lfp_coeffs = self.lfp_coeffs[pop_name]

            for i in range(0, int(lfp_ids.size())):
                ## Iterates over all cells chosen for the LFP computation

                gid = lfp_ids.x[i]
                cell = self.pc.gid2cell(gid)

                ## Iterates over each compartment of the cell
                for sec in list(cell.all):
                    if h.ismembrane('extracellular', sec=sec):

                        nn = sec.n3d()

                        xx = h.Vector(nn)
                        yy = h.Vector(nn)
                        zz = h.Vector(nn)
                        ll = h.Vector(nn)

                        for ii in range(0, nn):
                            xx.x[ii] = sec.x3d(ii)
                            yy.x[ii] = sec.y3d(ii)
                            zz.x[ii] = sec.z3d(ii)
                            ll.x[ii] = sec.arc3d(ii)

                        xint = h.Vector(sec.nseg + 2)
                        yint = h.Vector(sec.nseg + 2)
                        zint = h.Vector(sec.nseg + 2)

                        interpxyz(nn, sec.nseg, xx, yy, zz, ll, xint, yint, zint)

                        j = 0
                        sx0 = xint.x[0]
                        sy0 = yint.x[0]
                        sz0 = zint.x[0]
                        for seg in sec:

                            sx = xint.x[j]
                            sy = yint.x[j]
                            sz = zint.x[j]

                            ## l = L/nseg is compartment length 
                            ## rd is the perpendicular distance from the electrode to a line through the compartment
                            ## ld is longitudinal distance along this line from the electrode to one end of the compartment
                            ## sd = l - ld is longitudinal distance to the other end of the compartment
                            l = float(sec.L) / sec.nseg
                            rd = math.sqrt((ex - sx) * (ex - sx) + (ey - sy) * (ey - sy) + (ez - sz) * (ez - sz))
                            ld = math.sqrt((sx - sx0) * (sx - sx0) + (sy - sy0) * (sy - sy0) + (sz - sz0) * (sz - sz0))
                            sd = l - ld
                            k = 0.0001 * h.area(seg.x) * (self.rho / (4.0 * math.pi * l)) * abs(math.log(
                                ((math.sqrt(ld * ld + rd * rd) - ld) / (math.sqrt(sd * sd + rd * rd) - sd))))
                            if math.isnan(k):
                                k = 0.
                            ## Distal cell
                            if (lfp_types.x[i] == 2):
                                k = (1.0 / self.fdst) * k
                            ##printf ("host %d: npole_lfp: gid = %d i = %d j = %d r = %g h = %g k = %g\n", pc.id, gid, i, j, r, h, k)
                            lfp_coeffs.o(i).x[j] = k
                            j = j + 1
Exemple #20
0
def getCellParams(cell):
    dirCell = dir(cell)

    if 'all_sec' in dirCell:
        secs = cell.all_sec
    elif 'sec' in dirCell:
        secs = [cell.sec]
    elif 'allsec' in dir(h):
        secs = [sec for sec in h.allsec()]
    elif 'soma' in dirCell:
        secs = [cell.soma]
    else:
        secs = []
    

    # create dict with hname of each element in dir(cell)
    dirCellHnames = {}  
    for dirCellName in dirCell:
        try:
            dirCellHnames.update({getattr(cell, dirCellName).hname(): dirCellName})
        except:
            pass
    # create dict with dir(cell) name corresponding to each hname 
    dirCellSecNames = {} 
    for sec in secs:
        dirCellSecNames.update({hname: name for hname,name in dirCellHnames.iteritems() if hname == sec.hname()})

    secDic = {}
    synMechs = []
    for sec in secs: 
        # create new section dict with name of section
        secName = getSecName(sec, dirCellSecNames)

        if len(secs) == 1:
            secName = 'soma' # if just one section rename to 'soma'
        secDic[secName] = {'geom': {}, 'topol': {}, 'mechs': {}}  # create dictionary to store sec info

        # store geometry properties
        standardGeomParams = ['L', 'nseg', 'diam', 'Ra', 'cm']
        secDir = dir(sec)
        for geomParam in standardGeomParams:
            #if geomParam in secDir:
            try:
                secDic[secName]['geom'][geomParam] = sec.__getattribute__(geomParam)
            except:
                pass

        # store 3d geometry
        sec.push()  # access current section so ismembrane() works
        numPoints = int(h.n3d())
        if numPoints: 
            points = []
            for ipoint in range(numPoints):
                x = h.x3d(ipoint)
                y = h.y3d(ipoint)
                z = h.z3d(ipoint)
                diam = h.diam3d(ipoint)
                points.append((x, y, z, diam))
            secDic[secName]['geom']['pt3d'] = points

        # store mechanisms
        varList = mechVarList()  # list of properties for all density mechanisms and point processes
        ignoreMechs = ['dist']  # dist only used during cell creation 
        ignoreVars = []  # 
        mechDic = {}
        ionDic = {}
        
        for mech in dir(sec(0.5)): 
            if h.ismembrane(mech) and mech not in ignoreMechs:  # check if membrane mechanism
                if not mech.endswith('_ion'):  # exclude ions
                    mechDic[mech] = {}  # create dic for mechanism properties
                    varNames = [varName.replace('_'+mech, '') for varName in varList['mechs'][mech]]
                    varVals = []
                    for varName in varNames:
                        if varName not in ignoreVars:
                            try:
                                varVals = [seg.__getattribute__(mech).__getattribute__(varName) for seg in sec]
                                if len(set(varVals)) == 1:
                                    varVals = varVals[0] 
                                mechDic[mech][varName] = varVals
                            except: 
                                pass
                                #print 'Could not read variable %s from mechanism %s'%(varName,mech)

                # store ions
                elif mech.endswith('_ion'):
                    ionName = mech.split('_ion')[0]
                    varNames = [varName.replace('_'+mech, '').replace(ionName,'') for varName in varList['mechs'][mech]]
                    varNames.append('e')
                    varVals = []
                    ionDic[ionName] = {}  # create dic for mechanism properties
                    for varName in varNames:
                        varNameSplit = varName
                        if varName not in ignoreVars:
                            try:
                                varVals = [seg.__getattribute__(varNameSplit+ionName) for seg in sec]
                                if len(set(varVals)) == 1:
                                    varVals = varVals[0] 
                                ionDic[ionName][varNameSplit] = varVals
                            except: 
                                pass
                                #print 'Could not read variable %s from mechanism %s'%(varName,mech)                    


        secDic[secName]['mechs'] = mechDic
        if len(ionDic)>0: 
            secDic[secName]['ions'] = ionDic

        # add synapses and point neurons
        # for now read fixed params, but need to find way to read only synapse params
        pointps = {}
        for seg in sec:
            for ipoint,point in enumerate(seg.point_processes()):
                pointpMod = point.hname().split('[')[0]
                varNames = varList['pointps'][pointpMod]
                if any([s in pointpMod.lower() for s in ['syn', 'ampa', 'gaba', 'nmda', 'glu']]):
                #if 'synMech' in pptype.lower(): # if syn in name of point process then assume synapse
                    synMech = {}
                    synMech['label'] = pointpMod + '_' + str(len(synMechs))
                    synMech['mod'] = pointpMod
                    #synMech['loc'] = seg.x
                    for varName in varNames:
                        try:
                            synMech[varName] = point.__getattribute__(varName)
                        except:
                            print 'Could not read variable %s from synapse %s'%(varName,synMech['label'])

                    if not [_equal_dicts(synMech, synMech2, ignore_keys=['label']) for synMech2 in synMechs]:
                        synMechs.append(synMech)
                
                else: # assume its a non-synapse point process
                    pointpName = pointpMod + '_'+ str(len(pointps))
                    pointps[pointpName] = {}
                    pointps[pointpName]['mod'] = pointpMod
                    pointps[pointpName]['loc'] = seg.x
                    for varName in varNames:
                        try:
                            pointps[pointpName][varName] = point.__getattribute__(varName)
                            # special condition for Izhi model, to set vinit=vr
                            # if varName == 'vr': secDic[secName]['vinit'] = point.__getattribute__(varName) 
                        except:
                            print 'Could not read %s variable from point process %s'%(varName,pointpName)

        if pointps: secDic[secName]['pointps'] = pointps

        # store topology (keep at the end since h.SectionRef messes remaining loop)
        secRef = h.SectionRef(sec=sec)
        if secRef.has_parent():
            secDic[secName]['topol']['parentSec'] = getSecName(secRef.parent().sec, dirCellSecNames)
            secDic[secName]['topol']['parentX'] = h.parent_connection()
            secDic[secName]['topol']['childX'] = h.section_orientation()

        h.pop_section()  # to prevent section stack overflow
        
    # store section lists
    secLists = h.List('SectionList')
    if int(secLists.count()): 
        secListDic = {}
        for i in xrange(int(secLists.count())):  # loop over section lists
            hname = secLists.o(i).hname()
            if hname in dirCellHnames:  # use python variable name
                secListName = dirCellHnames[hname]
            else:
                secListName = hname
            secListDic[secListName] = [getSecName(sec, dirCellSecNames) for sec in secLists.o(i)]
    else:
        secListDic = {}

    # celsius warning
    if hasattr(h, 'celsius'):
        if h.celsius != 6.3:  # if not default value
            print "Warning: h.celsius=%.4g in imported file -- you can set this value in simConfig['hParams']['celsius']"%(h.celsius)

    # clean 
    h.initnrn()
    del(cell) # delete cell
    import gc; gc.collect()

    return secDic, secListDic, synMechs
Exemple #21
0
def getCellParams(cell, varList={}, origGlob={}):
    dirCell = dir(cell)

    if 'all_sec' in dirCell:
        secs = cell.all_sec
    elif 'sec' in dirCell:
        secs = [cell.sec]
    elif 'allsec' in dir(h):
        secs = [sec for sec in h.allsec()]
    elif 'soma' in dirCell:
        secs = [cell.soma]
    else:
        secs = []

    # create dict with hname of each element in dir(cell)
    dirCellHnames = {}
    for dirCellName in [d for d in dirCell if not d.startswith('__')
                        ]:  # avoid attributes starting with '__'
        dirCellObject = getattr(cell, dirCellName)
        if isinstance(dirCellObject, list):
            for i, dirCellObjectItem in enumerate(dirCellObject):
                try:
                    if dirCellObjectItem.hname(
                    ) not in dirCellHnames:  # give preference to dict entries
                        dirCellHnames.update({
                            dirCellObjectItem.hname():
                            dirCellName + '_' + str(i)
                        })
                except:
                    pass
        elif isinstance(dirCellObject, dict):
            for k, v in dirCellObject.items():
                try:
                    dirCellHnames.update({v.hname(): k})
                except:
                    pass
        else:
            try:
                dirCellHnames.update({dirCellObject.hname(): dirCellName})
            except:
                pass

    # create dict with dir(cell) name corresponding to each hname
    dirCellSecNames = {}
    for sec in secs:
        dirCellSecNames.update({
            hname: name
            for hname, name in dirCellHnames.items() if hname == sec.hname()
        })

    secDic = {}
    synMechs = []
    for sec in secs:
        # create new section dict with name of section
        secName = getSecName(sec, dirCellSecNames)

        # if len(secs) == 1: secName = 'soma' # if just one section rename to 'soma' -- REMOVED, doesn't always apply
        secDic[secName] = {
            'geom': {},
            'topol': {},
            'mechs': {}
        }  # create dictionary to store sec info

        # store geometry properties
        standardGeomParams = ['L', 'nseg', 'diam', 'Ra', 'cm']
        secDir = dir(sec)
        for geomParam in standardGeomParams:
            #if geomParam in secDir:
            try:
                secDic[secName]['geom'][geomParam] = sec.__getattribute__(
                    geomParam)
            except:
                pass

        # store 3d geometry
        sec.push()  # access current section so ismembrane() works
        numPoints = int(h.n3d())
        if numPoints:
            points = []
            for ipoint in range(numPoints):
                x = h.x3d(ipoint)
                y = h.y3d(ipoint)
                z = h.z3d(ipoint)
                diam = h.diam3d(ipoint)
                points.append((x, y, z, diam))
            secDic[secName]['geom']['pt3d'] = points

        # store mechanisms
        #varList = mechVarList()  # list of properties for all density mechanisms and point processes
        ignoreMechs = ['dist']  # dist only used during cell creation
        ignoreVars = []  #
        mechDic = {}
        ionDic = {}

        for mech in dir(sec(0.5)):
            if h.ismembrane(
                    mech
            ) and mech not in ignoreMechs:  # check if membrane mechanism
                if not mech.endswith('_ion'):  # exclude ions
                    mechDic[mech] = {}  # create dic for mechanism properties
                    varNames = [
                        varName.replace('_' + mech, '')
                        for varName in varList['mechs'][mech]
                    ]
                    varVals = []
                    for varName in varNames:
                        if varName not in ignoreVars:
                            try:
                                varVals = [
                                    seg.__getattribute__(
                                        mech).__getattribute__(varName)
                                    for seg in sec
                                ]
                                if len(set(varVals)) == 1:
                                    varVals = varVals[0]
                                mechDic[mech][varName] = varVals
                            except:
                                pass
                                #print 'Could not read variable %s from mechanism %s'%(varName,mech)

                # store ions
                elif mech.endswith('_ion'):
                    ionName = mech.split('_ion')[0]
                    varNames = [
                        varName.replace('_' + mech, '').replace(ionName, '')
                        for varName in varList['mechs'][mech]
                    ]
                    varNames.append('e')
                    varVals = []
                    ionDic[ionName] = {}  # create dic for mechanism properties
                    for varName in varNames:
                        varNameSplit = varName
                        if varName not in ignoreVars:
                            try:
                                if varNameSplit in [
                                        'i', 'o'
                                ]:  # var name after ion name (eg. 'nai', 'nao')
                                    varVals = [
                                        seg.__getattribute__(ionName +
                                                             varNameSplit)
                                        for seg in sec
                                    ]
                                else:  # var name before ion name (eg. 'ena')
                                    varVals = [
                                        seg.__getattribute__(varNameSplit +
                                                             ionName)
                                        for seg in sec
                                    ]
                                if len(set(varVals)) == 1:
                                    varVals = varVals[0]
                                ionDic[ionName][varNameSplit] = varVals
                            except:
                                pass
                                #print 'Could not read variable %s from mechanism %s'%(varName,mech)

        secDic[secName]['mechs'] = mechDic
        if len(ionDic) > 0:
            secDic[secName]['ions'] = ionDic

        # add synapses and point neurons
        # for now read fixed params, but need to find way to read only synapse params
        pointps = {}
        for seg in sec:
            for ipoint, point in enumerate(seg.point_processes()):
                pointpMod = point.hname().split('[')[0]
                varNames = varList['pointps'][pointpMod]
                if any([
                        s in pointpMod.lower()
                        for s in ['syn', 'ampa', 'gaba', 'nmda', 'glu']
                ]):
                    #if 'synMech' in pptype.lower(): # if syn in name of point process then assume synapse
                    synMech = {}
                    synMech['label'] = pointpMod + '_' + str(len(synMechs))
                    synMech['mod'] = pointpMod
                    #synMech['loc'] = seg.x
                    for varName in varNames:
                        try:
                            synMech[varName] = point.__getattribute__(varName)
                        except:
                            print(
                                'Could not read variable %s from synapse %s' %
                                (varName, synMech['label']))

                    if not any([
                            _equal_dicts(
                                synMech, synMech2, ignore_keys=['label'])
                            for synMech2 in synMechs
                    ]):
                        synMechs.append(synMech)

                else:  # assume its a non-synapse point process
                    pointpName = pointpMod + '_' + str(len(pointps))
                    pointps[pointpName] = {}
                    pointps[pointpName]['mod'] = pointpMod
                    pointps[pointpName]['loc'] = seg.x
                    for varName in varNames:
                        try:
                            pointps[pointpName][
                                varName] = point.__getattribute__(varName)
                            # special condition for Izhi model, to set vinit=vr
                            # if varName == 'vr': secDic[secName]['vinit'] = point.__getattribute__(varName)
                        except:
                            print(
                                'Could not read %s variable from point process %s'
                                % (varName, pointpName))

        if pointps: secDic[secName]['pointps'] = pointps

        # store topology (keep at the end since h.SectionRef messes remaining loop)
        secRef = h.SectionRef(sec=sec)
        if secRef.has_parent():
            secDic[secName]['topol']['parentSec'] = getSecName(
                secRef.parent().sec, dirCellSecNames)
            secDic[secName]['topol']['parentX'] = h.parent_connection()
            secDic[secName]['topol']['childX'] = h.section_orientation()

        h.pop_section()  # to prevent section stack overflow

    # store section lists
    secLists = h.List('SectionList')
    if int(secLists.count()):
        secListDic = {}
        for i in range(int(secLists.count())):  # loop over section lists
            hname = secLists.o(i).hname()
            if hname in dirCellHnames:  # use python variable name
                secListName = dirCellHnames[hname]
            else:
                secListName = hname
            secListDic[secListName] = [
                getSecName(sec, dirCellSecNames) for sec in secLists.o(i)
            ]
    else:
        secListDic = {}

    # globals
    mechsList = list(varList['mechs'].keys()) if 'mechs' in varList else []
    pointpsList = list(
        varList['pointps'].keys()) if 'pointps' in varList else []
    globs = getGlobals(mechsList + pointpsList, origGlob=origGlob)
    if 'v_init' in globs:  # set v_init for each section (allows for cells with differnet vinits)
        for sec in list(secDic.values()):
            sec['vinit'] = globs['v_init']

    # clean
    cell = None
    for i in range(len(secs)):
        tmp = secs.pop()
        del tmp

    import gc
    gc.collect()

    return secDic, secListDic, synMechs, globs
Exemple #22
0
def importCell(fileName, cellName, cellArgs = {}):
	''' 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)
		cell = getattr(h, cellName)(**cellArgs)  # arguments correspond to zloc, type and id -- remove in future (not used internally)
		secList = list(cell.allsec())
		dirCell = dir(cell)
	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
		cell = getattr(modulePointer, cellName)(**cellArgs)  # create cell and pass type as argument
		dirCell = dir(cell)

		if 'all_sec' in dirCell:
			secList = cell.all_sec
		elif 'sec' in dirCell:
			secList = [cell.sec]
		elif 'allsec' in dir(h):
			secList = [sec for sec in h.allsec()]
		elif 'soma' in dirCell:
			secList = [cell.soma]
		else:
			secList = []
		sys.path.remove(filePath)
	else:
		print "File name should be either .hoc or .py file"
		return

	# create dict with hname of each element in dir(cell)
	dirCellHnames = {}  
	for dirCellName in dirCell:
		try:
			dirCellHnames.update({cell.__dict__[dirCellName].hname(): dirCellName})
		except:
			pass
	# create dict with dir(cell) name corresponding to each hname 
	dirCellSecNames = {} 
	for sec in secList:
		dirCellSecNames.update({hname: name for hname,name in dirCellHnames.iteritems() if hname == sec.hname()})

	secDic = {}
	for sec in secList: 
		# create new section dict with name of section
		secName = getSecName(sec, dirCellSecNames)

		if len(secList) == 1:
			secName = 'soma' # if just one section rename to 'soma'
		secDic[secName] = {'geom': {}, 'topol': {}, 'mechs': {}, 'syns': {}}  # create dictionary to store sec info

		# store geometry properties
		standardGeomParams = ['L', 'nseg', 'diam', 'Ra', 'cm']
		secDir = dir(sec)
		for geomParam in standardGeomParams:
			#if geomParam in secDir:
			try:
				secDic[secName]['geom'][geomParam] = sec.__getattribute__(geomParam)
			except:
				pass

		# store 3d geometry
		numPoints = int(h.n3d())
		if numPoints: 
			points = []
			for ipoint in range(numPoints):
				x = h.x3d(ipoint)
				y = h.y3d(ipoint)
				z = h.z3d(ipoint)
				diam = h.diam3d(ipoint)
				points.append((x, y, z, diam))
			secDic[secName]['geom']['pt3d'] = points

		# store mechanisms
		varList = mechVarList()  # list of properties for all density mechanisms and point processes
		ignoreMechs = ['dist']  # dist only used during cell creation 
		mechDic = {}
		for mech in dir(sec(0.5)):  
			if h.ismembrane(mech) and mech not in ignoreMechs:  # check if membrane mechanism
				mechDic[mech] = {}  # create dic for mechanism properties
				varNames = [varName.replace('_'+mech, '') for varName in varList['mechs'][mech]]
				varVals = []
				for varName in varNames:
					try:
						varVals = [seg.__getattribute__(mech).__getattribute__(varName) for seg in sec]
						if len(set(varVals)) == 1:
							varVals = varVals[0] 
						mechDic[mech][varName] = varVals
					except: 
						pass
						#print 'Could not read variable %s from mechanism %s'%(varName,mech)

		secDic[secName]['mechs'] = mechDic

		# add synapses and point neurons
		# for now read fixed params, but need to find way to read only synapse params
		syns = {}
		pointps = {}
		for seg in sec:
			for ipoint,point in enumerate(seg.point_processes()):
				pptype = point.hname().split('[')[0]
				varNames = varList['pointps'][pptype]
				if any([s in pptype.lower() for s in ['syn', 'ampa', 'gaba', 'nmda', 'glu']]):
				#if 'syn' in pptype.lower(): # if syn in name of point process then assume synapse
					synName = pptype + '_' + str(len(syns))
					syns[synName] = {}
					syns[synName]['_type'] = pptype
					syns[synName]['_loc'] = seg.x
					for varName in varNames:
						try:
							syns[synName][varName] = point.__getattribute__(varName)
						except:
							print 'Could not read variable %s from synapse %s'%(varName,synName)
				
				else: # assume its a non-synapse point process
					pointpName = pptype + '_'+ str(len(pointps))
					pointps[pointpName] = {}
					pointps[pointpName]['_type'] = pptype
					pointps[pointpName]['_loc'] = seg.x
					for varName in varNames:
						try:
							pointps[pointpName][varName] = point.__getattribute__(varName)
							# special condition for Izhi model, to set vinit=vr
							# if varName == 'vr': secDic[secName]['vinit'] = point.__getattribute__(varName) 
						except:
							print 'Could not read %s variable from point process %s'%(varName,synName)

		if syns: secDic[secName]['syns'] = syns
		if pointps: secDic[secName]['pointps'] = pointps

		# store topology (keep at the end since h.SectionRef messes remaining loop)
		secRef = h.SectionRef(sec=sec)
		if secRef.has_parent():
			secDic[secName]['topol']['parentSec'] = getSecName(secRef.parent().sec, dirCellSecNames)
			secDic[secName]['topol']['parentX'] = h.parent_connection()
			secDic[secName]['topol']['childX'] = h.section_orientation()

	del(cell) # delete cell
	import gc; gc.collect()

	return secDic
Exemple #23
0
def getCellParams(cell):
    dirCell = dir(cell)

    if 'all_sec' in dirCell:
        secs = cell.all_sec
    elif 'sec' in dirCell:
        secs = [cell.sec]
    elif 'allsec' in dir(h):
        secs = [sec for sec in h.allsec()]
    elif 'soma' in dirCell:
        secs = [cell.soma]
    else:
        secs = []

    # create dict with hname of each element in dir(cell)
    dirCellHnames = {}
    for dirCellName in dirCell:
        try:
            dirCellHnames.update(
                {getattr(cell, dirCellName).hname(): dirCellName})
        except:
            pass
    # create dict with dir(cell) name corresponding to each hname
    dirCellSecNames = {}
    for sec in secs:
        dirCellSecNames.update({
            hname: name
            for hname, name in dirCellHnames.iteritems()
            if hname == sec.hname()
        })

    secDic = {}
    synMechs = []
    for sec in secs:
        # create new section dict with name of section
        secName = getSecName(sec, dirCellSecNames)

        if len(secs) == 1:
            secName = 'soma'  # if just one section rename to 'soma'
        secDic[secName] = {
            'geom': {},
            'topol': {},
            'mechs': {}
        }  # create dictionary to store sec info

        # store geometry properties
        standardGeomParams = ['L', 'nseg', 'diam', 'Ra', 'cm']
        secDir = dir(sec)
        for geomParam in standardGeomParams:
            #if geomParam in secDir:
            try:
                secDic[secName]['geom'][geomParam] = sec.__getattribute__(
                    geomParam)
            except:
                pass

        # store 3d geometry
        sec.push()  # access current section so ismembrane() works
        numPoints = int(h.n3d())
        if numPoints:
            points = []
            for ipoint in range(numPoints):
                x = h.x3d(ipoint)
                y = h.y3d(ipoint)
                z = h.z3d(ipoint)
                diam = h.diam3d(ipoint)
                points.append((x, y, z, diam))
            secDic[secName]['geom']['pt3d'] = points

        # store mechanisms
        varList = mechVarList(
        )  # list of properties for all density mechanisms and point processes
        ignoreMechs = ['dist']  # dist only used during cell creation
        ignoreVars = []  #
        mechDic = {}
        ionDic = {}

        for mech in dir(sec(0.5)):
            if h.ismembrane(
                    mech
            ) and mech not in ignoreMechs:  # check if membrane mechanism
                if not mech.endswith('_ion'):  # exclude ions
                    mechDic[mech] = {}  # create dic for mechanism properties
                    varNames = [
                        varName.replace('_' + mech, '')
                        for varName in varList['mechs'][mech]
                    ]
                    varVals = []
                    for varName in varNames:
                        if varName not in ignoreVars:
                            try:
                                varVals = [
                                    seg.__getattribute__(
                                        mech).__getattribute__(varName)
                                    for seg in sec
                                ]
                                if len(set(varVals)) == 1:
                                    varVals = varVals[0]
                                mechDic[mech][varName] = varVals
                            except:
                                pass
                                #print 'Could not read variable %s from mechanism %s'%(varName,mech)

                # store ions
                elif mech.endswith('_ion'):
                    ionName = mech.split('_ion')[0]
                    varNames = [
                        varName.replace('_' + mech, '').replace(ionName, '')
                        for varName in varList['mechs'][mech]
                    ]
                    varNames.append('e')
                    varVals = []
                    ionDic[ionName] = {}  # create dic for mechanism properties
                    for varName in varNames:
                        varNameSplit = varName
                        if varName not in ignoreVars:
                            try:
                                varVals = [
                                    seg.__getattribute__(varNameSplit +
                                                         ionName)
                                    for seg in sec
                                ]
                                if len(set(varVals)) == 1:
                                    varVals = varVals[0]
                                ionDic[ionName][varNameSplit] = varVals
                            except:
                                pass
                                #print 'Could not read variable %s from mechanism %s'%(varName,mech)

        secDic[secName]['mechs'] = mechDic
        if len(ionDic) > 0:
            secDic[secName]['ions'] = ionDic

        # add synapses and point neurons
        # for now read fixed params, but need to find way to read only synapse params
        pointps = {}
        for seg in sec:
            for ipoint, point in enumerate(seg.point_processes()):
                pointpMod = point.hname().split('[')[0]
                varNames = varList['pointps'][pointpMod]
                if any([
                        s in pointpMod.lower()
                        for s in ['syn', 'ampa', 'gaba', 'nmda', 'glu']
                ]):
                    #if 'synMech' in pptype.lower(): # if syn in name of point process then assume synapse
                    synMech = {}
                    synMech['label'] = pointpMod + '_' + str(len(synMechs))
                    synMech['mod'] = pointpMod
                    #synMech['loc'] = seg.x
                    for varName in varNames:
                        try:
                            synMech[varName] = point.__getattribute__(varName)
                        except:
                            print 'Could not read variable %s from synapse %s' % (
                                varName, synMech['label'])

                    if not [
                            _equal_dicts(
                                synMech, synMech2, ignore_keys=['label'])
                            for synMech2 in synMechs
                    ]:
                        synMechs.append(synMech)

                else:  # assume its a non-synapse point process
                    pointpName = pointpMod + '_' + str(len(pointps))
                    pointps[pointpName] = {}
                    pointps[pointpName]['mod'] = pointpMod
                    pointps[pointpName]['loc'] = seg.x
                    for varName in varNames:
                        try:
                            pointps[pointpName][
                                varName] = point.__getattribute__(varName)
                            # special condition for Izhi model, to set vinit=vr
                            # if varName == 'vr': secDic[secName]['vinit'] = point.__getattribute__(varName)
                        except:
                            print 'Could not read %s variable from point process %s' % (
                                varName, pointpName)

        if pointps: secDic[secName]['pointps'] = pointps

        # store topology (keep at the end since h.SectionRef messes remaining loop)
        secRef = h.SectionRef(sec=sec)
        if secRef.has_parent():
            secDic[secName]['topol']['parentSec'] = getSecName(
                secRef.parent().sec, dirCellSecNames)
            secDic[secName]['topol']['parentX'] = h.parent_connection()
            secDic[secName]['topol']['childX'] = h.section_orientation()

        h.pop_section()  # to prevent section stack overflow

    # store section lists
    secLists = h.List('SectionList')
    if int(secLists.count()):
        secListDic = {}
        for i in xrange(int(secLists.count())):  # loop over section lists
            hname = secLists.o(i).hname()
            if hname in dirCellHnames:  # use python variable name
                secListName = dirCellHnames[hname]
            else:
                secListName = hname
            secListDic[secListName] = [
                getSecName(sec, dirCellSecNames) for sec in secLists.o(i)
            ]
    else:
        secListDic = {}

    # celsius warning
    if hasattr(h, 'celsius'):
        if h.celsius != 6.3:  # if not default value
            print "Warning: h.celsius=%.4g in imported file -- you can set this value in simConfig['hParams']['celsius']" % (
                h.celsius)

    # clean
    h.initnrn()
    del (cell)  # delete cell
    import gc
    gc.collect()

    return secDic, secListDic, synMechs
def init_cell(cell_path, spines=True):

    """
    cell: path to cell definiton
    """

    h("forall delete_section()")

    # ---- conditions ----

    h.celsius = temp

    # ---- soma & dendrite ----

    h.xopen(cell_path)

    soma = h.soma

    dendritic = []

    # segment lengths should be not longer than 50um
    # contains soma!
    for sec in h.allsec():
        diam = sec.diam
        n = sec.L / 50.0 + 1
        sec.nseg = int(n)  # needed in Python, automatic in hoc
        if h.n3d() == 0:
            sec.diam = diam
        dendritic.append(sec)

    dendritic_only = []
    for sec in dendritic:
        if sec != h.soma:
            dendritic_only.append(sec)

    assert len(dendritic) - 1 == len(dendritic_only)

    # ---- spines ---

    if spines:

        for sec in dendritic_only:
            a = 0.0
            for seg in sec.allseg():
                a += seg.area()
            F = (sec.L * spine_area * spine_dens + a) / a
            sec.L = sec.L * F ** (2 / 3.0)
            for seg in sec.allseg():
                seg.diam = seg.diam * F ** (1 / 3.0)

    # ---- axon ----

    # initial segment between hillock + myelin
    iseg = h.Section(name="iseg")
    iseg.L = iseg_L
    iseg.nseg = iseg_nseg
    soma_compl_area = 0
    for seg in soma:
        soma_compl_area += seg.area()
    print soma_compl_area
    iseg.diam = (soma_compl_area / (4.0 * np.pi)) ** (0.5) / 10.0

    # axon hillock
    hill = h.Section(name="hill")
    hill.L = hill_L
    hill.nseg = hill_nseg
    taper_diam(hill, 4 * iseg.diam, iseg.diam)

    myelin = [h.Section(name="myelin %d" % i) for i in range(n_axon_seg)]
    for myelin_sec in myelin:
        myelin_sec.nseg = myelin_nseg  # each of the 5 sections has 5 segments
        myelin_sec.L = myelin_L
        myelin_sec.diam = iseg.diam

    node = [h.Section(name="node %d" % i) for i in range(n_axon_seg)]
    for node_sec in node:
        node_sec.nseg = node_nseg
        node_sec.L = node_L
        node_sec.diam = iseg.diam * 0.75

    # syntax: childsec.connect(parentsec, parentx, childx)
    hill.connect(soma, 0.5, 0)
    iseg.connect(hill, 1, 0)
    myelin[0].connect(iseg, 1, 0)
    node[0].connect(myelin[0], 1, 0)

    for i in range(n_axon_seg - 1):
        myelin[i + 1].connect(node[i], 1, 0)
        node[i + 1].connect(myelin[i + 1], 1, 0)

    # ---- mechanisms ----

    for sec in h.allsec():
        sec.insert("pas")
        sec.Ra = ra
        sec.cm = c_m
        sec.g_pas = 1.0 / rm
        sec.e_pas = v_init

        sec.insert("na")

    # dendrite
    for sec in dendritic_only:
        sec.gbar_na = gna_dend
        sec.insert("km")
        sec.gbar_km = gkm
        sec.insert("kca")
        sec.gbar_kca = gkca
        sec.insert("ca")
        sec.gbar_ca = gca
        sec.insert("cad")

    # na+ channels
    soma.gbar_na = gna_soma

    soma.insert("kv")
    soma.gbar_kv = gkv_soma

    soma.insert("km")
    soma.gbar_km = gkm_soma
    soma.insert("kca")
    soma.gbar_kca = gkca_soma
    soma.insert("ca")
    soma.gbar_ca = gca_soma
    soma.insert("cad")

    for myelin_sec in myelin:
        myelin_sec.cm = cm_myelin
        myelin_sec.gbar_na = gna_dend

    hill.gbar_na = gna_node
    iseg.gbar_na = gna_node

    for node_sec in node:
        node_sec.g_pas = g_pas_node
        node_sec.gbar_na = gna_node

    iseg.insert("kv")
    iseg.gbar_kv = gkv_axon

    hill.insert("kv")
    hill.gbar_kv = gkv_axon

    for sec in h.allsec():
        if h.ismembrane("k_ion"):
            sec.ek = Ek
        if h.ismembrane("na_ion"):
            sec.ena = Ena
            h.vshift_na = -5
        if h.ismembrane("ca_ion"):
            sec.eca = 140
            h.ion_style("ca_ion", 0, 1, 0, 0, 0)
            h.vshift_ca = 0

    axon = [iseg, hill, myelin, node]

    return soma, dendritic_only, axon
Exemple #25
0
    def setrx(stim_elec, rho=500, bipolar=False):
        """
        This function assumes a homogeneous outer medium for stimulation and sets the transmission resistance rx
        accordingly. While for the CNS this might be ok, it certainly isn't here in the PNS, so this function should
        not be used and could as well be removed.

        Args:
            stim_elec:
            axon_pos:
            rho:
            bipolar:

        Returns:

        """

        numPoints = stim_elec.shape[0]

        r = np.zeros(len(stim_elec))

        segCounter = 0
        # now expects xyc coords as arguments
        for sec in h.allsec():

            if h.ismembrane('xtra', sec=sec):

                for segInd, seg in enumerate(sec):

                    for j in range(numPoints):

                        [xe, ye, ze] = stim_elec[j, :]

                        # avoid nodes at 0 and 1 ends, so as not to override values at internal nodes
                        r[j] = math.sqrt(
                            math.pow(seg.x_xtra - xe, 2) +
                            math.pow(seg.y_xtra - ye, 2) +
                            math.pow(seg.z_xtra - ze, 2))

                        # 0.01 converts rho's cm to um and ohm to megohm
                        # if electrode is exactly at a node, r will be 0
                        # this would be meaningless since the location would be inside the cell
                        # so force r to be at least as big as local radius

                        if r[j] == 0:
                            r[j] = seg.diam / 2.0

                    sum_r = 0
                    pointIndex = 0
                    while pointIndex < numPoints:
                        if bipolar:
                            sign = (-1)**pointIndex
                        else:
                            sign = 1
                        sum_r += sign / r[pointIndex]
                        pointIndex += 1

                    # seg.xtra.rx = (sec.Ra / 4.0 / math.pi) * sum_r * 0.01
                    seg.xtra.rx = (rho / 4.0 / math.pi) * sum_r * 0.01

                    # print "seg no %i, rx %10.8f" % (segCounter, (rho / 4.0 / math.pi) * sum_r * 0.01)
                    segCounter += 1
Exemple #26
0
 def apply_nimodipine(self):
     """Simulates the application of nimodipine as a reduction of CaL channel conductance."""
     for sec in self.CA1.all:
         if h.ismembrane('cal', sec=sec):
             sec.gcalbar_cal = 0
Exemple #27
0
def mksyns(gid,
           cell,
           syn_ids,
           syn_types,
           swc_types,
           syn_locs,
           syn_sections,
           syn_kinetic_params,
           add_synapse=add_shared_synapse,
           spines=False):

    syns_dict_dend = defaultdict(lambda: defaultdict(lambda: {}))
    syns_dict_ais = defaultdict(lambda: defaultdict(lambda: {}))
    syns_dict_soma = defaultdict(lambda: defaultdict(lambda: {}))
    py_sections = [sec for sec in cell.sections]

    syn_obj_dict = {}

    for i in xrange(0, syn_ids.size):

        syn_id = syn_ids[i]
        if not (syn_id < syn_types.size):
            print 'mksyns syn_ids for gid %i: ' % gid, syn_ids
            raise ValueError('mksyns: cell %i received invalid syn_id %d' %
                             (gid, syn_id))

        syn_type = syn_types[syn_id]
        swc_type = swc_types[syn_id]
        syn_loc = syn_locs[syn_id]
        syn_section = syn_sections[syn_id]

        sref = None
        sec = py_sections[syn_section]
        if swc_type == swc_type_apical:
            syns_dict = syns_dict_dend
            if syn_type == syn_type_excitatory:
                if spines and h.ismembrane('spines', sec=sec):
                    sec(syn_loc).count_spines += 1
        elif swc_type == swc_type_basal:
            syns_dict = syns_dict_dend
            if syn_type == syn_type_excitatory:
                if spines and h.ismembrane('spines', sec=sec):
                    sec(syn_loc).count_spines += 1
        elif swc_type == swc_type_ais:
            syns_dict = syns_dict_ais
        elif swc_type == swc_type_soma:
            syns_dict = syns_dict_soma
        else:
            raise RuntimeError("Unsupported synapse SWC type %d" % swc_type)
        syn_mech_dict = {}
        for (syn_mech, params) in syn_kinetic_params.iteritems():
            syn = add_synapse(syn_mech, sec(syn_loc), syns_dict)
            syn.tau1 = params['t_rise']
            syn.tau2 = params['t_decay']
            syn.e = params['e_rev']
            cell.syns.append(syn)
            cell.syntypes.o(syn_type).append(syn)
            syn_mech_dict[syn_mech] = syn
        syn_obj_dict[syn_id] = syn_mech_dict

    if spines:
        cell.correct_for_spines()

    return syn_obj_dict
Exemple #28
0
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
        secs = list(cell.allsec())
        dirCell = dir(cell)
    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
        
        dirCell = dir(cell)

        if 'all_sec' in dirCell:
            secs = cell.all_sec
        elif 'sec' in dirCell:
            secs = [cell.sec]
        elif 'allsec' in dir(h):
            secs = [sec for sec in h.allsec()]
        elif 'soma' in dirCell:
            secs = [cell.soma]
        else:
            secs = []
        sys.path.remove(filePath)
    else:
        print "File name should be either .hoc or .py file"
        return

    # create dict with hname of each element in dir(cell)
    dirCellHnames = {}  
    for dirCellName in dirCell:
        try:
            dirCellHnames.update({getattr(cell, dirCellName).hname(): dirCellName})
        except:
            pass
    # create dict with dir(cell) name corresponding to each hname 
    dirCellSecNames = {} 
    for sec in secs:
        dirCellSecNames.update({hname: name for hname,name in dirCellHnames.iteritems() if hname == sec.hname()})

    secDic = {}
    synMechs = []
    for sec in secs: 
        # create new section dict with name of section
        secName = getSecName(sec, dirCellSecNames)

        if len(secs) == 1:
            secName = 'soma' # if just one section rename to 'soma'
        secDic[secName] = {'geom': {}, 'topol': {}, 'mechs': {}}  # create dictionary to store sec info

        # store geometry properties
        standardGeomParams = ['L', 'nseg', 'diam', 'Ra', 'cm']
        secDir = dir(sec)
        for geomParam in standardGeomParams:
            #if geomParam in secDir:
            try:
                secDic[secName]['geom'][geomParam] = sec.__getattribute__(geomParam)
            except:
                pass

        # store 3d geometry
        numPoints = int(h.n3d())
        if numPoints: 
            points = []
            for ipoint in range(numPoints):
                x = h.x3d(ipoint)
                y = h.y3d(ipoint)
                z = h.z3d(ipoint)
                diam = h.diam3d(ipoint)
                points.append((x, y, z, diam))
            secDic[secName]['geom']['pt3d'] = points

        # store mechanisms
        varList = mechVarList()  # list of properties for all density mechanisms and point processes
        ignoreMechs = ['dist']  # dist only used during cell creation 
        mechDic = {}
        sec.push()  # access current section so ismembrane() works
        for mech in dir(sec(0.5)): 
            if h.ismembrane(mech) and mech not in ignoreMechs:  # check if membrane mechanism
                mechDic[mech] = {}  # create dic for mechanism properties
                varNames = [varName.replace('_'+mech, '') for varName in varList['mechs'][mech]]
                varVals = []
                for varName in varNames:
                    try:
                        varVals = [seg.__getattribute__(mech).__getattribute__(varName) for seg in sec]
                        if len(set(varVals)) == 1:
                            varVals = varVals[0] 
                        mechDic[mech][varName] = varVals
                    except: 
                        pass
                        #print 'Could not read variable %s from mechanism %s'%(varName,mech)

        secDic[secName]['mechs'] = mechDic

        # add synapses and point neurons
        # for now read fixed params, but need to find way to read only synapse params
        
        pointps = {}
        for seg in sec:
            for ipoint,point in enumerate(seg.point_processes()):
                pointpMod = point.hname().split('[')[0]
                varNames = varList['pointps'][pointpMod]
                if any([s in pointpMod.lower() for s in ['syn', 'ampa', 'gaba', 'nmda', 'glu']]):
                #if 'synMech' in pptype.lower(): # if syn in name of point process then assume synapse
                    synMech = {}
                    synMech['label'] = pointpMod + '_' + str(len(synMechs))
                    synMech['mod'] = pointpMod
                    #synMech['loc'] = seg.x
                    for varName in varNames:
                        try:
                            synMech[varName] = point.__getattribute__(varName)
                        except:
                            print 'Could not read variable %s from synapse %s'%(varName,synMech['label'])

                    if not [_equal_dicts(synMech, synMech2, ignore_keys=['label']) for synMech2 in synMechs]:
                        synMechs.append(synMech)
                
                else: # assume its a non-synapse point process
                    pointpName = pointpMod + '_'+ str(len(pointps))
                    pointps[pointpName] = {}
                    pointps[pointpName]['mod'] = pointpMod
                    pointps[pointpName]['loc'] = seg.x
                    for varName in varNames:
                        try:
                            pointps[pointpName][varName] = point.__getattribute__(varName)
                            # special condition for Izhi model, to set vinit=vr
                            # if varName == 'vr': secDic[secName]['vinit'] = point.__getattribute__(varName) 
                        except:
                            print 'Could not read %s variable from point process %s'%(varName,pointpName)

        if pointps: secDic[secName]['pointps'] = pointps

        # store topology (keep at the end since h.SectionRef messes remaining loop)
        secRef = h.SectionRef(sec=sec)
        if secRef.has_parent():
            secDic[secName]['topol']['parentSec'] = getSecName(secRef.parent().sec, dirCellSecNames)
            secDic[secName]['topol']['parentX'] = h.parent_connection()
            secDic[secName]['topol']['childX'] = h.section_orientation()

        h.pop_section()  # to prevent section stack overflow

    # # store synMechs in input argument
    # if synMechs: 
    #     for synMech in synMechs: synMechParams.append(synMech)
        
    # store section lists
    secLists = h.List('SectionList')
    if int(secLists.count()): 
        secListDic = {}
        for i in xrange(int(secLists.count())):  # loop over section lists
            hname = secLists.o(i).hname()
            if hname in dirCellHnames:  # use python variable name
                secListName = dirCellHnames[hname]
            else:
                secListName = hname
            secListDic[secListName] = [getSecName(sec, dirCellSecNames) for sec in secLists.o(i)]
    else:
        secListDic = {}

    # celsius warning
    if hasattr(h, 'celsius'):
        if h.celsius != 6.3:  # if not default value
            print "Warning: h.celsius=%.4g in imported file %s -- you can set this value in simConfig['hParams']['celsius']"%(h.celsius, fileName)

    # clean 
    h.initnrn()
    del(cell) # delete cell
    import gc; gc.collect()

    return secDic, secListDic, synMechs
Exemple #29
0
def set_params(hobj, params_dict):
    # params_dict = json.load(open(params_file_name, 'r'))
    passive = params_dict['passive'][0]
    genome = params_dict['genome']
    conditions = params_dict['conditions'][0]

    section_map = {}
    for sec in hobj.all:
        section_name = sec.name().split(".")[1][:4]
        if section_name in section_map:
            section_map[section_name].append(sec)
        else:
            section_map[section_name] = [sec]

    for sec in hobj.all:
        sec.insert('pas')
        # sec.insert('extracellular')

    if 'e_pas' in passive:
        e_pas_val = passive['e_pas']
        for sec in hobj.all:
            for seg in sec:
                seg.pas.e = e_pas_val

    if 'ra' in passive:
        ra_val = passive['ra']
        for sec in hobj.all:
            sec.Ra = ra_val

    if 'cm' in passive:
        for cm_dict in passive['cm']:
            cm = cm_dict['cm']
            for sec in section_map.get(cm_dict['section'], []):
                sec.cm = cm

    for genome_dict in genome:
        g_section = genome_dict['section']
        if genome_dict['section'] == 'glob':
            print(
                "WARNING: There is a section called glob, probably old json file"
            )
            continue

        g_value = float(genome_dict['value'])
        g_name = genome_dict['name']
        g_mechanism = genome_dict.get("mechanism", "")
        for sec in section_map.get(g_section, []):
            if g_mechanism != "":
                sec.insert(g_mechanism)
            setattr(sec, g_name, g_value)

    for erev in conditions['erev']:
        erev_section = erev['section']
        erev_ena = erev['ena']
        erev_ek = erev['ek']
        if erev_section in section_map:
            for sec in section_map.get(erev_section, []):
                if h.ismembrane('k_ion', sec=sec) == 1:
                    setattr(sec, 'ek', erev_ek)
                if h.ismembrane('na_ion', sec=sec) == 1:
                    setattr(sec, 'ena', erev_ena)
        else:
            print(
                "Warning: can't set erev for {}, section array doesn't exist".
                format(erev_section))
Exemple #30
0
from neuron import h
Exemple #31
0
 def apply_TTX(self):
     """Simulates the application of TTX as a reduction of sodium channel conductance."""
     for sec in self.CA1.all:
         if h.ismembrane('nax', sec=sec):
             sec.gbar_nax = sec.gbar_nax / 2
st = h.IClamp(0.5)  #Choose where in the soma to point-stimulate

st.dur = 1000  #Stimulus duration (ms)
st.delay = 100  #Stimulus delay (ms)
st.amp = 1  #Stimulus amplitude (nA)
h.tstop = 1200  #stop the simulation (ms)

##########################################################################################################
# Run the simulation
##########################################################################################################

h.v_init = -65  #Set initializing simulation voltage (mV) at t0
h.finitialize(-65)  #Set initializing voltage for all mechanisms in the section
h.fcurrent()
if h.ismembrane(
        'cal'
):  #start the 'vClamp' by setting e_pas to match v_init (NEURON Book, ch8, p11)
    soma.e_pas = soma.v + (soma.ina + soma.ik + soma.ica) / soma.g_pas
else:
    soma.e_pas = soma.v + (soma.ina + soma.ik) / soma.g_pas

h.run()

###################################################
# PLOTTING
###################################################

plt.figure(figsize=(12, 7))
plt.title(pattern + ' firing pattern (IClamp)', fontweight='bold')
plt.plot(t_vec, v_vec)
plt.ylabel('Membrane voltage (mV)', fontsize=16)