"""Graphique HTML des analyses énergétiques, un panneau par analyse (poste de dev, plotly dans .venv). Documentation : docs/analyses/analyse_01.md, docs/analyses/analyse_02.md """ import argparse import os from plotly.subplots import make_subplots import energy_check as ec # 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), # seuil compris (c'est une courbe). Double-clic : retour à la vue complète. 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); } const box = {}; 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); }); """ 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, results): """Haut : une analyse par graphique, courbes superposées. Dessous : une série temporelle par graphique.""" metrics = ["BusVoltage"] + sorted(m for m in series if m != "BusVoltage") 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) 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)}
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["facts"].get("ma_v") for p in pts], name="moyenne 7 j", text=hover, hovertemplate="%{y:.3f} V
%{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) mesures = dict(legendgroup="mesures", legendgrouptitle_text="Mesures") for row, m in enumerate(metrics, start=n + 1): 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, **mesures) for a, b in gaps(series["BusVoltage"]): 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 fig.update_yaxes(fixedrange=True) # zoom horizontal seulement : l'ordonnée est recalée par AUTOSCALE_Y_JS fig.update_layout(title=f"{station} : analyses " + ", ".join(r["analysis"] for r in results), height=300 * (n + len(metrics)), legend=dict(groupclick="toggleitem")) return fig def main(argv=None): ap = argparse.ArgumentParser(description="Graphique HTML des analyses énergétiques") 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) paths = [] 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") figure(station, series, [ec.run(series), ec.run_midnight(series)]).write_html( path, include_plotlyjs="cdn", post_script=AUTOSCALE_Y_JS, config={"scrollZoom": True}) print(path) paths.append(path) return paths if __name__ == "__main__": main()