Gurobi: get LHS (left-hand side) of a constraint

Viewed 433

As written HERE (or HERE), one can get the sense (<, =, >) and the RHS (right-hand side) of a constraint like this:

for cnstr in model.getConstrs():
    print(cnstr.sense, cnstr.rhs)

How can one get the coefficients in a constraint? I checked the attributes of variables and models, but found nothing of the sort.

2 Answers

Okay, it seems that one way is using the Model.getCoeff() function:

for cnstr in pre.getConstrs():
    for var in pre.getVars():
        print(pre.getCoeff(cnstr, var), end=" ")

The best way to do this is to walk the object from the LHS. Assuming your model consists of only linear constraints, this looks like the following:

for cnstr in model.getConstrs():
  print("Constraint %s: sense %s, RHS=%f" % (cnstr.ConstrName, cnstr.Sense, cnstr.RHS))
  row = model.getRow(cnstr)
  for k in range(row.size()):
    print("Variable %s, coefficient %f" % (row.getVar(k).VarName, row.getCoeff(k))

You can also adapt this for quadratic constraints.

Related