Example #1
0
def get_pos_data_short():
    """
    Get positions of all segments currently loaded in Neuron in a simple matrix.
    Section position information is not available.

    :returns: 
        Matrix (3 x nSegments) With x,y,z positions. 
    :rtype: :class:`~numpy.ndarray`

    Example:
        .. code-block:: python

            data = get_pos_data_short()
    """
    n = 0
    for sec in h.allsec():
        n += int(h.n3d())
    data = np.zeros([4, n])
    cnt = 0
    for sec in h.allsec():
        for i in xrange(int(h.n3d())):
            data[0, cnt] = h.x3d(i)
            data[1, cnt] = h.y3d(i)
            data[2, cnt] = h.z3d(i)
            data[3, cnt] = h.diam3d(i)
            cnt += 1
    return data
Example #2
0
    def setup_sections(self):
        start = h.startsw()
        
        ###################################################
        # set up sections
        self.sections = []
        # old style, but it is need for section_name in hoc
        h(self.section_def_template % (self.name, len(self.tree)))
        for sec in h.allsec():
            self.sections.append(sec)


        ###################################################
        # connect sections
        for i,sec in enumerate(self.sections):
            parent = self.tree[i]
            #print "%d to %d" % (i, tree[i])
            if(parent != 0):
                sec.connect(self.sections[parent-1], 1, 0)

        self.num_compartment = 0
        for sec in h.allsec():
            self.num_compartment += 1

        self.setup_time += h.startsw() - start
Example #3
0
  def initialize():
      global Epas
      h.celsius = celsius
      for sec in h.soma:
          h.distance()    
 
      for sec in h.allsec():
          sec.v = Epas
          sec.e_pas = Epas
  
          sec.insert("pas")
          sec.e_pas = Epas
          sec.g_pas = 1/Rm
          sec.Ra = rall
          sec.cm = cap
          sec.gnabar_hh2 = 0 
          sec.gkbar_hh2 = 0
          dist = h.distance(0.5)
          # sec.gcabar_it2 = gcat_func(dist)
          sec.gcabar_it2 = gcat
      for sec in h.soma:
          sec.gnabar_hh2 = gna 
          sec.gkbar_hh2 = gkdr
          # sec.gcabar_it2 = 0.1054*gcat
          sec.gcabar_it2 = gcat
                                                                           
      h.finitialize()       
      h.fcurrent()     
      cvode.re_init()
Example #4
0
def get_pos_data():
    """
    Get positions x, y, z for all segments and their diameter. 

    :returns: 
        4 lists: x,y,z,d. One element per section where each element is
        a :class:`~numpy.ndarray`.

    Example:
        .. code-block:: python

            x,y,z,d = get_pos_data()
            for sec in xrange(len(x)):
                for seg in xrange(len(x[sec]):
                    print x[sec][seg], y[sec][seg], z[sec][seg]
    """
    x = []
    y = []
    z = []
    d = []
    for sec in h.allsec():
        n3d = int(h.n3d())
        x_i, y_i, z_i = np.zeros(n3d), np.zeros(n3d), np.zeros(n3d),
        d_i = np.zeros(n3d)
        for i in xrange(n3d):
            x_i[i] = h.x3d(i)
            y_i[i] = h.y3d(i)
            z_i[i] = h.z3d(i)
            d_i[i] = h.diam3d(i)
        x.append(x_i)
        y.append(y_i)
        z.append(z_i)
        d.append(d_i)
    return x, y, z, d
Example #5
0
 def compute_total_area(self):
     self.total_area = 0
     for sec in h.allsec():
         for seg in sec:
             self.total_area += h.area(seg.x, sec)
     if DEBUG:
         print('Total area: %.0f um^2.' % self.total_area)
Example #6
0
File: rxd.py Project: nrnhines/nrn
def set_solve_type(domain=None, dimension=None, dx=None, nsubseg=None, method=None):
    """Specify the numerical discretization and solver options.
    
    domain -- a section or Python iterable of sections"""
    setting_default = False
    if domain is None:
        domain = h.allsec()
        setting_default = True
    elif isinstance(domain, nrn.Section):
        domain = [domain]
    
    # NOTE: These attributes are set on a per-nrn.Section basis; they cannot 
    #       assume Section1D objects exist because they might be specified before
    #       those objects are created
    
    # domain is now always an iterable (or invalid)
    if method is not None:
        raise RxDException('using set_solve_type to specify method is not yet implemented')
    if dimension is not None:
        if dimension not in (1, 3):
            raise RxDException('invalid option to set_solve_type: dimension must be 1 or 3')
        factory = lambda: dimension
        if setting_default:
            _dimensions.default_factory = factory
        for sec in domain:
            _dimensions[sec] = dimension 
    if dx is not None:
        raise RxDException('using set_solve_type to specify dx is not yet implemented')
    if nsubseg is not None:
        raise RxDException('using set_solve_type to specify nsubseg is not yet implemented')
Example #7
0
  def initialize(Tdist):
      global Epas
      h.celsius = celsius
      for sec in h.soma:
          h.distance()    
 
      for sec in h.allsec():
          sec.v = Epas
          sec.e_pas = Epas
          sec.insert("pas")
          sec.e_pas = Epas
          sec.g_pas = 1/Rm
          sec.Ra = rall
          sec.cm = cap
          sec.gnabar_hh2 = 0 
          sec.gkbar_hh2 = 0
          for seg in sec:
              if Tdist == 1:
                  seg.gcabar_it2 = gcat
              if Tdist == 2:
                  seg.gcabar_it2 = gcat * (1 + 0.04 * (h.distance(0) + sec.L * seg.x)) * 0.10539397661220173
              
      for sec in h.soma:
          sec.gnabar_hh2 = gna 
          sec.gkbar_hh2 = gkdr
          if Tdist == 1:
              seg.gcabar_it2 = gcat
          if Tdist == 2:
              seg.gcabar_it2 = gcat * 0.10539397661220173
                                                                           
      h.finitialize()       
      h.fcurrent()     
      cvode.re_init()
def coarse(hoc_filename,cube_length,save_filename):
	# INPUT: NEURON .hoc filename to import (str), voxel cube side length (fl/str for gcd), name of file to create for mesh output (str)
	# 		>> cube_length: 'gcd' (gcd of box dims) OR floating-point (must be common factor of all box dims)
	# This function reads in NEURON data and passes their info to
	# coarse_gen(), then associates the tets of the STEPS Tetmesh object returned
	# to the NEURON sections which exist inside of them. 
	# Returns a tet_hoc dictionary -- tet_hoc[tet_index] = [encapsulated hoc section references] -- as well as the Tetmesh object

	## GET HOC SECTION INFO ##
	h.load_file(hoc_filename)

	allp = [[],[],[]]
	for s in h.allsec():
		for j in range(int(h.n3d())):
			allp[0].append(h.x3d(j))
			allp[1].append(h.y3d(j))
			allp[2].append(h.z3d(j))

	maxl = [max(allp[0]),max(allp[1]),max(allp[2])]
	minl = [min(allp[0]),min(allp[1]),min(allp[2])]
	bdim = [ maxl[0] - minl[0], maxl[1] - minl[1], maxl[2] - minl[2] ]
	print "dims: ", bdim
	print "mins: ", minl

	## CREATE COARSE MESH ##
	if (cube_length == 'gcd'):
		gcd = fractions.gcd(fractions.gcd(bdim[0],bdim[1]),fractions.gcd(bdim[2],bdim[1]))
		print "GCD: ", gcd
		cube_length = gcd

	sm = coarse_gen(cube_length,bdim,minl,save_filename)

	## ASSOCIATE HOC SECTIONS WITH THEIR TETS ##
	tet_hoc = tet_associate(sm[0])
	return tet_hoc, sm[0]
Example #9
0
 def __init__(self):
     """Create a MorphologyDB with the current NEURON morphology"""
     self._children = {sec:[] for sec in h.allsec()}
     self._parents = {}
     self._connection_pts = {}
     for sec in h.allsec():
         parent_sec = parent(sec)
         if parent_sec is not None:
             self._children[parent_sec].append(sec)
             pt = (parent_sec, parent_loc(sec, parent))
             local_pt = (sec, h.section_orientation(sec=sec))
             if pt in self._connection_pts:
                 self._connection_pts[pt].append(local_pt)
             else:
                 self._connection_pts[pt] = [pt, local_pt]
         self._parents[sec] = parent_sec
Example #10
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
Example #11
0
 def _check_clean(self):
     """Check that all objects have been cleared from NEURON kernel.
     """
     # Release objects held by an internal buffer
     # See https://www.neuron.yale.edu/phpBB/viewtopic.php?f=2&t=3221
     h.Vector().size()    
     
     # Make sure nothing is hanging around in reference cycles 
     gc.collect()
     
     remaining = []
     
     # No sections left
     n = len(list(h.allsec()))
     if n > 0:
         remaining.append((n, 'Section'))
         
     # NetCon (and other object types?)
     for objtyp in ['NetCon']:
         n = len(h.List('NetCon'))
         if n > 0:
             remaining.append((n, 'NetCon'))
     
     # No point processes or artificial cells left
     for name, typ in Mechanism.all_mechanism_types().items():
         if typ['artificial_cell'] or typ['point_process']:
             n = len(h.List(name))
             if n > 0:
                 remaining.append((n, name))
         
     if len(remaining) > 0:
         msg = ("Cannot create new context--old objects have not been "
             "cleared: %s" % ', '.join(['%d %s' % rem for rem in remaining]))
         raise RuntimeError(msg)
Example #12
0
    def record_vectors(self, nrnManager):
        """Add a vecRef to record the vectors"""
        t_i_r = self.param['neuron_time_recording_interval']
        
        for spine_id in self.param['stimulated_spines']:
            spine = nrnManager.spines[spine_id]
            for syn in spine.synapses:
                pp = syn.chan     
                self.manager.create_time_record(time_interval_recording=t_i_r,
                                                point_process=pp)
        
        for var in self.param['var_to_plot']:
            for sec_rec in self.param['sec_to_rec']:
                if sec_rec == 'all':
                    self.manager.add_all_vecRef(var, 
                                                t_i_r)
                    break
                else:
                    for sec in h.allsec():
                        if sec.name() in self.param['sec_to_rec']:
                            self.manager.add_vecRef(var, 
                                                    sec, 
                                                    t_i_r)

        # Recording the synapses
        
        for spine_id in self.param['stimulated_spines']:
            spine = nrnManager.spines[spine_id]
            for syn in spine.synapses:
                self.manager.add_synVecRef(syn)    
Example #13
0
 def set_kir_gkbar(self, gkbar):
     """Set the conductance of kir"""
     for sec in h.allsec():
         for seg in sec:
             for mech in seg:
                 if mech.name() == 'kir':
                     mech.gkbar = gkbar
Example #14
0
 def get_var_data(self, var, time_point=0):
     """Retrieve the value of the `var` for the `time_point`.
     Prameters:
     var - variable to retrieve
     time_point - point in the simulation"""
     
     var_scalar = []
     for sec in h.allsec():
         var_value = 0
         #if self.manager.refs.has_key('VecRef'):
         #    for vecRef in self.manager.refs['VecRef']:
         #        if vecRef.sec.name() == sec.name():
         #            if vecRef.vecs.has_key(var):
         #                vec = vecRef.vecs[var]
         #                try:
         #                    var_value = vec[time_point]
         #                except IndexError:
         #                    pass # vector exist, but not initialized.
         sec_scalar = self.build_sec_scalar(sec, var_value)
         var_scalar.extend(sec_scalar)
             
                 
                     
     
     if len(var_scalar) == 0:
         logger.debug( "Var scalar 0 length. Var: %s point_time: %s" %(var, 
                                                               time_point))
     return np.array(var_scalar)
