- src/analyse_01.py: single entry point, analyses data/, writes and opens the HTML report (switches to .venv for plotly). - Plot: analysis on top, one subplot per time series below; zoom in time only, y axes rescaled to the visible range on every zoom. - Tests removed: experimental prototype phase (D-008). - Ignore __pycache__/. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
127 lines
5.7 KiB
Python
127 lines
5.7 KiB
Python
"""Graphique HTML de l'analyse MA7D_DROP (poste de dev, plotly dans .venv).
|
|
|
|
Documentation : docs/analyses/analyse_01.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),
|
|
# en gardant la ligne de seuil visible. 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 = {yaxis: [__SEUIL__, __SEUIL__]};
|
|
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);
|
|
});
|
|
""".replace("__SEUIL__", str(ec.THRESHOLD_V))
|
|
|
|
|
|
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):
|
|
"""Haut : l'analyse, courbes superposées. Dessous : une série temporelle par graphique (échelles propres)."""
|
|
metrics = ["BusVoltage"] + sorted(m for m in series if m != "BusVoltage")
|
|
fig = make_subplots(rows=1 + len(metrics), cols=1, shared_xaxes=True, vertical_spacing=0.02,
|
|
row_heights=[1.5] + [1] * len(metrics),
|
|
specs=[[{"secondary_y": True}]] + [[{}]] * len(metrics),
|
|
subplot_titles=[f"Analyse {ec.RULE['id']}"] + metrics)
|
|
|
|
analyse = dict(legendgroup="analyse", legendgrouptitle_text="Analyse")
|
|
pts = result["points"]
|
|
x = [p["t"] for p in pts]
|
|
ref = [p["facts"].get("ref_v") for p in pts]
|
|
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=1, col=1, **analyse)
|
|
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, secondary_y=True, **analyse)
|
|
fig.add_scatter(x=x, y=ref, name="référence (max 30 j)", line=dict(color="green", dash="dot"),
|
|
row=1, col=1, secondary_y=True, **analyse)
|
|
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, secondary_y=True, **analyse)
|
|
fig.add_hline(y=ec.THRESHOLD_V, line=dict(color="black", dash="dash"), 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=1, col=1)
|
|
fig.update_yaxes(title_text="écart [V]", row=1, col=1, secondary_y=False)
|
|
fig.update_yaxes(title_text="BusVoltage moyennée [V]", row=1, col=1, secondary_y=True)
|
|
|
|
mesures = dict(legendgroup="mesures", legendgrouptitle_text="Mesures")
|
|
for row, m in enumerate(metrics, start=2):
|
|
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=2, col=1)
|
|
fig.update_yaxes(fixedrange=True) # zoom horizontal seulement : l'ordonnée est recalée par AUTOSCALE_Y_JS
|
|
fig.update_layout(title=f"{station} : analyse {ec.RULE['id']}", height=300 * (1 + len(metrics)),
|
|
legend=dict(groupclick="toggleitem"))
|
|
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)
|
|
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
|
|
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", post_script=AUTOSCALE_Y_JS, config={"scrollZoom": True})
|
|
print(path)
|
|
paths.append(path)
|
|
return paths
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|