Organize the project by domain and name analyses by their rule
Energy code moves to src/energy/ and its docs to docs/energy/; shared code (CSV loading, venv switch, browser, zoom script) goes to src/common/, and the AIMsight originals to docs/aimsight/. Analyses are no longer numbered: two Energy scripts remain, daily.py (delivered state and trend) and all_analyses.py (comparison of the four). Calculations and pages unchanged (D-026). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
77c8f24d2f
commit
8a32f4d418
44 files changed
+1757
-771
No files matched your search
Whitespace-only changes.
@@ -0,0 +1,59 @@
|
||||
"""Pages HTML du poste de dev : bascule sur .venv si plotly manque, ouverture dans le navigateur, zoom (D-013).
|
||||
|
||||
À importer avant plotly : si plotly n'est pas installé, l'import relance le script sous .venv/bin/python.
|
||||
"""
|
||||
import importlib.util
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import webbrowser
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
VENV = ROOT / ".venv" / "bin" / "python"
|
||||
if importlib.util.find_spec("plotly") is None and VENV.exists():
|
||||
os.execv(VENV, [str(VENV), *sys.argv]) # plotly n'est installé que dans .venv
|
||||
|
||||
# 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);
|
||||
});
|
||||
"""
|
||||
|
||||
|
||||
def open_html(path):
|
||||
if shutil.which("explorer.exe") and shutil.which("wslpath"): # WSL : navigateur Windows
|
||||
subprocess.run(["explorer.exe", subprocess.check_output(["wslpath", "-w", path], text=True).strip()])
|
||||
else:
|
||||
webbrowser.open(Path(path).resolve().as_uri())
|
||||
@@ -0,0 +1,67 @@
|
||||
"""Chargement des exports CSV des stations, commun à tous les domaines.
|
||||
|
||||
Format des CSV : docs/domaine/ce-que-mesure-la-station.md. Bibliothèque standard uniquement.
|
||||
"""
|
||||
import csv
|
||||
import glob
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from datetime import datetime
|
||||
|
||||
NAME_RE = re.compile(r"^(?P<station>[^_]+)_(?P<metric>.+?)_\d{4}_\d{2}_\d{2}_\d{2}_\d{2} to .+\.csv$")
|
||||
|
||||
|
||||
def parse_name(path):
|
||||
"""'<STATION>_<Metric>_<début> to <fin>.csv' -> (station, metric), ou None."""
|
||||
m = NAME_RE.match(os.path.basename(path))
|
||||
return (m["station"], m["metric"]) if m else None
|
||||
|
||||
|
||||
def load_csv(path):
|
||||
"""CSV ',time_utc,metric' -> {datetime UTC: float ou None (pas de mesure)}."""
|
||||
try:
|
||||
with open(path, newline="") as f:
|
||||
rows = csv.reader(f)
|
||||
next(rows)
|
||||
return {datetime.fromisoformat(r[1]): float(r[2]) if r[2] else None for r in rows}
|
||||
except (StopIteration, IndexError, ValueError) as e:
|
||||
raise ValueError(f"{path} : CSV illisible ({e!r})") from e
|
||||
|
||||
|
||||
def load_stations(paths):
|
||||
"""Fichiers et/ou dossiers -> {station: {metric: série}}."""
|
||||
files = []
|
||||
for p in paths:
|
||||
files += sorted(glob.glob(os.path.join(p, "*.csv"))) if os.path.isdir(p) else [p]
|
||||
stations, seen = {}, {}
|
||||
for path in files:
|
||||
real = os.path.realpath(path)
|
||||
if real in seen.values():
|
||||
continue
|
||||
key = parse_name(path)
|
||||
if key is None:
|
||||
print(f"ignoré (nom non reconnu) : {path}", file=sys.stderr)
|
||||
continue
|
||||
if key in seen:
|
||||
raise ValueError(f"doublon {key[0]}/{key[1]} : {seen[key]} et {path}")
|
||||
seen[key] = real
|
||||
try:
|
||||
stations.setdefault(key[0], {})[key[1]] = load_csv(path)
|
||||
except ValueError as e:
|
||||
print(f"ignoré : {e}", file=sys.stderr)
|
||||
return stations
|
||||
|
||||
|
||||
def gaps(v):
|
||||
"""Plages de créneaux sans mesure : [(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
|
||||
Reference in new issue
Block a user