Esempio n. 1
0
    def setup_ecp(self):
        self.im_ptr = h.PtrVector(self._nseg)  # pointer vector
        # used for gathering an array of  i_membrane values from the pointer vector
        self.im_ptr.ptr_update_callback(self.set_im_ptr)
        self.imVec = h.Vector(self._nseg)

        self.__set_extracell_mechanism()
Esempio n. 2
0
 def __init__(self, ncell, nsec):
     self.cells = [Cell(i, nsec) for i in range(ncell)]
     self.update_pointers()
     # Setup callback to update dipole POINTER for cache_efficiency
     # The PtrVector is used only to support the callback.
     self._callback_setup = h.PtrVector(1)
     self._callback_setup.ptr_update_callback(self.update_pointers)
Esempio n. 3
0
    def setup_xstim(self, set_nrn_mechanism=True):
        self.ptr2e_extracellular = h.PtrVector(self._nseg)
        self.ptr2e_extracellular.ptr_update_callback(self.set_ptr2e_extracellular)

        # Set the e_extracellular mechanism for all sections on this hoc object
        if set_nrn_mechanism:
            self.__set_extracell_mechanism()
Esempio n. 4
0
    def __init__(self, node, spike_threshold, dL, calc_ecp=False):
        super(BioCell, self).__init__(node)

        # Set up netcon object that can be used to detect and communicate cell spikes.
        self.set_spike_detector(spike_threshold)

        self._morph = None
        self._seg_coords = {}

        # Determine number of segments and store a list of all sections.
        self._nseg = 0
        self.set_nseg(dL)
        self._secs = []
        self.set_sec_array()

        self._synapses = []
        self._syn_src_gid = []
        self._syn_seg_ix = []
        self._syn_sec_x = []

 
        if calc_ecp:
            self.im_ptr = h.PtrVector(self._nseg)  # pointer vector
            self.im_ptr.ptr_update_callback(self.set_im_ptr)   # used for gathering an array of  i_membrane values from the pointer vector
            self.imVec = h.Vector(self._nseg)
Esempio n. 5
0
def setupRecordLFP():
    from .. import sim
    from netpyne.support.recxelectrode import RecXElectrode

    nsites = len(sim.cfg.recordLFP)
    saveSteps = int(np.ceil(sim.cfg.duration / sim.cfg.recordStep))
    sim.simData['LFP'] = np.zeros((saveSteps, nsites))
    if sim.cfg.saveLFPCells:
        for c in sim.net.cells:
            sim.simData['LFPCells'][c.gid] = np.zeros((saveSteps, nsites))

    if not sim.net.params.defineCellShapes:
        sim.net.defineCellShapes(
        )  # convert cell shapes (if not previously done already)
    sim.net.calcSegCoords()  # calculate segment coords for each cell
    sim.net.recXElectrode = RecXElectrode(
        sim)  # create exctracellular recording electrode

    if sim.cfg.createNEURONObj:
        for cell in sim.net.compartCells:
            nseg = cell._segCoords['p0'].shape[1]
            sim.net.recXElectrode.calcTransferResistance(
                cell.gid, cell._segCoords)  # transfer resistance for each cell
            cell.imembPtr = h.PtrVector(nseg)  # pointer vector
            cell.imembPtr.ptr_update_callback(
                cell.setImembPtr
            )  # used for gathering an array of  i_membrane values from the pointer vector
            cell.imembVec = h.Vector(nseg)

        sim.cvode.use_fast_imem(1)  # make i_membrane_ a range variable
