From fe1adac89af46ec34eb5e4725d47e4e2946ac6de Mon Sep 17 00:00:00 2001 From: maxime Date: Mon, 16 Nov 2026 17:23:53 +0100 Subject: [PATCH] thermal_displacement: the camera moving with the cold, partial days, DAY_MATCH and MIN_WARM_HOURS removed Removed (their benchmark contribution, each alone): the cold rule with COLD, which needed the station temperature and camera pose (Thermal found -64 at CLARIDEN and -19 at BREITHORN, 27 and 4 instants; Totals unchanged), so categories.py no longer reads them; PARTIAL days (Thermal found -1, correct -1); DAY_MATCH, every day of a cycle gets its episodes (Thermal found +8, correct -2); MIN_WARM_HOURS (none). The 24 h sinusoid by projection instead of least squares (same figures). The event sentences of the thermal varieties are now the episodes' texts. Benchmark Totals (from the previous commit): Thermal displacement found 74 -> 80 %, correct 75 -> 72 %; the other families unchanged. Co-Authored-By: Claude Opus 5.5 --- scripts/categories.py | 13 +- scripts/thermal_displacement.py | 318 ++++++++++---------------------- 2 files changed, 102 insertions(+), 229 deletions(-) diff --git a/scripts/categories.py b/scripts/categories.py index 7fb1e77..667ccfa 100644 --- a/scripts/categories.py +++ b/scripts/categories.py @@ -28,7 +28,6 @@ Usage: python3 scripts/categories.py (one line per event: fam classified alone, with the days of history before it if they exist; only the events touching the chunk are shown; "nothing" for a quiet chunk) """ -import functools import importlib import sys from datetime import datetime, timedelta, timezone @@ -38,17 +37,11 @@ from pathlib import Path # sibling of this one (one copy of each repository in the home directory). HERE = Path(__file__).resolve().parent sys.path[:0] = [str(HERE), str(HERE.parents[1] / "aimsight-tools" / "scripts")] -from data import iso, load, load_camera, load_temperature # noqa: E402 +from data import iso, load # noqa: E402 DETECTORS = ("displacement", "no_data", "target_issue", "thermal_displacement", "visibility") # modules next to this file -@functools.lru_cache(maxsize=None) -def _station(folder): - """What thermal_displacement reads besides the measurements (D-124): temperature, camera pose; once per folder.""" - return {"temperature": load_temperature(folder), "camera": load_camera(folder)} if folder else {} - - # The families, in the order of the timeline rows; ignore: greyed zone (None: as its episodes # say: a total loss of visibility, strong heat shimmer); process: Images button, nothing, or Images and a link to # Diagnosis. @@ -182,12 +175,12 @@ def classify(episodes, references=frozenset()): def events(measurements, end=None, folder=None): """Measurements (data.load) -> events of all detectors: what the page receives. end: the end of the window read - (batch run), for a hole touching it; folder: the station folder, for the temperature and the camera pose. A detector + (batch run), for a hole touching it; folder: unused, kept for the callers. A detector that fails is skipped with a message (a broken detector does not block the page).""" episodes = [] for name in DETECTORS: try: - kw = {"end": end} if name == "no_data" else _station(folder) if name == "thermal_displacement" else {} + kw = {"end": end} if name == "no_data" else {} episodes += importlib.import_module(name).detect(measurements, **kw) except Exception as e: # noqa: BLE001 print(f"Detectors: {name} skipped ({type(e).__name__}: {e})", file=sys.stderr) diff --git a/scripts/thermal_displacement.py b/scripts/thermal_displacement.py index c972d23..ba325e7 100644 --- a/scripts/thermal_displacement.py +++ b/scripts/thermal_displacement.py @@ -1,71 +1,44 @@ -"""Detector of the Thermal displacement family (the families document): the daily wave of the corrected displacements -(expansion by day, contraction in the evening). +"""Thermal displacement family: the daily wave of the displacements (expansion by day, contraction in the evening). -Method, per target (global references excluded) and per axis (corr_x, corr_y): -1. Each UTC day of at least MIN_HOURS hours: mean of each hour minus the median of the day (removes jumps and drift). -2. Profile = median, hour by hour, over the days; "repeatability" = median, over the days, of the correlation between - the day and the profile of the other days. Axis concerned if repeatability ≥ REPRO. An incomplete day (at least - PARTIAL hours, fewer than MIN_HOURS) does not enter the profile, but its likeness is measured on the hours it has: a - hole of half a day no longer takes its episode away (wf-improve session Thermal displacement, mod. 1, S4; at - MIN_HOURS = 12 or 16, the incomplete days distorted the profile, NIEDERHORN went back). -3. Cycle of the station if at least SHARE of the targets have an axis concerned, **and** (second method, asked by the - user) if a 24 h sinusoid, a + b·sin(2πt/24 h) + c·cos(2πt/24 h) by least squares, explains at least R2_MIN of the - curve of an axis for at least SHARE of the targets. -4. Warm hours: night level = median of the NIGHT flattest consecutive hours of the profile; an hour is warm if, as a - median over the axes concerned, the profile moves away from it by at least WARM times its amplitude. -5. Two episodes per complete day that looks like the others (median correlation ≥ DAY_MATCH over the axes concerned): - "Thermal expansion" from the start to the hour of the largest gap from the night level (the peak), then "Thermal - contraction" until the return. The warm hours say there is a cycle (at least MIN_WARM_HOURS of them); its bounds - are read lower, at EDGE times the amplitude: the start, going back from the peak while the gap stays ≥ EDGE (at most - to the calmest hour of the profile); the return, going down from the peak until it goes back under RETURN, after - midnight if needed, at most to the next day's start: a slow return at night chains the cycles (wf-improve session - Thermal displacement, mod. 1, S1). RETURN is half of EDGE: the warm-up is quick, the cooling tail slow, and the - labelled nights went on after the return reached EDGE (wf-improve NORDEND 2026-11-05, S1: NORDEND, JUNGFRAU; EDGE - itself at 0.05 made FLORIDA and SNCF01 overflow in the morning). The direction (a rising or falling curve) depends on the target's orientation: - it is not looked at, only the gap from the night level. -Reading: the cycle is almost everywhere in the raw positions (common mode) and the compensation removes it, except at -PS des Coudres where it stays in corr, with the same shape as in the raw positions. -Camera thermal effect (D-074): without a cycle in corr, the same method on the raw positions x, y gives "Camera thermal -expansion" and "Camera thermal contraction": the camera moves with the heat of its mount, the compensation removes it; -same categories, own sentence. On the raw positions the second method is not asked (WILDSTRUBEL, batch 01: the camera -rose by a 3 px block at sunrise, held 3 h and dropped in one step around 09:30, six days in a row, which the sinusoid -does not explain); in exchange, a single warm hour is not a cycle (MIN_WARM_HOURS: NIEDERHORN, E-005, hourly, would -otherwise have its noon hour as a camera contraction). The camera episode covers all sensors, references included: the -whole image moves. -Common slide, without a cycle (wf-improve MICHIGAN, mod. 1): lacking a cycle in the corrected curves as in the raw -positions, an instant is a camera slide if the raw positions (x or y) of at least SHARE of the sensors, references -included, **and** the corrected curves (corr_x or corr_y) of at least SHARE of the targets move away on the same side by -at least SLIDE_K noises (median of the steps of the series) from their median of the day before; slides less than a -day apart make one episode, "Camera thermal movement", on all sensors, host of the jumps back (categories.HOSTS). The -condition on the raw positions leaves to the jumps a flip of the computed pose alone (raw positions still). -The camera moves with the cold (wf-improve session Thermal displacement, mod. 1, S3): lacking a cycle, also a "Camera -thermal movement" where the camera pose (tilt, rotation or scale) moves away from its median of the day before by at -least COLD noises, while the station temperature (detect declares it, D-124) falls under its own by at least COLD -noises the same hour; noise: the median of the variations over an hour (over one step, at one measurement every 4 h), -so that the threshold does not depend on the cadence. The targets may move in opposite directions or stay almost still -(the compensation absorbs the movement): the slide rule does not see it. Consecutive pose instants make one episode. -Without a pose or without a temperature, nothing. The heat is not taken: in fine weather, it is the day's cycle. +Per target (references excluded) and per axis: +1. Each UTC day measured at least MIN_HOURS hours: the mean of each hour minus the median of the day. +2. Profile: the median, hour by hour, over the days. The axis has a cycle if its days look like the profile of the + other days (median correlation at least REPRO). +3. The station has a cycle if at least SHARE of the targets have an axis with one and, for the corrected curves, a 24 h + sinusoid explains at least R2_MIN of an axis of SHARE of the targets. +4. Gap of each hour from the night level (median of the NIGHT flattest consecutive hours of the profile), as a share of + the profile's amplitude, median over the axes with a cycle; there is a wave if the largest gap (the peak) reaches + WARM. "Expansion" from where the gap rises above EDGE to the peak, "contraction" from the peak until the gap falls + under RETURN, after midnight if needed, at most to the next start: the cooling tail is slow (wf-improve Thermal + displacement, mod. 1, S1; wf-improve NORDEND 2026-11-05, S1). Two episodes for every day of the axes with a cycle. +The corrected curves first (the structure, "Thermal ..."); without a cycle there, the raw positions x, y ("Camera +thermal ...": the camera moves with its mount and the compensation removes it, D-074; the whole image, every sensor); +without one either, the camera slides ("Camera thermal movement", wf-improve MICHIGAN, mod. 1): instants where the raw +positions of SHARE of the sensors and the corrected curves of SHARE of the targets move away on the same side by +SLIDE_K noises from their median of the day before; slides less than a day apart make one episode. """ import math import statistics from datetime import datetime, timedelta, timezone -from data import iso +from common import episode, noise, runs +from data import is_reference -MIN_HOURS = 20 # a UTC day counts in the profile if it has at least 20 measured hours -PARTIAL = 12 # an incomplete day of at least 12 hours gets its episode if it looks like the profile -REPRO = 0.6 # an axis has a cycle if each day looks like the others (pure noise ≈ 0) -SHARE = 0.5 # share of the targets concerned; 2026-10_NORDEND is just under (9/19) -WARM = 0.3 # gap from the night level, as a share of the profile's amplitude -DAY_MATCH = 0.5 # likeness of a day to the others to give it its episode -NIGHT = 8 # flattest consecutive hours of the profile = night level -R2_MIN = 0.3 # draft of 2026-10-24: PS des Coudres 14 axes out of 22 above, CLARIDEN 0 out of 48 -MIN_WARM_HOURS = 2 # WILDSTRUBEL, batch 01; NIEDERHORN (E-005) has only one warm hour (noon) -EDGE = 0.1 # start of the wave, as a share of the amplitude; WARM says whether there is a cycle -RETURN = 0.05 # return of the wave, lower: the cooling tail is slow (wf-improve NORDEND 2026-11-05, S1) -SLIDE_K = 3 # common slide, in noises (median of the steps) away from the median of the day before -COLD = 4 # the camera moves with the cold, in one-hour noises away from the day before (pose, temperature) -W = 2 * math.pi / 86400 # angular frequency of a 24 h cycle, in rad/s +MIN_HOURS = 20 # hours of a day of the profile +REPRO = 0.6 # pure noise ≈ 0 +SHARE = 0.5 # NORDEND of October is just under (9/19) +R2_MIN = 0.3 # PS des Coudres 14 axes out of 22 above, CLARIDEN 0 out of 48 (least squares then; now the projection) +NIGHT = 8 # flattest consecutive hours of the profile +WARM = 0.3 # a wave: the peak at WARM times the amplitude from the night level +EDGE = 0.1 # start of the wave (wf-improve Thermal displacement, mod. 1, S1) +RETURN = 0.05 # end of the wave (wf-improve NORDEND 2026-11-05, S1) +SLIDE_K = 3 # common slide, in noises (wf-improve MICHIGAN, mod. 1: at 2, Displacement instants of BREITHORN taken) +W = 2 * math.pi / 86400 # angular frequency of a 24 h cycle, rad/s +DAY = timedelta(days=1) +TEXTS = {"Thermal expansion": "The structure expands in the day heat.", + "Thermal contraction": "The structure contracts as it cools down.", + "Camera thermal expansion": "The camera support expands in the day heat; the curves are corrected for it.", + "Camera thermal contraction": "The camera support contracts as it cools down; the curves are corrected for it."} def _corr(a, b): @@ -81,20 +54,16 @@ def _axis(ms, col): for m in ms: if m[col] is not None: days.setdefault(m["t"].date(), {}).setdefault(m["t"].hour, []).append(m[col]) - full, every = {}, {} + full = {} for d, hs in days.items(): - if len(hs) >= PARTIAL: - med = statistics.median(v for l in hs.values() for v in l) - every[d] = {h: statistics.mean(l) - med for h, l in hs.items()} - if len(hs) >= MIN_HOURS: - full[d] = every[d] - if len(full) < 2: - return None - profile = [statistics.median(q[h] for q in full.values() if h in q) for h in range(24) if any(h in q for q in full.values())] - if len(profile) < 24: + if len(hs) >= MIN_HOURS: + med = statistics.median(v for vs in hs.values() for v in vs) + full[d] = {h: statistics.mean(vs) - med for h, vs in hs.items()} + if len(full) < 2 or any(all(h not in q for q in full.values()) for h in range(24)): return None + profile = [statistics.median(q[h] for q in full.values() if h in q) for h in range(24)] likeness = {} - for d, p in every.items(): + for d, p in full.items(): others = [q for e, q in full.items() if e != d] hs = [h for h in p if all(h in q for q in others)] if len(hs) >= 3: @@ -102,178 +71,89 @@ def _axis(ms, col): return profile, likeness -def sine_r2(ms, col): - """Share of the curve explained by a 24 h sinusoid (least squares, 3 unknowns), or None if too short.""" +def _sine_r2(ms, col): + """Share of the curve explained by a 24 h sinusoid (its projection on the sine and cosine of the day: the + measurements cover the hours evenly), or None if too short.""" pts = [(m["t"].timestamp(), m[col]) for m in ms if m[col] is not None] if len(pts) <= 48: return None - rows = [(1.0, math.sin(W * t), math.cos(W * t)) for t, _ in pts] - A = [[sum(r[i] * r[j] for r in rows) for j in range(3)] for i in range(3)] - B = [sum(r[i] * y for r, (_, y) in zip(rows, pts)) for i in range(3)] - for i in range(3): # Gaussian elimination - for k in range(i + 1, 3): - f = A[k][i] / A[i][i] - A[k] = [x - f * y for x, y in zip(A[k], A[i])] - B[k] -= f * B[i] - x = [0.0] * 3 - for i in (2, 1, 0): - x[i] = (B[i] - sum(A[i][j] * x[j] for j in range(i + 1, 3))) / A[i][i] - m = statistics.mean(y for _, y in pts) - sst = sum((y - m) ** 2 for _, y in pts) - sse = sum((y - sum(c * v for c, v in zip(x, r))) ** 2 for r, (_, y) in zip(rows, pts)) + mean = statistics.fmean(y for _, y in pts) + b = 2 * statistics.fmean((y - mean) * math.sin(W * t) for t, y in pts) + c = 2 * statistics.fmean((y - mean) * math.cos(W * t) for t, y in pts) + sst = sum((y - mean) ** 2 for _, y in pts) + sse = sum((y - mean - b * math.sin(W * t) - c * math.cos(W * t)) ** 2 for t, y in pts) return 1 - sse / sst if sst else None -def sine(measurements, cols=("corr_x", "corr_y")): - """-> (targets with an axis following a 24 h sinusoid, targets evaluated).""" - yes, evaluated = set(), set() - for s, ms in measurements.items(): - if ms[0]["pattern_type"] == "global_ref": - continue - for col in cols: - r2 = sine_r2(ms, col) - if r2 is not None: - evaluated.add(s) - if r2 >= R2_MIN: - yes.add(s) - return yes, evaluated +def _wave(measurements, cols, name, camera): + targets = {s: ms for s, ms in measurements.items() if not is_reference(ms)} + axes = [(s, *a) for s, ms in targets.items() for col in cols if (a := _axis(ms, col))] # (target, profile, likeness) + concerned = [a for a in axes if a[2] and statistics.median(a[2].values()) >= REPRO] + if not axes or len({a[0] for a in concerned}) < SHARE * len({a[0] for a in axes}): + return [] + if not camera: # the sinusoid must see it too + r2 = {s: [r for col in cols if (r := _sine_r2(ms, col)) is not None] for s, ms in targets.items()} + r2 = {s: v for s, v in r2.items() if v} + if not r2 or sum(max(v) >= R2_MIN for v in r2.values()) < SHARE * len(r2): + return [] - -def cycle(measurements, cols=("corr_x", "corr_y")): - """-> (axes concerned [(sensor, col, profile, likeness)], number of targets evaluated).""" - concerned, targets = [], set() - for s, ms in measurements.items(): - if ms[0]["pattern_type"] == "global_ref": - continue - for col in cols: - r = _axis(ms, col) - if r is None: - continue - targets.add(s) - if statistics.median(r[1].values()) >= REPRO: - concerned.append((s, col) + r) - return concerned, len(targets) - - -def gaps(concerned): - """Median gap (over the axes concerned) from the night level, hour by hour, as a share of the profile's amplitude.""" - def score(p, h): + def gap(p, h): # from the night level, as a share of the amplitude start = min(range(24), key=lambda i: max(p[(i + k) % 24] for k in range(NIGHT)) - min(p[(i + k) % 24] for k in range(NIGHT))) - night = statistics.median(p[(start + k) % 24] for k in range(NIGHT)) - return abs(p[h] - night) / (max(p) - min(p)) - return [statistics.median(score(c[2], h) for c in concerned) for h in range(24)] + return abs(p[h] - statistics.median(p[(start + k) % 24] for k in range(NIGHT))) / (max(p) - min(p)) + e = [statistics.median(gap(a[1], h) for a in concerned) for h in range(24)] + peak, rest = max(range(24), key=e.__getitem__), min(range(24), key=e.__getitem__) + if e[peak] < WARM: + return [] + a = peak + while (a - 1) % 24 != rest and e[(a - 1) % 24] >= EDGE: + a -= 1 + b = peak + 1 + while b < a + 24 and e[b % 24] >= RETURN: + b += 1 + last = max(m["t"] for ms in measurements.values() for m in ms) + sensors = measurements if camera else {a[0] for a in concerned} + out = [] + for d in sorted({d for a in concerned for d in a[2]}): + midnight = datetime(d.year, d.month, d.day, tzinfo=timezone.utc) + for label, u, v in ((f"{name} expansion", a, peak), (f"{name} contraction", peak, b)): + start, end = midnight + timedelta(hours=u), min(midnight + timedelta(hours=v), last) + if end > start: + out.append(episode(start, end, "Thermal displacement", label, + TEXTS[label] + " This daily wave is normal: nothing to do.", sensors, False)) + return out -def warm_hours(concerned): - return [h for h, e in enumerate(gaps(concerned)) if e >= WARM] - - -def detect(measurements, temperature=(), camera=()): - """Cycle of the corrected curves (the structure); otherwise, that of the raw positions (the camera moving with the - expansion of its mount, compensated: D-074); otherwise, the camera slides (with the cold).""" - return (_episodes(measurements, ("corr_x", "corr_y"), "Thermal", False) or - _episodes(measurements, ("x", "y"), "Camera thermal", True) or slides(measurements, temperature, camera)) - - -def _signs(ms, col, hourly=False, k=None): - """{instant: +1 or -1} where the measurement moves away by at least k (default SLIDE_K) noises from the median of the - day before; noise: the median of the steps from one measurement to the next or, hourly, of the variations over an - hour (one step if the cadence is slow).""" +def _signs(ms, col): + """{instant: +1 or -1} where the value moves away by at least SLIDE_K noises from its median of the day before.""" pts = [(m["t"], m[col]) for m in ms if m[col] is not None] - if len(pts) < 3: - return {} - step = statistics.median((b - a).total_seconds() for (a, _), (b, _) in zip(pts, pts[1:])) if hourly else 0 - n = max(1, round(3600 / step)) if step else 1 - noise = statistics.median(abs(pts[i + n][1] - pts[i][1]) for i in range(len(pts) - n)) if len(pts) > n else 0 - out, j = {}, 0 + n, out, j = noise([v for _, v in pts]), {}, 0 for i, (t, v) in enumerate(pts): - while pts[j][0] < t - timedelta(days=1): + while pts[j][0] < t - DAY: j += 1 before = [w for _, w in pts[j:i]] - if noise and len(before) >= 3 and abs(v - statistics.median(before)) >= (k or SLIDE_K) * noise: - out[t] = 1 if v > statistics.median(before) else -1 + if n and len(before) >= 3 and abs(v - (med := statistics.median(before))) >= SLIDE_K * n: + out[t] = 1 if v > med else -1 return out def _common(series): """[{instant: sign}] of a group of sensors -> instants where at least SHARE of them move away on the same side.""" - n, count = len(series), {} + count = {} for sg in series: for t, x in sg.items(): count[(t, x)] = count.get((t, x), 0) + 1 - return {t for (t, x), c in count.items() if n and c >= SHARE * n} + return {t for (t, x), c in count.items() if c >= SHARE * len(series)} -def _cold(measurements, temperature, camera): - """[(start, end)] of the runs of instants where the camera pose (tilt, rotation or scale) moves away from its day - before while the temperature falls under its own, by at least COLD one-hour noises; empty without one of them.""" - ts = [m["t"] for ms in measurements.values() for m in ms] - hour = lambda t: t.replace(minute=0, second=0, microsecond=0) # noqa: E731 - cold = {hour(t) for t, x in _signs([{"t": t, "T": v} for t, v in temperature], "T", True, COLD).items() if x < 0} - pose = [p for p in camera if min(ts) <= p["t"] <= max(ts)] if ts else [] - seen = {t for c in ("tilt", "rotation", "scale") for t in _signs(pose, c, True, COLD) if hour(t) in cold} - episodes = [] # consecutive pose instants make one episode - for i, p in enumerate(pose): - if p["t"] in seen: - if episodes and episodes[-1][2] == i - 1: - episodes[-1][1:] = [p["t"], i] - else: - episodes.append([p["t"], p["t"], i]) - return [(a, b) for a, b, _ in episodes] - - -def slides(measurements, temperature=(), camera=()): - """Common camera slide, without a 24 h cycle: the raw positions of most sensors, references included, and the - corrected curves of most targets move away together, on the same side, from their day before; or the camera pose - moves away from it with the cold (_cold).""" - targets = [ms for ms in measurements.values() if ms[0]["pattern_type"] != "global_ref"] +def slides(measurements): + targets = [ms for ms in measurements.values() if not is_reference(ms)] raw = set().union(*(_common([_signs(ms, c) for ms in measurements.values()]) for c in ("x", "y"))) corr = set().union(*(_common([_signs(ms, c) for ms in targets]) for c in ("corr_x", "corr_y"))) - episodes = [] - for t in sorted(raw & corr): - if episodes and t - episodes[-1][1] <= timedelta(days=1): # less than a day between two: the same slide - episodes[-1][1] = t - else: - episodes.append([t, t]) - return [{"start": iso(a), "end": iso(b), "kind": "Thermal displacement", "label": "Camera thermal movement", - "text": "The camera moved with a change of temperature and all the curves moved with it; this is not a " - "movement of the structure, nothing to do.", "ignore": False, "sensors": sorted(measurements)} - for a, b in episodes + _cold(measurements, temperature, camera)] + return [episode(r[0], r[-1], "Thermal displacement", "Camera thermal movement", "The camera moved with a change of " + "temperature and all the curves moved with it; this is not a movement of the structure, nothing to " + "do.", measurements, False) for r in runs(sorted(raw & corr), DAY)] -def _episodes(measurements, cols, name, camera): - concerned, n = cycle(measurements, cols) - sensors = sorted({c[0] for c in concerned}) - if not n or len(sensors) < SHARE * n: - return [] - if not camera: # second method, for the structure only: the sinusoid must see it too - yes, evaluated = sine(measurements, cols) - if not evaluated or len(yes) < SHARE * len(evaluated): - return [] - warm = warm_hours(concerned) - if len(warm) < MIN_WARM_HOURS: - return [] - e = gaps(concerned) - peak = max(warm, key=lambda h: e[h]) # the largest gap from the night level: end of the expansion - rest = min(range(24), key=lambda h: e[h]) - a = peak # start: going back from the peak while the profile stays above EDGE, up to the calmest hour - while (a - 1) % 24 != rest and e[(a - 1) % 24] >= EDGE: - a -= 1 - b = peak + 1 # return: until the profile goes back under RETURN, at most to the next start - while b < a + 24 and e[b % 24] >= RETURN: - b += 1 - last = max(m["t"] for ms in measurements.values() for m in ms) - days = sorted({d for c in concerned for d in c[3]}) - if camera: # the whole image moves, references included - sensors = sorted(measurements) - episodes = [] - for d in days: # ponytail: days of at least PARTIAL hours, the export's ends (22:00 → midnight) get no episode - if statistics.median(c[3][d] for c in concerned if d in c[3]) < DAY_MATCH: - continue - midnight = datetime(d.year, d.month, d.day, tzinfo=timezone.utc) - for label, u, v in ((f"{name} expansion", a, peak), (f"{name} contraction", peak, b)): - start, end = midnight + timedelta(hours=u), min(midnight + timedelta(hours=v), last) - if end > start: - episodes.append({"start": iso(start), "end": iso(end), - "kind": "Thermal displacement", "label": label, "text": "", "ignore": False, "sensors": sensors}) - return episodes +def detect(measurements): + return (_wave(measurements, ("corr_x", "corr_y"), "Thermal", False) + or _wave(measurements, ("x", "y"), "Camera thermal", True) or slides(measurements))