Пример #1
0
def mkmitral(gid):
  nrn = getmitral(gid)
  
  m = h.Mitral()
  m.createsec(len(nrn.dend), len(nrn.tuft))
  m.subsets()
  m.topol(0) # need to connect secondary dendrites explicitly

  for i, d in enumerate(nrn.dend):
    
    # <<< check my changed if
    if(d.parent == nrn.soma): # <<< changed name
      m.secden[i].connect(m.soma(.5))
    else:
      m.secden[i].connect(m.secden[d.parent.index](1)) # <<< changed name
  
  m.geometry()
  m.segments() # depends on geometry
  m.geometry() # again to get the hillock stylized shape

  fillall(nrn, m)
  
  m.segments() # again to get the proper number of segments for tuft and secden
  m.soma.push()
  m.x = h.x3d(0)
  m.y = h.y3d(0)
  m.z = h.z3d(0)
  h.pop_section()
  m.memb()
  return m
Пример #2
0
 def _addSynapses(self):
     """
     Adds all synapses to the neuron. Being this model composed by just a single
     compartment, all synapses are added to the soma.
     """
     if self.verbose:
         print('>>> Adding synapses to the model.')
     # TODO: take synapse parameters from:
     # Jaeger, D., De Schutter, E., & Bower, J. M. (1997).
     # The role of synaptic and voltage-gated currents in the control of Purkinje cell
     # spiking: a modeling study.
     # The Journal of Neuroscience, 17(1), 91-106.
     self.soma.push()
     for i in range(self.nSynapses):
         if self.synapseProperties['name'].lower() == 'ampa':
             syn = h.AMPA_S(self.soma(0.5))
             h.Erev_AMPA_S = self.synapseProperties['Erev']
         elif self.synapseProperties['name'].lower() == 'biexp':
             syn = h.Exp2Syn(self.soma(0.5))
             syn.tau1 = self.synapseProperties['tauRise']
             syn.tau2 = self.synapseProperties['tauDecay']
             syn.e = self.synapseProperties['Erev']
         else:
             raise Exception('Unknown synaptic model [%s]' % synapseProps['name'])
             return
         self.synapses.append(syn)
     h.pop_section()
Пример #3
0
    def draw_mayavi(self, x, y, z, d, edges):
        "Draw the surface the first time"

        # rendering disabled
        self.mayavi.visualization.scene.disable_render = True

        points = mlab.pipeline.scalar_scatter(x, y, z, d / 2.0)
        dataset = points.mlab_source.dataset
        dataset.point_data.get_array(0).name = "diameter"
        dataset.lines = np.vstack(edges)
        dataset.point_data.update()
        self.dataset = dataset

        # The tube
        src = mlab.pipeline.set_active_attribute(points, point_scalars="diameter")
        stripper = mlab.pipeline.stripper(src)
        tube = mlab.pipeline.tube(stripper, tube_sides=6, tube_radius=1)
        tube.filter.capping = True
        #        tube.filter.use_default_normal = False
        tube.filter.vary_radius = "vary_radius_by_absolute_scalar"
        self.tube = tube

        # Setting the voltage
        # Making room for the voltage
        v = []
        for sec in h.allsec():
            sec.push()
            v.extend(np.repeat(0.0, h.n3d()))
            h.pop_section()

        v = np.array(v)
        self.draw_surface(v, "v")

        # ReEnable the rendering
        self.mayavi.visualization.scene.disable_render = False
Пример #4
0
 def build_sec_scalar(self, sec, var_value):
     
     sec.push()
     npoints = self.n3dpoints_per_sec[sec.name()]
     sec_scalar = np.repeat(var_value, npoints)
     h.pop_section()
     return sec_scalar
Пример #5
0
    def retrieve_coordinate(self, sec):
        """Retrieve the coordinates of the section avoiding duplicates"""
        
        sec.push()
        x, y, z, d = [],[],[],[]

        tot_points = 0
        connect_next = False
        for i in range(int(h.n3d())):
            present = False
            x_i = h.x3d(i)
            y_i = h.y3d(i)
            z_i = h.z3d(i)
            d_i = h.diam3d(i)
            # Avoiding duplicates in the sec
            if x_i in x:
                ind = len(x) - 1 - x[::-1].index(x_i) # Getting the index of last value
                if y_i == y[ind]:
                    if z_i == z[ind]:
                        present = True
                    
            if not present:
                k =(x_i, y_i, z_i)
                x.append(x_i)
                y.append(y_i)
                z.append(z_i)
                d.append(d_i)                
        h.pop_section()
        #adding num 3d points per section
        self.n3dpoints_per_sec[sec.name()] = len(d)
        return (np.array(x),np.array(y),np.array(z),np.array(d))
Пример #6
0
def retrieve_coordinate(sec):
    sec.push()
    x, y, z, d = [],[],[],[]
    area = 0
    tot_points = 0
    connect_next = False
    for i in range(int(h.n3d())):
        present = False
	x_i = h.x3d(i)
	y_i = h.y3d(i)
	z_i = h.z3d(i)
	d_i = h.diam3d(i)
	a_i = h.area(0.5)
	if x_i in x:
            ind = len(x) - 1 - x[::-1].index(x_i) # Getting the index of last value
	    if y_i == y[ind]:
                if z_i == z[ind]:
                    present = True
                    
	if not present:
            k =(x_i, y_i, z_i)
	    x.append(x_i)
	    y.append(y_i)
	    z.append(z_i)
	    d.append(d_i)                
	    area += np.sum(a_i)
    h.pop_section()
        #adding num 3d points per section
    n3dpoints[sec.name()] = [np.array(x),np.array(y),np.array(z),np.array(d)]
    return (np.array(x),np.array(y),np.array(z),np.array(d),area)
Пример #7
0
        def append_v(sec, v):
            """ Append data to v """
            sec.push()
            for ii in xrange(1, int(nrn.n3d())):
                v.append(sec.v)
            nrn.pop_section()

            return v
Пример #8
0
def accumulate_density(sec, density, domain):
  sec.push()
  for i in range(int(h.n3d())):
    x,y = (h.x3d(i), h.y3d(i))
    r = (round(x, domain[0]),round(y, domain[1]))
    if not False in r:
      density[r] += 1
  h.pop_section()
def pr(sec):
  sec.push()
  for seg in sec:
    print '%s   x=%g   r=%g   t2.p=%g   p_t2=%g' % (sec.name(), seg.x, seg.t2.r, seg.t2.p, seg.p_t2),
    h.setdata_t2(seg.x)
    print '   f()=%g\n' % (h.f_t2()),
  print('\n')
  h.pop_section()
Пример #10
0
def e_ct_net_connect_delay_dist(net1, net2, threshold, delay_distbtn, weights):
    net1_net2_syn = list()
    for net1_neuron_i, net1_neuron in enumerate(net1):
        net1_neuron.soma.push()
        for net2_neuron_i, net2_neuron in enumerate(net2):
            net1_net2_syn.append(h.NetCon(net1_neuron.soma(0.5)._ref_v, net2_neuron.synE_CT, threshold,
                                          delay_distbtn[net1_neuron_i], weights[net1_neuron_i, net2_neuron_i]))
        h.pop_section()
    return net1_net2_syn
Пример #11
0
 def recurse_compartments(index, branches):
     for ii in xrange(int(h.s[index].nchild())):
         h.s[index].child[ii].push()
         child_index = cas_index()
         #print index,',',child_index
         branches.append([index,child_index])
         h.pop_section()
         branches = recurse_compartments(child_index, branches)
     return branches
Пример #12
0
def f(a, b, c, d):
    l = list()
    print h.cas().name()
    l.append(h.NetCon(a, b, 0, 0, 1))
    soma3.push()
    print h.cas().name()
    l.append(h.NetCon(c, d, 0, 0, 1))
    h.pop_section()
    print h.cas().name()
    return l
Пример #13
0
 def retrieve_coordinates(self, sec):
     xyzds = []
     sec.push()
     for ii in xrange(int(nrn.n3d())):
         xyzds.append([nrn.x3d(ii),
                      nrn.y3d(ii),
                      nrn.z3d(ii),
                      nrn.diam3d(ii)])
     nrn.pop_section()
     return xyzds
Пример #14
0
 def append_children_voltage(parent, v):
     parent.push()
     sref = nrn.SectionRef()
     nrn.pop_section()
     if sref.child:
         for child in sref.child:
             v = append_v(child, v)
             v = append_children_voltage(parent = child,
                                         v = v)
     return v
Пример #15
0
def connect(v1, syn2, v3, syn4):
    l = list()
    print h.cas().name()
    l.append(h.NetCon(v1, syn2, 0, 0, 0.5))
    soma3.push()
    print h.cas().name()
    l.append(h.NetCon(v3, syn4, 0, 0, 1))
    h.pop_section()
    print h.cas().name()
    return l
Пример #16
0
    def build_tree(self):
        print "-"*100
        def append_data(sec, xyzdv, parent_id, connections):
            """ Append data to xyzdv """

            if self.var is 'v':
                v = sec.v
            else:
                raise AttributeError('Variable %s not implemented' % self.var)


            sec.push()
            for ii in xrange(1, int(nrn.n3d())):
                x = nrn.x3d(ii)
                y = nrn.y3d(ii)
                z = nrn.z3d(ii)
                d = nrn.diam3d(ii)
                xyzdv.append([x,y,z,d,v])
                child_id = len(xyzdv)-1
                if len(xyzdv)>1:
                    connections.append([child_id, parent_id])
                parent_id = child_id
            nrn.pop_section()

            return xyzdv, connections

        def append_children_data(parent, parent_id, xyzdv, connections):
            parent.push()
            sref = nrn.SectionRef()
            nrn.pop_section()
            if sref.child:
                for child in sref.child:
                    xyzdv, connections = append_data(child, xyzdv, parent_id, connections)
                    xyzdv, connections = append_children_data(parent = child,
                                                              parent_id = len(xyzdv)-1,
                                                              xyzdv = xyzdv,
                                                              connections = connections)
            return xyzdv, connections

        # Find data and connections
        root_section = self.root_section()
        root_section.push()
        xyzdv = [[nrn.x3d(0),
                 nrn.y3d(0),
                 nrn.z3d(0),
                 nrn.diam3d(0),
                 root_section.v]]
        nrn.pop_section()
        xyzdv, connections = append_data(root_section, xyzdv, 0, [])
        xyzdv, connections = append_children_data(root_section,
                                                  len(xyzdv)-1,
                                                  xyzdv,
                                                  connections)
        self.xyzdv = array(xyzdv)
        self.connections = array(connections)
