Digital-twin smart-grid monitor — VoltHacks 2026 submission.
GridSense simulates a neighborhood of 40 IoT smart meters streaming telemetry over HTTP, detects anomalies (theft, faults, spikes) in real time with documented statistical detectors, and renders them on an operator console: a green/amber/red grid map, per-meter 24 h drill-down charts, and a live alert feed. A replay mode re-runs a full synthetic day at 60x speed with commentary, so judges can watch every detector fire in minutes.
No physical hardware is required — the simulator is a first-class digital twin with researched load-curve profiles, so the ingest→detect→alert→UI pipeline is byte-identical to what real AMI meters would drive.
┌───────────────────────────┐ HTTP POST /ingest (batch, every 2 s)
│ simulator/ │ ─────────────────────────────────────┐
│ 40 VirtualMeters │ ▼
│ ├ household ×24 │ ┌──────────────────────────────────┐
│ ├ shop ×10 (1 PV) │ │ server/ (FastAPI + uvicorn) │
│ └ streetlight×6 │ │ │
│ fault injectors: │ │ POST /ingest ──► SQLite store │
│ spike / gradual drift / │ │ (72 h ring │
│ flatline / reverse-flow │◄─commands──│ GET /api/* ──► buffer/meter) │
└───────────────────────────┘ poll │ │
▲ │ analyzer loop (2 s tick): │
│ dashboard buttons │ detection/*.evaluate() │
│ (remote fault console) │ │ │
│ │ ▼ │
┌──────┴───────────────────┐ │ 6 statistical detectors: │
│ dashboard/ (vanilla JS) │◄── polls ────│ spike · drift_high/low · │
│ NOC console v2: │ │ flatline · reverse_flow · │
│ grid map green/amber/ │ │ voltage_sag (IEEE 1159) · │
│ red + heat-strip tiles │ │ phase_imbalance (NEMA MG-1) │
│ Chart.js drilldown │ │ │ │
│ alert feed + workflow │ │ ▼ │
│ ACK→INVESTIGATE→ │ │ Alerter (cooldown dedup) │
│ RESOLVE + SLA timers │ │ ├ alerts.log (JSON lines) │
│ feeder/substation tree │ │ ├ webhook stub (env var) │
│ WebAudio critical beep │ │ └ /api/alerts feed │
│ shift-handover export │ │ │
└──────────△───────────────┘ │ ┌────────────────────────────┐ │
│ GET /api/cases/{id}: │ │ ML ensemble │ │
│ evidence chain · raw │ │ [GRIDSENSE_ML=1 gate, OFF] │ │
│ readings · score │ │ robust-z (median/MAD) + │ │
│ timeline · similar cases · │ │ STL-lite seasonal baseline │ │
│ auto loss estimate in Rs │ │ + spike + drift evidence, │ │
└─────────────────────────────►│ │ logistic fuse p=sigmoid(·) │ │
│ │ explainable reasons · │ │
│ │ trained F1 0.98 · adaptive │ │
│ │ per-meter thresholds │ │
│ └──────────────▲─────────────┘ │
│ │ reliability │
│ │ multipliers │
│ ┌──────────────┴─────────────┐ │
│ │ Case File service │ │
│ │ /api/cases/{id}: evidence │ │
│ │ chain · raw readings · │ │
│ │ detector-score timeline · │ │
│ │ similar historical cases · │ │
│ │ auto loss estimate in Rs · │ │
│ │ outcome: confirmed_theft / │ │
│ │ faulty_meter / false_alarm │ │
│ └────────────────────────────┘ │
└──────────────────────────────────┘
reliability feedback: every resolved case outcome retunes per-detector
multipliers back into the ML ensemble weights (ensemble_weights.json),
so detector weighting sharpens as field results accumulate.
replay/replay.py — streams a deterministic synthetic day into the same
/ingest endpoint at 60x speed, announcing scripted faults on the banner API.
pip install -r requirements.txt
# Terminal 1 — API + dashboard + analyzer
python -m uvicorn server.main:app --port 8000
# Terminal 2 — live telemetry from the 40-meter fleet (30x time compression)
python -m simulator.client --scenario demo
# Terminal 3 — open the operator console
start http://localhost:8000 # (any browser)Replay mode replaces Terminal 2:
python -m replay.replay # yesterday's synthetic day @ 60x (24 min)
python -m replay.replay --start-hour 17 # just the evening peak window--scenario demo schedules four faults automatically; the dashboard's
fault console buttons queue the same injections remotely:
| Wall time | Fault | Meter | Expected alert |
|---|---|---|---|
| t+90 s | sudden 8x spike | HH-03 | CRITICAL spike within ~2 s |
| t+240 s | meter freezes (flatline) | SL-02 | CRITICAL flatline after 15 identical readings |
| t+420 s | gradual upward drift begins (4 h ramp to 2.2x) | SH-04 | WARNING drift_high once the 30-min window mean clears the 1.6 ratio |
| t+600 s | reverse energy flow (non-PV theft signature) | HH-11 | CRITICAL reverse_flow_theft |
Also try: click any meter card → drilldown chart → press REV FLOW, then
watch SH-07 (the rooftop-PV shop) show benign INFO solar_export for
comparison.
- Z-score spike detector —
z = (x_t − μ_window)/σ_windowover a trailing 60-read window; fires above z=4 and an absolute jump floor of 1 kW (sub-kilowatt steps are routine appliance switching; field AMI alarm configs filter these). σ floored at 5 W; cold-start guard. - Rolling-baseline drift detector — ratio-of-means test
R = μ(recent 30 min)/μ(previous 24 h); R > 1.6 → creeping fault, R < 0.45 → sustained under-registration, the classic meter-tamper/bypass signature in NTL literature (raised CRITICAL). Skips baselines < 25 W where ratios are meaningless. - Flatline watchdog — 15 bit-identical consecutive readings = frozen measurement element. Threshold-free by design: real loads always carry noise, so exact equality has zero false positives and catches meters frozen at plausible values.
- Reverse-flow theft detector — net flow < −5 W on a non-PV service = wiring reversal/bypass suspect (CRITICAL); identical reading on the PV site is logged INFO as benign export.
All detections pass through a per-(meter, kind) cooldown (300 grid-s)
before reaching operators; alerts persist to SQLite, alerts.log
(JSON lines), and a webhook stub (GRIDSENSE_WEBHOOK=http://...).
Live mode: each meter emits one reading per simulated minute every 2 wall seconds (30x compression — a simulated day streams past in 48 min). Replay mode pushes one simulated minute per second (60x, full day in 24 min) using the same fleet code anchored to yesterday's date, with RNG seeding making it deterministic. Detector windows are count-based, so they behave identically under either compression. The server trusts device/grid timestamps (MDMS-style) and keeps a 72 h ring buffer per meter.
Verified against literature (sources below): household curves have night setback ~130–170 W and a dominant early-evening peak; small-commercial load follows operating hours with overnight refrigeration baseline and lighter weekends; streetlight circuits are zero by day, ON near dusk with late-night curfew dimming; reverse energy-flow flags and under-registration are canonical AMI tamper indicators while PV export makes the same sign benign.
Engineering assumptions (not directly verifiable online, chosen conservatively):
exact hourly anchor values (kW tables in simulator/profiles.py);
streetlight dusk/dawn fixed times (no astronomical calculation);
appliance-burst rate/amplitude (Poisson λ≈10/day households, 250–800 W);
per-meter scale heterogeneity U(0.6, 1.6); epoch-day weekend mapping;
8x spike magnitude and 2.2x drift target chosen to sit clearly inside
detector sensitivity ranges.
Sources: German WPuQ household dataset (Sci Data / PMC8847370); SCE 160k-home residential load study (Applied Energy 366, 2024); EIA Hourly Grid Monitor load-shape articles; UK half-hourly small-business usage benchmarks (retail 15–30 MWh/yr); Xylem/Sensus "Identifying Electric Meter Tampering" (reverse-flow flags, dead meters); Awesense UC48 AMI flag analysis; Northeast Group "Emerging Markets Smart Grid: Outlook 2015" (global theft $89.3B/yr — commonly misattributed to EPRI, see docs/RESEARCH.md §2); US NTL ~$1.6–6B/yr (Deloitte 2013; Smith 2004). Full citation audit: docs/RESEARCH.md · docs/CITATIONS.bib.
python -m pytest tests/ -q # 52 passed (see breakdown below)tests/test_detectors.py(19): every detector against hand-crafted series — fires/no-fires pairs, severity boundaries, cold-start guards, solar-awareness, cooldown dedup, sink behavior.tests/test_simulator.py(13): fleet composition, research-verified curve-shape invariants (evening>morning>night, shop plateau, curfew dim), seed determinism, each injector's exact math, command routing.tests/test_server.py(12): ingest validation, ring-buffer retention, end-to-end spike + reverse-flow detection through the real SQLite + analyzer path, status/staleness derivation, command queue exactly-once, banner API.
simulator/ profiles.py meters.py faults.py client.py
detection/ detectors.py alerts.py
server/ main.py db.py analyzer.py
dashboard/ index.html app.js styles.css vendor/chart.umd.js (vendored)
replay/ replay.py replay_clock.py
tests/ test_detectors.py test_simulator.py test_server.py
- 0:00 — problem: $89B/yr stolen or lost electricity; utilities fly blind between truck rolls.
- 0:20 — architecture walkthrough (diagram above), digital-twin-first rationale.
- 0:50 — live dashboard tour: 40 meters, profiles, drill-down sparkline.
- 1:20 — demo script table: inject spike → red pulse + CRITICAL alert in the feed.
- 2:00 — flatline + reverse-flow theft; contrast with benign PV export on SH-07.
- 2:30 — replay mode at 60x with commentary banner; detectors fire on schedule.
- 2:50 — roadmap: MQTT ingest, IsolationForest ensemble, transformer-area aggregation.
- ML anomaly ensemble (
detection/ml_anomaly.py, gated behindGRIDSENSE_ML=1): rolling robust-z on median/MAD, STL-lite seasonal baseline scored against a fixed reference day, plus spike and drift evidence, fused by a logistic model trained offline on synthetic fault injection (scripts/train_ensemble.py) — held-out F1 0.98 — with adaptive per-meter thresholds and an explainable component breakdown in every alert. - NOC console v2: acknowledge → investigate → resolve workflow with audit trail and SLA timers, feeder/substation tree, heat-strip tiles view, WebAudio critical beep, and shift-handover markdown export.
- Theft Case File (
GET /api/cases/{id}): evidence chain, raw readings, detector-score timeline, similar historical cases, automatic loss estimate in Rs, and recorded outcomes (confirmed_theft/faulty_meter/false_alarm) that feed a detector-reliability loop back into the ensemble weights (GET /api/detector-reliability) — the detectors retune themselves on field results. - Impact model (docs/IMPACT.md): tariff Rs 7.5/kWh, inspection cost Rs 1,500, diverted-load heuristics per alert kind, and break-even precision math (p* = 1500/(V+1500) ≈ 27 %) scaling to a 40,000-meter town projection of Rs 9.9M–72.8M/yr (expected ≈ Rs 2.96 crore).