# Constraint¶

class optlang.interface.Constraint(expression, lb=None, ub=None, indicator_variable=None, active_when=1, *args, **kwargs)[source]

Bases: optlang.interface.OptimizationExpression

Constraint objects represent the mathematical (in-)equalities that constrain an optimization problem. A constraint is formulated by a symbolic expression of variables and a lower and/or upper bound. Equality constraints can be formulated by setting the upper and lower bounds to the same value.

Some solvers support indicator variables. This lets a binary variable act as a switch that decides whether the constraint should be active (cannot be violated) or inactive (can be violated).

The constraint expression can be an arbitrary combination of variables, however the individual solvers have limits to the forms of constraints they allow. Most solvers only allow linear constraints, meaning that the expression should be of the form a * var1 + b * var2 + c * var3 ...

Examples

>>> expr = 2.4 * var1 - 3.8 * var2
>>> c1 = Constraint(expr, lb=0, ub=10)

>>> indicator_var = Variable("var3", type="binary") # Only possible with some solvers
>>> c2 = Constraint(var2, lb=0, ub=0, indicator_variable=indicator_var, active_when=1) # When the indicator is 1, var2 is constrained to be 0


Attributes

 expression: sympy The mathematical expression defining the constraint. name: str, optional The constraint’s name. lb: float or None, optional The lower bound, if None then -inf. ub: float or None, optional The upper bound, if None then inf. indicator_variable: Variable The indicator variable (needs to be binary). active_when: 0 or 1 (default 0) When the constraint should problem: Model or None, optional A reference to the optimization model the variable belongs to.

Methods

active_when

Activity relation of constraint to indicator variable (if supported).

classmethod clone(constraint, model=None, **kwargs)[source]

Make a copy of another constraint. The constraint being copied can be of the same type or belong to a different solver interface.

Parameters: constraint: interface.Constraint (or subclass) The constraint to copy model: Model or None The variables of the new constraint will be taken from this model. If None, new variables will be constructed.
dual

Dual of constraint (None if no solution exists).

classmethod from_json(json_obj, variables=None)[source]

Constructs a Variable from the provided json-object.

indicator_variable

The indicator variable of constraint (if available).

lb

Lower bound of constraint.

primal

Primal of constraint (None if no solution exists).

to_json()[source]

Returns a json-compatible object from the constraint that can be saved using the json module.

ub

Upper bound of constraint.