The Moving Sofa Problem is a famous unsolved problem in geometry that asks for the planar shape of maximal area that can move around a right-angled corner in a hallway of unit width. Solving this problem using a genetic algorithm (GA) involves several steps:
-
Representation of the Shape:
- Represent the sofa shape using a sequence of points connected by line segments. For simplicity, we'll use 30 points to define the sofa.
-
Initial Population:
- Generate an initial population of random shapes with 30 line segments.
-
Fitness Function:
- The fitness function should evaluate how "good" a sofa shape is. In this case, we aim to maximize the area while ensuring the sofa can navigate the hallway corner. However, verifying the navigability is complex, so we'll simplify by focusing on maximizing the width and minimizing overlaps or extreme angles.
-
Selection, Crossover, and Mutation:
- Implement GA operators to evolve the population over generations.
-
Constraints:
- Ensure the sofa remains within the bounds of the hallway and doesn't have overlapping segments.
Given the complexity of accurately simulating the sofa's movement around the corner, the following implementation provides a simplified version that focuses on evolving shapes with maximal width and reasonable geometry.
Dependencies
Before we begin, ensure you have the following Python libraries installed:
pip install numpy matplotlib DEAP
Implementation
import numpy as np
import matplotlib.pyplot as plt
import random
from deap import base, creator, tools, algorithms
# Define constants
NUM_SEGMENTS = 30
SEGMENT_LENGTH_RANGE = (0.5, 1.5) # Arbitrary units
ANGLE_RANGE = (-30, 30) # Degrees
POPULATION_SIZE = 50
GENERATIONS = 100
CX_PROB = 0.5
MUT_PROB = 0.2
# Fitness Function: Maximizing width while minimizing overlaps and extreme angles
def evaluate_shape(shape):
points = np.array(shape).reshape(NUM_SEGMENTS, 2)
# Calculate width as the max distance on x-axis
width = points[:,0].max() - points[:,0].min()
# Penalty for self-intersections (simplified)
penalty = 0
try:
from shapely.geometry import LineString
line = LineString(points)
if not line.is_simple:
penalty += 1000 # Large penalty for intersections
except ImportError:
pass # If shapely is not installed, skip intersection check
# Fitness is width minus penalty
fitness = width - penalty
return (fitness,)
# Create individual and fitness
creator.create("FitnessMax", base.Fitness, weights=(1.0,))
creator.create("Individual", list, fitness=creator.FitnessMax)
toolbox = base.Toolbox()
# Attribute generator: Randomly generate a line segment (dx, dy)
def random_segment():
length = random.uniform(*SEGMENT_LENGTH_RANGE)
angle = random.uniform(*ANGLE_RANGE)
rad = np.deg2rad(angle)
dx = length * np.cos(rad)
dy = length * np.sin(rad)
return [dx, dy]
toolbox.register("segment", random_segment)
# Structure initializers
toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.segment, n=NUM_SEGMENTS)
toolbox.register("population", tools.initRepeat, list, toolbox.individual)
# Genetic Operators
toolbox.register("evaluate", evaluate_shape)
toolbox.register("mate", tools.cxTwoPoint)
toolbox.register("mutate", tools.mutGaussian, mu=0, sigma=0.5, indpb=0.2)
toolbox.register("select", tools.selTournament, tournsize=3)
def main():
# Initialize population
pop = toolbox.population(n=POPULATION_SIZE)
# Statistics
stats = tools.Statistics(lambda ind: ind.fitness.values)
stats.register("avg", np.mean)
stats.register("max", np.max)
# Hall of Fame
hof = tools.HallOfFame(1)
# Run Genetic Algorithm
pop, log = algorithms.eaSimple(pop, toolbox, cxpb=CX_PROB, mutpb=MUT_PROB,
ngen=GENERATIONS, stats=stats, halloffame=hof, verbose=True)
# Best individual
best = hof[0]
print("Best fitness:", best.fitness.values[0])
# Convert to points
shape = np.array(best).reshape(NUM_SEGMENTS, 2)
points = np.cumsum(shape, axis=0)
points = np.vstack(([0,0], points)) # Start from origin
# Plot the shape
plt.figure(figsize=(8,8))
plt.plot(points[:,0], points[:,1], marker='o')
plt.title("Best Sofa Shape")
plt.xlabel("X")
plt.ylabel("Y")
plt.grid(True)
plt.axis('equal')
plt.show()
if __name__ == "__main__":
main()
Explanation
-
Representation:
- Each individual in the population represents a sofa shape as a list of
30 [dx, dy] pairs, where dx and dy are the changes in the x and y directions for each segment.
- The sofa starts at the origin
(0,0), and each segment is connected end-to-end.
-
Fitness Function:
- The primary objective is to maximize the width of the sofa, calculated as the difference between the maximum and minimum x-coordinates.
- A penalty is added if the sofa shape intersects itself. This is a simplified check using the
shapely library. If shapely is not installed, the penalty is skipped.
- The fitness is the width minus the penalty. Higher fitness values are better.
-
Genetic Operators:
- Crossover (
cxTwoPoint): Exchanges segments between two parents at two random points.
- Mutation (
mutGaussian): Adds Gaussian noise to each segment's dx and dy with a probability of 0.2 per gene.
- Selection (
selTournament): Uses tournament selection with a tournament size of 3.
-
Evolution Process:
- The GA runs for
100 generations with a population size of 50.
- In each generation, the population evolves through selection, crossover, and mutation.
- The
HallOfFame keeps track of the best individual found.
-
Visualization:
- After evolution, the best sofa shape is plotted using
matplotlib.
Enhancements and Considerations
-
Movement Constraints:
- Accurately simulating whether a shape can navigate around a corner is complex. This implementation simplifies the constraints to avoid self-intersections and maximize width.
- For a more accurate simulation, collision detection with the hallway boundaries during movement would be necessary, potentially using advanced geometry or physics simulations.
-
Fitness Function Improvements:
- Incorporate additional factors such as the area of the sofa.
- Penalize extreme angles or ensure the sofa remains within reasonable geometric bounds.
-
Representation:
- Instead of using relative
dx and dy, consider using absolute coordinates or other representations that might better capture feasible sofa shapes.
-
Libraries:
- Using libraries like
shapely for advanced geometric operations can enhance the fitness evaluation.
- For more efficient genetic algorithms, libraries like
DEAP are already utilized, but further optimizations can be made.
-
Scaling:
- The parameters like segment lengths, angles, population size, and generations can be tuned for better performance and results.
Final Notes
While this implementation provides a starting point for using a genetic algorithm to approach the Moving Sofa Problem, the actual problem's complexity requires more sophisticated techniques and constraints. The Moving Sofa Problem remains open in mathematics, and computational approaches like this can offer insights but may not yield the optimal solution.