Skip to content

Expression API Reference

Expression

Mathematical expression combining variables and coefficients.

An Expression represents a mathematical formula built from variables, constants, and arithmetic operations (+, -, *, **). Expressions can be linear, quadratic, or higher-order polynomial forms.

Parameters:

  • env (Environment, default: None ) –

    The environment for this expression. If None and created via __init__, requires an active environment context or raises NoActiveEnvironmentError.

Attributes:

  • environment (Environment) –

    The environment that this expression is associated with (contains variable metadata referenced by this expression).

  • num_variables (int) –

    Number of variables with non-zero coefficients in the expression.

Examples:

Create expressions from variables:

>>> from luna_model import Variable, Environment
>>> with Environment():
...     x = Variable("x")
...     y = Variable("y")
>>> expr = 3 * x + 2 * y - 5
>>> print(expr)
3 x + 2 y - 5

Create quadratic expression:

>>> with Environment():
...     x = Variable("x")
...     y = Variable("y")
...     z = Variable("z")
>>> quad_expr = x * y + z**2
>>> print(quad_expr)
x y + z

Create constant expression:

>>> from luna_model import Expression
>>> with Environment():
...     const_expr = Expression.const(42.0)
>>> print(const_expr)
42

Access expression terms:

>>> with Environment():
...     x = Variable("x")
...     y = Variable("y")
>>> expr = 3 * x + 2 * y - 5
>>> for variables, bias in expr.items():
...     print(f"{variables}: {bias}")
Linear(x): 3.0
Linear(y): 2.0
Constant(): -5.0
Notes

Arithmetic operations do not mutate the expressions and create new Expression objects. In-place operators (+=, -=, *=, **=) mutate the given expression.

environment: Environment property

Get the environment associated with this expression.

Returns:

  • Environment

    The environment this expression's variables are contained in.

num_variables: int property

Get the number of variables with non-zero coefficients in the expression.

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

Initialize an empty expression.

Parameters:

  • env (Environment, default: None ) –

    The environment for this expression.

const(value: float, /, env: Environment | None = None) -> Expression classmethod

Create a constant expression.

Parameters:

  • value (float) –

    The constant value.

  • env (Environment, default: None ) –

    The environment for this expression.

Returns:

  • Expression

    An expression representing the constant value.

Examples:

>>> from luna_model import Environment, Expression
>>> with Environment():
...     const = Expression.const(5.0)

get_offset() -> float

Get the constant offset of the expression.

Returns:

  • float

    The constant term in the expression.

get_linear(variable: Variable) -> float

Get the linear coefficient for a variable.

Parameters:

  • variable (Variable) –

    The variable to query.

Returns:

  • float

    The coefficient of the variable, or 0 if not present.

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

Get the quadratic coefficient for a variable pair.

Parameters:

Returns:

  • float

    The coefficient of the u*v term, or 0 if not present.

get_higher_order(*variables: Variable) -> float

Get the higher-order coefficient for a variable tuple.

Parameters:

  • *variables (Variable, default: () ) –

    The variables in the higher-order term.

Returns:

  • float

    The coefficient of the higher-order term, or 0 if not present.

items() -> ExprIter

Get an iterator over all terms in the expression.

Returns:

  • ExprIter

    Iterator yielding (variables, coefficient) tuples for each term.

Examples:

>>> from luna_model import Variable, Environment
>>> with Environment():
...     x = Variable("x")
...     y = Variable("y")
>>> expr = 3 * x + 2 * x * y + 5
>>> for vars, coeff in expr.items():
...     print(f"{vars}: {coeff}")
Linear(x): 3.0
Quadratic(x, y): 2.0
Constant(): 5.0

variables() -> list[Variable]

Get all variables with non-zero coefficients in the expression.

Returns:

  • list[Variable]

    List of all variables with non-zero coefficients appearing in the expression.

degree() -> int

Get the degree of the expression.

Returns:

  • int

    The highest degree of any term (0=constant, 1=linear, 2=quadratic, etc.).

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

Get all linear terms in the expression.

