Files
Support-Agent/src/energy_plot.py
T
maximeandClaude Opus 5.5 fc74fec10f Add the day color matrix, the energy diagnostic manual and the site figure
D-020: the delivered energy diagnostic keeps analyses 03 and 04 only,
combined by the state x trend matrix of cas-d-usage-03-04.drawio into
one color per day (green / orange / red, grey when unknown), coded in
src/day_color.py (standard library). docs/guide/diagnostic-energetique.md
explains it: part 1 for the client, part 2 for support.

D-021: energy_plot.daily_figure builds the figure for the monitoring
site (panel 03 above panel 04, shared time axis), written by
analyse_01.py as out/<STATION>_daily.html and .json. battery_state no
longer imports energy_check, so analyses 03 and 04 ship on their own.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 16:23:21 +02:00

237 lines
13 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Graphique HTML des analyses énergétiques, un panneau par analyse (poste de dev, plotly dans .venv).
Documentation : docs/analyses/analyse_01.md à analyse_04.md
"""
import argparse
import os
from datetime import datetime, time, timezone
from plotly.subplots import make_subplots
import energy_check as ec
import battery_state as bs
import battery_trend as bt
# 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);
});
"""
# Zones de BusVoltage selon l'état de la batterie (bandes de fond) : docs/domaine/tensions-selon-l-etat-de-la-batterie.md.
# [V] = VERMONT, 5e-95e centiles horaires ; [M] = manuel ; [E] = experts. Les zones « en charge » et « décharge »
# se recouvrent de 13,1 à 13,2 V : sur le plateau, la tension seule ne sépare pas la charge de la décharge.
ZONES = [
("décharge", 12.0, 13.2, "steelblue", "bottom left"), # 12,0 : coupure de la station [M] ; 13,2 : haut du plateau [V]
("en charge", 13.1, 13.8, "gold", "top left"), # bulk [V]
("pleine charge", 14.0, 14.4, "green", "top left"), # absorption 14,0-14,3 [V] ; secteur 14,2-14,4 [E]
]
# États de DAILY_BATTERY_STATE : couleurs validées par le skill dataviz (toutes paires, fond blanc).
# Le jaune contraste peu avec le fond : chaque état a aussi son symbole, sa légende et son survol.
STATE_STYLE = {
"FULL_CHARGE": ("pleine charge", "#008300", "circle"),
"PARTIAL_CHARGE": ("charge partielle (incertain)", "#eda100", "diamond"),
"BELOW_PLATEAU": ("sous le plateau", "#2a78d6", "triangle-down"),
"NO_CHARGE": ("aucune charge", "#4a3aa7", "x"),
None: ("état inconnu", "#8c8c8c", "circle-open"),
}
def noon(day):
"""Abscisse d'un point journalier (analyses 03 et 04) : midi UTC de son jour, au milieu de la journée."""
return datetime.combine(day, time(12), timezone.utc)
def daily_state_panel(fig, result, row):
"""Panneau DAILY_BATTERY_STATE : maximum et fin de nuit par jour, seuils, état en marqueurs (fiche analyse_03)."""
group = dict(legendgroup=result["analysis"], legendgrouptitle_text=f"Analyse {result['analysis']}")
rule, pts = result["rule"], result["points"]
x = [noon(p["t"].date()) for p in pts]
fig.add_scatter(x=x, y=[p["facts"].get("max_v") for p in pts], name="maximum du jour", mode="lines",
line=dict(color="#52514e", width=1.5), hoverinfo="skip", row=row, col=1, **group)
fig.add_scatter(x=x, y=[p["facts"].get("night_end_v") for p in pts], name="fin de nuit", mode="lines",
line=dict(color="#9a9893", width=1.5), hovertemplate="fin de nuit %{y:.2f} V<extra></extra>",
row=row, col=1, **group)
# Seuils tracés comme des courbes (un point par jour) : AUTOSCALE_Y_JS les garde visibles au zoom (D-013).
for v, name, state in ((rule["full_charge_v"], "pleine charge", "FULL_CHARGE"),
(rule["plateau_floor_v"], "bas du plateau", "BELOW_PLATEAU")):
fig.add_scatter(x=x, y=[v] * len(x), name=f"{name} {v} V", mode="lines", hoverinfo="skip",
line=dict(color=STATE_STYLE[state][1], dash="dash", width=1), row=row, col=1, **group)
for state, (label, color, symbol) in STATE_STYLE.items():
sel = [p for p in pts if p["facts"]["state"] == state and p["facts"].get("max_v") is not None]
if not sel:
continue
hover = [f"{p['t']:%Y-%m-%d} : {label}<br>" + "<br>".join(f"{k}={val}" for k, val in p["facts"].items())
for p in sel]
fig.add_scatter(x=[noon(p["t"].date()) for p in sel], y=[p["facts"]["max_v"] for p in sel], name=label,
mode="markers",
marker=dict(color=color, symbol=symbol, size=8, line=dict(color="white", width=1)),
text=hover, hovertemplate="%{text}<extra></extra>", row=row, col=1, **group)
fig.update_yaxes(title_text="BusVoltage [V]", row=row, col=1)
# Tendances de DAILY_BATTERY_TREND : paire divergente bleu/rouge et gris neutre du skill dataviz
# (vert/rouge refusé par son validateur : deutéranopie, ΔE 5,9). Chaque tendance a aussi sa légende et son survol.
TREND_STYLE = {"BETTER": ("mieux", "#2a78d6"), "STABLE": ("stable", "#8c8c8c"), "WORSE": ("pire", "#d03b3b")}
def daily_trend_panel(fig, result, row):
"""Panneau DAILY_BATTERY_TREND : écart de fin de nuit J − J−1 en barres, couleur = tendance (fiche analyse_04)."""
group = dict(legendgroup=result["analysis"], legendgrouptitle_text=f"Analyse {result['analysis']}")
pts, db = result["points"], result["rule"]["night_end_deadband_v"]
x = [noon(p["t"].date()) for p in pts]
# Zone morte tracée comme une courbe (un point par jour, None entre +db et −db) : visible au zoom (D-013).
fig.add_scatter(x=x + [None] + x, y=[db] * len(x) + [None] + [-db] * len(x), name=f"zone morte ±{db} V",
mode="lines", hoverinfo="skip", line=dict(color="#52514e", dash="dash", width=1),
row=row, col=1, **group)
for trend, (label, color) in TREND_STYLE.items():
sel = [p for p in pts if p["facts"]["trend"] == trend and p["value"] is not None]
if not sel:
continue
hover = [f"{p['t']:%Y-%m-%d}: {label} (décidé par {p['facts']['decided_by']})<br>"
f"{p['facts']['state_prev']} → {p['facts']['state']}<br>"
+ "<br>".join(f"{k}={v}" for k, v in p["facts"].items() if k.startswith("delta")) for p in sel]
fig.add_bar(x=[noon(p["t"].date()) for p in sel], y=[p["value"] for p in sel], name=label,
marker_color=color, width=0.8 * 86_400_000, hovertext=hover, hovertemplate="%{hovertext}<extra></extra>",
row=row, col=1, **group)
fig.update_yaxes(title_text="Δ fin de nuit [V]", row=row, col=1)
def daily_figure(station, series):
"""Graphique pour le site de monitoring (D-021) : analyse 03 en haut, analyse 04 dessous, même axe du temps."""
fig = make_subplots(rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.08,
subplot_titles=[f"Analyse {bs.RULE['id']}", f"Analyse {bt.RULE['id']}"])
daily_state_panel(fig, bs.run(series), 1)
daily_trend_panel(fig, bt.run(series), 2)
fig.update_xaxes(showticklabels=True)
fig.update_yaxes(fixedrange=True) # zoom horizontal seulement : l'ordonnée est recalée par AUTOSCALE_Y_JS
fig.update_layout(title=f"{station} : état et tendance de la batterie", height=700, barmode="overlay",
legend=dict(groupclick="toggleitem"))
return fig
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):
if result["analysis"] == bs.RULE["id"]:
daily_state_panel(fig, result, row)
continue
if result["analysis"] == bt.RULE["id"]:
daily_trend_panel(fig, result, row)
continue
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)
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)
for name, lo, hi, color, pos in ZONES:
fig.add_hrect(y0=lo, y1=hi, fillcolor=color, opacity=0.15, line_width=0, layer="below",
annotation_text=f"{name} {lo}-{hi} V", annotation_position=pos, 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)),
barmode="overlay", 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), bs.run(series), bt.run(series)]).write_html(
path, include_plotlyjs="cdn", post_script=AUTOSCALE_Y_JS, config={"scrollZoom": True})
print(path)
paths.append(path)
# Analyses 03 et 04 : page de démo, et figure Plotly en JSON pour le site (Plotly.newPlot).
path = os.path.join(a.out, f"{station}_daily.html")
fig = daily_figure(station, series)
fig.write_html(path, include_plotlyjs="cdn", post_script=AUTOSCALE_Y_JS, config={"scrollZoom": True})
fig.write_json(path.removesuffix(".html") + ".json")
print(path)
paths.append(path)
return paths
if __name__ == "__main__":
main()