Search is not available for this dataset
text
stringlengths
75
104k
def next(self, record, curInputBookmark): """ Return the next aggregated record, if any Parameters: ------------------------------------------------------------------------ record: The input record (values only) from the input source, or None if the input has reached EOF (th...
def processClubAttendance(f, clubs): """Process the attendance data of one club If the club already exists in the list update its data. If the club is new create a new Club object and add it to the dict The next step is to iterate over all the lines and add a record for each line. When reaching an empty...
def processClubConsumption(f, clubs): """Process the consumption a club - Skip the header line - Iterate over lines - Read 4 records at a time - Parse each line: club, date, time, consumption - Get club object from dictionary if needed - Aggregate consumption - Call club.processConsum...
def run(self, inputRecord): """ 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` ...
def _getModelCheckpointFilePath(checkpointDir): """ 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. """ path = os.path.join(checkpointDir, "model.data") ...
def writeToCheckpoint(self, checkpointDir): """Serializes model using capnproto and writes data to ``checkpointDir``""" proto = self.getSchema().new_message() self.write(proto) checkpointPath = self._getModelCheckpointFilePath(checkpointDir) # Clean up old saved state, if any if os.path.exist...
def readFromCheckpoint(cls, checkpointDir): """Deserializes model from checkpointDir using capnproto""" checkpointPath = cls._getModelCheckpointFilePath(checkpointDir) with open(checkpointPath, 'r') as f: proto = cls.getSchema().read(f, traversal_limit_in_words=_TRA...
def writeBaseToProto(self, proto): """Save the state maintained by the Model base class :param proto: capnp ModelProto message builder """ inferenceType = self.getInferenceType() # lower-case first letter to be compatible with capnproto enum naming inferenceType = inferenceType[:1].lower() + in...
def save(self, saveModelDir): """ Save the model in the given directory. :param saveModelDir: (string) Absolute directory path for saving the model. This directory should only be used to store a saved model. If the directory does not exist, it will be created automatically and popula...
def load(cls, savedModelDir): """ Load saved model. :param savedModelDir: (string) Directory of where the experiment is to be or was saved :returns: (:class:`Model`) The loaded model instance """ logger = opf_utils.initLogger(cls) logger.debug("Loading model from local checkpoint at ...
def _getModelPickleFilePath(saveModelDir): """ 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. """ path = os.path.join(saveModelDir, "model.pkl") path = os....
def _getModelExtraDataDir(saveModelDir): """ Return the absolute path to the directory where the model's own "extra data" are stored (i.e., data that's too big for pickling). :param saveModelDir: (string) Directory of where the experiment is to be or was saved :returns: (string) An absolute ...
def runExperiment(args, model=None): """ Run a single OPF experiment. .. note:: The caller is responsible for initializing python logging before calling this function (e.g., import :mod:`nupic.support`; :meth:`nupic.support.initLogging`) See also: :meth:`.initExperimentPrng`. :param args: (string...
def _parseCommandLineOptions(args): """Parse command line options Args: args: command line arguments (not including sys.argv[0]) Returns: namedtuple ParseCommandLineOptionsResult """ usageStr = ( "%prog [options] descriptionPyDirectory\n" "This script runs a single OPF Model described by desc...
def reapVarArgsCallback(option, optStr, value, parser): """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 """ newValues = [] # Re...
def _reportCommandLineUsageErrorAndExit(parser, message): """Report usage error and exit program with error indication.""" print parser.get_usage() print message sys.exit(1)
def _runExperimentImpl(options, model=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 const...
def _saveModel(model, experimentDir, checkpointLabel, newSerialization=False): """Save model""" checkpointDir = _getModelCheckpointDir(experimentDir, checkpointLabel) if newSerialization: model.writeToCheckpoint(checkpointDir) else: model.save(saveModelDir=checkpointDir)
def _getModelCheckpointDir(experimentDir, checkpointLabel): """Creates directory for serialization of the model checkpointLabel: Checkpoint label (string) Returns: absolute path to the serialization directory """ checkpointDir = os.path.join(getCheckpointParentDir(experimentDir), ...
def getCheckpointParentDir(experimentDir): """Get checkpoint parent dir. Returns: absolute path to the base serialization directory within which model checkpoints for this experiment are created """ baseDir = os.path.join(experimentDir, "savedmodels") baseDir = os.path.abspath(baseDir) return baseDi...
def _checkpointLabelFromCheckpointDir(checkpointDir): """Returns a checkpoint label string for the given model checkpoint directory checkpointDir: relative or absolute model checkpoint directory path """ assert checkpointDir.endswith(g_defaultCheckpointExtension) lastSegment = os.path.split(checkpointDir)[1...
def _isCheckpointDir(checkpointDir): """Return true iff checkpointDir appears to be a checkpoint directory.""" lastSegment = os.path.split(checkpointDir)[1] if lastSegment[0] == '.': return False if not checkpointDir.endswith(g_defaultCheckpointExtension): return False if not os.path.isdir(checkpoin...
def _printAvailableCheckpoints(experimentDir): """List available checkpoints for the specified experiment.""" checkpointParentDir = getCheckpointParentDir(experimentDir) if not os.path.exists(checkpointParentDir): print "No available checkpoints." return checkpointDirs = [x for x in os.listdir(checkpo...
def run(self): """Runs a single experiment task""" self.__logger.debug("run(): Starting task <%s>", self.__task['taskLabel']) # Set up the task # Create our main loop-control iterator if self.__cmdOptions.privateOptions['testMode']: numIters = 10 else: numIters = self.__task['itera...
def _createPeriodicActivities(self): """Creates and returns a list of activites for this TaskRunner instance Returns: a list of PeriodicActivityRequest elements """ # Initialize periodic activities periodicActivities = [] # Metrics reporting class MetricsReportCb(object): def __init_...
def _generateFile(filename, data): """ Parameters: ---------------------------------------------------------------- filename: name of .csv file to generate """ # Create the file print "Creating %s..." % (filename) numRecords, numFields = data.shape fields = [('field%...
def corruptVector(v1, noiseLevel, numActiveCols): """ Corrupts a copy of a binary vector by inverting noiseLevel percent of its bits. @param v1 (array) binary vector whose copy will be corrupted @param noiseLevel (float) amount of noise to be applied on the new vector @param numActiveCols (int) num...
def showPredictions(): """ 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 k in range(6): tm.reset() print "--- " + "ABCDXY"[k] + " ---" tm.compute(set(seqT[k][:].nonzero()[0...
def trainTM(sequence, timeSteps, noiseLevel): """ Trains the TM with given sequence for a given number of time steps and level of input corruption @param sequence (array) array whose rows are the input characters @param timeSteps (int) number of time steps in which the TM will be presented with sequen...
def encodeIntoArray(self, inputVal, outputVal): """See method description in base.py""" if len(inputVal) != len(outputVal): raise ValueError("Different input (%i) and output (%i) sizes." % ( len(inputVal), len(outputVal))) if self.w is not None and sum(inputVal) != self.w: raise Value...
def decode(self, encoded, parentFieldName=""): """See the function description in base.py""" if parentFieldName != "": fieldName = "%s.%s" % (parentFieldName, self.name) else: fieldName = self.name return ({fieldName: ([[0, 0]], "input")}, [fieldName])
def getBucketInfo(self, buckets): """See the function description in base.py""" return [EncoderResult(value=0, scalar=0, encoding=numpy.zeros(self.n))]
def topDownCompute(self, encoded): """See the function description in base.py""" return EncoderResult(value=0, scalar=0, encoding=numpy.zeros(self.n))
def closenessScores(self, expValues, actValues, **kwargs): """ Does a bitwise compare of the two bitmaps and returns a fractonal value between 0 and 1 of how similar they are. - ``1`` => identical - ``0`` => no overlaping bits ``kwargs`` will have the keyword "fractional", which is assumed by ...
def getCallerInfo(depth=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 ...
def title(s=None, additional='', stream=sys.stdout): """Utility function to display nice titles It automatically extracts the name of the function/method it is called from and you can add additional text. title() will then print the name of the function/method and the additional text surrounded by tow lines ...
def getArgumentDescriptions(f): """ 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... ...
def initLogging(verbose=False, console='stdout', consoleLevel='DEBUG'): """ Initilize NuPic logging by reading in from the logging configuration file. The logging configuration file is named ``nupic-logging.conf`` and is expected to be in the format defined by the python logging module. If the environment va...
def _genLoggingFilePath(): """ Generate a filepath for the calling app """ appName = os.path.splitext(os.path.basename(sys.argv[0]))[0] or 'UnknownApp' appLogDir = os.path.abspath(os.path.join( os.environ['NTA_LOG_DIR'], 'numenta-logs-%s' % (os.environ['USER'],), appName)) appLogFileName = '%s-%s-%s...
def aggregationToMonthsSeconds(interval): """ 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'...
def aggregationDivide(dividend, divisor): """ 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 ex...
def validateOpfJsonValue(value, opfJsonSchemaFilename): """ Validate a python object against an OPF json schema file :param value: target python object to validate (typically a dictionary) :param opfJsonSchemaFilename: (string) OPF json schema filename containing the json schema object. (e.g., opfTask...
def initLogger(obj): """ 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(obj): myClass = obj else: myClass = obj.__class__ logger = logging.getLogger(".".join( ['com.numenta', m...
def matchPatterns(patterns, keys): """ 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 """ results = [] if patterns: for pattern in patterns: prog = re.compile(pattern) fo...
def _getScaledValue(self, inpt): """ Convert the input, which is in normal space, into log space """ if inpt == SENTINEL_VALUE_FOR_MISSING_DATA: return None else: val = inpt if val < self.minval: val = self.minval elif val > self.maxval: val = self.maxval ...
def getBucketIndices(self, inpt): """ See the function description in base.py """ # Get the scaled value scaledVal = self._getScaledValue(inpt) if scaledVal is None: return [None] else: return self.encoder.getBucketIndices(scaledVal)
def encodeIntoArray(self, inpt, output): """ See the function description in base.py """ # Get the scaled value scaledVal = self._getScaledValue(inpt) if scaledVal is None: output[0:] = 0 else: self.encoder.encodeIntoArray(scaledVal, output) if self.verbosity >= 2: ...
def decode(self, encoded, parentFieldName=''): """ See the function description in base.py """ # Get the scalar values from the underlying scalar encoder (fieldsDict, fieldNames) = self.encoder.decode(encoded) if len(fieldsDict) == 0: return (fieldsDict, fieldNames) # Expect only 1 f...
def getBucketValues(self): """ See the function description in base.py """ # Need to re-create? if self._bucketValues is None: scaledValues = self.encoder.getBucketValues() self._bucketValues = [] for scaledValue in scaledValues: value = math.pow(10, scaledValue) s...
def getBucketInfo(self, buckets): """ See the function description in base.py """ scaledResult = self.encoder.getBucketInfo(buckets)[0] scaledValue = scaledResult.value value = math.pow(10, scaledValue) return [EncoderResult(value=value, scalar=value, encoding = sc...
def topDownCompute(self, encoded): """ See the function description in base.py """ scaledResult = self.encoder.topDownCompute(encoded)[0] scaledValue = scaledResult.value value = math.pow(10, scaledValue) return EncoderResult(value=value, scalar=value, encoding = s...
def closenessScores(self, expValues, actValues, fractional=True): """ See the function description in base.py """ # Compute the percent error in log space if expValues[0] > 0: expValue = math.log10(expValues[0]) else: expValue = self.minScaledValue if actValues [0] > 0: ...
def export(self): """ Exports a network as a networkx MultiDiGraph intermediate representation suitable for visualization. :return: networkx MultiDiGraph """ graph = nx.MultiDiGraph() # Add regions to graph as nodes, annotated by name regions = self.network.getRegions() for idx in...
def bitsToString(arr): """Returns a string representing a numpy array of 0's and 1's""" s = array('c','.'*len(arr)) for i in xrange(len(arr)): if arr[i] == 1: s[i]='*' return s
def percentOverlap(x1, x2, size): """ 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 """ nonZeroX1 = np.co...
def resetVector(x1, x2): """ Copies the contents of vector x1 into vector x2. @param x1 (array) binary vector to be copied @param x2 (array) binary vector where x1 is copied """ size = len(x1) for i in range(size): x2[i] = x1[i]
def runCPU(): """Poll CPU usage, make predictions, and plot the results. Runs forever.""" # Create the model for predicting CPU usage. model = ModelFactory.create(model_params.MODEL_PARAMS) model.enableInference({'predictedField': 'cpu'}) # The shifter will align prediction and actual values. shifter = Infe...
def _extractCallingMethodArgs(): """ Returns args dictionary from the calling method """ import inspect import copy callingFrame = inspect.stack()[1][0] argNames, _, _, frameLocalVarDict = inspect.getargvalues(callingFrame) argNames.remove("self") args = copy.copy(frameLocalVarDict) for varNam...
def write(self, proto): """Populate serialization proto instance. :param proto: (BacktrackingTMCppProto) the proto instance to populate """ # Write base class to proto.baseTM (BacktrackingTMProto) super(BacktrackingTMCPP, self).write(proto.baseTM) self.cells4.write(proto.cells4) proto.makeC...
def read(cls, proto): """Deserialize from proto instance. :param proto: (BacktrackingTMCppProto) the proto instance to read from """ # Use base class to create initial class from proto.baseTM # (BacktrackingTMProto) obj = BacktrackingTM.read(proto.baseTM) obj.__class__ = cls # Addition...
def _getEphemeralMembers(self): """ List of our member variables that we don't need to be saved """ e = BacktrackingTM._getEphemeralMembers(self) if self.makeCells4Ephemeral: e.extend(['cells4']) return e
def _initEphemerals(self): """ Initialize all ephemeral members after being restored to a pickled state. """ BacktrackingTM._initEphemerals(self) #--------------------------------------------------------------------------------- # cells4 specific initialization # If True, let C++ allocate m...
def compute(self, bottomUpInput, enableLearn, enableInference=None): """ Overrides :meth:`nupic.algorithms.backtracking_tm.BacktrackingTM.compute`. """ # The C++ TM takes 32 bit floats as input. uint32 works as well since the # code only checks whether elements are non-zero assert (bottomUpInput...
def _copyAllocatedStates(self): """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 self.verbosity > 1 or self.retrieveLearningStates: (activeT, activeT1, predT, predT1) = self.cells4.getLearnStates() self.lrnActiveSta...
def _setStatePointers(self): """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...
def reset(self): """ Overrides :meth:`nupic.algorithms.backtracking_tm.BacktrackingTM.reset`. """ if self.verbosity >= 3: print "TM Reset" self._setStatePointers() self.cells4.reset() BacktrackingTM.reset(self)
def trimSegments(self, minPermanence=None, minNumSyns=None): """ Overrides :meth:`nupic.algorithms.backtracking_tm.BacktrackingTM.trimSegments`. """ # Fill in defaults if minPermanence is None: minPermanence = 0.0 if minNumSyns is None: minNumSyns = 0 # Print all cells if verbos...
def printSegmentUpdates(self): """ Overrides :meth:`nupic.algorithms.backtracking_tm.BacktrackingTM.printSegmentUpdates`. """ # TODO: need to add C++ accessors to implement this method assert False print "=== SEGMENT UPDATES ===, Num = ", len(self.segmentUpdates) for key, updateList in self....
def _slowIsSegmentActive(self, seg, timeStep): """ A segment is active if it has >= activationThreshold connected synapses that are active due to infActiveState. """ numSyn = seg.size() numActiveSyns = 0 for synIdx in xrange(numSyn): if seg.getPermanence(synIdx) < self.connectedPerm:...
def printCell(self, c, i, onlyActiveSegments=False): """ Overrides :meth:`nupic.algorithms.backtracking_tm.BacktrackingTM.printCell`. """ nSegs = self.cells4.nSegmentsOnCell(c,i) if nSegs > 0: segList = self.cells4.getNonEmptySegList(c,i) gidx = c * self.cellsPerColumn + i print "C...
def getColCellIdx(self, idx): """ Get column and cell within column from a global cell index. The global index is ``idx = colIdx * nCellsPerCol() + cellIdxInCol`` :param idx: (int) global cell index :returns: (tuple) (colIdx, cellIdxInCol) """ c = idx//self.cellsPerColumn i = idx - ...
def getSegmentOnCell(self, c, i, segIdx): """ Overrides :meth:`nupic.algorithms.backtracking_tm.BacktrackingTM.getSegmentOnCell`. """ segList = self.cells4.getNonEmptySegList(c,i) seg = self.cells4.getSegment(c, i, segList[segIdx]) numSyn = seg.size() assert numSyn != 0 # Accumulate seg...
def getSegmentInfo(self, collectActiveData = False): """ Overrides :meth:`nupic.algorithms.backtracking_tm.BacktrackingTM.getSegmentInfo`. """ # Requires appropriate accessors in C++ cells4 (currently unimplemented) assert collectActiveData == False nSegments, nSynapses = self.getNumSegments(),...
def main(argv): """ The main function of the HypersearchWorker script. This parses the command line arguments, instantiates a HypersearchWorker instance, and then runs it. Parameters: ---------------------------------------------------------------------- retval: jobID of the job we ran. This is used ...
def _processUpdatedModels(self, cjDAO): """ For all models that modified their results since last time this method was called, send their latest results to the Hypersearch implementation. """ # Get the latest update counters. This returns a list of tuples: # (modelID, updateCounter) curModelI...
def run(self): """ Run this worker. Parameters: ---------------------------------------------------------------------- retval: jobID of the job we ran. This is used by unit test code when calling this working using the --params command line option (which tells th...
def getBucketIndices(self, x): """ See method description in base.py """ if ((isinstance(x, float) and math.isnan(x)) or x == SENTINEL_VALUE_FOR_MISSING_DATA): return [None] if self._offset is None: self._offset = x bucketIdx = ( (self._maxBuckets/2) + int(round((x - self....
def mapBucketIndexToNonZeroBits(self, index): """ 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 o...
def encodeIntoArray(self, x, output): """ See method description in base.py """ if x is not None and not isinstance(x, numbers.Number): raise TypeError( "Expected a scalar input but got input of type %s" % type(x)) # Get the bucket index to use bucketIdx = self.getBucketIndices(x)[0] ...
def _createBucket(self, index): """ Create the given bucket index. Recursively create as many in-between bucket indices as necessary. """ if index < self.minIndex: if index == self.minIndex - 1: # Create a new representation that has exactly w-1 overlapping bits # as the min re...
def _newRepresentation(self, index, newIndex): """ Return a new representation for newIndex that overlaps with the representation at index by exactly w-1 bits """ newRepresentation = self.bucketMap[index].copy() # Choose the bit we will replace in this representation. We need to shift # thi...
def _newRepresentationOK(self, newRep, newIndex): """ Return True if this new candidate representation satisfies all our overlap rules. Since we know that neighboring representations differ by at most one bit, we compute running overlaps. """ if newRep.size != self.w: return False if (...
def _countOverlapIndices(self, i, j): """ Return the overlap between bucket indices i and j """ if self.bucketMap.has_key(i) and self.bucketMap.has_key(j): iRep = self.bucketMap[i] jRep = self.bucketMap[j] return self._countOverlap(iRep, jRep) else: raise ValueError("Either i...
def _countOverlap(rep1, rep2): """ Return the overlap between two representations. rep1 and rep2 are lists of non-zero indices. """ overlap = 0 for e in rep1: if e in rep2: overlap += 1 return overlap
def _overlapOK(self, i, j, overlap=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 overlap is None: overlap = self._countOverlapIndices(i, j) if abs(i-j) < self.w: if overla...
def _initializeBucketMap(self, maxBuckets, offset): """ Initialize the bucket map assuming the given number of maxBuckets. """ # The first bucket index will be _maxBuckets / 2 and bucket indices will be # allowed to grow lower or higher as long as they don't become negative. # _maxBuckets is req...
def retrySQL(timeoutSec=60*5, logger=None): """ Return a closure suitable for use as a decorator for retrying a pymysql DAO function on certain failures that warrant retries ( e.g., RDS/MySQL server down temporarily, transaction deadlock, etc.). We share this function across multiple scripts (e.g., ClientJobsDA...
def create(*args, **kwargs): """ 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>`_. """...
def read(proto): """ :param proto: SDRClassifierRegionProto capnproto object """ impl = proto.implementation if impl == 'py': return SDRClassifier.read(proto.sdrClassifier) elif impl == 'cpp': return FastSDRClassifier.read(proto.sdrClassifier) elif impl == 'diff': return SD...
def cross_list(*sequences): """ From: http://book.opensourceproject.org.cn/lamp/python/pythoncook2/opensource/0596007973/pythoncook2-chp-19-sect-9.html """ result = [[ ]] for seq in sequences: result = [sublist+[item] for sublist in result for item in seq] return result
def cross(*sequences): """ From: http://book.opensourceproject.org.cn/lamp/python/pythoncook2/opensource/0596007973/pythoncook2-chp-19-sect-9.html """ # visualize an odometer, with "wheels" displaying "digits"...: wheels = map(iter, sequences) digits = [it.next( ) for it in wheels] while True: yield t...
def dcross(**keywords): """ Similar to cross(), but generates output dictionaries instead of tuples. """ keys = keywords.keys() # Could use keywords.values(), but unsure whether the order # the values come out in is guaranteed to be the same as that of keys # (appears to be anecdotally true). sequences ...
def mmGetMetricFromTrace(self, trace): """ 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(trace.makeCountsTrace(), ...
def mmGetMetricSequencesPredictedActiveCellsPerColumn(self): """ Metric for number of predicted => active cells per column for each sequence @return (Metric) metric """ self._mmComputeTransitionTraces() numCellsPerColumn = [] for predictedActiveCells in ( self._mmData["predictedAc...
def mmGetMetricSequencesPredictedActiveCellsShared(self): """ 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 """ self._mmComputeTransitionTraces() numSequencesForCell = defa...
def mmPrettyPrintConnections(self): """ Pretty print the connections in the temporal memory. TODO: Use PrettyTable. @return (string) Pretty-printed text """ text = "" text += ("Segments: (format => " "(#) [(source cell=permanence ...), ...]\n") text += "------------...
def mmPrettyPrintSequenceCellRepresentations(self, sortby="Column"): """ Pretty print the cell representations for sequences in the history. @param sortby (string) Column of table to sort by @return (string) Pretty-printed text """ self._mmComputeTransitionTraces() table = PrettyTable(["Pa...
def createTemporalAnomaly(recordParams, spatialParams=_SP_PARAMS, temporalParams=_TM_PARAMS, verbosity=_VERBOSITY): """Generates a Network with connected RecordSensor, SP, TM. This function takes care of generating regions and the canonical links. The network...
def runNetwork(network, writer): """Run the network and write output to writer. :param network: a Network instance to run :param writer: a csv.writer instance to write output to """ sensorRegion = network.regions["sensor"] temporalPoolerRegion = network.regions["temporalPoolerRegion"] for i in xrange(_N...
def __appendActivities(self, periodicActivities): """ periodicActivities: A sequence of PeriodicActivityRequest elements """ for req in periodicActivities: act = self.Activity(repeating=req.repeating, period=req.period, cb=req.cb, ...