Skip to main content

sparse_ir_core/
matrix.rs

1//! Small column-major dense containers for internal numerics.
2//!
3//! [`Mat`] and [`Mat3`] come from `sparse-ir-sve`, where they hold generic
4//! scalars (including `Df64`) for the SVE, polynomial, and kernel-matrix
5//! code paths. They are plain column-major `Vec<T>` buffers with infallible
6//! indexing: the first index varies fastest in memory, matching Fortran,
7//! BLAS, and tenferro.
8//!
9//! Public APIs that expose `f64`/`Complex<f64>` matrices use
10//! [`crate::Matrix`] (`TypedTensor<T, Rank<2>>`); [`MatTyped::into_typed`]
11//! and [`MatTyped::from_typed`] move between the two without copying.
12
13use tenferro_tensor::{Rank, TensorScalar, TypedTensor};
14
15pub use sparse_ir_sve::matrix::{Mat, Mat3, mat};
16
17/// Conversions between [`Mat`] and tenferro rank-2 tensors
18pub trait MatTyped<T: TensorScalar>: Sized {
19    /// Move into a tenferro rank-2 tensor without copying.
20    fn into_typed(self) -> TypedTensor<T, Rank<2>>;
21
22    /// Copy a host-resident tenferro matrix.
23    ///
24    /// # Errors
25    /// Returns an error when the tensor is not host-resident compact
26    /// column-major storage.
27    fn from_typed(t: &TypedTensor<T, Rank<2>>) -> Result<Self, tenferro_tensor::Error>;
28}
29
30impl<T: TensorScalar> MatTyped<T> for Mat<T> {
31    fn into_typed(self) -> TypedTensor<T, Rank<2>> {
32        let dims = self.dims();
33        TypedTensor::from_vec_col_major(dims, self.into_vec())
34            .expect("Mat invariant: buffer length equals nrows * ncols")
35    }
36
37    fn from_typed(t: &TypedTensor<T, Rank<2>>) -> Result<Self, tenferro_tensor::Error> {
38        let view = t.host_col_major_view()?;
39        Ok(Mat::from_vec_col_major(
40            *view.shape(),
41            view.as_slice().to_vec(),
42        ))
43    }
44}
45
46#[cfg(test)]
47mod tests {
48    use super::*;
49
50    #[test]
51    fn typed_roundtrip_is_zero_copy_layout() {
52        let a = Mat::from_fn([2, 2], |idx| (idx[0] + 2 * idx[1]) as f64);
53        let t = a.clone().into_typed();
54        assert_eq!(t.shape(), &[2, 2]);
55        assert_eq!(*t.get2(1, 0).unwrap(), 1.0);
56        assert_eq!(Mat::from_typed(&t).unwrap(), a);
57    }
58}