JuMP: how to find which constraints a variable appears in

I am using JuMP to formulate a large optimization problem. Is there any function which allows me to see all constraints in which a specific variable appears? Or if I have the reference to a specific constraint, is there a method for me to check whether or not a certain variable appears in that constraint?

So if I have:

using JuMP 
model = Model()
@variable(model, x[1:3])
my_constraint = @constraint(model, x[1] + x[2] >= 0)

I am looking for a function that I could ask if x[1] appears in my_constraint, and have it return true.

1 Like

Is there any function which allows me to see all constraints in which a specific variable appears?

There isn’t explicitly in JuMP for this, but if your constraints are linear, then one option is this:

julia> function in_constraint(constraint, variable)
           object = constraint_object(constraint)
           return !iszero(coefficient(object.func, variable))
       end
in_constraint (generic function with 1 method)

julia> in_constraint(my_constraint, x[1])
true

julia> in_constraint(my_constraint, x[2])
true

julia> in_constraint(my_constraint, x[3])
false
1 Like

OK, thank you, that’s very helpful! I have both linear and nonlinear constraints, but I realized the variable I’m interested in only appears in the linear constraints, so this will work great. (I did realize I could also just check for that variable as I’m formulating constraints and save the references to those constraints, but I was hoping for a method that wouldn’t require adding that additional code to the source, but rather to examine the model after it’s complete. So this is just what I was looking for.) Thanks!

1 Like