forked from PinSpace-Org/GistPin
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanomaly.ts
More file actions
48 lines (43 loc) 路 1.14 KB
/
Copy pathanomaly.ts
File metadata and controls
48 lines (43 loc) 路 1.14 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
export type AnomalySeverity = 'warning' | 'critical';
export interface Anomaly {
chartId: string;
label: string;
current: number;
average: number;
pctChange: number;
severity: AnomalySeverity;
direction: 'spike' | 'drop';
}
/** Compute rolling average of an array */
export function rollingAverage(values: number[]): number {
if (values.length === 0) return 0;
return values.reduce((sum, v) => sum + v, 0) / values.length;
}
/**
* Detect anomalies in a series.
* 卤30% from average = warning, 卤50% = critical.
*/
export function detectAnomalies(
chartId: string,
labels: string[],
values: number[],
): Anomaly[] {
const avg = rollingAverage(values);
if (avg === 0) return [];
return values.flatMap((value, i) => {
const pct = ((value - avg) / avg) * 100;
const abs = Math.abs(pct);
if (abs < 30) return [];
return [
{
chartId,
label: labels[i] ?? `Point ${i}`,
current: value,
average: Math.round(avg),
pctChange: Math.round(pct * 10) / 10,
severity: abs >= 50 ? 'critical' : 'warning',
direction: pct > 0 ? 'spike' : 'drop',
},
];
});
}