Ecosystem Modeling Framework
Build mass-balance food web models, run dynamic ecosystem simulations, and explore spatial dynamics with irregular grids — all from your browser.
Upload custom polygon geometries for realistic spatial modeling! ECOSPACE now supports shapefiles, GeoJSON, and GeoPackage formats.
Try it: Navigate to the Ecospace page and upload examples/coastal_grid_example.geojson
Predators turn towards prey that become more abundant: EwE's switching power, set per predator on the Ecosim page.
Explore: The Prey Switching demo page shows how the switching power shapes a predator's diet.
Environmental forcing, optimization tools, and improved multi-stanza support for age-structured populations.
Learn more: See the Advanced Features demos for detailed examples.
New IBM module with bioenergetics, predation, reproduction, and spatial movement for super-individual tracking.
Try it: Navigate to the IBM page to configure super-individual groups.
Start by defining your ecosystem's functional groups - producers, consumers, detritus, and fishing fleets.
create_rpath_params(groups, types)
Enter biomass, P/B, Q/B ratios, diet composition, and fishery catches for each group.
params.model['Biomass'] = ...
Run the mass-balance calculations to solve for missing parameters and validate the model.
model = rpath(params)
Create a scenario and run dynamic Ecosim simulations to explore ecosystem dynamics.
rsim_run(scenario)
Upload spatial grids and run Ecospace simulations with habitat preferences and dispersal.
rsim_run_spatial(ecospace)
Configure super-individual groups with bioenergetics, predation, and spatial movement parameters.
SmeltIBM.compute_step(state)
A step-by-step guide to ecosystem modeling with PyPath. Follow along using either the web interface or the Python API.
The Ecopath with Ecosim framework follows a natural progression:
Static mass-balance snapshot. Define groups, biomass, production rates, consumption rates, and diet.
Dynamic simulation. Project the balanced model forward in time with fishing, forcing, and vulnerability settings.
Spatial dynamics. Add habitat maps, dispersal, and spatial fishing effort on irregular polygon grids.
Individual-based modeling. Track super-individuals with bioenergetics, predation, and reproduction.
Every model starts by defining functional groups. Each group has a name and a type code:
| Type | Code | Description | Example |
|---|---|---|---|
| Consumer | 0 | Heterotroph (eats other groups) | Fish, Zooplankton, Benthos |
| Producer | 1 | Autotroph (primary production) | Phytoplankton, Macroalgae |
| Detritus | 2 | Non-living organic matter | Detritus, Discards |
| Fleet | 3 | Fishing gear type | Trawlers, Gillnets |
from pypath import create_rpath_params
params = create_rpath_params(
groups=["Phytoplankton", "Zooplankton", "Small Fish",
"Detritus", "Trawlers"],
types=[1, 0, 0, 2, 3],
)
Navigate to Ecopath Model and use the table editor to add groups. Set the Type column for each group (0, 1, 2, or 3).
For each group, provide the key ecological rates:
| Parameter | Symbol | Unit | Notes |
|---|---|---|---|
| Biomass | B | t/km² | Standing stock biomass |
| Production/Biomass | P/B | yr⁻¹ | Total mortality rate (= Z for fish) |
| Consumption/Biomass | Q/B | yr⁻¹ | Consumers only (not producers) |
| Ecotrophic Efficiency | EE | 0–1 | Fraction of production consumed in system |
# Biomass (t/km²)
params.model.loc[0, "Biomass"] = 10.0 # Phytoplankton
params.model.loc[1, "Biomass"] = 5.0 # Zooplankton
params.model.loc[2, "Biomass"] = 2.0 # Small Fish
# Production/Biomass (yr⁻¹)
params.model.loc[0, "PB"] = 200.0 # Phytoplankton: high turnover
params.model.loc[1, "PB"] = 50.0 # Zooplankton
params.model.loc[2, "PB"] = 1.0 # Small Fish
# Consumption/Biomass (yr⁻¹, consumers only)
params.model.loc[1, "QB"] = 150.0 # Zooplankton
params.model.loc[2, "QB"] = 5.0 # Small Fish
# Ecotrophic Efficiency
params.model.loc[0, "EE"] = 0.8
params.model.loc[1, "EE"] = 0.9
params.model.loc[2, "EE"] = 0.5
Edit cells directly in the Ecopath Model table. Leave one cell empty per group for the solver to fill in.
The diet matrix defines who eats whom. Each column is a predator, each row is a prey item. Columns must sum to 1.0 (100% of the diet).
| Prey \ Predator | Zooplankton | Small Fish |
|---|---|---|
| Phytoplankton | 0.90 | - |
| Zooplankton | - | 0.80 |
| Detritus | 0.10 | 0.20 |
| Total | 1.00 | 1.00 |
# Each list = diet column for that predator
# Order matches group list: [Phyto, Zoo, SmallFish, Detritus, Trawlers]
params.diet["Zooplankton"] = [0.90, 0.0, 0.0, 0.10, 0.0]
params.diet["Small Fish"] = [0.0, 0.80, 0.0, 0.20, 0.0]
Switch to the Diet tab on the Ecopath Model page. Edit diet fractions in the table. A warning appears if any column does not sum to 1.0.
The Ecopath solver checks mass balance and fills in missing parameters. The fundamental equation is:
Bᵢ × PBᵢ × EEᵢ = Σⱼ(Bⱼ × QBⱼ × DCⱼᵢ) + Yᵢ + Eᵢ + BAᵢ
Where:
from pypath import rpath
model = rpath(params)
print(model) # Shows balance status and group summary
Click the "Balance Model" button on the Ecopath Model page. The app runs pre-balance diagnostics and solves the linear system. Missing parameters appear automatically in the table.
Ecosim projects the balanced Ecopath model forward in time. It uses the foraging arena functional response, where prey availability is split into a vulnerable and an invulnerable pool.
from pypath import rsim_scenario, rsim_run
# Create a 50-year scenario from the balanced model
scenario = rsim_scenario(model, params, years=range(1, 51))
# Run with Adams-Bashforth (matches Rpath/EwE)
output = rsim_run(scenario, method="AB")
# Biomass trajectories: shape (n_months, n_groups+1)
print(output.out_Biomass.shape)
Navigate to the Ecosim page. Set the simulation years, choose the integration method, and click "Run Ecosim". Biomass trajectories appear automatically.
Modify fishing effort over time to explore management scenarios. Effort is a multiplier on the base catch rate (1.0 = status quo).
from pypath import adjust_fishing
# Double the Trawlers' fishing effort from year 10 to 30
adjust_fishing(scenario, parameter="ForcedEffort",
group="Trawlers", sim_year=range(10, 31),
value=2.0)
output = rsim_run(scenario)
On the Ecosim page, use the Fishing Effort panel to set effort multipliers for each fleet across time periods. Re-run the simulation to see the effect.
Vulnerability (VV) is the most important Ecosim calibration parameter. It controls how strongly predator biomass affects prey consumption:
| VV Value | Control Type | Behavior |
|---|---|---|
| 1.0 | Donor-controlled | Prey production limits consumption (bottom-up) |
| 2.0 | Mixed (default) | Both prey and predator influence flow rates |
| >10 | Recipient-controlled | Predator biomass drives consumption (top-down) |
from pypath import set_vulnerability
# Make Zooplankton highly vulnerable to Small Fish predation
set_vulnerability(scenario, prey="Zooplankton",
predator="Small Fish", value=5.0)
PyPath can read existing Ecopath with Ecosim models directly from EwE's native Access database format (.eweaccdb or .ewemdb files). This loads all parameters, diet matrices, stanzas, fleet catches, vulnerability overrides, and forcing functions.
from pypath import read_ewemdb, rpath
# Load Ecopath parameters from EwE database
params = read_ewemdb("path/to/model.eweaccdb")
model = rpath(params)
from pypath.io.ewemdb import ecosim_scenario_from_ewemdb
from pypath import rsim_run
# Load a ready-to-run Ecosim scenario (with all EwE settings)
scenario = ecosim_scenario_from_ewemdb("model.eweaccdb", scenario=16)
# This loads: vulnerability overrides, fishing effort shapes,
# environmental forcing, foraging time adjustments, and
# forced biomass from the EwE scenario ID.
output = rsim_run(scenario, method="AB")
from pypath import search_ecobase_models, get_ecobase_model, ecobase_to_rpath
# Search 350+ published Ecopath models
results = search_ecobase_models("Baltic Sea")
print(results)
# Download and convert
model_data = get_ecobase_model(model_id=123)
params = ecobase_to_rpath(model_data)
Navigate to Data Import and select your data source: EwE database file, EcoBase online repository, or CSV files. The importer handles format conversion automatically.
After running a simulation, plot biomass trajectories for all living groups:
import matplotlib.pyplot as plt
bio = output.out_Biomass
months = range(bio.shape[0])
for i, name in enumerate(model.Group):
if model.type[i] in (0, 1): # consumers + producers
b = bio[:, i + 1] # +1 for Outside offset
if b[0] > 0:
plt.plot(months, b / b[0], label=name)
plt.xlabel("Month")
plt.ylabel("Relative Biomass (B/B₀)")
plt.legend(loc='best', fontsize=8)
plt.title("Ecosim Biomass Trajectories")
plt.tight_layout()
plt.show()
In the web app, biomass plots are generated automatically on the Results page after an Ecosim run.
Run diagnostics before balancing to catch data entry errors and thermodynamic violations early.
Add spatial dynamics with irregular polygon grids, habitat maps, and dispersal.
Track super-individuals with bioenergetics, predation, reproduction, and movement.
Enter diet fractions (columns must sum to 1.0 for each predator)
Multi-stanza groups link age-structured life stages (e.g., juvenile/adult) that share growth and mortality parameters.
Pre-balance diagnostics help identify potential issues with your Ecopath model before attempting to balance it. This can save time and help you understand your model's structure better.
| Issue | Likely Cause | Solution |
|---|---|---|
| High predator/prey ratio | Predator biomass too high | Reduce predator biomass or increase prey biomass |
| Large biomass range | Missing functional groups | Add intermediate groups or check for data entry errors |
| Steep biomass slope | Strong top-down control | May be realistic (verify with literature) |
| Inverted vital rates | Data entry error | Check P/B and Q/B values against literature |
Run diagnostic checks on your unbalanced model to identify potential issues before balancing.
Configure environmental forcing on prey availability
Fast saves time only where the solver takes many steps a month (Black Sea 37 %, REco 8 %); Reference costs 2-3.5 × Default; continuous runs cost about 5-25 × RK4 on the Python loop, about 15-55 × with numba's consumption kernel (RK4 runs about 2-3 × faster).
Interpolates forcing that varies month to month (an imported EwE scenario's forcing functions); effort stays monthly; the page's own forcing card is constant in time
1 = Bottom-up, 2 = Mixed, High = Top-down
Predators turn towards prey that become more abundant. 0 = off; higher values switch more sharply (EwE allows 0 to 2). Values apply when you create the scenario.
Supported formats: Shapefile (.zip), GeoJSON (.geojson/.json), GeoPackage (.gpkg). File must contain polygon geometries.
Note: For 'Use polygons' mode, an 'id' field is required. For 'Create hexagons' mode, any boundary polygon works.
Name of the field containing unique patch IDs (default: 'id').
Info: Hexagonal grids provide better spatial isotropy (no directional bias) and each cell has 6 equidistant neighbors.
Size determines the distance from hexagon center to vertex. Smaller hexagons = more patches = slower computation.
Configure how organisms move between patches.
Without an active Ecospace Wizard configuration (its rates take precedence), every group disperses at this rate: between two neighbouring square cells, biomass flows at this rate times their current biomass difference, per year. For a non-migratory group, EwE's Mvel of 300 km/year on 36.7 km cells is about 2.6 per year.
Effort follows the biomass of these groups. Leave empty to follow total biomass.
Configure spatial grids, habitat preferences, movement parameters, and fishing allocation. Run spatially-explicit ecosystem simulations and visualize results.
von Bertalanffy Growth Equation:
Length: $L(t) = L_\infty (1 - e^{-K(t - t_0)})$
Weight: $W(t) = a \cdot L(t)^b$
Shows the distribution of biomass across age stanzas based on:
Multi-stanza groups represent age-structured populations where different life stages (stanzas) have distinct ecological properties.
von Bertalanffy Growth Model
Length-Weight Relationship
Stanza Properties
Fish Populations
Marine Mammals
Invertebrates
Blue: Standard simulation (no forcing)
Red: Simulation with forcing applied
Forcing Effect: Shows how forcing modifies the baseline simulation
Not available in this version.
rsim_run_advancedwith state forcing functions raisesNotImplementedError. UseForcedBioon the scenario to force biomass. Diet rewiring is deprecated; prey switching is set per predator (scenario.params.SwitchPower, or the Ecosim page). The examples below show the intended API only.
State-variable forcing allows you to override computed values with observed or prescribed values. This is a powerful technique for:
Example: Force phytoplankton biomass to satellite chlorophyll data
forcing = create_biomass_forcing(
group_idx=0,
observed_biomass=satellite_data,
mode='replace'
)
When to use:
Example: Gradually increase primary production
forcing = StateForcing()
forcing.add_forcing(
group_idx=0,
variable='primary_production',
time_series={2000: 1.0, 2050: 1.3, 2100: 1.6},
mode='multiply'
)
When to use:
Example: Fishing moratorium
forcing = StateForcing()
forcing.add_forcing(
group_idx=5,
variable='fishing_mortality',
time_series={2000: 0.3, 2010: 0.0, 2020: 0.15},
mode='replace'
)
When to use:
Example: Strong and weak year-classes
forcing = create_recruitment_forcing(
group_idx=3,
recruitment_multiplier={2005: 3.0, 2010: 0.5},
interpolate=False
)
When to use:
Combine empirical data with process-based simulation
When to use:
✅ DO:
⚠️ DON'T:
State-variable forcing has minimal computational overhead (~1%), making it suitable for production use.
Illustrates EwE's switching formula on one predator with three prey; in a model, set a predator's switching power on the Ecosim page.
Gaussian Process Visualization:
Bayesian optimization is an efficient method for finding optimal parameters when each evaluation is expensive. Perfect for ecosystem models!
Traditional Methods:
Bayesian Optimization:
Build Surrogate Model (Gaussian Process)
Acquisition Function
Iterate
What they control: Predation efficiency
Use when: Matching predator-prey dynamics
What they control: Predator search efficiency
Use when: Calibrating consumption rates
What they control: Time spent feeding vs other activities
Use when: Matching Q/B ratios
What they control: Natural mortality (M)
Use when: Matching abundance trends
RMSE = sqrt(mean((observed - predicted)^2))
NRMSE = RMSE / mean(observed) * 100
MAPE = mean(|observed - predicted| / observed) * 100
MAE = mean(|observed - predicted|)
LL = -sum(log(2*pi*sigma^2) + (obs-pred)^2/(2*sigma^2))
from pypath.core.optimization import bayesian_optimize_ecosim
# 1. Set up optimization
result = bayesian_optimize_ecosim(
model=model,
params=params,
observed_data=observed_biomass,
param_config=[
{
'param': 'vulnerabilities',
'bounds': (1.0, 3.0),
'groups': [0, 1, 2, 3]
}
],
n_iterations=50,
n_initial=10,
objective='nrmse',
acquisition='EI'
)
# 2. Get results
best_params = result['best_params']
best_score = result['best_score']
convergence = result['convergence']
# 3. Apply to model
for group_idx, value in best_params.items():
params.vulnerabilities[group_idx] = value
✅ DO:
⚠️ DON'T:
Good for:
Not for:
param_config=[
{'param': 'vulnerabilities', 'bounds': (1.0, 3.0), 'groups': [0,1]},
{'param': 'search_rates', 'bounds': (0.1, 1.0), 'groups': [0,1]},
{'param': 'Q0', 'bounds': (0.2, 0.8), 'groups': [2,3]}
]
# Ensure total Q/B stays within bounds
def constraint(params_dict):
total_qb = sum(params_dict.values())
return 10.0 <= total_qb <= 30.0
result = bayesian_optimize_ecosim(
...,
verbose=True, # Print progress
log_file='optimization.log' # Save log
)
Key Papers:
Applications in Ecology:
Compares standard Ecosim trajectory with IBM-enhanced simulation for the selected group.
Select a consumer group to model with super-individuals.
Configure and run individual-based population models coupled with Ecosim. Compare standard aggregate dynamics against size-structured super-individual simulations.
Ecological network analysis indices following Ulanowicz methodology.
MTI quantifies the direct and indirect effects of changes in one group's biomass on all other groups. Positive values indicate positive impacts.
Keystoneness identifies species with disproportionately large ecological effects relative to their biomass (Power et al. 1996, Libralato et al. 2006).
Check mass balance status and identify potential issues.
Export Ecopath model data to DataFrames for further analysis.
Scenario comparison is under development.
PyPath is a Python implementation of the Ecopath with Ecosim (EwE) ecosystem modeling approach. It provides tools for:
PyPath is based on the R package Rpath developed by NOAA's Northeast Fisheries Science Center.
Ecopath with Ecosim is a widely-used ecosystem modeling approach developed by Villy Christensen and Carl Walters. The approach consists of:
The Ecopath mass-balance equation:
Production = Predation + Catch + Net Migration + Biomass Accumulation + Other Mortality
Or mathematically:
Bᵢ × PBᵢ × EEᵢ = Σⱼ(Bⱼ × QBⱼ × DCⱼᵢ) + Yᵢ + Eᵢ + BAᵢ
MIT License
PyPath is free and open source software. Contributions are welcome!
| Python: | 3.13.16 |
| PyPath-EwE: | 1.11.0 |
| PyPath-Shiny: | 1.8.1 |
| Shiny: | 1.9.0 |
| NumPy: | 2.5.5 |
| Pandas: | 3.1.1 |
| SciPy: | 1.17.1 |
PyPath © 2026 | Documentation | Report Issue