"""Weak thermal labels: per target, hourly median of corr (instants inside non-thermal labels left out) minus a night level (median of 3 h of a given night), in the target's batch noise (ranges.py, k 5 rolling 8, noise column). Usage: python3 thermal_nights.py labels.jsonl ranges_roll8.txt ID NIGHT_START [ID NIGHT_START ...]""" import sys, json, re, statistics from datetime import timedelta sys.path.insert(0, "tools/scripts"); import data labs = {json.loads(l).get("id"): json.loads(l) for l in open(sys.argv[1])} noise = {}; col = None for line in open(sys.argv[2]): m = re.match(r"== (corr_[xy]):", line) if m: col = m.group(1); continue if line.startswith("corr_"): col = None; continue f = line.split() if col and len(f) >= 4 and f[0] != "sensor": try: noise[(col, f[0])] = float(f[3]) except ValueError: pass OTHER = [(data.parse_time(l["start"]), data.parse_time(l["end"])) for l in labs.values() if l["family"] not in ("Thermal displacement", "No data")] excl = lambda t: any(a < t < b for a, b in OTHER) by = data.load("data/NORDEND") for ms in by.values(): for m in ms: m["t"] = m["t"].replace(second=0, microsecond=0) tg = [s for s in by if s not in ("CTR02", "CTR03", "CTR04", "PR04")] a = sys.argv[3:] for i in range(0, len(a), 2): l = labs[a[i]]; N = data.parse_time(a[i + 1]); S, E = data.parse_time(l["start"]), data.parse_time(l["end"]) res = [] for c in ("corr_x", "corr_y"): for s in tg: night = [m[c] for m in by[s] if N <= m["t"] <= N + timedelta(hours=3) and m[c] is not None and not excl(m["t"])] if len(night) < 4: continue lv = statistics.median(night); hours = {} for m in by[s]: if S <= m["t"] <= E and m[c] is not None and not excl(m["t"]): hours.setdefault(m["t"].replace(minute=0), []).append(m[c]) for h, v in hours.items(): if len(v) >= 3: res.append(((statistics.median(v) - lv) / noise[(c, s)], s, c, h)) res.sort(key=lambda x: -abs(x[0])) print(a[i], "night from", a[i + 1], "max", f"{abs(res[0][0]):.1f}", "|", " ".join(f"{s}.{c[-1]} {d:+.1f}@{h:%d %H}h" for d, s, c, h in res[:6]))