Пример #17
0
 def __get_parent(self, sec, tree):
     """Recursive function used to create the tree list of section"""
     sec.push()
     secRef = h.SectionRef()
     if secRef.has_parent():
         parentSeg = secRef.parent()
         parentSec = parentSeg.sec
         tree.append(parentSec)
         tree = self.__get_parent(parentSec, tree)
     h.pop_section()
     return tree
Пример #18
0
 def basic_shape(self):
     self.soma.push()
     h.pt3dclear()
     h.pt3dadd(0, 0, 0, 1)
     h.pt3dadd(20, 0, 0, 1)
     h.pop_section()
     self.dend.push()
     h.pt3dclear()
     h.pt3dadd(15, 0, 0, 1)
     h.pt3dadd(215, 0, 0, 1)
     h.pop_section()
Пример #19
0
def retreive_coordinates(sec):
    ''' Only works with cell which have an xtra mechanism '''
    # Make sure to run h.setpointers() before running
    from neuron import h
    x=sec.sec(.5).x_xtra
    y=sec.sec(.5).y_xtra
    z=sec.sec(.5).z_xtra
    sec.sec.push()
    diam = h.diam3d(0)
    h.pop_section()
    return [x, y, z, diam]
Пример #20
0
    def set_geom(self, geom):
        """
        Create 3d geometry of the neuron.

        :param geom: List of 4d coordinates [x, y, z, diam].
        :type geom: list
        """
        self.push()  # necessary to access Section in NEURON
        h.pt3dclear()
        for g in geom:
            h.pt3dadd(g[0], g[1], g[2], g[3])
        h.pop_section()  # restore the previously accessed Section
Пример #21
0
 def append_children_data(parent, parent_id, xyzdv, connections):
     parent.push()
     sref = nrn.SectionRef()
     nrn.pop_section()
     if sref.child:
         for child in sref.child:
             xyzdv, connections = append_data(child, xyzdv, parent_id, connections)
             xyzdv, connections = append_children_data(parent = child,
                                                       parent_id = len(xyzdv)-1,
                                                       xyzdv = xyzdv,
                                                       connections = connections)
     return xyzdv, connections
Пример #22
0
def connectWithTMGSynapse(pre, post, E, taus, U, delay=1, weight=0.01):
    pre.sec.push()
    syn = h.tmgsyn(post)
    syn.e = E
    syn.tau_1 = taus['1']
    syn.tau_rec = taus['rec']
    syn.tau_facil = taus['facil']
    syn.U = U
    conn = h.NetCon(pre._ref_v, syn)
    conn.weight[0] = weight
    conn.delay = delay
    conn.threshold = 0
    h.pop_section()
    return syn,conn
Пример #23
0
 def find_middle_coordinates(self) :
     cell_list = []
     self.m_coordinates = []
     for n in range(self.num_neurons) :
         cell = []
         print "Neuron ", n
         for i in range(self.NSize[n]):
             exec "cell.append(h.neuron"+str(n)+"_tree["+str(i)+"])";
             cell[i].push()
             middle = int(h.n3d()/2)# It has to be integer!!
             self.m_coordinates.append((h.x3d(middle),h.y3d(middle),h.z3d(middle)))
             #print "Yo(", i, ") Middle is ", middle, Coordinates[i]
             h.pop_section()
         cell_list.append(cell)
     self.m_coordinates 
Пример #24
0
    def pre_synapse(self,j):
        '''
        search for viable synaptic vesicle sites.
        '''
        #from neuron import h   
        pc=h.ParallelContext()
        shiplist=[]
        h('objref coords') 
        h('coords = new Vector(3)')
        #self.celldict.items()[0]
        if j in self.celldict.keys():
            seglist= iter( (seg, sec, self.celldict[j]) for sec in self.celldict[j].spk_trig_ls for seg in sec )     
            for (seg,sec, cellc) in seglist:
                sec.push()
                get_cox = str('coords.x[0]=x_xtra('
                              + str(seg.x) + ')')
                h(get_cox)                   
                get_coy = str('coords.x[1]=y_xtra('
                              + str(seg.x) + ')')
                h(get_coy)
                get_coz = str('coords.x[2]=z_xtra('
                              + str(seg.x) + ')')
                h(get_coz)
                coordict={} 
                coordict['hostfrom'] = pc.id()
                coordict['coords'] = np.array(h.coords.to_python(),
                                          dtype=np.float64)
                coordict['gid']= int(j)
                coordict['seg']= seg.x                    
                secnames = h.cas().name()#sec.name()  
                coordict['secnames'] = str(secnames)
                shiplist.append(coordict)
                h.pop_section()

        '''                
        total_matrix=np.matrix(( 3,len(shiplist) ))
        total_list=[ (x['coords'][0],x['coords'][1],x['coords'][2]) for x in shiplist ]
        for i,j in enumerate(total_list):
            print type(j)
            #pdb.set_trace()
            total_matrix[i][0]=j[0]
            total_matrix[i][1]=j[1]
            total_matrix[i][2]=j[2]

        print total_array[:]
        '''
        
        return shiplist
Пример #25
0
 def insert_domain(self, sec, domain):
     start = h.startsw()
     modlist = []
     for subcomp in domain.dynamics.subcomponents:
         modlist.append(subcomp.name)
         sec.insert(subcomp.name)
         for prop in subcomp.dynamics.properties:
             ############################################
             # this is not good and old style
             #
             sec.push()
             h(prop.name+'_'+subcomp.name+' = '+str(prop.value))
             h.pop_section()
             # 
             #sec.setter(prop.name+'_'+subcomp.name, prop.value)
             ############################################
     self.setup_time += h.startsw() - start
Пример #26
0
 def set_position(self, x, y, z):
     """
     Set the base location in 3D and move all other
     parts of the cell relative to that location.
     """
     for sec in self.all:
         sec.push()
         #print('secname = %s, h.n3d = %d' % (h.secname(), h.n3d()))
         for i in range(int(h.n3d())):
             h.pt3dchange(i,
                     x - self.x + h.x3d(i),
                     y - self.y + h.y3d(i),
                     z - self.z + h.z3d(i),
                     h.diam3d(i), sec=sec)
         h.pop_section()
     #h.define_shape()
     self.x, self.y, self.z = x, y, z
Пример #27
0
def e_net_connect(net1, net2, threshold, delay, weights):
    """
    Connects two networks with an excitatory synapse
    :param net1: First network list (h.List()) of neurons
    :param net2: Second network list (h.List()) of neurons
    :param threshold: voltage threshold that generates spike in neuron in net1
    :param delay: time between spike in net1 and PSP in net2 (ms)
    :param weights: matrix of connection weights (strength of connection)
    :return:
    """
    net1_net2_syn = list()
    for net1_neuron_i, net1_neuron in enumerate(net1):
        net1_neuron.soma.push()
        for net2_neuron_i, net2_neuron in enumerate(net2):
            net1_net2_syn.append(h.NetCon(net1_neuron.soma(0.5)._ref_v, net2_neuron.synE, threshold, delay,
                                          weights[net1_neuron_i, net2_neuron_i]))
        h.pop_section()
    return net1_net2_syn
Пример #28
0
def retrieve_coordinate(sec):
    sec.push()
    x, y, z = [], [], []
    connect_next = False
    for i in range(int(h.n3d())):
        present = False
        x_i = h.x3d(i)
        y_i = h.y3d(i)
        z_i = h.z3d(i)
        if x_i in x:
            ind = len(x) - 1 - x[::-1].index(x_i)
            if y_i == y[ind]:
                if z_i == z[ind]:
                    present = True
        if not present:
            x.append(x_i)
            y.append(y_i)
            z.append(z_i)
    h.pop_section()
    return (np.array(x),np.array(y),np.array(z))
def _make_section(node,index,sections,**kwargs) :
    compartment = neuron.h.Section(name=str(index)) # NEW NRN SECTION
    # assume three point soma
    if node.get_index() not in [1,2,3] :
        pPos = node.get_parent_node().get_content()['p3d']
        cPos = node.get_content()['p3d']
        compartment.push()
        h.pt3dadd(float(pPos.x),float(pPos.y),float(pPos.z),float(pPos.radius))
        h.pt3dadd(float(cPos.x),float(cPos.y),float(cPos.z),float(cPos.radius))
        # nseg according to NEURON book
        compartment.nseg =int(((compartment.L/(0.1*h.lambda_f(100))+0.9)/2)*2+1)

        # passive properties
        compartment.cm = kwargs['cm'] if 'cm' in kwargs else 0.9
        compartment.Ra = kwargs['ra'] if 'ra' in kwargs else 200
        compartment.insert('pas')
        compartment.e_pas =  kwargs['e_pas'] if 'e_pas' in kwargs else -65
        compartment.g_pas =  kwargs['g_pas'] if 'g_pas' in kwargs else 1.0/25000
        
        h.pop_section()
        compartment.connect(sections.get(node.get_parent_node().get_index()),\
                            1,0)
        return compartment
    else :
        if node.get_index() == 1 :
            # root of SWC tree = soma
            cPos = node.get_content()['p3d']
            compartment.push()
            compartment.diam=rs#cPos.radius
            compartment.L=rs#cPos.radius

            # passive properties
            compartment.cm = kwargs['cm'] if 'cm' in kwargs else 0.9
            compartment.Ra = kwargs['ra'] if 'ra' in kwargs else 200
            compartment.insert('pas')
            compartment.e_pas =  kwargs['e_pas'] if 'e_pas' in kwargs else -65
            compartment.g_pas =  kwargs['g_pas'] if 'g_pas' in kwargs else 1.0/25000
                
            h.pop_section()
            #self._soma = compartment
            return compartment
Пример #30
0
 def find_point_process(self, sec):
     """Find a point_process in a section if any.
     
     Params:
         sec - Section to search
         
     Return:
         point_process or None if not present.
     """
     mt = h.MechanismType(1)
     total_mech = int(mt.count())
     sec.push()
     pp = None
     for i in range(total_mech):
         pp_type = mt.select(i)
         pp = mt.pp_begin()
         if pp is not None:
             break
         
     h.pop_section()
     return pp
