简体   繁体   English

在旅行商问题 (TSP) 中为 scipy.optimize.linprog Python function 定义线性规划约束

[英]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:更新:

  • No bounds: some variables eaqual to 2, null function无界:一些变量等于2,null function
  • Bounds: 'bounds = [(0, 1)] * n' returns ValueError: Invalid input for linprog: unable to interpret bounds with this dimension tuple: (10, 2). Bounds: 'bounds = [(0, 1)] * n' 返回 ValueError: Invalid input for linprog: unable to interpret bounds with this dimension tuple: (10, 2)。
  • Correct bounds: 'bounds = [(0, 1)] * (n*n)', variables equal to 1 or 0 but still null function + it seems only the diagonal (eg variables (i,j) = (0,0), (1,1)...) is equal to 1正确的边界:'bounds = [(0, 1)] * (n*n)',变量等于 1 或 0 但仍然是 null function + 似乎只有对角线(例如变量 (i,j) = (0,0 ), (1,1)...) 等于 1

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM