Exemple #1
0
def test_syn():
    precell = BallStick()
    postcell = BallStick()
    nc = precell.connect2target(postcell.synlist[0])
    nc.weight[0] = 0.01
    nc.delay = 0
    stim = h.IClamp(0.5, sec=precell.soma)
    stim.amp = 0.700
    stim.delay = 700
    stim.dur = 1000
    vec = {}
    for var in 't', 'pre', 'post':
        vec[var] = h.Vector()
    vec['t'].record(h._ref_t)
    vec['pre'].record(precell.soma(0.5)._ref_v)
    vec['post'].record(postcell.soma(0.5)._ref_v)
    cvode = h.CVode()
    cvode.active(1)
    h.finitialize(-65)
    tstop = 2000
    while h.t < tstop:
        h.fadvance()
    with open("vm.out", "w") as out:
        for time, vsoma in zip(vec['t'], vec['post']):
            out.write("%g %g\n" % (time, vsoma))
    try:
        import matplotlib.pyplot as plt
        plt.plot(vec['t'], vec['pre'], vec['t'], vec['post'])
        plt.show()
    except ImportError:
        pass
Exemple #2
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()
Exemple #3
0
def test_cell():
    cell = BallStick()
    stim = h.IClamp(0.5, sec=cell.soma)
    stim.amp = 0.620
    stim.delay = 700
    stim.dur = 1000
    tm = h.Vector()
    vm = h.Vector()
    ca = h.Vector()
    tm.record(h._ref_t)
    vm.record(cell.soma(0.5)._ref_v)
    ca.record(cell.soma(0.5)._ref_cai)
    cvode = h.CVode()
    cvode.active(1)
    h.finitialize(-65)
    tstop = 2000
    while h.t < tstop:
        h.fadvance()
    with open("vm.out", "w") as out:
        for time, vsoma in zip(tm, vm):
            out.write("%g %g\n" % (time, vsoma))
    with open("ca.out", "w") as out:
        for time, conc in zip(tm, ca):
            out.write("%g %g\n" % (time, conc))
    try:
        import matplotlib.pyplot as plt
        plt.plot(tm, vm)
        plt.show()
    except ImportError:
        pass
Exemple #4
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()
Exemple #5
0
 def test_initializer_initialize(self):
     init = simulator.initializer
     orig_initialize = init._initialize
     init._initialize = Mock()
     h.finitialize(-65)
     self.assertTrue(init._initialize.called)
     init._initialize = orig_initialize
def simulate(pool, tstop=1000, vinit=-55):
    ''' simulation control 
    Parameters
    ----------
    cell: NEURON cell
        cell for simulation
    tstop: int (ms)
        simulation time
    vinit: int (mV)
        initialized voltage
    '''
    h.finitialize(vinit)
    for i in pool:
        cell = pc.gid2cell(i)
        balance(cell)
    if h.cvode.active():
        h.cvode.active()
    else:
        h.fcurrent()
    h.frecord_init()
    h.tstop = tstop
    h.v_init = vinit
    pc.set_maxstep(0.5)
    h.stdinit()
    pc.psolve(tstop)
Exemple #7
0
 def test_initializer_initialize(self):
     init = simulator.initializer
     orig_initialize = init._initialize
     init._initialize = Mock()
     h.finitialize(-65)
     init._initialize.assert_called()
     init._initialize = orig_initialize
 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()
Exemple #9
0
 def reset(self):
     """Reset the state of the current network to time t = 0."""
     self.running = False
     self.t = 0
     self.tstop = 0
     self.t_start = 0
     self.segment_counter += 1
     h.finitialize()
Exemple #10
0
    def go(self):
        self.set_recording()
        h.dt = self.dt
        h.tstop = self.sim_time
        h.finitialize(-60)#self.v_init)
        h.init()
        h.run()

        self.rec_i = self.rec_ina.to_python()
def ivcurve(mechanism_name, i_type, vmin=-100, vmax=100, deltav=1, transient_time=50, test_time=50, rs=1, vinit=-665):
    """
    Returns the (peak) current-voltage relationship for an ion channel.

    Args:
        mechanism_name = name of the mechanism (e.g. hh)
        i_type = which current to monitor (e.g. ik, ina)
        vmin = minimum voltage step to test
        vmax = maximum voltage step to test
        deltav = increment of voltage
        transient_time = how long to ignore for initial conditions to stabilize (ms)
        test_time = duration of the voltage clamp tests (ms)
        rs = resistance of voltage clamp in MOhm
        vinit = initialization voltage

    Returns:
        i = iterable of peak currents (in mA/cm^2)
        v = iterable of corresponding test voltages

    Note:
        The initialization potential (vinit) may affect the result. For example, consider
        the Hodgkin-Huxley sodium channel; a large fraction are inactivated at rest. Using a
        strongly hyperpolarizing vinit will uninactivate many channels, leading to more
        current.
    """
    from neuron import h
    import numpy
    h.load_file('stdrun.hoc')
    sec = h.Section()
    sec.insert(mechanism_name)
    sec.L = 1
    sec.diam = 1
    seclamp = h.SEClamp(sec(0.5))
    seclamp.amp1 = vinit
    seclamp.dur1 = transient_time
    seclamp.dur2 = test_time 
    seclamp.rs = rs
    i_record = h.Vector()
    i_record.record(sec(0.5).__getattribute__('_ref_' + i_type))
    result_i = []
    result_v = numpy.arange(vmin, vmax, deltav)
    for test_v in result_v:
        seclamp.amp2 = test_v
        h.finitialize(vinit)
        h.continuerun(transient_time)
        num_transient_points = len(i_record)
        h.continuerun(test_time + transient_time)
        i_record2 = i_record.as_numpy()[num_transient_points:]
        baseline_i = i_record2[0]
        i_record_shift = i_record2 - baseline_i
        max_i = max(i_record_shift)
        min_i = min(i_record_shift)
        peak_i = max_i if abs(max_i) > abs(min_i) else min_i
        peak_i += baseline_i
        result_i.append(peak_i)
    return result_i, result_v
Exemple #12
0
def run_single_simulation(config, interactive):
    axon = Axon(config)
    axon.insert_stim(config['stim_position'], config['stim_amplitude'],
            config['stim_start_time'], config['stim_duration'])

    # set up recording vectors for python plots and the csv file
    t = h.Vector()
    t.record(h._ref_t)

    num_v_traces = config['num_v_traces']
    v_traces = []
    for i in range(num_v_traces):
        v = h.Vector()
        v.record(axon.section_at_f(
            # record at num_v_traces points along the axon, equally spaced
            # from eachother and from the end points (since we don't care
            # about things like the impedance mismatch at the ends)
            (i + 1) * 1.0 / (num_v_traces + 1))
            (Axon.middle)._ref_v)
        v_traces.append(v)

    # set up NEURON plotting code (if we're in an interactive session)
    if interactive:
        g = h.Graph()
        g.size(0, config['integration_time'], -80, 55)
        for i in range(num_v_traces):
            g.addvar('v(0.5)',
                    sec=axon.section_at_f((i+1) * 1.0 / (num_v_traces + 1)))

    # initialize the simulation
    h.dt = config['max_time_step']
    tstop = config['integration_time']
    h.finitialize(config['initial_membrane_potential'])
    h.fcurrent()

    # run the simulation
    if interactive:
        g.begin()
        while h.t < tstop:
            h.fadvance()
            g.plot(h.t)
        g.flush()
    else:
        while h.t < tstop:
            h.fadvance()

    # save the data as a csv
    with open(config['csv_filename'], 'w') as csv_file:
        # start with a header of the form "t_ms, V0_mV, V1_mv, V2_mV,..."
        csv_file.write(", ".join(
            ["t_ms"] + ["V{0}_mV".format(i) for i in range(num_v_traces)]
            ) + "\n")

        # write the time and each of the recorded voltages at that time
        for row in zip(t, *v_traces):
            csv_file.write(", ".join([str(x) for x in row]) + "\n")
Exemple #13
0
    def run(self, v_init=-60, tstop=20000., dt=0.1,
                                        cvode=True, ga_use_half=False):
        '''
        Simulates this cell and all desired vectors are recorded. Uses fixed
        or variable timestep depending on the `cvode=` boolean.

        Parameters:
        ----------
        v_init : int, float
            The starting voltage of the simulation.
        tstop : int, float
            The maximum time of integration
        dt : float
            The desired integration step.
        cvode : bool
            Selects variable time step integration. Default is False.
        ga_use_half : bool
            Will only use the 2nd have of recordings for GA
        '''
        
        h.load_file('stdrun.hoc')
        h.v_init = v_init
        h.tstop = tstop
        h.dt = dt
        #set the recording into the vecs dictionary
        #the _ref dictionary contain the hoc object attribute references
        for key in self._ref.keys():
            #This makes sure we overwrite any vectors if we already ran a sim
            if isinstance(self.vecs['time'], np.ndarray):
                self.vecs[key] = h.Vector()
                self.vecs[key].record(self._ref[key])
            else:
                self.vecs[key].record(self._ref[key])

        
        
        if cvode:
            solver = h.CVode()
            solver.active(1)
            h.finitialize(h.v_init)
            solver.solve(h.tstop)
        else:
            h.CVode().active(0)
            h.finitialize()
            for t in range(0, int(h.tstop/h.dt)):
                h.fadvance()

        for key, val in self.vecs.iteritems():
            self.vecs[key] = np.array(val)

        if ga_use_half:
            for key, val in self.vecs.iteritems():
                self.vecs[key] = val[(val.size)/2:]

        return self.vecs