Пример #31
0
def proceed(cell,
            v0,
            synList,
            RList,
            vecStimList,
            spikeTrain,
            n,
            trans,
            tend,
            vBack,
            tref,
            vThres,
            oneGo,
            t0,
            tstep,
            loc=np.array([]),
            pos=np.array([]),
            dendVclamp=np.array([]),
            alphaR=True,
            getDendV=False,
            monitorDend=False,
            pas=False,
            plotSlice=False,
            fign='slice',
            cpi=False,
            cpt=-1.0):
    f = open('pylog', 'a')
    h.tstop = tend
    print '    ', t0, ' with ', trans, ' trans ', ' to ', tend, ', tref: ', tref
    print >> f, '    ', t0, ' with ', trans, ' trans ', ' to ', tend, ', tref: ', tref
    print '    ', 'vBack: ', vBack, ' vThres: ', vThres, ' vStart ', v0
    print >> f, '    ', 'vBack: ', vBack, ' vThres: ', vThres, ' vStart: ', v0
    print '    RList:', RList
    print >> f, '    RList:', RList
    print '    spikeTrain:', spikeTrain
    print >> f, '    spikeTrain:', spikeTrain
    print '    oneGo: ', oneGo
    print >> f, '    oneGo: ', oneGo
    print '    loc: ', loc
    print >> f, '    loc: ', loc
    print '    pos: ', pos
    print >> f, '    pos: ', pos
    h.dt = tstep
    v = h.Vector()
    t = h.Vector()
    v.record(cell.soma(0.5)._ref_v)
    t.record(h._ref_t)
    if trans > 0:
        cell.soma.push()
        vHold = h.SEClamp(0.5)
        vHold.dur2 = 0.0
        vHold.dur3 = 0.0
        vHold.rs = 1e-9
        vHold.dur1 = t0 + trans
        vHold.amp1 = v0
        h.pop_section()
        print '    soma clamp'
        vHolds = []
        if not monitorDend:
            j = 0
            for i in xrange(len(loc)):
                if not abs(dendVclamp[i] - 1000) < 1e-10:
                    cell.dend[loc[i]].push()
                    vHolds.append(h.SEClamp(pos[i]))
                    vHolds[j].dur2 = 0.0
                    vHolds[j].dur3 = 0.0
                    if oneGo:
                        vHolds[j].rs = cell.dend[loc[i]].Ra
                    elif dendVclamp[i] > 0:
                        vHolds[j].rs = 1e-9
                        dendVclamp[i] = -dendVclamp[i]
                    vHolds[j].dur1 = t0 + trans
                    vHolds[j].amp1 = dendVclamp[i]
                    j = j + 1
                    h.pop_section()
                    print '    dend[', loc[i], '] clamped'
        else:
            print cell.ndend, '    dendrites clampled to ', v0
            for i in xrange(cell.ndend):
                cell.dend[i].push()
                vHolds.append(h.SEClamp(0.5))
                vHolds[i].dur2 = 0
                vHolds[i].dur3 = 0
                vHolds[i].rs = 1e-9
                vHolds[i].dur1 = t0 + trans
                vHolds[i].amp1 = cell.Vrest + (v0 - cell.Vrest) * 1.0
                h.pop_section()
    dendv = []
    if monitorDend:
        for i in xrange(cell.ndend):
            dendv.append(h.Vector())
            dendv[3 * i].record(cell.dend[i](0.16666)._ref_v)
            dendv.append(h.Vector())
            dendv[3 * i + 1].record(cell.dend[i](0.5)._ref_v)
            dendv.append(h.Vector())
            dendv[3 * i + 2].record(cell.dend[i](0.83333)._ref_v)
    else:
        for i in xrange(n):
            dendv.append(h.Vector())
            dendv[i].record(cell.dend[loc[i]](pos[i])._ref_v)
    for i in xrange(n):
        if len(spikeTrain) > 0:
            vecStimList[i].play(h.Vector(spikeTrain[i] + trans))
            vecStimList[i].dt = h.dt
            if alphaR:
                print '    played ', i, ' s: ', synList[i].g
                print >> f, '    played ', i, ' s: ', synList[i].g
            else:
                print '    played ', i, ' s: ', synList[i].gmax
                print >> f, '    played ', i, ' s: ', synList[i].gmax
            if alphaR:
                synList[i].deltat = h.dt
    print '    ready to run'
    print >> f, '    ready to run'
    fired, tsp = run(cell, v0, vBack, tref, vThres, synList, RList, n, trans,
                     oneGo, t0, alphaR, loc, pos, pas, v, t, dendv, cpi, cpt)
    v1 = v.as_numpy()
    if oneGo or int(round(h.t / h.dt)) > int(round(h.tstop / h.dt)):
        ntotal = int(round((tend - t0) / tstep) + 1)
    else:
        ntotal = int(round((h.t - t0) / tstep) + 1)
    #if __name__ == '__main__':
    t1 = t.as_numpy()
    if v1.size != ntotal:
        print >> f, '    v1 steps ', v1.size, ', ntotal ', ntotal
        print '    v1 steps ', v1.size, ', ntotal ', ntotal
        print >> f, '    remove extra step'
        print '    remove extra step'
        v1 = v1[:-1]
        #if __name__ == '__main__':
        t1 = t1[:-1]
    assert (t1.size == v1.size)
    print >> f, '    is this nan ', v1[-1], v1[0]
    print '    is this nan ', v1[-1], v1[0]
    print >> f, '    v size ', v1.size
    print '    v size ', v1.size
    ntrans = int(round(trans / tstep))
    print >> f, '    trans size ', ntrans
    print '    trans size ', ntrans
    print >> f, '    trans end, v0, v1', v1[ntrans - 1], v1[ntrans], v1[-1]
    print '    trans end, v0, v1', v1[ntrans - 1], v1[ntrans], v1[-1]
    print >> f, '    v w/o trans size ', v1.size - ntrans
    print '    v w/o trans size ', v1.size - ntrans
    if trans > 0:
        vHold = None

    if plotSlice:
        fig = pyplot.figure('slice', figsize=(8, 4))
        ax = fig.add_subplot(1, 1, 1)
        ax.minorticks_on()
        labels = ['dend[' + str(loc[x]) + ']' for x in range(n)]
        #istart = ntrans
        istart = 1
        if not monitorDend:
            #pyplot.plot(t1[ntrans:]-trans,v1[ntrans:],'k')
            ymax = -60
            if not oneGo:
                vline, = ax.plot(t1[istart:] - trans, v1[istart:], 'k')
            else:
                vline, = ax.plot(t1[istart:] - trans, v1[istart:], 'k')
            if np.amax(v1) > ymax:
                ymax = np.amax(v1)
            dline = []
            for i in xrange(n):
                dv = dendv[i].as_numpy()
                dv = dv[:v1.size]
                #pyplot.plot(t1[ntrans:]-trans,dv[ntrans:],':')
                if not oneGo:
                    dl, = ax.plot(t1[istart:] - trans, dv[istart:], ':')
                else:
                    dl, = ax.plot(t1[istart:] - trans, dv[istart:], ':')
                dline.append(dl)
                if np.amax(dv) > ymax:
                    ymax = np.amax(dv)
            ax.set_ylim(-80, np.amin([-40, ymax]))
            #pyplot.ylim(-69,-62)
            pyplot.legend(dline, labels)
            ax.yaxis.set_minor_locator(ticker.AutoMinorLocator())
            ax.xaxis.set_minor_locator(ticker.AutoMinorLocator())
        else:
            nt = ntrans
            dendVec = np.empty((3 * cell.ndend, ntotal), dtype='float')
            for i in xrange(cell.ndend):
                dendVec[3 * i, :] = dendv[3 * i].as_numpy()
                dendVec[3 * i + 1, :] = dendv[3 * i + 1].as_numpy()
                dendVec[3 * i + 2, :] = dendv[3 * i + 2].as_numpy()
            v1 = v.as_numpy()
            t1 = t.as_numpy()
            dendVec = np.reshape(dendVec, (3, 199, ntotal))
            mdend = np.average(dendVec, axis=0)
            print '    mdend ', mdend.shape
            #qdendlow = np.percentile(mdend,10, axis = 0)
            qdendlow = np.amin(mdend, axis=0)
            print '    qdendlow', qdendlow.shape
            #qdendhigh = np.percentile(mdend,90, axis = 0)
            qdendhigh = np.amax(mdend, axis=0)
            print '    qdendhigh', qdendhigh.shape
            dendAverage = np.average(mdend, axis=0)
            print '    dendAverage', dendAverage.shape
            denderrbar = np.vstack((qdendlow, qdendhigh))
            print '    denderrbar', denderrbar.shape
            istart = 0
            iend = t1.size
            #istart = nt
            t2 = t1[istart:iend]
            ax.plot(t2 - istart * tstep, v1[istart:iend])
            dA = dendAverage[istart:iend]
            dE = denderrbar[:, istart:iend]
            select = np.arange(0, t2.size, 10)
            t2 = t2[select] - istart * tstep
            print '    t2', t2.shape
            dA = dA[select]
            print '    dA', dA.shape
            dE = dE[:, select]
            print '    dE', dE.shape
            ax.plot(t2, dA, '--k')
            ax.plot(t2, dE[0, :], ':k')
            ax.plot(t2, dE[1, :], ':k')
            ax.errorbar(t2, dA, np.absolute(np.vstack((dA, dA)) - dE))
            qdendlow = np.percentile(mdend, 5, axis=0)
            qdendhigh = np.percentile(mdend, 95, axis=0)
            denderrbar = np.vstack((qdendlow, qdendhigh))
            dE = denderrbar[:, istart:]
            dE = dE[:, select]
            ax.errorbar(t2 + 0.2,
                        dA,
                        np.absolute(np.vstack((dA, dA)) - dE),
                        ls='None')
            qdendlow = np.percentile(mdend, 25, axis=0)
            qdendhigh = np.percentile(mdend, 75, axis=0)
            denderrbar = np.vstack((qdendlow, qdendhigh))
            dE = denderrbar[:, istart:]
            dE = dE[:, select]
            ax.errorbar(t2 + 0.4,
                        dA,
                        np.absolute(np.vstack((dA, dA)) - dE),
                        ls='None')
            qdendlow = np.percentile(mdend, 45, axis=0)
            qdendhigh = np.percentile(mdend, 55, axis=0)
            denderrbar = np.vstack((qdendlow, qdendhigh))
            dE = denderrbar[:, istart:]
            dE = dE[:, select]
            ax.errorbar(t2 + 0.6,
                        dA,
                        np.absolute(np.vstack((dA, dA)) - dE),
                        ls='None')
            ax.set_ylim(v0 - 0.25, v0 + 0.25)
        pyplot.savefig(fign + '.png',
                       format='png',
                       bbox_inches='tight',
                       dpi=900)
        pyplot.close()
        print fign, '.png saved'

    f.close()
    if getDendV:
        dendVecOut = np.array([])
        for i in xrange(n):
            if oneGo and monitorDend:
                dvtmp = dendv[loc[i]].as_numpy().copy()
            else:
                dvtmp = dendv[i].as_numpy().copy()
            if dvtmp.size != ntotal:
                print '    dendv steps ', dvtmp.size, ', ntotal ', ntotal
                print '    remove extra step'
                dvtmp = dvtmp[:-1]
            dendVecOut = np.concatenate((dendVecOut, dvtmp))
        print 'returning dendV', dendVecOut.size
        return v1.copy(), fired, tsp, ntrans, dendVecOut
    else:
        print 'returning somaV only'
        return v1.copy(), fired, tsp, ntrans
