def generateStats(filename, maxSamples = None,): """ Collect statistics for each of the fields in the user input data file and return a stats dict object. Parameters: ------------------------------------------------------------------------------ filename: The path and name of the data file. maxSamples: Upper bound on the number of rows to be processed retval: A dictionary of dictionaries. The top level keys are the field names and the corresponding values are the statistics collected for the individual file. Example: { 'consumption':{'min':0,'max':90,'mean':50,...}, 'gym':{'numDistinctCategories':10,...}, ... } """ # Mapping from field type to stats collector object statsCollectorMapping = {'float': FloatStatsCollector, 'int': IntStatsCollector, 'string': StringStatsCollector, 'datetime': DateTimeStatsCollector, 'bool': BoolStatsCollector, } filename = resource_filename("nupic.datafiles", filename) print "*"*40 print "Collecting statistics for file:'%s'" % (filename,) dataFile = FileRecordStream(filename) # Initialize collector objects # statsCollectors list holds statsCollector objects for each field statsCollectors = [] for fieldName, fieldType, fieldSpecial in dataFile.getFields(): # Find the corresponding stats collector for each field based on field type # and intialize an instance statsCollector = \ statsCollectorMapping[fieldType](fieldName, fieldType, fieldSpecial) statsCollectors.append(statsCollector) # Now collect the stats if maxSamples is None: maxSamples = 500000 for i in xrange(maxSamples): record = dataFile.getNextRecord() if record is None: break for i, value in enumerate(record): statsCollectors[i].addValue(value) # stats dict holds the statistics for each field stats = {} for statsCollector in statsCollectors: statsCollector.getStats(stats) # We don't want to include reset field in permutations # TODO: handle reset field in a clean way if dataFile.getResetFieldIdx() is not None: resetFieldName,_,_ = dataFile.getFields()[dataFile.reset] stats.pop(resetFieldName) if VERBOSITY > 0: pprint.pprint(stats) return stats
def checkpoint(self, checkpointSink, maxRows): """ [virtual method override] Save a checkpoint of the prediction output stream. The checkpoint comprises up to maxRows of the most recent inference records. Parameters: ---------------------------------------------------------------------- checkpointSink: A File-like object where predictions checkpoint data, if any, will be stored. maxRows: Maximum number of most recent inference rows to checkpoint. """ checkpointSink.truncate() if self.__dataset is None: if self.__checkpointCache is not None: self.__checkpointCache.seek(0) shutil.copyfileobj(self.__checkpointCache, checkpointSink) checkpointSink.flush() return else: # Nothing to checkpoint return self.__dataset.flush() totalDataRows = self.__dataset.getDataRowCount() if totalDataRows == 0: # Nothing to checkpoint return # Open reader of prediction file (suppress missingValues conversion) reader = FileRecordStream(self.__datasetPath, missingValues=[]) # Create CSV writer for writing checkpoint rows writer = csv.writer(checkpointSink) # Write the header row to checkpoint sink -- just field names writer.writerow(reader.getFieldNames()) # Determine number of rows to checkpoint numToWrite = min(maxRows, totalDataRows) # Skip initial rows to get to the rows that we actually need to checkpoint numRowsToSkip = totalDataRows - numToWrite for i in xrange(numRowsToSkip): reader.next() # Write the data rows to checkpoint sink numWritten = 0 while True: row = reader.getNextRecord() if row is None: break row = [str(element) for element in row] #print "DEBUG: _BasicPredictionWriter: checkpointing row: %r" % (row,) writer.writerow(row) numWritten += 1 assert numWritten == numToWrite, \ "numWritten (%s) != numToWrite (%s)" % (numWritten, numToWrite) checkpointSink.flush() return
def generateDataset(aggregationInfo, inputFilename, outputFilename=None): """Generate a dataset of aggregated values Parameters: ---------------------------------------------------------------------------- aggregationInfo: a dictionary that contains the following entries - fields: a list of pairs. Each pair is a field name and an aggregation function (e.g. sum). The function will be used to aggregate multiple values during the aggregation period. aggregation period: 0 or more of unit=value fields; allowed units are: [years months] | [weeks days hours minutes seconds milliseconds microseconds] NOTE: years and months are mutually-exclusive with the other units. See getEndTime() and _aggregate() for more details. Example1: years=1, months=6, Example2: hours=1, minutes=30, If none of the period fields are specified or if all that are specified have values of 0, then aggregation will be suppressed, and the given inputFile parameter value will be returned. inputFilename: filename of the input dataset within examples/prediction/data outputFilename: name for the output file. If not given, a name will be generated based on the input filename and the aggregation params retval: Name of the generated output file. This will be the same as the input file name if no aggregation needed to be performed If the input file contained a time field, sequence id field or reset field that were not specified in aggregationInfo fields, those fields will be added automatically with the following rules: 1. The order will be R, S, T, rest of the fields 2. The aggregation function for all will be to pick the first: lambda x: x[0] Returns: the path of the aggregated data file if aggregation was performed (in the same directory as the given input file); if aggregation did not need to be performed, then the given inputFile argument value is returned. """ # Create the input stream inputFullPath = resource_filename("nupic.datafiles", inputFilename) inputObj = FileRecordStream(inputFullPath) # Instantiate the aggregator aggregator = Aggregator(aggregationInfo=aggregationInfo, inputFields=inputObj.getFields()) # Is it a null aggregation? If so, just return the input file unmodified if aggregator.isNullAggregation(): return inputFullPath # ------------------------------------------------------------------------ # If we were not given an output filename, create one based on the # aggregation settings if outputFilename is None: outputFilename = 'agg_%s' % \ os.path.splitext(os.path.basename(inputFullPath))[0] timePeriods = 'years months weeks days '\ 'hours minutes seconds milliseconds microseconds' for k in timePeriods.split(): if aggregationInfo.get(k, 0) > 0: outputFilename += '_%s_%d' % (k, aggregationInfo[k]) outputFilename += '.csv' outputFilename = os.path.join(os.path.dirname(inputFullPath), outputFilename) # ------------------------------------------------------------------------ # If some other process already started creating this file, simply # wait for it to finish and return without doing anything lockFilePath = outputFilename + '.please_wait' if os.path.isfile(outputFilename) or \ os.path.isfile(lockFilePath): while os.path.isfile(lockFilePath): print('Waiting for %s to be fully written by another process' % \ lockFilePath) time.sleep(1) return outputFilename # Create the lock file lockFD = open(lockFilePath, 'w') # ------------------------------------------------------------------------- # Create the output stream outputObj = FileRecordStream(streamID=outputFilename, write=True, fields=inputObj.getFields()) # ------------------------------------------------------------------------- # Write all aggregated records to the output while True: inRecord = inputObj.getNextRecord() (aggRecord, aggBookmark) = aggregator.next(inRecord, None) if aggRecord is None and inRecord is None: break if aggRecord is not None: outputObj.appendRecord(aggRecord) return outputFilename
def checkpoint(self, checkpointSink, maxRows): """ [virtual method override] Save a checkpoint of the prediction output stream. The checkpoint comprises up to maxRows of the most recent inference records. Parameters: ---------------------------------------------------------------------- checkpointSink: A File-like object where predictions checkpoint data, if any, will be stored. maxRows: Maximum number of most recent inference rows to checkpoint. """ checkpointSink.truncate() if self.__dataset is None: if self.__checkpointCache is not None: self.__checkpointCache.seek(0) shutil.copyfileobj(self.__checkpointCache, checkpointSink) checkpointSink.flush() return else: # Nothing to checkpoint return self.__dataset.flush() totalDataRows = self.__dataset.getDataRowCount() if totalDataRows == 0: # Nothing to checkpoint return # Open reader of prediction file (suppress missingValues conversion) reader = FileRecordStream(self.__datasetPath, missingValues=[]) # Create CSV writer for writing checkpoint rows writer = csv.writer(checkpointSink) # Write the header row to checkpoint sink -- just field names writer.writerow(reader.getFieldNames()) # Determine number of rows to checkpoint numToWrite = min(maxRows, totalDataRows) # Skip initial rows to get to the rows that we actually need to checkpoint numRowsToSkip = totalDataRows - numToWrite for i in xrange(numRowsToSkip): reader.next() # Write the data rows to checkpoint sink numWritten = 0 while True: row = reader.getNextRecord() if row is None: break; row = [str(element) for element in row] #print "DEBUG: _BasicPredictionWriter: checkpointing row: %r" % (row,) writer.writerow(row) numWritten +=1 assert numWritten == numToWrite, \ "numWritten ({0!s}) != numToWrite ({1!s})".format(numWritten, numToWrite) checkpointSink.flush() return
def testMissingValues(self): print "Beginning Missing Data test..." filename = _getTempFileName() # Some values missing of each type # read dataset from disk, retrieve values # string should return empty string, numeric types sentinelValue print 'Creating tempfile:', filename # write dataset to disk with float, int, and string fields fields = [ FieldMetaInfo('timestamp', FieldMetaType.datetime, FieldMetaSpecial.timestamp), FieldMetaInfo('name', FieldMetaType.string, FieldMetaSpecial.none), FieldMetaInfo('integer', FieldMetaType.integer, FieldMetaSpecial.none), FieldMetaInfo('real', FieldMetaType.float, FieldMetaSpecial.none) ] s = FileRecordStream(streamID=filename, write=True, fields=fields) # Records records = ([datetime(day=1, month=3, year=2010), 'rec_1', 5, 6.5], [ datetime(day=2, month=3, year=2010), '', 8, 7.5 ], [datetime(day=3, month=3, year=2010), 'rec_3', '', 8.5], [ datetime(day=4, month=3, year=2010), 'rec_4', 12, '' ], [datetime(day=5, month=3, year=2010), 'rec_5', -87657496599, 6.5], [ datetime(day=6, month=3, year=2010), 'rec_6', 12, -87657496599 ], [datetime(day=6, month=3, year=2010), str(-87657496599), 12, 6.5]) for r in records: s.appendRecord(list(r)) s.close() # Read the standard file s = FileRecordStream(streamID=filename, write=False) fieldsRead = s.getFields() self.assertEqual(fields, fieldsRead) recordsRead = [] while True: r = s.getNextRecord() if r is None: break print 'Reading record ...' print r recordsRead.append(r) # sort the records by date, so we know for sure which is which sorted(recordsRead, key=lambda rec: rec[0]) # empty string self.assertEqual(SENTINEL_VALUE_FOR_MISSING_DATA, recordsRead[1][1]) # missing int self.assertEqual(SENTINEL_VALUE_FOR_MISSING_DATA, recordsRead[2][2]) # missing float self.assertEqual(SENTINEL_VALUE_FOR_MISSING_DATA, recordsRead[3][3]) # sentinel value in input handled correctly for int field self.assertNotEqual(SENTINEL_VALUE_FOR_MISSING_DATA, recordsRead[4][2]) # sentinel value in input handled correctly for float field self.assertNotEqual(SENTINEL_VALUE_FOR_MISSING_DATA, recordsRead[5][3]) # sentinel value in input handled correctly for string field # this should leave the string as-is, since a missing string # is encoded not with a sentinel value but with an empty string self.assertNotEqual(SENTINEL_VALUE_FOR_MISSING_DATA, recordsRead[6][1])
def generateDataset(aggregationInfo, inputFilename, outputFilename=None): """Generate a dataset of aggregated values Parameters: ---------------------------------------------------------------------------- aggregationInfo: a dictionary that contains the following entries - fields: a list of pairs. Each pair is a field name and an aggregation function (e.g. sum). The function will be used to aggregate multiple values during the aggregation period. aggregation period: 0 or more of unit=value fields; allowed units are: [years months] | [weeks days hours minutes seconds milliseconds microseconds] NOTE: years and months are mutually-exclusive with the other units. See getEndTime() and _aggregate() for more details. Example1: years=1, months=6, Example2: hours=1, minutes=30, If none of the period fields are specified or if all that are specified have values of 0, then aggregation will be suppressed, and the given inputFile parameter value will be returned. inputFilename: filename (or relative path form NTA_DATA_PATH) of the input dataset outputFilename: name for the output file. If not given, a name will be generated based on the input filename and the aggregation params retval: Name of the generated output file. This will be the same as the input file name if no aggregation needed to be performed If the input file contained a time field, sequence id field or reset field that were not specified in aggregationInfo fields, those fields will be added automatically with the following rules: 1. The order will be R, S, T, rest of the fields 2. The aggregation function for all will be to pick the first: lambda x: x[0] Returns: the path of the aggregated data file if aggregation was performed (in the same directory as the given input file); if aggregation did not need to be performed, then the given inputFile argument value is returned. """ # Create the input stream inputFullPath = findDataset(inputFilename) inputObj = FileRecordStream(inputFullPath) # Instantiate the aggregator aggregator = Aggregator(aggregationInfo=aggregationInfo, inputFields=inputObj.getFields()) # Is it a null aggregation? If so, just return the input file unmodified if aggregator.isNullAggregation(): return inputFullPath # ------------------------------------------------------------------------ # If we were not given an output filename, create one based on the # aggregation settings if outputFilename is None: outputFilename = 'agg_%s' % \ os.path.splitext(os.path.basename(inputFullPath))[0] timePeriods = 'years months weeks days '\ 'hours minutes seconds milliseconds microseconds' for k in timePeriods.split(): if aggregationInfo.get(k, 0) > 0: outputFilename += '_%s_%d' % (k, aggregationInfo[k]) outputFilename += '.csv' outputFilename = os.path.join(os.path.dirname(inputFullPath), outputFilename) # ------------------------------------------------------------------------ # If some other process already started creating this file, simply # wait for it to finish and return without doing anything lockFilePath = outputFilename + '.please_wait' if os.path.isfile(outputFilename) or \ os.path.isfile(lockFilePath): while os.path.isfile(lockFilePath): print 'Waiting for %s to be fully written by another process' % \ lockFilePath time.sleep(1) return outputFilename # Create the lock file lockFD = open(lockFilePath, 'w') # ------------------------------------------------------------------------- # Create the output stream outputObj = FileRecordStream(streamID=outputFilename, write=True, fields=inputObj.getFields()) # ------------------------------------------------------------------------- # Write all aggregated records to the output while True: inRecord = inputObj.getNextRecord() (aggRecord, aggBookmark) = aggregator.next(inRecord, None) if aggRecord is None and inRecord is None: break if aggRecord is not None: outputObj.appendRecord(aggRecord) return outputFilename
def testBasic(self): """Runs basic FileRecordStream tests.""" filename = _getTempFileName() # Write a standard file fields = [('name', 'string', ''), ('timestamp', 'datetime', 'T'), ('integer', 'int', ''), ('real', 'float', ''), ('reset', 'int', 'R'), ('sid', 'string', 'S'), ('categoryField', 'int', 'C'),] fieldNames = ['name', 'timestamp', 'integer', 'real', 'reset', 'sid', 'categoryField'] print 'Creating temp file:', filename s = FileRecordStream(streamID=filename, write=True, fields=fields) self.assertTrue(s.getDataRowCount() == 0) # Records records = ( ['rec_1', datetime(day=1, month=3, year=2010), 5, 6.5, 1, 'seq-1', 10], ['rec_2', datetime(day=2, month=3, year=2010), 8, 7.5, 0, 'seq-1', 11], ['rec_3', datetime(day=3, month=3, year=2010), 12, 8.5, 0, 'seq-1', 12]) self.assertTrue(s.getFields() == fields) self.assertTrue(s.getNextRecordIdx() == 0) print 'Writing records ...' for r in records: print list(r) s.appendRecord(list(r)) self.assertTrue(s.getDataRowCount() == 3) recordsBatch = ( ['rec_4', datetime(day=4, month=3, year=2010), 2, 9.5, 1, 'seq-1', 13], ['rec_5', datetime(day=5, month=3, year=2010), 6, 10.5, 0, 'seq-1', 14], ['rec_6', datetime(day=6, month=3, year=2010), 11, 11.5, 0, 'seq-1', 15]) print 'Adding batch of records...' for rec in recordsBatch: print rec s.appendRecords(recordsBatch) self.assertTrue(s.getDataRowCount() == 6) s.close() # Read the standard file s = FileRecordStream(filename) self.assertTrue(s.getDataRowCount() == 6) self.assertTrue(s.getFieldNames() == fieldNames) # Note! this is the number of records read so far self.assertTrue(s.getNextRecordIdx() == 0) readStats = s.getStats() print 'Got stats:', readStats expectedStats = { 'max': [None, None, 12, 11.5, 1, None, 15], 'min': [None, None, 2, 6.5, 0, None, 10] } self.assertTrue(readStats == expectedStats) readRecords = [] print 'Reading records ...' while True: r = s.getNextRecord() print r if r is None: break readRecords.append(r) allRecords = records + recordsBatch for r1, r2 in zip(allRecords, readRecords): print 'Expected:', r1 print 'Read :', r2 self.assertTrue(r1 == r2) s.close()
def testMissingValues(self): print "Beginning Missing Data test..." filename = _getTempFileName() # Some values missing of each type # read dataset from disk, retrieve values # string should return empty string, numeric types sentinelValue print 'Creating tempfile:', filename # write dataset to disk with float, int, and string fields fields = [('timestamp', 'datetime', 'T'), ('name', 'string', ''), ('integer', 'int', ''), ('real', 'float', '')] s = FileRecordStream(streamID=filename, write=True, fields=fields) # Records records = ( [datetime(day=1, month=3, year=2010), 'rec_1', 5, 6.5], [datetime(day=2, month=3, year=2010), '', 8, 7.5], [datetime(day=3, month=3, year=2010), 'rec_3', '', 8.5], [datetime(day=4, month=3, year=2010), 'rec_4', 12, ''], [datetime(day=5, month=3, year=2010), 'rec_5', -87657496599, 6.5], [datetime(day=6, month=3, year=2010), 'rec_6', 12, -87657496599], [datetime(day=6, month=3, year=2010), str(-87657496599), 12, 6.5]) for r in records: s.appendRecord(list(r)) s.close() # Read the standard file s = FileRecordStream(streamID=filename, write=False) fieldsRead = s.getFields() self.assertTrue(fields == fieldsRead) recordsRead = [] while True: r = s.getNextRecord() if r is None: break print 'Reading record ...' print r recordsRead.append(r) # sort the records by date, so we know for sure which is which sorted(recordsRead, key=lambda rec: rec[0]) # empty string self.assertTrue(recordsRead[1][1] == SENTINEL_VALUE_FOR_MISSING_DATA) # missing int self.assertTrue(recordsRead[2][2] == SENTINEL_VALUE_FOR_MISSING_DATA) # missing float self.assertTrue(recordsRead[3][3] == SENTINEL_VALUE_FOR_MISSING_DATA) # sentinel value in input handled correctly for int field self.assertTrue(recordsRead[4][2] != SENTINEL_VALUE_FOR_MISSING_DATA) # sentinel value in input handled correctly for float field self.assertTrue(recordsRead[5][3] != SENTINEL_VALUE_FOR_MISSING_DATA) # sentinel value in input handled correctly for string field # this should leave the string as-is, since a missing string # is encoded not with a sentinel value but with an empty string self.assertTrue(recordsRead[6][1] != SENTINEL_VALUE_FOR_MISSING_DATA)
class StreamReader(RecordStreamIface): """ Implements a stream reader. This is a high level class that owns one or more underlying implementations of a RecordStreamIFace. Each RecordStreamIFace implements the raw reading of records from the record store (which could be a file, hbase table or something else). In the future, we will support joining of two or more RecordStreamIFace's (which is why the streamDef accepts a list of 'stream' elements), but for now only 1 source is supported. The class also implements aggregation of the (in the future) joined records from the sources. This module parses the stream definition (as defined in /nupic/frameworks/opf/jsonschema/stream_def.json), creates the RecordStreamIFace for each source ('stream's element) defined in the stream def, performs aggregation, and returns each record in the correct format according to the desired column names specified in the streamDef. This class implements the RecordStreamIFace interface and thus can be used in place of a raw record stream. This is an example streamDef: { 'version': 1 'info': 'test_hotgym', 'streams': [ {'columns': [u'*'], 'info': u'hotGym.csv', 'last_record': 4000, 'source': u'file://extra/hotgym/hotgym.csv'}. ], 'timeField': 'timestamp', 'aggregation': { 'hours': 1, 'fields': [ ('timestamp', 'first'), ('gym', 'first'), ('consumption', 'sum') ], } } """ def __init__(self, streamDef, bookmark=None, saveOutput=False, isBlocking=True, maxTimeout=0, eofOnTimeout=False): """ Base class constructor, performs common initialization Parameters: ---------------------------------------------------------------- streamDef: The stream definition, potentially containing multiple sources (not supported yet). See /nupic/frameworks/opf/jsonschema/stream_def.json for the format of this dict bookmark: Bookmark to start reading from. This overrides the first_record field of the streamDef if provided. saveOutput: If true, save the output to a csv file in a temp directory. The path to the generated file can be found in the log output. isBlocking: should read operation block *forever* if the next row of data is not available, but the stream is not marked as 'completed' yet? maxTimeout: if isBlocking is False, max seconds to wait for more data before timing out; ignored when isBlocking is True. eofOnTimeout: If True and we get a read timeout (isBlocking must be False to get read timeouts), assume we've reached the end of the input and produce the last aggregated record, if one can be completed. """ # Call superclass constructor super(StreamReader, self).__init__() loggerPrefix = 'com.numenta.nupic.data.StreamReader' self._logger = logging.getLogger(loggerPrefix) jsonhelpers.validate(streamDef, schemaPath=resource_filename( jsonschema.__name__, "stream_def.json")) assert len( streamDef['streams']) == 1, "Only 1 source stream is supported" # Save constructor args sourceDict = streamDef['streams'][0] self._recordCount = 0 self._eofOnTimeout = eofOnTimeout self._logger.debug('Reading stream with the def: %s', sourceDict) # Dictionary to store record statistics (min and max of scalars for now) self._stats = None # --------------------------------------------------------------------- # Get the stream definition params # Limiting window of the stream. It would not return any records until # 'first_record' ID is read (or very first with the ID above that). The # stream will return EOS once it reads record with ID 'last_record' or # above (NOTE: the name 'lastRecord' is misleading because it is NOT # inclusive). firstRecordIdx = sourceDict.get('first_record', None) self._sourceLastRecordIdx = sourceDict.get('last_record', None) # If a bookmark was given, then override first_record from the stream # definition. if bookmark is not None: firstRecordIdx = None # Column names must be provided in the streamdef json # Special case is ['*'], meaning all available names from the record stream self._streamFieldNames = sourceDict.get('columns', None) if self._streamFieldNames != None and self._streamFieldNames[0] == '*': self._needFieldsFiltering = False else: self._needFieldsFiltering = True # Types must be specified in streamdef json, or in case of the # file_recod_stream types could be implicit from the file streamFieldTypes = sourceDict.get('types', None) self._logger.debug('Types from the def: %s', streamFieldTypes) # Validate that all types are valid if streamFieldTypes != None: for dataType in streamFieldTypes: assert (dataType in TYPES) # Reset, sequence and time fields might be provided by streamdef json streamResetFieldName = streamDef.get('resetField', None) streamTimeFieldName = streamDef.get('timeField', None) streamSequenceFieldName = streamDef.get('sequenceIdField', None) self._logger.debug('r, t, s fields: %s, %s, %s', streamResetFieldName, streamTimeFieldName, streamSequenceFieldName) # ======================================================================= # Open up the underlying record store dataUrl = sourceDict.get('source', None) assert (dataUrl is not None) self._openStream(dataUrl, isBlocking, maxTimeout, bookmark, firstRecordIdx) assert (self._recordStore is not None) # ======================================================================= # Prepare the data structures we need for returning just the fields # the caller wants from each record self._recordStoreFields = self._recordStore.getFields() self._recordStoreFieldNames = self._recordStore.getFieldNames() if not self._needFieldsFiltering: self._streamFieldNames = self._recordStoreFieldNames # Build up the field definitions for each field. This is a list of tuples # of (name, type, special) self._streamFields = [] for dstIdx, name in enumerate(self._streamFieldNames): if name not in self._recordStoreFieldNames: raise RuntimeError( "The column '%s' from the stream definition " "is not present in the underlying stream which has the following " "columns: %s" % (name, self._recordStoreFieldNames)) fieldIdx = self._recordStoreFieldNames.index(name) fieldType = self._recordStoreFields[fieldIdx][1] fieldSpecial = self._recordStoreFields[fieldIdx][2] # If the types or specials were defined in the stream definition, # then override what was found in the record store if streamFieldTypes is not None: fieldType = streamFieldTypes[dstIdx] if streamResetFieldName is not None and streamResetFieldName == name: fieldSpecial = 'R' if streamTimeFieldName is not None and streamTimeFieldName == name: fieldSpecial = 'T' if streamSequenceFieldName is not None and streamSequenceFieldName == name: fieldSpecial = 'S' self._streamFields.append( FieldMetaInfo(name, fieldType, fieldSpecial)) # ======================================================================== # Create the aggregator which will handle aggregation of records before # returning them. self._aggregator = Aggregator( aggregationInfo=streamDef.get('aggregation', None), inputFields=self._recordStoreFields, timeFieldName=streamDef.get('timeField', None), sequenceIdFieldName=streamDef.get('sequenceIdField', None), resetFieldName=streamDef.get('resetField', None)) # We rely on the aggregator to tell us the bookmark of the last raw input # that contributed to the aggregated record self._aggBookmark = None # Compute the aggregation period in terms of months and seconds if 'aggregation' in streamDef: self._aggMonthsAndSeconds = nupic.support.aggregationToMonthsSeconds( streamDef.get('aggregation')) else: self._aggMonthsAndSeconds = None # ======================================================================== # Are we saving the generated output to a csv? if saveOutput: tmpDir = tempfile.mkdtemp() outFilename = os.path.join(tmpDir, "generated_output.csv") self._logger.info( "StreamReader: Saving generated records to: '%s'" % outFilename) self._writer = FileRecordStream(streamID=outFilename, write=True, fields=self._streamFields) else: self._writer = None def _openStream(self, dataUrl, isBlocking, maxTimeout, bookmark, firstRecordIdx): """Open the underlying file stream. This only supports 'file://' prefixed paths. """ filePath = dataUrl[len(FILE_PREF):] if not os.path.isabs(filePath): filePath = os.path.join(os.getcwd(), filePath) self._recordStoreName = filePath self._recordStore = FileRecordStream(streamID=self._recordStoreName, write=False, bookmark=bookmark, firstRecord=firstRecordIdx) def close(self): """ Close the stream """ return self._recordStore.close() def getNextRecord(self): """ Returns combined data from all sources (values only). Returns None on EOF; empty sequence on timeout. """ # Keep reading from the raw input till we get enough for an aggregated # record while True: # Reached EOF due to lastRow constraint? if self._sourceLastRecordIdx is not None and \ self._recordStore.getNextRecordIdx() >= self._sourceLastRecordIdx: preAggValues = None # indicates EOF bookmark = self._recordStore.getBookmark() else: # Get the raw record and bookmark preAggValues = self._recordStore.getNextRecord() bookmark = self._recordStore.getBookmark() if preAggValues == (): # means timeout error occurred if self._eofOnTimeout: preAggValues = None # act as if we got EOF else: return preAggValues # Timeout indicator self._logger.debug('Read source record #%d: %r', self._recordStore.getNextRecordIdx() - 1, preAggValues) # Perform aggregation (fieldValues, aggBookmark) = self._aggregator.next(preAggValues, bookmark) # Update the aggregated record bookmark if we got a real record back if fieldValues is not None: self._aggBookmark = aggBookmark # Reached EOF? if preAggValues is None and fieldValues is None: return None # Return it if we have a record if fieldValues is not None: break # Do we need to re-order the fields in the record? if self._needFieldsFiltering: values = [] srcDict = dict(zip(self._recordStoreFieldNames, fieldValues)) for name in self._streamFieldNames: values.append(srcDict[name]) fieldValues = values # Write to debug output? if self._writer is not None: self._writer.appendRecord(fieldValues) self._recordCount += 1 self._logger.debug( 'Returning aggregated record #%d from getNextRecord(): ' '%r. Bookmark: %r', self._recordCount - 1, fieldValues, self._aggBookmark) return fieldValues def getDataRowCount(self): """Iterates through stream to calculate total records after aggregation. This will alter the bookmark state. """ inputRowCountAfterAggregation = 0 while True: record = self.getNextRecord() if record is None: return inputRowCountAfterAggregation inputRowCountAfterAggregation += 1 if inputRowCountAfterAggregation > 10000: raise RuntimeError('No end of datastream found.') def getLastRecords(self, numRecords): """Saves the record in the underlying storage.""" raise RuntimeError("Not implemented in StreamReader") def getRecordsRange(self, bookmark=None, range=None): """ Returns a range of records, starting from the bookmark. If 'bookmark' is None, then records read from the first available. If 'range' is None, all available records will be returned (caution: this could be a lot of records and require a lot of memory). """ raise RuntimeError("Not implemented in StreamReader") def getNextRecordIdx(self): """Returns the index of the record that will be read next from getNextRecord() """ return self._recordCount def recordsExistAfter(self, bookmark): """Returns True iff there are records left after the bookmark.""" return self._recordStore.recordsExistAfter(bookmark) def getAggregationMonthsAndSeconds(self): """ Returns the aggregation period of the record stream as a dict containing 'months' and 'seconds'. The months is always an integer and seconds is a floating point. Only one is allowed to be non-zero at a time. If there is no aggregation associated with the stream, returns None. Typically, a raw file or hbase stream will NOT have any aggregation info, but subclasses of RecordStreamIFace, like StreamReader, will and will return the aggregation period from this call. This call is used by the getNextRecordDict() method to assign a record number to a record given its timestamp and the aggregation interval Parameters: ------------------------------------------------------------------------ retval: aggregationPeriod (as a dict) or None 'months': number of months in aggregation period 'seconds': number of seconds in aggregation period (as a float) """ return self._aggMonthsAndSeconds def appendRecord(self, record, inputRef=None): """Saves the record in the underlying storage.""" raise RuntimeError("Not implemented in StreamReader") def appendRecords(self, records, inputRef=None, progressCB=None): """Saves multiple records in the underlying storage.""" raise RuntimeError("Not implemented in StreamReader") def removeOldData(self): raise RuntimeError("Not implemented in StreamReader") def seekFromEnd(self, numRecords): """Seeks to numRecords from the end and returns a bookmark to the new position. """ raise RuntimeError("Not implemented in StreamReader") def getFieldNames(self): """ Returns all fields in all inputs (list of plain names). NOTE: currently, only one input is supported """ return [f[0] for f in self._streamFields] def getFields(self): """ Returns a sequence of nupic.data.fieldmeta.FieldMetaInfo name/type/special tuples for each field in the stream. """ return self._streamFields def getBookmark(self): """ Returns a bookmark to the current position """ return self._aggBookmark def getResetFieldIdx(self): """ Index of the 'reset' field. """ for i, field in enumerate(self._streamFields): if field[2] == 'R' or field[2] == 'r': return i return None def getTimestampFieldIdx(self): """ Index of the 'timestamp' field. """ for i, field in enumerate(self._streamFields): if field[2] == 'T' or field[2] == 't': return i return None def getSequenceIdFieldIdx(self): """ Index of the 'sequenceId' field. """ for i, field in enumerate(self._streamFields): if field[2] == 'S' or field[2] == 's': return i return None def getCategoryFieldIdx(self): """ Index of the 'category' field. """ for i, field in enumerate(self._streamFields): if field[2] == 'C' or field[2] == 'c': return i return None def clearStats(self): """ Resets stats collected so far. """ self._recordStore.clearStats() def getStats(self): """ Returns stats (like min and max values of the fields). TODO: This method needs to be enhanced to get the stats on the *aggregated* records. """ # The record store returns a dict of stats, each value in this dict is # a list with one item per field of the record store # { # 'min' : [f1_min, f2_min, f3_min], # 'max' : [f1_max, f2_max, f3_max] # } recordStoreStats = self._recordStore.getStats() # We need to convert each item to represent the fields of the *stream* streamStats = dict() for (key, values) in recordStoreStats.items(): fieldStats = dict(zip(self._recordStoreFieldNames, values)) streamValues = [] for name in self._streamFieldNames: streamValues.append(fieldStats[name]) streamStats[key] = streamValues return streamStats def getError(self): """ Returns errors saved in the stream. """ return self._recordStore.getError() def setError(self, error): """ Saves specified error in the stream. """ self._recordStore.setError(error) def isCompleted(self): """ Returns True if all records have been read. """ return self._recordStore.isCompleted() def setCompleted(self, completed=True): """ Marks the stream completed (True or False) """ # CSV file is always considered completed, nothing to do self._recordStore.setCompleted(completed) def setTimeout(self, timeout): """ Set the read timeout """ self._recordStore.setTimeout(timeout) def flush(self): """ Flush the file to disk """ raise RuntimeError("Not implemented in StreamReader")
class StreamReader(RecordStreamIface): """ Implements a stream reader. This is a high level class that owns one or more underlying implementations of a RecordStreamIFace. Each RecordStreamIFace implements the raw reading of records from the record store (which could be a file, hbase table or something else). In the future, we will support joining of two or more RecordStreamIFace's (which is why the streamDef accepts a list of 'stream' elements), but for now only 1 source is supported. The class also implements aggregation of the (in the future) joined records from the sources. This module parses the stream definition (as defined in /nupic/frameworks/opf/jsonschema/stream_def.json), creates the RecordStreamIFace for each source ('stream's element) defined in the stream def, performs aggregation, and returns each record in the correct format according to the desired column names specified in the streamDef. This class implements the RecordStreamIFace interface and thus can be used in place of a raw record stream. This is an example streamDef: { 'version': 1 'info': 'test_hotgym', 'streams': [ {'columns': [u'*'], 'info': u'hotGym.csv', 'last_record': 4000, 'source': u'file://extra/hotgym/hotgym.csv'}. ], 'timeField': 'timestamp', 'aggregation': { 'hours': 1, 'fields': [ ('timestamp', 'first'), ('gym', 'first'), ('consumption', 'sum') ], } } """ ############################################################################ def __init__(self, streamDef, bookmark=None, saveOutput=False, isBlocking=True, maxTimeout=0, eofOnTimeout=False): """ Base class constructor, performs common initialization Parameters: ---------------------------------------------------------------- streamDef: The stream definition, potentially containing multiple sources (not supported yet). See /nupic/frameworks/opf/jsonschema/stream_def.json for the format of this dict bookmark: Bookmark to start reading from. This overrides the first_record field of the streamDef if provided. saveOutput: If true, save the output to a csv file in a temp directory. The path to the generated file can be found in the log output. isBlocking: should read operation block *forever* if the next row of data is not available, but the stream is not marked as 'completed' yet? maxTimeout: if isBlocking is False, max seconds to wait for more data before timing out; ignored when isBlocking is True. eofOnTimeout: If True and we get a read timeout (isBlocking must be False to get read timeouts), assume we've reached the end of the input and produce the last aggregated record, if one can be completed. """ # Call superclass constructor super(StreamReader, self).__init__() loggerPrefix = 'com.numenta.nupic.data.StreamReader' self._logger = logging.getLogger(loggerPrefix) jsonhelpers.validate(streamDef, schemaPath=resource_filename( jsonschema.__name__, "stream_def.json")) assert len(streamDef['streams']) == 1, "Only 1 source stream is supported" # Save constructor args sourceDict = streamDef['streams'][0] self._recordCount = 0 self._eofOnTimeout = eofOnTimeout self._logger.debug('Reading stream with the def: %s', sourceDict) # Dictionary to store record statistics (min and max of scalars for now) self._stats = None # --------------------------------------------------------------------- # Get the stream definition params # Limiting window of the stream. It would not return any records until # 'first_record' ID is read (or very first with the ID above that). The # stream will return EOS once it reads record with ID 'last_record' or # above (NOTE: the name 'lastRecord' is misleading because it is NOT # inclusive). firstRecordIdx = sourceDict.get('first_record', None) self._sourceLastRecordIdx = sourceDict.get('last_record', None) # If a bookmark was given, then override first_record from the stream # definition. if bookmark is not None: firstRecordIdx = None # Column names must be provided in the streamdef json # Special case is ['*'], meaning all available names from the record stream self._streamFieldNames = sourceDict.get('columns', None) if self._streamFieldNames != None and self._streamFieldNames[0] == '*': self._needFieldsFiltering = False else: self._needFieldsFiltering = True # Types must be specified in streamdef json, or in case of the # file_recod_stream types could be implicit from the file streamFieldTypes = sourceDict.get('types', None) self._logger.debug('Types from the def: %s', streamFieldTypes) # Validate that all types are valid if streamFieldTypes != None: for dataType in streamFieldTypes: assert(dataType in TYPES) # Reset, sequence and time fields might be provided by streamdef json streamResetFieldName = streamDef.get('resetField', None) streamTimeFieldName = streamDef.get('timeField', None) streamSequenceFieldName = streamDef.get('sequenceIdField', None) self._logger.debug('r, t, s fields: %s, %s, %s', streamResetFieldName, streamTimeFieldName, streamSequenceFieldName) # ======================================================================= # Open up the underlying record store dataUrl = sourceDict.get('source', None) assert(dataUrl is not None) self._openStream(dataUrl, isBlocking, maxTimeout, bookmark, firstRecordIdx) assert(self._recordStore is not None) # ======================================================================= # Prepare the data structures we need for returning just the fields # the caller wants from each record self._recordStoreFields = self._recordStore.getFields() self._recordStoreFieldNames = self._recordStore.getFieldNames() if not self._needFieldsFiltering: self._streamFieldNames = self._recordStoreFieldNames # Build up the field definitions for each field. This is a list of tuples # of (name, type, special) self._streamFields = [] for dstIdx, name in enumerate(self._streamFieldNames): if name not in self._recordStoreFieldNames: raise RuntimeError("The column '%s' from the stream definition " "is not present in the underlying stream which has the following " "columns: %s" % (name, self._recordStoreFieldNames)) fieldIdx = self._recordStoreFieldNames.index(name) fieldType = self._recordStoreFields[fieldIdx][1] fieldSpecial = self._recordStoreFields[fieldIdx][2] # If the types or specials were defined in the stream definition, # then override what was found in the record store if streamFieldTypes is not None: fieldType = streamFieldTypes[dstIdx] if streamResetFieldName is not None and streamResetFieldName == name: fieldSpecial = 'R' if streamTimeFieldName is not None and streamTimeFieldName == name: fieldSpecial = 'T' if streamSequenceFieldName is not None and streamSequenceFieldName == name: fieldSpecial = 'S' self._streamFields.append(FieldMetaInfo(name, fieldType, fieldSpecial)) # ======================================================================== # Create the aggregator which will handle aggregation of records before # returning them. self._aggregator = Aggregator( aggregationInfo=streamDef.get('aggregation', None), inputFields=self._recordStoreFields, timeFieldName=streamDef.get('timeField', None), sequenceIdFieldName=streamDef.get('sequenceIdField', None), resetFieldName=streamDef.get('resetField', None)) # We rely on the aggregator to tell us the bookmark of the last raw input # that contributed to the aggregated record self._aggBookmark = None # Compute the aggregation period in terms of months and seconds if 'aggregation' in streamDef: self._aggMonthsAndSeconds = nupic.support.aggregationToMonthsSeconds( streamDef.get('aggregation')) else: self._aggMonthsAndSeconds = None # ======================================================================== # Are we saving the generated output to a csv? if saveOutput: tmpDir = tempfile.mkdtemp() outFilename = os.path.join(tmpDir, "generated_output.csv") self._logger.info("StreamReader: Saving generated records to: '%s'" % outFilename) self._writer = FileRecordStream(streamID=outFilename, write=True, fields=self._streamFields) else: self._writer = None ############################################################################## def _openStream(self, dataUrl, isBlocking, maxTimeout, bookmark, firstRecordIdx): """Open the underlying file stream. This only supports 'file://' prefixed paths. """ self._recordStoreName = findDataset(dataUrl[len(FILE_PREF):]) self._recordStore = FileRecordStream(streamID=self._recordStoreName, write=False, bookmark=bookmark, firstRecord=firstRecordIdx) ############################################################################## def close(self): """ Close the stream """ return self._recordStore.close() ############################################################################ def getNextRecord(self): """ Returns combined data from all sources (values only). Returns None on EOF; empty sequence on timeout. """ # Keep reading from the raw input till we get enough for an aggregated # record while True: # Reached EOF due to lastRow constraint? if self._sourceLastRecordIdx is not None and \ self._recordStore.getNextRecordIdx() >= self._sourceLastRecordIdx: preAggValues = None # indicates EOF bookmark = self._recordStore.getBookmark() else: # Get the raw record and bookmark preAggValues = self._recordStore.getNextRecord() bookmark = self._recordStore.getBookmark() if preAggValues == (): # means timeout error occurred if self._eofOnTimeout: preAggValues = None # act as if we got EOF else: return preAggValues # Timeout indicator self._logger.debug('Read source record #%d: %r', self._recordStore.getNextRecordIdx()-1, preAggValues) # Perform aggregation (fieldValues, aggBookmark) = self._aggregator.next(preAggValues, bookmark) # Update the aggregated record bookmark if we got a real record back if fieldValues is not None: self._aggBookmark = aggBookmark # Reached EOF? if preAggValues is None and fieldValues is None: return None # Return it if we have a record if fieldValues is not None: break # Do we need to re-order the fields in the record? if self._needFieldsFiltering: values = [] srcDict = dict(zip(self._recordStoreFieldNames, fieldValues)) for name in self._streamFieldNames: values.append(srcDict[name]) fieldValues = values # Write to debug output? if self._writer is not None: self._writer.appendRecord(fieldValues) self._recordCount += 1 self._logger.debug('Returning aggregated record #%d from getNextRecord(): ' '%r. Bookmark: %r', self._recordCount-1, fieldValues, self._aggBookmark) return fieldValues def getDataRowCount(self): """Iterates through stream to calculate total records after aggregation. This will alter the bookmark state. """ inputRowCountAfterAggregation = 0 while True: record = self.getNextRecord() if record is None: return inputRowCountAfterAggregation inputRowCountAfterAggregation += 1 if inputRowCountAfterAggregation > 10000: raise RuntimeError('No end of datastream found.') ############################################################################ def getLastRecords(self, numRecords): """Saves the record in the underlying storage.""" raise RuntimeError("Not implemented in StreamReader") ############################################################################# def getRecordsRange(self, bookmark=None, range=None): """ Returns a range of records, starting from the bookmark. If 'bookmark' is None, then records read from the first available. If 'range' is None, all available records will be returned (caution: this could be a lot of records and require a lot of memory). """ raise RuntimeError("Not implemented in StreamReader") ############################################################################# def getNextRecordIdx(self): """Returns the index of the record that will be read next from getNextRecord() """ return self._recordCount ############################################################################# def recordsExistAfter(self, bookmark): """Returns True iff there are records left after the bookmark.""" return self._recordStore.recordsExistAfter(bookmark) ############################################################################## def getAggregationMonthsAndSeconds(self): """ Returns the aggregation period of the record stream as a dict containing 'months' and 'seconds'. The months is always an integer and seconds is a floating point. Only one is allowed to be non-zero at a time. If there is no aggregation associated with the stream, returns None. Typically, a raw file or hbase stream will NOT have any aggregation info, but subclasses of RecordStreamIFace, like StreamReader, will and will return the aggregation period from this call. This call is used by the getNextRecordDict() method to assign a record number to a record given its timestamp and the aggregation interval Parameters: ------------------------------------------------------------------------ retval: aggregationPeriod (as a dict) or None 'months': number of months in aggregation period 'seconds': number of seconds in aggregation period (as a float) """ return self._aggMonthsAndSeconds ############################################################################ def appendRecord(self, record, inputRef=None): """Saves the record in the underlying storage.""" raise RuntimeError("Not implemented in StreamReader") ############################################################################ def appendRecords(self, records, inputRef=None, progressCB=None): """Saves multiple records in the underlying storage.""" raise RuntimeError("Not implemented in StreamReader") ############################################################################# def removeOldData(self): raise RuntimeError("Not implemented in StreamReader") ############################################################################# def seekFromEnd(self, numRecords): """Seeks to numRecords from the end and returns a bookmark to the new position. """ raise RuntimeError("Not implemented in StreamReader") ############################################################################ def getFieldNames(self): """ Returns all fields in all inputs (list of plain names). NOTE: currently, only one input is supported """ return [f[0] for f in self._streamFields] ############################################################################ def getFields(self): """ Returns a sequence of nupic.data.fieldmeta.FieldMetaInfo name/type/special tuples for each field in the stream. """ return self._streamFields ############################################################################ def getBookmark(self): """ Returns a bookmark to the current position """ return self._aggBookmark ############################################################################# def getResetFieldIdx(self): """ Index of the 'reset' field. """ for i, field in enumerate(self._streamFields): if field[2] == 'R' or field[2] == 'r': return i return None ############################################################################# def getTimestampFieldIdx(self): """ Index of the 'timestamp' field. """ for i, field in enumerate(self._streamFields): if field[2] == 'T' or field[2] == 't': return i return None ############################################################################# def getSequenceIdFieldIdx(self): """ Index of the 'sequenceId' field. """ for i, field in enumerate(self._streamFields): if field[2] == 'S' or field[2] == 's': return i return None ############################################################################# def getCategoryFieldIdx(self): """ Index of the 'category' field. """ for i, field in enumerate(self._streamFields): if field[2] == 'C' or field[2] == 'c': return i return None ############################################################################# def clearStats(self): """ Resets stats collected so far. """ self._recordStore.clearStats() ############################################################################# def getStats(self): """ Returns stats (like min and max values of the fields). TODO: This method needs to be enhanced to get the stats on the *aggregated* records. """ # The record store returns a dict of stats, each value in this dict is # a list with one item per field of the record store # { # 'min' : [f1_min, f2_min, f3_min], # 'max' : [f1_max, f2_max, f3_max] # } recordStoreStats = self._recordStore.getStats() # We need to convert each item to represent the fields of the *stream* streamStats = dict() for (key, values) in recordStoreStats.items(): fieldStats = dict(zip(self._recordStoreFieldNames, values)) streamValues = [] for name in self._streamFieldNames: streamValues.append(fieldStats[name]) streamStats[key] = streamValues return streamStats ############################################################################# def getError(self): """ Returns errors saved in the stream. """ return self._recordStore.getError() ############################################################################# def setError(self, error): """ Saves specified error in the stream. """ self._recordStore.setError(error) ############################################################################# def isCompleted(self): """ Returns True if all records have been read. """ return self._recordStore.isCompleted() ############################################################################# def setCompleted(self, completed=True): """ Marks the stream completed (True or False) """ # CSV file is always considered completed, nothing to do self._recordStore.setCompleted(completed) ############################################################################# def setTimeout(self, timeout): """ Set the read timeout """ self._recordStore.setTimeout(timeout) ############################################################################# def flush(self): """ Flush the file to disk """ raise RuntimeError("Not implemented in StreamReader")
def testMissingValues(self): print "Beginning Missing Data test..." filename = _getTempFileName() # Some values missing of each type # read dataset from disk, retrieve values # string should return empty string, numeric types sentinelValue print "Creating tempfile:", filename # write dataset to disk with float, int, and string fields fields = [("timestamp", "datetime", "T"), ("name", "string", ""), ("integer", "int", ""), ("real", "float", "")] s = FileRecordStream(streamID=filename, write=True, fields=fields) # Records records = ( [datetime(day=1, month=3, year=2010), "rec_1", 5, 6.5], [datetime(day=2, month=3, year=2010), "", 8, 7.5], [datetime(day=3, month=3, year=2010), "rec_3", "", 8.5], [datetime(day=4, month=3, year=2010), "rec_4", 12, ""], [datetime(day=5, month=3, year=2010), "rec_5", -87657496599, 6.5], [datetime(day=6, month=3, year=2010), "rec_6", 12, -87657496599], [datetime(day=6, month=3, year=2010), str(-87657496599), 12, 6.5], ) for r in records: s.appendRecord(list(r)) s.close() # Read the standard file s = FileRecordStream(streamID=filename, write=False) fieldsRead = s.getFields() self.assertEqual(fields, fieldsRead) recordsRead = [] while True: r = s.getNextRecord() if r is None: break print "Reading record ..." print r recordsRead.append(r) # sort the records by date, so we know for sure which is which sorted(recordsRead, key=lambda rec: rec[0]) # empty string self.assertEqual(SENTINEL_VALUE_FOR_MISSING_DATA, recordsRead[1][1]) # missing int self.assertEqual(SENTINEL_VALUE_FOR_MISSING_DATA, recordsRead[2][2]) # missing float self.assertEqual(SENTINEL_VALUE_FOR_MISSING_DATA, recordsRead[3][3]) # sentinel value in input handled correctly for int field self.assertNotEqual(SENTINEL_VALUE_FOR_MISSING_DATA, recordsRead[4][2]) # sentinel value in input handled correctly for float field self.assertNotEqual(SENTINEL_VALUE_FOR_MISSING_DATA, recordsRead[5][3]) # sentinel value in input handled correctly for string field # this should leave the string as-is, since a missing string # is encoded not with a sentinel value but with an empty string self.assertNotEqual(SENTINEL_VALUE_FOR_MISSING_DATA, recordsRead[6][1])