JuMP 0.19 create constraints iteratively

I’m new to JuMP and I’m trying to model a simple problem:

``````using JuMP, Gurobi

months = 1:12
n_months = length(months)
demands = [30, 15, 15, 25, 33, 40, 45, 45, 26, 14, 25, 30]
cap = 20

model = Model(with_optimizer(Gurobi.Optimizer))
@variable(model, 0 <= pnorm[1:n_months] <= cap, Int)
@variable(model, 0 <= pover[1:n_months] <= 0.5 * cap, Int)
@variable(model, 0 <= store[1:n_months], Int)

@constraint(model,
con_balance,
pnorm[1:n_months] + pover[1:n_months] + store[1:n_months]
.== demands[1:n_months] + store[1:n_months])
``````

except that the constraint for the first month `t = 1` is different, so it should be something like:

``````istock = 2
@constraint(model,
con_balance[1:1],
pnorm[1:1] + pover[1:1] + istock
.== demands[1:1] + store[1:1])
``````

So I tried defining the constraints iteratively by using `@constraintref` (as mentioned here: http://www.juliaopt.org/JuMP.jl/v0.13/refexpr.html#constraint-references, last block of code) and looping over the elements of the constraint array but it seems to belong to older version of JuMP only and is not available in 0.19 anymore. I can’t find the equivalent now… does anybody know how I should handle that?

Many thanks!

There are a few ways to do this. Here’s one:

``````con_balance = Dict()
con_balance[1] = @constraint(model, pnorm[1] + pover[1] + istock == demands[i] + store[i])
for i in 2:N
con_balance[i] = @constraint(model, pnorm[i] + pover[i] == demands[i] + store[i])
end
``````

If you don’t need to keep the reference to the constraint (e.g., to modify coefficients later), you can write:

``````@constraint(model, pnorm[1] + pover[1] + istock == demands[i] + store[i])
for i in 2:N
@constraint(model, pnorm[i] + pover[i] == demands[i] + store[i])
end
``````
1 Like

Wonderful, thanks, the `Dict` one is exactly what I needed, sorry if I overlooked it in the doc (I tried…).