implement gaussian_pixel_int and modal_analysis

This commit is contained in:
w.pomp committed 2026-11-17 11:58:36 +01:00
1 parent 7a0b09c4c1
commit 3f2f01d795
7 files changed
+729 -16

No files matched your search

+1
View File
@@ -20,6 +20,7 @@ num = "0.4"
numpy = { version = "0.30", optional = true } numpy = { version = "0.30", optional = true }
pyo3 = { version = "0.30", features = ["abi3-py311", "anyhow", "generate-import-lib", "multiple-pymethods"], optional = true } pyo3 = { version = "0.30", features = ["abi3-py311", "anyhow", "generate-import-lib", "multiple-pymethods"], optional = true }
pyo3-stub-gen = { version = "0.23", optional = true } pyo3-stub-gen = { version = "0.23", optional = true }
statrs = "0.19"
strum = { version = "0.28", features = ["derive"] } strum = { version = "0.28", features = ["derive"] }
thiserror = "2" thiserror = "2"
+53
View File
@@ -1,11 +1,15 @@
# This file is automatically generated by pyo3_stub_gen # This file is automatically generated by pyo3_stub_gen
# ruff: noqa: E501, F401, F403, F405 # ruff: noqa: E501, F401, F403, F405
import builtins
import numpy import numpy
import numpy.typing import numpy.typing
import typing
__all__ = [ __all__ = [
"gaussian", "gaussian",
"gaussian_pixel_int",
"modal_analysis",
] ]
def gaussian(x: numpy.typing.ArrayLike, p: numpy.typing.ArrayLike) -> numpy.typing.NDArray[numpy.float64]: def gaussian(x: numpy.typing.ArrayLike, p: numpy.typing.ArrayLike) -> numpy.typing.NDArray[numpy.float64]:
@@ -13,3 +17,52 @@ def gaussian(x: numpy.typing.ArrayLike, p: numpy.typing.ArrayLike) -> numpy.typi
x: n 1d arrays, defining coordinates in each dimension x: n 1d arrays, defining coordinates in each dimension
p: I, x0, x1, ... xn, s00, s01, ..., s0n, s10, s11, ..., s1n, ..., sn0, sn1, ..., snn, o, o0, o1, ..., on p: I, x0, x1, ... xn, s00, s01, ..., s0n, s10, s11, ..., s1n, ..., sn0, sn1, ..., snn, o, o0, o1, ..., on
""" """
def gaussian_pixel_int(x: numpy.typing.ArrayLike, p: numpy.typing.ArrayLike) -> numpy.typing.NDArray[numpy.float64]:
r"""
p: I, x0, x1, ... xn, s00, s01, ..., s0n, s10, s11, ..., s1n, ..., sn0, sn1, ..., snn, o, o0, o1, ..., on
x: n 1d arrays, defining coordinates in each dimension
gaussian, but the signal is integrated over each pixel
Pixels are assumed to be unit hypercubes, i.e. pixel `i` in each dimension
covers `[x_i - 1/2, x_i + 1/2]`.
The pixel integral is evaluated as a product of 1D analytic integrals in
the eigenspace of the covariance (exact when the covariance is diagonal,
and the standard product-form approximation otherwise). Eigenvalues below
`n * eps * lambda_max` are treated as zero, in which case that dimension
contributes the point-emitter limit: 1 inside the pixel containing the
center, 1/2 on its boundary, and 0 elsewhere. Unlike `gaussian`, this works
for rank-deficient covariances.
"""
def modal_analysis(
g: numpy.typing.ArrayLike,
x: typing.Sequence[builtins.float],
s: typing.Sequence[builtins.float],
window_size: typing.Sequence[builtins.int],
n_iter: builtins.int,
tolerance: builtins.float,
background_subtraction: builtins.str,
fix_location: builtins.bool,
) -> builtins.list[builtins.float]:
r"""
Applies the algorithm from [Thompson et al. (2002) PNAS, 82:2775].
Parameters:
- g: an array with the image
- x: approximate coordinates of the spot to localize
- s: sigma
- fix_location: If 1, applied the iterative localization refinement algorithm, starting with the coordinates provided in coo. If 0, only measures the spot intensity at the coordinates provided in coo.
- background_subtraction: 0 -> no background subtraction. 1 -> constant background subtraction. 2 -> tilted plane background subtraction.
- window_size: size of the window (in pixels) around the position in coo, used for the iterative localization and for the background subtraction.
- tolerance: cutoff to determine convergence, i.e. the distance (in pixels) between two iterations
- n_iter: the maximal number of iterations.
Returns
- the intensity value of the spot.
- the coordinates of the spot.
- the backgound offset
- the tilted background
raises MaxIterations if not found after n_iter iterations
"""
+1 -1
View File
@@ -159,7 +159,7 @@ impl Detector for StdThreshold {
/// ///
/// ``` /// ```
/// use ndarray::Array; /// use ndarray::Array;
/// use smoll::maxima::local_maxima; /// use smoll::detection::local_maxima;
/// ///
/// let frame = Array::from_shape_vec((2, 2), vec![1., 2., 3., 4.]).unwrap(); /// let frame = Array::from_shape_vec((2, 2), vec![1., 2., 3., 4.]).unwrap();
/// let maxima = local_maxima(frame.view()); /// let maxima = local_maxima(frame.view());
+7 -5
View File
@@ -1,10 +1,12 @@
use strum::IntoStaticStr; #[derive(Debug, thiserror::Error, strum::IntoStaticStr)]
use thiserror::Error;
#[derive(Debug, Error, IntoStaticStr)]
pub enum Error { pub enum Error {
#[error("matrix not invertible")] #[error("matrix not invertible")]
MatrixNotInvertible, SingularMatrix,
#[error("maximum iterations reached: {0}")]
MaxIterations(usize),
#[error(transparent)]
ParseError(#[from] strum::ParseError),
#[error(transparent)] #[error(transparent)]
ShapeError(#[from] ndarray::ShapeError), ShapeError(#[from] ndarray::ShapeError),
} }
+572 -9
View File
@@ -1,8 +1,14 @@
use crate::error::Error; use crate::error::Error;
use crate::error::Error::MaxIterations;
use itertools::Itertools; use itertools::Itertools;
use ndarray::{Array, Array2, ArrayView1, AsArray, Axis, Dimension, Ix1, Ix2}; use ndarray::{
Array, Array1, Array2, ArrayView1, AsArray, Axis, Dimension, Ix1, Ix2, SliceInfoElem,
};
use statrs::function::erf::erf;
use statrs::statistics::Statistics;
use strum::EnumString;
const STP: f64 = 0.5 * std::f64::consts::FRAC_2_SQRT_PI * std::f64::consts::FRAC_1_SQRT_2; const FRAC_1_SQRT_2_PI: f64 = 0.3989422804014326779399460599343818684758586311649346576659258296;
/// p: I, x0, x1, ... xn, s00, s01, ..., s0n, s10, s11, ..., s1n, ..., sn0, sn1, ..., snn, o, o0, o1, ..., on /// p: I, x0, x1, ... xn, s00, s01, ..., s0n, s10, s11, ..., s1n, ..., sn0, sn1, ..., snn, o, o0, o1, ..., on
/// x: n 1d arrays, defining coordinates in each dimension /// x: n 1d arrays, defining coordinates in each dimension
@@ -27,7 +33,7 @@ where
let (lu, perm) = lu_factor(&c)?; let (lu, perm) = lu_factor(&c)?;
let c_inv = matrix_inverse(&lu, &perm); let c_inv = matrix_inverse(&lu, &perm);
let c_det = matrix_determinant(&lu, &perm); let c_det = matrix_determinant(&lu, &perm);
let a = p[0] * STP.powi(n as i32) / c_det.sqrt(); let a = p[0] * FRAC_1_SQRT_2_PI.powi(n as i32) / c_det.sqrt();
let x = x let x = x
.into_iter() .into_iter()
.map(|i| i.into()) .map(|i| i.into())
@@ -48,10 +54,331 @@ where
.into_dimensionality()?) .into_dimensionality()?)
} }
/// p: I, x0, x1, ... xn, s00, s01, ..., s0n, s10, s11, ..., s1n, ..., sn0, sn1, ..., snn, o, o0, o1, ..., on
/// x: n 1d arrays, defining coordinates in each dimension
/// gaussian, but the signal is integrated over each pixel
///
/// Pixels are assumed to be unit hypercubes, i.e. pixel `i` in each dimension
/// covers `[x_i - 1/2, x_i + 1/2]`.
///
/// The pixel integral is evaluated as a product of 1D analytic integrals in
/// the eigenspace of the covariance (exact when the covariance is diagonal,
/// and the standard product-form approximation otherwise). Eigenvalues below
/// `n * eps * lambda_max` are treated as zero, in which case that dimension
/// contributes the point-emitter limit: 1 inside the pixel containing the
/// center, 1/2 on its boundary, and 0 elsewhere. Unlike `gaussian`, this works
/// for rank-deficient covariances.
pub fn gaussian_pixel_int<'a, A, D>(x: Vec<A>, p: &[f64]) -> Result<Array<f64, D>, Error>
where
A: AsArray<'a, f64, Ix1>,
D: Dimension,
{
let n = x.len();
let n2 = n * n;
debug_assert_eq!(
p.len(),
2 + 2 * n + n2,
"number of parameters must be {}",
2 + 2 * n + n2
);
let i0 = p[0];
let m = ArrayView1::from(&p[1..1 + n]);
let s = &p[1 + n..1 + n + n2];
let o = p[1 + n + n2];
let q = ArrayView1::from(&p[2 + n + n2..]);
let c = Array2::from_shape_vec((n, n), s.to_vec())?.powi(2);
let (w, ev) = symmetric_eigen(&c);
let wmax = w.iter().copied().fold(0.0f64, f64::max);
let tol = (n as f64) * f64::EPSILON * wmax;
if w.iter().any(|&x| x < -tol) {
return Err(Error::SingularMatrix);
}
let x = x
.into_iter()
.map(|i| i.into())
.collect::<Vec<ArrayView1<f64>>>();
let shape = x.iter().map(|i| i.len()).collect::<Vec<_>>();
Ok(Array::from_shape_vec(
shape,
x.into_iter()
.zip(m)
.map(|(xi, &mi)| (&xi - mi).to_vec())
.multi_cartesian_product()
.map(|d| {
// pixel center, relative to the center of the gaussian
let mut gauss = i0;
for k in 0..n {
let zk = (0..n).map(|j| ev[[j, k]] * d[j]).sum::<f64>();
gauss *= pixel_factor(zk, w[k], tol);
}
gauss + o + (0..n).map(|k| q[k] * d[k]).sum::<f64>()
})
.collect(),
)?
.into_dimensionality()?)
}
#[derive(Debug, Clone, EnumString)]
pub enum BackgroundSubtraction {
None,
Constant,
Tilted,
}
/// Applies the algorithm from [Thompson et al. (2002) PNAS, 82:2775].
/// Parameters:
/// - g: an array with the image
/// - x: approximate coordinates of the spot to localize
/// - s: sigma
/// - fix_location: If 1, applied the iterative localization refinement algorithm, starting with the coordinates provided in coo. If 0, only measures the spot intensity at the coordinates provided in coo.
/// - background_subtraction: 0 -> no background subtraction. 1 -> constant background subtraction. 2 -> tilted plane background subtraction.
/// - window_size: size of the window (in pixels) around the position in coo, used for the iterative localization and for the background subtraction.
/// - tolerance: cutoff to determine convergence, i.e. the distance (in pixels) between two iterations
/// - n_iter: the maximal number of iterations.
///
/// Returns
/// - the intensity value of the spot.
/// - the coordinates of the spot.
/// - the backgound offset
/// - the tilted background
///
/// raises MaxIterations if not found after n_iter iterations
#[expect(clippy::too_many_arguments)]
pub fn modal_analysis<'a, A, D>(
g: A,
x: &[f64],
s: &[f64],
window_size: &[usize],
n_iter: usize,
tolerance: f64,
background_subtraction: BackgroundSubtraction,
fix_location: bool,
) -> Result<Vec<f64>, Error>
where
A: AsArray<'a, f64, D>,
D: Dimension,
{
let g = g.into().into_dyn();
let shape = g.shape();
let last_index = shape.iter().map(|i| i - 1).collect::<Vec<_>>();
let ndim = shape.len();
let mut x = x.to_vec();
for _ in 0..n_iter {
if x.iter()
.zip(window_size)
.any(|(xi, &wi)| xi - (wi as f64 / 2.0) < 0.0)
|| x.iter()
.zip(window_size)
.zip(shape)
.any(|((xi, &wi), &si)| xi - (wi as f64 / 2.0) > si as f64)
{
break;
}
let win_orig = x
.iter()
.zip(window_size)
.map(|(xi, &wi)| (xi - wi as f64 / 2.0) as isize)
.collect::<Vec<_>>();
let nn = Array::from_shape_vec(
shape,
x.iter()
.zip(window_size)
.map(|(xi, &wi)| (0..wi).map(|wii| wii as f64 - *xi))
.multi_cartesian_product()
.map(|xii| {
-xii.iter()
.zip(s)
.map(|(xiii, si)| {
(xiii / (2.0 * si)).powi(2) / (std::f64::consts::TAU * si.powi(2))
})
.sum::<f64>()
})
.collect(),
)?;
let slice = win_orig
.iter()
.zip(window_size)
.map(|(&oi, &si)| SliceInfoElem::Slice {
start: oi,
end: Some(oi + si as isize),
step: 1,
})
.collect::<Vec<_>>();
let gs = g.slice(slice.as_slice());
let bg = match background_subtraction {
BackgroundSubtraction::None => vec![0.0; 1 + ndim],
BackgroundSubtraction::Constant => {
let mut bg = vec![0.0; 1 + ndim];
bg[0] = gs
.indexed_iter()
.filter_map(|(i, v)| {
if i.as_array_view()
.iter()
.zip(&last_index)
.any(|(&i, &li)| (i == 0) || (i == li))
{
Some(v)
} else {
None
}
})
.mean();
bg
}
BackgroundSubtraction::Tilted => {
let mut bg = vec![0.0; 1 + ndim];
let (_i, v) = gs
.indexed_iter()
.filter(|(i, _)| {
i.as_array_view()
.iter()
.zip(&last_index)
.any(|(&i, &li)| (i == 0) || (i == li))
})
.collect::<(Vec<_>, Vec<f64>)>();
bg[0] = v.mean();
// TODO
bg
}
};
let gss = gs.clamp(0.0, f64::MAX);
if fix_location {
let mut p = vec![(&gss * &nn).sum() / nn.powi(2).sum()];
p.extend_from_slice(&x);
p.extend_from_slice(&bg);
return Ok(p);
} else {
let sn = &gss * &nn;
let ssn = sn.sum();
let new_x = x
.iter()
.enumerate()
.map(|(i, xi)| {
gss.axis_iter(Axis(i))
.enumerate()
.flat_map(|(j, gssi)| &gssi * (j as f64 - xi))
.sum::<f64>()
/ ssn
})
.collect::<Vec<_>>();
if Statistics::max(x.iter().zip(&new_x).map(|(xi, ni)| (*xi - ni).abs())) <= tolerance {
let mut p = vec![ssn / nn.powi(2).sum()];
p.extend_from_slice(&new_x);
p.extend_from_slice(&bg);
return Ok(p);
} else {
x = new_x;
}
}
}
Err(MaxIterations(n_iter))
}
/// Analytic integral of the 1D gaussian `exp(-t^2/(2w)) / sqrt(2*pi*w)`
/// over the unit pixel centered at `z`.
///
/// Returns the point-emitter limit instead when `w <= tol`:
/// 1 inside the pixel, 1/2 on its boundary, and 0 elsewhere.
fn pixel_factor(z: f64, w: f64, tol: f64) -> f64 {
if w <= tol {
let az = z.abs();
return if az < 0.5 {
1.0
} else if az == 0.5 {
0.5
} else {
0.0
};
}
let k = 1.0 / (2.0 * w).sqrt();
0.5 * (erf((z + 0.5) * k) - erf((z - 0.5) * k))
}
/// Eigen-decomposition of a symmetric matrix using cyclic Jacobi rotations.
///
/// Returns the eigenvalues and the eigenvectors (as **columns** of the
/// second array), such that `matrix` = `eigenvectors` · diag(eigenvalues) · `eigenvectors`.t().
fn symmetric_eigen(matrix: &Array2<f64>) -> (Array1<f64>, Array2<f64>) {
println!("matrix = {:?}", matrix);
let n = matrix.nrows();
debug_assert_eq!(n, matrix.ncols(), "matrix must be square");
let mut a = matrix.to_owned();
let mut v = Array2::eye(n);
for _ in 0..100 {
// squared sum of the off-diagonal elements
let mut off = 0.0;
for i in 0..n {
for j in (i + 1)..n {
off += a[[i, j]] * a[[i, j]];
}
}
if off == 0.0 {
break;
}
// relative convergence criterion
let total: f64 = a.iter().map(|&x| x * x).sum();
if off <= (f64::EPSILON * total) * (f64::EPSILON * total) {
break;
}
// one sweep over the strictly upper triangle
for p in 0..n - 1 {
for q in (p + 1)..n {
let apq = a[[p, q]];
if apq == 0.0 {
continue;
}
let app = a[[p, p]];
let aqq = a[[q, q]];
// rotation that zeroes a[p, q] (numerically stable form)
let theta = 0.5 * (aqq - app) / apq;
let t = if theta < 0.0 {
-1.0 / (-theta + (theta * theta + 1.0).sqrt())
} else {
1.0 / (theta + (theta * theta + 1.0).sqrt())
};
let c = 1.0 / (t * t + 1.0).sqrt();
let s = t * c;
a[[p, p]] = app - t * apq;
a[[q, q]] = aqq + t * apq;
a[[p, q]] = 0.0;
a[[q, p]] = 0.0;
for i in 0..n {
if i != p && i != q {
let apj = a[[i, p]];
let aqj = a[[i, q]];
a[[i, p]] = c * apj - s * aqj;
a[[i, q]] = s * apj + c * aqj;
}
// v = V * R: the rotation applies to every row,
// including rows p and q
let vpj = v[[i, p]];
let vqj = v[[i, q]];
v[[i, p]] = c * vpj - s * vqj;
v[[i, q]] = s * vpj + c * vqj;
}
for i in 0..n {
if i != p && i != q {
let apj = a[[p, i]];
let aqj = a[[q, i]];
a[[p, i]] = c * apj - s * aqj;
a[[q, i]] = s * apj + c * aqj;
}
}
}
}
}
let w = (0..n).map(|i| a[[i, i]]).collect::<Array1<f64>>();
(w, v)
}
/// PA = LU factorization (Doolittle with partial pivoting). /// PA = LU factorization (Doolittle with partial pivoting).
/// ///
/// Returns the packed LU matrix (lower unit triangular in columns /// Returns the packed LU matrix (lower unit triangular in columns
/// 0..k, upper triangular in rows k) and the row permutation, or `None` /// 0..k, upper triangular in rows k) and the row permutation, or `SingularMatrix`
/// if a pivot is singular or numerically rank-deficient. /// if a pivot is singular or numerically rank-deficient.
fn lu_factor<'a, A>(matrix: A) -> Result<(Array2<f64>, Vec<usize>), Error> fn lu_factor<'a, A>(matrix: A) -> Result<(Array2<f64>, Vec<usize>), Error>
where where
@@ -76,7 +403,7 @@ where
} }
} }
if lu[[pivot_row, k]].abs() <= threshold || !lu[[pivot_row, k]].is_finite() { if lu[[pivot_row, k]].abs() <= threshold || !lu[[pivot_row, k]].is_finite() {
return Err(Error::MatrixNotInvertible); return Err(Error::SingularMatrix);
} }
if pivot_row != k { if pivot_row != k {
for j in 0..n { for j in 0..n {
@@ -99,8 +426,6 @@ where
/// Calculate the inverse of a square matrix using LU factorization with partial /// Calculate the inverse of a square matrix using LU factorization with partial
/// pivoting. /// pivoting.
///
/// Returns `None` if the matrix is singular, or numerically rank-deficient.
fn matrix_inverse(lu: &Array2<f64>, perm: &[usize]) -> Array2<f64> { fn matrix_inverse(lu: &Array2<f64>, perm: &[usize]) -> Array2<f64> {
let n = lu.nrows(); let n = lu.nrows();
@@ -129,8 +454,6 @@ fn matrix_inverse(lu: &Array2<f64>, perm: &[usize]) -> Array2<f64> {
/// Calculate the determinant of a square matrix using LU factorization /// Calculate the determinant of a square matrix using LU factorization
/// with partial pivoting. /// with partial pivoting.
///
/// Returns `None` if the matrix is singular, or numerically rank-deficient.
fn matrix_determinant(lu: &Array2<f64>, perm: &[usize]) -> f64 { fn matrix_determinant(lu: &Array2<f64>, perm: &[usize]) -> f64 {
// sign of the row permutation: parity of its inversion count // sign of the row permutation: parity of its inversion count
let inversions = (1..perm.len()) let inversions = (1..perm.len())
@@ -144,6 +467,16 @@ fn matrix_determinant(lu: &Array2<f64>, perm: &[usize]) -> f64 {
mod tests { mod tests {
use super::*; use super::*;
#[test]
fn test_matrix_inverse() -> Result<(), Error> {
let matrix = Array2::from_shape_vec((2, 2), vec![2.12132, -3.535534, 2.12132, 3.535534])?;
let (lu, perm) = lu_factor(&matrix)?;
let inverse = matrix_inverse(&lu, &perm);
let truth = Array2::from_shape_vec((2, 2), vec![0.235702, 0.235702, -0.141421, 0.141421])?;
assert!((inverse - truth).sum().abs() < 1e-6);
Ok(())
}
#[test] #[test]
fn test_matrix_det() -> Result<(), Error> { fn test_matrix_det() -> Result<(), Error> {
// trivial 1x1 // trivial 1x1
@@ -183,4 +516,234 @@ mod tests {
assert!((ab - a_det * b_det).abs() < 1e-10); assert!((ab - a_det * b_det).abs() < 1e-10);
Ok(()) Ok(())
} }
#[test]
fn test_symmetric_eigen() -> Result<(), Error> {
let m = Array2::from_shape_vec(
(3, 3),
vec![5.0_f64, 1.0, 2.0, 1.0, 4.0, -1.0, 2.0, -1.0, 3.0],
)?;
let (w, v) = symmetric_eigen(&m);
// trace and determinant are preserved
assert!((w.iter().sum::<f64>() - 12.0).abs() < 1e-10);
let (lu, perm) = lu_factor(&m)?;
assert!((w.iter().product::<f64>() - matrix_determinant(&lu, &perm)).abs() < 1e-8);
// reconstruction v * diag(w) * v.t() = m
let d = Array2::from_shape_fn((3, 3), |rc| if rc.0 == rc.1 { w[rc.0] } else { 0.0 });
let recon = v.clone().dot(&d).dot(&v.t());
let err = (recon - m.clone())
.into_iter()
.fold(0.0_f64, |e, x| e.max(x.abs()));
assert!(err < 1e-8);
// eigenvectors are orthonormal
let gv = v.t().dot(&v);
let gerr = (gv - Array2::<f64>::eye(3))
.into_iter()
.fold(0.0_f64, |e, x| e.max(x.abs()));
assert!(gerr < 1e-9);
// degenerate input
let z = Array2::zeros((2, 2));
let (wz, _) = symmetric_eigen(&z);
assert!(wz.iter().all(|&x| x == 0.0));
Ok(())
}
#[test]
fn test_pixel_factor() {
// analytic: w = 0.5 -> exp(-t^2) / sqrt(pi)
assert!((pixel_factor(0.0, 0.5, 0.0) - erf(0.5)).abs() < 1e-14);
// point-emitter limit
assert_eq!(pixel_factor(0.0, 0.0, 0.0), 1.0);
assert_eq!(pixel_factor(0.5, 0.0, 0.0), 0.5);
assert_eq!(pixel_factor(0.6, 0.0, 0.0), 0.0);
assert_eq!(pixel_factor(-0.5, 0.0, 0.0), 0.5);
// tiny width below tolerance behaves as the limit
assert_eq!(pixel_factor(0.0, 1e-20, 1e-15), 1.0);
assert_eq!(pixel_factor(1.0, 1e-20, 1e-15), 0.0);
}
#[test]
fn test_gaussian_pixel_int_1d() -> Result<(), Error> {
// compare per-pixel values against the analytic 1D expression
// (including the centered offset and tilt terms)
let (i_, m_, w, o, qq): (f64, f64, f64, f64, f64) = (2.0, 3.7, 0.5, 0.1, 0.25);
let p = vec![i_, m_, w.sqrt(), o, qq];
let xv = Array1::from_vec((0..10).map(|i| i as f64).collect());
let x = vec![&xv];
let got: Array1<f64> = gaussian_pixel_int(x, &p)?;
let k = 1.0 / (2.0 * w).sqrt();
for xi in 0..10 {
let d = xi as f64 - m_;
let want = i_ * 0.5 * (erf((d + 0.5) * k) - erf((d - 0.5) * k)) + o + qq * d;
assert!(
(got[[xi]] - want).abs() < 1e-12,
"pixel {xi}: {} vs {want}",
got[[xi]]
);
}
Ok(())
}
#[test]
fn test_gaussian_pixel_int_vs_numeric_1d() -> Result<(), Error> {
// the pixel factors must equal the actual integral of the
// gaussian model (including offset and tilt) over the pixel
let (i_, m_, w, o, qq): (f64, f64, f64, f64, f64) = (1.3, 0.3, 0.8, 0.1, 0.25);
let p = vec![i_, m_, w.sqrt(), o, qq];
let xv = Array1::from_vec((0..11).map(|i| i as f64).collect());
let x = vec![&xv];
let got: Array1<f64> = gaussian_pixel_int(x, &p)?;
let norm = 1.0 / (2.0 * std::f64::consts::PI * w).sqrt();
for xi in 0..11 {
let lo = xi as f64 - 0.5;
let npts = 2000;
let dt = 1.0 / npts as f64;
let mut sum = 0.0;
for j in 0..=npts {
let t = lo + j as f64 * dt;
let g =
i_ * (norm * (-((t - m_) * (t - m_)) / (2.0 * w)).exp()) + o + qq * (t - m_);
let wj = if j == 0 || j == npts { 0.5 } else { 1.0 };
sum += wj * g;
}
sum *= dt;
assert!(
(got[[xi]] - sum).abs() < 1e-6,
"pixel {xi}: {} vs {sum}",
got[[xi]]
);
}
Ok(())
}
#[test]
fn test_gaussian_pixel_int_vs_numeric_2d() -> Result<(), Error> {
// diagonal covariance: the product of 1D integrals must equal the
// true 2D pixel integral (including offset and tilt)
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 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];
let got: Array2<f64> = gaussian_pixel_int(x, &p)?;
let norm = 1.0 / (2.0 * std::f64::consts::PI * (w1 * w2).sqrt());
for iy in 0..8 {
for ix in 0..8 {
let (cx, cy) = (ix as f64, iy as f64);
let npts = 200;
let dt = 1.0 / npts as f64;
let mut sum = 0.0;
for j in 0..=npts {
for i in 0..=npts {
let tx = cx - 0.5 + i as f64 * dt;
let ty = cy - 0.5 + j as f64 * dt;
let e = (-((tx - mx).powi(2) / (2.0 * w1)
+ (ty - my).powi(2) / (2.0 * w2)))
.exp();
let g = i_ * norm * e + o + qx * (tx - mx) + qy * (ty - my);
let wj = if i == 0 || i == npts { 0.5 } else { 1.0 };
let wk = if j == 0 || j == npts { 0.5 } else { 1.0 };
sum += g * wj * wk;
}
}
sum *= dt * dt;
assert!(
(got[[ix, iy]] - sum).abs() < 1e-4,
"pixel [{ix},{iy}]: {} vs {sum}",
got[[ix, iy]]
);
}
}
Ok(())
}
#[test]
fn test_gaussian_pixel_int_rotated() -> Result<(), Error> {
// non-diagonal covariance: compare against the product-form
// computed independently from the closed-form 2x2 eigenvalues
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 (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(),
o,
qx,
qy,
];
let xv = Array1::from_vec((0..8).map(|i| i as f64).collect());
let yv = Array1::from_vec((0..9).map(|i| i as f64).collect());
let x = vec![&xv, &yv];
let got: Array2<f64> = gaussian_pixel_int(x, &p)?;
let tr = c11 + c22;
let delta = ((c11 - c22) / 2.0).powi(2) + c12 * c12;
let ws = tr / 2.0 - delta.sqrt();
let wl = tr / 2.0 + delta.sqrt();
let vev = |w: f64| {
let nv = (c12 * c12 + (w - c11).powi(2)).sqrt();
(c12 / nv, (w - c11) / nv)
};
let factor = |z: f64, w: f64| {
let k = 1.0 / (2.0 * w).sqrt();
0.5 * (erf((z + 0.5) * k) - erf((z - 0.5) * k))
};
for iy in 0..9 {
for ix in 0..8 {
let d = (ix as f64 - mx, iy as f64 - my);
let (v1, v2) = (vev(wl), vev(ws));
let z1 = v1.0 * d.0 + v1.1 * d.1;
let z2 = v2.0 * d.0 + v2.1 * d.1;
let want = i_ * factor(z1, wl) * factor(z2, ws) + o + qx * d.0 + qy * d.1;
assert!(
(got[[ix, iy]] - want).abs() < 1e-12,
"pixel [{ix},{iy}]: {} vs {want}",
got[[ix, iy]]
);
}
}
Ok(())
}
#[test]
fn test_gaussian_pixel_int_point() -> Result<(), Error> {
// zero width: the intensity concentrates in the pixel
// containing the center (plus the offset and tilt terms)
let p = vec![2.0, 3.7, 0.0, 0.1, 0.25];
let xv = Array1::from_vec((0..8).map(|i| i as f64).collect());
let x = vec![&xv];
let got: Array1<f64> = gaussian_pixel_int(x, &p)?;
for xi in 0..8 {
let d = xi as f64 - 3.7;
let g = if d.abs() < 0.5 { 2.0 } else { 0.0 };
assert!(
(got[[xi]] - (g + 0.1 + 0.25 * d)).abs() < 1e-12,
"pixel {xi}: {}",
got[[xi]]
);
}
Ok(())
}
#[test]
fn test_gaussian_pixel_int_normalization() -> Result<(), Error> {
// a wide grid around the center integrates to the total intensity
let p = vec![1.0, 0.0, 0.6, 0.0, 0.0];
let xv = Array1::from_vec((-5..=5).map(|i| i as f64).collect());
let x = vec![&xv];
let got: Array1<f64> = gaussian_pixel_int(x, &p)?;
assert!((got.iter().sum::<f64>() - 1.0).abs() < 1e-8);
Ok(())
}
} }
+6
View File
@@ -90,5 +90,11 @@ mod smoll_rs {
mod gaussian { mod gaussian {
#[pymodule_export] #[pymodule_export]
use super::super::gaussian::gaussian; use super::super::gaussian::gaussian;
#[pymodule_export]
use super::super::gaussian::gaussian_pixel_int;
#[pymodule_export]
use super::super::gaussian::modal_analysis;
} }
} }
+89 -1
View File
@@ -1,5 +1,6 @@
use crate::error::Error;
use crate::gaussian as gaussian_rs; use crate::gaussian as gaussian_rs;
use numpy::{AllowTypeChange, IntoPyArray, PyArrayDyn, PyArrayLike1}; use numpy::{AllowTypeChange, IntoPyArray, PyArrayDyn, PyArrayLike1, PyArrayLikeDyn};
use pyo3::prelude::*; use pyo3::prelude::*;
use pyo3_stub_gen::derive::*; use pyo3_stub_gen::derive::*;
@@ -29,3 +30,90 @@ pub(crate) fn gaussian<'py>(
} }
.into_pyarray(py)) .into_pyarray(py))
} }
/// p: I, x0, x1, ... xn, s00, s01, ..., s0n, s10, s11, ..., s1n, ..., sn0, sn1, ..., snn, o, o0, o1, ..., on
/// x: n 1d arrays, defining coordinates in each dimension
/// gaussian, but the signal is integrated over each pixel
///
/// Pixels are assumed to be unit hypercubes, i.e. pixel `i` in each dimension
/// covers `[x_i - 1/2, x_i + 1/2]`.
///
/// The pixel integral is evaluated as a product of 1D analytic integrals in
/// the eigenspace of the covariance (exact when the covariance is diagonal,
/// and the standard product-form approximation otherwise). Eigenvalues below
/// `n * eps * lambda_max` are treated as zero, in which case that dimension
/// contributes the point-emitter limit: 1 inside the pixel containing the
/// center, 1/2 on its boundary, and 0 elsewhere. Unlike `gaussian`, this works
/// for rank-deficient covariances.
#[gen_stub_pyfunction(module = "smoll.gaussian")]
#[pyfunction]
pub(crate) fn gaussian_pixel_int<'py>(
py: Python<'py>,
#[gen_stub(override_type(type_repr="numpy.typing.ArrayLike", imports=("numpy.typing")))] x: Vec<
PyArrayLike1<f64, AllowTypeChange>,
>,
#[gen_stub(override_type(type_repr="numpy.typing.ArrayLike", imports=("numpy.typing")))]
p: PyArrayLike1<f64, AllowTypeChange>,
) -> PyResult<Bound<'py, PyArrayDyn<f64>>> {
let x = x
.into_iter()
.map(|i| i.as_array().to_owned())
.collect::<Vec<_>>();
let xv = x.iter().map(|i| i.view()).collect::<Vec<_>>();
Ok(if let Ok(p) = p.as_slice() {
gaussian_rs::gaussian_pixel_int(xv, p)?
} else {
let p = p.as_array().to_vec();
gaussian_rs::gaussian_pixel_int(xv, &p)?
}
.into_pyarray(py))
}
/// Applies the algorithm from [Thompson et al. (2002) PNAS, 82:2775].
/// Parameters:
/// - g: an array with the image
/// - x: approximate coordinates of the spot to localize
/// - s: sigma
/// - fix_location: If 1, applied the iterative localization refinement algorithm, starting with the coordinates provided in coo. If 0, only measures the spot intensity at the coordinates provided in coo.
/// - background_subtraction: 0 -> no background subtraction. 1 -> constant background subtraction. 2 -> tilted plane background subtraction.
/// - window_size: size of the window (in pixels) around the position in coo, used for the iterative localization and for the background subtraction.
/// - tolerance: cutoff to determine convergence, i.e. the distance (in pixels) between two iterations
/// - n_iter: the maximal number of iterations.
///
/// Returns
/// - the intensity value of the spot.
/// - the coordinates of the spot.
/// - the backgound offset
/// - the tilted background
///
/// raises MaxIterations if not found after n_iter iterations
#[gen_stub_pyfunction(module = "smoll.gaussian")]
#[pyfunction]
#[expect(clippy::too_many_arguments)]
pub(crate) fn modal_analysis<'py>(
py: Python<'py>,
#[gen_stub(override_type(type_repr="numpy.typing.ArrayLike", imports=("numpy.typing")))]
g: PyArrayLikeDyn<f64, AllowTypeChange>,
x: Vec<f64>,
s: Vec<f64>,
window_size: Vec<usize>,
n_iter: usize,
tolerance: f64,
background_subtraction: String,
fix_location: bool,
) -> PyResult<Vec<f64>> {
let g = g.as_array();
Ok(py.detach(|| {
gaussian_rs::modal_analysis(
g,
&x,
&s,
&window_size,
n_iter,
tolerance,
background_subtraction.parse().map_err(Error::from)?,
fix_location,
)
})?)
}