Guide
1. Every detector warms up first
A detector needs a little history before it knows what normal looks like. Until then
verdict.ready is false and it never raises an alarm, so the first readings of a new sensor
cannot page anyone.
const detector = zscore({ warmup: 20 });
const verdict = detector.update(reading);
if (verdict.ready && verdict.anomaly) page(verdict);
2. Do not learn from the anomaly
A detector that keeps learning from what it flags will slowly accept a leak as the new normal. By default
Nazar leaves flagged readings out of its baseline. Set adapt: 'always' only when a lasting
change should become the new normal.
cusum(); // adapt: 'normal-only', keeps reporting the leak
cusum({ adapt: 'always' }); // follows the leak and goes quiet
3. Survive a cold start
In a serverless function every invocation starts from nothing. Save the snapshot after each reading and
restore it next time. Restoring is exact: the restored detector continues as if it had never stopped.
import { cusum, restore } from 'nazar-js';
const saved = await kv.get('detector');
const detector = saved ? restore(JSON.parse(saved)) : cusum();
const verdict = detector.update(reading);
await kv.put('detector', JSON.stringify(detector.snapshot()));
4. Choose thresholds with real numbers
nazar-js/eval scores a detector the way an operator feels it: by events, not readings. A leak
that lasts an hour is one event, caught or missed.
import { evaluate } from 'nazar-js/eval';
import { waterFlowWithLeak } from 'nazar-js/synth';
const data = waterFlowWithLeak();
const flags = data.values.map(value => detector.update(value).anomaly);
evaluate(flags, data.labels, { tolerance: 10 });
// { precision, recall, f1, meanDelay, falseAlarms }
5. Combine detectors
Pair a spike detector with a shift detector, and wait for a few anomalous readings in a row before you
wake anyone up.
import { cusum, ensemble, hampel, persist } from 'nazar-js';
const watch = persist(ensemble([hampel(), cusum()], { mode: 'any' }), { min: 3 });