1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
//! This module contains functions for predicate testing of MathML elements, as well as extracting
//! semantically-meaningful objects from MathML expressions.

use crate::ast::operator::DerivativeNotation;
use crate::ast::{
    operator::{Derivative, Operator},
    Ci, MathExpression,
    MathExpression::{Mfrac, Mn, Mo, Mover, Mrow, Msub},
    Mi, Type,
};
use crate::petri_net::{Polarity, Var};

/// Check if fraction is a derivative of a single-variable function expressed in Leibniz notation,
/// and if so, return a derivative operator and the identifier of the function.
pub fn recognize_leibniz_differential_operator<'a>(
    numerator: &MathExpression,
    denominator: &MathExpression,
) -> Result<(Operator, MathExpression), &'a str> {
    let mut numerator_contains_d = false;
    let mut denominator_contains_d = false;

    let mut numerator_contains_partial = false;
    let mut denominator_contains_partial = false;
    let mut function_candidate: Option<MathExpression> = None;

    // Check if numerator is an mrow
    if let MathExpression::Mrow(num_expressions) = numerator {
        // Check if first element of numerator is an mi
        if let MathExpression::Mi(Mi(num_id)) = &num_expressions.0[0] {
            // Check if mi contains 'd'
            if num_id == "d" {
                numerator_contains_d = true;
            }

            if num_id == "∂" {
                numerator_contains_partial = true;
            }

            // Gather the second identifier as a potential candidate function.
            function_candidate = Some(num_expressions.0[1].clone());
        }
    }

    let mut denom_var = String::new();
    if let MathExpression::Mrow(denom_expressions) = denominator {
        // Check if first element of denominator is an mi
        if let MathExpression::Mi(Mi(denom_id)) = &denom_expressions.0[0] {
            // Check if mi contains 'd'
            if denom_id == "d" {
                denominator_contains_d = true;
            }
            if denom_id == "∂" {
                denominator_contains_partial = true;
            }
        }
        if let MathExpression::Mi(Mi(with_respect_to)) = &denom_expressions.0[1] {
            denom_var.push_str(with_respect_to);
        }
    }

    if numerator_contains_d && denominator_contains_d {
        Ok((
            Operator::new_derivative(Derivative::new(
                1,
                1,
                Ci::new(
                    Some(Type::Real),
                    Box::new(MathExpression::Mi(Mi(denom_var.trim().to_string()))),
                    None,
                    None,
                ),
                DerivativeNotation::LeibnizTotal,
            )),
            function_candidate.unwrap(),
        ))
    } else if numerator_contains_partial && denominator_contains_partial {
        Ok((
            Operator::new_derivative(Derivative::new(
                1,
                1,
                Ci::new(
                    Some(Type::Real),
                    Box::new(MathExpression::Mi(Mi(denom_var.trim().to_string()))),
                    None,
                    None,
                ),
                DerivativeNotation::LeibnizPartialStandard,
            )),
            function_candidate.unwrap(),
        ))
    } else {
        Err("This Mfrac does not correspond to a derivative in Leibniz notation")
    }
}

/// Predicate testing whether a MathML operator (Mo) is a subtraction or addition.
pub fn is_add_or_subtract_operator(element: &MathExpression) -> bool {
    if let MathExpression::Mo(operator) = element {
        return Operator::Add == *operator || Operator::Subtract == *operator;
    }
    false
}

/// Get polarity from a Mo element.
pub fn get_polarity(element: &MathExpression) -> Polarity {
    if let MathExpression::Mo(op) = element {
        if *op == Operator::Subtract {
            Polarity::Negative
        } else if *op == Operator::Add {
            Polarity::Positive
        } else {
            panic!("Unhandled operator!");
        }
    } else {
        panic!("Element must be of type Mo!");
    }
}

/// Get variable corresponding to specie.
pub fn get_specie_var(expression: &MathExpression) -> Var {
    // Check if expression is an mfrac
    match expression {
        Mfrac(numerator, denominator) => {
            if recognize_leibniz_differential_operator(numerator, denominator).is_ok() {
                mfrac_leibniz_to_specie(numerator, denominator)
            } else {
                panic!("Expression is an mfrac but not a Leibniz differential operator!");
            }
        }
        // Translate MathML :mover as Newton dot notation
        Mover(base, overscript) => {
            // Check if overscript is ˙
            if let Mo(id) = &**overscript {
                if *id == Operator::Other("˙".to_string()) {
                    Var(*base.clone())
                } else {
                    panic!("Overscript is not ˙, unhandled case!")
                }
            } else {
                panic!("Found an overscript that is not an Mo, aborting!");
            }
        }
        _ => panic!("Unhandled case!"),
    }
}

/// Predicate testing whether a MathML elm could be interpreted as a Var.
/// TODO: This currently permits Mn -> MathML numerical literals.
///     Perhaps useful to represent constant coefficients?
///     But should those be Vars?
pub fn is_var_candidate(element: &MathExpression) -> bool {
    matches!(element, MathExpression::Mi(_) | Mn(_) | Msub(_, _))
}

/// Translate a MathML mfrac (fraction) as an expression of a Leibniz differential operator.
/// In this case, the values after the 'd' or '∂' in the numerator are interpreted as
/// the Var tangent.
/// TODO: possibly generalize to accommodate superscripts for higher order derivatives;
///       although likely that would be an msup, so still the "first" elm of the numerator,
///       with the second (and beyond) elm(s) being the Var.
fn mfrac_leibniz_to_specie(numerator: &MathExpression, _denominator: &MathExpression) -> Var {
    // Check if numerator is an mrow
    if let Mrow(num_expressions) = numerator {
        // We assume here that the numerator is of the form dX where X is the variable of interest.
        if num_expressions.0.len() == 2 {
            let expression = &num_expressions.0[1];
            Var(expression.clone())
        } else {
            panic!(
                "More than two elements in the numerator, cannot extract specie from Leibniz differential operator!");
        }
    } else {
        panic!("Unable to extract specie from Leibniz differential operator!");
    }
}