"""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 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([]) def series(serie, nom, t0, t1): """Temps, error_value / seuil, flux en % du flux 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], "flux") return ([d["t"] for d in s], [d["error_value"] / d["error_threshold"] for d in s], [max(d["flux"], 1e-9) / ref[d["t"].hour] * 100 for d in s]) def panneaux(axe, axf, serie, points, t0, t1, instants): for nom, c, lab in points: tt, ev, fl = series(serie, nom, t0, t1) 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) 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("lumière renvoyée par la cible\n(flux, % du niveau habituel)") 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 / "fig1_visibilite_nuit-26-10_LENZSPITZE.png") def fig2(serie): """Occultation du point 92H par une flèche de grue le 30.10 : seul le flux de 92H s'effondre.""" pts = [("92H", COUL[2], "92H (56 m)"), ("8002", COUL[1], "8002 (133 m)"), ("8017", COUL[0], "8017 (15 m)")] fig = plt.figure(figsize=(16, 10), dpi=150) g = fig.add_gridspec(3, 3, height_ratios=[1.25, 1, 1], hspace=0.35, wspace=0.04) zone = (900, 620, 380, 260) for i, (nom, tit) in enumerate([("20261030T1301Z", "13:01 UTC : avant"), ("20261030T1401Z", "14:01 UTC : charge d'un engin de levage contre 92H"), ("20261030T1501Z", "15:01 UTC : après")]): vignette(fig.add_subplot(g[0, i]), nom, zone, tit, [("92H", COUL[2])], serie, vmin=0, vmax=255, rayon=30) axe, axf = fig.add_subplot(g[1, :]), fig.add_subplot(g[2, :]) axf.sharex(axe) panneaux(axe, axf, serie, pts, t("2026-10-30T12:30"), t("2026-10-30T15:30"), [t("2026-10-30T14:01")]) fig.suptitle("LENZSPITZE (Crissier) : point 92H masqué par un obstacle temporaire, 30.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 / "fig2_occultation_92H_30-10_LENZSPITZE.png") def fig3(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 / "fig3_vue-ensemble_hors-seuil_LENZSPITZE.png") if __name__ == "__main__": serie = charger() fig1(serie) fig2(serie) fig3(serie) print("\n".join(str(p) for p in sorted(ICI.glob("fig*.png"))))