How to set constraints in gurobipy given numpy matrix
AnsweredI'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.
-
Official comment
This post is more than two years old. Some information may not be up to date. For current information, please check the Gurobi Documentation or Knowledge Base. If you need more help, please create a new post in the community forum, or try Gurobot, our chatbot interface offering instant, expert-level support. -
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
Post is closed for comments.
Comments
2 comments