use crate::backend_ops::{BackendOps, ElementwiseOps, ReductionOps, ScalarPowerOps};
use crate::binary;
use coeus_core::Float;
use coeus_tensor::Tensor;
#[inline]
pub fn norm<T: Float, B: BackendOps<T> + Default>(
a: &Tensor<T, B>,
backend: &B,
) -> Result<T, B::Error> {
let n = a.numel();
if n == 0 {
return Ok(T::ZERO);
}
let flattened = if a.is_contiguous() && a.layout().offset() == 0 {
a.reshape([n])
} else {
a.to_contiguous_on(backend).reshape([n])
};
let sq = binary::mul(&flattened, &flattened, backend);
Ok(<T as Float>::sqrt(super::sum(&sq, backend)?))
}
#[inline]
pub fn norm_p_tensor<
T: Float,
B: ElementwiseOps<T> + ReductionOps<T> + ScalarPowerOps<T> + Default,
>(
a: &Tensor<T, B>,
p: T,
backend: &B,
) -> Tensor<T, B> {
let n = a.numel();
assert!(n > 0, "norm_p: empty tensor has no norm");
assert!(
p > T::zero() && <T as Float>::is_finite(p),
"norm_p: ord must be a finite positive number, got {p:?}"
);
let magnitudes = crate::abs(a, backend);
let powered = crate::pow_scalar(&magnitudes, p, backend);
let flattened = powered.reshape([n]);
let summed = super::sum_axis(&flattened, 0, backend).expect("norm_p: provider sum");
crate::pow_scalar(&summed, T::one() / p, backend)
}
#[inline]
pub fn norm_p<T: Float, B: ElementwiseOps<T> + ReductionOps<T> + ScalarPowerOps<T> + Default>(
a: &Tensor<T, B>,
p: T,
backend: &B,
) -> T {
let result = norm_p_tensor(a, p, backend);
let mut scalar = [T::zero()];
backend.copy_to_host(result.storage(), &mut scalar);
scalar[0]
}
#[inline]
pub fn norm_p_axis<
T: Float,
B: ElementwiseOps<T> + ReductionOps<T> + ScalarPowerOps<T> + Default,
>(
a: &Tensor<T, B>,
p: T,
axis: usize,
backend: &B,
) -> Tensor<T, B> {
assert!(axis < a.ndim(), "norm_p_axis: axis {axis} out of bounds");
let n_axis = a.shape()[axis];
assert!(n_axis > 0, "norm_p_axis: axis {axis} has zero elements");
assert!(
p > T::zero() && <T as Float>::is_finite(p),
"norm_p_axis: ord must be a finite positive number, got {p:?}"
);
let magnitudes = crate::abs(a, backend);
let powered = crate::pow_scalar(&magnitudes, p, backend);
let summed = super::sum_axis(&powered, axis, backend).expect("norm_p_axis: provider sum");
crate::pow_scalar(&summed, T::one() / p, backend)
}
#[inline]
pub fn frobenius_norm<T: Float, B: BackendOps<T> + Default>(
a: &Tensor<T, B>,
backend: &B,
) -> Result<T, B::Error> {
norm(a, backend)
}
#[inline]
pub fn frobenius_norm_batched<T: Float, B: BackendOps<T> + Default>(
a: &Tensor<T, B>,
backend: &B,
) -> Result<Tensor<T, B>, B::Error> {
let ndim = a.ndim();
assert!(
ndim >= 2,
"frobenius_norm_batched: tensor must have rank >= 2, got ndim={ndim}"
);
if ndim == 2 {
let v = norm(a, backend)?;
return Ok(Tensor::from_slice_on([], &[v], backend));
}
let contiguous = if a.is_contiguous() && a.layout().offset() == 0 {
a.reshape(a.shape().to_vec())
} else {
a.to_contiguous_on(backend)
};
let squared = binary::mul(&contiguous, &contiguous, backend);
let reduced_last = super::sum_axis(&squared, ndim - 1, backend)?;
let reduced_matrix = super::sum_axis(&reduced_last, ndim - 2, backend)?;
let norms = crate::unary::sqrt(&reduced_matrix, backend);
let out_shape: Vec<usize> = contiguous.shape()[..ndim - 2].to_vec();
Ok(norms.reshape(out_shape))
}
#[cfg(test)]
#[path = "norms_tests.rs"]
mod tests;