File size: 6,489 Bytes
a4ba047
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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]))