Primitives (Basic Objects)

Typing helpers

pymbolic.BoolT

alias of bool | bool

pymbolic.NumberT

alias of int | integer | float | complex | inexact

pymbolic.ScalarT

alias of int | integer | float | complex | inexact | bool | bool

pymbolic.ArithmeticExpressionT

A narrower type alias than ExpressionT that is returned by arithmetic operators, to allow continue doing arithmetic with the result of arithmetic.

> alias of int | integer | float | complex | inexact | Expression

pymbolic.ExpressionT

alias of int | integer | float | complex | inexact | bool | bool | Expression | Tuple[ExpressionT, …]

Expression base class

class pymbolic.Expression[source]

Superclass for parts of a mathematical expression. Overrides operators to implicitly construct Sum, Product and other expressions.

Expression objects are immutable.

Changed in version 2022.2: PEP 634-style pattern matching is now supported when Pymbolic is used under Python 3.10.

property a: _AttributeLookupCreator

Provide a spelling expr.a.name for encoding attribute lookup.

attr(name: str) Lookup[source]

Return a Lookup for name in self.

mapper_method: ClassVar[str]

The pymbolic.mapper.Mapper method called for objects of this type.

__getitem__(subscript: ExpressionT | EmptyOK) Expression[source]

Return an expression representing self[subscript].

make_stringifier(originating_stringifier=None)[source]

Return a pymbolic.mapper.Mapper instance that can be used to generate a human-readable representation of self. Usually a subclass of pymbolic.mapper.stringifier.StringifyMapper.

Parameters:

originating_stringifier – If provided, the newly created stringifier should carry forward attributes and settings of originating_stringifier.

__eq__(other) bool[source]

Provides equality testing with quick positive and negative paths based on id() and __hash__().

__hash__() int[source]

Provides caching for hash values.

__str__() str[source]

Use the make_stringifier() to return a human-readable string representation of self.

__repr__() str[source]

Return repr(self).

Logical operator constructors

not_() LogicalNot[source]

Return self wrapped in a LogicalNot.

Added in version 2015.2.

and_(other) LogicalAnd[source]

Return LogicalAnd between self and other.

Added in version 2015.2.

or_(other) LogicalOr[source]

Return LogicalOr between self and other.

Added in version 2015.2.

Comparison constructors

eq(other) Comparison[source]

Return a Comparison comparing self to other.

Added in version 2015.2.

ne(other) Comparison[source]

Return a Comparison comparing self to other.

Added in version 2015.2.

lt(other) Comparison[source]

Return a Comparison comparing self to other.

Added in version 2015.2.

le(other) Comparison[source]

Return a Comparison comparing self to other.

Added in version 2015.2.

gt(other) Comparison[source]

Return a Comparison comparing self to other.

Added in version 2015.2.

ge(other) Comparison[source]

Return a Comparison comparing self to other.

Added in version 2015.2.

pymbolic.expr_dataclass(init: bool = True, hash: bool = True) Callable[[type[_T]], type[_T]][source]

A class decorator that makes the class a dataclass() while also adding functionality needed for Expression nodes. Specifically, it adds cached hashing, equality comparisons with self is other shortcuts as well as some methods/attributes for backward compatibility (e.g. __getinitargs__, init_arg_names)

It also adds a Expression.mapper_method based on the class name if not already present. If mapper_method is inherited, it will be viewed as unset and replaced.

Added in version 2024.1.

class pymbolic.Variable(name: str)[source]

Bases: Leaf

name: str
mapper_method: ClassVar[str] = 'map_variable'

Expressions

class pymbolic.primitives.AlgebraicLeaf[source]

Bases: Expression

An expression that serves as a leaf for arithmetic evaluation. This may end up having child nodes still, but they’re not reached by ways of arithmetic.

mapper_method: ClassVar[str] = 'map_algebraic_leaf'
class pymbolic.primitives.Leaf[source]

Bases: AlgebraicLeaf

An expression that is irreducible, i.e. has no Expression-type parts whatsoever.

mapper_method: ClassVar[str] = 'map_leaf'
class pymbolic.primitives.Wildcard[source]

Bases: Leaf

A general wildcard that can be used to substitute expressions.

mapper_method: ClassVar[str] = 'map_wildcard'
class pymbolic.primitives.DotWildcard(name: str)[source]

Bases: Leaf

A wildcard that can be substituted for a single expression.

