diff --git a/src/energy_plot.py b/src/energy_plot.py new file mode 100644 index 0000000..ab1ad03 --- /dev/null +++ b/src/energy_plot.py @@ -0,0 +1,78 @@ +"""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']}
" + "
".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
%{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() diff --git a/tests/test_energy_plot.py b/tests/test_energy_plot.py new file mode 100644 index 0000000..a842db9 --- /dev/null +++ b/tests/test_energy_plot.py @@ -0,0 +1,49 @@ +"""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()