File size: 14,352 Bytes
0c48aa5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
#!/usr/bin/env python3
"""Read-only validation of a downloaded M4Raw Brain v1.6 release."""

from __future__ import annotations

import argparse
import csv
import hashlib
import json
import os
import re
import xml.etree.ElementTree as etree
from collections import Counter
from concurrent.futures import ProcessPoolExecutor
from pathlib import Path
from typing import Any

import h5py
import numpy as np
EXPECTED = {
    "h5": 2230,
    "train": 1024,
    "validation": 240,
    "test": 400,
    "motion_inter_scan": 64,
    "motion_intra_scan": 136,
    "gre": 366,
    "T1": 699,
    "T2": 699,
    "FLAIR": 466,
    "GRE": 366,
    "subjects": 208,
}
REQUIRED_H5_DATASETS = {"ismrmrd_header", "kspace", "reconstruction_rss"}
H5_RE = re.compile(
    r"^(?P<scan>\d+)_(?P<sequence>T1|T2|FLAIR|GRE)(?P<rep>\d{2})\.h5$"
)
CHECKSUM_EXCLUSIONS = {
    "SHA256SUMS",
    "metadata/hf_upload_audit.json",
}


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--release-root", type=Path, default=Path("."))
    parser.add_argument("--mode", choices=("quick", "full"), default="quick")
    parser.add_argument("--workers", type=int, default=min(8, os.cpu_count() or 1))
    parser.add_argument("--skip-checksums", action="store_true")
    return parser.parse_args()


