smoll 0.0.2

Single MOLecule Localization.
Documentation
use crate::detection;
use crate::detection::{AbsoluteThreshold, Detector, DoG, Filter, LoG, StdThreshold};
use numpy::{AllowTypeChange, IntoPyArray, PyArray2, PyArrayDyn, PyArrayLikeDyn};
use pyo3::IntoPyObjectExt;
use pyo3::exceptions::PyValueError;
use pyo3::prelude::*;
use pyo3_stub_gen::derive::*;

#[derive(Debug, Clone, PartialEq)]
enum Filters {
    DoG(DoG),
    LoG(LoG),
}

#[gen_stub_pyclass]
#[pyclass(subclass, from_py_object, name = "Filter", module = "smoll.detection")]
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct PyFilter {
    inner: Filters,
}

#[gen_stub_pymethods]
#[pymethods]
impl PyFilter {
    #[new]
    #[pyo3(signature = (variant, *args))]
    fn new(variant: String, args: Bound<PyAny>) -> PyResult<Self> {
        match variant.to_lowercase().as_str() {
            "dog" => {
                let (lower, upper) = args.extract()?;
                Ok(Self {
                    inner: Filters::DoG(DoG::new(lower, upper)),
                })
            }
            "log" => Ok(Self {
                inner: Filters::LoG(LoG::new()),
            }),
            _ => Err(PyValueError::new_err(format!(
                "Invalid variant name: {}",
                variant
            ))),
        }
    }

    fn __repr__(&self) -> String {
        format!("{:?}", self.inner)
    }

    fn __getnewargs__<'py>(&self, py: Python<'py>) -> PyResult<(String, Bound<'py, PyAny>)> {
        match self.inner {
            Filters::DoG(ref dog) => Ok((
                "DoG".to_string(),
                (dog.lower.clone(), dog.upper.clone()).into_bound_py_any(py)?,
            )),
            Filters::LoG(_) => Ok(("LoG".to_string(), ().into_bound_py_any(py)?)),
        }
    }

    #[staticmethod]
    fn dog(lower: Vec<f64>, upper: Vec<f64>) -> Self {
        Self {
            inner: Filters::DoG(DoG::new(lower, upper)),
        }
    }

    #[staticmethod]
    fn log() -> Self {
        Self {
            inner: Filters::LoG(LoG::new()),
        }
    }

    fn filter<'py>(
        &self,
        py: Python<'py>,
        #[gen_stub(override_type(type_repr="numpy.typing.ArrayLike", imports=("numpy.typing")))]
        array: PyArrayLikeDyn<f64, AllowTypeChange>,
    ) -> PyResult<Bound<'py, PyArrayDyn<f64>>> {
        let array = array.as_array();
        Ok(match self.inner {
            Filters::DoG(ref dog) => dog.filter_array(array)?,
            Filters::LoG(ref log) => log.filter_array(array)?,
        }
        .into_pyarray(py))
    }
}

#[gen_stub_pyfunction(module = "smoll.detection")]
#[pyfunction]
pub(crate) fn local_maxima<'py>(
    py: Python<'py>,
    #[gen_stub(override_type(type_repr="numpy.typing.ArrayLike", imports=("numpy.typing")))]
    array: PyArrayLikeDyn<f64, AllowTypeChange>,
) -> Bound<'py, PyArray2<u64>> {
    detection::local_maxima(array.as_array())
        .mapv(|i| i as u64)
        .into_pyarray(py)
}

#[derive(Debug, Clone, PartialEq)]
enum Detectors {
    Absolute(AbsoluteThreshold),
    Std(StdThreshold),
}

#[gen_stub_pyclass]
#[pyclass(
    subclass,
    from_py_object,
    name = "Detector",
    module = "smoll.detection"
)]
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct PyDetector {
    inner: Detectors,
}

#[gen_stub_pymethods]
#[pymethods]
impl PyDetector {
    #[new]
    #[pyo3(signature = (variant, *args))]
    fn new(variant: String, args: Bound<PyAny>) -> PyResult<Self> {
        match variant.to_lowercase().as_str() {
            "absolute" => Ok(Self {
                inner: Detectors::Absolute(AbsoluteThreshold::new(args.extract()?)),
            }),
            "std" => Ok(Self {
                inner: Detectors::Std(StdThreshold::new(args.extract()?)),
            }),
            _ => Err(PyValueError::new_err(format!(
                "Invalid variant name: {}",
                variant
            ))),
        }
    }

    fn __repr__(&self) -> String {
        format!("{:?}", self.inner)
    }

    fn __getnewargs__<'py>(&self, py: Python<'py>) -> PyResult<(String, Bound<'py, PyAny>)> {
        match self.inner {
            Detectors::Absolute(ref abs) => Ok((
                "Absolute".to_string(),
                (abs.threshold,).into_bound_py_any(py)?,
            )),
            Detectors::Std(ref std) => {
                Ok(("Std".to_string(), (std.threshold,).into_bound_py_any(py)?))
            }
        }
    }

    #[staticmethod]
    fn abs(threshold: f64) -> Self {
        Self {
            inner: Detectors::Absolute(AbsoluteThreshold { threshold }),
        }
    }

    #[staticmethod]
    fn std(threshold: f64) -> Self {
        Self {
            inner: Detectors::Std(StdThreshold { threshold }),
        }
    }

    fn detect<'py>(
        &self,
        py: Python<'py>,
        #[gen_stub(override_type(type_repr="numpy.typing.ArrayLike", imports=("numpy.typing")))]
        array: PyArrayLikeDyn<f64, AllowTypeChange>,
    ) -> PyResult<Bound<'py, PyArray2<u64>>> {
        let array = array.as_array();
        Ok(match self.inner {
            Detectors::Absolute(ref abs) => abs.detect(array)?,
            Detectors::Std(ref std) => std.detect(array)?,
        }
        .mapv(|i| i as u64)
        .into_pyarray(py))
    }
}