Esempio n. 6
0
def setupRecordLFP():
    """
    Function for/to <short description of `netpyne.sim.setup.setupRecordLFP`>


    """

    from .. import sim
    from netpyne.support.recxelectrode import RecXElectrode

    nsites = len(sim.cfg.recordLFP)
    saveSteps = int(np.ceil(sim.cfg.duration / sim.cfg.recordStep))
    sim.simData['LFP'] = np.zeros((saveSteps, nsites))
    if sim.cfg.saveLFPCells:
        if sim.cfg.saveLFPCells == True:
            cellsRecordLFP = utils.getCellsList(['all'])  # record all cells
        elif isinstance(sim.cfg.saveLFPCells, list):
            cellsRecordLFP = utils.getCellsList(sim.cfg.saveLFPCells)
        for c in cellsRecordLFP:
            sim.simData['LFPCells'][c.gid] = np.zeros((saveSteps, nsites))

    if sim.cfg.saveLFPPops:
        if sim.cfg.saveLFPPops == True:
            popsRecordLFP = list(sim.net.pops.keys())  # record all pops
        elif isinstance(sim.cfg.saveLFPPops, list):
            popsRecordLFP = [
                p for p in sim.cfg.saveLFPPops
                if p in list(sim.net.pops.keys())
            ]  # only pops that exist
            sim.net.popForEachGid = {}
            for pop in popsRecordLFP:
                sim.net.popForEachGid.update(
                    {gid: pop
                     for gid in sim.net.pops[pop].cellGids})
        for pop in popsRecordLFP:
            sim.simData['LFPPops'][pop] = np.zeros((saveSteps, nsites))

    if not sim.net.params.defineCellShapes:
        sim.net.defineCellShapes(
        )  # convert cell shapes (if not previously done already)
    sim.net.calcSegCoords()  # calculate segment coords for each cell
    sim.net.recXElectrode = RecXElectrode.fromConfig(
        sim.cfg)  # create exctracellular recording electrode

    if sim.cfg.createNEURONObj:
        for cell in sim.net.compartCells:
            nseg = cell._segCoords['p0'].shape[1]
            sim.net.recXElectrode.calcTransferResistance(
                cell.gid, cell._segCoords)  # transfer resistance for each cell
            cell.imembPtr = h.PtrVector(nseg)  # pointer vector
            cell.imembPtr.ptr_update_callback(
                cell.setImembPtr
            )  # used for gathering an array of  i_membrane values from the pointer vector
            cell.imembVec = h.Vector(nseg)

        sim.cvode.use_fast_imem(True)  # make i_membrane_ a range variable
        sim.cfg.use_fast_imem = True
Esempio n. 7
0
    def LFPinit(self):
        lsec = getallSections()
        n = len(lsec)
        # print('In LFPinit - pc.id = ',self.pc.id(),'len(lsec)=',n)
        self.imem_ptrvec = h.PtrVector(n)  #
        self.imem_vec = h.Vector(n)
        for i, s in enumerate(lsec):
            seg = s(0.5)
            #for seg in s # so do not need to use segments...? more accurate to use segments and their neighbors
            self.imem_ptrvec.pset(i, seg._ref_i_membrane_)

        self.vres = self.transfer_resistance(self.coord)
        self.lfp_t = h.Vector()
        self.lfp_v = h.Vector()
Esempio n. 8
0
    def LFPinit(self):
        lsec = get_all_sections()
        n_sections = len(lsec)

        self.imem_ptrvec = h.PtrVector(n_sections)
        self.imem_vec = h.Vector(n_sections)
        for i, s in enumerate(lsec):
            seg = s(0.5)
            # for seg in s # so do not need to use segments...?
            # more accurate to use segments and their neighbors
            self.imem_ptrvec.pset(i, seg._ref_i_membrane_)

        self.vres = self.transfer_resistance(self.coord, method=self.method)
        self.lfp_t = h.Vector()
        self.lfp_v = h.Vector()
Esempio n. 9
0
 def setup(self):
   size = 0
   for sec in self.sl:
     for seg in sec:
       size += 1
   self.pv = h.PtrVector(size)
   self.hv = h.Vector(size)
   self.v = self.hv.as_numpy()
   self.nodeindices = numpy.empty(size, dtype=int)
   self.n = numpy.empty(size, dtype=float)
   self.g = numpy.empty(size, dtype=float)
   i=0
   for sec in self.sl:
     for seg in sec:
       self.pv.pset(i, seg._ref_v)
       self.nodeindices[i] = seg.node_index()
       i += 1
Esempio n. 10
0
def _transfer_to_legacy():
    global  _c_ptr_vector, _c_ptr_vector_storage, _c_ptr_vector_storage_nrn
    global _last_c_ptr_length
    
    size = len(_all_cptrs)
    if _last_c_ptr_length != size:
        if size:
            _c_ptr_vector = h.PtrVector(size)
            for i, ptr in enumerate(_all_cptrs):
                _c_ptr_vector.pset(i, ptr)
            _c_ptr_vector_storage_nrn = h.Vector(size)
            _c_ptr_vector_storage = _c_ptr_vector_storage_nrn.as_numpy()
        else:
            _c_ptr_vector = None
        _last_c_ptr_length = size
    if size:
        _c_ptr_vector_storage[:] = node._get_states()[_all_cindices]
        _c_ptr_vector.scatter(_c_ptr_vector_storage_nrn)