def integrate(a, b, c, t):
    # g.begin()
    k = 0
    h.finitialize()
    while h.t < tstop:
        h.fadvance()
        a[k - 1] = cell.ek
        b[k - 1] = cell.ko
        c[k - 1] = cell.ik
        t[k - 1] = h.dt * (k - 1)
        k = k + 1
Exemple #15
0
def benchmark_cell():
    cell = BallStick()
    stim = h.IClamp(0.5, sec=cell.soma)
    stim.amp = 0.700
    stim.delay = 0
    stim.dur = 1e6
    cvode = h.CVode()
    cvode.active(1)
    h.finitialize(-65)
    tstop = 1e6
    while h.t < tstop:
        h.fadvance()
Exemple #16
0
 def _pre_run(self):
     if not self.running:
         self.running = True
         local_minimum_delay = self.parallel_context.set_maxstep(self.default_maxstep)
         if state.vargid_offsets:
             logger.info("Setting up transfer on MPI process {}".format(state.mpi_rank))
             state.parallel_context.setup_transfer()
         h.finitialize()
         self.tstop = 0
         logger.debug("default_maxstep on host #%d = %g" % (self.mpi_rank, self.default_maxstep ))
         logger.debug("local_minimum_delay on host #%d = %g" % (self.mpi_rank, local_minimum_delay))
         if self.num_processes > 1:
             assert local_minimum_delay >= self.min_delay, \
                    "There are connections with delays (%g) shorter than the minimum delay (%g)" % (local_minimum_delay, self.min_delay)
Exemple #17
0
 def run(self, simtime):
     """Advance the simulation for a certain time."""
     if not self.running:
         self.running = True
         local_minimum_delay = self.parallel_context.set_maxstep(self.default_maxstep)
         h.finitialize()
         self.tstop = 0
         logger.debug("default_maxstep on host #%d = %g" % (self.mpi_rank, self.default_maxstep ))
         logger.debug("local_minimum_delay on host #%d = %g" % (self.mpi_rank, local_minimum_delay))
         if self.num_processes > 1:
             assert local_minimum_delay >= self.min_delay, \
                    "There are connections with delays (%g) shorter than the minimum delay (%g)" % (local_minimum_delay, self.min_delay)
     self.tstop += simtime
     logger.info("Running the simulation for %g ms" % simtime)
     self.parallel_context.psolve(self.tstop)
    def go(self, sim_time=None):
        """
        Start the simulation once it's been intialized
        """

        self.set_recording()
        h.dt = self.dt
        
        h.finitialize(self.v_init)
        neuron.init()
        if sim_time:
            neuron.run(sim_time)
        else:
            neuron.run(self.sim_time)
        self.go_already = True
Exemple #19
0
def trivial_ecs(scale):
    from neuron import h, crxd as rxd
    import numpy
    import warnings
    warnings.simplefilter("ignore", UserWarning)
    h.load_file('stdrun.hoc')
    tstop = 10
    if scale:   #variable step case
        h.CVode().active(True)
        h.CVode().event(tstop)
    else:           #fixed step case
        h.dt = 0.1

    sec = h.Section() #NEURON requires at least 1 section

    # enable extracellular RxD
    rxd.options.enable.extracellular = True

    # simulation parameters
    dx = 1.0    # voxel size
    L = 9.0     # length of initial cube
    Lecs = 21.0 # lengths of ECS

    # define the extracellular region
    extracellular = rxd.Extracellular(-Lecs/2., -Lecs/2., -Lecs/2.,
                                      Lecs/2., Lecs/2., Lecs/2., dx=dx,
                                      volume_fraction=0.2, tortuosity=1.6)

    # define the extracellular species
    k_rxd = rxd.Species(extracellular, name='k', d=2.62, charge=1,
                        atolscale=scale, initial=lambda nd: 1.0 if 
                        abs(nd.x3d) <= L/2. and abs(nd.y3d) <= L/2. and 
                        abs(nd.z3d) <= L/2. else 0.0)

    # record the concentration at (0,0,0)
    ecs_vec = h.Vector()
    ecs_vec.record(k_rxd[extracellular].node_by_location(0, 0, 0)._ref_value)
    h.finitialize()
    h.continuerun(tstop) #run the simulation
    
    # compare with previous solution 
    ecs_vec.sub(h.Vector(trivial_ecs_data[scale]))
    ecs_vec.abs()
    if ecs_vec.sum() > 1e-9:
        return -1
    return 0
    def min_sim(self, TSTOP=100):
        """
        Launch a minimal simulation to test the model and determine its resting potential empirically
        """
        vrec = h.Vector()
        vrec.record(self.soma(0.5)._ref_v)

        for sec in h.allsec():
            h.finitialize(-65, sec)
            h.fcurrent(sec)
        h.frecord_init()

        while h.t < TSTOP: #Launch a simulation
            h.fadvance()

        vrest = np.array(vrec)[-1]

        return vrest
Exemple #21
0
 def init(self):
     """Set the vm_init from the spin button and prepare the simulator"""
     
     if not self.manager.refs.has_key('VecRef') :
         message = "No vector Created. Create at least one vector to run the simulation"
         logger.info(message)
         self.ui.statusbar.showMessage(message, 3500)
         return False
     else:
         v_init = self.ui.vSpinBox.value()
         # Set the v_init
         h.v_init = v_init
         h.finitialize(v_init)
         h.fcurrent()
     
         # Reset the time in the GUI
         self.ui.time_label.setNum(h.t)
         return True
Exemple #22
0
 def init(self, dt=None, celsius=None, tstop=None, t=None, finit=True):
     """Initialize the simulation.
     
     Parameters
     ----------
     dt : float
         Optionally sets the simulation time step (in msec)
     celsius : float
         Optionally sets the simulation temperature (in degrees C)
     tstop : float
         Optionally sets the simulation stop time (in msec)
     t : float
         Optionally sets the simulation start time (in msec)
     finit : bool
         If True, this method calls NEURON's `finitialize()` routine.
         
         
     See also
     --------
     
     http://www.neuron.yale.edu/neuron/static/new_doc/simctrl/programmatic.html#finitialize
     """
     self._check_active()
     self._check_args(finit=bool)
     if finit and t is not None:
         raise TypeError("Cannot set t when finit==True.")
     
     if dt is not None:
         self.dt = dt
     if celsius is not None:
         self.celsius = celsius
     if tstop is not None:
         self.tstop = tstop
     if t is not None:
         self.t = t
     
     h.dt = self.dt
     h.celsius = self.celsius
     h.t = self.t
     
     if finit:
         h.finitialize()
         self._finitialized = True
         self.t = h.t
Exemple #23
0
def is_blocked(axon):
    v = h.Vector()
    v.record(axon.section_at_x(axon.config['block_test_position'])
        (Axon.middle)._ref_v)

    # initialize the simulation
    h.dt = axon.config['max_time_step']
    tstop = axon.config['integration_time']
    v_init = axon.config['initial_membrane_potential']
    h.finitialize(v_init)
    h.fcurrent()

    # run the simulation
    while h.t < tstop:
        h.fadvance()

    if max(v) >= axon.config['block_test_threshold']:
        return False
    else:
        return True
Exemple #24
0
def main():
    pkj = h.DSB94()
    h.dt = 0.02
    Vrest = -74
    h.celsius = 37
    rec={}
    rec['v'] = h.Vector()
    rec['t'] = h.Vector()
    rec['v'].record(pkj.soma(0.5)._ref_v)  
    rec['t'].record(h._ref_t)
    iclamp = h.IClamp(pkj.soma(0.5))
    iclamp.amp = 0.300
    iclamp.dur = 1000
    iclamp.delay = 0
    h.finitialize(Vrest)
    h.tstop = 700
    h.run()
    plt.plot(rec['t'],rec['v'])
    plt.show()
    from ipdb import set_trace
    set_trace()
def simulate(cell, tstop=1500, vinit=-55):
    ''' simulation control 
    Parameters
    ----------
    cell: NEURON cell
        cell for simulation
    tstop: int (ms)
        simulation time
    vinit: int (mV)
        initialized voltage
    '''
    h.finitialize(vinit)
    balance(cell)
    if h.cvode.active():
        h.cvode.active()
    else:
        h.fcurrent()
    h.frecord_init()
    h.tstop = tstop
    h.v_init = vinit
    h.run()
Exemple #26
0
def test_pop():
    from random import random, choice
    ncells = 100
    cells = [BallStick(random()*0.2+0.9) for i in range(ncells)]
    nclist = []
    for postcell in cells:
        for i in range(20):
            precell = choice(cells)
            nc = precell.connect2target(postcell.synlist[0])
            nc.weight[0] = 0.01
            nc.delay = 0
            nclist.append(nc)
    splist = []
    stims = []
    for (i, cell) in enumerate(cells):
        tvec = h.Vector()
        idvec = h.Vector()
        nc = h.NetCon(cell.axon(1)._ref_v, None, sec=cell.axon)
        nc.record(tvec, idvec, i+1)
        splist.append([tvec, idvec])
    for cell in cells:
        stim = h.IClamp(0.5, sec=cell.soma)
        stim.amp = 0.700
        stim.delay = 600 + 200*random()
        stim.dur = 1000
	stims.append(stim)
    #cvode = h.CVode()
    #cvode.active(1)
    h.dt = 0.1
    h.finitialize(-65)
    tstop = 2000
    while h.t < tstop:
        h.fadvance()
    try:
        import matplotlib.pyplot as plt
        for spikes in splist:
            plt.scatter(spikes[0], spikes[1], marker='.')
        plt.show()
    except ImportError:
        pass
