How to set constraints in gurobipy given numpy matrix
回答済みI'm a beginner and I'm having trouble adding constraints to my model.
I created my model:
primal = gb.Model("Primal")
then I added my variables:
xVar = primal.addVars(numxVar, vtype=GRB.CONTINUOUS, name = "x")
I set my objective function:
primal.setObjective(xVar.sum(), GRB.MINIMIZE)
and finally I want to add my constraints; I have a numpy.matrix and I want to add more constraints, each of which is obtained by multiplying a row of the matrix with the vector of variables (my constraints are B*x >= d):
npMatB = np.matrix(B).transpose()
nonNeg = primal.addConstrs((xVar[i] >= 0 for i in range(numxVar)), name = "nonNeg")
demands = primal.addConstrs((xVar.prod(npMatB[i, :]) > listOfDemand[i]) for i in range(len(listOfDemand)))
but this code doens't work correctly and it gives me back
TypeError: tupledict.prod requires a dictionary
now, I've understood that the problem is that I can't use the numpy matrix in that way, but I can't figure out how to do what I want to do.
-
Hi Fabiano,
Ad described in the documentation of the tupledict.prod method, the coefficients have to be provided by a Python dictionary. Thus, you have to somehow convert the matrix slice into a fitting dictionary. A probably easier way is to just loop over the rows
m.addConstrs((gb.quicksum(x[j] * B[i,j] for j in range(numxVar)) >= listOfDemand[i]) for i in range(len(listOfDemand)))
Please also note that strict inequalities are not supported by Gurobi.
Best regards,
Jaromił0
サインインしてコメントを残してください。
コメント
1件のコメント