use super::{CsrMatrix, CsrView};
use crate::domain::scalar::Scalar;
use leto::{Array1, ArrayView1, LetoError, Result, Storage};
pub fn spmv_view_into<T: Scalar>(a: &CsrView<T>, x: &ArrayView1<'_, T>, y: &mut [T]) -> Result<()> {
let (nrows, ncols) = a.shape();
if x.shape() != [ncols] {
return Err(LetoError::ShapeMismatch {
lhs: x.shape().to_vec(),
rhs: vec![ncols],
});
}
if y.len() != nrows {
return Err(LetoError::ShapeMismatch {
lhs: vec![y.len()],
rhs: vec![nrows],
});
}
if let Some(xs) = x.as_slice() {
return spmv_slice_into(a, xs, y);
}
let x_contiguous = x.to_contiguous();
spmv_slice_into(a, x_contiguous.storage().as_slice(), y)
}
pub fn spmv_into<T: Scalar>(a: &CsrMatrix<T>, x: &ArrayView1<'_, T>, y: &mut [T]) -> Result<()> {
spmv_view_into(&a.as_view(), x, y)
}
fn spmv_slice_into<T: Scalar>(a: &CsrView<T>, xs: &[T], y: &mut [T]) -> Result<()> {
let (values, col_indices, row_ptr) = a.as_parts();
for (slot, window) in y.iter_mut().zip(row_ptr.windows(2)) {
let (start, end) = (window[0], window[1]);
let cols = &col_indices[start..end];
let vals = &values[start..end];
let mut acc = T::ZERO;
for (&value, &col) in vals.iter().zip(cols) {
acc = acc.add(value.mul(xs[col]));
}
*slot = acc;
}
Ok(())
}
pub fn spmv<T: Scalar>(a: &CsrMatrix<T>, x: &ArrayView1<'_, T>) -> Result<Array1<T>> {
let (nrows, _) = a.shape();
let mut y = vec![T::ZERO; nrows];
spmv_into(a, x, &mut y)?;
Array1::from_shape_vec([nrows], y)
}