File size: 11,191 Bytes
22df3dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
247
248
249
250
251
252
253
254
255
256
257
258
#!/usr/bin/env python3
"""Identity proof for the planner's opt-in parallel profiling (MedVision_PLANNER_WORKERS).

The annotation-identity rule makes this test the licence for the parallelization change:
a plan generated in parallel must be BYTE-IDENTICAL (after gzip decompression -- the gzip
header embeds an mtime) to one generated by the historical serial code, or the change is
minting different annotations under the same version number.

Three runs of each planner (detection, biometry-fromSeg) over the same tiny synthetic
dataset, compared pairwise on every artifact:

    old-serial    -- benchmark_planner.py as of git HEAD, no env var
    new-serial    -- working-tree code, no env var (must equal old-serial: proves the
                     refactor moved the loop bodies without changing them, and that the
                     once-per-task landmark extraction leaves the same final disk state)
    new-parallel  -- working-tree code, MedVision_PLANNER_WORKERS=3 (must equal both:
                     proves worker dispatch, result ordering, and facade attributes)

Compared per run directory: the decompressed plan JSON, every landmark .json.gz
(decompressed), every figure .png (raw bytes -- matplotlib embeds no timestamp), and the
exact set of files produced.

The DEFAULT assertion is `new-serial == new-parallel` on the CURRENT tree. That invariant is
permanent: however the planners evolve, running them in a pool must never change what they
produce. It is also self-contained -- no git ref, nothing to go stale.

`--baseline <ref>` additionally reverts benchmark_planner.py to `<ref>` and compares. That was
the one-time migration proof for the parallel change, and it is now EXPECTED TO FAIL for
biometry against any pre-2026-08-12 ref: removing the buffer-zone requirement from
`__fit_ellipses` deliberately recovers landmarks on oblique lesions, so the biometry artifacts
legitimately differ (strictly more of them). Detection is unaffected and should still match.

Run:  python scripts/test_planner_parallel_identity.py
      python scripts/test_planner_parallel_identity.py --baseline 8bb3be3
"""
import gzip
import json
import os
import shutil
import subprocess
import sys
import tempfile

import numpy as np

_HERE = os.path.dirname(os.path.abspath(__file__))
REPO = os.path.dirname(_HERE)
SRC = os.path.join(REPO, "src")
PLANNER_REL = "src/medvision_ds/utils/benchmark_planner.py"
# The v1.3.0 MSWAL release -- the last commit whose benchmark_planner.py is the serial original.
BASELINE_REF = "fbc5649"

failures = 0
total = 0


def check(cond, label, detail=""):
    global failures, total
    total += 1
    if not cond:
        failures += 1
    print(f"[{'PASS' if cond else 'FAIL'}] {label}" + (f"  {detail}" if detail else ""))


# ---------------------------------------------------------------- synthetic dataset
def build_synth_dataset(root):
    """6 cases, 24x20x16, labels {1,2} as ellipsoids big enough for the ellipse fit."""
    import nibabel as nib

    rng = np.random.default_rng(7)
    os.makedirs(os.path.join(root, "Images"))
    os.makedirs(os.path.join(root, "Masks"))
    zz, yy, xx = np.meshgrid(np.arange(16), np.arange(20), np.arange(24), indexing="ij")
    for n in range(6):
        img = rng.integers(-500, 1500, (24, 20, 16)).astype(np.int16)
        mask = np.zeros((24, 20, 16), dtype=np.uint16)
        # Label 1: large ellipsoid; label 2: smaller one, shifted per case.
        c1 = (12 + n % 3, 10, 8)
        e1 = ((xx.T - c1[0]) / 6.0) ** 2 + ((yy.T - c1[1]) / 5.0) ** 2 + (
            (zz.T - c1[2]) / 4.0) ** 2 <= 1.0
        c2 = (6 + n % 2, 6, 6)
        e2 = ((xx.T - c2[0]) / 4.0) ** 2 + ((yy.T - c2[1]) / 3.5) ** 2 + (
            (zz.T - c2[2]) / 3.0) ** 2 <= 1.0
        mask[e1] = 1
        mask[e2] = 2
        aff = np.diag([0.8, 0.7, 2.0, 1.0])
        im = nib.Nifti1Image(img, aff)
        im.set_data_dtype(np.int16)
        nib.save(im, os.path.join(root, "Images", f"case{n:02d}.nii.gz"))
        mk = nib.Nifti1Image(mask, aff)
        mk.set_data_dtype(np.uint16)
        nib.save(mk, os.path.join(root, "Masks", f"case{n:02d}.nii.gz"))


