use crate::error::Error;
use crate::linalg::{linefit, rotation_from_skew, symmetric_eigen};
use derive_builder::Builder;
use derive_getters::Getters;
use itertools::{Itertools, izip};
use ndarray::{
Array, Array1, Array2, ArrayView1, AsArray, Axis, Dimension, IntoDimension, Ix1, SliceInfoElem,
};
use statrs::function::erf::erf;
use statrs::statistics::Statistics;
use strum::EnumString;
const FRAC_1_SQRT_2_PI: f64 = 0.3989422804014326779399460599343818684758586311649346576659258296;
pub fn gaussian<'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 - 1) / 2;
debug_assert_eq!(
p.len(),
2 + 3 * n + n2,
"number of parameters must be {}",
2 + 3 * n + n2
);
let m = ArrayView1::from(&p[1..1 + n]); let s = ArrayView1::from(&p[1 + n..1 + 2 * n]); let r = rotation_from_skew(&p[1 + 2 * n..1 + 2 * n + n2])?; let o = p[1 + 2 * n + n2];
let q = ArrayView1::from(&p[2 + 2 * n + n2..]); let c = r
.dot(&Array2::from_diag(&s.mapv(|i| i.powi(-2))))
.dot(&r.t()); let a = p[0] * FRAC_1_SQRT_2_PI.powi(n as i32) / s.product();
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(|i| {
let xj = ArrayView1::from(&i).insert_axis(Axis(0));
a * (-0.5 * xj.dot(&c).dot(&xj.t())).sum().exp() + o + q.dot(&xj.t()).sum()
})
.collect(),
)?
.into_dimensionality()?)
}
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 - 1) / 2;
debug_assert_eq!(
p.len(),
2 + 3 * n + n2,
"number of parameters must be {}",
2 + 3 * n + n2
);
let i0 = p[0];
let m = ArrayView1::from(&p[1..1 + n]); let s = ArrayView1::from(&p[1 + n..1 + 2 * n]); let r = rotation_from_skew(&p[1 + 2 * n..1 + 2 * n + n2])?; let o = p[1 + 2 * n + n2];
let q = ArrayView1::from(&p[2 + 2 * n + n2..]); let c = r.dot(&Array2::from_diag(&s.mapv(|i| i * i))).dot(&r.t()); 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| {
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, Copy, Default, PartialEq, EnumString)]
pub enum BackgroundSubtraction {
#[strum(ascii_case_insensitive)]
#[default]
None,
#[strum(ascii_case_insensitive)]
Constant,
#[strum(ascii_case_insensitive)]
Tilted,
}
#[derive(Debug, Clone, Getters, PartialEq)]
pub struct ModalAnalysisResult {
iterations: usize,
integrated_intensity: f64,
position: Vec<f64>,
sigma: Vec<f64>,
background: Vec<f64>,
}
impl ModalAnalysisResult {
pub(crate) fn new(
iterations: usize,
integrated_intensity: f64,
position: Vec<f64>,
sigma: Vec<f64>,
background: Vec<f64>,
) -> Self {
Self {
iterations,
integrated_intensity,
position,
sigma,
background,
}
}
}
#[derive(Builder, Debug, Clone, PartialEq)]
#[builder(setter(into), build_fn(error = "Error"), derive(Debug, PartialEq))]
pub struct ModalAnalysis {
pub sigma: Vec<f64>,
pub window_shape: Vec<usize>,
#[builder(default = "20")]
pub max_iterations: usize,
#[builder(default = "1e-2")]
pub tolerance: f64,
#[builder(default = "BackgroundSubtraction::None")]
pub background_subtraction: BackgroundSubtraction,
#[builder(default = false)]
pub fix_location: bool,
}
impl Default for ModalAnalysis {
fn default() -> Self {
Self {
sigma: Vec::new(),
window_shape: Vec::new(),
max_iterations: 20,
tolerance: 1e-2,
background_subtraction: BackgroundSubtraction::None,
fix_location: false,
}
}
}
impl ModalAnalysis {
pub fn fit<'a, A, D>(&self, g: A, x: &[f64]) -> Result<ModalAnalysisResult, Error>
where
A: AsArray<'a, f64, D>,
D: Dimension,
{
let g = g.into().into_dyn();
let shape = g.shape();
let ndim = shape.len();
let mut x = x.to_vec();
for iteration in 0..self.max_iterations {
if x.iter()
.zip(&self.window_shape)
.any(|(xi, &wi)| xi - (wi as f64 / 2.0) < 0.0)
|| x.iter()
.zip(&self.window_shape)
.zip(shape)
.any(|((xi, &wi), &si)| xi - (wi as f64 / 2.0) > si as f64)
{
return Err(Error::OutsideFitWindow);
}
let win_orig = x
.iter()
.zip(&self.window_shape)
.map(|(&xi, &wi)| (xi as isize) - ((wi / 2) as isize))
.collect::<Vec<_>>();
let a = FRAC_1_SQRT_2_PI.powi(ndim as i32) / self.sigma.iter().product::<f64>();
let nn = Array::from_shape_vec(
self.window_shape.as_slice(),
x.iter()
.zip(&win_orig)
.zip(&self.window_shape)
.map(|((xi, &oi), &wi)| (oi..oi + wi as isize).map(|wii| wii as f64 - *xi))
.multi_cartesian_product()
.map(|xii| {
a * xii
.iter()
.zip(&self.sigma)
.map(|(xiii, si)| -0.5 * (xiii / si).powi(2))
.sum::<f64>()
.exp()
})
.collect(),
)?;
let slice = win_orig
.iter()
.zip(&self.window_shape)
.map(|(&oi, &si)| SliceInfoElem::Slice {
start: oi,
end: Some(oi + si as isize),
step: 1,
})
.collect::<Vec<_>>();
let mut gs = g.slice(slice.as_slice()).to_owned();
let bg = match self.background_subtraction {
BackgroundSubtraction::None => vec![0.0; 1 + ndim],
BackgroundSubtraction::Constant => {
let mut bg = vec![0.0; 1 + ndim];
let mut slice = vec![
SliceInfoElem::Slice {
start: 0,
end: None,
step: 1
};
ndim
];
let n = self.window_shape.iter().product::<usize>()
- self.window_shape.iter().map(|i| i - 2).product::<usize>();
bg[0] = self
.window_shape
.iter()
.enumerate()
.fold(0.0, |mut acc, (i, &si)| {
slice[i] = SliceInfoElem::Slice {
start: 0,
end: None,
step: (si as isize - 1).max(1),
};
acc += gs.slice(slice.as_slice()).sum();
slice[i] = SliceInfoElem::Slice {
start: 1,
end: Some(si as isize - 1),
step: 1,
};
acc
})
/ n as f64;
gs -= bg[0];
bg
}
BackgroundSubtraction::Tilted => {
let mut bg = vec![0.0];
let mut slice = self
.window_shape
.iter()
.map(|&si| SliceInfoElem::Slice {
start: 0,
end: None,
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 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 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,
end: None,
step: 1
};
ndim
];
let n = self.window_shape.iter().product::<usize>()
- self
.window_shape
.iter()
.map(|i| i.saturating_sub(2))
.product::<usize>();
bg[0] = self
.window_shape
.iter()
.enumerate()
.fold(0.0, |mut acc, (i, &si)| {
slice[i] = SliceInfoElem::Slice {
start: 0,
end: None,
step: (si as isize - 1).max(1),
};
acc += gs.slice(slice.as_slice()).sum();
slice[i] = SliceInfoElem::Slice {
start: 1,
end: Some(si as isize - 1),
step: 1,
};
acc
})
/ n as f64;
gs -= bg[0];
bg
}
};
let gss = gs.clamp(0.0, f64::MAX);
if self.fix_location {
return Ok(ModalAnalysisResult::new(
iteration,
(&gss * &nn).sum() / nn.powi(2).sum(),
x,
self.sigma.clone(),
bg,
));
} else {
let sn = &gss * &nn;
let ssn = sn.sum();
let new_x = win_orig
.iter()
.enumerate()
.map(|(i, oi)| {
sn.axis_iter(Axis(i))
.enumerate()
.flat_map(|(j, sni)| &sni * ((j as isize + oi) as f64))
.sum::<f64>()
/ ssn
})
.collect::<Vec<_>>();
if Statistics::max(x.iter().zip(&new_x).map(|(xi, ni)| (*xi - ni).abs()))
<= self.tolerance
{
return Ok(ModalAnalysisResult::new(
iteration,
ssn / nn.powi(2).sum(),
new_x,
self.sigma.clone(),
bg,
));
} else {
x = new_x;
}
}
}
Err(Error::MaxIterations(self.max_iterations))
}
}
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))
}
#[cfg(test)]
mod tests {
use super::*;
use ndarray::Ix2;
#[test]
fn test_pixel_factor() {
assert!((pixel_factor(0.0, 0.5, 0.0) - erf(0.5)).abs() < 1e-14);
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);
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> {
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> {
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> {
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(), 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];
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> {
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 = (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,
d1.sqrt(),
d2.sqrt(),
(th / 2.0).tan(),
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> {
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> {
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(())
}
#[test]
fn test_modal_analysis() -> Result<(), Error> {
let xv = Array1::from_vec((0..64).map(|i| i as f64).collect());
let yv = Array1::from_vec((0..64).map(|i| i as f64).collect());
let x = vec![&xv, &yv];
let mut m = ModalAnalysisBuilder::default()
.sigma(vec![2.0; 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, 2.0, 2.0, 0.0, 0.0, 0.0, 0.0])?;
let p = m.fit(&g, &[32.0; 2])?;
assert!((p.integrated_intensity() - 1.0).abs() < 1e-2, "{p:?}");
check(&p);
let g = gaussian::<_, Ix2>(x.clone(), &[1.0, 32.3, 31.5, 2.0, 2.0, 0.0, 4.0, 0.0, 0.0])?;
m.background_subtraction = BackgroundSubtraction::Constant;
let p = m.fit(&g, &[32.0; 2])?;
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, 2.0, 2.0, 0.0, 4.0, -1e-3, 2e-3])?;
m.background_subtraction = BackgroundSubtraction::Tilted;
let p = m.fit(&g, &[32.0; 2])?;
assert!((p.background()[0] - 4.0).abs() < 0.2, "{p:?}");
assert!((p.background()[1] + 1e-3).abs() < 1e-3, "{p:?}");
assert!((p.background()[2] - 2e-3).abs() < 1e-3, "{p:?}");
assert!((p.integrated_intensity() - 1.0).abs() < 0.1, "{p:?}");
check(&p);
Ok(())
}
}