qualia_core_db/medical/reconstruction/
pet_osem.rs1#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6pub enum OsemError {
7 DimensionMismatch,
8 InvalidConfig(&'static str),
9 NonFiniteInput,
10 NegativeMeasurements,
11 Overflow,
12}
13
14impl std::fmt::Display for OsemError {
15 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
16 write!(f, "PET OSEM reconstruction error: {self:?}")
17 }
18}
19impl std::error::Error for OsemError {}
20
21#[derive(Clone, Copy, Debug)]
22pub struct OsemConfig {
23 pub image_width: usize,
24 pub image_height: usize,
25 pub pixel_size_mm: f64,
26 pub subsets: usize,
27 pub iterations: usize,
28 pub min_sensitivity: f64,
29 pub initial_activity: f64,
30}
31
32#[derive(Clone, Debug)]
33pub struct PetSinogram<'a> {
34 pub source_blake3: [u8; 32],
35 pub n_angles: usize,
36 pub n_bins: usize,
37 pub bin_spacing_mm: f64,
38 pub angles_rad: &'a [f64],
39 pub prompts: &'a [f64],
40 pub attenuation_factors: Option<&'a [f64]>,
41 pub normalization_factors: Option<&'a [f64]>,
42}
43
44#[derive(Clone, Debug)]
45pub struct OsemResult {
46 pub source_blake3: [u8; 32],
47 pub derivation_blake3: [u8; 32],
48 pub sensitivity_image: Vec<f64>,
49 pub per_iteration_l1_residual: Vec<f64>,
50 pub total_measured_counts: f64,
51 pub total_forward_counts: f64,
52 pub min_voxel: f64,
53}
54
55pub fn trace_ray_into(
58 angle_rad: f64,
59 radial_u_mm: f64,
60 width: usize,
61 height: usize,
62 pixel_size_mm: f64,
63 out_sparse: &mut Vec<(usize, f64)>,
64) {
65 out_sparse.clear();
66 let (sin_t, cos_t) = angle_rad.sin_cos();
67 let ox = radial_u_mm * cos_t;
68 let oy = radial_u_mm * sin_t;
69 let dx = -sin_t;
70 let dy = cos_t;
71
72 let half_w = 0.5 * width as f64 * pixel_size_mm;
73 let half_h = 0.5 * height as f64 * pixel_size_mm;
74
75 let mut t_min = f64::NEG_INFINITY;
76 let mut t_max = f64::INFINITY;
77 if dx.abs() > 1e-12 {
78 let tx0 = (-half_w - ox) / dx;
79 let tx1 = (half_w - ox) / dx;
80 t_min = t_min.max(tx0.min(tx1));
81 t_max = t_max.min(tx0.max(tx1));
82 } else if ox < -half_w || ox > half_w {
83 return;
84 }
85 if dy.abs() > 1e-12 {
86 let ty0 = (-half_h - oy) / dy;
87 let ty1 = (half_h - oy) / dy;
88 t_min = t_min.max(ty0.min(ty1));
89 t_max = t_max.min(ty0.max(ty1));
90 } else if oy < -half_h || oy > half_h {
91 return;
92 }
93 if t_max <= t_min + 1e-9 {
94 return;
95 }
96
97 let mut ts = Vec::with_capacity(width + height + 2);
99 ts.push(t_min);
100 ts.push(t_max);
101 if dx.abs() > 1e-12 {
102 for ix in 1..width {
103 let x_plane = -half_w + ix as f64 * pixel_size_mm;
104 let t = (x_plane - ox) / dx;
105 if t > t_min + 1e-10 && t < t_max - 1e-10 {
106 ts.push(t);
107 }
108 }
109 }
110 if dy.abs() > 1e-12 {
111 for iy in 1..height {
112 let y_plane = -half_h + iy as f64 * pixel_size_mm;
113 let t = (y_plane - oy) / dy;
114 if t > t_min + 1e-10 && t < t_max - 1e-10 {
115 ts.push(t);
116 }
117 }
118 }
119 ts.sort_by(|a, b| a.total_cmp(b));
120
121 for seg in ts.windows(2) {
122 let len = seg[1] - seg[0];
123 if len <= 1e-11 {
124 continue;
125 }
126 let tm = 0.5 * (seg[0] + seg[1]);
127 let mx = ox + tm * dx;
128 let my = oy + tm * dy;
129 let px = ((mx + half_w) / pixel_size_mm).floor() as isize;
130 let py = ((my + half_h) / pixel_size_mm).floor() as isize;
131 if px >= 0 && px < width as isize && py >= 0 && py < height as isize {
132 let idx = (py as usize) * width + (px as usize);
133 if let Some(last) = out_sparse.last_mut() {
134 if last.0 == idx {
135 last.1 += len;
136 continue;
137 }
138 }
139 out_sparse.push((idx, len));
140 }
141 }
142}
143
144pub fn forward_project_pet(
146 image: &[f64],
147 sino: &PetSinogram<'_>,
148 pixel_size_mm: f64,
149 width: usize,
150 height: usize,
151) -> Result<Vec<f64>, OsemError> {
152 if image.len() != width * height || sino.angles_rad.len() != sino.n_angles {
153 return Err(OsemError::DimensionMismatch);
154 }
155 let total_rays = sino.n_angles * sino.n_bins;
156 let mut out = vec![0.0; total_rays];
157 let u_mid = 0.5 * (sino.n_bins - 1) as f64;
158 let mut ray = Vec::new();
159 for (ai, &theta) in sino.angles_rad.iter().enumerate() {
160 for bi in 0..sino.n_bins {
161 let u = (bi as f64 - u_mid) * sino.bin_spacing_mm;
162 trace_ray_into(theta, u, width, height, pixel_size_mm, &mut ray);
163 let idx = ai * sino.n_bins + bi;
164 let acf = sino.attenuation_factors.map_or(1.0, |a| a[idx]);
165 let norm = sino.normalization_factors.map_or(1.0, |n| n[idx]);
166 let w_ray = acf * norm;
167 let mut sum = 0.0;
168 for &(pix, chord) in &ray {
169 sum += chord * image[pix];
170 }
171 out[idx] = sum * w_ray;
172 }
173 }
174 Ok(out)
175}
176
177pub fn reconstruct_pet_osem_into(
178 sino: &PetSinogram<'_>,
179 cfg: &OsemConfig,
180 output: &mut [f64],
181) -> Result<OsemResult, OsemError> {
182 let n_pix = cfg.image_width.checked_mul(cfg.image_height).ok_or(OsemError::Overflow)?;
183 let n_rays = sino.n_angles.checked_mul(sino.n_bins).ok_or(OsemError::Overflow)?;
184 if n_pix == 0 || n_rays == 0 || sino.angles_rad.len() != sino.n_angles || sino.prompts.len() != n_rays {
185 return Err(OsemError::DimensionMismatch);
186 }
187 if output.len() < n_pix {
188 return Err(OsemError::DimensionMismatch);
189 }
190 if cfg.subsets == 0 || cfg.subsets > sino.n_angles || cfg.iterations == 0 || cfg.pixel_size_mm <= 0.0 {
191 return Err(OsemError::InvalidConfig("invalid OSEM subsets, iterations, or pixel size"));
192 }
193 if cfg.initial_activity <= 0.0 || !cfg.initial_activity.is_finite() || sino.bin_spacing_mm <= 0.0 {
194 return Err(OsemError::InvalidConfig("initial_activity and bin_spacing must be positive finite"));
195 }
196 if sino.prompts.iter().any(|&v| !v.is_finite()) || sino.angles_rad.iter().any(|&v| !v.is_finite()) {
197 return Err(OsemError::NonFiniteInput);
198 }
199 if sino.prompts.iter().any(|&v| v < 0.0) {
200 return Err(OsemError::NegativeMeasurements);
201 }
202 for opt in [sino.attenuation_factors, sino.normalization_factors].into_iter().flatten() {
203 if opt.len() != n_rays {
204 return Err(OsemError::DimensionMismatch);
205 }
206 if opt.iter().any(|&v| !v.is_finite() || v < 0.0) {
207 return Err(OsemError::NonFiniteInput);
208 }
209 }
210
211 let u_mid = 0.5 * (sino.n_bins - 1) as f64;
213 let mut subset_rays: Vec<Vec<(usize, Vec<(usize, f64)>)>> = vec![Vec::new(); cfg.subsets];
214 let mut subset_sens: Vec<Vec<f64>> = vec![vec![0.0; n_pix]; cfg.subsets];
215 let mut global_sens = vec![0.0; n_pix];
216 let mut scratch = Vec::new();
217
218 for (ai, &theta) in sino.angles_rad.iter().enumerate() {
219 let sub = ai % cfg.subsets;
220 for bi in 0..sino.n_bins {
221 let ray_idx = ai * sino.n_bins + bi;
222 let u = (bi as f64 - u_mid) * sino.bin_spacing_mm;
223 trace_ray_into(theta, u, cfg.image_width, cfg.image_height, cfg.pixel_size_mm, &mut scratch);
224 if scratch.is_empty() {
225 continue;
226 }
227 let acf = sino.attenuation_factors.map_or(1.0, |a| a[ray_idx]);
228 let norm = sino.normalization_factors.map_or(1.0, |n| n[ray_idx]);
229 let eff = acf * norm;
230 if eff <= 0.0 {
231 continue;
232 }
233 let mut entries = Vec::with_capacity(scratch.len());
234 for &(pix, chord) in &scratch {
235 let w = chord * eff;
236 subset_sens[sub][pix] += w;
237 global_sens[pix] += w;
238 entries.push((pix, w));
239 }
240 subset_rays[sub].push((ray_idx, entries));
241 }
242 }
243
244 let mut estimate = vec![cfg.initial_activity; n_pix];
245 for j in 0..n_pix {
246 if global_sens[j] < cfg.min_sensitivity {
247 estimate[j] = 0.0;
248 }
249 }
250
251 let mut residuals = Vec::with_capacity(cfg.iterations);
252 let mut back_buf = vec![0.0; n_pix];
253
254 for _iter in 0..cfg.iterations {
255 for sub in 0..cfg.subsets {
256 back_buf.fill(0.0);
257 for (ray_idx, entries) in &subset_rays[sub] {
258 let mut fp = 0.0;
259 for &(pix, w) in entries {
260 fp += w * estimate[pix];
261 }
262 if fp <= 1e-18 {
263 continue;
264 }
265 let ratio = sino.prompts[*ray_idx] / fp;
266 for &(pix, w) in entries {
267 back_buf[pix] += w * ratio;
268 }
269 }
270 for j in 0..n_pix {
271 let s = subset_sens[sub][j];
272 if s >= cfg.min_sensitivity {
273 estimate[j] = (estimate[j] * (back_buf[j] / s)).max(0.0);
274 }
275 }
276 }
277 let fwd = forward_project_pet(&estimate, sino, cfg.pixel_size_mm, cfg.image_width, cfg.image_height)?;
278 let l1: f64 = fwd.iter().zip(sino.prompts.iter()).map(|(f, y)| (f - y).abs()).sum();
279 residuals.push(l1);
280 }
281
282 let final_fwd = forward_project_pet(&estimate, sino, cfg.pixel_size_mm, cfg.image_width, cfg.image_height)?;
283 let total_measured_counts = sino.prompts.iter().sum();
284 let total_forward_counts = final_fwd.iter().sum();
285 let min_voxel = estimate.iter().copied().fold(f64::INFINITY, f64::min);
286
287 let mut hasher = blake3::Hasher::new();
288 hasher.update(&sino.source_blake3);
289 for v in &estimate {
290 hasher.update(&v.to_le_bytes());
291 }
292 output[..n_pix].copy_from_slice(&estimate);
293
294 Ok(OsemResult {
295 source_blake3: sino.source_blake3,
296 derivation_blake3: *hasher.finalize().as_bytes(),
297 sensitivity_image: global_sens,
298 per_iteration_l1_residual: residuals,
299 total_measured_counts,
300 total_forward_counts,
301 min_voxel,
302 })
303}