Compute 'cellsPerAxis', 'bumpSigma', and 'activeFiringRate' parameters for
  :class:`ThresholdedGaussian2DLocationModule` given the number of cells per
  axis. See :func:`createRatModuleFromCellCount`
486179
def computeRatModuleParametersFromCellCount(cellsPerAxis,
                                            baselineCellsPerAxis=6):
  
  bumpSigma = RAT_BUMP_SIGMA * (baselineCellsPerAxis / float(cellsPerAxis))
  activeFiringRate = ThresholdedGaussian2DLocationModule.chooseReliableActiveFiringRate(
    cellsPerAxis, bumpSigma)

  return {
    "cellsPerAxis": cellsPerAxis,
    "bumpSigma": bumpSigma,
    "activeFiringRate": activeFiringRate
  }
17328
def _setCellClass (self):
        ''' '''
        from .. import sim
        
        # Check whether it's a NeuroML2 based cell
        if 'originalFormat' in self.tags:
            if self.tags['originalFormat'] == 'NeuroML2':
                self.cellModelClass = sim.NML2Cell
            if self.tags['originalFormat'] == 'NeuroML2_SpikeSource':
                self.cellModelClass = sim.NML2SpikeSource

        else:
            # set cell class: CompartCell for compartmental cells of PointCell for point neurons (NetStims, IntFire1,...)
            try: # check if cellModel corresponds to an existing point process mechanism; if so, use PointCell

                    tmp = getattr(h, self.tags['cellModel'])
                    self.cellModelClass = sim.PointCell
                    excludeTags = ['pop', 'cellModel', 'cellType', 'numCells', 'density', 'cellsList',
                                'xRange', 'yRange', 'zRange', 'xnormRange', 'ynormRange', 'znormRange', 'vref', 'spkTimes']
                    params = {k: v for k,v in self.tags.items() if k not in excludeTags}
                    self.tags['params'] = params
                    for k in self.tags['params']: self.tags.pop(k)
                    sim.net.params.popTagsCopiedToCells.append('params')
            except:
                if getattr(self.tags, 'cellModel', None) in ['NetStim', 'VecStim', 'IntFire1', 'IntFire2', 'IntFire4']:
                    print('Warning: could not find %s point process mechanism required for population %s' % (self.tags['cellModel'], self.tags['pop']))
                self.cellModelClass = sim.CompartCell
1017722
def createCellsGrid (self):
        ''' '''
        from .. import sim

        cells = []
        
        rangeLocs = [[0, getattr(sim.net.params, 'size'+coord)] for coord in ['X','Y','Z']]
        for icoord, coord in enumerate(['x', 'y', 'z']):
            # constrain to range set by user
            if coord+'normRange' in self.tags:  # if normalized range, convert to normalized
                self.tags[coord+'Range'] = [float(point) * getattr(sim.net.params, 'size'+coord.upper()) for point in self.tags[coord+'Range']]                
            if coord+'Range' in self.tags:  # if user provided absolute range, calculate range
                self.tags[coord+'normRange'] = [float(point) / getattr(sim.net.params, 'size'+coord.upper()) for point in self.tags[coord+'Range']]
                rangeLocs[icoord] = [self.tags[coord+'Range'][0], self.tags[coord+'Range'][1]] 
              
        gridSpacing = self.tags['gridSpacing']
        gridLocs = []
        for x in np.arange(rangeLocs[0][0], rangeLocs[0][1]+1, gridSpacing):
            for y in np.arange(rangeLocs[1][0], rangeLocs[1][1]+1, gridSpacing):
                for z in np.arange(rangeLocs[2][0], rangeLocs[2][1]+1, gridSpacing):
                    gridLocs.append((x, y, z))

        numCells = len(gridLocs)

        for i in self._distributeCells(numCells)[sim.rank]:
            gid = sim.net.lastGid+i
            self.cellGids.append(gid)  # add gid list of cells belonging to this population - not needed?
            cellTags = {k: v for (k, v) in self.tags.items() if k in sim.net.params.popTagsCopiedToCells}  # copy all pop tags to cell tags, except those that are pop-specific
            cellTags['pop'] = self.tags['pop']
            cellTags['xnorm'] = gridLocs[i][0] / sim.net.params.sizeX # set x location (um)
            cellTags['ynorm'] = gridLocs[i][1] / sim.net.params.sizeY # set y location (um)
            cellTags['znorm'] = gridLocs[i][2] / sim.net.params.sizeZ # set z location (um)
            cellTags['x'] = gridLocs[i][0]   # set x location (um)
            cellTags['y'] = gridLocs[i][1] # set y location (um)
            cellTags['z'] = gridLocs[i][2] # set z location (um)
            cells.append(self.cellModelClass(gid, cellTags)) # instantiate Cell object
            if sim.cfg.verbose: print(('Cell %d/%d (gid=%d) of pop %s, on node %d, '%(i, numCells, gid, self.tags['pop'], sim.rank)))
        sim.net.lastGid = sim.net.lastGid + numCells
        return cells