mapper_method: ClassVar[str] = 'map_dot_wildcard'
class pymbolic.primitives.StarWildcard(name: str)[source]

Bases: Leaf

A wildcard that can be substituted by a sequence of expressions of non-negative length.

mapper_method: ClassVar[str] = 'map_star_wildcard'

Function Calls

class pymbolic.primitives.Call(function: ExpressionT, parameters: tuple[ExpressionT, ...])[source]

Bases: AlgebraicLeaf

A function invocation.

function: ExpressionT

A Expression that evaluates to a function.

parameters: tuple[ExpressionT, ...]

A tuple of positional parameters, each element of which is a Expression or a constant.

mapper_method: ClassVar[str] = 'map_call'
class pymbolic.primitives.CallWithKwargs(function: ExpressionT, parameters: tuple[ExpressionT, ...], kw_parameters: Mapping[str, ExpressionT])[source]

Bases: AlgebraicLeaf

A function invocation with keyword arguments.

function: ExpressionT

An Expression that evaluates to a function.

parameters: tuple[ExpressionT, ...]

A tuple of positional parameters, each element of which is a Expression or a constant.

kw_parameters: Mapping[str, ExpressionT]

A dictionary mapping names to arguments, each of which is a Expression or a constant.

mapper_method: ClassVar[str] = 'map_call_with_kwargs'
class pymbolic.primitives.Subscript(aggregate: ExpressionT, index: ExpressionT = <function Expression.index>)[source]

Bases: AlgebraicLeaf

An array subscript.

mapper_method: ClassVar[str] = 'map_subscript'
class pymbolic.primitives.Lookup(aggregate: ExpressionT, name: str)[source]

Bases: AlgebraicLeaf

Access to an attribute of an aggregate, such as an attribute of a class.

mapper_method: ClassVar[str] = 'map_lookup'

Sums, products and such

class pymbolic.primitives.Sum(children: tuple[ExpressionT, ...])[source]

Bases: Expression

children: tuple[ExpressionT, ...]
__add__(other)[source]
__radd__(other)[source]
__sub__(other)[source]
__bool__()[source]
mapper_method: ClassVar[str] = 'map_sum'
class pymbolic.primitives.Product(children: tuple[ExpressionT, ...])[source]

Bases: Expression

children: tuple[ExpressionT, ...]
__mul__(other)[source]
__rmul__(other)[source]
__bool__()[source]
mapper_method: ClassVar[str] = 'map_product'
class pymbolic.primitives.Min(children: tuple[ExpressionT, ...])[source]

Bases: Expression

children: tuple[ExpressionT, ...]
mapper_method: ClassVar[str] = 'map_min'
class pymbolic.primitives.Max(children: tuple[ExpressionT, ...])[source]

Bases: Expression

children: tuple[ExpressionT, ...]
mapper_method: ClassVar[str] = 'map_max'
class pymbolic.primitives.Quotient(numerator: ExpressionT, denominator: ExpressionT)[source]

Bases: Expression

numerator: ExpressionT
denominator: ExpressionT
mapper_method: ClassVar[str] = 'map_quotient'
class pymbolic.primitives.FloorDiv(numerator: ExpressionT, denominator: ExpressionT)[source]

Bases: Expression

numerator: ExpressionT
denominator: ExpressionT
mapper_method: ClassVar[str] = 'map_floor_div'
class pymbolic.primitives.Remainder(numerator: ExpressionT, denominator: ExpressionT)[source]

Bases: Expression

numerator: ExpressionT
denominator: ExpressionT
mapper_method: ClassVar[str] = 'map_remainder'
class pymbolic.primitives.Power(base: ExpressionT, exponent: ExpressionT)[source]

Bases: Expression

base: ExpressionT
exponent: ExpressionT
mapper_method: ClassVar[str] = 'map_power'

Shift operators

class pymbolic.primitives.LeftShift(shiftee: ExpressionT, shift: ExpressionT)[source]

Bases: Expression.

shiftee: ExpressionT
shift: ExpressionT
mapper_method: ClassVar[str] = 'map_left_shift'
class pymbolic.primitives.RightShift(shiftee: ExpressionT, shift: ExpressionT)[source]

Bases: Expression.

shiftee: ExpressionT
shift: ExpressionT
mapper_method: ClassVar[str] = 'map_right_shift'

Bitwise operators

class pymbolic.primitives.BitwiseNot(child: ExpressionT)[source]

Bases: Expression

