Skip to content

Expression

Polynomial expression supporting symbolic arithmetic, constraint creation, and encoding.

An Expression represents a real-valued mathematical function composed of variables, scalars, and coefficients. Expressions may include constant, linear, quadratic, and higher-order terms (cubic and beyond). They are used to build objective functions and constraints in symbolic optimization models.

Expressions support both regular and in-place arithmetic, including addition and multiplication with integers, floats, Variable instances, and other Expressions.

Parameters:

Name Type Description Default
env Environment

Environment used to scope the expression when explicitly instantiating it. Typically, expressions are constructed implicitly via arithmetic on variables.

...

Examples:

Constructing expressions from variables:

>>> from luna_quantum import Environment, Variable
>>> with Environment():
...     x = Variable("x")
...     y = Variable("y")
...     expr = 1 + 2 * x + 3 * x * y + x * y * y

Inspecting terms:

>>> expr.get_offset()
1.0
>>> expr.get_linear(x)
2.0
>>> expr.get_quadratic(x, y)
3.0
>>> expr.get_higher_order((x, y, y))
1.0

In-place arithmetic:

>>> expr += x
>>> expr *= 2

Creating constraints:

>>> constraint = expr == 10.0
>>> constraint2 = expr <= 15

Serialization:

>>> blob = expr.encode()
>>> restored = Expression.decode(blob)
Supported Arithmetic

The following operations are supported:

  • Addition:

    • expr + expr β†’ Expression
    • expr + variable β†’ Expression
    • expr + int | float β†’ Expression
    • int | float + expr β†’ Expression
  • In-place addition:

    • expr += expr
    • expr += variable
    • expr += int | float
  • Multiplication:

    • expr * expr
    • expr * variable
    • expr * int | float
    • int | float * expr
  • In-place multiplication:

    • expr *= expr
    • expr *= variable
    • expr *= int | float
  • Constraint creation:

    • expr == constant β†’ Constraint
    • expr <= constant β†’ Constraint
    • expr >= constant β†’ Constraint
Notes
  • Expressions are mutable: in-place operations (+=, *=) modify the instance.
  • Expressions are scoped to an environment via the variables they reference.
  • Comparisons like expr == expr return bool, not constraints.
  • Use ==, <=, >= with numeric constants to create constraints.

num_variables property

num_variables: int

Return the number of distinct variables in the expression.

Returns:

Type Description
int

Number of variables with non-zero coefficients.

__add__ method descriptor

__add__(value) -> Expression

Return self+value.

__eq__ method descriptor

__eq__(value) -> Constraint

Return self==value.

__ge__ method descriptor

__ge__(value) -> Constraint

Return self>=value.

__init__

__init__() -> None
__init__(env: Environment) -> None
__init__(env: Environment | None = ...) -> None

Create a new empty expression scoped to an environment.

Parameters:

Name Type Description Default
env Environment

The environment to which this expression is bound.

...

Raises:

Type Description
NoActiveEnvironmentFoundError

If no environment is provided and none is active in the context.

__le__ method descriptor

__le__(value) -> Constraint

Return self<=value.

__mul__ method descriptor

__mul__(value) -> Expression

Return self*value.

__neg__ method descriptor

__neg__() -> Expression

-self

__pow__ method descriptor

__pow__(value, mod=None) -> Expression

Return pow(self, value, mod).

__radd__ method descriptor

__radd__(value) -> Expression

Return value+self.

__repr__ method descriptor

__repr__() -> str

Return repr(self).

__rmul__ method descriptor

__rmul__(value) -> Expression

Return value*self.

__rsub__ method descriptor

__rsub__(value)

Return value-self.

__str__ method descriptor

__str__() -> str

Return str(self).

__sub__ method descriptor

__sub__(value) -> Expression

Return self-value.

decode builtin

decode(data: bytes, env) -> Expression

Reconstruct an expression from encoded bytes.

Parameters:

Name Type Description Default
data bytes

Binary blob returned by encode().

required

Returns:

Type Description
Expression

Deserialized expression object.

Raises:

Type Description
DecodeError

If decoding fails due to corruption or incompatibility.

degree method descriptor

degree() -> int

Get the degree of the expression.

deserialize builtin

deserialize(data: bytes, env) -> Expression