Esempio n. 11
0
def _update_node_data(force=False):
    global last_diam_change_cnt, last_structure_change_cnt, _curr_indices, _curr_scales, _curr_ptrs
    global _curr_ptr_vector, _curr_ptr_storage, _curr_ptr_storage_nrn
    if last_diam_change_cnt != _cvode_object.diam_change_count(
    ) or _cvode_object.structure_change_count(
    ) != last_structure_change_cnt or force:
        last_diam_change_cnt = _cvode_object.diam_change_count()
        last_structure_change_cnt = _cvode_object.structure_change_count()
        for sr in species._get_all_species().values():
            s = sr()
            if s is not None: s._update_node_data()
        for sr in species._get_all_species().values():
            s = sr()
            if s is not None: s._update_region_indices()
        for rptr in _all_reactions:
            r = rptr()
            if r is not None: r._update_indices()
        _curr_indices = []
        _curr_scales = []
        _curr_ptrs = []
        for sr in species._get_all_species().values():
            s = sr()
            if s is not None:
                s._setup_currents(_curr_indices, _curr_scales, _curr_ptrs)

        num = len(_curr_ptrs)
        if num:
            _curr_ptr_vector = h.PtrVector(num)
            for i, ptr in enumerate(_curr_ptrs):
                _curr_ptr_vector.pset(i, ptr)

            _curr_ptr_storage_nrn = h.Vector(num)
            _curr_ptr_storage = _curr_ptr_storage_nrn.as_numpy()
        else:
            _curr_ptr_vector = None

        _curr_scales = numpy.array(_curr_scales)
Esempio n. 12
0
def setupRecordDipole():
    """
    Function for/to <short description of `netpyne.sim.setup.setupRecordDipole`>


    """

    from .. import sim
    import lfpykit

    saveSteps = int(np.ceil(sim.cfg.duration / sim.cfg.recordStep))
    sim.simData['dipoleSum'] = np.zeros((saveSteps, 3))

    if sim.cfg.saveDipoleCells:
        if sim.cfg.saveDipoleCells == True:
            cellsRecordDipole = utils.getCellsList(['all'])  # record all cells
        elif isinstance(sim.cfg.saveDipoleCells, list):
            cellsRecordDipole = utils.getCellsList(sim.cfg.saveDipoleCells)
        for c in cellsRecordDipole:
            sim.simData['dipoleCells'][c.gid] = np.zeros((saveSteps, 3))

    if sim.cfg.saveDipolePops:
        if sim.cfg.saveDipolePops == True:
            popsRecordDipole = list(sim.net.pops.keys())  # record all pops
        elif isinstance(sim.cfg.saveDipolePops, list):
            popsRecordDipole = [
                p for p in sim.cfg.saveDipolePops
                if p in list(sim.net.pops.keys())
            ]  # only pops that exist
            sim.net.popForEachGid = {}
            for pop in popsRecordDipole:
                sim.net.popForEachGid.update(
                    {gid: pop
                     for gid in sim.net.pops[pop].cellGids})
        for pop in popsRecordDipole:
            sim.simData['dipolePops'][pop] = np.zeros((saveSteps, 3))

    if not sim.net.params.defineCellShapes:
        sim.net.defineCellShapes(
        )  # convert cell shapes (if not previously done already)
    sim.net.calcSegCoords()  # calculate segment coords for each cell

    if sim.cfg.createNEURONObj:
        for cell in sim.net.compartCells:
            lfpykitCell = lfpykit.CellGeometry(
                x=np.array([[p0, p1] for p0, p1 in zip(
                    cell._segCoords['p0'][0], cell._segCoords['p1'][0])]),
                y=np.array([[p0, p1] for p0, p1 in zip(
                    cell._segCoords['p0'][1], cell._segCoords['p1'][1])]),
                z=np.array([[p0, p1] for p0, p1 in zip(
                    cell._segCoords['p0'][2], cell._segCoords['p1'][2])]),
                d=np.array([[d0, d1] for d0, d1 in zip(
                    cell._segCoords['d0'], cell._segCoords['d1'])]))

            cdm = lfpykit.CurrentDipoleMoment(cell=lfpykitCell)
            cell.M = cdm.get_transformation_matrix()

            # set up recording of membrane currents (duplicate with setupRecordLFP -- unifiy and avoid calling twice)
            nseg = cell._segCoords['p0'].shape[1]
            cell.imembPtr = h.PtrVector(nseg)  # pointer vector
            cell.imembPtr.ptr_update_callback(
                cell.setImembPtr
            )  # used for gathering an array of  i_membrane values from the pointer vector
            cell.imembVec = h.Vector(nseg)

        sim.cvode.use_fast_imem(True)  # make i_membrane_ a range variable
        sim.cfg.use_fast_imem = True
