Cone Beam Iterative Reconstruction

This example demonstrates gradient-based iterative reconstruction for 3D cone beam CT using the differentiable ConeProjectorFunction from diffct_mlx.engine.

Overview

3D cone beam iterative reconstruction extends optimization methods to full volumetric reconstruction. This example shows how to:

  • Formulate 3D cone beam CT reconstruction as a large-scale optimization problem

  • Handle the computational complexity of 3D forward and backward projections

  • Apply memory-efficient optimization strategies for volumetric data

  • Monitor convergence in high-dimensional parameter space

Mathematical Background

3D Cone Beam Iterative Formulation

The 3D reconstruction problem is formulated as:

\[\hat{f} = \arg\min_f \|A_{\text{cone}}(f) - p\|_2^2 + \lambda R(f)\]

where: - \(f(x,y,z)\) is the unknown 3D volume - \(A_{\text{cone}}\) is the cone beam forward projection operator - \(p(\phi, u, v)\) is the measured 2D projection data - \(R(f)\) is an optional 3D regularization term

3D Forward Projection

The cone beam forward projection integrates along rays through the 3D volume:

\[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.

3D Gradient Computation

The gradient of the 3D loss function uses the cone beam backprojection operator:

\[\frac{\partial L}{\partial f} = 2A_{\text{cone}}^T(A_{\text{cone}}(f) - p_{\text{measured}})\]

where \(A_{\text{cone}}^T\) is the 3D cone beam backprojection operator (adjoint).

Computational Complexity

3D reconstruction presents significant computational challenges:

  • Memory Requirements: \(O(N^3)\) for volume storage vs \(O(N^2)\) for 2D images

  • Projection Data: \(O(N_{\phi} \times N_u \times N_v)\) 2D projections

  • Forward/Backward Operations: \(O(N^3 \times N_{\phi})\) computational complexity

  • Gradient Storage: Additional memory for automatic differentiation

Implementation Steps

  1. 3D Problem Setup: Define parameterized 3D volume as learnable tensor

  2. Cone Beam Forward Model: Generate source and detector trajectories (e.g., with diffct_mlx.engine.circular_trajectory_3d or spiral_trajectory_3d) and use ConeProjectorFunction for 2D projection prediction

  3. Loss Computation: Calculate L2 distance between predicted and measured projections

  4. 3D Gradient Computation: Use automatic differentiation through cone beam operators

  5. Memory-Efficient Optimization: Apply strategies to handle large 3D parameter space

  6. Convergence Monitoring: Track loss and 3D reconstruction quality

Model Architecture

The 3D reconstruction model consists of:

  • Parameterized Volume: Learnable 3D tensor representing the unknown volume

  • Cone Beam Forward Model: ConeProjectorFunction with 3D geometry parameters

  • Loss Function: Mean squared error between predicted and measured 2D projections

3D Regularization Options

Common 3D regularization terms:

  1. 3D Total Variation: \(R_{\text{TV}}(f) = \sum_{x,y,z} \|\nabla f(x,y,z)\|_2\)

  2. 3D Smoothness: \(R_{\text{smooth}}(f) = \sum_{x,y,z} \|\nabla f(x,y,z)\|_2^2\)

  3. L1 Sparsity: \(R_{\text{L1}}(f) = \sum_{x,y,z} |f(x,y,z)|\)

Memory Management Strategies

3D reconstruction requires careful memory management:

  • Gradient Checkpointing: Trade computation for memory in backpropagation

  • Mixed Precision: Use float16 when possible to reduce memory usage

  • Batch Processing: Process volume slices when memory is extremely limited

  • Efficient Data Layout: Optimize tensor storage and access patterns

Convergence Characteristics

3D cone beam reconstruction typically exhibits:

  1. Initial Convergence (0-100 iterations): Rapid loss decrease, basic 3D structure emerges

  2. Detail Refinement (100-500 iterations): Fine 3D features develop progressively

  3. Final Convergence (500+ iterations): Slow improvement, potential overfitting risk

Challenges in 3D Reconstruction

  • Cone Beam Artifacts: Increased artifacts for large cone angles in 3D

  • Incomplete Sampling: Missing data in certain regions of 3D Fourier space

  • Computational Cost: Orders of magnitude higher than 2D reconstruction

  • Memory Limitations: Large volumes may exceed available GPU memory

  • Convergence Complexity: Higher-dimensional optimization landscape

Applications

3D cone beam iterative reconstruction is essential for:

  • Medical CBCT: Dental, orthopedic, and interventional imaging

  • Industrial CT: Non-destructive testing and quality control

  • Micro-CT: High-resolution imaging of small specimens and materials

  • Security Screening: Advanced baggage and cargo inspection systems

Code Example

3D Cone Beam Iterative Example
  1import math
  2import sys
  3from pathlib import Path
  4
  5import torch
  6import numpy as np
  7import matplotlib.pyplot as plt
  8import torch.nn as nn
  9import torch.optim as optim
 10
 11ROOT_DIR = Path(__file__).resolve().parents[2]
 12if str(ROOT_DIR) not in sys.path:
 13    sys.path.insert(0, str(ROOT_DIR))
 14
 15from diffct_mlx.engine import ConeProjectorFunction, circular_trajectory_3d
 16
 17def shepp_logan_3d(shape):
 18    zz, yy, xx = np.mgrid[:shape[0], :shape[1], :shape[2]]
 19    xx = (xx - (shape[2] - 1) / 2) / ((shape[2] - 1) / 2)
 20    yy = (yy - (shape[1] - 1) / 2) / ((shape[1] - 1) / 2)
 21    zz = (zz - (shape[0] - 1) / 2) / ((shape[0] - 1) / 2)
 22    el_params = np.array([
 23        [0, 0, 0, 0.69, 0.92, 0.81, 0, 0, 0, 1],
 24        [0, -0.0184, 0, 0.6624, 0.874, 0.78, 0, 0, 0, -0.8],
 25        [0.22, 0, 0, 0.11, 0.31, 0.22, -np.pi/10.0, 0, 0, -0.2],
 26        [-0.22, 0, 0, 0.16, 0.41, 0.28, np.pi/10.0, 0, 0, -0.2],
 27        [0, 0.35, -0.15, 0.21, 0.25, 0.41, 0, 0, 0, 0.1],
 28        [0, 0.1, 0.25, 0.046, 0.046, 0.05, 0, 0, 0, 0.1],
 29        [0, -0.1, 0.25, 0.046, 0.046, 0.05, 0, 0, 0, 0.1],
 30        [-0.08, -0.605, 0, 0.046, 0.023, 0.05, 0, 0, 0, 0.1],
 31        [0, -0.605, 0, 0.023, 0.023, 0.02, 0, 0, 0, 0.1],
 32        [0.06, -0.605, 0, 0.023, 0.046, 0.02, 0, 0, 0, 0.1],
 33    ], dtype=np.float32)
 34
 35    # Extract parameters for vectorization
 36    x_pos = el_params[:, 0][:, None, None, None]
 37    y_pos = el_params[:, 1][:, None, None, None]
 38    z_pos = el_params[:, 2][:, None, None, None]
 39    a_axis = el_params[:, 3][:, None, None, None]
 40    b_axis = el_params[:, 4][:, None, None, None]
 41    c_axis = el_params[:, 5][:, None, None, None]
 42    phi = el_params[:, 6][:, None, None, None]
 43    val = el_params[:, 9][:, None, None, None]
 44
 45    # Broadcast grid to ellipsoid axis
 46    xc = xx[None, ...] - x_pos
 47    yc = yy[None, ...] - y_pos
 48    zc = zz[None, ...] - z_pos
 49
 50    c = np.cos(phi)
 51    s = np.sin(phi)
 52
 53    # Only rotation around z, so can vectorize:
 54    xp = c * xc - s * yc
 55    yp = s * xc + c * yc
 56    zp = zc
 57
 58    mask = (
 59        (xp ** 2) / (a_axis ** 2)
 60        + (yp ** 2) / (b_axis ** 2)
 61        + (zp ** 2) / (c_axis ** 2)
 62        <= 1.0
 63    )
 64
 65    # Use broadcasting to sum all ellipsoid contributions
 66    shepp_logan = np.sum(mask * val, axis=0)
 67    shepp_logan = np.clip(shepp_logan, 0, 1)
 68    return shepp_logan
 69
 70class IterativeRecoModel(nn.Module):
 71    def __init__(self, volume_shape, src_pos, det_center, det_u_vec, det_v_vec, det_u, det_v, du, dv, voxel_spacing):
 72        super().__init__()
 73        self.reco = nn.Parameter(torch.zeros(volume_shape))
 74        self.src_pos = src_pos
 75        self.det_center = det_center
 76        self.det_u_vec = det_u_vec
 77        self.det_v_vec = det_v_vec
 78        self.det_u = det_u
 79        self.det_v = det_v
 80        self.du = du
 81        self.dv = dv
 82        self.voxel_spacing = voxel_spacing
 83
 84    def forward(self, x):
 85        updated_reco = x + self.reco
 86        current_sino = ConeProjectorFunction.apply(updated_reco,
 87                                                   self.src_pos, self.det_center,
 88                                                   self.det_u_vec, self.det_v_vec,
 89                                                   self.det_u, self.det_v,
 90                                                   self.du, self.dv, self.voxel_spacing)
 91        return current_sino, updated_reco
 92
 93class Pipeline:
 94    def __init__(self, lr, volume_shape, src_pos, det_center, det_u_vec, det_v_vec,
 95                 det_u, det_v, du, dv, voxel_spacing,
 96                 device, epoches=1000):
 97
 98        self.epoches = epoches
 99        self.model = IterativeRecoModel(volume_shape, src_pos, det_center, det_u_vec, det_v_vec,
100                                        det_u, det_v, du, dv, voxel_spacing).to(device)
101
102        self.optimizer = optim.AdamW(list(self.model.parameters()), lr=lr)
103        self.loss = nn.MSELoss()
104
105    def train(self, input, label):
106        loss_values = []
107        for epoch in range(self.epoches):
108            self.optimizer.zero_grad()
109            predictions, current_reco = self.model(input)
110            loss_value = self.loss(predictions, label)
111            loss_value.backward()
112            self.optimizer.step()
113            with torch.no_grad():
114                self.model.reco.clamp_(min=0.0)
115            loss_values.append(loss_value.item())
116
117            if epoch % 10 == 0:
118                print(f"Epoch {epoch}, Loss: {loss_value.item()}")
119
120        return loss_values, self.model
121
122def main():
123    Nx, Ny, Nz = 64, 64, 64
124    phantom_cpu = shepp_logan_3d((Nz, Ny, Nx))
125
126    num_views = 180
127    det_u, det_v = 128, 128
128    du, dv = 1.0, 1.0
129    voxel_spacing = 1.0
130    sdd = 600.0
131    sid = 400.0
132
133    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
134    phantom_torch = torch.tensor(phantom_cpu, device=device, dtype=torch.float32).contiguous()
135
136    # Generate circular trajectory geometry
137    src_pos, det_center, det_u_vec, det_v_vec = circular_trajectory_3d(
138        n_views=num_views, sid=sid, sdd=sdd, device=device
139    )
140
141    # Generate the "real" sinogram
142    real_sinogram = ConeProjectorFunction.apply(phantom_torch, src_pos, det_center,
143                                               det_u_vec, det_v_vec,
144                                               det_u, det_v, du, dv, voxel_spacing)
145
146    pipeline_instance = Pipeline(lr=1e-1,
147                                 volume_shape=(Nz, Ny, Nx),
148                                 src_pos=src_pos,
149                                 det_center=det_center,
150                                 det_u_vec=det_u_vec,
151                                 det_v_vec=det_v_vec,
152                                 det_u=det_u, det_v=det_v,
153                                 du=du, dv=dv, voxel_spacing=voxel_spacing,
154                                 device=device, epoches=1000)
155    
156    ini_guess = torch.zeros_like(phantom_torch)
157    
158    loss_values, trained_model = pipeline_instance.train(ini_guess, real_sinogram)
159    
160    reco = trained_model(ini_guess)[1].squeeze().cpu().detach().numpy()
161
162    plt.figure()
163    plt.plot(loss_values)
164    plt.title("Loss Curve")
165    plt.xlabel("Epoch")
166    plt.ylabel("Loss")
167    plt.show()
168
169    mid_slice = Nz // 2
170    plt.figure(figsize=(12, 6))
171    plt.subplot(1, 2, 1)
172    plt.imshow(phantom_cpu[mid_slice, :, :], cmap="gray")
173    plt.title("Original Phantom Mid-Slice")
174    plt.axis("off")
175
176    plt.subplot(1, 2, 2)
177    plt.imshow(reco[mid_slice, :, :], cmap="gray")
178    plt.title("Reconstructed Mid-Slice")
179    plt.axis("off")
180    plt.show()
181
182if __name__ == "__main__":
183    main()