Accessing constraints from JuMP model created in function

Hello,
I have specified a function which creates a JuMP model as below. I can call the function to create the model, and subsequently can optimize! it. I wish to access the shadow prices/duals of the constraint created within the function. However, these constraints are not within the global scope and so when I try to access it, it does not work. How would i access the duals of the constraints created within the function?

Any help would be greatly appreciated. Thank you!!


function make_model(model=Model())
    @variable(model,x)
    @objective(model,Min,x^2)
    cons = []
    for a = 1:4
        c = @constraint(model, x >= a)
        push!(cons, c)
    end
    return model
end

model = Model()
set_optimizer(model,Cbc.Optimizer)
pm = make_model(model)
result = optimize!(model)
has_duals(model)
dual(cons)

Do @constraint(model, c[a=1:4], x >= a) and then access the vector of constraint references from the model with model[:c] .

2 Likes

Thank you though, I would like to nest the constrain inside a for loop as there are a few precalculation steps to actually creating the constraint. Is there a way to use the naming convention you outlined within a for loop?

cons is a local variable to make_model. You need to return it to the outer scope:

function make_model(model=Model())
    @variable(model,x)
    @objective(model,Min,x^2)
    cons = []
    for a = 1:4
        c = @constraint(model, x >= a)
        push!(cons, c)
    end
    return model, cons
end

model = Model()
set_optimizer(model,Cbc.Optimizer)
pm, cons = make_model(model)
result = optimize!(model)
has_duals(model)
dual.(cons)
2 Likes

Thank you ! That works great!