use crate::backend_ops::BackendOps;
use coeus_core::{BackendError, Scalar};
use coeus_tensor::Tensor;
#[inline]
pub fn mean<T: Scalar + coeus_core::FloatElement, B: BackendOps<T> + Default>(
a: &Tensor<T, B>,
backend: &B,
) -> Result<T, B::Error> {
if a.numel() == 0 {
return Ok(T::zero() / <T as coeus_core::FloatElement>::from_f64(0.0));
}
let reshaped = if a.is_contiguous() && a.layout().offset() == 0 {
a.reshape([a.numel()])
} else {
let contiguous = a.to_contiguous_on(backend);
contiguous.reshape([a.numel()])
};
let reduced = mean_axis(&reshaped, 0, backend)?;
let mut host_scalar = [T::zero()];
backend.copy_to_host(reduced.storage(), &mut host_scalar);
Ok(host_scalar[0])
}
#[inline]
pub fn mean_axis<T: Scalar + coeus_core::FloatElement, B: BackendOps<T> + Default>(
a: &Tensor<T, B>,
axis: usize,
backend: &B,
) -> Result<Tensor<T, B>, B::Error> {
if axis >= a.ndim() {
return Err(B::Error::from(BackendError::AxisOutOfRange {
operation: "mean_axis",
axis,
rank: a.ndim(),
}));
}
let mut out_shape = a.shape_cloned();
out_shape[axis] = 1;
let mut out = Tensor::alloc_on(out_shape, backend);
let (out_storage, out_layout) = out.storage_mut_and_layout();
backend.reduce_mean(a.storage(), a.layout(), axis, out_storage, out_layout)?;
Ok(out)
}