child: ExpressionT
mapper_method: ClassVar[str] = 'map_bitwise_not'
class pymbolic.primitives.BitwiseOr(children: tuple[ExpressionT, ...])[source]

Bases: Expression

children: tuple[ExpressionT, ...]
mapper_method: ClassVar[str] = 'map_bitwise_or'
class pymbolic.primitives.BitwiseXor(children: tuple[ExpressionT, ...])[source]

Bases: Expression

children: tuple[ExpressionT, ...]
mapper_method: ClassVar[str] = 'map_bitwise_xor'
class pymbolic.primitives.BitwiseAnd(children: tuple[ExpressionT, ...])[source]

Bases: Expression

children: tuple[ExpressionT, ...]
mapper_method: ClassVar[str] = 'map_bitwise_and'

Comparisons and logic

class pymbolic.primitives.Comparison(left: ExpressionT, operator: str, right: ExpressionT)[source]

Bases: Expression

left: ExpressionT
operator: str

One of [">", ">=", "==", "!=", "<", "<="].

right: ExpressionT

Note

Unlike other expressions, comparisons are not implicitly constructed by comparing Expression objects. See pymbolic.Expression.eq().

operator_to_name: ClassVar[dict[str, str]] = {'!=': 'ne', '<': 'lt', '<=': 'le', '==': 'eq', '>': 'gt', '>=': 'ge'}
name_to_operator: ClassVar[dict[str, str]] = {'eq': '==', 'ge': '>=', 'gt': '>', 'le': '<=', 'lt': '<', 'ne': '!='}
mapper_method: ClassVar[str] = 'map_comparison'
class pymbolic.primitives.LogicalNot(child: ExpressionT)[source]

Bases: Expression

child: ExpressionT
mapper_method: ClassVar[str] = 'map_logical_not'
class pymbolic.primitives.LogicalAnd(children: tuple[ExpressionT, ...])[source]

Bases: Expression

children: tuple[ExpressionT, ...]
mapper_method: ClassVar[str] = 'map_logical_and'
class pymbolic.primitives.LogicalOr(children: tuple[ExpressionT, ...])[source]

Bases: Expression

children: tuple[ExpressionT, ...]
mapper_method: ClassVar[str] = 'map_logical_or'
class pymbolic.primitives.If(condition: ExpressionT, then: ExpressionT, else_: ExpressionT)[source]

Bases: Expression

condition: ExpressionT
then: ExpressionT
else_: ExpressionT
mapper_method: ClassVar[str] = 'map_if'

Slices

class pymbolic.primitives.Slice(children: tuple[()] | tuple[ExpressionT] | tuple[ExpressionT, ExpressionT] | tuple[ExpressionT, ExpressionT, ExpressionT])[source]

Bases: Expression

A slice expression as in a[1:7].

children: tuple[()] | tuple[ExpressionT] | tuple[ExpressionT, ExpressionT] | tuple[ExpressionT, ExpressionT, ExpressionT]
property start
property stop
property step
mapper_method: ClassVar[str] = 'map_slice'

Code generation helpers

class pymbolic.primitives.CommonSubexpression(child: ExpressionT, prefix: str | None = None, scope: str = 'pymbolic_eval')[source]

Bases: Expression

A helper for code generation and caching. Denotes a subexpression that should only be evaluated once. If, in code generation, it is assigned to a variable, a name starting with prefix should be used.

child: ExpressionT
prefix: str | None = None
scope: str = 'pymbolic_eval'

One of the values in cse_scope. See there for meaning.

See pymbolic.mapper.c_code.CCodeMapper for an example.

mapper_method: ClassVar[str] = 'map_common_subexpression'
class pymbolic.primitives.cse_scope[source]

Determines the lifetime for the saved value of a CommonSubexpression.

EVALUATION: str

The evaluated result lives for the duration of the evaluation of the current expression and is discarded thereafter.

EXPRESSION: str

The evaluated result lives for the lifetime of the current expression (across multiple evaluations with multiple parameters) and is discarded when the expression is.

GLOBAL: str

The evaluated result lives until the execution context dies.

pymbolic.primitives.make_common_subexpression(field, prefix=None, scope=None)[source]

Wrap field in a CommonSubexpression with prefix. If field is a numpy object array, each individual entry is instead wrapped. If field is a pymbolic.geometric_algebra.MultiVector, each coefficient is individually wrapped.

See CommonSubexpression for the meaning of prefix and scope.

Symbolic derivatives and substitution

