# Getting constraint matrix from gurobi

Is there an easy way to obtain the current constraint matrix from gurobi (or the original constraint matrix and inverse of the basis matrix) using MathOptInterface.
I have been searching google and only found how to do it with the old MathBaseInterface, which does not work with the new versions.
Would appreciate any pointers.

1 Like

Hi there,

(Iâ€™ve moved your question to the â€śOptimization (Mathematical)â€ť section.)

Unfortunately thereâ€™s no easy way to do this using MathOptInterface, because we donâ€™t represent the problem in matrix form.

You can use Gurobiâ€™s C API to achieve this, although itâ€™s a little complicated. For example, to call https://www.gurobi.com/documentation/9.5/refman/c_getbasishead.html, do:

``````using JuMP, Gurobi
model = direct_model(Gurobi.Optimizer())
# build model
grb = unsafe_backend(model)
num_constraints = ...  # Number of rows in constraint matrix
basis = Vector{Cint}(undef, num_constraints)
``````

There is a â€śprivateâ€ť function `_standard_form_matrix` (i.e. shouldnâ€™t be depended on not to change) within JuMP that may get you where you need to go:

``````using JuMP
model = Model();
@variable(model, x[1:2], lower_bound=0)
@objective(model, Min, -x[1] - x[2])
cons = @constraints(model, begin
-5x[1] + 11x[2] <= 22
4x[1] -  6x[2] <= 8
end)
print(model)

s = JuMP._standard_form_matrix(model)
keys(s)
# = (:columns, :lower, :upper, :A, :bounds, :constraints)
# Here is the docstring:
r"""
_standard_form_matrix(model::Model)

Given a problem:

r_l <= Ax <= r_u
c_l <=  x <= c_u

Return the standard form:

[A -I] [x, y] = 0
[c_l, r_l] <= [x, y] <= [c_u, r_u]

`columns` maps the variable references to column indices.
"""
A = s.A
s.lower
s.upper
#  If n is the number of variables in the original problem
# and m is the number of affine constraints in the problem. Then
m, p = size(s.A)
# where p == n + m.
n = p - m
# Hence, we can recover the "original" constraint matrix as
cA = A[:,1:n]
# and the "identity" portion as
cI = A[:,(n+1):end]
``````
1 Like

If you want a Gurobi + MathOptInterface level example, let me know, itâ€™s a bit long to post here.

1 Like

Thank you!
Is there a way to get the mapping between the indexes in Gurobi model and JuMP variables anywhere?

You can use `Gurobi.column(grb, x[1])` to retrieve the column.