This repository has been archived by the owner on Aug 2, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 18
/
anomalyResultUtils.ts
1181 lines (1129 loc) · 31.5 KB
/
anomalyResultUtils.ts
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 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
import { get, isEmpty, orderBy } from 'lodash';
import moment from 'moment';
import { Dispatch } from 'redux';
import {
EntityAnomalySummaries,
EntityAnomalySummary,
Entity,
} from '../../../server/models/interfaces';
import {
AD_DOC_FIELDS,
DOC_COUNT_FIELD,
ENTITY_FIELD,
ENTITY_NAME_PATH_FIELD,
ENTITY_VALUE_PATH_FIELD,
KEY_FIELD,
MIN_IN_MILLI_SECS,
SORT_DIRECTION,
} from '../../../server/utils/constants';
import { toFixedNumberForAnomaly } from '../../../server/utils/helpers';
import {
Anomalies,
AnomalyData,
AnomalySummary,
DateRange,
Detector,
FeatureAggregationData,
FeatureAttributes,
} from '../../models/interfaces';
import { getDetectorLiveResults } from '../../redux/reducers/liveAnomalyResults';
import {
MAX_ANOMALIES,
MISSING_FEATURE_DATA_SEVERITY,
} from '../../utils/constants';
import { HeatmapCell } from '../AnomalyCharts/containers/AnomalyHeatmapChart';
import { AnomalyHeatmapSortType } from '../AnomalyCharts/utils/anomalyChartUtils';
import { DETECTOR_INIT_FAILURES } from '../DetectorDetail/utils/constants';
import {
COUNT_ANOMALY_AGGS,
ENTITY_DATE_BUCKET_ANOMALY_AGGS,
MAX_ANOMALY_AGGS,
MAX_ANOMALY_SORT_AGGS,
TOP_ANOMALY_GRADE_SORT_AGGS,
TOP_ENTITIES_FIELD,
TOP_ENTITY_AGGS,
} from './constants';
import { dateFormatter, minuteDateFormatter } from './helpers';
export const getQueryParamsForLiveAnomalyResults = (
detectionInterval: number,
intervals: number
) => {
const startTime = moment()
.subtract(intervals * detectionInterval, 'minutes')
.valueOf();
const updatedParams = {
from: 0,
size: intervals,
sortDirection: SORT_DIRECTION.DESC,
sortField: AD_DOC_FIELDS.DATA_START_TIME,
startTime: startTime.valueOf(),
fieldName: AD_DOC_FIELDS.DATA_START_TIME,
};
return updatedParams;
};
export const getLiveAnomalyResults = (
dispatch: Dispatch<any>,
detectorId: string,
detectionInterval: number,
intervals: number
) => {
const queryParams = getQueryParamsForLiveAnomalyResults(
detectionInterval,
intervals
);
dispatch(getDetectorLiveResults(detectorId, queryParams, false));
};
export const buildParamsForGetAnomalyResultsWithDateRange = (
startTime: number,
endTime: number,
anomalyOnly: boolean = false,
entity: Entity | undefined = undefined
) => {
return {
from: 0,
size: MAX_ANOMALIES,
sortDirection: SORT_DIRECTION.DESC,
sortField: AD_DOC_FIELDS.DATA_START_TIME,
startTime: startTime,
endTime: endTime,
fieldName: AD_DOC_FIELDS.DATA_START_TIME,
anomalyThreshold: anomalyOnly ? 0 : -1,
entityName: entity?.name,
entityValue: entity?.value,
};
};
const MAX_DATA_POINTS = 1000;
const MAX_FEATURE_ANNOTATIONS = 100;
const calculateStep = (total: number): number => {
return Math.ceil(total / MAX_DATA_POINTS);
};
export const calculateTimeWindowsWithMaxDataPoints = (
maxDataPoints: number,
dateRange: DateRange
): DateRange[] => {
const resultSampleWindows = [] as DateRange[];
const rangeInMilliSec = dateRange.endDate - dateRange.startDate;
const windowSizeinMilliSec = Math.max(
Math.ceil(rangeInMilliSec / maxDataPoints),
MIN_IN_MILLI_SECS
);
for (
let currentTime = dateRange.startDate;
currentTime < dateRange.endDate;
currentTime += windowSizeinMilliSec
) {
resultSampleWindows.push({
startDate: currentTime,
endDate: Math.min(currentTime + windowSizeinMilliSec, dateRange.endDate),
} as DateRange);
}
return resultSampleWindows;
};
// If array size is 100K, `findAnomalyWithMaxAnomalyGrade`
// takes less than 2ms by average, while `Array#reduce`
// takes about 16ms by average and`Array#sort`
// takes about 3ms by average.
// If array size is 1M, `findAnomalyWithMaxAnomalyGrade`
// takes less than 6ms by average, while `Array#reduce`
// takes about 170ms by average and`Array#sort` takes about
// 80ms by average.
// Considering performance impact, will not change this
// method currently.
function findAnomalyWithMaxAnomalyGrade(anomalies: any[]) {
let anomalyWithMaxGrade = anomalies[0];
for (let i = 1, len = anomalies.length; i < len; i++) {
let anomaly = anomalies[i];
anomalyWithMaxGrade =
anomaly.anomalyGrade > anomalyWithMaxGrade.anomalyGrade
? anomaly
: anomalyWithMaxGrade;
}
return anomalyWithMaxGrade;
}
const sampleMaxAnomalyGrade = (anomalies: any[]): any[] => {
const step = calculateStep(anomalies.length);
let index = 0;
const sampledAnomalies = [];
while (index < anomalies.length) {
const arr = anomalies.slice(index, index + step);
sampledAnomalies.push(findAnomalyWithMaxAnomalyGrade(arr));
index = index + step;
}
return sampledAnomalies;
};
export const prepareDataForLiveChart = (
data: any[],
dateRange: DateRange,
interval: number
) => {
if (!data || data.length === 0) {
return [];
}
let anomalies = [];
for (
let time = dateRange.endDate;
time > dateRange.startDate;
time -= MIN_IN_MILLI_SECS * interval
) {
anomalies.push({
startTime: time,
endTime: time,
plotTime: time,
confidence: null,
anomalyGrade: null,
});
}
anomalies.push({
startTime: dateRange.startDate,
endTime: dateRange.startDate,
plotTime: dateRange.startDate,
confidence: null,
anomalyGrade: null,
});
return anomalies;
};
export const prepareDataForChart = (
data: any[],
dateRange: DateRange,
withoutPadding?: boolean
) => {
let anomalies = [];
if (data && data.length > 0) {
anomalies = data.filter(
(anomaly) =>
anomaly.plotTime >= dateRange.startDate &&
anomaly.plotTime <= dateRange.endDate
);
if (anomalies.length > MAX_DATA_POINTS) {
anomalies = sampleMaxAnomalyGrade(anomalies);
}
}
if (withoutPadding) {
// just return result if padding/placeholder data is not needed
return anomalies;
}
anomalies.push({
startTime: dateRange.startDate,
endTime: dateRange.startDate,
plotTime: dateRange.startDate,
confidence: null,
anomalyGrade: null,
});
anomalies.unshift({
startTime: dateRange.endDate,
endTime: dateRange.endDate,
plotTime: dateRange.endDate,
confidence: null,
anomalyGrade: null,
});
return anomalies;
};
export const generateAnomalyAnnotations = (anomalies: any[]): any[] => {
return anomalies
.filter((anomaly: AnomalyData) => anomaly.anomalyGrade > 0)
.map((anomaly: AnomalyData) => ({
coordinates: {
x0: anomaly.startTime,
x1: anomaly.endTime,
},
details: `There is an anomaly with confidence ${
anomaly.confidence
} between ${moment(anomaly.startTime).format(
'MM/DD/YY h:mm A'
)} and ${moment(anomaly.endTime).format('MM/DD/YY h:mm A')}`,
entity: get(anomaly, 'entity', []),
}));
};
export const filterWithDateRange = (
data: any[],
dateRange: DateRange,
timeField: string
) => {
const anomalies = data
? data.filter((item) => {
const time = get(item, `${timeField}`);
return time && time >= dateRange.startDate && time <= dateRange.endDate;
})
: [];
return anomalies;
};
export const RETURNED_AD_RESULT_FIELDS = [
'data_start_time',
'data_end_time',
'anomaly_grade',
'confidence',
'feature_data',
'entity',
];
export const getAnomalySummaryQuery = (
startTime: number,
endTime: number,
detectorId: string,
entity: Entity | undefined = undefined,
isHistorical?: boolean,
taskId?: string
) => {
const termField =
isHistorical && taskId ? { task_id: taskId } : { detector_id: detectorId };
return {
size: MAX_ANOMALIES,
query: {
bool: {
filter: [
{
range: {
data_end_time: {
gte: startTime,
lte: endTime,
},
},
},
{
range: {
anomaly_grade: {
gt: 0,
},
},
},
{
term: termField,
},
...(entity
? [
{
nested: {
path: ENTITY_FIELD,
query: {
term: {
[ENTITY_VALUE_PATH_FIELD]: {
value: entity.value,
},
},
},
},
},
{
nested: {
path: ENTITY_FIELD,
query: {
term: {
[ENTITY_NAME_PATH_FIELD]: {
value: entity.name,
},
},
},
},
},
]
: []),
],
},
},
aggs: {
count_anomalies: {
value_count: {
field: 'anomaly_grade',
},
},
max_confidence: {
max: {
field: 'confidence',
},
},
min_confidence: {
min: {
field: 'confidence',
},
},
max_anomaly_grade: {
max: {
field: 'anomaly_grade',
},
},
min_anomaly_grade: {
min: {
field: 'anomaly_grade',
},
},
avg_anomaly_grade: {
avg: {
field: 'anomaly_grade',
},
},
max_data_end_time: {
max: {
field: 'data_end_time',
},
},
},
_source: {
includes: RETURNED_AD_RESULT_FIELDS,
},
};
};
export const getBucketizedAnomalyResultsQuery = (
startTime: number,
endTime: number,
detectorId: string,
entity: Entity | undefined = undefined,
isHistorical?: boolean,
taskId?: string
) => {
const termField =
isHistorical && taskId ? { task_id: taskId } : { detector_id: detectorId };
const fixedInterval = Math.ceil(
(endTime - startTime) / (MIN_IN_MILLI_SECS * MAX_DATA_POINTS)
);
return {
size: 0,
query: {
bool: {
filter: [
{
range: {
data_end_time: {
gte: startTime,
lte: endTime,
},
},
},
{
term: termField,
},
...(entity
? [
{
nested: {
path: ENTITY_FIELD,
query: {
term: {
[ENTITY_VALUE_PATH_FIELD]: {
value: entity.value,
},
},
},
},
},
{
nested: {
path: ENTITY_FIELD,
query: {
term: {
[ENTITY_NAME_PATH_FIELD]: {
value: entity.name,
},
},
},
},
},
]
: []),
],
},
},
aggs: {
bucketized_anomaly_grade: {
date_histogram: {
field: 'data_end_time',
fixed_interval: `${fixedInterval}m`,
},
aggs: {
top_anomaly_hits: {
top_hits: {
sort: [
{
anomaly_grade: {
order: 'desc',
},
},
],
_source: {
includes: RETURNED_AD_RESULT_FIELDS,
},
size: 1,
},
},
},
},
},
};
};
export const parseBucketizedAnomalyResults = (result: any): Anomalies => {
const rawAnomalies = get(
result,
'response.aggregations.bucketized_anomaly_grade.buckets',
[]
) as any[];
let anomalies = [] as AnomalyData[];
let featureData = {} as { [key: string]: FeatureAggregationData[] };
rawAnomalies.forEach((item) => {
if (get(item, 'top_anomaly_hits.hits.hits', []).length > 0) {
const rawAnomaly = get(item, 'top_anomaly_hits.hits.hits.0._source');
if (
get(rawAnomaly, 'anomaly_grade') !== undefined &&
get(rawAnomaly, 'feature_data', []).length > 0
) {
anomalies.push({
anomalyGrade: toFixedNumberForAnomaly(
get(rawAnomaly, 'anomaly_grade')
),
confidence: toFixedNumberForAnomaly(get(rawAnomaly, 'confidence')),
startTime: get(rawAnomaly, 'data_start_time'),
endTime: get(rawAnomaly, 'data_end_time'),
plotTime: get(rawAnomaly, 'data_end_time'),
entity: get(rawAnomaly, 'entity'),
});
get(rawAnomaly, 'feature_data', []).forEach((feature) => {
if (!get(featureData, get(feature, 'feature_id'))) {
featureData[get(feature, 'feature_id')] = [];
}
featureData[get(feature, 'feature_id')].push({
data: toFixedNumberForAnomaly(get(feature, 'data')),
startTime: get(rawAnomaly, 'data_start_time'),
endTime: get(rawAnomaly, 'data_end_time'),
plotTime: get(rawAnomaly, 'data_end_time'),
});
});
}
}
});
return {
anomalies: anomalies,
featureData: featureData,
};
};
export const parseAnomalySummary = (
anomalySummaryResult: any
): AnomalySummary => {
const anomalyCount = get(
anomalySummaryResult,
'response.aggregations.count_anomalies.value',
0
);
return {
anomalyOccurrence: anomalyCount,
minAnomalyGrade: anomalyCount
? toFixedNumberForAnomaly(
get(
anomalySummaryResult,
'response.aggregations.min_anomaly_grade.value'
)
)
: 0,
maxAnomalyGrade: anomalyCount
? toFixedNumberForAnomaly(
get(
anomalySummaryResult,
'response.aggregations.max_anomaly_grade.value'
)
)
: 0,
avgAnomalyGrade: anomalyCount
? toFixedNumberForAnomaly(
get(
anomalySummaryResult,
'response.aggregations.avg_anomaly_grade.value'
)
)
: 0,
minConfidence: anomalyCount
? toFixedNumberForAnomaly(
get(
anomalySummaryResult,
'response.aggregations.min_confidence.value'
)
)
: 0,
maxConfidence: anomalyCount
? toFixedNumberForAnomaly(
get(
anomalySummaryResult,
'response.aggregations.max_confidence.value'
)
)
: 0,
lastAnomalyOccurrence: anomalyCount
? minuteDateFormatter(
get(
anomalySummaryResult,
'response.aggregations.max_data_end_time.value'
)
)
: '',
};
};
export const parsePureAnomalies = (
anomalySummaryResult: any
): AnomalyData[] => {
const anomaliesHits = get(anomalySummaryResult, 'response.hits.hits', []);
const anomalies = [] as AnomalyData[];
if (anomaliesHits.length > 0) {
anomaliesHits.forEach((item: any) => {
const rawAnomaly = get(item, '_source');
anomalies.push({
anomalyGrade: toFixedNumberForAnomaly(get(rawAnomaly, 'anomaly_grade')),
confidence: toFixedNumberForAnomaly(get(rawAnomaly, 'confidence')),
startTime: get(rawAnomaly, 'data_start_time'),
endTime: get(rawAnomaly, 'data_end_time'),
plotTime: get(rawAnomaly, 'data_end_time'),
entity: get(rawAnomaly, 'entity'),
});
});
}
return anomalies;
};
export type FeatureDataPoint = {
isMissing: boolean;
plotTime: number;
startTime: number;
endTime: number;
};
export const FEATURE_DATA_CHECK_WINDOW_OFFSET = 2;
export const getFeatureDataPoints = (
featureData: FeatureAggregationData[],
interval: number,
dateRange: DateRange | undefined
): FeatureDataPoint[] => {
const featureDataPoints = [] as FeatureDataPoint[];
if (!dateRange) {
return featureDataPoints;
}
const existingTimes = isEmpty(featureData)
? []
: featureData
.map((feature) => getRoundedTimeInMin(feature.startTime))
.filter((featureTime) => featureTime != undefined);
for (
let currentTime = getRoundedTimeInMin(dateRange.startDate);
currentTime <
// skip checking for latest interval as data point for it may not be delivered in time
getRoundedTimeInMin(
dateRange.endDate -
FEATURE_DATA_CHECK_WINDOW_OFFSET * interval * MIN_IN_MILLI_SECS
);
currentTime += interval * MIN_IN_MILLI_SECS
) {
const isExisting = findTimeExistsInWindow(
existingTimes,
getRoundedTimeInMin(currentTime),
getRoundedTimeInMin(currentTime) + interval * MIN_IN_MILLI_SECS
);
featureDataPoints.push({
isMissing: !isExisting,
plotTime: currentTime + interval * MIN_IN_MILLI_SECS,
startTime: currentTime,
endTime: currentTime + interval * MIN_IN_MILLI_SECS,
});
}
return featureDataPoints;
};
const findTimeExistsInWindow = (
timestamps: any[],
startTime: number,
endTime: number
): boolean => {
// timestamps is in desc order
let result = false;
if (isEmpty(timestamps)) {
return result;
}
let left = 0;
let right = timestamps.length - 1;
while (left <= right) {
let middle = Math.floor((right + left) / 2);
if (timestamps[middle] >= startTime && timestamps[middle] < endTime) {
result = true;
break;
}
if (timestamps[middle] < startTime) {
right = middle - 1;
}
if (timestamps[middle] >= endTime) {
left = middle + 1;
}
}
return result;
};
const getRoundedTimeInMin = (timestamp: number): number => {
return Math.round(timestamp / MIN_IN_MILLI_SECS) * MIN_IN_MILLI_SECS;
};
const sampleFeatureMissingDataPoints = (
featureMissingDataPoints: FeatureDataPoint[],
dateRange?: DateRange
): FeatureDataPoint[] => {
if (!dateRange) {
return featureMissingDataPoints;
}
const sampleTimeWindows = calculateTimeWindowsWithMaxDataPoints(
MAX_FEATURE_ANNOTATIONS,
dateRange
);
const sampledResults = [] as FeatureDataPoint[];
for (const timeWindow of sampleTimeWindows) {
const sampledDataPoint = getMiddleDataPoint(
getDataPointsInWindow(featureMissingDataPoints, timeWindow)
);
if (sampledDataPoint) {
sampledResults.push({
...sampledDataPoint,
startTime: Math.min(timeWindow.startDate, sampledDataPoint.startTime),
endTime: Math.max(timeWindow.endDate, sampledDataPoint.endTime),
} as FeatureDataPoint);
}
}
return sampledResults;
};
const getMiddleDataPoint = (arr: any[]) => {
if (arr && arr.length > 0) {
return arr[Math.floor(arr.length / 2)];
}
return undefined;
};
const getDataPointsInWindow = (
dataPoints: FeatureDataPoint[],
timeWindow: DateRange
) => {
return dataPoints.filter(
(dataPoint) =>
get(dataPoint, 'plotTime', 0) >= timeWindow.startDate &&
get(dataPoint, 'plotTime', 0) < timeWindow.endDate
);
};
const generateFeatureMissingAnnotations = (
featureMissingDataPoints: FeatureDataPoint[]
) => {
return featureMissingDataPoints.map((feature) => ({
dataValue: feature.plotTime,
details: `There is feature data point missing between ${moment(
feature.startTime
).format('MM/DD/YY h:mm A')} and ${moment(feature.endTime).format(
'MM/DD/YY h:mm A'
)}`,
header: dateFormatter(feature.plotTime),
}));
};
const finalizeFeatureMissingDataAnnotations = (
featureMissingDataPoints: any[],
dateRange?: DateRange
) => {
const sampledFeatureMissingDataPoints = sampleFeatureMissingDataPoints(
featureMissingDataPoints,
dateRange
);
return generateFeatureMissingAnnotations(sampledFeatureMissingDataPoints);
};
export const getFeatureMissingDataAnnotations = (
featureData: FeatureAggregationData[],
interval: number,
queryDateRange?: DateRange,
displayDateRange?: DateRange
) => {
const featureMissingDataPoints = getFeatureDataPoints(
featureData,
interval,
queryDateRange
).filter((dataPoint) => get(dataPoint, 'isMissing', false));
const featureMissingAnnotations = finalizeFeatureMissingDataAnnotations(
featureMissingDataPoints,
displayDateRange
);
return featureMissingAnnotations;
};
// returns feature data points(missing/existing both included) for detector in a map like
// {
// 'featureName': data points[]
// }
export const getFeatureDataPointsForDetector = (
detector: Detector,
featuresData: { [key: string]: FeatureAggregationData[] },
interval: number,
dateRange?: DateRange
) => {
let featureDataPointsForDetector = {} as {
[key: string]: FeatureDataPoint[];
};
const allFeatures = get(
detector,
'featureAttributes',
[] as FeatureAttributes[]
);
allFeatures.forEach((feature) => {
//@ts-ignore
const featureData = featuresData[feature.featureId];
const featureDataPoints = getFeatureDataPoints(
featureData,
interval,
dateRange
);
featureDataPointsForDetector = {
...featureDataPointsForDetector,
[feature.featureName]: featureDataPoints,
};
});
return featureDataPointsForDetector;
};
export const getFeatureMissingSeverities = (featuresDataPoint: {
[key: string]: FeatureDataPoint[];
}): Map<MISSING_FEATURE_DATA_SEVERITY, string[]> => {
const featureMissingSeverities = new Map();
for (const [featureName, featureDataPoints] of Object.entries(
featuresDataPoint
)) {
// all feature data points should have same length
let featuresWithMissingData = [] as string[];
if (featureDataPoints.length <= 1) {
// return empty map
return featureMissingSeverities;
}
if (
featureDataPoints.length === 2 &&
featureDataPoints[0].isMissing &&
featureDataPoints[1].isMissing
) {
if (featureMissingSeverities.has(MISSING_FEATURE_DATA_SEVERITY.YELLOW)) {
featuresWithMissingData = featureMissingSeverities.get(
MISSING_FEATURE_DATA_SEVERITY.YELLOW
);
}
featuresWithMissingData.push(featureName);
featureMissingSeverities.set(
MISSING_FEATURE_DATA_SEVERITY.YELLOW,
featuresWithMissingData
);
continue;
}
const orderedFeatureDataPoints = orderBy(
featureDataPoints,
// sort by plot time in desc order
(dataPoint) => get(dataPoint, 'plotTime', 0),
SORT_DIRECTION.DESC
);
// feature has >= 3 data points
if (
orderedFeatureDataPoints.length >= 3 &&
orderedFeatureDataPoints[0].isMissing &&
orderedFeatureDataPoints[1].isMissing
) {
// at least latest 2 ones are missing
let currentSeverity = MISSING_FEATURE_DATA_SEVERITY.YELLOW;
if (orderedFeatureDataPoints[2].isMissing) {
// all the latest 3 ones are missing
currentSeverity = MISSING_FEATURE_DATA_SEVERITY.RED;
}
if (featureMissingSeverities.has(currentSeverity)) {
featuresWithMissingData = featureMissingSeverities.get(currentSeverity);
}
featuresWithMissingData.push(featureName);
featureMissingSeverities.set(currentSeverity, featuresWithMissingData);
}
}
return featureMissingSeverities;
};
export const getFeatureDataMissingMessageAndActionItem = (
featureMissingSev: MISSING_FEATURE_DATA_SEVERITY | undefined,
featuresWithMissingData: string[],
hideFeatureMessage: boolean
) => {
switch (featureMissingSev) {
case MISSING_FEATURE_DATA_SEVERITY.YELLOW:
return {
message: `Recent data is missing for feature${
featuresWithMissingData.length > 1 ? 's' : ''
}: ${featuresWithMissingData.join(
', '
)}. So, anomaly result is missing during this time.`,
actionItem:
'Make sure your data is ingested correctly.' + hideFeatureMessage
? ''
: ' See the feature data shown below for more details.',
};
case MISSING_FEATURE_DATA_SEVERITY.RED:
return {
message: `Data is not being ingested correctly for feature${
featuresWithMissingData.length > 1 ? 's' : ''
}: ${featuresWithMissingData.join(
', '
)}. So, anomaly result is missing during this time.`,
actionItem:
`${DETECTOR_INIT_FAILURES.NO_TRAINING_DATA.actionItem}` +
hideFeatureMessage
? ''
: ' See the feature data shown below for more details.',
};
default:
return {
message: '',
actionItem: '',
};
}
};
export const filterWithHeatmapFilter = (
data: any[],
heatmapCell: HeatmapCell | undefined,
isFilteringWithEntity: boolean = true,
timeField: string = 'plotTime'
) => {
if (!heatmapCell) {
return data;
}
if (isFilteringWithEntity) {
data = data
.filter((anomaly) => !isEmpty(get(anomaly, 'entity', [])))
.filter(
(anomaly) => get(anomaly, 'entity')[0].value === heatmapCell.entityValue
);
}
return filterWithDateRange(data, heatmapCell.dateRange, timeField);
};
export const getTopAnomalousEntitiesQuery = (
startTime: number,
endTime: number,
detectorId: string,
size: number,
sortType: AnomalyHeatmapSortType
) => {
return {
size: 0,
query: {
bool: {
filter: [
{
range: {
[AD_DOC_FIELDS.ANOMALY_GRADE]: {
gt: 0,
},
},
},
{
range: {
data_end_time: {
gte: startTime,
lte: endTime,
},
},
},
{
term: {
detector_id: detectorId,
},
},
],
},
},
aggs: {
[TOP_ENTITIES_FIELD]: {
nested: {
path: ENTITY_FIELD,
},
aggs: {
[TOP_ENTITY_AGGS]: {
terms: {
field: ENTITY_VALUE_PATH_FIELD,
size: size,
...(sortType === AnomalyHeatmapSortType.SEVERITY
? {
order: {
[TOP_ANOMALY_GRADE_SORT_AGGS]: SORT_DIRECTION.DESC,
},
}
: {}),
},
aggs: {
[TOP_ANOMALY_GRADE_SORT_AGGS]: {
reverse_nested: {},
aggs: {
[MAX_ANOMALY_AGGS]: {
max: {
field: AD_DOC_FIELDS.ANOMALY_GRADE,