Files
aimsight-detectors/scripts/episodes.py
T

47 lines
1.6 KiB
Python
Raw Normal View History

"""Helpers shared by the detectors."""
import statistics
from datetime import timedelta
from data import iso
def episode(start, end, kind, label, text, sensors, ignore, **extra):
return {"start": iso(start), "end": iso(end), "kind": kind, "label": label, "text": text, "ignore": ignore,
"sensors": sorted(sensors), **extra}
def runs(times, gap):
"""Sorted times -> [[t, ...]]: runs of times at most gap apart."""
out = []
for t in times:
if out and t - out[-1][-1] <= gap:
out[-1].append(t)
else:
out.append([t])
return out
def noise(v):
"""Median step of a series, from one value to the next."""
return statistics.median(abs(y - x) for x, y in zip(v, v[1:])) if len(v) > 1 else 0
def level(v):
"""-> (median, MAD) of the values."""
med = statistics.median(v)
return med, statistics.median(abs(x - med) for x in v) or 1e-9
def cadence(measurements):
"""Cycle of the measurements: the median gap between two instants, at least an hour divided by the median number of
instants per clock hour (a station measuring in bursts, three measurements a minute apart every 15 min: 15 min)."""
ts = sorted({m["t"].replace(second=0, microsecond=0) for ms in measurements.values() for m in ms})
per_hour = {}
for t in ts:
per_hour[t.replace(minute=0)] = per_hour.get(t.replace(minute=0), 0) + 1
gap = statistics.median(b - a for a, b in zip(ts, ts[1:])) if len(ts) > 1 else timedelta(hours=1)
return max(gap, timedelta(hours=1) / statistics.median(per_hour.values()))
def targets(n):
return "one target" if n == 1 else f"{n} targets"