Core Module¶
core ¶
Core module for effective precipitation calculations.
This module provides the main :class:EffectivePrecipitation class for calculating
effective precipitation from climate datasets available on Google Earth Engine (GEE)
or from precipitation rasters/NetCDF files that already exist on disk.
Two precipitation sources are supported:
- Google Earth Engine (default) - pass
asset_idandprecip_band. - Local files - pass
local_precippointing at a directory of monthly rasters, a NetCDF file, or a glob string. See :mod:pycropwat.local.
With local precipitation, available water capacity (AWC), reference evapotranspiration
(ETo) and GEE FeatureCollection geometries are still downloaded from Earth
Engine, so the usda_scs, ensemble and suet methods continue to require GEE
access. The precipitation-only methods (cropwat, fao_aglw, fixed_percentage,
dependable_rainfall, farmwest) need no Earth Engine at all - Earth Engine is
never initialised for them, so those runs work completely offline. The pcml method
is a pre-computed GEE product and is therefore incompatible with local precipitation.
The module supports multiple effective precipitation methods:
- Ensemble: Mean of 6 methods (default)
- CROPWAT: FAO CROPWAT method
- FAO/AGLW: FAO Dependable Rainfall (80% exceedance)
- Fixed Percentage: Simple fixed percentage method
- Dependable Rainfall: FAO Dependable Rainfall method
- FarmWest: FarmWest method
- USDA-SCS: Soil moisture depletion method (requires AWC and ETo)
- TAGEM-SuET: Turkish irrigation method (requires ETo)
- PCML: Physics-Constrained ML for Western U.S. (pre-computed GEE asset)
Example
from pycropwat import EffectivePrecipitation
ep = EffectivePrecipitation(
asset_id='ECMWF/ERA5_LAND/MONTHLY_AGGR',
precip_band='total_precipitation_sum',
geometry_path='study_area.geojson',
start_year=2015,
end_year=2020,
precip_scale_factor=1000,
method='ensemble'
)
results = ep.process(output_dir='./output', n_workers=4)
Local precipitation input (no Earth Engine required):
See Also
pycropwat.local : Readers for local precipitation rasters and NetCDF files. pycropwat.methods : Individual effective precipitation calculation functions. pycropwat.analysis : Post-processing and analysis tools. pycropwat.utils : Utility functions for GEE and file operations.
EffectivePrecipitation ¶
EffectivePrecipitation(asset_id: Optional[str] = None, precip_band: Optional[str] = None, geometry_path: Optional[Union[str, Path]] = None, start_year: int = None, end_year: int = None, scale: Optional[float] = None, precip_scale_factor: float = 1.0, gee_project: Optional[str] = None, gee_geometry_asset: Optional[str] = None, method: PeffMethod = 'ensemble', method_params: Optional[dict] = None, local_precip: Optional[Union[str, Path]] = None, local_precip_pattern: str = '*.tif', local_precip_variable: Optional[str] = None, local_precip_nodata: Optional[float] = None, local_precip_crs: Optional[str] = None, local_precip_date_regex: Optional[str] = None, clip_to_geometry: bool = True)
Calculate effective precipitation from GEE or local climate data.
Supports multiple effective precipitation calculation methods including CROPWAT, FAO/AGLW, Fixed Percentage, Dependable Rainfall, FarmWest, and USDA-SCS (which requires AWC and ETo data).
Precipitation is downloaded from Google Earth Engine by default. Pass
local_precip to read monthly precipitation from GeoTIFFs or NetCDF files
on disk instead. AWC, ETo and GEE FeatureCollection geometries are still
read from Earth Engine in that case, so usda_scs, ensemble and suet
still need GEE credentials. Precipitation-only methods (cropwat,
fao_aglw, fixed_percentage, dependable_rainfall, farmwest)
combined with local files need no Earth Engine at all - Earth Engine is never
initialised and the run works offline.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
asset_id
|
str
|
GEE ImageCollection asset ID for precipitation data. Required unless
|
None
|
precip_band
|
str
|
Name of the precipitation band in the asset. Required unless
|
None
|
geometry_path
|
str, Path, or None
|
Path to shapefile or GeoJSON file defining the region of interest.
Can also be a GEE FeatureCollection asset ID. Set to None if using
gee_geometry_asset instead. With |
None
|
start_year
|
int
|
Start year for processing (inclusive). Optional with |
None
|
end_year
|
int
|
End year for processing (inclusive). Optional with |
None
|
scale
|
float
|
Output resolution in meters. If None (default), uses native resolution of the dataset. |
None
|
precip_scale_factor
|
float
|
Factor to convert precipitation to mm. Default is 1.0. Common values: ERA5-Land (m to mm) = 1000, TerraClimate = 1.0, GridMET = 1.0. Also applied to local precipitation files. |
1.0
|
gee_project
|
str
|
GEE project ID for authentication. Required for cloud-based GEE access. |
None
|
gee_geometry_asset
|
str
|
GEE FeatureCollection asset ID for the region of interest. Takes precedence over geometry_path if both are provided. |
None
|
method
|
str
|
Effective precipitation calculation method. Default is 'ensemble'. Options:
|
'ensemble'
|
method_params
|
dict
|
Additional parameters for the selected method: For For For |
None
|
local_precip
|
str or Path
|
Local precipitation data to use instead of downloading precipitation from GEE. Accepts:
Files must contain monthly totals (converted to mm with
|
None
|
local_precip_pattern
|
str
|
Glob used when |
'*.tif'
|
local_precip_variable
|
str
|
NetCDF variable holding precipitation. Auto-detected when None (default). |
None
|
local_precip_nodata
|
float
|
Additional nodata sentinel, applied on top of the value stored in the file
metadata (e.g. |
None
|
local_precip_crs
|
str
|
CRS to assign when the local files carry none, or to override the stored
one, e.g. |
None
|
local_precip_date_regex
|
str
|
Regular expression with named groups |
None
|
clip_to_geometry
|
bool
|
Clip local precipitation rasters to |
True
|
Attributes:
| Name | Type | Description |
|---|---|---|
geometry |
Geometry or None
|
The loaded geometry for the region of interest. |
collection |
ImageCollection or None
|
The filtered and scaled precipitation image collection. |
bounds |
list
|
Bounding box coordinates of the geometry (lon/lat ring). |
Examples:
Basic usage with Ensemble method (default):
from pycropwat import EffectivePrecipitation
ep = EffectivePrecipitation(
asset_id='ECMWF/ERA5_LAND/MONTHLY_AGGR',
precip_band='total_precipitation_sum',
geometry_path='roi.geojson',
start_year=2015,
end_year=2020,
precip_scale_factor=1000
)
ep.process(output_dir='./output', n_workers=4)
Using GEE FeatureCollection asset:
ep = EffectivePrecipitation(
asset_id='ECMWF/ERA5_LAND/MONTHLY_AGGR',
precip_band='total_precipitation_sum',
gee_geometry_asset='projects/my-project/assets/study_area',
start_year=2015,
end_year=2020,
precip_scale_factor=1000,
gee_project='my-gee-project'
)
Using FAO/AGLW method:
ep = EffectivePrecipitation(
asset_id='IDAHO_EPSCOR/TERRACLIMATE',
precip_band='pr',
geometry_path='study_area.geojson',
start_year=2000,
end_year=2020,
method='fao_aglw'
)
Using fixed percentage method (80%):
ep = EffectivePrecipitation(
asset_id='IDAHO_EPSCOR/GRIDMET',
precip_band='pr',
geometry_path='farm.geojson',
start_year=2010,
end_year=2020,
method='fixed_percentage',
method_params={'percentage': 0.8}
)
Using USDA-SCS method with AWC and ETo data:
ep = EffectivePrecipitation(
asset_id='ECMWF/ERA5_LAND/MONTHLY_AGGR',
precip_band='total_precipitation_sum',
geometry_path='arizona.geojson',
start_year=2015,
end_year=2020,
precip_scale_factor=1000,
method='usda_scs',
method_params={
'awc_asset': 'projects/my-project/assets/soil_awc',
'awc_band': 'AWC',
'eto_asset': 'IDAHO_EPSCOR/GRIDMET',
'eto_band': 'eto',
'eto_is_daily': True,
'rooting_depth': 1.0
}
)
Local precipitation input (no Earth Engine required):
ep = EffectivePrecipitation(
local_precip='../pyCropWat_Data/Precip',
local_precip_pattern='Precip_*.tif',
local_precip_nodata=-9999,
method='cropwat'
)
# start_year/end_year inferred from the files when omitted
ep.process_sequential(output_dir='./output', months=[7, 8])
Local precipitation with AWC and ETo still coming from Earth Engine:
ep = EffectivePrecipitation(
local_precip='../pyCropWat_Data/Precip',
local_precip_pattern='Precip_*.tif',
local_precip_nodata=-9999,
geometry_path='basin.geojson',
start_year=2005,
end_year=2010,
method='ensemble',
gee_project='my-gee-project',
method_params={
'awc_asset': 'projects/sat-io/open-datasets/FAO/HWSD_V2_SMU',
'awc_band': 'AWC',
'awc_scale_factor': 0.001,
'eto_asset': 'IDAHO_EPSCOR/TERRACLIMATE',
'eto_band': 'pet',
'eto_scale_factor': 0.1,
'eto_is_daily': False,
'rooting_depth': 2.0,
'mad_factor': 1.0
}
)
ep.process(output_dir='./output', n_workers=4)
Local NetCDF input with an explicit variable and date pattern:
ep = EffectivePrecipitation(
local_precip='./wrf_precip.nc',
local_precip_variable='RAINNC',
local_precip_crs='EPSG:4326',
method='fao_aglw'
)
See Also
pycropwat.local : Readers for local precipitation rasters and NetCDF files. pycropwat.methods : Individual effective precipitation calculation functions. pycropwat.analysis : Post-processing and analysis tools.
Source code in pycropwat/core.py
654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 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 | |
__getstate__ ¶
Return picklable state, so instances survive Dask/distributed.
The NetCDF read lock and the open local precipitation source are dropped:
a lock and an open file handle cannot be pickled. Both are recreated on
demand by :meth:_get_local_lock and :attr:_local_source.
Returns:
| Type | Description |
|---|---|
dict
|
Instance state without the unpicklable entries. |
Source code in pycropwat/core.py
__setstate__ ¶
Restore state, leaving the lock and local source to be rebuilt lazily.
Earth Engine is re-initialised here when the restored instance needs it
(:meth:_ensure_gee), because ee state is process-local and does not
travel with the pickle: without this a Dask worker process would fail
every ee call with "Earth Engine client library not initialized". A
run that needs no Earth Engine initialises nothing, and a process that is
already initialised pays only a set lookup.
A failure here is logged rather than raised: unpickling must not fail, and
the first real Earth Engine call retries and raises
:class:_GeeUnavailableError so the failure is reported against the task
that needed it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
dict
|
State produced by :meth: |
required |
Source code in pycropwat/core.py
cropwat_effective_precip
staticmethod
¶
Calculate CROPWAT effective precipitation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pr
|
ndarray
|
Precipitation in mm. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Effective precipitation in mm. |
Source code in pycropwat/core.py
process ¶
process(output_dir: Union[str, Path], n_workers: int = 4, months: Optional[List[int]] = None, input_dir: Optional[Union[str, Path]] = None, save_inputs: bool = False) -> List[Tuple[Optional[Path], Optional[Path]]]
Process all months and save effective precipitation rasters.
Downloads precipitation data from Google Earth Engine - or reads it from
the local files given by local_precip - calculates effective
precipitation using the configured method, and saves results as GeoTIFF
files. Uses Dask for parallel processing of multiple months.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_dir
|
str or Path
|
Directory to save output rasters. Will be created if it doesn't exist. |
required |
n_workers
|
int
|
Number of parallel workers for Dask. Default is 4. Set to 1 for sequential processing. |
4
|
months
|
list of int
|
List of months to process (1-12). If None, processes all months in the date range. Useful for seasonal analyses. |
None
|
input_dir
|
str or Path
|
Directory to save downloaded input data (precipitation, AWC, ETo).
If None and save_inputs is True, uses |
None
|
save_inputs
|
bool
|
Whether to save downloaded input data as GeoTIFF files. Default is False. Useful for debugging or further analysis. |
False
|
Returns:
| Type | Description |
|---|---|
list of tuple
|
List of tuples containing paths to saved files:
|
Notes
Output files are named:
effective_precip_YYYY_MM.tif- Effective precipitation in mmeffective_precip_fraction_YYYY_MM.tif- Effective/total ratio (non-PCML methods)effective_precip_fraction_YYYY.tif- Annual (water year) fraction (PCML method only)
For the USDA-SCS method, AWC and ETo data are automatically downloaded and cached for efficiency. This is true for local precipitation too: AWC and ETo always come from Earth Engine.
With local precipitation, months that have no file are skipped with a warning instead of being reported as failures, and nodata pixels are written as NaN in both outputs.
Examples:
Process all months in parallel:
Process only summer months:
Save input data for debugging:
See Also
process_sequential: Sequential processing for debugging.
Source code in pycropwat/core.py
2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 | |
process_sequential ¶
process_sequential(output_dir: Union[str, Path], months: Optional[List[int]] = None, input_dir: Optional[Union[str, Path]] = None, save_inputs: bool = False) -> List[Tuple[Optional[Path], Optional[Path]]]
Process all months sequentially (useful for debugging).
Same as :meth:process but without parallel processing. Useful for
debugging issues, testing on small datasets, or when GEE rate limits
are a concern. Also the simplest way to run a local precipitation
workflow with no Earth Engine involvement.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_dir
|
str or Path
|
Directory to save output rasters. Will be created if it doesn't exist. |
required |
months
|
list of int
|
List of months to process (1-12). If None, processes all months in the date range. |
None
|
input_dir
|
str or Path
|
Directory to save downloaded input data (precipitation, AWC, ETo).
If None and save_inputs is True, uses |
None
|
save_inputs
|
bool
|
Whether to save downloaded input data. Default is False. |
False
|
Returns:
| Type | Description |
|---|---|
list of tuple
|
List of tuples containing paths to saved files:
|
Examples:
Debug a single month:
ep = EffectivePrecipitation(...)
results = ep.process_sequential(
output_dir='./output',
months=[1] # Process only January
)
See Also
process: Parallel processing method (recommended for production).
Source code in pycropwat/core.py
2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 | |