Example #15
0
def passive_soma(quad, show=False):
  """
  Creates the model with basic pyramidal passive properties.
  """
  # Load the hoc into neuron
  h('xopen(%s)' %quad.hocfile)
  h.load_file('stdrun.hoc')
  seclist = list(h.allsec())
  for sec in seclist:
    sec.insert('pas')
    sec.Ra = 200.
  
  # Current injection into soma or tip
  soma_sec = return_soma_seg(quad, h)
  stim_loc = 0.
  stim = h.IClamp(stim_loc, sec=soma_sec)
  stim.delay = 1 # ms
  stim.dur = 1 # ms
  stim.amp = 20 # nA
  
  # Run sim and record data
  (v, labels) = ez_record(h) # PyNeuron to record all compartments
  t, I = h.Vector(), h.Vector()
  t.record(h._ref_t)
  I.record(stim._ref_i)
  h.init()
  h.tstop = 10 # s?
  h.run()
  v = ez_convert(v) # Convert v to numpy 2D array
  
  # If show, plot, else just return v
  if show:
Example #16
0
 def launch_visio(self):
     msg = "Plotting..."
     self.ui.statusbar.showMessage(msg, 3500)
     if self.visio == None:
         
         # Checking there are sections in the model.
         i = 0
         for sec in h.allsec():
             i += 1
         
         if i > 0:
             self.visio = Visio(self.ui.sec_info_label, self.manager)
             self.visio.draw_model()
             self.ui.selected_section.setEnabled(True)
         else:
             msg = """No model found, no section created. You need 
             to have at least one."""
             logger.warning(msg)
     else:
         #Raise the visio window
         self.visio.container.show()
     # Enabling the animation
     try:
         self.animation()
     except KeyError:
         # No simulation run an nothing loaded.
         # just pass
         pass
Example #17
0
 def build_subsets(self):
     '''
     NEURON staff
     adds sections in NEURON SectionList
     '''
     self.all = h.SectionList()
     for sec in h.allsec():
       self.all.append(sec=sec)  
Example #18
0
    def _create_sectionlists(self):
            '''Create section lists for different kinds of sections'''
            #list with all sections
            self.allsecnames = []
            self.allseclist = h.SectionList()
            for sec in h.allsec():
                if sec.name().find('Ib_') >= 0:
                    self.allsecnames.append(sec.name())
                    self.allseclist.append(sec=sec)

            #list of soma sections, assuming it is named on the format "soma*"
            self.nsomasec = 0
            self.somalist = h.SectionList()
            for sec in h.allsec():
                if sec.name().find('Ib_soma') >= 0:
                    self.somalist.append(sec=sec)
                    self.nsomasec += 1
 def initialise(self, vrest=-65):
     """
     Initialise the model, to launch before each simulations
     """
     for sec in h.allsec():
         h.finitialize(vrest, sec)
         h.fcurrent(sec)
     h.frecord_init()
Example #20
0
    def insert_active_mech(self):
        ##### fast sodium and delayed rectifier potassium in all sections
        for sec in h.allsec():
            sec.insert('hh2')
            sec.ek = -90
            sec.ena = 50
            sec.vtraub_hh2 = -55
            sec.gnabar_hh2 = 0.05
            sec.gkbar_hh2 = 0.005

	##### SOMA
        for sec in self.soma:
            sec.insert('im')
            h.taumax_im = 1000
            sec.gkbar_im = 1e-3
            sec.insert('cad')
            sec.depth_cad = 1
            sec.taur_cad = 5
            sec.cainf_cad = 2.4e-4
            sec.kt_cad = 0
            sec.insert('it')
            sec.cai = 2.4e-4
            sec.cao = 2
            sec.eca = 120
            sec.gcabar_it = 0.002
            sec.insert('ical')
            sec.gcabar_ical = 1e-4
            sec.insert('KahpM95')
            sec.gbar_KahpM95 = 0.03
            sec.insert('kd')
            sec.gkdbar_kd = 1e-8
            sec.insert('napinst')
            sec.gbar_napinst = 1e-8

	##### DENDRITES
	for section in it.chain(self.basal,self.apical):
            section.insert('cad')
            section.depth_cad = 1
            section.taur_cad = 5
            section.cainf_cad = 2.4e-4
            section.kt_cad = 0
            section.cai = 2.4e-4
            section.cao = 2
            section.eca = 120
            section.insert('it')
            section.gcabar_it = 0.002
            section.insert('ical')
            section.gcabar_ical = 1e-4
            section.insert('KahpM95')
            section.gbar_KahpM95 = 0.02
            section.insert('kd')
            section.gkdbar_kd = 1e-8

        ##### AXON
        for section,distance in zip(self.axon,self.axon_length):
            if distance < 10: # AIS
                section.gnabar_hh2 = 0.25
Example #21
0
def set_vec_v(rec_sec_name, pc=0):
    vec_v = 0
    for sec in h.allsec():
        if(sec.name() == rec_sec_name):
            print "Record Compartment = %s in #%d" % (rec_sec_name, pc.id())
            vec_v = h.Vector()
            vec_v.record(sec(0.5)._ref_v)
    
    return(vec_v)
Example #22
0
    def run_individual(self,sim_var,show=False):
        """
        Run an individual simulation.

        The candidate data has been flattened into the sim_var dict. The
        sim_var dict contains parameter:value key value pairs, which are
        applied to the model before it is simulated.

        The simulation itself is carried out via the instantiation of a
        Simulation object (see Simulation class above).

        """

        #make compartments and connect them
        soma=h.Section()
        axon=h.Section()
        soma.connect(axon)
    
        axon.insert('na')
        axon.insert('kv')
        axon.insert('kv_3')
        soma.insert('na')
        soma.insert('kv')
        soma.insert('kv_3')
    
        soma.diam=10
        soma.L=10
        axon.diam=2
        axon.L=100
    
        #soma.insert('canrgc')
        #soma.insert('cad2')
    
        self.set_section_mechanism(axon,'na','gbar',sim_var['axon_gbar_na'])
        self.set_section_mechanism(axon,'kv','gbar',sim_var['axon_gbar_kv'])
        self.set_section_mechanism(axon,'kv_3','gbar',sim_var['axon_gbar_kv3'])
        self.set_section_mechanism(soma,'na','gbar',sim_var['soma_gbar_na'])
        self.set_section_mechanism(soma,'kv','gbar',sim_var['soma_gbar_kv'])
        self.set_section_mechanism(soma,'kv_3','gbar',sim_var['soma_gbar_kv3'])
    
        for sec in h.allsec():
            sec.insert('pas')
            sec.Ra=300
            sec.cm=0.75
            self.set_section_mechanism(sec,'pas','g',1.0/30000)
            self.set_section_mechanism(sec,'pas','e',-70)
    
        h.vshift_na=-5.0
        sim=Simulation(soma,sim_time=1000,v_init=-70.0)
        sim.set_IClamp(150, 0.1, 750)
        sim.go()

        if show:
            sim.show()
    
        return np.array(sim.rec_t), np.array(sim.rec_v)
Example #23
0
def set_iclamp(stim_sec_name, pc=0):
    stim = 0
    for sec in h.allsec():
        if(sec.name() == stim_sec_name):
            print "Stim Compartment = %s in #%d" % (stim_sec_name, pc.id())
            stim = h.IClamp(0.5, sec=sec)
            stim.amp = 1.0
            stim.delay = 100.0
            stim.dur = 200.0
    return(stim)
Example #24
0
 def _do_rangevar_update(self):
     rangevars = rangevars_present(list(h.allsec()))
     if len(rangevars) != len(self._rangevars) or any(r1 != r2 for r1, r2 in zip(rangevars, self._rangevars)):
         self._rangevars = rangevars
         self._rangevars_control.options = [r['name'] for r in rangevars]
         for i, rv in enumerate(rangevars):
             if rv['name'] == self._old_selection:
                 self._rangevars_control.index = i
                 break
         self._force_redraw = True
Example #25
0
 def create_vectors(self):
     "Vectors to store the resutls"
     for sec in h.allsec():
         for var in self.param['var_to_plot']:
             vec = self.manager.create_record_vector(sec, var, None)
             sec_name = sec.name()
             if self.vecs.has_key(sec_name):
                 self.vecs[sec_name].append(vec)
             else:
                 self.vecs[sec_name] = [vec]
Example #26
0
def shapeplot(h,ax,sections=None,order='pre',cvals=None,\
              clim=None,cmap=cm.YlOrBr_r,**kwargs):
    """
    Plots a 3D shapeplot

    Args:
        h = hocObject to interface with neuron
        ax = matplotlib axis for plotting
        sections = list of h.Section() objects to be plotted
        order = { None= use h.allsec() to get sections
                  'pre'= pre-order traversal of morphology }
        cvals = list/array with values mapped to color by cmap; useful
                for displaying voltage, calcium or some other state
                variable across the shapeplot.
        **kwargs passes on to matplotlib (e.g. color='r' for red lines)

    Returns:
        lines = list of line objects making up shapeplot
    """
    
    # Default is to plot all sections. 
    if sections is None:
        if order == 'pre':
            sections = allsec_preorder(h) # Get sections in "pre-order"
        else:
            sections = list(h.allsec())
    
    # Determine color limits
    if cvals is not None and clim is None:
        cn = [ isinstance(cv, numbers.Number) for cv in cvals ]
        if any(cn): 
            clim = [np.min(cvals[cn]), np.max(cvals[cn])]

    # Plot each segement as a line
    lines = []
    i = 0
    for sec in sections:
        xyz = get_section_path(h,sec)
        seg_paths = interpolate_jagged(xyz,sec.nseg)

        for (j,path) in enumerate(seg_paths):
            line, = plt.plot(path[:,0], path[:,1], path[:,2], '-k',**kwargs)
            if cvals is not None:
                if isinstance(cvals[i], numbers.Number):
                    # map number to colormap
                    col = cmap(int((cvals[i]-clim[0])*255/(clim[1]-clim[0])))
                else:
                    # use input directly. E.g. if user specified color with a string.
                    col = cvals[i]
                line.set_color(col)
            lines.append(line)
            i += 1

    return lines
Example #27
0
def root_sections(h):
    """
    Returns a list of all sections that have no parent.
    """
    roots = []
    for section in h.allsec():
        sref = h.SectionRef(sec=section)
        # has_parent returns a float... cast to bool
        if sref.has_parent() < 0.9:
            roots.append(section)
    return roots
Example #28
0
def leaf_sections(h):
    """
    Returns a list of all sections that have no children.
    """
    leaves = []
    for section in h.allsec():
        sref = h.SectionRef(sec=section)
        # nchild returns a float... cast to bool
        if sref.nchild() < 0.9:
            leaves.append(section)
    return leaves
Example #29
0
    def multisplit(self):
        start = h.startsw()
        self.complexity = h.multisplit()
        self.pc.multisplit()
        self.pc.set_maxstep(10)

        self.num_compartment = 0
        for sec in h.allsec():
            self.num_compartment += 1

        self.setup_time += h.startsw() - start