Exemple #27
0
def scalar_bistable(rxdstr):
    if rxdstr == 'rxd':
        from neuron import rxd
    else:
        from neuron import crxd as rxd
    h.load_file('stdrun.hoc')
    s = h.Section(name='s')
    s.nseg = 101
    cyt = rxd.Region(h.allsec())
    c = rxd.Species(cyt, name='c', initial=lambda node: 1 if 0.4 < node.x < 0.6 else 0, d=1)
    r = rxd.Rate(c, -c * (1-c)*(0.3-c))
    h.finitialize()
    h.run()

    #check the results
    result = h.Vector(c.nodes.concentration)
    cmpV = h.Vector(scalar_bistable_data[rxdstr])
    cmpV.sub(result)
    cmpV.abs()
    if cmpV.sum() < 1e-6:
        sys.exit(0) 
    sys.exit(-1)
Exemple #28
0
def simple():
    soma = h.Section()
    soma.insert('pas')
    soma.e_pas = -65
    #soma.g_pas = 1./200e3
    synapse = syn.AMPANMDASynapse(soma, 0.5, 0, 10000)
    synapse.set_presynaptic_spike_times([100])
    h.nmdafactor_AmpaNmda = 0
    rec = {}
    for lbl in 't','vsoma','vapical','vbasal','gampa','gnmda','iampa','inmda':
        rec[lbl] = h.Vector()
    rec['t'].record(h._ref_t)
    rec['vsoma'].record(soma(0.5)._ref_v)
    rec['gampa'].record(synapse.syn._ref_gampa)
    rec['gnmda'].record(synapse.syn._ref_gnmda)
    rec['iampa'].record(synapse.syn._ref_iampa)
    rec['inmda'].record(synapse.syn._ref_inmda)        
    h.load_file('stdrun.hoc')
    h.celsius = 35
    h.cvode_active(1)
    h.cvode.maxstep(10)
    h.tstop = 500
    h.finitialize(soma.e_pas)
    h.run()
    p.subplot(3,1,1)
    p.plot(rec['t'],rec['vsoma'],'k',label='Soma')
    p.subplot(3,1,2)
    p.plot(rec['t'],np.array(rec['gampa'])*1e3,'k',label='AMPA')
    p.plot(rec['t'],np.array(rec['gnmda'])*1e3,'r',label='NMDA')
    p.legend(loc='best')
    p.ylabel('Conductance (nS)')
    p.subplot(3,1,3)
    p.plot(rec['t'],np.array(rec['iampa']),'k',label='AMPA')
    p.plot(rec['t'],np.array(rec['inmda']),'r',label='NMDA')
    p.legend(loc='best')
    p.xlabel('Time (ms)')
    p.ylabel('Current (nA)')
    p.show()
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.6,0.8],    \
                                                              [0.65,0.85],  \
                                                              [0.78,0.82],  \
                                                              [0.85,1.25],  \
                                                              [1.0,2.0],    \
                                                              [1.0,2.0],    \
                                                              [0.0,1.0]]    )

        # 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/17.0,    \
                                        NC_conductance=0.15e-3,     \
                                        S_tau_dep=100               )

                # create a gaba synapse
                make_random_synapse(ns, nc, Syn, sec, 0.0,          \
                                        Type='tmgabaa',             \
                                        NS_interval=1000.0/4.0,     \
                                        NC_conductance=0.45e-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 == 2:
                    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}
Exemple #30
0
cell1_X = h.Vector()
cell1_X.record(cell1(0.5)._ref_xi)
cell1_Xorg = h.Vector()
cell1_Xorg.record(Xorg.nodes(cell1)(0.5)[0]._ref_concentration)
cell1V = h.Vector()
cell1V.record(cell1(0.5)._ref_v)

cell2_X = h.Vector()
cell2_X.record(cell2(0.5)._ref_xi)
cell2_Xorg = h.Vector()
cell2_Xorg.record(Xorg.nodes(cell2)(0.5)[0]._ref_concentration)
cell2V = h.Vector()
cell2V.record(cell2(0.5)._ref_v)

