"""Explicit pilot diagnostics for association-only corruption and abstention. These metrics are defined in the benchmark specification, not replacements for canonical HOTA/IDF1. Detections stay fixed. One global identity alignment is allowed. """ from __future__ import annotations import itertools import numpy as np import pandas as pd from scipy.optimize import linear_sum_assignment from sklearn.metrics import average_precision_score, roc_auc_score from cell_tracking.data.wormtrack_verify.adapters import TRUSTED, XYZ, validate_tracks def corrupt_tracks(tracks, *, kind, seed, start_frame, stop_frame=None, pair=None): """Deterministic swaps/fragmentation with row-level error labels and fixed observations. Labels mark correspondence to the original reference identity. Purely global renaming is not an error; start_frame must follow the first reference frame. Original images, detection IDs, and coordinates are preserved. """ validate_tracks(tracks) if not set(tracks.annotation_type).issubset(TRUSTED): raise ValueError("Corruptions require independently trusted source annotations") if tracks.recording_id.nunique() != 1 or tracks.label_set.nunique() != 1: raise ValueError("Corrupt one recording and one label set at a time") frames = sorted(tracks.frame_index.unique()) if start_frame <= frames[0] or start_frame > frames[-1]: raise ValueError("Corruption must follow the identity anchor and lie inside the recording") stop_frame = frames[-1] + 1 if stop_frame is None else stop_frame if stop_frame <= start_frame or stop_frame > frames[-1] + 1: raise ValueError("Invalid corruption interval") rng = np.random.default_rng(seed) ids = sorted(tracks.track_id.unique()) if pair is None: if len(ids) < 2: raise ValueError("Need two tracks") pair = list(rng.choice(ids, 2, replace=False)) if len(pair) != 2 or pair[0] == pair[1] or not set(pair).issubset(ids): raise ValueError("Pair must identify two distinct source tracks") df = tracks.copy() df["reference_track_id"] = df.track_id interval = (df.frame_index >= start_frame) & (df.frame_index < stop_frame) affected = interval & df.track_id.isin(pair) if not affected.any(): raise ValueError("No observations in the selected corruption interval") if kind in {"single_frame_swap", "persistent_swap", "swap_recovery", "nearby_swap"}: if kind == "single_frame_swap": affected &= df.frame_index == start_frame df.loc[affected, "track_id"] = df.loc[affected, "track_id"].map( {pair[0]: pair[1], pair[1]: pair[0]} ) elif kind == "fragmentation": affected = interval & (df.track_id == pair[0]) df.loc[affected, "track_id"] = pair[0] + f":fragment:{seed}" elif kind == "dropout": affected = interval & (df.track_id == pair[0]) df.loc[affected, "validity"] = False else: raise ValueError(f"Unsupported pilot corruption: {kind}") df["is_error"] = affected df["corruption_type"] = kind df["seed"] = seed df["scenario_id"] = f"{kind}:seed{seed}" return df def association_metrics(reference, prediction): """Score shared oracle detections with one recording-wide identity permutation. Missing predictions count against coverage and correct-observation rate. Switches are changes in predicted identity along each reference trajectory; fragmented runs also count reappearance after a missing prediction. Evaluation covers only source-supported reference observations, not unannotated frames. """ validate_tracks(reference) validate_tracks(prediction) if reference.recording_id.nunique() != 1 or prediction.recording_id.nunique() != 1: raise ValueError("Evaluate each independent recording separately") if reference.recording_id.iloc[0] != prediction.recording_id.iloc[0]: raise ValueError("Mismatched recording") key = ["frame_index", "detection_id"] valid_prediction = prediction.loc[prediction.validity] joined = reference.loc[reference.validity].merge( valid_prediction[key + ["track_id"]], on=key, how="left", suffixes=("_gt", "_pred"), validate="one_to_one", ) gt = sorted(joined.track_id_gt.unique()) pred = sorted(valid_prediction.track_id.unique()) counts = ( pd.crosstab(joined.track_id_gt, joined.track_id_pred) .reindex(index=gt, columns=pred, fill_value=0) .to_numpy() ) mapping = {} if counts.size: rows, cols = linear_sum_assignment(-counts) mapping = {pred[c]: gt[r] for r, c in zip(rows, cols, strict=True)} correct = joined.track_id_pred.map(mapping).eq(joined.track_id_gt) switches = fragments = 0 for _, group in joined.sort_values("frame_index").groupby("track_id_gt"): ids = group.track_id_pred.tolist() observed = [i for i in ids if pd.notna(i)] switches += sum(a != b for a, b in itertools.pairwise(observed)) fragments += max( 0, sum( pd.notna(v) and (j == 0 or pd.isna(ids[j - 1]) or v != ids[j - 1]) for j, v in enumerate(ids) ) - 1, ) extra = len( valid_prediction.merge(joined[key], on=key, how="left", indicator=True).query( '_merge == "left_only"' ) ) return { "reference_observations": len(joined), "predicted_observations": len(valid_prediction), "coverage": float(joined.track_id_pred.notna().mean()), "correct_observation_rate": float(correct.mean()), "identity_switches": int(switches), "fragmentations": int(fragments), "extra_observations": int(extra), } def reference_residual_scores(tracks, reference_cloud, *, physical=True): """Identity-sensitive distance from the fixed first-frame reference. This intentionally simple consistency diagnostic includes genuine tissue motion. It is not an independent deformation model or a certificate of correctness. Reference cloud must come from an independently trusted reference observation. """ cols = [f"{a}_um" for a in "xyz"] if physical else XYZ ref = reference_cloud.set_index("track_id") if ref.index.duplicated().any(): raise ValueError("Reference identities must be unique") a = tracks[cols].to_numpy(dtype=float) b = ref.reindex(tracks.track_id)[cols].to_numpy(dtype=float) scores = np.linalg.norm(a - b, axis=1) scores[~tracks.validity.to_numpy()] = np.inf # Unseen fragment IDs are unsupported; preserve absence rather than fit a new anatomy. scores[np.isnan(scores)] = np.inf return scores def verifier_metrics(scores, is_error, *, threshold): """Fixed-population selective risk/coverage; ties enter a risk curve together. False certification = accepted errors / all labeled errors. Selective risk = accepted errors / accepted observations. Unsupported scores abstain. Threshold must be specified before evaluation; this function does not select it. """ scores = np.asarray(scores, dtype=float) labels = np.asarray(is_error, dtype=bool) if len(scores) != len(labels) or not len(scores) or np.isnan(scores).any(): raise ValueError("Scores and labels must be aligned, nonempty, and non-NaN") if np.isnan(threshold): raise ValueError("Threshold cannot be NaN") accept = np.isfinite(scores) & (scores <= threshold) # Infinity denotes abstention; map it above all finite scores for ranking metrics. finite = scores[np.isfinite(scores)] ranked = np.where(np.isfinite(scores), scores, (finite.max() + 1 if len(finite) else 1)) both = labels.any() and not labels.all() curve = [] order = np.flatnonzero(np.isfinite(scores)) order = order[np.argsort(scores[order], kind="stable")] if len(order): ordered_scores = scores[order] cumulative_errors = np.cumsum(labels[order]) ends = np.r_[np.flatnonzero(np.diff(ordered_scores) != 0), len(order) - 1] curve = [ { "threshold": float(ordered_scores[i]), "coverage": float((i + 1) / len(scores)), "risk": float(cumulative_errors[i] / (i + 1)), } for i in ends ] return { "observations": len(scores), "error_prevalence": float(labels.mean()), "auroc": float(roc_auc_score(labels, ranked)) if both else None, "auprc": float(average_precision_score(labels, ranked)) if both else None, "false_certification_rate": float((accept & labels).sum() / labels.sum()) if labels.any() else None, "certified_coverage": float(accept.mean()), "selective_risk": float(labels[accept].mean()) if accept.any() else None, "correct_certified_coverage": float((accept & ~labels).mean()), "threshold": float(threshold), "risk_coverage": curve, } def oracle_association_baseline(detections, *, method="hungarian", physical=True): """Untrained Euclidean nearest-neighbor or bipartite association on fixed detections.""" if method not in {"nearest_neighbor", "hungarian"}: raise ValueError(method) cols = [f"{a}_um" for a in "xyz"] if physical else XYZ output = [] previous = None next_id = 0 for frame, points in detections.sort_values("frame_index").groupby("frame_index"): points = points.copy().reset_index(drop=True) xyz = points[cols].to_numpy(dtype=float) if not np.isfinite(xyz).all(): raise ValueError("Baseline requires valid coordinates in the selected units") ids = [None] * len(points) if previous is not None: old_xyz, old_ids = previous distance = np.linalg.norm(old_xyz[:, None] - xyz[None], axis=2) if method == "hungarian": rows, columns = linear_sum_assignment(distance) else: pairs = sorted((distance[i, j], i, j) for i, j in enumerate(distance.argmin(1))) chosen = set() matches = [] for _, i, j in pairs: if j not in chosen: matches.append((i, j)) chosen.add(j) rows = [p[0] for p in matches] columns = [p[1] for p in matches] for i, j in zip(rows, columns, strict=True): ids[j] = old_ids[i] for i, identity in enumerate(ids): if identity is None: ids[i] = f"baseline:{next_id}" next_id += 1 points["track_id"] = ids points["annotation_type"] = "algorithm_prediction" points["label_set"] = "prediction" output.append(points) previous = xyz, ids return pd.concat(output, ignore_index=True)