MedVision / scripts /align_tl_split_to_v1.0.0.py
YongchengYAO's picture
[release] v1.1.1: correct TL ellipse fit (transposed in-plane spacing + major/minor) for v1.1.1
79918b7
Raw
History Blame Contribute Delete
7.36 kB
"""Re-align the released v1.1.0 and v1.1.1 TL biometry plans to v1.0.0's exact
image-level train/test split, WITHOUT re-running the planner.
Why: the split is an image-level partition stored only in each plan's
train_cases[]/test_cases[] arrays. The sorted()-glob fix (dbb2028) landed after
v1.0.0, so v1.1.0 reshuffled ~41% of cases vs v1.0.0 and v1.1.1 inherited that.
This makes all three releases share v1.0.0's split by relabeling (moving case
objects between train/test to match v1.0.0's membership AND order). Annotation
VALUES (slice_profiles, landmark_file, figures) are byte-identical — only the
partition changes. v1.0.0 is the read-only anchor; case sets must already match
(BraTS-MET-00232-000 was removed beforehand).
Derived sidecars carry an informational per-entry "split" label; this refreshes
only those whose source plan is v1.1.0/v1.1.1 (consumers key on
task_ID/image_file/slice_dim/slice_idx and ignore "split", but keep it honest).
removed_samples_v1.0.0_to_* and multi_cluster_samples_v1.0.0_to_v1.1.0 are
sourced from the unchanged v1.0.0 baseline and are left untouched.
Backups of every touched file go to {dataset}/dev/bak/ before any write.
"""
import argparse
import gzip
import json
import shutil
from pathlib import Path
DATASETS = ["KiPA22", "HNTSMRG24", "autoPET-III", "KiTS23", "MSD", "BraTS24"]
V0 = "benchmark_plan_biometry_v1.0.0.json.gz"
V10 = "benchmark_plan_biometry_v1.1.0.json.gz"
V11 = "benchmark_plan_biometry_v1.1.1.json.gz"
# sidecar filename -> which re-aligned plan version supplies its "split" label
# ("v1.1.0"/"v1.1.1"); files sourced from the unchanged v1.0.0 baseline are absent.
SIDECAR_SOURCE = {
"multi_cluster_samples_v1.1.0.json": "v1.1.0",
"multi_cluster_samples_v1.1.1.json": "v1.1.1",
"added_samples_v1.0.0_to_v1.1.0.json": "v1.1.0",
"added_samples_v1.0.0_to_v1.1.1.json": "v1.1.1",
"added_samples_v1.1.0_to_v1.1.1.json": "v1.1.1",
"removed_samples_v1.1.0_to_v1.1.1.json": "v1.1.0",
}
def load_gz(p):
with gzip.open(p, "rt") as f:
return json.load(f)
def dump_gz(obj, p):
with gzip.open(p, "wt") as f:
json.dump(obj, f)
def v0_partition(plan):
"""task_ID -> {'train': [case_ID in order], 'test': [case_ID in order]}."""
out = {}
for t in plan["tasks"]:
out[t["task_ID"]] = {
"train": [c["case_ID"] for c in t.get("train_cases", [])],
"test": [c["case_ID"] for c in t.get("test_cases", [])],
}
return out
def realign_plan(plan, target):
"""Repartition each task's cases to match `target` (membership + order).
Mutates `plan` in place; returns (#moved, side_map) where side_map maps
(task_ID, image_file) and (task_ID, basename) -> 'train'|'test'."""
moved = 0
side_map = {}
for t in plan["tasks"]:
tid = t["task_ID"]
by_id = {c["case_ID"]: c for c in t.get("train_cases", []) + t.get("test_cases", [])}
tgt = target[tid]
have = set(by_id)
want = set(tgt["train"]) | set(tgt["test"])
if have != want:
raise SystemExit(
f" ABORT task {tid}: case sets differ from v1.0.0 "
f"(only-here={sorted(have - want)[:5]}, only-v0={sorted(want - have)[:5]})"
)
old_train = [c["case_ID"] for c in t.get("train_cases", [])]
new_train = [by_id[cid] for cid in tgt["train"]]
new_test = [by_id[cid] for cid in tgt["test"]]
moved += sum(1 for c in new_train if c["case_ID"] not in set(old_train))
t["train_cases"] = new_train
t["test_cases"] = new_test
t["train_cases_number"] = len(new_train)
t["test_cases_number"] = len(new_test)
for side, cases in (("train", new_train), ("test", new_test)):
for c in cases:
imf = c["image_file"]
side_map[(tid, imf)] = side
side_map[(tid, Path(imf).name)] = side
return moved, side_map
def patch_sidecar(path, side_map):
"""Refresh the 'split' label of every entry from side_map. Returns
(changed, total, misses)."""
with open(path) as f:
entries = json.load(f)
changed = misses = 0
for e in entries:
key = (e["task_ID"], e["image_file"])
side = side_map.get(key) or side_map.get((e["task_ID"], Path(e["image_file"]).name))
if side is None:
misses += 1
continue
if e.get("split") != side:
e["split"] = side
changed += 1
if misses == 0:
with open(path, "w") as f:
json.dump(entries, f, indent=2)
return changed, len(entries), misses
def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--data_dir", required=True,
help="Root containing per-dataset folders with the plans.")
ap.add_argument("--dry_run", action="store_true", help="Report only; write nothing.")
args = ap.parse_args()
root = Path(args.data_dir)
for ds in DATASETS:
d = root / ds
print("=" * 88)
print(ds)
print("=" * 88)
v0 = load_gz(d / V0)
target = v0_partition(v0)
side_maps = {}
# backup + realign each version's plan
for ver, fn in (("v1.1.0", V10), ("v1.1.1", V11)):
plan = load_gz(d / fn)
moved, side_map = realign_plan(plan, target)
side_maps[ver] = side_map
if not args.dry_run:
bak = d / "dev" / "bak"
bak.mkdir(parents=True, exist_ok=True)
shutil.copy2(d / fn, bak / fn)
dump_gz(plan, d / fn)
print(f" {fn}: relabeled, {moved} case(s) moved to match v1.0.0")
# patch sidecars
for fn, ver in SIDECAR_SOURCE.items():
p = d / fn
if not p.exists():
continue
if not args.dry_run:
bak = d / "dev" / "bak"
bak.mkdir(parents=True, exist_ok=True)
shutil.copy2(p, bak / fn)
changed, total, misses = patch_sidecar(p, side_maps[ver])
else:
with open(p) as f:
entries = json.load(f)
sm = side_maps[ver]
misses = sum(1 for e in entries
if (e["task_ID"], e["image_file"]) not in sm
and (e["task_ID"], Path(e["image_file"]).name) not in sm)
changed, total = -1, len(entries)
flag = f" !! {misses} unmatched -> NOT written" if misses else ""
print(f" {fn}: split refreshed on {changed}/{total} entries (src {ver}){flag}")
# ---- verification: all three plans share one split (membership + order) ----
print("=" * 88)
print("VERIFY: v1.0.0 == v1.1.0 == v1.1.1 (membership + order) per task")
print("=" * 88)
allok = True
for ds in DATASETS:
d = root / ds
p0 = v0_partition(load_gz(d / V0))
p1 = v0_partition(load_gz(d / V10))
p2 = v0_partition(load_gz(d / V11))
ok = (p0 == p1 == p2)
allok &= ok
detail = "" if ok else " <-- MISMATCH"
print(f" {ds:<13} identical={ok}{detail}")
print(f"\nALL DATASETS aligned: {allok}")
if __name__ == "__main__":
main()