Example #30
0
def load_3dcell(filename, max_compartment_size=20):

    dendritic = h.SectionList()

    for sec in h.allsec():
        del sec #is this correct?
      
    h.xopen(filename)
    h('access soma')
    
    #make sure no compartments exceed 50 uM length
    for sec in h.allsec():
        diam_save = sec.diam #sec.diam makes no sense does it since diam is a segment property
        n = sec.L / max_compartment_size 
        n_truncated = int(n)#use a truncating division to avoid error
        sec.nseg = n_truncated + 1 
        if h.n3d() == 0:
            sec.diam = diam_save
        dendritic.append()
        
    return dendritic
Example #31
0
caDiff = 0.016
#caDiff =0
ip3Diff = 0.283
#ip3Diff = 0
cac_init = 1.e-4
ip3_init = 0.1
gip3r = 12040
gserca = 0.3913
gleak = 6.020
kserca = 0.1
kip3 = 0.15
kact = 0.4
ip3rtau = 2000

# define the regions for the rxd
cyt = rxd.Region(h.allsec(), nrn_region='i', geometry=rxd.FractionalVolume(fc, surface_fraction=1))
er = rxd.Region(h.allsec(), geometry=rxd.FractionalVolume(fe))
cyt_er_membrane = rxd.Region(h.allsec(), geometry=rxd.FixedPerimeter(1))

# the species and other states
ca = rxd.Species([cyt, er], d=caDiff, name='ca', charge=2, initial=cac_init)
ip3 = rxd.Species(cyt, d=ip3Diff, initial=ip3_init)
ip3r_gate_state = rxd.State(cyt_er_membrane, initial=0.8)
h_gate = ip3r_gate_state[cyt_er_membrane]


# pumps and channels between ER and Cytosol

serca = rxd.MultiCompartmentReaction(ca[cyt]>ca[er], gserca/((kserca / (1000. * ca[cyt])) ** 2 + 1), membrane=cyt_er_membrane, custom_dynamics=True)
leak = rxd.MultiCompartmentReaction(ca[er]!=ca[cyt], gleak, gleak, membrane=cyt_er_membrane)
Example #32
0
from mpl_toolkits import mplot3d
import platform
import neuron as nrn

#load cell as mycell
#    def getmorph(self):
myCell = morphology.Cell()
morphology.load(filename=os.path.join(wdir, 'MN_morphology.swc'), cell=myCell)

#plot loaded cell
fig = plt.figure()
ax = plt.axes(projection='3d')
morphology.shapeplot(h, ax)

#get the sections from the cell
secs = list(h.allsec())
secs_all = secs
soma = []
axon = []
#dend = []

#get the sections fro soma, axon and dend
#def getset(self):
for sec in secs:
    name = sec.name()
    if name[0:4] == 'soma':
        soma.append(sec)
    if name[0:4] == 'axon':
        axon.append(sec)
    #if name[0:4] == 'dend':
    #dend.append(sec)
Example #33
0
def stick_and_ball(Ra=100.,
                   gpas=0.0001,
                   cm=1.,
                   Ra_max=250.,
                   dt=0.1,
                   stype='both',
                   custom_stim=None):
    """ Stick and Ball model variables: Passive conductance and axial resistance """
    # Create Sections
    soma = h.Section(name='soma')
    dend = h.Section(name='dend')

    # Topology
    dend.connect(soma(1))

    # Geometry
    soma.L = soma.diam = 30
    dend.L = 1000
    dend.diam = 3

    # Simulation duration and RUN
    h.dt = dt  # Time step (iteration)
    h.steps_per_ms = 1 / dt

    # Set the appropriate "nseg"
    for sec in h.allsec():
        sec.Ra = Ra_max
    h('forall {nseg = int((L/(0.1*lambda_f(100))+.9)/2)*2 + 1}'
      )  # If Ra_max = 105 dend.nseg = 21 and soma.nseg = 1

    # -- Biophysics --
    # Sec parameters and conductance
    for sec in h.allsec():
        sec.Ra = Ra  # Ra is a parameter to infer
        sec.cm = cm
        sec.v = -65

        sec.insert('pas')
        sec.g_pas = gpas  # gpas is a parameter to infer
        sec.e_pas = -65

    # Stimulus
    # Here we define three kind of experimental protocol:
    # 1.) brad electrode current
    # 2.) narrow electrode current
    # 3.) both
    if stype == 'broad':
        h.tstop = 300
        stim = h.IClamp(soma(0.5))
        stim.delay = 20
        stim.amp = 0.1
        stim.dur = 175
    elif stype == 'narrow':
        h.tstop = 100
        stim = h.IClamp(soma(0.5))
        stim.delay = 10
        stim.amp = 0.5
        stim.dur = 5
    elif stype == 'both':
        h.tstop = 400
        stim1 = h.IClamp(soma(0.5))
        stim1.delay = 10
        stim1.amp = 0.5
        stim1.dur = 5

        stim2 = h.IClamp(soma(0.5))
        stim2.delay = 120
        stim2.amp = 0.1
        stim2.dur = 175
    elif stype == 'steps':
        h.tstop = 500
        stim1 = h.IClamp(soma(0.5))
        stim1.delay = 10
        stim1.amp = 0.5
        stim1.dur = 5

        stim2 = h.IClamp(soma(0.5))
        stim2.delay = 120
        stim2.amp = 0.1
        stim2.dur = 175

        stim3 = h.IClamp(soma(0.5))
        stim3.delay = 400
        stim3.amp = 0.35
        stim3.dur = 5
    elif stype == 'custom':
        h.tstop = len(custom_stim) * dt
        h.load_file("vplay.hoc")
        vec = h.Vector(custom_stim)
        istim = h.IClamp(soma(0.5))
        vec.play(istim._ref_amp, h.dt)
        istim.delay = 0  # Just for Neuron
        istim.dur = 1e9  # Just for Neuron

    # Run simulation ->
    # Print information
    # h.psection()

    # Set up recording Vectors
    v_vec = h.Vector()
    t_vec = h.Vector()
    v_vec.record(soma(0.5)._ref_v)
    t_vec.record(h._ref_t)

    h.v_init = -65
    h.finitialize(h.v_init)  # Starting membrane potential

    h.init()
    h.run()

    t = t_vec.to_python()
    v = v_vec.to_python()

    return np.array(t), np.array(v)
Example #34
0
 def add_biophys_all(self):
     for sec in h.allsec():
         sec.Ra = 100  # Axial resistance in Ohm * cm
         sec.cm = 0.01  # Membrane capacitance in micro Farads / cm^2
Example #35
0
def nrn_assert_no_sections():
    for s in h.allsec():
        assert False, 'a section exists'
gip3r = 12040
gserca = 0.3913
gleak = 6.020
kserca = 0.1
kip3 = 0.15
kact = 0.4
ip3rtau = 2000.0

#These parameters where missing in the tutorial so arbitrary values were chosen
#any resemblance to experimental values is purely coincidental.
fc = 0.7
fe = 0.3
caCYT_init=0.1 


cyt = rxd.Region(h.allsec(), name='cyt', nrn_region='i', geometry=rxd.FractionalVolume(fc,surface_fraction=1))

er= rxd.Region(h.allsec(), name='er', geometry=rxd.FractionalVolume(fe/2.))

cyt_er_membrane = rxd.Region(h.allsec(), name='mem', geometry = rxd.ScalableBorder(1, on_cell_surface=False))

ca  = rxd.Species([cyt, er], d=caDiff, name="ca", charge=2, initial=caCYT_init)


ip3 = rxd.Species(cyt, d=ip3Diff, name="ip3", initial=ip3_init)
ip3r_gate_state = rxd.Species(cyt_er_membrane, name="gate", initial=0.8)
h_gate = ip3r_gate_state[cyt_er_membrane]

