PyPath

Ecosystem Modeling Framework

Ecopath with Ecosim in Python

Build mass-balance food web models, run dynamic ecosystem simulations, and explore spatial dynamics with irregular grids — all from your browser.

What's New in PyPath

Irregular Grid Support

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

Diet Rewiring

Advanced prey switching behavior! Predators now adapt their diet based on prey availability with configurable switching power.

Explore: Check out the Diet Rewiring Demo page for interactive examples.

Enhanced Ecosim

Environmental forcing, optimization tools, and improved multi-stanza support for age-structured populations.

Learn more: See the Advanced Features demos for detailed examples.

Individual-Based Modeling

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.

Features

Data Import
  • Connect to EcoBase database (350+ models)
  • Search and download published models
  • Import EwE database files (.ewemdb, .eweaccdb)
  • Automatic format conversion
  • Pre-configured ecosystem models
Ecopath Mass Balance
  • Define functional groups and food web
  • Set biomass, P/B, Q/B ratios
  • Automatic mass-balance calculations
  • Trophic level computation
  • Multi-stanza age structure
Ecosim Simulation
  • Dynamic ecosystem simulations
  • Foraging arena functional response
  • Fishing scenarios and forcing
  • Environmental forcing effects
  • Multiple integration methods
ECOSPACE Spatial ModelingNEW
  • Irregular grid support (GeoJSON, Shapefile)
  • Realistic spatial geometries
  • Habitat preference mapping
  • Dispersal and movement dynamics
  • Spatial fishing effort allocation
Individual-Based ModelNEW
  • Super-individual tracking
  • Wisconsin bioenergetics model
  • Size-structured predation
  • Stochastic reproduction
  • Spatial movement & foraging
Network Analysis
  • Food web topology metrics
  • Ecosystem health indicators
  • Trophic impact analysis (MTI)
  • Keystone species identification
  • Lindeman spine diagrams
Results & Visualization
  • Interactive time series plots
  • Food web diagrams
  • Biomass and catch trajectories
  • Export results to CSV/Excel
  • Comparative scenario analysis
Advanced Features
  • Diet rewiring (prey switching)
  • Environmental forcing functions
  • Multi-stanza age structure
  • Optimization and sensitivity analysis
  • Custom fishing scenarios

Access advanced features via dedicated demo pages.

About PyPath
  • Python port of R Rpath package
  • NOAA/EwE ecosystem modeling
  • Open source (MIT License)
  • GitHub repository
  • Active development
Documentation
  • User guides and tutorials
  • API reference documentation
  • Example models and scripts
  • Irregular grid guide (NEW)
  • Video tutorials (coming soon)

See the 'examples/' folder for guides and sample data.

Quick Start

Step 1: Define Groups

Start by defining your ecosystem's functional groups - producers, consumers, detritus, and fishing fleets.

create_rpath_params(groups, types)
Step 2: Set Parameters

Enter biomass, P/B, Q/B ratios, diet composition, and fishery catches for each group.

params.model['Biomass'] = ...
Step 3: Balance Model

Run the mass-balance calculations to solve for missing parameters and validate the model.

model = rpath(params)
Step 4: Run Simulation

Create a scenario and run dynamic Ecosim simulations to explore ecosystem dynamics.

rsim_run(scenario)
Step 5: Add Spatial DynamicsOptional

Upload spatial grids and run Ecospace simulations with habitat preferences and dispersal.

rsim_run_spatial(ecospace)
Step 6: Individual-Based ModelingOptional

Configure super-individual groups with bioenergetics, predation, and spatial movement parameters.

SmeltIBM.compute_step(state)

PyPath Tutorial

A step-by-step guide to ecosystem modeling with PyPath. Follow along using either the web interface or the Python API.

Modeling Workflow Overview

The Ecopath with Ecosim framework follows a natural progression:

1Ecopath

Static mass-balance snapshot. Define groups, biomass, production rates, consumption rates, and diet.

