Certainly! Below is a Python implementation of a Genetic Algorithm (GA) designed to find the largest possible shape (in terms of area) that can be created with a fixed perimeter of 1 metre.
Overview
-
Problem Interpretation:
- Objective: Maximize the area of a closed shape with a fixed perimeter of 1 metre.
- Optimal Solution: According to the isoperimetric theorem, the circle maximizes the area for a given perimeter. However, to approach this problem computationally, we'll approximate by using polygons.
-
Representation:
- Shape Representation: Each shape is represented as a polygon with a fixed number of sides (e.g., 10 sides).
- Encoding: Each individual in the population is encoded as a list of angles at each vertex. The side lengths are fixed (each side is
1/n metres where n is the number of sides).
-
Genetic Algorithm Components:
- Population Initialization: Randomly generate a population of polygons with random angles.
- Fitness Function: Calculate the area of the polygon. Higher area signifies better fitness.
- Selection: Use tournament selection to choose parents based on fitness.
- Crossover: Perform uniform crossover to combine parents' angles and produce offspring.
- Mutation: Apply small random changes to the angles to maintain diversity.
- Constraints: Ensure that the perimeter remains fixed by keeping side lengths constant.
-
Implementation:
- Libraries Used:
numpy for numerical operations, matplotlib for visualization.
- Assumptions: Some generated polygons might be self-intersecting. Such polygons are either handled gracefully or assigned lower fitness.
Python Implementation
import numpy as np
import matplotlib.pyplot as plt
import random
# Set random seed for reproducibility
random.seed(42)
np.random.seed(42)
class PolygonIndividual:
def __init__(self, angles):
self.angles = angles # List of angles at each vertex in radians
self.area = None
def calculate_area(self, side_length):
"""
Calculate the area of the polygon using the given angles and side length.
If the polygon is invalid (e.g., self-intersecting), return a very small area.
"""
n = len(self.angles)
angles = self.angles
# Starting at origin
x, y = 0, 0
vertices = [(x, y)]
current_angle = 0
# Calculate vertices
for angle in angles:
current_angle += angle
x += side_length * np.cos(current_angle)
y += side_length * np.sin(current_angle)
vertices.append((x, y))
# Check if polygon is closed (within a small epsilon)
epsilon = 1e-5
if not (np.isclose(x, 0, atol=epsilon) and np.isclose(y, 0, atol=epsilon)):
# Not a closed polygon
self.area = 1e-6
return self.area
# Use Shoelace formula
try:
vert_array = np.array(vertices[:-1]) # Exclude the last point which is same as first
x_coords = vert_array[:,0]
y_coords = vert_array[:,1]
area = 0.5 * np.abs(np.dot(x_coords, np.roll(y_coords, 1)) -
np.dot(y_coords, np.roll(x_coords, 1)))
# Handle self-intersecting polygons: area calculation might not be accurate
if np.isnan(area) or area < 0:
area = 1e-6
self.area = area
except:
self.area = 1e-6
return self.area
def initialize_population(pop_size, num_angles):
population = []
for _ in range(pop_size):
# Initialize angles randomly between (2π/n - delta) and (2π/n + delta)
# To encourage shapes close to regular polygon initially
delta = np.pi / num_angles
angles = np.random.uniform(low=0, high=2*np.pi, size=num_angles)
angles = angles / np.sum(angles) * 2 * np.pi # Normalize to sum to 2π
individual = PolygonIndividual(angles)
population.append(individual)
return population
def evaluate_population(population, side_length):
for individual in population:
individual.calculate_area(side_length)
def tournament_selection(population, tournament_size):
selected = []
pop_size = len(population)
for _ in range(pop_size):
competitors = random.sample(population, tournament_size)
winner = max(competitors, key=lambda ind: ind.area)
selected.append(winner)
return selected
def crossover(parent1, parent2):
"""
Uniform crossover: each angle is taken randomly from one of the parents
"""
child_angles = []
for a1, a2 in zip(parent1.angles, parent2.angles):
child_angles.append(a1 if random.random() < 0.5 else a2)
# Normalize angles to sum to 2π
child_angles = np.array(child_angles)
child_angles = child_angles / np.sum(child_angles) * 2 * np.pi
return PolygonIndividual(child_angles)
def mutate(individual, mutation_rate, mutation_strength):
"""
Mutate the individual's angles by adding a small random value
"""
angles = np.copy(individual.angles)
for i in range(len(angles)):
if random.random() < mutation_rate:
angles[i] += np.random.normal(0, mutation_strength)
# Ensure angles are positive
angles = np.clip(angles, 0.01, None)
# Normalize to sum to 2π
angles = angles / np.sum(angles) * 2 * np.pi
individual.angles = angles
return individual
def genetic_algorithm(
pop_size=100,
num_angles=10,
generations=1000,
crossover_rate=0.8,
mutation_rate=0.1,
mutation_strength=0.1,
tournament_size=3,
side_length=1.0 / 10 # Since perimeter is 1 metre and 10 sides
):
# Initialize population
population = initialize_population(pop_size, num_angles)
# Evaluate initial population
evaluate_population(population, side_length)
best_individual = max(population, key=lambda ind: ind.area)
print(f'Initial best area: {best_individual.area:.6f}')
for gen in range(generations):
# Selection
selected = tournament_selection(population, tournament_size)
# Crossover
offspring = []
for i in range(0, pop_size, 2):
parent1 = selected[i]
parent2 = selected[i+1 if i+1 < pop_size else 0]
if random.random() < crossover_rate:
child1 = crossover(parent1, parent2)
child2 = crossover(parent2, parent1)
else:
child1 = PolygonIndividual(np.copy(parent1.angles))
child2 = PolygonIndividual(np.copy(parent2.angles))
offspring.extend([child1, child2])
# Mutation
offspring = [mutate(ind, mutation_rate, mutation_strength) for ind in offspring]
# Evaluate offspring
evaluate_population(offspring, side_length)
# Elitism: carry forward the best individual
current_best = max(offspring, key=lambda ind: ind.area)
if current_best.area > best_individual.area:
best_individual = current_best
# Replace population
population = offspring
# Optional: Print progress
if (gen+1) % 100 == 0 or gen == 0:
print(f'Generation {gen+1}: Best Area = {best_individual.area:.6f}')
return best_individual
def plot_polygon(individual):
angles = individual.angles
side_length = 1.0 / len(angles)
x, y = 0, 0
vertices = [(x, y)]
current_angle = 0
for angle in angles:
current_angle += angle
x += side_length * np.cos(current_angle)
y += side_length * np.sin(current_angle)
vertices.append((x, y))
vertices = np.array(vertices)
plt.figure(figsize=(6,6))
plt.plot(vertices[:,0], vertices[:,1], 'bo-')
plt.fill(vertices[:,0], vertices[:,1], alpha=0.3)
plt.title(f'Best Polygon with Area = {individual.area:.6f} m²')
plt.axis('equal')
plt.show()
if __name__ == "__main__":
# Parameters
POP_SIZE = 200
NUM_ANGLES = 30 # More angles allow more complex shapes
GENERATIONS = 2000
CROSSOVER_RATE = 0.9
MUTATION_RATE = 0.2
MUTATION_STRENGTH = 0.05
TOURNAMENT_SIZE = 5
PERIMETER = 1.0 # meters
SIDE_LENGTH = PERIMETER / NUM_ANGLES
# Run Genetic Algorithm
best = genetic_algorithm(
pop_size=POP_SIZE,
num_angles=NUM_ANGLES,
generations=GENERATIONS,
crossover_rate=CROSSOVER_RATE,
mutation_rate=MUTATION_RATE,
mutation_strength=MUTATION_STRENGTH,
tournament_size=TOURNAMENT_SIZE,
side_length=SIDE_LENGTH
)
print(f'Best area found: {best.area:.6f} m²')
# Plot the best polygon
plot_polygon(best)
Explanation of the Code
-
Class PolygonIndividual:
- Represents a polygon with a specific set of angles.
- Contains a method
calculate_area to compute its area using the Shoelace formula. If the polygon isn't closed or is invalid, it assigns a very small area to discourage selection.
-
Population Initialization:
- The
initialize_population function creates a list of PolygonIndividual instances with random angles. Angles are normalized to ensure the sum equals 2π, making the polygon closed.
-
Fitness Evaluation:
- The
evaluate_population function computes the area for each individual in the population.
-
Selection:
- Tournament selection is implemented in
tournament_selection, where a subset of individuals is randomly chosen, and the one with the highest fitness (area) is selected as a parent.
-
Crossover:
- The
crossover function performs uniform crossover by randomly selecting each angle from one of the two parents. The resulting angles are normalized to maintain the fixed perimeter constraint.
-
Mutation:
- The
mutate function introduces random variations to the angles based on the mutation rate and strength. After mutation, angles are clipped to prevent negative values and normalized.
-
Genetic Algorithm Execution:
- The
genetic_algorithm function orchestrates the process over a given number of generations, applying selection, crossover, mutation, and elitism to evolve the population toward better solutions.
-
Visualization:
- The
plot_polygon function uses matplotlib to visualize the best-found polygon, showing its shape and computed area.
-
Main Execution:
- Sets the parameters for the GA, runs it, and plots the best solution found.
Running the Code
To run the code:
-
Dependencies: Ensure you have numpy and matplotlib installed. You can install them using:
pip install numpy matplotlib
-
Execution: Save the code to a file, say genetic_polygon.py, and run:
python genetic_polygon.py
Notes and Potential Improvements
-
Number of Angles: Increasing NUM_ANGLES allows for more complex and potentially larger area shapes but increases computational complexity.
-
Handling Self-Intersecting Polygons: Currently, self-intersecting polygons are given a minimal area. Implementing a more robust method to detect and penalize such polygons could improve performance.
-
Encouraging Circularity: Adding additional terms to the fitness function that encourage smoothness or circularity can guide the GA closer to the optimal circular shape.
-
Parallelization: For larger populations or more generations, parallelizing the fitness evaluation could speed up the algorithm.
This implementation provides a foundational approach to using a Genetic Algorithm for shape optimization under perimeter constraints. Depending on specific requirements or constraints, further refinements and optimizations can be made.