import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint
# Lotka-Volterra predator-prey model
# dx/dt = alpha * x - beta * x * y (prey growth minus predation)
# dy/dt = delta * x * y - gamma * y (predator growth from predation minus death)
def lotka_volterra(state, t, alpha, beta, delta, gamma):
"""
Define the system of ODEs.
Parameters:
- state: [x, y] where x is prey population, y is predator population
- t: time
- alpha, beta, delta, gamma: model parameters
"""
x, y = state
dxdt = alpha * x - beta * x * y
dydt = delta * x * y - gamma * y
return [dxdt, dydt]
# Parameters (example values for rabbits (prey) and foxes (predators))
alpha = 1.0 # Prey growth rate
beta = 0.1 # Predation rate
delta = 0.02 # Predator growth rate from predation
gamma = 1.0 # Predator death rate
# Initial conditions: [prey, predator]
state0 = [40, 9]
# Time points (0 to 100 in steps of 0.1)
t = np.linspace(0, 100, 1000)
# Solve ODE
states = odeint(lotka_volterra, state0, t, args=(alpha, beta, delta, gamma))
# Extract prey and predator populations
prey = states[:, 0]
predator = states[:, 1]
# Plot results
plt.figure(figsize=(10, 6))
plt.plot(t, prey, 'g-', label='Prey (Rabbits)')
plt.plot(t, predator, 'r-', label='Predators (Foxes)')
plt.xlabel('Time')
plt.ylabel('Population')
plt.title('Predator-Prey Model (Lotka-Volterra)')
plt.legend()
plt.grid(True)
plt.show()
# Optional: Phase plot (prey vs predator)
plt.figure(figsize=(8, 6))
plt.plot(prey, predator, 'b-')
plt.xlabel('Prey Population')
plt.ylabel('Predator Population')
plt.title('Phase Portrait')
plt.grid(True)
plt.show()
This code simulates the classic Lotka-Volterra predator-prey model using SciPy's odeint for numerical integration. It generates two plots: populations over time and a phase portrait. You can adjust parameters, initial conditions, or time span as needed. Requires numpy, matplotlib, and scipy. Run it in a Python environment like Jupyter or a script.