Python Gurobi 中线性规划的解决方案不可行

Solution not Feasible in Linear Programming in Python Gurobi

这是 的延续。我在 Python 中使用 Gurobi 编写 MILP,其中 objective 是为了最大化奖励,同时确保不违反距离约束。

但是我得到解决方案是不可行的。我尝试了 IIS,但它仍然没有帮助,因为它只显示了被违反的约束,而不是解决方案。

import random
import gurobipy as grb
import math

n = 4
Distance = 50000000

def distance(points, i, j):
  dx = points[i][0] - points[j][0]
  dy = points[i][1] - points[j][1]
  return math.sqrt(dx*dx + dy*dy)

random.seed(1)
points = []
for i in range(n):
  points.append((random.randint(0,100),random.randint(0,100)))
opt_model = grb.Model(name="MILP Model")

# <= Variables
x_vars = {}
for i in range(n):
   for j in range(n):
     x_vars[i,j] = opt_model.addVar(vtype=grb.GRB.BINARY,
                          name='e'+str(i)+'_'+str(j))
u={}
for i in range(1,n):
    u[i]=opt_model.addVar(vtype=grb.GRB.INTEGER,
                          name='e'+str(i))

# <= Constraint (Mandatory Edges and excluding vertexes) Eq(1)

opt_model.addConstr((grb.quicksum(x_vars[1,j] for j in range(1,n)))  == 1)
opt_model.addConstr((grb.quicksum(x_vars[i,n-1] for i in range(n-1)))  == 1)
opt_model.addConstr((grb.quicksum(x_vars[i,i] for i in range(n-1)))  == 0)
# <= Constraint (Distance) Eq(3)

for i in range(n-1):
  opt_model.addConstr(grb.quicksum(x_vars[i,j]*distance(points, i, j) for j in range(1,n)) <= Distance)

# <= Constraint (Equality & Single edge in and out) Eq(2)

for k in range(1, n-1):
  opt_model.addConstr(grb.quicksum(x_vars[i,k] for i in range(n-1))
                      == grb.quicksum(x_vars[k,j] for j in range(1, n)) <=1)

# <= Constraint (Subtour elimination) Eq(4) Eq(5)

for i in range(1,n):
  opt_model.addConstr(2 <= u[i] <= n)

for i in range(1,n):
    for j in range(1,n):
        opt_model.addConstr((u[i] - u[j] +1 <= (n-1)*(1-x_vars[j,i])))

# <= objective (maximize) Eq(1)

objective = grb.quicksum(x_vars[i,j]
                         for i in range(1, n-1)
                         for j in range(1, n))

opt_model.ModelSense = grb.GRB.MAXIMIZE
opt_model.setObjective(objective)
opt_model.update()
solution = opt_model.getAttr('x', x_vars )
print solution


更新后忘记调用优化函数

opt_model.ModelSense = grb.GRB.MAXIMIZE
opt_model.setObjective(objective)
opt_model.optimize()