2Ecosim

Dynamic simulation. Project the balanced model forward in time with fishing, forcing, and vulnerability settings.

3Ecospace

Spatial dynamics. Add habitat maps, dispersal, and spatial fishing effort on irregular polygon grids.

4IBM

Individual-based modeling. Track super-individuals with bioenergetics, predation, and reproduction.

This tutorial covers steps 1-2. See the Ecospace and IBM pages for spatial and individual-based extensions.
1Create a Model from Scratch

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
Python API
from pypath import create_rpath_params

params = create_rpath_params(
    groups=["Phytoplankton", "Zooplankton", "Small Fish",
           "Detritus", "Trawlers"],
    types=[1, 0, 0, 2, 3],
)
In the Web App

Navigate to Ecopath Model and use the table editor to add groups. Set the Type column for each group (0, 1, 2, or 3).

2Set Ecopath Parameters

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
You can leave one parameter unknown per group. The mass-balance solver will calculate it from the others.
Python API
# 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
In the Web App

Edit cells directly in the Ecopath Model table. Leave one cell empty per group for the solver to fill in.

3Define the Diet Matrix

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
Python API
# 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]
In the Web App

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.

4Balance the Model (Ecopath)

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:

  • Bᵢ × PBᵢ × EEᵢ = production of group i consumed in the system
  • Σⱼ(Bⱼ × QBⱼ × DCⱼᵢ) = total predation on group i
  • Yᵢ = fishery catch, Eᵢ = net emigration, BAᵢ = biomass accumulation
If any EE > 1.0, the model is unbalanced. Use the Pre-Balance page to diagnose issues before proceeding.
Python API
from pypath import rpath

model = rpath(params)
print(model)  # Shows balance status and group summary
In the Web App

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.

5Run an Ecosim Simulation

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.

Key Concepts
  • Vulnerability (VV) — Controls functional response shape: 1.0 = donor-controlled (bottom-up), 2.0 = mixed (default), >10 = recipient-controlled (top-down)
  • Integration methods — RK4 (Runge-Kutta 4th order) for accuracy, or AB (Adams-Bashforth 2-step) to match Rpath/EwE output
  • NoIntegrate groups — Detritus and fast-turnover groups use algebraic equilibrium instead of numerical integration
Python API
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)
In the Web App

Navigate to the Ecosim page. Set the simulation years, choose the integration method, and click "Run Ecosim". Biomass trajectories appear automatically.

6Apply Fishing Scenarios

Modify fishing effort over time to explore management scenarios. Effort is a multiplier on the base catch rate (1.0 = status quo).

Python API
from pypath import adjust_fishing

# Double fishing effort on Small Fish from year 10 to 30
adjust_fishing(scenario, group="Small Fish",
               value=2.0, years=range(10, 31))

output = rsim_run(scenario)
In the Web App

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.

7Adjust Vulnerability Parameters

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)
Python API
from pypath import set_vulnerability

# Make Zooplankton highly vulnerable to Small Fish predation
set_vulnerability(scenario, prey="Zooplankton",
                  pred="Small Fish", value=5.0)
Calibration Tips
  • Start with VV=2.0 (default) for all links
  • Lower VV (toward 1.0) for stable benthic prey or detritus feeders
  • Raise VV (toward 10+) for pelagic prey subject to strong top-down control
  • Use the Optimization page to fit VV to time series data
8Load from an EwE DatabaseAdvanced

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.

Option A: Ecopath Parameters Only
from pypath import read_ewemdb, rpath

# Load Ecopath parameters from EwE database
params = read_ewemdb("path/to/model.eweaccdb")
model = rpath(params)
Option B: Complete Ecosim Scenario
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")
Option C: From EcoBase Online Repository
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)
In the Web App

Navigate to Data Import and select your data source: EwE database file, EcoBase online repository, or CSV files. The importer handles format conversion automatically.

