"""Assemble the M0 HMC reference folder for the Hugging Face dataset path hmc/reference/. Usage: python -I pack_hmc.py OUT_DIR Copies text artefacts unchanged, gzips raw .nii files without a timestamp, writes the prediction intermediates as float32 and records every cast error. Writes OUT/index.json (relative paths, source path, source sha256, dtype, cast error). """ import gzip import hashlib import json import re import shutil import sys from pathlib import Path import h5py import nibabel as nb import numpy as np H = Path("/var/tmp/dwi-hmc") R = H / "runs" DATA = Path("/var/tmp/dwi-data/ds005577") QW = "work/qsiprep_26_1_wf/sub_107_wf/dwi_preproc_dir_AP_wf/qsiprep_hmcsdc_wf" HMC = QW + "/dwi_hmc_wf" NIFREEZE_RUNS = ( "trivial-a1", "trivial-a2", "trivial-float", "gp", "gp-float", "gp-seed1235", ) INTERMEDIATE_RUNS = ("trivial-a1", "gp") index: dict = {"files": {}, "notes": {}} OUT = Path(sys.argv[1]) def sha(p: Path) -> str: h = hashlib.sha256() with p.open("rb") as f: for chunk in iter(lambda: f.read(1 << 20), b""): h.update(chunk) return h.hexdigest() def rel(p: Path) -> str: return str(p.relative_to(OUT)) def record(dst: Path, src: Path, **extra) -> None: index["files"][rel(dst)] = {"source": str(src), "source_sha256": sha(src), **extra} def copy(src: Path, dst: Path, **extra) -> None: dst.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(src, dst) record(dst, src, **extra) def write_gz(raw: bytes, dst: Path) -> None: dst.parent.mkdir(parents=True, exist_ok=True) with ( dst.open("wb") as f, gzip.GzipFile(filename="", mode="wb", fileobj=f, mtime=0, compresslevel=9) as g, ): g.write(raw) def gzip_nii(src: Path, dst: Path) -> None: """Gzip a .nii byte for byte (the decompressed file equals the source).""" write_gz(src.read_bytes(), dst) record(dst, src, transform="gzip only; decompressed bytes equal the source") def float32_nii(src: Path, dst: Path) -> dict: img = nb.load(src) d64 = np.asarray(img.dataobj, dtype=np.float64) d32 = d64.astype(np.float32) err = np.abs(d32.astype(np.float64) - d64) scale = float(np.abs(d64).max()) or 1.0 hdr = img.header.copy() hdr.set_data_dtype(np.float32) out = nb.Nifti1Image(d32, img.affine, header=hdr) out.header.set_slope_inter(1.0, 0.0) write_gz(out.to_bytes(), dst) facts = { "source_dtype": str(img.get_data_dtype()), "stored_dtype": "float32", "cast_max_abs": float(err.max()), "cast_max_rel_to_volume_max": float(err.max()) / scale, } record(dst, src, **facts) return facts def write_text(dst: Path, text: str, src: str) -> None: """Write a file that has no source file; record the SHA-256 of the written file.""" dst.parent.mkdir(parents=True, exist_ok=True) dst.write_text(text) index["files"][rel(dst)] = {"source": src, "sha256": sha(dst)} # ---------------------------------------------------------------- input and mask for ext in ("nii.gz", "bval", "bvec"): copy( DATA / f"sub-107_dir-AP_dwi.{ext}", OUT / "input" / f"sub-107_dir-AP_dwi.{ext}" ) # The sidecar loses six site and time fields, as in noddi/examples/. Every other byte # stays: the script checks that json.dumps(indent=4) gives the original file back. SITE_FIELDS = ( "AcquisitionTime", "DeviceSerialNumber", "InstitutionAddress", "InstitutionName", "InstitutionalDepartmentName", "StationName", ) # Per-file record for the note site_fields_removed (the same form as redact_sidecars.py). site_note: dict = {} def drop_site_fields(obj, path: str = "") -> list[str]: """Delete SITE_FIELDS from obj and from every nested object. Return the paths.""" removed = [] if isinstance(obj, dict): for k in list(obj): p = f"{path}/{k}" if path else k if k in SITE_FIELDS: del obj[k] removed.append(p) else: removed += drop_site_fields(obj[k], p) elif isinstance(obj, list): for i, v in enumerate(obj): removed += drop_site_fields(v, f"{path}/{i}") return removed def redact_sidecar(src: Path, dst: Path) -> None: """Copy a BIDS sidecar without SITE_FIELDS, at any depth. Every other line stays. QSIPrep's output sidecar holds the fields twice: at the top level and in SourceMetadata/. """ raw_json = src.read_text() side = json.loads(raw_json) tail = raw_json[len(raw_json.rstrip("\n")) :] assert json.dumps(side, indent=4, ensure_ascii=False) + tail == raw_json, src assert all(k in side for k in SITE_FIELDS), src removed = drop_site_fields(side) new = json.dumps(side, indent=4, ensure_ascii=False) + tail # Only the lines of the removed fields go away (none of them is the last member). kept = [ ln for ln in raw_json.splitlines(keepends=True) if not any(f'"{k}":' in ln for k in SITE_FIELDS) ] assert kept == new.splitlines(keepends=True), src assert len(raw_json.splitlines()) - len(new.splitlines()) == len(removed), src dst.parent.mkdir(parents=True, exist_ok=True) dst.write_text(new) record( dst, src, removed_fields=list(SITE_FIELDS), removed_paths=removed, source_bytes=src.stat().st_size, ) site_note[rel(dst)] = { "original_sha256": index["files"][rel(dst)]["source_sha256"], "original_bytes": src.stat().st_size, "sha256": sha(dst), "bytes": dst.stat().st_size, "removed_paths": removed, } redact_sidecar(DATA / "sub-107_dir-AP_dwi.json", OUT / "input/sub-107_dir-AP_dwi.json") copy( H / "inputs/ds005577-meta/dataset_description.json", OUT / "input/dataset_description.json", ) copy(H / "inputs/input-facts.json", OUT / "input/input-facts.json") copy(H / "inputs/mask.nii.gz", OUT / "mask/sub-107_dir-AP_desc-mindgrab_mask.nii.gz") gzip_nii(H / "inputs/meanb0.nii", OUT / "mask/sub-107_dir-AP_desc-meanb0_dwiref.nii.gz") copy(H / "inputs/mask-facts.json", OUT / "mask/mask-facts.json") copy(H / "inputs/mask-overlay.png", OUT / "mask/mask-overlay.png") mask_sha = sha(H / "inputs/mask.nii.gz") # ---------------------------------------------------------------- NiFreeze runs sample_sets = {} for name in NIFREEZE_RUNS: run = R / f"nifreeze-{name}" dst = OUT / f"nifreeze-{name}" for f in ( "command.txt", "timing.txt", "nifreeze.log", "motion.tsv", "motion-check.json", "clip-facts.json", ): if (run / f).exists(): copy(run / f, dst / f) if sha(run / "mask.nii.gz") != mask_sha: copy(run / "mask.nii.gz", dst / "mask.nii.gz") for f in sorted((run / "out").iterdir()): if f.suffix in (".bval", ".bvec", ".x5"): copy(f, dst / "out" / f.name) work = run / "work" copy(work / "order.txt", dst / "work/order.txt") copy(work / "brainmask.nii.gz", dst / "work/brainmask.nii.gz") for f in sorted(work.glob("cmd-*.sh")): copy(f, dst / "work" / f.name) for f in sorted(work.glob("ants-*GenericAffine.mat")): copy(f, dst / "work" / f.name) (h5,) = list((run / "out").glob("*.h5")) with h5py.File(h5) as h: aff = np.asarray(h["0/motion_affines"]) if name == "gp": # The GP run never clips bzero, so its HDF5 holds the median of the raw b0 # volumes. The trivial run's HDF5 holds the clipped map (advanced_clip # writes in place into the float64 bzero). bzero = np.asarray(h["0/bzero"]) ref_affine = np.asarray(h["0/affine"]) rows = ["\t".join(f"m{i}{j}" for i in range(4) for j in range(4))] rows += ["\t".join(repr(float(v)) for v in a.ravel()) for a in aff] write_text( dst / "motion_affines.tsv", "\n".join(rows) + "\n", f"{h5}:0/motion_affines" ) index["files"][rel(dst / "motion_affines.tsv")]["source_sha256_h5"] = sha(h5) sample_sets[name] = {f.name: sha(f) for f in sorted(work.glob("sample_*.nii.gz"))} if name in INTERMEDIATE_RUNS: preds = sorted(work.glob("predicted_*.nii.gz")) pred_shas = {sha(p) for p in preds} if name == "trivial-a1": assert len(pred_shas) == 1, "trivial predictions differ" float32_nii(preds[0], dst / "work" / preds[0].name) index["notes"][f"nifreeze-{name}"] = ( f"all {len(preds)} predicted_*.nii.gz have one sha256 ({pred_shas.pop()}); " f"only {preds[0].name} is kept" ) else: bz = nb.Nifti1Image(bzero, ref_affine) bz.header.set_data_dtype(np.float64) p = dst / "bzero.nii.gz" write_gz(bz.to_bytes(), p) index["files"][rel(p)] = { "source": f"{h5}:0/bzero", "stored_dtype": "float64", "content": "median of the 11 raw b0 volumes, before any clip", } assert len(pred_shas) == len(preds) for p in preds: float32_nii(p, dst / "work" / p.name) for f in sorted(work.glob("sample_*.nii.gz")): copy(f, dst / "work" / f.name) ref = sample_sets["gp"] same = {n: s == ref for n, s in sample_sets.items()} index["notes"]["sample_sets_equal_to_gp"] = same assert all(same.values()), same # ---------------------------------------------------------------- Q53 b0 test, comparisons, QC for f in sorted((R / "q53-b0").glob("*.mat")): copy(f, OUT / "q53-b0" / f.name) copy(R / "q53-b0/q53-b0-summary.json", OUT / "q53-b0/q53-b0-summary.json") copy(R / "q53-seed-rule.json", OUT / "compare/q53-seed-rule.json") copy(R / "q53-b0.log", OUT / "q53-b0/q53-b0.log") for f in sorted(R.glob("compare-*.json")): copy(f, OUT / "compare" / f.name) for f in ("gp-dryrun-equiv.log", "gp-dryrun-fit.log"): copy(R / f, OUT / "compare" / f) for f in sorted((R / "qc").iterdir()): if f.is_file(): copy(f, OUT / "qc" / f.name) for f in sorted((R / "qc/converge").rglob("*")): if f.is_file(): copy(f, OUT / "qc/converge" / f.relative_to(R / "qc/converge")) # ---------------------------------------------------------------- QSIPrep # r1: local host, --nthreads 1, full layout (the one run with predictions and templates). # e1-e3: host epic, --nthreads 10, the repeat set for the Q54 spread. They keep the # transforms, command lines, motion, bvecs, config, text outputs and the --masks file. QSIPREP_RUNS = ("r1", "e1", "e2", "e3") FULL_RUN = "r1" split = R / "qsiprep-r1" / QW / "split_dwis" for f in sorted(split.glob("vol.*.nii")): gzip_nii(f, OUT / "qsiprep/input/split_dwis" / (f.name + ".gz")) for f in ( "qsiprep-spread-e123.json", "qsiprep-spread-e123.summary.json", "qsiprep-spread-r1e123.json", "qsiprep-spread-r1e123.summary.json", # SHORELine spread rule (shoreline-pairs.sh, shoreline_spread_rule.py). "qsiprep-spread-e123-rule.json", "qsiprep-spread-r1-e1.json", "qsiprep-spread-r1-e2.json", "qsiprep-spread-r1-e3.json", ): copy(R / f, OUT / "qsiprep" / f.removeprefix("qsiprep-")) # The conformed volumes of e1-e3 differ from r1 only in the AFNI extension (a random # idcode and its date). Check that the NIfTI header block and the voxel data are # equal, and name the AFNI attributes that differ. AFNI_ATR = re.compile(r'name\s*=\s*"(\w+)"[^>]*>(.*?)', re.DOTALL) def afni_items(img) -> list: (ext,) = img.header.extensions text = ext.get_content() return AFNI_ATR.findall(text.decode() if isinstance(text, bytes) else text) split_check = {} for name in QSIPREP_RUNS[1:]: other = R / f"qsiprep-{name}" / QW / "split_dwis" n_bytes = 0 differ: set = set() for f in sorted(split.glob("vol.*.nii")): g = other / f.name if sha(f) == sha(g): continue n_bytes += 1 a, b = nb.load(f), nb.load(g) assert a.header.binaryblock == b.header.binaryblock, g assert np.array_equal(np.asarray(a.dataobj), np.asarray(b.dataobj)), g ia, ib = afni_items(a), afni_items(b) assert [k for k, _ in ia] == [k for k, _ in ib], g differ |= {k for (k, va), (_, vb) in zip(ia, ib) if va != vb} split_check[name] = { "volumes": len(list(other.glob("vol.*.nii"))), "bytes_differ": n_bytes, "header_block_and_data_equal_to_r1": True, "afni_attributes_differ": sorted(differ), } index["notes"]["qsiprep_split_dwis_vs_r1"] = split_check IMAGES_GZ = { "b0_hmc_wf/initial_template/average.nii": "b0-initial-template.nii.gz", "b0_hmc_wf/iterative_alignment_000/averaged_images/average.nii": "b0-iter000-average.nii.gz", "b0_hmc_wf/iterative_alignment_000/invert_average/average_trans.nii": "b0-iter000-average_trans.nii.gz", "b0_hmc_wf/iterative_alignment_001/averaged_images/average.nii": "b0-iter001-average.nii.gz", "b0_hmc_wf/iterative_alignment_001/invert_average/average_trans.nii": "b0-iter001-average_trans.nii.gz", "b0_template_mask/synthstrip_wf/mask_brain/masked_brain.nii": "b0-template-masked_brain.nii.gz", } IMAGES_COPY = { "b0_template_mask/synthstrip_wf/mask_to_original_grid/average_trans_trans_mask_trans.nii.gz": "b0-template-mask.nii.gz", "dwi_model_hmc_wf/b0_mean/b0_mean.nii.gz": "b0_mean.nii.gz", "dwi_model_hmc_wf/calculate_cnr/SHORELine_CNR.nii.gz": "SHORELine_CNR.nii.gz", } MASK_KEY = next(iter(IMAGES_COPY)) init_template = {} for name in QSIPREP_RUNS: run = R / f"qsiprep-{name}" dst = OUT / f"qsiprep-{name}" for f in ("command.txt", "timing.txt"): copy(run / f, dst / f) write_gz((run / "qsiprep.log").read_bytes(), dst / "qsiprep.log.gz") record(dst / "qsiprep.log.gz", run / "qsiprep.log", transform="gzip only") col = run / "collected" for f in sorted(col.rglob("*")): if f.is_file() and f.suffix != ".html" and f.name != "manifest.json": copy(f, dst / "collected" / f.relative_to(col)) copy(col / "manifest.json", dst / "collected/manifest-host-paths.json") dwi_out = run / "out/sub-107/dwi" for f in sorted(dwi_out.iterdir()): if f.suffix in ( ".csv", ".tsv", ".json", ".bval", ".bvec", ".b", ".mat", ".txt", ): if f.suffix == ".json" and SITE_FIELDS[0] in f.read_text(): # QSIPrep copies the input sidecar fields into its output sidecar. redact_sidecar(f, dst / "out" / f.name) else: copy(f, dst / "out" / f.name) hmc = run / HMC init_template[name] = sha(hmc / "b0_hmc_wf/initial_template/average.nii") if name != FULL_RUN: copy(hmc / MASK_KEY, dst / "images" / IMAGES_COPY[MASK_KEY]) continue for s, d in IMAGES_GZ.items(): gzip_nii(hmc / s, dst / "images" / d) for s, d in IMAGES_COPY.items(): copy(hmc / s, dst / "images" / d) man = json.loads((col / "manifest.json").read_text()) worst = {} for it, v in man["model_iterations"].items(): errs = [] for p in v["predictions"]: src = Path(p["path"]) d = dst / "collected/model" / it / f"{p['index']:03d}" / "predicted.nii.gz" facts = float32_nii(src, d) index["files"][rel(d)]["source_name"] = src.name errs.append(facts["cast_max_rel_to_volume_max"]) worst[it] = max(errs) index["notes"]["qsiprep_prediction_cast_max_rel"] = worst index["notes"]["qsiprep_initial_template_sha256"] = init_template assert len(set(init_template.values())) == 1, init_template epic_sif = { name: dict( line.split("=", 1) for line in (R / f"qsiprep-{name}/command.txt").read_text().splitlines() if "=" in line )["sif_sha256"] for name in QSIPREP_RUNS[1:] } assert len(set(epic_sif.values())) == 1, epic_sif write_text( OUT / "env/qsiprep-26.1.1-epic.sif.sha256", f"{epic_sif['e1']} qsiprep-26.1.1.sif (host epic, runs e1-e3)\n", "sif_sha256 in qsiprep-e{1,2,3}/command.txt", ) # ---------------------------------------------------------------- patches, environment, scripts copy(H / "nifreeze-patch.diff", OUT / "patches/nifreeze-keepdir-float.diff") copy( H / "sklearn-gpr-patch.diff", OUT / "patches/sklearn-1.9.1-gpr-gradient-memory.diff" ) copy(H / "nifreeze-pip-freeze.txt", OUT / "env/nifreeze-pip-freeze.txt") copy(H / "analysis-pip-freeze.txt", OUT / "env/analysis-pip-freeze.txt") copy(H / "ants/BUILD-OPTIONS.sh", OUT / "env/ants-BUILD-OPTIONS.sh") copy(H / "containers/qsiprep-26.1.1-tag.json", OUT / "env/qsiprep-26.1.1-tag.json") copy(H / "containers/qsiprep-26.1.1.sif.sha256", OUT / "env/qsiprep-26.1.1.sif.sha256") copy(H / "bids-sha256.txt", OUT / "env/qsiprep-bids-input-sha256.txt") for f in sorted((H / "scripts").iterdir()): if f.is_file() and f.suffix in (".py", ".sh", ".mjs"): copy(f, OUT / "scripts" / f.name) # The input sidecar and the four QSIPrep output sidecars. assert len(site_note) == 5, sorted(site_note) index["notes"]["site_fields_removed"] = { "fields": list(SITE_FIELDS), "files": dict(sorted(site_note.items())), "kept": ( "The NIfTI descrip of input/sub-107_dir-AP_dwi.nii.gz (the public CC0 original, " "copied unchanged) and of mask/sub-107_dir-AP_desc-meanb0_dwiref.nii.gz (its " "header comes from the input) holds the acquisition time in its 'Time=' item." ), } (OUT / "index.json").write_text(json.dumps(index, indent=1, sort_keys=True) + "\n") print(json.dumps(index["notes"], indent=1))