# run and plot the results
h.finitialize(-65)
h.continuerun(1000)
"""
fig = pyplot.figure()
pyplot.subplot(2, 2, 1)
pyplot.plot(t_vec,cell1_X, label='cyt')
pyplot.plot(t_vec,cell1_Xorg, label='org')
pyplot.legend()
pyplot.xlabel('t (ms)')
pyplot.ylabel('cell 1 x (mM)')

pyplot.subplot(2, 2, 2)
pyplot.plot(t_vec,cell2_X, label='cyt')
pyplot.plot(t_vec,cell2_Xorg, label='org')
pyplot.xlabel('t (ms)')
pyplot.ylabel('cell 2 x (mM)')
Exemple #31
0
def simulate(tau_facil,
             tau_rec,
             stim_freq,
             celltype,
             tau_1=0.3,
             tau_2=0.6,
             u0=0.078,
             sampling_interval=0.5,
             v_clamp=-70.42,
             sec='proxd'):
    """Simulates a frequency stimulation of the tmgexp2syn meachnism onto a
    neuron and measure the conductance at the soma.

    Parameters
    ----------
    tau_facil : numeric
        facilitation time constant of the tmgexp2syn mechanism
        
    tau_rec : numeric
        recovery time constant of the tmgexp2syn mechanism
        
    stim_freq : numeric
        stimulation frequency in Hz
        
    celltype : ouropy.GenNeuron
        A class that inherits from ouropy.GenNeuron
        
    tau_1 : numeric
        Synaptic rise time
        
    tau_2 : numeric
        Synaptic decay time
        
    u0 : float
        The u0 parameters as specified in tmgexp2syn
        
    sampling_interval : numeric
        The sampling interval in ms
        
    v_clamp : numeric
        Holding potential of the
        
    Returns
    -------
    peaks_norm : ndarray
        Peak conductances normalized to first peak
    
    garr_norm : ndarray
        Conductance array normalized to first peak
    """
    # Resolve simulation hyperparameters
    left_pad, right_pad = 50, 100  # in ms
    simdur = left_pad + right_pad + 10 * (1000 / stim_freq)
    # Create cell
    mycell = celltype()
    # Create synapse
    syn = h.tmgexp2syn(mycell.get_segs_by_name(sec)[0](0.5))
    syn.tau_1 = tau_1
    syn.tau_2 = tau_2
    syn.tau_facil = tau_facil
    syn.tau_rec = tau_rec
    syn.u0 = u0
    syn.e = 0
    # Create stimulation
    stim_period_ms = 1000 / stim_freq
    stim = h.NetStim()
    stim.interval = stim_period_ms
    stim.start = left_pad
    stim.number = 10
    nc = h.NetCon(stim, syn)
    nc.weight[0] = 0.001
    # Create voltage clamp
    c = h.SEClamp(mycell.soma(0.5))
    c.dur1 = simdur
    c.amp1 = v_clamp
    c.rs = 0.1
    # Create recording vector
    ivec = h.Vector()
    ivec.record(c._ref_i)
    # Start simulation
    sample_period_ms = sampling_interval
    h.cvode.active(0)
    h.finitialize(-70.42)
    h.t = -2000
    h.secondorder = 0
    h.dt = 10
    while h.t < -100:
        h.fadvance()
    h.secondorder = 0
    h.t = 0
    h.dt = sample_period_ms
    h.steps_per_ms = 1.0 / h.dt
    h.frecord_init()  # Necessary after changing t to restart the vectors
    while h.t < simdur:
        h.fadvance()
    # Get Peaks from output

    iarr = np.array(ivec)
    garr = (iarr - iarr[0:50].mean()) / v_clamp
    stim_dtp = int(np.around(stim.interval / sampling_interval))
    pad_dtp = int(left_pad / sampling_interval)
    t_stim = np.arange(pad_dtp, stim_dtp * 11 + pad_dtp, stim_dtp)
    #dtp_stim = np.array(t_stim / sampling_interval, dtype=np.int)
    dtp_stim = np.array(t_stim, dtype=np.int)
    gvec_split = np.array(np.split(garr, dtp_stim)[1:-1])

    peaks = gvec_split.max(axis=1)
    peaks_norm = peaks / peaks[0]
    garr_norm = garr / peaks[0]

    return peaks_norm, garr_norm
Exemple #32
0
def measure_gap_junction_coupling (env, template_class, tree, v_init, cell_dict={}):
    
    h('objref gjlist, cells, Vlog1, Vlog2')

    pc = env.pc
    h.cells  = h.List()
    h.gjlist = h.List()
    
    cell1 = cells.make_neurotree_cell (template_class, neurotree_dict=tree)
    cell2 = cells.make_neurotree_cell (template_class, neurotree_dict=tree)

    h.cells.append(cell1)
    h.cells.append(cell2)

    ggid        = 20000000
    source      = 10422930
    destination = 10422670
    weight      = 5.4e-4
    srcsec   = int(cell1.somaidx.x[0])
    dstsec   = int(cell2.somaidx.x[0])

    stimdur     = 500
    tstop       = 2000
    
    pc.set_gid2node(source, int(pc.id()))
    nc = cell1.connect2target(h.nil)
    pc.cell(source, nc, 1)
    soma1 = list(cell1.soma)[0]

    pc.set_gid2node(destination, int(pc.id()))
    nc = cell2.connect2target(h.nil)
    pc.cell(destination, nc, 1)
    soma2 = list(cell2.soma)[0]

    stim1 = h.IClamp(soma1(0.5))
    stim1.delay = 250
    stim1.dur = stimdur
    stim1.amp = -0.1

    stim2 = h.IClamp(soma2(0.5))
    stim2.delay = 500+stimdur
    stim2.dur = stimdur
    stim2.amp = -0.1

    log_size = old_div(tstop,h.dt) + 1
    
    h.tlog = h.Vector(log_size,0)
    h.tlog.record (h._ref_t)

    h.Vlog1 = h.Vector(log_size)
    h.Vlog1.record (soma1(0.5)._ref_v)

    h.Vlog2 = h.Vector(log_size)
    h.Vlog2.record (soma2(0.5)._ref_v)


    gjpos = 0.5
    neuron_utils.mkgap(env, cell1, source, gjpos, srcsec, ggid, ggid+1, weight)
    neuron_utils.mkgap(env, cell2, destination, gjpos, dstsec, ggid+1, ggid, weight)

    pc.setup_transfer()
    pc.set_maxstep(10.0)

    h.stdinit()
    h.finitialize(v_init)
    pc.barrier()

    h.tstop = tstop
    pc.psolve(h.tstop)
        rval = -1
    return rval


_callback = nonvint_block_prototype(nonvint_block)


def activate_callback(activate):
    if (activate):
        set_nonvint_block(_callback)
    else:
        unset_nonvint_block(_callback)


if __name__ == '__main__':
    exec(test)  # see above string

    s = h.Section()
    print("fixed step finitialize")
    h.finitialize(0)
    print("fixed step fadvance")
    h.fadvance()

    h.load_file('stdgui.hoc')
    print("cvode active")
    h.cvode_active(1)
    print("cvode step finitialize")
    h.finitialize(0)
    print("cvode fadvance")
    h.fadvance()
def main(       cell_type=None,
                mdl_ID=0         ): 
    
    modeldir    =   './Striatal_network_models/{}/{}'.format(cell_type, cells_dirs[cell_type][mdl_ID])
    
    par         =   '{}/parameters_with_modulation.json'.format(modeldir)
    mech        =   '{}/mechanisms.json'.format(modeldir)
    protocols   =   '{}/protocols.json'.format(modeldir)
    morphology  =   glob.glob(modeldir+'/*.swc')[0] # ONLY 1 swc file / model allowed.
    
        
    # initiate cell 
    cell = build.CELL(  params=par,
                        mechanisms=mech,
                        morphology=morphology,
                        replace_axon=True,
                        N=40.0,
                        ffactor=ffactor  )
    
    #  ADD SPINES----
    SPINES = {}
    ID = 0
    for sec in cell.dendlist:
        SPINES[sec.name()] = {}
        for i,seg in enumerate(sec):
            for j in range(10):
                SPINES[sec.name()][ID] = spine.Spine(h,sec,seg.x)
                ID += 1
    
    print(ID)
    #return [1,1]
    #h.topology()          
      
    # THIS PART IS OPTIONAL oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
    # set input here
    
    # set current injection
    with open(protocols) as file:
        prot = json.load(file)
    
    # select first spiking prot
    all_keys    = sorted(prot.keys())
    key         = all_keys[0]
    
    i=1
    while 'sub' in key:
        key = all_keys[i]
        i += 1
    print(key)
    
    stim        =   h.IClamp(0.5, sec=cell.soma)
    s0          =   h.IClamp(0.5, sec=cell.soma)
    
    for stim_prot, stimuli, j in zip(prot[key]['stimuli'], [stim,s0], [0,1]): 
        stimuli.amp    =   stim_prot['amp']
        stimuli.delay  =   [200,0][j]
        stimuli.dur    =   stim_prot['duration']
    
    
    # oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
     
    # record vectors: set recordings here
    tm  = h.Vector()
    tm.record(h._ref_t)
    vm  = h.Vector()
    vm.record(cell.soma(0.5)._ref_v)
    
    tstop  = 600    # sim time (ms)
    
    h.finitialize(cell.v_init)
    
    # run simulation
    while h.t < tstop:
        h.fadvance()
        
    # save output ------------------------------------------------------------------------
    time    = tm.to_python()
    voltage = vm.to_python()
    
    return [time, voltage]
Exemple #35
0
# record currents
inaf = h.Vector().record(soma(0.5)._ref_ina_naf)
ikdr = h.Vector().record(soma(0.5)._ref_ik_kdr)
isk = h.Vector().record(soma(0.5)._ref_ik_sk)
inal = h.Vector().record(soma(0.5)._ref_ina_nal)
ika = h.Vector().record(soma(0.5)._ref_ik_ka)
ibk = h.Vector().record(soma(0.5)._ref_ik_bk)
iih = h.Vector().record(soma(0.5)._ref_ih_ih)
#ica = h.Vector().record(soma(0.5)._ref_ica)
ican = h.Vector().record(soma(0.5)._ref_ica_can)
icar = h.Vector().record(soma(0.5)._ref_ica_car)

# record intracellular ca
#caDat = h.Vector().record(ca.nodes[0]._ref_concentration)

h.finitialize(-55)
h.continuerun(1000)

# plots
plt.subplot(3, 1, 1)
plt.plot(t, v)
plt.ylabel('v (mV)')

plt.subplot(3, 1, 2)
plt.plot(t, inaf)
plt.plot(t, ikdr)
plt.plot(t, isk)
plt.plot(t, inal)
plt.plot(t, ika)
plt.plot(t, ibk)
plt.plot(t, iih)
Exemple #36
0
 def run(tstop):
     pc.set_maxstep(10)
     h.finitialize()
     pc.psolve(tstop)
Exemple #37
0
def _simulate_single_trial(neuron_net, trial_idx):
    """Simulate one trial."""

    from .dipole import Dipole

    global _PC, _CVODE

    h.load_file("stdrun.hoc")

    rank = _get_rank()
    nhosts = _get_nhosts()

    # Now let's simulate the dipole

    _PC.barrier()  # sync for output to screen
    if rank == 0:
        print("running trial %d on %d cores" % (trial_idx + 1, nhosts))

    # Set tstop before instantiating any classes
    h.tstop = neuron_net.net.params['tstop']
    h.dt = neuron_net.net.params['dt']  # simulation duration and time-step
    h.celsius = neuron_net.net.params['celsius']  # 37.0 - set temperature

    times = neuron_net.net.cell_response.times

    # sets the default max solver step in ms (purposefully large)
    _PC.set_maxstep(10)

    # initialize cells to -65 mV, after all the NetCon
    # delays have been specified
    h.finitialize()

    def simulation_time():
        print('Simulation time: {0} ms...'.format(round(h.t, 2)))

    if rank == 0:
        for tt in range(0, int(h.tstop), 10):
            _CVODE.event(tt, simulation_time)

    h.fcurrent()

    # initialization complete, but wait for all procs to start the solver
    _PC.barrier()

    # actual simulation - run the solver
    _PC.psolve(h.tstop)

    _PC.barrier()

    # these calls aggregate data across procs/nodes
    neuron_net.aggregate_data()
    _PC.allreduce(neuron_net.dipoles['L5_pyramidal'], 1)
    _PC.allreduce(neuron_net.dipoles['L2_pyramidal'], 1)

    # aggregate the currents and voltages independently on each proc
    vsoma_list = _PC.py_gather(neuron_net._vsoma, 0)
    isoma_list = _PC.py_gather(neuron_net._isoma, 0)

    # combine spiking data from each proc
    spike_times_list = _PC.py_gather(neuron_net._spike_times, 0)
    spike_gids_list = _PC.py_gather(neuron_net._spike_gids, 0)

    # only rank 0's lists are complete

    if rank == 0:
        for spike_vec in spike_times_list:
            neuron_net._all_spike_times.append(spike_vec)
        for spike_vec in spike_gids_list:
            neuron_net._all_spike_gids.append(spike_vec)
        for vsoma in vsoma_list:
            neuron_net._vsoma.update(vsoma)
        for isoma in isoma_list:
            neuron_net._isoma.update(isoma)

    _PC.barrier()  # get all nodes to this place before continuing

    dpl_data = np.c_[np.array(neuron_net.dipoles['L2_pyramidal'].to_python()) +
                     np.array(neuron_net.dipoles['L5_pyramidal'].to_python()),
                     np.array(neuron_net.dipoles['L2_pyramidal'].to_python()),
                     np.array(neuron_net.dipoles['L5_pyramidal'].to_python())]

    dpl = Dipole(times, dpl_data)

    return dpl
Exemple #38
0
def run_model(cell_index, ci):

    # 1s low input; 0.3s ramping input; 0.2s high input
    tstop = 1500
    modOnTime = 1000
    nbg = 5
    tau = 300
    conditions = ['ACh+DA', 'ACh', 'DA', 'ctrl']
    c = conditions[ci]

    # channel distribution parameter library
    path = '../Libraries'
    with open('{}/D2_34bestFit_updRheob.pkl'.format(path), 'rb') as f:
        model_sets = pickle.load(f, encoding="latin1")

    parameters = model_sets[cell_index]['variables']
    par = '../params_iMSN.json'
    morphology = '../Morphologies/WT-dMSN_P270-20_1.02_SGA1-m24.swc'

    cell = build.MSN(  params=par,                  \
                       morphology=morphology,       \
                       variables=parameters         )

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

    # transient to play
    transient = h.Vector([
        use.alpha(ht, modOnTime, 1, tau) if ht >= modOnTime else 0
        for ht in np.arange(0, tstop, h.dt)
    ])

    # result dict
    res = {}

    for i in range(20):
        res[i] = {}
        # draw random factors
        modulation_DA = {
            'intr': {
                'naf': np.random.uniform(0.95, 1.1),
                'kaf': np.random.uniform(1.0, 1.1),
                'kas': np.random.uniform(1.0, 1.1),
                'kir': np.random.uniform(0.8, 1.0),
                'can': np.random.uniform(0.9, 1.0),
                'car': np.random.uniform(0.6, 0.8),
                'cal12': np.random.uniform(0.7, 0.8),
                'cal13': np.random.uniform(0.7, 0.8)
            },
            'syn': {
                'NMDA': np.random.uniform(0.85, 1.05),
                'AMPA': np.random.uniform(0.7, 0.9),
                'GABA': np.random.uniform(0.90, 1.1)
            }
        }
        modulation_ACh = {
            'intr': {
                'naf': np.random.uniform(1.0, 1.2),
                'kir': np.random.uniform(0.5, 0.7),
                'can': np.random.uniform(0.65, 0.85),
                'cal12': np.random.uniform(0.3, 0.7),
                'cal13': np.random.uniform(0.3, 0.7),
                'Im': np.random.uniform(0.0, 0.4)
            },
            'syn': {
                'NMDA': np.random.uniform(1.0, 1.05),
                'AMPA': np.random.uniform(0.99, 1.01),
                'GABA': np.random.uniform(0.99, 1.01)
            }
        }

        res[i][ci] = {'factors': {'da': modulation_DA, 'ach': modulation_ACh}}

        # ACh factor sets used == 0 and 2 (since giving less inward rectification and higher excitability)
        V = {}
        for key in modulation_ACh['intr']:
            V[key] = transient
        for key in ['glut', 'gaba']:
            V[key] = transient

        # Master seed -> reset for all factor combinations
        #np.random.seed(seed=1000) # TODO no seed... will bg be different over workers?

        # set bg (constant+ramping).
        fgaba = 24.0
        Syn, nc, ns, mapper = use.set_ramping_stimuli(cell, [],
                                                      low=modOnTime,
                                                      high=modOnTime + tau)
        RAMP = {'s': Syn.copy(), 'nc': nc.copy(), 'ns': ns.copy}
        Syn, nc, ns = use.set_bg_noise(cell, fglut=12.0, fgaba=fgaba)

        # Clean
        DA = modulate.DA(cell,
                         modulation_DA['intr'],
                         modulation='uniform',
                         play=V,
                         syn_dict=modulation_DA['syn'])
        ACh = modulate.ACh(cell,
                           modulation_ACh['intr'],
                           shift_kaf=0,
                           play=V,
                           syn_dict=modulation_ACh['syn'])

        for bg in range(nbg):
            print(cell_index, c, bg)
            # finalize and run
            h.finitialize(-80)
            while h.t < tstop:
                h.fadvance()
            # downsample data and store in array
            if not 'time' in res:
                res['time'] = [t for ind, t in enumerate(tm) if ind % 4 == 0]
            res[i][bg] = [vm[ind] for ind, t in enumerate(tm) if ind % 4 == 0]

    # save
    with open(
            'inVivo_ramping_{}_{}_model{}.json'.format(conditions[ci], tag,
                                                       cell_index), 'wt') as f:
        json.dump(res, f, indent=4)
Exemple #39
0
                                                           weight=args.gmax)
 if args.rec <= 0:
     rec = [(n, data['orig']) for n, data in g.nodes(data=True)
            if data['orig'] is not None]
 else:
     rec = [(n, g.nodes[n]['orig']) for n in nu.select_good_nodes_by_sid(
         g, stype_node_map.keys(), [args.rec] * len(stype_node_map))]
 syn = zip(synnodes, synsecs)
 rec = list(set(rec + syn))
 recnodes, recsecs = zip(*rec)
 h.tstop = t_stop
 t_vec = h.Vector(np.arange(0, h.tstop, 10 * h.dt))
 # Record data
 tabs = [nu.setup_recording(sec, field='v', t=t_vec) for sec in recsecs]
 ts = datetime.now()
 h.finitialize(args.Em)
 h.fcurrent()
 while h.t < h.tstop:
     h.fadvance()
 # h.run()
 sys.stdout.flush()
 te = datetime.now()
 delta = te - ts
 print('Time for', h.tstop * 1e-3, 's simulation =',
       delta.days * 86400 + delta.seconds + 1e-6 * delta.microseconds)
 if args.outfile == '':
     outfilename = 'data/Vm_inhpoisson_stim_series_{}.h5'.format(
         ts.strftime('%Y%m%d_%H%M%S'))
 else:
     outfilename = args.outfile
 with h5.File(outfilename) as fd:
Exemple #40
0
chans = {'nav1.7': ['a1p7', 'b1p7', 'c1p7'], 'nav1.8': ['a1p8', 'b1p8', 'c1p8']}
traces = ['minf', 'mtau', 'hinf', 'htau']
data = {}

for nav in chans:
    for chan in chans[nav]:
        data[chan] = {}
        for trace in traces:
            data[chan][trace] = []
        soma.insert(chan)


vs = np.linspace(-70,30,100)
for v in vs:
    h.finitialize(v)
    data['a1p7']['minf'].append(getval( soma(0.5), 'a1p7', 'minf')
    data['a1p7']['mtau'].append(soma(0.5).a1p7.mtau)
    data['a1p7']['hinf'].append(soma(0.5).a1p7.hinf)
    data['a1p7']['htau'].append(soma(0.5).a1p7.htau)

    data['a1p8']['minf'].append(soma(0.5).a1p8.minf)
    data['a1p8']['mtau'].append(soma(0.5).a1p8.mtau)
    data['a1p8']['hinf'].append(soma(0.5).a1p8.hinf)
    data['a1p8']['htau'].append(soma(0.5).a1p8.htau)

    data['b1p7']['minf'].append(soma(0.5).b1p7.minf)
    data['b1p7']['mtau'].append(soma(0.5).b1p7.mtau)
    data['b1p7']['hinf'].append(soma(0.5).b1p7.hinf)
    data['b1p7']['htau'].append(soma(0.5).b1p7.htau)
Exemple #41
0
 def run(tstop):
     spiketime.resize(0)
     gidvec.resize(0)
     pc.set_maxstep(10)
     h.finitialize()
     pc.psolve(tstop)
Exemple #42
0
    def plot_voltage(self,
                     ax=None,
                     delay=2,
                     duration=100,
                     dt=0.2,
                     amplitude=1,
                     show=True):
        """Plot voltage on soma for an injected current

        Parameters
        ----------
        ax : instance of matplotlib axis | None
            An axis object from matplotlib. If None,
            a new figure is created.
        delay : float (in ms)
            The start time of the injection current.
        duration : float (in ms)
            The duration of the injection current.
        dt : float (in ms)
            The integration time step
        amplitude : float (in nA)
            The amplitude of the injection current.
        show : bool
            Call plt.show() if True. Set to False if working in
            headless mode (e.g., over a remote connection).
        """
        import matplotlib.pyplot as plt
        from neuron import h
        h.load_file('stdrun.hoc')

        soma = self.soma

        h.tstop = duration
        h.dt = dt
        h.celsius = 37

        iclamp = h.IClamp(soma(0.5))
        iclamp.delay = delay
        iclamp.dur = duration
        iclamp.amp = amplitude

        v_membrane = h.Vector().record(self.soma(0.5)._ref_v)
        times = h.Vector().record(h._ref_t)

        print('Simulating soma voltage')
        h.finitialize()

        def simulation_time():
            print('Simulation time: {0} ms...'.format(round(h.t, 2)))

        for tt in range(0, int(h.tstop), 10):
            h.CVode().event(tt, simulation_time)

        h.continuerun(duration)
        print('[Done]')

        if ax is None:
            fig, ax = plt.subplots(1, 1)
        ax.plot(times, v_membrane)
        ax.set_xlabel('Time (ms)')
        ax.set_ylabel('Voltage (mV)')
        if show:
            plt.show()
Exemple #43
0
def setup_transfer_verify():
    if rank == 0:
        print("setup_transfer_verify")
    h.finitialize(-65)
    frac = rank2frac(rank)
    for sec in h.allsec():
        sec.v = -1 - frac
    for seg in src2sids:
        seg.v = src2sids[seg][0] + frac
    for tar in tar2sid:
        tar.vgap = -2.0

    # do the parallel transfer
    h.finitialize()
    # note that FInitializeHandlers may destroy v but the transfer takes place
    # before any callback except type 3. So all the targets should have proper
    # value of firstsrcsid.rank

    # test 0. No transferred values are negative
    for tar in tar2sid:
        if tar.vgap < 0.0:
            print(("%d %s sid=%d vgap=%g" %
                   (rank, tar.hname(), tar2sid[tar], tar.vgap)))
            raise RuntimeError
    # test 1. All the transferred values make sense in terms of rank
    for tar in tar2sid:
        if frac2rank(tar.vgap) >= nhost:
            print(("%d %s has invalid rank code %d with value %g" %
                   (rank, tar.hname(), frac2rank(tar.vgap), tar.vgap)))
            raise RuntimeError

    # test 2. All the targets for a given sid should have the same value
    for sid in sid2tars:
        x0 = sid2tars[sid][0].vgap
        for tar in sid2tars[sid]:
            if tar.vgap != x0:
                print(("%d %s %g != %g %s" % (rank, sid2tars[sid][0].hname(),
                                              x0, tar.vgap, tar.hname())))
                raise RuntimeError

    # test 3. Send sid and vgap's sid back to rank it came from and verify on
    # the source rank that those sid's exist and have the same source
    # Because of test 2, only need to test first target of an sid
    data = [None] * nhost
    for sid, segs in list(sid2tars.items()):
        r, ssid = decode_vgap_val(segs[0].vgap)
        if data[r] == None:
            data[r] = []
        data[r].append((sid, ssid))

    # pr(data, 'source')
    data = pc.py_alltoall(data)
    # pr(data, 'destination')

    for r, x in enumerate(data):
        if x:
            for pair in x:
                for sid in pair:
                    if sid not in sid2src:
                        print((
                            "%d target sid %d from %d not associated with source here"
                            % (rank, sid, r)))
                        raise RuntimeError
Exemple #44
0
 def initialize():
     h.finitialize()
     h.run()
for run in runs:
    nw = net_tunedrev.TunedNetwork(10000, temporal_patterns[0 + run:24 + run],
                                   PP_to_GCs[0 + run:24 + run],
                                   PP_to_BCs[0 + run:24 + run])

    # Attach voltage recordings to all cells
    nw.populations[0].voltage_recording(range(2000))
    nw.populations[1].voltage_recording(range(60))
    nw.populations[2].voltage_recording(range(24))
    nw.populations[3].voltage_recording(range(24))
    # Run the model
    """Initialization for -2000 to -100"""
    h.cvode.active(0)
    dt = 0.1
    h.steps_per_ms = 1.0 / dt
    h.finitialize(-60)
    h.t = -2000
    h.secondorder = 0
    h.dt = 10
    while h.t < -100:
        h.fadvance()

    h.secondorder = 2
    h.t = 0
    h.dt = 0.1
    """Setup run control for -100 to 1500"""
    h.frecord_init()  # Necessary after changing t to restart the vectors

    while h.t < 600:
        h.fadvance()
    print("Done Running")
Exemple #46
0
 def setup_sim(self):
     h.dt = self.simParams.dt
     h.tstop = self.simParams.tstop
     h.celsius = self.simParams.celsius
     h.finitialize(self.simParams.v_init)
Exemple #47
0
syn.onset = 5.0
syn.tau = 0.1
syn.gmax = 0.05

cvode = h.CVode()
cvode.active(1)
cvode.atol(1.0e-5)


a = []
b = np.zeros(4)
dt = 0.01
tstop = 20
v_init = -65

h.finitialize(v_init)
while h.t < tstop:
    cvode.solve() #cvode.solve() -> calculate by defalt steps | cvode.solve(h.t+dt) -> calculate by dt steps
    b[0] = h.t
    b[1] = soma(0.5).v
    b[2] = ap_dend(0.1).v
    b[3] = ap_dend(0.9).v
    print '%lf,%lf,%lf,%lf' %(b[0],b[1],b[2],b[3])
    a.append(copy.deepcopy(b))
a=np.array(a)
print 'Calculation Complete.'
for i in range(1,4):
    plt.plot(a[:,0],a[:,i])

plt.xlim([0,tstop])
plt.ylim([-100,100])
Exemple #48
0
            self.somaV = h.Vector()
            self.somaV.record(self.soma(0.5)._ref_v, rec)


# Randomly distribute the neurons
all_neurons = [
    Neuron(
        (numpy.random.random() * 2.0 - 1.0) * (Lx / 2.0),
        (numpy.random.random() * 2.0 - 1.0) * (Ly / 2.0),
        (numpy.random.random() * 2.0 - 1.0) * (Lz / 2.0),
        100,
    ) for i in range(0, Ncell)
]

# initialize and set the intracellular concentrations
h.finitialize(-70)

h.dt = 1  # use a large time step as we are not focusing on spiking behaviour
# but on slower diffusion

h.continuerun(100)

if __name__ == "__main__":
    from matplotlib import pyplot

    pyplot.imshow(k[ecs].states3d.mean(2), extent=k[ecs].extent("xy"))
    for sec in h.allsec():
        pyplot.plot(
            [sec.x3d(i) for i in range(sec.n3d())],
            [sec.y3d(i) for i in range(sec.n3d())],
            "o",
Exemple #49
0
"""

