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,22 @@
"""Per-instant confusion: for each flagged family, the label families of its wrong instants (none = no label), and per variety. Args: detectors_dir station labels from to"""
import sys
from collections import Counter
from pathlib import Path
det, folder, lab, start, end = sys.argv[1:6]
sys.path.insert(0, str(Path(det) / "bench")); sys.path.insert(0, str(Path(det) / "scripts"))
import score
from data import iso, load
ms = load(folder)
labels = score.read_labels(lab, start, end)
evts = score.events(ms, start, end, folder)
inst = sorted({iso(m["t"]) for v in ms.values() for m in v if start <= iso(m["t"]) < end})
c, v = Counter(), Counter()
for t in inst:
a = {e["family"] for e in labels if e["start"] < t < e["end"]}
for fam in {x["category"] for x in evts if x["start"] <= t <= x["end"]} - a:
c[(fam, ",".join(sorted(a)) or "none")] += 1
for lbl in {x["episodes"][0]["label"] if x.get("episodes") else x.get("text", "")[:30] for x in evts if x["category"] == fam and x["start"] <= t <= x["end"]}:
v[(fam, lbl)] += 1
for k, n in sorted(c.items(), key=lambda x: -x[1]): print(n, k)
print("-- by variety")
for k, n in sorted(v.items(), key=lambda x: -x[1]): print(n, k)
@@ -0,0 +1,14 @@
"""Print the drift detector's daily levels of a sensor (kept days, level, amplitude). Args: detectors_dir station sensor from to"""
import sys
from datetime import datetime, timezone
from pathlib import Path
det, folder, sensor, start, end = sys.argv[1:6]
sys.path.insert(0, str(Path(det) / "scripts")); sys.path.insert(0, str(Path.home() / "aimsight-tools/scripts"))
import displacement as D
from data import load, parse_time
ms = [m for m in load(folder)[sensor] if parse_time(start) <= m["t"] < parse_time(end)]
for col in ("corr_x", "corr_y"):
ds, lv, ampl, _ = D._days(ms, col)
print(col, "ampl", round(ampl, 3), "whole", D._whole(ds, lv, ampl, _) if len(ds) > 1 else None, "pieces", D._pieces(ds, lv, ampl, _) if len(ds) > 1 else None)
for d, l in zip(ds, lv):
print(" ", d, round(l, 3))
@@ -0,0 +1,28 @@
"""Every Slow drift episode on the benchmark: station, sensor, axis, kind (whole/piece), drift/ampl, steps, share of its instants in a Displacement label. Args: detectors_dir labels_dir data_dir"""
import sys
from datetime import timedelta
from pathlib import Path
det, labdir, datadir = sys.argv[1:4]
sys.path.insert(0, str(Path(det) / "bench")); sys.path.insert(0, str(Path(det) / "scripts"))
import score, regression, displacement as D
from data import load, parse_time, iso
for path in sorted(Path(labdir).glob("*.jsonl")):
folder = Path(datadir) / path.stem
if not folder.is_dir(): continue
start, end = regression.label_range(path)
labels = score.read_labels(str(path), start, end)
h, b = parse_time(start) - score.HISTORY, parse_time(end)
ms = {s: k for s, v in load(str(folder)).items() if (k := [m for m in v if h <= m["t"] < b])}
for s, sm in sorted(ms.items()):
for col in ("corr_x", "corr_y"):
a = D._days(sm, col)
if len(a[0]) < 2: continue
ds, lv, ampl, sp = a
for kind, found in (("whole", D._whole(*a)), ("piece", D._pieces(*a) if not D._whole(*a) else [])):
for d, i, j in found:
st, en = iso(sp[i][0]), iso(sp[j][1])
steps = [round(abs(lv[k + 1] - lv[k]) / abs(d), 2) for k in range(i, j)]
gaps = [(ds[k + 1] - ds[k]).days for k in range(i, j)]
inst = sorted({iso(m["t"]) for m in sm if st <= iso(m["t"]) <= en and iso(m["t"]) >= start})
ok = sum(any(e["family"] == "Displacement" and e["start"] < t < e["end"] for e in labels) for t in inst)
print(f"{path.stem:11} {s:8} {col} {kind} {st[:10]}→{en[:10]} d/ampl={abs(d)/ampl:.1f} n={j-i+1} maxstep={max(steps)} steps={steps} gaps={gaps} disp={ok}/{len(inst)}")
@@ -0,0 +1,14 @@
"""Per measurement of a sensor in a window: value, distance to the median of the BASE previous, in noises (as displacement._jumps sees it). Args: detectors_dir station sensor axis from to [hist_from]"""
import sys, statistics
from pathlib import Path
det, folder, sensor, axis, a, b = sys.argv[1:7]
h = sys.argv[7] if len(sys.argv) > 7 else "2026-09-04"
sys.path.insert(0, str(Path(det) / "scripts")); sys.path.insert(0, str(Path.home() / "aimsight-tools/scripts"))
import displacement as D
from episodes import noise
from data import load, parse_time, iso
ms = [m for m in load(folder)[sensor] if parse_time(h) <= m["t"] < parse_time(b) and m[axis] is not None]
v = [m[axis] for m in ms]; n = noise(v); print("noise", round(n, 4), "K*n", round(D.K * n, 3))
for i in range(D.BASE, len(v)):
if iso(ms[i]["t"]) >= a:
base = statistics.median(v[i - D.BASE:i]); print(iso(ms[i]["t"]), round(v[i], 3), round((v[i] - base) / n, 1))
@@ -0,0 +1,32 @@
"""Per label: instants found by its family, and families flagged on it; per event: overlapping labels. Args: detectors_dir station labels from to [family]"""
import sys
from pathlib import Path
det, folder, lab, start, end = sys.argv[1:6]
fam = sys.argv[6] if len(sys.argv) > 6 else None
sys.path.insert(0, str(Path(det) / "bench")); sys.path.insert(0, str(Path(det) / "scripts"))
import score
from data import iso, load
ms = load(folder)
labels = score.read_labels(lab, start, end)
evts = score.events(ms, start, end, folder)
inst = sorted({iso(m["t"]) for v in ms.values() for m in v if start <= iso(m["t"]) < end})
print("== LABELS")
for e in sorted(labels, key=lambda e: e["start"]):
if fam and e["family"] != fam: 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"]]
hit = sum(any(v["category"] == e["family"] and v["start"] <= t <= v["end"] for v in evts) for t in ts)
other = {}
for t in ts:
for v in evts:
if v["start"] <= t <= v["end"] and v["category"] != e["family"]:
other[v["category"]] = other.get(v["category"], 0) + 1
print(f'{e["id"]:16} {e["start"][:16]} {e["end"][:16]} {e["family"]:20} {hit}/{len(ts)} other={other}')
print("== EVENTS (flagged instants not in a label of their family)")
for v in evts:
if fam and v["category"] != fam: continue
ts = [t for t in inst if v["start"] <= t <= v["end"] and t >= start]
ok = sum(any(e["family"] == v["category"] and e["start"] < t < e["end"] for e in labels) for t in ts)
if ok < len(ts):
ov = [e["id"] + ":" + e["family"][:5] for e in labels if e["start"] <= v["end"] and e["end"] >= v["start"]]
lbl = v.get("episodes", [{}])
print(f'{v["start"]} {v["end"]} {v["category"]:20} {ok}/{len(ts)} {v.get("text","")[:50]!r} {len(v.get("sensors",[]))}s ov={ov[:6]}')
@@ -0,0 +1,9 @@
#!/bin/bash
# Run the benchmark of each pruning variant on its own copy: run_variants.sh <base copy> <work dir> <optimizer root> <variant>...
base=$1; work=$2; root=$3; shift 3
T=$(dirname "$0")
for v in "$@"; do
rm -rf "$work/$v"; cp -r "$base" "$work/$v"; python3 "$T/variant.py" "$work/$v" "$v" || continue
(cd "$root" && python3 "$work/$v/bench/regression.py" --labels labeling/auto --data data > "$work/$v.txt" 2>&1) &
done
wait
@@ -0,0 +1,27 @@
"""Apply one pruning variant (a rule removed) to a copy of the detectors: variant.py <copy dir> <variant name>; --list lists them."""
import sys
from pathlib import Path
V = {
"whole_step": ("displacement.py", "abs(d) >= SIZE * ampl and step <= abs(d) / 2 and back", "abs(d) >= SIZE * ampl and back"),
"whole_retreat": ("displacement.py", " and back <= RETREAT * abs(d) else []", " else []"),
"piece_step": ("displacement.py", "if d and abs(d) >= PIECE * ampl and step <= PIECE * ampl / 2:", "if d and abs(d) >= PIECE * ampl:"),
"hours": ("displacement.py", "if len({m[\"t\"].hour for m in dm}) >= HOURS / 24 * slots)", ")"),
"no_pieces": ("displacement.py", "else [(p, a) for a in axes for p in _pieces(*a)]", "else []"),
"no_whole": ("displacement.py", "whole = [(w, a) for a in axes for w in _whole(*a)]", "whole = []"),
"together": ("displacement.py", "for name, ms in [*targets.items(), (\"\", _together(targets, axis))]:", "for name, ms in targets.items():"),
"floor": ("displacement.py", "floor = FLOOR * statistics.median(ns) if ns else 0", "floor = 0"),
}
V2 = { # after S1 (the whole-window drift removed)
"two_days": ("displacement.py", 'axes = [a for col in ("corr_x", "corr_y") if len((a := _days(ms, col))[0]) >= 2]', 'axes = [_days(ms, col) for col in ("corr_x", "corr_y")]'),
"together_one": ("displacement.py", 'if name or (state == "back" and a == b)}', 'if name or state == "back"}'),
"bridge0": ("target_issue.py", "BRIDGE = 1 ", "BRIDGE = 0 "),
"piece_tiebreak": ("displacement.py", "key=lambda x: (-abs(x[0]), x[2] - x[1])", "key=lambda x: -abs(x[0])"),
}
V.update(V2)
if sys.argv[1] == "--list":
print("\n".join(V2 if sys.argv[2:] == ["2"] else V)); sys.exit()
f, old, new = V[sys.argv[2]]
p = Path(sys.argv[1]) / "scripts" / f
s = p.read_text()
assert s.count(old) == 1, (sys.argv[2], s.count(old))
p.write_text(s.replace(old, new))