qualia_core_db/medical/reconstruction/
mri.rs1use super::spectral_fft::{fft_2d, fft_3d, fftshift_1d, fftshift_3d, validate_finite_complex};
4use crate::solvers::transforms::fourier::Cplx;
5
6#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7pub enum MriError {
8 DimensionMismatch,
9 InvalidAccelFactor,
10 MissingCoilData,
11 NonFiniteInput,
12 SingularSenseSystem,
13 Overflow,
14}
15
16impl std::fmt::Display for MriError {
17 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
18 write!(f, "MRI reconstruction error: {self:?}")
19 }
20}
21impl std::error::Error for MriError {}
22
23#[derive(Clone, Copy, Debug)]
24pub struct MriKspaceConfig {
25 pub slices: usize,
26 pub rows: usize,
27 pub cols: usize,
28 pub ifftshift_kspace: bool,
29 pub fftshift_image: bool,
30 pub unitary_scaling: bool,
31}
32
33#[derive(Clone, Debug)]
34pub struct MriComplexVolume {
35 pub source_blake3: [u8; 32],
36 pub derivation_blake3: [u8; 32],
37 pub slices: usize,
38 pub rows: usize,
39 pub cols: usize,
40 pub complex: Vec<Cplx>,
41 pub magnitude: Vec<f64>,
42 pub phase_rad: Vec<f64>,
43}
44
45#[derive(Clone, Debug)]
46pub struct SenseOutput {
47 pub derivation_blake3: [u8; 32],
48 pub rows: usize,
49 pub cols: usize,
50 pub complex: Vec<Cplx>,
51 pub magnitude: Vec<f64>,
52 pub phase_rad: Vec<f64>,
53 pub g_factor: Vec<f64>,
54}
55
56fn c_mul(a: Cplx, b: Cplx) -> Cplx {
57 (a.0 * b.0 - a.1 * b.1, a.0 * b.1 + a.1 * b.0)
58}
59
60fn c_conj(a: Cplx) -> Cplx {
61 (a.0, -a.1)
62}
63
64fn c_div(a: Cplx, b: Cplx) -> Result<Cplx, MriError> {
65 let denom = b.0 * b.0 + b.1 * b.1;
66 if denom <= 1e-30 || !denom.is_finite() {
67 return Err(MriError::SingularSenseSystem);
68 }
69 Ok(((a.0 * b.0 + a.1 * b.1) / denom, (a.1 * b.0 - a.0 * b.1) / denom))
70}
71
72fn shift_2d(data: &[Cplx], rows: usize, cols: usize, inverse: bool) -> Vec<Cplx> {
73 let mut tmp = vec![(0.0, 0.0); data.len()];
74 let mut row_tmp = vec![(0.0, 0.0); cols];
75 for r in 0..rows {
76 let src = &data[r * cols..(r + 1) * cols];
77 if inverse {
78 crate::medical::reconstruction::spectral_fft::ifftshift_1d(src, &mut row_tmp);
79 } else {
80 fftshift_1d(src, &mut row_tmp);
81 }
82 tmp[r * cols..(r + 1) * cols].copy_from_slice(&row_tmp);
83 }
84 let split = if inverse { rows.div_ceil(2) } else { rows / 2 };
85 let mut out = vec![(0.0, 0.0); data.len()];
86 for r in 0..rows {
87 let dr = (r + (rows - split)) % rows;
88 out[dr * cols..(dr + 1) * cols].copy_from_slice(&tmp[r * cols..(r + 1) * cols]);
89 }
90 out
91}
92
93fn hash_complex_slice(source_blake3: [u8; 32], complex: &[Cplx]) -> [u8; 32] {
94 let mut hasher = blake3::Hasher::new();
95 hasher.update(&source_blake3);
96 for &(re, im) in complex {
97 hasher.update(&re.to_le_bytes());
98 hasher.update(&im.to_le_bytes());
99 }
100 *hasher.finalize().as_bytes()
101}
102
103pub fn reconstruct_mri_kspace_2d(
104 kspace: &[Cplx],
105 rows: usize,
106 cols: usize,
107 source_blake3: [u8; 32],
108 ifftshift_kspace: bool,
109 fftshift_image: bool,
110 unitary_scaling: bool,
111) -> Result<MriComplexVolume, MriError> {
112 reconstruct_mri_kspace_3d(
113 kspace,
114 MriKspaceConfig {
115 slices: 1,
116 rows,
117 cols,
118 ifftshift_kspace,
119 fftshift_image,
120 unitary_scaling,
121 },
122 source_blake3,
123 )
124}
125
126pub fn reconstruct_mri_kspace_3d(
127 kspace: &[Cplx],
128 cfg: MriKspaceConfig,
129 source_blake3: [u8; 32],
130) -> Result<MriComplexVolume, MriError> {
131 let n = cfg
132 .slices
133 .checked_mul(cfg.rows)
134 .and_then(|v| v.checked_mul(cfg.cols))
135 .ok_or(MriError::Overflow)?;
136 if n == 0 || kspace.len() != n {
137 return Err(MriError::DimensionMismatch);
138 }
139 validate_finite_complex(kspace).map_err(|_| MriError::NonFiniteInput)?;
140
141 let prep = if cfg.ifftshift_kspace {
142 if cfg.slices == 1 {
143 shift_2d(kspace, cfg.rows, cfg.cols, true)
144 } else {
145 fftshift_3d(kspace, cfg.slices, cfg.rows, cfg.cols, true)
146 .map_err(|_| MriError::DimensionMismatch)?
147 }
148 } else {
149 kspace.to_vec()
150 };
151
152 let mut img = if cfg.slices == 1 {
153 fft_2d(&prep, cfg.rows, cfg.cols, true).map_err(|_| MriError::NonFiniteInput)?
154 } else {
155 fft_3d(&prep, cfg.slices, cfg.rows, cfg.cols, true).map_err(|_| MriError::NonFiniteInput)?
156 };
157
158 if cfg.unitary_scaling {
159 let u_scale = (n as f64).sqrt();
160 for v in &mut img {
161 v.0 *= u_scale;
162 v.1 *= u_scale;
163 }
164 }
165
166 if cfg.fftshift_image {
167 img = if cfg.slices == 1 {
168 shift_2d(&img, cfg.rows, cfg.cols, false)
169 } else {
170 fftshift_3d(&img, cfg.slices, cfg.rows, cfg.cols, false)
171 .map_err(|_| MriError::DimensionMismatch)?
172 };
173 }
174
175 let magnitude: Vec<f64> = img.iter().map(|&(re, im)| re.hypot(im)).collect();
176 let phase_rad: Vec<f64> = img.iter().map(|&(re, im)| im.atan2(re)).collect();
177 let derivation_blake3 = hash_complex_slice(source_blake3, &img);
178
179 Ok(MriComplexVolume {
180 source_blake3,
181 derivation_blake3,
182 slices: cfg.slices,
183 rows: cfg.rows,
184 cols: cfg.cols,
185 complex: img,
186 magnitude,
187 phase_rad,
188 })
189}
190
191pub fn combine_coils_sos(coil_images: &[&[Cplx]], noise_std: Option<&[f64]>) -> Result<Vec<f64>, MriError> {
193 if coil_images.is_empty() || coil_images[0].is_empty() {
194 return Err(MriError::MissingCoilData);
195 }
196 let n = coil_images[0].len();
197 for &c in coil_images {
198 if c.len() != n {
199 return Err(MriError::DimensionMismatch);
200 }
201 validate_finite_complex(c).map_err(|_| MriError::NonFiniteInput)?;
202 }
203 if let Some(sig) = noise_std {
204 if sig.len() != coil_images.len() || sig.iter().any(|&s| !s.is_finite() || s <= 0.0) {
205 return Err(MriError::DimensionMismatch);
206 }
207 }
208 let mut out = vec![0.0f64; n];
209 for (ci, &coil) in coil_images.iter().enumerate() {
210 let inv_var = noise_std.map_or(1.0, |s| 1.0 / (s[ci] * s[ci]));
211 for (i, &(re, im)) in coil.iter().enumerate() {
212 out[i] += (re * re + im * im) * inv_var;
213 }
214 }
215 for v in &mut out {
216 *v = v.sqrt();
217 }
218 Ok(out)
219}
220
221fn invert_complex_matrix(mat: &[Cplx], r: usize) -> Result<Vec<Cplx>, MriError> {
223 let mut a = mat.to_vec();
224 let mut inv = vec![(0.0, 0.0); r * r];
225 for i in 0..r {
226 inv[i * r + i] = (1.0, 0.0);
227 }
228 for col in 0..r {
229 let mut piv = col;
230 let mut best_mag = a[col * r + col].0.hypot(a[col * r + col].1);
231 for row in (col + 1)..r {
232 let m = a[row * r + col].0.hypot(a[row * r + col].1);
233 if m > best_mag {
234 best_mag = m;
235 piv = row;
236 }
237 }
238 if best_mag <= 1e-14 || !best_mag.is_finite() {
239 return Err(MriError::SingularSenseSystem);
240 }
241 if piv != col {
242 for k in 0..r {
243 a.swap(col * r + k, piv * r + k);
244 inv.swap(col * r + k, piv * r + k);
245 }
246 }
247 let diag = a[col * r + col];
248 for k in 0..r {
249 a[col * r + k] = c_div(a[col * r + k], diag)?;
250 inv[col * r + k] = c_div(inv[col * r + k], diag)?;
251 }
252 for row in 0..r {
253 if row == col {
254 continue;
255 }
256 let factor = a[row * r + col];
257 if factor == (0.0, 0.0) {
258 continue;
259 }
260 for k in 0..r {
261 let sub_a = c_mul(factor, a[col * r + k]);
262 let sub_i = c_mul(factor, inv[col * r + k]);
263 a[row * r + k].0 -= sub_a.0;
264 a[row * r + k].1 -= sub_a.1;
265 inv[row * r + k].0 -= sub_i.0;
266 inv[row * r + k].1 -= sub_i.1;
267 }
268 }
269 }
270 Ok(inv)
271}
272
273pub fn combine_coils_sense(
277 aliased_coil_images: &[&[Cplx]],
278 sensitivity_maps: &[&[Cplx]],
279 rows: usize,
280 cols: usize,
281 accel_r: usize,
282 noise_cov_inv_diag: Option<&[f64]>,
283 reg_lambda: f64,
284 source_blake3: [u8; 32],
285) -> Result<SenseOutput, MriError> {
286 if accel_r == 0 || rows == 0 || cols == 0 || rows % accel_r != 0 {
287 return Err(MriError::InvalidAccelFactor);
288 }
289 let nc = aliased_coil_images.len();
290 if nc == 0 || sensitivity_maps.len() != nc || nc < accel_r {
291 return Err(MriError::MissingCoilData);
292 }
293 let red_rows = rows / accel_r;
294 let red_len = red_rows * cols;
295 let full_len = rows * cols;
296 for c in 0..nc {
297 if aliased_coil_images[c].len() != red_len || sensitivity_maps[c].len() != full_len {
298 return Err(MriError::DimensionMismatch);
299 }
300 validate_finite_complex(aliased_coil_images[c]).map_err(|_| MriError::NonFiniteInput)?;
301 validate_finite_complex(sensitivity_maps[c]).map_err(|_| MriError::NonFiniteInput)?;
302 }
303 if let Some(inv_var) = noise_cov_inv_diag {
304 if inv_var.len() != nc || inv_var.iter().any(|&v| !v.is_finite() || v <= 0.0) {
305 return Err(MriError::DimensionMismatch);
306 }
307 }
308
309 let mut out_cx = vec![(0.0, 0.0); full_len];
310 let mut g_factor = vec![1.0; full_len];
311
312 for y0 in 0..red_rows {
313 for x in 0..cols {
314 let mut sh_psi_s = vec![(0.0, 0.0); accel_r * accel_r];
315 let mut sh_psi_m = vec![(0.0, 0.0); accel_r];
316 for c in 0..nc {
317 let psi = noise_cov_inv_diag.map_or(1.0, |v| v[c]);
318 let m_val = aliased_coil_images[c][y0 * cols + x];
319 for r1 in 0..accel_r {
320 let y1 = y0 + r1 * red_rows;
321 let s1_conj = c_conj(sensitivity_maps[c][y1 * cols + x]);
322 let term_m = c_mul(s1_conj, m_val);
323 sh_psi_m[r1].0 += psi * term_m.0;
324 sh_psi_m[r1].1 += psi * term_m.1;
325 for r2 in 0..accel_r {
326 let y2 = y0 + r2 * red_rows;
327 let s2 = sensitivity_maps[c][y2 * cols + x];
328 let prod = c_mul(s1_conj, s2);
329 sh_psi_s[r1 * accel_r + r2].0 += psi * prod.0;
330 sh_psi_s[r1 * accel_r + r2].1 += psi * prod.1;
331 }
332 }
333 }
334 let unreg_diag: Vec<f64> = (0..accel_r).map(|r| sh_psi_s[r * accel_r + r].0).collect();
336 for r in 0..accel_r {
337 sh_psi_s[r * accel_r + r].0 += reg_lambda.max(0.0);
338 }
339 let a_inv = invert_complex_matrix(&sh_psi_s, accel_r)?;
340 for r in 0..accel_r {
341 let y = y0 + r * red_rows;
342 let mut rho = (0.0, 0.0);
343 for k in 0..accel_r {
344 let t = c_mul(a_inv[r * accel_r + k], sh_psi_m[k]);
345 rho.0 += t.0;
346 rho.1 += t.1;
347 }
348 out_cx[y * cols + x] = rho;
349 let g_sq = (a_inv[r * accel_r + r].0 * unreg_diag[r]).max(1.0);
350 g_factor[y * cols + x] = g_sq.sqrt();
351 }
352 }
353 }
354
355 let magnitude = out_cx.iter().map(|&(re, im)| re.hypot(im)).collect();
356 let phase_rad = out_cx.iter().map(|&(re, im)| im.atan2(re)).collect();
357 let derivation_blake3 = hash_complex_slice(source_blake3, &out_cx);
358 Ok(SenseOutput {
359 derivation_blake3,
360 rows,
361 cols,
362 complex: out_cx,
363 magnitude,
364 phase_rad,
365 g_factor,
366 })
367}