File size: 8,354 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
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
"""Analytic back-projection of helical fan-beam measurements onto the reconstruction grid.

Ramp filter along detector columns with fan-beam cosine weighting, then, for every output
slice, back-projection of the gantry rotation of views nearest to that slice, with detector
rows chosen by the cone angle. A fast, vendor-independent reconstruction that the encoder is
trained to read. Output is in HU on the case's image grid at 256 x 256.

Vendors store angles, columns and rows with different signs and offsets. `calibrate` picks,
per manufacturer, the convention whose back-projection best matches the scanner images.
"""

import copy
import itertools
import json
import math
from pathlib import Path

import numpy as np
import torch
import torch.nn.functional as F

SIZE = 256  # output pixels per side


class Geometry:
    def __init__(self, case, size=SIZE):
        g, im, v = case.geometry, case.image_meta, case.views
        self.case, self.manufacturer = case.id, case.manufacturer.upper()
        self.head_first = str(g.get("patient_position", "FFS")).upper().startswith("HF")
        sid = v.get("source_isocenter_mm")
        self.sid = float(np.mean(sid)) if sid is not None else float(g["source_isocenter_mm"])
        self.sdd = float(g["source_detector_mm"])
        self.dgamma = float(g["column_spacing_mm"]) / self.sdd
        self.drow = float(g["row_spacing_mm"])
        self.c0, self.r0 = g["central_element"][0] - 1, g["central_element"][1] - 1  # 1-based in the file
        self.rows, self.cols = int(g["detector_rows"]), int(g["detector_columns"])
        self.mu = float(g["water_mu_per_mm"])
        self.n = round(float(g["stored_views_per_rotation"]))
        self.angle, self.z = v["angle_rad"].astype(np.float64), v["z_mm"].astype(np.float64)
        self.image_z = np.asarray(im["z_mm"], dtype=np.float64)
        self.thickness = float(im.get("thickness_mm", 1.5))
        # DICOM order: pixel_spacing_mm = [between rows (y), between columns (x)]
        sy, sx = (float(v) for v in im["pixel_spacing_mm"])
        width, height = int(im.get("columns", 512)), int(im.get("rows", im.get("columns", 512)))
        self.x = im["origin_mm"][0] + (np.arange(size) + 0.5) * sx * width / size - 0.5 * sx
        self.y = im["origin_mm"][1] + (np.arange(size) + 0.5) * sy * height / size - 0.5 * sy
        c = im.get("rotation_center_mm") or [0.0, 0.0]
        self.centre = (float(c[0]), float(c[1]))

    def valid(self):
        """Indices of image slices with measurements on both sides."""
        return np.flatnonzero((self.image_z >= self.z.min()) & (self.image_z <= self.z.max()))


