return self._cells[cell]._segments[idx]<EOL>

Returns a :class:`Segment` object of the specified segment using data from
the ``self._cells`` array.

:param cell: (int) cell index
:param idx:  (int) segment index on a cell
:returns: (:class:`Segment`) Segment object with index idx on the specified cell


return self._segmentForFlatIdx[flatIdx]<EOL>

Get the segment with the specified flatIdx.

:param flatIdx: (int) The segment's flattened list index.

:returns: (:class:`Segment`)


return self._nextFlatIdx<EOL>

Get the needed length for a list to hold a value for every segment's
flatIdx.

:returns: (int) Required list length


return self._synapsesForPresynapticCell[presynapticCell]<EOL>

Returns the synapses for the source cell that they synapse on.

:param presynapticCell: (int) Source cell index

:returns: (set) :class:`Synapse` objects


cellData = self._cells[cell]<EOL>if len(self._freeFlatIdxs) > <NUM_LIT:0>:<EOL><INDENT>flatIdx = self._freeFlatIdxs.pop()<EOL><DEDENT>else:<EOL><INDENT>flatIdx = self._nextFlatIdx<EOL>self._segmentForFlatIdx.append(None)<EOL>self._nextFlatIdx += <NUM_LIT:1><EOL><DEDENT>ordinal = self._nextSegmentOrdinal<EOL>self._nextSegmentOrdinal += <NUM_LIT:1><EOL>segment = Segment(cell, flatIdx, ordinal)<EOL>cellData._segments.append(segment)<EOL>self._segmentForFlatIdx[flatIdx] = segment<EOL>return segment<EOL>

Adds a new segment on a cell.

:param cell: (int) Cell index
:returns: (int) New segment index


<EOL>for synapse in segment._synapses:<EOL><INDENT>self._removeSynapseFromPresynapticMap(synapse)<EOL><DEDENT>self._numSynapses -= len(segment._synapses)<EOL>segments = self._cells[segment.cell]._segments<EOL>i = segments.index(segment)<EOL>del segments[i]<EOL>self._freeFlatIdxs.append(segment.flatIdx)<EOL>self._segmentForFlatIdx[segment.flatIdx] = None<EOL>

Destroys a segment.

:param segment: (:class:`Segment`) representing the segment to be destroyed.


def createSynapse(self, segment, presynapticCell, permanence):

idx = len(segment._synapses)<EOL>synapse = Synapse(segment, presynapticCell, permanence,<EOL>self._nextSynapseOrdinal)<EOL>self._nextSynapseOrdinal += <NUM_LIT:1><EOL>segment._synapses.add(synapse)<EOL>self._synapsesForPresynapticCell[presynapticCell].add(synapse)<EOL>self._numSynapses += <NUM_LIT:1><EOL>return synapse<EOL>

Creates a new synapse on a segment.

:param segment: (:class:`Segment`) Segment object for synapse to be synapsed
       to.
:param presynapticCell: (int) Source cell index.
:param permanence: (float) Initial permanence of synapse.
:returns: (:class:`Synapse`) created synapse


self._numSynapses -= <NUM_LIT:1><EOL>self._removeSynapseFromPresynapticMap(synapse)<EOL>synapse.segment._synapses.remove(synapse)<EOL>

Destroys a synapse.

:param synapse: (:class:`Synapse`) synapse to destroy


def updateSynapsePermanence(self, synapse, permanence):

synapse.permanence = permanence<EOL>

Updates the permanence for a synapse.

:param synapse: (class:`Synapse`) to be updated.
:param permanence: (float) New permanence.


def computeActivity(self, activePresynapticCells, connectedPermanence):

numActiveConnectedSynapsesForSegment = [<NUM_LIT:0>] * self._nextFlatIdx<EOL>numActivePotentialSynapsesForSegment = [<NUM_LIT:0>] * self._nextFlatIdx<EOL>threshold = connectedPermanence - EPSILON<EOL>for cell in activePresynapticCells:<EOL><INDENT>for synapse in self._synapsesForPresynapticCell[cell]:<EOL><INDENT>flatIdx = synapse.segment.flatIdx<EOL>numActivePotentialSynapsesForSegment[flatIdx] += <NUM_LIT:1><EOL>if synapse.permanence > threshold:<EOL><INDENT>numActiveConnectedSynapsesForSegment[flatIdx] += <NUM_LIT:1><EOL><DEDENT><DEDENT><DEDENT>return (numActiveConnectedSynapsesForSegment,<EOL>numActivePotentialSynapsesForSegment)<EOL>

Compute each segment's number of active synapses for a given input.
In the returned lists, a segment's active synapse count is stored at index
``segment.flatIdx``.

:param activePresynapticCells: (iter) Active cells.
:param connectedPermanence: (float) Permanence threshold for a synapse to be
       considered connected

:returns: (tuple) (``numActiveConnectedSynapsesForSegment`` [list],
                  ``numActivePotentialSynapsesForSegment`` [list])


if cell is not None:<EOL><INDENT>return len(self._cells[cell]._segments)<EOL><DEDENT>return self._nextFlatIdx - len(self._freeFlatIdxs)<EOL>

Returns the number of segments.

:param cell: (int) Optional parameter to get the number of segments on a
       cell.
:returns: (int) Number of segments on all cells if cell is not specified, or
          on a specific specified cell


if segment is not None:<EOL><INDENT>return len(segment._synapses)<EOL><DEDENT>return self._numSynapses<EOL>

Returns the number of Synapses.

:param segment: (:class:`Segment`) Optional parameter to get the number of
       synapses on a segment.

:returns: (int) Number of synapses on all segments if segment is not
          specified, or on a specified segment.


return segment.cell + (segment._ordinal / float(self._nextSegmentOrdinal))<EOL>

Return a numeric key for sorting this segment. This can be used with the
python built-in ``sorted()`` function.

:param segment: (:class:`Segment`) within this :class:`Connections`
       instance.
:returns: (float) A numeric key for sorting.


protoCells = proto.init('<STR_LIT>', self.numCells)<EOL>for i in xrange(self.numCells):<EOL><INDENT>segments = self._cells[i]._segments<EOL>protoSegments = protoCells[i].init('<STR_LIT>', len(segments))<EOL>for j, segment in enumerate(segments):<EOL><INDENT>synapses = segment._synapses<EOL>protoSynapses = protoSegments[j].init('<STR_LIT>', len(synapses))<EOL>for k, synapse in enumerate(sorted(synapses, key=lambda s: s._ordinal)):<EOL><INDENT>protoSynapses[k].presynapticCell = synapse.presynapticCell<EOL>protoSynapses[k].permanence = synapse.permanence<EOL><DEDENT><DEDENT><DEDENT>

Writes serialized data to proto object.

:param proto: (DynamicStructBuilder) Proto object


<EOL>protoCells = proto.cells<EOL>connections = cls(len(protoCells))<EOL>for cellIdx, protoCell in enumerate(protoCells):<EOL><INDENT>protoCell = protoCells[cellIdx]<EOL>protoSegments = protoCell.segments<EOL>connections._cells[cellIdx] = CellData()<EOL>segments = connections._cells[cellIdx]._segments<EOL>for segmentIdx, protoSegment in enumerate(protoSegments):<EOL><INDENT>segment = Segment(cellIdx, connections._nextFlatIdx,<EOL>connections._nextSegmentOrdinal)<EOL>segments.append(segment)<EOL>connections._segmentForFlatIdx.append(segment)<EOL>connections._nextFlatIdx += <NUM_LIT:1><EOL>connections._nextSegmentOrdinal += <NUM_LIT:1><EOL>synapses = segment._synapses<EOL>protoSynapses = protoSegment.synapses<EOL>for synapseIdx, protoSynapse in enumerate(protoSynapses):<EOL><INDENT>presynapticCell = protoSynapse.presynapticCell<EOL>synapse = Synapse(segment, presynapticCell, protoSynapse.permanence,<EOL>ordinal=connections._nextSynapseOrdinal)<EOL>connections._nextSynapseOrdinal += <NUM_LIT:1><EOL>synapses.add(synapse)<EOL>connections._synapsesForPresynapticCell[presynapticCell].add(synapse)<EOL>connections._numSynapses += <NUM_LIT:1><EOL><DEDENT><DEDENT><DEDENT>return connections<EOL>

Reads deserialized data from proto object

:param proto: (DynamicStructBuilder) Proto object

:returns: (:class:`Connections`) instance


<EOL>for i in xrange(self.numCells):<EOL><INDENT>segments = self._cells[i]._segments<EOL>otherSegments = other._cells[i]._segments<EOL>if len(segments) != len(otherSegments):<EOL><INDENT>return False<EOL><DEDENT>for j in xrange(len(segments)):<EOL><INDENT>segment = segments[j]<EOL>otherSegment = otherSegments[j]<EOL>synapses = segment._synapses<EOL>otherSynapses = otherSegment._synapses<EOL>if len(synapses) != len(otherSynapses):<EOL><INDENT>return False<EOL><DEDENT>for synapse in synapses:<EOL><INDENT>found = False<EOL>for candidate in otherSynapses:<EOL><INDENT>if synapse == candidate:<EOL><INDENT>found = True<EOL>break<EOL><DEDENT><DEDENT>if not found:<EOL><INDENT>return False<EOL><DEDENT><DEDENT><DEDENT><DEDENT>if (len(self._synapsesForPresynapticCell) !=<EOL>len(self._synapsesForPresynapticCell)):<EOL><INDENT>return False<EOL><DEDENT>for i in self._synapsesForPresynapticCell.keys():<EOL><INDENT>synapses = self._synapsesForPresynapticCell[i]<EOL>otherSynapses = other._synapsesForPresynapticCell[i]<EOL>if len(synapses) != len(otherSynapses):<EOL><INDENT>return False<EOL><DEDENT>for synapse in synapses:<EOL><INDENT>found = False<EOL>for candidate in otherSynapses:<EOL><INDENT>if synapse == candidate:<EOL><INDENT>found = True<EOL>break<EOL><DEDENT><DEDENT>if not found:<EOL><INDENT>return False<EOL><DEDENT><DEDENT><DEDENT>if self._numSynapses != other._numSynapses:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>

Equality operator for Connections instances.
        Checks if two instances are functionally identical

        :param other: (:class:`Connections`) Connections instance to compare to


return not self.__eq__(other)<EOL>

Non-equality operator for Connections instances.
Checks if two instances are not functionally identical

:param other: (:class:`Connections`) Connections instance to compare to


if cellsPerCol == <NUM_LIT:0>:<EOL><INDENT>cellsPerCol = <NUM_LIT:1><EOL><DEDENT>cols = activeInputs.size / cellsPerCol<EOL>activeInputs = activeInputs.reshape(cols, cellsPerCol)<EOL>(cols, cellIdxs) = activeInputs.nonzero()<EOL>if len(cols) == <NUM_LIT:0>:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>items = ["<STR_LIT>" % (len(cols))]<EOL>prevCol = -<NUM_LIT:1><EOL>for (col,cellIdx) in zip(cols, cellIdxs):<EOL><INDENT>if col != prevCol:<EOL><INDENT>if prevCol != -<NUM_LIT:1>:<EOL><INDENT>items.append("<STR_LIT>")<EOL><DEDENT>items.append("<STR_LIT>" % col)<EOL>prevCol = col<EOL><DEDENT>items.append("<STR_LIT>" % cellIdx)<EOL><DEDENT>items.append("<STR_LIT:]>")<EOL>return "<STR_LIT:U+0020>".join(items)<EOL>

Print the list of [column, cellIdx] indices for each of the active
    cells in activeInputs.


self._Memory = None<EOL>self._numPatterns = <NUM_LIT:0><EOL>self._M = None<EOL>self._categoryList = []<EOL>self._partitionIdList = []<EOL>self._partitionIdMap = {}<EOL>self._finishedLearning = False<EOL>self._iterationIdx = -<NUM_LIT:1><EOL>if self.maxStoredPatterns > <NUM_LIT:0>:<EOL><INDENT>assert self.useSparseMemory, ("<STR_LIT>"<EOL>"<STR_LIT>")<EOL>self.fixedCapacity = True<EOL>self._categoryRecencyList = []<EOL><DEDENT>else:<EOL><INDENT>self.fixedCapacity = False<EOL><DEDENT>self._protoSizes = None<EOL>self._s = None<EOL>self._vt = None<EOL>self._nc = None<EOL>self._mean = None<EOL>self._specificIndexTraining = False<EOL>self._nextTrainingIndices = None<EOL>


def prototypeSetCategory(self, idToCategorize, newCategory):

if idToCategorize not in self._categoryRecencyList:<EOL><INDENT>return<EOL><DEDENT>recordIndex = self._categoryRecencyList.index(idToCategorize)<EOL>self._categoryList[recordIndex] = newCategory<EOL>

Allows ids to be assigned a category and subsequently enables users to use:

  - :meth:`~.KNNClassifier.KNNClassifier.removeCategory`
  - :meth:`~.KNNClassifier.KNNClassifier.closestTrainingPattern`
  - :meth:`~.KNNClassifier.KNNClassifier.closestOtherTrainingPattern`


<EOL>rowsToRemove = [k for k, rowID in enumerate(self._categoryRecencyList)if rowID in idsToRemove]<EOL>self._removeRows(rowsToRemove)<EOL>

There are two caveats. First, this is a potentially slow operation. Second,
pattern indices will shift if patterns before them are removed.

:param idsToRemove: A list of row indices to remove.