Plotting Results

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.

Next Steps
Pre-Balance Diagnostics

Run diagnostics before balancing to catch data entry errors and thermodynamic violations early.

Ecospace Spatial Modeling

Add spatial dynamics with irregular polygon grids, habitat maps, and dispersal.

Individual-Based Modeling

Track super-individuals with bioenergetics, predation, reproduction, and movement.

API Documentation

Full API reference for all PyPath functions, classes, and modules.

View Docs

Model Preview

Stanza Groups
Life Stages

Ecopath Mass-Balance Model

Basic Parameters

No data (was 9999) Has remark (from EwE file)
Parameter Descriptions
Group
Name of the functional group (species or group of species)
Type
Group type: 0=Consumer, 1=Producer, 2=Detritus, 3=Fleet
Biomass
Biomass (t/km²) - standing stock of the group
PB
Production/Biomass ratio (1/year) - turnover rate
QB
Consumption/Biomass ratio (1/year) - feeding rate (grey for producers/detritus)
EE
Ecotrophic Efficiency (0-1) - fraction of production used in the system
Unassim
Unassimilated consumption (0-1) - fraction of food not assimilated (grey for producers/detritus)
BioAcc
Biomass accumulation rate (t/km²/year) - change in biomass over time

Diet Composition

Enter diet fractions (columns must sum to 1.0 for each predator)

Landings & Discards

Balanced Model Results

Multi-Stanza Groups

Multi-stanza groups link age-structured life stages (e.g., juvenile/adult) that share growth and mortality parameters.

Stanza Group Configuration
Individual Life Stages

Model Diagnostics

P/B Ratios

Q/B Ratios

Pre-Balance Diagnostics Help

Overview

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.

Diagnostic Metrics

1. Biomass Slope

  • Measures how biomass changes across trophic levels
  • Typical range: -0.5 to -1.5 (negative slope expected)
  • Interpretation:
    • Steep slope (< -2): Very strong top-down control
    • Flat slope (> -0.3): Weak trophic structure

2. Biomass Range

  • Measures the span of biomasses (log10 scale)
  • Warning threshold: > 6 orders of magnitude
  • Issues:
    • Large ranges may indicate missing functional groups
    • Could suggest unrealistic biomass values

3. Predator-Prey Biomass Ratios

  • Compares predator biomass to total prey biomass
  • Typical range: 0.01 to 0.5
  • Warning threshold: > 1.0
  • Interpretation:
    • Ratio > 1: Predator biomass exceeds prey (unsustainable)
    • High ratios indicate insufficient prey support

4. Vital Rate Ratios (P/B, Q/B)

  • Compares predator rates to mean prey rates
  • Expected pattern: Predators have lower rates than prey
  • Interpretation:
    • Follows metabolic theory (larger animals = slower rates)
    • Violations may indicate data errors

How to Use

  1. Load Model: Import your unbalanced Ecopath model on the Data Import page
  2. Run Diagnostics: Click "Run Diagnostics" button
  3. Review Summary: Check overall metrics and ranges
  4. Check Warnings: Address any flagged issues
  5. Examine Ratios: Look for suspicious predator-prey relationships
  6. Visualize: Use plots to identify outliers
  7. Fix Issues: Return to Data Import or Ecopath pages to adjust values
  8. Re-run: Run diagnostics again until warnings are resolved

Visualization Options

  • Biomass vs TL: Shows biomass distribution across food web
  • P/B vs TL: Production rates should decrease with trophic level
  • Q/B vs TL: Consumption rates should decrease with trophic level
  • Exclude Groups: Optionally remove groups from visualization (e.g., marine mammals)

Common Issues and Solutions

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

