Certainly! Below is a self-contained Python code for a simple yet thoughtful evolution simulator tailored for a Kaggle notebook environment. This simulator models a population of organisms with specific traits, applies natural selection based on fitness, and visualizes the evolution of traits over generations using matplotlib.
Key Features:
- Population Initialization: Each organism has a trait value (e.g., height) initialized randomly.
- Fitness Calculation: Fitness is determined based on how close an organism's trait is to an optimal value.
- Selection: The top-performing organisms are selected to reproduce.
- Reproduction: Selected organisms produce offspring with slight variations (mutations) in their traits.
- Visualization: The distribution of traits across generations is visualized using histograms and line plots.
You can run this code directly in a Kaggle notebook without needing to download any additional resources.
# Import necessary libraries
import numpy as np
import matplotlib.pyplot as plt
from IPython.display import clear_output
from tqdm.notebook import tqdm
import random
# Set random seed for reproducibility
np.random.seed(42)
random.seed(42)
# Parameters of the simulation
POPULATION_SIZE = 100
NUM_GENERATIONS = 100
MUTATION_RATE = 0.05
SELECTION_RATE = 0.2
INITIAL_MEAN = 50
INITIAL_STD = 10
OPTIMAL_TRAIT = 70
FITNESS_STRENGTH = 1.0 # How strongly fitness depends on trait
# Initialize the population with traits drawn from a normal distribution
population = np.random.normal(INITIAL_MEAN, INITIAL_STD, POPULATION_SIZE)
# To store statistics
history = {
'mean': [],
'std': [],
'generation': []
}
# Prepare the plot
plt.ion()
fig, ax = plt.subplots(figsize=(10, 6))
for generation in tqdm(range(NUM_GENERATIONS), desc="Simulating Evolution"):
# Calculate fitness: higher fitness for traits closer to OPTIMAL_TRAIT
fitness = np.exp(-FITNESS_STRENGTH * (population - OPTIMAL_TRAIT)**2)
# Select the top-performing individuals
num_selected = int(SELECTION_RATE * POPULATION_SIZE)
selected_indices = np.argsort(fitness)[-num_selected:]
selected = population[selected_indices]
# Reproduce: create new population
new_population = []
for _ in range(POPULATION_SIZE):
parent = random.choice(selected)
# Apply mutation
if random.random() < MUTATION_RATE:
child = parent + np.random.normal(0, 1)
else:
child = parent
new_population.append(child)
population = np.array(new_population)
# Record statistics
current_mean = np.mean(population)
current_std = np.std(population)
history['mean'].append(current_mean)
history['std'].append(current_std)
history['generation'].append(generation)
# Update visualization every 10 generations
if generation % 10 == 0 or generation == NUM_GENERATIONS - 1:
clear_output(wait=True)
ax.clear()
ax.hist(population, bins=20, alpha=0.7, color='skyblue', edgecolor='black')
ax.axvline(OPTIMAL_TRAIT, color='red', linestyle='dashed', linewidth=2, label='Optimal Trait')
ax.set_title(f'Generation {generation}')
ax.set_xlabel('Trait Value')
ax.set_ylabel('Frequency')
ax.legend()
plt.show()
# Final visualization of evolution over generations
plt.figure(figsize=(12, 6))
plt.plot(history['generation'], history['mean'], label='Mean Trait')
plt.fill_between(history['generation'],
np.array(history['mean']) - np.array(history['std']),
np.array(history['mean']) + np.array(history['std']),
color='b', alpha=0.2, label='Std Dev')
plt.axhline(OPTIMAL_TRAIT, color='red', linestyle='dashed', linewidth=2, label='Optimal Trait')
plt.title('Evolution of Trait Over Generations')
plt.xlabel('Generation')
plt.ylabel('Trait Value')
plt.legend()
plt.grid(True)
plt.show()
Explanation of the Code:
-
Imports and Initialization:
- Libraries: We use
numpy for numerical operations, matplotlib for plotting, tqdm for progress bars, and random for stochastic processes.
- Parameters: Define key simulation parameters such as population size, number of generations, mutation rate, selection rate, initial trait distribution, optimal trait value, and fitness strength.
-
Population Initialization:
- The initial population's traits are sampled from a normal distribution with a specified mean and standard deviation.
-
Simulation Loop:
- Fitness Calculation: Fitness is calculated using an exponential decay function based on the squared difference between an organism's trait and the optimal trait. This ensures that traits closer to the optimal value have higher fitness.
- Selection: A fraction of the top-performing individuals (based on fitness) are selected to reproduce.
- Reproduction and Mutation: Each new individual in the population is a copy of a selected parent, potentially undergoing mutation. Mutation introduces variability by adding a small random value to the parent's trait.
- Statistics Recording: After each generation, the mean and standard deviation of the population's traits are recorded.
-
Visualization:
- Real-time Histogram: Every 10 generations (and the final generation), a histogram of the population's trait distribution is displayed. The optimal trait value is marked with a red dashed line.
- Evolution Plot: After the simulation, a line plot shows how the mean trait value and its standard deviation evolve over generations, highlighting the population's adaptation toward the optimal trait.
Running the Simulator:
-
Kaggle Notebook:
- Copy and paste the above code into a Kaggle notebook cell and execute it. The simulator will display real-time histograms and a final evolution plot.
-
Customization:
- You can modify the parameters (like
POPULATION_SIZE, NUM_GENERATIONS, OPTIMAL_TRAIT, etc.) to observe different evolutionary dynamics.
-
Interpreting Results:
- Observe how the mean trait value approaches the optimal trait over generations, and how the population's diversity changes. The final plot provides insights into the convergence and variability of the population traits.
Potential Enhancements:
- Multiple Traits: Extend the simulator to handle multiple traits per organism, introducing more complex interactions and fitness landscapes.
- Environmental Changes: Implement changing optimal traits over time to simulate dynamic environments.
- Visualization Enhancements: Use more advanced visualization libraries like
seaborn or plotly for interactive plots.
- Data Analysis: Incorporate statistical analyses to evaluate evolutionary trends, such as convergence rates or genetic diversity metrics.
This simulator provides a foundational framework for understanding evolutionary processes and can be expanded to incorporate more sophisticated biological concepts as needed.