Cone Beam FDK Reconstruction

This example demonstrates 3D cone beam FDK (Feldkamp-Davis-Kress) reconstruction using the ConeProjectorFunction and ConeBackprojectorFunction from diffct_mlx.engine.

Overview

The FDK algorithm is the standard analytical method for 3D cone beam CT reconstruction. This example shows how to:

  • Configure 3D cone beam geometry with 2D detector array

  • Generate cone beam projections from a 3D phantom

  • Apply cosine weighting and ramp filtering for FDK reconstruction

  • Perform 3D backprojection to reconstruct the volume

Mathematical Background

Cone Beam Geometry

Cone beam CT extends fan beam to 3D using a point X-ray source and 2D detector array. Key parameters:

  • SDD \(D_s\): Source-to-Detector Distance (distance from X-ray source to detector plane)

  • SID \(D_{sid}\): Source-to-Isocenter Distance (distance from X-ray source to rotation center)

  • Detector coordinates \((u, v)\): Horizontal and vertical detector positions

  • Cone angles \((\alpha, \beta)\): Horizontal and vertical beam divergence

3D Forward Projection

The cone beam projection at source angle \(\phi\) and detector position \((u, v)\) is:

\[p(\phi, u, v) = \int_0^{\infty} f\left(\vec{r}_s(\phi) + t \cdot \vec{d}(\phi, u, v)\right) dt\]

where \(\vec{r}_s(\phi)\) is the source position and \(\vec{d}(\phi, u, v)\) is the ray direction vector.

FDK Algorithm

The Feldkamp-Davis-Kress algorithm performs approximate 3D reconstruction in three steps:

  1. Cosine Weighting: Compensate for ray divergence and \(1/r^2\) intensity falloff:

    \[p_w(\phi, u, v) = p(\phi, u, v) \cdot \frac{D_s}{\sqrt{D_s^2 + u^2 + v^2}}\]
  2. Row-wise Ramp Filtering: Apply 1D ramp filter along detector rows (u-direction):

    \[p_f(\phi, u, v) = \mathcal{F}_u^{-1}\{|\omega_u| \cdot \mathcal{F}_u\{p_w(\phi, u, v)\}\}\]

    Each detector row is filtered independently.

  3. 3D Cone Beam Backprojection: Reconstruct volume using weighted backprojection:

    \[f(x,y,z) = \int_0^{2\pi} \frac{D_s^2}{(D_s + x\cos\phi + y\sin\phi)^2} p_f(\phi, u_{xyz}, v_{xyz}) d\phi\]

    where detector coordinates \((u_{xyz}, v_{xyz})\) for voxel \((x,y,z)\) are:

    \[u_{xyz} = D_s \frac{-x\sin\phi + y\cos\phi}{D_s + x\cos\phi + y\sin\phi}\]
    \[v_{xyz} = D_s \frac{z}{D_s + x\cos\phi + y\sin\phi}\]

Implementation Steps

  1. 3D Phantom Generation: Create 3D Shepp-Logan phantom with 10 ellipsoids

  2. Cone Beam Projection: Generate 2D projections using ConeProjectorFunction with geometry from helpers such as diffct_mlx.engine.circular_trajectory_3d

  3. Cosine Weighting: Apply distance-dependent weights

  4. Row-wise Filtering: Apply ramp filter to each detector row

  5. 3D Backprojection: Reconstruct volume using ConeBackprojectorFunction

  6. Normalization: Scale by \(\frac{\pi}{N_{\text{angles}}}\) factor

3D Shepp-Logan Phantom

The 3D phantom extends the 2D version with 10 ellipsoids representing anatomical structures:

  • Outer skull: Large ellipsoid encompassing the head

  • Brain tissue: Medium ellipsoids for different brain regions

  • Ventricles: Small ellipsoids representing fluid-filled cavities

  • Lesions: High-contrast features for reconstruction assessment

Each ellipsoid is defined by center position \((x_0, y_0, z_0)\), semi-axes \((a, b, c)\), rotation angles, and attenuation coefficient.

