forked from rhyolight/nupic.cerebro
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cerebro_model.py
473 lines (358 loc) · 14.5 KB
/
cerebro_model.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
# The MIT License (MIT)
#
# Copyright (c) 2013 Numenta, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import nupic.frameworks.opf.opfhelpers as opfhelpers
import tempfile
import os.path
import json
import pymongo
import re
import pprint
from collections import deque
from anomaly_runner import AnomalyRunner
from experiment_runner import ExperimentRunner
from Dataset import (FileDataset,
ProceduralDataset,
SamplingDict)
from Queue import Queue
from nupic.frameworks.opf.exp_generator.ExpGenerator import (expGenerator)
from nupic.frameworks.opf.opfutils import (InferenceType,
InferenceElement)
from experiment_db import ExperimentDB
class CerebroModel:
# Dummy Streamdef used for procedural datasets
_DUMMY_STREAMDEF = dict(
version = 1,
info = "cerebro_dummy",
streams = [
dict(source="file://joined_mosman_2011.csv",
info="hotGym.csv",
columns=["*"],
),
],
)
_ptr = None
@staticmethod
def get():
if not CerebroModel._ptr:
CerebroModel._ptr = CerebroModel()
return CerebroModel._ptr
def __init__(self):
# All the Dataset objects for this session
self.datasets = []
self.models = []
self.currentDataset = None
self.currentModel = None
self.experimentRunner = None
self.descriptionText = ""
self.subDescriptionText = ""
self.control = None
# Name of model - used for mongodb name
self.default_name = "_lastModelRun"
self.name = self.default_name
# Data for current model
self.__currentModelData = []
# MongDB stuff
self.dbConnection = pymongo.Connection()
self.db = self.dbConnection["CerebroDB"]
self.db.drop_collection("modelOutput")
self.collection = self.db.modelOutput
def loadDescriptionFile(self, descriptionFile, subDescriptionFile=None):
"""
Loads a description.py and creates a new experiment
Parameters:
-----------------------------------------------------------------------
descriptionFile: A filename or open file object corresponding to
the description.py
subDescriptionFile: A file corresponding to a sub description file
"""
# TODO: Hack for now is to write open experiment file to a temp directory
#if type(descriptionFile) is not str:
tempDir = tempfile.mkdtemp()
expPath = os.path.join(tempDir, "description.py")
with open(expPath, "w") as tempDescription:
tempDescription.write(descriptionFile)
self.descriptionText = descriptionFile
self.subDescriptionText = subDescriptionFile
descriptionFile = expPath
if subDescriptionFile:
# Make sure that there is relative path to the base
pattern = r'(.+importBaseDescription)\((.+),(.*)\)'
repl = r"\g<1>('../description.py', \g<3>)"
subDescriptionFile = re.sub(pattern, repl, subDescriptionFile)
os.makedirs(os.path.join(tempDir, "model_0"))
expPath = os.path.join(tempDir, "model_0", "description.py")
with open(expPath, "w") as f:
f.write(subDescriptionFile)
descriptionFile = expPath
# -----------------------------------------------------------------------
# Get the model parameters
#
experimentDir = os.path.dirname(descriptionFile)
expIface = self.__getCurrentModelFromDir(experimentDir)
# -----------------------------------------------------------------------
# Get the data path and create the Dataset object
#
control = expIface.getModelControl()
self.control = control
if control['environment'] == 'opfExperiment':
experimentTasks = expIface.getModelControl()['tasks']
task = experimentTasks[0]
datasetURI = task['dataset']['streams'][0]['source']
elif control['environment'] == 'grok':
datasetURI = control['dataset']['streams'][0]['source']
datasetPath = datasetURI[len("file://"):]
dataset = FileDataset(control['dataset'])
self.datasets.append(dataset)
self.currentDataset = len(self.datasets) - 1
self.experimentRunner = None
return True
def createProceduralDataset(self, fnText, iterations):
""" Create a dataset from the text of a function"""
fnLines = fnText.split('\n')
filteredText = ['def foo(t):',
'\tfields=SamplingDict()'
]
# Filter out lines with return statements
for line in fnLines:
if line.find('return') >= 0:
continue
filteredText.append('\t'+line)
filteredText.append('\treturn fields')
fnText = '\n'.join(filteredText)
code = compile(fnText, "<string>", "exec")
# -----------------------------------------------------------------------
# Import global modules available to the function
import random
import numpy
import string
import math
history = deque([], 20)
globs={'random': random,
'numpy':numpy,
'string':string,
"math": math,
'SamplingDict':SamplingDict,
'history':history
}
locs = {}
eval(code, globs, locs)
foo = locs['foo']
dataset = ProceduralDataset(foo, iterations, history)
self.datasets.append(dataset)
self.currentDataset = len(self.datasets) - 1
datasetInfo = self.datasets[self.currentDataset].getDatasetFieldMetaData()
includedFields = []
for fieldInfo in datasetInfo:
includedFields.append({'fieldName': fieldInfo.name,
'fieldType':fieldInfo.type})
expDesc = json.dumps(dict( environment = "grok",
inferenceType=InferenceType.TemporalMultiStep,
inferenceArgs={"predictedField":datasetInfo[0].name,
"predictionSteps":[1]},
includedFields=includedFields,
streamDef=self._DUMMY_STREAMDEF,
))
tempDir = tempfile.mkdtemp()
expGenerator(["--description=%s"%expDesc, "--outDir=%s"%tempDir, "--version=v2"])
descFile = os.path.join(tempDir, "description.py")
f = open(descFile)
self.descriptionText = f.read()
f.close()
self.__getCurrentModelFromDir(tempDir)
return True
def __getCurrentModelFromDir(self, expDir):
""" Loads a description.py file from the specified directory, and sets it to
be the current model """
descriptionPyModule = \
opfhelpers.loadExperimentDescriptionScriptFromDir(expDir)
expIface = \
opfhelpers.getExperimentDescriptionInterfaceFromModule(descriptionPyModule)
modelDescription = expIface.getModelDescription()
modelDescription['predictedField'] = None
modelDescription['modelParams']['clParams']['implementation'] = 'py'
# Add model to global list
self.models.append(modelDescription)
self.currentModel = len(self.models) - 1
self.control = expIface.getModelControl()
modelDescription['predictedField'] = self.control['inferenceArgs']['predictedField']
return expIface
def getDescriptionText(self):
""" Return the text for a BASE description file """
return self.descriptionText
def getDatasetText(self):
""" Returns the text of the dataset, in csv format """
dataset = self.datasets[self.currentDataset]
metaData = dataset.getDatasetFieldMetaData()
names = [f.name for f in metaData]
types = [f.type for f in metaData]
specials = [f.special for f in metaData]
lines = [", ".join(names), ", ".join(types), ", ".join(specials)]
while True:
try:
record = dataset.getNextRecord()
values = [str(record[name]) for name in names]
lines.append(", ".join(values))
except StopIteration:
break
return "\n".join(lines)
def getCurrentModelParams(self):
"""Gets the parameters for the current models
Returns:
"""
return self.models[self.currentModel]
def setPredictedField(self, fieldname):
"Sets the predicted field for the CURRENT model."
# TODO: validate fieldname
currentModel = self.models[self.currentModel]
currentModel['predictedField'] = fieldname
if self.control['inferenceArgs'] is None:
self.control['inferenceArgs'] = {}
self.control['inferenceArgs']['predictedField'] = fieldname
pprint.pprint(self.models[self.currentModel])
def setModelParams(self, newParams):
""""
Updates the current model params dictionary
"""
self.models[self.currentModel]['modelParams'] = newParams
def setClassifierThreshold(self, threshold):
results = dict()
if self.experimentRunner is not None:
results['labels'] = self.experimentRunner.setClassifierThreshold(threshold)
pprint.pprint(results)
return results
def getExperimentInfo(self, modelDescription):
"""Get details about the current experiment to return to the client"""
expInfo = {"name" : self.name,
"started" : True,
"fieldInfo" : {}}
fieldRanges = self.experimentRunner.getFieldRanges()
fieldInfo = {}
for name, fRange in fieldRanges.iteritems():
fieldInfo[name] = {}
fieldInfo[name]['size'] = fRange[1] - fRange[0]
expInfo['fieldInfo'] = fieldInfo
return expInfo
def runCurrentExperiment(self, expType="Standard", isLoad=False):
"""
Creates an experiment runner for the current model and starts running the
model in a seperate thread
"""
if self.experimentRunner:
self.stopCurrentExperiment()
self.datasets[self.currentDataset].rewind()
if isLoad:
modelInfo = json.loads(ExperimentDB.get(self.name)['metadata'])
modelDescriptionText = modelInfo['modelDescriptionText']
subDescriptionText = modelInfo['subDescriptionText']
self.loadDescriptionFile(modelDescriptionText, subDescriptionText)
else:
data = dict(
modelDescriptionText=self.descriptionText,
subDescriptionText=self.subDescriptionText
)
ExperimentDB.add(self.name, data)
self.__currentModelData = []
if expType == "Standard":
self.experimentRunner = ExperimentRunner(
name = self.name,
modelDescription=self.models[self.currentModel],
control= self.control,
dataset=self.datasets[self.currentDataset])
elif expType == "Anomaly":
self.experimentRunner = AnomalyRunner(
name = self.name,
modelDescription=self.models[self.currentModel],
control= self.control,
dataset=self.datasets[self.currentDataset])
if isLoad:
self.experimentRunner.load()
else:
self.experimentRunner.run()
return self.getExperimentInfo(self.models[self.currentModel])
def stopCurrentExperiment(self):
"""Stops the current experiment """
self.experimentRunner.stop()
def getLatestPredictions(self):
""" Gets the latest set of predictions from the ExperimentRunner. Blocks
if there are no new results
"""
newData = []
while True:
if not self.experimentRunner:
return None
newData = self.experimentRunner.getNewData()
if newData or self.experimentRunner.isFinished():
break
data = dict(
results = dict(
actual = [],
),
finished = self.experimentRunner.isFinished()
)
if newData is None:
return data
results = data['results']
# -----------------------------------------------------------------------
# Figure out which inference elements are being generated
inferenceElements = set(json.loads(newData[0]['inferences']).keys())
if InferenceElement.prediction in inferenceElements \
or InferenceElement.multiStepBestPredictions in inferenceElements:
results['prediction'] = []
if InferenceElement.anomalyScore in inferenceElements:
results['anomaly'] = []
results['anomalyLabel'] = []
# -----------------------------------------------------------------------
# Fill return dict with data
predictedField = self.models[self.currentModel]['predictedField']
for elem in newData:
predictedFieldIndex = self.experimentRunner.getFieldNames().index(predictedField)
inferences = json.loads(elem["inferences"])
results['actual'].append(elem["actual"])
if 'prediction' in results:
if InferenceElement.multiStepBestPredictions in inferenceElements:
inference = inferences[InferenceElement.multiStepBestPredictions]
step = min(inference.iterkeys())
prediction =inference[step]
else:
prediction = inferences[InferenceElement.prediction][predictedFieldIndex]
if prediction is None:
prediction = 0.0
results['prediction'].append(prediction)
if 'anomaly' in results:
anomaly = inferences[InferenceElement.anomalyScore]
results['anomaly'].append(anomaly)
if InferenceElement.anomalyLabel in inferences:
anomalyLabel = inferences[InferenceElement.anomalyLabel]
results['anomalyLabel'].append(anomalyLabel)
# print "Actual", len(results["actual"]), "Prediction", len(results["prediction"])
return data
def getDataAtTime(self, dataInput):
""" Gets all of the model data for the current timestep.
Returns:
...
"""
output = self.experimentRunner.getDataAtTime(dataInput)
output['auxText'] = self.experimentRunner.auxText(dataInput['timestep'], output)
return output
# Managing Experiments
def setExperimentName(self, name):
return self.experimentRunner.setName(name)