提问人:Lino 提问时间:7/19/2023 更新时间:7/19/2023 访问量:21
TSP 求解器问题。找不到正确的行程
TSP Solver Issue. Can't find correct tour
问:
我想在给定距离矩阵的情况下求解 TSP。但是,我的代码只返回“array([0, 0, 0, 0])”,这意味着它只想留在当前位置而不离开。但我显然想以最低的成本游览所有地点。
这是我到目前为止拥有的代码:
import numpy as np
from ortools.linear_solver import pywraplp
class TSPSolver:
def __init__(self, distance_matrix, method):
self.distance_matrix = np.array(distance_matrix)
self.method = method
def solve_tsp(self):
return self.method.solve()
class TSPMethod:
def __init__(self, distance_matrix):
self.distance_matrix = np.array(distance_matrix)
def solve(self):
raise NotImplementedError("This method should be overridden in subclasses")
class FlowBasedMethod(TSPMethod):
def solve(self):
self.distance_matrix = self.distance_matrix.astype(int) # integers required by SCIP
n = self.distance_matrix.shape[0]
# Create the linear solver
solver = pywraplp.Solver.CreateSolver('SCIP')
# Create variables
x = {}
for i in range(n):
for j in range(n):
x[i, j] = solver.IntVar(0, 1, f'x_{i}_{j}')
u = [solver.IntVar(0, n, f'u_{i}') for i in range(n)]
# Constraints
for i in range(n):
solver.Add(solver.Sum(x[i, j] for j in range(n)) == 1) # each city must be departed from exactly once
solver.Add(solver.Sum(x[j, i] for j in range(n)) == 1) # each city must be visited exactly once
for i in range(1, n):
for j in range(1, n):
if i != j:
solver.Add(u[i] - u[j] + n * x[i, j] <= n - 1) # subtour elimination
# Objective function: minimize the total distance
solver.Minimize(solver.Sum(self.distance_matrix[i, j] * x[i, j] for i in range(n) for j in range(n)))
# Solve the problem
status = solver.Solve()
# If a solution was found, extract the tour
if status == pywraplp.Solver.OPTIMAL:
# Start from the first city
tour = [0]
current_city = 0
while len(tour) < n:
# Go to the next city
for j in range(n):
if x[current_city, j].solution_value() > 0.5:
tour.append(j)
current_city = j
break
return np.array(tour)
else:
print('No solution found!')
return None
distance_matrix = [
[0, 10, 15, 20],
[10, 0, 35, 25],
[15, 35, 0, 30],
[20, 25, 30, 0]
]
method = FlowBasedMethod(distance_matrix)
solver = TSPSolver(distance_matrix, method)
solver.solve_tsp()
预期输出:array([0, 1, 3, 2])
答: 暂无答案
评论