Skip to content
SlateGitOrgPublic

About

Leak alarms on district night flow from a CUSUM whose threshold is set for one false alarm per district per year, calibrated by simulation and checked against Siegmund's formula.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

1 Commit

Folders and files

Repository files navigation

nightflow

CI

nightflow

nightflow raises leak alarms on the night flow of district metered areas (DMAs). Inlet-meter readings are upserted by district and timestamp, closed into one 02:00-04:00 night-flow value per district on a watermark, standardised against a guarded robust baseline, and fed to a one-sided CUSUM whose threshold h is chosen so that the expected time between false alarms is 365 nights. h is found by Monte Carlo, checked against Siegmund's closed-form approximation, and re-derived on bootstrapped residuals of an in-control fleet because the baseline's own estimation error makes real residuals wider and more correlated than N(0, 1). A Shewhart detector and a set of injected leaks on a seeded synthetic fleet show what the cumulative detector buys. All data is synthetic.

The problem

A water utility splits its network into DMAs whose inlet meters report flow every 15 minutes. A new leak shows up as a step in the night flow, when legitimate demand is lowest, but each district has its own level and noise, so a fixed "20% over last month" rule floods small noisy districts with false alarms and misses modest leaks in large ones. Every false alarm sends a crew out for a night, so the false-alarm rate has to be a design input, and the pipeline has to cope with meter resends, gaps, late deliveries and planned network operations such as mains flushing.

How it works

flowchart LR
    A["Meter readings<br/>(dma, ts, seq, value)"] --> B["Upsert by (dma, ts)<br/>highest seq wins"]
    B --> C["Night window 02:00-04:00<br/>in the district's UTC offset"]
    C -->|"watermark passes 04:00 + 6 h"| D["Night value<br/>complete if 6 of 8 readings"]
    D --> E["Guarded robust baseline<br/>median, MAD x 1.4826<br/>28 nights ending 21 nights ago"]
    E --> F["Residual z"]
    F --> G["One-sided CUSUM<br/>S = max(0, S + z - k)<br/>alarm when S > h"]
    F --> H["Shewhart<br/>alarm when z > c"]
    G --> I["Leak alarms<br/>change night, size estimate"]
    G -.->|"S below h/2 only"| E
    O["Operations calendar"] -.->|"hold S"| G
    I --> J["Scored against<br/>injected leaks"]
    H --> J
    K["Calibration<br/>Monte Carlo ARL0 = 365<br/>Siegmund check<br/>block bootstrap"] -->|"h"| G
Loading
  • ingest.py keeps readings keyed by (district, timestamp); the highest sequence number wins, so resends and corrections are safe in any arrival order. A night is the 02:00-04:00 window in the district's fixed UTC offset (no time-zone database). It closes when that district's watermark passes 04:00 plus 6 hours; later readings are counted and dropped. A night with fewer than 6 of its 8 readings is incomplete, and a night with no readings is emitted as an empty incomplete night.
  • baseline.py takes the median and MAD x 1.4826 of the accepted nights in [t - 48, t - 21], a 28-night window that ends 21 nights before the current night, so a new leak cannot enter its own baseline. A night is accepted only if the CUSUM statistic after it is below h/2. When too few nights qualify, the last good estimate is kept.
  • cusum.py holds S = max(0, S + z - k), the alarm rule (S > h, strictly), the change-night estimate (the first night after the last zero of S) and the leak-size estimate k + S / n sigmas over the n nights since the change. S is held unchanged on incomplete nights and on nights in the operations calendar, and reset when an alarm is acknowledged.
  • calibrate.py estimates the average run length by vectorised Monte Carlo under N(0, 1) or under a moving-block bootstrap of observed residuals, evaluates Siegmund's approximation ARL = (exp(-2Db) + 2Db - 1) / (2D^2) with b = h + 1.166, D = mu - k, and bisects on h.
  • evaluate.py calibrates on an in-control twin fleet (a different seed, nothing injected), scores detection delay per injected leak against the Shewhart detector, and counts false alarms with a Clopper-Pearson interval.
  • checkpoint.py snapshots per-district state (baseline window, S, open alarm, last closed night) and the ingest buffers (open nights, watermarks) to JSON.
  • gen.py is the seeded fleet generator: 40 districts x 365 nights, 15-minute readings from 00:00 to 05:45 local time (about 354,000 deliveries), base night flow 2-40 L/s, night-to-night noise CV 4-12% plus 5% per-reading noise, weekend nights 3% higher, 1% of readings resent (half with corrected values), 2% delivered up to 3 hours late. Injected: 12 leaks of 0.5, 1, 2 and 3 sigma (three each, 90 nights, starting after night 60), two 5-night meter outages, and two nights of planned mains flushing listed in data/ops_calendar.csv. The first 49 nights are warm-up with no alarms.

