opensrdk_symbolic_computation/expression/
tex_code.rs

1use crate::Expression;
2use std::collections::HashMap;
3
4#[derive(Clone, Copy, Debug, PartialEq, Eq)]
5pub enum BracketsLevel {
6    None,
7    ForMul,
8    ForDiv,
9    ForOperation,
10}
11
12impl Expression {
13    pub(crate) fn _tex_code(
14        &self,
15        variables: &HashMap<&str, &str>,
16        brackets_level: BracketsLevel,
17    ) -> String {
18        match self {
19            Expression::Variable(id, _) => format!("{{{}}}", variables[id.as_str()]),
20            Expression::Constant(_) => r"\text{const.}".to_owned(),
21            Expression::PartialVariable(_) => r"\text{abbreviated.}".to_owned(),
22            Expression::Add(l, r) => Expression::tex_code_add(l, r, variables, brackets_level),
23            Expression::Sub(l, r) => Expression::tex_code_sub(l, r, variables, brackets_level),
24            Expression::Mul(l, r) => Expression::tex_code_mul(l, r, variables, brackets_level),
25            Expression::Div(l, r) => Expression::tex_code_div(l, r, variables, brackets_level),
26            Expression::Neg(v) => Expression::tex_code_neg(v, variables),
27            Expression::Transcendental(v) => v._tex_code(variables, brackets_level),
28            Expression::Tensor(v) => v._tex_code(variables, brackets_level),
29            Expression::Matrix(v) => v._tex_code(variables, brackets_level),
30        }
31    }
32
33    pub fn tex_code(&self, symbols: &HashMap<&str, &str>) -> String {
34        self._tex_code(symbols, BracketsLevel::None)
35    }
36}
37
38#[cfg(test)]
39mod tests {
40    use std::collections::{HashMap, HashSet};
41
42    use opensrdk_linear_algebra::sparse::SparseTensor;
43
44    use crate::{new_variable, Expression};
45
46    #[test]
47    fn it_works1() {
48        let a = 5.0f64;
49        let b = vec![a; 8];
50
51        let ea = Expression::from(a);
52        let eb = Expression::from(b);
53
54        let tex_symbols = vec![].into_iter().collect();
55
56        let tex_a = ea.tex_code(&tex_symbols);
57        let tex_b = eb.tex_code(&tex_symbols);
58
59        assert_eq!("\\text{const.}", tex_a);
60        assert_eq!("\\text{const.}", tex_b);
61    }
62
63    #[test]
64    fn it_works2() {
65        let id = "x";
66        let a = HashSet::from([id; 1]);
67        let ea = new_variable((id).to_string());
68
69        let tex_symbols = vec![("x", "y")].into_iter().collect();
70
71        let tex_a = ea.tex_code(&tex_symbols);
72
73        assert_eq!("{y}", tex_a);
74    }
75}