Пример #32
0
    def recordTraces(self):
        from .. import sim

        # set up voltagse recording; recdict will be taken from global context
        for key, params in sim.cfg.recordTraces.items():
            conditionsMet = 1

            if 'conds' in params:
                for (condKey, condVal) in params['conds'].items(
                ):  # check if all conditions are met
                    # choose what to comapare to
                    if condKey in ['gid']:  # CHANGE TO GID
                        compareTo = self.gid
                    else:
                        compareTo = self.tags[condKey]

                    # check if conditions met
                    if isinstance(condVal, list) and isinstance(
                            condVal[0], Number):
                        if compareTo < condVal[0] or compareTo > condVal[1]:
                            conditionsMet = 0
                            break
                    elif isinstance(condVal, list) and isinstance(
                            condVal[0], basestring):
                        if compareTo not in condVal:
                            conditionsMet = 0
                            break
                    elif compareTo != condVal:
                        conditionsMet = 0
                        break
            if conditionsMet:
                try:
                    ptr = None
                    if 'loc' in params and params['sec'] in self.secs:
                        if 'mech' in params:  # eg. soma(0.5).hh._ref_gna
                            ptr = getattr(
                                getattr(
                                    self.secs[params['sec']]['hObj'](
                                        params['loc']), params['mech']),
                                '_ref_' + params['var'])
                        elif 'synMech' in params:  # eg. soma(0.5).AMPA._ref_g
                            sec = self.secs[params['sec']]
                            synMechList = [
                                synMech for synMech in sec['synMechs']
                                if synMech['label'] == params['synMech']
                                and synMech['loc'] == params['loc']
                            ]  # make list with this label/loc
                            ptr = None
                            if len(synMechList) > 0:
                                if 'index' in params:
                                    if params['index'] < len(synMechList):
                                        synMech = synMechList[params['index']]
                                        ptr = getattr(synMech['hObj'],
                                                      '_ref_' + params['var'])
                                else:
                                    synMech = synMechList[
                                        0]  # 0th one which would have been returned by next()
                                    ptr = getattr(synMech['hObj'],
                                                  '_ref_' + params['var'])
                        elif 'stim' in params:  # e.g. sim.net.cells[0].stims[0]['hObj'].i
                            if 'sec' in params and 'loc' in params and 'var' in params:
                                sec = self.secs[params['sec']]
                                stimList = [
                                    stim for stim in self.stims
                                    if stim['label'] == params['stim']
                                    and stim['loc'] == params['loc']
                                ]  # make list with this label/loc
                                ptr = None
                                if len(stimList) > 0:
                                    if 'index' in params:
                                        if params['index'] < len(stimList):
                                            stim = stimList[params['index']]
                                            ptr = getattr(
                                                stim['hObj'],
                                                '_ref_' + params['var'])
                                    else:
                                        stim = stimList[
                                            0]  # 0th one which would have been returned by next()
                                        ptr = getattr(stim['hObj'],
                                                      '_ref_' + params['var'])
                        else:  # eg. soma(0.5)._ref_v
                            ptr = getattr(
                                self.secs[params['sec']]['hObj'](
                                    params['loc']), '_ref_' + params['var'])
                    elif 'synMech' in params:  # special case where want to record from multiple synMechs
                        if 'sec' in params:
                            sec = self.secs[params['sec']]
                            synMechs = [
                                synMech for synMech in sec['synMechs']
                                if synMech['label'] == params['synMech']
                            ]
                            ptr = [
                                getattr(synMech['hObj'],
                                        '_ref_' + params['var'])
                                for synMech in synMechs
                            ]
                            secLocs = [
                                params.sec + str(synMech['loc'])
                                for synMech in synMechs
                            ]
                        else:
                            ptr = []
                            secLocs = []
                            for secName, sec in self.secs.items():
                                synMechs = [
                                    synMech for synMech in sec['synMechs']
                                    if synMech['label'] == params['synMech']
                                ]
                                ptr.extend([
                                    getattr(synMech['hObj'],
                                            '_ref_' + params['var'])
                                    for synMech in synMechs
                                ])
                                secLocs.extend([
                                    secName + '_' + str(synMech['loc'])
                                    for synMech in synMechs
                                ])

                    else:
                        if 'pointp' in params:  # eg. soma.izh._ref_u
                            if params['pointp'] in self.secs[
                                    params['sec']]['pointps']:
                                ptr = getattr(
                                    self.secs[params['sec']]['pointps'][
                                        params['pointp']]['hObj'],
                                    '_ref_' + params['var'])
                        elif 'conns' in params:  # e.g. cell.conns
                            if 'mech' in params:
                                ptr = []
                                secLocs = []
                                for conn_idx, conn in enumerate(self.conns):
                                    if params['mech'] in conn.keys():
                                        if isinstance(
                                                conn[params['mech']],
                                                dict) and 'hObj' in conn[
                                                    params['mech']].keys():
                                            ptr.extend([
                                                getattr(
                                                    conn[params['mech']]
                                                    ['hObj'],
                                                    '_ref_' + params['var'])
                                            ])
                                        else:
                                            ptr.extend([
                                                getattr(
                                                    conn[params['mech']],
                                                    '_ref_' + params['var'])
                                            ])
                                        secLocs.extend([
                                            params['sec'] + '_conn_' +
                                            str(conn_idx)
                                        ])
                            else:
                                print(
                                    "Error recording conn trace, you need to specify the conn mech to record from."
                                )

                        elif 'var' in params:  # point process cell eg. cell._ref_v
                            ptr = getattr(self.hPointp,
                                          '_ref_' + params['var'])

                    if ptr:  # if pointer has been created, then setup recording
                        if isinstance(ptr, list):
                            sim.simData[key]['cell_' + str(self.gid)] = {}
                            for ptrItem, secLoc in zip(ptr, secLocs):
                                if sim.cfg.recordStep == 'adaptive':
                                    recordStep = 0.1
                                else:
                                    recordStep = sim.cfg.recordStep
                                if hasattr(sim.cfg, 'use_local_dt'
                                           ) and sim.cfg.use_local_dt:
                                    self.secs[params['sec']]['hObj'].push()
                                    if hasattr(
                                            sim.cfg, 'recordStep'
                                    ) and sim.cfg.recordStep == 'adaptive':
                                        sim.simData[key]['cell_time_' + str(
                                            self.gid)][secLoc] = h.Vector()
                                        sim.simData[key]['cell_' + str(
                                            self.gid)][secLoc] = h.Vector()
                                        sim.cvode.record(
                                            ptrItem, sim.simData[key]
                                            ['cell_' + str(self.gid)][secLoc],
                                            sim.simData[key][
                                                'cell_time_' +
                                                str(self.gid)][secLoc])
                                    else:
                                        sim.simData[key][
                                            'cell_' +
                                            str(self.gid)][secLoc] = h.Vector(
                                                sim.cfg.duration / recordStep +
                                                1).resize(0)
                                        sim.cvode.record(
                                            ptrItem, sim.simData[key]
                                            ['cell_' + str(self.gid)][secLoc],
                                            sim.simData['t'], 1)
                                    h.pop_section()
                                else:

                                    sim.simData[key][
                                        'cell_' +
                                        str(self.gid)][secLoc] = h.Vector(
                                            sim.cfg.duration / recordStep +
                                            1).resize(0)
                                    sim.simData[key][
                                        'cell_' +
                                        str(self.gid)][secLoc].record(
                                            ptrItem, recordStep)
                        else:
                            if hasattr(
                                    sim.cfg,
                                    'use_local_dt') and sim.cfg.use_local_dt:
                                self.secs[params['sec']]['hObj'].push()
                                sim.simData[key]['cell_' +
                                                 str(self.gid)] = h.Vector()
                                if hasattr(
                                        sim.cfg, 'recordStep'
                                ) and sim.cfg.recordStep == 'adaptive':
                                    sim.simData[key][
                                        'cell_time_' +
                                        str(self.gid)] = h.Vector()
                                    sim.cvode.record(
                                        ptr, sim.simData[key]['cell_' +
                                                              str(self.gid)],
                                        sim.simData[key]['cell_time_' +
                                                         str(self.gid)])
                                else:
                                    sim.cvode.record(
                                        ptr, sim.simData[key]['cell_' +
                                                              str(self.gid)],
                                        sim.simData['t'], 1)
                                h.pop_section()
                            else:
                                sim.simData[key]['cell_' +
                                                 str(self.gid)] = h.Vector(
                                                     sim.cfg.duration /
                                                     sim.cfg.recordStep +
                                                     1).resize(0)
                                sim.simData[key]['cell_' +
                                                 str(self.gid)].record(
                                                     ptr, sim.cfg.recordStep)
                        if sim.cfg.verbose:
                            print('  Recording ', key, 'from cell ', self.gid,
                                  ' with parameters: ', str(params))
                            print(sim.simData[key]['cell_' + str(self.gid)])
                except:
                    if sim.cfg.verbose:
                        print('  Cannot record ', key, 'from cell ', self.gid)
            else:
                if sim.cfg.verbose:
                    print('  Conditions preclude recording ', key,
                          ' from cell ', self.gid)
