当模型给出不可行的解决方案时获得约束的解决方案

时间:2016-11-21 16:24:05

标签: python-2.7 optimization gurobi

我正在编写优化问题。该模型提供了不可行的解决方案。我想检查哪个约束给出了不可行的解决方案。到目前为止,我已经在网上查了一下,但还是没能找到问题的解决方案。谁能帮我?例如:在下面的代码中,由于约束3模型是不可行的。我如何从解决方案中确定它?感谢

from gurobipy import *

# Create a new model
m = Model("mip1")

# Create variables
x1 = m.addVar(vtype=GRB.INTEGER, name="x1")
x2 = m.addVar(vtype=GRB.INTEGER, name="x2")


# Integrate new variables
m.update()

# Set objective
m.setObjective(7*x1 + 2*x2, GRB.MAXIMIZE)


m.addConstr(-x1 + 2 * x2 <= 4, "constraint-0")


m.addConstr(5*x1 + x2 <= 20, "constraint-1")
m.addConstr(-2*x1 -2*x2 <= -7, "constraint-2")
m.addConstr(x1 <= -2, "constraint-3")
m.addConstr(x2 <= 4, "constraint-4")

m.optimize()

for v in m.getVars():
    print('%s %g' % (v.varName, v.x))

print('Obj: %g' % m.objVal)

1 个答案:

答案 0 :(得分:1)

一个例子:

&#13;
&#13;
from gurobipy import *

# Create a new model
m = Model("mip1")
# Create variables
x1= m.addVar(lb=0,ub=62,vtype=GRB.INTEGER,name="x1")
x2 = m.addVar(lb=0,ub=50, vtype=GRB.INTEGER,name="x2")
m.update()

m.addConstr(-x1 + 2*x2 <= 4, "constraint-0")
m.addConstr(5*x1 + x2 <= 20, "constraint-1")
m.addConstr(-2*x1 -2*x2 <= -25, "constraint-2")
m.addConstr(x1 <= 2, "constraint-3")
#m.addConstr(x2 <= 50, "constraint-4")

m.update()

# Set objective
m.setObjective(7*x1 + 2*x2, GRB.MAXIMIZE)
m.update()

m.optimize()

status = m.status
if status == GRB.Status.OPTIMAL:
    for v in m.getVars():
        print('%s %g' % (v.varName, v.x))
    print('Obj: %g' % m.objVal)
       
elif status == GRB.Status.INFEASIBLE:
    print('Optimization was stopped with status %d' % status)
    # do IIS
    m.computeIIS()
    for c in m.getConstrs():
        if c.IISConstr:
            print('%s' % c.constrName)
&#13;
&#13;
&#13;