Sure! I can help you create a simple evolution simulator in Python with visualization using matplotlib. This simulator will model a population of creatures that evolve over generations based on a fitness function. Since you're using Replit without a subscription, this solution avoids heavy dependencies and runs smoothly in the browser.
Overview
- Population: Each creature has a genome represented by a list of genes (binary in this case).
- Fitness Function: Determines how "fit" each creature is based on their genome.
- Selection: Higher fitness creatures are more likely to reproduce.
- Crossover & Mutation: Gitomes of parents are combined and mutated to create offspring.
- Visualization: Displays the average fitness over generations.
Step-by-Step Guide
1. Setting Up Replit
- Go to Replit and create a new Repl using the Python template.
- In the
main.py file, you'll write the simulation code.
- Ensure that
matplotlib is included in your Repl's packages. Replit usually has it pre-installed, but if not, you can add it by clicking on the "Packages" icon on the left sidebar and searching for matplotlib.
2. The Code
Here's the complete code for the evolution simulator:
import matplotlib.pyplot as plt
import random
import matplotlib.animation as animation
# Parameters
POPULATION_SIZE = 50
GENOME_LENGTH = 20
GENERATIONS = 100
MUTATION_RATE = 0.01
TARGET_GENOME = [1] * GENOME_LENGTH # Optimal genome
# Initialize population with random genomes
def initialize_population():
population = []
for _ in range(POPULATION_SIZE):
genome = [random.randint(0, 1) for _ in range(GENOME_LENGTH)]
population.append(genome)
return population
# Fitness function: number of matching genes to TARGET_GENOME
def fitness(genome):
return sum(1 for gene, target in zip(genome, TARGET_GENOME) if gene == target)
# Selection: Roulette Wheel Selection
def select_parent(population, fitnesses):
total_fitness = sum(fitnesses)
if total_fitness == 0:
return random.choice(population)
pick = random.uniform(0, total_fitness)
current = 0
for genome, fit in zip(population, fitnesses):
current += fit
if current > pick:
return genome
return population[-1]
# Crossover: Single point
def crossover(parent1, parent2):
point = random.randint(1, GENOME_LENGTH - 1)
child = parent1[:point] + parent2[point:]
return child
# Mutation
def mutate(genome):
mutated = []
for gene in genome:
if random.random() < MUTATION_RATE:
mutated.append(1 - gene) # Flip gene
else:
mutated.append(gene)
return mutated
# Evolve population
def evolve(population):
fitnesses = [fitness(genome) for genome in population]
new_population = []
for _ in range(POPULATION_SIZE):
parent1 = select_parent(population, fitnesses)
parent2 = select_parent(population, fitnesses)
child = crossover(parent1, parent2)
child = mutate(child)
new_population.append(child)
return new_population, fitnesses
# Visualization setup
fig, ax = plt.subplots()
plt.title("Evolution Simulator")
plt.xlabel("Generation")
plt.ylabel("Average Fitness")
x_data = []
y_data = []
line, = ax.plot([], [], lw=2)
def init():
ax.set_xlim(0, GENERATIONS)
ax.set_ylim(0, GENOME_LENGTH)
return line,
def animate(i):
global population
if i < GENERATIONS:
population, fitnesses = evolve(population)
avg_fitness = sum(fitnesses) / POPULATION_SIZE
x_data.append(i)
y_data.append(avg_fitness)
line.set_data(x_data, y_data)
return line,
# Initialize population
population = initialize_population()
# Create animation
ani = animation.FuncAnimation(fig, animate, init_func=init,
frames=GENERATIONS, interval=200, blit=True)
plt.show()
3. Understanding the Code
- Initialization: The population is initialized with random genomes (lists of 0s and 1s).
- Fitness Evaluation: The fitness of each genome is the number of genes matching the
TARGET_GENOME.
- Selection: Uses Roulette Wheel Selection where genomes with higher fitness have a higher chance of being selected as parents.
- Crossover: Combines two parent genomes at a random crossover point to produce a child genome.
- Mutation: Each gene has a small chance (
MUTATION_RATE) to flip.
- Evolution Loop: For each generation, a new population is created using selection, crossover, and mutation. The average fitness is recorded for visualization.
- Visualization: Uses
matplotlib's animation to plot the average fitness over generations.
4. Running the Simulation
- Paste the above code into your
main.py in Replit.
- Click the "Run" button at the top.
- A window should appear showing the evolution of the average fitness over generations.
5. Customizing the Simulator
You can tweak the simulation parameters at the top of the script to see how they affect evolution:
POPULATION_SIZE: Number of creatures in each generation.
GENOME_LENGTH: Length of each creature's genome.
GENERATIONS: Number of generations to simulate.
MUTATION_RATE: Probability of each gene mutating.
TARGET_GENOME: The optimal genome that creatures are evolving towards.
6. Example Output
When you run the simulation, you should see a plot where the average fitness increases over generations, indicating that the population is evolving towards the target genome.
[image: Evolution Simulator Example] open (Replace with an actual image if available)
Conclusion
This simple evolution simulator demonstrates the basics of genetic algorithms and how populations can evolve over time based on selection, crossover, and mutation. You can expand upon this by introducing more complex fitness functions, multiple traits, or even visual representations of each creature. Enjoy experimenting with evolutionary concepts!