52 lines
1.6 KiB
Python
52 lines
1.6 KiB
Python
![]() |
import os
|
||
|
import matplotlib.pyplot as plt
|
||
|
|
||
|
def read_tsp_file(file_path):
|
||
|
cities = []
|
||
|
with open(file_path, 'r') as f:
|
||
|
reading_coords = False
|
||
|
for line in f:
|
||
|
if line.strip() == 'NODE_COORD_SECTION':
|
||
|
reading_coords = True
|
||
|
continue
|
||
|
if line.strip() == 'EOF':
|
||
|
break
|
||
|
if reading_coords:
|
||
|
parts = line.strip().split()
|
||
|
if len(parts) == 3:
|
||
|
index, x, y = int(parts[0]), float(parts[1]), float(parts[2])
|
||
|
cities.append((index, x, y))
|
||
|
return cities
|
||
|
|
||
|
def plot_tsp_data(data_dir):
|
||
|
# 获取所有TSP文件
|
||
|
tsp_files = [f for f in os.listdir(data_dir) if f.endswith('.tsp')]
|
||
|
n_files = len(tsp_files)
|
||
|
|
||
|
# 创建子图
|
||
|
fig = plt.figure(figsize=(15, 5 * ((n_files + 2) // 3)))
|
||
|
|
||
|
for i, tsp_file in enumerate(tsp_files, 1):
|
||
|
# 读取TSP文件数据
|
||
|
cities = read_tsp_file(os.path.join(data_dir, tsp_file))
|
||
|
|
||
|
# 创建子图
|
||
|
ax = fig.add_subplot(((n_files + 2) // 3), 3, i)
|
||
|
|
||
|
# 绘制城市点
|
||
|
for index, x, y in cities:
|
||
|
ax.scatter(x, y, c='blue', s=50)
|
||
|
ax.annotate(f'{index}', (x, y), xytext=(5, 5), textcoords='offset points')
|
||
|
|
||
|
# 设置标题和标签
|
||
|
ax.set_title(f'TSP Problem: {tsp_file}')
|
||
|
ax.set_xlabel('X Coordinate')
|
||
|
ax.set_ylabel('Y Coordinate')
|
||
|
ax.grid(True)
|
||
|
|
||
|
plt.tight_layout()
|
||
|
plt.show()
|
||
|
|
||
|
if __name__ == '__main__':
|
||
|
data_dir = 'data'
|
||
|
plot_tsp_data(data_dir)
|