import numpy as np import matplotlib.pyplot as plt from matplotlib.patches import…
- User
import numpy as np import matplotlib.pyplot as plt from matplotlib.patches import Polygon import random
Genetic Algorithm Parameters
POPULATION_SIZE = 100 GENERATIONS = 1000 MUTATION_RATE = 0.01 NUM_VERTICES = 30 # Number of vertices in the polygon
Helper Functions
def generate_initial_population(): population = [] for _ in range(POPULATION_SIZE): # Random angles between 0 and 2*pi, sorted to ensure consistent vertex ordering angles = np.sort(np.random.uniform(0, 2 * np.pi, NUM_VERTICES)) # Random radii, normalized to have perimeter 1 radii = np.random.uniform(0.1, 1.0, NUM_VERTICES) shape = np.column_stack((radii * np.cos(angles), radii * np.sin(angles))) population.append(shape) return population
def calculate_perimeter(shape): perimeter = 0 for i in range(len(shape)): perimeter += np.linalg.norm(shape[i] - shape[i - 1]) return perimeter
def normalize_shape(shape): perimeter = calculate_perimeter(shape) if perimeter == 0: return shape return shape / perimeter
def calculate_area(shape): # Using Shoelace formula x = shape[:, 0] y = shape[:, 1] return 0.5 * np.abs(np.dot(x, np.roll(y, 1)) - np.dot(y, np.roll(x, 1)))
def fitness(shape): return calculate_area(shape)
def selection(population): # Sort population based on fitness (descending) sorted_population = sorted(population, key=lambda x: fitness(x), reverse=True) # Select top 50% return sorted_population[:POPULATION_SIZE // 2]
def crossover(parent1, parent2): # Single point crossover point = random.randint(1, NUM_VERTICES - 1) child1 = np.vstack((parent1[:point], parent2[point:])) child2 = np.vstack((parent2[:point], parent1[point:])) return child1, child2
def mutate(shape): for i in range(NUM_VERTICES): if random.random() < MUTATION_RATE: # Small perturbation delta_radius = np.random.normal(0, 0.05) delta_angle = np.random.normal(0, 0.1) r = np.linalg.norm(shape[i]) theta = np.arctan2(shape[i,1], shape[i,0]) r = max(0.1, r + delta_radius) # Prevent radius from becoming too small theta = (theta + delta_angle) % (2 * np.pi) shape[i] = [r * np.cos(theta), r * np.sin(theta)] return shape
def create_next_generation(selected_population): next_generation = selected_population.copy() while len(next_generation) < POPULATION_SIZE: parent1, parent2 = random.sample(selected_population, 2) child1, child2 = crossover(parent1, parent2) child1 = mutate(child1) child2 = mutate(child2) child1 = normalize_shape(child1) child2 = normalize_shape(child2) next_generation.extend([child1, child2]) return next_generation[:POPULATION_SIZE]
def genetic_algorithm(): population = generate_initial_population() best_shape = None best_fitness = -1 fitness_history = [] best_shapes_at_intervals = {} # To store best shapes at every 100th generation max_diff = 0 generation_of_max_diff = 0 previous_best_fitness = None # Store best shapes for max fitness difference shape_before_max_diff = None shape_at_max_diff = None
- Assistant