def Func(arg_0, arg_1=None):
    # TODO: incorporate data from choice variables....
    # TODO: make sure we're calling this when appropriate.
    """Choose a new position based on results obtained so far from all other
    particles.

    Parameters:
    --------------------------------------------------------------
    whichVars:       If not None, only move these variables
    retval:               new position
    """
    # Get the global best position for this swarm generation
    arg_2 = None
    # If speculative particles are enabled, use the global best considering
    #  even particles in the current generation. This gives better results
    #  but does not provide repeatable results because it depends on
    #  worker timing
    if arg_0._hsObj._speculativeParticles:
      arg_3 = arg_0.genIdx
    else:
      arg_3 = arg_0.genIdx - 1

    if arg_3 >= 0:
      (arg_4, arg_5) = arg_0._resultsDB.bestModelIdAndErrScore(arg_0.swarmId,
                                                                arg_3)
      if arg_4 is not None:
        (arg_6, arg_5, arg_5, arg_5, arg_5) = arg_0._resultsDB.getParticleInfo(
          arg_4)
        arg_2 = Particle.getPositionFromState(arg_6)

    # Update each variable
    for (arg_7, arg_8) in arg_0.permuteVars.iteritems():
      if arg_1 is not None and arg_7 not in arg_1:
        continue
      if arg_2 is None:
        arg_8.Func(None, arg_0._rng)
      else:
        arg_8.Func(arg_2[arg_7], arg_0._rng)

    # get the new position
    arg_9 = arg_0.getPosition()

    # Log the new position
    if arg_0.logger.getEffectiveLevel() <= logging.DEBUG:
      arg_10 = StringIO.StringIO()
      print >> arg_10, "New particle position: \n%s" % (pprint.pformat(arg_9,
                                                                    indent=4))
      print >> arg_10, "Particle variables:"
      for (arg_7, arg_8) in arg_0.permuteVars.iteritems():
        print >> arg_10, "  %s: %s" % (arg_7, str(arg_8))
      arg_0.logger.debug(arg_10.getvalue())
      arg_10.close()

    return arg_9


def Func(arg_0):
    """ Get the logger for this object.

    :returns: (Logger) A Logger object.
    """
    if arg_0.__logger is None:
      arg_0.__logger = opf_utils.initLogger(arg_0)
    return arg_0.__logger


def Func(arg_0, arg_1=arg_2.ERROR):
    """ Create a new model instance, given a description dictionary.

    :param modelConfig: (dict)
           A dictionary describing the current model,
           `described here <../../quick-start/example-model-params.html>`_.

    :param logLevel: (int) The level of logging output that should be generated

    :raises Exception: Unsupported model type

    :returns: :class:`nupic.frameworks.opf.model.Model`
    """
    arg_4 = ModelFactory.__getLogger()
    arg_4.setLevel(arg_1)
    arg_4.debug("ModelFactory returning Model from dict: %s", arg_0)

    arg_5 = None
    if arg_0['model'] == "HTMPrediction":
      arg_5 = HTMPredictionModel
    elif arg_0['model'] == "TwoGram":
      arg_5 = TwoGramModel
    elif arg_0['model'] == "PreviousValue":
      arg_5 = PreviousValueModel
    else:
      raise Exception("ModelFactory received unsupported Model type: %s" % \
                      arg_0['model'])

    return arg_5(**arg_0['modelParams'])


def Func(arg_0, arg_1, arg_2=True):
    """
    Perform one time step of the Temporal Memory algorithm.

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

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

    :param learn: (bool) Whether or not learning is enabled.
    """
    arg_0.activateCells(sorted(arg_1), arg_2)
    arg_0.activateDendrites(arg_2)


def Func(arg_0, arg_1, arg_2=True):
    """
    Calculate the active cells, using the current active columns and dendrite
    segments. Grow and reinforce synapses.

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

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

      **Pseudocode:**

      ::

        for each column
          if column is active and has active distal dendrite segments
            call activatePredictedColumn
          if column is active and doesn't have active distal dendrite segments
            call burstColumn
          if column is inactive and has matching distal dendrite segments
            call punishPredictedColumn
    """
    arg_3 = arg_0.activeCells
    arg_4 = arg_0.winnerCells
    arg_0.activeCells = []
    arg_0.winnerCells = []

    arg_7 = lambda segment: int(segment.cell / arg_0.cellsPerColumn)
    arg_8 = lambda x: x

    for arg_9 in groupby2(arg_1, arg_8,
                               arg_0.activeSegments, arg_7,
                               arg_0.matchingSegments, arg_7):
      (arg_10,
       arg_1,
       arg_11,
       arg_12) = arg_9
      if arg_1 is not None:
        if arg_11 is not None:
          arg_13 = arg_0.activatePredictedColumn(arg_10,
                                                    arg_11,
                                                    arg_12,
                                                    arg_3,
                                                    arg_4,
                                                    arg_2)

          arg_0.activeCells += arg_13
          arg_0.winnerCells += arg_13
        else:
          (arg_13,
           arg_14) = arg_0.burstColumn(arg_10,
                                          arg_12,
                                          arg_3,
                                          arg_4,
                                          arg_2)

          arg_0.activeCells += arg_13
          arg_0.winnerCells.append(arg_14)
      else:
        if arg_2:
          arg_0.punishPredictedColumn(arg_10,
                                     arg_11,
                                     arg_12,
                                     arg_3,
                                     arg_4)


def Func(arg_0, arg_1, arg_2,
                              arg_3, arg_4,
                              arg_5, arg_6):
    """
    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.
    """
    return arg_0._Func(
      arg_0.connections, arg_0._random,
      arg_2, arg_4, arg_5,
      arg_0.numActivePotentialSynapsesForSegment,
      arg_0.maxNewSynapseCount, arg_0.initialPermanence,
      arg_0.permanenceIncrement, arg_0.permanenceDecrement,
      arg_0.maxSynapsesPerSegment, arg_6)


def Func(arg_0, arg_1, arg_2,
                            arg_3, arg_4,
                            arg_5):
    """
    Punishes the Segments that incorrectly predicted a column to be active.

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

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

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

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

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

    """
    arg_0._Func(
      arg_0.connections, arg_3, arg_4,
      arg_0.predictedSegmentDecrement)


def Func(arg_0, arg_1, arg_2, arg_3,
                     arg_4, arg_5):
    """
    Create a segment on the connections, enforcing the maxSegmentsPerCell
    parameter.
    """
    # Enforce maxSegmentsPerCell.
    while arg_1.numSegments(arg_3) >= arg_5:
      arg_6 = min(
        arg_1.segmentsForCell(arg_3),
        key=lambda arg_7 : arg_2[arg_7.flatIdx])

      arg_1.destroySegment(arg_6)

    # Create the segment.
    arg_7 = arg_1.createSegment(arg_3)

    # Do TM-specific bookkeeping for the segment.
    if arg_7.flatIdx == len(arg_2):
      arg_2.append(arg_4)
    elif arg_7.flatIdx < len(arg_2):
      # A flatIdx was recycled.
      arg_2[arg_7.flatIdx] = arg_4
    else:
      raise AssertionError(
        "All segments should be created with the TM createSegment method.")

    return arg_7


def Func(arg_0, arg_1, arg_2, arg_3, arg_4,
                    arg_5, arg_6, arg_7):
    """
    Creates nDesiredNewSynapes synapses on the segment passed in if
    possible, choosing random cells from the previous winner cells that are
    not already on the segment.

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

    """
    arg_8 = list(arg_5)

    for arg_9 in arg_1.synapsesForSegment(arg_3):
      arg_10 = binSearch(arg_8, arg_9.presynapticCell)
      if arg_10 != -1:
        del arg_8[arg_10]

    arg_11 = min(arg_4, len(arg_8))

    # Check if we're going to surpass the maximum number of synapses.
    arg_12 = arg_1.numSynapses(arg_3) + arg_11 - arg_7
    if arg_12 > 0:
      arg_0._destroyMinPermanenceSynapses(arg_1, arg_2, arg_3, arg_12,
                                        arg_5)

    # Recalculate in case we weren't able to destroy as many synapses as needed.
    arg_11 = min(arg_11,
                  arg_7 - arg_1.numSynapses(arg_3))

    for arg_13 in range(arg_11):
      arg_10 = arg_2.getUInt32(len(arg_8))
      arg_1.createSynapse(arg_3, arg_8[arg_10], arg_6)
      del arg_8[arg_10]