Returns:

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

Get all quadratic terms in the expression.

Returns:

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

Get all higher-order terms in the expression.

Returns:

is_constant() -> bool

Check if the expression is a constant (no variables).

Returns:

  • bool

    True if the expression contains no variables.

has_quadratic() -> bool

Check if the expression has quadratic terms.

Returns:

  • bool

    True if the expression contains at least one quadratic term.

has_higher_order() -> bool

Check if the expression has higher-order terms.

Returns:

  • bool

    True if the expression contains at least one term of degree > 2.

is_equal(other: Expression) -> bool

Check if two expressions are structurally equal.

Parameters:

  • other (Expression) –

    The expression to compare with.

Returns:

  • bool

    True if expressions are structurally equal.

equal_contents(other: Expression) -> bool

Check if two expressions have equal terms and coefficients.

Parameters:

  • other (Expression) –

    The expression to compare with.

Returns:

  • bool

    True if expressions have the same terms with same coefficients.

separate(variables: Sequence[Variable]) -> tuple[Expression, Expression]

Separate expression into two parts based on variables.

Splits the expression so that all specified variables appear only in the first returned expression.

Parameters:

  • variables (Sequence[Variable]) –

    Variables to isolate in the first expression.

Returns:

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

Substitute a variable with an expression or another variable.

Parameters:

  • target (Variable) –

    The variable to replace.

  • replacement (Expression or Variable) –

    The expression or variable to substitute in place of target.

Returns:

  • Expression

    New expression with the substitution applied.

Examples:

>>> from luna_model import Variable, Environment
>>> with Environment():
...     x = Variable("x")
...     y = Variable("y")
...     z = Variable("z")
>>> expr = 2 * x + 3 * y
>>> print(expr)
2 x + 3 y
>>> new_expr = expr.substitute(x, z + 1)  # Replace x with z+1
>>> print(new_expr)
3 y + 2 z + 2

evaluate(solution: Solution) -> NDArray

Evaluate the expression using variable values from a solution.

Parameters:

  • solution (Solution) –

    The solution containing variable assignments.

Returns:

  • NDArray

    The evaluated value(s) of the expression.

evaluate_sample(sample: Sample | dict[Variable | str, int | float]) -> float

Evaluate the expression using variable values from a sample.

Parameters:

Returns:

  • float

    The evaluated value of the expression.

encode() -> bytes

Serialize the expression into a compact binary format.

Returns:

  • bytes

    Encoded expression representation.

serialize() -> bytes

Serialize the expression into a compact binary format.

This is an alias for :meth:encode.

Returns:

  • bytes

    Encoded expression representation.

decode(data: bytes, env: Environment) -> Expression classmethod

Reconstruct an expression from encoded bytes.

Parameters:

  • data (bytes) –

    Encoded expression data.

  • env (Environment) –

    The environment containing the vairables associated with the encoded expression.

Returns:

deserialize(data: bytes, env: Environment) -> Expression classmethod

Reconstruct an expression from encoded bytes.

This is an alias for :meth:decode.

Parameters:

  • data (bytes) –

    Encoded expression data.

  • env (Environment) –

    The environment containing the vairables associated with the encoded expression.

Returns:

deep_clone_many(exprs: Sequence[Expression]) -> list[Expression] classmethod

Deep clones all provided expressions into a new environment.

Parameters:

Returns:

  • list[Expression]

    The passed expressions as part of a new environment.

Raises:

  • DifferentEnvsError

    If any expression is from a different environment as the first expression in the passed list of expressions.

__add__(other: Expression | Variable | float) -> Expression

Add another term to this expression.

Parameters:

Returns:

  • Expression

    A new expression representing the sum.

Examples:

>>> from luna_model import Expression, Variable, Environment
>>> with Environment():
...     x = Variable("x")
...     y = Variable("y")
...     expr = Expression()
>>> expr = expr + x  # Add variable
>>> expr = expr + y  # Add another variable
>>> expr = expr + 5.0  # Add constant
>>> print(expr)
x + y + 5

