from nupic.math.cross import cross<EOL>shape = spaceShape<EOL>if shape[<NUM_LIT:0>] == <NUM_LIT:1> and shape[<NUM_LIT:1>] == <NUM_LIT:1>:<EOL><INDENT>centerOffsets = [(<NUM_LIT:0>,<NUM_LIT:0>)]<EOL><DEDENT>else:<EOL><INDENT>xMin = -<NUM_LIT:1> * (shape[<NUM_LIT:1>] // <NUM_LIT:2>)<EOL>xMax = xMin + shape[<NUM_LIT:1>] - <NUM_LIT:1><EOL>xPositions = list(range(stepSize * xMin, stepSize * xMax + <NUM_LIT:1>, stepSize))<EOL>yMin = -<NUM_LIT:1> * (shape[<NUM_LIT:0>] // <NUM_LIT:2>)<EOL>yMax = yMin + shape[<NUM_LIT:0>] - <NUM_LIT:1><EOL>yPositions = list(range(stepSize * yMin, stepSize * yMax + <NUM_LIT:1>, stepSize))<EOL>centerOffsets = list(cross(yPositions, xPositions))<EOL><DEDENT>numCenterOffsets = len(centerOffsets)<EOL>print("<STR_LIT>", centerOffsets)<EOL>shape = spreadShape<EOL>if shape[<NUM_LIT:0>] == <NUM_LIT:1> and shape[<NUM_LIT:1>] == <NUM_LIT:1>:<EOL><INDENT>spreadOffsets = [(<NUM_LIT:0>,<NUM_LIT:0>)]<EOL><DEDENT>else:<EOL><INDENT>xMin = -<NUM_LIT:1> * (shape[<NUM_LIT:1>] // <NUM_LIT:2>)<EOL>xMax = xMin + shape[<NUM_LIT:1>] - <NUM_LIT:1><EOL>xPositions = list(range(stepSize * xMin, stepSize * xMax + <NUM_LIT:1>, stepSize))<EOL>yMin = -<NUM_LIT:1> * (shape[<NUM_LIT:0>] // <NUM_LIT:2>)<EOL>yMax = yMin + shape[<NUM_LIT:0>] - <NUM_LIT:1><EOL>yPositions = list(range(stepSize * yMin, stepSize * yMax + <NUM_LIT:1>, stepSize))<EOL>spreadOffsets = list(cross(yPositions, xPositions))<EOL>spreadOffsets.remove((<NUM_LIT:0>,<NUM_LIT:0>))<EOL>spreadOffsets.insert(<NUM_LIT:0>, (<NUM_LIT:0>,<NUM_LIT:0>))<EOL><DEDENT>numSpreadOffsets = len(spreadOffsets)<EOL>print("<STR_LIT>", spreadOffsets)<EOL>return centerOffsets, spreadOffsets<EOL>

Generates centre offsets and spread offsets for block-mode based training
regimes - star, cross, block.

  Parameters:
  -----------------------------------------------
  spaceShape:   The (height, width) of the 2-D space to explore. This
                sets the number of center-points.
  spreadShape:  The shape (height, width) of the area around each center-point
                to explore.
  stepSize:     The step size. How big each step is, in pixels. This controls
                *both* the spacing of the center-points within the block and the
                points we explore around each center-point
  retval:       (centreOffsets, spreadOffsets)


output = numpy.zeros(self.numberOfColumns())<EOL>columns = [self.columnForCell(idx) for idx in self.getPredictiveCells()]<EOL>output[columns] = <NUM_LIT:1><EOL>return output<EOL>

(From `backtracking_tm.py`)
Top-down compute - generate expected input given output of the TM

@param topDownIn top down input from the level above us

@returns best estimate of the TM input that would have generated bottomUpOut.


tm = super(TMShimMixin, cls).read(proto)<EOL>tm.infActiveState = {"<STR_LIT:t>": None}<EOL>return tm<EOL>

Intercepts TemporalMemory deserialization request in order to initialize
`self.infActiveState`

@param proto (DynamicStructBuilder) Proto object

@return (TemporalMemory) TemporalMemory shim instance


def compute(self, bottomUpInput, enableLearn, computeInfOutput=None):

super(TMShimMixin, self).compute(set(bottomUpInput.nonzero()[<NUM_LIT:0>]),<EOL>learn=enableLearn)<EOL>numberOfCells = self.numberOfCells()<EOL>activeState = numpy.zeros(numberOfCells)<EOL>activeState[self.getActiveCells()] = <NUM_LIT:1><EOL>self.infActiveState["<STR_LIT:t>"] = activeState<EOL>output = numpy.zeros(numberOfCells)<EOL>output[self.getPredictiveCells()] = <NUM_LIT:1><EOL>output[self.getActiveCells()] = <NUM_LIT:1><EOL>return output<EOL>

(From `backtracking_tm.py`)
Handle one compute, possibly learning.

@param bottomUpInput     The bottom-up input, typically from a spatial pooler
@param enableLearn       If true, perform learning
@param computeInfOutput  If None, default behavior is to disable the inference
                         output when enableLearn is on.
                         If true, compute the inference output
                         If false, do not compute the inference output


def compute(self, recordNum, patternNZ, classification, learn, infer):

if self.verbosity >= <NUM_LIT:1>:<EOL><INDENT>print("<STR_LIT>", learn)<EOL>print("<STR_LIT>", recordNum)<EOL>print("<STR_LIT>" % len(patternNZ), patternNZ)<EOL>print("<STR_LIT>", classification)<EOL><DEDENT>if len(self._patternNZHistory) > <NUM_LIT:0>:<EOL><INDENT>if recordNum < self._patternNZHistory[-<NUM_LIT:1>][<NUM_LIT:0>]:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT><DEDENT>if len(self._patternNZHistory) == <NUM_LIT:0> orrecordNum > self._patternNZHistory[-<NUM_LIT:1>][<NUM_LIT:0>]:<EOL><INDENT>self._patternNZHistory.append((recordNum, patternNZ))<EOL><DEDENT>retval = {}<EOL>if max(patternNZ) > self._maxInputIdx:<EOL><INDENT>newMaxInputIdx = max(patternNZ)<EOL>for nSteps in self.steps:<EOL><INDENT>self._weightMatrix[nSteps] = numpy.concatenate((<EOL>self._weightMatrix[nSteps],<EOL>numpy.zeros(shape=(newMaxInputIdx-self._maxInputIdx,<EOL>self._maxBucketIdx+<NUM_LIT:1>))), axis=<NUM_LIT:0>)<EOL><DEDENT>self._maxInputIdx = int(newMaxInputIdx)<EOL><DEDENT>if classification is not None:<EOL><INDENT>if type(classification["<STR_LIT>"]) is not list:<EOL><INDENT>bucketIdxList = [classification["<STR_LIT>"]]<EOL>actValueList = [classification["<STR_LIT>"]]<EOL>numCategory = <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>bucketIdxList = classification["<STR_LIT>"]<EOL>actValueList = classification["<STR_LIT>"]<EOL>numCategory = len(classification["<STR_LIT>"])<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if learn:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>actValueList = None<EOL>bucketIdxList = None<EOL><DEDENT>if infer:<EOL><INDENT>retval = self.infer(patternNZ, actValueList)<EOL><DEDENT>if learn and classification["<STR_LIT>"] is not None:<EOL><INDENT>for categoryI in range(numCategory):<EOL><INDENT>bucketIdx = bucketIdxList[categoryI]<EOL>actValue = actValueList[categoryI]<EOL>if bucketIdx > self._maxBucketIdx:<EOL><INDENT>for nSteps in self.steps:<EOL><INDENT>self._weightMatrix[nSteps] = numpy.concatenate((<EOL>self._weightMatrix[nSteps],<EOL>numpy.zeros(shape=(self._maxInputIdx+<NUM_LIT:1>,<EOL>bucketIdx-self._maxBucketIdx))), axis=<NUM_LIT:1>)<EOL><DEDENT>self._maxBucketIdx = int(bucketIdx)<EOL><DEDENT>while self._maxBucketIdx > len(self._actualValues) - <NUM_LIT:1>:<EOL><INDENT>self._actualValues.append(None)<EOL><DEDENT>if self._actualValues[bucketIdx] is None:<EOL><INDENT>self._actualValues[bucketIdx] = actValue<EOL><DEDENT>else:<EOL><INDENT>if (isinstance(actValue, int) or<EOL>isinstance(actValue, float) or<EOL>isinstance(actValue, int)):<EOL><INDENT>self._actualValues[bucketIdx] = ((<NUM_LIT:1.0> - self.actValueAlpha)<EOL>* self._actualValues[bucketIdx]<EOL>+ self.actValueAlpha * actValue)<EOL><DEDENT>else:<EOL><INDENT>self._actualValues[bucketIdx] = actValue<EOL><DEDENT><DEDENT><DEDENT>for (learnRecordNum, learnPatternNZ) in self._patternNZHistory:<EOL><INDENT>error = self._calculateError(recordNum, bucketIdxList)<EOL>nSteps = recordNum - learnRecordNum<EOL>if nSteps in self.steps:<EOL><INDENT>for bit in learnPatternNZ:<EOL><INDENT>self._weightMatrix[nSteps][bit, :] += self.alpha * error[nSteps]<EOL><DEDENT><DEDENT><DEDENT><DEDENT>if infer and self.verbosity >= <NUM_LIT:1>:<EOL><INDENT>print("<STR_LIT>")<EOL>print("<STR_LIT>", retval["<STR_LIT>"])<EOL>for (nSteps, votes) in list(retval.items()):<EOL><INDENT>if nSteps == "<STR_LIT>":<EOL><INDENT>continue<EOL><DEDENT>print("<STR_LIT>" % (nSteps), _pFormatArray(votes))<EOL>bestBucketIdx = votes.argmax()<EOL>print(("<STR_LIT>"<EOL>"<STR_LIT>" % (bestBucketIdx,<EOL>retval["<STR_LIT>"][bestBucketIdx])))<EOL><DEDENT>print()<EOL><DEDENT>return retval<EOL>

Process one input sample.

This method is called by outer loop code outside the nupic-engine. We
use this instead of the nupic engine compute() because our inputs and
outputs aren't fixed size vectors of reals.

:param recordNum: Record number of this input pattern. Record numbers
  normally increase sequentially by 1 each time unless there are missing
  records in the dataset. Knowing this information insures that we don't get
  confused by missing records.

:param patternNZ: List of the active indices from the output below. When the
  input is from TemporalMemory, this list should be the indices of the
  active cells.

:param classification: Dict of the classification information where:

  - bucketIdx: list of indices of the encoder bucket
  - actValue: list of actual values going into the encoder

  Classification could be None for inference mode.
:param learn: (bool) if true, learn this sample
:param infer: (bool) if true, perform inference

:return:    Dict containing inference results, there is one entry for each
            step in self.steps, where the key is the number of steps, and
            the value is an array containing the relative likelihood for
            each bucketIdx starting from bucketIdx 0.

            There is also an entry containing the average actual value to
            use for each bucket. The key is 'actualValues'.

            for example:

            .. code-block:: python

               {1 :             [0.1, 0.3, 0.2, 0.7],
                 4 :             [0.2, 0.4, 0.3, 0.5],
                 'actualValues': [1.5, 3,5, 5,5, 7.6],
               }


return "<STR_LIT>" + "<STR_LIT:U+0020>".join(fmt % x for x in array_) + "<STR_LIT>"<EOL>

Return a string with pretty-print of a numpy array using the given format
    for each element


def _calculateError(self, recordNum, bucketIdxList):

error = dict()<EOL>targetDist = numpy.zeros(self._maxBucketIdx + <NUM_LIT:1>)<EOL>numCategories = len(bucketIdxList)<EOL>for bucketIdx in bucketIdxList:<EOL><INDENT>targetDist[bucketIdx] = <NUM_LIT:1.0>/numCategories<EOL><DEDENT>for (learnRecordNum, learnPatternNZ) in self._patternNZHistory:<EOL><INDENT>nSteps = recordNum - learnRecordNum<EOL>if nSteps in self.steps:<EOL><INDENT>predictDist = self.inferSingleStep(learnPatternNZ,<EOL>self._weightMatrix[nSteps])<EOL>error[nSteps] = targetDist - predictDist<EOL><DEDENT><DEDENT>return error<EOL>

Calculate error signal

:param bucketIdxList: list of encoder buckets

:return: dict containing error. The key is the number of steps
         The value is a numpy array of error at the output layer


self._synPermBelowStimulusInc = synPermBelowStimulusInc<EOL>

Sets the permanence increment amount for columns that have not been
recently active.

:param synPermBelowStimulusInc: (float) value to set.


return self._minPctOverlapDutyCycles<EOL>

:returns: (float) the minimum tolerated overlaps, given as percent of
          neighbors overlap score


self._minOverlapDutyCycles[:] = minOverlapDutyCycles[:]<EOL>

Sets the minimum overlap duty cycles for all columns.
``minOverlapDutyCycles`` size must match the number of columns.

:param minOverlapDutyCycles: (iter) value to set.


assert(localAreaDensity > <NUM_LIT:0> and localAreaDensity <= <NUM_LIT:1>)<EOL>self._localAreaDensity = localAreaDensity<EOL>self._numActiveColumnsPerInhArea = <NUM_LIT:0><EOL>

Sets the local area density. Invalidates the 'numActiveColumnsPerInhArea'
parameter

:param localAreaDensity: (float) value to set


self._updatePeriod = updatePeriod<EOL>

:param updatePeriod: (int) The period at which active duty cycles are
       updated.


centerInput = self._mapColumn(index)<EOL>columnInputs = self._getInputNeighborhood(centerInput).astype(uintType)<EOL>numPotential = int(columnInputs.size * self._potentialPct + <NUM_LIT:0.5>)<EOL>selectedInputs = numpy.empty(numPotential, dtype=uintType)<EOL>self._random.sample(columnInputs, selectedInputs)<EOL>potential = numpy.zeros(self._numInputs, dtype=uintType)<EOL>potential[selectedInputs] = <NUM_LIT:1><EOL>return potential<EOL>

Maps a column to its input bits. This method encapsulates the topology of
the region. It takes the index of the column as an argument and determines
what are the indices of the input vector that are located within the
column's potential pool. The return value is a list containing the indices
of the input bits. The current implementation of the base class only
supports a 1 dimensional topology of columns with a 1 dimensional topology
of inputs. To extend this class to support 2-D topology you will need to
override this method. Examples of the expected output of this method:
* If the potentialRadius is greater than or equal to the largest input
  dimension then each column connects to all of the inputs.
* If the topology is one dimensional, the input space is divided up evenly
  among the columns and each column is centered over its share of the
  inputs.  If the potentialRadius is 5, then each column connects to the
  input it is centered above as well as the 5 inputs to the left of that
  input and the five inputs to the right of that input, wrapping around if
  wrapAround=True.
* If the topology is two dimensional, the input space is again divided up
  evenly among the columns and each column is centered above its share of
  the inputs.  If the potentialRadius is 5, the column connects to a square
  that has 11 inputs on a side and is centered on the input that the column
  is centered above.

Parameters:
----------------------------
:param index:   The index identifying a column in the permanence, potential
                and connectivity matrices.


p = self._synPermConnected * self._random.getReal64()<EOL>p = int(p*<NUM_LIT>) / <NUM_LIT><EOL>return p<EOL>

Returns a randomly generated permanence value for a synapses that is to be
initialized in a non-connected state.


self._stimulusThreshold = stimulusThreshold<EOL>

:param stimulusThreshold: (float) value to set.


return (self._iterationNum % self._updatePeriod) == <NUM_LIT:0><EOL>

returns true if enough rounds have passed to warrant updates of
duty cycles


return self._synPermBelowStimulusInc<EOL>

:returns: (float) the permanence increment amount for columns that have not
          been recently active.


def _inhibitColumnsLocal(self, overlaps, density):

activeArray = numpy.zeros(self._numColumns, dtype="<STR_LIT:bool>")<EOL>for column, overlap in enumerate(overlaps):<EOL><INDENT>if overlap >= self._stimulusThreshold:<EOL><INDENT>neighborhood = self._getColumnNeighborhood(column)<EOL>neighborhoodOverlaps = overlaps[neighborhood]<EOL>numBigger = numpy.count_nonzero(neighborhoodOverlaps > overlap)<EOL>ties = numpy.where(neighborhoodOverlaps == overlap)<EOL>tiedNeighbors = neighborhood[ties]<EOL>numTiesLost = numpy.count_nonzero(activeArray[tiedNeighbors])<EOL>numActive = int(<NUM_LIT:0.5> + density * len(neighborhood))<EOL>if numBigger + numTiesLost < numActive:<EOL><INDENT>activeArray[column] = True<EOL><DEDENT><DEDENT><DEDENT>return activeArray.nonzero()[<NUM_LIT:0>]<EOL>

Performs local inhibition. Local inhibition is performed on a column by
column basis. Each column observes the overlaps of its neighbors and is
selected if its overlap score is within the top 'numActive' in its local
neighborhood. At most half of the columns in a local neighborhood are
allowed to be active. Columns with an overlap score below the
'stimulusThreshold' are always inhibited.

:param overlaps: an array containing the overlap score for each  column.
                The overlap score for a column is defined as the number
                of synapses in a "connected state" (connected synapses)
                that are connected to input bits which are turned on.
:param density: The fraction of columns to survive inhibition. This
                value is only an intended target. Since the surviving
                columns are picked in a local fashion, the exact fraction
                of surviving columns is likely to vary.
@return list with indices of the winning columns


return super(_SparseMatrixCorticalColumnAdapter, self).getRow(columnIndex)<EOL>

Wraps getRow() such that instances may be indexed by columnIndex.


Gets a neighborhood of columns.

Simply calls topology.neighborhood or topology.wrappingNeighborhood

A subclass can insert different topology behavior by overriding this method.

:param centerColumn (int)
The center of the neighborhood.

@returns (1D numpy array of integers)
The columns in the neighborhood.


return self._potentialRadius<EOL>


self._globalInhibition = globalInhibition<EOL>

:param globalInhibition: (bool) value to set.


def compute(self, inputVector, learn, activeArray):

if not isinstance(inputVector, numpy.ndarray):<EOL><INDENT>raise TypeError("<STR_LIT>" %<EOL>str(type(inputVector)))<EOL><DEDENT>if inputVector.size != self._numInputs:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>" % (<EOL>inputVector.size, self._numInputs))<EOL><DEDENT>self._updateBookeepingVars(learn)<EOL>inputVector = numpy.array(inputVector, dtype=realDType)<EOL>inputVector.reshape(-<NUM_LIT:1>)<EOL>self._overlaps = self._calculateOverlap(inputVector)<EOL>if learn:<EOL><INDENT>self._boostedOverlaps = self._boostFactors * self._overlaps<EOL><DEDENT>else:<EOL><INDENT>self._boostedOverlaps = self._overlaps<EOL><DEDENT>activeColumns = self._inhibitColumns(self._boostedOverlaps)<EOL>if learn:<EOL><INDENT>self._adaptSynapses(inputVector, activeColumns)<EOL>self._updateDutyCycles(self._overlaps, activeColumns)<EOL>self._bumpUpWeakColumns()<EOL>self._updateBoostFactors()<EOL>if self._isUpdateRound():<EOL><INDENT>self._updateInhibitionRadius()<EOL>self._updateMinDutyCycles()<EOL><DEDENT><DEDENT>activeArray.fill(<NUM_LIT:0>)<EOL>activeArray[activeColumns] = <NUM_LIT:1><EOL>

This is the primary public method of the SpatialPooler class. This
function takes a input vector and outputs the indices of the active columns.
If 'learn' is set to True, this method also updates the permanences of the
columns.

:param inputVector: A numpy array of 0's and 1's that comprises the input
    to the spatial pooler. The array will be treated as a one dimensional
    array, therefore the dimensions of the array do not have to match the
    exact dimensions specified in the class constructor. In fact, even a
    list would suffice. The number of input bits in the vector must,
    however, match the number of bits specified by the call to the
    constructor. Therefore there must be a '0' or '1' in the array for
    every input bit.
:param learn: A boolean value indicating whether learning should be
    performed. Learning entails updating the  permanence values of the
    synapses, and hence modifying the 'state' of the model. Setting
    learning to 'off' freezes the SP and has many uses. For example, you
    might want to feed in various inputs and examine the resulting SDR's.
:param activeArray: An array whose size is equal to the number of columns.
    Before the function returns this array will be populated with 1's at
    the indices of the active columns, and 0's everywhere else.


return self._stimulusThreshold<EOL>


self._potentialPct = potentialPct<EOL>

:param potentialPct: (float) value to set


def _updateDutyCycles(self, overlaps, activeColumns):

overlapArray = numpy.zeros(self._numColumns, dtype=realDType)<EOL>activeArray = numpy.zeros(self._numColumns, dtype=realDType)<EOL>overlapArray[overlaps > <NUM_LIT:0>] = <NUM_LIT:1><EOL>activeArray[activeColumns] = <NUM_LIT:1><EOL>period = self._dutyCyclePeriod<EOL>if (period > self._iterationNum):<EOL><INDENT>period = self._iterationNum<EOL><DEDENT>self._overlapDutyCycles = self._updateDutyCyclesHelper(<EOL>self._overlapDutyCycles,<EOL>overlapArray,<EOL>period<EOL>)<EOL>self._activeDutyCycles = self._updateDutyCyclesHelper(<EOL>self._activeDutyCycles,<EOL>activeArray,<EOL>period<EOL>)<EOL>

Updates the duty cycles for each column. The OVERLAP duty cycle is a moving
average of the number of inputs which overlapped with the each column. The
ACTIVITY duty cycles is a moving average of the frequency of activation for
each column.

Parameters:
----------------------------
:param overlaps:
                An array containing the overlap score for each column.
                The overlap score for a column is defined as the number
                of synapses in a "connected state" (connected synapses)
                that are connected to input bits which are turned on.
:param activeColumns:
                An array containing the indices of the active columns,
                the sparse set of columns which survived inhibition


self._iterationNum += <NUM_LIT:1><EOL>if learn:<EOL><INDENT>self._iterationLearnNum += <NUM_LIT:1><EOL><DEDENT>

Updates counter instance variables each round.

Parameters:
----------------------------
:param learn:   a boolean value indicating whether learning should be
                performed. Learning entails updating the  permanence
                values of the synapses, and hence modifying the 'state'
                of the model. setting learning to 'off' might be useful
                for indicating separate training vs. testing sets.


<EOL>targetDensity = numpy.zeros(self._numColumns, dtype=realDType)<EOL>for i in range(self._numColumns):<EOL><INDENT>maskNeighbors = self._getColumnNeighborhood(i)<EOL>targetDensity[i] = numpy.mean(self._activeDutyCycles[maskNeighbors])<EOL><DEDENT>self._boostFactors = numpy.exp(<EOL>(targetDensity - self._activeDutyCycles) * self._boostStrength)<EOL>

Update boost factors when local inhibition is used


def _adaptSynapses(self, inputVector, activeColumns):

inputIndices = numpy.where(inputVector > <NUM_LIT:0>)[<NUM_LIT:0>]<EOL>permChanges = numpy.zeros(self._numInputs, dtype=realDType)<EOL>permChanges.fill(-<NUM_LIT:1> * self._synPermInactiveDec)<EOL>permChanges[inputIndices] = self._synPermActiveInc<EOL>for columnIndex in activeColumns:<EOL><INDENT>perm = self._permanences[columnIndex]<EOL>maskPotential = numpy.where(self._potentialPools[columnIndex] > <NUM_LIT:0>)[<NUM_LIT:0>]<EOL>perm[maskPotential] += permChanges[maskPotential]<EOL>self._updatePermanencesForColumn(perm, columnIndex, raisePerm=True)<EOL><DEDENT>

The primary method in charge of learning. Adapts the permanence values of
the synapses based on the input vector, and the chosen columns after
inhibition round. Permanence values are increased for synapses connected to
input bits that are turned on, and decreased for synapses connected to
inputs bits that are turned off.

Parameters:
----------------------------
:param inputVector:
                A numpy array of 0's and 1's that comprises the input to
                the spatial pooler. There exists an entry in the array
                for every input bit.
:param activeColumns:
                An array containing the indices of the columns that
                survived inhibition.


def getPermanence(self, columnIndex, permanence):

assert(columnIndex < self._numColumns)<EOL>permanence[:] = self._permanences[columnIndex]<EOL>

Returns the permanence values for a given column. ``permanence`` size
must match the number of inputs.

:param columnIndex: (int) column index to get permanence for.
:param permanence: (list) will be overwritten with permanences.


return self._iterationNum<EOL>


return self._numActiveColumnsPerInhArea<EOL>

:returns: (float) the number of active columns per inhibition area. Returns
          a value less than 0 if parameter is unused.


if self._globalInhibition:<EOL><INDENT>self._inhibitionRadius = int(self._columnDimensions.max())<EOL>return<EOL><DEDENT>avgConnectedSpan = numpy.average(<EOL>[self._avgConnectedSpanForColumnND(i)<EOL>for i in range(self._numColumns)]<EOL>)<EOL>columnsPerInput = self._avgColumnsPerInput()<EOL>diameter = avgConnectedSpan * columnsPerInput<EOL>radius = (diameter - <NUM_LIT:1>) / <NUM_LIT><EOL>radius = max(<NUM_LIT:1.0>, radius)<EOL>self._inhibitionRadius = int(radius + <NUM_LIT:0.5>)<EOL>

Update the inhibition radius. The inhibition radius is a measure of the
square (or hypersquare) of columns that each a column is "connected to"
on average. Since columns are are not connected to each other directly, we
determine this quantity by first figuring out how many *inputs* a column is
connected to, and then multiplying it by the total number of columns that
exist for each input. For multiple dimension the aforementioned
calculations are averaged over all dimensions of inputs and columns. This
value is meaningless if global inhibition is enabled.


return self._inhibitionRadius<EOL>


if seed != -<NUM_LIT:1>:<EOL><INDENT>self._random = NupicRandom(seed)<EOL><DEDENT>else:<EOL><INDENT>self._random = NupicRandom()<EOL><DEDENT>


self._activeDutyCycles[:] = activeDutyCycles<EOL>

Sets the activity duty cycles for all columns. ``activeDutyCycles`` size
must match the number of columns.

:param activeDutyCycles: (list) value to set.


self._synPermActiveInc = synPermActiveInc<EOL>

Sets the permanence increment amount for active synapses.

:param synPermActiveInc: (float) value to set.


<EOL>if state['<STR_LIT>'] < <NUM_LIT:2>:<EOL><INDENT>state['<STR_LIT>'] = True<EOL><DEDENT>if state['<STR_LIT>'] < <NUM_LIT:3>:<EOL><INDENT>state['<STR_LIT>'] = numpy.zeros(self._numColumns, dtype=realDType)<EOL>state['<STR_LIT>'] = numpy.zeros(self._numColumns, dtype=realDType)<EOL><DEDENT>state['<STR_LIT>'] = VERSION<EOL>self.__dict__.update(state)<EOL>

Initialize class properties from stored values.


return super(_SparseMatrixCorticalColumnAdapter, self).setRowFromDense(<EOL>columnIndex, vector<EOL>)<EOL>


return self._numInputs<EOL>

:returns: (int) the total number of inputs.


self._boostStrength = boostStrength<EOL>

Sets the maximum boost value.
:param boostStrength: (float) value to set


self._spVerbosity = spVerbosity<EOL>

:param spVerbosity: (int) value to set, larger is more verbose.


weakColumns = numpy.where(self._overlapDutyCycles<EOL>< self._minOverlapDutyCycles)[<NUM_LIT:0>]<EOL>for columnIndex in weakColumns:<EOL><INDENT>perm = self._permanences[columnIndex].astype(realDType)<EOL>maskPotential = numpy.where(self._potentialPools[columnIndex] > <NUM_LIT:0>)[<NUM_LIT:0>]<EOL>perm[maskPotential] += self._synPermBelowStimulusInc<EOL>self._updatePermanencesForColumn(perm, columnIndex, raisePerm=False)<EOL><DEDENT>

This method increases the permanence values of synapses of columns whose
activity level has been too low. Such columns are identified by having an
overlap duty cycle that drops too much below those of their peers. The
permanence values for such columns are increased.


<EOL>if (self._localAreaDensity > <NUM_LIT:0>):<EOL><INDENT>targetDensity = self._localAreaDensity<EOL><DEDENT>else:<EOL><INDENT>inhibitionArea = ((<NUM_LIT:2> * self._inhibitionRadius + <NUM_LIT:1>)<EOL>** self._columnDimensions.size)<EOL>inhibitionArea = min(self._numColumns, inhibitionArea)<EOL>targetDensity = float(self._numActiveColumnsPerInhArea) / inhibitionArea<EOL>targetDensity = min(targetDensity, <NUM_LIT:0.5>)<EOL><DEDENT>self._boostFactors = numpy.exp(<EOL>(targetDensity - self._activeDutyCycles) * self._boostStrength)<EOL>

Update boost factors when global inhibition is used


self._minPctOverlapDutyCycles = minPctOverlapDutyCycles<EOL>

Sets the minimum tolerated activity duty cycle, given as percent of
neighbors' activity duty cycle.

:param minPctOverlapDutyCycles: (float) value to set.


self._potentialRadius = potentialRadius<EOL>

:param potentialRadius: (float) value to set


return self._synPermInactiveDec<EOL>

:returns: (float) the permanence decrement amount for inactive synapses.


assert(self._inputDimensions.size == <NUM_LIT:1>)<EOL>connected = self._connectedSynapses[columnIndex].nonzero()[<NUM_LIT:0>]<EOL>if connected.size == <NUM_LIT:0>:<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT>else:<EOL><INDENT>return max(connected) - min(connected) + <NUM_LIT:1><EOL><DEDENT>

The range of connected synapses for column. This is used to
calculate the inhibition radius. This variation of the function only
supports a 1 dimensional column topology.

Parameters:
----------------------------
:param columnIndex:   The index identifying a column in the permanence,
                      potential and connectivity matrices


activeDutyCycles[:] = self._activeDutyCycles[:]<EOL>

Gets the activity duty cycles for all columns. Input list will be
overwritten.

:param activeDutyCycles: (list) size must match number of columns.


Save Cells4 state to a file. File can be loaded with :meth:`loadFromFile`.


def _slowIsSegmentActive(self, seg, timeStep):

numSyn = seg.size()<EOL>numActiveSyns = <NUM_LIT:0><EOL>for synIdx in range(numSyn):<EOL><INDENT>if seg.getPermanence(synIdx) < self.connectedPerm:<EOL><INDENT>continue<EOL><DEDENT>sc, si = self.getColCellIdx(seg.getSrcCellIdx(synIdx))<EOL>if self.infActiveState[timeStep][sc, si]:<EOL><INDENT>numActiveSyns += <NUM_LIT:1><EOL>if numActiveSyns >= self.activationThreshold:<EOL><INDENT>return True<EOL><DEDENT><DEDENT><DEDENT>return numActiveSyns >= self.activationThreshold<EOL>

A segment is active if it has >= activationThreshold connected
synapses that are active due to infActiveState.


e = BacktrackingTM._getEphemeralMembers(self)<EOL>if self.makeCells4Ephemeral:<EOL><INDENT>e.extend(['<STR_LIT>'])<EOL><DEDENT>return e<EOL>

List of our member variables that we don't need to be saved


if self.verbosity >= <NUM_LIT:3>:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>self._setStatePointers()<EOL>self.cells4.reset()<EOL>BacktrackingTM.reset(self)<EOL>


BacktrackingTM._initEphemerals(self)<EOL>self.allocateStatesInCPP = False<EOL>self.retrieveLearningStates = False<EOL>if self.makeCells4Ephemeral:<EOL><INDENT>self._initCells4()<EOL><DEDENT>

Initialize all ephemeral members after being restored to a pickled state.


<EOL>if self.verbosity > <NUM_LIT:1> or self.retrieveLearningStates:<EOL><INDENT>(activeT, activeT1, predT, predT1) = self.cells4.getLearnStates()<EOL>self.lrnActiveState['<STR_LIT>'] = activeT1.reshape((self.numberOfCols, self.cellsPerColumn))<EOL>self.lrnActiveState['<STR_LIT:t>'] = activeT.reshape((self.numberOfCols, self.cellsPerColumn))<EOL>self.lrnPredictedState['<STR_LIT>'] = predT1.reshape((self.numberOfCols, self.cellsPerColumn))<EOL>self.lrnPredictedState['<STR_LIT:t>'] = predT.reshape((self.numberOfCols, self.cellsPerColumn))<EOL><DEDENT>if self.allocateStatesInCPP:<EOL><INDENT>assert False<EOL>(activeT, activeT1, predT, predT1, colConfidenceT, colConfidenceT1, confidenceT,<EOL>confidenceT1) = self.cells4.getStates()<EOL>self.cellConfidence['<STR_LIT:t>'] = confidenceT.reshape((self.numberOfCols, self.cellsPerColumn))<EOL>self.cellConfidence['<STR_LIT>'] = confidenceT1.reshape((self.numberOfCols, self.cellsPerColumn))<EOL>self.colConfidence['<STR_LIT:t>'] = colConfidenceT.reshape(self.numberOfCols)<EOL>self.colConfidence['<STR_LIT>'] = colConfidenceT1.reshape(self.numberOfCols)<EOL>self.infActiveState['<STR_LIT>'] = activeT1.reshape((self.numberOfCols, self.cellsPerColumn))<EOL>self.infActiveState['<STR_LIT:t>'] = activeT.reshape((self.numberOfCols, self.cellsPerColumn))<EOL>self.infPredictedState['<STR_LIT>'] = predT1.reshape((self.numberOfCols, self.cellsPerColumn))<EOL>self.infPredictedState['<STR_LIT:t>'] = predT.reshape((self.numberOfCols, self.cellsPerColumn))<EOL><DEDENT>

If state is allocated in CPP, copy over the data into our numpy arrays.


import inspect<EOL>import copy<EOL>callingFrame = inspect.stack()[<NUM_LIT:1>][<NUM_LIT:0>]<EOL>argNames, _, _, frameLocalVarDict = inspect.getargvalues(callingFrame)<EOL>argNames.remove("<STR_LIT>")<EOL>args = copy.copy(frameLocalVarDict)<EOL>for varName in frameLocalVarDict:<EOL><INDENT>if varName not in argNames:<EOL><INDENT>args.pop(varName)<EOL><DEDENT><DEDENT>return args<EOL>

Returns args dictionary from the calling method


return self.cells4.nSegmentsOnCell(c,i)<EOL>


<EOL>super(BacktrackingTMCPP, self).write(proto.baseTM)<EOL>self.cells4.write(proto.cells4)<EOL>proto.makeCells4Ephemeral = self.makeCells4Ephemeral<EOL>proto.seed = self.seed<EOL>proto.checkSynapseConsistency = self.checkSynapseConsistency<EOL>proto.initArgs = json.dumps(self._initArgsDict)<EOL>

Populate serialization proto instance.

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


def getSegmentInfo(self, collectActiveData = False):

<EOL>assert collectActiveData == False<EOL>nSegments, nSynapses = self.getNumSegments(), self.cells4.nSynapses()<EOL>distSegSizes, distNSegsPerCell = {}, {}<EOL>nActiveSegs, nActiveSynapses = <NUM_LIT:0>, <NUM_LIT:0><EOL>distPermValues = {}   <EOL>numAgeBuckets = <NUM_LIT:20><EOL>distAges = []<EOL>ageBucketSize = int((self.iterationIdx+<NUM_LIT:20>) / <NUM_LIT:20>)<EOL>for i in range(numAgeBuckets):<EOL><INDENT>distAges.append(['<STR_LIT>' % (i*ageBucketSize, (i+<NUM_LIT:1>)*ageBucketSize-<NUM_LIT:1>), <NUM_LIT:0>])<EOL><DEDENT>for c in range(self.numberOfCols):<EOL><INDENT>for i in range(self.cellsPerColumn):<EOL><INDENT>nSegmentsThisCell = self.getNumSegmentsInCell(c,i)<EOL>if nSegmentsThisCell > <NUM_LIT:0>:<EOL><INDENT>if nSegmentsThisCell in distNSegsPerCell:<EOL><INDENT>distNSegsPerCell[nSegmentsThisCell] += <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>distNSegsPerCell[nSegmentsThisCell] = <NUM_LIT:1><EOL><DEDENT>segList = self.cells4.getNonEmptySegList(c,i)<EOL>for segIdx in range(nSegmentsThisCell):<EOL><INDENT>seg = self.getSegmentOnCell(c, i, segIdx)<EOL>nSynapsesThisSeg = len(seg) - <NUM_LIT:1><EOL>if nSynapsesThisSeg > <NUM_LIT:0>:<EOL><INDENT>if nSynapsesThisSeg in distSegSizes:<EOL><INDENT>distSegSizes[nSynapsesThisSeg] += <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>distSegSizes[nSynapsesThisSeg] = <NUM_LIT:1><EOL><DEDENT>for syn in seg[<NUM_LIT:1>:]:<EOL><INDENT>p = int(syn[<NUM_LIT:2>]*<NUM_LIT:10>)<EOL>if p in distPermValues:<EOL><INDENT>distPermValues[p] += <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>distPermValues[p] = <NUM_LIT:1><EOL><DEDENT><DEDENT><DEDENT>segObj = self.cells4.getSegment(c, i, segList[segIdx])<EOL>age = self.iterationIdx - segObj.getLastActiveIteration()<EOL>ageBucket = int(age/ageBucketSize)<EOL>distAges[ageBucket][<NUM_LIT:1>] += <NUM_LIT:1><EOL><DEDENT><DEDENT><DEDENT><DEDENT>return (nSegments, nSynapses, nActiveSegs, nActiveSynapses,distSegSizes, distNSegsPerCell, distPermValues, distAges)<EOL>


def getSegmentOnCell(self, c, i, segIdx):

segList = self.cells4.getNonEmptySegList(c,i)<EOL>seg = self.cells4.getSegment(c, i, segList[segIdx])<EOL>numSyn = seg.size()<EOL>assert numSyn != <NUM_LIT:0><EOL>result = []<EOL>result.append([int(segIdx), bool(seg.isSequenceSegment()),<EOL>seg.getPositiveActivations(),<EOL>seg.getTotalActivations(), seg.getLastActiveIteration(),<EOL>seg.getLastPosDutyCycle(),<EOL>seg.getLastPosDutyCycleIteration()])<EOL>for s in range(numSyn):<EOL><INDENT>sc, si = self.getColCellIdx(seg.getSrcCellIdx(s))<EOL>result.append([int(sc), int(si), seg.getPermanence(s)])<EOL><DEDENT>return result<EOL>


return self.cells4.nSegments()<EOL>


self.__dict__.update(state)<EOL>if not hasattr(self, '<STR_LIT>'):<EOL><INDENT>self._mode = Anomaly.MODE_PURE<EOL><DEDENT>if not hasattr(self, '<STR_LIT>'):<EOL><INDENT>self._movingAverage = None<EOL><DEDENT>if not hasattr(self, '<STR_LIT>'):<EOL><INDENT>self._binaryThreshold = None<EOL><DEDENT>


def compute(self, activeColumns, predictedColumns,<EOL>inputValue=None, timestamp=None):

<EOL>anomalyScore = computeRawAnomalyScore(activeColumns, predictedColumns)<EOL>if self._mode == Anomaly.MODE_PURE:<EOL><INDENT>score = anomalyScore<EOL><DEDENT>elif self._mode == Anomaly.MODE_LIKELIHOOD:<EOL><INDENT>if inputValue is None:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>probability = self._likelihood.anomalyProbability(<EOL>inputValue, anomalyScore, timestamp)<EOL>score = <NUM_LIT:1> - probability<EOL><DEDENT>elif self._mode == Anomaly.MODE_WEIGHTED:<EOL><INDENT>probability = self._likelihood.anomalyProbability(<EOL>inputValue, anomalyScore, timestamp)<EOL>score = anomalyScore * (<NUM_LIT:1> - probability)<EOL><DEDENT>if self._movingAverage is not None:<EOL><INDENT>score = self._movingAverage.next(score)<EOL><DEDENT>if self._binaryThreshold is not None:<EOL><INDENT>if score >= self._binaryThreshold:<EOL><INDENT>score = <NUM_LIT:1.0><EOL><DEDENT>else:<EOL><INDENT>score = <NUM_LIT:0.0><EOL><DEDENT><DEDENT>return score<EOL>

Compute the anomaly score as the percent of active columns not predicted.

        :param activeColumns: array of active column indices
        :param predictedColumns: array of columns indices predicted in this step
                                 (used for anomaly in step T+1)
        :param inputValue: (optional) value of current input to encoders
                                      (eg "cat" for category encoder)
                                      (used in anomaly-likelihood)
        :param timestamp: (optional) date timestamp when the sample occured
                                     (used in anomaly-likelihood)
        :returns: the computed anomaly score; float 0..1


def freeNSynapses(self, numToFree, inactiveSynapseIndices, verbosity= <NUM_LIT:0>):

<EOL>assert (numToFree <= len(self.syns))<EOL>if (verbosity >= <NUM_LIT:4>):<EOL><INDENT>print("<STR_LIT>", numToFree, end='<STR_LIT:U+0020>')<EOL>print("<STR_LIT>", end='<STR_LIT:U+0020>')<EOL>for i in inactiveSynapseIndices:<EOL><INDENT>print(self.syns[i][<NUM_LIT:0>:<NUM_LIT:2>], end='<STR_LIT:U+0020>')<EOL><DEDENT>print()<EOL><DEDENT>if len(inactiveSynapseIndices) > <NUM_LIT:0>:<EOL><INDENT>perms = numpy.array([self.syns[i][<NUM_LIT:2>] for i in inactiveSynapseIndices])<EOL>candidates = numpy.array(inactiveSynapseIndices)[<EOL>perms.argsort()[<NUM_LIT:0>:numToFree]]<EOL>candidates = list(candidates)<EOL><DEDENT>else:<EOL><INDENT>candidates = []<EOL><DEDENT>if len(candidates) < numToFree:<EOL><INDENT>activeSynIndices = [i for i in range(len(self.syns))<EOL>if i not in inactiveSynapseIndices]<EOL>perms = numpy.array([self.syns[i][<NUM_LIT:2>] for i in activeSynIndices])<EOL>moreToFree = numToFree - len(candidates)<EOL>moreCandidates = numpy.array(activeSynIndices)[<EOL>perms.argsort()[<NUM_LIT:0>:moreToFree]]<EOL>candidates += list(moreCandidates)<EOL><DEDENT>if verbosity >= <NUM_LIT:4>:<EOL><INDENT>print("<STR_LIT>" % (<EOL>len(candidates)), candidates)<EOL>print("<STR_LIT>", end='<STR_LIT:U+0020>')<EOL>self.debugPrint()<EOL><DEDENT>synsToDelete = [self.syns[i] for i in candidates]<EOL>for syn in synsToDelete:<EOL><INDENT>self.syns.remove(syn)<EOL><DEDENT>if verbosity >= <NUM_LIT:4>:<EOL><INDENT>print("<STR_LIT>", end='<STR_LIT:U+0020>')<EOL>self.debugPrint()<EOL><DEDENT>

Free up some synapses in this segment. We always free up inactive
        synapses (lowest permanence freed up first) before we start to free up
        active ones.

        :param numToFree              number of synapses to free up
        :param inactiveSynapseIndices list of the inactive synapse indices.


self._random = pickle.loads(state)<EOL>

@internal Set the random number state.

        This is used during unit testing to generate repeatable results.


def _addToSegmentUpdates(self, c, i, segUpdate):

<EOL>if segUpdate is None or len(segUpdate.activeSynapses) == <NUM_LIT:0>:<EOL><INDENT>return<EOL><DEDENT>key = (c, i) <EOL>if key in self.segmentUpdates:<EOL><INDENT>self.segmentUpdates[key] += [(self.lrnIterationIdx, segUpdate)]<EOL><DEDENT>else:<EOL><INDENT>self.segmentUpdates[key] = [(self.lrnIterationIdx, segUpdate)]<EOL><DEDENT>

Store a dated potential segment update. The "date" (iteration index) is used
later to determine whether the update is too old and should be forgotten.
This is controlled by parameter ``segUpdateValidDuration``.

:param c: TODO: document
:param i: TODO: document
:param segUpdate: TODO: document


print("<STR_LIT>", len(self.segmentUpdates))<EOL>for key, updateList in self.segmentUpdates.items():<EOL><INDENT>c, i = key[<NUM_LIT:0>], key[<NUM_LIT:1>]<EOL>print(c, i, updateList)<EOL><DEDENT>


proto.version = TM_VERSION<EOL>self._random.write(proto.random)<EOL>proto.numberOfCols = self.numberOfCols<EOL>proto.cellsPerColumn = self.cellsPerColumn<EOL>proto.initialPerm = float(self.initialPerm)<EOL>proto.connectedPerm = float(self.connectedPerm)<EOL>proto.minThreshold = self.minThreshold<EOL>proto.newSynapseCount = self.newSynapseCount<EOL>proto.permanenceInc = float(self.permanenceInc)<EOL>proto.permanenceDec = float(self.permanenceDec)<EOL>proto.permanenceMax = float(self.permanenceMax)<EOL>proto.globalDecay = float(self.globalDecay)<EOL>proto.activationThreshold = self.activationThreshold<EOL>proto.doPooling = self.doPooling<EOL>proto.segUpdateValidDuration = self.segUpdateValidDuration<EOL>proto.burnIn = self.burnIn<EOL>proto.collectStats = self.collectStats<EOL>proto.verbosity = self.verbosity<EOL>proto.pamLength = self.pamLength<EOL>proto.maxAge = self.maxAge<EOL>proto.maxInfBacktrack = self.maxInfBacktrack<EOL>proto.maxLrnBacktrack = self.maxLrnBacktrack<EOL>proto.maxSeqLength = self.maxSeqLength<EOL>proto.maxSegmentsPerCell = self.maxSegmentsPerCell<EOL>proto.maxSynapsesPerSegment = self.maxSynapsesPerSegment<EOL>proto.outputType = self.outputType<EOL>proto.activeColumns = self.activeColumns<EOL>cellListProto = proto.init("<STR_LIT>", len(self.cells))<EOL>for i, columnSegments in enumerate(self.cells):<EOL><INDENT>columnSegmentsProto = cellListProto.init(i, len(columnSegments))<EOL>for j, cellSegments in enumerate(columnSegments):<EOL><INDENT>cellSegmentsProto = columnSegmentsProto.init(j, len(cellSegments))<EOL>for k, segment in enumerate(cellSegments):<EOL><INDENT>segment.write(cellSegmentsProto[k])<EOL><DEDENT><DEDENT><DEDENT>proto.lrnIterationIdx = self.lrnIterationIdx<EOL>proto.iterationIdx = self.iterationIdx<EOL>proto.segID = self.segID<EOL>if self.currentOutput is None:<EOL><INDENT>proto.currentOutput.none = None<EOL><DEDENT>else:<EOL><INDENT>proto.currentOutput.list = self.currentOutput.tolist()<EOL><DEDENT>proto.pamCounter = self.pamCounter<EOL>proto.collectSequenceStats = self.collectSequenceStats<EOL>proto.resetCalled = self.resetCalled<EOL>proto.avgInputDensity = self.avgInputDensity or -<NUM_LIT:1.0><EOL>proto.learnedSeqLength = self.learnedSeqLength<EOL>proto.avgLearnedSeqLength = self.avgLearnedSeqLength<EOL>proto.prevLrnPatterns = self._prevLrnPatterns<EOL>proto.prevInfPatterns = self._prevInfPatterns<EOL>segmentUpdatesListProto = proto.init("<STR_LIT>",<EOL>len(self.segmentUpdates))<EOL>for i, (key, updates) in enumerate(self.segmentUpdates.items()):<EOL><INDENT>cellSegmentUpdatesProto = segmentUpdatesListProto[i]<EOL>cellSegmentUpdatesProto.columnIdx = key[<NUM_LIT:0>]<EOL>cellSegmentUpdatesProto.cellIdx = key[<NUM_LIT:1>]<EOL>segmentUpdatesProto = cellSegmentUpdatesProto.init("<STR_LIT>",<EOL>len(updates))<EOL>for j, (lrnIterationIdx, segmentUpdate) in enumerate(updates):<EOL><INDENT>segmentUpdateWrapperProto = segmentUpdatesProto[j]<EOL>segmentUpdateWrapperProto.lrnIterationIdx = lrnIterationIdx<EOL>segmentUpdate.write(segmentUpdateWrapperProto.segmentUpdate)<EOL><DEDENT><DEDENT>proto.cellConfidenceT = self.cellConfidence["<STR_LIT:t>"].tolist()<EOL>proto.cellConfidenceT1 = self.cellConfidence["<STR_LIT>"].tolist()<EOL>proto.cellConfidenceCandidate = self.cellConfidence["<STR_LIT>"].tolist()<EOL>proto.colConfidenceT = self.colConfidence["<STR_LIT:t>"].tolist()<EOL>proto.colConfidenceT1 = self.colConfidence["<STR_LIT>"].tolist()<EOL>proto.colConfidenceCandidate = self.colConfidence["<STR_LIT>"].tolist()<EOL>proto.lrnActiveStateT = self.lrnActiveState["<STR_LIT:t>"].tolist()<EOL>proto.lrnActiveStateT1 = self.lrnActiveState["<STR_LIT>"].tolist()<EOL>proto.infActiveStateT = self.infActiveState["<STR_LIT:t>"].tolist()<EOL>proto.infActiveStateT1 = self.infActiveState["<STR_LIT>"].tolist()<EOL>proto.infActiveStateBackup = self.infActiveState["<STR_LIT>"].tolist()<EOL>proto.infActiveStateCandidate = self.infActiveState["<STR_LIT>"].tolist()<EOL>proto.lrnPredictedStateT = self.lrnPredictedState["<STR_LIT:t>"].tolist()<EOL>proto.lrnPredictedStateT1 = self.lrnPredictedState["<STR_LIT>"].tolist()<EOL>proto.infPredictedStateT = self.infPredictedState["<STR_LIT:t>"].tolist()<EOL>proto.infPredictedStateT1 = self.infPredictedState["<STR_LIT>"].tolist()<EOL>proto.infPredictedStateBackup = self.infPredictedState["<STR_LIT>"].tolist()<EOL>proto.infPredictedStateCandidate = self.infPredictedState["<STR_LIT>"].tolist()<EOL>proto.consolePrinterVerbosity = self.consolePrinterVerbosity<EOL>

Populate serialization proto instance.

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


return self.compute(bottomUpInput, enableLearn=False)<EOL>

TODO: document

:param bottomUpInput:
:return:


print("<STR_LIT>")<EOL>for c in range(self.numberOfCols):<EOL><INDENT>print(int(x[c]), end='<STR_LIT:U+0020>')<EOL><DEDENT>print()<EOL>


<EOL>print("<STR_LIT>" % (self.segID), end='<STR_LIT:U+0020>')<EOL>if self.isSequenceSeg:<EOL><INDENT>print("<STR_LIT:True>", end='<STR_LIT:U+0020>')<EOL><DEDENT>else:<EOL><INDENT>print("<STR_LIT:False>", end='<STR_LIT:U+0020>')<EOL><DEDENT>print("<STR_LIT>" % (self.dutyCycle(readOnly=True)), end='<STR_LIT:U+0020>')<EOL>print("<STR_LIT>" % (self.positiveActivations,<EOL>self.totalActivations), end='<STR_LIT:U+0020>')<EOL>print("<STR_LIT>" % (self.tm.lrnIterationIdx - self.lastActiveIteration), end='<STR_LIT:U+0020>')<EOL>sortedSyns = sorted(self.syns)<EOL>for _, synapse in enumerate(sortedSyns):<EOL><INDENT>print("<STR_LIT>" % (synapse[<NUM_LIT:0>], synapse[<NUM_LIT:1>], synapse[<NUM_LIT:2>]), end='<STR_LIT:U+0020>')<EOL><DEDENT>print()<EOL>

Print segment information for verbose messaging and debugging.
        This uses the following format:

         ID:54413 True 0.64801 (24/36) 101 [9,1]0.75 [10,1]0.75 [11,1]0.75

        where:
          54413 - is the unique segment id
          True - is sequence segment
          0.64801 - moving average duty cycle
          (24/36) - (numPositiveActivations / numTotalActivations)
          101 - age, number of iterations since last activated
          [9,1]0.75 - synapse from column 9, cell #1, strength 0.75
          [10,1]0.75 - synapse from column 10, cell #1, strength 0.75
          [11,1]0.75 - synapse from column 11, cell #1, strength 0.75


def _trimSegmentsInCell(self, colIdx, cellIdx, segList, minPermanence,<EOL>minNumSyns):

<EOL>if minPermanence is None:<EOL><INDENT>minPermanence = self.connectedPerm<EOL><DEDENT>if minNumSyns is None:<EOL><INDENT>minNumSyns = self.activationThreshold<EOL><DEDENT>nSegsRemoved, nSynsRemoved = <NUM_LIT:0>, <NUM_LIT:0><EOL>segsToDel = [] <EOL>for segment in segList:<EOL><INDENT>synsToDel = [syn for syn in segment.syns if syn[<NUM_LIT:2>] < minPermanence]<EOL>if len(synsToDel) == len(segment.syns):<EOL><INDENT>segsToDel.append(segment) <EOL><DEDENT>else:<EOL><INDENT>if len(synsToDel) > <NUM_LIT:0>:<EOL><INDENT>for syn in synsToDel: <EOL><INDENT>segment.syns.remove(syn)<EOL>nSynsRemoved += <NUM_LIT:1><EOL><DEDENT><DEDENT>if len(segment.syns) < minNumSyns:<EOL><INDENT>segsToDel.append(segment)<EOL><DEDENT><DEDENT><DEDENT>nSegsRemoved += len(segsToDel)<EOL>for seg in segsToDel: <EOL><INDENT>self._cleanUpdatesList(colIdx, cellIdx, seg)<EOL>self.cells[colIdx][cellIdx].remove(seg)<EOL>nSynsRemoved += len(seg.syns)<EOL><DEDENT>return nSegsRemoved, nSynsRemoved<EOL>

This method goes through a list of segments for a given cell and
deletes all synapses whose permanence is less than minPermanence and deletes
any segments that have less than minNumSyns synapses remaining.

:param colIdx        Column index
:param cellIdx       Cell index within the column
:param segList       List of segment references
:param minPermanence Any syn whose permamence is 0 or < minPermanence will
                     be deleted.
:param minNumSyns    Any segment with less than minNumSyns synapses remaining
                     in it will be deleted.

:returns: tuple (numSegsRemoved, numSynsRemoved)


<EOL>numPrevPatterns = len(self._prevLrnPatterns) - <NUM_LIT:1><EOL>if numPrevPatterns <= <NUM_LIT:0>:<EOL><INDENT>if self.verbosity >= <NUM_LIT:3>:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>return False<EOL><DEDENT>badPatterns = []<EOL>inSequence = False<EOL>for startOffset in range(<NUM_LIT:0>, numPrevPatterns):<EOL><INDENT>inSequence = self._learnBacktrackFrom(startOffset, readOnly=True)<EOL>if inSequence:<EOL><INDENT>break<EOL><DEDENT>badPatterns.append(startOffset)<EOL><DEDENT>if not inSequence:<EOL><INDENT>if self.verbosity >= <NUM_LIT:3>:<EOL><INDENT>print ("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>self._prevLrnPatterns = []<EOL>return False<EOL><DEDENT>if self.verbosity >= <NUM_LIT:3>:<EOL><INDENT>print(("<STR_LIT>"<EOL>"<STR_LIT>" % (numPrevPatterns - startOffset),<EOL>self._prevLrnPatterns[startOffset]))<EOL><DEDENT>self._learnBacktrackFrom(startOffset, readOnly=False)<EOL>for i in range(numPrevPatterns):<EOL><INDENT>if i in badPatterns or i <= startOffset:<EOL><INDENT>if self.verbosity >= <NUM_LIT:3>:<EOL><INDENT>print(("<STR_LIT>",<EOL>self._prevLrnPatterns[<NUM_LIT:0>]))<EOL><DEDENT>self._prevLrnPatterns.pop(<NUM_LIT:0>)<EOL><DEDENT>else:<EOL><INDENT>break<EOL><DEDENT><DEDENT>return numPrevPatterns - startOffset<EOL>

This "backtracks" our learning state, trying to see if we can lock onto
the current set of inputs by assuming the sequence started up to N steps
ago on start cells.

This will adjust @ref lrnActiveState['t'] if it does manage to lock on to a
sequence that started earlier.

:returns:          >0 if we managed to lock on to a sequence that started
                  earlier. The value returned is how many steps in the
                  past we locked on.
                  If 0 is returned, the caller needs to change active
                  state to start on start cells.

How it works:
-------------------------------------------------------------------
This method gets called from updateLearningState when we detect either of
the following two conditions:

#. Our PAM counter (@ref pamCounter) expired
#. We reached the max allowed learned sequence length

Either of these two conditions indicate that we want to start over on start
cells.

Rather than start over on start cells on the current input, we can
accelerate learning by backtracking a few steps ago and seeing if perhaps
a sequence we already at least partially know already started.

This updates/modifies:
    - @ref lrnActiveState['t']

This trashes:
    - @ref lrnActiveState['t-1']
    - @ref lrnPredictedState['t']
    - @ref lrnPredictedState['t-1']


def trimSegments(self, minPermanence=None, minNumSyns=None):

<EOL>if minPermanence is None:<EOL><INDENT>minPermanence = self.connectedPerm<EOL><DEDENT>if minNumSyns is None:<EOL><INDENT>minNumSyns = self.activationThreshold<EOL><DEDENT>totalSegsRemoved, totalSynsRemoved = <NUM_LIT:0>, <NUM_LIT:0><EOL>for c, i in itertools.product(range(self.numberOfCols),<EOL>range(self.cellsPerColumn)):<EOL><INDENT>(segsRemoved, synsRemoved) = self._trimSegmentsInCell(<EOL>colIdx=c, cellIdx=i, segList=self.cells[c][i],<EOL>minPermanence=minPermanence, minNumSyns=minNumSyns)<EOL>totalSegsRemoved += segsRemoved<EOL>totalSynsRemoved += synsRemoved<EOL><DEDENT>if self.verbosity >= <NUM_LIT:5>:<EOL><INDENT>print("<STR_LIT>")<EOL>self.printCells(predictedOnly=False)<EOL><DEDENT>return totalSegsRemoved, totalSynsRemoved<EOL>

This method deletes all synapses whose permanence is less than
minPermanence and deletes any segments that have less than
minNumSyns synapses remaining.

:param minPermanence: (float) Any syn whose permanence is 0 or <
       ``minPermanence``  will be deleted. If None is passed in, then
       ``self.connectedPerm`` is used.
:param minNumSyns: (int) Any segment with less than ``minNumSyns`` synapses
       remaining in it will be deleted. If None is passed in, then
       ``self.activationThreshold`` is used.
:returns: (tuple) ``numSegsRemoved``, ``numSynsRemoved``


<EOL>removeKeys = []<EOL>trimSegments = []<EOL>for key, updateList in self.segmentUpdates.items():<EOL><INDENT>c, i = key[<NUM_LIT:0>], key[<NUM_LIT:1>]<EOL>if c in activeColumns:<EOL><INDENT>action = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>if self.doPooling and self.lrnPredictedState['<STR_LIT:t>'][c, i] == <NUM_LIT:1>:<EOL><INDENT>action = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>action = '<STR_LIT>'<EOL><DEDENT><DEDENT>updateListKeep = []<EOL>if action != '<STR_LIT>':<EOL><INDENT>for (createDate, segUpdate) in updateList:<EOL><INDENT>if self.verbosity >= <NUM_LIT:4>:<EOL><INDENT>print("<STR_LIT>", self.lrnIterationIdx, end='<STR_LIT:U+0020>')<EOL>print(segUpdate)<EOL><DEDENT>if self.lrnIterationIdx - createDate > self.segUpdateValidDuration:<EOL><INDENT>continue<EOL><DEDENT>if action == '<STR_LIT>':<EOL><INDENT>trimSegment = self._adaptSegment(segUpdate)<EOL>if trimSegment:<EOL><INDENT>trimSegments.append((segUpdate.columnIdx, segUpdate.cellIdx,<EOL>segUpdate.segment))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>updateListKeep.append((createDate, segUpdate))<EOL><DEDENT><DEDENT><DEDENT>self.segmentUpdates[key] = updateListKeep<EOL>if len(updateListKeep) == <NUM_LIT:0>:<EOL><INDENT>removeKeys.append(key)<EOL><DEDENT><DEDENT>for key in removeKeys:<EOL><INDENT>self.segmentUpdates.pop(key)<EOL><DEDENT>for (c, i, segment) in trimSegments:<EOL><INDENT>self._trimSegmentsInCell(c, i, [segment], minPermanence = <NUM_LIT>,<EOL>minNumSyns = <NUM_LIT:0>)<EOL><DEDENT>

Go through the list of accumulated segment updates and process them
as follows:

if the segment update is too old, remove the update
else if the cell received bottom-up, update its permanences
else if it's still being predicted, leave it in the queue
else remove it.

:param activeColumns TODO: document


def _checkPrediction(self, patternNZs, output=None, colConfidence=None,<EOL>details=False):

<EOL>numPatterns = len(patternNZs)<EOL>orAll = set()<EOL>orAll = orAll.union(*patternNZs)<EOL>if output is None:<EOL><INDENT>assert self.currentOutput is not None<EOL>output = self.currentOutput<EOL><DEDENT>output = set(output.sum(axis=<NUM_LIT:1>).nonzero()[<NUM_LIT:0>])<EOL>totalExtras = len(output.difference(orAll))<EOL>totalMissing = len(orAll.difference(output))<EOL>if colConfidence is None:<EOL><INDENT>colConfidence = self.colConfidence['<STR_LIT:t>']<EOL><DEDENT>confidences = []<EOL>for i in range(numPatterns):<EOL><INDENT>positivePredictionSum = colConfidence[patternNZs[i]].sum()<EOL>positiveColumnCount   = len(patternNZs[i])<EOL>totalPredictionSum    = colConfidence.sum()<EOL>totalColumnCount      = len(colConfidence)<EOL>negativePredictionSum = totalPredictionSum - positivePredictionSum<EOL>negativeColumnCount   = totalColumnCount   - positiveColumnCount<EOL>if positiveColumnCount != <NUM_LIT:0>:<EOL><INDENT>positivePredictionScore = positivePredictionSum<EOL><DEDENT>else:<EOL><INDENT>positivePredictionScore = <NUM_LIT:0.0><EOL><DEDENT>if negativeColumnCount != <NUM_LIT:0>:<EOL><INDENT>negativePredictionScore = negativePredictionSum<EOL><DEDENT>else:<EOL><INDENT>negativePredictionScore = <NUM_LIT:0.0><EOL><DEDENT>currentSum = negativePredictionScore + positivePredictionScore<EOL>if currentSum > <NUM_LIT:0>:<EOL><INDENT>positivePredictionScore *= <NUM_LIT:1.0>/currentSum<EOL>negativePredictionScore *= <NUM_LIT:1.0>/currentSum<EOL><DEDENT>predictionScore = positivePredictionScore - negativePredictionScore<EOL>confidences.append((predictionScore,<EOL>positivePredictionScore,<EOL>negativePredictionScore))<EOL><DEDENT>if details:<EOL><INDENT>missingPatternBits = [set(pattern).difference(output)<EOL>for pattern in patternNZs]<EOL>return (totalExtras, totalMissing, confidences, missingPatternBits)<EOL><DEDENT>else:<EOL><INDENT>return (totalExtras, totalMissing, confidences)<EOL><DEDENT>

This function produces goodness-of-match scores for a set of input patterns,
by checking for their presence in the current and predicted output of the
TM. Returns a global count of the number of extra and missing bits, the
confidence scores for each input pattern, and (if requested) the
bits in each input pattern that were not present in the TM's prediction.

:param patternNZs a list of input patterns that we want to check for. Each
                  element is a list of the non-zeros in that pattern.
:param output     The output of the TM. If not specified, then use the
                  TM's current output. This can be specified if you are
                  trying to check the prediction metric for an output from
                  the past.
:param colConfidence The column confidences. If not specified, then use the
                     TM's current self.colConfidence. This can be specified if you
                     are trying to check the prediction metrics for an output
                     from the past.
:param details    if True, also include details of missing bits per pattern.

:returns:  list containing:

          [
            totalExtras,
            totalMissing,
            [conf_1, conf_2, ...],
            [missing1, missing2, ...]
          ]

@retval totalExtras a global count of the number of 'extras', i.e. bits that
                    are on in the current output but not in the or of all the
                    passed in patterns
@retval totalMissing a global count of all the missing bits, i.e. the bits
                     that are on in the or of the patterns, but not in the
                     current output
@retval conf_i the confidence score for the i'th pattern inpatternsToCheck
               This consists of 3 items as a tuple:
               (predictionScore, posPredictionScore, negPredictionScore)
@retval missing_i the bits in the i'th pattern that were missing
                  in the output. This list is only returned if details is
                  True.


return ["<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>]<EOL>

Any newly added dynamic states in the TM should be added to this list.

Parameters:
--------------------------------------------
retval:       The list of names of TM dynamic state variables.


def _getBestMatchingSegment(self, c, i, activeState):

maxActivity, which = self.minThreshold, -<NUM_LIT:1><EOL>for j, s in enumerate(self.cells[c][i]):<EOL><INDENT>activity = self._getSegmentActivityLevel(s, activeState,<EOL>connectedSynapsesOnly=False)<EOL>if activity >= maxActivity:<EOL><INDENT>maxActivity, which = activity, j<EOL><DEDENT><DEDENT>if which == -<NUM_LIT:1>:<EOL><INDENT>return None<EOL><DEDENT>else:<EOL><INDENT>return self.cells[c][i][which]<EOL><DEDENT>

For the given cell, find the segment with the largest number of active
synapses. This routine is aggressive in finding the best match. The
permanence value of synapses is allowed to be below connectedPerm. The number
of active synapses is allowed to be below activationThreshold, but must be
above minThreshold. The routine returns the segment index. If no segments are
found, then an index of -1 is returned.

:param c TODO: document
:param i TODO: document
:param activeState TODO: document


tpDynamicState = dict()<EOL>for variableName in self._getTPDynamicStateVariableNames():<EOL><INDENT>tpDynamicState[variableName] = copy.deepcopy(self.__dict__[variableName])<EOL><DEDENT>return tpDynamicState<EOL>

Parameters:
--------------------------------------------
retval:       A dict with all the dynamic state variable names as keys and
              their values at this instant as values.


if predictedOnly:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>print("<STR_LIT>", self.activationThreshold, end='<STR_LIT:U+0020>')<EOL>print("<STR_LIT>", self.minThreshold, end='<STR_LIT:U+0020>')<EOL>print("<STR_LIT>", self.connectedPerm)<EOL>for c in range(self.numberOfCols):<EOL><INDENT>for i in range(self.cellsPerColumn):<EOL><INDENT>if not predictedOnly or self.infPredictedState['<STR_LIT:t>'][c, i]:<EOL><INDENT>self.printCell(c, i, predictedOnly)<EOL><DEDENT><DEDENT><DEDENT>

TODO: document

:param predictedOnly:
:return:


state = self.__dict__.copy()<EOL>for ephemeralMemberName in self._getEphemeralMembers():<EOL><INDENT>state.pop(ephemeralMemberName, None)<EOL><DEDENT>state['<STR_LIT>'] = self._getRandomState()<EOL>state['<STR_LIT:version>'] = TM_VERSION<EOL>return state<EOL>

@internal
        Return serializable state.  This function will return a version of the
        __dict__ with all "ephemeral" members stripped out.  "Ephemeral" members
        are defined as those that do not need to be (nor should be) stored
        in any kind of persistent file (e.g., NuPIC network XML file.)


for variableName in self._getTPDynamicStateVariableNames():<EOL><INDENT>self.__dict__[variableName] = tpDynamicState.pop(variableName)<EOL><DEDENT>

Set all the dynamic state variables from the <tpDynamicState> dict.

<tpDynamicState> dict has all the dynamic state variable names as keys and
their values at this instant as values.

We set the dynamic state variables in the tm object with these items.


def _getBestMatchingCell(self, c, activeState, minThreshold):

<EOL>bestActivityInCol = minThreshold<EOL>bestSegIdxInCol = -<NUM_LIT:1><EOL>bestCellInCol = -<NUM_LIT:1><EOL>for i in range(self.cellsPerColumn):<EOL><INDENT>maxSegActivity = <NUM_LIT:0><EOL>maxSegIdx = <NUM_LIT:0><EOL>for j, s in enumerate(self.cells[c][i]):<EOL><INDENT>activity = self._getSegmentActivityLevel(s, activeState)<EOL>if activity > maxSegActivity:<EOL><INDENT>maxSegActivity = activity<EOL>maxSegIdx = j<EOL><DEDENT><DEDENT>if maxSegActivity >= bestActivityInCol:<EOL><INDENT>bestActivityInCol = maxSegActivity<EOL>bestSegIdxInCol = maxSegIdx<EOL>bestCellInCol = i<EOL><DEDENT><DEDENT>if bestCellInCol == -<NUM_LIT:1>:<EOL><INDENT>return (None, None, None)<EOL><DEDENT>else:<EOL><INDENT>return (bestCellInCol, self.cells[c][bestCellInCol][bestSegIdxInCol],<EOL>bestActivityInCol)<EOL><DEDENT>

Find weakly activated cell in column with at least minThreshold active
synapses.

:param c            which column to look at
:param activeState  the active cells
:param minThreshold minimum number of synapses required

:returns: tuple (cellIdx, segment, numActiveSynapses)


return pickle.dumps(self._random)<EOL>

@internal
        Return the random number state.

        This is used during unit testing to generate repeatable results.


def _updateStatsInferEnd(self, stats, bottomUpNZ, predictedState,<EOL>colConfidence):

<EOL>if not self.collectStats:<EOL><INDENT>return<EOL><DEDENT>stats['<STR_LIT>'] += <NUM_LIT:1><EOL>(numExtra2, numMissing2, confidences2) = self._checkPrediction(<EOL>patternNZs=[bottomUpNZ], output=predictedState,<EOL>colConfidence=colConfidence)<EOL>predictionScore, positivePredictionScore, negativePredictionScore = (<EOL>confidences2[<NUM_LIT:0>])<EOL>stats['<STR_LIT>'] = float(predictionScore)<EOL>stats['<STR_LIT>'] = <NUM_LIT:1.0> - float(positivePredictionScore)<EOL>stats['<STR_LIT>'] = float(negativePredictionScore)<EOL>stats['<STR_LIT>'] = numMissing2<EOL>stats['<STR_LIT>'] = numExtra2<EOL>if stats['<STR_LIT>'] <= self.burnIn:<EOL><INDENT>return<EOL><DEDENT>stats['<STR_LIT>'] += <NUM_LIT:1><EOL>numExpected = max(<NUM_LIT:1.0>, float(len(bottomUpNZ)))<EOL>stats['<STR_LIT>'] += numMissing2<EOL>stats['<STR_LIT>'] += numExtra2<EOL>stats['<STR_LIT>'] += <NUM_LIT> * numExtra2 / numExpected<EOL>stats['<STR_LIT>'] += <NUM_LIT> * numMissing2 / numExpected<EOL>stats['<STR_LIT>'] += float(predictionScore)<EOL>stats['<STR_LIT>'] += <NUM_LIT:1.0> - float(positivePredictionScore)<EOL>stats['<STR_LIT>'] += float(negativePredictionScore)<EOL>if self.collectSequenceStats:<EOL><INDENT>cc = self.cellConfidence['<STR_LIT>'] * self.infActiveState['<STR_LIT:t>']<EOL>sconf = cc.sum(axis=<NUM_LIT:1>)<EOL>for c in range(self.numberOfCols):<EOL><INDENT>if sconf[c] > <NUM_LIT:0>:<EOL><INDENT>cc[c, :] /= sconf[c]<EOL><DEDENT><DEDENT>self._internalStats['<STR_LIT>'] += cc<EOL><DEDENT>

Called at the end of learning and inference, this routine will update
a number of stats in our _internalStats dictionary, including our computed
prediction score.

:param stats            internal stats dictionary
:param bottomUpNZ       list of the active bottom-up inputs
:param predictedState   The columns we predicted on the last time step (should
                        match the current bottomUpNZ in the best case)
:param colConfidence    Column confidences we determined on the last time step


def printStates(self, printPrevious = True, printLearnState = True):

def formatRow(var, i):<EOL><INDENT>s = '<STR_LIT>'<EOL>for c in range(self.numberOfCols):<EOL><INDENT>if c > <NUM_LIT:0> and c % <NUM_LIT:10> == <NUM_LIT:0>:<EOL><INDENT>s += '<STR_LIT:U+0020>'<EOL><DEDENT>s += str(var[c, i])<EOL><DEDENT>s += '<STR_LIT:U+0020>'<EOL>return s<EOL><DEDENT>print("<STR_LIT>")<EOL>for i in range(self.cellsPerColumn):<EOL><INDENT>if printPrevious:<EOL><INDENT>print(formatRow(self.infActiveState['<STR_LIT>'], i), end='<STR_LIT:U+0020>')<EOL><DEDENT>print(formatRow(self.infActiveState['<STR_LIT:t>'], i))<EOL><DEDENT>print("<STR_LIT>")<EOL>for i in range(self.cellsPerColumn):<EOL><INDENT>if printPrevious:<EOL><INDENT>print(formatRow(self.infPredictedState['<STR_LIT>'], i), end='<STR_LIT:U+0020>')<EOL><DEDENT>print(formatRow(self.infPredictedState['<STR_LIT:t>'], i))<EOL><DEDENT>if printLearnState:<EOL><INDENT>print("<STR_LIT>")<EOL>for i in range(self.cellsPerColumn):<EOL><INDENT>if printPrevious:<EOL><INDENT>print(formatRow(self.lrnActiveState['<STR_LIT>'], i), end='<STR_LIT:U+0020>')<EOL><DEDENT>print(formatRow(self.lrnActiveState['<STR_LIT:t>'], i))<EOL><DEDENT>print("<STR_LIT>")<EOL>for i in range(self.cellsPerColumn):<EOL><INDENT>if printPrevious:<EOL><INDENT>print(formatRow(self.lrnPredictedState['<STR_LIT>'], i), end='<STR_LIT:U+0020>')<EOL><DEDENT>print(formatRow(self.lrnPredictedState['<STR_LIT:t>'], i))<EOL><DEDENT><DEDENT>

TODO: document

:param printPrevious:
:param printLearnState:
:return:


def _learnPhase1(self, activeColumns, readOnly=False):

<EOL>self.lrnActiveState['<STR_LIT:t>'].fill(<NUM_LIT:0>)<EOL>numUnpredictedColumns = <NUM_LIT:0><EOL>for c in activeColumns:<EOL><INDENT>predictingCells = numpy.where(self.lrnPredictedState['<STR_LIT>'][c] == <NUM_LIT:1>)[<NUM_LIT:0>]<EOL>numPredictedCells = len(predictingCells)<EOL>assert numPredictedCells <= <NUM_LIT:1><EOL>if numPredictedCells == <NUM_LIT:1>:<EOL><INDENT>i = predictingCells[<NUM_LIT:0>]<EOL>self.lrnActiveState['<STR_LIT:t>'][c, i] = <NUM_LIT:1><EOL>continue<EOL><DEDENT>numUnpredictedColumns += <NUM_LIT:1><EOL>if readOnly:<EOL><INDENT>continue<EOL><DEDENT>i, s, numActive = self._getBestMatchingCell(<EOL>c, self.lrnActiveState['<STR_LIT>'], self.minThreshold)<EOL>if s is not None and s.isSequenceSegment():<EOL><INDENT>if self.verbosity >= <NUM_LIT:4>:<EOL><INDENT>print("<STR_LIT>", c)<EOL><DEDENT>self.lrnActiveState['<STR_LIT:t>'][c, i] = <NUM_LIT:1><EOL>segUpdate = self._getSegmentActiveSynapses(<EOL>c, i, s, self.lrnActiveState['<STR_LIT>'], newSynapses = True)<EOL>s.totalActivations += <NUM_LIT:1><EOL>trimSegment = self._adaptSegment(segUpdate)<EOL>if trimSegment:<EOL><INDENT>self._trimSegmentsInCell(c, i, [s], minPermanence = <NUM_LIT>,<EOL>minNumSyns = <NUM_LIT:0>)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>i = self._getCellForNewSegment(c)<EOL>if (self.verbosity >= <NUM_LIT:4>):<EOL><INDENT>print("<STR_LIT>", c, end='<STR_LIT:U+0020>')<EOL>print("<STR_LIT>", i)<EOL><DEDENT>self.lrnActiveState['<STR_LIT:t>'][c, i] = <NUM_LIT:1><EOL>segUpdate = self._getSegmentActiveSynapses(<EOL>c, i, None, self.lrnActiveState['<STR_LIT>'], newSynapses=True)<EOL>segUpdate.sequenceSegment = True <EOL>self._adaptSegment(segUpdate)  <EOL><DEDENT><DEDENT>numBottomUpColumns = len(activeColumns)<EOL>if numUnpredictedColumns < numBottomUpColumns / <NUM_LIT:2>:<EOL><INDENT>return True   <EOL><DEDENT>else:<EOL><INDENT>return False<EOL><DEDENT>

Compute the learning active state given the predicted state and
the bottom-up input.

:param activeColumns list of active bottom-ups
:param readOnly      True if being called from backtracking logic.
                     This tells us not to increment any segment
                     duty cycles or queue up any updates.
:returns: True if the current input was sufficiently predicted, OR
         if we started over on startCells. False indicates that the current
         input was NOT predicted, well enough to consider it as "inSequence"

This looks at:
    - @ref lrnActiveState['t-1']
    - @ref lrnPredictedState['t-1']

This modifies:
    - @ref lrnActiveState['t']
    - @ref lrnActiveState['t-1']


def printConfidence(self, aState, maxCols = <NUM_LIT:20>):

def formatFPRow(var, i):<EOL><INDENT>s = '<STR_LIT>'<EOL>for c in range(min(maxCols, self.numberOfCols)):<EOL><INDENT>if c > <NUM_LIT:0> and c % <NUM_LIT:10> == <NUM_LIT:0>:<EOL><INDENT>s += '<STR_LIT:U+0020>'<EOL><DEDENT>s += '<STR_LIT>' % var[c, i]<EOL><DEDENT>s += '<STR_LIT:U+0020>'<EOL>return s<EOL><DEDENT>for i in range(self.cellsPerColumn):<EOL><INDENT>print(formatFPRow(aState, i))<EOL><DEDENT>

Print a floating point array that is the same shape as activeState.

:param aState: TODO: document
:param maxCols: TODO: document


def dutyCycle(self, active=False, readOnly=False):

<EOL>if self.tm.lrnIterationIdx <= self.dutyCycleTiers[<NUM_LIT:1>]:<EOL><INDENT>dutyCycle = float(self.positiveActivations)/ self.tm.lrnIterationIdx<EOL>if not readOnly:<EOL><INDENT>self._lastPosDutyCycleIteration = self.tm.lrnIterationIdx<EOL>self._lastPosDutyCycle = dutyCycle<EOL><DEDENT>return dutyCycle<EOL><DEDENT>age = self.tm.lrnIterationIdx - self._lastPosDutyCycleIteration<EOL>if age == <NUM_LIT:0> and not active:<EOL><INDENT>return self._lastPosDutyCycle<EOL><DEDENT>for tierIdx in range(len(self.dutyCycleTiers)-<NUM_LIT:1>, <NUM_LIT:0>, -<NUM_LIT:1>):<EOL><INDENT>if self.tm.lrnIterationIdx > self.dutyCycleTiers[tierIdx]:<EOL><INDENT>alpha = self.dutyCycleAlphas[tierIdx]<EOL>break<EOL><DEDENT><DEDENT>dutyCycle = pow(<NUM_LIT:1.0>-alpha, age) * self._lastPosDutyCycle<EOL>if active:<EOL><INDENT>dutyCycle += alpha<EOL><DEDENT>if not readOnly:<EOL><INDENT>self._lastPosDutyCycleIteration = self.tm.lrnIterationIdx<EOL>self._lastPosDutyCycle = dutyCycle<EOL><DEDENT>return dutyCycle<EOL>

Compute/update and return the positive activations duty cycle of
        this segment. This is a measure of how often this segment is
        providing good predictions.

        :param active   True if segment just provided a good prediction

        :param readOnly If True, compute the updated duty cycle, but don't change
                   the cached value. This is used by debugging print statements.

        :returns: The duty cycle, a measure of how often this segment is
        providing good predictions.

        **NOTE:** This method relies on different schemes to compute the duty cycle
        based on how much history we have. In order to support this tiered
        approach **IT MUST BE CALLED ON EVERY SEGMENT AT EACH DUTY CYCLE TIER**
        (@ref dutyCycleTiers).

        When we don't have a lot of history yet (first tier), we simply return
        number of positive activations / total number of iterations

        After a certain number of iterations have accumulated, it converts into
        a moving average calculation, which is updated only when requested
        since it can be a bit expensive to compute on every iteration (it uses
        the pow() function).

        The duty cycle is computed as follows:

            dc[t] = (1-alpha) * dc[t-1] + alpha * value[t]

        If the value[t] has been 0 for a number of steps in a row, you can apply
        all of the updates at once using:

            dc[t] = (1-alpha)^(t-lastT) * dc[lastT]

        We use the alphas and tiers as defined in @ref dutyCycleAlphas and
        @ref dutyCycleTiers.


assert proto.version == TM_VERSION<EOL>obj = object.__new__(cls)<EOL>obj._random = Random()<EOL>obj._random.read(proto.random)<EOL>obj.numberOfCols = int(proto.numberOfCols)<EOL>obj.cellsPerColumn = int(proto.cellsPerColumn)<EOL>obj._numberOfCells = obj.numberOfCols * obj.cellsPerColumn<EOL>obj.initialPerm = numpy.float32(proto.initialPerm)<EOL>obj.connectedPerm = numpy.float32(proto.connectedPerm)<EOL>obj.minThreshold = int(proto.minThreshold)<EOL>obj.newSynapseCount = int(proto.newSynapseCount)<EOL>obj.permanenceInc = numpy.float32(proto.permanenceInc)<EOL>obj.permanenceDec = numpy.float32(proto.permanenceDec)<EOL>obj.permanenceMax = numpy.float32(proto.permanenceMax)<EOL>obj.globalDecay = numpy.float32(proto.globalDecay)<EOL>obj.activationThreshold = int(proto.activationThreshold)<EOL>obj.doPooling = proto.doPooling<EOL>obj.segUpdateValidDuration = int(proto.segUpdateValidDuration)<EOL>obj.burnIn = int(proto.burnIn)<EOL>obj.collectStats = proto.collectStats<EOL>obj.verbosity = int(proto.verbosity)<EOL>obj.pamLength = int(proto.pamLength)<EOL>obj.maxAge = int(proto.maxAge)<EOL>obj.maxInfBacktrack = int(proto.maxInfBacktrack)<EOL>obj.maxLrnBacktrack = int(proto.maxLrnBacktrack)<EOL>obj.maxSeqLength = int(proto.maxSeqLength)<EOL>obj.maxSegmentsPerCell = proto.maxSegmentsPerCell<EOL>obj.maxSynapsesPerSegment = proto.maxSynapsesPerSegment<EOL>obj.outputType = proto.outputType<EOL>obj.activeColumns = [int(col) for col in proto.activeColumns]<EOL>obj.cells = [[] for _ in range(len(proto.cells))]<EOL>for columnSegments, columnSegmentsProto in zip(obj.cells, proto.cells):<EOL><INDENT>columnSegments.extend([[] for _ in range(len(columnSegmentsProto))])<EOL>for cellSegments, cellSegmentsProto in zip(columnSegments,<EOL>columnSegmentsProto):<EOL><INDENT>for segmentProto in cellSegmentsProto:<EOL><INDENT>segment = Segment.read(segmentProto, obj)<EOL>cellSegments.append(segment)<EOL><DEDENT><DEDENT><DEDENT>obj.lrnIterationIdx = int(proto.lrnIterationIdx)<EOL>obj.iterationIdx = int(proto.iterationIdx)<EOL>obj.segID = int(proto.segID)<EOL>obj.pamCounter = int(proto.pamCounter)<EOL>obj.collectSequenceStats = proto.collectSequenceStats<EOL>obj.resetCalled = proto.resetCalled<EOL>avgInputDensity = proto.avgInputDensity<EOL>if avgInputDensity < <NUM_LIT:0.0>:<EOL><INDENT>obj.avgInputDensity = None<EOL><DEDENT>else:<EOL><INDENT>obj.avgInputDensity = avgInputDensity<EOL><DEDENT>obj.learnedSeqLength = int(proto.learnedSeqLength)<EOL>obj.avgLearnedSeqLength = proto.avgLearnedSeqLength<EOL>obj._initEphemerals()<EOL>if proto.currentOutput.which() == "<STR_LIT:none>":<EOL><INDENT>obj.currentOutput = None<EOL><DEDENT>else:<EOL><INDENT>obj.currentOutput = numpy.array(proto.currentOutput.list,<EOL>dtype='<STR_LIT>')<EOL><DEDENT>for pattern in proto.prevLrnPatterns:<EOL><INDENT>obj.prevLrnPatterns.append([v for v in pattern])<EOL><DEDENT>for pattern in proto.prevInfPatterns:<EOL><INDENT>obj.prevInfPatterns.append([v for v in pattern])<EOL><DEDENT>for cellWrapperProto in proto.segmentUpdates:<EOL><INDENT>key = (cellWrapperProto.columnIdx, cellWrapperProto.cellIdx)<EOL>value = []<EOL>for updateWrapperProto in cellWrapperProto.segmentUpdates:<EOL><INDENT>segmentUpdate = SegmentUpdate.read(updateWrapperProto.segmentUpdate, obj)<EOL>value.append((int(updateWrapperProto.lrnIterationIdx), segmentUpdate))<EOL><DEDENT>obj.segmentUpdates[key] = value<EOL><DEDENT>numpy.copyto(obj.cellConfidence["<STR_LIT:t>"], proto.cellConfidenceT)<EOL>numpy.copyto(obj.cellConfidence["<STR_LIT>"], proto.cellConfidenceT1)<EOL>numpy.copyto(obj.cellConfidence["<STR_LIT>"],<EOL>proto.cellConfidenceCandidate)<EOL>numpy.copyto(obj.colConfidence["<STR_LIT:t>"], proto.colConfidenceT)<EOL>numpy.copyto(obj.colConfidence["<STR_LIT>"], proto.colConfidenceT1)<EOL>numpy.copyto(obj.colConfidence["<STR_LIT>"], proto.colConfidenceCandidate)<EOL>numpy.copyto(obj.lrnActiveState["<STR_LIT:t>"], proto.lrnActiveStateT)<EOL>numpy.copyto(obj.lrnActiveState["<STR_LIT>"], proto.lrnActiveStateT1)<EOL>numpy.copyto(obj.infActiveState["<STR_LIT:t>"], proto.infActiveStateT)<EOL>numpy.copyto(obj.infActiveState["<STR_LIT>"], proto.infActiveStateT1)<EOL>numpy.copyto(obj.infActiveState["<STR_LIT>"], proto.infActiveStateBackup)<EOL>numpy.copyto(obj.infActiveState["<STR_LIT>"],<EOL>proto.infActiveStateCandidate)<EOL>numpy.copyto(obj.lrnPredictedState["<STR_LIT:t>"], proto.lrnPredictedStateT)<EOL>numpy.copyto(obj.lrnPredictedState["<STR_LIT>"], proto.lrnPredictedStateT1)<EOL>numpy.copyto(obj.infPredictedState["<STR_LIT:t>"], proto.infPredictedStateT)<EOL>numpy.copyto(obj.infPredictedState["<STR_LIT>"], proto.infPredictedStateT1)<EOL>numpy.copyto(obj.infPredictedState["<STR_LIT>"],<EOL>proto.infPredictedStateBackup)<EOL>numpy.copyto(obj.infPredictedState["<STR_LIT>"],<EOL>proto.infPredictedStateCandidate)<EOL>obj.consolePrinterVerbosity = int(proto.consolePrinterVerbosity)<EOL>return obj<EOL>

Deserialize from proto instance.

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


def printColConfidence(self, aState, maxCols = <NUM_LIT:20>):

def formatFPRow(var):<EOL><INDENT>s = '<STR_LIT>'<EOL>for c in range(min(maxCols, self.numberOfCols)):<EOL><INDENT>if c > <NUM_LIT:0> and c % <NUM_LIT:10> == <NUM_LIT:0>:<EOL><INDENT>s += '<STR_LIT:U+0020>'<EOL><DEDENT>s += '<STR_LIT>' % var[c]<EOL><DEDENT>s += '<STR_LIT:U+0020>'<EOL>return s<EOL><DEDENT>print(formatFPRow(aState))<EOL>

Print up to maxCols number from a flat floating point array.

:param aState: TODO: document
:param maxCols: TODO: document


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.


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


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


return synapse<EOL>

Returns the data for a synapse.

.. note:: This method exists to match the interface of the C++ Connections.
   This allows tests and tools to inspect the connections using a common
   interface.

:param synapse: (:class:`Synapse`)
:returns: Synapse data


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])


return segment._synapses<EOL>

Returns the synapses on a segment.

:param segment: (int) Segment index
:returns: (set) Synapse objects representing synapses on the given segment.


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.segment.cell == other.segment.cell and<EOL>self.presynapticCell == other.presynapticCell and<EOL>abs(self.permanence - other.permanence) < EPSILON)<EOL>

