Skip to content

Example Models

PyPath ships three real food-web models, from EPath's EwE-F test cases, ready to balance and run. In the app, pick one from Open a real model… on the Home page, or under Example Model on the Ecosim page, which also balances it; its EwE-F Ecosim settings then become the starting scenario on the Ecosim page.

Name Model Groups Source
Central_Baltic Baltic Proper, 1974, modified for a stationary baseline 22 Tomczak et al. (2012), Ecological Modelling 230, 123–147
Curonian_Lagoon Curonian Lagoon pelagic food web, 2005–2007 19 Marine Research Institute, Klaipėda University
Lithuanian_Coast Exposed sandy coast of Lithuania, with round goby 44 Razinkovas-Baziukas et al. (2017), Estuarine, Coastal and Shelf Science 195, 110–123

Each model's folder (pypath/examples/data/<name>/) has a README with its source, the changes made to it and the files included: the EwE-F Ecopath inputs and the Ecosim settings (vulnerabilities, group settings, fishing forcing). PyPath's balance of each matches Ecopath-F's.

The Curonian Lagoon model is also a spatial model. It ships its own Ecospace set-up, from the same EwE-F case: a grid of 1,576 cells of 1 km (the lagoon and the Klaipėda strait) with the cells' depth and a habitat map per group (example_ecospace). As an alternative grid it has the 29 boxes of a SHYFEM box model of the lagoon (example_ecospace_grid), for which habitat maps and dispersal rates are yours to set. In the app, the Ecospace page offers both while the example is open: Load the example's Ecospace set-up and Load the example's grid.

Balance and run one

from pypath.core.ecopath import rpath
from pypath.core.ecosim import rsim_run
from pypath.examples import example_ecosim_scenario, load_example_model

params = load_example_model("Lithuanian_Coast")
balanced = rpath(params)

years = range(1, 11)
scenario = example_ecosim_scenario("Lithuanian_Coast", years=years)
result = rsim_run(scenario, method="RK4", years=years)

The Curonian Lagoon on its own grid

from pypath.examples import example_ecosim_scenario, example_ecospace
from pypath.spatial import rsim_run_spatial

years = range(1, 3)
scenario = example_ecosim_scenario("Curonian_Lagoon", years=years)
ecospace = example_ecospace("Curonian_Lagoon")  # 1,576 cells, 20 group rows
result = rsim_run_spatial(scenario, ecospace=ecospace, years=years)

The configuration is PyPath's Ecospace on the case's grid and habitat maps: each map, over its largest value, is its group's habitat capacity, and every group disperses at EwE's speed for a new Ecospace group (300 km a year, 10 for detritus) over cells of 1 km. Those two are chosen, as the EwE-F files do not hold them; pypath.io.ewef.read_ewef_ecospace takes others. EwE-F's own movement, and the case's advection field, are not reproduced.

The spatial run settles below the Ecopath biomasses

Over ten years the map totals settle at about 0.6 of the start for most groups. The phytoplankton map is the cause. In EwE 6's Ecospace, which PyPath follows, a producer's production in a cell is its capacity there times what it would be without it, and can rise only to the group's maximum relative P/B (2 by default): at capacity c the producer settles at (2c - 1) of its level at capacity 1, and at nothing where c is below 0.5. The map follows depth and is divided by its largest value, which puts 43 % of the lagoon's cells below 0.5. With every map uniform the totals stay at 1.000; with phytoplankton's maximum relative P/B at 5 they end between 0.82 and 0.97; with its pattern moved to EwE's relative primary production map (EcospaceParams.relative_pp) and its capacity uniform, between 0.80 and 1.04. This is what EwE 6's equations give for these maps, checked against EwE's source; there is no EwE 6 run of this model to compare numbers with. The maps were drawn for EwE-F, which rescales each to a mean of 1. The example's README has the figures.

The Curonian Lagoon on its 29 boxes

import numpy as np
from pypath.examples import example_ecosim_scenario, example_ecospace_grid
from pypath.spatial import EcospaceParams, rsim_run_spatial

years = range(1, 3)
scenario = example_ecosim_scenario("Curonian_Lagoon", years=years)
grid = example_ecospace_grid("Curonian_Lagoon")  # 29 patches, one per box
n = scenario.params.NUM_GROUPS
ecospace = EcospaceParams(
    grid=grid,
    habitat_preference=np.ones((n, grid.n_patches)),
    habitat_capacity=np.ones((n, grid.n_patches)),
    dispersal_rate=np.full(n, 1.0),
    advection_enabled=np.zeros(n, dtype=bool),
    gravity_strength=np.zeros(n),
)
result = rsim_run_spatial(scenario, ecospace=ecospace, years=years)

The grid's element types are the box numbers, so the box model's own output fits it: see the hydrodynamic link for fields, water transport and a capacity by month.

