Parallel Beam Iterative Reconstruction

This example demonstrates 2D parallel beam iterative reconstruction using the differentiable ParallelProjectorFunction and ParallelBackprojectorFunction from diffct_mlx.engine.

Overview

Parallel beam iterative reconstruction solves the CT inverse problem through optimization, offering advantages over analytical methods like FBP. This example shows how to:

  • Formulate parallel beam CT reconstruction as an optimization problem

  • Use automatic differentiation for gradient computation

  • Apply gradient-based optimization with parallel beam operators

  • Monitor convergence and reconstruction quality

Mathematical Background

Parallel Beam Iterative Formulation

The parallel beam reconstruction problem is formulated as:

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

where: - \(f\) is the unknown 2D image - \(A_{\text{parallel}}\) is the parallel beam forward projection operator (Radon transform) - \(p\) is the measured sinogram data - \(R(f)\) is an optional regularization term - \(\lambda\) is the regularization parameter

Gradient-Based Optimization

The gradient of the data fidelity term is computed using the adjoint operator:

\[\nabla_f \|A_{\text{parallel}}(f) - p\|_2^2 = 2A_{\text{parallel}}^T(A_{\text{parallel}}(f) - p)\]

where \(A_{\text{parallel}}^T\) is the parallel beam backprojection operator (adjoint of the forward projector).

Automatic Differentiation

PyTorch’s automatic differentiation computes gradients through the differentiable operators:

\[\frac{\partial L}{\partial f} = \frac{\partial}{\partial f} \|A_{\text{parallel}}(f) - p_{\text{measured}}\|_2^2\]

This enables seamless integration with advanced optimizers like Adam.

Adam Optimizer

The Adam optimizer adapts learning rates using gradient statistics:

\[f^{(k+1)} = f^{(k)} - \alpha \cdot \frac{m^{(k)}}{1-\beta_1^k} \cdot \frac{1}{\sqrt{v^{(k)}/(1-\beta_2^k)} + \epsilon}\]

where \(m^{(k)}\) and \(v^{(k)}\) are biased first and second moment estimates.

Implementation Steps

  1. Problem Setup: Define parameterized 2D image as learnable tensor

  2. Forward Model: Generate ray geometry (e.g., with diffct_mlx.engine.circular_trajectory_2d_parallel) and compute the predicted sinogram using ParallelProjectorFunction

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

  4. Gradient Computation: Use automatic differentiation for gradient calculation

  5. Parameter Update: Apply Adam optimizer for iterative improvement

  6. Convergence Monitoring: Track loss and reconstruction quality

Model Architecture

The reconstruction model consists of:

  • Parameterized Image: Learnable 2D tensor representing the unknown image

  • Forward Projection: ParallelProjectorFunction for sinogram prediction

  • Loss Function: Mean squared error between predicted and measured sinograms

Advantages of Iterative Methods

  • Noise Robustness: Superior handling of noisy measurements

  • Regularization: Natural incorporation of prior knowledge

  • Incomplete Data: Effective with limited-angle or sparse-view acquisitions

  • Flexibility: Easy modification of cost functions and constraints

  • Artifact Reduction: Better control over reconstruction artifacts

Convergence Characteristics

Typical convergence behavior:

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

  2. Refinement Phase (100-500 iterations): Fine details develop, slower convergence

  3. Convergence Phase (500+ iterations): Minimal improvement, potential overfitting