FDK Approximations and Limitations

The FDK algorithm makes several approximations:

  • Circular orbit: Assumes circular source trajectory

  • Row-wise filtering: Ramp filtering only along detector rows

  • Small cone angle: Most accurate for limited cone angles

These approximations introduce cone beam artifacts for large cone angles, but FDK remains widely used due to computational efficiency.

3D Cone Beam FDK Example
  1"""Circular-orbit cone-beam FDK reconstruction example.
  2
  3Pipeline:
  4
  5    ConeProjectorFunction.apply    # forward projection (sinogram)
  6    parker_weights (optional)      # short-scan redundancy weighting
  7    cone_cosine_weights            # 1/r^2 cosine pre-weight
  8    ramp_filter_1d                 # row-wise ramp filter along u
  9    angular_integration_weights    # per-view integration weights
 10    cone_weighted_backproject      # voxel-driven FDK gather
 11
 12Every geometry and reconstruction parameter below is annotated with
 13its meaning, units, and available options. This is the dev-branch
 14arbitrary-trajectory version: geometry comes from
 15``circular_trajectory_3d`` as per-view ``(src_pos, det_center,
 16det_u_vec, det_v_vec)`` arrays.
 17"""
 18
 19import math
 20import sys
 21from pathlib import Path
 22
 23import matplotlib.pyplot as plt
 24import numpy as np
 25import torch
 26import torch.nn.functional as F
 27
 28ROOT_DIR = Path(__file__).resolve().parents[2]
 29if str(ROOT_DIR) not in sys.path:
 30    sys.path.insert(0, str(ROOT_DIR))
 31
 32from diffct_mlx.engine import (
 33    ConeProjectorFunction,
 34    angular_integration_weights,
 35    circular_trajectory_3d,
 36    cone_cosine_weights,
 37    cone_weighted_backproject,
 38    parker_weights,
 39    ramp_filter_1d,
 40)
 41
 42
 43def shepp_logan_3d(shape):
 44    """Build a 3D Shepp-Logan phantom clipped to ``[0, 1]``."""
 45    Nz, Ny, Nx = shape
 46    zz, yy, xx = np.mgrid[:Nz, :Ny, :Nx].astype(np.float32)
 47    xx = (xx - Nx * 0.5) / (Nx * 0.5)
 48    yy = (yy - Ny * 0.5) / (Ny * 0.5)
 49    zz = (zz - Nz * 0.5) / (Nz * 0.5)
 50
 51    el_params = np.array(
 52        [
 53            [0, 0, 0, 0.69, 0.92, 0.81, 0, 0, 0, 1.0],
 54            [0, -0.0184, 0, 0.6624, 0.874, 0.78, 0, 0, 0, -0.8],
 55            [0.22, 0, 0, 0.11, 0.31, 0.22, -np.pi / 10.0, 0, 0, -0.2],
 56            [-0.22, 0, 0, 0.16, 0.41, 0.28, np.pi / 10.0, 0, 0, -0.2],
 57            [0, 0.35, -0.15, 0.21, 0.25, 0.41, 0, 0, 0, 0.1],
 58            [0, 0.10, 0.25, 0.046, 0.046, 0.05, 0, 0, 0, 0.1],
 59            [0, -0.10, 0.25, 0.046, 0.046, 0.05, 0, 0, 0, 0.1],
 60            [-0.08, -0.605, 0, 0.046, 0.023, 0.05, 0, 0, 0, 0.1],
 61            [0, -0.605, 0, 0.023, 0.023, 0.02, 0, 0, 0, 0.1],
 62            [0.06, -0.605, 0, 0.023, 0.046, 0.02, 0, 0, 0, 0.1],
 63        ],
 64        dtype=np.float32,
 65    )
 66    x_pos = el_params[:, 0][:, None, None, None]
 67    y_pos = el_params[:, 1][:, None, None, None]
 68    z_pos = el_params[:, 2][:, None, None, None]
 69    a_axis = el_params[:, 3][:, None, None, None]
 70    b_axis = el_params[:, 4][:, None, None, None]
 71    c_axis = el_params[:, 5][:, None, None, None]
 72    phi = el_params[:, 6][:, None, None, None]
 73    val = el_params[:, 9][:, None, None, None]
 74
 75    xc = xx[None, ...] - x_pos
 76    yc = yy[None, ...] - y_pos
 77    zc = zz[None, ...] - z_pos
 78    c = np.cos(phi)
 79    s = np.sin(phi)
 80    xp = c * xc - s * yc
 81    yp = s * xc + c * yc
 82    zp = zc
 83    mask = (
 84        (xp ** 2) / (a_axis ** 2)
 85        + (yp ** 2) / (b_axis ** 2)
 86        + (zp ** 2) / (c_axis ** 2)
 87        <= 1.0
 88    )
 89    phantom = np.sum(mask * val, axis=0)
 90    return np.clip(phantom, 0.0, 1.0).astype(np.float32)
 91
 92
 93def main():
 94    # ------------------------------------------------------------------
 95    # 1. Volume geometry
 96    # ------------------------------------------------------------------
 97    # ``Nx / Ny / Nz`` are the number of voxels along each axis. The
 98    # phantom tensor has shape ``(Nz, Ny, Nx) = (D, H, W)``. Making the
 99    # volume larger increases reconstruction quality but also memory
