Download src/cell_tracking/data/wormtrack_verify/adapters.py from pytc/trackingBench: direct link, hf CLI and curl.
- Browser
- Download file 5.06 kB
-
https://huggingface.co/datasets/pytc/trackingBench/resolve/main/src/cell_tracking/data/wormtrack_verify/adapters.py
- Command line
-
hf download hf://datasets/pytc/trackingBench/src/cell_tracking/data/wormtrack_verify/adapters.py
-
curl -L -o adapters.py https://huggingface.co/datasets/pytc/trackingBench/resolve/main/src/cell_tracking/data/wormtrack_verify/adapters.py
5.06 kB
| """Native ASCENT and ZephIR table adapters with conservative annotation provenance.""" | |
| from __future__ import annotations | |
| import numpy as np | |
| import pandas as pd | |
| XYZ = ["x_voxel", "y_voxel", "z_voxel"] | |
| TRUSTED = {"human_corrected", "manually_verified", "verified_checkpoint"} | |
| def _physical(df, spacing_xyz): | |
| for axis, scale in zip("xyz", spacing_xyz or [None] * 3, strict=True): | |
| df[f"{axis}_um"] = df[f"{axis}_voxel"] * scale if scale is not None else np.nan | |
| df["coordinate_system"] = "source_microscope" | |
| df["annotation_confidence"] = np.nan | |
| df["validity"] = True | |
| return df | |
| def ascent_tracks(path, recording_id, *, predicted=False): | |
| """Read native ZYX CSV; physical spacing is from Zenodo 17561700 metadata.""" | |
| df = pd.read_csv(path).rename( | |
| columns={ | |
| "TrackID": "track_id", | |
| "ObjectID": "detection_id", | |
| "t": "frame_index", | |
| "x": "x_voxel", | |
| "y": "y_voxel", | |
| "z": "z_voxel", | |
| } | |
| ) | |
| required = {"track_id", "detection_id", "frame_index", *XYZ} | |
| if not required.issubset(df.columns): | |
| raise ValueError(f"Missing ASCENT fields: {sorted(required - set(df.columns))}") | |
| df["recording_id"] = recording_id | |
| df["annotation_type"] = "algorithm_prediction" if predicted else "human_corrected" | |
| df["source_provenance"] = "ASCENT-PRED" if predicted else "ASCENT-GT-proofread-ZephIR" | |
| df["label_set"] = "prediction" if predicted else "reference" | |
| df["track_id"] = df.track_id.astype(str) | |
| df["detection_id"] = df.detection_id.map(lambda i: f"{'pred' if predicted else 'gt'}:{i}") | |
| return _physical(df, [0.243, 0.243, 1.5]) | |
| def zephir_tracks(path, metadata, recording_id): | |
| """Retain scorer codes; only documented ZEIR results are classified as predictions. | |
| Other codes remain unknown until their human/algorithm provenance is verified. | |
| Normalized coordinates map to voxel index x*size-0.5 using the native viewer | |
| convention. No voxel spacing is inferred from the neuron arrangement. | |
| """ | |
| import h5py | |
| with h5py.File(path, "r") as h: | |
| df = pd.DataFrame({k: h[k][()] for k in h}) | |
| df = df.rename( | |
| columns={ | |
| "t_idx": "frame_index", | |
| "worldline_id": "track_id", | |
| "id": "detection_id", | |
| "provenance": "source_provenance", | |
| } | |
| ) | |
| df["source_provenance"] = df.source_provenance.map(lambda s: s.decode("utf-8")) | |
| for axis in "xyz": | |
| df[f"{axis}_normalized"] = df[axis] | |
| df[f"{axis}_voxel"] = df[axis] * metadata[f"shape_{axis}"] - 0.5 | |
| df = df.drop(columns=axis) | |
| df["annotation_type"] = np.where( | |
| df.source_provenance == "ZEIR", "algorithm_prediction", "unknown" | |
| ) | |
| df["recording_id"] = recording_id | |
| df["label_set"] = "source_mixed" | |
| df["track_id"] = df.track_id.astype(str) | |
| df["detection_id"] = df.detection_id.map(lambda i: f"source:{i}") | |
| df = _physical(df, None) | |
| normalized = df[[f"{axis}_normalized" for axis in "xyz"]].to_numpy(dtype=float) | |
| df["validity"] = ( | |
| np.isfinite(normalized).all(axis=1) | |
| & (normalized >= 0).all(axis=1) | |
| & (normalized <= 1).all(axis=1) | |
| ) | |
| return df | |
| def validate_tracks(df, *, shape_xyz=None): | |
| """Reject ambiguous assignments and nonfinite observed points; never clamp or interpolate.""" | |
| required = { | |
| "recording_id", | |
| "frame_index", | |
| "track_id", | |
| "detection_id", | |
| *XYZ, | |
| "annotation_type", | |
| "label_set", | |
| "validity", | |
| } | |
| if not required.issubset(df.columns): | |
| raise ValueError(f"Missing fields: {sorted(required - set(df.columns))}") | |
| if df.empty: | |
| raise ValueError("Empty tracking table") | |
| valid = df.loc[df.validity] | |
| scope = ["recording_id", "label_set", "frame_index"] | |
| if valid.duplicated(scope + ["track_id"]).any(): | |
| raise ValueError("Duplicate track assignments") | |
| if valid.duplicated(scope + ["detection_id"]).any(): | |
| raise ValueError("Duplicate detection assignments") | |
| if valid.track_id.isna().any() or valid.detection_id.isna().any(): | |
| raise ValueError("Missing identity on a valid observation") | |
| if not np.isfinite(valid[XYZ].to_numpy(dtype=float)).all(): | |
| raise ValueError("Nonfinite observed coordinates") | |
| if (valid.frame_index < 0).any() or (valid.frame_index % 1 != 0).any(): | |
| raise ValueError("Invalid frame index") | |
| # Centers use pixel boundaries [-0.5, size-0.5], including ZephIR normalized endpoints. | |
| if shape_xyz is not None: | |
| points = valid[XYZ].to_numpy(dtype=float) | |
| if ((points < -0.5) | (points > np.asarray(shape_xyz) - 0.5)).any(): | |
| raise ValueError("Spatial coordinates outside source bounds") | |
| return { | |
| "observations": len(valid), | |
| "frames": int(valid.frame_index.nunique()), | |
| "tracks": int(valid.track_id.nunique()), | |
| "annotation_types": { | |
| str(k): int(v) for k, v in valid.annotation_type.value_counts().items() | |
| }, | |
| } | |