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 | |
__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 | |
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 | |
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 | |
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 |
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 | |
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 | |
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 | |
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 ( |
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 |
monthly_capacity |
Optional[MonthlyCapacity]
|
A habitat capacity for every month for chosen groups, acting on the
local dynamics and, with its |
relative_pp |
Optional[ndarray]
|
Relative primary production of each patch [n_patches], not
negative: EwE's relative primary production map ( |
environmental_drivers |
Optional[object]
|
Time-varying environmental drivers (EnvironmentalDrivers instance).
A run does not evaluate them: make a capacity from them with
|
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 ( |
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 | |
__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 | |
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 |
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 | |
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 | |
__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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 |
"auto"
|
element_depth
|
ndarray
|
Depth of each element; a patch gets the area-weighted mean. |
None
|
crs
|
str
|
Coordinate system of |
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
|
|
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 | |
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 |
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 |
'auto'
|
crs
|
str
|
As in |
'auto'
|
geometry
|
str
|
As in |
'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 | |
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 | |
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
|
|
required |
n_groups
|
int
|
Number of rows of the result. Default: |
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 | |
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 | |
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 |
required |
grid
|
EcospaceGrid
|
A grid of the boxes ( |
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: |
None
|
Returns:
| Type | Description |
|---|---|
EnvironmentalDrivers
|
One layer per variable, named as in the series ( |
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 | |
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 |
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: |
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
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When a patch's zone is not in |
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 | |
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 |
values |
ndarray
|
Capacity [n_months, n_groups_given, n_patches], not negative, on
the scale of the base map ( |
first_month |
int
|
The run's month (0 is its first) that the first month of |
beyond |
{'refuse', 'repeat_year', 'mean_year', 'hold'}
|
The months of a run that |
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 | |
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 | |
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 |
required |
responses
|
mapping
|
|
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 | |
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 | |
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 | |
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 | |
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_boundariesnames 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 |
boundary_id, boundary_zone |
ndarray
|
Id of each section to the outside and the position in |
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 | |
from_link_flows
classmethod
¶
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 |
required |
groups
|
sequence of int
|
The groups carried, as rows of |
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, |
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
|
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 | |
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 |
required |
groups
|
sequence of int
|
The groups carried, as rows of |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 GeoDataFramehaversine_distance()— great circle distance in kmvalidate_adjacency_symmetry()— check matrix is symmetricget_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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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). |
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 | |
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 | |
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 | |
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 | |
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 | |
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 |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
flatten_quality ¶
flatten_quality() -> np.ndarray
Return habitat quality as flattened 1D vector.
Source code in pypath/spatial/habitat.py
523 524 525 | |
flatten_substrate ¶
flatten_substrate() -> np.ndarray
Return substrate as flattened 1D vector.
Source code in pypath/spatial/habitat.py
527 528 529 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
__init__ ¶
__init__(layers: Optional[Dict[str, EnvironmentalLayer]] = None)
Initialize environmental drivers.
Source code in pypath/spatial/environmental.py
206 207 208 209 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 |
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 | |
__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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
__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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 |
None
|
rates_out
|
dict
|
Arrays [n_groups+1, n_patches] keyed like |
None
|
include_diffusion
|
bool
|
Include diffusion in the movement flux (default). |
True
|
_fast_capture
|
dict
|
Internal ( |
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 | |
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 |
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 ( |
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
|
None
|
store_state_vectors
|
bool
|
If True, stores per-timestep flattened state vectors as
|
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
( |
True
|
on_month
|
callable
|
Called as |
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 |
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 |
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 | |
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 biomassB0 x BRatio;Vspace = X x Qarena / (B0_prey x BRatio_prey)withQarena = Q0 x BRatio_pred(one predator per arena), floored at Ecosim's vulnerability rateX x Q0 / B0_prey;- search rates from five passes of
A = Q0 / (Vtemp x MeanBP),Vtemp = Vspace / (2 Vspace + A x Pbar),MeanBPthe map-wide mean ofHabCap_prey x HabCap_predtimes 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 | |
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 | |
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 | |
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_spatialleaves 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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 |
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 | |
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 | |
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 | |
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 | |
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 |
required |
n_patches
|
int
|
Number of patches. |
required |
habitat_capacity
|
ndarray
|
Capacity matrix |
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 | |
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 | |