Get restrictions in matrix format from gurobipy

I encoded my model in gurobipy and I want to get a constraint matrix and a cost vector. Is there any way to access them?

+4
source share
1 answer

There is no single function in the python API to get matrix coefficients from the Gurobi model, but it is not difficult to write it yourself.

It’s convenient to have lists of your variables and constraints. If you have a gurobi model in a variablem

dvars = m.getVars()
constrs = m.getConstrs()

. m.getAttr , . , "Obj"

obj_coeffs = m.getAttr('Obj', dvars)

. , , . COOrdinate

variable constraint python Gurobi . ,

var_index = {v: i for i, v in enumerate(dvars)}
constr_index= {c: i for i, c in enumerate(constrs)}

constrs . - - sense (< =, ==, > =) -

. LinExpr, getRow . Gurobi 6.x, , ,

def get_expr_coos(expr, var_indices):
    for i in range(expr.size()):
        dvar = expr.getVar(i)
        yield expr.getCoeff(i), var_indices[dvar]

, .

def get_matrix_coo(m):
    dvars = m.getVars()
    constrs = m.getConstrs()
    var_indices = {v: i for i, v in enumerate(dvars)}
    for row_idx, constr in enumerate(constrs):
        for coeff, col_idx in get_expr_cos(m.getRow(constr), var_indices):
            yield row_idx, col_idx, coeff

, , ​​ pandas dataframe

 nzs = pd.DataFrame(get_matrix_coos(m), 
                    columns=['row_idx', 'col_idx', 'coeff'])

. miplib aflow40b.

 import matplotlib.pyplot as plt
 import pandas as pd
 import gurobipy as grb
 m = grb.read("miplib/instances/miplib2010/aflow40b.mps.gz")
 nzs = pd.DataFrame(get_matrix_coo(m), 
                    columns=['row_idx', 'col_idx', 'coeff'])
 plt.scatter(nzs.col_idx, nzs.row_idx, 
        marker='.', lw=0)

aflow nonzeros

+10

Source: https://habr.com/ru/post/1649466/


All Articles