forked from ymirsky/Kitsune-py
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AfterImage.py
442 lines (371 loc) · 16.1 KB
/
AfterImage.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
import math
import numpy as np
class incStat:
def __init__(self, Lambda, ID, init_time=0, isTypeDiff=False): # timestamp is creation time
self.ID = ID
self.CF1 = 0 # linear sum
self.CF2 = 0 # sum of squares
self.w = 1e-20 # weight
self.isTypeDiff = isTypeDiff
self.Lambda = Lambda # Decay Factor
self.lastTimestamp = init_time
self.cur_mean = np.nan
self.cur_var = np.nan
self.cur_std = np.nan
self.covs = [] # a list of incStat_covs (references) with relate to this incStat
def insert(self, v, t=0): # v is a scalar, t is v's arrival the timestamp
if self.isTypeDiff:
dif = t - self.lastTimestamp
if dif > 0:
v = dif
else:
v = 0
self.processDecay(t)
# update with v
self.CF1 += v
self.CF2 += math.pow(v, 2)
self.w += 1
self.cur_mean = np.nan # force recalculation if called
self.cur_var = np.nan
self.cur_std = np.nan
# update covs (if any)
for cov in self.covs:
cov.update_cov(self.ID, v, t)
def processDecay(self, timestamp):
factor=1
# check for decay
timeDiff = timestamp - self.lastTimestamp
if timeDiff > 0:
factor = math.pow(2, (-self.Lambda * timeDiff))
self.CF1 = self.CF1 * factor
self.CF2 = self.CF2 * factor
self.w = self.w * factor
self.lastTimestamp = timestamp
return factor
def weight(self):
return self.w
def mean(self):
if math.isnan(self.cur_mean): # calculate it only once when necessary
self.cur_mean = self.CF1 / self.w
return self.cur_mean
def var(self):
if math.isnan(self.cur_var): # calculate it only once when necessary
self.cur_var = abs(self.CF2 / self.w - math.pow(self.mean(), 2))
return self.cur_var
def std(self):
if math.isnan(self.cur_std): # calculate it only once when necessary
self.cur_std = math.sqrt(self.var())
return self.cur_std
def cov(self,ID2):
for cov in self.covs:
if cov.incStats[0].ID == ID2 or cov.incStats[1].ID == ID2:
return cov.cov()
return [np.nan]
def pcc(self,ID2):
for cov in self.covs:
if cov.incStats[0].ID == ID2 or cov.incStats[1].ID == ID2:
return cov.pcc()
return [np.nan]
def cov_pcc(self,ID2):
for cov in self.covs:
if cov.incStats[0].ID == ID2 or cov.incStats[1].ID == ID2:
return cov.get_stats1()
return [np.nan]*2
def radius(self, other_incStats): # the radius of a set of incStats
A = self.var()
for incS in other_incStats:
A += incS.var()
return math.sqrt(A)
def magnitude(self, other_incStats): # the magnitude of a set of incStats
A = math.pow(self.mean(), 2)
for incS in other_incStats:
A += math.pow(incS.mean(), 2)
return math.sqrt(A)
#calculates and pulls all stats on this stream
def allstats_1D(self):
self.cur_mean = self.CF1 / self.w
self.cur_var = abs(self.CF2 / self.w - math.pow(self.cur_mean, 2))
return [self.w, self.cur_mean, self.cur_var]
#calculates and pulls all stats on this stream, and stats shared with the indicated stream
def allstats_2D(self, ID2):
stats1D = self.allstats_1D()
# Find cov component
stats2D = [np.nan] * 4
for cov in self.covs:
if cov.incStats[0].ID == ID2 or cov.incStats[1].ID == ID2:
stats2D = cov.get_stats2()
break
return stats1D + stats2D
def getHeaders_1D(self, suffix=True):
if self.ID is None:
s0=""
else:
s0 = "_0"
if suffix:
s0 = "_"+self.ID
headers = ["weight"+s0, "mean"+s0, "std"+s0]
return headers
def getHeaders_2D(self, ID2, suffix=True):
hdrs1D = self.getHeaders_1D(suffix)
if self.ID is None:
s0=""
s1=""
else:
s0 = "_0"
s1 = "_1"
if suffix:
s0 = "_"+self.ID
s1 = "_" + ID2
hdrs2D = ["radius_" + s0 + "_" + s1, "magnitude_" + s0 + "_" + s1, "covariance_" + s0 + "_" + s1,
"pcc_" + s0 + "_" + s1]
return hdrs1D+hdrs2D
#like incStat, but maintains stats between two streams
class incStat_cov:
def __init__(self, incS1, incS2, init_time = 0):
# store references tot he streams' incStats
self.incStats = [incS1,incS2]
self.lastRes = [0,0]
# init extrapolators
#self.EXs = [extrapolator(),extrapolator()]
# init sum product residuals
self.CF3 = 0 # sum of residule products (A-uA)(B-uB)
self.w3 = 1e-20
self.lastTimestamp_cf3 = init_time
#other_incS_decay is the decay factor of the other incstat
# ID: the stream ID which produced (v,t)
def update_cov(self, ID, v, t): # it is assumes that incStat "ID" has ALREADY been updated with (t,v) [this si performed automatically in method incStat.insert()]
# find incStat
if ID == self.incStats[0].ID:
inc = 0
elif ID == self.incStats[1].ID:
inc = 1
else:
print("update_cov ID error")
return ## error
# Decay other incStat
self.incStats[not(inc)].processDecay(t)
# Decay residules
self.processDecay(t,inc)
# Update extrapolator for current stream
#self.EXs[inc].insert(t,v)
# Extrapolate other stream
#v_other = self.EXs[not(inc)].predict(t)
# Compute and update residule
res = (v - self.incStats[inc].mean())
resid = (v - self.incStats[inc].mean()) * self.lastRes[not(inc)]
self.CF3 += resid
self.w3 += 1
self.lastRes[inc] = res
def processDecay(self,t,micro_inc_indx):
factor = 1
# check for decay cf3
timeDiffs_cf3 = t - self.lastTimestamp_cf3
if timeDiffs_cf3 > 0:
factor = math.pow(2, (-(self.incStats[micro_inc_indx].Lambda) * timeDiffs_cf3))
self.CF3 *= factor
self.w3 *= factor
self.lastTimestamp_cf3 = t
self.lastRes[micro_inc_indx] *= factor
return factor
#todo: add W3 for cf3
#covariance approximation
def cov(self):
return self.CF3 / self.w3
# Pearson corl. coef
def pcc(self):
ss = self.incStats[0].std() * self.incStats[1].std()
if ss != 0:
return self.cov() / ss
else:
return 0
# calculates and pulls all correlative stats
def get_stats1(self):
return [self.cov(), self.pcc()]
# calculates and pulls all correlative stats AND 2D stats from both streams (incStat)
def get_stats2(self):
return [self.incStats[0].radius([self.incStats[1]]),self.incStats[0].magnitude([self.incStats[1]]),self.cov(), self.pcc()]
# calculates and pulls all correlative stats AND 2D stats AND the regular stats from both streams (incStat)
def get_stats3(self):
return [self.incStats[0].w,self.incStats[0].mean(),self.incStats[0].std(),self.incStats[1].w,self.incStats[1].mean(),self.incStats[1].std(),self.cov(), self.pcc()]
# calculates and pulls all correlative stats AND the regular stats from both incStats AND 2D stats
def get_stats4(self):
return [self.incStats[0].w,self.incStats[0].mean(),self.incStats[0].std(),self.incStats[1].w,self.incStats[1].mean(),self.incStats[1].std(), self.incStats[0].radius([self.incStats[1]]),self.incStats[0].magnitude([self.incStats[1]]),self.cov(), self.pcc()]
def getHeaders(self,ver,suffix=True): #ver = {1,2,3,4}
headers = []
s0 = "0"
s1 = "1"
if suffix:
s0 = self.incStats[0].ID
s1 = self.incStats[1].ID
if ver == 1:
headers = ["covariance_"+s0+"_"+s1, "pcc_"+s0+"_"+s1]
if ver == 2:
headers = ["radius_"+s0+"_"+s1, "magnitude_"+s0+"_"+s1, "covariance_"+s0+"_"+s1, "pcc_"+s0+"_"+s1]
if ver == 3:
headers = ["weight_"+s0, "mean_"+s0, "std_"+s0,"weight_"+s1, "mean_"+s1, "std_"+s1, "covariance_"+s0+"_"+s1, "pcc_"+s0+"_"+s1]
if ver == 4:
headers = ["weight_" + s0, "mean_" + s0, "std_" + s0, "covariance_" + s0 + "_" + s1, "pcc_" + s0 + "_" + s1]
if ver == 5:
headers = ["weight_"+s0, "mean_"+s0, "std_"+s0,"weight_"+s1, "mean_"+s1, "std_"+s1, "radius_"+s0+"_"+s1, "magnitude_"+s0+"_"+s1, "covariance_"+s0+"_"+s1, "pcc_"+s0+"_"+s1]
return headers
class incStatDB:
# default_lambda: use this as the lambda for all streams. If not specified, then you must supply a Lambda with every query.
def __init__(self,limit=np.Inf,default_lambda=np.nan):
self.HT = dict()
self.limit = limit
self.df_lambda = default_lambda
def get_lambda(self,Lambda):
if not np.isnan(self.df_lambda):
Lambda = self.df_lambda
return Lambda
# Registers a new stream. init_time: init lastTimestamp of the incStat
def register(self,ID,Lambda=1,init_time=0,isTypeDiff=False):
#Default Lambda?
Lambda = self.get_lambda(Lambda)
#Retrieve incStat
key = ID+"_"+str(Lambda)
incS = self.HT.get(key)
if incS is None: #does not already exist
if len(self.HT) + 1 > self.limit:
raise LookupError(
'Adding Entry:\n' + key + '\nwould exceed incStatHT 1D limit of ' + str(
self.limit) + '.\nObservation Rejected.')
incS = incStat(Lambda, ID, init_time, isTypeDiff)
self.HT[key] = incS #add new entry
return incS
# Registers covariance tracking for two streams, registers missing streams
def register_cov(self,ID1,ID2,Lambda=1,init_time=0,isTypeDiff=False):
#Default Lambda?
Lambda = self.get_lambda(Lambda)
# Lookup both streams
incS1 = self.register(ID1,Lambda,init_time,isTypeDiff)
incS2 = self.register(ID2,Lambda,init_time,isTypeDiff)
#check for pre-exiting link
for cov in incS1.covs:
if cov.incStats[0].ID == ID2 or cov.incStats[1].ID == ID2:
return cov #there is a pre-exiting link
# Link incStats
inc_cov = incStat_cov(incS1,incS2,init_time)
incS1.covs.append(inc_cov)
incS2.covs.append(inc_cov)
return inc_cov
# updates/registers stream
def update(self,ID,t,v,Lambda=1,isTypeDiff=False):
incS = self.register(ID,Lambda,t,isTypeDiff)
incS.insert(v,t)
return incS
# Pulls current stats from the given ID
def get_1D_Stats(self,ID,Lambda=1): #weight, mean, std
#Default Lambda?
Lambda = self.get_lambda(Lambda)
#Get incStat
incS = self.HT.get(ID+"_"+str(Lambda))
if incS is None: # does not already exist
return [np.na]*3
else:
return incS.allstats_1D()
# Pulls current correlational stats from the given IDs
def get_2D_Stats(self, ID1, ID2, Lambda=1): #cov, pcc
# Default Lambda?
Lambda = self.get_lambda(Lambda)
# Get incStat
incS1 = self.HT.get(ID1 + "_" + str(Lambda))
if incS1 is None: # does not exist
return [np.na]*2
# find relevant cov entry
return incS1.cov_pcc(ID2)
# Pulls all correlational stats registered with the given ID
# returns tuple [0]: stats-covs&pccs, [2]: IDs
def get_all_2D_Stats(self, ID, Lambda=1): # cov, pcc
# Default Lambda?
Lambda = self.get_lambda(Lambda)
# Get incStat
incS1 = self.HT.get(ID + "_" + str(Lambda))
if incS1 is None: # does not exist
return ([],[])
# find relevant cov entry
stats = []
IDs = []
for cov in incS1.covs:
stats.append(cov.get_stats1())
IDs.append([cov.incStats[0].ID,cov.incStats[1].ID])
return stats,IDs
# Pulls current multidimensional stats from the given IDs
def get_nD_Stats(self,IDs,Lambda=1): #radius, magnitude (IDs is a list)
# Default Lambda?
Lambda = self.get_lambda(Lambda)
# Get incStats
incStats = []
for ID in IDs:
incS = self.HT.get(ID + "_" + str(Lambda))
if incS is not None: #exists
incStats.append(incS)
# Compute stats
rad = 0 #radius
mag = 0 #magnitude
for incS in incStats:
rad += incS.var()
mag += incS.mean()**2
return [np.sqrt(rad),np.sqrt(mag)]
# Updates and then pulls current 1D stats from the given ID. Automatically registers previously unknown stream IDs
def update_get_1D_Stats(self, ID,t,v,Lambda=1,isTypeDiff=False): # weight, mean, std
incS = self.update(ID,t,v,Lambda,isTypeDiff)
return incS.allstats_1D()
# Updates and then pulls current correlative stats between the given IDs. Automatically registers previously unknown stream IDs, and cov tracking
#Note: AfterImage does not currently support Diff Type streams for correlational statistics.
def update_get_2D_Stats(self, ID1,ID2,t1,v1,Lambda=1,level=1): #level= 1:cov,pcc 2:radius,magnitude,cov,pcc
#retrieve/add cov tracker
inc_cov = self.register_cov(ID1, ID2, Lambda, t1)
# Update cov tracker
inc_cov.update_cov(ID1,v1,t1)
if level == 1:
return inc_cov.get_stats1()
else:
return inc_cov.get_stats2()
# Updates and then pulls current 1D and 2D stats from the given IDs. Automatically registers previously unknown stream IDs
def update_get_1D2D_Stats(self, ID1,ID2,t1,v1,Lambda=1): # weight, mean, std
return self.update_get_1D_Stats(ID1,t1,v1,Lambda) + self.update_get_2D_Stats(ID1,ID2,t1,v1,Lambda,level=2)
def getHeaders_1D(self,Lambda=1,ID=None):
# Default Lambda?
Lambda = self.get_lambda(Lambda)
hdrs = incStat(Lambda,ID).getHeaders_1D(suffix=False)
return [str(Lambda)+"_"+s for s in hdrs]
def getHeaders_2D(self,Lambda=1,IDs=None, ver=1): #IDs is a 2-element list or tuple
# Default Lambda?
Lambda = self.get_lambda(Lambda)
if IDs is None:
IDs = [0,1]
hdrs = incStat_cov(incStat(Lambda,IDs[0]),incStat(Lambda,IDs[0]),Lambda).getHeaders(ver,suffix=False)
return [str(Lambda)+"_"+s for s in hdrs]
def getHeaders_1D2D(self,Lambda=1,IDs=None, ver=1):
# Default Lambda?
Lambda = self.get_lambda(Lambda)
if IDs is None:
IDs = [0,1]
hdrs1D = self.getHeaders_1D(Lambda,IDs[0])
hdrs2D = self.getHeaders_2D(Lambda,IDs, ver)
return hdrs1D + hdrs2D
def getHeaders_nD(self,Lambda=1,IDs=[]): #IDs is a n-element list or tuple
# Default Lambda?
ID = ":"
for s in IDs:
ID += "_"+s
Lambda = self.get_lambda(Lambda)
hdrs = ["radius"+ID, "magnitude"+ID]
return [str(Lambda)+"_"+s for s in hdrs]
#cleans out records that have a weight less than the cutoff.
#returns number or removed records.
def cleanOutOldRecords(self,cutoffWeight,curTime):
n = 0
dump = sorted(self.HT.items(), key=lambda tup: tup[1][0].getMaxW(curTime))
for entry in dump:
entry[1][0].processDecay(curTime)
W = entry[1][0].w
if W <= cutoffWeight:
key = entry[0]
del entry[1][0]
del self.HT[key]
n=n+1
elif W > cutoffWeight:
break
return n