File size: 5,056 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
"""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()
        },
    }