References

  • Bauer, B. (2016). Prebal routine for Rpath. Stockholm University.
  • Link, J. S. (2010). Adding rigor to ecological network models by evaluating a set of pre-balance diagnostics: A plea for PREBAL. Ecological Modelling, 221(12), 1580-1591.
  • Christensen, V., & Walters, C. J. (2004). Ecopath with Ecosim: Methods, capabilities and limitations. Ecological Modelling, 172(2-4), 109-139.

Ecosim Dynamic Simulation

Scenario Configuration

Effort Forcing
Biomass Forcing

Configure environmental forcing on prey availability

Simulation Status

Biomass Trajectories

Catch Trajectories

Simulation Summary

Spatial distribution of fishing effort based on selected allocation method.

Summary statistics for spatial distribution of biomass.

ECOSPACE - Spatial Ecosystem Modeling

Configure spatial grids, habitat preferences, movement parameters, and fishing allocation. Run spatially-explicit ecosystem simulations and visualize results.

Ecospace Data Wizard

1. Select Area2. Configure Grid3. Download Data4. Review Habitats5. Assign Preferences6. Set Dispersal7. Review & Launch
von Bertalanffy Growth Model

von Bertalanffy Growth Equation:

Length: $L(t) = L_\infty (1 - e^{-K(t - t_0)})$

Weight: $W(t) = a \cdot L(t)^b$

Calculated Stanza Parameters
Biomass by Stanza

Shows the distribution of biomass across age stanzas based on:

  • Growth rate (von Bertalanffy K)
  • Natural mortality (Z)
  • Recruitment patterns
Multi-Stanza Groups

What are Multi-Stanza Groups?

Multi-stanza groups represent age-structured populations where different life stages (stanzas) have distinct ecological properties.

Key Concepts

von Bertalanffy Growth Model

  • K: Growth rate coefficient (higher = faster growth)
  • L∞: Asymptotic (maximum) length
  • t₀: Theoretical age at zero length

Length-Weight Relationship

  • W = a × L^b
  • Typical b values: 2.5-3.5 (3.0 for isometric growth)

Stanza Properties

  • Each stanza represents an age range
  • Properties calculated based on growth model
  • Biomass distributed across stanzas

Example Use Cases

  1. Fish Populations

    • Juveniles, Sub-adults, Adults
    • Different vulnerability to predation
    • Size-dependent diet preferences
  2. Marine Mammals

    • Pups, Juveniles, Adults
    • Age-specific reproduction
    • Different energy requirements
  3. Invertebrates

    • Larvae, Juveniles, Adults
    • Metamorphosis stages
    • Size-structured populations

How to Use

  1. Select a group from your model
  2. Set number of stanzas (typically 2-5)
  3. Enter growth parameters (K, L∞, t₀)
  4. Set length-weight relationship (a, b)
  5. Calculate to see growth curves and properties
  6. Review stanza properties and biomass distribution
  7. Save configuration to apply to your model

Tips

  • Start simple: Begin with 2-3 stanzas
  • Use literature values: Find K, L∞ from FishBase or literature
  • Check biomass: Ensure distribution makes ecological sense
  • Validate: Compare with observed age structure if available
Forced Values Over Time

                              
Effect of Forcing on Simulation

Blue: Standard simulation (no forcing)

Red: Simulation with forcing applied

Forcing Effect: Shows how forcing modifies the baseline simulation

Python Code for This Configuration
State-Variable Forcing Use Cases

What is State-Variable Forcing?

State-variable forcing allows you to override computed values with observed or prescribed values. This is a powerful technique for:

1. Calibration to Observations

Example: Force phytoplankton biomass to satellite chlorophyll data

forcing = create_biomass_forcing(
    group_idx=0,
    observed_biomass=satellite_data,
    mode='replace'
)

When to use:

  • You have reliable observations
  • Want to match empirical patterns
  • Testing bottom-up vs top-down control

2. Climate Change Scenarios

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:

  • Climate-driven changes
  • Temperature effects
  • Ocean acidification impacts

3. Fishing Management

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:

  • Marine protected areas
  • Fishing bans
  • Quota changes
  • Recovery scenarios