from matplotlib.pyplot import figure, show

from neuron import h

from CA3Neuronlibrary import *

from CA3simulations import HocVector

h.load_file('stdrun.hoc')
h.v_init = -62.94
h.tstop = 50
h.dt = 1/5.

h.finitialize(-75)

# cell with morphology and biophysics
mycell = create_cell(CA3NeuronJonas)

# stimulator
stim = h.IClamp(0.5, sec= mycell.dend[141])
stim.amp = .7
stim.dur = 5 
stim.delay = 10 

# Load HocVectors
soma_AP = HocVector(seg = mycell.soma(0.5)) 
dend_AP = HocVector(seg = mycell.dend[141](0.5)) 

# run simulation (stimulate in the dendrite)
Exemple #50
0
from neuron import h
from neuron.units import ms, mV
import matplotlib.pyplot as plt
from ring import Ring

ring = Ring()

pc = h.ParallelContext()
pc.set_maxstep(10 * ms)

t = h.Vector().record(h._ref_t)
h.finitialize(-65 * mV)
pc.psolve(100 * ms)

# send all spike time data to node 0
local_data = {cell._gid: list(cell.spike_times) for cell in ring.cells}
all_data = pc.py_alltoall([local_data] + [None] * (pc.nhost() - 1))

if pc.id() == 0:
    # combine the data from the various processes
    data = {}
    for process_data in all_data:
        data.update(process_data)
    # plot it
    plt.figure()
    for i, spike_times in data.items():
        plt.vlines(spike_times, i + 0.5, i + 1.5)
    plt.show()