Пример #33
0
def leaky(cell,
          v0,
          synList,
          RList,
          vecStimList,
          n,
          trans,
          tend,
          tstep,
          loc,
          pos,
          alphaR=True,
          cpi=False,
          cpt=-1.0):
    f = open('pylog', 'a')
    h.tstop = tend
    print loc
    print >> f, loc
    print pos
    print >> f, pos

    h.dt = tstep
    v = h.Vector()
    t = h.Vector()
    v.record(cell.soma(0.5)._ref_v)
    t.record(h._ref_t)
    if trans > 0:
        cell.soma.push()
        vHold = h.SEClamp(0.5)
        vHold.dur2 = 0
        vHold.dur3 = 0
        vHold.rs = 1e-9
        vHold.dur1 = trans
        vHold.amp1 = v0
        h.pop_section()
        print ' soma clamp'
    dendv = []
    for i in xrange(n):
        dendv.append(h.Vector())
        dendv[i].record(cell.dend[loc[i]](pos[i])._ref_v)
        print 'record ', i
        print >> f, 'record ', i
        if alphaR:
            synList[i].deltat = h.dt
        vecStimList[i].play(h.Vector([]))
        vecStimList[i].dt = h.dt
    print 'ready to run'
    print >> f, 'ready to run'
    run(cell, v0, 0, 0, 0, synList, RList, n, trans, 1, 0, alphaR, loc, pos,
        False, v, t, dendv, cpi, cpt)
    #print   'i ran and i killed ', fired, ' bedbug(s)'
    #print >>f,   'i ran and i killed ', fired, ' bedbug(s)'
    v1 = v.as_numpy()
    ntotal = int(round(tend / tstep) + 1)
    if __name__ == '__main__':
        t1 = t.as_numpy()
    if v1.size != ntotal:
        print ' steps ', v1.size, ', ntotal ', ntotal
        print ' remove extra step'
        print >> f, ' remove extra step'
        v1 = v1[:-1]
        if __name__ == '__main__':
            t1 = t1[:-1]
    print ' is this nan ', v1[-1], v1[-2], v1[-3]
    print >> f, ' is this nan ', v1[-1], v1[-2], v1[-3]
    print ' v size ', v1.size
    print >> f, ' v size ', v1.size
    ntrans = int(round(trans / tstep))
    #if v1[ntrans] == v1[ntrans-1]:
    #    ntrans = ntrans+1
    #assert(v1[ntrans] != v1[ntrans-1])
    print ' trans size ', ntrans
    print ' trans end, v0, v1', v1[ntrans - 1], v1[ntrans], v1[ntrans + 1]
    print >> f, ' trans end, v0, v1', v1[ntrans - 1], v1[ntrans], v1[ntrans +
                                                                     1]
    print ' v w/o trans size ', v1.size - ntrans
    print >> f, ' v w/o trans size ', v1.size - ntrans
    if trans > 0:
        vHold = None
    if __name__ == '__main__':
        nt = int((trans) / tstep)
        pyplot.figure('slice', figsize=(8, 4))
        pyplot.plot(t1[nt:], v1[nt:])
        #pyplot.show()
        pyplot.savefig('slice.png', format='png', bbox_inches='tight', dpi=900)
    #print 'highest voltage ', np.amax(v1), ' in ', v1.size, ' steps'
    #print >>f, 'highest voltage ', np.amax(v1), ' in ', v1.size, ' steps'
    dendvArray = np.empty((n, ntotal))
    for i in xrange(n):
        dvtmp = dendv[i].as_numpy().copy()
        if dvtmp.size != ntotal:
            print '    dendv steps ', dvtmp.size, ', ntotal ', ntotal
            print '    remove extra step'
            dvtmp = dvtmp[:-1]
        dendvArray[i, :] = dvtmp
    f.close()
    return v1.copy(), dendvArray
Пример #34
0
import numpy
import types

h("objref p")
h("p = new PythonObject()")

try:
    import pylab
    from pylab import plot, arange, figure
    my_pylab_loaded = True
except ImportError:
    print "Pylab not imported"
    my_pylab_loaded = False

def htype (obj): st=obj.hname(); sv=st.split('['); return sv[0]
def secname (obj): obj.push(); print h.secname() ; h.pop_section()
def psection (obj): obj.push(); print h.psection() ; h.pop_section()

allsecs=None #global list containing all NEURON sections, initialized via mkallsecs

# still need to generate a full allsecs
def mkallsecs ():
  """ mkallsecs - make the global allsecs variable, containing
      all the NEURON sections.
  """
  global allsecs
  allsecs=h.SectionList() # no .clear() command
  roots=h.SectionList()
  roots.allroots()
  for s in roots:
    s.push()
Пример #35
0
def importCell(fileName, cellName, cellArgs=None, cellInstance=False):
    """
    Function for/to <short description of `netpyne.conversion.neuronPyHoc.importCell`>

    Parameters
    ----------
    fileName : <type>
        <Short description of fileName>
        **Default:** *required*

    cellName : <type>
        <Short description of cellName>
        **Default:** *required*

    cellArgs : <``None``?>
        <Short description of cellArgs>
        **Default:** ``None``
        **Options:** ``<option>`` <description of option>

    cellInstance : bool
        <Short description of cellInstance>
        **Default:** ``False``
        **Options:** ``<option>`` <description of option>

"""

    h.initnrn()

    varList = mechVarList(
    )  # list of properties for all density mechanisms and point processes
    origGlob = getGlobals(
        list(varList['mechs'].keys()) + list(varList['pointps'].keys()))
    origGlob[
        'v_init'] = -65  # add by hand since won't be set unless load h.load_file('stdrun')

    if cellArgs is None:
        cellArgs = []  # Define as empty list if not otherwise defined

    if fileName.endswith('.hoc') or fileName.endswith('.tem'):
        h.load_file(fileName)
        if not cellInstance:
            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
        else:
            try:
                cell = getattr(h, cellName)
            except:
                cell = None
    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)
            removeFilePath = True
        else:
            removeFilePath = False
        moduleName = fileNameOnly.split('.py')[
            0]  # remove .py to obtain module name
        tempModule = importlib.import_module(moduleName)
        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
        if removeFilePath: sys.path.remove(filePath)
    else:
        print("File name should be either .hoc or .py file")
        return

    secDic, secListDic, synMechs, globs = getCellParams(
        cell, varList, origGlob)

    if fileName.endswith('.py'):
        _delete_module(moduleName)
        _delete_module('tempModule')
        del modulePointer
    elif fileName.endswith('.hoc'):
        for sec in h.allsec():
            try:
                if h.cas() != sec: sec.push()
                h.delete_section()
                h.pop_section()
            except:
                pass
    h.initnrn()

    setGlobals(origGlob)  # restore original globals

    return secDic, secListDic, synMechs, globs
Пример #36
0
    def set_biophysics(self, p_all):
        "Set the biophysics for the default Pyramidal cell."

        # Insert 'hh2' mechanism
        self.soma.insert('hh2')
        self.soma.gkbar_hh2 = p_all['L5Pyr_soma_gkbar_hh2']
        self.soma.gnabar_hh2 = p_all['L5Pyr_soma_gnabar_hh2']
        self.soma.gl_hh2 = p_all['L5Pyr_soma_gl_hh2']
        self.soma.el_hh2 = p_all['L5Pyr_soma_el_hh2']

        # insert 'ca' mechanism
        # Units: pS/um^2
        self.soma.insert('ca')
        self.soma.gbar_ca = p_all['L5Pyr_soma_gbar_ca']

        # insert 'cad' mechanism
        # units of tau are ms
        self.soma.insert('cad')
        self.soma.taur_cad = p_all['L5Pyr_soma_taur_cad']

        # insert 'kca' mechanism
        # units are S/cm^2?
        self.soma.insert('kca')
        self.soma.gbar_kca = p_all['L5Pyr_soma_gbar_kca']

        # Insert 'km' mechanism
        # Units: pS/um^2
        self.soma.insert('km')
        self.soma.gbar_km = p_all['L5Pyr_soma_gbar_km']

        # insert 'cat' mechanism
        self.soma.insert('cat')
        self.soma.gbar_cat = p_all['L5Pyr_soma_gbar_cat']

        # insert 'ar' mechanism
        self.soma.insert('ar')
        self.soma.gbar_ar = p_all['L5Pyr_soma_gbar_ar']

        # 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 = p_all['L5Pyr_dend_gkbar_hh2']
            self.dends[key].gl_hh2 = p_all['L5Pyr_dend_gl_hh2']
            self.dends[key].gnabar_hh2 = p_all['L5Pyr_dend_gnabar_hh2']
            self.dends[key].el_hh2 = p_all['L5Pyr_dend_el_hh2']

            # Insert 'ca' mechanims
            # Units: pS/um^2
            self.dends[key].insert('ca')
            self.dends[key].gbar_ca = p_all['L5Pyr_dend_gbar_ca']

            # Insert 'cad' mechanism
            self.dends[key].insert('cad')
            self.dends[key].taur_cad = p_all['L5Pyr_dend_taur_cad']

            # Insert 'kca' mechanism
            self.dends[key].insert('kca')
            self.dends[key].gbar_kca = p_all['L5Pyr_dend_gbar_kca']

            # Insert 'km' mechansim
            # Units: pS/um^2
            self.dends[key].insert('km')
            self.dends[key].gbar_km = p_all['L5Pyr_dend_gbar_km']

            # insert 'cat' mechanism
            self.dends[key].insert('cat')
            self.dends[key].gbar_cat = 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 = 1e-6 * np.exp(3e-3 * h.distance(seg.x))

            h.pop_section()