Quick start

python3 -m venv .venv && . .venv/bin/activate
pip install -e ".[dev]"
nightflow calibrate --k 0.5 --arl0 365
nightflow run --seed 21
nightflow evaluate --seed 21
pytest

nightflow gen --seed 21 --out data rewrites the three small committed data files (dmas.csv, ops_calendar.csv, injected_leaks.csv). run and evaluate take --h to skip calibration, and run --auto-ack acknowledges every alarm immediately so that a district can alarm again.

Example output

nightflow calibrate --k 0.5 --arl0 365

CUSUM k=0.5, target ARL0=365 nights, 20000 runs per estimate, seed 0
Monte Carlo h : 4.082  (ARL0 at this h: 365.6)
Siegmund h    : 4.074  (ARL0 at this h: 365.0)
Shewhart c    : 2.777  (same false-alarm rate per night)

ARL1 in nights at Monte Carlo h=4.082, sustained shift from S=0
shift (sigma)  Monte Carlo  Siegmund
          0.5         27.4      27.5
            1          8.5       8.5
          1.5          4.8       4.7
            2          3.4       3.3
          2.5          2.7       2.5
            3          2.2       2.0

For N(0, 1) residuals the Monte Carlo and closed-form thresholds agree to 0.01. The closed form is within 0.1 nights of the simulation up to a 1.5-sigma shift and runs low for larger shifts, where the run is only a few nights long.

nightflow evaluate --seed 21

Fleet seed 21: 40 districts, 365 nights
CUSUM k=0.5 h=7.194: block-bootstrap ARL0=365 on the in-control twin fleet (seed 1021, 12640 residuals, block 28); Siegmund h for N(0,1) is 4.074
Shewhart c=3.808: the same in-control rate on the twin's residuals; c=2.777 is the N(0,1) value for one alarm a year

   dma  size (sigma)  start night  CUSUM delay  Shewhart c=3.81  Shewhart c=2.78
DMA-01             2           71            6               23               13
DMA-13           0.5           74           10              90*              90*
DMA-03             2           77            7              90*               44
DMA-16             1           82           30              90*                4
DMA-34           0.5          118           21               33               21
DMA-24             3          124            3                2                1
DMA-25             1          146            9              90*                3
DMA-35             1          147            9              90*                5
DMA-26             2          213            1                6                1
DMA-15             3          253            2                1                1
DMA-30           0.5          257           10              90*                7
DMA-17             3          260            6                9                2
delay in nights from the leak's first night; * = not detected in 90 nights
total delay: CUSUM 114, Shewhart c=3.81 614, Shewhart c=2.78 192

False alarms over 10070 in-control district-nights:
  CUSUM    33 observed, 27.6 expected at ARL0=365
  99% Clopper-Pearson interval for the CUSUM rate: 0.73 to 1.84 per district-year (design 1.00)
  Shewhart c=3.81: 35 observed
  Shewhart c=2.78: 143 observed

