INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Generates a table where each cell represent a frequency of pairs as described below. x coordinate is the % difference between input records ( origData list ) y coordinate is the % difference between corresponding output records. | def generatePlot(outputs, origData):
""" Generates a table where each cell represent a frequency of pairs
as described below.
x coordinate is the % difference between input records (origData list),
y coordinate is the % difference between corresponding output records.
"""
PLOT_PRECISION = 100
distribMat... |
Generates a set of input record | def generateRandomInput(numRecords, elemSize = 400, numSet = 42):
""" Generates a set of input record
Params:
numRecords - how many records to generate
elemSize - the size of each record (num 0s or 1s)
numSet - how many 1s in each record
Returns: a list of inputs
"""
inputs = ... |
Creates an one - off record for each record in the inputs. Appends new records to the same inputs list. | def appendInputWithSimilarValues(inputs):
""" Creates an 'one-off' record for each record in the inputs. Appends new
records to the same inputs list.
"""
numInputs = len(inputs)
for i in xrange(numInputs):
input = inputs[i]
for j in xrange(len(input)-1):
if input[j] == 1 and input[j+1] == 0:
... |
Creates a neighboring record for each record in the inputs and adds new records at the end of the inputs list | def appendInputWithNSimilarValues(inputs, numNear = 10):
""" Creates a neighboring record for each record in the inputs and adds
new records at the end of the inputs list
"""
numInputs = len(inputs)
skipOne = False
for i in xrange(numInputs):
input = inputs[i]
numChanged = 0
newInput = copy.deep... |
Modifies up to maxChanges number of bits in the inputVal | def modifyBits(inputVal, maxChanges):
""" Modifies up to maxChanges number of bits in the inputVal
"""
changes = np.random.random_integers(0, maxChanges, 1)[0]
if changes == 0:
return inputVal
inputWidth = len(inputVal)
whatToChange = np.random.random_integers(0, 41, changes)
runningIndex = -1
n... |
Returns a random selection from the inputSpace with randomly modified up to maxChanges number of bits. | def getRandomWithMods(inputSpace, maxChanges):
""" Returns a random selection from the inputSpace with randomly modified
up to maxChanges number of bits.
"""
size = len(inputSpace)
ind = np.random.random_integers(0, size-1, 1)[0]
value = copy.deepcopy(inputSpace[ind])
if maxChanges == 0:
return valu... |
Creates and returns a #MultiEncoder including a ScalarEncoder for energy consumption and a DateEncoder for the time of the day. | def createEncoder():
"""
Creates and returns a #MultiEncoder including a ScalarEncoder for
energy consumption and a DateEncoder for the time of the day.
@see nupic/encoders/__init__.py for type to file-name mapping
@see nupic/encoders for encoder source files
"""
encoder = MultiEncoder()
encoder.addMul... |
Creates a RecordSensor region that allows us to specify a file record stream as the input source. | def createRecordSensor(network, name, dataSource):
"""
Creates a RecordSensor region that allows us to specify a file record
stream as the input source.
"""
# Specific type of region. Possible options can be found in /nupic/regions/
regionType = "py.RecordSensor"
# Creates a json from specified dictiona... |
Creates and returns a new Network with a sensor region reading data from dataSource. There are two hierarchical levels each with one SP and one TM. | def createNetwork(dataSource):
"""Creates and returns a new Network with a sensor region reading data from
'dataSource'. There are two hierarchical levels, each with one SP and one TM.
@param dataSource - A RecordStream containing the input data
@returns a Network ready to run
"""
network = Network()
# C... |
Runs specified Network writing the ensuing anomaly scores to writer. | def runNetwork(network, numRecords, writer):
"""
Runs specified Network writing the ensuing anomaly
scores to writer.
@param network: The Network instance to be run
@param writer: A csv.writer used to write to output file.
"""
sensorRegion = network.regions[_RECORD_SENSOR]
l1SpRegion = network.regions[... |
Removes trailing whitespace on each line. | def clean(s):
"""Removes trailing whitespace on each line."""
lines = [l.rstrip() for l in s.split('\n')]
return '\n'.join(lines) |
Compute the new metrics values given the next inference/ ground - truth values | def update(self, results):
"""
Compute the new metrics values, given the next inference/ground-truth values
:param results: (:class:`~nupic.frameworks.opf.opf_utils.ModelResult`)
object that was computed during the last iteration of the model.
:returns: (dict) where each key is the metric-... |
Gets the current metric values | def getMetrics(self):
"""
Gets the current metric values
:returns: (dict) where each key is the metric-name, and the values are
it scalar value. Same as the output of
:meth:`~nupic.frameworks.opf.prediction_metrics_manager.MetricsManager.update`
"""
result = {}
f... |
Gets detailed info about a given metric in addition to its value. This may including any statistics or auxilary data that are computed for a given metric. | def getMetricDetails(self, metricLabel):
"""
Gets detailed info about a given metric, in addition to its value. This
may including any statistics or auxilary data that are computed for a given
metric.
:param metricLabel: (string) label of the given metric (see
:class:`~nupic.frameworks... |
Stores the current model results in the manager s internal store | def _addResults(self, results):
"""
Stores the current model results in the manager's internal store
Parameters:
-----------------------------------------------------------------------
results: A ModelResults object that contains the current timestep's
input/inferences
"""
# ... |
Get the actual value for this field | def _getGroundTruth(self, inferenceElement):
"""
Get the actual value for this field
Parameters:
-----------------------------------------------------------------------
sensorInputElement: The inference element (part of the inference) that
is being used for this me... |
Creates the required metrics modules | def __constructMetricsModules(self, metricSpecs):
"""
Creates the required metrics modules
Parameters:
-----------------------------------------------------------------------
metricSpecs:
A sequence of MetricSpec objects that specify which metric modules to
instantiate
"""
if no... |
Generate a simple dataset. This contains a bunch of non - overlapping sequences. At the end of the dataset we introduce missing records so that test code can insure that the model didn t get confused by them. Parameters: ---------------------------------------------------- filename: name of the file to produce includin... | def _generateSimple(filename="simple.csv", numSequences=1, elementsPerSeq=3,
numRepeats=10):
""" Generate a simple dataset. This contains a bunch of non-overlapping
sequences.
At the end of the dataset, we introduce missing records so that test
code can insure that the model didn't get ... |
Shift the model result and return the new instance. | def shift(self, modelResult):
"""Shift the model result and return the new instance.
Queues up the T(i+1) prediction value and emits a T(i)
input/prediction pair, if possible. E.g., if the previous T(i-1)
iteration was learn-only, then we would not have a T(i) prediction in our
FIFO and would not b... |
Collect statistics for each of the fields in the user input data file and return a stats dict object. | def generateStats(filename, maxSamples = None,):
"""
Collect statistics for each of the fields in the user input data file and
return a stats dict object.
Parameters:
------------------------------------------------------------------------------
filename: The path and name of the data file.
m... |
Override of getStats () in BaseStatsCollector | def getStats(self, stats):
""" Override of getStats() in BaseStatsCollector
stats: A dictionary where all the stats are
outputted
"""
BaseStatsCollector.getStats(self, stats)
sortedNumberList = sorted(self.valueList)
listLength = len(sortedNumberList)
min = sortedNumberList[0... |
Run according to options in sys. argv and diff classifiers. | def main():
"""Run according to options in sys.argv and diff classifiers."""
initLogging(verbose=True)
# Initialize PRNGs
initExperimentPrng()
# Mock out the creation of the SDRClassifier.
@staticmethod
def _mockCreate(*args, **kwargs):
kwargs.pop('implementation', None)
return SDRClassifierDiff... |
Abbreviate the given text to threshold chars and append an ellipsis if its length exceeds threshold ; used for logging ; | def _abbreviate(text, threshold):
""" Abbreviate the given text to threshold chars and append an ellipsis if its
length exceeds threshold; used for logging;
NOTE: the resulting text could be longer than threshold due to the ellipsis
"""
if text is not None and len(text) > threshold:
text = text[:threshol... |
Generates the ClientJobs database name for the given version of the database | def __getDBNameForVersion(cls, dbVersion):
""" Generates the ClientJobs database name for the given version of the
database
Parameters:
----------------------------------------------------------------
dbVersion: ClientJobs database version number
retval: the ClientJobs database na... |
Get the instance of the ClientJobsDAO created for this process ( or perhaps at some point in the future for this thread ). | def get():
""" Get the instance of the ClientJobsDAO created for this process (or
perhaps at some point in the future, for this thread).
Parameters:
----------------------------------------------------------------
retval: instance of ClientJobsDAO
"""
# Instantiate if needed
if Client... |
Convert a database internal column name to a public name. This takes something of the form word1_word2_word3 and converts it to: word1Word2Word3. If the db field name starts with _ it is stripped out so that the name is compatible with collections. namedtuple. for example: _word1_word2_word3 = > word1Word2Word3 | def _columnNameDBToPublic(self, dbName):
""" Convert a database internal column name to a public name. This
takes something of the form word1_word2_word3 and converts it to:
word1Word2Word3. If the db field name starts with '_', it is stripped out
so that the name is compatible with collections.namedtup... |
Locate the current version of the jobs DB or create a new one and optionally delete old versions laying around. If desired this method can be called at any time to re - create the tables from scratch delete old versions of the database etc. | def connect(self, deleteOldVersions=False, recreate=False):
""" Locate the current version of the jobs DB or create a new one, and
optionally delete old versions laying around. If desired, this method
can be called at any time to re-create the tables from scratch, delete
old versions of the database, et... |
Initialize tables if needed | def _initTables(self, cursor, deleteOldVersions, recreate):
""" Initialize tables, if needed
Parameters:
----------------------------------------------------------------
cursor: SQL cursor
deleteOldVersions: if true, delete any old versions of the DB left
on... |
Return a sequence of matching rows with the requested field values from a table or empty sequence if nothing matched. | def _getMatchingRowsNoRetries(self, tableInfo, conn, fieldsToMatch,
selectFieldNames, maxRows=None):
""" Return a sequence of matching rows with the requested field values from
a table or empty sequence if nothing matched.
tableInfo: Table information: a ClientJobsDAO.... |
Like _getMatchingRowsNoRetries () but with retries on transient MySQL failures | def _getMatchingRowsWithRetries(self, tableInfo, fieldsToMatch,
selectFieldNames, maxRows=None):
""" Like _getMatchingRowsNoRetries(), but with retries on transient MySQL
failures
"""
with ConnectionFactory.get() as conn:
return self._getMatchingRowsNoRetries(tabl... |
Return a single matching row with the requested field values from the the requested table or None if nothing matched. | def _getOneMatchingRowNoRetries(self, tableInfo, conn, fieldsToMatch,
selectFieldNames):
""" Return a single matching row with the requested field values from the
the requested table or None if nothing matched.
tableInfo: Table information: a ClientJobsDAO._TableInfo... |
Like _getOneMatchingRowNoRetries () but with retries on transient MySQL failures | def _getOneMatchingRowWithRetries(self, tableInfo, fieldsToMatch,
selectFieldNames):
""" Like _getOneMatchingRowNoRetries(), but with retries on transient MySQL
failures
"""
with ConnectionFactory.get() as conn:
return self._getOneMatchingRowNoRetries(tableInfo,... |
Attempt to insert a row with the given parameters into the jobs table. Return jobID of the inserted row or of an existing row with matching client/ jobHash key. | def _insertOrGetUniqueJobNoRetries(
self, conn, client, cmdLine, jobHash, clientInfo, clientKey, params,
minimumWorkers, maximumWorkers, jobType, priority, alreadyRunning):
""" Attempt to insert a row with the given parameters into the jobs table.
Return jobID of the inserted row, or of an existing row ... |
Resumes processing of an existing job that is presently in the STATUS_COMPLETED state. | def _resumeJobNoRetries(self, conn, jobID, alreadyRunning):
""" Resumes processing of an existing job that is presently in the
STATUS_COMPLETED state.
NOTE: this is primarily for resuming suspended Production and Stream Jobs; DO
NOT use it on Hypersearch jobs.
This prepares an existing job entry ... |
Resumes processing of an existing job that is presently in the STATUS_COMPLETED state. | def jobResume(self, jobID, alreadyRunning=False):
""" Resumes processing of an existing job that is presently in the
STATUS_COMPLETED state.
NOTE: this is primarily for resuming suspended Production Jobs; DO NOT use
it on Hypersearch jobs.
NOTE: The job MUST be in the STATUS_COMPLETED state at the... |
Add an entry to the jobs table for a new job request. This is called by clients that wish to startup a new job like a Hypersearch stream job or specific model evaluation from the engine. | def jobInsert(self, client, cmdLine, clientInfo='', clientKey='', params='',
alreadyRunning=False, minimumWorkers=0, maximumWorkers=0,
jobType='', priority=DEFAULT_JOB_PRIORITY):
""" Add an entry to the jobs table for a new job request. This is called by
clients that wish to star... |
Add an entry to the jobs table for a new job request but only if the same job by the same client is not already running. If the job is already running or queued up to run this call does nothing. If the job does not exist in the jobs table or has completed it will be inserted and/ or started up again. | def jobInsertUnique(self, client, cmdLine, jobHash, clientInfo='',
clientKey='', params='', minimumWorkers=0,
maximumWorkers=0, jobType='',
priority=DEFAULT_JOB_PRIORITY):
""" Add an entry to the jobs table for a new job request, but only if the
... |
Place the given job in STATUS_RUNNING mode ; the job is expected to be STATUS_NOTSTARTED. | def _startJobWithRetries(self, jobID):
""" Place the given job in STATUS_RUNNING mode; the job is expected to be
STATUS_NOTSTARTED.
NOTE: this function was factored out of jobStartNext because it's also
needed for testing (e.g., test_client_jobs_dao.py)
"""
with ConnectionFactory.get() as conn... |
For use only by Nupic Scheduler ( also known as ClientJobManager ) Look through the jobs table and see if any new job requests have been queued up. If so pick one and mark it as starting up and create the model table to hold the results | def jobStartNext(self):
""" For use only by Nupic Scheduler (also known as ClientJobManager) Look
through the jobs table and see if any new job requests have been
queued up. If so, pick one and mark it as starting up and create the
model table to hold the results
Parameters:
-------------------... |
Look through the jobs table and reactivate all that are already in the running state by setting their _eng_allocate_new_workers fields to True ; used by Nupic Scheduler as part of its failure - recovery procedure. | def jobReactivateRunningJobs(self):
""" Look through the jobs table and reactivate all that are already in the
running state by setting their _eng_allocate_new_workers fields to True;
used by Nupic Scheduler as part of its failure-recovery procedure.
"""
# Get a database connection and cursor
w... |
Look through the jobs table and get the demand - minimum and maximum number of workers requested if new workers are to be allocated if there are any untended dead workers for all running jobs. | def jobGetDemand(self,):
""" Look through the jobs table and get the demand - minimum and maximum
number of workers requested, if new workers are to be allocated, if there
are any untended dead workers, for all running jobs.
Parameters:
--------------------------------------------------------------... |
Set cancel field of all currently - running jobs to true. | def jobCancelAllRunningJobs(self):
""" Set cancel field of all currently-running jobs to true.
"""
# Get a database connection and cursor
with ConnectionFactory.get() as conn:
query = 'UPDATE %s SET cancel=TRUE WHERE status<>%%s ' \
% (self.jobsTableName,)
conn.cursor.execute... |
Look through the jobs table and count the running jobs whose cancel field is true. | def jobCountCancellingJobs(self,):
""" Look through the jobs table and count the running jobs whose
cancel field is true.
Parameters:
----------------------------------------------------------------
retval: A count of running jobs with the cancel field set to true.
"""
with ConnectionF... |
Look through the jobs table and get the list of running jobs whose cancel field is true. | def jobGetCancellingJobs(self,):
""" Look through the jobs table and get the list of running jobs whose
cancel field is true.
Parameters:
----------------------------------------------------------------
retval: A (possibly empty) sequence of running job IDs with cancel field
... |
Generator to allow iterating slices at dynamic intervals | def partitionAtIntervals(data, intervals):
""" Generator to allow iterating slices at dynamic intervals
Parameters:
----------------------------------------------------------------
data: Any data structure that supports slicing (i.e. list or tuple)
*intervals: Iterable of intervals. The sum ... |
Return a list of namedtuples from the result of a join query. A single database result is partitioned at intervals corresponding to the fields in namedTuples. The return value is the result of applying namedtuple. _make () to each of the partitions for each of the namedTuples. | def _combineResults(result, *namedTuples):
""" Return a list of namedtuples from the result of a join query. A
single database result is partitioned at intervals corresponding to the
fields in namedTuples. The return value is the result of applying
namedtuple._make() to each of the partitions, for eac... |
Get all info about a job with model details if available. | def jobInfoWithModels(self, jobID):
""" Get all info about a job, with model details, if available.
Parameters:
----------------------------------------------------------------
job: jobID of the job to query
retval: A sequence of two-tuples if the jobID exists in the jobs
table (exe... |
Get all info about a job | def jobInfo(self, jobID):
""" Get all info about a job
Parameters:
----------------------------------------------------------------
job: jobID of the job to query
retval: namedtuple containing the job info.
"""
row = self._getOneMatchingRowWithRetries(
self._jobs, dict(job_id=job... |
Change the status on the given job | def jobSetStatus(self, jobID, status, useConnectionID=True,):
""" Change the status on the given job
Parameters:
----------------------------------------------------------------
job: jobID of the job to change status
status: new status string (ClientJobsDAO.STATUS_xxxxx)
useConnecti... |
Change the status on the given job to completed | def jobSetCompleted(self, jobID, completionReason, completionMsg,
useConnectionID = True):
""" Change the status on the given job to completed
Parameters:
----------------------------------------------------------------
job: jobID of the job to mark as completed
... |
Cancel the given job. This will update the cancel field in the jobs table and will result in the job being cancelled. | def jobCancel(self, jobID):
""" Cancel the given job. This will update the cancel field in the
jobs table and will result in the job being cancelled.
Parameters:
----------------------------------------------------------------
jobID: jobID of the job to mark as completed
to Fal... |
Fetch all the modelIDs that correspond to a given jobID ; empty sequence if none | def jobGetModelIDs(self, jobID):
"""Fetch all the modelIDs that correspond to a given jobID; empty sequence
if none"""
rows = self._getMatchingRowsWithRetries(self._models, dict(job_id=jobID),
['model_id'])
return [r[0] for r in rows] |
Return the number of jobs for the given clientInfo and a status that is not completed. | def getActiveJobCountForClientInfo(self, clientInfo):
""" Return the number of jobs for the given clientInfo and a status that is
not completed.
"""
with ConnectionFactory.get() as conn:
query = 'SELECT count(job_id) ' \
'FROM %s ' \
'WHERE client_info = %%s ' \
... |
Return the number of jobs for the given clientKey and a status that is not completed. | def getActiveJobCountForClientKey(self, clientKey):
""" Return the number of jobs for the given clientKey and a status that is
not completed.
"""
with ConnectionFactory.get() as conn:
query = 'SELECT count(job_id) ' \
'FROM %s ' \
'WHERE client_key = %%s ' \
... |
Fetch jobIDs for jobs in the table with optional fields given a specific clientInfo | def getActiveJobsForClientInfo(self, clientInfo, fields=[]):
""" Fetch jobIDs for jobs in the table with optional fields given a
specific clientInfo """
# Form the sequence of field name strings that will go into the
# request
dbFields = [self._jobs.pubToDBNameDict[x] for x in fields]
dbFields... |
Helper function for querying the models table including relevant job info where the job type matches the specified jobType. Only records for which there is a matching jobId in both tables is returned and only the requested fields are returned in each result assuming that there is not a conflict. This function is useful... | def getFieldsForActiveJobsOfType(self, jobType, fields=[]):
""" Helper function for querying the models table including relevant job
info where the job type matches the specified jobType. Only records for
which there is a matching jobId in both tables is returned, and only the
requested fields are retu... |
Fetch the values of 1 or more fields from a job record. Here fields is a list with the names of the fields to fetch. The names are the public names of the fields ( camelBack not the lower_case_only form as stored in the DB ). | def jobGetFields(self, jobID, fields):
""" Fetch the values of 1 or more fields from a job record. Here, 'fields'
is a list with the names of the fields to fetch. The names are the public
names of the fields (camelBack, not the lower_case_only form as stored in
the DB).
Parameters:
------------... |
Fetch the values of 1 or more fields from a sequence of job records. Here fields is a sequence ( list or tuple ) with the names of the fields to fetch. The names are the public names of the fields ( camelBack not the lower_case_only form as stored in the DB ). | def jobsGetFields(self, jobIDs, fields, requireAll=True):
""" Fetch the values of 1 or more fields from a sequence of job records.
Here, 'fields' is a sequence (list or tuple) with the names of the fields to
fetch. The names are the public names of the fields (camelBack, not the
lower_case_only form as ... |
Change the values of 1 or more fields in a job. Here fields is a dict with the name/ value pairs to change. The names are the public names of the fields ( camelBack not the lower_case_only form as stored in the DB ). This method is for private use by the ClientJobManager only. | def jobSetFields(self, jobID, fields, useConnectionID=True,
ignoreUnchanged=False):
""" Change the values of 1 or more fields in a job. Here, 'fields' is a
dict with the name/value pairs to change. The names are the public names of
the fields (camelBack, not the lower_case_only form as st... |
Change the value of 1 field in a job to newValue but only if the current value matches curValue. The fieldName is the public name of the field ( camelBack not the lower_case_only form as stored in the DB ). | def jobSetFieldIfEqual(self, jobID, fieldName, newValue, curValue):
""" Change the value of 1 field in a job to 'newValue', but only if the
current value matches 'curValue'. The 'fieldName' is the public name of
the field (camelBack, not the lower_case_only form as stored in the DB).
This method is use... |
Incremet the value of 1 field in a job by increment. The fieldName is the public name of the field ( camelBack not the lower_case_only form as stored in the DB ). | def jobIncrementIntField(self, jobID, fieldName, increment=1,
useConnectionID=False):
""" Incremet the value of 1 field in a job by increment. The 'fieldName' is
the public name of the field (camelBack, not the lower_case_only form as
stored in the DB).
This method is used fo... |
Update the results string and last - update - time fields of a model. | def jobUpdateResults(self, jobID, results):
""" Update the results string and last-update-time fields of a model.
Parameters:
----------------------------------------------------------------
jobID: job ID of model to modify
results: new results (json dict string)
"""
with Connection... |
Delete all models from the models table | def modelsClearAll(self):
""" Delete all models from the models table
Parameters:
----------------------------------------------------------------
"""
self._logger.info('Deleting all rows from models table %r',
self.modelsTableName)
with ConnectionFactory.get() as conn:
... |
Insert a new unique model ( based on params ) into the model table in the running state. This will return two things: whether or not the model was actually inserted ( i. e. that set of params isn t already in the table ) and the modelID chosen for that set of params. Even if the model was not inserted by this call ( it... | def modelInsertAndStart(self, jobID, params, paramsHash, particleHash=None):
""" Insert a new unique model (based on params) into the model table in the
"running" state. This will return two things: whether or not the model was
actually inserted (i.e. that set of params isn't already in the table) and
t... |
Get ALL info for a set of models | def modelsInfo(self, modelIDs):
""" Get ALL info for a set of models
WARNING!!!: The order of the results are NOT necessarily in the same order as
the order of the model IDs passed in!!!
Parameters:
----------------------------------------------------------------
modelIDs: list of model IDs... |
Fetch the values of 1 or more fields from a sequence of model records. Here fields is a list with the names of the fields to fetch. The names are the public names of the fields ( camelBack not the lower_case_only form as stored in the DB ). | def modelsGetFields(self, modelIDs, fields):
""" Fetch the values of 1 or more fields from a sequence of model records.
Here, 'fields' is a list with the names of the fields to fetch. The names
are the public names of the fields (camelBack, not the lower_case_only form
as stored in the DB).
WARNING... |
Gets the specified fields for all the models for a single job. This is similar to modelsGetFields | def modelsGetFieldsForJob(self, jobID, fields, ignoreKilled=False):
""" Gets the specified fields for all the models for a single job. This is
similar to modelsGetFields
Parameters:
----------------------------------------------------------------
jobID: jobID for the models to be searc... |
Gets fields from all models in a job that have been checkpointed. This is used to figure out whether or not a new model should be checkpointed. | def modelsGetFieldsForCheckpointed(self, jobID, fields):
"""
Gets fields from all models in a job that have been checkpointed. This is
used to figure out whether or not a new model should be checkpointed.
Parameters:
-----------------------------------------------------------------------
jobID:... |
Change the values of 1 or more fields in a model. Here fields is a dict with the name/ value pairs to change. The names are the public names of the fields ( camelBack not the lower_case_only form as stored in the DB ). | def modelSetFields(self, modelID, fields, ignoreUnchanged = False):
""" Change the values of 1 or more fields in a model. Here, 'fields' is a
dict with the name/value pairs to change. The names are the public names of
the fields (camelBack, not the lower_case_only form as stored in the DB).
Parameters:... |
Get the params and paramsHash for a set of models. | def modelsGetParams(self, modelIDs):
""" Get the params and paramsHash for a set of models.
WARNING!!!: The order of the results are NOT necessarily in the same order as
the order of the model IDs passed in!!!
Parameters:
----------------------------------------------------------------
modelID... |
Get the results string and other status fields for a set of models. | def modelsGetResultAndStatus(self, modelIDs):
""" Get the results string and other status fields for a set of models.
WARNING!!!: The order of the results are NOT necessarily in the same order
as the order of the model IDs passed in!!!
For each model, this returns a tuple containing:
(modelID, re... |
Return info on all of the models that are in already in the models table for a given job. For each model this returns a tuple containing: ( modelID updateCounter ). | def modelsGetUpdateCounters(self, jobID):
""" Return info on all of the models that are in already in the models
table for a given job. For each model, this returns a tuple
containing: (modelID, updateCounter).
Note that we don't return the results for all models, since the results
string could be ... |
Update the results string and/ or num_records fields of a model. This will fail if the model does not currently belong to this client ( connection_id doesn t match ). | def modelUpdateResults(self, modelID, results=None, metricValue =None,
numRecords=None):
""" Update the results string, and/or num_records fields of
a model. This will fail if the model does not currently belong to this
client (connection_id doesn't match).
Parameters:
----... |
Mark a model as completed with the given completionReason and completionMsg. This will fail if the model does not currently belong to this client ( connection_id doesn t match ). | def modelSetCompleted(self, modelID, completionReason, completionMsg,
cpuTime=0, useConnectionID=True):
""" Mark a model as completed, with the given completionReason and
completionMsg. This will fail if the model does not currently belong to this
client (connection_id doesn't match)... |
Look through the models table for an orphaned model which is a model that is not completed yet whose _eng_last_update_time is more than maxUpdateInterval seconds ago. | def modelAdoptNextOrphan(self, jobId, maxUpdateInterval):
""" Look through the models table for an orphaned model, which is a model
that is not completed yet, whose _eng_last_update_time is more than
maxUpdateInterval seconds ago.
If one is found, change its _eng_worker_conn_id to the current worker's
... |
profiling performance of SpatialPooler ( SP ) using the python cProfile module and ordered by cumulative time see how to run on command - line above. | def profileSP(spClass, spDim, nRuns):
"""
profiling performance of SpatialPooler (SP)
using the python cProfile module and ordered by cumulative time,
see how to run on command-line above.
@param spClass implementation of SP (cpp, py, ..)
@param spDim number of columns in SP (in 1D, for 2D see colDim in co... |
Overrides: meth: nupic. bindings. regions. PyRegion. PyRegion. getSpec. | def getSpec(cls):
"""
Overrides :meth:`nupic.bindings.regions.PyRegion.PyRegion.getSpec`.
"""
ns = dict(
description=KNNClassifierRegion.__doc__,
singleNodeOnly=True,
inputs=dict(
categoryIn=dict(
description='Vector of zero or more category indices for this... |
Initialize attributes that are not saved with the checkpoint. | def _initEphemerals(self):
"""
Initialize attributes that are not saved with the checkpoint.
"""
self._firstComputeCall = True
self._accuracy = None
self._protoScores = None
self._categoryDistances = None
self._knn = knn_classifier.KNNClassifier(**self.knnParams)
for x in ('_partit... |
Overrides: meth: nupic. bindings. regions. PyRegion. PyRegion. getParameter. | def getParameter(self, name, index=-1):
"""
Overrides :meth:`nupic.bindings.regions.PyRegion.PyRegion.getParameter`.
"""
if name == "patternCount":
return self._knn._numPatterns
elif name == "patternMatrix":
return self._getPatternMatrix()
elif name == "k":
return self._knn.k
... |
Overrides: meth: nupic. bindings. regions. PyRegion. PyRegion. setParameter. | def setParameter(self, name, index, value):
"""
Overrides :meth:`nupic.bindings.regions.PyRegion.PyRegion.setParameter`.
"""
if name == "learningMode":
self.learningMode = bool(int(value))
self._epoch = 0
elif name == "inferenceMode":
self._epoch = 0
if int(value) and not sel... |
Begin writing output tap files. | def enableTap(self, tapPath):
"""
Begin writing output tap files.
:param tapPath: (string) base name of the output tap files to write.
"""
self._tapFileIn = open(tapPath + '.in', 'w')
self._tapFileOut = open(tapPath + '.out', 'w') |
Disable writing of output tap files. | def disableTap(self):
"""
Disable writing of output tap files.
"""
if self._tapFileIn is not None:
self._tapFileIn.close()
self._tapFileIn = None
if self._tapFileOut is not None:
self._tapFileOut.close()
self._tapFileOut = None |
Write inputs to output tap file.: param inputs: ( iter ) some inputs. | def handleLogInput(self, inputs):
"""
Write inputs to output tap file.
:param inputs: (iter) some inputs.
"""
if self._tapFileIn is not None:
for input in inputs:
for k in range(len(input)):
print >> self._tapFileIn, input[k],
print >> self._tapFileIn |
Write outputs to output tap file. | def handleLogOutput(self, output):
"""
Write outputs to output tap file.
:param outputs: (iter) some outputs.
"""
#raise Exception('MULTI-LINE DUMMY\nMULTI-LINE DUMMY')
if self._tapFileOut is not None:
for k in range(len(output)):
print >> self._tapFileOut, output[k],
print ... |
Store a training sample and associated category label | def _storeSample(self, inputVector, trueCatIndex, partition=0):
"""
Store a training sample and associated category label
"""
# If this is the first sample, then allocate a numpy array
# of the appropriate size in which to store all samples.
if self._samples is None:
self._samples = numpy... |
Process one input sample. This method is called by the runtime engine. | def compute(self, inputs, outputs):
"""
Process one input sample. This method is called by the runtime engine.
.. note:: the number of input categories may vary, but the array size is
fixed to the max number of categories allowed (by a lower region), so
"unused" indices of the input categor... |
Does nothing. Kept here for API compatibility | def _finishLearning(self):
"""Does nothing. Kept here for API compatibility """
if self._doSphering:
self._finishSphering()
self._knn.finishLearning()
# Compute leave-one-out validation accuracy if
# we actually received non-trivial partition info
self._accuracy = None |
Compute normalization constants for each feature dimension based on the collected training samples. Then normalize our training samples using these constants ( so that each input dimension has mean and variance of zero and one respectively. ) Then feed these sphered training samples into the underlying SVM model. | def _finishSphering(self):
"""
Compute normalization constants for each feature dimension
based on the collected training samples. Then normalize our
training samples using these constants (so that each input
dimension has mean and variance of zero and one, respectively.)
Then feed these "spher... |
Overrides: meth: nupic. bindings. regions. PyRegion. PyRegion. getOutputElementCount. | def getOutputElementCount(self, name):
"""
Overrides :meth:`nupic.bindings.regions.PyRegion.PyRegion.getOutputElementCount`.
"""
if name == 'categoriesOut':
return self.maxCategoryCount
elif name == 'categoryProbabilitiesOut':
return self.maxCategoryCount
elif name == 'bestPrototypeI... |
Generate requested statistics for a dataset and cache to a file. If filename is None then don t cache to a file | def generateStats(filename, statsInfo, maxSamples = None, filters=[], cache=True):
"""Generate requested statistics for a dataset and cache to a file.
If filename is None, then don't cache to a file"""
# Sanity checking
if not isinstance(statsInfo, dict):
raise RuntimeError("statsInfo must be a dict -- "
... |
Return a dict that can be used to create an anomaly model via: meth: nupic. frameworks. opf. model_factory. ModelFactory. create. | def getScalarMetricWithTimeOfDayAnomalyParams(metricData,
minVal=None,
maxVal=None,
minResolution=None,
tmImplementation = "cpp"):
"""... |
Return reasonable min/ max values to use given the data. | def _rangeGen(data, std=1):
"""
Return reasonable min/max values to use given the data.
"""
dataStd = np.std(data)
if dataStd == 0:
dataStd = 1
minval = np.min(data) - std * dataStd
maxval = np.max(data) + std * dataStd
return minval, maxval |
Given model params figure out the correct parameters for the RandomDistributed encoder. Modifies params in place. | def _fixupRandomEncoderParams(params, minVal, maxVal, minResolution):
"""
Given model params, figure out the correct parameters for the
RandomDistributed encoder. Modifies params in place.
"""
encodersDict = (
params["modelConfig"]["modelParams"]["sensorParams"]["encoders"]
)
for encoder in encodersD... |
Intercepts TemporalMemory deserialization request in order to initialize TemporalMemoryMonitorMixin state | def read(cls, proto):
"""
Intercepts TemporalMemory deserialization request in order to initialize
`TemporalMemoryMonitorMixin` state
@param proto (DynamicStructBuilder) Proto object
@return (TemporalMemory) TemporalMemory shim instance
"""
tm = super(TemporalMemoryMonitorMixin, cls).read(... |
Intercepts TemporalMemory deserialization request in order to initialize self. infActiveState | def read(cls, proto):
"""
Intercepts TemporalMemory deserialization request in order to initialize
`self.infActiveState`
@param proto (DynamicStructBuilder) Proto object
@return (TemporalMemory) TemporalMemory shim instance
"""
tm = super(TMShimMixin, cls).read(proto)
tm.infActiveState... |
( From backtracking_tm. py ) Top - down compute - generate expected input given output of the TM | def topDownCompute(self, topDownIn=None):
"""
(From `backtracking_tm.py`)
Top-down compute - generate expected input given output of the TM
@param topDownIn top down input from the level above us
@returns best estimate of the TM input that would have generated bottomUpOut.
"""
output = num... |
Intercepts TemporalMemory deserialization request in order to initialize self. infActiveState | def read(cls, proto):
"""
Intercepts TemporalMemory deserialization request in order to initialize
`self.infActiveState`
@param proto (DynamicStructBuilder) Proto object
@return (TemporalMemory) TemporalMemory shim instance
"""
tm = super(MonitoredTMShim, cls).read(proto)
tm.infActiveS... |
( From backtracking_tm. py ) Handle one compute possibly learning. | def compute(self, bottomUpInput, enableLearn, computeInfOutput=None):
"""
(From `backtracking_tm.py`)
Handle one compute, possibly learning.
@param bottomUpInput The bottom-up input, typically from a spatial pooler
@param enableLearn If true, perform learning
@param computeInfOutput ... |
Pick a value according to the provided distribution. | def pickByDistribution(distribution, r=None):
"""
Pick a value according to the provided distribution.
Example:
::
pickByDistribution([.2, .1])
Returns 0 two thirds of the time and 1 one third of the time.
:param distribution: Probability distribution. Need not be normalized.
:param r: Instance o... |
Returns an array of length size and type dtype that is everywhere 0 except in the index in pos. | def Indicator(pos, size, dtype):
"""
Returns an array of length size and type dtype that is everywhere 0,
except in the index in pos.
:param pos: (int) specifies the position of the one entry that will be set.
:param size: (int) The total size of the array to be returned.
:param dtype: The element type (co... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.