Expression Simplifier
SRToolkit.utils.expression_simplifier
Algebraic simplification of symbolic expressions using SymPy. The functions in this script are work in progress and will be improved in the future for better accuracy and performance.
simplify
simplify(expr: Union[List[str], Node], symbol_library: SymbolLibrary = SymbolLibrary.default_symbols()) -> Union[List[str], Node]
Simplify an expression algebraically.
Two successive steps are applied:
- SymPy simplification — expands and reduces the expression algebraically
(e.g.
X_0 * X_1 / X_0→X_1). - Constant folding — collapses any sub-expression containing no variables
into a single free constant
C(e.g.C * C + C→C).
Examples:
>>> expr = ["C", "+", "C", "*", "C", "+", "X_0", "*", "X_1", "/", "X_0"]
>>> print("".join(simplify(expr)))
C+X_1
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
expr
|
Union[List[str], Node]
|
Expression as a token list in infix notation or a Node tree. |
required |
symbol_library
|
SymbolLibrary
|
Symbol library defining variables and constants. Defaults to SymbolLibrary.default_symbols. |
default_symbols()
|
Returns:
| Type | Description |
|---|---|
Union[List[str], Node]
|
The simplified expression in the same form as the input (list if a list was given, Node if a tree was given). |
Raises:
| Type | Description |
|---|---|
Exception
|
If simplification fails or the result contains tokens absent from
|