pyfao56v2 0.5.6__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of pyfao56v2 might be problematic. Click here for more details.
- pyfao56v2/__init__.py +46 -0
- pyfao56v2/autoirrigate.py +248 -0
- pyfao56v2/forecast.py +186 -0
- pyfao56v2/irrigation.py +118 -0
- pyfao56v2/main.py +442 -0
- pyfao56v2/model.py +789 -0
- pyfao56v2/parameters.py +282 -0
- pyfao56v2/refet.py +386 -0
- pyfao56v2/tools/__init__.py +34 -0
- pyfao56v2/tools/euptfv2/FC_EUHYDI/FC_PTF01.rdata +0 -0
- pyfao56v2/tools/euptfv2/FC_EUHYDI/FC_PTF02.rdata +0 -0
- pyfao56v2/tools/euptfv2/FC_EUHYDI/FC_PTF03.rdata +0 -0
- pyfao56v2/tools/euptfv2/FC_EUHYDI/FC_PTF04.rdata +0 -0
- pyfao56v2/tools/euptfv2/FC_EUHYDI/FC_PTF06.rdata +0 -0
- pyfao56v2/tools/euptfv2/FC_EUHYDI/FC_PTF07.rdata +0 -0
- pyfao56v2/tools/euptfv2/FC_EUHYDI/FC_PTF08.rdata +0 -0
- pyfao56v2/tools/euptfv2/FC_EUHYDI/FC_PTF09.rdata +0 -0
- pyfao56v2/tools/euptfv2/FC_EUHYDI/FC_PTF11.rdata +0 -0
- pyfao56v2/tools/euptfv2/FC_EUHYDI/FC_PTF14.rdata +0 -0
- pyfao56v2/tools/euptfv2/WP_EUHYDI/WP_PTF01.rdata +0 -0
- pyfao56v2/tools/euptfv2/WP_EUHYDI/WP_PTF02.rdata +0 -0
- pyfao56v2/tools/euptfv2/WP_EUHYDI/WP_PTF05.rdata +0 -0
- pyfao56v2/tools/euptfv2/WP_EUHYDI/WP_PTF07.rdata +0 -0
- pyfao56v2/tools/euptfv2/WP_EUHYDI/WP_PTF08.rdata +0 -0
- pyfao56v2/tools/euptfv2/WP_EUHYDI/WP_PTF09.rdata +0 -0
- pyfao56v2/tools/euptfv2/WP_EUHYDI/WP_PTF17.rdata +0 -0
- pyfao56v2/tools/euptfv2/list_of_final_PTFs.csv +33 -0
- pyfao56v2/tools/euptfv2.py +136 -0
- pyfao56v2/tools/lut.py +14 -0
- pyfao56v2/tools/luts/crop.csv +10 -0
- pyfao56v2/tools/luts/irrigation.csv +8 -0
- pyfao56v2/tools/luts/soil.csv +10 -0
- pyfao56v2/tools/misc.py +76 -0
- pyfao56v2/tools/pheno.py +91 -0
- pyfao56v2/tools/rosetta.py +97 -0
- pyfao56v2/tools/van_genuchten.py +23 -0
- pyfao56v2/tools/visualization.py +452 -0
- pyfao56v2/weather.py +204 -0
- pyfao56v2-0.5.6.dist-info/METADATA +66 -0
- pyfao56v2-0.5.6.dist-info/RECORD +42 -0
- pyfao56v2-0.5.6.dist-info/WHEEL +4 -0
- pyfao56v2-0.5.6.dist-info/licenses/LICENSE +21 -0
pyfao56v2/__init__.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"""
|
|
2
|
+
########################################################################
|
|
3
|
+
The pyfao56v2 Python package builds on top of the pyfao56 library mantained by USDA-ARS.
|
|
4
|
+
|
|
5
|
+
- pyfao56 facilitates FAO-56 computations of daily soil
|
|
6
|
+
water balance using the dual crop coefficient method to estimate crop
|
|
7
|
+
evapotranspiration (ET).
|
|
8
|
+
The FAO-56 method is described in the following documentation:
|
|
9
|
+
Allen, R. G., Pereira, L. S., Raes, D., Smith, M., 1998. FAO Irrigation
|
|
10
|
+
and Drainage Paper No. 56. Crop Evapotranspiration: Guidelines for
|
|
11
|
+
Computing Crop Water Requirements. Food and Agriculture Organization of
|
|
12
|
+
the United Nations, Rome Italy.
|
|
13
|
+
http://www.fao.org/3/x0490e/x0490e00.htm
|
|
14
|
+
Reference ET is computed using the ASCE Standardized Reference ET
|
|
15
|
+
Equation, which is described in the following documentation:
|
|
16
|
+
ASCE Task Committee on Standardization of Reference Evapotranspiration
|
|
17
|
+
(Walter, I. A., Allen, R. G., Elliott, R., Itenfisu, D., Brown, P.,
|
|
18
|
+
Jensen, M. E.,Mecham, B., Howell, T. A., Snyder, R., Eching, S.,
|
|
19
|
+
Spofford, T., Hattendorf, M., Martin, D., Cuenca, R. H., Wright, J. L.)
|
|
20
|
+
, 2005. The ASCE Standardized Reference Evapotranspiration Equation.
|
|
21
|
+
American Society of Civil Engineers, Reston, VA.
|
|
22
|
+
https://ascelibrary.org/doi/book/10.1061/9780784408056
|
|
23
|
+
|
|
24
|
+
- pyfao56v2 extends the pyfao56 library by:
|
|
25
|
+
- working with "full" dates (YYYY-MM-DD) instead of day-of-year dates
|
|
26
|
+
(YYYY-DOY)
|
|
27
|
+
- allowing the input of custom Kcb time series, letting go of the
|
|
28
|
+
trapezoidal Kcb curve in the original FAO-56 method
|
|
29
|
+
- introducing lookup tables for crop, soil, and irrigation parameters
|
|
30
|
+
- other improvements yet to be documented...
|
|
31
|
+
########################################################################
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
# pyfao56v2/
|
|
35
|
+
from .main import simulate, WaterBalance
|
|
36
|
+
from .model import Model
|
|
37
|
+
from .parameters import Parameters
|
|
38
|
+
from .weather import Weather
|
|
39
|
+
from .irrigation import Irrigation
|
|
40
|
+
from .autoirrigate import AutoIrrigate
|
|
41
|
+
from .forecast import Forecast
|
|
42
|
+
#from .soil_profile import SoilProfile
|
|
43
|
+
#from .update import Update
|
|
44
|
+
|
|
45
|
+
# pyfao56v2/tools/
|
|
46
|
+
from .tools import Visualization
|
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
"""
|
|
2
|
+
########################################################################
|
|
3
|
+
The autoirrigate.py module contains the AutoIrrigate class, which
|
|
4
|
+
provides I/O tools for defining conditions for scheduling irrigation
|
|
5
|
+
automatically in pyfao56.
|
|
6
|
+
########################################################################
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import pandas as pd
|
|
10
|
+
|
|
11
|
+
class AutoIrrigate:
|
|
12
|
+
"""A class for managing multiple sets of autoirrigation conditions
|
|
13
|
+
|
|
14
|
+
Attributes
|
|
15
|
+
----------
|
|
16
|
+
data : DataFrame
|
|
17
|
+
AutoIrrigate data with mixed data types
|
|
18
|
+
* index - counter as int
|
|
19
|
+
* columns - ['start','end','alre','idow','fpdep','fpday','fpact',
|
|
20
|
+
'mad','madDr','ksc','dsli','dsle','evnt','icon',
|
|
21
|
+
'itdr','itfdr','ietrd','ietri','ietre','ettyp',
|
|
22
|
+
'iper','ieff','imin','imax','fw']
|
|
23
|
+
|
|
24
|
+
Variables to determine if autoirrigation occurs or not:
|
|
25
|
+
* * start - Autoirrigate only on start date or later
|
|
26
|
+
(str, 'yyyy-ddd')
|
|
27
|
+
* * end - Autoirrigate only on end date or earlier
|
|
28
|
+
(str, 'yyyy-ddd')
|
|
29
|
+
* * alre - Autoirrigate only after last reported irrigation
|
|
30
|
+
event (boolean)
|
|
31
|
+
* * idow - Autoirrigate only on specified days of the week
|
|
32
|
+
(str, e.g. '0123456'; default is all days)
|
|
33
|
+
0=sun, 1=mon, 2=tue, 3=wed, 4=thu, 5=fri, 6=sat
|
|
34
|
+
* * fpdep - Threshold for cumulative forecasted precipitation depth
|
|
35
|
+
(float, mm; default: 10.)
|
|
36
|
+
* * fpday : Number of days to consider for computing the cumulative
|
|
37
|
+
forecasted precipitation depth
|
|
38
|
+
(int, days; default: 1)
|
|
39
|
+
* * fpact : Action if forecasted precip is above threshold:
|
|
40
|
+
None (default) - Proceed to autoirrigate anyway if needed
|
|
41
|
+
'cancel' - Do not autoirrigate
|
|
42
|
+
'reduce' - Deduct forecasted precip from autoirrigation amount
|
|
43
|
+
* * mad - Management allowed depletion (float, mm/mm)
|
|
44
|
+
Autoirrigate if fractional root-zone soil water
|
|
45
|
+
depletion (fDr) >= mad
|
|
46
|
+
* * madDr - Management allowed depletion (float, mm)
|
|
47
|
+
Autoirrigate if root-zone soil water depletion (Dr) >= madDr
|
|
48
|
+
* * ksc - Critical value for transpiration reduction factor Ks
|
|
49
|
+
(float, 0-1, 1:full transpiration, 0:no trans.)
|
|
50
|
+
Autoirrigate if Ks <= ksc
|
|
51
|
+
* * dsli - Days since last irrigation event
|
|
52
|
+
(float, days)
|
|
53
|
+
Autoirrigate if days since last irrigation >= dsli
|
|
54
|
+
* * dsle - Days since last watering event, considering both
|
|
55
|
+
eff. precip and eff. irrigation (float, days)
|
|
56
|
+
Autoirrigate if days since last watering event >= dsle
|
|
57
|
+
* * evnt - Minimum depth of effective precipitation and
|
|
58
|
+
effective irrigation to be considered a watering
|
|
59
|
+
event (float, mm)
|
|
60
|
+
|
|
61
|
+
The default autoirrigation amount is root-zone soil water depletion (Dr,
|
|
62
|
+
mm). Variables to alter this irrigation amount are as follows:
|
|
63
|
+
* * icon - Apply a constant autoirrigation amount (float, mm)
|
|
64
|
+
* * itdr - Target a specfic root-zone soil water depletion (Dr)
|
|
65
|
+
following autoirrigation (float, mm)
|
|
66
|
+
* * itfdr - Target a specific fractional root-zone soil water
|
|
67
|
+
depletion following autoirrigation (float, mm/mm)
|
|
68
|
+
* * ietrd - Replace ET minus effective precipitation from the
|
|
69
|
+
past given number of days (int, days)
|
|
70
|
+
* * ietri - Replace ET minus effective precipitation since the
|
|
71
|
+
last irrigation event (boolean)
|
|
72
|
+
* * ietre - Replace ET minus effective precipitation since the
|
|
73
|
+
last watering event (boolean)
|
|
74
|
+
* * ettyp - Specify type of ET to adjust, when one among ietrd, ietri or ietre is specified
|
|
75
|
+
'ETcadj' (default) - Replace ETcadj less precip
|
|
76
|
+
'ETc' - Replace ETc less precip
|
|
77
|
+
* * iper - Adjust the autoirrigation amount by a fixed
|
|
78
|
+
percentage (float, %)
|
|
79
|
+
* * ieff - Consider an application efficiency for
|
|
80
|
+
autoirrigation (float, %; default: same as
|
|
81
|
+
irrigation efficiency)
|
|
82
|
+
* * imin - Limit autoirrigation to >= minimum amount (float,mm)
|
|
83
|
+
* * imax - Limit autoirrigation to <= maximum amount (float,mm)
|
|
84
|
+
* * fw - Fraction of soil surface wetted (FAO-56 Table 20; default: 1.0)
|
|
85
|
+
"""
|
|
86
|
+
|
|
87
|
+
COLS = ['start','end','alre','idow','fpdep','fpday',
|
|
88
|
+
'fpact','mad','madDr','ksc','dsli','dsle','evnt',
|
|
89
|
+
'icon','itdr','itfdr','ietrd','ietri','ietre',
|
|
90
|
+
'ettyp','iper','ieff','imin','imax','fw']
|
|
91
|
+
|
|
92
|
+
def __init__(self, data=None, **kwargs):
|
|
93
|
+
"""Initialize the AutoIrrigate class attributes.
|
|
94
|
+
|
|
95
|
+
Parameters
|
|
96
|
+
----------
|
|
97
|
+
data : DataFrame, optional
|
|
98
|
+
AutoIrrigation rules
|
|
99
|
+
columns - ['start','end','alre','idow','fpdep','fpday',
|
|
100
|
+
'fpact','mad','madDr','ksc','dsli','dsle','evnt',
|
|
101
|
+
'icon','itdr','itfdr','ietrd','ietri','ietre',
|
|
102
|
+
'ettyp','iper','ieff','imin','imax','fw']
|
|
103
|
+
"""
|
|
104
|
+
|
|
105
|
+
self.data = pd.DataFrame(columns=self.COLS)
|
|
106
|
+
|
|
107
|
+
if data is not None:
|
|
108
|
+
assert set(data.columns).issubset(set(self.COLS)), 'Invalid column names are present'
|
|
109
|
+
# add missing columns with NaN values
|
|
110
|
+
self.data = pd.concat([self.data, data])
|
|
111
|
+
|
|
112
|
+
# cast start and end columns to datetime
|
|
113
|
+
self.data['start'] = pd.to_datetime(self.data['start'])
|
|
114
|
+
self.data['end'] = pd.to_datetime(self.data['end'])
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def add_rule(self, start, end, alre=True, idow='0123456', fpdep=10.,
|
|
118
|
+
fpday=1, fpact=None, mad=float('NaN'),
|
|
119
|
+
madDr=float('NaN'), ksc=float('NaN'), dsli=float('NaN'),
|
|
120
|
+
dsle=float('NaN'), evnt=10., icon=None,
|
|
121
|
+
itdr=None, itfdr=None, ietrd=None,
|
|
122
|
+
ietri=False, ietre=False, ettyp='ETcadj', iper=None,
|
|
123
|
+
ieff=None, imin=None, imax=None, fw=1.0):
|
|
124
|
+
"""Add an autoirrigation rule for the given date range"""
|
|
125
|
+
|
|
126
|
+
# check that no other rule is already present for the given date range
|
|
127
|
+
if not self.data.empty:
|
|
128
|
+
assert not ((self.data['start'] <= pd.to_datetime(end)) &
|
|
129
|
+
(self.data['end'] >= pd.to_datetime(start))).any(), \
|
|
130
|
+
f'Rule already exists for the given date range: {start} to {end}'
|
|
131
|
+
# check that the start and end dates are valid
|
|
132
|
+
assert isinstance(start, str), f'start must be a string. Got type {type(start)}'
|
|
133
|
+
assert isinstance(end, str), f'end must be a string. Got type {type(end)}'
|
|
134
|
+
assert pd.to_datetime(start, format='%Y-%m-%d', errors='coerce') is not pd.NaT, \
|
|
135
|
+
f'start must be a valid date string in the format yyyy-mm-dd. Got {start}'
|
|
136
|
+
assert pd.to_datetime(end, format='%Y-%m-%d', errors='coerce') is not pd.NaT, \
|
|
137
|
+
f'end must be a valid date string in the format yyyy-mm-dd. Got {end}'
|
|
138
|
+
assert pd.to_datetime(start) <= pd.to_datetime(end), \
|
|
139
|
+
f'start date must be before end date. Got {start} and {end}'
|
|
140
|
+
# various checks on given arguments
|
|
141
|
+
assert isinstance(alre, bool), f'alre must be a boolean. Got type {type(alre)}'
|
|
142
|
+
assert isinstance(idow, str), f'idow must be a string. Got type {type(idow)}'
|
|
143
|
+
assert len(idow) <= 7, f'idow must be a string of at most 7 numbers. Got {idow}'
|
|
144
|
+
assert all(c in '0123456' for c in idow), \
|
|
145
|
+
f'idow must be a string containing numbers in 0,...,6. Got {idow}'
|
|
146
|
+
assert fpact is None or fpact in ['cancel', 'reduce'], \
|
|
147
|
+
f'Invalid value for fpact. Must be None, "cancel", or "reduce". Got {fpact}'
|
|
148
|
+
assert isinstance(fpday, int), f'fpday must be an integer. Got type {type(fpday)}'
|
|
149
|
+
assert fpday >= 0, f'fpday must be >= 0. Got {fpday}'
|
|
150
|
+
assert fpdep >= 0, f'fpdep must be >= 0. Got {fpdep}'
|
|
151
|
+
if ieff is not None:
|
|
152
|
+
assert isinstance(ieff, (int, float)), \
|
|
153
|
+
f'ieff must be an integer or float. Got type {type(ieff)}'
|
|
154
|
+
assert 0 <= ieff <= 100, f'ieff must be between 0 and 100. Got {ieff}'
|
|
155
|
+
f'ieff must be between 0 and 100. Got {ieff}'
|
|
156
|
+
if imin is not None:
|
|
157
|
+
assert isinstance(imin, (int, float)), \
|
|
158
|
+
f'imin must be an integer or float. Got type {type(imin)}'
|
|
159
|
+
assert imin >= 0, f'imin must be >= 0. Got {imin}'
|
|
160
|
+
if imax is not None:
|
|
161
|
+
assert isinstance(imax, (int, float)), \
|
|
162
|
+
f'imax must be an integer or float. Got type {type(imax)}'
|
|
163
|
+
assert imax >= 0, f'imax must be >= 0. Got {imax}'
|
|
164
|
+
if imin is not None and imax is not None:
|
|
165
|
+
assert imin <= imax, f'imax must be >= imin. Got {imin} and {imax}'
|
|
166
|
+
if fw is not None:
|
|
167
|
+
assert isinstance(fw, (int, float)), \
|
|
168
|
+
f'fw must be an integer or float. Got type {type(fw)}'
|
|
169
|
+
assert 0 <= fw <= 1, f'fw must be between 0 and 1. Got {fw}'
|
|
170
|
+
if ietrd is not None:
|
|
171
|
+
assert isinstance(ietrd, int), \
|
|
172
|
+
f'ietrd must be an integer. Got type {type(ietrd)}'
|
|
173
|
+
assert ietrd >= 0, f'ietrd must be >= 0. Got {ietrd}'
|
|
174
|
+
assert sum([
|
|
175
|
+
(icon is not None), (itdr is not None), (itfdr is not None),
|
|
176
|
+
(ietrd is not None), (ietri is True), (ietre is True)
|
|
177
|
+
]) == 1, \
|
|
178
|
+
'Exactly one among icon, itdr, itfdr, ietrd, ietri or ietre must be specified'
|
|
179
|
+
assert ettyp in ['ETcadj', 'ETc'], \
|
|
180
|
+
f'Invalid value for ettyp. Must be "ETcadj" or "ETc". Got {ettyp}'
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
rule = dict(
|
|
185
|
+
start=pd.to_datetime(start, format='%Y-%m-%d'),
|
|
186
|
+
end=pd.to_datetime(end, format='%Y-%m-%d'),
|
|
187
|
+
alre=alre, idow=idow, fpdep=fpdep,
|
|
188
|
+
fpday=fpday, fpact=fpact, mad=mad, madDr=madDr, ksc=ksc,
|
|
189
|
+
dsli=dsli, dsle=dsle, evnt=evnt, icon=icon, itdr=itdr,
|
|
190
|
+
itfdr=itfdr, ietrd=ietrd, ietri=ietri, ietre=ietre,
|
|
191
|
+
ettyp=ettyp, iper=iper, ieff=ieff, imin=imin, imax=imax,
|
|
192
|
+
fw=fw,
|
|
193
|
+
)
|
|
194
|
+
|
|
195
|
+
self.data = pd.concat([self.data, pd.DataFrame([rule])])
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def to_csv(self, path='pyfao56.airr'):
|
|
199
|
+
"""Save autoirrigation data to csv file
|
|
200
|
+
|
|
201
|
+
Parameters
|
|
202
|
+
----------
|
|
203
|
+
path : str
|
|
204
|
+
Filepath for saving the autoirrigation data
|
|
205
|
+
"""
|
|
206
|
+
|
|
207
|
+
self.data.to_csv(path, index=False)
|
|
208
|
+
|
|
209
|
+
@classmethod
|
|
210
|
+
def from_csv(cls, path):
|
|
211
|
+
"""Load autoirrigation data from csv file
|
|
212
|
+
|
|
213
|
+
Parameters
|
|
214
|
+
----------
|
|
215
|
+
path : str
|
|
216
|
+
Filepath for loading the autoirrigation data
|
|
217
|
+
|
|
218
|
+
Returns
|
|
219
|
+
-------
|
|
220
|
+
AutoIrrigate
|
|
221
|
+
AutoIrrigate class object
|
|
222
|
+
"""
|
|
223
|
+
|
|
224
|
+
data = pd.read_csv(path)
|
|
225
|
+
return cls(data)
|
|
226
|
+
|
|
227
|
+
@classmethod
|
|
228
|
+
def from_rules(cls, rules):
|
|
229
|
+
"""Load autoirrigation data from a list of rules
|
|
230
|
+
|
|
231
|
+
Parameters
|
|
232
|
+
----------
|
|
233
|
+
rules : list
|
|
234
|
+
List of dictionaries containing autoirrigation rules, e.g.:
|
|
235
|
+
[{'start': '2020-01-01', 'end': '2020-12-31', 'alre': True, ...}, ...]
|
|
236
|
+
|
|
237
|
+
Returns
|
|
238
|
+
-------
|
|
239
|
+
AutoIrrigate
|
|
240
|
+
AutoIrrigate class object
|
|
241
|
+
"""
|
|
242
|
+
|
|
243
|
+
#data = pd.DataFrame(rules)
|
|
244
|
+
#return cls(data)
|
|
245
|
+
airr = cls()
|
|
246
|
+
for rule in rules:
|
|
247
|
+
airr.add_rule(**rule)
|
|
248
|
+
return airr
|
pyfao56v2/forecast.py
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
"""
|
|
2
|
+
########################################################################
|
|
3
|
+
The forecast.py module contains the Forecast class, which is used to
|
|
4
|
+
retrieve weather forecasts from OpenMeteo.
|
|
5
|
+
########################################################################
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import openmeteo_requests
|
|
9
|
+
import requests_cache
|
|
10
|
+
import pandas as pd
|
|
11
|
+
from retry_requests import retry
|
|
12
|
+
from .weather import Weather
|
|
13
|
+
from math import log
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class Forecast:
|
|
18
|
+
def __init__(
|
|
19
|
+
self, lat, lon, z=None, wndht=2.0, rfcrp='S', clmt='dry', loctn='interior',
|
|
20
|
+
cache_dir='.cache', expire_after=3600, retries=5, backoff_factor=0.2,
|
|
21
|
+
**kwargs
|
|
22
|
+
):
|
|
23
|
+
"""Initialize the Forecast class attributes.
|
|
24
|
+
|
|
25
|
+
Parameters
|
|
26
|
+
----------
|
|
27
|
+
lat : float
|
|
28
|
+
Weather station latitude (decimal degrees)
|
|
29
|
+
lon : float
|
|
30
|
+
Weather station longitude (decimal degrees)
|
|
31
|
+
z : float, optional
|
|
32
|
+
Weather station elevation (z) (m)
|
|
33
|
+
wndht : float, optional
|
|
34
|
+
Weather station wind speed measurement height (m)
|
|
35
|
+
rfcrp : str, optional
|
|
36
|
+
Type of reference crop - Short ('S') or Tall ('T')
|
|
37
|
+
clmt : str, optional
|
|
38
|
+
Climate type - 'dry' or 'wet'
|
|
39
|
+
loctn : str, optional
|
|
40
|
+
Location type - 'coastal' or 'interior'
|
|
41
|
+
cache_dir : str, optional
|
|
42
|
+
Directory to store the cache (default = '.cache')
|
|
43
|
+
expire_after : int, optional
|
|
44
|
+
Cache expiration time (default = 3600)
|
|
45
|
+
retries : int, optional
|
|
46
|
+
Number of retries on error (default = 5)
|
|
47
|
+
backoff_factor : float, optional
|
|
48
|
+
Backoff factor for retries (default = 0.2)
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
self.lat = lat
|
|
52
|
+
self.lon = lon
|
|
53
|
+
self.z = z
|
|
54
|
+
self.wndht = wndht
|
|
55
|
+
self.rfcrp = rfcrp
|
|
56
|
+
self.clmt = clmt
|
|
57
|
+
self.loctn = loctn
|
|
58
|
+
self.data = None
|
|
59
|
+
|
|
60
|
+
# Setup the Open-Meteo API client with cache and retry on error
|
|
61
|
+
self.cache_session = requests_cache.CachedSession(cache_dir, expire_after=expire_after)
|
|
62
|
+
self.retry_session = retry(self.cache_session, retries=retries, backoff_factor=backoff_factor)
|
|
63
|
+
self.openmeteo = openmeteo_requests.Client(session=self.retry_session)
|
|
64
|
+
self.url_endpoint = "https://api.open-meteo.com/v1/forecast"
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def get_forecast(self, start_date=None, end_date=None, forecast_days=7):
|
|
68
|
+
"""Get the weather forecast for a location
|
|
69
|
+
|
|
70
|
+
Parameters
|
|
71
|
+
----------
|
|
72
|
+
start_date : str, optional
|
|
73
|
+
Start date of the forecast (YYYY-MM-DD)
|
|
74
|
+
end_date : str, optional
|
|
75
|
+
End date of the forecast (YYYY-MM-DD)
|
|
76
|
+
forecast_days : int, optional
|
|
77
|
+
Number of days to forecast from the start date
|
|
78
|
+
|
|
79
|
+
Returns
|
|
80
|
+
-------
|
|
81
|
+
forecast : pd.DataFrame
|
|
82
|
+
Weather forecast data
|
|
83
|
+
"""
|
|
84
|
+
if end_date is not None:
|
|
85
|
+
assert start_date is not None, "start_date must be provided if end_date is provided"
|
|
86
|
+
# in this case, ignore the forecast_days parameter
|
|
87
|
+
forecast_days = None
|
|
88
|
+
|
|
89
|
+
params = {
|
|
90
|
+
"latitude": self.lat,
|
|
91
|
+
"longitude": self.lon,
|
|
92
|
+
"elevation": self.z,
|
|
93
|
+
"hourly": [
|
|
94
|
+
"temperature_2m",
|
|
95
|
+
"relative_humidity_2m",
|
|
96
|
+
"vapour_pressure_deficit",
|
|
97
|
+
"dew_point_2m",
|
|
98
|
+
"wind_speed_10m",
|
|
99
|
+
"precipitation_probability",
|
|
100
|
+
"precipitation",
|
|
101
|
+
],
|
|
102
|
+
"daily": [
|
|
103
|
+
"shortwave_radiation_sum",
|
|
104
|
+
"et0_fao_evapotranspiration",
|
|
105
|
+
],
|
|
106
|
+
"start_date": start_date,
|
|
107
|
+
"end_date": end_date,
|
|
108
|
+
"forecast_days": forecast_days,
|
|
109
|
+
"wind_speed_unit": "ms",
|
|
110
|
+
"timezone": "auto"
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
# perform the request
|
|
114
|
+
response = self.openmeteo.weather_api(self.url_endpoint, params=params)[0]
|
|
115
|
+
if self.z is None:
|
|
116
|
+
self.z = response.Elevation() # if elevation is not provided, use the elevation from the response
|
|
117
|
+
#timezone = response.TimezoneAbbreviation()
|
|
118
|
+
#utc_offset = response.UtcOffsetSeconds()
|
|
119
|
+
|
|
120
|
+
# Process hourly data
|
|
121
|
+
hourly = response.Hourly()
|
|
122
|
+
hourly_data = {"date": pd.date_range(
|
|
123
|
+
start = pd.to_datetime(hourly.Time(), unit="s", utc=True),
|
|
124
|
+
end = pd.to_datetime(hourly.TimeEnd(), unit="s", utc=True),
|
|
125
|
+
freq = pd.Timedelta(seconds = hourly.Interval()),
|
|
126
|
+
inclusive = "left"
|
|
127
|
+
)}
|
|
128
|
+
for v_idx,v in enumerate(params["hourly"]):
|
|
129
|
+
hourly_data[v] = hourly.Variables(v_idx).ValuesAsNumpy()
|
|
130
|
+
hourly_dataframe = pd.DataFrame(data=hourly_data).set_index("date")
|
|
131
|
+
|
|
132
|
+
# Process daily data
|
|
133
|
+
daily = response.Daily()
|
|
134
|
+
daily_data = {"date": pd.date_range(
|
|
135
|
+
start = pd.to_datetime(daily.Time(), unit="s", utc=True),
|
|
136
|
+
end = pd.to_datetime(daily.TimeEnd(), unit="s", utc=True),
|
|
137
|
+
freq = pd.Timedelta(seconds = daily.Interval()),
|
|
138
|
+
inclusive = "left"
|
|
139
|
+
)}
|
|
140
|
+
for v_idx,v in enumerate(params["daily"]):
|
|
141
|
+
daily_data[v] = daily.Variables(v_idx).ValuesAsNumpy()
|
|
142
|
+
daily_dataframe = pd.DataFrame(data=daily_data).set_index("date")
|
|
143
|
+
|
|
144
|
+
# aggregate data
|
|
145
|
+
daily_dataframe["Tmin"] = hourly_dataframe["temperature_2m"].resample("D").min()
|
|
146
|
+
daily_dataframe["Tmax"] = hourly_dataframe["temperature_2m"].resample("D").max()
|
|
147
|
+
daily_dataframe["Tmean"] = hourly_dataframe["temperature_2m"].resample("D").mean()
|
|
148
|
+
daily_dataframe["RHmin"] = hourly_dataframe["relative_humidity_2m"].resample("D").min()
|
|
149
|
+
daily_dataframe["RHmax"] = hourly_dataframe["relative_humidity_2m"].resample("D").max()
|
|
150
|
+
daily_dataframe["RHmean"] = hourly_dataframe["relative_humidity_2m"].resample("D").mean()
|
|
151
|
+
daily_dataframe["Vapr"] = hourly_dataframe["vapour_pressure_deficit"].resample("D").mean()
|
|
152
|
+
daily_dataframe["Tdew"] = hourly_dataframe["dew_point_2m"].resample("D").mean()
|
|
153
|
+
daily_dataframe["Wndsp"] = hourly_dataframe["wind_speed_10m"].resample("D").mean() # NB: forecasted wind speed seems a bit overestimated...
|
|
154
|
+
# adjust wind speed to the desired height
|
|
155
|
+
if self.wndht != 10.0:
|
|
156
|
+
daily_dataframe["Wndsp"] = daily_dataframe["Wndsp"] * (4.87/log(67.8*self.wndht-5.42))
|
|
157
|
+
daily_dataframe["Srad"] = daily_dataframe.pop("shortwave_radiation_sum")
|
|
158
|
+
# compute rain as sum of hourly values weighted by probability
|
|
159
|
+
hourly_dataframe["precipitation_probability"] = hourly_dataframe["precipitation_probability"].fillna(100) / 100
|
|
160
|
+
daily_dataframe["Rain"] = (hourly_dataframe["precipitation"] * hourly_dataframe["precipitation_probability"]).resample("D").sum()
|
|
161
|
+
daily_dataframe["ETref"] = daily_dataframe.pop("et0_fao_evapotranspiration")
|
|
162
|
+
daily_dataframe.index.name = "Date"
|
|
163
|
+
|
|
164
|
+
# compute the reference evapotranspiration (through the Weather class)
|
|
165
|
+
#daily_dataframe["ETref"] = Weather(data=daily_dataframe, z=self.z, lat=self.lat, wndht=self.wndht, rfcrp=self.rfcrp, clmt=self.clmt, loctn=self.loctn).data["ETref"]
|
|
166
|
+
self.data = daily_dataframe
|
|
167
|
+
|
|
168
|
+
return self.data
|
|
169
|
+
|
|
170
|
+
def to_csv(self, path='pyfao56.frc'):
|
|
171
|
+
"""Save forecast weather data to a CSV file.
|
|
172
|
+
|
|
173
|
+
Parameters
|
|
174
|
+
----------
|
|
175
|
+
filepath : str, optional
|
|
176
|
+
Path to forecast weather data file (default = 'pyfao56.frc')
|
|
177
|
+
"""
|
|
178
|
+
|
|
179
|
+
with open(path, 'w') as f:
|
|
180
|
+
f.write(f'#z: {self.z}\n')
|
|
181
|
+
f.write(f'#lat: {self.lat}\n')
|
|
182
|
+
f.write(f'#wndht: {self.wndht}\n')
|
|
183
|
+
f.write(f'#rfcrp: {self.rfcrp}\n')
|
|
184
|
+
f.write(f'#clmt: {self.clmt}\n')
|
|
185
|
+
f.write(f'#loctn: {self.loctn}\n')
|
|
186
|
+
self.data.to_csv(f)
|
pyfao56v2/irrigation.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
"""
|
|
2
|
+
########################################################################
|
|
3
|
+
The irrigation.py module contains the Irrigation class, which provides
|
|
4
|
+
I/O tools for defining the irrigation management schedule, as required
|
|
5
|
+
for FAO-56 calculations.
|
|
6
|
+
########################################################################
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import pandas as pd
|
|
10
|
+
|
|
11
|
+
class Irrigation:
|
|
12
|
+
"""A class for managing irrigation data for FAO-56 calculations
|
|
13
|
+
|
|
14
|
+
Attributes
|
|
15
|
+
----------
|
|
16
|
+
data : DataFrame
|
|
17
|
+
Irrigation data
|
|
18
|
+
* index - Dates ('YYYY-MM-DD')
|
|
19
|
+
* columns - ['Depth','fw','ieff']
|
|
20
|
+
* * Depth - Irrigation depth (mm)
|
|
21
|
+
* * fw - fraction of soil surface wetted (FAO-56 Table 20)
|
|
22
|
+
* * ieff - Irrigation application efficiency (%)
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
COLS = ['Depth','fw','ieff']
|
|
26
|
+
|
|
27
|
+
def __init__(self, data=None, **kwargs):
|
|
28
|
+
"""Initialize the Irrigation class attributes.
|
|
29
|
+
|
|
30
|
+
Parameters
|
|
31
|
+
----------
|
|
32
|
+
data : DataFrame
|
|
33
|
+
Irrigation events
|
|
34
|
+
index - Dates ('YYYY-MM-DD')
|
|
35
|
+
columns - ['Depth','fw','ieff']
|
|
36
|
+
Depth - Irrigation depth (mm)
|
|
37
|
+
fw - fraction of soil surface wetted (FAO-56 Table 20)
|
|
38
|
+
ieff - Irrigation application efficiency (%) (FAO-24 Section 3.3.1)
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
self.data = pd.DataFrame(columns=self.COLS)
|
|
42
|
+
|
|
43
|
+
if data is not None:
|
|
44
|
+
assert set(data.columns) == set(self.COLS), f'Columns should be {self.COLS}. Got {data.columns}'
|
|
45
|
+
self.data = data[self.COLS] # change order of columns if necessary
|
|
46
|
+
self.data.index = pd.to_datetime(self.data.index, format='%Y-%m-%d')
|
|
47
|
+
|
|
48
|
+
# drop rows in which Depth is nan or 0
|
|
49
|
+
self.data = self.data.dropna(subset=["Depth"])
|
|
50
|
+
self.data = self.data[self.data['Depth'] > 0]
|
|
51
|
+
|
|
52
|
+
def to_csv(self, path='pyfao56.irr'):
|
|
53
|
+
"""Save irrigation data to csv file
|
|
54
|
+
|
|
55
|
+
Parameters
|
|
56
|
+
----------
|
|
57
|
+
path : str
|
|
58
|
+
Filepath for saving the irrigation data
|
|
59
|
+
"""
|
|
60
|
+
|
|
61
|
+
self.data.to_csv(path)
|
|
62
|
+
return
|
|
63
|
+
|
|
64
|
+
@classmethod
|
|
65
|
+
def from_csv(cls, path):
|
|
66
|
+
"""Load irrigation data from csv file
|
|
67
|
+
|
|
68
|
+
Parameters
|
|
69
|
+
----------
|
|
70
|
+
path : str
|
|
71
|
+
Filepath for loading the irrigation data
|
|
72
|
+
|
|
73
|
+
Returns
|
|
74
|
+
-------
|
|
75
|
+
Irrigation
|
|
76
|
+
Irrigation class object
|
|
77
|
+
"""
|
|
78
|
+
|
|
79
|
+
data = pd.read_csv(path, index_col=0)
|
|
80
|
+
return cls(data)
|
|
81
|
+
|
|
82
|
+
@classmethod
|
|
83
|
+
def from_events(cls, events, **kwargs):
|
|
84
|
+
"""Create an Irrigation object from a list of irrigation events
|
|
85
|
+
|
|
86
|
+
Parameters
|
|
87
|
+
----------
|
|
88
|
+
events : list
|
|
89
|
+
List of dictionaries containing irrigation events, e.g.:
|
|
90
|
+
[{'Date': '2020-01-01', 'Depth': 8.0, 'fw': 1.0, 'ieff': 90}, ...]
|
|
91
|
+
|
|
92
|
+
Returns
|
|
93
|
+
-------
|
|
94
|
+
Irrigation
|
|
95
|
+
Irrigation class object
|
|
96
|
+
"""
|
|
97
|
+
|
|
98
|
+
data = pd.DataFrame(events).set_index('Date')
|
|
99
|
+
return cls(data)
|
|
100
|
+
|
|
101
|
+
def get_irrig(self, date):
|
|
102
|
+
"""Get irrigation data for a specific date
|
|
103
|
+
|
|
104
|
+
Parameters
|
|
105
|
+
----------
|
|
106
|
+
date : str
|
|
107
|
+
Date ('YYYY-MM-DD')
|
|
108
|
+
|
|
109
|
+
Returns
|
|
110
|
+
-------
|
|
111
|
+
dict
|
|
112
|
+
Irrigation data for the specified date
|
|
113
|
+
"""
|
|
114
|
+
|
|
115
|
+
if date in self.data.index:
|
|
116
|
+
return self.data.loc[date].to_dict()
|
|
117
|
+
else:
|
|
118
|
+
return {"Depth": 0, "fw": 0, "ieff": 100}
|