Skip to content

Spatial API Reference (Ecospace)

Ecospace extends Ecosim into two-dimensional space, simulating biomass dynamics across a grid of interconnected patches. Each patch runs its own Ecosim-like derivative computation while species disperse, advect, and respond to spatially varying habitat and environmental conditions.

Functional Development Workflows

Workflow Primary API Entry Points Typical Outcome
Coupled state-vector initialization build_initial_state_vector() Convert total-biomass vectors into patch-resolved coupled vectors
End-to-end coupled run run_coupled_simulation(), rsim_run_spatial() Spatially explicit Ecosim-Ecospace simulation with optional vector roundtrip
Patch-level custom derivatives deriv_vector_spatial() Direct access to local+movement derivative calculations for custom integrators
Spatial policy controls rsim_run_spatial(..., mpa=..., spatial_fishing=..., environmental_drivers=...) Marine protected area closures, fleet redistribution, and habitat/environment forcing

Coupled run pattern

from pypath.spatial import build_initial_state_vector
from pypath.spatial.integration import rsim_run_spatial

initial = build_initial_state_vector(
    total_biomass=scenario.start_state.Biomass,
    n_patches=ecospace.grid.n_patches,
    habitat_capacity=ecospace.habitat_capacity,
)

result = rsim_run_spatial(
    scenario,
    ecospace=ecospace,
    initial_state_vector=initial.values,
    store_state_vectors=True,
)

# New coupled outputs
spatial_biomass = result.out_Biomass_spatial
state_history = result.out_StateVector
state_final = result.state_vector_final

Core Data Structures

Parameters defining the spatial grid, habitat maps, dispersal rates, and environmental layers.

pypath.spatial.ecospace_params

ECOSPACE spatial parameter data structures.

This module defines the core data structures for spatial-temporal ecosystem modeling: - EcospaceGrid: Spatial grid configuration (irregular polygons) - EcospaceParams: Spatial parameters (habitat, dispersal, external flux) - SpatialState: Extended state for spatial simulation - ExternalFluxTimeseries: External flux data from ocean models

EcospaceGrid dataclass

Spatial grid configuration using irregular polygons.

Attributes:

Name Type Description
n_patches int

Number of spatial patches/cells

patch_ids ndarray

Unique identifiers for each patch [n_patches]

patch_areas ndarray

Area of each patch in km² [n_patches]

patch_centroids ndarray

(lon, lat) coordinates of patch centroids [n_patches, 2]

adjacency_matrix csr_matrix

Sparse adjacency matrix [n_patches, n_patches] 1 if patches share border, 0 otherwise

edge_lengths Dict[Tuple[int, int], float]

Border lengths (km) for adjacent patch pairs

crs str

Coordinate reference system (default: "EPSG:4326")

geometry Optional[GeoDataFrame]

GeoDataFrame with polygon geometries (if available)

Source code in pypath/spatial/ecospace_params.py
 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
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
@dataclass
class EcospaceGrid:
    """Spatial grid configuration using irregular polygons.

    Attributes
    ----------
    n_patches : int
        Number of spatial patches/cells
    patch_ids : np.ndarray
        Unique identifiers for each patch [n_patches]
    patch_areas : np.ndarray
        Area of each patch in km² [n_patches]
    patch_centroids : np.ndarray
        (lon, lat) coordinates of patch centroids [n_patches, 2]
    adjacency_matrix : scipy.sparse.csr_matrix
        Sparse adjacency matrix [n_patches, n_patches]
        1 if patches share border, 0 otherwise
    edge_lengths : Dict[Tuple[int, int], float]
        Border lengths (km) for adjacent patch pairs
    crs : str
        Coordinate reference system (default: "EPSG:4326")
    geometry : Optional[gpd.GeoDataFrame]
        GeoDataFrame with polygon geometries (if available)
    """

    n_patches: int
    patch_ids: np.ndarray
    patch_areas: np.ndarray
    patch_centroids: np.ndarray
    adjacency_matrix: scipy.sparse.csr_matrix
    edge_lengths: Dict[Tuple[int, int], float]
    crs: str = "EPSG:4326"
    geometry: Optional[object] = None  # gpd.GeoDataFrame when available
    cell_metadata: Optional["pd.DataFrame"] = (
        None  # row/col/depth/habitat_type_id per patch
    )
    # Centroids on a plane in km [n_patches, 2]. When given, distances between
    # patches are taken from it instead of patch_centroids in degrees x 111.
    centroid_km: Optional[np.ndarray] = None
    # Distance in km between neighbouring patches, keyed (i, j) both ways.
    # When given, movement between neighbours uses it (a mesh grid measures
    # through the shared sides, which stays positive for nested zones).
    edge_distances: Optional[Dict[Tuple[int, int], float]] = None

    def __post_init__(self):
        """Validate grid data."""
        # Check dimensions
        if len(self.patch_ids) != self.n_patches:
            raise ValueError(
                f"patch_ids length ({len(self.patch_ids)}) != n_patches ({self.n_patches})"
            )
        if len(self.patch_areas) != self.n_patches:
            raise ValueError(
                f"patch_areas length ({len(self.patch_areas)}) != n_patches ({self.n_patches})"
            )
        if self.patch_centroids.shape != (self.n_patches, 2):
            raise ValueError(
                f"patch_centroids shape {self.patch_centroids.shape} != ({self.n_patches}, 2)"
            )
        if self.adjacency_matrix.shape != (self.n_patches, self.n_patches):
            raise ValueError(
                f"adjacency_matrix shape {self.adjacency_matrix.shape} != ({self.n_patches}, {self.n_patches})"
            )

        # Check that all areas are positive
        if np.any(self.patch_areas <= 0):
            raise ValueError("All patch areas must be positive")

        if self.centroid_km is not None:
            self.centroid_km = np.asarray(self.centroid_km, dtype=float)
            if self.centroid_km.shape != (self.n_patches, 2):
                raise ValueError(
                    f"centroid_km shape {self.centroid_km.shape} != ({self.n_patches}, 2)"
                )

        # Check that adjacency matrix is symmetric (sparse-safe)
        # Avoid densifying large adjacency matrices which can OOM; instead
        # check that (A - A.T) has no non-zero entries.
        diff = self.adjacency_matrix - self.adjacency_matrix.T
        if diff.nnz != 0:
            raise ValueError("Adjacency matrix must be symmetric")

    @classmethod
    def from_shapefile(
        cls,
        filepath: str,
        id_field: str = "id",
        area_field: Optional[str] = None,
        crs: Optional[str] = None,
    ) -> EcospaceGrid:
        """Create grid from shapefile or GeoJSON.

        Parameters
        ----------
        filepath : str
            Path to .shp, .geojson, or .gpkg file
        id_field : str
            Field containing unique patch IDs (default: "id")
        area_field : str, optional
            Field with pre-computed areas in km²
            If None, calculates from geometry
        crs : str, optional
            Force coordinate reference system (e.g., "EPSG:4326")

        Returns
        -------
        EcospaceGrid

        Raises
        ------
        ImportError
            If geopandas is not installed
        """
        if not _GIS_AVAILABLE:
            raise ImportError(
                "geopandas is required for shapefile support. "
                "Install with: pip install geopandas shapely rtree"
            )

        # Import here to avoid requiring geopandas if not using shapefiles
        from pypath.spatial.gis_utils import load_spatial_grid

        return load_spatial_grid(filepath, id_field, area_field, crs)

    @classmethod
    def from_shyfem_grd(
        cls,
        path,
        patches="element",
        *,
        units: str = "auto",
        crs: Optional[str] = None,
        geometry: bool = False,
    ) -> EcospaceGrid:
        """Create a grid from a SHYFEM finite-element mesh (``.grd``).

        ``pypath.spatial.mesh`` says how areas, borders and depth are made.

        Parameters
        ----------
        path : str, Path or pypath.io.shyfem.ShyfemMesh
            The ``.grd`` file or a mesh already read.
        patches : {"element", "type"} or np.ndarray
            One patch per element, one per element type (the box number of
            a SHYFEM box model), or a zone id per element.
        units : {"auto", "degrees", "m", "km"}
            Units of the file's coordinates; "auto" takes degrees when every
            coordinate can be a longitude and latitude.
        crs : str, optional
            Coordinate system to record on the grid.
        geometry : bool
            Also build the patch polygons (needs geopandas).
        """
        from pypath.spatial.mesh import grid_from_shyfem_grd

        return grid_from_shyfem_grd(
            path, patches, units=units, crs=crs, geometry=geometry
        )

    @classmethod
    def from_regular_grid(
        cls, bounds: Tuple[float, float, float, float], nx: int, ny: int
    ) -> EcospaceGrid:
        """Create regular rectangular grid (for testing).

        Parameters
        ----------
        bounds : Tuple[float, float, float, float]
            (min_lon, min_lat, max_lon, max_lat)
        nx : int
            Number of grid cells in x direction
        ny : int
            Number of grid cells in y direction

        Returns
        -------
        EcospaceGrid
        """
        from pypath.spatial.gis_utils import create_regular_grid

        return create_regular_grid(bounds, nx, ny)

    def get_neighbors(self, patch_idx: int) -> np.ndarray:
        """Get indices of neighboring patches.

        Parameters
        ----------
        patch_idx : int
            Index of patch

        Returns
        -------
        np.ndarray
            Indices of neighboring patches
        """
        return self.adjacency_matrix[patch_idx].nonzero()[1]

    def get_edge_length(self, patch_i: int, patch_j: int) -> float:
        """Get border length between two patches.

        Parameters
        ----------
        patch_i, patch_j : int
            Patch indices

        Returns
        -------
        float
            Border length in km (0 if not adjacent)
        """
        key = (min(patch_i, patch_j), max(patch_i, patch_j))
        return self.edge_lengths.get(key, 0.0)
__post_init__
__post_init__()

Validate grid data.

Source code in pypath/spatial/ecospace_params.py
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
def __post_init__(self):
    """Validate grid data."""
    # Check dimensions
    if len(self.patch_ids) != self.n_patches:
        raise ValueError(
            f"patch_ids length ({len(self.patch_ids)}) != n_patches ({self.n_patches})"
        )
    if len(self.patch_areas) != self.n_patches:
        raise ValueError(
            f"patch_areas length ({len(self.patch_areas)}) != n_patches ({self.n_patches})"
        )
    if self.patch_centroids.shape != (self.n_patches, 2):
        raise ValueError(
            f"patch_centroids shape {self.patch_centroids.shape} != ({self.n_patches}, 2)"
        )
    if self.adjacency_matrix.shape != (self.n_patches, self.n_patches):
        raise ValueError(
            f"adjacency_matrix shape {self.adjacency_matrix.shape} != ({self.n_patches}, {self.n_patches})"
        )

    # Check that all areas are positive
    if np.any(self.patch_areas <= 0):
        raise ValueError("All patch areas must be positive")

    if self.centroid_km is not None:
        self.centroid_km = np.asarray(self.centroid_km, dtype=float)
        if self.centroid_km.shape != (self.n_patches, 2):
            raise ValueError(
                f"centroid_km shape {self.centroid_km.shape} != ({self.n_patches}, 2)"
            )

    # Check that adjacency matrix is symmetric (sparse-safe)
    # Avoid densifying large adjacency matrices which can OOM; instead
    # check that (A - A.T) has no non-zero entries.
    diff = self.adjacency_matrix - self.adjacency_matrix.T
    if diff.nnz != 0:
        raise ValueError("Adjacency matrix must be symmetric")
from_regular_grid classmethod
from_regular_grid(bounds: Tuple[float, float, float, float], nx: int, ny: int) -> EcospaceGrid

Create regular rectangular grid (for testing).

Parameters:

Name Type Description Default
bounds Tuple[float, float, float, float]

(min_lon, min_lat, max_lon, max_lat)

required
nx int

Number of grid cells in x direction

required
ny int

Number of grid cells in y direction

required

Returns:

Type Description
EcospaceGrid
Source code in pypath/spatial/ecospace_params.py
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
@classmethod
def from_regular_grid(
    cls, bounds: Tuple[float, float, float, float], nx: int, ny: int
) -> EcospaceGrid:
    """Create regular rectangular grid (for testing).

    Parameters
    ----------
    bounds : Tuple[float, float, float, float]
        (min_lon, min_lat, max_lon, max_lat)
    nx : int
        Number of grid cells in x direction
    ny : int
        Number of grid cells in y direction

    Returns
    -------
    EcospaceGrid
    """
    from pypath.spatial.gis_utils import create_regular_grid

    return create_regular_grid(bounds, nx, ny)
from_shapefile classmethod
from_shapefile(filepath: str, id_field: str = 'id', area_field: Optional[str] = None, crs: Optional[str] = None) -> EcospaceGrid

Create grid from shapefile or GeoJSON.

Parameters:

Name Type Description Default
filepath str

Path to .shp, .geojson, or .gpkg file

required
id_field str

Field containing unique patch IDs (default: "id")

'id'
area_field str

Field with pre-computed areas in km² If None, calculates from geometry

None
crs str

Force coordinate reference system (e.g., "EPSG:4326")

None

Returns:

Type Description
EcospaceGrid

Raises:

Type Description
ImportError

If geopandas is not installed

Source code in pypath/spatial/ecospace_params.py
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
@classmethod
def from_shapefile(
    cls,
    filepath: str,
    id_field: str = "id",
    area_field: Optional[str] = None,
    crs: Optional[str] = None,
) -> EcospaceGrid:
    """Create grid from shapefile or GeoJSON.

    Parameters
    ----------
    filepath : str
        Path to .shp, .geojson, or .gpkg file
    id_field : str
        Field containing unique patch IDs (default: "id")
    area_field : str, optional
        Field with pre-computed areas in km²
        If None, calculates from geometry
    crs : str, optional
        Force coordinate reference system (e.g., "EPSG:4326")

    Returns
    -------
    EcospaceGrid

    Raises
    ------
    ImportError
        If geopandas is not installed
    """
    if not _GIS_AVAILABLE:
        raise ImportError(
            "geopandas is required for shapefile support. "
            "Install with: pip install geopandas shapely rtree"
        )

    # Import here to avoid requiring geopandas if not using shapefiles
    from pypath.spatial.gis_utils import load_spatial_grid

    return load_spatial_grid(filepath, id_field, area_field, crs)
from_shyfem_grd classmethod
from_shyfem_grd(path, patches='element', *, units: str = 'auto', crs: Optional[str] = None, geometry: bool = False) -> EcospaceGrid

Create a grid from a SHYFEM finite-element mesh (.grd).

pypath.spatial.mesh says how areas, borders and depth are made.

Parameters:

Name Type Description Default
path (str, Path or ShyfemMesh)

The .grd file or a mesh already read.

required
patches ('element', 'type')

One patch per element, one per element type (the box number of a SHYFEM box model), or a zone id per element.

"element"
units ('auto', 'degrees', 'm', 'km')

Units of the file's coordinates; "auto" takes degrees when every coordinate can be a longitude and latitude.

"auto"
crs str

Coordinate system to record on the grid.

None
geometry bool

Also build the patch polygons (needs geopandas).

False
Source code in pypath/spatial/ecospace_params.py
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
@classmethod
def from_shyfem_grd(
    cls,
    path,
    patches="element",
    *,
    units: str = "auto",
    crs: Optional[str] = None,
    geometry: bool = False,
) -> EcospaceGrid:
    """Create a grid from a SHYFEM finite-element mesh (``.grd``).

    ``pypath.spatial.mesh`` says how areas, borders and depth are made.

    Parameters
    ----------
    path : str, Path or pypath.io.shyfem.ShyfemMesh
        The ``.grd`` file or a mesh already read.
    patches : {"element", "type"} or np.ndarray
        One patch per element, one per element type (the box number of
        a SHYFEM box model), or a zone id per element.
    units : {"auto", "degrees", "m", "km"}
        Units of the file's coordinates; "auto" takes degrees when every
        coordinate can be a longitude and latitude.
    crs : str, optional
        Coordinate system to record on the grid.
    geometry : bool
        Also build the patch polygons (needs geopandas).
    """
    from pypath.spatial.mesh import grid_from_shyfem_grd

    return grid_from_shyfem_grd(
        path, patches, units=units, crs=crs, geometry=geometry
    )
get_edge_length
get_edge_length(patch_i: int, patch_j: int) -> float

Get border length between two patches.

Parameters:

Name Type Description Default
patch_i int

Patch indices

required
patch_j int

Patch indices

required

Returns:

Type Description
float

Border length in km (0 if not adjacent)

Source code in pypath/spatial/ecospace_params.py
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
def get_edge_length(self, patch_i: int, patch_j: int) -> float:
    """Get border length between two patches.

    Parameters
    ----------
    patch_i, patch_j : int
        Patch indices

    Returns
    -------
    float
        Border length in km (0 if not adjacent)
    """
    key = (min(patch_i, patch_j), max(patch_i, patch_j))
    return self.edge_lengths.get(key, 0.0)
get_neighbors
get_neighbors(patch_idx: int) -> np.ndarray

Get indices of neighboring patches.

Parameters:

Name Type Description Default
patch_idx int

Index of patch

required

Returns:

Type Description
ndarray

Indices of neighboring patches

Source code in pypath/spatial/ecospace_params.py
217
218
219
220
221
222
223
224
225
226
227
228
229
230
def get_neighbors(self, patch_idx: int) -> np.ndarray:
    """Get indices of neighboring patches.

    Parameters
    ----------
    patch_idx : int
        Index of patch

    Returns
    -------
    np.ndarray
        Indices of neighboring patches
    """
    return self.adjacency_matrix[patch_idx].nonzero()[1]

EcospaceParams dataclass

Spatial parameters for ECOSPACE simulation.

This extends the standard Ecosim parameters with spatial components. If ecospace=None in RsimScenario, simulation runs as non-spatial.

Per-group arrays have one row per Ecosim group: n_groups is the scenario's NUM_GROUPS (living, detritus and fleets), and row g - 1 is Ecosim group g. Unlike the state arrays they have no "Outside" row. rsim_run_spatial rejects fewer rows and warns about more.

Attributes:

Name Type Description
grid EcospaceGrid

Spatial grid configuration

habitat_preference ndarray

Habitat preference/suitability [n_groups, n_patches] Values 0-1 where 1 = optimal habitat

habitat_capacity ndarray

Habitat capacity multiplier [n_groups, n_patches] Affects local carrying capacity (1.0 = no effect)

dispersal_rate ndarray

Dispersal rate per year [n_groups]; 0 = no dispersal. Between neighbours, diffusion moves rate x density difference x mean patch area x border / distance per year (dispersal.diffusion_flux): on a regular grid, rate x (B_p - B_q). read_ecospace sets EwE's movement rate Mrate = Mvel / (3.14159 x CellLength).

advection_enabled ndarray

Enable habitat-directed movement [n_groups], boolean

gravity_strength ndarray

Strength of biomass-weighted movement [n_groups] 0 = no gravity effect

external_flux Optional[ExternalFluxTimeseries]

Externally provided flux (e.g., from ocean models) If provided for a group, overrides model-calculated dispersal

water_transport Optional[WaterTransport]

Monthly water flows between zones (a hydrodynamic box model's) and the groups they carry; see pypath.spatial.transport

monthly_capacity Optional[MonthlyCapacity]

A habitat capacity for every month for chosen groups, acting on the local dynamics and, with its movement=True, on movement between patches; see pypath.spatial.monthly_capacity

relative_pp Optional[ndarray]

Relative primary production of each patch [n_patches], not negative: EwE's relative primary production map (RelPP). Only its pattern matters; a run divides it by its area-weighted mean, so the map as a whole holds the nutrient Ecopath's does. In a patch the total nutrient is the map-wide total times the patch's value (cSpaceSolver.vb 570, 860), and the producers' production follows the free nutrient, at most doubling: with nearly all the nutrient free (EwE's default) a value s scales production by 2s / (1 + s). The nutrient is kept, the production is not: that response bends, so a map that varies leaves the producers' total below Ecopath's (cells of 1, 0.6 and 0.2: about 0.87). The same pattern as a habitat capacity, which caps their production, cuts it further (about 0.67; see the parity register, B-prod and B-relpp). It needs the EwE rule's nutrient limitation and applies to every producer. None (default): no map, as a map of 1 everywhere.

environmental_drivers Optional[object]

Time-varying environmental drivers (EnvironmentalDrivers instance). A run does not evaluate them: make a capacity from them with capacity_from_layers (one map) or MonthlyCapacity.from_layers (a map per month)

new_multi_stanza bool

Distribute multi-stanza groups as EwE's NewMultiStanza model (Ecospace ModelType 2, EwE's default for a new scenario): each life stage keeps a population index per patch and its map-wide total is spread by it (pypath.spatial.stanza_space). False spreads each stage's total by the patches' current shares of it. read_ecospace sets it from the scenario's ModelType.

detritus_pass_on bool

Pass detritus from one detritus pool to another in each patch, as Ecosim does (DetPassedProp x B x DF under the EwE rule, the pool's detritus links under Rpath's). False (the default) follows EwE 6.7.144's Ecospace, where no pool receives anything from another (cSpaceSolver.vb 1519-1526); a donor still loses its share in the export rate taken from Ecosim. With False a uniform map differs from Ecosim for a model whose detritus pools pass to each other.

Source code in pypath/spatial/ecospace_params.py
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
443
444
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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
@dataclass
class EcospaceParams:
    """Spatial parameters for ECOSPACE simulation.

    This extends the standard Ecosim parameters with spatial components.
    If ecospace=None in RsimScenario, simulation runs as non-spatial.

    Per-group arrays have one row per Ecosim group: n_groups is the
    scenario's NUM_GROUPS (living, detritus and fleets), and row g - 1 is
    Ecosim group g. Unlike the state arrays they have no "Outside" row.
    ``rsim_run_spatial`` rejects fewer rows and warns about more.

    Attributes
    ----------
    grid : EcospaceGrid
        Spatial grid configuration
    habitat_preference : np.ndarray
        Habitat preference/suitability [n_groups, n_patches]
        Values 0-1 where 1 = optimal habitat
    habitat_capacity : np.ndarray
        Habitat capacity multiplier [n_groups, n_patches]
        Affects local carrying capacity (1.0 = no effect)
    dispersal_rate : np.ndarray
        Dispersal rate per year [n_groups]; 0 = no dispersal. Between
        neighbours, diffusion moves rate x density difference x mean patch
        area x border / distance per year (``dispersal.diffusion_flux``): on
        a regular grid, rate x (B_p - B_q). ``read_ecospace`` sets EwE's
        movement rate Mrate = Mvel / (3.14159 x CellLength).
    advection_enabled : np.ndarray
        Enable habitat-directed movement [n_groups], boolean
    gravity_strength : np.ndarray
        Strength of biomass-weighted movement [n_groups]
        0 = no gravity effect
    external_flux : Optional[ExternalFluxTimeseries]
        Externally provided flux (e.g., from ocean models)
        If provided for a group, overrides model-calculated dispersal
    water_transport : Optional[WaterTransport]
        Monthly water flows between zones (a hydrodynamic box model's) and
        the groups they carry; see ``pypath.spatial.transport``
    monthly_capacity : Optional[MonthlyCapacity]
        A habitat capacity for every month for chosen groups, acting on the
        local dynamics and, with its ``movement=True``, on movement between
        patches; see ``pypath.spatial.monthly_capacity``
    relative_pp : Optional[np.ndarray]
        Relative primary production of each patch [n_patches], not
        negative: EwE's relative primary production map (``RelPP``). Only
        its pattern matters; a run divides it by its area-weighted mean, so
        the map as a whole holds the nutrient Ecopath's does. In a patch
        the total nutrient is the map-wide total times the patch's value
        (``cSpaceSolver.vb`` 570, 860), and the producers' production
        follows the free nutrient, at most doubling: with nearly all the
        nutrient free (EwE's default) a value s scales production by
        2s / (1 + s). The nutrient is kept, the production is not: that
        response bends, so a map that varies leaves the producers' total
        below Ecopath's (cells of 1, 0.6 and 0.2: about 0.87). The same
        pattern as a habitat capacity, which caps their production, cuts
        it further (about 0.67; see the parity register, B-prod and
        B-relpp). It needs the EwE rule's nutrient limitation and applies
        to every producer. None (default): no map, as a map of 1
        everywhere.
    environmental_drivers : Optional[object]
        Time-varying environmental drivers (EnvironmentalDrivers instance).
        A run does not evaluate them: make a capacity from them with
        ``capacity_from_layers`` (one map) or ``MonthlyCapacity.from_layers``
        (a map per month)
    new_multi_stanza : bool
        Distribute multi-stanza groups as EwE's NewMultiStanza model
        (Ecospace ModelType 2, EwE's default for a new scenario): each life
        stage keeps a population index per patch and its map-wide total is
        spread by it (``pypath.spatial.stanza_space``). False spreads each
        stage's total by the patches' current shares of it.
        ``read_ecospace`` sets it from the scenario's ModelType.
    detritus_pass_on : bool
        Pass detritus from one detritus pool to another in each patch, as
        Ecosim does (DetPassedProp x B x DF under the EwE rule, the pool's
        detritus links under Rpath's). False (the default) follows EwE
        6.7.144's Ecospace, where no pool receives anything from another
        (cSpaceSolver.vb 1519-1526); a donor still loses its share in the
        export rate taken from Ecosim. With False a uniform map differs from
        Ecosim for a model whose detritus pools pass to each other.
    """

    grid: EcospaceGrid
    habitat_preference: np.ndarray
    habitat_capacity: np.ndarray
    dispersal_rate: np.ndarray
    advection_enabled: np.ndarray
    gravity_strength: np.ndarray
    external_flux: Optional[ExternalFluxTimeseries] = None
    environmental_drivers: Optional[object] = (
        None  # EnvironmentalDrivers when available
    )
    new_multi_stanza: bool = True
    detritus_pass_on: bool = False
    # Water flows between zones carrying chosen groups (WaterTransport of
    # pypath.spatial.transport), applied implicitly once a month. Last, so that
    # positional arguments keep their places.
    water_transport: Optional[object] = None
    # A capacity per month for chosen groups (MonthlyCapacity of
    # pypath.spatial.monthly_capacity): the month's feeding efficiency per
    # patch; habitat_capacity stays the base map.
    monthly_capacity: Optional[object] = None
    # EwE's relative primary production map (RelPP), per patch; a run divides
    # it by its area-weighted mean and scales each patch's total nutrient.
    relative_pp: Optional[np.ndarray] = None

    def with_group_rows(self, n_groups: int) -> "EcospaceParams":
        """A copy with one row per Ecosim group, fleets included.

        A run needs a row for every group of the scenario: living, detritus
        and fleets (``rsim_run_spatial``). A configuration read for the
        living and detritus groups only (``pypath.io.ewemdb.read_ecospace``)
        is short of the fleets' rows; they are added here as groups that
        live everywhere and do not move (preference and capacity 1, no
        dispersal). With ``n_groups`` rows already, ``self`` is returned.

        Raises
        ------
        ValueError
            If there are more rows than ``n_groups``.
        """
        rows = int(np.shape(self.habitat_preference)[0])
        n_groups = int(n_groups)
        if rows == n_groups:
            return self
        if rows > n_groups:
            raise ValueError(
                f"the configuration has {rows} group rows, more than the "
                f"{n_groups} groups asked for"
            )
        import dataclasses

        extra, n_patches = n_groups - rows, self.grid.n_patches
        ones = np.ones((extra, n_patches))
        return dataclasses.replace(
            self,
            habitat_preference=np.vstack([self.habitat_preference, ones]),
            habitat_capacity=np.vstack([self.habitat_capacity, ones]),
            dispersal_rate=np.concatenate([self.dispersal_rate, np.zeros(extra)]),
            advection_enabled=np.concatenate(
                [self.advection_enabled, np.zeros(extra, dtype=bool)]
            ),
            gravity_strength=np.concatenate([self.gravity_strength, np.zeros(extra)]),
        )

    def __post_init__(self):
        """Validate spatial parameters."""
        n_patches = self.grid.n_patches

        # Infer n_groups from habitat_preference
        if self.habitat_preference.ndim != 2:
            raise ValueError(
                f"habitat_preference must be 2D [n_groups, n_patches], got {self.habitat_preference.ndim}D"
            )

        n_groups = self.habitat_preference.shape[0]

        # Check habitat_preference dimensions
        if self.habitat_preference.shape != (n_groups, n_patches):
            raise ValueError(
                f"habitat_preference shape {self.habitat_preference.shape} != "
                f"({n_groups}, {n_patches})"
            )

        # Check habitat_capacity dimensions
        if self.habitat_capacity.shape != (n_groups, n_patches):
            raise ValueError(
                f"habitat_capacity shape {self.habitat_capacity.shape} != "
                f"({n_groups}, {n_patches})"
            )

        # Check dispersal_rate dimensions
        if len(self.dispersal_rate) != n_groups:
            raise ValueError(
                f"dispersal_rate length ({len(self.dispersal_rate)}) != n_groups ({n_groups})"
            )

        # Check advection_enabled dimensions
        if len(self.advection_enabled) != n_groups:
            raise ValueError(
                f"advection_enabled length ({len(self.advection_enabled)}) != n_groups ({n_groups})"
            )

        # Check gravity_strength dimensions
        if len(self.gravity_strength) != n_groups:
            raise ValueError(
                f"gravity_strength length ({len(self.gravity_strength)}) != n_groups ({n_groups})"
            )

        # Check value ranges
        if np.any(self.habitat_preference < 0) or np.any(self.habitat_preference > 1):
            raise ValueError("habitat_preference values must be in [0, 1]")

        if np.any(self.habitat_capacity < 0):
            raise ValueError("habitat_capacity values must be non-negative")

        if np.any(self.dispersal_rate < 0):
            raise ValueError("dispersal_rate values must be non-negative")

        if np.any(self.gravity_strength < 0):
            raise ValueError("gravity_strength values must be non-negative")

        if self.relative_pp is not None:
            self.relative_pp = np.asarray(self.relative_pp, dtype=float)
            if self.relative_pp.shape != (n_patches,):
                raise ValueError(
                    f"relative_pp shape {self.relative_pp.shape} != ({n_patches},)"
                )
            if not np.all(np.isfinite(self.relative_pp)) or np.any(
                self.relative_pp < 0
            ):
                raise ValueError("relative_pp must be finite and not negative")
            if not np.any(self.relative_pp > 0):
                raise ValueError("relative_pp is zero in every patch")
__post_init__
__post_init__()

Validate spatial parameters.

Source code in pypath/spatial/ecospace_params.py
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
def __post_init__(self):
    """Validate spatial parameters."""
    n_patches = self.grid.n_patches

    # Infer n_groups from habitat_preference
    if self.habitat_preference.ndim != 2:
        raise ValueError(
            f"habitat_preference must be 2D [n_groups, n_patches], got {self.habitat_preference.ndim}D"
        )

    n_groups = self.habitat_preference.shape[0]

    # Check habitat_preference dimensions
    if self.habitat_preference.shape != (n_groups, n_patches):
        raise ValueError(
            f"habitat_preference shape {self.habitat_preference.shape} != "
            f"({n_groups}, {n_patches})"
        )

    # Check habitat_capacity dimensions
    if self.habitat_capacity.shape != (n_groups, n_patches):
        raise ValueError(
            f"habitat_capacity shape {self.habitat_capacity.shape} != "
            f"({n_groups}, {n_patches})"
        )

    # Check dispersal_rate dimensions
    if len(self.dispersal_rate) != n_groups:
        raise ValueError(
            f"dispersal_rate length ({len(self.dispersal_rate)}) != n_groups ({n_groups})"
        )

    # Check advection_enabled dimensions
    if len(self.advection_enabled) != n_groups:
        raise ValueError(
            f"advection_enabled length ({len(self.advection_enabled)}) != n_groups ({n_groups})"
        )

    # Check gravity_strength dimensions
    if len(self.gravity_strength) != n_groups:
        raise ValueError(
            f"gravity_strength length ({len(self.gravity_strength)}) != n_groups ({n_groups})"
        )

    # Check value ranges
    if np.any(self.habitat_preference < 0) or np.any(self.habitat_preference > 1):
        raise ValueError("habitat_preference values must be in [0, 1]")

    if np.any(self.habitat_capacity < 0):
        raise ValueError("habitat_capacity values must be non-negative")

    if np.any(self.dispersal_rate < 0):
        raise ValueError("dispersal_rate values must be non-negative")

    if np.any(self.gravity_strength < 0):
        raise ValueError("gravity_strength values must be non-negative")

    if self.relative_pp is not None:
        self.relative_pp = np.asarray(self.relative_pp, dtype=float)
        if self.relative_pp.shape != (n_patches,):
            raise ValueError(
                f"relative_pp shape {self.relative_pp.shape} != ({n_patches},)"
            )
        if not np.all(np.isfinite(self.relative_pp)) or np.any(
            self.relative_pp < 0
        ):
            raise ValueError("relative_pp must be finite and not negative")
        if not np.any(self.relative_pp > 0):
            raise ValueError("relative_pp is zero in every patch")
with_group_rows
with_group_rows(n_groups: int) -> 'EcospaceParams'

A copy with one row per Ecosim group, fleets included.

A run needs a row for every group of the scenario: living, detritus and fleets (rsim_run_spatial). A configuration read for the living and detritus groups only (pypath.io.ewemdb.read_ecospace) is short of the fleets' rows; they are added here as groups that live everywhere and do not move (preference and capacity 1, no dispersal). With n_groups rows already, self is returned.

Raises:

Type Description
ValueError

If there are more rows than n_groups.

Source code in pypath/spatial/ecospace_params.py
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
def with_group_rows(self, n_groups: int) -> "EcospaceParams":
    """A copy with one row per Ecosim group, fleets included.

    A run needs a row for every group of the scenario: living, detritus
    and fleets (``rsim_run_spatial``). A configuration read for the
    living and detritus groups only (``pypath.io.ewemdb.read_ecospace``)
    is short of the fleets' rows; they are added here as groups that
    live everywhere and do not move (preference and capacity 1, no
    dispersal). With ``n_groups`` rows already, ``self`` is returned.

    Raises
    ------
    ValueError
        If there are more rows than ``n_groups``.
    """
    rows = int(np.shape(self.habitat_preference)[0])
    n_groups = int(n_groups)
    if rows == n_groups:
        return self
    if rows > n_groups:
        raise ValueError(
            f"the configuration has {rows} group rows, more than the "
            f"{n_groups} groups asked for"
        )
    import dataclasses

    extra, n_patches = n_groups - rows, self.grid.n_patches
    ones = np.ones((extra, n_patches))
    return dataclasses.replace(
        self,
        habitat_preference=np.vstack([self.habitat_preference, ones]),
        habitat_capacity=np.vstack([self.habitat_capacity, ones]),
        dispersal_rate=np.concatenate([self.dispersal_rate, np.zeros(extra)]),
        advection_enabled=np.concatenate(
            [self.advection_enabled, np.zeros(extra, dtype=bool)]
        ),
        gravity_strength=np.concatenate([self.gravity_strength, np.zeros(extra)]),
    )

ExternalFluxTimeseries dataclass

Externally generated flux timeseries from ocean models.

Allows users to provide pre-computed transport between patches from: - Ocean circulation models (ROMS, MITgcm, HYCOM) - Particle tracking systems (Ichthyop, OpenDrift, Parcels) - Connectivity matrices (genetic data, telemetry, mark-recapture)

Attributes:

Name Type Description
flux_data Union[ndarray, csr_matrix]

Flux timeseries with shape: - [n_timesteps, n_groups, n_patches, n_patches] for full format - Sparse format supported for memory efficiency flux_data[t, g, p, q] = flux from patch p to patch q for group g at time t

times ndarray

Time points (in years) corresponding to flux_data [n_timesteps]

group_indices ndarray

Which groups have external flux [n_groups_with_flux] Groups not in this list will use model-calculated dispersal

interpolate bool

Whether to use temporal interpolation (default: True)

format str

Data format: "flux_matrix" or "connectivity_matrix" - "flux_matrix": Direct flux values (biomass/time) - "connectivity_matrix": Proportions (0-1) scaled by biomass

validated bool

Whether flux conservation has been validated

Source code in pypath/spatial/ecospace_params.py
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
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
386
387
388
389
390
391
392
393
394
395
@dataclass
class ExternalFluxTimeseries:
    """Externally generated flux timeseries from ocean models.

    Allows users to provide pre-computed transport between patches from:
    - Ocean circulation models (ROMS, MITgcm, HYCOM)
    - Particle tracking systems (Ichthyop, OpenDrift, Parcels)
    - Connectivity matrices (genetic data, telemetry, mark-recapture)

    Attributes
    ----------
    flux_data : Union[np.ndarray, scipy.sparse.csr_matrix]
        Flux timeseries with shape:
        - [n_timesteps, n_groups, n_patches, n_patches] for full format
        - Sparse format supported for memory efficiency
        flux_data[t, g, p, q] = flux from patch p to patch q for group g at time t
    times : np.ndarray
        Time points (in years) corresponding to flux_data [n_timesteps]
    group_indices : np.ndarray
        Which groups have external flux [n_groups_with_flux]
        Groups not in this list will use model-calculated dispersal
    interpolate : bool
        Whether to use temporal interpolation (default: True)
    format : str
        Data format: "flux_matrix" or "connectivity_matrix"
        - "flux_matrix": Direct flux values (biomass/time)
        - "connectivity_matrix": Proportions (0-1) scaled by biomass
    validated : bool
        Whether flux conservation has been validated
    """

    flux_data: Union[np.ndarray, scipy.sparse.csr_matrix]
    times: np.ndarray
    group_indices: np.ndarray
    interpolate: bool = True
    format: str = "flux_matrix"
    validated: bool = False

    def __post_init__(self):
        """Validate external flux data."""
        # Check that times are sorted
        if not np.all(np.diff(self.times) > 0):
            raise ValueError("times must be strictly increasing")

        # Check format
        if self.format not in ["flux_matrix", "connectivity_matrix"]:
            raise ValueError(
                f"format must be 'flux_matrix' or 'connectivity_matrix', got '{self.format}'"
            )

        # Validate dimensions
        if isinstance(self.flux_data, np.ndarray):
            if self.flux_data.ndim != 4:
                raise ValueError(
                    f"flux_data must be 4D [time, group, patch, patch], got {self.flux_data.ndim}D"
                )
            if self.flux_data.shape[0] != len(self.times):
                raise ValueError(
                    f"flux_data time dimension ({self.flux_data.shape[0]}) != len(times) ({len(self.times)})"
                )

    def get_flux_at_time(self, t: float, group_idx: int) -> np.ndarray:
        """Get flux matrix at given time for group.

        Parameters
        ----------
        t : float
            Simulation time (years)
        group_idx : int
            Group index

        Returns
        -------
        np.ndarray
            Flux matrix [n_patches, n_patches]
            flux[p, q] = flux from patch p to patch q
        """
        # Find group in external flux data
        group_position = np.where(self.group_indices == group_idx)[0]
        if len(group_position) == 0:
            raise ValueError(f"Group {group_idx} not found in external flux")
        group_pos = group_position[0]

        # Get flux at time t (with interpolation if enabled)
        if self.interpolate:
            # Linear interpolation between timesteps
            if t <= self.times[0]:
                time_idx = 0
                flux_matrix = self.flux_data[0, group_pos]
            elif t >= self.times[-1]:
                time_idx = len(self.times) - 1
                flux_matrix = self.flux_data[-1, group_pos]
            else:
                # Find bracketing times
                idx_after = np.searchsorted(self.times, t)
                idx_before = idx_after - 1

                # Interpolation weight
                t_before = self.times[idx_before]
                t_after = self.times[idx_after]
                weight = (t - t_before) / (t_after - t_before)

                # Linear interpolation
                flux_before = self.flux_data[idx_before, group_pos]
                flux_after = self.flux_data[idx_after, group_pos]
                flux_matrix = (1 - weight) * flux_before + weight * flux_after
        else:
            # Nearest neighbor (no interpolation)
            time_idx = np.argmin(np.abs(self.times - t))
            flux_matrix = self.flux_data[time_idx, group_pos]

        # Convert to dense if sparse
        if scipy.sparse.issparse(flux_matrix):
            flux_matrix = flux_matrix.toarray()

        return flux_matrix

    @classmethod
    def from_netcdf(
        cls,
        filepath: str,
        time_var: str = "time",
        flux_var: str = "flux",
        group_mapping: Optional[Dict[str, int]] = None,
    ) -> ExternalFluxTimeseries:
        """Load external flux from NetCDF file.

        Parameters
        ----------
        filepath : str
            Path to NetCDF file
        time_var : str
            Name of time variable
        flux_var : str
            Name of flux variable
        group_mapping : dict, optional
            Map species names to group indices

        Returns
        -------
        ExternalFluxTimeseries
        """
        from pypath.spatial.external_flux import load_external_flux_from_netcdf

        return load_external_flux_from_netcdf(
            filepath, time_var, flux_var, group_mapping
        )
__post_init__
__post_init__()

Validate external flux data.

Source code in pypath/spatial/ecospace_params.py
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
def __post_init__(self):
    """Validate external flux data."""
    # Check that times are sorted
    if not np.all(np.diff(self.times) > 0):
        raise ValueError("times must be strictly increasing")

    # Check format
    if self.format not in ["flux_matrix", "connectivity_matrix"]:
        raise ValueError(
            f"format must be 'flux_matrix' or 'connectivity_matrix', got '{self.format}'"
        )

    # Validate dimensions
    if isinstance(self.flux_data, np.ndarray):
        if self.flux_data.ndim != 4:
            raise ValueError(
                f"flux_data must be 4D [time, group, patch, patch], got {self.flux_data.ndim}D"
            )
        if self.flux_data.shape[0] != len(self.times):
            raise ValueError(
                f"flux_data time dimension ({self.flux_data.shape[0]}) != len(times) ({len(self.times)})"
            )
from_netcdf classmethod
from_netcdf(filepath: str, time_var: str = 'time', flux_var: str = 'flux', group_mapping: Optional[Dict[str, int]] = None) -> ExternalFluxTimeseries

Load external flux from NetCDF file.

Parameters:

Name Type Description Default
filepath str

Path to NetCDF file

required
time_var str

Name of time variable

'time'
flux_var str

Name of flux variable

'flux'
group_mapping dict

Map species names to group indices

None

Returns:

Type Description
ExternalFluxTimeseries
Source code in pypath/spatial/ecospace_params.py
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
@classmethod
def from_netcdf(
    cls,
    filepath: str,
    time_var: str = "time",
    flux_var: str = "flux",
    group_mapping: Optional[Dict[str, int]] = None,
) -> ExternalFluxTimeseries:
    """Load external flux from NetCDF file.

    Parameters
    ----------
    filepath : str
        Path to NetCDF file
    time_var : str
        Name of time variable
    flux_var : str
        Name of flux variable
    group_mapping : dict, optional
        Map species names to group indices

    Returns
    -------
    ExternalFluxTimeseries
    """
    from pypath.spatial.external_flux import load_external_flux_from_netcdf

    return load_external_flux_from_netcdf(
        filepath, time_var, flux_var, group_mapping
    )
get_flux_at_time
get_flux_at_time(t: float, group_idx: int) -> np.ndarray

Get flux matrix at given time for group.

Parameters:

Name Type Description Default
t float

Simulation time (years)

required
group_idx int

Group index

required

Returns:

Type Description
ndarray

Flux matrix [n_patches, n_patches] flux[p, q] = flux from patch p to patch q

Source code in pypath/spatial/ecospace_params.py
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
def get_flux_at_time(self, t: float, group_idx: int) -> np.ndarray:
    """Get flux matrix at given time for group.

    Parameters
    ----------
    t : float
        Simulation time (years)
    group_idx : int
        Group index

    Returns
    -------
    np.ndarray
        Flux matrix [n_patches, n_patches]
        flux[p, q] = flux from patch p to patch q
    """
    # Find group in external flux data
    group_position = np.where(self.group_indices == group_idx)[0]
    if len(group_position) == 0:
        raise ValueError(f"Group {group_idx} not found in external flux")
    group_pos = group_position[0]

    # Get flux at time t (with interpolation if enabled)
    if self.interpolate:
        # Linear interpolation between timesteps
        if t <= self.times[0]:
            time_idx = 0
            flux_matrix = self.flux_data[0, group_pos]
        elif t >= self.times[-1]:
            time_idx = len(self.times) - 1
            flux_matrix = self.flux_data[-1, group_pos]
        else:
            # Find bracketing times
            idx_after = np.searchsorted(self.times, t)
            idx_before = idx_after - 1

            # Interpolation weight
            t_before = self.times[idx_before]
            t_after = self.times[idx_after]
            weight = (t - t_before) / (t_after - t_before)

            # Linear interpolation
            flux_before = self.flux_data[idx_before, group_pos]
            flux_after = self.flux_data[idx_after, group_pos]
            flux_matrix = (1 - weight) * flux_before + weight * flux_after
    else:
        # Nearest neighbor (no interpolation)
        time_idx = np.argmin(np.abs(self.times - t))
        flux_matrix = self.flux_data[time_idx, group_pos]

    # Convert to dense if sparse
    if scipy.sparse.issparse(flux_matrix):
        flux_matrix = flux_matrix.toarray()

    return flux_matrix

SpatialState dataclass

Extended state for spatial simulation.

Attributes:

Name Type Description
Biomass ndarray

Biomass state [n_groups+1, n_patches] Index 0 = "Outside" (detritus, patch-invariant)

N Optional[ndarray]

Numbers (for multi-stanza groups) [n_groups+1, n_patches]

Ftime Optional[ndarray]

Foraging time [n_groups+1, n_patches]

Source code in pypath/spatial/ecospace_params.py
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
@dataclass
class SpatialState:
    """Extended state for spatial simulation.

    Attributes
    ----------
    Biomass : np.ndarray
        Biomass state [n_groups+1, n_patches]
        Index 0 = "Outside" (detritus, patch-invariant)
    N : Optional[np.ndarray]
        Numbers (for multi-stanza groups) [n_groups+1, n_patches]
    Ftime : Optional[np.ndarray]
        Foraging time [n_groups+1, n_patches]
    """

    Biomass: np.ndarray
    N: Optional[np.ndarray] = None
    Ftime: Optional[np.ndarray] = None

    def collapse_to_total(self) -> np.ndarray:
        """Sum biomass across patches for compatibility.

        Returns
        -------
        np.ndarray
            Total biomass [n_groups+1]
        """
        return np.sum(self.Biomass, axis=1)

    def get_patch_biomass(self, patch_idx: int) -> np.ndarray:
        """Get biomass in a specific patch.

        Parameters
        ----------
        patch_idx : int
            Patch index

        Returns
        -------
        np.ndarray
            Biomass in patch [n_groups+1]
        """
        return self.Biomass[:, patch_idx]
collapse_to_total
collapse_to_total() -> np.ndarray

Sum biomass across patches for compatibility.

Returns:

Type Description
ndarray

Total biomass [n_groups+1]

Source code in pypath/spatial/ecospace_params.py
633
634
635
636
637
638
639
640
641
def collapse_to_total(self) -> np.ndarray:
    """Sum biomass across patches for compatibility.

    Returns
    -------
    np.ndarray
        Total biomass [n_groups+1]
    """
    return np.sum(self.Biomass, axis=1)
get_patch_biomass
get_patch_biomass(patch_idx: int) -> np.ndarray

Get biomass in a specific patch.

Parameters:

Name Type Description Default
patch_idx int

Patch index

required

Returns:

Type Description
ndarray

Biomass in patch [n_groups+1]

Source code in pypath/spatial/ecospace_params.py
643
644
645
646
647
648
649
650
651
652
653
654
655
656
def get_patch_biomass(self, patch_idx: int) -> np.ndarray:
    """Get biomass in a specific patch.

    Parameters
    ----------
    patch_idx : int
        Patch index

    Returns
    -------
    np.ndarray
        Biomass in patch [n_groups+1]
    """
    return self.Biomass[:, patch_idx]

Grid Creation & GIS Utilities

Functions for building regular, hexagonal, and irregular grids, plus coordinate transforms and shapefile integration via pyogrio.

pypath.spatial.gis_utils

GIS utilities for ECOSPACE spatial grids.

Functions for loading spatial grids from shapefiles/GeoJSON and creating regular grids for testing.

create_1d_grid

create_1d_grid(n_patches: int, spacing: float = 1.0) -> 'EcospaceGrid'

Create 1D chain of patches for testing.

Parameters:

Name Type Description Default
n_patches int

Number of patches

required
spacing float

Distance between patch centers (km)

1.0

Returns:

Type Description
EcospaceGrid
Source code in pypath/spatial/gis_utils.py
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
def create_1d_grid(n_patches: int, spacing: float = 1.0) -> "EcospaceGrid":
    """Create 1D chain of patches for testing.

    Parameters
    ----------
    n_patches : int
        Number of patches
    spacing : float
        Distance between patch centers (km)

    Returns
    -------
    EcospaceGrid
    """
    # Import here to avoid circular imports
    from pypath.spatial.ecospace_params import EcospaceGrid

    patch_ids = np.arange(n_patches)
    patch_areas = np.ones(n_patches)  # 1 km² each
    patch_centroids = np.column_stack(
        [
            np.arange(n_patches) * spacing,  # x coordinates
            np.zeros(n_patches),  # y coordinates (all at y=0)
        ]
    )

    # Build adjacency for 1D chain
    rows = []
    cols = []
    edge_lengths = {}

    for i in range(n_patches - 1):
        rows.extend([i, i + 1])
        cols.extend([i + 1, i])
        edge_lengths[(i, i + 1)] = 1.0  # Unit border length

    # Create sparse adjacency matrix
    data = np.ones(len(rows))
    adjacency_matrix = scipy.sparse.csr_matrix(
        (data, (rows, cols)), shape=(n_patches, n_patches)
    )

    return EcospaceGrid(
        n_patches=n_patches,
        patch_ids=patch_ids,
        patch_areas=patch_areas,
        patch_centroids=patch_centroids,
        adjacency_matrix=adjacency_matrix,
        edge_lengths=edge_lengths,
        crs="EPSG:4326",
        geometry=None,
    )

create_regular_grid

create_regular_grid(bounds: Tuple[float, float, float, float], nx: int, ny: int) -> 'EcospaceGrid'

Create regular rectangular grid for testing.

Parameters:

Name Type Description Default
bounds Tuple[float, float, float, float]

(min_lon, min_lat, max_lon, max_lat)

required
nx int

Number of grid cells in x direction

required
ny int

Number of grid cells in y direction

required

Returns:

Type Description
EcospaceGrid
Source code in pypath/spatial/gis_utils.py
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
def create_regular_grid(
    bounds: Tuple[float, float, float, float], nx: int, ny: int
) -> "EcospaceGrid":
    """Create regular rectangular grid for testing.

    Parameters
    ----------
    bounds : Tuple[float, float, float, float]
        (min_lon, min_lat, max_lon, max_lat)
    nx : int
        Number of grid cells in x direction
    ny : int
        Number of grid cells in y direction

    Returns
    -------
    EcospaceGrid
    """
    # Import here to avoid circular imports
    from pypath.spatial.ecospace_params import EcospaceGrid

    min_lon, min_lat, max_lon, max_lat = bounds

    # Grid spacing
    dx = (max_lon - min_lon) / nx
    dy = (max_lat - min_lat) / ny

    # Create grid cells
    n_patches = nx * ny
    patch_ids = np.arange(n_patches)
    patch_areas = np.full(n_patches, dx * dy * 111 * 111)  # Rough km² conversion
    patch_centroids = np.zeros((n_patches, 2))

    # Build adjacency matrix for regular grid
    # Patches are indexed row-major: patch_idx = iy * nx + ix
    rows = []
    cols = []
    edge_lengths = {}

    for iy in range(ny):
        for ix in range(nx):
            patch_idx = iy * nx + ix

            # Calculate centroid
            lon = min_lon + (ix + 0.5) * dx
            lat = min_lat + (iy + 0.5) * dy
            patch_centroids[patch_idx] = [lon, lat]

            # Add neighbors (rook adjacency: 4-connected)
            # Right neighbor
            if ix < nx - 1:
                neighbor_idx = iy * nx + (ix + 1)
                rows.extend([patch_idx, neighbor_idx])
                cols.extend([neighbor_idx, patch_idx])
                edge_key = (min(patch_idx, neighbor_idx), max(patch_idx, neighbor_idx))
                edge_lengths[edge_key] = dy * 111  # Rough km conversion

            # Top neighbor
            if iy < ny - 1:
                neighbor_idx = (iy + 1) * nx + ix
                rows.extend([patch_idx, neighbor_idx])
                cols.extend([neighbor_idx, patch_idx])
                edge_key = (min(patch_idx, neighbor_idx), max(patch_idx, neighbor_idx))
                edge_lengths[edge_key] = dx * 111  # Rough km conversion

    # Create sparse adjacency matrix
    data = np.ones(len(rows))
    adjacency_matrix = scipy.sparse.csr_matrix(
        (data, (rows, cols)), shape=(n_patches, n_patches)
    )

    return EcospaceGrid(
        n_patches=n_patches,
        patch_ids=patch_ids,
        patch_areas=patch_areas,
        patch_centroids=patch_centroids,
        adjacency_matrix=adjacency_matrix,
        edge_lengths=edge_lengths,
        crs="EPSG:4326",
        geometry=None,
    )

load_spatial_grid

load_spatial_grid(filepath: str, id_field: str = 'id', area_field: Optional[str] = None, crs: Optional[str] = None) -> 'EcospaceGrid'

Load spatial grid from shapefile or GeoJSON.

Parameters:

Name Type Description Default
filepath str

Path to .shp, .geojson, or .gpkg file

required
id_field str

Field containing unique patch IDs

'id'
area_field str

Field with pre-computed areas in km² If None, calculates from geometry

None
crs str

Force coordinate reference system (e.g., "EPSG:4326")

None

Returns:

Type Description
EcospaceGrid

Raises:

Type Description
ImportError

If geopandas is not installed

FileNotFoundError

If filepath does not exist

ValueError

If required fields are missing

Source code in pypath/spatial/gis_utils.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
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
def load_spatial_grid(
    filepath: str,
    id_field: str = "id",
    area_field: Optional[str] = None,
    crs: Optional[str] = None,
) -> "EcospaceGrid":
    """Load spatial grid from shapefile or GeoJSON.

    Parameters
    ----------
    filepath : str
        Path to .shp, .geojson, or .gpkg file
    id_field : str
        Field containing unique patch IDs
    area_field : str, optional
        Field with pre-computed areas in km²
        If None, calculates from geometry
    crs : str, optional
        Force coordinate reference system (e.g., "EPSG:4326")

    Returns
    -------
    EcospaceGrid

    Raises
    ------
    ImportError
        If geopandas is not installed
    FileNotFoundError
        If filepath does not exist
    ValueError
        If required fields are missing
    """
    if not _GIS_AVAILABLE:
        raise ImportError(
            "geopandas is required for shapefile support. "
            "Install with: pip install geopandas shapely rtree"
        )

    # Import here to avoid circular imports
    from pypath.spatial.connectivity import build_adjacency_from_gdf
    from pypath.spatial.ecospace_params import EcospaceGrid

    # Load GeoDataFrame
    gdf = gpd.read_file(filepath)

    # Force CRS if specified
    if crs is not None:
        gdf = gdf.to_crs(crs)

    # Check for required fields
    if id_field not in gdf.columns:
        raise ValueError(
            f"Field '{id_field}' not found in shapefile. Available: {list(gdf.columns)}"
        )

    n_patches = len(gdf)
    patch_ids = gdf[id_field].values

    # Calculate areas if not provided
    if area_field is None:
        # Project to equal-area CRS for accurate area calculation
        # EPSG:3857 (Web Mercator) is reasonable for most applications
        # For global datasets, use appropriate equal-area projection
        gdf_area = gdf.to_crs("EPSG:3857")  # Units: meters
        areas_m2 = gdf_area.geometry.area
        patch_areas = areas_m2 / 1e6  # Convert to km²
    else:
        if area_field not in gdf.columns:
            raise ValueError(
                f"Area field '{area_field}' not found. Available: {list(gdf.columns)}"
            )
        patch_areas = gdf[area_field].values

    # Calculate centroids
    centroids = gdf.geometry.centroid
    patch_centroids = np.array([[c.x, c.y] for c in centroids])

    # Build adjacency matrix
    adjacency, edge_metadata = build_adjacency_from_gdf(gdf)

    return EcospaceGrid(
        n_patches=n_patches,
        patch_ids=patch_ids,
        patch_areas=patch_areas,
        patch_centroids=patch_centroids,
        adjacency_matrix=adjacency,
        edge_lengths=edge_metadata["border_lengths"],
        crs=gdf.crs.to_string() if gdf.crs else "EPSG:4326",
        geometry=gdf,
    )

Finite-Element Meshes

Grids from a triangle mesh (SHYFEM's .grd): one patch per element, or one per zone of elements, with areas, borders and depth from the mesh. See the worked example.

pypath.spatial.mesh

Ecospace grids from finite-element meshes.

A mesh of triangles (or other polygons) becomes an EcospaceGrid with one patch per element, or one patch per zone of elements: SHYFEM marks zones by the element type, which a box model uses as the box number. A zone's area is the sum of its elements', the border between two zones is the total length of the element sides they share, and its depth the area-weighted mean.

Lengths and areas are in km. Degrees are projected first, by an azimuthal equidistant projection about the middle of the mesh: within about 500 km of that point lengths and areas are right to about 0.1 %. The sphere's radius is 6371.0088 km; SHYFEM's own element areas are about 0.2 % larger.

dispersal_rate_for_grid

dispersal_rate_for_grid(rate, from_grid: 'EcospaceGrid', to_grid: 'EcospaceGrid')

The dispersal rate on to_grid that spreads biomass as rate does on from_grid.

Ecospace's dispersal rate is an exchange rate between neighbouring patches: the flow is rate x mean patch area x border / distance x the density difference (pypath.spatial.dispersal.diffusion_flux). The diffusivity in km2 per year is therefore rate x mean patch area, and the same rate spreads biomass more slowly on a finer grid. This returns rate x mean area of from_grid / mean area of to_grid, which keeps the diffusivity: a release in one box of a 29-box mesh then spreads the same, within a few percent, on its 2027 elements.

Source code in pypath/spatial/mesh.py
42
43
44
45
46
47
48
49
50
51
52
53
54
55
def dispersal_rate_for_grid(rate, from_grid: "EcospaceGrid", to_grid: "EcospaceGrid"):
    """The dispersal rate on ``to_grid`` that spreads biomass as ``rate`` does on ``from_grid``.

    Ecospace's dispersal rate is an exchange rate between neighbouring
    patches: the flow is rate x mean patch area x border / distance x the
    density difference (``pypath.spatial.dispersal.diffusion_flux``). The
    diffusivity in km2 per year is therefore rate x mean patch area, and the
    same rate spreads biomass more slowly on a finer grid. This returns
    ``rate x mean area of from_grid / mean area of to_grid``, which keeps
    the diffusivity: a release in one box of a 29-box mesh then spreads the
    same, within a few percent, on its 2027 elements.
    """
    ratio = float(np.mean(from_grid.patch_areas)) / float(np.mean(to_grid.patch_areas))
    return np.asarray(rate, dtype=float) * ratio

grid_from_mesh

grid_from_mesh(xy: ndarray, elements: ndarray, zones: Optional[ndarray] = None, *, units: str = 'auto', element_depth: Optional[ndarray] = None, crs: Optional[str] = None, geometry: bool = False) -> 'EcospaceGrid'

Build an Ecospace grid from mesh nodes and elements.

Parameters:

Name Type Description Default
xy ndarray

Node coordinates [n_nodes, 2]: longitude and latitude in degrees, or x and y in metres or km.

required
elements ndarray

Node positions of each element [n_elements, n]; pad a shorter element with -1.

required
zones ndarray

A zone id per element. Elements of one zone make one patch. Without it every element is a patch.

None
units ('auto', 'degrees', 'm', 'km')

Units of xy. "auto" takes degrees when every coordinate can be a longitude and latitude, metres otherwise.

"auto"
element_depth ndarray

Depth of each element; a patch gets the area-weighted mean.

None
crs str

Coordinate system of xy. Degrees are "EPSG:4326" unless named. Metres and km without one make a "local" grid, whose centroids stay in the mesh's units: the run is right, but maps and the samplers of pypath.io.marine_data need longitude and latitude. With one (e.g. "EPSG:32630"; needs pyproj) the centroids and polygons are given in longitude and latitude and the grid is "EPSG:4326". Areas and lengths come from the mesh's own plane either way.

None
geometry bool

Also build the patches' polygons as a GeoDataFrame (needs geopandas; a zone's polygon is the union of its elements).

False

Returns:

Type Description
EcospaceGrid

patch_ids are the zone ids (or 0..n-1 per element), patch_centroids are in the units of xy (see crs), centroid_km holds them in km, edge_distances the distance between neighbours through their shared sides, and cell_metadata has zone, n_elements and depth per patch.

Source code in pypath/spatial/mesh.py
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
def grid_from_mesh(
    xy: np.ndarray,
    elements: np.ndarray,
    zones: Optional[np.ndarray] = None,
    *,
    units: str = "auto",
    element_depth: Optional[np.ndarray] = None,
    crs: Optional[str] = None,
    geometry: bool = False,
) -> "EcospaceGrid":
    """Build an Ecospace grid from mesh nodes and elements.

    Parameters
    ----------
    xy : np.ndarray
        Node coordinates [n_nodes, 2]: longitude and latitude in degrees, or
        x and y in metres or km.
    elements : np.ndarray
        Node positions of each element [n_elements, n]; pad a shorter
        element with -1.
    zones : np.ndarray, optional
        A zone id per element. Elements of one zone make one patch. Without
        it every element is a patch.
    units : {"auto", "degrees", "m", "km"}
        Units of ``xy``. "auto" takes degrees when every coordinate can be a
        longitude and latitude, metres otherwise.
    element_depth : np.ndarray, optional
        Depth of each element; a patch gets the area-weighted mean.
    crs : str, optional
        Coordinate system of ``xy``. Degrees are "EPSG:4326" unless named.
        Metres and km without one make a "local" grid, whose centroids stay
        in the mesh's units: the run is right, but maps and the samplers of
        ``pypath.io.marine_data`` need longitude and latitude. With one
        (e.g. "EPSG:32630"; needs pyproj) the centroids and polygons are
        given in longitude and latitude and the grid is "EPSG:4326". Areas
        and lengths come from the mesh's own plane either way.
    geometry : bool
        Also build the patches' polygons as a GeoDataFrame (needs geopandas;
        a zone's polygon is the union of its elements).

    Returns
    -------
    EcospaceGrid
        ``patch_ids`` are the zone ids (or 0..n-1 per element),
        ``patch_centroids`` are in the units of ``xy`` (see ``crs``), ``centroid_km``
        holds them in km, ``edge_distances`` the distance between neighbours
        through their shared sides, and ``cell_metadata`` has ``zone``,
        ``n_elements`` and ``depth`` per patch.
    """
    import pandas as pd

    from pypath.spatial.ecospace_params import EcospaceGrid

    if units not in _UNITS:
        raise ValueError(f"units must be one of {_UNITS}, not {units!r}")
    xy = np.asarray(xy, dtype=float)
    elements = np.asarray(elements, dtype=int)
    if units == "auto":
        units = mesh_units(xy)
    n_elements = len(elements)
    if zones is None:
        zone_ids = np.arange(n_elements)
        patch_of = np.arange(n_elements)
    else:
        zones = np.asarray(zones)
        if zones.shape != (n_elements,):
            raise ValueError(
                f"zones needs one value per element ({n_elements}), "
                f"got shape {zones.shape}"
            )
        zone_ids, patch_of = np.unique(zones, return_inverse=True)
    n_patches = len(zone_ids)

    km = _to_km(xy, units)
    area_e, centroid_e_km = _polygon_area_centroid(km, elements)
    if np.any(area_e <= 0) or not np.all(np.isfinite(centroid_e_km)):
        bad = int(np.flatnonzero(~(area_e > 0))[0]) if np.any(area_e <= 0) else -1
        raise ValueError(f"element at position {bad} has no area")
    _, centroid_e_xy = _polygon_area_centroid(xy - xy.mean(axis=0), elements)
    centroid_e_xy = centroid_e_xy + xy.mean(axis=0)

    area = np.bincount(patch_of, weights=area_e, minlength=n_patches)

    def _mean(values):
        return np.column_stack(
            [
                np.bincount(
                    patch_of, weights=area_e * values[:, k], minlength=n_patches
                )
                / area
                for k in range(values.shape[1])
            ]
        )

    centroid_km = _mean(centroid_e_km)
    centroid_xy = _mean(centroid_e_xy)

    # element sides: a side two elements share is an interface
    n_vert = (elements >= 0).sum(axis=1)
    width = elements.shape[1]
    owner = np.repeat(np.arange(n_elements), width)
    a = elements.reshape(-1)
    nxt = np.roll(elements, -1, axis=1)
    nxt[np.arange(n_elements), n_vert - 1] = elements[:, 0]
    b = nxt.reshape(-1)
    real = (np.arange(width)[None, :] < n_vert[:, None]).reshape(-1)
    owner, a, b = owner[real], a[real], b[real]
    lo, hi = np.minimum(a, b), np.maximum(a, b)
    key = lo.astype(np.int64) * (len(xy) + 1) + hi
    order = np.argsort(key, kind="stable")
    key_s, owner_s, lo_s, hi_s = key[order], owner[order], lo[order], hi[order]
    same = key_s[1:] == key_s[:-1]
    if np.any(same[1:] & same[:-1]):
        raise ValueError("a side belongs to more than two elements")
    first = np.flatnonzero(same)
    p, q = patch_of[owner_s[first]], patch_of[owner_s[first + 1]]
    length = np.linalg.norm(km[lo_s[first]] - km[hi_s[first]], axis=1)
    midpoint = 0.5 * (km[lo_s[first]] + km[hi_s[first]])
    between = p != q
    p, q, length, midpoint = p[between], q[between], length[between], midpoint[between]
    i, j = np.minimum(p, q), np.maximum(p, q)
    # the way from one centroid to the other through the shared side
    through = np.linalg.norm(centroid_km[p] - midpoint, axis=1) + np.linalg.norm(
        centroid_km[q] - midpoint, axis=1
    )
    path = scipy.sparse.coo_matrix(
        (length * through, (i, j)), shape=(n_patches, n_patches)
    ).tocsr()
    path.sum_duplicates()
    border = scipy.sparse.coo_matrix(
        (length, (i, j)), shape=(n_patches, n_patches)
    ).tocsr()  # duplicate (i, j) entries are summed
    border.sum_duplicates()
    rows, cols = border.nonzero()
    lengths = np.asarray(border[rows, cols]).reshape(-1)
    edge_lengths = {(int(r), int(c)): float(v) for r, c, v in zip(rows, cols, lengths)}
    # Distance between two neighbours: centroid to the shared sides and on to
    # the other centroid, weighted by the sides' lengths. For cells whose
    # shared side lies between the centroids it is the centroid distance; it
    # stays positive when two zones share a centroid (one inside the other).
    through_mean = np.asarray(path[rows, cols]).reshape(-1) / lengths
    edge_distances = {}
    for r, c, v in zip(rows, cols, through_mean):
        edge_distances[(int(r), int(c))] = edge_distances[(int(c), int(r))] = float(v)
    adjacency = scipy.sparse.csr_matrix(
        (np.ones(2 * len(rows)), (np.r_[rows, cols], np.r_[cols, rows])),
        shape=(n_patches, n_patches),
    )

    meta = pd.DataFrame(
        {
            "zone": zone_ids,
            "n_elements": np.bincount(patch_of, minlength=n_patches),
        }
    )
    if element_depth is not None:
        depth = np.asarray(element_depth, dtype=float)
        known = np.isfinite(depth)
        weight = np.bincount(patch_of, weights=area_e * known, minlength=n_patches)
        total = np.bincount(
            patch_of, weights=area_e * np.where(known, depth, 0.0), minlength=n_patches
        )
        with np.errstate(invalid="ignore", divide="ignore"):
            meta["depth"] = np.where(weight > 0, total / weight, np.nan)

    map_xy = xy
    if units == "degrees":
        crs = crs or "EPSG:4326"
    elif crs is None:
        crs = "local"
    else:
        # a projected mesh with a named system: centroids and polygons go to
        # longitude and latitude, which the maps and the data samplers read
        map_xy = _to_lonlat(xy * (1000.0 if units == "km" else 1.0), crs)
        _, centroid_e_xy = _polygon_area_centroid(
            map_xy - map_xy.mean(axis=0), elements
        )
        centroid_xy = _mean(centroid_e_xy + map_xy.mean(axis=0))
        crs = "EPSG:4326"
    geo = None
    if geometry:
        geo = _geometry(map_xy, elements, n_vert, patch_of, zone_ids, crs)

    return EcospaceGrid(
        n_patches=n_patches,
        patch_ids=zone_ids,
        patch_areas=area,
        patch_centroids=centroid_xy,
        adjacency_matrix=adjacency,
        edge_lengths=edge_lengths,
        crs=crs,
        geometry=geo,
        cell_metadata=meta,
        centroid_km=centroid_km,
        edge_distances=edge_distances,
    )

grid_from_shyfem_grd

grid_from_shyfem_grd(path: Union[str, Path, 'ShyfemMesh'], patches: Union[str, ndarray] = 'element', *, units: str = 'auto', crs: Optional[str] = None, geometry: bool = False) -> 'EcospaceGrid'

Build an Ecospace grid from a SHYFEM .grd mesh.

Depth is each element's own value, or else the mean of its nodes'.

Parameters:

Name Type Description Default
path (str, Path or ShyfemMesh)

The .grd file, or a mesh already read by pypath.io.shyfem.read_grd.

required
patches ('element', 'type')

"element": one patch per element. "type": one patch per element type, which is the box number in a SHYFEM box model. An array gives a zone id per element, in the file's element order.

"element"
units str

As in grid_from_mesh. A .grd file names no coordinate system, so check units when the automatic choice could be wrong.

'auto'
crs str

As in grid_from_mesh. A .grd file names no coordinate system, so check units when the automatic choice could be wrong.

'auto'
geometry str

As in grid_from_mesh. A .grd file names no coordinate system, so check units when the automatic choice could be wrong.

'auto'
Source code in pypath/spatial/mesh.py
339
340
341
342
343
344
345
346
347
348
349
350
351
352
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
386
387
388
389
def grid_from_shyfem_grd(
    path: Union[str, Path, "ShyfemMesh"],
    patches: Union[str, np.ndarray] = "element",
    *,
    units: str = "auto",
    crs: Optional[str] = None,
    geometry: bool = False,
) -> "EcospaceGrid":
    """Build an Ecospace grid from a SHYFEM ``.grd`` mesh.

    Depth is each element's own value, or else the mean of its nodes'.

    Parameters
    ----------
    path : str, Path or ShyfemMesh
        The ``.grd`` file, or a mesh already read by ``pypath.io.shyfem.read_grd``.
    patches : {"element", "type"} or np.ndarray
        "element": one patch per element. "type": one patch per element
        type, which is the box number in a SHYFEM box model. An array gives
        a zone id per element, in the file's element order.
    units, crs, geometry
        As in ``grid_from_mesh``. A ``.grd`` file names no coordinate
        system, so check ``units`` when the automatic choice could be wrong.
    """
    from pypath.io.shyfem import ShyfemMesh, read_grd

    mesh = path if isinstance(path, ShyfemMesh) else read_grd(path)
    if isinstance(patches, str):
        if patches == "element":
            zones = None
        elif patches == "type":
            zones = mesh.element_type
        else:
            raise ValueError(
                f'patches must be "element", "type" or an array, not {patches!r}'
            )
    else:
        zones = np.asarray(patches)
        if zones.shape != (mesh.n_elements,):
            raise ValueError(
                f"patches needs one value per element ({mesh.n_elements}), "
                f"got shape {zones.shape}"
            )
    safe = np.where(mesh.elements >= 0, mesh.elements, mesh.elements[:, :1])
    node_mean = np.where(mesh.elements >= 0, mesh.node_depth[safe], np.nan)
    with warnings.catch_warnings():
        warnings.simplefilter("ignore", RuntimeWarning)  # all-NaN rows stay NaN
        from_nodes = np.nanmean(node_mean, axis=1)
    depth = np.where(np.isfinite(mesh.element_depth), mesh.element_depth, from_nodes)
    grid = _grid_with_types(mesh, zones, units, depth, crs, geometry)
    return grid

mesh_units

mesh_units(xy: ndarray) -> str

"degrees" if the coordinates can be longitude and latitude, else "m".

Source code in pypath/spatial/mesh.py
58
59
60
61
62
63
def mesh_units(xy: np.ndarray) -> str:
    """ "degrees" if the coordinates can be longitude and latitude, else "m"."""
    xy = np.asarray(xy, dtype=float)
    if np.all(np.abs(xy[:, 0]) <= 360.0) and np.all(np.abs(xy[:, 1]) <= 90.0):
        return "degrees"
    return "m"

Fields Given per Zone

Box-model output as monthly layers on a grid, and a habitat capacity made from layers and response functions.

pypath.spatial.zone_fields

Fields given per zone, on the patches of an Ecospace grid.

A hydrodynamic box model, a monitoring programme or a table of basin means gives a value per zone and time. zone_series_layer turns such a series into an EnvironmentalLayer of monthly means on a grid: each patch takes the value of its zone, so the same series serves a grid of boxes and a grid of the mesh elements inside them. shyfem_box_layers does it for every variable of a SHYFEM box model's output. capacity_from_layers makes a habitat capacity from layers and response functions.

Time in a layer is in years from a start date, as in a spatial run; a month's mean is held for the whole month (month k covers k/12 up to (k+1)/12).

capacity_from_layers

capacity_from_layers(drivers: Union[EnvironmentalDrivers, Mapping[str, EnvironmentalLayer]], responses: Mapping[Union[int, str], Mapping[str, Callable]], *, n_groups: Optional[int] = None, group_names: Optional[Sequence[str]] = None, when: Union[str, float] = 'mean', combine: str = 'multiplicative') -> np.ndarray

Habitat capacity of each group in each patch from environmental layers.

A group's capacity is the product (or the minimum) of its responses to the layers it is given one for; a group without responses has capacity 1 everywhere. The result is what EcospaceParams.habitat_capacity takes: it does not change during a run. Ecospace uses the pattern of a group's capacity over the map, not its level. For a capacity that changes from month to month, see pypath.spatial.monthly_capacity.MonthlyCapacity, whose base map this function also makes.

Parameters:

Name Type Description Default
drivers EnvironmentalDrivers or mapping of name to EnvironmentalLayer

The layers.

required
responses mapping

{group: {layer name: response function}}. A group is its row (0 is the first group) or, with group_names, its name. A response function takes the layer's values and returns suitability between 0 and 1 (create_linear_response and the like).

required
n_groups int

Number of rows of the result. Default: len(group_names).

None
group_names sequence of str

The groups' names, in row order.

None
when 'mean' or float

"mean": the mean over the layers' months of the suitability (not the suitability at the mean conditions). A number: the time, in years, at which the layers are read.

'mean'
combine ('multiplicative', 'minimum')

How a group's responses to several layers are combined.

"multiplicative"

Returns:

Type Description
ndarray

Capacity [n_groups, n_patches], between 0 and 1.

Source code in pypath/spatial/zone_fields.py
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
def capacity_from_layers(
    drivers: Union[EnvironmentalDrivers, Mapping[str, EnvironmentalLayer]],
    responses: Mapping[Union[int, str], Mapping[str, Callable]],
    *,
    n_groups: Optional[int] = None,
    group_names: Optional[Sequence[str]] = None,
    when: Union[str, float] = "mean",
    combine: str = "multiplicative",
) -> np.ndarray:
    """Habitat capacity of each group in each patch from environmental layers.

    A group's capacity is the product (or the minimum) of its responses to
    the layers it is given one for; a group without responses has capacity 1
    everywhere. The result is what ``EcospaceParams.habitat_capacity`` takes:
    it does not change during a run. Ecospace uses the pattern of a group's
    capacity over the map, not its level. For a capacity that changes from
    month to month, see ``pypath.spatial.monthly_capacity.MonthlyCapacity``,
    whose base map this function also makes.

    Parameters
    ----------
    drivers : EnvironmentalDrivers or mapping of name to EnvironmentalLayer
        The layers.
    responses : mapping
        ``{group: {layer name: response function}}``. A group is its row
        (0 is the first group) or, with ``group_names``, its name. A
        response function takes the layer's values and returns suitability
        between 0 and 1 (``create_linear_response`` and the like).
    n_groups : int, optional
        Number of rows of the result. Default: ``len(group_names)``.
    group_names : sequence of str, optional
        The groups' names, in row order.
    when : "mean" or float
        "mean": the mean over the layers' months of the suitability (not
        the suitability at the mean conditions). A number: the time, in
        years, at which the layers are read.
    combine : {"multiplicative", "minimum"}
        How a group's responses to several layers are combined.

    Returns
    -------
    np.ndarray
        Capacity [n_groups, n_patches], between 0 and 1.
    """
    layers = (
        drivers.layers if isinstance(drivers, EnvironmentalDrivers) else dict(drivers)
    )
    if combine not in ("multiplicative", "minimum"):
        raise ValueError(
            f'combine must be "multiplicative" or "minimum", not {combine!r}'
        )
    if n_groups is None:
        if group_names is None:
            raise ValueError("give n_groups or group_names")
        n_groups = len(group_names)
    if not layers:
        raise ValueError("no layers given")
    n_patches = next(iter(layers.values())).n_patches
    capacity = np.ones((n_groups, n_patches))
    for group, by_layer in responses.items():
        if isinstance(group, str):
            if group_names is None or group not in list(group_names):
                raise KeyError(f"no group named {group!r} in group_names")
            row = list(group_names).index(group)
        else:
            row = int(group)
            if not 0 <= row < n_groups:
                raise KeyError(f"group row {row} is outside 0..{n_groups - 1}")
        if not by_layer:
            continue
        for layer_name in by_layer:
            if layer_name not in layers:
                raise KeyError(
                    f"no layer {layer_name!r}; the layers are {sorted(layers)}"
                )
        if when == "mean":
            moments = sorted(
                {
                    float(t)
                    for name in by_layer
                    if layers[name].is_time_varying
                    for t in layers[name].times
                }
            ) or [0.0]
        else:
            moments = [float(when)]
        total = np.zeros(n_patches)
        for t in moments:
            parts = [
                np.clip(
                    np.asarray(fn(layers[name].get_value_at_time(t)), dtype=float),
                    0.0,
                    1.0,
                )
                for name, fn in by_layer.items()
            ]
            total += (
                np.prod(parts, axis=0)
                if combine == "multiplicative"
                else np.min(parts, axis=0)
            )
        capacity[row] = total / len(moments)
    return capacity

patch_zones

patch_zones(grid: 'EcospaceGrid') -> np.ndarray

The zone each patch of a grid lies in.

A grid made from a SHYFEM mesh knows it (cell_metadata["type"]: the element type, which is the box number in a box model). Other grids are taken to have one patch per zone, numbered by patch_ids.

Source code in pypath/spatial/zone_fields.py
40
41
42
43
44
45
46
47
48
49
50
def patch_zones(grid: "EcospaceGrid") -> np.ndarray:
    """The zone each patch of a grid lies in.

    A grid made from a SHYFEM mesh knows it (``cell_metadata["type"]``: the
    element type, which is the box number in a box model). Other grids are
    taken to have one patch per zone, numbered by ``patch_ids``.
    """
    meta = getattr(grid, "cell_metadata", None)
    if meta is not None and "type" in meta:
        return np.asarray(meta["type"])
    return np.asarray(grid.patch_ids)

shyfem_box_layers

shyfem_box_layers(series: 'ShyfemBoxSeries', grid: 'EcospaceGrid', *, start=None, variables: Optional[Sequence[str]] = None, zones_of_patches: Optional[ndarray] = None) -> EnvironmentalDrivers

A SHYFEM box model's output as monthly layers on a grid.

Parameters:

Name Type Description Default
series ShyfemBoxSeries

From pypath.io.shyfem.read_box_series.

required
grid EcospaceGrid

A grid of the boxes (from_shyfem_grd(..., patches="type")), of the mesh's elements, or any grid with zones_of_patches.

required
start str or datetime64

The date of time 0 of the run. Default: the series' first month.

None
variables sequence of str

The variables to take. Default: all in the series.

None
zones_of_patches ndarray

The box of each patch. Default: patch_zones(grid).

None

Returns:

Type Description
EnvironmentalDrivers

One layer per variable, named as in the series (temp, salt, cur_speed, ...).

Source code in pypath/spatial/zone_fields.py
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
def shyfem_box_layers(
    series: "ShyfemBoxSeries",
    grid: "EcospaceGrid",
    *,
    start=None,
    variables: Optional[Sequence[str]] = None,
    zones_of_patches: Optional[np.ndarray] = None,
) -> EnvironmentalDrivers:
    """A SHYFEM box model's output as monthly layers on a grid.

    Parameters
    ----------
    series : ShyfemBoxSeries
        From ``pypath.io.shyfem.read_box_series``.
    grid : EcospaceGrid
        A grid of the boxes (``from_shyfem_grd(..., patches="type")``), of
        the mesh's elements, or any grid with ``zones_of_patches``.
    start : str or datetime64, optional
        The date of time 0 of the run. Default: the series' first month.
    variables : sequence of str, optional
        The variables to take. Default: all in the series.
    zones_of_patches : np.ndarray, optional
        The box of each patch. Default: ``patch_zones(grid)``.

    Returns
    -------
    EnvironmentalDrivers
        One layer per variable, named as in the series (``temp``, ``salt``,
        ``cur_speed``, ...).
    """
    names = list(series.variables) if variables is None else list(variables)
    layers = {}
    for name in names:
        layers[name] = zone_series_layer(
            series.times,
            series.variable(name),
            series.boxes,
            grid,
            name=name,
            units=_SHYFEM_UNITS.get(name, ""),
            start=start,
            zones_of_patches=zones_of_patches,
            # monthly means made while reading are stamped with their month
            stamped_at_end=not getattr(series, "monthly", False),
        )
    return EnvironmentalDrivers(layers)

zone_series_layer

zone_series_layer(times, values, zone_ids, grid: 'EcospaceGrid', *, name: str, units: str = '', start=None, zones_of_patches: Optional[ndarray] = None, stamped_at_end: bool = True) -> EnvironmentalLayer

Monthly means of a per-zone time series as a layer on a grid.

Parameters:

Name Type Description Default
times array of datetime64

Time stamp of each record [n_times].

required
values ndarray

The series [n_times, n_zones].

required
zone_ids ndarray

The zone of each column of values [n_zones], in any order.

required
grid EcospaceGrid

The grid whose patches get the values.

required
name str

Name and units of the layer.

required
units str

Name and units of the layer.

required
start str or datetime64

The date of time 0 of the run the layer is for. Months before it are dropped. Default: the first month in the series.

None
zones_of_patches ndarray

The zone of each patch [n_patches]. Default: patch_zones(grid).

None
stamped_at_end bool

Records are stamped at the end of their interval (as SHYFEM's are): each counts in the month of its stamp, except one stamped at the first instant of a month, which closes the month before. With False a record always counts in the month of its stamp.

True

Returns:

Type Description
EnvironmentalLayer

values [n_months, n_patches] with times at the start of each month, in years from start, and hold set: month k's mean holds from k/12 up to (k+1)/12. Before the first month the first mean is given, after the last month the last.

Raises:

Type Description
ValueError

When a patch's zone is not in zone_ids, or the series has no data on or after start.

Source code in pypath/spatial/zone_fields.py
 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
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
def zone_series_layer(
    times,
    values,
    zone_ids,
    grid: "EcospaceGrid",
    *,
    name: str,
    units: str = "",
    start=None,
    zones_of_patches: Optional[np.ndarray] = None,
    stamped_at_end: bool = True,
) -> EnvironmentalLayer:
    """Monthly means of a per-zone time series as a layer on a grid.

    Parameters
    ----------
    times : array of datetime64
        Time stamp of each record [n_times].
    values : np.ndarray
        The series [n_times, n_zones].
    zone_ids : np.ndarray
        The zone of each column of ``values`` [n_zones], in any order.
    grid : EcospaceGrid
        The grid whose patches get the values.
    name, units : str
        Name and units of the layer.
    start : str or datetime64, optional
        The date of time 0 of the run the layer is for. Months before it
        are dropped. Default: the first month in the series.
    zones_of_patches : np.ndarray, optional
        The zone of each patch [n_patches]. Default: ``patch_zones(grid)``.
    stamped_at_end : bool
        Records are stamped at the end of their interval (as SHYFEM's are):
        each counts in the month of its stamp, except one stamped at the
        first instant of a month, which closes the month before. With False
        a record always counts in the month of its stamp.

    Returns
    -------
    EnvironmentalLayer
        ``values`` [n_months, n_patches] with ``times`` at the start of
        each month, in years from ``start``, and ``hold`` set: month k's
        mean holds from k/12 up to (k+1)/12. Before the first month the
        first mean is given, after the last month the last.

    Raises
    ------
    ValueError
        When a patch's zone is not in ``zone_ids``, or the series has no
        data on or after ``start``.
    """
    times = np.asarray(times).astype("datetime64[s]")
    values = np.asarray(values, dtype=float)
    zone_ids = np.asarray(zone_ids)
    if values.shape != (len(times), len(zone_ids)):
        raise ValueError(
            f"values must be [n_times, n_zones] = ({len(times)}, {len(zone_ids)}), "
            f"got {values.shape}"
        )
    zones = (
        patch_zones(grid) if zones_of_patches is None else np.asarray(zones_of_patches)
    )
    if zones.shape != (grid.n_patches,):
        raise ValueError(
            f"zones_of_patches needs one value per patch ({grid.n_patches})"
        )
    order = np.argsort(zone_ids, kind="stable")
    sorted_ids = zone_ids[order]
    where = np.searchsorted(sorted_ids, zones)
    where = np.clip(where, 0, len(sorted_ids) - 1)
    missing = np.unique(zones[sorted_ids[where] != zones])
    if len(missing):
        listed = ", ".join(str(z) for z in missing[:10])
        more = "" if len(missing) <= 10 else f" and {len(missing) - 10} more"
        raise ValueError(
            f"the series has no values for zone{'s' if len(missing) > 1 else ''} "
            f"{listed}{more}, which the grid's patches lie in"
        )
    column = order[where]  # the series column of each patch

    # A record stamped at the end of its interval counts in the month that
    # interval ends in; one stamped at the first instant of a month closes
    # the month before (the rule of read_box_series(monthly=True)).
    stamps = times - np.timedelta64(1, "s") if stamped_at_end else times
    month = _month_index(stamps)
    first = (
        int(month.min())
        if start is None
        else int(_month_index(np.array([np.datetime64(start, "s")]))[0])
    )
    keep = month >= first
    if not keep.any():
        raise ValueError(f"the series has no data on or after {start}")
    months = np.unique(month[keep])
    means = np.empty((len(months), len(zone_ids)))
    for k, m in enumerate(months):
        means[k] = values[month == m].mean(axis=0)
    return EnvironmentalLayer(
        name=name,
        units=units,
        values=means[:, column],
        times=(months - first) / 12.0,
        hold=True,
    )

Capacity by Month

A habitat capacity for every month of a run for chosen groups, as the month's feeding efficiency per patch; the base map keeps the calibration.

pypath.spatial.monthly_capacity

Habitat capacity that changes from month to month during a spatial run.

EcospaceParams.habitat_capacity is one map for the whole run: it says where a group lives. MonthlyCapacity gives chosen groups a capacity for every month, made for instance from a hydrodynamic model's monthly salinity and temperature (from_layers).

What the month's capacity does, and what the base map keeps. As in EwE's Ecospace, the run is calibrated once, on the base map (habitat_capacity): a group's base biomass, search rates and vulnerabilities do not change afterwards. Each month the group's capacity in a patch, divided by the peak of its base map, becomes that patch's feeding efficiency (a producer's production factor). So unlike the base map, of which only the pattern matters, the month's level matters: a month in which a group's capacity is half the base peak everywhere halves what it can eat everywhere.

Mind the scale. The model's Ecopath balance stands for the conditions at the peak of the base map. A response that is far below 1 for months, such as a temperature optimum reached only in summer, starves the group for the rest of the year: in one lagoon model a zooplankton group with such a response fell to 7 % of its biomass each winter. Shape a response so that it is near 1 under the conditions the model describes, and lower only where the group really does worse.

The base map still sets the start distribution, the stanza ratios, the rest state of WaterTransport with rest="capacity" and, unless asked, movement between patches. With movement=True the groups' diffusion reads the month's map, as movement does in EwE (which sets its movement rates again whenever the capacity has changed): a group then leaves a patch that has turned poor, at min(1, capacity there / capacity here) of its dispersal rate towards each neighbour. Without it, diffusion keeps pulling the group back to the base pattern, which at a high dispersal rate undoes much of what the month's capacity does locally. Habitat-directed advection reads habitat_preference and is not changed.

The rest state of water transport does not follow the month's map, with or without movement. Water exchange moves a group towards its rest pattern at the water's rate divided by the zone's weight, so a zone whose capacity fell in one month would lose far more than its water carries (with 5 % of the water exchanged in a month, 39 % of the biomass at a capacity of 0.05). For a carried group whose capacity changes by month, rest="volume" lets the water mix it without a habitat pattern.

Groups a run does not treat as one pool per patch are refused: multi-stanza groups and IBM groups. So is a monthly capacity on a uniform base map together with an MPA capacity bonus, which acts differently on a uniform map than in the calibrated form a monthly capacity brings in; with a base map that varies between patches the two combine exactly.

MonthlyCapacity dataclass

A capacity per month, patch and group, for the groups named.

Attributes:

Name Type Description
groups sequence of int

The groups given a monthly capacity, as rows of EcospaceParams arrays (0 is the first group).

values ndarray

Capacity [n_months, n_groups_given, n_patches], not negative, on the scale of the base map (habitat_capacity).

first_month int

The run's month (0 is its first) that the first month of values belongs to.

beyond {'refuse', 'repeat_year', 'mean_year', 'hold'}

The months of a run that values does not cover, before or after: refuse the run; repeat the nearest twelve months, in step with the calendar; use the mean year, each calendar month's mean over all the years given; or hold the nearest month.

movement bool

Whether these groups' diffusion between patches reads the month's map (as EwE's movement does) and not the base map. Off by default.

Source code in pypath/spatial/monthly_capacity.py
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
@dataclass
class MonthlyCapacity:
    """A capacity per month, patch and group, for the groups named.

    Attributes
    ----------
    groups : sequence of int
        The groups given a monthly capacity, as rows of ``EcospaceParams``
        arrays (0 is the first group).
    values : np.ndarray
        Capacity [n_months, n_groups_given, n_patches], not negative, on
        the scale of the base map (``habitat_capacity``).
    first_month : int
        The run's month (0 is its first) that the first month of ``values``
        belongs to.
    beyond : {"refuse", "repeat_year", "mean_year", "hold"}
        The months of a run that ``values`` does not cover, before or
        after: refuse the run; repeat the nearest twelve months, in step
        with the calendar; use the mean year, each calendar month's mean
        over all the years given; or hold the nearest month.
    movement : bool
        Whether these groups' diffusion between patches reads the month's
        map (as EwE's movement does) and not the base map. Off by default.
    """

    groups: Sequence[int]
    values: np.ndarray
    first_month: int = 0
    beyond: str = "refuse"
    movement: bool = False

    def __post_init__(self):
        self.groups = [int(g) for g in self.groups]
        if len(set(self.groups)) != len(self.groups):
            raise ValueError("a group is named twice")
        self.values = np.asarray(self.values, dtype=float)
        if self.values.ndim != 3 or self.values.shape[1] != len(self.groups):
            raise ValueError(
                f"values must be [n_months, {len(self.groups)}, n_patches], "
                f"got {self.values.shape}"
            )
        if self.values.shape[0] < 1:
            raise ValueError("values holds no month")
        if not np.all(np.isfinite(self.values)) or np.any(self.values < 0):
            raise ValueError("capacities must be finite and not negative")
        if self.beyond not in _BEYOND:
            raise ValueError(f"beyond must be one of {_BEYOND}, not {self.beyond!r}")
        m = self.values.shape[0]
        if self.beyond in ("repeat_year", "mean_year") and m < 12:
            raise ValueError(f"{self.beyond} needs at least twelve months")
        self.first_month = int(self.first_month)
        self._n_given = m
        if self.beyond == "mean_year":
            mean = np.stack([self.values[c:m:12].mean(axis=0) for c in range(12)])
            self.values = np.concatenate([self.values, mean])

    # -- construction ------------------------------------------------------

    @classmethod
    def from_layers(
        cls,
        drivers: Union["EnvironmentalDrivers", Mapping[str, "EnvironmentalLayer"]],
        responses: Mapping[Union[int, str], Mapping[str, Callable]],
        *,
        group_names: Optional[Sequence[str]] = None,
        combine: str = "multiplicative",
        beyond: str = "refuse",
        movement: bool = False,
    ) -> "MonthlyCapacity":
        """Each month's capacity from monthly layers and response functions.

        The capacity of a group in a patch and month is the product (or the
        minimum) of its responses to the layers it is given one for, read
        at that month. Use it with a base map on the same scale, for
        instance ``capacity_from_layers`` with the same layers and
        responses, whose base is the mean over the months.

        Parameters
        ----------
        drivers : EnvironmentalDrivers or mapping of name to EnvironmentalLayer
            Layers whose times are month starts in years from the run's
            start (as ``shyfem_box_layers`` and ``zone_series_layer`` make
            them).
        responses : mapping
            ``{group: {layer name: response function}}``; a group is its row
            (0 is the first group) or, with ``group_names``, its name. Only
            these groups get a monthly capacity.
        group_names : sequence of str, optional
            The groups' names, in row order.
        combine : {"multiplicative", "minimum"}
            How a group's responses to several layers are combined.
        beyond : str
            As on the class.
        movement : bool
            As on the class.

        Raises
        ------
        ValueError
            When no group is given a response to a layer that varies in
            time, or the layers' months have gaps.
        """
        from pypath.spatial.environmental import EnvironmentalDrivers

        layers = (
            drivers.layers
            if isinstance(drivers, EnvironmentalDrivers)
            else dict(drivers)
        )
        if combine not in ("multiplicative", "minimum"):
            raise ValueError(
                f'combine must be "multiplicative" or "minimum", not {combine!r}'
            )
        rows, by_row = [], []
        for group, by_layer in responses.items():
            if not by_layer:
                continue
            if isinstance(group, str):
                if group_names is None or group not in list(group_names):
                    raise KeyError(f"no group named {group!r} in group_names")
                row = list(group_names).index(group)
            else:
                row = int(group)
            for name in by_layer:
                if name not in layers:
                    raise KeyError(
                        f"no layer {name!r}; the layers are {sorted(layers)}"
                    )
            rows.append(row)
            by_row.append(by_layer)
        months = sorted(
            {
                int(round(float(t) * 12.0))
                for by_layer in by_row
                for name in by_layer
                if layers[name].is_time_varying
                for t in layers[name].times
            }
        )
        if not months:
            raise ValueError(
                "no group is given a response to a layer that changes in time; "
                "a capacity that does not change belongs in habitat_capacity"
            )
        if months != list(range(months[0], months[-1] + 1)):
            raise ValueError("the layers' months have gaps")
        n_patches = next(iter(layers.values())).n_patches
        values = np.empty((len(months), len(rows), n_patches))
        for k, month in enumerate(months):
            for g, by_layer in enumerate(by_row):
                parts = [
                    np.clip(
                        np.asarray(
                            fn(layers[name].get_value_at_time(month / 12.0)),
                            dtype=float,
                        ),
                        0.0,
                        1.0,
                    )
                    for name, fn in by_layer.items()
                ]
                values[k, g] = (
                    np.prod(parts, axis=0)
                    if combine == "multiplicative"
                    else np.min(parts, axis=0)
                )
        return cls(
            groups=rows,
            values=values,
            first_month=months[0],
            beyond=beyond,
            movement=movement,
        )

    # -- time --------------------------------------------------------------

    @property
    def n_months(self) -> int:
        """Months given (the mean year's rows are not counted)."""
        return self._n_given

    def month_index(self, month: int) -> int:
        """The row of ``values`` used for a run's month (0 is the first)."""
        m = self.n_months
        rel = int(month) - self.first_month
        if 0 <= rel < m:
            return rel
        if self.beyond == "hold":
            return m - 1 if rel >= m else 0
        if self.beyond == "mean_year":
            return m + rel % 12
        if self.beyond == "repeat_year":
            return rel % 12 if rel < 0 else m - 12 + (rel - (m - 12)) % 12
        raise ValueError(
            f"month {month} of the run is outside the monthly capacity (its "
            f"months {self.first_month}..{self.first_month + m - 1}); set "
            'beyond="mean_year", "repeat_year" or "hold" to run there'
        )

    # -- in a spatial run --------------------------------------------------

    def prepare(
        self,
        ecospace: "EcospaceParams",
        n_run_months: int,
        *,
        n_groups: Optional[int] = None,
        stanza_rows=(),
        ibm_rows=(),
        names: Optional[Sequence[str]] = None,
    ) -> list:
        """Check against a run; return the state rows given a monthly capacity."""
        n_patches = ecospace.grid.n_patches
        if self.values.shape[2] != n_patches:
            raise ValueError(
                f"the monthly capacity has {self.values.shape[2]} patches, "
                f"the grid {n_patches}"
            )
        if self.beyond == "refuse" and (
            self.first_month > 0 or n_run_months > self.first_month + self.n_months
        ):
            raise ValueError(
                f"the run has months 0..{n_run_months - 1}, the monthly capacity "
                f"covers {self.first_month}..{self.first_month + self.n_months - 1}; "
                'set beyond="mean_year", "repeat_year" or "hold" to run the others'
            )
        n_rows = len(ecospace.dispersal_rate)
        n_groups = n_rows if n_groups is None else min(int(n_groups), n_rows)

        def label(row):
            return (
                f"{names[row]!r}"
                if names is not None and row < len(names)
                else str(row)
            )

        rows = []
        for g in self.groups:
            if not 0 <= g < n_groups:
                raise ValueError(
                    f"monthly capacity group row {g} is outside 0..{n_groups - 1}"
                )
            row = g + 1
            for kind, members in (
                ("a multi-stanza group", stanza_rows),
                ("an IBM group", ibm_rows),
            ):
                if row in {int(r) for r in members}:
                    raise ValueError(
                        f"group {label(row)} cannot take a monthly capacity: it "
                        f"is {kind}"
                    )
            rows.append(row)
        return rows

    def efficiency(self, month: int, base_peak: np.ndarray) -> np.ndarray:
        """Feeding efficiency of the groups given, in a run's month.

        ``base_peak`` is the peak of each of those groups' base maps
        [n_groups_given]; the month's capacity over it, not below EwE's
        minimum capacity.
        """
        peak = np.asarray(base_peak, dtype=float)
        peak = np.where(peak > 0, peak, 1.0)
        return np.maximum(
            self.values[self.month_index(month)] / peak[:, np.newaxis], _MIN_CAPACITY
        )

    def movement_rows(self, month: int, base_peak: np.ndarray) -> dict:
        """The capacity that movement reads in a run's month, by group row.

        Empty unless ``movement`` is set. Otherwise each group given maps to
        its month's capacity per patch, floored as ``efficiency`` floors it
        (EwE's movement reads the same floored map), so a patch at no
        capacity is left slowly and not at an infinite rate.
        """
        if not self.movement:
            return {}
        return dict(zip(self.groups, self.efficiency(month, base_peak)))
n_months property
n_months: int

Months given (the mean year's rows are not counted).

efficiency
efficiency(month: int, base_peak: ndarray) -> np.ndarray

Feeding efficiency of the groups given, in a run's month.

base_peak is the peak of each of those groups' base maps [n_groups_given]; the month's capacity over it, not below EwE's minimum capacity.

Source code in pypath/spatial/monthly_capacity.py
328
329
330
331
332
333
334
335
336
337
338
339
def efficiency(self, month: int, base_peak: np.ndarray) -> np.ndarray:
    """Feeding efficiency of the groups given, in a run's month.

    ``base_peak`` is the peak of each of those groups' base maps
    [n_groups_given]; the month's capacity over it, not below EwE's
    minimum capacity.
    """
    peak = np.asarray(base_peak, dtype=float)
    peak = np.where(peak > 0, peak, 1.0)
    return np.maximum(
        self.values[self.month_index(month)] / peak[:, np.newaxis], _MIN_CAPACITY
    )
from_layers classmethod
from_layers(drivers: Union['EnvironmentalDrivers', Mapping[str, 'EnvironmentalLayer']], responses: Mapping[Union[int, str], Mapping[str, Callable]], *, group_names: Optional[Sequence[str]] = None, combine: str = 'multiplicative', beyond: str = 'refuse', movement: bool = False) -> 'MonthlyCapacity'

Each month's capacity from monthly layers and response functions.

The capacity of a group in a patch and month is the product (or the minimum) of its responses to the layers it is given one for, read at that month. Use it with a base map on the same scale, for instance capacity_from_layers with the same layers and responses, whose base is the mean over the months.

Parameters:

Name Type Description Default
drivers EnvironmentalDrivers or mapping of name to EnvironmentalLayer

Layers whose times are month starts in years from the run's start (as shyfem_box_layers and zone_series_layer make them).

required
responses mapping

{group: {layer name: response function}}; a group is its row (0 is the first group) or, with group_names, its name. Only these groups get a monthly capacity.

required
group_names sequence of str

The groups' names, in row order.

None
combine ('multiplicative', 'minimum')

How a group's responses to several layers are combined.

"multiplicative"
beyond str

As on the class.

'refuse'
movement bool

As on the class.

False

Raises:

Type Description
ValueError

When no group is given a response to a layer that varies in time, or the layers' months have gaps.

Source code in pypath/spatial/monthly_capacity.py
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
@classmethod
def from_layers(
    cls,
    drivers: Union["EnvironmentalDrivers", Mapping[str, "EnvironmentalLayer"]],
    responses: Mapping[Union[int, str], Mapping[str, Callable]],
    *,
    group_names: Optional[Sequence[str]] = None,
    combine: str = "multiplicative",
    beyond: str = "refuse",
    movement: bool = False,
) -> "MonthlyCapacity":
    """Each month's capacity from monthly layers and response functions.

    The capacity of a group in a patch and month is the product (or the
    minimum) of its responses to the layers it is given one for, read
    at that month. Use it with a base map on the same scale, for
    instance ``capacity_from_layers`` with the same layers and
    responses, whose base is the mean over the months.

    Parameters
    ----------
    drivers : EnvironmentalDrivers or mapping of name to EnvironmentalLayer
        Layers whose times are month starts in years from the run's
        start (as ``shyfem_box_layers`` and ``zone_series_layer`` make
        them).
    responses : mapping
        ``{group: {layer name: response function}}``; a group is its row
        (0 is the first group) or, with ``group_names``, its name. Only
        these groups get a monthly capacity.
    group_names : sequence of str, optional
        The groups' names, in row order.
    combine : {"multiplicative", "minimum"}
        How a group's responses to several layers are combined.
    beyond : str
        As on the class.
    movement : bool
        As on the class.

    Raises
    ------
    ValueError
        When no group is given a response to a layer that varies in
        time, or the layers' months have gaps.
    """
    from pypath.spatial.environmental import EnvironmentalDrivers

    layers = (
        drivers.layers
        if isinstance(drivers, EnvironmentalDrivers)
        else dict(drivers)
    )
    if combine not in ("multiplicative", "minimum"):
        raise ValueError(
            f'combine must be "multiplicative" or "minimum", not {combine!r}'
        )
    rows, by_row = [], []
    for group, by_layer in responses.items():
        if not by_layer:
            continue
        if isinstance(group, str):
            if group_names is None or group not in list(group_names):
                raise KeyError(f"no group named {group!r} in group_names")
            row = list(group_names).index(group)
        else:
            row = int(group)
        for name in by_layer:
            if name not in layers:
                raise KeyError(
                    f"no layer {name!r}; the layers are {sorted(layers)}"
                )
        rows.append(row)
        by_row.append(by_layer)
    months = sorted(
        {
            int(round(float(t) * 12.0))
            for by_layer in by_row
            for name in by_layer
            if layers[name].is_time_varying
            for t in layers[name].times
        }
    )
    if not months:
        raise ValueError(
            "no group is given a response to a layer that changes in time; "
            "a capacity that does not change belongs in habitat_capacity"
        )
    if months != list(range(months[0], months[-1] + 1)):
        raise ValueError("the layers' months have gaps")
    n_patches = next(iter(layers.values())).n_patches
    values = np.empty((len(months), len(rows), n_patches))
    for k, month in enumerate(months):
        for g, by_layer in enumerate(by_row):
            parts = [
                np.clip(
                    np.asarray(
                        fn(layers[name].get_value_at_time(month / 12.0)),
                        dtype=float,
                    ),
                    0.0,
                    1.0,
                )
                for name, fn in by_layer.items()
            ]
            values[k, g] = (
                np.prod(parts, axis=0)
                if combine == "multiplicative"
                else np.min(parts, axis=0)
            )
    return cls(
        groups=rows,
        values=values,
        first_month=months[0],
        beyond=beyond,
        movement=movement,
    )
month_index
month_index(month: int) -> int

The row of values used for a run's month (0 is the first).

Source code in pypath/spatial/monthly_capacity.py
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
def month_index(self, month: int) -> int:
    """The row of ``values`` used for a run's month (0 is the first)."""
    m = self.n_months
    rel = int(month) - self.first_month
    if 0 <= rel < m:
        return rel
    if self.beyond == "hold":
        return m - 1 if rel >= m else 0
    if self.beyond == "mean_year":
        return m + rel % 12
    if self.beyond == "repeat_year":
        return rel % 12 if rel < 0 else m - 12 + (rel - (m - 12)) % 12
    raise ValueError(
        f"month {month} of the run is outside the monthly capacity (its "
        f"months {self.first_month}..{self.first_month + m - 1}); set "
        'beyond="mean_year", "repeat_year" or "hold" to run there'
    )
movement_rows
movement_rows(month: int, base_peak: ndarray) -> dict

The capacity that movement reads in a run's month, by group row.

Empty unless movement is set. Otherwise each group given maps to its month's capacity per patch, floored as efficiency floors it (EwE's movement reads the same floored map), so a patch at no capacity is left slowly and not at an infinite rate.

Source code in pypath/spatial/monthly_capacity.py
341
342
343
344
345
346
347
348
349
350
351
def movement_rows(self, month: int, base_peak: np.ndarray) -> dict:
    """The capacity that movement reads in a run's month, by group row.

    Empty unless ``movement`` is set. Otherwise each group given maps to
    its month's capacity per patch, floored as ``efficiency`` floors it
    (EwE's movement reads the same floored map), so a patch at no
    capacity is left slowly and not at an infinite rate.
    """
    if not self.movement:
        return {}
    return dict(zip(self.groups, self.efficiency(month, base_peak)))
prepare
prepare(ecospace: 'EcospaceParams', n_run_months: int, *, n_groups: Optional[int] = None, stanza_rows=(), ibm_rows=(), names: Optional[Sequence[str]] = None) -> list

Check against a run; return the state rows given a monthly capacity.

Source code in pypath/spatial/monthly_capacity.py
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
def prepare(
    self,
    ecospace: "EcospaceParams",
    n_run_months: int,
    *,
    n_groups: Optional[int] = None,
    stanza_rows=(),
    ibm_rows=(),
    names: Optional[Sequence[str]] = None,
) -> list:
    """Check against a run; return the state rows given a monthly capacity."""
    n_patches = ecospace.grid.n_patches
    if self.values.shape[2] != n_patches:
        raise ValueError(
            f"the monthly capacity has {self.values.shape[2]} patches, "
            f"the grid {n_patches}"
        )
    if self.beyond == "refuse" and (
        self.first_month > 0 or n_run_months > self.first_month + self.n_months
    ):
        raise ValueError(
            f"the run has months 0..{n_run_months - 1}, the monthly capacity "
            f"covers {self.first_month}..{self.first_month + self.n_months - 1}; "
            'set beyond="mean_year", "repeat_year" or "hold" to run the others'
        )
    n_rows = len(ecospace.dispersal_rate)
    n_groups = n_rows if n_groups is None else min(int(n_groups), n_rows)

    def label(row):
        return (
            f"{names[row]!r}"
            if names is not None and row < len(names)
            else str(row)
        )

    rows = []
    for g in self.groups:
        if not 0 <= g < n_groups:
            raise ValueError(
                f"monthly capacity group row {g} is outside 0..{n_groups - 1}"
            )
        row = g + 1
        for kind, members in (
            ("a multi-stanza group", stanza_rows),
            ("an IBM group", ibm_rows),
        ):
            if row in {int(r) for r in members}:
                raise ValueError(
                    f"group {label(row)} cannot take a monthly capacity: it "
                    f"is {kind}"
                )
        rows.append(row)
    return rows

Water Transport

Monthly water flows between zones carrying chosen groups.

pypath.spatial.transport

Water movement between zones carrying biomass.

A hydrodynamic box model gives the water flow through each section between its boxes. WaterTransport holds the monthly means of those flows and moves the biomass of chosen groups with them during a spatial run::

dB_i/dt = sum_j ( Q_ji B_j s_j  -  Q_ij B_i s_i )

Q_ij is the flow from zone i to zone j and s_i the share of zone i's biomass a unit of its water carries. The sum is taken implicitly over each month, which is stable for any flow: boxes are flushed in days, a run steps in months.

Two ways to use the flows.

  • Exchange only (the default, throughflow=False). Each pair of zones exchanges the water that goes both ways between them, min(Q_ij, Q_ji). The net flow, the rivers' water on its way to the sea, is left out. The map is closed: the carried biomass is mixed between the zones, its total is kept exactly, and the rest state below holds exactly.
  • With throughflow (throughflow=True). All the water moves. A boundary that brings in more water than it takes out over the series (a river) is a diluting one: its net inflow brings none of the group, so the group is flushed towards the sea: a loss the Ecopath balance does not hold, large for slow pools such as detritus. Water going both ways through a boundary (the open sea), and water a zone stores or releases as its volume changes, carries what the zone has. open_boundaries names the diluting boundaries when that rule is not the right one.

Both directions of a section matter: with the net flow alone a tracer does not follow an estuary's exchange at all (salinity carried with a lagoon model's flows: 2.3 psu off in the strait with net flows, 1.3 with both directions).

Rest state. With rest="volume" a unit of water carries 1 / volume of the zone's biomass, so biomass at rest is in proportion to the zones' volumes: one concentration everywhere. With rest="capacity" it is in proportion to area x habitat capacity, as Ecospace's diffusion leaves it, so a uniform map stays as it is; a zone's biomass then leaves at (its depth / the map's mean depth) of the water's rate. The default is "capacity" for exchange only, where a month mixes the zones almost fully either way and a uniform map then stays Ecosim, and "volume" with throughflow, where the water's own rate sets the flushing.

Flows are known between zones only. On a grid with several patches in a zone (the elements of a mesh) the zone's total moves and each patch keeps its share of it. A zone the grid has no patch in is outside the map and takes no part.

WaterTransport dataclass

Monthly water flows between zones, and the groups they carry.

Attributes:

Name Type Description
zones ndarray

Zone ids [n_zones] (the box numbers of a box model).

flow ndarray

Flow from zone i to zone j, m3/s [n_months, n_zones, n_zones].

volume ndarray

Volume of each zone, m3 [n_months, n_zones].

groups sequence of int

The groups carried, as rows of EcospaceParams arrays (0 is the first group).

boundary_id, boundary_zone ndarray

Id of each section to the outside and the position in zones of the zone it touches [n_boundaries].

boundary_in, boundary_out ndarray

Flow into and out of the zone through it, m3/s [n_months, n_boundaries].

rest ({'volume', 'capacity'}, optional)

What biomass at rest is in proportion to (see the module text). Default: "capacity" for exchange only, "volume" with throughflow.

throughflow bool

False (default): the two-way exchange between zones only, which keeps the total. True: all the water moves and rivers dilute.

open_boundaries sequence of int, optional

With throughflow, the boundary ids whose net inflow brings none of the group. Default: the boundaries that bring in more water than they take out over the series.

beyond {'refuse', 'repeat_year', 'mean_year', 'hold'}

The months of a run the flows do not cover, before their first month or after their last: refuse the run; repeat the nearest twelve months of the flows (the first year before them, the last after); use the mean year, each calendar month's mean over all the years of the flows; or hold the nearest month.

first_month int

The run's month (0 is its first) that the first month of the flows belongs to. Above 0 the flows begin after the run does.

Source code in pypath/spatial/transport.py
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
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
386
387
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
443
444
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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
@dataclass
class WaterTransport:
    """Monthly water flows between zones, and the groups they carry.

    Attributes
    ----------
    zones : np.ndarray
        Zone ids [n_zones] (the box numbers of a box model).
    flow : np.ndarray
        Flow from zone i to zone j, m3/s [n_months, n_zones, n_zones].
    volume : np.ndarray
        Volume of each zone, m3 [n_months, n_zones].
    groups : sequence of int
        The groups carried, as rows of ``EcospaceParams`` arrays (0 is the
        first group).
    boundary_id, boundary_zone : np.ndarray
        Id of each section to the outside and the position in ``zones`` of
        the zone it touches [n_boundaries].
    boundary_in, boundary_out : np.ndarray
        Flow into and out of the zone through it, m3/s
        [n_months, n_boundaries].
    rest : {"volume", "capacity"}, optional
        What biomass at rest is in proportion to (see the module text).
        Default: "capacity" for exchange only, "volume" with throughflow.
    throughflow : bool
        False (default): the two-way exchange between zones only, which
        keeps the total. True: all the water moves and rivers dilute.
    open_boundaries : sequence of int, optional
        With throughflow, the boundary ids whose net inflow brings none of
        the group. Default: the boundaries that bring in more water than
        they take out over the series.
    beyond : {"refuse", "repeat_year", "mean_year", "hold"}
        The months of a run the flows do not cover, before their first
        month or after their last: refuse the run; repeat the nearest
        twelve months of the flows (the first year before them, the last
        after); use the mean year, each calendar month's mean over all the
        years of the flows; or hold the nearest month.
    first_month : int
        The run's month (0 is its first) that the first month of the flows
        belongs to. Above 0 the flows begin after the run does.
    """

    zones: np.ndarray
    flow: np.ndarray
    volume: np.ndarray
    groups: Sequence[int]
    boundary_id: np.ndarray = field(default_factory=lambda: np.empty(0, dtype=int))
    boundary_zone: np.ndarray = field(default_factory=lambda: np.empty(0, dtype=int))
    boundary_in: Optional[np.ndarray] = None
    boundary_out: Optional[np.ndarray] = None
    rest: Optional[str] = None
    throughflow: bool = False
    open_boundaries: Optional[Sequence[int]] = None
    beyond: str = "refuse"
    first_month: int = 0

    def __post_init__(self):
        if self.rest is None:
            self.rest = "volume" if self.throughflow else "capacity"
        self.zones = np.asarray(self.zones)
        self.flow = np.asarray(self.flow, dtype=float)
        self.volume = np.asarray(self.volume, dtype=float)
        n = len(self.zones)
        if self.flow.ndim != 3 or self.flow.shape[1:] != (n, n):
            raise ValueError(
                f"flow must be [n_months, {n}, {n}], got {self.flow.shape}"
            )
        m = self.flow.shape[0]
        if self.volume.shape != (m, n):
            raise ValueError(f"volume must be [{m}, {n}], got {self.volume.shape}")
        if np.any(self.flow < 0) or not np.all(np.isfinite(self.flow)):
            raise ValueError("flows must be finite and not negative")
        if np.any(self.volume <= 0) or not np.all(np.isfinite(self.volume)):
            raise ValueError("volumes must be finite and positive")
        if self.rest not in _RESTS:
            raise ValueError(f"rest must be one of {_RESTS}, not {self.rest!r}")
        if self.beyond not in _BEYOND:
            raise ValueError(f"beyond must be one of {_BEYOND}, not {self.beyond!r}")
        if self.beyond in ("repeat_year", "mean_year") and m < 12:
            raise ValueError(f"{self.beyond} needs at least twelve months of flows")
        self.first_month = int(self.first_month)
        self._n_given = m
        # each group once: a group named twice would be moved twice a month
        self.groups = list(dict.fromkeys(int(g) for g in self.groups))
        self.boundary_id = np.asarray(self.boundary_id, dtype=int)
        self.boundary_zone = np.asarray(self.boundary_zone, dtype=int)
        nb = len(self.boundary_id)
        for name in ("boundary_in", "boundary_out"):
            value = getattr(self, name)
            value = np.zeros((m, nb)) if value is None else np.asarray(value, float)
            if value.shape != (m, nb):
                raise ValueError(f"{name} must be [{m}, {nb}], got {value.shape}")
            setattr(self, name, value)
        if self.open_boundaries is None:
            # a boundary that brings more water in than it takes out over
            # the series: a river (also one with some backflow)
            # (a boundary id may have several sections: they count together)
            self.open_boundaries = sorted(
                int(b)
                for b in np.unique(self.boundary_id)
                if self.boundary_in[:, self.boundary_id == b].sum()
                > self.boundary_out[:, self.boundary_id == b].sum()
            )
        else:
            self.open_boundaries = [int(b) for b in self.open_boundaries]
        unknown = set(self.open_boundaries) - set(self.boundary_id.tolist())
        if unknown:
            raise ValueError(
                f"open_boundaries {sorted(unknown)} are not boundary ids "
                f"({sorted(set(self.boundary_id.tolist()))})"
            )
        if self.beyond == "mean_year":
            # twelve more rows: each calendar month's mean over the years
            for name in ("flow", "volume", "boundary_in", "boundary_out"):
                table = getattr(self, name)
                mean = np.stack([table[c:m:12].mean(axis=0) for c in range(12)])
                setattr(self, name, np.concatenate([table, mean]))
        self._solvers: dict = {}
        self._patch_zone: Optional[np.ndarray] = None

    # -- construction ------------------------------------------------------

    @classmethod
    def from_link_flows(
        cls,
        times,
        flows,
        upstream,
        downstream,
        volume,
        groups: Sequence[int],
        *,
        zones=None,
        sections=None,
        start=None,
        stamped_at_end: bool = False,
        rest: Optional[str] = None,
        throughflow: bool = False,
        open_boundaries: Optional[Sequence[int]] = None,
        beyond: str = "refuse",
    ) -> "WaterTransport":
        """Monthly flows from a time series of directed links between zones.

        A link carries water one way, from its upstream zone to its
        downstream zone; an exchange is two links. A zone id below 1 is the
        outside (a river, the open sea), with that id as the boundary's.
        Links with the same two ends add up. Each calendar month's mean is
        taken, so the series should be daily or finer: both directions of a
        section matter, and flows averaged over a week or more lose them.

        Parameters
        ----------
        times : array of datetime64
            Time stamp of each record [n_times].
        flows : np.ndarray
            Flow through each link, m3/s, not negative [n_times, n_links].
        upstream, downstream : array of int
            The zone each link leaves and the zone it enters [n_links].
        volume : np.ndarray
            The zones' volumes, m3, in the order of ``zones``: constant
            [n_zones], or a series on ``times`` [n_times, n_zones].
        groups : sequence of int
            The groups carried, as rows of ``EcospaceParams`` arrays.
        zones : array of int, optional
            The zone ids. Default: the ids of the links' ends, ascending.
        sections : array of int, optional
            The section each link crosses [n_links]. The links of one
            section to the outside are its two directions, and what goes
            both ways through it is the same water; a diluting boundary
            dilutes by each section's own net inflow. Default: the links
            between one boundary id and one zone count as one section.
        start : str or datetime64, optional
            The date of time 0 of the run. Months of flows before it are
            dropped; if the flows begin after it, ``first_month`` says by
            how many months. Default: the first month of the flows.
        stamped_at_end : bool
            True when a record is stamped at the end of its interval (as
            SHYFEM's are): one stamped at the first instant of a month then
            closes the month before. Default: a record counts in the month
            of its stamp.
        rest, throughflow, open_boundaries, beyond
            As on the class.

        Raises
        ------
        ValueError
            For flows that are negative or not finite in any record, a
            link between unknown zones or from the outside to the outside,
            months missing inside the series, and no data on or after
            ``start``.
        """
        times = np.asarray(times).astype("datetime64[s]")
        flows = np.asarray(flows, dtype=float)
        upstream = np.asarray(upstream, dtype=int)
        downstream = np.asarray(downstream, dtype=int)
        if flows.ndim != 2 or flows.shape != (len(times), len(upstream)):
            raise ValueError(
                f"flows must be [n_times, n_links] = ({len(times)}, "
                f"{len(upstream)}), got {flows.shape}"
            )
        if len(downstream) != len(upstream):
            raise ValueError("upstream and downstream need one zone per link")
        # every record, not the monthly means: -2 and 4 would average to 1
        if not np.all(np.isfinite(flows)):
            raise ValueError("flows must be finite in every record")
        if np.any(flows < 0):
            raise ValueError(
                "flows must not be negative in any record: a link runs one way"
            )
        if sections is not None:
            sections = np.asarray(sections)
            if sections.shape != upstream.shape:
                raise ValueError("sections needs one value per link")
        if np.any((upstream < 1) & (downstream < 1)):
            raise ValueError("a link cannot run from the outside to the outside")
        if zones is None:
            ends = np.concatenate([upstream, downstream])
            zones = np.unique(ends[ends > 0])
        zones = np.asarray(zones)
        n = len(zones)
        position = {int(z): i for i, z in enumerate(zones)}
        unknown = sorted(
            {int(z) for z in np.concatenate([upstream, downstream]) if z > 0}
            - set(position)
        )
        if unknown:
            raise ValueError(f"links name zones {unknown}, which are not in zones")
        volume = np.asarray(volume, dtype=float)
        if volume.shape not in ((n,), (len(times), n)):
            raise ValueError(
                f"volume must be [{n}] or [{len(times)}, {n}], got {volume.shape}"
            )

        stamps = times - np.timedelta64(1, "s") if stamped_at_end else times
        month = stamps.astype("datetime64[M]").astype(int)
        first = (
            int(month.min())
            if start is None
            else int(np.datetime64(start, "s").astype("datetime64[M]").astype(int))
        )
        every = np.unique(month)  # all the months supplied
        months = every[every >= first]
        if len(months) == 0:
            raise ValueError(f"the flows have no data on or after {start}")
        if np.any(np.diff(months) != 1):
            raise ValueError(
                "the flows must cover every month from their first to their "
                "last; some are missing"
            )

        inside = np.flatnonzero((upstream > 0) & (downstream > 0))
        i_from = np.array([position[int(z)] for z in upstream[inside]], dtype=int)
        i_to = np.array([position[int(z)] for z in downstream[inside]], dtype=int)
        # a boundary entry per (id, zone, section), in order of appearance
        column: dict = {}
        b_links, b_col, b_comes_in = [], [], []
        for k in np.flatnonzero((upstream < 1) | (downstream < 1)):
            comes_in = bool(upstream[k] < 1)
            key = (
                int(upstream[k] if comes_in else downstream[k]),
                position[int(downstream[k] if comes_in else upstream[k])],
                None if sections is None else sections[k].item(),
            )
            b_links.append(int(k))
            b_col.append(column.setdefault(key, len(column)))
            b_comes_in.append(comes_in)
        b_links = np.array(b_links, dtype=int)
        b_col = np.array(b_col, dtype=int)
        b_comes_in = np.array(b_comes_in, dtype=bool)

        def tables(which):
            """Monthly flow, volume and boundary tables of the months given."""
            flow = np.zeros((len(which), n, n))
            vol = np.empty((len(which), n))
            b_in = np.zeros((len(which), len(column)))
            b_out = np.zeros_like(b_in)
            for row, m in enumerate(which):
                rows = month == m
                mean = flows[rows].mean(axis=0)
                vol[row] = volume if volume.ndim == 1 else volume[rows].mean(axis=0)
                np.add.at(flow[row], (i_from, i_to), mean[inside])
                np.add.at(b_in[row], b_col[b_comes_in], mean[b_links[b_comes_in]])
                np.add.at(b_out[row], b_col[~b_comes_in], mean[b_links[~b_comes_in]])
            return flow, vol, b_in, b_out

        flow, vol, b_in, b_out = tables(months)
        keys = list(column)
        made = cls(
            zones=zones,
            flow=flow,
            volume=vol,
            groups=groups,
            boundary_id=np.array([key[0] for key in keys], dtype=int),
            boundary_zone=np.array([key[1] for key in keys], dtype=int),
            boundary_in=b_in,
            boundary_out=b_out,
            rest=rest,
            throughflow=throughflow,
            open_boundaries=open_boundaries,
            beyond=beyond,
            first_month=int(months[0] - first),
        )
        if beyond == "mean_year" and len(every) > len(months):
            # the mean year is that of all the years supplied, also those
            # before the start date, by calendar month
            full = tables(every)
            calendar = (every - months[0]) % 12
            for name, table in zip(
                ("flow", "volume", "boundary_in", "boundary_out"), full
            ):
                getattr(made, name)[len(months) :] = np.stack(
                    [table[calendar == c].mean(axis=0) for c in range(12)]
                )
        return made

    @classmethod
    def from_shyfem_box_series(
        cls,
        series: "ShyfemBoxSeries",
        groups: Sequence[int],
        *,
        start=None,
        rest: Optional[str] = None,
        throughflow: bool = False,
        open_boundaries: Optional[Sequence[int]] = None,
        beyond: str = "refuse",
    ) -> "WaterTransport":
        """Monthly flows and volumes from a SHYFEM box model's output.

        Each section becomes two links, its positive part one way and its
        negative part the other (``from_link_flows``).

        Parameters
        ----------
        series : ShyfemBoxSeries
            From ``pypath.io.shyfem.read_box_series`` (with or without
            ``monthly=True``). It must hold the section flows and the
            ``volume`` variable.
        groups : sequence of int
            The groups carried, as rows of ``EcospaceParams`` arrays.
        start : str or datetime64, optional
            The date of time 0 of the run. Months before it are dropped.
            Default: the first month in the series.
        rest, throughflow, open_boundaries, beyond
            As on the class. A section whose box number is negative is a
            boundary, with that number as its id.
        """
        if len(series.section_from) == 0:
            raise ValueError("the box series holds no section flows")
        frm, to = np.asarray(series.section_from), np.asarray(series.section_to)
        return cls.from_link_flows(
            series.times,
            np.concatenate(
                [series.section_flow[:, :, 1], series.section_flow[:, :, 2]], axis=1
            ),
            np.concatenate([frm, to]),
            np.concatenate([to, frm]),
            series.variable("volume"),
            groups,
            zones=np.asarray(series.boxes),
            # a section's positive and negative parts are its two directions
            sections=np.tile(np.arange(len(frm)), 2),
            start=start,
            stamped_at_end=not series.monthly,
            rest=rest,
            throughflow=throughflow,
            open_boundaries=open_boundaries,
            beyond=beyond,
        )

    # -- time --------------------------------------------------------------

    @property
    def n_months(self) -> int:
        """Months of flows given (the mean year's rows are not counted)."""
        return self._n_given

    def month_index(self, month: int) -> int:
        """The row of the flows used for a run's month (0 is the first)."""
        m = self.n_months
        rel = int(month) - self.first_month  # months from the flows' first
        if 0 <= rel < m:
            return rel
        if self.beyond == "hold":
            return m - 1 if rel >= m else 0
        if self.beyond == "mean_year":
            return m + rel % 12
        if self.beyond == "repeat_year":
            # the nearest twelve months, in step with the calendar
            return rel % 12 if rel < 0 else m - 12 + (rel - (m - 12)) % 12
        raise ValueError(
            f"month {month} of the run is outside the water flows (its months "
            f"{self.first_month}..{self.first_month + m - 1}); set "
            'beyond="mean_year", "repeat_year" or "hold" to run there'
        )

    # -- the operator ------------------------------------------------------

    def rate_matrix(self, index: int, weights: np.ndarray) -> np.ndarray:
        """``A`` [n_zones, n_zones] per year with ``dB/dt = A B`` for zone totals.

        ``weights`` is what biomass at rest is in proportion to in each zone
        (the volumes for ``rest="volume"``). A zone of weight 0 holds none
        of the group: nothing is carried into or out of it.
        """
        w = np.asarray(weights, dtype=float)
        v = self.volume[index]
        live = w > 0
        if not live.any():
            return np.zeros((len(w), len(w)))
        # share of a zone's biomass in a unit of its water; the mean weight
        # per volume keeps the flushing times those of the water
        per_volume = w[live].sum() / v[live].sum()
        share = np.where(live, per_volume / np.where(live, w, 1.0), 0.0)
        # water to or from a zone that holds none of the group carries none
        q = self.flow[index] * live[np.newaxis, :] * live[:, np.newaxis]
        if not self.throughflow:
            q = np.minimum(q, q.T)  # the water that goes both ways
        rate = q * share[:, np.newaxis] * _SECONDS_PER_YEAR  # [from, to]
        a = rate.T.copy()
        a[np.diag_indices_from(a)] -= rate.sum(axis=1)
        if not self.throughflow:
            return a
        # A zone whose inflow from the other zones differs from its outflow
        # to them exchanges the difference with the outside or with its own
        # storage (its volume changes over the month). That water carries
        # what the zone has, in and out ...
        surplus = q.sum(axis=0) - q.sum(axis=1)  # in from zones - out to zones
        a[np.diag_indices_from(a)] -= surplus * share * _SECONDS_PER_YEAR
        # ... except a diluting boundary's inflow, which brings nothing.
        is_open = np.isin(self.boundary_id, list(self.open_boundaries))
        for b, zone in enumerate(self.boundary_zone):
            if is_open[b]:
                # its net inflow is new water; what goes both ways through
                # it carries what the zone has
                new_water = max(
                    self.boundary_in[index, b] - self.boundary_out[index, b], 0.0
                )
                a[zone, zone] -= new_water * share[zone] * _SECONDS_PER_YEAR
        return a

    def step_zones(
        self, totals: np.ndarray, index: int, weights: np.ndarray, dt: float, key=None
    ) -> np.ndarray:
        """Zone totals after ``dt`` years of the flows of month row ``index``.

        One implicit (backward Euler) step. ``key`` names the weights so the
        factorised system can be kept (a group's row; its weights must then
        not change between calls with the same ``index``).
        """
        from scipy.linalg import lu_factor, lu_solve

        totals = np.asarray(totals, dtype=float)
        if not np.all(np.isfinite(totals)):
            # a run that has already failed: leave it as it is
            return totals.copy()
        cache_key = None if key is None else (index, key, float(dt))
        solver = self._solvers.get(cache_key) if cache_key is not None else None
        if solver is None:
            system = np.eye(len(self.zones)) - dt * self.rate_matrix(index, weights)
            solver = lu_factor(system)
            if cache_key is not None:
                self._solvers[cache_key] = solver
        return np.maximum(lu_solve(solver, np.asarray(totals, dtype=float)), 0.0)

    # -- in a spatial run --------------------------------------------------

    def prepare(
        self,
        ecospace: "EcospaceParams",
        n_run_months: int,
        *,
        fast_rows=(),
        stanza_rows=(),
        ibm_rows=(),
        names: Optional[Sequence[str]] = None,
        n_groups: Optional[int] = None,
    ) -> list:
        """Check the transport against a run; return the state rows carried.

        Raises ValueError for a patch whose zone has no flows, a run longer
        than the flows (unless ``beyond`` allows it), a carried group that
        is not one of the run's ``n_groups`` groups, and one that a run
        does not integrate as a pool of its own: a fast-equilibrium group,
        a multi-stanza group or an IBM group.
        """
        from pypath.spatial.zone_fields import patch_zones

        zones_of_patches = patch_zones(ecospace.grid)
        order = np.argsort(self.zones, kind="stable")
        where = np.clip(
            np.searchsorted(self.zones[order], zones_of_patches), 0, len(order) - 1
        )
        missing = np.unique(
            zones_of_patches[self.zones[order][where] != zones_of_patches]
        )
        if len(missing):
            raise ValueError(
                "the water flows have no zone "
                f"{', '.join(str(z) for z in missing[:10])}, which the grid's "
                "patches lie in"
            )
        self._patch_zone = order[where]
        self._covered = np.bincount(self._patch_zone, minlength=len(self.zones)) > 0
        self._solvers = {}
        if self.beyond == "refuse" and (
            self.first_month > 0 or n_run_months > self.first_month + self.n_months
        ):
            raise ValueError(
                f"the run has months 0..{n_run_months - 1}, the water flows cover "
                f"{self.first_month}..{self.first_month + self.n_months - 1}; set "
                'beyond="mean_year", "repeat_year" or "hold" to run the others'
            )
        # the run's groups; EcospaceParams may carry rows beyond them
        n_rows = len(ecospace.dispersal_rate)
        n_groups = n_rows if n_groups is None else min(int(n_groups), n_rows)

        def label(row):
            return (
                f"{names[row]!r}"
                if names is not None and row < len(names)
                else str(row)
            )

        rows = []
        for g in self.groups:
            if not 0 <= g < n_groups:
                raise ValueError(
                    f"transported group row {g} is outside 0..{n_groups - 1}"
                )
            row = g + 1
            for kind, members, advice in (
                (
                    "a fast-equilibrium group",
                    fast_rows,
                    "its biomass is set to its local equilibrium at every step; "
                    "pass the scenario through pypath.core.ecosim.integrate_groups "
                    "to integrate it",
                ),
                (
                    "a multi-stanza group",
                    stanza_rows,
                    "its biomass is spread over the patches by the stanza model",
                ),
                ("an IBM group", ibm_rows, "its individuals move themselves"),
            ):
                if row in set(int(r) for r in members):
                    raise ValueError(
                        f"water transport cannot carry group {label(row)}: it is "
                        f"{kind} ({advice})"
                    )
            rows.append(row)
        return rows

    def _weights(self, ecospace: "EcospaceParams", group: int, index: int):
        """Zone weights of a group for month row ``index``, and patch weights."""
        areas = np.asarray(ecospace.grid.patch_areas, dtype=float)
        n = len(self.zones)
        if self.rest == "volume":
            # a zone the grid has no patch in is outside the map: weight 0
            return self.volume[index] * self._covered, areas, ("volume", index)
        capacity = np.asarray(ecospace.habitat_capacity, dtype=float)[group]
        patch_w = areas * capacity
        return (
            np.bincount(self._patch_zone, weights=patch_w, minlength=n),
            patch_w,
            group,
        )

    def move(
        self, biomass: np.ndarray, group: int, month: int, dt: float, ecospace
    ) -> np.ndarray:
        """A group's biomass per patch after a month of the water's flow.

        ``group`` is the group's row in ``EcospaceParams`` arrays, ``month``
        the run's month (0 is the first). The zones' totals move; inside a
        zone each patch keeps its share (a zone that was empty is filled in
        proportion to its patches' weights).
        """
        if self._patch_zone is None:
            raise RuntimeError("call prepare() before move()")
        index = self.month_index(month)
        zone_w, patch_w, key = self._weights(ecospace, group, index)
        biomass = np.asarray(biomass, dtype=float)
        n = len(self.zones)
        before = np.bincount(self._patch_zone, weights=biomass, minlength=n)
        after = self.step_zones(before, index, zone_w, dt, key=key)
        ratio = np.divide(after, before, out=np.zeros(n), where=before > 0)
        moved = biomass * ratio[self._patch_zone]
        empty = (before <= 0) & (after > 0)
        if empty.any():
            in_zone = np.bincount(self._patch_zone, weights=patch_w, minlength=n)
            share = np.divide(
                patch_w,
                in_zone[self._patch_zone],
                out=np.zeros_like(patch_w),
                where=in_zone[self._patch_zone] > 0,
            )
            fill = empty[self._patch_zone]
            moved[fill] = (after[self._patch_zone] * share)[fill]
        return moved
n_months property
n_months: int

Months of flows given (the mean year's rows are not counted).

from_link_flows(times, flows, upstream, downstream, volume, groups: Sequence[int], *, zones=None, sections=None, start=None, stamped_at_end: bool = False, rest: Optional[str] = None, throughflow: bool = False, open_boundaries: Optional[Sequence[int]] = None, beyond: str = 'refuse') -> 'WaterTransport'

Monthly flows from a time series of directed links between zones.

A link carries water one way, from its upstream zone to its downstream zone; an exchange is two links. A zone id below 1 is the outside (a river, the open sea), with that id as the boundary's. Links with the same two ends add up. Each calendar month's mean is taken, so the series should be daily or finer: both directions of a section matter, and flows averaged over a week or more lose them.

Parameters:

Name Type Description Default
times array of datetime64

Time stamp of each record [n_times].

required
flows ndarray

Flow through each link, m3/s, not negative [n_times, n_links].

required
upstream array of int

The zone each link leaves and the zone it enters [n_links].

required
downstream array of int

The zone each link leaves and the zone it enters [n_links].

required
volume ndarray

The zones' volumes, m3, in the order of zones: constant [n_zones], or a series on times [n_times, n_zones].

required
groups sequence of int

The groups carried, as rows of EcospaceParams arrays.

required
zones array of int

The zone ids. Default: the ids of the links' ends, ascending.

None
sections array of int

The section each link crosses [n_links]. The links of one section to the outside are its two directions, and what goes both ways through it is the same water; a diluting boundary dilutes by each section's own net inflow. Default: the links between one boundary id and one zone count as one section.

None
start str or datetime64

The date of time 0 of the run. Months of flows before it are dropped; if the flows begin after it, first_month says by how many months. Default: the first month of the flows.

None
stamped_at_end bool

True when a record is stamped at the end of its interval (as SHYFEM's are): one stamped at the first instant of a month then closes the month before. Default: a record counts in the month of its stamp.

False
rest Optional[str]

As on the class.

None
throughflow Optional[str]

As on the class.

None
open_boundaries Optional[str]

As on the class.

None
beyond Optional[str]

As on the class.

None

Raises:

Type Description
ValueError

For flows that are negative or not finite in any record, a link between unknown zones or from the outside to the outside, months missing inside the series, and no data on or after start.

Source code in pypath/spatial/transport.py
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
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
@classmethod
def from_link_flows(
    cls,
    times,
    flows,
    upstream,
    downstream,
    volume,
    groups: Sequence[int],
    *,
    zones=None,
    sections=None,
    start=None,
    stamped_at_end: bool = False,
    rest: Optional[str] = None,
    throughflow: bool = False,
    open_boundaries: Optional[Sequence[int]] = None,
    beyond: str = "refuse",
) -> "WaterTransport":
    """Monthly flows from a time series of directed links between zones.

    A link carries water one way, from its upstream zone to its
    downstream zone; an exchange is two links. A zone id below 1 is the
    outside (a river, the open sea), with that id as the boundary's.
    Links with the same two ends add up. Each calendar month's mean is
    taken, so the series should be daily or finer: both directions of a
    section matter, and flows averaged over a week or more lose them.

    Parameters
    ----------
    times : array of datetime64
        Time stamp of each record [n_times].
    flows : np.ndarray
        Flow through each link, m3/s, not negative [n_times, n_links].
    upstream, downstream : array of int
        The zone each link leaves and the zone it enters [n_links].
    volume : np.ndarray
        The zones' volumes, m3, in the order of ``zones``: constant
        [n_zones], or a series on ``times`` [n_times, n_zones].
    groups : sequence of int
        The groups carried, as rows of ``EcospaceParams`` arrays.
    zones : array of int, optional
        The zone ids. Default: the ids of the links' ends, ascending.
    sections : array of int, optional
        The section each link crosses [n_links]. The links of one
        section to the outside are its two directions, and what goes
        both ways through it is the same water; a diluting boundary
        dilutes by each section's own net inflow. Default: the links
        between one boundary id and one zone count as one section.
    start : str or datetime64, optional
        The date of time 0 of the run. Months of flows before it are
        dropped; if the flows begin after it, ``first_month`` says by
        how many months. Default: the first month of the flows.
    stamped_at_end : bool
        True when a record is stamped at the end of its interval (as
        SHYFEM's are): one stamped at the first instant of a month then
        closes the month before. Default: a record counts in the month
        of its stamp.
    rest, throughflow, open_boundaries, beyond
        As on the class.

    Raises
    ------
    ValueError
        For flows that are negative or not finite in any record, a
        link between unknown zones or from the outside to the outside,
        months missing inside the series, and no data on or after
        ``start``.
    """
    times = np.asarray(times).astype("datetime64[s]")
    flows = np.asarray(flows, dtype=float)
    upstream = np.asarray(upstream, dtype=int)
    downstream = np.asarray(downstream, dtype=int)
    if flows.ndim != 2 or flows.shape != (len(times), len(upstream)):
        raise ValueError(
            f"flows must be [n_times, n_links] = ({len(times)}, "
            f"{len(upstream)}), got {flows.shape}"
        )
    if len(downstream) != len(upstream):
        raise ValueError("upstream and downstream need one zone per link")
    # every record, not the monthly means: -2 and 4 would average to 1
    if not np.all(np.isfinite(flows)):
        raise ValueError("flows must be finite in every record")
    if np.any(flows < 0):
        raise ValueError(
            "flows must not be negative in any record: a link runs one way"
        )
    if sections is not None:
        sections = np.asarray(sections)
        if sections.shape != upstream.shape:
            raise ValueError("sections needs one value per link")
    if np.any((upstream < 1) & (downstream < 1)):
        raise ValueError("a link cannot run from the outside to the outside")
    if zones is None:
        ends = np.concatenate([upstream, downstream])
        zones = np.unique(ends[ends > 0])
    zones = np.asarray(zones)
    n = len(zones)
    position = {int(z): i for i, z in enumerate(zones)}
    unknown = sorted(
        {int(z) for z in np.concatenate([upstream, downstream]) if z > 0}
        - set(position)
    )
    if unknown:
        raise ValueError(f"links name zones {unknown}, which are not in zones")
    volume = np.asarray(volume, dtype=float)
    if volume.shape not in ((n,), (len(times), n)):
        raise ValueError(
            f"volume must be [{n}] or [{len(times)}, {n}], got {volume.shape}"
        )

    stamps = times - np.timedelta64(1, "s") if stamped_at_end else times
    month = stamps.astype("datetime64[M]").astype(int)
    first = (
        int(month.min())
        if start is None
        else int(np.datetime64(start, "s").astype("datetime64[M]").astype(int))
    )
    every = np.unique(month)  # all the months supplied
    months = every[every >= first]
    if len(months) == 0:
        raise ValueError(f"the flows have no data on or after {start}")
    if np.any(np.diff(months) != 1):
        raise ValueError(
            "the flows must cover every month from their first to their "
            "last; some are missing"
        )

    inside = np.flatnonzero((upstream > 0) & (downstream > 0))
    i_from = np.array([position[int(z)] for z in upstream[inside]], dtype=int)
    i_to = np.array([position[int(z)] for z in downstream[inside]], dtype=int)
    # a boundary entry per (id, zone, section), in order of appearance
    column: dict = {}
    b_links, b_col, b_comes_in = [], [], []
    for k in np.flatnonzero((upstream < 1) | (downstream < 1)):
        comes_in = bool(upstream[k] < 1)
        key = (
            int(upstream[k] if comes_in else downstream[k]),
            position[int(downstream[k] if comes_in else upstream[k])],
            None if sections is None else sections[k].item(),
        )
        b_links.append(int(k))
        b_col.append(column.setdefault(key, len(column)))
        b_comes_in.append(comes_in)
    b_links = np.array(b_links, dtype=int)
    b_col = np.array(b_col, dtype=int)
    b_comes_in = np.array(b_comes_in, dtype=bool)

    def tables(which):
        """Monthly flow, volume and boundary tables of the months given."""
        flow = np.zeros((len(which), n, n))
        vol = np.empty((len(which), n))
        b_in = np.zeros((len(which), len(column)))
        b_out = np.zeros_like(b_in)
        for row, m in enumerate(which):
            rows = month == m
            mean = flows[rows].mean(axis=0)
            vol[row] = volume if volume.ndim == 1 else volume[rows].mean(axis=0)
            np.add.at(flow[row], (i_from, i_to), mean[inside])
            np.add.at(b_in[row], b_col[b_comes_in], mean[b_links[b_comes_in]])
            np.add.at(b_out[row], b_col[~b_comes_in], mean[b_links[~b_comes_in]])
        return flow, vol, b_in, b_out

    flow, vol, b_in, b_out = tables(months)
    keys = list(column)
    made = cls(
        zones=zones,
        flow=flow,
        volume=vol,
        groups=groups,
        boundary_id=np.array([key[0] for key in keys], dtype=int),
        boundary_zone=np.array([key[1] for key in keys], dtype=int),
        boundary_in=b_in,
        boundary_out=b_out,
        rest=rest,
        throughflow=throughflow,
        open_boundaries=open_boundaries,
        beyond=beyond,
        first_month=int(months[0] - first),
    )
    if beyond == "mean_year" and len(every) > len(months):
        # the mean year is that of all the years supplied, also those
        # before the start date, by calendar month
        full = tables(every)
        calendar = (every - months[0]) % 12
        for name, table in zip(
            ("flow", "volume", "boundary_in", "boundary_out"), full
        ):
            getattr(made, name)[len(months) :] = np.stack(
                [table[calendar == c].mean(axis=0) for c in range(12)]
            )
    return made
from_shyfem_box_series classmethod
from_shyfem_box_series(series: 'ShyfemBoxSeries', groups: Sequence[int], *, start=None, rest: Optional[str] = None, throughflow: bool = False, open_boundaries: Optional[Sequence[int]] = None, beyond: str = 'refuse') -> 'WaterTransport'

Monthly flows and volumes from a SHYFEM box model's output.

Each section becomes two links, its positive part one way and its negative part the other (from_link_flows).

Parameters:

Name Type Description Default
series ShyfemBoxSeries

From pypath.io.shyfem.read_box_series (with or without monthly=True). It must hold the section flows and the volume variable.

required
groups sequence of int

The groups carried, as rows of EcospaceParams arrays.

required
start str or datetime64

The date of time 0 of the run. Months before it are dropped. Default: the first month in the series.

None
rest Optional[str]

As on the class. A section whose box number is negative is a boundary, with that number as its id.

None
throughflow Optional[str]

As on the class. A section whose box number is negative is a boundary, with that number as its id.

None
open_boundaries Optional[str]

As on the class. A section whose box number is negative is a boundary, with that number as its id.

None
beyond Optional[str]

As on the class. A section whose box number is negative is a boundary, with that number as its id.

None
Source code in pypath/spatial/transport.py
387
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
@classmethod
def from_shyfem_box_series(
    cls,
    series: "ShyfemBoxSeries",
    groups: Sequence[int],
    *,
    start=None,
    rest: Optional[str] = None,
    throughflow: bool = False,
    open_boundaries: Optional[Sequence[int]] = None,
    beyond: str = "refuse",
) -> "WaterTransport":
    """Monthly flows and volumes from a SHYFEM box model's output.

    Each section becomes two links, its positive part one way and its
    negative part the other (``from_link_flows``).

    Parameters
    ----------
    series : ShyfemBoxSeries
        From ``pypath.io.shyfem.read_box_series`` (with or without
        ``monthly=True``). It must hold the section flows and the
        ``volume`` variable.
    groups : sequence of int
        The groups carried, as rows of ``EcospaceParams`` arrays.
    start : str or datetime64, optional
        The date of time 0 of the run. Months before it are dropped.
        Default: the first month in the series.
    rest, throughflow, open_boundaries, beyond
        As on the class. A section whose box number is negative is a
        boundary, with that number as its id.
    """
    if len(series.section_from) == 0:
        raise ValueError("the box series holds no section flows")
    frm, to = np.asarray(series.section_from), np.asarray(series.section_to)
    return cls.from_link_flows(
        series.times,
        np.concatenate(
            [series.section_flow[:, :, 1], series.section_flow[:, :, 2]], axis=1
        ),
        np.concatenate([frm, to]),
        np.concatenate([to, frm]),
        series.variable("volume"),
        groups,
        zones=np.asarray(series.boxes),
        # a section's positive and negative parts are its two directions
        sections=np.tile(np.arange(len(frm)), 2),
        start=start,
        stamped_at_end=not series.monthly,
        rest=rest,
        throughflow=throughflow,
        open_boundaries=open_boundaries,
        beyond=beyond,
    )
month_index
month_index(month: int) -> int

The row of the flows used for a run's month (0 is the first).

Source code in pypath/spatial/transport.py
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
def month_index(self, month: int) -> int:
    """The row of the flows used for a run's month (0 is the first)."""
    m = self.n_months
    rel = int(month) - self.first_month  # months from the flows' first
    if 0 <= rel < m:
        return rel
    if self.beyond == "hold":
        return m - 1 if rel >= m else 0
    if self.beyond == "mean_year":
        return m + rel % 12
    if self.beyond == "repeat_year":
        # the nearest twelve months, in step with the calendar
        return rel % 12 if rel < 0 else m - 12 + (rel - (m - 12)) % 12
    raise ValueError(
        f"month {month} of the run is outside the water flows (its months "
        f"{self.first_month}..{self.first_month + m - 1}); set "
        'beyond="mean_year", "repeat_year" or "hold" to run there'
    )
move
move(biomass: ndarray, group: int, month: int, dt: float, ecospace) -> np.ndarray

A group's biomass per patch after a month of the water's flow.

group is the group's row in EcospaceParams arrays, month the run's month (0 is the first). The zones' totals move; inside a zone each patch keeps its share (a zone that was empty is filled in proportion to its patches' weights).

Source code in pypath/spatial/transport.py
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
def move(
    self, biomass: np.ndarray, group: int, month: int, dt: float, ecospace
) -> np.ndarray:
    """A group's biomass per patch after a month of the water's flow.

    ``group`` is the group's row in ``EcospaceParams`` arrays, ``month``
    the run's month (0 is the first). The zones' totals move; inside a
    zone each patch keeps its share (a zone that was empty is filled in
    proportion to its patches' weights).
    """
    if self._patch_zone is None:
        raise RuntimeError("call prepare() before move()")
    index = self.month_index(month)
    zone_w, patch_w, key = self._weights(ecospace, group, index)
    biomass = np.asarray(biomass, dtype=float)
    n = len(self.zones)
    before = np.bincount(self._patch_zone, weights=biomass, minlength=n)
    after = self.step_zones(before, index, zone_w, dt, key=key)
    ratio = np.divide(after, before, out=np.zeros(n), where=before > 0)
    moved = biomass * ratio[self._patch_zone]
    empty = (before <= 0) & (after > 0)
    if empty.any():
        in_zone = np.bincount(self._patch_zone, weights=patch_w, minlength=n)
        share = np.divide(
            patch_w,
            in_zone[self._patch_zone],
            out=np.zeros_like(patch_w),
            where=in_zone[self._patch_zone] > 0,
        )
        fill = empty[self._patch_zone]
        moved[fill] = (after[self._patch_zone] * share)[fill]
    return moved
prepare
prepare(ecospace: 'EcospaceParams', n_run_months: int, *, fast_rows=(), stanza_rows=(), ibm_rows=(), names: Optional[Sequence[str]] = None, n_groups: Optional[int] = None) -> list

Check the transport against a run; return the state rows carried.

Raises ValueError for a patch whose zone has no flows, a run longer than the flows (unless beyond allows it), a carried group that is not one of the run's n_groups groups, and one that a run does not integrate as a pool of its own: a fast-equilibrium group, a multi-stanza group or an IBM group.

Source code in pypath/spatial/transport.py
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
def prepare(
    self,
    ecospace: "EcospaceParams",
    n_run_months: int,
    *,
    fast_rows=(),
    stanza_rows=(),
    ibm_rows=(),
    names: Optional[Sequence[str]] = None,
    n_groups: Optional[int] = None,
) -> list:
    """Check the transport against a run; return the state rows carried.

    Raises ValueError for a patch whose zone has no flows, a run longer
    than the flows (unless ``beyond`` allows it), a carried group that
    is not one of the run's ``n_groups`` groups, and one that a run
    does not integrate as a pool of its own: a fast-equilibrium group,
    a multi-stanza group or an IBM group.
    """
    from pypath.spatial.zone_fields import patch_zones

    zones_of_patches = patch_zones(ecospace.grid)
    order = np.argsort(self.zones, kind="stable")
    where = np.clip(
        np.searchsorted(self.zones[order], zones_of_patches), 0, len(order) - 1
    )
    missing = np.unique(
        zones_of_patches[self.zones[order][where] != zones_of_patches]
    )
    if len(missing):
        raise ValueError(
            "the water flows have no zone "
            f"{', '.join(str(z) for z in missing[:10])}, which the grid's "
            "patches lie in"
        )
    self._patch_zone = order[where]
    self._covered = np.bincount(self._patch_zone, minlength=len(self.zones)) > 0
    self._solvers = {}
    if self.beyond == "refuse" and (
        self.first_month > 0 or n_run_months > self.first_month + self.n_months
    ):
        raise ValueError(
            f"the run has months 0..{n_run_months - 1}, the water flows cover "
            f"{self.first_month}..{self.first_month + self.n_months - 1}; set "
            'beyond="mean_year", "repeat_year" or "hold" to run the others'
        )
    # the run's groups; EcospaceParams may carry rows beyond them
    n_rows = len(ecospace.dispersal_rate)
    n_groups = n_rows if n_groups is None else min(int(n_groups), n_rows)

    def label(row):
        return (
            f"{names[row]!r}"
            if names is not None and row < len(names)
            else str(row)
        )

    rows = []
    for g in self.groups:
        if not 0 <= g < n_groups:
            raise ValueError(
                f"transported group row {g} is outside 0..{n_groups - 1}"
            )
        row = g + 1
        for kind, members, advice in (
            (
                "a fast-equilibrium group",
                fast_rows,
                "its biomass is set to its local equilibrium at every step; "
                "pass the scenario through pypath.core.ecosim.integrate_groups "
                "to integrate it",
            ),
            (
                "a multi-stanza group",
                stanza_rows,
                "its biomass is spread over the patches by the stanza model",
            ),
            ("an IBM group", ibm_rows, "its individuals move themselves"),
        ):
            if row in set(int(r) for r in members):
                raise ValueError(
                    f"water transport cannot carry group {label(row)}: it is "
                    f"{kind} ({advice})"
                )
        rows.append(row)
    return rows
rate_matrix
rate_matrix(index: int, weights: ndarray) -> np.ndarray

A [n_zones, n_zones] per year with dB/dt = A B for zone totals.

weights is what biomass at rest is in proportion to in each zone (the volumes for rest="volume"). A zone of weight 0 holds none of the group: nothing is carried into or out of it.

Source code in pypath/spatial/transport.py
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
def rate_matrix(self, index: int, weights: np.ndarray) -> np.ndarray:
    """``A`` [n_zones, n_zones] per year with ``dB/dt = A B`` for zone totals.

    ``weights`` is what biomass at rest is in proportion to in each zone
    (the volumes for ``rest="volume"``). A zone of weight 0 holds none
    of the group: nothing is carried into or out of it.
    """
    w = np.asarray(weights, dtype=float)
    v = self.volume[index]
    live = w > 0
    if not live.any():
        return np.zeros((len(w), len(w)))
    # share of a zone's biomass in a unit of its water; the mean weight
    # per volume keeps the flushing times those of the water
    per_volume = w[live].sum() / v[live].sum()
    share = np.where(live, per_volume / np.where(live, w, 1.0), 0.0)
    # water to or from a zone that holds none of the group carries none
    q = self.flow[index] * live[np.newaxis, :] * live[:, np.newaxis]
    if not self.throughflow:
        q = np.minimum(q, q.T)  # the water that goes both ways
    rate = q * share[:, np.newaxis] * _SECONDS_PER_YEAR  # [from, to]
    a = rate.T.copy()
    a[np.diag_indices_from(a)] -= rate.sum(axis=1)
    if not self.throughflow:
        return a
    # A zone whose inflow from the other zones differs from its outflow
    # to them exchanges the difference with the outside or with its own
    # storage (its volume changes over the month). That water carries
    # what the zone has, in and out ...
    surplus = q.sum(axis=0) - q.sum(axis=1)  # in from zones - out to zones
    a[np.diag_indices_from(a)] -= surplus * share * _SECONDS_PER_YEAR
    # ... except a diluting boundary's inflow, which brings nothing.
    is_open = np.isin(self.boundary_id, list(self.open_boundaries))
    for b, zone in enumerate(self.boundary_zone):
        if is_open[b]:
            # its net inflow is new water; what goes both ways through
            # it carries what the zone has
            new_water = max(
                self.boundary_in[index, b] - self.boundary_out[index, b], 0.0
            )
            a[zone, zone] -= new_water * share[zone] * _SECONDS_PER_YEAR
    return a
step_zones
step_zones(totals: ndarray, index: int, weights: ndarray, dt: float, key=None) -> np.ndarray

Zone totals after dt years of the flows of month row index.

One implicit (backward Euler) step. key names the weights so the factorised system can be kept (a group's row; its weights must then not change between calls with the same index).

Source code in pypath/spatial/transport.py
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
def step_zones(
    self, totals: np.ndarray, index: int, weights: np.ndarray, dt: float, key=None
) -> np.ndarray:
    """Zone totals after ``dt`` years of the flows of month row ``index``.

    One implicit (backward Euler) step. ``key`` names the weights so the
    factorised system can be kept (a group's row; its weights must then
    not change between calls with the same ``index``).
    """
    from scipy.linalg import lu_factor, lu_solve

    totals = np.asarray(totals, dtype=float)
    if not np.all(np.isfinite(totals)):
        # a run that has already failed: leave it as it is
        return totals.copy()
    cache_key = None if key is None else (index, key, float(dt))
    solver = self._solvers.get(cache_key) if cache_key is not None else None
    if solver is None:
        system = np.eye(len(self.zones)) - dt * self.rate_matrix(index, weights)
        solver = lu_factor(system)
        if cache_key is not None:
            self._solvers[cache_key] = solver
    return np.maximum(lu_solve(solver, np.asarray(totals, dtype=float)), 0.0)

Connectivity

Patch-to-patch connectivity matrices (adjacency, distance weighting) used by the dispersal and movement algorithms.

Key functions:

  • build_adjacency_from_gdf() — build adjacency matrix from GeoDataFrame
  • haversine_distance() — great circle distance in km
  • validate_adjacency_symmetry() — check matrix is symmetric
  • get_connectivity_graph_stats() — graph statistics (degree, isolated patches)
  • find_k_nearest_neighbors() — k-NN for each patch

pypath.spatial.connectivity

Connectivity and adjacency calculations for spatial grids.

Functions for building adjacency matrices from polygon geometries, calculating edge properties, and spatial indexing.

build_adjacency_from_gdf

build_adjacency_from_gdf(gdf: 'gpd.GeoDataFrame', method: str = 'rook') -> Tuple[scipy.sparse.csr_matrix, Dict]

Build adjacency matrix from GeoDataFrame.

Parameters:

Name Type Description Default
gdf GeoDataFrame

GeoDataFrame with polygon geometries

required
method str

Adjacency method: - "rook": Shared border (edge) required - "queen": Shared point or border

'rook'

Returns:

Name Type Description
adjacency csr_matrix

Sparse adjacency matrix [n_patches, n_patches] adjacency[i, j] = 1 if patches i and j are adjacent

metadata dict

Dictionary with: - 'border_lengths': Dict[(i, j)] = border length in km - 'method': adjacency method used

Raises:

Type Description
ImportError

If geopandas is not installed

Source code in pypath/spatial/connectivity.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
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
def build_adjacency_from_gdf(
    gdf: "gpd.GeoDataFrame", method: str = "rook"
) -> Tuple[scipy.sparse.csr_matrix, Dict]:
    """Build adjacency matrix from GeoDataFrame.

    Parameters
    ----------
    gdf : gpd.GeoDataFrame
        GeoDataFrame with polygon geometries
    method : str
        Adjacency method:
        - "rook": Shared border (edge) required
        - "queen": Shared point or border

    Returns
    -------
    adjacency : scipy.sparse.csr_matrix
        Sparse adjacency matrix [n_patches, n_patches]
        adjacency[i, j] = 1 if patches i and j are adjacent
    metadata : dict
        Dictionary with:
        - 'border_lengths': Dict[(i, j)] = border length in km
        - 'method': adjacency method used

    Raises
    ------
    ImportError
        If geopandas is not installed
    """
    if not _GIS_AVAILABLE:
        raise ImportError("geopandas is required for adjacency calculations")

    n_patches = len(gdf)

    # Use spatial index for efficient neighbor queries
    sindex = gdf.sindex

    rows, cols = [], []
    border_lengths = {}

    for i, geom_i in enumerate(gdf.geometry):
        # Query spatial index for potential neighbors
        possible_neighbors = list(sindex.intersection(geom_i.bounds))

        for j in possible_neighbors:
            if i >= j:  # Skip self and avoid duplicates
                continue

            geom_j = gdf.geometry.iloc[j]

            # Check intersection based on method
            if method == "rook":
                # Must share a line (not just a point)
                intersection = geom_i.intersection(geom_j)
                if intersection.length > 0:
                    rows.extend([i, j])
                    cols.extend([j, i])
                    # Store border length (convert to km if in degrees)
                    border_length_deg = intersection.length
                    # Rough conversion: 1 degree ≈ 111 km at equator
                    border_length_km = border_length_deg * 111.0
                    border_lengths[(i, j)] = border_length_km

            elif method == "queen":
                # Shares point or border
                if geom_i.touches(geom_j) or geom_i.intersects(geom_j):
                    rows.extend([i, j])
                    cols.extend([j, i])
                    intersection = geom_i.intersection(geom_j)
                    border_length_deg = (
                        intersection.length if hasattr(intersection, "length") else 0
                    )
                    border_length_km = border_length_deg * 111.0
                    border_lengths[(i, j)] = border_length_km

            else:
                raise ValueError(f"Unknown adjacency method: {method}")

    # Create sparse adjacency matrix
    data = np.ones(len(rows))
    adjacency = scipy.sparse.csr_matrix(
        (data, (rows, cols)), shape=(n_patches, n_patches)
    )

    metadata = {"border_lengths": border_lengths, "method": method}

    return adjacency, metadata

build_distance_matrix

build_distance_matrix(grid: 'EcospaceGrid', method: str = 'haversine') -> np.ndarray

Build distance matrix between all patch pairs.

Parameters:

Name Type Description Default
grid EcospaceGrid

Spatial grid

required
method str

Distance calculation method: - "haversine": Great circle distance (accurate for lat/lon) - "euclidean": Euclidean distance (fast, approximate)

'haversine'

Returns:

Type Description
ndarray

Distance matrix [n_patches, n_patches] in km

Source code in pypath/spatial/connectivity.py
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
def build_distance_matrix(
    grid: "EcospaceGrid", method: str = "haversine"
) -> np.ndarray:
    """Build distance matrix between all patch pairs.

    Parameters
    ----------
    grid : EcospaceGrid
        Spatial grid
    method : str
        Distance calculation method:
        - "haversine": Great circle distance (accurate for lat/lon)
        - "euclidean": Euclidean distance (fast, approximate)

    Returns
    -------
    np.ndarray
        Distance matrix [n_patches, n_patches] in km
    """
    if getattr(grid, "centroid_km", None) is not None:
        if method not in ("haversine", "euclidean"):
            raise ValueError(f"Unknown distance method: {method}")
        return calculate_patch_distances(grid)  # already in km on a plane

    _n_patches = grid.n_patches
    centroids = grid.patch_centroids

    if method == "haversine":
        # Pairwise haversine distances
        distances = np.zeros((_n_patches, _n_patches))
        for i in range(_n_patches):
            distances[i, :] = haversine_distance(
                centroids[i, 0], centroids[i, 1], centroids[:, 0], centroids[:, 1]
            )
        return distances

    elif method == "euclidean":
        # Simple Euclidean (degrees to km)
        return calculate_patch_distances(grid)

    else:
        raise ValueError(f"Unknown distance method: {method}")

calculate_patch_distances

calculate_patch_distances(grid: 'EcospaceGrid') -> np.ndarray

Calculate pairwise distances between patch centroids.

Parameters:

Name Type Description Default
grid EcospaceGrid

Spatial grid

required

Returns:

Type Description
ndarray

Distance matrix [n_patches, n_patches] in km

Source code in pypath/spatial/connectivity.py
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
def calculate_patch_distances(grid: "EcospaceGrid") -> np.ndarray:
    """Calculate pairwise distances between patch centroids.

    Parameters
    ----------
    grid : EcospaceGrid
        Spatial grid

    Returns
    -------
    np.ndarray
        Distance matrix [n_patches, n_patches] in km
    """
    plane = getattr(grid, "centroid_km", None)
    if plane is not None:  # a grid that knows its centroids in km
        from scipy.spatial.distance import cdist

        return cdist(plane, plane, metric="euclidean")

    _n_patches = grid.n_patches
    centroids = grid.patch_centroids

    # Calculate Euclidean distances
    # For geographic coordinates, this is approximate
    # For more accurate distances, use haversine formula
    from scipy.spatial.distance import cdist

    # Vectorized distance calculation (much faster than nested loops)
    # Calculate all pairwise distances at once
    distances_deg = cdist(centroids, centroids, metric="euclidean")
    distances = (
        distances_deg * _KM_PER_DEGREE_LAT
    )  # Rough conversion from degrees to km

    return distances

find_k_nearest_neighbors

find_k_nearest_neighbors(grid: 'EcospaceGrid', k: int, method: str = 'haversine') -> np.ndarray

Find k nearest neighbors for each patch.

Parameters:

Name Type Description Default
grid EcospaceGrid

Spatial grid

required
k int

Number of nearest neighbors to find

required
method str

Distance calculation method

'haversine'

Returns:

Type Description
ndarray

Neighbor indices [n_patches, k] neighbors[i, :] = indices of k nearest patches to patch i

Source code in pypath/spatial/connectivity.py
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
def find_k_nearest_neighbors(
    grid: "EcospaceGrid", k: int, method: str = "haversine"
) -> np.ndarray:
    """Find k nearest neighbors for each patch.

    Parameters
    ----------
    grid : EcospaceGrid
        Spatial grid
    k : int
        Number of nearest neighbors to find
    method : str
        Distance calculation method

    Returns
    -------
    np.ndarray
        Neighbor indices [n_patches, k]
        neighbors[i, :] = indices of k nearest patches to patch i
    """
    distances = build_distance_matrix(grid, method=method)

    # For each patch, find k+1 nearest (including self)
    # Then exclude self
    n_patches = grid.n_patches
    neighbors = np.zeros((n_patches, k), dtype=int)

    for i in range(n_patches):
        # argsort gives indices from nearest to farthest
        sorted_indices = np.argsort(distances[i, :])
        # Exclude self (distance 0) and take next k
        neighbors[i, :] = sorted_indices[1 : k + 1]

    return neighbors

get_connectivity_graph_stats

get_connectivity_graph_stats(adjacency: csr_matrix) -> Dict

Calculate graph statistics from adjacency matrix.

Parameters:

Name Type Description Default
adjacency csr_matrix

Adjacency matrix

required

Returns:

Type Description
dict

Dictionary with: - 'n_nodes': Number of patches - 'n_edges': Number of edges (undirected) - 'mean_degree': Average number of neighbors - 'max_degree': Maximum number of neighbors - 'min_degree': Minimum number of neighbors - 'isolated_patches': Patches with no neighbors

Source code in pypath/spatial/connectivity.py
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
def get_connectivity_graph_stats(adjacency: scipy.sparse.csr_matrix) -> Dict:
    """Calculate graph statistics from adjacency matrix.

    Parameters
    ----------
    adjacency : scipy.sparse.csr_matrix
        Adjacency matrix

    Returns
    -------
    dict
        Dictionary with:
        - 'n_nodes': Number of patches
        - 'n_edges': Number of edges (undirected)
        - 'mean_degree': Average number of neighbors
        - 'max_degree': Maximum number of neighbors
        - 'min_degree': Minimum number of neighbors
        - 'isolated_patches': Patches with no neighbors
    """
    n_patches = adjacency.shape[0]

    # Degree of each node
    degrees = np.array(adjacency.sum(axis=1)).flatten()

    # Number of edges (each edge counted twice in adjacency, so divide by 2)
    n_edges = int(adjacency.nnz / 2)

    stats = {
        "n_nodes": n_patches,
        "n_edges": n_edges,
        "mean_degree": np.mean(degrees),
        "max_degree": int(np.max(degrees)),
        "min_degree": int(np.min(degrees)),
        "isolated_patches": np.where(degrees == 0)[0].tolist(),
    }

    return stats

haversine_distance

haversine_distance(lon1: ndarray, lat1: ndarray, lon2: ndarray, lat2: ndarray) -> np.ndarray

Calculate great circle distance between points.

Uses the haversine formula for accurate distances on a sphere.

Parameters:

Name Type Description Default
lon1 ndarray

Longitude and latitude of first point(s) in degrees

required
lat1 ndarray

Longitude and latitude of first point(s) in degrees

required
lon2 ndarray

Longitude and latitude of second point(s) in degrees

required
lat2 ndarray

Longitude and latitude of second point(s) in degrees

required

Returns:

Type Description
ndarray

Distance in kilometers

Source code in pypath/spatial/connectivity.py
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
def haversine_distance(
    lon1: np.ndarray, lat1: np.ndarray, lon2: np.ndarray, lat2: np.ndarray
) -> np.ndarray:
    """Calculate great circle distance between points.

    Uses the haversine formula for accurate distances on a sphere.

    Parameters
    ----------
    lon1, lat1 : np.ndarray
        Longitude and latitude of first point(s) in degrees
    lon2, lat2 : np.ndarray
        Longitude and latitude of second point(s) in degrees

    Returns
    -------
    np.ndarray
        Distance in kilometers
    """
    # Convert to radians
    lon1_rad = np.radians(lon1)
    lat1_rad = np.radians(lat1)
    lon2_rad = np.radians(lon2)
    lat2_rad = np.radians(lat2)

    # Haversine formula
    dlon = lon2_rad - lon1_rad
    dlat = lat2_rad - lat1_rad

    a = (
        np.sin(dlat / 2) ** 2
        + np.cos(lat1_rad) * np.cos(lat2_rad) * np.sin(dlon / 2) ** 2
    )
    c = 2 * np.arcsin(np.sqrt(a))

    # Earth radius in km
    R = 6371.0

    return R * c

validate_adjacency_symmetry

validate_adjacency_symmetry(adjacency: csr_matrix) -> bool

Check if adjacency matrix is symmetric.

Parameters:

Name Type Description Default
adjacency csr_matrix

Adjacency matrix

required

Returns:

Type Description
bool

True if symmetric (within tolerance)

Source code in pypath/spatial/connectivity.py
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
def validate_adjacency_symmetry(adjacency: scipy.sparse.csr_matrix) -> bool:
    """Check if adjacency matrix is symmetric.

    Parameters
    ----------
    adjacency : scipy.sparse.csr_matrix
        Adjacency matrix

    Returns
    -------
    bool
        True if symmetric (within tolerance)
    """
    diff = adjacency - adjacency.T
    return diff.nnz == 0 or np.allclose(diff.data, 0)

Dispersal

Diffusion-based and advection-based dispersal of biomass between patches each timestep.

pypath.spatial.dispersal

Dispersal and movement mechanics for ECOSPACE.

Implements spatial flux calculations: - Diffusion (Fick's law) - Habitat-directed advection - Gravity models (biomass-weighted movement) - Hybrid flux (external + model-calculated)

apply_external_flux

apply_external_flux(biomass_vector: ndarray, external_flux: ExternalFluxTimeseries, group_idx: int, t: float) -> np.ndarray

Apply externally provided flux matrix to biomass.

External flux can come from: - Ocean circulation models (ROMS, MITgcm, HYCOM) - Particle tracking (Ichthyop, OpenDrift, Parcels) - Connectivity matrices (genetic data, telemetry)

Parameters:

Name Type Description Default
biomass_vector ndarray

Biomass in each patch [n_patches]

required
external_flux ExternalFluxTimeseries

External flux data

required
group_idx int

Group index

required
t float

Simulation time (years)

required

Returns:

Type Description
ndarray

Net flux for each patch [n_patches]

Notes

flux_matrix[p, q] = flux from patch p to patch q net_flux[p] = Σ_q flux_matrix[q, p] - Σ_q flux_matrix[p, q] = inflow - outflow

Source code in pypath/spatial/dispersal.py
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
def apply_external_flux(
    biomass_vector: np.ndarray,
    external_flux: ExternalFluxTimeseries,
    group_idx: int,
    t: float,
) -> np.ndarray:
    """Apply externally provided flux matrix to biomass.

    External flux can come from:
    - Ocean circulation models (ROMS, MITgcm, HYCOM)
    - Particle tracking (Ichthyop, OpenDrift, Parcels)
    - Connectivity matrices (genetic data, telemetry)

    Parameters
    ----------
    biomass_vector : np.ndarray
        Biomass in each patch [n_patches]
    external_flux : ExternalFluxTimeseries
        External flux data
    group_idx : int
        Group index
    t : float
        Simulation time (years)

    Returns
    -------
    np.ndarray
        Net flux for each patch [n_patches]

    Notes
    -----
    flux_matrix[p, q] = flux from patch p to patch q
    net_flux[p] = Σ_q flux_matrix[q, p] - Σ_q flux_matrix[p, q]
                = inflow - outflow
    """
    # Get flux matrix at time t
    flux_matrix = external_flux.get_flux_at_time(t, group_idx)

    # Calculate net flux for each patch
    # Inflow: sum over columns (from all q to p)
    # Outflow: sum over rows (from p to all q)
    if scipy.sparse.issparse(flux_matrix):
        inflow = np.array(flux_matrix.sum(axis=0)).flatten()
        outflow = np.array(flux_matrix.sum(axis=1)).flatten()
    else:
        inflow = flux_matrix.sum(axis=0)
        outflow = flux_matrix.sum(axis=1)

    net_flux = inflow - outflow

    return net_flux

apply_flux_limiter

apply_flux_limiter(flux: ndarray, biomass: ndarray, dt: float = 1.0) -> np.ndarray

Apply flux limiter to prevent negative biomass.

Limits outflow so that biomass cannot go negative during the timestep.

Parameters:

Name Type Description Default
flux ndarray

Net flux [n_patches]

required
biomass ndarray

Current biomass [n_patches]

required
dt float

Timestep size (fraction of month, default: 1.0)

1.0

Returns:

Type Description
ndarray

Limited flux [n_patches]

Source code in pypath/spatial/dispersal.py
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
def apply_flux_limiter(
    flux: np.ndarray, biomass: np.ndarray, dt: float = 1.0
) -> np.ndarray:
    """Apply flux limiter to prevent negative biomass.

    Limits outflow so that biomass cannot go negative
    during the timestep.

    Parameters
    ----------
    flux : np.ndarray
        Net flux [n_patches]
    biomass : np.ndarray
        Current biomass [n_patches]
    dt : float
        Timestep size (fraction of month, default: 1.0)

    Returns
    -------
    np.ndarray
        Limited flux [n_patches]
    """
    limited_flux = flux.copy()

    # For patches with outflow, limit to available biomass
    outflow_mask = flux < 0
    max_outflow = biomass[outflow_mask] / dt

    # Limit outflow
    limited_flux[outflow_mask] = np.maximum(flux[outflow_mask], -max_outflow)

    return limited_flux

calculate_spatial_flux

calculate_spatial_flux(state: ndarray, ecospace: EcospaceParams, params: dict, t: float, include_diffusion: bool = True) -> np.ndarray

Calculate total spatial flux (diffusion + advection + external).

Priority order for each group: 1. If external_flux provided for group -> use external 2. Else if dispersal_rate > 0 -> calculate model flux 3. Else -> no movement for this group

Parameters:

Name Type Description Default
state ndarray

Spatial state [n_groups+1, n_patches]

required
ecospace EcospaceParams

Spatial parameters

required
params dict

Ecosim parameters

required
t float

Simulation time (years)

required
include_diffusion bool

Include diffusion (default). rsim_run_spatial leaves it out when it moves the groups with implicit_diffusion_step instead; the advection of a dispersing group stays in the flux.

True

Returns:

Type Description
ndarray

Spatial flux [n_groups+1, n_patches] flux[g, p] = net flux for group g in patch p

Source code in pypath/spatial/dispersal.py
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
def calculate_spatial_flux(
    state: np.ndarray,
    ecospace: EcospaceParams,
    params: dict,
    t: float,
    include_diffusion: bool = True,
) -> np.ndarray:
    """Calculate total spatial flux (diffusion + advection + external).

    Priority order for each group:
    1. If external_flux provided for group -> use external
    2. Else if dispersal_rate > 0 -> calculate model flux
    3. Else -> no movement for this group

    Parameters
    ----------
    state : np.ndarray
        Spatial state [n_groups+1, n_patches]
    ecospace : EcospaceParams
        Spatial parameters
    params : dict
        Ecosim parameters
    t : float
        Simulation time (years)
    include_diffusion : bool
        Include diffusion (default). ``rsim_run_spatial`` leaves it out when
        it moves the groups with ``implicit_diffusion_step`` instead; the
        advection of a dispersing group stays in the flux.

    Returns
    -------
    np.ndarray
        Spatial flux [n_groups+1, n_patches]
        flux[g, p] = net flux for group g in patch p
    """
    n_groups = state.shape[0]
    _n_patches = state.shape[1]
    flux = np.zeros_like(state, dtype=float)

    grid = ecospace.grid
    adj = ecospace.grid.adjacency_matrix

    # IBM groups manage their own spatial movement; skip standard dispersal
    ibm_groups = params.get("ibm_groups", {})

    # Calculate flux for each group
    for group_idx in range(1, n_groups):  # Skip index 0 (Outside/Detritus)
        # Skip IBM groups — they handle movement in compute_step Phase 5
        if group_idx in ibm_groups:
            continue

        # Ecospace parameters are indexed from 0, but group_idx starts at 1
        # So we need to subtract 1 when accessing ecospace arrays
        eco_idx = group_idx - 1

        # Check for external flux first
        if (
            ecospace.external_flux is not None
            and eco_idx in ecospace.external_flux.group_indices
        ):
            # Use external flux (from ocean models, particle tracking, etc.)
            flux[group_idx] = apply_external_flux(
                state[group_idx], ecospace.external_flux, eco_idx, t
            )

        # Otherwise use model-calculated dispersal
        elif ecospace.dispersal_rate[eco_idx] > 0:
            # Passive diffusion (Fick's law)
            if include_diffusion:
                flux[group_idx] = diffusion_flux(
                    state[group_idx],
                    ecospace.dispersal_rate[eco_idx],
                    grid,
                    adj,
                    capacity=movement_capacity(
                        ecospace, eco_idx, params.get("_movement_capacity")
                    ),
                )

            # Add habitat-directed movement if enabled
            if (
                ecospace.advection_enabled[eco_idx]
                and ecospace.gravity_strength[eco_idx] > 0
            ):
                flux[group_idx] += habitat_advection(
                    state[group_idx],
                    ecospace.habitat_preference[eco_idx],
                    ecospace.gravity_strength[eco_idx],
                    grid,
                    adj,
                )

    return flux

diffusion_flux

diffusion_flux(biomass_vector: ndarray, dispersal_rate: float, grid: EcospaceGrid, adjacency: csr_matrix, capacity: Optional[ndarray] = None) -> np.ndarray

Calculate diffusion flux using Fick's law on density.

Flux between adjacent patches follows: flux_pq = -D * (rho_p - rho_q) * A_mean * (border_length / distance)

where rho = B / area is the density, A_mean the mean patch area and D the dispersal rate. Patches at the same density exchange nothing, whatever their areas (#57); on a grid of equal cells this is the same as using the biomass per patch.

With capacity (the group's habitat capacity per patch) movement is EwE's (B2): the flow from p to q is D * min(1, H_q / H_p) * rho_p * A_mean * (border_length / distance), so density in proportion to the capacity is at rest (_capacity_ratios). A uniform capacity is plain diffusion.

Parameters:

Name Type Description Default
biomass_vector ndarray

Biomass in each patch [n_patches]

required
dispersal_rate float

Dispersal rate per year (the spatial derivative and its RK4 step are per year). Multiplied by the mean patch area it is a diffusion coefficient in km² per year.

required
grid EcospaceGrid

Spatial grid configuration

required
adjacency csr_matrix

Adjacency matrix [n_patches, n_patches]

required
capacity ndarray

The group's habitat capacity per patch (EwE's HabCap, 0 to 1)

None

Returns:

Type Description
ndarray

Net flux for each patch [n_patches] - Positive = inflow (biomass increases) - Negative = outflow (biomass decreases) - Sum over all patches = 0 (conservation)

Source code in pypath/spatial/dispersal.py
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
def diffusion_flux(
    biomass_vector: np.ndarray,
    dispersal_rate: float,
    grid: EcospaceGrid,
    adjacency: scipy.sparse.csr_matrix,
    capacity: Optional[np.ndarray] = None,
) -> np.ndarray:
    """Calculate diffusion flux using Fick's law on density.

    Flux between adjacent patches follows:
        flux_pq = -D * (rho_p - rho_q) * A_mean * (border_length / distance)

    where rho = B / area is the density, A_mean the mean patch area and D
    the dispersal rate. Patches at the same density exchange nothing,
    whatever their areas (#57); on a grid of equal cells this is the same
    as using the biomass per patch.

    With ``capacity`` (the group's habitat capacity per patch) movement is
    EwE's (B2): the flow from p to q is D * min(1, H_q / H_p) * rho_p *
    A_mean * (border_length / distance), so density in proportion to the
    capacity is at rest (``_capacity_ratios``). A uniform capacity is plain
    diffusion.

    Parameters
    ----------
    biomass_vector : np.ndarray
        Biomass in each patch [n_patches]
    dispersal_rate : float
        Dispersal rate per year (the spatial derivative and its RK4 step are
        per year). Multiplied by the mean patch area it is a diffusion
        coefficient in km² per year.
    grid : EcospaceGrid
        Spatial grid configuration
    adjacency : scipy.sparse.csr_matrix
        Adjacency matrix [n_patches, n_patches]
    capacity : np.ndarray, optional
        The group's habitat capacity per patch (EwE's HabCap, 0 to 1)

    Returns
    -------
    np.ndarray
        Net flux for each patch [n_patches]
        - Positive = inflow (biomass increases)
        - Negative = outflow (biomass decreases)
        - Sum over all patches = 0 (conservation)
    """
    n_patches = len(biomass_vector)
    net_flux = np.zeros(n_patches)

    rows, cols, border_lengths, distances = _get_diffusion_edge_data(grid, adjacency)

    if len(rows) == 0:
        return net_flux

    biomass_vector = _area_scaled_density(biomass_vector, grid)

    if not _uniform(capacity):
        x_to_y, y_to_x = _capacity_ratios(capacity, rows, cols)
        safe_distances = np.where(distances == 0, np.inf, distances)
        rate = dispersal_rate * border_lengths / safe_distances
        flow = rate * (x_to_y * biomass_vector[rows] - y_to_x * biomass_vector[cols])
        np.add.at(net_flux, rows, -flow)
        np.add.at(net_flux, cols, flow)
        return net_flux

    # Use Numba-accelerated implementation when available
    if HAS_NUMBA:
        return _diffusion_flux_numba(
            biomass_vector,
            dispersal_rate,
            rows,
            cols,
            border_lengths,
            distances,
            n_patches,
        )

    # Vectorized gradient calculation
    gradients = biomass_vector[rows] - biomass_vector[cols]

    # Vectorized flux calculation
    # Guard against zero distances (e.g. same-centroid adjacent patches)
    safe_distances = np.where(distances == 0, np.inf, distances)
    flux_rates = dispersal_rate * border_lengths / safe_distances
    flux_values = flux_rates * gradients

    # Accumulate fluxes using np.add.at (vectorized accumulation)
    np.add.at(net_flux, rows, -flux_values)  # Outflow from rows
    np.add.at(net_flux, cols, flux_values)  # Inflow to cols

    return net_flux

diffusion_solver

diffusion_solver(dispersal_rate: float, grid: EcospaceGrid, adjacency: csr_matrix, dt: float, cache: dict | None = None, capacity: Optional[ndarray] = None)

The factorisation :func:implicit_diffusion_step solves with, or None when the step moves nothing (no rate, or one patch).

implicit_diffusion_step(b, ...) is lu.solve(b) (a copy of b for None): a caller stepping the same group many times with the same arguments can look the solver up once (rsim_run_spatial does, per month).

Source code in pypath/spatial/dispersal.py
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
def diffusion_solver(
    dispersal_rate: float,
    grid: EcospaceGrid,
    adjacency: scipy.sparse.csr_matrix,
    dt: float,
    cache: dict | None = None,
    capacity: Optional[np.ndarray] = None,
):
    """The factorisation :func:`implicit_diffusion_step` solves with, or
    None when the step moves nothing (no rate, or one patch).

    ``implicit_diffusion_step(b, ...)`` is ``lu.solve(b)`` (a copy of ``b``
    for None): a caller stepping the same group many times with the same
    arguments can look the solver up once (``rsim_run_spatial`` does, per
    month).
    """
    import scipy.sparse.linalg

    step = float(dispersal_rate) * float(dt)
    if not step > 0 or grid.n_patches < 2:
        return None
    if _uniform(capacity):
        capacity = None
        key = step
    else:
        capacity = np.asarray(capacity, dtype=float)
        key = (step, capacity.tobytes())
    lu = None if cache is None else cache.get(key)
    if lu is None:
        operator = _diffusion_operator(grid, adjacency, capacity)
        system = scipy.sparse.identity(grid.n_patches, format="csc") + step * operator
        lu = scipy.sparse.linalg.splu(system.tocsc())
        if cache is not None:
            cache[key] = lu
    return lu

gravity_model_flux

gravity_model_flux(biomass_vector: ndarray, attractiveness: ndarray, gravity_strength: float, grid: EcospaceGrid, adjacency: csr_matrix, distance_decay: float = 1.0) -> np.ndarray

Calculate gravity model flux (biomass-weighted attraction).

Movement rate from patch i to patch j: flux_ij ∝ (biomass_i) * (attractiveness_j) / (distance_ij ^ decay)

Parameters:

Name Type Description Default
biomass_vector ndarray

Biomass in each patch [n_patches]

required
attractiveness ndarray

Attractiveness of each patch [n_patches] Could be: biomass (aggregation), habitat quality, resources

required
gravity_strength float

Overall movement rate

required
grid EcospaceGrid

Spatial grid

required
adjacency csr_matrix

Adjacency matrix

required
distance_decay float

Distance decay exponent (default: 1.0) Higher values = stronger distance penalty

1.0

Returns:

Type Description
ndarray

Net flux [n_patches]

Source code in pypath/spatial/dispersal.py
431
432
433
434
435
436
437
438
439
440
441
442
443
444
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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
def gravity_model_flux(
    biomass_vector: np.ndarray,
    attractiveness: np.ndarray,
    gravity_strength: float,
    grid: EcospaceGrid,
    adjacency: scipy.sparse.csr_matrix,
    distance_decay: float = 1.0,
) -> np.ndarray:
    """Calculate gravity model flux (biomass-weighted attraction).

    Movement rate from patch i to patch j:
        flux_ij ∝ (biomass_i) * (attractiveness_j) / (distance_ij ^ decay)

    Parameters
    ----------
    biomass_vector : np.ndarray
        Biomass in each patch [n_patches]
    attractiveness : np.ndarray
        Attractiveness of each patch [n_patches]
        Could be: biomass (aggregation), habitat quality, resources
    gravity_strength : float
        Overall movement rate
    grid : EcospaceGrid
        Spatial grid
    adjacency : scipy.sparse.csr_matrix
        Adjacency matrix
    distance_decay : float
        Distance decay exponent (default: 1.0)
        Higher values = stronger distance penalty

    Returns
    -------
    np.ndarray
        Net flux [n_patches]
    """
    n_patches = len(biomass_vector)
    net_flux = np.zeros(n_patches)

    rows, cols = _get_upper_triangle_edges(adjacency)

    if len(rows) == 0:
        return net_flux

    distances = _edge_distances(grid, rows, cols)

    # Filter out zero distances
    valid_dist = distances > 0
    if not np.any(valid_dist):
        return net_flux

    rows = rows[valid_dist]
    cols = cols[valid_dist]
    distances = distances[valid_dist]

    # Use Numba-accelerated implementation when available
    if HAS_NUMBA:
        return _gravity_model_flux_numba(
            biomass_vector,
            attractiveness,
            gravity_strength,
            rows,
            cols,
            distances,
            distance_decay,
            n_patches,
        )

    # Vectorized gravity model calculations
    attractiveness_rows = attractiveness[rows]
    attractiveness_cols = attractiveness[cols]

    # Distance decay factor
    distance_factor = distances**distance_decay

    # Flux from rows to cols
    flux_ij = (
        gravity_strength * biomass_vector[rows] * attractiveness_cols / distance_factor
    )

    # Flux from cols to rows
    flux_ji = (
        gravity_strength * biomass_vector[cols] * attractiveness_rows / distance_factor
    )

    # Net flux (vectorized)
    net_fluxes = flux_ij - flux_ji

    # Accumulate using np.add.at
    np.add.at(net_flux, rows, -net_fluxes)
    np.add.at(net_flux, cols, net_fluxes)

    return net_flux

habitat_advection

habitat_advection(biomass_vector: ndarray, habitat_preference: ndarray, gravity_strength: float, grid: EcospaceGrid, adjacency: csr_matrix) -> np.ndarray

Calculate habitat-directed movement (advection).

Organisms move toward patches with higher habitat quality, in proportion to the habitat gradient and to the density of the patch they leave (scaled by the mean patch area, as in diffusion_flux; #57).

Parameters:

Name Type Description Default
biomass_vector ndarray

Biomass in each patch [n_patches]

required
habitat_preference ndarray

Habitat quality [n_patches], values 0-1

required
gravity_strength float

Movement strength (0-1) 0 = no movement, 1 = strong habitat-seeking

required
grid EcospaceGrid

Spatial grid configuration

required
adjacency csr_matrix

Adjacency matrix

required

Returns:

Type Description
ndarray

Net flux for each patch [n_patches]

Source code in pypath/spatial/dispersal.py
339
340
341
342
343
344
345
346
347
348
349
350
351
352
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
386
387
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
def habitat_advection(
    biomass_vector: np.ndarray,
    habitat_preference: np.ndarray,
    gravity_strength: float,
    grid: EcospaceGrid,
    adjacency: scipy.sparse.csr_matrix,
) -> np.ndarray:
    """Calculate habitat-directed movement (advection).

    Organisms move toward patches with higher habitat quality, in proportion
    to the habitat gradient and to the density of the patch they leave
    (scaled by the mean patch area, as in ``diffusion_flux``; #57).

    Parameters
    ----------
    biomass_vector : np.ndarray
        Biomass in each patch [n_patches]
    habitat_preference : np.ndarray
        Habitat quality [n_patches], values 0-1
    gravity_strength : float
        Movement strength (0-1)
        0 = no movement, 1 = strong habitat-seeking
    grid : EcospaceGrid
        Spatial grid configuration
    adjacency : scipy.sparse.csr_matrix
        Adjacency matrix

    Returns
    -------
    np.ndarray
        Net flux for each patch [n_patches]
    """
    if gravity_strength <= 0:
        return np.zeros(len(biomass_vector))

    n_patches = len(biomass_vector)
    net_flux = np.zeros(n_patches)

    rows, cols = _get_upper_triangle_edges(adjacency)

    if len(rows) == 0:
        return net_flux

    biomass_vector = _area_scaled_density(biomass_vector, grid)

    # Use Numba-accelerated implementation when available
    if HAS_NUMBA:
        return _habitat_advection_numba(
            biomass_vector, habitat_preference, gravity_strength, rows, cols, n_patches
        )

    # Vectorized habitat gradient calculation
    habitat_gradients = habitat_preference[cols] - habitat_preference[rows]

    # Filter out negligible gradients
    significant = np.abs(habitat_gradients) >= 1e-10
    if not np.any(significant):
        return net_flux

    rows = rows[significant]
    cols = cols[significant]
    habitat_gradients = habitat_gradients[significant]

    # Vectorized movement calculation
    # Positive gradient: move from rows to cols
    # Negative gradient: move from cols to rows
    positive_grad = habitat_gradients > 0
    negative_grad = ~positive_grad

    # For positive gradients: move from p (rows) to q (cols)
    if np.any(positive_grad):
        movement_rates_pos = (
            gravity_strength
            * biomass_vector[rows[positive_grad]]
            * habitat_gradients[positive_grad]
        )
        np.add.at(net_flux, rows[positive_grad], -movement_rates_pos)
        np.add.at(net_flux, cols[positive_grad], movement_rates_pos)

    # For negative gradients: move from q (cols) to p (rows)
    if np.any(negative_grad):
        movement_rates_neg = (
            gravity_strength
            * biomass_vector[cols[negative_grad]]
            * np.abs(habitat_gradients[negative_grad])
        )
        np.add.at(net_flux, cols[negative_grad], -movement_rates_neg)
        np.add.at(net_flux, rows[negative_grad], movement_rates_neg)

    return net_flux

implicit_diffusion_step

implicit_diffusion_step(biomass_vector: ndarray, dispersal_rate: float, grid: EcospaceGrid, adjacency: csr_matrix, dt: float, cache: dict | None = None, capacity: Optional[ndarray] = None) -> np.ndarray

Diffuse one group's biomass over dt years by backward Euler.

Solves (I + dt * rate * Lap @ D_s) B_new = B (_diffusion_operator), the implicit form of diffusion_flux: stable at any rate, conserving biomass, and non-negative (the matrix is a column-diagonally dominant M-matrix). With cache (a dict the caller owns for one grid) the factorisation is kept per rate x dt; it is not stored on the grid, which must stay copyable and picklable (SuperLU objects are neither).

Parameters:

Name Type Description Default
biomass_vector ndarray

Biomass in each patch [n_patches]

required
dispersal_rate float

Dispersal rate per year

required
grid EcospaceGrid

Spatial grid configuration

required
adjacency csr_matrix

Adjacency matrix [n_patches, n_patches]

required
dt float

Time step in years

required
cache dict

Factorisations by rate x dt (and capacity), owned by the caller (one per grid)

None
capacity ndarray

The group's habitat capacity per patch: EwE's capacity-weighted movement (see diffusion_flux). Uniform or None is plain diffusion.

None

Returns:

Type Description
ndarray

Biomass in each patch after the step [n_patches]

Source code in pypath/spatial/dispersal.py
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
def implicit_diffusion_step(
    biomass_vector: np.ndarray,
    dispersal_rate: float,
    grid: EcospaceGrid,
    adjacency: scipy.sparse.csr_matrix,
    dt: float,
    cache: dict | None = None,
    capacity: Optional[np.ndarray] = None,
) -> np.ndarray:
    """Diffuse one group's biomass over ``dt`` years by backward Euler.

    Solves ``(I + dt * rate * Lap @ D_s) B_new = B`` (``_diffusion_operator``),
    the implicit form of ``diffusion_flux``: stable at any rate, conserving
    biomass, and non-negative (the matrix is a column-diagonally dominant
    M-matrix). With ``cache`` (a dict the caller owns for one grid) the
    factorisation is kept per rate x dt; it is not stored on the grid, which
    must stay copyable and picklable (SuperLU objects are neither).

    Parameters
    ----------
    biomass_vector : np.ndarray
        Biomass in each patch [n_patches]
    dispersal_rate : float
        Dispersal rate per year
    grid : EcospaceGrid
        Spatial grid configuration
    adjacency : scipy.sparse.csr_matrix
        Adjacency matrix [n_patches, n_patches]
    dt : float
        Time step in years
    cache : dict, optional
        Factorisations by rate x dt (and capacity), owned by the caller
        (one per grid)
    capacity : np.ndarray, optional
        The group's habitat capacity per patch: EwE's capacity-weighted
        movement (see ``diffusion_flux``). Uniform or None is plain diffusion.

    Returns
    -------
    np.ndarray
        Biomass in each patch after the step [n_patches]
    """
    biomass_vector = np.asarray(biomass_vector, dtype=float)
    lu = diffusion_solver(dispersal_rate, grid, adjacency, dt, cache, capacity)
    if lu is None:
        return biomass_vector.copy()
    return lu.solve(biomass_vector)

movement_capacity

movement_capacity(ecospace, eco_idx: int, month_rows=None)

A group's habitat capacity row for movement, or None.

None when there is no habitat capacity, no row for the group, or the row is the same everywhere: movement is then plain diffusion. month_rows holds the rows of the groups whose movement follows a monthly capacity (MonthlyCapacity.movement_rows); the other groups read the base map.

Source code in pypath/spatial/dispersal.py
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
def movement_capacity(ecospace, eco_idx: int, month_rows=None):
    """A group's habitat capacity row for movement, or None.

    None when there is no habitat capacity, no row for the group, or the row
    is the same everywhere: movement is then plain diffusion. ``month_rows``
    holds the rows of the groups whose movement follows a monthly capacity
    (``MonthlyCapacity.movement_rows``); the other groups read the base map.
    """
    if month_rows and eco_idx in month_rows:
        row = month_rows[eco_idx]
        return None if _uniform(row) else row
    cap = getattr(ecospace, "habitat_capacity", None)
    if cap is None:
        return None
    cap = np.asarray(cap, dtype=float)
    if cap.ndim != 2 or not 0 <= eco_idx < cap.shape[0]:
        return None
    row = cap[eco_idx]
    return None if np.all(row == row[0]) else row

spatial_flux_is_zero

spatial_flux_is_zero(n_groups: int, ecospace: EcospaceParams, params: dict, include_diffusion: bool) -> bool

Whether :func:calculate_spatial_flux would return all zeros: no external flux, no IBM groups, and no dispersing group with diffusion included or habitat-directed movement. False whenever in doubt (the flux is then computed).

Source code in pypath/spatial/dispersal.py
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
def spatial_flux_is_zero(
    n_groups: int, ecospace: EcospaceParams, params: dict, include_diffusion: bool
) -> bool:
    """Whether :func:`calculate_spatial_flux` would return all zeros: no
    external flux, no IBM groups, and no dispersing group with diffusion
    included or habitat-directed movement. False whenever in doubt (the
    flux is then computed)."""
    if ecospace.external_flux is not None or params.get("ibm_groups"):
        return False
    m = n_groups - 1
    try:
        rate = np.asarray(ecospace.dispersal_rate, dtype=float)
        adv = np.asarray(ecospace.advection_enabled, dtype=bool)
        grav = np.asarray(ecospace.gravity_strength, dtype=float)
    except (TypeError, ValueError):
        return False
    if rate.ndim != 1 or len(rate) < m or len(adv) < m or len(grav) < m:
        return False
    movers = rate[:m] > 0
    if not movers.any():
        return True
    if include_diffusion:
        return False
    return not np.any(movers & adv[:m] & (grav[:m] > 0))

validate_flux_conservation

validate_flux_conservation(flux: ndarray, tolerance: float = 1e-08) -> bool

Validate that spatial flux conserves mass.

The sum of flux over all patches should be zero (no net creation or destruction of biomass).

Parameters:

Name Type Description Default
flux ndarray

Flux array [n_groups, n_patches] or [n_patches]

required
tolerance float

Numerical tolerance for zero (default: 1e-8)

1e-08

Returns:

Type Description
bool

True if flux is conserved (within tolerance)

Source code in pypath/spatial/dispersal.py
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
def validate_flux_conservation(flux: np.ndarray, tolerance: float = 1e-8) -> bool:
    """Validate that spatial flux conserves mass.

    The sum of flux over all patches should be zero
    (no net creation or destruction of biomass).

    Parameters
    ----------
    flux : np.ndarray
        Flux array [n_groups, n_patches] or [n_patches]
    tolerance : float
        Numerical tolerance for zero (default: 1e-8)

    Returns
    -------
    bool
        True if flux is conserved (within tolerance)
    """
    if flux.ndim == 1:
        # Single group
        total_flux = np.sum(flux)
        return abs(total_flux) < tolerance
    else:
        # Multiple groups
        total_flux = np.sum(flux, axis=1)
        return np.all(np.abs(total_flux) < tolerance)

Habitat Suitability

Habitat preference and capacity functions that modulate local carrying capacity and foraging efficiency per species per patch.

pypath.spatial.habitat

Habitat capacity and response functions for ECOSPACE.

Implements functions that map environmental conditions to habitat suitability: - Gaussian response (optimal value ± tolerance) - Threshold response (trapezoidal) - Linear response - Custom response functions - Multi-driver habitat capacity calculations

HabitatMap dataclass

Spatial habitat map with substrate and quality layers.

Source code in pypath/spatial/habitat.py
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
@dataclass
class HabitatMap:
    """Spatial habitat map with substrate and quality layers."""

    substrate: np.ndarray
    quality: np.ndarray | None = None
    cell_area_km2: float = 1.0
    metadata: dict[str, str] = field(default_factory=dict)

    def __post_init__(self):
        self.substrate = np.asarray(self.substrate)
        if self.substrate.ndim != 2:
            raise ValueError(
                f"substrate must be 2D [rows, cols], got {self.substrate.ndim}D"
            )
        if self.quality is None:
            self.quality = np.ones(self.substrate.shape, dtype=float)
        else:
            self.quality = np.asarray(self.quality, dtype=float)
            if self.quality.shape != self.substrate.shape:
                raise ValueError(
                    f"quality shape {self.quality.shape} must match substrate shape "
                    f"{self.substrate.shape}"
                )
        if self.cell_area_km2 <= 0:
            raise ValueError(f"cell_area_km2 must be > 0, got {self.cell_area_km2}")
        if not np.isfinite(self.quality).all():
            raise ValueError("quality contains non-finite values")

    @property
    def shape(self) -> tuple[int, int]:
        """Grid shape as (rows, cols)."""
        return self.substrate.shape

    @property
    def n_cells(self) -> int:
        """Number of cells in the map."""
        return int(self.substrate.size)

    def flatten_quality(self) -> np.ndarray:
        """Return habitat quality as flattened 1D vector."""
        return self.quality.reshape(-1).copy()

    def flatten_substrate(self) -> np.ndarray:
        """Return substrate as flattened 1D vector."""
        return self.substrate.reshape(-1).copy()

    def get_substrate_mask(self, substrate_type: SubstrateType | str) -> np.ndarray:
        """Boolean mask for all cells of a given substrate."""
        value = (
            substrate_type.value
            if isinstance(substrate_type, SubstrateType)
            else str(substrate_type)
        )
        return self.substrate == value

    def compute_species_quality(
        self, substrate_preferences: dict[str | SubstrateType, float]
    ) -> np.ndarray:
        """Compute species-specific quality from substrate preferences."""
        result = np.zeros(self.shape, dtype=float)
        for key, score in substrate_preferences.items():
            mask = self.get_substrate_mask(key)
            result[mask] = float(np.clip(score, 0.0, 1.0))
        return np.clip(result * self.quality, 0.0, 1.0)

    @classmethod
    def from_array(
        cls,
        substrate: np.ndarray,
        quality: np.ndarray | None = None,
        cell_area_km2: float = 1.0,
    ) -> "HabitatMap":
        """Create habitat map from in-memory arrays."""
        return cls(substrate=substrate, quality=quality, cell_area_km2=cell_area_km2)

    @classmethod
    def from_csv(
        cls,
        substrate_path: str | Path,
        quality_path: str | Path | None = None,
        delimiter: str = ",",
        cell_area_km2: float = 1.0,
    ) -> "HabitatMap":
        """Load habitat map from CSV rasters."""
        substrate = np.loadtxt(substrate_path, dtype=str, delimiter=delimiter)
        quality = (
            np.loadtxt(quality_path, dtype=float, delimiter=delimiter)
            if quality_path is not None
            else None
        )
        return cls(
            substrate=substrate,
            quality=quality,
            cell_area_km2=cell_area_km2,
            metadata={"source": "csv"},
        )

    @classmethod
    def from_netcdf(
        cls,
        path: str | Path,
        substrate_var: str,
        quality_var: str | None = None,
        cell_area_km2: float = 1.0,
    ) -> "HabitatMap":
        """Load habitat map from NetCDF."""
        try:
            import xarray as xr
        except ImportError as exc:
            raise ImportError(
                "xarray is required to load habitat maps from NetCDF"
            ) from exc

        ds = xr.open_dataset(path)
        try:
            substrate = ds[substrate_var].values
            quality = ds[quality_var].values if quality_var is not None else None
        finally:
            ds.close()
        return cls(
            substrate=substrate,
            quality=quality,
            cell_area_km2=cell_area_km2,
            metadata={"source": "netcdf"},
        )
n_cells property
n_cells: int

Number of cells in the map.

shape property
shape: tuple[int, int]

Grid shape as (rows, cols).

compute_species_quality
compute_species_quality(substrate_preferences: dict[str | SubstrateType, float]) -> np.ndarray

Compute species-specific quality from substrate preferences.

Source code in pypath/spatial/habitat.py
540
541
542
543
544
545
546
547
548
def compute_species_quality(
    self, substrate_preferences: dict[str | SubstrateType, float]
) -> np.ndarray:
    """Compute species-specific quality from substrate preferences."""
    result = np.zeros(self.shape, dtype=float)
    for key, score in substrate_preferences.items():
        mask = self.get_substrate_mask(key)
        result[mask] = float(np.clip(score, 0.0, 1.0))
    return np.clip(result * self.quality, 0.0, 1.0)
flatten_quality
flatten_quality() -> np.ndarray

Return habitat quality as flattened 1D vector.

Source code in pypath/spatial/habitat.py
523
524
525
def flatten_quality(self) -> np.ndarray:
    """Return habitat quality as flattened 1D vector."""
    return self.quality.reshape(-1).copy()
flatten_substrate
flatten_substrate() -> np.ndarray

Return substrate as flattened 1D vector.

Source code in pypath/spatial/habitat.py
527
528
529
def flatten_substrate(self) -> np.ndarray:
    """Return substrate as flattened 1D vector."""
    return self.substrate.reshape(-1).copy()
from_array classmethod
from_array(substrate: ndarray, quality: ndarray | None = None, cell_area_km2: float = 1.0) -> 'HabitatMap'

Create habitat map from in-memory arrays.

Source code in pypath/spatial/habitat.py
550
551
552
553
554
555
556
557
558
@classmethod
def from_array(
    cls,
    substrate: np.ndarray,
    quality: np.ndarray | None = None,
    cell_area_km2: float = 1.0,
) -> "HabitatMap":
    """Create habitat map from in-memory arrays."""
    return cls(substrate=substrate, quality=quality, cell_area_km2=cell_area_km2)
from_csv classmethod
from_csv(substrate_path: str | Path, quality_path: str | Path | None = None, delimiter: str = ',', cell_area_km2: float = 1.0) -> 'HabitatMap'

Load habitat map from CSV rasters.

Source code in pypath/spatial/habitat.py
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
@classmethod
def from_csv(
    cls,
    substrate_path: str | Path,
    quality_path: str | Path | None = None,
    delimiter: str = ",",
    cell_area_km2: float = 1.0,
) -> "HabitatMap":
    """Load habitat map from CSV rasters."""
    substrate = np.loadtxt(substrate_path, dtype=str, delimiter=delimiter)
    quality = (
        np.loadtxt(quality_path, dtype=float, delimiter=delimiter)
        if quality_path is not None
        else None
    )
    return cls(
        substrate=substrate,
        quality=quality,
        cell_area_km2=cell_area_km2,
        metadata={"source": "csv"},
    )
from_netcdf classmethod
from_netcdf(path: str | Path, substrate_var: str, quality_var: str | None = None, cell_area_km2: float = 1.0) -> 'HabitatMap'

Load habitat map from NetCDF.

Source code in pypath/spatial/habitat.py
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
@classmethod
def from_netcdf(
    cls,
    path: str | Path,
    substrate_var: str,
    quality_var: str | None = None,
    cell_area_km2: float = 1.0,
) -> "HabitatMap":
    """Load habitat map from NetCDF."""
    try:
        import xarray as xr
    except ImportError as exc:
        raise ImportError(
            "xarray is required to load habitat maps from NetCDF"
        ) from exc

    ds = xr.open_dataset(path)
    try:
        substrate = ds[substrate_var].values
        quality = ds[quality_var].values if quality_var is not None else None
    finally:
        ds.close()
    return cls(
        substrate=substrate,
        quality=quality,
        cell_area_km2=cell_area_km2,
        metadata={"source": "netcdf"},
    )
get_substrate_mask
get_substrate_mask(substrate_type: SubstrateType | str) -> np.ndarray

Boolean mask for all cells of a given substrate.

Source code in pypath/spatial/habitat.py
531
532
533
534
535
536
537
538
def get_substrate_mask(self, substrate_type: SubstrateType | str) -> np.ndarray:
    """Boolean mask for all cells of a given substrate."""
    value = (
        substrate_type.value
        if isinstance(substrate_type, SubstrateType)
        else str(substrate_type)
    )
    return self.substrate == value

HabitatQuality dataclass

Patch-level habitat quality components.

Source code in pypath/spatial/habitat.py
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
@dataclass
class HabitatQuality:
    """Patch-level habitat quality components."""

    substrate_quality: float
    structural_complexity: float = 1.0
    environmental_suitability: float = 1.0

    def overall(self) -> float:
        """Compute bounded overall habitat quality in [0, 1]."""
        quality = (
            self.substrate_quality
            * self.structural_complexity
            * self.environmental_suitability
        )
        return float(np.clip(quality, 0.0, 1.0))
overall
overall() -> float

Compute bounded overall habitat quality in [0, 1].

Source code in pypath/spatial/habitat.py
474
475
476
477
478
479
480
481
def overall(self) -> float:
    """Compute bounded overall habitat quality in [0, 1]."""
    quality = (
        self.substrate_quality
        * self.structural_complexity
        * self.environmental_suitability
    )
    return float(np.clip(quality, 0.0, 1.0))

SubstrateType

Bases: str, Enum

Canonical substrate categories for habitat maps.

Source code in pypath/spatial/habitat.py
455
456
457
458
459
460
461
462
463
class SubstrateType(str, Enum):
    """Canonical substrate categories for habitat maps."""

    MUD = "mud"
    SAND = "sand"
    GRAVEL = "gravel"
    ROCK = "rock"
    VEGETATION = "vegetation"
    MIXED = "mixed"

apply_habitat_preference_and_suitability

apply_habitat_preference_and_suitability(base_preference: ndarray, environmental_suitability: ndarray, combine_method: str = 'multiplicative') -> np.ndarray

Combine base habitat preference with environmental suitability.

Base preference represents intrinsic patch quality (structure, substrate), while environmental suitability represents dynamic factors (temperature).

Parameters:

Name Type Description Default
base_preference ndarray

Base habitat preference [n_patches], values in [0, 1]

required
environmental_suitability ndarray

Environmental suitability [n_patches], values in [0, 1]

required
combine_method str

How to combine: - "multiplicative": preference * suitability (default) - "minimum": min(preference, suitability) - "average": (preference + suitability) / 2

'multiplicative'

Returns:

Type Description
ndarray

Combined habitat quality [n_patches], values in [0, 1]

Examples:

>>> base_pref = np.array([1.0, 0.5, 0.8])  # Intrinsic quality
>>> env_suit = np.array([0.8, 1.0, 0.6])   # Environmental suitability
>>>
>>> # Multiplicative (strict)
>>> apply_habitat_preference_and_suitability(base_pref, env_suit, "multiplicative")
array([0.8 , 0.5 , 0.48])
>>>
>>> # Minimum (limiting factor)
>>> apply_habitat_preference_and_suitability(base_pref, env_suit, "minimum")
array([0.8, 0.5, 0.6])
Source code in pypath/spatial/habitat.py
387
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
443
444
445
446
447
448
449
def apply_habitat_preference_and_suitability(
    base_preference: np.ndarray,
    environmental_suitability: np.ndarray,
    combine_method: str = "multiplicative",
) -> np.ndarray:
    """Combine base habitat preference with environmental suitability.

    Base preference represents intrinsic patch quality (structure, substrate),
    while environmental suitability represents dynamic factors (temperature).

    Parameters
    ----------
    base_preference : np.ndarray
        Base habitat preference [n_patches], values in [0, 1]
    environmental_suitability : np.ndarray
        Environmental suitability [n_patches], values in [0, 1]
    combine_method : str
        How to combine:
        - "multiplicative": preference * suitability (default)
        - "minimum": min(preference, suitability)
        - "average": (preference + suitability) / 2

    Returns
    -------
    np.ndarray
        Combined habitat quality [n_patches], values in [0, 1]

    Examples
    --------
    >>> base_pref = np.array([1.0, 0.5, 0.8])  # Intrinsic quality
    >>> env_suit = np.array([0.8, 1.0, 0.6])   # Environmental suitability
    >>>
    >>> # Multiplicative (strict)
    >>> apply_habitat_preference_and_suitability(base_pref, env_suit, "multiplicative")
    array([0.8 , 0.5 , 0.48])
    >>>
    >>> # Minimum (limiting factor)
    >>> apply_habitat_preference_and_suitability(base_pref, env_suit, "minimum")
    array([0.8, 0.5, 0.6])
    """
    base_preference = np.asarray(base_preference, dtype=float)
    environmental_suitability = np.asarray(environmental_suitability, dtype=float)

    if base_preference.shape != environmental_suitability.shape:
        raise ValueError(
            f"Shape mismatch: base_preference {base_preference.shape} != "
            f"environmental_suitability {environmental_suitability.shape}"
        )

    if combine_method == "multiplicative":
        return base_preference * environmental_suitability

    elif combine_method == "minimum":
        return np.minimum(base_preference, environmental_suitability)

    elif combine_method == "average":
        return (base_preference + environmental_suitability) / 2

    else:
        raise ValueError(
            f"Unknown combine_method '{combine_method}'. "
            f"Must be one of: multiplicative, minimum, average"
        )

calculate_habitat_suitability

calculate_habitat_suitability(environmental_values: ndarray, response_functions: List[Callable], combine_method: str = 'multiplicative') -> np.ndarray

Calculate habitat suitability from multiple environmental drivers.

Combines multiple environmental responses into overall habitat suitability.

Parameters:

Name Type Description Default
environmental_values ndarray

Environmental values [n_patches, n_drivers]

required
response_functions list of callable

Response function for each driver Must match number of drivers

required
combine_method str

How to combine responses: - "multiplicative": product of all responses (default) - "minimum": minimum of all responses - "geometric_mean": geometric mean - "average": arithmetic mean

'multiplicative'

Returns:

Type Description
ndarray

Habitat suitability [n_patches], values in [0, 1]

Examples:

>>> # Temperature and depth responses
>>> env = np.array([
...     [10, 50],   # Patch 0: 10°C, 50m
...     [15, 100],  # Patch 1: 15°C, 100m
...     [8, 30]     # Patch 2: 8°C, 30m
... ])
>>>
>>> temp_response = create_gaussian_response(optimal_value=12, tolerance=4)
>>> depth_response = create_linear_response(min_value=0, max_value=200)
>>>
>>> suitability = calculate_habitat_suitability(
...     env,
...     [temp_response, depth_response],
...     combine_method="multiplicative"
... )
Source code in pypath/spatial/habitat.py
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
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
def calculate_habitat_suitability(
    environmental_values: np.ndarray,
    response_functions: List[Callable],
    combine_method: str = "multiplicative",
) -> np.ndarray:
    """Calculate habitat suitability from multiple environmental drivers.

    Combines multiple environmental responses into overall habitat suitability.

    Parameters
    ----------
    environmental_values : np.ndarray
        Environmental values [n_patches, n_drivers]
    response_functions : list of callable
        Response function for each driver
        Must match number of drivers
    combine_method : str
        How to combine responses:
        - "multiplicative": product of all responses (default)
        - "minimum": minimum of all responses
        - "geometric_mean": geometric mean
        - "average": arithmetic mean

    Returns
    -------
    np.ndarray
        Habitat suitability [n_patches], values in [0, 1]

    Examples
    --------
    >>> # Temperature and depth responses
    >>> env = np.array([
    ...     [10, 50],   # Patch 0: 10°C, 50m
    ...     [15, 100],  # Patch 1: 15°C, 100m
    ...     [8, 30]     # Patch 2: 8°C, 30m
    ... ])
    >>>
    >>> temp_response = create_gaussian_response(optimal_value=12, tolerance=4)
    >>> depth_response = create_linear_response(min_value=0, max_value=200)
    >>>
    >>> suitability = calculate_habitat_suitability(
    ...     env,
    ...     [temp_response, depth_response],
    ...     combine_method="multiplicative"
    ... )
    """
    environmental_values = np.asarray(environmental_values, dtype=float)

    # Handle 1D case (single patch)
    if environmental_values.ndim == 1:
        environmental_values = environmental_values.reshape(1, -1)

    n_patches, n_drivers = environmental_values.shape

    if len(response_functions) != n_drivers:
        raise ValueError(
            f"Number of response functions ({len(response_functions)}) "
            f"must match number of drivers ({n_drivers})"
        )

    # Calculate response for each driver
    responses = np.zeros((n_patches, n_drivers), dtype=float)

    for i, response_func in enumerate(response_functions):
        responses[:, i] = response_func(environmental_values[:, i])

    # Combine responses
    if combine_method == "multiplicative":
        # Product of all responses
        suitability = np.prod(responses, axis=1)

    elif combine_method == "minimum":
        # Limiting factor (minimum response)
        suitability = np.min(responses, axis=1)

    elif combine_method == "geometric_mean":
        # Geometric mean — clip to avoid log(0) bias on non-zero responses
        suitability = np.exp(np.mean(np.log(np.clip(responses, 1e-10, None)), axis=1))

    elif combine_method == "average":
        # Arithmetic mean
        suitability = np.mean(responses, axis=1)

    else:
        raise ValueError(
            f"Unknown combine_method '{combine_method}'. "
            f"Must be one of: multiplicative, minimum, geometric_mean, average"
        )

    return suitability

create_gaussian_response

create_gaussian_response(optimal_value: float, tolerance: float, min_value: Optional[float] = None, max_value: Optional[float] = None) -> Callable[[np.ndarray], np.ndarray]

Create Gaussian (normal) response function.

Habitat suitability peaks at optimal value and decreases with distance from optimum:

response(x) = exp(-((x - optimal) / tolerance)²)

Parameters:

Name Type Description Default
optimal_value float

Optimal environmental value (maximum suitability)

required
tolerance float

Tolerance range (standard deviation) Suitability = 0.607 at optimal ± tolerance

required
min_value float

Minimum valid environmental value (hard cutoff) Values below this return 0 suitability

None
max_value float

Maximum valid environmental value (hard cutoff)

None

Returns:

Type Description
callable

Response function: env_value -> suitability [0, 1]

Examples:

>>> # Cod prefer 8°C ± 4°C
>>> response = create_gaussian_response(optimal_value=8.0, tolerance=4.0)
>>> response(np.array([4, 8, 12, 16]))
array([0.60653066, 1.        , 0.60653066, 0.13533528])
>>> # With hard cutoffs
>>> response = create_gaussian_response(
...     optimal_value=15.0,
...     tolerance=5.0,
...     min_value=5.0,
...     max_value=25.0
... )
>>> response(np.array([0, 10, 15, 20, 30]))
array([0.        , 0.60653066, 1.        , 0.60653066, 0.        ])
Source code in pypath/spatial/habitat.py
25
26
27
28
29
30
31
32
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
86
87
88
89
90
91
92
def create_gaussian_response(
    optimal_value: float,
    tolerance: float,
    min_value: Optional[float] = None,
    max_value: Optional[float] = None,
) -> Callable[[np.ndarray], np.ndarray]:
    """Create Gaussian (normal) response function.

    Habitat suitability peaks at optimal value and decreases
    with distance from optimum:

        response(x) = exp(-((x - optimal) / tolerance)²)

    Parameters
    ----------
    optimal_value : float
        Optimal environmental value (maximum suitability)
    tolerance : float
        Tolerance range (standard deviation)
        Suitability = 0.607 at optimal ± tolerance
    min_value : float, optional
        Minimum valid environmental value (hard cutoff)
        Values below this return 0 suitability
    max_value : float, optional
        Maximum valid environmental value (hard cutoff)

    Returns
    -------
    callable
        Response function: env_value -> suitability [0, 1]

    Examples
    --------
    >>> # Cod prefer 8°C ± 4°C
    >>> response = create_gaussian_response(optimal_value=8.0, tolerance=4.0)
    >>> response(np.array([4, 8, 12, 16]))
    array([0.60653066, 1.        , 0.60653066, 0.13533528])

    >>> # With hard cutoffs
    >>> response = create_gaussian_response(
    ...     optimal_value=15.0,
    ...     tolerance=5.0,
    ...     min_value=5.0,
    ...     max_value=25.0
    ... )
    >>> response(np.array([0, 10, 15, 20, 30]))
    array([0.        , 0.60653066, 1.        , 0.60653066, 0.        ])
    """

    if tolerance <= 0:
        raise ValueError(f"tolerance must be > 0, got {tolerance}")

    def response_function(env_values: np.ndarray) -> np.ndarray:
        env_values = np.asarray(env_values, dtype=float)

        # Gaussian response
        suitability = np.exp(-(((env_values - optimal_value) / tolerance) ** 2))

        # Apply hard cutoffs if specified
        if min_value is not None:
            suitability[env_values < min_value] = 0.0

        if max_value is not None:
            suitability[env_values > max_value] = 0.0

        return suitability

    return response_function

create_linear_response

create_linear_response(min_value: float, max_value: float, increasing: bool = True) -> Callable[[np.ndarray], np.ndarray]

Create linear response function.

Suitability increases or decreases linearly with environmental value.

Parameters:

Name Type Description Default
min_value float

Environmental value where suitability = 0 (or 1 if decreasing)

required
max_value float

Environmental value where suitability = 1 (or 0 if decreasing)

required
increasing bool

If True, suitability increases with env value (default) If False, suitability decreases

True

Returns:

Type Description
callable

Response function: env_value -> suitability [0, 1]

Examples:

>>> # Deeper is better (increasing)
>>> response = create_linear_response(min_value=0, max_value=100, increasing=True)
>>> response(np.array([0, 50, 100]))
array([0. , 0.5, 1. ])
>>> # Shallower is better (decreasing)
>>> response = create_linear_response(min_value=0, max_value=100, increasing=False)
>>> response(np.array([0, 50, 100]))
array([1. , 0.5, 0. ])
Source code in pypath/spatial/habitat.py
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
def create_linear_response(
    min_value: float, max_value: float, increasing: bool = True
) -> Callable[[np.ndarray], np.ndarray]:
    """Create linear response function.

    Suitability increases or decreases linearly with environmental value.

    Parameters
    ----------
    min_value : float
        Environmental value where suitability = 0 (or 1 if decreasing)
    max_value : float
        Environmental value where suitability = 1 (or 0 if decreasing)
    increasing : bool
        If True, suitability increases with env value (default)
        If False, suitability decreases

    Returns
    -------
    callable
        Response function: env_value -> suitability [0, 1]

    Examples
    --------
    >>> # Deeper is better (increasing)
    >>> response = create_linear_response(min_value=0, max_value=100, increasing=True)
    >>> response(np.array([0, 50, 100]))
    array([0. , 0.5, 1. ])

    >>> # Shallower is better (decreasing)
    >>> response = create_linear_response(min_value=0, max_value=100, increasing=False)
    >>> response(np.array([0, 50, 100]))
    array([1. , 0.5, 0. ])
    """
    if min_value >= max_value:
        raise ValueError(f"min_value ({min_value}) must be < max_value ({max_value})")

    def response_function(env_values: np.ndarray) -> np.ndarray:
        env_values = np.asarray(env_values, dtype=float)

        # Normalize to [0, 1]
        suitability = (env_values - min_value) / (max_value - min_value)

        # Clip to [0, 1]
        suitability = np.clip(suitability, 0.0, 1.0)

        # Invert if decreasing
        if not increasing:
            suitability = 1.0 - suitability

        return suitability

    return response_function

create_step_response

create_step_response(threshold: float, above_threshold: float = 1.0, below_threshold: float = 0.0) -> Callable[[np.ndarray], np.ndarray]

Create step (binary) response function.

Suitability is constant above/below threshold.

Parameters:

Name Type Description Default
threshold float

Threshold value

required
above_threshold float

Suitability when env >= threshold (default: 1.0)

1.0
below_threshold float

Suitability when env < threshold (default: 0.0)

0.0

Returns:

Type Description
callable

Response function: env_value -> suitability

Examples:

>>> # Requires minimum depth of 50m
>>> response = create_step_response(threshold=50, above_threshold=1.0, below_threshold=0.0)
>>> response(np.array([30, 50, 100]))
array([0., 1., 1.])
Source code in pypath/spatial/habitat.py
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
def create_step_response(
    threshold: float, above_threshold: float = 1.0, below_threshold: float = 0.0
) -> Callable[[np.ndarray], np.ndarray]:
    """Create step (binary) response function.

    Suitability is constant above/below threshold.

    Parameters
    ----------
    threshold : float
        Threshold value
    above_threshold : float
        Suitability when env >= threshold (default: 1.0)
    below_threshold : float
        Suitability when env < threshold (default: 0.0)

    Returns
    -------
    callable
        Response function: env_value -> suitability

    Examples
    --------
    >>> # Requires minimum depth of 50m
    >>> response = create_step_response(threshold=50, above_threshold=1.0, below_threshold=0.0)
    >>> response(np.array([30, 50, 100]))
    array([0., 1., 1.])
    """

    def response_function(env_values: np.ndarray) -> np.ndarray:
        env_values = np.asarray(env_values, dtype=float)
        suitability = np.where(
            env_values >= threshold, above_threshold, below_threshold
        )
        return suitability

    return response_function

create_threshold_response

create_threshold_response(min_value: float, max_value: float, optimal_min: Optional[float] = None, optimal_max: Optional[float] = None) -> Callable[[np.ndarray], np.ndarray]

Create threshold (trapezoidal) response function.

Response forms a trapezoid: - 0 below min_value - Linear increase from min_value to optimal_min - 1 (optimal) from optimal_min to optimal_max - Linear decrease from optimal_max to max_value - 0 above max_value

If optimal_min/max not specified, response is triangular with peak at midpoint.

Parameters:

Name Type Description Default
min_value float

Minimum tolerable value (suitability = 0)

required
max_value float

Maximum tolerable value (suitability = 0)

required
optimal_min float

Start of optimal range (suitability = 1) Default: midpoint between min and max

None
optimal_max float

End of optimal range (suitability = 1) Default: same as optimal_min (triangular response)

None

Returns:

Type Description
callable

Response function: env_value -> suitability [0, 1]

Examples:

>>> # Herring tolerate 0-20°C, optimal 8-12°C
>>> response = create_threshold_response(
...     min_value=0.0,
...     max_value=20.0,
...     optimal_min=8.0,
...     optimal_max=12.0
... )
>>> response(np.array([-5, 0, 4, 10, 16, 20, 25]))
array([0. , 0. , 0.5, 1. , 0.5, 0. , 0. ])
>>> # Triangular response (no optimal plateau)
>>> response = create_threshold_response(min_value=5, max_value=25)
>>> response(np.array([5, 15, 25]))
array([0., 1., 0.])
Source code in pypath/spatial/habitat.py
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
def create_threshold_response(
    min_value: float,
    max_value: float,
    optimal_min: Optional[float] = None,
    optimal_max: Optional[float] = None,
) -> Callable[[np.ndarray], np.ndarray]:
    """Create threshold (trapezoidal) response function.

    Response forms a trapezoid:
    - 0 below min_value
    - Linear increase from min_value to optimal_min
    - 1 (optimal) from optimal_min to optimal_max
    - Linear decrease from optimal_max to max_value
    - 0 above max_value

    If optimal_min/max not specified, response is triangular
    with peak at midpoint.

    Parameters
    ----------
    min_value : float
        Minimum tolerable value (suitability = 0)
    max_value : float
        Maximum tolerable value (suitability = 0)
    optimal_min : float, optional
        Start of optimal range (suitability = 1)
        Default: midpoint between min and max
    optimal_max : float, optional
        End of optimal range (suitability = 1)
        Default: same as optimal_min (triangular response)

    Returns
    -------
    callable
        Response function: env_value -> suitability [0, 1]

    Examples
    --------
    >>> # Herring tolerate 0-20°C, optimal 8-12°C
    >>> response = create_threshold_response(
    ...     min_value=0.0,
    ...     max_value=20.0,
    ...     optimal_min=8.0,
    ...     optimal_max=12.0
    ... )
    >>> response(np.array([-5, 0, 4, 10, 16, 20, 25]))
    array([0. , 0. , 0.5, 1. , 0.5, 0. , 0. ])

    >>> # Triangular response (no optimal plateau)
    >>> response = create_threshold_response(min_value=5, max_value=25)
    >>> response(np.array([5, 15, 25]))
    array([0., 1., 0.])
    """
    # Set defaults for optimal range
    if optimal_min is None and optimal_max is None:
        # Triangular - peak at midpoint
        midpoint = (min_value + max_value) / 2
        optimal_min = midpoint
        optimal_max = midpoint
    elif optimal_min is None:
        optimal_min = optimal_max
    elif optimal_max is None:
        optimal_max = optimal_min

    # Validate
    if not (min_value <= optimal_min <= optimal_max <= max_value):
        raise ValueError(
            f"Must satisfy: min_value ({min_value}) <= "
            f"optimal_min ({optimal_min}) <= "
            f"optimal_max ({optimal_max}) <= "
            f"max_value ({max_value})"
        )

    def response_function(env_values: np.ndarray) -> np.ndarray:
        env_values = np.asarray(env_values, dtype=float)
        suitability = np.zeros_like(env_values, dtype=float)

        # Below minimum: 0
        # (already initialized to 0)

        # Rising edge: min_value to optimal_min
        if optimal_min > min_value:
            mask = (env_values >= min_value) & (env_values < optimal_min)
            suitability[mask] = (env_values[mask] - min_value) / (
                optimal_min - min_value
            )

        # Optimal plateau: optimal_min to optimal_max
        mask = (env_values >= optimal_min) & (env_values <= optimal_max)
        suitability[mask] = 1.0

        # Falling edge: optimal_max to max_value
        if max_value > optimal_max:
            mask = (env_values > optimal_max) & (env_values <= max_value)
            suitability[mask] = (max_value - env_values[mask]) / (
                max_value - optimal_max
            )

        # Above maximum: 0
        # (already initialized to 0)

        return suitability

    return response_function

Environmental Drivers

Spatially and temporally varying environmental layers (temperature, salinity, depth) that influence growth, metabolism, and movement.

pypath.spatial.environmental

Environmental drivers for ECOSPACE.

Implements time-varying spatial environmental fields: - Temperature, salinity, depth, currents - Multiple environmental layers - Temporal interpolation - Integration with habitat capacity models

EnvironmentalDrivers

Manager for multiple environmental layers.

Coordinates multiple environmental variables and provides combined environmental state for habitat calculations.

Parameters:

Name Type Description Default
layers dict

Dictionary of EnvironmentalLayer objects {name: layer}

None

Examples:

>>> drivers = EnvironmentalDrivers()
>>> drivers.add_layer(temp_layer)
>>> drivers.add_layer(depth_layer)
>>>
>>> # Get all drivers at specific time
>>> env = drivers.get_drivers_at_time(t=0.5)  # [n_patches, n_layers]
>>>
>>> # Get specific layer
>>> temp = drivers.get_layer_at_time('temperature', t=0.5)  # [n_patches]
Source code in pypath/spatial/environmental.py
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
class EnvironmentalDrivers:
    """Manager for multiple environmental layers.

    Coordinates multiple environmental variables and provides
    combined environmental state for habitat calculations.

    Parameters
    ----------
    layers : dict, optional
        Dictionary of EnvironmentalLayer objects {name: layer}

    Examples
    --------
    >>> drivers = EnvironmentalDrivers()
    >>> drivers.add_layer(temp_layer)
    >>> drivers.add_layer(depth_layer)
    >>>
    >>> # Get all drivers at specific time
    >>> env = drivers.get_drivers_at_time(t=0.5)  # [n_patches, n_layers]
    >>>
    >>> # Get specific layer
    >>> temp = drivers.get_layer_at_time('temperature', t=0.5)  # [n_patches]
    """

    def __init__(self, layers: Optional[Dict[str, EnvironmentalLayer]] = None):
        """Initialize environmental drivers."""
        self.layers = layers if layers is not None else {}
        self._validate_layers()

    def _validate_layers(self):
        """Validate that all layers have same number of patches."""
        if not self.layers:
            return

        n_patches_list = [layer.n_patches for layer in self.layers.values()]

        if len(set(n_patches_list)) > 1:
            raise ValueError(
                f"All layers must have same n_patches. Got: "
                f"{dict(zip(self.layers.keys(), n_patches_list))}"
            )

    @property
    def n_patches(self) -> int:
        """Number of spatial patches."""
        if not self.layers:
            return 0
        return next(iter(self.layers.values())).n_patches

    @property
    def n_layers(self) -> int:
        """Number of environmental layers."""
        return len(self.layers)

    @property
    def layer_names(self) -> list:
        """Names of all environmental layers."""
        return list(self.layers.keys())

    def add_layer(self, layer: EnvironmentalLayer):
        """Add environmental layer.

        Parameters
        ----------
        layer : EnvironmentalLayer
            Environmental layer to add

        Raises
        ------
        ValueError
            If layer name already exists or n_patches doesn't match
        """
        if layer.name in self.layers:
            raise ValueError(f"Layer '{layer.name}' already exists")

        # Check n_patches compatibility
        if self.layers and layer.n_patches != self.n_patches:
            raise ValueError(
                f"Layer '{layer.name}' has {layer.n_patches} patches, "
                f"but existing layers have {self.n_patches} patches"
            )

        self.layers[layer.name] = layer

    def remove_layer(self, name: str):
        """Remove environmental layer.

        Parameters
        ----------
        name : str
            Name of layer to remove

        Raises
        ------
        KeyError
            If layer doesn't exist
        """
        if name not in self.layers:
            raise KeyError(f"Layer '{name}' not found")

        del self.layers[name]

    def get_layer_at_time(self, name: str, t: float) -> np.ndarray:
        """Get specific layer values at time t.

        Parameters
        ----------
        name : str
            Layer name
        t : float
            Time (years)

        Returns
        -------
        np.ndarray
            Environmental values [n_patches]
        """
        if name not in self.layers:
            raise KeyError(f"Layer '{name}' not found")

        return self.layers[name].get_value_at_time(t)

    def get_drivers_at_time(
        self, t: float, layer_names: Optional[list] = None
    ) -> np.ndarray:
        """Get all environmental drivers at time t.

        Parameters
        ----------
        t : float
            Time (years)
        layer_names : list, optional
            Specific layers to include (default: all layers)
            Order matters - returned array will match this order

        Returns
        -------
        np.ndarray
            Environmental drivers [n_patches, n_layers]
        """
        if not self.layers:
            return np.array([]).reshape(0, 0)

        # Use all layers if not specified
        if layer_names is None:
            layer_names = self.layer_names

        # Validate layer names
        for name in layer_names:
            if name not in self.layers:
                raise KeyError(f"Layer '{name}' not found")

        # Stack all layers
        drivers = np.column_stack(
            [self.layers[name].get_value_at_time(t) for name in layer_names]
        )

        return drivers

    def get_statistics(self) -> Dict[str, Dict]:
        """Get statistics for all layers.

        Returns
        -------
        dict
            {layer_name: statistics_dict}
        """
        return {name: layer.get_statistics() for name, layer in self.layers.items()}

    def get_time_range(self) -> Tuple[float, float]:
        """Get overall time range across all layers.

        Returns
        -------
        tuple
            (min_time, max_time)
        """
        if not self.layers:
            return (0.0, 0.0)

        min_times = []
        max_times = []

        for layer in self.layers.values():
            if layer.is_time_varying:
                min_times.append(layer.times[0])
                max_times.append(layer.times[-1])

        if not min_times:
            # No time-varying layers
            return (0.0, 0.0)

        return (min(min_times), max(max_times))
layer_names property
layer_names: list

Names of all environmental layers.

n_layers property
n_layers: int

Number of environmental layers.

n_patches property
n_patches: int

Number of spatial patches.

__init__
__init__(layers: Optional[Dict[str, EnvironmentalLayer]] = None)

Initialize environmental drivers.

Source code in pypath/spatial/environmental.py
206
207
208
209
def __init__(self, layers: Optional[Dict[str, EnvironmentalLayer]] = None):
    """Initialize environmental drivers."""
    self.layers = layers if layers is not None else {}
    self._validate_layers()
add_layer
add_layer(layer: EnvironmentalLayer)

Add environmental layer.

Parameters:

Name Type Description Default
layer EnvironmentalLayer

Environmental layer to add

required

Raises:

Type Description
ValueError

If layer name already exists or n_patches doesn't match

Source code in pypath/spatial/environmental.py
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
def add_layer(self, layer: EnvironmentalLayer):
    """Add environmental layer.

    Parameters
    ----------
    layer : EnvironmentalLayer
        Environmental layer to add

    Raises
    ------
    ValueError
        If layer name already exists or n_patches doesn't match
    """
    if layer.name in self.layers:
        raise ValueError(f"Layer '{layer.name}' already exists")

    # Check n_patches compatibility
    if self.layers and layer.n_patches != self.n_patches:
        raise ValueError(
            f"Layer '{layer.name}' has {layer.n_patches} patches, "
            f"but existing layers have {self.n_patches} patches"
        )

    self.layers[layer.name] = layer
get_drivers_at_time
get_drivers_at_time(t: float, layer_names: Optional[list] = None) -> np.ndarray

Get all environmental drivers at time t.

Parameters:

Name Type Description Default
t float

Time (years)

required
layer_names list

Specific layers to include (default: all layers) Order matters - returned array will match this order

None

Returns:

Type Description
ndarray

Environmental drivers [n_patches, n_layers]

Source code in pypath/spatial/environmental.py
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
def get_drivers_at_time(
    self, t: float, layer_names: Optional[list] = None
) -> np.ndarray:
    """Get all environmental drivers at time t.

    Parameters
    ----------
    t : float
        Time (years)
    layer_names : list, optional
        Specific layers to include (default: all layers)
        Order matters - returned array will match this order

    Returns
    -------
    np.ndarray
        Environmental drivers [n_patches, n_layers]
    """
    if not self.layers:
        return np.array([]).reshape(0, 0)

    # Use all layers if not specified
    if layer_names is None:
        layer_names = self.layer_names

    # Validate layer names
    for name in layer_names:
        if name not in self.layers:
            raise KeyError(f"Layer '{name}' not found")

    # Stack all layers
    drivers = np.column_stack(
        [self.layers[name].get_value_at_time(t) for name in layer_names]
    )

    return drivers
get_layer_at_time
get_layer_at_time(name: str, t: float) -> np.ndarray

Get specific layer values at time t.

Parameters:

Name Type Description Default
name str

Layer name

required
t float

Time (years)

required

Returns:

Type Description
ndarray

Environmental values [n_patches]

Source code in pypath/spatial/environmental.py
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
def get_layer_at_time(self, name: str, t: float) -> np.ndarray:
    """Get specific layer values at time t.

    Parameters
    ----------
    name : str
        Layer name
    t : float
        Time (years)

    Returns
    -------
    np.ndarray
        Environmental values [n_patches]
    """
    if name not in self.layers:
        raise KeyError(f"Layer '{name}' not found")

    return self.layers[name].get_value_at_time(t)
get_statistics
get_statistics() -> Dict[str, Dict]

Get statistics for all layers.

Returns:

Type Description
dict

{layer_name: statistics_dict}

Source code in pypath/spatial/environmental.py
341
342
343
344
345
346
347
348
349
def get_statistics(self) -> Dict[str, Dict]:
    """Get statistics for all layers.

    Returns
    -------
    dict
        {layer_name: statistics_dict}
    """
    return {name: layer.get_statistics() for name, layer in self.layers.items()}
get_time_range
get_time_range() -> Tuple[float, float]

Get overall time range across all layers.

Returns:

Type Description
tuple

(min_time, max_time)

Source code in pypath/spatial/environmental.py
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
def get_time_range(self) -> Tuple[float, float]:
    """Get overall time range across all layers.

    Returns
    -------
    tuple
        (min_time, max_time)
    """
    if not self.layers:
        return (0.0, 0.0)

    min_times = []
    max_times = []

    for layer in self.layers.values():
        if layer.is_time_varying:
            min_times.append(layer.times[0])
            max_times.append(layer.times[-1])

    if not min_times:
        # No time-varying layers
        return (0.0, 0.0)

    return (min(min_times), max(max_times))
remove_layer
remove_layer(name: str)

Remove environmental layer.

Parameters:

Name Type Description Default
name str

Name of layer to remove

required

Raises:

Type Description
KeyError

If layer doesn't exist

Source code in pypath/spatial/environmental.py
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
def remove_layer(self, name: str):
    """Remove environmental layer.

    Parameters
    ----------
    name : str
        Name of layer to remove

    Raises
    ------
    KeyError
        If layer doesn't exist
    """
    if name not in self.layers:
        raise KeyError(f"Layer '{name}' not found")

    del self.layers[name]

EnvironmentalLayer dataclass

Time-varying spatial environmental field.

Represents a single environmental variable (temperature, depth, etc.) that varies across patches and potentially over time.

Parameters:

Name Type Description Default
name str

Variable name (e.g., "temperature", "depth", "salinity")

required
units str

Units of measurement (e.g., "celsius", "meters", "psu")

required
values ndarray

Environmental values [n_timesteps, n_patches] or [n_patches] If 1D, assumed constant over time

required
times ndarray

Time points corresponding to values (years) Required if values is 2D

None
interpolate bool

Whether to interpolate between timesteps (default: True)

True
hold bool

Step lookup (default: False): the value at time t is that of the last entry of times at or before t.

False

Examples:

>>> # Constant depth layer
>>> depth = EnvironmentalLayer(
...     name='depth',
...     units='meters',
...     values=np.array([10, 20, 30, 40, 50])
... )
>>> # Time-varying temperature
>>> temp = EnvironmentalLayer(
...     name='temperature',
...     units='celsius',
...     values=np.array([[5, 6, 7], [10, 12, 14], [8, 9, 10]]),
...     times=np.array([0.0, 0.5, 1.0])
... )
>>> temp.get_value_at_time(0.25)  # Interpolates between t=0 and t=0.5
array([7.5, 9., 10.5])
Source code in pypath/spatial/environmental.py
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 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
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
@dataclass
class EnvironmentalLayer:
    """Time-varying spatial environmental field.

    Represents a single environmental variable (temperature, depth, etc.)
    that varies across patches and potentially over time.

    Parameters
    ----------
    name : str
        Variable name (e.g., "temperature", "depth", "salinity")
    units : str
        Units of measurement (e.g., "celsius", "meters", "psu")
    values : np.ndarray
        Environmental values [n_timesteps, n_patches] or [n_patches]
        If 1D, assumed constant over time
    times : np.ndarray, optional
        Time points corresponding to values (years)
        Required if values is 2D
    interpolate : bool
        Whether to interpolate between timesteps (default: True)
    hold : bool
        Step lookup (default: False): the value at time t is that of the
        last entry of ``times`` at or before t.

    Examples
    --------
    >>> # Constant depth layer
    >>> depth = EnvironmentalLayer(
    ...     name='depth',
    ...     units='meters',
    ...     values=np.array([10, 20, 30, 40, 50])
    ... )

    >>> # Time-varying temperature
    >>> temp = EnvironmentalLayer(
    ...     name='temperature',
    ...     units='celsius',
    ...     values=np.array([[5, 6, 7], [10, 12, 14], [8, 9, 10]]),
    ...     times=np.array([0.0, 0.5, 1.0])
    ... )
    >>> temp.get_value_at_time(0.25)  # Interpolates between t=0 and t=0.5
    array([7.5, 9., 10.5])
    """

    name: str
    units: str
    values: np.ndarray
    times: Optional[np.ndarray] = None
    interpolate: bool = True
    # Step lookup: the value at time t is that of the last ``times`` entry at
    # or before t (the first entry before the series starts). For monthly
    # means given at the start of each month: a month's value then holds
    # from k/12 up to (k+1)/12. Takes precedence over ``interpolate``.
    hold: bool = False

    def __post_init__(self):
        """Validate layer after initialization."""
        self.values = np.asarray(self.values, dtype=float)

        # Handle 1D vs 2D values
        if self.values.ndim == 1:
            # Constant over time
            self.n_patches = len(self.values)
            self.n_timesteps = 1
            self.is_time_varying = False

        elif self.values.ndim == 2:
            # Time-varying
            self.n_timesteps, self.n_patches = self.values.shape
            self.is_time_varying = True

            # Require times for time-varying data
            if self.times is None:
                raise ValueError(
                    f"Layer '{self.name}': times required for time-varying values"
                )

            self.times = np.asarray(self.times, dtype=float)

            if len(self.times) != self.n_timesteps:
                raise ValueError(
                    f"Layer '{self.name}': times length ({len(self.times)}) != "
                    f"n_timesteps ({self.n_timesteps})"
                )
        else:
            raise ValueError(
                f"Layer '{self.name}': values must be 1D [n_patches] or 2D [n_timesteps, n_patches], "
                f"got {self.values.ndim}D"
            )

    def get_value_at_time(self, t: float) -> np.ndarray:
        """Get environmental values at time t.

        Parameters
        ----------
        t : float
            Time (years)

        Returns
        -------
        np.ndarray
            Environmental values [n_patches]
        """
        if not self.is_time_varying:
            # Constant over time
            return self.values.copy()

        if self.hold:
            # The last entry at or before t; a hair of tolerance so that a
            # time computed as k / 12 falls in month k
            idx = int(np.searchsorted(self.times, t + 1e-9, side="right")) - 1
            return self.values[max(idx, 0)].copy()

        # Time-varying - interpolate if requested
        if not self.interpolate:
            # Find nearest timestep
            idx = np.argmin(np.abs(self.times - t))
            return self.values[idx].copy()

        # Linear interpolation
        if t <= self.times[0]:
            return self.values[0].copy()

        if t >= self.times[-1]:
            return self.values[-1].copy()

        # Find bracketing timesteps
        idx_after = np.searchsorted(self.times, t)
        idx_before = idx_after - 1

        t_before = self.times[idx_before]
        t_after = self.times[idx_after]

        # Linear interpolation weight
        weight = (t - t_before) / (t_after - t_before)

        return (1 - weight) * self.values[idx_before] + weight * self.values[idx_after]

    def get_statistics(self) -> Dict[str, float]:
        """Get summary statistics for this layer.

        Returns
        -------
        dict
            Statistics: min, max, mean, std
        """
        return {
            "name": self.name,
            "units": self.units,
            "min": float(np.min(self.values)),
            "max": float(np.max(self.values)),
            "mean": float(np.mean(self.values)),
            "std": float(np.std(self.values)),
            "n_patches": self.n_patches,
            "n_timesteps": self.n_timesteps,
            "is_time_varying": self.is_time_varying,
        }
__post_init__
__post_init__()

Validate layer after initialization.

Source code in pypath/spatial/environmental.py
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
def __post_init__(self):
    """Validate layer after initialization."""
    self.values = np.asarray(self.values, dtype=float)

    # Handle 1D vs 2D values
    if self.values.ndim == 1:
        # Constant over time
        self.n_patches = len(self.values)
        self.n_timesteps = 1
        self.is_time_varying = False

    elif self.values.ndim == 2:
        # Time-varying
        self.n_timesteps, self.n_patches = self.values.shape
        self.is_time_varying = True

        # Require times for time-varying data
        if self.times is None:
            raise ValueError(
                f"Layer '{self.name}': times required for time-varying values"
            )

        self.times = np.asarray(self.times, dtype=float)

        if len(self.times) != self.n_timesteps:
            raise ValueError(
                f"Layer '{self.name}': times length ({len(self.times)}) != "
                f"n_timesteps ({self.n_timesteps})"
            )
    else:
        raise ValueError(
            f"Layer '{self.name}': values must be 1D [n_patches] or 2D [n_timesteps, n_patches], "
            f"got {self.values.ndim}D"
        )
get_statistics
get_statistics() -> Dict[str, float]

Get summary statistics for this layer.

Returns:

Type Description
dict

Statistics: min, max, mean, std

Source code in pypath/spatial/environmental.py
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
def get_statistics(self) -> Dict[str, float]:
    """Get summary statistics for this layer.

    Returns
    -------
    dict
        Statistics: min, max, mean, std
    """
    return {
        "name": self.name,
        "units": self.units,
        "min": float(np.min(self.values)),
        "max": float(np.max(self.values)),
        "mean": float(np.mean(self.values)),
        "std": float(np.std(self.values)),
        "n_patches": self.n_patches,
        "n_timesteps": self.n_timesteps,
        "is_time_varying": self.is_time_varying,
    }
get_value_at_time
get_value_at_time(t: float) -> np.ndarray

Get environmental values at time t.

Parameters:

Name Type Description Default
t float

Time (years)

required

Returns:

Type Description
ndarray

Environmental values [n_patches]

Source code in pypath/spatial/environmental.py
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
def get_value_at_time(self, t: float) -> np.ndarray:
    """Get environmental values at time t.

    Parameters
    ----------
    t : float
        Time (years)

    Returns
    -------
    np.ndarray
        Environmental values [n_patches]
    """
    if not self.is_time_varying:
        # Constant over time
        return self.values.copy()

    if self.hold:
        # The last entry at or before t; a hair of tolerance so that a
        # time computed as k / 12 falls in month k
        idx = int(np.searchsorted(self.times, t + 1e-9, side="right")) - 1
        return self.values[max(idx, 0)].copy()

    # Time-varying - interpolate if requested
    if not self.interpolate:
        # Find nearest timestep
        idx = np.argmin(np.abs(self.times - t))
        return self.values[idx].copy()

    # Linear interpolation
    if t <= self.times[0]:
        return self.values[0].copy()

    if t >= self.times[-1]:
        return self.values[-1].copy()

    # Find bracketing timesteps
    idx_after = np.searchsorted(self.times, t)
    idx_before = idx_after - 1

    t_before = self.times[idx_before]
    t_after = self.times[idx_after]

    # Linear interpolation weight
    weight = (t - t_before) / (t_after - t_before)

    return (1 - weight) * self.values[idx_before] + weight * self.values[idx_after]

create_constant_layer

create_constant_layer(name: str, values: ndarray, units: str = '') -> EnvironmentalLayer

Create constant (time-invariant) environmental layer.

Parameters:

Name Type Description Default
name str

Layer name (e.g., "depth", "slope")

required
values ndarray

Environmental values [n_patches]

required
units str

Units of measurement

''

Returns:

Type Description
EnvironmentalLayer
Source code in pypath/spatial/environmental.py
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
def create_constant_layer(
    name: str, values: np.ndarray, units: str = ""
) -> EnvironmentalLayer:
    """Create constant (time-invariant) environmental layer.

    Parameters
    ----------
    name : str
        Layer name (e.g., "depth", "slope")
    values : np.ndarray
        Environmental values [n_patches]
    units : str
        Units of measurement

    Returns
    -------
    EnvironmentalLayer
    """
    return EnvironmentalLayer(
        name=name,
        units=units,
        values=np.asarray(values, dtype=float),
        times=None,
        interpolate=False,
    )

create_seasonal_temperature

create_seasonal_temperature(baseline_temp: ndarray, amplitude: float = 10.0, n_months: int = 12) -> EnvironmentalLayer

Create seasonal temperature variation.

Temperature follows sinusoidal pattern: T(month) = baseline + amplitude * sin(2π * month / 12)

Parameters:

Name Type Description Default
baseline_temp ndarray

Baseline temperature for each patch [n_patches]

required
amplitude float

Seasonal amplitude (default: 10°C)

10.0
n_months int

Number of monthly timesteps (default: 12)

12

Returns:

Type Description
EnvironmentalLayer

Time-varying temperature layer

Examples:

>>> baseline = np.array([15, 18, 20])  # Baseline temps
>>> temp = create_seasonal_temperature(baseline, amplitude=8.0)
>>> # Winter (t=0): ~7-12°C
>>> # Summer (t=0.5): ~23-28°C
Source code in pypath/spatial/environmental.py
377
378
379
380
381
382
383
384
385
386
387
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
def create_seasonal_temperature(
    baseline_temp: np.ndarray, amplitude: float = 10.0, n_months: int = 12
) -> EnvironmentalLayer:
    """Create seasonal temperature variation.

    Temperature follows sinusoidal pattern:
        T(month) = baseline + amplitude * sin(2π * month / 12)

    Parameters
    ----------
    baseline_temp : np.ndarray
        Baseline temperature for each patch [n_patches]
    amplitude : float
        Seasonal amplitude (default: 10°C)
    n_months : int
        Number of monthly timesteps (default: 12)

    Returns
    -------
    EnvironmentalLayer
        Time-varying temperature layer

    Examples
    --------
    >>> baseline = np.array([15, 18, 20])  # Baseline temps
    >>> temp = create_seasonal_temperature(baseline, amplitude=8.0)
    >>> # Winter (t=0): ~7-12°C
    >>> # Summer (t=0.5): ~23-28°C
    """
    baseline_temp = np.asarray(baseline_temp, dtype=float)
    _n_patches = len(baseline_temp)

    times = np.arange(n_months) / 12.0  # Monthly timesteps in years

    # Seasonal pattern (peak in summer, month 6)
    seasonal = amplitude * np.sin(2 * np.pi * (times - 0.25))

    # Apply to each patch
    values = baseline_temp[np.newaxis, :] + seasonal[:, np.newaxis]

    return EnvironmentalLayer(
        name="temperature",
        units="celsius",
        values=values,
        times=times,
        interpolate=True,
    )

External Flux

Boundary conditions for open systems: immigration, emigration, and nutrient loading at grid edges.

pypath.spatial.external_flux

External flux loading and validation.

Functions for loading flux timeseries from: - NetCDF files (ocean models: ROMS, MITgcm, HYCOM) - CSV files (connectivity matrices, telemetry data) - Numpy arrays (pre-computed flux)

convert_connectivity_to_flux

convert_connectivity_to_flux(connectivity_matrix: ndarray, biomass: ndarray) -> np.ndarray

Convert connectivity matrix to flux matrix.

Connectivity represents proportions (0-1), while flux represents actual biomass movement.

Parameters:

Name Type Description Default
connectivity_matrix ndarray

Connectivity proportions [n_patches, n_patches] connectivity[i, j] = fraction of biomass in i that moves to j

required
biomass ndarray

Biomass in each patch [n_patches]

required

Returns:

Type Description
ndarray

Flux matrix [n_patches, n_patches] flux[i, j] = biomass moving from i to j

Source code in pypath/spatial/external_flux.py
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 convert_connectivity_to_flux(
    connectivity_matrix: np.ndarray, biomass: np.ndarray
) -> np.ndarray:
    """Convert connectivity matrix to flux matrix.

    Connectivity represents proportions (0-1), while flux represents
    actual biomass movement.

    Parameters
    ----------
    connectivity_matrix : np.ndarray
        Connectivity proportions [n_patches, n_patches]
        connectivity[i, j] = fraction of biomass in i that moves to j
    biomass : np.ndarray
        Biomass in each patch [n_patches]

    Returns
    -------
    np.ndarray
        Flux matrix [n_patches, n_patches]
        flux[i, j] = biomass moving from i to j
    """
    flux_matrix = connectivity_matrix * biomass[:, np.newaxis]
    np.fill_diagonal(flux_matrix, 0.0)
    return flux_matrix

create_flux_from_connectivity_matrix

create_flux_from_connectivity_matrix(connectivity_matrix: ndarray, times: Optional[ndarray] = None, seasonal_pattern: Optional[ndarray] = None) -> 'ExternalFluxTimeseries'

Create flux timeseries from connectivity matrix.

Connectivity matrix represents proportion of individuals/biomass moving from patch i to patch j per timestep.

Parameters:

Name Type Description Default
connectivity_matrix ndarray

Connectivity matrix [n_patches, n_patches] connectivity[i, j] = proportion moving from i to j

required
times ndarray

Time points (years). If None, uses monthly for 1 year

None
seasonal_pattern ndarray

Seasonal variation in connectivity strength [n_timesteps] If None, assumes constant connectivity

None

Returns:

Type Description
ExternalFluxTimeseries
Source code in pypath/spatial/external_flux.py
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
def create_flux_from_connectivity_matrix(
    connectivity_matrix: np.ndarray,
    times: Optional[np.ndarray] = None,
    seasonal_pattern: Optional[np.ndarray] = None,
) -> "ExternalFluxTimeseries":
    """Create flux timeseries from connectivity matrix.

    Connectivity matrix represents proportion of individuals/biomass
    moving from patch i to patch j per timestep.

    Parameters
    ----------
    connectivity_matrix : np.ndarray
        Connectivity matrix [n_patches, n_patches]
        connectivity[i, j] = proportion moving from i to j
    times : np.ndarray, optional
        Time points (years). If None, uses monthly for 1 year
    seasonal_pattern : np.ndarray, optional
        Seasonal variation in connectivity strength [n_timesteps]
        If None, assumes constant connectivity

    Returns
    -------
    ExternalFluxTimeseries
    """
    from pypath.spatial.ecospace_params import ExternalFluxTimeseries

    n_patches = connectivity_matrix.shape[0]

    # Validate connectivity matrix
    if connectivity_matrix.shape != (n_patches, n_patches):
        raise ValueError(
            f"Connectivity matrix must be square, got {connectivity_matrix.shape}"
        )

    # Default times: monthly for 1 year
    if times is None:
        n_timesteps = 12
        times = np.arange(n_timesteps) / 12.0
    else:
        n_timesteps = len(times)

    # Default seasonal pattern: constant
    if seasonal_pattern is None:
        seasonal_pattern = np.ones(n_timesteps)
    elif len(seasonal_pattern) != n_timesteps:
        raise ValueError(
            f"seasonal_pattern length ({len(seasonal_pattern)}) != n_timesteps ({n_timesteps})"
        )

    # Create flux timeseries
    flux_data = np.zeros((n_timesteps, 1, n_patches, n_patches))

    for t_idx in range(n_timesteps):
        flux_data[t_idx, 0] = connectivity_matrix * seasonal_pattern[t_idx]

    return ExternalFluxTimeseries(
        flux_data=flux_data,
        times=times,
        group_indices=np.array([0]),
        interpolate=True,
        format="connectivity_matrix",
    )

load_external_flux_from_csv

load_external_flux_from_csv(filepath: str, n_patches: int, time_column: str = 'time', patch_from_column: str = 'from', patch_to_column: str = 'to', flux_column: str = 'flux') -> 'ExternalFluxTimeseries'

Load external flux from CSV file.

CSV format (edge list): time, from, to, flux 0.0, 0, 1, 0.5 0.0, 1, 2, 0.3 ...

Parameters:

Name Type Description Default
filepath str

Path to CSV file

required
n_patches int

Number of patches in grid

required
time_column str

Name of time column

'time'
patch_from_column str

Name of source patch column

'from'
patch_to_column str

Name of destination patch column

'to'
flux_column str

Name of flux value column

'flux'

Returns:

Type Description
ExternalFluxTimeseries
Source code in pypath/spatial/external_flux.py
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
def load_external_flux_from_csv(
    filepath: str,
    n_patches: int,
    time_column: str = "time",
    patch_from_column: str = "from",
    patch_to_column: str = "to",
    flux_column: str = "flux",
) -> "ExternalFluxTimeseries":
    """Load external flux from CSV file.

    CSV format (edge list):
        time, from, to, flux
        0.0, 0, 1, 0.5
        0.0, 1, 2, 0.3
        ...

    Parameters
    ----------
    filepath : str
        Path to CSV file
    n_patches : int
        Number of patches in grid
    time_column : str
        Name of time column
    patch_from_column : str
        Name of source patch column
    patch_to_column : str
        Name of destination patch column
    flux_column : str
        Name of flux value column

    Returns
    -------
    ExternalFluxTimeseries
    """
    import pandas as pd

    from pypath.spatial.ecospace_params import ExternalFluxTimeseries

    # Load CSV
    df = pd.read_csv(filepath)

    # Check for required columns
    required = [time_column, patch_from_column, patch_to_column, flux_column]
    missing = [col for col in required if col not in df.columns]
    if missing:
        raise ValueError(f"Missing columns: {missing}. Available: {list(df.columns)}")

    # Get unique times
    times = np.sort(df[time_column].unique())
    n_timesteps = len(times)

    # Initialize flux array (assume single group for CSV)
    flux_data = np.zeros((n_timesteps, 1, n_patches, n_patches))

    # Fill flux matrix for each timestep
    for t_idx, t in enumerate(times):
        df_t = df[df[time_column] == t]

        for _, row in df_t.iterrows():
            i = int(row[patch_from_column])
            j = int(row[patch_to_column])
            flux_val = float(row[flux_column])

            flux_data[t_idx, 0, i, j] = flux_val

    return ExternalFluxTimeseries(
        flux_data=flux_data,
        times=times,
        group_indices=np.array([0]),  # Single group
        interpolate=True,
        format="flux_matrix",
    )

load_external_flux_from_netcdf

load_external_flux_from_netcdf(filepath: str, time_var: str = 'time', flux_var: str = 'flux', group_mapping: Optional[Dict[str, int]] = None) -> 'ExternalFluxTimeseries'

Load external flux from NetCDF file.

Typical NetCDF structure from ocean models: dimensions: time = n_timesteps group = n_groups (or species) patch_from = n_patches patch_to = n_patches

variables:
    float time(time)  # Time in years or days
    float flux(time, group, patch_from, patch_to)

Parameters:

Name Type Description Default
filepath str

Path to NetCDF file

required
time_var str

Name of time dimension/variable (default: "time")

'time'
flux_var str

Name of flux variable (default: "flux") Expected shape: [time, group, patch_from, patch_to]

'flux'
group_mapping dict

Map from species names to group indices Example: {'cod': 3, 'herring': 5} If None, uses sequential indices

None

Returns:

Type Description
ExternalFluxTimeseries

Raises:

Type Description
ImportError

If netCDF4/xarray not installed

FileNotFoundError

If filepath does not exist

ValueError

If required variables not found

Source code in pypath/spatial/external_flux.py
 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
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
def load_external_flux_from_netcdf(
    filepath: str,
    time_var: str = "time",
    flux_var: str = "flux",
    group_mapping: Optional[Dict[str, int]] = None,
) -> "ExternalFluxTimeseries":
    """Load external flux from NetCDF file.

    Typical NetCDF structure from ocean models:
        dimensions:
            time = n_timesteps
            group = n_groups (or species)
            patch_from = n_patches
            patch_to = n_patches

        variables:
            float time(time)  # Time in years or days
            float flux(time, group, patch_from, patch_to)

    Parameters
    ----------
    filepath : str
        Path to NetCDF file
    time_var : str
        Name of time dimension/variable (default: "time")
    flux_var : str
        Name of flux variable (default: "flux")
        Expected shape: [time, group, patch_from, patch_to]
    group_mapping : dict, optional
        Map from species names to group indices
        Example: {'cod': 3, 'herring': 5}
        If None, uses sequential indices

    Returns
    -------
    ExternalFluxTimeseries

    Raises
    ------
    ImportError
        If netCDF4/xarray not installed
    FileNotFoundError
        If filepath does not exist
    ValueError
        If required variables not found
    """
    if not _NETCDF_AVAILABLE:
        raise ImportError(
            "netCDF4 and xarray required for NetCDF support. "
            "Install with: pip install netCDF4 xarray"
        )

    from pypath.spatial.ecospace_params import ExternalFluxTimeseries

    # Load NetCDF using xarray
    with xr.open_dataset(filepath) as ds:
        # Check for required variables
        if time_var not in ds:
            raise ValueError(
                f"Time variable '{time_var}' not found in NetCDF. Available: {list(ds.variables)}"
            )

        if flux_var not in ds:
            raise ValueError(
                f"Flux variable '{flux_var}' not found in NetCDF. Available: {list(ds.variables)}"
            )

        # Load time
        times = ds[time_var].values

        # Convert time to years if needed
        if hasattr(ds[time_var], "units"):
            units = ds[time_var].units
            if "days" in units.lower():
                times = times / 365.25
            elif "months" in units.lower():
                times = times / 12.0

        # Load flux data
        flux_data = ds[flux_var].values

        # Validate dimensions
        if flux_data.ndim != 4:
            raise ValueError(
                f"Flux variable must be 4D [time, group, patch_from, patch_to], "
                f"got {flux_data.ndim}D with shape {flux_data.shape}"
            )

        n_timesteps, n_groups, n_patches_from, n_patches_to = flux_data.shape

        if n_patches_from != n_patches_to:
            raise ValueError(
                f"Flux matrix must be square [patch_from, patch_to], "
                f"got {n_patches_from} x {n_patches_to}"
            )

        # Determine group indices
        if group_mapping is not None:
            # Use provided mapping
            group_indices = np.array(list(group_mapping.values()))
        else:
            # Sequential indices
            group_indices = np.arange(n_groups)

    return ExternalFluxTimeseries(
        flux_data=flux_data,
        times=times,
        group_indices=group_indices,
        interpolate=True,
        format="flux_matrix",
    )

rescale_flux_for_conservation

rescale_flux_for_conservation(flux_matrix: ndarray) -> np.ndarray

Rescale flux matrix to enforce mass conservation.

Normalizes each row so that total outflow fraction does not exceed 1.0 (i.e., a patch cannot export more than 100% of its biomass per step). Rows whose outflow sums to <= 1.0 are left unchanged.

Parameters:

Name Type Description Default
flux_matrix ndarray

Flux matrix [n_patches, n_patches] flux_matrix[i, j] = fraction of biomass in patch i moving to patch j.

required

Returns:

Type Description
ndarray

Rescaled flux matrix where no row sums to more than 1.0.

Source code in pypath/spatial/external_flux.py
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
def rescale_flux_for_conservation(flux_matrix: np.ndarray) -> np.ndarray:
    """Rescale flux matrix to enforce mass conservation.

    Normalizes each row so that total outflow fraction does not exceed 1.0
    (i.e., a patch cannot export more than 100% of its biomass per step).
    Rows whose outflow sums to <= 1.0 are left unchanged.

    Parameters
    ----------
    flux_matrix : np.ndarray
        Flux matrix [n_patches, n_patches]
        flux_matrix[i, j] = fraction of biomass in patch i moving to patch j.

    Returns
    -------
    np.ndarray
        Rescaled flux matrix where no row sums to more than 1.0.
    """
    result = flux_matrix.copy()
    for i in range(result.shape[0]):
        row_sum = result[i, :].sum()
        if row_sum > 1.0:
            logger.warning("Row %d outflow fraction %.4f > 1.0, rescaling", i, row_sum)
            result[i, :] /= row_sum
    return result

summarize_external_flux

summarize_external_flux(external_flux: 'ExternalFluxTimeseries') -> Dict

Summarize external flux timeseries.

Parameters:

Name Type Description Default
external_flux ExternalFluxTimeseries

External flux data

required

Returns:

Type Description
dict

Summary statistics: - 'n_timesteps': Number of time points - 'time_range': (min_time, max_time) - 'n_groups': Number of groups with external flux - 'n_patches': Number of patches - 'mean_flux': Mean flux value - 'max_flux': Maximum flux value - 'is_conserved': Whether flux conserves mass

Source code in pypath/spatial/external_flux.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
def summarize_external_flux(external_flux: "ExternalFluxTimeseries") -> Dict:
    """Summarize external flux timeseries.

    Parameters
    ----------
    external_flux : ExternalFluxTimeseries
        External flux data

    Returns
    -------
    dict
        Summary statistics:
        - 'n_timesteps': Number of time points
        - 'time_range': (min_time, max_time)
        - 'n_groups': Number of groups with external flux
        - 'n_patches': Number of patches
        - 'mean_flux': Mean flux value
        - 'max_flux': Maximum flux value
        - 'is_conserved': Whether flux conserves mass
    """
    flux_data = external_flux.flux_data

    # Check conservation for first timestep
    is_conserved = validate_external_flux_conservation(flux_data[0, 0])

    summary = {
        "n_timesteps": len(external_flux.times),
        "time_range": (external_flux.times[0], external_flux.times[-1]),
        "n_groups": len(external_flux.group_indices),
        "n_patches": flux_data.shape[2],
        "mean_flux": float(np.mean(np.abs(flux_data))),
        "max_flux": float(np.max(np.abs(flux_data))),
        "is_conserved": is_conserved,
        "interpolate": external_flux.interpolate,
        "format": external_flux.format,
    }

    return summary

validate_external_flux_conservation

validate_external_flux_conservation(flux_matrix: ndarray, tolerance: float = 1e-10) -> bool

Validate that external flux conserves mass.

Sum over all patches: inflow - outflow should be 0 (within numerical tolerance).

Parameters:

Name Type Description Default
flux_matrix ndarray

Flux matrix [n_patches, n_patches] flux_matrix[i, j] = flux from patch i to patch j

required
tolerance float

Numerical tolerance for zero

1e-10

Returns:

Type Description
bool

True if flux is conserved

Notes

For mass conservation: Σ_i Σ_j flux[i, j] = Σ_j Σ_i flux[i, j] (total outflow = total inflow)

Equivalently: Σ_i (Σ_j flux[i, j] - Σ_j flux[j, i]) = 0

Source code in pypath/spatial/external_flux.py
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
def validate_external_flux_conservation(
    flux_matrix: np.ndarray, tolerance: float = 1e-10
) -> bool:
    """Validate that external flux conserves mass.

    Sum over all patches: inflow - outflow should be 0
    (within numerical tolerance).

    Parameters
    ----------
    flux_matrix : np.ndarray
        Flux matrix [n_patches, n_patches]
        flux_matrix[i, j] = flux from patch i to patch j
    tolerance : float
        Numerical tolerance for zero

    Returns
    -------
    bool
        True if flux is conserved

    Notes
    -----
    For mass conservation:
        Σ_i Σ_j flux[i, j] = Σ_j Σ_i flux[i, j]
        (total outflow = total inflow)

    Equivalently:
        Σ_i (Σ_j flux[i, j] - Σ_j flux[j, i]) = 0
    """
    # Calculate net flux for each patch
    if scipy.sparse.issparse(flux_matrix):
        inflow = np.array(flux_matrix.sum(axis=0)).flatten()
        outflow = np.array(flux_matrix.sum(axis=1)).flatten()
    else:
        inflow = flux_matrix.sum(axis=0)
        outflow = flux_matrix.sum(axis=1)

    net_flux = inflow - outflow

    # Total imbalance
    total_imbalance = np.abs(net_flux).sum()

    return total_imbalance < tolerance

Spatial Fishing

Spatially explicit fishing effort and catch allocation across patches.

pypath.spatial.fishing

Spatial fishing effort allocation for ECOSPACE.

Implements spatially-explicit fishing with multiple allocation strategies: - Uniform: Equal effort across all patches - Gravity: Biomass-weighted effort (fish where fish are) - Port-based: Distance from fishing ports - Prescribed: User-defined spatial patterns - Habitat-based: Target preferred habitats

FleetDeployment dataclass

Spatial fleet deployment plan.

Source code in pypath/spatial/fishing.py
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
@dataclass
class FleetDeployment:
    """Spatial fleet deployment plan."""

    fleet_name: str
    home_ports: np.ndarray
    max_range_km: float
    capacity: float

    def accessibility_weights(self, distance_to_port_km: np.ndarray) -> np.ndarray:
        """Compute accessibility weights by distance to nearest port."""
        dist = np.asarray(distance_to_port_km, dtype=float)
        weights = np.exp(-dist / max(self.max_range_km, 1e-9))
        weights[dist > self.max_range_km] = 0.0
        return weights
accessibility_weights
accessibility_weights(distance_to_port_km: ndarray) -> np.ndarray

Compute accessibility weights by distance to nearest port.

Source code in pypath/spatial/fishing.py
656
657
658
659
660
661
def accessibility_weights(self, distance_to_port_km: np.ndarray) -> np.ndarray:
    """Compute accessibility weights by distance to nearest port."""
    dist = np.asarray(distance_to_port_km, dtype=float)
    weights = np.exp(-dist / max(self.max_range_km, 1e-9))
    weights[dist > self.max_range_km] = 0.0
    return weights

SpatialFishing dataclass

Spatial fishing effort allocation.

Represents how fishing effort is distributed across spatial patches.

Parameters:

Name Type Description Default
allocation_type str

Method for allocating effort: - "uniform": Equal across patches - "gravity": Biomass-weighted (alpha, beta parameters) - "port": Distance from ports (beta parameter) - "prescribed": User-defined pattern - "habitat": Target specific habitat types

'uniform'
effort_allocation ndarray

Pre-computed effort distribution [n_months, n_gears, n_patches] Normalized so sum over patches = ForcedEffort[month, gear]

None
gravity_alpha float

Biomass attraction exponent (default: 1.0) Higher = stronger attraction to high biomass

1.0
gravity_beta float

Distance penalty exponent (default: 0.5) Higher = stronger distance penalty from ports

0.5
port_patches ndarray

Indices of patches containing ports

None
target_groups List[int]

Group indices to target for gravity allocation

None
custom_allocation_function Callable

Custom function(biomass, t, params) -> allocation [n_patches]

None

Examples:

>>> # Uniform allocation
>>> fishing = SpatialFishing(allocation_type="uniform")
>>> # Gravity model (fish where fish are)
>>> fishing = SpatialFishing(
...     allocation_type="gravity",
...     gravity_alpha=1.5,  # Strong biomass attraction
...     target_groups=[3, 5, 7]  # Target specific species
... )
>>> # Port-based (effort decreases with distance)
>>> fishing = SpatialFishing(
...     allocation_type="port",
...     port_patches=np.array([0, 5, 10]),  # Three ports
...     gravity_beta=1.0  # Distance penalty
... )
Source code in pypath/spatial/fishing.py
 26
 27
 28
 29
 30
 31
 32
 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
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
@dataclass
class SpatialFishing:
    """Spatial fishing effort allocation.

    Represents how fishing effort is distributed across spatial patches.

    Parameters
    ----------
    allocation_type : str
        Method for allocating effort:
        - "uniform": Equal across patches
        - "gravity": Biomass-weighted (alpha, beta parameters)
        - "port": Distance from ports (beta parameter)
        - "prescribed": User-defined pattern
        - "habitat": Target specific habitat types
    effort_allocation : np.ndarray, optional
        Pre-computed effort distribution [n_months, n_gears, n_patches]
        Normalized so sum over patches = ForcedEffort[month, gear]
    gravity_alpha : float
        Biomass attraction exponent (default: 1.0)
        Higher = stronger attraction to high biomass
    gravity_beta : float
        Distance penalty exponent (default: 0.5)
        Higher = stronger distance penalty from ports
    port_patches : np.ndarray, optional
        Indices of patches containing ports
    target_groups : List[int], optional
        Group indices to target for gravity allocation
    custom_allocation_function : Callable, optional
        Custom function(biomass, t, params) -> allocation [n_patches]

    Examples
    --------
    >>> # Uniform allocation
    >>> fishing = SpatialFishing(allocation_type="uniform")

    >>> # Gravity model (fish where fish are)
    >>> fishing = SpatialFishing(
    ...     allocation_type="gravity",
    ...     gravity_alpha=1.5,  # Strong biomass attraction
    ...     target_groups=[3, 5, 7]  # Target specific species
    ... )

    >>> # Port-based (effort decreases with distance)
    >>> fishing = SpatialFishing(
    ...     allocation_type="port",
    ...     port_patches=np.array([0, 5, 10]),  # Three ports
    ...     gravity_beta=1.0  # Distance penalty
    ... )
    """

    allocation_type: str = "uniform"
    effort_allocation: Optional[np.ndarray] = None
    gravity_alpha: float = 1.0
    gravity_beta: float = 0.5
    port_patches: Optional[np.ndarray] = None
    target_groups: Optional[List[int]] = None
    custom_allocation_function: Optional[Callable] = None

    def __post_init__(self):
        """Validate parameters after initialization."""
        valid_types = ["uniform", "gravity", "port", "prescribed", "habitat", "custom"]
        if self.allocation_type not in valid_types:
            raise ValueError(
                f"allocation_type must be one of {valid_types}, got '{self.allocation_type}'"
            )

        if self.allocation_type == "prescribed" and self.effort_allocation is None:
            raise ValueError(
                "allocation_type='prescribed' requires effort_allocation array"
            )

        if self.allocation_type == "custom" and self.custom_allocation_function is None:
            raise ValueError(
                "allocation_type='custom' requires custom_allocation_function"
            )

        if self.port_patches is not None:
            self.port_patches = np.asarray(self.port_patches, dtype=int)
__post_init__
__post_init__()

Validate parameters after initialization.

Source code in pypath/spatial/fishing.py
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
def __post_init__(self):
    """Validate parameters after initialization."""
    valid_types = ["uniform", "gravity", "port", "prescribed", "habitat", "custom"]
    if self.allocation_type not in valid_types:
        raise ValueError(
            f"allocation_type must be one of {valid_types}, got '{self.allocation_type}'"
        )

    if self.allocation_type == "prescribed" and self.effort_allocation is None:
        raise ValueError(
            "allocation_type='prescribed' requires effort_allocation array"
        )

    if self.allocation_type == "custom" and self.custom_allocation_function is None:
        raise ValueError(
            "allocation_type='custom' requires custom_allocation_function"
        )

    if self.port_patches is not None:
        self.port_patches = np.asarray(self.port_patches, dtype=int)

allocate_gravity

allocate_gravity(biomass: ndarray, target_groups: Optional[List[int]], total_effort: float, alpha: float = 1.0, beta: float = 0.0, port_patches: Optional[ndarray] = None, grid: Optional['EcospaceGrid'] = None) -> np.ndarray

Allocate effort using gravity model (biomass attraction + distance penalty).

Effort follows: effort[p] ∝ (Σ_g biomass[g, p]^alpha) / distance[port, p]^beta

where g ∈ target_groups, and distance is from nearest port.

Parameters:

Name Type Description Default
biomass ndarray

Biomass by group and patch [n_groups+1, n_patches]

required
target_groups list of int

Group indices to target (if None, use all groups)

required
total_effort float

Total effort to allocate

required
alpha float

Biomass attraction exponent (default: 1.0) - 0 = ignore biomass (random) - 1 = proportional to biomass - >1 = concentrate on high biomass

1.0
beta float

Distance penalty exponent (default: 0.0) - 0 = ignore distance - >0 = avoid distant patches

0.0
port_patches ndarray

Indices of patches with ports If None, assumes uniform accessibility

None
grid EcospaceGrid

Spatial grid (required if beta > 0)

None

Returns:

Type Description
ndarray

Effort per patch [n_patches], sums to total_effort

Examples:

>>> biomass = np.array([[0, 0, 0], [10, 20, 5]])  # 1 group, 3 patches
>>> allocate_gravity(biomass, target_groups=[1], total_effort=100, alpha=1.0)
array([28.57142857, 57.14285714, 14.28571429])  # Proportional to biomass
Source code in pypath/spatial/fishing.py
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
def allocate_gravity(
    biomass: np.ndarray,
    target_groups: Optional[List[int]],
    total_effort: float,
    alpha: float = 1.0,
    beta: float = 0.0,
    port_patches: Optional[np.ndarray] = None,
    grid: Optional["EcospaceGrid"] = None,
) -> np.ndarray:
    """Allocate effort using gravity model (biomass attraction + distance penalty).

    Effort follows:
        effort[p] ∝ (Σ_g biomass[g, p]^alpha) / distance[port, p]^beta

    where g ∈ target_groups, and distance is from nearest port.

    Parameters
    ----------
    biomass : np.ndarray
        Biomass by group and patch [n_groups+1, n_patches]
    target_groups : list of int, optional
        Group indices to target (if None, use all groups)
    total_effort : float
        Total effort to allocate
    alpha : float
        Biomass attraction exponent (default: 1.0)
        - 0 = ignore biomass (random)
        - 1 = proportional to biomass
        - >1 = concentrate on high biomass
    beta : float
        Distance penalty exponent (default: 0.0)
        - 0 = ignore distance
        - >0 = avoid distant patches
    port_patches : np.ndarray, optional
        Indices of patches with ports
        If None, assumes uniform accessibility
    grid : EcospaceGrid, optional
        Spatial grid (required if beta > 0)

    Returns
    -------
    np.ndarray
        Effort per patch [n_patches], sums to total_effort

    Examples
    --------
    >>> biomass = np.array([[0, 0, 0], [10, 20, 5]])  # 1 group, 3 patches
    >>> allocate_gravity(biomass, target_groups=[1], total_effort=100, alpha=1.0)
    array([28.57142857, 57.14285714, 14.28571429])  # Proportional to biomass
    """
    n_groups, n_patches = biomass.shape

    # Determine target groups
    if target_groups is None:
        target_groups = list(range(1, n_groups))  # Skip index 0 (Outside)

    # Calculate attractiveness (biomass-based)
    attractiveness = np.zeros(n_patches)

    for g in target_groups:
        if g < n_groups:
            attractiveness += biomass[g] ** alpha

    # Apply distance penalty if ports specified
    if beta > 0 and port_patches is not None and grid is not None:
        distance_penalty = calculate_distance_penalty(grid, port_patches, beta)
        attractiveness = attractiveness / (distance_penalty + 1e-10)

    # Normalize to total effort
    total_attractiveness = attractiveness.sum()

    if total_attractiveness < 1e-10:
        # No biomass - fall back to uniform
        return allocate_uniform(n_patches, total_effort)

    effort = attractiveness * (total_effort / total_attractiveness)

    return effort

allocate_habitat_based

allocate_habitat_based(habitat_preference: ndarray, total_effort: float, threshold: float = 0.5) -> np.ndarray

Allocate effort based on habitat preference.

Targets patches with high habitat quality for target species.

Parameters:

Name Type Description Default
habitat_preference ndarray

Habitat preference values [n_patches] Values in [0, 1]

required
total_effort float

Total effort to allocate

required
threshold float

Minimum habitat preference to fish (default: 0.5) Patches below this get zero effort

0.5

Returns:

Type Description
ndarray

Effort per patch [n_patches], sums to total_effort

Examples:

>>> habitat = np.array([0.2, 0.6, 0.8, 0.4, 0.9])
>>> allocate_habitat_based(habitat, total_effort=100, threshold=0.5)
array([ 0., 26.08695652, 34.78260870,  0., 39.13043478])
# Only patches with preference > 0.5 get effort
Source code in pypath/spatial/fishing.py
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
def allocate_habitat_based(
    habitat_preference: np.ndarray, total_effort: float, threshold: float = 0.5
) -> np.ndarray:
    """Allocate effort based on habitat preference.

    Targets patches with high habitat quality for target species.

    Parameters
    ----------
    habitat_preference : np.ndarray
        Habitat preference values [n_patches]
        Values in [0, 1]
    total_effort : float
        Total effort to allocate
    threshold : float
        Minimum habitat preference to fish (default: 0.5)
        Patches below this get zero effort

    Returns
    -------
    np.ndarray
        Effort per patch [n_patches], sums to total_effort

    Examples
    --------
    >>> habitat = np.array([0.2, 0.6, 0.8, 0.4, 0.9])
    >>> allocate_habitat_based(habitat, total_effort=100, threshold=0.5)
    array([ 0., 26.08695652, 34.78260870,  0., 39.13043478])
    # Only patches with preference > 0.5 get effort
    """
    habitat_preference = np.asarray(habitat_preference, dtype=float)

    # Apply threshold
    effort = habitat_preference.copy()
    effort[effort < threshold] = 0.0

    # Normalize
    total_pref = effort.sum()

    if total_pref < 1e-10:
        # No suitable habitat - fall back to uniform
        return allocate_uniform(len(habitat_preference), total_effort)

    effort = effort * (total_effort / total_pref)

    return effort

allocate_port_based

allocate_port_based(grid: 'EcospaceGrid', port_patches: ndarray, total_effort: float, beta: float = 1.0, max_distance: Optional[float] = None) -> np.ndarray

Allocate effort based on distance from fishing ports.

Effort decreases with distance from nearest port: effort[p] ∝ 1 / distance[p]^beta

Parameters:

Name Type Description Default
grid EcospaceGrid

Spatial grid

required
port_patches ndarray

Indices of patches containing ports

required
total_effort float

Total effort to allocate

required
beta float

Distance decay exponent (default: 1.0) Higher = faster decay with distance

1.0
max_distance float

Maximum fishing distance from ports (km) Patches beyond this get zero effort

None

Returns:

Type Description
ndarray

Effort per patch [n_patches], sums to total_effort

Examples:

>>> grid = create_1d_grid(n_patches=5)
>>> allocate_port_based(grid, port_patches=np.array([0]), total_effort=100, beta=1.0)
# Returns effort decreasing with distance from patch 0
Source code in pypath/spatial/fishing.py
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
def allocate_port_based(
    grid: "EcospaceGrid",
    port_patches: np.ndarray,
    total_effort: float,
    beta: float = 1.0,
    max_distance: Optional[float] = None,
) -> np.ndarray:
    """Allocate effort based on distance from fishing ports.

    Effort decreases with distance from nearest port:
        effort[p] ∝ 1 / distance[p]^beta

    Parameters
    ----------
    grid : EcospaceGrid
        Spatial grid
    port_patches : np.ndarray
        Indices of patches containing ports
    total_effort : float
        Total effort to allocate
    beta : float
        Distance decay exponent (default: 1.0)
        Higher = faster decay with distance
    max_distance : float, optional
        Maximum fishing distance from ports (km)
        Patches beyond this get zero effort

    Returns
    -------
    np.ndarray
        Effort per patch [n_patches], sums to total_effort

    Examples
    --------
    >>> grid = create_1d_grid(n_patches=5)
    >>> allocate_port_based(grid, port_patches=np.array([0]), total_effort=100, beta=1.0)
    # Returns effort decreasing with distance from patch 0
    """
    from scipy.spatial.distance import cdist

    n_patches = grid.n_patches

    # Vectorized distance from each patch to nearest port
    all_centroids, km_per_unit = _distance_points(grid)  # [n_patches, 2]
    port_centroids = all_centroids[port_patches]  # [n_ports, 2]
    dist_matrix = cdist(all_centroids, port_centroids, metric="euclidean") * km_per_unit
    distance_to_port = np.maximum(dist_matrix.min(axis=1), 0.1)

    # Calculate effort based on inverse distance
    effort = 1.0 / (distance_to_port**beta)

    # Apply maximum distance cutoff if specified
    if max_distance is not None:
        effort[distance_to_port > max_distance] = 0.0

    # Normalize to total effort
    total_attractiveness = effort.sum()

    if total_attractiveness < 1e-10:
        # All patches too far - fall back to uniform at ports
        effort = np.zeros(n_patches)
        effort[port_patches] = 1.0
        total_attractiveness = len(port_patches)

    effort = effort * (total_effort / total_attractiveness)

    return effort

allocate_uniform

allocate_uniform(n_patches: int, total_effort: float = 1.0) -> np.ndarray

Allocate effort uniformly across all patches.

Parameters:

Name Type Description Default
n_patches int

Number of spatial patches

required
total_effort float

Total effort to allocate (default: 1.0)

1.0

Returns:

Type Description
ndarray

Effort per patch [n_patches], sums to total_effort

Examples:

>>> allocate_uniform(5, total_effort=100)
array([20., 20., 20., 20., 20.])
Source code in pypath/spatial/fishing.py
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
def allocate_uniform(n_patches: int, total_effort: float = 1.0) -> np.ndarray:
    """Allocate effort uniformly across all patches.

    Parameters
    ----------
    n_patches : int
        Number of spatial patches
    total_effort : float
        Total effort to allocate (default: 1.0)

    Returns
    -------
    np.ndarray
        Effort per patch [n_patches], sums to total_effort

    Examples
    --------
    >>> allocate_uniform(5, total_effort=100)
    array([20., 20., 20., 20., 20.])
    """
    return np.ones(n_patches) * (total_effort / n_patches)

calculate_distance_penalty

calculate_distance_penalty(grid: 'EcospaceGrid', port_patches: ndarray, beta: float) -> np.ndarray

Calculate distance penalty from nearest port.

Parameters:

Name Type Description Default
grid EcospaceGrid

Spatial grid

required
port_patches ndarray

Indices of port patches

required
beta float

Distance decay exponent

required

Returns:

Type Description
ndarray

Distance penalty [n_patches] penalty[p] = distance_to_nearest_port[p]^beta

Source code in pypath/spatial/fishing.py
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
def calculate_distance_penalty(
    grid: "EcospaceGrid", port_patches: np.ndarray, beta: float
) -> np.ndarray:
    """Calculate distance penalty from nearest port.

    Parameters
    ----------
    grid : EcospaceGrid
        Spatial grid
    port_patches : np.ndarray
        Indices of port patches
    beta : float
        Distance decay exponent

    Returns
    -------
    np.ndarray
        Distance penalty [n_patches]
        penalty[p] = distance_to_nearest_port[p]^beta
    """
    from scipy.spatial.distance import cdist

    all_centroids, km_per_unit = _distance_points(grid)
    port_centroids = all_centroids[port_patches]
    dist_matrix = cdist(all_centroids, port_centroids, metric="euclidean") * km_per_unit
    min_dist = np.maximum(dist_matrix.min(axis=1), 0.1)
    return min_dist**beta

create_spatial_fishing

create_spatial_fishing(n_months: int, n_gears: int, n_patches: int, forced_effort: ndarray, allocation_type: str = 'uniform', **kwargs) -> SpatialFishing

Create spatial fishing with pre-computed effort allocation.

Parameters:

Name Type Description Default
n_months int

Number of monthly timesteps

required
n_gears int

Number of fishing gears/fleets

required
n_patches int

Number of spatial patches

required
forced_effort ndarray

Total effort by month and gear [n_months, n_gears+1] Column 0 is "Outside" (ignored)

required
allocation_type str

Allocation method (see SpatialFishing)

'uniform'
**kwargs

Additional parameters for allocation method (e.g., gravity_alpha, port_patches, etc.)

{}

Returns:

Type Description
SpatialFishing

Spatial fishing object with effort_allocation computed

Examples:

>>> forced_effort = np.ones((12, 3))  # 12 months, 2 gears + Outside
>>> fishing = create_spatial_fishing(
...     n_months=12,
...     n_gears=2,
...     n_patches=10,
...     forced_effort=forced_effort,
...     allocation_type="uniform"
... )
Source code in pypath/spatial/fishing.py
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
def create_spatial_fishing(
    n_months: int,
    n_gears: int,
    n_patches: int,
    forced_effort: np.ndarray,
    allocation_type: str = "uniform",
    **kwargs,
) -> SpatialFishing:
    """Create spatial fishing with pre-computed effort allocation.

    Parameters
    ----------
    n_months : int
        Number of monthly timesteps
    n_gears : int
        Number of fishing gears/fleets
    n_patches : int
        Number of spatial patches
    forced_effort : np.ndarray
        Total effort by month and gear [n_months, n_gears+1]
        Column 0 is "Outside" (ignored)
    allocation_type : str
        Allocation method (see SpatialFishing)
    **kwargs
        Additional parameters for allocation method
        (e.g., gravity_alpha, port_patches, etc.)

    Returns
    -------
    SpatialFishing
        Spatial fishing object with effort_allocation computed

    Examples
    --------
    >>> forced_effort = np.ones((12, 3))  # 12 months, 2 gears + Outside
    >>> fishing = create_spatial_fishing(
    ...     n_months=12,
    ...     n_gears=2,
    ...     n_patches=10,
    ...     forced_effort=forced_effort,
    ...     allocation_type="uniform"
    ... )
    """
    # Initialize effort allocation array
    effort_allocation = np.zeros((n_months, n_gears + 1, n_patches))

    # Column 0 (Outside) always zero
    effort_allocation[:, 0, :] = 0.0

    # Allocate each gear for each month
    for month in range(n_months):
        for gear in range(1, n_gears + 1):
            total_effort = forced_effort[month, gear]

            if allocation_type == "uniform":
                allocation = allocate_uniform(n_patches, total_effort)

            elif allocation_type == "gravity":
                # Requires biomass - will be computed dynamically
                # For now, use uniform as placeholder
                allocation = allocate_uniform(n_patches, total_effort)

            elif allocation_type == "port":
                # Requires grid and port_patches
                grid = kwargs.get("grid")
                port_patches = kwargs.get("port_patches")

                if grid is None or port_patches is None:
                    raise ValueError(
                        "allocation_type='port' requires 'grid' and 'port_patches'"
                    )

                beta = kwargs.get("gravity_beta", 1.0)
                allocation = allocate_port_based(grid, port_patches, total_effort, beta)

            else:
                # Fall back to uniform
                allocation = allocate_uniform(n_patches, total_effort)

            effort_allocation[month, gear, :] = allocation

    # Filter kwargs to only include SpatialFishing parameters
    # Exclude allocation-specific parameters that were only used for calculation
    spatial_fishing_kwargs = {}
    valid_params = [
        "gravity_alpha",
        "gravity_beta",
        "port_patches",
        "target_groups",
        "custom_allocation_function",
    ]

    for key in valid_params:
        if key in kwargs:
            spatial_fishing_kwargs[key] = kwargs[key]

    # Create SpatialFishing object
    spatial_fishing = SpatialFishing(
        allocation_type=allocation_type,
        effort_allocation=effort_allocation,
        **spatial_fishing_kwargs,
    )

    return spatial_fishing

distribute_effort_with_fleet

distribute_effort_with_fleet(base_effort: ndarray, deployment: FleetDeployment, distance_to_port_km: ndarray) -> np.ndarray

Distribute effort according to fleet deployment constraints.

Source code in pypath/spatial/fishing.py
664
665
666
667
668
669
670
671
672
673
674
675
676
def distribute_effort_with_fleet(
    base_effort: np.ndarray,
    deployment: FleetDeployment,
    distance_to_port_km: np.ndarray,
) -> np.ndarray:
    """Distribute effort according to fleet deployment constraints."""
    effort = np.asarray(base_effort, dtype=float)
    weights = deployment.accessibility_weights(distance_to_port_km)
    weighted = effort * weights
    total = weighted.sum()
    if total <= 1e-12:
        return np.zeros_like(effort)
    return weighted * (deployment.capacity / total)

effort_multipliers

effort_multipliers(spatial_fishing: 'SpatialFishing', n_patches: int, n_gears: int, biomass: Optional[ndarray] = None, grid: Optional['EcospaceGrid'] = None, habitat_preference: Optional[ndarray] = None, month: int = 0) -> np.ndarray

Per-patch, per-gear effort multipliers for a spatial simulation.

The spatial solver applies the fleet's ForcedEffort in every patch, so an allocation has to reach it as a relative multiplier rather than as an absolute split. Each gear's allocation is therefore normalised to mean 1.0 across patches: total effort over the grid is unchanged, and a "uniform" allocation reproduces a run with no spatial fishing exactly, except for EwE mediation shapes mediated by a fleet: with an allocation they follow each patch's effort, without one they count the fleet at its base effort of 1 (as EwE's Ecospace does with and without predicted effort).

Parameters:

Name Type Description Default
spatial_fishing SpatialFishing

Allocation settings.

required
n_patches int

Number of spatial patches.

required
n_gears int

Number of fishing gears (excluding the "Outside" column).

required
biomass ndarray

Current biomass [n_groups + 1, n_patches]. Required for "gravity".

None
grid EcospaceGrid

Grid, required for "port" allocation.

None
habitat_preference ndarray

Habitat preference [n_groups, n_patches] as in EcospaceParams (row g - 1 is Ecosim group g, no "Outside" row), averaged over the groups, or [n_patches]. Required for "habitat" allocation.

None
month int

Month index, used to select a slice of a "prescribed" allocation.

0

Returns:

Type Description
ndarray

Multipliers [n_patches, n_gears], each column averaging 1.0. An allocation that cannot be computed falls back to ones (uniform).

Examples:

>>> f = SpatialFishing(allocation_type="uniform")
>>> effort_multipliers(f, n_patches=4, n_gears=1)
array([[1.],
       [1.],
       [1.],
       [1.]])
Source code in pypath/spatial/fishing.py
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
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
443
444
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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
def effort_multipliers(
    spatial_fishing: "SpatialFishing",
    n_patches: int,
    n_gears: int,
    biomass: Optional[np.ndarray] = None,
    grid: Optional["EcospaceGrid"] = None,
    habitat_preference: Optional[np.ndarray] = None,
    month: int = 0,
) -> np.ndarray:
    """Per-patch, per-gear effort multipliers for a spatial simulation.

    The spatial solver applies the fleet's `ForcedEffort` in every patch, so an
    allocation has to reach it as a *relative* multiplier rather than as an
    absolute split. Each gear's allocation is therefore normalised to mean 1.0
    across patches: total effort over the grid is unchanged, and a "uniform"
    allocation reproduces a run with no spatial fishing exactly, except for
    EwE mediation shapes mediated by a fleet: with an allocation they follow
    each patch's effort, without one they count the fleet at its base effort
    of 1 (as EwE's Ecospace does with and without predicted effort).

    Parameters
    ----------
    spatial_fishing : SpatialFishing
        Allocation settings.
    n_patches : int
        Number of spatial patches.
    n_gears : int
        Number of fishing gears (excluding the "Outside" column).
    biomass : np.ndarray, optional
        Current biomass [n_groups + 1, n_patches]. Required for "gravity".
    grid : EcospaceGrid, optional
        Grid, required for "port" allocation.
    habitat_preference : np.ndarray, optional
        Habitat preference [n_groups, n_patches] as in EcospaceParams (row
        g - 1 is Ecosim group g, no "Outside" row), averaged over the groups,
        or [n_patches]. Required for "habitat" allocation.
    month : int
        Month index, used to select a slice of a "prescribed" allocation.

    Returns
    -------
    np.ndarray
        Multipliers [n_patches, n_gears], each column averaging 1.0.
        An allocation that cannot be computed falls back to ones (uniform).

    Examples
    --------
    >>> f = SpatialFishing(allocation_type="uniform")
    >>> effort_multipliers(f, n_patches=4, n_gears=1)
    array([[1.],
           [1.],
           [1.],
           [1.]])
    """
    ones = np.ones((n_patches, max(n_gears, 0)))
    if n_gears <= 0 or n_patches <= 0 or spatial_fishing is None:
        return ones

    kind = spatial_fishing.allocation_type

    def _normalise(alloc: np.ndarray) -> np.ndarray:
        """Scale an allocation to mean 1.0, or fall back to uniform."""
        alloc = np.asarray(alloc, dtype=float).ravel()
        if alloc.shape[0] != n_patches or not np.all(np.isfinite(alloc)):
            return np.ones(n_patches)
        alloc = np.clip(alloc, 0.0, None)
        total = alloc.sum()
        if total <= 1e-12:
            return np.ones(n_patches)
        return alloc * (n_patches / total)

    per_gear = []
    for gear in range(1, n_gears + 1):
        try:
            if kind == "gravity":
                if biomass is None:
                    raise ValueError("gravity allocation requires biomass")
                alloc = allocate_gravity(
                    np.asarray(biomass, dtype=float),
                    target_groups=spatial_fishing.target_groups,
                    total_effort=1.0,
                    alpha=spatial_fishing.gravity_alpha,
                    beta=spatial_fishing.gravity_beta,
                    port_patches=spatial_fishing.port_patches,
                    grid=grid,
                )
            elif kind == "port":
                if grid is None or spatial_fishing.port_patches is None:
                    raise ValueError("port allocation requires grid and port_patches")
                alloc = allocate_port_based(
                    grid,
                    spatial_fishing.port_patches,
                    total_effort=1.0,
                    beta=spatial_fishing.gravity_beta,
                )
            elif kind == "habitat":
                if habitat_preference is None:
                    raise ValueError("habitat allocation requires habitat_preference")
                pref = np.asarray(habitat_preference, dtype=float)
                if pref.ndim == 2:
                    # Average over the groups; EcospaceParams rows are groups
                    # 1..n (row g - 1 is group g), with no "Outside" row.
                    pref = pref.mean(axis=0)
                alloc = allocate_habitat_based(pref, total_effort=1.0)
            elif kind in ("prescribed", "custom"):
                supplied = spatial_fishing.effort_allocation
                if kind == "custom" and spatial_fishing.custom_allocation_function:
                    alloc = spatial_fishing.custom_allocation_function(
                        biomass, month, spatial_fishing
                    )
                elif supplied is None:
                    raise ValueError(f"{kind} allocation requires effort_allocation")
                else:
                    supplied = np.asarray(supplied, dtype=float)
                    # [n_months, n_gears + 1, n_patches] or [n_gears + 1, n_patches]
                    if supplied.ndim == 3:
                        idx = min(month, supplied.shape[0] - 1)
                        alloc = supplied[idx, gear]
                    elif supplied.ndim == 2:
                        alloc = supplied[gear]
                    else:
                        alloc = supplied
            else:  # "uniform" and anything unrecognised
                alloc = np.ones(n_patches)
        except (ValueError, IndexError, TypeError, AttributeError) as e:
            logger.warning(
                "Spatial effort allocation '%s' failed for gear %d (%s); "
                "using uniform effort",
                kind,
                gear,
                e,
            )
            alloc = np.ones(n_patches)

        per_gear.append(_normalise(alloc))

    return np.column_stack(per_gear)

mpa_spillover_potential

mpa_spillover_potential(biomass_inside_mpa: float, biomass_outside_mpa: float, boundary_length_km: float, mobility_rate: float) -> float

Estimate fishery spillover potential from MPA boundaries.

Source code in pypath/spatial/fishing.py
679
680
681
682
683
684
685
686
687
def mpa_spillover_potential(
    biomass_inside_mpa: float,
    biomass_outside_mpa: float,
    boundary_length_km: float,
    mobility_rate: float,
) -> float:
    """Estimate fishery spillover potential from MPA boundaries."""
    gradient = max(biomass_inside_mpa - biomass_outside_mpa, 0.0)
    return gradient * max(boundary_length_km, 0.0) * max(mobility_rate, 0.0)

validate_effort_allocation

validate_effort_allocation(effort_allocation: ndarray, forced_effort: ndarray, tolerance: float = 1e-08) -> bool

Validate that spatial effort allocation sums correctly.

For each month and gear: Σ_patches effort_allocation[m, g, p] = forced_effort[m, g]

Parameters:

Name Type Description Default
effort_allocation ndarray

Spatial effort [n_months, n_gears+1, n_patches]

required
forced_effort ndarray

Total effort [n_months, n_gears+1]

required
tolerance float

Numerical tolerance (default: 1e-8)

1e-08

Returns:

Type Description
bool

True if allocation is valid

Source code in pypath/spatial/fishing.py
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
def validate_effort_allocation(
    effort_allocation: np.ndarray, forced_effort: np.ndarray, tolerance: float = 1e-8
) -> bool:
    """Validate that spatial effort allocation sums correctly.

    For each month and gear:
        Σ_patches effort_allocation[m, g, p] = forced_effort[m, g]

    Parameters
    ----------
    effort_allocation : np.ndarray
        Spatial effort [n_months, n_gears+1, n_patches]
    forced_effort : np.ndarray
        Total effort [n_months, n_gears+1]
    tolerance : float
        Numerical tolerance (default: 1e-8)

    Returns
    -------
    bool
        True if allocation is valid
    """
    # Sum over patches
    spatial_total = effort_allocation.sum(axis=2)

    # Compare to forced effort
    difference = np.abs(spatial_total - forced_effort)

    return np.all(difference < tolerance)

Spatial Integration

The main simulation runner that couples Ecosim derivatives with spatial dispersal, habitat effects, and optional IBM groups across the grid.

pypath.spatial.integration

Spatial-temporal integration for ECOSPACE.

Integrates ECOSPACE spatial dynamics with Ecosim temporal dynamics: - Spatial derivative calculation (local dynamics + movement) - RK4 integration extended for spatial state - Wrapper functions for spatial simulations - Backward compatibility with non-spatial Ecosim

deriv_vector_spatial

deriv_vector_spatial(state_spatial: ndarray, params: Dict, forcing: Dict, fishing: Dict, ecospace: EcospaceParams, environmental_drivers: Optional[EnvironmentalDrivers], t: float = 0.0, dt: float = 1.0 / 12.0, mpa_effort_mask: Optional[ndarray] = None, mpa_cap_mult: Optional[ndarray] = None, effort_multiplier: Optional[ndarray] = None, stanza_pred_ratio: Optional[ndarray] = None, rates_out: Optional[Dict[str, ndarray]] = None, include_diffusion: bool = True, _fast_capture: Optional[dict] = None) -> np.ndarray

Calculate spatial derivative (local dynamics + movement).

For each patch p: 1. Calculate local Ecosim dynamics (production, predation, fishing, M0) 2. Apply habitat capacity to the patch's base biomass and flows (always) 3. Add spatial fluxes (migration/dispersal)

Parameters:

Name Type Description Default
state_spatial ndarray

Spatial state [n_groups+1, n_patches] Index 0 = "Outside" (no dynamics) Index 1+ = Living and detritus groups

required
params dict

Ecosim parameters (from RsimParams)

required
forcing dict

Environmental forcing (from RsimForcing)

required
fishing dict

Fishing forcing (from RsimFishing)

required
ecospace EcospaceParams

Spatial parameters

required
environmental_drivers EnvironmentalDrivers

Time-varying environmental layers. Not evaluated here; the habitat capacity applies with or without them.

required
t float

Simulation time (years)

0.0
dt float

Timestep size (default: 1/12 year = 1 month)

1.0 / 12.0
stanza_pred_ratio ndarray

Per-patch StanzaPredRatio [n_groups+1, n_patches] for multi-stanza groups (NaN elsewhere); becomes forcing["StanzaPredRatio"] of each patch.

None
rates_out dict

Arrays [n_groups+1, n_patches] keyed like deriv_vector's rates (e.g. "FoodGain", "LossPropToB"); each patch writes its own column with its absolute flows.

None
include_diffusion bool

Include diffusion in the movement flux (default). rsim_run_spatial leaves it out when it diffuses implicitly after each RK4 step.

True
_fast_capture dict

Internal (rsim_run_spatial's month): nothing is evaluated and None is returned. When the compiled derivative would run, the dict gets "call", its prepared :class:~pypath.spatial.batched_fast. CellCall (call.run(state, out) gives what this function would put in its result before the movement flux, for any state), and "flux_zero", whether that flux would be all zeros; otherwise it is left empty.

None

Returns:

Type Description
ndarray

Spatial derivative [n_groups+1, n_patches] deriv[g, p] = rate of change for group g in patch p

Notes

This function extends the standard Ecosim derivative to spatial grids. For each patch, the local Ecosim dynamics are calculated independently, then spatial fluxes (movement) are added to account for dispersal.

The habitat capacity (ecospace.habitat_capacity) always applies, as EwE's Ecospace always uses HabCap. environmental_drivers no longer switches it on.

Source code in pypath/spatial/integration.py
347
348
349
350
351
352
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
386
387
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
443
444
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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
def deriv_vector_spatial(
    state_spatial: np.ndarray,
    params: Dict,
    forcing: Dict,
    fishing: Dict,
    ecospace: EcospaceParams,
    environmental_drivers: Optional[EnvironmentalDrivers],
    t: float = 0.0,
    dt: float = 1.0 / 12.0,
    mpa_effort_mask: Optional[np.ndarray] = None,
    mpa_cap_mult: Optional[np.ndarray] = None,
    effort_multiplier: Optional[np.ndarray] = None,
    stanza_pred_ratio: Optional[np.ndarray] = None,
    rates_out: Optional[Dict[str, np.ndarray]] = None,
    include_diffusion: bool = True,
    _fast_capture: Optional[dict] = None,
) -> np.ndarray:
    """Calculate spatial derivative (local dynamics + movement).

    For each patch p:
        1. Calculate local Ecosim dynamics (production, predation, fishing, M0)
        2. Apply habitat capacity to the patch's base biomass and flows (always)
        3. Add spatial fluxes (migration/dispersal)

    Parameters
    ----------
    state_spatial : np.ndarray
        Spatial state [n_groups+1, n_patches]
        Index 0 = "Outside" (no dynamics)
        Index 1+ = Living and detritus groups
    params : dict
        Ecosim parameters (from RsimParams)
    forcing : dict
        Environmental forcing (from RsimForcing)
    fishing : dict
        Fishing forcing (from RsimFishing)
    ecospace : EcospaceParams
        Spatial parameters
    environmental_drivers : EnvironmentalDrivers, optional
        Time-varying environmental layers. Not evaluated here; the habitat
        capacity applies with or without them.
    t : float
        Simulation time (years)
    dt : float
        Timestep size (default: 1/12 year = 1 month)
    stanza_pred_ratio : np.ndarray, optional
        Per-patch ``StanzaPredRatio`` [n_groups+1, n_patches] for multi-stanza
        groups (NaN elsewhere); becomes ``forcing["StanzaPredRatio"]`` of each
        patch.
    rates_out : dict, optional
        Arrays [n_groups+1, n_patches] keyed like ``deriv_vector``'s ``rates``
        (e.g. ``"FoodGain"``, ``"LossPropToB"``); each patch writes its own
        column with its absolute flows.
    include_diffusion : bool
        Include diffusion in the movement flux (default). ``rsim_run_spatial``
        leaves it out when it diffuses implicitly after each RK4 step.
    _fast_capture : dict, optional
        Internal (``rsim_run_spatial``'s month): nothing is evaluated and
        None is returned. When the compiled derivative would run, the dict
        gets ``"call"``, its prepared :class:`~pypath.spatial.batched_fast.
        CellCall` (``call.run(state, out)`` gives what this function would
        put in its result before the movement flux, for any state), and
        ``"flux_zero"``, whether that flux would be all zeros; otherwise it
        is left empty.

    Returns
    -------
    np.ndarray
        Spatial derivative [n_groups+1, n_patches]
        deriv[g, p] = rate of change for group g in patch p

    Notes
    -----
    This function extends the standard Ecosim derivative to spatial grids.
    For each patch, the local Ecosim dynamics are calculated independently,
    then spatial fluxes (movement) are added to account for dispersal.

    The habitat capacity (``ecospace.habitat_capacity``) always applies, as
    EwE's Ecospace always uses HabCap. ``environmental_drivers`` no longer
    switches it on.
    """
    from pypath.ibm.base import SpatialContext
    from pypath.spatial.dispersal import (
        calculate_spatial_flux,
        spatial_flux_is_zero,
    )

    _n_groups = state_spatial.shape[0]
    n_patches = state_spatial.shape[1]

    # Initialize derivative
    deriv_spatial = np.zeros_like(state_spatial, dtype=float)

    # Each patch holds its share of the biomass, so it also holds that share
    # of the base biomass and base flows. The local dynamics are therefore
    # evaluated on densities, as in EwE Ecospace: biomass divided by the
    # patch's area fraction, with the whole-model Bbase/QQbase as the base
    # densities. The derivative is scaled back by the area fraction (#51).
    # IBM groups compute their own absolute rates, so they keep the old form.
    patch_share = _patch_area_fractions(ecospace, n_patches)
    _mediation_scale = None
    if params.get("ibm_groups"):
        logger.debug("IBM groups present: patch dynamics not density-scaled")
        # EwE mediation compares a mediator's density with its whole-model
        # base, so it still gets densities: biomass / the patch's area share
        if params.get("EweMediation") is not None:
            _mediation_scale = 1.0 / patch_share
        patch_share = None

    # Per-patch, per-fleet effort scaling. MPA closures and spatial effort
    # allocation both scale a fleet's effort in a patch, so they compose.
    if effort_multiplier is None:
        patch_effort_mask = mpa_effort_mask
    elif mpa_effort_mask is None:
        patch_effort_mask = effort_multiplier
    else:
        patch_effort_mask = mpa_effort_mask * effort_multiplier

    # A fleet mediator's effort. EwE's Ecospace passes the cell's predicted
    # effort, EffortSpace (the month's effort x the cell's share), when it
    # predicts effort, and 1 otherwise (cSpaceSolver.vb:516-528). PyPath's
    # counterpart of predicted effort is the spatial effort allocation: with
    # it each patch's own effort is used (ForcedEffort), without it 1.
    if effort_multiplier is None and params.get("EweMediation") is not None:
        forcing = dict(forcing)
        forcing["MediationEffort"] = np.ones_like(
            np.asarray(
                forcing.get("ForcedEffort", np.ones(params.get("NUM_GEARS", 0) + 1)),
                dtype=float,
            )
        )

    # EwE's relative primary production map: each patch's total nutrient is
    # the map-wide total times its value (cSpaceSolver.vb 570, 860), which
    # the kernel reads as the patch's nutrient forcing
    _nut_scale = params.get("_nut_scale_patches")

    def _patch_forcing(patch_idx):
        """Forcing of one patch: its own effort, stanza consumption index and
        relative primary production."""
        if (
            patch_effort_mask is None
            and stanza_pred_ratio is None
            and _nut_scale is None
        ):
            return forcing
        patch_forcing = forcing.copy()
        if _nut_scale is not None:
            patch_forcing["NutForcing"] = float(_nut_scale[patch_idx])
        if patch_effort_mask is not None:
            patch_effort = forcing["ForcedEffort"].copy()
            n_mask_fleets = patch_effort_mask.shape[1]
            patch_effort[1 : n_mask_fleets + 1] *= patch_effort_mask[patch_idx, :]
            patch_forcing["ForcedEffort"] = patch_effort
        if stanza_pred_ratio is not None:
            patch_forcing["StanzaPredRatio"] = stanza_pred_ratio[:, patch_idx]
        return patch_forcing

    def _store_rates(patch_idx, rates):
        """Write one patch's flows into its column of ``rates_out``."""
        if rates is None:
            return
        for key, out in rates_out.items():
            out[:, patch_idx] = rates[key]

    # Step 1: Calculate local dynamics for each patch
    # Pre-compute habitat capacity modifications if needed
    # Habitat capacity as EwE6 applies it (#58), always (B4): each patch's
    # base biomass is B * c and each link's base flow Q0 * c_prey * c_pred
    # over the map-wide mean of that product (EwE's MeanBP rescaling of the
    # search rates). Map-wide base flows stay Ecopath's, and a group's
    # per-capita rates no longer rise as its own habitat gets poorer.
    capacity = (
        _capacity_matrix(
            ecospace,
            mpa_cap_mult,
            len(params["B_BaseRef"]),
            n_patches,
            patch_share,
        )
        # EwE's base calibration (below) replaces this capacity scaling
        if "B_BaseRef" in params and params.get("_space_cal") is None
        else None
    )
    params_need_modification = capacity is not None

    # EwE's base calibration (rsim_run_spatial sets it): the same calibrated
    # parameters for every patch, and each patch's feeding efficiency (EatEff,
    # its habitat capacity, times any MPA capacity bonus)
    _space_cal = params.get("_space_cal")
    _eat_eff_patches = params.get("_eat_eff_patches")
    _saved_params = None
    if _space_cal is not None:
        _saved_params = {key: params.get(key, _MISSING) for key in _space_cal}
        params.update(_space_cal)
        params_need_modification = False
        if mpa_cap_mult is not None and _eat_eff_patches is not None:
            _eat_eff_patches = _eat_eff_patches.copy()
            _eat_eff_patches[1:] *= np.asarray(mpa_cap_mult, dtype=float)[np.newaxis, :]

    if params_need_modification:
        b_base_ref_original = np.asarray(params["B_BaseRef"], dtype=float)
        b_base_ref_patches = b_base_ref_original[:, np.newaxis] * capacity
        qq_base_original = params.get("QQbase")
        capacity_overlap = (
            _capacity_overlap(capacity, patch_share, n_patches)
            if qq_base_original is not None
            and np.shape(qq_base_original)[0] == len(b_base_ref_original)
            else None
        )

    def _patch_qq_base(patch_idx):
        """Base consumption matrix of one patch under habitat capacity."""
        return qq_base_original * _patch_link_factor(
            capacity, capacity_overlap, patch_idx
        )

    # Build SpatialContext for each IBM group
    ibm_groups = params.get("ibm_groups", {})
    ibm_spatial_contexts = {}
    if ibm_groups:
        ActiveLink = params.get("ActiveLink", None)
        n_state = state_spatial.shape[0]
        adjacency_matrix = ecospace.grid.adjacency_matrix

        for g_idx, _ibm in ibm_groups.items():
            # Use habitat preference for this group, or uniform if unavailable
            hab_idx = g_idx - 1  # Convert 1-based Ecosim index to 0-based
            if hab_idx < ecospace.habitat_preference.shape[0]:
                habitat_qual = ecospace.habitat_preference[hab_idx]
            else:
                habitat_qual = np.ones(n_patches)

            # Compute prey and predator densities using the diet matrix.
            # ActiveLink[prey, pred] is True when pred eats prey.
            if ActiveLink is not None:
                # Use cached masks if available (ActiveLink is static)
                cache_key = "_ibm_masks_%d" % g_idx
                cached = params.get(cache_key)
                if cached is not None:
                    prey_mask, pred_mask = cached
                else:
                    prey_mask = np.zeros(n_state, dtype=bool)
                    for prey in range(1, min(n_state, ActiveLink.shape[0])):
                        if g_idx < ActiveLink.shape[1] and ActiveLink[prey, g_idx]:
                            prey_mask[prey] = True
                    pred_mask = np.zeros(n_state, dtype=bool)
                    for pred in range(1, min(n_state, ActiveLink.shape[1])):
                        if g_idx < ActiveLink.shape[0] and ActiveLink[g_idx, pred]:
                            pred_mask[pred] = True
                    params[cache_key] = (prey_mask, pred_mask)

                food = (
                    state_spatial[prey_mask, :].sum(axis=0)
                    if prey_mask.any()
                    else np.zeros(n_patches)
                )
                pred = (
                    state_spatial[pred_mask, :].sum(axis=0)
                    if pred_mask.any()
                    else np.zeros(n_patches)
                )
            else:
                # Fallback: total living biomass (less informative but safe)
                food = state_spatial[1:, :].sum(axis=0)
                pred = state_spatial[1:, :].sum(axis=0)

            ibm_spatial_contexts[g_idx] = SpatialContext(
                adjacency=adjacency_matrix,
                habitat_quality=habitat_qual,
                food_density=food,
                predator_density=pred,
                n_patches=n_patches,
            )

    # Inject IBM spatial contexts into params for deriv_vector
    for g_idx, ctx in ibm_spatial_contexts.items():
        params["_ibm_spatial_context_%d" % g_idx] = ctx

    # EwE6 handling time: each patch's Hden column (updated in place)
    _hden_patches = params.get("_hden_patches")

    # EcospaceParams.detritus_pass_on reaches each patch's derivative; a value
    # the caller set (rsim_run_spatial does) is kept
    _pass_on_added = "_detritus_pass_on" not in params
    if _pass_on_added:
        params["_detritus_pass_on"] = bool(getattr(ecospace, "detritus_pass_on", False))

    # The loop writes each patch's values into the shared params dict. What
    # was there goes back afterwards and a key the caller did not have is
    # removed, so the dict comes back as it went in (a patch's _hden is a view
    # into its own Hden column). Each patch takes its values from arrays made
    # before the loop, so nothing needs restoring between patches.
    _per_patch_keys = ["_hden", "_eat_eff", "_mediation_density_scale"]
    if params_need_modification:
        _per_patch_keys += ["B_BaseRef", "Bbase", "QQbase"]
    _prior = {key: params.get(key, _MISSING) for key in _per_patch_keys}

    # rsim_run_spatial(n_jobs=...) puts its process pool here. Each worker
    # takes a chunk of patches: the columns it needs travel with the task and
    # the columns it advanced (Hden), with the derivatives and rates, come
    # back. IBM groups keep the serial loop (see _n_patch_workers).
    _pool = params.get("_patch_pool")
    if ibm_spatial_contexts:
        _pool = None
    _batched_ok = (
        USE_BATCHED_DERIV
        and patch_share is not None
        and not ibm_spatial_contexts
        and batch_supported(params, forcing, () if rates_out is None else rates_out)
    )
    try:
        if _fast_capture is not None and not _batched_ok:
            return None
        if _batched_ok:
            # All patches in one array computation, bit-identical to the
            # per-patch loop below (pypath.spatial.batched)
            _w = np.asarray(patch_share, dtype=float)
            _bb_p = _qq_p = None
            if params_need_modification:
                _bb_p = np.ascontiguousarray(b_base_ref_patches.T)
                if capacity_overlap is not None:
                    _qq_p = np.stack([_patch_qq_base(p) for p in range(n_patches)])
            _effort_p = None
            if patch_effort_mask is not None:
                _base_eff = np.asarray(forcing["ForcedEffort"], dtype=float)
                _effort_p = np.tile(_base_eff, (n_patches, 1))
                _n_mask_fleets = patch_effort_mask.shape[1]
                _effort_p[:, 1 : _n_mask_fleets + 1] *= patch_effort_mask
            _eat_gp = None
            if _space_cal is not None and _eat_eff_patches is not None:
                _eat_gp = _eat_eff_patches  # EwE's base calibration (G, P)
            if USE_FAST_BATCHED and fast_supported(params, _eat_gp):
                # The compiled loop (pypath.spatial.batched_fast), its patches
                # over n_jobs threads, on the run's own (groups x patches)
                # arrays: densities, area shares, Hden in place
                _ratio_gp = None
                if stanza_pred_ratio is not None:
                    _ratio_gp = stanza_pred_ratio
                elif forcing.get("StanzaPredRatio") is not None:
                    _ratio_gp = np.tile(
                        np.asarray(forcing["StanzaPredRatio"], dtype=float)[:, None],
                        (1, n_patches),
                    )
                if _fast_capture is not None:
                    _hden_ok = _hden_patches is None or (
                        isinstance(_hden_patches, np.ndarray)
                        and _hden_patches.dtype == np.float64
                        and _hden_patches.flags.c_contiguous
                    )
                    if _hden_ok:
                        _fast_capture["call"] = spatial_call(
                            state_spatial.shape,
                            patch_share,
                            params,
                            forcing,
                            fishing,
                            bbase=_bb_p,
                            qqbase=_qq_p,
                            hden=_hden_patches,
                            patch_effort=_effort_p,
                            stanza_ratio=_ratio_gp,
                            eat_eff=_eat_gp,
                            nut_forcing=_nut_scale,
                            rate_keys=() if rates_out is None else tuple(rates_out),
                            n_threads=1 if _pool is None else int(_pool[1]),
                        )
                        _fast_capture["flux_zero"] = spatial_flux_is_zero(
                            state_spatial.shape[0], ecospace, params, include_diffusion
                        )
                    return None
                deriv_spatial_fast(
                    state_spatial,
                    patch_share,
                    params,
                    forcing,
                    fishing,
                    deriv_out=deriv_spatial,
                    bbase=_bb_p,
                    qqbase=_qq_p,
                    hden=_hden_patches,
                    patch_effort=_effort_p,
                    stanza_ratio=_ratio_gp,
                    eat_eff=_eat_gp,
                    nut_forcing=_nut_scale,
                    rates_out=rates_out,
                    n_threads=1 if _pool is None else int(_pool[1]),
                )
            else:
                # NumPy's (pypath.spatial.batched), patch-major
                if _fast_capture is not None:
                    return None
                _dens = state_spatial.T / _w[:, None]
                _ratio_p = None
                if stanza_pred_ratio is not None:
                    _ratio_p = np.ascontiguousarray(np.asarray(stanza_pred_ratio).T)
                elif forcing.get("StanzaPredRatio") is not None:
                    _ratio_p = np.tile(
                        np.asarray(forcing["StanzaPredRatio"], dtype=float),
                        (n_patches, 1),
                    )
                _hden_p = None
                if _hden_patches is not None:
                    _hden_p = np.ascontiguousarray(_hden_patches.T)
                # each patch's EatEff, as the loop's params["_eat_eff"]
                _eat_p = None
                if _eat_gp is not None:
                    _eat_p = np.ascontiguousarray(np.asarray(_eat_gp, dtype=float).T)
                _d_p, _r_p = deriv_batched(
                    _dens,
                    params,
                    forcing,
                    fishing,
                    bbase=_bb_p,
                    qqbase=_qq_p,
                    hden=_hden_p,
                    patch_effort=_effort_p,
                    stanza_ratio=_ratio_p,
                    eat_eff=_eat_p,
                    nut_forcing=_nut_scale,
                    want_rates=rates_out is not None,
                )
                if _hden_p is not None and not params.get("_hden_frozen", False):
                    _hden_patches[:] = _hden_p.T
                deriv_spatial[:] = (_w[:, None] * _d_p).T
                if rates_out is not None:
                    for _key, _out in rates_out.items():
                        _out[:] = (_r_p[_key] * _w[:, None]).T
        elif _pool is not None:
            executor, n_jobs = _pool
            worker_params = {
                k: v for k, v in params.items() if k not in _NOT_FOR_WORKERS
            }
            _eat = (
                _eat_eff_patches
                if _space_cal is not None and _eat_eff_patches is not None
                else None
            )
            chunks = [c for c in np.array_split(np.arange(n_patches), n_jobs) if len(c)]
            futures = [
                executor.submit(
                    _patch_chunk_derivs,
                    state_spatial[:, ch],
                    worker_params,
                    [_patch_forcing(int(i)) for i in ch],
                    fishing,
                    t,
                    None if patch_share is None else patch_share[ch],
                    None if _hden_patches is None else _hden_patches[:, ch],
                    None if _eat is None else _eat[:, ch],
                    b_base_ref_patches[:, ch] if params_need_modification else None,
                    [_patch_qq_base(int(i)) for i in ch]
                    if params_need_modification and capacity_overlap is not None
                    else None,
                    rates_out is not None,
                )
                for ch in chunks
            ]
            for ch, future in zip(chunks, futures):
                d, h, rates_list = future.result()
                deriv_spatial[:, ch] = d
                if _hden_patches is not None:
                    _hden_patches[:, ch] = h
                for i, rates in zip(ch, rates_list):
                    _store_rates(int(i), rates)
        # Patches run one after another on this thread. The per-patch step is
        # Python (deriv_vector), so threads cannot run patches in parallel
        # under the GIL; a thread pool here only added overhead and was
        # removed after profiling (2026-11-17).
        _loop_start = n_patches if (_batched_ok or _pool is not None) else 0
        for patch_idx in range(_loop_start, n_patches):
            state_patch = state_spatial[:, patch_idx]
            patch_forcing = _patch_forcing(patch_idx)
            rates = {} if rates_out is not None else None
            if _hden_patches is not None:
                params["_hden"] = _hden_patches[:, patch_idx]  # a view
            if _space_cal is not None and _eat_eff_patches is not None:
                params["_eat_eff"] = _eat_eff_patches[:, patch_idx]
            if _mediation_scale is not None:
                params["_mediation_density_scale"] = _mediation_scale[patch_idx]

            if params_need_modification:
                modified = b_base_ref_patches[:, patch_idx]
                params["B_BaseRef"] = modified
                params["Bbase"] = modified
                if capacity_overlap is not None:
                    params["QQbase"] = _patch_qq_base(patch_idx)

            deriv_spatial[:, patch_idx] = _local_deriv(
                state_patch,
                params,
                patch_forcing,
                fishing,
                t,
                patch_share,
                patch_idx,
                rates=rates,
            )
            _store_rates(patch_idx, rates)
    finally:
        # Clean up injected spatial context keys
        for g_idx in ibm_spatial_contexts:
            params.pop("_ibm_spatial_context_%d" % g_idx, None)
        _restore_keys(params, _prior)
        if _pass_on_added:
            params.pop("_detritus_pass_on", None)
        if _saved_params is not None:
            _restore_keys(params, _saved_params)

    # Step 2: Add spatial fluxes (movement/dispersal)
    if spatial_flux_is_zero(
        state_spatial.shape[0], ecospace, params, include_diffusion
    ):
        # no flux to compute: adding 0.0 is adding the zero flux, bit for bit
        deriv_spatial += 0.0
    else:
        spatial_flux = calculate_spatial_flux(
            state_spatial, ecospace, params, t, include_diffusion=include_diffusion
        )

        # Add spatial fluxes to local dynamics
        deriv_spatial += spatial_flux

    return deriv_spatial

rsim_run_spatial

rsim_run_spatial(scenario: RsimScenario, method: str = 'RK4', years: Optional[range] = None, ecospace: Optional[EcospaceParams] = None, environmental_drivers: Optional[EnvironmentalDrivers] = None, *, mpa: Optional['MPAConfig'] = None, spatial_fishing: Optional['SpatialFishing'] = None, initial_state_vector: Optional[ndarray] = None, store_state_vectors: bool = False, implicit_movement: bool = True, on_month: Optional[Callable[[int, int], Optional[bool]]] = None, n_jobs: int = 1, mp_context: Optional[str] = None) -> RsimOutput

Run spatial Ecosim simulation.

Wrapper for Ecosim that extends to spatial grids. If ecospace is None, falls back to standard non-spatial Ecosim.

Parameters:

Name Type Description Default
scenario RsimScenario

Simulation scenario (params, forcing, fishing, start state)

required
method str

Integration method (default: 'RK4') Currently only RK4 is implemented

'RK4'
years range

Years to simulate (default: use scenario years). As in rsim_run it must start at scenario.start_year (the first len(years) years are run), else ValueError. Example: range(1, 101) for 100 years of a scenario starting in year 1

None
ecospace EcospaceParams

Spatial parameters If None, runs standard non-spatial Ecosim

None
environmental_drivers EnvironmentalDrivers

Time-varying environmental layers. Not evaluated in the run; the habitat capacity (ecospace.habitat_capacity) applies with or without them (B4).

None
mpa MPAConfig

Marine protected areas; closes patches to some or all fleets

None
spatial_fishing SpatialFishing

How fleet effort is distributed across patches. Effort is redistributed relative to the grid mean, so total fleet effort is unchanged and "uniform" reproduces a run with no spatial fishing (except for EwE mediation shapes mediated by a fleet, which follow each patch's effort with an allocation and count the fleet at effort 1 without one).

None
initial_state_vector ndarray

Flattened initial coupled state vector with shape [(n_groups+1) * n_patches]. If omitted, start biomass is distributed by patch area, so every patch starts at the same density.

None
store_state_vectors bool

If True, stores per-timestep flattened state vectors as output.out_StateVector for coupled workflow diagnostics.

False
implicit_movement bool

Diffuse implicitly (default): diffusion leaves the RK4 derivative and each dispersing group is moved by backward Euler after every RK4 step (dispersal.implicit_diffusion_step), which is stable at any rate. Advection and external fluxes stay in the derivative. Fast- equilibrium groups are not moved, as their biomass is set from their local equilibrium at every step (EwE rule). False keeps diffusion in the derivative, as before B3; it is stable only to about 4.2 x RK4_STEPS per year per cell side on a rook grid.

True
on_month callable

Called as on_month(month, n_months) once per simulated month, on the calling thread, after that month's biomass is stored; month counts from 1. Use it to report progress. Returning the bool True stops the run with RunCancelled (any other value, truthy or not, lets it go on), as in rsim_run. Without ecospace it is passed to rsim_run.

None
n_jobs int

Worker processes for the patches' local dynamics. 1 (default) runs them one after another in this process. A larger number starts that many processes for the run, each taking a share of the patches at every derivative evaluation; -1 uses one per CPU this process may use. Never more than the number of patches. The results are the serial run's, bit for bit. It pays off on grids of a few hundred patches with 4 or more workers: the Black Sea test model (304 patches, 3 years) ran 1.2 times faster with 2 workers, 2.3 with 4 and 3.1 with 8, on a busy 28-core machine. The workers take a second or two to start, and every evaluation hands them the run's parameters, so a small grid or a short run gains nothing. Movement, stanzas and the month's bookkeeping stay in this process. With IBM groups, or without ecospace, the run is serial whatever n_jobs says. In the workers warnings are ignored and numpy's default error handling applies: the caller's warning filters and np.seterr do not reach them.

1
mp_context str

The multiprocessing start method for the workers: "forkserver", "spawn" or "fork". None uses forkserver on Linux and spawn on macOS and Windows. Call from under if __name__ == "__main__": in a script, as these methods import the main module in each worker. Avoid "fork" in a program that runs threads.

None

Returns:

Type Description
RsimOutput

Simulation results - out_Biomass: Total biomass (summed over patches) for compatibility - out_Biomass_spatial: Spatial biomass [n_months, n_groups+1, n_patches] (if spatial) - Other outputs as per standard Ecosim

Examples:

>>> # Non-spatial (standard Ecosim)
>>> result = rsim_run_spatial(scenario)
>>> # Spatial ECOSPACE
>>> from pypath.spatial import EcospaceGrid, EcospaceParams
>>> grid = EcospaceGrid.from_shapefile('grid.shp')
>>> ecospace = EcospaceParams(grid, ...)
>>> result = rsim_run_spatial(scenario, ecospace=ecospace)
>>> spatial_biomass = result.out_Biomass_spatial  # [n_months, n_groups, n_patches]
>>> total_biomass = result.out_Biomass  # [n_months, n_groups] (summed over patches)
Source code in pypath/spatial/integration.py
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
def rsim_run_spatial(
    scenario: RsimScenario,
    method: str = "RK4",
    years: Optional[range] = None,
    ecospace: Optional[EcospaceParams] = None,
    environmental_drivers: Optional[EnvironmentalDrivers] = None,
    *,
    mpa: Optional["MPAConfig"] = None,
    spatial_fishing: Optional["SpatialFishing"] = None,
    initial_state_vector: Optional[np.ndarray] = None,
    store_state_vectors: bool = False,
    implicit_movement: bool = True,
    on_month: Optional[Callable[[int, int], Optional[bool]]] = None,
    n_jobs: int = 1,
    mp_context: Optional[str] = None,
) -> RsimOutput:
    """Run spatial Ecosim simulation.

    Wrapper for Ecosim that extends to spatial grids. If ecospace is None,
    falls back to standard non-spatial Ecosim.

    Parameters
    ----------
    scenario : RsimScenario
        Simulation scenario (params, forcing, fishing, start state)
    method : str
        Integration method (default: 'RK4')
        Currently only RK4 is implemented
    years : range, optional
        Years to simulate (default: use scenario years). As in ``rsim_run``
        it must start at ``scenario.start_year`` (the first ``len(years)``
        years are run), else ``ValueError``. Example: range(1, 101) for 100
        years of a scenario starting in year 1
    ecospace : EcospaceParams, optional
        Spatial parameters
        If None, runs standard non-spatial Ecosim
    environmental_drivers : EnvironmentalDrivers, optional
        Time-varying environmental layers. Not evaluated in the run; the
        habitat capacity (``ecospace.habitat_capacity``) applies with or
        without them (B4).
    mpa : MPAConfig, optional
        Marine protected areas; closes patches to some or all fleets
    spatial_fishing : SpatialFishing, optional
        How fleet effort is distributed across patches. Effort is redistributed
        relative to the grid mean, so total fleet effort is unchanged and
        "uniform" reproduces a run with no spatial fishing (except for EwE
        mediation shapes mediated by a fleet, which follow each patch's effort
        with an allocation and count the fleet at effort 1 without one).
    initial_state_vector : np.ndarray, optional
        Flattened initial coupled state vector with shape
        ``[(n_groups+1) * n_patches]``. If omitted, start biomass is
        distributed by patch area, so every patch starts at the same density.
    store_state_vectors : bool
        If True, stores per-timestep flattened state vectors as
        ``output.out_StateVector`` for coupled workflow diagnostics.
    implicit_movement : bool
        Diffuse implicitly (default): diffusion leaves the RK4 derivative and
        each dispersing group is moved by backward Euler after every RK4 step
        (``dispersal.implicit_diffusion_step``), which is stable at any rate.
        Advection and external fluxes stay in the derivative. Fast-
        equilibrium groups are not moved, as their biomass is set from their
        local equilibrium at every step (EwE rule). ``False`` keeps diffusion
        in the derivative, as before B3; it is stable only to about
        4.2 x RK4_STEPS per year per cell side on a rook grid.
    on_month : callable, optional
        Called as ``on_month(month, n_months)`` once per simulated month, on
        the calling thread, after that month's biomass is stored; ``month``
        counts from 1. Use it to report progress. Returning the bool True
        stops the run with ``RunCancelled`` (any other value, truthy or not,
        lets it go on), as in ``rsim_run``. Without ``ecospace`` it is passed
        to ``rsim_run``.
    n_jobs : int
        Worker processes for the patches' local dynamics. 1 (default) runs
        them one after another in this process. A larger number starts that
        many processes for the run, each taking a share of the patches at
        every derivative evaluation; -1 uses one per CPU this process may
        use. Never more than the number of patches. The results are the
        serial run's, bit for bit. It pays off on grids of a few hundred
        patches with 4 or more workers: the Black Sea test model (304
        patches, 3 years) ran 1.2 times faster with 2 workers, 2.3 with 4
        and 3.1 with 8, on a busy 28-core machine. The workers take a
        second or two to start, and every evaluation hands them the run's
        parameters, so a small grid or a short run gains nothing. Movement,
        stanzas and the month's bookkeeping stay in this process. With IBM
        groups, or without ``ecospace``, the run is serial whatever
        ``n_jobs`` says. In the workers warnings are ignored and numpy's
        default error handling applies: the caller's warning filters and
        ``np.seterr`` do not reach them.
    mp_context : str, optional
        The multiprocessing start method for the workers: "forkserver",
        "spawn" or "fork". None uses forkserver on Linux and spawn on macOS
        and Windows. Call from under ``if __name__ == "__main__":`` in a
        script, as these methods import the main module in each worker.
        Avoid "fork" in a program that runs threads.

    Returns
    -------
    RsimOutput
        Simulation results
        - out_Biomass: Total biomass (summed over patches) for compatibility
        - out_Biomass_spatial: Spatial biomass [n_months, n_groups+1, n_patches] (if spatial)
        - Other outputs as per standard Ecosim

    Examples
    --------
    >>> # Non-spatial (standard Ecosim)
    >>> result = rsim_run_spatial(scenario)

    >>> # Spatial ECOSPACE
    >>> from pypath.spatial import EcospaceGrid, EcospaceParams
    >>> grid = EcospaceGrid.from_shapefile('grid.shp')
    >>> ecospace = EcospaceParams(grid, ...)
    >>> result = rsim_run_spatial(scenario, ecospace=ecospace)
    >>> spatial_biomass = result.out_Biomass_spatial  # [n_months, n_groups, n_patches]
    >>> total_biomass = result.out_Biomass  # [n_months, n_groups] (summed over patches)
    """
    context = mp_context_for(mp_context)  # refuses an unknown method
    # biomass forcing of stanza groups cannot hold: dropped, with a warning
    # (as rsim_run)
    from pypath.core.ecosim import _without_stanza_forced_biomass

    scenario, run_notes = _without_stanza_forced_biomass(scenario)
    run = dict(
        scenario=scenario,
        method=method,
        years=years,
        ecospace=ecospace,
        environmental_drivers=environmental_drivers,
        mpa=mpa,
        spatial_fishing=spatial_fishing,
        initial_state_vector=initial_state_vector,
        store_state_vectors=store_state_vectors,
        implicit_movement=implicit_movement,
        on_month=on_month,
    )
    if ecospace is None:
        resolve_n_jobs(n_jobs, 1)  # checked, though nothing runs in workers
        return _with_notes(_run_spatial(**run), run_notes)
    n_workers = _n_patch_workers(scenario, ecospace, n_jobs)
    if n_workers == 1:
        return _with_notes(_run_spatial(**run), run_notes)

    pool = ProcessPoolExecutor(max_workers=n_workers, mp_context=context)
    finished = False
    try:
        output = _run_spatial(**run, patch_pool=(pool, n_workers))
        finished = True
        return _with_notes(output, run_notes)
    except BrokenProcessPool as exc:
        raise BrokenProcessPool(
            "An Ecospace worker process died. It may have run out of memory, "
            "or failed to unpickle the model: a mediation class must be "
            "importable from a module, not defined in a notebook or in "
            "__main__. Try n_jobs=1."
        ) from exc
    finally:
        # After an error or a cancel the tasks in flight are not waited for.
        pool.shutdown(wait=finished, cancel_futures=True)

Ecospace Calibration

EwE's Ecospace base calibration (AdjustSpaceParsNew), mapped onto the consumption kernel: the search and vulnerability rates for groups spread by habitat capacity.

pypath.spatial.calibration

EwE's Ecospace base calibration, mapped onto PyPath's consumption kernel.

EwE 6.7.144 sets Ecospace's search and vulnerability rates in AdjustSpaceParsNew (cEcoSpace.vb 6036-6180) so that, with every group spread in proportion to its habitat capacity, map-wide consumption follows Ecopath's:

  • BRatio = ThabArea / TotHabCap: a group's density in its habitat over its map-wide mean, and its base biomass B0 x BRatio;
  • Vspace = X x Qarena / (B0_prey x BRatio_prey) with Qarena = Q0 x BRatio_pred (one predator per arena), floored at Ecosim's vulnerability rate X x Q0 / B0_prey;
  • search rates from five passes of A = Q0 / (Vtemp x MeanBP), Vtemp = Vspace / (2 Vspace + A x Pbar), MeanBP the map-wide mean of HabCap_prey x HabCap_pred times the base densities, Pbar = B0_pred x BRatio_pred; the passes stop early when the change is small, and on donor-controlled links (X near 1) they do not converge, so EwE's map-wide base flow there is below Ecopath's;
  • producers' shading PbSpace = pbbiomass / BRatio.

In a cell EwE eats A V B_prey P / (2V + A P / EatEff_pred) (handling aside), with EatEff = HabCap. PyPath's kernel eats QQ x PDY x PYY x X / (X - 1 + PDY / EatEff) on biomass relative to a base. The two are the same with the base B0 x BRatio for every group and, per link, X' = 1 + 2 Vspace / (A x Pb) and QQ' = Vspace x Bb_prey / X' (Pb, Bb the predator's and prey's bases). With a uniform habitat this gives back Ecosim's X and Q0 exactly. A producer's gain is its link from group 0; PbSpace = pbbiomass / BRatio on the base B0 x BRatio is that link with QQ' = Q0 x BRatio and its X unchanged.

SpaceCalibration dataclass

Ecospace's base parameters for PyPath's kernel.

Attributes:

Name Type Description
bbase ndarray

Every group's base density, B0 x BRatio [n_groups + 1].

qq ndarray

Base flows QQ' [prey, pred]; the producers' links from group 0 carry Q0 x BRatio.

vv ndarray

Vulnerabilities X' [prey, pred].

bratio ndarray

BRatio = map-wide mean / mean over the habitat [n_groups + 1].

vspace ndarray

EwE's Vspace by link [prey, pred] (0 where there is no link).

search ndarray

EwE's search rate before the handling correction (Atemp) [prey, pred].

Source code in pypath/spatial/calibration.py
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
@dataclass
class SpaceCalibration:
    """Ecospace's base parameters for PyPath's kernel.

    Attributes
    ----------
    bbase : np.ndarray
        Every group's base density, B0 x BRatio [n_groups + 1].
    qq : np.ndarray
        Base flows QQ' [prey, pred]; the producers' links from group 0 carry
        Q0 x BRatio.
    vv : np.ndarray
        Vulnerabilities X' [prey, pred].
    bratio : np.ndarray
        BRatio = map-wide mean / mean over the habitat [n_groups + 1].
    vspace : np.ndarray
        EwE's Vspace by link [prey, pred] (0 where there is no link).
    search : np.ndarray
        EwE's search rate before the handling correction (Atemp) [prey, pred].
    """

    bbase: np.ndarray
    qq: np.ndarray
    vv: np.ndarray
    bratio: np.ndarray
    vspace: np.ndarray
    search: np.ndarray

ewe_space_calibration

ewe_space_calibration(b0: ndarray, qq: ndarray, vv: ndarray, capacity: ndarray, patch_share: Optional[ndarray] = None) -> SpaceCalibration

EwE's AdjustSpaceParsNew, as PyPath kernel parameters.

Parameters:

Name Type Description Default
b0 ndarray

Base biomass by group, index 0 the outside [n_groups + 1].

required
qq ndarray

Ecopath base flows [prey, pred], row 0 the producers' links.

required
vv ndarray

Ecosim vulnerabilities X [prey, pred].

required
capacity ndarray

Habitat capacity per group and patch [n_groups + 1, n_patches]; row 0 and groups without habitat are 1.

required
patch_share ndarray

Patch area fractions (equal patches when omitted).

None

Returns:

Type Description
SpaceCalibration
Source code in pypath/spatial/calibration.py
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
def ewe_space_calibration(
    b0: np.ndarray,
    qq: np.ndarray,
    vv: np.ndarray,
    capacity: np.ndarray,
    patch_share: Optional[np.ndarray] = None,
) -> SpaceCalibration:
    """EwE's AdjustSpaceParsNew, as PyPath kernel parameters.

    Parameters
    ----------
    b0 : np.ndarray
        Base biomass by group, index 0 the outside [n_groups + 1].
    qq : np.ndarray
        Ecopath base flows [prey, pred], row 0 the producers' links.
    vv : np.ndarray
        Ecosim vulnerabilities X [prey, pred].
    capacity : np.ndarray
        Habitat capacity per group and patch [n_groups + 1, n_patches]; row 0
        and groups without habitat are 1.
    patch_share : np.ndarray, optional
        Patch area fractions (equal patches when omitted).

    Returns
    -------
    SpaceCalibration
    """
    b0 = np.asarray(b0, dtype=float)
    q0 = np.asarray(qq, dtype=float)
    x0 = np.asarray(vv, dtype=float)
    cap = np.asarray(capacity, dtype=float)
    n = cap.shape[1]
    w = (
        np.full(n, 1.0 / n)
        if patch_share is None
        else np.asarray(patch_share, dtype=float)
    )
    br = habitat_ratio(cap, w)
    br[0] = 1.0

    qq_new, vv_new = q0.copy(), x0.copy()
    vspace = np.zeros_like(q0)
    search = np.zeros_like(q0)
    prey, pred = np.nonzero(q0 > 0)
    keep = (prey >= 1) & (pred >= 1)
    prey, pred = prey[keep], pred[keep]
    if len(prey):
        q = q0[prey, pred]
        x = x0[prey, pred] + 1e-10  # EwE adds 1e-10 to VulMult
        qarena = q * br[pred]
        v = x * qarena / (b0[prey] * br[prey])
        v = np.where(v == 0, 1.0, v)
        # Ecosim's VulArena (cEcoSimModel.vb 5384) is Vspace's floor (vb 6090)
        v = np.maximum(v, x * q / b0[prey])
        vul_biom = (x - 1.0) * qarena / (2.0 * v)
        vul_biom = np.where(vul_biom == 0, 1.0, vul_biom)
        # the predator index: X' and QQ' do not depend on its scale
        a = np.where(vul_biom > 0, q / (vul_biom * b0[pred]), 0.0)
        pbar = b0 * br
        overlap = (cap * w[np.newaxis, :]) @ cap.T
        mean_bp = overlap[prey, pred] * b0[prey] * b0[pred] * br[prey] * br[pred]
        for _ in range(5):  # vb 6147-6174
            vtemp = v / (2.0 * v + a * pbar[pred])
            new = np.where(
                mean_bp > 0, q / (vtemp * np.where(mean_bp > 0, mean_bp, 1.0)), a
            )
            change = np.abs(new - a).sum()
            a = new
            if change < 0.01 * len(q):
                break
        pb = b0[pred] * br[pred]
        x_new = 1.0 + 2.0 * v / (a * pb)
        qq_new[prey, pred] = v * b0[prey] * br[prey] / x_new
        vv_new[prey, pred] = x_new
        vspace[prey, pred] = v
        search[prey, pred] = a
    # producers' links from group 0: PbSpace = pbbiomass / BRatio
    sun = np.nonzero(q0[0] > 0)[0]
    qq_new[0, sun] = q0[0, sun] * br[sun]
    return SpaceCalibration(
        bbase=b0 * br, qq=qq_new, vv=vv_new, bratio=br, vspace=vspace, search=search
    )

habitat_ratio

habitat_ratio(capacity: ndarray, patch_share: Optional[ndarray] = None) -> np.ndarray

EwE's BRatio = ThabArea / TotHabCap of each group row of capacity.

capacity holds each group's habitat capacity per patch (rows by group). The ratio is 1 / the area-weighted mean capacity.

Source code in pypath/spatial/calibration.py
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
def habitat_ratio(
    capacity: np.ndarray, patch_share: Optional[np.ndarray] = None
) -> np.ndarray:
    """EwE's BRatio = ThabArea / TotHabCap of each group row of ``capacity``.

    ``capacity`` holds each group's habitat capacity per patch (rows by
    group). The ratio is 1 / the area-weighted mean capacity.
    """
    cap = np.asarray(capacity, dtype=float)
    n = cap.shape[1]
    w = (
        np.full(n, 1.0 / n)
        if patch_share is None
        else np.asarray(patch_share, dtype=float)
    )
    mean = (cap * w[np.newaxis, :]).sum(axis=1)
    return np.where(mean > 0, 1.0 / np.where(mean > 0, mean, 1.0), 1.0)

Multi-stanza Distribution

EwE's NewMultiStanza model: a population index per patch and life stage that spreads each stage's map-wide total and weights the age structure's update. EcospaceParams.new_multi_stanza switches it.

pypath.spatial.stanza_space

EwE's NewMultiStanza distribution of stanza groups over Ecospace patches.

EwE 6.7.144's Ecospace (ModelType 2, its default for a new scenario) does not integrate a multi-stanza group cell by cell. Each life stage keeps a population index W per cell (Bcell(nvar2 + isc)), solved with the other groups each time step (cSpaceSolver.vb 665-720):

dW/dt = Rflow - Z W + movement
  • Z is the cell's loss rate of the stage group, loss / B (FlowoutRate), or 100 where the cell holds none;
  • Rflow is RelR (1 - exp(-Z Tstanza)) for the first stage, with RelR the cell's adult density over the adults' start biomass (RelRepStanza), and the previous stage's density for the others;
  • W moves between cells like the stage group itself. PyPath's index carries the capacity-weighted diffusion only, so a species with a stage moved by an external flux or habitat-directed advection keeps the patch-share rule (rsim_run_spatial leaves it out).

EwE leaves the stage groups out of the integration (ByPassIntegrate). Every step it updates the map-wide age structure with the cells' rates averaged by W (SpaceSplitUpdate, cEcoSpace.vb 7451-7470) and spreads each stage's new total over the cells in proportion to W (UpdateMultiStanza, 7406-7445). The W it spreads by is the one read before the step's solve. The index starts at RecSplit / Z x the cell's habitat capacity over the map's mean (NstanzaBase, 3187-3210 and 2569).

PyPath keeps biomass as amounts per patch (density x area share), so W, a density, weighs each patch by its area. One step is backward Euler on the local terms, then the stage's implicit movement step on the amounts W x area. EwE solves both together, with its second-order time step.

StanzaSpaceIndex dataclass

Per-patch population index of each life stage (EwE's NewMultiStanza).

Parameters:

Name Type Description Default
species list of (rows, tstanza)

For each multi-stanza species, its stage groups' state rows (Rsim indexing, youngest first) and each stage's duration in years, (Age2 - Age1 + 1) / 12.

required
patch_share ndarray

Each patch's share of the map's area.

required
Source code in pypath/spatial/stanza_space.py
 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
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
@dataclass
class StanzaSpaceIndex:
    """Per-patch population index of each life stage (EwE's NewMultiStanza).

    Parameters
    ----------
    species : list of (rows, tstanza)
        For each multi-stanza species, its stage groups' state rows (Rsim
        indexing, youngest first) and each stage's duration in years,
        (Age2 - Age1 + 1) / 12.
    patch_share : np.ndarray
        Each patch's share of the map's area.
    """

    species: List[Tuple[List[int], List[float]]]
    patch_share: np.ndarray
    index: Dict[int, np.ndarray] = field(default_factory=dict)
    adult_start: Dict[int, float] = field(default_factory=dict)

    @classmethod
    def from_stanzas(cls, stanzas, patch_share, leave_out=()) -> "StanzaSpaceIndex":
        """Read the stages from an ``RsimStanzas``-like object.

        A species with a stage row in ``leave_out`` gets no index.
        """
        leave_out = {int(r) for r in leave_out}
        code = np.asarray(stanzas.ecopath_code, dtype=float)
        age1 = np.asarray(stanzas.age1, dtype=float)
        age2 = np.asarray(stanzas.age2, dtype=float)
        n_stanzas = np.asarray(stanzas.n_stanzas)
        species = []
        for isp in range(1, int(stanzas.n_split) + 1):
            stages = range(1, int(n_stanzas[isp]) + 1)
            if leave_out & {int(code[isp, ist]) for ist in stages}:
                continue
            species.append(
                (
                    [int(code[isp, ist]) for ist in stages],
                    [(age2[isp, ist] - age1[isp, ist] + 1) / 12.0 for ist in stages],
                )
            )
        return cls(species, np.asarray(patch_share, dtype=float))

    @property
    def started(self) -> bool:
        return bool(self.index)

    def _loss_rate(self, biomass, loss_prop_to_b, row):
        b = biomass[row]
        with np.errstate(divide="ignore", invalid="ignore"):
            return np.where(
                b > _EMPTY,
                loss_prop_to_b[row] / np.where(b > _EMPTY, b, 1.0),
                EMPTY_CELL_LOSS_RATE,
            )

    def start(self, biomass: np.ndarray, loss_prop_to_b: np.ndarray) -> None:
        """Set EwE's start index, NstanzaBase x relative capacity.

        ``biomass`` and ``loss_prop_to_b`` hold each patch's amounts at the
        start; the map-wide loss rate stands in for EwE's FlowoutRate at the
        start biomass, and a patch's density over the map's mean for
        HabCap x nWater / TotHabCap.
        """
        for rows, tstanza in self.species:
            survivors = 1.0
            for k, row in enumerate(rows):
                total = float(biomass[row].sum())
                z = float(loss_prop_to_b[row].sum()) / total if total > 0 else 0.0
                remaining = survivors * np.exp(-tstanza[k] * z)
                rec = survivors - remaining if k < len(rows) - 1 else survivors
                survivors = remaining
                relative = (
                    biomass[row] / self.patch_share / total
                    if total > 0
                    else np.ones_like(self.patch_share)
                )
                self.index[row] = rec / z * relative if z > 0 else relative.copy()
            self.adult_start[rows[-1]] = float(biomass[rows[-1]].sum())

    def weighted_sums(self, biomass, food_gain, loss_prop_to_b):
        """Map-wide biomass, consumption and losses for the age structure.

        Groups without stanzas get the plain sums over the patches. A stage
        gets EwE's averages over the cells weighted by W (TotBiom, TotEatenBy,
        TotLoss). EwE's cells all count alike (ThabArea counts them); here a
        patch counts by its area, so each is the sum of the patch amounts x W
        over the sum of share x W, with share the patch's part of the stage's
        biomass: the plain sums when W is uniform, and EwE's sums of cell
        densities x W when the patches have equal areas. Divided by the age
        structure's map-wide pred, the consumption gives EwE's
        TotEatenBy / TotPred, as each cell's pred is its share of the map's.
        """
        sums = [
            np.asarray(a, dtype=float).sum(axis=1)
            for a in (biomass, food_gain, loss_prop_to_b)
        ]
        for row, w in self.index.items():
            total = biomass[row].sum()
            share = biomass[row] / total if total > 0 else self.patch_share
            norm = float(np.sum(share * w))
            if norm > 0:
                for out, a in zip(sums, (biomass, food_gain, loss_prop_to_b)):
                    out[row] = float(np.sum(a[row] * w)) / norm
        return tuple(sums)

    def distribute(self, total: np.ndarray, biomass: np.ndarray) -> np.ndarray:
        """Spread each stage's map-wide total over the patches by W.

        Returns a copy of ``biomass`` with the stage rows replaced; a stage
        whose index is zero everywhere keeps its current shares.
        """
        out = np.array(biomass, dtype=float, copy=True)
        for row, w in self.index.items():
            amounts = w * self.patch_share
            s = amounts.sum()
            if s > 0:
                out[row] = total[row] * amounts / s
            else:
                current = out[row].sum()
                share = out[row] / current if current > 0 else self.patch_share
                out[row] = total[row] * share
        return out

    def advance(
        self,
        biomass: np.ndarray,
        loss_prop_to_b: np.ndarray,
        dt: float,
        move: Optional[Callable[[int, np.ndarray], np.ndarray]] = None,
    ) -> None:
        """One time step of the index from the step's start state.

        ``move(row, amounts)``, if given, moves the amounts W x area of the
        stage group ``row`` over the step and returns them.
        """
        density = biomass / self.patch_share[None, :]
        for rows, tstanza in self.species:
            adult = rows[-1]
            relr = (
                density[adult] / self.adult_start[adult]
                if self.adult_start[adult] > 0
                else 0.0
            )
            for k, row in enumerate(rows):
                z = self._loss_rate(biomass, loss_prop_to_b, row)
                if k == 0:
                    rflow = relr * (1.0 - np.exp(-z * tstanza[0]))
                else:
                    rflow = density[rows[k - 1]]
                w = (self.index[row] + dt * rflow) / (1.0 + dt * z)
                if move is not None:
                    w = move(row, w * self.patch_share) / self.patch_share
                self.index[row] = np.maximum(w, 0.0)
advance
advance(biomass: ndarray, loss_prop_to_b: ndarray, dt: float, move: Optional[Callable[[int, ndarray], ndarray]] = None) -> None

One time step of the index from the step's start state.

move(row, amounts), if given, moves the amounts W x area of the stage group row over the step and returns them.

Source code in pypath/spatial/stanza_space.py
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
def advance(
    self,
    biomass: np.ndarray,
    loss_prop_to_b: np.ndarray,
    dt: float,
    move: Optional[Callable[[int, np.ndarray], np.ndarray]] = None,
) -> None:
    """One time step of the index from the step's start state.

    ``move(row, amounts)``, if given, moves the amounts W x area of the
    stage group ``row`` over the step and returns them.
    """
    density = biomass / self.patch_share[None, :]
    for rows, tstanza in self.species:
        adult = rows[-1]
        relr = (
            density[adult] / self.adult_start[adult]
            if self.adult_start[adult] > 0
            else 0.0
        )
        for k, row in enumerate(rows):
            z = self._loss_rate(biomass, loss_prop_to_b, row)
            if k == 0:
                rflow = relr * (1.0 - np.exp(-z * tstanza[0]))
            else:
                rflow = density[rows[k - 1]]
            w = (self.index[row] + dt * rflow) / (1.0 + dt * z)
            if move is not None:
                w = move(row, w * self.patch_share) / self.patch_share
            self.index[row] = np.maximum(w, 0.0)
distribute
distribute(total: ndarray, biomass: ndarray) -> np.ndarray

Spread each stage's map-wide total over the patches by W.

Returns a copy of biomass with the stage rows replaced; a stage whose index is zero everywhere keeps its current shares.

Source code in pypath/spatial/stanza_space.py
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
def distribute(self, total: np.ndarray, biomass: np.ndarray) -> np.ndarray:
    """Spread each stage's map-wide total over the patches by W.

    Returns a copy of ``biomass`` with the stage rows replaced; a stage
    whose index is zero everywhere keeps its current shares.
    """
    out = np.array(biomass, dtype=float, copy=True)
    for row, w in self.index.items():
        amounts = w * self.patch_share
        s = amounts.sum()
        if s > 0:
            out[row] = total[row] * amounts / s
        else:
            current = out[row].sum()
            share = out[row] / current if current > 0 else self.patch_share
            out[row] = total[row] * share
    return out
from_stanzas classmethod
from_stanzas(stanzas, patch_share, leave_out=()) -> 'StanzaSpaceIndex'

Read the stages from an RsimStanzas-like object.

A species with a stage row in leave_out gets no index.

Source code in pypath/spatial/stanza_space.py
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
@classmethod
def from_stanzas(cls, stanzas, patch_share, leave_out=()) -> "StanzaSpaceIndex":
    """Read the stages from an ``RsimStanzas``-like object.

    A species with a stage row in ``leave_out`` gets no index.
    """
    leave_out = {int(r) for r in leave_out}
    code = np.asarray(stanzas.ecopath_code, dtype=float)
    age1 = np.asarray(stanzas.age1, dtype=float)
    age2 = np.asarray(stanzas.age2, dtype=float)
    n_stanzas = np.asarray(stanzas.n_stanzas)
    species = []
    for isp in range(1, int(stanzas.n_split) + 1):
        stages = range(1, int(n_stanzas[isp]) + 1)
        if leave_out & {int(code[isp, ist]) for ist in stages}:
            continue
        species.append(
            (
                [int(code[isp, ist]) for ist in stages],
                [(age2[isp, ist] - age1[isp, ist] + 1) / 12.0 for ist in stages],
            )
        )
    return cls(species, np.asarray(patch_share, dtype=float))
start
start(biomass: ndarray, loss_prop_to_b: ndarray) -> None

Set EwE's start index, NstanzaBase x relative capacity.

biomass and loss_prop_to_b hold each patch's amounts at the start; the map-wide loss rate stands in for EwE's FlowoutRate at the start biomass, and a patch's density over the map's mean for HabCap x nWater / TotHabCap.

Source code in pypath/spatial/stanza_space.py
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
def start(self, biomass: np.ndarray, loss_prop_to_b: np.ndarray) -> None:
    """Set EwE's start index, NstanzaBase x relative capacity.

    ``biomass`` and ``loss_prop_to_b`` hold each patch's amounts at the
    start; the map-wide loss rate stands in for EwE's FlowoutRate at the
    start biomass, and a patch's density over the map's mean for
    HabCap x nWater / TotHabCap.
    """
    for rows, tstanza in self.species:
        survivors = 1.0
        for k, row in enumerate(rows):
            total = float(biomass[row].sum())
            z = float(loss_prop_to_b[row].sum()) / total if total > 0 else 0.0
            remaining = survivors * np.exp(-tstanza[k] * z)
            rec = survivors - remaining if k < len(rows) - 1 else survivors
            survivors = remaining
            relative = (
                biomass[row] / self.patch_share / total
                if total > 0
                else np.ones_like(self.patch_share)
            )
            self.index[row] = rec / z * relative if z > 0 else relative.copy()
        self.adult_start[rows[-1]] = float(biomass[rows[-1]].sum())
weighted_sums
weighted_sums(biomass, food_gain, loss_prop_to_b)

Map-wide biomass, consumption and losses for the age structure.

Groups without stanzas get the plain sums over the patches. A stage gets EwE's averages over the cells weighted by W (TotBiom, TotEatenBy, TotLoss). EwE's cells all count alike (ThabArea counts them); here a patch counts by its area, so each is the sum of the patch amounts x W over the sum of share x W, with share the patch's part of the stage's biomass: the plain sums when W is uniform, and EwE's sums of cell densities x W when the patches have equal areas. Divided by the age structure's map-wide pred, the consumption gives EwE's TotEatenBy / TotPred, as each cell's pred is its share of the map's.

Source code in pypath/spatial/stanza_space.py
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
def weighted_sums(self, biomass, food_gain, loss_prop_to_b):
    """Map-wide biomass, consumption and losses for the age structure.

    Groups without stanzas get the plain sums over the patches. A stage
    gets EwE's averages over the cells weighted by W (TotBiom, TotEatenBy,
    TotLoss). EwE's cells all count alike (ThabArea counts them); here a
    patch counts by its area, so each is the sum of the patch amounts x W
    over the sum of share x W, with share the patch's part of the stage's
    biomass: the plain sums when W is uniform, and EwE's sums of cell
    densities x W when the patches have equal areas. Divided by the age
    structure's map-wide pred, the consumption gives EwE's
    TotEatenBy / TotPred, as each cell's pred is its share of the map's.
    """
    sums = [
        np.asarray(a, dtype=float).sum(axis=1)
        for a in (biomass, food_gain, loss_prop_to_b)
    ]
    for row, w in self.index.items():
        total = biomass[row].sum()
        share = biomass[row] / total if total > 0 else self.patch_share
        norm = float(np.sum(share * w))
        if norm > 0:
            for out, a in zip(sums, (biomass, food_gain, loss_prop_to_b)):
                out[row] = float(np.sum(a[row] * w)) / norm
    return tuple(sums)

Advanced Movement

Higher-level movement utilities for behavioral migration, ontogenetic shifts, and predator-avoidance flows.

pypath.spatial.movement

Advanced movement models for ECOSPACE.

MovementKernel dataclass

Movement kernel parameters.

Source code in pypath/spatial/movement.py
10
11
12
13
14
15
16
@dataclass
class MovementKernel:
    """Movement kernel parameters."""

    rate: float
    preference_strength: float = 0.0
    avoidance_strength: float = 0.0

aggregation_index

aggregation_index(biomass: ndarray) -> float

Compute simple aggregation index (CV of biomass distribution).

Source code in pypath/spatial/movement.py
76
77
78
79
80
81
82
def aggregation_index(biomass: np.ndarray) -> float:
    """Compute simple aggregation index (CV of biomass distribution)."""
    biomass = np.asarray(biomass, dtype=float)
    mean = float(np.mean(biomass))
    if mean <= 0:
        return 0.0
    return float(np.std(biomass) / mean)

behavioral_migration

behavioral_migration(biomass: ndarray, habitat_quality: ndarray, adjacency: ndarray, kernel: MovementKernel) -> np.ndarray

Compute net movement toward high-quality habitat.

Source code in pypath/spatial/movement.py
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
def behavioral_migration(
    biomass: np.ndarray,
    habitat_quality: np.ndarray,
    adjacency: np.ndarray,
    kernel: MovementKernel,
) -> np.ndarray:
    """Compute net movement toward high-quality habitat."""
    biomass = np.asarray(biomass, dtype=float)
    habitat_quality = np.asarray(habitat_quality, dtype=float)
    adjacency = np.asarray(adjacency, dtype=float)
    if biomass.shape != habitat_quality.shape:
        raise ValueError("biomass and habitat_quality must have identical shape")

    pref = np.clip(habitat_quality, 0.0, None) ** (1.0 + kernel.preference_strength)
    base = adjacency * pref[np.newaxis, :]
    transitions = normalize_transition_matrix(base)
    outflow = biomass * kernel.rate
    inflow = transitions.T @ outflow
    return inflow - outflow

normalize_transition_matrix

normalize_transition_matrix(matrix: ndarray) -> np.ndarray

Normalize rows of a transition matrix to probabilities.

Source code in pypath/spatial/movement.py
19
20
21
22
23
24
25
26
27
28
29
def normalize_transition_matrix(matrix: np.ndarray) -> np.ndarray:
    """Normalize rows of a transition matrix to probabilities."""
    matrix = np.asarray(matrix, dtype=float)
    if matrix.ndim != 2 or matrix.shape[0] != matrix.shape[1]:
        raise ValueError("transition matrix must be square")
    row_sums = matrix.sum(axis=1, keepdims=True)
    normalized = np.zeros_like(matrix, dtype=float)
    with np.errstate(divide="ignore", invalid="ignore"):
        np.divide(matrix, row_sums, out=normalized, where=row_sums > 0)
    normalized[row_sums.squeeze() <= 0] = 0.0
    return normalized

ontogenetic_movement

ontogenetic_movement(juvenile_biomass: ndarray, adult_biomass: ndarray, nursery_quality: ndarray, feeding_quality: ndarray, maturation_rate: float) -> tuple[np.ndarray, np.ndarray]

Shift biomass from nursery-preferred juvenile stage to adult stage.

Source code in pypath/spatial/movement.py
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
def ontogenetic_movement(
    juvenile_biomass: np.ndarray,
    adult_biomass: np.ndarray,
    nursery_quality: np.ndarray,
    feeding_quality: np.ndarray,
    maturation_rate: float,
) -> tuple[np.ndarray, np.ndarray]:
    """Shift biomass from nursery-preferred juvenile stage to adult stage."""
    juvenile_biomass = np.asarray(juvenile_biomass, dtype=float)
    adult_biomass = np.asarray(adult_biomass, dtype=float)
    nursery_quality = np.asarray(nursery_quality, dtype=float)
    feeding_quality = np.asarray(feeding_quality, dtype=float)

    recruit = juvenile_biomass * np.clip(maturation_rate, 0.0, 1.0)
    destination_weight = np.clip(feeding_quality, 0.0, None)
    destination_weight = destination_weight / max(destination_weight.sum(), 1e-12)

    juvenile_next = juvenile_biomass - recruit
    adult_next = adult_biomass + recruit.sum() * destination_weight
    juvenile_next *= np.clip(nursery_quality, 0.0, 1.0)
    return juvenile_next, adult_next

predator_avoidance_movement

predator_avoidance_movement(prey_biomass: ndarray, predator_pressure: ndarray, adjacency: ndarray, kernel: MovementKernel) -> np.ndarray

Move prey away from patches with high predator pressure.

Source code in pypath/spatial/movement.py
85
86
87
88
89
90
91
92
93
94
95
96
def predator_avoidance_movement(
    prey_biomass: np.ndarray,
    predator_pressure: np.ndarray,
    adjacency: np.ndarray,
    kernel: MovementKernel,
) -> np.ndarray:
    """Move prey away from patches with high predator pressure."""
    prey_biomass = np.asarray(prey_biomass, dtype=float)
    predator_pressure = np.asarray(predator_pressure, dtype=float)
    risk = np.clip(predator_pressure, 0.0, None)
    safety = 1.0 / (1.0 + kernel.avoidance_strength * risk)
    return behavioral_migration(prey_biomass, safety, adjacency, kernel)

Larval Dispersal

Larval advection, settlement, and source-sink connectivity helpers.

pypath.spatial.larval_dispersal

Larval dispersal and settlement utilities for ECOSPACE.

LarvalDispersalParams dataclass

Parameters controlling larval drift and settlement.

Source code in pypath/spatial/larval_dispersal.py
10
11
12
13
14
15
16
@dataclass
class LarvalDispersalParams:
    """Parameters controlling larval drift and settlement."""

    mortality_rate: float = 0.1
    settlement_rate: float = 0.3
    retention_rate: float = 0.2

advect_larvae

advect_larvae(larvae: ndarray, transport_matrix: ndarray, params: LarvalDispersalParams) -> np.ndarray

Transport larval biomass using a row-stochastic transport matrix.

Source code in pypath/spatial/larval_dispersal.py
19
20
21
22
23
24
25
26
27
28
29
30
def advect_larvae(
    larvae: np.ndarray,
    transport_matrix: np.ndarray,
    params: LarvalDispersalParams,
) -> np.ndarray:
    """Transport larval biomass using a row-stochastic transport matrix."""
    larvae = np.asarray(larvae, dtype=float)
    transport = np.asarray(transport_matrix, dtype=float)
    moved = transport.T @ larvae
    survived = moved * (1.0 - np.clip(params.mortality_rate, 0.0, 1.0))
    retained = larvae * np.clip(params.retention_rate, 0.0, 1.0)
    return survived + retained

larval_connectivity_matrix

larval_connectivity_matrix(source_spawning: ndarray, transport_matrix: ndarray, params: LarvalDispersalParams) -> np.ndarray

Build source-to-destination larval connectivity matrix.

Source code in pypath/spatial/larval_dispersal.py
47
48
49
50
51
52
53
54
55
56
57
def larval_connectivity_matrix(
    source_spawning: np.ndarray,
    transport_matrix: np.ndarray,
    params: LarvalDispersalParams,
) -> np.ndarray:
    """Build source-to-destination larval connectivity matrix."""
    spawning = np.asarray(source_spawning, dtype=float)
    transport = np.asarray(transport_matrix, dtype=float)
    survival = 1.0 - np.clip(params.mortality_rate, 0.0, 1.0)
    settled_factor = np.clip(params.settlement_rate, 0.0, 1.0)
    return np.diag(spawning) @ transport * (survival * settled_factor)

settle_larvae

settle_larvae(larvae: ndarray, habitat_quality: ndarray, params: LarvalDispersalParams) -> tuple[np.ndarray, np.ndarray]

Settle a fraction of larvae based on habitat quality.

Source code in pypath/spatial/larval_dispersal.py
33
34
35
36
37
38
39
40
41
42
43
44
def settle_larvae(
    larvae: np.ndarray,
    habitat_quality: np.ndarray,
    params: LarvalDispersalParams,
) -> tuple[np.ndarray, np.ndarray]:
    """Settle a fraction of larvae based on habitat quality."""
    larvae = np.asarray(larvae, dtype=float)
    quality = np.clip(np.asarray(habitat_quality, dtype=float), 0.0, 1.0)
    settlement_fraction = np.clip(params.settlement_rate, 0.0, 1.0) * quality
    settled = larvae * settlement_fraction
    remaining = larvae - settled
    return settled, remaining

Spatial Forcing

Patch-resolved forcing fields for upwelling, latitudinal temperature gradients, and oxygen-minimum zone masks.

pypath.spatial.forcing

Spatial forcing fields for ECOSPACE.

SpatialForcingField dataclass

Time-varying forcing field [time, patch].

Source code in pypath/spatial/forcing.py
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
@dataclass
class SpatialForcingField:
    """Time-varying forcing field [time, patch]."""

    values: np.ndarray
    times: np.ndarray

    def value_at(self, t: float) -> np.ndarray:
        """Interpolate forcing values at time ``t``."""
        v = np.asarray(self.values, dtype=float)
        tt = np.asarray(self.times, dtype=float)
        if v.ndim != 2:
            raise ValueError("values must be 2D [time, patch]")
        if len(tt) != v.shape[0]:
            raise ValueError("times length must equal values time dimension")
        if t <= tt[0]:
            return v[0].copy()
        if t >= tt[-1]:
            return v[-1].copy()
        idx = np.searchsorted(tt, t)
        t0, t1 = tt[idx - 1], tt[idx]
        w = (t - t0) / (t1 - t0)
        return (1.0 - w) * v[idx - 1] + w * v[idx]
value_at
value_at(t: float) -> np.ndarray

Interpolate forcing values at time t.

Source code in pypath/spatial/forcing.py
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
def value_at(self, t: float) -> np.ndarray:
    """Interpolate forcing values at time ``t``."""
    v = np.asarray(self.values, dtype=float)
    tt = np.asarray(self.times, dtype=float)
    if v.ndim != 2:
        raise ValueError("values must be 2D [time, patch]")
    if len(tt) != v.shape[0]:
        raise ValueError("times length must equal values time dimension")
    if t <= tt[0]:
        return v[0].copy()
    if t >= tt[-1]:
        return v[-1].copy()
    idx = np.searchsorted(tt, t)
    t0, t1 = tt[idx - 1], tt[idx]
    w = (t - t0) / (t1 - t0)
    return (1.0 - w) * v[idx - 1] + w * v[idx]

coastal_upwelling_index

coastal_upwelling_index(wind_stress: ndarray, coastline_orientation: ndarray, upwelling_scale: float = 1.0) -> np.ndarray

Estimate patch upwelling from alongshore wind stress.

Source code in pypath/spatial/forcing.py
35
36
37
38
39
40
41
42
43
def coastal_upwelling_index(
    wind_stress: np.ndarray,
    coastline_orientation: np.ndarray,
    upwelling_scale: float = 1.0,
) -> np.ndarray:
    """Estimate patch upwelling from alongshore wind stress."""
    wind = np.asarray(wind_stress, dtype=float)
    coast = np.asarray(coastline_orientation, dtype=float)
    return upwelling_scale * wind * np.sin(np.deg2rad(coast))

oxygen_minimum_zone_mask

oxygen_minimum_zone_mask(oxygen_concentration: ndarray, threshold: float = 2.0) -> np.ndarray

Boolean mask for oxygen minimum zones.

Source code in pypath/spatial/forcing.py
56
57
58
59
60
61
62
def oxygen_minimum_zone_mask(
    oxygen_concentration: np.ndarray,
    threshold: float = 2.0,
) -> np.ndarray:
    """Boolean mask for oxygen minimum zones."""
    oxygen = np.asarray(oxygen_concentration, dtype=float)
    return oxygen < threshold

temperature_gradient_field

temperature_gradient_field(base_temperature: float, latitudes: ndarray, lapse_per_degree: float = -0.3) -> np.ndarray

Create latitudinal temperature field.

Source code in pypath/spatial/forcing.py
46
47
48
49
50
51
52
53
def temperature_gradient_field(
    base_temperature: float,
    latitudes: np.ndarray,
    lapse_per_degree: float = -0.3,
) -> np.ndarray:
    """Create latitudinal temperature field."""
    lat = np.asarray(latitudes, dtype=float)
    return base_temperature + lapse_per_degree * (lat - np.mean(lat))

Ecological Interactions

Spatial predator-prey and metapopulation interaction helpers.

pypath.spatial.ecological_interactions

Spatial ecological interaction utilities.

EdgeEffectParams dataclass

Parameters controlling habitat edge effects.

Source code in pypath/spatial/ecological_interactions.py
10
11
12
13
14
15
@dataclass
class EdgeEffectParams:
    """Parameters controlling habitat edge effects."""

    edge_intensity: float = 0.2
    edge_width_cells: int = 1

apply_edge_effects

apply_edge_effects(habitat_quality: ndarray, edge_mask: ndarray, params: EdgeEffectParams) -> np.ndarray

Reduce habitat quality in edge cells.

Source code in pypath/spatial/ecological_interactions.py
32
33
34
35
36
37
38
39
40
41
def apply_edge_effects(
    habitat_quality: np.ndarray,
    edge_mask: np.ndarray,
    params: EdgeEffectParams,
) -> np.ndarray:
    """Reduce habitat quality in edge cells."""
    quality = np.asarray(habitat_quality, dtype=float).copy()
    mask = np.asarray(edge_mask, dtype=bool)
    quality[mask] *= max(0.0, 1.0 - params.edge_intensity)
    return np.clip(quality, 0.0, 1.0)

metapopulation_occupancy_step

metapopulation_occupancy_step(occupancy: ndarray, colonization_rate: float, extinction_rate: float, connectivity: ndarray) -> np.ndarray

Single Levins-style occupancy update with connectivity.

Source code in pypath/spatial/ecological_interactions.py
44
45
46
47
48
49
50
51
52
53
54
55
56
def metapopulation_occupancy_step(
    occupancy: np.ndarray,
    colonization_rate: float,
    extinction_rate: float,
    connectivity: np.ndarray,
) -> np.ndarray:
    """Single Levins-style occupancy update with connectivity."""
    occ = np.clip(np.asarray(occupancy, dtype=float), 0.0, 1.0)
    conn = np.asarray(connectivity, dtype=float)
    incoming = conn @ occ
    colonization = np.clip(colonization_rate, 0.0, 1.0) * (1.0 - occ) * incoming
    extinction = np.clip(extinction_rate, 0.0, 1.0) * occ
    return np.clip(occ + colonization - extinction, 0.0, 1.0)

spatial_predation_rate

spatial_predation_rate(predator_biomass: ndarray, prey_biomass: ndarray, encounter_kernel: ndarray, attack_rate: float) -> np.ndarray

Compute patchwise predation mortality on prey.

Source code in pypath/spatial/ecological_interactions.py
18
19
20
21
22
23
24
25
26
27
28
29
def spatial_predation_rate(
    predator_biomass: np.ndarray,
    prey_biomass: np.ndarray,
    encounter_kernel: np.ndarray,
    attack_rate: float,
) -> np.ndarray:
    """Compute patchwise predation mortality on prey."""
    predator = np.asarray(predator_biomass, dtype=float)
    prey = np.asarray(prey_biomass, dtype=float)
    kernel = np.asarray(encounter_kernel, dtype=float)
    encounters = kernel @ predator
    return np.clip(attack_rate, 0.0, None) * encounters * prey

Coupled Ecosim-Ecospace State Vector

Unified state-vector helpers for coupled simulations, including vector roundtrip conversions and runtime wrappers.

pypath.spatial.coupling

Coupled Ecosim-Ecospace state-vector utilities.

CoupledStateVector dataclass

Flattened coupled state vector representation.

Parameters:

Name Type Description Default
values ndarray

Flattened state vector with length (n_groups + 1) * n_patches.

required
n_groups int

Number of modeled groups (excluding Outside index).

required
n_patches int

Number of spatial patches.

required
Source code in pypath/spatial/coupling.py
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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
@dataclass(frozen=True)
class CoupledStateVector:
    """Flattened coupled state vector representation.

    Parameters
    ----------
    values : np.ndarray
        Flattened state vector with length ``(n_groups + 1) * n_patches``.
    n_groups : int
        Number of modeled groups (excluding Outside index).
    n_patches : int
        Number of spatial patches.
    """

    values: np.ndarray
    n_groups: int
    n_patches: int

    def __post_init__(self):
        values = np.asarray(self.values, dtype=float).reshape(-1)
        expected = (self.n_groups + 1) * self.n_patches
        if values.size != expected:
            raise ValueError(
                f"State vector length {values.size} does not match expected {expected}"
            )
        if np.any(values < 0):
            raise ValueError("State vector values must be non-negative")
        object.__setattr__(self, "values", values)

    def to_spatial_biomass(self) -> np.ndarray:
        """Return spatial biomass matrix ``[n_groups+1, n_patches]``."""
        return self.values.reshape(self.n_groups + 1, self.n_patches).copy()

    def to_total_biomass(self) -> np.ndarray:
        """Collapse spatial biomass to total biomass by group."""
        return self.to_spatial_biomass().sum(axis=1)

    @classmethod
    def from_spatial_biomass(cls, biomass_spatial: np.ndarray) -> "CoupledStateVector":
        """Create coupled vector from spatial biomass matrix."""
        arr = np.asarray(biomass_spatial, dtype=float)
        if arr.ndim != 2:
            raise ValueError("biomass_spatial must be 2D [n_groups+1, n_patches]")
        n_groups_plus_one, n_patches = arr.shape
        return cls(
            values=arr.reshape(-1), n_groups=n_groups_plus_one - 1, n_patches=n_patches
        )
from_spatial_biomass classmethod
from_spatial_biomass(biomass_spatial: ndarray) -> 'CoupledStateVector'

Create coupled vector from spatial biomass matrix.

Source code in pypath/spatial/coupling.py
52
53
54
55
56
57
58
59
60
61
@classmethod
def from_spatial_biomass(cls, biomass_spatial: np.ndarray) -> "CoupledStateVector":
    """Create coupled vector from spatial biomass matrix."""
    arr = np.asarray(biomass_spatial, dtype=float)
    if arr.ndim != 2:
        raise ValueError("biomass_spatial must be 2D [n_groups+1, n_patches]")
    n_groups_plus_one, n_patches = arr.shape
    return cls(
        values=arr.reshape(-1), n_groups=n_groups_plus_one - 1, n_patches=n_patches
    )
to_spatial_biomass
to_spatial_biomass() -> np.ndarray

Return spatial biomass matrix [n_groups+1, n_patches].

Source code in pypath/spatial/coupling.py
44
45
46
def to_spatial_biomass(self) -> np.ndarray:
    """Return spatial biomass matrix ``[n_groups+1, n_patches]``."""
    return self.values.reshape(self.n_groups + 1, self.n_patches).copy()
to_total_biomass
to_total_biomass() -> np.ndarray

Collapse spatial biomass to total biomass by group.

Source code in pypath/spatial/coupling.py
48
49
50
def to_total_biomass(self) -> np.ndarray:
    """Collapse spatial biomass to total biomass by group."""
    return self.to_spatial_biomass().sum(axis=1)

build_initial_state_vector

build_initial_state_vector(total_biomass: ndarray, n_patches: int, habitat_capacity: Optional[ndarray] = None) -> CoupledStateVector

Build an initial coupled state vector from group-level biomass totals.

Parameters:

Name Type Description Default
total_biomass ndarray

Group-level biomass vector [n_groups+1].

required
n_patches int

Number of patches.

required
habitat_capacity ndarray

Capacity matrix [n_groups, n_patches] used to weight initial distribution for living/detritus groups. Outside group (index 0) is always distributed uniformly.

None
Source code in pypath/spatial/coupling.py
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
def build_initial_state_vector(
    total_biomass: np.ndarray,
    n_patches: int,
    habitat_capacity: Optional[np.ndarray] = None,
) -> CoupledStateVector:
    """Build an initial coupled state vector from group-level biomass totals.

    Parameters
    ----------
    total_biomass : np.ndarray
        Group-level biomass vector ``[n_groups+1]``.
    n_patches : int
        Number of patches.
    habitat_capacity : np.ndarray, optional
        Capacity matrix ``[n_groups, n_patches]`` used to weight initial
        distribution for living/detritus groups. Outside group (index 0)
        is always distributed uniformly.
    """
    totals = np.asarray(total_biomass, dtype=float)
    if totals.ndim != 1:
        raise ValueError("total_biomass must be 1D")
    if np.any(totals < 0):
        raise ValueError("total_biomass must be non-negative")
    if n_patches <= 0:
        raise ValueError(f"n_patches must be positive, got {n_patches}")

    n_groups_plus_one = totals.size
    biomass_spatial = np.zeros((n_groups_plus_one, n_patches), dtype=float)

    # Outside / boundary pool
    biomass_spatial[0, :] = totals[0] / n_patches

    if habitat_capacity is None:
        biomass_spatial[1:, :] = totals[1:, np.newaxis] / n_patches
    else:
        cap = np.asarray(habitat_capacity, dtype=float)
        if cap.shape != (n_groups_plus_one - 1, n_patches):
            raise ValueError(
                f"habitat_capacity shape {cap.shape} must equal "
                f"({n_groups_plus_one - 1}, {n_patches})"
            )
        cap = np.clip(cap, 0.0, None)
        row_sum = cap.sum(axis=1, keepdims=True)
        row_sum[row_sum <= 0.0] = 1.0
        shares = cap / row_sum
        biomass_spatial[1:, :] = totals[1:, np.newaxis] * shares

    return CoupledStateVector.from_spatial_biomass(biomass_spatial)

run_coupled_simulation

run_coupled_simulation(scenario: 'RsimScenario', ecospace: 'EcospaceParams', years: Optional[range] = None, *, state_vector: Optional[ndarray] = None, store_state_vectors: bool = False, method: str = 'RK4', mpa=None, spatial_fishing=None, environmental_drivers=None, postprocess: Optional[Callable[['RsimOutput'], None]] = None)

Run a coupled Ecosim-Ecospace simulation using state-vector IO.

Source code in pypath/spatial/coupling.py
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
def run_coupled_simulation(
    scenario: "RsimScenario",
    ecospace: "EcospaceParams",
    years: Optional[range] = None,
    *,
    state_vector: Optional[np.ndarray] = None,
    store_state_vectors: bool = False,
    method: str = "RK4",
    mpa=None,
    spatial_fishing=None,
    environmental_drivers=None,
    postprocess: Optional[Callable[["RsimOutput"], None]] = None,
):
    """Run a coupled Ecosim-Ecospace simulation using state-vector IO."""
    from pypath.spatial.integration import rsim_run_spatial

    result = rsim_run_spatial(
        scenario,
        method=method,
        years=years,
        ecospace=ecospace,
        environmental_drivers=environmental_drivers,
        mpa=mpa,
        spatial_fishing=spatial_fishing,
        initial_state_vector=state_vector,
        store_state_vectors=store_state_vectors,
    )
    if postprocess is not None:
        postprocess(result)
    return result