Search is not available for this dataset
text
stringlengths
75
104k
def computeSaturationLevels(outputs, outputsShape, sparseForm=False): """ Compute the saturation for a continuous level. This breaks the level into multiple regions and computes the saturation level for each region. Parameters: -------------------------------------------- outputs: output of the level. If sparseForm is True, this is a list of the non-zeros. If sparseForm is False, it is the dense representation outputsShape: The shape of the outputs of the level (height, width) retval: (sat, innerSat): sat: list of the saturation levels of each non-empty region of the level (each 0 -> 1.0) innerSat: list of the saturation level of each non-empty region that is not near an edge (each 0 -> 1.0) """ # Get the outputs into a SparseBinaryMatrix if not sparseForm: outputs = outputs.reshape(outputsShape) spOut = SM32(outputs) else: if len(outputs) > 0: assert (outputs.max() < outputsShape[0] * outputsShape[1]) spOut = SM32(1, outputsShape[0] * outputsShape[1]) spOut.setRowFromSparse(0, outputs, [1]*len(outputs)) spOut.reshape(outputsShape[0], outputsShape[1]) # Get the activity in each local region using the nNonZerosPerBox method # This method takes a list of the end row indices and a list of the end # column indices. # We will use regions that are 15x15, which give us about a 1/225 (.4%) resolution # on saturation. regionSize = 15 rows = xrange(regionSize+1, outputsShape[0]+1, regionSize) cols = xrange(regionSize+1, outputsShape[1]+1, regionSize) regionSums = spOut.nNonZerosPerBox(rows, cols) # Get all the nonzeros out - those are our saturation sums (locations, values) = regionSums.tolist() values /= float(regionSize * regionSize) sat = list(values) # Now, to compute which are the inner regions, we will only take the ones that # are surrounded by activity above, below, left and right innerSat = [] locationSet = set(locations) for (location, value) in itertools.izip(locations, values): (row, col) = location if (row-1,col) in locationSet and (row, col-1) in locationSet \ and (row+1, col) in locationSet and (row, col+1) in locationSet: innerSat.append(value) return (sat, innerSat)
def checkMatch(input, prediction, sparse=True, verbosity=0): """ Compares the actual input with the predicted input and returns results Parameters: ----------------------------------------------- input: The actual input prediction: the predicted input verbosity: If > 0, print debugging messages sparse: If true, they are in sparse form (list of active indices) retval (foundInInput, totalActiveInInput, missingFromInput, totalActiveInPrediction) foundInInput: The number of predicted active elements that were found in the actual input totalActiveInInput: The total number of active elements in the input. missingFromInput: The number of predicted active elements that were not found in the actual input totalActiveInPrediction: The total number of active elements in the prediction """ if sparse: activeElementsInInput = set(input) activeElementsInPrediction = set(prediction) else: activeElementsInInput = set(input.nonzero()[0]) activeElementsInPrediction = set(prediction.nonzero()[0]) totalActiveInPrediction = len(activeElementsInPrediction) totalActiveInInput = len(activeElementsInInput) foundInInput = len(activeElementsInPrediction.intersection(activeElementsInInput)) missingFromInput = len(activeElementsInPrediction.difference(activeElementsInInput)) missingFromPrediction = len(activeElementsInInput.difference(activeElementsInPrediction)) if verbosity >= 1: print "preds. found in input:", foundInInput, "out of", totalActiveInPrediction, print "; preds. missing from input:", missingFromInput, "out of", \ totalActiveInPrediction, print "; unexpected active in input:", missingFromPrediction, "out of", \ totalActiveInInput return (foundInInput, totalActiveInInput, missingFromInput, totalActiveInPrediction)
def predictionExtent(inputs, resets, outputs, minOverlapPct=100.0): """ Computes the predictive ability of a temporal memory (TM). This routine returns a value which is the average number of time steps of prediction provided by the TM. It accepts as input the inputs, outputs, and resets provided to the TM as well as a 'minOverlapPct' used to evalulate whether or not a prediction is a good enough match to the actual input. The 'outputs' are the pooling outputs of the TM. This routine treats each output as a "manifold" that includes the active columns that should be present in the next N inputs. It then looks at each successive input and sees if it's active columns are within the manifold. For each output sample, it computes how many time steps it can go forward on the input before the input overlap with the manifold is less then 'minOverlapPct'. It returns the average number of time steps calculated for each output. Parameters: ----------------------------------------------- inputs: The inputs to the TM. Row 0 contains the inputs from time step 0, row 1 from time step 1, etc. resets: The reset input to the TM. Element 0 contains the reset from time step 0, element 1 from time step 1, etc. outputs: The pooling outputs from the TM. Row 0 contains the outputs from time step 0, row 1 from time step 1, etc. minOverlapPct: How much each input's columns must overlap with the pooling output's columns to be considered a valid prediction. retval: (Average number of time steps of prediction over all output samples, Average number of time steps of prediction when we aren't cut short by the end of the sequence, List containing frequency counts of each encountered prediction time) """ # List of how many times we encountered each prediction amount. Element 0 # is how many times we successfully predicted 0 steps in advance, element 1 # is how many times we predicted 1 step in advance, etc. predCounts = None # Total steps of prediction over all samples predTotal = 0 # Total number of samples nSamples = len(outputs) # Total steps of prediction for samples at the start of the sequence, or # for samples whose prediction runs aren't cut short by the end of the # sequence. predTotalNotLimited = 0 nSamplesNotLimited = 0 # Compute how many cells/column we have nCols = len(inputs[0]) nCellsPerCol = len(outputs[0]) // nCols # Evalulate prediction for each output sample for idx in xrange(nSamples): # What are the active columns for this output? activeCols = outputs[idx].reshape(nCols, nCellsPerCol).max(axis=1) # How many steps of prediction do we have? steps = 0 while (idx+steps+1 < nSamples) and (resets[idx+steps+1] == 0): overlap = numpy.logical_and(inputs[idx+steps+1], activeCols) overlapPct = 100.0 * float(overlap.sum()) / inputs[idx+steps+1].sum() if overlapPct >= minOverlapPct: steps += 1 else: break # print "idx:", idx, "steps:", steps # Accumulate into our total predCounts = _accumulateFrequencyCounts([steps], predCounts) predTotal += steps # If this sample was not cut short by the end of the sequence, include # it into the "NotLimited" runs if resets[idx] or \ ((idx+steps+1 < nSamples) and (not resets[idx+steps+1])): predTotalNotLimited += steps nSamplesNotLimited += 1 # Return results return (float(predTotal) / nSamples, float(predTotalNotLimited) / nSamplesNotLimited, predCounts)
def getCentreAndSpreadOffsets(spaceShape, spreadShape, stepSize=1): """ Generates centre offsets and spread offsets for block-mode based training regimes - star, cross, block. Parameters: ----------------------------------------------- spaceShape: The (height, width) of the 2-D space to explore. This sets the number of center-points. spreadShape: The shape (height, width) of the area around each center-point to explore. stepSize: The step size. How big each step is, in pixels. This controls *both* the spacing of the center-points within the block and the points we explore around each center-point retval: (centreOffsets, spreadOffsets) """ from nupic.math.cross import cross # ===================================================================== # Init data structures # What is the range on the X and Y offsets of the center points? shape = spaceShape # If the shape is (1,1), special case of just 1 center point if shape[0] == 1 and shape[1] == 1: centerOffsets = [(0,0)] else: xMin = -1 * (shape[1] // 2) xMax = xMin + shape[1] - 1 xPositions = range(stepSize * xMin, stepSize * xMax + 1, stepSize) yMin = -1 * (shape[0] // 2) yMax = yMin + shape[0] - 1 yPositions = range(stepSize * yMin, stepSize * yMax + 1, stepSize) centerOffsets = list(cross(yPositions, xPositions)) numCenterOffsets = len(centerOffsets) print "centerOffsets:", centerOffsets # What is the range on the X and Y offsets of the spread points? shape = spreadShape # If the shape is (1,1), special case of no spreading around each center # point if shape[0] == 1 and shape[1] == 1: spreadOffsets = [(0,0)] else: xMin = -1 * (shape[1] // 2) xMax = xMin + shape[1] - 1 xPositions = range(stepSize * xMin, stepSize * xMax + 1, stepSize) yMin = -1 * (shape[0] // 2) yMax = yMin + shape[0] - 1 yPositions = range(stepSize * yMin, stepSize * yMax + 1, stepSize) spreadOffsets = list(cross(yPositions, xPositions)) # Put the (0,0) entry first spreadOffsets.remove((0,0)) spreadOffsets.insert(0, (0,0)) numSpreadOffsets = len(spreadOffsets) print "spreadOffsets:", spreadOffsets return centerOffsets, spreadOffsets
def makeCloneMap(columnsShape, outputCloningWidth, outputCloningHeight=-1): """Make a two-dimensional clone map mapping columns to clone master. This makes a map that is (numColumnsHigh, numColumnsWide) big that can be used to figure out which clone master to use for each column. Here are a few sample calls >>> makeCloneMap(columnsShape=(10, 6), outputCloningWidth=4) (array([[ 0, 1, 2, 3, 0, 1], [ 4, 5, 6, 7, 4, 5], [ 8, 9, 10, 11, 8, 9], [12, 13, 14, 15, 12, 13], [ 0, 1, 2, 3, 0, 1], [ 4, 5, 6, 7, 4, 5], [ 8, 9, 10, 11, 8, 9], [12, 13, 14, 15, 12, 13], [ 0, 1, 2, 3, 0, 1], [ 4, 5, 6, 7, 4, 5]], dtype=uint32), 16) >>> makeCloneMap(columnsShape=(7, 8), outputCloningWidth=3) (array([[0, 1, 2, 0, 1, 2, 0, 1], [3, 4, 5, 3, 4, 5, 3, 4], [6, 7, 8, 6, 7, 8, 6, 7], [0, 1, 2, 0, 1, 2, 0, 1], [3, 4, 5, 3, 4, 5, 3, 4], [6, 7, 8, 6, 7, 8, 6, 7], [0, 1, 2, 0, 1, 2, 0, 1]], dtype=uint32), 9) >>> makeCloneMap(columnsShape=(7, 11), outputCloningWidth=5) (array([[ 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0], [ 5, 6, 7, 8, 9, 5, 6, 7, 8, 9, 5], [10, 11, 12, 13, 14, 10, 11, 12, 13, 14, 10], [15, 16, 17, 18, 19, 15, 16, 17, 18, 19, 15], [20, 21, 22, 23, 24, 20, 21, 22, 23, 24, 20], [ 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0], [ 5, 6, 7, 8, 9, 5, 6, 7, 8, 9, 5]], dtype=uint32), 25) >>> makeCloneMap(columnsShape=(7, 8), outputCloningWidth=3, outputCloningHeight=4) (array([[ 0, 1, 2, 0, 1, 2, 0, 1], [ 3, 4, 5, 3, 4, 5, 3, 4], [ 6, 7, 8, 6, 7, 8, 6, 7], [ 9, 10, 11, 9, 10, 11, 9, 10], [ 0, 1, 2, 0, 1, 2, 0, 1], [ 3, 4, 5, 3, 4, 5, 3, 4], [ 6, 7, 8, 6, 7, 8, 6, 7]], dtype=uint32), 12) The basic idea with this map is that, if you imagine things stretching off to infinity, every instance of a given clone master is seeing the exact same thing in all directions. That includes: - All neighbors must be the same - The "meaning" of the input to each of the instances of the same clone master must be the same. If input is pixels and we have translation invariance--this is easy. At higher levels where input is the output of lower levels, this can be much harder. - The "meaning" of the inputs to neighbors of a clone master must be the same for each instance of the same clone master. The best way to think of this might be in terms of 'inputCloningWidth' and 'outputCloningWidth'. - The 'outputCloningWidth' is the number of columns you'd have to move horizontally (or vertically) before you get back to the same the same clone that you started with. MUST BE INTEGRAL! - The 'inputCloningWidth' is the 'outputCloningWidth' of the node below us. If we're getting input from an sensor where every element just represents a shift of every other element, this is 1. At a conceptual level, it means that if two different inputs are shown to the node and the only difference between them is that one is shifted horizontally (or vertically) by this many pixels, it means we are looking at the exact same real world input, but shifted by some number of pixels (doesn't have to be 1). MUST BE INTEGRAL! At level 1, I think you could have this: * inputCloningWidth = 1 * sqrt(coincToInputRatio^2) = 2.5 * outputCloningWidth = 5 ...in this case, you'd end up with 25 masters. Let's think about this case: input: - - - 0 1 2 3 4 5 - - - - - columns: 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 ...in other words, input 0 is fed to both column 0 and column 1. Input 1 is fed to columns 2, 3, and 4, etc. Hopefully, you can see that you'll get the exact same output (except shifted) with: input: - - - - - 0 1 2 3 4 5 - - - columns: 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 ...in other words, we've shifted the input 2 spaces and the output shifted 5 spaces. *** The outputCloningWidth MUST ALWAYS be an integral multiple of the *** *** inputCloningWidth in order for all of our rules to apply. *** *** NOTE: inputCloningWidth isn't passed here, so it's the caller's *** *** responsibility to ensure that this is true. *** *** The outputCloningWidth MUST ALWAYS be an integral multiple of *** *** sqrt(coincToInputRatio^2), too. *** @param columnsShape The shape (height, width) of the columns. @param outputCloningWidth See docstring above. @param outputCloningHeight If non-negative, can be used to make rectangular (instead of square) cloning fields. @return cloneMap An array (numColumnsHigh, numColumnsWide) that contains the clone index to use for each column. @return numDistinctClones The number of distinct clones in the map. This is just outputCloningWidth*outputCloningHeight. """ if outputCloningHeight < 0: outputCloningHeight = outputCloningWidth columnsHeight, columnsWidth = columnsShape numDistinctMasters = outputCloningWidth * outputCloningHeight a = numpy.empty((columnsHeight, columnsWidth), 'uint32') for row in xrange(columnsHeight): for col in xrange(columnsWidth): a[row, col] = (col % outputCloningWidth) + \ (row % outputCloningHeight) * outputCloningWidth return a, numDistinctMasters
def numpyStr(array, format='%f', includeIndices=False, includeZeros=True): """ Pretty print a numpy matrix using the given format string for each value. Return the string representation Parameters: ------------------------------------------------------------ array: The numpy array to print. This can be either a 1D vector or 2D matrix format: The format string to use for each value includeIndices: If true, include [row,col] label for each value includeZeros: Can only be set to False if includeIndices is on. If True, include 0 values in the print-out If False, exclude 0 values from the print-out. """ shape = array.shape assert (len(shape) <= 2) items = ['['] if len(shape) == 1: if includeIndices: format = '%d:' + format if includeZeros: rowItems = [format % (c,x) for (c,x) in enumerate(array)] else: rowItems = [format % (c,x) for (c,x) in enumerate(array) if x != 0] else: rowItems = [format % (x) for x in array] items.extend(rowItems) else: (rows, cols) = shape if includeIndices: format = '%d,%d:' + format for r in xrange(rows): if includeIndices: rowItems = [format % (r,c,x) for c,x in enumerate(array[r])] else: rowItems = [format % (x) for x in array[r]] if r > 0: items.append('') items.append('[') items.extend(rowItems) if r < rows-1: items.append(']\n') else: items.append(']') items.append(']') return ' '.join(items)
def sample(self, rgen): """Generates a random sample from the discrete probability distribution and returns its value and the log of the probability of sampling that value. """ rf = rgen.uniform(0, self.sum) index = bisect.bisect(self.cdf, rf) return self.keys[index], numpy.log(self.pmf[index])
def logProbability(self, distn): """Form of distribution must be an array of counts in order of self.keys.""" x = numpy.asarray(distn) n = x.sum() return (logFactorial(n) - numpy.sum([logFactorial(k) for k in x]) + numpy.sum(x * numpy.log(self.dist.pmf)))
def sample(self, rgen): """Generates a random sample from the Poisson probability distribution and returns its value and the log of the probability of sampling that value. """ x = rgen.poisson(self.lambdaParameter) return x, self.logDensity(x)
def createDataOutLink(network, sensorRegionName, regionName): """Link sensor region to other region so that it can pass it data.""" network.link(sensorRegionName, regionName, "UniformLink", "", srcOutput="dataOut", destInput="bottomUpIn")
def createFeedForwardLink(network, regionName1, regionName2): """Create a feed-forward link between 2 regions: regionName1 -> regionName2""" network.link(regionName1, regionName2, "UniformLink", "", srcOutput="bottomUpOut", destInput="bottomUpIn")
def createResetLink(network, sensorRegionName, regionName): """Create a reset link from a sensor region: sensorRegionName -> regionName""" network.link(sensorRegionName, regionName, "UniformLink", "", srcOutput="resetOut", destInput="resetIn")
def createSensorToClassifierLinks(network, sensorRegionName, classifierRegionName): """Create required links from a sensor region to a classifier region.""" network.link(sensorRegionName, classifierRegionName, "UniformLink", "", srcOutput="bucketIdxOut", destInput="bucketIdxIn") network.link(sensorRegionName, classifierRegionName, "UniformLink", "", srcOutput="actValueOut", destInput="actValueIn") network.link(sensorRegionName, classifierRegionName, "UniformLink", "", srcOutput="categoryOut", destInput="categoryIn")
def createNetwork(dataSource): """Create and initialize a network.""" with open(_PARAMS_PATH, "r") as f: modelParams = yaml.safe_load(f)["modelParams"] # Create a network that will hold the regions. network = Network() # Add a sensor region. network.addRegion("sensor", "py.RecordSensor", '{}') # Set the encoder and data source of the sensor region. sensorRegion = network.regions["sensor"].getSelf() sensorRegion.encoder = createEncoder(modelParams["sensorParams"]["encoders"]) sensorRegion.dataSource = dataSource # Make sure the SP input width matches the sensor region output width. modelParams["spParams"]["inputWidth"] = sensorRegion.encoder.getWidth() # Add SP and TM regions. network.addRegion("SP", "py.SPRegion", json.dumps(modelParams["spParams"])) network.addRegion("TM", "py.TMRegion", json.dumps(modelParams["tmParams"])) # Add a classifier region. clName = "py.%s" % modelParams["clParams"].pop("regionName") network.addRegion("classifier", clName, json.dumps(modelParams["clParams"])) # Add all links createSensorToClassifierLinks(network, "sensor", "classifier") createDataOutLink(network, "sensor", "SP") createFeedForwardLink(network, "SP", "TM") createFeedForwardLink(network, "TM", "classifier") # Reset links are optional, since the sensor region does not send resets. createResetLink(network, "sensor", "SP") createResetLink(network, "sensor", "TM") # Make sure all objects are initialized. network.initialize() return network
def getPredictionResults(network, clRegionName): """Get prediction results for all prediction steps.""" classifierRegion = network.regions[clRegionName] actualValues = classifierRegion.getOutputData("actualValues") probabilities = classifierRegion.getOutputData("probabilities") steps = classifierRegion.getSelf().stepsList N = classifierRegion.getSelf().maxCategoryCount results = {step: {} for step in steps} for i in range(len(steps)): # stepProbabilities are probabilities for this prediction step only. stepProbabilities = probabilities[i * N:(i + 1) * N - 1] mostLikelyCategoryIdx = stepProbabilities.argmax() predictedValue = actualValues[mostLikelyCategoryIdx] predictionConfidence = stepProbabilities[mostLikelyCategoryIdx] results[steps[i]]["predictedValue"] = predictedValue results[steps[i]]["predictionConfidence"] = predictionConfidence return results
def runHotgym(numRecords): """Run the Hot Gym example.""" # Create a data source for the network. dataSource = FileRecordStream(streamID=_INPUT_FILE_PATH) numRecords = min(numRecords, dataSource.getDataRowCount()) network = createNetwork(dataSource) # Set predicted field network.regions["sensor"].setParameter("predictedField", "consumption") # Enable learning for all regions. network.regions["SP"].setParameter("learningMode", 1) network.regions["TM"].setParameter("learningMode", 1) network.regions["classifier"].setParameter("learningMode", 1) # Enable inference for all regions. network.regions["SP"].setParameter("inferenceMode", 1) network.regions["TM"].setParameter("inferenceMode", 1) network.regions["classifier"].setParameter("inferenceMode", 1) results = [] N = 1 # Run the network, N iterations at a time. for iteration in range(0, numRecords, N): network.run(N) predictionResults = getPredictionResults(network, "classifier") oneStep = predictionResults[1]["predictedValue"] oneStepConfidence = predictionResults[1]["predictionConfidence"] fiveStep = predictionResults[5]["predictedValue"] fiveStepConfidence = predictionResults[5]["predictionConfidence"] result = (oneStep, oneStepConfidence * 100, fiveStep, fiveStepConfidence * 100) print "1-step: {:16} ({:4.4}%)\t 5-step: {:16} ({:4.4}%)".format(*result) results.append(result) return results
def _loadDummyModelParameters(self, params): """ Loads all the parameters for this dummy model. For any paramters specified as lists, read the appropriate value for this model using the model index """ for key, value in params.iteritems(): if type(value) == list: index = self.modelIndex % len(params[key]) self._params[key] = params[key][index] else: self._params[key] = params[key]
def _computModelDelay(self): """ Computes the amount of time (if any) to delay the run of this model. This can be determined by two mutually exclusive parameters: delay and sleepModelRange. 'delay' specifies the number of seconds a model should be delayed. If a list is specified, the appropriate amount of delay is determined by using the model's modelIndex property. However, this doesn't work when testing orphaned models, because the modelIndex will be the same for every recovery attempt. Therefore, every recovery attempt will also be delayed and potentially orphaned. 'sleepModelRange' doesn't use the modelIndex property for a model, but rather sees which order the model is in the database, and uses that to determine whether or not a model should be delayed. """ # 'delay' and 'sleepModelRange' are mutually exclusive if self._params['delay'] is not None \ and self._params['sleepModelRange'] is not None: raise RuntimeError("Only one of 'delay' or " "'sleepModelRange' may be specified") # Get the sleepModel range if self._sleepModelRange is not None: range, delay = self._sleepModelRange.split(':') delay = float(delay) range = map(int, range.split(',')) modelIDs = self._jobsDAO.jobGetModelIDs(self._jobID) modelIDs.sort() range[1] = min(range[1], len(modelIDs)) # If the model is in range, add the delay if self._modelID in modelIDs[range[0]:range[1]]: self._delay = delay else: self._delay = self._params['delay']
def _getMetrics(self): """ Protected function that can be overridden by subclasses. Its main purpose is to allow the the OPFDummyModelRunner to override this with deterministic values Returns: All the metrics being computed for this model """ metric = None if self.metrics is not None: metric = self.metrics(self._currentRecordIndex+1) elif self.metricValue is not None: metric = self.metricValue else: raise RuntimeError('No metrics or metric value specified for dummy model') return {self._optimizeKeyPattern:metric}
def run(self): """ Runs the given OPF task against the given Model instance """ self._logger.debug("Starting Dummy Model: modelID=%s;" % (self._modelID)) # ========================================================================= # Initialize periodic activities (e.g., for model result updates) # ========================================================================= periodic = self._initPeriodicActivities() self._optimizedMetricLabel = self._optimizeKeyPattern self._reportMetricLabels = [self._optimizeKeyPattern] # ========================================================================= # Create our top-level loop-control iterator # ========================================================================= if self._iterations >= 0: iterTracker = iter(xrange(self._iterations)) else: iterTracker = iter(itertools.count()) # ========================================================================= # This gets set in the unit tests. It tells the worker to sys exit # the first N models. This is how we generate orphaned models doSysExit = False if self._sysExitModelRange is not None: modelAndCounters = self._jobsDAO.modelsGetUpdateCounters(self._jobID) modelIDs = [x[0] for x in modelAndCounters] modelIDs.sort() (beg,end) = self._sysExitModelRange if self._modelID in modelIDs[int(beg):int(end)]: doSysExit = True if self._delayModelRange is not None: modelAndCounters = self._jobsDAO.modelsGetUpdateCounters(self._jobID) modelIDs = [x[0] for x in modelAndCounters] modelIDs.sort() (beg,end) = self._delayModelRange if self._modelID in modelIDs[int(beg):int(end)]: time.sleep(10) # DEBUG!!!! infinite wait if we have 50 models #if len(modelIDs) >= 50: # jobCancel = self._jobsDAO.jobGetFields(self._jobID, ['cancel'])[0] # while not jobCancel: # time.sleep(1) # jobCancel = self._jobsDAO.jobGetFields(self._jobID, ['cancel'])[0] if self._errModelRange is not None: modelAndCounters = self._jobsDAO.modelsGetUpdateCounters(self._jobID) modelIDs = [x[0] for x in modelAndCounters] modelIDs.sort() (beg,end) = self._errModelRange if self._modelID in modelIDs[int(beg):int(end)]: raise RuntimeError("Exiting with error due to errModelRange parameter") # ========================================================================= # Delay, if necessary if self._delay is not None: time.sleep(self._delay) # ========================================================================= # Run it! # ========================================================================= self._currentRecordIndex = 0 while True: # ========================================================================= # Check if the model should be stopped # ========================================================================= # If killed by a terminator, stop running if self._isKilled: break # If job stops or hypersearch ends, stop running if self._isCanceled: break # If model is mature, stop running ONLY IF we are not the best model # for the job. Otherwise, keep running so we can keep returning # predictions to the user if self._isMature: if not self._isBestModel: self._cmpReason = self._jobsDAO.CMPL_REASON_STOPPED break else: self._cmpReason = self._jobsDAO.CMPL_REASON_EOF # ========================================================================= # Get the the next record, and "write it" # ========================================================================= try: self._currentRecordIndex = next(iterTracker) except StopIteration: break # "Write" a dummy output value. This is used to test that the batched # writing works properly self._writePrediction(ModelResult(None, None, None, None)) periodic.tick() # ========================================================================= # Compute wait times. See if model should exit # ========================================================================= if self.__shouldSysExit(self._currentRecordIndex): sys.exit(1) # Simulate computation time if self._busyWaitTime is not None: time.sleep(self._busyWaitTime) self.__computeWaitTime() # Asked to abort after so many iterations? if doSysExit: sys.exit(1) # Asked to raise a jobFailException? if self._jobFailErr: raise utils.JobFailException("E10000", "dummyModel's jobFailErr was True.") # ========================================================================= # Handle final operations # ========================================================================= if self._doFinalize: if not self._makeCheckpoint: self._model = None # Delay finalization operation if self._finalDelay is not None: time.sleep(self._finalDelay) self._finalize() self._logger.info("Finished: modelID=%r "% (self._modelID)) return (self._cmpReason, None)
def _createPredictionLogger(self): """ Creates the model's PredictionLogger object, which is an interface to write model results to a permanent storage location """ class DummyLogger: def writeRecord(self, record): pass def writeRecords(self, records, progressCB): pass def close(self): pass self._predictionLogger = DummyLogger()
def __shouldSysExit(self, iteration): """ Checks to see if the model should exit based on the exitAfter dummy parameter """ if self._exitAfter is None \ or iteration < self._exitAfter: return False results = self._jobsDAO.modelsGetFieldsForJob(self._jobID, ['params']) modelIDs = [e[0] for e in results] modelNums = [json.loads(e[1][0])['structuredParams']['__model_num'] for e in results] sameModelNumbers = filter(lambda x: x[1] == self.modelIndex, zip(modelIDs, modelNums)) firstModelID = min(zip(*sameModelNumbers)[0]) return firstModelID == self._modelID
def getDescription(self): """Returns a description of the dataset""" description = {'name':self.name, 'fields':[f.name for f in self.fields], \ 'numRecords by field':[f.numRecords for f in self.fields]} return description
def setSeed(self, seed): """Set the random seed and the numpy seed Parameters: -------------------------------------------------------------------- seed: random seed """ rand.seed(seed) np.random.seed(seed)
def addField(self, name, fieldParams, encoderParams): """Add a single field to the dataset. Parameters: ------------------------------------------------------------------- name: The user-specified name of the field fieldSpec: A list of one or more dictionaries specifying parameters to be used for dataClass initialization. Each dict must contain the key 'type' that specifies a distribution for the values in this field encoderParams: Parameters for the field encoder """ assert fieldParams is not None and'type' in fieldParams dataClassName = fieldParams.pop('type') try: dataClass=eval(dataClassName)(fieldParams) except TypeError, e: print ("#### Error in constructing %s class object. Possibly missing " "some required constructor parameters. Parameters " "that were provided are: %s" % (dataClass, fieldParams)) raise encoderParams['dataClass']=dataClass encoderParams['dataClassName']=dataClassName fieldIndex = self.defineField(name, encoderParams)
def addMultipleFields(self, fieldsInfo): """Add multiple fields to the dataset. Parameters: ------------------------------------------------------------------- fieldsInfo: A list of dictionaries, containing a field name, specs for the data classes and encoder params for the corresponding field. """ assert all(x in field for x in ['name', 'fieldSpec', 'encoderParams'] for field \ in fieldsInfo) for spec in fieldsInfo: self.addField(spec.pop('name'), spec.pop('fieldSpec'), spec.pop('encoderParams'))
def defineField(self, name, encoderParams=None): """Initialize field using relevant encoder parameters. Parameters: ------------------------------------------------------------------- name: Field name encoderParams: Parameters for the encoder. Returns the index of the field """ self.fields.append(_field(name, encoderParams)) return len(self.fields)-1
def setFlag(self, index, flag): """Set flag for field at index. Flags are special characters such as 'S' for sequence or 'T' for timestamp. Parameters: -------------------------------------------------------------------- index: index of field whose flag is being set flag: special character """ assert len(self.fields)>index self.fields[index].flag=flag
def generateRecord(self, record): """Generate a record. Each value is stored in its respective field. Parameters: -------------------------------------------------------------------- record: A 1-D array containing as many values as the number of fields fields: An object of the class field that specifies the characteristics of each value in the record Assertion: -------------------------------------------------------------------- len(record)==len(fields): A value for each field must be specified. Replace missing values of any type by SENTINEL_VALUE_FOR_MISSING_DATA This method supports external classes but not combination of classes. """ assert(len(record)==len(self.fields)) if record is not None: for x in range(len(self.fields)): self.fields[x].addValue(record[x]) else: for field in self.fields: field.addValue(field.dataClass.getNext())
def generateRecords(self, records): """Generate multiple records. Refer to definition for generateRecord""" if self.verbosity>0: print 'Generating', len(records), 'records...' for record in records: self.generateRecord(record)
def getRecord(self, n=None): """Returns the nth record""" if n is None: assert len(self.fields)>0 n = self.fields[0].numRecords-1 assert (all(field.numRecords>n for field in self.fields)) record = [field.values[n] for field in self.fields] return record
def getAllRecords(self): """Returns all the records""" values=[] numRecords = self.fields[0].numRecords assert (all(field.numRecords==numRecords for field in self.fields)) for x in range(numRecords): values.append(self.getRecord(x)) return values
def encodeRecord(self, record, toBeAdded=True): """Encode a record as a sparse distributed representation Parameters: -------------------------------------------------------------------- record: Record to be encoded toBeAdded: Whether the encodings corresponding to the record are added to the corresponding fields """ encoding=[self.fields[i].encodeValue(record[i], toBeAdded) for i in \ xrange(len(self.fields))] return encoding
def encodeAllRecords(self, records=None, toBeAdded=True): """Encodes a list of records. Parameters: -------------------------------------------------------------------- records: One or more records. (i,j)th element of this 2D array specifies the value at field j of record i. If unspecified, records previously generated and stored are used. toBeAdded: Whether the encodings corresponding to the record are added to the corresponding fields """ if records is None: records = self.getAllRecords() if self.verbosity>0: print 'Encoding', len(records), 'records.' encodings = [self.encodeRecord(record, toBeAdded) for record in records] return encodings
def addValueToField(self, i, value=None): """Add 'value' to the field i. Parameters: -------------------------------------------------------------------- value: value to be added i: value is added to field i """ assert(len(self.fields)>i) if value is None: value = self.fields[i].dataClass.getNext() self.fields[i].addValue(value) return value else: self.fields[i].addValue(value)
def addValuesToField(self, i, numValues): """Add values to the field i.""" assert(len(self.fields)>i) values = [self.addValueToField(i) for n in range(numValues)] return values
def getSDRforValue(self, i, j): """Returns the sdr for jth value at column i""" assert len(self.fields)>i assert self.fields[i].numRecords>j encoding = self.fields[i].encodings[j] return encoding
def getZeroedOutEncoding(self, n): """Returns the nth encoding with the predictedField zeroed out""" assert all(field.numRecords>n for field in self.fields) encoding = np.concatenate([field.encoder.encode(SENTINEL_VALUE_FOR_MISSING_DATA)\ if field.isPredictedField else field.encodings[n] for field in self.fields]) return encoding
def getTotaln(self): """Returns the cumulative n for all the fields in the dataset""" n = sum([field.n for field in self.fields]) return n
def getTotalw(self): """Returns the cumulative w for all the fields in the dataset""" w = sum([field.w for field in self.fields]) return w
def getEncoding(self, n): """Returns the nth encoding""" assert (all(field.numEncodings>n for field in self.fields)) encoding = np.concatenate([field.encodings[n] for field in self.fields]) return encoding
def getAllEncodings(self): """Returns encodings for all the records""" numEncodings=self.fields[0].numEncodings assert (all(field.numEncodings==numEncodings for field in self.fields)) encodings = [self.getEncoding(index) for index in range(numEncodings)] return encodings
def saveRecords(self, path='myOutput'): """Export all the records into a csv file in numenta format. Example header format: fieldName1 fieldName2 fieldName3 date string float T S Parameters: -------------------------------------------------------------------- path: Relative path of the file to which the records are to be exported """ numRecords = self.fields[0].numRecords assert (all(field.numRecords==numRecords for field in self.fields)) import csv with open(path+'.csv', 'wb') as f: writer = csv.writer(f) writer.writerow(self.getAllFieldNames()) writer.writerow(self.getAllDataTypes()) writer.writerow(self.getAllFlags()) writer.writerows(self.getAllRecords()) if self.verbosity>0: print '******', numRecords,'records exported in numenta format to file:',\ path,'******\n'
def removeAllRecords(self): """Deletes all the values in the dataset""" for field in self.fields: field.encodings, field.values=[], [] field.numRecords, field.numEncodings= (0, 0)
def encodeValue(self, value, toBeAdded=True): """Value is encoded as a sdr using the encoding parameters of the Field""" encodedValue = np.array(self.encoder.encode(value), dtype=realDType) if toBeAdded: self.encodings.append(encodedValue) self.numEncodings+=1 return encodedValue
def _setTypes(self, encoderSpec): """Set up the dataTypes and initialize encoders""" if self.encoderType is None: if self.dataType in ['int','float']: self.encoderType='adaptiveScalar' elif self.dataType=='string': self.encoderType='category' elif self.dataType in ['date', 'datetime']: self.encoderType='date' if self.dataType is None: if self.encoderType in ['scalar','adaptiveScalar']: self.dataType='float' elif self.encoderType in ['category', 'enumeration']: self.dataType='string' elif self.encoderType in ['date', 'datetime']: self.dataType='datetime'
def _initializeEncoders(self, encoderSpec): """ Initialize the encoders""" #Initializing scalar encoder if self.encoderType in ['adaptiveScalar', 'scalar']: if 'minval' in encoderSpec: self.minval = encoderSpec.pop('minval') else: self.minval=None if 'maxval' in encoderSpec: self.maxval = encoderSpec.pop('maxval') else: self.maxval = None self.encoder=adaptive_scalar.AdaptiveScalarEncoder(name='AdaptiveScalarEncoder', \ w=self.w, n=self.n, minval=self.minval, maxval=self.maxval, periodic=False, forced=True) #Initializing category encoder elif self.encoderType=='category': self.encoder=sdr_category.SDRCategoryEncoder(name='categoryEncoder', \ w=self.w, n=self.n) #Initializing date encoder elif self.encoderType in ['date', 'datetime']: self.encoder=date.DateEncoder(name='dateEncoder') else: raise RuntimeError('Error in constructing class object. Either encoder type' 'or dataType must be specified')
def getScalars(self, input): """ See method description in base.py """ if input == SENTINEL_VALUE_FOR_MISSING_DATA: return numpy.array([None]) else: return numpy.array([self.categoryToIndex.get(input, 0)])
def getBucketIndices(self, input): """ See method description in base.py """ # Get the bucket index from the underlying scalar encoder if input == SENTINEL_VALUE_FOR_MISSING_DATA: return [None] else: return self.encoder.getBucketIndices(self.categoryToIndex.get(input, 0))
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 field assert(len(fieldsDict) == 1) # Get the list of categories the scalar values correspond to and # generate the description from the category name(s). (inRanges, inDesc) = fieldsDict.values()[0] outRanges = [] desc = "" for (minV, maxV) in inRanges: minV = int(round(minV)) maxV = int(round(maxV)) outRanges.append((minV, maxV)) while minV <= maxV: if len(desc) > 0: desc += ", " desc += self.indexToCategory[minV] minV += 1 # Return result if parentFieldName != '': fieldName = "%s.%s" % (parentFieldName, self.name) else: fieldName = self.name return ({fieldName: (outRanges, desc)}, [fieldName])
def closenessScores(self, expValues, actValues, fractional=True,): """ See the function description in base.py kwargs will have the keyword "fractional", which is ignored by this encoder """ expValue = expValues[0] actValue = actValues[0] if expValue == actValue: closeness = 1.0 else: closeness = 0.0 if not fractional: closeness = 1.0 - closeness return numpy.array([closeness])
def getBucketValues(self): """ See the function description in base.py """ if self._bucketValues is None: numBuckets = len(self.encoder.getBucketValues()) self._bucketValues = [] for bucketIndex in range(numBuckets): self._bucketValues.append(self.getBucketInfo([bucketIndex])[0].value) return self._bucketValues
def getBucketInfo(self, buckets): """ See the function description in base.py """ # For the category encoder, the bucket index is the category index bucketInfo = self.encoder.getBucketInfo(buckets)[0] categoryIndex = int(round(bucketInfo.value)) category = self.indexToCategory[categoryIndex] return [EncoderResult(value=category, scalar=categoryIndex, encoding=bucketInfo.encoding)]
def topDownCompute(self, encoded): """ See the function description in base.py """ encoderResult = self.encoder.topDownCompute(encoded)[0] value = encoderResult.value categoryIndex = int(round(value)) category = self.indexToCategory[categoryIndex] return EncoderResult(value=category, scalar=categoryIndex, encoding=encoderResult.encoding)
def loadExperiment(path): """Loads the experiment description file from the path. :param path: (string) The path to a directory containing a description.py file or the file itself. :returns: (config, control) """ if not os.path.isdir(path): path = os.path.dirname(path) descriptionPyModule = loadExperimentDescriptionScriptFromDir(path) expIface = getExperimentDescriptionInterfaceFromModule(descriptionPyModule) return expIface.getModelDescription(), expIface.getModelControl()
def loadExperimentDescriptionScriptFromDir(experimentDir): """ Loads the experiment description python script from the given experiment directory. :param experimentDir: (string) experiment directory path :returns: module of the loaded experiment description scripts """ descriptionScriptPath = os.path.join(experimentDir, "description.py") module = _loadDescriptionFile(descriptionScriptPath) return module
def getExperimentDescriptionInterfaceFromModule(module): """ :param module: imported description.py module :returns: (:class:`nupic.frameworks.opf.exp_description_api.DescriptionIface`) represents the experiment description """ result = module.descriptionInterface assert isinstance(result, exp_description_api.DescriptionIface), \ "expected DescriptionIface-based instance, but got %s" % type(result) return result
def _loadDescriptionFile(descriptionPyPath): """Loads a description file and returns it as a module. descriptionPyPath: path of description.py file to load """ global g_descriptionImportCount if not os.path.isfile(descriptionPyPath): raise RuntimeError(("Experiment description file %s does not exist or " + \ "is not a file") % (descriptionPyPath,)) mod = imp.load_source("pf_description%d" % g_descriptionImportCount, descriptionPyPath) g_descriptionImportCount += 1 if not hasattr(mod, "descriptionInterface"): raise RuntimeError("Experiment description file %s does not define %s" % \ (descriptionPyPath, "descriptionInterface")) if not isinstance(mod.descriptionInterface, exp_description_api.DescriptionIface): raise RuntimeError(("Experiment description file %s defines %s but it " + \ "is not DescriptionIface-based") % \ (descriptionPyPath, name)) return mod
def update(self, modelID, modelParams, modelParamsHash, metricResult, completed, completionReason, matured, numRecords): """ Insert a new entry or update an existing one. If this is an update of an existing entry, then modelParams will be None Parameters: -------------------------------------------------------------------- modelID: globally unique modelID of this model modelParams: params dict for this model, or None if this is just an update of a model that it already previously reported on. See the comments for the createModels() method for a description of this dict. modelParamsHash: hash of the modelParams dict, generated by the worker that put it into the model database. metricResult: value on the optimizeMetric for this model. May be None if we have no results yet. completed: True if the model has completed evaluation, False if it is still running (and these are online results) completionReason: One of the ClientJobsDAO.CMPL_REASON_XXX equates matured: True if this model has matured numRecords: Number of records that have been processed so far by this model. retval: Canonicalized result on the optimize metric """ # The modelParamsHash must always be provided - it can change after a # model is inserted into the models table if it got detected as an # orphan assert (modelParamsHash is not None) # We consider a model metricResult as "final" if it has completed or # matured. By default, assume anything that has completed has matured if completed: matured = True # Get the canonicalized optimize metric results. For this metric, lower # is always better if metricResult is not None and matured and \ completionReason in [ClientJobsDAO.CMPL_REASON_EOF, ClientJobsDAO.CMPL_REASON_STOPPED]: # Canonicalize the error score so that lower is better if self._hsObj._maximize: errScore = -1 * metricResult else: errScore = metricResult if errScore < self._bestResult: self._bestResult = errScore self._bestModelID = modelID self._hsObj.logger.info("New best model after %d evaluations: errScore " "%g on model %s" % (len(self._allResults), self._bestResult, self._bestModelID)) else: errScore = numpy.inf # If this model completed with an unacceptable completion reason, set the # errScore to infinite and essentially make this model invisible to # further queries if completed and completionReason in [ClientJobsDAO.CMPL_REASON_ORPHAN]: errScore = numpy.inf hidden = True else: hidden = False # Update our set of erred models and completed models. These are used # to determine if we should abort the search because of too many errors if completed: self._completedModels.add(modelID) self._numCompletedModels = len(self._completedModels) if completionReason == ClientJobsDAO.CMPL_REASON_ERROR: self._errModels.add(modelID) self._numErrModels = len(self._errModels) # Are we creating a new entry? wasHidden = False if modelID not in self._modelIDToIdx: assert (modelParams is not None) entry = dict(modelID=modelID, modelParams=modelParams, modelParamsHash=modelParamsHash, errScore=errScore, completed=completed, matured=matured, numRecords=numRecords, hidden=hidden) self._allResults.append(entry) entryIdx = len(self._allResults) - 1 self._modelIDToIdx[modelID] = entryIdx self._paramsHashToIndexes[modelParamsHash] = entryIdx swarmId = modelParams['particleState']['swarmId'] if not hidden: # Update the list of particles in each swarm if swarmId in self._swarmIdToIndexes: self._swarmIdToIndexes[swarmId].append(entryIdx) else: self._swarmIdToIndexes[swarmId] = [entryIdx] # Update number of particles at each generation in this swarm genIdx = modelParams['particleState']['genIdx'] numPsEntry = self._swarmNumParticlesPerGeneration.get(swarmId, [0]) while genIdx >= len(numPsEntry): numPsEntry.append(0) numPsEntry[genIdx] += 1 self._swarmNumParticlesPerGeneration[swarmId] = numPsEntry # Replacing an existing one else: entryIdx = self._modelIDToIdx.get(modelID, None) assert (entryIdx is not None) entry = self._allResults[entryIdx] wasHidden = entry['hidden'] # If the paramsHash changed, note that. This can happen for orphaned # models if entry['modelParamsHash'] != modelParamsHash: self._paramsHashToIndexes.pop(entry['modelParamsHash']) self._paramsHashToIndexes[modelParamsHash] = entryIdx entry['modelParamsHash'] = modelParamsHash # Get the model params, swarmId, and genIdx modelParams = entry['modelParams'] swarmId = modelParams['particleState']['swarmId'] genIdx = modelParams['particleState']['genIdx'] # If this particle just became hidden, remove it from our swarm counts if hidden and not wasHidden: assert (entryIdx in self._swarmIdToIndexes[swarmId]) self._swarmIdToIndexes[swarmId].remove(entryIdx) self._swarmNumParticlesPerGeneration[swarmId][genIdx] -= 1 # Update the entry for the latest info entry['errScore'] = errScore entry['completed'] = completed entry['matured'] = matured entry['numRecords'] = numRecords entry['hidden'] = hidden # Update the particle best errScore particleId = modelParams['particleState']['id'] genIdx = modelParams['particleState']['genIdx'] if matured and not hidden: (oldResult, pos) = self._particleBest.get(particleId, (numpy.inf, None)) if errScore < oldResult: pos = Particle.getPositionFromState(modelParams['particleState']) self._particleBest[particleId] = (errScore, pos) # Update the particle latest generation index prevGenIdx = self._particleLatestGenIdx.get(particleId, -1) if not hidden and genIdx > prevGenIdx: self._particleLatestGenIdx[particleId] = genIdx elif hidden and not wasHidden and genIdx == prevGenIdx: self._particleLatestGenIdx[particleId] = genIdx-1 # Update the swarm best score if not hidden: swarmId = modelParams['particleState']['swarmId'] if not swarmId in self._swarmBestOverall: self._swarmBestOverall[swarmId] = [] bestScores = self._swarmBestOverall[swarmId] while genIdx >= len(bestScores): bestScores.append((None, numpy.inf)) if errScore < bestScores[genIdx][1]: bestScores[genIdx] = (modelID, errScore) # Update the self._modifiedSwarmGens flags to support the # getMaturedSwarmGenerations() call. if not hidden: key = (swarmId, genIdx) if not key in self._maturedSwarmGens: self._modifiedSwarmGens.add(key) return errScore
def getModelIDFromParamsHash(self, paramsHash): """ Return the modelID of the model with the given paramsHash, or None if not found. Parameters: --------------------------------------------------------------------- paramsHash: paramsHash to look for retval: modelId, or None if not found """ entryIdx = self. _paramsHashToIndexes.get(paramsHash, None) if entryIdx is not None: return self._allResults[entryIdx]['modelID'] else: return None
def numModels(self, swarmId=None, includeHidden=False): """Return the total # of models we have in our database (if swarmId is None) or in a specific swarm. Parameters: --------------------------------------------------------------------- swarmId: A string representation of the sorted list of encoders in this swarm. For example '__address_encoder.__gym_encoder' includeHidden: If False, this will only return the number of models that are not hidden (i.e. orphanned, etc.) retval: numModels """ # Count all models if includeHidden: if swarmId is None: return len(self._allResults) else: return len(self._swarmIdToIndexes.get(swarmId, [])) # Only count non-hidden models else: if swarmId is None: entries = self._allResults else: entries = [self._allResults[entryIdx] for entryIdx in self._swarmIdToIndexes.get(swarmId,[])] return len([entry for entry in entries if not entry['hidden']])
def bestModelIdAndErrScore(self, swarmId=None, genIdx=None): """Return the model ID of the model with the best result so far and it's score on the optimize metric. If swarm is None, then it returns the global best, otherwise it returns the best for the given swarm for all generatons up to and including genIdx. Parameters: --------------------------------------------------------------------- swarmId: A string representation of the sorted list of encoders in this swarm. For example '__address_encoder.__gym_encoder' genIdx: consider the best in all generations up to and including this generation if not None. retval: (modelID, result) """ if swarmId is None: return (self._bestModelID, self._bestResult) else: if swarmId not in self._swarmBestOverall: return (None, numpy.inf) # Get the best score, considering the appropriate generations genScores = self._swarmBestOverall[swarmId] bestModelId = None bestScore = numpy.inf for (i, (modelId, errScore)) in enumerate(genScores): if genIdx is not None and i > genIdx: break if errScore < bestScore: bestScore = errScore bestModelId = modelId return (bestModelId, bestScore)
def getParticleInfo(self, modelId): """Return particle info for a specific modelId. Parameters: --------------------------------------------------------------------- modelId: which model Id retval: (particleState, modelId, errScore, completed, matured) """ entry = self._allResults[self._modelIDToIdx[modelId]] return (entry['modelParams']['particleState'], modelId, entry['errScore'], entry['completed'], entry['matured'])
def getParticleInfos(self, swarmId=None, genIdx=None, completed=None, matured=None, lastDescendent=False): """Return a list of particleStates for all particles we know about in the given swarm, their model Ids, and metric results. Parameters: --------------------------------------------------------------------- swarmId: A string representation of the sorted list of encoders in this swarm. For example '__address_encoder.__gym_encoder' genIdx: If not None, only return particles at this specific generation index. completed: If not None, only return particles of the given state (either completed if 'completed' is True, or running if 'completed' is false matured: If not None, only return particles of the given state (either matured if 'matured' is True, or not matured if 'matured' is false. Note that any model which has completed is also considered matured. lastDescendent: If True, only return particles that are the last descendent, that is, the highest generation index for a given particle Id retval: (particleStates, modelIds, errScores, completed, matured) particleStates: list of particleStates modelIds: list of modelIds errScores: list of errScores, numpy.inf is plugged in if we don't have a result yet completed: list of completed booleans matured: list of matured booleans """ # The indexes of all the models in this swarm. This list excludes hidden # (orphaned) models. if swarmId is not None: entryIdxs = self._swarmIdToIndexes.get(swarmId, []) else: entryIdxs = range(len(self._allResults)) if len(entryIdxs) == 0: return ([], [], [], [], []) # Get the particles of interest particleStates = [] modelIds = [] errScores = [] completedFlags = [] maturedFlags = [] for idx in entryIdxs: entry = self._allResults[idx] # If this entry is hidden (i.e. it was an orphaned model), it should # not be in this list if swarmId is not None: assert (not entry['hidden']) # Get info on this model modelParams = entry['modelParams'] isCompleted = entry['completed'] isMatured = entry['matured'] particleState = modelParams['particleState'] particleGenIdx = particleState['genIdx'] particleId = particleState['id'] if genIdx is not None and particleGenIdx != genIdx: continue if completed is not None and (completed != isCompleted): continue if matured is not None and (matured != isMatured): continue if lastDescendent \ and (self._particleLatestGenIdx[particleId] != particleGenIdx): continue # Incorporate into return values particleStates.append(particleState) modelIds.append(entry['modelID']) errScores.append(entry['errScore']) completedFlags.append(isCompleted) maturedFlags.append(isMatured) return (particleStates, modelIds, errScores, completedFlags, maturedFlags)
def getOrphanParticleInfos(self, swarmId, genIdx): """Return a list of particleStates for all particles in the given swarm generation that have been orphaned. Parameters: --------------------------------------------------------------------- swarmId: A string representation of the sorted list of encoders in this swarm. For example '__address_encoder.__gym_encoder' genIdx: If not None, only return particles at this specific generation index. retval: (particleStates, modelIds, errScores, completed, matured) particleStates: list of particleStates modelIds: list of modelIds errScores: list of errScores, numpy.inf is plugged in if we don't have a result yet completed: list of completed booleans matured: list of matured booleans """ entryIdxs = range(len(self._allResults)) if len(entryIdxs) == 0: return ([], [], [], [], []) # Get the particles of interest particleStates = [] modelIds = [] errScores = [] completedFlags = [] maturedFlags = [] for idx in entryIdxs: # Get info on this model entry = self._allResults[idx] if not entry['hidden']: continue modelParams = entry['modelParams'] if modelParams['particleState']['swarmId'] != swarmId: continue isCompleted = entry['completed'] isMatured = entry['matured'] particleState = modelParams['particleState'] particleGenIdx = particleState['genIdx'] particleId = particleState['id'] if genIdx is not None and particleGenIdx != genIdx: continue # Incorporate into return values particleStates.append(particleState) modelIds.append(entry['modelID']) errScores.append(entry['errScore']) completedFlags.append(isCompleted) maturedFlags.append(isMatured) return (particleStates, modelIds, errScores, completedFlags, maturedFlags)
def getMaturedSwarmGenerations(self): """Return a list of swarm generations that have completed and the best (minimal) errScore seen for each of them. Parameters: --------------------------------------------------------------------- retval: list of tuples. Each tuple is of the form: (swarmId, genIdx, bestErrScore) """ # Return results go in this list result = [] # For each of the swarm generations which have had model result updates # since the last time we were called, see which have completed. modifiedSwarmGens = sorted(self._modifiedSwarmGens) # Walk through them in order from lowest to highest generation index for key in modifiedSwarmGens: (swarmId, genIdx) = key # Skip it if we've already reported on it. This should happen rarely, if # ever. It means that some worker has started and completed a model in # this generation after we've determined that the generation has ended. if key in self._maturedSwarmGens: self._modifiedSwarmGens.remove(key) continue # If the previous generation for this swarm is not complete yet, don't # bother evaluating this one. if (genIdx >= 1) and not (swarmId, genIdx-1) in self._maturedSwarmGens: continue # We found a swarm generation that had some results reported since last # time, see if it's complete or not (_, _, errScores, completedFlags, maturedFlags) = \ self.getParticleInfos(swarmId, genIdx) maturedFlags = numpy.array(maturedFlags) numMatured = maturedFlags.sum() if numMatured >= self._hsObj._minParticlesPerSwarm \ and numMatured == len(maturedFlags): errScores = numpy.array(errScores) bestScore = errScores.min() self._maturedSwarmGens.add(key) self._modifiedSwarmGens.remove(key) result.append((swarmId, genIdx, bestScore)) # Return results return result
def firstNonFullGeneration(self, swarmId, minNumParticles): """ Return the generation index of the first generation in the given swarm that does not have numParticles particles in it, either still in the running state or completed. This does not include orphaned particles. Parameters: --------------------------------------------------------------------- swarmId: A string representation of the sorted list of encoders in this swarm. For example '__address_encoder.__gym_encoder' minNumParticles: minium number of partices required for a full generation. retval: generation index, or None if no particles at all. """ if not swarmId in self._swarmNumParticlesPerGeneration: return None numPsPerGen = self._swarmNumParticlesPerGeneration[swarmId] numPsPerGen = numpy.array(numPsPerGen) firstNonFull = numpy.where(numPsPerGen < minNumParticles)[0] if len(firstNonFull) == 0: return len(numPsPerGen) else: return firstNonFull[0]
def getResultsPerChoice(self, swarmId, maxGenIdx, varName): """ Return a dict of the errors obtained on models that were run with each value from a PermuteChoice variable. For example, if a PermuteChoice variable has the following choices: ['a', 'b', 'c'] The dict will have 3 elements. The keys are the stringified choiceVars, and each value is tuple containing (choiceVar, errors) where choiceVar is the original form of the choiceVar (before stringification) and errors is the list of errors received from models that used the specific choice: retval: ['a':('a', [0.1, 0.2, 0.3]), 'b':('b', [0.5, 0.1, 0.6]), 'c':('c', [])] Parameters: --------------------------------------------------------------------- swarmId: swarm Id of the swarm to retrieve info from maxGenIdx: max generation index to consider from other models, ignored if None varName: which variable to retrieve retval: list of the errors obtained from each choice. """ results = dict() # Get all the completed particles in this swarm (allParticles, _, resultErrs, _, _) = self.getParticleInfos(swarmId, genIdx=None, matured=True) for particleState, resultErr in itertools.izip(allParticles, resultErrs): # Consider this generation? if maxGenIdx is not None: if particleState['genIdx'] > maxGenIdx: continue # Ignore unless this model completed successfully if resultErr == numpy.inf: continue position = Particle.getPositionFromState(particleState) varPosition = position[varName] varPositionStr = str(varPosition) if varPositionStr in results: results[varPositionStr][1].append(resultErr) else: results[varPositionStr] = (varPosition, [resultErr]) return results
def _getStreamDef(self, modelDescription): """ Generate stream definition based on """ #-------------------------------------------------------------------------- # Generate the string containing the aggregation settings. aggregationPeriod = { 'days': 0, 'hours': 0, 'microseconds': 0, 'milliseconds': 0, 'minutes': 0, 'months': 0, 'seconds': 0, 'weeks': 0, 'years': 0, } # Honor any overrides provided in the stream definition aggFunctionsDict = {} if 'aggregation' in modelDescription['streamDef']: for key in aggregationPeriod.keys(): if key in modelDescription['streamDef']['aggregation']: aggregationPeriod[key] = modelDescription['streamDef']['aggregation'][key] if 'fields' in modelDescription['streamDef']['aggregation']: for (fieldName, func) in modelDescription['streamDef']['aggregation']['fields']: aggFunctionsDict[fieldName] = str(func) # Do we have any aggregation at all? hasAggregation = False for v in aggregationPeriod.values(): if v != 0: hasAggregation = True break # Convert the aggFunctionsDict to a list aggFunctionList = aggFunctionsDict.items() aggregationInfo = dict(aggregationPeriod) aggregationInfo['fields'] = aggFunctionList streamDef = copy.deepcopy(modelDescription['streamDef']) streamDef['aggregation'] = copy.deepcopy(aggregationInfo) return streamDef
def close(self): """Deletes temporary system objects/files. """ if self._tempDir is not None and os.path.isdir(self._tempDir): self.logger.debug("Removing temporary directory %r", self._tempDir) shutil.rmtree(self._tempDir) self._tempDir = None return
def _readPermutationsFile(self, filename, modelDescription): """ Read the permutations file and initialize the following member variables: _predictedField: field name of the field we are trying to predict _permutations: Dict containing the full permutations dictionary. _flattenedPermutations: Dict containing the flattened version of _permutations. The keys leading to the value in the dict are joined with a period to create the new key and permute variables within encoders are pulled out of the encoder. _encoderNames: keys from self._permutations of only the encoder variables. _reportKeys: The 'report' list from the permutations file. This is a list of the items from each experiment's pickled results file that should be included in the final report. The format of each item is a string of key names separated by colons, each key being one level deeper into the experiment results dict. For example, 'key1:key2'. _filterFunc: a user-supplied function that can be used to filter out specific permutation combinations. _optimizeKey: which report key to optimize for _maximize: True if we should try and maximize the optimizeKey metric. False if we should minimize it. _dummyModelParamsFunc: a user-supplied function that can be used to artificially generate HTMPredictionModel results. When supplied, the model is not actually run through the OPF, but instead is run through a "Dummy Model" (nupic.swarming.ModelRunner. OPFDummyModelRunner). This function returns the params dict used to control various options in the dummy model (the returned metric, the execution time, etc.). This is used for hypersearch algorithm development. Parameters: --------------------------------------------------------- filename: Name of permutations file retval: None """ # Open and execute the permutations file vars = {} permFile = execfile(filename, globals(), vars) # Read in misc info. self._reportKeys = vars.get('report', []) self._filterFunc = vars.get('permutationFilter', None) self._dummyModelParamsFunc = vars.get('dummyModelParams', None) self._predictedField = None # default self._predictedFieldEncoder = None # default self._fixedFields = None # default # The fastSwarm variable, if present, contains the params from a best # model from a previous swarm. If present, use info from that to seed # a fast swarm self._fastSwarmModelParams = vars.get('fastSwarmModelParams', None) if self._fastSwarmModelParams is not None: encoders = self._fastSwarmModelParams['structuredParams']['modelParams']\ ['sensorParams']['encoders'] self._fixedFields = [] for fieldName in encoders: if encoders[fieldName] is not None: self._fixedFields.append(fieldName) if 'fixedFields' in vars: self._fixedFields = vars['fixedFields'] # Get min number of particles per swarm from either permutations file or # config. self._minParticlesPerSwarm = vars.get('minParticlesPerSwarm') if self._minParticlesPerSwarm == None: self._minParticlesPerSwarm = Configuration.get( 'nupic.hypersearch.minParticlesPerSwarm') self._minParticlesPerSwarm = int(self._minParticlesPerSwarm) # Enable logic to kill off speculative swarms when an earlier sprint # has found that it contains poorly performing field combination? self._killUselessSwarms = vars.get('killUselessSwarms', True) # The caller can request that the predicted field ALWAYS be included ("yes") # or optionally include ("auto"). The setting of "no" is N/A and ignored # because in that case the encoder for the predicted field will not even # be present in the permutations file. # When set to "yes", this will force the first sprint to try the predicted # field only (the legacy mode of swarming). # When set to "auto", the first sprint tries all possible fields (one at a # time) in the first sprint. self._inputPredictedField = vars.get("inputPredictedField", "yes") # Try all possible 3-field combinations? Normally, we start with the best # 2-field combination as a base. When this flag is set though, we try # all possible 3-field combinations which takes longer but can find a # better model. self._tryAll3FieldCombinations = vars.get('tryAll3FieldCombinations', False) # Always include timestamp fields in the 3-field swarms? # This is a less compute intensive version of tryAll3FieldCombinations. # Instead of trying ALL possible 3 field combinations, it just insures # that the timestamp fields (dayOfWeek, timeOfDay, weekend) are never left # out when generating the 3-field swarms. self._tryAll3FieldCombinationsWTimestamps = vars.get( 'tryAll3FieldCombinationsWTimestamps', False) # Allow the permutations file to override minFieldContribution. This would # be set to a negative number for large swarms so that you don't disqualify # a field in an early sprint just because it did poorly there. Sometimes, # a field that did poorly in an early sprint could help accuracy when # added in a later sprint minFieldContribution = vars.get('minFieldContribution', None) if minFieldContribution is not None: self._minFieldContribution = minFieldContribution # Allow the permutations file to override maxBranching. maxBranching = vars.get('maxFieldBranching', None) if maxBranching is not None: self._maxBranching = maxBranching # Read in the optimization info. if 'maximize' in vars: self._optimizeKey = vars['maximize'] self._maximize = True elif 'minimize' in vars: self._optimizeKey = vars['minimize'] self._maximize = False else: raise RuntimeError("Permutations file '%s' does not include a maximize" " or minimize metric.") # The permutations file is the new location for maxModels. The old location, # in the jobParams is deprecated. maxModels = vars.get('maxModels') if maxModels is not None: if self._maxModels is None: self._maxModels = maxModels else: raise RuntimeError('It is an error to specify maxModels both in the job' ' params AND in the permutations file.') # Figure out if what kind of search this is: # # If it's a temporal prediction search: # the first sprint has 1 swarm, with just the predicted field # elif it's a spatial prediction search: # the first sprint has N swarms, each with predicted field + one # other field. # elif it's a classification search: # the first sprint has N swarms, each with 1 field inferenceType = modelDescription['modelParams']['inferenceType'] if not InferenceType.validate(inferenceType): raise ValueError("Invalid inference type %s" %inferenceType) if inferenceType in [InferenceType.TemporalMultiStep, InferenceType.NontemporalMultiStep]: # If it does not have a separate encoder for the predicted field that # goes to the classifier, it is a legacy multi-step network classifierOnlyEncoder = None for encoder in modelDescription["modelParams"]["sensorParams"]\ ["encoders"].values(): if encoder.get("classifierOnly", False) \ and encoder["fieldname"] == vars.get('predictedField', None): classifierOnlyEncoder = encoder break if classifierOnlyEncoder is None or self._inputPredictedField=="yes": # If we don't have a separate encoder for the classifier (legacy # MultiStep) or the caller explicitly wants to include the predicted # field, then use the legacy temporal search methodology. self._searchType = HsSearchType.legacyTemporal else: self._searchType = HsSearchType.temporal elif inferenceType in [InferenceType.TemporalNextStep, InferenceType.TemporalAnomaly]: self._searchType = HsSearchType.legacyTemporal elif inferenceType in (InferenceType.TemporalClassification, InferenceType.NontemporalClassification): self._searchType = HsSearchType.classification else: raise RuntimeError("Unsupported inference type: %s" % inferenceType) # Get the predicted field. Note that even classification experiments # have a "predicted" field - which is the field that contains the # classification value. self._predictedField = vars.get('predictedField', None) if self._predictedField is None: raise RuntimeError("Permutations file '%s' does not have the required" " 'predictedField' variable" % filename) # Read in and validate the permutations dict if 'permutations' not in vars: raise RuntimeError("Permutations file '%s' does not define permutations" % filename) if not isinstance(vars['permutations'], dict): raise RuntimeError("Permutations file '%s' defines a permutations variable " "but it is not a dict") self._encoderNames = [] self._permutations = vars['permutations'] self._flattenedPermutations = dict() def _flattenPermutations(value, keys): if ':' in keys[-1]: raise RuntimeError("The permutation variable '%s' contains a ':' " "character, which is not allowed.") flatKey = _flattenKeys(keys) if isinstance(value, PermuteEncoder): self._encoderNames.append(flatKey) # If this is the encoder for the predicted field, save its name. if value.fieldName == self._predictedField: self._predictedFieldEncoder = flatKey # Store the flattened representations of the variables within the # encoder. for encKey, encValue in value.kwArgs.iteritems(): if isinstance(encValue, PermuteVariable): self._flattenedPermutations['%s:%s' % (flatKey, encKey)] = encValue elif isinstance(value, PermuteVariable): self._flattenedPermutations[flatKey] = value else: if isinstance(value, PermuteVariable): self._flattenedPermutations[key] = value rApply(self._permutations, _flattenPermutations)
def _checkForOrphanedModels (self): """If there are any models that haven't been updated in a while, consider them dead, and mark them as hidden in our resultsDB. We also change the paramsHash and particleHash of orphaned models so that we can re-generate that particle and/or model again if we desire. Parameters: ---------------------------------------------------------------------- retval: """ self.logger.debug("Checking for orphaned models older than %s" % \ (self._modelOrphanIntervalSecs)) while True: orphanedModelId = self._cjDAO.modelAdoptNextOrphan(self._jobID, self._modelOrphanIntervalSecs) if orphanedModelId is None: return self.logger.info("Removing orphaned model: %d" % (orphanedModelId)) # Change the model hash and params hash as stored in the models table so # that we can insert a new model with the same paramsHash for attempt in range(100): paramsHash = hashlib.md5("OrphanParams.%d.%d" % (orphanedModelId, attempt)).digest() particleHash = hashlib.md5("OrphanParticle.%d.%d" % (orphanedModelId, attempt)).digest() try: self._cjDAO.modelSetFields(orphanedModelId, dict(engParamsHash=paramsHash, engParticleHash=particleHash)) success = True except: success = False if success: break if not success: raise RuntimeError("Unexpected failure to change paramsHash and " "particleHash of orphaned model") # Mark this model as complete, with reason "orphaned" self._cjDAO.modelSetCompleted(modelID=orphanedModelId, completionReason=ClientJobsDAO.CMPL_REASON_ORPHAN, completionMsg="Orphaned") # Update our results DB immediately, rather than wait for the worker # to inform us. This insures that the getParticleInfos() calls we make # below don't include this particle. Setting the metricResult to None # sets it to worst case self._resultsDB.update(modelID=orphanedModelId, modelParams=None, modelParamsHash=paramsHash, metricResult=None, completed = True, completionReason = ClientJobsDAO.CMPL_REASON_ORPHAN, matured = True, numRecords = 0)
def _hsStatePeriodicUpdate(self, exhaustedSwarmId=None): """ Periodically, check to see if we should remove a certain field combination from evaluation (because it is doing so poorly) or move on to the next sprint (add in more fields). This method is called from _getCandidateParticleAndSwarm(), which is called right before we try and create a new model to run. Parameters: ----------------------------------------------------------------------- removeSwarmId: If not None, force a change to the current set of active swarms by removing this swarm. This is used in situations where we can't find any new unique models to create in this swarm. In these situations, we update the hypersearch state regardless of the timestamp of the last time another worker updated it. """ if self._hsState is None: self._hsState = HsState(self) # Read in current state from the DB self._hsState.readStateFromDB() # This will hold the list of completed swarms that we find completedSwarms = set() # Mark the exhausted swarm as completing/completed, if any if exhaustedSwarmId is not None: self.logger.info("Removing swarm %s from the active set " "because we can't find any new unique particle " "positions" % (exhaustedSwarmId)) # Is it completing or completed? (particles, _, _, _, _) = self._resultsDB.getParticleInfos( swarmId=exhaustedSwarmId, matured=False) if len(particles) > 0: exhaustedSwarmStatus = 'completing' else: exhaustedSwarmStatus = 'completed' # Kill all swarms that don't need to be explored based on the most recent # information. if self._killUselessSwarms: self._hsState.killUselessSwarms() # For all swarms that were in the 'completing' state, see if they have # completed yet. # # Note that we are not quite sure why this doesn't automatically get handled # when we receive notification that a model finally completed in a swarm. # But, we ARE running into a situation, when speculativeParticles is off, # where we have one or more swarms in the 'completing' state even though all # models have since finished. This logic will serve as a failsafe against # this situation. completingSwarms = self._hsState.getCompletingSwarms() for swarmId in completingSwarms: # Is it completed? (particles, _, _, _, _) = self._resultsDB.getParticleInfos( swarmId=swarmId, matured=False) if len(particles) == 0: completedSwarms.add(swarmId) # Are there any swarms we can remove (because they have matured)? completedSwarmGens = self._resultsDB.getMaturedSwarmGenerations() priorCompletedSwarms = self._hsState.getCompletedSwarms() for (swarmId, genIdx, errScore) in completedSwarmGens: # Don't need to report it if the swarm already completed if swarmId in priorCompletedSwarms: continue completedList = self._swarmTerminator.recordDataPoint( swarmId=swarmId, generation=genIdx, errScore=errScore) # Update status message statusMsg = "Completed generation #%d of swarm '%s' with a best" \ " errScore of %g" % (genIdx, swarmId, errScore) if len(completedList) > 0: statusMsg = "%s. Matured swarm(s): %s" % (statusMsg, completedList) self.logger.info(statusMsg) self._cjDAO.jobSetFields (jobID=self._jobID, fields=dict(engStatus=statusMsg), useConnectionID=False, ignoreUnchanged=True) # Special test mode to check which swarms have terminated if 'NTA_TEST_recordSwarmTerminations' in os.environ: while True: resultsStr = self._cjDAO.jobGetFields(self._jobID, ['results'])[0] if resultsStr is None: results = {} else: results = json.loads(resultsStr) if not 'terminatedSwarms' in results: results['terminatedSwarms'] = {} for swarm in completedList: if swarm not in results['terminatedSwarms']: results['terminatedSwarms'][swarm] = (genIdx, self._swarmTerminator.swarmScores[swarm]) newResultsStr = json.dumps(results) if newResultsStr == resultsStr: break updated = self._cjDAO.jobSetFieldIfEqual(jobID=self._jobID, fieldName='results', curValue=resultsStr, newValue = json.dumps(results)) if updated: break if len(completedList) > 0: for name in completedList: self.logger.info("Swarm matured: %s. Score at generation %d: " "%s" % (name, genIdx, errScore)) completedSwarms = completedSwarms.union(completedList) if len(completedSwarms)==0 and (exhaustedSwarmId is None): return # We need to mark one or more swarms as completed, keep trying until # successful, or until some other worker does it for us. while True: if exhaustedSwarmId is not None: self._hsState.setSwarmState(exhaustedSwarmId, exhaustedSwarmStatus) # Mark the completed swarms as completed for swarmId in completedSwarms: self._hsState.setSwarmState(swarmId, 'completed') # If nothing changed, we're done if not self._hsState.isDirty(): return # Update the shared Hypersearch state now # This will do nothing and return False if some other worker beat us to it success = self._hsState.writeStateToDB() if success: # Go through and cancel all models that are still running, except for # the best model. Once the best model changes, the one that used to be # best (and has matured) will notice that and stop itself at that point. jobResultsStr = self._cjDAO.jobGetFields(self._jobID, ['results'])[0] if jobResultsStr is not None: jobResults = json.loads(jobResultsStr) bestModelId = jobResults.get('bestModel', None) else: bestModelId = None for swarmId in list(completedSwarms): (_, modelIds, _, _, _) = self._resultsDB.getParticleInfos( swarmId=swarmId, completed=False) if bestModelId in modelIds: modelIds.remove(bestModelId) if len(modelIds) == 0: continue self.logger.info("Killing the following models in swarm '%s' because" "the swarm is being terminated: %s" % (swarmId, str(modelIds))) for modelId in modelIds: self._cjDAO.modelSetFields(modelId, dict(engStop=ClientJobsDAO.STOP_REASON_KILLED), ignoreUnchanged = True) return # We were not able to change the state because some other worker beat us # to it. # Get the new state, and try again to apply our changes. self._hsState.readStateFromDB() self.logger.debug("New hsState has been set by some other worker to: " " \n%s" % (pprint.pformat(self._hsState._state, indent=4)))
def _getCandidateParticleAndSwarm (self, exhaustedSwarmId=None): """Find or create a candidate particle to produce a new model. At any one time, there is an active set of swarms in the current sprint, where each swarm in the sprint represents a particular combination of fields. Ideally, we should try to balance the number of models we have evaluated for each swarm at any time. This method will see how many models have been evaluated for each active swarm in the current active sprint(s) and then try and choose a particle from the least represented swarm in the first possible active sprint, with the following constraints/rules: for each active sprint: for each active swarm (preference to those with least# of models so far): 1.) The particle will be created from new (generation #0) if there are not already self._minParticlesPerSwarm particles in the swarm. 2.) Find the first gen that has a completed particle and evolve that particle to the next generation. 3.) If we got to here, we know that we have satisfied the min# of particles for the swarm, and they are all currently running (probably at various generation indexes). Go onto the next swarm If we couldn't find a swarm to allocate a particle in, go onto the next sprint and start allocating particles there.... Parameters: ---------------------------------------------------------------- exhaustedSwarmId: If not None, force a change to the current set of active swarms by marking this swarm as either 'completing' or 'completed'. If there are still models being evaluaed in it, mark it as 'completing', else 'completed. This is used in situations where we can't find any new unique models to create in this swarm. In these situations, we force an update to the hypersearch state so no other worker wastes time try to use this swarm. retval: (exit, particle, swarm) exit: If true, this worker is ready to exit (particle and swarm will be None) particle: Which particle to run swarm: which swarm the particle is in NOTE: When particle and swarm are None and exit is False, it means that we need to wait for one or more other worker(s) to finish their respective models before we can pick a particle to run. This will generally only happen when speculativeParticles is set to False. """ # Cancel search? jobCancel = self._cjDAO.jobGetFields(self._jobID, ['cancel'])[0] if jobCancel: self._jobCancelled = True # Did a worker cancel the job because of an error? (workerCmpReason, workerCmpMsg) = self._cjDAO.jobGetFields(self._jobID, ['workerCompletionReason', 'workerCompletionMsg']) if workerCmpReason == ClientJobsDAO.CMPL_REASON_SUCCESS: self.logger.info("Exiting due to job being cancelled") self._cjDAO.jobSetFields(self._jobID, dict(workerCompletionMsg="Job was cancelled"), useConnectionID=False, ignoreUnchanged=True) else: self.logger.error("Exiting because some worker set the " "workerCompletionReason to %s. WorkerCompletionMsg: %s" % (workerCmpReason, workerCmpMsg)) return (True, None, None) # Perform periodic updates on the Hypersearch state. if self._hsState is not None: priorActiveSwarms = self._hsState.getActiveSwarms() else: priorActiveSwarms = None # Update the HypersearchState, checking for matured swarms, and marking # the passed in swarm as exhausted, if any self._hsStatePeriodicUpdate(exhaustedSwarmId=exhaustedSwarmId) # The above call may have modified self._hsState['activeSwarmIds'] # Log the current set of active swarms activeSwarms = self._hsState.getActiveSwarms() if activeSwarms != priorActiveSwarms: self.logger.info("Active swarms changed to %s (from %s)" % (activeSwarms, priorActiveSwarms)) self.logger.debug("Active swarms: %s" % (activeSwarms)) # If too many model errors were detected, exit totalCmpModels = self._resultsDB.getNumCompletedModels() if totalCmpModels > 5: numErrs = self._resultsDB.getNumErrModels() if (float(numErrs) / totalCmpModels) > self._maxPctErrModels: # Get one of the errors errModelIds = self._resultsDB.getErrModelIds() resInfo = self._cjDAO.modelsGetResultAndStatus([errModelIds[0]])[0] modelErrMsg = resInfo.completionMsg cmpMsg = "%s: Exiting due to receiving too many models failing" \ " from exceptions (%d out of %d). \nModel Exception: %s" % \ (ErrorCodes.tooManyModelErrs, numErrs, totalCmpModels, modelErrMsg) self.logger.error(cmpMsg) # Cancel the entire job now, if it has not already been cancelled workerCmpReason = self._cjDAO.jobGetFields(self._jobID, ['workerCompletionReason'])[0] if workerCmpReason == ClientJobsDAO.CMPL_REASON_SUCCESS: self._cjDAO.jobSetFields( self._jobID, fields=dict( cancel=True, workerCompletionReason = ClientJobsDAO.CMPL_REASON_ERROR, workerCompletionMsg = cmpMsg), useConnectionID=False, ignoreUnchanged=True) return (True, None, None) # If HsState thinks the search is over, exit. It is seeing if the results # on the sprint we just completed are worse than a prior sprint. if self._hsState.isSearchOver(): cmpMsg = "Exiting because results did not improve in most recently" \ " completed sprint." self.logger.info(cmpMsg) self._cjDAO.jobSetFields(self._jobID, dict(workerCompletionMsg=cmpMsg), useConnectionID=False, ignoreUnchanged=True) return (True, None, None) # Search successive active sprints, until we can find a candidate particle # to work with sprintIdx = -1 while True: # Is this sprint active? sprintIdx += 1 (active, eos) = self._hsState.isSprintActive(sprintIdx) # If no more sprints to explore: if eos: # If any prior ones are still being explored, finish up exploring them if self._hsState.anyGoodSprintsActive(): self.logger.info("No more sprints to explore, waiting for prior" " sprints to complete") return (False, None, None) # Else, we're done else: cmpMsg = "Exiting because we've evaluated all possible field " \ "combinations" self._cjDAO.jobSetFields(self._jobID, dict(workerCompletionMsg=cmpMsg), useConnectionID=False, ignoreUnchanged=True) self.logger.info(cmpMsg) return (True, None, None) if not active: if not self._speculativeParticles: if not self._hsState.isSprintCompleted(sprintIdx): self.logger.info("Waiting for all particles in sprint %d to complete" "before evolving any more particles" % (sprintIdx)) return (False, None, None) continue # ==================================================================== # Look for swarms that have particle "holes" in their generations. That is, # an earlier generation with less than minParticlesPerSwarm. This can # happen if a model that was started eariler got orphaned. If we detect # this, start a new particle in that generation. swarmIds = self._hsState.getActiveSwarms(sprintIdx) for swarmId in swarmIds: firstNonFullGenIdx = self._resultsDB.firstNonFullGeneration( swarmId=swarmId, minNumParticles=self._minParticlesPerSwarm) if firstNonFullGenIdx is None: continue if firstNonFullGenIdx < self._resultsDB.highestGeneration(swarmId): self.logger.info("Cloning an earlier model in generation %d of swarm " "%s (sprintIdx=%s) to replace an orphaned model" % ( firstNonFullGenIdx, swarmId, sprintIdx)) # Clone a random orphaned particle from the incomplete generation (allParticles, allModelIds, errScores, completed, matured) = \ self._resultsDB.getOrphanParticleInfos(swarmId, firstNonFullGenIdx) if len(allModelIds) > 0: # We have seen instances where we get stuck in a loop incessantly # trying to clone earlier models (NUP-1511). My best guess is that # we've already successfully cloned each of the orphaned models at # least once, but still need at least one more. If we don't create # a new particleID, we will never be able to instantiate another # model (since particleID hash is a unique key in the models table). # So, on 1/8/2013 this logic was changed to create a new particleID # whenever we clone an orphan. newParticleId = True self.logger.info("Cloning an orphaned model") # If there is no orphan, clone one of the other particles. We can # have no orphan if this was a speculative generation that only # continued particles completed in the prior generation. else: newParticleId = True self.logger.info("No orphans found, so cloning a non-orphan") (allParticles, allModelIds, errScores, completed, matured) = \ self._resultsDB.getParticleInfos(swarmId=swarmId, genIdx=firstNonFullGenIdx) # Clone that model modelId = random.choice(allModelIds) self.logger.info("Cloning model %r" % (modelId)) (particleState, _, _, _, _) = self._resultsDB.getParticleInfo(modelId) particle = Particle(hsObj = self, resultsDB = self._resultsDB, flattenedPermuteVars=self._flattenedPermutations, newFromClone=particleState, newParticleId=newParticleId) return (False, particle, swarmId) # ==================================================================== # Sort the swarms in priority order, trying the ones with the least # number of models first swarmSizes = numpy.array([self._resultsDB.numModels(x) for x in swarmIds]) swarmSizeAndIdList = zip(swarmSizes, swarmIds) swarmSizeAndIdList.sort() for (_, swarmId) in swarmSizeAndIdList: # ------------------------------------------------------------------- # 1.) The particle will be created from new (at generation #0) if there # are not already self._minParticlesPerSwarm particles in the swarm. (allParticles, allModelIds, errScores, completed, matured) = ( self._resultsDB.getParticleInfos(swarmId)) if len(allParticles) < self._minParticlesPerSwarm: particle = Particle(hsObj=self, resultsDB=self._resultsDB, flattenedPermuteVars=self._flattenedPermutations, swarmId=swarmId, newFarFrom=allParticles) # Jam in the best encoder state found from the first sprint bestPriorModel = None if sprintIdx >= 1: (bestPriorModel, errScore) = self._hsState.bestModelInSprint(0) if bestPriorModel is not None: self.logger.info("Best model and errScore from previous sprint(%d):" " %s, %g" % (0, str(bestPriorModel), errScore)) (baseState, modelId, errScore, completed, matured) \ = self._resultsDB.getParticleInfo(bestPriorModel) particle.copyEncoderStatesFrom(baseState) # Copy the best inference type from the earlier sprint particle.copyVarStatesFrom(baseState, ['modelParams|inferenceType']) # It's best to jiggle the best settings from the prior sprint, so # compute a new position starting from that previous best # Only jiggle the vars we copied from the prior model whichVars = [] for varName in baseState['varStates']: if ':' in varName: whichVars.append(varName) particle.newPosition(whichVars) self.logger.debug("Particle after incorporating encoder vars from best " "model in previous sprint: \n%s" % (str(particle))) return (False, particle, swarmId) # ------------------------------------------------------------------- # 2.) Look for a completed particle to evolve # Note that we use lastDescendent. We only want to evolve particles that # are at their most recent generation index. (readyParticles, readyModelIds, readyErrScores, _, _) = ( self._resultsDB.getParticleInfos(swarmId, genIdx=None, matured=True, lastDescendent=True)) # If we have at least 1 ready particle to evolve... if len(readyParticles) > 0: readyGenIdxs = [x['genIdx'] for x in readyParticles] sortedGenIdxs = sorted(set(readyGenIdxs)) genIdx = sortedGenIdxs[0] # Now, genIdx has the generation of the particle we want to run, # Get a particle from that generation and evolve it. useParticle = None for particle in readyParticles: if particle['genIdx'] == genIdx: useParticle = particle break # If speculativeParticles is off, we don't want to evolve a particle # into the next generation until all particles in the current # generation have completed. if not self._speculativeParticles: (particles, _, _, _, _) = self._resultsDB.getParticleInfos( swarmId, genIdx=genIdx, matured=False) if len(particles) > 0: continue particle = Particle(hsObj=self, resultsDB=self._resultsDB, flattenedPermuteVars=self._flattenedPermutations, evolveFromState=useParticle) return (False, particle, swarmId) # END: for (swarmSize, swarmId) in swarmSizeAndIdList: # No success in this swarm, onto next swarm # ==================================================================== # We couldn't find a particle in this sprint ready to evolve. If # speculative particles is OFF, we have to wait for one or more other # workers to finish up their particles before we can do anything. if not self._speculativeParticles: self.logger.info("Waiting for one or more of the %s swarms " "to complete a generation before evolving any more particles" \ % (str(swarmIds))) return (False, None, None)
def _okToExit(self): """Test if it's OK to exit this worker. This is only called when we run out of prospective new models to evaluate. This method sees if all models have matured yet. If not, it will sleep for a bit and return False. This will indicate to the hypersearch worker that we should keep running, and check again later. This gives this worker a chance to pick up and adopt any model which may become orphaned by another worker before it matures. If all models have matured, this method will send a STOP message to all matured, running models (presummably, there will be just one - the model which thinks it's the best) before returning True. """ # Send an update status periodically to the JobTracker so that it doesn't # think this worker is dead. print >> sys.stderr, "reporter:status:In hypersearchV2: _okToExit" # Any immature models still running? if not self._jobCancelled: (_, modelIds, _, _, _) = self._resultsDB.getParticleInfos(matured=False) if len(modelIds) > 0: self.logger.info("Ready to end hyperseach, but not all models have " \ "matured yet. Sleeping a bit to wait for all models " \ "to mature.") # Sleep for a bit, no need to check for orphaned models very often time.sleep(5.0 * random.random()) return False # All particles have matured, send a STOP signal to any that are still # running. (_, modelIds, _, _, _) = self._resultsDB.getParticleInfos(completed=False) for modelId in modelIds: self.logger.info("Stopping model %d because the search has ended" \ % (modelId)) self._cjDAO.modelSetFields(modelId, dict(engStop=ClientJobsDAO.STOP_REASON_STOPPED), ignoreUnchanged = True) # Update the HsState to get the accurate field contributions. self._hsStatePeriodicUpdate() pctFieldContributions, absFieldContributions = \ self._hsState.getFieldContributions() # Update the results field with the new field contributions. jobResultsStr = self._cjDAO.jobGetFields(self._jobID, ['results'])[0] if jobResultsStr is not None: jobResults = json.loads(jobResultsStr) else: jobResults = {} # Update the fieldContributions field. if pctFieldContributions != jobResults.get('fieldContributions', None): jobResults['fieldContributions'] = pctFieldContributions jobResults['absoluteFieldContributions'] = absFieldContributions isUpdated = self._cjDAO.jobSetFieldIfEqual(self._jobID, fieldName='results', curValue=jobResultsStr, newValue=json.dumps(jobResults)) if isUpdated: self.logger.info('Successfully updated the field contributions:%s', pctFieldContributions) else: self.logger.info('Failed updating the field contributions, ' \ 'another hypersearch worker must have updated it') return True
def createModels(self, numModels=1): """Create one or more new models for evaluation. These should NOT be models that we already know are in progress (i.e. those that have been sent to us via recordModelProgress). We return a list of models to the caller (HypersearchWorker) and if one can be successfully inserted into the models table (i.e. it is not a duplicate) then HypersearchWorker will turn around and call our runModel() method, passing in this model. If it is a duplicate, HypersearchWorker will call this method again. A model is a duplicate if either the modelParamsHash or particleHash is identical to another entry in the model table. The numModels is provided by HypersearchWorker as a suggestion as to how many models to generate. This particular implementation only ever returns 1 model. Before choosing some new models, we first do a sweep for any models that may have been abandonded by failed workers. If/when we detect an abandoned model, we mark it as complete and orphaned and hide it from any subsequent queries to our ResultsDB. This effectively considers it as if it never existed. We also change the paramsHash and particleHash in the model record of the models table so that we can create another model with the same params and particle status and run it (which we then do immediately). The modelParamsHash returned for each model should be a hash (max allowed size of ClientJobsDAO.hashMaxSize) that uniquely identifies this model by it's params and the optional particleHash should be a hash of the particleId and generation index. Every model that gets placed into the models database, either by this worker or another worker, will have these hashes computed for it. The recordModelProgress gets called for every model in the database and the hash is used to tell which, if any, are the same as the ones this worker generated. NOTE: We check first ourselves for possible duplicates using the paramsHash before we return a model. If HypersearchWorker failed to insert it (because some other worker beat us to it), it will turn around and call our recordModelProgress with that other model so that we now know about it. It will then call createModels() again. This methods returns an exit boolean and the model to evaluate. If there is no model to evalulate, we may return False for exit because we want to stay alive for a while, waiting for all other models to finish. This gives us a chance to detect and pick up any possibly orphaned model by another worker. Parameters: ---------------------------------------------------------------------- numModels: number of models to generate retval: (exit, models) exit: true if this worker should exit. models: list of tuples, one for each model. Each tuple contains: (modelParams, modelParamsHash, particleHash) modelParams is a dictionary containing the following elements: structuredParams: dictionary containing all variables for this model, with encoders represented as a dict within this dict (or None if they are not included. particleState: dictionary containing the state of this particle. This includes the position and velocity of each of it's variables, the particleId, and the particle generation index. It contains the following keys: id: The particle Id of the particle we are using to generate/track this model. This is a string of the form <hypesearchWorkerId>.<particleIdx> genIdx: the particle's generation index. This starts at 0 and increments every time we move the particle to a new position. swarmId: The swarmId, which is a string of the form <encoder>.<encoder>... that describes this swarm varStates: dict of the variable states. The key is the variable name, the value is a dict of the variable's position, velocity, bestPosition, bestResult, etc. """ # Check for and mark orphaned models self._checkForOrphanedModels() modelResults = [] for _ in xrange(numModels): candidateParticle = None # If we've reached the max # of model to evaluate, we're done. if (self._maxModels is not None and (self._resultsDB.numModels() - self._resultsDB.getNumErrModels()) >= self._maxModels): return (self._okToExit(), []) # If we don't already have a particle to work on, get a candidate swarm and # particle to work with. If None is returned for the particle it means # either that the search is over (if exitNow is also True) or that we need # to wait for other workers to finish up their models before we can pick # another particle to run (if exitNow is False). if candidateParticle is None: (exitNow, candidateParticle, candidateSwarm) = ( self._getCandidateParticleAndSwarm()) if candidateParticle is None: if exitNow: return (self._okToExit(), []) else: # Send an update status periodically to the JobTracker so that it doesn't # think this worker is dead. print >> sys.stderr, "reporter:status:In hypersearchV2: speculativeWait" time.sleep(self._speculativeWaitSecondsMax * random.random()) return (False, []) useEncoders = candidateSwarm.split('.') numAttempts = 0 # Loop until we can create a unique model that we haven't seen yet. while True: # If this is the Nth attempt with the same candidate, agitate it a bit # to find a new unique position for it. if numAttempts >= 1: self.logger.debug("Agitating particle to get unique position after %d " "failed attempts in a row" % (numAttempts)) candidateParticle.agitate() # Create the hierarchical params expected by the base description. Note # that this is where we incorporate encoders that have no permuted # values in them. position = candidateParticle.getPosition() structuredParams = dict() def _buildStructuredParams(value, keys): flatKey = _flattenKeys(keys) # If it's an encoder, either put in None if it's not used, or replace # all permuted constructor params with the actual position. if flatKey in self._encoderNames: if flatKey in useEncoders: # Form encoder dict, substituting in chosen permutation values. return value.getDict(flatKey, position) # Encoder not used. else: return None # Regular top-level variable. elif flatKey in position: return position[flatKey] # Fixed override of a parameter in the base description. else: return value structuredParams = rCopy(self._permutations, _buildStructuredParams, discardNoneKeys=False) # Create the modelParams. modelParams = dict( structuredParams=structuredParams, particleState = candidateParticle.getState() ) # And the hashes. m = hashlib.md5() m.update(sortedJSONDumpS(structuredParams)) m.update(self._baseDescriptionHash) paramsHash = m.digest() particleInst = "%s.%s" % (modelParams['particleState']['id'], modelParams['particleState']['genIdx']) particleHash = hashlib.md5(particleInst).digest() # Increase attempt counter numAttempts += 1 # If this is a new one, and passes the filter test, exit with it. # TODO: There is currently a problem with this filters implementation as # it relates to self._maxUniqueModelAttempts. When there is a filter in # effect, we should try a lot more times before we decide we have # exhausted the parameter space for this swarm. The question is, how many # more times? if self._filterFunc and not self._filterFunc(structuredParams): valid = False else: valid = True if valid and self._resultsDB.getModelIDFromParamsHash(paramsHash) is None: break # If we've exceeded the max allowed number of attempts, mark this swarm # as completing or completed, so we don't try and allocate any more new # particles to it, and pick another. if numAttempts >= self._maxUniqueModelAttempts: (exitNow, candidateParticle, candidateSwarm) \ = self._getCandidateParticleAndSwarm( exhaustedSwarmId=candidateSwarm) if candidateParticle is None: if exitNow: return (self._okToExit(), []) else: time.sleep(self._speculativeWaitSecondsMax * random.random()) return (False, []) numAttempts = 0 useEncoders = candidateSwarm.split('.') # Log message if self.logger.getEffectiveLevel() <= logging.DEBUG: self.logger.debug("Submitting new potential model to HypersearchWorker: \n%s" % (pprint.pformat(modelParams, indent=4))) modelResults.append((modelParams, paramsHash, particleHash)) return (False, modelResults)
def recordModelProgress(self, modelID, modelParams, modelParamsHash, results, completed, completionReason, matured, numRecords): """Record or update the results for a model. This is called by the HSW whenever it gets results info for another model, or updated results on a model that is still running. The first time this is called for a given modelID, the modelParams will contain the params dict for that model and the modelParamsHash will contain the hash of the params. Subsequent updates of the same modelID will have params and paramsHash values of None (in order to save overhead). The Hypersearch object should save these results into it's own working memory into some table, which it then uses to determine what kind of new models to create next time createModels() is called. Parameters: ---------------------------------------------------------------------- modelID: ID of this model in models table modelParams: params dict for this model, or None if this is just an update of a model that it already previously reported on. See the comments for the createModels() method for a description of this dict. modelParamsHash: hash of the modelParams dict, generated by the worker that put it into the model database. results: tuple containing (allMetrics, optimizeMetric). Each is a dict containing metricName:result pairs. . May be none if we have no results yet. completed: True if the model has completed evaluation, False if it is still running (and these are online results) completionReason: One of the ClientJobsDAO.CMPL_REASON_XXX equates matured: True if this model has matured. In most cases, once a model matures, it will complete as well. The only time a model matures and does not complete is if it's currently the best model and we choose to keep it running to generate predictions. numRecords: Number of records that have been processed so far by this model. """ if results is None: metricResult = None else: metricResult = results[1].values()[0] # Update our database. errScore = self._resultsDB.update(modelID=modelID, modelParams=modelParams,modelParamsHash=modelParamsHash, metricResult=metricResult, completed=completed, completionReason=completionReason, matured=matured, numRecords=numRecords) # Log message. self.logger.debug('Received progress on model %d: completed: %s, ' 'cmpReason: %s, numRecords: %d, errScore: %s' , modelID, completed, completionReason, numRecords, errScore) # Log best so far. (bestModelID, bestResult) = self._resultsDB.bestModelIdAndErrScore() self.logger.debug('Best err score seen so far: %s on model %s' % \ (bestResult, bestModelID))
def runModel(self, modelID, jobID, modelParams, modelParamsHash, jobsDAO, modelCheckpointGUID): """Run the given model. This runs the model described by 'modelParams'. Periodically, it updates the results seen on the model to the model database using the databaseAO (database Access Object) methods. Parameters: ------------------------------------------------------------------------- modelID: ID of this model in models table jobID: ID for this hypersearch job in the jobs table modelParams: parameters of this specific model modelParams is a dictionary containing the name/value pairs of each variable we are permuting over. Note that variables within an encoder spec have their name structure as: <encoderName>.<encodrVarName> modelParamsHash: hash of modelParamValues jobsDAO jobs data access object - the interface to the jobs database where model information is stored modelCheckpointGUID: A persistent, globally-unique identifier for constructing the model checkpoint key """ # We're going to make an assumption that if we're not using streams, that # we also don't need checkpoints saved. For now, this assumption is OK # (if there are no streams, we're typically running on a single machine # and just save models to files) but we may want to break this out as # a separate controllable parameter in the future if not self._createCheckpoints: modelCheckpointGUID = None # Register this model in our database self._resultsDB.update(modelID=modelID, modelParams=modelParams, modelParamsHash=modelParamsHash, metricResult = None, completed = False, completionReason = None, matured = False, numRecords = 0) # Get the structured params, which we pass to the base description structuredParams = modelParams['structuredParams'] if self.logger.getEffectiveLevel() <= logging.DEBUG: self.logger.debug("Running Model. \nmodelParams: %s, \nmodelID=%s, " % \ (pprint.pformat(modelParams, indent=4), modelID)) # Record time.clock() so that we can report on cpu time cpuTimeStart = time.clock() # Run the experiment. This will report the results back to the models # database for us as well. logLevel = self.logger.getEffectiveLevel() try: if self._dummyModel is None or self._dummyModel is False: (cmpReason, cmpMsg) = runModelGivenBaseAndParams( modelID=modelID, jobID=jobID, baseDescription=self._baseDescription, params=structuredParams, predictedField=self._predictedField, reportKeys=self._reportKeys, optimizeKey=self._optimizeKey, jobsDAO=jobsDAO, modelCheckpointGUID=modelCheckpointGUID, logLevel=logLevel, predictionCacheMaxRecords=self._predictionCacheMaxRecords) else: dummyParams = dict(self._dummyModel) dummyParams['permutationParams'] = structuredParams if self._dummyModelParamsFunc is not None: permInfo = dict(structuredParams) permInfo ['generation'] = modelParams['particleState']['genIdx'] dummyParams.update(self._dummyModelParamsFunc(permInfo)) (cmpReason, cmpMsg) = runDummyModel( modelID=modelID, jobID=jobID, params=dummyParams, predictedField=self._predictedField, reportKeys=self._reportKeys, optimizeKey=self._optimizeKey, jobsDAO=jobsDAO, modelCheckpointGUID=modelCheckpointGUID, logLevel=logLevel, predictionCacheMaxRecords=self._predictionCacheMaxRecords) # Write out the completion reason and message jobsDAO.modelSetCompleted(modelID, completionReason = cmpReason, completionMsg = cmpMsg, cpuTime = time.clock() - cpuTimeStart) except InvalidConnectionException, e: self.logger.warn("%s", e)
def _escape(s): """Escape commas, tabs, newlines and dashes in a string Commas are encoded as tabs """ assert isinstance(s, str), \ "expected %s but got %s; value=%s" % (type(str), type(s), s) s = s.replace("\\", "\\\\") s = s.replace("\n", "\\n") s = s.replace("\t", "\\t") s = s.replace(",", "\t") return s
def _engineServicesRunning(): """ Return true if the engine services are running """ process = subprocess.Popen(["ps", "aux"], stdout=subprocess.PIPE) stdout = process.communicate()[0] result = process.returncode if result != 0: raise RuntimeError("Unable to check for running client job manager") # See if the CJM is running running = False for line in stdout.split("\n"): if "python" in line and "clientjobmanager.client_job_manager" in line: running = True break return running
def runWithConfig(swarmConfig, options, outDir=None, outputLabel="default", permWorkDir=None, verbosity=1): """ Starts a swarm, given an dictionary configuration. @param swarmConfig {dict} A complete [swarm description](http://nupic.docs.numenta.org/0.7.0.dev0/guides/swarming/running.html#the-swarm-description) object. @param outDir {string} Optional path to write swarm details (defaults to current working directory). @param outputLabel {string} Optional label for output (defaults to "default"). @param permWorkDir {string} Optional location of working directory (defaults to current working directory). @param verbosity {int} Optional (1,2,3) increasing verbosity of output. @returns {object} Model parameters """ global g_currentVerbosityLevel g_currentVerbosityLevel = verbosity # Generate the description and permutations.py files in the same directory # for reference. if outDir is None: outDir = os.getcwd() if permWorkDir is None: permWorkDir = os.getcwd() _checkOverwrite(options, outDir) _generateExpFilesFromSwarmDescription(swarmConfig, outDir) options["expDescConfig"] = swarmConfig options["outputLabel"] = outputLabel options["outDir"] = outDir options["permWorkDir"] = permWorkDir runOptions = _injectDefaultOptions(options) _validateOptions(runOptions) return _runAction(runOptions)
def runWithJsonFile(expJsonFilePath, options, outputLabel, permWorkDir): """ Starts a swarm, given a path to a JSON file containing configuration. This function is meant to be used with a CLI wrapper that passes command line arguments in through the options parameter. @param expJsonFilePath {string} Path to a JSON file containing the complete [swarm description](http://nupic.docs.numenta.org/0.7.0.dev0/guides/swarming/running.html#the-swarm-description). @param options {dict} CLI options. @param outputLabel {string} Label for output. @param permWorkDir {string} Location of working directory. @returns {int} Swarm job id. """ if "verbosityCount" in options: verbosity = options["verbosityCount"] del options["verbosityCount"] else: verbosity = 1 _setupInterruptHandling() with open(expJsonFilePath, "r") as jsonFile: expJsonConfig = json.loads(jsonFile.read()) outDir = os.path.dirname(expJsonFilePath) return runWithConfig(expJsonConfig, options, outDir=outDir, outputLabel=outputLabel, permWorkDir=permWorkDir, verbosity=verbosity)
def runWithPermutationsScript(permutationsFilePath, options, outputLabel, permWorkDir): """ Starts a swarm, given a path to a permutations.py script. This function is meant to be used with a CLI wrapper that passes command line arguments in through the options parameter. @param permutationsFilePath {string} Path to permutations.py. @param options {dict} CLI options. @param outputLabel {string} Label for output. @param permWorkDir {string} Location of working directory. @returns {object} Model parameters. """ global g_currentVerbosityLevel if "verbosityCount" in options: g_currentVerbosityLevel = options["verbosityCount"] del options["verbosityCount"] else: g_currentVerbosityLevel = 1 _setupInterruptHandling() options["permutationsScriptPath"] = permutationsFilePath options["outputLabel"] = outputLabel options["outDir"] = permWorkDir options["permWorkDir"] = permWorkDir # Assume it's a permutations python script runOptions = _injectDefaultOptions(options) _validateOptions(runOptions) return _runAction(runOptions)
def _backupFile(filePath): """Back up a file Parameters: ---------------------------------------------------------------------- retval: Filepath of the back-up """ assert os.path.exists(filePath) stampNum = 0 (prefix, suffix) = os.path.splitext(filePath) while True: backupPath = "%s.%d%s" % (prefix, stampNum, suffix) stampNum += 1 if not os.path.exists(backupPath): break shutil.copyfile(filePath, backupPath) return backupPath
def _iterModels(modelIDs): """Creates an iterator that returns ModelInfo elements for the given modelIDs WARNING: The order of ModelInfo elements returned by the iterator may not match the order of the given modelIDs Parameters: ---------------------------------------------------------------------- modelIDs: A sequence of model identifiers (e.g., as returned by _HyperSearchJob.queryModelIDs()). retval: Iterator that returns ModelInfo elements for the given modelIDs (NOTE:possibly in a different order) """ class ModelInfoIterator(object): """ModelInfo iterator implementation class """ # Maximum number of ModelInfo elements to load into cache whenever # cache empties __CACHE_LIMIT = 1000 debug=False def __init__(self, modelIDs): """ Parameters: ---------------------------------------------------------------------- modelIDs: a sequence of Nupic model identifiers for which this iterator will return _NupicModelInfo instances. NOTE: The returned instances are NOT guaranteed to be in the same order as the IDs in modelIDs sequence. retval: nothing """ # Make our own copy in case caller changes model id list during iteration self.__modelIDs = tuple(modelIDs) if self.debug: _emit(Verbosity.DEBUG, "MODELITERATOR: __init__; numModelIDs=%s" % len(self.__modelIDs)) self.__nextIndex = 0 self.__modelCache = collections.deque() return def __iter__(self): """Iterator Protocol function Parameters: ---------------------------------------------------------------------- retval: self """ return self def next(self): """Iterator Protocol function Parameters: ---------------------------------------------------------------------- retval: A _NupicModelInfo instance or raises StopIteration to signal end of iteration. """ return self.__getNext() def __getNext(self): """Implementation of the next() Iterator Protocol function. When the modelInfo cache becomes empty, queries Nupic and fills the cache with the next set of NupicModelInfo instances. Parameters: ---------------------------------------------------------------------- retval: A _NupicModelInfo instance or raises StopIteration to signal end of iteration. """ if self.debug: _emit(Verbosity.DEBUG, "MODELITERATOR: __getNext(); modelCacheLen=%s" % ( len(self.__modelCache))) if not self.__modelCache: self.__fillCache() if not self.__modelCache: raise StopIteration() return self.__modelCache.popleft() def __fillCache(self): """Queries Nupic and fills an empty modelInfo cache with the next set of _NupicModelInfo instances Parameters: ---------------------------------------------------------------------- retval: nothing """ assert (not self.__modelCache) # Assemble a list of model IDs to look up numModelIDs = len(self.__modelIDs) if self.__modelIDs else 0 if self.__nextIndex >= numModelIDs: return idRange = self.__nextIndex + self.__CACHE_LIMIT if idRange > numModelIDs: idRange = numModelIDs lookupIDs = self.__modelIDs[self.__nextIndex:idRange] self.__nextIndex += (idRange - self.__nextIndex) # Query Nupic for model info of all models in the look-up list # NOTE: the order of results may not be the same as lookupIDs infoList = _clientJobsDB().modelsInfo(lookupIDs) assert len(infoList) == len(lookupIDs), \ "modelsInfo returned %s elements; expected %s." % \ (len(infoList), len(lookupIDs)) # Create _NupicModelInfo instances and add them to cache for rawInfo in infoList: modelInfo = _NupicModelInfo(rawInfo=rawInfo) self.__modelCache.append(modelInfo) assert len(self.__modelCache) == len(lookupIDs), \ "Added %s elements to modelCache; expected %s." % \ (len(self.__modelCache), len(lookupIDs)) if self.debug: _emit(Verbosity.DEBUG, "MODELITERATOR: Leaving __fillCache(); modelCacheLen=%s" % \ (len(self.__modelCache),)) return ModelInfoIterator(modelIDs)
def pickupSearch(self): """Pick up the latest search from a saved jobID and monitor it to completion Parameters: ---------------------------------------------------------------------- retval: nothing """ self.__searchJob = self.loadSavedHyperSearchJob( permWorkDir=self._options["permWorkDir"], outputLabel=self._options["outputLabel"]) self.monitorSearchJob()
def monitorSearchJob(self): """ Parameters: ---------------------------------------------------------------------- retval: nothing """ assert self.__searchJob is not None jobID = self.__searchJob.getJobID() startTime = time.time() lastUpdateTime = datetime.now() # Monitor HyperSearch and report progress # NOTE: may be -1 if it can't be determined expectedNumModels = self.__searchJob.getExpectedNumModels( searchMethod = self._options["searchMethod"]) lastNumFinished = 0 finishedModelIDs = set() finishedModelStats = _ModelStats() # Keep track of the worker state, results, and milestones from the job # record lastWorkerState = None lastJobResults = None lastModelMilestones = None lastEngStatus = None hyperSearchFinished = False while not hyperSearchFinished: jobInfo = self.__searchJob.getJobStatus(self._workers) # Check for job completion BEFORE processing models; NOTE: this permits us # to process any models that we may not have accounted for in the # previous iteration. hyperSearchFinished = jobInfo.isFinished() # Look for newly completed models, and process them modelIDs = self.__searchJob.queryModelIDs() _emit(Verbosity.DEBUG, "Current number of models is %d (%d of them completed)" % ( len(modelIDs), len(finishedModelIDs))) if len(modelIDs) > 0: # Build a list of modelIDs to check for completion checkModelIDs = [] for modelID in modelIDs: if modelID not in finishedModelIDs: checkModelIDs.append(modelID) del modelIDs # Process newly completed models if checkModelIDs: _emit(Verbosity.DEBUG, "Checking %d models..." % (len(checkModelIDs))) errorCompletionMsg = None for (i, modelInfo) in enumerate(_iterModels(checkModelIDs)): _emit(Verbosity.DEBUG, "[%s] Checking completion: %s" % (i, modelInfo)) if modelInfo.isFinished(): finishedModelIDs.add(modelInfo.getModelID()) finishedModelStats.update(modelInfo) if (modelInfo.getCompletionReason().isError() and not errorCompletionMsg): errorCompletionMsg = modelInfo.getCompletionMsg() # Update the set of all encountered metrics keys (we will use # these to print column names in reports.csv) metrics = modelInfo.getReportMetrics() self.__foundMetrcsKeySet.update(metrics.keys()) numFinished = len(finishedModelIDs) # Print current completion stats if numFinished != lastNumFinished: lastNumFinished = numFinished if expectedNumModels is None: expModelsStr = "" else: expModelsStr = "of %s" % (expectedNumModels) stats = finishedModelStats print ("<jobID: %s> %s %s models finished [success: %s; %s: %s; %s: " "%s; %s: %s; %s: %s; %s: %s; %s: %s]" % ( jobID, numFinished, expModelsStr, #stats.numCompletedSuccess, (stats.numCompletedEOF+stats.numCompletedStopped), "EOF" if stats.numCompletedEOF else "eof", stats.numCompletedEOF, "STOPPED" if stats.numCompletedStopped else "stopped", stats.numCompletedStopped, "KILLED" if stats.numCompletedKilled else "killed", stats.numCompletedKilled, "ERROR" if stats.numCompletedError else "error", stats.numCompletedError, "ORPHANED" if stats.numCompletedError else "orphaned", stats.numCompletedOrphaned, "UNKNOWN" if stats.numCompletedOther else "unknown", stats.numCompletedOther)) # Print the first error message from the latest batch of completed # models if errorCompletionMsg: print "ERROR MESSAGE: %s" % errorCompletionMsg # Print the new worker state, if it changed workerState = jobInfo.getWorkerState() if workerState != lastWorkerState: print "##>> UPDATED WORKER STATE: \n%s" % (pprint.pformat(workerState, indent=4)) lastWorkerState = workerState # Print the new job results, if it changed jobResults = jobInfo.getResults() if jobResults != lastJobResults: print "####>> UPDATED JOB RESULTS: \n%s (elapsed time: %g secs)" \ % (pprint.pformat(jobResults, indent=4), time.time()-startTime) lastJobResults = jobResults # Print the new model milestones if they changed modelMilestones = jobInfo.getModelMilestones() if modelMilestones != lastModelMilestones: print "##>> UPDATED MODEL MILESTONES: \n%s" % ( pprint.pformat(modelMilestones, indent=4)) lastModelMilestones = modelMilestones # Print the new engine status if it changed engStatus = jobInfo.getEngStatus() if engStatus != lastEngStatus: print "##>> UPDATED STATUS: \n%s" % (engStatus) lastEngStatus = engStatus # Sleep before next check if not hyperSearchFinished: if self._options["timeout"] != None: if ((datetime.now() - lastUpdateTime) > timedelta(minutes=self._options["timeout"])): print "Timeout reached, exiting" self.__cjDAO.jobCancel(jobID) sys.exit(1) time.sleep(1) # Tabulate results modelIDs = self.__searchJob.queryModelIDs() print "Evaluated %s models" % len(modelIDs) print "HyperSearch finished!" jobInfo = self.__searchJob.getJobStatus(self._workers) print "Worker completion message: %s" % (jobInfo.getWorkerCompletionMsg())
def _launchWorkers(self, cmdLine, numWorkers): """ Launch worker processes to execute the given command line Parameters: ----------------------------------------------- cmdLine: The command line for each worker numWorkers: number of workers to launch """ self._workers = [] for i in range(numWorkers): stdout = tempfile.NamedTemporaryFile(delete=False) stderr = tempfile.NamedTemporaryFile(delete=False) p = subprocess.Popen(cmdLine, bufsize=1, env=os.environ, shell=True, stdin=None, stdout=stdout, stderr=stderr) p._stderr_file = stderr p._stdout_file = stdout self._workers.append(p)
def __startSearch(self): """Starts HyperSearch as a worker or runs it inline for the "dryRun" action Parameters: ---------------------------------------------------------------------- retval: the new _HyperSearchJob instance representing the HyperSearch job """ # This search uses a pre-existing permutations script params = _ClientJobUtils.makeSearchJobParamsDict(options=self._options, forRunning=True) if self._options["action"] == "dryRun": args = [sys.argv[0], "--params=%s" % (json.dumps(params))] print print "==================================================================" print "RUNNING PERMUTATIONS INLINE as \"DRY RUN\"..." print "==================================================================" jobID = hypersearch_worker.main(args) else: cmdLine = _setUpExports(self._options["exports"]) # Begin the new search. The {JOBID} string is replaced by the actual # jobID returned from jobInsert. cmdLine += "$HYPERSEARCH" maxWorkers = self._options["maxWorkers"] jobID = self.__cjDAO.jobInsert( client="GRP", cmdLine=cmdLine, params=json.dumps(params), minimumWorkers=1, maximumWorkers=maxWorkers, jobType=self.__cjDAO.JOB_TYPE_HS) cmdLine = "python -m nupic.swarming.hypersearch_worker" \ " --jobID=%d" % (jobID) self._launchWorkers(cmdLine, maxWorkers) searchJob = _HyperSearchJob(jobID) # Save search ID to file (this is used for report generation) self.__saveHyperSearchJobID( permWorkDir=self._options["permWorkDir"], outputLabel=self._options["outputLabel"], hyperSearchJob=searchJob) if self._options["action"] == "dryRun": print "Successfully executed \"dry-run\" hypersearch, jobID=%d" % (jobID) else: print "Successfully submitted new HyperSearch job, jobID=%d" % (jobID) _emit(Verbosity.DEBUG, "Each worker executing the command line: %s" % (cmdLine,)) return searchJob
def generateReport(cls, options, replaceReport, hyperSearchJob, metricsKeys): """Prints all available results in the given HyperSearch job and emits model information to the permutations report csv. The job may be completed or still in progress. Parameters: ---------------------------------------------------------------------- options: NupicRunPermutations options dict replaceReport: True to replace existing report csv, if any; False to append to existing report csv, if any hyperSearchJob: _HyperSearchJob instance; if None, will get it from saved jobID, if any metricsKeys: sequence of report metrics key names to include in report; if None, will pre-scan all modelInfos to generate a complete list of metrics key names. retval: model parameters """ # Load _HyperSearchJob instance from storage, if not provided if hyperSearchJob is None: hyperSearchJob = cls.loadSavedHyperSearchJob( permWorkDir=options["permWorkDir"], outputLabel=options["outputLabel"]) modelIDs = hyperSearchJob.queryModelIDs() bestModel = None # If metricsKeys was not provided, pre-scan modelInfos to create the list; # this is needed by _ReportCSVWriter # Also scan the parameters to generate a list of encoders and search # parameters metricstmp = set() searchVar = set() for modelInfo in _iterModels(modelIDs): if modelInfo.isFinished(): vars = modelInfo.getParamLabels().keys() searchVar.update(vars) metrics = modelInfo.getReportMetrics() metricstmp.update(metrics.keys()) if metricsKeys is None: metricsKeys = metricstmp # Create a csv report writer reportWriter = _ReportCSVWriter(hyperSearchJob=hyperSearchJob, metricsKeys=metricsKeys, searchVar=searchVar, outputDirAbsPath=options["permWorkDir"], outputLabel=options["outputLabel"], replaceReport=replaceReport) # Tallies of experiment dispositions modelStats = _ModelStats() #numCompletedOther = long(0) print "\nResults from all experiments:" print "----------------------------------------------------------------" # Get common optimization metric info from permutations script searchParams = hyperSearchJob.getParams() (optimizationMetricKey, maximizeMetric) = ( _PermutationUtils.getOptimizationMetricInfo(searchParams)) # Print metrics, while looking for the best model formatStr = None # NOTE: we may find additional metrics if HyperSearch is still running foundMetricsKeySet = set(metricsKeys) sortedMetricsKeys = [] # pull out best Model from jobs table jobInfo = _clientJobsDB().jobInfo(hyperSearchJob.getJobID()) # Try to return a decent error message if the job was cancelled for some # reason. if jobInfo.cancel == 1: raise Exception(jobInfo.workerCompletionMsg) try: results = json.loads(jobInfo.results) except Exception, e: print "json.loads(jobInfo.results) raised an exception. " \ "Here is some info to help with debugging:" print "jobInfo: ", jobInfo print "jobInfo.results: ", jobInfo.results print "EXCEPTION: ", e raise bestModelNum = results["bestModel"] bestModelIterIndex = None # performance metrics for the entire job totalWallTime = 0 totalRecords = 0 # At the end, we will sort the models by their score on the optimization # metric scoreModelIDDescList = [] for (i, modelInfo) in enumerate(_iterModels(modelIDs)): # Output model info to report csv reportWriter.emit(modelInfo) # Update job metrics totalRecords+=modelInfo.getNumRecords() format = "%Y-%m-%d %H:%M:%S" startTime = modelInfo.getStartTime() if modelInfo.isFinished(): endTime = modelInfo.getEndTime() st = datetime.strptime(startTime, format) et = datetime.strptime(endTime, format) totalWallTime+=(et-st).seconds # Tabulate experiment dispositions modelStats.update(modelInfo) # For convenience expDesc = modelInfo.getModelDescription() reportMetrics = modelInfo.getReportMetrics() optimizationMetrics = modelInfo.getOptimizationMetrics() if modelInfo.getModelID() == bestModelNum: bestModel = modelInfo bestModelIterIndex=i bestMetric = optimizationMetrics.values()[0] # Keep track of the best-performing model if optimizationMetrics: assert len(optimizationMetrics) == 1, ( "expected 1 opt key, but got %d (%s) in %s" % ( len(optimizationMetrics), optimizationMetrics, modelInfo)) # Append to our list of modelIDs and scores if modelInfo.getCompletionReason().isEOF(): scoreModelIDDescList.append((optimizationMetrics.values()[0], modelInfo.getModelID(), modelInfo.getGeneratedDescriptionFile(), modelInfo.getParamLabels())) print "[%d] Experiment %s\n(%s):" % (i, modelInfo, expDesc) if (modelInfo.isFinished() and not (modelInfo.getCompletionReason().isStopped or modelInfo.getCompletionReason().isEOF())): print ">> COMPLETION MESSAGE: %s" % modelInfo.getCompletionMsg() if reportMetrics: # Update our metrics key set and format string foundMetricsKeySet.update(reportMetrics.iterkeys()) if len(sortedMetricsKeys) != len(foundMetricsKeySet): sortedMetricsKeys = sorted(foundMetricsKeySet) maxKeyLen = max([len(k) for k in sortedMetricsKeys]) formatStr = " %%-%ds" % (maxKeyLen+2) # Print metrics for key in sortedMetricsKeys: if key in reportMetrics: if key == optimizationMetricKey: m = "%r (*)" % reportMetrics[key] else: m = "%r" % reportMetrics[key] print formatStr % (key+":"), m print # Summarize results print "--------------------------------------------------------------" if len(modelIDs) > 0: print "%d experiments total (%s).\n" % ( len(modelIDs), ("all completed successfully" if (modelStats.numCompletedKilled + modelStats.numCompletedEOF) == len(modelIDs) else "WARNING: %d models have not completed or there were errors" % ( len(modelIDs) - ( modelStats.numCompletedKilled + modelStats.numCompletedEOF + modelStats.numCompletedStopped)))) if modelStats.numStatusOther > 0: print "ERROR: models with unexpected status: %d" % ( modelStats.numStatusOther) print "WaitingToStart: %d" % modelStats.numStatusWaitingToStart print "Running: %d" % modelStats.numStatusRunning print "Completed: %d" % modelStats.numStatusCompleted if modelStats.numCompletedOther > 0: print " ERROR: models with unexpected completion reason: %d" % ( modelStats.numCompletedOther) print " ran to EOF: %d" % modelStats.numCompletedEOF print " ran to stop signal: %d" % modelStats.numCompletedStopped print " were orphaned: %d" % modelStats.numCompletedOrphaned print " killed off: %d" % modelStats.numCompletedKilled print " failed: %d" % modelStats.numCompletedError assert modelStats.numStatusOther == 0, "numStatusOther=%s" % ( modelStats.numStatusOther) assert modelStats.numCompletedOther == 0, "numCompletedOther=%s" % ( modelStats.numCompletedOther) else: print "0 experiments total." # Print out the field contributions print global gCurrentSearch jobStatus = hyperSearchJob.getJobStatus(gCurrentSearch._workers) jobResults = jobStatus.getResults() if "fieldContributions" in jobResults: print "Field Contributions:" pprint.pprint(jobResults["fieldContributions"], indent=4) else: print "Field contributions info not available" # Did we have an optimize key? if bestModel is not None: maxKeyLen = max([len(k) for k in sortedMetricsKeys]) maxKeyLen = max(maxKeyLen, len(optimizationMetricKey)) formatStr = " %%-%ds" % (maxKeyLen+2) bestMetricValue = bestModel.getOptimizationMetrics().values()[0] optimizationMetricName = bestModel.getOptimizationMetrics().keys()[0] print print "Best results on the optimization metric %s (maximize=%s):" % ( optimizationMetricName, maximizeMetric) print "[%d] Experiment %s (%s):" % ( bestModelIterIndex, bestModel, bestModel.getModelDescription()) print formatStr % (optimizationMetricName+":"), bestMetricValue print print "Total number of Records processed: %d" % totalRecords print print "Total wall time for all models: %d" % totalWallTime hsJobParams = hyperSearchJob.getParams() # Were we asked to write out the top N model description files? if options["genTopNDescriptions"] > 0: print "\nGenerating description files for top %d models..." % ( options["genTopNDescriptions"]) scoreModelIDDescList.sort() scoreModelIDDescList = scoreModelIDDescList[ 0:options["genTopNDescriptions"]] i = -1 for (score, modelID, description, paramLabels) in scoreModelIDDescList: i += 1 outDir = os.path.join(options["permWorkDir"], "model_%d" % (i)) print "Generating description file for model %s at %s" % \ (modelID, outDir) if not os.path.exists(outDir): os.makedirs(outDir) # Fix up the location to the base description file. # importBaseDescription() chooses the file relative to the calling file. # The calling file is in outDir. # The base description is in the user-specified "outDir" base_description_path = os.path.join(options["outDir"], "description.py") base_description_relpath = os.path.relpath(base_description_path, start=outDir) description = description.replace( "importBaseDescription('base.py', config)", "importBaseDescription('%s', config)" % base_description_relpath) fd = open(os.path.join(outDir, "description.py"), "wb") fd.write(description) fd.close() # Generate a csv file with the parameter settings in it fd = open(os.path.join(outDir, "params.csv"), "wb") writer = csv.writer(fd) colNames = paramLabels.keys() colNames.sort() writer.writerow(colNames) row = [paramLabels[x] for x in colNames] writer.writerow(row) fd.close() print "Generating model params file..." # Generate a model params file alongside the description.py mod = imp.load_source("description", os.path.join(outDir, "description.py")) model_description = mod.descriptionInterface.getModelDescription() fd = open(os.path.join(outDir, "model_params.py"), "wb") fd.write("%s\nMODEL_PARAMS = %s" % (getCopyrightHead(), pprint.pformat(model_description))) fd.close() print reportWriter.finalize() return model_description
def loadSavedHyperSearchJob(cls, permWorkDir, outputLabel): """Instantiates a _HyperSearchJob instance from info saved in file Parameters: ---------------------------------------------------------------------- permWorkDir: Directory path for saved jobID file outputLabel: Label string for incorporating into file name for saved jobID retval: _HyperSearchJob instance; raises exception if not found """ jobID = cls.__loadHyperSearchJobID(permWorkDir=permWorkDir, outputLabel=outputLabel) searchJob = _HyperSearchJob(nupicJobID=jobID) return searchJob
def __saveHyperSearchJobID(cls, permWorkDir, outputLabel, hyperSearchJob): """Saves the given _HyperSearchJob instance's jobID to file Parameters: ---------------------------------------------------------------------- permWorkDir: Directory path for saved jobID file outputLabel: Label string for incorporating into file name for saved jobID hyperSearchJob: _HyperSearchJob instance retval: nothing """ jobID = hyperSearchJob.getJobID() filePath = cls.__getHyperSearchJobIDFilePath(permWorkDir=permWorkDir, outputLabel=outputLabel) if os.path.exists(filePath): _backupFile(filePath) d = dict(hyperSearchJobID = jobID) with open(filePath, "wb") as jobIdPickleFile: pickle.dump(d, jobIdPickleFile)
def __loadHyperSearchJobID(cls, permWorkDir, outputLabel): """Loads a saved jobID from file Parameters: ---------------------------------------------------------------------- permWorkDir: Directory path for saved jobID file outputLabel: Label string for incorporating into file name for saved jobID retval: HyperSearch jobID; raises exception if not found. """ filePath = cls.__getHyperSearchJobIDFilePath(permWorkDir=permWorkDir, outputLabel=outputLabel) jobID = None with open(filePath, "r") as jobIdPickleFile: jobInfo = pickle.load(jobIdPickleFile) jobID = jobInfo["hyperSearchJobID"] return jobID
def __getHyperSearchJobIDFilePath(cls, permWorkDir, outputLabel): """Returns filepath where to store HyperSearch JobID Parameters: ---------------------------------------------------------------------- permWorkDir: Directory path for saved jobID file outputLabel: Label string for incorporating into file name for saved jobID retval: Filepath where to store HyperSearch JobID """ # Get the base path and figure out the path of the report file. basePath = permWorkDir # Form the name of the output csv file that will contain all the results filename = "%s_HyperSearchJobID.pkl" % (outputLabel,) filepath = os.path.join(basePath, filename) return filepath
def emit(self, modelInfo): """Emit model info to csv file Parameters: ---------------------------------------------------------------------- modelInfo: _NupicModelInfo instance retval: nothing """ # Open/init csv file, if needed if self.__csvFileObj is None: # sets up self.__sortedVariableNames and self.__csvFileObj self.__openAndInitCSVFile(modelInfo) csv = self.__csvFileObj # Emit model info row to report.csv print >> csv, "%s, " % (self.__searchJobID), print >> csv, "%s, " % (modelInfo.getModelID()), print >> csv, "%s, " % (modelInfo.statusAsString()), if modelInfo.isFinished(): print >> csv, "%s, " % (modelInfo.getCompletionReason()), else: print >> csv, "NA, ", if not modelInfo.isWaitingToStart(): print >> csv, "%s, " % (modelInfo.getStartTime()), else: print >> csv, "NA, ", if modelInfo.isFinished(): dateFormat = "%Y-%m-%d %H:%M:%S" startTime = modelInfo.getStartTime() endTime = modelInfo.getEndTime() print >> csv, "%s, " % endTime, st = datetime.strptime(startTime, dateFormat) et = datetime.strptime(endTime, dateFormat) print >> csv, "%s, " % (str((et - st).seconds)), else: print >> csv, "NA, ", print >> csv, "NA, ", print >> csv, "%s, " % str(modelInfo.getModelDescription()), print >> csv, "%s, " % str(modelInfo.getNumRecords()), paramLabelsDict = modelInfo.getParamLabels() for key in self.__sortedVariableNames: # Some values are complex structures,.. which need to be represented as # strings if key in paramLabelsDict: print >> csv, "%s, " % (paramLabelsDict[key]), else: print >> csv, "None, ", metrics = modelInfo.getReportMetrics() for key in self.__sortedMetricsKeys: value = metrics.get(key, "NA") value = str(value) value = value.replace("\n", " ") print >> csv, "%s, " % (value), print >> csv
def finalize(self): """Close file and print report/backup csv file paths Parameters: ---------------------------------------------------------------------- retval: nothing """ if self.__csvFileObj is not None: # Done with file self.__csvFileObj.close() self.__csvFileObj = None print "Report csv saved in %s" % (self.__reportCSVPath,) if self.__backupCSVPath: print "Previous report csv file was backed up to %s" % \ (self.__backupCSVPath,) else: print "Nothing was written to report csv file."
def __openAndInitCSVFile(self, modelInfo): """ - Backs up old report csv file; - opens the report csv file in append or overwrite mode (per self.__replaceReport); - emits column fields; - sets up self.__sortedVariableNames, self.__csvFileObj, self.__backupCSVPath, and self.__reportCSVPath Parameters: ---------------------------------------------------------------------- modelInfo: First _NupicModelInfo instance passed to emit() retval: nothing """ # Get the base path and figure out the path of the report file. basePath = self.__outputDirAbsPath # Form the name of the output csv file that will contain all the results reportCSVName = "%s_Report.csv" % (self.__outputLabel,) reportCSVPath = self.__reportCSVPath = os.path.join(basePath, reportCSVName) # If a report CSV file already exists, back it up backupCSVPath = None if os.path.exists(reportCSVPath): backupCSVPath = self.__backupCSVPath = _backupFile(reportCSVPath) # Open report file if self.__replaceReport: mode = "w" else: mode = "a" csv = self.__csvFileObj = open(reportCSVPath, mode) # If we are appending, add some blank line separators if not self.__replaceReport and backupCSVPath: print >> csv print >> csv # Print the column names print >> csv, "jobID, ", print >> csv, "modelID, ", print >> csv, "status, " , print >> csv, "completionReason, ", print >> csv, "startTime, ", print >> csv, "endTime, ", print >> csv, "runtime(s), " , print >> csv, "expDesc, ", print >> csv, "numRecords, ", for key in self.__sortedVariableNames: print >> csv, "%s, " % key, for key in self.__sortedMetricsKeys: print >> csv, "%s, " % key, print >> csv
def getJobStatus(self, workers): """ Parameters: ---------------------------------------------------------------------- workers: If this job was launched outside of the nupic job engine, then this is an array of subprocess Popen instances, one for each worker retval: _NupicJob.JobStatus instance """ jobInfo = self.JobStatus(self.__nupicJobID, workers) return jobInfo
def queryModelIDs(self): """Queuries DB for model IDs of all currently instantiated models associated with this HyperSearch job. See also: _iterModels() Parameters: ---------------------------------------------------------------------- retval: A sequence of Nupic modelIDs """ jobID = self.getJobID() modelCounterPairs = _clientJobsDB().modelsGetUpdateCounters(jobID) modelIDs = tuple(x[0] for x in modelCounterPairs) return modelIDs
def makeSearchJobParamsDict(cls, options, forRunning=False): """Constructs a dictionary of HyperSearch parameters suitable for converting to json and passing as the params argument to ClientJobsDAO.jobInsert() Parameters: ---------------------------------------------------------------------- options: NupicRunPermutations options dict forRunning: True if the params are for running a Hypersearch job; False if params are for introspection only. retval: A dictionary of HyperSearch parameters for ClientJobsDAO.jobInsert() """ if options["searchMethod"] == "v2": hsVersion = "v2" else: raise Exception("Unsupported search method: %r" % options["searchMethod"]) maxModels = options["maxPermutations"] if options["action"] == "dryRun" and maxModels is None: maxModels = 1 useTerminators = options["useTerminators"] if useTerminators is None: params = { "hsVersion": hsVersion, "maxModels": maxModels, } else: params = { "hsVersion": hsVersion, "useTerminators": useTerminators, "maxModels": maxModels, } if forRunning: params["persistentJobGUID"] = str(uuid.uuid1()) if options["permutationsScriptPath"]: params["permutationsPyFilename"] = options["permutationsScriptPath"] elif options["expDescConfig"]: params["description"] = options["expDescConfig"] else: with open(options["expDescJsonPath"], mode="r") as fp: params["description"] = json.load(fp) return params