opensrdk_symbolic_computation/expression/matrix_expression/
mod.rs

1pub mod assign;
2pub mod differential;
3pub mod operations;
4pub mod size;
5pub mod tex_code;
6pub mod variable;
7
8pub use assign::*;
9pub use differential::*;
10pub use operations::*;
11use serde::{Deserialize, Serialize};
12pub use size::*;
13pub use tex_code::*;
14pub use variable::*;
15
16use crate::Expression;
17
18#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
19pub enum MatrixExpression {
20    T(Box<Expression>),
21    Inv(Box<Expression>),
22    Det(Box<Expression>),
23}
24
25impl Expression {
26    pub fn matrix(self) -> Option<MatrixExpression> {
27        match self {
28            Expression::Matrix(t) => Some(*t),
29            _ => None,
30        }
31    }
32
33    pub fn into_matrix(self) -> MatrixExpression {
34        match self {
35            Expression::Matrix(t) => *t,
36            _ => panic!("The expression is not a matrix expression."),
37        }
38    }
39}
40
41// impl TensorExpression {
42//     pub fn to_mat(self) -> MatrixExpression {
43//         let sizes = self.sizes();
44//         if sizes.len() != 2 {
45//             panic!("The rank of the argument must be 2.");
46//         }
47
48//         if let TensorExpression::Constant(v) = self {
49//             return MatrixExpression::Constant(v.to_mat()).into();
50//         }
51
52//         MatrixExpression::Mat(self.into())
53//     }
54// }
55
56impl From<MatrixExpression> for Expression {
57    fn from(m: MatrixExpression) -> Self {
58        Expression::Matrix(m.into())
59    }
60}
61
62#[cfg(test)]
63mod tests {
64    use std::{collections::HashMap, ops::Add};
65
66    use opensrdk_linear_algebra::Matrix;
67
68    use crate::{Expression, MatrixExpression};
69
70    #[test]
71    fn it_works() {
72        let len = 3usize;
73        let a = Matrix::from(len, vec![1.0, 3.0, 4.0, 0.0, 1.0, 0.0, 0.0, 0.0, 3.0]).unwrap();
74        let ea = Expression::from(a.clone());
75
76        let a_t = a.clone().t();
77        let ea_t = ea.clone().t();
78
79        assert_eq!(Expression::from(a_t), ea_t);
80
81        let a_inv = a.clone().getrf().unwrap().getri().unwrap();
82        let ea_inv = ea.clone().inv();
83
84        assert_eq!(Expression::from(a_inv), ea_inv);
85
86        let a_det = a.clone().getrf().unwrap().0.trdet();
87        let ea_det = ea.clone().det();
88
89        println!("{:?}", ea_det);
90        assert_eq!(Expression::from(a_det), ea_det);
91    }
92}