smoll 0.0.2

Single MOLecule Localization.
Documentation
use crate::error::Error;
use crate::filter::gaussian_smooth;
use itertools::Itertools;
use ndarray::{Array, Array2, AsArray, Axis, Dimension, IntoDimension, stack};
use std::cmp::Ordering;

pub trait Filter {
    type Error;

    fn filter_array<'a, A, D>(&self, array: A) -> Result<Array<f64, D>, Self::Error>
    where
        A: AsArray<'a, f64, D>,
        D: Dimension;
}

#[derive(Debug, Clone, PartialEq)]
pub struct DoG {
    pub lower: Vec<f64>,
    pub upper: Vec<f64>,
}

impl DoG {
    pub fn new(lower: Vec<f64>, upper: Vec<f64>) -> Self {
        Self { lower, upper }
    }
}

impl Filter for DoG {
    type Error = Error;

    fn filter_array<'a, A, D>(&self, array: A) -> Result<Array<f64, D>, Self::Error>
    where
        A: AsArray<'a, f64, D>,
        D: Dimension,
    {
        let array = array.into();
        Ok(gaussian_smooth(&array, &self.lower)? - gaussian_smooth(array, &self.upper)?)
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct LoG {}

impl LoG {
    pub fn new() -> Self {
        Self {}
    }
}

impl Default for LoG {
    fn default() -> Self {
        Self::new()
    }
}

impl Filter for LoG {
    type Error = Error;

    fn filter_array<'a, A, D>(&self, _array: A) -> Result<Array<f64, D>, Self::Error>
    where
        A: AsArray<'a, f64, D>,
        D: Dimension,
    {
        todo!()
    }
}

pub trait Detector {
    type Error;

    fn detect<'a, A, D>(&self, array: A) -> Result<Array2<usize>, Self::Error>
    where
        A: AsArray<'a, f64, D>,
        D: Dimension;
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub struct AbsoluteThreshold {
    pub threshold: f64,
}

impl AbsoluteThreshold {
    pub fn new(threshold: f64) -> Self {
        Self { threshold }
    }
}

impl Detector for AbsoluteThreshold {
    type Error = Error;

    fn detect<'a, A, D>(&self, array: A) -> Result<Array2<usize>, Self::Error>
    where
        A: AsArray<'a, f64, D>,
        D: Dimension,
    {
        let array = array.into().into_dyn();
        let candidates = local_maxima(array.view());

        let a = candidates
            .rows()
            .into_iter()
            .filter(|&x| {
                if let Some(s) = x.as_slice() {
                    array[s] > self.threshold
                } else {
                    let s = x.to_vec();
                    array[s.as_slice()] > self.threshold
                }
            })
            .collect::<Vec<_>>();

        Ok(stack(Axis(0), &a)?)
    }
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub struct StdThreshold {
    pub threshold: f64,
}

impl StdThreshold {
    pub fn new(threshold: f64) -> Self {
        Self { threshold }
    }
}

impl Detector for StdThreshold {
    type Error = Error;

    fn detect<'a, A, D>(&self, array: A) -> Result<Array2<usize>, Self::Error>
    where
        A: AsArray<'a, f64, D>,
        D: Dimension,
    {
        let array = array.into().into_dyn();
        let std = array.std(0.0) * self.threshold;
        let candidates = local_maxima(array.view());

        let a = candidates
            .rows()
            .into_iter()
            .filter(|&x| {
                if let Some(s) = x.as_slice() {
                    array[s] > std
                } else {
                    let s = x.to_vec();
                    array[s.as_slice()] > std
                }
            })
            .collect::<Vec<_>>();

        Ok(stack(Axis(0), &a)?)
    }
}

/// Find all indices of the strict local maxima of `frame`.
///
/// A point is a strict local maximum if it is **strictly** greater than
/// every point in its direct neighborhood: the `3^dim - 1` points at
/// Chebyshev distance 1 (including diagonal neighbors), excluding itself.
/// Edge points have fewer in-bounds neighbors, and a point with no in-bounds
/// neighbors at all is vacuously a local maximum.
///
/// Since the comparison is strict, plateaus (points equal to a neighbor) and
/// NaN values are never maxima.
///
/// The result has shape (n_maxima, dim), holding one index per row, ordered by
/// the arrays logical (row-major) iteration order.
///
/// # Examples
///
/// ```
/// use ndarray::Array;
/// use smoll::detection::local_maxima;
///
/// let frame = Array::from_shape_vec((2, 2), vec![1., 2., 3., 4.]).unwrap();
/// let maxima = local_maxima(frame.view());
/// assert_eq!(maxima, Array::from_shape_vec((1, 2), vec![1, 1]).unwrap());
/// ```
pub fn local_maxima<'a, A, D>(frame: A) -> Array2<usize>
where
    A: AsArray<'a, f64, D>,
    D: Dimension,
{
    let frame = frame.into();
    let shape = frame.shape();
    let ndim = frame.ndim();

    // All relative offsets of the direct neighborhood: one of `{-1, 0, 1}`
    // per axis, with the zero offset excluded.
    let offsets: Vec<Vec<i8>> = (0..ndim)
        .map(|_| -1i8..=1)
        .multi_cartesian_product()
        .filter(|off| off.iter().any(|&d| d != 0))
        .collect();

    // Coordinates of the maxima, stacked one row at a time.
    let mut coords = Vec::new();
    for (position, &center) in frame.indexed_iter() {
        let index = position.into_dimension();
        let coord = index.as_array_view();

        let mut is_max = true;
        for off in &offsets {
            let mut neighbor = index.clone();
            let mut out_of_bounds = false;
            for (axis, &d) in off.iter().enumerate() {
                match d {
                    -1 => {
                        if coord[axis] == 0 {
                            out_of_bounds = true;
                            break;
                        }
                        neighbor[axis] -= 1;
                    }
                    1 => {
                        if coord[axis] + 1 >= shape[axis] {
                            out_of_bounds = true;
                            break;
                        }
                        neighbor[axis] += 1;
                    }
                    _ => {}
                }
            }
            if out_of_bounds {
                continue;
            }
            // Must be strictly greater than this neighbor; `NaN` on either
            // side of the comparison fails the test. The neighbor is
            // guaranteed to be in bounds.
            if let Some(Ordering::Less) =
                center.partial_cmp(frame.get(neighbor).expect("neighbor out of bounds"))
            {
                is_max = false;
                break;
            }
        }
        if is_max {
            coords.extend(coord.iter().copied());
        }
    }

    let count = coords.len().checked_div(ndim).unwrap_or(frame.len());

    // Guaranteed to fit: exactly `ndim` coordinates are pushed per maximum.
    let maxima: Array2<usize> =
        Array2::<usize>::from_shape_vec((count, ndim), coords).expect("shape/length mismatch");
    maxima
}