Utilities for dealing with expressions

Parser

pymbolic.parse(expr_str)

Return a pymbolic.primitives.Expression tree corresponding to expr_str.

The parser is also relatively easy to extend. See the source code of the following class.

class pymbolic.parser.Parser

Compiler

class pymbolic.compiler.CompiledExpression(expression, variables=[])

This class encapsulates an expression compiled into Python bytecode for faster evaluation.

Its instances (unlike plain lambdas) are pickleable.

Parameters:variables – The first arguments (as strings or pymbolic.primitives.Variable instances) to be used for the compiled function. All variables used by the expression and not present here are added in alphabetical order.
__call__(*args)

Interoperability with other symbolic systems

Interoperability with sympy

Interoperability with Maxima

class pymbolic.interop.maxima.MaximaStringifyMapper(constant_mapper=<class 'str'>)
Parameters:constant_mapper – A function of a single expr argument being used to map constants into strings.
class pymbolic.interop.maxima.MaximaParser
class pymbolic.interop.maxima.MaximaKernel(executable='maxima', timeout=30)
restart()
shutdown()
reset()
exec_str(s, enforce_prompt_numbering=True)
eval_str(s, enforce_prompt_numbering=True)
eval_expr(expr)
pymbolic.interop.maxima.eval_expr_with_setup(assignments, expr)
pymbolic.interop.maxima.diff(expr, var, count=1, assignments=())

Interoperability with Python’s ast module

An example:

src = """
def f():
    xx = 3*y + z * (12 if x < 13 else 13)
    yy = f(x, y=y)
"""

import ast
mod = ast.parse(src.replace("\n    ", "\n"))

print(ast.dump(mod))

from pymbolic.interop.ast import ASTToPymbolic
ast2p = ASTToPymbolic()

for f in mod.body:
    if not isinstance(f, ast.FunctionDef):
        continue

    for stmt in f.body:
        if not isinstance(stmt, ast.Assign):
            continue

        lhs, = stmt.targets
        lhs = ast2p(lhs)
        rhs = ast2p(stmt.value)

        print(lhs, rhs)
class pymbolic.interop.ast.ASTToPymbolic