use xingo_sparse::{DenseBlock, Real};
use crate::StatlaError;
#[derive(Clone, Copy, Debug)]
pub struct MatRef<'a, T: Real = f64> {
rows: usize,
cols: usize,
ld: usize,
data: &'a [T],
}
#[derive(Debug)]
pub struct MatMut<'a, T: Real = f64> {
rows: usize,
cols: usize,
ld: usize,
data: &'a mut [T],
}
fn extent(rows: usize, cols: usize, ld: usize, len: usize) -> Result<usize, StatlaError> {
if ld < rows {
return Err(StatlaError::InvalidArgument { what: "ld < rows" });
}
let need = if cols == 0 {
0
} else {
ld.checked_mul(cols - 1)
.and_then(|v| v.checked_add(rows))
.ok_or(StatlaError::InvalidArgument {
what: "view extent overflows usize",
})?
};
if len < need {
return Err(StatlaError::Dimension {
what: "data",
expected: need,
found: len,
});
}
Ok(need)
}
impl<'a, T: Real> MatRef<'a, T> {
pub fn new(rows: usize, cols: usize, ld: usize, data: &'a [T]) -> Result<Self, StatlaError> {
extent(rows, cols, ld, data.len())?;
Ok(Self {
rows,
cols,
ld,
data,
})
}
#[must_use]
pub fn from_block(b: &'a DenseBlock<T>) -> Self {
let cols = if b.data.len() >= b.rows.saturating_mul(b.cols) {
b.cols
} else {
0
};
Self {
rows: b.rows,
cols,
ld: b.rows,
data: &b.data,
}
}
#[must_use]
pub fn rows(&self) -> usize {
self.rows
}
#[must_use]
pub fn cols(&self) -> usize {
self.cols
}
#[must_use]
pub fn ld(&self) -> usize {
self.ld
}
#[must_use]
pub fn get(&self, i: usize, j: usize) -> Option<T> {
if i < self.rows && j < self.cols {
Some(self.data[i + j * self.ld])
} else {
None
}
}
#[must_use]
pub fn col(&self, j: usize) -> Option<&'a [T]> {
if j < self.cols {
let s = j * self.ld;
Some(&self.data[s..s + self.rows])
} else {
None
}
}
pub fn cols_range(&self, j0: usize, j1: usize) -> Result<Self, StatlaError> {
if j0 > j1 || j1 > self.cols {
return Err(StatlaError::InvalidArgument {
what: "column range outside the view",
});
}
let start = (j0 * self.ld).min(self.data.len());
Ok(Self {
rows: self.rows,
cols: j1 - j0,
ld: self.ld,
data: &self.data[start..],
})
}
pub(crate) fn raw(&self) -> &'a [T] {
self.data
}
#[must_use]
pub fn to_block(&self) -> DenseBlock<T> {
let mut b = DenseBlock::zeros(self.rows, self.cols);
for j in 0..self.cols {
let s = j * self.ld;
b.data[j * self.rows..(j + 1) * self.rows]
.copy_from_slice(&self.data[s..s + self.rows]);
}
b
}
}
impl<'a, T: Real> MatMut<'a, T> {
pub fn new(
rows: usize,
cols: usize,
ld: usize,
data: &'a mut [T],
) -> Result<Self, StatlaError> {
extent(rows, cols, ld, data.len())?;
Ok(Self {
rows,
cols,
ld,
data,
})
}
pub fn from_block(b: &'a mut DenseBlock<T>) -> Self {
let cols = if b.data.len() >= b.rows.saturating_mul(b.cols) {
b.cols
} else {
0
};
Self {
rows: b.rows,
cols,
ld: b.rows,
data: &mut b.data,
}
}
#[must_use]
pub fn as_ref(&self) -> MatRef<'_, T> {
MatRef {
rows: self.rows,
cols: self.cols,
ld: self.ld,
data: self.data,
}
}
#[must_use]
pub(crate) fn rows(&self) -> usize {
self.rows
}
#[must_use]
pub(crate) fn cols(&self) -> usize {
self.cols
}
pub fn col_mut(&mut self, j: usize) -> Option<&mut [T]> {
if j < self.cols {
let s = j * self.ld;
Some(&mut self.data[s..s + self.rows])
} else {
None
}
}
}
#[cfg(test)]
#[allow(clippy::float_cmp)] mod tests {
use super::*;
#[test]
fn views_index_with_the_leading_dimension() {
let data = [1.0, 2.0, 99.0, 3.0, 4.0, 99.0, 5.0, 6.0];
let a = MatRef::new(2, 3, 3, &data).unwrap();
assert_eq!((a.rows(), a.cols(), a.ld()), (2, 3, 3));
assert_eq!(a.get(1, 2), Some(6.0));
assert_eq!(a.get(2, 0), None);
assert_eq!(a.get(0, 3), None);
assert_eq!(a.col(1), Some(&[3.0, 4.0][..]));
assert_eq!(a.col(3), None);
let b = a.to_block();
assert_eq!(b.data, vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0]);
let c = a.cols_range(1, 3).unwrap();
assert_eq!(
(c.cols(), c.get(0, 0), c.get(1, 1)),
(2, Some(3.0), Some(6.0))
);
let e = a.cols_range(3, 3).unwrap();
assert_eq!((e.cols(), e.col(0)), (0, None));
assert!(a.cols_range(2, 1).is_err() && a.cols_range(0, 4).is_err());
assert_eq!(MatRef::from_block(&b).get(1, 2), Some(6.0));
}
#[test]
fn construction_is_checked() {
let data = [0.0; 5];
assert_eq!(
MatRef::new(3, 2, 2, &data).unwrap_err(),
StatlaError::InvalidArgument { what: "ld < rows" }
);
assert_eq!(
MatRef::new(3, 2, 3, &data).unwrap_err(),
StatlaError::Dimension {
what: "data",
expected: 6,
found: 5
}
);
assert!(MatRef::new(usize::MAX, 3, usize::MAX, &data).is_err());
assert!(MatRef::<f64>::new(0, 0, 0, &[]).is_ok());
assert!(MatRef::<f64>::new(4, 0, 4, &[]).is_ok());
let inconsistent = DenseBlock {
rows: 2,
cols: 2,
data: vec![1.0],
};
assert_eq!(MatRef::from_block(&inconsistent).cols(), 0);
}
#[test]
fn mutable_views_write_through() {
let mut data = vec![0.0; 8];
{
let mut m = MatMut::new(2, 3, 3, &mut data).unwrap();
m.col_mut(2).unwrap()[1] = 8.0;
assert!(m.col_mut(3).is_none());
assert_eq!(m.as_ref().get(1, 2), Some(8.0));
}
assert_eq!(data[7], 8.0);
let mut b = DenseBlock::<f64>::zeros(2, 2);
MatMut::from_block(&mut b).col_mut(1).unwrap()[0] = 3.0;
assert_eq!(b.get(0, 1), 3.0);
assert!(MatMut::new(3, 1, 2, &mut data).is_err());
}
}