Add implementation plan for MA7D_DROP energy analysis

Four TDD tasks: CSV loading, causal analysis, periods/summary/CLI,
plotly report. Code validated against real data in a prototype.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
maximeandClaude Opus 5.5 committed 2026-10-09 18:38:50 +02:00
1 parent e07656902a
commit 55ec0499bb
1 file changed
+780
@@ -0,0 +1,780 @@
# Analyse énergétique MA7D_DROP : plan d'implémentation
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal :** un script Python qui calcule, à chaque horodatage d'une station, l'écart entre la moyenne de `BusVoltage` sur 7 jours et son maximum des 30 jours précédents. Il signale une anomalie énergétique sous −0,2 V et produit un JSON, un résumé texte et un graphique HTML.
**Architecture :**
- `src/energy_check.py`, bibliothèque standard uniquement (embarquable), dans cet ordre : chargement des CSV par station, analyse causale `run()`, regroupement en périodes, résumé texte, ligne de commande.
- `src/energy_plot.py` importe `energy_check` et trace le résultat avec plotly (poste de dev, `.venv`).
- Tests en `unittest`, sur les données réelles de `data/` et `vermont/` uniquement.
**Tech Stack :** Python 3.14 (bibliothèque standard), plotly 7.1.0 installé dans `.venv/`, `unittest`.
**Spec :** `docs/superpowers/specs/2026-10-09-energy-ma7d-design.md`
## Global Constraints
- `src/energy_check.py` : **bibliothèque standard uniquement** (cible : système embarqué de la station). Ni pandas, ni numpy.
- `src/energy_plot.py` : plotly autorisé. Il s'exécute avec `.venv/bin/python`.
- Constantes, valeurs exactes de la spec §4.2 : `WINDOW_H = 168`, `REF_H = 720`, `MIN_COVERAGE = 0.8`, `MIN_REF_POINTS = 24`, `THRESHOLD_V = -0.2`.
- Causalité : le point t n'utilise que les données ≤ t.
- Vocabulaire du résumé : `consistent with` (anomalie), `not observed` (aucune), `insufficient evidence` (pas assez de données). Pas de pseudo-probabilité.
- Tests : **données réelles uniquement** (`data/`, `vermont/`). Ne jamais générer de CSV simulé ni de générateur de scénarios. Seules les copies de fichiers réels sous un autre nom sont permises.
- Ne pas modifier `src/__main__ (3).py` ni `architecture.drawio`.
- Messages et documents en français. Messages de commit en anglais, avec la ligne `Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>`.
- Travailler sur la branche `energy-ma7d`, déjà créée. Ne commiter que les fichiers de la tâche : `data/`, `doc/`, `vermont/`, `src/__main__ (3).py` et `architecture.drawio` restent non suivis.
## Review Focus
1. **Historique trop court (< 7 jours) ou `BusVoltage` sans aucune ligne** : tous les points sont UNKNOWN (ou il n'y a aucun point), le résumé dit `insufficient evidence`, rien ne plante. Testé en Task 2 et Task 3.
2. **Horodatages hors de la grille horaire** (export à 15 min, horodatages avec des secondes) : `ValueError` explicite plutôt qu'une moyenne fausse et silencieuse. Testé en Task 2.
3. **Le même fichier passé deux fois** (par son dossier et par son chemin) n'est pas un doublon. Deux fichiers différents pour la même station et la même métrique lèvent `ValueError`. Testé en Task 1.
4. **CSV au nom non reconnu dans un dossier scanné** : il est ignoré avec un message sur stderr, et les autres stations sont traitées. Testé en Task 1.
5. **Station sans `BusVoltage`** (températures seules) : elle est ignorée avec un message, sans plantage. Testé en Task 3.
## File Structure
| Fichier | Rôle | Tâches |
|---|---|---|
| `src/energy_check.py` | chargement CSV, analyse `MA7D_DROP`, périodes, résumé, ligne de commande (bibliothèque standard) | 1, 2, 3 |
| `tests/test_energy_check.py` | tests de régression sur données réelles | 1, 2, 3 |
| `.gitignore` | ajout de `out/` | 3 |
| `src/energy_plot.py` | graphique HTML plotly | 4 |
| `tests/test_energy_plot.py` | tests de fumée du graphique, ignorés sans plotly | 4 |
Commande de test, valable à chaque étape, depuis la racine du dépôt :
```bash
python3 -m unittest discover -s tests -v
```
---
### Task 1 : chargement des CSV par station
**Files :**
- Create : `src/energy_check.py`
- Create : `tests/test_energy_check.py`
**Interfaces :**
- Consumes : rien.
- Produces :
- `parse_name(path: str) -> tuple[str, str] | None` : renvoie `(station, metric)` ;
- `load_csv(path) -> dict[datetime, float | None]` : datetimes UTC « aware » ;
- `load_stations(paths: list[str]) -> dict[str, dict[str, dict[datetime, float | None]]]` : renvoie `{station: {metric: série}}` et lève `ValueError` sur un doublon.
- [ ] **Step 1 : écrire les tests qui échouent**
Créer `tests/test_energy_check.py` :
```python
"""Tests de régression de l'analyse MA7D_DROP, sur données réelles uniquement (spec §9)."""
import functools
import io
import shutil
import sys
import tempfile
import unittest
from contextlib import redirect_stderr
from datetime import datetime, timezone
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "src"))
import energy_check as ec # noqa: E402
DATA, VERMONT = ROOT / "data", ROOT / "vermont"
VERMONT_V = VERMONT / "VERMONT_BusVoltage_2026_04_09_15_00 to 2026_10_09_15_00.csv"
VERMONT_THERMAL = VERMONT / "VERMONT_sensor_thermal_deg_c_2026_02_22_15_00 to 2026_10_09_15_00.csv"
JUNGFRAU_V = DATA / "JUNGFRAU_BusVoltage_2026_09_11_14_00 to 2026_10_09_14_00.csv"
def at(*args):
return datetime(*args, tzinfo=timezone.utc)
@functools.cache
def stations():
return ec.load_stations([str(DATA), str(VERMONT)])
class Loading(unittest.TestCase):
def test_parse_name_metric_with_underscores(self):
self.assertEqual(ec.parse_name(str(VERMONT_THERMAL)), ("VERMONT", "sensor_thermal_deg_c"))
def test_parse_name_rejects_unknown_pattern(self):
self.assertIsNone(ec.parse_name("data/metadata.csv"))
def test_load_csv_empty_value_is_none(self):
s = ec.load_csv(VERMONT_V)
self.assertIsNone(s[at(2026, 4, 9, 15)])
self.assertAlmostEqual(s[at(2026, 4, 9, 16)], 14.011)
def test_load_stations_groups_by_station(self):
self.assertEqual(sorted(stations()), ["FLORIDA", "JUNGFRAU", "MISSISSIPPI", "VERMONT", "WILDSTRUBEL"])
self.assertEqual(len(stations()["VERMONT"]), 7)
def test_same_file_given_twice_is_not_a_duplicate(self):
self.assertIn("BusVoltage", ec.load_stations([str(DATA), str(JUNGFRAU_V)])["JUNGFRAU"])
def test_two_files_same_station_metric_raise(self):
with tempfile.TemporaryDirectory() as d:
shutil.copy(JUNGFRAU_V, Path(d) / "JUNGFRAU_BusVoltage_2026_09_12_14_00 to 2026_10_09_14_00.csv")
with self.assertRaises(ValueError):
ec.load_stations([str(DATA), d])
def test_unknown_csv_name_is_skipped_with_message(self):
with tempfile.TemporaryDirectory() as d:
shutil.copy(JUNGFRAU_V, Path(d) / "export.csv")
shutil.copy(JUNGFRAU_V, d)
err = io.StringIO()
with redirect_stderr(err):
st = ec.load_stations([d])
self.assertEqual(list(st), ["JUNGFRAU"])
self.assertIn("export.csv", err.getvalue())
if __name__ == "__main__":
unittest.main()
```
- [ ] **Step 2 : vérifier que les tests échouent**
Run : `python3 -m unittest discover -s tests -v`
Expected : ERROR `ModuleNotFoundError: No module named 'energy_check'`
- [ ] **Step 3 : écrire l'implémentation minimale**
Créer `src/energy_check.py` :
```python
"""Analyse énergétique MA7D_DROP : tendance de BusVoltage en moyenne glissante.
Spec : docs/superpowers/specs/2026-10-09-energy-ma7d-design.md
Bibliothèque standard uniquement (cible : système embarqué de la station).
"""
import csv
import glob
import os
import re
import sys
from datetime import datetime
NAME_RE = re.compile(r"^(?P<station>[^_]+)_(?P<metric>.+?)_\d{4}_\d{2}_\d{2}_\d{2}_\d{2} to .+\.csv$")
def parse_name(path):
"""'<STATION>_<Metric>_<début> to <fin>.csv' -> (station, metric), ou None."""
m = NAME_RE.match(os.path.basename(path))
return (m["station"], m["metric"]) if m else None
def load_csv(path):
"""CSV ',time_utc,metric' -> {datetime UTC: float ou None (pas de mesure)}."""
with open(path, newline="") as f:
rows = csv.reader(f)
next(rows)
return {datetime.fromisoformat(r[1]): float(r[2]) if r[2] else None for r in rows}
def load_stations(paths):
"""Fichiers et/ou dossiers -> {station: {metric: série}}."""
files = []
for p in paths:
files += sorted(glob.glob(os.path.join(p, "*.csv"))) if os.path.isdir(p) else [p]
stations, seen = {}, {}
for path in files:
real = os.path.realpath(path)
if real in seen.values():
continue
key = parse_name(path)
if key is None:
print(f"ignoré (nom non reconnu) : {path}", file=sys.stderr)
continue
if key in seen:
raise ValueError(f"doublon {key[0]}/{key[1]} : {seen[key]} et {path}")
seen[key] = real
stations.setdefault(key[0], {})[key[1]] = load_csv(path)
return stations
```
- [ ] **Step 4 : vérifier que les tests passent**
Run : `python3 -m unittest discover -s tests -v`
Expected : `Ran 7 tests` … `OK`
- [ ] **Step 5 : commit**
```bash
git add src/energy_check.py tests/test_energy_check.py
git commit -m "Add CSV loading per station for energy analysis" -m "Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>"
```
---
### Task 2 : analyse causale `run()` (MA7D_DROP)
**Files :**
- Modify : `src/energy_check.py` (import `datetime` et ajouts à la suite de `load_stations`)
- Modify : `tests/test_energy_check.py` (imports, helpers, classe `Ma7dDrop`)
**Interfaces :**
- Consumes : `load_stations` et `load_csv` (Task 1).
- Produces :
- les constantes `HOUR`, `WINDOW_H`, `REF_H`, `MIN_COVERAGE`, `MIN_REF_POINTS`, `THRESHOLD_V` et le dict `RULE` ;
- `run(series: dict[str, dict[datetime, float | None]]) -> dict`, qui renvoie `{"analysis": "MA7D_DROP", "rule": RULE, "points": [Point]}` ;
- `Point = {"t": datetime, "value": float | None, "anomaly": bool | None, "facts": dict}` :
- `facts` contient toujours `coverage` (float) ;
- plus `ma_v` (float, 3 décimales) si la moyenne est définie ;
- plus `ref_v` (float) et `ref_t` (datetime) si la référence est définie.
- `run` lève `ValueError` si un horodatage n'est pas sur la grille horaire.
- [ ] **Step 1 : écrire les tests qui échouent**
Dans `tests/test_energy_check.py`, remplacer la ligne `from datetime import datetime, timezone` par :
```python
from datetime import datetime, timedelta, timezone
```
Ajouter après la fonction `stations()` :
```python
@functools.cache
def result(name):
return ec.run(stations()[name])
def first_anomaly(res):
return next((p["t"] for p in res["points"] if p["anomaly"] is True), None)
```
Ajouter avant `if __name__ == "__main__":` :
```python
class Ma7dDrop(unittest.TestCase):
def test_florida_never_anomalous(self):
self.assertIsNone(first_anomaly(result("FLORIDA")))
def test_jungfrau_never_anomalous(self):
self.assertIsNone(first_anomaly(result("JUNGFRAU")))
def test_vermont_first_anomaly_before_first_cut(self):
t = first_anomaly(result("VERMONT"))
self.assertIsNotNone(t)
self.assertTrue(at(2026, 9, 20) <= t < at(2026, 9, 27, 1), t)
def test_wildstrubel_first_anomaly_before_cut(self):
t = first_anomaly(result("WILDSTRUBEL"))
self.assertIsNotNone(t)
self.assertLess(t, at(2026, 9, 9, 22))
def test_mississippi_first_anomaly_before_first_cut(self):
t = first_anomaly(result("MISSISSIPPI"))
self.assertIsNotNone(t)
self.assertLess(t, at(2025, 12, 25, 14))
def test_causal(self):
t = at(2026, 9, 24, 7)
truncated = {"BusVoltage": {k: x for k, x in stations()["VERMONT"]["BusVoltage"].items() if k <= t}}
last = ec.run(truncated)["points"][-1]
full = next(p for p in result("VERMONT")["points"] if p["t"] == t)
self.assertEqual(last["t"], t)
self.assertEqual((last["value"], last["anomaly"]), (full["value"], full["anomaly"]))
def test_one_point_per_timestamp(self):
self.assertEqual([p["t"] for p in result("VERMONT")["points"]],
sorted(stations()["VERMONT"]["BusVoltage"]))
def test_facts_trace_the_verdict(self):
p = next(p for p in result("VERMONT")["points"] if p["anomaly"] is True)
self.assertEqual(set(p["facts"]), {"coverage", "ma_v", "ref_v", "ref_t"})
self.assertLess(p["facts"]["ref_t"], p["t"])
def test_short_history_is_unknown(self):
v = stations()["JUNGFRAU"]["BusVoltage"]
short = {"BusVoltage": {t: x for t, x in v.items() if t < min(v) + timedelta(days=5)}}
self.assertTrue(all(p["anomaly"] is None for p in ec.run(short)["points"]))
def test_empty_series_gives_no_points(self):
self.assertEqual(ec.run({"BusVoltage": {}})["points"], [])
def test_off_grid_timestamp_raises(self):
v = dict(stations()["JUNGFRAU"]["BusVoltage"])
v[min(v) + timedelta(minutes=30)] = None
with self.assertRaises(ValueError):
ec.run({"BusVoltage": v})
```
- [ ] **Step 2 : vérifier que les tests échouent**
Run : `python3 -m unittest discover -s tests -v`
Expected : les 11 tests `Ma7dDrop` en ERROR `AttributeError: module 'energy_check' has no attribute 'run'`. Les 7 tests `Loading` restent OK.
- [ ] **Step 3 : écrire l'implémentation minimale**
Dans `src/energy_check.py`, remplacer `from datetime import datetime` par :
```python
from datetime import datetime, timedelta
```
Ajouter juste après les imports, avant `NAME_RE` :
```python
HOUR = timedelta(hours=1)
# Constantes de calibration (spec §4.2).
WINDOW_H = 168 # multiple de 24 h : annule le cycle jour/nuit ; 72 h ne lisse pas la météo
REF_H = 720 # 30 jours : contient le dernier régime sain avant un déficit (choix de conception)
MIN_COVERAGE = 0.8 # à 0,5, JUNGFRAU (sain) tombe à -0,19 V en début d'historique ; à 0,8 : -0,13 V
MIN_REF_POINTS = 24 # au moins un jour de référence (choix de conception)
THRESHOLD_V = -0.2 # cas de régression : pire écart sain -0,16 V (VERMONT 05-11)
RULE = {
"id": "MA7D_DROP",
"window_h": WINDOW_H,
"ref_h": REF_H,
"min_coverage": MIN_COVERAGE,
"min_ref_points": MIN_REF_POINTS,
"threshold_v": THRESHOLD_V,
"threshold_source": "cas de régression FLORIDA, JUNGFRAU, VERMONT, WILDSTRUBEL, MISSISSIPPI (spec §4.3)",
"spec": "docs/superpowers/specs/2026-10-09-energy-ma7d-design.md",
}
```
Ajouter à la fin du fichier :
```python
def run(series):
"""Analyse MA7D_DROP, causale : le point t n'utilise que les données <= t (spec §4.1, §5)."""
v = series["BusVoltage"]
if not v:
return {"analysis": RULE["id"], "rule": RULE, "points": []}
t0 = min(v)
if any((t - t0) % HOUR for t in v):
raise ValueError("BusVoltage : horodatages hors de la grille horaire")
grid = [t0 + i * HOUR for i in range((max(v) - t0) // HOUR + 1)]
vals = [v.get(t) for t in grid]
# Moyenne glissante sur WINDOW_H créneaux (somme courante), définie si couverture suffisante.
ma, cov = [None] * len(grid), [0.0] * len(grid)
total = count = 0
for i, x in enumerate(vals):
if x is not None:
total += x
count += 1
if i >= WINDOW_H and vals[i - WINDOW_H] is not None:
total -= vals[i - WINDOW_H]
count -= 1
cov[i] = count / WINDOW_H
if count >= MIN_COVERAGE * WINDOW_H:
ma[i] = total / count
points = []
for i, t in enumerate(grid):
if t not in v:
continue
facts = {"coverage": round(cov[i], 3)}
value = anomaly = None
if ma[i] is not None:
facts["ma_v"] = round(ma[i], 3)
lo = max(0, i - REF_H)
ref_vals = [m for m in ma[lo:i] if m is not None]
if len(ref_vals) >= MIN_REF_POINTS:
ref = max(ref_vals)
value = ma[i] - ref
anomaly = value < THRESHOLD_V
facts["ref_v"] = round(ref, 3)
facts["ref_t"] = grid[ma.index(ref, lo, i)]
points.append({"t": t, "value": value, "anomaly": anomaly, "facts": facts})
return {"analysis": RULE["id"], "rule": RULE, "points": points}
```
- [ ] **Step 4 : vérifier que les tests passent**
Run : `python3 -m unittest discover -s tests -v`
Expected : `Ran 18 tests` … `OK`. Durée attendue : moins d'une seconde (prototype : 0,5 s).
- [ ] **Step 5 : commit**
```bash
git add src/energy_check.py tests/test_energy_check.py
git commit -m "Add causal MA7D_DROP voltage-trend analysis" -m "Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>"
```
---
### Task 3 : périodes, résumé texte et ligne de commande
**Files :**
- Modify : `src/energy_check.py` (imports et ajouts à la fin)
- Modify : `tests/test_energy_check.py` (imports et classe `Reporting`)
- Modify : `.gitignore` (ajout de `out/`)
**Interfaces :**
- Consumes : `run`, `RULE`, `THRESHOLD_V` (Task 2) ; `load_stations` (Task 1).
- Produces :
- `periods(points: list[Point]) -> list[dict]`. Chaque période vaut `{"start": datetime, "end": datetime | None, "worst_value": float, "worst_t": datetime}`, et `end` vaut `None` si la période est en cours ;
- `summary(station: str, result: dict, per: list[dict]) -> str`, une ligne par période ;
- `main(argv: list[str] | None = None)`, qui écrit `<out>/<STATION>_energy.json` et affiche le résumé.
- [ ] **Step 1 : écrire les tests qui échouent**
Dans `tests/test_energy_check.py` :
- ajouter `import json` sous `import io` ;
- remplacer `from contextlib import redirect_stderr` par :
```python
from contextlib import redirect_stderr, redirect_stdout
```
Ajouter avant `if __name__ == "__main__":` :
```python
class Reporting(unittest.TestCase):
def test_vermont_period_is_ongoing(self):
per = ec.periods(result("VERMONT")["points"])
self.assertEqual(per[-1]["start"], at(2026, 9, 24, 7))
self.assertIsNone(per[-1]["end"])
def test_mississippi_first_period_is_closed(self):
per = ec.periods(result("MISSISSIPPI")["points"])
self.assertEqual((per[0]["start"], per[0]["end"]), (at(2025, 12, 9, 12), at(2025, 12, 18, 6)))
def test_florida_has_no_period(self):
self.assertEqual(ec.periods(result("FLORIDA")["points"]), [])
def test_summary_vocabulary(self):
for name, word in [("FLORIDA", "not observed"), ("VERMONT", "consistent with")]:
res = result(name)
self.assertIn(word, ec.summary(name, res, ec.periods(res["points"])))
def test_summary_short_history_is_insufficient_evidence(self):
v = stations()["JUNGFRAU"]["BusVoltage"]
res = ec.run({"BusVoltage": {t: x for t, x in v.items() if t < min(v) + timedelta(days=5)}})
self.assertIn("insufficient evidence", ec.summary("JUNGFRAU", res, ec.periods(res["points"])))
def test_cli_writes_json_and_summary(self):
out = io.StringIO()
with tempfile.TemporaryDirectory() as d, redirect_stdout(out):
ec.main([str(VERMONT), "--out", d])
doc = json.loads((Path(d) / "VERMONT_energy.json").read_text())
self.assertEqual((doc["station"], doc["analysis"]), ("VERMONT", "MA7D_DROP"))
self.assertIsNone(doc["periods"][-1]["end"])
self.assertIn("VERMONT : anomalie énergétique", out.getvalue())
def test_cli_skips_station_without_busvoltage(self):
out = io.StringIO()
with tempfile.TemporaryDirectory() as d, redirect_stdout(out):
ec.main([str(VERMONT_THERMAL), "--out", d])
self.assertIn("ignorée, pas de BusVoltage", out.getvalue())
```
- [ ] **Step 2 : vérifier que les tests échouent**
Run : `python3 -m unittest discover -s tests -v`
Expected : les 7 tests `Reporting` en ERROR `AttributeError: module 'energy_check' has no attribute 'periods'` (ou `'main'`). Les 18 autres restent OK.
- [ ] **Step 3 : écrire l'implémentation minimale**
Dans `src/energy_check.py`, ajouter `import argparse` avant `import csv`, et `import json` après `import glob`. Puis ajouter à la fin du fichier :
```python
def periods(points):
"""Séquences maximales True/None commençant et finissant par True (spec §7.1)."""
spans, cur = [], None
for k, p in enumerate(points):
if p["anomaly"] is True:
if cur is None:
cur = {"first": k, "last": k, "worst": k}
cur["last"] = k
if p["value"] < points[cur["worst"]]["value"]:
cur["worst"] = k
elif p["anomaly"] is False and cur is not None:
spans.append(cur)
cur = None
if cur is not None:
spans.append(cur)
out = []
for s in spans:
ongoing = all(p["anomaly"] is None for p in points[s["last"] + 1:])
out.append({
"start": points[s["first"]]["t"],
"end": None if ongoing else points[s["last"]]["t"],
"worst_value": points[s["worst"]]["value"],
"worst_t": points[s["worst"]]["t"],
})
return out
def _d(t):
return t.strftime("%Y-%m-%d %H:%M")
def _v(x):
return f"{x:.2f}".replace(".", ",")
def summary(station, result, per):
"""Résumé texte généré à partir des faits calculés (une ligne par période)."""
rule = f"Règle {RULE['id']} (seuil {_v(THRESHOLD_V)} V, source : cas de régression)."
defined = [p for p in result["points"] if p["value"] is not None]
if not defined:
return f"{station} : analyse impossible (insufficient evidence) : historique trop court ou vide. {rule}"
if not per:
w = min(defined, key=lambda p: p["value"])
return (f"{station} : aucune anomalie énergétique (not observed) sur la période analysée. "
f"Pire écart {_v(w['value'])} V le {_d(w['t'])}. {rule}")
lines = []
for p in per:
w = next(q for q in result["points"] if q["t"] == p["worst_t"])
f = w["facts"]
until = "la fin de l'export" if p["end"] is None else _d(p["end"])
lines.append(
f"{station} : anomalie énergétique (consistent with) du {_d(p['start'])} à {until}. "
f"Pire écart le {_d(w['t'])} : moyenne sur 7 jours {_v(f['ma_v'])} V, soit {_v(-w['value'])} V "
f"sous son maximum du {_d(f['ref_t'])} ({_v(f['ref_v'])} V). {rule}")
return "\n".join(lines)
def main(argv=None):
ap = argparse.ArgumentParser(description="Analyse énergétique MA7D_DROP")
ap.add_argument("paths", nargs="+", help="fichiers CSV et/ou dossiers")
ap.add_argument("--out", default="out", help="dossier de sortie (défaut : out/)")
a = ap.parse_args(argv)
os.makedirs(a.out, exist_ok=True)
for station, series in sorted(load_stations(a.paths).items()):
if "BusVoltage" not in series:
print(f"{station} : ignorée, pas de BusVoltage")
continue
result = run(series)
per = periods(result["points"])
with open(os.path.join(a.out, f"{station}_energy.json"), "w") as f:
json.dump({"station": station, **result, "periods": per}, f, indent=1,
default=lambda o: o.isoformat())
print(summary(station, result, per))
if __name__ == "__main__":
main()
```
Ajouter la ligne suivante à la fin de `.gitignore` :
```
out/
```
- [ ] **Step 4 : vérifier que les tests passent**
Run : `python3 -m unittest discover -s tests -v`
Expected : `Ran 25 tests` … `OK`
- [ ] **Step 5 : vérifier sur les données réelles**
Run : `python3 src/energy_check.py data/ vermont/`
Expected : 8 lignes, dont :
```
FLORIDA : aucune anomalie énergétique (not observed) sur la période analysée. Pire écart -0,04 V le 2026-05-17 07:00. Règle MA7D_DROP (seuil -0,20 V, source : cas de régression).
JUNGFRAU : aucune anomalie énergétique (not observed) sur la période analysée. Pire écart -0,13 V le 2026-10-05 01:00. Règle MA7D_DROP (seuil -0,20 V, source : cas de régression).
VERMONT : anomalie énergétique (consistent with) du 2026-09-24 07:00 à la fin de l'export. Pire écart le 2026-10-09 01:00 : moyenne sur 7 jours 12,78 V, soit 0,55 V sous son maximum du 2026-09-09 06:00 (13,33 V). Règle MA7D_DROP (seuil -0,20 V, source : cas de régression).
WILDSTRUBEL : anomalie énergétique (consistent with) du 2026-09-06 14:00 à la fin de l'export. Pire écart le 2026-10-04 05:00 : moyenne sur 7 jours 12,85 V, soit 0,53 V sous son maximum du 2026-09-04 05:00 (13,38 V). Règle MA7D_DROP (seuil -0,20 V, source : cas de régression).
```
Plus 4 lignes MISSISSIPPI : périodes commençant le 2025-12-09 12:00, le 2025-12-24 07:00, le 2026-08-16 18:00 et le 2026-10-06 15:00. La dernière est en cours. Les fichiers `out/*_energy.json` sont créés et `git status` ne les montre pas.
- [ ] **Step 6 : commit**
```bash
git add src/energy_check.py tests/test_energy_check.py .gitignore
git commit -m "Add anomaly periods, text summary and CLI for MA7D_DROP" -m "Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>"
```
---
### Task 4 : graphique HTML (plotly)
**Files :**
- Create : `src/energy_plot.py`
- Create : `tests/test_energy_plot.py`
**Interfaces :**
- Consumes : `load_stations`, `run`, `periods`, `RULE`, `THRESHOLD_V` de `energy_check` (Tasks 1 à 3). Clés de `facts` : `coverage`, `ma_v`, `ref_v`, `ref_t`.
- Produces :
- `gaps(v: dict[datetime, float | None]) -> list[tuple[datetime, datetime]]` : renvoie `(premier créneau vide, première valeur suivante)`, ou le dernier horodatage si le trou est en fin de série ;
- `figure(station, series, result, per) -> plotly Figure` ;
- `main(argv=None)`, qui écrit `<out>/<STATION>_energy.html`.
- [ ] **Step 1 : écrire les tests qui échouent**
Créer `tests/test_energy_plot.py` :
```python
"""Test de fumée du graphique MA7D_DROP (nécessite plotly : .venv/bin/python)."""
import importlib.util
import io
import sys
import tempfile
import unittest
from contextlib import redirect_stdout
from datetime import datetime, timezone
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "src"))
import energy_check as ec # noqa: E402
HAS_PLOTLY = importlib.util.find_spec("plotly") is not None
if HAS_PLOTLY:
import energy_plot as ep
VERMONT = ROOT / "vermont"
def at(*args):
return datetime(*args, tzinfo=timezone.utc)
@unittest.skipUnless(HAS_PLOTLY, "plotly absent : lancer avec .venv/bin/python")
class Plot(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.series = ec.load_stations([str(VERMONT)])["VERMONT"]
cls.result = ec.run(cls.series)
def test_gaps_include_first_vermont_cut(self):
self.assertIn((at(2026, 9, 27, 1), at(2026, 9, 27, 7)), ep.gaps(self.series["BusVoltage"]))
def test_figure_has_all_series(self):
fig = ep.figure("VERMONT", self.series, self.result, ec.periods(self.result["points"]))
names = {t.name for t in fig.data}
self.assertLessEqual({"BusVoltage", "moyenne 7 j", "référence (max 30 j)", "seuil", "écart"}, names)
self.assertLessEqual(set(self.series) - {"BusVoltage"}, names)
def test_cli_writes_html(self):
with tempfile.TemporaryDirectory() as d, redirect_stdout(io.StringIO()):
ep.main([str(VERMONT), "--out", d])
self.assertGreater((Path(d) / "VERMONT_energy.html").stat().st_size, 0)
if __name__ == "__main__":
unittest.main()
```
- [ ] **Step 2 : vérifier que les tests échouent**
Run : `.venv/bin/python -m unittest discover -s tests -v`
Expected : ERROR au chargement de `test_energy_plot` avec `ModuleNotFoundError: No module named 'energy_plot'`. Les 25 tests de `test_energy_check` restent OK.
- [ ] **Step 3 : écrire l'implémentation minimale**
Créer `src/energy_plot.py` :
```python
"""Graphique HTML de l'analyse MA7D_DROP (poste de dev, plotly dans .venv).
Spec : docs/superpowers/specs/2026-10-09-energy-ma7d-design.md §7.2
"""
import argparse
import os
from plotly.subplots import make_subplots
import energy_check as ec
def gaps(v):
"""Plages de créneaux sans BusVoltage : [(premier créneau vide, première valeur suivante)]."""
out, start = [], None
for t in sorted(v):
if v[t] is None and start is None:
start = t
elif v[t] is not None and start is not None:
out.append((start, t))
start = None
if start is not None:
out.append((start, max(v)))
return out
def figure(station, series, result, per):
extra = sorted(m for m in series if m != "BusVoltage")
fig = make_subplots(rows=2 + len(extra), cols=1, shared_xaxes=True, vertical_spacing=0.03,
subplot_titles=["BusVoltage [V]", f"Écart {ec.RULE['id']} [V]"] + extra)
v = series["BusVoltage"]
pts = result["points"]
x = [p["t"] for p in pts]
ref = [p["facts"].get("ref_v") for p in pts]
fig.add_scatter(x=sorted(v), y=[v[t] for t in sorted(v)], name="BusVoltage",
line=dict(width=1, color="lightgray"), row=1, col=1)
fig.add_scatter(x=x, y=[p["facts"].get("ma_v") for p in pts], name="moyenne 7 j",
line=dict(color="royalblue"), row=1, col=1)
fig.add_scatter(x=x, y=ref, name="référence (max 30 j)",
line=dict(color="green", dash="dot"), row=1, col=1)
fig.add_scatter(x=x, y=[None if r is None else r + ec.THRESHOLD_V for r in ref], name="seuil",
line=dict(color="red", dash="dash"), row=1, col=1)
hover = [f"anomalie={p['anomaly']}<br>" + "<br>".join(f"{k}={val}" for k, val in p["facts"].items())
for p in pts]
fig.add_scatter(x=x, y=[p["value"] for p in pts], name="écart", text=hover,
hovertemplate="%{y:.3f} V<br>%{text}", line=dict(color="black"), row=2, col=1)
fig.add_hline(y=ec.THRESHOLD_V, line=dict(color="red", dash="dash"), row=2, col=1)
for a, b in gaps(v):
fig.add_vrect(x0=a, x1=b, fillcolor="gray", opacity=0.3, line_width=0, row=1, col=1)
for p in per:
fig.add_vrect(x0=p["start"], x1=p["end"] or x[-1], fillcolor="red", opacity=0.15,
line_width=0, row=2, col=1)
for row, m in enumerate(extra, start=3):
s = series[m]
fig.add_scatter(x=sorted(s), y=[s[t] for t in sorted(s)], name=m, line=dict(width=1),
row=row, col=1)
fig.update_layout(title=f"{station} : analyse {ec.RULE['id']}", height=280 * (2 + len(extra)))
return fig
def main(argv=None):
ap = argparse.ArgumentParser(description="Graphique HTML de l'analyse MA7D_DROP")
ap.add_argument("paths", nargs="+", help="fichiers CSV et/ou dossiers")
ap.add_argument("--out", default="out", help="dossier de sortie (défaut : out/)")
a = ap.parse_args(argv)
os.makedirs(a.out, exist_ok=True)
for station, series in sorted(ec.load_stations(a.paths).items()):
if "BusVoltage" not in series:
print(f"{station} : ignorée, pas de BusVoltage")
continue
result = ec.run(series)
path = os.path.join(a.out, f"{station}_energy.html")
figure(station, series, result, ec.periods(result["points"])).write_html(path, include_plotlyjs="cdn")
print(path)
if __name__ == "__main__":
main()
```
Note : `include_plotlyjs="cdn"` garde les fichiers légers (≤ 2,5 Mo) mais demande un accès internet pour les afficher. Ponytail : mettre `True` si un affichage hors ligne devient nécessaire.
- [ ] **Step 4 : vérifier que les tests passent**
Run : `.venv/bin/python -m unittest discover -s tests -v`
Expected : `Ran 28 tests` … `OK`
Run : `python3 -m unittest discover -s tests -v`
Expected : `Ran 28 tests` … `OK (skipped=3)`. Le Python système n'a pas plotly, le module se charge quand même.
- [ ] **Step 5 : générer les graphiques réels**
Run : `.venv/bin/python src/energy_plot.py data/ vermont/`
Expected : 5 chemins affichés (`out/FLORIDA_energy.html` … `out/WILDSTRUBEL_energy.html`). Ouvrir `out/VERMONT_energy.html` et vérifier à l'œil :
- 8 sous-graphes (tension, écart, puis 6 métriques) ;
- un fond rouge sur l'écart à partir du 24/09 ;
- des bandes grises sur les coupures nocturnes dès le 27/09.
- [ ] **Step 6 : commit**
```bash
git add src/energy_plot.py tests/test_energy_plot.py
git commit -m "Add plotly HTML report for MA7D_DROP" -m "Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>"
```