Clinical Helical CT#
This example reconstructs measured projections of patients from a clinical helical CT scanner. The same script also reconstructs case C002 (chest, Siemens, flying focal spot, 11072 views). The data are the full-dose projections of LDCT-and-Projection-data (see Data sources). Each view is one detector readout in the DICOM-CT-PD format.
Case L213 (abdomen, GE): 7140 views, 888 × 64 cylindrical detector, 1 mm voxels, 30 CGLS iterations without regularization. Soft-tissue window.#
Geometry#
The scanner geometry goes to Projector as per-view tensors, without
rebinning to a circular orbit or a flat detector:
Source: the focal spot of each view, including the flying focal spot offsets in angle, radius and z.
Detector: a cylindrical surface centred on the nominal focal spot, given as a
detector_surfacecallback. Projection and backprojection use these pixel positions directly.Views: the views are split over the GPUs with
distributed=True;cgls()runs on the distributed operator.
The detector column of the central ray is 368.56 for C002 and 442.2 for L213, as 0-based stored columns. We estimated both values beforehand with gradient-based calibration of the column offset; that calibration is not part of this script.
def helical(args):
"""CGLS of measured full-dose helical projections with diffct's distributed Projector."""
from torch import distributed as dist
device = torch.device("cuda", int(os.environ["LOCAL_RANK"]))
torch.cuda.set_device(device)
dist.init_process_group("nccl", device_id=device)
rank = dist.get_rank()
case = Path(args.case)
m = dict(np.load(case / "meta.npz"))
proj = np.load(case / "proj.npy", mmap_mode="r")
scan = ClinicalScan(
projections=proj, angle=m["phi"], z=m["z"], radius=m["rho"], sdd=m["sdd"],
focal_angle_offset=m["dphi"], focal_z_offset=m["dz"], focal_radius_offset=m["drho"],
instance=m["instance"], detector_spacing=(float(m["du"][0]), float(m["dv"][0])),
central_element=(float(m["ce_col"][0]) - 1, float(m["ce_row"][0]) - 1),
detector_shape=str(m["detector_shape"]), ffs_mode=str(m["ffs"]),
water_attenuation=float(m["water_attenuation"]), manufacturer=str(m["manufacturer"]))
(n_cols, n_rows), z = proj.shape[1:], m["z"]
sdd, dv, rho = (float(m[k][0]) for k in ("sdd", "dv", "rho"))
margin = math.ceil(n_rows / 2 * dv * (rho + 250) / sdd + np.abs(m["dz"]).max())
mid = 0.5 * (z.min() + z.max())
depth = int(math.ceil(z.max() - z.min() + 2 * margin))
geometry = clinical_geometry(scan, z_center=mid, central_column=args.center)
operator = Projector(geometry.trajectory, (depth, 512, 512), geometry.detector_shape,
detector_spacing=geometry.detector_spacing, voxel_spacing=1.0,
detector_surface=geometry.detector_surface, distributed=True, partition="views")
b = torch.from_numpy(np.ascontiguousarray(proj[operator.view_slice])).to(device).div_(scan.water_attenuation)
keep, snapshots = set(args.keep), {}
def callback(iteration, residual, volume):
if rank == 0 and iteration in keep:
snapshots[iteration] = volume.detach().float().cpu()
print(f"it {iteration} residual {residual:.6g}", flush=True)
start = time.time()
result = cgls(operator, b, max(args.keep), callback=callback)
torch.cuda.synchronize()
seconds = time.time() - start
if rank == 0:
axial_z = args.axial_z or [mid - 60.0, mid, mid + 60.0]
axial_index = [int(round(zv - (mid - depth / 2))) for zv in axial_z]
arrays = {}
for it, volume in snapshots.items():
arrays[f"axial_{it}"] = np.stack([volume[k].numpy().astype(np.float16) for k in axial_index])
arrays[f"coronal_{it}"] = volume[:, 256].numpy().astype(np.float16)
arrays[f"sagittal_{it}"] = volume[:, :, 256].numpy().astype(np.float16)
history = np.array([float(x) for x in result.residual_history])
save(Path(args.out), f"helical_{case.name}", **arrays, iterations=np.array(sorted(snapshots)),
residual=history, axial_z=np.array(axial_z), seconds=seconds,
views=len(z), detector=np.array([n_cols, n_rows]), gpus=dist.get_world_size(),
manufacturer=str(m["manufacturer"]), depth=depth, z_mid=mid)
print("HELICAL_DONE", case.name, f"{seconds:.1f} s", flush=True)
dist.barrier()
dist.destroy_process_group()
Run it#
Download the full-dose projection and image series of a Chest or Liver case from The Cancer Imaging Archive.
Convert one case to arrays:
pip install 'diffct[dicom]' python docs/assets/gallery/ldct_prep.py <projection dir> <image dir> ldct/L213
Re-run preparation for older arrays: metadata now includes the detector shape and the scan’s water attenuation, rather than assuming GE’s value.
Reconstruct on 8 GPUs:
torchrun --nproc-per-node=8 docs/assets/gallery/compute.py helical \ --case ldct/L213 --center 442.2 --axial-z -418 -364 -307 --out arrays
Library API (CPU or GPU)#
The reader accepts a directory or a list of projection files. Views are sorted by InstanceNumber; sparse gaps are allowed, duplicates and changing detector geometry are rejected. It reads already-corrected CT-PD data and applies each file’s rescale slope/intercept without taking another logarithm.
import torch
from diffct import read_dicom_ct_pd, clinical_geometry, Projector, cgls
scan = read_dicom_ct_pd("projections")
geometry = clinical_geometry(scan) # CPU float32, FFS enabled
operator = Projector(
geometry.trajectory, (32, 64, 64), geometry.detector_shape,
detector_spacing=geometry.detector_spacing,
detector_surface=geometry.detector_surface,
voxel_spacing=4.0, backend="torch")
measurements = torch.from_numpy(scan.projections) / scan.water_attenuation
result = cgls(operator, measurements, iterations=6)
Size the volume and view/detector subset for available memory and CPU time.
The explicit division above normalizes the reconstruction to water units, in
which water is 1 and HU is 1000 * (reconstruction - 1). Without that
division the reconstruction is absolute attenuation and needs
attenuation_to_hu(reconstruction, scan.water_attenuation) instead.
ClinicalScan is a frozen dataclass (its NumPy arrays remain mutable).
Geometry vectors are float64 in mm/radians; projections are float32 with shape
(views, channels, rows). ClinicalGeometry contains the four named
Projector arguments shown above. z_center defaults to the midpoint of the
nominal source-z range. central_column overrides the zero-based header
column for calibrated data; flying_focal_spot=False removes all source
offsets. device and dtype control the returned trajectory tensors.
The detector frame remains nominal while the source receives all three
offsets, even if a mode named FFSZ also has radial/angular offsets. Stored
rows run opposite to v. Only cylindrical detectors are currently implemented;
other shapes raise NotImplementedError. Analytical FBP/FDK still require flat
data, and this API does not relax helical FDK’s CUDA/constant-radius/monotone-z
restrictions. Patient-coordinate registration of vendor images remains a
separate step. Water calibration comes from CT-PD tag (7041,1001), e.g.
0.0192/mm for C002 versus 0.0186/mm for L213.