sprs/sparse/
symmetric.rs

1/// Functions dealing with symmetric sparse matrices
2use std::ops::Deref;
3
4use crate::indexing::SpIndex;
5use crate::sparse::prelude::*;
6
7pub fn is_symmetric<N, I, Iptr, IpStorage, IStorage, DStorage>(
8    mat: &CsMatBase<N, I, IpStorage, IStorage, DStorage, Iptr>,
9) -> bool
10where
11    N: PartialEq,
12    I: SpIndex,
13    Iptr: SpIndex,
14    IpStorage: Deref<Target = [Iptr]>,
15    IStorage: Deref<Target = [I]>,
16    DStorage: Deref<Target = [N]>,
17{
18    if mat.rows() != mat.cols() {
19        return false;
20    }
21    for (outer_ind, vec) in mat.outer_iterator().enumerate() {
22        for (inner_ind, value) in vec.iter() {
23            match mat.get_outer_inner(inner_ind, outer_ind) {
24                None => return false,
25                Some(transposed_val) => {
26                    if transposed_val != value {
27                        return false;
28                    }
29                }
30            }
31        }
32    }
33    true
34}
35
36#[cfg(test)]
37mod test {
38    use super::is_symmetric;
39    use crate::sparse::CsMatView;
40
41    #[test]
42    fn is_symmetric_simple() {
43        let indptr: &[usize] = &[0, 2, 5, 6, 7, 13, 14, 17, 20, 24, 28];
44        let indices: &[usize] = &[
45            0, 8, 1, 4, 9, 2, 3, 1, 4, 6, 7, 8, 9, 5, 4, 6, 9, 4, 7, 8, 0, 4,
46            7, 8, 1, 4, 6, 9,
47        ];
48        let data: &[f64] = &[
49            1.7, 0.13, 1., 0.02, 0.01, 1.5, 1.1, 0.02, 2.6, 0.16, 0.09, 0.52,
50            0.53, 1.2, 0.16, 1.3, 0.56, 0.09, 1.6, 0.11, 0.13, 0.52, 0.11, 1.4,
51            0.01, 0.53, 0.56, 3.1,
52        ];
53
54        let a = CsMatView::new((10, 10), indptr, indices, data);
55
56        assert!(is_symmetric(&a));
57    }
58
59    // TODO: symmetry test on A^T*A products
60}