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 + leto_ops::Scalar, 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 {
let crossover = backend.host_staging_crossover();
if crossover > 0 && n < crossover {
return super::staging::staged_scalar(a, backend, norm);
}
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,
) -> Result<Tensor<T, B>, B::Error> {
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)?;
crate::pow_scalar(&summed, T::ONE / p, backend)
}
#[inline]
pub fn norm_p<
T: Float + leto_ops::Scalar + leto_ops::RealScalar,
B: ElementwiseOps<T> + ReductionOps<T> + ScalarPowerOps<T> + Default,
>(
a: &Tensor<T, B>,
p: T,
backend: &B,
) -> Result<T, B::Error> {
if a.is_contiguous() && a.layout().offset() == 0 {
let crossover = backend.host_staging_crossover();
if crossover > 0 && a.numel() < crossover {
return super::staging::staged_scalar(a, backend, |host, seq| norm_p(host, p, seq));
}
}
let result = norm_p_tensor(a, p, backend)?;
let mut scalar = [T::ZERO];
backend.copy_to_host(result.storage(), &mut scalar)?;
Ok(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,
) -> Result<Tensor<T, B>, B::Error> {
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)?;
crate::pow_scalar(&summed, T::ONE / p, backend)
}
#[inline]
pub fn frobenius_norm<T: Float + leto_ops::Scalar, 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 + leto_ops::Scalar, 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 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;