M4Raw_brain / code /validate_release.py
mylyu's picture
Add files using upload-large-folder tool
0c48aa5 verified
Raw History Blame Contribute Delete
14.4 kB
#!/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()