def testOverlap(self):
        """Create a simple network to test the region."""

        rawParams = {"outputWidth": 8 * 2048}
        net = Network()
        rawSensor = net.addRegion("raw", "py.RawSensor", json.dumps(rawParams))
        l2c = net.addRegion("L2", "py.ColumnPoolerRegion", "")
        net.link("raw", "L2", "UniformLink", "")

        self.assertEqual(rawSensor.getParameterUInt32("outputWidth"), l2c.getParameterUInt32("inputWidth"), "Incorrect outputWidth parameter")

        rawSensor.executeCommand('addDataToQueue', [2, 4, 6], 0, 42)
        rawSensor.executeCommand('addDataToQueue', [2, 42, 1023], 1, 43)
        rawSensor.executeCommand('addDataToQueue', [18, 19, 20], 0, 44)

        # Run the network and check outputs are as expected
        net.run(3)
Example #2
0
def _createNetwork(inverseReadoutResolution, anchorInputSize, dualPhase=False):
    """
    Create a simple network connecting sensor and motor inputs to the location
    region. Use :meth:`RawSensor.addDataToQueue` to add sensor input and growth
    candidates. Use :meth:`RawValues.addDataToQueue` to add motor input.
    ::
                        +----------+
    [   sensor*   ] --> |          | --> [     activeCells        ]
    [ candidates* ] --> | location | --> [    learnableCells      ]
    [    motor    ] --> |          | --> [ sensoryAssociatedCells ]
                        +----------+

    :param inverseReadoutResolution:
        Specifies the diameter of the circle of phases in the rhombus encoded by a
        bump.
    :type inverseReadoutResolution: int

    :type anchorInputSize: int
    :param anchorInputSize:
        The number of input bits in the anchor input.

    .. note::
        (*) This function will only add the 'sensor' and 'candidates' regions when
        'anchorInputSize' is greater than zero. This is useful if you would like to
        compute locations ignoring sensor input

    .. seealso::
         - :py:func:`htmresearch.frameworks.location.path_integration_union_narrowing.createRatModuleFromReadoutResolution`

    """
    net = Network()

    # Create simple region to pass motor commands as displacement vectors (dx, dy)
    net.addRegion("motor", "py.RawValues", json.dumps({"outputWidth": 2}))

    if anchorInputSize > 0:
        # Create simple region to pass growth candidates
        net.addRegion("candidates", "py.RawSensor",
                      json.dumps({"outputWidth": anchorInputSize}))

        # Create simple region to pass sensor input
        net.addRegion("sensor", "py.RawSensor",
                      json.dumps({"outputWidth": anchorInputSize}))

    # Initialize region with 5 modules varying scale by sqrt(2) and 4 different
    # random orientations for each scale
    scale = []
    orientation = []
    for i in range(5):
        for _ in range(4):
            angle = np.radians(random.gauss(7.5, 7.5))
            orientation.append(random.choice([angle, -angle]))
            scale.append(10.0 * (math.sqrt(2)**i))

    # Create location region
    params = computeRatModuleParametersFromReadoutResolution(
        inverseReadoutResolution)
    params.update({
        "moduleCount": len(scale),
        "scale": scale,
        "orientation": orientation,
        "anchorInputSize": anchorInputSize,
        "activationThreshold": 8,
        "initialPermanence": 1.0,
        "connectedPermanence": 0.5,
        "learningThreshold": 8,
        "sampleSize": 10,
        "permanenceIncrement": 0.1,
        "permanenceDecrement": 0.0,
        "dualPhase": dualPhase,
        "bumpOverlapMethod": "probabilistic"
    })
    net.addRegion("location", "py.GridCellLocationRegion", json.dumps(params))

    if anchorInputSize > 0:
        # Link sensor
        net.link("sensor",
                 "location",
                 "UniformLink",
                 "",
                 srcOutput="dataOut",
                 destInput="anchorInput")
        net.link("sensor",
                 "location",
                 "UniformLink",
                 "",
                 srcOutput="resetOut",
                 destInput="resetIn")
        net.link("candidates",
                 "location",
                 "UniformLink",
                 "",
                 srcOutput="dataOut",
                 destInput="anchorGrowthCandidates")

    # Link motor input
    net.link("motor",
             "location",
             "UniformLink",
             "",
             srcOutput="dataOut",
             destInput="displacement")

    # Initialize network objects
    net.initialize()

    return net
