manbet体育手机客户端


tsp.py.


#!/ usr / bin / python#版权所有2019,guro狗万app足彩bi优化,llc#使用延迟约束解决了一组随机生成的#积分的旅行推销员问题。基础MIP模型仅包括#'度-2'约束,要求每个节点恰好#两个事件边缘。此模型的解决方案可能包含子台楼 - #旅游,不会访问每个城市。延迟约束回调#添加新的约束来关闭它们。导入系统导入数学导入数学导入随机导入itertools从gurobipy导入*#呼叫 - 使用延迟约束来消除子旅行def子学课程(模型,where):如果其中== grb.callback.mipsol:#在其中选择了一个边缘solution vals = model.cbgetsolution(model._vars)被选中= tuplelist((i,j)为i,j在model._vars.keys()如果Vals [i,j]> 0.5)#查找所选的最短周期边缘列表Tour = Subtour(选定)如果Len(Tour) len(本循环):cycle = thiscycle返回周期#解析参数如果len(sys.argv)<2:print('用法:tsp.py npoints')出口(1)n = int(sys.argv [1])#创建n个随机点.seyed(1)点= [(random.randint(0,100),irand.randint(0,100))在范围内(n)]#每对点之间的欧几里德距离字典dist = {(i,j):math.sqrt(sum((point [i] [k] -ppoints [j] [k])** 2为k in range(2))) for i in range(n) for j in range(i)} m = Model() # Create variables vars = m.addVars(dist.keys(), obj=dist, vtype=GRB.BINARY, name='e') for i,j in vars.keys(): vars[j,i] = vars[i,j] # edge in opposite direction # You could use Python looping constructs and m.addVar() to create # these decision variables instead. The following would be equivalent # to the preceding m.addVars() call... # # vars = tupledict() # for i,j in dist.keys(): # vars[i,j] = m.addVar(obj=dist[i,j], vtype=GRB.BINARY, # name='e[%d,%d]'%(i,j)) # Add degree-2 constraint m.addConstrs(vars.sum(i,'*') == 2 for i in range(n)) # Using Python looping constructs, the preceding would be... # # for i in range(n): # m.addConstr(sum(vars[i,j] for j in range(n)) == 2) # Optimize model m._vars = vars m.Params.lazyConstraints = 1 m.optimize(subtourelim) vals = m.getAttr('x', vars) selected = tuplelist((i,j) for i,j in vals.keys() if vals[i,j] > 0.5) tour = subtour(selected) assert len(tour) == n print('') print('Optimal tour: %s' % str(tour)) print('Optimal cost: %g' % m.objVal) print('')