def sha256(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as handle:
        for block in iter(lambda: handle.read(8 * 1024 * 1024), b""):
            digest.update(block)
    return digest.hexdigest()


def relative_l2(reference: np.ndarray, observed: np.ndarray) -> float:
    difference = np.asarray(reference) - np.asarray(observed)
    numerator = np.sqrt(np.sum(np.abs(difference) ** 2, dtype=np.float64))
    denominator = np.sqrt(np.sum(np.abs(reference) ** 2, dtype=np.float64))
    return float(numerator / max(float(denominator), 1e-12))


def centered_ifft_rss(kspace: np.ndarray) -> np.ndarray:
    coil_images = np.fft.fftshift(
        np.fft.ifft2(
            np.fft.ifftshift(kspace, axes=(-2, -1)),
            axes=(-2, -1),
            norm="ortho",
        ),
        axes=(-2, -1),
    )
    return np.sqrt(np.sum(np.abs(coil_images) ** 2, axis=1)).astype(np.float32)


def classify_h5(path: Path) -> tuple[str, str, int]:
    match = H5_RE.fullmatch(path.name)
    if match is None:
        raise ValueError(f"Invalid H5 filename: {path.name}")
    return match.group("scan"), match.group("sequence"), int(match.group("rep"))


def validate_h5_task(task: tuple[str, bool]) -> dict[str, Any]:
    path_text, full = task
    path = Path(path_text)
    errors: list[str] = []
    rss_relative_l2 = None
    try:
        scan_id, sequence, repetition = classify_h5(path)
        with h5py.File(path, "r") as handle:
            missing = REQUIRED_H5_DATASETS - set(handle.keys())
            if missing:
                errors.append(f"missing datasets {sorted(missing)}")
            kspace_dataset = handle["kspace"]
            target_dataset = handle["reconstruction_rss"]
            if kspace_dataset.ndim != 4:
                errors.append(f"kspace rank/shape {kspace_dataset.shape}")
            if target_dataset.ndim != 3:
                errors.append(f"target rank/shape {target_dataset.shape}")
            if kspace_dataset.ndim == 4 and target_dataset.ndim == 3:
                if kspace_dataset.shape[0] != target_dataset.shape[0]:
                    errors.append("slice count mismatch")
                if kspace_dataset.shape[1] != 4:
                    errors.append(f"receiver coils {kspace_dataset.shape[1]}")
                if kspace_dataset.shape[-2:] != target_dataset.shape[-2:]:
                    errors.append("spatial matrix mismatch")
                if kspace_dataset.shape[-2:] != (256, 256):
                    errors.append(f"spatial matrix {kspace_dataset.shape[-2:]}")
            if kspace_dataset.dtype != np.dtype(np.complex64):
                errors.append(f"kspace dtype {kspace_dataset.dtype}")
            if target_dataset.dtype != np.dtype(np.float32):
                errors.append(f"target dtype {target_dataset.dtype}")

            header = handle["ismrmrd_header"][()]
            payload = header if isinstance(header, bytes) else str(header).encode()
            root = etree.fromstring(payload)
            if root.tag.rsplit("}", 1)[-1] != "ismrmrdHeader":
                errors.append("unexpected XML root")

            attrs = handle.attrs
            for field in ("acquisition", "max", "patient_id"):
                if field not in attrs:
                    errors.append(f"missing root attribute {field}")

            kspace = np.asarray(kspace_dataset)
            target = np.asarray(target_dataset)
            stored_mask = (
                np.asarray(handle["acquired_pe_mask"], dtype=np.uint8)
                if "acquired_pe_mask" in handle
                else None
            )
        if not np.all(np.isfinite(kspace.real)) or not np.all(np.isfinite(kspace.imag)):
            errors.append("nonfinite kspace")
        if not np.all(np.isfinite(target)):
            errors.append("nonfinite target")
        pe_mask = np.any(kspace != 0, axis=(0, 1, 2)).astype(np.uint8)
        orthogonal_mask = np.any(kspace != 0, axis=(0, 1, 3)).astype(np.uint8)
        if stored_mask is not None and not np.array_equal(stored_mask, pe_mask):
            errors.append("stored acquired PE mask mismatch")
        if np.count_nonzero(pe_mask) == 0:
            errors.append("empty PE support")
        if (
            sequence != "GRE"
            and np.count_nonzero(pe_mask) == 256
            and np.count_nonzero(orthogonal_mask) < 256
        ):
            errors.append("partial support is not on documented final PE axis")
        if full:
            rss_relative_l2 = relative_l2(centered_ifft_rss(kspace), target)
            if rss_relative_l2 > 2e-6:
                errors.append(f"RSS relative L2 {rss_relative_l2:.3g}")
        return {
            "path": path_text,
            "scan_id": scan_id,
            "sequence": sequence,
            "repetition": repetition,
            "shape": list(kspace.shape),
            "pe_lines": int(np.count_nonzero(pe_mask)),
            "rss_relative_l2": rss_relative_l2,
            "errors": errors,
            "pass": not errors,
        }
    except Exception as error:
        return {
            "path": path_text,
            "errors": [f"{type(error).__name__}: {error}"],
            "pass": False,
        }


def read_tsv(path: Path) -> list[dict[str, str]]:
    with path.open(newline="", encoding="utf-8") as handle:
        return list(csv.DictReader(handle, delimiter="\t"))


def validate_manifests(root: Path) -> dict[str, Any]:
    errors: list[str] = []
    acquisitions = read_tsv(root / "metadata" / "acquisitions.tsv")
    subjects = read_tsv(root / "metadata" / "subjects.tsv")
    manifest_paths: set[str] = set()
    sequence_manifests: dict[str, list[dict[str, str]]] = {}
    for sequence in ("T1", "T2", "FLAIR", "GRE"):
        rows = read_tsv(root / "metadata" / f"{sequence}_manifest.tsv")
        sequence_manifests[sequence] = rows
        expected_rows = 183 if sequence == "GRE" else 208
        if len(rows) != expected_rows:
            errors.append(f"{sequence} manifest rows {len(rows)}")
        if len({row["scan_id"] for row in rows}) != len(rows):
            errors.append(f"{sequence} duplicate scan IDs")
        for row in rows:
            present_repetitions = sum(
                bool(row.get(f"h5_rep{index:02d}")) for index in range(1, 7)
            )
            expected_repetitions = (
                2
                if sequence == "GRE"
                else 6
                if sequence in {"T1", "T2"} and row["participant_split"] == "test"
                else 4
                if sequence == "FLAIR" and row["participant_split"] == "test"
                else 3
                if sequence in {"T1", "T2"}
                else 2
            )
            if present_repetitions != expected_repetitions:
                errors.append(
                    f"{sequence} repetitions {row['scan_id']}={present_repetitions}"
                )
            for index in range(1, 7):
                value = row.get(f"h5_rep{index:02d}", "")
                if value:
                    manifest_paths.add(value)
    actual_paths = {
        str(path.relative_to(root))
        for directory in (
            "multicoil_train",
            "multicoil_val",
            "multicoil_test",
            "multicoil_motion",
            "multicoil_gre",
        )
        for path in (root / directory).rglob("*.h5")
    }
    acquisition_paths = {row["relative_path"] for row in acquisitions}
    if manifest_paths != actual_paths:
        errors.append("sequence manifest path set mismatch")
    if acquisition_paths != actual_paths:
        errors.append("acquisition table path set mismatch")
    if len(subjects) != EXPECTED["subjects"]:
        errors.append(f"subject rows {len(subjects)}")
    if len({row["scan_id"] for row in subjects}) != len(subjects):
        errors.append("duplicate subject IDs")
    expected_subject_splits = {
        "train": 128,
        "validation": 30,
        "test": 25,
        "motion_inter_scan": 8,
        "motion_intra_scan": 17,
    }
    subject_splits = dict(Counter(row["participant_split"] for row in subjects))
    if subject_splits != expected_subject_splits:
        errors.append(f"subject split counts {subject_splits}")
    if any(
        row["participant_split"] == "test" and row["GRE_available"] != "false"
        for row in subjects
    ):
        errors.append("GRE unexpectedly available in expanded test cohort")
    if len(acquisitions) != EXPECTED["h5"]:
        errors.append(f"acquisition rows {len(acquisitions)}")
    if len({row["relative_path"] for row in acquisitions}) != len(acquisitions):
        errors.append("duplicate acquisition paths")
    if any(row["native_axis_order"] != "slice,coil,FE,PE" for row in acquisitions):
        errors.append("acquisition axis contract")
    if any(
        row["kspace_dtype"] != "complex64" or row["target_dtype"] != "float32"
        for row in acquisitions
    ):
        errors.append("acquisition dtype contract")
    missing = [relative for relative in actual_paths if not (root / relative).is_file()]
    if missing:
        errors.append(f"missing H5 files {len(missing)}")
    return {
        "pass": not errors,
        "acquisition_rows": len(acquisitions),
        "subject_rows": len(subjects),
        "errors": errors,
    }


def validate_checksums(root: Path) -> dict[str, Any]:
    expected: dict[str, str] = {}
    for line in (root / "SHA256SUMS").read_text(encoding="ascii").splitlines():
        digest, relative = line.split("  ", 1)
        expected[relative] = digest
    failures: list[str] = []
    for relative, digest in expected.items():
        path = root / relative
        if not path.is_file() or sha256(path) != digest:
            failures.append(relative)
    actual = {
        str(path.relative_to(root))
        for path in root.rglob("*")
        if path.is_file()
        and str(path.relative_to(root)) not in CHECKSUM_EXCLUSIONS
    }
    if actual != set(expected):
        failures.append("checksum path set mismatch")
    return {"pass": not failures, "checked": len(expected), "failures": failures}


def observed_counts(root: Path, results: list[dict[str, Any]]) -> dict[str, int]:
    paths = [Path(result["path"]) for result in results]
    sequences = Counter(result.get("sequence") for result in results)
    return {
        "h5": len(paths),
        "train": sum("multicoil_train" in path.parts for path in paths),
        "validation": sum("multicoil_val" in path.parts for path in paths),
        "test": sum("multicoil_test" in path.parts for path in paths),
        "motion_inter_scan": sum(
            "multicoil_motion" in path.parts and "inter_scan" in path.parts
            for path in paths
        ),
        "motion_intra_scan": sum(
            "multicoil_motion" in path.parts and "intra_scan" in path.parts
            for path in paths
        ),
        "gre": sum("multicoil_gre" in path.parts for path in paths),
        "T1": sequences["T1"],
        "T2": sequences["T2"],
        "FLAIR": sequences["FLAIR"],
        "GRE": sequences["GRE"],
        "subjects": len({result.get("scan_id") for result in results}),
    }


def main() -> None:
    args = parse_args()
    root = args.release_root.resolve()
    h5_paths = sorted(
        path
        for directory in (
            "multicoil_train",
            "multicoil_val",
            "multicoil_test",
            "multicoil_motion",
            "multicoil_gre",
        )
        for path in (root / directory).rglob("*.h5")
    )
    tasks = [(str(path), args.mode == "full") for path in h5_paths]
    with ProcessPoolExecutor(max_workers=args.workers) as executor:
        results = list(executor.map(validate_h5_task, tasks, chunksize=4))
    counts = observed_counts(root, results)
    structure = {
        "pass": counts == EXPECTED and all(result["pass"] for result in results),
        "counts": counts,
        "expected": EXPECTED,
        "failed_h5": [result for result in results if not result["pass"]],
        "maximum_rss_relative_l2": max(
            (result["rss_relative_l2"] or 0.0 for result in results), default=0.0
        ),
    }
    manifests = validate_manifests(root)
    checksums = (
        {"pass": True, "skipped": True}
        if args.skip_checksums
        else validate_checksums(root)
    )
    forbidden = [
        str(path.relative_to(root))
        for path in root.rglob("*")
        if path.is_file()
        and (path.suffix in {".zip", ".pyc"} or "__pycache__" in path.parts)
    ]
    report = {
        "release_root": str(root),
        "mode": args.mode,
        "structure_and_h5": structure,
        "manifests": manifests,
        "checksums": checksums,
        "forbidden_files": forbidden,
    }
    report["pass"] = (
        structure["pass"] and manifests["pass"] and checksums["pass"] and not forbidden
    )
    print(json.dumps(report, indent=2, sort_keys=True))
    if not report["pass"]:
        raise SystemExit(1)


if __name__ == "__main__":
    main()