2026-10-12 09:31:52 +02:00
|
|
|
"""Graphique HTML des analyses énergétiques, un panneau par analyse (poste de dev, plotly dans .venv).
|
2026-10-09 19:27:28 +02:00
|
|
|
|
2026-10-12 09:31:52 +02:00
|
|
|
Documentation : docs/analyses/analyse_01.md, docs/analyses/analyse_02.md
|
2026-10-09 19:27:28 +02:00
|
|
|
"""
|
|
|
|
|
import argparse
|
|
|
|
|
import os
|
|
|
|
|
|
|
|
|
|
from plotly.subplots import make_subplots
|
|
|
|
|
|
|
|
|
|
import energy_check as ec
|
|
|
|
|
|
2026-10-09 23:29:42 +02:00
|
|
|
# Plotly ne recale pas l'ordonnée sur la plage visible : après chaque zoom ou déplacement horizontal,
|
|
|
|
|
# ce script recalcule l'axe vertical de chaque graphique sur les points visibles (5 % de marge),
|
2026-10-12 09:31:52 +02:00
|
|
|
# seuil compris (c'est une courbe). Double-clic : retour à la vue complète.
|
2026-10-09 23:29:42 +02:00
|
|
|
AUTOSCALE_Y_JS = """
|
|
|
|
|
const gd = document.getElementById('{plot_id}');
|
|
|
|
|
const name = (t, a) => a + 'axis' + (t[a + 'axis'] || a).slice(1);
|
|
|
|
|
const xs = gd.data.map(t => t.x.map(v => gd._fullLayout[name(t, 'x')].d2l(v)));
|
|
|
|
|
gd.on('plotly_relayout', ev => {
|
|
|
|
|
const keys = Object.keys(ev);
|
|
|
|
|
if (!keys.some(k => k.startsWith('xaxis'))) return;
|
|
|
|
|
const upd = {};
|
|
|
|
|
if (keys.some(k => k.endsWith('autorange'))) {
|
|
|
|
|
gd.data.forEach(t => { upd[name(t, 'y') + '.autorange'] = true; });
|
|
|
|
|
return Plotly.relayout(gd, upd);
|
|
|
|
|
}
|
2026-10-12 09:31:52 +02:00
|
|
|
const box = {};
|
2026-10-09 23:29:42 +02:00
|
|
|
gd.data.forEach((t, i) => {
|
|
|
|
|
if (t.visible === 'legendonly' || t.visible === false) return;
|
|
|
|
|
const xa = gd._fullLayout[name(t, 'x')];
|
|
|
|
|
const [a, b] = xa.range.map(r => xa.r2l(r));
|
|
|
|
|
const r = box[name(t, 'y')] || (box[name(t, 'y')] = [Infinity, -Infinity]);
|
|
|
|
|
t.y.forEach((y, j) => {
|
|
|
|
|
if (y === null || !isFinite(y) || xs[i][j] < a || xs[i][j] > b) return;
|
|
|
|
|
r[0] = Math.min(r[0], y);
|
|
|
|
|
r[1] = Math.max(r[1], y);
|
|
|
|
|
});
|
|
|
|
|
});
|
|
|
|
|
for (const [ya, [lo, hi]] of Object.entries(box)) {
|
|
|
|
|
if (lo > hi) continue;
|
|
|
|
|
const pad = (hi - lo) * 0.05 || Math.abs(hi) * 0.01 || 1;
|
|
|
|
|
upd[ya + '.range'] = [lo - pad, hi + pad];
|
|
|
|
|
}
|
|
|
|
|
Plotly.relayout(gd, upd);
|
|
|
|
|
});
|
2026-10-12 09:31:52 +02:00
|
|
|
"""
|
2026-10-09 23:29:42 +02:00
|
|
|
|
2026-10-09 19:27:28 +02:00
|
|
|
|
|
|
|
|
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
|
|
|
|
|
|
|
|
|
|
|
2026-10-12 09:31:52 +02:00
|
|
|
def figure(station, series, results):
|
|
|
|
|
"""Haut : une analyse par graphique, courbes superposées. Dessous : une série temporelle par graphique."""
|
2026-10-09 23:29:42 +02:00
|
|
|
metrics = ["BusVoltage"] + sorted(m for m in series if m != "BusVoltage")
|
2026-10-12 09:31:52 +02:00
|
|
|
n = len(results)
|
|
|
|
|
fig = make_subplots(rows=n + len(metrics), cols=1, shared_xaxes=True, vertical_spacing=0.03,
|
|
|
|
|
row_heights=[1.5] * n + [1] * len(metrics),
|
|
|
|
|
subplot_titles=[f"Analyse {r['analysis']}" for r in results] + metrics)
|
2026-10-09 23:29:42 +02:00
|
|
|
|
2026-10-12 09:31:52 +02:00
|
|
|
for row, result in enumerate(results, start=1):
|
|
|
|
|
analyse = dict(legendgroup=result["analysis"], legendgrouptitle_text=f"Analyse {result['analysis']}")
|
|
|
|
|
thr = result["rule"]["threshold_v"]
|
|
|
|
|
pts = result["points"]
|
|
|
|
|
x = [p["t"] for p in pts]
|
|
|
|
|
ref = [p["facts"].get("ref_v") for p in pts]
|
|
|
|
|
hover = [f"écart={p['value'] if p['value'] is None else round(p['value'], 3)}<br>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["facts"].get("ma_v") for p in pts], name="moyenne 7 j", text=hover,
|
|
|
|
|
hovertemplate="%{y:.3f} V<br>%{text}", line=dict(color="royalblue"), row=row, col=1,
|
|
|
|
|
**analyse)
|
|
|
|
|
fig.add_scatter(x=x, y=[None if r is None else r + thr for r in ref], name=f"seuil (max 30 j {thr:+} V)",
|
|
|
|
|
line=dict(color="red", dash="dash"), row=row, col=1, **analyse)
|
|
|
|
|
for p in ec.periods(pts):
|
|
|
|
|
fig.add_vrect(x0=p["start"], x1=p["end"] or x[-1], fillcolor="red", opacity=0.15,
|
|
|
|
|
line_width=0, row=row, col=1)
|
|
|
|
|
fig.update_yaxes(title_text="BusVoltage moyennée [V]", row=row, col=1)
|
2026-10-09 23:29:42 +02:00
|
|
|
|
|
|
|
|
mesures = dict(legendgroup="mesures", legendgrouptitle_text="Mesures")
|
2026-10-12 09:31:52 +02:00
|
|
|
for row, m in enumerate(metrics, start=n + 1):
|
2026-10-09 19:27:28 +02:00
|
|
|
s = series[m]
|
|
|
|
|
fig.add_scatter(x=sorted(s), y=[s[t] for t in sorted(s)], name=m, line=dict(width=1),
|
2026-10-09 23:29:42 +02:00
|
|
|
row=row, col=1, **mesures)
|
|
|
|
|
for a, b in gaps(series["BusVoltage"]):
|
2026-10-12 09:31:52 +02:00
|
|
|
fig.add_vrect(x0=a, x1=b, fillcolor="gray", opacity=0.3, line_width=0, row=n + 1, col=1)
|
|
|
|
|
fig.update_xaxes(showticklabels=True) # dates sous chaque graphique, pas seulement le dernier
|
2026-10-09 23:29:42 +02:00
|
|
|
fig.update_yaxes(fixedrange=True) # zoom horizontal seulement : l'ordonnée est recalée par AUTOSCALE_Y_JS
|
2026-10-12 09:31:52 +02:00
|
|
|
fig.update_layout(title=f"{station} : analyses " + ", ".join(r["analysis"] for r in results),
|
|
|
|
|
height=300 * (n + len(metrics)),
|
2026-10-09 23:29:42 +02:00
|
|
|
legend=dict(groupclick="toggleitem"))
|
2026-10-09 19:27:28 +02:00
|
|
|
return fig
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def main(argv=None):
|
2026-10-12 09:31:52 +02:00
|
|
|
ap = argparse.ArgumentParser(description="Graphique HTML des analyses énergétiques")
|
2026-10-09 19:27:28 +02:00
|
|
|
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)
|
2026-10-09 23:29:42 +02:00
|
|
|
paths = []
|
2026-10-09 19:27:28 +02:00
|
|
|
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
|
|
|
|
|
path = os.path.join(a.out, f"{station}_energy.html")
|
2026-10-12 09:31:52 +02:00
|
|
|
figure(station, series, [ec.run(series), ec.run_midnight(series)]).write_html(
|
2026-10-09 23:29:42 +02:00
|
|
|
path, include_plotlyjs="cdn", post_script=AUTOSCALE_Y_JS, config={"scrollZoom": True})
|
2026-10-09 19:27:28 +02:00
|
|
|
print(path)
|
2026-10-09 23:29:42 +02:00
|
|
|
paths.append(path)
|
|
|
|
|
return paths
|
2026-10-09 19:27:28 +02:00
|
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
|
main()
|