Fan Beam Iterative Reconstruction

This example demonstrates 2D fan beam iterative reconstruction using the differentiable FanProjectorFunction and FanBackprojectorFunction from diffct_mlx.engine.

Overview

Fan beam iterative reconstruction extends the optimization approach to the more realistic fan beam geometry. This example shows how to:

  • Formulate fan beam CT reconstruction as an optimization problem

  • Handle geometric complexities of divergent ray geometry

  • Apply gradient-based optimization with fan beam operators

  • Monitor convergence and reconstruction quality

Mathematical Background

Fan Beam Iterative Formulation

The fan beam reconstruction problem is formulated as:

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

where \(A_{\text{fan}}\) is the fan beam forward projection operator accounting for divergent ray geometry.

Fan Beam Forward Model

The fan beam projection operator maps 2D image \(f(x,y)\) to sinogram \(p(\beta, u)\):

\[p(\beta, u) = \int_{\text{ray}} f(x,y) \, dl\]

where integration follows the ray from point source to detector element \(u\) at source angle \(\beta\).

Gradient Computation

The gradient involves the fan beam backprojection operator (adjoint):

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

where \(A_{\text{fan}}^T\) is the fan beam backprojection operator.

Geometric Considerations

Fan beam geometry introduces complexities compared to parallel beam:

  • Ray Divergence: Non-parallel rays affect sampling density and conditioning

  • Magnification Effects: Variable magnification across the field of view

  • Non-uniform Resolution: Spatial resolution varies with distance from rotation center

  • Geometric Distortion: Requires careful handling of coordinate transformations

Implementation Steps

  1. Geometry Setup: Configure fan beam parameters (SID, SDD) using helpers such as diffct_mlx.engine.circular_trajectory_2d_fan

  2. Problem Formulation: Define parameterized image and fan beam forward model

  3. Loss Computation: Calculate L2 distance using FanProjectorFunction

  4. Gradient Computation: Use automatic differentiation through fan beam operators

  5. Optimization: Apply Adam optimizer with appropriate learning rate

  6. Convergence Monitoring: Track reconstruction quality and loss evolution

Model Architecture

The fan beam reconstruction model consists of:

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

  • Fan Beam Forward Model: FanProjectorFunction with geometric parameters

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

Convergence Characteristics

Fan beam reconstruction typically exhibits:

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

  2. Detail Refinement (100-500 iterations): Fine features develop, slower progress

  3. Final Convergence (500+ iterations): Minimal improvement, convergence plateau

Challenges and Solutions

  • Conditioning: Fan beam system matrix may have different conditioning properties

  • Geometric Artifacts: Proper weighting and filtering help reduce artifacts

  • Parameter Tuning: Learning rate may need adjustment for optimal convergence

  • Memory Usage: Similar to parallel beam but with additional geometric computations

2D Fan 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 FanProjectorFunction, circular_trajectory_2d_fan
 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, src_pos, det_center, det_u_vec,
 48                 num_detectors, detector_spacing, voxel_spacing):
 49
 50        super().__init__()
 51        self.reco = nn.Parameter(torch.zeros(volume_shape))
 52        self.src_pos = src_pos
 53        self.det_center = det_center
 54        self.det_u_vec = det_u_vec
 55        self.num_detectors = num_detectors
 56        self.detector_spacing = detector_spacing
 57        self.voxel_spacing = voxel_spacing
 58
 59    def forward(self, x):
 60        updated_reco = x + self.reco
 61        current_sino = FanProjectorFunction.apply(updated_reco, self.src_pos, self.det_center, self.det_u_vec,
 62                                                  self.num_detectors, self.detector_spacing, self.voxel_spacing)
 63        return current_sino, updated_reco
 64
 65class Pipeline:
 66    def __init__(self, lr, volume_shape, src_pos, det_center, det_u_vec,
 67                 num_detectors, detector_spacing, voxel_spacing,
 68                 device, epoches=1000):
 69
 70        self.epoches = epoches
 71        self.model = IterativeRecoModel(volume_shape, src_pos, det_center, det_u_vec,
 72                                        num_detectors, detector_spacing, voxel_spacing).to(device)
 73        
 74        self.optimizer = optim.AdamW(list(self.model.parameters()), lr=lr)
 75        self.loss = nn.MSELoss()
 76
 77    def train(self, input, label):
 78        loss_values = []
 79        for epoch in range(self.epoches):
 80            self.optimizer.zero_grad()
 81            predictions, current_reco = self.model(input)
 82            loss_value = self.loss(predictions, label)
 83            loss_value.backward()
 84            self.optimizer.step()
 85            with torch.no_grad():
 86                self.model.reco.clamp_(min=0.0)
 87            loss_values.append(loss_value.item())
 88
 89            if epoch % 10 == 0:
 90                print(f"Epoch {epoch}, Loss: {loss_value.item()}")
 91                
 92        return loss_values, self.model
 93
 94def main():
 95    Nx, Ny = 128, 128
 96    phantom_cpu = shepp_logan_2d(Nx, Ny)
 97
 98    num_views = 360
 99    num_detectors = 256
100    detector_spacing = 1.0
101    voxel_spacing = 1.0
102    sdd = 600.0
103    sid = 400.0
104
105    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
106    phantom_torch = torch.tensor(phantom_cpu, device=device, dtype=torch.float32)
107
108    # Generate trajectory geometry for fan beam
109    src_pos, det_center, det_u_vec = circular_trajectory_2d_fan(num_views, sid, sdd, device=device)
110
111    # Generate the "real" sinogram
112    real_sinogram = FanProjectorFunction.apply(phantom_torch, src_pos, det_center, det_u_vec,
113                                               num_detectors, detector_spacing, voxel_spacing)
114
115    pipeline_instance = Pipeline(lr=1e-1,
116                                 volume_shape=(Ny, Nx),
117                                 src_pos=src_pos,
118                                 det_center=det_center,
119                                 det_u_vec=det_u_vec,
120                                 num_detectors=num_detectors,
121                                 detector_spacing=detector_spacing,
122                                 voxel_spacing=voxel_spacing,
123                                 device=device, epoches=1000)
124
125    ini_guess = torch.zeros_like(phantom_torch)
126
127    loss_values, trained_model = pipeline_instance.train(ini_guess, real_sinogram)
128
129    reco = trained_model(ini_guess)[1].squeeze().cpu().detach().numpy()
130
131    plt.figure()
132    plt.plot(loss_values)
133    plt.title("Loss Curve")
134    plt.xlabel("Epoch")
135    plt.ylabel("Loss")
136    plt.show()
137
138    plt.figure(figsize=(12, 6))
139    plt.subplot(1, 2, 1)
140    plt.imshow(phantom_cpu, cmap="gray")
141    plt.title("Original Phantom")
142    plt.axis("off")
143
144    plt.subplot(1, 2, 2)
145    plt.imshow(reco, cmap="gray")
146    plt.title("Reconstructed")
147    plt.axis("off")
148    plt.show()
149
150if __name__ == "__main__":
151    main()