def Func(arg_0, arg_1, arg_2, arg_3,
                    arg_4, arg_5):
    """
    Updates synapses on segment.
    Strengthens active synapses; weakens inactive synapses.

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

    # Destroying a synapse modifies the set that we're iterating through.
    arg_6 = []

    for arg_7 in arg_1.synapsesForSegment(arg_2):
      arg_8 = arg_7.permanence

      if binSearch(arg_3, arg_7.presynapticCell) != -1:
        arg_8 += arg_4
      else:
        arg_8 -= arg_5

      # Keep permanence within min/max bounds
      arg_8 = max(0.0, min(1.0, arg_8))

      if arg_8 < EPSILON:
        arg_6.append(arg_7)
      else:
        arg_1.updateSynapsePermanence(arg_7, arg_8)

    for arg_7 in arg_6:
      arg_1.destroySynapse(arg_7)

    if arg_1.numSynapses(arg_2) == 0:
      arg_1.destroySegment(arg_2)


def Func(arg_0, arg_1):
    """
    Returns the index of the column that a cell belongs to.

    :param cell: (int) Cell index

    :returns: (int) Column index
    """
    arg_0._validateCell(arg_1)

    return int(arg_1 / arg_0.cellsPerColumn)


def Func(arg_0, arg_1):
    """
    Reads deserialized data from proto object.

    :param proto: (DynamicStructBuilder) Proto object

    :returns: (:class:TemporalMemory) TemporalMemory instance
    """
    arg_2 = object.__new__(arg_0)

    # capnp fails to save a tuple, so proto.columnDimensions was forced to
    # serialize as a list.  We prefer a tuple, however, because columnDimensions
    # should be regarded as immutable.
    arg_2.columnDimensions = tuple(arg_1.columnDimensions)
    arg_2.cellsPerColumn = int(arg_1.cellsPerColumn)
    arg_2.activationThreshold = int(arg_1.activationThreshold)
    arg_2.initialPermanence = round(arg_1.initialPermanence, EPSILON_ROUND)
    arg_2.connectedPermanence = round(arg_1.connectedPermanence, EPSILON_ROUND)
    arg_2.minThreshold = int(arg_1.minThreshold)
    arg_2.maxNewSynapseCount = int(arg_1.maxNewSynapseCount)
    arg_2.permanenceIncrement = round(arg_1.permanenceIncrement, EPSILON_ROUND)
    arg_2.permanenceDecrement = round(arg_1.permanenceDecrement, EPSILON_ROUND)
    arg_2.predictedSegmentDecrement = round(arg_1.predictedSegmentDecrement,
                                         EPSILON_ROUND)

    arg_2.maxSegmentsPerCell = int(arg_1.maxSegmentsPerCell)
    arg_2.maxSynapsesPerSegment = int(arg_1.maxSynapsesPerSegment)

    arg_2.connections = Connections.Func(arg_1.connections)
    #pylint: disable=W0212
    arg_2._random = Random()
    arg_2._random.Func(arg_1.random)
    #pylint: enable=W0212

    arg_2.activeCells = [int(x) for x in arg_1.activeCells]
    arg_2.winnerCells = [int(x) for x in arg_1.winnerCells]

    arg_19 = arg_2.connections.segmentFlatListLength()
    arg_2.numActiveConnectedSynapsesForSegment = [0] * arg_19
    arg_2.numActivePotentialSynapsesForSegment = [0] * arg_19
    arg_2.lastUsedIterationForSegment = [0] * arg_19

    arg_2.activeSegments = []
    arg_2.matchingSegments = []

    for arg_25 in arg_1.activeSegments:
      arg_2.activeSegments.append(
        arg_2.connections.getSegment(arg_25.cell,
                                  arg_25.idxOnCell))

    for arg_25 in arg_1.matchingSegments:
      arg_2.matchingSegments.append(
        arg_2.connections.getSegment(arg_25.cell,
                                  arg_25.idxOnCell))

    for arg_25 in arg_1.numActivePotentialSynapsesForSegment:
      arg_26 = arg_2.connections.getSegment(arg_25.cell,
                                          arg_25.idxOnCell)

      arg_2.numActivePotentialSynapsesForSegment[arg_26.flatIdx] = (
        int(arg_25.number))

    arg_2.iteration = long(arg_1.iteration)

    for arg_25 in arg_1.lastUsedIterationForSegment:
      arg_26 = arg_2.connections.getSegment(arg_25.cell,
                                          arg_25.idxOnCell)

      arg_2.lastUsedIterationForSegment[arg_26.flatIdx] = (
        long(arg_25.number))

    return arg_2


def Func(arg_0, arg_1):
    """
    Generate a sequence from a list of numbers.

    Note: Any `None` in the list of numbers is considered a reset.

    @param numbers (list) List of numbers

    @return (list) Generated sequence
    """
    arg_2 = []

    for arg_3 in arg_1:
      if arg_3 == None:
        arg_2.append(arg_3)
      else:
        arg_4 = arg_0.patternMachine.get(arg_3)
        arg_2.append(arg_4)

    return arg_2


def Func(arg_0, arg_1, arg_2):
    """
    Add spatial noise to each pattern in the sequence.

    @param sequence (list)  Sequence
    @param amount   (float) Amount of spatial noise

    @return (list) Sequence with spatial noise
    """
    arg_3 = []

    for arg_4 in arg_1:
      if arg_4 is not None:
        arg_4 = arg_0.patternMachine.addNoise(arg_4, arg_2)
      arg_3.append(arg_4)

    return arg_3


def Func(arg_0, arg_1, arg_2=1):
    """
    Pretty print a sequence.

    @param sequence  (list) Sequence
    @param verbosity (int)  Verbosity level

    @return (string) Pretty-printed text
    """
    arg_3 = ""

    for arg_4 in xrange(len(arg_1)):
      arg_5 = arg_1[arg_4]

      if arg_5 == None:
        arg_3 += "<reset>"
        if arg_4 < len(arg_1) - 1:
          arg_3 += "\n"
      else:
        arg_3 += arg_0.patternMachine.prettyPrintPattern(arg_5,
                                                       arg_2=arg_2)

    return arg_3


def Func(arg_0, arg_1=None):
    """
    Returns pretty-printed table of traces.

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

    @return (string) Pretty-printed table of traces.
    """
    assert len(arg_0) > 0, "No traces found"
    arg_2 = PrettyTable(["#"] + [arg_4.prettyPrintTitle() for arg_4 in arg_0])

    for arg_3 in xrange(len(arg_0[0].data)):
      if arg_1 and arg_1.data[arg_3]:
        arg_2.add_row(["<reset>"] * (len(arg_0) + 1))
      arg_2.add_row([arg_3] +
        [arg_4.prettyPrintDatum(arg_4.data[arg_3]) for arg_4 in arg_0])

    return arg_2.get_string().encode("utf-8")


def Func(arg_0,
                             arg_1,
                             arg_2=0):
  """
  Compute updated probabilities for anomalyScores using the given params.

  :param anomalyScores: a list of records. Each record is a list with the
                        following three elements: [timestamp, value, score]

                        Example::

                            [datetime.datetime(2013, 8, 10, 23, 0), 6.0, 1.0]

  :param params: the JSON dict returned by estimateAnomalyLikelihoods
  :param verbosity: integer controlling extent of printouts for debugging
  :type verbosity: int

  :returns: 3-tuple consisting of:

            - likelihoods

              numpy array of likelihoods, one for each aggregated point

            - avgRecordList

              list of averaged input records

            - params

              an updated JSON object containing the state of this metric.

  """
  if arg_2 > 3:
    print("In Func.")
    print("Number of anomaly scores:", len(arg_0))
    print("First 20:", arg_0[0:min(20, len(arg_0))])
    print("Params:", arg_1)

  if len(arg_0) == 0:
    raise ValueError("Must have at least one anomalyScore")

  if not isValidEstimatorParams(arg_1):
    raise ValueError("'params' is not a valid params structure")

  # For backward compatibility.
  if "historicalLikelihoods" not in arg_1:
    arg_1["historicalLikelihoods"] = [1.0]

  # Compute moving averages of these new scores using the previous values
  # as well as likelihood for these scores using the old estimator
  arg_3  = arg_1["movingAverage"]["historicalValues"]
  arg_4             = arg_1["movingAverage"]["total"]
  arg_5        = arg_1["movingAverage"]["windowSize"]

  arg_6 = numpy.zeros(len(arg_0), dtype=float)
  arg_7 = numpy.zeros(len(arg_0), dtype=float)
  for arg_8, arg_9 in enumerate(arg_0):
    arg_10, arg_3, arg_4 = (
      MovingAverage.compute(arg_3, arg_4, arg_9[2], arg_5)
    )
    arg_6[arg_8] = arg_10
    arg_7[arg_8]   = tailProbability(arg_10, arg_1["distribution"])

  # Filter the likelihood values. First we prepend the historical likelihoods
  # to the current set. Then we filter the values.  We peel off the likelihoods
  # to return and the last windowSize values to store for later.
  arg_11 = arg_1["historicalLikelihoods"] + list(arg_7)
  arg_12 = _filterLikelihoods(arg_11)
  arg_7[:] = arg_12[-len(arg_7):]
  arg_13 = arg_11[-min(arg_5, len(arg_11)):]

  # Update the estimator
  arg_14 = {
    "distribution": arg_1["distribution"],
    "movingAverage": {
      "historicalValues": arg_3,
      "total": arg_4,
      "windowSize": arg_5,
    },
    "historicalLikelihoods": arg_13,
  }

  assert len(arg_14["historicalLikelihoods"]) <= arg_5

  if arg_2 > 3:
    print("Number of likelihoods:", len(arg_7))
    print("First 20 likelihoods:", arg_7[0:min(20, len(arg_7))])
    print("Leaving Func.")

  return (arg_7, arg_6, arg_14)


def Func(arg_0, arg_1, arg_2):
    """Return the value of skipRecords for passing to estimateAnomalyLikelihoods

    If `windowSize` is very large (bigger than the amount of data) then this
    could just return `learningPeriod`. But when some values have fallen out of
    the historical sliding window of anomaly records, then we have to take those
    into account as well so we return the `learningPeriod` minus the number
    shifted out.

    :param numIngested - (int) number of data points that have been added to the
      sliding window of historical data points.
    :param windowSize - (int) size of sliding window of historical data points.
    :param learningPeriod - (int) the number of iterations required for the
      algorithm to learn the basic patterns in the dataset and for the anomaly
      score to 'settle down'.
    """
    arg_3 = max(0, arg_0 - arg_1)
    return min(arg_0, max(0, arg_2 - arg_3))


def Func(arg_0, arg_1):
    """ capnp serialization method for the anomaly likelihood object

    :param proto: (Object) capnp proto object specified in
                          nupic.regions.anomaly_likelihood.capnp
    """

    arg_1.iteration = arg_0._iteration

    arg_3 = arg_1.init('historicalScores', len(arg_0._historicalScores))
    for arg_4, arg_5 in enumerate(list(arg_0._historicalScores)):
      arg_6, arg_7, arg_8 = arg_5
      arg_9 = arg_3[arg_4]
      arg_9.value = float(arg_7)
      arg_9.anomalyScore = float(arg_8)

    if arg_0._distribution:
      arg_1.distribution.name = arg_0._distribution["distribution"]["name"]
      arg_1.distribution.mean = float(arg_0._distribution["distribution"]["mean"])
      arg_1.distribution.variance = float(arg_0._distribution["distribution"]["variance"])
      arg_1.distribution.stdev = float(arg_0._distribution["distribution"]["stdev"])

      arg_1.distribution.movingAverage.windowSize = float(arg_0._distribution["movingAverage"]["windowSize"])

      arg_17 = arg_0._distribution["movingAverage"]["historicalValues"]
      arg_18 = arg_1.distribution.movingAverage.init(
        "historicalValues", len(arg_17))
      for arg_4, arg_7 in enumerate(arg_17):
        arg_18[arg_4] = float(arg_7)

      #proto.distribution.movingAverage.historicalValues = self._distribution["movingAverage"]["historicalValues"]
      arg_1.distribution.movingAverage.total = float(arg_0._distribution["movingAverage"]["total"])

      arg_20 = arg_0._distribution["historicalLikelihoods"]
      arg_21 = arg_1.distribution.init("historicalLikelihoods",
                                                 len(arg_20))
      for arg_4, arg_22 in enumerate(arg_20):
        arg_21[arg_4] = float(arg_22)

    arg_1.probationaryPeriod = arg_0._probationaryPeriod
    arg_1.learningPeriod = arg_0._learningPeriod
    arg_1.reestimationPeriod = arg_0._reestimationPeriod
    arg_1.historicWindowSize = arg_0._historicalScores.maxlen


def Func(arg_0, arg_1):
    """ Replaces the Iteration Cycle phases

    :param phaseSpecs: Iteration cycle description consisting of a sequence of
                  IterationPhaseSpecXXXXX elements that are performed in the
                  given order
    """

    # -----------------------------------------------------------------------
    # Replace our phase manager
    #
    arg_0.__phaseManager = _PhaseManager(
      model=arg_0.__model,
      arg_1=arg_1)

    return


def Func(arg_0, arg_1):
    """
    Processes the given record according to the current iteration cycle phase

    :param inputRecord: (object) record expected to be returned from
           :meth:`nupic.data.record_stream.RecordStreamIface.getNextRecord`.

    :returns: :class:`nupic.frameworks.opf.opf_utils.ModelResult`
    """
    assert arg_1, "Invalid inputRecord: %r" % arg_1

    arg_2 = arg_0.__phaseManager.Func(arg_1)
    arg_3 = arg_0.__metricsMgr.update(arg_2)

    # Execute task-postIter callbacks
    for arg_4 in arg_0.__userCallbacks['postIter']:
      arg_4(arg_0.__model)

    arg_2.metrics = arg_3

    # Return the input and predictions for this record
    return arg_2


def Func(arg_0):
    """ Advances the iteration;

    Returns:      True if more iterations remain; False if this is the final
                  iteration.
    """
    arg_1 = True
    try:
      arg_0.__iter.next()
    except StopIteration:
      arg_0.__iter = None
      arg_1 = False

    return arg_1


def Func(arg_0, arg_1):
    """ Serialize via capnp

    :param proto: capnp PreviousValueModelProto message builder
    """
    super(PreviousValueModel, arg_0).FuncBaseToProto(arg_1.modelBase)

    arg_1.fieldNames = arg_0._fieldNames
    arg_1.fieldTypes = arg_0._fieldTypes
    if arg_0._predictedField:
      arg_1.predictedField = arg_0._predictedField
    arg_1.predictionSteps = arg_0._predictionSteps


def Func(arg_0, arg_1=None):
  """
  Accepts log-values as input, exponentiates them, computes the sum,
  then converts the sum back to log-space and returns the result.
  Handles underflow by rescaling so that the largest values is exactly 1.0.
  """
  arg_0 = numpy.asarray(arg_0)
  arg_2 = arg_0.max()

  # If the input is the log of 0's, catch this condition before we generate
  #  an exception, and return the log(0)
  if numpy.isinf(arg_2):
    return arg_2

  # If the user specified an epsilon and we are below it, return epsilon
  if (arg_1 is not None) and (arg_2 < arg_1):
    return arg_1

  arg_3 = numpy.exp(arg_0 - arg_2)
  arg_4 = arg_3.sum()

  arg_5 = numpy.log(arg_4) + arg_2
  # try:
  #   conventional = numpy.log(numpy.exp(lx).sum())
  #   if not similar(result, conventional):
  #     if numpy.isinf(conventional).any() and not numpy.isinf(result).any():
  #       # print "Scaled log sum avoided underflow or overflow."
  #       pass
  #     else:
  #       import sys
  #       print >>sys.stderr, "Warning: scaled log sum did not match."
  #       print >>sys.stderr, "Scaled log result:"
  #       print >>sys.stderr, result
  #       print >>sys.stderr, "Conventional result:"
  #       print >>sys.stderr, conventional
  # except FloatingPointError, e:
  #   # print "Scaled log sum avoided underflow or overflow."
  #   pass

  return arg_5


def Func(arg_0):
  """
  Accepts log-values as input, exponentiates them,
  Funcs and returns the result.
  Handles underflow by rescaling so that the largest values is exactly 1.0.
  """
  arg_0 = numpy.asarray(arg_0)
  arg_1 = arg_0.max()
  arg_2 = numpy.exp(arg_0 - arg_1)
  arg_3 = arg_2 / arg_2.sum()

  arg_4 = (numpy.exp(arg_0) / numpy.exp(arg_0).sum())
  assert similar(arg_3, arg_4)

  return arg_3


def Func(arg_0, arg_1, *arg_2, **arg_3):
    """
    Log 'msg % args' with severity 'DEBUG'.

    To pass exception information, use the keyword argument exc_info with
    a true value, e.g.

    logger.Func("Houston, we have a %s", "thorny problem", exc_info=1)
    """
    arg_0._baseLogger.Func(arg_0, arg_0.getExtendedMsg(arg_1), *arg_2, **arg_3)


def Func(arg_0, arg_1, *arg_2, **arg_3):
    """
    Log 'msg % args' with severity 'INFO'.

    To pass exception Funcrmation, use the keyword argument exc_Func with
    a true value, e.g.

    logger.Func("Houston, we have a %s", "interesting problem", exc_Func=1)
    """
    arg_0._baseLogger.Func(arg_0, arg_0.getExtendedMsg(arg_1), *arg_2, **arg_3)


def Func(arg_0, arg_1, *arg_2, **arg_3):
    """
    Log 'msg % args' with severity 'ERROR'.

    To pass exception information, use the keyword argument exc_info with
    a true value, e.g.

    logger.Func("Houston, we have a %s", "major problem", exc_info=1)
    """
    arg_0._baseLogger.Func(arg_0, arg_0.getExtendedMsg(arg_1), *arg_2, **arg_3)


def Func(arg_0, arg_1, *arg_2, **arg_3):
    """
    Log 'msg % args' with severity 'CRITICAL'.

    To pass exception information, use the keyword argument exc_info with
    a true value, e.g.

    logger.Func("Houston, we have a %s", "major disaster", exc_info=1)
    """
    arg_0._baseLogger.Func(arg_0, arg_0.getExtendedMsg(arg_1), *arg_2, **arg_3)


def Func(arg_0, arg_1, arg_2, *arg_3, **arg_4):
      """
      Log 'msg % args' with the integer severity 'level'.

      To pass exception information, use the keyword argument exc_info with
      a true value, e.g.

      Funcger.Func(level, "We have a %s", "mysterious problem", exc_info=1)
      """
      arg_0._baseLogger.Func(arg_0, arg_1, arg_0.getExtendedMsg(arg_2), *arg_3,
                           **arg_4)


def Func(arg_0):
  """ Returns sum of the elements in the list. Missing items are replaced with
  the mean value
  """
  arg_1 = _aggr_mean(arg_0)
  if arg_1 == None:
    return None

  arg_2 = 0
  for arg_3 in arg_0:
    if arg_3 != SENTINEL_VALUE_FOR_MISSING_DATA:
      arg_2 += arg_3
    else:
      arg_2 += arg_1

  return arg_2


def Func(arg_0):
  """ Returns mean of non-None elements of the list
  """
  arg_1 = 0
  arg_2 = 0
  for arg_3 in arg_0:
    if arg_3 != SENTINEL_VALUE_FOR_MISSING_DATA:
      arg_1 += arg_3
      arg_2 += 1
  if arg_2 != 0:
    return arg_1 / arg_2
  else:
    return None


def Func(arg_0):
  """ Returns most common value seen in the non-None elements of the list
  """

  arg_1 = dict()
  arg_2 = 0

  for arg_3 in arg_0:
    if arg_3 == SENTINEL_VALUE_FOR_MISSING_DATA:
      continue

    arg_2 += 1
    if arg_3 in arg_1:
      arg_1[arg_3] += 1
    else:
      arg_1[arg_3] = 1

  # Get the most common one
  if arg_2 == 0:
    return None

  # Sort by counts
  arg_4 = arg_1.items()
  arg_4.sort(cmp=lambda x,y: x[1] - y[1], reverse=True)
  return arg_4[0][0]


def Func(arg_0, arg_1, arg_2=None):
  """Generate a dataset of aggregated values

  Parameters:
  ----------------------------------------------------------------------------
  aggregationInfo: a dictionary that contains the following entries
    - fields: a list of pairs. Each pair is a field name and an
      aggregation function (e.g. sum). The function will be used to aggregate
      multiple values during the aggregation period.

  aggregation period: 0 or more of unit=value fields; allowed units are:
        [years months] |
        [weeks days hours minutes seconds milliseconds microseconds]
        NOTE: years and months are mutually-exclusive with the other units.
              See getEndTime() and _aggregate() for more details.
        Example1: years=1, months=6,
        Example2: hours=1, minutes=30,
        If none of the period fields are specified or if all that are specified
        have values of 0, then aggregation will be suppressed, and the given
        inputFile parameter value will be returned.

  inputFilename: filename of the input dataset within examples/prediction/data

  outputFilename: name for the output file. If not given, a name will be
        generated based on the input filename and the aggregation params

  retval: Name of the generated output file. This will be the same as the input
      file name if no aggregation needed to be performed

  If the input file contained a time field, sequence id field or reset field
  that were not specified in aggregationInfo fields, those fields will be
  added automatically with the following rules:

  1. The order will be R, S, T, rest of the fields
  2. The aggregation function for all will be to pick the first: lambda x: x[0]

    Returns: the path of the aggregated data file if aggregation was performed
      (in the same directory as the given input file); if aggregation did not
      need to be performed, then the given inputFile argument value is returned.
  """

  # Create the input stream
  arg_3 = resource_filename("nupic.datafiles", arg_1)
  arg_4 = FileRecordStream(arg_3)

  # Instantiate the aggregator
  arg_5 = Aggregator(arg_0=arg_0,
                          inputFields=arg_4.getFields())

  # Is it a null aggregation? If so, just return the input file unmodified
  if arg_5.isNullAggregation():
    return arg_3

  # ------------------------------------------------------------------------
  # If we were not given an output filename, create one based on the
  #  aggregation settings
  if arg_2 is None:
    arg_2 = 'agg_%s' % \
                        os.path.splitext(os.path.basename(arg_3))[0]
    arg_6 = 'years months weeks days '\
                  'hours minutes seconds milliseconds microseconds'
    for arg_7 in arg_6.split():
      if arg_0.get(arg_7, 0) > 0:
        arg_2 += '_%s_%d' % (arg_7, arg_0[arg_7])

    arg_2 += '.csv'
    arg_2 = os.path.join(os.path.dirname(arg_3), arg_2)

  # ------------------------------------------------------------------------
  # If some other process already started creating this file, simply
  #   wait for it to finish and return without doing anything
  arg_8 = arg_2 + '.please_wait'
  if os.path.isfile(arg_2) or \
     os.path.isfile(arg_8):
    while os.path.isfile(arg_8):
      print 'Waiting for %s to be fully written by another process' % \
            arg_8
      time.sleep(1)
    return arg_2

  # Create the lock file
  arg_9 = open(arg_8, 'w')

  # -------------------------------------------------------------------------
  # Create the output stream
  arg_10 = FileRecordStream(streamID=arg_2, write=True,
                               fields=arg_4.getFields())

  # -------------------------------------------------------------------------
  # Write all aggregated records to the output
  while True:
    arg_11 = arg_4.getNextRecord()

    (arg_12, arg_13) = arg_5.next(arg_11, None)

    if arg_12 is None and arg_11 is None:
      break

    if arg_12 is not None:
      arg_10.appendRecord(arg_12)

  return arg_2


def Func(arg_0, arg_1):
  """Generate the filename for aggregated dataset

  The filename is based on the input filename and the
  aggregation period.

  Returns the inputFile if no aggregation required (aggregation
  info has all 0's)
  """

  # Find the actual file, with an absolute path
  arg_1 = resource_filename("nupic.datafiles", arg_1)

  arg_2 = defaultdict(lambda: 0, arg_0)
  arg_3 = os.path.dirname(arg_1)
  arg_4 = 'agg_%s' % os.path.splitext(os.path.basename(arg_1))[0]
  arg_5 = True
  arg_6 = 'years months weeks days '\
                'hours minutes seconds milliseconds microseconds'
  for arg_7 in arg_6.split():
    if arg_2[arg_7] > 0:
      arg_5 = False
      arg_4 += '_%s_%d' % (arg_7, arg_2[arg_7])

  if arg_5:
    return arg_1
  arg_4 += '.csv'
  arg_4 = os.path.join(arg_3, arg_4)

  return arg_4


def Func(arg_0, arg_1):
    """Add the aggregation period to the input time t and return a datetime object

    Years and months are handled as aspecial case due to leap years
    and months with different number of dates. They can't be converted
    to a strict timedelta because a period of 3 months will have different
    durations actually. The solution is to just add the years and months
    fields directly to the current time.

    Other periods are converted to timedelta and just added to current time.
    """

    assert isinstance(arg_1, datetime.datetime)
    if arg_0._aggTimeDelta:
      return arg_1 + arg_0._aggTimeDelta
    else:
      arg_2 = arg_1.year + arg_0._aggYears + (arg_1.month - 1 + arg_0._aggMonths) / 12
      arg_3 = (arg_1.month - 1 + arg_0._aggMonths) % 12 + 1
      return arg_1.replace(arg_2=arg_2, arg_3=arg_3)


def Func(arg_0, arg_1):
    """ Given the name of an aggregation function, returns the function pointer
    and param.

    Parameters:
    ------------------------------------------------------------------------
    funcName:  a string (name of function) or funcPtr
    retval:   (funcPtr, param)
    """

    arg_2 = None
    if isinstance(arg_1, basestring):
      if arg_1 == 'sum':
        arg_3 = _aggr_sum
      elif arg_1 == 'first':
        arg_3 = _aggr_first
      elif arg_1 == 'last':
        arg_3 = _aggr_last
      elif arg_1 == 'mean':
        arg_3 = _aggr_mean
      elif arg_1 == 'max':
        arg_3 = max
      elif arg_1 == 'min':
        arg_3 = min
      elif arg_1 == 'mode':
        arg_3 = _aggr_mode
      elif arg_1.startswith('wmean:'):
        arg_3 = _aggr_weighted_mean
        arg_4 = arg_1[6:]
        arg_2 = [f[0] for f in arg_0._inputFields].index(arg_4)
    else:
      arg_3 = arg_1

    return (arg_3, arg_2)


def Func(arg_0):
    """ Generate the aggregated output record

    Parameters:
    ------------------------------------------------------------------------
    retval: outputRecord

    """

    arg_1 = []

    for arg_2, (arg_3, arg_4, arg_5) in enumerate(arg_0._fields):
      if arg_4 is None: # this field is not supposed to be aggregated.
        continue

      arg_6 = arg_0._slice[arg_2]
      arg_7 = None
      if arg_5 is not None:
        arg_1.append(arg_4(arg_6, arg_0._slice[arg_5]))
      else:
        arg_1.append(arg_4(arg_6))

    return arg_1


def Func(arg_0, arg_1):
    """
    Run one iteration of this model.

    :param inputRecord: (object)
           A record object formatted according to
           :meth:`~nupic.data.record_stream.RecordStreamIface.getNextRecord` or
           :meth:`~nupic.data.record_stream.RecordStreamIface.getNextRecordDict`
           result format.
    :returns: (:class:`~nupic.frameworks.opf.opf_utils.ModelResult`)
             An ModelResult namedtuple. The contents of ModelResult.inferences
             depends on the the specific inference type of this model, which
             can be queried by :meth:`.getInferenceType`.
    """
    # 0-based prediction index for ModelResult
    arg_2 = arg_0._numPredictions
    arg_0._numPredictions += 1
    arg_3 = opf_utils.ModelResult(arg_2=arg_2,
                                   rawInput=arg_1)
    return arg_3


def Func(arg_0):
    """ Return the absolute path of the model's checkpoint file.

    :param checkpointDir: (string)
           Directory of where the experiment is to be or was saved
    :returns: (string) An absolute path.
    """
    arg_1 = os.path.join(arg_0, "model.data")
    arg_1 = os.path.abspath(arg_1)
    return arg_1


def Func(arg_0, arg_1):
    """Serializes model using capnproto and writes data to ``checkpointDir``"""
    arg_2 = arg_0.getSchema().new_message()

    arg_0.write(arg_2)

    arg_3 = arg_0._getModelCheckpointFilePath(arg_1)

    # Clean up old saved state, if any
    if os.path.exists(arg_1):
      if not os.path.isdir(arg_1):
        raise Exception(("Existing filesystem entry <%s> is not a model"
                         " checkpoint -- refusing to delete (not a directory)") \
                          % arg_1)
      if not os.path.isfile(arg_3):
        raise Exception(("Existing filesystem entry <%s> is not a model"
                         " checkpoint -- refusing to delete"\
                         " (%s missing or not a file)") % \
                          (arg_1, arg_3))

      shutil.rmtree(arg_1)

    # Create a new directory for saving state
    arg_0.__makeDirectoryFromAbsolutePath(arg_1)

    with open(arg_3, 'wb') as f:
      arg_2.write(f)


def Func(arg_0, arg_1):
    """Deserializes model from checkpointDir using capnproto"""
    arg_2 = arg_0._getModelCheckpointFilePath(arg_1)

    with open(arg_2, 'r') as f:
      arg_3 = arg_0.getSchema().read(f,
                                   traversal_limit_in_words=_TRAVERSAL_LIMIT_IN_WORDS)

    arg_4 = arg_0.read(arg_3)
    return arg_4


def Func(arg_0, arg_1):
    """Save the state maintained by the Model base class

    :param proto: capnp ModelProto message builder
    """
    arg_2 = arg_0.getInferenceType()
    # lower-case first letter to be compatible with capnproto enum naming
    arg_2 = arg_2[:1].lower() + arg_2[1:]
    arg_1.inferenceType = arg_2

    arg_1.numPredictions = arg_0._numPredictions

    arg_1.learningEnabled = arg_0.__learningEnabled
    arg_1.inferenceEnabled = arg_0.__inferenceEnabled
    arg_1.inferenceArgs = json.dumps(arg_0.__inferenceArgs)


def Func(arg_0):
    """ Return the absolute path of the model's pickle file.

    :param saveModelDir: (string)
           Directory of where the experiment is to be or was saved
    :returns: (string) An absolute path.
    """
    arg_1 = os.path.join(arg_0, "model.pkl")
    arg_1 = os.path.abspath(arg_1)
    return arg_1


def Func(arg_0, arg_1, arg_2, arg_3):
  """Used as optparse callback for reaping a variable number of option args.
  The option may be specified multiple times, and all the args associated with
  that option name will be accumulated in the order that they are encountered
  """
  arg_4 = []

  # Reap the args, taking care to stop before the next option or '.'
  arg_5 = False
  for arg_6 in arg_3.rargs:
    # Stop on --longname options
    if arg_6.startswith("--") and len(arg_6) > 2:
      break

    # Stop on -b options
    if arg_6.startswith("-") and len(arg_6) > 1:
      break

    if arg_6 == ".":
      arg_5 = True
      break

    arg_4.append(arg_6)

  if not arg_4:
    raise optparse.OptionValueError(
      ("Empty arg list for option %r expecting one or more args "
       "(remaining tokens: %r)") % (arg_1, arg_3.rargs))

  del arg_3.rargs[:len(arg_4) + int(arg_5)]

  # Retrieve the existing arg accumulator, if any
  arg_2 = getattr(arg_3.values, arg_0.dest, [])
  #print "Previous value: %r" % value
  if arg_2 is None:
    arg_2 = []

  # Append the new args to the existing ones and save to the parser
  arg_2.extend(arg_4)
  setattr(arg_3.values, arg_0.dest, arg_2)


def Func(arg_0, arg_1):
  """Report usage error and exit program with error indication."""
  print arg_0.get_usage()
  print arg_1
  sys.exit(1)


def Func(arg_0, arg_1=None):
  """Creates and runs the experiment

  Args:
    options: namedtuple ParseCommandLineOptionsResult
    model: For testing: may pass in an existing OPF Model instance
        to use instead of creating a new one.

  Returns: reference to OPFExperiment instance that was constructed (this
      is provided to aid with debugging) or None, if none was
      created.
  """
  json_helpers.validate(arg_0.privateOptions,
                        schemaDict=g_parsedPrivateCommandLineOptionsSchema)

  # Load the experiment's description.py module
  arg_2 = arg_0.experimentDir
  arg_3 = helpers.loadExperimentDescriptionScriptFromDir(
      arg_2)
  arg_4 = helpers.getExperimentDescriptionInterfaceFromModule(
      arg_3)

  # Handle "list checkpoints" request
  if arg_0.privateOptions['listAvailableCheckpoints']:
    _printAvailableCheckpoints(arg_2)
    return None

  # Load experiment tasks
  arg_5 = arg_4.getModelControl().get('tasks', [])

  # If the tasks list is empty, and this is a nupic environment description
  # file being run from the OPF, convert it to a simple OPF description file.
  if (len(arg_5) == 0 and
      arg_4.getModelControl()['environment'] == OpfEnvironment.Nupic):
    arg_4.convertNupicEnvToOPF()
    arg_5 = arg_4.getModelControl().get('tasks', [])

  # Ensures all the source locations are either absolute paths or relative to
  # the nupic.datafiles package_data location.
  arg_4.normalizeStreamSources()

  # Extract option
  arg_6 = arg_0.privateOptions['newSerialization']

  # Handle listTasks
  if arg_0.privateOptions['listTasks']:
    print "Available tasks:"

    for arg_7 in [t['taskLabel'] for t in arg_5]:
      print "\t", arg_7

    return None

  # Construct the experiment instance
  if arg_0.privateOptions['runCheckpointName']:

    assert arg_1 is None

    arg_8 = arg_0.privateOptions['runCheckpointName']

    arg_1 = ModelFactory.loadFromCheckpoint(
          savedModelDir=_getModelCheckpointDir(arg_2, arg_8),
          arg_6=arg_6)

  elif arg_1 is not None:
    print "Skipping creation of OPFExperiment instance: caller provided his own"
  else:
    arg_9 = arg_4.getModelDescription()
    arg_1 = ModelFactory.create(arg_9)

  # Handle "create model" request
  if arg_0.privateOptions['createCheckpointName']:
    arg_8 = arg_0.privateOptions['createCheckpointName']
    _saveModel(arg_1=arg_1,
               arg_2=arg_2,
               checkpointLabel=arg_8,
               arg_6=arg_6)

    return arg_1

  # Build the task list

  # Default task execution index list is in the natural list order of the tasks
  arg_10 = range(len(arg_5))

  arg_11 = arg_0.privateOptions['taskLabels']
  if arg_11:
    arg_12 = [t['taskLabel'] for t in arg_5]
    arg_13 = set(arg_12)

    arg_14 = set(arg_11)

    assert arg_14.issubset(arg_13), \
           ("Some custom-provided task execution labels don't correspond "
            "to actual task labels: mismatched labels: %r; actual task "
            "labels: %r.") % (arg_14 - arg_13,
                              arg_11)

    arg_10 = [arg_12.index(arg_7) for arg_7 in
                     arg_11]

    print "#### Executing custom task list: %r" % [arg_12[arg_15] for
                                                   arg_15 in arg_10]

  # Run all experiment tasks
  for arg_16 in arg_10:

    arg_17 = arg_5[arg_16]

    # Create a task runner and run it!
    arg_18 = _TaskRunner(arg_1=arg_1,
                             arg_17=arg_17,
                             cmdOptions=arg_0)
    arg_18.run()
    del arg_18

    if arg_0.privateOptions['checkpointModel']:
      _saveModel(arg_1=arg_1,
                 arg_2=arg_2,
                 checkpointLabel=arg_17['taskLabel'],
                 arg_6=arg_6)

  return arg_1


def Func(arg_0, arg_1):
  """Creates directory for serialization of the model

  checkpointLabel:
      Checkpoint label (string)

  Returns:
    absolute path to the serialization directory
  """
  arg_2 = os.path.join(getCheckpointParentDir(arg_0),
                               arg_1 + g_defaultCheckpointExtension)
  arg_2 = os.path.abspath(arg_2)

  return arg_2


def Func(arg_0):
  """Returns a checkpoint label string for the given model checkpoint directory

  checkpointDir: relative or absolute model checkpoint directory path
  """
  assert arg_0.endswith(g_defaultCheckpointExtension)

  arg_1 = os.path.split(arg_0)[1]

  arg_2 = arg_1[0:-len(g_defaultCheckpointExtension)]

  return arg_2


def Func(arg_0):
  """Return true iff checkpointDir appears to be a checkpoint directory."""
  arg_1 = os.path.split(arg_0)[1]
  if arg_1[0] == '.':
    return False

  if not arg_0.endswith(g_defaultCheckpointExtension):
    return False

  if not os.path.isdir(arg_0):
    return False

  return True


def Func(arg_0):
  """List available checkpoints for the specified experiment."""
  arg_1 = getCheckpointParentDir(arg_0)

  if not os.path.exists(arg_1):
    print "No available checkpoints."
    return

  arg_2 = [x for x in os.listdir(arg_1)
                    if _isCheckpointDir(os.path.join(arg_1, x))]
  if not arg_2:
    print "No available checkpoints."
    return

  print "Available checkpoints:"
  arg_3 = [_checkpointLabelFromCheckpointDir(x)
                    for x in arg_2]

  for arg_4 in sorted(arg_3):
    print "\t", arg_4

  print
  print "To start from a checkpoint:"
  print "  python run_opf_experiment.py experiment --load <CHECKPOINT>"
  print "For example, to start from the checkpoint \"MyCheckpoint\":"
  print "  python run_opf_experiment.py experiment --load MyCheckpoint"


def Func(arg_0):
    """Creates and returns a list of activites for this TaskRunner instance

    Returns: a list of PeriodicActivityRequest elements
    """
    # Initialize periodic activities
    arg_1 = []

    # Metrics reporting
    class MetricsReportCb(object):
      def __init__(arg_0, arg_2):
        arg_0.__taskRunner = arg_2
        return

      def __call__(arg_0):
        arg_0.__taskRunner._getAndEmitExperimentMetrics()

    arg_4 = PeriodicActivityRequest(
      repeating=True,
      period=1000,
      cb=MetricsReportCb(arg_0))

    arg_1.append(arg_4)

    # Iteration progress
    class IterationProgressCb(object):
      arg_5 = 1000

      def __init__(arg_0, arg_6, arg_7, arg_8):
        arg_0.__taskLabel = arg_6
        arg_0.__requestedIterationCount = arg_7
        arg_0.__logger = arg_8

        arg_0.__numIterationsSoFar = 0

      def __call__(arg_0):
        arg_0.__numIterationsSoFar += arg_0.PROGRESS_UPDATE_PERIOD_TICKS
        arg_0.__logger.debug("%s: ITERATION PROGRESS: %s of %s" % (
                              arg_0.__taskLabel,
                              arg_0.__numIterationsSoFar,
                              arg_0.__requestedIterationCount))

    arg_13 = IterationProgressCb(
      arg_6=arg_0.__task['taskLabel'],
      arg_7=arg_0.__task['iterationCount'],
      arg_8=arg_0.__logger)
    arg_14 = PeriodicActivityRequest(
      repeating=True,
      period=IterationProgressCb.PROGRESS_UPDATE_PERIOD_TICKS,
      cb=arg_13)

    arg_1.append(arg_14)

    return arg_1


def Func():
  """
  Shows predictions of the TM when presented with the characters A, B, C, D, X, and
  Y without any contextual information, that is, not embedded within a sequence.
  """
  for arg_0 in range(6):
    tm.reset()
    print "--- " + "ABCDXY"[arg_0] + " ---"
    tm.compute(set(seqT[arg_0][:].nonzero()[0].tolist()), learn=False)
    arg_1 = [tm.columnForCell(i) for i in tm.getActiveCells()]
    arg_2 = [tm.columnForCell(i) for i in tm.getPredictiveCells()]
    arg_3 = [1 if i in arg_1 else 0 for i in range(tm.numberOfColumns())]
    arg_4 = [1 if i in arg_2 else 0 for i in range(tm.numberOfColumns())]
    print("Active cols: " + str(np.nonzero(arg_3)[0]))
    print("Predicted cols: " + str(np.nonzero(arg_4)[0]))
    print ""


def Func(arg_0=2):
  """Utility function to get information about function callers

  The information is the tuple (function/method name, filename, class)
  The class will be None if the caller is just a function and not an object
  method.

  :param depth: (int) how far back in the callstack to go to extract the caller
         info

  """
  arg_1 = sys._getframe(arg_0)
  arg_2 = arg_1.f_code.co_name
  arg_3 = arg_1.f_code.co_filename

  arg_4 = None
  arg_5 = inspect.getargvalues(arg_1)
  if len(arg_5[0]) > 0:
    arg_6 = arg_5[0][0] # potentially the 'self' arg if its a method
    arg_4 = arg_5[3][arg_6].__class__.__name__
  return (arg_2, arg_3, arg_4)


def Func(arg_0):
  """
  Get the arguments, default values, and argument descriptions for a function.

  Parses the argument descriptions out of the function docstring, using a
  format something lke this:

  ::

    [junk]
    argument_name:     description...
      description...
      description...
    [junk]
    [more arguments]

  It will find an argument as long as the exact argument name starts the line.
  It will then strip a trailing colon, if present, then strip the rest of the
  line and use it to start the description. It will then strip and append any
  subsequent lines with a greater indent level than the original argument name.

  :param f: (function) to inspect
  :returns: (list of tuples) (``argName``, ``argDescription``, ``defaultValue``)
    If an argument has no default value, the tuple is only two elements long (as
    ``None`` cannot be used, since it could be a default value itself).
  """

  # Get the argument names and default values
  arg_1 = inspect.getargspec(arg_0)

  # Scan through the docstring to extract documentation for each argument as
  # follows:
  #   Check the first word of the line, stripping a colon if one is present.
  #   If it matches an argument name:
  #    Take the rest of the line, stripping leading whitespeace
  #    Take each subsequent line if its indentation level is greater than the
  #      initial indentation level
  #    Once the indentation level is back to the original level, look for
  #      another argument
  arg_2 = arg_0.__doc__
  arg_3 = {}
  if arg_2:
    arg_4 = arg_2.split('\n')
    arg_5 = 0
    while arg_5 < len(arg_4):
      arg_6 = arg_4[arg_5].lstrip()
      if not arg_6:
        arg_5 += 1
        continue
      # Indentation level is index of the first character
      arg_7 = arg_4[arg_5].index(arg_6[0])
      # Get the first word and remove the colon, if present
      arg_8 = arg_6.split()[0]
      if arg_8.endswith(':'):
        arg_8 = arg_8[:-1]
      if arg_8 in arg_1.args:
        # Found an argument
        arg_9 = arg_8
        arg_10 = arg_6[len(arg_8)+1:].strip()
        arg_11 = [arg_10]
        # Take the next lines as long as they are indented more
        arg_5 += 1
        while arg_5 < len(arg_4):
          arg_6 = arg_4[arg_5].lstrip()
          if not arg_6:
            # Empty line - stop
            break
          if arg_4[arg_5].index(arg_6[0]) <= arg_7:
            # No longer indented far enough - stop
            break
          # This line counts too
          arg_11.append(arg_4[arg_5].strip())
          arg_5 += 1
        # Store this description
        arg_3[arg_9] = ' '.join(arg_11)
      else:
        # Not an argument
        arg_5 += 1

  # Build the list of (argName, description, defaultValue)
  arg_12 = []
  if arg_1.defaults:
    arg_13 = len(arg_1.defaults)
  else:
    arg_13 = 0
  arg_14 = len(arg_1.args) - arg_13
  for arg_5, arg_9 in enumerate(arg_1.args):
    if arg_5 >= arg_14:
      arg_15 = arg_1.defaults[arg_5 - arg_14]
      arg_12.append((arg_9, arg_3.get(arg_9, ""), arg_15))
    else:
      arg_12.append((arg_9, arg_3.get(arg_9, "")))

  return arg_12


def Func():
  """ Generate a filepath for the calling app """
  arg_0 = os.path.splitext(os.path.basename(sys.argv[0]))[0] or 'UnknownApp'
  arg_1 = os.path.abspath(os.path.join(
    os.environ['NTA_LOG_DIR'],
    'numenta-logs-%s' % (os.environ['USER'],),
    arg_0))
  arg_2 = '%s-%s-%s.log' % (
    arg_0, long(time.mktime(time.gmtime())), os.getpid())
  return os.path.join(arg_1, arg_2)


def Func(arg_0):
  """
  Return the number of months and seconds from an aggregation dict that
  represents a date and time.

  Interval is a dict that contain one or more of the following keys: 'years',
  'months', 'weeks', 'days', 'hours', 'minutes', seconds', 'milliseconds',
  'microseconds'.

  For example:

  ::

    aggregationMicroseconds({'years': 1, 'hours': 4, 'microseconds':42}) ==
        {'months':12, 'seconds':14400.000042}

  :param interval: (dict) The aggregation interval representing a date and time
  :returns: (dict) number of months and seconds in the interval:
            ``{months': XX, 'seconds': XX}``. The seconds is
            a floating point that can represent resolutions down to a
            microsecond.

  """

  arg_1 = arg_0.get('microseconds', 0) * 0.000001
  arg_1 += arg_0.get('milliseconds', 0) * 0.001
  arg_1 += arg_0.get('seconds', 0)
  arg_1 += arg_0.get('minutes', 0) * 60
  arg_1 += arg_0.get('hours', 0) * 60 * 60
  arg_1 += arg_0.get('days', 0) * 24 * 60 * 60
  arg_1 += arg_0.get('weeks', 0) * 7 * 24 * 60 * 60

  arg_2 = arg_0.get('months', 0)
  arg_2 += 12 * arg_0.get('years', 0)

  return {'months': arg_2, 'seconds': arg_1}


def Func(arg_0, arg_1):
  """
  Return the result from dividing two dicts that represent date and time.

  Both dividend and divisor are dicts that contain one or more of the following
  keys: 'years', 'months', 'weeks', 'days', 'hours', 'minutes', seconds',
  'milliseconds', 'microseconds'.

  For example:

  ::

    Func({'hours': 4}, {'minutes': 15}) == 16

  :param dividend: (dict) The numerator, as a dict representing a date and time
  :param divisor: (dict) the denominator, as a dict representing a date and time
  :returns: (float) number of times divisor goes into dividend

  """

  # Convert each into microseconds
  arg_2 = aggregationToMonthsSeconds(arg_0)
  arg_3 = aggregationToMonthsSeconds(arg_1)

  # It is a usage error to mix both months and seconds in the same operation
  if (arg_2['months'] != 0 and arg_3['seconds'] != 0) \
    or (arg_2['seconds'] != 0 and arg_3['months'] != 0):
    raise RuntimeError("Aggregation dicts with months/years can only be "
      "inter-operated with other aggregation dicts that contain "
      "months/years")

  if arg_2['months'] > 0:
    return float(arg_2['months']) / arg_1['months']

  else:
    return float(arg_2['seconds']) / arg_3['seconds']


def Func(arg_0):
  """
  Helper function to create a logger object for the current object with
  the standard Numenta prefix.

  :param obj: (object) to add a logger to
  """
  if inspect.isclass(arg_0):
    arg_1 = arg_0
  else:
    arg_1 = arg_0.__class__
  arg_2 = logging.getLogger(".".join(
    ['com.numenta', arg_1.__module__, arg_1.__name__]))
  return arg_2


def Func(arg_0, arg_1):
  """
  Returns a subset of the keys that match any of the given patterns

  :param patterns: (list) regular expressions to match
  :param keys: (list) keys to search for matches
  """
  arg_2 = []
  if arg_0:
    for arg_3 in arg_0:
      arg_4 = re.compile(arg_3)
      for arg_5 in arg_1:
        if arg_4.match(arg_5):
          arg_2.append(arg_5)
  else:
    return None

  return arg_2


def Func(arg_0, arg_1):
    """
    Convert the input, which is in normal space, into log space
    """
    if arg_1 == SENTINEL_VALUE_FOR_MISSING_DATA:
      return None
    else:
      arg_2 = arg_1
      if arg_2 < arg_0.minval:
        arg_2 = arg_0.minval
      elif arg_2 > arg_0.maxval:
        arg_2 = arg_0.maxval

      arg_3 = math.log10(arg_2)
      return arg_3


def Func(arg_0):
    """
    Exports a network as a networkx MultiDiGraph intermediate representation
    suitable for visualization.

    :return: networkx MultiDiGraph
    """
    arg_1 = nx.MultiDiGraph()

    # Add regions to graph as nodes, annotated by name
    arg_2 = arg_0.network.getRegions()

    for arg_3 in xrange(arg_2.getCount()):
      arg_4 = arg_2.getByIndex(arg_3)
      arg_5 = arg_4[0]
      arg_1.add_node(arg_5, label=arg_5)

    # Add links between regions to graph as edges, annotate by input-output
    # name pairs
    for arg_6, arg_7 in arg_0.network.getLinks():
      arg_1.add_edge(arg_7.getSrcRegionName(),
                     arg_7.getDestRegionName(),
                     src=arg_7.getSrcOutputName(),
                     dest=arg_7.getDestInputName())

    return arg_1


def Func(arg_0, arg_1, arg_2):
  """
  Computes the percentage of overlap between vectors x1 and x2.

  @param x1   (array) binary vector
  @param x2   (array) binary vector
  @param size (int)   length of binary vectors

  @return percentOverlap (float) percentage overlap between x1 and x2
  """
  arg_3 = np.count_nonzero(arg_0)
  arg_4 = np.count_nonzero(arg_1)
  arg_5 = min(arg_3, arg_4)
  Func = 0
  if arg_5 > 0:
    Func = float(np.dot(arg_0, arg_1))/float(arg_5)
  return Func


def Func():
  """Poll CPU usage, make predictions, and plot the results. Runs forever."""
  # Create the model for predicting CPU usage.
  arg_0 = ModelFactory.create(model_params.MODEL_PARAMS)
  arg_0.enableInference({'predictedField': 'cpu'})
  # The shifter will align prediction and actual values.
  arg_1 = InferenceShifter()
  # Keep the last WINDOW predicted and actual values for plotting.
  arg_2 = deque([0.0] * WINDOW, maxlen=60)
  arg_3 = deque([0.0] * WINDOW, maxlen=60)

  # Initialize the plot lines that we will update with each new record.
  arg_4, = plt.plot(range(WINDOW), arg_2)
  arg_5, = plt.plot(range(WINDOW), arg_3)
  # Set the y-axis range.
  arg_4.axes.set_ylim(0, 100)
  arg_5.axes.set_ylim(0, 100)

  while True:
    arg_6 = time.time()

    # Get the CPU usage.
    arg_7 = psutil.cpu_percent()

    # Run the input through the model and shift the resulting prediction.
    arg_8 = {'cpu': arg_7}
    arg_9 = arg_1.shift(arg_0.run(arg_8))

    # Update the trailing predicted and actual value deques.
    arg_10 = arg_9.inferences['multiStepBestPredictions'][5]
    if arg_10 is not None:
      arg_2.append(arg_9.rawInput['cpu'])
      arg_3.append(arg_10)

    # Redraw the chart with the new data.
    arg_4.set_ydata(arg_2)  # update the data
    arg_5.set_ydata(arg_3)  # update the data
    plt.draw()
    plt.legend( ('actual','predicted') )

    # Make sure we wait a total of 2 seconds per iteration.
    try:
      plt.pause(SECONDS_PER_STEP)
    except:
      pass


def Func(arg_0):
    """
    List of our member variables that we don't need to be saved
    """
    arg_1 = BacktrackingTM.Func(arg_0)
    if arg_0.makeCells4Ephemeral:
      arg_1.extend(['cells4'])
    return arg_1


def Func(arg_0):
    """If state is allocated in CPP, copy over the data into our numpy arrays."""

    # Get learn states if we need to print them out
    if arg_0.verbosity > 1 or arg_0.retrieveLearningStates:
      (arg_1, arg_2, arg_3, arg_4) = arg_0.cells4.getLearnStates()
      arg_0.lrnActiveState['t-1'] = arg_2.reshape((arg_0.numberOfCols, arg_0.cellsPerColumn))
      arg_0.lrnActiveState['t'] = arg_1.reshape((arg_0.numberOfCols, arg_0.cellsPerColumn))
      arg_0.lrnPredictedState['t-1'] = arg_4.reshape((arg_0.numberOfCols, arg_0.cellsPerColumn))
      arg_0.lrnPredictedState['t'] = arg_3.reshape((arg_0.numberOfCols, arg_0.cellsPerColumn))

    if arg_0.allocateStatesInCPP:
      assert False
      (arg_1, arg_2, arg_3, arg_4, arg_7, arg_8, arg_9,
       arg_10) = arg_0.cells4.getStates()
      arg_0.cellConfidence['t'] = arg_9.reshape((arg_0.numberOfCols, arg_0.cellsPerColumn))
      arg_0.cellConfidence['t-1'] = arg_10.reshape((arg_0.numberOfCols, arg_0.cellsPerColumn))
      arg_0.colConfidence['t'] = arg_7.reshape(arg_0.numberOfCols)
      arg_0.colConfidence['t-1'] = arg_8.reshape(arg_0.numberOfCols)
      arg_0.infActiveState['t-1'] = arg_2.reshape((arg_0.numberOfCols, arg_0.cellsPerColumn))
      arg_0.infActiveState['t'] = arg_1.reshape((arg_0.numberOfCols, arg_0.cellsPerColumn))
      arg_0.infPredictedState['t-1'] = arg_4.reshape((arg_0.numberOfCols, arg_0.cellsPerColumn))
      arg_0.infPredictedState['t'] = arg_3.reshape((arg_0.numberOfCols, arg_0.cellsPerColumn))


def Func(arg_0):
    """If we are having CPP use numpy-allocated buffers, set these buffer
    pointers. This is a relatively fast operation and, for safety, should be
    done before every call to the cells4 compute methods.  This protects us
    in situations where code can cause Python or numpy to create copies."""
    if not arg_0.allocateStatesInCPP:
      arg_0.cells4.setStatePointers(
          arg_0.infActiveState["t"], arg_0.infActiveState["t-1"],
          arg_0.infPredictedState["t"], arg_0.infPredictedState["t-1"],
          arg_0.colConfidence["t"], arg_0.colConfidence["t-1"],
          arg_0.cellConfidence["t"], arg_0.cellConfidence["t-1"])


def Func(arg_0, arg_1, arg_2):
    """
    A segment is active if it has >= activationThreshold connected
    synapses that are active due to infActiveState.

    """

    arg_3 = arg_1.size()
    arg_4 = 0
    for arg_5 in xrange(arg_3):
      if arg_1.getPermanence(arg_5) < arg_0.connectedPerm:
        continue
      arg_6, arg_7 = arg_0.getColCellIdx(arg_1.getSrcCellIdx(arg_5))
      if arg_0.infActiveState[arg_2][arg_6, arg_7]:
        arg_4 += 1
        if arg_4 >= arg_0.activationThreshold:
          return True

    return arg_4 >= arg_0.activationThreshold


def Func(arg_0, arg_1):
    """
    Given a bucket index, return the list of non-zero bits. If the bucket
    index does not exist, it is created. If the index falls outside our range
    we clip it.

    :param index The bucket index to get non-zero bits for.
    @returns numpy array of indices of non-zero bits for specified index.
    """
    if arg_1 < 0:
      arg_1 = 0

    if arg_1 >= arg_0._maxBuckets:
      arg_1 = arg_0._maxBuckets-1

    if not arg_0.bucketMap.has_key(arg_1):
      if arg_0.verbosity >= 2:
        print "Adding additional buckets to handle index=", arg_1
      arg_0._createBucket(arg_1)
    return arg_0.bucketMap[arg_1]


def Func(arg_0, arg_1):
    """
    Create the given bucket index. Recursively create as many in-between
    bucket indices as necessary.
    """
    if arg_1 < arg_0.minIndex:
      if arg_1 == arg_0.minIndex - 1:
        # Create a new representation that has exactly w-1 overlapping bits
        # as the min representation
        arg_0.bucketMap[arg_1] = arg_0._newRepresentation(arg_0.minIndex,
                                                        arg_1)
        arg_0.minIndex = arg_1
      else:
        # Recursively create all the indices above and then this index
        arg_0.Func(arg_1+1)
        arg_0.Func(arg_1)
    else:
      if arg_1 == arg_0.maxIndex + 1:
        # Create a new representation that has exactly w-1 overlapping bits
        # as the max representation
        arg_0.bucketMap[arg_1] = arg_0._newRepresentation(arg_0.maxIndex,
                                                        arg_1)
        arg_0.maxIndex = arg_1
      else:
        # Recursively create all the indices below and then this index
        arg_0.Func(arg_1-1)
        arg_0.Func(arg_1)


def Func(arg_0, arg_1, arg_2):
    """
    Return a new representation for newIndex that overlaps with the
    representation at index by exactly w-1 bits
    """
    arg_3 = arg_0.bucketMap[arg_1].copy()

    # Choose the bit we will replace in this representation. We need to shift
    # this bit deterministically. If this is always chosen randomly then there
    # is a 1 in w chance of the same bit being replaced in neighboring
    # representations, which is fairly high
    arg_4 = arg_2 % arg_0.w

    # Now we choose a bit such that the overlap rules are satisfied.
    arg_5 = arg_0.random.getUInt32(arg_0.n)
    arg_3[arg_4] = arg_5
    while arg_5 in arg_0.bucketMap[arg_1] or \
          not arg_0.FuncOK(arg_3, arg_2):
      arg_0.numTries += 1
      arg_5 = arg_0.random.getUInt32(arg_0.n)
      arg_3[arg_4] = arg_5

    return arg_3


def Func(arg_0, arg_1, arg_2):
    """
    Return the overlap between bucket indices i and j
    """
    if arg_0.bucketMap.has_key(arg_1) and arg_0.bucketMap.has_key(arg_2):
      arg_3 = arg_0.bucketMap[arg_1]
      arg_4 = arg_0.bucketMap[arg_2]
      return arg_0._countOverlap(arg_3, arg_4)
    else:
      raise ValueError("Either i or j don't exist")


def Func(arg_0, arg_1):
    """
    Return the overlap between two representations. rep1 and rep2 are lists of
    non-zero indices.
    """
    arg_2 = 0
    for arg_3 in arg_0:
      if arg_3 in arg_1:
        arg_2 += 1
    return arg_2


def Func(arg_0, arg_1, arg_2, arg_3=None):
    """
    Return True if the given overlap between bucket indices i and j are
    acceptable. If overlap is not specified, calculate it from the bucketMap
    """
    if arg_3 is None:
      arg_3 = arg_0._countOverlapIndices(arg_1, arg_2)
    if abs(arg_1-arg_2) < arg_0.w:
      if arg_3 == (arg_0.w - abs(arg_1-arg_2)):
        return True
      else:
        return False
    else:
      if arg_3 <= arg_0._maxOverlap:
        return True
      else:
        return False


def Func(*arg_0, **arg_1):
    """
    Create a SDR classifier factory.
    The implementation of the SDR Classifier can be specified with
    the "implementation" keyword argument.

    The SDRClassifierFactory uses the implementation as specified in
     `Default NuPIC Configuration <default-config.html>`_.
    """
    arg_2 = arg_1.pop('implementation', None)
    if arg_2 is None:
      arg_2 = Configuration.get('nupic.opf.sdrClassifier.implementation')
    if arg_2 == 'py':
      return SDRClassifier(*arg_0, **arg_1)
    elif arg_2 == 'cpp':
      return FastSDRClassifier(*arg_0, **arg_1)
    elif arg_2 == 'diff':
      return SDRClassifierDiff(*arg_0, **arg_1)
    else:
      raise ValueError('Invalid classifier implementation (%r). Value must be '
                       '"py", "cpp" or "diff".' % arg_2)


def Func(arg_0, arg_1):
    """
    Convenience method to compute a metric over an indices trace, excluding
    resets.

    @param (IndicesTrace) Trace of indices

    @return (Metric) Metric over trace excluding resets
    """
    return Metric.createFromTrace(arg_1.makeCountsTrace(),
                                  excludeResets=arg_0.mmGetTraceResets())


def Func(arg_0):
    """
    Metric for number of predicted => active cells per column for each sequence

    @return (Metric) metric
    """
    arg_0._mmComputeTransitionTraces()

    arg_1 = []

    for arg_2 in (
        arg_0._mmData["predictedActiveCellsForSequence"].values()):
      arg_3 = arg_0.mapCellsToColumns(arg_2)
      arg_1 += [len(arg_4) for arg_4 in arg_3.values()]

    return Metric(arg_0,
                  "# predicted => active cells per column for each sequence",
                  arg_1)


def Func(arg_0):
    """
    Metric for number of sequences each predicted => active cell appears in

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

    @return (Metric) metric
    """
    arg_0._mmComputeTransitionTraces()

    arg_1 = defaultdict(lambda: 0)

    for arg_2 in (
          arg_0._mmData["predictedActiveCellsForSequence"].values()):
      for arg_3 in arg_2:
        arg_1[arg_3] += 1

    return Metric(arg_0,
                  "# sequences each predicted => active cells appears in",
                  arg_1.values())


def Func(arg_0):
    """
    Pretty print the connections in the temporal memory.

    TODO: Use PrettyTable.

    @return (string) Pretty-printed text
    """
    arg_1 = ""

    arg_1 += ("Segments: (format => "
             "(#) [(source cell=permanence ...),       ...]\n")
    arg_1 += "------------------------------------\n"

    arg_2 = range(arg_0.numberOfColumns())

    for arg_3 in arg_2:
      arg_4 = arg_0.cellsForColumn(arg_3)

      for arg_5 in arg_4:
        arg_6 = dict()

        for arg_7 in arg_0.connections.segmentsForCell(arg_5):
          arg_8 = []

          for arg_9 in arg_0.connections.synapsesForSegment(arg_7):
            arg_10 = arg_0.connections.dataForSynapse(arg_9)
            arg_8.append(
                (arg_10.presynapticCell, arg_10.permanence))

          arg_8.sort()
          arg_11 = ["{0:3}={1:.2f}".format(sourceCell, permanence) for
                               sourceCell, permanence in arg_8]
          arg_6[arg_7] = "({0})".format(" ".join(arg_11))

        arg_1 += ("Column {0:3} / Cell {1:3}:\t({2}) {3}\n".format(
          arg_3, arg_5,
          len(arg_6.values()),
          "[{0}]".format(",       ".join(arg_6.values()))))

      if arg_3 < len(arg_2) - 1:  # not last
        arg_1 += "\n"

    arg_1 += "------------------------------------\n"

    return arg_1


def Func(arg_0, arg_1=arg_2,
                          arg_3=arg_4,
                          arg_5=arg_6):

  """Generates a Network with connected RecordSensor, SP, TM.

  This function takes care of generating regions and the canonical links.
  The network has a sensor region reading data from a specified input and
  passing the encoded representation to an SPRegion.
  The SPRegion output is passed to a TMRegion.

  Note: this function returns a network that needs to be initialized. This
  allows the user to extend the network by adding further regions and
  connections.

  :param recordParams: a dict with parameters for creating RecordSensor region.
  :param spatialParams: a dict with parameters for creating SPRegion.
  :param temporalParams: a dict with parameters for creating TMRegion.
  :param verbosity: an integer representing how chatty the network will be.
  """
  arg_7 = arg_0["inputFilePath"]
  arg_8 = arg_0["scalarEncoderArgs"]
  arg_9 = arg_0["dateEncoderArgs"]

  arg_10 = ScalarEncoder(**arg_8)
  arg_11 = DateEncoder(**arg_9)

  arg_12 = MultiEncoder()
  arg_12.addEncoder(arg_8["name"], arg_10)
  arg_12.addEncoder(arg_9["name"], arg_11)

  arg_13 = Network()

  arg_13.addRegion("sensor", "py.RecordSensor",
                    json.dumps({"verbosity": arg_5}))

  arg_14 = arg_13.regions["sensor"].getSelf()
  arg_14.encoder = arg_12
  arg_14.dataSource = FileRecordStream(streamID=arg_7)

  # Create the spatial pooler region
  arg_1["inputWidth"] = arg_14.encoder.getWidth()
  arg_13.addRegion("spatialPoolerRegion", "py.SPRegion",
                    json.dumps(arg_1))

  # Link the SP region to the sensor input
  arg_13.link("sensor", "spatialPoolerRegion", "UniformLink", "")
  arg_13.link("sensor", "spatialPoolerRegion", "UniformLink", "",
               srcOutput="resetOut", destInput="resetIn")
  arg_13.link("spatialPoolerRegion", "sensor", "UniformLink", "",
               srcOutput="spatialTopDownOut", destInput="spatialTopDownIn")
  arg_13.link("spatialPoolerRegion", "sensor", "UniformLink", "",
               srcOutput="temporalTopDownOut", destInput="temporalTopDownIn")

  # Add the TPRegion on top of the SPRegion
  arg_13.addRegion("temporalPoolerRegion", "py.TMRegion",
                    json.dumps(arg_3))

  arg_13.link("spatialPoolerRegion", "temporalPoolerRegion", "UniformLink", "")
  arg_13.link("temporalPoolerRegion", "spatialPoolerRegion", "UniformLink", "",
               srcOutput="topDownOut", destInput="topDownIn")

  arg_16 = arg_13.regions["spatialPoolerRegion"]

  # Make sure learning is enabled
  arg_16.setParameter("learningMode", True)
  # We want temporal anomalies so disable anomalyMode in the SP. This mode is
  # used for computing anomalies in a non-temporal model.
  arg_16.setParameter("anomalyMode", False)

  arg_17 = arg_13.regions["temporalPoolerRegion"]

  # Enable topDownMode to get the predicted columns output
  arg_17.setParameter("topDownMode", True)
  # Make sure learning is enabled (this is the default)
  arg_17.setParameter("learningMode", True)
  # Enable inference mode so we get predictions
  arg_17.setParameter("inferenceMode", True)
  # Enable anomalyMode to compute the anomaly score.
  arg_17.setParameter("anomalyMode", True)

  return arg_13


def Func(arg_0, arg_1, arg_2, arg_3, arg_4, arg_5):
  """Multiplies a value over a range of rows.

  Args:
    reader: A FileRecordStream object with input data.
    writer: A FileRecordStream  object to write output data to.
    column: The column of data to modify.
    start: The first row in the range to modify.
    end: The last row in the range to modify.
    multiple: The value to Func/multiply by.
  """
  for arg_6, arg_7 in enumerate(arg_0):
    if arg_6 >= arg_3 and arg_6 <= arg_4:
      arg_7[arg_2] = type(arg_5)(arg_7[arg_2]) * arg_5
    arg_1.appendRecord(arg_7)


def Func(arg_0, arg_1, arg_2, arg_3, arg_4=None, arg_5=None):
  """Copies a range of values to a new location in the data set.

  Args:
    reader: A FileRecordStream object with input data.
    writer: A FileRecordStream object to write output data to.
    start: The first row in the range to Func.
    stop: The last row in the range to Func.
    insertLocation: The location to insert the copied range. If not specified,
        the range is inserted immediately following itself.
  """
  assert arg_3 >= arg_2
  arg_6 = []
  arg_7 = []
  arg_8 = None
  arg_9 = None
  if arg_5 is None:
    arg_5 = arg_0.getTimestampFieldIdx()
  for arg_10, arg_11 in enumerate(arg_0):
    # Get the first timestamp and the increment.
    if arg_8 is None:
      arg_8 = arg_11[arg_5]
    elif arg_9 is None:
      arg_9 = arg_11[arg_5] - arg_8
    # Keep a list of all rows and a list of rows to Func.
    if arg_10 >= arg_2 and arg_10 <= arg_3:
      arg_7.append(arg_11)
    arg_6.append(arg_11)
  # Insert the copied rows.
  if arg_4 is None:
    arg_4 = arg_3 + 1
  arg_6[arg_4:arg_4] = arg_7
  # Update the timestamps.
  for arg_11 in arg_6:
    arg_11[arg_5] = arg_8
    arg_1.appendRecord(arg_11)
    arg_8 += arg_9


def Func(arg_0, arg_1):
    """generate description from a text description of the ranges"""
    arg_2 = ""
    arg_3 = len(arg_1)
    for arg_4 in xrange(arg_3):
      if arg_1[arg_4][0] != arg_1[arg_4][1]:
        arg_2 += "%.2f-%.2f" % (arg_1[arg_4][0], arg_1[arg_4][1])
      else:
        arg_2 += "%.2f" % (arg_1[arg_4][0])
      if arg_4 < arg_3 - 1:
        arg_2 += ", "
    return arg_2


def Func(arg_0,):
    """
    Reset the state of all cells.

    This is normally used between sequences while training. All internal states
    are Func to 0.
    """
    if arg_0.verbosity >= 3:
      print "\n==== RESET ====="

    arg_0.lrnActiveState['t-1'].fill(0)
    arg_0.lrnActiveState['t'].fill(0)
    arg_0.lrnPredictedState['t-1'].fill(0)
    arg_0.lrnPredictedState['t'].fill(0)

    arg_0.infActiveState['t-1'].fill(0)
    arg_0.infActiveState['t'].fill(0)
    arg_0.infPredictedState['t-1'].fill(0)
    arg_0.infPredictedState['t'].fill(0)

    arg_0.cellConfidence['t-1'].fill(0)
    arg_0.cellConfidence['t'].fill(0)

    # Flush the segment update queue
    arg_0.segmentUpdates = {}

    arg_0._internalStats['nInfersSinceReset'] = 0

    #To be removed
    arg_0._internalStats['curPredictionScore'] = 0
    #New prediction score
    arg_0._internalStats['curPredictionScore2']   = 0
    arg_0._internalStats['curFalseNegativeScore'] = 0
    arg_0._internalStats['curFalsePositiveScore'] = 0

    arg_0._internalStats['curMissing'] = 0
    arg_0._internalStats['curExtra'] = 0

    # When a Func occurs, set prevSequenceSignature to the signature of the
    # just-completed sequence and start accumulating histogram for the next
    # sequence.
    arg_0._internalStats['prevSequenceSignature'] = None
    if arg_0.collectSequenceStats:
      if arg_0._internalStats['confHistogram'].sum() > 0:
        arg_3 = arg_0._internalStats['confHistogram'].copy()
        arg_3.reshape(arg_0.numberOfCols * arg_0.cellsPerColumn)
        arg_0._internalStats['prevSequenceSignature'] = arg_3
      arg_0._internalStats['confHistogram'].fill(0)

    arg_0.FuncCalled = True

    # Clear out input history
    arg_0._prevInfPatterns = []
    arg_0._prevLrnPatterns = []


def Func(arg_0, arg_1, arg_2, arg_3,
                           arg_4):
    """
    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
    """
    # Return if not collecting stats
    if not arg_0.collectStats:
      return
    arg_1['nInfersSinceReset'] += 1

    # Compute the prediction score, how well the prediction from the last
    # time step predicted the current bottom-up input
    (arg_5, arg_6, arg_7) = arg_0._checkPrediction(
        patternNZs=[arg_2], output=arg_3,
        arg_4=arg_4)
    arg_8, arg_9, arg_10 = (
        arg_7[0])

    # Store the stats that don't depend on burn-in
    arg_1['curPredictionScore2'] = float(arg_8)
    arg_1['curFalseNegativeScore'] = 1.0 - float(arg_9)
    arg_1['curFalsePositiveScore'] = float(arg_10)

    arg_1['curMissing'] = arg_6
    arg_1['curExtra'] = arg_5

    # If we are passed the burn-in period, update the accumulated stats
    # Here's what various burn-in values mean:
    #   0: try to predict the first element of each sequence and all subsequent
    #   1: try to predict the second element of each sequence and all subsequent
    #   etc.
    if arg_1['nInfersSinceReset'] <= arg_0.burnIn:
      return

    # Burn-in related stats
    arg_1['nPredictions'] += 1
    arg_11 = max(1.0, float(len(arg_2)))

    arg_1['totalMissing'] += arg_6
    arg_1['totalExtra'] += arg_5
    arg_1['pctExtraTotal'] += 100.0 * arg_5 / arg_11
    arg_1['pctMissingTotal'] += 100.0 * arg_6 / arg_11
    arg_1['predictionScoreTotal2'] += float(arg_8)
    arg_1['falseNegativeScoreTotal'] += 1.0 - float(arg_9)
    arg_1['falsePositiveScoreTotal'] += float(arg_10)

    if arg_0.collectSequenceStats:
      # Collect cell confidences for every cell that correctly predicted current
      # bottom up input. Normalize confidence across each column
      arg_12 = arg_0.cellConfidence['t-1'] * arg_0.infActiveState['t']
      arg_13 = arg_12.sum(axis=1)
      for arg_14 in range(arg_0.numberOfCols):
        if arg_13[arg_14] > 0:
          arg_12[arg_14, :] /= arg_13[arg_14]

      # Update cell confidence histogram: add column-normalized confidence
      # scores to the histogram
      arg_0._internalStats['confHistogram'] += arg_12


def Func(arg_0, arg_1):
    """
    Print an integer array that is the same shape as activeState.

    :param aState: TODO: document
    """
    def formatRow(arg_2, arg_3):
      arg_4 = ''
      for arg_5 in range(arg_0.numberOfCols):
        if arg_5 > 0 and arg_5 % 10 == 0:
          arg_4 += ' '
        arg_4 += str(arg_2[arg_5, arg_3])
      arg_4 += ' '
      return arg_4

    for arg_3 in xrange(arg_0.cellsPerColumn):
      print formatRow(arg_1, arg_3)


def Func(arg_0, arg_1, arg_2 = 20):
    """
    Print a floating point array that is the same shape as activeState.

    :param aState: TODO: document
    :param maxCols: TODO: document
    """
    def formatFPRow(arg_3, arg_4):
      arg_5 = ''
      for arg_6 in range(min(arg_2, arg_0.numberOfCols)):
        if arg_6 > 0 and arg_6 % 10 == 0:
          arg_5 += '   '
        arg_5 += ' %5.3f' % arg_3[arg_6, arg_4]
      arg_5 += ' '
      return arg_5

    for arg_4 in xrange(arg_0.cellsPerColumn):
      print formatFPRow(arg_1, arg_4)


def Func(arg_0, arg_1, arg_2 = 20):
    """
    Print up to maxCols number from a flat floating point array.

    :param aState: TODO: document
    :param maxCols: TODO: document
    """
    def formatFPRow(arg_3):
      arg_4 = ''
      for arg_5 in range(min(arg_2, arg_0.numberOfCols)):
        if arg_5 > 0 and arg_5 % 10 == 0:
          arg_4 += '   '
        arg_4 += ' %5.3f' % arg_3[arg_5]
      arg_4 += ' '
      return arg_4

    print formatFPRow(arg_1)


def Func(arg_0):
    """
    Print the parameter settings for the TM.
    """
    print "numberOfCols=", arg_0.numberOfCols
    print "cellsPerColumn=", arg_0.cellsPerColumn
    print "minThreshold=", arg_0.minThreshold
    print "newSynapseCount=", arg_0.newSynapseCount
    print "activationThreshold=", arg_0.activationThreshold
    print
    print "initialPerm=", arg_0.initialPerm
    print "connectedPerm=", arg_0.connectedPerm
    print "permanenceInc=", arg_0.permanenceInc
    print "permanenceDec=", arg_0.permanenceDec
    print "permanenceMax=", arg_0.permanenceMax
    print "globalDecay=", arg_0.globalDecay
    print
    print "doPooling=", arg_0.doPooling
    print "segUpdateValidDuration=", arg_0.segUpdateValidDuration
    print "pamLength=", arg_0.pamLength


def Func(arg_0, arg_1, arg_2=False):
    """
    Called at the end of inference to print out various diagnostic
    information based on the current verbosity level.

    :param output: TODO: document
    :param learn: TODO: document
    """
    if arg_0.verbosity >= 3:
      print "----- computeEnd summary: "
      print "learn:", arg_2
      print "numBurstingCols: %s, " % (
          arg_0.infActiveState['t'].min(axis=1).sum()),
      print "curPredScore2: %s, " % (
          arg_0._internalStats['curPredictionScore2']),
      print "curFalsePosScore: %s, " % (
          arg_0._internalStats['curFalsePositiveScore']),
      print "1-curFalseNegScore: %s, " % (
          1 - arg_0._internalStats['curFalseNegativeScore'])
      print "numSegments: ", arg_0.getNumSegments(),
      print "avgLearnedSeqLength: ", arg_0.avgLearnedSeqLength

      print "----- infActiveState (%d on) ------" % (
          arg_0.infActiveState['t'].sum())
      arg_0.printActiveIndices(arg_0.infActiveState['t'])
      if arg_0.verbosity >= 6:
        arg_0.printState(arg_0.infActiveState['t'])

      print "----- infPredictedState (%d on)-----" % (
          arg_0.infPredictedState['t'].sum())
      arg_0.printActiveIndices(arg_0.infPredictedState['t'])
      if arg_0.verbosity >= 6:
        arg_0.printState(arg_0.infPredictedState['t'])

      print "----- lrnActiveState (%d on) ------" % (
          arg_0.lrnActiveState['t'].sum())
      arg_0.printActiveIndices(arg_0.lrnActiveState['t'])
      if arg_0.verbosity >= 6:
        arg_0.printState(arg_0.lrnActiveState['t'])

      print "----- lrnPredictedState (%d on)-----" % (
          arg_0.lrnPredictedState['t'].sum())
      arg_0.printActiveIndices(arg_0.lrnPredictedState['t'])
      if arg_0.verbosity >= 6:
        arg_0.printState(arg_0.lrnPredictedState['t'])

      print "----- cellConfidence -----"
      arg_0.printActiveIndices(arg_0.cellConfidence['t'], andValues=True)
      if arg_0.verbosity >= 6:
        arg_0.printConfidence(arg_0.cellConfidence['t'])

      print "----- colConfidence -----"
      arg_0.printActiveIndices(arg_0.colConfidence['t'], andValues=True)

      print "----- cellConfidence[t-1] for currently active cells -----"
      arg_3 = arg_0.cellConfidence['t-1'] * arg_0.infActiveState['t']
      arg_0.printActiveIndices(arg_3, andValues=True)

      if arg_0.verbosity == 4:
        print "Cells, predicted segments only:"
        arg_0.printCells(predictedOnly=True)
      elif arg_0.verbosity >= 5:
        print "Cells, all segments:"
        arg_0.printCells(predictedOnly=False)
      print

    elif arg_0.verbosity >= 1:
      print "TM: learn:", arg_2
      print "TM: active outputs(%d):" % len(arg_1.nonzero()[0]),
      arg_0.printActiveIndices(arg_1.reshape(arg_0.numberOfCols,
                                             arg_0.cellsPerColumn))


def Func(arg_0, arg_1):
    """Update our moving average of learned sequence length."""
    if arg_0.lrnIterationIdx < 100:
      arg_2 = 0.5
    else:
      arg_2 = 0.1

    arg_0.avgLearnedSeqLength = ((1.0 - arg_2) * arg_0.avgLearnedSeqLength +
                                (arg_2 * arg_1))


def Func(arg_0, arg_1, arg_2=True):
    """
    A utility method called from learnBacktrack. This will backtrack
    starting from the given startOffset in our prevLrnPatterns queue.

    It returns True if the backtrack was successful and we managed to get
    predictions all the way up to the current time step.

    If readOnly, then no segments are updated or modified, otherwise, all
    segment updates that belong to the given path are applied.

    This updates/modifies:

        - lrnActiveState['t']

    This trashes:

        - lrnPredictedState['t']
        - lrnPredictedState['t-1']
        - lrnActiveState['t-1']

    :param startOffset: Start offset within the prevLrnPatterns input history
    :param readOnly:
    :return: True if we managed to lock on to a sequence that started
                       earlier.
                       If False, we lost predictions somewhere along the way
                       leading up to the current time.
    """
    # How much input history have we accumulated?
    # The current input is always at the end of self._prevInfPatterns (at
    # index -1), but it is also evaluated as a potential starting point by
    # turning on it's start cells and seeing if it generates sufficient
    # predictions going forward.
    arg_3 = len(arg_0._prevLrnPatterns)

    # This is an easy to use label for the current time step
    arg_4 = arg_3 - 1

    # Clear out any old segment updates. learnPhase2() adds to the segment
    # updates if we're not readOnly
    if not arg_2:
      arg_0.segmentUpdates = {}

    # Status message
    if arg_0.verbosity >= 3:
      if arg_2:
        print (
            "Trying to lock-on using startCell state from %d steps ago:" % (
                arg_3 - 1 - arg_1),
            arg_0._prevLrnPatterns[arg_1])
      else:
        print (
            "Locking on using startCell state from %d steps ago:" % (
                arg_3 - 1 - arg_1),
            arg_0._prevLrnPatterns[arg_1])

    # Play through up to the current time step
    arg_6 = True
    for arg_7 in range(arg_1, arg_3):

      # Copy predicted and active states into t-1
      arg_0.lrnPredictedState['t-1'][:, :] = arg_0.lrnPredictedState['t'][:, :]
      arg_0.lrnActiveState['t-1'][:, :] = arg_0.lrnActiveState['t'][:, :]

      # Get the input pattern
      arg_10 = arg_0._prevLrnPatterns[arg_7]

      # Apply segment updates from the last set of predictions
      if not arg_2:
        arg_0._processSegmentUpdates(arg_10)

      # Phase 1:
      # Compute activeState[t] given bottom-up and predictedState[t-1]
      if arg_7 == arg_1:
        arg_0.lrnActiveState['t'].fill(0)
        for arg_11 in arg_10:
          arg_0.lrnActiveState['t'][arg_11, 0] = 1
        arg_6 = True
      else:
        # Uses lrnActiveState['t-1'] and lrnPredictedState['t-1']
        # computes lrnActiveState['t']
        arg_6 = arg_0._learnPhase1(arg_10, arg_2=arg_2)

      # Break out immediately if we fell out of sequence or reached the current
      # time step
      if not arg_6 or arg_7 == arg_4:
        break

      # Phase 2:
      # Computes predictedState['t'] given activeState['t'] and also queues
      # up active segments into self.segmentUpdates, unless this is readOnly
      if arg_0.verbosity >= 3:
        print "  backtrack: computing predictions from ", arg_10
      arg_0._learnPhase2(arg_2=arg_2)

    # Return whether or not this starting point was valid
    return arg_6


def Func(arg_0):
    """
    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']

    """
    # How much input history have we accumulated?
    # The current input is always at the end of self._prevInfPatterns (at
    # index -1), and is not a valid startingOffset to evaluate.
    arg_1 = len(arg_0._prevLrnPatterns) - 1
    if arg_1 <= 0:
      if arg_0.verbosity >= 3:
        print "lrnBacktrack: No available history to backtrack from"
      return False

    # We will record which previous input patterns did not generate predictions
    # up to the current time step and remove all the ones at the head of the
    # input history queue so that we don't waste time evaluating them again at
    # a later time step.
    arg_2 = []

    # Let's go back in time and replay the recent inputs from start cells and
    # see if we can lock onto this current set of inputs that way.
    #
    # Start the farthest back and work our way forward. For each starting point,
    # See if firing on start cells at that point would predict the current
    # input.
    #
    # We want to pick the point farthest in the past that has continuity
    # up to the current time step
    arg_3 = False
    for arg_4 in range(0, arg_1):
      # Can we backtrack from startOffset?
      arg_3 = arg_0.FuncFrom(arg_4, readOnly=True)

      # Done playing through the sequence from starting point startOffset
      # Break out as soon as we find a good path
      if arg_3:
        break

      # Take this bad starting point out of our input history so we don't
      # try it again later.
      arg_2.append(arg_4)

    # If we failed to lock on at any starting point, return failure. The caller
    # will start over again on start cells
    if not arg_3:
      if arg_0.verbosity >= 3:
        print ("Failed to lock on. Falling back to start cells on current "
               "time step.")
      # Nothing in our input history was a valid starting point, so get rid
      #  of it so we don't try any of them again at a later iteration
      arg_0._prevLrnPatterns = []
      return False

    # We did find a valid starting point in the past. Now, we need to
    # re-enforce all segments that became active when following this path.
    if arg_0.verbosity >= 3:
      print ("Discovered path to current input by using start cells from %d "
             "steps ago:" % (arg_1 - arg_4),
             arg_0._prevLrnPatterns[arg_4])

    arg_0.FuncFrom(arg_4, readOnly=False)

    # Remove any useless patterns at the head of the input pattern history
    # queue.
    for arg_6 in range(arg_1):
      if arg_6 in arg_2 or arg_6 <= arg_4:
        if arg_0.verbosity >= 3:
          print ("Removing useless pattern from history:",
                 arg_0._prevLrnPatterns[0])
        arg_0._prevLrnPatterns.pop(0)
      else:
        break

    return arg_1 - arg_4


def Func(arg_0, arg_1, arg_2=False):
    """
    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']
    """
    # Save previous active state and start out on a clean slate
    arg_0.lrnActiveState['t'].fill(0)

    # For each column, turn on the predicted cell. There will always be at most
    # one predicted cell per column
    arg_3 = 0
    for arg_4 in arg_1:
      arg_5 = numpy.where(arg_0.lrnPredictedState['t-1'][arg_4] == 1)[0]
      arg_6 = len(arg_5)
      assert arg_6 <= 1

      # If we have a predicted cell, turn it on. The segment's posActivation
      # count will have already been incremented by processSegmentUpdates
      if arg_6 == 1:
        arg_7 = arg_5[0]
        arg_0.lrnActiveState['t'][arg_4, arg_7] = 1
        continue

      arg_3 += 1
      if arg_2:
        continue

      # If no predicted cell, pick the closest matching one to reinforce, or
      # if none exists, create a new segment on a cell in that column
      arg_7, arg_9, arg_10 = arg_0._getBestMatchingCell(
          arg_4, arg_0.lrnActiveState['t-1'], arg_0.minThreshold)
      if arg_9 is not None and arg_9.isSequenceSegment():
        if arg_0.verbosity >= 4:
          print "Learn branch 0, found segment match. Learning on col=", arg_4
        arg_0.lrnActiveState['t'][arg_4, arg_7] = 1
        arg_11 = arg_0._getSegmentActiveSynapses(
            arg_4, arg_7, arg_9, arg_0.lrnActiveState['t-1'], newSynapses = True)
        arg_9.totalActivations += 1
        # This will update the permanences, posActivationsCount, and the
        # lastActiveIteration (age).
        arg_12 = arg_0._adaptSegment(arg_11)
        if arg_12:
          arg_0._trimSegmentsInCell(arg_4, arg_7, [arg_9], minPermanence = 0.00001,
                                   minNumSyns = 0)

      # If no close match exists, create a new one
      else:
        # Choose a cell in this column to add a new segment to
        arg_7 = arg_0._getCellForNewSegment(arg_4)
        if (arg_0.verbosity >= 4):
          print "Learn branch 1, no match. Learning on col=", arg_4,
          print ", newCellIdxInCol=", arg_7
        arg_0.lrnActiveState['t'][arg_4, arg_7] = 1
        arg_11 = arg_0._getSegmentActiveSynapses(
            arg_4, arg_7, None, arg_0.lrnActiveState['t-1'], newSynapses=True)
        arg_11.sequenceSegment = True # Make it a sequence segment
        arg_0._adaptSegment(arg_11)  # No need to check whether perm reached 0

    # Determine if we are out of sequence or not and reset our PAM counter
    # if we are in sequence
    arg_14 = len(arg_1)
    if arg_3 < arg_14 / 2:
      return True   # in sequence
    else:
      return False


def Func(arg_0, arg_1=False):
    """
    Compute the predicted segments given the current set of active cells.

    :param readOnly       True if being called from backtracking logic.
                          This tells us not to increment any segment
                          duty cycles or queue up any updates.

    This computes the lrnPredictedState['t'] and queues up any segments that
    became active (and the list of active synapses for each segment) into
    the segmentUpdates queue

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

    This modifies:
        - @ref lrnPredictedState['t']
        - @ref segmentUpdates
    """
    # Clear out predicted state to start with
    arg_0.lrnPredictedState['t'].fill(0)

    # Compute new predicted state. When computing predictions for
    # phase 2, we predict at  most one cell per column (the one with the best
    # matching segment).
    for arg_2 in xrange(arg_0.numberOfCols):

      # Is there a cell predicted to turn on in this column?
      arg_3, arg_4, arg_5 = arg_0._getBestMatchingCell(
          arg_2, arg_0.lrnActiveState['t'], minThreshold = arg_0.activationThreshold)
      if arg_3 is None:
        continue

      # Turn on the predicted state for the best matching cell and queue
      #  the pertinent segment up for an update, which will get processed if
      #  the cell receives bottom up in the future.
      arg_0.lrnPredictedState['t'][arg_2, arg_3] = 1
      if arg_1:
        continue

      # Queue up this segment for updating
      arg_7 = arg_0._getSegmentActiveSynapses(
          arg_2, arg_3, arg_4, activeState=arg_0.lrnActiveState['t'],
          newSynapses=(arg_5 < arg_0.newSynapseCount))

      arg_4.totalActivations += 1    # increment totalActivations
      arg_0._addToSegmentUpdates(arg_2, arg_3, arg_7)

      if arg_0.doPooling:
        # creates a new pooling segment if no best matching segment found
        # sum(all synapses) >= minThreshold, "weak" activation
        arg_8 = arg_0._getBestMatchingSegment(arg_2, arg_3,
                                                   arg_0.lrnActiveState['t-1'])
        arg_7 = arg_0._getSegmentActiveSynapses(arg_2, arg_3, arg_8,
                                                   arg_0.lrnActiveState['t-1'], newSynapses=True)
        arg_0._addToSegmentUpdates(arg_2, arg_3, arg_7)