points: the point labels, one boolean per measurement of a range (valid or not), set by hand in aimsight-app; scripts/points.py reads, writes and checks them
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
74b161b0a1
commit
16582782b2
3 files changed
+161
-3
No files matched your search
@@ -2,11 +2,11 @@
|
||||
|
||||
labeling: the AIMsight displacement labels and the knowledge to place them, in a single copy on the workstation (`README.md`). aimsight-app reads and writes there, Optimizer only reads, both through a link `labeling -> ~/aimsight-labeling`; the support agent writes its folders in `auto/support/`; commits are made here.
|
||||
|
||||
- **The labels**: `manual/<STATION>.jsonl` (the expert, for him alone), `auto/<STATION>.jsonl` (the agents; `review` = the date the user validated the label in aimsight-app, nothing else writes it), one per line, `{"id", "start", "end", "family", "description", ...}`. The aimsight-app analyses: `auto/analyses/<STATION>_<start>_<end>/`. The support agent's folders: `auto/support/<YYYY-MM-DD>_<subject>/`. The cases: `auto/cases/<id>.json`, built by the `cases` skill (`/cases`) from the labels; `review` there is written by the user in the JSON.
|
||||
- **The labels**: `manual/<STATION>.jsonl` (the expert, for him alone), `auto/<STATION>.jsonl` (the agents; `review` = the date the user validated the label in aimsight-app, nothing else writes it), one per line, `{"id", "start", "end", "family", "description", ...}`. The aimsight-app analyses: `auto/analyses/<STATION>_<start>_<end>/`. The support agent's folders: `auto/support/<YYYY-MM-DD>_<subject>/`. The cases: `auto/cases/<id>.json`, built by the `cases` skill (`/cases`) from the labels; `review` there is written by the user in the JSON. The point labels: `points/<STATION>_<start>_<end>.csv` (days, end excluded), one line per measurement of the range, `sensor_name,time_utc,valid` (1 or 0), set by hand by the user in aimsight-app (page Points), every point valid at the creation; no family, no cause: the ground truth of the benchmarks, point by point.
|
||||
- **The knowledge**, one source per kind (`README.md`), maintained by hand: `families.md` (the families, their boundaries), `labeling-rules.md` (bounds, a single event, description, stated cause), `reading-rules.md` (what the data mean), `stations.md` (the installations); the phenomena, false friends and lessons are the cases, `auto/cases/`, through `cases.py`; the labels themselves through `precedents.py`; what the data are: `tools/DATA.md`. A piece of knowledge lives in one of them only.
|
||||
- **The tools**, standard library: `python3 scripts/validate.py [STATION | file.jsonl | cases]` (the rules), `python3 scripts/ids.py [STATION]` (the stable id of new labels), `python3 scripts/client.py` (what the client is told of a detectors' event, from `families.md`; its check), `python3 scripts/cases.py "<text>" [--family F] [--k N]` (the RAG of the cases; it starts the Ollama container `ollama-bge-m3` by itself if it does not answer; `--list` and `--check` without it), `python3 scripts/precedents.py "<text>" [--exclude STATION START END] [--family F] [--k N]` (the RAG of the labels; `--check` without Ollama).
|
||||
- **The tools**, standard library: `python3 scripts/validate.py [STATION | file.jsonl | cases]` (the rules), `python3 scripts/ids.py [STATION]` (the stable id of new labels), `python3 scripts/client.py` (what the client is told of a detectors' event, from `families.md`; its check), `python3 scripts/cases.py "<text>" [--family F] [--k N]` (the RAG of the cases; it starts the Ollama container `ollama-bge-m3` by itself if it does not answer; `--list` and `--check` without it), `python3 scripts/precedents.py "<text>" [--exclude STATION START END] [--family F] [--k N]` (the RAG of the labels; `--check` without Ollama), `python3 scripts/points.py` (the point labels: `create`, `read`, `mark`, `datasets`, their check; `--test`).
|
||||
- **For aimsight-app**, which calls them and holds no rule of its own: `validate.check(label, proposed)` (the rules of one label, before it is written in `auto/`), `ids.assign`, `client.message` and `client.action` (the "For the client" columns of `families.md`, per family and per variety). A rename here needs the change there.
|
||||
- **Verify**: `python3 scripts/validate.py` (0 errors expected), `python3 scripts/validate.py --check`, `python3 scripts/cases.py --check` and `python3 scripts/precedents.py --check`.
|
||||
- **Verify**: `python3 scripts/validate.py` (0 errors expected), `python3 scripts/validate.py --check`, `python3 scripts/cases.py --check` and `python3 scripts/precedents.py --check`, `python3 scripts/points.py` and `python3 scripts/points.py --test`.
|
||||
|
||||
Rules:
|
||||
- **`manual/` is the expert's, for him alone**: no agent and no process reads or writes there; the whole project (analyst, cases, precedents, benchmark, optimization) uses only `auto/`.
|
||||
|
||||
@@ -6,6 +6,7 @@ The AIMsight displacement labels and all the domain knowledge to place them, in
|
||||
- `auto/analyses/<STATION>_<start>_<end>/`: the analyses launched from the Data page of aimsight-app (`work/` outside git).
|
||||
- `auto/support/<YYYY-MM-DD>_<subject>/`: the folders of the `support` agent (agents repository): the request, the answer, the analyst's work when it was called (`work/` outside git).
|
||||
- `auto/cases/<id>.json`: the cases, the phenomena, false friends and lessons drawn from the labels, one JSON file each (`docs/superpowers/specs/2026-11-18-cases-design.md`); built and refreshed by the `cases` skill (`/cases`, `.claude/skills/cases/`), which never writes `review` nor commits; `review` is the date the user validated a case, written by the user in its JSON, removed by the skill when it changes the case's text; `auto/cases/.read.json`, the skill's state (which case each label went to).
|
||||
- `points/<STATION>_<start>_<end>.csv`: the point labels, one boolean per measurement of a range (days, UTC, end excluded), `sensor_name,time_utc,valid` (1 valid, 0 invalid), set by hand in the Points page of aimsight-app; created with every point valid; no family, no cause: the ground truth of the benchmarks, point by point. The rejected measurements (without `corr_x`, `corr_y`) are not points. `scripts/points.py` reads, writes and checks them.
|
||||
- The knowledge, one source per kind, maintained by hand by the user, but for the cases; the analyst reads the four files in full and searches the cases:
|
||||
|
||||
| Kind of knowledge | Source |
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
"""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` (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; the measurements are those the station delivered with a position (rejected ones, without
|
||||
`corr_x`, `corr_y`, are not points). 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"]
|
||||
NAME = re.compile(r"^([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 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)
|
||||
Reference in new issue
Block a user