File size: 10,991 Bytes
bc88015
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
"""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)