sessions of 2026-11-18 (the optimization campaign; three runs without summary, interrupted and rerun)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
maximeandClaude Opus 5.5 committed 2026-11-18 17:47:59 +01:00
1 parent 8a81c53cd9
commit 0cfbd1b7bc
363 files changed
+30822

No files matched your search

@@ -0,0 +1,21 @@
"""Prints, for given sensors around an instant, error_value (in MAD above the sensor median, and / threshold), flux, corr_x, corr_y. Args: <detectors> <station folder> <iso center> <minutes half-width> <sensor,...>"""
import sys
from datetime import timedelta
from pathlib import Path
det = Path(sys.argv[1]).resolve()
sys.path[:0] = [str(det / "scripts"), str(det.parents[0] / "aimsight-tools" / "scripts")]
from data import load, parse_time # noqa
from episodes import level # noqa
c, w = parse_time(sys.argv[3]), timedelta(minutes=int(sys.argv[4]))
ms = load(sys.argv[2])
for s in sys.argv[5].split(","):
v = ms[s]
med, mad = level([m["error_value"] for m in v if m["error_value"] is not None])
print(s, f"median {med:.3g} mad {mad:.3g}")
for m in v:
if c - w <= m["t"] <= c + w:
e = m["error_value"]
z = f"{(e - med) / mad:7.1f}" if e is not None else " -"
r = f"{e / m['error_threshold']:.2f}" if e is not None and m["error_threshold"] else "-"
f = lambda k: f"{m.get(k):.3f}" if isinstance(m.get(k), float) else str(m.get(k))
print(" ", m["t"].strftime("%m-%d %H:%M"), "z", z, "ratio", r, "flux", f("flux"), "cx", f("corr_x"), "cy", f("corr_y"))
@@ -0,0 +1,21 @@
"""Builds a test station folder: one day's export of a station with x, y emptied for chosen sensors, images linked.
Usage: python3 -I blank_xy.py <station folder> <YYYYMMDD> <SENSOR,SENSOR> <new folder>"""
import csv
import os
import sys
src, day, names, dst = sys.argv[1], sys.argv[2], set(sys.argv[3].split(",")), sys.argv[4]
os.makedirs(os.path.join(dst, "displacement"), exist_ok=True)
name = next(f for f in os.listdir(os.path.join(src, "displacement")) if day in f)
with open(os.path.join(src, "displacement", name), newline="") as f:
rows = list(csv.DictReader(f))
for r in rows:
if r["sensor_name"] in names:
r["x"] = r["y"] = ""
with open(os.path.join(dst, "displacement", name), "w", newline="") as f:
w = csv.DictWriter(f, fieldnames=list(rows[0]))
w.writeheader()
w.writerows(rows)
if not os.path.exists(os.path.join(dst, "images")):
os.symlink(os.path.abspath(os.path.join(src, "images")), os.path.join(dst, "images"))
print(os.path.join(dst, "displacement", name), len(rows), "rows")
@@ -0,0 +1,29 @@
"""Prints, per target and axis, the daily levels, amplitude and whole-window slow-drift statistics of displacement.py. Args: <detectors> <station folder> <from> <to> [targets,...]"""
import sys
from datetime import datetime, timedelta, timezone
from pathlib import Path
det = Path(sys.argv[1]).resolve()
sys.path[:0] = [str(det / "scripts"), str(det.parents[0] / "aimsight-tools" / "scripts")]
from data import load, is_reference # noqa
import displacement as D # noqa
day = lambda d: datetime.strptime(d, "%Y-%m-%d").replace(tzinfo=timezone.utc)
a, b = day(sys.argv[3]) - timedelta(days=3), day(sys.argv[4])
ms = {s: [m for m in v if a <= m["t"] < b] for s, v in load(sys.argv[2]).items()}
want = sys.argv[5].split(",") if len(sys.argv) > 5 else None
for s, v in sorted(ms.items()):
if is_reference(v) or (want and s not in want):
continue
for col in ("corr_x", "corr_y"):
ds, lv, ampl, _ = D._days(v, col)
if len(ds) < D.DAYS:
continue
w = D._whole(ds, lv, ampl, None)
pairs = [(i, j) for i in range(len(ds)) for j in range(i + 1, len(ds))]
slope = sorted((lv[j] - lv[i]) / (ds[j] - ds[i]).days for i, j in pairs)[len(pairs) // 2]
tau = sum((lv[j] > lv[i]) - (lv[j] < lv[i]) for i, j in pairs) / len(pairs)
d = slope * (ds[-1] - ds[0]).days
step = max(abs(y - x) for x, y in zip(lv, lv[1:]))
print(f"{s} {col} n={len(ds)} ampl={ampl:.3f} drift={d:+.3f} ({d/ampl if ampl else 0:+.1f} ampl) tau={tau:+.2f} "
f"step={step:.3f} whole={'YES' if w else 'no'} pieces={D._pieces(ds, lv, ampl, None) if not w else ''}")
if want:
print(" ", " ".join(f"{x.day}:{y:+.3f}" for x, y in zip(ds, lv)))
@@ -0,0 +1,22 @@
"""Removes the Kendall-tau (STEADY) condition of the slow drift from a displacement.py and its thresholds.md line. Args: <detectors folder>"""
import sys
from pathlib import Path
root = Path(sys.argv[1])
p = root / "scripts" / "displacement.py"
s = p.read_text()
for old, new in [
("at least SIZE median daily amplitudes, |Kendall tau| ≥ STEADY, and\n# no step", "at least SIZE median daily amplitudes, and no\n# step"),
("amplitudes, with\n# the same tau and step conditions;", "amplitudes, with\n# the same step condition;"),
("STEADY = 0.6 # D-055\n", ""),
(" tau = sum((lv[j] > lv[i]) - (lv[j] < lv[i]) for i, j in pairs) / len(pairs)\n", ""),
("SIZE * ampl and abs(tau) >= STEADY and step", "SIZE * ampl and step"),
(" signs = step = 0\n", " step = 0\n"),
(" signs += sum((lv[j] > lv[k]) - (lv[j] < lv[k]) for k in range(i, j)) # Kendall tau, step by step\n", ""),
("step <= abs(d) / 2 \\\n and signs * (1 if d > 0 else -1) >= STEADY * n * (n - 1) / 2:", "step <= abs(d) / 2:"),
]:
assert s.count(old) == 1, old
s = s.replace(old, new)
p.write_text(s)
t = root / "thresholds.md"
lines = [x for x in t.read_text().splitlines(keepends=True) if not x.startswith("| | `STEADY` |")]
t.write_text("".join(lines))
@@ -0,0 +1,14 @@
"""Lists the displacement.py jump episodes (start, end, family, sensors) between two instants, with each jump's size in noises. Args: <detectors> <station folder> <from day> <to day> <iso start> <iso end>"""
import sys
from datetime import datetime, timedelta, timezone
from pathlib import Path
det = Path(sys.argv[1]).resolve()
sys.path[:0] = [str(det / "scripts"), str(det.parents[0] / "aimsight-tools" / "scripts")]
from data import load # noqa
import displacement as D # noqa
day = lambda d: datetime.strptime(d, "%Y-%m-%d").replace(tzinfo=timezone.utc)
a, b = day(sys.argv[3]) - timedelta(days=3), day(sys.argv[4])
ms = {s: [m for m in v if a <= m["t"] < b] for s, v in load(sys.argv[2]).items()}
for e in D.jumps(ms):
if sys.argv[5] <= e["start"] <= sys.argv[6]:
print(e["start"], e["end"], e["kind"], len(e["sensors"]), ",".join(e["sensors"][:6]))
@@ -0,0 +1,21 @@
"""Per label of a range: its instants (bounds excluded, as score.py), how many the detectors flag in its family, and the families flagged there instead. Args: <detectors> <station folder> <labels.jsonl> <from YYYY-MM-DD> <to YYYY-MM-DD> [family]"""
import sys
from collections import Counter
from pathlib import Path
det = Path(sys.argv[1]).resolve()
sys.path[:0] = [str(det / "bench"), str(det / "scripts")]
import score # noqa
from data import iso, load, parse_time # noqa
folder, lab, a, b = sys.argv[2], sys.argv[3], sys.argv[4] + "T00:00Z", sys.argv[5] + "T00:00Z"
ms = load(folder)
labels = score.read_labels(lab, a, b)
ev = score.events(ms, a, b, folder)
inst = sorted({iso(m["t"]) for v in ms.values() for m in v if a <= iso(m["t"]) < b})
for e in labels:
if len(sys.argv) > 6 and e["family"] != sys.argv[6]:
continue
ts = [t for t in inst if e["start"] < t < e["end"]] or [t for t in inst if e["start"] <= t <= e["end"]]
fam = [{v["category"] for v in ev if v["start"] <= t <= v["end"]} for t in ts]
hit = sum(e["family"] in f for f in fam)
other = Counter(c for f in fam for c in f if c != e["family"])
print(f'{e["id"]:<16} {e["start"][5:16]} {e["family"]:<20} {hit}/{len(ts)} others: {dict(other)}')
@@ -0,0 +1,23 @@
"""Prints visibility.heat_shimmer's per-hour stats (share of sensors agitated at RATIO, median error ratio) between two instants of a range. Args: <detectors> <station folder> <from day> <to day> <iso start> <iso end>"""
import statistics
import sys
from datetime import datetime, timedelta, timezone
from pathlib import Path
det = Path(sys.argv[1]).resolve()
sys.path[:0] = [str(det / "scripts"), str(det.parents[0] / "aimsight-tools" / "scripts")]
from data import load, iso # noqa
import visibility as V # noqa
day = lambda d: datetime.strptime(d, "%Y-%m-%d").replace(tzinfo=timezone.utc)
a, b = day(sys.argv[3]) - timedelta(days=3), day(sys.argv[4])
ms = {s: [m for m in v if a <= m["t"] < b] for s, v in load(sys.argv[2]).items()}
hours = {}
for s, v in ms.items():
ag = V._ratios([(y["t"], abs(y["corr_x"] - x["corr_x"]) + abs(y["corr_y"] - x["corr_y"]))
for x, y in zip(v, v[1:]) if x["corr_x"] is not None and y["corr_x"] is not None])
er = V._ratios([(m["t"], m["error_value"]) for m in v if m["error_value"] is not None])
for h in ag.keys() & er.keys():
hours.setdefault(h, {})[s] = (ag[h], er[h])
for h, r in sorted(hours.items()):
if sys.argv[5] <= iso(h) <= sys.argv[6]:
sh = sum(x >= V.RATIO for x, _ in r.values()) / len(r)
print(iso(h), f"agitated share {sh:.2f} median agit {statistics.median(x for x, _ in r.values()):.2f} median err {statistics.median(e for _, e in r.values()):.2f}")
@@ -0,0 +1,23 @@
"""Prints why thermal_displacement._wave accepts or rejects a station window: axes, concerned share, sine R2 share, wave profile. Args: <detectors> <station folder> <from> <to>"""
import statistics
import sys
from datetime import datetime, timedelta, timezone
from pathlib import Path
det = Path(sys.argv[1]).resolve()
sys.path[:0] = [str(det / "scripts"), str(det.parents[0] / "aimsight-tools" / "scripts")]
from data import load, is_reference # noqa
import thermal_displacement as T # noqa
day = lambda d: datetime.strptime(d, "%Y-%m-%d").replace(tzinfo=timezone.utc)
a, b = day(sys.argv[3]) - timedelta(days=3), day(sys.argv[4])
ms = {s: [m for m in v if a <= m["t"] < b] for s, v in load(sys.argv[2]).items()}
for cols in (("corr_x", "corr_y"), ("x", "y")):
targets = {s: v for s, v in ms.items() if not is_reference(v)}
axes = [(s, c, *r) for s, v in targets.items() for c in cols if (r := T._axis(v, c))]
conc = [x for x in axes if x[3] and statistics.median(x[3].values()) >= T.REPRO]
print(cols, "axes", len(axes), "targets", len({x[0] for x in axes}), "concerned targets", len({x[0] for x in conc}))
for x in axes:
print(" ", x[0], x[1], "days", len(x[3]), "median likeness %.2f" % (statistics.median(x[3].values()) if x[3] else 0))
r2 = {s: [r for c in cols if (r := T._sine_r2(v, c)) is not None] for s, v in targets.items()}
r2 = {s: v for s, v in r2.items() if v}
print(" R2>=%.1f:" % T.R2_MIN, sum(max(v) >= T.R2_MIN for v in r2.values()), "of", len(r2),
" ".join(f"{s}:{max(v):.2f}" for s, v in sorted(r2.items())))