- finalized modal analysis

- Cayley transform for rotated gaussians
- all python objects now picklable
This commit is contained in:
Wim Pomp committed 2026-11-24 11:52:55 +01:00
1 parent 94e4bd3eb6
commit b3c7bf1461
15 files changed
+861 -186

No files matched your search

+3 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "smoll"
version = "0.0.1"
version = "0.0.2"
edition = "2024"
rust-version = "1.85.1"
authors = ["Wim Pomp <w.pomp@nki.nl>"]
@@ -13,6 +13,8 @@ keywords = ["science", "microscopy", "single-molecule", "detection", "localizati
categories = ["computer-vision", "science"]
[dependencies]
derive_builder = "0.20"
derive-getters = "0.5"
itertools = "0.15"
ndarray = { version = "0.17", features = ["rayon"] }
ndrustfft = "0.6"
+2
View File
@@ -5,3 +5,5 @@ A Rust/Python library for Single MOLecule Localization.
Implemented so far:
- Difference of Gaussian filter
- Finding particles using a local maximum filter and thresholding
- Generating ND gaussians
- Fitting using iterative modal analysis
+4 -3
View File
@@ -14,11 +14,12 @@ os.environ["RUST_BACKTRACE"] = "full"
os.environ["COLORBT_SHOW_HIDDEN"] = "1"
from .smoll_rs import generate_stub
from .smoll_rs import detection, filter, gaussian
from .smoll_rs import detection, filter, gaussian, linalg
sys.modules["smoll.detection"] = detection
sys.modules["smoll.filter"] = filter
sys.modules["smoll.filter"] = gaussian
sys.modules["smoll.gaussian"] = gaussian
sys.modules["smoll.linalg"] = linalg
try:
__version__ = version(Path(__file__).parent.name)
@@ -34,7 +35,7 @@ except Exception: # noqa
__git_commit_hash__ = "unknown"
__all__ = ["detection", "filter", "gaussian"]
__all__ = ["detection", "filter", "gaussian", "linalg"]
def smoll_generate_stub():
+2
View File
@@ -5,12 +5,14 @@ import builtins
from . import detection
from . import filter
from . import gaussian
from . import linalg
__all__ = [
"detection",
"filter",
"gaussian",
"generate_stub",
"linalg",
]
def generate_stub(dest_path: builtins.str) -> None:
+6
View File
@@ -13,6 +13,9 @@ __all__ = [
]
class Detector:
def __new__(cls, variant: builtins.str, *args: typing.Any) -> Detector: ...
def __repr__(self) -> builtins.str: ...
def __getnewargs__(self) -> tuple[builtins.str, typing.Any]: ...
@staticmethod
def abs(threshold: builtins.float) -> Detector: ...
@staticmethod
@@ -20,6 +23,9 @@ class Detector:
def detect(self, array: numpy.typing.ArrayLike) -> numpy.typing.NDArray[numpy.uint64]: ...
class Filter:
def __new__(cls, variant: builtins.str, *args: typing.Any) -> Filter: ...
def __repr__(self) -> builtins.str: ...
def __getnewargs__(self) -> tuple[builtins.str, typing.Any]: ...
@staticmethod
def dog(lower: typing.Sequence[builtins.float], upper: typing.Sequence[builtins.float]) -> Filter: ...
@staticmethod
+107 -34
View File
@@ -7,21 +7,125 @@ import numpy.typing
import typing
__all__ = [
"BackgroundSubtraction",
"ModelAnalysis",
"ModelAnalysisResult",
"gaussian",
"gaussian_pixel_int",
"modal_analysis",
]
class BackgroundSubtraction:
def __new__(cls, t: builtins.str) -> BackgroundSubtraction: ...
def __getnewargs__(self) -> builtins.str: ...
def __repr__(self) -> builtins.str: ...
@staticmethod
def none() -> BackgroundSubtraction: ...
@staticmethod
def constant() -> BackgroundSubtraction: ...
@staticmethod
def tilted() -> BackgroundSubtraction: ...
class ModelAnalysis:
r"""
Applies the algorithm from [Thompson et al. (2002) PNAS, 82:2775].
"""
@property
def sigma(self) -> list[float]: ...
@sigma.setter
def sigma(self, value: numpy.typing.ArrayLike) -> None: ...
@property
def window_shape(self) -> list[int]: ...
@window_shape.setter
def window_shape(self, value: numpy.typing.ArrayLike) -> None: ...
@property
def max_iterations(self) -> builtins.int: ...
@max_iterations.setter
def max_iterations(self, value: builtins.int) -> None: ...
@property
def tolerance(self) -> builtins.float: ...
@tolerance.setter
def tolerance(self, value: builtins.float) -> None: ...
@property
def background_subtraction(self) -> BackgroundSubtraction: ...
@background_subtraction.setter
def background_subtraction(self, value: typing.Any) -> None: ...
@property
def fix_location(self) -> builtins.bool: ...
@fix_location.setter
def fix_location(self, value: builtins.bool) -> None: ...
def __new__(
cls,
sigma: typing.Sequence[builtins.float],
window_shape: typing.Sequence[builtins.int],
max_iterations: builtins.int = 20,
tolerance: builtins.float = 0.01,
background_subtraction: typing.Optional[typing.Any] = None,
fix_location: builtins.bool = False,
) -> ModelAnalysis: ...
def __repr__(self) -> builtins.str: ...
def __getnewargs__(
self,
) -> tuple[
builtins.list[builtins.float],
builtins.list[builtins.int],
builtins.int,
builtins.float,
builtins.str,
builtins.bool,
]: ...
def fit(self, g: numpy.typing.ArrayLike, x: numpy.typing.ArrayLike) -> ModelAnalysisResult: ...
def with_sigma(self, sigma: numpy.typing.ArrayLike) -> ModelAnalysis: ...
def with_window_shape(self, window_shape: numpy.typing.ArrayLike) -> ModelAnalysis: ...
def with_max_iterations(self, max_iterations: builtins.int) -> ModelAnalysis: ...
def with_tolerance(self, tolerance: builtins.float) -> ModelAnalysis: ...
def with_background_subtraction(self, background_subtraction: typing.Any) -> ModelAnalysis: ...
def with_fix_location(self, fix_location: builtins.bool) -> ModelAnalysis: ...
class ModelAnalysisResult:
@property
def iterations(self) -> builtins.int: ...
@property
def integrated_intensity(self) -> builtins.float: ...
@property
def position(self) -> list[float]: ...
@property
def sigma(self) -> list[float]: ...
@property
def background(self) -> list[float]: ...
def __new__(
cls,
iterations: builtins.int,
integrated_intensity: builtins.float,
position: typing.Sequence[builtins.float],
sigma: typing.Sequence[builtins.float],
background: typing.Sequence[builtins.float],
) -> ModelAnalysisResult: ...
def __repr__(self) -> builtins.str: ...
def __getnewargs__(
self,
) -> tuple[
builtins.int,
builtins.float,
builtins.list[builtins.float],
builtins.list[builtins.float],
builtins.list[builtins.float],
]: ...
def gaussian(x: numpy.typing.ArrayLike, p: numpy.typing.ArrayLike) -> numpy.typing.NDArray[numpy.float64]:
r"""
p: I, x0, x1, ... xn-1, s0, s1, ..., sn-1, r0, r1, ..., rm-1, o, o0, o1, ..., on-1
r: upper triangle without diagonal of (I-R)*(I+R)^{-1} (Cayley transform),
for 2D: theta(theta/2)
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
"""
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
p: I, x0, x1, ... xn-1, s0, s1, ..., sn-1, r0, r1, ..., rm-1, o, o0, o1, ..., on-1
r: upper triangle without diagonal of (I-R)*(I+R)^{-1} (Cayley transform),
for 2D: theta(theta/2)
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
@@ -35,34 +139,3 @@ def gaussian_pixel_int(x: numpy.typing.ArrayLike, p: numpy.typing.ArrayLike) ->
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
"""
+14
View File
@@ -0,0 +1,14 @@
# This file is automatically generated by pyo3_stub_gen
# ruff: noqa: E501, F401, F403, F405
import builtins
import numpy
import numpy.typing
__all__ = [
"rotation_from_skew",
"skew_from_rotation",
]
def rotation_from_skew(a: numpy.typing.ArrayLike) -> numpy.typing.NDArray[numpy.float64]: ...
def skew_from_rotation(r: numpy.typing.ArrayLike) -> builtins.list[builtins.float]: ...
+16 -4
View File
@@ -15,8 +15,8 @@ pub trait Filter {
#[derive(Debug, Clone, PartialEq)]
pub struct DoG {
lower: Vec<f64>,
upper: Vec<f64>,
pub lower: Vec<f64>,
pub upper: Vec<f64>,
}
impl DoG {
@@ -74,11 +74,17 @@ pub trait Detector {
D: Dimension;
}
#[derive(Debug, Clone, PartialEq)]
#[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;
@@ -107,11 +113,17 @@ impl Detector for AbsoluteThreshold {
}
}
#[derive(Debug, Clone, PartialEq)]
#[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;
+10
View File
@@ -4,6 +4,10 @@ pub enum Error {
SingularMatrix,
#[error("maximum iterations reached: {0}")]
MaxIterations(usize),
#[error("fit landed outside fit window")]
OutsideFitWindow,
#[error("uninitialized field: {0}")]
UninitializedField(String),
#[error(transparent)]
ParseError(#[from] strum::ParseError),
@@ -11,6 +15,12 @@ pub enum Error {
ShapeError(#[from] ndarray::ShapeError),
}
impl From<derive_builder::UninitializedFieldError> for Error {
fn from(value: derive_builder::UninitializedFieldError) -> Self {
Self::UninitializedField(value.to_string())
}
}
impl Error {
/// the name of the error variant as a static string
pub fn variant_name(&self) -> &'static str {
+191 -97
View File
@@ -1,5 +1,7 @@
use crate::error::Error;
use crate::linalg::{linefit, lu_factor, matrix_determinant, matrix_inverse, symmetric_eigen};
use crate::linalg::{linefit, rotation_from_skew, symmetric_eigen};
use derive_builder::Builder;
use derive_getters::Getters;
use itertools::Itertools;
use ndarray::{
Array, Array1, Array2, ArrayView1, AsArray, Axis, Dimension, IntoDimension, Ix1, SliceInfoElem,
@@ -10,7 +12,9 @@ use strum::EnumString;
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-1, s0, s1, ..., sn-1, r0, r1, ..., rm-1, o, o0, o1, ..., on-1
/// r: upper triangle without diagonal of (I-R)*(I+R)^{-1} (Cayley transform),
/// for 2D: theta(theta/2)
/// x: n 1d arrays, defining coordinates in each dimension
pub fn gaussian<'a, A, D>(x: Vec<A>, p: &[f64]) -> Result<Array<f64, D>, Error>
where
@@ -18,22 +22,21 @@ where
D: Dimension,
{
let n = x.len();
let n2 = n * n;
let n2 = n * (n - 1) / 2;
debug_assert_eq!(
p.len(),
2 + 2 * n + n2,
2 + 3 * n + n2,
"number of parameters must be {}",
2 + 2 * n + n2
2 + 3 * n + n2
);
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 (lu, perm) = lu_factor(&c)?;
let c_inv = matrix_inverse(&lu, &perm);
let c_det = matrix_determinant(&lu, &perm);
let a = p[0] * FRAC_1_SQRT_2_PI.powi(n as i32) / c_det.sqrt();
let m = ArrayView1::from(&p[1..1 + n]); // n means
let s = ArrayView1::from(&p[1 + n..1 + 2 * n]); // n sigmas
let r = rotation_from_skew(&p[1 + 2 * n..1 + 2 * n + n2])?; // n * (n - 1) / 2 upper triangle rotation
let o = p[1 + 2 * n + n2];
let q = ArrayView1::from(&p[2 + 2 * n + n2..]); // n tilted offset
let c = r.dot(&Array2::from_diag(&s.mapv(|i| 1.0 / i))).dot(&r.t()); // inverse covariance matrix
let a = p[0] * FRAC_1_SQRT_2_PI.powi(n as i32) / s.product().sqrt();
let x = x
.into_iter()
.map(|i| i.into())
@@ -47,14 +50,16 @@ where
.multi_cartesian_product()
.map(|i| {
let xj = ArrayView1::from(&i).insert_axis(Axis(0));
a * (-0.5 * xj.dot(&c_inv).dot(&xj.t())).sum().exp() + o + q.dot(&xj.t()).sum()
a * (-0.5 * xj.dot(&c).dot(&xj.t())).sum().exp() + o + q.dot(&xj.t()).sum()
})
.collect(),
)?
.into_dimensionality()?)
}
/// p: I, x0, x1, ... xn, s00, s01, ..., s0n, s10, s11, ..., s1n, ..., sn0, sn1, ..., snn, o, o0, o1, ..., on
/// p: I, x0, x1, ... xn-1, s0, s1, ..., sn-1, r0, r1, ..., rm-1, o, o0, o1, ..., on-1
/// r: upper triangle without diagonal of (I-R)*(I+R)^{-1} (Cayley transform),
/// for 2D: theta(theta/2)
/// x: n 1d arrays, defining coordinates in each dimension
/// gaussian, but the signal is integrated over each pixel
///
@@ -74,19 +79,20 @@ where
D: Dimension,
{
let n = x.len();
let n2 = n * n;
let n2 = n * (n - 1) / 2;
debug_assert_eq!(
p.len(),
2 + 2 * n + n2,
2 + 3 * n + n2,
"number of parameters must be {}",
2 + 2 * n + n2
2 + 3 * 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 m = ArrayView1::from(&p[1..1 + n]); // n means
let s = ArrayView1::from(&p[1 + n..1 + 2 * n]); // n sigmas
let r = rotation_from_skew(&p[1 + 2 * n..1 + 2 * n + n2])?; // n * (n - 1) / 2 upper triangle rotation
let o = p[1 + 2 * n + n2];
let q = ArrayView1::from(&p[2 + 2 * n + n2..]); // n tilted offset
let c = r.dot(&Array2::from_diag(&s)).dot(&r.t()); // inverse covariance matrix
let (w, ev) = symmetric_eigen(&c);
let wmax = w.iter().copied().fold(0.0f64, f64::max);
let tol = (n as f64) * f64::EPSILON * wmax;
@@ -118,42 +124,77 @@ where
.into_dimensionality()?)
}
#[derive(Debug, Clone, EnumString)]
#[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,
}
}
}
/// Applies the algorithm from [Thompson et al. (2002) PNAS, 82:2775].
/// Parameters:
#[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 {
/// - 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>
pub fn fit<'a, A, D>(&self, g: A, x: &[f64]) -> Result<ModalAnalysisResult, Error>
where
A: AsArray<'a, f64, D>,
D: Dimension,
@@ -162,41 +203,43 @@ where
let shape = g.shape();
let ndim = shape.len();
let mut x = x.to_vec();
for _ in 0..n_iter {
for iteration in 0..self.max_iterations {
if x.iter()
.zip(window_size)
.zip(&self.window_shape)
.any(|(xi, &wi)| xi - (wi as f64 / 2.0) < 0.0)
|| x.iter()
.zip(window_size)
.zip(&self.window_shape)
.zip(shape)
.any(|((xi, &wi), &si)| xi - (wi as f64 / 2.0) > si as f64)
{
break;
return Err(Error::OutsideFitWindow);
}
let win_orig = x
.iter()
.zip(window_size)
.map(|(xi, &wi)| (xi - wi as f64 / 2.0) as isize)
.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(
shape,
self.window_shape.as_slice(),
x.iter()
.zip(window_size)
.map(|(xi, &wi)| (0..wi).map(|wii| wii as f64 - *xi))
.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| {
-xii.iter()
.zip(s)
.map(|(xiii, si)| {
(xiii / (2.0 * si)).powi(2) / (std::f64::consts::TAU * si.powi(2))
})
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(window_size)
.zip(&self.window_shape)
.map(|(&oi, &si)| SliceInfoElem::Slice {
start: oi,
end: Some(oi + si as isize),
@@ -204,7 +247,7 @@ where
})
.collect::<Vec<_>>();
let mut gs = g.slice(slice.as_slice()).to_owned();
let bg = match background_subtraction {
let bg = match self.background_subtraction {
BackgroundSubtraction::None => vec![0.0; 1 + ndim],
BackgroundSubtraction::Constant => {
let mut bg = vec![0.0; 1 + ndim];
@@ -216,10 +259,14 @@ where
};
ndim
];
let n = shape.iter().product::<usize>()
- shape.iter().map(|i| i - 2).product::<usize>();
let n = self.window_shape.iter().product::<usize>()
- self.window_shape.iter().map(|i| i - 2).product::<usize>();
// mean of values around edges
bg[0] = shape.iter().enumerate().fold(0.0, |mut acc, (i, &si)| {
bg[0] = self
.window_shape
.iter()
.enumerate()
.fold(0.0, |mut acc, (i, &si)| {
slice[i] = SliceInfoElem::Slice {
start: 0,
end: None,
@@ -228,11 +275,12 @@ where
acc += gs.slice(slice.as_slice()).sum();
slice[i] = SliceInfoElem::Slice {
start: 1,
end: Some(si as isize - 2),
end: Some(si as isize - 1),
step: 1,
};
acc
}) / n as f64;
})
/ n as f64;
gs -= bg[0];
bg
}
@@ -250,21 +298,24 @@ where
perm.push(0);
let perm = perm.into_dimension();
// rotate axes, for each dimension fitting edges with y = a*x + b
bg.extend(shape.iter().zip(&x).map(|(&si, xi)| {
bg.extend(self.window_shape.iter().zip(&win_orig).zip(&x).map(
|((&si, &oi), &xi)| {
let mut xx = Vec::from_iter(0..si);
xx.extend(0..si);
let xx = Array1::from_vec(xx).mapv(|i| i as f64 - xi);
let xx = Array1::from_vec(xx).mapv(|i| oi as f64 - xi + i as f64);
slice[0] = SliceInfoElem::Slice {
start: 0,
end: None,
step: (si as isize - 1).max(1),
};
let yy = gs.slice(slice.as_slice());
let (a, b) = linefit(xx.view(), yy.flatten());
gs = &gs - a * Array1::from_iter(0..si).mapv(|i| i as f64 - xi) - b;
let (a, _) = linefit(xx.view(), yy.flatten());
gs = &gs
- a * Array1::from_iter(0..si).mapv(|i| oi as f64 - xi + i as f64);
gs.permute_axes(perm.clone());
a
}));
},
));
slice = vec![
SliceInfoElem::Slice {
start: 0,
@@ -273,10 +324,18 @@ where
};
ndim
];
let n = shape.iter().product::<usize>()
- shape.iter().map(|i| i.saturating_sub(2)).product::<usize>();
let n = self.window_shape.iter().product::<usize>()
- self
.window_shape
.iter()
.map(|i| i.saturating_sub(2))
.product::<usize>();
// mean of values around edges
bg[0] = shape.iter().enumerate().fold(0.0, |mut acc, (i, &si)| {
bg[0] = self
.window_shape
.iter()
.enumerate()
.fold(0.0, |mut acc, (i, &si)| {
slice[i] = SliceInfoElem::Slice {
start: 0,
end: None,
@@ -285,45 +344,56 @@ where
acc += gs.slice(slice.as_slice()).sum();
slice[i] = SliceInfoElem::Slice {
start: 1,
end: Some(si as isize - 2),
end: Some(si as isize - 1),
step: 1,
};
acc
}) / n as f64;
})
/ n as f64;
gs -= bg[0];
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);
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 = x
let new_x = win_orig
.iter()
.enumerate()
.map(|(i, xi)| {
gss.axis_iter(Axis(i))
.map(|(i, oi)| {
sn.axis_iter(Axis(i))
.enumerate()
.flat_map(|(j, gssi)| &gssi * (j as f64 - xi))
.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())) <= tolerance {
let mut p = vec![ssn / nn.powi(2).sum()];
p.extend_from_slice(&new_x);
p.extend_from_slice(&bg);
return Ok(p);
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(n_iter))
Err(Error::MaxIterations(self.max_iterations))
}
}
/// Analytic integral of the 1D gaussian `exp(-t^2/(2w)) / sqrt(2*pi*w)`
@@ -349,6 +419,7 @@ fn pixel_factor(z: f64, w: f64, tol: f64) -> f64 {
#[cfg(test)]
mod tests {
use super::*;
use ndarray::Ix2;
#[test]
fn test_pixel_factor() {
@@ -548,4 +619,27 @@ mod tests {
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![3.0; 2])
.window_shape([5; 2])
.build()?;
let g = gaussian::<_, Ix2>(x.clone(), &[1.0, 32.3, 31.5, 3.0, 3.0, 0.0, 0.0, 0.0, 0.0])?;
let p = m.fit(&g, &[32.0; 2])?;
println!("p: {:?}", p);
let g = gaussian::<_, Ix2>(x.clone(), &[1.0, 32.3, 31.5, 3.0, 3.0, 0.0, 4.0, 0.0, 0.0])?;
m.background_subtraction = BackgroundSubtraction::Constant;
let p = m.fit(&g, &[32.0; 2])?;
println!("p: {:?}", p);
let g = gaussian::<_, Ix2>(x, &[1.0, 32.3, 31.5, 3.0, 3.0, 0.0, 4.0, -1.0, 2.0])?;
m.background_subtraction = BackgroundSubtraction::Tilted;
let p = m.fit(&g, &[32.0; 2])?;
println!("p: {:?}", p);
Ok(())
}
}
+32 -2
View File
@@ -1,5 +1,5 @@
use crate::error::Error;
use ndarray::{Array1, Array2, ArrayView1, AsArray, CowArray, Ix1, Ix2};
use ndarray::{Array1, Array2, ArrayView1, ArrayView2, AsArray, CowArray, Ix1, Ix2};
use statrs::statistics::Statistics;
/// Eigen-decomposition of a symmetric matrix using cyclic Jacobi rotations.
@@ -7,7 +7,6 @@ use statrs::statistics::Statistics;
/// Returns the eigenvalues and the eigenvectors (as **columns** of the
/// second array), such that `matrix` = `eigenvectors` · diag(eigenvalues) · `eigenvectors`.t().
pub(crate) 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");
@@ -160,8 +159,39 @@ pub(crate) fn matrix_inverse(lu: &Array2<f64>, perm: &[usize]) -> Array2<f64> {
inv
}
/// R = (I - A) * (I + A)^{-1}; A^T = -A, using Cayley transform
pub(crate) fn rotation_from_skew(r: &[f64]) -> Result<Array2<f64>, Error> {
let n = (2 * r.len()).isqrt() + 1; // invert n -> n * (n - 1) / 2
let mut a = Array2::<f64>::zeros((n, n));
let mut r = r.iter();
for i in 0..n {
for j in (1 + i)..n {
if let Some(r) = r.next() {
a[[i, j]] = *r;
a[[j, i]] = -r;
}
}
}
let ii = Array2::<f64>::eye(n);
let (lu, perm) = lu_factor(&(&ii + &a))?;
Ok((&ii - &a).dot(&matrix_inverse(&lu, &perm)))
}
/// A = (I - R) * (I + R)^{-1}; A^T = -A, using Cayley transform
pub(crate) fn skew_from_rotation(r: ArrayView2<f64>) -> Result<Vec<f64>, Error> {
let n = r.nrows();
let ii = Array2::<f64>::eye(n);
let (lu, perm) = lu_factor(&(&ii + &r))?;
Ok((&ii - &r)
.dot(&matrix_inverse(&lu, &perm))
.indexed_iter()
.filter_map(|((i, j), &k)| if i < j { Some(k) } else { None })
.collect::<Vec<f64>>())
}
/// Calculate the determinant of a square matrix using LU factorization
/// with partial pivoting.
#[allow(dead_code)]
pub(crate) fn matrix_determinant(lu: &Array2<f64>, perm: &[usize]) -> f64 {
// sign of the row permutation: parity of its inversion count
let inversions = (1..perm.len())
+17 -1
View File
@@ -1,6 +1,7 @@
mod detection;
mod filter;
mod gaussian;
mod linalg;
use crate::error::Error;
use pyo3::exceptions::PyRuntimeError;
@@ -95,6 +96,21 @@ mod smoll_rs {
use super::super::gaussian::gaussian_pixel_int;
#[pymodule_export]
use super::super::gaussian::modal_analysis;
use super::super::gaussian::PyBackgroundSubtraction;
#[pymodule_export]
use super::super::gaussian::PyModalAnalysis;
#[pymodule_export]
use super::super::gaussian::PyModalAnalysisResult;
}
#[pymodule]
mod linalg {
#[pymodule_export]
use super::super::linalg::skew_from_rotation;
#[pymodule_export]
use super::super::linalg::rotation_from_skew;
}
}
+69
View File
@@ -1,6 +1,8 @@
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::*;
@@ -20,6 +22,40 @@ pub(crate) struct PyFilter {
#[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 {
@@ -82,6 +118,39 @@ pub(crate) struct PyDetector {
#[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 {
+359 -44
View File
@@ -1,11 +1,14 @@
use crate::error::Error;
use crate::gaussian as gaussian_rs;
use crate::gaussian::{BackgroundSubtraction, ModalAnalysis, ModalAnalysisResult};
use numpy::{AllowTypeChange, IntoPyArray, PyArrayDyn, PyArrayLike1, PyArrayLikeDyn};
use pyo3::prelude::*;
use pyo3_stub_gen::derive::*;
/// p: I, x0, x1, ... xn-1, s0, s1, ..., sn-1, r0, r1, ..., rm-1, o, o0, o1, ..., on-1
/// r: upper triangle without diagonal of (I-R)*(I+R)^{-1} (Cayley transform),
/// for 2D: theta(theta/2)
/// 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
#[gen_stub_pyfunction(module = "smoll.gaussian")]
#[pyfunction]
pub(crate) fn gaussian<'py>(
@@ -31,8 +34,11 @@ pub(crate) fn gaussian<'py>(
.into_pyarray(py))
}
/// p: I, x0, x1, ... xn, s00, s01, ..., s0n, s10, s11, ..., s1n, ..., sn0, sn1, ..., snn, o, o0, o1, ..., on
/// p: I, x0, x1, ... xn-1, s0, s1, ..., sn-1, r0, r1, ..., rm-1, o, o0, o1, ..., on-1
/// r: upper triangle without diagonal of (I-R)*(I+R)^{-1} (Cayley transform),
/// for 2D: theta(theta/2)
/// 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
@@ -70,50 +76,359 @@ pub(crate) fn gaussian_pixel_int<'py>(
.into_pyarray(py))
}
#[gen_stub_pyclass]
#[pyclass(
subclass,
from_py_object,
name = "BackgroundSubtraction",
module = "smoll.gaussian"
)]
#[derive(Debug, Clone, PartialEq, Copy)]
pub(crate) struct PyBackgroundSubtraction {
inner: BackgroundSubtraction,
}
#[gen_stub_pymethods]
#[pymethods]
impl PyBackgroundSubtraction {
#[new]
fn new(t: String) -> PyResult<Self> {
Ok(Self {
inner: t.parse().map_err(Error::from)?,
})
}
fn __getnewargs__(&self) -> String {
format!("{:?}", self.inner)
}
fn __repr__(&self) -> String {
format!("{:?}", self.inner)
}
#[staticmethod]
fn none() -> Self {
Self {
inner: BackgroundSubtraction::None,
}
}
#[staticmethod]
fn constant() -> Self {
Self {
inner: BackgroundSubtraction::Constant,
}
}
#[staticmethod]
fn tilted() -> Self {
Self {
inner: BackgroundSubtraction::Tilted,
}
}
}
#[gen_stub_pyclass]
#[pyclass(
subclass,
from_py_object,
name = "ModelAnalysisResult",
module = "smoll.gaussian"
)]
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct PyModalAnalysisResult {
inner: ModalAnalysisResult,
}
#[gen_stub_pymethods]
#[pymethods]
impl PyModalAnalysisResult {
#[new]
fn new(
iterations: usize,
integrated_intensity: f64,
position: Vec<f64>,
sigma: Vec<f64>,
background: Vec<f64>,
) -> Self {
Self {
inner: ModalAnalysisResult::new(
iterations,
integrated_intensity,
position,
sigma,
background,
),
}
}
fn __repr__(&self) -> String {
format!("{:?}", self.inner)
}
fn __getnewargs__(&self) -> (&usize, &f64, &Vec<f64>, &Vec<f64>, &Vec<f64>) {
(
self.inner.iterations(),
self.inner.integrated_intensity(),
self.inner.position(),
self.inner.sigma(),
self.inner.background(),
)
}
#[getter]
fn iterations(&self) -> &usize {
self.inner.iterations()
}
#[getter]
fn integrated_intensity(&self) -> &f64 {
self.inner.integrated_intensity()
}
#[gen_stub(override_return_type(type_repr = "list[float]"))]
#[getter]
fn position(&self) -> &[f64] {
self.inner.position()
}
#[gen_stub(override_return_type(type_repr = "list[float]"))]
#[getter]
fn sigma(&self) -> &[f64] {
self.inner.sigma()
}
#[gen_stub(override_return_type(type_repr = "list[float]"))]
#[getter]
fn background(&self) -> &[f64] {
self.inner.background()
}
}
/// 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_pyclass]
#[pyclass(
subclass,
from_py_object,
name = "ModelAnalysis",
module = "smoll.gaussian"
)]
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct PyModalAnalysis {
inner: ModalAnalysis,
}
#[gen_stub_pymethods]
#[pymethods]
impl PyModalAnalysis {
#[new]
#[pyo3(signature = (sigma, window_shape, max_iterations=20, tolerance=1e-2, background_subtraction=None, fix_location=false))]
fn new(
sigma: Vec<f64>,
window_shape: Vec<usize>,
max_iterations: usize,
tolerance: f64,
background_subtraction: Option<Bound<PyAny>>,
fix_location: bool,
) -> PyResult<Self> {
let background_subtraction = if let Some(background_subtraction) = background_subtraction {
if let Ok(background_subtraction) =
background_subtraction.extract::<PyBackgroundSubtraction>()
{
background_subtraction.inner
} else {
background_subtraction
.call_method0("__str__")?
.extract::<String>()?
.parse()
.map_err(Error::from)?
}
} else {
BackgroundSubtraction::None
};
Ok(Self {
inner: ModalAnalysis {
sigma,
window_shape,
max_iterations,
tolerance,
background_subtraction,
fix_location,
},
})
}
fn __repr__(&self) -> String {
format!("{:?}", self.inner)
}
fn __getnewargs__(&self) -> (&Vec<f64>, &Vec<usize>, &usize, &f64, String, &bool) {
(
&self.inner.sigma,
&self.inner.window_shape,
&self.inner.max_iterations,
&self.inner.tolerance,
format!("{:?}", self.inner.background_subtraction),
&self.inner.fix_location,
)
}
fn fit(
&self,
py: Python,
#[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>> {
#[gen_stub(override_type(type_repr="numpy.typing.ArrayLike", imports=("numpy.typing")))]
x: PyArrayLike1<f64, AllowTypeChange>,
) -> PyResult<PyModalAnalysisResult> {
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,
)
})?)
let x = x.as_array();
let result = if let Some(x) = x.as_slice() {
py.detach(|| self.inner.fit(g, x))?
} else {
let x = x.to_vec();
py.detach(|| self.inner.fit(g, &x))?
};
Ok(PyModalAnalysisResult { inner: result })
}
fn with_sigma<'py>(
mut slf: PyRefMut<'py, Self>,
#[gen_stub(override_type(type_repr="numpy.typing.ArrayLike", imports=("numpy.typing")))]
sigma: PyArrayLike1<f64, AllowTypeChange>,
) -> PyRefMut<'py, Self> {
slf.inner.sigma = sigma.as_array().to_vec();
slf
}
#[gen_stub(override_return_type(type_repr = "list[float]"))]
#[getter]
fn get_sigma(&self) -> &[f64] {
self.inner.sigma.as_slice()
}
#[setter]
fn set_sigma(
&mut self,
#[gen_stub(override_type(type_repr="numpy.typing.ArrayLike", imports=("numpy.typing")))]
sigma: PyArrayLike1<f64, AllowTypeChange>,
) {
self.inner.sigma = sigma.as_array().to_vec();
}
fn with_window_shape<'py>(
mut slf: PyRefMut<'py, Self>,
#[gen_stub(override_type(type_repr="numpy.typing.ArrayLike", imports=("numpy.typing")))]
window_shape: PyArrayLike1<usize, AllowTypeChange>,
) -> PyRefMut<'py, Self> {
slf.inner.window_shape = window_shape.as_array().to_vec();
slf
}
#[gen_stub(override_return_type(type_repr = "list[int]"))]
#[getter]
fn get_window_shape(&self) -> &[usize] {
self.inner.window_shape.as_slice()
}
#[setter]
fn set_window_shape(
&mut self,
#[gen_stub(override_type(type_repr="numpy.typing.ArrayLike", imports=("numpy.typing")))]
window_shape: PyArrayLike1<usize, AllowTypeChange>,
) {
self.inner.window_shape = window_shape.as_array().to_vec();
}
fn with_max_iterations(
mut slf: PyRefMut<'_, Self>,
max_iterations: usize,
) -> PyRefMut<'_, Self> {
slf.inner.max_iterations = max_iterations;
slf
}
#[getter]
fn get_max_iterations(&self) -> usize {
self.inner.max_iterations
}
#[setter]
fn set_max_iterations(&mut self, max_iterations: usize) {
self.inner.max_iterations = max_iterations;
}
fn with_tolerance(mut slf: PyRefMut<'_, Self>, tolerance: f64) -> PyRefMut<'_, Self> {
slf.inner.tolerance = tolerance;
slf
}
#[getter]
fn get_tolerance(&self) -> f64 {
self.inner.tolerance
}
#[setter]
fn set_tolerance(&mut self, tolerance: f64) {
self.inner.tolerance = tolerance;
}
fn with_background_subtraction<'py>(
mut slf: PyRefMut<'py, Self>,
background_subtraction: Bound<'py, PyAny>,
) -> PyResult<PyRefMut<'py, Self>> {
if let Ok(background_subtraction) =
background_subtraction.extract::<PyBackgroundSubtraction>()
{
slf.inner.background_subtraction = background_subtraction.inner;
} else {
slf.inner.background_subtraction = background_subtraction
.call_method0("__str__")?
.extract::<String>()?
.parse()
.map_err(Error::from)?;
};
Ok(slf)
}
#[getter]
fn get_background_subtraction(&self) -> PyBackgroundSubtraction {
PyBackgroundSubtraction {
inner: self.inner.background_subtraction,
}
}
#[setter]
fn set_background_subtraction(
&mut self,
background_subtraction: Bound<'_, PyAny>,
) -> PyResult<()> {
if let Ok(background_subtraction) =
background_subtraction.extract::<PyBackgroundSubtraction>()
{
self.inner.background_subtraction = background_subtraction.inner;
} else {
self.inner.background_subtraction = background_subtraction
.call_method0("__str__")?
.extract::<String>()?
.parse()
.map_err(Error::from)?;
}
Ok(())
}
fn with_fix_location(mut slf: PyRefMut<'_, Self>, fix_location: bool) -> PyRefMut<'_, Self> {
slf.inner.fix_location = fix_location;
slf
}
#[getter]
fn get_fix_location(&self) -> bool {
self.inner.fix_location
}
#[setter]
fn set_fix_location(&mut self, fix_location: bool) {
self.inner.fix_location = fix_location;
}
}
+29
View File
@@ -0,0 +1,29 @@
use crate::linalg;
use numpy::{AllowTypeChange, IntoPyArray, PyArray2, PyArrayLike1, PyArrayLike2};
use pyo3::prelude::*;
use pyo3_stub_gen::derive::*;
#[gen_stub_pyfunction(module = "smoll.linalg")]
#[pyfunction]
pub(crate) fn skew_from_rotation(
#[gen_stub(override_type(type_repr="numpy.typing.ArrayLike", imports=("numpy.typing")))]
r: PyArrayLike2<f64, AllowTypeChange>,
) -> PyResult<Vec<f64>> {
Ok(linalg::skew_from_rotation(r.as_array())?)
}
#[gen_stub_pyfunction(module = "smoll.linalg")]
#[pyfunction]
pub(crate) fn rotation_from_skew<'py>(
py: Python<'py>,
#[gen_stub(override_type(type_repr="numpy.typing.ArrayLike", imports=("numpy.typing")))]
a: PyArrayLike1<f64, AllowTypeChange>,
) -> PyResult<Bound<'py, PyArray2<f64>>> {
let a = a.as_array();
if let Some(a) = a.as_slice() {
Ok(linalg::rotation_from_skew(a)?.into_pyarray(py))
} else {
let a = a.to_vec();
Ok(linalg::rotation_from_skew(&a)?.into_pyarray(py))
}
}