from typing import Callable, Optional, Union
import numpy as np
from scipy.integrate import solve_ivp
from scipy.optimize import least_squares
class GeneralizedLotkaVolterra:
"""
Generalized Lotka-Volterra model for simulating interacting species (e.g., competing products).
The model assumes the dynamics of N interacting species are governed by:
dx_i/dt = x_i * (r_i + sum_j(alpha_ij * x_j))
Attributes:
n_species (int): Number of species in the model.
r_ (np.ndarray): Estimated intrinsic growth rates after fitting, shape (n_species,).
alpha_ (np.ndarray): Estimated interaction coefficients after fitting, shape (n_species, n_species).
"""
def __init__(self, n_species: int):
"""
Initialize the Generalized Lotka-Volterra model.
Args:
n_species (int): Number of species in the model.
"""
self.n_species: int = n_species
self.r_: Optional[np.ndarray] = None # To be estimated during fitting
self.alpha_: Optional[np.ndarray] = None # To be estimated during fitting
def _glv_equations(
self,
t: float,
X: np.ndarray,
r: np.ndarray,
alpha: np.ndarray
) -> np.ndarray:
"""
Generalized Lotka-Volterra differential equations.
Args:
t (float): Time point.
X (np.ndarray): State variables at time t, shape (n_species,).
r (np.ndarray): Intrinsic growth rates, shape (n_species,).
alpha (np.ndarray): Interaction coefficients, shape (n_species, n_species).
Returns:
np.ndarray: Derivatives at time t, shape (n_species,).
"""
return X * (r + alpha @ X)
def fit(self, time: np.ndarray, X: np.ndarray):
"""
Fit the model to time series data.
Args:
time (np.ndarray): Time points of observations, shape (n_time_points,).
X (np.ndarray): Observations at each time points, shape (n_time_points, n_species).
Raises:
ValueError: If the dimensions of X do not match n_species.
"""
n_species = self.n_species
n_time_points = len(time)
if X.shape != (n_time_points, n_species):
raise ValueError(
f"Expected X shape ({n_time_points}, {n_species}), got {X.shape}"
)
# Initial guess for parameters: r and alpha
initial_r = np.random.rand(n_species)
initial_alpha = np.random.rand(n_species, n_species)
# Flatten parameters for optimization
initial_params = np.concatenate([initial_r, initial_alpha.flatten()])
# Define the residual function
def residuals(params):
r = params[:n_species]
alpha = params[n_species:].reshape((n_species, n_species))
# Integrate the differential equations
sol = solve_ivp(
fun=lambda t, y: self._glv_equations(t, y, r, alpha),
t_span=(time[0], time[-1]),
y0=X[0],
t_eval=time,
vectorized=True,
method='RK45',
)
if sol.y.shape[1] < len(time):
# Integration failed before reaching all time points
simulated_X = np.full_like(X, np.nan)
else:
simulated_X = sol.y.T # Shape (n_time_points, n_species)
resid = (X - simulated_X).ravel()
return resid
# Optimize the parameters
result = least_squares(
fun=residuals,
x0=initial_params,
method='trf',
verbose=2
)
# Extract optimized parameters
optimized_params = result.x
self.r_ = optimized_params[:n_species]
self.alpha_ = optimized_params[n_species:].reshape((n_species, n_species))
def predict(self, time: np.ndarray, X0: np.ndarray) -> np.ndarray:
"""
Predict future values using the fitted model.
Args:
time (np.ndarray): Time points to predict, shape (n_time_predict,).
X0 (np.ndarray): Initial state of species at the first time point, shape (n_species,).
Returns:
np.ndarray: Predicted values at each time point, shape (n_time_predict, n_species).
Raises:
ValueError: If the model parameters are not fitted.
"""
if self.r_ is None or self.alpha_ is None:
raise ValueError("Model parameters not fitted. Please call 'fit' before 'predict'.")
sol = solve_ivp(
fun=lambda t, y: self._glv_equations(t, y, self.r_, self.alpha_),
t_span=(time[0], time[-1]),
y0=X0,
t_eval=time,
vectorized=True,
method='RK45',
)
predicted_X = sol.y.T # Shape (n_time_predict, n_species)
return predicted_X
This module implements the generalized Lotka-Volterra (gLV) model for modeling and forecasting the dynamics of competing products. It is designed to be reusable and follows scikit-learn's style guidelines for estimator classes.
Usage Example:
import numpy as np
import matplotlib.pyplot as plt
# Suppose we have quarterly data for 8 products over 3 years (12 time points)
n_species = 8
n_time_points = 12
time = np.linspace(0, 11, n_time_points) # Time points from 0 to 11
X = np.random.rand(n_time_points, n_species) # Placeholder for your actual data
# Initialize the model
glv_model = GeneralizedLotkaVolterra(n_species=n_species)
# Fit the model to the data
glv_model.fit(time, X)
# Predict future values for the next 8 quarters
future_time = np.linspace(12, 19, 8) # Time points from 12 to 19
X0 = X[-1] # Use the last observed state as the initial condition
predictions = glv_model.predict(future_time, X0)
# Plot the results
for i in range(n_species):
plt.plot(time, X[:, i], 'o-', label=f'Product {i+1} Observed')
plt.plot(future_time, predictions[:, i], '--', label=f'Product {i+1} Predicted')
plt.xlabel('Time (Quarters)')
plt.ylabel('Market Share')
plt.legend()
plt.show()
Dependencies:
Notes:
- The
fit method estimates the intrinsic growth rates (r_) and interaction coefficients (alpha_) by minimizing the difference between the observed data and the model's predictions.
- The
predict method uses the fitted parameters to forecast future dynamics.
- The model assumes that the market shares of the products are continuous and can be modeled as interacting populations.
Important Considerations:
- Ensure that your actual data replaces the placeholder random data in the usage example.
- The optimization process in the
fit method may take time, especially for a larger number of species. Adjust the optimization settings if necessary.
- Always check the convergence status of the optimizer to ensure that the parameter estimation is reliable.
Packaging for PyPI:
To create a reusable package and deploy it to PyPI (pip), you should structure your module accordingly and include the necessary setup.py or pyproject.toml files. Consider adding unit tests and documentation to make your package more robust and user-friendly.