The CUSUM threshold used for detection is 7.19, not 4.07, because the residuals the baseline produces are not N(0, 1). nightflow run --seed 21 lists the first alarm of each district (an unacknowledged alarm stays open):

Fleet seed 21: 40 districts, 365 nights, 353597 deliveries; k=0.5 h=7.194
27 alarms
11 of 12 injected leaks alarmed inside their 90-night window
   dma  alarm night  change night  nights  shift (sigma)  shift (L/s)
DMA-06   2025-03-01    2025-02-19      11           1.27         2.29
DMA-39   2025-03-08    2025-02-24      13           1.08         1.24
DMA-01   2025-03-18    2025-03-13       6           1.74         1.16
DMA-03   2025-03-25    2025-03-18       8           1.51         4.10
DMA-13   2025-03-25    2025-03-16      10           1.32         5.36
DMA-33   2025-03-28    2025-03-05      24           0.81         1.26
DMA-08   2025-04-06    2025-03-28      10           1.33         0.18
DMA-18   2025-04-17    2025-04-06      12           1.28         0.19
DMA-04   2025-04-20    2025-04-15       6           1.76         0.24
...
DMA-30   2025-09-24    2025-09-10      15           1.04         0.31
DMA-09   2025-10-01    2025-09-19      13           1.08         2.24
DMA-37   2025-11-21    2025-11-17       5           2.07         0.42

Eleven of the 12 injected leaks raise an alarm inside their own 90-night window. DMA-26 does not: with one open alarm per district, a false alarm on 2025-07-26 (night 206, before its leak starts on night 213) is still open and shadows the leak. The other 16 alarms are false alarms in districts without a leak or before the leak. With run --auto-ack, or evaluate, which acknowledges false alarms, all 12 leaks are caught.

