Rework analysis 01 entry point and plots, drop tests
- 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>
This commit is contained in:
1 parent
128d4bc298
commit
0b950199b8
6 files changed
+109
-283
No files matched your search
+70
-22
@@ -1,6 +1,6 @@
|
||||
"""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
|
||||
Documentation : docs/analyses/analyse_01.md
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
@@ -9,6 +9,42 @@ 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)]."""
|
||||
@@ -25,36 +61,44 @@ def gaps(v):
|
||||
|
||||
|
||||
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"]
|
||||
"""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]
|
||||
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']}<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=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)
|
||||
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=2, col=1)
|
||||
for row, m in enumerate(extra, start=3):
|
||||
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)
|
||||
fig.update_layout(title=f"{station} : analyse {ec.RULE['id']}", height=280 * (2 + len(extra)))
|
||||
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
|
||||
|
||||
|
||||
@@ -64,14 +108,18 @@ def main(argv=None):
|
||||
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")
|
||||
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__":
|
||||
|
||||
Reference in new issue
Block a user