Creating Genetic Algorithm for TSP
The user wants Python code to use a genetic algorithm (GA) for optimizing a Traveling Salesman Problem (TSP) route, but they haven’t specified certain details like size or libraries. I think they’re looking for a self-contained example, so I’ll include key GA components: tour representation, initialization, evaluation, selection methods, crossover, mutation, and the main loop. Maybe I’ll keep the code concise with necessary comments and avoid heavy external libraries, relying on the Python standard library. I'll also generate random coordinates for demonstration.Structuring Genetic Algorithm Classes
I’m thinking about structuring the code into classes, like City and the GA implementation. I want to run an example at the end. For the GA representation, I'll use a list of integers as indices of cities and Euclidean distances for calculations.
I'll implement methods to create routes, form the initial population, rank routes, select routes through roulette or tournament methods, and generate new routes via crossover and mutation. The user seems to want something straightforward, so I’ll aim for a single file with good readability and proper documentation, including type hints.Designing the Genetic Algorithm
I'm planning to simplify the design for the genetic algorithm. The cities will have coordinates in 2D, and while we could technically use Euclidean distance squared for comparing tours, users generally expect actual distances.
So, I’ll start with defining some basic components in Python, such as tuples for city coordinates and lists for routes and populations. I also need to implement a function to calculate distances, create routes randomly, and set up the genetic algorithm's parts, including a fitness function to evaluate routes and a tournament selection method. This should make everything more manageable!Implementing Genetic Algorithm Components
I’m considering the selection methods for the genetic algorithm, like using roulette to compute total fitness for each route. I’ll need to be cautious about ensuring routes aren’t replicated too much, but that’s not a huge issue. Additionally, implementing elitism to keep the best individuals unchanged will be valuable.
For crossover, I’ll use order crossover (OX) by selecting cut points from two parents and filling the child with genes accordingly. Mutation will involve swapping genes randomly based on a set mutation rate.
I’ll outline the main function for running the GA, including initializing the population and generating new populations over specified generations.Finalizing Genetic Algorithm Implementation
I want to define a main function to generate random cities for testing. I’ll print the results, but I’ll keep it simple. The main code will set a seed, create city coordinates, and run the genetic algorithm.
Additionally, I could incorporate optional plotting with matplotlib, but I'll handle its absence gracefully. I also want to ensure a stoppage condition is in place if no improvements occur over a specified number of generations.
The code will compute distances, evaluate populations, and employ tournament selection, elitism, and mutation processes for route optimization, ensuring everything functions systematically. I’m excited to get this testing underway!Crafting Final Script
When I store best_route by slicing the population[min_i][:], it ensures we don’t modify best_route with mutations. I’ll also make sure to copy elite individuals.
For clarity, I need to add docstrings and comments. Since the user wants code, I’ll provide it with minimal explanations wrapped in triple backticks for easy copying, and I’ll keep everything in one file. In the main section, I’ll define 20 random cities and run the genetic algorithm, printing the best route and distance.
I might also include optional progress prints and set a seed for replicability, ensuring the typing is imported. Let’s put this all together! ```python
"""
Genetic Algorithm for the Traveling Salesman Problem (TSP)
- Cities are points in 2D (x, y)
- A route is a permutation of city indices
- Objective: minimize total tour length (round trip)
Run this file directly to see a demo with random cities.
"""
import math
import random
from typing import List, Tuple
City = Tuple[float, float] # (x, y)
Route = List[int] # permutation of city indices
--------------------
Problem definition
--------------------
def euclidean_distance(a: City, b: City) -> float:
"""Euclidean distance between two cities."""
return math.hypot(a[0] - b[0], a[1] - b[1])
def route_length(route: Route, cities: List[City]) -> float:
"""Total length of a circular route (returns to start)."""
distance = 0.0
n = len(route)
for i in range(n):
city_a = cities[route[i]]
city_b = cities[route[(i + 1) % n]] # wrap around
distance += euclidean_distance(city_a, city_b)
return distance
--------------------
Genetic operators
--------------------
def create_random_route(num_cities: int) -> Route:
"""Create a random permutation of city indices."""
route = list(range(num_cities))
random.shuffle(route)
return route
def initialize_population(pop_size: int, num_cities: int) -> List[Route]:
"""Initialize population with random routes."""
return [create_random_route(num_cities) for _ in range(pop_size)]
def ordered_crossover(parent1: Route, parent2: Route) -> Route:
"""
Ordered crossover (OX):
- Take a slice from parent1
- Fill remaining positions with genes from parent2 in order
"""
size = len(parent1)
start, end = sorted(random.sample(range(size), 2))
child = [None] * size
# Copy slice from parent1
child[start:end] = parent1[start:end]
# Fill remaining from parent2 in order
p2_index = 0
for i in range(size):
if child[i] is None:
while parent2[p2_index] in child:
p2_index += 1
child[i] = parent2[p2_index]
return child
def mutate(route: Route, mutation_rate: float) -> None:
"""
Swap mutation:
- For each position, with probability mutation_rate, swap with another.
Mutation is done in-place.
"""
n = len(route)
for i in range(n):
if random.random() < mutation_rate:
j = random.randrange(n)
route[i], route[j] = route[j], route[i]
def tournament_selection(population: List[Route],
lengths: List[float],
tournament_size: int) -> Route:
"""
Tournament selection:
- Randomly pick 'tournament_size' individuals
- Return the best (shortest length)
"""
indices = random.sample(range(len(population)), tournament_size)
best_idx = min(indices, key=lambda i: lengths[i])
# Return a copy so parents aren't modified accidentally
return population[best_idx][:]
--------------------
GA driver
--------------------
def genetic_algorithm_tsp(
cities: List[City],
pop_size: int = 100,
elite_size: int = 20,
mutation_rate: float = 0.01,
generations: int = 500,
tournament_size: int = 5,
verbose: bool = True
) -> Tuple[Route, float]:
"""
Run a Genetic Algorithm to approximate a solution to the TSP.
Returns:
best_route: list of city indices
best_distance: total length of that route
"""
num_cities = len(cities)
population = initialize_population(pop_size, num_cities)
best_route = None
best_distance = float("inf")
for gen in range(generations):
# Evaluate population
lengths = [route_length(route, cities) for route in population]
# Track global best
gen_best_idx = min(range(len(population)), key=lambda i: lengths[i])
gen_best_distance = lengths[gen_best_idx]
if gen_best_distance < best_distance:
best_distance = gen_best_distance
best_route = population[gen_best_idx][:]
if verbose and (gen == 0 or (gen + 1) % max(1, generations // 10) == 0):
print(f"Generation {gen + 1:4d} | Best distance so far: {best_distance:.3f}")
# Elitism: carry over best elite_size individuals
elite_indices = sorted(range(len(population)), key=lambda i: lengths[i])[:elite_size]
new_population: List[Route] = [population[i][:] for i in elite_indices]
# Create rest of new population
while len(new_population) < pop_size:
parent1 = tournament_selection(population, lengths, tournament_size)
parent2 = tournament_selection(population, lengths, tournament_size)
child = ordered_crossover(parent1, parent2)
mutate(child, mutation_rate)
new_population.append(child)
population = new_population
return best_route, best_distance
--------------------
Demo / Usage example
--------------------
if name == "main":
random.seed(42)
# Create random cities in a 100x100 square
num_cities = 20
cities = [(random.uniform(0, 100), random.uniform(0, 100))
for _ in range(num_cities)]
best_route, best_distance = genetic_algorithm_tsp(
cities,
pop_size=150,
elite_size=30,
mutation_rate=0.02,
generations=500,
tournament_size=5,
verbose=True,
)
print("\nBest route found (city indices):")
print(best_route)
print(f"Total distance: {best_distance:.3f}")
# Optional: plot the final route if matplotlib is available
try:
import matplotlib.pyplot as plt
xs = [cities[i][0] for i in best_route] + [cities[best_route[0]][0]]
ys = [cities[i][1] for i in best_route] + [cities[best_route[0]][1]]
plt.figure(figsize=(6, 6))
plt.plot(xs, ys, "-o")
for idx, (x, y) in enumerate(cities):
plt.text(x + 0.5, y + 0.5, str(idx), fontsize=8)
plt.title(f"TSP route (distance: {best_distance:.2f})")
plt.xlabel("X")
plt.ylabel("Y")
plt.tight_layout()
plt.show()
except ImportError:
print("matplotlib not installed; skipping plot.")
To adapt this to your own data, replace the random `cities` list with your own list of `(x, y)` coordinates, then call `genetic_algorithm_tsp(cities, ...)`.