#![cfg_attr(test, allow(clippy::unwrap_used, reason = "test scope"))]
use super::{CscMatrix, CscView};
use crate::domain::scalar::Scalar;
use leto::{Array1, ArrayView1, LetoError, Result};
pub fn csc_spmv_view_into<T: Scalar>(
a: &CscView<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],
});
}
y.fill(T::ZERO);
let (values, row_indices, col_ptr) = a.as_parts();
if let Some(xs) = x.as_slice() {
for (&xj, window) in xs.iter().zip(col_ptr.windows(2)) {
if xj == T::ZERO {
continue;
}
let rows = &row_indices[window[0]..window[1]];
let vals = &values[window[0]..window[1]];
for (&i, &value) in rows.iter().zip(vals) {
y[i] = y[i].add(value.mul(xj));
}
}
} else {
for (j, window) in col_ptr.windows(2).enumerate() {
let xj = *x.get([j])?;
if xj == T::ZERO {
continue;
}
let rows = &row_indices[window[0]..window[1]];
let vals = &values[window[0]..window[1]];
for (&i, &value) in rows.iter().zip(vals) {
y[i] = y[i].add(value.mul(xj));
}
}
}
Ok(())
}
pub fn csc_spmv_into<T: Scalar>(
a: &CscMatrix<T>,
x: &ArrayView1<'_, T>,
y: &mut [T],
) -> Result<()> {
csc_spmv_view_into(&a.as_view(), x, y)
}
pub fn csc_spmv<T: Scalar>(a: &CscMatrix<T>, x: &ArrayView1<'_, T>) -> Result<Array1<T>> {
let (nrows, _) = a.shape();
let mut y = vec![T::ZERO; nrows];
csc_spmv_into(a, x, &mut y)?;
Array1::from_shape_vec([nrows], y)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn csc_spmv_basic() {
let a = CscMatrix::from_dense(
&leto::Array2::from_shape_vec([3, 2], vec![1.0, 0.0, 0.0, 2.0, 3.0, 0.0])
.unwrap()
.view(),
);
let x = leto::Array1::from_shape_vec([2], vec![2.0, 5.0]).unwrap();
let y = csc_spmv(&a, &x.view()).unwrap();
assert_eq!(
y,
leto::Array1::from_shape_vec([3], vec![2.0, 10.0, 6.0]).unwrap()
);
}
#[test]
fn csc_spmv_identity() {
let a = CscMatrix::from_dense(
&leto::Array2::from_shape_vec([2, 2], vec![1.0, 0.0, 0.0, 1.0])
.unwrap()
.view(),
);
let x = leto::Array1::from_shape_vec([2], vec![3.0, 7.0]).unwrap();
let y = csc_spmv(&a, &x.view()).unwrap();
assert_eq!(
y,
leto::Array1::from_shape_vec([2], vec![3.0, 7.0]).unwrap()
);
}
#[test]
fn csc_spmv_shape_mismatch() {
let a = CscMatrix::<f64>::zeros(3, 2);
let x = leto::Array1::from_shape_vec([3], vec![1.0, 2.0, 3.0]).unwrap();
assert!(csc_spmv(&a, &x.view()).is_err());
}
}