How to get/set constraint names?

Hi, I am trying to set and get constraint names but am running into some errors. I originally built the model without naming the constraints but now I want to name them. Take for example,

for i in 1:timerange
    @constraint(m, cost[i,1] == s[i,1] * price[i])
end

Then I tried to name it with

for i in 1:timerange
    @constraint(m, con[i], cost[i,1] == s[i,1] * price[i])
end

but I got

LoadError: An object of name con is already attached to this model. If this is intended, consider using the anonymous construction syntax, e.g., x = @variable(model, [1:N], …) where the name of the object does not appear inside the macro.

This error happens no matter what I name the variable. However when I do constraint_by_name(m,“con[1]”) it actually shows the constraint correctly… Is there a way to conveniently name all the constraints without causing the error?

See https://jump.dev/JuMP.jl/stable/constraints/#Constraint-names-1

for i in 1:timerange
    c = @constraint(m, cost[i,1] == s[i,1] * price[i])
    set_name(c, "my_constraint_$(i)")
end

# or 

@constraint(m, con[i=1:timerange], cost[i,1] == s[i,1] * price[i])
# effectively equivalent to
con = [
    @constriant(m, cost[i,1] == s[i,1] * price[i])
    for i in 1:timerange
]
for i in 1:timerange
    set_name(con[i], "con[$i]")
end
2 Likes

Thanks that worked. Is there a way to get all of the constraints in the entire model at once and put them into an array and/or name them?

See https://jump.dev/JuMP.jl/stable/constraints/#Accessing-constraints-from-a-model-1

I did see that before. I guess I could loop through each constraint type then. Another question if you don’t mind: when I get an optimal solution I get as part of the output “User MIP start violates constraint R0 by 10000.000000000” but when I try constraint_by_name(m, “R0”) it does nothing. Is there any way to find which constraint R0 is?