File size: 2,347 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
"""Patch the NiFreeze venv for the M0 reference runs.

- NIFREEZE_KEEP_DIR: process in this directory instead of a TemporaryDirectory,
  so sample_*, predicted_*, cmd-*.sh and ants-*0GenericAffine.mat stay.
  The visiting order of volumes goes to order.txt in that directory.
- NIFREEZE_ANTS_FLOAT=1: add --float 1 to antsRegistration (nipype `float`).

Originals are kept as *.orig for the diff.
"""

import shutil
import sys
from pathlib import Path

PKG = Path("/var/tmp/dwi-hmc/nifreeze-venv/lib/python3.12/site-packages/nifreeze")


def patch(path: Path, old: str, new: str) -> None:
    orig = path.with_suffix(path.suffix + ".orig")
    if not orig.exists():
        shutil.copy2(path, orig)
    text = orig.read_text()
    if text.count(old) != 1:
        sys.exit(f"pattern not found once in {path}: {old!r}")
    path.write_text(text.replace(old, new))


est = PKG / "estimator.py"
est_old = """        with TemporaryDirectory() as tmp_dir:
            print(f"Processing in <{tmp_dir}>")
            ptmp_dir = Path(tmp_dir)
"""
est_new = """        import contextlib
        import os

        _keep = os.environ.get("NIFREEZE_KEEP_DIR")
        if _keep:
            Path(_keep).mkdir(parents=True, exist_ok=True)
        with (
            contextlib.nullcontext(_keep) if _keep else TemporaryDirectory()
        ) as tmp_dir:
            print(f"Processing in <{tmp_dir}>")
            ptmp_dir = Path(tmp_dir)
"""
patch(est, est_old, est_new)
text = est.read_text()
order_old = """                    # update
                    dataset.set_transform(i, xform.matrix)
"""
order_new = """                    # update
                    dataset.set_transform(i, xform.matrix)
                    with open(ptmp_dir / "order.txt", "a") as _f:
                        _f.write(f"{i}\\n")
"""
if text.count(order_old) != 1:
    sys.exit("order pattern not found")
est.write_text(text.replace(order_old, order_new))

ants = PKG / "registration" / "ants.py"
ants_old = """    if num_threads:
        reg_iface.inputs.num_threads = num_threads

    return reg_iface
"""
ants_new = """    if num_threads:
        reg_iface.inputs.num_threads = num_threads

    import os

    if os.environ.get("NIFREEZE_ANTS_FLOAT") == "1":
        reg_iface.inputs.float = True

    return reg_iface
"""
patch(ants, ants_old, ants_new)
print("patched")