I/O API Reference¶
Import and export functions for loading Ecopath models from various sources: EcoBase online repository, EwE Access databases, CSV files, and external biological/environmental data services.
EcoBase¶
Search, download, and convert models from the EcoBase online repository of published Ecopath models.
pypath.io.ecobase ¶
EcoBase database connector for PyPath.
This module provides functions to connect to the EcoBase database (http://ecobase.ecopath.org/) and download Ecopath model data.
EcoBase is a global repository of Ecopath models maintained by AGROCAMPUS OUEST (France).
Functions: - list_ecobase_models(): Get list of all available public models - get_ecobase_model(model_id): Download a specific model's data - ecobase_to_rpath(model_data): Convert EcoBase data to RpathParams
Example: >>> from pypath.io.ecobase import list_ecobase_models, get_ecobase_model >>> models = list_ecobase_models() >>> print(f"Found {len(models)} models") >>> model_data = get_ecobase_model(403) # Get specific model >>> rpath_params = ecobase_to_rpath(model_data)
EcoBaseGroupData
dataclass
¶
Data for a single functional group from EcoBase.
Attributes:
| Name | Type | Description |
|---|---|---|
group_seq |
int
|
Group sequence number (1-based) |
group_name |
str
|
Name of the group |
trophic_level |
float
|
Calculated trophic level |
biomass |
float
|
Biomass (t/km²) |
biomass_hab |
float
|
Biomass in habitat area |
prod_biom |
float
|
Production/Biomass ratio (/year) |
cons_biom |
float
|
Consumption/Biomass ratio (/year) |
ecotrophic_eff |
float
|
Ecotrophic efficiency |
prod_cons |
float
|
Production/Consumption ratio |
unassim_cons |
float
|
Unassimilated consumption fraction |
habitat_area |
float
|
Habitat area fraction |
Source code in pypath/io/ecobase.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 | |
EcoBaseModel
dataclass
¶
Container for EcoBase model metadata.
Attributes:
| Name | Type | Description |
|---|---|---|
model_number |
int
|
Unique model identifier in EcoBase |
model_name |
str
|
Name of the model |
country |
str
|
Country/region of the ecosystem |
ecosystem_type |
str
|
Type of ecosystem (marine, freshwater, etc.) |
num_groups |
int
|
Number of functional groups |
author |
str
|
Model author(s) |
year |
int
|
Year of model creation |
reference |
str
|
Publication reference |
description |
str
|
Model description |
dissemination_allow |
bool
|
Whether public access is allowed |
Source code in pypath/io/ecobase.py
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 | |
download_ecobase_model_to_file ¶
download_ecobase_model_to_file(model_id: int, output_path: str, format: str = 'csv') -> None
Download EcoBase model and save to file(s).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_id
|
int
|
Model ID from EcoBase |
required |
output_path
|
str
|
Base path for output files (without extension) |
required |
format
|
str
|
Output format: 'csv', 'excel', 'json' |
'csv'
|
Example
download_ecobase_model_to_file(403, "baltic_model", format="csv")
Creates: baltic_model_groups.csv, baltic_model_diet.csv¶
Source code in pypath/io/ecobase.py
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 | |
ecobase_to_rpath ¶
ecobase_to_rpath(model_data: Dict[str, Any], include_fleets: bool = True, use_input_values: bool = True) -> RpathParams
Convert EcoBase model data to RpathParams.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_data
|
dict
|
Model data from get_ecobase_model() |
required |
include_fleets
|
bool
|
Whether to include fishing fleets |
True
|
use_input_values
|
bool
|
If True, prefer input values (before balancing) over output values. EcoBase stores both input (original) and output (balanced) parameters. |
True
|
Returns:
| Type | Description |
|---|---|
RpathParams
|
PyPath parameter structure ready for balancing |
Example
model_data = get_ecobase_model(403) params = ecobase_to_rpath(model_data) from pypath.core.ecopath import rpath balanced = rpath(params)
Source code in pypath/io/ecobase.py
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 | |
get_ecobase_model ¶
get_ecobase_model(model_id: int, timeout: int = 60) -> Dict[str, Any]
Download a specific model from EcoBase.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_id
|
int
|
Model number (from list_ecobase_models()) |
required |
timeout
|
int
|
Request timeout in seconds |
60
|
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary containing: - 'metadata': Model metadata - 'groups': List of group data dictionaries - 'diet': Diet matrix as nested dict - 'raw_xml': Raw XML string for debugging |
Example
model_data = get_ecobase_model(403) print(f"Model has {len(model_data['groups'])} groups")
Source code in pypath/io/ecobase.py
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 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 | |
list_ecobase_models ¶
list_ecobase_models(filter_public: bool = True, timeout: int = 60) -> pd.DataFrame
Get list of available Ecopath models from EcoBase.
Connects to the EcoBase SOAP API and retrieves metadata for all available models.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filter_public
|
bool
|
If True, only return models with public access allowed |
True
|
timeout
|
int
|
Request timeout in seconds |
60
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with model metadata including: - model_number: Unique ID - model_name: Name - country: Location - ecosystem_type: Type - num_groups: Number of groups - author: Author(s) - year: Year - reference: Publication |
Example
models = list_ecobase_models() print(f"Found {len(models)} public models")
Filter by ecosystem type¶
marine = models[models['ecosystem_type'].str.contains('marine', case=False)]
Source code in pypath/io/ecobase.py
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 | |
search_ecobase_models ¶
search_ecobase_models(query: str, field: str = 'all', models_df: Optional[DataFrame] = None) -> pd.DataFrame
Search EcoBase models by keyword.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query
|
str
|
Search term |
required |
field
|
str
|
Field to search: 'all', 'model_name', 'country', 'ecosystem_type', 'author' |
'all'
|
models_df
|
DataFrame
|
Pre-fetched models DataFrame. If None, will fetch from EcoBase. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Matching models |
Example
results = search_ecobase_models("Baltic") results = search_ecobase_models("coral", field="ecosystem_type")
Source code in pypath/io/ecobase.py
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 | |
EwE Database (.eweaccdb)¶
Read Ecopath with Ecosim models stored in Microsoft Access database
format (.eweaccdb / .ewemdb).
Key functions:
read_ewemdb()— load Ecopath parameters (biomass, diet, stanzas)read_ewemdb_table()— read any raw table from the databaselist_ewemdb_tables()— list all tables in an EwE databaseget_ewemdb_metadata()— retrieve model metadataecosim_scenario_from_ewemdb()— load a complete Ecosim scenario with vulnerability overrides, foraging time adjustments, forced biomass, fishing effort, and environmental forcing from a specific EwE scenario ID
See the EwE Database Loading example for a complete walkthrough.
pypath.io.ewemdb ¶
EwE Database (ewemdb) file reader for PyPath.
This module provides functions to read Ecopath with Ecosim database files (.ewemdb format), which are Microsoft Access database files.
The ewemdb format is the native file format for EwE 6.x software. These files contain all model parameters, diet matrices, time series, and simulation settings.
Requirements: - pyodbc (Windows with Access drivers) - pypyodbc (alternative) - or: mdbtools + pandas (Linux/Mac)
Functions: - read_ewemdb(filepath): Read an ewemdb file and return RpathParams - list_ewemdb_tables(filepath): List all tables in the database - read_ewemdb_table(filepath, table): Read a specific table as DataFrame
Example: >>> from pypath.io.ewemdb import read_ewemdb >>> params = read_ewemdb("my_model.ewemdb") >>> from pypath.core.ecopath import rpath >>> balanced = rpath(params)
EcospaceReadResult
dataclass
¶
Result of reading Ecospace configuration from an EwE database.
Source code in pypath/io/ewemdb.py
3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 | |
EwEDatabaseError ¶
Bases: Exception
Exception for EwE database errors.
Source code in pypath/io/ewemdb.py
193 194 195 196 | |
TaxonomyData
dataclass
¶
Complete taxonomy data from an EwE model.
Source code in pypath/io/ewemdb.py
107 108 109 110 111 112 113 | |
TaxonomyRecord
dataclass
¶
A single species/taxon entry from EcopathTaxon.
Source code in pypath/io/ewemdb.py
92 93 94 95 96 97 98 99 100 101 102 103 104 | |
ValueChainData
dataclass
¶
Raw EwE value chain tables as DataFrames for round-trip I/O.
Source code in pypath/io/ewemdb.py
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 | |
check_ewemdb_support ¶
check_ewemdb_support() -> Dict[str, bool]
Check what database drivers are available.
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary indicating available drivers: - pyodbc: True if pyodbc is installed - pypyodbc: True if pypyodbc is installed - mdb_tools: True if mdb-tools is available - any_available: True if any driver works |
Source code in pypath/io/ewemdb.py
3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 | |
ecosim_scenario_from_ewemdb ¶
ecosim_scenario_from_ewemdb(filepath: str, scenario: Optional[Union[int, str]] = 1, balance: bool = True, years: Optional[range] = None) -> 'RsimScenario'
Convenience: create a full RsimScenario from an EwE database scenario.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filepath
|
str
|
Path to .ewemdb file |
required |
scenario
|
int or str
|
Scenario ID (int) or name (str) to select |
1
|
balance
|
bool
|
Whether to run Ecopath balancing via :func: |
True
|
years
|
range
|
Years to simulate. If None, derived from scenario metadata. |
None
|
Returns:
| Type | Description |
|---|---|
RsimScenario
|
Ready-to-run scenario object (can be passed to :func: |
Example
scen = ecosim_scenario_from_ewemdb('model.ewemdb', scenario=1) out = rsim_run(scen, method='RK4', years=range(1, 11))
Source code in pypath/io/ewemdb.py
3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 | |
get_ewemdb_metadata ¶
get_ewemdb_metadata(filepath: str) -> Dict[str, Any]
Get metadata from an EwE database file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filepath
|
str
|
Path to the ewemdb file |
required |
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary with model metadata including: - name: Model name - description: Model description - author: Author name - date: Creation date - version: EwE version - num_groups: Number of groups - num_fleets: Number of fleets |
Source code in pypath/io/ewemdb.py
3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 | |
list_ewemdb_tables ¶
list_ewemdb_tables(filepath: str) -> List[str]
List all tables in an EwE database file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filepath
|
str
|
Path to the ewemdb file |
required |
Returns:
| Type | Description |
|---|---|
list
|
List of table names |
Example
tables = list_ewemdb_tables("model.ewemdb") print(tables) ['EcopathGroup', 'EcopathDietComp', 'EcopathFleet', ...]
Source code in pypath/io/ewemdb.py
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 | |
read_ecospace ¶
read_ecospace(db_path: str, n_groups: int, scenario_id: int = 1, grid: 'Optional[EcospaceGrid]' = None) -> EcospaceReadResult
Read Ecospace configuration from an EwE database.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
db_path
|
str
|
Path to the .eweaccdb database file. |
required |
n_groups
|
int
|
Number of living + dead groups (from Ecopath model). |
required |
scenario_id
|
int
|
Scenario ID to filter by (default 1). |
1
|
grid
|
EcospaceGrid
|
User-provided spatial grid. If None, a regular grid is constructed from Inrow/Incol/CellLength in EcospaceScenario. |
None
|
Returns:
| Type | Description |
|---|---|
EcospaceReadResult
|
|
Raises:
| Type | Description |
|---|---|
EwEDatabaseError
|
If EcospaceScenario table is missing. |
Source code in pypath/io/ewemdb.py
3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 | |
read_ecotracer ¶
read_ecotracer(db_path: str, n_groups: int) -> 'EcotracerParams'
Read Ecotracer parameters from an EwE database.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
db_path
|
str
|
Path to the .eweaccdb database file. |
required |
n_groups
|
int
|
Number of groups (NUM_LIVING + NUM_DEAD). |
required |
Returns:
| Type | Description |
|---|---|
EcotracerParams
|
Tracer parameters with per-group values. Returns default params if tables are missing/empty. |
Source code in pypath/io/ewemdb.py
3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 | |
read_ewemdb ¶
read_ewemdb(filepath: str, scenario: int = 1, include_ecosim: bool = False) -> RpathParams
Read an EwE database file and convert to RpathParams.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filepath
|
str
|
Path to the ewemdb file |
required |
scenario
|
int
|
Scenario number to load (default: 1) |
1
|
include_ecosim
|
bool
|
Whether to read Ecosim parameters (not yet implemented) |
False
|
Returns:
| Type | Description |
|---|---|
RpathParams
|
PyPath parameter structure ready for balancing |
Example
params = read_ewemdb("my_model.ewemdb") from pypath.core.ecopath import rpath balanced = rpath(params)
Notes
The ewemdb format uses Microsoft Access database structure. Key tables include: - EcopathGroup: Group parameters (biomass, P/B, Q/B, etc.) - EcopathDietComp: Diet composition matrix - EcopathFleet: Fleet definitions - EcopathCatch: Catch data by fleet and group - Stanza: Multi-stanza group definitions - StanzaLifeStage: Life stage parameters
Source code in pypath/io/ewemdb.py
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 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 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 | |
read_ewemdb_table ¶
read_ewemdb_table(filepath: str, table: str, columns: Optional[List[str]] = None) -> pd.DataFrame
Read a specific table from an EwE database.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filepath
|
str
|
Path to the ewemdb file |
required |
table
|
str
|
Name of the table to read |
required |
columns
|
list
|
Specific columns to read. If None, reads all columns. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Table data as DataFrame |
Example
groups = read_ewemdb_table("model.ewemdb", "EcopathGroup") print(groups.columns)
Source code in pypath/io/ewemdb.py
398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 | |
read_fleet_dynamics ¶
read_fleet_dynamics(db_path: str, n_fleets: int, n_links: int, n_groups: int, fleet_ids: list[int], fishing_links: dict) -> 'FleetEconParams'
Read fleet dynamics parameters from an EwE database.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
db_path
|
str
|
Path to the .eweaccdb database file. |
required |
n_fleets
|
int
|
Number of fleets. |
required |
n_links
|
int
|
Number of fishing links (length of FishFrom array). |
required |
n_groups
|
int
|
Number of biological groups (NUM_LIVING + NUM_DEAD). |
required |
fleet_ids
|
list[int]
|
1-based EcopathFleetID values, in fleet array order. |
required |
fishing_links
|
dict
|
Must contain 'FishFrom' and 'FishThrough' arrays (1-based). |
required |
Returns:
| Type | Description |
|---|---|
FleetEconParams
|
Fleet dynamics parameters. Returns defaults if tables missing. |
Source code in pypath/io/ewemdb.py
3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 | |
read_mediation ¶
read_mediation(db_path: str) -> 'MediationCollection'
Read mediation shapes and link assignments from an EwE database.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
db_path
|
str
|
Path to the .eweaccdb database file. |
required |
Returns:
| Type | Description |
|---|---|
MediationCollection
|
Collection of shapes and links. Empty if mediation tables are missing. |
Source code in pypath/io/ewemdb.py
3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 | |
read_mpa_config ¶
read_mpa_config(db_path: str, n_patches: int, fleet_ids: list[int], scenario_id: int = 1) -> 'MPAConfig'
Read MPA configuration from an EwE database.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
db_path
|
str
|
Path to the .eweaccdb database file. |
required |
n_patches
|
int
|
Number of spatial patches. |
required |
fleet_ids
|
list[int]
|
1-based EcopathFleetID values, in fleet array order. |
required |
scenario_id
|
int
|
Scenario ID to filter by (default 1). |
1
|
Returns:
| Type | Description |
|---|---|
MPAConfig
|
MPA configuration. Returns empty config if tables missing. |
Source code in pypath/io/ewemdb.py
4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 | |
read_pedigree ¶
read_pedigree(db_path: str) -> tuple
Read pedigree tables from an EwE database.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
db_path
|
str
|
Path to the .eweaccdb database file. |
required |
Returns:
| Type | Description |
|---|---|
tuple[PedigreeConfig, DataFrame]
|
(config, group_pedigree) where: - config: PedigreeConfig with level_to_cv mapping - group_pedigree: DataFrame with columns [GroupID, VarName, CV] |
Source code in pypath/io/ewemdb.py
3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 | |
read_taxonomy ¶
read_taxonomy(db_path: str) -> TaxonomyData
Read taxonomy tables from an EwE database.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
db_path
|
str
|
Path to the .eweaccdb database file. |
required |
Returns:
| Type | Description |
|---|---|
TaxonomyData
|
Taxonomy records, group assignments, and stanza assignments. Empty defaults if tables are missing. |
Source code in pypath/io/ewemdb.py
4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 | |
read_timeseries ¶
read_timeseries(filepath: str, scenario: int = 1) -> 'EweTimeSeriesCollection'
Read time series data from an EwE database.
Reads the EcosimTimeSeries and EcosimTimeSeriesValues tables and constructs an EweTimeSeriesCollection. If tables are missing, returns an empty collection.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filepath
|
str
|
Path to the EwE database file (.eweaccdb, .ewemdb, or .accdb). |
required |
scenario
|
int
|
Scenario ID to filter by (default 1). |
1
|
Returns:
| Type | Description |
|---|---|
EweTimeSeriesCollection
|
Collection of all time series in the database. |
Source code in pypath/io/ewemdb.py
3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 | |
read_value_chain ¶
read_value_chain(db_path: str) -> ValueChainData | None
Read value chain economics tables from an EwE database.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
db_path
|
str
|
Path to the EwE database file. |
required |
Returns:
| Type | Description |
|---|---|
ValueChainData or None
|
Populated dataclass if value chain tables exist, None otherwise. |
Source code in pypath/io/ewemdb.py
4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 | |
EwE Database Export¶
Export PyPath models back to native EwE 6.6+ format. Exported databases use the correct EwE 6.6+ schema (column names, table names, integer enum fields) and load directly in the EwE desktop application.
write_ewemdb(params, path)— Auto-detects best backendwrite_ewemdb(params, path, backend="access")— Force Access (.eweaccdb)write_ewemdb(params, path, backend="csv")— Force CSV bundle (.ewecsv.zip)write_ewemdb(params, path, scenarios=[scen1])— Include Ecosim scenarioswrite_ewemdb(params, path, ecospace=ecospace)— Include Ecospace spatial datawrite_ewemdb(params, path, source_db="ref.eweaccdb")— Use existing DB as template
Backends:
| Backend | Extension | Requires | Platform |
|---|---|---|---|
access |
.eweaccdb |
pyodbc + Access ODBC driver | Windows |
csv |
.ewecsv.zip |
None | Cross-platform |
auto |
Either | Auto-detects ODBC | Any |
Example:
from pypath.io.ewe_writer import write_ewemdb
# Export Ecopath model (auto-detects backend)
write_ewemdb(params, "my_model.eweaccdb")
# With Ecosim scenarios
write_ewemdb(params, "my_model.eweaccdb", scenarios=[scenario1])
# Cross-platform CSV fallback
write_ewemdb(params, "my_model.ewecsv.zip", backend="csv")
# Round-trip: read -> modify -> write back
from pypath.io.ewemdb import read_ewemdb
params = read_ewemdb("original.eweaccdb")
# ... modify params ...
write_ewemdb(params, "modified.eweaccdb")
Specialized EwE Readers¶
Additional functions for reading specific EwE subsystem data:
read_timeseries()— time series data (biomass, catch, effort, fishing mortality)read_mediation()— mediation shapes and link assignmentsread_pedigree()— data quality pedigree valuesread_ecotracer()— contaminant tracking parametersread_fleet_dynamics()— fleet economic scenario parametersread_ecospace()— Ecospace spatial parameters (16 tables)read_mpa_config()— MPA zone configurationread_taxonomy()— taxonomy species records and group assignmentsread_value_chain()— value chain economics (21 c-prefix tables)
Biological Data (WoRMS/OBIS/FishBase)¶
Integration with marine biological databases: WoRMS for taxonomy, OBIS for occurrence records, and FishBase/SeaLifeBase for species parameters (growth, mortality, diet).
pypath.io.biodata ¶
Biodiversity data integration for PyPath.
This module provides functions to retrieve species information from global biodiversity databases and convert it to Ecopath parameters.
Data sources: - WoRMS (World Register of Marine Species): Taxonomy and nomenclature - OBIS (Ocean Biodiversity Information System): Occurrence data - FishBase: Trait data (diet, trophic level, growth parameters)
Requirements: - pyworms (pip install pyworms) - pyobis (pip install pyobis) - requests (for FishBase API)
Main workflow: Common name → WoRMS → AphiaID → Scientific name → OBIS + FishBase → RpathParams
Functions: - get_species_info(): Get comprehensive species data - batch_get_species_info(): Process multiple species in parallel - biodata_to_rpath(): Convert biodiversity data to RpathParams
Example: >>> from pypath.io.biodata import get_species_info, biodata_to_rpath >>> # Get data for a single species >>> info = get_species_info("Atlantic cod") >>> print(f"Scientific name: {info.scientific_name}") 'Gadus morhua' >>> print(f"Trophic level: {info.trophic_level}") 4.4 >>> >>> # Batch process multiple species >>> species = ["Atlantic cod", "Herring", "Sprat"] >>> df = batch_get_species_info(species) >>> >>> # Convert to Rpath parameters >>> biomass = {'Atlantic cod': 2.0, 'Herring': 5.0, 'Sprat': 8.0} >>> params = biodata_to_rpath(df, biomass_estimates=biomass) >>> from pypath.core.ecopath import rpath >>> balanced = rpath(params)
APIConnectionError ¶
Bases: BiodataError
Raised when API connection fails.
Source code in pypath/io/biodata.py
115 116 117 118 | |
AmbiguousSpeciesError ¶
Bases: BiodataError
Raised when multiple species match the query.
Source code in pypath/io/biodata.py
121 122 123 124 125 126 | |
BiodataError ¶
Bases: Exception
Base exception for biodiversity data errors.
Source code in pypath/io/biodata.py
103 104 105 106 | |
BiodiversityCache ¶
In-memory LRU cache with TTL for API responses.
Implements caching with time-to-live for each entry to reduce API load. Stores results keyed by (source, identifier) tuples.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
maxsize
|
int
|
Maximum number of cached entries |
1000
|
ttl_seconds
|
int
|
Time-to-live for cached entries in seconds |
3600
|
Examples:
>>> cache = BiodiversityCache(maxsize=1000, ttl_seconds=3600)
>>> cache.set('worms', 'Atlantic cod', {'AphiaID': 126436, ...})
>>> result = cache.get('worms', 'Atlantic cod')
>>> stats = cache.stats()
>>> print(f"Hit rate: {stats['hit_rate']:.2%}")
Source code in pypath/io/biodata.py
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 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 | |
__init__ ¶
__init__(maxsize: int = 1000, ttl_seconds: int = 3600)
Initialize cache with size limit and TTL.
Source code in pypath/io/biodata.py
235 236 237 238 239 240 241 | |
clear ¶
clear()
Clear all cached entries and reset statistics.
Source code in pypath/io/biodata.py
289 290 291 292 293 | |
get ¶
get(source: str, identifier: str) -> Optional[Any]
Get cached value if exists and not expired.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str
|
Data source ('worms', 'obis', 'fishbase') |
required |
identifier
|
str
|
Unique identifier for the cached item |
required |
Returns:
| Type | Description |
|---|---|
Any or None
|
Cached value if found and valid, None otherwise |
Source code in pypath/io/biodata.py
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 | |
set ¶
set(source: str, identifier: str, value: Any)
Cache a value with current timestamp.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str
|
Data source ('worms', 'obis', 'fishbase') |
required |
identifier
|
str
|
Unique identifier for the cached item |
required |
value
|
Any
|
Value to cache |
required |
Source code in pypath/io/biodata.py
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 | |
stats ¶
stats() -> Dict[str, Union[int, float]]
Get cache statistics.
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary with 'size', 'hits', 'misses', 'hit_rate' |
Source code in pypath/io/biodata.py
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 | |
FishBaseTraits
dataclass
¶
FishBase ecological trait data.
Attributes:
| Name | Type | Description |
|---|---|---|
species_code |
int
|
FishBase species code |
trophic_level |
(float, optional)
|
Trophic level from ecology table |
diet_items |
list of dict
|
List of prey items with {'prey': str, 'percentage': float} |
growth_params |
(dict, optional)
|
Von Bertalanffy growth parameters {'Loo': float, 'K': float, 'to': float} |
max_length |
(float, optional)
|
Maximum observed length in cm |
habitat |
(str, optional)
|
Preferred habitat type |
Source code in pypath/io/biodata.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 | |
SpeciesInfo
dataclass
¶
Complete species information from all data sources.
Attributes:
| Name | Type | Description |
|---|---|---|
common_name |
str
|
Original common/vernacular name queried |
scientific_name |
str
|
Accepted scientific name from WoRMS |
aphia_id |
int
|
WoRMS AphiaID |
authority |
str
|
Taxonomic authority |
trophic_level |
(float, optional)
|
Trophic level from FishBase |
diet_items |
list of dict, optional
|
Diet composition from FishBase |
growth_params |
(dict, optional)
|
VBGF parameters from FishBase |
max_length |
(float, optional)
|
Maximum length from FishBase |
occurrence_count |
(int, optional)
|
Number of OBIS occurrence records |
depth_range |
(tuple, optional)
|
(min_depth, max_depth) from OBIS in meters |
geographic_extent |
(dict, optional)
|
Bounding box from OBIS |
habitat |
(str, optional)
|
Habitat preference from FishBase |
Source code in pypath/io/biodata.py
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 | |
SpeciesNotFoundError ¶
Bases: BiodataError
Raised when species cannot be found in any database.
Source code in pypath/io/biodata.py
109 110 111 112 | |
auto_populate_taxonomy ¶
auto_populate_taxonomy(rpath, group_species_map: dict, proportions: dict = None) -> 'TaxonomyData'
Auto-populate taxonomy data from species names using WoRMS/FishBase.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rpath
|
Rpath
|
Balanced Ecopath model output (pypath.core.ecopath.Rpath). Used to look up group indices by name (rpath.Group). |
required |
group_species_map
|
dict[str, list[str]]
|
{group_name: [species_name, ...]}. Names can be common or scientific. |
required |
proportions
|
dict[str, list[float]]
|
{group_name: [proportion, ...]}. Must sum to 1.0 per group. If None, defaults to equal split (1/n). |
None
|
Returns:
| Type | Description |
|---|---|
TaxonomyData
|
Populated taxonomy data with species records and group assignments. |
Source code in pypath/io/biodata.py
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 | |
batch_get_species_info ¶
batch_get_species_info(common_names: List[str], include_occurrences: bool = True, include_traits: bool = True, strict: bool = False, cache: bool = True, max_workers: int = 5, timeout: int = 30) -> pd.DataFrame
Get species information for multiple species in parallel.
Uses ThreadPoolExecutor to fetch data for multiple species concurrently.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
common_names
|
list of str
|
List of common/vernacular names |
required |
include_occurrences
|
bool
|
Whether to fetch OBIS occurrence data |
True
|
include_traits
|
bool
|
Whether to fetch FishBase trait data |
True
|
strict
|
bool
|
If True, raise on any failure. If False, continue with partial data. |
False
|
cache
|
bool
|
Whether to use cached results |
True
|
max_workers
|
int
|
Maximum number of concurrent API requests |
5
|
timeout
|
int
|
API request timeout per species |
30
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with one row per species, columns for all retrieved data |
Example
from pypath.io.biodata import batch_get_species_info species = ["Atlantic cod", "Herring", "Sprat"] df = batch_get_species_info(species) print(df[['common_name', 'scientific_name', 'trophic_level']])
Source code in pypath/io/biodata.py
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 | |
biodata_to_rpath ¶
biodata_to_rpath(species_data: Union[SpeciesInfo, DataFrame], group_names: Optional[List[str]] = None, biomass_estimates: Optional[Dict[str, float]] = None, area_km2: float = 1000.0) -> RpathParams
Convert biodiversity data to RpathParams format.
Creates an Rpath parameter structure using trait data from biodiversity databases. Follows the ecobase_to_rpath() pattern.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
species_data
|
SpeciesInfo or DataFrame
|
Species information from get_species_info() or batch_get_species_info() |
required |
group_names
|
list of str
|
Custom group names. If None, uses scientific names. |
None
|
biomass_estimates
|
dict
|
Manual biomass estimates {group_name: biomass}. If not provided, uses occurrence density as proxy. |
None
|
area_km2
|
float
|
Ecosystem area in km² for biomass normalization |
1000.0
|
Returns:
| Type | Description |
|---|---|
RpathParams
|
Parameter structure ready for balancing |
Example
from pypath.io.biodata import batch_get_species_info, biodata_to_rpath df = batch_get_species_info(["Cod", "Herring", "Sprat"]) params = biodata_to_rpath( ... df, ... biomass_estimates={'Cod': 2.0, 'Herring': 5.0, 'Sprat': 8.0} ... ) from pypath.core.ecopath import rpath balanced = rpath(params)
Notes
Mapping from FishBase/OBIS to Rpath parameters: - PB: Estimated from growth parameter K (VBGF) - QB: Estimated from trophic level and P/B (Palomares & Pauly) - Biomass: From manual estimates or OBIS density - Diet: From FishBase diet composition (simplified) - TL: From FishBase ecology data
Source code in pypath/io/biodata.py
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 | |
clear_cache ¶
clear_cache()
Clear the global biodiversity data cache.
Example
from pypath.io.biodata import clear_cache clear_cache()
Source code in pypath/io/biodata.py
1278 1279 1280 1281 1282 1283 1284 1285 1286 | |
get_cache_stats ¶
get_cache_stats() -> Dict[str, Union[int, float]]
Get statistics about the global cache.
Returns:
| Type | Description |
|---|---|
dict
|
Cache statistics including size, hits, misses, hit_rate |
Example
from pypath.io.biodata import get_cache_stats stats = get_cache_stats() print(f"Cache hit rate: {stats['hit_rate']:.2%}")
Source code in pypath/io/biodata.py
1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 | |
get_species_info ¶
get_species_info(common_name: str, include_occurrences: bool = True, include_traits: bool = True, strict: bool = False, cache: bool = True, timeout: int = 30) -> SpeciesInfo
Get comprehensive species information from common name.
Implements the workflow: 1. Search WoRMS vernacular database for common name 2. Get AphiaID and accepted scientific name 3. Query OBIS for occurrence data (if include_occurrences=True) 4. Query FishBase for trait data (if include_traits=True)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
common_name
|
str
|
Common/vernacular name of species (e.g., "Atlantic cod") |
required |
include_occurrences
|
bool
|
Whether to fetch OBIS occurrence data |
True
|
include_traits
|
bool
|
Whether to fetch FishBase trait data |
True
|
strict
|
bool
|
If True, raise errors on any failure. If False, return partial data. |
False
|
cache
|
bool
|
Whether to use cached results |
True
|
timeout
|
int
|
API request timeout in seconds |
30
|
Returns:
| Type | Description |
|---|---|
SpeciesInfo
|
Dataclass containing all retrieved information |
Raises:
| Type | Description |
|---|---|
SpeciesNotFoundError
|
If species not found in WoRMS (only in strict mode) |
AmbiguousSpeciesError
|
If multiple species match and auto-selection fails |
APIConnectionError
|
If API connection fails (only in strict mode) |
Example
from pypath.io.biodata import get_species_info info = get_species_info("Atlantic cod") print(info.scientific_name) 'Gadus morhua' print(info.trophic_level) 4.4 print(f"Found {info.occurrence_count} OBIS records")
Source code in pypath/io/biodata.py
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 | |
Marine Environmental Data (EMODnet)¶
Download and process marine environmental layers (bathymetry, temperature, salinity, substrate) from the EMODnet Web Coverage Service for use as Ecospace habitat and environmental inputs.
pypath.io.marine_data ¶
Marine data clients for EMODnet habitats, bathymetry, and salinity.
Provides: - MarineDataCache: Local file cache for downloaded marine data - EMODnetHabitatsClient: WFS client for EUSeaMap seabed habitats - EMODnetBathymetryClient: WCS client for bathymetry depth grids - SalinityLoader: Load salinity from user-provided files - HabitatPreferenceBuilder: Semi-automatic habitat preference assignment
EMODnetBathymetryClient ¶
WCS client for EMODnet bathymetry depth data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cache
|
MarineDataCache
|
Cache instance for storing downloaded data. |
required |
Source code in pypath/io/marine_data.py
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 | |
fetch_depth ¶
fetch_depth(bbox: tuple[float, float, float, float], resolution: float = 0.002)
Fetch depth raster for a bounding box.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bbox
|
tuple
|
(min_lon, min_lat, max_lon, max_lat) in WGS84. |
required |
resolution
|
float
|
Grid resolution in degrees (default ~200m). |
0.002
|
Returns:
| Type | Description |
|---|---|
tuple of (np.ndarray, tuple)
|
(raster [rows, cols], transform tuple). |
Source code in pypath/io/marine_data.py
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 | |
sample_to_grid ¶
sample_to_grid(raster: ndarray, transform: tuple, grid: 'gpd.GeoDataFrame') -> np.ndarray
Average raster values within each grid patch.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
raster
|
ndarray
|
Depth raster [rows, cols]. |
required |
transform
|
tuple
|
(x_origin, pixel_width, x_skew, y_origin, y_skew, pixel_height). |
required |
grid
|
EcospaceGrid
|
Target spatial grid. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Mean depth per patch [n_patches]. |
Source code in pypath/io/marine_data.py
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 | |
EMODnetHabitatsClient ¶
WFS client for EMODnet EUSeaMap seabed habitats.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cache
|
MarineDataCache
|
Cache instance for storing downloaded data. |
required |
Source code in pypath/io/marine_data.py
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 | |
fetch_euseamap ¶
fetch_euseamap(bbox: tuple[float, float, float, float], eunis_level: int = 3)
Fetch EUSeaMap habitat polygons within a bounding box.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bbox
|
tuple
|
(min_lon, min_lat, max_lon, max_lat) in WGS84. |
required |
eunis_level
|
int
|
EUNIS classification level (default 3). |
3
|
Returns:
| Type | Description |
|---|---|
GeoDataFrame
|
Habitat polygons with EUNIS classification columns. |
Source code in pypath/io/marine_data.py
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 | |
get_habitat_types
staticmethod
¶
get_habitat_types(gdf: 'gpd.GeoDataFrame', level: int = 3) -> list
Extract unique EUNIS codes truncated to requested level.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gdf
|
GeoDataFrame
|
Habitat polygons with 'EUNIScomb' column. |
required |
level
|
int
|
EUNIS hierarchy level (e.g., 3 means 'A5.2'). |
3
|
Returns:
| Type | Description |
|---|---|
list of str
|
Sorted unique EUNIS codes at the requested level. |
Source code in pypath/io/marine_data.py
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 | |
rasterize_habitats ¶
rasterize_habitats(gdf: 'gpd.GeoDataFrame', grid: 'gpd.GeoDataFrame') -> np.ndarray
Assign majority EUNIS habitat class to each grid patch.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gdf
|
GeoDataFrame
|
Habitat polygons with 'EUNIScomb' column. |
required |
grid
|
EcospaceGrid
|
Target spatial grid. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
EUNIS code per patch [n_patches], dtype=object. |
Source code in pypath/io/marine_data.py
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 | |
HabitatPreferenceBuilder ¶
Build habitat preference matrices for ecospace models.
Source code in pypath/io/marine_data.py
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 | |
apply_preset ¶
apply_preset(n_groups: int, habitat_types: list, preset: str) -> np.ndarray
Apply a preset preference pattern.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_groups
|
int
|
Number of species groups. |
required |
habitat_types
|
list of str
|
Unique habitat type codes. |
required |
preset
|
str
|
One of 'pelagic', 'demersal', 'benthic'. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Preference matrix [n_groups, n_habitat_types], values 0-1. |
Source code in pypath/io/marine_data.py
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 | |
build_preference_matrix
staticmethod
¶
build_preference_matrix(prefs_by_type: ndarray, habitat_types: list, habitat_map: ndarray, grid) -> np.ndarray
Convert habitat-type preferences to per-patch preferences.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prefs_by_type
|
ndarray
|
Preference per habitat type [n_groups, n_habitat_types]. |
required |
habitat_types
|
list of str
|
Ordered habitat type codes matching prefs_by_type columns. |
required |
habitat_map
|
ndarray
|
EUNIS code per patch [n_patches], dtype=object. |
required |
grid
|
EcospaceGrid
|
Target spatial grid. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Preference matrix [n_groups, n_patches]. |
Source code in pypath/io/marine_data.py
504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 | |
suggest_preferences ¶
suggest_preferences(group_names: list, habitat_types: list, depth_per_patch: Optional[ndarray] = None)
Auto-suggest preferences using biodata lookups.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
group_names
|
list of str
|
Species/group names from the Ecopath model. |
required |
habitat_types
|
list of str
|
Unique EUNIS habitat type codes. |
required |
depth_per_patch
|
ndarray
|
Depth values per patch for depth-based suggestions. |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Suggested preference matrix [n_groups, n_habitat_types]. |
Source code in pypath/io/marine_data.py
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 | |
MarineDataCache ¶
Local file cache for marine data downloads.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cache_dir
|
str or Path
|
Directory for cached files. Created if it doesn't exist. |
None
|
Source code in pypath/io/marine_data.py
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | |
cache_key
staticmethod
¶
cache_key(bbox: tuple[float, float, float, float], layer: str, **kwargs) -> str
Generate deterministic cache key from parameters.
Source code in pypath/io/marine_data.py
59 60 61 62 63 64 | |
get ¶
get(key: str) -> Optional[bytes]
Retrieve cached data by key. Returns None on cache miss.
Source code in pypath/io/marine_data.py
44 45 46 47 48 49 50 | |
put ¶
put(key: str, data: bytes) -> None
Store data in cache.
Source code in pypath/io/marine_data.py
52 53 54 55 56 57 | |
SalinityLoader ¶
Load salinity data from user-provided files.
Source code in pypath/io/marine_data.py
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 | |
load_from_csv
staticmethod
¶
load_from_csv(filepath: str, grid) -> 'EnvironmentalLayer'
Load salinity from CSV with lon, lat, salinity columns.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filepath
|
str
|
Path to CSV file with columns: lon, lat, salinity. |
required |
grid
|
EcospaceGrid
|
Target spatial grid for nearest-neighbor sampling. |
required |
Returns:
| Type | Description |
|---|---|
EnvironmentalLayer
|
Salinity values sampled onto the grid patches. |
Source code in pypath/io/marine_data.py
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 | |
load_from_netcdf
staticmethod
¶
load_from_netcdf(filepath: str, grid, variable: str = 'so') -> 'EnvironmentalLayer'
Load salinity from NetCDF.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filepath
|
str
|
Path to NetCDF file. |
required |
grid
|
EcospaceGrid
|
Target spatial grid. |
required |
variable
|
str
|
NetCDF variable name for salinity (default: 'so'). |
'so'
|
Returns:
| Type | Description |
|---|---|
EnvironmentalLayer
|
Salinity values sampled onto the grid patches. |
Source code in pypath/io/marine_data.py
355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 | |
Utilities¶
Shared I/O helper functions: CSV reading, unit conversions, and data validation.
pypath.io.utils ¶
Shared utilities for PyPath I/O modules.
This module provides common helper functions used across multiple I/O modules (biodata, ecobase, ewemdb) to avoid code duplication and ensure consistency.
Functions:
| Name | Description |
|---|---|
- safe_float |
|
- fetch_url |
|
estimate_pb_from_growth ¶
estimate_pb_from_growth(k: float, max_age: Optional[float] = None) -> float
Estimate P/B ratio from von Bertalanffy growth parameter K.
Uses the empirical relationship that P/B is approximately proportional to the growth coefficient K from the von Bertalanffy growth function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
k
|
float
|
Von Bertalanffy growth coefficient K (1/year) |
required |
max_age
|
float
|
Maximum age in years. If provided, uses Z/K ratio method. If None, uses simple approximation P/B ≈ 2.5 * K. |
None
|
Returns:
| Type | Description |
|---|---|
float
|
Estimated P/B ratio (1/year) |
Notes
Based on Brey (2001) and Pauly (1980) empirical relationships between growth parameters and production rates.
References
- Brey, T. (2001). Population dynamics in benthic invertebrates. A virtual handbook. http://www.thomas-brey.de/science/virtualhandbook
- Pauly, D. (1980). On the interrelationships between natural mortality, growth parameters, and mean environmental temperature in 175 fish stocks. ICES Journal of Marine Science, 39(2), 175-192.
Source code in pypath/io/utils.py
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 | |
estimate_qb_from_tl_pb ¶
estimate_qb_from_tl_pb(trophic_level: float, pb: float) -> float
Estimate Q/B ratio from trophic level and P/B ratio.
Uses the empirical relationship from Palomares & Pauly (1998) relating consumption rates to trophic level and production rates.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
trophic_level
|
float
|
Trophic level (typically 2.0 to 5.0 for consumers) |
required |
pb
|
float
|
Production/Biomass ratio (1/year) |
required |
Returns:
| Type | Description |
|---|---|
float
|
Estimated Q/B ratio (1/year) |
Notes
The relationship assumes: - Higher trophic levels have lower assimilation efficiency - Q/B scales with P/B but modified by trophic efficiency - Typical P/Q ratios: 0.1-0.3 for fish, 0.2-0.4 for invertebrates
References
Palomares, M.L.D. & Pauly, D. (1998). Predicting food consumption of fish populations as functions of mortality, food type, morphometrics, temperature and salinity. Marine and Freshwater Research, 49, 447-453.
Source code in pypath/io/utils.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 | |
fetch_url ¶
fetch_url(url: str, params: Optional[Dict] = None, timeout: int = 30, parse_json: bool = True) -> Union[str, Dict]
Fetch content from URL with automatic fallback to urllib.
Attempts to use the requests library if available, falling back to urllib.request if not. Optionally parses JSON responses.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
URL to fetch |
required |
params
|
dict
|
Query parameters to append to URL |
None
|
timeout
|
int
|
Request timeout in seconds |
30
|
parse_json
|
bool
|
If True, attempt to parse response as JSON. If parsing fails or parse_json is False, return raw text. |
True
|
Returns:
| Type | Description |
|---|---|
str or dict
|
Response content as dictionary (if JSON parsing succeeds) or string (if JSON parsing fails or is disabled) |
Raises:
| Type | Description |
|---|---|
HTTPError
|
If request fails (non-200 status code) |
URLError
|
If connection fails |
Examples:
>>> data = fetch_url("https://api.example.com/data")
>>> text = fetch_url("https://example.com/page", parse_json=False)
>>> filtered = fetch_url("https://api.example.com/search",
... params={"q": "marine species"})
Notes
- Prefers requests library for better error handling and features
- Automatically falls back to urllib if requests is not installed
- JSON parsing is attempted but never raises an error if it fails
Source code in pypath/io/utils.py
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 | |
safe_float ¶
safe_float(value: Any, default: Optional[float] = None) -> Optional[float]
Safely convert a value to float, handling booleans and strings.
This function handles various input types and edge cases when converting to float, including boolean values, empty strings, and common text representations of missing data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
Value to convert to float |
required |
default
|
float or None
|
Default value to return if conversion fails. If None (default), returns None on conversion failure. |
None
|
Returns:
| Type | Description |
|---|---|
float or None
|
Converted float value, or default/None if conversion fails |
Examples:
>>> safe_float(42)
42.0
>>> safe_float("3.14")
3.14
>>> safe_float("NA")
None
>>> safe_float("invalid", default=0.0)
0.0
>>> safe_float(True) # Booleans converted to numeric
1.0
>>> safe_float(False)
0.0
Notes
- Boolean values (True/False) are converted to 1.0/0.0
- Empty strings and common missing data indicators ('NA', 'nan', 'none', etc.) return None
- Case-insensitive string matching for missing data indicators
Source code in pypath/io/utils.py
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 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 | |