diff --git a/py/smoll/smoll_rs/gaussian.pyi b/py/smoll/smoll_rs/gaussian.pyi index fa7cb48..03ad592 100644 --- a/py/smoll/smoll_rs/gaussian.pyi +++ b/py/smoll/smoll_rs/gaussian.pyi @@ -115,7 +115,7 @@ def gaussian(x: numpy.typing.ArrayLike, p: numpy.typing.ArrayLike) -> numpy.typi r""" p: I, x0, x1, ... xn-1, s0, s1, ..., sn-1, r0, r1, ..., rm-1, o, o0, o1, ..., on-1 r: upper triangle without diagonal of (I-R)*(I+R)^{-1} (Cayley transform), - for 2D: theta(theta/2) + for 2D: r0 = tan(theta/2) x: n 1d arrays, defining coordinates in each dimension """ @@ -123,7 +123,7 @@ def gaussian_pixel_int(x: numpy.typing.ArrayLike, p: numpy.typing.ArrayLike) -> r""" p: I, x0, x1, ... xn-1, s0, s1, ..., sn-1, r0, r1, ..., rm-1, o, o0, o1, ..., on-1 r: upper triangle without diagonal of (I-R)*(I+R)^{-1} (Cayley transform), - for 2D: theta(theta/2) + for 2D: r0 = tan(theta/2) x: n 1d arrays, defining coordinates in each dimension gaussian, but the signal is integrated over each pixel diff --git a/src/filter.rs b/src/filter.rs index dfca1d3..2f4c982 100644 --- a/src/filter.rs +++ b/src/filter.rs @@ -73,6 +73,8 @@ where x } +/// 1D gaussian `exp(-(x - mu)^2 / (2 * sigma^2)) / sqrt(2*pi*sigma^2)` +/// (`sigma` is the standard deviation) pub fn gaussian(x: &[f64], mu: f64, sigma: f64) -> Vec { let a = 2.0 * sigma.powi(2); let b = (a * f64::PI()).sqrt(); @@ -82,6 +84,7 @@ pub fn gaussian(x: &[f64], mu: f64, sigma: f64) -> Vec { } /// Gaussian kernel in frequency space +/// (`sigma` are the standard deviations, one per dimension) pub fn gaussian_kernel(shape: &[usize], sigma: &[f64]) -> Result, D>, Error> where D: Dimension, @@ -100,6 +103,7 @@ where } /// smooth an array using a Gaussian kernel +/// (`sigma` are the standard deviations, one per dimension) pub fn gaussian_smooth<'a, A, D>(array: A, sigma: &[f64]) -> Result, Error> where A: AsArray<'a, f64, D>, @@ -110,3 +114,55 @@ where let kernel = gaussian_kernel::(shape, sigma)?; Ok(ifft((kernel * fft(array.view())?).view())?.mapv(|i| i.re)) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_gaussian_width() { + // sigma is a standard deviation: mean = mu, variance = sigma^2, sum ~= 1 + let (mu, sigma): (f64, f64) = (25.0, 2.3); + let xs: Vec = (-50..201).map(|i| i as f64).collect(); + let g = gaussian(&xs, mu, sigma); + let sum: f64 = g.iter().sum(); + let mean = xs.iter().zip(&g).map(|(x, p)| x * p).sum::() / sum; + let var = xs + .iter() + .zip(&g) + .map(|(x, p)| (x - mean).powi(2) * p) + .sum::() + / sum; + assert!((sum - 1.0).abs() < 1e-6, "sum = {sum}"); + assert!((mean - mu).abs() < 1e-6, "mean = {mean}"); + assert!((var - sigma * sigma).abs() < 1e-6, "var = {var}"); + } + + #[test] + fn test_gaussian_smooth_delta_width() { + // smoothing a delta gives a normalized gaussian whose standard + // deviation is exactly the sigma that was passed in + let (n, m): (usize, usize) = (64, 20); + let sigma = 1.7; + let mut delta = vec![0.0; n]; + delta[m] = 1.0; + let g = gaussian_smooth(&delta, &[sigma]).unwrap(); + let sum: f64 = g.iter().sum(); + let mean: f64 = (0..n) + .map(|i| i as f64) + .zip(&g) + .map(|(x, p)| x * p) + .sum::() + / sum; + let var: f64 = (0..n) + .map(|i| ((i as f64) - mean).powi(2)) + .zip(&g) + .map(|(x2, p)| x2 * p) + .sum::() + / sum; + assert!((sum - 1.0).abs() < 1e-12, "sum = {sum}"); + assert!((mean - m as f64).abs() < 1e-6, "mean = {mean}"); + // the fft kernel is a riemann-sum approximation of the ideal gaussian + assert!((var.sqrt() - sigma).abs() < 1e-5, "std = {}", var.sqrt()); + } +} diff --git a/src/gaussian.rs b/src/gaussian.rs index 0428e10..59db978 100644 --- a/src/gaussian.rs +++ b/src/gaussian.rs @@ -2,7 +2,7 @@ use crate::error::Error; use crate::linalg::{linefit, rotation_from_skew, symmetric_eigen}; use derive_builder::Builder; use derive_getters::Getters; -use itertools::Itertools; +use itertools::{Itertools, izip}; use ndarray::{ Array, Array1, Array2, ArrayView1, AsArray, Axis, Dimension, IntoDimension, Ix1, SliceInfoElem, }; @@ -14,7 +14,7 @@ const FRAC_1_SQRT_2_PI: f64 = 0.398942280401432677939946059934381868475858631164 /// p: I, x0, x1, ... xn-1, s0, s1, ..., sn-1, r0, r1, ..., rm-1, o, o0, o1, ..., on-1 /// r: upper triangle without diagonal of (I-R)*(I+R)^{-1} (Cayley transform), -/// for 2D: theta(theta/2) +/// for 2D: r0 = tan(theta/2) /// x: n 1d arrays, defining coordinates in each dimension pub fn gaussian<'a, A, D>(x: Vec, p: &[f64]) -> Result, Error> where @@ -34,8 +34,10 @@ where let r = rotation_from_skew(&p[1 + 2 * n..1 + 2 * n + n2])?; // n * (n - 1) / 2 upper triangle rotation let o = p[1 + 2 * n + n2]; let q = ArrayView1::from(&p[2 + 2 * n + n2..]); // n tilted offset - let c = r.dot(&Array2::from_diag(&s.mapv(|i| 1.0 / i))).dot(&r.t()); // inverse covariance matrix - let a = p[0] * FRAC_1_SQRT_2_PI.powi(n as i32) / s.product().sqrt(); + let c = r + .dot(&Array2::from_diag(&s.mapv(|i| i.powi(-2)))) + .dot(&r.t()); // inverse covariance matrix + let a = p[0] * FRAC_1_SQRT_2_PI.powi(n as i32) / s.product(); let x = x .into_iter() @@ -59,7 +61,7 @@ where /// p: I, x0, x1, ... xn-1, s0, s1, ..., sn-1, r0, r1, ..., rm-1, o, o0, o1, ..., on-1 /// r: upper triangle without diagonal of (I-R)*(I+R)^{-1} (Cayley transform), -/// for 2D: theta(theta/2) +/// for 2D: r0 = tan(theta/2) /// x: n 1d arrays, defining coordinates in each dimension /// gaussian, but the signal is integrated over each pixel /// @@ -92,7 +94,7 @@ where let r = rotation_from_skew(&p[1 + 2 * n..1 + 2 * n + n2])?; // n * (n - 1) / 2 upper triangle rotation let o = p[1 + 2 * n + n2]; let q = ArrayView1::from(&p[2 + 2 * n + n2..]); // n tilted offset - let c = r.dot(&Array2::from_diag(&s)).dot(&r.t()); // inverse covariance matrix + let c = r.dot(&Array2::from_diag(&s.mapv(|i| i * i))).dot(&r.t()); // covariance matrix; its eigenvalues are the variances let (w, ev) = symmetric_eigen(&c); let wmax = w.iter().copied().fold(0.0f64, f64::max); let tol = (n as f64) * f64::EPSILON * wmax; @@ -129,12 +131,19 @@ pub enum BackgroundSubtraction { #[strum(ascii_case_insensitive)] #[default] None, + /// a single offset is estimated from the window edges and subtracted #[strum(ascii_case_insensitive)] Constant, + /// a linear background is estimated: the slopes are fitted independently + /// along each coordinate axis from the faces perpendicular to it #[strum(ascii_case_insensitive)] Tilted, } +/// `background` is `[offset, slope_0, ..., slope_{n-1}]`, in axis order: the +/// fitted linear background is `offset + sum_d slope_d * (x_d - center_d)`, +/// with one slope per unit coordinate per dimension and the offset anchored +/// at the fitted spot center. #[derive(Debug, Clone, Getters, PartialEq)] pub struct ModalAnalysisResult { iterations: usize, @@ -286,36 +295,37 @@ impl ModalAnalysis { } BackgroundSubtraction::Tilted => { let mut bg = vec![0.0]; - let mut slice = vec![ - SliceInfoElem::Slice { + let mut slice = self + .window_shape + .iter() + .map(|&si| SliceInfoElem::Slice { start: 0, end: None, - step: 1 + step: (si as isize - 1).max(1), + }) + .collect::>(); + for (d, (&si, &oi, &xi)) in izip!(&self.window_shape, &win_orig, &x).enumerate() + { + slice[d] = SliceInfoElem::Slice { + start: 0, + end: None, + step: 1, }; - ndim - ]; - let mut perm = Vec::from_iter(1..ndim); - perm.push(0); - let perm = perm.into_dimension(); - // rotate axes, for each dimension fitting edges with y = a*x + b - bg.extend(self.window_shape.iter().zip(&win_orig).zip(&x).map( - |((&si, &oi), &xi)| { - let mut xx = Vec::from_iter(0..si); - xx.extend(0..si); - let xx = Array1::from_vec(xx).mapv(|i| oi as f64 - xi + i as f64); - slice[0] = SliceInfoElem::Slice { - start: 0, - end: None, - step: (si as isize - 1).max(1), - }; - let yy = gs.slice(slice.as_slice()); - let (a, _) = linefit(xx.view(), yy.flatten()); - gs = &gs - - a * Array1::from_iter(0..si).mapv(|i| oi as f64 - xi + i as f64); - gs.permute_axes(perm.clone()); - a - }, - )); + let yy = gs.slice(slice.as_slice()); + let xx = yy + .indexed_iter() + .map(|(i, _)| oi as f64 - xi + i.as_array_view()[d] as f64) + .collect::>(); + let (a, _) = linefit(xx.view(), yy.flatten()); + let mut cshape = vec![1usize; ndim]; + cshape[d] = si; + let xx = Array::from_shape_vec( + cshape, + (0..si).map(|i| oi as f64 - xi + i as f64).collect(), + )?; + gs = &gs - a * xx; + bg.push(a); + } slice = vec![ SliceInfoElem::Slice { start: 0, @@ -496,7 +506,7 @@ mod tests { let (i_, mx, my): (f64, f64, f64) = (1.0, 2.3, 5.1); let (w1, w2): (f64, f64) = (1.44, 0.7225); let (o, qx, qy): (f64, f64, f64) = (0.05, 0.08, -0.06); - let p = vec![i_, mx, my, w1.sqrt(), 0.0, 0.0, w2.sqrt(), o, qx, qy]; + let p = vec![i_, mx, my, w1.sqrt(), w2.sqrt(), 0.0, o, qx, qy]; let xv = Array1::from_vec((0..8).map(|i| i as f64).collect()); let yv = Array1::from_vec((0..8).map(|i| i as f64).collect()); let x = vec![&xv, &yv]; @@ -536,22 +546,23 @@ mod tests { fn test_gaussian_pixel_int_rotated() -> Result<(), Error> { // non-diagonal covariance: compare against the product-form // computed independently from the closed-form 2x2 eigenvalues + // covariance C = R(*th) * diag(d1, d2) * R(*th)^T, + // i.e. sigmas sqrt(d1), sqrt(d2) and rotation parameter tan(th/2) let th = 0.6_f64; let (ct, st) = (th.cos(), th.sin()); let (d1, d2): (f64, f64) = (0.7225, 1.44); let c11 = d1 * ct * ct + d2 * st * st; let c22 = d1 * st * st + d2 * ct * ct; - let c12 = (d2 - d1) * st * ct; + let c12 = (d1 - d2) * st * ct; let (i_, mx, my, o) = (1.0, 3.0, 5.5, 0.2); let (qx, qy) = (0.1, -0.05); let p = vec![ i_, mx, my, - c11.sqrt(), - c12.sqrt(), - c12.sqrt(), - c22.sqrt(), + d1.sqrt(), + d2.sqrt(), + (th / 2.0).tan(), o, qx, qy, @@ -627,19 +638,31 @@ mod tests { let x = vec![&xv, &yv]; let mut m = ModalAnalysisBuilder::default() .sigma(vec![3.0; 2]) - .window_shape([5; 2]) + .window_shape([15; 2]) .build()?; + let check = |p: &ModalAnalysisResult| { + assert!((p.position()[0] - 32.3).abs() < 0.05, "{p:?}"); + assert!((p.position()[1] - 31.5).abs() < 0.05, "{p:?}"); + }; let g = gaussian::<_, Ix2>(x.clone(), &[1.0, 32.3, 31.5, 3.0, 3.0, 0.0, 0.0, 0.0, 0.0])?; let p = m.fit(&g, &[32.0; 2])?; - println!("p: {:?}", p); + assert!((p.integrated_intensity() - 1.0).abs() < 1e-2, "{p:?}"); + check(&p); let g = gaussian::<_, Ix2>(x.clone(), &[1.0, 32.3, 31.5, 3.0, 3.0, 0.0, 4.0, 0.0, 0.0])?; m.background_subtraction = BackgroundSubtraction::Constant; let p = m.fit(&g, &[32.0; 2])?; - println!("p: {:?}", p); + assert!((p.background()[0] - 4.0).abs() < 1e-2, "{p:?}"); + assert!((p.integrated_intensity() - 1.0).abs() < 0.1, "{p:?}"); + check(&p); let g = gaussian::<_, Ix2>(x, &[1.0, 32.3, 31.5, 3.0, 3.0, 0.0, 4.0, -1.0, 2.0])?; m.background_subtraction = BackgroundSubtraction::Tilted; let p = m.fit(&g, &[32.0; 2])?; - println!("p: {:?}", p); + // background = [offset, slope0, slope1] + assert!((p.background()[0] - 4.0).abs() < 0.2, "{p:?}"); + assert!((p.background()[1] + 1.0).abs() < 1e-2, "{p:?}"); + assert!((p.background()[2] - 2.0).abs() < 1e-2, "{p:?}"); + assert!((p.integrated_intensity() - 1.0).abs() < 0.1, "{p:?}"); + check(&p); Ok(()) } } diff --git a/src/lib.rs b/src/lib.rs index 0ce4076..03e2a8c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,3 +1,5 @@ +//! single MOLecule Localization + pub mod detection; pub mod error; pub mod filter; diff --git a/src/py/gaussian.rs b/src/py/gaussian.rs index ab6de53..f465208 100644 --- a/src/py/gaussian.rs +++ b/src/py/gaussian.rs @@ -7,7 +7,7 @@ use pyo3_stub_gen::derive::*; /// p: I, x0, x1, ... xn-1, s0, s1, ..., sn-1, r0, r1, ..., rm-1, o, o0, o1, ..., on-1 /// r: upper triangle without diagonal of (I-R)*(I+R)^{-1} (Cayley transform), -/// for 2D: theta(theta/2) +/// for 2D: r0 = tan(theta/2) /// x: n 1d arrays, defining coordinates in each dimension #[gen_stub_pyfunction(module = "smoll.gaussian")] #[pyfunction] @@ -36,7 +36,7 @@ pub(crate) fn gaussian<'py>( /// p: I, x0, x1, ... xn-1, s0, s1, ..., sn-1, r0, r1, ..., rm-1, o, o0, o1, ..., on-1 /// r: upper triangle without diagonal of (I-R)*(I+R)^{-1} (Cayley transform), -/// for 2D: theta(theta/2) +/// for 2D: r0 = tan(theta/2) /// x: n 1d arrays, defining coordinates in each dimension /// /// gaussian, but the signal is integrated over each pixel