100    # and runtime which scale roughly ``O(N^3)``.
101    Nx, Ny, Nz = 128, 128, 128
102    phantom_cpu = shepp_logan_3d((Nz, Ny, Nx))
103
104    # ``voxel_spacing`` is the physical size of one voxel in the same
105    # length unit used by ``du``, ``dv``, ``sdd`` and ``sid`` below.
106    # All geometry math inside the CUDA kernels is done in voxel units,
107    # and physical spacings are divided by ``voxel_spacing`` internally,
108    # so only the *ratios* matter.
109    voxel_spacing = 1.0
110
111    # ------------------------------------------------------------------
112    # 2. Detector geometry
113    # ------------------------------------------------------------------
114    # (Listed before the trajectory so the short-scan coverage below can
115    # use the detector fan angle to compute ``pi + 2*gamma_max``.)
116    #
117    # ``det_u`` / ``det_v`` are the number of detector cells along the
118    # u (in-plane / horizontal) and v (axial / vertical) directions.
119    # ``du`` / ``dv`` are their physical spacings.
120    det_u, det_v = 256, 256
121    du, dv = 1.0, 1.0
122
123    # ``sdd`` = source-to-detector distance, ``sid`` = source-to-
124    # isocenter distance. Their ratio is the geometric magnification
125    # at the detector. Typical clinical cone-beam systems have
126    # magnifications around 1.3 - 2.0; here we pick 1.5.
127    sdd = 900.0
128    sid = 600.0
129
130    # ------------------------------------------------------------------
131    # 3. Source trajectory (circular orbit)
132    # ------------------------------------------------------------------
133    # ``apply_parker`` selects between two supported trajectories:
134    #
135    #   False -> full 2*pi circular scan. Each ray is sampled twice
136    #            (once going one way, once the opposite), so the FDK
137    #            formula carries a 1/2 redundancy factor which is
138    #            absorbed by ``redundant_full_scan=True`` inside the
139    #            angular integration weights.
140    #
141    #   True  -> minimal short scan of length ``pi + 2*gamma_max``
142    #            where ``gamma_max`` is the maximum fan angle. Every
143    #            ray is sampled at least once, some rays twice; the
144    #            Parker window smoothly tapers the duplicate regions
145    #            so each ray's total contribution integrates to pi.
146    #
147    # Short scans are common on clinical C-arm and cone-beam systems
148    # where a full 2*pi rotation is mechanically impossible.
149    apply_parker = False
150
151    if apply_parker:
152        u_max = (det_u * 0.5) * du  # dev convention
153        gamma_max = math.atan(u_max / sdd)
154        scan_range = math.pi + 2.0 * gamma_max
155    else:
156        scan_range = 2.0 * math.pi
157
158    num_views = 360
159
160    # ------------------------------------------------------------------
161    # 4. Move everything to CUDA and build the trajectory arrays
162    # ------------------------------------------------------------------
163    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
164    phantom_torch = torch.tensor(
165        phantom_cpu, device=device, dtype=torch.float32
166    ).contiguous()
167
168    src_pos, det_center, det_u_vec, det_v_vec = circular_trajectory_3d(
169        num_views,
170        sid=sid,
171        sdd=sdd,
172        start_angle=0.0,
173        end_angle=scan_range,
174        device=device,
175    )
176    angles_torch = torch.linspace(
177        0.0, scan_range, num_views + 1, device=device, dtype=torch.float32
178    )[:-1]
179
180    # ------------------------------------------------------------------
181    # 5. Forward projection: volume -> sinogram
182    # ------------------------------------------------------------------
183    # ``ConeProjectorFunction`` is the differentiable Siddon-based cone-
184    # beam forward projector. It returns a ``(num_views, det_u, det_v)``
185    # sinogram. The call is autograd-aware so the same function can be
186    # used inside an iterative reconstruction loop (see
187    # ``iterative_reco_cone.py``).
188    sinogram = ConeProjectorFunction.apply(
189        phantom_torch,
190        src_pos,
191        det_center,
192        det_u_vec,
193        det_v_vec,
194        det_u,
195        det_v,
196        du,
197        dv,
198        voxel_spacing,
199    )
200
201    # ==================================================================
202    # 6. FDK analytical reconstruction
203    # ==================================================================
204
205    # --- 6.1  Optional Parker redundancy weighting -------------------
206    # ``parker_weights`` returns a ``(num_views, det_u)`` tensor that
207    # tapers rays in the redundantly-sampled regions of a short scan.
208    # For a full 2*pi scan it returns all ones (no-op).
209    if apply_parker:
210        parker = parker_weights(
211            angles_torch, det_u, du, sdd
212        )
213        sinogram = sinogram * parker.unsqueeze(-1)
214
215    # --- 6.2  Cosine pre-weight --------------------------------------
216    # Multiplies each detector pixel by ``sdd / sqrt(sdd^2 + u^2 + v^2)``,
217    # i.e. the cosine of the cone angle. Compensates for the extra path
218    # length that off-center rays traverse relative to the principal
219    # ray. The ``unsqueeze(0)`` broadcasts over the view axis.
220    weights = cone_cosine_weights(
221        det_u, det_v, du, dv, sdd,
222        device=device, dtype=phantom_torch.dtype,
223    ).unsqueeze(0)
224    sino_weighted = sinogram * weights
225
226    # --- 6.3  1D ramp filter along the detector-u direction ----------
227    # ``ramp_filter_1d`` is a generic building block. For high-quality
228    # FDK reconstruction the recommended arguments are:
229    #
230    #   dim=1                  u-axis of the ``(views, u, v)`` sinogram
231    #   sample_spacing=du      physical detector-u spacing (amplitude-
232    #                          calibrated output across detector pitches)
233    #   pad_factor=2           zero-pad the signal to suppress
234    #                          circular-convolution wrap-around
235    #   window="hann"          smoothly suppresses high-frequency noise
236    #
237    # Other ``window`` options: ``None`` / ``"ram-lak"`` (sharp Ram-Lak,
238    # no smoothing), ``"hamming"``, ``"cosine"``, ``"shepp-logan"``.
239    sinogram_filt = ramp_filter_1d(
240        sino_weighted,
241        dim=1,
242        sample_spacing=du,
243        pad_factor=2,
244        window="hann",
245    ).contiguous()
246
247    # --- 6.4  Per-view angular integration weights -------------------
248    # For a full 2*pi scan each view contributes ``pi / num_views`` to
249    # the FDK integral (with the ``1/2`` redundancy factor absorbed by
250    # ``redundant_full_scan=True``). For a Parker short scan the
251    # redundancy is already baked into the Parker window above, so we
252    # use a plain trapezoidal rule with ``redundant_full_scan=False``.
253    d_beta = angular_integration_weights(
254        angles_torch, redundant_full_scan=(not apply_parker)
255    ).view(-1, 1, 1)
256    sinogram_filt = sinogram_filt * d_beta
257
258    # --- 6.5  Voxel-driven FDK backprojection -------------------------
259    # ``cone_weighted_backproject`` dispatches to a dedicated voxel-
260    # driven gather kernel (separate from the Siddon-based autograd
261    # cone backprojector). For every voxel it computes the detector
262    # ``(u, v)`` the voxel projects to, bilinearly samples the filtered
263    # sinogram, and accumulates ``(sid_n / U_n)^2 * sample`` over all
264    # views, where ``U_n`` is the per-view source-to-voxel distance
265    # along the detector normal and ``sid_n`` is its iso analogue. For
266    # a circular orbit both reduce to the classical scalars. The final
267    # ``sdd / (2*pi*sid)`` analytical constant is applied inside the
268    # wrapper.
269    reconstruction_raw = cone_weighted_backproject(
270        sinogram_filt,
271        src_pos,
272        det_center,
273        det_u_vec,
274        det_v_vec,
275        Nz,
276        Ny,
277        Nx,
278        du,
279        dv,
280        voxel_spacing=voxel_spacing,
281    )
282
283    # Optional non-negativity clamp. FDK can produce small negative
284    # values near sharp edges because the ramp filter has negative
285    # lobes in the spatial domain; for visualization we clamp with ReLU.
286    reconstruction = F.relu(reconstruction_raw)
287
288    # ------------------------------------------------------------------
289    # 7. Quantitative summary
290    # ------------------------------------------------------------------
291    raw_loss = torch.mean((reconstruction_raw - phantom_torch) ** 2)
292    clamped_loss = torch.mean((reconstruction - phantom_torch) ** 2)
293
294    scan_label = "Parker short scan" if apply_parker else "full 2*pi scan"
295    print(f"Cone Beam FDK example ({scan_label}):")
296    print(f"  Raw MSE:             {raw_loss.item():.6f}")
297    print(f"  Clamped MSE:         {clamped_loss.item():.6f}")
298    print(f"  Reconstruction shape: {tuple(reconstruction.shape)}")
299    print(
300        "  Raw reco data range:  "
301        f"[{reconstruction_raw.min().item():.4f}, {reconstruction_raw.max().item():.4f}]"
302    )
303    print(
304        "  Clamped reco range:   "
305        f"[{reconstruction.min().item():.4f}, {reconstruction.max().item():.4f}]"
306    )
307    print(
308        "  Phantom data range:   "
309        f"[{float(phantom_cpu.min()):.4f}, {float(phantom_cpu.max()):.4f}]"
310    )
311
312    # ------------------------------------------------------------------
313    # 8. Visualization
314    # ------------------------------------------------------------------
315    reconstruction_cpu = reconstruction.detach().cpu().numpy()
316    sinogram_cpu = sinogram.detach().cpu().numpy()
317    mid_slice = Nz // 2
318
319    plt.figure(figsize=(12, 4))
320    plt.subplot(1, 3, 1)
321    plt.imshow(phantom_cpu[mid_slice, :, :], cmap="gray")
322    plt.title("Phantom mid-slice")
323    plt.axis("off")
324    plt.subplot(1, 3, 2)
325    plt.imshow(sinogram_cpu[num_views // 2].T, cmap="gray", origin="lower")
326    plt.title("Sinogram mid-view")
327    plt.axis("off")
328    plt.subplot(1, 3, 3)
329    plt.imshow(reconstruction_cpu[mid_slice, :, :], cmap="gray")
330    plt.title("Recon mid-slice")
331    plt.axis("off")
332    plt.tight_layout()
333    plt.show()
334
335
336if __name__ == "__main__":
337    main()