2D Parallel 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 ParallelProjectorFunction, circular_trajectory_2d_parallel
 16
 17
 18def shepp_logan_2d(Nx, Ny):
 19    Nx = int(Nx)
 20    Ny = int(Ny)
 21    phantom = np.zeros((Ny, Nx), dtype=np.float32)
 22    ellipses = [
 23        (0.0, 0.0, 0.69, 0.92, 0, 1.0),
 24        (0.0, -0.0184, 0.6624, 0.8740, 0, -0.8),
 25        (0.22, 0.0, 0.11, 0.31, -18.0, -0.8),
 26        (-0.22, 0.0, 0.16, 0.41, 18.0, -0.8),
 27        (0.0, 0.35, 0.21, 0.25, 0, 0.7),
 28    ]
 29    cx = (Nx - 1)*0.5
 30    cy = (Ny - 1)*0.5
 31    for ix in range(Nx):
 32        for iy in range(Ny):
 33            xnorm = (ix - cx)/(Nx/2)
 34            ynorm = (iy - cy)/(Ny/2)
 35            val = 0.0
 36            for (x0, y0, a, b, angdeg, ampl) in ellipses:
 37                th = np.deg2rad(angdeg)
 38                xprime = (xnorm - x0)*np.cos(th) + (ynorm - y0)*np.sin(th)
 39                yprime = -(xnorm - x0)*np.sin(th) + (ynorm - y0)*np.cos(th)
 40                if xprime*xprime/(a*a) + yprime*yprime/(b*b) <= 1.0:
 41                    val += ampl
 42            phantom[iy, ix] = val
 43    phantom = np.clip(phantom, 0.0, 1.0)
 44    return phantom
 45
 46class IterativeRecoModel(nn.Module):
 47    def __init__(self, volume_shape, ray_dir, det_origin, det_u_vec, num_detectors, detector_spacing, voxel_spacing):
 48        super().__init__()
 49        self.reco = nn.Parameter(torch.zeros(volume_shape))
 50        self.ray_dir = ray_dir
 51        self.det_origin = det_origin
 52        self.det_u_vec = det_u_vec
 53        self.num_detectors = num_detectors
 54        self.detector_spacing = detector_spacing
 55        self.voxel_spacing = voxel_spacing
 56
 57    def forward(self, x):
 58        updated_reco = x + self.reco
 59        current_sino = ParallelProjectorFunction.apply(updated_reco, self.ray_dir, self.det_origin, self.det_u_vec,
 60                                                       self.num_detectors, self.detector_spacing, self.voxel_spacing)
 61        return current_sino, updated_reco
 62
 63class Pipeline:
 64    def __init__(self, lr, volume_shape, ray_dir, det_origin, det_u_vec, num_detectors, detector_spacing,
 65                 voxel_spacing, device, epoches=1000):
 66
 67        self.epoches = epoches
 68        self.model = IterativeRecoModel(volume_shape, ray_dir, det_origin, det_u_vec, num_detectors,
 69                                        detector_spacing, voxel_spacing).to(device)
 70
 71        self.optimizer = optim.AdamW(list(self.model.parameters()), lr=lr)
 72        self.loss = nn.MSELoss()
 73
 74    def train(self, input, label):
 75        loss_values = []
 76        for epoch in range(self.epoches):
 77            self.optimizer.zero_grad()
 78            predictions, current_reco = self.model(input)
 79            loss_value = self.loss(predictions, label)
 80            loss_value.backward()
 81            self.optimizer.step()
 82            with torch.no_grad():
 83                self.model.reco.clamp_(min=0.0)
 84            loss_values.append(loss_value.item())
 85
 86            if epoch % 10 == 0:
 87                print(f"Epoch {epoch}, Loss: {loss_value.item()}")
 88                
 89        return loss_values, self.model
 90
 91def main():
 92    Nx, Ny = 128, 128
 93    phantom_cpu = shepp_logan_2d(Nx, Ny)
 94
 95    num_views = 360
 96    num_detectors = 256
 97    detector_spacing = 0.5
 98    voxel_spacing = 1.0
 99
100    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
101    phantom_torch = torch.tensor(phantom_cpu, device=device, dtype=torch.float32)
102
103    # Generate trajectory geometry for parallel beam
104    ray_dir, det_origin, det_u_vec = circular_trajectory_2d_parallel(num_views, device=device)
105
106    # Generate the "real" sinogram
107    real_sinogram = ParallelProjectorFunction.apply(phantom_torch, ray_dir, det_origin, det_u_vec,
108                                                    num_detectors, detector_spacing, voxel_spacing)
109
110    pipeline_instance = Pipeline(lr=1e-1,
111                                 volume_shape=(Ny, Nx),
112                                 ray_dir=ray_dir,
113                                 det_origin=det_origin,
114                                 det_u_vec=det_u_vec,
115                                 num_detectors=num_detectors,
116                                 detector_spacing=detector_spacing,
117                                 voxel_spacing=voxel_spacing,
118                                 device=device, epoches=1000)
119
120    ini_guess = torch.zeros_like(phantom_torch)
121
122    loss_values, trained_model = pipeline_instance.train(ini_guess, real_sinogram)
123
124    reco = trained_model(ini_guess)[1].squeeze().cpu().detach().numpy()
125
126    plt.figure()
127    plt.plot(loss_values)
128    plt.title("Loss Curve")
129    plt.xlabel("Epoch")
130    plt.ylabel("Loss")
131    plt.show()
132
133    plt.figure(figsize=(12, 6))
134    plt.subplot(1, 2, 1)
135    plt.imshow(phantom_cpu, cmap="gray")
136    plt.title("Original Phantom")
137    plt.axis("off")
138
139    plt.subplot(1, 2, 2)
140    plt.imshow(reco, cmap="gray")
141    plt.title("Reconstructed")
142    plt.axis("off")
143    plt.show()
144
145if __name__ == "__main__":
146    main()