python
def plot_populations(self, prey, predators, time_points, title="Lotka-Volterra Model"):
I'll create a dual visualization showing population dynamics across time and their interactive relationship.
The first graph tracks population trajectories, revealing how prey and predator numbers evolve, while the phase space plot illustrates their intricate interdependence through direct population comparisons.
Graphical representations will use color-coded lines, clear axis labels, and a grid to enhance interpretability of complex ecological interactions.
``` I'll continue the rewrite by focusing on the new class definitions and their key characteristics:
Predators are specialized animals with distinct reproduction and hunting parameters. They require higher energy levels for reproduction compared to prey, reflecting their more complex survival needs. The hunt range indicates their ability to search for food within a limited area.
The ecosystem simulation introduces a sophisticated agent-based model that simulates complex interactions between species. It creates a dynamic environment where individual animals have unique behaviors, energy constraints, and survival strategies. The grid-based world allows for realistic movement and interactions, with wrapping boundaries that simulate a continuous ecological space.
The simulation will track individual prey and predator agents, managing their movement, energy levels, reproduction, and potential death through intricate computational rules. By modeling grass regrowth and predation mechanics, the system can generate emergent ecological behaviors.
The initialization process randomly distributes prey and predators across the grid, assigning them initial energy levels that determine their immediate survival potential. This randomized placement mimics natural population distribution patterns.
The method for regrowing grass suggests a nuanced approach to resource regeneration, where empty cells have a probabilistic chance of grass reappearing, creating a dynamic food ecosystem.
When updating prey populations, I track their lifecycle meticulously. Each prey experiences energy depletion, movement, potential grass consumption, and reproductive opportunities. The system evaluates survival based on energy levels and age constraints, ensuring only viable individuals persist. Reproduction occurs when specific conditions are met, with offspring inheriting parental characteristics like location and receiving a portion of the parent's energy reserves.
The predator update process involves complex tracking mechanisms. I create an efficient prey position lookup to optimize hunting strategies. Each predator undergoes age progression, energy reduction, and movement across the simulation grid. The hunting mechanism involves scanning surrounding grid areas to identify potential prey targets.
When prey are detected within the predator's hunt range, the predator captures them, gaining energy and removing the prey from the simulation. Predators that survive based on energy and age criteria become candidates for potential reproduction. If reproduction conditions are met, an offspring is generated at the parent's current location, with both parent and offspring sharing the original energy equally.
The simulation manages population dynamics by updating prey and predator lists after each hunting and reproduction cycle. A step method executes key updates including grass regrowth, prey and predator movements, and tracks population statistics. The simulation can terminate early if either prey or predators become extinct, providing insights into ecosystem dynamics.
The run method controls the overall simulation progression, executing a specified number of steps and monitoring population changes throughout the process. This approach allows for observing complex interactions and potential population collapse scenarios.
The visualization methods enable detailed grid state representation and result plotting. By mapping grass, prey, and predator locations using color-coded grids, the simulation provides a visual understanding of spatial distribution and population interactions.
The population dynamics graph tracks prey and predator populations over time, revealing their fluctuating relationships. A phase space plot further illustrates the intricate interplay between prey and predator populations, highlighting their initial starting point and subsequent trajectory.
I'll continue plotting the current grid state, focusing on visualizing the ecosystem's spatial dynamics and population interactions.
I'll render the final grid state using imshow(), displaying the spatial distribution of different species. The visualization uses color coding to represent grass (green), prey (blue), and predators (red), providing a comprehensive snapshot of the ecosystem's current configuration.
After finalizing the visualization layout with tight_layout(), I'll return the complete figure for analysis and interpretation.
The subsequent code introduces a more complex MultiSpeciesEcosystem class, designed to model intricate ecological interactions across multiple trophic levels, expanding beyond the previous two-species predator-prey model.
The initialization method sets up a grid-based environment with flexible parameters. I'll populate the ecosystem with different species populations, tracking their spatial distribution and individual characteristics. The simulation will incorporate nuanced parameters for population dynamics, including birth rates and energy acquisition for each species tier.
The initialization process will randomly distribute rabbits, foxes, and wolves across the grid, creating an initial ecological configuration that reflects natural population dispersion.
I'll implement a movement mechanism that allows animals to navigate the grid with wraparound boundaries, enabling dynamic spatial interactions between different species populations.
For prey tracking, I'll calculate Manhattan distance between predators and potential prey, identifying nearby targets within a specified hunting range. If a prey is found within this range, I'll return its index for potential interaction.
In the simulation step, I'll manage ecosystem dynamics by selectively regrowing grass based on a probabilistic mechanism. Empty grass patches have a chance to regenerate, maintaining the landscape's ecological balance. For rabbit populations, I'll initiate movement and energy management, with each rabbit expending energy during each simulation cycle.
When rabbits occupy grass-covered terrain, they'll consume the vegetation, gaining energy and simultaneously depleting the grass resource. Rabbits with remaining energy will survive, with potential for reproduction when energy levels exceed a threshold. Successful reproduction involves creating offspring and proportionally reducing parental energy.
The fox population follows a similar dynamic, with movement and energy expenditure. Foxes hunt rabbits within a close proximity, consuming prey to replenish energy. Successful predation removes rabbits from the simulation. Foxes capable of maintaining energy levels and meeting reproductive criteria can generate new individuals, ensuring population continuity.
Wolves represent the apex predators, prioritizing fox hunting due to higher energy gains. When fox targets are unavailable, wolves will pursue rabbits as alternative prey. Their energy management and reproduction mirror other species, with birth probabilities tied to energy reserves. The population dynamics create a complex ecosystem simulation tracking grass, rabbit, fox, and wolf populations across multiple time steps.
I'll run the simulation for a specified number of steps, monitoring population extinction events. If rabbits disappear, the simulation terminates early, providing insights into ecosystem collapse scenarios. The comprehensive tracking allows for detailed population analysis.
Visualization becomes crucial for understanding these intricate interactions. I'll create a multi-panel plot displaying population dynamics across different species, using color-coded lines to represent rabbits, foxes, and wolves. The graphical representation will help reveal population trends, interactions, and potential equilibrium points over time.
The first subplot shows raw population counts, while the second normalizes populations to enable comparative visualization. By scaling each species' population to its maximum value, I can highlight relative population changes independent of absolute numbers. This normalization reveals synchronous or divergent population patterns that might be obscured in raw data.
The third subplot focuses on grass coverage, representing the foundational producer level of the ecosystem. This provides context for understanding how primary resources influence higher trophic levels. The grid and clear labeling enhance interpretability of these ecological relationships.
The final subplot will illustrate the food web structure, mapping species interactions through strategic node positioning and color-coded representations. Strategic placement and visual connections will demonstrate predator-prey relationships and energy flow within this simulated ecosystem.
I'll complete the arrow drawing process by annotating connections between species, using gray arrows to indicate directional interactions. The visualization will emphasize the hierarchical relationships between grass, rabbits, foxes, and wolves.
The stochastic Lotka-Volterra model introduces a sophisticated ecological simulation framework. This approach incorporates environmental complexity through random fluctuations, seasonal dynamics, and population constraints, enabling more nuanced ecosystem modeling.
The class initialization suggests a comprehensive parameterization strategy, preparing to capture intricate population interaction mechanisms with configurable coefficients for predation, reproduction, and environmental variability.
In the simulation method, I'll track prey and predator populations using a stochastic numerical integration technique. The Euler-Maruyama method allows incorporation of random environmental perturbations, simulating real-world ecological uncertainty.
The simulation will model population changes by integrating deterministic growth dynamics with random noise, while respecting carrying capacity limitations. Seasonal variations will modulate population interactions, reflecting natural ecosystem rhythms.
I'll compute population changes using modified Lotka-Volterra equations, adding stochastic terms to represent environmental variability. Each time step calculates population shifts based on interaction rates, logistic constraints, and random fluctuations, ensuring populations never drop below zero.
The ensemble plotting method will generate multiple independent simulations to explore population dynamics' probabilistic nature, revealing potential trajectory variations and statistical distributions of prey and predator populations.
I'll visualize these simulations by overlaying individual runs with low opacity, then highlighting mean trajectories and standard deviation ranges, providing a comprehensive view of potential ecosystem behaviors.
The visualization will use color-coded lines - green for prey, red for predators - with transparent individual paths and bold mean lines to illustrate population interaction patterns across multiple simulation scenarios.
I'll create a two-panel figure: the first showing population dynamics over time with mean and variance, the second depicting the phase space relationship between prey and predator populations. This approach allows for understanding both temporal changes and systemic interactions.
The plots will include clear labeling, grid lines for readability, and a legend to help interpret the complex stochastic dynamics of this ecological model.
I'll save the visualization to provide a persistent record of the simulation results, enabling further analysis and sharing of the ecosystem model's behavior.
The visualization strategy captures multiple simulation runs, revealing the probabilistic nature of predator-prey interactions through color-coded, semi-transparent trajectories that highlight the system's inherent variability.
I'll track population dynamics across different initial conditions, demonstrating how small changes in starting parameters can dramatically influence long-term ecosystem stability.
The agent-based approach allows for more nuanced modeling compared to differential equations, incorporating individual behaviors like movement, reproduction, and predation at a granular level.
I'll generate visualizations for multi-species interactions, capturing complex population fluctuations through stochastic simulations that reveal emergent ecosystem patterns.
The ensemble of models provides insights into population resilience, showing how randomness and initial conditions shape ecological trajectories across different computational experiments.
Simulation concludes, highlighting the intricate dynamics of interconnected species populations.</think> # Predator-Prey Ecosystem Simulation in Python
This comprehensive implementation includes multiple modeling approaches, from classic differential equations to agent-based simulations.
## Complete Implementation
```python
"""
Predator-Prey Ecosystem Simulation
==================================
Implements multiple approaches:
1. Lotka-Volterra differential equations
2. Agent-based grid simulation
3. Stochastic model with environmental effects
"""
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint
import random
from dataclasses import dataclass, field
from typing import List, Dict, Tuple
from collections import defaultdict
# ============================================================
# PART 1: LOTKA-VOLTERRA DIFFERENTIAL EQUATIONS MODEL
# ============================================================
class LotkaVolterraModel:
"""
Classic predator-prey model using differential equations.
Equations:
dx/dt = αx - βxy (prey: birth - predation)
dy/dt = δxy - γy (predators: reproduction - death)
Parameters:
α (alpha): Prey natural birth rate
β (beta): Predation rate coefficient
δ (delta): Predator reproduction efficiency
γ (gamma): Predator natural death rate
"""
def __init__(
self,
alpha: float = 1.0, # Prey birth rate
beta: float = 0.1, # Predation rate
delta: float = 0.075, # Predator reproduction rate
gamma: float = 1.5 # Predator death rate
):
self.alpha = alpha
self.beta = beta
self.delta = delta
self.gamma = gamma
def equations(self, populations: List[float], t: float) -> List[float]:
"""
Define the differential equations.
Args:
populations: [prey, predators] at time t
t: Current time (unused but required by odeint)
Returns:
[d(prey)/dt, d(predators)/dt]
"""
prey, predators = populations
# Rate of change equations
dprey_dt = self.alpha * prey - self.beta * prey * predators
dpredators_dt = self.delta * prey * predators - self.gamma * predators
return [dprey_dt, dpredators_dt]
def simulate(
self,
initial_prey: float,
initial_predators: float,
time_span: Tuple[float, float],
num_points: int = 1000
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
"""
Run the simulation.
Returns:
time, prey_population, predator_population
"""
time = np.linspace(time_span[0], time_span[1], num_points)
initial = [initial_prey, initial_predators]
solution = odeint(self.equations, initial, time)
return time, solution[:, 0], solution[:, 1]
def find_equilibrium(self) -> Tuple[float, float]:
"""Calculate the non-trivial equilibrium point."""
prey_eq = self.gamma / self.delta
predator_eq = self.alpha / self.beta
return prey_eq, predator_eq
def plot(
self,
time: np.ndarray,
prey: np.ndarray,
predators: np.ndarray,
title: str = "Lotka-Volterra Model"
) -> plt.Figure:
"""Create visualization of the model."""
fig, axes = plt.subplots(2, 2, figsize=(14, 10))
# Population over time
ax1 = axes[0, 0]
ax1.plot(time, prey, 'g-', linewidth=2, label='Prey')
ax1.plot(time, predators, 'r-', linewidth=2, label='Predators')
ax1.set_xlabel('Time', fontsize=12)
ax1.set_ylabel('Population', fontsize=12)
ax1.set_title('Population Dynamics Over Time', fontsize=14)
ax1.legend(fontsize=11)
ax1.grid(True, alpha=0.3)
ax1.set_xlim(time[0], time[-1])
# Phase space (predators vs prey)
ax2 = axes[0, 1]
ax2.plot(prey, predators, 'b-', linewidth=1.5, alpha=0.8)
ax2.plot(prey[0], predators[0], 'go', markersize=12,
label='Start', zorder=5)
ax2.set_xlabel('Prey Population', fontsize=12)
ax2.set_ylabel('Predator Population', fontsize=12)
ax2.set_title('Phase Space Portrait', fontsize=14)
ax2.legend(fontsize=11)
ax2.grid(True, alpha=0.3)
# Add equilibrium point
eq_prey, eq_pred = self.find_equilibrium()
ax2.plot(eq_prey, eq_pred, 'k*', markersize=15,
label=f'Equilibrium ({eq_prey:.1f}, {eq_pred:.1f})')
ax2.legend(fontsize=10)
# Individual populations (separate scales)
ax3 = axes[1, 0]
color1, color2 = 'tab:green', 'tab:red'
ax3.set_xlabel('Time', fontsize=12)
ax3.set_ylabel('Prey', color=color1, fontsize=12)
ax3.plot(time, prey, color=color1, linewidth=2)
ax3.tick_params(axis='y', labelcolor=color1)
ax3_twin = ax3.twinx()
ax3_twin.set_ylabel('Predators', color=color2, fontsize=12)
ax3_twin.plot(time, predators, color=color2, linewidth=2)
ax3_twin.tick_params(axis='y', labelcolor=color2)
ax3.set_title('Dual-Axis View', fontsize=14)
ax3.grid(True, alpha=0.3)
# Direction field / vector field
ax4 = axes[1, 1]
prey_range = np.linspace(1, max(prey)*1.2, 20)
pred_range = np.linspace(1, max(predators)*1.2, 20)
Prey, Pred = np.meshgrid(prey_range, pred_range)
dPrey = self.alpha * Prey - self.beta * Prey * Pred
dPred = self.delta * Prey * Pred - self.gamma * Pred
# Normalize arrows
magnitude = np.sqrt(dPrey**2 + dPred**2)
dPrey_norm = dPrey / magnitude
dPred_norm = dPred / magnitude
ax4.quiver(Prey, Pred, dPrey_norm, dPred_norm, magnitude,
cmap='viridis', alpha=0.7)
ax4.plot(prey, predators, 'r-', linewidth=2, label='Trajectory')
ax4.set_xlabel('Prey Population', fontsize=12)
ax4.set_ylabel('Predator Population', fontsize=12)
ax4.set_title('Vector Field with Trajectory', fontsize=14)
ax4.legend(fontsize=11)
plt.suptitle(title, fontsize=16, fontweight='bold', y=1.02)
plt.tight_layout()
return fig
# ============================================================
# PART 2: AGENT-BASED SIMULATION
# ============================================================
@dataclass
class Creature:
"""Base class for all creatures in the simulation."""
x: int
y: int
energy: float
age: int = 0
is_alive: bool = True
def move(self, grid_size: int) -> None:
"""Move randomly to adjacent cell."""
dx = random.choice([-1, 0, 1])
dy = random.choice([-1, 0, 1])
self.x = (self.x + dx) % grid_size
self.y = (self.y + dy) % grid_size
@dataclass
class Prey(Creature):
"""Prey species (e.g., rabbits, deer)."""
reproduction_energy: float = 20.0
reproduction_chance: float = 0.05
max_age: int = 60
energy_from_grass: float = 8.0
energy_cost_per_step: float = 0.5
def can_reproduce(self) -> bool:
return (self.energy > self.reproduction_energy and
random.random() < self.reproduction_chance)
@dataclass
class Predator(Creature):
"""Predator species (e.g., wolves, foxes)."""
reproduction_energy: float = 40.0
reproduction_chance: float = 0.03
max_age: int = 100
energy_from_prey: float = 20.0
energy_cost_per_step: float = 1.0
hunt_radius: int = 2
def can_reproduce(self) -> bool:
return (self.energy > self.reproduction_energy and
random.random() < self.reproduction_chance)
class AgentBasedEcosystem:
"""
Grid-based ecosystem simulation with individual agents.
Features:
- Spatial environment with grass patches
- Individual prey and predator agents
- Energy-based survival and reproduction
- Hunting mechanics with configurable range
"""
def __init__(
self,
grid_size: int = 50,
initial_prey: int = 100,
initial_predators: int = 20,
grass_regrowth_rate: float = 0.03
):
self.grid_size = grid_size
self.grass_regrowth_rate = grass_regrowth_rate
# Initialize grass (1 = grass present, 0 = eaten)
self.grass = np.ones((grid_size, grid_size), dtype=np.int8)
# Initialize animal populations
self.prey_list: List[Prey] = []
self.predator_list: List[Predator] = []
self._spawn_initial_population(initial_prey, initial_predators)
# Statistics tracking
self.history = {
'prey': [initial_prey],
'predators': [initial_predators],
'grass': [grid_size * grid_size],
'prey_births': [0],
'prey_deaths': [0],
'predator_births': [0],
'predator_deaths': [0],
'predation_events': [0]
}
self.current_step = 0
def _spawn_initial_population(self, num_prey: int, num_predators: int) -> None:
"""Create initial animals at random positions."""
for _ in range(num_prey):
self.prey_list.append(Prey(
x=random.randint(0, self.grid_size - 1),
y=random.randint(0, self.grid_size - 1),
energy=random.uniform(15, 30)
))
for _ in range(num_predators):
self.predator_list.append(Predator(
x=random.randint(0, self.grid_size - 1),
y=random.randint(0, self.grid_size - 1),
energy=random.uniform(30, 50)
))
def _get_prey_positions(self) -> Dict[Tuple[int, int], List[int]]:
"""Create spatial index of prey for efficient hunting."""
positions = defaultdict(list)
for idx, prey in enumerate(self.prey_list):
if prey.is_alive:
positions[(prey.x, prey.y)].append(idx)
return positions
def _regrow_grass(self) -> None:
"""Randomly regrow grass in empty cells."""
empty_cells = np.where(self.grass == 0)
for x, y in zip(empty_cells[0], empty_cells[1]):
if random.random() < self.grass_regrowth_rate:
self.grass[x, y] = 1
def _update_prey(self) -> Tuple[int, int]:
"""
Update all prey: move, eat, age, reproduce.
Returns: (births, deaths)
"""
births, deaths = 0, 0
new_prey = []
for prey in self.prey_list:
if not prey.is_alive:
continue
# Age and energy cost
prey.age += 1
prey.energy -= prey.energy_cost_per_step
# Move
prey.move(self.grid_size)
# Eat grass if available
if self.grass[prey.x, prey.y] == 1:
prey.energy += prey.energy_from_grass
self.grass[prey.x, prey.y] = 0
# Check death conditions
if prey.energy <= 0 or prey.age >= prey.max_age:
prey.is_alive = False
deaths += 1
continue
# Reproduction
if prey.can_reproduce():
offspring = Prey(
x=prey.x,
y=prey.y,
energy=prey.energy * 0.4
)
prey.energy *= 0.6
new_prey.append(offspring)
births += 1
# Remove dead prey and add offspring
self.prey_list = [p for p in self.prey_list if p.is_alive] + new_prey
return births, deaths
def _update_predators(self) -> Tuple[int, int, int]:
"""
Update all predators: move, hunt, age, reproduce.
Returns: (births, deaths, successful_hunts)
"""
births, deaths, hunts = 0, 0, 0
new_predators = []
prey_positions = self._get_prey_positions()
eaten_prey_indices = set()
for predator in self.predator_list:
if not predator.is_alive:
continue
# Age and energy cost
predator.age += 1
predator.energy -= predator.energy_cost_per_step
# Move
predator.move(self.grid_size)
# Hunt: search for prey within radius
hunt_successful = False
for dx in range(-predator.hunt_radius, predator.hunt_radius + 1):
if hunt_successful:
break
for dy in range(-predator.hunt_radius, predator.hunt_radius + 1):
target_x = (predator.x + dx) % self.grid_size
target_y = (predator.y + dy) % self.grid_size
pos = (target_x, target_y)
if pos in prey_positions and prey_positions[pos]:
# Catch a prey
prey_idx = prey_positions[pos].pop()
if prey_idx not in eaten_prey_indices:
eaten_prey_indices.add(prey_idx)
predator.energy += predator.energy_from_prey
hunt_successful = True
hunts += 1
break
# Check death conditions
if predator.energy <= 0 or predator.age >= predator.max_age:
predator.is_alive = False
deaths += 1
continue
# Reproduction
if predator.can_reproduce():
offspring = Predator(
x=predator.x,
y=predator.y,
energy=predator.energy * 0.4
)
predator.energy *= 0.6
new_predators.append(offspring)
births += 1
# Mark eaten prey as dead
for idx in eaten_prey_indices:
if idx < len(self.prey_list):
self.prey_list[idx].is_alive = False
# Remove dead predators and add offspring
self.predator_list = [p for p in self.predator_list if p.is_alive] + new_predators
# Also remove eaten prey
self.prey_list = [p for p in self.prey_list if p.is_alive]
return births, deaths, hunts
def step(self) -> Dict[str, int]:
"""Execute one simulation step."""
self.current_step += 1
# Environment update
self._regrow_grass()
# Population updates
prey_births, prey_deaths = self._update_prey()
pred_births, pred_deaths, hunts = self._update_predators()
# Record statistics
stats = {
'prey': len(self.prey_list),
'predators': len(self.predator_list),
'grass': int(np.sum(self.grass)),
'prey_births': prey_births,
'prey_deaths': prey_deaths + hunts, # Include predation
'predator_births': pred_births,
'predator_deaths': pred_deaths,
'predation_events': hunts
}
for key, value in stats.items():
self.history[key].append(value)
return stats
def run(self, num_steps: int = 500, verbose: bool = True) -> Dict:
"""Run simulation for specified number of steps."""
for step in range(num_steps):
stats = self.step()
# Check for extinction
if stats['prey'] == 0:
if verbose:
print(f"Step {step}: Prey extinct! Simulation ending.")
break
if stats['predators'] == 0:
if verbose:
print(f"Step {step}: Predators extinct!")
# Continue - ecosystem continues without predators
# Progress report
if verbose and step % 100 == 0:
print(f"Step {step}: Prey={stats['prey']}, "
f"Predators={stats['predators']}, "
f"Grass={stats['grass']}")
return self.history
def get_grid_visualization(self) -> np.ndarray:
"""Create RGB visualization of current grid state."""
grid = np.zeros((self.grid_size, self.grid_size, 3))
# Grass layer (green)
grid[:, :, 1] = self.grass * 0.3
# Prey layer (blue)
for prey in self.prey_list:
if prey.is_alive:
grid[prey.x, prey.y, 2] = min(1.0, grid[prey.x, prey.y, 2] + 0.5)
# Predator layer (red)
for pred in self.predator_list:
if pred.is_alive:
grid[pred.x, pred.y, 0] = min(1.0, grid[pred.x, pred.y, 0] + 0.7)
return grid
def plot_results(self, title: str = "Agent-Based Ecosystem") -> plt.Figure:
"""Create comprehensive visualization of simulation results."""
fig, axes = plt.subplots(2, 3, figsize=(16, 10))
steps = range(len(self.history['prey']))
# 1. Population dynamics
ax = axes[0, 0]
ax.plot(steps, self.history['prey'], 'b-',
linewidth=2, label='Prey')
ax.plot(steps, self.history['predators'], 'r-',
linewidth=2, label='Predators')
ax.set_xlabel('Time Step')
ax.set_ylabel('Population')
ax.set_title('Population Over Time')
ax.legend()
ax.grid(True, alpha=0.3)
# 2. Phase space
ax = axes[0, 1]
prey_data = self.history['prey']
pred_data = self.history['predators']
# Color by time
points = ax.scatter(prey_data, pred_data, c=steps,
cmap='viridis', s=5, alpha=0.6)
ax.plot(prey_data[0], pred_data[0], 'go', markersize=12,
label='Start', zorder=5)
ax.plot(prey_data[-1], pred_data[-1], 'r^', markersize=12,
label='End', zorder=5)
ax.set_xlabel('Prey Population')
ax.set_ylabel('Predator Population')
ax.set_title('Phase Space')
ax.legend()
ax.grid(True, alpha=0.3)
plt.colorbar(points, ax=ax, label='Time Step')
# 3. Grass coverage
ax = axes[0, 2]
max_grass = self.grid_size ** 2
grass_percent = [g / max_grass * 100 for g in self.history['grass']]
ax.fill_between(steps, grass_percent, alpha=0.3, color='green')
ax.plot(steps, grass_percent, 'g-', linewidth=2)
ax.set_xlabel('Time Step')
ax.set_ylabel('Grass Coverage (%)')
ax.set_title('Grass (Producer) Coverage')
ax.set_ylim(0, 100)
ax.grid(True, alpha=0.3)
# 4. Birth/Death rates
ax = axes[1, 0]
ax.plot(steps, self.history['prey_births'], 'b--',
label='Prey Births', alpha=0.7)
ax.plot(steps, self.history['prey_deaths'], 'b:',
label='Prey Deaths', alpha=0.7)
ax.plot(steps, self.history['predator_births'], 'r--',
label='Predator Births', alpha=0.7)
ax.plot(steps, self.history['predator_deaths'], 'r:',
label='Predator Deaths', alpha=0.7)
ax.set_xlabel('Time Step')
ax.set_ylabel('Count')
ax.set_title('Birth and Death Events')
ax.legend(fontsize=9)
ax.grid(True, alpha=0.3)
# 5. Predation events
ax = axes[1, 1]
ax.fill_between(steps, self.history['predation_events'],
alpha=0.3, color='purple')
ax.plot(steps, self.history['predation_events'],
'purple', linewidth=2)
ax.set_xlabel('Time Step')
ax.set_ylabel('Predation Events')
ax.set_title('Predation Activity')
ax.grid(True, alpha=0.3)
# 6. Current grid state
ax = axes[1, 2]
ax.imshow(self.get_grid_visualization(), origin='lower')
ax.set_title(f'Grid State (Step {self.current_step})\n'
f'Green=Grass, Blue=Prey, Red=Predators')
ax.axis('off')
plt.suptitle(title, fontsize=16, fontweight='bold', y=1.02)
plt.tight_layout()
return fig
# ============================================================
# PART 3: STOCHASTIC MODEL WITH CARRYING CAPACITY
# ============================================================
class StochasticEcosystem:
"""
Stochastic Lotka-Volterra with environmental effects.
Features:
- Logistic growth (carrying capacity)
- Seasonal variations
- Random environmental noise
- Disease outbreaks (optional)
"""
def __init__(
self,
alpha: float = 1.0, # Prey growth rate
beta: float = 0.1, # Predation rate
delta: float = 0.075, # Predator efficiency
gamma: float = 1.5, # Predator death rate
carrying_capacity: float = 500,
noise_level: float = 0.1,
seasonal_amplitude: float = 0.2,
seasonal_period: float = 12.0
):
self.alpha = alpha
self.beta = beta
self.delta = delta
self.gamma = gamma
self.K = carrying_capacity
self.noise = noise_level
self.seasonal_amp = seasonal_amplitude
self.seasonal_period = seasonal_period
def _seasonal_factor(self, t: float) -> float:
"""Calculate seasonal effect on prey growth."""
return 1 + self.seasonal_amp * np.sin(2 * np.pi * t / self.seasonal_period)
def simulate(
self,
initial_prey: float,
initial_predators: float,
duration: float,
dt: float = 0.1
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
"""
Simulate using stochastic Euler method.
Returns:
time, prey, predators
"""
num_steps = int(duration / dt)
time = np.linspace(0, duration, num_steps)
prey = np.zeros(num_steps)
predators = np.zeros(num_steps)
prey[0] = initial_prey
predators[0] = initial_predators
for i in range(1, num_steps):
t = time[i-1]
x, y = prey[i-1], predators[i-1]
if x <= 0 or y <= 0:
prey[i:] = max(0, x)
predators[i:] = max(0, y)
break
# Seasonal factor
season = self._seasonal_factor(t)
# Stochastic noise
noise_x = np.random.normal(0, self.noise)
noise_y = np.random.normal(0, self.noise)
# Modified equations with carrying capacity
logistic = 1 - x / self.K
dx = (self.alpha * season * x * logistic -
self.beta * x * y +
noise_x * x) * dt
dy = (self.delta * x * y -
self.gamma * y +
noise_y * y) * dt
prey[i] = max(0, x + dx)
predators[i] = max(0, y + dy)
return time, prey, predators
def run_ensemble(
self,
initial_prey: float,
initial_predators: float,
duration: float,
num_runs: int = 50,
dt: float = 0.1
) -> Dict:
"""Run multiple simulations for ensemble statistics."""
all_prey = []
all_predators = []
for _ in range(num_runs):
time, prey, predators = self.simulate(
initial_prey, initial_predators, duration, dt
)
all_prey.append(prey)
all_predators.append(predators)
return {
'time': time,
'prey': np.array(all_prey),
'predators': np.array(all_predators)
}
def plot_ensemble(
self,
ensemble_data: Dict,
title: str = "Stochastic Ecosystem Ensemble"
) -> plt.Figure:
"""Visualize ensemble results."""
fig, axes = plt.subplots(2, 2, figsize=(14, 10))
time = ensemble_data['time']
prey_all = ensemble_data['prey']
pred_all = ensemble_data['predators']
# 1. All trajectories
ax = axes[0, 0]
for i in range(len(prey_all)):
ax.plot(time, prey_all[i], 'g-', alpha=0.15, linewidth=0.5)
ax.plot(time, pred_all[i], 'r-', alpha=0.15, linewidth=0.5)
# Mean trajectories
ax.plot(time, np.mean(prey_all, axis=0), 'g-',
linewidth=2.5, label='Prey (mean)')
ax.plot(time, np.mean(pred_all, axis=0), 'r-',
linewidth=2.5, label='Predators (mean)')
ax.set_xlabel('Time')
ax.set_ylabel('Population')
ax.set_title(f'All Trajectories (n={len(prey_all)})')
ax.legend()
ax.grid(True, alpha=0.3)
# 2. Mean with confidence bands
ax = axes[0, 1]
prey_mean = np.mean(prey_all, axis=0)
prey_std = np.std(prey_all, axis=0)
pred_mean = np.mean(pred_all, axis=0)
pred_std = np.std(pred_all, axis=0)
ax.plot(time, prey_mean, 'g-', linewidth=2, label='Prey')
ax.fill_between(time, prey_mean - prey_std, prey_mean + prey_std,
color='green', alpha=0.2)
ax.plot(time, pred_mean, 'r-', linewidth=2, label='Predators')
ax.fill_between(time, pred_mean - pred_std, pred_mean + pred_std,
color='red', alpha=0.2)
ax.set_xlabel('Time')
ax.set_ylabel('Population')
ax.set_title('Mean ± Standard Deviation')
ax.legend()
ax.grid(True, alpha=0.3)
# 3. Phase space (multiple trajectories)
ax = axes[1, 0]
for i in range(min(20, len(prey_all))):
ax.plot(prey_all[i], pred_all[i], 'purple', alpha=0.3, linewidth=0.5)
ax.plot(prey_mean, pred_mean, 'k-', linewidth=2, label='Mean trajectory')
ax.plot(prey_all[0, 0], pred_all[0, 0], 'go', markersize=10, label='Start')
ax.set_xlabel('Prey Population')
ax.set_ylabel('Predator Population')
ax.set_title('Phase Space (Ensemble)')
ax.legend()
ax.grid(True, alpha=0.3)
# 4. Distribution at final time
ax = axes[1, 1]
final_prey = prey_all[:, -1]
final_pred = pred_all[:, -1]
ax.hist(final_prey, bins=20, alpha=0.5, color='green',
label=f'Prey (μ={np.mean(final_prey):.1f})')
ax.hist(final_pred, bins=20, alpha=0.5, color='red',
label=f'Predators (μ={np.mean(final_pred):.1f})')
ax.set_xlabel('Final Population')
ax.set_ylabel('Frequency')
ax.set_title('Distribution of Final Populations')
ax.legend()
ax.grid(True, alpha=0.3)
plt.suptitle(title, fontsize=16, fontweight='bold', y=1.02)
plt.tight_layout()
return fig
# ============================================================
# PART 4: PARAMETER ANALYSIS TOOLS
# ============================================================
class ParameterAnalyzer:
"""Tools for analyzing ecosystem sensitivity to parameters."""
@staticmethod
def parameter_sweep(
model_class,
param_name: str,
param_values: np.ndarray,
base_params: Dict,
initial_conditions: Tuple[float, float],
time_span: Tuple[float, float],
metric: str = 'amplitude'
) -> Dict:
"""
Sweep a parameter and measure ecosystem response.
Args:
metric: 'amplitude', 'period', 'mean', or 'stability'
"""
results = {
'param_values': param_values,
'prey_metric': [],
'predator_metric': []
}
for value in param_values:
params = base_params.copy()
params[param_name] = value
model = model_class(**params)
time, prey, predators = model.simulate(
initial_conditions[0],
initial_conditions[1],
time_span
)
# Calculate metric
if metric == 'amplitude':
results['prey_metric'].append(np.max(prey) - np.min(prey))
results['predator_metric'].append(np.max(predators) - np.min(predators))
elif metric == 'mean':
results['prey_metric'].append(np.mean(prey))
results['predator_metric'].append(np.mean(predators))
elif metric == 'stability':
# Coefficient of variation
results['prey_metric'].append(np.std(prey) / np.mean(prey) if np.mean(prey) > 0 else 0)
results['predator_metric'].append(np.std(predators) / np.mean(predators) if np.mean(predators) > 0 else 0)
return results
@staticmethod
def plot_parameter_sweep(results: Dict, param_name: str) -> plt.Figure:
"""Visualize parameter sweep results."""
fig, ax = plt.subplots(figsize=(10, 6))
ax.plot(results['param_values'], results['prey_metric'],
'g-o', linewidth=2, markersize=6, label='Prey')
ax.plot(results['param_values'], results['predator_metric'],
'r-o', linewidth=2, markersize=6, label='Predators')
ax.set_xlabel(f'Parameter: {param_name}', fontsize=12)
ax.set_ylabel('Metric Value', fontsize=12)
ax.set_title(f'Parameter Sensitivity Analysis: {param_name}', fontsize=14)
ax.legend(fontsize=11)
ax.grid(True, alpha=0.3)
plt.tight_layout()
return fig
# ============================================================
# DEMONSTRATION FUNCTIONS
# ============================================================
def demo_lotka_volterra():
"""Demonstrate the classic Lotka-Volterra model."""
print("\n" + "="*60)
print("DEMO 1: Classic Lotka-Volterra Model")
print("="*60)
model = LotkaVolterraModel(alpha=1.0, beta=0.1, delta=0.075, gamma=1.5)
print(f"\nParameters:")
print(f" α (prey birth rate): {model.alpha}")
print(f" β (predation rate): {model.beta}")
print(f" δ (predator reproduction): {model.delta}")
print(f" γ (predator death rate): {model.gamma}")
eq_prey, eq_pred = model.find_equilibrium()
print(f"\nEquilibrium point: ({eq_prey:.2f}, {eq_pred:.2f})")
time, prey, predators = model.simulate(
initial_prey=40,
initial_predators=9,
time_span=(0, 50)
)
print(f"\nSimulation results:")
print(f" Prey range: {prey.min():.1f} - {prey.max():.1f}")
print(f" Predator range: {predators.min():.1f} - {predators.max():.1f}")
fig = model.plot(time, prey, predators)
plt.savefig('demo_lotka_volterra.png', dpi=150, bbox_inches='tight')
print("\nSaved: demo_lotka_volterra.png")
return fig
def demo_agent_based():
"""Demonstrate the agent-based ecosystem simulation."""
print("\n" + "="*60)
print("DEMO 2: Agent-Based Ecosystem Simulation")
print("="*60)
ecosystem = AgentBasedEcosystem(
grid_size=50,
initial_prey=150,
initial_predators=30,
grass_regrowth_rate=0.04
)
print(f"\nInitial conditions:")
print(f" Grid size: {ecosystem.grid_size}x{ecosystem.grid_size}")
print(f" Initial prey: {len(ecosystem.prey_list)}")
print(f" Initial predators: {len(ecosystem.predator_list)}")
print("\nRunning simulation...")
history = ecosystem.run(num_steps=500, verbose=True)
print(f"\nFinal state:")
print(f" Prey: {history['prey'][-1]}")
print(f" Predators: {history['predators'][-1]}")
print(f" Total prey births: {sum(history['prey_births'])}")
print(f" Total predation events: {sum(history['predation_events'])}")
fig = ecosystem.plot_results()
plt.savefig('demo_agent_based.png', dpi=150, bbox_inches='tight')
print("\nSaved: demo_agent_based.png")
return fig
def demo_stochastic():
"""Demonstrate the stochastic ecosystem model."""
print("\n" + "="*60)
print("DEMO 3: Stochastic Ecosystem with Environmental Effects")
print("="*60)
model = StochasticEcosystem(
carrying_capacity=300,
noise_level=0.12,
seasonal_amplitude=0.25
)
print(f"\nModel features:")
print(f" Carrying capacity: {model.K}")
print(f" Noise level: {model.noise}")
print(f" Seasonal amplitude: {model.seasonal_amp}")
print(f" Seasonal period: {model.seasonal_period}")
print("\nRunning ensemble simulation (50 runs)...")
ensemble = model.run_ensemble(
initial_prey=100,
initial_predators=20,
duration=100,
num_runs=50
)
print(f"\nEnsemble statistics at final time:")
final_prey = ensemble['prey'][:, -1]
final_pred = ensemble['predators'][:, -1]
print(f" Prey: {np.mean(final_prey):.1f} ± {np.std(final_prey):.1f}")
print(f" Predators: {np.mean(final_pred):.1f} ± {np.std(final_pred):.1f}")
fig = model.plot_ensemble(ensemble)
plt.savefig('demo_stochastic.png', dpi=150, bbox_inches='tight')
print("\nSaved: demo_stochastic.png")
return fig
def demo_parameter_analysis():
"""Demonstrate parameter sensitivity analysis."""
print("\n" + "="*60)
print("DEMO 4: Parameter Sensitivity Analysis")
print("="*60)
base_params = {
'alpha': 1.0,
'beta': 0.1,
'delta': 0.075,
'gamma': 1.5
}
# Sweep predation rate
beta_values = np.linspace(0.05, 0.2, 15)
print("\nSweeping predation rate (β)...")
results = ParameterAnalyzer.parameter_sweep(
LotkaVolterraModel,
'beta',
beta_values,
base_params,
initial_conditions=(40, 9),
time_span=(0, 50),
metric='amplitude'
)
fig = ParameterAnalyzer.plot_parameter_sweep(results, 'β (predation rate)')
plt.savefig('demo_parameter_sweep.png', dpi=150, bbox_inches='tight')
print("\nSaved: demo_parameter_sweep.png")
return fig
def main():
"""Run all demonstrations."""
print("\n" + "="*60)
print("PREDATOR-PREY ECOSYSTEM SIMULATION")
print("="*60)
print("\nThis demonstration shows multiple approaches to modeling")
print("predator-prey dynamics in ecological systems.")
# Run demonstrations
demo_lotka_volterra()
demo_agent_based()
demo_stochastic()
demo_parameter_analysis()
print("\n" + "="*60)
print("ALL DEMONSTRATIONS COMPLETE")
print("="*60)
print("\nGenerated files:")
print(" - demo_lotka_volterra.png")
print(" - demo_agent_based.png")
print(" - demo_stochastic.png")
print(" - demo_parameter_sweep.png")
plt.show()
if __name__ == "__main__":
main()