plot_tsp.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. """
  2. ==========================
  3. Traveling Salesman Problem
  4. ==========================
  5. This is an example of a drawing solution of the traveling salesman problem
  6. The function is used to produce the solution is christofides,
  7. where given a set of nodes, it calculates the route of the nodes
  8. that the traveler has to follow in order to minimize the total cost.
  9. """
  10. import matplotlib.pyplot as plt
  11. import networkx as nx
  12. import networkx.algorithms.approximation as nx_app
  13. import math
  14. G = nx.random_geometric_graph(20, radius=0.4, seed=3)
  15. pos = nx.get_node_attributes(G, "pos")
  16. # Depot should be at (0,0)
  17. pos[0] = (0.5, 0.5)
  18. H = G.copy()
  19. # Calculating the distances between the nodes as edge's weight.
  20. for i in range(len(pos)):
  21. for j in range(i + 1, len(pos)):
  22. dist = math.hypot(pos[i][0] - pos[j][0], pos[i][1] - pos[j][1])
  23. dist = dist
  24. G.add_edge(i, j, weight=dist)
  25. cycle = nx_app.christofides(G, weight="weight")
  26. edge_list = list(nx.utils.pairwise(cycle))
  27. # Draw closest edges on each node only
  28. nx.draw_networkx_edges(H, pos, edge_color="blue", width=0.5)
  29. # Draw the route
  30. nx.draw_networkx(
  31. G,
  32. pos,
  33. with_labels=True,
  34. edgelist=edge_list,
  35. edge_color="red",
  36. node_size=200,
  37. width=3,
  38. )
  39. print("The route of the traveller is:", cycle)
  40. plt.show()