__sub__(other: Expression | Variable | float) -> Expression

Subtract another term from this expression.

Parameters:

Returns:

  • Expression

    A new expression representing the difference.

Examples:

>>> from luna_model import Expression, Variable, Environment
>>> with Environment():
...     x = Variable("x")
...     y = Variable("y")
...     expr = Expression()
>>> expr = expr - x  # Sub variable
>>> expr = expr - y  # Sub another variable
>>> expr = expr - 5.0  # Sub constant
>>> print(expr)
-x - y - 5

__mul__(other: Expression | Variable | float) -> Expression

Multiply this expression by another term.

Parameters:

Returns:

  • Expression

    A new expression representing the product.

Examples:

>>> from luna_model import Variable, Environment
>>> with Environment():
...     x = Variable("x")
...     y = Variable("y")
>>> expr = 2 * x
>>> expr = expr * y  # Creates quadratic term
>>> expr = expr * 3  # Scale by constant
>>> print(expr)
6 x y

__radd__(other: Expression | Variable | float) -> Expression

Add this expression to another term (right operand).

Parameters:

Returns:

  • Expression

    A new expression representing the sum.

__rsub__(other: Expression | Variable | float) -> Expression

Subtract this expression from another term (right operand).

Parameters:

Returns:

  • Expression

    A new expression representing the difference.

__rmul__(other: Expression | Variable | float) -> Expression

Multiply another term by this expression (right operand).

Parameters:

Returns:

  • Expression

    A new expression representing the product.

__iadd__(other: Expression | Variable | float) -> Self

Add another term to this expression in-place.

Parameters:

Returns:

  • Expression

    This expression modified in-place.

Examples:

>>> from luna_model import Expression, Variable, Environment
>>> with Environment():
...     x = Variable("x")
...     y = Variable("y")
...     expr = Expression()
>>> expr += x
>>> expr += y
>>> print(expr)
x + y

__isub__(other: Expression | Variable | float) -> Self

Subtract another term from this expression in-place.

Parameters:

Returns:

  • Expression

    This expression modified in-place.

Examples:

>>> from luna_model import Expression, Variable, Environment
>>> with Environment():
...     x = Variable("x")
...     y = Variable("y")
...     expr = Expression()
>>> expr -= x
>>> expr -= y
>>> print(expr)
-x - y

__imul__(other: Expression | Variable | float) -> Self

Multiply this expression by another term in-place.

Parameters:

Returns:

  • Expression

    This expression modified in-place.

Examples:

>>> from luna_model import Expression, Variable, Environment
>>> with Environment():
...     x = Variable("x")
...     y = Variable("y")
...     expr = Expression.const(42)
>>> expr *= x
>>> expr *= y
>>> print(expr)
42 x y

__pow__(value: int) -> Expression

Raise this expression to an integer power.

Parameters:

  • value (int) –

    The exponent (must be a non-negative integer).

Returns:

  • Expression

    A new expression representing this expression raised to the power.

Examples:

>>> from luna_model import Variable, Vtype, Environment
>>> with Environment():
...     x = Variable("x", vtype=Vtype.INTEGER)
...     y = Variable("y", vtype=Vtype.INTEGER)
>>> expr = x**2  # Quadratic
>>> expr += y**3  # Cubic
>>> print(expr)
y^3 + x^2

__ipow__(other: int) -> Self

Raise this expression to an integer power in-place.

Parameters:

  • other (int) –

    The exponent (must be a non-negative integer).

Returns:

  • Expression

    This expression modified in-place.

Examples:

>>> from luna_model import Variable, Vtype, Environment
>>> with Environment():
...     a = Variable("a", vtype=Vtype.INTEGER)
...     b = Variable("b", vtype=Vtype.INTEGER)
>>> expr = a + b
>>> expr **= 2
>>> print(expr)
a^2 + 2 a b + b^2

__neg__() -> Expression

Negate this expression.

Returns:

  • Expression

    A new expression representing the negation.

Examples:

>>> from luna_model import Variable, Environment
>>> with Environment():
...     x = Variable("x")
...     y = Variable("y")
>>> expr = -x
>>> print(expr)
-x
>>> expr = -(x + y)
>>> print(expr)
-x - y

__eq__(other: Expression | Variable | float) -> Constraint

Create an equality constraint.

Parameters:

Returns:

  • Constraint

    A constraint representing self == other.

Examples:

>>> from luna_model import Variable, Environment
>>> with Environment():
...     x = Variable("x")
...     y = Variable("y")
>>> constraint = x + y == 10
>>> print(constraint)
x + y == 10

__le__(other: Expression | Variable | float) -> Constraint

Create a less-than-or-equal-to constraint.

Parameters:

Returns:

  • Constraint

    A constraint representing self <= other.

Examples:

>>> from luna_model import Variable, Environment
>>> with Environment():
...     x = Variable("x")
...     y = Variable("y")
>>> constraint = x + y <= 100
>>> print(constraint)
x + y <= 100

__ge__(other: Expression | Variable | float) -> Constraint

Create a greater-than-or-equal-to constraint.

Parameters:

Returns:

  • Constraint

    A constraint representing self >= other.

Examples:

>>> from luna_model import Variable, Environment
>>> with Environment():
...     x = Variable("x")
...     y = Variable("y")
>>> constraint = x + y >= 0
>>> print(constraint)
x + y >= 0

__reduce__() -> tuple[Callable[[bytes, bytes], Expression], tuple[bytes, bytes]]

Support for pickle serialization.

Returns:

  • tuple

    A tuple of (decoder_function, encoded_data) for pickle.

Notes

This method is called automatically by Python's pickle module.

__str__() -> str

Get human-readable string representation.

Returns:

  • str

    A string showing the expression structure.

Examples:

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

Constant

Constant term in an expression.

Represents a term of the form: coefficient

Linear

Linear term in an expression.

Represents a term of the form: coefficient * variable

Attributes:

var: Variable property

Get the variable in this linear term.

Returns:

__str__() -> str

Return human-readable string representation.

Returns:

  • str

    String representation of the linear term.

Quadratic

Quadratic term in an expression.

Represents a term of the form: coefficient * var_a * var_b

Attributes:

var_a: Variable property

Get the first variable in the quadratic term.

Returns:

var_b: Variable property

Get the second variable in the quadratic term.

Returns:

__str__() -> str

Return human-readable string representation.

Returns:

  • str

    String representation of the quadratic term.

HigherOrder

Higher-order term in an expression.

Represents a term with degree > 2 of the form: coefficient * var1 * var2 * ...

Attributes:

vars: list[Variable] property

Get the variables in this higher-order term.

Returns:

__str__() -> str

Return human-readable string representation.

Returns:

  • str

    String representation of the higher-order term.

Constant

Constant term in an expression.

Represents a term of the form: coefficient

ExprIter

Iterator over terms in an expression.

Iterates over all terms in an expression, yielding (term, coefficient) tuples where term is a Constant, Linear, Quadratic, or HigherOrder object.

Examples:

>>> from luna_model import Variable, Environment
>>> from luna_model import Constant, Linear, Quadratic, HigherOrder
>>> with Environment():
...     x, y, z = Variable("x"), Variable("y"), Variable("z")
...     expr = 3 * x + 2 * x * y + 4 * x * y * z + 5
...     for term, coeff in expr.items():
...         match term:
...             case Constant():
...                 print(f"constant: {coeff}")
...             case Linear(var):
...                 print("linear:", coeff, var.name)
...             case Quadratic(var_a, var_b):
...                 print("quadratic:", coeff, var_a.name, var_b.name)
...             case HigherOrder(vars):
...                 print("higher-order:", coeff, *[v.name for v in vars])
linear: 3.0 x
quadratic: 2.0 x y
higher-order: 4.0 x y z
constant: 5.0

__next__() -> tuple[Constant | Linear | Quadratic | HigherOrder, float]

Get the next term and coefficient.

Returns:

Raises:

__iter__() -> ExprIter

Return the iterator object itself.