Example #3
0
def main(parameters=default_parameters, argv=None, verbose=True):
    if verbose:
        import pprint
        print("Parameters:")
        pprint.pprint(parameters, indent=4)
        print("")

    # Read the input file.
    records = []
    with open(_INPUT_FILE_PATH, "r") as fin:
        reader = csv.reader(fin)
        headers = next(reader)
        next(reader)
        next(reader)
        for record in reader:
            records.append(record)

    net = Network()
    # Make the Encoders.  These will convert input data into binary representations.
    dateEncoderRegion = net.addRegion(
        'dateEncoder', 'DateEncoderRegion',
        str(
            dict(timeOfDay_width=parameters["enc"]["time"]["timeOfDay"][0],
                 timeOfDay_radius=parameters["enc"]["time"]["timeOfDay"][1],
                 weekend_width=parameters["enc"]["time"]["weekend"])))

    valueEncoderRegion = net.addRegion(
        'valueEncoder', 'RDSEEncoderRegion',
        str(
            dict(size=parameters["enc"]["value"]["size"],
                 sparsity=parameters["enc"]["value"]["sparsity"],
                 resolution=parameters["enc"]["value"]["resolution"])))

    # Make the HTM.  SpatialPooler & TemporalMemory & associated tools.
    spParams = parameters["sp"]
    spRegion = net.addRegion(
        'sp',
        'SPRegion',
        str(
            dict(
                columnCount=spParams['columnCount'],
                potentialPct=spParams["potentialPct"],
                potentialRadius=0,  # 0 is auto assign as inputWith
                globalInhibition=True,
                localAreaDensity=spParams["localAreaDensity"],
                synPermInactiveDec=spParams["synPermInactiveDec"],
                synPermActiveInc=spParams["synPermActiveInc"],
                synPermConnected=spParams["synPermConnected"],
                boostStrength=spParams["boostStrength"],
                wrapAround=True)))

    tmParams = parameters["tm"]
    tmRegion = net.addRegion(
        'tm', 'TMRegion',
        str(
            dict(columnCount=spParams['columnCount'],
                 cellsPerColumn=tmParams["cellsPerColumn"],
                 activationThreshold=tmParams["activationThreshold"],
                 initialPermanence=tmParams["initialPerm"],
                 connectedPermanence=spParams["synPermConnected"],
                 minThreshold=tmParams["minThreshold"],
                 maxNewSynapseCount=tmParams["newSynapseCount"],
                 permanenceIncrement=tmParams["permanenceInc"],
                 permanenceDecrement=tmParams["permanenceDec"],
                 predictedSegmentDecrement=0.0,
                 maxSegmentsPerCell=tmParams["maxSegmentsPerCell"],
                 maxSynapsesPerSegment=tmParams["maxSynapsesPerSegment"])))

    net.link('dateEncoder', 'sp', '', '', 'encoded', 'bottomUpIn')
    net.link('valueEncoder', 'sp', '', '', 'encoded', 'bottomUpIn')
    net.link('sp', 'tm', '', '', 'bottomUpOut', 'bottomUpIn')

    net.initialize()

    # Iterate through every datum in the dataset, record the inputs & outputs.
    inputs = []
    anomaly = []

    for count, record in enumerate(records):

        # Convert date string into Python date object.
        dateString = datetime.datetime.strptime(record[0], "%m/%d/%y %H:%M")
        # Convert data value string into float.
        consumption = float(record[1])
        inputs.append(consumption)

        # Call the encoders to create bit representations for each value.  These are SDR objects.
        dateEncoderRegion.setParameterInt64('sensedTime',
                                            int(dateString.timestamp()))
        valueEncoderRegion.setParameterReal64('sensedValue', consumption)

        net.run(1)
        anomaly.append(np.array(tmRegion.getOutputArray("anomaly"))[0])

    try:
        import matplotlib.pyplot as plt
    except:
        print("WARNING: failed to import matplotlib, plots cannot be shown.")
        return

    plt.title("Anomaly Score")
    plt.xlabel("Time")
    plt.ylabel("Power Consumption")
    inputs = np.array(inputs) / max(inputs)
    plt.plot(
        np.arange(len(inputs)),
        inputs,
        'red',
        np.arange(len(inputs)),
        anomaly,
        'blue',
    )
    plt.legend(labels=('Input', 'Anomaly Score'))
    plt.show()
    return