I'm currently dissecting the problem's components. I'm focusing on the core challenge: crafting Python code for the Traveling Salesman Problem (TSP) utilizing a Genetic Algorithm. My immediate goal is to understand the necessary steps and functionalities.
Decomposing the Strategy
I've been drilling down on the fundamental elements necessary to solve the TSP. Specifically, the data representation within the Genetic Algorithm as well as the fitness function has been given thought. The central consideration right now is the right Crossover method. I realize the usual single-point crossover won't work because it produces invalid tours. The ordered crossover (OX) method or a related technique appears to be mandatory.
Defining Mutation Strategies
The mutation step is now clear. I've realized standard bit-flip won't cut it. Swap mutation or scramble mutation are necessary to maintain valid routes. Following that, creating the next generation from the children is the final step. I've shifted to code structure.
Formulating the Implementation
I'm now zeroing in on the coding specifics. The fitness function calculation method is now finalized: I will calculate it via cumulative sum with random.choices. I have settled on Ordered Crossover with specific steps. I've also decided on Swap mutation to keep valid routes. I've started putting together the code structure, considering numpy for calculations and matplotlib for output verification.
Outlining Core Components
I'm solidifying the fitness and evolution functions. The code structure for calculating distances using the Euclidean formula is clear, as is the fitness class. I've mapped out how the initial population, ranking, selection, mating pool, breeding (with Ordered Crossover), and mutation (with Swap) will work. I've begun to translate the logic to actual Python function stubs. My next step is assembling all these pieces into a working evolutionary loop.
Refining and Clarifying
I'm now focusing on making the code more user-friendly. I'm adding detailed comments, especially around the Ordered Crossover logic and defining key variables like population size and elite size for clarity. I'm also including a plotting function to visualize the solution. I've reviewed common TSP algorithm pitfalls, ensuring the route is circular in the distance calculations. I'm restructuring the code into classes and separate functions for readability, and optimizing it for performance.
Improving Explanations
I'm presently zeroing in on documentation, with a focus on clarifying how the Genetic Algorithm's core elements actually work. The reasoning behind the chosen crossover, Ordered Crossover, and mutation, Swap Mutation, is now being more thoroughly documented, which is crucial for future work. I want the purpose of each function to be self-evident.
Here is a complete Python implementation to solve the Traveling Salesman Problem (TSP) using a Genetic Algorithm.
This solution includes the City class, the Fitness logic, and the core Genetic Algorithm steps (Selection, Ordered Crossover, and Swap Mutation).
Prerequisites
You will need numpy and matplotlib installed to run this code:
bash
pip install numpy matplotlib
The Python Code
python
How it works:
Encoding (Representation): A "Chromosome" is a simple list of Cities (e.g., [City1, City5, City2...]). This represents the order in which the salesman visits them.
Fitness Function: We calculate total Euclidean distance. Since Genetic Algorithms usually maximize a score, our fitness is 1/distance.
Selection: We use Ranked Selection with Elitism.
Elitism: The best routes from the previous generation are copied directly to the next (prevents the best solution from accidentally mutating away).
Selection: Better routes have a higher probability of being chosen as parents.
Crossover (Mating): This is the trickiest part of TSP. We cannot use standard splitting (like merging half of parent A and half of parent B) because we might end up visiting City 1 twice and City 5 never.
We use Ordered Crossover: We take a random subset of cities from Parent A. We fill the remaining empty spots with cities from Parent B, in the order they appear in Parent B, skipping cities we already have.
Mutation: We use Swap Mutation.
We iterate through the list of cities and, with a low probability (1% in this code), swap a city with another random city in the list. This prevents the algorithm from getting stuck in local minima.
import numpy as np
import random
import operator
import pandas as pd
import matplotlib.pyplot as plt
# ------------------------------------------------
# 1. Create the City and Fitness Classes
# ------------------------------------------------
class City:
def __init__(self, x, y):
self.x = x
self.y = y
def distance(self, city):
"""Calculates Euclidean distance to another city"""
xDis = abs(self.x - city.x)
yDis = abs(self.y - city.y)
distance = np.sqrt((xDis ** 2) + (yDis ** 2))
return distance
def __repr__(self):
return f"({self.x},{self.y})"
class Fitness:
def __init__(self, route):
self.route = route
self.distance = 0
self.fitness = 0.0
def routeDistance(self):
"""Calculates total distance of the path (including return to start)"""
if self.distance == 0:
pathDistance = 0
for i in range(0, len(self.route)):
fromCity = self.route[i]
toCity = None
# Check if we are at the last city, if so connect to start
if i + 1 < len(self.route):
toCity = self.route[i + 1]
else:
toCity = self.route[0]
pathDistance += fromCity.distance(toCity)
self.distance = pathDistance
return self.distance
def routeFitness(self):
"""Fitness is inverse of distance (we want to maximize score, minimize distance)"""
if self.fitness == 0:
self.fitness = 1 / float(self.routeDistance())
return self.fitness
# ------------------------------------------------
# 2. Genetic Algorithm Core Functions
# ------------------------------------------------
def createRoute(cityList):
"""Create a random individual (route)"""
route = random.sample(cityList, len(cityList))
return route
def initialPopulation(popSize, cityList):
"""Create the starting population"""
population = []
for i in range(0, popSize):
population.append(createRoute(cityList))
return population
def rankRoutes(population):
"""Rank individuals by fitness (1/distance)"""
fitnessResults = {}
for i in range(0,len(population)):
fitnessResults[i] = Fitness(population[i]).routeFitness()
# Sort by fitness (highest first)
return sorted(fitnessResults.items(), key=operator.itemgetter(1), reverse=True)
def selection(popRanked, eliteSize):
"""
Select parents. Uses Roulette Wheel Selection but ensures
elitism (keeping the absolute best)
"""
selectionResults = []
df = pd.DataFrame(np.array(popRanked), columns=["Index","Fitness"])
df['cum_sum'] = df.Fitness.cumsum()
df['cum_perc'] = 100*df.cum_sum/df.Fitness.sum()
# Elitism: Keep the best 'eliteSize' routes automatically
for i in range(0, eliteSize):
selectionResults.append(popRanked[i][0])
# Roulette Wheel Selection for the rest
for i in range(0, len(popRanked) - eliteSize):
pick = 100*random.random()
for i in range(0, len(popRanked)):
if pick <= df.iat[i,3]:
selectionResults.append(popRanked[i][0])
break
return selectionResults
def matingPool(population, selectionResults):
pool = []
for i in range(0, len(selectionResults)):
index = selectionResults[i]
pool.append(population[index])
return pool
def breed(parent1, parent2):
"""
Ordered Crossover.
Standard crossover doesn't work for TSP because it creates duplicates.
This method takes a slice from parent1 and fills gaps with parent2.
"""
child = []
childP1 = []
childP2 = []
geneA = int(random.random() * len(parent1))
geneB = int(random.random() * len(parent1))
startGene = min(geneA, geneB)
endGene = max(geneA, geneB)
# Get genes from Parent 1
for i in range(startGene, endGene):
childP1.append(parent1[i])
# Get genes from Parent 2 (if they are not already in childP1)
childP2 = [item for item in parent2 if item not in childP1]
child = childP1 + childP2
return child
def breedPopulation(matingpool, eliteSize):
children = []
length = len(matingpool) - eliteSize
pool = random.sample(matingpool, len(matingpool))
# Elitism: Keep best parents
for i in range(0,eliteSize):
children.append(matingpool[i])
# Breed the rest
for i in range(0, length):
child = breed(pool[i], pool[len(matingpool)-i-1])
children.append(child)
return children
def mutate(individual, mutationRate):
"""
Swap Mutation.
Swaps two cities in the route with a low probability.
"""
for swapped in range(len(individual)):
if(random.random() < mutationRate):
swapWith = int(random.random() * len(individual))
city1 = individual[swapped]
city2 = individual[swapWith]
individual[swapped] = city2
individual[swapWith] = city1
return individual
def mutatePopulation(population, mutationRate):
mutatedPop = []
for ind in range(0, len(population)):
mutatedInd = mutate(population[ind], mutationRate)
mutatedPop.append(mutatedInd)
return mutatedPop
def nextGeneration(currentGen, eliteSize, mutationRate):
popRanked = rankRoutes(currentGen)
selectionResults = selection(popRanked, eliteSize)
matingpool = matingPool(currentGen, selectionResults)
children = breedPopulation(matingpool, eliteSize)
nextGeneration = mutatePopulation(children, mutationRate)
return nextGeneration
# ------------------------------------------------
# 3. Main Execution Function
# ------------------------------------------------
def geneticAlgorithm(population, popSize, eliteSize, mutationRate, generations):
"""Run the full GA loop"""
print("Initializing population...")
pop = initialPopulation(popSize, population)
print("Initial distance: " + str(1 / rankRoutes(pop)[0][1]))
progress = []
progress.append(1 / rankRoutes(pop)[0][1])
for i in range(0, generations):
pop = nextGeneration(pop, eliteSize, mutationRate)
# Optional: Print progress every 50 generations
if (i + 1) % 50 == 0:
dist = 1 / rankRoutes(pop)[0][1]
print(f"Generation {i+1} Distance: {dist:.2f}")
progress.append(dist)
print("Final distance: " + str(1 / rankRoutes(pop)[0][1]))
bestRouteIndex = rankRoutes(pop)[0][0]
bestRoute = pop[bestRouteIndex]
return bestRoute, progress
# ------------------------------------------------
# 4. Run and Visualize
# ------------------------------------------------
if __name__ == "__main__":
# 1. Setup Data (Random list of Cities)
cityList = []
# Create 25 random cities
for i in range(0, 25):
cityList.append(City(x=int(random.random() * 200), y=int(random.random() * 200)))
# 2. Run Algorithm
# popSize: Number of routes per generation
# eliteSize: Number of best routes kept automatically
# mutationRate: Probability of swapping cities
# generations: How many iterations
bestRoute, progress = geneticAlgorithm(population=cityList,
popSize=100,
eliteSize=20,
mutationRate=0.01,
generations=500)
# 3. Plotting Results
# Plot the Improvement over time
plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.plot(progress)
plt.ylabel('Distance')
plt.xlabel('Generations (x50)')
plt.title('Optimization Progress')
# Plot the Best Route found
x_coords = [city.x for city in bestRoute]
y_coords = [city.y for city in bestRoute]
# Connect back to start to visualize loop
x_coords.append(bestRoute[0].x)
y_coords.append(bestRoute[0].y)
plt.subplot(1, 2, 2)
plt.plot(x_coords, y_coords, 'o-r')
plt.title('Best Route Found')
plt.show()