josand commited on
Commit
05fa11f
·
verified ·
1 Parent(s): a798b30

Publish reproducible MuscleMap qualification tools

Browse files
qualification/make_reference_fixtures.py ADDED
@@ -0,0 +1,596 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Record independent MONAI 1.3.2 reference outputs for the MuscleMap port.
2
+
3
+ Run in the pinned oracle environment (Python 3.11, torch 2.4.1, MONAI 1.3.2):
4
+
5
+ PYTHONPATH=src environment/oracle/.venv/bin/python \
6
+ scripts/make_reference_fixtures.py --assets weights --output build/msk-porting/fixtures
7
+
8
+ The script uses only synthetic arrays and the publisher checkpoint. It records
9
+ the exact upstream preprocessing stages, 64x64 network logits, the full small
10
+ pipeline labels and inverted logits, and a larger sliding-window case. The
11
+ resulting .npz files are development artifacts and stay ignored.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import argparse
17
+ import json
18
+ import time
19
+ from pathlib import Path
20
+ from tempfile import TemporaryDirectory
21
+
22
+ import nibabel as nib
23
+ import numpy as np
24
+ import scipy
25
+ import torch
26
+ from monai.inferers import SliceInferer
27
+ from monai.networks.layers import Norm
28
+ from monai.networks.nets import UNet
29
+ from monai.transforms import (
30
+ AsDiscreted,
31
+ Compose,
32
+ CropForegroundd,
33
+ EnsureChannelFirstd,
34
+ EnsureTyped,
35
+ Invertd,
36
+ LoadImaged,
37
+ MapTransform,
38
+ NormalizeIntensityd,
39
+ Orientationd,
40
+ Spacingd,
41
+ SpatialPadd,
42
+ )
43
+ from scipy import ndimage as ndi
44
+
45
+ from musclemap_mlx.assets import verify_assets
46
+ from musclemap_mlx.config import CONFIG_NAME, load_model_config
47
+
48
+ SCHEMA_VERSION = 1
49
+ SMALL_SHAPE = (100, 90, 4)
50
+ WINDOW_SHAPE = (320, 220, 2)
51
+ OBLIQUE_SHAPE = (44, 40, 3)
52
+ LARGE_SHAPE = (280, 260, 20)
53
+ AFFINE = np.array(
54
+ [
55
+ [-0.9, 0.0, 0.0, 12.0],
56
+ [0.0, -1.3, 0.0, -7.0],
57
+ [0.0, 0.0, 2.5, 30.0],
58
+ [0.0, 0.0, 0.0, 1.0],
59
+ ],
60
+ dtype=np.float64,
61
+ )
62
+
63
+
64
+ def _rotated_affine(
65
+ angle_deg: float, spacing: tuple[float, float, float], translation: tuple[float, float, float]
66
+ ) -> np.ndarray:
67
+ """An in-plane rotated, anisotropic RAS-like affine for geometry coverage."""
68
+ angle = np.deg2rad(angle_deg)
69
+ rotation = np.array(
70
+ [
71
+ [np.cos(angle), -np.sin(angle), 0.0],
72
+ [np.sin(angle), np.cos(angle), 0.0],
73
+ [0.0, 0.0, 1.0],
74
+ ],
75
+ dtype=np.float64,
76
+ )
77
+ scale = np.diag(np.asarray(spacing, dtype=np.float64))
78
+ affine = np.eye(4, dtype=np.float64)
79
+ affine[:3, :3] = rotation @ scale
80
+ affine[:3, 3] = np.asarray(translation, dtype=np.float64)
81
+ return affine
82
+
83
+
84
+ OBLIQUE_AFFINE = _rotated_affine(18.0, (0.9, 1.25, 2.5), (10.0, -6.0, 20.0))
85
+ LARGE_AFFINE = _rotated_affine(8.0, (1.0, 1.2, 2.5), (15.0, -9.0, 25.0))
86
+
87
+
88
+ class SqueezeTransform(MapTransform):
89
+ """Remove a leading singleton channel after argparse, as upstream does."""
90
+
91
+ def __init__(self, keys: tuple[str, ...]) -> None:
92
+ super().__init__(keys)
93
+
94
+ def __call__(self, data: dict[str, object]) -> dict[str, object]:
95
+ output = dict(data)
96
+ for key in self.keys:
97
+ value = output[key]
98
+ if isinstance(value, torch.Tensor) and value.dim() > 3 and value.shape[0] == 1:
99
+ output[key] = value.squeeze(0)
100
+ return output
101
+
102
+
103
+ class RemapLabels(MapTransform):
104
+ """Restore the publisher's anatomical IDs from network channel indices."""
105
+
106
+ def __init__(self, keys: tuple[str, ...], id_map: dict[int, int]) -> None:
107
+ super().__init__(keys)
108
+ self.id_map = id_map
109
+
110
+ def __call__(self, data: dict[str, object]) -> dict[str, object]:
111
+ output = dict(data)
112
+ for key in self.keys:
113
+ value = output[key]
114
+ if not isinstance(value, torch.Tensor):
115
+ continue
116
+ result = value.clone()
117
+ for source, target in self.id_map.items():
118
+ result[value == source] = target
119
+ output[key] = result
120
+ return output
121
+
122
+
123
+ def main(argv: list[str] | None = None) -> int:
124
+ parser = argparse.ArgumentParser(description=__doc__)
125
+ parser.add_argument("--assets", required=True, type=Path)
126
+ parser.add_argument("--output", required=True, type=Path)
127
+ parser.add_argument("--image", type=Path, help="Record a real NIfTI instead of synthetic cases")
128
+ parser.add_argument("--chunk-size", type=int, default=8)
129
+ args = parser.parse_args(argv)
130
+ assets = args.assets.expanduser().absolute()
131
+ output = args.output.expanduser().absolute()
132
+ output.mkdir(parents=True, exist_ok=True)
133
+ verify_assets(assets)
134
+ config_path = assets / CONFIG_NAME
135
+ load_model_config(config_path)
136
+ torch.set_num_threads(1)
137
+ torch.manual_seed(0)
138
+ state = torch.load(
139
+ assets / "contrast_agnostic_wholebody_model.pth",
140
+ map_location="cpu",
141
+ weights_only=True,
142
+ )
143
+ network = _network(config_path)
144
+ network.load_state_dict(state)
145
+ network.eval()
146
+
147
+ if args.image is not None:
148
+ _record_real(args.image, network, config_path, output, args.chunk_size)
149
+ return 0
150
+
151
+ small_image = _phantom(SMALL_SHAPE, (50, 45, 2), (13, 10, 2), seed=7)
152
+ small_path = output / "small_input.nii.gz"
153
+ _write_nifti(small_path, small_image, AFFINE)
154
+ preprocess, stages, final = _run_stages(small_path, config_path)
155
+ _save_preprocess(output / "preprocess.npz", small_image, stages, final)
156
+
157
+ inverted, raw_labels = _run_pipeline(
158
+ preprocess, final, network, config_path, filter_connected=False
159
+ )
160
+ labels = connected_chunks(raw_labels)
161
+ reader_affine = np.asarray(stages["loaded_affine"], dtype=np.float64)
162
+ np.savez_compressed(
163
+ output / "pipeline.npz",
164
+ input=small_image,
165
+ input_affine=reader_affine,
166
+ inverted_logits=np.ascontiguousarray(inverted),
167
+ labels_unfiltered=np.ascontiguousarray(raw_labels),
168
+ labels=np.ascontiguousarray(labels),
169
+ )
170
+ chunked_labels = _run_chunked_pipeline(small_path, network, config_path, chunk_size=2)
171
+ np.savez_compressed(
172
+ output / "pipeline_chunked.npz",
173
+ input=small_image,
174
+ input_affine=reader_affine,
175
+ labels=np.ascontiguousarray(chunked_labels),
176
+ )
177
+ inverse_rng = np.random.default_rng(99)
178
+ padded_logits = inverse_rng.normal(size=(4, 256, 256, 4)).astype(np.float32)
179
+ inverted_logits = _invert_logits(preprocess, final, padded_logits)
180
+ np.savez_compressed(
181
+ output / "inverse.npz",
182
+ padded_logits=padded_logits,
183
+ inverted_logits=np.ascontiguousarray(inverted_logits),
184
+ )
185
+
186
+ rng = np.random.default_rng(20261102)
187
+ network_input = rng.normal(size=(1, 1, 64, 64)).astype(np.float32)
188
+ with torch.inference_mode():
189
+ network_logits = network(torch.from_numpy(network_input)).numpy()
190
+ np.savez_compressed(
191
+ output / "network64.npz",
192
+ input=network_input,
193
+ logits=np.ascontiguousarray(network_logits),
194
+ )
195
+
196
+ window_image = _slab(WINDOW_SHAPE)
197
+ window_path = output / "window_input.nii.gz"
198
+ _write_nifti(window_path, window_image, AFFINE)
199
+ window_preprocess, window_stages, window_final = _run_stages(window_path, config_path)
200
+ _, window_labels = _run_pipeline(window_preprocess, window_final, network, config_path)
201
+ window_affine = np.asarray(window_stages["loaded_affine"], dtype=np.float64)
202
+ np.savez_compressed(
203
+ output / "windows.npz",
204
+ input=window_image,
205
+ input_affine=window_affine,
206
+ labels=np.ascontiguousarray(window_labels),
207
+ )
208
+
209
+ oblique_image = _phantom(OBLIQUE_SHAPE, (22, 20, 1), (9, 8, 1), seed=11)
210
+ oblique_path = output / "oblique_input.nii.gz"
211
+ _write_nifti(oblique_path, oblique_image, OBLIQUE_AFFINE)
212
+ oblique_preprocess, oblique_stages, oblique_final = _run_stages(oblique_path, config_path)
213
+ _save_preprocess(
214
+ output / "preprocess_oblique.npz", oblique_image, oblique_stages, oblique_final
215
+ )
216
+ oblique_pad_shape = np.asarray(oblique_stages["pad_data"]).shape[1:]
217
+ oblique_rng = np.random.default_rng(101)
218
+ oblique_padded = oblique_rng.normal(size=(4, *oblique_pad_shape)).astype(np.float32)
219
+ oblique_inverted = _invert_logits(oblique_preprocess, oblique_final, oblique_padded)
220
+ np.savez_compressed(
221
+ output / "inverse_oblique.npz",
222
+ padded_logits=oblique_padded,
223
+ inverted_logits=np.ascontiguousarray(oblique_inverted),
224
+ )
225
+
226
+ large_image = _large_slab(LARGE_SHAPE)
227
+ large_path = output / "large_oblique_input.nii.gz"
228
+ _write_nifti(large_path, large_image, LARGE_AFFINE)
229
+ large_preprocess, large_stages, large_final = _run_stages(large_path, config_path)
230
+ _save_preprocess(output / "preprocess_large.npz", large_image, large_stages, large_final)
231
+ _, raw_whole = _run_pipeline(
232
+ large_preprocess, large_final, network, config_path, filter_connected=False
233
+ )
234
+ large_whole = connected_chunks(raw_whole)
235
+ large_chunked = _run_chunked_pipeline(large_path, network, config_path, chunk_size=8)
236
+ large_chunked2 = _run_chunked_pipeline(large_path, network, config_path, chunk_size=2)
237
+ large_reader_affine = np.asarray(large_stages["loaded_affine"], dtype=np.float64)
238
+ np.savez_compressed(
239
+ output / "large_oblique.npz",
240
+ input=large_image,
241
+ input_affine=large_reader_affine,
242
+ labels_whole=np.ascontiguousarray(large_whole),
243
+ labels_chunked=np.ascontiguousarray(large_chunked),
244
+ labels_chunked2=np.ascontiguousarray(large_chunked2),
245
+ )
246
+
247
+ metadata = {
248
+ "schema_version": SCHEMA_VERSION,
249
+ "upstream": {
250
+ "repository": "https://github.com/MuscleMap/MuscleMap",
251
+ "revision": "35a2138a4a3a63be713bae5584632ffc6433b960",
252
+ "zenodo_record": "https://zenodo.org/records/21929873",
253
+ },
254
+ "versions": {
255
+ "torch": torch.__version__,
256
+ "monai": _module_version("monai"),
257
+ "numpy": np.__version__,
258
+ "nibabel": nib.__version__,
259
+ "scipy": scipy.__version__,
260
+ "torch_threads": torch.get_num_threads(),
261
+ },
262
+ "cases": {
263
+ "preprocess": {"shape": list(SMALL_SHAPE), "affine": AFFINE.tolist()},
264
+ "network64": {"shape": [1, 1, 64, 64], "seed": 20261102},
265
+ "pipeline": {"shape": list(SMALL_SHAPE), "affine": AFFINE.tolist()},
266
+ "windows": {"shape": list(WINDOW_SHAPE), "affine": AFFINE.tolist()},
267
+ "oblique": {"shape": list(OBLIQUE_SHAPE), "affine": OBLIQUE_AFFINE.tolist()},
268
+ "large": {"shape": list(LARGE_SHAPE), "affine": LARGE_AFFINE.tolist()},
269
+ },
270
+ }
271
+ (output / "metadata.json").write_text(
272
+ json.dumps(metadata, indent=2, sort_keys=True) + "\n", encoding="utf-8"
273
+ )
274
+ print(json.dumps(metadata, indent=2, sort_keys=True))
275
+ return 0
276
+
277
+
278
+ def _record_real(
279
+ path: Path, network: UNet, config: Path, output: Path, chunk_size: int
280
+ ) -> None:
281
+ """Record upstream float32 chunk logits and the assembled anatomical mask.
282
+
283
+ Chunk NIfTI construction follows upstream ``_write_temp_chunk``. Component
284
+ filtering runs once after assembly, never independently on each chunk.
285
+ """
286
+ if chunk_size < 1:
287
+ raise ValueError("chunk-size must be positive")
288
+ started = time.perf_counter()
289
+ image = nib.load(str(path))
290
+ data = np.asarray(image.dataobj, dtype=np.float32)
291
+ if data.ndim != 3:
292
+ raise ValueError("A real reference input must be three-dimensional")
293
+ full = np.zeros(data.shape, dtype=np.int16)
294
+ with TemporaryDirectory(prefix="chunks-", dir=output) as temporary:
295
+ for start in range(0, data.shape[2], chunk_size):
296
+ end = min(start + chunk_size, data.shape[2])
297
+ chunk = data[..., start:end]
298
+ chunk_path = Path(temporary) / "input.nii"
299
+ nib.save(nib.Nifti1Image(chunk, image.affine, image.header.copy()), str(chunk_path))
300
+ transforms, stages, final = _run_stages(chunk_path, config)
301
+ inverted, labels = _run_pipeline(
302
+ transforms, final, network, config, filter_connected=False
303
+ )
304
+ full[..., start:end] = labels
305
+ prepared = final["image"]
306
+ window = prepared[None, :, :256, :256, :1].squeeze(-1)
307
+ with torch.inference_mode():
308
+ network_logits = network(window).detach().cpu().numpy()
309
+ np.savez_compressed(
310
+ output / f"chunk-{start}.npz", input=np.asarray(stages["loaded_data"]),
311
+ affine=np.asarray(stages["loaded_affine"]),
312
+ prepared=np.asarray(prepared), network_input=np.asarray(window),
313
+ network_logits=network_logits, inverted_logits=inverted,
314
+ )
315
+ print(f"Recorded slices {start}:{end}", flush=True)
316
+ np.save(output / "labels.npy", connected_chunks(full))
317
+ metadata = {
318
+ "upstream_revision": "35a2138a4a3a63be713bae5584632ffc6433b960",
319
+ "checkpoint_record": "https://zenodo.org/records/21929873",
320
+ "input_name": path.name, "shape": list(data.shape),
321
+ "affine": image.affine.tolist(), "units": image.header.get_xyzt_units(),
322
+ "chunk_size": chunk_size, "overlap": 0.9, "dtype": "float32",
323
+ "torch": torch.__version__, "monai": _module_version("monai"),
324
+ "numpy": np.__version__, "nibabel": nib.__version__, "scipy": scipy.__version__,
325
+ "duration_seconds": time.perf_counter() - started,
326
+ }
327
+ (output / "metadata.json").write_text(json.dumps(metadata, indent=2) + "\n")
328
+
329
+
330
+ def _network(config_path: Path) -> UNet:
331
+ spec = load_model_config(config_path)
332
+ return UNet(
333
+ spatial_dims=spec.spatial_dims,
334
+ in_channels=spec.in_channels,
335
+ out_channels=spec.out_channels,
336
+ channels=spec.channels,
337
+ act=spec.act,
338
+ strides=spec.strides,
339
+ num_res_units=spec.num_res_units,
340
+ norm=Norm.INSTANCE,
341
+ )
342
+
343
+
344
+ def _transforms(config_path: Path) -> Compose:
345
+ spec = load_model_config(config_path)
346
+ return Compose(
347
+ [
348
+ LoadImaged(keys=["image"], image_only=False),
349
+ EnsureChannelFirstd(keys=["image"]),
350
+ Orientationd(keys=["image"], axcodes="RAS"),
351
+ Spacingd(keys=["image"], pixdim=spec.pix_dim, mode="bilinear"),
352
+ NormalizeIntensityd(keys=["image"], nonzero=True),
353
+ CropForegroundd(keys=["image"], source_key="image", margin=20),
354
+ SpatialPadd(
355
+ keys=["image"],
356
+ spatial_size=(256, 256, 1),
357
+ method="end",
358
+ mode="constant",
359
+ ),
360
+ EnsureTyped(keys=["image"]),
361
+ ]
362
+ )
363
+
364
+
365
+ def _run_stages(
366
+ path: Path, config_path: Path
367
+ ) -> tuple[Compose, dict[str, object], dict[str, object]]:
368
+ transforms = _transforms(config_path)
369
+ data: dict[str, object] = {"image": str(path)}
370
+ stages: dict[str, object] = {}
371
+ names = ["loaded", "channel", "orientation", "spacing", "normalize", "crop", "pad", "typed"]
372
+ for name, transform in zip(names, transforms.transforms, strict=True):
373
+ data = transform(data)
374
+ image = data["image"]
375
+ if isinstance(image, torch.Tensor):
376
+ stages[f"{name}_data"] = np.array(image.detach().cpu(), copy=True)
377
+ affine = getattr(image, "affine", None)
378
+ if affine is not None:
379
+ stages[f"{name}_affine"] = np.array(affine.detach().cpu(), copy=True)
380
+ if "foreground_start_coord" in data:
381
+ stages["crop_start"] = np.asarray(data["foreground_start_coord"], dtype=np.int64)
382
+ stages["crop_end"] = np.asarray(data["foreground_end_coord"], dtype=np.int64)
383
+ return transforms, stages, data
384
+
385
+
386
+ def _invert_logits(
387
+ transforms: Compose, data: dict[str, object], padded_logits: np.ndarray
388
+ ) -> np.ndarray:
389
+ image = data["image"]
390
+ if not isinstance(image, torch.Tensor):
391
+ raise TypeError("upstream transform did not produce a tensor")
392
+ invert = Invertd(
393
+ keys="pred",
394
+ transform=transforms,
395
+ orig_keys="image",
396
+ meta_keys="pred_meta_dict",
397
+ orig_meta_keys="image_meta_dict",
398
+ meta_key_postfix="meta_dict",
399
+ nearest_interp=False,
400
+ to_tensor=True,
401
+ device=torch.device("cpu"),
402
+ )
403
+ post = {
404
+ "pred": torch.from_numpy(padded_logits),
405
+ "image": image,
406
+ "image_meta_dict": data["image_meta_dict"],
407
+ "image_transforms": image.applied_operations,
408
+ }
409
+ inverted = invert(post)["pred"]
410
+ if not isinstance(inverted, torch.Tensor):
411
+ raise TypeError("Invertd did not produce a tensor")
412
+ return np.asarray(inverted.detach().cpu(), dtype=np.float32)
413
+
414
+
415
+ def _run_pipeline(
416
+ transforms: Compose,
417
+ data: dict[str, object],
418
+ network: UNet,
419
+ config_path: Path,
420
+ *,
421
+ filter_connected: bool = True,
422
+ ) -> tuple[np.ndarray, np.ndarray]:
423
+ spec = load_model_config(config_path)
424
+ labels = sorted({label.value for label in spec.labels})
425
+ id_map = {0: 0}
426
+ for new_id, original in enumerate(labels, start=1):
427
+ id_map[original] = new_id
428
+ inverse_map = {new_id: original for original, new_id in id_map.items()}
429
+ image = data["image"]
430
+ if not isinstance(image, torch.Tensor):
431
+ raise TypeError("upstream transform did not produce a tensor")
432
+ tensor = image
433
+ if tensor.ndim == 4:
434
+ tensor = tensor.unsqueeze(0)
435
+ inferer = SliceInferer(
436
+ roi_size=spec.roi_size,
437
+ sw_batch_size=spec.spatial_window_batch_size,
438
+ spatial_dim=2,
439
+ mode="gaussian",
440
+ overlap=0.9,
441
+ )
442
+ with torch.inference_mode():
443
+ prediction = inferer(tensor, network)
444
+ single = prediction.squeeze(0).squeeze(0)
445
+ invert = Invertd(
446
+ keys="pred",
447
+ transform=transforms,
448
+ orig_keys="image",
449
+ meta_keys="pred_meta_dict",
450
+ orig_meta_keys="image_meta_dict",
451
+ meta_key_postfix="meta_dict",
452
+ nearest_interp=False,
453
+ to_tensor=True,
454
+ device=torch.device("cpu"),
455
+ )
456
+ post = {"pred": single, "image": data["image"], "image_meta_dict": data["image_meta_dict"]}
457
+ inverted = invert(post)
458
+ inverted_tensor = inverted["pred"]
459
+ if not isinstance(inverted_tensor, torch.Tensor):
460
+ raise TypeError("Invertd did not produce a tensor")
461
+ inverted_logits = np.asarray(inverted_tensor.detach().cpu(), dtype=np.float32)
462
+ discrete = AsDiscreted(keys="pred", argmax=True)(inverted)
463
+ squeezed = SqueezeTransform(keys=("pred",))(discrete)
464
+ remapped = RemapLabels(keys=("pred",), id_map=inverse_map)(squeezed)
465
+ result = remapped["pred"]
466
+ if not isinstance(result, torch.Tensor):
467
+ raise TypeError("upstream postprocessing did not produce a tensor")
468
+ labels = np.asarray(result.detach().cpu(), dtype=np.int16)
469
+ return inverted_logits, connected_chunks(labels) if filter_connected else labels
470
+
471
+
472
+ def _run_chunked_pipeline(
473
+ path: Path, network: UNet, config_path: Path, *, chunk_size: int
474
+ ) -> np.ndarray:
475
+ image = nib.load(str(path))
476
+ affine = np.asarray(image.affine, dtype=np.float64)
477
+ data = np.asanyarray(image.dataobj)
478
+ header = image.header.copy()
479
+ full = np.zeros(data.shape, dtype=np.int16)
480
+ depth = int(data.shape[-1])
481
+ for start in range(0, depth, chunk_size):
482
+ end = min(start + chunk_size, depth)
483
+ chunk_path = path.parent / f"chunk_{start}_{end}.nii"
484
+ chunk = np.asarray(data[..., start:end], dtype=np.float32)
485
+ chunk_image = nib.Nifti1Image(chunk, affine, header.copy())
486
+ chunk_image.set_qform(affine, 1)
487
+ chunk_image.set_sform(affine, 1)
488
+ nib.save(chunk_image, str(chunk_path))
489
+ transforms, _stages, final = _run_stages(chunk_path, config_path)
490
+ _, labels = _run_pipeline(
491
+ transforms, final, network, config_path, filter_connected=False
492
+ )
493
+ full[..., start:end] = labels
494
+ chunk_path.unlink()
495
+ return connected_chunks(full)
496
+
497
+
498
+ def connected_chunks(seg: np.ndarray, connectivity: int = 1) -> np.ndarray:
499
+ """Keep the largest 3D connected component of each nonzero label.
500
+
501
+ Copied from ``mm_util.connected_chunks`` at the pinned upstream revision.
502
+ """
503
+ labels = np.unique(seg)
504
+ labels = labels[labels != 0]
505
+ result = np.array(seg, dtype=np.int16, copy=True)
506
+ if labels.size == 0:
507
+ return result
508
+ structure = ndi.generate_binary_structure(rank=3, connectivity=connectivity)
509
+ mask3d = np.empty(result.shape, dtype=bool)
510
+ lab3d = np.empty(result.shape, dtype=np.int32)
511
+ for label in labels:
512
+ np.equal(result, label, out=mask3d)
513
+ if not mask3d.any():
514
+ continue
515
+ ndi.label(mask3d, structure=structure, output=lab3d)
516
+ max_lab = int(lab3d.max())
517
+ if max_lab <= 1:
518
+ continue
519
+ counts = np.bincount(lab3d.ravel())
520
+ keep = counts[1:].argmax() + 1
521
+ np.logical_and(mask3d, lab3d != keep, out=mask3d)
522
+ result[mask3d] = 0
523
+ return result
524
+
525
+
526
+ def _save_preprocess(
527
+ path: Path, image: np.ndarray, stages: dict[str, object], final: dict[str, object]
528
+ ) -> None:
529
+ final_image = final["image"]
530
+ if not isinstance(final_image, torch.Tensor):
531
+ raise TypeError("final transform did not produce a tensor")
532
+ stages["input"] = image
533
+ stages["final"] = np.asarray(final_image.detach().cpu())
534
+ np.savez_compressed(path, **stages)
535
+
536
+
537
+ def _phantom(
538
+ shape: tuple[int, int, int],
539
+ center: tuple[int, int, int],
540
+ radii: tuple[int, int, int],
541
+ *,
542
+ seed: int,
543
+ ) -> np.ndarray:
544
+ rng = np.random.default_rng(seed)
545
+ axes = [np.arange(size, dtype=np.float32) for size in shape]
546
+ grid = np.meshgrid(*axes, indexing="ij")
547
+ distance = sum(
548
+ ((coordinate - center[index]) / radii[index]) ** 2
549
+ for index, coordinate in enumerate(grid)
550
+ )
551
+ data = np.zeros(shape, dtype=np.float32)
552
+ inside = distance <= 1.0
553
+ phase = distance[inside] * np.float32(np.pi)
554
+ data[inside] = (
555
+ np.float32(40.0)
556
+ + np.float32(30.0) * np.cos(phase)
557
+ + np.float32(3.0) * rng.normal(size=int(inside.sum())).astype(np.float32)
558
+ )
559
+ data[distance <= 0.12] = np.float32(-25.0)
560
+ return np.ascontiguousarray(data)
561
+
562
+
563
+ def _slab(shape: tuple[int, int, int]) -> np.ndarray:
564
+ data = np.zeros(shape, dtype=np.float32)
565
+ data[20:300, 10:210, :] = np.float32(100.0)
566
+ data[20:300, 10:210, :] += np.linspace(-5.0, 5.0, 280, dtype=np.float32)[:, None, None]
567
+ data[120:180, 80:130, :] = np.float32(-20.0)
568
+ return np.ascontiguousarray(data)
569
+
570
+
571
+ def _large_slab(shape: tuple[int, int, int]) -> np.ndarray:
572
+ """A deterministic large volume made by tiling the labelled synthetic phantom.
573
+
574
+ A uniform slab made the released model predict background everywhere; tiling the
575
+ smaller phantom keeps the multi-window and multi-chunk cases numerically active.
576
+ """
577
+ small = _phantom((100, 90, 4), (50, 45, 2), (13, 10, 2), seed=7)
578
+ tiled = np.tile(small, (3, 3, 5))
579
+ return np.ascontiguousarray(tiled[: shape[0], : shape[1], : shape[2]])
580
+
581
+
582
+ def _write_nifti(path: Path, data: np.ndarray, affine: np.ndarray) -> None:
583
+ image = nib.Nifti1Image(data, affine)
584
+ image.set_qform(affine, 1)
585
+ image.set_sform(affine, 1)
586
+ image.header.set_xyzt_units("mm", "sec")
587
+ nib.save(image, str(path))
588
+
589
+
590
+ def _module_version(name: str) -> str:
591
+ module = __import__(name)
592
+ return str(getattr(module, "__version__", "unknown"))
593
+
594
+
595
+ if __name__ == "__main__":
596
+ raise SystemExit(main())
qualification/qualify_real.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Compare native Metal inference with recorded real-image MONAI 1.3.2 outputs.
2
+
3
+ Run after recording with make_reference_fixtures.py:
4
+
5
+ .venv/bin/python scripts/qualify_real.py \
6
+ --reference build/reference --weights build/converted --output build/parity.json
7
+
8
+ The existing float32 contract is atol=5e-4, rtol=1e-5 for network and restored
9
+ logits. Anatomical masks must match exactly, including component filtering.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import argparse
15
+ import json
16
+ from pathlib import Path
17
+
18
+ import numpy as np
19
+ from medmlx_core.runtime import import_mlx
20
+ from medmlx_core.sliding_window import sliding_window_inference
21
+
22
+ from musclemap_mlx.config import load_model_config
23
+ from musclemap_mlx.geometry import (
24
+ discretize,
25
+ invert_logits,
26
+ keep_largest_components,
27
+ preprocess,
28
+ )
29
+ from musclemap_mlx.pipeline import _predict_window
30
+ from musclemap_mlx.weights import load_network
31
+
32
+
33
+ def _error(actual: np.ndarray, expected: np.ndarray) -> dict[str, object]:
34
+ difference = np.abs(actual - expected)
35
+ return {
36
+ "max_absolute_error": float(difference.max()),
37
+ "mean_absolute_error": float(difference.mean()),
38
+ "allclose": bool(np.allclose(actual, expected, atol=5e-4, rtol=1e-5)),
39
+ "finite": bool(np.isfinite(actual).all()),
40
+ }
41
+
42
+
43
+ def main() -> int:
44
+ parser = argparse.ArgumentParser(description=__doc__)
45
+ parser.add_argument("--reference", type=Path, required=True)
46
+ parser.add_argument("--weights", type=Path, required=True)
47
+ parser.add_argument("--output", type=Path, required=True)
48
+ args = parser.parse_args()
49
+ metadata = json.loads((args.reference / "metadata.json").read_text())
50
+ spec = load_model_config(args.weights / "config.json")
51
+ mx = import_mlx()
52
+ network = load_network(args.weights, spec)
53
+ expected = np.load(args.reference / "labels.npy", allow_pickle=False)
54
+ full = np.zeros(expected.shape, dtype=np.int16)
55
+ chunks: list[dict[str, object]] = []
56
+ for path in sorted(args.reference.glob("chunk-*.npz"), key=lambda p: int(p.stem[6:])):
57
+ start = int(path.stem[6:])
58
+ with np.load(path, allow_pickle=False) as fixture:
59
+ prepared = preprocess(fixture["input"], fixture["affine"], spec)
60
+ preprocessing_error = float(np.max(np.abs(prepared.data - fixture["prepared"])))
61
+ prediction = network(mx.array(fixture["network_input"]))
62
+ mx.eval(prediction)
63
+ network_error = _error(np.asarray(prediction), fixture["network_logits"])
64
+ padded = sliding_window_inference(
65
+ prepared.data[None], (256, 256, 1), spec.spatial_window_batch_size,
66
+ lambda window: _predict_window(network, window), overlap=0.9,
67
+ mode="gaussian", sigma_scale=0.125, padding_mode="constant", cval=0.0,
68
+ sw_device="gpu", device="cpu", predictor_input="mlx",
69
+ )
70
+ inverted = invert_logits(np.asarray(padded)[0], prepared.geometry)
71
+ restored_error = _error(inverted, fixture["inverted_logits"])
72
+ labels = discretize(inverted, spec)
73
+ end = start + labels.shape[2]
74
+ full[..., start:end] = labels
75
+ chunks.append({
76
+ "slices": [start, end], "preprocessing_max_absolute_error": preprocessing_error,
77
+ "network": network_error, "restored_logits": restored_error,
78
+ })
79
+ print(json.dumps(chunks[-1]), flush=True)
80
+ actual = keep_largest_components(full)
81
+ mismatch = int(np.count_nonzero(actual != expected))
82
+ dice: dict[str, float] = {}
83
+ for label in np.union1d(np.unique(actual), np.unique(expected)):
84
+ if label != 0:
85
+ left, right = actual == label, expected == label
86
+ dice[str(int(label))] = float(
87
+ 2 * np.count_nonzero(left & right) / (left.sum() + right.sum())
88
+ )
89
+ report = {
90
+ "input_name": metadata["input_name"], "shape": list(actual.shape),
91
+ "chunks": chunks, "mismatched_voxels": mismatch,
92
+ "voxel_agreement": float(np.mean(actual == expected)), "dice": dice,
93
+ "foreground_labels": len(dice), "mlx_device": str(mx.default_device()),
94
+ "criteria": {"logits_atol": 5e-4, "logits_rtol": 1e-5, "mask_exact": True},
95
+ "passed": mismatch == 0 and all(
96
+ c["network"]["allclose"] and c["restored_logits"]["allclose"]
97
+ for c in chunks
98
+ ),
99
+ }
100
+ args.output.write_text(json.dumps(report, indent=2) + "\n")
101
+ print(json.dumps({key: value for key, value in report.items() if key != "chunks"}))
102
+ return 0 if report["passed"] else 1
103
+
104
+
105
+ if __name__ == "__main__":
106
+ raise SystemExit(main())
qualification/requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # Upstream reference environment for MuscleMap v1.4 (dev-only).
2
+ # torch 2.4.1 and MONAI 1.3.2 follow reference/requirements.txt; Python 3.12 is
3
+ # required because torch 2.4.1 has no CPython 3.13 wheel.
4
+ torch==2.4.1
5
+ monai==1.3.2
6
+ numpy==1.24.4
7
+ nibabel==5.2.1
8
+ scipy==1.11.4
9
+ safetensors>=0.4,<1