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.

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.

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.