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 raisesNoActiveEnvironmentError.
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:
get_offset() -> float
get_linear(variable: Variable) -> float
get_quadratic(u: Variable, v: Variable) -> float
get_higher_order(*variables: Variable) -> float
items() -> ExprIter
Get an iterator over all terms in the expression.
Returns:
-
ExprIter–Iterator yielding (variables, coefficient) tuples for each term.
Examples:
variables() -> list[Variable]
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]]
quadratic_items() -> list[tuple[Variable, Variable, float]]
higher_order_items() -> list[tuple[list[Variable], float]]
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:
Returns:
-
tuple[Expression, Expression]–Two expressions: (terms_with_variables, terms_without_variables).
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:
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
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:
-
Expression–The decoded expression.
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:
-
Expression–The decoded expression.
deep_clone_many(exprs: Sequence[Expression]) -> list[Expression]
classmethod
Deep clones all provided expressions into a new environment.
Parameters:
-
exprs(Sequence[Expression]) –The expressions to move to the new environment.
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:
-
other(Expression or Variable or float) –The term to add.
Returns:
-
Expression–A new expression representing the sum.
Examples:
__sub__(other: Expression | Variable | float) -> Expression
Subtract another term from this expression.
Parameters:
-
other(Expression or Variable or float) –The term to subtract.
Returns:
-
Expression–A new expression representing the difference.
Examples:
__mul__(other: Expression | Variable | float) -> Expression
Multiply this expression by another term.
Parameters:
-
other(Expression or Variable or float) –The term to multiply by.
Returns:
-
Expression–A new expression representing the product.
Examples:
__radd__(other: Expression | Variable | float) -> Expression
Add this expression to another term (right operand).
Parameters:
-
other(Expression or Variable or float) –The term to add this expression to.
Returns:
-
Expression–A new expression representing the sum.
__rsub__(other: Expression | Variable | float) -> Expression
Subtract this expression from another term (right operand).
Parameters:
-
other(Expression or Variable or float) –The term to subtract this expression from.
Returns:
-
Expression–A new expression representing the difference.
__rmul__(other: Expression | Variable | float) -> Expression
Multiply another term by this expression (right operand).
Parameters:
-
other(Expression or Variable or float) –The term to multiply by this expression.
Returns:
-
Expression–A new expression representing the product.
__iadd__(other: Expression | Variable | float) -> Self
Add another term to this expression in-place.
Parameters:
-
other(Expression or Variable or float) –The term to add.
Returns:
-
Expression–This expression modified in-place.
Examples:
__isub__(other: Expression | Variable | float) -> Self
Subtract another term from this expression in-place.
Parameters:
-
other(Expression or Variable or float) –The term to subtract.
Returns:
-
Expression–This expression modified in-place.
Examples:
__imul__(other: Expression | Variable | float) -> Self
Multiply this expression by another term in-place.
Parameters:
-
other(Expression or Variable or float) –The term to multiply by.
Returns:
-
Expression–This expression modified in-place.
Examples:
__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:
__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:
__neg__() -> Expression
__eq__(other: Expression | Variable | float) -> Constraint
Create an equality constraint.
Parameters:
-
other(Expression or Variable or float) –The right-hand side of the equality.
Returns:
-
Constraint–A constraint representing
self == other.
Examples:
__le__(other: Expression | Variable | float) -> Constraint
Create a less-than-or-equal-to constraint.
Parameters:
-
other(Expression or Variable or float) –The right-hand side of the inequality.
Returns:
-
Constraint–A constraint representing
self <= other.
Examples:
__ge__(other: Expression | Variable | float) -> Constraint
Create a greater-than-or-equal-to constraint.
Parameters:
-
other(Expression or Variable or float) –The right-hand side of the inequality.
Returns:
-
Constraint–A constraint representing
self >= other.
Examples:
__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:
Constant
Linear
Quadratic
Quadratic term in an expression.
Represents a term of the form: coefficient * var_a * var_b
Attributes:
-
var_a(Variable) –The first variable in the quadratic term.
-
var_b(Variable) –The second variable in the quadratic term.
var_a: Variable
property
var_b: Variable
property
__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:
Constant
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]
__iter__() -> ExprIter
Return the iterator object itself.