pc.barrier()
pc.done()
def go():
    h.finitialize(v_init)
    while h.t < tstop:
        h.fadvance()
Exemple #52
0
    def run(self, t_max, downsample=1,
            record_from_syns=False, record_from_iclamps=False, record_from_vclamps=False,
            record_from_channels=False, record_v_deriv=False, record_concentrations=[],
            pprint=False):
        """
        Run the NEURON simulation. Records at all locations stored
        under the name 'rec locs' on `self` (see `MorphTree.storeLocs()`)

        Parameters
        ----------
        t_max: float
            Duration of the simulation
        downsample: int (> 0)
            Records the state of the model every `downsample` time-steps
        record_from_syns: bool (default ``False``)
            Record currents of synapstic point processes (in `self.syns`).
            Accessible as `np.ndarray` in the output dict under key 'i_syn'
        record_from_iclamps: bool (default ``False``)
            Record currents of iclamps (in `self.iclamps`)
            Accessible as `np.ndarray` in the output dict under key 'i_clamp'
        record_from_vclamps: bool (default ``False``)
            Record currents of vclamps (in `self.vclamps`)
            Accessible as `np.ndarray` in the output dict under key 'i_vclamp'
        record_from_channels: bool (default ``False``)
            Record channel state variables from `neat` defined channels in `self`,
            at locations stored under 'rec locs'
            Accessible as `np.ndarray` in the output dict under key 'chan'
        record_v_deriv: bool (default ``False``)
            Record voltage derivative at locations stored under 'rec locs'
            Accessible as `np.ndarray` in the output dict under key 'dv_dt'
        record_from_concentrations: bool (default ``False``)
            Record ion concentration at locations stored under 'rec locs'
            Accessible as `np.ndarray` in the output dict with as key the ion's
            name

        Returns
        -------
        dict
            Dictionary with the results of the simulation. Contains time and
            voltage as `np.ndarray` at locations stored under the name '
            rec locs', respectively with keys 't' and 'v_m'. Also contains
            traces of other recorded variables if the option to record them was
            set to ``True``
        """
        assert isinstance(downsample, int) and downsample > 0
        # simulation time recorder
        res = {'t': h.Vector()}
        res['t'].record(h._ref_t)
        # voltage recorders
        res['v_m'] = []
        for loc in self.getLocs('rec locs'):
            res['v_m'].append(h.Vector())
            res['v_m'][-1].record(self.sections[loc['node']](loc['x'])._ref_v)
        # synapse current recorders
        if record_from_syns:
            res['i_syn'] = []
            for syn in self.syns:
                res['i_syn'].append(h.Vector())
                res['i_syn'][-1].record(syn._ref_i)
        # current clamp current recorders
        if record_from_iclamps:
            res['i_clamp'] = []
            for iclamp in self.iclamps:
                res['i_clamp'].append(h.Vector())
                res['i_clamp'][-1].record(iclamp._ref_i)
        # voltage clamp current recorders
        if record_from_vclamps:
            res['i_vclamp'] = []
            for vclamp in self.vclamps:
                res['i_vclamp'].append(h.Vector())
                res['i_vclamp'][-1].record(vclamp._ref_i)
        # channel state variable recordings
        if record_from_channels:
            res['chan'] = {}
            channel_names = self.getChannelsInTree()
            for channel_name in channel_names:
                res['chan'][channel_name] = {str(var): [] for var in self.channel_storage[channel_name].statevars}
                for loc in self.getLocs('rec locs'):
                    for ind, varname in enumerate(self.channel_storage[channel_name].statevars):
                        var = str(varname)
                        # assure xcoordinate is refering to proper neuron section (not endpoint)
                        xx = loc['x']
                        if xx < 1e-3: xx += 1e-3
                        elif xx > 1. - 1e-3: xx -= 1e-3
                        # create the recorder
                        try:
                            rec = h.Vector()
                            exec('rec.record(self.sections[loc[0]](xx).' + mechname[channel_name] + '._ref_' + str(var) +')')
                            res['chan'][channel_name][var].append(rec)
                        except AttributeError:
                            # the channel does not exist here
                            res['chan'][channel_name][var].append([])
        if len(record_concentrations) > 0:
            for c_ion in record_concentrations:
                res[c_ion] = []
                for loc in self.getLocs('rec locs'):
                    res[c_ion].append(h.Vector())
                    exec('res[c_ion][-1].record(self.sections[loc[\'node\']](loc[\'x\'])._ref_' + c_ion + 'i)')
        # record voltage derivative
        if record_v_deriv:
            res['dv_dt'] = []
            for ii, loc in enumerate(self.getLocs('rec locs')):
                res['dv_dt'].append(h.Vector())
                # res['dv_dt'][-1].deriv(res['v_m'][ii], self.dt)

        # initialize
        # neuron.celsius=37.
        h.finitialize(self.v_init)
        h.dt = self.dt

        # simulate
        if pprint: print('>>> Simulating the NEURON model for ' + str(t_max) + ' ms. <<<')
        start = time.process_time()
        neuron.run(t_max + self.t_calibrate)
        stop = time.process_time()
        if pprint: print('>>> Elapsed time: ' + str(stop-start) + ' seconds. <<<')
        runtime = stop-start

        # compute derivative
        if 'dv_dt' in res:
            for ii, loc in enumerate(self.getLocs('rec locs')):
                res['dv_dt'][ii].deriv(res['v_m'][ii], h.dt, 2)
                res['dv_dt'][ii] = np.array(res['dv_dt'][ii])[self.indstart:][::downsample]
            res['dv_dt'] = np.array(res['dv_dt'])
        # cast recordings into numpy arrays
        res['t'] = np.array(res['t'])[self.indstart:][::downsample] - self.t_calibrate
        for key in set(res.keys()) - {'t', 'chan', 'dv_dt'}:
            if key in res and len(res[key]) > 0:
                res[key] = np.array([np.array(reslist)[self.indstart:][::downsample] \
                                     for reslist in res[key]])
                if key in ('i_syn', 'i_clamp', 'i_vclamp'):
                    res[key] *= -1.
        # cast channel recordings into numpy arrays
        if 'chan' in res:
            for channel_name in channel_names:
                channel = self.channel_storage[channel_name]
                for ind0, varname in enumerate(channel.statevars):
                    var = str(varname)
                    for ind1 in range(len(self.getLocs('rec locs'))):
                        res['chan'][channel_name][var][ind1] = \
                                np.array(res['chan'][channel_name][var][ind1])[self.indstart:][::downsample]
                        if len(res['chan'][channel_name][var][ind1]) == 0:
                            res['chan'][channel_name][var][ind1] = np.zeros_like(res['t'])
                    res['chan'][channel_name][var] = \
                            np.array(res['chan'][channel_name][var])
                # compute P_open
                # sv = np.zeros((len(channel.statevars), len(self.getLocs('rec locs')), len(res['t'])))
                sv = {}
                for varname in channel.statevars:
                    var = str(varname)
                    sv[var] = res['chan'][channel_name][var]
                res['chan'][channel_name]['p_open'] = channel.computePOpen(res['v_m'], **sv)

        return res
