The conflict of variables using @build_constraint

Hi,
If there are two models in my code

model1=Model()
@variable(model1,x[1:5])
model2=Model()
@variable(model2,x[1:5])

If I use
con=@build_constraint(x[1]<=1)
the x[1] belongs to model1 or model2?
Thanks in advance!

If I use con=@build_constraint(x[1]<=1) the x[1] belongs to model1 or model2 ?

It depends on when you call it. There is nothing special about x things that JuMP macros create; they are regular Julia variables (sometimes called bindings to make clear they are not optimization variables) that can be overwritten.

The JuMP documentation explains this.

In your example:

model1=Model()
@variable(model1,x[1:5])

# `x` is a binding to the vector of variables `model1[:x]`

model2=Model()
@variable(model2,x[1:5])

# Now `x` is a binding to the vector of variables `model2[:x]`

ok, I have still some confusion. my model is something like this,

model1=Model()
@variable(model1,x)
@constraint(model1,x<=5)
function lazy_constraints(cb_data)
     model2=Model()
     @variable=(model2,x<=5)
     @optimize!(model2)
     Judge = has_values(model2)
     if Judge == false
           con=build_constraint(x<=2)
     end
end

so constraint x<=2 is added in model1 or model2

Your code is not valid, so I’m not sure what you’re trying to do. Please make a reproducible example:

In your function x <= 2 refers to the x binding created by model2. if you want x from model1, call the inner x something different so the binding doesn’t get over-written, or use model1[:x].

1 Like

Thank you @odow. I have understood, just now I have misunderstood the meaning you say.

MOI.submit(model1, MOI.LazyConstraint(cb_data), con), if I use this code, it can also assign con to model1?

it can also assign con to model1 ?

Only if it refers to variables in model1.

I guess you want something like

model1 = Model()
@variable(model1, x <= 5)
function lazy_constraints(cb_data)
    model2 = Model()
    @variable(model2, x <= 5)
    optimize!(model2)
    Judge = has_values(model2)
    if Judge == false
        con = @build_constraint(model1[:x] <= 2)
        MOI.submit(model1, MOI.LazyConstraint(cb_data), con)
    end
    return
end
1 Like

Thank you for your kindly help, I have understood. It is what I want to express.