Core API Reference¶
The core module implements the Ecopath mass-balance solver, Ecosim dynamic simulation, and supporting subsystems (stanzas, forcing, optimization).
Functional Development Workflows¶
This reference now covers functional developments added around the baseline Ecopath/Ecosim pipeline.
| Workflow | Primary API Entry Points | Typical Outcome |
|---|---|---|
| Balanced baseline modeling | create_rpath_params(), rpath(), rsim_scenario(), rsim_run() |
Mass-balanced static model and dynamic biomass trajectories |
| Recruitment-aware dynamics | RickerRecruitment, BevertonHoltRecruitment, MyersRecruitment, RsimScenario.set_recruitment_model(), RsimScenario.apply_recruitment_to_forcing() |
Group-specific recruitment multipliers injected into monthly forcing |
| Metabolism scaling | TemperatureDependence, MetabolicModel, compute_temperature_adjusted_metabolism() |
Temperature/body-size adjusted metabolic rates |
| Fishing strategy prototyping | DynamicLogisticSelectivity, TimeVaryingSelectivity, SpatialSelectivity, FishingOptimization |
Selectivity and effort-allocation experiments before full scenario runs |
| Uncertainty and risk | SensitivityAnalyzer, UncertaintyPropagation, RiskAssessment |
Local/global sensitivity, ensemble uncertainty, collapse/extinction risk metrics |
Recruitment-enabled scenario pattern¶
from pypath import rsim_scenario
from pypath.core.recruitment import RickerRecruitment
scenario = rsim_scenario(model, params, years=range(1, 51))
scenario.set_recruitment_model("Cod", RickerRecruitment(alpha=0.8, beta=0.02, rmax=1.5))
ssb = {"Cod": 1200.0}
scenario.apply_recruitment_to_forcing(month_index=0, time=0.0, ssb_by_group=ssb)
Ecopath (Mass-Balance)¶
pypath.core.ecopath ¶
Ecopath mass-balance model implementation.
This module contains the core Rpath class and the rpath() function that performs mass-balance calculations for food web models.
Rpath
dataclass
¶
Balanced Ecopath model.
This class represents a mass-balanced food web model created by the rpath() function.
Attributes:
| Name | Type | Description |
|---|---|---|
NUM_GROUPS |
int
|
Total number of groups (living + dead + gears) |
NUM_LIVING |
int
|
Number of living groups (consumers + producers) |
NUM_DEAD |
int
|
Number of detritus groups |
NUM_GEARS |
int
|
Number of fishing fleets |
Group |
ndarray
|
Names of all groups |
type |
ndarray
|
Type codes (0=consumer, 1=producer, 2=detritus, 3=fleet) |
TL |
ndarray
|
Trophic levels |
Biomass |
ndarray
|
Biomass values (t/km²) |
PB |
ndarray
|
Production/Biomass ratios (1/year) |
QB |
ndarray
|
Consumption/Biomass ratios (1/year) |
EE |
ndarray
|
Ecotrophic efficiencies |
GE |
ndarray
|
Gross efficiencies (P/Q) |
M0 |
ndarray
|
Other mortality rates (M0 = PB * (1 - EE)) |
BA |
ndarray
|
Biomass accumulation rates |
Unassim |
ndarray
|
Unassimilated consumption fractions |
DC |
ndarray
|
Diet composition matrix |
DetFate |
ndarray
|
Detritus fate matrix |
Landings |
ndarray
|
Landings by group and fleet |
Discards |
ndarray
|
Discards by group and fleet |
eco_name |
str
|
Ecosystem name |
eco_area |
float
|
Ecosystem area (km²) |
Source code in pypath/core/ecopath.py
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 | |
summary ¶
summary() -> pd.DataFrame
Get summary table of model results.
Returns:
| Type | Description |
|---|---|
DataFrame
|
Summary with Group, Type, TL, Biomass, PB, QB, EE, GE, and Removals. |
Source code in pypath/core/ecopath.py
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 | |
EweDetritusFate
dataclass
¶
EwE6's detritus fate on a balanced model (see :func:ewe_detritus_fate).
Each array has one value per group, in the model's group order, and is 0 except on detritus groups.
Attributes:
| Name | Type | Description |
|---|---|---|
input_to_det |
ndarray
|
Inflow (EwE InputToDet): import, living groups' deaths and egestion, discards and the surplus other pools passed on. |
det_eaten |
ndarray
|
Consumption of the pool (EwE DetEaten). |
passed_on |
ndarray
|
Surplus passed on to the other pools (EwE DetPassedOn, the Ecopath FlowToDet of a detritus group). |
ba |
ndarray
|
Biomass accumulation: the model's BA plus the surplus share the pool sends to itself (EwE BA after CalcBAofDetritus). |
ee |
ndarray
|
Ecotrophic efficiency, det_eaten / input_to_det (EwE EE). |
Source code in pypath/core/ecopath.py
934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 | |
rpath ¶
rpath(rpath_params: RpathParams, eco_name: str = '', eco_area: float = 1.0, debug: bool = False) -> Union[Rpath, Tuple[Rpath, Dict[str, object]]]
Balance an Ecopath model.
Performs initial mass balance using an RpathParams object. Preserves the original group order from the input parameters.
The mass balance equation solved is:
Production = Predation Mortality + Fishing Mortality + Other Mortality + Biomass Accumulation + Net Migration
Or equivalently: B_i * PB_i * EE_i = Σ(B_j * QB_j * DC_ji) + Y_i + BA_i
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rpath_params
|
RpathParams
|
R object containing the parameters needed to create an Rpath model. |
required |
eco_name
|
str
|
Name of the ecosystem (stored as attribute). |
''
|
eco_area
|
float
|
Area of the ecosystem (stored as attribute). |
1.0
|
debug
|
bool
|
If False (default), return only the balanced Rpath object.
If True, return a tuple |
False
|
Returns:
| Type | Description |
|---|---|
Rpath or tuple[Rpath, dict]
|
Balanced model that can be supplied to rsim_scenario().
When debug=True, returns |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the model cannot be balanced due to missing parameters. |
Notes
When debug=True the function returns a tuple
(rpath_obj, diagnostics) where diagnostics contains
intermediate matrices useful for debugging (A, b_vec, x,
diet_values, nodetrdiet, living_idx, no_b, no_ee).
Examples:
>>> params = create_rpath_params(...)
>>> # Fill in parameter values
>>> model = rpath(params, eco_name='Georges Bank')
>>> print(model)
Source code in pypath/core/ecopath.py
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 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 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 | |
ewe_detritus_fate ¶
ewe_detritus_fate(model: Rpath) -> EweDetritusFate
Route detritus between pools as EwE6's Ecopath does.
EwE (cEcoPathModel.CalcFateOfDetritus and CalcBAofDetritus, vb 619-668) takes the detritus pools in group order. A pool's surplus, inflow minus consumption, goes to every other pool j in the fraction DF(i, j); a later pool's surplus therefore includes what earlier pools passed to it, while what a later pool passes back to an earlier one only adds to that pool's inflow. The fraction a pool sends to itself is not inflow but biomass accumulation, BA += (inflow - consumption - catch) x DF(i, i).
:func:rpath keeps Rpath v1.1's routing instead (a pool's own share
counts as inflow; only the first-stage surpluses are passed on), so its
detritus EE differ wherever a pool has a fate to itself or passes on
detritus another pool passed to it. Ecosim's EwE rule uses this routing.
Source code in pypath/core/ecopath.py
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 | |
Parameters¶
pypath.core.params ¶
Parameter data structures for PyPath.
This module contains the RpathParams class and functions for creating, reading, writing, and validating Ecopath parameter files.
RpathStanzaParams
dataclass
¶
Parameters for multi-stanza (age-structured) groups.
Attributes:
| Name | Type | Description |
|---|---|---|
n_stanza_groups |
int
|
Number of stanza group sets (e.g., juvenile + adult = 1 set) |
stgroups |
DataFrame
|
Stanza group parameters (VBGF_Ksp, VBGF_d, Wmat, etc.) |
stindiv |
DataFrame
|
Individual stanza parameters (First, Last, Z, Leading) |
Source code in pypath/core/params.py
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | |
RpathParams
dataclass
¶
Container for Rpath model parameters.
This class holds all parameters needed to create a balanced Ecopath model.
Attributes:
| Name | Type | Description |
|---|---|---|
model |
DataFrame
|
Basic parameters for each group including: - Group: Group name - Type: 0=consumer, 1=producer, 2=detritus, 3=fleet - Biomass: Biomass (t/km²) - PB: Production/Biomass ratio (1/year) - QB: Consumption/Biomass ratio (1/year) - EE: Ecotrophic efficiency - ProdCons: Production/Consumption ratio (GE) - BioAcc: Biomass accumulation rate - Unassim: Unassimilated consumption fraction - DetInput: Detrital input (for detritus groups) Plus columns for detritus fate and landings/discards by fleet. |
diet |
DataFrame
|
Diet composition matrix where rows are prey (including Import) and columns are predators. Values are fractions (0-1). |
stanzas |
RpathStanzaParams
|
Multi-stanza (age-structured) group parameters. |
pedigree |
DataFrame
|
Data quality/pedigree information for parameters. |
remarks |
DataFrame
|
Comments/remarks for parameter values. Has same structure as model with string values containing remarks for each cell. |
compat |
{'rpath', 'ewe'}
|
Whose conventions the model follows (roadmap decision D1): "ewe" for
models read from EwE ( |
Examples:
>>> params = create_rpath_params(
... groups=['Phyto', 'Zoo', 'Fish', 'Detritus', 'Fleet'],
... types=[1, 0, 0, 2, 3]
... )
>>> params.model['Biomass'] = [10.0, 5.0, 2.0, 100.0, np.nan]
Source code in pypath/core/params.py
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 | |
get_groups_by_type ¶
get_groups_by_type(groups: List[str], types: List[int]) -> Dict[str, List[str]]
Return dict mapping type names to group lists.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
groups
|
list of str
|
Names of all groups in the model. |
required |
types
|
list of int
|
Type code for each group (0=consumer, 1=producer, 2=detritus, 3=fleet). |
required |
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary with keys: 'consumers', 'producers', 'detritus', 'fleets', 'living' (types 0 and 1), and 'prey' (types 0, 1, and 2). |
Source code in pypath/core/params.py
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 | |
create_rpath_params ¶
create_rpath_params(groups: List[str], types: List[int], stgroups: Optional[List[str]] = None) -> RpathParams
Create a shell RpathParams object with empty parameter values.
Creates the basic structure for an Ecopath model that can be filled in with actual parameter values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
groups
|
list of str
|
Names of all groups in the model (living, detritus, and fleets). |
required |
types
|
list of int
|
Type code for each group: - 0: Consumer - 1: Primary producer (or value 0-1 for mixotrophs) - 2: Detritus - 3: Fleet/fishery |
required |
stgroups
|
list of str
|
Stanza group assignment for each group. Use None for non-stanza groups. Groups with the same stanza group name will be linked (e.g., juvenile/adult). |
None
|
Returns:
| Type | Description |
|---|---|
RpathParams
|
Parameter object with NA values ready to be filled in. |
Examples:
>>> params = create_rpath_params(
... groups=['Phyto', 'Zoo', 'SmallFish', 'LargeFish', 'Detritus', 'Fleet'],
... types=[1, 0, 0, 0, 2, 3],
... stgroups=[None, None, 'Fish', 'Fish', None, None]
... )
Source code in pypath/core/params.py
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 | |
read_rpath_params ¶
read_rpath_params(model_file: Union[str, Path], diet_file: Union[str, Path], pedigree_file: Optional[Union[str, Path]] = None, stanza_group_file: Optional[Union[str, Path]] = None, stanza_file: Optional[Union[str, Path]] = None) -> RpathParams
Read Rpath parameters from CSV files.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_file
|
str or Path
|
Path to CSV file with model parameters. |
required |
diet_file
|
str or Path
|
Path to CSV file with diet composition matrix. |
required |
pedigree_file
|
str or Path
|
Path to CSV file with pedigree information. |
None
|
stanza_group_file
|
str or Path
|
Path to CSV file with stanza group parameters. |
None
|
stanza_file
|
str or Path
|
Path to CSV file with individual stanza parameters. |
None
|
Returns:
| Type | Description |
|---|---|
RpathParams
|
Parameter object populated from files. |
Source code in pypath/core/params.py
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 | |
write_rpath_params ¶
write_rpath_params(params: RpathParams, eco_name: str, path: Union[str, Path] = '') -> None
Write Rpath parameters to CSV files.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
params
|
RpathParams
|
Parameter object to write. |
required |
eco_name
|
str
|
Ecosystem name used in file names. |
required |
path
|
str or Path
|
Directory path for output files. |
''
|
Source code in pypath/core/params.py
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 | |
check_rpath_params ¶
check_rpath_params(params: RpathParams) -> bool
Check Rpath parameter files for consistency.
Validates that parameter files are filled out correctly and data is in the expected locations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
params
|
RpathParams
|
Parameter object to validate. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if parameters are valid, False otherwise. |
Raises:
| Type | Description |
|---|---|
warn
|
For each validation issue found. |
Source code in pypath/core/params.py
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 | |
Ecosim (Dynamic Simulation)¶
The Ecosim engine runs time-dynamic food web simulations using foraging arena theory. Key entry points:
rsim_scenario()— create a scenario from a balanced Ecopath modelrsim_run()— run the simulation with RK4 or Adams-Bashforth integration, or with a continuous SciPy solver (see below)
Integration methods¶
| Method | Description |
|---|---|
"RK4" |
4th-order Runge-Kutta. Stable, self-starting. Good for short runs. |
"AB" |
Adams-Bashforth 2-step (matches Rpath). Uses 1 month RK4 warmup then AB2: B_{n+1} = B_n + dt/2 * (3*f_n - f_{n-1}). Includes dynamic fast equilibrium for NoIntegrate groups and Rpath-style biomass bounds. Recommended for calibration and comparison with EwE/Rpath. |
"lsoda", "dop853", "radau", "bdf" |
Continuous pathway (not EwE parity): SciPy's solve_ivp, one call per month, with the defect corrections applied. Results differ from EwE by design; see Continuous Integration Pathway. |
Consumption formula¶
The consumption kernel uses the full Rpath foraging arena functional response:
Q = QQbase * PDY * PYY^(HandleSwitch*COUPLED) *
DD / (DD - 1 + ((1-Hself)*PYY + Hself*HandleSuite)^(HandleSwitch*COUPLED)) *
VV / (VV - 1 + (1-Sself)*PDY + Sself*PredSuite)
Where PredSuite and HandleSuite are pooled competitor biomass sums
across all predator-prey links sharing the same prey or predator.
The pooling weights (PredPredWeight, PreyPreyWeight) are Rpath's: VV is
converted to a rate, VV * QQ / B_prey, before the weight formula, and each
prey's (predator's) weights are normalised to sum to 1.
Foraging time¶
Predators dynamically adjust foraging time using the Rpath formula:
Ftime_new = 0.1 + 0.9 * Ftime_old * ((1 - FtimeAdj) + FtimeAdj * QBopt / (FoodGain / B))
Capped at 2.0. Groups with FtimeAdj = 0 do not adjust foraging time.
NoIntegrate groups (fast equilibrium)¶
Groups flagged as NoIntegrate (typically detritus, meiobenthos, and other fast-turnover groups) use instantaneous equilibrium instead of ODE integration when running with the AB method:
biomeq = TotGain / (TotLoss / B)
B_new = 0.5 * biomeq + 0.5 * B_old
This matches Rpath's SORWT=0.5 smoothing.
pypath.core.ecosim ¶
Ecosim dynamic simulation implementation.
This module will contain the core Ecosim simulation engine, including the derivative calculations and integration methods.
RunCancelled ¶
Bases: RuntimeError
Raised by rsim_run when its on_month callback asks the run to stop.
Source code in pypath/core/ecosim.py
70 71 | |
RsimParams
dataclass
¶
Dynamic simulation parameters.
Contains all parameters needed to run an Ecosim simulation, derived from a balanced Rpath model.
Attributes:
| Name | Type | Description |
|---|---|---|
NUM_GROUPS |
int
|
Total number of groups |
NUM_LIVING |
int
|
Number of living groups |
NUM_DEAD |
int
|
Number of detritus groups |
NUM_GEARS |
int
|
Number of fishing fleets |
NUM_BIO |
int
|
Number of biomass groups (living + dead) |
spname |
list
|
Species/group names with "Outside" as first element |
spnum |
ndarray
|
Species numbers (0 to NUM_GROUPS) |
B_BaseRef |
ndarray
|
Reference biomass values |
MzeroMort |
ndarray
|
Other mortality rate (M0 = PB * (1-EE)) |
UnassimRespFrac |
ndarray
|
Unassimilated fraction of consumption |
ActiveRespFrac |
ndarray
|
Active respiration fraction |
FtimeAdj |
ndarray
|
Foraging time adjustment rate |
FtimeQBOpt |
ndarray
|
Optimal Q/B for foraging time |
PBopt |
ndarray
|
Base production/biomass |
NoIntegrate |
ndarray
|
Fast equilibrium flag (0 = fast eq, else normal) |
HandleSelf |
ndarray
|
Prey-overlap weight of each predator's handling time, one value per
group (length NUM_GROUPS + 1, as Rpath); every link of a predator
takes that predator's value. An array of one value per link (length
|
ScrambleSelf |
ndarray
|
Predator-overlap weight of the vulnerability term, per group and keyed by the predator, as HandleSelf |
Predator-Prey Link Arrays
PreyFrom : np.ndarray Prey index for each link PreyTo : np.ndarray Predator index for each link QQ : np.ndarray Base consumption rate for each link DD : np.ndarray Handling time parameter VV : np.ndarray Vulnerability parameter HandleSwitch : np.ndarray Prey switching exponent PredPredWeight : np.ndarray Predator density weight PreyPreyWeight : np.ndarray Prey density weight NumPredPreyLinks : int Number of predator-prey links
Fishing Link Arrays
FishFrom : np.ndarray Fished group index FishThrough : np.ndarray Fleet index FishQ : np.ndarray Fishing rate (catch/biomass) FishTo : np.ndarray Destination (0=outside, or detritus) NumFishingLinks : int Number of fishing links
Detritus Link Arrays
DetFrac : np.ndarray Fraction flowing to detritus DetFrom : np.ndarray Source group index DetTo : np.ndarray Detritus destination index NumDetLinks : int Number of detritus links
Source code in pypath/core/ecosim.py
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 | |
RsimState
dataclass
¶
State variables for Ecosim simulation.
Attributes:
| Name | Type | Description |
|---|---|---|
Biomass |
ndarray
|
Current biomass values |
N |
ndarray
|
Numbers (for stanza groups) |
Ftime |
ndarray
|
Foraging time multiplier |
Source code in pypath/core/ecosim.py
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 | |
RsimForcing
dataclass
¶
Forcing matrices for environmental and biological effects.
All matrices are (n_months x n_groups+1) where first column is "Outside".
Attributes:
| Name | Type | Description |
|---|---|---|
ForcedPrey |
ndarray
|
Prey availability multiplier |
ForcedMort |
ndarray
|
Mortality multiplier |
ForcedRecs |
ndarray
|
Recruitment multiplier |
ForcedSearch |
ndarray
|
Search rate multiplier |
ForcedActresp |
ndarray
|
Active respiration multiplier |
ForcedMigrate |
ndarray
|
Migration rate |
ForcedBio |
ndarray
|
Forced biomass values (-1 = not forced) |
Source code in pypath/core/ecosim.py
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 | |
RsimFishing
dataclass
¶
Fishing forcing matrices.
Attributes:
| Name | Type | Description |
|---|---|---|
ForcedEffort |
ndarray
|
Monthly effort multiplier (n_months x n_gears+1) |
ForcedFRate |
ndarray
|
Annual F rate by species (n_years x n_bio+1) |
ForcedCatch |
ndarray
|
Annual forced catch by species (n_years x n_bio+1) |
Source code in pypath/core/ecosim.py
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 | |
RsimScenario
dataclass
¶
Complete Ecosim simulation scenario.
Attributes:
| Name | Type | Description |
|---|---|---|
params |
RsimParams
|
Dynamic simulation parameters |
start_state |
RsimState
|
Initial state variables |
forcing |
RsimForcing
|
Environmental forcing matrices |
fishing |
RsimFishing
|
Fishing forcing matrices |
stanzas |
dict
|
Multi-stanza parameters (if any) |
eco_name |
str
|
Ecosystem name |
start_year |
int
|
First year of simulation |
ecospace |
(EcospaceParams, optional)
|
Spatial ECOSPACE parameters (if None, runs non-spatial Ecosim) |
environmental_drivers |
(EnvironmentalDrivers, optional)
|
Time-varying environmental layers for habitat capacity |
Source code in pypath/core/ecosim.py
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 | |
RsimOutput
dataclass
¶
Output from Ecosim simulation run.
Attributes:
| Name | Type | Description |
|---|---|---|
out_Biomass |
ndarray
|
Monthly biomass values (n_months x n_groups+1) |
out_Catch |
ndarray
|
Monthly catch (n_months x n_groups+1): the month-end biomass times
the month's fishing mortality ( |
out_Gear_Catch |
ndarray
|
Monthly catch by gear link: the gears' share (effort and fleet
mediation). A forced F has no fleet breakdown, so where it replaces
the gears their links carry 0. Month-mean biomass on the continuous
path, as |
annual_Biomass |
ndarray
|
Annual biomass (n_years x n_groups+1) |
annual_Catch |
ndarray
|
Annual catch (n_years x n_groups+1) |
annual_QB |
ndarray
|
Annual Q/B values |
annual_Qlink |
ndarray
|
Annual consumption by pred-prey pair |
stanza_biomass |
ndarray or None
|
Monthly sum(N * W) of each multi-stanza group (n_months+1 x
n_groups+1, zero for other groups); equals |
out_FishMort |
ndarray or None
|
Fishing mortality (per year) applied in each month, as the derivative
applies it (effort, forced F and catch; EwE6's FishTime), n_months+1 x
n_groups+1; row m is month m, row 0 the base F (FishQ at effort 1).
Predicts catch as B x F in |
out_Hden |
ndarray or None
|
EwE6's handling-time term Hden of each predator at the end of each
month (n_months+1 x n_groups+1; row 0 the run's start, CmCo / (CmCo +
1)). None when |
end_state |
RsimState
|
Final state at end of simulation |
crash_year |
int
|
Year of crash (-1 if no crash) |
crashed_groups |
set
|
Set of group indices that crashed (biomass < threshold) |
pred |
ndarray
|
Predator names for Qlink columns |
prey |
ndarray
|
Prey names for Qlink columns |
start_state |
RsimState
|
Initial state (copy) |
params |
dict
|
Summary parameters |
solver_info |
dict or None
|
Continuous path only: |
out_Catch_month_end |
ndarray or None
|
Continuous path only: EwE's booking, the month's F times the month-end biomass / 12 (n_months+1 x n_groups+1). None for RK4 and AB. |
Source code in pypath/core/ecosim.py
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 | |
RunSetup
dataclass
¶
The per-run inputs that rsim_run's paths share (_run_setup).
params_dict and fishing_dict are the derivative's dicts and
state the start biomass after the stanza start. stanzas is the
scenario's stanza object, stanza_state its age structure (None when
the run goes without it) and stanza_idx the stanza groups. ftime
is a copy of start_state.Ftime, which the run updates in place;
risk0 is RiskTime's base predation risk (None when RiskTime is
off) and handling _ewe_handling_setup's (hden0, hden_start,
cmco_qb) or None. params_dict["_hden"] is hden_start, EwE's
start value, before the run's start-of-run derivative advances it.
Source code in pypath/core/ecosim.py
1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 | |
SubstepCheck
dataclass
¶
What substep_check found.
max_difference is the largest relative difference of any group's
biomass in any month between the run at substeps and the run at
finer sub-steps (infinite if either is not finite), at group in
month. converged says whether it is within the tolerance asked.
Source code in pypath/core/ecosim.py
2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 | |
detritus_self_fates ¶
detritus_self_fates(rpath, nliving: int, ndead: int) -> dict
Detritus groups whose detritus fate points to themselves.
Returns {group name: fraction} for every dead group with a fate
fraction > 0 to its own pool.
Source code in pypath/core/ecosim.py
570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 | |
default_fast_group_rule ¶
default_fast_group_rule(rpath, rpath_params=None) -> str
The fast-group rule a model gets when none is named (roadmap D1).
"ewe" when the model's origin, its compat, is "ewe" (models
read from EwE: read_ewemdb, read_ewef, ecobase_to_rpath) and
"rpath" otherwise (models built from CSV or in code). compat is
read from rpath_params when it is given and has one, else from
rpath; a missing compat counts as "rpath".
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rpath
|
Rpath
|
Balanced Ecopath model (or anything with a |
required |
rpath_params
|
RpathParams
|
The model's parameters; their |
None
|
Returns:
| Type | Description |
|---|---|
str
|
|
Source code in pypath/core/ecosim.py
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 | |
rsim_params ¶
rsim_params(rpath: Rpath, mscramble: float = 2.0, mhandle: float = 1000.0, preyswitch: float = 1.0, scrambleselfwt: float = 0.0, handleselfwt: float = 0.0, steps_yr: int = 12, steps_m: int = 1, fast_group_rule: Optional[str] = None) -> RsimParams
Convert Rpath model to Ecosim simulation parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rpath
|
Rpath
|
Balanced Ecopath model |
required |
mscramble
|
float
|
Base vulnerability parameter (default 2.0 = mixed response) |
2.0
|
mhandle
|
float
|
Base handling time parameter (default 1000 = off) |
1000.0
|
preyswitch
|
float
|
Prey switching exponent (default 1.0 = off) |
1.0
|
scrambleselfwt
|
float
|
Predator overlap weight (0 = individual, 1 = all overlap), the start
value of every group's |
0.0
|
handleselfwt
|
float
|
Prey overlap weight (0 = individual, 1 = all overlap), the start
value of every group's |
0.0
|
steps_yr
|
int
|
Timesteps per year (default 12 = monthly) |
12
|
steps_m
|
int
|
Sub-timesteps per month (default 1) |
1
|
fast_group_rule
|
('ewe', 'rpath')
|
Which groups are solved as fast equilibria ( |
"ewe"
|
Returns:
| Type | Description |
|---|---|
RsimParams
|
Parameters object for simulation |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the balanced model's groups are not in block order (living groups, types 0 and 1, then detritus, 2, then fleets, 3), a group is a mixotroph (0 < type < 1), or a group has some other type. |
Source code in pypath/core/ecosim.py
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 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 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 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 | |
rsim_state ¶
rsim_state(params: RsimParams) -> RsimState
Create initial state vectors for simulation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
params
|
RsimParams
|
Simulation parameters |
required |
Returns:
| Type | Description |
|---|---|
RsimState
|
Initial state with biomass, N, and Ftime |
Source code in pypath/core/ecosim.py
1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 | |
rsim_forcing ¶
rsim_forcing(params: RsimParams, years: range) -> RsimForcing
Create forcing matrices with default values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
params
|
RsimParams
|
Simulation parameters |
required |
years
|
range
|
Years of simulation |
required |
Returns:
| Type | Description |
|---|---|
RsimForcing
|
Forcing matrices initialized to default values |
Source code in pypath/core/ecosim.py
1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 | |
rsim_fishing ¶
rsim_fishing(params: RsimParams, years: range) -> RsimFishing
Create fishing matrices with default values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
params
|
RsimParams
|
Simulation parameters |
required |
years
|
range
|
Years of simulation |
required |
Returns:
| Type | Description |
|---|---|
RsimFishing
|
Fishing matrices initialized to default values |
Source code in pypath/core/ecosim.py
1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 | |
rsim_scenario ¶
rsim_scenario(rpath: Rpath, rpath_params: RpathParams, years: range = range(1, 101), vulnerability: float = 2.0, scenario_overrides: dict = None, fast_group_rule: Optional[str] = None) -> RsimScenario
Create a complete Ecosim scenario.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rpath
|
Rpath
|
Balanced Ecopath model |
required |
rpath_params
|
RpathParams
|
Original model parameters |
required |
years
|
range
|
Years to simulate; |
range(1, 101)
|
vulnerability
|
float
|
Base vulnerability parameter (default 2.0 = mixed response) Controls predator-prey functional response: - 1.0 = donor control (top-down) - 2.0 = mixed control - Higher values = more bottom-up control |
2.0
|
scenario_overrides
|
dict
|
EwE scenario-level parameter overrides. Keys: - 'ftime_adjust': dict mapping 0-based group index -> FtimeAdjust value - 'vv_overrides': dict mapping (prey_0based, pred_0based) -> VV value - 'forced_bio': dict mapping 0-based group index -> array of annual biomass values - 'nut_base_free_prop': EwE's NutBaseFreeProp (EWE rule only) - 'nut_forcing': monthly factors on EwE's total nutrient, from the first simulated month; months past its end take 1 - 'cm_co': dict mapping 0-based group index -> QBmax/QB0 (handling) |
None
|
fast_group_rule
|
('ewe', 'rpath')
|
Passed to :func: |
"ewe"
|
Returns:
| Type | Description |
|---|---|
RsimScenario
|
Complete scenario ready for simulation |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in pypath/core/ecosim.py
1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 | |
integrate_groups ¶
integrate_groups(scenario: 'RsimScenario', groups, substeps=None) -> 'RsimScenario'
A copy of a scenario in which the named fast groups are integrated.
Under the EwE rule a group whose turnover is fast (plankton, often
detritus) is not integrated: every step sets its biomass to its local
equilibrium (NoIntegrate). Such a group cannot be moved between the
patches of a spatial run, by diffusion or by water
(pypath.spatial.WaterTransport). This clears the flag of the groups
named, which are then integrated like the others; the rest of the EwE
rule stays, and the other fast groups stay fast.
An integrated group needs sub-steps in proportion to its turnover, and
the number cannot be read off its P/B alone: use substep_check. In a
25-group lagoon model zooplankton needed 1 sub-step a month, zooplankton
with phytoplankton 4, and detritus, turning over 3,400 times a year,
128; a pool that fast is better left as it is. With enough sub-steps the
run differs from the default by what separates an equilibrium from its
integration (1e-4 to 1e-3 of the biomass in the models tried).
Every sub-step also brings the groups left fast halfway to their equilibrium, so with more sub-steps they follow it more closely.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scenario
|
RsimScenario
|
From |
required |
groups
|
sequence of str or int
|
The groups to integrate: names, or rows where 0 is the first group
(the numbering of |
required |
substeps
|
int
|
RK4 sub-steps per month for the copy ( |
None
|
Returns:
| Type | Description |
|---|---|
RsimScenario
|
A deep copy with the flags, and the sub-steps if given, changed. |
Source code in pypath/core/ecosim.py
2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 | |
substep_check ¶
substep_check(scenario: 'RsimScenario', years: Optional[range] = None, *, factor: int = 2, tolerance: float = 0.001, ecospace=None) -> SubstepCheck
Does the run change when its RK4 sub-steps are multiplied?
Runs the scenario as it is and with factor times its sub-steps
(RK4_STEPS), and compares the biomass of every living and detritus
group in every month. A run with too few sub-steps for an integrated
group's turnover differs widely or fails; one with enough differs by
little. The scenario is not changed. Check a scenario that moves
(changed fishing, forcing): one at rest shows nothing.
A run that fails counts as an infinite difference. rsim_run puts a
floor of 1e-10 where a month's biomass is not finite, so a group that
started above the floor and is found at it in either run is taken to
have failed there (a group that truly collapses that far is reported
the same way). The spatial run keeps non-finite values, which count
too.
With ecospace, or for a scenario that carries one, both runs are
spatial runs (rsim_run_spatial) and every patch is compared: the
sub-steps a spatial run needs are checked on the spatial run.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scenario
|
RsimScenario
|
The scenario to check, e.g. from |
required |
years
|
range
|
As for |
None
|
factor
|
int
|
The finer run has |
2
|
tolerance
|
float
|
|
0.001
|
ecospace
|
EcospaceParams
|
Check the spatial run on these spatial parameters. Default: the
scenario's own |
None
|
Source code in pypath/core/ecosim.py
2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 | |
rsim_run ¶
rsim_run(scenario: RsimScenario, method: str = 'RK4', years: Optional[range] = None, *, mediation=None, ecotracer=None, fleet_dynamics=None, solver_options: Optional[dict] = None, on_month: Optional[Callable[[int, int], Optional[bool]]] = None) -> RsimOutput
Run Ecosim simulation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scenario
|
RsimScenario
|
Simulation scenario |
required |
method
|
str
|
Integration method, case-insensitive:
Anything else raises |
'RK4'
|
years
|
range
|
Years to run (default: all years in scenario). It must start at the
scenario's first year ( |
None
|
solver_options
|
dict
|
Options of the continuous methods (unused by RK4 and AB):
|
None
|
on_month
|
callable
|
Called as |
None
|
Returns:
| Type | Description |
|---|---|
RsimOutput
|
Simulation results |
Raises:
| Type | Description |
|---|---|
RunCancelled
|
When |
Source code in pypath/core/ecosim.py
2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 | |
ODE Derivatives¶
The consumption kernel and derivative vector used by the Ecosim ODE solver.
Key functions:
deriv_vector()— compute dB/dt for all groups at a given state_compute_consumption_python()— foraging arena consumption matrix (Rpath-compatible)compute_biomeq()— fast equilibrium for NoIntegrate groupsintegrate_rk4()— single RK4 stepintegrate_ab()— single AB2 step with Rpath-style biomass bounds
pypath.core.ecosim_deriv ¶
Ecosim derivative calculation and integration routines.
This module contains the core numerical routines for Ecosim simulation: - deriv_vector: Calculate derivatives for all state variables - RK4 and Adams-Bashforth integration methods - Prey switching and mediation functions - Primary production forcing
These are ported from the C++ ecosim.cpp file in Rpath.
The sparse consumption loop runs as a numba kernel
(_compute_consumption_sparse_numba, bit-identical to the Python loop
_compute_consumption_sparse_python) when numba is installed. Setting the
environment variable PYPATH_NUMBA_CONSUMPTION=0 (or false, no,
off) before this module is imported keeps the Python loop.
KernelInputs
dataclass
¶
What the consumption loop reads in one deriv_vector call.
Handed to params["_hden_solver"] on the continuous path
(_hden_exact) so that handling time can be solved on the kernel
alone. predYY is unscaled: the loop's predator term is
predYY * hden0 / Hden. VV and QQbase are after the
prey-switching, arena and search remaps; link_prey / link_pred
are the links the loop visits, in its order; eat_eff is the loop's
(producers at 1) and index the predator abundance of the Hden update.
The pooling arrays, HandleSwitch, med_multipliers and eat_eff
are None when the loop gets None. BB is a copy; the other arrays may
be shared with the call, so read them only.
Source code in pypath/core/ecosim_deriv.py
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 | |
HdenKernel ¶
The link loop's consumption as a vector function of Hden.
Only the predator term (PDY, the VV denominator and the predator
suite) depends on Hden. The prey term, the DD factor, the base flow and
the mediation multiplier are computed once here, with the loop's skips
(B <= 0 at either end, QQbase <= 0); :meth:q applies its clamp at 0.
Source code in pypath/core/ecosim_deriv.py
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 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 | |
coupled ¶
coupled() -> bool
Whether one predator's Hden reaches another's consumption: a
consuming link with ScrambleSelf > 0 shares its prey's suite.
Source code in pypath/core/ecosim_deriv.py
824 825 826 827 | |
q ¶
q(hden: ndarray) -> np.ndarray
sum over prey >= 1 of Q[prey, j] at hden, per group j,
as the loop's HdenConsumption.
Source code in pypath/core/ecosim_deriv.py
829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 | |
q_and_dq ¶
q_and_dq(hden: ndarray) -> tuple[np.ndarray, np.ndarray]
(q, dq) at hden: q as :meth:q, and dq[j] the
derivative of q[j] with respect to hden[j].
With pdy = predYY * hden0 / H_j, eff the predator term of the
VV denominator and den = max(vv - 1 + max(eff, 1e-10), 1e-10):
dq[j] = sum over j's links of base * (vv_term - pdy * vv / den**2
* d eff / d pdy) * (-pdy / H_j). A clamped eff or den
contributes no d eff term, and a link whose flow is clamped at 0
contributes nothing. Each q[j] depends on H_j alone only when
no consuming link has ScrambleSelf > 0: raises ValueError when
:meth:coupled.
Source code in pypath/core/ecosim_deriv.py
847 848 849 850 851 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 884 885 886 887 888 889 890 891 892 | |
SimState
dataclass
¶
Current state of the simulation.
Source code in pypath/core/ecosim_deriv.py
1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 | |
prey_switch_weights ¶
prey_switch_weights(VV, QQbase, Bbase) -> np.ndarray
EwE6 base search rates A[prey, pred] up to a per-predator factor.
EwE6 MakeAMatrixCell: with the vulnerability exchange rate
v = VV * Q0 / B0_prey,
A = 2 Dzero Q0 v / max(P0 (B0_prey v - Q0), 1e-20)
= 2 Dzero VV Q0^2 / B0_prey / max(P0 Q0 (VV - 1), 1e-20).
The predator's 2 Dzero cancels in the switching factor and is left
out. Row 0 (imports) gets no weight.
Source code in pypath/core/ecosim_deriv.py
1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 | |
ewe_prey_multiplier_arena ¶
ewe_prey_multiplier_arena(VV, QQbase, f)
EwE6 prey Ftime / vulnerability forcing in the arena (audit D1).
EwE scales only the flow into the vulnerable pool, Veff = VulArena * f (cEcoSimModel.vb:2886-2905). For a private arena that is Rpath's form with the prey term B/B0 (f left out) and, per link of a prey with f != 1, VV' = 1 + (VV - 1)(1 + f) / 2 and QQbase' = QQbase * VV * f / VV': Q = Q0 x f K y / ((K - 1)(1 + f)/2 + y) instead of Q0 (f x) K y / (K - 1 + y).
VV and QQbase are (prey, predator) matrices; f is per prey, or a
(prey, predator) matrix when a link carries its own vulnerability forcing.
Row 0 (a producer's link from group 0) is not remapped. Returns new arrays;
the inputs are not modified.
Source code in pypath/core/ecosim_deriv.py
1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 | |
ewe_link_search_arena ¶
ewe_link_search_arena(VV, QQbase, s)
EwE6 search-rate forcing on single links (ApplyAVmodifiers per link).
A multiplier s on a link's search rate replaces the predator term y by
s*y in that link's arena: Q = Q0 x K s y / (K - 1 + s y). That is Rpath's
form with VV' = 1 + (VV - 1) / s and QQbase' = QQbase * VV / VV'. It
composes with ewe_prey_multiplier_arena (apply that one first). s is a
(prey, predator) matrix; s = 0 stops the link. Row 0 is not remapped.
Returns new arrays; the inputs are not modified.
Source code in pypath/core/ecosim_deriv.py
1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 | |
apply_prey_switching ¶
apply_prey_switching(BB, VV, QQbase, switch_power, Bbase, weights=None)
EwE6 prey switching as an effective vulnerability and base flow.
EwE6 (SetRelaSwitch) multiplies the search rate of link (i, j) by
r = [A_ij B_i^s / sum_k A_kj B_k^s] / [A_ij B0_i^s / sum_k A_kj B0_k^s]
with s the predator's SwitchPower. In the closed-form kernel
Q = Q0 PYY PDY VV / (VV - 1 + PDY) a search-rate factor r is
Q = Q0 PYY (r PDY) VV / (VV - 1 + r PDY), i.e. the kernel with
VV' = 1 + (VV - 1) / r and Q0' = Q0 VV / VV'. Returns copies of
VV and QQbase with those values on the switching predators' links;
the inputs are left untouched. Bbase is the base biomass EwE6
normalises by (Ecospace: the map-wide Ecosim base).
Source code in pypath/core/ecosim_deriv.py
1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 | |
prey_switching ¶
prey_switching(BB: ndarray, Bbase: ndarray, pred: int, ActiveLink: ndarray, switch_power: float = 2.0) -> np.ndarray
Calculate prey switching factors.
Not used by the simulation, and not EwE6's formula: Ecosim runs use
:func:apply_prey_switching (EwE6 SetRelaSwitch) with each
predator's SwitchPower.
Prey switching occurs when predators preferentially consume more abundant prey, stabilizing the system. Uses a power function of relative abundance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
BB
|
ndarray
|
Current biomass array |
required |
Bbase
|
ndarray
|
Baseline biomass array |
required |
pred
|
int
|
Predator index |
required |
ActiveLink
|
ndarray
|
Active link matrix [prey, pred] |
required |
switch_power
|
float
|
Prey switching power (default 2.0, range 0-2) - 0: No switching - 1: Linear switching - 2: Strong switching (Murdoch switching) |
2.0
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Switching factors for each prey (indexed by prey) |
Source code in pypath/core/ecosim_deriv.py
1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 | |
mediation_function ¶
mediation_function(mediation_type: int, med_bio: float, med_base: float, med_params: Dict[str, float]) -> float
.. deprecated::
Use :class:pypath.core.mediation.MediationShape and its evaluate()
method instead. This function is kept for backward compatibility.
Calculate mediation effect on predation.
Mediation allows a third party (mediator) to affect the predator-prey interaction, representing effects like habitat provision or fear.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mediation_type
|
int
|
Type of mediation function: - 0: No mediation (returns 1.0) - 1: Positive mediation (more mediator = more predation) - 2: Negative mediation (more mediator = less predation) - 3: U-shaped (optimal at intermediate mediator biomass) |
required |
med_bio
|
float
|
Current mediator biomass |
required |
med_base
|
float
|
Baseline mediator biomass |
required |
med_params
|
dict
|
Parameters including 'low', 'high', 'shape' |
required |
Returns:
| Type | Description |
|---|---|
float
|
Mediation multiplier (>0) |
Source code in pypath/core/ecosim_deriv.py
2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 | |
primary_production_forcing ¶
primary_production_forcing(BB: ndarray, Bbase: ndarray, PB: ndarray, PP_forcing: ndarray, PP_type: ndarray, NUM_LIVING: int) -> np.ndarray
Calculate primary production with environmental forcing.
In Ecosim/Rpath, primary producers use density-dependent production to ensure stability. The production rate decreases as biomass increases above baseline, mimicking nutrient limitation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
BB
|
ndarray
|
Current biomass |
required |
Bbase
|
ndarray
|
Baseline biomass |
required |
PB
|
ndarray
|
Production/biomass ratios |
required |
PP_forcing
|
ndarray
|
Primary production forcing multipliers by group |
required |
PP_type
|
ndarray
|
Producer type by group: - 0: Not a producer (consumer) - 1: Primary producer (density-dependent, default) - 2: Detritus (no production) |
required |
NUM_LIVING
|
int
|
Number of living groups |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Primary production rates |
Source code in pypath/core/ecosim_deriv.py
2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 | |
fishing_mortality ¶
fishing_mortality(params: dict, forcing: dict, fishing: dict, fleet_med: ndarray | None = None) -> tuple[np.ndarray, np.ndarray]
Fishing mortality per group (per year) under one month's forcing.
The gears' FishQ x effort (forcing["ForcedEffort"], times the fleet
mediation multipliers when given) plus the forced fishing of the month
(forcing["ForcedF"], which replaces the gears where
ForcedFReplace is set). This is the F deriv_vector applies, EwE6's
FishTime. Returns (FishMort, link_fish_rate): F by group
(NUM_GROUPS + 1) and the per-biomass catch rate of each fishing link.
Source code in pypath/core/ecosim_deriv.py
2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 | |
deriv_vector ¶
deriv_vector(state: ndarray, params: dict, forcing: dict, fishing: dict, t: float = 0.0, rates: dict | None = None) -> np.ndarray
Calculate derivatives for all state variables in Ecosim.
This is the core function that implements the Ecosim differential equations based on foraging arena theory with prey switching and mediation support.
The functional response is: C_ij = (a_ij * v_ij * B_i * B_j * T_j * S_ij * D_j * M_ij) / (v_ij + v_ijT_jD_j + a_ijB_jD_j + a_ijd_ijB_j*D_j^2)
Where: a_ij = base search rate (from QQ/BB setup) v_ij = vulnerability exchange rate B_i = prey biomass B_j = predator biomass T_j = time forcing on predator S_ij = prey switching factor D_j = handling time factor d_ij = handling time for this link M_ij = mediation multiplier
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
ndarray
|
Current state vector (biomass values) indexed 0 to NUM_GROUPS |
required |
params
|
dict
|
Model parameters containing: - NUM_GROUPS: Total number of groups - NUM_LIVING: Number of living groups - NUM_DEAD: Number of detritus groups - NUM_GEARS: Number of fishing gears - PB: Production/Biomass ratios - QB: Consumption/Biomass ratios - ActiveLink: Boolean array [prey, pred] of active links - DC: Diet composition matrix [prey, pred] - VV: Vulnerability parameters [prey, pred] - DD: Handling time parameters [prey, pred] - Bbase: Baseline biomass [group] - DetFrac: Fraction to detritus [group] - Unassim: Unassimilated fraction [group] - SwitchPower: per-group EwE6 prey switching power (array, 0 = off); see apply_prey_switching. SwitchA / SwitchBbase optionally give the pre-computed search-rate weights and normalising base biomass - PP_type: Producer type array [group] - Mediation: Mediation configuration dict |
required |
forcing
|
dict
|
Forcing arrays: - ForcedBio: Forced biomass values [group] - ForcedMigrate: Migration forcing [group] - ForcedCatch: Forced catch [group] - ForcedEffort: Forced effort [gear] - PP_forcing: Primary production forcing [group] - Ftime: Time forcing [group] - StanzaPredRatio: StanzaPred / baseStanzaPred for multi-stanza groups, NaN elsewhere; replaces B / Bbase in the predator term |
required |
fishing
|
dict
|
Fishing parameters: - FishingMort: Base fishing mortality [group] - EffortCap: Effort cap [gear] |
required |
t
|
float
|
Current time (for time-varying forcing) |
0.0
|
rates
|
dict
|
If given, filled with per-group rates (per year) as Rpath's
derivative returns them: |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Derivative vector (dB/dt for each group) |
Source code in pypath/core/ecosim_deriv.py
2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 | |
log_mean ¶
log_mean(a, b)
(b - a) / ln(b / a) elementwise, the mean of an exponential path from a to b (Rpath 1.2.0's catch smoother); a where the two are within 1e-9 of a (Rpath's BIG_EPSILON) or either is not positive.
Source code in pypath/core/ecosim_deriv.py
3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 | |
integrate_rk4 ¶
integrate_rk4(state: ndarray, params: dict, forcing: dict, fishing: dict, dt: float, n_steps: int = 1, stage_rates: Optional[dict] = None, catch_bio: Optional[ndarray] = None) -> np.ndarray
Runge-Kutta 4th order integration step.
catch_bio, when given (one value per state entry), receives per
sub-step its length times the log mean of its start and end biomass
(before the clamp): F times it is the step's catch as Rpath 1.2.0
books it (its cum_Catch).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
ndarray
|
Current state vector |
required |
params
|
dict
|
Model parameters |
required |
forcing
|
dict
|
Forcing arrays |
required |
fishing
|
dict
|
Fishing parameters |
required |
dt
|
float
|
Time step |
required |
n_steps
|
int
|
Number of RK4 sub-steps of |
1
|
stage_rates
|
dict
|
Filled with the derivative's |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Updated state vector |
Source code in pypath/core/ecosim_deriv.py
3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 | |
compute_biomeq ¶
compute_biomeq(total_gain, total_loss, biomass, sorwt=0.5)
Compute fast-equilibrium biomass for NoIntegrate groups.
Rpath formula: biomeq = TotGain / (TotLoss / B) Then: new_B = (1-SORWT)biomeq + SORWTold_B
Source code in pypath/core/ecosim_deriv.py
4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 | |
integrate_ab ¶
integrate_ab(state: ndarray, derivs_history: list, params: dict, forcing: dict, fishing: dict, dt: float) -> Tuple[np.ndarray, np.ndarray]
Adams-Bashforth integration step.
Uses 2-step Adams-Bashforth method (matching Rpath) when history is available, falls back to Euler with no history.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
ndarray
|
Current state vector |
required |
derivs_history
|
list
|
List of previous derivative vectors (most recent first) |
required |
params
|
dict
|
Model parameters |
required |
forcing
|
dict
|
Forcing arrays |
required |
fishing
|
dict
|
Fishing parameters |
required |
dt
|
float
|
Time step |
required |
Returns:
| Type | Description |
|---|---|
Tuple[ndarray, ndarray]
|
Updated state vector and new derivative |
Source code in pypath/core/ecosim_deriv.py
4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 | |
run_ecosim ¶
run_ecosim(initial_state: ndarray, params: dict, forcing: dict, fishing: dict, years: float, dt: float = 1 / 12, method: str = 'ab', save_interval: int = 1) -> dict
Run Ecosim simulation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
initial_state
|
ndarray
|
Initial biomass vector |
required |
params
|
dict
|
Model parameters |
required |
forcing
|
dict
|
Forcing arrays |
required |
fishing
|
dict
|
Fishing parameters |
required |
years
|
float
|
Number of years to simulate |
required |
dt
|
float
|
Time step (fraction of year) |
1 / 12
|
method
|
str
|
Integration method ('rk4' or 'ab') |
'ab'
|
save_interval
|
int
|
Save state every N steps |
1
|
Returns:
| Type | Description |
|---|---|
dict
|
Results containing: - time: Time points - biomass: Biomass time series [time, group] - catch: Catch time series [time, group] |
Source code in pypath/core/ecosim_deriv.py
4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 | |
Continuous Integration Pathway¶
rsim_run(scenario, method="lsoda") (or "dop853", "radau", "bdf")
solves the continuous Ecosim equations month by month with SciPy's
solve_ivp. The month's forcing, effort, forced F or catch and forced
biomass are held; feeding time is a state (dFt/dt = 12 (clip(target) - Ft)
for groups with FtimeAdj > 0) and RiskTime is instantaneous. Stanza updates
and fleet dynamics run at the month boundaries; the stanza update and the
catch use the month's quadrature means (6-point Gauss-Legendre of the dense
output); fleet dynamics does not. The pathway applies the defect corrections
(R2, R4, R5, detritus fate applied once), solves handling time exactly from
a recalibrated Hden0 on a vectorised kernel, and interpolates EwE's mediation
lookup in float64, so it differs from EwE by design. Options go in
solver_options (anything else raises ValueError naming the key): rtol,
atol (the default follows rtol), corrections (False leaves out R2, R4,
R5 and DF once), on_failure, hden_tol (the handling-time tolerance,
default 1e-12, in (0, 1e-8]) and the options below.
jacobian:"reuse"(default) or"solver". LSODA, Radau and BDF reuse the finite-difference Jacobian across the monthly restarts, a fresh one costingn_state + 1evaluations; with"reuse"LSODA'snfevno longer counts the Jacobian columns, so compare cost byrhs_evals. Per monthjac_freshandjac_reused.forcing_interpolation:"constant"(default),"linear"or"smooth". Linear and smooth change the model: they replace the month-held forcing by a mean-preserving tent or quadratic. Effort stays held monthly.positivity:"clip"(default) or"log"(log-transformed biomass states, the same equations).fast_groups:"states"(default) or"quasi-steady", withqs_rate(per year, default 365). Quasi-steady changes the model: the selected fast groups are solved for their equilibrium instead of integrated, which suits DOP853; seeqs_groupsandqs_separation(a WARNING below 10) insolver_info.
Which method: LSODA is the default; use BDF for stiff models (LT2022:
11.3 x RK4 against 17.3 x on LSODA on the Python consumption loop (numba not
installed, or PYPATH_NUMBA_CONSUMPTION=0); 32.5-33.3 x against 50.5-54.1 x
with numba's consumption kernel, where RK4 runs about 2-3 x faster, measured
2026-11-17); DOP853 for non-stiff models and under
quasi-steady groups.
RsimOutput.solver_info records the corrections that act, the EwE numerics
switches ignored, atol (the biomass atol; atol_ftime lists the
feeding-time states' atol, the tail of the solver's vector), rhs_evals,
ftime_groups and per-month solver statistics: nfev, steps, degraded (a
month whose means fell back to the start state), hden_passes_max,
hden_residual_max (the largest relative residual of the solved handling
time), kernel_check (the vectorised consumption pass against the link loop),
ftime_range, last_step (the month's last full step; every month leaves its
first step to the solver), and the mass budget: budget_residual and
pool_budget_residual (None in a month with forced biomass, and under
quasi-steady groups; the month residual has a floor of about 1e-9 from the
quadrature, it is not a leak), nutrient_floor and negative_export. A
failed month raises RuntimeError naming the month. out_Catch is the
integral of F x B over the month; EwE's month-end booking is in
out_Catch_month_end. Pooled models (ScrambleSelf > 0) now use Rpath's
scramble weights on every method. docs/parity/continuous_path.md has the
options, the corrections, the validation and the cost.
out = rsim_run(scenario, method="lsoda", solver_options={"rtol": 1e-8})
out.solver_info["corrections"]
pypath.core.ecosim_continuous ¶
Continuous integration pathway for Ecosim (independent of the EwE pathway).
The pathway's pieces: the handling-time solver (solve_hden_kernel, with
solve_hden its full-derivative reference), the pure right-hand side
(ContinuousRHS) and the month integrator (integrate_month) that
rsim_run calls for the continuous methods. Under EwE's rule the
derivative scales each predator's search rate by Hden0 / Hden where
Hden satisfies the disc-equation fixed point
Hden = 1 + Hden * q(Hden) / (CmCo * QB * index)
EwE takes one damped pass of that per derivative call; here it is solved
exactly at each state, on the consumption kernel alone (HdenKernel),
with a safeguarded Newton per predator on the kernel's analytic dq/dH
(iterate_hden), or undamped passes where pooling couples the predators.
The package's modules, by responsibility: options (continuous_options,
METHOD_NAMES, the option modes, default_atol), hden (handling
time), forcing (neutral_forcing, ForcingInterpolant), feeding
(feeding time), rhs (ContinuousRHS, exchange_rate), jacobian
(JacobianReuse), quasi_steady (QuasiSteady) and month
(integrate_month, MonthResult, month_budget). Every public name is
re-exported here. A module global (solve_ivp, deriv_vector, root,
solve_hden_kernel, _ATOL_Z_MAX) is read by the submodule that uses it,
so a test that monkeypatches one patches that submodule: setting this
package's attribute does not reach it.
ForcingInterpolant ¶
Mean-preserving interpolation of monthly forcing inside each month.
monthly maps a forcing key to its monthly values, an array of shape
(n_months, ...) (the same n_months for every key, else
ValueError); the arrays are copied, never written. Months are
0-based: month k is row k, and s in [0, 1] (clipped) is
the fraction of the month.
The boundary values: inside the series b_k = min((m_{k-1} + m_k) / 2,
2 m_{k-1}, 2 m_k) for a non-negative key and (m_{k-1} + m_k) / 2
for a key in signed; at the ends b_0 = m_0 and b_N =
m_{N-1}, so nothing past the series is read. With kind="linear"
month k is a continuous tent through (0, b_k), (1/2, c_k)
and (1, b_{k+1}), c_k = 2 m_k - (b_k + b_{k+1}) / 2; it has a
kink at mid-month. With kind="smooth" it is one quadratic, b_k (1
- s) + b_{k+1} s + 6 (m_k - (b_k + b_{k+1}) / 2) s (1 - s). Either way
the month's mean is exactly m_k, the values are continuous at the
month boundaries, a non-negative key (every key not in signed,
whose monthly values are taken to be >= 0) stays >= 0 (0 <= b <= 2
m on both sides of every month), and a series constant in time gives
exactly that constant.
Source code in pypath/core/ecosim_continuous/forcing.py
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 | |
at ¶
at(month: int, s: float) -> dict
Every key's value at the fraction s of month month.
Each half of the month is written from its own end (the start for
s <= 1/2, the end beyond), so a month's ends are exactly its
boundary values and a constant series is exactly constant.
Source code in pypath/core/ecosim_continuous/forcing.py
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 | |
mean ¶
mean(month: int, key: str) -> np.ndarray
Month month's mean of key: its monthly value, exactly.
Source code in pypath/core/ecosim_continuous/forcing.py
147 148 149 | |
for_month ¶
for_month(month: int, dt: float) -> Callable[[float], dict]
forcing_at(t) for :meth:ContinuousRHS.set_month: the values at
time t of a month of length dt (s = t / dt).
Source code in pypath/core/ecosim_continuous/forcing.py
151 152 153 154 155 156 157 158 159 160 161 162 | |
FeedingTime
dataclass
¶
The groups whose feeding time is a state of the continuous path.
groups are the living groups with FtimeAdj > 0. The other arrays
are full length (index 0 = Outside): adj (FtimeAdj), qbopt
(FtimeQBOpt), cap (FtimeMax, 2.0 when the scenario has none),
risk_time and risk0 (RiskTime and its base predation risk; zeros
when RiskTime is off) and mo (MzeroMort). lower is
ForagingTimeLowerLimit.
Source code in pypath/core/ecosim_continuous/feeding.py
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | |
ContinuousRHS ¶
Pure right-hand side dy/dt = f(t, y) of the continuous pathway.
y holds the biomass states of groups 1..n_bio, then (with
feeding) the feeding times of feeding.groups. The month's
forcing, the non-state slots of the full state vector (slot 0, gears) and
the forced groups are held from :meth:set_month; with its
forcing_at (a :class:ForcingInterpolant's month) the interpolated
keys take their values at the evaluation's t, merged into a new dict
over the held one, which is never written. Evaluation is a pure
function of (t, y) and one deriv_vector call: handling time is
solved inside it, on the consumption kernel, by the solver installed as
the private params_dict's _hden_solver (:func:solve_hden_kernel
at hden_tol), always from Hden0, so no evaluation depends on an
earlier one. The private copy of params_dict is not changed after
construction (its _hden array is its own and never read by the
solve), and no array is written in place: _det_out is pre-filled at
the unforced base state so deriv_vector has nothing left to set.
The private copy also sets _KERNEL_VECTOR, so the final consumption
pass is the link loop's vectorised twin; the first counted evaluation
after :meth:set_month runs the link loop as well, in a second
deriv_vector call that only checks the first (its derivative is not
used).
With corrections True (the default) the defect corrections R2, R4, R5
and DF once are applied; with False none of them is, and the scenario's
flags and emigration are kept. The recalibrated Hden0 and the exact Hden
are not defect corrections and apply either way. Differences from the EwE
pathway are listed in self.corrections; EwE numerics switches this
pathway does not honour are in ignored_switches.
Feeding time obeys dFt/dt = 12 * (clip(target, L, FtimeMax) - Ft)
per year, target being the monthly rule (_ftime_update_rpath) at
the current state: one forward-Euler month equals the monthly update.
Each evaluation writes clip(Ft, L, FtimeMax) into a copy of the
month's Ftime (the held array is never written) and takes FoodGain
and FoodLoss from the same deriv_vector call. Qopt is _risk_qopt
at the current FoodLoss and biomass.
stats (reset by :meth:set_month) holds clips, min_state,
hden_passes_max (kernel passes of the largest Hden solve),
hden_residual_max, the largest relative residual of the solved Hden
under the consumption of the final deriv_vector pass (the vectorised
pass; the link loop at the checked evaluation), kernel_check, the
month's check max |q_vector - q_loop| / max |q_loop| of the
vectorised pass against the link loop, q being HdenConsumption (or
FoodGain without handling time; NaN until the check has run),
nutrient_floor, the number of evaluations with the free nutrient at
its floor, and negative_export, the number of evaluations (under the
EwE rule) where a pool's DetExport is below -NEGATIVE_EXPORT_TOL x
DetritusOut x B.
evals counts every evaluation of the right-hand side over the object's
life (solver, Jacobian columns, start checks, quadrature and
:meth:rates calls alike; not reset by :meth:set_month).
:meth:exchange is the net external flux of the biomass states
(:func:exchange_rate) at an evaluation's rates, under the forcing those
rates were evaluated with (rates["_forcing"]).
Source code in pypath/core/ecosim_continuous/rhs.py
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 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 | |
set_month ¶
set_month(forcing_dict: dict, state_full: ndarray, forced_mask: ndarray, forced_values: ndarray, forcing_at: Optional[Callable[[float], dict]] = None) -> None
Hold the month's forcing, non-state slots and forced groups.
forced_mask and forced_values have one entry per group
(NUM_GROUPS + 1, slot 0 included), else ValueError.
forcing_at(t) (None: the month's forcing is held) returns the
interpolated keys at the time t into the month
(:meth:ForcingInterpolant.for_month); each evaluation merges them
over forcing_dict.
Source code in pypath/core/ecosim_continuous/rhs.py
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 | |
rates ¶
rates(y: ndarray, t: float = 0.0) -> dict
deriv_vector's rates at (t, y), with "Hden" the solved
Hden (None without handling time), "Ftime" the month's feeding
time as the evaluation used it (full length) and "_forcing" the
forcing dict it applied (not to be written); no stats.
Source code in pypath/core/ecosim_continuous/rhs.py
625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 | |
exchange ¶
exchange(rates: dict, y: ndarray) -> float
:func:exchange_rate of rates (from :meth:rates at y),
over the full state the evaluation saw and under the forcing it
applied (rates["_forcing"], else the held forcing); feeding times
do not enter.
Source code in pypath/core/ecosim_continuous/rhs.py
747 748 749 750 751 752 753 | |
base_loss_rate ¶
base_loss_rate() -> np.ndarray
LossPropToB / B of groups 1..n_bio at the unforced base:
the base biomass, :func:neutral_forcing (feeding time 1, effort 1)
and nothing forced, whatever month :meth:set_month holds. One
evaluation, counted in evals (no stats); 0 where B0 = 0.
Source code in pypath/core/ecosim_continuous/rhs.py
755 756 757 758 759 760 761 762 763 764 765 766 767 768 | |
JacobianReuse ¶
Finite-difference Jacobians for solve_ivp, reused across the
monthly restarts of a run.
:meth:for_month returns the month's jac(t, y) callable, a new
closure each month over the month's right-hand side fun. The object
holds only the last Jacobian formed and the state y_J it was formed
at; the right-hand side holds nothing of it.
The rule, per request:
- a month's first request returns the run's last Jacobian when one of
the right shape (
len(y)square) is held; - later requests: BDF and Radau always form a fresh one (SciPy asks
again only after a failed Newton iteration, or for Radau after a slowly
converging step); LSODA reuses the held one only when
tstrictly advances past the previous request's and the state has not moved,max |y - y_J| / (|y_J| + 1e-12) <= move. A request at or before the previoustis a retry (after a corrector failure ODEPACK cuts the step and asks again at an earliert) and gets a fresh one.
A fresh Jacobian is forward differences in every state, h_k = 1.49e-8
x max(|y_k|, floor_k), floor the month's step floor
(:meth:for_month's step_floor, by default atol / rtol; > 0, so
the step is too where y_k = 0): fun at y and once per column,
len(y) + 1 evaluations (SciPy passes no f(t, y) to jac), each
a call of fun and so counted in ContinuousRHS.evals. SciPy's
nfev leaves them out, and its njev counts reused requests too.
rsim_run passes atol / rtol with the biomass states' capped at
the default atol's ratio, 0.01 x max(B0_k, 1e-6 x max B0) (so a large
user atol does not make the step large; the default atol gives its own
ratio), and :func:integrate_month gives log states a floor of 1, h_k
= 1.49e-8 x max(|z_k|, 1). Only a finite fresh Jacobian is held: one
with a non-finite entry goes to the solver, and the held one is dropped,
so the next request forms a fresh one.
stats (reset by :meth:for_month) counts the month's requests:
jac_fresh formed, jac_reused answered with the held Jacobian.
Every request returns a copy, so a solver cannot change the held one.
Source code in pypath/core/ecosim_continuous/jacobian.py
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 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 | |
for_month ¶
for_month(fun: Callable, step_floor: Optional[ndarray] = None) -> Callable[[float, np.ndarray], np.ndarray]
The month's jac(t, y) over fun; resets stats.
step_floor (a scalar or one value > 0 per state fun takes;
default: the object's atol / rtol) is the floor of the difference
step, h_k = 1.49e-8 x max(|y_k|, step_floor_k). rsim_run
passes its capped floor, and :func:integrate_month's jac_factory
call the floor of the solver's states (1 for log states).
Source code in pypath/core/ecosim_continuous/jacobian.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 | |
QuasiSteady ¶
Quasi-steady fast groups: the reduced right-hand side of a
:class:ContinuousRHS (a model option, solver_options["fast_groups"]
= "quasi-steady").
groups (group numbers in 1..rhs.n_bio) leave the state.
slow holds the indices of rhs's states that stay (the other
biomass states, then any feeding times), n_state their number and
n_bio the number of biomass states among them, which lead. An
evaluation at (t, ys) solves dB_f/dt = 0 for the selected
groups' biomass B_f with the slow states at ys and returns the
slow states' derivative at the solution; :meth:expand returns the full
state there.
The solve is a chord Newton from the month-start B_f with the
month-start J_ff, forward differences of rhs in B_f formed
by :meth:set_month. Each step is halved until every B_f > 0. It
stops when |dB_f/dt| <= tol x TotGain_f for every selected group
(TotGain from deriv_vector's rates at the same evaluation), in
at most max_iter steps. When the residual (its largest
|dB_f/dt| / TotGain_f) stops falling, J_ff is formed again,
once, at the iterate, for the rest of that solve only.
A root is accepted only if it is finite, positive, within the tolerance
above and attracting: every eigenvalue of J_ff there has a negative
real part, so the fast dynamics relax to it. A producer has a second
root near B = 1e-10, where a loss term that does not scale with B
meets its production: the slope there is positive, an unstable branch
that a root finder can walk into. The check forms J_ff by forward
differences at the root (one evaluation per selected group). A chord
root of a single group skips it when the chord's matrix (the month's, or
the refreshed one) is negative: the chord converges only to a root
whose slope has its matrix's sign. With several groups every chord root
is checked (no such guarantee holds for matrices).
When the chord fails or its root is rejected (a month start far from
the solution: the chord converges linearly at the ratio
|1 - J*/J_ff|, and a producer whose quasi-steady value jumps 30 %
can defeat it), a pseudo-transient continuation follows the fast
dynamics, the slow states held, from the month-start B_f: each step
solves (I / dtau - J_ff) delta = dB_f/dt with J_ff formed by
forward differences at the iterate, halving delta to keep
B_f > 0; dtau starts at 0.5 / max |diag J_ff| (half the
fastest relaxation time, so that I / dtau - J_ff stays regular where
a slope is positive) and grows by switched evolution relaxation,
dtau x r_prev / r (r the largest |dB_f/dt| / TotGain_f),
capped at 1e12 times its start, which ends as Newton's method; at
most ptc_max_iter steps. It starts from the month-start B_f, not
the chord's best iterate, which may be the unstable root, where the
continuation would stall. If it fails too,
scipy.optimize.root(method="hybr") runs in ln B_f (every
iterate positive) from the continuation's best iterate, scaled by its
TotGain_f, with the same acceptance. Otherwise RuntimeError
names "quasi-steady" and the groups. The start B_f, J_ff and
the groups are fixed by :meth:set_month, the fallback starts from them
and the evaluation's own iterates, and an evaluation keeps nothing it
computes, so each evaluation is a function of (t, ys) and the
month's data, as rhs's own are.
tol defaults to 1e-10; rsim_run passes min(1e-10, max(1e-2 x
rtol, 1e-13)), so that a user rtol below 1e-8 keeps the solve's
error two orders under the solver's (the floor 1e-13 is about the
roundoff of dB_f/dt relative to TotGain_f).
Every inner evaluation (residuals and difference columns, of every
stage, hybr's own difference Jacobian included) is an evaluation of
rhs and is counted in rhs.evals. Those of the
solver's evaluations (:meth:__call__) and of :meth:set_month's
J_ff also count in rhs.stats, as :class:JacobianReuse's columns
do; those of :meth:expand (the quadrature, the month end) and of
:meth:reduced_rate do not. stats["qs_inner_max"], reset by
:meth:set_month, is the largest number of chord-Newton steps one solve
of the month took (every solve counted; at most max_iter), and
stats["qs_fallbacks"] counts the month's solves that fell back to
the continuation ("ptc") and on to hybr ("hybr"), the roots
rejected as not attracting ("unstable", every stage), and the
evaluations the two fallback stages took ("evals", measured as
rhs.evals across them; a chord root's check is the chord's).
A difference column k steps by 1.49e-8 x max(|y_k|,
step_floor_k), step_floor being a scalar or one value per state of
rhs (default 0; rsim_run passes atol / rtol, the floor
:class:JacobianReuse uses). names (optional, one per group) label
the groups in errors.
Source code in pypath/core/ecosim_continuous/quasi_steady.py
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 | |
set_month ¶
set_month(forcing_dict: dict, state_full: ndarray, forced_mask: ndarray, forced_values: ndarray, forcing_at: Optional[Callable[[float], dict]] = None, *, y0: ndarray) -> None
:meth:ContinuousRHS.set_month, then the month's data at the
month start y0 (every state of rhs): the start B_f
(y0's, floored at 1e-20) and J_ff there at t = 0.
A selected group forced this month raises ValueError (the run
excludes groups forced in any month); a singular or non-finite
J_ff raises RuntimeError.
Source code in pypath/core/ecosim_continuous/quasi_steady.py
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 | |
__call__ ¶
__call__(t: float, ys: ndarray) -> np.ndarray
The slow states' derivative at (t, ys), B_f solved.
Source code in pypath/core/ecosim_continuous/quasi_steady.py
477 478 479 480 | |
expand ¶
expand(t: float, ys: ndarray, count: bool = False) -> np.ndarray
The full state of rhs at (t, ys): ys in the slow
states, the solved B_f in the selected groups' (count: the
inner evaluations count in rhs.stats).
Source code in pypath/core/ecosim_continuous/quasi_steady.py
482 483 484 485 486 487 | |
reduced_rate ¶
reduced_rate() -> float
The largest |Re lambda| (per year) of the reduced Jacobian at
the month start (t = 0, the month-start slow states, B_f
solved): the Schur complement J_ss - J_sf J_ff^-1 J_fs of
rhs's forward-difference Jacobian there, rhs.n_state + 1
evaluations after the solve's (no stats). 0 when no state stays.
Source code in pypath/core/ecosim_continuous/quasi_steady.py
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 | |
MonthResult
dataclass
¶
One integrated month.
y_end holds every state; y_mean only the biomass states (groups
1..n_bio; any states beyond them are feeding times, which
rsim_run reads from y_end[n_bio:]).
food_gain_mean and loss_rate_mean are full length, indexed by group
like deriv_vector's rates (index 0 = Outside), so
food_gain_mean[1:n_bio + 1] lines up with y_mean. A test double
must follow the same convention: rates(y) returns full-length arrays
whose entries 1..n_bio correspond to y.
y_end is floored at 1e-20; y_mean is the quadrature mean of the
dense output clipped at 0 (not floored), so a group at the floor has a
mean of 0, not a small negative number. loss_rate_mean is the time
mean of LossPropToB / B (0 where B = 0 at a node).
exchange_mean is the time mean of rhs.exchange (NaN when rhs
has none) and pool_net_mean that of DetGain - DetLoss, full
length like food_gain_mean (None when the rates carry no
DetGain). Both come from the quadrature's evaluations of the rates.
steps is the number of solver steps (len(sol.t) - 1).
last_step is the last full step, a diagnostic only (no month starts
from it): the second-to-last step (the last is truncated at dt), or the only step
of a one-step month. status
and message are as SciPy reports them; t_reached is the end of the
interval reached (dt unless the solve failed).
degraded is True when any of the means fell back to the start state:
non-finite dense output, non-finite rates at a quadrature node, or no
interval to average over. A failed solve whose means are taken over the
interval reached is not degraded; status and t_reached show it.
Source code in pypath/core/ecosim_continuous/month.py
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 | |
recalibrated_hden0 ¶
recalibrated_hden0(params_dict: dict, cmco_qb: ndarray) -> np.ndarray
Hden0 that makes the base state an exact fixed point of the kernel.
1 / (1 - q0 / cmco_qb) for groups with cmco_qb > 0, else 1, where
q0_j = QQbase[1:, j].sum() / Bbase[j] (link flows only; diet import is
row 0 and stays out). Raises ValueError naming the groups where
q0 >= cmco_qb, which have no positive Hden0.
Source code in pypath/core/ecosim_continuous/hden.py
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | |
hden_index ¶
hden_index(y_full: ndarray, params_dict: dict, forcing: dict) -> np.ndarray
Predator abundance in biomass units, as deriv_vector's Hden block.
The state biomass, except for stanza groups where it is
Bbase * StanzaPredRatio (ratio finite).
Source code in pypath/core/ecosim_continuous/hden.py
49 50 51 52 53 54 55 56 57 58 59 60 | |
iterate_hden ¶
iterate_hden(g: Callable[[ndarray], ndarray], h0: ndarray, active: ndarray, *, tol: float = 1e-12, max_iter: int = 30, fallback: bool = True, accel: str = 'bracketed', coupled: bool = False, dg: Optional[Callable[[ndarray], ndarray]] = None) -> tuple[np.ndarray, int]
Solve H = g(H) on the active components, from h0.
g maps a full-length H to a full-length array; the inactive
components stay at h0. An iterate is accepted when its residual
max |g(H) - H| / H over the active components is <= tol and
every active H is finite and > 0; the accepted iterate is the one whose
residual was measured.
accel="bracketed" (with coupled False, i.e. each component of
g depending on its own H only) runs a secant per component inside a
bracket, with the Illinois modification: the start a = h0, the
second end 1e6 where F = g - H is > 0 at a, else 1. A component
whose two ends do not straddle a sign change takes undamped passes
(H <- g(H)) instead. A component that converges is held there, which
is sound only because the components are independent. With
accel="none" or coupled True every pass is the plain map
H <- g(H) on every active component, none held: on a coupled map a
converged component's residual moves with the others. After max_iter
passes beyond the start (and the bracket end), fallback hands the
active components to scipy.optimize.root(method="hybr").
accel="newton" needs dg (dg(H), full length: the diagonal
dg_j / dH_j) and independent components (coupled False, else
ValueError). It runs a safeguarded Newton per component, H <- H -
F / (dg - 1), inside a bracket that starts as [1, 1e6) (F(1) >=
0 because g >= 1, so the end 1 may be the root) and narrows to the
points where F was measured > 0 (lower, then open) or < 0 (upper,
open); a step that is not finite or leaves the bracket bisects it. A
converged component is held. After max_iter passes (the start
included) the unconverged solve continues as the bracketed secant from
the last iterate, then hybr as above; its passes add to the count.
Returns (H, passes), passes being the calls of g. Raises
RuntimeError naming "handling time" and the unconverged components
when nothing is accepted.
Source code in pypath/core/ecosim_continuous/hden.py
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 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 | |
solve_hden ¶
solve_hden(y_full, params_dict, forcing, fishing, index, cmco_qb, *, h0=None, tol=1e-12, max_iter=30, fallback=True)
Solve H = 1 + H * q(H) / (cmco_qb * index) at the state y_full.
The full-derivative reference of :func:solve_hden_kernel. Groups with
cmco_qb > 0 and index > 0 are solved; the rest keep H = 1.
q(H) is the link consumption of one deriv_vector call with
_hden_exact (and no _hden_solver) on a shallow copy of
params_dict; the caller's dict and arrays are never written.
:func:iterate_hden iterates from h0 (default
params_dict["_hden0"]) with tol, max_iter and fallback,
as a coupled map when a link has ScrambleSelf > 0.
Returns (H, n_evaluations); raises RuntimeError naming the
unconverged groups when no solution is found.
Source code in pypath/core/ecosim_continuous/hden.py
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 | |
solve_hden_kernel ¶
solve_hden_kernel(inputs: KernelInputs, *, tol: float = 1e-12, max_iter: int = 30, fallback: bool = True) -> tuple[np.ndarray, int]
Solve Hden on the consumption kernel alone, at the state inputs
describe (deriv_vector hands them to params["_hden_solver"]).
As :func:solve_hden with q(H) = HdenKernel(inputs).q(H), from
inputs.hden0: groups with cmco_qb > 0 and index > 0 are
solved, the rest keep H = 1. The map is coupled when a consuming link has
ScrambleSelf > 0, and then takes undamped passes. Otherwise each
predator is solved by Newton (iterate_hden(accel="newton")), g
and dg = (q + H dq) / (cmco_qb * index) coming from one
:meth:HdenKernel.q_and_dq per pass. Returns (H, passes); raises
RuntimeError naming "handling time" and the groups when no solution
is found.
Source code in pypath/core/ecosim_continuous/hden.py
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 | |
continuous_emig ¶
continuous_emig(emig: Optional[ndarray], emig_rate: Optional[ndarray], n_living: int) -> Optional[np.ndarray]
R4: emigration rates of living groups for the continuous path.
EwE sets Emig = Emigration / B0 for living groups (so emig == 0
means no Emigration was entered) and never reads EmigRate for them.
Here a living group with emig == 0 and emig_rate > 0 takes the
rate; every other entry keeps emig. With emig None, the rates
start from zeros. Returns a new array, or None when both inputs are None
or the result is all zero.
Source code in pypath/core/ecosim_continuous/rhs.py
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 | |
neutral_forcing ¶
neutral_forcing(params_dict: dict) -> dict
Unforced monthly forcing: ones for time/prey/search/mortality/effort, zeros for forced biomass and migration.
Source code in pypath/core/ecosim_continuous/forcing.py
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | |
feeding_time ¶
feeding_time(params, risk0: Optional[ndarray]) -> Optional[FeedingTime]
The feeding-time states of a scenario's params, or None.
risk0 is the setup's base predation risk (None when RiskTime is
off). None is returned when no living group has FtimeAdj > 0.
Source code in pypath/core/ecosim_continuous/feeding.py
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 | |
ftime_target ¶
ftime_target(ft, adj, qopt, food_gain, index, lower, cap) -> np.ndarray
_ftime_update_rpath over arrays, clipped to [lower, cap].
lower + (1 - lower) * ft * ((1 - adj) + adj * qopt / (food_gain /
index)), in the scalar rule's order of operations. Where food_gain,
index or qopt is <= 0 the feeding time is kept (no division at a
zero index).
Source code in pypath/core/ecosim_continuous/feeding.py
73 74 75 76 77 78 79 80 81 82 83 84 85 86 | |
exchange_rate ¶
exchange_rate(rates: dict, y_full: ndarray, params_dict: dict, forcing: dict) -> float
The net external flux of groups 1..n_bio (per year), from one
evaluation's rates at the full state y_full.
It uses exactly these terms:
- in:
rates["Production"]of the living groups that are not consumers (producers, and groups with QB 0, drawn from no food);rates["Import"];params_dict["Immigration"]andforcing["ForcedMigrate"]of the living groups; and the pools'_det_inflow(params_dict["DetInput"]plus pool Immigration); - out: respiration
(1 - Unassim) x rates["FoodGain"]of the living groups, lessrates["Production"]for consumers;rates["Landed"]of groups1..n_bio(the catch of the fishing links to no detritus pool, plus the forced F; under the EwE rule none from a pool, whose catch stays in it);rates["EmigLoss"]of the living groups; under the EwE rule (DetPassedPropset) a pool'sparams_dict["Emig"] x y_full; andrates["DetExport"](link flows to outside and, under the EwE rule, (DetritusOut - DetPassedProp) x B, both from parameters).
Consumers are told apart as the living kernel does (PP_type as an int
<= 0, then QB > 0). No flow between groups enters: not predation, other
mortality, unassimilated food, the flows between pools, nor discards. A
transfer the derivative does not close therefore leaves
sum(dy) - exchange nonzero.
Source code in pypath/core/ecosim_continuous/rhs.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 | |
continuous_options ¶
continuous_options(method, solver_options: Optional[dict], n_bio: int) -> dict
rsim_run's checks of a continuous method and its solver_options.
method is a name in METHOD_NAMES, in any case; anything else, a
non-string included, raises ValueError listing the methods
(rsim_run calls this for every method but RK4 and AB).
solver_options takes rtol (> 0, default 1e-6), atol (a scalar
0 or
n_biovalues > 0),corrections(True or False, default True),on_failure("raise", the default, or"warn"),hden_tol(the handling-time tolerance, a number in (0, 1e-8], default 1e-12),jacobian("reuse", the default: :class:JacobianReuse; or"solver": the solver's own Jacobians) andforcing_interpolation("constant", the default,"linear"or"smooth": a model option, :class:ForcingInterpolant) andpositivity("clip", the default, or"log": a numerical option, the same equations with the biomass states integrated asln B, see :func:integrate_month),fast_groups("states", the default, or"quasi-steady": a model option, :class:QuasiSteady) andqs_rate(a number > 0 per year, default 365: the base loss rate above which a flagged group is quasi-steady; given withfast_groups="states"it is unused, which logs a WARNING); other keys and invalid values raiseValueError.
Returns a dict with keys method (lower case), rtol (float),
atol (None when not given, else an ndarray, 0-d for a scalar),
on_failure, corrections (bool), hden_tol (float),
jacobian, forcing_interpolation, positivity, fast_groups
and qs_rate (float).
Source code in pypath/core/ecosim_continuous/options.py
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 | |
default_atol ¶
default_atol(b0_bio: ndarray, rtol: float = 1e-06) -> np.ndarray
Absolute tolerance per state, scaled to the base biomass and, so that
a tighter rtol is not capped by atol, to rtol / 1e-6.
Source code in pypath/core/ecosim_continuous/options.py
203 204 205 206 207 | |
quasi_steady_groups ¶
quasi_steady_groups(base_rate: ndarray, no_integrate, qs_rate: float, *, forced: Optional[ndarray] = None, stanza=()) -> tuple[list[int], dict[str, list[int]]]
The run's quasi-steady groups (fast_groups="quasi-steady").
base_rate[i - 1] is group i's base loss rate, LossPropToB /
B at the unforced base (:meth:ContinuousRHS.base_loss_rate), for
groups 1..n; no_integrate holds the scenario's NoIntegrate
flags, slot 0 first (RsimParams.NoIntegrate). A group qualifies when
it is flagged and its base loss rate exceeds qs_rate (EwE's flag,
24 /yr, also flags groups that are not fast: LT2022's Zooplankton turns
over at 25 /yr). A qualifying group that is forced in any month of the
run (forced[i - 1]) or is a stanza group (in stanza) stays a
state for the whole run.
Returns (selected, excluded): the selected group numbers, ascending,
and {"forced": [...], "stanza": [...]}, the qualifying groups kept
as states (a forced stanza group is listed as forced).
Source code in pypath/core/ecosim_continuous/quasi_steady.py
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 | |
integrate_month ¶
integrate_month(rhs, y0: ndarray, dt: float, method: str, rtol: float, atol, *, on_failure: str = 'raise', label: Optional[str] = None, n_bio: Optional[int] = None, first_step: Optional[float] = None, jac: Optional[Callable] = None, forcing_interpolation: str = 'constant', positivity: str = 'clip', jac_factory: Optional[Callable] = None, quasi_steady: Optional[QuasiSteady] = None, step_floor: Optional[ndarray] = None) -> MonthResult
Solve one month with solve_ivp and average rates by quadrature.
The means are 6-point Gauss-Legendre quadrature of the dense output over
the month (over the interval actually reached after a failure). With
on_failure="warn" a failed solve logs a warning and returns the last
state reached; otherwise it raises RuntimeError. Even with "warn", a
non-finite derivative or non-finite rates at the start state raise, and
so does any exception from rhs itself (such as a handling-time solve
that fails inside the right-hand side). label (rsim_run passes
"month m (year y)") prefixes the logged warnings; rsim_run adds
the month to raised errors itself. n_bio (default len(y0)) is the
number of leading biomass states: the rates, loss rates and y_mean
use those, the rest are other states (feeding times). The quadrature
nodes' biomass states are clipped at 0 before rhs.rates and the
loss-rate division; when the rates fall back on the start state (with
"warn"), y_mean does too. first_step (default: the solver's own
choice) is passed to solve_ivp, and so is jac (a Jacobian callable,
such as :meth:JacobianReuse.for_month's) unless it is None or the method
is DOP853, which uses none.
forcing_interpolation (one of FORCING_INTERPOLATIONS, else
ValueError) is the run's: with "linear" the tent's kink at
mid-month splits the quadrature into 6-point Gauss-Legendre on each
half (12 nodes; :func:_split_nodes), and with "linear" or
"smooth" the rates are evaluated as rhs.rates(y, t) at the node
times, so they see the forcing applied there. With "constant" the
6-point rule and rhs.rates(y) stay as they were (rsim_run
passes "constant" when no forcing varies in time, so no kink).
positivity="log" (a numerical option: the same equations in other
variables, so the same solution to the tolerance; "clip" is the
default and is the code above unchanged) integrates z = ln max(B,
1e-20) for the n_bio biomass states and leaves the feeding times
linear. The solver's function is B = exp(max(z, ln 1e-20)), dz =
dB / B from rhs(t, [B, Ft]), with dz = max(dz, 0) where z <= ln 1e-20
(the floor absorbs: a group there can only grow). A forced group has
dB = 0 and so a constant z. The log state's atol is
min(max(atol_i / y0_i, rtol), 0.1) (the linear tolerance at the month-start
biomass; atol is broadcast to y0's length first). sol.y and
the dense output are transformed back to biomass before the means,
y_end, the stats and the budget, so the quadrature means are of B and
everything downstream sees biomass. rhs always sees B >= 1e-20,
so rhs.stats["clips"] stays 0 and min_state is the smallest B
evaluated. A Jacobian is differentiated in z: a linear-space jac with
positivity="log" raises ValueError; jac_factory(fun,
step_floor) (JacobianReuse.for_month) is called with the wrapped
function and the difference step's floor in the solver's states instead:
min(atol_z / rtol, 1) for a log state (1 unless rtol > 0.1, so
h = 1.49e-8 x max(|z|, 1), a relative step in B), and
step_floor's value for a feeding time.
quasi_steady (a :class:QuasiSteady over rhs, its month set by
its set_month; a model option) reduces the solver's state: the
solver integrates quasi_steady's slow states (from y0's, with
atol broadcast to y0 and taken at them; "log" transforms the
slow biomass states), and the state reached and every quadrature node
are expanded to every state, the selected groups at their solved
biomass (:meth:QuasiSteady.expand at the node's time), before the
means, the rates, the exchange and y_end, so MonthResult keeps
its layout. A Jacobian is differentiated in the slow states: a jac
with quasi_steady raises ValueError, and jac_factory is
called with the solver's function and the slow states' step_floor
(as under "log"). A quasi-steady solve that fails raises, as any
error from rhs does.
step_floor (a scalar or one value > 0 per state of y0, in
biomass and feeding-time units; default atol / rtol) is the floor of
jac_factory's difference step for the linear states (rsim_run
passes its capped floor, see :class:JacobianReuse).
rhs.stats, when the right-hand side keeps one (ContinuousRHS,
reset by its set_month), counts the solver's evaluations, the start
check and jac's columns included; the quadrature's rhs.rates
calls do not count.
Source code in pypath/core/ecosim_continuous/month.py
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 | |
month_budget ¶
month_budget(y0: ndarray, res: MonthResult, n_living: int, n_bio: int, forced: bool, *, quasi_steady: bool = False) -> tuple[Optional[float], Optional[float]]
(budget_residual, pool_budget_residual) of an integrated month.
Over the biomass states y0[:n_bio] and res.y_end[:n_bio] (any
states beyond them are feeding times), with t = res.t_reached:
budget_residual = (sum(y_end) - sum(y0) - t * exchange_mean) /
sum(y0) and pool_budget_residual the largest over the detritus
pools of |y_end_d - y0_d - t * pool_net_mean_d| / y0_d. Both are None
when forced (forced biomass: its flows are imposed), under
quasi_steady groups (the reduction sets their dB_f/dt to 0 while
B_f moves, so the budget does not close to the solver's tolerance)
or when the month is degraded (its means are the start state's);
the pool residual is None without pool_net_mean or pools, and skips
pools starting at or below the 1e-20 floor (None if every pool is
skipped).
Source code in pypath/core/ecosim_continuous/month.py
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 | |
Advanced Ecosim (State Forcing & Diet Rewiring)¶
rsim_run_advanced runs rsim_run. State forcing and diet rewiring are not
implemented in this version and raise NotImplementedError. Prey switching
(EwE SwitchPower) is available instead of diet rewiring: set
scenario.params.SwitchPower, or use the Prey Switching control on the app's
Ecosim page.
pypath.core.ecosim_advanced ¶
Advanced Ecosim entry point: state forcing and diet rewiring (not implemented).
rsim_run_advanced runs rsim_run. State forcing (StateForcing)
and diet rewiring (DietRewiring) are not implemented in this version and
raise NotImplementedError. Earlier versions ran a placeholder loop that
never integrated, so they returned the start biomass in every month. Prey
switching, EwE's per-predator SwitchPower, is available instead of diet
rewiring: set scenario.params.SwitchPower, which rsim_run applies, or
use the Prey Switching control on the app's Ecosim page.
apply_state_forcing and apply_diet_rewiring are standalone helpers
that no simulation calls.
apply_state_forcing ¶
apply_state_forcing(state: ndarray, year: float, state_forcing: Optional[StateForcing], variable: StateVariable = StateVariable.BIOMASS) -> np.ndarray
Apply state forcing to current state vector.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
ndarray
|
Current state vector (biomass, catch, etc.) |
required |
year
|
float
|
Current simulation year (fractional for monthly steps) |
required |
state_forcing
|
StateForcing or None
|
Forcing configuration |
required |
variable
|
StateVariable
|
Which variable is being forced |
BIOMASS
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Modified state vector |
Source code in pypath/core/ecosim_advanced.py
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 | |
apply_diet_rewiring ¶
apply_diet_rewiring(biomass: ndarray, diet_rewiring: Optional[DietRewiring], month: int) -> Optional[np.ndarray]
Update diet matrix based on current biomass.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
biomass
|
ndarray
|
Current biomass values |
required |
diet_rewiring
|
DietRewiring or None
|
Diet rewiring configuration |
required |
month
|
int
|
Current month (for update interval check) |
required |
Returns:
| Type | Description |
|---|---|
ndarray or None
|
Updated diet matrix, or None if no update |
Source code in pypath/core/ecosim_advanced.py
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 | |
rsim_run_advanced ¶
rsim_run_advanced(scenario: RsimScenario, state_forcing: Optional[StateForcing] = None, diet_rewiring: Optional[DietRewiring] = None, method: str = 'RK4', years: Optional[range] = None, verbose: bool = False, *, on_month: Optional[Callable[[int, int], Optional[bool]]] = None) -> RsimOutput
Run Ecosim with rsim_run. Diet rewiring and state forcing are refused.
Without diet rewiring or state forcing, this is
rsim_run(scenario, method=method, years=years, on_month=on_month).
Its output is returned unchanged. An unknown method, or a years
range that does not start at scenario.start_year, raises
rsim_run's ValueError.
Diet rewiring and state forcing are not implemented in this version.
Either one raises NotImplementedError. Earlier versions ran a
placeholder loop that never integrated: every method, even an
unknown one, returned the start biomass of every unforced group in
every month, and zero catch. The rewired diet was computed but never
applied.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scenario
|
RsimScenario
|
Standard Ecosim scenario |
required |
state_forcing
|
StateForcing
|
Must be None or empty (no forcing functions). Any forcing function
raises |
None
|
diet_rewiring
|
DietRewiring
|
Must be None or disabled ( |
None
|
method
|
str
|
Integration method, passed to |
'RK4'
|
years
|
range
|
Years to simulate, passed to |
None
|
verbose
|
bool
|
Unused, kept for compatibility. |
False
|
on_month
|
callable
|
Passed to |
None
|
Returns:
| Type | Description |
|---|---|
RsimOutput
|
|
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If |
ValueError
|
From |
RunCancelled
|
From |
Source code in pypath/core/ecosim_advanced.py
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 | |
create_advanced_scenario ¶
create_advanced_scenario(base_scenario: RsimScenario, state_forcing: Optional[StateForcing] = None, diet_rewiring: Optional[DietRewiring] = None) -> tuple[RsimScenario, StateForcing, DietRewiring]
Create advanced scenario with forcing and rewiring.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
base_scenario
|
RsimScenario
|
Base Ecosim scenario |
required |
state_forcing
|
StateForcing
|
State forcing configuration |
None
|
diet_rewiring
|
DietRewiring
|
Diet rewiring configuration |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
scenario |
RsimScenario
|
Base scenario (unchanged) |
state_forcing |
StateForcing
|
State forcing (created if None) |
diet_rewiring |
DietRewiring
|
Diet rewiring (created if None) |
Source code in pypath/core/ecosim_advanced.py
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 | |
Stanzas (Multi-Stanza Groups)¶
pypath.core.stanzas ¶
Multi-stanza (age-structured) groups for PyPath.
This module implements age-structured population dynamics using Von Bertalanffy growth and stage-based mortality rates.
Based on Rpath's rpath.stanzas() and rsim.stanzas() functions, and on the SplitUpdate / SplitSetPred routines of Rpath's ecosim.cpp.
In rsim_run the age structure is coupled to Ecosim as in Rpath: each month
:func:split_update ages numbers and weights with the realised mortality and
food intake of each stanza's group and adds recruits, and
:func:split_set_pred sets the stanza groups' biomass to sum(N * W). The
groups eat in proportion to sum(N * Q) relative to its base value.
EcosimStanzaParams
dataclass
¶
Container for all multi-stanza parameters.
Attributes:
n_stanza_groups: Number of stanza groups
stanza_groups: List of StanzaGroup objects
stanza_individuals: List of StanzaIndividual objects
st_groups: DataFrame with stanza calculations per age
plus_group_rule: Age table :func:rpath_stanzas built ("rpath" or
"ewe")
Source code in pypath/core/stanzas.py
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 | |
RsimStanzaState
dataclass
¶
Live age structure of the multi-stanza groups during a run.
Rpath keeps these in the simulation state (NageS, WageS,
QageS, StanzaPred, SpawnBio, EggsStanza) and leaves the
base* arrays of :class:RsimStanzas untouched. Keeping them apart
means a scenario can be run more than once from the same start.
Source code in pypath/core/stanzas.py
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 | |
from_base
classmethod
¶
from_base(stanzas: RsimStanzas, n_groups: int) -> 'RsimStanzaState'
Start state: copies of the base arrays (Rpath rsim.scenario).
Source code in pypath/core/stanzas.py
784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 | |
RsimStanzas
dataclass
¶
Stanza parameters for Ecosim simulation.
Contains age-structured dynamics parameters needed by the simulation engine.
Source code in pypath/core/stanzas.py
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 | |
StanzaGroup
dataclass
¶
Parameters for a single multi-stanza species group.
Attributes:
stanza_group_num: Index of this stanza group (1-based)
n_stanzas: Number of age stanzas in this group
vbgf_ksp: Von Bertalanffy K parameter (annual)
vbgf_d: Von Bertalanffy d parameter (default 2/3)
wmat: Weight at 50% maturity relative to Winf
bab: Biomass accumulation / background mortality
rec_power: Recruitment power parameter
recruits: Base number of recruits (R)
last_month: Final month of the oldest age class
ahat, rhat: Ford-Walford intercept and slope of the plus group
(EwE age table only; see :func:_ewe_age_table)
Source code in pypath/core/stanzas.py
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 | |
StanzaIndividual
dataclass
¶
Parameters for an individual stanza (age class) within a group.
Attributes: stanza_group_num: Index of parent stanza group stanza_num: Index of this stanza within group (1-based) group_num: Ecopath group number for this stanza group_name: Name of this stanza group in model first: First month of this age class last: Last month of this age class z: Total mortality rate (annual) leading: True if this is the leading (reference) stanza leading_cb: True if this stanza anchors the group's consumption (EwE's LeadingCB); when no stanza is marked, the leading one does biomass: Calculated biomass qb: Calculated Q/B
Source code in pypath/core/stanzas.py
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 | |
calculate_survival ¶
calculate_survival(z_by_month: ndarray, bab: float = 0.0) -> np.ndarray
Calculate cumulative survival to each age.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
z_by_month
|
ndarray
|
Monthly mortality rate for each month |
required |
bab
|
float
|
Background/accumulation mortality rate (annual) |
0.0
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Cumulative survival probability to each age |
Source code in pypath/core/stanzas.py
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 | |
check_stanza_arrays ¶
check_stanza_arrays(stanzas: RsimStanzas, n_groups: int) -> List[str]
Return the problems that stop the age structure from being simulated.
An empty list means :func:split_update / :func:split_set_pred can run.
Source code in pypath/core/stanzas.py
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 | |
create_stanza_params ¶
create_stanza_params(groups: List[Dict[str, Any]], individuals: List[Dict[str, Any]]) -> EcosimStanzaParams
Create EcosimStanzaParams from dictionaries.
Convenience function to create stanza parameters from dictionary inputs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
groups
|
List[Dict[str, Any]]
|
List of dictionaries with stanza group parameters. Required keys: stanza_group_num, n_stanzas, vbgf_ksp. Optional keys: vbgf_d, wmat, bab, rec_power. |
required |
individuals
|
List[Dict[str, Any]]
|
List of dictionaries with individual stanza parameters. Required keys: stanza_group_num, stanza_num, group_num, group_name, first, last, z. Optional keys: leading, leading_cb (defaults to leading). |
required |
Returns:
| Type | Description |
|---|---|
EcosimStanzaParams
|
EcosimStanzaParams object |
Examples:
>>> groups = [{'stanza_group_num': 1, 'n_stanzas': 2, 'vbgf_ksp': 0.3}]
>>> individuals = [
... {'stanza_group_num': 1, 'stanza_num': 1, 'group_num': 1,
... 'group_name': 'Fish_juv', 'first': 0, 'last': 11,
... 'z': 1.5, 'leading': False},
... {'stanza_group_num': 1, 'stanza_num': 2, 'group_num': 2,
... 'group_name': 'Fish_adult', 'first': 12, 'last': 60,
... 'z': 0.5, 'leading': True}
... ]
>>> params = create_stanza_params(groups, individuals)
Source code in pypath/core/stanzas.py
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 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 | |
ecosim_stanza_params ¶
ecosim_stanza_params(stanzas: Any, model: DataFrame | None = None) -> EcosimStanzaParams
Convert RpathParams.stanzas to the form the stanza engine uses.
RpathParams.stanzas keeps the stanza tables as DataFrames
(stgroups and stindiv, Rpath's layout), while rpath_stanzas
and rsim_stanzas work on :class:EcosimStanzaParams. An
EcosimStanzaParams passed in is returned as it is.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stanzas
|
Any
|
|
required |
model
|
DataFrame | None
|
The model table. Used to look up the group number of each stanza
when |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If a stanza lacks a value the dynamics need (Z, first month, leading flag, or the VBGF K of its group), or names a group that is not in the model. |
Source code in pypath/core/stanzas.py
1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 | |
has_stanza_tables ¶
has_stanza_tables(stanzas: Any) -> bool
True if stanzas describes at least one stanza group.
Looks at the tables rather than n_stanza_groups alone, because code
that assigns stgroups/stindiv directly often leaves the count at 0.
Source code in pypath/core/stanzas.py
1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 | |
rpath_stanzas ¶
rpath_stanzas(rpath_params: RpathParams, stanza_params: EcosimStanzaParams | None = None, rule: str = 'rpath') -> RpathParams
Calculate biomass and consumption for multi-stanza groups.
Uses the leading stanza to calculate biomass and consumption of trailing stanzas necessary to support the leading stanza.
This implements Von Bertalanffy growth to distribute biomass across age classes based on the leading stanza's biomass.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rpath_params
|
RpathParams
|
RpathParams object with stanza information |
required |
stanza_params
|
EcosimStanzaParams
|
Stanza parameters to work on. Defaults to |
None
|
rule
|
('rpath', 'ewe')
|
The age table. "rpath" (default) runs it out to 99.999 % of the
cumulative biomass, as Rpath's |
"rpath"
|
Returns:
| Type | Description |
|---|---|
RpathParams
|
Updated RpathParams with calculated stanza biomass and Q/B |
Source code in pypath/core/stanzas.py
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 | |
rsim_stanzas ¶
rsim_stanzas(rpath_params: RpathParams, state: ndarray, params: dict, stanza_params: EcosimStanzaParams | None = None) -> RsimStanzas
Initialize stanza parameters for Ecosim simulation.
Creates the stanza parameter structure needed by rsim_run().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rpath_params
|
RpathParams
|
RpathParams object with stanza information |
required |
state
|
ndarray
|
RsimState object with initial state |
required |
params
|
dict
|
RsimParams object with simulation parameters |
required |
stanza_params
|
EcosimStanzaParams
|
The object :func: |
None
|
Returns:
| Type | Description |
|---|---|
RsimStanzas
|
RsimStanzas object with simulation parameters |
Source code in pypath/core/stanzas.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 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 | |
split_set_pred ¶
split_set_pred(stanzas: RsimStanzas, sstate: RsimStanzaState, biomass: ndarray) -> None
Sum the age structure into group totals (Rpath SplitSetPred).
Sets each stanza group's biomass to sum(N * W) over its months, and its
numbers and StanzaPred (sum(N * Q), the consumption index used by the
functional response and :func:split_update). biomass is updated in
place: this is what couples the age structure to Ecosim.
Source code in pypath/core/stanzas.py
1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 | |
split_update ¶
split_update(stanzas: RsimStanzas, sstate: RsimStanzaState, biomass: ndarray, food_gain: ndarray, loss_prop_to_b: ndarray, forced_recs: ndarray | None = None, month_index: int | None = None) -> None
Advance the stanza age structure by one month (Rpath SplitUpdate).
For every stanza the numbers at age are reduced by the month's realised
mortality, exp(-LossPropToB / 12 / B), and weights grow by
WageS = vBM * WageS + (FoodGain / StanzaPred) * SplitAlpha. Spawning
biomass (weight above Wmat) sets the egg output, ages move up one
month (the oldest two months merge into the plus group), and recruits
enter at the first month as
RscaleSplit * RzeroS * (eggs / baseEggs) ** RecPower.
With stanzas.plus_group_rule == "ewe" (EwE6 SplitUpdate) the plus
group's weight is (Su * Ahat + (1 - Su) * W[n-1]) / (1 - Rhat * Su)
instead of the numbers-weighted mean, and the consumption weights
qage_s stay at the setup's W^(2/3), as EwE's SplitSetPred.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stanzas
|
RsimStanzas
|
Stanza parameters; not modified. |
required |
sstate
|
RsimStanzaState
|
Live age structure; updated in place. |
required |
biomass
|
ndarray
|
Group biomass (Rsim indexing, Outside = 0) the rates were taken at. |
required |
food_gain
|
ndarray
|
Consumption by each group, and its losses proportional to biomass (predation + M0 + fishing), per year, from the derivative. |
required |
loss_prop_to_b
|
ndarray
|
Consumption by each group, and its losses proportional to biomass (predation + M0 + fishing), per year, from the derivative. |
required |
forced_recs
|
ndarray
|
Recruitment forcing by group for this month. Like Rpath, it is read at the group of the last stanza. |
None
|
Source code in pypath/core/stanzas.py
869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 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 | |
stanza_group_indices ¶
stanza_group_indices(stanzas: RsimStanzas) -> np.ndarray
Model group numbers (Rsim indexing, Outside = 0) of all stanza groups.
Source code in pypath/core/stanzas.py
803 804 805 806 807 808 809 | |
von_bertalanffy_consumption ¶
von_bertalanffy_consumption(wage_s: ndarray, d: float = 0.66667) -> np.ndarray
Calculate consumption at age from weight.
Q(a) = W(a)^d
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
wage_s
|
ndarray
|
Weight at age relative to Winf |
required |
d
|
float
|
Allometric exponent (default 2/3) |
0.66667
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Consumption at each age |
Source code in pypath/core/stanzas.py
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 | |
von_bertalanffy_weight ¶
von_bertalanffy_weight(age: ndarray, k: float, d: float = 0.66667) -> np.ndarray
Calculate weight at age using Von Bertalanffy growth model.
W(a) = (1 - exp(-K * (1-d) * a))^(1/(1-d))
Weight is relative to Winf (asymptotic weight = 1).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
age
|
ndarray
|
Age in months |
required |
k
|
float
|
Monthly K parameter (Ksp * 3 / 12) |
required |
d
|
float
|
Allometric exponent (default 2/3) |
0.66667
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Weight relative to Winf at each age |
Raises:
| Type | Description |
|---|---|
ValueError
|
If d is not in the open interval (0, 1). |
Source code in pypath/core/stanzas.py
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 | |
Adjustments¶
pypath.core.adjustments ¶
Adjustment functions for Ecosim scenarios.
This module provides functions to modify fishing rates, forcing functions, and other scenario parameters over time.
Based on Rpath's adjust.fishing(), adjust.forcing(), and adjust.scenario() functions.
adjust_fishing ¶
adjust_fishing(scenario: RsimScenario, parameter: str, group: Union[str, int, List[Union[str, int]]], sim_year: Union[int, range, List[int]], value: Union[float, ndarray], sim_month: Optional[Union[int, range, List[int]]] = None) -> RsimScenario
Adjust fishing parameters in an Ecosim scenario.
Modifies fishing-related forcing matrices (ForcedEffort, ForcedFRate, or ForcedCatch) for specified groups and time periods.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scenario
|
RsimScenario
|
RsimScenario object to modify |
required |
parameter
|
str
|
One of 'ForcedEffort', 'ForcedFRate', or 'ForcedCatch' |
required |
group
|
Union[str, int, List[Union[str, int]]]
|
Group name(s) or index(es) to modify. Can be: - Single group name (str) or index (int) - List of group names or indices |
required |
sim_year
|
Union[int, range, List[int]]
|
Year(s) to modify, counted from the scenario's first year
( |
required |
value
|
Union[float, ndarray]
|
New value(s) to set. Can be: - Single value applied to all specified cells - Array matching the shape of selected cells - For ForcedEffort, one value per year, held through that year's selected months |
required |
sim_month
|
Optional[Union[int, range, List[int]]]
|
Optional month(s) to modify (1-12). Only used for ForcedEffort which is monthly. If None, modifies all months. |
None
|
Returns:
| Type | Description |
|---|---|
RsimScenario
|
Modified scenario object |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a year lies outside the scenario or a month outside 1 to 12. |
Examples:
>>> # Double fishing mortality for 'Fish' group in years 10-20
>>> scenario = adjust_fishing(
... scenario,
... parameter='ForcedFRate',
... group='Fish',
... sim_year=range(10, 21),
... value=0.5
... )
>>> # Set catch quota
>>> scenario = adjust_fishing(
... scenario,
... parameter='ForcedCatch',
... group=['Cod', 'Haddock'],
... sim_year=2025,
... value=100.0
... )
Source code in pypath/core/adjustments.py
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 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 | |
adjust_forcing ¶
adjust_forcing(scenario: RsimScenario, parameter: str, group: Union[str, int, List[Union[str, int]]], sim_year: Union[int, range, List[int]], sim_month: Union[int, range, List[int]], value: Union[float, ndarray]) -> RsimScenario
Adjust forcing parameters in an Ecosim scenario.
Modifies environmental forcing matrices (ForcedPrey, ForcedMort, ForcedRecs, ForcedSearch, ForcedActresp, ForcedMigrate, ForcedBio) for specified groups and time periods.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scenario
|
RsimScenario
|
RsimScenario object to modify |
required |
parameter
|
str
|
One of: - 'ForcedPrey': Prey availability multiplier - 'ForcedMort': Additional mortality multiplier - 'ForcedRecs': Recruitment multiplier - 'ForcedSearch': Search rate multiplier - 'ForcedActresp': Active respiration multiplier - 'ForcedMigrate': Migration rate (additive) - 'ForcedBio': Biomass forcing (-1 = off) |
required |
group
|
Union[str, int, List[Union[str, int]]]
|
Group name(s) or index(es) to modify |
required |
sim_year
|
Union[int, range, List[int]]
|
Year(s) to modify |
required |
sim_month
|
Union[int, range, List[int]]
|
Month(s) to modify (1-12) |
required |
value
|
Union[float, ndarray]
|
New value(s) to set |
required |
Returns:
| Type | Description |
|---|---|
RsimScenario
|
Modified scenario object |
Examples:
>>> # Reduce prey availability in summer
>>> scenario = adjust_forcing(
... scenario,
... parameter='ForcedPrey',
... group='Zooplankton',
... sim_year=range(1, 51),
... sim_month=[6, 7, 8],
... value=0.8
... )
>>> # Add pulse recruitment
>>> scenario = adjust_forcing(
... scenario,
... parameter='ForcedRecs',
... group='Fish',
... sim_year=15,
... sim_month=3,
... value=2.0
... )
Source code in pypath/core/adjustments.py
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 | |
adjust_group_parameter ¶
adjust_group_parameter(scenario: RsimScenario, group: Union[str, int], parameter: str, value: float) -> RsimScenario
Adjust a parameter for a specific group.
Modifies group-level parameters in the scenario's params object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scenario
|
RsimScenario
|
RsimScenario object to modify |
required |
group
|
Union[str, int]
|
Group name or index |
required |
parameter
|
str
|
Parameter name. Options include: - 'MzeroMort': Background mortality - 'UnassimRespFrac': Unassimilated fraction - 'ActiveRespFrac': Active respiration fraction - 'FtimeAdj': Feeding time adjustment - 'PBopt': Optimal P/B |
required |
value
|
float
|
New value to set |
required |
Returns:
| Type | Description |
|---|---|
RsimScenario
|
Modified scenario object |
Source code in pypath/core/adjustments.py
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 | |
adjust_scenario ¶
adjust_scenario(scenario: RsimScenario, parameter: str, value: Union[float, int, ndarray]) -> RsimScenario
Adjust global scenario parameters.
Modifies simulation-wide parameters in the scenario's params object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scenario
|
RsimScenario
|
RsimScenario object to modify |
required |
parameter
|
str
|
Parameter name to modify. Common options: - 'BURN_YEARS': Number of burn-in years (-1 = off) - 'COUPLED': Coupling flag (0 = uncoupled, 1 = coupled) - 'RK4_STEPS': Integration steps per month - 'SENSE_LIMIT': Sensitivity limits [min, max] |
required |
value
|
Union[float, int, ndarray]
|
New value to set |
required |
Returns:
| Type | Description |
|---|---|
RsimScenario
|
Modified scenario object |
Examples:
>>> # Enable burn-in period
>>> scenario = adjust_scenario(scenario, 'BURN_YEARS', 10)
>>> # Change integration precision
>>> scenario = adjust_scenario(scenario, 'RK4_STEPS', 8)
Source code in pypath/core/adjustments.py
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 | |
create_fishing_ramp ¶
create_fishing_ramp(scenario: RsimScenario, group: Union[str, int], start_year: int, end_year: int, start_value: float, end_value: float, parameter: str = 'ForcedFRate') -> RsimScenario
Create a linear ramp in fishing pressure.
Convenience function to linearly interpolate fishing between two values over a range of years.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scenario
|
RsimScenario
|
RsimScenario object to modify |
required |
group
|
Union[str, int]
|
Group to modify |
required |
start_year
|
int
|
First year of ramp |
required |
end_year
|
int
|
Last year of ramp |
required |
start_value
|
float
|
Value at start_year |
required |
end_value
|
float
|
Value at end_year |
required |
parameter
|
str
|
Fishing parameter to modify |
'ForcedFRate'
|
Returns:
| Type | Description |
|---|---|
RsimScenario
|
Modified scenario object |
Source code in pypath/core/adjustments.py
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 | |
create_pulse_forcing ¶
create_pulse_forcing(scenario: RsimScenario, group: Union[str, int], pulse_years: List[int], pulse_months: Union[int, List[int]], magnitude: float, parameter: str = 'ForcedRecs') -> RsimScenario
Create pulse forcing events.
Convenience function to add periodic pulse events (e.g., recruitment pulses, mortality events).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scenario
|
RsimScenario
|
RsimScenario object to modify |
required |
group
|
Union[str, int]
|
Group to modify |
required |
pulse_years
|
List[int]
|
List of years with pulse events |
required |
pulse_months
|
Union[int, List[int]]
|
Month(s) when pulse occurs |
required |
magnitude
|
float
|
Multiplier for pulse (>1 = increase, <1 = decrease) |
required |
parameter
|
str
|
Forcing parameter to modify |
'ForcedRecs'
|
Returns:
| Type | Description |
|---|---|
RsimScenario
|
Modified scenario object |
Source code in pypath/core/adjustments.py
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 | |
create_seasonal_forcing ¶
create_seasonal_forcing(scenario: RsimScenario, group: Union[str, int], years: Union[range, List[int]], monthly_values: List[float], parameter: str = 'ForcedPrey') -> RsimScenario
Create seasonal forcing pattern.
Applies a repeating 12-month pattern of forcing values across multiple years.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scenario
|
RsimScenario
|
RsimScenario object to modify |
required |
group
|
Union[str, int]
|
Group to modify |
required |
years
|
Union[range, List[int]]
|
Years to apply pattern |
required |
monthly_values
|
List[float]
|
List of 12 values, one per month |
required |
parameter
|
str
|
Forcing parameter to modify |
'ForcedPrey'
|
Returns:
| Type | Description |
|---|---|
RsimScenario
|
Modified scenario object |
Examples:
>>> # Higher prey availability in summer
>>> seasonal = [0.8, 0.9, 1.0, 1.1, 1.2, 1.3,
... 1.3, 1.2, 1.1, 1.0, 0.9, 0.8]
>>> scenario = create_seasonal_forcing(
... scenario, 'Zooplankton', range(1, 51), seasonal
... )
Source code in pypath/core/adjustments.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 657 658 659 660 661 662 663 664 665 666 667 668 669 | |
set_handling_time ¶
set_handling_time(scenario: RsimScenario, predator: Union[str, int], prey: Union[str, int], value: float) -> RsimScenario
Set handling time (d) for a predator-prey link.
Handling time controls predator satiation: - d = 1000: Off (default) - d = 0: Maximum satiation effect
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scenario
|
RsimScenario
|
RsimScenario object to modify |
required |
predator
|
Union[str, int]
|
Predator group name or index |
required |
prey
|
Union[str, int]
|
Prey group name or index |
required |
value
|
float
|
New handling time value |
required |
Returns:
| Type | Description |
|---|---|
RsimScenario
|
Modified scenario object |
Source code in pypath/core/adjustments.py
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 | |
set_vulnerability ¶
set_vulnerability(scenario: RsimScenario, predator: Union[str, int], prey: Union[str, int], value: float) -> RsimScenario
Set vulnerability (v) for a predator-prey link.
Vulnerability controls the functional response shape: - v = 1: Linear (Type I) - v = 2: Holling Type II (default) - v > 2: Approaches Type III
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scenario
|
RsimScenario
|
RsimScenario object to modify |
required |
predator
|
Union[str, int]
|
Predator group name or index |
required |
prey
|
Union[str, int]
|
Prey group name or index |
required |
value
|
float
|
New vulnerability value |
required |
Returns:
| Type | Description |
|---|---|
RsimScenario
|
Modified scenario object |
Source code in pypath/core/adjustments.py
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 | |
Forcing¶
pypath.core.forcing ¶
Advanced forcing mechanisms for Ecosim simulations.
This module provides: 1. State-variable forcing (biomass, catch, etc.) 2. Dynamic diet rewiring based on prey availability 3. Flexible forcing modes (replace, add, multiply) 4. Temporal interpolation for sub-annual time steps
DietRewiring
dataclass
¶
Dynamic diet matrix rewiring based on prey availability.
Allows predator diet preferences to change over time in response to changing prey abundance (prey switching, adaptive foraging).
Attributes:
| Name | Type | Description |
|---|---|---|
enabled |
bool
|
Whether diet rewiring is active |
switching_power |
float
|
Prey switching exponent (higher = more switching) |
min_proportion |
float
|
Minimum diet proportion to maintain (prevents division by zero) |
update_interval |
int
|
How often to update diet (in months) |
base_diet |
ndarray
|
Original diet matrix (n_prey x n_pred) |
current_diet |
ndarray
|
Current diet matrix (updated each interval) |
Source code in pypath/core/forcing.py
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 | |
initialize ¶
initialize(diet_matrix: ndarray)
Initialize with base diet matrix.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
diet_matrix
|
ndarray
|
Base diet proportions (n_prey x n_pred) |
required |
Source code in pypath/core/forcing.py
298 299 300 301 302 303 304 305 306 307 | |
reset ¶
reset()
Reset diet to base values.
Source code in pypath/core/forcing.py
386 387 388 389 | |
update_diet ¶
update_diet(prey_biomass: ndarray, predator_idx: Optional[int] = None) -> 'np.ndarray | None'
Update diet preferences based on prey availability.
Uses a prey switching model where diet preferences shift toward more abundant prey species.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prey_biomass
|
ndarray
|
Current biomass of all prey groups |
required |
predator_idx
|
int
|
Update only this predator (None = update all) |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Updated diet matrix |
Notes
The prey switching model:
new_diet[prey, pred] = base_diet[prey, pred] * (biomass[prey] / B_ref[prey])^power
Then normalize so sum of diet = 1 for each predator.
Higher switching_power = stronger response to biomass changes.
Source code in pypath/core/forcing.py
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 | |
ForcingFunction
dataclass
¶
Single forcing function for a state variable.
Attributes:
| Name | Type | Description |
|---|---|---|
group_idx |
int
|
Index of group to force (-1 for all groups) |
variable |
StateVariable
|
Which state variable to force |
mode |
ForcingMode
|
How to apply the forcing |
time_series |
ndarray
|
Time series of forced values (years) |
years |
ndarray
|
Year indices corresponding to time_series |
interpolate |
bool
|
Whether to interpolate between annual values |
active |
bool
|
Whether this forcing is currently active |
Source code in pypath/core/forcing.py
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 | |
get_value ¶
get_value(year: float) -> float
Get forced value at given year (with interpolation).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
year
|
float
|
Simulation year (can be fractional for monthly time steps) |
required |
Returns:
| Type | Description |
|---|---|
float
|
Forced value at this time |
Source code in pypath/core/forcing.py
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 | |
ForcingMode ¶
Bases: Enum
Mode for applying forced values.
Source code in pypath/core/forcing.py
25 26 27 28 29 30 31 | |
StateForcing
dataclass
¶
Collection of forcing functions for state variables.
Attributes:
| Name | Type | Description |
|---|---|---|
functions |
list[ForcingFunction]
|
List of individual forcing functions |
Source code in pypath/core/forcing.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 | |
add_forcing ¶
add_forcing(group_idx: int, variable: Union[str, StateVariable], time_series: Union[ndarray, Series, Dict[int, float]], years: Optional[ndarray] = None, mode: Union[str, ForcingMode] = ForcingMode.REPLACE, interpolate: bool = True)
Add a forcing function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
group_idx
|
int
|
Index of group to force |
required |
variable
|
str or StateVariable
|
Which state variable to force |
required |
time_series
|
array - like or dict
|
Time series of forced values If dict, keys are years and values are forced values |
required |
years
|
array - like
|
Year indices (required if time_series is array) |
None
|
mode
|
str or ForcingMode
|
How to apply forcing ("replace", "add", "multiply", "rescale") |
REPLACE
|
interpolate
|
bool
|
Whether to interpolate between annual values |
True
|
Examples:
>>> forcing = StateForcing()
>>> # Force phytoplankton biomass to observed series
>>> forcing.add_forcing(
... group_idx=0,
... variable='biomass',
... time_series={2000: 15.0, 2001: 18.0, 2002: 16.0},
... mode='replace'
... )
>>>
>>> # Add recruitment pulse for herring in 2005
>>> forcing.add_forcing(
... group_idx=3,
... variable='recruitment',
... time_series={2005: 2.5}, # 2.5x normal recruitment
... mode='multiply'
... )
Source code in pypath/core/forcing.py
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 | |
get_forcing ¶
get_forcing(year: float, variable: StateVariable, group_idx: Optional[int] = None) -> List[Tuple[ForcingFunction, float]]
Get all active forcing values for a variable at given time.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
year
|
float
|
Current simulation year |
required |
variable
|
StateVariable
|
Which state variable to query |
required |
group_idx
|
int
|
Specific group index (None = all groups) |
None
|
Returns:
| Type | Description |
|---|---|
list of (ForcingFunction, float)
|
List of (forcing function, forced value) tuples |
Source code in pypath/core/forcing.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 | |
remove_forcing ¶
remove_forcing(group_idx: int, variable: Union[str, StateVariable])
Remove forcing for a specific group and variable.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
group_idx
|
int
|
Index of group |
required |
variable
|
str or StateVariable
|
Which state variable |
required |
Source code in pypath/core/forcing.py
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 | |
StateVariable ¶
Bases: Enum
State variables that can be forced.
Source code in pypath/core/forcing.py
34 35 36 37 38 39 40 41 42 43 | |
create_biomass_forcing ¶
create_biomass_forcing(group_idx: int, observed_biomass: Union[ndarray, Series, Dict[int, float]], years: Optional[ndarray] = None, mode: str = 'replace', interpolate: bool = True) -> StateForcing
Convenience function to create biomass forcing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
group_idx
|
int
|
Index of group to force |
required |
observed_biomass
|
array - like or dict
|
Observed biomass time series |
required |
years
|
array - like
|
Year indices |
None
|
mode
|
str
|
Forcing mode ("replace", "add", "multiply") |
'replace'
|
interpolate
|
bool
|
Whether to interpolate monthly values |
True
|
Returns:
| Type | Description |
|---|---|
StateForcing
|
Forcing object ready to use |
Examples:
>>> # Force phytoplankton to observed biomass
>>> forcing = create_biomass_forcing(
... group_idx=0,
... observed_biomass={2000: 15.0, 2005: 18.0, 2010: 16.0},
... mode='replace'
... )
Source code in pypath/core/forcing.py
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 | |
create_diet_rewiring ¶
create_diet_rewiring(switching_power: float = 2.0, min_proportion: float = 0.001, update_interval: int = 12) -> DietRewiring
Convenience function to create diet rewiring configuration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
switching_power
|
float
|
Prey switching exponent (1.0 = proportional, >1 = switching) |
2.0
|
min_proportion
|
float
|
Minimum diet proportion to maintain |
0.001
|
update_interval
|
int
|
How often to update diet (months) |
12
|
Returns:
| Type | Description |
|---|---|
DietRewiring
|
Diet rewiring object ready to use |
Examples:
>>> # Enable strong prey switching
>>> rewiring = create_diet_rewiring(switching_power=3.0)
Source code in pypath/core/forcing.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 | |
create_recruitment_forcing ¶
create_recruitment_forcing(group_idx: int, recruitment_multiplier: Union[ndarray, Dict[int, float]], years: Optional[ndarray] = None, interpolate: bool = False) -> StateForcing
Convenience function to create recruitment forcing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
group_idx
|
int
|
Index of group to force |
required |
recruitment_multiplier
|
array - like or dict
|
Recruitment multiplier (1.0 = normal, 2.0 = double, etc.) |
required |
years
|
array - like
|
Year indices |
None
|
interpolate
|
bool
|
Whether to interpolate (usually False for recruitment pulses) |
False
|
Returns:
| Type | Description |
|---|---|
StateForcing
|
Forcing object ready to use |
Examples:
>>> # Strong recruitment in 2005, weak in 2010
>>> forcing = create_recruitment_forcing(
... group_idx=3,
... recruitment_multiplier={2005: 3.0, 2010: 0.5}
... )
Source code in pypath/core/forcing.py
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 | |
Recruitment Models¶
Stock-recruitment relationships and larval connectivity helpers for advanced population replenishment dynamics.
pypath.core.recruitment ¶
Advanced recruitment models for Ecosim scenarios.
This module provides a consistent API for stock-recruitment relationships that map spawning stock biomass (SSB) to a recruitment multiplier. The multiplier is intended to scale baseline recruitment processes in dynamic Ecosim simulations.
BevertonHoltRecruitment ¶
Bases: RecruitmentModel
Beverton-Holt model: R = (alpha * SSB) / (1 + beta * SSB).
Source code in pypath/core/recruitment.py
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 | |
LarvalConnectivity ¶
Larval dispersal model linking source and sink recruitment pools.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
connectivity_matrix
|
ndarray
|
Matrix with shape (n_targets, n_sources). Each column describes how recruits from one source distribute across target groups. |
required |
source_groups
|
list[str]
|
Source group names aligned to matrix columns. |
required |
target_groups
|
list[str]
|
Target group names aligned to matrix rows. |
required |
survival_rate
|
float
|
Global larval survival applied after dispersal. |
1.0
|
normalize_columns
|
bool
|
If True, each source column is normalized to sum to 1 when positive. |
True
|
Source code in pypath/core/recruitment.py
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 | |
apply_to_array ¶
apply_to_array(source_recruits: ndarray) -> np.ndarray
Apply connectivity to source recruitment vector.
Source code in pypath/core/recruitment.py
324 325 326 327 328 329 330 331 332 333 | |
disperse ¶
disperse(source_recruitment: dict[str, float]) -> dict[str, float]
Disperse recruitment dictionary into target-group recruitment.
Source code in pypath/core/recruitment.py
335 336 337 338 339 340 341 342 343 344 345 | |
get_connectivity ¶
get_connectivity(source_group: str, target_group: str) -> float
Get dispersal proportion from source to target.
Source code in pypath/core/recruitment.py
314 315 316 317 318 319 320 321 322 | |
set_survival_rate ¶
set_survival_rate(survival_rate: float) -> None
Update larval survival rate.
Source code in pypath/core/recruitment.py
307 308 309 310 311 312 | |
MyersRecruitment ¶
Bases: RecruitmentModel
Myers-style saturating model: R = rmax * SSB^p / (k^p + SSB^p).
Source code in pypath/core/recruitment.py
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 | |
RecruitmentModel ¶
Bases: ABC
Abstract base class for recruitment models.
Recruitment models return multiplicative factors that can be applied to baseline recruitment. A factor of 1.0 indicates baseline recruitment.
Source code in pypath/core/recruitment.py
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 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 | |
__init__ ¶
__init__(name: str = 'RecruitmentModel', rmax: float = 1.0)
Initialize recruitment model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Human-readable model name. |
'RecruitmentModel'
|
rmax
|
float
|
Maximum scaling multiplier used by the model. |
1.0
|
Source code in pypath/core/recruitment.py
24 25 26 27 28 29 30 31 32 33 34 35 36 37 | |
get_recruitment
abstractmethod
¶
get_recruitment(ssb: float, time: float = 0.0, env_factor: float = 1.0) -> float
Get recruitment multiplier for one state.
Source code in pypath/core/recruitment.py
39 40 41 42 43 44 | |
get_recruitment_batch
abstractmethod
¶
get_recruitment_batch(ssb_array: ndarray, time_array: ndarray, env_factors: Optional[ndarray] = None) -> np.ndarray
Get recruitment multipliers for arrays of states.
Source code in pypath/core/recruitment.py
46 47 48 49 50 51 52 53 54 | |
get_recruitment_trajectory ¶
get_recruitment_trajectory(ssb_timeline: dict[float, float], times: ndarray) -> np.ndarray
Interpolate SSB across time and evaluate recruitment trajectory.
Source code in pypath/core/recruitment.py
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 | |
RickerRecruitment ¶
Bases: RecruitmentModel
Ricker model: R = alpha * SSB * exp(-beta * SSB).
Source code in pypath/core/recruitment.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 | |
normalize_ssb_effect ¶
normalize_ssb_effect(ssb: float | ndarray, reference_ssb: float, effect_magnitude: float = 1.0) -> float | np.ndarray
Normalize SSB relative to a reference stock biomass.
Source code in pypath/core/recruitment.py
396 397 398 399 400 401 402 403 404 405 406 407 408 409 | |
validate_recruitment_params ¶
validate_recruitment_params(model_type: str, **kwargs) -> dict[str, float | str]
Validate model parameters for recruitment model construction.
Source code in pypath/core/recruitment.py
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 | |
Ecosim Recruitment Wiring¶
Runtime wiring that patches recruitment processes into RsimScenario
and Ecosim time stepping.
pypath.core.ecosim_recruitment ¶
Recruitment support for Ecosim scenarios.
Monkey-patches RsimScenario with recruitment model registration,
trajectory helpers, and optional larval connectivity application.
add_recruitment_support ¶
add_recruitment_support() -> None
Monkey-patch RsimScenario with recruitment methods.
Source code in pypath/core/ecosim_recruitment.py
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 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 | |
Metabolism¶
Temperature- and size-dependent metabolic scaling utilities.
pypath.core.metabolism ¶
Metabolic scaling models for Ecosim dynamics.
This module provides temperature- and body-size-dependent metabolic scaling utilities used to modulate production and consumption processes.
MetabolicModel
dataclass
¶
Metabolic scaling model with allometric and thermal dependence.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
base_metabolism
|
float
|
Baseline metabolic rate at reference mass and temperature. |
required |
mass_exponent
|
float
|
Allometric exponent for body-mass scaling. |
0.75
|
reference_mass
|
float
|
Body mass where mass-scaling multiplier equals 1.0. |
1.0
|
temperature_dependence
|
TemperatureDependence
|
Temperature model (defaults to q10=2.0 at 10°C). |
None
|
activity_budget
|
float
|
Baseline activity multiplier. |
1.0
|
Source code in pypath/core/metabolism.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 162 163 164 165 166 167 168 169 170 171 172 173 | |
compute_mass_factor ¶
compute_mass_factor(body_mass: float | ndarray) -> float | np.ndarray
Compute allometric mass scaling factor.
Source code in pypath/core/metabolism.py
96 97 98 99 100 101 102 103 104 105 106 107 108 | |
compute_metabolic_rate ¶
compute_metabolic_rate(body_mass: float, temperature: float, activity_multiplier: float = 1.0) -> float
Compute metabolic rate for a single body mass and temperature.
Source code in pypath/core/metabolism.py
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 | |
compute_metabolic_rate_batch ¶
compute_metabolic_rate_batch(body_mass: ndarray, temperature: ndarray, activity_multiplier: Optional[ndarray] = None) -> np.ndarray
Compute metabolic rates for vector inputs.
Source code in pypath/core/metabolism.py
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 | |
compute_temperature_factor ¶
compute_temperature_factor(temperature: float | ndarray) -> float | np.ndarray
Compute thermal scaling factor using configured Q10 model.
Source code in pypath/core/metabolism.py
110 111 112 113 114 | |
TemperatureDependence
dataclass
¶
Q10-based temperature dependence model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
q10_coefficient
|
float
|
Multiplicative increase in rate per +10°C. |
2.0
|
reference_temperature
|
float
|
Reference temperature where factor equals 1.0. |
10.0
|
min_factor
|
float
|
Lower clamp for computed factors. |
0.01
|
max_factor
|
float
|
Upper clamp for computed factors. |
100.0
|
Source code in pypath/core/metabolism.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 | |
compute_q10_factor ¶
compute_q10_factor(temperature: float | ndarray) -> float | np.ndarray
Compute temperature scaling factor using the Q10 formulation.
Source code in pypath/core/metabolism.py
46 47 48 49 50 51 52 53 54 55 | |
apply_size_dependent_rates ¶
apply_size_dependent_rates(base_rates: ndarray, body_mass: ndarray, mass_exponent: float, reference_mass: float = 1.0) -> np.ndarray
Apply allometric mass scaling to an array of baseline rates.
Source code in pypath/core/metabolism.py
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 | |
compute_temperature_adjusted_metabolism ¶
compute_temperature_adjusted_metabolism(base_metabolism: float | ndarray, temperature: float | ndarray, temperature_model: TemperatureDependence) -> float | np.ndarray
Apply thermal scaling to baseline metabolism using a temperature model.
Source code in pypath/core/metabolism.py
199 200 201 202 203 204 205 206 207 208 209 210 | |
Fishing Management¶
Selectivity and management strategy helpers for dynamic fishing controls.
pypath.core.fishing_management ¶
Advanced fishing management models for dynamic selectivity and effort allocation.
DynamicLogisticSelectivity
dataclass
¶
Bases: SelectivityPattern
Logistic selectivity with optional time-varying L50.
S(L) = 1 / (1 + exp(-k * (L - L50_t))).
Source code in pypath/core/fishing_management.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 | |
FishingOptimization
dataclass
¶
Simple fishing optimization utility functions.
Source code in pypath/core/fishing_management.py
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 | |
constrain_sustainability ¶
constrain_sustainability(effort: ndarray, biomass: ndarray, biomass_threshold: float, reduction_factor: float = 0.5) -> np.ndarray
Reduce effort where biomass is below threshold.
Source code in pypath/core/fishing_management.py
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 | |
maximize_revenue ¶
maximize_revenue(catchability: ndarray, biomass: ndarray, price: ndarray, effort_budget: float) -> np.ndarray
Allocate effort proportional to marginal revenue potential.
Source code in pypath/core/fishing_management.py
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 | |
minimize_bycatch ¶
minimize_bycatch(effort: ndarray, bycatch_risk: ndarray, target_reduction: float) -> np.ndarray
Reduce effort in high-bycatch-risk fleets first.
Source code in pypath/core/fishing_management.py
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 | |
SelectivityPattern ¶
Bases: ABC
Abstract selectivity pattern interface.
Source code in pypath/core/fishing_management.py
12 13 14 15 16 17 18 19 20 21 22 23 | |
evaluate
abstractmethod
¶
evaluate(lengths: ndarray, time: Optional[float] = None, space: Optional[str] = None) -> np.ndarray
Evaluate selectivity for provided lengths.
Source code in pypath/core/fishing_management.py
15 16 17 18 19 20 21 22 23 | |
SpatialSelectivity
dataclass
¶
Bases: SelectivityPattern
Spatially varying selectivity using per-zone multipliers.
Source code in pypath/core/fishing_management.py
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 | |
TimeVaryingSelectivity
dataclass
¶
Bases: SelectivityPattern
Time-varying multiplicative selectivity profile.
Source code in pypath/core/fishing_management.py
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 | |
Sensitivity & Uncertainty Analysis¶
Screening, uncertainty propagation, and risk-assessment helpers for scenario robustness analysis.
pypath.core.sensitivity_analysis ¶
Sensitivity and uncertainty analysis utilities for Ecosim-style models.
RiskAssessment
dataclass
¶
Risk metrics for extinction/collapse under uncertainty.
Source code in pypath/core/sensitivity_analysis.py
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 | |
compute_collapse_risk ¶
compute_collapse_risk(biomass: ArrayLike, baseline_biomass: float, collapse_fraction: float = 0.2) -> float
Probability biomass falls below collapse fraction of baseline.
Source code in pypath/core/sensitivity_analysis.py
180 181 182 183 184 185 186 187 188 189 190 191 192 | |
compute_extinction_risk ¶
compute_extinction_risk(biomass: ArrayLike, threshold: float) -> float
Probability biomass falls below extinction threshold.
Source code in pypath/core/sensitivity_analysis.py
173 174 175 176 177 178 | |
worst_case_analysis ¶
worst_case_analysis(outputs: ArrayLike) -> Dict[str, float]
Summarize worst-case, best-case, and spread.
Source code in pypath/core/sensitivity_analysis.py
194 195 196 197 198 199 200 201 202 203 204 | |
SensitivityAnalyzer
dataclass
¶
Compute local/global sensitivity diagnostics for model outputs.
Source code in pypath/core/sensitivity_analysis.py
14 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 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 | |
compute_global_sensitivity ¶
compute_global_sensitivity(samples: ndarray, outputs: ndarray) -> np.ndarray
Approximate global sensitivity via absolute Pearson correlation.
Source code in pypath/core/sensitivity_analysis.py
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | |
compute_local_sensitivity ¶
compute_local_sensitivity(model_func: ModelFunc, baseline_params: ArrayLike) -> np.ndarray
Finite-difference local sensitivity around baseline parameters.
Source code in pypath/core/sensitivity_analysis.py
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | |
morris_screening ¶
morris_screening(model_func: ModelFunc, bounds: ndarray, n_trajectories: int = 20, delta: float = 0.1, random_seed: int | None = None) -> Dict[str, np.ndarray]
Compute Morris elementary effects summary statistics.
Source code in pypath/core/sensitivity_analysis.py
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 | |
UncertaintyPropagation
dataclass
¶
Monte Carlo and sampling helpers for output uncertainty.
Source code in pypath/core/sensitivity_analysis.py
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 | |
latin_hypercube_sampling ¶
latin_hypercube_sampling(bounds: ndarray, n_samples: int, random_seed: int | None = None) -> np.ndarray
Generate Latin Hypercube samples for bounded parameters.
Source code in pypath/core/sensitivity_analysis.py
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 | |
monte_carlo_ensemble ¶
monte_carlo_ensemble(model_func: ModelFunc, samples: ndarray) -> np.ndarray
Evaluate model outputs for sample matrix.
Source code in pypath/core/sensitivity_analysis.py
142 143 144 145 146 147 148 149 150 151 | |
quantile_analysis ¶
quantile_analysis(outputs: ArrayLike, quantiles: Iterable[float] = (0.05, 0.5, 0.95)) -> Dict[float, float]
Compute quantiles for an output distribution.
Source code in pypath/core/sensitivity_analysis.py
153 154 155 156 157 158 159 160 161 162 163 164 165 166 | |
Optimization¶
Parameter-fitting and search utilities for core Ecosim calibration.
Scenario-level management optimization is documented in Analysis API: Scenario Optimization.
pypath.core.optimization ¶
Bayesian optimization for Ecosim parameter calibration.
This module provides tools to optimize Ecosim parameters to match observed time series data using Bayesian optimization with Gaussian Processes.
EcosimOptimizer ¶
Bayesian optimizer for Ecosim parameters.
Calibrates Ecosim parameters to match observed biomass time series using Bayesian optimization with Gaussian Processes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Rpath
|
Balanced Ecopath model |
required |
params
|
RpathParams
|
Model parameters |
required |
observed_data
|
dict
|
Dictionary mapping group indices to observed biomass time series Example: {1: np.array([1.0, 1.2, 1.1, ...]), 2: np.array([0.5, 0.6, ...])} |
required |
years
|
range
|
Years to simulate |
required |
objective
|
str or callable
|
Objective function to minimize. Options: - 'mse': Mean squared error - 'mape': Mean absolute percentage error - 'nrmse': Normalized root mean squared error - 'loglik': Negative log-likelihood - callable: Custom function(y_true, y_pred) -> float |
'mse'
|
verbose
|
bool
|
Print optimization progress |
True
|
Attributes:
| Name | Type | Description |
|---|---|---|
model |
Rpath
|
Ecopath model |
params |
RpathParams
|
Model parameters |
observed_data |
dict
|
Observed time series |
years |
range
|
Simulation years |
objective_func |
callable
|
Objective function |
verbose |
bool
|
Verbosity flag |
n_calls |
int
|
Number of function evaluations performed |
Source code in pypath/core/optimization.py
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 | |
optimize ¶
optimize(param_bounds: Dict[str, Tuple[float, float]], n_calls: int = 50, n_initial_points: int = 10, random_state: int = 42) -> OptimizationResult
Run Bayesian optimization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
param_bounds
|
dict
|
Dictionary mapping parameter names to (min, max) bounds Example: {'vulnerability': (1.0, 5.0), 'VV_3': (1.0, 10.0)} |
required |
n_calls
|
int
|
Number of function evaluations |
50
|
n_initial_points
|
int
|
Number of random initial points before Bayesian optimization |
10
|
random_state
|
int
|
Random seed for reproducibility |
42
|
Returns:
| Type | Description |
|---|---|
OptimizationResult
|
Optimization results including best parameters and convergence |
Source code in pypath/core/optimization.py
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 | |
validate ¶
validate(params: Dict[str, float], test_data: Optional[Dict[int, ndarray]] = None) -> Dict[str, Any]
Validate optimized parameters on test data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
params
|
dict
|
Parameter values to validate |
required |
test_data
|
dict
|
Test data. If None, uses training data (self.observed_data) |
None
|
Returns:
| Type | Description |
|---|---|
dict
|
Validation metrics for each group and overall |
Source code in pypath/core/optimization.py
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 | |
OptimizationResult
dataclass
¶
Results from Bayesian optimization.
Attributes:
| Name | Type | Description |
|---|---|---|
best_params |
dict
|
Best parameter values found |
best_score |
float
|
Best objective function value (lower is better) |
n_iterations |
int
|
Number of optimization iterations |
convergence |
list
|
Objective function values over iterations |
all_params |
list
|
All parameter combinations tried |
all_scores |
list
|
All objective function values |
optimization_time |
float
|
Total optimization time in seconds |
Source code in pypath/core/optimization.py
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 | |
log_likelihood ¶
log_likelihood(y_true: ndarray, y_pred: ndarray, sigma: float = 0.1) -> float
Calculate negative log-likelihood (Gaussian).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y_true
|
ndarray
|
Observed values |
required |
y_pred
|
ndarray
|
Predicted values |
required |
sigma
|
float
|
Standard deviation of measurement error |
0.1
|
Returns:
| Type | Description |
|---|---|
float
|
Negative log-likelihood |
Source code in pypath/core/optimization.py
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 | |
mean_absolute_percentage_error ¶
mean_absolute_percentage_error(y_true: ndarray, y_pred: ndarray) -> float
Calculate mean absolute percentage error.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y_true
|
ndarray
|
Observed values |
required |
y_pred
|
ndarray
|
Predicted values |
required |
Returns:
| Type | Description |
|---|---|
float
|
Mean absolute percentage error |
Source code in pypath/core/optimization.py
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 | |
mean_squared_error ¶
mean_squared_error(y_true: ndarray, y_pred: ndarray) -> float
Calculate mean squared error between observed and predicted values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y_true
|
ndarray
|
Observed values |
required |
y_pred
|
ndarray
|
Predicted values |
required |
Returns:
| Type | Description |
|---|---|
float
|
Mean squared error |
Source code in pypath/core/optimization.py
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 | |
normalized_root_mean_squared_error ¶
normalized_root_mean_squared_error(y_true: ndarray, y_pred: ndarray) -> float
Calculate normalized root mean squared error.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y_true
|
ndarray
|
Observed values |
required |
y_pred
|
ndarray
|
Predicted values |
required |
Returns:
| Type | Description |
|---|---|
float
|
Normalized RMSE |
Source code in pypath/core/optimization.py
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 | |
plot_fit ¶
plot_fit(optimizer: EcosimOptimizer, params: Dict[str, float], save_path: Optional[str] = None)
Plot observed vs simulated biomass time series.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
optimizer
|
EcosimOptimizer
|
Optimizer instance with observed data |
required |
params
|
dict
|
Parameter values to simulate |
required |
save_path
|
str
|
Path to save figure |
None
|
Source code in pypath/core/optimization.py
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 | |
plot_optimization_results ¶
plot_optimization_results(result: OptimizationResult, save_path: Optional[str] = None)
Plot optimization convergence and parameter distributions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
result
|
OptimizationResult
|
Optimization results |
required |
save_path
|
str
|
Path to save figure |
None
|
Source code in pypath/core/optimization.py
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 | |
Plotting¶
pypath.core.plotting ¶
Plotting module for PyPath.
This module provides visualization functions for Ecopath models and Ecosim simulation results using matplotlib and optionally plotly.
Functions include: - Food web network diagrams - Biomass time series - Catch time series - Trophic level distributions - Mixed Trophic Impacts heatmaps
Based on Rpath's plotting functions.
plot_biomass ¶
plot_biomass(output: RsimOutput, groups: Optional[List[int]] = None, relative: bool = False, title: str = 'Biomass Time Series', figsize: Tuple[int, int] = (12, 6), legend_loc: str = 'best', ax: Optional[Axes] = None) -> plt.Figure
Plot biomass time series from Ecosim simulation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output
|
RsimOutput
|
Simulation results |
required |
groups
|
list of int
|
Group indices to plot (default: all living) |
None
|
relative
|
bool
|
If True, plot relative to initial biomass |
False
|
title
|
str
|
Plot title |
'Biomass Time Series'
|
figsize
|
tuple
|
Figure size |
(12, 6)
|
legend_loc
|
str
|
Legend location |
'best'
|
ax
|
Axes
|
Matplotlib axes |
None
|
Returns:
| Type | Description |
|---|---|
Figure
|
|
Source code in pypath/core/plotting.py
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 | |
plot_biomass_grid ¶
plot_biomass_grid(output: RsimOutput, groups: Optional[List[int]] = None, n_cols: int = 4, relative: bool = True, figsize: Optional[Tuple[int, int]] = None) -> plt.Figure
Plot biomass as a grid of subplots.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output
|
RsimOutput
|
Simulation results |
required |
groups
|
list of int
|
Group indices to plot |
None
|
n_cols
|
int
|
Number of columns in grid |
4
|
relative
|
bool
|
Plot relative to initial biomass |
True
|
figsize
|
tuple
|
Figure size |
None
|
Returns:
| Type | Description |
|---|---|
Figure
|
|
Source code in pypath/core/plotting.py
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 | |
plot_biomass_interactive ¶
plot_biomass_interactive(output: RsimOutput, groups: Optional[List[int]] = None, relative: bool = False, title: str = 'Biomass Time Series') -> Any
Create interactive biomass plot with Plotly.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output
|
RsimOutput
|
Simulation results |
required |
groups
|
list of int
|
Groups to plot |
None
|
relative
|
bool
|
Plot relative to initial |
False
|
title
|
str
|
Plot title |
'Biomass Time Series'
|
Returns:
| Type | Description |
|---|---|
Figure
|
|
Source code in pypath/core/plotting.py
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 | |
plot_catch ¶
plot_catch(output: RsimOutput, groups: Optional[List[int]] = None, title: str = 'Catch Time Series', figsize: Tuple[int, int] = (12, 6), stacked: bool = False, ax: Optional[Axes] = None) -> plt.Figure
Plot catch time series from Ecosim simulation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output
|
RsimOutput
|
Simulation results |
required |
groups
|
list of int
|
Group indices to plot |
None
|
title
|
str
|
Plot title |
'Catch Time Series'
|
figsize
|
tuple
|
Figure size |
(12, 6)
|
stacked
|
bool
|
If True, create stacked area plot |
False
|
ax
|
Axes
|
Matplotlib axes |
None
|
Returns:
| Type | Description |
|---|---|
Figure
|
|
Source code in pypath/core/plotting.py
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 | |
plot_ecosim_summary ¶
plot_ecosim_summary(output: RsimOutput, groups: Optional[List[int]] = None, figsize: Tuple[int, int] = (14, 10)) -> plt.Figure
Create summary plot with biomass, relative biomass, and catch.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output
|
RsimOutput
|
Simulation results |
required |
groups
|
list of int
|
Groups to plot |
None
|
figsize
|
tuple
|
Figure size |
(14, 10)
|
Returns:
| Type | Description |
|---|---|
Figure
|
|
Source code in pypath/core/plotting.py
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 | |
plot_foodweb ¶
plot_foodweb(rpath: Rpath, title: str = 'Food Web', layout: str = 'trophic', node_size_by: str = 'biomass', edge_width_by: str = 'flow', show_labels: bool = True, min_flow: float = 0.01, figsize: Tuple[int, int] = (12, 10), cmap: str = 'viridis', ax: Optional[Axes] = None) -> plt.Figure
Plot food web network diagram.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rpath
|
Rpath
|
Balanced Ecopath model |
required |
title
|
str
|
Plot title |
'Food Web'
|
layout
|
str
|
Node layout: 'trophic' (y=TL), 'spring', 'circular' |
'trophic'
|
node_size_by
|
str
|
What to scale node size by: 'biomass', 'production', 'equal' |
'biomass'
|
edge_width_by
|
str
|
What to scale edge width by: 'flow', 'diet', 'equal' |
'flow'
|
show_labels
|
bool
|
Show group labels |
True
|
min_flow
|
float
|
Minimum flow to show (relative to max) |
0.01
|
figsize
|
tuple
|
Figure size |
(12, 10)
|
cmap
|
str
|
Colormap for trophic levels |
'viridis'
|
ax
|
Axes
|
Matplotlib axes to plot on |
None
|
Returns:
| Type | Description |
|---|---|
Figure
|
The figure object |
Source code in pypath/core/plotting.py
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 | |
plot_foodweb_interactive ¶
plot_foodweb_interactive(rpath: Rpath, title: str = 'Food Web', min_flow: float = 0.01) -> Any
Create interactive food web plot with Plotly.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rpath
|
Rpath
|
Balanced model |
required |
title
|
str
|
Plot title |
'Food Web'
|
min_flow
|
float
|
Minimum flow to show |
0.01
|
Returns:
| Type | Description |
|---|---|
Figure
|
|
Source code in pypath/core/plotting.py
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 | |
plot_mti_heatmap ¶
plot_mti_heatmap(mti: ndarray, group_names: Optional[List[str]] = None, title: str = 'Mixed Trophic Impacts', figsize: Tuple[int, int] = (10, 8), cmap: str = 'RdBu_r', ax: Optional[Axes] = None) -> plt.Figure
Plot Mixed Trophic Impacts as a heatmap.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mti
|
ndarray
|
MTI matrix from mixed_trophic_impacts() |
required |
group_names
|
list of str
|
Names for groups |
None
|
title
|
str
|
Plot title |
'Mixed Trophic Impacts'
|
figsize
|
tuple
|
Figure size |
(10, 8)
|
cmap
|
str
|
Colormap |
'RdBu_r'
|
ax
|
Axes
|
Matplotlib axes |
None
|
Returns:
| Type | Description |
|---|---|
Figure
|
|
Source code in pypath/core/plotting.py
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 | |
plot_trophic_spectrum ¶
plot_trophic_spectrum(rpath: Rpath, by: str = 'biomass', n_bins: int = 10, title: str = 'Trophic Spectrum', figsize: Tuple[int, int] = (10, 6), ax: Optional[Axes] = None) -> plt.Figure
Plot trophic spectrum (biomass or production by trophic level).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rpath
|
Rpath
|
Balanced model |
required |
by
|
str
|
What to aggregate: 'biomass', 'production', 'consumption' |
'biomass'
|
n_bins
|
int
|
Number of trophic level bins |
10
|
title
|
str
|
Plot title |
'Trophic Spectrum'
|
figsize
|
tuple
|
Figure size |
(10, 6)
|
ax
|
Axes
|
Matplotlib axes |
None
|
Returns:
| Type | Description |
|---|---|
Figure
|
|
Source code in pypath/core/plotting.py
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 | |
save_plots ¶
save_plots(figures: Union[Figure, List[Figure]], filename: str, dpi: int = 150, format: str = 'png') -> None
Save matplotlib figure(s) to file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
figures
|
Figure or list of Figure
|
Figure(s) to save |
required |
filename
|
str
|
Output filename (without extension for multiple figures) |
required |
dpi
|
int
|
Resolution |
150
|
format
|
str
|
Output format ('png', 'pdf', 'svg') |
'png'
|
Source code in pypath/core/plotting.py
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 | |
Analysis & Network Indices¶
Mixed Trophic Impacts, network indices (connectance, omnivory), and Ecosim output summary statistics.
pypath.core.analysis ¶
Analysis and diagnostics module for PyPath.
This module provides functions for analyzing Ecopath models and Ecosim simulation results, including: - Mixed Trophic Impacts (MTI) - Network indices (connectance, omnivory index, etc.) - Ecosim output summary statistics - Model diagnostics and validation
Based on Rpath's analysis functions.
NetworkIndices
dataclass
¶
Container for food web network indices.
Attributes:
| Name | Type | Description |
|---|---|---|
n_groups |
int
|
Number of groups |
n_living |
int
|
Number of living groups |
n_links |
int
|
Number of trophic links (non-zero diet entries) |
connectance |
float
|
Links / (living groups)^2 |
linkage_density |
float
|
Links / living groups |
omnivory_index |
float
|
Mean variance of prey trophic levels |
system_omnivory |
float
|
Total system omnivory |
mean_trophic_level |
float
|
Biomass-weighted mean trophic level |
max_trophic_level |
float
|
Maximum trophic level |
total_biomass |
float
|
Sum of all biomass |
total_throughput |
float
|
Sum of all flows |
transfer_efficiency |
float
|
Mean trophic transfer efficiency |
finn_cycling_index |
float
|
Fraction of throughput recycled |
Source code in pypath/core/analysis.py
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 | |
EcosimSummary
dataclass
¶
Summary statistics for Ecosim simulation results.
Attributes:
| Name | Type | Description |
|---|---|---|
group_names |
list
|
Names of groups |
years |
int
|
Number of years simulated |
Biomass statistics
biomass_start : np.ndarray Initial biomass biomass_end : np.ndarray Final biomass biomass_min : np.ndarray Minimum biomass over simulation biomass_max : np.ndarray Maximum biomass over simulation biomass_mean : np.ndarray Mean biomass over simulation biomass_cv : np.ndarray Coefficient of variation of biomass biomass_change : np.ndarray Relative change (end/start - 1)
Catch statistics
total_catch : np.ndarray Total catch over simulation mean_annual_catch : np.ndarray Mean annual catch catch_cv : np.ndarray Coefficient of variation of catch
Source code in pypath/core/analysis.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 | |
mixed_trophic_impacts ¶
mixed_trophic_impacts(rpath: Rpath) -> np.ndarray
Mixed trophic impacts, as EwE and Rpath 1.2.0 compute them.
The direct impact of group i on group j is DC[i, j] - FC[j, i]:
the share of j's diet that is i (a fleet's "diet" is its landings)
less the share of j's outflow that i takes (consumption, and landings
plus discards for a fleet). Detritus is not a predator. The total
impact is pinv(I - direct) - I, with the detritus groups' own
impact set to 0 (Ulanowicz and Puccia 1990; Rpath's MTI()).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rpath
|
Rpath
|
Balanced Ecopath model |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
MTI matrix [impacting, impacted] over every group, fleets included, in model order. |
Example
mti = mixed_trophic_impacts(rpath) impact = mti[1, 2] # of the second group on the third
Source code in pypath/core/analysis.py
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 | |
keystoneness_index ¶
keystoneness_index(rpath: Rpath, mti: Optional[ndarray] = None) -> np.ndarray
Keystoneness of each living group (Libralato et al. 2006; EwE's KS1).
KS_i = log10(eps_i * (1 - p_i)), where eps_i is the overall
effect of group i, the square root of the sum of its squared mixed
trophic impacts on the other living groups (its impact on itself, on
detritus and on fleets left out), and p_i is its share of the total
biomass of the living groups. A high value marks a group whose effect
is large for its biomass. The paper's logarithm base was not checked;
the base changes the scale only, not the ranking or the sign.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rpath
|
Rpath
|
Balanced Ecopath model |
required |
mti
|
ndarray
|
Pre-computed MTI matrix (from :func: |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
One value per group, in model order (the order of the MTI matrix): NaN for detritus and fleets, and for a living group with no overall effect (its logarithm is undefined). |
References
Valls, A., Coll, M., & Christensen, V. (2015). Keystone species: toward an operational concept for marine biodiversity conservation. Ecological Monographs, 85(1), 29-47. https://doi.org/10.1890/14-0306.1
Libralato, S., Christensen, V., & Pauly, D. (2006). A method for identifying keystone species in food web models. Ecological Modelling, 195(3-4), 153-171. https://doi.org/10.1016/j.ecolmodel.2005.11.029
Source code in pypath/core/analysis.py
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 | |
calculate_network_indices ¶
calculate_network_indices(rpath: Rpath) -> NetworkIndices
Calculate food web network indices.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rpath
|
Rpath
|
Balanced Ecopath model |
required |
Returns:
| Type | Description |
|---|---|
NetworkIndices
|
Container with all calculated indices |
Source code in pypath/core/analysis.py
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 | |
summarize_ecosim_output ¶
summarize_ecosim_output(output: RsimOutput, scenario: Optional[RsimScenario] = None) -> EcosimSummary
Calculate summary statistics for Ecosim output.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output
|
RsimOutput
|
Simulation results |
required |
scenario
|
RsimScenario
|
Original scenario (for group names) |
None
|
Returns:
| Type | Description |
|---|---|
EcosimSummary
|
Summary statistics |
Source code in pypath/core/analysis.py
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 | |
compare_scenarios ¶
compare_scenarios(outputs: List[RsimOutput], names: List[str], groups: Optional[List[int]] = None) -> pd.DataFrame
Compare multiple Ecosim scenarios.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
outputs
|
list of RsimOutput
|
Simulation results to compare |
required |
names
|
list of str
|
Names for each scenario |
required |
groups
|
list of int
|
Group indices to compare (default: all living groups) |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Comparison table with biomass changes per scenario |
Source code in pypath/core/analysis.py
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 | |
check_ecopath_balance ¶
check_ecopath_balance(rpath: Rpath, tolerance: float = 0.01, allow_partial_diet: bool = False) -> Dict[str, Any]
Check Ecopath model balance.
Verifies that the model satisfies mass-balance constraints: - EE <= 1 for all groups - Consumption = Production + Respiration + Unassimilated for consumers, with a respiration of zero or more - Diet compositions sum to 1
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rpath
|
Rpath
|
Balanced model to check |
required |
tolerance
|
float
|
Acceptable deviation from balance |
0.01
|
allow_partial_diet
|
bool
|
If True, allow consumer diet columns to sum below 1.0 and treat the remainder as unresolved/other food instead of a hard issue. |
False
|
Returns:
| Type | Description |
|---|---|
dict
|
Diagnostics including: - is_balanced: bool - ee_issues: list of groups with EE > 1 - diet_issues: list of groups with diet sum != 1 - balance_issues: list of consumers with P/Q outside 0 to 1 - respiration_issues: list of consumers with a negative respiration, Q/B x (1 - Unassim) - (1 - producer share) x P/B per unit biomass. Like balance_issues, they do not change is_balanced. - messages: list of diagnostic messages |
Source code in pypath/core/analysis.py
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 | |
check_ecosim_stability ¶
check_ecosim_stability(scenario: RsimScenario, burn_years: int = 10) -> Dict[str, Any]
Check Ecosim scenario stability.
Runs a short burn-in simulation to verify the model reaches equilibrium.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scenario
|
RsimScenario
|
Scenario to check |
required |
burn_years
|
int
|
Years to run for stability check |
10
|
Returns:
| Type | Description |
|---|---|
dict
|
Stability diagnostics including: - is_stable: bool - crashed_groups: list of groups that crashed - unstable_groups: list of groups with > 50% change - messages: list of diagnostic messages |
Source code in pypath/core/analysis.py
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 | |
export_ecopath_to_dataframe ¶
export_ecopath_to_dataframe(rpath: Rpath) -> Dict[str, pd.DataFrame]
Export Ecopath model to DataFrames.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rpath
|
Rpath
|
Balanced model |
required |
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary of DataFrames: - 'groups': Group parameters - 'diet': Diet composition matrix - 'flows': Flow matrix |
Source code in pypath/core/analysis.py
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 | |
export_ecosim_to_dataframe ¶
export_ecosim_to_dataframe(output: RsimOutput, scenario: Optional[RsimScenario] = None) -> Dict[str, pd.DataFrame]
Export Ecosim results to DataFrames.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output
|
RsimOutput
|
Simulation results |
required |
scenario
|
RsimScenario
|
Original scenario for metadata |
None
|
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary of DataFrames: - 'biomass_annual': Annual biomass - 'catch_annual': Annual catch - 'biomass_monthly': Monthly biomass (if available) |
Source code in pypath/core/analysis.py
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 | |
Autofix (Stability Diagnostics)¶
Automatic parameter diagnostics and repair routines to prevent Ecosim simulation crashes and improve model stability.
Key functions:
diagnose_crash_causes()— identify critical issues (EE > 1, incomplete diets) and warnings (low biomass, high vulnerability, extreme QQ)autofix_parameters()— automatically cap vulnerabilities, enforce minimum biomass, reduce extreme density dependencevalidate_and_fix_scenario()— combined validation and repair in one stepAutofixResult— dataclass with applied fixes and diagnostic info
See the Autofix Guide for practical usage.
pypath.core.autofix ¶
Automatic parameter calibration and fixing for Ecosim stability.
This module provides diagnostic and automatic fixing routines to prevent simulation crashes and improve model stability.
AutofixResult
dataclass
¶
Results from automatic parameter fixing.
Attributes:
| Name | Type | Description |
|---|---|---|
success |
bool
|
Whether fixes were successful |
fixes_applied |
list
|
List of fixes that were applied |
warnings |
list
|
List of warnings about potential issues |
original_params |
dict
|
Original parameter values before fixing |
Source code in pypath/core/autofix.py
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | |
diagnose_crash_causes ¶
diagnose_crash_causes(rpath: Rpath, params: RsimParams) -> Dict[str, Any]
Diagnose potential causes of simulation crashes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rpath
|
Rpath
|
Balanced Ecopath model |
required |
params
|
RsimParams
|
Ecosim parameters |
required |
Returns:
| Type | Description |
|---|---|
dict
|
Diagnostic results with issues and recommendations |
Source code in pypath/core/autofix.py
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 | |
autofix_parameters ¶
autofix_parameters(rpath: Rpath, params: RsimParams, aggressive: bool = False) -> Tuple[RsimParams, AutofixResult]
Automatically fix parameters to improve stability.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rpath
|
Rpath
|
Balanced Ecopath model |
required |
params
|
RsimParams
|
Ecosim parameters to fix |
required |
aggressive
|
bool
|
If True, apply more aggressive fixes |
False
|
Returns:
| Type | Description |
|---|---|
RsimParams
|
Fixed parameters |
AutofixResult
|
Summary of fixes applied |
Source code in pypath/core/autofix.py
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 | |
validate_and_fix_scenario ¶
validate_and_fix_scenario(scenario: RsimScenario, rpath: Rpath, auto_fix: bool = True, verbose: bool = True) -> Tuple[RsimScenario, Dict[str, Any]]
Validate scenario and optionally apply automatic fixes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scenario
|
RsimScenario
|
Ecosim scenario to validate |
required |
rpath
|
Rpath
|
Original Ecopath model |
required |
auto_fix
|
bool
|
Whether to automatically fix parameters |
True
|
verbose
|
bool
|
Whether to print diagnostic messages |
True
|
Returns:
| Type | Description |
|---|---|
RsimScenario
|
Validated (and potentially fixed) scenario |
dict
|
Diagnostic report |
Source code in pypath/core/autofix.py
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 | |
Sparse Link Array¶
Compressed prey-predator link lists for efficient consumption kernel computation in sparse food webs.
pypath.core.link_array ¶
Compressed link-list for sparse food webs.
Pre-computes arrays of active prey-predator link indices so that the consumption kernel can iterate only over active links instead of the full (NUM_GROUPS+1) x (NUM_GROUPS+1) matrix. For a 50-group model with 70% sparsity this eliminates 70% of iterations.
ActiveLinkArray
dataclass
¶
Pre-computed arrays of active prey-predator link indices.
Attributes:
| Name | Type | Description |
|---|---|---|
prey |
ndarray
|
1-D int64 array of prey indices for each active link. |
pred |
ndarray
|
1-D int64 array of predator indices for each active link. |
n_links |
int
|
Number of active links. |
Source code in pypath/core/link_array.py
14 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 | |
from_bool_matrix
classmethod
¶
from_bool_matrix(active: ndarray) -> ActiveLinkArray
Build an ActiveLinkArray from a boolean (or int) ActiveLink matrix.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
active
|
ndarray
|
Boolean or integer matrix of shape (N, N) where |
required |
Returns:
| Type | Description |
|---|---|
ActiveLinkArray
|
Compressed representation containing only the active links. |
Source code in pypath/core/link_array.py
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | |
Constants¶
Physical and biological constants used throughout PyPath.
pypath.core.constants ¶
Physical and biological constants for ecosystem modeling.
This module centralizes magic numbers and constants used throughout PyPath, improving maintainability and reducing errors from scattered hard-coded values.
Time Series & Calibration¶
Time series data structures for observed data and calibration against EwE reference series.
pypath.core.timeseries ¶
EwE time series data structures and driver application.
Provides data classes for observed and forced time series used in Ecosim calibration and scenario forcing.
EweTimeSeries
dataclass
¶
A single EwE time series.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
series_id
|
int
|
Unique identifier for this series. |
required |
name
|
str
|
Human-readable name (e.g. "Cod biomass"). |
required |
dat_type
|
int
|
DatType constant indicating the series type. |
required |
group_idx
|
int or None
|
0-based group index, or None for fleet-level series. Note: this differs from EcosimOptimizer which uses 1-based indices. |
required |
fleet_idx
|
int or None
|
0-based fleet index, or None for group-level series. |
required |
values
|
ndarray
|
Time series values, shape (n_timesteps,). NaN for missing. |
required |
weight
|
float
|
Weighting factor for SS objective (default 1.0). |
1.0
|
dataset_id
|
int
|
Dataset grouping identifier (default 0). |
0
|
Source code in pypath/core/timeseries.py
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 | |
EweTimeSeriesCollection
dataclass
¶
Container for multiple EwE time series with filtered views.
On construction, all series are NaN-padded to the length of the longest
series, and n_timesteps is set to that uniform length.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
series
|
list[EweTimeSeries]
|
List of time series to include. |
list()
|
interval
|
str
|
The dataset's data interval ( |
'annual'
|
Source code in pypath/core/timeseries.py
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 | |
observed_biomass
property
¶
observed_biomass: list[EweTimeSeries]
Series with dat_type in {0 (relative), 1 (absolute)}.
forced_biomass
property
¶
forced_biomass: list[EweTimeSeries]
Series with dat_type == -1 (forced biomass).
to_observed_dict ¶
to_observed_dict(n_timesteps: int) -> dict[int, np.ndarray]
Convert observed biomass series to {group_idx: array} dict.
Arrays are padded with NaN or truncated to n_timesteps.
Compatible with EcosimOptimizer's observed_data format (note:
EcosimOptimizer uses 1-based group indices; this returns 0-based).
Source code in pypath/core/timeseries.py
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 | |
to_dataframe ¶
to_dataframe() -> 'pd.DataFrame'
Convert to a DataFrame in simple format (time, group, value, dat_type).
Suitable for CSV export and round-tripping.
Source code in pypath/core/timeseries.py
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 | |
apply_timeseries_drivers ¶
apply_timeseries_drivers(scenario: 'RsimScenario', collection: EweTimeSeriesCollection) -> None
Apply driver time series to an Ecosim scenario's forcing arrays.
Modifies scenario in place, the way EwE6 applies the dataset loaded
in Ecosim: forced biomass (type -1, absolute biomass that replaces the
group's state in every month of the data year), fishing effort (3, the
fleet's effort multiplier by year) and fishing mortality (4, by year).
Observed series are ignored. Yearly values hold for their twelve months;
a missing year, or a year beyond the data, leaves the driver untouched.
Raises:
| Type | Description |
|---|---|
ValueError
|
If any forced biomass values are negative (excluding NaN). |
Source code in pypath/core/timeseries.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 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 | |
load_timeseries ¶
load_timeseries(path: str | Path) -> EweTimeSeriesCollection
Load time series from a file, dispatching by extension.
Supported extensions:
- .csv -> CSV loader (simple format)
- .eweaccdb, .ewemdb, .accdb -> EwE database reader
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str or Path
|
Path to the time series file. |
required |
Returns:
| Type | Description |
|---|---|
EweTimeSeriesCollection
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the file extension is not recognized. |
Source code in pypath/core/timeseries.py
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 | |
Calibration¶
Sum-of-squares fitting against reference time series.
pypath.core.calibration ¶
Ecosim calibration via sum-of-squares fitting to time series data.
Provides fit_to_timeseries() for optimizing Ecosim vulnerability (VV) and primary production (PP) parameters against observed time series.
CalibrationResult
dataclass
¶
Result of time series calibration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
best_vv
|
ndarray
|
Fitted vulnerability values, one per pred-prey link. |
required |
best_pp
|
ndarray or None
|
Fitted primary production anomaly (if fit_pp was True). |
required |
ss
|
float
|
Final sum-of-squares value. |
required |
ss_by_group
|
dict[int, float]
|
SS contribution per group index (0-based). |
required |
n_iterations
|
int
|
Number of optimizer iterations performed. |
required |
converged
|
bool
|
Whether the optimizer converged. |
required |
fitted_scenario
|
RsimScenario or None
|
Scenario with best-fit parameters applied. |
required |
link_map
|
list[tuple[int, int]]
|
(prey_idx, pred_idx) 0-based for each entry in best_vv. |
required |
Source code in pypath/core/calibration.py
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 | |
EweSSResult
dataclass
¶
EwE6's sum of squares of a run against reference time series.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
total
|
float
|
Sum over series of WtType x sum (Z - q)^2. |
required |
by_series
|
dict[int, float]
|
Each series' weighted contribution, by |
required |
by_group
|
dict[int, float]
|
Summed by the series' 0-based group (EwE's SS by group). |
required |
log_q
|
dict[int, float]
|
ln q of each series: mean(Z) for relative series, 0 otherwise. |
required |
n_obs
|
dict[int, int]
|
Observations compared, by |
required |
Source code in pypath/core/calibration.py
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 | |
ewe_sum_of_squares ¶
ewe_sum_of_squares(output, timeseries, *, warn: bool = True) -> EweSSResult
EwE6's sum of squares of an Ecosim run against reference time series.
Follows cEcoSimModel.AccumulateDataInfo and PlotDataInfo (vb
2575-2735, 3849-3966):
- Annual data (
timeseries.interval == "annual") are compared once a year, at the start of month 6 before its integration: the biomass at the end of month (year - 1) x 12 + 5, i.e.out_Biomassrow (year - 1) x 12 + 5. Time-step data compare value k with row k - 1 (the start of month k). Data years past the run are ignored. - Each observation gives Z = ln(obs / pred). Biomass series predict B;
catch series predict B x F, F being the fishing mortality of the month
before the sample (EwE sets FishTime after the comparison), from
out_FishMort. An observation of an unfished group (F = 0) counts with Z = 0, as in EwE. Observations <= 0 or missing are skipped. - Relative series (types 0, 61) subtract q = mean(Z); absolute ones do not. Each series adds WtType x sum (Z - q)^2, and every series counts, several per group included.
Other reference types (total mortality, average weight, landings, discards, fishing mortality) are reported and left out; drivers (forced biomass, effort, ...) are not compared, as in EwE.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output
|
RsimOutput
|
The run; needs |
required |
timeseries
|
EweTimeSeriesCollection
|
The dataset, with each series' |
required |
warn
|
bool
|
Report the weighted series left out (unsupported types, no group).
|
True
|
Returns:
| Type | Description |
|---|---|
EweSSResult
|
|
Source code in pypath/core/calibration.py
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 | |
fit_to_timeseries ¶
fit_to_timeseries(rpath_model, params, timeseries, *, fit_vv: bool = True, fit_pp: bool = False, fit_groups: list[int] | None = None, vv_bounds: tuple = (1.0, 100.0), pp_bounds: tuple = (0.0, 2.0), method: str = 'differential_evolution', max_iterations: int = 1000, verbose: bool = False, workers: int = 1) -> CalibrationResult
Fit Ecosim parameters to observed time series data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rpath_model
|
Rpath
|
Balanced Ecopath model. |
required |
params
|
RpathParams
|
Model parameters. |
required |
timeseries
|
EweTimeSeriesCollection or dict
|
Observed time series. If dict, treated as {group_idx: np.array} of relative biomass (0-based group indices). |
required |
fit_vv
|
bool
|
Fit vulnerability (VV) parameters (default True). |
True
|
fit_pp
|
bool
|
Fit primary production anomaly. Not yet implemented. |
False
|
fit_groups
|
list[int] or None
|
0-based group indices to fit. None = all groups with observed data. |
None
|
vv_bounds
|
tuple
|
(min, max) bounds for VV parameters. |
(1.0, 100.0)
|
pp_bounds
|
tuple
|
(min, max) bounds for PP parameters (reserved). |
(0.0, 2.0)
|
method
|
str
|
"differential_evolution" or "minimize" (L-BFGS-B). |
'differential_evolution'
|
max_iterations
|
int
|
Maximum optimizer iterations. |
1000
|
verbose
|
bool
|
Print progress. |
False
|
workers
|
int
|
Processes used to evaluate differential evolution candidates in
parallel (default 1: serial, exactly as before). |
1
|
Returns:
| Type | Description |
|---|---|
CalibrationResult
|
|
Source code in pypath/core/calibration.py
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 | |
Mediation Functions¶
Trophic mediation functions that modify predator-prey vulnerability based on the biomass of a mediating group.
pypath.core.mediation ¶
Mediation functions for Ecosim predation modification.
Mediation allows a third species (mediator) to modify predator-prey interactions, fleet catchability, or landing proportions based on the mediator's relative biomass and a user-defined response shape.
MediationShape
dataclass
¶
A mediation response shape defined by X-Y point pairs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
shape_id
|
int
|
Unique identifier for this shape. |
required |
name
|
str
|
Human-readable name. |
required |
x_points
|
ndarray
|
Relative biomass values (mediator B / B_base). |
required |
y_points
|
ndarray
|
Corresponding multiplier values. |
required |
Source code in pypath/core/mediation.py
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 | |
evaluate ¶
evaluate(relative_biomass: float) -> float
Evaluate the shape at a given relative biomass via linear interpolation.
Values outside the x_points range are clamped to the nearest endpoint.
Source code in pypath/core/mediation.py
37 38 39 40 41 42 43 44 | |
MediationLink
dataclass
¶
Maps a mediation shape to a specific interaction.
Exactly one target type should be specified: - Group: prey_idx and pred_idx both set - Fleet: fleet_idx set - Landings: landing_group_idx and landing_fleet_idx both set
All indices are 0-based.
Source code in pypath/core/mediation.py
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | |
MediationCollection
dataclass
¶
Container for mediation shapes and their link assignments.
Source code in pypath/core/mediation.py
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 | |
compute_group_multipliers ¶
compute_group_multipliers(BB: ndarray, Bbase: ndarray, ActiveLink: ndarray) -> np.ndarray
Compute 2D (n+1, n+1) multiplier matrix for group mediation.
For each group link, evaluate the shape at BB[mediator+1]/Bbase[mediator+1] and set mult[prey+1, pred+1]. Multiple links on the same pair multiply together.
Source code in pypath/core/mediation.py
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 | |
compute_fleet_multipliers ¶
compute_fleet_multipliers(BB: ndarray, Bbase: ndarray, n_fleets: int) -> np.ndarray
Compute per-fleet multiplier array.
Each fleet link evaluates the shape at mediator relative biomass. Default 1.0 for unaffected fleets.
Source code in pypath/core/mediation.py
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 | |
compute_landing_multipliers ¶
compute_landing_multipliers(BB: ndarray, Bbase: ndarray, n_fleets: int, n_groups: int) -> np.ndarray
Compute (n_fleets, n_groups) multiplier matrix for landings.
Default 1.0 for unaffected fleet-group combinations.
Source code in pypath/core/mediation.py
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 | |
EweMediation
dataclass
¶
EwE6's pred/prey mediation functions, as Ecosim applies them.
Each shape has 1200 points (points[s, ip - 1] is Medpoints(ip)) and
a base point imedbase[s]. Its mediators are the groups with a weight
0 in
weights[s](rsim index) and the fleets with a weight > 0 infleet_weights[s](gear index, the column of ForcedEffort). Every derivative sets the shape's value from the current biomass and effort (SetMedFunctions, cEcoSimModel.vb:2851, cMediationDataStructures.vb:129): X = 1e-10 + sum(weight x B) + sum(fleet weight x effort), ip = Trunc(IMedBase x X / MedXbase + 0.01) clamped to 1..1200, value = Medpoints(ip) / MedYbase, with MedXbase = sum(weight x start biomass) + sum(fleet weight), as "Ecosim effort at Ecopath base effort is always one", and MedYbase = Medpoints(IMedBase) (InitializeMedFunctions, vb 3568-3650). Groups come first in both sums, then fleets, as in EwE. A shape without mediators, base X or base point value is unused and its value stays 1. EwE computes in single precision; so does this, so the point index truncates alike.
links are (prey, pred, shape, application) (rsim indices): a
search-rate function multiplies the link's search rate, a vulnerability
function its vulnerability (ApplyAVmodifiers, vb 4928-4970). Several
functions on one link multiply.
Source code in pypath/core/mediation.py
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 | |
setup ¶
setup(start_biomass: ndarray) -> None
MedXbase, MedYbase and MedIsUsed from the start biomass.
Source code in pypath/core/mediation.py
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 | |
lookup ¶
lookup(shape: int, x: float, *, interpolate: bool = False) -> float
getMedValue: the shape's value at mediator sum x.
With interpolate (the continuous path) the value is linear in
ratio = IMedBase x x / xbase64 between the points, in float64 and
clamped at the end points, so the base gives exactly 1 and the value
is continuous in x. EwE's truncating single-precision lookup is
the default.
Source code in pypath/core/mediation.py
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 | |
values ¶
values(biomass: ndarray, effort: ndarray | None = None, *, interpolate: bool = False) -> np.ndarray
MedVal of every shape at biomass and effort (by gear, as a
row of ForcedEffort; None or a missing gear counts as the base effort,
1). Unused shapes are 1. With interpolate the sum is in float64
without EwE's 1e-10 (see :meth:lookup).
Source code in pypath/core/mediation.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 | |
link_factors ¶
link_factors(biomass: ndarray, n: int, effort: ndarray | None = None, *, interpolate: bool = False)
Search-rate and vulnerability multipliers by link, (n, n) arrays
indexed [prey, pred], or None where no link has that application.
effort is the fleets' effort by gear (see :meth:values).
Source code in pypath/core/mediation.py
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 | |
make_positive_shape ¶
make_positive_shape(shape_id: int = 0, name: str = 'positive', low: float = 0.5, high: float = 2.0, shape: float = 1.0, n_points: int = 9) -> MediationShape
Create a positive (increasing) mediation shape.
y = low + (high - low) * x^shape / (1 + x^shape)
Source code in pypath/core/mediation.py
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 | |
make_negative_shape ¶
make_negative_shape(shape_id: int = 0, name: str = 'negative', low: float = 0.5, high: float = 2.0, shape: float = 1.0, n_points: int = 9) -> MediationShape
Create a negative (decreasing) mediation shape.
y = high - (high - low) * x^shape / (1 + x^shape)
Source code in pypath/core/mediation.py
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 | |
make_ushape ¶
make_ushape(shape_id: int = 0, name: str = 'u-shaped', low: float = 0.5, high: float = 2.0, shape: float = 1.0, n_points: int = 9) -> MediationShape
Create a U-shaped mediation shape (peaks at x=1.0).
y = high - (high - low) * |x-1|^shape / (1 + |x-1|^shape)
Source code in pypath/core/mediation.py
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 | |
Pedigree System (Phase 1B.1)¶
Data quality tracking using EwE pedigree indices (0-4 scale mapping to HIGH/MEDIUM/LOW confidence). Integrates with Monte Carlo sampling for uncertainty quantification.
pypath.core.pedigree ¶
Pedigree-based parameter distributions and sampling.
Pedigree values (coefficients of variation) define parameter uncertainty. This module converts pedigree CVs to statistical distributions and generates parameter samples for Monte Carlo analysis.
ScalarDistribution
dataclass
¶
A single scalar parameter's sampling distribution (log-normal).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
param_name
|
str
|
Parameter name (e.g. "Biomass", "PB", "QB"). |
required |
group_idx
|
int
|
0-based group index. |
required |
base_value
|
float
|
Current Ecopath value. |
required |
cv
|
float
|
Coefficient of variation from pedigree. |
required |
bounds
|
tuple[float, float] | None
|
Optional hard bounds for rejection sampling. |
None
|
Source code in pypath/core/pedigree.py
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | |
DietDistribution
dataclass
¶
A predator's diet composition distribution (Dirichlet).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pred_idx
|
int
|
0-based predator group index. |
required |
base_proportions
|
ndarray
|
Current diet column (prey proportions, sum=1). |
required |
cv
|
float
|
Controls Dirichlet concentration (higher CV = more spread). |
required |
Source code in pypath/core/pedigree.py
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | |
PedigreeConfig
dataclass
¶
Configuration for pedigree-to-CV mapping.
EwE 6 stores pedigree as (VarName, LevelID) pairs in the Pedigree table, where each VarName has its own set of levels with IndexValue (the CV).
In the Python API, params.pedigree values are treated as CVs directly. PedigreeConfig is only needed when importing from EwE databases.
Source code in pypath/core/pedigree.py
74 75 76 77 78 79 80 81 82 83 84 85 | |
PedigreeQuality ¶
Bases: Enum
Pedigree quality classification (EwE standard).
Maps pedigree_index values (0-4) to quality levels.
Source code in pypath/core/pedigree.py
323 324 325 326 327 328 329 330 331 | |
EwePedigreeConfig
dataclass
¶
Pedigree configuration for EwE quality tracking (Phase 1B.1).
Represents the quality and reliability of input data or derived values following the EwE pedigree index standard (0-4).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pedigree_index
|
int
|
Pedigree index in range [0, 4]. - 0-1: HIGH quality (well-documented, peer-reviewed) - 2: MEDIUM quality (literature values) - 3-4: LOW quality (expert guess, uncertain) |
required |
comment
|
str
|
Human-readable description of data source or uncertainty. |
''
|
Attributes:
| Name | Type | Description |
|---|---|---|
quality_flag |
PedigreeQuality
|
Auto-set from pedigree_index; not a constructor argument. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If pedigree_index is not in [0, 4]. |
Examples:
>>> cfg = EwePedigreeConfig(pedigree_index=0, comment="Published literature")
>>> cfg.quality_flag
<PedigreeQuality.HIGH: 'high'>
>>> cfg.to_ewe_format()
0
Source code in pypath/core/pedigree.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 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 | |
__post_init__ ¶
__post_init__() -> None
Validate pedigree_index and auto-set quality_flag.
Raises:
| Type | Description |
|---|---|
ValueError
|
If pedigree_index not in [0, 4]. |
Source code in pypath/core/pedigree.py
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 | |
from_ewe_format
classmethod
¶
from_ewe_format(index: int, comment: str = '') -> 'EwePedigreeConfig'
Parse EwE pedigree index format.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index
|
int
|
Pedigree index in range [0, 4]. |
required |
comment
|
str
|
Optional comment text. |
''
|
Returns:
| Type | Description |
|---|---|
EwePedigreeConfig
|
Initialized config object. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If index not in [0, 4]. |
Source code in pypath/core/pedigree.py
394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 | |
to_ewe_format ¶
to_ewe_format() -> int
Export to EwE format (pedigree index 0-4).
Returns:
| Type | Description |
|---|---|
int
|
Pedigree index value. |
Source code in pypath/core/pedigree.py
417 418 419 420 421 422 423 424 425 | |
PedigreeContainer ¶
Container for managing EwE pedigree data across groups (Phase 1B.1).
Holds pedigree configurations for each group/parameter and provides serialization, validation, and query methods.
Attributes:
| Name | Type | Description |
|---|---|---|
group_pedigree |
dict[str, EwePedigreeConfig]
|
Mapping of group name to its pedigree configuration. |
metadata |
dict
|
Metadata (source, timestamp, notes, etc.). |
Source code in pypath/core/pedigree.py
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 | |
__init__ ¶
__init__() -> None
Initialize empty pedigree container.
Source code in pypath/core/pedigree.py
501 502 503 504 | |
get_pedigree ¶
get_pedigree(group_name: str) -> Optional[EwePedigreeConfig]
Get pedigree configuration for a group.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
group_name
|
str
|
Name of the group. |
required |
Returns:
| Type | Description |
|---|---|
EwePedigreeConfig or None
|
Pedigree config if found, None otherwise. |
Source code in pypath/core/pedigree.py
506 507 508 509 510 511 512 513 514 515 516 517 518 519 | |
add_pedigree ¶
add_pedigree(group_name: str, config: EwePedigreeConfig) -> None
Add or update pedigree configuration for a group.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
group_name
|
str
|
Name of the group. |
required |
config
|
EwePedigreeConfig
|
Pedigree configuration to add. |
required |
Source code in pypath/core/pedigree.py
521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 | |
validate ¶
validate() -> list[str]
Validate all pedigree entries.
Returns:
| Type | Description |
|---|---|
list[str]
|
List of validation issues (empty if valid). |
Source code in pypath/core/pedigree.py
537 538 539 540 541 542 543 544 545 | |
to_dataframe ¶
to_dataframe() -> pd.DataFrame
Export pedigree data as DataFrame.
Returns:
| Type | Description |
|---|---|
DataFrame
|
Table with columns: group, pedigree_index, quality_flag, comment. |
Source code in pypath/core/pedigree.py
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 | |
from_dataframe
classmethod
¶
from_dataframe(df: DataFrame) -> 'PedigreeContainer'
Create PedigreeContainer from DataFrame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
DataFrame with columns: group, pedigree_index, quality_flag (optional). |
required |
Returns:
| Type | Description |
|---|---|
PedigreeContainer
|
Initialized container. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If required columns are missing. |
Source code in pypath/core/pedigree.py
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 | |
build_distributions ¶
build_distributions(params: 'RpathParams', config: PedigreeConfig | None = None) -> list[ParameterDistribution]
Build parameter distributions from pedigree CVs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
params
|
RpathParams
|
Ecopath parameters with pedigree DataFrame. |
required |
config
|
PedigreeConfig
|
EwE database pedigree mapping (for converting LevelIDs to CVs). |
None
|
Returns:
| Type | Description |
|---|---|
list[ParameterDistribution]
|
Distributions for all parameters with CV > 0. |
Source code in pypath/core/pedigree.py
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 | |
sample_parameters ¶
sample_parameters(distributions: list[ParameterDistribution], n_samples: int, method: str = 'lhs', rng: Generator | None = None) -> list[dict]
Generate parameter samples from distributions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
distributions
|
list[ParameterDistribution]
|
Parameter distributions from build_distributions(). |
required |
n_samples
|
int
|
Number of samples to generate. |
required |
method
|
str
|
"lhs" for Latin Hypercube Sampling, "random" for direct sampling. |
'lhs'
|
rng
|
Generator
|
Random number generator for reproducibility. |
None
|
Returns:
| Type | Description |
|---|---|
list[dict]
|
N parameter sets. Keys are (param_name, group_idx) tuples. |
Source code in pypath/core/pedigree.py
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 | |
apply_sample ¶
apply_sample(params: 'RpathParams', sample: dict) -> 'RpathParams'
Apply a parameter sample to a copy of RpathParams.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
params
|
RpathParams
|
Original parameters (not modified). |
required |
sample
|
dict
|
Parameter sample from sample_parameters(). |
required |
Returns:
| Type | Description |
|---|---|
RpathParams
|
New params with sampled values applied. |
Source code in pypath/core/pedigree.py
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 | |
validate_ewe_pedigree ¶
validate_ewe_pedigree(pedigree_dict: dict[str, EwePedigreeConfig]) -> list[str]
Validate EwE pedigree configuration dictionary.
Checks that all pedigree entries conform to EwE standards and internal consistency. Returns a list of validation issues; empty list means valid.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pedigree_dict
|
dict[str, EwePedigreeConfig]
|
Mapping of group name to EwePedigreeConfig. |
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
List of validation warning/error messages. Empty if all valid. |
Examples:
>>> pedigree = {
... "Cod": EwePedigreeConfig(0, comment="Published"),
... "Herring": EwePedigreeConfig(2),
... }
>>> issues = validate_ewe_pedigree(pedigree)
>>> len(issues)
0
Source code in pypath/core/pedigree.py
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 | |
Key Classes:
- PedigreeQuality — Enum mapping EwE pedigree indices to quality levels
- EwePedigreeConfig — Configuration for pedigree parameters (index, min, max)
- PedigreeContainer — Multi-group pedigree management with validation
Monte Carlo Sampling¶
pypath.core.montecarlo ¶
Monte Carlo uncertainty analysis for Ecopath/Ecosim.
Runs ensemble simulations with parameter sampling from pedigree-defined
distributions. MCConfig.n_jobs runs the samples in worker processes; the
results are the serial run's, sample for sample.
MCConfig
dataclass
¶
Monte Carlo run configuration.
Attributes:
| Name | Type | Description |
|---|---|---|
n_samples |
int
|
Number of parameter samples. |
method |
str
|
Sampling method: "lhs" (Latin hypercube) or "random". |
seed |
(int, optional)
|
Seed for drawing the samples; None draws fresh ones. |
ecopath_only |
bool
|
Balance each sample with Ecopath only, without running Ecosim. |
ecosim_years |
(range, optional)
|
Years of each sample's Ecosim run (default |
store_runs |
bool
|
Keep every sample's Ecopath and Ecosim biomass in the result. |
n_jobs |
int
|
Worker processes for the samples. 1 (the default) runs them serially
in this process. A larger number runs that many processes, never more
than there are samples; -1 uses one per CPU this process may use. The
samples are drawn up front from |
mediation |
(object, optional)
|
Mediation passed to every sample's Ecosim run. |
ecosim_method |
str
|
Ecosim integration method (default "RK4"). |
eco_area |
float
|
Ecopath area passed to |
mp_context |
(str, optional)
|
The multiprocessing start method for the workers: "forkserver", "spawn" or "fork". None uses forkserver on Linux and spawn on macOS and Windows, as CPython's own defaults do from Python 3.14. forkserver and spawn start clean worker processes:
"fork" starts workers fastest but is unsafe in a multi-threaded process (Python warns, and numpy's BLAS threads count), so ask for it only from a single-threaded script. |
Source code in pypath/core/montecarlo.py
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 | |
MCResult
dataclass
¶
Monte Carlo ensemble results.
Source code in pypath/core/montecarlo.py
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 | |
to_dataframe ¶
to_dataframe() -> pd.DataFrame
Return ecopath_stats as a single flat DataFrame.
Source code in pypath/core/montecarlo.py
121 122 123 124 125 126 127 128 129 130 | |
to_dict ¶
to_dict() -> dict
Return JSON-serializable summary dict.
Source code in pypath/core/montecarlo.py
132 133 134 135 136 137 138 139 140 141 142 | |
run_montecarlo ¶
run_montecarlo(params: 'RpathParams', config: MCConfig | None = None, *, pedigree_config: 'PedigreeConfig | None' = None, progress_callback: Callable[[int, int], None] | None = None) -> MCResult
Run Monte Carlo uncertainty analysis.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
params
|
RpathParams
|
Base Ecopath parameters. |
required |
config
|
MCConfig
|
MC configuration. Defaults to MCConfig(). |
None
|
pedigree_config
|
PedigreeConfig
|
EwE pedigree mapping. |
None
|
progress_callback
|
callable
|
Called with (current_sample, total_samples) after each run, in sample
order, in this process (also when |
None
|
Returns:
| Type | Description |
|---|---|
MCResult
|
|
Source code in pypath/core/montecarlo.py
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 | |
Taxonomic Linkage System (Phase 1B.2)¶
Hierarchical taxonomic linking for species identification across external databases (WoRMS, ITIS, FishBase). Supports multi-level taxonomy assignment, validation, and integration with biodiversity data systems.
pypath.core.taxonomy ¶
Taxonomic hierarchical linking with WoRMS/ITIS integration.
This module provides taxonomic classification and cross-referencing for food web groups, enabling integration with authoritative taxonomic databases (WoRMS, ITIS) and hierarchical validation.
Phase 1B.2: TG3.2 Taxonomic Linkage System
TaxonLink
dataclass
¶
A single taxon with hierarchical classification and external IDs.
Represents a species or higher-order taxon with full taxonomic hierarchy, common names, and links to authoritative databases (WoRMS, ITIS).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scientific_name
|
str
|
Binomial scientific name (e.g., "Gadus morhua"). |
required |
common_name
|
str
|
Vernacular common name (e.g., "Atlantic cod"). |
None
|
worms_aphia_id
|
int
|
WoRMS (World Register of Marine Species) AphiaID. |
None
|
itis_tsn
|
str
|
ITIS (Integrated Taxonomic Information System) Taxonomic Serial Number. |
None
|
kingdom
|
str
|
Kingdom (e.g., "Animalia"). |
''
|
phylum
|
str
|
Phylum (e.g., "Chordata"). |
''
|
class_
|
str
|
Class (note: 'class' is reserved keyword, use 'class_'). |
''
|
order
|
str
|
Order (e.g., "Gadiformes"). |
''
|
family
|
str
|
Family (e.g., "Gadidae"). |
''
|
genus
|
str
|
Genus (e.g., "Gadus"). |
''
|
species
|
str
|
Species epithet (e.g., "morhua"). |
''
|
match_confidence
|
float
|
Confidence score for database match (0.0-1.0). 1.0 = exact match, <0.5 = uncertain. |
1.0
|
Attributes:
| Name | Type | Description |
|---|---|---|
kingdom, phylum, class_, order, family, genus, species |
str
|
Full taxonomic hierarchy. |
Source code in pypath/core/taxonomy.py
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 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 | |
is_valid ¶
is_valid() -> bool
Validate taxon record for completeness and consistency.
Checks that: - scientific_name is not empty - match_confidence is in [0.0, 1.0] - At least one external ID is present (worms_aphia_id or itis_tsn) - Hierarchy is at least partially filled
Returns:
| Type | Description |
|---|---|
bool
|
True if taxon is valid, False otherwise. |
Source code in pypath/core/taxonomy.py
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 | |
to_dict ¶
to_dict() -> dict
Export taxon to dictionary.
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary with all fields. |
Source code in pypath/core/taxonomy.py
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 | |
from_dict
classmethod
¶
from_dict(data: dict) -> 'TaxonLink'
Create TaxonLink from dictionary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
dict
|
Dictionary with TaxonLink fields. |
required |
Returns:
| Type | Description |
|---|---|
TaxonLink
|
Initialized taxon object. |
Source code in pypath/core/taxonomy.py
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 | |
TaxonomyLinkage ¶
Container for managing taxonomic classifications of food web groups.
Maintains a mapping of food web groups to taxa, validates consistency, and provides serialization for integration with ecological models.
Attributes:
| Name | Type | Description |
|---|---|---|
taxa |
dict[str, TaxonLink]
|
Mapping of scientific name to TaxonLink objects. |
group_assignments |
dict[str, str]
|
Mapping of group name (from Ecopath model) to scientific name. |
metadata |
dict
|
Metadata (source, timestamp, notes, etc.). |
Source code in pypath/core/taxonomy.py
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 | |
__init__ ¶
__init__() -> None
Initialize empty taxonomy container.
Source code in pypath/core/taxonomy.py
170 171 172 173 174 | |
add_taxon ¶
add_taxon(taxon: TaxonLink) -> None
Add or update a taxon.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
taxon
|
TaxonLink
|
Taxon to add. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If taxon is invalid. |
Source code in pypath/core/taxonomy.py
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 | |
get_taxon ¶
get_taxon(scientific_name: str) -> Optional[TaxonLink]
Retrieve a taxon by scientific name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scientific_name
|
str
|
Scientific name to look up. |
required |
Returns:
| Type | Description |
|---|---|
TaxonLink or None
|
Taxon if found, None otherwise. |
Source code in pypath/core/taxonomy.py
196 197 198 199 200 201 202 203 204 205 206 207 208 209 | |
assign_group ¶
assign_group(group_name: str, scientific_name: str) -> None
Assign a food web group to a taxon.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
group_name
|
str
|
Ecopath group name (e.g., "Cod"). |
required |
scientific_name
|
str
|
Scientific name of taxon. |
required |
Raises:
| Type | Description |
|---|---|
KeyError
|
If scientific_name is not in taxa. |
Source code in pypath/core/taxonomy.py
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 | |
validate ¶
validate() -> tuple[bool, list[str]]
Validate taxonomy consistency.
Checks: - All taxa are valid (is_valid() == True) - No duplicate assignments - Assigned groups reference existing taxa - Hierarchical consistency (no orphaned ranks)
Returns:
| Type | Description |
|---|---|
tuple[bool, list[str]]
|
(is_valid, error_list). is_valid is True iff error_list is empty. |
Source code in pypath/core/taxonomy.py
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 | |
to_dataframe ¶
to_dataframe() -> pd.DataFrame
Export taxonomy to DataFrame.
Returns:
| Type | Description |
|---|---|
DataFrame
|
Table with columns: group, scientific_name, common_name, worms_aphia_id, itis_tsn, kingdom, phylum, class_, order, family, genus, species, match_confidence. |
Source code in pypath/core/taxonomy.py
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 | |
from_dataframe
classmethod
¶
from_dataframe(df: DataFrame) -> 'TaxonomyLinkage'
Create TaxonomyLinkage from DataFrame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
DataFrame with columns: group, scientific_name, kingdom, etc. |
required |
Returns:
| Type | Description |
|---|---|
TaxonomyLinkage
|
Initialized taxonomy linkage. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If required columns are missing. |
Source code in pypath/core/taxonomy.py
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 | |
validate_taxonomy_links ¶
validate_taxonomy_links(taxonomy: TaxonomyLinkage) -> tuple[bool, list[str]]
Validate taxonomy linkage for consistency and completeness.
Performs comprehensive checks: - All taxa are valid - No missing or orphaned groups - No duplicate assignments - Hierarchical consistency
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
taxonomy
|
TaxonomyLinkage
|
Taxonomy object to validate. |
required |
Returns:
| Type | Description |
|---|---|
tuple[bool, list[str]]
|
(is_valid, error_list). is_valid is True iff error_list is empty. |
Source code in pypath/core/taxonomy.py
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 | |
resolve_worms_link ¶
resolve_worms_link(scientific_name: str) -> Optional[TaxonLink]
Resolve a single species name to WoRMS database.
STUB: This is a placeholder for WoRMS API integration. In production, this would query the WoRMS REST API and return a TaxonLink with WoRMS metadata.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scientific_name
|
str
|
Scientific name to resolve (e.g., "Gadus morhua"). |
required |
Returns:
| Type | Description |
|---|---|
TaxonLink or None
|
Resolved taxon with WoRMS data, or None if not found. |
Source code in pypath/core/taxonomy.py
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 | |
batch_resolve_worms ¶
batch_resolve_worms(scientific_names: list[str]) -> dict[str, Optional[TaxonLink]]
Batch resolve multiple species names to WoRMS.
STUB: This is a placeholder for batch WoRMS API integration. In production, this would efficiently query multiple species using WoRMS batch endpoints or caching.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scientific_names
|
list[str]
|
List of scientific names to resolve. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Optional[TaxonLink]]
|
Mapping of scientific name to resolved TaxonLink (or None if unfound). |
Source code in pypath/core/taxonomy.py
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 | |
Key Classes:
- TaxonLink — Full taxonomic hierarchy (kingdom through species) with external IDs
- TaxonomyLinkage — Multi-group taxonomy container with WoRMS integration stubs
- resolve_worms_link() — Look up WoRMS taxon by name (stub function)
- batch_resolve_worms_taxonomy() — Batch resolution for multiple groups
Integration with biodata.py:
- integrate_taxonomy_with_biodata() — Merge taxonomy with FishBase/WoRMS data
- resolve_worms_taxonomy() — Fetch and store WoRMS records
- sync_taxonomy_with_rpath() — Sync TaxonomyLinkage with RpathParams
Size Distribution System (Phase 1B.3)¶
Population size structure and age-size conversions for age-structured modeling and Individual-Based Model (IBM) frameworks.
pypath.core.size ¶
Size-structured population analysis using EwE PSD tables.
Phase 1B.3: TG3.3 Size Distribution System
This module implements size-structured population analysis for aquatic groups, including size class definitions, population size distributions (PSD), and von Bertalanffy growth function integration for age-size conversions.
SizeClass
dataclass
¶
A single size interval for population structure analysis.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
size_min
|
float
|
Minimum size of the interval. |
required |
size_max
|
float
|
Maximum size of the interval. |
required |
size_unit
|
str
|
Unit of size measurement ('cm' or 'mm'). |
'cm'
|
Attributes:
| Name | Type | Description |
|---|---|---|
size_min, size_max |
float
|
Interval boundaries (inclusive). |
size_unit |
str
|
Unit (default 'cm'). |
Source code in pypath/core/size.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 | |
__post_init__ ¶
__post_init__() -> None
Validate size_min, size_max, and size_unit after initialization.
Source code in pypath/core/size.py
47 48 49 50 51 52 53 54 55 | |
midpoint ¶
midpoint() -> float
Return the midpoint of the size interval.
Returns:
| Type | Description |
|---|---|
float
|
Midpoint: (size_min + size_max) / 2. |
Source code in pypath/core/size.py
57 58 59 60 61 62 63 64 65 | |
width ¶
width() -> float
Return the width of the size interval.
Returns:
| Type | Description |
|---|---|
float
|
Width: size_max - size_min. |
Source code in pypath/core/size.py
67 68 69 70 71 72 73 74 75 | |
contains ¶
contains(size: float) -> bool
Check if a size value falls within this interval.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
size
|
float
|
Size value to check. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if size_min <= size < size_max. |
Source code in pypath/core/size.py
77 78 79 80 81 82 83 84 85 86 87 88 89 90 | |
SizeDistribution
dataclass
¶
Population size distribution (PSD) for a group.
Represents the count or biomass distribution across size classes, typically imported from EwE PSD (Population Size Distribution) tables.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
group_name
|
str
|
Name of the group (e.g., "Herring"). |
required |
size_classes
|
list[SizeClass]
|
Ordered list of size intervals. |
list()
|
counts
|
ndarray
|
Individual counts per size class (1D array, same length as size_classes). |
(lambda: array([], dtype=float64))()
|
Attributes:
| Name | Type | Description |
|---|---|---|
group_name |
str
|
Unique identifier for the group. |
size_classes |
list[SizeClass]
|
Size intervals (assumed to be non-overlapping and ordered). |
counts |
ndarray
|
Count array (float64). |
Source code in pypath/core/size.py
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 | |
__post_init__ ¶
__post_init__() -> None
Validate that size_classes and counts have matching lengths.
Source code in pypath/core/size.py
123 124 125 126 127 128 129 | |
is_valid ¶
is_valid() -> bool
Validate the size distribution for consistency.
Checks that: - size_classes and counts have matching lengths - all counts are non-negative - size intervals are ordered and non-overlapping
Returns:
| Type | Description |
|---|---|
bool
|
True if valid. |
Source code in pypath/core/size.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 | |
total_count ¶
total_count() -> float
Return total individuals across all size classes.
Returns:
| Type | Description |
|---|---|
float
|
Sum of all counts. |
Source code in pypath/core/size.py
171 172 173 174 175 176 177 178 179 | |
mean_size ¶
mean_size() -> float
Compute mean size (weighted by counts).
Returns:
| Type | Description |
|---|---|
float
|
Weighted mean midpoint across size classes. |
Source code in pypath/core/size.py
181 182 183 184 185 186 187 188 189 190 191 192 193 194 | |
to_dataframe ¶
to_dataframe() -> pd.DataFrame
Export size distribution to DataFrame.
Returns:
| Type | Description |
|---|---|
DataFrame
|
Columns: ['group_name', 'size_min', 'size_max', 'size_unit', 'midpoint', 'width', 'count']. |
Source code in pypath/core/size.py
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 | |
from_dataframe
classmethod
¶
from_dataframe(df: DataFrame, group_name: str) -> SizeDistribution
Load size distribution from DataFrame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
DataFrame with columns: size_min, size_max, size_unit, count. May also contain: midpoint, width (ignored). |
required |
group_name
|
str
|
Group identifier. |
required |
Returns:
| Type | Description |
|---|---|
SizeDistribution
|
Reconstructed distribution object. |
Source code in pypath/core/size.py
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 | |
SizeStructure
dataclass
¶
Container for size distributions across multiple groups.
Manages a collection of SizeDistribution objects and provides validation and export methods.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
distributions
|
dict[str, SizeDistribution]
|
Mapping from group_name to SizeDistribution. |
dict()
|
Attributes:
| Name | Type | Description |
|---|---|---|
distributions |
dict[str, SizeDistribution]
|
Collection of PSD data by group. |
Source code in pypath/core/size.py
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 | |
add_distribution ¶
add_distribution(distribution: SizeDistribution) -> None
Add or replace a size distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
distribution
|
SizeDistribution
|
Distribution object to add. |
required |
Source code in pypath/core/size.py
281 282 283 284 285 286 287 288 289 290 | |
get_distribution ¶
get_distribution(group_name: str) -> Optional[SizeDistribution]
Retrieve a size distribution by group name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
group_name
|
str
|
Name of the group. |
required |
Returns:
| Type | Description |
|---|---|
SizeDistribution | None
|
Distribution if found, else None. |
Source code in pypath/core/size.py
292 293 294 295 296 297 298 299 300 301 302 303 304 305 | |
validate ¶
validate() -> tuple[bool, list[str]]
Validate all distributions for consistency.
Returns:
| Type | Description |
|---|---|
tuple[bool, list[str]]
|
(is_valid, error_messages). If is_valid is False, error_messages contains diagnostic details. |
Source code in pypath/core/size.py
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 | |
to_dataframe ¶
to_dataframe() -> pd.DataFrame
Export all distributions to a single DataFrame.
Returns:
| Type | Description |
|---|---|
DataFrame
|
Combined DataFrame with rows for all size classes across all groups. Columns: ['group_name', 'size_min', 'size_max', 'size_unit', 'midpoint', 'width', 'count']. |
Source code in pypath/core/size.py
328 329 330 331 332 333 334 335 336 337 338 339 340 341 | |
from_dataframe
classmethod
¶
from_dataframe(df: DataFrame) -> SizeStructure
Load size distributions from DataFrame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Combined DataFrame with a 'group_name' column grouping rows. Expected columns: group_name, size_min, size_max, size_unit, count. |
required |
Returns:
| Type | Description |
|---|---|
SizeStructure
|
Reconstructed structure with distributions for each unique group. |
Source code in pypath/core/size.py
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 | |
vb_length ¶
vb_length(age: float, loo: float, k: float, t0: float = 0.0) -> float
Von Bertalanffy length at age.
Computes length given age using the von Bertalanffy growth function: L(t) = L∞ * (1 - exp(-k * (t - t₀)))
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
age
|
float
|
Age in years. |
required |
loo
|
float
|
Asymptotic (maximum) length (same units as returned value). |
required |
k
|
float
|
Growth constant (year⁻¹). |
required |
t0
|
float
|
Theoretical age at length 0 (years, default 0.0). |
0.0
|
Returns:
| Type | Description |
|---|---|
float
|
Length at the given age. |
Source code in pypath/core/size.py
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 | |
vb_age ¶
vb_age(length: float, loo: float, k: float, t0: float = 0.0) -> float
Age from von Bertalanffy length.
Inverts the von Bertalanffy equation to compute age given length: t = t₀ - ln(1 - L / L∞) / k
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
length
|
float
|
Length in same units as loo. |
required |
loo
|
float
|
Asymptotic length. |
required |
k
|
float
|
Growth constant (year⁻¹). |
required |
t0
|
float
|
Theoretical age at length 0 (years, default 0.0). |
0.0
|
Returns:
| Type | Description |
|---|---|
float
|
Age in years corresponding to the given length. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If length >= loo or k <= 0. |
Source code in pypath/core/size.py
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 | |
age_at_size_class ¶
age_at_size_class(size_class: SizeClass, loo: float, k: float, t0: float = 0.0) -> tuple[float, float]
Compute age range for a size class using von Bertalanffy.
Given a size interval, computes the corresponding age interval using the inverse von Bertalanffy function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
size_class
|
SizeClass
|
Size interval (min, max). |
required |
loo
|
float
|
Asymptotic length in same units as size_class. |
required |
k
|
float
|
Growth constant (year⁻¹). |
required |
t0
|
float
|
Theoretical age at length 0 (default 0.0). |
0.0
|
Returns:
| Type | Description |
|---|---|
tuple[float, float]
|
(age_at_min, age_at_max) in years. age_at_max corresponds to size_min, age_at_min corresponds to size_max (inverse relationship). |
Source code in pypath/core/size.py
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 | |
validate_size_structure ¶
validate_size_structure(structure: SizeStructure) -> tuple[bool, list[str]]
Comprehensive validation of a SizeStructure.
Checks for: - Missing or empty distributions - Overlapping or gapped size ranges - Negative or inconsistent counts - Size classes not ordered
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
structure
|
SizeStructure
|
Size structure to validate. |
required |
Returns:
| Type | Description |
|---|---|
tuple[bool, list[str]]
|
(is_valid, error_messages). |
Source code in pypath/core/size.py
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 | |
estimate_psd_from_vb ¶
estimate_psd_from_vb(loo: float, k: float, t0: float, recruitment_rate: float, time_steps: int, n_size_classes: int, size_min: float = 0.1, size_max: float = 100.0, size_unit: str = 'cm', group_name: str = 'Group') -> SizeDistribution
Estimate PSD from von Bertalanffy growth parameters.
Generates a theoretical population size distribution by simulating cohorts of individuals aging under the von Bertalanffy growth function and applying recruitment. This is a simplified approach intended for initialization or sensitivity analysis.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
loo
|
float
|
Asymptotic length. |
required |
k
|
float
|
Growth constant (year⁻¹). |
required |
t0
|
float
|
Theoretical age at length 0 (years). |
required |
recruitment_rate
|
float
|
Annual recruitment (new individuals per year). |
required |
time_steps
|
int
|
Number of annual time steps to simulate. |
required |
n_size_classes
|
int
|
Number of size classes to create. |
required |
size_min
|
float
|
Minimum size (default 0.1, same units as loo). |
0.1
|
size_max
|
float
|
Maximum size (default 100.0). |
100.0
|
size_unit
|
str
|
Unit of measurement ('cm' or 'mm', default 'cm'). |
'cm'
|
group_name
|
str
|
Group identifier (default 'Group'). |
'Group'
|
Returns:
| Type | Description |
|---|---|
SizeDistribution
|
Theoretical PSD with uniform bin widths. |
Notes
This function uses a simple discrete-age cohort model with no natural mortality. The distribution is for illustrative and initialization use; a full population model should include mortality and recruitment dynamics.
Source code in pypath/core/size.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 | |
Key Classes:
- SizeClass — Size interval definition with midpoint, width, and contains logic
- SizeDistribution — Population size distribution (PSD) container with statistics
- SizeStructure — Multi-group size distributions with aggregation
Von Bertalanffy Functions:
- vb_length(age, Loo, K, t0) — Age-to-length conversion
- vb_age(length, Loo, K, t0) — Length-to-age conversion
- age_at_size_class() — Estimate mean age from size interval
- estimate_psd_from_vb() — Generate theoretical PSD from VBGF parameters
Fleet & Discard Dynamics (Phase 1B.4)¶
Dynamic fishing fleet management with gear types, catchability, effort allocation, and discard routing to multiple fates. Highest complexity Phase 1B module with integration to Ecosim fishing mortality.
pypath.core.fleet ¶
Fishing fleet management, gear types, and discard routing.
This module implements fleet-based fishing dynamics, including gear classification, catchability by group, and discard fate allocation for Ecopath with Ecosim models.
Phase 1B.4: TG3.4 Fleet & Discard System
GearType ¶
Bases: Enum
Fishing gear types with associated selectivity metadata.
Each gear type carries default bycatch rate and selectivity characteristics used in catch allocation and validation.
Attributes:
| Name | Type | Description |
|---|---|---|
SEINE |
GearType
|
Seine net (mid-water or bottom); moderate selectivity, low bycatch. |
NET |
GearType
|
General net (gill, cast, etc.); moderate-high selectivity, variable bycatch. |
TRAP |
GearType
|
Fish trap or pot; high selectivity, low bycatch. |
TRAWL |
GearType
|
Trawl (bottom, mid-water, or pelagic); low selectivity, high bycatch. |
HOOK |
GearType
|
Hook and line; very high selectivity, minimal bycatch. |
OTHER |
GearType
|
Unspecified gear; assume moderate selectivity and bycatch. |
Source code in pypath/core/fleet.py
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 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 | |
selectivity ¶
selectivity() -> float
Return default selectivity for this gear type.
Selectivity (0-1) represents how narrowly the gear targets intended species. Higher values = more selective (lower bycatch proportion).
Returns:
| Type | Description |
|---|---|
float
|
Selectivity coefficient (0.2-1.0). |
Source code in pypath/core/fleet.py
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | |
bycatch_rate ¶
bycatch_rate() -> float
Return default bycatch rate for this gear type.
Bycatch rate (0-1) represents the proportion of non-target catch relative to target catch.
Returns:
| Type | Description |
|---|---|
float
|
Bycatch rate (0.0-0.8). |
Source code in pypath/core/fleet.py
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 | |
FleetGroup
dataclass
¶
A fishing fleet with effort, catchability, and gear composition.
Represents a commercial or subsistence fishing fleet targeting one or more groups. Effort is applied via catchability coefficients (q values) to compute catch from available biomass.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Fleet name (e.g., "Small-scale pelagic"). |
required |
fleet_id
|
int
|
Unique fleet identifier (0-based). |
required |
gears
|
list[GearType]
|
List of gear types used by this fleet. |
required |
fuel_efficiency
|
float
|
Fuel consumption (kg fuel per ton catch). Default 0.05. |
0.05
|
base_effort
|
float
|
Nominal effort (days or trips per year). Default 100. |
100.0
|
catchability
|
dict[str, float]
|
Catchability coefficients (q values) by group name. Maps group_name -> q. |
dict()
|
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
Fleet name. |
fleet_id |
int
|
Fleet identifier. |
gears |
list[GearType]
|
Gear list. |
fuel_efficiency |
float
|
Fuel per unit catch (0.01-0.20). |
base_effort |
float
|
Baseline effort (>0). |
catchability |
dict[str, float]
|
q values (0.0-1.0). |
Raises:
| Type | Description |
|---|---|
ValueError
|
If fleet_id < 0, base_effort <= 0, or catchability values out of bounds. |
Source code in pypath/core/fleet.py
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 | |
__post_init__ ¶
__post_init__() -> None
Validate fleet parameters after initialization.
Source code in pypath/core/fleet.py
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 | |
is_valid ¶
is_valid() -> bool
Validate fleet definition for completeness.
Checks that name, fleet_id, and at least one catchability value exist.
Returns:
| Type | Description |
|---|---|
bool
|
True if valid, False otherwise. |
Source code in pypath/core/fleet.py
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 | |
to_dict ¶
to_dict() -> dict
Serialize fleet to dictionary.
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary with keys: name, fleet_id, gears, fuel_efficiency, base_effort, catchability. |
Source code in pypath/core/fleet.py
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 | |
from_dict
classmethod
¶
from_dict(data: dict) -> FleetGroup
Deserialize fleet from dictionary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
dict
|
Dictionary with fleet parameters. |
required |
Returns:
| Type | Description |
|---|---|
FleetGroup
|
Reconstructed fleet instance. |
Source code in pypath/core/fleet.py
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 | |
DiscardPath
dataclass
¶
Pathway for discarded catch to its fate.
Discards can be lost to the system (total mortality), routed to predators (as food), or deposited as detritus/benthos. Depth-dependent routing enables spatially-explicit discard fate in Ecospace.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source_group
|
str
|
Group name for the discarded catch (e.g., "Juvenile cod"). |
required |
target_group
|
str
|
Group that consumes discards (None for lost/detritus routing). |
None
|
discard_rate
|
float
|
Proportion discarded (0-1). Example: 0.15 = 15% discarded. |
0.0
|
fate
|
str
|
Discard fate ('lost', 'predation', 'detritus', 'benthos'). - 'lost': mortality (biomass removed from system) - 'predation': biomass routed to target_group - 'detritus': enters detritus pool - 'benthos': enters benthic organic matter pool |
'lost'
|
depth_dependent
|
bool
|
If True, discard fate depends on water column position (Ecospace). |
False
|
Attributes:
| Name | Type | Description |
|---|---|---|
source_group |
str
|
Source group name. |
target_group |
str | None
|
Target group name (or None). |
discard_rate |
float
|
Proportion discarded (0.0-1.0). |
fate |
str
|
Fate category. |
depth_dependent |
bool
|
Spatially-explicit routing flag. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If discard_rate not in [0, 1] or fate not in valid categories. |
Source code in pypath/core/fleet.py
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 | |
__post_init__ ¶
__post_init__() -> None
Validate discard path parameters after initialization.
Source code in pypath/core/fleet.py
270 271 272 273 274 275 276 277 278 | |
is_valid ¶
is_valid() -> bool
Validate discard path for consistency.
Checks that source_group exists and fate-group combinations are valid.
Returns:
| Type | Description |
|---|---|
bool
|
True if valid, False otherwise. |
Source code in pypath/core/fleet.py
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 | |
apply_to_biomass ¶
apply_to_biomass(biomass: float) -> float
Calculate discard biomass from total catch.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
biomass
|
float
|
Total catch biomass (tons). |
required |
Returns:
| Type | Description |
|---|---|
float
|
Discard biomass (tons). |
Source code in pypath/core/fleet.py
298 299 300 301 302 303 304 305 306 307 308 309 310 311 | |
to_dict ¶
to_dict() -> dict
Serialize discard path to dictionary.
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary representation. |
Source code in pypath/core/fleet.py
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 | |
from_dict
classmethod
¶
from_dict(data: dict) -> DiscardPath
Deserialize discard path from dictionary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
dict
|
Dictionary with discard path parameters. |
required |
Returns:
| Type | Description |
|---|---|
DiscardPath
|
Reconstructed discard path instance. |
Source code in pypath/core/fleet.py
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 | |
FleetDynamics
dataclass
¶
Container for fleet groups and discard routing rules.
Manages collection of fleets and discard paths, with validation and application methods for catch allocation and discard fate routing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fleets
|
dict[str, FleetGroup]
|
Fleet groups indexed by name. Default empty dict. |
dict()
|
discard_paths
|
dict[str, list[DiscardPath]]
|
Discard paths indexed by source_group. Default empty dict. |
dict()
|
Attributes:
| Name | Type | Description |
|---|---|---|
fleets |
dict[str, FleetGroup]
|
Active fleets. |
discard_paths |
dict[str, list[DiscardPath]]
|
Discard routing rules. |
Source code in pypath/core/fleet.py
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 | |
add_fleet ¶
add_fleet(fleet: FleetGroup) -> None
Add or replace a fleet.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fleet
|
FleetGroup
|
Fleet to add. If a fleet with the same name exists, it is replaced. |
required |
Source code in pypath/core/fleet.py
377 378 379 380 381 382 383 384 385 386 387 388 | |
add_discard_path ¶
add_discard_path(path: DiscardPath) -> None
Add a discard path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
DiscardPath
|
Discard path to add. |
required |
Source code in pypath/core/fleet.py
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 | |
get_fleet ¶
get_fleet(name: str) -> Optional[FleetGroup]
Retrieve a fleet by name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Fleet name. |
required |
Returns:
| Type | Description |
|---|---|
FleetGroup | None
|
Fleet if found, None otherwise. |
Source code in pypath/core/fleet.py
408 409 410 411 412 413 414 415 416 417 418 419 420 421 | |
validate ¶
validate() -> tuple[bool, list[str]]
Validate fleet dynamics configuration.
Checks that: - All fleets are valid - All discard paths are valid - Referenced groups exist (soft check: logged as warning, not error)
Returns:
| Type | Description |
|---|---|
tuple[bool, list[str]]
|
(is_valid, error_messages). is_valid=True only if all checks pass. |
Source code in pypath/core/fleet.py
423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 | |
to_dataframe ¶
to_dataframe() -> dict[str, pd.DataFrame]
Convert fleet dynamics to DataFrame representation.
Returns:
| Type | Description |
|---|---|
dict[str, DataFrame]
|
Dictionary with keys 'fleets' and 'discards', each a DataFrame. - fleets: columns [name, fleet_id, gears, fuel_efficiency, base_effort, catchability (dict column)] - discards: columns [source_group, target_group, discard_rate, fate, depth_dependent] |
Source code in pypath/core/fleet.py
448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 | |
from_dataframe
classmethod
¶
from_dataframe(fleets_df: DataFrame, discards_df: DataFrame) -> FleetDynamics
Reconstruct fleet dynamics from DataFrames.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fleets_df
|
DataFrame
|
Fleet data (as returned by to_dataframe()['fleets']). |
required |
discards_df
|
DataFrame
|
Discard data (as returned by to_dataframe()['discards']). |
required |
Returns:
| Type | Description |
|---|---|
FleetDynamics
|
Reconstructed fleet dynamics instance. |
Source code in pypath/core/fleet.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 | |
allocate_catch ¶
allocate_catch(total_catch: float, catchability: dict[str, float]) -> dict[str, float]
Allocate catch across groups based on catchability.
Distributes total catch proportionally to catchability coefficients (q values) for each group.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
total_catch
|
float
|
Total catch biomass (tons). |
required |
catchability
|
dict[str, float]
|
Catchability by group name. Values should be normalized (sum to ~1) for intuitive interpretation. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, float]
|
Allocated catch per group. |
Examples:
>>> catchability = {"Cod": 0.6, "Haddock": 0.4}
>>> catch = allocate_catch(100.0, catchability)
>>> catch["Cod"]
60.0
Source code in pypath/core/fleet.py
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 | |
allocate_discards ¶
allocate_discards(discard_rate: float, source_group: str) -> dict[str, float]
Allocate discard biomass from a source group.
Computes discard proportion and residual landed proportion from a discard rate. Used to split catch into landed and discarded components.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
discard_rate
|
float
|
Proportion discarded (0-1). |
required |
source_group
|
str
|
Source group name (for logging). |
required |
Returns:
| Type | Description |
|---|---|
dict[str, float]
|
Dictionary with 'landed' and 'discarded' proportions. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If discard_rate not in [0, 1]. |
Source code in pypath/core/fleet.py
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 | |
validate_allocation ¶
validate_allocation(allocation: dict[str, float], tolerance: float = 0.01) -> bool
Validate that allocation sums to approximately 1.0.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
allocation
|
dict[str, float]
|
Allocation dictionary (e.g., from allocate_catch or allocate_discards). |
required |
tolerance
|
float
|
Acceptable deviation from 1.0. Default 0.01 (1%). |
0.01
|
Returns:
| Type | Description |
|---|---|
bool
|
True if allocation sums to 1.0 ± tolerance, False otherwise. |
Source code in pypath/core/fleet.py
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 | |
estimate_catch_value ¶
estimate_catch_value(catch: dict[str, float], prices: dict[str, float]) -> float
Estimate total economic value of catch.
Multiplies catch biomass by price per unit (e.g., $/kg) for each group and sums the total value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
catch
|
dict[str, float]
|
Catch biomass per group (tons). |
required |
prices
|
dict[str, float]
|
Price per unit (e.g., $/kg) by group name. |
required |
Returns:
| Type | Description |
|---|---|
float
|
Total catch value (in same currency units as prices). |
Notes
This is a stub function for economic analysis. Price data and units ($/kg, $/ton, etc.) should be externally documented.
Source code in pypath/core/fleet.py
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 | |
estimate_fuel_cost ¶
estimate_fuel_cost(effort: float, fuel_price: float) -> float
Estimate fuel cost for fishing effort.
Computes cost based on effort (days/trips) and fuel price per unit. Assumes a default fuel consumption profile per effort unit.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
effort
|
float
|
Effort (days or trips). |
required |
fuel_price
|
float
|
Price per unit fuel (e.g., $/liter). |
required |
Returns:
| Type | Description |
|---|---|
float
|
Total fuel cost (same currency units as fuel_price). |
Notes
This is a stub function. Actual fuel consumption profiles should be calibrated to specific fleet characteristics or regional data.
Source code in pypath/core/fleet.py
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 | |
Key Classes:
- GearType — Enum for 6 gear types (SEINE, NET, TRAP, TRAWL, HOOK, OTHER)
- FleetGroup — Fleet definition with catchability matrix, fuel efficiency, base effort
- DiscardPath — Discard routing with 4 fates (lost, predation, detritus, benthos)
- FleetDynamics — Multi-fleet container with allocation and validation
Allocation Functions:
- allocate_catch() — Distribute catch among prey based on catchability
- allocate_discards() — Route discards to specified fates
- estimate_catch_value() — Economic value estimation (stub)
- estimate_fuel_cost() — Fuel cost calculation (stub)
Nutrient Cycling System (Phase 1B.5)¶
Ecosystem-level nutrient cycling (N, P, C) with excretion, uptake kinetics, and stoichiometric relationships. Implements Monod saturation for producer nutrient limitation.
pypath.core.nutrients ¶
Nutrient cycling (N, P, C) system for Ecopath groups.
This module implements nutrient content, excretion, and uptake calculations following standard aquatic biogeochemistry conventions.
NutrientElement ¶
Bases: str, Enum
Nutrient elements tracked in food web models.
Attributes:
| Name | Type | Description |
|---|---|---|
NITROGEN |
str
|
Nitrogen (N), molecular weight 14.01 g/mol |
PHOSPHORUS |
str
|
Phosphorus (P), molecular weight 30.97 g/mol |
CARBON |
str
|
Carbon (C), molecular weight 12.01 g/mol |
Source code in pypath/core/nutrients.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 | |
molecular_weight
property
¶
molecular_weight: float
Molecular weight in g/mol.
Returns:
| Type | Description |
|---|---|
float
|
Molecular weight of the element. |
NutrientContent
dataclass
¶
Nutrient elemental composition of a biomass group.
Attributes:
| Name | Type | Description |
|---|---|---|
group_name |
str
|
Name of the functional group |
nitrogen_percent |
float
|
Nitrogen as % dry weight (typical: 7-15%) |
phosphorus_percent |
float
|
Phosphorus as % dry weight (typical: 1-2%) |
carbon_percent |
float
|
Carbon as % dry weight (typical: 45-50%) |
ash_percent |
float
|
Ash (mineral) as % dry weight (typical: 5-15%) |
Source code in pypath/core/nutrients.py
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 | |
__post_init__ ¶
__post_init__() -> None
Validate nutrient composition ranges.
Source code in pypath/core/nutrients.py
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 | |
is_valid ¶
is_valid() -> bool
Check if nutrient composition is valid.
Returns:
| Type | Description |
|---|---|
bool
|
True if all constraints are satisfied, False otherwise. |
Source code in pypath/core/nutrients.py
102 103 104 105 106 107 108 109 110 111 112 113 114 | |
to_dict ¶
to_dict() -> Dict[str, float]
Convert to dictionary representation.
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary with nutrient percentages. |
Source code in pypath/core/nutrients.py
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 | |
from_dict
classmethod
¶
from_dict(data: Dict[str, float]) -> NutrientContent
Create from dictionary representation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
dict
|
Dictionary with required keys: group_name, nitrogen_percent, phosphorus_percent, carbon_percent, ash_percent. |
required |
Returns:
| Type | Description |
|---|---|
NutrientContent
|
Instantiated object. |
Source code in pypath/core/nutrients.py
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 | |
NutrientExcretion
dataclass
¶
Excretion rates and fecal composition for a group.
Attributes:
| Name | Type | Description |
|---|---|---|
group_name |
str
|
Name of the functional group |
n_excretion_rate |
float
|
Nitrogen excretion as % of daily consumption (typical: 5-15%) |
p_excretion_rate |
float
|
Phosphorus excretion as % of daily consumption (typical: 1-3%) |
fecal_n_fraction |
float
|
Fraction of excretion that is fecal vs. dissolved (0-1) |
fecal_p_fraction |
float
|
Fraction of phosphorus excretion that is fecal (0-1) |
Source code in pypath/core/nutrients.py
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__() -> None
Validate excretion rates.
Source code in pypath/core/nutrients.py
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 | |
calculate_excretion ¶
calculate_excretion(consumption: float, element: str) -> float
Calculate excretion of a nutrient element.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
consumption
|
float
|
Daily consumption rate (mass units, e.g., kg/day) |
required |
element
|
str
|
Element name ('nitrogen' or 'phosphorus') |
required |
Returns:
| Type | Description |
|---|---|
float
|
Daily excretion rate (same units as consumption) |
Raises:
| Type | Description |
|---|---|
ValueError
|
If element is not 'nitrogen' or 'phosphorus'. |
Source code in pypath/core/nutrients.py
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 | |
to_dict ¶
to_dict() -> Dict[str, float]
Convert to dictionary representation.
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary with excretion parameters. |
Source code in pypath/core/nutrients.py
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 | |
NutrientUptake
dataclass
¶
Nutrient uptake kinetics for primary producers.
Attributes:
| Name | Type | Description |
|---|---|---|
group_name |
str
|
Name of the functional group (typically a primary producer) |
n_uptake_rate |
float
|
Maximum nitrogen uptake rate (mg N / mg biomass / day) |
p_uptake_rate |
float
|
Maximum phosphorus uptake rate (mg P / mg biomass / day) |
half_saturation_n |
float
|
Half-saturation constant for nitrogen (mg N/L) |
half_saturation_p |
float
|
Half-saturation constant for phosphorus (mg P/L) |
Source code in pypath/core/nutrients.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 | |
__post_init__ ¶
__post_init__() -> None
Validate uptake parameters.
Source code in pypath/core/nutrients.py
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 | |
calculate_uptake ¶
calculate_uptake(nutrient_level: float, rate: float) -> float
Calculate uptake using Monod (Michaelis-Menten) kinetics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
nutrient_level
|
float
|
Ambient nutrient concentration (mg/L) |
required |
rate
|
float
|
Maximum uptake rate (Vmax) |
required |
Returns:
| Type | Description |
|---|---|
float
|
Uptake rate under Monod kinetics (mg/L/day or similar) |
Notes
Uses the Monod equation: v = (Vmax * [S]) / (Km + [S]) where Km is the appropriate half-saturation constant.
Source code in pypath/core/nutrients.py
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 | |
to_dict ¶
to_dict() -> Dict[str, float]
Convert to dictionary representation.
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary with uptake parameters. |
Source code in pypath/core/nutrients.py
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 | |
NutrientCycle
dataclass
¶
Container for nutrient cycling parameters across all groups.
Attributes:
| Name | Type | Description |
|---|---|---|
contents |
dict
|
Mapping of group_name -> NutrientContent |
excretions |
dict
|
Mapping of group_name -> NutrientExcretion |
uptakes |
dict
|
Mapping of group_name -> NutrientUptake (typically producers only) |
Source code in pypath/core/nutrients.py
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 | |
add_content ¶
add_content(content: NutrientContent) -> None
Add or update nutrient content for a group.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
content
|
NutrientContent
|
Nutrient composition parameters. |
required |
Source code in pypath/core/nutrients.py
358 359 360 361 362 363 364 365 366 367 368 369 | |
add_excretion ¶
add_excretion(excretion: NutrientExcretion) -> None
Add or update excretion parameters for a group.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
excretion
|
NutrientExcretion
|
Excretion and fecal composition parameters. |
required |
Source code in pypath/core/nutrients.py
371 372 373 374 375 376 377 378 379 380 | |
add_uptake ¶
add_uptake(uptake: NutrientUptake) -> None
Add or update uptake parameters for a group.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
uptake
|
NutrientUptake
|
Nutrient uptake kinetics (typically for producers). |
required |
Source code in pypath/core/nutrients.py
382 383 384 385 386 387 388 389 390 391 | |
validate ¶
validate() -> Tuple[bool, List[str]]
Validate nutrient cycle consistency.
Returns:
| Type | Description |
|---|---|
tuple[bool, list[str]]
|
(is_valid, list of error/warning messages) |
Source code in pypath/core/nutrients.py
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 | |
calculate_mass_balance ¶
calculate_mass_balance(rpath_params: RpathParams) -> Dict[str, float]
Calculate nutrient mass balance across groups.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rpath_params
|
RpathParams
|
Ecopath model parameters with biomass and flow information. |
required |
Returns:
| Type | Description |
|---|---|
dict
|
Mass balance summary with keys like 'total_n_biomass', 'total_p_biomass', 'balance_status'. |
Source code in pypath/core/nutrients.py
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 | |
to_dataframe ¶
to_dataframe() -> pd.DataFrame
Convert to pandas DataFrame representation.
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with one row per group, containing nutrient content, excretion, and uptake parameters. |
Source code in pypath/core/nutrients.py
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 | |
from_dataframe
classmethod
¶
from_dataframe(df: DataFrame) -> NutrientCycle
Create from pandas DataFrame representation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
DataFrame with nutrient parameters, one row per group. |
required |
Returns:
| Type | Description |
|---|---|
NutrientCycle
|
Instantiated NutrientCycle object. |
Source code in pypath/core/nutrients.py
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 | |
validate_nutrient_cycle ¶
validate_nutrient_cycle(cycle: NutrientCycle) -> Tuple[bool, List[str]]
Validate a complete nutrient cycling system.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cycle
|
NutrientCycle
|
Nutrient cycle to validate. |
required |
Returns:
| Type | Description |
|---|---|
tuple[bool, list[str]]
|
(is_valid, list of error/warning messages) |
Notes
This function performs comprehensive validation including: - Individual data integrity - Consistency across content, excretion, and uptake - Reasonable biological ranges
Source code in pypath/core/nutrients.py
593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 | |
estimate_excretion_from_pb ¶
estimate_excretion_from_pb(pb_ratio: float, group_type: str = 'consumer') -> Dict[str, float]
Estimate excretion rates from Production/Biomass ratio.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pb_ratio
|
float
|
Production/Biomass ratio (1/year) |
required |
group_type
|
str
|
Type of group ('consumer', 'producer', or 'detritus') |
'consumer'
|
Returns:
| Type | Description |
|---|---|
dict
|
Estimated excretion parameters with keys: - n_excretion_rate (% of consumption per day) - p_excretion_rate (% of consumption per day) - fecal_n_fraction - fecal_p_fraction |
Notes
This is a heuristic based on typical aquatic food web stoichiometry. Empirical calibration may be required for specific systems.
Source code in pypath/core/nutrients.py
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 | |
Key Classes:
- NutrientElement — Enum for N, P, C with molecular weights
- NutrientContent — Elemental composition (%) with validation
- NutrientExcretion — Excretion rates with fecal/dissolved partitioning
- NutrientUptake — Producer kinetics (half-saturation, max rate)
- NutrientCycle — Ecosystem-level cycling with mass balance
Key Functions:
- uptake_rate_monod() — Monod saturation function for producer uptake
- validate_nutrient_cycle() — Consistency checks across groups
- estimate_excretion_from_pb() — Heuristic excretion estimation from P/B
Enhanced Landings System (Phase 1B.6)¶
Catch and landings tracking with temporal (seasonal) distribution, landing types, and aggregation. Interfaces with dynamic Ecosim monthly dispatch.
pypath.core.landings ¶
Landings system for catch/landings tracking with temporal distribution.
This module implements catch and landings data management for fisheries, including support for multiple landing types, temporal distribution (seasonality), and validation of catch data.
Classes:
| Name | Description |
|---|---|
LandingType |
Enum defining types of catch/landings. |
LandingRecord |
Dataclass representing a single catch record. |
LandingSeasonality |
Dataclass for monthly catch distribution patterns. |
LandingsData |
Container for managing collections of landing records and seasonality patterns. |
Functions:
| Name | Description |
|---|---|
validate_landings |
Validate a LandingsData collection. |
estimate_seasonality_from_records |
Infer monthly seasonality from historical records. |
aggregate_landings |
Sum catches by group, year, and/or landing type. |
LandingType ¶
Bases: Enum
Enumeration of catch/landings types.
Attributes:
| Name | Type | Description |
|---|---|---|
COMMERCIAL |
Commercial fishing catch. |
|
SUBSISTENCE |
Subsistence/artisanal fishing. |
|
RECREATIONAL |
Recreational fishing catch. |
|
UNREPORTED |
Unreported or illegal fishing catch. |
|
DISCARDS |
Discarded bycatch. |
Source code in pypath/core/landings.py
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | |
LandingRecord
dataclass
¶
A single catch/landings record.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
group_name
|
str
|
Name of the functional group (e.g., "Cod", "Herring"). |
required |
year
|
int
|
Year of the landing. |
required |
month
|
Optional[int]
|
Month of landing (1-12), or None if annual. |
required |
landing_type
|
LandingType
|
Type of catch/landing. |
required |
catch_tons
|
float
|
Catch in metric tons, must be >= 0. |
required |
value_usd
|
Optional[float]
|
Economic value in USD, optional. |
None
|
fleet_id
|
Optional[str]
|
Identifier for the fleet (e.g., "Baltic_Demersal_Fleet"). |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
During validation if data is inconsistent. |
Source code in pypath/core/landings.py
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 | |
__post_init__ ¶
__post_init__() -> None
Validate record on instantiation.
Source code in pypath/core/landings.py
101 102 103 104 | |
is_valid ¶
is_valid() -> bool
Check if the record is valid.
Returns:
| Type | Description |
|---|---|
bool
|
True if group_name is non-empty, year is positive, month (if present) is in 1-12, catch_tons >= 0, and value_usd (if present) >= 0. |
Source code in pypath/core/landings.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 | |
is_seasonal ¶
is_seasonal() -> bool
Check if this record has seasonal (monthly) resolution.
Returns:
| Type | Description |
|---|---|
bool
|
True if month is specified. |
Source code in pypath/core/landings.py
132 133 134 135 136 137 138 139 140 | |
to_dict ¶
to_dict() -> dict
Convert to dictionary representation.
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary with all fields; LandingType converted to string value. |
Source code in pypath/core/landings.py
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 | |
from_dict
classmethod
¶
from_dict(data: dict) -> LandingRecord
Create from dictionary representation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
dict
|
Dictionary with record fields. landing_type can be string (enum value) or LandingType instance. |
required |
Returns:
| Type | Description |
|---|---|
LandingRecord
|
Reconstructed record. |
Source code in pypath/core/landings.py
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 | |
LandingSeasonality
dataclass
¶
Temporal (monthly) distribution of catch for a functional group.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
group_name
|
str
|
Name of the functional group. |
required |
monthly_proportions
|
ndarray
|
Array of shape (12,) with monthly fractions summing to 1.0. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If monthly_proportions does not sum to ~1.0 or has incorrect shape. |
Source code in pypath/core/landings.py
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 | |
__post_init__ ¶
__post_init__() -> None
Validate seasonality on instantiation.
Source code in pypath/core/landings.py
201 202 203 204 205 | |
is_valid ¶
is_valid() -> bool
Check if seasonality is valid.
Returns:
| Type | Description |
|---|---|
bool
|
True if proportions has length 12, all values >= 0, and sum ≈ 1.0. |
Source code in pypath/core/landings.py
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 | |
get_monthly_catch ¶
get_monthly_catch(annual_catch: float) -> np.ndarray
Distribute annual catch across months using seasonality.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
annual_catch
|
float
|
Total annual catch in metric tons. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Array of shape (12,) with monthly catch values. |
Source code in pypath/core/landings.py
233 234 235 236 237 238 239 240 241 242 243 244 245 246 | |
to_dict ¶
to_dict() -> dict
Convert to dictionary representation.
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary with group_name and monthly_proportions (as list). |
Source code in pypath/core/landings.py
248 249 250 251 252 253 254 255 256 257 258 259 | |
from_dict
classmethod
¶
from_dict(data: dict) -> LandingSeasonality
Create from dictionary representation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
dict
|
Dictionary with group_name and monthly_proportions. |
required |
Returns:
| Type | Description |
|---|---|
LandingSeasonality
|
Reconstructed seasonality pattern. |
Source code in pypath/core/landings.py
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 | |
LandingsData
dataclass
¶
Container for landing records and seasonality patterns.
Attributes:
| Name | Type | Description |
|---|---|---|
records |
List[LandingRecord]
|
Collection of landing records. |
seasonality |
Dict[str, LandingSeasonality]
|
Seasonality patterns indexed by group name. |
Source code in pypath/core/landings.py
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 | |
add_record ¶
add_record(record: LandingRecord) -> None
Add a landing record.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
record
|
LandingRecord
|
Record to add. Must be valid. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If record is not valid. |
Source code in pypath/core/landings.py
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 | |
add_seasonality ¶
add_seasonality(seasonality: LandingSeasonality) -> None
Add or update a seasonality pattern.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seasonality
|
LandingSeasonality
|
Seasonality pattern. Must be valid. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If seasonality is not valid. |
Source code in pypath/core/landings.py
318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 | |
get_annual_catch ¶
get_annual_catch(group_name: str, year: int) -> float
Get total annual catch for a group and year.
Aggregates across all landing types and seasons.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
group_name
|
str
|
Name of the functional group. |
required |
year
|
int
|
Year to query. |
required |
Returns:
| Type | Description |
|---|---|
float
|
Total catch in metric tons. |
Source code in pypath/core/landings.py
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 | |
get_monthly_catch ¶
get_monthly_catch(group_name: str, year: int, month: int) -> float
Get catch for a specific month.
First checks for exact monthly records; if not found and seasonality exists, estimates from annual data using seasonality pattern.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
group_name
|
str
|
Name of the functional group. |
required |
year
|
int
|
Year to query. |
required |
month
|
int
|
Month (1-12). |
required |
Returns:
| Type | Description |
|---|---|
float
|
Monthly catch in metric tons. |
Source code in pypath/core/landings.py
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 | |
validate ¶
validate() -> Tuple[bool, List[str]]
Validate all records and seasonality patterns.
Returns:
| Type | Description |
|---|---|
Tuple[bool, List[str]]
|
(is_valid, list_of_error_messages). is_valid is True if all records and seasonality patterns are valid and consistent. |
Source code in pypath/core/landings.py
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 | |
to_dataframe ¶
to_dataframe() -> pd.DataFrame
Convert records to DataFrame.
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with columns: group_name, year, month, landing_type, catch_tons, value_usd, fleet_id. |
Source code in pypath/core/landings.py
427 428 429 430 431 432 433 434 435 436 437 438 439 | |
from_dataframe
classmethod
¶
from_dataframe(df: DataFrame) -> LandingsData
Create LandingsData from DataFrame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
DataFrame with columns matching LandingRecord fields. |
required |
Returns:
| Type | Description |
|---|---|
LandingsData
|
Reconstructed container. |
Source code in pypath/core/landings.py
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 | |
validate_landings ¶
validate_landings(landings: LandingsData) -> Tuple[bool, List[str]]
Validate a LandingsData collection.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
landings
|
LandingsData
|
Collection to validate. |
required |
Returns:
| Type | Description |
|---|---|
Tuple[bool, List[str]]
|
(is_valid, error_messages). |
Source code in pypath/core/landings.py
462 463 464 465 466 467 468 469 470 471 472 473 474 475 | |
estimate_seasonality_from_records ¶
estimate_seasonality_from_records(records: List[LandingRecord], group_name: str) -> Optional[LandingSeasonality]
Estimate monthly seasonality from historical records.
Computes the proportion of catch in each month across all available records for a given group.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
records
|
List[LandingRecord]
|
List of landing records with monthly resolution. |
required |
group_name
|
str
|
Name of the functional group. |
required |
Returns:
| Type | Description |
|---|---|
Optional[LandingSeasonality]
|
Seasonality pattern, or None if no monthly data available. |
Source code in pypath/core/landings.py
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 | |
aggregate_landings ¶
aggregate_landings(records: List[LandingRecord], group_name: Optional[str] = None, year: Optional[int] = None, landing_type: Optional[LandingType] = None) -> float
Aggregate landing records by filters.
Sum catch across records matching specified criteria. All filters are optional; if omitted, matches all records.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
records
|
List[LandingRecord]
|
Records to aggregate. |
required |
group_name
|
Optional[str]
|
Filter by functional group name. |
None
|
year
|
Optional[int]
|
Filter by year. |
None
|
landing_type
|
Optional[LandingType]
|
Filter by landing type. |
None
|
Returns:
| Type | Description |
|---|---|
float
|
Sum of catch_tons for matching records. |
Source code in pypath/core/landings.py
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 | |
Key Classes:
- LandingType — Enum for 5 catch categories (COMMERCIAL, SUBSISTENCE, RECREATIONAL, UNREPORTED, DISCARDS)
- LandingRecord — Month-level catch tracking with optional value and fleet ID
- LandingSeasonality — Monthly catch distribution patterns (12-element array)
- LandingsData — Multi-record container with aggregation and validation
Key Functions:
- estimate_seasonality_from_records() — Infer monthly patterns from data
- aggregate_landings() — Flexible aggregation (by group, year, type, season)
- dispatch_to_monthly_steps() — Convert annual landings to monthly for Ecosim
Sensitivity Analysis¶
Morris OAT screening and Sobol variance-based sensitivity analysis.
pypath.core.sensitivity ¶
Sensitivity analysis for Ecopath/Ecosim models.
Morris elementary effects screening and optional Sobol variance-based
sensitivity analysis (requires SALib). SensitivityConfig.n_jobs runs the
evaluations in worker processes; the results are the serial run's, bit for
bit.
MorrisResult
dataclass
¶
Morris elementary effects screening results.
Source code in pypath/core/sensitivity.py
39 40 41 42 43 44 45 46 47 | |
SobolResult
dataclass
¶
Sobol variance-based sensitivity indices.
Source code in pypath/core/sensitivity.py
50 51 52 53 54 55 56 57 58 59 | |
SensitivityConfig
dataclass
¶
Sensitivity analysis configuration.
Every evaluation balances the model with Ecopath and reads its biomass.
Attributes:
| Name | Type | Description |
|---|---|---|
method |
str
|
"morris" (elementary effects screening) or "sobol" (variance-based indices, needs SALib). |
n_trajectories |
int
|
Morris trajectories; each costs one evaluation per parameter, plus one. |
n_levels |
int
|
Morris grid levels |
n_samples |
int
|
Sobol base sample size |
seed |
(int, optional)
|
Seed for the design and for Sobol's bootstrap confidence intervals; None draws fresh ones. |
n_jobs |
int
|
Worker processes for the evaluations. 1 (the default) runs them
serially in this process. A larger number runs that many processes,
never more than there are evaluations; -1 uses one per CPU this
process may use. The design is drawn up front from |
output_variable |
str
|
Name stored as the result's |
output_group_idx |
(int, optional)
|
Group whose biomass is the output; None sums the biomass of every group that is not a fleet. |
ecopath_only |
bool
|
Not used: every evaluation is an Ecopath balance. |
ecosim_years |
(range, optional)
|
Not used: every evaluation is an Ecopath balance. |
mp_context |
(str, optional)
|
The multiprocessing start method for the workers: "forkserver", "spawn" or "fork". None uses forkserver on Linux and spawn on macOS and Windows, as CPython's own defaults do from Python 3.14. forkserver and spawn start clean worker processes:
"fork" starts workers fastest but is unsafe in a multi-threaded process (Python warns, and numpy's BLAS threads count), so ask for it only from a single-threaded script. |
Source code in pypath/core/sensitivity.py
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 | |
run_sensitivity ¶
run_sensitivity(params: 'RpathParams', config: SensitivityConfig | None = None, *, pedigree_config: 'PedigreeConfig | None' = None, progress_callback: Callable[[int, int], None] | None = None) -> MorrisResult | SobolResult
Run sensitivity analysis on Ecopath/Ecosim model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
params
|
RpathParams
|
Base Ecopath parameters. |
required |
config
|
SensitivityConfig
|
Sensitivity configuration. |
None
|
pedigree_config
|
PedigreeConfig
|
EwE pedigree mapping. |
None
|
progress_callback
|
callable
|
Called with (current, total) after each model evaluation, in order,
in this process (also when |
None
|
Returns:
| Type | Description |
|---|---|
MorrisResult or SobolResult
|
|
Source code in pypath/core/sensitivity.py
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 | |
Simplified contaminant tracer (ecotracer)¶
Track contaminant concentrations through the food web coupled to Ecosim biomass dynamics. This is PyPath's own simplified tracer, not a port of EwE's Ecotracer: it has no environment pool, and its uptake and loss terms differ, so its results are not EwE Ecotracer output.
pypath.core.ecotracer ¶
Simplified contaminant tracer, coupled to Ecosim.
Tracks contaminant concentrations alongside Ecosim biomass dynamics. Each group has initial concentration, environmental/immigration inputs, decay, assimilation, and metabolism rates.
This is PyPath's own simplified tracer, not a port of EwE's Ecotracer:
it has no environment pool, and its uptake and loss terms differ. Its
results should not be read as EwE Ecotracer output (deviation F in
docs/parity/deviations.md).
EcotracerParams
dataclass
¶
Per-group tracer parameters.
All arrays are 0-based, length n_groups = NUM_LIVING + NUM_DEAD. No fleets, no padding column.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
czero
|
ndarray
|
Initial concentration per group (n_groups,). |
required |
cenv
|
ndarray
|
Environmental input concentration (n_groups,). |
required |
cimmig
|
ndarray
|
Immigration input concentration (n_groups,). |
required |
cdecay
|
ndarray
|
Decay rate (n_groups,). |
required |
cassim
|
ndarray
|
Assimilation proportion, 0-1 (n_groups,). |
required |
cmetab
|
ndarray
|
Metabolism loss rate (n_groups,). |
required |
Source code in pypath/core/ecotracer.py
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 | |
EcotracerResult
dataclass
¶
Output time series from Ecotracer simulation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
out_Conc
|
ndarray
|
Monthly concentrations (n_months+1, n_groups). Index 0 is initial state. |
required |
annual_Conc
|
ndarray
|
Annual average concentrations (n_years, n_groups). |
required |
group_names
|
list[str]
|
Group name labels. |
required |
Source code in pypath/core/ecotracer.py
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | |
create_ecotracer_params ¶
create_ecotracer_params(n_groups: int) -> EcotracerParams
Create EcotracerParams with sensible defaults.
Defaults: czero=0, cenv=0, cimmig=0, cdecay=0, cassim=1.0, cmetab=0.
Source code in pypath/core/ecotracer.py
74 75 76 77 78 79 80 81 82 83 84 85 86 | |
ecotracer_deriv ¶
ecotracer_deriv(conc: ndarray, biomass: ndarray, Q_matrix: ndarray, params: EcotracerParams, detritus_fate: ndarray | None = None, n_living: int = 0) -> np.ndarray
Compute dC/dt for all groups.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
conc
|
ndarray
|
Current concentrations (n_groups,). |
required |
biomass
|
ndarray
|
Current biomass (n_groups,). |
required |
Q_matrix
|
ndarray
|
Consumption matrix Q[prey, pred] (n_groups, n_groups), 0-based. |
required |
params
|
EcotracerParams
|
Tracer parameters. |
required |
detritus_fate
|
ndarray
|
Detritus fate fractions (n_living, n_detritus). When None, detritus only decays. |
None
|
n_living
|
int
|
Number of living groups (groups 0..n_living-1 are living, n_living..n_groups-1 are detritus). |
0
|
Returns:
| Type | Description |
|---|---|
ndarray
|
dC/dt for each group (n_groups,). |
Source code in pypath/core/ecotracer.py
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 | |
ecotracer_step ¶
ecotracer_step(conc: ndarray, biomass: ndarray, Q_matrix: ndarray, params: EcotracerParams, dt: float, detritus_fate: ndarray | None = None, n_living: int = 0) -> np.ndarray
Analytic update for tracer concentration (unconditionally stable).
For each group i: input_i = dietary_intake_i + cenv_i + cimmig_i loss_rate_i = cdecay_i + cmetab_i if loss_rate_i > 0: C_i(t+dt) = input_i/loss_rate_i + (C_i - input_i/loss_rate_i) * exp(-loss_rate_i*dt) else: C_i(t+dt) = C_i + input_i * dt
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
conc
|
ndarray
|
Current concentrations (n_groups,). |
required |
biomass
|
ndarray
|
Current biomass (n_groups,). |
required |
Q_matrix
|
ndarray
|
Consumption matrix Q[prey, pred] (n_groups, n_groups), 0-based. |
required |
params
|
EcotracerParams
|
Tracer parameters. |
required |
dt
|
float
|
Timestep (typically 1/12 for monthly). |
required |
detritus_fate
|
ndarray
|
Detritus fate fractions (n_living, n_detritus). |
None
|
n_living
|
int
|
Number of living groups. |
0
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Updated concentrations (n_groups,), clamped to >= 0. |
Source code in pypath/core/ecotracer.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 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 | |
Fleet Dynamics¶
Dynamic fleet effort response to profitability with quota management.
pypath.core.fleet_dynamics ¶
Fleet Dynamics: profit-responsive effort and TAC quota management.
Models fleet capacity dynamics where effort responds to economic profit signals, and total allowable catch (TAC) quotas can cap fishing activity.
Each fleet has capacity that grows when profitable and depreciates otherwise. Effort is derived from capacity via an efficiency power relationship.
FleetEconParams
dataclass
¶
Economic parameters for fleet dynamics.
All cost/price arrays are indexed by fishing link (1-based externally, but stored as 0-based arrays here).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fixed_cost
|
ndarray
|
Fixed annual cost per fleet (n_fleets,). Does not depend on effort. |
required |
variable_cost
|
ndarray
|
Variable cost per fleet per unit capacity (n_fleets,). |
required |
sailing_cost
|
ndarray
|
Sailing cost per fleet per unit capacity (n_fleets,). |
required |
price
|
ndarray
|
Price per unit catch per fishing link (n_links,). |
required |
cap_depreciate
|
ndarray
|
Capacity depreciation rate per fleet (n_fleets,). |
required |
cap_base_growth
|
ndarray
|
Base capacity growth rate per fleet when profitable (n_fleets,). |
required |
eff_power
|
ndarray
|
Efficiency power: effort = capacity ** eff_power (n_fleets,). |
required |
tac
|
ndarray or None
|
Total allowable catch (n_fleets, n_groups). None means no TAC limits. |
None
|
Source code in pypath/core/fleet_dynamics.py
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 | |
FleetDynamicsResult
dataclass
¶
Output time series from fleet dynamics simulation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
out_Effort
|
ndarray
|
Monthly effort per fleet (n_months, n_fleets). |
required |
out_Revenue
|
ndarray
|
Monthly revenue per fleet (n_months, n_fleets). |
required |
out_Cost
|
ndarray
|
Monthly cost per fleet (n_months, n_fleets). |
required |
out_Profit
|
ndarray
|
Monthly profit per fleet (n_months, n_fleets). |
required |
annual_Effort
|
ndarray
|
Annual average effort per fleet (n_years, n_fleets). |
required |
annual_Profit
|
ndarray
|
Annual total profit per fleet (n_years, n_fleets). |
required |
fleet_names
|
list[str]
|
Fleet name labels. |
required |
Source code in pypath/core/fleet_dynamics.py
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 | |
create_fleet_econ_params ¶
create_fleet_econ_params(n_fleets: int, n_links: int) -> FleetEconParams
Create FleetEconParams with sensible defaults.
Defaults: all cost/depreciation rates zero, eff_power=1.0, tac=None.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_fleets
|
int
|
Number of fleets. |
required |
n_links
|
int
|
Number of fishing links (fleet-group combinations). |
required |
Returns:
| Type | Description |
|---|---|
FleetEconParams
|
Parameter object with zero arrays and eff_power=1.0. |
Source code in pypath/core/fleet_dynamics.py
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 | |
fleet_dynamics_step ¶
fleet_dynamics_step(capacity: ndarray, monthly_catch: ndarray, cumulative_catch: ndarray, params: FleetEconParams, fish_through: ndarray, fish_from: ndarray, fleet_lookup: dict, n_fleets: int, dt: float = 1.0 / 12) -> tuple[np.ndarray, np.ndarray]
Advance fleet capacity and effort by one time step.
Computes revenue from catches, costs from capacity, a profit signal, then updates capacity using a logistic-style ODE.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
capacity
|
ndarray
|
Current fleet capacities (n_fleets,). Modified in place via copy. |
required |
monthly_catch
|
ndarray
|
Catch from this month's fishing links (n_links,). 1-based index 0 unused. |
required |
cumulative_catch
|
ndarray
|
Cumulative annual catch per fleet per group (n_fleets, n_groups). Not modified here; used externally. |
required |
params
|
FleetEconParams
|
Economic parameters. |
required |
fish_through
|
ndarray
|
Fleet group index per fishing link (1-based, length n_links+1, index 0 unused). |
required |
fish_from
|
ndarray
|
Prey group index per fishing link (1-based, length n_links+1, index 0 unused). |
required |
fleet_lookup
|
dict
|
Maps gear_0based (int) -> 1-based gear array index (int). |
required |
n_fleets
|
int
|
Number of fleets. |
required |
dt
|
float
|
Time step in years (default 1/12 for monthly). |
1.0 / 12
|
Returns:
| Name | Type | Description |
|---|---|---|
new_capacity |
ndarray
|
Updated fleet capacities (n_fleets,). |
effort |
ndarray
|
Fleet effort this step (n_fleets,), effort = capacity ** eff_power. |
Source code in pypath/core/fleet_dynamics.py
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 | |
apply_quota_caps ¶
apply_quota_caps(fish_q: ndarray, cumulative_catch: ndarray, tac: ndarray, fish_through: ndarray, fish_from: ndarray, fleet_lookup: dict) -> np.ndarray
Zero out fishing catchability for links that have reached their TAC.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fish_q
|
ndarray
|
Current FishQ values per fishing link (n_links+1,), index 0 unused. |
required |
cumulative_catch
|
ndarray
|
Cumulative annual catch (n_fleets, n_groups), 0-based indices. |
required |
tac
|
ndarray
|
Total allowable catch allocation (n_fleets, n_groups), 0-based. |
required |
fish_through
|
ndarray
|
Fleet group index per fishing link (1-based, length n_links+1). |
required |
fish_from
|
ndarray
|
Prey group index per fishing link (1-based, length n_links+1). |
required |
fleet_lookup
|
dict
|
Maps gear_0based (int) -> 1-based gear array index (int). |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Copy of fish_q with zeroed entries for TAC-exhausted links. |
Source code in pypath/core/fleet_dynamics.py
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 | |
Ecological Indicators¶
Ecosystem-level indicators including Ulanowicz flow analysis, Finn Cycling Index, transfer efficiency, and system maturity indices.
pypath.core.indicators ¶
Ecological indicators: flow analysis and ecosystem summary metrics.
Provides Ulanowicz ascendency framework (TST, ascendency, capacity, overhead, Finn cycling index) and ecosystem summary indicators (MTL catch, Marine Trophic Index, Shannon diversity, Kempton Q, gross efficiency).
FlowAnalysis
dataclass
¶
Results of Ulanowicz flow analysis.
Attributes:
| Name | Type | Description |
|---|---|---|
total_system_throughput |
float
|
TST: sum of all flows through the system. |
ascendency |
float
|
System organization (bits x flow). |
capacity |
float
|
Development capacity (upper bound for ascendency). |
overhead |
float
|
Capacity - Ascendency (resilience reserve). |
relative_ascendency |
float
|
Ascendency / Capacity [0-1]. |
finn_cycling_index |
float
|
Fraction of TST recycled [0-1]. |
transfer_efficiency |
ndarray
|
Per-trophic-level transfer efficiency array. |
Source code in pypath/core/indicators.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 | |
EcosystemIndicators
dataclass
¶
Ecosystem summary indicators from balanced Ecopath model.
Attributes:
| Name | Type | Description |
|---|---|---|
mtl_catch |
float
|
Mean trophic level of catch. |
marine_trophic_index |
float
|
MTL of catch excluding groups with TL < 3.25. |
catch_biomass_ratio |
float
|
Total catch / total living biomass. |
gross_efficiency |
float
|
Total catch / net primary production. |
shannon_diversity |
float
|
Shannon H' of biomass (living groups), natural log. |
kempton_q |
float
|
Biomass evenness in TL 3-4 range. |
Source code in pypath/core/indicators.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 | |
SystemMaturityIndices
dataclass
¶
Odum's ecosystem development / maturity indicators.
Attributes:
| Name | Type | Description |
|---|---|---|
total_production |
float
|
Sum of production across all living groups (P = Σ PB×B). |
total_respiration |
float
|
Sum of respiration across all living groups (R = Σ QB×B×Unassim + metabolism). |
total_biomass |
float
|
Sum of biomass across all living groups. |
net_production |
float
|
Total production minus total respiration (P - R). |
pr_ratio |
float
|
Production / Respiration ratio. Mature ecosystems approach 1.0. |
b_tst_ratio |
float
|
Total biomass / total system throughput. Higher in mature ecosystems. |
mean_path_length |
float
|
Average number of trophic transfers per unit of energy. Computed as TST / total consumption at TL 1. |
Source code in pypath/core/indicators.py
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 | |
flow_analysis ¶
flow_analysis(rpath: Rpath) -> FlowAnalysis
Compute Ulanowicz flow analysis for a balanced Ecopath model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rpath
|
Rpath
|
Balanced Ecopath model with computed trophic levels. |
required |
Returns:
| Type | Description |
|---|---|
FlowAnalysis
|
TST, ascendency, capacity, overhead, relative ascendency, Finn cycling index, and per-level transfer efficiency. |
Source code in pypath/core/indicators.py
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 | |
finn_cycling_index ¶
finn_cycling_index(rpath: Rpath) -> float
Compute Finn Cycling Index for a balanced Ecopath model.
The Finn Cycling Index (FCI) measures the fraction of total system throughput that is recycled. Values near 0 indicate linear flow; values near 1 indicate high recycling.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rpath
|
Rpath
|
Balanced Ecopath model. |
required |
Returns:
| Type | Description |
|---|---|
float
|
Finn Cycling Index in [0, 1]. |
Source code in pypath/core/indicators.py
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 | |
transfer_efficiency ¶
transfer_efficiency(rpath: Rpath) -> np.ndarray
Compute per-trophic-level transfer efficiency.
Uses simplified integer-bin approach: groups are binned by floor(TL), and efficiency is computed as the ratio of flow from level L to level L+1 divided by total input to level L.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rpath
|
Rpath
|
Balanced Ecopath model. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Transfer efficiency per TL bin (starting from TL 2). Empty array if no groups at TL >= 2. |
Source code in pypath/core/indicators.py
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 | |
ecosystem_indicators ¶
ecosystem_indicators(rpath: Rpath) -> EcosystemIndicators
Compute ecosystem summary indicators from a balanced Ecopath model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rpath
|
Rpath
|
Balanced Ecopath model. |
required |
Returns:
| Type | Description |
|---|---|
EcosystemIndicators
|
Static ecosystem summary metrics. |
Source code in pypath/core/indicators.py
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 | |
system_maturity ¶
system_maturity(rpath: Rpath) -> SystemMaturityIndices
Compute Odum's ecosystem maturity indicators.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rpath
|
Rpath
|
Balanced Ecopath model. |
required |
Returns:
| Type | Description |
|---|---|
SystemMaturityIndices
|
|
Source code in pypath/core/indicators.py
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 | |
ecosystem_indicators_timeseries ¶
ecosystem_indicators_timeseries(output: RsimOutput, scenario: RsimScenario, rpath: Rpath) -> pd.DataFrame
Compute ecosystem indicators per year from Ecosim output.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output
|
RsimOutput
|
Ecosim simulation output with annual_Biomass and annual_Catch. |
required |
scenario
|
RsimScenario
|
Ecosim scenario for group count validation. |
required |
rpath
|
Rpath
|
Balanced Ecopath model for trophic levels and group types. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
Columns: year, mtl_catch, marine_trophic_index, catch_biomass_ratio, gross_efficiency, shannon_diversity. One row per year. |
Source code in pypath/core/indicators.py
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 | |