Exemple #53
0
def get_base_vm_cli(neuron_model=None, default_cli=4, **kwargs):
    """
    Determine steady-state internal chloride concentration by
    1) instantiating a class that extends BaseNeuron (NOTE: class should not have spiking at default values)
    2) adding KCC2 using the add_kcc2() method
    3) setting [Cl]_i to an arbitrary value (can be set in method invocation)
    4) running a fast simulation for a long time
    5) checking if chloride is at steady state (repeat 4 until it is)
    6) return steady state Vm and [Cl]_i

    :param neuron_model: class extending BaseNeuron
    :param default_cli: arbitrary value of [Cl]_i hopefully close to steady state
    :return: steady state Vm and [Cl]_i
    """
    from baseneuron import BaseNeuron
    remove_kcc2 = False
    if neuron_model is None:
        neuron_model = BaseNeuron
    if isinstance(neuron_model, BaseNeuron):
        # is instantiation of class
        base = neuron_model
        if not base.kcc2_inserted:
            base.add_kcc2()
            remove_kcc2 = True
        base.set_cl(default_cli)

    else:
        # is BaseNeuron class (or child class)
        base = neuron_model(**kwargs)
        base.add_kcc2()
        base.set_cl(default_cli)
    h.tstop = 50000
    h.useCV()
    h.finitialize(-65)

    h.run()

    def at_steady_state(continue_dt):
        """
        check if [Cl]_i is at steady state
        :param continue_dt: amount of time to run
        :return: [Cl]_i if at steady state, False otherwise
        """
        v_start = base.soma(.5)._ref_v[0]
        cli_start = base.soma(.5)._ref_cli[0]
        h.continuerun(h.tstop + continue_dt)
        h.tstop += continue_dt
        v_after = base.soma(.5)._ref_v[0]
        cli_after = base.soma(.5)._ref_cli[0]
        if v_after - v_start < 1e-6 and cli_after - cli_start < 1e-6:
            return cli_after
        else:
            return False

    num_steady_state_checks = 0
    while not at_steady_state(1):
        h.continuerun(h.tstop + 10000)
        h.tstop += 10000
        num_steady_state_checks += 1
        if num_steady_state_checks > 10:
            print("not at steady state even after {} ms".format(
                50000 + num_steady_state_checks * 10000))
            exit(-1)

    h.disableCV()
    vm, cli = base.soma(.5)._ref_v[0], base.soma(.5)._ref_cli[0]
    logger.info("steady state [Cl]_i {}".format(cli))
    logger.info("steady state Vm {}".format(vm))
    logger.info(
        "took {} ms (simulation time)".format(50000 +
                                              num_steady_state_checks * 10000))
    if remove_kcc2:
        base.remove_kcc2()
    h.finitialize(vm)
    return vm, cli
Exemple #54
0
def gap_junction_test(tree, v_init):

    h('objref gjlist, cells, Vlog1, Vlog2')

    h.pc = h.ParallelContext()
    h.cells = h.List()
    h.gjlist = h.List()

    cell1 = cells.make_neurotree_cell("NGFCell", neurotree_dict=tree)
    cell2 = cells.make_neurotree_cell("NGFCell", neurotree_dict=tree)

    h.cells.append(cell1)
    h.cells.append(cell2)

    ggid = 20000000
    source = 10422930
    destination = 10422670
    srcbranch = 1
    dstbranch = 2
    weight = 5.4e-4

    stimdur = 500
    tstop = 2000

    h.pc.set_gid2node(source, int(h.pc.id()))
    nc = cell1.connect2target(h.nil)
    h.pc.cell(source, nc, 1)

    h.pc.set_gid2node(destination, int(h.pc.id()))
    nc = cell2.connect2target(h.nil)
    h.pc.cell(destination, nc, 1)

    stim1 = h.IClamp(cell1.sections[0](0.5))
    stim1.delay = 250
    stim1.dur = stimdur
    stim1.amp = -0.1

    stim2 = h.IClamp(cell2.sections[0](0.5))
    stim2.delay = 500 + stimdur
    stim2.dur = stimdur
    stim2.amp = -0.1

    log_size = old_div(tstop, h.dt) + 1

    h.tlog = h.Vector(log_size, 0)
    h.tlog.record(h._ref_t)

    h.Vlog1 = h.Vector(log_size)
    h.Vlog1.record(cell1.sections[0](0.5)._ref_v)

    h.Vlog2 = h.Vector(log_size)
    h.Vlog2.record(cell2.sections[0](0.5)._ref_v)

    h.mkgap(h.pc, h.gjlist, source, srcbranch, ggid, ggid + 1, weight)
    h.mkgap(h.pc, h.gjlist, destination, dstbranch, ggid + 1, ggid, weight)

    h.pc.setup_transfer()
    h.pc.set_maxstep(10.0)

    h.stdinit()
    h.finitialize(v_init)
    h.pc.barrier()

    h.tstop = tstop
    h.pc.psolve(h.tstop)

    f = open("NGFCellGJ.dat", 'w')
    for (t, v1, v2) in zip(h.tlog, h.Vlog1, h.Vlog2):
        f.write("%f %f %f\n" % (t, v1, v2))
    f.close()
Exemple #55
0
    # set current injection
    rheobase = model_sets[cell_index]['rheobase']
    Istim = h.IClamp(0.5, sec=cell.soma)
    Istim.delay = 100
    Istim.dur = 1000
    Istim.amp = (rheobase) * 1e-3

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

    # run simulation
    h.finitialize(-80)

    # run simulation
    while h.t < 1000:
        h.fadvance()

    OUT[cell_index] = {
        'tm': tm.to_python(),
        'vm': vm.to_python,
        'rheo': rheobase
    }

# plot
for cell_index in OUT:
    plt.plot(OUT[cell_index]['tm'], OUT[cell_index]['vm'], \
        label='mdl:{} rhb:{:.0f}'.format(cell_index,OUT[cell_index]['rheo']))
Exemple #56
0
def nrngo(tstop, vinit):
    h.finitialize(vinit)
    h.fcurrent()
    while h.t < tstop:
        h.fadvance()
