- implemented first bits

This commit is contained in:
Wim Pomp committed 2026-11-14 18:40:19 +01:00
1 parent 47d242cf95
commit ecd3ebdbdc
21 files changed
+1305 -19

No files matched your search

+238
View File
@@ -0,0 +1,238 @@
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 {
lower: Vec<f64>,
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, PartialEq)]
pub struct AbsoluteThreshold {
pub threshold: f64,
}
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, PartialEq)]
pub struct StdThreshold {
pub threshold: f64,
}
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::maxima::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
}
+15
View File
@@ -0,0 +1,15 @@
use strum::IntoStaticStr;
use thiserror::Error;
#[derive(Debug, Error, IntoStaticStr)]
pub enum Error {
#[error(transparent)]
ShapeError(#[from] ndarray::ShapeError),
}
impl Error {
/// the name of the error variant as a static string
pub fn variant_name(&self) -> &'static str {
self.into()
}
}
+112
View File
@@ -0,0 +1,112 @@
//! Module containing gaussian smooth functions as well as helper functions to calculate ND fast
//! fourier transforms
use crate::error::Error;
use itertools::Itertools;
use ndarray::{Array, Array1, ArrayD, AsArray, Axis, Dimension, RemoveAxis, concatenate, s};
use ndrustfft::{FftHandler, Normalization, ndfft_par, ndifft_par};
use num::Complex;
use num::traits::FloatConst;
use std::ops::MulAssign;
/// Fourier transform
pub fn fft<'a, A, D>(array: A) -> Result<Array<Complex<f64>, D>, Error>
where
A: AsArray<'a, f64, D>,
D: Dimension,
{
let mut input = array.into().mapv(|i| Complex::new(i, 0.0));
let shape = input.shape().to_vec();
let mut tmp = ArrayD::zeros(shape.clone()).into_dimensionality()?;
for (i, s) in shape.iter().enumerate() {
let handler = FftHandler::new(*s).normalization(Normalization::None);
ndfft_par(&input.view(), &mut tmp.view_mut(), &handler, i);
std::mem::swap(&mut input, &mut tmp);
}
Ok(input)
}
/// inverse Fourier transform
pub fn ifft<'a, A, D>(array: A) -> Result<Array<Complex<f64>, D>, Error>
where
A: AsArray<'a, Complex<f64>, D>,
D: Dimension,
{
let mut input = array.into().to_owned();
let shape = input.shape().to_vec();
let mut tmp = ArrayD::zeros(shape.clone()).into_dimensionality()?;
for (i, s) in shape.iter().enumerate() {
let handler = FftHandler::new(*s).normalization(Normalization::None);
ndifft_par(&input.view(), &mut tmp.view_mut(), &handler, i);
std::mem::swap(&mut input, &mut tmp);
}
Ok(input / Complex::from(shape.iter().product::<usize>() as f64))
}
pub fn fft_freq(size: usize) -> Array1<f64> {
// let s = size as isize;
// let h = s / 2;
// (-h..h).map(|i| (i % s - s) as f64 / s as f64).collect()
let val = 1.0 / size as f64;
let mut results = Array1::zeros(size);
let n = (size - 1) / 2 + 1;
let p1 = Array1::range(0.0, n as f64, 1.0);
results.slice_mut(s![..n]).assign(&p1);
let p2 = Array1::range(-((size / 2) as f64), 0.0, 1.0);
results.slice_mut(s![n..]).assign(&p2);
results * val
}
pub fn fft_shift<'a, A, T, D>(x: A) -> Array<T, D>
where
A: AsArray<'a, T, D>,
T: 'a + Clone,
D: Dimension + RemoveAxis,
{
let mut x = x.into().to_owned();
let shift = x.shape().iter().map(|i| i / 2).collect::<Vec<_>>();
for (i, s) in shift.iter().enumerate() {
let (a, b) = x.view().split_at(Axis(i), *s);
x = concatenate(Axis(i), &[b, a]).unwrap();
}
x
}
pub fn gaussian(x: &[f64], mu: f64, sigma: f64) -> Vec<f64> {
let a = 2.0 * sigma.powi(2);
let b = (a * f64::PI()).sqrt();
x.iter()
.map(|i| (-(i - mu).powi(2) / a).exp() / b)
.collect()
}
/// Gaussian kernel in frequency space
pub fn gaussian_kernel<D>(shape: &[usize], sigma: &[f64]) -> Result<Array<Complex<f64>, D>, Error>
where
D: Dimension,
{
let mut g = Array::ones(shape).into_dimensionality()?;
for (i, (s, t)) in shape.iter().zip_eq(sigma.iter()).enumerate() {
let a = 0.5 / t.powi(2);
let f = (-(f64::PI() * fft_freq(*s)).powi(2) / a)
.exp()
.mapv(Complex::from);
for mut lane in g.lanes_mut(Axis(i)) {
lane.mul_assign(&f);
}
}
Ok(g)
}
/// smooth an array using a Gaussian kernel
pub fn gaussian_smooth<'a, A, D>(array: A, sigma: &[f64]) -> Result<Array<f64, D>, Error>
where
A: AsArray<'a, f64, D>,
D: Dimension,
{
let array = array.into().to_owned();
let shape = array.shape();
let kernel = gaussian_kernel::<D>(shape, sigma)?;
Ok(ifft((kernel * fft(array.view())?).view())?.mapv(|i| i.re))
}
+5
View File
@@ -0,0 +1,5 @@
pub mod detection;
pub mod error;
pub mod filter;
#[cfg(feature = "python")]
mod py;
+87
View File
@@ -0,0 +1,87 @@
mod detection;
mod filter;
use crate::error::Error;
use pyo3::exceptions::PyRuntimeError;
use pyo3::prelude::*;
use pyo3_stub_gen::derive::gen_stub_pyfunction;
use pyo3_stub_gen::{StubGenConfig, StubInfo};
use std::error::Error as StdError;
use std::path::PathBuf;
fn format_error_chain(err: &Error) -> String {
let mut msg = format!("[{}] {err}", err.variant_name());
let mut source = err.source();
while let Some(s) = source {
msg.push_str(&format!("\n |-> {s}"));
source = s.source();
}
msg
}
impl From<Error> for PyErr {
#[track_caller]
fn from(err: Error) -> PyErr {
let location = std::panic::Location::caller();
let msg = format!("{}: {}", location, format_error_chain(&err));
PyRuntimeError::new_err(msg)
}
}
/// generates .pyi files
#[gen_stub_pyfunction]
#[pyfunction]
pub fn generate_stub(dest_path: String) -> PyResult<()> {
Ok(StubInfo::from_project_root(
"smoll".to_string(),
PathBuf::from(dest_path).join("py"),
true,
StubGenConfig::default(),
)?
.generate()?)
}
#[pymodule]
#[pyo3(name = "smoll_rs")]
mod smoll_rs {
use pyo3::prelude::*;
#[pymodule_export]
use super::generate_stub;
#[pymodule]
mod detection {
#[pymodule_export]
use super::super::detection::PyFilter;
#[pymodule_export]
use super::super::detection::PyDetector;
#[pymodule_export]
use super::super::detection::local_maxima;
}
#[pymodule]
mod filter {
#[pymodule_export]
use super::super::filter::fft;
#[pymodule_export]
use super::super::filter::ifft;
#[pymodule_export]
use super::super::filter::fft_freq;
#[pymodule_export]
use super::super::filter::fft_shift;
#[pymodule_export]
use super::super::filter::gaussian;
#[pymodule_export]
use super::super::filter::gaussian_kernel;
#[pymodule_export]
use super::super::filter::gaussian_smooth;
}
}
+113
View File
@@ -0,0 +1,113 @@
use crate::detection;
use crate::detection::{AbsoluteThreshold, Detector, DoG, Filter, LoG, StdThreshold};
use numpy::{AllowTypeChange, IntoPyArray, PyArray2, PyArrayDyn, PyArrayLikeDyn};
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 {
#[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 {
#[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))
}
}
+75
View File
@@ -0,0 +1,75 @@
use crate::filter;
use numpy::{
AllowTypeChange, IntoPyArray, PyArray1, PyArrayDyn, PyArrayLikeDyn, PyArrayMethods,
PyReadonlyArrayDyn,
};
use pyo3::PyResult;
use pyo3::prelude::*;
use pyo3_stub_gen::derive::*;
/// Fourier transform
#[gen_stub_pyfunction(module = "smoll.filter")]
#[pyfunction]
pub(crate) fn fft<'py>(
py: Python<'py>,
#[gen_stub(override_type(type_repr="numpy.typing.ArrayLike", imports=("numpy.typing")))]
array: PyArrayLikeDyn<f64, AllowTypeChange>,
) -> PyResult<Bound<'py, PyArrayDyn<num::Complex<f64>>>> {
Ok(filter::fft(array.as_array())?.into_pyarray(py))
}
/// inverse Fourier transform
#[gen_stub_pyfunction(module = "smoll.filter")]
#[pyfunction]
pub(crate) fn ifft<'py>(
py: Python<'py>,
#[gen_stub(override_type(type_repr="numpy.typing.ArrayLike", imports=("numpy.typing")))]
array: PyReadonlyArrayDyn<'py, num::Complex<f64>>,
) -> PyResult<Bound<'py, PyArrayDyn<num::Complex<f64>>>> {
Ok(filter::ifft(array.readonly().as_array())?.into_pyarray(py))
}
#[gen_stub_pyfunction(module = "smoll.filter")]
#[pyfunction]
pub(crate) fn fft_freq<'py>(py: Python<'py>, size: usize) -> Bound<'py, PyArray1<f64>> {
filter::fft_freq(size).into_pyarray(py)
}
#[gen_stub_pyfunction(module = "smoll.filter")]
#[pyfunction]
pub(crate) fn fft_shift<'py>(
py: Python<'py>,
#[gen_stub(override_type(type_repr="numpy.typing.ArrayLike", imports=("numpy.typing")))]
array: PyArrayLikeDyn<f64, AllowTypeChange>,
) -> Bound<'py, PyArrayDyn<f64>> {
filter::fft_shift(array.as_array()).into_pyarray(py)
}
#[gen_stub_pyfunction(module = "smoll.filter")]
#[pyfunction]
pub(crate) fn gaussian(x: Vec<f64>, mu: f64, sigma: f64) -> Vec<f64> {
filter::gaussian(&x, mu, sigma)
}
/// Gaussian kernel in frequency space
#[gen_stub_pyfunction(module = "smoll.filter")]
#[pyfunction]
pub(crate) fn gaussian_kernel<'py>(
py: Python<'py>,
shape: Vec<usize>,
sigma: Vec<f64>,
) -> PyResult<Bound<'py, PyArrayDyn<num::Complex<f64>>>> {
Ok(filter::gaussian_kernel(&shape, &sigma)?.into_pyarray(py))
}
/// smooth an array using a Gaussian kernel
#[gen_stub_pyfunction(module = "smoll.filter")]
#[pyfunction]
pub(crate) fn gaussian_smooth<'py>(
py: Python<'py>,
#[gen_stub(override_type(type_repr="numpy.typing.ArrayLike", imports=("numpy.typing")))]
array: PyArrayLikeDyn<f64, AllowTypeChange>,
sigma: Vec<f64>,
) -> PyResult<Bound<'py, PyArrayDyn<f64>>> {
Ok(filter::gaussian_smooth(array.as_array(), &sigma)?.into_pyarray(py))
}