- change modal analysis tilted background fit

This commit is contained in:
Wim Pomp committed 2026-11-24 16:35:04 +01:00
1 parent b3c7bf1461
commit 3e53827d83
5 files changed
+125 -44

No files matched your search

+2 -2
View File
@@ -115,7 +115,7 @@ def gaussian(x: numpy.typing.ArrayLike, p: numpy.typing.ArrayLike) -> numpy.typi
r""" r"""
p: I, x0, x1, ... xn-1, s0, s1, ..., sn-1, r0, r1, ..., rm-1, o, o0, o1, ..., on-1 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), 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 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""" r"""
p: I, x0, x1, ... xn-1, s0, s1, ..., sn-1, r0, r1, ..., rm-1, o, o0, o1, ..., on-1 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), 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 x: n 1d arrays, defining coordinates in each dimension
gaussian, but the signal is integrated over each pixel gaussian, but the signal is integrated over each pixel
+56
View File
@@ -73,6 +73,8 @@ where
x 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<f64> { pub fn gaussian(x: &[f64], mu: f64, sigma: f64) -> Vec<f64> {
let a = 2.0 * sigma.powi(2); let a = 2.0 * sigma.powi(2);
let b = (a * f64::PI()).sqrt(); let b = (a * f64::PI()).sqrt();
@@ -82,6 +84,7 @@ pub fn gaussian(x: &[f64], mu: f64, sigma: f64) -> Vec<f64> {
} }
/// Gaussian kernel in frequency space /// Gaussian kernel in frequency space
/// (`sigma` are the standard deviations, one per dimension)
pub fn gaussian_kernel<D>(shape: &[usize], sigma: &[f64]) -> Result<Array<Complex<f64>, D>, Error> pub fn gaussian_kernel<D>(shape: &[usize], sigma: &[f64]) -> Result<Array<Complex<f64>, D>, Error>
where where
D: Dimension, D: Dimension,
@@ -100,6 +103,7 @@ where
} }
/// smooth an array using a Gaussian kernel /// 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<Array<f64, D>, Error> pub fn gaussian_smooth<'a, A, D>(array: A, sigma: &[f64]) -> Result<Array<f64, D>, Error>
where where
A: AsArray<'a, f64, D>, A: AsArray<'a, f64, D>,
@@ -110,3 +114,55 @@ where
let kernel = gaussian_kernel::<D>(shape, sigma)?; let kernel = gaussian_kernel::<D>(shape, sigma)?;
Ok(ifft((kernel * fft(array.view())?).view())?.mapv(|i| i.re)) 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<f64> = (-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::<f64>() / sum;
let var = xs
.iter()
.zip(&g)
.map(|(x, p)| (x - mean).powi(2) * p)
.sum::<f64>()
/ 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::<f64>()
/ sum;
let var: f64 = (0..n)
.map(|i| ((i as f64) - mean).powi(2))
.zip(&g)
.map(|(x2, p)| x2 * p)
.sum::<f64>()
/ 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());
}
}
+63 -40
View File
@@ -2,7 +2,7 @@ use crate::error::Error;
use crate::linalg::{linefit, rotation_from_skew, symmetric_eigen}; use crate::linalg::{linefit, rotation_from_skew, symmetric_eigen};
use derive_builder::Builder; use derive_builder::Builder;
use derive_getters::Getters; use derive_getters::Getters;
use itertools::Itertools; use itertools::{Itertools, izip};
use ndarray::{ use ndarray::{
Array, Array1, Array2, ArrayView1, AsArray, Axis, Dimension, IntoDimension, Ix1, SliceInfoElem, 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 /// 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), /// 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 /// x: n 1d arrays, defining coordinates in each dimension
pub fn gaussian<'a, A, D>(x: Vec<A>, p: &[f64]) -> Result<Array<f64, D>, Error> pub fn gaussian<'a, A, D>(x: Vec<A>, p: &[f64]) -> Result<Array<f64, D>, Error>
where 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 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 o = p[1 + 2 * n + n2];
let q = ArrayView1::from(&p[2 + 2 * n + n2..]); // n tilted offset 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 c = r
let a = p[0] * FRAC_1_SQRT_2_PI.powi(n as i32) / s.product().sqrt(); .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 let x = x
.into_iter() .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 /// 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), /// 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 /// x: n 1d arrays, defining coordinates in each dimension
/// gaussian, but the signal is integrated over each pixel /// 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 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 o = p[1 + 2 * n + n2];
let q = ArrayView1::from(&p[2 + 2 * n + n2..]); // n tilted offset 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 (w, ev) = symmetric_eigen(&c);
let wmax = w.iter().copied().fold(0.0f64, f64::max); let wmax = w.iter().copied().fold(0.0f64, f64::max);
let tol = (n as f64) * f64::EPSILON * wmax; let tol = (n as f64) * f64::EPSILON * wmax;
@@ -129,12 +131,19 @@ pub enum BackgroundSubtraction {
#[strum(ascii_case_insensitive)] #[strum(ascii_case_insensitive)]
#[default] #[default]
None, None,
/// a single offset is estimated from the window edges and subtracted
#[strum(ascii_case_insensitive)] #[strum(ascii_case_insensitive)]
Constant, 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)] #[strum(ascii_case_insensitive)]
Tilted, 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)] #[derive(Debug, Clone, Getters, PartialEq)]
pub struct ModalAnalysisResult { pub struct ModalAnalysisResult {
iterations: usize, iterations: usize,
@@ -286,36 +295,37 @@ impl ModalAnalysis {
} }
BackgroundSubtraction::Tilted => { BackgroundSubtraction::Tilted => {
let mut bg = vec![0.0]; let mut bg = vec![0.0];
let mut slice = vec![ let mut slice = self
SliceInfoElem::Slice { .window_shape
start: 0, .iter()
end: None, .map(|&si| SliceInfoElem::Slice {
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, start: 0,
end: None, end: None,
step: (si as isize - 1).max(1), step: (si as isize - 1).max(1),
})
.collect::<Vec<_>>();
for (d, (&si, &oi, &xi)) in izip!(&self.window_shape, &win_orig, &x).enumerate()
{
slice[d] = SliceInfoElem::Slice {
start: 0,
end: None,
step: 1,
}; };
let yy = gs.slice(slice.as_slice()); 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::<Array1<_>>();
let (a, _) = linefit(xx.view(), yy.flatten()); let (a, _) = linefit(xx.view(), yy.flatten());
gs = &gs let mut cshape = vec![1usize; ndim];
- a * Array1::from_iter(0..si).mapv(|i| oi as f64 - xi + i as f64); cshape[d] = si;
gs.permute_axes(perm.clone()); let xx = Array::from_shape_vec(
a cshape,
}, (0..si).map(|i| oi as f64 - xi + i as f64).collect(),
)); )?;
gs = &gs - a * xx;
bg.push(a);
}
slice = vec![ slice = vec![
SliceInfoElem::Slice { SliceInfoElem::Slice {
start: 0, start: 0,
@@ -496,7 +506,7 @@ mod tests {
let (i_, mx, my): (f64, f64, f64) = (1.0, 2.3, 5.1); let (i_, mx, my): (f64, f64, f64) = (1.0, 2.3, 5.1);
let (w1, w2): (f64, f64) = (1.44, 0.7225); let (w1, w2): (f64, f64) = (1.44, 0.7225);
let (o, qx, qy): (f64, f64, f64) = (0.05, 0.08, -0.06); 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 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 yv = Array1::from_vec((0..8).map(|i| i as f64).collect());
let x = vec![&xv, &yv]; let x = vec![&xv, &yv];
@@ -536,22 +546,23 @@ mod tests {
fn test_gaussian_pixel_int_rotated() -> Result<(), Error> { fn test_gaussian_pixel_int_rotated() -> Result<(), Error> {
// non-diagonal covariance: compare against the product-form // non-diagonal covariance: compare against the product-form
// computed independently from the closed-form 2x2 eigenvalues // 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 th = 0.6_f64;
let (ct, st) = (th.cos(), th.sin()); let (ct, st) = (th.cos(), th.sin());
let (d1, d2): (f64, f64) = (0.7225, 1.44); let (d1, d2): (f64, f64) = (0.7225, 1.44);
let c11 = d1 * ct * ct + d2 * st * st; let c11 = d1 * ct * ct + d2 * st * st;
let c22 = d1 * st * st + d2 * ct * ct; 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 (i_, mx, my, o) = (1.0, 3.0, 5.5, 0.2);
let (qx, qy) = (0.1, -0.05); let (qx, qy) = (0.1, -0.05);
let p = vec![ let p = vec![
i_, i_,
mx, mx,
my, my,
c11.sqrt(), d1.sqrt(),
c12.sqrt(), d2.sqrt(),
c12.sqrt(), (th / 2.0).tan(),
c22.sqrt(),
o, o,
qx, qx,
qy, qy,
@@ -627,19 +638,31 @@ mod tests {
let x = vec![&xv, &yv]; let x = vec![&xv, &yv];
let mut m = ModalAnalysisBuilder::default() let mut m = ModalAnalysisBuilder::default()
.sigma(vec![3.0; 2]) .sigma(vec![3.0; 2])
.window_shape([5; 2]) .window_shape([15; 2])
.build()?; .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 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])?; 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])?; 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; m.background_subtraction = BackgroundSubtraction::Constant;
let p = m.fit(&g, &[32.0; 2])?; 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])?; 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; m.background_subtraction = BackgroundSubtraction::Tilted;
let p = m.fit(&g, &[32.0; 2])?; 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(()) Ok(())
} }
} }
+2
View File
@@ -1,3 +1,5 @@
//! single MOLecule Localization
pub mod detection; pub mod detection;
pub mod error; pub mod error;
pub mod filter; pub mod filter;
+2 -2
View File
@@ -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 /// 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), /// 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 /// x: n 1d arrays, defining coordinates in each dimension
#[gen_stub_pyfunction(module = "smoll.gaussian")] #[gen_stub_pyfunction(module = "smoll.gaussian")]
#[pyfunction] #[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 /// 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), /// 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 /// x: n 1d arrays, defining coordinates in each dimension
/// ///
/// gaussian, but the signal is integrated over each pixel /// gaussian, but the signal is integrated over each pixel