4. Recruitment Variability

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:

  • Environmental recruitment drivers
  • Regime shifts
  • El Niño effects
  • Temperature-dependent recruitment

5. Hybrid Models

Combine empirical data with process-based simulation

When to use:

  • Mix observations with mechanistic models
  • Data-rich for some variables, not others
  • Testing specific hypotheses
  • Filling knowledge gaps

Forcing Modes Explained

REPLACE Mode

  • What it does: Completely overrides computed value
  • Use when: You have reliable absolute measurements
  • Example: Satellite biomass, catch statistics

ADD Mode

  • What it does: Adds to computed value
  • Use when: Representing additive processes
  • Example: Immigration, supplementation

MULTIPLY Mode

  • What it does: Scales computed value
  • Use when: Representing proportional changes
  • Example: Environmental multipliers, recruitment strength

RESCALE Mode

  • What it does: Rescales to match target while preserving proportions
  • Use when: Want to match total while keeping ratios
  • Example: Total catch with fleet proportions

Best Practices

DO:

  • Validate forced data quality
  • Check for ecological realism
  • Document assumptions
  • Test sensitivity to forcing
  • Compare with and without forcing

⚠️ DON'T:

  • Force too many variables (reduces model predictive power)
  • Ignore mass balance violations
  • Use poor quality data
  • Forget to document what was forced

Performance

State-variable forcing has minimal computational overhead (~1%), making it suitable for production use.

Diet Shift Visualization

                              
How Diet Changes with Biomass

Prey Switching Model:

$\text{new_diet}[i] = \text{base_diet}[i] \times \left(\frac{B_i}{\bar{B}}\right)^p$

Where:

  • $B_i$ = current prey biomass
  • $\bar{B}$ = mean prey biomass
  • $p$ = switching power

Then normalized so diet sums to 1.

Diet Evolution Over Time

Shows how diet composition changes as prey biomass varies over time.

Python Code
Dynamic Diet Rewiring Guide

What is Dynamic Diet Rewiring?

Diet rewiring allows predator diet preferences to change over time in response to changing prey abundance. This implements:

  • Prey switching: Predators shift to more abundant prey
  • Adaptive foraging: Optimize feeding efficiency
  • Functional responses: Beyond static diet matrices

Key Parameters

Switching Power (p)

Controls the strength of the prey switching response:

  • p = 1.0: Proportional response (no switching)

    • Diet changes proportionally with biomass
    • Weak adaptive behavior
  • p = 2.0-3.0: Moderate switching (typical)

    • Realistic for most predators
    • Balanced foraging strategy
  • p > 3.0: Strong switching

    • Highly opportunistic predators
    • Can create alternative stable states

Update Interval

How often diet is recalculated:

  • Monthly (1): Fast-changing systems

    • High computational cost
    • Very responsive
  • Quarterly (3): Seasonal changes

    • Moderate cost
    • Seasonal adaptation
  • Annual (12): Slow-changing systems

    • Low computational cost
    • Long-term adaptation

Minimum Proportion

Prevents diet proportions from going to zero:

  • 0.001: Standard value
  • Prevents division by zero
  • Ensures some consumption of all prey

Ecological Scenarios

1. Normal Conditions

  • All prey at similar biomass
  • Diet close to base preferences
  • Minimal switching

2. Prey Collapse

  • One prey becomes scarce
  • Predator shifts away from scarce prey
  • Increases other prey consumption
  • Prey refuge effect

3. Prey Bloom

  • One prey becomes very abundant
  • Predator shifts heavily to abundant prey
  • Opportunistic feeding

4. Alternating Abundance

  • Prey biomass cycles
  • Diet tracks abundance patterns
  • Dynamic adaptation

Example Use Cases

Fish Predators

# Cod switching between herring and sprat
diet_rewiring = create_diet_rewiring(
    switching_power=2.5,  # Moderate opportunism
    update_interval=3      # Quarterly
)