serca = rxd.MultiCompartmentReaction(ca[cyt],ca[er], gserca/((kserca / (1000. * ca[cyt])) ** 2 + 1), membrane=cyt_er_membrane, custom_dynamics=True)
leak = rxd.MultiCompartmentReaction(ca[cyt],ca[er], gleak, gleak, membrane=cyt_er_membrane)
def main(par="./params-msn.json", \
                            sim='vm',       \
                            amp=0.265,      \
                            run=None,       \
                            modulation=1,   \
                            simDur=7000,    \
                            stimDur=900,    \
                            factors=None,   \
                            section=None,   \
                            randMod=None,   \
                            chan2mod=['naf', 'kas', 'kaf', 'kir', 'cal12', 'cal13', 'can'] ):

    # initiate cell
    cell = MSN(params=par, factors=factors)

    # set cascade ---- move to MSN def?
    casc = h.D1_reduced_cascade2_0(
        0.5, sec=cell.soma)  # other cascades also possible...

    pointer = casc._ref_Target1p  #totalActivePKA    (if full cascade used)

    # set edge of soma as reference for distance
    h.distance(1, sec=h.soma[0])

    # set current injection
    stim = h.IClamp(0.5, sec=cell.soma)
    stim.amp = amp
    stim.delay = 100
    stim.dur = stimDur  # 2ms 2nA to elicit single AP, following Day et al 2008 Ca dyn

    # record vectors
    tm = h.Vector()
    tm.record(h._ref_t)
    vm = h.Vector()
    vm.record(cell.soma(0.5)._ref_v)

    pka = h.Vector()
    pka.record(pointer)

    # peak n dipp parameters
    da_peak = 1500  # concentration [nM]
    da_tstart = 500  # stimulation time [ms]
    da_tau = 500  # time constant [ms]

    tstop = simDur  # [ms]

    # all channels to modulate
    mod_list = ['naf', 'kas', 'kaf', 'kir', 'cal12', 'cal13', 'can']

    not2mod = []  #['kaf']

    # find channels that should not be modulated
    for chan in mod_list:

        if chan not in chan2mod:

            not2mod.append(chan)

    # calc modulation factors--------------------------------------------------------------
    base_mod = casc.init_Target1p

    # for random modulation: modValues = np.arange(0.1, 2.0, 0.1)
    if randMod == 1:

        if amp == 0.32:

            mod_fact = calc_rand_Modulation(mod_list, range_list=[[0.60,0.80],    \
                                                                  [0.65,0.85],  \
                                                                  [0.75,0.85],  \
                                                                  [0.85,1.25],  \
                                                                  [1.0,2.0],    \
                                                                  [1.0,2.0],    \
                                                                  [0.0,1.0]],
                                                                  distribution='uniform'  )

        else:

            mod_fact = RES[run]['factors']

    else:
        mod_fact = [0.8, 0.8, 0.8, 1.25, 2.0, 2.0, 0.5]

    factors = []
    for i, mech in enumerate(mod_list):

        # normalization of factors to substrate range. Only for dynamical mod?
        factor = (mod_fact[i] - 1) / (2317.1 - base_mod)  #2317.1

        factors.append(factor)

        #print(mech, mod_fact[i], factor) # --------------------------------------------------------

    # set pointers
    for sec in h.allsec():

        for seg in sec:

            # naf and kas is in all sections
            h.setpointer(pointer, 'pka', seg.kas)
            h.setpointer(pointer, 'pka', seg.naf)

            if sec.name().find('axon') < 0:

                # these channels are not in the axon section

                h.setpointer(pointer, 'pka', seg.kaf)
                h.setpointer(pointer, 'pka', seg.cal12)
                h.setpointer(pointer, 'pka', seg.cal13)
                h.setpointer(pointer, 'pka', seg.kir)
                #h.setpointer(pointerc, 'pka', seg.car )

                if sec.name().find('soma') >= 0:

                    # can is only distributed to the soma section
                    h.setpointer(pointer, 'pka', seg.can)

    # dynamical modulation ---------------------------------------------------------------
    if sim == 'modulation':

        print('inne ', sim)

        for sec in h.allsec():

            for seg in sec:

                for mech in seg:

                    # if this first statement is active the axon will not be modulated
                    '''if sec.name().find('axon') >= 0     \
                            and mech.name() in mod_list:
                            
                        mech.factor = 0.0
                        print(sec.name(), seg.x, mech.name() )'''

                    if mech.name() in not2mod:

                        mech.factor = 0.0
                        print(mech.name(), 'and channel:', not2mod,
                              mech.factor, sec.name())

                    elif mech.name() in mod_list:

                        mech.base = base_mod
                        index = mod_list.index(mech.name())
                        mech.factor = factors[index]

    # static modulation
    elif sim == 'directMod':

        #print('inne ', sim)

        for sec in h.allsec():

            for seg in sec:

                for mech in seg:

                    if mech.name() in mod_list:

                        if sec.name().find(
                                'axon'
                        ) < 0:  # if 0: no axon modulated; if 10: all sections modulated

                            factor = mod_fact[mod_list.index(mech.name())]

                            if mech.name() in not2mod:
                                mech.factor = 0.0
                            elif mech.name()[0] == 'c':
                                pbar = mech.pbar
                                mech.pbar = pbar * factor
                                #print(''.join(['setting pbar ', mech.name(), ' ', str(factor) ]) )
                            else:
                                gbar = mech.gbar
                                mech.gbar = gbar * factor
                                #if seg.x < 0.2:
                                #print(''.join(['setting gbar ', mech.name(), ' ', str(factor), ' ', str(gbar), ' ', str(factor*gbar) ]) )

                        else:

                            print(sec.name(), seg.x, sec.name().find('axon'))

    # set ampa and nmda epsp's--what compartments to use?
    elif sim == 'plateau':

        print('inne ', sim)

        dend_name = 'dend[' + str(int(section)) + ']'

        for sec in h.allsec():

            if sec.name() == dend_name:

                x = 0.5

                ampa = h.ampa(x, sec=sec)
                ampa.onset = 100
                ampa.gmax = 5e-3
                #h.setpointer(pointer, 'pka', seg.kaf )

                nmda = h.nmda(x, sec=sec)
                nmda.onset = 100
                nmda.gmax = 10e-2
                #h.setpointer(pointer, 'pka', seg.kaf )

                vmL = h.Vector()
                vmL.record(sec(x)._ref_v)

                d2soma = int(h.distance(x, sec=sec))

                #print(sec.name(), h.distance(seg.x, sec=sec))

    # record Ca dynamics!
    elif sim == 'ca':

        print('inne ', sim)

        for i, sec in enumerate(h.allsec()):

            if sec.name().find('axon') < 0:  # don't record in axon

                for j, seg in enumerate(sec):

                    sName = sec.name().split('[')[0]

                    # N, P/Q, R Ca pool
                    cmd = 'ca_%s%s_%s = h.Vector()' % (sName, str(i), str(j))
                    exec(cmd)

                    cmd = 'ca_%s%s_%s.record(seg._ref_cai)' % (sName, str(i),
                                                               str(j))
                    exec(cmd)

                    # the L-type Ca
                    cmd = 'cal_%s%s_%s = h.Vector()' % (sName, str(i), str(j))
                    exec(cmd)

                    cmd = 'cal_%s%s_%s.record(seg._ref_cali)' % (sName, str(i),
                                                                 str(j))
                    exec(cmd)

                    # uncomment here if testing kaf blocking effect on bAP
                    #gbar = seg.kaf.gbar
                    #seg.kaf.gbar = 0.8 * gbar

    # solver------------------------------------------------------------------------------
    cvode = h.CVode()

    h.finitialize(cell.v_init)

    # run simulation
    while h.t < tstop:

        if modulation == 1:

            if h.t > da_tstart:

                # set DA and ACh values (using alpha function)
                casc.DA = alpha(da_tstart, da_peak, da_tau)
                #casc.ACh = ach_base - alpha(ach_tstart, ach_base, ach_tau)

        h.fadvance()

    # save output
    if sim in ['vm', 'directMod', 'modulation']:
        '''s = ''
        for chan in not2mod:
            s = chan + s'''

        save_vector(tm, vm,
                    ''.join(['./vm_', sim, '_',
                             str(int(amp * 1e3)), '.out']))
        '''
        spikes      = getSpikedata_x_y(tm,vm) 
        amp         = int(amp*1e3) 
        
        
        if amp == 320:
            
            RES[run]                = {}
            RES[run]['factors']     = mod_fact
            
            if run == 0:
            
                RES['channels'] = mod_list
        
        RES[run][amp]   = {'spikes': spikes}'''

    elif sim == 'plateau':

        save_vector(
            tm, vm, ''.join([
                './vm_', sim,
                str(d2soma), '_dend',
                str(int(section)), '.out'
            ]))
        save_vector(
            tm, vmL, ''.join([
                './vmL_', sim,
                str(d2soma), '_dend',
                str(int(section)), '.out'
            ]))

    elif sim == 'ca':

        # vm
        save_vector(tm, vm,
                    ''.join(['./vm_', sim, '_',
                             str(int(amp * 1e3)), '.out']))

        # Ca
        for i, sec in enumerate(h.allsec()):

            if sec.name().find('axon') < 0:

                for j, seg in enumerate(sec):

                    sName = sec.name().split('[')[0]

                    vName = 'ca_%s%s_%s' % (sName, str(i), str(j))
                    v2Name = 'cal_%s%s_%s' % (sName, str(i), str(j))
                    fName = 'Ca/Org/ca_%s_%s.out' % (str(
                        int(np.round(h.distance(seg.x)))), vName)

                    cmd = 'save_vector(tm, np.add(%s, %s), %s)' % (
                        vName, v2Name, 'fName')

                    exec(cmd)
Example #38
0
from neuron import h, gui
h.load_file('ri04_figs6-7_run.hoc')
import numpy as np
for sec in h.allsec():
    gbar = np.pi * sec.gbar_h * sec.L * sec.diam * 1e-12
    print sec.name(), gbar
Example #39
0
def get_all_sections(sec_type='Pyr'):
    ls = h.allsec()
    ls = [s for s in ls if sec_type in s.name()]
    return ls
from neuron import h, rxd

h.load_file("stdrun.hoc")
h.CVode().active(True)

sec = h.Section(name="sec")
sec.L = 10
sec.nseg = 11
sec.diam = 5
rxd.set_solve_type(dimension=3)

cyt = rxd.Region(h.allsec(), name="cyt", nrn_region="i")
ip3 = rxd.Species(cyt,
                  name="ip3",
                  initial=lambda nd: 1000 if nd.segment == sec(0.3) else 0)


def callbackfun():
    return 1000


for nd in ip3.nodes(sec(0.1)):
    nd.include_flux(1000)

for nd in ip3.nodes(sec(0.5)):
    nd.include_flux(callbackfun)

for nd in ip3.nodes(sec(0.9)):
    nd.include_flux(sec(0.3)._ref_ip3i)

h.finitialize(-70)
Example #41
0
caDiff = 0.016
#caDiff =0
ip3Diff = 0.283
#ip3Diff = 0
cac_init = 1.e-4
ip3_init = 0.1
gip3r = 12040
gserca = 0.3913
gleak = 6.020
kserca = 0.1
kip3 = 0.15
kact = 0.4
ip3rtau = 2000

# define the regions for the rxd
cyt = rxd.Region(h.allsec(),
                 nrn_region='i',
                 geometry=rxd.FractionalVolume(fc, surface_fraction=1))
er = rxd.Region(h.allsec(), geometry=rxd.FractionalVolume(fe))
cyt_er_membrane = rxd.Region(h.allsec(), geometry=rxd.FixedPerimeter(1))

# the species and other states
ca = rxd.Species([cyt, er], d=caDiff, name='ca', charge=2, initial=cac_init)
ip3 = rxd.Species(cyt, d=ip3Diff, initial=ip3_init)
ip3r_gate_state = rxd.State(cyt_er_membrane, initial=0.8)
h_gate = ip3r_gate_state[cyt_er_membrane]

# pumps and channels between ER and Cytosol

