Files
Support-Agent/src/energy/focus_jour.py
T

147 lines
9.0 KiB
Python
Raw Normal View History

"""Focus sur un jour : sa couleur (matrice état × tendance) et ce qui l'explique, sur le jour J et la veille seulement (D-024).
2026-10-13 09:10:35 +02:00
Usage : python3 src/energy/focus_jour.py JJ.MM[.AAAA] [CSV ou dossiers...] (défaut : data/VERMONT/ ; sans année, celle des données)
Affiche le résumé des faits, écrit out/<STATION>_focus_<AAAA-MM-JJ>.html (+ .json, la figure Plotly pour le site)
et l'ouvre dans le navigateur. Textes du résumé et du graphique en anglais : destinés au site (D-023).
"""
import sys
from datetime import date, timedelta
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1])) # src/ : paquets common et energy
from common.page import ROOT, open_html # noqa: E402 (bascule seule sur .venv si plotly manque)
from common.stations import gaps, load_stations # noqa: E402
import plotly.graph_objects as go # noqa: E402
from energy import battery_state as bs, battery_trend as bt, day_color as dc, power_source as ps # noqa: E402
from energy.final import STATE_STYLE, TREND_STYLE, noon # noqa: E402
# Statuts : noms et couleurs de la maquette System Summary (maquettes/user/summary_template.html).
COLOR = {"GREEN": ("Green", "#008300"), "ORANGE": ("Orange", "#eda100"), "RED": ("Red", "#d03b3b"),
None: ("Unknown", "#8c8c8c")}
# Condition qui a donné l'état (fiche daily_battery_state, « Principe », dans l'ordre d'évaluation).
STATE_RULE = {
"FULL_CHARGE": f"at least one hour ≥ {bs.FULL_CHARGE_V} V",
"BELOW_PLATEAU": f"one hour < {bs.PLATEAU_FLOOR_V} V",
"NO_CHARGE": f"daily rise < {bs.MIN_RISE_V} V",
"PARTIAL_CHARGE": f"daily rise ≥ {bs.MIN_RISE_V} V, no hour ≥ {bs.FULL_CHARGE_V} V",
None: f"fewer than {bs.MIN_COVERAGE * 24:.0f} h measured, no conclusion",
}
def parse_day(arg, series):
"""« 27.09 » ou « 27.09.2026 » -> date ; sans année, celle de la dernière mesure."""
d, m, *y = (int(x) for x in arg.split("."))
return date(y[0] if y else max(series["BusVoltage"]).year, m, d)
def summary(station, f):
"""Résumé texte traçable : couleur, règle, faits de J−1 et de J, tendance et ce qui l'a décidée."""
d, prev, cur = f["day"], f["prev"], f["cur"]
lines = [f"{station}, {d:%d/%m/%Y}: {COLOR[f['color']][0]}"]
if cur["power"] == "MAINS": # sur secteur, la perte du secteur décide (fiche daily_power_source)
lines.append(f" rule: on mains (3-day mean {cur['mean_3_days_v']} V ≥ {ps.MAINS_MEAN_V} V):"
f" {cur['hours_lost']} h < {ps.MAINS_LOST_V} V → {f['color'] or 'unknown'}")
else:
lines.append(f" rule: {dc.POWER_LABEL[cur['power']].lower()}, matrix state × trend (user manual § 7):"
f" {cur['state']} × {cur['trend']} → {f['color'] or 'unknown'}")
for tag, x, facts in (("D-1", d - timedelta(days=1), prev), ("D ", d, cur)):
if not facts or facts.get("max_v") is None:
lines.append(f" {tag} {x:%d/%m}: no measurement")
continue
lines.append(f" {tag} {x:%d/%m}: {facts['state']} ({STATE_RULE[facts['state']]}) · max {facts['max_v']} V"
f" · night end {facts['night_end_v']} V at {facts['night_end_h']:02d}:00"
f" · {facts['coverage'] * 24:.0f} h measured")
if cur["trend"]:
how = (f"state {cur['state_prev']} → {cur['state']}" if cur["decided_by"] == "state" else
f"night end {prev['night_end_v']} → {cur['night_end_v']} V"
f" (dead band ±{bt.NIGHT_END_DEADBAND_V} V)")
lines.append(f" trend: {cur['trend']}, decided by {how} · Δ night end {cur['delta_night_end_v']:+} V")
else:
lines.append(" trend: unknown (no state for D-1 or D)")
if provisional(f):
lines.append(f" provisional: data stop at {max(f['hours']):%H:%M} UTC, "
"the color can still change until midnight UTC")
return "\n".join(lines)
def provisional(f):
"""Le jour J n'est pas fini dans les données (dernier jour d'un export, ou jour en cours) : couleur provisoire."""
last = max(f["hours"])
return last.date() == f["day"] and last.hour < 23
def figure(station, f):
"""BusVoltage horaire sur J−1 et J, seuils de DAILY_BATTERY_STATE, maximum et fin de nuit de chaque jour,
flèche de fin de nuit J−1 -> J (comparaison de DAILY_BATTERY_TREND)."""
d, h = f["day"], f["hours"]
name, color = COLOR[f["color"]]
fig = go.Figure()
fig.add_scatter(x=list(h), y=list(h.values()), mode="lines+markers", line=dict(color="#636efa", width=2),
marker_size=4, hovertemplate="%{x|%d/%m %H:%M} UTC: %{y:.3f} V<extra></extra>")
for a, b in gaps(h):
fig.add_vrect(x0=a, x1=b, fillcolor="gray", opacity=0.3, line_width=0)
for v, label, state in ((bs.FULL_CHARGE_V, "full charge", "FULL_CHARGE"),
(bs.PLATEAU_FLOOR_V, "plateau floor", "BELOW_PLATEAU")):
fig.add_hline(y=v, line_dash="dash", line_width=1, line_color=STATE_STYLE[state][1],
annotation_text=f"{label} {v} V", annotation_position="top right")
midnight = noon(d) - timedelta(hours=12) # début de J (UTC) : l'axe couvre toujours J−1 et J, 48 h
fig.add_vline(x=midnight, line_width=1, line_color="#52514e")
night_ends = []
for tag, x, facts in (("D-1", d - timedelta(days=1), f["prev"]), ("D", d, f["cur"])):
fig.add_annotation(x=noon(x), y=1.07, yref="paper", showarrow=False,
text=f"<b>{tag} {x:%d/%m}</b>: {facts['state'] or 'unknown state' if facts else 'no data'}")
if not facts or facts.get("max_v") is None:
continue
day_h = {t: v for t, v in h.items() if t.date() == x and v is not None}
t_max = max(day_h, key=day_h.get)
t_end = next(t for t in day_h if t.hour == facts["night_end_h"])
night_ends.append((t_end, facts["night_end_v"]))
hover = "<br>".join(f"{k}={v}" for k, v in facts.items())
label, c, symbol = STATE_STYLE[facts["state"]]
fig.add_scatter(x=[t_max], y=[facts["max_v"]], mode="markers+text", text=[f"max {facts['max_v']} V"], cliponaxis=False,
textposition="top center", marker=dict(color=c, symbol=symbol, size=12),
hovertext=[f"{x:%d/%m}: {label}<br>{hover}"], hovertemplate="%{hovertext}<extra></extra>")
fig.add_scatter(x=[t_end], y=[facts["night_end_v"]], mode="markers+text", cliponaxis=False,
text=[f"night end {facts['night_end_v']} V"], textposition="bottom center",
marker=dict(color="#52514e", size=10), hovertext=[f"{x:%d/%m}: night end<br>{hover}"],
hovertemplate="%{hovertext}<extra></extra>")
trend = f["cur"]["trend"]
if len(night_ends) == 2 and trend:
(t0, v0), (t1, v1) = night_ends
label, c = TREND_STYLE[trend]
fig.add_annotation(x=t1, y=v1, ax=t0, ay=v0, axref="x", ayref="y", text="", showarrow=True,
arrowhead=2, arrowwidth=2, arrowcolor=c)
fig.add_annotation(x=t0 + (t1 - t0) / 2, y=(v0 + v1) / 2, showarrow=False, yshift=14, font_color=c,
text=f"{label} (decided by {f['cur']['decided_by'].replace('_', ' ')}) · "
f"Δ night end {f['cur']['delta_night_end_v']:+} V")
fig.update_xaxes(range=[midnight - timedelta(days=1), midnight + timedelta(days=1)], dtick=6 * 3_600_000, tickformat="%d/%m %H:%M")
ys = [v for v in h.values() if v is not None] + [bs.FULL_CHARGE_V, bs.PLATEAU_FLOOR_V] # seuils toujours visibles
fig.update_yaxes(title_text="BusVoltage [V]", range=[min(ys) - 0.15, max(ys) + 0.15])
fig.update_layout(title=f"{station}, {d:%d %b %Y}: <span style='color:{color}'>■ {name}</span>"
+ (" · on mains, lost" if f["cur"]["hours_lost"] else " · on mains" if f["cur"]["power"] == "MAINS"
else f" · {f['cur']['state']} × {trend or 'unknown trend'}")
+ (" · provisional (day not over)" if provisional(f) else "")
+ "<br><sup>gray band: no measurement · dashed: thresholds of the daily state"
" · arrow: night end D-1 → D (trend)</sup>",
height=500, showlegend=False, margin=dict(t=120))
return fig
if __name__ == "__main__":
if len(sys.argv) < 2:
sys.exit(__doc__)
(ROOT / "out").mkdir(exist_ok=True)
2026-10-13 09:10:35 +02:00
for station, series in sorted(load_stations(sys.argv[2:] or [str(ROOT / "data" / "VERMONT")]).items()):
if "BusVoltage" not in series:
continue
try:
f = dc.focus(series, parse_day(sys.argv[1], series))
except ValueError as e:
sys.exit(f"{station} : {e} (date attendue : JJ.MM ou JJ.MM.AAAA)")
print(summary(station, f))
path = ROOT / "out" / f"{station}_focus_{f['day']}.html"
fig = figure(station, f)
fig.write_html(path, include_plotlyjs="cdn")
fig.write_json(path.with_suffix(".json"))
print(path)
open_html(path)