An Ecospace scenario from an EwE database

pypath.io.read_ecospace reads a database's Ecospace scenario: its grid (the water cells of the depth map), each group's habitat capacity and its dispersal rates. It has a row for each living and detritus group; a run also needs the fleets' rows, which with_group_rows adds:

from pypath.io import read_ecospace
from pypath.io.ewemdb import ecosim_scenario_from_ewemdb

scenario = ecosim_scenario_from_ewemdb("model.eweaccdb", scenario=1)
p = scenario.params
read = read_ecospace("model.eweaccdb", n_groups=p.NUM_LIVING + p.NUM_DEAD)
ecospace = read.ecospace.with_group_rows(p.NUM_GROUPS)

EwE places a cell as the same number of degrees each way, which draws a grid of km cells too narrow east to west (by cos(latitude): 0.57 at 55 N). cell_placement="ground" puts the cells where they lie on the ground instead; geometry=True keeps them as polygons for a map. Only the position changes: the run is the same on either placement.

read = read_ecospace(
    "model.eweaccdb",
    n_groups=p.NUM_LIVING + p.NUM_DEAD,
    cell_placement="ground",
    geometry=True,
)

In the app, the Ecospace page offers the scenarios of the database you imported under Stored Ecospace Scenario, placed on the ground unless you choose EwE's coordinates.

API

pypath.examples

Example models shipped with PyPath.

Three EwE-F models from EPath's test cases, each with its Ecopath inputs (scenario, diet, detritus fate, growth) and its Ecosim settings (vulnerabilities, group settings, fishing forcing). Each model's folder has a README with its source and the changes made to it. The Curonian Lagoon model is also a spatial model: its own Ecospace set-up on a grid of 1 km cells with a habitat map per group (example_ecospace), and as an alternative grid the 29 boxes of a SHYFEM box model (example_ecospace_grid).

Examples:

>>> from pypath.examples import list_example_models, load_example_model
>>> [m.name for m in list_example_models()]
['Central_Baltic', 'Curonian_Lagoon', 'Lithuanian_Coast']
>>> params = load_example_model("Central_Baltic")  # RpathParams, for rpath()

ExampleModel dataclass

An example model: its name, what it is and where it comes from.

Attributes:

Name Type Description
name str

The name to load it by, also its folder in pypath/examples/data.

title str

A short title.

description str

The food web, its groups and the changes made to the source model.

source str

The publication or institution the model comes from.

provenance tuple of (str, str)

Where the model's data and parameters come from, section by section (the food web, the Ecopath data, the changes made to the source, the Ecosim parameters, the Ecospace inputs, the files and the checks), as (heading, text) pairs. Drawn from the model folder's README files.

Source code in pypath/examples/__init__.py
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
@dataclass(frozen=True)
class ExampleModel:
    """An example model: its name, what it is and where it comes from.

    Attributes
    ----------
    name : str
        The name to load it by, also its folder in ``pypath/examples/data``.
    title : str
        A short title.
    description : str
        The food web, its groups and the changes made to the source model.
    source : str
        The publication or institution the model comes from.
    provenance : tuple of (str, str)
        Where the model's data and parameters come from, section by section
        (the food web, the Ecopath data, the changes made to the source, the
        Ecosim parameters, the Ecospace inputs, the files and the checks), as
        (heading, text) pairs. Drawn from the model folder's README files.
    """

    name: str
    title: str
    description: str
    source: str
    provenance: Tuple[Tuple[str, str], ...] = ()

    @property
    def path(self) -> Path:
        """The model's folder."""
        return DATA / self.name

    @property
    def ecopath_path(self) -> Path:
        """The EwE-F Ecopath inputs (folder with the ``filenames.nml``)."""
        return self.path / "ecopath"

    @property
    def ecosim_path(self) -> Path:
        """The EwE-F Ecosim inputs (folder with the ``filenames.nml``)."""
        return self.path / "ecosim"

    @property
    def ecospace_path(self) -> Optional[Path]:
        """The EwE-F Ecospace inputs (grid, depth, habitat maps), or None."""
        folder = self.path / "ecospace"
        return folder if any(folder.glob("*_grid.csv")) else None

    @property
    def grid_path(self) -> Optional[Path]:
        """The model's SHYFEM mesh (``.grd``) for Ecospace, or None."""
        meshes = sorted((self.path / "ecospace").glob("*.grd"))
        return meshes[0] if meshes else None
ecopath_path property
ecopath_path: Path

The EwE-F Ecopath inputs (folder with the filenames.nml).

ecosim_path property
ecosim_path: Path

The EwE-F Ecosim inputs (folder with the filenames.nml).

ecospace_path property
ecospace_path: Optional[Path]

The EwE-F Ecospace inputs (grid, depth, habitat maps), or None.

grid_path property
grid_path: Optional[Path]

