File size: 3,432 Bytes
76eb7b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Denoised back-projections of every case at several dose levels and view fractions, for one fold.

Uses the fold's own denoiser, so held-out cases are processed by a model that never saw them.
Levels: `full` (routine dose), `low` (the supplied reduced dose), `min` (noise scaled to
--min-dose of routine). View fractions: keep every k-th view. Cases are split across GPUs.

    torchrun --nproc_per_node 8 -m proj2rep bank --data DATA --work WORK --fold 0
Output: WORK/bank/fold<F>/<case>/<level>_v<k>.npy (int16 HU, 256 x 256) and z_mm.npy
"""

import argparse
from pathlib import Path

import numpy as np

from . import dist
from .data import group_of, load_cohort
from .geometry import Conventions, Geometry, reconstruct, sparse
from .models import denoise_scan
from .train_denoiser import load, noise_scale


def bank_dir(work, fold, case_id):
    return Path(work) / "bank" / f"fold{fold}" / case_id


def build_case(case, model, conv, out, device, levels, views, min_dose):
    geo = Geometry(case)
    zs = geo.image_z[geo.valid()]
    out.mkdir(parents=True, exist_ok=True)
    np.save(out / "z_mm.npy", zs)
    full = np.asarray(case.array("proj_full"), dtype=np.float32)
    noise = None
    if case.has("proj_low"):
        noise = np.asarray(case.array("proj_low"), dtype=np.float32) - full
    for level in levels:
        if level != "full" and (noise is None or not case.low_dose_fraction):
            continue
        scale = {"full": 0.0, "low": 1.0}[level] if level != "min" else noise_scale(case.low_dose_fraction, min_dose)
        for k in views if level != "min" else [1]:
            path = out / f"{level}_v{k}.npy"
            if path.exists():
                continue
            data = np.ascontiguousarray((full + scale * noise if scale else full)[::k])
            g = sparse(geo, k) if k > 1 else geo
            vol = reconstruct(g, denoise_scan(model, data, device), zs, device, conv(geo))
            tmp = path.with_suffix(".tmp.npy")
            np.save(tmp, vol.clamp(-2000, 6000).round().short().cpu().numpy())
            tmp.replace(path)


def main(argv=None):
    p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    p.add_argument("--data", required=True)
    p.add_argument("--work", required=True)
    p.add_argument("--fold", type=int, required=True, help="fold whose models are used (-1: the model trained on every case)")
    p.add_argument("--levels", nargs="+", default=["full", "low"], choices=["full", "low", "min"])
    p.add_argument("--views", type=int, nargs="+", default=[1, 2, 4, 8])
    p.add_argument("--min-dose", type=float, default=0.025)
    p.add_argument("--no-thin", nargs="*", default=[], help="REGION:MANUFACTURER groups built at all views only")
    a = p.parse_args(argv)

    rank, world, device = dist.init()
    cohort = load_cohort(a.data, work_dir=a.work)
    model = load(a.work, a.fold, device)
    conv = Conventions(Path(a.work) / "convention.json")
    ids = cohort.cases(cohort.ids(), image=False)[rank::world]
    for i, case in enumerate(ids):
        cid = case.id
        views = [1] if group_of(case, a.no_thin) else a.views
        build_case(case, model, conv, bank_dir(a.work, a.fold, cid), device, a.levels, views, a.min_dose)
        print(f"[rank {rank}] bank fold {a.fold}: {cid} ({i + 1}/{len(ids)})", flush=True)
    dist.done(sync=False)


if __name__ == "__main__":
    main()