Opportunistic Feeders

# Jellyfish switching between zooplankton types
diet_rewiring = create_diet_rewiring(
    switching_power=4.0,  # High opportunism
    update_interval=1      # Monthly
)

Specialist Predators

# Killer whales with preferred prey
diet_rewiring = create_diet_rewiring(
    switching_power=1.5,  # Weak switching
    update_interval=12     # Annual
)

Scientific Background

Theoretical Basis

  • Murdoch (1969): Original prey switching experiments
  • Chesson (1983): Frequency-dependent predation theory
  • Gentleman et al. (2003): Functional responses in Ecosim

When Prey Switching Matters

Important when:

  • Prey abundance varies substantially
  • Predators are generalists
  • Multiple prey species available
  • System shows regime shifts

⚠️ Less important when:

  • Prey abundance is stable
  • Predators are specialists
  • Strong habitat segregation
  • Morphological constraints on diet

Best Practices

Choosing Switching Power

  1. Start with 2.0 (moderate switching)
  2. Increase for: Opportunistic predators, variable prey
  3. Decrease for: Specialists, morphological constraints
  4. Validate with: Observed diet data, gut content analysis

Setting Update Interval

  1. Consider timescales: Monthly for plankton, annual for fish
  2. Balance: Realism vs. computational cost
  3. Start with 12 months: Good for most applications

Validation

Check:

  • Diet sums to 1 (automatically ensured)
  • Ecological realism of shifts
  • Comparison with observed diets
  • Sensitivity to parameters

Performance

  • Annual updates: ~1% overhead (negligible)
  • Monthly updates: ~5-10% overhead (acceptable)
  • Real-time updates: Use with caution

Limitations

⚠️ Simplified model:

  • No handling time
  • No search costs
  • No learning
  • No spatial effects
  • Assumes biomass = availability

Despite simplifications, provides realistic adaptive foraging dynamics for ecosystem models.

Convergence Plot

                              
Gaussian Process Model

Gaussian Process Visualization:

  • Black dots: Evaluated points
  • Red star: Best point found
  • Blue line: GP mean prediction
  • Shaded area: 95% confidence interval
Optimized vs Observed
Python Code
Bayesian Optimization Guide

What is Bayesian Optimization?

Bayesian optimization is an efficient method for finding optimal parameters when each evaluation is expensive. Perfect for ecosystem models!

Why Bayesian Optimization?

Traditional Methods:

  • Grid search: Try all combinations (very slow)
  • Random search: Try random points (inefficient)
  • Gradient descent: Requires derivatives (not available)

Bayesian Optimization:

  • ✅ Learns from previous evaluations
  • ✅ Focuses search on promising regions
  • ✅ Handles expensive evaluations
  • ✅ No derivatives needed
  • ✅ Quantifies uncertainty

How It Works

  1. Build Surrogate Model (Gaussian Process)

    • Learns relationship between parameters and objective
    • Provides mean prediction and uncertainty
  2. Acquisition Function

    • Decides where to sample next
    • Balances exploration vs exploitation
  3. Iterate

    • Evaluate at selected point
    • Update surrogate model
    • Repeat until convergence

Parameters You Can Optimize

1. Vulnerabilities

What they control: Predation efficiency

  • Low (1.0): Hard to catch (prey refuge)
  • High (3.0+): Easy to catch (no refuge)

Use when: Matching predator-prey dynamics

2. Search Rates

What they control: Predator search efficiency

  • Controls encounter rates
  • Affects foraging arena dynamics

Use when: Calibrating consumption rates

3. Feeding Time (Q0)

What they control: Time spent feeding vs other activities

  • Range: 0.1 - 0.9
  • Higher = more feeding time

Use when: Matching Q/B ratios

4. Mortality Rates

What they control: Natural mortality (M)

  • Background death rate
  • Not from predation or fishing

