xkronosx's picture
Cryo-EM acquisition dataset: 4 EPU sessions, labels, features, loader + validator
d67b900 verified
Raw
History Blame Contribute Delete
7.62 kB
"""Check an index against the contract. Run this on a new dataset FIRST.
python -m cryoem_au_data.validate <index_dir>
Every check corresponds to a failure we have actually hit. The ones marked
FATAL break training silently rather than loudly, which is why they are checks
and not comments.
"""
from __future__ import annotations
import sys
from pathlib import Path
import numpy as np
import pandas as pd
from .load import TABLES, load_index, compute_utility
from .schema import (
GEOMETRY_REQUIRED, HOLES_REQUIRED, HOLE_UID_RE, LABEL_REQUIRED,
OPERATOR_ONLY, SQUARE_UID_RE, STATUSES, STATUS_OK, TARGET_REQUIRED,
session_of,
)
class Report:
def __init__(self) -> None:
self.fatal: list[str] = []
self.warn: list[str] = []
self.info: list[str] = []
def check(self, ok: bool, message: str, fatal: bool = True) -> bool:
if ok:
self.info.append(f"ok {message}")
elif fatal:
self.fatal.append(f"FATAL {message}")
else:
self.warn.append(f"warn {message}")
return ok
def show(self) -> int:
for line in self.info:
print(line)
for line in self.warn:
print(line)
for line in self.fatal:
print(line)
print()
if self.fatal:
print(f"{len(self.fatal)} FATAL problem(s): the agents will not train correctly.")
return 1
if self.warn:
print(f"passed with {len(self.warn)} warning(s).")
return 0
print("passed.")
return 0
def validate(index_dir) -> int:
root = Path(index_dir)
r = Report()
tables = load_index(root)
targets, holes = tables["target_locations"], tables["holes"]
geometry, labels = tables["square_geometry"], tables["labels_v4_outcomes"]
for name, frame, required in (
("target_locations", targets, TARGET_REQUIRED),
("holes", holes, HOLES_REQUIRED),
("square_geometry", geometry, GEOMETRY_REQUIRED),
("labels_v4_outcomes", labels, LABEL_REQUIRED),
):
missing = [c for c in required if c not in frame.columns]
r.check(not missing, f"{name}: required columns present"
+ (f" (missing {missing})" if missing else ""))
# --- UID grammar: the silent-failure class -------------------------------
bad = [u for u in targets["hole_uid"].astype(str)[:5000] if not HOLE_UID_RE.match(u)]
r.check(not bad, "hole_uid matches session:<name>:square:<id>:hole:<id>"
+ (f" (e.g. {bad[0]!r})" if bad else ""))
bad_sq = [u for u in geometry["square_uid"].astype(str)[:5000] if not SQUARE_UID_RE.match(u)]
r.check(not bad_sq, "square_uid matches session:<name>:square:<id>"
+ (f" (e.g. {bad_sq[0]!r})" if bad_sq else ""))
sessions = sorted({session_of(u) for u in targets["hole_uid"].astype(str)})
r.check(len(sessions) >= 1, f"sessions found: {len(sessions)}")
# --- joins ---------------------------------------------------------------
r.check(labels["sample_id"].is_unique, "sample_id is unique in labels")
orphan = set(labels["hole_uid"]) - set(targets["hole_uid"])
r.check(not orphan, f"every labelled hole_uid appears in target_locations"
+ (f" ({len(orphan)} orphans)" if orphan else ""))
orphan_sq = set(targets["square_uid"]) - set(geometry["square_uid"])
r.check(not orphan_sq, f"every square_uid has geometry"
+ (f" ({len(orphan_sq)} missing)" if orphan_sq else ""),
fatal=False)
# --- candidates vs acquired ---------------------------------------------
ratio = len(targets) / max(len(holes), 1)
r.check(len(targets) > len(holes),
f"target_locations holds ALL candidates, not just acquired "
f"({len(targets):,} candidates / {len(holes):,} acquired = {ratio:.1f}x)")
# --- leakage -------------------------------------------------------------
leaked = OPERATOR_ONLY & set(targets.columns)
r.check(not leaked, f"no operator-derived feature columns"
+ (f" ({sorted(leaked)})" if leaked else ""), fatal=False)
# --- labels --------------------------------------------------------------
unknown = set(labels["status"].astype(str)) - set(STATUSES)
r.check(not unknown, f"status vocabulary is {STATUSES}"
+ (f" (saw {sorted(unknown)})" if unknown else ""))
n_ok = int((labels["status"] == STATUS_OK).sum())
r.check(n_ok > 0, f"{n_ok:,} acquisitions usable for training "
f"({100*n_ok/max(len(labels),1):.0f}%)")
# Replay order. Missing timestamps fall back to a sample_id sort, which is
# alphabetical rather than chronological — usable but not the real order.
# Three of our four reference sessions have none; please do better than we did.
ts = pd.to_datetime(labels["timestamp"], errors="coerce")
per_session_ts = (
labels.assign(_s=[session_of(u) for u in labels["hole_uid"].astype(str)],
_t=ts.notna())
.groupby("_s")["_t"].mean())
bare = sorted(per_session_ts[per_session_ts < 0.5].index)
r.check(not bare,
"every session has timestamps (replay order is chronological)"
+ (f" — missing for {[b.replace('session:','') for b in bare]}" if bare else ""),
fatal=False)
r.check(ts.notna().any() and ts.nunique() > 1,
"timestamps vary where present (not a constant placeholder)", fatal=False)
per_hole = labels.groupby("hole_uid").size()
r.check((per_hole > 1).any(),
f"some holes have repeated acquisitions (max {int(per_hole.max())}) "
"— needed for within-hole variance", fatal=False)
# --- utility reproduces --------------------------------------------------
recomputed = compute_utility(labels)
diff = np.abs(recomputed - labels["utility"].to_numpy(float))
err = float(np.nanmax(diff)) if np.isfinite(diff).any() else float("inf")
r.check(np.isfinite(diff).all() and err < 1e-6,
f"utility column matches the documented formula (max err {err:.2e})")
ok_rows = labels[labels["status"] == STATUS_OK]
if len(ok_rows) > 10:
res = ok_rows["ctf_res_adj"].to_numpy(float)
ice = ok_rows["ice_ring"].to_numpy(float)
gate = 1.0 / (1.0 + np.exp(-(6.0 - res) / 1.5))
r.check(0.02 < gate.std() < 0.6,
f"CTF gate has dynamic range (std {gate.std():.3f}) — if ~0 the "
"6 A target is off the end of this dataset and needs re-tuning",
fatal=False)
r.check(np.isfinite(ice).any() and (ice > 1.5).mean() < 0.95,
f"ice threshold 1.5 is not penalising everything "
f"({100*(ice > 1.5).mean():.0f}% above) — re-tune if it is",
fatal=False)
util = ok_rows["utility"].to_numpy(float)
r.check(util.std() > 0, f"utility varies (mean {util.mean():.1f}, sd {util.std():.1f})")
print(f"index: {root}")
print(f" {len(targets):,} candidate holes · {len(holes):,} acquired · "
f"{len(labels):,} acquisitions · {len(geometry):,} squares")
print(f" sessions: {', '.join(s.replace('session:', '') for s in sessions)}\n")
return r.show()
def main(argv: list[str] | None = None) -> int:
args = sys.argv[1:] if argv is None else argv
if not args:
print(__doc__)
return 2
return validate(args[0])
if __name__ == "__main__":
raise SystemExit(main())