Skip to main content

bixverse_core/utils/
macros.rs

1//! Collection of generic assertion macros for the crate
2
3///////////////////
4// Matrix macros //
5///////////////////
6
7/// Assertion that a matrix is symmetric.
8#[macro_export]
9macro_rules! assert_symmetric_mat {
10    ($matrix:expr) => {{
11        let nrows = $matrix.nrows();
12        let ncols = $matrix.ncols();
13        assert_eq!(
14            nrows, ncols,
15            "Matrix is not square: {} rows != {} cols",
16            nrows, ncols
17        );
18        let check_size = nrows.min(10);
19        for i in 0..check_size {
20            for j in (i + 1)..check_size {
21                let val_ij = *$matrix.get(i, j);
22                let val_ji = *$matrix.get(j, i);
23                assert!(
24                    (val_ij - val_ji).abs() < T::from_f64(1e-10).unwrap(),
25                    "Matrix not symmetric at ({}, {}): {} != {}",
26                    i,
27                    j,
28                    val_ij,
29                    val_ji
30                );
31            }
32        }
33    }};
34}
35
36/// Assertion that two matrices have the same number of rows.
37#[macro_export]
38macro_rules! assert_nrows {
39    ($matrix1:expr, $matrix2:expr) => {
40        assert_eq!(
41            $matrix1.nrows(),
42            $matrix2.nrows(),
43            "Matrices have different number of rows: {} != {}",
44            $matrix1.nrows(),
45            $matrix2.nrows()
46        );
47    };
48}
49
50/// Assertion that two matrices have the same dimensions (rows and columns).
51#[macro_export]
52macro_rules! assert_same_dims {
53    ($matrix1:expr, $matrix2:expr) => {
54        assert_eq!(
55            ($matrix1.nrows(), $matrix1.ncols()),
56            ($matrix2.nrows(), $matrix2.ncols()),
57            "Matrices have different dimensions: {}x{} != {}x{}",
58            $matrix1.nrows(),
59            $matrix1.ncols(),
60            $matrix2.nrows(),
61            $matrix2.ncols()
62        );
63    };
64}
65
66///////////////////
67// Vector macros //
68///////////////////
69
70/// Assertion that all vectors have the same length.
71#[macro_export]
72macro_rules! assert_same_len {
73    ($($vec:expr),+ $(,)?) => {
74        {
75            let lengths: Vec<usize> = vec![$($vec.len()),+];
76            let first_len = lengths[0];
77
78            if !lengths.iter().all(|&len| len == first_len) {
79                panic!(
80                    "Vectors have different lengths: {:?}",
81                    lengths
82                );
83            }
84        }
85    };
86}