I coded my model in gurobipy and I want to get the matrix of constraints and vector of cost. Is there any way to access those?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
Cannot comment on the answer of @david-nehme due to insufficient reputation, feel free to add this to his answer and delete mine.
Since Gurobi 9.0 you can query the coefficient matrix via
.getA()
as a<class 'scipy.sparse.csr.csr_matrix'>
.Also check out matrix plots using betterspy.
From the python API, there's no single function to get the matrix coefficients from a Gurobi model, but it's not to hard to write one yourself.
It is convenient to have lists of your variables and constraints. If you have a gurobi model in variable
m
will give you the list of variables and constraints. You can then use m.getAttr to retrieve attributes related to the variables. To obtain the objective function coefficients, you query the 'Obj' attribute
This will give you a list of the objective coefficient for each variable in the model. For the constraint matrix, you likely want to store just the nonzeros. I'll just store them in the COOrdinate format
In this example, it is convenient to have the index of each variable and constraint object. I'll just create dictionaries that map the objects to the indices
Each constraint object in the
constrs
list corresponds to a constraint in the model. Each constraint has aFor the constraint matrix, you need only the left hand side. It is represented by a LinExpr object which you can obtain with the getRow method on the model. As of Gurobi 6.x, obtaining a list of column index, coefficient tuples requires a function like the following
To get the matrix, you need to apply this function for every constraint.
Using this function, you can store the matrix into a structure like a pandas dataframe
From this structure, you can do a basic plot of the nonzero pattern. Using a problem from the miplib aflow40b benchmark problem.