nazar

A TypeScript library · zero dependencies · MIT

Keep an eye on your streams.

Nazar spots the wrong reading in a live sensor stream, one value at a time, in constant memory. It catches spikes, slow leaks, drift, stuck sensors and readings that are wrong for the time of day. Its state is plain JSON, so it survives a serverless cold start.

npm i nazar-js

Not on npm yet. Until the first release, install from the release tarball (see the README).

FLOW · main line · L/min live
    A simulated flow sensor watched by ensemble([hampel(), cusum()]). Bursts and slow leaks are injected every few seconds.

    Pick the right detector

    No single test catches everything. A spike detector misses a slow leak; a shift detector is slow to notice a spike. Each one below is shown on the kind of trouble it was made for, with the readings it flagged ringed in red.

    Also included
    range({ min, max }) Physically impossible readings: a negative flow, a humidity of 140%.
    rateOfChange({ maxDelta }) Impossible jumps between readings, per reading or per second for irregular sampling.
    ensemble([...]), persist(d) Combine detectors by any, all or majority vote; raise the alarm only after several anomalous readings in a row.

    Playground

    Pick a scenario and a detector, move the sliders, and see what it catches. Click the chart to add a spike of your own.

    1 reading
    • Readings
    • What the detector expected
    • Where the real anomalies are
    • Flagged by the detector

    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 });

    API at a glance

    Export What it is
    zscore, hampel, cusum, pageHinkley, seasonal, flatline, range, rateOfChange Detector factories. Each returns a Detector.
    detector.update(value, timestamp?) Judges one reading and returns a Verdict: anomaly, score, ready, and when available expected, lower, upper, reason.
    detector.snapshot(), restore(snapshot) Plain-JSON state, and a validating rebuild from it.
    ensemble(detectors, { mode }), persist(detector, { min }) Combinators, which are detectors themselves.
    nazar-js/synth Seeded signals, anomaly injectors and four labelled scenarios.
    nazar-js/eval evaluate(flags, labels): event-based precision, recall, F1 and detection delay.