1260475
def _make_skel_func(code, cell_count, base_globals=None):
    
    if base_globals is None:
        base_globals = {}
    base_globals['__builtins__'] = __builtins__

    closure = (
        tuple(_make_empty_cell() for _ in range(cell_count))
        if cell_count >= 0 else
        None
    )
    return types.FunctionType(code, base_globals, None, None, closure)
469458
def dr( self, cell_lengths ):
        
        half_cell_lengths = cell_lengths / 2.0
        this_dr = self.final_site.r - self.initial_site.r
        for i in range( 3 ):
            if this_dr[ i ] > half_cell_lengths[ i ]:
                this_dr[ i ] -= cell_lengths[ i ]
            if this_dr[ i ] < -half_cell_lengths[ i ]:
                this_dr[ i ] += cell_lengths[ i ]
        return this_dr
320704
def _setup_grid(self, cutoff, unit_cell, grid):
        """"""
        if grid is None:
            # automatically choose a decent grid
            if unit_cell is None:
                grid = cutoff/2.9
            else:
                # The following would be faster, but it is not reliable
                # enough yet.
                #grid = unit_cell.get_optimal_subcell(cutoff/2.0)
                divisions = np.ceil(unit_cell.spacings/cutoff)
                divisions[divisions<1] = 1
                grid = unit_cell/divisions

        if isinstance(grid, float):
            grid_cell = UnitCell(np.array([
                [grid, 0, 0],
                [0, grid, 0],
                [0, 0, grid]
            ]))
        elif isinstance(grid, UnitCell):
            grid_cell = grid
        else:
            raise TypeError("Grid must be None, a float or a UnitCell instance.")

        if unit_cell is not None:
            # The columns of integer_matrix are the unit cell vectors in
            # fractional coordinates of the grid cell.
            integer_matrix = grid_cell.to_fractional(unit_cell.matrix.transpose()).transpose()
            if abs((integer_matrix - np.round(integer_matrix))*self.unit_cell.active).max() > 1e-6:
                raise ValueError("The unit cell vectors are not an integer linear combination of grid cell vectors.")
            integer_matrix = integer_matrix.round()
            integer_cell = UnitCell(integer_matrix, unit_cell.active)
        else:
            integer_cell = None

        return grid_cell, integer_cell
1372395
def loadCurve(data, groups, thresholds, absvals, fs, xlabels):
        """"""
        xlims = (xlabels[0], xlabels[-1])
        pw = ProgressWidget(groups, xlims)
        spike_counts = []
        # skip control
        for itrace in range(data.shape[0]):
            count = 0
            for ichan in range(data.shape[2]):
                flat_reps = data[itrace,:,ichan,:].flatten()
                count += len(spikestats.spike_times(flat_reps, thresholds[ichan], fs, absvals[ichan]))
            spike_counts.append(count/(data.shape[1]*data.shape[2])) #mean spikes per rep

        i = 0
        for g in groups:
            for x in xlabels:
                pw.setPoint(x, g, spike_counts[i])
                i +=1

        return pw
1302689
def _createGsshaPyObjects(self, cell):
        
        # Initialize GSSHAPY GridPipeCell object
        gridCell = GridPipeCell(cellI=cell['i'],
                                cellJ=cell['j'],
                                numPipes=cell['numPipes'])

        # Associate GridPipeCell with GridPipeFile
        gridCell.gridPipeFile = self

        for spipe in cell['spipes']:
            # Create GSSHAPY GridPipeNode object
            gridNode = GridPipeNode(linkNumber=spipe['linkNumber'],
                                    nodeNumber=spipe['nodeNumber'],
                                    fractPipeLength=spipe['fraction'])

            # Associate GridPipeNode with GridPipeCell
            gridNode.gridPipeCell = gridCell
28115
def apicalCheck(self, apicalInput):
    
    # Calculate predictions for this timestep
    (activeApicalSegments, matchingApicalSegments,
     apicalPotentialOverlaps) = self._calculateSegmentActivity(
       self.apicalConnections, apicalInput, self.connectedPermanence,
       self.activationThreshold, self.minThreshold, self.reducedBasalThreshold)

    apicallySupportedCells = self.apicalConnections.mapSegmentsToCells(
      activeApicalSegments)

    predictedCells = np.intersect1d(
      self.basalConnections.mapSegmentsToCells(self.activeBasalSegments),
      apicallySupportedCells)

    return predictedCells
564710
function (parallelModel, ecModel, api) {

        var dimensions = parallelModel.dimensions;
        var parallelAxisIndex = parallelModel.parallelAxisIndex;

        each(dimensions, function (dim, idx) {

            var axisIndex = parallelAxisIndex[idx];
            var axisModel = ecModel.getComponent('parallelAxis', axisIndex);

            var axis = this._axesMap.set(dim, new ParallelAxis(
                dim,
                axisHelper.createScaleByModel(axisModel),
                [0, 0],
                axisModel.get('type'),
                axisIndex
            ));

            var isCategory = axis.type === 'category';
            axis.onBand = isCategory && axisModel.get('boundaryGap');
            axis.inverse = axisModel.get('inverse');

            // Injection
            axisModel.axis = axis;
            axis.model = axisModel;
            axis.coordinateSystem = axisModel.coordinateSystem = this;

        }, this);
    }
