Skip to content

Expression Simplifier Module

SRToolkit.utils.expression_simplifier

simplify(expr, symbol_library=SymbolLibrary.default_symbols())

Simplifies a mathematical expression by
  1. making use of sympy's simplification functions
  2. simplifying constants, 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]

The expression given as a list of tokens in the infix notation or as an instance of SRToolkit.utils.expression_tree.Node

required
symbol_library SymbolLibrary

The symbol library to use. Defaults to SymbolLibrary.default_symbols().

default_symbols()

Returns:

Type Description
Union[List[str], Node]

The simplified expression

Source code in SRToolkit/utils/expression_simplifier.py
def simplify(expr: Union[List[str], Node], symbol_library: SymbolLibrary=SymbolLibrary.default_symbols()) -> Union[List[str], Node]:
    """
    Simplifies a mathematical expression by:
        1. making use of sympy's simplification functions
        2. simplifying constants, e.g. C*C + C -> C

    Examples:
        >>> expr = ["C", "+", "C" "*", "C", "+", "X_0", "*", "X_1", "/", "X_0"]
        >>> print("".join(simplify(expr)))
        C+X_1

    Args:
        expr: The expression given as a list of tokens in the infix notation or as an instance of SRToolkit.utils.expression_tree.Node
        symbol_library: The symbol library to use. Defaults to SymbolLibrary.default_symbols().

    Returns:
        The simplified expression
    """
    is_tree = False
    if isinstance(expr, Node):
        expr = expr.to_list(notation="infix", symbol_library=symbol_library)
        is_tree = True

    variables = symbol_library.get_symbols_of_type("var")
    # We expect only one symbol for constants
    constant = symbol_library.get_symbols_of_type("const")[0]

    expr = _simplify_expression("".join(expr), constant, variables)
    expr = sympify(_denumerate_constants(str(expr), constant), evaluate=False)
    expr = _sympy_to_sr(expr)

    if is_tree:
        return expr
    else:
        return expr.to_list("infix", symbol_library=symbol_library)