Exemple #57
0
def wave_search(size, size_segments, time_period, times, au, Du):
    # needed for standard run system
    h.load_file('stdrun.hoc')

    global dend

    dend = h.Section()
    dend.L = size
    dend.nseg = size_segments

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

    # WHO the actors are
    global u
    global z
    global v

    u = rxd.Species(where, d=Du, initial=0.5)  # activator
    z = rxd.Species(where, d=20, initial=0.5)  # inhibitor
    v = rxd.Species(where, d=0, initial=(1 / dend.L) * 30)  # modulator

    # HOW they act

    a = au
    b = -0.4
    c = 0.6
    d = -0.8
    u0 = 0.5
    z0 = 0.5
    av = 5.0
    kz = 0.001

    bistable_reaction1 = rxd.Rate(u, (a * (u - u0) + b * (z - z0) - av *
                                      (u - u0)**3) * (v**-2))
    bistable_reaction2 = rxd.Rate(z, (c * (u - u0) + d * (z - z0)) * (v**-2))

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

    # Setting up time frame
    global u_timespace

    T_d = times
    T = time_period
    u_timespace = []

    for i in np.arange(0, T_d):
        h.continuerun(i * T)
        u_timespace.append(u.nodes.concentration)

    # activator FFT source files
    u_fft_y = u.nodes.concentration
    u_fft_y = u_fft_y - np.mean(u_fft_y)
    u_fft_x = u.nodes.x
    global u_fft_x_norm
    u_fft_x_norm = dend.L * np.array(u_fft_x)

    # inhibitor FFT source files
    z_fft_y = z.nodes.concentration
    z_fft_y = z_fft_y - np.mean(z_fft_y)
    z_fft_x = z.nodes.x
    z_fft_x_norm = dend.L * np.array(u_fft_x)

    # activator FFT
    Y1 = np.fft.fft(u_fft_y)
    N = len(Y1) / 2 + 1
    dt = dend.L / dend.nseg
    fa = 1.0 / dt
    X = np.linspace(0, fa / 2, N, endpoint=True)

    # inhibitor FFT
    Y2 = np.fft.fft(z_fft_y)
    X2 = np.linspace(0, fa / 2, N, endpoint=True)
    #
    # if ((np.amax(Y1) - np.amin(Y1) < .01) or (np.amax(Y2) - np.amin(Y2) < .01)):
    #     return 0

    if (len(X) == len(2.0 * np.abs(Y1[:N] / N))):
        u_maxx = (np.argmax(2.0 * np.abs(Y1[:N] / N)))
        wavelen = np.around(1 / X[u_maxx])

    plot_it(time_period, times, u_timespace)
    plt.savefig('results/plots/{0}_{1}_{2}_{3}_{4}_{5}.png'.format(
        size, size_segments, time_period, times, au, Du))

    return wavelen
Exemple #58
0
ip3r = rxd.MultiCompartmentReaction(ca[er]!=ca[cyt], k, k, membrane=cyt_er_membrane)
ip3rg = rxd.Rate(h_gate, (1. / (1 + 1000. * ca[cyt] / (0.3)) - h_gate) / ip3rtau)

v1 = h.Vector()
v1.record(sec(0.5)._ref_v)
ca1 = h.Vector()
ca1.record(sec(0.5)._ref_cai)
v2 = h.Vector()
v2.record(sec(0.25)._ref_v)
ca2 = h.Vector()
ca2.record(sec(0.25)._ref_cai)
times = h.Vector()
times.record(h._ref_t)


h.finitialize()

cae_init = (0.0017 - cac_init * fc) / fe
ca[er].concentration = cae_init

#ip3.nodes.concentration = 2
for node in ip3.nodes:
    if  node.x<.8 and node.x>=.6  and node.sec._sec==sec:
        node.concentration = 2


h.CVode().re_init()

s.variable('cai')
#s.scale(-70, -50)
s.scale(0, 2e-3)
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]
minf = ip3[cyt] * 1000. * ca[cyt] / (ip3[cyt] + kip3) / (1000. * ca[cyt] + kact)
k = gip3r * (minf * h_gate) ** 3

ip3r = rxd.MultiCompartmentReaction(ca[er],ca[cyt], k, k, membrane=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[er],ca[cyt], gleak, gleak, membrane=cyt_er_membrane)


ip3r = rxd.MultiCompartmentReaction(ca[er],ca[cyt], k, k, membrane=cyt_er_membrane)
ip3rg = rxd.Rate(h_gate, (1. / (1 + 1000. * ca[cyt] / (0.3)) - h_gate) / ip3rtau)

h.finitialize()

cacyt_trace = h.Vector()
cacyt_trace.record(ca[cyt].nodes(sec)(.5)[0]._ref_concentration)

caer_trace = h.Vector()
caer_trace.record(ca[er].nodes(sec)(.5)[0]._ref_concentration)

ip3_trace = h.Vector()
ip3_trace.record(ip3.nodes(sec)(.5)[0]._ref_concentration)

times = h.Vector()
times.record(h._ref_t)

h.finitialize()
Exemple #60
0
def main():
    args = parse_args()
    # TODO: standardise Erev
    normalize = args.normalize  # normalize all traces between 0 and 1
    plotting = args.plotting  # plot traces
    mod_name = args.mod_type
    input_directory = args.mod_loc
    result_directory = args.results_dir
    var_dt = args.variable_dt
    if var_dt == 0:
        var_dt = False
    elif var_dt == 1:
        var_dt = True
    else:
        var_dt = True

    try:
        current_type = {
            'kv': 'outward',
            'nav': 'inward',
            'cav': 'outward',
            'kca': 'outward',
            'ih': 'outward'
        }[mod_name]
    except KeyError:
        print('Incorrect argument mod_type')

    # 2. PREPARE DIR - clean up, then add all mod files and compile
    if os.path.isdir(input_directory):
        input_path = input_directory
        mod_files = glob.glob(os.path.join(input_path,
                                           '*.mod'))  # should use glob instead
    elif os.path.isfile(input_directory):
        input_path = os.path.dirname(os.path.abspath(input_directory))
        mod_files = [input_directory]
    print('Processing %d mod files,' % (len(mod_files)))
    orig_directory = getcwd()
    with cd(input_path):
        unique_id = str(int(time.time() * 1000))
        folder_temp = "compiled_files_" + unique_id
        compiled_dir = create_dir(folder_temp)
        print(mod_files)
        custom_files = {}
        # python hack - copy all mod files to the directory and compile
        # NOTE: each file is given a new name (tmpmodX.mod) and suffix (suff_X), where X is the index in list mod_files
        for (m_idx, mpath) in enumerate(mod_files):
            m = os.path.basename(mpath)
            print("{} is tmpmod{}".format(m, m_idx))
            dest_file = 'tmpmod' + str(m_idx) + '.mod'
            new_suffix = 'suff_' + str(m_idx)
            rename_suffix(m, join(compiled_dir, dest_file), new_suffix)
            if isfile(
                    abspath(
                        join(orig_directory, '../', 'custom_code',
                             'customcode_' + splitext(m)[0] + '.hoc'))):
                custom_files[m_idx] = abspath(
                    join(orig_directory, '../', 'custom_code',
                         'customcode_' + splitext(m)[0] + '.hoc'))
        with cd(compiled_dir):
            # compile the mod files
            mod_files = nrnivmodl(len(mod_files), mod_files)
            # remove mode files which caused an issue
            mod_files = [m for m in mod_files]
            # this must be done AFTER compiling of mechanisms is complete
            # import within the same directory as compiled mod files to have them loaded automatically into NEURON
            from neuron import h, gui
        print(custom_files)

        # SET UP NEURON ENVIRONMENT
        h.celsius = 37.0
        h.finitialize(-80.0)
        # because nrnutils has neuron import statement, these should be placed after this file's neuron import
        from vClampCell import ICGCell
        from protocols import protocol_dict, plotting_done, \
            Activation, Inactivation, Deactivation, Ramp, ActionPotential

        # 3. LOOP THROUGH AND RUN ALL MOD FILES
        for (m_idx, m) in enumerate(mod_files):
            print('*' * 50 + '\n' + 'Running protocols for modfile: ', m)
            if m is None:
                continue
            fname = m.replace('.mod', '')
            new_suffix = 'suff_' + str(m_idx)
            print('suffix =', new_suffix)
            # create the cell and insert the ion channel conductance
            cell = ICGCell(mod_name, current_type)

            # some files require custom_code: if extra hoc file exists, then run it
            with cd(orig_directory):
                open('../customcode.hoc', 'w').close()  # empty the file
                if m_idx in custom_files.keys():
                    print('This mod requires additional files. Loading...')
                    copyfile(custom_files[m_idx], '../customcode.hoc')
                    h('load("../customcode.hoc")')

            cell.insert_distributed_channel(new_suffix)

            # loop through protocols
            protocol_list = protocol_dict.keys()
            for p in protocol_list:
                print('Running protocol: ', p)
                # create protocol and run
                protocol = protocol_dict[p](
                    h, dt=0.025, var_dt=var_dt
                )  # should generate an instance of the correct protocol
                protocol.clampCell(cell)  # create SEClamp attached to soma
                protocol.run(cell)  # run the protocol
                with cd(orig_directory):
                    ff = fname.rsplit('/', 1)[-1]
                    protocol.saveMat(
                        ff, result_directory)  # save voltage, current and time

                # optional plotting
                if plotting:  # plot each run from the matrices
                    protocol.plot()
        rmtree(folder_temp, ignore_errors=True)
    plotting_done()