File size: 3,016 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
"""Encode new scans from their measurements with a trained denoiser and encoder.

A case folder needs geometry.json, views.npz, proj_full.npy (any dose) and image.json, which
here only defines the output grid (z_mm, pixel_spacing_mm, origin_mm, thickness_mm); no image
array is read. Embeddings of the fold models are averaged when several folds are given.

    python -m proj2rep encode --cases DIR [DIR ...] --work WORK --folds 0 1 2 3 4 --out embeddings/
Output per case: <out>/<case>.npz with z0 (n,), slab (n, 512), regions (n, grid*grid, 512).
"""

import argparse
from pathlib import Path

import numpy as np
import torch

from .data import STEP, Case, slab_rows, to_input
from .evaluate import embed
from .geometry import Conventions, Geometry, reconstruct
from .models import denoise_scan
from .train_denoiser import load as load_denoiser
from .train_encoder import load as load_encoder


def encode_case(case, models, conv, device, grid=4):
    geo = Geometry(case)
    zs = geo.image_z[geo.valid()]
    lo, hi = case.slab_range
    z = np.arange(lo, hi + 1e-6, STEP)
    data = case.array("proj_full")
    slabs, regions = [], []
    for enc, dn in models:
        vol = reconstruct(geo, denoise_scan(dn, data, device), zs, device, conv(geo))
        xs = []
        for z0 in z:
            rows, flip = slab_rows(zs, z0)
            x = vol[rows].float().cpu()
            xs.append(to_input(x.flip(0) if flip else x))

        def run(x, enc=enc):
            with torch.autocast("cuda", dtype=torch.bfloat16):
                return enc(x.to(device).contiguous(memory_format=torch.channels_last_3d), grid=grid)

        s, r = embed(run, xs)
        slabs.append(s)
        regions.append(r.astype(np.float32))
    return {"z0": z, "slab": np.mean(slabs, 0), "regions": np.mean(regions, 0).astype(np.float16)}


def main(argv=None):
    p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    p.add_argument("--cases", nargs="+", required=True, help="case folders")
    p.add_argument("--work", required=True, help="training work directory (models and convention.json)")
    p.add_argument("--folds", type=int, nargs="+", default=[0])
    p.add_argument("--grid", type=int, choices=[4, 8], default=4, help="regional grid side length (8 for lesion scoring)")
    p.add_argument("--out", required=True)
    p.add_argument("--device", default="cuda:0" if torch.cuda.is_available() else "cpu")
    a = p.parse_args(argv)
    device = torch.device(a.device)
    models = [(load_encoder(a.work, f, device), load_denoiser(a.work, f, device)) for f in a.folds]
    conv = Conventions(Path(a.work) / "convention.json")
    out = Path(a.out)
    out.mkdir(parents=True, exist_ok=True)
    for folder in map(Path, a.cases):
        case = Case(folder.parent, folder.name)
        np.savez_compressed(out / f"{case.id}.npz", **encode_case(case, models, conv, device, a.grid))
        print("encoded", case.id, flush=True)


if __name__ == "__main__":
    main()