use crate::backend_ops::BackendOps;
use coeus_core::{CpuAddressableStorage, CpuAddressableStorageMut, Scalar};
use coeus_tensor::Tensor;
#[inline]
pub fn roll<T: Scalar, B: BackendOps<T> + Default>(
input: &Tensor<T, B>,
shifts: &[isize],
dims: &[usize],
_backend: &B,
) -> Result<Tensor<T, B>, B::Error>
where
B::DeviceBuffer<T>: CpuAddressableStorage<T> + CpuAddressableStorageMut<T>,
{
assert_eq!(
shifts.len(),
dims.len(),
"roll: shifts and dims must have equal length"
);
let ndim = input.ndim();
let shape = input.shape();
let numel: usize = shape.iter().product();
let out_vec: Vec<T> = (0..numel)
.map(|flat| {
let mut idx = crate::shape::flat_to_nd(flat, shape);
for (&shift, &dim) in shifts.iter().zip(dims.iter()) {
assert!(
dim < ndim,
"roll: dim {dim} out of range for {ndim}-D tensor"
);
let n = shape[dim] as isize;
let eff_shift = ((shift % n) + n) % n;
let src = ((idx[dim] as isize - eff_shift + n) % n) as usize;
idx[dim] = src;
}
input.get(&idx)
})
.collect();
Tensor::from_slice(shape.to_vec(), &out_vec)
}
#[cfg(test)]
mod tests {
use super::*;
use coeus_core::SequentialBackend;
use coeus_tensor::Tensor;
#[test]
fn roll_1d_shift_1() {
let b = SequentialBackend::new();
let x = Tensor::from_slice(vec![4], &[0.0f32, 1.0, 2.0, 3.0])
.expect("invariant: test backend operation succeeds");
let out = roll(&x, &[1], &[0], &b).expect("invariant: test operation succeeds");
assert_eq!(out.as_slice(), &[3.0, 0.0, 1.0, 2.0]);
}
#[test]
fn roll_1d_negative_shift() {
let b = SequentialBackend::new();
let x = Tensor::from_slice(vec![4], &[0.0f32, 1.0, 2.0, 3.0])
.expect("invariant: test backend operation succeeds");
let out = roll(&x, &[-1], &[0], &b).expect("invariant: test operation succeeds");
assert_eq!(out.as_slice(), &[1.0, 2.0, 3.0, 0.0]);
}
#[test]
fn roll_2d_shift_row() {
let b = SequentialBackend::new();
let x = Tensor::from_slice(vec![2, 3], &[1.0f32, 2.0, 3.0, 4.0, 5.0, 6.0])
.expect("invariant: test backend operation succeeds");
let out = roll(&x, &[1], &[0], &b).expect("invariant: test operation succeeds");
assert_eq!(out.as_slice(), &[4.0, 5.0, 6.0, 1.0, 2.0, 3.0]);
}
#[test]
fn roll_shift_zero_is_identity() {
let b = SequentialBackend::new();
let x = Tensor::from_slice(vec![3], &[7.0f32, 8.0, 9.0])
.expect("invariant: test backend operation succeeds");
let out = roll(&x, &[0], &[0], &b).expect("invariant: test operation succeeds");
assert_eq!(out.as_slice(), &[7.0, 8.0, 9.0]);
}
}