Skip to content

Objective

Bases: Expression

The objective for an optimization model.

Examples:

An Objective is automatically created when an Expression is assigned to .minimize or .maximize

>>> m = pf.Model()
>>> m.A, m.B = pf.Variable(lb=0), pf.Variable(lb=0)
>>> m.con = m.A + m.B <= 10
>>> m.maximize = 2 * m.B + 4
>>> m.maximize
<Objective terms=2 type=linear>
2 B +4

The objective value can be retrieved with from the solver once the model is solved using .value.

>>> m.optimize()
>>> m.maximize.value
24.0

Objectives support += and -= operators.

>>> m.maximize += 3 * m.A
>>> m.optimize()
>>> m.A.solution, m.B.solution
(10.0, 0.0)
>>> m.maximize -= 2 * m.A
>>> m.optimize()
>>> m.A.solution, m.B.solution
(0.0, 10.0)

Objectives cannot be created from dimensioned expressions since an objective must be a single expression.

>>> m = pf.Model()
>>> m.dimensioned_variable = pf.Variable(
...     {"city": ["Toronto", "Berlin", "Paris"]}
... )
>>> m.maximize = m.dimensioned_variable
Traceback (most recent call last):
...
ValueError: Objective cannot be created from a dimensioned expression. Did you forget to use .sum()?

Objectives cannot be overwritten.

>>> m = pf.Model()
>>> m.A = pf.Variable(lb=0)
>>> m.maximize = 2 * m.A
>>> m.maximize = 3 * m.A
Traceback (most recent call last):
...
ValueError: An objective already exists. Use += or -= to modify it.

Attributes:

Name Type Description
value float

The value of the objective function (only available after solving the model).

Source code in pyoframe/_objective.py
def __init__(self, expr: Operable, _constructive: bool = False) -> None:
    self._constructive = _constructive
    if isinstance(expr, (int, float)):
        expr = Expression.constant(expr)
    else:
        expr = expr.to_expr()
    super().__init__(expr.data, name="objective")
    self._model = expr._model
    if self.dimensions is not None:
        raise ValueError(
            "Objective cannot be created from a dimensioned expression. Did you forget to use .sum()?"
        )

value: float

The value of the objective function (only available after solving the model).

This value is obtained by directly querying the solver.