gpt4 book ai didi

python-2.7 - 当模型给出不可行解时获取约束解

转载 作者:行者123 更新时间:2023-12-02 04:03:35 24 4
gpt4 key购买 nike

我正在编写一个优化问题。该模型给出了不可行的解决方案。我想检查哪个约束给出了不可行的解决方案。到目前为止,我已经在网上查过,但还没有找到问题的解决方案。谁能帮我?例如:在下面的代码中,由于约束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)

最佳答案

一个例子:

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)

关于python-2.7 - 当模型给出不可行解时获取约束解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40724776/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com