import numpy as np
import random
import operator
import matplotlib.pyplot as plt
"""
Genetic Algorithm components:
1. Representation: A list of city indices representing a route.
2. Fitness: Inverse of total route distance (1/distance).
3. Selection: Tournament selection.
4. Crossover: Ordered Crossover (OX1) to preserve valid permutations.
5. Mutation: Swap mutation.
"""
class City:
def __init__(self, x, y):
self.x = x
self.y = y
def distance(self, 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 "(" + str(self.x) + "," + str(self.y) + ")"
class Fitness:
def __init__(self, route):
self.route = route
self.distance = 0
self.fitness = 0.0
def routeDistance(self):
if self.distance == 0:
pathDistance = 0
for i in range(0, len(self.route)):
fromCity = self.route[i]
toCity = None
if i + 1 < len(self.route):
toCity = self.route[i + 1]
else:
toCity = self.route[0] # Return to start
pathDistance += fromCity.distance(toCity)
self.distance = pathDistance
return self.distance
def routeFitness(self):
if self.fitness == 0:
self.fitness = 1 / float(self.routeDistance())
return self.fitness
# --- GA Operations ---
def createRoute(cityList):
route = random.sample(cityList, len(cityList))
return route
def initialPopulation(popSize, cityList):
population = []
for i in range(0, popSize):
population.append(createRoute(cityList))
return population
def rankRoutes(population):
fitnessResults = {}
for i in range(0, len(population)):
fitnessResults[i] = Fitness(population[i]).routeFitness()
return sorted(fitnessResults.items(), key=operator.itemgetter(1), reverse=True)
def selection(popRanked, eliteSize):
selectionResults = []
# Convert fitness to cumulative probability (Roulette Wheel)
df = pd.DataFrame(popRanked, columns=["Index", "Fitness"])
df['cum_sum'] = df.Fitness.cumsum()
df['cum_perc'] = 100 * df.cum_sum / df.Fitness.sum()
for i in range(0, eliteSize):
selectionResults.append(popRanked[i][0]) # Keep the best ones
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):
matingpool = []
for i in range(0, len(selectionResults)):
index = selectionResults[i]
matingpool.append(population[index])
return matingpool
def breed(parent1, parent2):
"""
Ordered Crossover (OX1)
We take a random subset from P1 and fill the remaining gaps with P2's order.
"""
child = []
childP1 = []
childP2 = []
geneA = int(random.random() * len(parent1))
geneB = int(random.random() * len(parent1))
startGene = min(geneA, geneB)
endGene = max(geneA, geneB)
for i in range(startGene, endGene):
childP1.append(parent1[i])
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 the best routes directly
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: Swap two cities in the route.
"""
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
# --- Main Loop ---
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
def geneticAlgorithm(population, popSize, eliteSize, mutationRate, generations):
pop = initialPopulation(popSize, population)
progress = []
# Calculate initial distance
initialDistance = 1 / rankRoutes(pop)[0][1]
print(f"Initial Distance: {initialDistance}")
progress.append(initialDistance)
for i in range(0, generations):
pop = nextGeneration(pop, eliteSize, mutationRate)
bestRouteIndex = rankRoutes(pop)[0][1]
bestDistance = 1 / bestRouteIndex
progress.append(bestDistance)
# Optional: Print progress every 50 generations
if i % 50 == 0:
print(f"Generation {i}: {bestDistance}")
bestRouteIndex = rankRoutes(pop)[0][0]
bestRoute = pop[bestRouteIndex]
print(f"Final Distance: {1 / rankRoutes(pop)[0][1]}")
return bestRoute, progress
# --- Execution ---
if __name__ == "__main__":
# 1. Setup Data (Pandas is often used here, but we can use simple lists for selection logic)
# We need pandas DataFrame for the simple 'selection' function logic above used in Roulette Wheel
try:
import pandas as pd
except ImportError:
print("Pandas is required for the selection logic demonstration. Installing...")
import subprocess
subprocess.check_call(['pip', 'install', 'pandas'])
import pandas as pd
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 GA
bestRoute, progress = geneticAlgorithm(population=cityList, popSize=100, eliteSize=20, mutationRate=0.01, generations=500)
# 3. Plot Progress
plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.plot(progress)
plt.ylabel('Distance')
plt.xlabel('Generation')
plt.title('TSP GA Optimization Progress')
# 4. Plot Route
plt.subplot(1, 2, 2)
x_coords = [city.x for city in bestRoute] + [bestRoute[0].x]
y_coords = [city.y for city in bestRoute] + [bestRoute[0].y]
plt.scatter([c.x for c in cityList], [c.y for c in cityList], color='red', zorder=2)
plt.plot(x_coords, y_coords, zorder=1)
plt.title('Optimized Route')
plt.tight_layout()
plt.show()