removedRows = <NUM_LIT:0><EOL>if self._Memory is None:<EOL><INDENT>return removedRows<EOL><DEDENT>catToRemove = float(categoryToRemove)<EOL>rowsToRemove = [k for k, catID in enumerate(self._categoryList)if catID == catToRemove]<EOL>self._removeRows(rowsToRemove)<EOL>assert catToRemove not in self._categoryList<EOL>

There are two caveats. First, this is a potentially slow operation. Second,
pattern indices will shift if patterns before them are removed.

:param categoryToRemove: Category label to remove


<EOL>removalArray = numpy.array(rowsToRemove)<EOL>self._categoryList = numpy.delete(numpy.array(self._categoryList),<EOL>removalArray).tolist()<EOL>if self.fixedCapacity:<EOL><INDENT>self._categoryRecencyList = numpy.delete(<EOL>numpy.array(self._categoryRecencyList), removalArray).tolist()<EOL><DEDENT>for row in reversed(rowsToRemove):  <EOL><INDENT>self._partitionIdList.pop(row)<EOL><DEDENT>self._rebuildPartitionIdMap(self._partitionIdList)<EOL>if self.useSparseMemory:<EOL><INDENT>for rowIndex in rowsToRemove[::-<NUM_LIT:1>]:<EOL><INDENT>self._Memory.deleteRow(rowIndex)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self._M = numpy.delete(self._M, removalArray, <NUM_LIT:0>)<EOL><DEDENT>numRemoved = len(rowsToRemove)<EOL>numRowsExpected = self._numPatterns - numRemoved<EOL>if self.useSparseMemory:<EOL><INDENT>if self._Memory is not None:<EOL><INDENT>assert self._Memory.nRows() == numRowsExpected<EOL><DEDENT><DEDENT>else:<EOL><INDENT>assert self._M.shape[<NUM_LIT:0>] == numRowsExpected<EOL><DEDENT>assert len(self._categoryList) == numRowsExpected<EOL>self._numPatterns -= numRemoved<EOL>return numRemoved<EOL>

A list of row indices to remove. There are two caveats. First, this is
a potentially slow operation. Second, pattern indices will shift if
patterns before them are removed.


self._iterationIdx += <NUM_LIT:1><EOL>

Utility method to increment the iteration index. Intended for models that
don't learn each timestep.


def learn(self, inputPattern, inputCategory, partitionId=None, isSparse=<NUM_LIT:0>,<EOL>rowID=None):