Esempio n. 13
0
    def _build(self, cvode=None, include_celltypes='all'):
        """Assemble NEURON objects for calculating extracellular potentials.

        The handler is set up to maintain a vector of membrane currents at at
        every inner segment of every section of every cell on each CVODE
        integration step. In addition, it records a time vector of sample
        times.

        Parameters
        ----------
        cvode : instance of h.CVode
            Multi order variable time step integration method.
        include_celltypes : str
            String to match against the cell type of each section. Defaults to
            ``'all'``: calculate extracellular potential generated by all
            cells. To restrict this to include only pyramidal cells, use
            ``'Pyr'``. For basket cells, use ``'Basket'``. NB This argument is
            currently not exposed in the API.
        """
        secs_on_rank = h.allsec()  # get all h.Sections known to this MPI rank
        _validate_type(include_celltypes, str)
        _check_option('include_celltypes', include_celltypes,
                      ['all', 'Pyr', 'Basket'])
        if include_celltypes.lower() != 'all':
            secs_on_rank = [
                s for s in secs_on_rank if include_celltypes in s.name()
            ]

        segment_counts = [sec.nseg for sec in secs_on_rank]
        n_total_segments = np.sum(segment_counts)

        # pointers assigned to _ref_i_membrane_ at each EACH internal segment
        self._nrn_imem_ptrvec = h.PtrVector(n_total_segments)
        # placeholder into which pointer values are read on each sim time step
        self._nrn_imem_vec = h.Vector(n_total_segments)

        ptr_idx = 0
        for sec in secs_on_rank:
            for seg in sec:  # section end points (0, 1) not included
                # set Nth pointer to the net membrane current at this segment
                self._nrn_imem_ptrvec.pset(ptr_idx,
                                           sec(seg.x)._ref_i_membrane_)
                ptr_idx += 1
        if ptr_idx != n_total_segments:
            raise RuntimeError(f'Expected {n_total_segments} imem pointers, '
                               f'got {ptr_idx}.')

        # transfer resistances for each segment (keep in Neuron Matrix object)
        self._nrn_r_transfer = h.Matrix(self.n_contacts, n_total_segments)

        for row, pos in enumerate(self.array.positions):
            if self.array.method is not None:
                transfer_resistance = list()
                for sec in secs_on_rank:
                    this_xfer_r = _transfer_resistance(
                        sec,
                        pos,
                        conductivity=self.array.conductivity,
                        method=self.array.method,
                        min_distance=self.array.min_distance)
                    transfer_resistance.extend(this_xfer_r)

                self._nrn_r_transfer.setrow(row, h.Vector(transfer_resistance))
            else:
                # for testing, make a matrix of ones
                self._nrn_r_transfer.setrow(row,
                                            h.Vector(n_total_segments, 1.))

        # record time for each array
        self._nrn_times = h.Vector().record(h._ref_t)

        # contributions of all segments on this rank to total calculated
        # potential at electrode (_PC.allreduce called in _simulate_dipole)
        # NB voltages of all contacts are initialised to 0 mV, i.e., the
        # potential at time 0.0 ms is defined to be zero.
        self._nrn_voltages = h.Vector(self.n_contacts, 0.)

        # NB we must make a copy of the function reference, and keep it for
        # later decoupling using extra_scatter_gather_remove
        # (instead of a new function reference)
        self._recording_callback = self._gather_nrn_voltages
        # Nb extra_scatter_gather is called _after_ the solver takes a step,
        # so the initial state is not recorded (initialised to zero above)
        cvode.extra_scatter_gather(0, self._recording_callback)
Esempio n. 14
0
    glu.ijnmda[i] = h.ijk(*locations[i], nz - 1)

h.load_file("test1.ses")

