python gurobi_在Python Gurobi中的线性编程中不可行的解决方案

This is continuation of this thread. I am coding MILP using Gurobi in Python where the objective is to maximize the rewards while ensuring the distance constraint is not violated.

I am however getting solution is infeasible. I tried the IIS but it still didnt help because it only shows the constraint that is being violated but not the solution.

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

解决方案

You forgot to call the optimize function after update

opt_model.ModelSense = grb.GRB.MAXIMIZE

opt_model.setObjective(objective)

opt_model.optimize()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值