if self.verbosity >= <NUM_LIT:1>:<EOL><INDENT>print("<STR_LIT>" % g_debugPrefix)<EOL>print("<STR_LIT>", int(inputCategory))<EOL>print("<STR_LIT>", _labeledInput(inputPattern,<EOL>cellsPerCol=self.cellsPerCol))<EOL><DEDENT>if isSparse > <NUM_LIT:0>:<EOL><INDENT>assert all(inputPattern[i] <= inputPattern[i+<NUM_LIT:1>]<EOL>for i in range(len(inputPattern)-<NUM_LIT:1>)),"<STR_LIT>"<EOL>assert all(bit < isSparse for bit in inputPattern),("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>if rowID is None:<EOL><INDENT>rowID = self._iterationIdx<EOL><DEDENT>if not self.useSparseMemory:<EOL><INDENT>assert self.cellsPerCol == <NUM_LIT:0>, "<STR_LIT>"<EOL>if isSparse > <NUM_LIT:0>:<EOL><INDENT>denseInput = numpy.zeros(isSparse)<EOL>denseInput[inputPattern] = <NUM_LIT:1.0><EOL>inputPattern = denseInput<EOL><DEDENT>if self._specificIndexTraining and not self._nextTrainingIndices:<EOL><INDENT>return self._numPatterns<EOL><DEDENT>if self._Memory is None:<EOL><INDENT>inputWidth = len(inputPattern)<EOL>self._Memory = numpy.zeros((<NUM_LIT:100>,inputWidth))<EOL>self._numPatterns = <NUM_LIT:0><EOL>self._M = self._Memory[:self._numPatterns]<EOL><DEDENT>addRow = True<EOL>if self._vt is not None:<EOL><INDENT>inputPattern = numpy.dot(self._vt, inputPattern - self._mean)<EOL><DEDENT>if self.distThreshold > <NUM_LIT:0>:<EOL><INDENT>dist = self._calcDistance(inputPattern)<EOL>minDist = dist.min()<EOL>addRow = (minDist >= self.distThreshold)<EOL><DEDENT>if addRow:<EOL><INDENT>self._protoSizes = None     <EOL>if self._numPatterns == self._Memory.shape[<NUM_LIT:0>]:<EOL><INDENT>self._doubleMemoryNumRows()<EOL><DEDENT>if not self._specificIndexTraining:<EOL><INDENT>self._Memory[self._numPatterns] = inputPattern<EOL>self._numPatterns += <NUM_LIT:1><EOL>self._categoryList.append(int(inputCategory))<EOL><DEDENT>else:<EOL><INDENT>vectorIndex = self._nextTrainingIndices.pop(<NUM_LIT:0>)<EOL>while vectorIndex >= self._Memory.shape[<NUM_LIT:0>]:<EOL><INDENT>self._doubleMemoryNumRows()<EOL><DEDENT>self._Memory[vectorIndex] = inputPattern<EOL>self._numPatterns = max(self._numPatterns, vectorIndex + <NUM_LIT:1>)<EOL>if vectorIndex >= len(self._categoryList):<EOL><INDENT>self._categoryList += [-<NUM_LIT:1>] * (vectorIndex -<EOL>len(self._categoryList) + <NUM_LIT:1>)<EOL><DEDENT>self._categoryList[vectorIndex] = int(inputCategory)<EOL><DEDENT>self._M = self._Memory[<NUM_LIT:0>:self._numPatterns]<EOL>self._addPartitionId(self._numPatterns-<NUM_LIT:1>, partitionId)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if isSparse > <NUM_LIT:0> and (self._vt is not None or self.distThreshold > <NUM_LIT:0>or self.numSVDDims is not None or self.numSVDSamples > <NUM_LIT:0>or self.numWinners > <NUM_LIT:0>):<EOL><INDENT>denseInput = numpy.zeros(isSparse)<EOL>denseInput[inputPattern] = <NUM_LIT:1.0><EOL>inputPattern = denseInput<EOL>isSparse = <NUM_LIT:0><EOL><DEDENT>if isSparse > <NUM_LIT:0>:<EOL><INDENT>inputWidth = isSparse<EOL><DEDENT>else:<EOL><INDENT>inputWidth = len(inputPattern)<EOL><DEDENT>if self._Memory is None:<EOL><INDENT>self._Memory = NearestNeighbor(<NUM_LIT:0>, inputWidth)<EOL><DEDENT>if self._vt is not None:<EOL><INDENT>inputPattern = numpy.dot(self._vt, inputPattern - self._mean)<EOL><DEDENT>if isSparse == <NUM_LIT:0>:<EOL><INDENT>thresholdedInput = self._sparsifyVector(inputPattern, True)<EOL><DEDENT>addRow = True<EOL>if self.cellsPerCol >= <NUM_LIT:1>:<EOL><INDENT>burstingCols = thresholdedInput.reshape(-<NUM_LIT:1>,<EOL>self.cellsPerCol).min(axis=<NUM_LIT:1>).nonzero()[<NUM_LIT:0>]<EOL>for col in burstingCols:<EOL><INDENT>thresholdedInput[(col * self.cellsPerCol) + <NUM_LIT:1> :<EOL>(col * self.cellsPerCol) + self.cellsPerCol] = <NUM_LIT:0><EOL><DEDENT><DEDENT>if self._Memory.nRows() > <NUM_LIT:0>:<EOL><INDENT>dist = None<EOL>if self.replaceDuplicates:<EOL><INDENT>dist = self._calcDistance(thresholdedInput, distanceNorm=<NUM_LIT:1>)<EOL>if dist.min() == <NUM_LIT:0>:<EOL><INDENT>rowIdx = dist.argmin()<EOL>self._categoryList[rowIdx] = int(inputCategory)<EOL>if self.fixedCapacity:<EOL><INDENT>self._categoryRecencyList[rowIdx] = rowID<EOL><DEDENT>addRow = False<EOL><DEDENT><DEDENT>if self.distThreshold > <NUM_LIT:0>:<EOL><INDENT>if dist is None or self.distanceNorm != <NUM_LIT:1>:<EOL><INDENT>dist = self._calcDistance(thresholdedInput)<EOL><DEDENT>minDist = dist.min()<EOL>addRow = (minDist >= self.distThreshold)<EOL>if not addRow:<EOL><INDENT>if self.fixedCapacity:<EOL><INDENT>rowIdx = dist.argmin()<EOL>self._categoryRecencyList[rowIdx] = rowID<EOL><DEDENT><DEDENT><DEDENT><DEDENT>if addRow and self.minSparsity > <NUM_LIT:0.0>:<EOL><INDENT>if isSparse==<NUM_LIT:0>:<EOL><INDENT>sparsity = ( float(len(thresholdedInput.nonzero()[<NUM_LIT:0>])) /<EOL>len(thresholdedInput) )<EOL><DEDENT>else:<EOL><INDENT>sparsity = float(len(inputPattern)) / isSparse<EOL><DEDENT>if sparsity < self.minSparsity:<EOL><INDENT>addRow = False<EOL><DEDENT><DEDENT>if addRow:<EOL><INDENT>self._protoSizes = None     <EOL>if isSparse == <NUM_LIT:0>:<EOL><INDENT>self._Memory.addRow(thresholdedInput)<EOL><DEDENT>else:<EOL><INDENT>self._Memory.addRowNZ(inputPattern, [<NUM_LIT:1>]*len(inputPattern))<EOL><DEDENT>self._numPatterns += <NUM_LIT:1><EOL>self._categoryList.append(int(inputCategory))<EOL>self._addPartitionId(self._numPatterns-<NUM_LIT:1>, partitionId)<EOL>if self.fixedCapacity:<EOL><INDENT>self._categoryRecencyList.append(rowID)<EOL>if self._numPatterns > self.maxStoredPatterns andself.maxStoredPatterns > <NUM_LIT:0>:<EOL><INDENT>leastRecentlyUsedPattern = numpy.argmin(self._categoryRecencyList)<EOL>self._Memory.deleteRow(leastRecentlyUsedPattern)<EOL>self._categoryList.pop(leastRecentlyUsedPattern)<EOL>self._categoryRecencyList.pop(leastRecentlyUsedPattern)<EOL>self._numPatterns -= <NUM_LIT:1><EOL><DEDENT><DEDENT><DEDENT><DEDENT>if self.numSVDDims is not None and self.numSVDSamples > <NUM_LIT:0>and self._numPatterns == self.numSVDSamples:<EOL><INDENT>self.computeSVD()<EOL><DEDENT>return self._numPatterns<EOL>

Train the classifier to associate specified input pattern with a
particular category.

:param inputPattern: (list) The pattern to be assigned a category. If
    isSparse is 0, this should be a dense array (both ON and OFF bits
    present). Otherwise, if isSparse > 0, this should be a list of the
    indices of the non-zero bits in sorted order

:param inputCategory: (int) The category to be associated to the training
    pattern

:param partitionId: (int) partitionID allows you to associate an id with each
    input vector. It can be used to associate input patterns stored in the
    classifier with an external id. This can be useful for debugging or
    visualizing. Another use case is to ignore vectors with a specific id
    during inference (see description of infer() for details). There can be
    at most one partitionId per stored pattern (i.e. if two patterns are
    within distThreshold, only the first partitionId will be stored). This
    is an optional parameter.

:param isSparse: (int) 0 if the input pattern is a dense representation.
    When the input pattern is a list of non-zero indices, then isSparse
    is the number of total bits (n). E.g. for the dense array
    [0, 1, 1, 0, 0, 1], isSparse should be `0`. For the equivalent sparse
    representation [1, 2, 5] (which specifies the indices of active bits),
    isSparse should be `6`, which is the total number of bits in the input
    space.

:param rowID: (int) UNKNOWN

:returns: The number of patterns currently stored in the classifier


assert self.useSparseMemory, "<STR_LIT>"<EOL>overlaps = self._Memory.rightVecSumAtNZ(inputPattern)<EOL>return (overlaps, self._categoryList)<EOL>

Return the degree of overlap between an input pattern and each category
stored in the classifier. The overlap is computed by computing:

.. code-block:: python

  logical_and(inputPattern != 0, trainingPattern != 0).sum()

:param inputPattern: pattern to check overlap of

:returns: (overlaps, categories) Two numpy arrays of the same length, where:

            * overlaps: an integer overlap amount for each category
            * categories: category index for each element of overlaps


dist = self._getDistances(inputPattern)<EOL>return (dist, self._categoryList)<EOL>

Return the distances between the input pattern and all other
        stored patterns.

        :param inputPattern: pattern to check distance with

        :returns: (distances, categories) numpy arrays of the same length.
            - overlaps: an integer overlap amount for each category
            - categories: category index for each element of distances


def infer(self, inputPattern, computeScores=True, overCategories=True,<EOL>partitionId=None):

<EOL>sparsity = <NUM_LIT:0.0><EOL>if self.minSparsity > <NUM_LIT:0.0>:<EOL><INDENT>sparsity = ( float(len(inputPattern.nonzero()[<NUM_LIT:0>])) /<EOL>len(inputPattern) )<EOL><DEDENT>if len(self._categoryList) == <NUM_LIT:0> or sparsity < self.minSparsity:<EOL><INDENT>winner = None<EOL>inferenceResult = numpy.zeros(<NUM_LIT:1>)<EOL>dist = numpy.ones(<NUM_LIT:1>)<EOL>categoryDist = numpy.ones(<NUM_LIT:1>)<EOL><DEDENT>else:<EOL><INDENT>maxCategoryIdx = max(self._categoryList)<EOL>inferenceResult = numpy.zeros(maxCategoryIdx+<NUM_LIT:1>)<EOL>dist = self._getDistances(inputPattern, partitionId=partitionId)<EOL>validVectorCount = len(self._categoryList) - self._categoryList.count(-<NUM_LIT:1>)<EOL>if self.exact:<EOL><INDENT>exactMatches = numpy.where(dist<<NUM_LIT>)[<NUM_LIT:0>]<EOL>if len(exactMatches) > <NUM_LIT:0>:<EOL><INDENT>for i in exactMatches[:min(self.k, validVectorCount)]:<EOL><INDENT>inferenceResult[self._categoryList[i]] += <NUM_LIT:1.0><EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>sorted = dist.argsort()<EOL>for j in sorted[:min(self.k, validVectorCount)]:<EOL><INDENT>inferenceResult[self._categoryList[j]] += <NUM_LIT:1.0><EOL><DEDENT><DEDENT>if inferenceResult.any():<EOL><INDENT>winner = inferenceResult.argmax()<EOL>inferenceResult /= inferenceResult.sum()<EOL><DEDENT>else:<EOL><INDENT>winner = None<EOL><DEDENT>categoryDist = min_score_per_category(maxCategoryIdx,<EOL>self._categoryList, dist)<EOL>categoryDist.clip(<NUM_LIT:0>, <NUM_LIT:1.0>, categoryDist)<EOL><DEDENT>if self.verbosity >= <NUM_LIT:1>:<EOL><INDENT>print("<STR_LIT>" % (g_debugPrefix))<EOL>print("<STR_LIT>",  _labeledInput(inputPattern,<EOL>cellsPerCol=self.cellsPerCol))<EOL>print("<STR_LIT>", winner)<EOL>print("<STR_LIT>", inferenceResult)<EOL>print("<STR_LIT>", dist)<EOL>print("<STR_LIT>", categoryDist)<EOL><DEDENT>result = (winner, inferenceResult, dist, categoryDist)<EOL>return result<EOL>

Finds the category that best matches the input pattern. Returns the
        winning category index as well as a distribution over all categories.

        :param inputPattern: (list or array) The pattern to be classified. This
            must be a dense representation of the array (e.g. [0, 0, 1, 1, 0, 1]).

        :param computeScores: NO EFFECT

        :param overCategories: NO EFFECT

        :param partitionId: (int) If provided, all training vectors with partitionId
            equal to that of the input pattern are ignored.
            For example, this may be used to perform k-fold cross validation
            without repopulating the classifier. First partition all the data into
            k equal partitions numbered 0, 1, 2, ... and then call learn() for each
            vector passing in its partitionId. Then, during inference, by passing
            in the partition ID in the call to infer(), all other vectors with the
            same partitionId are ignored simulating the effect of repopulating the
            classifier while ommitting the training vectors in the same partition.

        :returns: 4-tuple with these keys:

          - ``winner``: The category with the greatest number of nearest neighbors
              within the kth nearest neighbors. If the inferenceResult contains no
              neighbors, the value of winner is None. This can happen, for example,
              in cases of exact matching, if there are no stored vectors, or if
              minSparsity is not met.
          - ``inferenceResult``: A list of length numCategories, each entry contains
              the number of neighbors within the top k neighbors that are in that
              category.
          - ``dist``: A list of length numPrototypes. Each entry is the distance
              from the unknown to that prototype. All distances are between 0.0 and
              1.0.
          - ``categoryDist``: A list of length numCategories. Each entry is the
                            distance from the unknown to the nearest prototype of
                            that category. All distances are between 0 and 1.0.


def getClosest(self, inputPattern, topKCategories=<NUM_LIT:3>):

inferenceResult = numpy.zeros(max(self._categoryList)+<NUM_LIT:1>)<EOL>dist = self._getDistances(inputPattern)<EOL>sorted = dist.argsort()<EOL>validVectorCount = len(self._categoryList) - self._categoryList.count(-<NUM_LIT:1>)<EOL>for j in sorted[:min(self.k, validVectorCount)]:<EOL><INDENT>inferenceResult[self._categoryList[j]] += <NUM_LIT:1.0><EOL><DEDENT>winner = inferenceResult.argmax()<EOL>topNCats = []<EOL>for i in range(topKCategories):<EOL><INDENT>topNCats.append((self._categoryList[sorted[i]], dist[sorted[i]] ))<EOL><DEDENT>return winner, dist, topNCats<EOL>

Returns the index of the pattern that is closest to inputPattern,
        the distances of all patterns to inputPattern, and the indices of the k
        closest categories.


def closestTrainingPattern(self, inputPattern, cat):

dist = self._getDistances(inputPattern)<EOL>sorted = dist.argsort()<EOL>for patIdx in sorted:<EOL><INDENT>patternCat = self._categoryList[patIdx]<EOL>if patternCat == cat:<EOL><INDENT>if self.useSparseMemory:<EOL><INDENT>closestPattern = self._Memory.getRow(int(patIdx))<EOL><DEDENT>else:<EOL><INDENT>closestPattern = self._M[patIdx]<EOL><DEDENT>return closestPattern<EOL><DEDENT><DEDENT>return None<EOL>

Returns the closest training pattern to inputPattern that belongs to
        category "cat".

        :param inputPattern: The pattern whose closest neighbor is sought

        :param cat: The required category of closest neighbor

        :returns: A dense version of the closest training pattern, or None if no
            such patterns exist


def closestOtherTrainingPattern(self, inputPattern, cat):

dist = self._getDistances(inputPattern)<EOL>sorted = dist.argsort()<EOL>for patIdx in sorted:<EOL><INDENT>patternCat = self._categoryList[patIdx]<EOL>if patternCat != cat:<EOL><INDENT>if self.useSparseMemory:<EOL><INDENT>closestPattern = self._Memory.getRow(int(patIdx))<EOL><DEDENT>else:<EOL><INDENT>closestPattern = self._M[patIdx]<EOL><DEDENT>return closestPattern<EOL><DEDENT><DEDENT>return None<EOL>

Return the closest training pattern that is *not* of the given
        category "cat".

        :param inputPattern: The pattern whose closest neighbor is sought

        :param cat: Training patterns of this category will be ignored no matter
            their distance to inputPattern

        :returns: A dense version of the closest training pattern, or None if no
            such patterns exist


def getPattern(self, idx, sparseBinaryForm=False, cat=None):

if cat is not None:<EOL><INDENT>assert idx is None<EOL>idx = self._categoryList.index(cat)<EOL><DEDENT>if not self.useSparseMemory:<EOL><INDENT>pattern = self._Memory[idx]<EOL>if sparseBinaryForm:<EOL><INDENT>pattern = pattern.nonzero()[<NUM_LIT:0>]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>(nz, values) = self._Memory.rowNonZeros(idx)<EOL>if not sparseBinaryForm:<EOL><INDENT>pattern = numpy.zeros(self._Memory.nCols())<EOL>numpy.put(pattern, nz, <NUM_LIT:1>)<EOL><DEDENT>else:<EOL><INDENT>pattern = nz<EOL><DEDENT><DEDENT>return pattern<EOL>

Gets a training pattern either by index or category number.

        :param idx: Index of the training pattern

        :param sparseBinaryForm: If true, returns a list of the indices of the
            non-zero bits in the training pattern

        :param cat: If not None, get the first pattern belonging to category cat. If
            this is specified, idx must be None.

        :returns: The training pattern with specified index


if (i < <NUM_LIT:0>) or (i >= self._numPatterns):<EOL><INDENT>raise RuntimeError("<STR_LIT>")<EOL><DEDENT>partitionId = self._partitionIdList[i]<EOL>if partitionId == numpy.inf:<EOL><INDENT>return None<EOL><DEDENT>else:<EOL><INDENT>return partitionId<EOL><DEDENT>

Gets the partition id given an index.

:param i: index of partition
:returns: the partition id associated with pattern i. Returns None if no id
    is associated with it.


return self._partitionIdList<EOL>

:returns: a list of complete partition id objects


return len(self._partitionIdMap)<EOL>

:returns: the number of unique partition Ids stored.


return list(self._partitionIdMap.keys())<EOL>

:returns: a list containing unique (non-None) partition Ids (just the keys)


return self._partitionIdMap.get(partitionId, [])<EOL>

:returns: a list of pattern indices corresponding to this partitionId.
    Return an empty list if there are none.


def _addPartitionId(self, index, partitionId=None):

if partitionId is None:<EOL><INDENT>self._partitionIdList.append(numpy.inf)<EOL><DEDENT>else:<EOL><INDENT>self._partitionIdList.append(partitionId)<EOL>indices = self._partitionIdMap.get(partitionId, [])<EOL>indices.append(index)<EOL>self._partitionIdMap[partitionId] = indices<EOL><DEDENT>


self._partitionIdMap = {}<EOL>for row, partitionId in enumerate(partitionIdList):<EOL><INDENT>indices = self._partitionIdMap.get(partitionId, [])<EOL>indices.append(row)<EOL>self._partitionIdMap[partitionId] = indices<EOL><DEDENT>

Rebuilds the partition Id map using the given partitionIdList


def _calcDistance(self, inputPattern, distanceNorm=None):

if distanceNorm is None:<EOL><INDENT>distanceNorm = self.distanceNorm<EOL><DEDENT>if self.useSparseMemory:<EOL><INDENT>if self._protoSizes is None:<EOL><INDENT>self._protoSizes = self._Memory.rowSums()<EOL><DEDENT>overlapsWithProtos = self._Memory.rightVecSumAtNZ(inputPattern)<EOL>inputPatternSum = inputPattern.sum()<EOL>if self.distanceMethod == "<STR_LIT>":<EOL><INDENT>dist = inputPattern.sum() - overlapsWithProtos<EOL><DEDENT>elif self.distanceMethod == "<STR_LIT>":<EOL><INDENT>dist = inputPatternSum - overlapsWithProtos<EOL>if inputPatternSum > <NUM_LIT:0>:<EOL><INDENT>dist /= inputPatternSum<EOL><DEDENT><DEDENT>elif self.distanceMethod == "<STR_LIT>":<EOL><INDENT>overlapsWithProtos /= self._protoSizes<EOL>dist = <NUM_LIT:1.0> - overlapsWithProtos<EOL><DEDENT>elif self.distanceMethod == "<STR_LIT>":<EOL><INDENT>maxVal = numpy.maximum(self._protoSizes, inputPatternSum)<EOL>if maxVal.all() > <NUM_LIT:0>:<EOL><INDENT>overlapsWithProtos /= maxVal<EOL><DEDENT>dist = <NUM_LIT:1.0> - overlapsWithProtos<EOL><DEDENT>elif self.distanceMethod == "<STR_LIT>":<EOL><INDENT>dist = self._Memory.vecLpDist(self.distanceNorm, inputPattern)<EOL>distMax = dist.max()<EOL>if distMax > <NUM_LIT:0>:<EOL><INDENT>dist /= distMax<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise RuntimeError("<STR_LIT>" %<EOL>self.distanceMethod)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if self.distanceMethod == "<STR_LIT>":<EOL><INDENT>dist = numpy.power(numpy.abs(self._M - inputPattern), self.distanceNorm)<EOL>dist = dist.sum(<NUM_LIT:1>)<EOL>dist = numpy.power(dist, <NUM_LIT:1.0>/self.distanceNorm)<EOL>dist /= dist.max()<EOL><DEDENT>else:<EOL><INDENT>raise RuntimeError ("<STR_LIT>")<EOL><DEDENT><DEDENT>return dist<EOL>

Calculate the distances from inputPattern to all stored patterns. All
        distances are between 0.0 and 1.0

        :param inputPattern The pattern from which distances to all other patterns
            are calculated

        :param distanceNorm Degree of the distance norm


def _getDistances(self, inputPattern, partitionId=None):

if not self._finishedLearning:<EOL><INDENT>self.finishLearning()<EOL>self._finishedLearning = True<EOL><DEDENT>if self._vt is not None and len(self._vt) > <NUM_LIT:0>:<EOL><INDENT>inputPattern = numpy.dot(self._vt, inputPattern - self._mean)<EOL><DEDENT>sparseInput = self._sparsifyVector(inputPattern)<EOL>dist = self._calcDistance(sparseInput)<EOL>if self._specificIndexTraining:<EOL><INDENT>dist[numpy.array(self._categoryList) == -<NUM_LIT:1>] = numpy.inf<EOL><DEDENT>if partitionId is not None:<EOL><INDENT>dist[self._partitionIdMap.get(partitionId, [])] = numpy.inf<EOL><DEDENT>return dist<EOL>

Return the distances from inputPattern to all stored patterns.

        :param inputPattern The pattern from which distances to all other patterns
            are returned

        :param partitionId If provided, ignore all training vectors with this
            partitionId.


if self.numSVDDims is not None and self._vt is None:<EOL><INDENT>self.computeSVD()<EOL><DEDENT>

Used for batch scenarios.  This method needs to be called between learning
and inference.


def computeSVD(self, numSVDSamples=<NUM_LIT:0>, finalize=True):

if numSVDSamples == <NUM_LIT:0>:<EOL><INDENT>numSVDSamples = self._numPatterns<EOL><DEDENT>if not self.useSparseMemory:<EOL><INDENT>self._a = self._Memory[:self._numPatterns]<EOL><DEDENT>else:<EOL><INDENT>self._a = self._Memory.toDense()[:self._numPatterns]<EOL><DEDENT>self._mean = numpy.mean(self._a, axis=<NUM_LIT:0>)<EOL>self._a -= self._mean<EOL>u,self._s,self._vt = numpy.linalg.svd(self._a[:numSVDSamples])<EOL>if finalize:<EOL><INDENT>self._finalizeSVD()<EOL><DEDENT>return self._s<EOL>

Compute the singular value decomposition (SVD). The SVD is a factorization
of a real or complex matrix. It factors the matrix `a` as
`u * np.diag(s) * v`, where `u` and `v` are unitary and `s` is a 1-d array
of `a`'s singular values.

**Reason for computing the SVD:**

There are cases where you want to feed a lot of vectors to the
KNNClassifier. However, this can be slow. You can speed up training by (1)
computing the SVD of the input patterns which will give you the
eigenvectors, (2) only keeping a fraction of the eigenvectors, and (3)
projecting the input patterns onto the remaining eigenvectors.

Note that all input patterns are projected onto the eigenvectors in the same
fashion. Keeping only the highest eigenvectors increases training
performance since it reduces the dimensionality of the input.

:param numSVDSamples: (int) the number of samples to use for the SVD
                      computation.

:param finalize: (bool) whether to apply SVD to the input patterns.

:returns: (array) The singular values for every matrix, sorted in
           descending order.


def getAdaptiveSVDDims(self, singularValues, fractionOfMax=<NUM_LIT>):

v = singularValues/singularValues[<NUM_LIT:0>]<EOL>idx = numpy.where(v<fractionOfMax)[<NUM_LIT:0>]<EOL>if len(idx):<EOL><INDENT>print("<STR_LIT>", idx[<NUM_LIT:0>], "<STR_LIT>", len(v))<EOL>return idx[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>print("<STR_LIT>", len(v)-<NUM_LIT:1>, "<STR_LIT>", len(v))<EOL>return len(v)-<NUM_LIT:1><EOL><DEDENT>

Compute the number of eigenvectors (singularValues) to keep.

:param singularValues:
:param fractionOfMax:
:return:


if numSVDDims is not None:<EOL><INDENT>self.numSVDDims = numSVDDims<EOL><DEDENT>if self.numSVDDims=="<STR_LIT>":<EOL><INDENT>if self.fractionOfMax is not None:<EOL><INDENT>self.numSVDDims = self.getAdaptiveSVDDims(self._s, self.fractionOfMax)<EOL><DEDENT>else:<EOL><INDENT>self.numSVDDims = self.getAdaptiveSVDDims(self._s)<EOL><DEDENT><DEDENT>if self._vt.shape[<NUM_LIT:0>] < self.numSVDDims:<EOL><INDENT>print("<STR_LIT>")<EOL>print ("<STR_LIT>"<EOL>"<STR_LIT>")<EOL>print("<STR_LIT>", self._vt.shape[<NUM_LIT:0>])<EOL>print("<STR_LIT>")<EOL>self.numSVDDims = self._vt.shape[<NUM_LIT:0>]<EOL><DEDENT>self._vt = self._vt[:self.numSVDDims]<EOL>if len(self._vt) == <NUM_LIT:0>:<EOL><INDENT>return<EOL><DEDENT>self._Memory = numpy.zeros((self._numPatterns,self.numSVDDims))<EOL>self._M = self._Memory<EOL>self.useSparseMemory = False<EOL>for i in range(self._numPatterns):<EOL><INDENT>self._Memory[i] = numpy.dot(self._vt, self._a[i])<EOL><DEDENT>self._a = None<EOL>

Called by finalizeLearning(). This will project all the patterns onto the
SVD eigenvectors.
:param numSVDDims: (int) number of egeinvectors used for projection.
:return:


categoryArray = numpy.array(self._categoryList)<EOL>newCategoryArray = numpy.zeros(categoryArray.shape[<NUM_LIT:0>])<EOL>newCategoryArray.fill(-<NUM_LIT:1>)<EOL>for i in range(len(mapping)):<EOL><INDENT>newCategoryArray[categoryArray==i] = mapping[i]<EOL><DEDENT>self._categoryList = list(newCategoryArray)<EOL>

Change the category indices.

        Used by the Network Builder to keep the category indices in sync with the
        ImageSensor categoryInfo when the user renames or removes categories.

        :param mapping: List of new category indices. For example, mapping=[2,0,1]
            would change all vectors of category 0 to be category 2, category 1 to
            0, and category 2 to 1


def setCategoryOfVectors(self, vectorIndices, categoryIndices):

if not hasattr(vectorIndices, "<STR_LIT>"):<EOL><INDENT>vectorIndices = [vectorIndices]<EOL>categoryIndices = [categoryIndices]<EOL><DEDENT>elif not hasattr(categoryIndices, "<STR_LIT>"):<EOL><INDENT>categoryIndices = [categoryIndices] * len(vectorIndices)<EOL><DEDENT>for i in range(len(vectorIndices)):<EOL><INDENT>vectorIndex = vectorIndices[i]<EOL>categoryIndex = categoryIndices[i]<EOL>if vectorIndex < len(self._categoryList):<EOL><INDENT>self._categoryList[vectorIndex] = categoryIndex<EOL><DEDENT><DEDENT>

Change the category associated with this vector(s).

        Used by the Network Builder to move vectors between categories, to enable
        categories, and to invalidate vectors by setting the category to -1.

        :param vectorIndices: Single index or list of indices

        :param categoryIndices: Single index or list of indices. Can also be a
            single index when vectorIndices is a list, in which case the same
            category will be used for all vectors


state = self.__dict__.copy()<EOL>return state<EOL>

Return serializable state.

        This function will return a version of the __dict__.


if "<STR_LIT:version>" not in state:<EOL><INDENT>pass<EOL><DEDENT>elif state["<STR_LIT:version>"] == <NUM_LIT:1>:<EOL><INDENT>pass<EOL><DEDENT>elif state["<STR_LIT:version>"] == <NUM_LIT:2>:<EOL><INDENT>raise RuntimeError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>if "<STR_LIT>" in state:<EOL><INDENT>state.pop("<STR_LIT>")<EOL><DEDENT>if "<STR_LIT>" not in state:<EOL><INDENT>state["<STR_LIT>"] = <NUM_LIT:0.0><EOL><DEDENT>self.__dict__.update(state)<EOL>if "<STR_LIT>" not in state:<EOL><INDENT>self._rebuildPartitionIdMap(self._partitionIdList)<EOL><DEDENT>self.version = KNNCLASSIFIER_VERSION<EOL>

Set the state of this object from a serialized state.


import sys<EOL>originalPath = sys.path<EOL>try:<EOL><INDENT>augmentedPath = [path] + sys.path<EOL>sys.path = augmentedPath<EOL>func = getattr(__import__(moduleName, fromlist=[funcName]), funcName)<EOL>sys.path = originalPath<EOL><DEDENT>except:<EOL><INDENT>sys.path = originalPath<EOL>raise<EOL><DEDENT>return func(**keywords)<EOL>

Run a named function specified by a filesystem path, module name
and function name.

Returns the value returned by the imported function.

Use this when access is needed to code that has
not been added to a package accessible from the ordinary Python
path. Encapsulates the multiple lines usually needed to
safely manipulate and restore the Python path.

Parameters
----------
path: filesystem path
Path to the directory where the desired module is stored.
This will be used to temporarily augment the Python path.

moduleName: basestring
Name of the module, without trailing extension, where the desired
function is stored. This module should be in the directory specified
with path.

funcName: basestring
Name of the function to import and call.

keywords:
Keyword arguments to be passed to the imported function.


fullExpression = '<STR_LIT>''<STR_LIT>' + expression + '<STR_LIT>'<EOL>return runtimeElement.interpret(fullExpression)<EOL>

Calls runtimeElement.interpret(expression) and wraps the result
in a call to nupic.bindings.research.lockHandle().


def transferCoincidences(network, fromElementName, toElementName):

Gets the coincidence matrix from one element and sets it on
another element
(using locked handles, a la nupic.bindings.research.lockHandle).

TODO: Generalize to more node types, parameter name pairs, etc.

Does not work across processes.


numberOfCols = <NUM_LIT:1><EOL>for n in columnDimensions:<EOL><INDENT>numberOfCols *= n<EOL><DEDENT>super(TemporalMemoryShim, self).__init__(<EOL>numberOfCols=numberOfCols,<EOL>cellsPerColumn=cellsPerColumn,<EOL>initialPerm=initialPermanence,<EOL>connectedPerm=connectedPermanence,<EOL>minThreshold=minThreshold,<EOL>newSynapseCount=maxNewSynapseCount,<EOL>permanenceInc=permanenceIncrement,<EOL>permanenceDec=permanenceDecrement,<EOL>permanenceMax=<NUM_LIT:1.0>,<EOL>globalDecay=<NUM_LIT:0>,<EOL>activationThreshold=activationThreshold,<EOL>seed=seed)<EOL>self.connections = Connections(numberOfCols * cellsPerColumn)<EOL>self.predictiveCells = set()<EOL>

Translate parameters and initialize member variables
specific to TemporalMemory


def compute(self, activeColumns, learn=True):

bottomUpInput = numpy.zeros(self.numberOfCols, dtype=dtype)<EOL>bottomUpInput[list(activeColumns)] = <NUM_LIT:1><EOL>super(TemporalMemoryShim, self).compute(bottomUpInput,<EOL>enableLearn=learn,<EOL>enableInference=True)<EOL>predictedState = self.getPredictedState()<EOL>self.predictiveCells = set(numpy.flatnonzero(predictedState))<EOL>

Feeds input record through TM, performing inference and learning.
Updates member variables with new state.

@param activeColumns (set) Indices of active columns in `t`


tm = super(TemporalMemoryShim, cls).read(proto.baseTM)<EOL>tm.predictiveCells = set(proto.predictedState)<EOL>tm.connections = Connections.read(proto.conncetions)<EOL>

Deserialize from proto instance.

        :param proto: (TemporalMemoryShimProto) the proto instance to read from


super(TemporalMemoryShim, self).write(proto.baseTM)<EOL>proto.connections.write(self.connections)<EOL>proto.predictiveCells = self.predictiveCells<EOL>

Populate serialization proto instance.

        :param proto: (TemporalMemoryShimProto) the proto instance to populate


return Connections(*args, **kwargs)<EOL>

Create a :class:`~nupic.algorithms.connections.Connections` instance.
:class:`TemporalMemory` subclasses may override this method to choose a
different :class:`~nupic.algorithms.connections.Connections` implementation,
or to augment the instance otherwise returned by the default
:class:`~nupic.algorithms.connections.Connections` implementation.

See :class:`~nupic.algorithms.connections.Connections` for constructor
signature and usage.

:returns: :class:`~nupic.algorithms.connections.Connections` instance


self.activateCells(sorted(activeColumns), learn)<EOL>self.activateDendrites(learn)<EOL>

Perform one time step of the Temporal Memory algorithm.

This method calls :meth:`activateCells`, then calls
:meth:`activateDendrites`. Using :class:`TemporalMemory` via its
:meth:`compute` method ensures that you'll always be able to call
:meth:`getPredictiveCells` to get predictions for the next time step.

:param activeColumns: (iter) Indices of active columns.

:param learn: (bool) Whether or not learning is enabled.


def activateCells(self, activeColumns, learn=True):

prevActiveCells = self.activeCells<EOL>prevWinnerCells = self.winnerCells<EOL>self.activeCells = []<EOL>self.winnerCells = []<EOL>segToCol = lambda segment: int(segment.cell / self.cellsPerColumn)<EOL>identity = lambda x: x<EOL>for columnData in groupby2(activeColumns, identity,<EOL>self.activeSegments, segToCol,<EOL>self.matchingSegments, segToCol):<EOL><INDENT>(column,<EOL>activeColumns,<EOL>columnActiveSegments,<EOL>columnMatchingSegments) = columnData<EOL>if activeColumns is not None:<EOL><INDENT>if columnActiveSegments is not None:<EOL><INDENT>cellsToAdd = self.activatePredictedColumn(column,<EOL>columnActiveSegments,<EOL>columnMatchingSegments,<EOL>prevActiveCells,<EOL>prevWinnerCells,<EOL>learn)<EOL>self.activeCells += cellsToAdd<EOL>self.winnerCells += cellsToAdd<EOL><DEDENT>else:<EOL><INDENT>(cellsToAdd,<EOL>winnerCell) = self.burstColumn(column,<EOL>columnMatchingSegments,<EOL>prevActiveCells,<EOL>prevWinnerCells,<EOL>learn)<EOL>self.activeCells += cellsToAdd<EOL>self.winnerCells.append(winnerCell)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if learn:<EOL><INDENT>self.punishPredictedColumn(column,<EOL>columnActiveSegments,<EOL>columnMatchingSegments,<EOL>prevActiveCells,<EOL>prevWinnerCells)<EOL><DEDENT><DEDENT><DEDENT>

Calculate the active cells, using the current active columns and dendrite
segments. Grow and reinforce synapses.

:param activeColumns: (iter) A sorted list of active column indices.

:param learn: (bool) If true, reinforce / punish / grow synapses.

  **Pseudocode:**

  ::

    for each column
      if column is active and has active distal dendrite segments
        call activatePredictedColumn
      if column is active and doesn't have active distal dendrite segments
        call burstColumn
      if column is inactive and has matching distal dendrite segments
        call punishPredictedColumn


(numActiveConnected,<EOL>numActivePotential) = self.connections.computeActivity(<EOL>self.activeCells,<EOL>self.connectedPermanence)<EOL>activeSegments = (<EOL>self.connections.segmentForFlatIdx(i)<EOL>for i in xrange(len(numActiveConnected))<EOL>if numActiveConnected[i] >= self.activationThreshold<EOL>)<EOL>matchingSegments = (<EOL>self.connections.segmentForFlatIdx(i)<EOL>for i in xrange(len(numActivePotential))<EOL>if numActivePotential[i] >= self.minThreshold<EOL>)<EOL>self.activeSegments = sorted(activeSegments,<EOL>key=self.connections.segmentPositionSortKey)<EOL>self.matchingSegments = sorted(matchingSegments,<EOL>key=self.connections.segmentPositionSortKey)<EOL>self.numActiveConnectedSynapsesForSegment = numActiveConnected<EOL>self.numActivePotentialSynapsesForSegment = numActivePotential<EOL>if learn:<EOL><INDENT>for segment in self.activeSegments:<EOL><INDENT>self.lastUsedIterationForSegment[segment.flatIdx] = self.iteration<EOL><DEDENT>self.iteration += <NUM_LIT:1><EOL><DEDENT>

Calculate dendrite segment activity, using the current active cells.

:param learn: (bool) If true, segment activations will be recorded. This
       information is used during segment cleanup.

**Pseudocode:**

::

  for each distal dendrite segment with activity >= activationThreshold
    mark the segment as active
  for each distal dendrite segment with unconnected activity >= minThreshold
    mark the segment as matching


self.activeCells = []<EOL>self.winnerCells = []<EOL>self.activeSegments = []<EOL>self.matchingSegments = []<EOL>

Indicates the start of a new sequence. Clears any predictions and makes sure
synapses don't grow to the currently active cells in the next time step.


def activatePredictedColumn(self, column, columnActiveSegments,<EOL>columnMatchingSegments, prevActiveCells,<EOL>prevWinnerCells, learn):

return self._activatePredictedColumn(<EOL>self.connections, self._random,<EOL>columnActiveSegments, prevActiveCells, prevWinnerCells,<EOL>self.numActivePotentialSynapsesForSegment,<EOL>self.maxNewSynapseCount, self.initialPermanence,<EOL>self.permanenceIncrement, self.permanenceDecrement,<EOL>self.maxSynapsesPerSegment, learn)<EOL>

Determines which cells in a predicted column should be added to winner cells
list, and learns on the segments that correctly predicted this column.

:param column: (int) Index of bursting column.

:param columnActiveSegments: (iter) Active segments in this column.

:param columnMatchingSegments: (iter) Matching segments in this column.

:param prevActiveCells: (list) Active cells in ``t-1``.

:param prevWinnerCells: (list) Winner cells in ``t-1``.

:param learn: (bool) If true, grow and reinforce synapses.

:returns: (list) A list of predicted cells that will be added to
          active cells and winner cells.


def burstColumn(self, column, columnMatchingSegments, prevActiveCells,<EOL>prevWinnerCells, learn):

start = self.cellsPerColumn * column<EOL>cellsForColumn = xrange(start, start + self.cellsPerColumn)<EOL>return self._burstColumn(<EOL>self.connections, self._random, self.lastUsedIterationForSegment, column,<EOL>columnMatchingSegments, prevActiveCells, prevWinnerCells, cellsForColumn,<EOL>self.numActivePotentialSynapsesForSegment, self.iteration,<EOL>self.maxNewSynapseCount, self.initialPermanence, self.permanenceIncrement,<EOL>self.permanenceDecrement, self.maxSegmentsPerCell,<EOL>self.maxSynapsesPerSegment, learn)<EOL>

Activates all of the cells in an unpredicted active column, chooses a winner
cell, and, if learning is turned on, learns on one segment, growing a new
segment if necessary.

:param column: (int) Index of bursting column.

:param columnMatchingSegments: (iter) Matching segments in this column, or
       None if there aren't any.

:param prevActiveCells: (list) Active cells in ``t-1``.

:param prevWinnerCells: (list) Winner cells in ``t-1``.

:param learn: (bool) Whether or not learning is enabled.

:returns: (tuple) Contains (``cells`` [iter], ``winnerCell`` [int])


def punishPredictedColumn(self, column, columnActiveSegments,<EOL>columnMatchingSegments, prevActiveCells,<EOL>prevWinnerCells):

self._punishPredictedColumn(<EOL>self.connections, columnMatchingSegments, prevActiveCells,<EOL>self.predictedSegmentDecrement)<EOL>

Punishes the Segments that incorrectly predicted a column to be active.

:param column: (int) Index of bursting column.

:param columnActiveSegments: (iter) Active segments for this column, or None
       if there aren't any.

:param columnMatchingSegments: (iter) Matching segments for this column, or
       None if there aren't any.

:param prevActiveCells: (list) Active cells in ``t-1``.

:param prevWinnerCells: (list) Winner cells in ``t-1``.


return self._createSegment(<EOL>self.connections, self.lastUsedIterationForSegment, cell, self.iteration,<EOL>self.maxSegmentsPerCell)<EOL>

Create a :class:`~nupic.algorithms.connections.Segment` on the specified
cell. This method calls
:meth:`~nupic.algorithms.connections.Connections.createSegment` on the
underlying :class:`~nupic.algorithms.connections.Connections`, and it does
some extra bookkeeping. Unit tests should call this method, and not
:meth:`~nupic.algorithms.connections.Connections.createSegment`.

:param cell: (int) Index of cell to create a segment on.

:returns: (:class:`~nupic.algorithms.connections.Segment`) The created
          segment.


@classmethod<EOL><INDENT>def _activatePredictedColumn(cls, connections, random, columnActiveSegments,<EOL>prevActiveCells, prevWinnerCells,<EOL>numActivePotentialSynapsesForSegment,<EOL>maxNewSynapseCount, initialPermanence,<EOL>permanenceIncrement, permanenceDecrement,<EOL>maxSynapsesPerSegment, learn):<DEDENT>

cellsToAdd = []<EOL>previousCell = None<EOL>for segment in columnActiveSegments:<EOL><INDENT>if segment.cell != previousCell:<EOL><INDENT>cellsToAdd.append(segment.cell)<EOL>previousCell = segment.cell<EOL><DEDENT>if learn:<EOL><INDENT>cls._adaptSegment(connections, segment, prevActiveCells,<EOL>permanenceIncrement, permanenceDecrement)<EOL>active = numActivePotentialSynapsesForSegment[segment.flatIdx]<EOL>nGrowDesired = maxNewSynapseCount - active<EOL>if nGrowDesired > <NUM_LIT:0>:<EOL><INDENT>cls._growSynapses(connections, random, segment, nGrowDesired,<EOL>prevWinnerCells, initialPermanence,<EOL>maxSynapsesPerSegment)<EOL><DEDENT><DEDENT><DEDENT>return cellsToAdd<EOL>

:param connections: (Object)
Connections for the TM. Gets mutated.

:param random: (Object)
Random number generator. Gets mutated.

:param columnActiveSegments: (iter)
Active segments in this column.

:param prevActiveCells: (list)
Active cells in `t-1`.

:param prevWinnerCells: (list)
Winner cells in `t-1`.

:param numActivePotentialSynapsesForSegment: (list)
Number of active potential synapses per segment, indexed by the segment's
flatIdx.

:param maxNewSynapseCount: (int)
The maximum number of synapses added to a segment during learning

:param initialPermanence: (float)
Initial permanence of a new synapse.

@permanenceIncrement (float)
Amount by which permanences of synapses are incremented during learning.

@permanenceDecrement (float)
Amount by which permanences of synapses are decremented during learning.

:param maxSynapsesPerSegment: (int)
The maximum number of synapses per segment.

:param learn: (bool)
If true, grow and reinforce synapses.

:returns: cellsToAdd (list)
A list of predicted cells that will be added to active cells and winner
cells.

Pseudocode:
for each cell in the column that has an active distal dendrite segment
  mark the cell as active
  mark the cell as a winner cell
  (learning) for each active distal dendrite segment
    strengthen active synapses
    weaken inactive synapses
    grow synapses to previous winner cells


@classmethod<EOL><INDENT>def _burstColumn(cls, connections, random, lastUsedIterationForSegment,<EOL>column, columnMatchingSegments, prevActiveCells,<EOL>prevWinnerCells, cellsForColumn,<EOL>numActivePotentialSynapsesForSegment, iteration,<EOL>maxNewSynapseCount, initialPermanence, permanenceIncrement,<EOL>permanenceDecrement, maxSegmentsPerCell,<EOL>maxSynapsesPerSegment, learn):<DEDENT>

if columnMatchingSegments is not None:<EOL><INDENT>numActive = lambda s: numActivePotentialSynapsesForSegment[s.flatIdx]<EOL>bestMatchingSegment = max(columnMatchingSegments, key=numActive)<EOL>winnerCell = bestMatchingSegment.cell<EOL>if learn:<EOL><INDENT>cls._adaptSegment(connections, bestMatchingSegment, prevActiveCells,<EOL>permanenceIncrement, permanenceDecrement)<EOL>nGrowDesired = maxNewSynapseCount - numActive(bestMatchingSegment)<EOL>if nGrowDesired > <NUM_LIT:0>:<EOL><INDENT>cls._growSynapses(connections, random, bestMatchingSegment,<EOL>nGrowDesired, prevWinnerCells, initialPermanence,<EOL>maxSynapsesPerSegment)<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>winnerCell = cls._leastUsedCell(random, cellsForColumn, connections)<EOL>if learn:<EOL><INDENT>nGrowExact = min(maxNewSynapseCount, len(prevWinnerCells))<EOL>if nGrowExact > <NUM_LIT:0>:<EOL><INDENT>segment = cls._createSegment(connections,<EOL>lastUsedIterationForSegment, winnerCell,<EOL>iteration, maxSegmentsPerCell)<EOL>cls._growSynapses(connections, random, segment, nGrowExact,<EOL>prevWinnerCells, initialPermanence,<EOL>maxSynapsesPerSegment)<EOL><DEDENT><DEDENT><DEDENT>return cellsForColumn, winnerCell<EOL>

:param connections: (Object)
Connections for the TM. Gets mutated.

:param random: (Object)
Random number generator. Gets mutated.

:param lastUsedIterationForSegment: (list)
Last used iteration for each segment, indexed by the segment's flatIdx.
Gets mutated.

:param column: (int)
Index of bursting column.

:param columnMatchingSegments: (iter)
Matching segments in this column.

:param prevActiveCells: (list)
Active cells in `t-1`.

:param prevWinnerCells: (list)
Winner cells in `t-1`.

:param cellsForColumn: (sequence)
Range of cell indices on which to operate.

:param numActivePotentialSynapsesForSegment: (list)
Number of active potential synapses per segment, indexed by the segment's
flatIdx.

:param iteration: (int)
The current timestep.

:param maxNewSynapseCount: (int)
The maximum number of synapses added to a segment during learning.

:param initialPermanence: (float)
Initial permanence of a new synapse.

:param permanenceIncrement: (float)
Amount by which permanences of synapses are incremented during learning.

:param permanenceDecrement: (float)
Amount by which permanences of synapses are decremented during learning.

:param maxSegmentsPerCell: (int)
The maximum number of segments per cell.

:param maxSynapsesPerSegment: (int)
The maximum number of synapses per segment.

:param learn: (bool)
Whether or not learning is enabled.

:returns: (tuple) Contains:
                  `cells`         (iter),
                  `winnerCell`    (int),

Pseudocode:
mark all cells as active
if there are any matching distal dendrite segments
  find the most active matching segment
  mark its cell as a winner cell
  (learning)
    grow and reinforce synapses to previous winner cells
else
  find the cell with the least segments, mark it as a winner cell
  (learning)
    (optimization) if there are prev winner cells
      add a segment to this winner cell
      grow synapses to previous winner cells


@classmethod<EOL><INDENT>def _punishPredictedColumn(cls, connections, columnMatchingSegments,<EOL>prevActiveCells, predictedSegmentDecrement):<DEDENT>

if predictedSegmentDecrement > <NUM_LIT:0.0> and columnMatchingSegments is not None:<EOL><INDENT>for segment in columnMatchingSegments:<EOL><INDENT>cls._adaptSegment(connections, segment, prevActiveCells,<EOL>-predictedSegmentDecrement, <NUM_LIT:0.0>)<EOL><DEDENT><DEDENT>

:param connections: (Object)
Connections for the TM. Gets mutated.

:param columnMatchingSegments: (iter)
Matching segments for this column.

:param prevActiveCells: (list)
Active cells in `t-1`.

:param predictedSegmentDecrement: (float)
Amount by which segments are punished for incorrect predictions.

Pseudocode:
for each matching segment in the column
  weaken active synapses


@classmethod<EOL><INDENT>def _createSegment(cls, connections, lastUsedIterationForSegment, cell,<EOL>iteration, maxSegmentsPerCell):<DEDENT>

<EOL>while connections.numSegments(cell) >= maxSegmentsPerCell:<EOL><INDENT>leastRecentlyUsedSegment = min(<EOL>connections.segmentsForCell(cell),<EOL>key=lambda segment : lastUsedIterationForSegment[segment.flatIdx])<EOL>connections.destroySegment(leastRecentlyUsedSegment)<EOL><DEDENT>segment = connections.createSegment(cell)<EOL>if segment.flatIdx == len(lastUsedIterationForSegment):<EOL><INDENT>lastUsedIterationForSegment.append(iteration)<EOL><DEDENT>elif segment.flatIdx < len(lastUsedIterationForSegment):<EOL><INDENT>lastUsedIterationForSegment[segment.flatIdx] = iteration<EOL><DEDENT>else:<EOL><INDENT>raise AssertionError(<EOL>"<STR_LIT>")<EOL><DEDENT>return segment<EOL>

Create a segment on the connections, enforcing the maxSegmentsPerCell
parameter.


@classmethod<EOL><INDENT>def _destroyMinPermanenceSynapses(cls, connections, random, segment,<EOL>nDestroy, excludeCells):<DEDENT>

destroyCandidates = sorted(<EOL>(synapse for synapse in connections.synapsesForSegment(segment)<EOL>if synapse.presynapticCell not in excludeCells),<EOL>key=lambda s: s._ordinal<EOL>)<EOL>for _ in xrange(nDestroy):<EOL><INDENT>if len(destroyCandidates) == <NUM_LIT:0>:<EOL><INDENT>break<EOL><DEDENT>minSynapse = None<EOL>minPermanence = float("<STR_LIT>")<EOL>for synapse in destroyCandidates:<EOL><INDENT>if synapse.permanence < minPermanence - EPSILON:<EOL><INDENT>minSynapse = synapse<EOL>minPermanence = synapse.permanence<EOL><DEDENT><DEDENT>connections.destroySynapse(minSynapse)<EOL>destroyCandidates.remove(minSynapse)<EOL><DEDENT>

Destroy nDestroy synapses on the specified segment, but don't destroy
synapses to the "excludeCells".


@classmethod<EOL><INDENT>def _leastUsedCell(cls, random, cells, connections):<DEDENT>

leastUsedCells = []<EOL>minNumSegments = float("<STR_LIT>")<EOL>for cell in cells:<EOL><INDENT>numSegments = connections.numSegments(cell)<EOL>if numSegments < minNumSegments:<EOL><INDENT>minNumSegments = numSegments<EOL>leastUsedCells = []<EOL><DEDENT>if numSegments == minNumSegments:<EOL><INDENT>leastUsedCells.append(cell)<EOL><DEDENT><DEDENT>i = random.getUInt32(len(leastUsedCells))<EOL>return leastUsedCells[i]<EOL>

Gets the cell with the smallest number of segments.
Break ties randomly.

:param random: (Object)
Random number generator. Gets mutated.

:param cells: (list)
Indices of cells.

:param connections: (Object)
Connections instance for the TM.

:returns: (int) Cell index.


@classmethod<EOL><INDENT>def _growSynapses(cls, connections, random, segment, nDesiredNewSynapes,<EOL>prevWinnerCells, initialPermanence, maxSynapsesPerSegment):<DEDENT>

candidates = list(prevWinnerCells)<EOL>for synapse in connections.synapsesForSegment(segment):<EOL><INDENT>i = binSearch(candidates, synapse.presynapticCell)<EOL>if i != -<NUM_LIT:1>:<EOL><INDENT>del candidates[i]<EOL><DEDENT><DEDENT>nActual = min(nDesiredNewSynapes, len(candidates))<EOL>overrun = connections.numSynapses(segment) + nActual - maxSynapsesPerSegment<EOL>if overrun > <NUM_LIT:0>:<EOL><INDENT>cls._destroyMinPermanenceSynapses(connections, random, segment, overrun,<EOL>prevWinnerCells)<EOL><DEDENT>nActual = min(nActual,<EOL>maxSynapsesPerSegment - connections.numSynapses(segment))<EOL>for _ in range(nActual):<EOL><INDENT>i = random.getUInt32(len(candidates))<EOL>connections.createSynapse(segment, candidates[i], initialPermanence)<EOL>del candidates[i]<EOL><DEDENT>

Creates nDesiredNewSynapes synapses on the segment passed in if
possible, choosing random cells from the previous winner cells that are
not already on the segment.

:param connections:        (Object) Connections instance for the tm
:param random:             (Object) TM object used to generate random
                                    numbers
:param segment:            (int)    Segment to grow synapses on.
:param nDesiredNewSynapes: (int)    Desired number of synapses to grow
:param prevWinnerCells:    (list)   Winner cells in `t-1`
:param initialPermanence:  (float)  Initial permanence of a new synapse.


@classmethod<EOL><INDENT>def _adaptSegment(cls, connections, segment, prevActiveCells,<EOL>permanenceIncrement, permanenceDecrement):<DEDENT>

<EOL>synapsesToDestroy = []<EOL>for synapse in connections.synapsesForSegment(segment):<EOL><INDENT>permanence = synapse.permanence<EOL>if binSearch(prevActiveCells, synapse.presynapticCell) != -<NUM_LIT:1>:<EOL><INDENT>permanence += permanenceIncrement<EOL><DEDENT>else:<EOL><INDENT>permanence -= permanenceDecrement<EOL><DEDENT>permanence = max(<NUM_LIT:0.0>, min(<NUM_LIT:1.0>, permanence))<EOL>if permanence < EPSILON:<EOL><INDENT>synapsesToDestroy.append(synapse)<EOL><DEDENT>else:<EOL><INDENT>connections.updateSynapsePermanence(synapse, permanence)<EOL><DEDENT><DEDENT>for synapse in synapsesToDestroy:<EOL><INDENT>connections.destroySynapse(synapse)<EOL><DEDENT>if connections.numSynapses(segment) == <NUM_LIT:0>:<EOL><INDENT>connections.destroySegment(segment)<EOL><DEDENT>

Updates synapses on segment.
Strengthens active synapses; weakens inactive synapses.

:param connections:          (Object) Connections instance for the tm
:param segment:              (int)    Segment to adapt
:param prevActiveCells:      (list)   Active cells in `t-1`
:param permanenceIncrement:  (float)  Amount to increment active synapses
:param permanenceDecrement:  (float)  Amount to decrement inactive synapses


self._validateCell(cell)<EOL>return int(cell / self.cellsPerColumn)<EOL>

Returns the index of the column that a cell belongs to.

:param cell: (int) Cell index

:returns: (int) Column index


self._validateColumn(column)<EOL>start = self.cellsPerColumn * column<EOL>end = start + self.cellsPerColumn<EOL>return range(start, end)<EOL>

Returns the indices of cells that belong to a column.

:param column: (int) Column index

:returns: (list) Cell indices


return reduce(mul, self.columnDimensions, <NUM_LIT:1>)<EOL>

Returns the number of columns in this layer.

:returns: (int) Number of columns


return self.numberOfColumns() * self.cellsPerColumn<EOL>

Returns the number of cells in this layer.

:returns: (int) Number of cells


cellsForColumns = defaultdict(set)<EOL>for cell in cells:<EOL><INDENT>column = self.columnForCell(cell)<EOL>cellsForColumns[column].add(cell)<EOL><DEDENT>return cellsForColumns<EOL>

Maps cells to the columns they belong to.

:param cells: (set) Cells

:returns: (dict) Mapping from columns to their cells in `cells`


return self.getCellIndices(self.activeCells)<EOL>

Returns the indices of the active cells.

:returns: (list) Indices of active cells.


previousCell = None<EOL>predictiveCells = []<EOL>for segment in self.activeSegments:<EOL><INDENT>if segment.cell != previousCell:<EOL><INDENT>predictiveCells.append(segment.cell)<EOL>previousCell = segment.cell<EOL><DEDENT><DEDENT>return predictiveCells<EOL>

Returns the indices of the predictive cells.

        :returns: (list) Indices of predictive cells.


return self.getCellIndices(self.winnerCells)<EOL>

Returns the indices of the winner cells.

:returns: (list) Indices of winner cells.


return self.activeSegments<EOL>

Returns the active segments.

:returns: (list) Active segments


return self.matchingSegments<EOL>

Returns the matching segments.

:returns: (list) Matching segments


return self.cellsPerColumn<EOL>

Returns the number of cells per column.

:returns: (int) The number of cells per column.


return self.columnDimensions<EOL>

Returns the dimensions of the columns in the region.

:returns: (tuple) Column dimensions


return self.activationThreshold<EOL>

Returns the activation threshold.

:returns: (int) The activation threshold.


self.activationThreshold = activationThreshold<EOL>

Sets the activation threshold.

:param activationThreshold: (int) activation threshold.


return self.initialPermanence<EOL>

Get the initial permanence.

:returns: (float) The initial permanence.


self.initialPermanence = initialPermanence<EOL>

Sets the initial permanence.

:param initialPermanence: (float) The initial permanence.


return self.minThreshold<EOL>

Returns the min threshold.

:returns: (int) The min threshold.


self.minThreshold = minThreshold<EOL>

Sets the min threshold.

:param minThreshold: (int) min threshold.


return self.maxNewSynapseCount<EOL>

Returns the max new synapse count.

:returns: (int) The max new synapse count.


self.maxNewSynapseCount = maxNewSynapseCount<EOL>

Sets the max new synapse count.

:param maxNewSynapseCount: (int) Max new synapse count.


return self.permanenceIncrement<EOL>

Get the permanence increment.

:returns: (float) The permanence increment.


self.permanenceIncrement = permanenceIncrement<EOL>

Sets the permanence increment.

:param permanenceIncrement: (float) The permanence increment.


return self.permanenceDecrement<EOL>

Get the permanence decrement.

:returns: (float) The permanence decrement.


self.permanenceDecrement = permanenceDecrement<EOL>

Sets the permanence decrement.

:param permanenceDecrement: (float) The permanence decrement.


return self.predictedSegmentDecrement<EOL>

Get the predicted segment decrement.

:returns: (float) The predicted segment decrement.


self.predictedSegmentDecrement = predictedSegmentDecrement<EOL>

Sets the predicted segment decrement.

:param predictedSegmentDecrement: (float) The predicted segment decrement.


return self.connectedPermanence<EOL>

Get the connected permanence.

:returns: (float) The connected permanence.


self.connectedPermanence = connectedPermanence<EOL>

Sets the connected permanence.

:param connectedPermanence: (float) The connected permanence.


return self.maxSegmentsPerCell<EOL>

Get the maximum number of segments per cell

:returns: (int) max number of segments per cell


return self.maxSynapsesPerSegment<EOL>

Get the maximum number of synapses per segment.

:returns: (int) max number of synapses per segment


<EOL>proto.columnDimensions = list(self.columnDimensions)<EOL>proto.cellsPerColumn = self.cellsPerColumn<EOL>proto.activationThreshold = self.activationThreshold<EOL>proto.initialPermanence = round(self.initialPermanence, EPSILON_ROUND)<EOL>proto.connectedPermanence = round(self.connectedPermanence, EPSILON_ROUND)<EOL>proto.minThreshold = self.minThreshold<EOL>proto.maxNewSynapseCount = self.maxNewSynapseCount<EOL>proto.permanenceIncrement = round(self.permanenceIncrement, EPSILON_ROUND)<EOL>proto.permanenceDecrement = round(self.permanenceDecrement, EPSILON_ROUND)<EOL>proto.predictedSegmentDecrement = self.predictedSegmentDecrement<EOL>proto.maxSegmentsPerCell = self.maxSegmentsPerCell<EOL>proto.maxSynapsesPerSegment = self.maxSynapsesPerSegment<EOL>self.connections.write(proto.connections)<EOL>self._random.write(proto.random)<EOL>proto.activeCells = list(self.activeCells)<EOL>proto.winnerCells = list(self.winnerCells)<EOL>protoActiveSegments = proto.init("<STR_LIT>", len(self.activeSegments))<EOL>for i, segment in enumerate(self.activeSegments):<EOL><INDENT>protoActiveSegments[i].cell = segment.cell<EOL>idx = self.connections.segmentsForCell(segment.cell).index(segment)<EOL>protoActiveSegments[i].idxOnCell = idx<EOL><DEDENT>protoMatchingSegments = proto.init("<STR_LIT>",<EOL>len(self.matchingSegments))<EOL>for i, segment in enumerate(self.matchingSegments):<EOL><INDENT>protoMatchingSegments[i].cell = segment.cell<EOL>idx = self.connections.segmentsForCell(segment.cell).index(segment)<EOL>protoMatchingSegments[i].idxOnCell = idx<EOL><DEDENT>protoNumActivePotential = proto.init(<EOL>"<STR_LIT>",<EOL>len(self.numActivePotentialSynapsesForSegment))<EOL>for i, numActivePotentialSynapses in enumerate(<EOL>self.numActivePotentialSynapsesForSegment):<EOL><INDENT>segment = self.connections.segmentForFlatIdx(i)<EOL>if segment is not None:<EOL><INDENT>protoNumActivePotential[i].cell = segment.cell<EOL>idx = self.connections.segmentsForCell(segment.cell).index(segment)<EOL>protoNumActivePotential[i].idxOnCell = idx<EOL>protoNumActivePotential[i].number = numActivePotentialSynapses<EOL><DEDENT><DEDENT>proto.iteration = self.iteration<EOL>protoLastUsedIteration = proto.init(<EOL>"<STR_LIT>",<EOL>len(self.numActivePotentialSynapsesForSegment))<EOL>for i, lastUsed in enumerate(self.lastUsedIterationForSegment):<EOL><INDENT>segment = self.connections.segmentForFlatIdx(i)<EOL>if segment is not None:<EOL><INDENT>protoLastUsedIteration[i].cell = segment.cell<EOL>idx = self.connections.segmentsForCell(segment.cell).index(segment)<EOL>protoLastUsedIteration[i].idxOnCell = idx<EOL>protoLastUsedIteration[i].number = lastUsed<EOL><DEDENT><DEDENT>

Writes serialized data to proto object.

:param proto: (DynamicStructBuilder) Proto object


tm = object.__new__(cls)<EOL>tm.columnDimensions = tuple(proto.columnDimensions)<EOL>tm.cellsPerColumn = int(proto.cellsPerColumn)<EOL>tm.activationThreshold = int(proto.activationThreshold)<EOL>tm.initialPermanence = round(proto.initialPermanence, EPSILON_ROUND)<EOL>tm.connectedPermanence = round(proto.connectedPermanence, EPSILON_ROUND)<EOL>tm.minThreshold = int(proto.minThreshold)<EOL>tm.maxNewSynapseCount = int(proto.maxNewSynapseCount)<EOL>tm.permanenceIncrement = round(proto.permanenceIncrement, EPSILON_ROUND)<EOL>tm.permanenceDecrement = round(proto.permanenceDecrement, EPSILON_ROUND)<EOL>tm.predictedSegmentDecrement = round(proto.predictedSegmentDecrement,<EOL>EPSILON_ROUND)<EOL>tm.maxSegmentsPerCell = int(proto.maxSegmentsPerCell)<EOL>tm.maxSynapsesPerSegment = int(proto.maxSynapsesPerSegment)<EOL>tm.connections = Connections.read(proto.connections)<EOL>tm._random = Random()<EOL>tm._random.read(proto.random)<EOL>tm.activeCells = [int(x) for x in proto.activeCells]<EOL>tm.winnerCells = [int(x) for x in proto.winnerCells]<EOL>flatListLength = tm.connections.segmentFlatListLength()<EOL>tm.numActiveConnectedSynapsesForSegment = [<NUM_LIT:0>] * flatListLength<EOL>tm.numActivePotentialSynapsesForSegment = [<NUM_LIT:0>] * flatListLength<EOL>tm.lastUsedIterationForSegment = [<NUM_LIT:0>] * flatListLength<EOL>tm.activeSegments = []<EOL>tm.matchingSegments = []<EOL>for protoSegment in proto.activeSegments:<EOL><INDENT>tm.activeSegments.append(<EOL>tm.connections.getSegment(protoSegment.cell,<EOL>protoSegment.idxOnCell))<EOL><DEDENT>for protoSegment in proto.matchingSegments:<EOL><INDENT>tm.matchingSegments.append(<EOL>tm.connections.getSegment(protoSegment.cell,<EOL>protoSegment.idxOnCell))<EOL><DEDENT>for protoSegment in proto.numActivePotentialSynapsesForSegment:<EOL><INDENT>segment = tm.connections.getSegment(protoSegment.cell,<EOL>protoSegment.idxOnCell)<EOL>tm.numActivePotentialSynapsesForSegment[segment.flatIdx] = (<EOL>int(protoSegment.number))<EOL><DEDENT>tm.iteration = long(proto.iteration)<EOL>for protoSegment in proto.lastUsedIterationForSegment:<EOL><INDENT>segment = tm.connections.getSegment(protoSegment.cell,<EOL>protoSegment.idxOnCell)<EOL>tm.lastUsedIterationForSegment[segment.flatIdx] = (<EOL>long(protoSegment.number))<EOL><DEDENT>return tm<EOL>

Reads deserialized data from proto object.

:param proto: (DynamicStructBuilder) Proto object

:returns: (:class:TemporalMemory) TemporalMemory instance


if self.columnDimensions != other.columnDimensions:<EOL><INDENT>return False<EOL><DEDENT>if self.cellsPerColumn != other.cellsPerColumn:<EOL><INDENT>return False<EOL><DEDENT>if self.activationThreshold != other.activationThreshold:<EOL><INDENT>return False<EOL><DEDENT>if abs(self.initialPermanence - other.initialPermanence) > EPSILON:<EOL><INDENT>return False<EOL><DEDENT>if abs(self.connectedPermanence - other.connectedPermanence) > EPSILON:<EOL><INDENT>return False<EOL><DEDENT>if self.minThreshold != other.minThreshold:<EOL><INDENT>return False<EOL><DEDENT>if self.maxNewSynapseCount != other.maxNewSynapseCount:<EOL><INDENT>return False<EOL><DEDENT>if abs(self.permanenceIncrement - other.permanenceIncrement) > EPSILON:<EOL><INDENT>return False<EOL><DEDENT>if abs(self.permanenceDecrement - other.permanenceDecrement) > EPSILON:<EOL><INDENT>return False<EOL><DEDENT>if abs(self.predictedSegmentDecrement -<EOL>other.predictedSegmentDecrement) > EPSILON:<EOL><INDENT>return False<EOL><DEDENT>if self.connections != other.connections:<EOL><INDENT>return False<EOL><DEDENT>if self.activeCells != other.activeCells:<EOL><INDENT>return False<EOL><DEDENT>if self.winnerCells != other.winnerCells:<EOL><INDENT>return False<EOL><DEDENT>if self.matchingSegments != other.matchingSegments:<EOL><INDENT>return False<EOL><DEDENT>if self.activeSegments != other.activeSegments:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>

Non-equality operator for TemporalMemory instances.
Checks if two instances are functionally identical
(might have different internal state).

:param other: (TemporalMemory) TemporalMemory instance to compare to


return not self.__eq__(other)<EOL>

Non-equality operator for TemporalMemory instances.
Checks if two instances are not functionally identical
(might have different internal state).

:param other: (TemporalMemory) TemporalMemory instance to compare to


if column >= self.numberOfColumns() or column < <NUM_LIT:0>:<EOL><INDENT>raise IndexError("<STR_LIT>")<EOL><DEDENT>

Raises an error if column index is invalid.

:param column: (int) Column index


if cell >= self.numberOfCells() or cell < <NUM_LIT:0>:<EOL><INDENT>raise IndexError("<STR_LIT>")<EOL><DEDENT>

Raises an error if cell index is invalid.

:param cell: (int) Cell index


return [cls.getCellIndex(c) for c in cells]<EOL>

Returns the indices of the cells passed in.

:param cells: (list) cells to find the indices of


return cell<EOL>

Returns the index of the cell.

:param cell: (int) cell to find the index of


self.mmName = kwargs.get("<STR_LIT>")<EOL>if "<STR_LIT>" in kwargs:<EOL><INDENT>del kwargs["<STR_LIT>"]<EOL><DEDENT>super(MonitorMixinBase, self).__init__(*args, **kwargs)<EOL>self._mmTraces = None<EOL>self._mmData = None<EOL>self.mmClearHistory()<EOL>

Note: If you set the kwarg "mmName", then pretty-printing of traces and
      metrics will include the name you specify as a tag before every title.


self._mmTraces = {}<EOL>self._mmData = {}<EOL>


assert len(traces) > <NUM_LIT:0>, "<STR_LIT>"<EOL>table = PrettyTable(["<STR_LIT:#>"] + [trace.prettyPrintTitle() for trace in traces])<EOL>for i in xrange(len(traces[<NUM_LIT:0>].data)):<EOL><INDENT>if breakOnResets and breakOnResets.data[i]:<EOL><INDENT>table.add_row(["<STR_LIT>"] * (len(traces) + <NUM_LIT:1>))<EOL><DEDENT>table.add_row([i] +<EOL>[trace.prettyPrintDatum(trace.data[i]) for trace in traces])<EOL><DEDENT>return table.get_string().encode("<STR_LIT:utf-8>")<EOL>

Returns pretty-printed table of traces.

@param traces (list) Traces to print in table
@param breakOnResets (BoolsTrace) Trace of resets to break table on

@return (string) Pretty-printed table of traces.


assert len(metrics) > <NUM_LIT:0>, "<STR_LIT>"<EOL>table = PrettyTable(["<STR_LIT>", "<STR_LIT>", "<STR_LIT>",<EOL>"<STR_LIT>", "<STR_LIT>", "<STR_LIT>", ])<EOL>for metric in metrics:<EOL><INDENT>table.add_row([metric.prettyPrintTitle()] + metric.getStats())<EOL><DEDENT>return table.get_string().encode("<STR_LIT:utf-8>")<EOL>

Returns pretty-printed table of metrics.

@param metrics (list) Traces to print in table
@param sigFigs (int)  Number of significant figures to print

@return (string) Pretty-printed table of metrics.


return []<EOL>

Returns list of default traces. (To be overridden.)

@param verbosity (int) Verbosity level

@return (list) Default traces


return []<EOL>

Returns list of default metrics. (To be overridden.)

@param verbosity (int) Verbosity level

@return (list) Default metrics


def mmGetCellTracePlot(self, cellTrace, cellCount, activityType, title="<STR_LIT>",<EOL>showReset=False, resetShading=<NUM_LIT>):

plot = Plot(self, title)<EOL>resetTrace = self.mmGetTraceResets().data<EOL>data = numpy.zeros((cellCount, <NUM_LIT:1>))<EOL>for i in xrange(len(cellTrace)):<EOL><INDENT>if showReset and resetTrace[i]:<EOL><INDENT>activity = numpy.ones((cellCount, <NUM_LIT:1>)) * resetShading<EOL><DEDENT>else:<EOL><INDENT>activity = numpy.zeros((cellCount, <NUM_LIT:1>))<EOL><DEDENT>activeIndices = cellTrace[i]<EOL>activity[list(activeIndices)] = <NUM_LIT:1><EOL>data = numpy.concatenate((data, activity), <NUM_LIT:1>)<EOL><DEDENT>plot.add2DArray(data, xlabel="<STR_LIT>", ylabel=activityType, name=title)<EOL>return plot<EOL>

Returns plot of the cell activity. Note that if many timesteps of
activities are input, matplotlib's image interpolation may omit activities
(columns in the image).

@param cellTrace    (list)   a temporally ordered list of sets of cell
                             activities

@param cellCount    (int)    number of cells in the space being rendered

@param activityType (string) type of cell activity being displayed

@param title        (string) an optional title for the figure

@param showReset    (bool)   if true, the first set of cell activities
                             after a reset will have a grayscale background

@param resetShading (float)  applicable if showReset is true, specifies the
                             intensity of the reset background with 0.0
                             being white and 1.0 being black

@return (Plot) plot


def __init__(self, monitor, title, show=True):

self._monitor = monitor<EOL>self._title = title<EOL>self._fig = self._initFigure()<EOL>self._show = show<EOL>if self._show:<EOL><INDENT>plt.ion()<EOL>plt.show()<EOL><DEDENT>

@param monitor (MonitorMixinBase) Monitor Mixin instance that generated
                                  this plot

@param title  (string)            Plot title


def addGraph(self, data, position=<NUM_LIT>, xlabel=None, ylabel=None):

ax = self._addBase(position, xlabel=xlabel, ylabel=ylabel)<EOL>ax.plot(data)<EOL>plt.draw()<EOL>

Adds a graph to the plot's figure.

        @param data See matplotlib.Axes.plot documentation.
        @param position A 3-digit number. The first two digits define a 2D grid
                where subplots may be added. The final digit specifies the nth grid
                location for the added subplot
        @param xlabel text to be displayed on the x-axis
        @param ylabel text to be displayed on the y-axis


def addHistogram(self, data, position=<NUM_LIT>, xlabel=None, ylabel=None,<EOL>bins=None):

ax = self._addBase(position, xlabel=xlabel, ylabel=ylabel)<EOL>ax.hist(data, bins=bins, color="<STR_LIT>", alpha=<NUM_LIT>)<EOL>plt.draw()<EOL>

Adds a histogram to the plot's figure.

        @param data See matplotlib.Axes.hist documentation.
        @param position A 3-digit number. The first two digits define a 2D grid
                where subplots may be added. The final digit specifies the nth grid
                location for the added subplot
        @param xlabel text to be displayed on the x-axis
        @param ylabel text to be displayed on the y-axis


def add2DArray(self, data, position=<NUM_LIT>, xlabel=None, ylabel=None, cmap=None,<EOL>aspect="<STR_LIT>", interpolation="<STR_LIT>", name=None):

if cmap is None:<EOL><INDENT>cmap = cm.Greys<EOL><DEDENT>ax = self._addBase(position, xlabel=xlabel, ylabel=ylabel)<EOL>ax.imshow(data, cmap=cmap, aspect=aspect, interpolation=interpolation)<EOL>if self._show:<EOL><INDENT>plt.draw()<EOL><DEDENT>if name is not None:<EOL><INDENT>if not os.path.exists("<STR_LIT>"):<EOL><INDENT>os.mkdir("<STR_LIT>")<EOL><DEDENT>plt.savefig("<STR_LIT>".format(name=name), bbox_inches="<STR_LIT>",<EOL>figsize=(<NUM_LIT:8>, <NUM_LIT:6>), dpi=<NUM_LIT>)<EOL><DEDENT>

Adds an image to the plot's figure.

        @param data a 2D array. See matplotlib.Axes.imshow documentation.
        @param position A 3-digit number. The first two digits define a 2D grid
                where subplots may be added. The final digit specifies the nth grid
                location for the added subplot
        @param xlabel text to be displayed on the x-axis
        @param ylabel text to be displayed on the y-axis
        @param cmap color map used in the rendering
        @param aspect how aspect ratio is handled during resize
        @param interpolation interpolation method


def _addBase(self, position, xlabel=None, ylabel=None):

ax = self._fig.add_subplot(position)<EOL>ax.set_xlabel(xlabel)<EOL>ax.set_ylabel(ylabel)<EOL>return ax<EOL>

Adds a subplot to the plot's figure at specified position.

        @param position A 3-digit number. The first two digits define a 2D grid
                where subplots may be added. The final digit specifies the nth grid
                location for the added subplot
        @param xlabel text to be displayed on the x-axis
        @param ylabel text to be displayed on the y-axis
        @returns (matplotlib.Axes) Axes instance


return self._mmTraces["<STR_LIT>"]<EOL>


return self._mmTraces["<STR_LIT>"]<EOL>

@return (Trace) Trace of predictive cells


return self._mmTraces["<STR_LIT>"]<EOL>

@return (Trace) Trace of sequence labels


self._mmComputeTransitionTraces()<EOL>return self._mmTraces["<STR_LIT>"]<EOL>

@return (Trace) Trace of predicted => active cells


@return (Trace) Trace of predicted => inactive cells


@return (Trace) Trace of predicted => active columns


@return (Trace) Trace of predicted => inactive columns


@return (Trace) Trace of unpredicted => active columns


return Metric.createFromTrace(trace.makeCountsTrace(),<EOL>excludeResets=self.mmGetTraceResets())<EOL>

Convenience method to compute a metric over an indices trace, excluding
resets.

@param (IndicesTrace) Trace of indices

@return (Metric) Metric over trace excluding resets


self._mmComputeTransitionTraces()<EOL>numCellsPerColumn = []<EOL>for predictedActiveCells in (<EOL>self._mmData["<STR_LIT>"].values()):<EOL><INDENT>cellsForColumn = self.mapCellsToColumns(predictedActiveCells)<EOL>numCellsPerColumn += [len(x) for x in cellsForColumn.values()]<EOL><DEDENT>return Metric(self,<EOL>"<STR_LIT>",<EOL>numCellsPerColumn)<EOL>

Metric for number of predicted => active cells per column for each sequence

@return (Metric) metric


self._mmComputeTransitionTraces()<EOL>numSequencesForCell = defaultdict(lambda: <NUM_LIT:0>)<EOL>for predictedActiveCells in (<EOL>self._mmData["<STR_LIT>"].values()):<EOL><INDENT>for cell in predictedActiveCells:<EOL><INDENT>numSequencesForCell[cell] += <NUM_LIT:1><EOL><DEDENT><DEDENT>return Metric(self,<EOL>"<STR_LIT>",<EOL>numSequencesForCell.values())<EOL>

Metric for number of sequences each predicted => active cell appears in

Note: This metric is flawed when it comes to high-order sequences.

@return (Metric) metric


text = "<STR_LIT>"<EOL>text += ("<STR_LIT>"<EOL>"<STR_LIT>")<EOL>text += "<STR_LIT>"<EOL>columns = range(self.numberOfColumns())<EOL>for column in columns:<EOL><INDENT>cells = self.cellsForColumn(column)<EOL>for cell in cells:<EOL><INDENT>segmentDict = dict()<EOL>for seg in self.connections.segmentsForCell(cell):<EOL><INDENT>synapseList = []<EOL>for synapse in self.connections.synapsesForSegment(seg):<EOL><INDENT>synapseData = self.connections.dataForSynapse(synapse)<EOL>synapseList.append(<EOL>(synapseData.presynapticCell, synapseData.permanence))<EOL><DEDENT>synapseList.sort()<EOL>synapseStringList = ["<STR_LIT>".format(sourceCell, permanence) for<EOL>sourceCell, permanence in synapseList]<EOL>segmentDict[seg] = "<STR_LIT>".format("<STR_LIT:U+0020>".join(synapseStringList))<EOL><DEDENT>text += ("<STR_LIT>".format(<EOL>column, cell,<EOL>len(segmentDict.values()),<EOL>"<STR_LIT>".format("<STR_LIT:U+002CU+0020>".join(segmentDict.values()))))<EOL><DEDENT>if column < len(columns) - <NUM_LIT:1>:  <EOL><INDENT>text += "<STR_LIT:\n>"<EOL><DEDENT><DEDENT>text += "<STR_LIT>"<EOL>return text<EOL>

Pretty print the connections in the temporal memory.

TODO: Use PrettyTable.

@return (string) Pretty-printed text


self._mmComputeTransitionTraces()<EOL>table = PrettyTable(["<STR_LIT>", "<STR_LIT>", "<STR_LIT>"])<EOL>for sequenceLabel, predictedActiveCells in (<EOL>self._mmData["<STR_LIT>"].iteritems()):<EOL><INDENT>cellsForColumn = self.mapCellsToColumns(predictedActiveCells)<EOL>for column, cells in cellsForColumn.iteritems():<EOL><INDENT>table.add_row([sequenceLabel, column, list(cells)])<EOL><DEDENT><DEDENT>return table.get_string(sortby=sortby).encode("<STR_LIT:utf-8>")<EOL>

Pretty print the cell representations for sequences in the history.

@param sortby (string) Column of table to sort by

@return (string) Pretty-printed text


if not self._mmTransitionTracesStale:<EOL><INDENT>return<EOL><DEDENT>self._mmData["<STR_LIT>"] = defaultdict(set)<EOL>self._mmTraces["<STR_LIT>"] = IndicesTrace(self,<EOL>"<STR_LIT>")<EOL>self._mmTraces["<STR_LIT>"] = IndicesTrace(self,<EOL>"<STR_LIT>")<EOL>self._mmTraces["<STR_LIT>"] = IndicesTrace(self,<EOL>"<STR_LIT>")<EOL>self._mmTraces["<STR_LIT>"] = IndicesTrace(self,<EOL>"<STR_LIT>")<EOL>self._mmTraces["<STR_LIT>"] = IndicesTrace(self,<EOL>"<STR_LIT>")<EOL>predictedCellsTrace = self._mmTraces["<STR_LIT>"]<EOL>for i, activeColumns in enumerate(self.mmGetTraceActiveColumns().data):<EOL><INDENT>predictedActiveCells = set()<EOL>predictedInactiveCells = set()<EOL>predictedActiveColumns = set()<EOL>predictedInactiveColumns = set()<EOL>for predictedCell in predictedCellsTrace.data[i]:<EOL><INDENT>predictedColumn = self.columnForCell(predictedCell)<EOL>if predictedColumn  in activeColumns:<EOL><INDENT>predictedActiveCells.add(predictedCell)<EOL>predictedActiveColumns.add(predictedColumn)<EOL>sequenceLabel = self.mmGetTraceSequenceLabels().data[i]<EOL>if sequenceLabel is not None:<EOL><INDENT>self._mmData["<STR_LIT>"][sequenceLabel].add(<EOL>predictedCell)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>predictedInactiveCells.add(predictedCell)<EOL>predictedInactiveColumns.add(predictedColumn)<EOL><DEDENT><DEDENT>unpredictedActiveColumns = activeColumns - predictedActiveColumns<EOL>self._mmTraces["<STR_LIT>"].data.append(predictedActiveCells)<EOL>self._mmTraces["<STR_LIT>"].data.append(predictedInactiveCells)<EOL>self._mmTraces["<STR_LIT>"].data.append(predictedActiveColumns)<EOL>self._mmTraces["<STR_LIT>"].data.append(<EOL>predictedInactiveColumns)<EOL>self._mmTraces["<STR_LIT>"].data.append(<EOL>unpredictedActiveColumns)<EOL><DEDENT>self._mmTransitionTracesStale = False<EOL>

Computes the transition traces, if necessary.

Transition traces are the following:

    predicted => active cells
    predicted => inactive cells
    predicted => active columns
    predicted => inactive columns
    unpredicted => active columns


def mmGetCellActivityPlot(self, title="<STR_LIT>", showReset=False,<EOL>resetShading=<NUM_LIT>, activityType="<STR_LIT>"):

if activityType == "<STR_LIT>":<EOL><INDENT>self._mmComputeTransitionTraces()<EOL><DEDENT>cellTrace = copy.deepcopy(self._mmTraces[activityType].data)<EOL>for i in xrange(len(cellTrace)):<EOL><INDENT>cellTrace[i] = self.getCellIndices(cellTrace[i])<EOL><DEDENT>return self.mmGetCellTracePlot(cellTrace, self.numberOfCells(),<EOL>activityType, title, showReset,<EOL>resetShading)<EOL>

Returns plot of the cell activity.

@param title        (string)  an optional title for the figure

@param showReset    (bool)    if true, the first set of cell activities
                              after a reset will have a gray background

@param resetShading (float)   if showReset is true, this float specifies the
                              intensity of the reset background with 0.0
                              being white and 1.0 being black

@param activityType (string)  The type of cell activity to display. Valid
                              types include "activeCells",
                              "predictiveCells", "predictedCells",
                              and "predictedActiveCells"

@return (Plot) plot


def __init__(self, monitor, title, data):

self.monitor = monitor<EOL>self.title = title<EOL>self.min = None<EOL>self.max = None<EOL>self.sum = None<EOL>self.mean = None<EOL>self.standardDeviation = None<EOL>self._computeStats(data)<EOL>

@param monitor (MonitorMixinBase) Monitor Mixin instance that generated
                                  this trace
@param title   (string)           Title
@param data    (list)             List of numbers to compute metric from


self.monitor = monitor<EOL>self.title = title<EOL>self.data = []<EOL>

@param monitor (MonitorMixinBase) Monitor Mixin instance that generated
                                  this trace
@param title   (string)           Title


return str(datum) if datum is not None else "<STR_LIT>"<EOL>

@param datum (object) Datum from `self.data` to pretty-print

@return (string) Pretty-printed datum


trace = CountsTrace(self.monitor, "<STR_LIT>".format(self.title))<EOL>trace.data = [len(indices) for indices in self.data]<EOL>return trace<EOL>

@return (CountsTrace) A new Trace made up of counts of this trace's indices.


trace = CountsTrace(self.monitor, "<STR_LIT>".format(self.title))<EOL>countsTrace = self.makeCountsTrace()<EOL>def accumulate(iterator):<EOL><INDENT>total = <NUM_LIT:0><EOL>for item in iterator:<EOL><INDENT>total += item<EOL>yield total<EOL><DEDENT><DEDENT>trace.data = list(accumulate(countsTrace.data))<EOL>return trace<EOL>

@return (CountsTrace) A new Trace made up of cumulative counts of this
trace's indices.


global g_models<EOL>return json.dumps({"<STR_LIT>": g_models.keys()})<EOL>

/models

returns:
[model1, model2, model3, ...] list of model names


global g_models<EOL>data = json.loads(web.data())<EOL>modelParams = data["<STR_LIT>"]<EOL>predictedFieldName = data["<STR_LIT>"]<EOL>if name in g_models.keys():<EOL><INDENT>raise web.badrequest("<STR_LIT>" % name)<EOL><DEDENT>model = ModelFactory.create(modelParams)<EOL>model.enableInference({'<STR_LIT>': predictedFieldName})<EOL>g_models[name] = model<EOL>return json.dumps({"<STR_LIT:success>": name})<EOL>

/models/{name}

schema:
{
  "modelParams": dict containing model parameters
  "predictedFieldName": str
}

returns:
{"success":name}


global g_models<EOL>data = json.loads(web.data())<EOL>data["<STR_LIT>"] = datetime.datetime.strptime(<EOL>data["<STR_LIT>"], "<STR_LIT>")<EOL>if name not in g_models.keys():<EOL><INDENT>raise web.notfound("<STR_LIT>" % name)<EOL><DEDENT>modelResult = g_models[name].run(data)<EOL>predictionNumber = modelResult.predictionNumber<EOL>anomalyScore = modelResult.inferences["<STR_LIT>"]<EOL>return json.dumps({"<STR_LIT>": predictionNumber,<EOL>"<STR_LIT>": anomalyScore})<EOL>

/models/{name}/run

schema:
  {
    predictedFieldName: value
    timestamp: %m/%d/%y %H:%M
  }
  NOTE: predictedFieldName MUST be the same name specified when
        creating the model.

returns:
{
  "predictionNumber":<number of record>,
  "anomalyScore":anomalyScore
}


self._hsObj = hsObj<EOL>self._allResults = []<EOL>self._errModels = set()<EOL>self._numErrModels = <NUM_LIT:0><EOL>self._completedModels = set()<EOL>self._numCompletedModels = <NUM_LIT:0><EOL>self._modelIDToIdx = dict()<EOL>self._bestResult = numpy.inf<EOL>self._bestModelID = None<EOL>self._swarmBestOverall = dict()<EOL>self._swarmNumParticlesPerGeneration = dict()<EOL>self._modifiedSwarmGens = set()<EOL>self._maturedSwarmGens = set()<EOL>self._particleBest = dict()<EOL>self._particleLatestGenIdx = dict()<EOL>self._swarmIdToIndexes = dict()<EOL>self._paramsHashToIndexes = dict()<EOL>

Instantiate our results database

        Parameters:
        --------------------------------------------------------------------
        hsObj:        Reference to the HypersearchV2 instance