sum of array constraints
AnsweredHi
I have several array, let say
a1=np.array([1,0,0,0,0])
a2=np.array([0,1,0,0,0])
a3=np.array([0,0,1,0,0])
a4=np.array([0,0,0,0,1])
i have x a binary decision variable (x1,x2,x3,x4)
I want to create a constraint : x1*a1+x2*a2+x3*a3+x4*a4 = [1,1,0,0,0]
I can do it for each array elements (5 times), like these:
m.addConstr( x1*a1[0]+x2*a2[0]+x3*a3[0]+x4*a4[0] == 1 )
m.addConstr( x1*a1[1]+x2*a2[1]+x3*a3[1]+x4*a4[1] = 1 )
m.addConstr( x1*a1[2]+x2*a2[2]+x3*a3[2]+x4*a4[2] = 0 )
m.addConstr( x1*a1[3]+x2*a2[3]+x3*a3[3]+x4*a4[3] = 0 )
m.addConstr( x1*a1[4]+x2*a2[4]+x3*a3[4]+x4*a4[4] = 0 )
are there any other ways?
Thank you
-
Hi Muhummad,
What you have here is a standard form matrix constraint, and the ideal way to model this is to use MVars and the matrix-friendly API:
A = np.array([a1, a2, a3, a4]).transpose() # 5 rows by 4 columns
b = np.array([1, 1, 0, 0, 0]) # length 5 vector
model = gp.Model()
x = model.addMVar(4, name="x") # length 4 MVar
model.addConstr(A @ x == b) # 5 constraintsNote though that if your data has a lot of zeros, then it is best to use a scipy.sparse matrix to represent A, instead of the dense numpy format.
0
Please sign in to leave a comment.
Comments
1 comment