1300054
def _compute_cell_extents_grid(bounding_rect=(0.03, 0.03, 0.97, 0.97),
                                   num_rows=2, num_cols=6,
                                   axis_pad=0.01):
        

        left, bottom, width, height = bounding_rect
        height_padding = axis_pad * (num_rows + 1)
        width_padding = axis_pad * (num_cols + 1)
        cell_height = float((height - height_padding) / num_rows)
        cell_width = float((width - width_padding) / num_cols)

        cell_height_padded = cell_height + axis_pad
        cell_width_padded = cell_width + axis_pad

        extents = list()
        for row in range(num_rows - 1, -1, -1):
            for col in range(num_cols):
                extents.append((left + col * cell_width_padded,
                                bottom + row * cell_height_padded,
                                cell_width, cell_height))

        return extents
604271
def movementCompute(self, displacement, noiseFactor = 0):
    

    if noiseFactor != 0:
      displacement = copy.deepcopy(displacement)
      xnoise = np.random.normal(0, noiseFactor)
      ynoise = np.random.normal(0, noiseFactor)
      displacement[0] += xnoise
      displacement[1] += ynoise


    # Calculate delta in the module's coordinates.
    phaseDisplacement = (np.matmul(self.rotationMatrix, displacement) *
                         self.phasesPerUnitDistance)

    # Shift the active coordinates.
    np.add(self.activePhases, phaseDisplacement, out=self.activePhases)

    # In Python, (x % 1.0) can return 1.0 because of floating point goofiness.
    # Generally this doesn't cause problems, it's just confusing when you're
    # debugging.
    np.round(self.activePhases, decimals=9, out=self.activePhases)
    np.mod(self.activePhases, 1.0, out=self.activePhases)

    self._computeActiveCells()
    self.phaseDisplacement = phaseDisplacement
331629
function _calculateGridLatLonOffset(cellSize, latitude) {
  const yOffset = _calculateLatOffset(cellSize);
  const xOffset = _calculateLonOffset(latitude, cellSize);
  return {yOffset, xOffset};
}
815345
def _getCellsWithFewestSegments(self, columns):
    
    candidateCells = np2.getAllCellsInColumns(columns, self.cellsPerColumn)

    # Arrange the segment counts into one row per minicolumn.
    segmentCounts = np.reshape(
      self.basalConnections.getSegmentCounts(candidateCells) +
      self.apicalConnections.getSegmentCounts(candidateCells),
      newshape=(len(columns),
                self.cellsPerColumn))

    # Filter to just the cells that are tied for fewest in their minicolumn.
    minSegmentCounts = np.amin(segmentCounts, axis=1, keepdims=True)
    candidateCells = candidateCells[np.flatnonzero(segmentCounts ==
                                                   minSegmentCounts)]

    # Filter to one cell per column, choosing randomly from the minimums.
    # To do the random choice, add a random offset to each index in-place, using
    # casting to floor the result.
    (_,
     onePerColumnFilter,
     numCandidatesInColumns) = np.unique(candidateCells / self.cellsPerColumn,
                                         return_index=True, return_counts=True)

    offsetPercents = np.empty(len(columns), dtype="float32")
    self.rng.initializeReal32Array(offsetPercents)

    np.add(onePerColumnFilter,
           offsetPercents*numCandidatesInColumns,
           out=onePerColumnFilter,
           casting="unsafe")

    return candidateCells[onePerColumnFilter]
185422
def _createGsshaPyObjects(self, cell):
        
        # Initialize GSSHAPY PipeGridCell object
        gridCell = GridStreamCell(cellI=cell['i'],
                                  cellJ=cell['j'],
                                  numNodes=cell['numNodes'])

        # Associate GridStreamCell with GridStreamFile
        gridCell.gridStreamFile = self

        for linkNode in cell['linkNodes']:
            # Create GSSHAPY GridStreamNode object
            gridNode = GridStreamNode(linkNumber=linkNode['linkNumber'],
                                      nodeNumber=linkNode['nodeNumber'],
                                      nodePercentGrid=linkNode['percent'])

            # Associate GridStreamNode with GridStreamCell
            gridNode.gridStreamCell = gridCell
807463
def laid_out_pcoord(self, mesh_axis):
    
    divisor = list_product(self.shape.to_integer_list[mesh_axis + 1:])
    modulus = self.shape[mesh_axis].size
    def my_fn(pnum):
      return (pnum // divisor) % modulus
    return self.slicewise(my_fn, self.laid_out_pnum())
56953
function calculateGridLatLonOffset(cellSize, latitude) {
  const yOffset = calculateLatOffset(cellSize);
  const xOffset = calculateLonOffset(latitude, cellSize);
  return {yOffset, xOffset};
}