I/O API Reference¶
EcoBase¶
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
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 | |
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
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 | |
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 | |
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
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 | |
EwE Database (.eweaccdb)¶
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)
EwEDatabaseError ¶
Bases: Exception
Exception for EwE database errors.
Source code in pypath/io/ewemdb.py
110 111 112 113 | |
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
2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 | |
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
2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 | |
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
2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 | |
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
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 | |
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
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 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 | |
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
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 | |
Biological Data (WoRMS/OBIS/FishBase)¶
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
112 113 114 115 | |
AmbiguousSpeciesError ¶
Bases: BiodataError
Raised when multiple species match the query.
Source code in pypath/io/biodata.py
118 119 120 121 122 123 | |
BiodataError ¶
Bases: Exception
Base exception for biodiversity data errors.
Source code in pypath/io/biodata.py
100 101 102 103 | |
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
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 | |
__init__ ¶
__init__(maxsize: int = 1000, ttl_seconds: int = 3600)
Initialize cache with size limit and TTL.
Source code in pypath/io/biodata.py
232 233 234 235 236 237 238 | |
clear ¶
clear()
Clear all cached entries and reset statistics.
Source code in pypath/io/biodata.py
286 287 288 289 290 | |
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
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 | |
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
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 | |
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
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 | |
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
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 | |
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
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 | |
SpeciesNotFoundError ¶
Bases: BiodataError
Raised when species cannot be found in any database.
Source code in pypath/io/biodata.py
106 107 108 109 | |
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
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 | |
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
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 | |
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
1275 1276 1277 1278 1279 1280 1281 1282 1283 | |
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
1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 | |
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
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 | |
Marine Environmental Data (EMODnet)¶
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 | |
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
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 | |
Utilities¶
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 | |