Fan Beam Filtered Backprojection (FBP)
This example demonstrates 2D fan beam filtered backprojection (FBP) reconstruction using the FanProjectorFunction and FanBackprojectorFunction from diffct_mlx.engine.
Overview
Fan beam FBP extends parallel beam reconstruction to the more realistic fan beam geometry used in clinical CT scanners. This example shows how to:
Configure fan beam geometry parameters (SID, SDD)
Generate fan beam projections with proper weighting
Apply ramp filtering with cosine weighting correction
Perform fan beam backprojection reconstruction
Mathematical Background
Fan Beam Geometry
Fan beam CT uses a point X-ray source creating a fan-shaped beam. Key geometric parameters:
SDD \(D_s\): Source-to-Detector Distance (distance from X-ray source to detector array)
SID \(D_{sid}\): Source-to-Isocenter Distance (distance from X-ray source to rotation center)
Fan angle \(\gamma\): Angle between central ray and detector element
The detector position \(u\) relates to fan angle \(\gamma\) by:
Fan Beam Forward Projection
The fan beam projection at source angle \(\beta\) and detector position \(u\) is:
where \(\vec{r}_s\) is the source position and \(\vec{d}(\beta, u)\) is the ray direction vector.
Fan Beam FBP Algorithm
Fan beam FBP reconstruction involves three sequential steps:
Cosine Weighting: Compensate for ray divergence:
\[p_w(\beta, u) = p(\beta, u) \cdot \cos(\gamma) = p(\beta, u) \cdot \frac{D_s}{\sqrt{D_s^2 + u^2}}\]Ramp Filtering: Apply frequency domain filter:
\[p_f(\beta, u) = \mathcal{F}^{-1}\{|\omega| \cdot \mathcal{F}\{p_w(\beta, u)\}\}\]Fan Beam Backprojection: Reconstruct using weighted backprojection:
\[f(x,y) = \int_0^{2\pi} \frac{D_s^2}{(D_s + x\cos\beta + y\sin\beta)^2} p_f(\beta, u_{xy}) d\beta\]where the detector coordinate \(u_{xy}\) for pixel \((x,y)\) is:
\[u_{xy} = D_s \frac{-x\sin\beta + y\cos\beta}{D_s + x\cos\beta + y\sin\beta}\]
Implementation Steps
Phantom Generation: Create Shepp-Logan phantom for testing
Fan Beam Projection: Generate sinogram using FanProjectorFunction with geometry from helpers such as
diffct_mlx.engine.circular_trajectory_2d_fanCosine Weighting: Apply divergence correction weights
Ramp Filtering: Filter each projection in frequency domain
Fan Beam Backprojection: Reconstruct using FanBackprojectorFunction
Normalization: Scale by \(\frac{\pi}{N_{\text{angles}}}\) factor
Advantages of Fan Beam Geometry
Clinical Relevance: Matches real CT scanner geometry
Higher Flux: Better X-ray utilization than parallel beam
Natural Magnification: Improved spatial resolution
Faster Acquisition: Wider coverage per projection angle
1"""Circular-orbit fan-beam FBP reconstruction example.
2
3Pipeline (matches the cone-beam FDK example, one dimension lower):
4
5 FanProjectorFunction.apply # forward projection (sinogram)
6 parker_weights (optional) # short-scan redundancy weighting
7 fan_cosine_weights # cos(gamma) pre-weighting
8 ramp_filter_1d # ramp filter along detector axis
9 angular_integration_weights # per-view integration weights
10 fan_weighted_backproject # voxel-driven FBP gather
11
12Every geometry and reconstruction parameter below is annotated with
13its meaning, units, and available options so the file can be used as
14a reference for the other analytical 2D entry points. This is the
15dev-branch arbitrary-trajectory version: geometry is expressed as
16per-view ``(src_pos, det_center, det_u_vec)`` tensors produced by the
17``circular_trajectory_2d_fan`` helper, and every subsequent helper
18accepts the same arrays.
19"""
20
21import math
22import sys
23from pathlib import Path
24
25import matplotlib.pyplot as plt
26import numpy as np
27import torch
28import torch.nn.functional as F
29
30ROOT_DIR = Path(__file__).resolve().parents[2]
31if str(ROOT_DIR) not in sys.path:
32 sys.path.insert(0, str(ROOT_DIR))
33
34from diffct_mlx.engine import (
35 FanProjectorFunction,
36 angular_integration_weights,
37 circular_trajectory_2d_fan,
38 fan_cosine_weights,
39 fan_weighted_backproject,
40 parker_weights,
41 ramp_filter_1d,
42)
43
44
45def shepp_logan_2d(Nx, Ny):
46 """2D Shepp-Logan phantom clipped to ``[0, 1]``."""
47 phantom = np.zeros((Ny, Nx), dtype=np.float32)
48 ellipses = [
49 (0.0, 0.0, 0.69, 0.92, 0.0, 1.0),
50 (0.0, -0.0184, 0.6624, 0.8740, 0.0, -0.8),
51 (0.22, 0.0, 0.11, 0.31, -18.0, -0.8),
52 (-0.22, 0.0, 0.16, 0.41, 18.0, -0.8),
53 (0.0, 0.35, 0.21, 0.25, 0.0, 0.7),
54 ]
55 cx = Nx * 0.5 # kernel convention
56 cy = Ny * 0.5
57 ys, xs = np.mgrid[0:Ny, 0:Nx].astype(np.float32)
58 xn = (xs - cx) / (Nx / 2)
59 yn = (ys - cy) / (Ny / 2)
60 for (x0, y0, a, b, angdeg, ampl) in ellipses:
61 th = math.radians(angdeg)
62 xp = (xn - x0) * math.cos(th) + (yn - y0) * math.sin(th)
63 yp = -(xn - x0) * math.sin(th) + (yn - y0) * math.cos(th)
64 mask = (xp * xp) / (a * a) + (yp * yp) / (b * b) <= 1.0
65 phantom[mask] += ampl
66 return np.clip(phantom, 0.0, 1.0)
67
68
69def main():
70 # ------------------------------------------------------------------
71 # 1. Image geometry
72 # ------------------------------------------------------------------
73 # ``Nx`` / ``Ny`` are the reconstruction grid size in pixels. The
74 # phantom tensor has shape ``(Ny, Nx)`` which matches the ``(H, W)``
75 # layout every 2D routine in diffct expects.
76 Nx, Ny = 256, 256
77 phantom = shepp_logan_2d(Nx, Ny)
78
79 # ``voxel_spacing`` is the physical size of one pixel in the same
80 # length unit used by ``detector_spacing``, ``sdd`` and ``sid``
81 # below. Internally all physical quantities are divided by
82 # ``voxel_spacing``, so only their *ratios* matter.
83 voxel_spacing = 1.0
84
85 # ------------------------------------------------------------------
86 # 2. Detector geometry
87 # ------------------------------------------------------------------
88 # (Listed before the trajectory so the short-scan coverage below can
89 # use the detector fan angle to compute ``pi + 2*gamma_max``.)
90 #
91 # ``num_detectors`` is the number of detector cells along the
92 # detector axis. ``detector_spacing`` is their physical pitch. Make
93 # sure the detector is wide enough that no ray through the FOV ever
94 # projects outside it, otherwise truncation artifacts appear at the
95 # image edges.
96 num_detectors = 600
97 detector_spacing = 1.0
98
99 # ``sdd`` = source-to-detector distance, ``sid`` = source-to-
100 # isocenter distance, both in physical units. The magnification at
101 # the detector is ``sdd / sid`` (here = 1.6). Typical clinical fan
102 # beam systems have magnifications around 1.3 - 2.0.
103 sdd = 800.0
104 sid = 500.0
105
106 # ------------------------------------------------------------------
107 # 3. Source trajectory (circular orbit)
108 # ------------------------------------------------------------------
109 # ``apply_parker`` selects between two supported trajectories:
110 #
111 # False -> full 2*pi scan, 1/2 FBP redundancy factor absorbed
112 # inside ``redundant_full_scan=True``.
113 #
114 # True -> minimal short scan ``pi + 2*gamma_max`` with Parker
115 # redundancy weighting. ``gamma_max`` is computed from
116 # the detector half-width and ``sdd``.
117 #
118 # Both branches reuse the same ``num_angles`` so reconstruction
119 # runtime stays identical - only the angular *range* changes.
120 apply_parker = False
121
122 if apply_parker:
123 # Use dev's detector convention (u[k] = (k - N/2)*ds) for the
124 # maximum |u| on the detector.
125 u_max = (num_detectors * 0.5) * detector_spacing
126 gamma_max = math.atan(u_max / sdd)
127 scan_range = math.pi + 2.0 * gamma_max
128 else:
129 scan_range = 2.0 * math.pi
130
131 num_angles = 360
132
133 # ------------------------------------------------------------------
134 # 4. Move everything to CUDA and build the trajectory arrays
135 # ------------------------------------------------------------------
136 device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
137 image_torch = torch.tensor(phantom, device=device, dtype=torch.float32)
138
139 src_pos, det_center, det_u_vec = circular_trajectory_2d_fan(
140 num_angles,
141 sid=sid,
142 sdd=sdd,
143 start_angle=0.0,
144 end_angle=scan_range,
145 device=device,
146 )
147 angles_torch = torch.linspace(
148 0.0, scan_range, num_angles + 1, device=device, dtype=torch.float32
149 )[:-1]
150
151 # ------------------------------------------------------------------
152 # 5. Forward projection: image -> fan sinogram
153 # ------------------------------------------------------------------
154 # ``FanProjectorFunction`` is the differentiable Siddon-based fan-
155 # beam forward projector. It returns a ``(num_angles, num_detectors)``
156 # sinogram. The call is autograd-aware so the same function can be
157 # used inside an iterative reconstruction loop (see
158 # ``iterative_reco_fan.py``).
159 sinogram = FanProjectorFunction.apply(
160 image_torch,
161 src_pos,
162 det_center,
163 det_u_vec,
164 num_detectors,
165 detector_spacing,
166 voxel_spacing,
167 )
168
169 # ==================================================================
170 # 6. FBP analytical reconstruction
171 # ==================================================================
172
173 # --- 6.1 Optional Parker redundancy weighting -------------------
174 # For short-scan trajectories, ``parker_weights`` returns a
175 # ``(num_angles, num_detectors)`` weight that smoothly tapers views
176 # near the two ends of the angular range so each ray contributes
177 # exactly once. For a full 2*pi scan this helper returns all-ones
178 # and is a no-op.
179 if apply_parker:
180 parker = parker_weights(
181 angles_torch, num_detectors, detector_spacing, sdd
182 )
183 sinogram = sinogram * parker
184
185 # --- 6.2 Fan-beam cosine pre-weighting --------------------------
186 # Multiplies each detector cell by ``cos(gamma) = sdd / sqrt(sdd^2
187 # + u^2)``, the cosine of the fan angle. Compensates for the extra
188 # path length that off-center rays traverse relative to the
189 # principal ray.
190 weights = fan_cosine_weights(
191 num_detectors,
192 detector_spacing,
193 sdd,
194 device=device,
195 dtype=image_torch.dtype,
196 ).unsqueeze(0)
197 sino_weighted = sinogram * weights
198
199 # --- 6.3 1D ramp filter along the detector axis -----------------
200 # See the fdk_cone.py example for the full option list. Recommended
201 # fan FBP call: ``sample_spacing=detector_spacing``, ``pad_factor=2``,
202 # ``window="hann"``.
203 sinogram_filt = ramp_filter_1d(
204 sino_weighted,
205 dim=1,
206 sample_spacing=detector_spacing,
207 pad_factor=2,
208 window="hann",
209 ).contiguous()
210
211 # --- 6.4 Per-view angular integration weights -------------------
212 # For a full 2*pi scan uniformly sampled, each view contributes
213 # ``pi / num_angles`` to the FBP integral; the ``1/2`` redundancy
214 # factor of the full-scan formula is absorbed inside
215 # ``redundant_full_scan=True``. For a short scan with Parker
216 # weights we already handle redundancy there, so pass
217 # ``redundant_full_scan=False``.
218 d_beta = angular_integration_weights(
219 angles_torch, redundant_full_scan=(not apply_parker)
220 ).view(-1, 1)
221 sinogram_filt = sinogram_filt * d_beta
222
223 # --- 6.5 Voxel-driven FBP backprojection ------------------------
224 # ``fan_weighted_backproject`` dispatches to the dedicated fan FBP
225 # gather kernel. For each pixel it projects onto the detector,
226 # linearly samples the filtered sinogram, multiplies by the
227 # per-view ``(sid_n/U_n)^2`` weight (generalised to the detector
228 # normal for arbitrary trajectories) and accumulates over views.
229 # The analytical ``sdd/(2*pi*sid)`` FBP constant is applied inside
230 # the wrapper so the returned image is already amplitude-calibrated.
231 reconstruction_raw = fan_weighted_backproject(
232 sinogram_filt,
233 src_pos,
234 det_center,
235 det_u_vec,
236 detector_spacing,
237 Ny,
238 Nx,
239 voxel_spacing=voxel_spacing,
240 )
241 reconstruction = F.relu(reconstruction_raw)
242
243 # ------------------------------------------------------------------
244 # 7. Quantitative summary
245 # ------------------------------------------------------------------
246 raw_loss = torch.mean((reconstruction_raw - image_torch) ** 2)
247 clamped_loss = torch.mean((reconstruction - image_torch) ** 2)
248
249 scan_label = "Parker short scan" if apply_parker else "full 2*pi scan"
250 print(f"Fan Beam FBP example ({scan_label}):")
251 print(f" Raw MSE: {raw_loss.item():.6f}")
252 print(f" Clamped MSE: {clamped_loss.item():.6f}")
253 print(f" Reconstruction shape: {tuple(reconstruction.shape)}")
254 print(
255 " Raw reco data range: "
256 f"[{reconstruction_raw.min().item():.4f}, {reconstruction_raw.max().item():.4f}]"
257 )
258 print(
259 " Clamped reco range: "
260 f"[{reconstruction.min().item():.4f}, {reconstruction.max().item():.4f}]"
261 )
262 print(
263 " Phantom data range: "
264 f"[{float(phantom.min()):.4f}, {float(phantom.max()):.4f}]"
265 )
266
267 # ------------------------------------------------------------------
268 # 8. Visualization
269 # ------------------------------------------------------------------
270 sinogram_cpu = sinogram.detach().cpu().numpy()
271 reco_cpu = reconstruction.detach().cpu().numpy()
272
273 plt.figure(figsize=(12, 4))
274 plt.subplot(1, 3, 1)
275 plt.imshow(phantom, cmap="gray")
276 plt.title("Phantom")
277 plt.axis("off")
278 plt.subplot(1, 3, 2)
279 plt.imshow(sinogram_cpu, cmap="gray", aspect="auto")
280 plt.title("Fan Sinogram")
281 plt.axis("off")
282 plt.subplot(1, 3, 3)
283 plt.imshow(reco_cpu, cmap="gray")
284 plt.title("Fan Reconstruction")
285 plt.axis("off")
286 plt.tight_layout()
287 plt.show()
288
289
290if __name__ == "__main__":
291 main()