ExpressionNormalizer
The core class that provides mathematical expression normalization and equivalence checking with LaTeX support.Constructor
Initializes the normalizer with SymPy transformations and a local dictionary of mathematical functions. Transformations:- Standard SymPy transformations
- Implicit multiplication application (e.g.,
2x→2*x) - XOR conversion
- Mathematical functions:
log,ln,exp,sqrt,sin,cos,tan,asin,acos,atan,sinh,cosh,tanh - Constants:
e,pi - Calculus:
Integral,Derivative - Special functions:
Piecewise,Heaviside,floor,ceiling,Max,Min - Relational operators:
Eq,Ne,Lt,Gt,Le,Ge
app/utils/math_engine.py:83-131
normalize_expression()
Converts an expression to canonical form for comparison.expression_str(str): The mathematical expression to normalize
str: Stable canonical string representation
- Parse to SymPy expression
- Apply canonicalization
- Convert to stable string
app/utils/math_engine.py:136-146
expressions_equivalent()
Checks if two expressions are mathematically equivalent.expr1(str): First mathematical expressionexpr2(str): Second mathematical expression
bool: True if expressions are mathematically equivalent
- Parse both expressions to SymPy
- Convert to difference form
- Check if difference is symbolically zero
- Fall back to numeric probing if symbolic methods inconclusive
- Final fallback to structural comparison
app/utils/math_engine.py:148-174
get_canonical_form()
Generates canonical form for database storage.expression_str(str): Expression to canonicalize
str: Canonical string representation for consistent storage
app/utils/math_engine.py:176-186
Public Functions
Convenience functions that use the globalmath_normalizer instance.
compare_mathematical_expressions()
Compares two mathematical expressions for equivalence.user_answer(str): User’s submitted answercorrect_answer(str): Expected correct answer
bool: True if expressions are equivalent
app/utils/math_engine.py:541-545
normalize_expression_for_storage()
Normalizes an expression for consistent database storage.expression(str): Expression to normalize
str: Canonical form suitable for database storage
app/utils/math_engine.py:548-552
latex_to_sympy_string()
Converts LaTeX expression to SymPy string representation.latex_expr(str): LaTeX formatted expression
str: SymPy string representation
- Prefers
latex2sympy2library when available - Falls back to SymPy’s parser for non-LaTeX or parsing failures
app/utils/math_engine.py:555-582
latex_to_simplified_latex()
Simplifies a LaTeX expression and returns simplified LaTeX.latex_expr(str): LaTeX formatted expression
str: Simplified LaTeX expression
- Try
latex2latexfor quick simplification (when available) - Fall back to parse → SymPy canonicalize → LaTeX printer
- Return original if all methods fail
app/utils/math_engine.py:585-612
LaTeX Support
The math engine provides comprehensive LaTeX support through thelatex2sympy2 library with intelligent fallbacks.
Supported LaTeX Features
Fractions:LaTeX Detection
The engine automatically detects LaTeX input based on:- Math mode markers:
$,\(,\),\[,\] - LaTeX commands:
\frac,\sqrt,\sin,\cos, etc. - LaTeX operators:
\cdot,\times,\div - Superscripts/subscripts:
^{,_{
app/utils/math_engine.py:50-68
Expression Normalization Strategies
The canonicalization pipeline applies multiple SymPy simplifications in sequence:Canonicalization Pipeline
- Basic Simplification:
sp.simplify(expr) - Rational Functions:
sp.together()andsp.cancel() - Logarithm Expansion:
sp.expand_log()andsp.logcombine() - Power Simplification:
sp.powsimp()andsp.powdenest() - Multiplication Expansion:
sp.expand_mul() - Term Factoring:
sp.factor_terms() - Final Simplification:
sp.simplify() - Term Ordering: Lexicographic sorting of terms
app/utils/math_engine.py:325-368
Equivalence Checking Methods
Symbolic Zero Detection:- Canonicalize and check if difference equals 0
- Apply
sp.simplify(),sp.together(),sp.cancel()
app/utils/math_engine.py:415-433
Numeric Probing:
- Evaluates difference at random points
- 8 trials with domain -5 to 6
- Tolerance: 1e-9
- Skips domain errors (division by zero, etc.)
app/utils/math_engine.py:435-477
Structural Comparison:
- Final fallback comparing canonicalized string forms
app/utils/math_engine.py:479-488
Security Features
The math engine includes input validation to prevent code injection:Dangerous Pattern Detection
Blocks expressions containing:- Python builtins:
exec,eval,compile,__import__ - Attribute access:
getattr,setattr,delattr - File operations:
open,file - User input:
input - Special attributes:
__name__,__dict__, etc. - Import statements
- Lambda expressions
app/utils/math_engine.py:192-219
Usage Examples
Basic Expression Validation
Database Integration
LaTeX Form Handling
Error Handling
The math engine implements graceful degradation:- Primary: LaTeX parsing via
latex2sympy2 - Secondary: SymPy parsing with transformations
- Tertiary: SymPy parsing without transformations
- Fallback: Basic string normalization
Dependencies
Required:sympy >= 1.12.0- Symbolic mathematics engine
latex2sympy2- Enhanced LaTeX parsing (recommended)
latex2sympy2 is not available, the engine will still function but with reduced LaTeX parsing capabilities.