-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy pathanomaly.py
More file actions
3202 lines (2386 loc) · 117 KB
/
Copy pathanomaly.py
File metadata and controls
3202 lines (2386 loc) · 117 KB
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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# *****************************************************************************
# © Copyright IBM Corp. 2018, 2022 All Rights Reserved.
#
# This program and the accompanying materials
# are made available under the terms of the Apache V2.0 license
# which accompanies this distribution, and is available at
# http://www.apache.org/licenses/LICENSE-2.0
#
# *****************************************************************************
"""
The Built In Functions module contains preinstalled functions
"""
import itertools as it
import datetime as dt
import importlib
import logging
import time
import hashlib # encode feature names
import traceback
import numpy as np
import pandas as pd
import scipy as sp
from pyod.models.cblof import CBLOF
import numpy as np
import pandas as pd
import scipy as sp
from pyod.models.cblof import CBLOF
import ruptures as rpt
# for Spectral Analysis
from scipy import signal, fftpack
import skimage as ski
from skimage import util as skiutil # for nifty windowing
# for KMeans
from sklearn import ensemble
from sklearn import linear_model
from sklearn import metrics
from sklearn.covariance import MinCovDet
from sklearn.neighbors import (KernelDensity, LocalOutlierFactor)
from sklearn.pipeline import Pipeline, TransformerMixin
from sklearn.model_selection import train_test_split
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.mixture import BayesianGaussianMixture
from sklearn.preprocessing import (StandardScaler, RobustScaler, MinMaxScaler,
minmax_scale, PolynomialFeatures)
from sklearn.utils import check_array
# for Matrix Profile
import stumpy
# for KDEAnomalyScorer
import statsmodels.api as sm
from statsmodels.nonparametric.kernel_density import KDEMultivariate
from statsmodels.tsa.arima.model import ARIMA
# EXCLUDED until we upgrade to statsmodels 0.12
#from statsmodels.tsa.forecasting.stl import STLForecast
from .base import (BaseTransformer, BaseRegressor, BaseEstimatorFunction, BaseSimpleAggregator)
from .bif import (AlertHighValue)
from .ui import (UISingle, UIMulti, UIMultiItem, UIFunctionOutSingle, UISingleItem, UIFunctionOutMulti)
from .db import (Database, DatabaseFacade)
from .dbtables import (FileModelStore, DBModelStore)
# VAE
import torch
import torch.autograd
import torch.nn as nn
logger = logging.getLogger(__name__)
try:
# for gradient boosting
import lightgbm
except (AttributeError, ImportError):
logger.exception('')
logger.debug(f'Could not import lightgm package. Might have issues when using GBMRegressor catalog function')
PACKAGE_URL = 'git+https://github.com/ibm-watson-iot/functions.git@'
_IS_PREINSTALLED = True
Error_SmallWindowsize = 0.0001
Error_Generic = 0.0002
FrequencySplit = 0.3
DefaultWindowSize = 12
SmallEnergy = 1e-20
KMeans_normalizer = 1
Spectral_normalizer = 100 / 2.8
FFT_normalizer = 1
Saliency_normalizer = 1
Generalized_normalizer = 1 / 300
# Do away with numba logs
numba_logger = logging.getLogger('numba')
numba_logger.setLevel(logging.ERROR)
# from
# https://stackoverflow.com/questions/44790072/sliding-window-on-time-series-data
def view_as_windows1(temperature, length, step):
logger.info('VIEW ' + str(temperature.shape) + ' ' + str(length) + ' ' + str(step))
def moving_window(x, length, _step=1):
if type(step) != 'int' or _step < 1:
logger.info('MOVE ' + str(_step))
_step = 1
streams = it.tee(x, length)
return zip(*[it.islice(stream, i, None, _step) for stream, i in zip(streams, it.count(step=1))])
x_ = list(moving_window(temperature, length, step))
return np.asarray(x_)
def view_as_windows(temperature, length, step):
return skiutil.view_as_windows(temperature, window_shape=(length,), step=step)
def custom_resampler(array_like):
# initialize
if 'gap' not in dir():
gap = 0
if array_like.values.size > 0:
gap = 0
return 0
else:
gap += 1
return gap
def min_delta(df):
# minimal time delta for merging
if df is None:
return pd.Timedelta('5 seconds'), df
elif len(df.index.names) > 1:
df2 = df.reset_index(level=df.index.names[1:], drop=True)
else:
df2 = df
try:
mindelta = df2.index.to_series().diff().min()
except Exception as e:
logger.debug('Min Delta error: ' + str(e))
mindelta = pd.Timedelta('5 seconds')
if mindelta == dt.timedelta(seconds=0) or pd.isnull(mindelta):
mindelta = pd.Timedelta('5 seconds')
return mindelta, df2
def set_window_size_and_overlap(windowsize, trim_value=2 * DefaultWindowSize):
# make sure it exists
if windowsize is None:
windowsize = DefaultWindowSize
# make sure it is positive and not too large
trimmed_ws = np.minimum(np.maximum(windowsize, 1), trim_value)
# overlap
if trimmed_ws == 1:
ws_overlap = 0
else:
# larger overlap - half the window
ws_overlap = trimmed_ws // 2
return trimmed_ws, ws_overlap
def dampen_anomaly_score(array, dampening):
if dampening is None:
dampening = 0.9 # gradient dampening
if dampening >= 1:
return array
if dampening < 0.01:
return array
if array.size <= 1:
return array
gradient = np.gradient(array)
# dampened
grad_damp = np.float_power(abs(gradient), dampening) * np.sign(gradient)
# reconstruct (dampened) anomaly score by discrete integration
integral = []
x = array[0]
for x_el in np.nditer(grad_damp):
x = x + x_el
integral.append(x)
# shift array slightly to the right to position anomaly score
array_damp = np.roll(np.asarray(integral), 1)
array_damp[0] = array_damp[1]
# normalize
return array_damp / dampening / 2
# Saliency helper functions
# copied from https://github.com/y-bar/ml-based-anomaly-detection
# remove the boring part from an image resp. time series
def series_filter(values, kernel_size=3):
"""
Filter a time series. Practically, calculated mean value inside kernel size.
As math formula, see https://docs.opencv.org/2.4/modules/imgproc/doc/filtering.html.
:param values:
:param kernel_size:
:return: The list of filtered average
"""
filter_values = np.cumsum(values, dtype=float)
logger.info('SERIES_FILTER: ' + str(values.shape) + ',' + str(filter_values.shape) + ',' + str(kernel_size))
filter_values[kernel_size:] = filter_values[kernel_size:] - filter_values[:-kernel_size]
filter_values[kernel_size:] = filter_values[kernel_size:] / kernel_size
for i in range(1, kernel_size):
filter_values[i] /= i + 1
return filter_values
# Saliency class
# see https://www.inf.uni-hamburg.de/en/inst/ab/cv/research/research1-visual-attention.html
class Saliency(object):
def __init__(self, amp_window_size, series_window_size, score_window_size):
self.amp_window_size = amp_window_size
self.series_window_size = series_window_size
self.score_window_size = score_window_size
def transform_saliency_map(self, values):
"""
Transform a time-series into spectral residual, which is method in computer vision.
For example, See https://docs.opencv.org/master/d8/d65/group__saliency.html
:param values: a list or numpy array of float values.
:return: silency map and spectral residual
"""
freq = np.fft.fft(values)
mag = np.sqrt(freq.real ** 2 + freq.imag ** 2)
# remove the boring part of a timeseries
spectral_residual = np.exp(np.log(mag) - series_filter(np.log(mag), self.amp_window_size))
freq.real = freq.real * spectral_residual / mag
freq.imag = freq.imag * spectral_residual / mag
# and apply inverse fourier transform
saliency_map = np.fft.ifft(freq)
return saliency_map
def transform_spectral_residual(self, values):
saliency_map = self.transform_saliency_map(values)
spectral_residual = np.sqrt(saliency_map.real ** 2 + saliency_map.imag ** 2)
return spectral_residual
#######################################################################################
# Scalers
#######################################################################################
class Standard_Scaler(BaseEstimatorFunction):
"""
Learns and applies standard scaling
"""
eval_metric = staticmethod(metrics.r2_score)
# class variables
train_if_no_model = True
def set_estimators(self):
self.estimators['standard_scaler'] = (StandardScaler, self.params)
logger.info('Standard Scaler initialized')
def __init__(self, features=None, targets=None, predictions=None):
super().__init__(features=features, targets=targets, predictions=predictions, keep_current_models=True)
# do not run score and call transform instead of predict
self.is_scaler = True
self.experiments_per_execution = 1
self.normalize = True # support for optional scaling in subclasses
self.prediction = self.predictions[0] # support for subclasses with univariate focus
self.params = {}
self.whoami = 'Standard_Scaler'
# used by all the anomaly scorers based on it
def prepare_data(self, dfEntity):
logger.debug(self.whoami + ': prepare Data for ' + self.prediction + ' column')
# operate on simple timestamp index
# needed for aggregated data with 3 or more indices
if len(dfEntity.index.names) > 1:
index_names = dfEntity.index.names
dfe = dfEntity.reset_index(index_names[1:])
else:
dfe = dfEntity
# interpolate gaps - data imputation
try:
dfe = dfe.interpolate(method="time")
except Exception as e:
logger.error('Prepare data error: ' + str(e))
# one dimensional time series - named temperature for catchyness
temperature = dfe[self.prediction].fillna(0).to_numpy(dtype=np.float64)
return dfe, temperature
# dummy function for scaler, can be replaced with anomaly functions
def kexecute(self, entity, df_copy):
return df_copy
def execute(self, df):
df_copy = df.copy()
entities = np.unique(df_copy.index.levels[0])
logger.debug(str(entities))
missing_cols = [x for x in self.predictions if x not in df_copy.columns]
for m in missing_cols:
df_copy[m] = None
for entity in entities:
normalize_entity = self.normalize
try:
check_array(df_copy.loc[[entity]][self.features].values, allow_nd=True)
except Exception as e:
normalize_entity = False
logger.error(
'Found Nan or infinite value in feature columns for entity ' + str(entity) + ' error: ' + str(e))
# support for optional scaling in subclasses
if normalize_entity:
dfe = super()._execute(df_copy.loc[[entity]], entity)
df_copy.loc[entity, self.predictions] = dfe[self.predictions]
else:
self.prediction = self.features[0]
df_copy = self.kexecute(entity, df_copy)
self.prediction = self.predictions[0]
logger.info('Standard_Scaler: Found columns ' + str(df_copy.columns))
return df_copy
@classmethod
def build_ui(cls):
# define arguments that behave as function inputs
inputs = []
inputs.append(UIMultiItem(name='features', datatype=float, required=True))
inputs.append(UIMultiItem(name='targets', datatype=float, required=True, output_item='predictions',
is_output_datatype_derived=True))
# define arguments that behave as function outputs
outputs = []
return inputs, outputs
class Robust_Scaler(BaseEstimatorFunction):
"""
Learns and applies robust scaling, scaling after outlier removal
"""
eval_metric = staticmethod(metrics.r2_score)
# class variables
train_if_no_model = True
def set_estimators(self):
self.estimators['robust_scaler'] = (RobustScaler, self.params)
logger.info('Robust Scaler initialized')
def __init__(self, features=None, targets=None, predictions=None):
super().__init__(features=features, targets=targets, predictions=predictions, keep_current_models=True)
# do not run score and call transform instead of predict
self.is_scaler = True
self.experiments_per_execution = 1
self.params = {}
def execute(self, df):
df_copy = df.copy()
entities = np.unique(df_copy.index.levels[0])
logger.debug(str(entities))
missing_cols = [x for x in self.predictions if x not in df_copy.columns]
for m in missing_cols:
df_copy[m] = None
for entity in entities:
# per entity - copy for later inplace operations
try:
check_array(df_copy.loc[[entity]][self.features].values, allow_nd=True)
except Exception as e:
logger.error(
'Found Nan or infinite value in feature columns for entity ' + str(entity) + ' error: ' + str(e))
continue
dfe = super()._execute(df_copy.loc[[entity]], entity)
df_copy.loc[entity, self.predictions] = dfe[self.predictions]
return df_copy
@classmethod
def build_ui(cls):
# define arguments that behave as function inputs
inputs = []
inputs.append(UIMultiItem(name='features', datatype=float, required=True))
inputs.append(UIMultiItem(name='targets', datatype=float, required=True, output_item='predictions',
is_output_datatype_derived=True))
# define arguments that behave as function outputs
outputs = []
return inputs, outputs
class MinMax_Scaler(BaseEstimatorFunction):
"""
Learns and applies minmax scaling
"""
eval_metric = staticmethod(metrics.r2_score)
# class variables
train_if_no_model = True
def set_estimators(self):
self.estimators['minmax_scaler'] = (MinMaxScaler, self.params)
logger.info('MinMax Scaler initialized')
def __init__(self, features=None, targets=None, predictions=None):
super().__init__(features=features, targets=targets, predictions=predictions, keep_current_models=True)
# do not run score and call transform instead of predict
self.is_scaler = True
self.experiments_per_execution = 1
self.params = {}
def execute(self, df):
df_copy = df.copy()
entities = np.unique(df_copy.index.levels[0])
logger.debug(str(entities))
missing_cols = [x for x in self.predictions if x not in df_copy.columns]
for m in missing_cols:
df_copy[m] = None
for entity in entities:
try:
check_array(df_copy.loc[[entity]][self.features].values, allow_nd=True)
except Exception as e:
logger.error(
'Found Nan or infinite value in feature columns for entity ' + str(entity) + ' error: ' + str(e))
continue
dfe = super()._execute(df_copy.loc[[entity]], entity)
df_copy.loc[entity, self.predictions] = dfe[self.predictions]
return df_copy
@classmethod
def build_ui(cls):
# define arguments that behave as function inputs
inputs = []
inputs.append(UIMultiItem(name='features', datatype=float, required=True))
inputs.append(UIMultiItem(name='targets', datatype=float, required=True, output_item='predictions',
is_output_datatype_derived=True))
# define arguments that behave as function outputs
outputs = []
return inputs, outputs
#######################################################################################
# Anomaly Scorers
#######################################################################################
class AnomalyScorer(BaseTransformer):
"""
Superclass of all unsupervised anomaly detection functions.
"""
def __init__(self, input_item, windowsize, output_items):
super().__init__()
logger.debug(input_item)
self.input_item = input_item
# use 12 by default
self.windowsize, self.windowoverlap = set_window_size_and_overlap(windowsize)
# assume 1 per sec for now
self.frame_rate = 1
# step
self.step = self.windowsize - self.windowoverlap
self.output_items = output_items
self.normalize = False
self.whoami = 'Anomaly'
def _set_dms(self, dms):
self.dms = dms
def _get_dms(self):
return self.dms
def get_model_name(self, prefix='model', suffix=None):
name = []
if prefix is not None:
name.append(prefix)
name.extend([self._entity_type.name, self.whoami])
name.append(self.output_items[0])
if suffix is not None:
name.append(suffix)
name = '.'.join(name)
return name
# make sure data is evenly spaced
def prepare_data(self, dfEntity):
logger.debug(self.whoami + ': prepare Data')
# operate on simple timestamp index
if len(dfEntity.index.names) > 1:
index_names = dfEntity.index.names
dfe = dfEntity.reset_index(index_names[1:])
else:
dfe = dfEntity
# interpolate gaps - data imputation
try:
#dfe = dfe.dropna(subset=[self.input_item]).interpolate(method="time")
dfe = dfe.interpolate(method="time")
except Exception as e:
logger.error('Prepare data error: ' + str(e))
# one dimensional time series - named temperature for catchyness
temperature = dfe[self.input_item].fillna(0).to_numpy(dtype=np.float64)
return dfe, temperature
def execute(self, df):
logger.debug('Execute ' + self.whoami)
df_copy = df # no copy
# check data type
if not pd.api.types.is_numeric_dtype(df_copy[self.input_item].dtype):
logger.error('Anomaly scoring on non-numeric feature:' + str(self.input_item))
return df_copy
# set output columns to zero
for output_item in self.output_items:
df_copy[output_item] = 0
# delegate to _calc
logger.debug('Execute ' + self.whoami + ' enter per entity execution')
# group over entities
group_base = [pd.Grouper(axis=0, level=0)]
if not df_copy.empty:
df_copy = df_copy.groupby(group_base).apply(self._calc)
logger.debug('Scoring done')
return df_copy
def _calc(self, df):
#entity = df.index.levels[0][0]
entity = df.index[0][0]
# get rid of entity id as part of the index
df = df.droplevel(0)
# Get new data frame with sorted index
dfe_orig = df.sort_index()
# remove all rows with only null entries
dfe = dfe_orig.dropna(how='all')
logger.info('Anomaly ' + str(df[self.output_items[0]].values.shape) + ', ' +
str(dfe_orig[self.output_items[0]].values.shape) + ', ' +
str(dfe[self.output_items[0]].values.shape))
# minimal time delta for merging
mindelta, dfe_orig = min_delta(dfe_orig)
logger.info('Anomaly II ' + str(dfe_orig[self.output_items[0]].values.shape))
logger.debug('Timedelta:' + str(mindelta) + ' Index: ' + str(dfe_orig.index))
# one dimensional time series - named temperature for catchyness
# interpolate gaps - data imputation by default
# for missing data detection we look at the timestamp gradient instead
dfe, temperature = self.prepare_data(dfe)
logger.debug(
self.whoami + ', Entity: ' + str(entity) + ', Input: ' + str(self.input_item) + ', Windowsize: ' + str(
self.windowsize) + ', Output: ' + str(self.output_items) + ', Overlap: ' + str(
self.windowoverlap) + ', Inputsize: ' + str(temperature.size))
if temperature.size <= self.windowsize:
logger.debug(str(temperature.size) + ' <= ' + str(self.windowsize))
for output_item in self.output_items:
dfe[output_item] = Error_SmallWindowsize
else:
logger.debug(str(temperature.size) + ", " + str(self.windowsize))
for output_item in self.output_items:
dfe[output_item] = Error_Generic
temperature = self.scale(temperature, entity)
scores = self.score(temperature)
# length of time_series_temperature, signal_energy and ets_zscore is smaller than half the original
# extend it to cover the full original length
logger.debug('->')
try:
for i,output_item in enumerate(self.output_items):
# check for fast path, no interpolation required
diff = temperature.size - scores[i].size
# slow path - interpolate result score to stretch it to the size of the input data
if diff > 0:
dfe[output_item] = 0.0006
time_series_temperature = np.linspace(self.windowsize // 2, temperature.size - self.windowsize // 2 + 1,
temperature.size - diff)
linear_interpolate = sp.interpolate.interp1d(time_series_temperature, scores[i], kind='linear',
fill_value='extrapolate')
# stretch anomaly score to fit temperature.size
score = abs(linear_interpolate(np.arange(0, temperature.size, 1)))
# and make sure sure it's positive
score[score < 0] = 0
dfe[output_item] = score
# merge so that data is stretched to match the original data w/o gaps and NaNs
dfe_orig = pd.merge_asof(dfe_orig, dfe[output_item], left_index=True, right_index=True,
direction='nearest', tolerance=mindelta)
if output_item + '_y' in dfe_orig:
zScoreII = dfe_orig[output_item + '_y'].to_numpy()
else:
zScoreII = dfe_orig[output_item].to_numpy()
logger.debug('Merge Score : ' + str(score.shape) + ', ' + str(zScoreII.shape))
# fast path - either cut off or just copy
elif diff < 0:
zScoreII = scores[i][0:temperature.size]
else:
zScoreII = scores[i]
# make sure shape is correct
try:
df[output_item] = zScoreII
except Exception as e2:
df[output_item] = zScoreII.reshape(-1,1)
pass
except Exception as e:
logger.error(self.whoami + ' score integration failed with ' + str(e) + '\n' + traceback.format_exc())
logger.debug('--->')
return df
def score(self, temperature):
#scores = np.zeros((len(self.output_items), ) + temperature.shape)
scores = []
for output_item in self.output_items:
scores.append(np.zeros(temperature.shape))
try:
# super simple 1-dimensional z-score
ets_zscore = abs(sp.stats.zscore(temperature))
scores[0] = ets_zscore
# 2nd argument to return the modified input argument (for no data)
if len(self.output_items) > 1:
scores[1] = temperature
except Exception as e:
logger.error(self.whoami + ' failed with ' + str(e))
return scores
def scale(self, temperature, entity):
normalize_entity = self.normalize
if not normalize_entity:
return temperature
temp = temperature.reshape(-1, 1)
logger.info(self.whoami + ' scaling ' + str(temperature.shape))
try:
check_array(temp, allow_nd=True)
except Exception as e:
logger.error('Found Nan or infinite value in input data, error: ' + str(e))
return temperature
# obtain db handler
db = self.get_db()
scaler_model = None
# per entity - copy for later inplace operations
model_name = self.get_model_name(suffix=entity)
try:
scaler_model = db.model_store.retrieve_model(model_name)
logger.info('load model %s' % str(scaler_model))
except Exception as e:
logger.error('Model retrieval failed with ' + str(e))
# failed to load a model, so train it
if scaler_model is None:
# all variables should be continuous
scaler_model = StandardScaler().fit(temp)
logger.debug('Created Scaler ' + str(scaler_model))
try:
db.model_store.store_model(model_name, scaler_model)
except Exception as e:
logger.error('Model store failed with ' + str(e))
if scaler_model is not None:
temp = scaler_model.transform(temp)
return temp.reshape(temperature.shape)
return temperature
#####
# experimental function to interpolate over larger gaps
####
class Interpolator(AnomalyScorer):
"""
Interpolates NaN and data to be interpreted as NaN (for example 0 as invalid sensor reading)
The window size is typically set large enough to allow for "bridging" gaps
Missing indicates sensor readings to be interpreted as invalid.
"""
def __init__(self, input_item, windowsize, missing, output_item):
super().__init__(input_item, windowsize, [output_item])
logger.debug(input_item)
self.missing = missing
self.whoami = 'Interpolator'
def prepare_data(self, dfEntity):
logger.debug(self.whoami + ': prepare Data')
# operate on simple timestamp index
if len(dfEntity.index.names) > 1:
index_names = dfEntity.index.names
dfe = dfEntity.reset_index(index_names[1:])
else:
dfe = dfEntity
# remove Nan
dfe = dfe[dfe[self.input_item].notna()]
# remove self.missing
dfe = dfe[dfe[self.input_item] != self.missing]
# interpolate gaps - data imputation
try:
dfe = dfe.interpolate(method="time")
except Exception as e:
logger.error('Prepare data error: ' + str(e))
# one dimensional time series - named temperature for catchyness
# replace NaN with self.missing
temperature = dfe[self.input_item].fillna(0).to_numpy(dtype=np.float64)
return dfe, temperature
@classmethod
def build_ui(cls):
# define arguments that behave as function inputs
inputs = []
inputs.append(UISingleItem(name='input_item', datatype=float, description='Data item to interpolate'))
inputs.append(
UISingle(name='windowsize', datatype=int, description='Minimal size of the window for interpolating data.'))
inputs.append(UISingle(name='missing', datatype=int, description='Data to be interpreted as not-a-number.'))
# define arguments that behave as function outputs
outputs = []
outputs.append(UIFunctionOutSingle(name='output_item', datatype=float, description='Interpolated data'))
return (inputs, outputs)
class NoDataAnomalyScoreExt(AnomalyScorer):
"""
An unsupervised anomaly detection function.
Uses z-score AnomalyScorer to find gaps in data.
The function moves a sliding window across the data signal and applies the anomaly model to each window.
The window size is typically set to 12 data points.
"""
def __init__(self, input_item, windowsize, output_item):
super().__init__(input_item, windowsize, [output_item])
self.whoami = 'NoDataExt'
self.normalizer = 1
logger.debug('NoDataExt')
def prepare_data(self, dfEntity):
logger.debug(self.whoami + ': prepare Data')
# operate on simple timestamp index
if len(dfEntity.index.names) > 1:
index_names = dfEntity.index.names
dfe = dfEntity.reset_index(index_names[1:])
else:
dfe = dfEntity
# count the timedelta in seconds between two events
timeSeq = (dfe.index.values - dfe.index[0].to_datetime64()) / np.timedelta64(1, 's')
#dfe = dfEntity.copy()
# one dimensional time series - named temperature for catchyness
# we look at the gradient of the time series timestamps for anomaly detection
# might throw an exception - we catch it in the super class !!
try:
temperature = np.gradient(timeSeq)
dfe[[self.input_item]] = temperature
except Exception as pe:
logger.info("NoData Gradient failed with " + str(pe))
dfe[[self.input_item]] = 0
temperature = dfe[[self.input_item]].values
temperature[0] = 10 ** 10
temperature = temperature.astype('float64').reshape(-1)
return dfe, temperature
@classmethod
def build_ui(cls):
# define arguments that behave as function inputs
inputs = []
inputs.append(UISingleItem(name='input_item', datatype=float, description='Data item to analyze'))
inputs.append(UISingle(name='windowsize', datatype=int,
description='Size of each sliding window in data points. Typically set to 12.'))
# define arguments that behave as function outputs
outputs = []
outputs.append(UIFunctionOutSingle(name='output_item', datatype=float, description='No data anomaly score'))
return inputs, outputs
class ChangePointDetector(AnomalyScorer):
'''
An unsupervised anomaly detection function.
Applies a spectral analysis clustering techniqueto extract features from time series data and to create z scores.
Moves a sliding window across the data signal and applies the anomalymodelto each window.
The window size is typically set to 12 data points.
Try several anomaly detectors on your data and use the one that fits your data best.
'''
def __init__(self, input_item, windowsize, chg_pts):
super().__init__(input_item, windowsize, [chg_pts])
logger.debug(input_item)
self.whoami = 'ChangePointDetector'
def score(self, temperature):
scores = []
sc = np.zeros(temperature.shape)
try:
algo = rpt.BottomUp(model="l2", jump=2).fit(temperature)
chg_pts = algo.predict(n_bkps=15)
for j in chg_pts:
x = np.arange(0, temperature.shape[0], 1)
Gaussian = sp.stats.norm(j-1, temperature.shape[0]/20) # high precision
y = Gaussian.pdf(x) * temperature.shape[0]/8 # max is ~1
sc += y
except Exception as e:
logger.error(self.whoami + ' failed with ' + str(e))
scores.append(sc)
return scores
@classmethod
def build_ui(cls):
# define arguments that behave as function inputs
inputs = []
inputs.append(UISingleItem(name='input_item', datatype=float, description='Data item to analyze'))
# define arguments that behave as function outputs
outputs = []
outputs.append(UIFunctionOutSingle(name='chg_pts', datatype=float, description='Change points'))
return inputs, outputs
ENSEMBLE = '_ensemble_'
SPECTRALEXT = 'SpectralAnomalyScoreExt'
class EnsembleAnomalyScore(BaseTransformer):
'''
Call a set of anomaly detectors and return an joint vote along with the individual results
'''
def __init__(self, input_item, windowsize, scorers, thresholds, output_item):
super().__init__()
self.input_item = input_item
self.windowsize = windowsize
self.output_item = output_item
logger.debug(input_item)
self.whoami = 'EnsembleAnomalyScore'
self.list_of_scorers = scorers.split(',')
self.thresholds = list(map(int, thresholds.split(',')))
self.klasses = []
self.instances = []
self.output_items = []
module = importlib.import_module('mmfunctions.anomaly')
for m in self.list_of_scorers:
klass = getattr(module, m)
self.klasses.append(klass)
print(klass.__name__)
if klass.__name__ == SPECTRALEXT:
inst = klass(input_item, windowsize, output_item + ENSEMBLE + klass.__name__,
output_item + ENSEMBLE + klass.__name__ + '_inv')
else:
inst = klass(input_item, windowsize, output_item + ENSEMBLE + klass.__name__)
self.output_items.append(output_item + ENSEMBLE + klass.__name__)
self.instances.append(inst)
def execute(self, df):
logger.debug('Execute ' + self.whoami)
df_copy = df # no copy
binned_indices_list = []
for inst, output, threshold in zip(self.instances, self.output_items, self.thresholds):
logger.info('Execute anomaly scorer ' + str(inst.__class__.__name__) + ' with threshold ' + str(threshold))
tic = time.perf_counter_ns()
df_copy = inst.execute(df_copy)
toc = time.perf_counter_ns()
logger.info('Executed anomaly scorer ' + str(inst.__class__.__name__) + ' in ' +\
str((toc-tic)//1000000) + ' milliseconds')
arr = df_copy[output]
# sort results into bins that depend on the thresholds
# 0 - below 3/4 threshold, 1 - up to the threshold, 2 - crossed the threshold,
# 3 - very high, 4 - extreme
if inst.__class__.__name__ == SPECTRALEXT and isinstance(threshold, int):
# hard coded threshold for inverted values
threshold_ = 5
bins = [threshold * 0.75, threshold, threshold * 1.5, threshold * 2]
binned_indices_list.append(np.searchsorted(bins, arr, side='left'))
if inst.__class__.__name__ == SPECTRALEXT:
bins = [threshold_ * 0.75, threshold_, threshold_ * 1.5, threshold_ * 2]
arr = df_copy[output + '_inv']