Creating a genetic algorithm (GA) to find the largest shape (i.e., the shape with the maximum area) that can be formed with a 1-meter-long line involves optimizing the arrangement of the line to form a closed shape. According to the isoperimetric inequality, among all possible shapes with a fixed perimeter, the circle encloses the maximum area. However, since we're using a GA, we'll explore how the algorithm converges toward this optimal solution through a discrete approximation, such as polygons with a fixed number of sides.
Below is a step-by-step guide and Python implementation of a genetic algorithm to approximate the largest possible shape (maximum area) with a perimeter of 1 meter using regular polygons. We'll keep the number of sides fixed for simplicity, but the approach can be extended for more complex representations.
Approach Overview
-
Representation (Chromosome):
- Each individual (chromosome) in the population represents a polygon defined by a fixed number of sides.
- For a fixed perimeter of 1 meter, a regular polygon's area depends on the number of sides. However, to introduce variability, we'll allow slight deviations in side lengths and angles to permit the GA to explore different polygon shapes.
-
Initialization:
- Generate an initial population of polygons with side lengths that sum to the perimeter (1 meter). To simplify, we'll start with regular polygons and introduce random variations.
-
Fitness Function:
- The fitness of each individual is determined by the area of the polygon. The goal is to maximize this area.
-
Selection:
- Select individuals based on their fitness scores to participate in reproduction. Higher fitness increases the chance of selection.
-
Crossover (Recombination):
- Combine pairs of selected individuals to produce offspring, inheriting traits (side lengths and angles) from both parents.
-
Mutation:
- Introduce random changes to some offspring to maintain genetic diversity and explore new solutions.
-
Replacement:
- Form a new generation by selecting the best individuals from the current and offspring populations.
-
Termination:
- Repeat the process for a set number of generations or until convergence is achieved.
Python Implementation
Here's a Python implementation of the described genetic algorithm. We'll use the numpy library for numerical operations and matplotlib for visualization.
import numpy as np
import matplotlib.pyplot as plt
import random
# Settings
POPULATION_SIZE = 100
NUM_GENERATIONS = 500
NUM_SIDES = 6 # Starting with a hexagon
MUTATION_RATE = 0.1
ELITE_SIZE = 2 # Number of top individuals to retain each generation
# Helper function to calculate the area of a polygon given its side lengths
def polygon_area(sides):
# Assuming the polygon is simple and can be divided into triangles
# This is a simplification; accurate area calculation would require angles
# Here, we'll assume it's close to a regular polygon for area estimation
n = len(sides)
perimeter = sum(sides)
if perimeter == 0:
return 0
# Calculate the radius of the circumscribed circle for a regular polygon
# Area of regular polygon: (n * s^2) / (4 * tan(pi/n))
# Adjusted for irregular polygons by using average side length
avg_side = perimeter / n
try:
area = (n * avg_side**2) / (4 * np.tan(np.pi / n))
except:
area = 0
return area
# Initialize population
def initialize_population():
population = []
for _ in range(POPULATION_SIZE):
# Randomly distribute the perimeter among the sides
sides = np.random.dirichlet(np.ones(NUM_SIDES), size=1)[0]
population.append(sides)
return population
# Fitness evaluation
def evaluate_fitness(population):
fitness_scores = []
for individual in population:
area = polygon_area(individual)
fitness_scores.append(area)
return fitness_scores
# Selection (Tournament Selection)
def selection(population, fitness_scores):
selected = []
for _ in range(POPULATION_SIZE):
# Tournament size of 3
aspirants_idx = random.sample(range(POPULATION_SIZE), 3)
aspirants = [population[i] for i in aspirants_idx]
aspirant_fitness = [fitness_scores[i] for i in aspirants_idx]
winner = aspirants[np.argmax(aspirant_fitness)]
selected.append(winner)
return selected
# Crossover (Single-point crossover)
def crossover(parent1, parent2):
point = random.randint(1, NUM_SIDES - 1)
child1 = np.concatenate([parent1[:point], parent2[point:]])
child2 = np.concatenate([parent2[:point], parent1[point:]])
return child1, child2
# Mutation (Gaussian mutation)
def mutate(individual):
if random.random() < MUTATION_RATE:
# Apply small Gaussian perturbation
perturbation = np.random.normal(0, 0.05, NUM_SIDES)
individual = individual + perturbation
# Ensure no side is negative
individual = np.clip(individual, 0.01, None)
# Renormalize to maintain perimeter of 1
individual = individual / np.sum(individual)
return individual
# Create next generation
def create_next_generation(selected):
next_gen = []
# Elitism: retain top ELITE_SIZE individuals
fitness_scores = evaluate_fitness(selected)
sorted_indices = np.argsort(fitness_scores)[::-1]
elites = [selected[i] for i in sorted_indices[:ELITE_SIZE]]
next_gen.extend(elites)
# Crossover and mutation
while len(next_gen) < POPULATION_SIZE:
parent1, parent2 = random.sample(selected, 2)
child1, child2 = crossover(parent1, parent2)
child1 = mutate(child1)
child2 = mutate(child2)
next_gen.append(child1)
if len(next_gen) < POPULATION_SIZE:
next_gen.append(child2)
return next_gen[:POPULATION_SIZE]
# Genetic Algorithm
def genetic_algorithm():
population = initialize_population()
best_fitness = []
avg_fitness = []
for generation in range(NUM_GENERATIONS):
fitness_scores = evaluate_fitness(population)
best_fitness.append(max(fitness_scores))
avg_fitness.append(np.mean(fitness_scores))
# Print progress every 50 generations
if generation % 50 == 0:
print(f"Generation {generation}: Max Area = {max(fitness_scores):.5f}, Avg Area = {np.mean(fitness_scores):.5f}")
# Selection
selected = selection(population, fitness_scores)
# Create next generation
population = create_next_generation(selected)
# Final evaluation
fitness_scores = evaluate_fitness(population)
best_index = np.argmax(fitness_scores)
best_individual = population[best_index]
best_area = fitness_scores[best_index]
print(f"Best Area after {NUM_GENERATIONS} generations: {best_area:.5f}")
return best_individual, best_area, best_fitness, avg_fitness
# Visualization of fitness over generations
def plot_fitness(best_fitness, avg_fitness):
plt.figure(figsize=(10,6))
plt.plot(best_fitness, label='Best Fitness')
plt.plot(avg_fitness, label='Average Fitness')
plt.title('Fitness over Generations')
plt.xlabel('Generation')
plt.ylabel('Area')
plt.legend()
plt.show()
# Visualization of the best polygon
def plot_polygon(sides):
angles = np.linspace(0, 2 * np.pi, NUM_SIDES, endpoint=False)
angles += np.random.uniform(0, 2 * np.pi / NUM_SIDES, NUM_SIDES) # Add some randomness
angles = np.sort(angles)
# Convert side lengths to angles assuming a simple polygon
# This is a simplification; for accurate plotting, more complex geometry is needed
x, y = [0], [0]
current_angle = angles[0]
for length, angle in zip(sides, angles):
current_angle = angle
x.append(x[-1] + length * np.cos(current_angle))
y.append(y[-1] + length * np.sin(current_angle))
# Close the polygon
x.append(x[0])
y.append(y[0])
plt.figure(figsize=(6,6))
plt.plot(x, y, marker='o')
plt.title('Best Polygon Shape')
plt.axis('equal')
plt.show()
# Run the genetic algorithm
best_individual, best_area, best_fitness, avg_fitness = genetic_algorithm()
# Plot fitness over generations
plot_fitness(best_fitness, avg_fitness)
# Plot the best polygon (approximated)
plot_polygon(best_individual)
Explanation of the Code
-
Initialization (initialize_population):
- Uses the Dirichlet distribution to generate random side lengths that sum to 1 for each individual in the population.
- Each individual represents a polygon with
NUM_SIDES sides.
-
Fitness Evaluation (evaluate_fitness):
- Calculates the area of each polygon. For simplicity, we approximate the area assuming the polygon is roughly regular. A more accurate calculation would require both side lengths and internal angles.
-
Selection (selection):
- Implements tournament selection where three individuals are randomly chosen, and the one with the highest fitness is selected.
-
Crossover (crossover):
- Performs single-point crossover between two parents to produce two offspring.
-
Mutation (mutate):
- Applies Gaussian perturbations to the side lengths with a certain probability (
MUTATION_RATE).
- Ensures no side length becomes negative and renormalizes the side lengths to maintain the perimeter constraint of 1 meter.
-
Elitism and Replacement (create_next_generation):
- Retains the top
ELITE_SIZE individuals to the next generation.
- Fills the rest of the population with offspring produced by crossover and mutation.
-
Genetic Algorithm Execution (genetic_algorithm):
- Runs the GA for a specified number of generations (
NUM_GENERATIONS).
- Tracks and prints the maximum and average fitness scores every 50 generations.
- Returns the best individual found along with its fitness score.
-
Visualization:
plot_fitness visualizes how the best and average fitness scores evolve over generations.
plot_polygon provides a visual representation of the best polygon shape found. Note that accurately plotting an irregular polygon based solely on side lengths requires more complex geometric calculations involving internal angles, which are simplified here for demonstration purposes.
Notes and Considerations
-
Simplifications:
- The area calculation assumes roughly regular polygons. For irregular polygons, calculating the exact area requires knowledge of internal angles or vertex coordinates.
- The plotting function simplifies the polygon structure and may not accurately represent the true shape based on side lengths alone.
-
Extensions:
- To handle irregular polygons more accurately, you could represent each individual with both side lengths and internal angles or vertex coordinates.
- Incorporate more sophisticated methods for ensuring valid polygons and accurately computing their areas.
-
Expected Outcome:
- The GA should evolve the population towards polygons with larger areas. Given the perimeter constraint, the circle (approximated by polygons with an increasing number of sides) maximizes the area. However, with a fixed number of sides, the GA optimizes the side lengths and angles to approximate this ideal as closely as possible.
Conclusion
This implementation provides a foundational framework for using a genetic algorithm to optimize polygon shapes for maximum area under a perimeter constraint. While simplifications are made for brevity and clarity, the approach can be expanded and refined for more precise shape optimization tasks.