serca = rxd.MultiCompartmentReaction(ca[cyt] > ca[er],
                                     gserca / ((kserca /
Example #42
0
from neuron import h, rxd
import numpy
from matplotlib import pyplot
import time

# needed for standard run system
h.load_file('stdrun.hoc')

dend = h.Section()
dend.nseg = 501

# WHERE the dynamics will take place
where = rxd.Region(h.allsec())

# WHO the actors are
u = rxd.Species(where, d=1, initial=0)

# HOW they act
bistable_reaction = rxd.Rate(u, -u * (1 - u) * (0.3 - u))

# initial conditions
h.finitialize()
for node in u.nodes:
    if node.x < .2: node.concentration = 1

def plot_it(color='k'):
    y = u.nodes.concentration
    x = u.nodes.x

    # convert x from normalized position to microns
    x = dend.L * numpy.array(x)
    'soma_re0': ['[0].soma_re'],
    'dend_re_receiver': ['REcell[1].dend_re3[16]', 'REcell[2].dend_re3[16]']
    #	'dend_receiver2': ['REcell[2].dend_re4', 'REcell[2]']
}
reticular = {
    'soma_re': ['[0].soma_re'],
    #	'proximal_re':['REcell[0].dend_re1[2]', 'REcell[0].dend_re2[2]', '[0].soma_re'],
    'proximal_re': ['[0].soma_re'],
    'distal_re': ['[1].dend_re4[2]', '[2].dend_re4[2]']
}
#print 'proximal_re =', reticular['proximal_re']
########################################################################
###### create a list contains proximal_re dendrites of reticular cell
proximal_re = []
proximalname_re = []
for prox_re in h.allsec(
):  # print prox_re.name() # gives out REcell[0].soma_re......
    if any(s in prox_re.name() for s in reticular['proximal_re']):
        proximal_re.append(prox_re)
        proximalname_re.append(prox_re.name())
print "PROXI_NAME", proximalname_re
selprox_re = random.sample(proximal_re, 1)
selproxname_re = random.sample(proximalname_re, 1)

#print 's.sec: ', proximal_re, '\n'
print 's.name: ', proximalname_re, '\n'
print 'proximal_re dendrites:', selprox_re, '\n', selproxname_re
print '------------------------------------------------------'
###### create a list contains distal_re dendrites of reticular cell
distal_re = []
distalname_re = []
for dist_re in h.allsec():
def main(par="./params-msn.json", \
                            sim='vm',       \
                            amp=0.265,      \
                            run=None,       \
                            modulation=1,   \
                            simDur=7000,    \
                            stimDur=900,    \
                            factors=None,   \
                            section=None,   \
                            randMod=None,   \
                            testMode=False, \
                            target=None,    \
                            chan2mod=['naf', 'kas', 'kaf', 'kir', 'cal12', 'cal13', 'can'] ):

    print(locals())

    # initiate cell
    cell = MSN(params=par, factors=factors)

    # set cascade ---- move to MSN def?
    casc = h.D1_reduced_cascade2_0(
        0.5, sec=cell.soma)  # other cascades also possible...

    if target:
        cmd = 'pointer = casc._ref_' + target
        exec(cmd)

        base_mod = SUBSTRATES[target][0]
        max_mod = SUBSTRATES[target][1]

    else:
        pointer = casc._ref_Target1p  #Target1p   #totalActivePKA    (if full cascade used)
        base_mod = casc.init_Target1p
        max_mod = 2317.1

    # cAMP; init: 38.186016

    # set edge of soma as reference for distance
    h.distance(1, sec=h.soma[0])

    # set current injection
    stim = h.IClamp(0.5, sec=cell.soma)
    stim.amp = amp
    stim.delay = 100
    stim.dur = stimDur  # 2ms 2nA to elicit single AP, following Day et al 2008 Ca dyn

    # record vectors
    tm = h.Vector()
    tm.record(h._ref_t)
    vm = h.Vector()
    vm.record(cell.soma(0.5)._ref_v)

    # substrates
    pka = h.Vector()
    pka.record(casc._ref_Target1p)
    camp = h.Vector()
    camp.record(casc._ref_cAMP)
    gprot = h.Vector()
    gprot.record(casc._ref_D1RDAGolf)  #D1RDAGolf
    gbg = h.Vector()
    gbg.record(casc._ref_Gbgolf)  #Gbgolf

    # peak n dipp parameters
    da_peak = 500  # concentration [nM]
    da_tstart = 1000  # stimulation time [ms]
    da_tau = 500  # time constant [ms]

    tstop = simDur  # [ms]

    # all channels to modulate
    mod_list = ['naf', 'kas', 'kaf', 'kir', 'cal12', 'cal13', 'can']

    not2mod = []  #['kaf']

    # find channels that should not be modulated
    for chan in mod_list:

        if chan not in chan2mod:

            not2mod.append(chan)

    # for random modulation: modValues = np.arange(0.1, 2.0, 0.1) -------------------------
    if randMod == 1:

        # new factors every run
        mod_fact = calc_rand_Modulation(mod_list, range_list=[[0.60,0.80],    \
                                                              [0.65,0.85],  \
                                                              [0.75,0.85],  \
                                                              [0.85,1.25],  \
                                                              [1.0,2.0],    \
                                                              [1.0,2.0],    \
                                                              [0.0,1.0]],
                                                              distribution='uniform'  )

        # keep old factors
        '''
        if run == 0:
        
            mod_fact = calc_rand_Modulation(mod_list)
            
        else:
            
            mod_fact = RES['factors']
        '''

    else:
        mod_fact = [0.8, 0.8, 0.8, 1.25, 2.0, 2.0, 0.5]

    # noormalize factors to  target values seen in simulation
    factors = []
    for i, mech in enumerate(mod_list):

        factor = (mod_fact[i] - 1) / (max_mod - base_mod)  #2317.1

        factors.append(factor)

        #print(mech, mod_fact[i], factor) # --------------------------------------------------------

    # set pointers
    for sec in h.allsec():

        for seg in sec:

            # naf and kas is in all sections
            h.setpointer(pointer, 'pka', seg.kas)
            h.setpointer(pointer, 'pka', seg.naf)

            if sec.name().find('axon') < 0:

                # these channels are not in the axon section

                h.setpointer(pointer, 'pka', seg.kaf)
                h.setpointer(pointer, 'pka', seg.cal12)
                h.setpointer(pointer, 'pka', seg.cal13)
                h.setpointer(pointer, 'pka', seg.kir)
                #h.setpointer(pointerc, 'pka', seg.car )

                if sec.name().find('soma') >= 0:

                    # can is only distributed to the soma section
                    h.setpointer(pointer, 'pka', seg.can)

    # synaptic modulation ================================================================
    if sim == 'synMod':

        # draw random modulation factors (intervals given by range_list[[min,max]]
        glut_f, glut_f_norm     = set_rand_synapse(['amp', 'nmd'], base_mod, max_mod,   \
                                                    range_list=[[0.9,1.6], [0.9,1.6]]   )

        gaba_f, gaba_f_norm     = set_rand_synapse(['gab'],        base_mod, max_mod,   \
                                                    range_list=[[0.6,1.4]]              )

        syn_fact = glut_f + gaba_f

        I_d = {}

        ns = {}
        nc = {}
        Syn = {}
        for sec in h.allsec():
            if sec.name().find('dend') >= 0:

                # create a glut synapse
                make_random_synapse(ns, nc, Syn, sec, 0.5,          \
                                        NS_interval=1000.0/20.0,    \
                                        NC_conductance=0.165e-3,     \
                                        S_tau_dep=100               )

                # create a gaba synapse
                make_random_synapse(ns, nc, Syn, sec, 0.0,          \
                                        Type='tmgabaa',             \
                                        NS_interval=1000.0/5.0,     \
                                        NC_conductance=0.495e-3      )

                # set pointer(s)
                h.setpointer(pointer, 'pka', Syn[sec])
                h.setpointer(pointer, 'pka', Syn[sec.name() + '_gaba'])

                # set (random?) modulation
                Syn[sec].base = base_mod

                #randMod?
                if randMod == 1:
                    Syn[sec].f_ampa = glut_f_norm[0]
                    Syn[sec].f_nmda = glut_f_norm[1]
                else:
                    Syn[sec].f_ampa = 0
                    Syn[sec].f_nmda = 0

                if randMod == 1:
                    Syn[sec.name() + '_gaba'].base = base_mod
                    Syn[sec.name() + '_gaba'].f_gaba = gaba_f_norm[0]
                else:
                    Syn[sec.name() + '_gaba'].f_gaba = 0
                '''
                # record synaptic current from synapse

                I_d[sec.name()]             = h.Vector()

                I_d[sec.name()].record(Syn[sec]._ref_i)
                
                I_d[sec.name()+'_gaba']     = h.Vector()
                I_d[sec.name()+'_gaba'].record(Syn[sec.name()+'_gaba']._ref_i)
                '''

            elif sec.name().find('axon') >= 0:
                continue

            if randMod == 1:
                for seg in sec:

                    for mech in seg:

                        if mech.name() in not2mod:

                            mech.factor = 0.0
                            print(mech.name(), 'and channel:', not2mod,
                                  mech.factor, sec.name())

                        elif mech.name() in mod_list:

                            mech.base = base_mod
                            index = mod_list.index(mech.name())
                            mech.factor = factors[index]

    # dynamical modulation
    elif sim == 'modulation':

        print('inne ', sim)

        for sec in h.allsec():

            for seg in sec:

                for mech in seg:

                    # if this first statement is active the axon will not be modulated
                    '''if sec.name().find('axon') >= 0     \
                            and mech.name() in mod_list:
                            
                        mech.factor = 0.0
                        print(sec.name(), seg.x, mech.name() )'''

                    if mech.name() in not2mod:

                        mech.factor = 0.0
                        print(mech.name(), 'and channel:', not2mod,
                              mech.factor, sec.name())

                    elif mech.name() in mod_list:

                        mech.base = base_mod
                        index = mod_list.index(mech.name())
                        mech.factor = factors[index]

    # static modulation
    elif sim == 'directMod':

        print('inne ', sim)

        for sec in h.allsec():

            for seg in sec:

                for mech in seg:

                    if mech.name() in mod_list:

                        if sec.name().find(
                                'axon'
                        ) < 10:  # 0 no axon modulated; 10 all sections

                            factor = mod_fact[mod_list.index(mech.name())]

                            if mech.name() in not2mod:
                                mech.factor = 0.0
                            elif mech.name()[0] == 'c':
                                pbar = mech.pbar
                                mech.pbar = pbar * factor
                                #print(''.join(['setting pbar ', mech.name(), ' ', str(factor) ]) )
                            else:
                                gbar = mech.gbar
                                mech.gbar = gbar * factor
                                #if seg.x < 0.2:
                                #print(''.join(['setting gbar ', mech.name(), ' ', str(factor), ' ', str(gbar), ' ', str(factor*gbar) ]) )

                        else:

                            print(sec.name(), seg.x, sec.name().find('axon'))

    # solver------------------------------------------------------------------------------
    cvode = h.CVode()

    h.finitialize(cell.v_init)

    # run simulation
    while h.t < tstop:

        if modulation == 1:

            if h.t > da_tstart:

                # set DA and ACh values (using alpha function)
                casc.DA = alpha(da_tstart, da_peak, da_tau)
                #casc.ACh = ach_base - alpha(ach_tstart, ach_base, ach_tau)

        h.fadvance()

    # save output
    if sim in ['vm', 'directMod', 'modulation', 'synMod']:

        if testMode:

            mod_fact = mod_fact + syn_fact

            ID = ''

            for i, mech in enumerate(mod_list + syn_mod):

                ID = ID + mech + str(int(mod_fact[i] * 100))

            save_vector(tm, vm,
                        ''.join(['./spiking_',
                                 str(run), '_', ID, '.out']))
            '''
            names = ['Target1p', 'cAMP', 'Gbgolf', 'D1RDAGolf']
            data  = {}
            for i,substrate in enumerate([pka, camp, gbg, gprot]):
                save_vector(tm, substrate, './substrate_'+names[i]+'.out' )
                print(min(substrate), max(substrate))
                data[names[i]] = [min(substrate), max(substrate)] 
            
            print(ID)
            with open('substrates.json', 'w') as outfile:
                json.dump(data, outfile)'''

            #for key in I_d:

            #save_vector(tm, I_d[key], ''.join(['./I_', key, '_', str(run), '.out']) )

        spikes = getSpikedata_x_y(tm, vm)

        RES[run] = {'factors': mod_fact + syn_fact, 'spikes': spikes}
Example #45
0
sim.net.createPops()  # instantiate network populations
sim.net.createCells()  # instantiate network cells based on defined populations
sim.net.connectCells()  # create connections between cells based on params
sim.net.addStims()  # add external stimulation to cells (IClamps etc)
sim.net.addRxD(nthreads=6)  # add reaction-diffusion (RxD)

# Additional sim setup
## parallel context
pc = h.ParallelContext()
pcid = pc.id()
nhost = pc.nhost()
pc.timeout(0)
pc.set_maxstep(100)  # required when using multiple processes

random.seed(pcid + 120194)
all_secs = [sec for sec in h.allsec()]
cells_per_node = len(all_secs)
rec_inds = random.sample(range(cells_per_node), int(cfg.nRec / nhost))
rec_cells = [h.Vector().record(all_secs[ind](0.5)._ref_v) for ind in rec_inds]
pos = [[all_secs[ind].x3d(0), all_secs[ind].y3d(0), all_secs[ind].z3d(0)]
       for ind in rec_inds]
pops = [str(all_secs[ind]).split('.')[1].split('s')[0] for ind in rec_inds]

## only single core stuff
if pcid == 0:
    ### create output dir
    if not os.path.exists(cfg.filename):
        try:
            os.makedirs(cfg.filename)
        except:
            print(
Example #46
0
 def get_all_point_processes(cls):
     for sec in h.allsec():
         for pp in sec.psection()['point_processes'].values():
             for p in pp:
                 yield p
Example #47
0
from neuron import h
from mayavi import mlab
from neuron.rxd import geometry3d

[s1, s2, s3] = [h.Section() for i in xrange(3)]

for s in h.allsec():
    s.diam = 1
    s.L = 5

s2.connect(s1)
s3.connect(s1)

tri_mesh = geometry3d.surface(h.allsec())
mlab.triangular_mesh(tri_mesh.x,
                     tri_mesh.y,
                     tri_mesh.z,
                     tri_mesh.faces,
                     color=(1, 0, 0))
mlab.show()
Example #48
0
Db = 0 
Dcab = 0 

# create sections
soma = h.Section(name="soma")
dend = h.Section(name="dend")
soma.L=100
soma.diam=1
soma.nseg=101
dend.L=100
dend.diam=1
dend.nseg=101
soma.connect(dend)


r = rxd.Region(h.allsec())
Ca = rxd.Species(r, name='Ca', d=Dca)
Buf = rxd.Species(r, name='Buf', d=Db)
CaBuf = rxd.Species(r, name='CaBuf', d=Dcab)

buffering = rxd.Reaction(Ca[r] + Buf[r], CaBuf[r], kf, kb)


#
# set initial concentrations to ca0, b0, cab0 in soma, 
# and to 0.001 in dend
#
Ca.initial = lambda node: (ca0 if node.sec._sec==soma else 0.001)
Buf.initial = lambda node: (b0 if node.sec._sec==soma else 0.001)
CaBuf.initial = lambda node:(cab0 if node.sec._sec==soma else 0.001)
Example #49
0
cell1.pt3dadd(-20, 0, 0, 10)
cell1.pt3dadd(-10, 0, 0, 10)
cell1.nseg = 11
cell1.insert('pump')

# create cell2 where `x` will be pumped in and accumulate
cell2 = h.Section('cell2')
cell2.pt3dclear()
cell2.pt3dadd(10, 0, 0, 10)
cell2.pt3dadd(20, 0, 0, 10)
cell2.nseg = 11
cell2.insert('pump')

# Where?
# the intracellular spaces
cyt = rxd.Region(h.allsec(),
                 name='cyt',
                 nrn_region='i',
                 geometry=rxd.FractionalVolume(0.9, surface_fraction=1.0))

org = rxd.Region(h.allsec(), name='org', geometry=rxd.FractionalVolume(0.1))

cyt_org_membrane = rxd.Region(h.allsec(),
                              name='mem',
                              geometry=rxd.ScalableBorder(
                                  pi / 2.0, on_cell_surface=False))

# the extracellular space
ecs = rxd.Extracellular(-55,
                        -55,
                        -55,
# In[1]:

from neuron import h, rxd

h.load_file("stdrun.hoc")

# In[2]:

axon = h.Section(name="s1")
axon_terminal = h.Section(name="s")
axon.connect(axon_terminal)

axon_terminal_region = rxd.Region([axon_terminal], nrn_region="i")
synaptic_cleft = rxd.Region([axon_terminal], nrn_region="o")
terminal_membrane = rxd.Region(h.allsec(), geometry=rxd.DistributedBoundary(1))

# In[3]:

VA = rxd.Species([axon_terminal_region], name="VA", initial=10, charge=1)
T = rxd.Species([synaptic_cleft], name="T", initial=10, charge=1)

# In[4]:

# if you comment the exocytosis line below, the error will go away
exocytosis = rxd.MultiCompartmentReaction(
    VA[axon_terminal_region],
    T[synaptic_cleft],
    500,
    0,
    membrane=terminal_membrane,
Example #51
0
somaA.nseg = 1

somaB = h.Section("somaB")
somaB.pt3dclear()
somaB.pt3dadd(60, 0, 0, 30)
somaB.pt3dadd(90, 0, 0, 30)
somaB.nseg = 1

# mod version
somaB.insert("hh")

# rxd version

# Where?
# intracellular
cyt = rxd.Region(h.allsec(), name="cyt", nrn_region="i")

# membrane
mem = rxd.Region(h.allsec(), name="cell_mem", geometry=rxd.membrane())

# extracellular
ecs = rxd.Extracellular(-100, -100, -100, 100, 100, 100, dx=33)


# Who?
def init(ics, ecs):
    return lambda nd: ecs if isinstance(nd, rxd.node.NodeExtracellular
                                        ) else ics


# ions
Example #52
0
def saveVs():
    all_v = []
    for sec in h.allsec():
        for seg in sec.allseg():
            all_v.append(seg.v)
    numpy.save(os.path.join(outdir, 'pcid' + str(pcid) + '_allv.npy'), all_v)
Example #53
0
            h.dend[int(tar[5:-1])](.5).v = 35
        elif tar[:4] == 'soma':
            soma_col = 'cyan'
        elif tar[:4] == 'axon':
            h.axon[int(tar[5:-1])](.5).v = 35

# visualisation ==========

# plots dendrites
'''
sections = h.SectionList([sec for sec in h.allsec() if 'dend' in str(sec)])
ps = h.PlotShape(sections,False).plot(plt)
ps._do_plot(0,1,h.dend,'v',cmap=vis_cmap)
'''
ps = h.PlotShape(h.SectionList(), False).plot(plt)
ps._do_plot(0, 1, h.allsec(), 'v', cmap=vis_cmap)

# Make sphere to mimic soma
u = np.linspace(0, 2 * np.pi, 100)
v = np.linspace(0, np.pi, 100)
x = 12 * np.outer(np.cos(u), np.sin(v))
y = 12 * np.outer(np.sin(u), np.sin(v))
z = 12 * np.outer(np.ones(np.size(u)), np.cos(v))
ps.plot_surface(x, y + 5, z + 10, color=soma_col)
ps.plot_surface(x, y + 5, z + 14, color=soma_col)
ps.plot_surface(x, y + 5, z + 17, color=soma_col)

# removes plot background
ps.xaxis.pane.fill = False
ps.yaxis.pane.fill = False
ps.zaxis.pane.fill = False
Example #54
0
somaA = h.Section('somaA')
somaA.pt3dclear()
somaA.pt3dadd(90, 0, 0, 30)
somaA.pt3dadd(60, 0, 0, 30)
somaA.nseg = 11

# somaB = h.Section('somaB')
# somaB.pt3dclear()
# somaB.pt3dadd(60,0,0,30)
# somaB.pt3dadd(90,0,0,30)
# somaB.nseg = 11

# Where?
# intracellular
cyt = rxd.Region(h.allsec(), name='cyt', nrn_region='i')

# membrane
mem = rxd.Region(h.allsec(), name='cell_mem', geometry=rxd.membrane())

# extracellular
ecs = rxd.Extracellular(-100, -100, -100, 100, 100, 100, dx=33)

# Who?  ions & gates

# intracellular sodium & potassium
na = rxd.Species([cyt, mem], name='na', d=1, charge=1, initial=10)
k = rxd.Species([cyt, mem], name='k', d=1, charge=1, initial=54.4)

# extracellular parameters provide a constant concentration for the Nernst potential and reactions.
kecs = rxd.Parameter(ecs, name='k_ecs', charge=1, value=2.5)
Example #55
0
def run_nrn_sim(tend,
                sample_dt=0.025,
                report_t=None,
                report_dt=None,
                dt=None,
                **meta):
    if dt is None:
        dt = default_model_parameters['dt']

    # Instrument mid-point and ends of each section for traces.
    vtraces = []
    vtrace_t_hoc = h.Vector()

    ncomps = set([s.nseg for s in h.allsec() if s.name() != 'soma'])
    if len(ncomps) == 1:
        common_ncomp = {'ncomp': ncomps.pop()}
    else:
        common_ncomp = {}

    for s in h.allsec():
        vend = h.Vector()
        vend.record(s(0.5)._ref_v, sample_dt)
        vtraces.append((s.name() + ".mid", vend))
        if s.nseg != 1 or s.name() != 'soma':
            vmid = h.Vector()
            vmid.record(s(1.0)._ref_v, sample_dt)
            vtraces.append((s.name() + ".end", vmid))

    vtrace_t_hoc.record(h._ref_t, sample_dt)

    # Instrument every segment for section voltage reports.
    if report_t is None:
        if report_dt is not None:
            report_t = [
                report_dt * (1 + i) for i in xrange(int(tend / report_dt))
            ]
        else:
            report_t = []
    elif not isinstance(report_t, list):
        report_t = [report_t]

    vreports = []
    vreport_t_hoc = h.Vector(report_t)

    if report_t:
        for s in h.allsec():
            nseg = s.nseg
            ps = [0] + [(i + 0.5) / nseg for i in xrange(nseg)] + [1]
            vs = [h.Vector() for p in ps]
            for p, v in zip(ps, vs):
                v.record(s(p)._ref_v, vreport_t_hoc)
            vreports.append((s.name(), s.L, s.nseg, ps, vs))

    # Run sim
    if dt == 0:
        # Use CVODE instead
        h.cvode.active(1)
        abstol = default_model_parameters['abstol']
        h.cvode.atol(abstol)
        common_meta = {'dt': 0, 'cvode': True, 'abstol': abstol}
    else:
        h.dt = dt
        h.steps_per_ms = 1 / dt  # or else NEURON might noisily fudge dt
        common_meta = {'dt': dt, 'cvode': False}

    h.secondorder = 2
    h.tstop = tend
    h.run()

    # convert results to traces with metadata
    traces = []

    vtrace_t = list(vtrace_t_hoc)
    traces.append(
        combine(
            common_meta, meta, common_ncomp, {
                'name': 'membrane voltage',
                'sim': 'neuron',
                'units': 'mV',
                'data': combine({n: list(v)
                                 for n, v in vtraces},
                                time=vtrace_t)
            }))

    # and section reports too
    vreport_t = list(vreport_t_hoc)
    for name, length, nseg, ps, vs in vreports:
        obs = np.column_stack([np.array(v) for v in vs])
        xs = [length * p for p in ps]
        for i, t in enumerate(report_t):
            if i >= obs.shape[0]:
                break

            traces.append(
                combine(
                    common_meta, meta, {
                        'name': 'membrane voltage',
                        'sim': 'neuron',
                        'units': {
                            'x': 'µm',
                            name: 'mV'
                        },
                        'ncomp': nseg,
                        'time': t,
                        'data': {
                            'x': xs,
                            name: list(obs[i, :])
                        }
                    }))

    return traces
Example #56
0
def real_morphology_model_dend_spatial(stim,
                                       d=30,
                                       k=0.001,
                                       gpas_soma=0.0001,
                                       Ra=100.,
                                       cm=1.,
                                       dt=0.1):
    # -- Biophysics --
    # Sec parameters and conductance
    for sec in h.allsec():
        sec.Ra = Ra  # Ra is a parameter to infer
        sec.cm = cm  # parameter optimisation algorithm found this
        sec.v = 0

        sec.insert('pas')
        sec.g_pas = gpas_soma  # gpas is a parameter to infer

        for seg in sec:
            h('soma distance()')
            dist = (h.distance(seg.x))
            gpas = gpas_soma * (1 + k * dist)

            if gpas < 0:
                seg.g_pas = 0
                print("WARNING!!! 'gpas' is in negative! Corrected to zero.")
            else:
                seg.g_pas = gpas

        sec.e_pas = 0

    # Print information
    # h.psection()

    h.dt = dt  # Time step (iteration)
    h.steps_per_ms = 1 / dt

    # Stimulus
    h.tstop = len(stim) * dt
    h.load_file("vplay.hoc")
    vec = h.Vector(stim)
    istim = h.IClamp(h.apic[d](0.5))
    vec.play(istim._ref_amp, h.dt)
    istim.delay = 0  # Just for Neuron
    istim.dur = 1e9  # Just for Neuron

    # Run simulation ->
    # Set up recording Vectors
    v_vec = h.Vector()  # Membrane potential vector
    t_vec = h.Vector()  # Time stamp vector
    v_vec.record(h.apic[d](0.5)._ref_v)
    t_vec.record(h._ref_t)

    # Simulation duration and RUN
    # h.tstop = 1200  # Simulation end
    h.v_init = 0
    h.finitialize(h.v_init)

    h.init()
    h.run()

    t = t_vec.to_python()
    v = v_vec.to_python()

    return t, v
    def plot_morphology(self,
                        figsize_tuple=(10, 10),
                        synapses=False,
                        color_dendrites=False,
                        synapse_marker_r=5,
                        synapse_marker_alpha=0.5,
                        plot_electrodes=False,
                        xy=(512, 512),
                        dpatch_left=False,
                        selection_string='stim_dict'):

        plt.figure(figsize=figsize_tuple)
        im = Image.new('RGB', xy, (255, 255, 255))
        draw = ImageDraw.Draw(im)

        mc_ints = {
            'b': (77, 117, 179),
            'r': (210, 88, 88),
            'k': (38, 35, 35),
            'grey': (197, 198, 199)
        }

        mc_f = {
            key: tuple([x / 255.0 for x in mc_ints[key]])
            for key in mc_ints.keys()
        }

        if color_dendrites:
            import seaborn as sns
            self.cp = sns.color_palette('hls', len(self.unique_dendrites))
            self.dend_to_index = {
                str(dend): i
                for i, dend in enumerate(self.unique_dendrites)
            }

            self.cp = sns.color_palette('hls', len(self.unique_dendrites))
            self.cp = {
                'b':
                (0.2980392156862745, 0.4470588235294118, 0.6901960784313725),
                'r':
                (0.7686274509803922, 0.3058823529411765, 0.3215686274509804)
            }
            self.dend_to_index = {
                str(dend): 0
                for dend in self.unique_dendrites
            }
            for dend in self.unique_dendrites:
                if str(dend).split('_')[2][0] == 'a':

                    self.dend_to_index[str(dend)] = 1

        # plot the morph
        for sec in h.allsec():
            if color_dendrites:
                if sec.name().split('[')[0] == 'jc_tree2_soma':
                    fill_color = (0, 0, 0)
                else:
                    dname = sec.name().split('[')[0]
                    if dname.split('_')[2][0] == 'a':
                        fill_color = tuple([
                            int(f * 255.0)
                            for f in (0.2980392156862745, 0.4470588235294118,
                                      0.6901960784313725)
                        ])
                    else:
                        fill_color = tuple([
                            int(f * 255.0)
                            for f in (0.7686274509803922, 0.3058823529411765,
                                      0.3215686274509804)
                        ])

            else:
                fill_color = (0, 0, 0)
            x, y, z, d = self.get_coordinates(sec)
            x += 50
            xy = zip(x, y)
            for i in range(len(x) - 1):
                draw.line((xy[i], xy[i + 1]), fill=fill_color, width=int(d[i]))

        if synapses:
            if selection_string == 'stim_dict':
                syncolor_dict = {'stim1': mc_f['r'], 'stim2': mc_f['b']}
                for key in self.cpampa_stim_dict.keys():
                    cpampa_list = self.cpampa_stim_dict[key]
                    for syn in cpampa_list:
                        syn_loc = syn.get_segment().x
                        sec = syn.get_segment().sec
                        x, y = self.get_2d_position(sec, syn_loc)
                        plt.plot(x,
                                 y,
                                 'o',
                                 alpha=synapse_marker_alpha,
                                 color=syncolor_dict[key],
                                 markersize=synapse_marker_r)
                # make legend
                stim1_patch = mpatches.Patch(color=syncolor_dict['stim1'],
                                             label='stim1')
                stim2_patch = mpatches.Patch(color=syncolor_dict['stim2'],
                                             label='stim2')
                plt.legend(handles=[stim1_patch, stim2_patch])

            elif selection_string == 'cpampa_list':
                syn_color = mc_f['r']
                for key in self.cpampa_list:
                    cpampa_list = self.cpampa_list
                    for syn in cpampa_list:
                        syn_loc = syn.get_segment().x
                        sec = syn.get_segment().sec
                        x, y = self.get_2d_position(sec, syn_loc)
                        plt.plot(x,
                                 y,
                                 'o',
                                 alpha=synapse_marker_alpha,
                                 color=syn_color,
                                 markersize=synapse_marker_r)

        if plot_electrodes:
            xs, ys = self.get_2d_position(self.root, 0.5)
            self.plot_electrode(xs, ys, 'k')
            if self.dend_to_patch:
                xd, yd = self.get_2d_position(self.dend_to_patch, 0.5)
                self.plot_electrode(xd,
                                    yd,
                                    'grey',
                                    dpatch_left,
                                    linestyle='--')

        plt.imshow(np.asarray(im))
        plt.axis('off')
Example #58
0
 def size(self) -> int:
     """
     Returns number of sections in the current NEURON environment.
     """
     return len(list(h.allsec()))
Example #59
0
def real_morphology_model_srsoma_rdend_spatial(stim,
                                               d=30,
                                               k=0.001,
                                               gpas_soma=0.0001,
                                               Ra=100.,
                                               cm=1.,
                                               dt=0.1):
    """
    This simulation protocol  assumes spatial change of the 'gpas' parameter

    :param stim:
    :param d:     distance from soma in um
    :param m:     rate of linear change in gpas density moving away from soma (opt)
    :param gpas_soma: the value of gpas in soma (opt)
    :param Ra:    Axial resistance (opt)
    :param cm:    Membrane conductance (opt)
    :param dt:    Time step (opt)
    :return:
    """

    # Sec parameters and conductance
    for sec in h.allsec():
        sec.Ra = Ra  # Ra is a parameter to infer
        sec.cm = cm  # parameter optimisation algorithm found this
        sec.v = 0

        sec.insert('pas')
        sec.g_pas = gpas_soma  # gpas is a parameter to infer

        for seg in sec:
            h('soma distance()')
            dist = (h.distance(seg.x))
            gpas = gpas_soma * (1 + k * dist)

            if gpas < 0:
                seg.g_pas = 0
                print("WARNING!!! 'gpas' is in negative! Corrected to zero.")
            else:
                seg.g_pas = gpas

        sec.e_pas = 0

    # Print information
    # h.psection()

    h.dt = dt  # Time step (iteration)
    h.steps_per_ms = 1 / dt

    # Stimulus
    h.tstop = len(stim) * dt
    h.load_file("vplay.hoc")
    vec = h.Vector(stim)
    istim = h.IClamp(h.soma(0.5))
    vec.play(istim._ref_amp, h.dt)
    istim.delay = 0  # Just for Neuron
    istim.dur = 1e9  # Just for Neuron

    # Run simulation ->
    # Set up recording Vectors
    vs_vec = h.Vector()  # Membrane potential vector for soma recording
    vd_vec = h.Vector()  # Membrane potential vector for dendrite recording
    t_vec = h.Vector()  # Time stamp vector
    vd_vec.record(h.apic[d](0.5)._ref_v)
    vs_vec.record(h.soma(0.5)._ref_v)
    t_vec.record(h._ref_t)

    # Simulation duration and RUN
    # h.tstop = 1200  # Simulation end
    h.v_init = 0
    h.finitialize(h.v_init)

    h.init()
    h.run()

    t = t_vec.to_python()
    v_soma = vs_vec.to_python()
    v_dend = vd_vec.to_python()

    v_soma = np.array(v_soma)
    v_dend = np.array(v_dend)

    v = np.concatenate((v_soma, v_dend))
    return t, v
    def biophys(self):
        Rm = 20000
        gka_soma = 0.0075
        gh_soma = 0.00005
        self.soma.insert('hha2')
        for seg in self.soma:
            seg.hha2.gnabar = 0.007
            seg.hha2.gkbar = 0.007 / 5
            seg.hha2.gl = 0
            seg.hha2.el = -70
        self.soma.insert('pas')
        for seg in self.soma:
            seg.pas.g = 1. / Rm
        self.soma.insert('h')
        for seg in self.soma:
            seg.h.ghdbar = gh_soma
            seg.h.vhalfl = -73
        #self.soma.insert('hNa')
        #for seg in self.soma:
        #    seg.hNa.gbar = 0.000043
        #    seg.hNa.gbar = 1.87e-5
        self.soma.insert('kap')
        for seg in self.soma:
            seg.kap.gkabar = gka_soma
        self.soma.insert('km')
        for seg in self.soma:
            seg.km.gbar = 0.06
        self.soma.insert('cal')
        for seg in self.soma:
            seg.cal.gcalbar = 0.0014 / 2
        self.soma.insert('cat')
        for seg in self.soma:
            seg.cat.gcatbar = 0.0001 / 2
        self.soma.insert('somacar')
        for seg in self.soma:
            seg.somacar.gcabar = 0.0003
        self.soma.insert('kca')
        for seg in self.soma:
            seg.kca.gbar = 5 * 0.0001
        self.soma.insert('mykca')
        for seg in self.soma:
            seg.mykca.gkbar = 0.09075
        self.soma.insert('cad')

        self.radTprox.insert('h')
        for seg in self.radTprox:
            seg.h.ghdbar = 2 * gh_soma
            seg.h.vhalfl = -81
        self.radTprox.insert('car')
        for seg in self.radTprox:
            seg.car.gcabar = 0.1 * 0.0003

        self.radTprox.insert('calH')
        for seg in self.radTprox:
            seg.calH.gcalbar = 0.1 * 0.00031635

        self.radTprox.insert('cat')
        for seg in self.radTprox:
            seg.cat.gcatbar = 0.0001

        self.radTprox.insert('cad')
        self.radTprox.insert('kca')
        for seg in self.radTprox:
            seg.kca.gbar = 5 * 0.0001

        self.radTprox.insert('mykca')
        for seg in self.radTprox:
            seg.mykca.gkbar = 2 * 0.0165

        self.radTprox.insert('km')
        for seg in self.radTprox:
            seg.km.gbar = 0.06

        self.radTprox.insert('kap')
        for seg in self.radTprox:
            seg.kap.gkabar = 2 * gka_soma

        self.radTprox.insert('kad')
        for seg in self.radTprox:
            seg.kad.gkabar = 0.0

        self.radTprox.insert('hha_old')
        for sseg in self.radTprox:
            seg.hha_old.gnabar = 0.007
            seg.hha_old.gkbar = 0.007 / 8.065
            seg.hha_old.el = -70

        self.radTprox.insert('pas')

        self.radTmed.insert('h')
        for seg in self.radTmed:
            seg.h.ghdbar = 4 * gh_soma
            seg.h.vhalfl = -81
        self.radTmed.insert('car')
        for seg in self.radTmed:
            seg.car.gcabar = 0.1 * 0.0003

        self.radTmed.insert('calH')
        for seg in self.radTmed:
            seg.calH.gcalbar = 10 * 0.00031635

        self.radTmed.insert('cat')
        for seg in self.radTmed:
            seg.cat.gcatbar = .0001

        self.radTmed.insert('cad')
        self.radTmed.insert('kca')
        for seg in self.radTmed:
            seg.kca.gbar = 5 * 0.0001
        self.radTmed.insert('mykca')
        for seg in self.radTmed:
            seg.mykca.gkbar = 2 * 0.0165
        self.radTmed.insert('km')
        for seg in self.radTmed:
            seg.km.gbar = 0.06
        self.radTmed.insert('kap')
        for seg in self.radTmed:
            seg.kap.gkabar = 0.0
        self.radTmed.insert('kad')
        for seg in self.radTmed:
            seg.kad.gkabar = 4 * gka_soma
        self.radTmed.insert('hha_old')
        for seg in self.radTmed:
            seg.hha_old.gnabar = 0.007
            seg.hha_old.gkbar = 0.007 / 8.065
            seg.hha_old.el = -70
        self.radTmed.insert('pas')

        self.radTdist.insert('h')
        for seg in self.radTdist:
            seg.h.ghdbar = 7 * gh_soma
            seg.h.vhalfl = -81

        self.radTdist.insert('car')
        for seg in self.radTdist:
            seg.car.gcabar = 0.1 * 0.0003
        self.radTdist.insert('calH')
        for seg in self.radTdist:
            seg.calH.gcalbar = 10 * 0.00031635
        self.radTdist.insert('cat')
        for seg in self.radTdist:
            seg.cat.gcatbar = 0.0001
        self.radTdist.insert('cad')
        self.radTdist.insert('kca')
        for seg in self.radTdist:
            seg.kca.gbar = 0.5 * 0.0001
        self.radTdist.insert('mykca')
        for seg in self.radTdist:
            seg.mykca.gkbar = 0.25 * 0.0165
        self.radTdist.insert('km')
        for seg in self.radTdist:
            seg.km.gbar = 0.06
        self.radTdist.insert('kap')
        for seg in self.radTdist:
            seg.kap.gkabar = 0.0
        self.radTdist.insert('kad')
        for seg in self.radTdist:
            seg.kad.gkabar = 6 * gka_soma
        self.radTdist.insert('hha_old')
        for seg in self.radTdist:
            seg.hha_old.gnabar = 0.007
            seg.hha_old.gkbar = 0.007 / 8.065
            seg.hha_old.el = -70
        self.radTdist.insert('pas')

        self.lm_thick2.insert('hha_old')
        for seg in self.lm_thick2:
            seg.hha_old.gnabar = 0.007
            seg.hha_old.gkbar = 0.007 / 8.065
            seg.hha_old.el = -70
            seg.hha_old.gl = 0
        self.lm_thick2.insert('pas')
        for seg in self.lm_thick2:
            seg.pas.g = 1 / 200000
        self.lm_thick2.insert('kad')
        for seg in self.lm_thick2:
            seg.kad.gkabar = 6.5 * gka_soma

        self.lm_medium2.insert('hha_old')
        for seg in self.lm_medium2:
            seg.hha_old.gnabar = 0.007
            seg.hha_old.gkbar = 0.007 / 8.065
            seg.hha_old.el = -70
            seg.hha_old.gl = 0
        self.lm_medium2.insert('pas')
        for seg in self.lm_medium2:
            seg.pas.g = 1. / 200000
        self.lm_medium2.insert('kad')
        for seg in self.lm_medium2:
            seg.kad.gkabar = 6.5 * gka_soma

        self.lm_thin2.insert('hha_old')
        for seg in self.lm_thin2:
            seg.hha_old.gnabar = 0.007
            seg.hha_old.gkbar = 0.007 / 8.065
            seg.hha_old.el = -70
            seg.hha_old.gl = 0
        self.lm_thin2.insert('pas')
        for seg in self.lm_thin2:
            seg.pas.g = 1. / 200000
        self.lm_thin2.insert('kad')
        for seg in self.lm_thin2:
            seg.kad.gkabar = 6.5 * gka_soma

        self.lm_thick1.insert('hha_old')
        for seg in self.lm_thick1:
            seg.hha_old.gnabar = 0.007
            seg.hha_old.gkbar = 0.007 / 8.065
            seg.hha_old.el = -70
            seg.hha_old.gl = 0
        self.lm_thick1.insert('pas')
        for seg in self.lm_thick1:
            seg.pas.g = 1 / 200000
        self.lm_thick1.insert('kad')
        for seg in self.lm_thick1:
            seg.kad.gkabar = 6.5 * gka_soma

        self.lm_medium1.insert('hha_old')
        for seg in self.lm_medium1:
            seg.hha_old.gnabar = 0.007
            seg.hha_old.gkbar = 0.007 / 8.065
            seg.hha_old.el = -70
            seg.hha_old.gl = 0
        self.lm_medium1.insert('pas')
        for seg in self.lm_medium1:
            seg.pas.g = 1. / 200000
        self.lm_medium1.insert('kad')
        for seg in self.lm_medium1:
            seg.kad.gkabar = 6.5 * gka_soma

        self.lm_thin1.insert('hha_old')
        for seg in self.lm_thin1:
            seg.hha_old.gnabar = 0.007
            seg.hha_old.gkbar = 0.007 / 8.065
            seg.hha_old.el = -70
            seg.hha_old.gl = 0
        self.lm_thin1.insert('pas')
        for seg in self.lm_thin1:
            seg.pas.g = 1. / 200000
        self.lm_thin1.insert('kad')
        for seg in self.lm_thin1:
            seg.kad.gkabar = 6.5 * gka_soma

        self.oriprox1.insert('h')
        for seg in self.oriprox1:
            seg.h.ghdbar = gh_soma
            seg.h.vhalfl = -81
        self.oriprox1.insert('car')
        for seg in self.oriprox1:
            seg.car.gcabar = 0.1 * 0.0003
        self.oriprox1.insert('calH')
        for seg in self.oriprox1:
            seg.calH.gcalbar = 0.1 * 0.00031635
        self.oriprox1.insert('cat')
        for seg in self.oriprox1:
            seg.cat.gcatbar = 0.0001
        self.oriprox1.insert('cad')
        self.oriprox1.insert('kca')
        for seg in self.oriprox1:
            seg.kca.gbar = 5.0 * 0.0001
        self.oriprox1.insert('mykca')
        for seg in self.oriprox1:
            seg.mykca.gkbar = 2 * 0.0165
        self.oriprox1.insert('km')
        for seg in self.oriprox1:
            seg.km.gbar = 0.06
        self.oriprox1.insert('kap')
        for seg in self.oriprox1:
            seg.kap.gkabar = gka_soma
        self.oriprox1.insert('kad')
        for seg in self.oriprox1:
            seg.kad.gkabar = 0.0
        self.oriprox1.insert('hha_old')
        for seg in self.oriprox1:
            seg.hha_old.gnabar = 0.007
            seg.hha_old.gkbar = 0.007 / 8.065
            seg.hha_old.el = -70
        self.oriprox1.insert('pas')

        self.oridist1.insert('h')
        for seg in self.oridist1:
            seg.h.ghdbar = 2 * gh_soma
            seg.h.vhalfl = -81
        self.oridist1.insert('car')
        for seg in self.oridist1:
            seg.car.gcabar = 0.1 * 0.0003
        self.oridist1.insert('calH')
        for seg in self.oridist1:
            seg.calH.gcalbar = 0.1 * 0.00031635
        self.oridist1.insert('cat')
        for seg in self.oridist1:
            seg.cat.gcatbar = 0.0001
        self.oridist1.insert('cad')
        self.oridist1.insert('kca')
        for seg in self.oridist1:
            seg.kca.gbar = 5 * 0.0001
        self.oridist1.insert('mykca')
        for seg in self.oridist1:
            seg.mykca.gkbar = 2 * 0.0165
        self.oridist1.insert('km')
        for seg in self.oridist1:
            seg.km.gbar = 0.06
        self.oridist1.insert('kap')
        for seg in self.oridist1:
            seg.kap.gkabar = gka_soma
        self.oridist1.insert('kad')
        for seg in self.oridist1:
            seg.kad.gkabar = 0.0
        self.oridist1.insert('hha_old')
        for seg in self.oridist1:
            seg.hha_old.gnabar = 0.007
            seg.hha_old.gkbar = 0.007 / 8.065
            seg.hha_old.el = -70
        self.oridist1.insert('pas')

        self.oriprox2.insert('h')
        for seg in self.oriprox2:
            seg.h.ghdbar = gh_soma
            seg.h.vhalfl = -81
        self.oriprox2.insert('car')
        for seg in self.oriprox2:
            seg.car.gcabar = 0.1 * 0.0003
        self.oriprox2.insert('calH')
        for seg in self.oriprox2:
            seg.calH.gcalbar = 0.1 * 0.00031635
        self.oriprox2.insert('cat')
        for seg in self.oriprox2:
            seg.cat.gcatbar = 0.0001
        self.oriprox2.insert('cad')
        self.oriprox2.insert('kca')
        for seg in self.oriprox2:
            seg.kca.gbar = 5.0 * 0.0001
        self.oriprox2.insert('mykca')
        for seg in self.oriprox2:
            seg.mykca.gkbar = 2 * 0.0165
        self.oriprox2.insert('km')
        for seg in self.oriprox2:
            seg.km.gbar = 0.06
        self.oriprox2.insert('kap')
        for seg in self.oriprox2:
            seg.kap.gkabar = gka_soma
        self.oriprox2.insert('kad')
        for seg in self.oriprox2:
            seg.kad.gkabar = 0.0
        self.oriprox2.insert('hha_old')
        for seg in self.oriprox2:
            seg.hha_old.gnabar = 0.007
            seg.hha_old.gkbar = 0.007 / 8.065
            seg.hha_old.el = -70
        self.oriprox2.insert('pas')

        self.oridist2.insert('h')
        for seg in self.oridist2:
            seg.h.ghdbar = 2 * gh_soma
            seg.h.vhalfl = -81
        self.oridist2.insert('car')
        for seg in self.oridist2:
            seg.car.gcabar = 0.1 * 0.0003
        self.oridist2.insert('calH')
        for seg in self.oridist2:
            seg.calH.gcalbar = 0.1 * 0.00031635
        self.oridist2.insert('cat')
        for seg in self.oridist2:
            seg.cat.gcatbar = 0.0001
        self.oridist2.insert('cad')
        self.oridist2.insert('kca')
        for seg in self.oridist2:
            seg.kca.gbar = 5 * 0.0001
        self.oridist2.insert('mykca')
        for seg in self.oridist2:
            seg.mykca.gkbar = 2 * 0.0165
        self.oridist2.insert('km')
        for seg in self.oridist2:
            seg.km.gbar = 0.06
        self.oridist2.insert('kap')
        for seg in self.oridist2:
            seg.kap.gkabar = gka_soma
        self.oridist2.insert('kad')
        for seg in self.oridist2:
            seg.kad.gkabar = 0.0
        self.oridist2.insert('hha_old')
        for seg in self.oridist2:
            seg.hha_old.gnabar = 0.007
            seg.hha_old.gkbar = 0.007 / 8.065
            seg.hha_old.el = -70
        self.oridist2.insert('pas')

        self.axon.insert('hha2')
        for seg in self.axon:
            seg.hha2.gnabar = 0.1
            seg.hha2.gkbar = .1 / 5
            seg.hha2.gl = 0
            seg.hha2.el = -70
        self.axon.insert('pas')
        for seg in self.axon:
            seg.pas.g = 1 / Rm
        self.axon.insert('km')
        for seg in self.axon:
            seg.km.gbar = 0.5 * 0.06

        for sec in h.allsec():
            sec.ek = -80
            sec.ena = 50
            sec.Ra = 150
            sec.cm = 1
            for seg in sec:
                seg.pas.e = 70
                seg.pas.g = 1 / Rm