Julia JuMP model scope

I want to define a function that creates a JuMP model that then calls a function to add a set of additional constraints to that model. That set of constraints would be the same across a number of different models.

The following example gives the error: “VariableNotOwned{VariableRef}(x): the variable x cannot be used in this model because it belongs to a different model.”

function f()
    m = Model(Gurobi.Optimizer)
    @variable(m, x ≥ 0)
    @objective(m, Min, 5*x)
    g(m)
    return m
end
function g(m)
    @constraint(m, eqcon, 2*x-3 == 0)
    return m
end
mod = f()

The following modification works, but seems a bit tedious for large numbers of variables. Is there a better way to do this?

function g(m)
    @constraint(m, eqcon, 2*m[:x]-3 == 0)
    return m
end

You can “index” a JuMP model to pull out the variable ref:

function g(m)
    x = m[:x]
    @constraint(m, eqcon, 2*x-3 == 0)
    return m
end

[EDIT]: sorry, I did not see the bottom “The following modification works…”

1 Like

Hi @cby, take a read of this tutorial: Design patterns for larger models · JuMP

Another approach would be

function f()
    model = Model(Gurobi.Optimizer)
    @variable(model, x >= 0)
    @objective(model, Min, 5 * x)
    g(model, x)
    return model
end
function g(model, x)
    @constraint(model, eqcon, 2 * x - 3 == 0)
    return model
end
mod = f()