The model's SHYFEM mesh (.grd) for Ecospace, or None.

path property
path: Path

The model's folder.

example_ecosim_scenario

example_ecosim_scenario(name: str, years: Optional[range] = None, fast_group_rule: Optional[str] = None) -> 'RsimScenario'

An Ecosim scenario with the example's own Ecosim settings.

Parameters:

Name Type Description Default
name str

An example's name (see :func:list_example_models).

required
years range

Simulation years; the default is the model's EwE-F run length.

None
fast_group_rule ('ewe', 'rpath')

Passed to :func:pypath.core.ecosim.rsim_scenario. Default: by the model's origin (compat): 'ewe' for EwE imports, 'rpath' otherwise, so 'ewe' for these EwE-F models.

'ewe'

Returns:

Type Description
RsimScenario

From :func:pypath.io.ewef.ecosim_scenario_from_ewef: the balanced model with the example's vulnerabilities, group settings and fishing.

Source code in pypath/examples/__init__.py
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
def example_ecosim_scenario(
    name: str,
    years: Optional[range] = None,
    fast_group_rule: Optional[str] = None,
) -> "RsimScenario":
    """An Ecosim scenario with the example's own Ecosim settings.

    Parameters
    ----------
    name : str
        An example's name (see :func:`list_example_models`).
    years : range, optional
        Simulation years; the default is the model's EwE-F run length.
    fast_group_rule : {'ewe', 'rpath'}, optional
        Passed to :func:`pypath.core.ecosim.rsim_scenario`. Default: by the
        model's origin (``compat``): ``'ewe'`` for EwE imports, ``'rpath'``
        otherwise, so ``'ewe'`` for these EwE-F models.

    Returns
    -------
    RsimScenario
        From :func:`pypath.io.ewef.ecosim_scenario_from_ewef`: the balanced
        model with the example's vulnerabilities, group settings and fishing.
    """
    from pypath.io.ewef import ecosim_scenario_from_ewef

    model = example_model(name)
    return ecosim_scenario_from_ewef(
        model.ecopath_path,
        model.ecosim_path,
        years=years,
        fast_group_rule=fast_group_rule,
    )

example_ecospace

example_ecospace(name: str, geometry: bool = False, cell_placement: str = 'ground') -> 'EcospaceParams'

An example's own Ecospace set-up, ready for a spatial run.

The grid's water cells as patches, each group's habitat capacity from its habitat map, and a dispersal rate per group, with a row for every group of the model (fleets included). Use it with :func:example_ecosim_scenario:

scenario = example_ecosim_scenario("Curonian_Lagoon") ecospace = example_ecospace("Curonian_Lagoon") out = rsim_run_spatial(scenario, ecospace=ecospace) # doctest: +SKIP

It is PyPath's Ecospace on the case's grid and maps (:func:pypath.io.ewef.read_ewef_ecospace says what is read and what is chosen), not EwE-F's own movement.

Parameters:

Name Type Description Default
name str

An example's name (see :func:list_example_models).

required
geometry bool

Keep the cells as polygons, for maps (needs geopandas and shapely).

False
cell_placement ('ground', 'ewe')

Where the cells are put; the run is the same either way.

"ground"

Returns:

Type Description
EcospaceParams

Raises:

Type Description
ValueError

If the example has no Ecospace set-up; the message names those that have one.

Source code in pypath/examples/__init__.py
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
def example_ecospace(
    name: str, geometry: bool = False, cell_placement: str = "ground"
) -> "EcospaceParams":
    """An example's own Ecospace set-up, ready for a spatial run.

    The grid's water cells as patches, each group's habitat capacity from
    its habitat map, and a dispersal rate per group, with a row for every
    group of the model (fleets included). Use it with
    :func:`example_ecosim_scenario`:

    >>> scenario = example_ecosim_scenario("Curonian_Lagoon")
    >>> ecospace = example_ecospace("Curonian_Lagoon")
    >>> out = rsim_run_spatial(scenario, ecospace=ecospace)  # doctest: +SKIP

    It is PyPath's Ecospace on the case's grid and maps
    (:func:`pypath.io.ewef.read_ewef_ecospace` says what is read and what
    is chosen), not EwE-F's own movement.

    Parameters
    ----------
    name : str
        An example's name (see :func:`list_example_models`).
    geometry : bool
        Keep the cells as polygons, for maps (needs geopandas and shapely).
    cell_placement : {"ground", "ewe"}
        Where the cells are put; the run is the same either way.

    Returns
    -------
    EcospaceParams

    Raises
    ------
    ValueError
        If the example has no Ecospace set-up; the message names those
        that have one.
    """
    from pypath.io.ewef import read_ewef, read_ewef_ecospace

    model = example_model(name)
    if model.ecospace_path is None:
        with_one = ", ".join(m.name for m in _CATALOG if m.ecospace_path is not None)
        raise ValueError(
            f"The example {model.name} has no Ecospace set-up; the examples "
            f"with one are: {with_one}"
        )
    params = read_ewef(model.ecopath_path)
    ecospace = read_ewef_ecospace(
        model.ecospace_path,
        params,
        ecosim_path=model.ecosim_path,
        cell_placement=cell_placement,
        geometry=geometry,
    )
    return ecospace.with_group_rows(len(params.model))

