Create a genetic algorithm to evolve prey and predators in Python.
- User
Create a genetic algorithm to evolve prey and predators in Python.
- Assistant
Create a genetic algorithm to evolve prey and predators in Python.
Creating a genetic algorithm (GA) to evolve both prey and predators involves simulating an ecosystem where both species adapt over generations based on their interactions. Below is a Python implementation that demonstrates this concept. The simulation includes:
Prey and Predator classes with genomes.import random
import math
import copy
import matplotlib.pyplot as plt
# Parameters
WIDTH, HEIGHT = 100, 100
NUM_PREY = 50
NUM_PREDATORS = 20
GENERATIONS = 50
TIME_STEPS = 200
# Genetic Algorithm Parameters
PREY_MUTATION_RATE = 0.1
PREDATOR_MUTATION_RATE = 0.1
ELITISM = 0.1
# Genome Traits
PREY_TRAITS = ['speed', 'vision']
PREDATOR_TRAITS = ['speed', 'vision', 'attack_power']
def distance(a, b):
return math.hypot(a.x - b.x, a.y - b.y)
class Agent:
def __init__(self, genome, x=None, y=None):
self.genome = genome
self.x = x if x is not None else random.uniform(0, WIDTH)
self.y = y if y is not None else random.uniform(0, HEIGHT)
self.alive = True
class Prey(Agent):
def __init__(self, genome=None, x=None, y=None):
if genome is None:
genome = {
'speed': random.uniform(1, 5),
'vision': random.uniform(5, 20)
}
super().__init__(genome, x, y)
self.fitness = 0
def move(self, predators):
# Simple avoidance behavior
nearest_pred = None
min_dist = float('inf')
for predator in predators:
dist = distance(self, predator)
if dist < min_dist and dist < self.genome['vision']:
min_dist = dist
nearest_pred = predator
if nearest_pred:
# Move away from predator
angle = math.atan2(self.y - nearest_pred.y, self.x - nearest_pred.x)
self.x += self.genome['speed'] * math.cos(angle)
self.y += self.genome['speed'] * math.sin(angle)
else:
# Random movement
angle = random.uniform(0, 2 * math.pi)
self.x += self.genome['speed'] * math.cos(angle)
self.y += self.genome['speed'] * math.sin(angle)
# Keep within bounds
self.x = max(0, min(WIDTH, self.x))
self.y = max(0, min(HEIGHT, self.y))
class Predator(Agent):
def __init__(self, genome=None, x=None, y=None):
if genome is None:
genome = {
'speed': random.uniform(1, 7),
'vision': random.uniform(10, 30),
'attack_power': random.uniform(1, 5)
}
super().__init__(genome, x, y)
self.fitness = 0
def move(self, preys):
# Simple hunting behavior
nearest_prey = None
min_dist = float('inf')
for prey in preys:
dist = distance(self, prey)
if dist < min_dist and dist < self.genome['vision']:
min_dist = dist
nearest_prey = prey
if nearest_prey:
# Move towards prey
angle = math.atan2(nearest_prey.y - self.y, nearest_prey.x - self.x)
self.x += self.genome['speed'] * math.cos(angle)
self.y += self.genome['speed'] * math.sin(angle)
else:
# Random movement
angle = random.uniform(0, 2 * math.pi)
self.x += self.genome['speed'] * math.cos(angle)
self.y += self.genome['speed'] * math.sin(angle)
# Keep within bounds
self.x = max(0, min(WIDTH, self.x))
self.y = max(0, min(HEIGHT, self.y))
def evaluate_fitness(preys, predators):
for prey in preys:
if prey.alive:
prey.fitness += 1 # Survived this time step
for predator in predators:
predator.fitness += 1 # Survived this time step
def reproduce(population, elitism, mutation_rate, traits):
# Sort population by fitness
population = sorted(population, key=lambda agent: agent.fitness, reverse=True)
# Elitism
num_elites = int(elitism * len(population))
new_population = population[:num_elites]
# Generate rest of the population
while len(new_population) < len(population):
parent1 = select_agent(population)
parent2 = select_agent(population)
child_genome = crossover(parent1.genome, parent2.genome)
child_genome = mutate(child_genome, mutation_rate, traits)
if isinstance(parent1, Prey):
child = Prey(genome=child_genome)
else:
child = Predator(genome=child_genome)
new_population.append(child)
return new_population
def select_agent(population):
total_fitness = sum(agent.fitness for agent in population)
if total_fitness == 0:
return random.choice(population)
pick = random.uniform(0, total_fitness)
current = 0
for agent in population:
current += agent.fitness
if current > pick:
return agent
return random.choice(population)
def crossover(genome1, genome2):
child_genome = {}
for key in genome1:
child_genome[key] = random.choice([genome1[key], genome2[key]])
return child_genome
def mutate(genome, mutation_rate, traits):
for key in genome:
if random.random() < mutation_rate:
# Simple mutation: add a small random value
mutation_value = random.uniform(-0.5, 0.5)
genome[key] += mutation_value
# Ensure traits stay within reasonable bounds
if key == 'speed':
genome[key] = max(0.1, min(10, genome[key]))
elif key == 'vision':
genome[key] = max(1, min(50, genome[key]))
elif key == 'attack_power':
genome[key] = max(0.1, min(10, genome[key]))
return genome
def main():
# Initialize populations
preys = [Prey() for _ in range(NUM_PREY)]
predators = [Predator() for _ in range(NUM_PREDATORS)]
prey_history = []
predator_history = []
for generation in range(GENERATIONS):
print(f"Generation {generation+1}")
# Reset fitness
for prey in preys:
prey.fitness = 0
prey.alive = True
for predator in predators:
predator.fitness = 0
for time_step in range(TIME_STEPS):
# Prey move
for prey in preys:
if prey.alive:
prey.move(predators)
# Predator move
for predator in predators:
predator.move([prey for prey in preys if prey.alive])
# Check for predation
for predator in predators:
for prey in preys:
if prey.alive and distance(predator, prey) < 1.0:
prey.alive = False
predator.fitness += predator.genome['attack_power']
# Evaluate fitness
evaluate_fitness(preys, predators)
# Collect data
avg_prey_fitness = sum(prey.fitness for prey in preys) / len(preys)
avg_predator_fitness = sum(predator.fitness for predator in predators) / len(predators)
prey_history.append(avg_prey_fitness)
predator_history.append(avg_predator_fitness)
print(f"Avg Prey Fitness: {avg_prey_fitness:.2f}, Avg Predator Fitness: {avg_predator_fitness:.2f}")
# Reproduce populations
preys = reproduce(preys, ELITISM, PREY_MUTATION_RATE, PREY_TRAITS)
predators = reproduce(predators, ELITISM, PREDATOR_MUTATION_RATE, PREDATOR_TRAITS)
# Plot results
plt.plot(range(1, GENERATIONS+1), prey_history, label='Prey Average Fitness')
plt.plot(range(1, GENERATIONS+1), predator_history, label='Predator Average Fitness')
plt.xlabel('Generation')
plt.ylabel('Average Fitness')
plt.legend()
plt.show()
if __name__ == "__main__":
main()
Parameters: Define simulation parameters such as the environment size, population sizes, number of generations, and genetic algorithm parameters.
Agent Classes:
Agent: Base class for common attributes like position and genome.Prey: Inherits from Agent, includes behavior for movement to avoid predators.Predator: Inherits from Agent, includes behavior for hunting prey.Movement Logic:
Fitness Evaluation:
Genetic Operations:
Reproduction: Create a new population by selecting parents, performing crossover and mutation, and applying elitism to carry over top-performing individuals unchanged.
Main Simulation Loop:
Ensure you have the required libraries installed. You can install matplotlib if it's not already installed:
pip install matplotlib
Run the script using Python 3:
python predator_prey_ga.py
This will execute the simulation and display a plot showing the evolution of average fitness for both prey and predators over generations.
This implementation provides a foundational framework for simulating and evolving predator and prey populations using a genetic algorithm in Python. It demonstrates the basic principles of selection, crossover, and mutation in the context of an interactive ecosystem. You can build upon this foundation to create more complex and realistic simulations.
Not yet included in a published release.