# ---------------------------------------------------------------- child process
CHILD = r"""
import os, sys
task, data_root, version = sys.argv[1], sys.argv[2], sys.argv[3]
os.chdir(data_root)
from medvision_ds.utils.benchmark_planner import (
    MedVision_BenchmarkPlannerDetection, MedVision_BenchmarkPlannerBiometry_fromSeg)

labels_map = {"1": "blob one", "2": "blob two"}
landmarks_map = {"P1": "a", "P2": "b", "P3": "c", "P4": "d"}
lines_map = {
    "L-1-2": {"name": "major", "element_keys": ["P1", "P2"], "element_map_name": "landmarks_map"},
    "L-3-4": {"name": "minor", "element_keys": ["P3", "P4"], "element_map_name": "landmarks_map"},
}
biometrics_map = [
    {"metric_type": "distance", "metric_map_name": "lines_map", "metric_key": "L-1-2"},
    {"metric_type": "distance", "metric_map_name": "lines_map", "metric_key": "L-3-4"},
]

def task_dict(label):
    return {
        "image_modality": "CT",
        "image_folder": "Images", "mask_folder": "Masks",
        "image_prefix": "", "image_suffix": ".nii.gz",
        "mask_prefix": "", "mask_suffix": ".nii.gz",
        "landmark_folder": f"Landmarks-Label{label}",
        "landmark_figure_folder": f"Landmarks-Label{label}-fig",
        "landmark_prefix": "", "landmark_suffix": ".json.gz",
        "labels_map": labels_map, "landmarks_map": landmarks_map,
        "lines_map": lines_map, "angles_map": {}, "biometrics_map": biometrics_map,
        "target_label": label, "cluster_size_threshold": 20,
    }

if task == "detection":
    plan = {"dataset_info": {"dataset": "SynthDS"},
            "tasks": [{"image_folder": "Images", "mask_folder": "Masks",
                       "image_prefix": "", "image_suffix": ".nii.gz",
                       "mask_prefix": "", "mask_suffix": ".nii.gz",
                       "labels_map": labels_map}]}
    planner = MedVision_BenchmarkPlannerDetection(
        dataset_dir=data_root, bm_plan=plan, dataset_name="SynthDS",
        seed=1024, split_ratio=0.7, force_uint16_mask=False, reorient2RAS=False,
        num_proc=1, version=version)
else:
    plan = {"dataset_info": {"dataset": "SynthDS"},
            "tasks": [task_dict(1), task_dict(2)]}
    planner = MedVision_BenchmarkPlannerBiometry_fromSeg(
        dataset_dir=data_root, bm_plan=plan, dataset_name="SynthDS",
        seed=1024, split_ratio=0.7, shrunk_bbox_scale=0.9, enlarged_bbox_scale=1.1,
        force_uint16_mask=False, reorient2RAS=False, visualization=True,
        num_proc=1, version=version)
planner.process()
"""


def run_planner(src_path, task, data_root, workers):
    env = dict(os.environ)
    env["PYTHONPATH"] = src_path
    env.pop("MedVision_PLANNER_WORKERS", None)
    if workers > 1:
        env["MedVision_PLANNER_WORKERS"] = str(workers)
    r = subprocess.run(
        [sys.executable, "-c", CHILD, task, data_root, "9.9.9"],
        env=env, capture_output=True, text=True,
    )
    if r.returncode != 0:
        print(r.stdout[-1500:])
        print(r.stderr[-3000:])
        raise RuntimeError(f"{task} run failed in {data_root}")


