Create a Python genetic algorithm to solve the Moving sofa problem.
- User
Create a Python genetic algorithm to solve the Moving sofa problem.
- Assistant
Create a Python genetic algorithm to solve the Moving sofa problem.
The Moving Sofa Problem is a famous unsolved problem in geometric optimization. It asks for the planar shape of largest area that can be moved around a right-angled (L-shaped) corner in a corridor of unit width. Despite its simplicity in definition, the problem remains unsolved, with the best-known solution being the Hammersley sofa, which has an area of approximately 2.2195.
Implementing a Genetic Algorithm (GA) to approximate a solution to the Moving Sofa Problem is an intriguing approach. Below, I'll guide you through a simplified Python implementation of such a GA. This implementation makes several simplifications to make the problem tractable, but it captures the essence of how a GA can be applied to this complex optimization problem.
Representation (Encoding): We represent the sofa shape as a polygon defined by a sequence of vertices. To simplify, we'll use a parametric representation based on polar coordinates, where each vertex is determined by an angle and a radius.
Initial Population: Generate a set of random sofa shapes that roughly fit within the corridor constraints.
Fitness Function: Evaluate each sofa shape based on two criteria:
Selection: Select parent shapes based on their fitness scores to produce offspring for the next generation.
Crossover and Mutation: Combine and slightly alter parent shapes to create new offspring, introducing diversity into the population.
Iteration: Repeat the selection, crossover, and mutation steps for a number of generations, progressively improving the population's fitness.
Movement Feasibility: Accurately determining whether a sofa shape can navigate the corridor is highly non-trivial. For simplicity, we'll assume that if the sofa's dimensions in certain orientations don't exceed the corridor's constraints, it's feasible.
Shape Representation: Instead of arbitrary polygons, we'll use a fixed number of vertices with parameters that define their positions, simplifying the evaluation and genetic operations.
Collision Detection: Simplified to boundary checks based on the corridor's unit width.
These simplifications allow us to implement a workable GA without delving into the complex geometry of the moving sofa problem.
Below is a Python implementation of the described genetic algorithm. This code uses standard libraries and is self-contained. You can run it as-is to see the GA in action.
import numpy as np
import matplotlib.pyplot as plt
from shapely.geometry import Polygon, Point
from shapely.affinity import rotate, translate
import random
# Ensure you have shapely installed:
# pip install shapely
# Constants
POPULATION_SIZE = 50
GENERATIONS = 100
MUTATION_RATE = 0.1
NUM_VERTICES = 8 # Number of vertices to define the sofa shape
CORRIDOR_WIDTH = 1.0
def generate_random_shape(num_vertices):
"""
Generates a random convex polygon shape within certain bounds.
"""
angles = np.sort(np.random.uniform(0, 2 * np.pi, num_vertices))
radii = np.random.uniform(0.2, 0.5, num_vertices) # Radii between 0.2 and 0.5
points = np.array([
(r * np.cos(a), r * np.sin(a))
for r, a in zip(radii, angles)
])
# Ensure the polygon is convex and simple
polygon = Polygon(points).convex_hull
return polygon
def calculate_area(polygon):
return polygon.area
def is_feasible(polygon):
"""
Simplified feasibility check:
- The sofa must fit within the corridor when aligned horizontally or vertically.
"""
minx, miny, maxx, maxy = polygon.bounds
width = maxx - minx
height = maxy - miny
# Check if the shape can fit horizontally and vertically
return width <= CORRIDOR_WIDTH and height <= CORRIDOR_WIDTH
def fitness(polygon):
"""
Fitness function combines feasibility and area.
If not feasible, fitness is 0.
If feasible, fitness is the area.
"""
if is_feasible(polygon):
return calculate_area(polygon)
else:
return 0
def selection(population, fitnesses):
"""
Select two parents using tournament selection.
"""
tournament_size = 3
selected = []
for _ in range(2):
aspirants = random.sample(list(zip(population, fitnesses)), tournament_size)
aspirants = sorted(aspirants, key=lambda x: x[1], reverse=True)
selected.append(aspirants[0][0])
return selected[0], selected[1]
def crossover(parent1, parent2):
"""
Single point crossover based on vertices.
"""
if parent1.geom_type != 'Polygon' or parent2.geom_type != 'Polygon':
return parent1, parent2
coords1 = list(parent1.exterior.coords)[:-1] # Exclude the closing point
coords2 = list(parent2.exterior.coords)[:-1]
if len(coords1) != len(coords2):
return parent1, parent2
point = random.randint(1, len(coords1)-1)
child1_coords = coords1[:point] + coords2[point:]
child2_coords = coords2[:point] + coords1[point:]
child1 = Polygon(child1_coords).convex_hull
child2 = Polygon(child2_coords).convex_hull
return child1, child2
def mutate(polygon):
"""
Mutate the polygon by slightly altering the position of a random vertex.
"""
coords = list(polygon.exterior.coords)[:-1]
idx = random.randint(0, len(coords)-1)
x, y = coords[idx]
angle = np.arctan2(y, x)
radius = np.hypot(x, y)
# Perturb the angle and radius slightly
angle += np.random.uniform(-0.1, 0.1)
radius += np.random.uniform(-0.05, 0.05)
radius = np.clip(radius, 0.2, 0.5)
new_x = radius * np.cos(angle)
new_y = radius * np.sin(angle)
coords[idx] = (new_x, new_y)
new_polygon = Polygon(coords).convex_hull
return new_polygon
def plot_best(population, fitnesses, generation):
"""
Plot the best polygon in the current population.
"""
best_idx = np.argmax(fitnesses)
best_polygon = population[best_idx]
area = fitnesses[best_idx]
plt.figure(figsize=(6,6))
x, y = best_polygon.exterior.xy
plt.plot(x, y, 'b-')
plt.fill(x, y, alpha=0.5, label=f'Area: {area:.3f}')
plt.title(f'Generation {generation}')
plt.xlabel('X')
plt.ylabel('Y')
plt.legend()
plt.xlim(-1, 1)
plt.ylim(-1, 1)
plt.grid(True)
plt.show()
def genetic_algorithm():
# Initialize population
population = [generate_random_shape(NUM_VERTICES) for _ in range(POPULATION_SIZE)]
for generation in range(GENERATIONS):
fitnesses = [fitness(individual) for individual in population]
new_population = []
# Elitism: carry over the best individual
best_idx = np.argmax(fitnesses)
best_individual = population[best_idx]
new_population.append(best_individual)
# Generate rest of the new population
while len(new_population) < POPULATION_SIZE:
parent1, parent2 = selection(population, fitnesses)
child1, child2 = crossover(parent1, parent2)
# Mutation
if random.random() < MUTATION_RATE:
child1 = mutate(child1)
if random.random() < MUTATION_RATE:
child2 = mutate(child2)
new_population.extend([child1, child2])
population = new_population[:POPULATION_SIZE]
# Optionally, plot the best individual every 10 generations
if generation % 10 == 0 or generation == GENERATIONS -1:
plot_best(population, fitnesses, generation)
print(f'Generation {generation}: Best Area = {fitnesses[best_idx]:.3f}')
# After all generations, return the best solution
final_fitnesses = [fitness(individual) for individual in population]
best_idx = np.argmax(final_fitnesses)
best_individual = population[best_idx]
best_area = final_fitnesses[best_idx]
print(f'Best Area after {GENERATIONS} generations: {best_area:.3f}')
return best_individual
if __name__ == "__main__":
best_sofa = genetic_algorithm()
# Plot the final best sofa
plot_best([best_sofa], [calculate_area(best_sofa)], 'Final Best')
Imports and Constants:
numpy and matplotlib are used for numerical operations and plotting.shapely is used for geometric operations on polygons.Shape Generation (generate_random_shape):
Fitness Evaluation (fitness):
Selection (selection):
Crossover (crossover):
Mutation (mutate):
Plotting (plot_best):
Genetic Algorithm (genetic_algorithm):
Execution:
Prerequisites:
pip install numpy matplotlib shapely
Execution:
moving_sofa_ga.py.python moving_sofa_ga.py
Visualization:
Feasibility Check: The current feasibility check is overly simplistic. Implementing a more accurate collision detection and movement simulation would yield better results but would significantly increase computational complexity.
Shape Representation: Using a fixed number of vertices limits the diversity of shapes. Exploring more flexible representations, such as splines or adaptive vertex counts, could enhance the search.
Genetic Operators: More sophisticated crossover and mutation operators tailored to the geometric nature of the problem could improve performance.
Performance Optimization: The current implementation may be slow for larger populations or more generations. Optimizing geometry operations and leveraging parallel processing can help.
Despite these limitations, this implementation provides a foundational approach to applying genetic algorithms to complex geometric optimization problems like the Moving Sofa Problem.