Пример #37
0
def clampEffects(cell, v0, trans, tend, t0, tstep, clampDend):
    f = open('pylog', 'a')
    h.tstop = tend
    print '     ', t0, ' with ', trans, ' trans ', ' to ', tend
    print >> f, '     ', t0, ' with ', trans, ' trans ', ' to ', tend

    h.dt = tstep
    v = h.Vector()
    t = h.Vector()
    v.record(cell.soma(0.5)._ref_v)
    t.record(h._ref_t)
    if trans > 0:
        cell.soma.push()
        vHold = h.SEClamp(0.5)
        vHold.dur2 = 0
        vHold.dur3 = 0
        vHold.rs = 1e-9
        vHold.dur1 = t0 + trans
        vHold.amp1 = v0
        h.pop_section()
        print ' soma clamp'
        if clampDend:
            vHolds = []
            print cell.ndend, ' dendrites'
            for i in xrange(cell.ndend):
                cell.dend[i].push()
                vHolds.append(h.SEClamp(0.5))
                vHolds[i].dur2 = 0
                vHolds[i].dur3 = 0
                vHolds[i].rs = 1e-9
                vHolds[i].dur1 = t0 + trans
                vHolds[i].amp1 = v0
                h.pop_section()
    dendv = []
    for i in xrange(cell.ndend):
        dendv.append(h.Vector())
        dendv[3 * i].record(cell.dend[i](0.16666)._ref_v)
        dendv.append(h.Vector())
        dendv[3 * i + 1].record(cell.dend[i](0.5)._ref_v)
        dendv.append(h.Vector())
        dendv[3 * i + 2].record(cell.dend[i](0.83333)._ref_v)
    print 'ready to run'
    print >> f, 'ready to run'
    srun(cell, v0, trans, t0)
    #print   'i ran and i killed ', fired, ' bedbug(s)'
    #print >>f,   'i ran and i killed ', fired, ' bedbug(s)'
    ntotal = int(round((tend - t0) / tstep) + 1)
    nt = int((trans) / tstep)
    dendVec = np.empty((3 * cell.ndend, ntotal), dtype='float')
    for i in xrange(cell.ndend):
        dendVec[3 * i, :] = dendv[3 * i].as_numpy()
        dendVec[3 * i + 1, :] = dendv[3 * i + 1].as_numpy()
        dendVec[3 * i + 2, :] = dendv[3 * i + 2].as_numpy()
    v1 = v.as_numpy()
    t1 = t.as_numpy()
    dendVec = np.reshape(dendVec, (3, 199, ntotal))
    mdend = np.average(dendVec, axis=0)
    print 'mdend ', mdend.shape
    qdendlow = np.percentile(mdend, 10, axis=0)
    print 'qdendlow', qdendlow.shape
    qdendhigh = np.percentile(mdend, 90, axis=0)
    print 'qdendhigh', qdendhigh.shape
    dendAverage = np.average(mdend, axis=0)
    print 'dendAverage', dendAverage.shape
    denderrbar = np.vstack((qdendlow, qdendhigh))
    print 'denderrbar', denderrbar.shape
    pyplot.figure('slice', figsize=(8, 4))
    #istart = nt
    istart = 0
    pyplot.plot(t1[istart:], v1[istart:])
    t2 = t1[istart:]
    dA = dendAverage[istart:]
    dE = denderrbar[:, istart:]
    select = np.arange(0, t2.size, 50)
    t2 = t2[select]
    print 't2', t2.shape
    dA = dA[select]
    print 'dA', dA.shape
    dE = dE[:, select]
    print 'dE', dE.shape
    pyplot.errorbar(t2, dA, np.absolute(np.vstack((dA, dA)) - dE))
    pyplot.draw()
    #pyplot.savefig('slice.png',format='png',bbox_inches='tight',dpi=900)
    #print 'highest voltage ', np.amax(v1), ' in ', v1.size, ' steps'
    #print >>f, 'highest voltage ', np.amax(v1), ' in ', v1.size, ' steps'
    f.close()
Пример #38
0
def push_section(section):
    '''push a section onto the top of the NEURON stack, pop it when leaving the context'''
    section.push()
    yield
    h.pop_section()
def getCenter(soma):
    soma.push()
    center = (h.x3d(0), h.y3d(0), h.z3d(0))
    h.pop_section()
    return center
Пример #40
0
    def __set_3Dshape (self):
        # set 3d shape of soma by calling shape_soma from class Cell
        # print("Warning: You are setiing 3d shape geom. You better be doing")
        # print("gui analysis and not numerical analysis!!")
        self.shape_soma()

        # soma proximal coords
        x_prox = 0
        y_prox = 0

        # soma distal coords
        x_distal = 0
        y_distal = self.soma.L

        # dend 0-2 are major axis, dend 3 is branch
        # deal with distal first along major cable axis
        # the way this is assigning variables is ugly/lazy right now
        for i in range(0, 3):
            h.pt3dclear(sec=self.list_dend[i])

            # x_distal and y_distal are the starting points for each segment
            # these are updated at the end of the loop
            h.pt3dadd(0, y_distal, 0, self.dend_diam[i], sec=self.list_dend[i])

            # update x_distal and y_distal after setting them
            # x_distal += dend_dx[i]
            y_distal += self.dend_L[i]

            # add next point
            h.pt3dadd(0, y_distal, 0, self.dend_diam[i], sec=self.list_dend[i])

        # now deal with dend 3
        # dend 3 will ALWAYS be positioned at the end of dend[0]
        h.pt3dclear(sec=self.list_dend[3])

        # activate this section with 'sec =' notation
        # self.list_dend[0].push()
        x_start = h.x3d(1, sec = self.list_dend[0])
        y_start = h.y3d(1, sec = self.list_dend[0])
        # h.pop_section()

        h.pt3dadd(x_start, y_start, 0, self.dend_diam[3], sec=self.list_dend[3])
        # self.dend_L[3] is subtracted because lengths always positive,
        # and this goes to negative x
        h.pt3dadd(x_start-self.dend_L[3], y_start, 0, self.dend_diam[3], sec=self.list_dend[3])

        # now deal with proximal dends
        for i in range(4, 7):
            h.pt3dclear(sec=self.list_dend[i])

        # deal with dend 4, ugly. sorry.
        h.pt3dadd(x_prox, y_prox, 0, self.dend_diam[i], sec=self.list_dend[4])
        y_prox += -self.dend_L[4]

        h.pt3dadd(x_prox, y_prox, 0, self.dend_diam[4], sec=self.list_dend[4])

        # x_prox, y_prox are now the starting points for BOTH last 2 sections

        # dend 5
        # Calculate x-coordinate for end of dend
        dend5_x = -self.dend_L[5] * np.sqrt(2) / 2.
        h.pt3dadd(x_prox, y_prox, 0, self.dend_diam[5], sec=self.list_dend[5])
        h.pt3dadd(dend5_x, y_prox-self.dend_L[5] * np.sqrt(2) / 2.,
                    0, self.dend_diam[5], sec=self.list_dend[5])

        # dend 6
        # Calculate x-coordinate for end of dend
        dend6_x = self.dend_L[6] * np.sqrt(2) / 2.
        h.pt3dadd(x_prox, y_prox, 0, self.dend_diam[6], sec=self.list_dend[6])
        h.pt3dadd(dend6_x, y_prox-self.dend_L[6] * np.sqrt(2) / 2.,
                    0, self.dend_diam[6], sec=self.list_dend[6])

        # set 3D position
        # z grid position used as y coordinate in h.pt3dchange() to satisfy
        # gui convention that y is height and z is depth. In h.pt3dchange()
        # x and z components are scaled by 100 for visualization clarity
        self.soma.push()
        for i in range(0, int(h.n3d())):
            h.pt3dchange(i, self.pos[0]*100 + h.x3d(i), self.pos[2] +
                           h.y3d(i), self.pos[1] * 100 + h.z3d(i),
                           h.diam3d(i))

        h.pop_section()
Пример #41
0
 gmax = args.gmax
 diascale = args.diascale
 dialim = args.dialim
 maxrate = args.maxrate / 1000.0  # s^-1 to per ms^-1
 mechs = {'pas': {'g': '{} S/cm**2'.format(args.gpas), 'e': '-51.0mV'}}
 h.xopen(celltemplate)
 ggn = nu.create_cell(args.cellname,
                      mechparams=mechs,
                      Ra='{}ohm*cm'.format(args.RA),
                      filename=args.celltemplate)
 if (args.diascale is not None) and (args.dialim is not None):
     count = 0
     ggn.soma.push()
     ordered_tree = h.SectionList()
     ordered_tree.wholetree()
     h.pop_section()
     for sec in ordered_tree:
         sec.push()
         for ii, seg in enumerate(sec):
             if seg.diam < dialim:
                 seg.diam = seg.diam * diascale
                 count += 1
         h.pop_section()
     print('Scaled diameters of', count, 'sections whose diameters were <',
           dialim, 'by', diascale)
 g0 = nu.nrngraph(ggn)
 g, nmap = ng.renumber_nodes(g0, ggn.soma.name())
 # This also gets the dummy nodes at the tips
 stype_node_map_all = ng.get_stype_node_map(g)
 stype_node_map = {}
 # Collect only nodes with sections associated.
Пример #42
0
    def set_geometry(self, TopolDict):
        """ 
        Set the topology and geometry from the :attr:`TopolDict` dictionary.

        * First, the beginning of each ``Section`` is connected to the end of its "father" ``Section``, defined in the :attr:`MorphoData` csv

        * Second, it sets each compartment position and diameter

        Parameters
        ----------
        TopolDict: Dictionary
            :class:`neuron_class`'s :attr:`TopolDict` attribute: Dictionary with all topological information in the form

                [ [ SecListName[SecNumber] ,  Who is connected to (IDFather) ,  x ,  y ,  z ] ] , [...], ... ]

            Eg.:

            .. code-block:: python

                #            NEURON object    name           ID of father     x  y  z
                TopolDict = { SomaList[0]: ['SomaList[0]',       -1,          0, 0, 0]
                              SomaList[1]: ['SomaList[1]', ID of SomaList[0], 0, 0, -2],
                              ...
                              ApicList[9]: ['ApicList[9]', ID of ApicList[2], 0, 0, -1000]}
        """
        for key in TopolDict.keys():
            # The first section (SomaList[0]) doesn't need to be connected
            if key != self.SomaList[0]:
                key.connect(TopolDict[key][1])

        # Once all sections are connected, we define its position and diameter:
        h.pop_section()
        for key in TopolDict.keys():
            if key in self.SomApicList:
                numsegs = 15
                key.push()
                h.pt3dclear()
                pointList = []
                for i in range(3, len(TopolDict[key])):
                    # If it's a list, then add that 3d point
                    pointList.append([
                        TopolDict[key][i][0], TopolDict[key][i][1],
                        TopolDict[key][i][2], TopolDict[key][i][3]
                    ])
                ID_compartment = np.array(
                    [float(i) / numsegs
                     for i in range(numsegs)]) * len(pointList)
                for idc in ID_compartment:
                    xi, yi, zi, di = pointList[int(idc)]
                    h.pt3dadd(xi, yi, zi, di)
                h.pop_section()
                key.nseg = numsegs
                continue
            else:
                key.push()
                h.pt3dclear()
                pointList = []
                for i in range(3, len(TopolDict[key])):
                    # If it's a list, then add that 3d point
                    pointList.append([
                        TopolDict[key][i][0], TopolDict[key][i][1],
                        TopolDict[key][i][2], TopolDict[key][i][3]
                    ])
                if len(pointList) < 2: numsegs = 1
                else: numsegs = 3
                ID_compartment = np.array(
                    [float(i) / numsegs
                     for i in range(numsegs)]) * len(pointList)
                for idc in ID_compartment:
                    xi, yi, zi, di = pointList[int(idc)]
                    h.pt3dadd(xi, yi, zi, di)
                h.pop_section()
                key.nseg = numsegs
