Add the diagnostic agent's plot tool and matplotlib (D-046)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
maximeandClaude Opus 5.5 committed 2026-10-14 15:14:11 +02:00
1 parent f33f09dbf6
commit 77fda7103d
2 files changed
+75 -1

No files matched your search

+74
View File
@@ -0,0 +1,74 @@
"""Graphique PNG des séries d'un export « advanced », pour que l'agent de diagnostic les regarde.
Usage : .venv/bin/python agents/diagnostic/outils/graphique.py data/PS_DES_COUDRES/
[--capteurs REF_G,REF_D] [--colonnes error_value,corr_x,corr_y] [--debut ...] [--fin ...]
Un panneau par colonne, une courbe par capteur, heures UTC. Imprime le chemin du PNG (out/diagnostic/).
"""
import argparse
import os
import sys
import matplotlib
matplotlib.use("Agg")
import matplotlib.dates as mdates # noqa: E402
import matplotlib.pyplot as plt # noqa: E402
from donnees import charger, est_reference, filtrer, instant # noqa: E402
RACINE = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", ".."))
COLONNES = ("error_value", "corr_x", "corr_y", "relative_x", "relative_y", "x", "y", "sigma0", "reproj_err")
def borne(t, defaut):
return t.strftime("%Y%m%dT%H%MZ") if t else defaut
def main():
a = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
a.add_argument("dossier")
a.add_argument("--capteurs", help="liste séparée par des virgules (défaut : tous)")
a.add_argument("--colonnes", default="error_value,corr_x,corr_y")
a.add_argument("--debut", type=instant)
a.add_argument("--fin", type=instant)
o = a.parse_args()
par = charger(o.dossier)
if not par:
sys.exit(f"Aucun export « advanced » dans {o.dossier} (voir inventaire.py).")
noms = o.capteurs.split(",") if o.capteurs else sorted(par, key=lambda s: (not est_reference(par[s]), s))
colonnes = o.colonnes.split(",")
for demandes, connus, quoi in ((noms, par, "Capteurs"), (colonnes, COLONNES, "Colonnes")):
absents = [x for x in demandes if x not in connus]
if absents:
sys.exit(f"{quoi} inconnus : {', '.join(absents)}. Connus : {', '.join(sorted(connus))}.")
series = {s: filtrer(par[s], o.debut, o.fin) for s in noms}
if not any(series.values()):
sys.exit("Aucune mesure dans la fenêtre demandée.")
fig, axes = plt.subplots(len(colonnes), 1, sharex=True, figsize=(14, 3.2 * len(colonnes)), squeeze=False)
tab20 = plt.get_cmap("tab20").colors
couleurs = tab20[::2] + tab20[1::2] # teintes foncées d'abord : deux capteurs voisins ne partagent pas une teinte
for ax, col in zip(axes[:, 0], colonnes):
for i, s in enumerate(noms):
ms = [m for m in series[s] if m[col] is not None]
ax.plot([m["t"] for m in ms], [m[col] for m in ms], ".-", ms=2, lw=0.7,
color=couleurs[i % len(couleurs)], label=s)
ax.set_ylabel(col)
ax.grid(alpha=0.3)
axes[0, 0].legend(loc="upper left", bbox_to_anchor=(1.0, 1.0), fontsize=8)
axes[-1, 0].xaxis.set_major_formatter(mdates.DateFormatter("%d/%m\n%H:%MZ"))
station = os.path.basename(os.path.normpath(o.dossier))
fig.suptitle(f"{station} : {', '.join(colonnes)} (heures UTC)")
dossier_sortie = os.path.join(RACINE, "out", "diagnostic")
os.makedirs(dossier_sortie, exist_ok=True)
qui = "-".join(noms) if o.capteurs else "tous"
sortie = os.path.join(dossier_sortie, f"{station}_{'-'.join(colonnes)}_{qui}_"
f"{borne(o.debut, 'debut')}_{borne(o.fin, 'fin')}.png")
fig.savefig(sortie, dpi=100, bbox_inches="tight")
print(sortie)
if __name__ == "__main__":
main()