Files
aimsight-app/app/server/station.py
T

415 lines
21 KiB
Python
Raw Normal View History

"""The data of the Data page: a station's images, its curves, its labels.
Data are read as the agents read them, tools/scripts/data.py (the tools repository, through the tools/ link); the detectors'
events are those of detectors/scripts/categories.py (window); the rules of the labels and what the client is told, those of
labeling/scripts (validate, ids, client). Read-only on data/, filled only by pump.sh; writes only in
labeling/auto/. What brings data in (the pumping, the list of the tracked stations) is in ~/aimsight-data, called as it
is (extraction/pumping.py); the weather is pumped with the data, data/<STATION>/weather/ (data.load_weather).
The runs of the differential data (data_diff/<SERIAL>/runs/<run>/ of ~/aimsight-data) are stations too, <SERIAL>@<run>:
read by the same reader (data.shared: their images, metrics and weather in data_diff/<SERIAL>/); their labels are those of
<SERIAL>.
"""
import bisect
import functools
import glob
import json
import os
import pickle
import re
import statistics
import subprocess
import sys
from datetime import datetime, timedelta
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
# ~/aimsight-data, the repository of data/: the method that brings data in (the pumping, the weather with it), called as it is
DATA_REPOSITORY = Path(os.environ.get("AIMSIGHT_DATA", ROOT / "data")).resolve().parent
sys.path[:0] = [str(ROOT / "tools" / "scripts"), str(ROOT / "detectors" / "scripts"), str(ROOT / "labeling" / "scripts"),
str(DATA_REPOSITORY / "extraction")]
import categories # noqa: E402
import client # noqa: E402 (labeling: what the client is told of an event)
import data # noqa: E402
import ids # noqa: E402 (labeling: the stable id of the labels)
import pumping # noqa: E402
import validate # noqa: E402 (labeling: the rules of a label)
# data/ and labeling/ are links to ~/aimsight-data/data and ~/aimsight-labeling: no resolve(), the agents see data/ and labeling/
DATA = Path(os.environ.get("AIMSIGHT_DATA", ROOT / "data")).absolute()
LABELS = Path(os.environ.get("AIMSIGHT_LABELS", ROOT / "labeling")).absolute()
DATA_DIFF = DATA_REPOSITORY / "data_diff" # the runs, data_diff/<SERIAL>/runs/<run>/: out of git, filled by ~/aimsight-data
RUN = "@" # <SERIAL>@<run>: a run of data_diff/ in the list of the stations
TOOLS = ROOT / "tools" # the reading harness (~/aimsight-tools), read by the analyst and written by the upgrader (Optimizer)
def links():
"""--add-dir for claude -p: the real target of the data/, labeling/ and tools/ links, outside the repository."""
return [a for d in (DATA, LABELS, TOOLS) for a in ("--add-dir", str(d.resolve()))]
FOLDERS = ("auto",) # the labels of the agents and of the page (D-105); manual/ is the expert's alone (labeling/CLAUDE.md)
FORMAT = "%Y-%m-%dT%H:%MZ"
COLORS = ["#2a78d6", "#eb6834", "#1baf7a", "#8a5cd6", "#d6a12a", "#d63b8a", "#3bb3d6", "#6b6b66"] # one per sensor
POSE = (("pan", "#1a1a19"), ("tilt", "#8a8a85"), ("rotation", "#b5651d"))
# The Advanced menu of Explore, in its order (Support-Agent labeling.PLOTS, QUALITE)
PLOTS = (("error_value", "Error value"), ("x", "X [px]"), ("y", "Y [px]"),
("relative_x", "Relative Horizontal Shift"), ("relative_y", "Relative Vertical Shift"),
("corr_x", "Relative Corrected Horizontal Shift"), ("corr_y", "Relative Corrected Vertical Shift"),
("corr_x_mm", "Relative Corrected Horizontal Shift [mm]"), ("corr_y_mm", "Relative Corrected Vertical Shift [mm]"),
("reproj_err", "References (reproj. error)"))
QUALITY = (("peak", "Quality: Peak"), ("flux", "Quality: Flux"), ("sharpness", "Quality: Sharpness"),
("fwhm", "Quality: FWHM [px]"), ("dominance", "Quality: Dominance"), ("snr", "Quality: SNR"))
class Refusal(ValueError):
"""A request to refuse (400), with its reason."""
def stations():
runs = sorted(f"{d.parent.parent.name}{RUN}{d.name}" for d in DATA_DIFF.glob("*/runs/*") if d.is_dir())
return sorted(d.name for d in DATA.iterdir() if d.is_dir()) + runs
def serial(station):
"""The station of a run, <SERIAL>@<run> -> <SERIAL> (its labels); a station of data/ -> itself."""
return station.partition(RUN)[0]
def folder(station):
if station not in stations(): # the name becomes a path: a folder of data/ or a run of data_diff/, nothing else
raise Refusal(f"unknown station: {station}")
s, _, run = station.partition(RUN)
return DATA_DIFF / s / "runs" / run if run else DATA / station
def pumped(station):
"""A station of data/ (the agents read data/ only): a run of data_diff/ refused."""
folder(station)
if RUN in station:
raise Refusal(f"{station} is a run of data_diff/: the agents read the stations of data/ only")
def bounds(start, end):
return data.parse_time(start or "0001-01-01"), data.parse_time(end or "9999-01-01")
# --- the positions of the sensors in the image
def positions(measurements, a, b):
"""Where to circle each sensor on the images: its median x, y over [a, b) (image px, tools/DATA.md)."""
return {s: (statistics.median(xs), statistics.median(ys)) for s, ms in measurements.items()
if (xs := [m["x"] for m in ms if a <= m["t"] < b and m["x"] is not None])
and (ys := [m["y"] for m in ms if a <= m["t"] < b and m["y"] is not None])}
def references(measurements):
"""The references of the compensation (tools/scripts/data.py, is_reference)."""
return {s for s, ms in measurements.items() if data.is_reference(ms)}
# --- the images of the Data page
def images(station, start, end):
"""The images of [start, end), the median positions of the sensors, the references, and for each circled sensor its
corr_x, corr_y at the time of each image: the nearest valid measurement, within 30 min, otherwise 0."""
d, (a, b) = folder(station), bounds(start, end)
views = [(t, im) for im in sorted(glob.glob(str(Path(data.shared(d)) / "images" / "*"))) if (t := data.image_time(im)) and a <= t < b]
if not views:
raise Refusal(f"no image of {station} in this range")
measurements = data.load(d)
homes, refs = positions(measurements, a, b), references(measurements)
# ponytail: a single measurement at each bound, noisy; a median over a window if the arrows shake too much
margin, corr = timedelta(minutes=30), {}
for s in homes:
series = [(m["t"], m["corr_x"], m["corr_y"]) for m in measurements[s] if m["corr_x"] is not None and m["corr_y"] is not None]
times, corr[s] = [m[0] for m in series], []
for t, _ in views:
k = bisect.bisect_left(times, t)
k = min((n for n in (k - 1, k) if 0 <= n < len(series)), key=lambda n: abs(times[n] - t), default=None)
corr[s].append([round(series[k][1], 4), round(series[k][2], 4)] if k is not None and abs(times[k] - t) <= margin else 0)
return {"images": [{"t": data.iso(t).replace("T", " ").rstrip("Z"), "name": os.path.basename(im)} for t, im in views],
"positions": {s: [round(x, 1), round(y, 1)] for s, (x, y) in sorted(homes.items())},
"references": sorted(refs), "corr": corr}
def image(station, name):
images = Path(data.shared(folder(station))) / "images"
f = (images / name).resolve()
if f.parent != images.resolve() or not f.is_file():
raise Refusal("unknown image")
return f
# --- the curves of the Data page
def holes(points, step=timedelta(hours=1)):
"""[(t, v)] sorted -> the same, with (t + step, None) after a point followed by nothing during more than a step."""
out = []
for t, v in points:
if out and t - out[-1][0] > step:
out.append((out[-1][0] + step, None))
out.append((t, v))
return out
def span(measurements, start, end):
"""The range read: from start to end (excluded), otherwise from the first measurement to the last, plus one step."""
every = sorted({m["t"] for ms in measurements.values() for m in ms})
a = data.parse_time(start) if start else every[0]
b = data.parse_time(end) if end else every[-1] + (every[-1] - every[-2] if len(every) > 1 else timedelta(hours=1))
return a, b
def curves(station, start, end):
"""-> {A, B, T, plots}: T, the times of each series, once (key: the sensor, "" for the camera, "system:" and its
name for a metric); plot: title and traces (name, t, y, line, mode), without empty plots or sensors."""
d = folder(station)
measurements = data.load(d)
if not measurements:
raise Refusal(f"no \"advanced\" export for {station}")
a, b = span(measurements, start, end)
poses = [p for p in data.load_camera(d) if a <= p["t"] < b]
hour = lambda t: t.strftime("%Y-%m-%d %H:%M") # noqa: E731 (UTC, without time zone: as Plotly shows it)
values = lambda s, c: [None if m[c] is None else round(m[c], 5) for m in s] # noqa: E731
inside = {s: [m for m in measurements[s] if a <= m["t"] < b] for s in sorted(measurements)}
refs, out = references(measurements), []
def per_sensor(columns):
for col, title in columns:
traces = [{"name": s + " (ref.)" * (s in refs), "t": s, "y": y,
"line": {"width": 1.2, "color": COLORS[i % len(COLORS)], "dash": "dot" if s in refs else "solid"}}
for i, (s, y) in enumerate((s, values(ms, col)) for s, ms in inside.items()) if any(v is not None for v in y)]
if traces:
out.append({"title": title, "traces": traces})
per_sensor(PLOTS)
if poses:
out.append({"title": "Camera movement (deg)", "traces": [{"name": c, "t": "", "y": values(poses, c),
"line": {"width": 1.2, "color": col}} for c, col in POSE]})
per_sensor(QUALITY)
T = {"": [hour(p["t"]) for p in poses], **{s: [hour(m["t"]) for m in ms] for s, ms in inside.items()}}
# the numeric system metrics (data.load_metrics: without the text metrics and the identifiers), over [a, b); an
# hour without value breaks the line (None), the hole shows
system = {n: holes(kept) for n, vs in data.load_metrics(d).items() if (kept := [(t, v) for t, v in vs if a <= t < b])}
for name in sorted(system, key=str.lower):
T["system:" + name] = [hour(t) for t, _ in system[name]]
out.append({"title": "System: " + name, "traces": [{"name": name, "t": "system:" + name, "mode": "lines+markers",
"y": [None if v is None else round(v, 5) for _, v in system[name]],
"line": {"width": 1.2, "color": COLORS[0]}}]})
if not out:
raise Refusal(f"no measurement of {station} in this range")
result = {"A": data.iso(a), "B": data.iso(b), "T": T, "plots": out}
if hours := [h for h in data.load_weather(d) if a <= h["t"] < b]: # the weather pumped with the data, if any
label, times, plots = weather(hours)
T.update(times)
out += plots
result["weather"] = label
elif pumping.tracked().get(serial(station)):
result["weather"] = "none pumped in this range (see the pumping log)"
return result
# --- the Data page, the weather pumped in data/<STATION>/weather/ (extraction/weather.py of ~/aimsight-data): plots "Weather: …"
WEATHER = (("Precipitation (mm/h)", "precipitation_mm"), ("Temperature (°C)", "temperature_c"), ("Humidity (%)", "humidity_pct"),
("Wind (km/h)", "wind_speed_kmh", "wind_gust_kmh"), ("Wind direction (deg)", "wind_direction_deg"),
("Pressure (hPa)", "pressure_hpa"), ("Sunshine (min/h)", "sunshine_min"),
("Global radiation (W/m²)", "global_radiation_wm2"), ("Snow depth (cm)", "snow_depth_cm"))
def weather(hours):
"""[hour] of data.load_weather, not empty -> (label, T, plots) as curves(); their times under T["system:weather"], so
that the target filters ignore them; the label: where the last hour was measured."""
plots = []
for title, *columns in WEATHER:
traces = [{"name": c.rsplit("_", 1)[0].replace("_", " "), "t": "system:weather", "y": y,
"mode": "markers" if "direction" in c else "lines",
"line": {"width": 1.2, "color": COLORS[i], "shape": "hv" if c == "precipitation_mm" else "linear"}}
for i, (c, y) in enumerate((c, [h.get(c) for h in hours]) for c in columns) if any(v is not None for v in y)]
if traces:
plots.append({"title": "Weather: " + title, "traces": traces})
w = hours[-1]
return (f"{w['place']} → MeteoSwiss {w['station']} {w['station_name']}, {w['distance_km']} km, {w['height_m']} m"
+ " (no measurement in this range)" * (not plots),
{"system:weather": [h["t"].strftime("%Y-%m-%d %H:%M") for h in hours]}, plots)
# --- the tracked stations and the pumping: extraction/pumping.py of ~/aimsight-data
pump_process = None # the pumping launched by the app
def save_tracked(rows):
try:
return [{"serial": s, "position": p} for s, p in pumping.save(rows).items()]
except ValueError as e:
raise Refusal(str(e))
def pump_state():
"""{running, log}; the end of the app's pumping empties the cache of the detectors' events."""
global pump_process
if pump_process and pump_process.poll() is not None:
pump_process = None
detectors.cache_clear()
return {"running": pumping.running() or pump_process is not None, "log": pumping.log()}
def pump(body):
global pump_process
try:
pump_process = pumping.start(body.get("stations") or [], body.get("start") or "", body.get("end") or "", body.get("images"))
except ValueError as e:
raise Refusal(str(e))
return pump_state()
# --- the Data page, "Detectors" labels: the events of the journal, read-only
# The sets of detectors: detectors/scripts/ (classic, imported here), detectors/manual/ (the same layout, hand-made: run in
# a process of its own, its modules bear the same names as the classic ones)
MANUAL = ROOT / "detectors" / "manual"
CHILD = ("import pickle, sys; out, sys.stdout = sys.stdout.buffer, sys.stderr; sys.path.insert(0, sys.argv[1]); import categories; "
"pickle.dump(categories.window(*pickle.load(sys.stdin.buffer)), out)")
def window(set_, every, a, b):
"""categories.window of the chosen set."""
if set_ != "manual":
return categories.window(every, a, b)
if not (MANUAL / "categories.py").is_file():
raise Refusal("no manual detectors: detectors/manual/ has no categories.py")
run = subprocess.run([sys.executable, "-c", CHILD, str(MANUAL)], input=pickle.dumps((every, a, b)), capture_output=True, cwd=ROOT)
sys.stderr.write(run.stderr.decode(errors="replace"))
if run.returncode:
raise Refusal("the manual detectors failed: " + (run.stderr.decode(errors="replace").strip().splitlines() or ["?"])[-1])
return pickle.loads(run.stdout)
# ponytail: kept until the server restarts (a minute or more per range); restart it after an /optimize run outside the app
@functools.lru_cache(maxsize=32)
def detectors(station, start, end, targets="", set_="classic"):
"""-> the detectors' events over the range, in the label format (start, end, family, description); plus kind,
sensors, ignore (greyed area of the journal). targets: the sensors kept, comma-separated (empty: all); the others are
removed before the detectors, as if they did not exist. set_: classic (detectors/scripts/) or manual (detectors/manual/)."""
d = folder(station)
every = data.load(d)
if targets:
keep = set(targets.split(","))
every = {s: ms for s, ms in every.items() if s in keep}
if not every:
raise Refusal(f"no \"advanced\" export for {station}" + " with these targets" * bool(targets))
a, b = span(every, start, end)
refs, advice = references(every), client.advice()
return [{"id": f"D-{i + 1}", "start": v["start"], "end": v["end"], "family": v["category"], "kind": (ep := v["episodes"][0])["label"],
"description": f"{ep['label']}. {v['text']}", "sensors": v["sensors"], "ignore": v["ignore"],
"targets": [s for s in v["sensors"] if s not in refs], "references": [s for s in v["sensors"] if s in refs],
"message": client.message(v["text"]), "action": client.action(v["category"], ep["label"], ep.get("level"), advice)}
for i, v in enumerate(window(set_, every, a, b))]
# --- the labels
def label_file(station, source):
if source not in FOLDERS:
raise Refusal("unknown label folder")
folder(station)
return LABELS / source / f"{serial(station)}.jsonl"
CORE = ("start", "end", "family", "description") # what a label says; the rest (id, review, analysis) is about it
def core(label):
return tuple(label.get(k) for k in CORE)
def write(f, labels):
"""Writes the labels next to the file then replaces it: an interruption does not damage it."""
temp = f.with_name(f.name + ".tmp")
temp.write_text("".join(json.dumps(e, ensure_ascii=False) + "\n" for e in labels), encoding="utf-8")
os.replace(temp, f)
def read(station, source):
f = label_file(station, source)
# split and not splitlines: the latter would also cut on the Unicode separators the text may contain
return [json.loads(l) for l in f.read_text(encoding="utf-8").split("\n") if l.strip()] if f.exists() else []
def checked(label):
"""A label written in auto/: the rules of labeling (labeling/scripts/validate.py, check), before its id."""
if errors := validate.check(label, proposed=True):
raise Refusal("; ".join(errors))
def checked_range(start, end):
"""A range asked by the page: YYYY-MM-DDTHH:MMZ, start before end."""
try:
if datetime.strptime(start, FORMAT) < datetime.strptime(end, FORMAT):
return
except (TypeError, ValueError):
pass
raise Refusal("unreadable or empty range (YYYY-MM-DDTHH:MMZ)")
def add(body):
station, source = body.get("station"), body.get("folder", "auto")
f = label_file(station, source)
label = {"start": body.get("start"), "end": body.get("end"), "family": body.get("family"),
"description": (body.get("description") or "").strip()}
checked(label)
ids.assign(serial(station), read(station, source) + [label]) # a stable id, the next of its station (D-131)
f.parent.mkdir(parents=True, exist_ok=True)
before = f.read_bytes() if f.exists() else b"" # a line removed by hand may leave the file without a final newline
with open(f, "ab") as out:
out.write(b"\n" * bool(before and not before.endswith(b"\n")) + json.dumps(label, ensure_ascii=False).encode() + b"\n")
return label
def update(body):
before = body.get("before") or {}
start, end = body.get("start", before.get("start")), body.get("end", before.get("end"))
label = dict.fromkeys(("id", "start", "end", "family")) | before | {"start": start, "end": end, "family": body.get("family"),
"description": (body.get("description") or "").strip()}
if label["id"] is None:
del label["id"]
label.pop("review", None) # changed: no longer reviewed
checked(label)
return replace(body.get("station"), body.get("folder", "auto"), before, label)
def delete(body):
replace(body.get("station"), body.get("folder", "auto"), body.get("before"), None)
return body.get("before")
def replace(station, source, before, label):
"""Replaces the label before by label (None: removes it), found by its content, not by its rank: the file may have
changed since the page was loaded. Writes next to it then replaces: an interruption does not damage the file."""
f = label_file(station, source)
lines = f.read_text(encoding="utf-8").split("\n") if f.exists() else []
for i, line in enumerate(lines):
if line.strip() and json.loads(line) == before:
lines[i:i + 1] = [] if label is None else [json.dumps(label, ensure_ascii=False)]
temp = f.with_name(f.name + ".tmp")
temp.write_text("\n".join(lines), encoding="utf-8")
os.replace(temp, f)
if before.get("analysis"):
analysis_label(before, label)
return label
raise Refusal("this label is no longer in the file: reload the page")
def analysis_label(before, label):
"""A label of an analysis edited or removed in the page: the same in the labels.jsonl of the analysis, which says
whether it is validated (its review); a resubmission then keeps the edit."""
f = LABELS / "auto" / "analyses" / before["analysis"] / "labels.jsonl"
if not f.exists():
return
labels = [json.loads(l) for l in f.read_text(encoding="utf-8").split("\n") if l.strip()]
for i, e in enumerate(labels):
if core(e) == core(before):
labels[i:i + 1] = [] if label is None else [{k: label[k] for k in (*CORE, "review") if k in label}]
write(f, labels)
return