example_ecospace_grid

example_ecospace_grid(name: str, patches: str = 'type', geometry: bool = False) -> 'EcospaceGrid'

An example's alternative grid for Ecospace, from its SHYFEM mesh.

The boxes of a hydrodynamic box model, not the grid of the example's own Ecospace set-up (:func:example_ecospace). Only the grid: habitat maps and dispersal rates are yours to set (EcospaceParams). The element types of the mesh are the boxes of the hydrodynamic box model, so the model's box output (pypath.io.shyfem.read_box_series) fits the grid as it is.

Parameters:

Name Type Description Default
name str

An example's name (see :func:list_example_models).

required
patches ('type', 'element')

One patch per element type (the boxes; default) or per element.

'type'
geometry bool

Also make the patches' polygons (needs geopandas and shapely).

False

Returns:

Type Description
EcospaceGrid

From :meth:pypath.spatial.EcospaceGrid.from_shyfem_grd.

Raises:

Type Description
ValueError

If the example has no grid; the message names those that have one.

Source code in pypath/examples/__init__.py
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
def example_ecospace_grid(
    name: str, patches: str = "type", geometry: bool = False
) -> "EcospaceGrid":
    """An example's alternative grid for Ecospace, from its SHYFEM mesh.

    The boxes of a hydrodynamic box model, not the grid of the example's
    own Ecospace set-up (:func:`example_ecospace`). Only the grid: habitat
    maps and dispersal rates are yours to set (``EcospaceParams``). The element types of the mesh are the boxes of
    the hydrodynamic box model, so the model's box output
    (``pypath.io.shyfem.read_box_series``) fits the grid as it is.

    Parameters
    ----------
    name : str
        An example's name (see :func:`list_example_models`).
    patches : {'type', 'element'}
        One patch per element type (the boxes; default) or per element.
    geometry : bool
        Also make the patches' polygons (needs geopandas and shapely).

    Returns
    -------
    EcospaceGrid
        From :meth:`pypath.spatial.EcospaceGrid.from_shyfem_grd`.

    Raises
    ------
    ValueError
        If the example has no grid; the message names those that have one.
    """
    from pypath.spatial import EcospaceGrid

    model = example_model(name)
    if model.grid_path is None:
        with_grid = ", ".join(m.name for m in _CATALOG if m.grid_path is not None)
        raise ValueError(
            f"The example {model.name} has no spatial grid; the examples with "
            f"one are: {with_grid}"
        )
    return EcospaceGrid.from_shyfem_grd(
        model.grid_path, patches=patches, geometry=geometry
    )

example_model

example_model(name: str) -> ExampleModel

The example model of that name (case does not matter).

Raises:

Type Description
ValueError

If there is no example of that name; the message lists the names.

Source code in pypath/examples/__init__.py
319
320
321
322
323
324
325
326
327
328
329
330
331
332
def example_model(name: str) -> ExampleModel:
    """The example model of that name (case does not matter).

    Raises
    ------
    ValueError
        If there is no example of that name; the message lists the names.
    """
    wanted = str(name).strip().lower()
    for model in _CATALOG:
        if model.name.lower() == wanted:
            return model
    names = ", ".join(m.name for m in _CATALOG)
    raise ValueError(f"No example model {name!r}; the examples are: {names}")

list_example_models

list_example_models() -> List[ExampleModel]

The example models shipped with PyPath, in name order.

Source code in pypath/examples/__init__.py
314
315
316
def list_example_models() -> List[ExampleModel]:
    """The example models shipped with PyPath, in name order."""
    return list(_CATALOG)

load_example_model

load_example_model(name: str) -> 'RpathParams'

An example model's Ecopath parameters, ready for rpath.

Parameters:

Name Type Description Default
name str

An example's name (see :func:list_example_models).

required

Returns:

Type Description
RpathParams

Read with :func:pypath.io.ewef.read_ewef.

Source code in pypath/examples/__init__.py
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
def load_example_model(name: str) -> "RpathParams":
    """An example model's Ecopath parameters, ready for ``rpath``.

    Parameters
    ----------
    name : str
        An example's name (see :func:`list_example_models`).

    Returns
    -------
    RpathParams
        Read with :func:`pypath.io.ewef.read_ewef`.
    """
    from pypath.io.ewef import read_ewef

    return read_ewef(example_model(name).ecopath_path)