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:
1 parent
8a81c53cd9
commit
0cfbd1b7bc
363 files changed
+30822
No files matched your search
@@ -0,0 +1,42 @@
|
||||
"""Print, hour by hour over a span, the visibility signals: median z of error_value (MAD above each sensor's median, as
|
||||
visibility.py), the number of high sensors (K_MAD), of rejected ones, and the median flux ratio to each sensor's median.
|
||||
Usage: python3 diffuse.py <detectors folder> <station folder> <window from> <window to> <show from ISO> <show to ISO>
|
||||
"""
|
||||
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")]
|
||||
import visibility as vis # noqa: E402
|
||||
from episodes import level # noqa: E402
|
||||
from data import load # noqa: E402
|
||||
|
||||
day = lambda d: datetime.strptime(d, "%Y-%m-%d").replace(tzinfo=timezone.utc) # noqa: E731
|
||||
a, b = day(sys.argv[3]) - timedelta(days=3), day(sys.argv[4])
|
||||
lo, hi = datetime.fromisoformat(sys.argv[5].replace("Z", "+00:00")), datetime.fromisoformat(sys.argv[6].replace("Z", "+00:00"))
|
||||
ms = {s: k for s, v in load(sys.argv[2]).items() if (k := [m for m in v if a <= m["t"] < b])}
|
||||
keys = sorted({k for v in ms.values() for m in v for k in m})
|
||||
z, hc, rj, fl = {}, {}, {}, {}
|
||||
for s, v in ms.items():
|
||||
e = [m["error_value"] for m in v if m["error_value"] is not None]
|
||||
if len(e) < 10:
|
||||
continue
|
||||
med, mad = level(e)
|
||||
fx = [m.get("flux") for m in v if m.get("flux")]
|
||||
fmed = statistics.median(fx) if fx else None
|
||||
for m in v:
|
||||
t, x = m["t"], m["error_value"]
|
||||
if x is None or not lo <= t < hi:
|
||||
continue
|
||||
h = t.replace(minute=0, second=0, microsecond=0)
|
||||
z.setdefault(h, []).append((x - med) / mad)
|
||||
hc[h] = hc.get(h, 0) + (x > med + vis.K_MAD * mad and x > vis.FACTOR * med)
|
||||
rj[h] = rj.get(h, 0) + bool(m["error_threshold"] and x > m["error_threshold"])
|
||||
if fmed and m.get("flux"):
|
||||
fl.setdefault(h, []).append(m["flux"] / fmed)
|
||||
print("fields:", keys)
|
||||
for h in sorted(z):
|
||||
print(f"{h:%m-%d %H:%M} z_med={statistics.median(z[h]):6.2f} high/h={hc[h]:4d} rejected/h={rj[h]:4d} "
|
||||
f"flux={statistics.median(fl[h]) if h in fl else float('nan'):.2f} n={len(z[h])}")
|
||||
@@ -0,0 +1,32 @@
|
||||
"""Per label: instants inside it and how many an event of its family covers; per event: instants and how many no label of
|
||||
its family covers (wrongly flagged), with the families labelled there instead.
|
||||
Usage: python3 perlabel.py <detectors folder> <station folder> <labels.jsonl> <from YYYY-MM-DD> <to YYYY-MM-DD>
|
||||
"""
|
||||
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: E402
|
||||
from data import iso, load, parse_time # noqa: E402
|
||||
|
||||
folder, lab, start, end = sys.argv[2], sys.argv[3], iso(parse_time(sys.argv[4])), iso(parse_time(sys.argv[5]))
|
||||
ms = load(folder)
|
||||
labels = [e for e in score.read_labels(lab, start, end) if e["family"] != "None"]
|
||||
evts = score.events(ms, start, end, folder)
|
||||
instants = sorted({iso(m["t"]) for v in ms.values() for m in v if start <= iso(m["t"]) < end})
|
||||
inside = lambda e, t: e["start"] < t < e["end"] # noqa: E731
|
||||
print("== labels")
|
||||
for e in labels:
|
||||
ts = [t for t in instants if inside(e, t)]
|
||||
f = sum(any(v["category"] == e["family"] and v["start"] <= t <= v["end"] for v in evts) for t in ts)
|
||||
other = Counter(v["category"] for t in ts for v in evts if v["start"] <= t <= v["end"] and v["category"] != e["family"])
|
||||
print(f"{e['id']:<14} {e['start'][5:16]} → {e['end'][5:16]} {e['family']:<21} found {f}/{len(ts)} others: {dict(other)}")
|
||||
print("== events")
|
||||
for v in evts:
|
||||
ts = [t for t in instants if v["start"] <= t <= v["end"]]
|
||||
wrong = [t for t in ts if not any(inside(e, t) and e["family"] == v["category"] for e in labels)]
|
||||
there = Counter(e["family"] for t in wrong for e in labels if inside(e, t))
|
||||
print(f"{v['start'][5:16]} → {v['end'][5:16]} {v['category']:<21} {v['episodes'][0]['label']:<28} "
|
||||
f"{len(ts):>4} instants, wrong {len(wrong):>4} {dict(there)}")
|
||||
@@ -0,0 +1,40 @@
|
||||
"""Make one copy of the detectors per rule of visibility.py removed (pruning), each next to a link to the tools repository.
|
||||
Usage: python3 prune.py <detectors folder> <tools folder> <work folder> [variant ...] (no variant: all)
|
||||
Prints the copies made; a replacement not found is an error (the rule's text changed).
|
||||
"""
|
||||
import shutil
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
VARIANTS = { # name -> [(old, new)] in scripts/visibility.py
|
||||
"factor_high": [("if x > med + K_MAD * mad and x > FACTOR * med:", "if x > med + K_MAD * mad:")],
|
||||
"factor_strong": [('if m["error_threshold"] and x > m["error_threshold"] and x > FACTOR * med:',
|
||||
'if m["error_threshold"] and x > m["error_threshold"]:')],
|
||||
"lone": [(" elif not few:\n continue\n", " else:\n continue\n")],
|
||||
"salience": [("if n(t) >= BRIEF_MIN and n(t) >= SALIENCE * max(map(n, around), default=0):", "if n(t) >= BRIEF_MIN:")],
|
||||
"brief_min": [("if n(t) >= BRIEF_MIN and n(t) >= SALIENCE", "if n(t) and n(t) >= SALIENCE")],
|
||||
"two_sensors": [("zones = [zone for zone in zones if len(zone[2]) >= 2]\n", "")],
|
||||
"not_briefs": [("if s in high.get(t, ()) and t not in briefs]", "if s in high.get(t, ())]")],
|
||||
"diffuse": [(" if len(r) >= RUN_MIN and not any(", " if False and not any(")],
|
||||
"diffuse_run": [(" if len(r) >= RUN_MIN and not any(", " if not any(")],
|
||||
"diffuse_hosts": [("if len(r) >= RUN_MIN and not any(h[\"start\"] <= e[\"start\"] and e[\"end\"] <= h[\"end\"] for h in hosts):",
|
||||
"if len(r) >= RUN_MIN:")],
|
||||
"shimmer_share": [("if sum(a >= RATIO for a, _ in r.values()) >= SHARE * len(r)\n and statistics", "if statistics")],
|
||||
"run_min": [(" if len(r) >= RUN_MIN]\n", " ]\n")],
|
||||
"shimmer_error": [(" and statistics.median(e for _, e in r.values()) >= RATIO]", " ]")],
|
||||
}
|
||||
|
||||
det, tools, work = map(Path, sys.argv[1:4])
|
||||
for name in sys.argv[4:] or VARIANTS:
|
||||
dst = work / name
|
||||
shutil.rmtree(dst, ignore_errors=True)
|
||||
shutil.copytree(det, dst / "aimsight-detectors", ignore=shutil.ignore_patterns(".git", "__pycache__"))
|
||||
(dst / "aimsight-tools").symlink_to(tools.resolve())
|
||||
p = dst / "aimsight-detectors" / "scripts" / "visibility.py"
|
||||
s = p.read_text()
|
||||
for old, new in VARIANTS[name]:
|
||||
if old not in s:
|
||||
sys.exit(f"{name}: not found: {old!r}")
|
||||
s = s.replace(old, new, 1)
|
||||
p.write_text(s)
|
||||
print(dst)
|
||||
@@ -0,0 +1,29 @@
|
||||
"""Print the camera-slide instants of thermal_displacement.slides per day, and the runs they make with several merge gaps.
|
||||
Usage: python3 slides.py <detectors folder> <station folder> <from YYYY-MM-DD> <to YYYY-MM-DD>
|
||||
"""
|
||||
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")]
|
||||
import thermal_displacement as td # noqa: E402
|
||||
from episodes import runs # noqa: E402
|
||||
from data import load, is_reference # noqa: E402
|
||||
|
||||
day = lambda d: datetime.strptime(d, "%Y-%m-%d").replace(tzinfo=timezone.utc) # noqa: E731
|
||||
a, b = day(sys.argv[3]) - timedelta(days=3), day(sys.argv[4])
|
||||
ms = {s: k for s, v in load(sys.argv[2]).items() if (k := [m for m in v if a <= m["t"] < b])}
|
||||
print("wave corr:", bool(td._wave(ms, ("corr_x", "corr_y"), "Thermal", False)),
|
||||
"wave raw:", bool(td._wave(ms, ("x", "y"), "Camera thermal", True)))
|
||||
targets = [v for v in ms.values() if not is_reference(v)]
|
||||
both = sorted(set().union(*(td._common([td._signs(v, c) for v in ms.values()]) & td._common(
|
||||
[td._signs(v, "corr_" + c) for v in targets]) for c in ("x", "y"))))
|
||||
per = {}
|
||||
for t in both:
|
||||
per.setdefault(t.date(), []).append(t.strftime("%H:%M"))
|
||||
for d, ts in sorted(per.items()):
|
||||
print(d, len(ts), ts[0], "->", ts[-1])
|
||||
for h in (1, 2, 3, 6, 12, 24):
|
||||
rs = runs(both, timedelta(hours=h))
|
||||
print(f"gap {h} h: {len(rs)} runs:", ", ".join(f"{r[0]:%m-%d %H:%M}→{r[-1]:%m-%d %H:%M}" for r in rs if len(rs) < 40))
|
||||
@@ -0,0 +1,28 @@
|
||||
"""From an output of perlabel.py: per family, labels, labels found (at least one instant, or a hole), events flagged, events
|
||||
wholly wrong (no instant in a label of its family).
|
||||
Usage: python3 table.py <perlabel output>
|
||||
"""
|
||||
import re
|
||||
import sys
|
||||
|
||||
lab, found, flag, wrong = {}, {}, {}, {}
|
||||
part = None
|
||||
for line in open(sys.argv[1], encoding="utf-8"):
|
||||
if line.startswith("== "):
|
||||
part = line.strip()[3:]
|
||||
continue
|
||||
if part == "labels":
|
||||
m = re.match(r"\S+\s+\S+ → \S+ (.+?)\s+found (\d+)/(\d+)", line)
|
||||
fam, f, n = m.group(1).strip(), int(m.group(2)), int(m.group(3))
|
||||
if n == 0 and "others: {}" in line and fam != "No data":
|
||||
continue # no instant on the range (a label starting at its very end)
|
||||
lab[fam] = lab.get(fam, 0) + 1
|
||||
found[fam] = found.get(fam, 0) + (f > 0 or n == 0)
|
||||
elif part == "events":
|
||||
m = re.match(r"\S+ → \S+ (.+?)\s{2,}.*?(\d+) instants, wrong\s+(\d+)", line)
|
||||
fam = m.group(1).strip()
|
||||
flag[fam] = flag.get(fam, 0) + 1
|
||||
wrong[fam] = wrong.get(fam, 0) + (m.group(2) == m.group(3))
|
||||
print("| Family | labelled | found | flagged | wrongly |\n|---|---|---|---|---|")
|
||||
for k in sorted(set(lab) | set(flag)):
|
||||
print(f"| {k} | {lab.get(k, 0)} | {found.get(k, 0)} | {flag.get(k, 0)} | {wrong.get(k, 0)} |")
|
||||
@@ -0,0 +1,35 @@
|
||||
"""Diagnose thermal_displacement._wave on a station window: per target and column, the median day likeness and the R2.
|
||||
Usage: python3 wave.py <detectors folder> <station folder> <from YYYY-MM-DD> <to YYYY-MM-DD> [history days, default 3]
|
||||
"""
|
||||
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")]
|
||||
import thermal_displacement as td # noqa: E402
|
||||
from data import load, is_reference # noqa: E402
|
||||
|
||||
day = lambda d: datetime.strptime(d, "%Y-%m-%d").replace(tzinfo=timezone.utc) # noqa: E731
|
||||
hist = int(sys.argv[5]) if len(sys.argv) > 5 else 3
|
||||
a, b = day(sys.argv[3]) - timedelta(days=hist), day(sys.argv[4])
|
||||
ms = {s: k for s, v in load(sys.argv[2]).items() if (k := [m for m in v if a <= m["t"] < b])}
|
||||
for cols in (("corr_x", "corr_y"), ("x", "y")):
|
||||
n_ok = 0
|
||||
n = 0
|
||||
for s, v in sorted(ms.items()):
|
||||
if is_reference(v):
|
||||
continue
|
||||
n += 1
|
||||
row = []
|
||||
ok = False
|
||||
for c in cols:
|
||||
ax = td._axis(v, c)
|
||||
lk = statistics.median(ax[1].values()) if ax and ax[1] else None
|
||||
ok |= lk is not None and lk >= td.REPRO
|
||||
r2 = td._sine_r2(v, c)
|
||||
row.append(f"{c}: like={lk if lk is None else round(lk, 2)} days={len(ax[1]) if ax else 0} r2={r2 if r2 is None else round(r2, 2)}")
|
||||
n_ok += ok
|
||||
print(s, " | ".join(row))
|
||||
print(cols, f"targets with a cycle: {n_ok}/{n}\n")
|
||||
Reference in new issue
Block a user