A solver independent library for modeling optimization problems.
Example use to model the optimization problem:
max 2.0 * x + y
s.t. x + y <= 1.5
x in {0.0, 1.0}
y in [0.0, 2.5]
model = mathopt.Model(name='my_model')
x = model.add_binary_variable(name='x')
y = model.add_variable(lb=0.0, ub=2.5, name='y')
# We can directly use linear combinations of variables ...
model.add_linear_constraint(x + y <= 1.5, name='c')
# ... or build them incrementally.
objective_expression = 0
objective_expression += 2 * x
objective_expression += y
model.maximize(objective_expression)
# May raise a RuntimeError on invalid input or internal solver errors.
result = mathopt.solve(model, mathopt.SolverType.GSCIP)
if result.termination.reason not in (mathopt.TerminationReason.OPTIMAL,
mathopt.TerminationReason.FEASIBLE):
raise RuntimeError(f'model failed to solve: {result.termination}')
print(f'Objective value: {result.objective_value()}')
print(f'Value for variable x: {result.variable_values()[x]}')
Converts a linear constraint to a NormalizedLinearInequality.
The simplest way to specify the constraint is by passing a one-sided or
two-sided linear inequality as in:
* as_normalized_linear_inequality(x + y + 1.0 <= 2.0),
* as_normalized_linear_inequality(x + y >= 2.0), or
* as_normalized_linear_inequality((1.0 <= x + y) <= 2.0).
Note the extra parenthesis for two-sided linear inequalities, which is
required due to some language limitations (see
https://peps.python.org/pep-0335/ and https://peps.python.org/pep-0535/).
If the parenthesis are omitted, a TypeError will be raised explaining the
issue (if this error was not raised the first inequality would have been
silently ignored because of the noted language limitations).
The second way to specify the constraint is by setting lb, ub, and/o expr as
in:
* as_normalized_linear_inequality(expr=x + y + 1.0, ub=2.0),
* as_normalized_linear_inequality(expr=x + y, lb=2.0),
* as_normalized_linear_inequality(expr=x + y, lb=1.0, ub=2.0), or
* as_normalized_linear_inequality(lb=1.0).
Omitting lb is equivalent to setting it to -math.inf and omiting ub is
equivalent to setting it to math.inf.
These two alternatives are exclusive and a combined call like:
* as_normalized_linear_inequality(x + y <= 2.0, lb=1.0), or
* as_normalized_linear_inequality(x + y <= 2.0, ub=math.inf)
will raise a ValueError. A ValueError is also raised if expr's offset is
infinite.
Args:
bounded_expr: a linear inequality describing the constraint. Cannot be
specified together with lb, ub, or expr.
lb: The constraint's lower bound if bounded_expr is omitted (if both
bounder_expr and lb are omitted, the lower bound is -math.inf).
ub: The constraint's upper bound if bounded_expr is omitted (if both
bounder_expr and ub are omitted, the upper bound is math.inf).
expr: The constraint's linear expression if bounded_expr is omitted.
Returns:
A NormalizedLinearInequality representing the linear constraint.
Definition at line 2188 of file model.py.