Create a thoughtful evolutionary simulation with visualization. Keep in mind that I use…
- User
Create a thoughtful evolutionary simulation with visualization. Keep in mind that I use Replit without a subscription.
- Assistant
Create a thoughtful evolutionary simulation with visualization. Keep in mind that I use Replit without a subscription.
Creating an evolutionary simulation is a fantastic way to explore concepts like natural selection, genetic variation, and adaptation. Below, I'll guide you through building a simple yet thoughtful evolutionary simulation using Python. We'll leverage the matplotlib library for visualization, which is well-supported on Replit's free tier.
Objective: Simulate a population of organisms that evolve over generations to maximize their fitness in a given environment.
Key Components:
Ensure you have a Python environment with matplotlib installed. On Replit, you can specify dependencies in the requirements.txt file:
matplotlib
Replit will automatically install the required packages.
We'll represent each individual as a set of genes. For simplicity, let's consider each gene as a binary value (0 or 1).
import random
import matplotlib.pyplot as plt
# Parameters
POPULATION_SIZE = 100
GENE_LENGTH = 20
GENERATIONS = 50
MUTATION_RATE = 0.01
Create a function to initialize a population with random genes.
def initialize_population(size, gene_length):
population = []
for _ in range(size):
genes = [random.randint(0, 1) for _ in range(gene_length)]
population.append(genes)
return population
For this example, let's define fitness as the number of genes set to 1. The goal is to evolve towards all genes being 1.
def calculate_fitness(individual):
return sum(individual)
Select individuals based on their fitness. We'll use tournament selection for simplicity.
def selection(population, fitnesses):
# Tournament selection
selected = []
for _ in range(len(population)):
i, j = random.sample(range(len(population)), 2)
if fitnesses[i] > fitnesses[j]:
selected.append(population[i])
else:
selected.append(population[j])
return selected
Create new individuals by combining genes from parents and introduce mutations.
def crossover(parent1, parent2):
crossover_point = random.randint(1, len(parent1)-1)
child = parent1[:crossover_point] + parent2[crossover_point:]
return child
def mutate(individual, mutation_rate):
return [
gene if random.random() > mutation_rate else 1 - gene
for gene in individual
]
Generate a new population through selection, crossover, and mutation.
def create_next_generation(selected_population, mutation_rate):
next_generation = []
for i in range(0, len(selected_population), 2):
parent1 = selected_population[i]
parent2 = selected_population[i+1] if i+1 < len(selected_population) else selected_population[0]
child1 = crossover(parent1, parent2)
child2 = crossover(parent2, parent1)
child1 = mutate(child1, mutation_rate)
child2 = mutate(child2, mutation_rate)
next_generation.extend([child1, child2])
return next_generation[:len(selected_population)]
Now, let's put everything together and visualize the average and maximum fitness over generations.
def simulate():
population = initialize_population(POPULATION_SIZE, GENE_LENGTH)
average_fitness_history = []
max_fitness_history = []
for generation in range(GENERATIONS):
fitnesses = [calculate_fitness(ind) for ind in population]
average_fitness = sum(fitnesses) / len(fitnesses)
max_fitness = max(fitnesses)
average_fitness_history.append(average_fitness)
max_fitness_history.append(max_fitness)
print(f"Generation {generation}: Avg Fitness = {average_fitness}, Max Fitness = {max_fitness}")
selected = selection(population, fitnesses)
population = create_next_generation(selected, MUTATION_RATE)
# Visualization
plt.plot(range(GENERATIONS), average_fitness_history, label='Average Fitness')
plt.plot(range(GENERATIONS), max_fitness_history, label='Max Fitness')
plt.xlabel('Generation')
plt.ylabel('Fitness')
plt.title('Evolutionary Simulation')
plt.legend()
plt.show()
if __name__ == "__main__":
simulate()
Create a New Python Repl:
Add Dependencies:
matplotlib is listed in the requirements.txt file.Add the Code:
main.py file.Run the Repl:
Visualization: For more interactive visualizations, consider using libraries like pygame or plotly. However, note that some might have limitations on Replit's free tier.
Complex Traits: Instead of binary genes, use real numbers to represent traits, enabling more nuanced evolution.
Environmental Factors: Introduce changing environments that affect the fitness function, simulating shifting selection pressures.
Genetic Diversity: Implement mechanisms to maintain or measure genetic diversity within the population.
Performance Optimization: For larger populations or more generations, consider optimizing the code for better performance.
This simulation provides a foundational understanding of evolutionary principles. You can expand upon it by introducing more complex genetics, varying environmental conditions, or different selection strategies. Replit's free tier is sufficient for running and visualizing this simulation, making it an excellent platform for experimenting and learning.
Feel free to modify the parameters and observe how they affect the evolution of the population!
Not yet included in a published release.