INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Set multiple custom properties and persist them to the custom configuration store. | def setCustomProperties(cls, properties):
""" Set multiple custom properties and persist them to the custom
configuration store.
Parameters:
----------------------------------------------------------------
properties: a dict of property name/value pairs to set
"""
_getLogger().info("Setting... |
Clear all configuration properties from in - memory cache but do NOT alter the custom configuration file. Used in unit - testing. | def clear(cls):
""" Clear all configuration properties from in-memory cache, but do NOT
alter the custom configuration file. Used in unit-testing.
"""
# Clear the in-memory settings cache, forcing reload upon subsequent "get"
# request.
super(Configuration, cls).clear()
# Reset in-memory cu... |
Clear all custom configuration settings and delete the persistent custom configuration store. | def resetCustomConfig(cls):
""" Clear all custom configuration settings and delete the persistent
custom configuration store.
"""
_getLogger().info("Resetting all custom configuration properties; "
"caller=%r", traceback.format_stack())
# Clear the in-memory settings cache, fo... |
If persistent is True delete the temporary file | def clear(cls, persistent=False):
""" If persistent is True, delete the temporary file
Parameters:
----------------------------------------------------------------
persistent: if True, custom configuration file is deleted
"""
if persistent:
try:
os.unlink(cls.getPath())
exce... |
Returns a dict of all temporary values in custom configuration file | def getCustomDict(cls):
""" Returns a dict of all temporary values in custom configuration file
"""
if not os.path.exists(cls.getPath()):
return dict()
properties = Configuration._readConfigFile(os.path.basename(
cls.getPath()), os.path.dirname(cls.getPath()))
values = dict()
for ... |
Edits the XML configuration file with the parameters specified by properties | def edit(cls, properties):
""" Edits the XML configuration file with the parameters specified by
properties
Parameters:
----------------------------------------------------------------
properties: dict of settings to be applied to the custom configuration store
(key is property nam... |
Sets the path of the custom configuration file | def _setPath(cls):
""" Sets the path of the custom configuration file
"""
cls._path = os.path.join(os.environ['NTA_DYNAMIC_CONF_DIR'],
cls.customFileName) |
Get the particle state as a dict. This is enough information to instantiate this particle on another worker. | def getState(self):
"""Get the particle state as a dict. This is enough information to
instantiate this particle on another worker."""
varStates = dict()
for varName, var in self.permuteVars.iteritems():
varStates[varName] = var.getState()
return dict(id=self.particleId,
genId... |
Init all of our variable positions velocities and optionally the best result and best position from the given particle. | def initStateFrom(self, particleId, particleState, newBest):
"""Init all of our variable positions, velocities, and optionally the best
result and best position from the given particle.
If newBest is true, we get the best result and position for this new
generation from the resultsDB, This is used when... |
Copy specific variables from particleState into this particle. | def copyVarStatesFrom(self, particleState, varNames):
"""Copy specific variables from particleState into this particle.
Parameters:
--------------------------------------------------------------
particleState: dict produced by a particle's getState() method
varNames: which variab... |
Return the position of this particle. This returns a dict () of key value pairs where each key is the name of the flattened permutation variable and the value is its chosen value. | def getPosition(self):
"""Return the position of this particle. This returns a dict() of key
value pairs where each key is the name of the flattened permutation
variable and the value is its chosen value.
Parameters:
--------------------------------------------------------------
retval: dic... |
Return the position of a particle given its state dict. | def getPositionFromState(pState):
"""Return the position of a particle given its state dict.
Parameters:
--------------------------------------------------------------
retval: dict() of particle position, keys are the variable names,
values are their positions
"""
result =... |
Agitate this particle so that it is likely to go to a new position. Every time agitate is called the particle is jiggled an even greater amount. | def agitate(self):
"""Agitate this particle so that it is likely to go to a new position.
Every time agitate is called, the particle is jiggled an even greater
amount.
Parameters:
--------------------------------------------------------------
retval: None
"""
for (varName,... |
Choose a new position based on results obtained so far from all other particles. | def newPosition(self, whichVars=None):
# TODO: incorporate data from choice variables....
# TODO: make sure we're calling this when appropriate.
"""Choose a new position based on results obtained so far from all other
particles.
Parameters:
------------------------------------------------------... |
Generates a random sample from the discrete probability distribution and returns its value the log of the probability of sampling that value and the log of the probability of sampling the current value ( passed in ). | def propose(self, current, r):
"""Generates a random sample from the discrete probability distribution and
returns its value, the log of the probability of sampling that value and the
log of the probability of sampling the current value (passed in).
"""
stay = (r.uniform(0, 1) < self.kernel)
if ... |
Generates a random sample from the Poisson probability distribution with with location and scale parameter equal to the current value ( passed in ). Returns the value of the random sample the log of the probability of sampling that value and the log of the probability of sampling the current value if the roles of the n... | def propose(self, current, r):
"""Generates a random sample from the Poisson probability distribution with
with location and scale parameter equal to the current value (passed in).
Returns the value of the random sample, the log of the probability of
sampling that value, and the log of the probability o... |
Get the logger for this object. | def __getLogger(cls):
""" Get the logger for this object.
:returns: (Logger) A Logger object.
"""
if cls.__logger is None:
cls.__logger = opf_utils.initLogger(cls)
return cls.__logger |
Create a new model instance given a description dictionary. | def create(modelConfig, logLevel=logging.ERROR):
""" Create a new model instance, given a description dictionary.
:param modelConfig: (dict)
A dictionary describing the current model,
`described here <../../quick-start/example-model-params.html>`_.
:param logLevel: (int) The level of... |
Load saved model. | def loadFromCheckpoint(savedModelDir, newSerialization=False):
""" Load saved model.
:param savedModelDir: (string)
Directory of where the experiment is to be or was saved
:returns: (:class:`nupic.frameworks.opf.model.Model`) The loaded model
instance.
"""
if newSerializati... |
Perform one time step of the Temporal Memory algorithm. | def compute(self, activeColumns, learn=True):
"""
Perform one time step of the Temporal Memory algorithm.
This method calls :meth:`activateCells`, then calls
:meth:`activateDendrites`. Using :class:`TemporalMemory` via its
:meth:`compute` method ensures that you'll always be able to call
:me... |
Calculate the active cells using the current active columns and dendrite segments. Grow and reinforce synapses. | def activateCells(self, activeColumns, learn=True):
"""
Calculate the active cells, using the current active columns and dendrite
segments. Grow and reinforce synapses.
:param activeColumns: (iter) A sorted list of active column indices.
:param learn: (bool) If true, reinforce / punish / grow syna... |
Calculate dendrite segment activity using the current active cells. | def activateDendrites(self, learn=True):
"""
Calculate dendrite segment activity, using the current active cells.
:param learn: (bool) If true, segment activations will be recorded. This
information is used during segment cleanup.
**Pseudocode:**
::
for each distal dendrite... |
Indicates the start of a new sequence. Clears any predictions and makes sure synapses don t grow to the currently active cells in the next time step. | def reset(self):
"""
Indicates the start of a new sequence. Clears any predictions and makes sure
synapses don't grow to the currently active cells in the next time step.
"""
self.activeCells = []
self.winnerCells = []
self.activeSegments = []
self.matchingSegments = [] |
Determines which cells in a predicted column should be added to winner cells list and learns on the segments that correctly predicted this column. | def activatePredictedColumn(self, column, columnActiveSegments,
columnMatchingSegments, prevActiveCells,
prevWinnerCells, learn):
"""
Determines which cells in a predicted column should be added to winner cells
list, and learns on the segments that... |
Punishes the Segments that incorrectly predicted a column to be active. | def punishPredictedColumn(self, column, columnActiveSegments,
columnMatchingSegments, prevActiveCells,
prevWinnerCells):
"""
Punishes the Segments that incorrectly predicted a column to be active.
:param column: (int) Index of bursting column.
:p... |
Create a: class: ~nupic. algorithms. connections. Segment on the specified cell. This method calls: meth: ~nupic. algorithms. connections. Connections. createSegment on the underlying: class: ~nupic. algorithms. connections. Connections and it does some extra bookkeeping. Unit tests should call this method and not: met... | def createSegment(self, cell):
"""
Create a :class:`~nupic.algorithms.connections.Segment` on the specified
cell. This method calls
:meth:`~nupic.algorithms.connections.Connections.createSegment` on the
underlying :class:`~nupic.algorithms.connections.Connections`, and it does
some extra boo... |
: param connections: ( Object ) Connections for the TM. Gets mutated. | def _activatePredictedColumn(cls, connections, random, columnActiveSegments,
prevActiveCells, prevWinnerCells,
numActivePotentialSynapsesForSegment,
maxNewSynapseCount, initialPermanence,
permanen... |
: param connections: ( Object ) Connections for the TM. Gets mutated. | def _burstColumn(cls, connections, random, lastUsedIterationForSegment,
column, columnMatchingSegments, prevActiveCells,
prevWinnerCells, cellsForColumn,
numActivePotentialSynapsesForSegment, iteration,
maxNewSynapseCount, initialPermanence, pe... |
: param connections: ( Object ) Connections for the TM. Gets mutated. | def _punishPredictedColumn(cls, connections, columnMatchingSegments,
prevActiveCells, predictedSegmentDecrement):
"""
:param connections: (Object)
Connections for the TM. Gets mutated.
:param columnMatchingSegments: (iter)
Matching segments for this column.
:param ... |
Create a segment on the connections enforcing the maxSegmentsPerCell parameter. | def _createSegment(cls, connections, lastUsedIterationForSegment, cell,
iteration, maxSegmentsPerCell):
"""
Create a segment on the connections, enforcing the maxSegmentsPerCell
parameter.
"""
# Enforce maxSegmentsPerCell.
while connections.numSegments(cell) >= maxSegmentsPe... |
Destroy nDestroy synapses on the specified segment but don t destroy synapses to the excludeCells. | def _destroyMinPermanenceSynapses(cls, connections, random, segment,
nDestroy, excludeCells):
"""
Destroy nDestroy synapses on the specified segment, but don't destroy
synapses to the "excludeCells".
"""
destroyCandidates = sorted(
(synapse for synapse in c... |
Gets the cell with the smallest number of segments. Break ties randomly. | def _leastUsedCell(cls, random, cells, connections):
"""
Gets the cell with the smallest number of segments.
Break ties randomly.
:param random: (Object)
Random number generator. Gets mutated.
:param cells: (list)
Indices of cells.
:param connections: (Object)
Connections instance... |
Creates nDesiredNewSynapes synapses on the segment passed in if possible choosing random cells from the previous winner cells that are not already on the segment. | def _growSynapses(cls, connections, random, segment, nDesiredNewSynapes,
prevWinnerCells, initialPermanence, maxSynapsesPerSegment):
"""
Creates nDesiredNewSynapes synapses on the segment passed in if
possible, choosing random cells from the previous winner cells that are
not already... |
Updates synapses on segment. Strengthens active synapses ; weakens inactive synapses. | def _adaptSegment(cls, connections, segment, prevActiveCells,
permanenceIncrement, permanenceDecrement):
"""
Updates synapses on segment.
Strengthens active synapses; weakens inactive synapses.
:param connections: (Object) Connections instance for the tm
:param segment:... |
Returns the index of the column that a cell belongs to. | def columnForCell(self, cell):
"""
Returns the index of the column that a cell belongs to.
:param cell: (int) Cell index
:returns: (int) Column index
"""
self._validateCell(cell)
return int(cell / self.cellsPerColumn) |
Returns the indices of cells that belong to a column. | def cellsForColumn(self, column):
"""
Returns the indices of cells that belong to a column.
:param column: (int) Column index
:returns: (list) Cell indices
"""
self._validateColumn(column)
start = self.cellsPerColumn * column
end = start + self.cellsPerColumn
return range(start, e... |
Maps cells to the columns they belong to. | def mapCellsToColumns(self, cells):
"""
Maps cells to the columns they belong to.
:param cells: (set) Cells
:returns: (dict) Mapping from columns to their cells in `cells`
"""
cellsForColumns = defaultdict(set)
for cell in cells:
column = self.columnForCell(cell)
cellsForColum... |
Returns the indices of the predictive cells. | def getPredictiveCells(self):
""" Returns the indices of the predictive cells.
:returns: (list) Indices of predictive cells.
"""
previousCell = None
predictiveCells = []
for segment in self.activeSegments:
if segment.cell != previousCell:
predictiveCells.append(segment.cell)
... |
Writes serialized data to proto object. | def write(self, proto):
"""
Writes serialized data to proto object.
:param proto: (DynamicStructBuilder) Proto object
"""
# capnp fails to save a tuple. Let's force columnDimensions to list.
proto.columnDimensions = list(self.columnDimensions)
proto.cellsPerColumn = self.cellsPerColumn
... |
Reads deserialized data from proto object. | def read(cls, proto):
"""
Reads deserialized data from proto object.
:param proto: (DynamicStructBuilder) Proto object
:returns: (:class:TemporalMemory) TemporalMemory instance
"""
tm = object.__new__(cls)
# capnp fails to save a tuple, so proto.columnDimensions was forced to
# serial... |
Generate a sequence from a list of numbers. | def generateFromNumbers(self, numbers):
"""
Generate a sequence from a list of numbers.
Note: Any `None` in the list of numbers is considered a reset.
@param numbers (list) List of numbers
@return (list) Generated sequence
"""
sequence = []
for number in numbers:
if number == N... |
Add spatial noise to each pattern in the sequence. | def addSpatialNoise(self, sequence, amount):
"""
Add spatial noise to each pattern in the sequence.
@param sequence (list) Sequence
@param amount (float) Amount of spatial noise
@return (list) Sequence with spatial noise
"""
newSequence = []
for pattern in sequence:
if patter... |
Pretty print a sequence. | def prettyPrintSequence(self, sequence, verbosity=1):
"""
Pretty print a sequence.
@param sequence (list) Sequence
@param verbosity (int) Verbosity level
@return (string) Pretty-printed text
"""
text = ""
for i in xrange(len(sequence)):
pattern = sequence[i]
if pattern ... |
compute Receiver operating characteristic ( ROC ) | def ROCCurve(y_true, y_score):
"""compute Receiver operating characteristic (ROC)
Note: this implementation is restricted to the binary classification task.
Parameters
----------
y_true : array, shape = [n_samples]
true binary labels
y_score : array, shape = [n_samples]
targe... |
Compute Area Under the Curve ( AUC ) using the trapezoidal rule | def AreaUnderCurve(x, y):
"""Compute Area Under the Curve (AUC) using the trapezoidal rule
Parameters
----------
x : array, shape = [n]
x coordinates
y : array, shape = [n]
y coordinates
Returns
-------
auc : float
Examples
--------
>>> import numpy as np
... |
Returns pretty - printed table of traces. | def mmPrettyPrintTraces(traces, breakOnResets=None):
"""
Returns pretty-printed table of traces.
@param traces (list) Traces to print in table
@param breakOnResets (BoolsTrace) Trace of resets to break table on
@return (string) Pretty-printed table of traces.
"""
assert len(traces) > 0, "N... |
Returns pretty - printed table of metrics. | def mmPrettyPrintMetrics(metrics, sigFigs=5):
"""
Returns pretty-printed table of metrics.
@param metrics (list) Traces to print in table
@param sigFigs (int) Number of significant figures to print
@return (string) Pretty-printed table of metrics.
"""
assert len(metrics) > 0, "No metrics ... |
Returns plot of the cell activity. Note that if many timesteps of activities are input matplotlib s image interpolation may omit activities ( columns in the image ). | def mmGetCellTracePlot(self, cellTrace, cellCount, activityType, title="",
showReset=False, resetShading=0.25):
"""
Returns plot of the cell activity. Note that if many timesteps of
activities are input, matplotlib's image interpolation may omit activities
(columns in the image)... |
Given a series of anomaly scores compute the likelihood for each score. This function should be called once on a bunch of historical anomaly scores for an initial estimate of the distribution. It should be called again every so often ( say every 50 records ) to update the estimate. | def estimateAnomalyLikelihoods(anomalyScores,
averagingWindow=10,
skipRecords=0,
verbosity=0):
"""
Given a series of anomaly scores, compute the likelihood for each score. This
function should be called once on a bunch of... |
Compute updated probabilities for anomalyScores using the given params. | def updateAnomalyLikelihoods(anomalyScores,
params,
verbosity=0):
"""
Compute updated probabilities for anomalyScores using the given params.
:param anomalyScores: a list of records. Each record is a list with the
following three e... |
Filter the list of raw ( pre - filtered ) likelihoods so that we only preserve sharp increases in likelihood. likelihoods can be a numpy array of floats or a list of floats. | def _filterLikelihoods(likelihoods,
redThreshold=0.99999, yellowThreshold=0.999):
"""
Filter the list of raw (pre-filtered) likelihoods so that we only preserve
sharp increases in likelihood. 'likelihoods' can be a numpy array of floats or
a list of floats.
:returns: A new list of floa... |
Given a list of anomaly scores return a list of averaged records. anomalyScores is assumed to be a list of records of the form: [ datetime. datetime ( 2013 8 10 23 0 ) 6. 0 1. 0 ] | def _anomalyScoreMovingAverage(anomalyScores,
windowSize=10,
verbosity=0,
):
"""
Given a list of anomaly scores return a list of averaged records.
anomalyScores is assumed to be a list of records of the form:
... |
: param sampleData:: type sampleData: Numpy array.: param performLowerBoundCheck:: type performLowerBoundCheck: bool: returns: A dict containing the parameters of a normal distribution based on the sampleData. | def estimateNormal(sampleData, performLowerBoundCheck=True):
"""
:param sampleData:
:type sampleData: Numpy array.
:param performLowerBoundCheck:
:type performLowerBoundCheck: bool
:returns: A dict containing the parameters of a normal distribution based on
the ``sampleData``.
"""
params = {
"... |
Given the normal distribution specified by the mean and standard deviation in distributionParams return the probability of getting samples further from the mean. For values above the mean this is the probability of getting samples > x and for values below the mean the probability of getting samples < x. This is the Q -... | def tailProbability(x, distributionParams):
"""
Given the normal distribution specified by the mean and standard deviation
in distributionParams, return the probability of getting samples further
from the mean. For values above the mean, this is the probability of getting
samples > x and for values below the ... |
: returns: True if p is a valid estimator params as might be returned by estimateAnomalyLikelihoods () or updateAnomalyLikelihoods False otherwise. Just does some basic validation. | def isValidEstimatorParams(p):
"""
:returns: ``True`` if ``p`` is a valid estimator params as might be returned
by ``estimateAnomalyLikelihoods()`` or ``updateAnomalyLikelihoods``,
``False`` otherwise. Just does some basic validation.
"""
if not isinstance(p, dict):
return False
if "distribution"... |
Return the value of skipRecords for passing to estimateAnomalyLikelihoods | def _calcSkipRecords(numIngested, windowSize, learningPeriod):
"""Return the value of skipRecords for passing to estimateAnomalyLikelihoods
If `windowSize` is very large (bigger than the amount of data) then this
could just return `learningPeriod`. But when some values have fallen out of
the historical... |
capnp deserialization method for the anomaly likelihood object | def read(cls, proto):
""" capnp deserialization method for the anomaly likelihood object
:param proto: (Object) capnp proto object specified in
nupic.regions.anomaly_likelihood.capnp
:returns: (Object) the deserialized AnomalyLikelihood object
"""
# pylint: disable=W0212
... |
capnp serialization method for the anomaly likelihood object | def write(self, proto):
""" capnp serialization method for the anomaly likelihood object
:param proto: (Object) capnp proto object specified in
nupic.regions.anomaly_likelihood.capnp
"""
proto.iteration = self._iteration
pHistScores = proto.init('historicalScores', len(s... |
Compute the probability that the current value plus anomaly score represents an anomaly given the historical distribution of anomaly scores. The closer the number is to 1 the higher the chance it is an anomaly. | def anomalyProbability(self, value, anomalyScore, timestamp=None):
"""
Compute the probability that the current value plus anomaly score represents
an anomaly given the historical distribution of anomaly scores. The closer
the number is to 1, the higher the chance it is an anomaly.
:param value: th... |
Creates and returns the _IterationPhase - based instance corresponding to this phase specification | def _getImpl(self, model):
""" Creates and returns the _IterationPhase-based instance corresponding
to this phase specification
model: Model instance
"""
impl = _IterationPhaseLearnOnly(model=model,
nIters=self.__nIters)
return impl |
Creates and returns the _IterationPhase - based instance corresponding to this phase specification | def _getImpl(self, model):
""" Creates and returns the _IterationPhase-based instance corresponding
to this phase specification
model: Model instance
"""
impl = _IterationPhaseInferOnly(model=model,
nIters=self.__nIters,
... |
Replaces the Iteration Cycle phases | def replaceIterationCycle(self, phaseSpecs):
""" Replaces the Iteration Cycle phases
:param phaseSpecs: Iteration cycle description consisting of a sequence of
IterationPhaseSpecXXXXX elements that are performed in the
given order
"""
# -----------------------------... |
Processes the given record according to the current iteration cycle phase | def handleInputRecord(self, inputRecord):
"""
Processes the given record according to the current iteration cycle phase
:param inputRecord: (object) record expected to be returned from
:meth:`nupic.data.record_stream.RecordStreamIface.getNextRecord`.
:returns: :class:`nupic.frameworks.opf.o... |
Advance to the next iteration cycle phase | def __advancePhase(self):
""" Advance to the next iteration cycle phase
"""
self.__currentPhase = self.__phaseCycler.next()
self.__currentPhase.enterPhase()
return |
Processes the given record according to the current phase | def handleInputRecord(self, inputRecord):
""" Processes the given record according to the current phase
inputRecord: record object formatted according to
nupic.data.FileSource.getNext() result format.
Returns: An opf_utils.ModelResult object with the inputs and inferences
... |
Performs initialization that is necessary upon entry to the phase. Must be called before handleInputRecord () at the beginning of each phase | def enterPhase(self):
"""
Performs initialization that is necessary upon entry to the phase. Must
be called before handleInputRecord() at the beginning of each phase
"""
self.__iter = iter(xrange(self.__nIters))
# Prime the iterator
self.__iter.next() |
Advances the iteration ; | def advance(self):
""" Advances the iteration;
Returns: True if more iterations remain; False if this is the final
iteration.
"""
hasMore = True
try:
self.__iter.next()
except StopIteration:
self.__iter = None
hasMore = False
return hasMore |
[ _IterationPhase method implementation ] Performs initialization that is necessary upon entry to the phase. Must be called before handleInputRecord () at the beginning of each phase | def enterPhase(self):
""" [_IterationPhase method implementation]
Performs initialization that is necessary upon entry to the phase. Must
be called before handleInputRecord() at the beginning of each phase
"""
super(_IterationPhaseLearnOnly, self).enterPhase()
self.__model.enableLearning()
s... |
[ _IterationPhase method implementation ] Performs initialization that is necessary upon entry to the phase. Must be called before handleInputRecord () at the beginning of each phase | def enterPhase(self):
""" [_IterationPhase method implementation]
Performs initialization that is necessary upon entry to the phase. Must
be called before handleInputRecord() at the beginning of each phase
"""
super(_IterationPhaseInferCommon, self).enterPhase()
self._model.enableInference(infer... |
Serialize via capnp | def write(self, proto):
""" Serialize via capnp
:param proto: capnp PreviousValueModelProto message builder
"""
super(PreviousValueModel, self).writeBaseToProto(proto.modelBase)
proto.fieldNames = self._fieldNames
proto.fieldTypes = self._fieldTypes
if self._predictedField:
proto.pre... |
Deserialize via capnp | def read(cls, proto):
"""Deserialize via capnp
:param proto: capnp PreviousValueModelProto message reader
:returns: new instance of PreviousValueModel deserialized from the given
proto
"""
instance = object.__new__(cls)
super(PreviousValueModel, instance).__init__(proto=proto.mod... |
Accepts log - values as input exponentiates them computes the sum then converts the sum back to log - space and returns the result. Handles underflow by rescaling so that the largest values is exactly 1. 0. | def lscsum(lx, epsilon=None):
"""
Accepts log-values as input, exponentiates them, computes the sum,
then converts the sum back to log-space and returns the result.
Handles underflow by rescaling so that the largest values is exactly 1.0.
"""
lx = numpy.asarray(lx)
base = lx.max()
# If the input is the... |
Accepts log - values as input exponentiates them sums down the rows ( first dimension ) then converts the sum back to log - space and returns the result. Handles underflow by rescaling so that the largest values is exactly 1. 0. | def lscsum0(lx):
"""
Accepts log-values as input, exponentiates them, sums down the rows
(first dimension), then converts the sum back to log-space and returns the result.
Handles underflow by rescaling so that the largest values is exactly 1.0.
"""
# rows = lx.shape[0]
# columns = numpy.prod(lx.shape[1:]... |
Accepts log - values as input exponentiates them normalizes and returns the result. Handles underflow by rescaling so that the largest values is exactly 1. 0. | def normalize(lx):
"""
Accepts log-values as input, exponentiates them,
normalizes and returns the result.
Handles underflow by rescaling so that the largest values is exactly 1.0.
"""
lx = numpy.asarray(lx)
base = lx.max()
x = numpy.exp(lx - base)
result = x / x.sum()
conventional = (numpy.exp(lx)... |
Accepts log - values as input exponentiates them sums down the rows ( first dimension ) normalizes and returns the result. Handles underflow by rescaling so that the largest values is exactly 1. 0. | def nsum0(lx):
"""
Accepts log-values as input, exponentiates them, sums down the rows
(first dimension), normalizes and returns the result.
Handles underflow by rescaling so that the largest values is exactly 1.0.
"""
lx = numpy.asarray(lx)
base = lx.max()
x = numpy.exp(lx - base)
ssum = x.sum(0)
r... |
returns log ( exp ( A ) + exp ( B )). A and B are numpy arrays | def logSumExp(A, B, out=None):
""" returns log(exp(A) + exp(B)). A and B are numpy arrays"""
if out is None:
out = numpy.zeros(A.shape)
indicator1 = A >= B
indicator2 = numpy.logical_not(indicator1)
out[indicator1] = A[indicator1] + numpy.log1p(numpy.exp(B[indicator1]-A[indicator1]))
out[indicator2] ... |
returns log ( exp ( A ) - exp ( B )). A and B are numpy arrays. values in A should be greater than or equal to corresponding values in B | def logDiffExp(A, B, out=None):
""" returns log(exp(A) - exp(B)). A and B are numpy arrays. values in A should be
greater than or equal to corresponding values in B"""
if out is None:
out = numpy.zeros(A.shape)
indicator1 = A >= B
assert indicator1.all(), "Values in the first array should be greater tha... |
Return index of the field matching the field meta special value.: param fields: sequence of nupic. data. fieldmeta. FieldMetaInfo objects representing the fields of a stream: param special: one of the special field attribute values from nupic. data. fieldmeta. FieldMetaSpecial: returns: first zero - based index of the ... | def _getFieldIndexBySpecial(fields, special):
""" Return index of the field matching the field meta special value.
:param fields: sequence of nupic.data.fieldmeta.FieldMetaInfo objects
representing the fields of a stream
:param special: one of the special field attribute values from
nupic.data.fieldmeta.F... |
Encodes the given input row as a dict with the keys being the field names. This also adds in some meta fields: _category: The value from the category field ( if any ) _reset: True if the reset field was True ( if any ) _sequenceId: the value from the sequenceId field ( if any ) | def encode(self, inputRow):
"""Encodes the given input row as a dict, with the
keys being the field names. This also adds in some meta fields:
'_category': The value from the category field (if any)
'_reset': True if the reset field was True (if any)
'_sequenceId': the value from the sequenceI... |
Give the timestamp of a record ( a datetime object ) compute the record s timestamp index - this is the timestamp divided by the aggregation period. | def _computeTimestampRecordIdx(self, recordTS):
""" Give the timestamp of a record (a datetime object), compute the record's
timestamp index - this is the timestamp divided by the aggregation period.
Parameters:
------------------------------------------------------------------------
recordTS: da... |
Returns next available data record from the storage as a dict with the keys being the field names. This also adds in some meta fields: | def getNextRecordDict(self):
"""Returns next available data record from the storage as a dict, with the
keys being the field names. This also adds in some meta fields:
- ``_category``: The value from the category field (if any)
- ``_reset``: True if the reset field was True (if any)
- ``_sequ... |
If underlying implementation does not support min/ max stats collection or if a field type does not support min/ max ( non scalars ) the return value will be None. | def getFieldMin(self, fieldName):
"""
If underlying implementation does not support min/max stats collection,
or if a field type does not support min/max (non scalars), the return
value will be None.
:param fieldName: (string) name of field to get min
:returns: current minimum value for the fie... |
If underlying implementation does not support min/ max stats collection or if a field type does not support min/ max ( non scalars ) the return value will be None. | def getFieldMax(self, fieldName):
"""
If underlying implementation does not support min/max stats collection,
or if a field type does not support min/max (non scalars), the return
value will be None.
:param fieldName: (string) name of field to get max
:returns: current maximum value for the fie... |
Log msg % args with severity DEBUG. | def debug(self, msg, *args, **kwargs):
"""
Log 'msg % args' with severity 'DEBUG'.
To pass exception information, use the keyword argument exc_info with
a true value, e.g.
logger.debug("Houston, we have a %s", "thorny problem", exc_info=1)
"""
self._baseLogger.debug(self, self.getExtendedM... |
Log msg % args with severity INFO. | def info(self, msg, *args, **kwargs):
"""
Log 'msg % args' with severity 'INFO'.
To pass exception information, use the keyword argument exc_info with
a true value, e.g.
logger.info("Houston, we have a %s", "interesting problem", exc_info=1)
"""
self._baseLogger.info(self, self.getExtended... |
Log msg % args with severity WARNING. | def warning(self, msg, *args, **kwargs):
"""
Log 'msg % args' with severity 'WARNING'.
To pass exception information, use the keyword argument exc_info with
a true value, e.g.
logger.warning("Houston, we have a %s", "bit of a problem", exc_info=1)
"""
self._baseLogger.warning(self, self.ge... |
Log msg % args with severity ERROR. | def error(self, msg, *args, **kwargs):
"""
Log 'msg % args' with severity 'ERROR'.
To pass exception information, use the keyword argument exc_info with
a true value, e.g.
logger.error("Houston, we have a %s", "major problem", exc_info=1)
"""
self._baseLogger.error(self, self.getExtendedMs... |
Log msg % args with severity CRITICAL. | def critical(self, msg, *args, **kwargs):
"""
Log 'msg % args' with severity 'CRITICAL'.
To pass exception information, use the keyword argument exc_info with
a true value, e.g.
logger.critical("Houston, we have a %s", "major disaster", exc_info=1)
"""
self._baseLogger.critical(self, self.... |
Log msg % args with the integer severity level. | def log(self, level, msg, *args, **kwargs):
"""
Log 'msg % args' with the integer severity 'level'.
To pass exception information, use the keyword argument exc_info with
a true value, e.g.
logger.log(level, "We have a %s", "mysterious problem", exc_info=1)
"""
self._baseLogge... |
Initializes internal filter variables for further processing. Returns a tuple ( function to call parameters for the filter call ) | def initFilter(input, filterInfo = None):
""" Initializes internal filter variables for further processing.
Returns a tuple (function to call,parameters for the filter call)
The filterInfo is a dict. Here is an example structure:
{fieldName: {'min': x,
'max': y,
'type': 'cat... |
Takes a record and returns true if record meets filter criteria false otherwise | def _filterRecord(filterList, record):
""" Takes a record and returns true if record meets filter criteria,
false otherwise
"""
for (fieldIdx, fp, params) in filterList:
x = dict()
x['value'] = record[fieldIdx]
x['acceptValues'] = params['acceptValues']
x['min'] = params['min']
x['max'] = p... |
Returns sum of the elements in the list. Missing items are replaced with the mean value | def _aggr_sum(inList):
""" Returns sum of the elements in the list. Missing items are replaced with
the mean value
"""
aggrMean = _aggr_mean(inList)
if aggrMean == None:
return None
aggrSum = 0
for elem in inList:
if elem != SENTINEL_VALUE_FOR_MISSING_DATA:
aggrSum += elem
else:
a... |
Returns mean of non - None elements of the list | def _aggr_mean(inList):
""" Returns mean of non-None elements of the list
"""
aggrSum = 0
nonNone = 0
for elem in inList:
if elem != SENTINEL_VALUE_FOR_MISSING_DATA:
aggrSum += elem
nonNone += 1
if nonNone != 0:
return aggrSum / nonNone
else:
return None |
Returns most common value seen in the non - None elements of the list | def _aggr_mode(inList):
""" Returns most common value seen in the non-None elements of the list
"""
valueCounts = dict()
nonNone = 0
for elem in inList:
if elem == SENTINEL_VALUE_FOR_MISSING_DATA:
continue
nonNone += 1
if elem in valueCounts:
valueCounts[elem] += 1
else:
v... |
Weighted mean uses params ( must be the same size as inList ) and makes weighed mean of inList | def _aggr_weighted_mean(inList, params):
""" Weighted mean uses params (must be the same size as inList) and
makes weighed mean of inList"""
assert(len(inList) == len(params))
# If all weights are 0, then the value is not defined, return None (missing)
weightsSum = sum(params)
if weightsSum == 0:
retur... |
Generate a dataset of aggregated values | def generateDataset(aggregationInfo, inputFilename, outputFilename=None):
"""Generate a dataset of aggregated values
Parameters:
----------------------------------------------------------------------------
aggregationInfo: a dictionary that contains the following entries
- fields: a list of pairs. Each pai... |
Generate the filename for aggregated dataset | def getFilename(aggregationInfo, inputFile):
"""Generate the filename for aggregated dataset
The filename is based on the input filename and the
aggregation period.
Returns the inputFile if no aggregation required (aggregation
info has all 0's)
"""
# Find the actual file, with an absolute path
inputF... |
Add the aggregation period to the input time t and return a datetime object | def _getEndTime(self, t):
"""Add the aggregation period to the input time t and return a datetime object
Years and months are handled as aspecial case due to leap years
and months with different number of dates. They can't be converted
to a strict timedelta because a period of 3 months will have differ... |
Given the name of an aggregation function returns the function pointer and param. | def _getFuncPtrAndParams(self, funcName):
""" Given the name of an aggregation function, returns the function pointer
and param.
Parameters:
------------------------------------------------------------------------
funcName: a string (name of function) or funcPtr
retval: (funcPtr, param)
... |
Generate the aggregated output record | def _createAggregateRecord(self):
""" Generate the aggregated output record
Parameters:
------------------------------------------------------------------------
retval: outputRecord
"""
record = []
for i, (fieldIdx, aggFP, paramIdx) in enumerate(self._fields):
if aggFP is None: # t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.