webapps / hmc /reference /scripts /collect_qsiprep.py
gdevenyi's picture
hmc: NiFreeze 3bcfb00 and QSIPrep 26.1.1 SHORELine reference runs on ds005577 sub-107 (part 9)
a4ba047 verified
Raw History Blame Contribute Delete
6.49 kB
"""Collect the SHORELine reference artefacts of one QSIPrep run (M0).
Copies the small text artefacts (antsRegistration command lines, ITK .mat transforms,
motion CSVs, bvecs/bvals, config.toml, confounds) into RUN/collected/ and writes
RUN/collected/manifest.json, which lists every image the port needs (SHORE predictions,
registration inputs, b0 mean, b0 template mask) by path in the kept work directory,
with sha256, dtype, shape and scaling.
Usage: python -I collect_qsiprep.py RUN_DIR
"""
import hashlib
import json
import re
import shutil
import sys
from pathlib import Path
import nibabel as nb
import tomllib
HMC = "qsiprep_26_1_wf/sub_107_wf/dwi_preproc_dir_AP_wf/qsiprep_hmcsdc_wf/dwi_hmc_wf"
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 img_facts(p: Path) -> dict:
im = nb.load(p)
return {
"path": str(p),
"sha256": sha(p),
"shape": list(im.shape),
"on_disk_dtype": str(im.get_data_dtype()),
"slope": float(im.dataobj.slope),
"inter": float(im.dataobj.inter),
"axcodes": "".join(nb.aff2axcodes(im.affine)),
}
def mapflow_index(d: Path) -> int:
return int(re.search(r"(\d+)$", d.name).group(1))
def container_to_host(path: str, run: Path) -> Path:
return Path(path.replace("/work/", str(run / "work") + "/", 1))
def parse_reg(cmd: str, run: Path) -> dict:
metric = re.findall(r"--metric \w+\[ ([^,]+), ([^,]+),", cmd)
masks = re.findall(r"--masks \[ ([^,\]]+)", cmd)
return {
"fixed": [str(container_to_host(m[0], run)) for m in metric],
"moving": [str(container_to_host(m[1], run)) for m in metric],
"fixed_masks": [str(container_to_host(m, run)) for m in masks],
}
def collect_regs(base: Path, prefix: str, run: Path, dest: Path) -> list:
rows = []
for d in sorted(base.glob(f"mapflow/_{prefix}*"), key=mapflow_index):
i = mapflow_index(d)
cmd = (d / "command.txt").read_text()
mat = d / "transform0GenericAffine.mat"
out = dest / f"{i:03d}"
out.mkdir(parents=True, exist_ok=True)
shutil.copy2(d / "command.txt", out / "command.txt")
if mat.exists():
shutil.copy2(mat, out / "transform0GenericAffine.mat")
rows.append(
{"index": i, "dir": str(d), "has_mat": mat.exists(), **parse_reg(cmd, run)}
)
return rows
def main(run: Path) -> None:
work = run / "work"
hmc = work / HMC
dest = run / "collected"
if dest.exists():
shutil.rmtree(dest)
dest.mkdir()
man: dict = {"run": str(run)}
(cfg,) = sorted(work.glob("*/config.toml"))
shutil.copy2(cfg, dest / "config.toml")
conf = tomllib.loads(cfg.read_text())
man["seeds"] = conf["seeds"]
man["workflow_settings"] = {
k: conf["workflow"].get(k)
for k in (
"hmc_method",
"hmc_transform",
"shoreline_model",
"shoreline_iters",
"denoise_method",
"b0_threshold",
"output_resolution",
"anat_modality",
)
}
man["nipype"] = {k: conf["nipype"].get(k) for k in ("nprocs", "omp_nthreads")}
# b0 stage
b0 = hmc / "b0_hmc_wf"
man["b0_stage"] = {}
for it in sorted(b0.glob("iterative_alignment_*")):
(reg,) = list(it.glob("reg_*"))
man["b0_stage"][it.name] = collect_regs(reg, "reg_", run, dest / "b0" / it.name)
man["b0_initial_template"] = img_facts(b0 / "initial_template" / "average.nii")
man["b0_template_mask"] = [
img_facts(p) for p in sorted((hmc / "b0_template_mask").rglob("*.nii*"))
]
# SHORELine model iterations
model = hmc / "dwi_model_hmc_wf"
man["b0_mean"] = [img_facts(p) for p in sorted((model / "b0_mean").glob("*.nii*"))]
iters = [model / "initial_model_iteration"] + sorted(
model.glob("shoreline_iteration*")
)
man["model_iterations"] = {}
for it in iters:
name = it.name
regs = collect_regs(
it / "register_to_predicted",
"register_to_predicted",
run,
dest / "model" / name,
)
preds = []
for d in sorted(
(it / "predict_dwis").glob("mapflow/_predict_dwis*"), key=mapflow_index
):
(p,) = list(d.glob("predicted_*.nii*"))
preds.append({"index": mapflow_index(d), **img_facts(p)})
mot = it / "calculate_motion" / "motion_params.csv"
if mot.exists():
shutil.copy2(mot, dest / f"motion_params_{name}.csv")
for f in (it / "post_bvec_transforms").glob("*.bvec"):
shutil.copy2(f, dest / f"rotated_{name}_{f.name}")
man["model_iterations"][name] = {"registrations": regs, "predictions": preds}
# Registration inputs (moving images: original split volumes) and their facts
moving = sorted(
{
m
for it in man["model_iterations"].values()
for r in it["registrations"]
for m in r["moving"]
}
)
man["moving_images"] = [img_facts(Path(p)) for p in moving]
# Outputs
outs = run / "out"
for pat in (
"**/*_dwi.bvec",
"**/*_dwi.bval",
"**/*_dwi.b",
"**/*confounds*.tsv",
"**/*motion*",
"**/*.html",
):
for f in outs.glob(pat):
if f.is_file():
shutil.copy2(f, dest / f.name)
man["outputs"] = sorted(
str(p.relative_to(outs)) for p in outs.rglob("*") if p.is_file()
)
(dest / "manifest.json").write_text(json.dumps(man, indent=1))
print(
json.dumps(
{
"seeds": man["seeds"],
"workflow": man["workflow_settings"],
"b0_stage": {k: len(v) for k, v in man["b0_stage"].items()},
"model_iterations": {
k: (len(v["registrations"]), len(v["predictions"]))
for k, v in man["model_iterations"].items()
},
"moving_images": len(man["moving_images"]),
"moving_dtypes": sorted(
{m["on_disk_dtype"] for m in man["moving_images"]}
),
"n_outputs": len(man["outputs"]),
},
indent=1,
)
)
if __name__ == "__main__":
main(Path(sys.argv[1]))