Global constraints in functions

Hi,

I declared some constraints in a function because I needed an if condition, and wanted to know if I can somehow make these constraints defined outside the function as well. Here’s part of the function:

function amortization(z)
	if z == 0
          @constraints(m, begin
		       int[t = 1:T], γ[t] == k * ( δ0 - (t-1) * A )
		       pay[t = 1:T], δ[t] == A + γ[t]
           end)

So in this case, is there any way to edit this so that int and pay can be referred to, outside the function?

Thanks!

return int, pay?

3 Likes

I’m getting an error

 UndefVarError: pay not defined

See the JuMP documentation:
http://www.juliaopt.org/JuMP.jl/v0.19.2/variables/#What-is-a-JuMP-variable?-1
http://www.juliaopt.org/JuMP.jl/v0.19.2/constraints/
You can query named variables and constraints using a symbol.

You can do this:

function add_variable(model)
    @variable(model, x)
end

function add_constraint(model)
    x = model[:x]
    @constraint(model, con, 2 * x <= 1)
end

model = Model()
add_variable(model)
add_constraint(model)
x = model[:x]
con = model[:con]

Or

function add_constraint(model, x)
    @constraint(model, con, 2 * x <= 1)
    return con
end

model = Model()
@variable(model, x)
con = add_constraint(model, x)
1 Like

Thank you, that helped!

Just a quick question, would this method work for multiple constraints? Thanks

Yes.

function foo(model)
    @variable(model, x[i=1:2])
    @constraint(model, con[i=1:2], x[i] <= 2)
end

model = Model()
foo(model)
x = model[:x]
con = model[:con]

x[1]
con[2]
1 Like

Awesome, thanks!