Use when: Matching abundance trends

Objective Functions

RMSE (Root Mean Square Error)

RMSE = sqrt(mean((observed - predicted)^2))
  • Use when: Want absolute error minimization
  • Units: Same as data
  • Best for: Similar-scale data

NRMSE (Normalized RMSE)

NRMSE = RMSE / mean(observed) * 100
  • Use when: Comparing different variables
  • Units: Percentage
  • Best for: Multi-group optimization

MAPE (Mean Absolute Percentage Error)

MAPE = mean(|observed - predicted| / observed) * 100
  • Use when: Percentage error matters
  • Units: Percentage
  • Best for: Relative errors

MAE (Mean Absolute Error)

MAE = mean(|observed - predicted|)
  • Use when: Robust to outliers
  • Units: Same as data
  • Best for: Skewed distributions

Log-Likelihood

LL = -sum(log(2*pi*sigma^2) + (obs-pred)^2/(2*sigma^2))
  • Use when: Statistical inference needed
  • Units: Log probability
  • Best for: Probabilistic models

Acquisition Functions

Expected Improvement (EI)

  • What it does: Maximizes expected improvement over best
  • Behavior: Balanced exploration-exploitation
  • Best for: General purpose

Upper Confidence Bound (UCB)

  • What it does: Optimistic estimate (mean + uncertainty)
  • Behavior: More exploration
  • Best for: Uncertain landscapes

Probability of Improvement (PI)

  • What it does: Maximizes probability of improvement
  • Behavior: More exploitation
  • Best for: Near-optimal solutions

Example Workflow

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

Tips for Success

DO:

  • Start with 10-20 initial points
  • Run 30-50 iterations minimum
  • Use NRMSE for multi-group problems
  • Check convergence plots
  • Validate with held-out data

⚠️ DON'T:

  • Optimize too many parameters at once (curse of dimensionality)
  • Use too few iterations (won't converge)
  • Ignore biological constraints
  • Over-fit to short time series

Computational Cost

  • Single iteration: 1 full Ecosim simulation
  • 50 iterations: ~5-10 minutes (typical)
  • Parallelization: Supported for initial points
  • Caching: Previous results reused

When to Use

Good for:

  • Parameter calibration
  • Uncertainty quantification
  • Sensitivity analysis
  • Multi-objective optimization

Not for:

  • Very high-dimensional problems (>10 parameters)
  • Very cheap evaluations (use grid search)
  • Discrete-only parameters
  • Real-time applications

Advanced Features

Multi-Parameter Optimization

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]}
]

Custom Constraints

# Ensure total Q/B stays within bounds
def constraint(params_dict):
    total_qb = sum(params_dict.values())
    return 10.0 <= total_qb <= 30.0

Progress Tracking

result = bayesian_optimize_ecosim(
    ...,
    verbose=True,  # Print progress
    log_file='optimization.log'  # Save log
)

Scientific Background

Key Papers:

  • Mockus (1974): Original Bayesian optimization
  • Snoek et al. (2012): Practical implementation
  • Frazier (2018): Tutorial review

Applications in Ecology:

  • Ecosystem model calibration
  • Species distribution models
  • Population dynamics
  • Resource management
Parameter Summary
Initialization Status

Compares standard Ecosim trajectory with IBM-enhanced simulation for the selected group.

Individual-Based Model

Configure and run individual-based population models coupled with Ecosim. Compare standard aggregate dynamics against size-structured super-individual simulations.

Ecosystem Analysis

Network Indices

Ecological network analysis indices following Ulanowicz methodology.

System Indices
Flow Indices
Food Web Structure

Trophic Structure

Trophic Level Summary
Trophic Spectrum

Mixed Trophic Impacts (MTI)

MTI quantifies the direct and indirect effects of changes in one group's biomass on all other groups. Positive values indicate positive impacts.


MTI Details
Top Positive Impacts
Top Negative Impacts

