Change value of a constant in the objective function


I have a JuMP model that is being instantiated at some point of my code.

I will be running optimize!(model) several times and, for each, I would like to change the value of the coefficient given as a parameter to the create_model() function.

The following MWE is working for now, but I was wondering if there was a more efficient way (in terms of performance) to change the value of this coefficient.

using JuMP
using HiGHS

function create_model(value::Float64)
    model = Model(HiGHS.Optimizer)
    @variable(model, x[1:5] >= 5)
    @objective(model, Min, sum(x[i]*value for i in 1:5))
    return model

model = create_model(1.0)

    [MOI.ScalarCoefficientChange(MOI.VariableIndex(model[:x][i]), 2.0)
        for i in 1:5]

I thought about creating an expression @expression(model, value, 0.0) and changing its value, but could not find the documentation for it.

Does anyone know what is the best option?

Thanks in advance!

Hey @pedroripper, you’re looking for set_objective_coefficient.

See the docs:

If you’re modifying lots of coefficients, you can also just set a new objective function:

julia> using JuMP

julia> function create_model(value::Float64)
           model = Model()
           @variable(model, x[1:5])
           @objective(model, Min, sum(value * x[i] for i in 1:5))
           return model
create_model (generic function with 1 method)

julia> model = create_model(1.0);

julia> print(model)
Min x[1] + x[2] + x[3] + x[4] + x[5]
Subject to

julia> set_objective_coefficient.(model, model[:x], 2.0);

julia> print(model)
Min 2 x[1] + 2 x[2] + 2 x[3] + 2 x[4] + 2 x[5]
Subject to

julia> @objective(model, Min, sum(3.0 * model[:x][i] for i in 1:5))
3 x[1] + 3 x[2] + 3 x[3] + 3 x[4] + 3 x[5]

julia> print(model)
Min 3 x[1] + 3 x[2] + 3 x[3] + 3 x[4] + 3 x[5]
Subject to

Thank you very much!

1 Like