Files
2026-11-12 15:58:56 +01:00

196 lines
11 KiB
Python

"""Figures du rapport Inogy/CFF, section 4.4 « Métrique de la qualité des points », LENZSPITZE (Crissier).
Usage (racine du dépôt) : .venv/bin/python support/2026-11-12_LENZSPITZE_metrique-qualite/analyste/figures.py
Écrit fig1_*.png, fig2_*.png, fig3_*.png dans ../output/ et annexe_*.png dans ce dossier. Lecture seule de data/LENZSPITZE/."""
import sys
from collections import defaultdict
from datetime import datetime, timedelta, timezone
from pathlib import Path
import matplotlib
matplotlib.use("Agg")
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import BoundaryNorm, ListedColormap
from PIL import Image
ICI = Path(__file__).parent
sys.path.insert(0, str(ICI / "outils"))
from stats import charger, motifs, reference_calme # noqa: E402
IMAGES = Path("data/LENZSPITZE/images")
UTC = timezone.utc
plt.rcParams.update({"font.size": 11, "axes.spines.top": False, "axes.spines.right": False})
COUL = ["#1b6ca8", "#e08a00", "#b5272b"] # proche, moyen, lointain / point touché
def t(s):
return datetime.fromisoformat(s).replace(tzinfo=UTC)
def image(nom):
return np.asarray(Image.open(next(IMAGES.glob(nom + "*.jpg"))).convert("L"))
def vignette(ax, nom, zone, titre, points, serie, vmin=10, vmax=120, rayon=22):
"""Zone x, y, l, h de l'image ; cercle et nom de chaque point à sa position (x, y) de la mesure la plus proche."""
x0, y0, l, h = zone
ax.imshow(image(nom)[y0:y0 + h, x0:x0 + l], cmap="gray", vmin=vmin, vmax=vmax, extent=[x0, x0 + l, y0 + h, y0])
ti = datetime.strptime(nom[:14], "%Y%m%dT%H%MZ").replace(tzinfo=UTC)
for nom_p, c in points:
d = min(serie[nom_p], key=lambda d: abs(d["t"] - ti))
ax.add_patch(plt.Circle((d["x"], d["y"]), rayon, fill=False, color=c, lw=2))
ax.annotate(nom_p, (d["x"], d["y"]), xytext=(16, -16), textcoords="offset points", color=c, fontsize=11, fontweight="bold")
ax.set_title(titre, fontsize=11)
ax.set_xticks([]); ax.set_yticks([])
FLUX = "lumière renvoyée par la cible\n(flux, % du niveau habituel)"
NETTETE = "netteté de la tache de la cible\n(sharpness, % du niveau habituel)"
SNR = "contraste de la cible sur le fond\n(rapport signal/bruit, % du niveau habituel)"
def series(serie, nom, t0, t1, metrique="flux"):
"""Temps, error_value / seuil, métrique en % de son niveau habituel (même heure UTC, jours calmes 28-31.10)."""
s = [d for d in serie[nom] if t0 <= d["t"] <= t1]
ref = reference_calme(serie[nom], metrique)
return ([d["t"] for d in s], [d["error_value"] / d["error_threshold"] for d in s],
[max(d[metrique], 1e-9) / ref[d["t"].hour] * 100 for d in s])
def panneaux(axe, axf, serie, points, t0, t1, instants, metrique="flux", titre=FLUX):
for nom, c, lab in points:
tt, ev, fl = series(serie, nom, t0, t1, metrique)
axe.plot(tt, ev, color=c, lw=1.8, label=lab)
axf.plot(tt, fl, color=c, lw=1.8, label=lab)
axe.axhline(1, color="black", ls="--", lw=1.2)
axe.text(t0, 1.03, " seuil d'alarme (mesure jugée peu fiable au-dessus)", va="bottom", fontsize=9)
axe.set_ylabel("erreur de mesure\n(error_value / seuil)")
axe.set_ylim(0, 1.6)
if metrique == "sharpness": # écarts de quelques dizaines de %, échelle linéaire
axf.set_ylim(0, 150)
axf.set_yticks([0, 25, 50, 75, 100, 125], ["0 %", "25 %", "50 %", "75 %", "100 %", "125 %"])
else:
axf.set_yscale("log")
axf.set_ylim(0.05, 300)
axf.set_yticks([0.1, 1, 10, 100], ["0,1 %", "1 %", "10 %", "100 %"])
axf.axhline(100, color="grey", ls=":", lw=1)
axf.set_ylabel(titre)
for ax in (axe, axf):
for ti in instants:
ax.axvline(ti, color="grey", lw=1, ls=":")
ax.set_xlim(t0, t1)
ax.grid(axis="y", color="#dddddd", lw=0.6)
axf.xaxis.set_major_formatter(mdates.DateFormatter("%d.%m %H:%M", tz=UTC))
axf.set_xlabel("heure UTC")
axe.legend(loc="upper left", bbox_to_anchor=(1.0, 1.0), frameon=False, fontsize=10)
def fig1(serie):
"""Perte de visibilité nocturne du 26.10 : la lumière renvoyée baisse d'autant plus que le point est loin."""
pts = [("1021", COUL[0], "1021 (16 m)"), ("202H", COUL[1], "202H (47 m)"), ("8002", COUL[2], "8002 (133 m)")]
fig = plt.figure(figsize=(16, 10), dpi=150)
g = fig.add_gridspec(3, 2, height_ratios=[1.0, 1, 1], hspace=0.3, wspace=0.04)
zone = (1000, 700, 1900, 700)
vignette(fig.add_subplot(g[0, 0]), "20261029T0301Z", zone, "Nuit normale : 29.10 à 03:01 UTC",
[(n, c) for n, c, _ in pts], serie)
vignette(fig.add_subplot(g[0, 1]), "20261026T0300Z", zone, "Nuit du 26.10 à 03:00 UTC : les points lointains ne sont plus visibles",
[(n, c) for n, c, _ in pts], serie)
axe, axf = fig.add_subplot(g[1, :]), fig.add_subplot(g[2, :])
axf.sharex(axe)
panneaux(axe, axf, serie, pts, t("2026-10-25T20:00"), t("2026-10-26T11:00"), [t("2026-10-26T03:00")])
fig.suptitle("LENZSPITZE (Crissier) : perte de visibilité dans la nuit du 26.10.2026", fontsize=14, x=0.02, ha="left")
fig.subplots_adjust(left=0.08, right=0.86, top=0.93, bottom=0.07)
fig.savefig(ICI.parent / "output" / "fig1_visibilite_nuit-26-10_LENZSPITZE.png")
def fig2(serie):
"""Soleil bas dans le champ, matin du 02.11 : le contraste des cibles proches du soleil s'effondre, leur lumière non."""
pts = [("202H", COUL[2], "202H (47 m)"), ("101B", COUL[1], "101B (47 m)"), ("1009", COUL[0], "1009 (45 m, témoin)")]
fig = plt.figure(figsize=(16, 10), dpi=150)
g = fig.add_gridspec(3, 2, height_ratios=[1.25, 1, 1], hspace=0.3, wspace=0.04)
zone = (1700, 600, 800, 500)
vignette(fig.add_subplot(g[0, 0]), "20261031T0701Z", zone, "31.10 à 07:01 UTC : ciel couvert",
[(n, c) for n, c, _ in pts], serie, vmin=0, vmax=255)
vignette(fig.add_subplot(g[0, 1]), "20261102T0701Z", zone, "02.11 à 07:01 UTC : soleil bas dans le champ, juste au-dessus des cibles",
[(n, c) for n, c, _ in pts], serie, vmin=0, vmax=255)
axe, axf = fig.add_subplot(g[1, :]), fig.add_subplot(g[2, :])
axf.sharex(axe)
t0, t1 = t("2026-11-02T05:30"), t("2026-11-02T09:30")
panneaux(axe, axf, serie, pts, t0, t1, [t("2026-11-02T07:01")], "snr", SNR)
tt, _, fl = series(serie, "202H", t0, t1, "flux")
axf.plot(tt, fl, color=COUL[2], lw=1.2, ls="--", label="202H : lumière\nrenvoyée (flux)")
axf.legend(loc="upper left", bbox_to_anchor=(1.0, 1.0), frameon=False, fontsize=10)
axf.set_ylim(0.5, 300)
axf.set_yticks([1, 10, 100], ["1 %", "10 %", "100 %"])
axf.xaxis.set_major_formatter(mdates.DateFormatter("%d.%m %H:%M", tz=UTC))
fig.suptitle("LENZSPITZE (Crissier) : éblouissement par le soleil bas, matin du 02.11.2026", fontsize=14, x=0.02, ha="left")
fig.subplots_adjust(left=0.08, right=0.84, top=0.93, bottom=0.07)
fig.savefig(ICI.parent / "output" / "fig2_eblouissement-soleil_matin-02-11_LENZSPITZE.png")
def fig3(serie):
"""Passage d'un train le 01.11 à 11:00 (image de la même minute) : la tache de toutes les cibles perd sa netteté, pas sa lumière."""
pts = [("1001", COUL[2], "1001 (64 m)"), ("1012", COUL[1], "1012 (40 m)"), ("1016", "#7a3fa0", "1016 (30 m)"),
("1021", COUL[0], "1021 (16 m, témoin)")]
fig = plt.figure(figsize=(16, 10), dpi=150)
g = fig.add_gridspec(3, 3, height_ratios=[1.1, 1, 1], hspace=0.3, wspace=0.04)
zone = (1150, 560, 1000, 760)
for i, (nom, tit) in enumerate([("20261101T1001Z", "10:01 UTC : avant"),
("20261101T1100Z", "11:00 UTC : un train passe sur la voie"),
("20261101T1201Z", "12:01 UTC : après")]):
vignette(fig.add_subplot(g[0, i]), nom, zone, tit, [(n, c) for n, c, _ in pts], serie, vmin=0, vmax=255, rayon=16)
axe, axf = fig.add_subplot(g[1, :]), fig.add_subplot(g[2, :])
axf.sharex(axe)
t0, t1 = t("2026-11-01T10:00"), t("2026-11-01T12:30")
panneaux(axe, axf, serie, pts, t0, t1, [t("2026-11-01T11:00")], "sharpness", NETTETE)
tt, _, fl = series(serie, "1012", t0, t1, "flux")
axf.plot(tt, fl, color=COUL[1], lw=1.2, ls="--", label="1012 : lumière\nrenvoyée (flux)")
axf.legend(loc="upper left", bbox_to_anchor=(1.0, 1.0), frameon=False, fontsize=10)
axf.xaxis.set_major_formatter(mdates.DateFormatter("%d.%m %H:%M", tz=UTC))
fig.suptitle("LENZSPITZE (Crissier) : passage d'un train, 01.11.2026 à 11:00 UTC", fontsize=14, x=0.02, ha="left")
fig.subplots_adjust(left=0.08, right=0.84, top=0.93, bottom=0.07)
fig.savefig(ICI.parent / "output" / "fig3_passage-train_01-11_LENZSPITZE.png")
def annexe(serie):
"""Vue d'ensemble : part des mesures au-dessus du seuil, par point (trié par distance) et par jour."""
meta = motifs()
jours = sorted({d["t"].date() for s in serie.values() for d in s})
noms = sorted(serie, key=lambda n: -meta.get(n, {}).get("dist_m", -1))
M = np.zeros((len(noms), len(jours)))
for i, n in enumerate(noms):
c = defaultdict(lambda: [0, 0])
for d in serie[n]:
k = c[d["t"].date()]
k[0] += 1
k[1] += d["error_value"] > d["error_threshold"]
for j, jo in enumerate(jours):
M[i, j] = 100 * c[jo][1] / c[jo][0] if c[jo][0] else np.nan
bornes = [0, 0.001, 2, 10, 30, 101]
cmap = ListedColormap(["#ffffff", "#fde0c5", "#f59e5b", "#d9541e", "#8c1d04"]); cmap.set_bad("#dddddd")
fig, ax = plt.subplots(figsize=(16, 11), dpi=150)
im = ax.imshow(M, aspect="auto", interpolation="nearest", cmap=cmap, norm=BoundaryNorm(bornes, cmap.N))
lab = [f"{n} ({meta[n]['dist_m']:.0f} m)" if n in meta else f"{n} (distance inconnue)" for n in noms]
ax.set_yticks(range(len(noms)), lab, fontsize=9)
ax.set_xticks(range(len(jours)), [f"{j:%d.%m}" for j in jours], fontsize=9)
ax.set_xticks(np.arange(-0.5, len(jours)), minor=True); ax.set_yticks(np.arange(-0.5, len(noms)), minor=True)
ax.grid(which="minor", color="#eeeeee", lw=0.5); ax.tick_params(which="minor", length=0)
ax.set_xlabel("jour (UTC) ; 16.10 et 05.11 partiels")
ax.set_title("LENZSPITZE (Crissier) : part des mesures au-dessus du seuil d'alarme, par point et par jour\n"
"points classés du plus lointain (en haut) au plus proche", fontsize=13, loc="left")
cb = fig.colorbar(im, ax=ax, fraction=0.025, pad=0.02, ticks=[0.0005, 1, 6, 20, 65])
cb.ax.set_yticklabels(["0 %", "moins de 2 %", "2 à 10 %", "10 à 30 %", "plus de 30 %"])
cb.set_label("mesures du jour au-dessus du seuil")
fig.tight_layout()
fig.savefig(ICI / "annexe_vue-ensemble_hors-seuil_LENZSPITZE.png")
if __name__ == "__main__":
serie = charger()
fig1(serie)
fig2(serie)
fig3(serie)
annexe(serie)
print("\n".join(str(p) for p in sorted([*ICI.glob("annexe*.png"), *(ICI.parent / "output").glob("fig*.png")])))