Core API Reference¶
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 | |
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
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 | |
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
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 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 | |
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. |
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 | |
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
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 | |
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
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 | |
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
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 | |
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
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 | |
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
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 | |
Ecosim (Dynamic Simulation)¶
pypath.core.ecosim ¶
Ecosim dynamic simulation implementation.
This module will contain the core Ecosim simulation engine, including the derivative calculations and integration methods.
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) |
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
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 | |
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
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 | |
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
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 | |
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
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 | |
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
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 | |
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 values (n_months x n_groups+1) |
out_Gear_Catch |
ndarray
|
Monthly catch by gear link |
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
|
Optional monthly stanza-resolved biomass (n_months x n_groups+1) |
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 |
Source code in pypath/core/ecosim.py
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 | |
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) -> 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) |
0.0
|
handleselfwt
|
float
|
Prey overlap weight (0 = individual, 1 = all overlap) |
0.0
|
steps_yr
|
int
|
Timesteps per year (default 12 = monthly) |
12
|
steps_m
|
int
|
Sub-timesteps per month (default 1) |
1
|
Returns:
| Type | Description |
|---|---|
RsimParams
|
Parameters object for simulation |
Source code in pypath/core/ecosim.py
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 | |
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
753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 | |
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
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 | |
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
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 | |
rsim_scenario ¶
rsim_scenario(rpath: Rpath, rpath_params: RpathParams, years: range = range(1, 101), vulnerability: float = 2.0) -> 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
|
Returns:
| Type | Description |
|---|---|
RsimScenario
|
Complete scenario ready for simulation |
Source code in pypath/core/ecosim.py
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 | |
rsim_run ¶
rsim_run(scenario: RsimScenario, method: str = 'RK4', years: Optional[range] = None) -> RsimOutput
Run Ecosim simulation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scenario
|
RsimScenario
|
Simulation scenario |
required |
method
|
str
|
Integration method: 'RK4' (Runge-Kutta 4) or 'AB' (Adams-Bashforth) |
'RK4'
|
years
|
range
|
Years to run (default: all years in scenario) |
None
|
Returns:
| Type | Description |
|---|---|
RsimOutput
|
Simulation results |
Source code in pypath/core/ecosim.py
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 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 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 1211 1212 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 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 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 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 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 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 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 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 1971 1972 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 2035 2036 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 2092 2093 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 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 | |
ODE Derivatives¶
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.
SimState
dataclass
¶
Current state of the simulation.
Source code in pypath/core/ecosim_deriv.py
561 562 563 564 565 566 567 568 569 570 571 572 573 574 | |
prey_switching ¶
prey_switching(BB: ndarray, Bbase: ndarray, pred: int, ActiveLink: ndarray, switch_power: float = 2.0) -> np.ndarray
Calculate prey switching factors.
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
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 | |
mediation_function ¶
mediation_function(mediation_type: int, med_bio: float, med_base: float, med_params: Dict[str, float]) -> float
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
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 | |
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
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 | |
deriv_vector ¶
deriv_vector(state: ndarray, params: dict, forcing: dict, fishing: dict, t: float = 0.0) -> 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: Prey switching power (0-2, default 0) - 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] |
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
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Derivative vector (dB/dt for each group) |
Source code in pypath/core/ecosim_deriv.py
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 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 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 1211 1212 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 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 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 | |
integrate_rk4 ¶
integrate_rk4(state: ndarray, params: dict, forcing: dict, fishing: dict, dt: float) -> np.ndarray
Runge-Kutta 4th order integration step.
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 |
Returns:
| Type | Description |
|---|---|
ndarray
|
Updated state vector |
Source code in pypath/core/ecosim_deriv.py
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 | |
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 4-step Adams-Bashforth method when history is available, falls back to simpler methods with less 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
1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 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 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 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 1971 1972 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 2035 2036 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 2092 2093 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 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 | |
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
2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 | |
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.
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
Source code in pypath/core/stanzas.py
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 | |
RsimStanzas
dataclass
¶
Stanza parameters for Ecosim simulation.
Contains age-structured dynamics parameters needed by the simulation engine.
Source code in pypath/core/stanzas.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 122 123 124 125 126 127 128 129 130 131 132 133 134 | |
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
Source code in pypath/core/stanzas.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 | |
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 biomass: Calculated biomass qb: Calculated Q/B
Source code in pypath/core/stanzas.py
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 | |
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
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 | |
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. |
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
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 | |
rpath_stanzas ¶
rpath_stanzas(rpath_params: RpathParams) -> 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 |
Returns:
| Type | Description |
|---|---|
RpathParams
|
Updated RpathParams with calculated stanza biomass and Q/B |
Source code in pypath/core/stanzas.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 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 | |
rsim_stanzas ¶
rsim_stanzas(rpath_params: RpathParams, state: ndarray, params: dict) -> 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 |
Returns:
| Type | Description |
|---|---|
RsimStanzas
|
RsimStanzas object with simulation parameters |
Source code in pypath/core/stanzas.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 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 | |
split_set_pred ¶
split_set_pred(stanzas: RsimStanzas, state: ndarray, params: dict) -> None
Set predation rates for stanza groups.
Updates the consumption calculations for multi-stanza groups based on current biomass.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stanzas
|
RsimStanzas
|
RsimStanzas object |
required |
state
|
ndarray
|
RsimState with current biomass |
required |
params
|
dict
|
RsimParams with model parameters |
required |
Source code in pypath/core/stanzas.py
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 | |
split_update ¶
split_update(stanzas: RsimStanzas, state: ndarray, params: dict, sim_month: int) -> None
Update stanza age structure for a simulation month.
This updates the numbers-at-age, weight-at-age, and recruitment for multi-stanza groups.
Called monthly during Ecosim simulation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stanzas
|
RsimStanzas
|
RsimStanzas object |
required |
state
|
ndarray
|
RsimState with current biomass |
required |
params
|
dict
|
RsimParams with model parameters |
required |
sim_month
|
int
|
Current simulation month |
required |
Source code in pypath/core/stanzas.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 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 | |
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
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 | |
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 |
Source code in pypath/core/stanzas.py
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 | |
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. Can be: - Single year (int) - Range of years (range object) - List of years |
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 |
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 |
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 | |
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
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 | |
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
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 | |
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
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 | |
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
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 | |
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
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 | |
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
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 | |
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
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 | |
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
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 | |
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
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 | |
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
285 286 287 288 289 290 291 292 293 294 | |
reset ¶
reset()
Reset diet to base values.
Source code in pypath/core/forcing.py
373 374 375 376 | |
update_diet ¶
update_diet(prey_biomass: ndarray, predator_idx: Optional[int] = None) -> np.ndarray
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
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 | |
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
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 | |
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
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 | |
ForcingMode ¶
Bases: Enum
Mode for applying forced values.
Source code in pypath/core/forcing.py
24 25 26 27 28 29 30 | |
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
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 | |
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
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 | |
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
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 | |
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
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 | |
StateVariable ¶
Bases: Enum
State variables that can be forced.
Source code in pypath/core/forcing.py
33 34 35 36 37 38 39 40 41 42 | |
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
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 | |
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
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 | |
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
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 | |
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
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 | |
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
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 | |
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
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 | |
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
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 | |
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
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 | |
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
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 | |
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
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 | |
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
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 | |
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
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 | |
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
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 | |