Files
aimsight-labeling/scripts/points.py
T

160 lines
6.5 KiB
Python

"""The point labels: one boolean per measurement (sensor and time) on a chosen range, valid or not, set by the user in
aimsight-app (page Points). No family, no cause: the ground truth of the benchmarks, point by point.
python3 labeling/scripts/points.py # checks every dataset of points/
python3 labeling/scripts/points.py --test # the self-check of this file
A dataset: `points/<STATION>_<start>_<end>.csv` (`<STATION>` a station of data/ or a run, `<SERIAL>@<run>`) (days, UTC, end excluded), one line per measurement of the range,
`sensor_name,time_utc,valid` (`time_utc` `YYYY-MM-DDTHH:MM:SSZ`, `valid` 1 or 0), sorted by sensor then time. Created
with every point valid; a point is every measurement with a relative position (`relative_x`, `relative_y`), the
rejected ones included: the truth is the user's, not the platform's threshold. Standard library.
"""
import csv
import os
import re
import sys
from datetime import datetime, timezone
FOLDER = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "points")
HEADER = ["sensor_name", "time_utc", "valid"]
# a station of data/, or a run of the emulator <SERIAL>@<run> (data_diff/<SERIAL>/runs/<run>/: its own measurements)
NAME = re.compile(r"^([A-Za-z0-9_-]+(?:@[A-Za-z0-9_-]+)?)_(\d{4}-\d{2}-\d{2})_(\d{4}-\d{2}-\d{2})$")
TIME = "%Y-%m-%dT%H:%M:%SZ"
def name(station, start, end):
"""-> the name of the dataset of a station over [start, end) (days); refuses what would not be one."""
n = f"{station}_{start}_{end}"
if not NAME.match(n) or not start < end:
raise ValueError(f"not a dataset: station {station!r}, from {start!r} to {end!r} (days YYYY-MM-DD, start before end)")
return n
def parts(n):
"""'NORDEND_2026-11-01_2026-11-02' -> ('NORDEND', '2026-11-01', '2026-11-02')."""
m = NAME.match(n)
if not m:
raise ValueError(f"not a dataset: {n!r}")
return m.groups()
def path(n):
parts(n)
return os.path.join(FOLDER, n + ".csv")
def time(t):
"""A UTC datetime -> the time_utc of a line."""
return t.astimezone(timezone.utc).strftime(TIME)
def write(n, points):
"""points: {(sensor, time_utc): bool} -> the file, sorted."""
os.makedirs(FOLDER, exist_ok=True)
tmp = path(n) + ".tmp"
with open(tmp, "w", newline="") as f:
w = csv.writer(f, lineterminator="\n")
w.writerow(HEADER)
w.writerows([s, t, int(v)] for (s, t), v in sorted(points.items()))
os.replace(tmp, path(n)) # never a half-written dataset
def create(n, measurements):
"""measurements: {sensor: [UTC datetime]} of the range -> the dataset, every point valid; refuses one that exists."""
if os.path.exists(path(n)):
raise ValueError(f"the dataset {n} exists")
points = {(s, time(t)): True for s, ts in measurements.items() for t in ts}
if not points:
raise ValueError(f"no measurement for {n}")
write(n, points)
return points
def read(n):
"""-> {(sensor, time_utc): bool}, the points of the dataset (the benchmark reads it so)."""
with open(path(n), newline="") as f:
return {(r["sensor_name"], r["time_utc"]): r["valid"] == "1" for r in csv.DictReader(f)}
def mark(n, sensor, times, valid):
"""Sets the points (sensor, each time) valid or not -> the points; refuses a point the dataset does not have."""
points = read(n)
missing = [t for t in times if (sensor, t) not in points]
if missing:
raise ValueError(f"{len(missing)} point(s) not in {n}, the first: {sensor} {missing[0]}")
points.update({(sensor, t): bool(valid) for t in times})
write(n, points)
return points
def datasets(station=None):
"""-> the names of the datasets, of one station or all."""
names = sorted(f[:-4] for f in os.listdir(FOLDER) if f.endswith(".csv") and NAME.match(f[:-4])) if os.path.isdir(FOLDER) else []
return [n for n in names if station is None or parts(n)[0] == station]
def check(n):
"""-> the errors of a dataset: header, valid 0 or 1, times in UTC and in the range, no point twice, sorted."""
_, start, end = parts(n)
errors, seen, last = [], set(), None
with open(path(n), newline="") as f:
r = csv.reader(f)
if next(r, None) != HEADER:
return [f"{n}: the header is not {','.join(HEADER)}"]
for i, row in enumerate(r, 2):
if len(row) != 3:
errors.append(f"{n}:{i}: {len(row)} fields")
continue
s, t, v = row
try:
ok = datetime.strptime(t, TIME) and start <= t[:10] < end
except ValueError:
ok = False
if not ok:
errors.append(f"{n}:{i}: time {t!r} not {TIME} in [{start}, {end})")
if v not in ("0", "1"):
errors.append(f"{n}:{i}: valid {v!r}, not 0 or 1")
if (s, t) in seen:
errors.append(f"{n}:{i}: {s} {t} twice")
elif last and (s, t) < last:
errors.append(f"{n}:{i}: not sorted by sensor then time")
seen.add((s, t))
last = (s, t)
return errors
def test():
import tempfile
global FOLDER
keep, FOLDER = FOLDER, tempfile.mkdtemp()
try:
n = name("X1", "2026-01-01", "2026-01-02")
a, b = datetime(2026, 1, 1, 0, 10, tzinfo=timezone.utc), datetime(2026, 1, 1, 0, 20, tzinfo=timezone.utc)
create(n, {"T2": [a], "T1": [b, a]})
assert parts(name("X1@run01", "2026-01-01", "2026-01-02"))[0] == "X1@run01"
assert all(read(n).values()) and len(read(n)) == 3 and datasets() == [n] == datasets("X1") and datasets("X") == []
p = mark(n, "T1", [time(b)], False)
assert p[("T1", time(b))] is False and p[("T1", time(a))] is True and read(n) == p and check(n) == []
for bad in (lambda: mark(n, "T2", [time(b)], False), lambda: create(n, {"T1": [a]}),
lambda: name("X/1", "2026-01-01", "2026-01-02"), lambda: name("X1", "2026-01-02", "2026-01-01")):
try:
bad()
raise AssertionError("not refused")
except ValueError:
pass
with open(path(n), "a") as f:
f.write("T1,2026-01-02T00:00:00Z,2\n")
assert len(check(n)) == 3 # out of the range, valid 2, after T2
finally:
FOLDER = keep
print("points.py: ok")
if __name__ == "__main__":
if "--test" in sys.argv:
test()
else:
errors = [e for n in datasets() for e in check(n)]
print("\n".join(errors) or f"{len(datasets())} dataset(s), 0 errors")
sys.exit(1 if errors else 0)