Add anomaly periods, text summary and CLI for MA7D_DROP

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
maximeandClaude Opus 5.5 committed 2026-10-09 19:26:44 +02:00
1 parent 041770ec47
commit d91ab866e2
3 files changed
+123 -1

No files matched your search

+1
View File
@@ -1,3 +1,4 @@
.claude/settings.local.json .claude/settings.local.json
.env .env
.env.* .env.*
out/
+81
View File
@@ -3,8 +3,10 @@
Spec : docs/superpowers/specs/2026-10-09-energy-ma7d-design.md Spec : docs/superpowers/specs/2026-10-09-energy-ma7d-design.md
Bibliothèque standard uniquement (cible : système embarqué de la station). Bibliothèque standard uniquement (cible : système embarqué de la station).
""" """
import argparse
import csv import csv
import glob import glob
import json
import os import os
import re import re
import sys import sys
@@ -111,3 +113,82 @@ def run(series):
facts["ref_t"] = grid[ma.index(ref, lo, i)] facts["ref_t"] = grid[ma.index(ref, lo, i)]
points.append({"t": t, "value": value, "anomaly": anomaly, "facts": facts}) points.append({"t": t, "value": value, "anomaly": anomaly, "facts": facts})
return {"analysis": RULE["id"], "rule": RULE, "points": points} return {"analysis": RULE["id"], "rule": RULE, "points": points}
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()
+41 -1
View File
@@ -1,11 +1,12 @@
"""Tests de régression de l'analyse MA7D_DROP, sur données réelles uniquement (spec §9).""" """Tests de régression de l'analyse MA7D_DROP, sur données réelles uniquement (spec §9)."""
import functools import functools
import io import io
import json
import shutil import shutil
import sys import sys
import tempfile import tempfile
import unittest import unittest
from contextlib import redirect_stderr from contextlib import redirect_stderr, redirect_stdout
from datetime import datetime, timedelta, timezone from datetime import datetime, timedelta, timezone
from pathlib import Path from pathlib import Path
@@ -127,5 +128,44 @@ class Ma7dDrop(unittest.TestCase):
ec.run({"BusVoltage": v}) ec.run({"BusVoltage": v})
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())
if __name__ == "__main__": if __name__ == "__main__":
unittest.main() unittest.main()