Python example: mrpt_expr_example.py

Compiles and evaluates math formulas with variables at runtime with mrpt.expr.

Modules: mrpt.expr

 1#!/usr/bin/env python3
 2"""
 3Compiles and evaluates math formulas with variables at runtime with mrpt.expr.
 4"""
 5
 6import mrpt.expr
 7
 8
 9def main():
10    # 1. Basic Expression Evaluation
11    # ---------------------------------------------------------
12    expr = mrpt.expr.CRuntimeCompiledExpression()
13
14    # We can pass variables as a dictionary
15    variables = {"x": 10.0, "y": 5.5}
16
17    formula = "x * sin(PI / 2) + y^2"
18    print(f"Compiling: {formula}")
19
20    expr.compile(formula, variables)
21
22    if expr.is_compiled():
23        result = expr.eval()
24        print(f"Result: {result}")  # Expected: 10 * 1 + 5.5^2 = 40.25
25
26    # 2. Using Custom Python Functions in the Formula
27    # ---------------------------------------------------------
28    print("\nRegistering custom Python function...")
29
30    # Define a custom Python function
31    def my_custom_logic(a, b):
32        # This could be any complex Python logic
33        return (a + b) / 2.0
34
35    expr_custom = mrpt.expr.CRuntimeCompiledExpression()
36
37    # Register it! Now the parser knows 'avg(a,b)'
38    expr_custom.register_function("avg", my_custom_logic)
39
40    expr_custom.compile("avg(10, 20) + 5")
41    print(f"Custom result: {expr_custom.eval()}")  # Expected: 15 + 5 = 20.0
42
43    # 3. Dynamic Updates
44    # ---------------------------------------------------------
45    # Note: To update variable values in this specific C++ API,
46    # you re-compile the expression with the new values.
47    # Because compilation is extremely fast (μs), this is standard.
48    new_vars = {"x": 20.0, "y": 2.0}
49    expr.compile(formula, new_vars)
50    print(f"Updated result: {expr.eval()}")
51
52
53if __name__ == "__main__":
54    main()