Expand description
Expression tree representation and symbolic differentiation Expression module for representing mathematical expressions.
This module defines the core expression types used to represent mathematical expressions in a form that supports both JIT compilation and automatic differentiation. The main types are:
Expr: An enum representing different kinds of mathematical expressionsVarRef: A struct containing metadata about variables in expressions
The expression tree is built recursively using Box<Expr> for nested expressions and can be:
- JIT compiled into machine code using Cranelift
- Symbolically differentiated to compute derivatives
- Evaluated efficiently at runtime
- Simplified using algebraic rules
- Modified by inserting replacement expressions
Supported operations include:
- Basic arithmetic (+, -, *, /)
- Variables and constants
- Absolute value
- Integer exponentiation
- Transcendental functions (exp, ln, sqrt)
- Expression caching for optimization
§Expression Tree Structure
The expression tree is built recursively with each node being one of:
- Leaf nodes: Constants and Variables
- Unary operations: Abs, Neg, Exp, Ln, Sqrt
- Binary operations: Add, Sub, Mul, Div
- Special nodes: Pow (with integer exponent), Cached expressions
§Symbolic Differentiation
The derivative method implements symbolic differentiation by recursively applying calculus rules like:
- Product rule
- Quotient rule
- Chain rule
- Power rule
- Special function derivatives (exp, ln, sqrt)
§Expression Simplification
The simplify method performs algebraic simplifications including:
- Constant folding (e.g. 2 + 3 → 5)
- Identity rules (e.g. x + 0 → x, x * 1 → x)
- Exponent rules (e.g. x^0 → 1, x^1 → x)
- Expression caching for repeated subexpressions
- Special function simplifications
§Expression Modification
The insert method allows replacing parts of an expression tree by:
- Matching nodes using a predicate function
- Replacing matched nodes with a new expression
- Recursively traversing and rebuilding the tree
Structs§
- Flattened
Expr - Flattened expression representation for efficient evaluation
- VarRef
- Represents a reference to a variable in an expression.