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, 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)
GRBgetBasisHead(grb, basis)

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

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

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
#  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.