<jupyter_start><jupyter_text>Ant Colony Optimization for the Traveling Salesman ProblemImporting modules:- **pants** - ant colony optimization algorithms- **numpy** - powerful N-dimensional array manipulation- **matplotlib** - ploing library<jupyter_code>from math import sqrt, pow
import random

import pants as ants
import matplotlib.pyplot as plt
import numpy as np
euclidean = lambda a, b: sqrt(pow(a[1] - b[1], 2) + pow(a[0] - b[0], 2))<jupyter_output><empty_output><jupyter_text>Generating random nodes (10x2 array with random numbers from 0 to 10)<jupyter_code>nodes = [[random.uniform(0, 10), random.uniform(0, 10)] for _ in range(10)]
nodes<jupyter_output><empty_output><jupyter_text>Initializing world<jupyter_code>world = ants.World(nodes, euclidean)
acoSolver = ants.Solver()<jupyter_output><empty_output><jupyter_text>Calculating the shortest possible route that visits each nodes exactly once<jupyter_code>solution = acoSolver.solve(world)<jupyter_output><empty_output><jupyter_text>Plotting nodes chart<jupyter_code>plt.style.use('ggplot')

coords = np.array(nodes)
plt.plot(coords[:,0], coords[:,1], 'r.')
plt.xticks(np.arange(0, 11, 1.0))
plt.yticks(np.arange(1, 11, 1.0))
plt.ylabel('y')
plt.xlabel('x')
plt.show()<jupyter_output><empty_output><jupyter_text>Plotting the shortest route chart<jupyter_code>shortest_route_coords = np.array(solution.tour)
shortest_route_coords
first_visited_node = coords[solution.start]
plt.plot(first_visited_node[0], first_visited_node[1], 'go')
plt.plot(coords[:,0], coords[:,1], 'r.')
plt.plot(shortest_route_coords[:,0], shortest_route_coords[:,1], 'b')
plt.xticks(np.arange(0, 11, 1.0))
plt.yticks(np.arange(1, 11, 1.0))
plt.ylabel('y')
plt.xlabel('x')
plt.show()

first_visited_node
solution.distance
solution.tour<jupyter_output><empty_output>
StarcoderdataJupyterStructuredCleanDedup