I am experiencing slowness using for loop within addConstrs method. The python code is as followed:
from gurobipy import Model, quicksum, GRB
import numpy as np
m = Model('sparse_decision_variables')
num_dim1 = 100
num_dim2 = 200
num_constraints = 1000
feasible_arcs = [(i, j) for i in range(num_dim1) for j in range(num_dim2) if i + j % 5 != 3]
A = np.random.rand(num_dim2, num_constraints)
rhs = np.random.rand(num_constraints, 1)
# decision variable x is a sparse 10 * 10 matrix (addMVar doesnt support adding variables from list)
x = m.addVars(feasible_arcs, vtype=GRB.BINARY, name="x")
m.addConstrs((((quicksum(x[i, j] * A[j, k] for i, j in feasible_arcs)) <= rhs[k]) for k in range(num_constraints)), name='slow_constraint' )
Suppose a and b are the number of rows and columns of decision variable x, c is the size of rhs (number of constraints). For clearity, we use @ to represent matrix multiplication and * to represent element wise multiplication.
In this example, a = 100, b=200, c=1000
In matrix form, x @ A has dimension a*c (x is a a * b matrix and A is a b * c matrix). The constraint basically wants to express row sum of x@ A <= rhs. MATLAB allows to add constraints like one vector containing decision variables is less than another vector. But in python gurobi API, all I know is to loop over each element in the vector (for k in range(num_constraints)).
We have already tried:
m.addConstrs((((quicksum(x[i, j] * A[j, :] for i, j in feasible_arcs)) >= rhs)), name='slow_constraint' )
m.addConstrs((((np.dot(x[i, j] , A[j, :] for i, j in feasible_arcs)) >= rhs)), name='slow_constraint' )
But neither worked.
Could anyone propose an idea to efficiently add this type of constraints? Thanks
Please sign in to leave a comment.