use crate::backend_ops::BackendOps;
use coeus_core::{BackendError, CpuAddressableStorage, CpuAddressableStorageMut, Scalar};
use coeus_tensor::Tensor;
#[inline]
pub fn nonzero<T: Scalar, B: BackendOps<T> + Default>(
input: &Tensor<T, B>,
backend: &B,
) -> Result<Tensor<T, B>, B::Error>
where
B::DeviceBuffer<T>: CpuAddressableStorage<T> + CpuAddressableStorageMut<T>,
{
let shape = input.shape();
let ndim = input.ndim();
let mut out_vec = Vec::new();
let mut count = 0usize;
for flat in 0..input.numel() {
let idx = crate::shape::flat_to_nd(flat, shape);
if input.get(&idx) != T::ZERO {
count += 1;
for coord in idx {
let value = T::try_from_count(coord).map_err(|error| BackendError::Storage {
operation: "nonzero",
reason: error.to_string(),
})?;
out_vec.push(value);
}
}
}
Tensor::from_slice_on(vec![count, ndim], &out_vec, backend)
}
#[cfg(test)]
mod tests {
use super::*;
use coeus_core::SequentialBackend;
use coeus_tensor::Tensor;
#[test]
fn nonzero_1d_returns_positions() {
let b = SequentialBackend::new();
let input = Tensor::from_slice(vec![4], &[0.0f64, 2.0, 0.0, 3.0])
.expect("invariant: test backend operation succeeds");
let out =
nonzero(&input, &b).expect("invariant: float elements represent every coordinate");
assert_eq!(out.shape(), &[2, 1]);
assert_eq!(out.as_slice(), &[1.0, 3.0]);
}
#[test]
fn nonzero_2d_returns_row_major_indices() {
let b = SequentialBackend::new();
let input = Tensor::from_slice(vec![2, 3], &[0.0f64, 5.0, 0.0, 6.0, 7.0, 0.0])
.expect("invariant: test backend operation succeeds");
let out =
nonzero(&input, &b).expect("invariant: float elements represent every coordinate");
assert_eq!(out.shape(), &[3, 2]);
assert_eq!(out.as_slice(), &[0.0, 1.0, 1.0, 0.0, 1.0, 1.0]);
}
#[test]
fn nonzero_all_zero_returns_empty_rows() {
let b = SequentialBackend::new();
let input = Tensor::<f64, SequentialBackend>::zeros(vec![2, 2])
.expect("invariant: test backend operation succeeds");
let out =
nonzero(&input, &b).expect("invariant: float elements represent every coordinate");
assert_eq!(out.shape(), &[0, 2]);
assert!(out.as_slice().is_empty());
}
#[test]
fn nonzero_integer_element_rejects_a_coordinate_outside_its_range() {
let b = SequentialBackend::new();
let mut values = vec![0i8; 129];
values[128] = 1;
let input = Tensor::from_slice(vec![129], &values)
.expect("invariant: test backend operation succeeds");
let Err(err) = nonzero(&input, &b) else {
panic!("coordinate 128 does not fit i8");
};
assert!(
matches!(
err,
coeus_core::BackendError::Storage { operation, .. } if operation == "nonzero"
),
"unexpected error: {err:?}"
);
}
#[test]
fn nonzero_single_element_tensor() {
let b = SequentialBackend::new();
let input = Tensor::from_slice(vec![1], &[4.0f64])
.expect("invariant: test backend operation succeeds");
let out =
nonzero(&input, &b).expect("invariant: float elements represent every coordinate");
assert_eq!(out.shape(), &[1, 1]);
assert_eq!(out.as_slice(), &[0.0]);
}
}