Objectives

This page describes macros and functions related to linear and quadratic objective functions only, unless otherwise indicated. For nonlinear objective functions, see Nonlinear Modeling.

Set a linear objective

Use the @objective macro to set a linear objective function.

Use Min to create a minimization objective:

julia> @objective(model, Min, 2x + 1)
2 x + 1

Use Max to create a maximization objective:

julia> @objective(model, Max, 2x + 1)
2 x + 1

Set a quadratic objective

Use the @objective macro to set a quadratic objective function.

Use ^2 to have a variable squared:

julia> @objective(model, Min, x^2 + 2x + 1)
x² + 2 x + 1

You can also have bilinear terms between variables:

julia> @variable(model, x)
x

julia> @variable(model, y)
y

julia> @objective(model, Max, x * y + x + y)
x*y + x + y

Query the objective function

Use objective_function to return the current objective function.

julia> @objective(model, Min, 2x + 1)
2 x + 1

julia> objective_function(model)
2 x + 1

Query the objective sense

Use objective_sense to return the current objective sense.

julia> @objective(model, Min, 2x + 1)
2 x + 1

julia> objective_sense(model)
MIN_SENSE::OptimizationSense = 0

Modify an objective

To modify an objective, call @objective with the new objective function.

julia> @objective(model, Min, 2x)
2 x

julia> @objective(model, Max, -2x)
-2 x

Alternatively, use set_objective_function.

julia> @objective(model, Min, 2x)
2 x

julia> new_objective = @expression(model, -2 * x)
-2 x

julia> set_objective_function(model, new_objective)

Modify an objective coefficient

Use set_objective_coefficient to modify an objective coefficient.

julia> @objective(model, Min, 2x)
2 x

julia> set_objective_coefficient(model, x, 3)

julia> objective_function(model)
3 x
Info

There is no way to modify the coefficient of a quadratic term. Set a new objective instead.

Modify the objective sense

Use set_objective_sense to modify the objective sense.

julia> @objective(model, Min, 2x)
2 x

julia> objective_sense(model)
MIN_SENSE::OptimizationSense = 0

julia> set_objective_sense(model, MOI.MAX_SENSE);

julia> objective_sense(model)
MAX_SENSE::OptimizationSense = 1

Alternatively, call @objective and pass the existing objective function.

julia> @objective(model, Min, 2x)
2 x

julia> @objective(model, Max, objective_function(model))
2 x