Пример #43
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
        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 -- 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
Пример #44
0
    def __init__(self, position, record_all=0, Dt=0.1):
        self.record_all = record_all
        # if record_all:
        #     print "Recording all in Grc"
        self.soma = h.Section(cell=self)
        self.soma.nseg = 1
        self.soma.diam = 9.76
        self.soma.L = 9.76
        self.soma.cm = 1
        self.soma.Ra = 100
        # h.celsius = 37

        self.whatami = "grc"

        self.soma.push()
        h.pt3dclear()
        h.pt3dadd(position.item(0),
                  position.item(1) - self.soma.L, position.item(2),
                  self.soma.diam)
        h.pt3dadd(position.item(0),
                  position.item(1) + self.soma.L, position.item(2),
                  self.soma.diam)
        h.pop_section()

        self.soma.insert('GRANULE_LKG1')
        self.soma.insert('GRANULE_LKG2')
        self.soma.insert('GRANULE_Nmda_leak')
        self.soma.insert('GRANULE_NA')
        self.soma.insert('GRANULE_NAR')
        self.soma.insert('GRANULE_PNA')
        self.soma.insert('GRANULE_KV')
        self.soma.insert('GRANULE_KA')
        self.soma.insert('GRANULE_KIR')
        self.soma.insert('GRANULE_KCA')
        self.soma.insert('GRANULE_KM')
        self.soma.insert('GRANULE_CA')
        self.soma.insert('GRANULE_CALC')

        h.usetable_GRANULE_NA = 1
        h.usetable_GRANULE_NAR = 1
        h.usetable_GRANULE_PNA = 1
        h.usetable_GRANULE_KV = 1
        h.usetable_GRANULE_KA = 1
        h.usetable_GRANULE_KIR = 1
        h.usetable_GRANULE_KCA = 0
        h.usetable_GRANULE_KM = 1
        h.usetable_GRANULE_CA = 1

        self.soma.ena = 87.39
        self.soma.ek = -84.69
        self.soma.eca = 129.33

        self.MF_L = []
        self.GOC_L = []
        self.mfncpc = []
        self.gocncpc = []

        self.spike = h.NetStim(0.5, sec=self.soma)
        self.spike.start = -10
        self.spike.number = 1
        self.spike.interval = 1e9

        self.nc_spike = h.NetCon(self.soma(1)._ref_v,
                                 self.spike,
                                 -20,
                                 0,
                                 1,
                                 sec=self.soma)

        self.record = {}

        self.record['spk'] = h.Vector()
        self.nc_spike.record(self.record['spk'])

        if self.record_all:
            self.record['vm'] = h.Vector()
            self.record['vm'].record(self.soma(.5)._ref_v, Dt, sec=self.soma)

            # self.record['ca'] = h.Vector()
            # self.record['ca'].record(self.soma(.5)._ref_cai, Dt, sec = self.soma) #Just an attempt to record Calcium currents
            self.record['NA'] = h.Vector()
            self.record['NA'].record(
                self.soma(.5)._ref_ic_GRANULE_NA, Dt,
                sec=self.soma)  #Just an attempt to record Potassium currents

            self.record['NAR'] = h.Vector()
            self.record['NAR'].record(
                self.soma(.5)._ref_ic_GRANULE_NAR, Dt,
                sec=self.soma)  #Just an attempt to record Potassium currents

            self.record['PNA'] = h.Vector()
            self.record['PNA'].record(
                self.soma(.5)._ref_ic_GRANULE_NA, Dt,
                sec=self.soma)  #Just an attempt to record Potassium currents

            self.record['KV'] = h.Vector()
            self.record['KV'].record(
                self.soma(.5)._ref_ic_GRANULE_KV, Dt,
                sec=self.soma)  #Just an attempt to record Potassium currents

            self.record['KA'] = h.Vector()
            self.record['KA'].record(
                self.soma(.5)._ref_ic_GRANULE_KA, Dt,
                sec=self.soma)  #Just an attempt to record Potassium currents

            self.record['KIR'] = h.Vector()
            self.record['KIR'].record(
                self.soma(.5)._ref_ic_GRANULE_KIR, Dt,
                sec=self.soma)  #Just an attempt to record Potassium currents

            self.record['KCA'] = h.Vector()
            self.record['KCA'].record(
                self.soma(.5)._ref_ic_GRANULE_KCA, Dt,
                sec=self.soma)  #Just an attempt to record Potassium currents

            self.record['KM'] = h.Vector()
            self.record['KM'].record(
                self.soma(.5)._ref_ic_GRANULE_KM, Dt,
                sec=self.soma)  #Just an attempt to record Potassium currents

            self.record['CA'] = h.Vector()
            self.record['CA'].record(
                self.soma(.5)._ref_ic_GRANULE_CA, Dt,
                sec=self.soma)  #Just an attempt to record Potassium currents

            self.record['CALC'] = h.Vector()
            self.record['CALC'].record(
                self.soma(.5)._ref_ic_GRANULE_CALC, Dt,
                sec=self.soma)  #Just an attempt to record Potassium currents

            self.record['LKG1'] = h.Vector()
            self.record['LKG1'].record(
                self.soma(.5)._ref_ic_GRANULE_LKG1, Dt,
                sec=self.soma)  #Just an attempt to record Potassium currents

            self.record['LKG2'] = h.Vector()
            self.record['LKG2'].record(
                self.soma(.5)._ref_ic_GRANULE_LKG2, Dt,
                sec=self.soma)  #Just an attempt to record Potassium currents
Пример #45
0
    def __init__(self, _id):
        self._id = _id

        h.load_file('stdlib.hoc')
        h.load_file('import3d.hoc')

        cell = h.Import3d_Neurolucida3()
        cell.input('morphology/GrC2020.asc')

        i3d = h.Import3d_GUI(cell, 0)
        i3d.instantiate(self)

        #Soma channels
        self.soma[0].nseg = 1 + (2 * int(self.soma[0].L / 40))
        self.soma[0].Ra = 100
        self.soma[0].cm = 2

        self.soma[0].insert('Leak')
        self.soma[0].gmax_Leak = 0.00029038073716
        self.soma[0].e_Leak = -60

        self.soma[0].insert('Kv3_4')
        self.soma[0].gkbar_Kv3_4 = 0.00076192450951999995

        self.soma[0].insert('Kv4_3')
        self.soma[0].gkbar_Kv4_3 = 0.0028149683906099998
        self.soma[0].ek = -88

        self.soma[0].insert('Kir2_3')
        self.soma[0].gkbar_Kir2_3 = 0.00074725514701999996

        self.soma[0].insert('GRC_CA')
        self.soma[0].gcabar_GRC_CA = 0.00060938071783999998

        self.soma[0].insert('Kv1_1')
        self.soma[0].gbar_Kv1_1 = 0.0056973826455499997

        self.soma[0].insert('Kv1_5')
        self.soma[0].gKur_Kv1_5 = 0.00083407556713999999

        self.soma[0].insert('Kv2_2_0010')
        self.soma[0].gKv2_2bar_Kv2_2_0010 = 1.203410852e-05

        self.soma[0].insert('cdp5_CR')

        self.soma[0].push()
        self.soma[0].eca = 137.5
        h.pop_section()

        self.whatami = "GrC_2020_regular"

        #DEND
        for i in self.dend:
            i.nseg = 1 + (2 * int(i.L / 40))
            i.Ra = 100
            i.cm = 2.5

            i.insert('Leak')
            i.gmax_Leak = 0.00025029700736999997
            i.e_Leak = -60

            i.insert('GRC_CA')
            i.gcabar_GRC_CA = 0.0050012800845900002

            i.insert('Kca1_1')
            i.gbar_Kca1_1 = 0.010018074546510001
            i.ek = -88

            i.insert('Kv1_1')
            i.gbar_Kv1_1 = 0.00381819207934

            i.insert('cdp5_CR')

            i.push()
            i.eca = 137.5
            h.pop_section()

