I would like to access the slack variables that are added with range
constraints using the Python interface of Gurobi.
Consider the following example program:
import gurobipy as gp
m = gp.Model("rangetest")
x1 = m.addVar(0.0, 1.0, 1.0, gp.GRB.CONTINUOUS, "x1")
x2 = m.addVar(0.0, 1.0, 1.0, gp.GRB.CONTINUOUS, "x2")
m.update()
m.addRange(gp.LinExpr([1.0, 2.0], [x1, x2]), 1.0, 2.0, "r1")
m.optimize()
print
for v in m.getVars():
print v.VarName, v.X, v.RC
print
for c in m.getConstrs():
print c.ConstrName, c.Pi
r = m.getRow(c);
Note that after the call to Model.addRange(), the model has 3
variables. But the list returned by Model.getVars() only contains the
first two variables x1 and x2. Does anybody know how to access the
third (slack) variable?
Another (maybe unrelated) observation is that the last line in the
script above errors out with the following error message:
Traceback (most recent call last):
File "rangetest.py", line 20, in <module>
r = m.getRow(c);
File "model.pxi", line 1485, in gurobipy.Model.getRow (../../src/
python/gurobipy.c:24851)
File "model.pxi", line 151, in gurobipy.Model.__getVar (../../src/
python/gurobipy.c:14484)
IndexError: list index out of range
Am I using this in a wrong way?
Best regards,
Markus
In the meantime, you can reformulate your range constraints by adding an extra variable with fixed bounds. In your example, replace your range constraint:
1 <= x1 + 2 x2 <= 2
by:
x1 + 2 x2 - r = 0
and set lower and upper bounds of 1 and 2 on r, respectively.