qualia_core_db/medical/reconstruction/
fbp.rs1use super::spectral_fft::{fft_1d, ifft_1d};
4use crate::medical::dicom_frames::ValueUnits;
5use core::f64::consts::PI;
6
7#[derive(Clone, Copy, Debug, PartialEq, Eq)]
8pub enum FbpFilter {
9 RamLak,
10 SheppLogan,
11 Hann,
12}
13
14#[derive(Clone, Copy, Debug, PartialEq)]
15pub enum ProjectionGeometry {
16 Parallel,
17 FanEquiangular {
18 source_to_isocenter_mm: f64,
19 detector_arc_spacing_rad: f64,
20 },
21 FanEquispaced {
22 source_to_isocenter_mm: f64,
23 source_to_detector_mm: f64,
24 detector_spacing_mm: f64,
25 },
26}
27
28#[derive(Clone, Copy, Debug)]
29pub struct FbpConfig {
30 pub image_width: usize,
31 pub image_height: usize,
32 pub pixel_spacing_mm: [f64; 2],
33 pub filter: FbpFilter,
34 pub cutoff_ratio: f64,
35 pub geometry: ProjectionGeometry,
36 pub apply_parker_short_scan: bool,
37}
38
39#[derive(Clone, Copy, Debug)]
40pub struct SinogramView<'a> {
41 pub source_blake3: [u8; 32],
42 pub n_angles: usize,
43 pub n_detectors: usize,
44 pub detector_spacing_mm: f64,
45 pub center_detector_offset: f64,
46 pub angles_rad: &'a [f64],
47 pub projections: &'a [f64],
48 pub units: ValueUnits<'a>,
49}
50
51#[derive(Clone, Copy, Debug, PartialEq)]
52pub struct FbpProvenance<'a> {
53 pub source_blake3: [u8; 32],
54 pub derivation_blake3: [u8; 32],
55 pub image_width: usize,
56 pub image_height: usize,
57 pub filter: FbpFilter,
58 pub geometry: ProjectionGeometry,
59 pub units: ValueUnits<'a>,
60}
61
62#[derive(Debug, Clone, Copy, PartialEq, Eq)]
63pub enum FbpError {
64 MissingSourceData,
65 DimensionMismatch,
66 OutputTooSmall,
67 NonFiniteInput,
68 InvalidGeometry(&'static str),
69 InvalidFilterCutoff,
70 Overflow,
71}
72
73impl std::fmt::Display for FbpError {
74 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
75 write!(f, "CT FBP reconstruction error: {self:?}")
76 }
77}
78impl std::error::Error for FbpError {}
79
80pub fn filter_projection_fft(
83 proj: &[f64],
84 spacing: f64,
85 filter: FbpFilter,
86 cutoff_ratio: f64,
87) -> Result<Vec<f64>, FbpError> {
88 let n = proj.len();
89 let pad = (n * 2).max(8).next_power_of_two();
90 let half = pad / 2;
91
92 let mut kernel = vec![(0.0, 0.0); pad];
94 kernel[0] = (1.0 / (4.0 * spacing * spacing), 0.0);
95 for k in 1..half {
96 if k % 2 == 1 {
97 let val = -1.0 / (PI * k as f64 * spacing).powi(2);
98 kernel[k] = (val, 0.0);
99 kernel[pad - k] = (val, 0.0);
100 }
101 }
102 let mut h_freq = fft_1d(&kernel).map_err(|_| FbpError::NonFiniteInput)?;
103
104 for (k, bin) in h_freq.iter_mut().enumerate() {
106 let bin_abs = if k <= half { k } else { pad - k };
107 let norm_f = bin_abs as f64 / half as f64; let w = if norm_f > cutoff_ratio {
109 0.0
110 } else {
111 let scaled = norm_f / cutoff_ratio.max(1e-9);
112 match filter {
113 FbpFilter::RamLak => 1.0,
114 FbpFilter::SheppLogan => {
115 if scaled == 0.0 {
116 1.0
117 } else {
118 let a = 0.5 * PI * scaled;
119 a.sin() / a
120 }
121 }
122 FbpFilter::Hann => 0.5 * (1.0 + (PI * scaled).cos()),
123 }
124 };
125 bin.0 *= w;
126 bin.1 *= w;
127 }
128
129 let mut padded = vec![(0.0, 0.0); pad];
130 for (i, &v) in proj.iter().enumerate() {
131 padded[i] = (v, 0.0);
132 }
133 let mut p_freq = fft_1d(&padded).map_err(|_| FbpError::NonFiniteInput)?;
134 for (pf, hf) in p_freq.iter_mut().zip(h_freq.iter()) {
135 let re = pf.0 * hf.0 - pf.1 * hf.1;
136 let im = pf.0 * hf.1 + pf.1 * hf.0;
137 *pf = (re, im);
138 }
139 let filtered = ifft_1d(&p_freq).map_err(|_| FbpError::NonFiniteInput)?;
140 Ok(filtered.into_iter().take(n).map(|(re, _)| re * spacing).collect())
141}
142
143fn parker_weight(beta: f64, gamma: f64, delta: f64) -> f64 {
145 if delta <= 0.0 {
146 return 1.0;
147 }
148 let beta_w = beta.rem_euclid(2.0 * PI);
149 let cond1 = 2.0 * delta - 2.0 * gamma;
150 let cond2 = PI - 2.0 * gamma;
151 let cond3 = PI + 2.0 * delta + 2.0 * gamma;
152 let cond4 = PI + 2.0 * delta;
153 if beta_w >= 0.0 && beta_w < cond1 {
154 let arg = (PI / 4.0) * (beta_w / (delta - gamma).max(1e-9));
155 arg.sin().powi(2)
156 } else if beta_w >= cond1 && beta_w < cond2 {
157 1.0
158 } else if beta_w >= cond2 && beta_w <= cond4.max(cond3) {
159 let denom = (delta + gamma).max(1e-9);
160 let arg = (PI / 4.0) * ((PI + 2.0 * delta - beta_w) / denom).clamp(0.0, 2.0);
161 arg.sin().powi(2)
162 } else {
163 0.0
164 }
165}
166
167fn bilinear_sample(row: &[f64], pos: f64) -> f64 {
168 if pos < 0.0 || pos > (row.len() - 1) as f64 {
169 return 0.0;
170 }
171 let idx = pos.floor() as usize;
172 let frac = pos - idx as f64;
173 if idx + 1 >= row.len() {
174 row[idx]
175 } else {
176 row[idx] * (1.0 - frac) + row[idx + 1] * frac
177 }
178}
179
180fn validate_sinogram_and_config(
181 sino: &SinogramView<'_>,
182 cfg: &FbpConfig,
183 out_len: usize,
184) -> Result<(usize, f64), FbpError> {
185 if sino.n_angles == 0 || sino.n_detectors < 2 || cfg.image_width == 0 || cfg.image_height == 0 {
186 return Err(FbpError::MissingSourceData);
187 }
188 let expected_sino = sino.n_angles.checked_mul(sino.n_detectors).ok_or(FbpError::Overflow)?;
189 if sino.angles_rad.len() != sino.n_angles || sino.projections.len() != expected_sino {
190 return Err(FbpError::DimensionMismatch);
191 }
192 let out_pixels = cfg.image_width.checked_mul(cfg.image_height).ok_or(FbpError::Overflow)?;
193 if out_len < out_pixels {
194 return Err(FbpError::OutputTooSmall);
195 }
196 if cfg.pixel_spacing_mm[0] <= 0.0
197 || cfg.pixel_spacing_mm[1] <= 0.0
198 || !cfg.pixel_spacing_mm[0].is_finite()
199 || !cfg.pixel_spacing_mm[1].is_finite()
200 {
201 return Err(FbpError::InvalidGeometry("pixel spacing must be positive and finite"));
202 }
203 if sino.detector_spacing_mm <= 0.0 || !sino.detector_spacing_mm.is_finite() {
204 return Err(FbpError::InvalidGeometry("detector spacing must be positive"));
205 }
206 if !(0.05..=1.0).contains(&cfg.cutoff_ratio) || !cfg.cutoff_ratio.is_finite() {
207 return Err(FbpError::InvalidFilterCutoff);
208 }
209 if sino.angles_rad.iter().any(|v| !v.is_finite()) || sino.projections.iter().any(|v| !v.is_finite()) {
210 return Err(FbpError::NonFiniteInput);
211 }
212 match cfg.geometry {
213 ProjectionGeometry::Parallel => {}
214 ProjectionGeometry::FanEquiangular { source_to_isocenter_mm, detector_arc_spacing_rad } => {
215 if source_to_isocenter_mm <= 0.0 || detector_arc_spacing_rad <= 0.0 {
216 return Err(FbpError::InvalidGeometry("fan equiangular parameters must be positive"));
217 }
218 }
219 ProjectionGeometry::FanEquispaced {
220 source_to_isocenter_mm,
221 source_to_detector_mm,
222 detector_spacing_mm,
223 } => {
224 if source_to_isocenter_mm <= 0.0 || source_to_detector_mm <= 0.0 || detector_spacing_mm <= 0.0 {
225 return Err(FbpError::InvalidGeometry("fan equispaced parameters must be positive"));
226 }
227 }
228 }
229 let min_a = sino.angles_rad.iter().copied().fold(f64::INFINITY, f64::min);
230 let max_a = sino.angles_rad.iter().copied().fold(f64::NEG_INFINITY, f64::max);
231 let span = (max_a - min_a).abs();
232 if span <= 1e-6 {
233 return Err(FbpError::InvalidGeometry("zero angular span"));
234 }
235 let d_theta = if sino.n_angles > 1 { span / (sino.n_angles - 1) as f64 } else { span };
236 Ok((out_pixels, d_theta))
237}
238
239pub fn reconstruct_ct_fbp_into<'a>(
242 sino: &SinogramView<'a>,
243 cfg: &FbpConfig,
244 output: &mut [f64],
245) -> Result<FbpProvenance<'a>, FbpError> {
246 let (out_pixels, d_theta) = validate_sinogram_and_config(sino, cfg, output.len())?;
247
248 let mut staged = vec![0.0f64; out_pixels];
249 let det_mid = 0.5 * (sino.n_detectors - 1) as f64 + sino.center_detector_offset;
250 let img_cx = 0.5 * (cfg.image_width - 1) as f64;
251 let img_cy = 0.5 * (cfg.image_height - 1) as f64;
252
253 let min_a = sino.angles_rad.iter().copied().fold(f64::INFINITY, f64::min);
254 let max_a = sino.angles_rad.iter().copied().fold(f64::NEG_INFINITY, f64::max);
255 let span = max_a - min_a;
256
257 for (ai, &angle) in sino.angles_rad.iter().enumerate() {
258 let raw_row = &sino.projections[ai * sino.n_detectors..(ai + 1) * sino.n_detectors];
259 let mut weighted = vec![0.0; sino.n_detectors];
260 let filt_spacing = match cfg.geometry {
261 ProjectionGeometry::Parallel => {
262 weighted.copy_from_slice(raw_row);
263 sino.detector_spacing_mm
264 }
265 ProjectionGeometry::FanEquiangular { source_to_isocenter_mm, detector_arc_spacing_rad } => {
266 let half_fan = 0.5 * (sino.n_detectors as f64) * detector_arc_spacing_rad;
267 for (di, wv) in weighted.iter_mut().enumerate() {
268 let gamma = (di as f64 - det_mid) * detector_arc_spacing_rad;
269 let pw = if cfg.apply_parker_short_scan && span < 1.9 * PI {
270 parker_weight(angle - min_a, gamma, half_fan)
271 } else {
272 1.0
273 };
274 *wv = raw_row[di] * source_to_isocenter_mm * gamma.cos() * pw;
275 }
276 detector_arc_spacing_rad
277 }
278 ProjectionGeometry::FanEquispaced { source_to_isocenter_mm, source_to_detector_mm, detector_spacing_mm } => {
279 let half_fan = (0.5 * sino.n_detectors as f64 * detector_spacing_mm).atan2(source_to_detector_mm);
280 for (di, wv) in weighted.iter_mut().enumerate() {
281 let s = (di as f64 - det_mid) * detector_spacing_mm;
282 let cos_g = source_to_detector_mm / (source_to_detector_mm.powi(2) + s * s).sqrt();
283 let gamma = s.atan2(source_to_detector_mm);
284 let pw = if cfg.apply_parker_short_scan && span < 1.9 * PI {
285 parker_weight(angle - min_a, gamma, half_fan)
286 } else {
287 1.0
288 };
289 let mag = source_to_isocenter_mm / source_to_detector_mm;
290 *wv = raw_row[di] * mag * cos_g * pw;
291 }
292 detector_spacing_mm * (source_to_isocenter_mm / source_to_detector_mm)
293 }
294 };
295
296 let filt_row = filter_projection_fft(&weighted, filt_spacing, cfg.filter, cfg.cutoff_ratio)?;
297 let (sin_a, cos_a) = angle.sin_cos();
298
299 for py in 0..cfg.image_height {
300 let y = (py as f64 - img_cy) * cfg.pixel_spacing_mm[0];
301 for px in 0..cfg.image_width {
302 let x = (px as f64 - img_cx) * cfg.pixel_spacing_mm[1];
303 let (det_idx, bp_weight) = match cfg.geometry {
304 ProjectionGeometry::Parallel => {
305 let t = x * cos_a + y * sin_a;
306 (det_mid + t / sino.detector_spacing_mm, 1.0)
307 }
308 ProjectionGeometry::FanEquiangular { source_to_isocenter_mm, detector_arc_spacing_rad } => {
309 let sx = -source_to_isocenter_mm * sin_a;
310 let sy = source_to_isocenter_mm * cos_a;
311 let rx = x - sx;
312 let ry = y - sy;
313 let l_sq = rx * rx + ry * ry;
314 let u = x * cos_a + y * sin_a;
315 let v_dist = source_to_isocenter_mm - (-x * sin_a + y * cos_a);
316 let gamma = u.atan2(v_dist.max(1e-6));
317 (det_mid + gamma / detector_arc_spacing_rad, 0.5 / l_sq.max(1e-6))
318 }
319 ProjectionGeometry::FanEquispaced {
320 source_to_isocenter_mm,
321 source_to_detector_mm,
322 detector_spacing_mm,
323 } => {
324 let u_vec = source_to_isocenter_mm + x * sin_a - y * cos_a;
325 let ratio = source_to_detector_mm / u_vec.max(1e-6);
326 let s = (x * cos_a + y * sin_a) * ratio;
327 let mag_u = (source_to_isocenter_mm / u_vec.max(1e-6)).powi(2);
328 (det_mid + s / detector_spacing_mm, 0.5 * mag_u)
329 }
330 };
331 let val = bilinear_sample(&filt_row, det_idx);
332 staged[py * cfg.image_width + px] += val * bp_weight * d_theta;
333 }
334 }
335 }
336
337 let mut hasher = blake3::Hasher::new();
338 hasher.update(&sino.source_blake3);
339 hasher.update(&(cfg.image_width as u64).to_le_bytes());
340 hasher.update(&(cfg.image_height as u64).to_le_bytes());
341 for v in &staged {
342 hasher.update(&v.to_le_bytes());
343 }
344 output[..out_pixels].copy_from_slice(&staged);
345 Ok(FbpProvenance {
346 source_blake3: sino.source_blake3,
347 derivation_blake3: *hasher.finalize().as_bytes(),
348 image_width: cfg.image_width,
349 image_height: cfg.image_height,
350 filter: cfg.filter,
351 geometry: cfg.geometry,
352 units: sino.units,
353 })
354}