[英]Defining the linear programming constraints in the Traveling Salesman Problem (TSP) for the scipy.optimize.linprog Python function
I am trying to solve the Linear Programming formulation of the Traveling Salesman Problem (TSP) using scipy.optimize.linprog in Python .我正在尝试使用Python 中的 scipy.optimize.linprog解决旅行商问题 (TSP)的线性规划公式。
This document clearly defines the problem and, though I understand the idea, I can't figure out how to translate it into the required parameters. This document清楚地定义了问题,虽然我理解这个想法,但我无法弄清楚如何将其转换为所需的参数。
I've already flattened the distance matrix, so the function should be fine.我已经展平了距离矩阵,所以 function 应该没问题。 What about the constraint matrix and constraint vector?
约束矩阵和约束向量呢?
I've tried this...我试过这个...
n = len(d)
TSP_c = [d[i][j] for i in range(n) for j in range(n)]
E = [(i,j) for i in range(len(d)) for j in range(len(d))]
TSP_A = [[1 if k in (i, j) else 0 for (i, j) in E] for k in range(n)]
TSP_b = [2] * n
TSP_res = linprog(TSP_c, TSP_A, TSP_b, bounds = bounds, method = 'simplex')
TSP_res
...in an attempt to reproduce this example (I don't know how to use panda by the way). ...试图重现这个例子(顺便说一句,我不知道如何使用熊猫)。
Updates:更新:
This works:这有效:
d = [[distance_ij(coord_rad,i,j) for j in range(len(coord_rad))] for i in range(len(coord_rad))]
n = len(d)
E = [[i, j] for i in range(n) for j in range(n)]
TSP_A_eq = []
for k in range(n) :
TSP_A_eq.append([1 if i == k and k != j else 0 for [i, j] in E]) # somme des arêtes sortantes
TSP_A_eq.append([1 if k == j and i != k else 0 for [i, j] in E]) # somme des arêtes rentrantes
for i in range(n) :
TSP_A_eq.append([1 if i == j else 0 for [i, j] in E]) # pas d'arête (i, i)
TSP_c = [d[i][j] for [i, j] in E]
TSP_b_eq = [1] * (2 * n) + [0] * n
bounds = [(0, 1)] * (n * n)
TSP_res = linprog(c=TSP_c, A_eq=TSP_A_eq, b_eq=TSP_b_eq, bounds=bounds, method='simplex', integrality=1)
Then there are the subtour elimination constraints...然后是subtour消除约束......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.