Keystone Species Analysis

Keystoneness identifies species with disproportionately large ecological effects relative to their biomass (Power et al. 1996, Libralato et al. 2006).

Top Keystone Species
Keystoneness vs Biomass

Ecopath Balance Diagnostics

Check mass balance status and identify potential issues.

Balance Summary
EE Values
Detailed Diagnostics

Export Model Data

Export Ecopath model data to DataFrames for further analysis.

Basic Parameters
Diet Matrix

Download All Data (CSV)

Results & Visualization

Ecopath Model Summary


Trophic Structure

Food Web Diagram

Ecosim Simulation Results

Biomass Time Series

Catch Time Series

Scenario Comparison

Scenario comparison is under development.

Raw Data Tables

About PyPath

What is PyPath?

PyPath is a Python implementation of the Ecopath with Ecosim (EwE) ecosystem modeling approach. It provides tools for:

  • Ecopath - Static mass-balance modeling of food webs
  • Ecosim - Time-dynamic simulation of ecosystem changes
  • Ecospace - Spatial-temporal modeling with irregular polygon grids
  • IBM - Individual-based modeling with super-individual tracking

PyPath is based on the R package Rpath developed by NOAA's Northeast Fisheries Science Center.

Key Features
Ecopath Mass Balance
  • Define functional groups and food web structure
  • Set biomass, production, and consumption rates
  • Automatic calculation of missing parameters
  • Trophic level computation
  • Multi-stanza age structure
Ecosim Simulation
  • Foraging arena-based functional response
  • Vulnerability parameters for top-down/bottom-up control
  • Fishing effort scenarios
  • Environmental forcing
  • Diet rewiring (prey switching)
Ecospace Spatial Modeling
  • Irregular polygon grids (GeoJSON, Shapefile)
  • Habitat preference mapping
  • Dispersal and movement dynamics
  • Environmental drivers
  • Spatial fishing effort allocation
Individual-Based Model (IBM)
  • Super-individual tracking
  • Wisconsin bioenergetics model
  • Size-structured predation
  • Stochastic reproduction
  • Spatial movement and adaptive foraging
Network Analysis
  • Food web topology metrics
  • Trophic impact analysis (MTI)
  • Keystone species identification
  • Lindeman spine diagrams
  • Pre-balance diagnostics
Visualization & Export
  • Interactive time series plots
  • Food web diagrams
  • Scenario comparisons
  • Export to CSV/Excel
  • Spatial map visualizations
Scientific Background
Ecopath with Ecosim

Ecopath with Ecosim is a widely-used ecosystem modeling approach developed by Villy Christensen and Carl Walters. The approach consists of:

  1. Ecopath - Creates a static, mass-balanced snapshot of an ecosystem
  2. Ecosim - Projects the ecosystem forward in time under various scenarios
  3. Ecospace - Adds spatial dynamics with irregular polygon grids
  4. IBM - Individual-based modeling for tracking super-individuals with bioenergetics and life history
Key Equations

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ᵢ
References
  • Christensen, V., & Walters, C. J. (2004). Ecopath with Ecosim: methods, capabilities and limitations. Ecological Modelling, 172(2-4), 109-139.
  • Lucey, S. M., et al. (2020). Conducting Management Strategy Evaluation for the Northeast US Continental Shelf. Frontiers in Marine Science, 7, 1029.
Development
Technology Stack
  • Python 3.10+
  • NumPy for numerical computations
  • SciPy for optimization and integration
  • Pandas for data handling
  • Shiny for Python for the web interface
  • Matplotlib for visualization
License

MIT License

PyPath is free and open source software. Contributions are welcome!

Version Information
Python: 3.13.12
PyPath-EwE: 0.4.2
PyPath-Shiny: 0.4.1
Shiny: 1.5.1
NumPy: 2.4.2
Pandas: 2.3.3
SciPy: 1.16.3