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 some sensors of a station over [FROM, TO), each error_value with its MAD score and whether visibility.py counts it high (K_MAD and FACTOR). Args: <station folder> <from ISO> <to ISO> SENSOR...
import sys
from datetime import datetime
sys.path[:0] = ["/home/maxime/aimsight-detectors/scripts", "/home/maxime/aimsight-tools/scripts"]
from data import load # noqa: E402
from episodes import level # noqa: E402
import visibility as v # noqa: E402
folder, a, b, *sensors = sys.argv[1:]
a, b = (datetime.fromisoformat(x.replace("Z", "+00:00")) for x in (a, b))
ms = load(folder)
for s in sensors:
e = [m["error_value"] for m in ms[s] if m["error_value"] is not None]
med, mad = level(e)
print(s, f"median {med:.3g} MAD {mad:.3g} threshold {ms[s][0]['error_threshold']}")
for m in ms[s]:
if a <= m["t"] < b and m["error_value"] is not None:
x = m["error_value"]
high = x > med + v.K_MAD * mad and x > v.FACTOR * med
print(" ", m["t"].strftime("%m-%d %H:%M"), f"{x:.3g}", f"{(x - med) / mad:5.1f} MAD", "HIGH" if high else "")
@@ -0,0 +1,8 @@
# Print the labels of a JSONL file touching [FROM, TO): id, start, end, family, description. Args: file FROM TO
import json, sys
f, a, b = sys.argv[1:4]
for line in open(f):
if not line.strip(): continue
l = json.loads(line)
if l["start"] < b and l["end"] >= a:
print(l["id"], l["start"], l["end"], l["family"], "|", l["description"])
@@ -0,0 +1,23 @@
# Lists the Perturbation labels of the given stations that a Perturbation event of detectors copy A overlaps and no Perturbation event of copy B does (what B absorbed). Args: <labels folder> <data folder> <detectors A> <detectors B> STATION...
import json
import subprocess
import sys
from pathlib import Path
labels_dir, data_dir, a, b, *stations = sys.argv[1:]
def perturbations(det, st):
out = subprocess.run([sys.executable, str(Path(det) / "scripts" / "categories.py"), str(Path(data_dir) / st)],
capture_output=True, text=True).stdout
return [(l.split()[0], l.split()[2]) for l in out.splitlines() if " Perturbation " in l]
for st in stations:
pa, pb = perturbations(a, st), perturbations(b, st)
for l in map(json.loads, filter(str.strip, open(Path(labels_dir) / f"{st}.jsonl"))):
if l["family"] != "Perturbation":
continue
hit = lambda ev: any(s <= l["end"] and e >= l["start"] for s, e in ev) # noqa: E731
if hit(pa) and not hit(pb):
print(st, l["id"], l["start"], l["end"], "|", l["description"][:200])
@@ -0,0 +1,23 @@
# Applies one pruning variant (P1..P5: a rule of categories.py removed) to the categories.py of a copy of the detectors, by exact text replacement; fails if the text is not found. Args: <copy dir> <variant>
import sys
from pathlib import Path
H = ''' e, h) and h["kind"] in ("Obstruction", "Target issue") and (h["start"] == h["end"] or set(e["sensors"]) <= set(
h["sensors"])))), None)'''
VARIANTS = {
"P1": [(H, ''' e, h) and h["kind"] == "Obstruction" and (h["start"] == h["end"] or set(e["sensors"]) <= set(
h["sensors"])))), None)''')], # a jump back never joins a Target issue
"P2": [(H, ''' e, h) and h["kind"] in ("Obstruction", "Target issue"))), None)''')], # no sensor condition
"P3": [('(h["kind"] == "Visibility" and overlap(near, h)', '(h["kind"] == "Visibility" and overlap(e, h)')], # no MERGE look-back
"P4": [(''' e["sensors"] = [s for s in e["sensors"] if not any(s in h["sensors"] and overlap(e, h) for h in issues)]''',
''' pass''')], # Obstruction keeps targets of a Target issue
"P5": [('''variety(m[0]) == variety(g[0]) and (g[0]["kind"] not in (''',
'''variety(m[0]) == variety(g[0]) and (True or g[0]["kind"] not in (''')], # merge without the same target
}
path = Path(sys.argv[1]) / "scripts" / "categories.py"
src = path.read_text()
for old, new in VARIANTS[sys.argv[2]]:
if src.count(old) != 1:
sys.exit(f"{sys.argv[2]}: text not found once")
src = src.replace(old, new)
path.write_text(src)
@@ -0,0 +1,18 @@
# Prints, per hour, the median over sensors of the error_value agitation ratio (median |delta error_value| over its calm), the variant tried for the heat-shimmer gate. Args: <station folder> <from> <to>
import sys, statistics
from datetime import datetime, timezone, timedelta
sys.path[:0] = ["/home/maxime/aimsight-detectors/scripts", "/home/maxime/aimsight-tools/scripts"]
from data import load
import visibility as v
day = lambda d: datetime.strptime(d, "%Y-%m-%d").replace(tzinfo=timezone.utc)
a, b = day(sys.argv[2]), day(sys.argv[3])
ms = {s: k for s, x in load(sys.argv[1]).items() if (k := [m for m in x if a - timedelta(days=3) <= m["t"] < b])}
hours = {}
for s, x in ms.items():
e = [m for m in x if m["error_value"] is not None]
r = v._ratios([(q["t"], abs(q["error_value"] - p["error_value"])) for p, q in zip(e, e[1:])])
for h, val in r.items():
hours.setdefault(h, []).append(val)
for h, r in sorted(hours.items()):
if h >= a:
print(h.strftime("%m-%d %H"), f"errag={statistics.median(r):.2f}")
@@ -0,0 +1,24 @@
# Prints, per hour, the heat-shimmer statistics of visibility.heat_shimmer: share of sensors agitated >= RATIO, median agitation and median error_value ratio. Args: <station folder> <from> <to> [detectors dir]
import sys, statistics
from datetime import datetime, timezone, timedelta
from pathlib import Path
det = Path(sys.argv[4] if len(sys.argv) > 4 else "/home/maxime/aimsight-detectors") / "scripts"
sys.path[:0] = [str(det), "/home/maxime/aimsight-tools/scripts"]
from data import load
import visibility as v
day = lambda d: datetime.strptime(d, "%Y-%m-%d").replace(tzinfo=timezone.utc)
a, b = day(sys.argv[2]), day(sys.argv[3])
ms = {s: k for s, x in load(sys.argv[1]).items() if (k := [m for m in x if a - timedelta(days=3) <= m["t"] < b])}
hours = {}
for s, x in ms.items():
ag = v._ratios([(q["t"], abs(q["corr_x"] - p["corr_x"]) + abs(q["corr_y"] - p["corr_y"]))
for p, q in zip(x, x[1:]) if p["corr_x"] is not None and q["corr_x"] is not None])
er = v._ratios([(m["t"], m["error_value"]) for m in x 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 h < a:
continue
sh = sum(x >= v.RATIO for x, _ in r.values()) / len(r)
print(h.strftime("%m-%d %H"), f"n={len(r):2d} share={sh:.2f} agit={statistics.median(x for x,_ in r.values()):.2f} err={statistics.median(e for _,e in r.values()):.2f}",
"TURB" if sh >= v.SHARE and statistics.median(e for _, e in r.values()) >= v.RATIO else "")
@@ -0,0 +1,46 @@
# Per station, the hours where at least SHARE of the sensors are agitated (visibility.heat_shimmer, without its error gate), binned by median agitation and by median error_value level ratio, counted inside / outside a Visibility label. Args: <labels folder> <data folder> [detectors dir]
import json
import statistics
import sys
from collections import Counter
from datetime import datetime
from pathlib import Path
det = Path(sys.argv[3] if len(sys.argv) > 3 else "/home/maxime/aimsight-detectors") / "scripts"
sys.path[:0] = [str(det), "/home/maxime/aimsight-tools/scripts"]
from data import load # noqa: E402
import visibility as v # noqa: E402
labels_dir, data_dir = Path(sys.argv[1]), Path(sys.argv[2])
when = lambda s: datetime.fromisoformat(s.replace("Z", "+00:00")) # noqa: E731
bins = (1.5, 2.0, 2.5, 3.0, 99)
total = Counter()
for f in sorted(labels_dir.glob("*.jsonl")):
st = f.stem
if not (data_dir / st).exists():
continue
vis = [(when(l["start"]), when(l["end"])) for l in map(json.loads, filter(str.strip, open(f)))
if l["family"] == "Visibility"]
ms = load(str(data_dir / st))
hours = {}
for s, x in ms.items():
ag = v._ratios([(q["t"], abs(q["corr_x"] - p["corr_x"]) + abs(q["corr_y"] - p["corr_y"]))
for p, q in zip(x, x[1:]) if p["corr_x"] is not None and q["corr_x"] is not None])
er = v._ratios([(m["t"], m["error_value"]) for m in x if m["error_value"] is not None])
for h in ag.keys() & er.keys():
hours.setdefault(h, {})[s] = (ag[h], er[h])
c = Counter()
for h, r in hours.items():
if sum(a >= v.RATIO for a, _ in r.values()) < v.SHARE * len(r):
continue
agit = statistics.median(a for a, _ in r.values())
err = statistics.median(e for _, e in r.values())
b = next(x for x in bins if agit < x)
inside = any(a <= h + v.HOUR / 2 <= e for a, e in vis)
key = (b, "err+" if err >= v.RATIO else "err-", "in" if inside else "out")
c[key] += 1
total[key] += 1
print(st, " ".join(f"<{b}/{g}/{i}={n}" for (b, g, i), n in sorted(c.items())))
print("TOTAL")
for (b, g, i), n in sorted(total.items()):
print(f" agit<{b} {g} {i}: {n}")