sl = h.SectionList()
hin = h.PlotShape[0]
hin.size(0, nx, 0, nx)
hin.scale(0, 1)
for i in range(nx):
    for k in range(nz):
        hin.hinton(glu._ref_glu[i + k * nx * ny], float(i), float(k), .9, .9)
#h.flush_list.append(hin)
hin.exec_menu("Shape Plot")

# plot of glu[i, 0, nz-1]
gluline = h.PtrVector(nx)
gluline.label("glu[i, 0, nz-1]")
for i in range(nx):
    gluline.pset(i, glu._ref_glu[int(h.ijk(i, 0, nz - 1))])
glulinegraph = h.Graph[2]
gluline.plot(glulinegraph)

gluline2 = h.PtrVector(nx)
gluline2.label("glu[i, 0, 0]")
for i in range(nx):
    gluline2.pset(i, glu._ref_glu[int(h.ijk(i, 0, 0))])
gluline2.plot(glulinegraph)
#glulinegraph2.size(0, 30, 0, 3)
h.flush_list.append(glulinegraph)

h.stdinit()
Esempio n. 15
0
    def __init__(self, tracker_sec, use_fast_imem, lfp_scheme, sigma,
                 electrode_coords, *args):
        """
        Add all segments in given SectionLists as LFP sources, using the given
        LFP approximation scheme

        ARGUMENTS
        ---------

        @param   $o1 : tracking_section <Section>
                 Section where LFP summator object should be inserted.
                 This has no influence on the section and is only necessary
                 because a POINT_PROCESS object needs a container.
        
        @param   $s2 : use_fast_imem <bool>
                 True if CVode.fast_imem should be used and 'extracellular' mechanism
                 should not be inserted.
        
        @param   $s3 : lfp_scheme <string>
                 LFP approximation scheme: "PSA", "LSA", or "RC"
        
        @param   $4 : sigma <float>
                 Conductivity of the extracellular medium.
        
        @param   $o5 : electrode_coords <Vector>
                 Vector of length 3 containing electrode x,y,z coordinates.
        
        @param   $o6 - $oN : tracked_seclist <SectionList>
                 SectionLists containing sections whose LFP contributions should
                 be summed.

        PRECONDITIONS
        -------------

        @pre     If the 'use_fast_imem' argument is True, cvode = h.CVode(); 
                 cvode.use_fast_imem(True) must be called before calling this function.
                 If not, the variable 'i_membrane_' is not created.

        PYTHON USAGE
        ------------
        
           >>> cell = MyCellTemplate()
           >>> soma = cell.soma              # Section
           >>> dendritic = cell.dendritic    # SectionList
           >>> sigma = 0.3
           >>> electrode_coords = h.Vector([10.0, 50.0, 20.0])
           >>> tracker = LfpTracker(soma, True, "PSA", sigma, electrode_coords, dendritic)
        """

        self.summator = h.LfpSumStep(tracker_sec(0.5))
        self.tracked_seclists = args
        self.use_fast_imem = use_fast_imem

        num_tracked_segs = sum(
            (sec.nseg for sl in self.tracked_seclists for sec in sl))
        self.imemb_ptrs = h.PtrVector(num_tracked_segs)

        self.lfp_imemb_factors = h.calc_lfp_factors(use_fast_imem, lfp_scheme,
                                                    sigma, electrode_coords,
                                                    *args).as_numpy()

        i_seg = 0
        for sl in self.tracked_seclists:
            for sec in sl:
                for seg in sec:
                    if use_fast_imem:
                        h.setpointer(seg._ref_i_membrane_, 'temp_ptr',
                                     self.summator)
                        factor = self.lfp_imemb_factors[i_seg] * 1e2
                    else:
                        h.setpointer(seg._ref_i_membrane, 'temp_ptr',
                                     self.summator)
                        factor = self.lfp_imemb_factors[i_seg]

                        self.imemb_ptrs.pset(i_seg, seg._ref_i_membrane_)
                        self.summator.add_lfp_source(factor)
                        i_seg += 1

                        self.imemb_ptrs.ptr_update_callback(
                            self.update_imemb_ptrs)
Esempio n. 16
0
from neuron import h
a = h.Vector(5).indgen()
b = h.Vector(5).fill(0)
pv = h.PtrVector(5)
for i in range(len(a)):
    pv.pset(i, b._ref_x[i])

pv.scatter(a)
b.printf()

print(pv.label())
pv.label("hello")
print(pv.label())