# ---------------------------------------------------------------- comparison
def artifact_map(root):
    """{relative path: content-bytes} for every produced artifact, gzip-normalized."""
    out = {}
    for dirpath, _dirs, files in os.walk(root):
        for f in files:
            p = os.path.join(dirpath, f)
            rel = os.path.relpath(p, root)
            if rel.startswith(("Images", "Masks")):
                continue  # inputs, identical by construction
            if f.endswith(".json.gz") or f.endswith(".gz"):
                with gzip.open(p, "rb") as fh:
                    out[rel] = fh.read()
            else:
                out[rel] = open(p, "rb").read()
    return out


def compare(tag, a_root, b_root):
    a, b = artifact_map(a_root), artifact_map(b_root)
    check(set(a) == set(b), f"{tag}: identical artifact sets",
          f"only-left={sorted(set(a) - set(b))[:3]} only-right={sorted(set(b) - set(a))[:3]}")
    diff = [k for k in sorted(set(a) & set(b)) if a[k] != b[k]]
    check(not diff, f"{tag}: every artifact byte-identical (decompressed)",
          f"{len(diff)} differ, e.g. {diff[:3]}")


def main():
    work = tempfile.mkdtemp(prefix="planner_par_identity_")
    print(f"workdir: {work}")

    baseline_ref = None
    if "--baseline" in sys.argv:
        baseline_ref = sys.argv[sys.argv.index("--baseline") + 1]

    runs = {"new-serial": (SRC, 1), "new-parallel": (SRC, 3)}
    if baseline_ref:
        # Old tree = working src with benchmark_planner.py reverted to the baseline ref.
        old_src = os.path.join(work, "old_src")
        shutil.copytree(SRC, old_src, ignore=shutil.ignore_patterns("__pycache__"))
        old_planner = subprocess.run(
            ["git", "-C", REPO, "show", f"{baseline_ref}:{PLANNER_REL}"],
            capture_output=True, text=True, check=True,
        ).stdout
        # Refuse a baseline that already has the change: the runs would then be
        # parallel-vs-parallel and every check would pass while proving nothing.
        if "_map_cases_ordered" in old_planner:
            sys.exit(
                f"baseline ref {baseline_ref!r} ALREADY contains the parallel change, so this "
                "comparison would be vacuous. Pass a ref whose benchmark_planner.py predates "
                "it, e.g. the release commit before the change landed."
            )
        short = subprocess.run(
            ["git", "-C", REPO, "rev-parse", "--short", baseline_ref],
            capture_output=True, text=True,
        ).stdout.strip()
        print(f"baseline: {baseline_ref} ({short})  "
              "[biometry is EXPECTED to differ -- see module docstring]")
        with open(os.path.join(old_src, "medvision_ds/utils/benchmark_planner.py"), "w") as fh:
            fh.write(old_planner)
        runs["old-serial"] = (old_src, 1)

    seed_ds = os.path.join(work, "seed_ds")
    build_synth_dataset(seed_ds)

    for task in ("detection", "biometry"):
        print(f"\n-- {task} --")
        roots = {}
        for name, (src_path, workers) in runs.items():
            root = os.path.join(work, f"{task}_{name}")
            shutil.copytree(seed_ds, root)
            run_planner(src_path, task, root, workers)
            roots[name] = root
        n_plans = sum(1 for f in os.listdir(roots["new-serial"])
                      if f.startswith("benchmark_plan_"))
        check(n_plans == 1, f"{task}: produced a plan")
        # THE invariant: a process pool must not change what the planner produces.
        compare(f"{task}: new-parallel vs new-serial", roots["new-serial"], roots["new-parallel"])
        if baseline_ref:
            compare(f"{task}: new-serial vs old-serial",
                    roots["old-serial"], roots["new-serial"])

    print()
    if failures:
        print(f"{failures} of {total} checks FAILED.  (workdir kept: {work})")
        sys.exit(1)
    shutil.rmtree(work, ignore_errors=True)
    print(f"All {total} checks passed.")


if __name__ == "__main__":
    main()