Design decisions

  1. Calibrate h on residuals, not on N(0, 1). The Gaussian answer is h = 4.07 for one false alarm a year, but a baseline built from 28 noisy nights has its own error, which widens the residuals (standard deviation 1.19 on the twin fleet, against 1 for N(0, 1)) and carries over from night to night. An iid bootstrap (h = 6.39) still gave 50 false alarms where the design expects 27.6 on the evaluation fleet; a moving-block bootstrap (blocks of 28 nights, the baseline's memory) gives h = 7.19 and 33. The block length of 28 was chosen after the iid bootstrap had failed on the evaluation fleet, so the twin-fleet calibration is partly tuned to the fleet it is scored on, and the 33 against 27.6 is not a fully out-of-sample check. The cost is a higher threshold: every shift takes longer to accumulate to 7.19 than to 4.07.
  2. A twin fleet for calibration. h comes from an in-control fleet generated with a different seed, so the evaluation fleet's false alarms are a test of the calibration and not a restatement of it. Because the baseline only learns from nights with S < h/2, the residuals depend on h; the calibration runs three passes, moving the gate halfway to each result.
  3. Guard gap plus refusal to learn from suspicious nights. The baseline window ends 21 nights back and skips nights with a high statistic, so a slow leak is not absorbed before it is caught. The price is that a long unacknowledged leak starves the window; the baseline then keeps its last good estimate instead of learning the leak. The guard only holds while S stays high: acknowledging a true alarm resets S to 0, the leak's nights then pass the S < h/2 gate and, after the 21-night guard gap, the baseline absorbs the leak. So evaluate acknowledges false alarms at once but leaves an alarm that falls inside a leak window open (the crew has confirmed a leak that is not yet repaired). Acknowledging everything would hide the 2-sigma leak in DMA-03 from Shewhart for all 90 nights, because Shewhart shares the baseline, and would turn the comparison into an artifact of the acknowledgement rule.
  4. Holds instead of imputation. Incomplete nights and calendar nights freeze S and stay out of the baseline. A flushing spike of 6 sigma on two nights would otherwise raise an alarm (a test runs the same district without the calendar to show it).
  5. Idempotent upsert, event-time windows. Last sequence number wins and nights close on a per-district watermark, so the output does not depend on arrival order within the lateness bound. Checkpoints include the open night buffers and the watermarks, so a restored pipeline continues from the cut without the earlier readings; replaying the whole log from the start also works (closed nights are skipped, open nights are idempotent upserts).
  6. A configured weekend factor. Weekend nights run 3% above weekdays in the generator and Params.weekend_uplift divides it out before the baseline. In a deployment this factor would be estimated across the fleet from the warm-up period.

Testing

pytest runs 70 tests in about 30 seconds, offline. They cover hand-computed night-flow and CUSUM fixtures, Siegmund and Monte Carlo ARL, the calibrated threshold and ARL1 bands, the Shewhart constant, ingest edge cases (offsets, lateness, resends in either order, gaps), property tests (arrival order, CUSUM path), and end-to-end checks on the seed-21 fleet: closed nights equal the generator's truth, every 2- and 3-sigma leak is alarmed within 7 nights, CUSUM total delay is below that of a Shewhart detector with the same false-alarm rate, each leak alarms inside its own window, false alarms are within a factor of 2 of the design, holds during outages and flushing, a checkpoint cut at night 180 continues from the cut (and, separately, by replaying the log) to the same alarm list, and shuffled deliveries with 1% duplicates give identical alarms.

Limits worth knowing: the false-alarm check counts one fleet-year, so its interval is wide (see the Clopper-Pearson line above); the Shewhart comparison is scored twice, because the two thresholds answer different questions. c = 2.777 is the N(0, 1) value for one alarm a year but gives 143 false alarms against the CUSUM's 33 on these heavier-tailed residuals, so it is not a matched comparison: it is quicker than the CUSUM on 7 of the 11 leaks both detect (102 nights in total against 104), and the CUSUM's lower total (114 against 192) comes from DMA-13, the 0.5-sigma leak Shewhart never sees. The headline column uses the 1 - 1/365 quantile of the twin fleet's in-control residuals (c = 3.81, 35 false alarms), the same false-alarm rate as the CUSUM; there Shewhart misses six leaks and the total delay is 614 against 114. The CUSUM's advantage is real only at a matched false-alarm rate, and it is largest on the 0.5- to 1-sigma leaks; the generator's noise is independent between nights, which real demand is not.

Two caveats on the evidence. First, the acceptance check that every 2- and 3-sigma leak is alarmed within 7 nights has no margin: DMA-03 (2 sigma) is detected on exactly its seventh night with h = 7.19, a value that comes from a Monte Carlo run, and the delay stays at 7 only for h between 7.0 and 8.0, so a slightly different calibration would fail the test. Second, the Clopper-Pearson interval treats the 10,070 district-nights as independent Bernoulli trials, although the residuals are serially correlated and alarms are acknowledged runs; the interval is therefore probably narrower than the true uncertainty, and the 0.73 to 1.84 range should be read as a lower bound on it.

Project layout

src/nightflow/
  config.py      offsets, operations calendar, parameters
  ingest.py      upsert, night windows, watermark closing
  baseline.py    guarded robust baseline
  cusum.py       CUSUM, change and size estimates
  shewhart.py    comparison detector
  calibrate.py   Monte Carlo ARL, Siegmund, bisection, block bootstrap
  pipeline.py    ingest -> baseline -> detectors, checkpoint restore
  checkpoint.py  JSON snapshots
  gen.py         seeded fleet generator
  evaluate.py    twin calibration, delay and false-alarm scoring
  cli.py         calibrate / run / evaluate / gen
data/            dmas.csv, ops_calendar.csv, injected_leaks.csv (seed 21)
tests/

License

MIT

About

Leak alarms on district night flow from a CUSUM whose threshold is set for one false alarm per district per year, calibrated by simulation and checked against Siegmund's formula.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages