Parameters in a JuMP model

I am new to Julia and uses JuMP to model optimizations problems. I am trying to model a problem with parameters that I could change. I didn’t how to do this and don’t know if it is actually possible to do.

More concretely, what I would want to do is something like this, although the example is quite dumb.

``````using JuMP
using HiGHS

p = [1 2];
model = Model(HiGHS.Optimizer);
@variable(model, x1);
@variable(model, x2);
@constraint(model, c1, x1 == p[1]);
@constraint(model, c2, x2 == p[2]);
@objective(model, Min, x1+x2);
optimize!(model)
``````

This will solve \min_{x_1,x_2} x_1+x_2 such that x_1 =1 and x_2 = 2. Currently, when the following code is

``````p = [2 4];
optimize!(model)
``````

it still solve the same problem as above. What I would want is to solve now is \min_{x_1,x_2} x_1+x_2 such that x_1 =2 and x_2 = 4.

Is there a way to do that?

1 Like

Welcome! Once you create the model, the values of `p[1]` and `p[2]` are linked to that model (as far as I know). Thus, changing these values afterwards without updating the model will have no effect. You could do it in a loop, e.g.,

``````P = [[1 2], [2 4]]
for p in P
model = Model(HiGHS.Optimizer);
@variable(model, x1);
@variable(model, x2);
@constraint(model, c1, x1 == p[1]);
@constraint(model, c2, x2 == p[2]);
@objective(model, Min, x1+x2);
optimize!(model)
println("objective: ", objective_value(model))
print(model)
end
``````

or with a function taking your parameters as argument, e.g.,

``````function build_model(p)
model = Model(HiGHS.Optimizer);
@variable(model, x1);
@variable(model, x2);
@constraint(model, c1, x1 == p[1]);
@constraint(model, c2, x2 == p[2]);
@objective(model, Min, x1+x2);
return model
end

P = [[1 2], [2 4]]
for p in P
model = build_model(p)
optimize!(model)
println("objective: ", objective_value(model))
end
``````

There is probably a more efficient way (with respect to performance) to do that, but I do not know.

2 Likes

There are a bunch of ways you can modify a JuMP model. For this particular example, take a look at

There are also a bunch of tutorials which demonstrate how to optimize over parameters:

As a rule of thumb, @mike_k’s approach of creating a function and optimizing is a great place to start. In most cases, it is “fast enough” and it’s simple to mix a whole bunch of different parameters and modifications. But modifying the problem in-place can be a lot faster, particularly for bigger models.

2 Likes

Both work well for me. Thanks for the solutions and welcome.

1 Like