def tsp_path_planning(points): # TSP路径规划 n = len(points) dist_matrix = cdist(points, points) mst = minimum_spanning_tree(csr_matrix(dist_matrix)).toarray() graph = Graph() for i in range(n): graph.add_node(i) for i in range(n): for j in range(i+1, n): if mst[i, j] != 0: graph.add_edge(i, j, weight=dist_matrix[i, j]) vertex_cover = min_weighted_vertex_cover(graph, weight='weight') odd_vertices = list(vertex_cover) odd_edges = np.zeros((len(vertex_cover), 2)) k = 0 for i in range(n): if i in odd_vertices: odd_edges[k, 0] = i k += 1 closed_tour = np.array(list(vertex_cover) + [vertex_cover[0]]) for i in range(0, len(odd_edges), 2): u, v = int(odd_edges[i, 0]), int(odd_edges[i+1, 0]) min_dist, min_j = np.inf, -1 for j in range(n): if j not in odd_vertices: dist = dist_matrix[u, j] + dist_matrix[v, j] if dist < min_dist: min_dist, min_j = dist, j closed_tour = np.insert(closed_tour, np.where(closed_tour == u)[0][0]+1, min_j) closed_tour = np.insert(closed_tour, np.where(closed_tour == v)[0][0]+1, min_j) odd_vertices.remove(u) odd_vertices.remove(v) return closed_tour这个函数貌似没有删除重复的顶点
时间: 2024-01-19 20:04:46 浏览: 222
是的,你说得没错。这个函数确实没有删除重复的顶点,因为它是用于求解TSP路径规划的,而TSP路径规划中需要经过所有的顶点,因此不需要删除重复的顶点。另外,由于TSP问题是NP问题,没有一种简单的算法可以在多项式时间内求解,因此很多TSP路径规划算法都是近似算法或者启发式算法,而不是精确算法,因此允许一定的误差和重复顶点。
相关问题
以下代码有什么问题def cal_total_distance(routine): '''The objective function. input routine, return total distance. cal_total_distance(np.arange(num_points)) ''' num_points, = routine.shape return sum([distance_matrix[routine[i % num_points], routine[(i + 1) % num_points]] for i in range(num_points)]) # 蚁群算法 from sko.ACA import ACA_TSP aca = ACA_TSP(func=cal_total_distance, n_dim=num_points, size_pop=50, max_iter=200, distance_matrix=distance_matrix) best_x, best_y = aca.run() fig, ax = plt.subplots(1, 2) best_points_ = np.concatenate([best_x, [best_x[0]]]) best_points_coordinate = points_coordinate[best_points_, :] ax[0].plot(best_points_coordinate[:, 0], best_points_coordinate[:, 1], 'o-r') pd.DataFrame(aca.y_best_history).cummin().plot(ax=ax[1]) plt.show() print(best_points_) print(best_y)
这段代码有两个问题:
1. 在函数 `cal_total_distance` 中,变量 `num_points` 没有定义,应该在调用该函数之前定义该变量。
2. 在代码中缺少必要的库导入,如 `numpy` 和 `matplotlib` 库,需要在代码开头导入这些库。
下面是修改后的代码:
```python
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
def cal_total_distance(routine, distance_matrix, num_points):
'''The objective function. input routine, return total distance.
cal_total_distance(np.arange(num_points), distance_matrix, num_points)
'''
return sum([distance_matrix[routine[i % num_points], routine[(i + 1) % num_points]] for i in range(num_points)])
# 蚁群算法
from sko.ACA import ACA_TSP
num_points = 10
distance_matrix = np.random.rand(num_points, num_points)
aca = ACA_TSP(func=cal_total_distance, n_dim=num_points, distance_matrix=distance_matrix,
size_pop=50, max_iter=200)
best_x, best_y = aca.run()
fig, ax = plt.subplots(1, 2)
best_points_ = np.concatenate([best_x, [best_x[0]]])
best_points_coordinate = points_coordinate[best_points_, :]
ax[0].plot(best_points_coordinate[:, 0], best_points_coordinate[:, 1], 'o-r')
pd.DataFrame(aca.y_best_history).cummin().plot(ax=ax[1])
plt.show()
print(best_points_)
print(best_y)
```
import numpy as np import cv2 # Load image img = cv2.imread("input.jpg") # Convert to grayscale gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Detect edges edges = cv2.Canny(gray, 100, 200) # Display image with edges cv2.imshow("Image with Edges", edges) # Select edge points using a mouse click points = [] def select_point(event, x, y, flags, param): if event == cv2.EVENT_LBUTTONDOWN: points.append((x, y)) cv2.namedWindow("Select Points") cv2.setMouseCallback("Select Points", select_point) while True: cv2.imshow("Select Points", img) key = cv2.waitKey(1) if key == ord("q"): break # Generate TSP art and tsplib dataset n = len(points) distances = np.zeros((n, n)) for i in range(n): for j in range(n): if i != j: distances[i][j] = np.sqrt((points[i][0] - points[j][0]) ** 2 + (points[i][1] - points[j][1]) ** 2) # Write tsplib dataset with open("output.tsp", "w") as f: f.write("NAME: output\n") f.write("TYPE: TSP\n") f.write("DIMENSION: {}\n".format(n)) f.write("EDGE_WEIGHT_TYPE: EUC_2D\n") f.write("NODE_COORD_SECTION\n") for i in range(n): f.write("{} {} {}\n".format(i+1, points[i][0], points[i][1])) f.write("EOF\n") # Display TSP art tsp_art = np.zeros_like(gray) path = list(range(n)) + [0] for i in range(n): cv2.line(tsp_art, points[path[i]], points[path[i+1]], (255, 255, 255), thickness=1) cv2.imshow("TSP Art", tsp_art) cv2.waitKey(0) cv2.destroyAllWindows()
这段代码使用了 OpenCV 库来生成一个 TSP 艺术图,并生成一个 tsplib 数据集。具体步骤如下:
1. 加载一张图片并将其转换为灰度图像。
2. 使用 Canny 边缘检测算法检测图像的边缘。
3. 使用鼠标点击来选择边缘上的点。
4. 计算这些点之间的距离,并生成一个 tsplib 数据集。
5. 使用路径规划算法生成一个 TSP 艺术图。
其中,路径规划算法使用的是一个简单的贪心算法,即依次连接相邻的点。
阅读全文