Certainly! Let's tackle a classic optimization problem using a Genetic Algorithm (GA) in Python.
Problem: Traveling Salesman Problem (TSP)
Problem Description:
The Traveling Salesman Problem is a well-known optimization problem where a salesman needs to visit a set of cities exactly once and return to the starting city, minimizing the total travel distance. The challenge lies in determining the most efficient route, especially as the number of cities increases.
Why Use a Genetic Algorithm?
Genetic Algorithms are inspired by the process of natural selection and are particularly effective for solving combinatorial optimization problems like TSP. They work well because they can explore a large search space efficiently, avoid getting trapped in local minima, and provide good approximations to optimal solutions within reasonable timeframes.
Implementation Overview:
We'll implement the Genetic Algorithm with the following components:
- Representation (Chromosome): Each route is represented as a sequence of city indices.
- Initial Population: A set of randomly generated routes.
- Fitness Function: inverse of the total distance of the route (shorter routes have higher fitness).
- Selection: Roulette Wheel Selection based on fitness scores.
- Crossover: Ordered Crossover (OX) to combine two parent routes.
- Mutation: Swap Mutation to introduce variability.
- Termination: After a fixed number of generations or when convergence is reached.
Python Implementation:
import random
import numpy as np
import matplotlib.pyplot as plt
# -----------------------
# Problem Setup
# -----------------------
class City:
def __init__(self, x, y):
self.x = x
self.y = y
def distance_to(self, other):
"""Calculate Euclidean distance to another city."""
return np.hypot(self.x - other.x, self.y - other.y)
def __repr__(self):
return f"City({self.x}, {self.y})"
def create_cities(num_cities, width=100, height=100):
"""Generate a list of cities with random coordinates."""
return [City(random.uniform(0, width), random.uniform(0, height)) for _ in range(num_cities)]
# -----------------------
# Genetic Algorithm Components
# -----------------------
def total_distance(route):
"""Calculate the total distance of the route."""
distance = 0
for i in range(len(route)):
from_city = route[i]
to_city = route[(i + 1) % len(route)] # Ensure loop back to start
distance += from_city.distance_to(to_city)
return distance
def fitness(route):
"""Fitness function: inverse of total distance."""
return 1 / total_distance(route)
def initial_population(pop_size, cities):
"""Generate initial population with random routes."""
population = []
for _ in range(pop_size):
route = cities.copy()
random.shuffle(route)
population.append(route)
return population
def roulette_wheel_selection(population, fitnesses):
"""Select a parent using roulette wheel selection."""
total_fitness = sum(fitnesses)
pick = random.uniform(0, total_fitness)
current = 0
for route, fit in zip(population, fitnesses):
current += fit
if current > pick:
return route
return population[-1]
def ordered_crossover(parent1, parent2):
"""Perform ordered crossover (OX) between two parents."""
start, end = sorted(random.sample(range(len(parent1)), 2))
child_p1 = parent1[start:end]
child_p2 = [city for city in parent2 if city not in child_p1]
child = child_p2[:start] + child_p1 + child_p2[start:]
return child
def swap_mutation(route, mutation_rate):
"""Perform swap mutation on a route."""
for swapped in range(len(route)):
if random.random() < mutation_rate:
swap_with = random.randint(0, len(route) - 1)
route[swapped], route[swap_with] = route[swap_with], route[swapped]
return route
# -----------------------
# Genetic Algorithm
# -----------------------
def genetic_algorithm(cities, pop_size=100, generations=500, mutation_rate=0.01):
"""Run the Genetic Algorithm to solve TSP."""
population = initial_population(pop_size, cities)
best_route = None
best_distance = float('inf')
history = []
for gen in range(generations):
# Calculate fitness for the population
fitnesses = [fitness(route) for route in population]
# Find the best route in the current generation
current_best_fitness = max(fitnesses)
current_best_route = population[fitnesses.index(current_best_fitness)]
current_best_distance = total_distance(current_best_route)
if current_best_distance < best_distance:
best_distance = current_best_distance
best_route = current_best_route
print(f"Generation {gen}: Best Distance = {best_distance:.2f}")
history.append(best_distance)
# Create new population
new_population = []
for _ in range(pop_size):
# Selection
parent1 = roulette_wheel_selection(population, fitnesses)
parent2 = roulette_wheel_selection(population, fitnesses)
# Crossover
child = ordered_crossover(parent1, parent2)
# Mutation
child = swap_mutation(child, mutation_rate)
new_population.append(child)
population = new_population
return best_route, history
# -----------------------
# Visualization
# -----------------------
def plot_route(route, title='Best Route'):
"""Plot the route on a 2D plane."""
x = [city.x for city in route] + [route[0].x]
y = [city.y for city in route] + [route[0].y]
plt.figure(figsize=(10, 6))
plt.plot(x, y, 'o-', color='blue', markersize=5)
plt.title(title)
plt.xlabel('X Coordinate')
plt.ylabel('Y Coordinate')
plt.grid(True)
plt.show()
def plot_history(history):
"""Plot the history of best distances over generations."""
plt.figure(figsize=(10, 6))
plt.plot(history, color='red')
plt.title('Best Distance Over Generations')
plt.xlabel('Generation')
plt.ylabel('Distance')
plt.grid(True)
plt.show()
# -----------------------
# Main Execution
# -----------------------
if __name__ == "__main__":
# Parameters
NUM_CITIES = 20
POPULATION_SIZE = 200
GENERATIONS = 1000
MUTATION_RATE = 0.02
# Create cities
cities = create_cities(NUM_CITIES)
# Run Genetic Algorithm
best_route, history = genetic_algorithm(
cities,
pop_size=POPULATION_SIZE,
generations=GENERATIONS,
mutation_rate=MUTATION_RATE
)
# Display Results
print(f"\nBest route found has distance: {total_distance(best_route):.2f}")
plot_route(best_route, title='Best Route Found by Genetic Algorithm')
plot_history(history)
Explanation of the Code:
-
City Representation:
- The
City class represents a city with x and y coordinates.
- It includes a method
distance_to to calculate the Euclidean distance to another city.
-
Population Initialization:
- The
initial_population function creates a list of random routes (routes are permutations of cities).
-
Fitness Evaluation:
- The
fitness function calculates the inverse of the total distance of a route. This ensures that shorter routes have higher fitness.
-
Selection:
roulette_wheel_selection selects a parent route based on their fitness proportionate probabilities.
-
Crossover:
ordered_crossover combines two parent routes to produce a child route, preserving the sequence of cities.
-
Mutation:
swap_mutation introduces variability by swapping two cities in the route with a certain mutation rate.
-
Genetic Algorithm Loop:
- The
genetic_algorithm function runs the GA for a specified number of generations, continuously evolving the population by selection, crossover, and mutation.
- It keeps track of the best route found and logs the progress.
-
Visualization:
plot_route visualizes the best route on a 2D plot.
plot_history shows how the best distance evolves over generations.
-
Execution:
- The
if __name__ == "__main__": block sets up the problem parameters, runs the GA, and displays the results.
Dependencies:
Make sure you have the required Python packages installed. You can install them using pip:
pip install numpy matplotlib
Running the Code:
-
Save the Code:
- Save the above code to a file named, for example,
tsp_ga.py.
-
Execute the Script:
- Run the script using Python:
python tsp_ga.py
-
Observe the Output:
- The script will print the best distance found at certain generations.
- After completion, it will display two plots:
- Best Route Found: Visual representation of the most efficient route discovered.
- Best Distance Over Generations: Graph showing the improvement of the best distance as generations progress.
Sample Output:
Generation 0: Best Distance = 346.78
Generation 50: Best Distance = 250.34
Generation 100: Best Distance = 200.12
...
Generation 900: Best Distance = 110.45
Generation 950: Best Distance = 105.67
Note: The actual distances and generations may vary due to the random nature of genetic algorithms.
Conclusion:
This implementation demonstrates how Genetic Algorithms can effectively solve combinatorial optimization problems like the Traveling Salesman Problem. By tweaking parameters such as population size, number of generations, and mutation rates, you can explore different solution qualities and convergence behaviors.
Feel free to experiment with different numbers of cities, adjust GA parameters, or enhance the algorithm with additional genetic operators to further improve performance!