Download src/cell_tracking/data/wormtrack_verify/assembly.py from pytc/trackingBench: direct link, hf CLI and curl.
- Browser
- Download file 28.5 kB
-
https://huggingface.co/datasets/pytc/trackingBench/resolve/main/src/cell_tracking/data/wormtrack_verify/assembly.py
- Command line
-
hf download hf://datasets/pytc/trackingBench/src/cell_tracking/data/wormtrack_verify/assembly.py
-
curl -L -o assembly.py https://huggingface.co/datasets/pytc/trackingBench/resolve/main/src/cell_tracking/data/wormtrack_verify/assembly.py
28.5 kB
| """Build a development pilot from audited, checksum-pinned upstream assets. | |
| Usage: python -m cell_tracking.data.wormtrack_verify.assembly WORKSPACE OUTPUT | |
| Acquisition is deliberately separate: this command never downloads large files. | |
| """ | |
| from __future__ import annotations | |
| import hashlib | |
| import json | |
| import shutil | |
| import sys | |
| from datetime import datetime | |
| from pathlib import Path | |
| from zoneinfo import ZoneInfo | |
| import h5py | |
| import numpy as np | |
| import pandas as pd | |
| from cell_tracking.data.wormtrack_verify.adapters import ( | |
| XYZ, | |
| ascent_tracks, | |
| validate_tracks, | |
| zephir_tracks, | |
| ) | |
| from cell_tracking.data.wormtrack_verify.inventory import DANDI_COHORTS, WORMND_COMMIT | |
| from cell_tracking.evaluation.wormtrack_verify import ( | |
| association_metrics, | |
| corrupt_tracks, | |
| oracle_association_baseline, | |
| reference_residual_scores, | |
| verifier_metrics, | |
| ) | |
| VERSION = "0.1.0-alpha.1" | |
| SEED = 20261007 | |
| def digest(path, algorithm="sha256"): | |
| h = hashlib.new(algorithm) | |
| with Path(path).open("rb") as stream: | |
| for chunk in iter(lambda: stream.read(8 * 1024**2), b""): | |
| h.update(chunk) | |
| return h.hexdigest() | |
| def dump(path, data): | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| path.write_text(json.dumps(data, indent=2, allow_nan=False) + "\n") | |
| def table(root, path, df): | |
| target = root / path | |
| target.parent.mkdir(parents=True, exist_ok=True) | |
| df.to_parquet(target, index=False) | |
| return path | |
| def harmonize_tables(root): | |
| """Align per-recording Parquet schemas without dropping source-specific fields.""" | |
| import pyarrow as pa | |
| import pyarrow.parquet as pq | |
| for folder in Path(root).glob("data/*"): | |
| files = sorted(folder.glob("*.parquet")) | |
| if not files: | |
| continue | |
| schema = pa.unify_schemas( | |
| [pq.read_schema(path) for path in files], promote_options="permissive" | |
| ).remove_metadata() | |
| for path in files: | |
| original = pq.read_table(path) | |
| arrays = [ | |
| original[field.name].cast(field.type) | |
| if field.name in original.column_names | |
| else pa.nulls(original.num_rows, type=field.type) | |
| for field in schema | |
| ] | |
| pq.write_table(pa.Table.from_arrays(arrays, schema=schema), path) | |
| def build(workspace, destination): | |
| workspace, root = Path(workspace), Path(destination) | |
| root.mkdir(parents=True, exist_ok=True) | |
| audit, raw = workspace / "audit", workspace / "raw" | |
| now = datetime.now(ZoneInfo("America/New_York")).isoformat() | |
| sources, recordings, upstream, overlaps = [], [], [], [] | |
| original = pd.read_csv(audit / "wormid-tracking-split.csv") | |
| split_lookup = original.drop_duplicates("filename").set_index("filename") | |
| provenance_path = audit / "dandi-asset-provenance.json" | |
| provenance = json.loads(provenance_path.read_text()) if provenance_path.exists() else {} | |
| subject_groups = {} | |
| for identifier, cohort in DANDI_COHORTS.items(): | |
| release = json.loads((audit / f"dandi-{identifier}-pinned.json").read_text()) | |
| assets = json.loads((audit / f"dandi-{identifier}-assets.json").read_text()) | |
| sources.append( | |
| { | |
| "source_id": f"dandi-{identifier}", | |
| "name": cohort, | |
| "priority": "P0" if identifier not in {"001623", "000981"} else "P1", | |
| "version": assets["version"], | |
| "url": f"https://dandiarchive.org/dandiset/{identifier}/{assets['version']}", | |
| "license": release.get("license"), | |
| "license_status": "verified_release_metadata", | |
| "asset_count": len(assets["assets"]), | |
| "bytes": sum(a["size"] for a in assets["assets"]), | |
| "assembly_status": "inventoried_assets_not_bulk_ingested", | |
| } | |
| ) | |
| for asset in assets["assets"]: | |
| subject = asset["path"].split("/")[0] | |
| rid = f"dandi-{identifier}-{subject}" | |
| animal = f"dandi:{identifier}:{subject}" | |
| subject_groups.setdefault(subject, []).append(rid) | |
| full_name = f"{identifier}/{asset['path']}" | |
| split = split_lookup.loc[full_name] if full_name in split_lookup.index else None | |
| tracking = bool(split.use_for_calcium_task == 1) if split is not None else False | |
| # SF is explicitly excluded from the published trusted tracking subset. | |
| tracking = tracking and cohort != "SF" | |
| record = { | |
| "recording_id": rid, | |
| "source_dataset": f"dandi-{identifier}", | |
| "source_cohort": cohort, | |
| "source_version": assets["version"], | |
| "source_asset": asset["asset_id"], | |
| "source_path": asset["path"], | |
| "source_checksum": json.dumps(provenance.get(asset["asset_id"], {}).get("digest")), | |
| "source_size_bytes": asset["size"], | |
| "lab_id": None, | |
| "animal_id": animal, | |
| "session_id": asset["path"].split("/")[-1].removesuffix(".nwb"), | |
| "species": None, | |
| "sex": None, | |
| "stage": None, | |
| "strain": None, | |
| "fov_region": "unknown", | |
| "acquisition_setup": "unknown", | |
| "shape_tczyx": None, | |
| "voxel_size_um": None, | |
| "timestamps_status": "not_inspected", | |
| "channels": None, | |
| "tracking_gt_level": "not_inspected", | |
| "posture_gt_level": "not_inspected", | |
| "source_overlap_group": subject, | |
| "license": ";".join(release.get("license", [])), | |
| "qc_status": "inventory_only", | |
| "hosted_tracks": False, | |
| "hosted_volume": False, | |
| "wormid_tracking_subset": tracking, | |
| "wormid_fold": str(split.dataset_split) if split is not None else None, | |
| } | |
| recordings.append(record) | |
| upstream.append( | |
| { | |
| "recording_id": rid, | |
| "asset_id": asset["asset_id"], | |
| "source_version": assets["version"], | |
| "path": asset["path"], | |
| "bytes": asset["size"], | |
| "digests": provenance.get(asset["asset_id"], {}).get("digest"), | |
| "location": "external", | |
| "url": f"https://api.dandiarchive.org/api/assets/{asset['asset_id']}/download/", | |
| } | |
| ) | |
| for subject, ids in subject_groups.items(): | |
| if len(ids) > 1: | |
| overlaps.append( | |
| { | |
| "group_id": subject, | |
| "recording_ids": ids, | |
| "status": "potential_same_animal_or_acquisition", | |
| "evidence": "shared upstream subject identifier", | |
| "split_policy": "keep together; prohibit separate test assignments until audited", | |
| } | |
| ) | |
| components, qc, counts = {}, {}, {} | |
| def recording(rid): | |
| return next(r for r in recordings if r["recording_id"] == rid) | |
| def register_tracks(rid, df, shape_xyz): | |
| qc[rid] = validate_tracks(df, shape_xyz=shape_xyz) | |
| qc[rid]["invalid_observations_preserved"] = int((~df.validity).sum()) | |
| counts[rid] = qc[rid] | |
| entry = components.setdefault(rid, {}) | |
| entry["tracks"] = table(root, f"data/tracks/{rid}.parquet", df) | |
| detections = df.drop(columns=["track_id"]).copy() | |
| entry["detections"] = table(root, f"data/detections/{rid}.parquet", detections) | |
| recording(rid).update( | |
| hosted_tracks=True, | |
| qc_status="table_validated", | |
| tracking_gt_level="trusted_human_corrected" | |
| if set(df.annotation_type) == {"human_corrected"} | |
| else "unknown_or_mixed_provenance", | |
| ) | |
| # Small real recordings and trusted ASCENT annotations. | |
| for source, identifier in [ | |
| ("ASCENT", "17561700"), | |
| ("ZephIR", "10818810"), | |
| ("Targettrack", "10008744"), | |
| ]: | |
| meta = json.loads((audit / f"zenodo-{identifier}.json").read_text()) | |
| sources.append( | |
| { | |
| "source_id": source.lower(), | |
| "name": source, | |
| "priority": "P0" if source == "ZephIR" else "P1", | |
| "version": f"10.5281/zenodo.{identifier}", | |
| "url": f"https://zenodo.org/records/{identifier}", | |
| "license": meta["metadata"].get("license", {}).get("id"), | |
| "license_status": "verified_record_metadata", | |
| "asset_count": len(meta["files"]), | |
| "bytes": sum(a["size"] for a in meta["files"]), | |
| "assembly_status": "pilot_assets_and_tables", | |
| } | |
| ) | |
| for asset in meta["files"]: | |
| upstream.append( | |
| { | |
| "recording_id": None, | |
| "source_dataset": source.lower(), | |
| "path": asset["key"], | |
| "bytes": asset["size"], | |
| "digests": {"md5": asset["checksum"].split(":", 1)[-1]}, | |
| "location": "external", | |
| "url": asset["links"]["self"], | |
| } | |
| ) | |
| local = raw / asset["key"] | |
| if local.exists() and digest(local, "md5") != asset["checksum"].split(":", 1)[-1]: | |
| raise ValueError(f"Upstream checksum mismatch: {local.name}") | |
| template = { | |
| "source_checksum": None, | |
| "source_size_bytes": None, | |
| "species": "Caenorhabditis elegans", | |
| "sex": None, | |
| "stage": None, | |
| "strain": None, | |
| "fov_region": "unknown", | |
| "acquisition_setup": "unknown", | |
| "shape_tczyx": None, | |
| "voxel_size_um": None, | |
| "timestamps_status": "unknown", | |
| "channels": None, | |
| "tracking_gt_level": "unknown", | |
| "posture_gt_level": "unavailable", | |
| "license": "CC-BY-4.0", | |
| "qc_status": "inventory_only", | |
| "hosted_tracks": False, | |
| "hosted_volume": False, | |
| "wormid_tracking_subset": False, | |
| "wormid_fold": None, | |
| } | |
| def new_record(rid, source, version, asset, **kwargs): | |
| record = dict( | |
| template, | |
| recording_id=rid, | |
| source_dataset=source, | |
| source_cohort=source, | |
| source_version=version, | |
| source_asset=asset, | |
| source_path=asset, | |
| lab_id=None, | |
| animal_id=rid, | |
| session_id=rid, | |
| source_overlap_group=rid, | |
| ) | |
| record.update(kwargs) | |
| recordings.append(record) | |
| rid = "ascent-opterra" | |
| new_record( | |
| rid, | |
| "ascent", | |
| "10.5281/zenodo.17561700", | |
| "InHouse_Opterra_tracks_GT.csv", | |
| fov_region="head", | |
| acquisition_setup="device_restricted", | |
| strain="ZM9624", | |
| shape_tczyx=json.dumps([1100, 2, 9, 512, 512]), | |
| voxel_size_um=json.dumps([0.243, 0.243, 1.5]), | |
| timestamps_status="nominal_3.3Hz_not_measured_timestamps", | |
| channels=json.dumps( | |
| [ | |
| {"index": 0, "name": "mNeptune", "role": "structural"}, | |
| {"index": 1, "name": "GCaMP6", "role": "calcium"}, | |
| ] | |
| ), | |
| ) | |
| clean = ascent_tracks(raw / "InHouse_Opterra_tracks_GT.csv", rid) | |
| register_tracks(rid, clean, [512, 512, 9]) | |
| pred = ascent_tracks(raw / "InHouse_Opterra_tracks_PRED.csv", rid, predicted=True) | |
| qc["ascent-source-predictions"] = validate_tracks(pred, shape_xyz=[512, 512, 9]) | |
| table(root, "evaluation/source_predictions/ascent.parquet", pred) | |
| # Source-predicted objects differ from oracle detections: do not score these as oracle association. | |
| ref = clean.loc[clean.frame_index == clean.frame_index.min()].copy() | |
| ref["reference_origin"] = "same_animal_human_corrected_reference_frame" | |
| components[rid]["anatomy"] = table(root, f"data/anatomy/{rid}.parquet", ref) | |
| scenarios, verification, results = [], [], {} | |
| clean_control = clean.copy() | |
| clean_control["scenario_id"] = "clean" | |
| clean_control["is_error"] = False | |
| clean_control["reference_track_id"] = clean_control.track_id | |
| clean_control["corruption_type"] = "clean" | |
| clean_control["seed"] = SEED | |
| scenarios.append(clean_control) | |
| # Choose a nearby pair using only the development reference frame. | |
| positions = ref[["x_um", "y_um", "z_um"]].to_numpy() | |
| distance = np.linalg.norm(positions[:, None] - positions[None], axis=2) | |
| np.fill_diagonal(distance, np.inf) | |
| i, j = np.unravel_index(distance.argmin(), distance.shape) | |
| pair = [ref.track_id.iloc[i], ref.track_id.iloc[j]] | |
| for kind in [ | |
| "single_frame_swap", | |
| "persistent_swap", | |
| "swap_recovery", | |
| "nearby_swap", | |
| "fragmentation", | |
| "dropout", | |
| ]: | |
| stop = 700 if kind in {"swap_recovery", "nearby_swap"} else None | |
| corrupted = corrupt_tracks( | |
| clean, | |
| kind=kind, | |
| seed=SEED, | |
| start_frame=300, | |
| stop_frame=stop, | |
| pair=pair if kind == "nearby_swap" else None, | |
| ) | |
| scenarios.append(corrupted) | |
| for df in scenarios: | |
| scores = reference_residual_scores(df, ref) | |
| report = verifier_metrics(scores, df.is_error, threshold=5.0) | |
| # Keep exact risk/coverage breakpoints in a separate tabular artifact. | |
| curve = report.pop("risk_coverage") | |
| table( | |
| root, f"evaluation/risk_coverage/{df.scenario_id.iloc[0]}.parquet", pd.DataFrame(curve) | |
| ) | |
| scenario = df.scenario_id.iloc[0] | |
| report["association"] = association_metrics(clean, df) | |
| results[scenario] = report | |
| verification.append( | |
| pd.DataFrame( | |
| { | |
| "recording_id": rid, | |
| "scenario_id": scenario, | |
| "frame_index": df.frame_index, | |
| "detection_id": df.detection_id, | |
| "reference_track_id": df.reference_track_id, | |
| "proposed_track_id": df.track_id, | |
| "is_error": df.is_error, | |
| "score_um": scores, | |
| "verifier": "fixed_reference_distance", | |
| "threshold_um": 5.0, | |
| "partition": "development", | |
| } | |
| ) | |
| ) | |
| components[rid]["perturbations"] = table( | |
| root, f"data/perturbations/{rid}.parquet", pd.concat(scenarios, ignore_index=True) | |
| ) | |
| table(root, f"data/verification/{rid}.parquet", pd.concat(verification, ignore_index=True)) | |
| for method in ["nearest_neighbor", "hungarian"]: | |
| prediction = oracle_association_baseline(clean.drop(columns="track_id"), method=method) | |
| table(root, f"evaluation/baseline_predictions/{method}.parquet", prediction) | |
| results[method] = association_metrics(clean, prediction) | |
| dump(root / "evaluation/pilot_results.json", results) | |
| for name, rid, source in [ | |
| ("ZM9624_Ex(myo-20_mCherry)", "zephir-zm9624", "zephir"), | |
| ("nguyen2017_AL_w1", "nerve-al-w1-via-zephir", "nerve"), | |
| ]: | |
| folder = raw / "zephir/zephir" / name | |
| meta = json.loads((folder / "metadata.json").read_text()) | |
| new_record( | |
| rid, | |
| source, | |
| "10.5281/zenodo.10818810", | |
| f"zephir/{name}/annotations.h5", | |
| acquisition_setup="freely_moving", | |
| shape_tczyx=json.dumps([meta[f"shape_{a}"] for a in "tczyx"]), | |
| source_overlap_group="nerve-al-w1" if source == "nerve" else rid, | |
| timestamps_status="source_times_hosted" if source == "zephir" else "unknown", | |
| ) | |
| register_tracks( | |
| rid, | |
| zephir_tracks(folder / "annotations.h5", meta, rid), | |
| [meta[f"shape_{a}"] for a in "xyz"], | |
| ) | |
| dest = root / "assets" / rid | |
| dest.mkdir(parents=True, exist_ok=True) | |
| for filename in ["annotations.h5", "worldlines.h5", "metadata.json"]: | |
| shutil.copy2(folder / filename, dest / filename) | |
| if (audit / "zephir-image-times.json").exists(): | |
| shutil.copy2( | |
| audit / "zephir-image-times.json", root / "assets/zephir-zm9624/timestamps_s.json" | |
| ) | |
| rid = "targettrack-epfl10" | |
| new_record( | |
| rid, | |
| "targettrack", | |
| "10.5281/zenodo.10008744", | |
| "Targettrack/epfl10_CZANet_Final.h5", | |
| shape_tczyx=json.dumps([761, 1, 32, 128, 192]), | |
| acquisition_setup="unknown", | |
| tracking_gt_level="mask_provenance_unresolved", | |
| ) | |
| points, transforms = [], [] | |
| with h5py.File(raw / "Targettrack/epfl10_CZANet_Final.h5") as h: | |
| for t in range(int(h.attrs["T"])): | |
| g = h[str(t)] | |
| transforms.append( | |
| { | |
| "recording_id": rid, | |
| "frame_index": t, | |
| "original_frame_index": int(g["original_fr"][()]), | |
| "source_transform": g["transfo_matrix"][()].reshape(-1).tolist(), | |
| "direction": "unknown", | |
| "units": "unknown", | |
| } | |
| ) | |
| if "mask" not in g: | |
| continue | |
| mask = g["mask"][()] | |
| for identity in np.unique(mask): | |
| if identity == 0: | |
| continue | |
| xyz = np.argwhere(mask == identity).mean(axis=0) | |
| points.append( | |
| { | |
| "recording_id": rid, | |
| "frame_index": t, | |
| "track_id": str(identity), | |
| "detection_id": f"{t}:{identity}", | |
| **dict(zip(XYZ, xyz.tolist(), strict=True)), | |
| "x_um": np.nan, | |
| "y_um": np.nan, | |
| "z_um": np.nan, | |
| "annotation_type": "unknown", | |
| "annotation_confidence": np.nan, | |
| "label_set": "source_mask", | |
| "source_provenance": "centroid_of_native_mask; manual_or_propagated_unresolved", | |
| "coordinate_system": "source_processed_CXYZ", | |
| "validity": True, | |
| } | |
| ) | |
| register_tracks(rid, pd.DataFrame(points), [192, 128, 32]) | |
| table(root, "metadata/targettrack_transforms.parquet", pd.DataFrame(transforms)) | |
| # Same-animal NeuroPAL cloud from a directly inspected CC-BY NWB. | |
| asset = json.loads((audit / "dandi-000715-assets.json").read_text())["assets"][0] | |
| rid = "dandi-000715-" + asset["path"].split("/")[0] | |
| with h5py.File(raw / "neuropal-reference.nwb") as h: | |
| group = h["processing/NeuroPAL/NeuroPALSegmentation/NeuroPALNeurons"] | |
| voxels, ids = group["voxel_mask"][()], group["id"][()] | |
| spacing = h["general/optophysiology/NeuroPALImVol/grid_spacing"] | |
| if spacing.attrs["unit"] != "micrometers": | |
| raise ValueError("Unsupported physical calibration") | |
| cloud = pd.DataFrame( | |
| { | |
| "recording_id": rid, | |
| "track_id": ids.astype(str), | |
| **{f"{a}_voxel": voxels[a].astype(float) for a in "xyz"}, | |
| **{f"{a}_um": voxels[a] * spacing[i] for i, a in enumerate("xyz")}, | |
| "reference_origin": "same_animal_structural_volume", | |
| "annotation_type": "source_annotation_uncertainty_unknown", | |
| "coordinate_system": "source_microscope", | |
| "uncertainty_um": np.nan, | |
| } | |
| ) | |
| components.setdefault(rid, {})["anatomy"] = table( | |
| root, f"data/anatomy/{rid}.parquet", cloud | |
| ) | |
| chars = group["ID_labels"][()] | |
| ends = group["ID_labels_index"][()] | |
| start, names = 0, [] | |
| for end in ends: | |
| names.append(b"".join(chars[start:end]).decode()) | |
| start = end | |
| table( | |
| root, | |
| "metadata/optional_neuronal_names.parquet", | |
| pd.DataFrame( | |
| { | |
| "recording_id": rid, | |
| "source_neuron_id": ids.astype(str), | |
| "biological_name": names, | |
| "used_in_primary_evaluation": False, | |
| } | |
| ), | |
| ) | |
| recording(rid).update( | |
| qc_status="reference_cloud_validated", voxel_size_um=json.dumps(spacing[()].tolist()) | |
| ) | |
| # Preserve the original small structural NWB; explicit component download only. | |
| (root / "assets" / rid).mkdir(parents=True, exist_ok=True) | |
| shutil.copy2(raw / "neuropal-reference.nwb", root / "assets" / rid / "reference.nwb") | |
| if (raw / "wormid-ey-pilot.parquet").exists(): | |
| meta = json.loads((audit / "wormid-ey-pilot.json").read_text()) | |
| rid = "dandi-000541-" + meta["asset"]["path"].split("/")[0] | |
| df = pd.read_parquet(raw / "wormid-ey-pilot.parquet") | |
| for i, a in enumerate("xyz"): | |
| df[f"{a}_um"] = df[f"{a}_voxel"] * meta["spacing_xyz"][i] | |
| df["recording_id"], df["annotation_type"], df["label_set"] = ( | |
| rid, | |
| "unknown", | |
| "source_segmentation", | |
| ) | |
| df["annotation_confidence"] = np.nan | |
| df["source_provenance"] = "native_NWB_plane_segmentation_ID; temporal_identity_QC_pending" | |
| df["coordinate_system"], df["validity"] = "source_microscope", True | |
| register_tracks(rid, df, list(reversed(meta["shape_tczyx"][2:]))) | |
| recording(rid).update( | |
| shape_tczyx=json.dumps(meta["shape_tczyx"]), | |
| voxel_size_um=json.dumps(meta["spacing_xyz"]), | |
| timestamps_status="starting_time_and_rate_4Hz", | |
| fov_region="unknown", | |
| ) | |
| dump(root / "metadata/wormid_ey_image_annotation_discrepancy.json", meta) | |
| if (raw / "sf-behavior.parquet").exists(): | |
| meta = json.loads((audit / "sf-behavior.json").read_text()) | |
| rid = "dandi-000776-" + meta["asset"]["path"].split("/")[0] | |
| df = pd.read_parquet(raw / "sf-behavior.parquet") | |
| df["recording_id"], df["component_type"], df["status"] = rid, "behavior_summary", "measured" | |
| components.setdefault(rid, {})["posture"] = table(root, f"data/posture/{rid}.parquet", df) | |
| recording(rid)["posture_gt_level"] = "behavioral_summaries_only_no_centerline" | |
| dump(root / "metadata/sf_behavior_provenance.json", meta) | |
| for stem, rid, frames in [ | |
| ("ascent-opterra", "ascent-opterra", list(range(4))), | |
| ("zephir-zm9624", "zephir-zm9624", list(range(4))), | |
| ("targettrack-epfl10", "targettrack-epfl10", list(range(32))), | |
| ("wormid-ey-20190924-01", "dandi-000541-sub-20190924-01", list(range(4))), | |
| ]: | |
| src = workspace / "volumes" / (stem + ".h5") | |
| if src.exists(): | |
| dest = root / "assets" / rid / "pilot.h5" | |
| dest.parent.mkdir(parents=True, exist_ok=True) | |
| shutil.copy2(src, dest) | |
| components.setdefault(rid, {})["volume"] = { | |
| "path": str(dest.relative_to(root)), | |
| "frames": frames, | |
| "axis_order": "CZYX", | |
| "transformation": "axis_permutation_only", | |
| } | |
| recording(rid)["hosted_volume"] = True | |
| for source, name, priority, url, status in [ | |
| ( | |
| "nerve", | |
| "NeRVE original release", | |
| "P0", | |
| "https://doi.org/10.21227/H2901H", | |
| "one_annotation_recording_via_ZephIR; original_inventory_pending", | |
| ), | |
| ( | |
| "cender", | |
| "CeNDeR C1-C3", | |
| "P0", | |
| "https://osf.io/v2b5n/", | |
| "blocked_data_license_unstated; OSF_storage_empty; linked_Google_Drive_API_404", | |
| ), | |
| ( | |
| "brainalignnet", | |
| "BrainAlignNet / ANTSUN 2.0", | |
| "P1", | |
| "https://doi.org/10.7910/DVN/8UE0H9", | |
| "Dataverse_API_unavailable; license_and_overlap_pending", | |
| ), | |
| ( | |
| "skuhersky-atlas", | |
| "Skuhersky 3D anatomical atlas", | |
| "P2", | |
| "https://github.com/bluevex/elegans-atlas", | |
| "data_license_unresolved; external_reference_only", | |
| ), | |
| ( | |
| "neuropal-canonical", | |
| "NeuroPAL canonical positions", | |
| "P2", | |
| "https://github.com/openworm/NeuroPAL", | |
| "shared_Skuhersky_CSV; data_license_unresolved", | |
| ), | |
| ( | |
| "stat-atlas", | |
| "Statistical anatomical atlas", | |
| "P2", | |
| "https://github.com/amin-nejat/stat-atlas", | |
| "data_license_unresolved; external_reference_only", | |
| ), | |
| ( | |
| "openworm-movement", | |
| "OpenWorm Movement Database", | |
| "P2", | |
| "https://movement.openworm.org/", | |
| "DNS_resolution_failed; license_and_assets_unresolved", | |
| ), | |
| ( | |
| "eigenworms", | |
| "Stephens et al. 2008", | |
| "P2", | |
| "https://doi.org/10.1371/journal.pcbi.1000028", | |
| "paper_audited; reusable_basis_asset_not_ingested", | |
| ), | |
| ]: | |
| sources.append( | |
| { | |
| "source_id": source, | |
| "name": name, | |
| "priority": priority, | |
| "url": url, | |
| "version": None, | |
| "license": None, | |
| "license_status": "verify", | |
| "assembly_status": status, | |
| "asset_count": None, | |
| "bytes": None, | |
| } | |
| ) | |
| # All pilots are development assets. No small single-worm split is presented as generalization. | |
| active = sorted(components) | |
| splits = { | |
| p: {"train": [], "validation": [], "test": [], "development": active, "quarantine": []} | |
| for p in ["tracking_gt", "anatomical_verification", "anatomical_consistency"] | |
| } | |
| splits["tracking_gt"]["development"] = ["ascent-opterra"] | |
| splits["anatomical_verification"]["development"] = ["ascent-opterra"] | |
| table(root, "data/recordings/recordings.parquet", pd.DataFrame(recordings)) | |
| dump(root / "metadata/sources.json", sources) | |
| dump(root / "metadata/upstream_assets.json", upstream) | |
| dump(root / "metadata/overlap_registry.json", overlaps) | |
| dump( | |
| root / "metadata/client_manifest.json", | |
| { | |
| "schema_version": VERSION, | |
| "recordings": "data/recordings/recordings.parquet", | |
| "components": components, | |
| "splits": splits, | |
| }, | |
| ) | |
| dump( | |
| root / "splits/assignments.json", | |
| { | |
| "seed": SEED, | |
| "status": "development_only_no_frozen_test", | |
| "protocols": splits, | |
| "original_wormid_commit": WORMND_COMMIT, | |
| }, | |
| ) | |
| table(root, "splits/original_wormid_folds.parquet", original) | |
| dump( | |
| root / "evaluation/validation.json", | |
| {"status": "passed", "scope": "published_table_invariants", "tables": qc}, | |
| ) | |
| dump( | |
| root / "metadata/assembly_counts.json", | |
| { | |
| "version": VERSION, | |
| "assembled_at": now, | |
| "inventory_recordings": len(recordings), | |
| "wormid_inventory_assets": sum( | |
| r["source_dataset"] in {f"dandi-{i}" for i in list(DANDI_COHORTS)[:7]} | |
| for r in recordings | |
| ), | |
| "ingested": counts, | |
| "source_inventory_entries": len(sources), | |
| "pilot_imaging_frames": sum( | |
| len(c.get("volume", {}).get("frames", [])) for c in components.values() | |
| ), | |
| "anatomical_clouds": sum("anatomy" in c for c in components.values()), | |
| "measured_centerlines": 0, | |
| "independent_behavior_summary_recordings": sum( | |
| "posture" in c for c in components.values() | |
| ), | |
| "release_gates": { | |
| "A": "partial: full non-DANDI inventories pending", | |
| "B": "partial: independent moving-worm GT and centerline pending", | |
| "C": "not_passed: all P0 ingestion and held-out evaluation pending", | |
| }, | |
| }, | |
| ) | |
| harmonize_tables(root) | |
| print( | |
| json.dumps( | |
| {"root": str(root), "inventory_recordings": len(recordings), "ingested": counts}, | |
| indent=2, | |
| ) | |
| ) | |
| return root | |
| if __name__ == "__main__": | |
| build(*sys.argv[1:3]) | |