INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Build the additional specs in three groups ( for the inspector ) | def _getAdditionalSpecs(temporalImp, kwargs={}):
"""Build the additional specs in three groups (for the inspector)
Use the type of the default argument to set the Spec type, defaulting
to 'Byte' for None and complex types
Determines the spatial parameters based on the selected implementation.
It defaults to... |
Overrides: meth: ~nupic. bindings. regions. PyRegion. initialize. | def initialize(self):
"""
Overrides :meth:`~nupic.bindings.regions.PyRegion.initialize`.
"""
# Allocate appropriate temporal memory object
# Retrieve the necessary extra arguments that were handled automatically
autoArgs = dict((name, getattr(self, name))
for name in self._te... |
Run one iteration of TMRegion s compute | def _compute(self, inputs, outputs):
"""
Run one iteration of TMRegion's compute
"""
#if self.topDownMode and (not 'topDownIn' in inputs):
# raise RuntimeError("The input topDownIn must be linked in if "
# "topDownMode is True")
if self._tfdr is None:
raise Runtime... |
Doesn t include the spatial temporal and other parameters | def getBaseSpec(cls):
"""
Doesn't include the spatial, temporal and other parameters
:returns: (dict) the base Spec for TMRegion.
"""
spec = dict(
description=TMRegion.__doc__,
singleNodeOnly=True,
inputs=dict(
bottomUpIn=dict(
description="""The input signal, co... |
Overrides: meth: ~nupic. bindings. regions. PyRegion. PyRegion. getSpec. | def getSpec(cls):
"""
Overrides :meth:`~nupic.bindings.regions.PyRegion.PyRegion.getSpec`.
The parameters collection is constructed based on the parameters specified
by the various components (spatialSpec, temporalSpec and otherSpec)
"""
spec = cls.getBaseSpec()
t, o = _getAdditionalSpecs(t... |
Overrides: meth: ~nupic. bindings. regions. PyRegion. PyRegion. getParameter. | def getParameter(self, parameterName, index=-1):
"""
Overrides :meth:`~nupic.bindings.regions.PyRegion.PyRegion.getParameter`.
Get the value of a parameter. Most parameters are handled automatically by
:class:`~nupic.bindings.regions.PyRegion.PyRegion`'s parameter get mechanism. The
ones that need... |
Overrides: meth: ~nupic. bindings. regions. PyRegion. PyRegion. setParameter. | def setParameter(self, parameterName, index, parameterValue):
"""
Overrides :meth:`~nupic.bindings.regions.PyRegion.PyRegion.setParameter`.
"""
if parameterName in self._temporalArgNames:
setattr(self._tfdr, parameterName, parameterValue)
elif parameterName == "logPathOutput":
self.logP... |
Perform an internal optimization step that speeds up inference if we know learning will not be performed anymore. This call may for example remove all potential inputs to each column. | def finishLearning(self):
"""
Perform an internal optimization step that speeds up inference if we know
learning will not be performed anymore. This call may, for example, remove
all potential inputs to each column.
"""
if self._tfdr is None:
raise RuntimeError("Temporal memory has not bee... |
Overrides: meth: ~nupic. bindings. regions. PyRegion. PyRegion. writeToProto. | def writeToProto(self, proto):
"""
Overrides :meth:`~nupic.bindings.regions.PyRegion.PyRegion.writeToProto`.
Write state to proto object.
:param proto: TMRegionProto capnproto object
"""
proto.temporalImp = self.temporalImp
proto.columnCount = self.columnCount
proto.inputWidth = self.i... |
Overrides: meth: ~nupic. bindings. regions. PyRegion. PyRegion. readFromProto. | def readFromProto(cls, proto):
"""
Overrides :meth:`~nupic.bindings.regions.PyRegion.PyRegion.readFromProto`.
Read state from proto object.
:param proto: TMRegionProto capnproto object
"""
instance = cls(proto.columnCount, proto.inputWidth, proto.cellsPerColumn)
instance.temporalImp = pro... |
Overrides: meth: ~nupic. bindings. regions. PyRegion. PyRegion. getOutputElementCount. | def getOutputElementCount(self, name):
"""
Overrides :meth:`~nupic.bindings.regions.PyRegion.PyRegion.getOutputElementCount`.
"""
if name == 'bottomUpOut':
return self.outputWidth
elif name == 'topDownOut':
return self.columnCount
elif name == 'lrnActiveStateT':
return self.out... |
Computes the raw anomaly score. | def computeRawAnomalyScore(activeColumns, prevPredictedColumns):
"""Computes the raw anomaly score.
The raw anomaly score is the fraction of active columns not predicted.
:param activeColumns: array of active column indices
:param prevPredictedColumns: array of columns indices predicted in prev step
:return... |
Compute the anomaly score as the percent of active columns not predicted. | def compute(self, activeColumns, predictedColumns,
inputValue=None, timestamp=None):
"""Compute the anomaly score as the percent of active columns not predicted.
:param activeColumns: array of active column indices
:param predictedColumns: array of columns indices predicted in this step
... |
Adds a graph to the plot s figure. | def addGraph(self, data, position=111, xlabel=None, ylabel=None):
""" Adds a graph to the plot's figure.
@param data See matplotlib.Axes.plot documentation.
@param position A 3-digit number. The first two digits define a 2D grid
where subplots may be added. The final digit specifies the nth gri... |
Adds a histogram to the plot s figure. | def addHistogram(self, data, position=111, xlabel=None, ylabel=None,
bins=None):
""" Adds a histogram to the plot's figure.
@param data See matplotlib.Axes.hist documentation.
@param position A 3-digit number. The first two digits define a 2D grid
where subplots may be added.... |
Adds an image to the plot s figure. | def add2DArray(self, data, position=111, xlabel=None, ylabel=None, cmap=None,
aspect="auto", interpolation="nearest", name=None):
""" Adds an image to the plot's figure.
@param data a 2D array. See matplotlib.Axes.imshow documentation.
@param position A 3-digit number. The first two digits... |
Adds a subplot to the plot s figure at specified position. | def _addBase(self, position, xlabel=None, ylabel=None):
""" Adds a subplot to the plot's figure at specified position.
@param position A 3-digit number. The first two digits define a 2D grid
where subplots may be added. The final digit specifies the nth grid
location for the added subpl... |
Generate a temporal dataset containing sequences that overlap one or more elements with other sequences. Parameters: ---------------------------------------------------- filename: name of the file to produce including extension. It will be created in a datasets sub - directory within the directory containing this scrip... | def _generateOverlapping(filename="overlap.csv", numSequences=2, elementsPerSeq=3,
numRepeats=10, hub=[0,1], hubOffset=1, resets=False):
""" Generate a temporal dataset containing sequences that overlap one or more
elements with other sequences.
Parameters:
--------------------------... |
Generate the initial first order and second order transition probabilities for probability0. For this model we generate the following set of sequences:. 1. 75 0 ---- 1 ----- 2 \ \ \ \. 25 \ \ ----- 3 \ \. 9. 5 \ --- 4 --------- 2 \ \. 5 \ --------- 3 Parameters: ---------------------------------------------------------... | def _generateFirstOrder0():
""" Generate the initial, first order, and second order transition
probabilities for 'probability0'. For this model, we generate the following
set of sequences:
.1 .75
0----1-----2
\ \
\ \ .25
\ \-----3
\
\ .9 .5
\--- 4-----... |
Generate a set of records reflecting a set of probabilities. Parameters: ---------------------------------------------------------------- filename: name of. csv file to generate numRecords: number of records to generate categoryList: list of category names initProb: Initial probability for each category. This is a vect... | def _generateFileFromProb(filename, numRecords, categoryList, initProb,
firstOrderProb, secondOrderProb, seqLen, numNoise=0, resetsEvery=None):
""" Generate a set of records reflecting a set of probabilities.
Parameters:
----------------------------------------------------------------
filename: ... |
Get version from local file. | def getVersion():
"""
Get version from local file.
"""
with open(os.path.join(REPO_DIR, "VERSION"), "r") as versionFile:
return versionFile.read().strip() |
Make an attempt to determine if a pre - release version of nupic. bindings is installed already. | def nupicBindingsPrereleaseInstalled():
"""
Make an attempt to determine if a pre-release version of nupic.bindings is
installed already.
@return: boolean
"""
try:
nupicDistribution = pkg_resources.get_distribution("nupic.bindings")
if pkg_resources.parse_version(nupicDistribution.version).is_prere... |
Read the requirements. txt file and parse into requirements for setup s install_requirements option. | def findRequirements():
"""
Read the requirements.txt file and parse into requirements for setup's
install_requirements option.
"""
requirementsPath = os.path.join(REPO_DIR, "requirements.txt")
requirements = parse_file(requirementsPath)
if nupicBindingsPrereleaseInstalled():
# User has a pre-release... |
Parses and validates the -- description option args and executes the request | def _handleDescriptionOption(cmdArgStr, outDir, usageStr, hsVersion,
claDescriptionTemplateFile):
"""
Parses and validates the --description option args and executes the
request
Parameters:
-----------------------------------------------------------------------
cmdArgStr: JSON... |
Parses and validates the -- descriptionFromFile option and executes the request | def _handleDescriptionFromFileOption(filename, outDir, usageStr, hsVersion,
claDescriptionTemplateFile):
"""
Parses and validates the --descriptionFromFile option and executes the
request
Parameters:
-----------------------------------------------------------------------
filena... |
Return ( isInt intValue ) for a given floating point number. | def _isInt(x, precision = 0.0001):
"""
Return (isInt, intValue) for a given floating point number.
Parameters:
----------------------------------------------------------------------
x: floating point number to evaluate
precision: desired precision
retval: (isInt, intValue)
isInt: True if x... |
Indent all lines in the given string | def _indentLines(str, indentLevels = 1, indentFirstLine=True):
""" Indent all lines in the given string
str: input string
indentLevels: number of levels of indentation to apply
indentFirstLine: if False, the 1st line will not be indented
Returns: The result string with all lines indented
"""... |
Generates the string representation of a MetricSpec object and returns the metric key associated with the metric. | def _generateMetricSpecString(inferenceElement, metric,
params=None, field=None,
returnLabel=False):
""" Generates the string representation of a MetricSpec object, and returns
the metric key associated with the metric.
Parameters:
------------------... |
Generates a file by applying token replacements to the given template file | def _generateFileFromTemplates(templateFileNames, outputFilePath,
replacementDict):
""" Generates a file by applying token replacements to the given template
file
templateFileName:
A list of template file names; these files are assumed to be in
th... |
Return a list of possible encoder parameter combinations for the given field and the default aggregation function to use. Each parameter combination is a dict defining the parameters for the encoder. Here is an example return value for the encoderChoicesList: | def _generateEncoderChoicesV1(fieldInfo):
""" Return a list of possible encoder parameter combinations for the given
field and the default aggregation function to use. Each parameter combination
is a dict defining the parameters for the encoder. Here is an example
return value for the encoderChoicesList:
[
... |
Generate and return the following encoder related substitution variables: | def _generateEncoderStringsV1(includedFields):
""" Generate and return the following encoder related substitution variables:
encoderSpecsStr:
For the base description file, this string defines the default
encoding dicts for each encoder. For example:
'__gym_encoder' : { 'fieldname': 'gym',
... |
Generate the string that defines the permutations to apply for a given encoder. | def _generatePermEncoderStr(options, encoderDict):
""" Generate the string that defines the permutations to apply for a given
encoder.
Parameters:
-----------------------------------------------------------------------
options: experiment params
encoderDict: the encoder dict, which gets placed into the des... |
Generate and return the following encoder related substitution variables: | def _generateEncoderStringsV2(includedFields, options):
""" Generate and return the following encoder related substitution variables:
encoderSpecsStr:
For the base description file, this string defines the default
encoding dicts for each encoder. For example:
__gym_encoder = { 'fieldname': 'gym... |
Handle legacy options ( TEMPORARY ) | def _handleJAVAParameters(options):
""" Handle legacy options (TEMPORARY) """
# Find the correct InferenceType for the Model
if 'inferenceType' not in options:
prediction = options.get('prediction', {InferenceType.TemporalNextStep:
{'optimize':True}})
inferen... |
Checks to see if property is specified in options. If not reads the default value from the schema | def _getPropertyValue(schema, propertyName, options):
"""Checks to see if property is specified in 'options'. If not, reads the
default value from the schema"""
if propertyName not in options:
paramsSchema = schema['properties'][propertyName]
if 'default' in paramsSchema:
options[propertyName] = pa... |
Returns the experiment description schema. This implementation loads it in from file experimentDescriptionSchema. json. | def _getExperimentDescriptionSchema():
"""
Returns the experiment description schema. This implementation loads it in
from file experimentDescriptionSchema.json.
Parameters:
--------------------------------------------------------------------------
Returns: returns a dict representing the experiment des... |
Executes the -- description option which includes: | def _generateExperiment(options, outputDirPath, hsVersion,
claDescriptionTemplateFile):
""" Executes the --description option, which includes:
1. Perform provider compatibility checks
2. Preprocess the training and testing datasets (filter, join providers)
3. If test da... |
Generate the token substitution for metrics related fields. This includes: \ $METRICS \ $LOGGED_METRICS \ $PERM_OPTIMIZE_SETTING | def _generateMetricsSubstitutions(options, tokenReplacements):
"""Generate the token substitution for metrics related fields.
This includes:
\$METRICS
\$LOGGED_METRICS
\$PERM_OPTIMIZE_SETTING
"""
# -----------------------------------------------------------------------
#
options['loggedMetrics']... |
Generates the Metrics for a given InferenceType | def _generateMetricSpecs(options):
""" Generates the Metrics for a given InferenceType
Parameters:
-------------------------------------------------------------------------
options: ExpGenerator options
retval: (metricsList, optimizeMetricLabel)
metricsList: list of metric string names
... |
Generates the non - default metrics specified by the expGenerator params | def _generateExtraMetricSpecs(options):
"""Generates the non-default metrics specified by the expGenerator params """
_metricSpecSchema = {'properties': {}}
results = []
for metric in options['metrics']:
for propertyName in _metricSpecSchema['properties'].keys():
_getPropertyValue(_metricSpecSchema,... |
Gets the predicted field and it s datatype from the options dictionary | def _getPredictedField(options):
""" Gets the predicted field and it's datatype from the options dictionary
Returns: (predictedFieldName, predictedFieldType)
"""
if not options['inferenceArgs'] or \
not options['inferenceArgs']['predictedField']:
return None, None
predictedField = options['inferen... |
Generates the token substitutions related to the predicted field and the supplemental arguments for prediction | def _generateInferenceArgs(options, tokenReplacements):
""" Generates the token substitutions related to the predicted field
and the supplemental arguments for prediction
"""
inferenceType = options['inferenceType']
optionInferenceArgs = options.get('inferenceArgs', None)
resultInferenceArgs = {}
predicte... |
Parses validates and executes command - line options ; | def expGenerator(args):
""" Parses, validates, and executes command-line options;
On success: Performs requested operation and exits program normally
On Error: Dumps exception/error info in JSON format to stdout and exits the
program with non-zero status.
"""
# -----------------------------... |
Parses a textual datetime format and return a Python datetime object. | def parseTimestamp(s):
"""
Parses a textual datetime format and return a Python datetime object.
The supported format is: ``yyyy-mm-dd h:m:s.ms``
The time component is optional.
- hours are 00..23 (no AM/PM)
- minutes are 00..59
- seconds are 00..59
- micro-seconds are 000000..999999
:param s: (st... |
String to boolean | def parseBool(s):
"""
String to boolean
:param s: (string)
:return: (bool)
"""
l = s.lower()
if l in ("true", "t", "1"):
return True
if l in ("false", "f", "0"):
return False
raise Exception("Unable to convert string '%s' to a boolean value" % s) |
Escape commas tabs newlines and dashes in a string | def escape(s):
"""
Escape commas, tabs, newlines and dashes in a string
Commas are encoded as tabs.
:param s: (string) to escape
:returns: (string) escaped string
"""
if s is None:
return ''
assert isinstance(s, basestring), \
"expected %s but got %s; value=%s" % (basestring, type(s), s)
... |
Unescapes a string that may contain commas tabs newlines and dashes | def unescape(s):
"""
Unescapes a string that may contain commas, tabs, newlines and dashes
Commas are decoded from tabs.
:param s: (string) to unescape
:returns: (string) unescaped string
"""
assert isinstance(s, basestring)
s = s.replace('\t', ',')
s = s.replace('\\,', ',')
s = s.replace('\\n', '... |
Parses a string containing only 0 s and 1 s and return a Python list object. | def parseSdr(s):
"""
Parses a string containing only 0's and 1's and return a Python list object.
:param s: (string) string to parse
:returns: (list) SDR out
"""
assert isinstance(s, basestring)
sdr = [int(c) for c in s if c in ("0", "1")]
if len(sdr) != len(s):
raise ValueError("The provided strin... |
Parse a string of space - separated numbers returning a Python list. | def parseStringList(s):
"""
Parse a string of space-separated numbers, returning a Python list.
:param s: (string) to parse
:returns: (list) binary SDR
"""
assert isinstance(s, basestring)
return [int(i) for i in s.split()] |
Translate an index into coordinates using the given coordinate system. | def coordinatesFromIndex(index, dimensions):
"""
Translate an index into coordinates, using the given coordinate system.
Similar to ``numpy.unravel_index``.
:param index: (int) The index of the point. The coordinates are expressed as a
single index by using the dimensions as a mixed radix definition... |
Translate coordinates into an index using the given coordinate system. | def indexFromCoordinates(coordinates, dimensions):
"""
Translate coordinates into an index, using the given coordinate system.
Similar to ``numpy.ravel_multi_index``.
:param coordinates: (list of ints) A list of coordinates of length
``dimensions.size()``.
:param dimensions: (list of ints) The co... |
Get the points in the neighborhood of a point. | def neighborhood(centerIndex, radius, dimensions):
"""
Get the points in the neighborhood of a point.
A point's neighborhood is the n-dimensional hypercube with sides ranging
[center - radius, center + radius], inclusive. For example, if there are two
dimensions and the radius is 3, the neighborhood is 6x6. ... |
See nupic. encoders. base. Encoder for more information. | def encodeIntoArray(self, inputData, output):
"""
See `nupic.encoders.base.Encoder` for more information.
@param inputData (tuple) Contains coordinate (numpy.array, N-dimensional
integer coordinate) and radius (int)
@param output (numpy.array) Stores encoded SDR in this num... |
Returns coordinates around given coordinate within given radius. Includes given coordinate. | def _neighbors(coordinate, radius):
"""
Returns coordinates around given coordinate, within given radius.
Includes given coordinate.
@param coordinate (numpy.array) N-dimensional integer coordinate
@param radius (int) Radius around `coordinate`
@return (numpy.array) List of coordinates
"""... |
Returns the top W coordinates by order. | def _topWCoordinates(cls, coordinates, w):
"""
Returns the top W coordinates by order.
@param coordinates (numpy.array) A 2D numpy array, where each element
is a coordinate
@param w (int) Number of top coordinates to return
@return (numpy.array) A subset of `coo... |
Hash a coordinate to a 64 bit integer. | def _hashCoordinate(coordinate):
"""Hash a coordinate to a 64 bit integer."""
coordinateStr = ",".join(str(v) for v in coordinate)
# Compute the hash and convert to 64 bit int.
hash = int(int(hashlib.md5(coordinateStr).hexdigest(), 16) % (2 ** 64))
return hash |
Returns the order for a coordinate. | def _orderForCoordinate(cls, coordinate):
"""
Returns the order for a coordinate.
@param coordinate (numpy.array) Coordinate
@return (float) A value in the interval [0, 1), representing the
order of the coordinate
"""
seed = cls._hashCoordinate(coordinate)
rng = Random(s... |
Maps the coordinate to a bit in the SDR. | def _bitForCoordinate(cls, coordinate, n):
"""
Maps the coordinate to a bit in the SDR.
@param coordinate (numpy.array) Coordinate
@param n (int) The number of available bits in the SDR
@return (int) The index to a bit in the SDR
"""
seed = cls._hashCoordinate(coordinate)
rng = Random(s... |
Function for running binary search on a sorted list. | def binSearch(arr, val):
"""
Function for running binary search on a sorted list.
:param arr: (list) a sorted list of integers to search
:param val: (int) a integer to search for in the sorted array
:returns: (int) the index of the element if it is found and -1 otherwise.
"""
i = bisect_left(arr, val)
... |
Adds a new segment on a cell. | def createSegment(self, cell):
"""
Adds a new segment on a cell.
:param cell: (int) Cell index
:returns: (int) New segment index
"""
cellData = self._cells[cell]
if len(self._freeFlatIdxs) > 0:
flatIdx = self._freeFlatIdxs.pop()
else:
flatIdx = self._nextFlatIdx
self... |
Destroys a segment. | def destroySegment(self, segment):
"""
Destroys a segment.
:param segment: (:class:`Segment`) representing the segment to be destroyed.
"""
# Remove the synapses from all data structures outside this Segment.
for synapse in segment._synapses:
self._removeSynapseFromPresynapticMap(synapse)... |
Creates a new synapse on a segment. | def createSynapse(self, segment, presynapticCell, permanence):
"""
Creates a new synapse on a segment.
:param segment: (:class:`Segment`) Segment object for synapse to be synapsed
to.
:param presynapticCell: (int) Source cell index.
:param permanence: (float) Initial permanence of syna... |
Destroys a synapse. | def destroySynapse(self, synapse):
"""
Destroys a synapse.
:param synapse: (:class:`Synapse`) synapse to destroy
"""
self._numSynapses -= 1
self._removeSynapseFromPresynapticMap(synapse)
synapse.segment._synapses.remove(synapse) |
Compute each segment s number of active synapses for a given input. In the returned lists a segment s active synapse count is stored at index segment. flatIdx. | def computeActivity(self, activePresynapticCells, connectedPermanence):
"""
Compute each segment's number of active synapses for a given input.
In the returned lists, a segment's active synapse count is stored at index
``segment.flatIdx``.
:param activePresynapticCells: (iter) Active cells.
:p... |
Returns the number of segments. | def numSegments(self, cell=None):
"""
Returns the number of segments.
:param cell: (int) Optional parameter to get the number of segments on a
cell.
:returns: (int) Number of segments on all cells if cell is not specified, or
on a specific specified cell
"""
if cell ... |
Return a numeric key for sorting this segment. This can be used with the python built - in sorted () function. | def segmentPositionSortKey(self, segment):
"""
Return a numeric key for sorting this segment. This can be used with the
python built-in ``sorted()`` function.
:param segment: (:class:`Segment`) within this :class:`Connections`
instance.
:returns: (float) A numeric key for sorting.
... |
Writes serialized data to proto object. | def write(self, proto):
"""
Writes serialized data to proto object.
:param proto: (DynamicStructBuilder) Proto object
"""
protoCells = proto.init('cells', self.numCells)
for i in xrange(self.numCells):
segments = self._cells[i]._segments
protoSegments = protoCells[i].init('segment... |
Reads deserialized data from proto object | def read(cls, proto):
"""
Reads deserialized data from proto object
:param proto: (DynamicStructBuilder) Proto object
:returns: (:class:`Connections`) instance
"""
#pylint: disable=W0212
protoCells = proto.cells
connections = cls(len(protoCells))
for cellIdx, protoCell in enumera... |
Retrieve the requested property as a string. If property does not exist then KeyError will be raised. | def getString(cls, prop):
""" Retrieve the requested property as a string. If property does not exist,
then KeyError will be raised.
:param prop: (string) name of the property
:raises: KeyError
:returns: (string) property value
"""
if cls._properties is None:
cls._readStdConfigFiles()... |
Retrieve the requested property and return it as a bool. If property does not exist then KeyError will be raised. If the property value is neither 0 nor 1 then ValueError will be raised | def getBool(cls, prop):
""" Retrieve the requested property and return it as a bool. If property
does not exist, then KeyError will be raised. If the property value is
neither 0 nor 1, then ValueError will be raised
:param prop: (string) name of the property
:raises: KeyError, ValueError
:retur... |
Set the value of the given configuration property. | def set(cls, prop, value):
""" Set the value of the given configuration property.
:param prop: (string) name of the property
:param value: (object) value to set
"""
if cls._properties is None:
cls._readStdConfigFiles()
cls._properties[prop] = str(value) |
Return a dict containing all of the configuration properties | def dict(cls):
""" Return a dict containing all of the configuration properties
:returns: (dict) containing all configuration properties.
"""
if cls._properties is None:
cls._readStdConfigFiles()
# Make a copy so we can update any current values obtained from environment
# variables
... |
Parse the given XML file and store all properties it describes. | def readConfigFile(cls, filename, path=None):
""" Parse the given XML file and store all properties it describes.
:param filename: (string) name of XML file to parse (no path)
:param path: (string) path of the XML file. If None, then use the standard
configuration search path.
"""
... |
Search the configuration path ( specified via the NTA_CONF_PATH environment variable ) for the given filename. If found return the complete path to the file. | def findConfigFile(cls, filename):
""" Search the configuration path (specified via the NTA_CONF_PATH
environment variable) for the given filename. If found, return the complete
path to the file.
:param filename: (string) name of file to locate
"""
paths = cls.getConfigPaths()
for p in pat... |
Return the list of paths to search for configuration files. | def getConfigPaths(cls):
""" Return the list of paths to search for configuration files.
:returns: (list) of paths
"""
configPaths = []
if cls._configPaths is not None:
return cls._configPaths
else:
if 'NTA_CONF_PATH' in os.environ:
configVar = os.environ['NTA_CONF_PATH']
... |
Add noise to the given input. | def addNoise(input, noise=0.1, doForeground=True, doBackground=True):
"""
Add noise to the given input.
Parameters:
-----------------------------------------------
input: the input to add noise to
noise: how much noise to add
doForeground: If true, turn off some of the 1 bits in the inpu... |
Generate a coincidence matrix. This is used to generate random inputs to the temporal learner and to compare the predicted output against. | def generateCoincMatrix(nCoinc=10, length=500, activity=50):
"""
Generate a coincidence matrix. This is used to generate random inputs to the
temporal learner and to compare the predicted output against.
It generates a matrix of nCoinc rows, each row has length 'length' and has
a total of 'activity' bits on.... |
Generate a list of random sparse distributed vectors. This is used to generate training vectors to the spatial or temporal learner and to compare the predicted output against. | def generateVectors(numVectors=100, length=500, activity=50):
"""
Generate a list of random sparse distributed vectors. This is used to generate
training vectors to the spatial or temporal learner and to compare the predicted
output against.
It generates a list of 'numVectors' elements, each element has len... |
Generate a set of simple sequences. The elements of the sequences will be integers from 0 to nCoinc - 1. The length of each sequence will be randomly chosen from the seqLength list. | def generateSimpleSequences(nCoinc=10, seqLength=[5,6,7], nSeq=100):
"""
Generate a set of simple sequences. The elements of the sequences will be
integers from 0 to 'nCoinc'-1. The length of each sequence will be
randomly chosen from the 'seqLength' list.
Parameters:
--------------------------------------... |
Generate a set of hub sequences. These are sequences which contain a hub element in the middle. The elements of the sequences will be integers from 0 to nCoinc - 1. The hub elements will only appear in the middle of each sequence. The length of each sequence will be randomly chosen from the seqLength list. | def generateHubSequences(nCoinc=10, hubs = [2,6], seqLength=[5,6,7], nSeq=100):
"""
Generate a set of hub sequences. These are sequences which contain a hub
element in the middle. The elements of the sequences will be integers
from 0 to 'nCoinc'-1. The hub elements will only appear in the middle of
each seque... |
Generate a non overlapping coincidence matrix. This is used to generate random inputs to the temporal learner and to compare the predicted output against. | def generateSimpleCoincMatrix(nCoinc=10, length=500, activity=50):
"""
Generate a non overlapping coincidence matrix. This is used to generate random
inputs to the temporal learner and to compare the predicted output against.
It generates a matrix of nCoinc rows, each row has length 'length' and has
a total ... |
Generate a set of simple and hub sequences. A simple sequence contains a randomly chosen set of elements from 0 to nCoinc - 1. A hub sequence always contains a hub element in the middle of it. | def generateSequences(nPatterns=10, patternLen=500, patternActivity=50,
hubs=[2,6], seqLength=[5,6,7],
nSimpleSequences=50, nHubSequences=50):
"""
Generate a set of simple and hub sequences. A simple sequence contains
a randomly chosen set of elements from 0 to 'nCoinc-1'... |
Generate the simulated output from a spatial pooler that s sitting on top of another spatial pooler/ temporal memory pair. The average on - time of the outputs from the simulated TM is given by the l1Pooling argument. | def generateL2Sequences(nL1Patterns=10, l1Hubs=[2,6], l1SeqLength=[5,6,7],
nL1SimpleSequences=50, nL1HubSequences=50,
l1Pooling=4, perfectStability=False, spHysteresisFactor=1.0,
patternLen=500, patternActivity=50):
"""
Generate the simulated output from a spat... |
Convert a list of sequences of pattern indices and a pattern lookup table into a an array of patterns | def vectorsFromSeqList(seqList, patternMatrix):
"""
Convert a list of sequences of pattern indices, and a pattern lookup table
into a an array of patterns
Parameters:
-----------------------------------------------
seq: the sequence, given as indices into the patternMatrix
patternMatrix: ... |
Given two TM instances see if any parameters are different. | def sameTMParams(tp1, tp2):
"""Given two TM instances, see if any parameters are different."""
result = True
for param in ["numberOfCols", "cellsPerColumn", "initialPerm", "connectedPerm",
"minThreshold", "newSynapseCount", "permanenceInc", "permanenceDec",
"permanenceMax", "global... |
Given a synapse and a list of synapses check whether this synapse exist in the list. A synapse is represented as [ col cell permanence ]. A synapse matches if col and cell are identical and the permanence value is within 0. 001. | def sameSynapse(syn, synapses):
"""Given a synapse and a list of synapses, check whether this synapse
exist in the list. A synapse is represented as [col, cell, permanence].
A synapse matches if col and cell are identical and the permanence value is
within 0.001."""
for s in synapses:
if (s[0]==syn[0]) a... |
Return True if seg1 and seg2 are identical ignoring order of synapses | def sameSegment(seg1, seg2):
"""Return True if seg1 and seg2 are identical, ignoring order of synapses"""
result = True
# check sequence segment, total activations etc. In case any are floats,
# check that they are within 0.001.
for field in [1, 2, 3, 4, 5, 6]:
if abs(seg1[0][field] - seg2[0][field]) > 0... |
Given two TM instances list the difference between them and returns False if there is a difference. This function checks the major parameters. If this passes ( and checkLearn is true ) it checks the number of segments on each cell. If this passes checks each synapse on each segment. When comparing C ++ and Py the segme... | def tmDiff(tm1, tm2, verbosity = 0, relaxSegmentTests =True):
"""
Given two TM instances, list the difference between them and returns False
if there is a difference. This function checks the major parameters. If this
passes (and checkLearn is true) it checks the number of segments on
each cell. If this passe... |
Given two TM instances list the difference between them and returns False if there is a difference. This function checks the major parameters. If this passes ( and checkLearn is true ) it checks the number of segments on each cell. If this passes checks each synapse on each segment. When comparing C ++ and Py the segme... | def tmDiff2(tm1, tm2, verbosity = 0, relaxSegmentTests =True,
checkLearn = True, checkStates = True):
"""
Given two TM instances, list the difference between them and returns False
if there is a difference. This function checks the major parameters. If this
passes (and checkLearn is true) it checks ... |
Function that compares two spatial pooler instances. Compares the static variables between the two poolers to make sure that they are equivalent. | def spDiff(SP1,SP2):
"""
Function that compares two spatial pooler instances. Compares the
static variables between the two poolers to make sure that they are equivalent.
Parameters
-----------------------------------------
SP1 first spatial pooler to be compared
SP2 second spatial pooler ... |
Convert a list of sequences of pattern indices and a pattern lookup table into a an array of patterns | def removeSeqStarts(vectors, resets, numSteps=1):
"""
Convert a list of sequences of pattern indices, and a pattern lookup table
into a an array of patterns
Parameters:
-----------------------------------------------
vectors: the data vectors. Row 0 contains the outputs from time
... |
Accumulate a list of values values into the frequency counts freqCounts and return the updated frequency counts | def _accumulateFrequencyCounts(values, freqCounts=None):
"""
Accumulate a list of values 'values' into the frequency counts 'freqCounts',
and return the updated frequency counts
For example, if values contained the following: [1,1,3,5,1,3,5], and the initial
freqCounts was None, then the return value would b... |
Returns 3 things for a vector: * the total on time * the number of runs * a list of the durations of each run. | def _listOfOnTimesInVec(vector):
"""
Returns 3 things for a vector:
* the total on time
* the number of runs
* a list of the durations of each run.
Parameters:
-----------------------------------------------
input stream: 11100000001100000000011111100000
return value: (11, 3, [3, 2, 6])
"""
... |
Helper function used by averageOnTimePerTimestep. durations is a vector which must be the same len as vector. For each on in vector it fills in the corresponding element of duration with the duration of that on signal up until that time | def _fillInOnTimes(vector, durations):
"""
Helper function used by averageOnTimePerTimestep. 'durations' is a vector
which must be the same len as vector. For each "on" in vector, it fills in
the corresponding element of duration with the duration of that "on" signal
up until that time
Parameters:
------... |
Computes the average on - time of the outputs that are on at each time step and then averages this over all time steps. | def averageOnTimePerTimestep(vectors, numSamples=None):
"""
Computes the average on-time of the outputs that are on at each time step, and
then averages this over all time steps.
This metric is resiliant to the number of outputs that are on at each time
step. That is, if time step 0 has many more outputs on ... |
Returns the average on - time averaged over all on - time runs. | def averageOnTime(vectors, numSamples=None):
"""
Returns the average on-time, averaged over all on-time runs.
Parameters:
-----------------------------------------------
vectors: the vectors for which the onTime is calculated. Row 0
contains the outputs from time step 0, row 1 fr... |
Generate a figure that shows each output over time. Time goes left to right and each output is plotted on a different line allowing you to see the overlap in the outputs when they turn on/ off etc. | def plotOutputsOverTime(vectors, buVectors=None, title='On-times'):
"""
Generate a figure that shows each output over time. Time goes left to right,
and each output is plotted on a different line, allowing you to see the overlap
in the outputs, when they turn on/off, etc.
Parameters:
----------------------... |
This is usually used to display a histogram of the on - times encountered in a particular output. | def plotHistogram(freqCounts, title='On-Times Histogram', xLabel='On-Time'):
"""
This is usually used to display a histogram of the on-times encountered
in a particular output.
The freqCounts is a vector containg the frequency counts of each on-time
(starting at an on-time of 0 and going to an on-time = len(... |
Returns the stability for the population averaged over multiple time steps | def populationStability(vectors, numSamples=None):
"""
Returns the stability for the population averaged over multiple time steps
Parameters:
-----------------------------------------------
vectors: the vectors for which the stability is calculated
numSamples the number of time steps where ... |
Returns the percent of the outputs that remain completely stable over N time steps. | def percentOutputsStableOverNTimeSteps(vectors, numSamples=None):
"""
Returns the percent of the outputs that remain completely stable over
N time steps.
Parameters:
-----------------------------------------------
vectors: the vectors for which the stability is calculated
numSamples: the numbe... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.