Loading Native EwE Databases¶
This guide shows how to load and run models from Ecopath with Ecosim's
native .eweaccdb database format. This is the recommended workflow
when working with existing EwE models.
Prerequisites¶
Loading EwE databases requires a Microsoft Access ODBC driver:
- Windows: Usually pre-installed (Microsoft Access Database Engine)
- Linux/macOS: Install
mdbtools(apt install mdbtoolsorbrew install mdbtools)
Quick Start: One-Line Scenario Loading¶
The fastest way to get a running Ecosim simulation from an EwE database:
from pypath.io.ewemdb import ecosim_scenario_from_ewemdb
from pypath import rsim_run
# Load scenario 16 (calibrated) with all EwE settings
scenario = ecosim_scenario_from_ewemdb("LT2022_model.eweaccdb", scenario=16)
output = rsim_run(scenario, method="AB")
# Annual biomass: shape (n_years+1, n_groups+1)
print(output.annual_Biomass.shape)
ecosim_scenario_from_ewemdb reads from the database in a single call:
- Ecopath parameters (biomass, diet, stanzas)
- Ecopath mass-balance (calls
rpath()internally) - Ecosim scenario settings (time span, integration step)
- Vulnerability matrix overrides per predator-prey link
- Foraging time adjustments per group
- Forced biomass time series
- Fishing effort time series
- Environmental forcing functions
Step-by-Step: Ecopath Only¶
If you only need Ecopath (no Ecosim):
from pypath import read_ewemdb, rpath
# Load just Ecopath parameters
params = read_ewemdb("model.eweaccdb")
# Balance the model
model = rpath(params)
# Inspect results
print(f"Groups: {model.NUM_GROUPS}")
print(f"Living: {model.NUM_LIVING}")
for i in range(model.NUM_GROUPS):
print(f" {model.Group[i]:20s} B={model.Biomass[i]:.4f} EE={model.EE[i]:.4f}")
Exploring Database Contents¶
List Available Tables¶
from pypath.io.ewemdb import list_ewemdb_tables
tables = list_ewemdb_tables("model.eweaccdb")
print(f"{len(tables)} tables found")
for t in sorted(tables):
print(f" {t}")
Read Any Table¶
from pypath.io.ewemdb import read_ewemdb_table
# List available Ecosim scenarios
scenarios = read_ewemdb_table("model.eweaccdb", "EcosimScenario")
print(scenarios[["ScenarioID", "ScenarioName", "TotalTime"]])
# Read the vulnerability matrix for scenario 16
vv = read_ewemdb_table("model.eweaccdb", "EcosimScenarioForcingMatrix")
print(f"{len(vv)} predator-prey vulnerability entries")
# Read time series data
ts = read_ewemdb_table("model.eweaccdb", "EcosimTimeSeries")
print(f"{len(ts)} time series records")
Get Model Metadata¶
from pypath.io.ewemdb import get_ewemdb_metadata
meta = get_ewemdb_metadata("model.eweaccdb")
print(f"Model: {meta.get('name', 'unknown')}")
print(f"Description: {meta.get('description', '')}")
Running Multiple Scenarios¶
EwE databases often contain multiple Ecosim scenarios (e.g., uncalibrated baseline, calibrated fit, management projections):
from pypath.io.ewemdb import ecosim_scenario_from_ewemdb, read_ewemdb_table
from pypath import rsim_run
# List scenarios
scenarios_df = read_ewemdb_table("model.eweaccdb", "EcosimScenario")
print(scenarios_df[["ScenarioID", "ScenarioName"]])
# Run scenario 1 (baseline, uncalibrated)
scen1 = ecosim_scenario_from_ewemdb("model.eweaccdb", scenario=1)
out1 = rsim_run(scen1, method="AB")
# Run scenario 16 (calibrated)
scen16 = ecosim_scenario_from_ewemdb("model.eweaccdb", scenario=16)
out16 = rsim_run(scen16, method="AB")
# Compare results
import numpy as np
print(f"Scenario 1 crashed groups: {out1.crashed_groups}")
print(f"Scenario 16 crashed groups: {out16.crashed_groups}")
Diagnosing and Fixing Unstable Scenarios¶
If a scenario produces crashes or explosive biomass, use the autofix module:
from pypath import read_ewemdb, rpath
from pypath.core.autofix import diagnose_crash_causes, autofix_parameters
# Load and balance
params = read_ewemdb("model.eweaccdb")
model = rpath(params)
# Build an Ecosim scenario
from pypath import rsim_scenario
scenario = rsim_scenario(model, params, years=range(1, 51))
# Diagnose potential issues
report = diagnose_crash_causes(model, scenario.params)
for issue in report["critical"]:
print(f"CRITICAL: {issue['type']} — group {issue['group']}: {issue['message']}")
for issue in report["warnings"]:
print(f"WARNING: {issue['type']} — {issue['message']}")
# Automatically fix parameters
fixed_params, result = autofix_parameters(model, scenario.params)
print(f"Fixes applied: {len(result.fixes_applied)}")
for fix in result.fixes_applied:
print(f" {fix}")
# Use the fixed parameters
scenario.params = fixed_params
output = rsim_run(scenario, method="AB")
Comparing with EwE Reference Output¶
To validate that PyPath reproduces EwE results, compare biomass trajectories against the EwE time series data stored in the database:
import numpy as np
from pypath.io.ewemdb import ecosim_scenario_from_ewemdb, read_ewemdb_table
from pypath import rsim_run, read_ewemdb, rpath
# Run simulation
scenario = ecosim_scenario_from_ewemdb("model.eweaccdb", scenario=16)
output = rsim_run(scenario, method="AB")
# Load observed time series from the database
model = rpath(read_ewemdb("model.eweaccdb"))
ts = read_ewemdb_table("model.eweaccdb", "EcosimTimeSeries")
# Calculate sum of squares for relative biomass series
# (DatType=0 means relative biomass)
biomass_ts = ts[ts["DatType"] == 0]
total_ss = 0.0
for _, row in biomass_ts.iterrows():
group_idx = row["GroupID"] # map to model group index
observed = np.array([float(x) for x in str(row["TimeValues"]).split()])
simulated = output.annual_Biomass[:, group_idx + 1] / model.Biomass[group_idx]
n = min(len(observed), len(simulated))
total_ss += np.sum((simulated[:n] - observed[:n]) ** 2)
print(f"Total SS: {total_ss:.1f}")
Exporting Models Back to EwE Format¶
PyPath can write models back to native EwE 6.6+ format. The exported databases use the correct EwE 6.6+ schema and load directly in the EwE desktop application.
Round-Trip: Read, Modify, Write¶
from pypath.io.ewemdb import read_ewemdb
from pypath.io.ewe_writer import write_ewemdb
# Load existing model
params = read_ewemdb("original_model.eweaccdb")
# Modify parameters
params.model.loc[0, "Biomass"] = 12.5 # Adjust phytoplankton biomass
# Write back to EwE format
write_ewemdb(params, "modified_model.eweaccdb")
Export to CSV Bundle (Cross-Platform)¶
If you don't have the Access ODBC driver (Linux/macOS), use the CSV bundle format:
write_ewemdb(params, "my_model.ewecsv.zip", backend="csv")
The CSV bundle is a ZIP file containing one CSV per EwE table, which can be imported by EwE or read back by PyPath.
Export with Ecosim Scenarios¶
from pypath import rsim_scenario, rpath
model = rpath(params)
scenario = rsim_scenario(model, params, years=range(1, 51))
write_ewemdb(params, "with_ecosim.eweaccdb", scenarios=[scenario])
Common EwE Database Tables¶
| Table | Contents |
|---|---|
EcopathGroup |
Group names, types, biomass, PB, QB, EE |
EcopathDietComp |
Diet composition matrix |
EcopathStanza / StanzaLifeStage |
Multi-stanza group definitions |
EcosimScenario |
Scenario names, time spans, settings |
EcosimScenarioForcingMatrix |
Vulnerability overrides per pred-prey link (Ecosim GroupIDs) |
EcosimScenarioGroup |
Per-group Ecosim settings (FtimeAdjust, etc.); maps Ecosim GroupID to EcopathGroupID |
EcosimTimeSeries |
Observed time series for calibration |
EcosimTimeSeriesGroup |
Time series to group mapping |
EcosimShape / EcosimShapeTime |
Forcing function shapes |
EcosimScenarioPredPreyShape |
Which shape acts on which link, and how (FunctionType: 1 search rate, 2 vulnerability, 6 production rate, 8 other mortality, ...) |
EcosimShapeFishRate |
Fishing effort time series |
Groups are identified by ID in every scenario table. EwE assigns IDs in
creation order, which is not the model order (EcopathGroup.Sequence), so
PyPath resolves them through EcopathGroup.GroupID → group name. A
production-rate shape on a producer scales its production only
(ForcedSearch on that group); a vulnerability shape scales a prey's
availability (ForcedPrey). Stanza growth uses EcopathGroup.vbK of the
leading life stage's group, as EwE6 does.
Curonian Lagoon End-to-End Example¶
A runnable Curonian workflow example is included at:
examples/curonian_model_workflow_example.py
It auto-selects an available Curonian/LT2022 database, picks a likely Ecosim scenario, and reports PASS/WARN/FAIL diagnostics for:
- Ecopath balance (with partial-diet aware checks)
- EwE parity for PB/QB/EE/Trophic Level
- Ecosim stability run
- Calibration smoke test (when time series exist)
python examples/curonian_model_workflow_example.py
python examples/curonian_model_workflow_example.py --scenario 16 --verbose
Use --strict-biomass if you want biomass parity mismatches treated as
hard failures instead of warnings.
EwE-F Models¶
EwE-F, the Fortran implementation
of Ecopath with Ecosim, keeps a model in CSV files named by a namelist
(*_filenames.nml). read_ewef reads the Ecopath part and
ecosim_scenario_from_ewef builds an Ecosim scenario from the Ecopath and
Ecosim inputs:
from pypath.core.ecopath import rpath
from pypath.core.ecosim import rsim_run
from pypath.io import ecosim_scenario_from_ewef, read_ewef
params = read_ewef("ecopath-f/testcases/Black_Sea") # or the .nml file
model = rpath(params)
scenario = ecosim_scenario_from_ewef(
"ecopath-f/testcases/Black_Sea", "ecosim-f/testcases/Black_Sea", years=range(1, 11)
)
output = rsim_run(scenario, method="AB")
For the Black Sea test case (tests/data/ewef/Black_Sea) PyPath reproduces
EwE-F's Ecopath biomass and EE for all 20 living groups to within 1e-5. Two
differences are known:
- Detritus EE: PyPath routes detritus between pools as Rpath does, counting a pool's own fate share; EwE 6 and EwE-F skip it and pass surpluses in group order. Models with detritus self-fate or chained detritus flows differ.
- Multi-stanza Q/B: PyPath ends the plus group where 99.999 % of the cumulative biomass is reached (Rpath); EwE-F uses its own maximum age. The juvenile anchovy Q/B differs by 3e-5.
Settings PyPath does not apply are reported in a warning: handling time (QBmax/QBo), predator effect on feeding time, density-dependent catchability, nutrient limitation and fishing forcing of type 4 or 5. Diet links without a vulnerability, which EwE-F's Ecosim skips, keep the default vulnerability, as in EwE 6.
Data/BlackSea_EwEF_testcase.eweaccdb is the same model as an EwE 6
database; read through read_ewemdb it gives the same Ecopath balance and the
same Ecosim settings.
Next Steps¶
- Basic Model Example — Create a model from scratch
- Spatial Modeling — Extend to Ecospace
- IBM Example — Add individual-based groups
- API Reference: I/O — Full ewemdb API docs
- API Reference: Autofix — Crash diagnostics