Proj2Rep-CTFM / proj2rep /geometry.py
markjiang1's picture
Optimized release: verified metadata, download instructions and package structure
76eb7b3
Raw History Blame Contribute Delete
8.35 kB
"""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