Defining constraint over dense and sparse constraint

Hi! I have a question regarding the definition of constraints including both dense and sparse variables. In the example below, I am trying to define the constraint x_{ij} + y_{ij} \leq 0 \quad \forall \quad i \in \mathcal{M},j \in \mathcal{N}. However, we know from the data_matrix that some y_{ij} are automatically forced to be zero. I know that I would be able to define the variable y over all indices of both sets and fix the zero valued entries using fix function as described in the docs. However, if I define the variables as I have done below, what is the best way to write the constraint without having to use if-else blocks to determine which y_{ij} entries are nonzero?

using JuMP

M = 5
N = 3
data_matrix = rand((0,1),(M,N))
M_set = 1:M
N_set = 1:N

model = Model()

@variable(model, y[i = M_set, j = N_set; data_matrix[i,j] > 0])
@variable(model, x[i = M_set, j = N_set])

# write constraint x[i,j] + y[i,j] <= 0

for i in M_set, j in N_set
    if haskey(y, (i,j))
        @constraint(model, x[i,j] + y[i,j] <= 0)
    else
        @constraint(model, x[i,j] <= 0)
    end
end
print(model)

Hi @danrib07,

This might give you some ideas:

using JuMP

M, N = 5, 3
data_matrix = rand(Bool, (M, N))

model = Model()
@variable(model, x[i in 1:M, j in 1:N])
@variable(model, y[i in 1:M, j in 1:N; data_matrix[i,j]])

# Option 1
for i in 1:M, j in 1:N
    @constraint(model, x[i,j] + (data_matrix[i,j] ? y[i,j] : 0) <= 0)
end

# Option 2
@constraint(model, [i in 1:M, j in 1:N; data_matrix[i,j]], x[i,j] + y[i,j] <= 0)
@constraint(model, [i in 1:M, j in 1:N; !data_matrix[i,j]], x[i,j] <= 0)

Thank you!

1 Like