Inspired by similar functionality in sympy.

class pymbolic.primitives.Substitution(child: ExpressionT, variables: tuple[str, ...], values: tuple[ExpressionT, ...])[source]

Bases: Expression

Work-alike of Subs.

child: ExpressionT
variables: tuple[str, ...]
values: tuple[ExpressionT, ...]
mapper_method: ClassVar[str] = 'map_substitution'
class pymbolic.primitives.Derivative(child: ExpressionT, variables: tuple[str, ...])[source]

Bases: Expression

Work-alike of sympy’s Derivative.

child: ExpressionT
variables: tuple[str, ...]
mapper_method: ClassVar[str] = 'map_derivative'

Helper functions

pymbolic.primitives.is_zero(value)[source]
pymbolic.primitives.is_constant(value: object) TypeIs[int | integer | float | complex | inexact | bool | bool][source]
pymbolic.primitives.flattened_sum(terms)[source]

Recursively flattens all the top level Sums in terms.

Parameters:

terms – an Iterable of expressions.

Returns:

a Sum expression or, if there is only one term in the sum, the respective term.

pymbolic.primitives.flattened_product(terms)[source]

Recursively flattens all the top level Products in terms.

This operation does not change the order of the terms in the products, so it does not require the product to be commutative.

Parameters:

terms – an Iterable of expressions.

Returns:

a Product expression or, if there is only one term in the product, the respective term.

pymbolic.primitives.register_constant_class(class_)[source]
pymbolic.primitives.unregister_constant_class(class_)[source]
pymbolic.primitives.variables(s)[source]

Return a list of variables for each (space-delimited) identifier in s.

Interaction with numpy arrays

numpy.ndarray instances are supported anywhere in an expression. In particular, numpy object arrays are useful for capturing vectors and matrices of pymbolic objects.

pymbolic.primitives.make_sym_vector(name, components, var_factory=<class 'pymbolic.primitives.Variable'>)[source]

Return an object array of components subscripted Variable (or subclass) instances.

Parameters:
  • components – Either a list of indices, or an integer representing the number of indices.

  • var_factory – The Variable subclass to use for instantiating the scalar variables.

For example, this creates a vector with three components:

>>> make_sym_vector("vec", 3)
array([Subscript(Variable('vec'), 0), Subscript(Variable('vec'), 1),
       Subscript(Variable('vec'), 2)], dtype=object)
pymbolic.primitives.make_sym_array(name, shape, var_factory=<class 'pymbolic.primitives.Variable'>)[source]

Constants

class pymbolic.primitives.NaN(data_type: Callable[[float], Any] | None = None)[source]

Bases: Expression

An expression node representing not-a-number as a floating point number. Unlike, math.nan, all instances of NaN compare equal, as one might reasonably expect for program representation. (If this weren’t so, programs containing NaNs would effectively be unhashable, because they don’t compare equal to themselves.)

Note that, in Python, this equality comparison is made even more complex by this issue, due to which np.nan == np.nan is False, but (np.nan,) == (np.nan,) is True.

data_type: Callable[[float], Any] | None = None

The data type used for the actual realization of the constant. Defaults to None. If given, This must be a callable to which a NaN float can be passed to obtain a NaN of the yield the desired type. It must also be suitable for use as the second argument of isinstance().

mapper_method: ClassVar[str] = 'map_nan'

Helper classes

class pymbolic.primitives.EmptyOK(child: 'ExpressionT')[source]
class pymbolic.primitives._AttributeLookupCreator(aggregate: ExpressionT)[source]

Helper used by pymbolic.Expression.a to create lookups.

__getattr__(name: str) Lookup[source]

References

class pymbolic.primitives.DataclassInstance

An instance of a dataclass().

class pymbolic.primitives._T

A type variable.

class numpy.bool_

Deprecated alias for numpy.bool.

class typing_extensions.TypeIs

See typing_extensions.TypeIs.

class typing_extensions.Variable

See pymbolic.Variable.

class typing_extensions.ExpressionT

See pymbolic.ExpressionT.

class pymbolic.Comparison

See pymbolic.primitives.Comparison.

class pymbolic.LogicalNot

See pymbolic.primitives.LogicalNot.

class pymbolic.LogicalAnd

See pymbolic.primitives.LogicalAnd.

class pymbolic.LogicalOr

See pymbolic.primitives.LogicalOr.

class pymbolic.Lookup

See pymbolic.primitives.Lookup.