我需要为 ACO TSP 的以下解决方案绘制图形。我需要绘制的图形将与此接近:
我可以处理的任何代码片段?
从tsplib95的文档中:
Converting problems get_graph() creates a networkx.Graph instance from the problem data: >>> G = problem.get_graph() >>> G.nodes NodeView((1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16))
所以,G 是一个networkx
图形,这意味着你可以用networkx
它来绘制它:
import matplotlib.pyplot as plt
import networkx as nx
nx.draw_networkx(G)
plt.show()
编辑:绘制路径:
pos = nx.spring_layout(G)
H = nx.DiGraph(G) # convert to directed graph s.t. the edges have arrows.
nx.draw_networkx_nodes(H, pos=pos) # draw nodes
nx.draw_networkx_edges(H, pos=pos, alpha=0.1) # draw all edges with transparency
nx.draw_networkx_edges(H, pos=pos, edgelist=tour.path, edge_color='red') # highlight the edges in the path
plt.show()
然后是否可以绘制游览,即 G 的完成版本(将算法应用于 G 以获得最短距离)?
大概。您可以尝试使用 type(tour) 来查看 Tour 的数据类型吗?
游览属于 'acopy.solvers.Solution' 类。我还可以使用 tour.nodes 和 tour.path 获取游览节点和路径。
@pepegaClap 查看我的编辑
代码似乎有效,但没有输出图形