def sparse(geo, k):
    """The same acquisition keeping every k-th view (use with data[::k])."""
    g = copy.copy(geo)
    g.angle, g.z, g.n = geo.angle[::k], geo.z[::k], max(geo.n // k, 1)
    return g


def ramp(geo, device):
    """Equiangular fan-beam ramp kernel, including the column step."""
    n = torch.arange(-(geo.cols - 1), geo.cols, device=device, dtype=torch.float64)
    k = torch.zeros_like(n)
    odd = (n.abs() % 2) == 1
    k[odd] = -1 / (2 * math.pi**2 * torch.sin(n[odd] * geo.dgamma) ** 2)
    k[n == 0] = 1 / (8 * geo.dgamma**2)
    return (k * geo.dgamma).float()


def _filter(geo, views, kernel):
    gamma = (torch.arange(geo.cols, device=views.device) - geo.c0) * geo.dgamma
    x = views.float() * (geo.sid * torch.cos(gamma))
    return F.conv1d(x.reshape(-1, 1, geo.cols), kernel[None, None], padding=geo.cols - 1).reshape(views.shape)


class Conventions:
    """Per-manufacturer geometric convention (angle sign, quarter turns, column sign, row sign)."""

    def __init__(self, path):
        self.path = Path(path)
        self.table = json.loads(self.path.read_text()) if self.path.exists() else {}

    def __call__(self, geo):
        key = next((k for k in self.table if geo.manufacturer.startswith(k)), None)
        if key is None:
            raise KeyError(f"no calibrated convention for manufacturer {geo.manufacturer!r}; run `proj2rep calibrate`")
        return oriented(self.table[key], geo)


def oriented(conv, geo):
    """Feet-first convention -> the one for this case (head-first mirrors left-right and the table axis)."""
    sa, quarter, sc, sr = conv
    return [-sa, quarter, -sc, -sr] if geo.head_first else [sa, quarter, sc, sr]


@torch.no_grad()
def backproject(geo, data, zs, device, conv):
    """data: (V, rows, cols) line integrals -> HU volume (len(zs), SIZE, SIZE)."""
    sa, quarter, sc, sr = conv
    kernel = ramp(geo, device)
    x = torch.tensor(geo.x - geo.centre[0], device=device, dtype=torch.float32)
    y = torch.tensor(geo.y - geo.centre[1], device=device, dtype=torch.float32)
    yy, xx = torch.meshgrid(y, x, indexing="ij")
    out = torch.zeros(len(zs), len(y), len(x), device=device)
    for i, z in enumerate(zs):
        c = int(np.abs(geo.z - z).argmin())
        a = min(max(c - geo.n // 2, 0), max(len(geo.z) - geo.n, 0))
        pick = slice(a, a + geo.n)
        q = _filter(geo, torch.from_numpy(np.array(data[pick], dtype=np.float32)).to(device), kernel)
        beta = torch.tensor(sa * geo.angle[pick] + quarter * math.pi / 2, device=device, dtype=torch.float32)
        dz = torch.tensor(z - geo.z[pick], device=device, dtype=torch.float32)
        ux, uy = -torch.sin(beta)[:, None, None], torch.cos(beta)[:, None, None]
        along = geo.sid - (xx * ux + yy * uy)
        across = xx * uy - yy * ux
        dist2 = along**2 + across**2
        col = geo.c0 + sc * torch.atan2(across, along) / geo.dgamma
        row = geo.r0 + sr * dz[:, None, None] * geo.sdd / dist2.sqrt() / geo.drow
        grid = torch.stack([2 * col / (geo.cols - 1) - 1, 2 * row.clamp(0, geo.rows - 1) / (geo.rows - 1) - 1], -1)
        s = F.grid_sample(q[:, None], grid, mode="bilinear", padding_mode="zeros", align_corners=True)[:, 0]
        out[i] = (s / dist2).sum(0) * (2 * math.pi / len(beta))
    return 1000 * (out / geo.mu - 1)


def reconstruct(geo, data, zs, device, conv, chunk=8):
    """Back-projection averaged over the image slice thickness, in chunks of slices."""
    n = max(1, round(geo.thickness / 1.5))
    offsets = (np.arange(n) - (n - 1) / 2) * geo.thickness / n
    zs = np.asarray(zs)
    parts = []
    for i in range(0, len(zs), chunk):
        z = zs[i : i + chunk]
        parts.append(sum(backproject(geo, data, z + o, device, conv) for o in offsets) / n)
    return torch.cat(parts)


def reference(case, geo, zs):
    """Scanner image at the given slices, on the 256 x 256 grid, HU."""
    im = case.array("image_full")
    idx = [int(np.abs(geo.image_z - z).argmin()) for z in zs]
    x = torch.from_numpy(np.stack([im[i] for i in idx]).astype(np.float32)).clamp(-1024, 3000)
    return F.interpolate(x[:, None], (SIZE, SIZE), mode="area")[:, 0]


def calibrate(cohort, out, device, per_vendor=3):
    """Choose each manufacturer's convention by correlation with the scanner images."""
    result, report = {}, {}
    cases = cohort.cases(cohort.ids())
    makers = sorted({c.manufacturer.upper().split()[0] for c in cases})
    for maker in makers:
        mine = sorted((c for c in cases if c.manufacturer.upper().startswith(maker)), key=lambda c: Geometry(c).head_first)
        pick = mine[:per_vendor]  # feet-first cases first; head-first cases are scored through `oriented`
        if not pick:
            continue
        score = {}
        for case in pick:
            geo = Geometry(case)
            data = case.array("proj_full")
            v = geo.valid()
            zs = geo.image_z[v[[len(v) // 3, 2 * len(v) // 3]]]
            ref = reference(case, geo, zs).to(device)
            for conv in itertools.product((1, -1), (0, 1, 2, 3), (1, -1), (1, -1)):
                r = backproject(geo, data, zs, device, oriented(conv, geo)).clamp(-1024, 3000)
                c = torch.corrcoef(torch.stack([r.flatten(), ref.flatten()]))[0, 1].item()
                score[conv] = score.get(conv, 0) + c / len(pick)
        best = sorted(score, key=score.get, reverse=True)
        result[maker] = list(best[0])
        report[maker] = {"cases": [c.id for c in pick], "top": [[list(b), round(score[b], 4)] for b in best[:4]]}
        print(maker, report[maker], flush=True)
    Path(out).parent.mkdir(parents=True, exist_ok=True)
    Path(out).write_text(json.dumps(result, indent=1) + "\n")
    return report