#Hilock
        self.axon = h.Section(name='hilock', cell=self)
        self.axon.L = 1
        self.axon.nseg = 1
        self.axon.diam = 1.5
        self.axon.Ra = 100
        self.axon.cm = 2

        self.axon.insert('Leak')
        self.axon.gmax_Leak = 0.00036958189720000001
        self.axon.e_Leak = -60

        self.axon.insert('GRC_NA_FHF')
        self.axon.gnabar_GRC_NA_FHF = 0.0092880585146199995
        self.axon.ena = 87.39

        self.axon.insert('Kv3_4')
        self.axon.gkbar_Kv3_4 = 0.020373463109149999
        self.axon.ek = -88

        self.axon.insert('GRC_CA')
        self.axon.gcabar_GRC_CA = 0.00057726155447

        self.axon.insert('cdp5_CR')

        self.axon.push()
        self.axon.eca = 137.5
        h.pt3dadd(0.0, 5.62232, 0.0, self.axon.diam)
        h.pt3dadd(0.0, 6.62232, 0.0, self.axon.diam)
        h.pop_section()

        self.axon.connect(self.soma[0], 0, 0)

        #AIS
        self.ais = h.Section(name='ais', cell=self)
        self.ais.L = 10
        self.ais.nseg = 1
        self.ais.diam = 0.7
        self.ais.Ra = 100
        self.ais.cm = 1

        self.ais.insert('GRC_NA_FHF')
        self.ais.gnabar_GRC_NA_FHF = 1.28725006737226
        self.ais.ena = 87.39

        self.ais.insert('Kv3_4')
        self.ais.gkbar_Kv3_4 = 0.0064959534065400001
        self.ais.ek = -88

        self.ais.insert('Leak')
        self.ais.gmax_Leak = 0.00029276697557000002
        self.ais.e_Leak = -60

        self.ais.insert('GRC_CA')
        self.ais.gcabar_GRC_CA = 0.00031198539471999999

        self.ais.insert('GRC_KM')
        self.ais.gkbar_GRC_KM = 0.00056671971737000002

        self.ais.insert('cdp5_CR')

        self.ais.push()
        self.ais.eca = 137.5

        h.pt3dadd(0.0, 6.62232, 0.0, self.ais.diam)
        h.pt3dadd(0.0, 16.62232, 0.0, self.ais.diam)
        h.pop_section()

        lensec = 7
        secnumber_aa = int(126 / lensec)
        secnumber_pf = int(1000 / lensec)

        self.ais.connect(self.axon, 1, 0)

        self.HD_aa = [
            h.Section(cell=self, name='aa_' + str(x))
            for x in range(secnumber_aa)
        ]
        for b in self.HD_aa:
            b.L = lensec
            b.nseg = 1
            b.diam = 0.3
            b.Ra = 100
            b.cm = 1

            b.insert('GRC_NA')
            b.gnabar_GRC_NA = 0.026301636815019999
            b.ena = 87.39

            b.insert('Kv3_4')
            b.gkbar_Kv3_4 = 0.00237386061632
            b.ek = -88

            b.insert('Leak')
            b.gmax_Leak = 9.3640921249999996e-05
            b.e_Leak = -60

            b.insert('GRC_CA')
            b.gcabar_GRC_CA = 0.00068197420273000001

            b.insert('cdp5_CR')

            b.push()
            b.eca = 137.5

            len_initial = 16.62232
            len_ending = 7

            h.pt3dadd(0.0, len_initial, 0.0, b.diam)
            h.pt3dadd(0.0, len_initial + len_ending, 0.0, b.diam)
            h.pop_section()

            len_initial = len_initial + len_ending

        self.HD_pf1 = [
            h.Section(cell=self, name='pf_' + str(x))
            for x in range(secnumber_pf)
        ]

        for i in self.HD_pf1:
            i.L = lensec
            i.nseg = 1
            i.diam = 0.15
            i.Ra = 100
            i.cm = 1

            i.insert('GRC_NA')
            i.gnabar_GRC_NA = 0.017718484492610001
            i.ena = 87.39

            i.insert('Kv3_4')
            i.gkbar_Kv3_4 = 0.0081756804703699993
            i.ek = -88

            i.insert('Leak')
            i.gmax_Leak = 3.5301616000000001e-07
            i.e_Leak = -60

            i.insert('GRC_CA')
            i.gcabar_GRC_CA = 0.00020856833529999999

            i.insert('cdp5_CR')

            i.push()
            i.eca = 137.5

            len_initial = 142.62232
            len_ending = 7

            h.pt3dadd(len_initial, len_initial, 0.0, i.diam)
            h.pt3dadd(len_initial + len_ending, len_initial, 0.0, i.diam)
            h.pop_section()

            len_initial = len_initial + len_ending

        self.HD_pf2 = [
            h.Section(cell=self, name='pf_' + str(x))
            for x in range(secnumber_pf)
        ]
        for z in self.HD_pf2:
            z.L = lensec
            z.nseg = 1
            z.diam = 0.15
            z.Ra = 100
            z.cm = 1

            z.insert('GRC_NA')
            z.gnabar_GRC_NA = 0.017718484492610001
            z.ena = 87.39

            z.insert('Kv3_4')
            z.gkbar_Kv3_4 = 0.0081756804703699993
            z.ek = -88

            z.insert('Leak')
            z.gmax_Leak = 3.5301616000000001e-07
            z.e_Leak = -60

            z.insert('GRC_CA')
            z.gcabar_GRC_CA = 0.00020856833529999999

            z.insert('cdp5_CR')

            z.push()
            z.eca = 137.5

            len_initial = 142.62232
            len_ending = 7

            h.pt3dadd(len_initial, len_initial, 0.0, i.diam)
            h.pt3dadd(len_initial - len_ending, len_initial, 0.0, i.diam)
            h.pop_section()

            len_initial = len_initial - len_ending

#Connections

#AA
        for j in range(secnumber_aa - 1):
            l = j + 1
            self.HD_aa[l].connect(self.HD_aa[j], 1, 0)
#PF
        for i in range(secnumber_pf - 1):
            l = i + 1
            self.HD_pf1[l].connect(self.HD_pf1[i], 1, 0)
            self.HD_pf2[l].connect(self.HD_pf2[i], 1, 0)

        self.HD_pf1[0].connect(self.HD_aa[secnumber_aa - 1], 1, 0)
        self.HD_pf2[0].connect(self.HD_aa[secnumber_aa - 1], 1, 0)

        #Axon connection to the AIS
        self.HD_aa[0].connect(self.ais, 1, 0)

        #Time and Voltage vectors
        self.time_vector = h.Vector()
        self.time_vector.record(h._ref_t)

        self.vm_soma = h.Vector()
        self.vm_soma.record(self.soma[0](0.5)._ref_v)
Пример #46
0
def importCell(fileName, cellName, cellArgs=None, cellInstance=False):
    h.initnrn()
    varList = mechVarList(
    )  # list of properties for all density mechanisms and point processes
    origGlob = getGlobals(varList['mechs'].keys() + varList['pointps'].keys())
    origGlob[
        'v_init'] = -65  # add by hand since won't be set unless load h.load_file('stdrun')

    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') or fileName.endswith('.tem'):
        h.load_file(fileName)
        if not cellInstance:
            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
        else:
            try:
                cell = getattr(h, cellName)
            except:
                cell = None
    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)
            removeFilePath = True
        else:
            removeFilePath = False
        moduleName = fileNameOnly.split('.py')[
            0]  # remove .py to obtain module name
        tempModule = importlib.import_module(moduleName)
        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
        if removeFilePath: sys.path.remove(filePath)
    else:
        print "File name should be either .hoc or .py file"
        return

    secDic, secListDic, synMechs, globs = getCellParams(
        cell, varList, origGlob)

    if fileName.endswith('.py'):
        _delete_module(moduleName)
        _delete_module('tempModule')
        del modulePointer
    elif fileName.endswith('.hoc'):
        for sec in h.allsec():
            try:
                if h.cas() != sec: sec.push()
                h.delete_section()
                h.pop_section()
            except:
                pass
    h.initnrn()

    setGlobals(origGlob)  # restore original globals

    return secDic, secListDic, synMechs, globs
Пример #47
0
def prepCell(gList, loc, pos, n, v0, alphaR=True):
    f = open('pylog', 'a')
    #print '    location,  strength,   pos'
    #print >>f, '    location,  strength,   pos'
    #for i in xrange(n):
    #    print '#{:2d}   {:3d}      {: 1.1e}    {:0.1f}'.format(i,loc[i],gList[i],pos[i])
    #    print >>f, '#{:2d}   {:3d}      {: 1.1e}    {:0.1f}'.format(i,loc[i],gList[i],pos[i])
    print >> f, 'gList = np.array([',
    print 'gList = np.array([',
    for i in xrange(n):
        if i == n - 1:
            print >> f, gList[i],
            print gList[i],
        else:
            print >> f, gList[i], ', ',
            print gList[i], ', ',
    print >> f, '])'
    print '])'

    print >> f, 'loc = np.array([',
    print 'loc = np.array([',
    for i in xrange(n):
        if i == n - 1:
            print >> f, loc[i],
            print loc[i],
        else:
            print >> f, loc[i], ', ',
            print loc[i], ', ',
    print >> f, '])'
    print '])'

    print >> f, 'pos = np.array([',
    print 'pos = np.array([',
    for i in xrange(n):
        if i == n - 1:
            print >> f, pos[i],
            print pos[i],
        else:
            print >> f, pos[i], ', ',
            print pos[i], ', ',
    print >> f, '])'
    print '])'

    h.cvode.active(0)
    cell = RealisticNeuron(v0)
    cell.soma.push()
    h.distance()
    h.pop_section()
    vecStimList = [h.VecStim() for i in xrange(n)]
    synList = []
    dist = np.zeros((n))
    print >> f, 'distance = np.array([',
    print 'distance = np.array([',
    for i in xrange(n):
        cell.dend[loc[i]].push()
        if gList[i] < 0:
            if alphaR:
                synList.append(h.ALPHAI())
            else:
                synList.append(h.GABAa())
        else:
            if alphaR:
                synList.append(h.ALPHAE())
            else:
                synList.append(h.AMPA())
        synList[i].loc(pos[i])
        h.setpointer(vecStimList[i]._ref_y, 'pre', synList[i])
        h.pop_section()
        if gList[i] < 0:
            if alphaR:
                synList[i].f = -gList[i]
            else:
                synList[i].gmax = -gList[i]
        else:
            if alphaR:
                synList[i].f = gList[i]
            else:
                synList[i].gmax = gList[i]
        dist[i] = h.distance(cell.dend[loc[i]](pos[i]))
        if i == n - 1:
            print >> f, dist[i],
            print dist[i],
        else:
            print >> f, dist[i], ', ',
            print dist[i], ', ',

    print >> f, '])'
    print '])'
    f.close()
    return cell, vecStimList, synList, dist
Пример #48
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 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' -- 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 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 = {}

    # globals
    globs = getGlobals(varList['mechs'].keys() + varList['pointps'].keys(),
                       origGlob=origGlob)
    if 'v_init' in globs:  # set v_init for each section (allows for cells with differnet vinits)
        for sec in 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
Пример #49
0
 def connect2target(self, target):
     self.soma.push()
     nc = h.NetCon(self.soma(0.5)._ref_v, target)
     h.pop_section()
     return nc