-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathevolution-sim.py
More file actions
46 lines (34 loc) · 1.45 KB
/
Copy pathevolution-sim.py
File metadata and controls
46 lines (34 loc) · 1.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#!/usr/bin/env python3
"""Minimal evolution simulator. Fitness-based selection over generations."""
import random
def evolve(population, fitness_fn, generations=10, mutation_rate=0.1):
"""Run evolution simulation."""
for gen in range(generations):
# Evaluate fitness
scored = [(ind, fitness_fn(ind)) for ind in population]
scored.sort(key=lambda x: x[1], reverse=True)
# Select top 50%
survivors = [ind for ind, _ in scored[:len(scored)//2]]
# Reproduce
offspring = []
while len(offspring) < len(population) - len(survivors):
parent = random.choice(survivors)
child = mutate(parent, mutation_rate)
offspring.append(child)
population = survivors + offspring
best_fitness = scored[0][1]
print(f"Gen {gen}: best fitness = {best_fitness:.2f}")
return population
def mutate(individual, rate):
"""Mutate individual with given probability."""
return [gene + random.gauss(0, 0.1) if random.random() < rate else gene
for gene in individual]
if __name__ == "__main__":
# Example: evolve toward target [1, 2, 3, 4, 5]
target = [1, 2, 3, 4, 5]
def fitness(ind):
return -sum((a - b)**2 for a, b in zip(ind, target))
pop = [[random.random() * 10 for _ in range(5)] for _ in range(20)]
final = evolve(pop, fitness, generations=50)
print(f"\nBest individual: {final[0]}")
print(f"Target: {target}")