Alias for decode().

See decode() for full documentation.

encode method descriptor

encode(compress: bool | None = True, level: int | None = 3) -> bytes

Serialize the expression into a compact binary format.

Parameters:

Name Type Description Default
compress bool

Whether to compress the data. Default is True.

True
level int

Compression level (0–9). Default is 3.

3

Returns:

Type Description
bytes

Encoded representation of the expression.

Raises:

Type Description
IOError

If serialization fails.

equal_contents method descriptor

equal_contents(other)

get_higher_order method descriptor

get_higher_order(variables: tuple[Variable, ...]) -> float

Get the coefficient for a higher-order term (degree β‰₯ 3).

Parameters:

Name Type Description Default
variables tuple of Variable

A tuple of variables specifying the term.

required

Returns:

Type Description
float

The coefficient, or 0.0 if not present.

Raises:

Type Description
VariableOutOfRangeError

If any variable is out of bounds for the environment.

get_linear method descriptor

get_linear(variable: Variable) -> float

Get the coefficient of a linear term for a given variable.

Parameters:

Name Type Description Default
variable Variable

The variable whose linear coefficient is being queried.

required

Returns:

Type Description
float

The coefficient, or 0.0 if the variable is not present.

Raises:

Type Description
VariableOutOfRangeError

If the variable index is not valid in this expression's environment.

get_offset method descriptor

get_offset() -> float

Get the constant (offset) term in the expression.

Returns:

Type Description
float

The constant term.

get_quadratic method descriptor

get_quadratic(u: Variable, v: Variable) -> float

Get the coefficient for a quadratic term (u * v).

Parameters:

Name Type Description Default
u Variable
required
v Variable
required

Returns:

Type Description
float

The coefficient, or 0.0 if not present.

Raises:

Type Description
VariableOutOfRangeError

If either variable is out of bounds for the expression's environment.

has_higher_order method descriptor

has_higher_order() -> bool

Check if expression has higher-order.

Returns:

Type Description
bool

If the expression has higher-order

has_quadratic method descriptor

has_quadratic() -> bool

Check if expression has quadratic.

Returns:

Type Description
bool

If the expression has quadratic

higher_order_items method descriptor

higher_order_items() -> list[tuple[list[Variable], float]]

Get all higher-order components.

Returns:

Type Description
list[tuple[list[Variable], float]]

The higher-order components.

is_constant method descriptor

is_constant() -> bool

Check if expression is constant.

Returns:

Type Description
bool

If the expression is constant

is_equal method descriptor

is_equal(other: Expression) -> bool

Compare two expressions for equality.

Parameters:

Name Type Description Default
other Expression

The expression to which self is compared to.

required

Returns:

Type Description
bool

If the two expressions are equal.

items method descriptor

items() -> ExpressionIterator

Iterate over the single components of an expression. An component refers to a single constant, linear, quadratic, or higher-order term of an expression.

Returns:

Type Description
ExpressionIterator

The iterator over the expression's components.

linear_items method descriptor

linear_items() -> list[tuple[Variable, float]]

Get all linear components.

Returns:

Type Description
list[tuple[Variable, float]]

The linear components.

quadratic_items method descriptor

quadratic_items() -> list[tuple[Variable, Variable, float]]

Get all quadratic components.

Returns:

Type Description
list[tuple[Variable, Variable, float]]

The quadratic components.

serialize method descriptor

serialize(compress: bool | None = True, level: int | None = 3) -> bytes

Alias for encode().

See encode() for full documentation.

substitute method descriptor

substitute(target: Variable, replacement: Expression | Variable) -> Expression

Substitute every occurrence of a variable in an expression with another expression.

Given an expression self, this method replaces all occurrences of target with replacement. If the substitution would cross differing environments (e.g. captures from two different scopes), it returns a DifferentEnvsError.

Parameters:

Name Type Description Default
target VarRef

The variable reference to replace.

required
replacement Expression | Variable

The expression to insert in place of target.

required

Returns:

Type Description
Expression

The resulting expression after substitution.

Raises:

Type Description
DifferentEnvsError

If the environments of self, target and replacement are not compatible.

variables method descriptor

variables() -> list[Variable]

Get all variables that are part of this expression.

Returns:

Type Description
list[Variable]

The list of active variables