Explicitly implement this for unit testing. Allow floating point
        differences for synapse permanence.


i = bisect_left(arr, val)<EOL>if i != len(arr) and arr[i] == val:<EOL><INDENT>return i<EOL><DEDENT>return -<NUM_LIT:1><EOL>

Function for running binary search on a sorted list.

:param arr: (list) a sorted list of integers to search
:param val: (int)  a integer to search for in the sorted array
:returns: (int) the index of the element if it is found and -1 otherwise.


return (self.cell == other.cell and<EOL>(sorted(self._synapses, key=lambda x: x._ordinal) ==<EOL>sorted(other._synapses, key=lambda x: x._ordinal)))<EOL>

Explicitly implement this for unit testing. The flatIdx is not designed
        to be consistent after serialize / deserialize, and the synapses might not
        enumerate in the same order.


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.


<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.


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


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


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

Return serializable state.

        This function will return a version of the __dict__.


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

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


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.


return self._partitionIdList<EOL>

:returns: a list of complete partition id objects


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:


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


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


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


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

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


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


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.


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 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:


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.


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.


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


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`


<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


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.


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


self.permanenceDecrement = permanenceDecrement<EOL>

Sets the permanence decrement.

:param permanenceDecrement: (float) The permanence decrement.


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.activeSegments<EOL>

Returns the active segments.

:returns: (list) Active segments


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


return self.connectedPermanence<EOL>

Get the connected permanence.

:returns: (float) The connected permanence.


return cell<EOL>

Returns the index of the cell.

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


return self.maxSynapsesPerSegment<EOL>

Get the maximum number of synapses per segment.

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


return self.activationThreshold<EOL>

Returns the activation threshold.

:returns: (int) The activation threshold.