STIC-JPL 1.1.0__py3-none-any.whl → 1.2.2__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 STIC-JPL might be problematic. Click here for more details.

@@ -0,0 +1,49 @@
1
+ from typing import Union
2
+ import numpy as np
3
+ import rasters as rt
4
+ from rasters import Raster
5
+
6
+ KPAR = 0.5
7
+ MIN_FIPAR = 0.0
8
+ MAX_FIPAR = 1.0
9
+ MIN_LAI = 0.0
10
+ MAX_LAI = 10.0
11
+
12
+ def FVC_from_NDVI(NDVI: Union[Raster, np.ndarray]) -> Union[Raster, np.ndarray]:
13
+ """
14
+ Estimate Fractional Vegetation Cover (FVC) from Normalized Difference Vegetation Index (NDVI)
15
+ using a scaled NDVI approach.
16
+
17
+ This method linearly scales NDVI values between two endmembers:
18
+ - NDVIs: NDVI value for bare soil (typically ~0.04 ± 0.03)
19
+ - NDVIv: NDVI value for full vegetation (typically ~0.52 ± 0.03)
20
+
21
+ The resulting Fractional Vegetation Cover (FVC) is calculated as:
22
+
23
+ FVC = clip((NDVI - NDVIs) / (NDVIv - NDVIs), 0.0, 1.0)
24
+
25
+ This approach is based on the assumption that NDVI increases linearly with vegetation cover
26
+ between these two extremes, and is well-supported in the literature.
27
+
28
+ References:
29
+ Carlson, T. N., & Ripley, D. A. (1997). On the relation between NDVI, fractional vegetation cover,
30
+ and leaf area index. Remote Sensing of Environment, 62(3), 241–252.
31
+ https://doi.org/10.1016/S0034-4257(97)00104-1
32
+
33
+ Gutman, G., & Ignatov, A. (1998). The derivation of the green vegetation fraction from NOAA/AVHRR
34
+ data for use in numerical weather prediction models. International Journal of Remote Sensing,
35
+ 19(8), 1533–1543. https://doi.org/10.1080/014311698215333
36
+
37
+ Parameters:
38
+ NDVI (Union[Raster, np.ndarray]): Input NDVI data.
39
+
40
+ Returns:
41
+ Union[Raster, np.ndarray]: Estimated Fractional Vegetation Cover (FVC).
42
+ """
43
+ NDVIv = 0.52 # NDVI for fully vegetated pixel
44
+ NDVIs = 0.04 # NDVI for bare soil pixel
45
+
46
+ # Scale NDVI to FVC using a linear model and clip to [0, 1]
47
+ FVC = rt.clip((NDVI - NDVIs) / (NDVIv - NDVIs), 0.0, 1.0)
48
+
49
+ return FVC
@@ -0,0 +1,61 @@
1
+ from typing import Union
2
+ import numpy as np
3
+ import rasters as rt
4
+ from rasters import Raster
5
+
6
+ # Constants
7
+ KPAR = 0.5 # Extinction coefficient for PAR, assumed average for broadleaf canopies (Weiss & Baret, 2010)
8
+ MIN_FIPAR = 0.0
9
+ MAX_FIPAR = 1.0
10
+ MIN_LAI = 0.0
11
+ MAX_LAI = 10.0
12
+
13
+ def LAI_from_NDVI(
14
+ NDVI: Union[Raster, np.ndarray],
15
+ min_fIPAR: float = MIN_FIPAR,
16
+ max_fIPAR: float = MAX_FIPAR,
17
+ min_LAI: float = MIN_LAI,
18
+ max_LAI: float = MAX_LAI) -> Union[Raster, np.ndarray]:
19
+ """
20
+ Estimate Leaf Area Index (LAI) from NDVI using a simplified two-step empirical model.
21
+
22
+ This method first approximates the fraction of absorbed photosynthetically active radiation (fIPAR)
23
+ from NDVI, and then estimates LAI using the Beer–Lambert Law. The extinction coefficient for PAR (KPAR)
24
+ is assumed to be 0.5, which is typical for broadleaf canopies under diffuse light conditions.
25
+
26
+ Steps:
27
+ 1. fIPAR ≈ NDVI - 0.05 (empirical offset to account for soil background and sensor noise)
28
+ - Based on observed relationships in Myneni & Williams (1994)
29
+ 2. LAI = -ln(1 - fIPAR) / KPAR (Beer–Lambert Law)
30
+ - From Sellers (1985)
31
+
32
+ All outputs are clipped to user-defined minimum and maximum thresholds to ensure physical realism.
33
+
34
+ Parameters:
35
+ NDVI (Union[Raster, np.ndarray]): Input NDVI data.
36
+ min_fIPAR (float): Minimum fIPAR value for clipping (default 0.0).
37
+ max_fIPAR (float): Maximum fIPAR value for clipping (default 1.0).
38
+ min_LAI (float): Minimum LAI value for clipping (default 0.0).
39
+ max_LAI (float): Maximum LAI value for clipping (default 10.0).
40
+
41
+ Returns:
42
+ Union[Raster, np.ndarray]: Estimated LAI values.
43
+
44
+ References:
45
+ - Sellers, P. J. (1985). Canopy reflectance, photosynthesis and transpiration.
46
+ *International Journal of Remote Sensing*, 6(8), 1335–1372.
47
+ - Myneni, R. B., & Williams, D. L. (1994). On the relationship between FAPAR and NDVI.
48
+ *Remote Sensing of Environment*, 49(3), 200–211.
49
+ - Weiss, M., & Baret, F. (2010). CAN-EYE V6.1 User Manual. INRA-CSE.
50
+
51
+ """
52
+ # Empirical conversion from NDVI to fIPAR (adjusted for background noise)
53
+ fIPAR = rt.clip(NDVI - 0.05, min_fIPAR, max_fIPAR)
54
+
55
+ # Avoid division by zero or log of 0 by masking zero fIPAR values
56
+ fIPAR = np.where(fIPAR == 0, np.nan, fIPAR)
57
+
58
+ # Apply Beer–Lambert law to estimate LAI
59
+ LAI = rt.clip(-np.log(1 - fIPAR) * (1 / KPAR), min_LAI, max_LAI)
60
+
61
+ return LAI
STIC_JPL/STIC_JPL.py CHANGED
@@ -1,370 +1,3 @@
1
- from typing import Union, Callable
2
- import logging
3
- from datetime import datetime, timedelta
4
- from os.path import join, abspath, expanduser
5
- from typing import Dict, List
6
- import numpy as np
7
- import warnings
8
- from .diagnostic import diagnostic
9
- import colored_logging as cl
10
- from .meteorology_conversion import calculate_air_density, calculate_specific_heat, calculate_specific_humidity, calculate_surface_pressure, celcius_to_kelvin
11
- import rasters as rt
12
- from GEOS5FP import GEOS5FP
13
- from solar_apparent_time import solar_day_of_year_for_area, solar_hour_of_day_for_area
14
-
15
- from .timer import Timer
16
-
17
- from rasters import Raster, RasterGeometry
18
-
19
- from .vegetation_conversion.vegetation_conversion import FVC_from_NDVI, LAI_from_NDVI
20
-
21
- from .constants import *
22
- from .closure import STIC_closure
23
- from .soil_moisture_initialization import initialize_soil_moisture
24
- from .soil_moisture_iteration import iterate_soil_moisture
25
- from .net_radiation import calculate_net_longwave_radiation
26
- from .initialize_with_solar import initialize_with_solar
27
- from .canopy_air_stream import calculate_canopy_air_stream_vapor_pressure
28
- from .initialize_without_solar import initialize_without_solar
29
- from .iterate_with_solar import iterate_with_solar
30
- from .iterate_without_solar import iterate_without_solar
31
- from .root_zone_initialization import calculate_root_zone_moisture
32
-
33
- from .soil_heat_flux import calculate_SEBAL_soil_heat_flux
34
-
35
- __author__ = 'Kaniska Mallick, Madeleine Pascolini-Campbell, Gregory Halverson'
36
-
37
- logger = logging.getLogger(__name__)
38
-
39
- def STIC_JPL(
40
- ST_C: Union[Raster, np.ndarray],
41
- emissivity: Union[Raster, np.ndarray],
42
- NDVI: Union[Raster, np.ndarray],
43
- albedo: Union[Raster, np.ndarray],
44
- Rn_Wm2: Union[Raster, np.ndarray],
45
- geometry: RasterGeometry = None,
46
- time_UTC: datetime = None,
47
- hour_of_day: np.ndarray = None,
48
- day_of_year: np.ndarray = None,
49
- GEOS5FP_connection: GEOS5FP = None,
50
- Ta_C: Union[Raster, np.ndarray] = None,
51
- RH: Union[Raster, np.ndarray] = None,
52
- G: Union[Raster, np.ndarray] = None,
53
- G_method: str = DEFAULT_G_METHOD,
54
- SM: Union[Raster, np.ndarray] = None,
55
- Rg_Wm2: Union[Raster, np.ndarray] = None,
56
- FVC: Union[Raster, np.ndarray] = None,
57
- LAI: Union[Raster, np.ndarray] = None,
58
- elevation_m: Union[Raster, np.ndarray] = None,
59
- delta_hPa: Union[Raster, np.ndarray] = None,
60
- gamma_hPa: Union[Raster, np.ndarray, float] = GAMMA_HPA,
61
- rho_kgm3: Union[Raster, np.ndarray] = RHO_KGM3,
62
- Cp_Jkg: Union[Raster, np.ndarray] = CP_JKG,
63
- alpha: float = PT_ALPHA,
64
- LE_convergence_target: float = LE_CONVERGENCE_TARGET_WM2,
65
- max_iterations: int = MAX_ITERATIONS,
66
- diagnostic_directory: str = None,
67
- show_distributions: bool = SHOW_DISTRIBUTIONS,
68
- use_variable_alpha: bool = USE_VARIABLE_ALPHA) -> Dict[str, Union[Raster, np.ndarray]]:
69
- results = {}
70
-
71
- if geometry is None and isinstance(ST_C, Raster):
72
- geometry = ST_C.geometry
73
-
74
- if GEOS5FP_connection is None:
75
- GEOS5FP_connection = GEOS5FP()
76
-
77
- if (day_of_year is None or hour_of_day is None) and time_UTC is not None and geometry is not None:
78
- day_of_year = solar_day_of_year_for_area(time_UTC=time_UTC, geometry=geometry)
79
- hour_of_day = solar_hour_of_day_for_area(time_UTC=time_UTC, geometry=geometry)
80
-
81
- if time_UTC is None and day_of_year is None and hour_of_day is None:
82
- raise ValueError("no time given between time_UTC, day_of_year, and hour_of_day")
83
-
84
- diag_kwargs = {
85
- "show_distributions": show_distributions,
86
- "output_directory": diagnostic_directory
87
- }
88
-
89
- seconds_of_day = hour_of_day * 3600.0
90
-
91
- # load air temperature in Celsius if not provided
92
- if Ta_C is None:
93
- Ta_C = GEOS5FP_connection.Ta_C(time_UTC=time_UTC, geometry=geometry, resampling=resampling)
94
-
95
- # load relative humidity if not provided
96
- if RH is None:
97
- RH = GEOS5FP_connection.RH(time_UTC=time_UTC, geometry=geometry, resampling=resampling)
98
-
99
- # calculate fraction of vegetation cover if it's not given
100
- if FVC is None:
101
- FVC = FVC_from_NDVI(NDVI)
102
-
103
- # calculate leaf area index if it's not given
104
- if LAI is None:
105
- LAI = LAI_from_NDVI(NDVI)
106
-
107
- # saturation air pressure in hPa
108
- SVP_hPa = 6.13753 * (np.exp((17.27 * Ta_C) / (Ta_C + 237.3)))
109
-
110
- # calculate delta term if it's not given
111
- if delta_hPa is None:
112
- # slope of saturation vapor pressure to air temperature (hpa/K)
113
- delta_hPa = 4098 * SVP_hPa / (Ta_C + 237.3) ** 2
114
-
115
- Ta_K = celcius_to_kelvin(Ta_C)
116
-
117
- # actual vapor pressure at TA (hpa/K)
118
- Ea_hPa = SVP_hPa * (RH)
119
- Ea_Pa = Ea_hPa * 100.0
120
-
121
- # vapor pressure deficit (hPa)
122
- VPD_hPa = SVP_hPa - Ea_hPa
123
-
124
- # swapping in the dew-point calculation from PT-JPL
125
- Td_C = Ta_C - ((100 - RH * 100) / 5.0)
126
-
127
- # difference between surface and air temperature (Celsius)
128
- dTS_C = ST_C - Ta_C
129
-
130
- # saturation vapor pressure at surface temperature (hPa/K)
131
- Estar_hPa = 6.13753 * np.exp((17.27 * ST_C) / (ST_C + 237.3))
132
-
133
- if Rg_Wm2 is None:
134
- # if G is None and SM is None:
135
- # raise ValueError("soil heat flux or soil moisture prior required if solar radiation is not given")
136
-
137
- if G is None:
138
- G = calculate_SEBAL_soil_heat_flux(
139
- ST_C=ST_C,
140
- NDVI=NDVI,
141
- albedo=albedo,
142
- Rn=Rn_Wm2,
143
- )
144
-
145
- phi_Wm2 = Rn_Wm2 - G
146
-
147
- # initialize without solar radiation
148
- SM, SMrz, s1, s3, s33, s44, Ms, Tsd_C, Es_hPa, Ds = initialize_without_solar(
149
- ST_C = ST_C, # Surface temperature in Celsius
150
- Ta_C = Ta_C, # Air temperature in Celsius
151
- dTS = dTS_C, # Temperature difference between surface and air in Celsius
152
- Td_C = Td_C, # Dewpoint temperature in Celsius
153
- Ea_hPa = Ea_hPa, # Actual vapor pressure in hPa
154
- Estar_hPa = Estar_hPa, # Saturation vapor pressure at surface temperature (hPa/K)
155
- SVP_hPa = SVP_hPa, # Saturation vapor pressure at the surface in hPa
156
- delta_hPa = delta_hPa, # Slope of the saturation vapor pressure-temperature curve in hPa/K
157
- phi_Wm2 = phi_Wm2, # Available energy in W/m2
158
- gamma_hPa = gamma_hPa, # Psychrometric constant in hPa/°C
159
- alpha = alpha # Priestley-Taylor alpha
160
- )
161
- else:
162
- SM, SMrz, Ms, s1, s3, Ep_PT, Rnsoil, LWnet_Wm2, G, Tsd_C, Ds, Es_hPa, phi_Wm2 = initialize_with_solar(
163
- seconds_of_day = seconds_of_day, # time of day in seconds since midnight
164
- Rg_Wm2 = Rg_Wm2, # solar radiation (W/m^2)
165
- Rn_Wm2 = Rn_Wm2, # net radiation (W/m^2)
166
- ST_C = ST_C, # surface temperature (Celsius)
167
- emissivity = emissivity, # emissivity of the surface
168
- Ta_C = Ta_C, # air temperature (Celsius)
169
- dTS_C = dTS_C, # surface air temperature difference (Celsius)
170
- Td_C = Td_C, # dew point temperature (Celsius)
171
- VPD_hPa = VPD_hPa, # vapor pressure deficit (hPa)
172
- SVP_hPa = SVP_hPa, # saturation vapor pressure at given air temperature (hPa)
173
- Ea_hPa = Ea_hPa, # actual vapor pressure at air temperature (hPa)
174
- Estar_hPa = Estar_hPa, # saturation vapor pressure at surface temperature (hPa)
175
- delta_hPa = delta_hPa, # slope of saturation vapor pressure to air temperature (hpa/K)
176
- NDVI=NDVI, # normalized difference vegetation index
177
- FVC = FVC, # fractional vegetation cover
178
- LAI = LAI, # leaf area index
179
- albedo = albedo, # albedo of the surface
180
- gamma_hPa=gamma_hPa, # psychrometric constant (hPa/°C)
181
- G_method = DEFAULT_G_METHOD, # method for calculating soil heat flux
182
- )
183
-
184
- diagnostic(Ms, "Ms", **diag_kwargs)
185
-
186
- # STIC analytical equations (convergence on LE)
187
- gB_ms, gS_ms, dT_C, EF = STIC_closure(
188
- delta_hPa=delta_hPa,
189
- phi_Wm2=phi_Wm2,
190
- Es_hPa=Es_hPa,
191
- Ea_hPa=Ea_hPa,
192
- Estar_hPa=Estar_hPa,
193
- SM=SM,
194
- gamma_hPa=gamma_hPa,
195
- rho_kgm3=rho_kgm3,
196
- Cp_Jkg=Cp_Jkg,
197
- alpha=alpha
198
- )
199
-
200
- gBB = gB_ms
201
- gSS = gS_ms
202
- gBB_by_gSS = rt.where(gSS == 0, 0, gBB / gSS)
203
- gB_by_gS = rt.where(gS_ms == 0, 0, gB_ms / gS_ms)
204
- dT_C = dT_C
205
- T0_C = dT_C + Ta_C
206
-
207
- PET_Wm2 = ((delta_hPa * phi_Wm2 + rho_kgm3 * Cp_Jkg * gB_ms * VPD_hPa) / (delta_hPa + gamma_hPa)) # Penman potential evaporation
208
-
209
- gR = (4 * SB_SIGMA * (Ta_C + 273) ** 3 * emissivity) / (rho_kgm3 * Cp_Jkg)
210
- omega = ((delta_hPa / gamma_hPa) + 1) / ((delta_hPa / gamma_hPa) + 1 + gB_by_gS)
211
- LE_eq = (phi_Wm2 * (delta_hPa / gamma_hPa)) / ((delta_hPa / gamma_hPa) + 1)
212
- LE_imp = (Cp_Jkg * 0.0289644 / gamma_hPa) * gS_ms * 40 * VPD_hPa
213
- LE_init = omega * LE_eq + (1 - omega) * LE_imp
214
- dry = (Ds > VPD_hPa) & (PET_Wm2 > phi_Wm2) & (dTS_C > 0) & (Td_C <= 0)
215
- omega = rt.where(dry,
216
- ((delta_hPa / gamma_hPa) + 1 + gR / gB_ms) / ((delta_hPa / gamma_hPa) + 1 + gB_ms / gS_ms + gR / gS_ms + gR / gB_ms),
217
- omega)
218
- LE_eq = rt.where(dry, (phi_Wm2 * (delta_hPa / gamma_hPa)) / ((delta_hPa / gamma_hPa) + 1 + gR / gB_ms), LE_eq)
219
- LE_init = rt.where(dry, omega * LE_eq + (1 - omega * LE_imp), LE_init)
220
-
221
- # sensible heat flux
222
- H_Wm2 = ((gamma_hPa * phi_Wm2 * (1 + gB_by_gS) - rho_kgm3 * Cp_Jkg * gB_ms * VPD_hPa) / (delta_hPa + gamma_hPa * (1 + (gB_by_gS))))
223
-
224
- LE_Wm2_new = LE_init
225
- LE_Wm2_change = LE_convergence_target
226
- LE_Wm2_old = LE_Wm2_new
227
- LE_transpiration_Wm2 = None
228
- PT_Wm2 = None
229
- iteration = 1
230
- LE_Wm2_max_change = 0
231
- t = Timer()
232
-
233
- while (np.nanmax(LE_Wm2_change) >= LE_convergence_target and iteration <= max_iterations):
234
- logger.info(f"running STIC iteration {cl.val(iteration)} / {cl.val(max_iterations)}")
235
-
236
- if Rg_Wm2 is None:
237
- SM, SMrz, Ms, s1, e0, e0star, Tsd_C, D0, alphaN = iterate_without_solar(
238
- LE = LE_Wm2_new, # Latent heat flux (W/m^2)
239
- PET = PET_Wm2, # Potential evapotranspiration (W/m^2)
240
- SM = SM,
241
- ST_C = ST_C, # Surface temperature (°C)
242
- Ta_C = Ta_C, # Air temperature (°C)
243
- dTS = dTS_C, # Surface-air temperature difference (°C)
244
- T0 = T0_C, # Reference temperature (°C)
245
- gB = gB_ms, # Boundary layer conductance (m/s)
246
- gS = gS_ms, # Stomatal conductance (m/s)
247
- Ea_hPa = Ea_hPa, # Actual vapor pressure (hPa)
248
- Td_C = Td_C, # Dew point temperature (°C)
249
- VPD_hPa = VPD_hPa, # Vapor pressure deficit (hPa)
250
- Estar = Estar_hPa, # Saturation vapor pressure at surface temperature (hPa)
251
- delta = delta_hPa, # Slope of the saturation vapor pressure-temperature curve (hPa/°C)
252
- phi = phi_Wm2, # available energy (W/m^2)
253
- Ds = Ds, # Vapor pressure deficit at source (hPa)
254
- Es = Es_hPa, # Saturation vapor pressure (hPa)
255
- s3 = s3, # Slope of the saturation vapor pressure and temperature
256
- s4 = s44, # Slope of the saturation vapor pressure and temperature
257
- gB_by_gS = gB_by_gS, # Ratio of boundary layer conductance to stomatal conductance
258
- gamma_hPa = gamma_hPa, # Psychrometric constant (hPa/°C)
259
- rho_kgm3 = rho_kgm3, # Air density (kg/m^3)
260
- Cp_Jkg = Cp_Jkg # Specific heat at constant pressure (J/kg/K)
261
- )
262
- else:
263
- SM, G, e0, e0star, D0, alphaN = iterate_with_solar(
264
- seconds_of_day = seconds_of_day, # Seconds of the day
265
- ST_C = ST_C, # Soil temperature (°C)
266
- NDVI = NDVI, # Normalized Difference Vegetation Index
267
- albedo = albedo, # Albedo
268
- gB_ms = gB_ms, # boundary layer conductance (m/s)
269
- gS_ms = gS_ms, # stomatal conductance (m/s)
270
- LE_Wm2 = LE_Wm2_new, # latent heat flux (W/m^2)
271
- Rg_Wm2 = Rg_Wm2, # Incoming solar radiation (W/m^2)
272
- Rn_Wm2 = Rn_Wm2, # Net radiation (W/m^2)
273
- LWnet_Wm2 = LWnet_Wm2, # Net longwave radiation (W/m^2)
274
- Ta_C = Ta_C, # Air temperature (°C)
275
- dTS_C = dTS_C, # Change in soil temperature (°C)
276
- Td_C = Td_C, # Dew point temperature (°C)
277
- Tsd_C = Tsd_C, # Soil dew point temperature (°C)
278
- Ea_hPa = Ea_hPa, # actual vapor pressure (hPa)
279
- Estar_hPa = Estar_hPa, # saturation vapor pressure at surface temperature (hPa)
280
- VPD_hPa = VPD_hPa, # Vapor pressure deficit (hPa)
281
- SVP_hPa = SVP_hPa, # Saturation vapor pressure (hPa)
282
- delta_hPa = delta_hPa, # Slope of the saturation vapor pressure-temperature curve (hPa/°C)
283
- phi_Wm2 = phi_Wm2, # Net radiation minus soil heat flux (W/m^2)
284
- Es_hPa = Es_hPa, # Saturation vapor pressure (hPa)
285
- s1 = s1, # Soil moisture parameter
286
- s3 = s3, # Soil moisture parameter
287
- FVC = FVC, # Fractional canopy cover
288
- T0_C = T0_C, # Reference temperature (°C)
289
- gB_by_gS = gB_by_gS, # Ratio of boundary layer conductance to stomatal conductance
290
- gamma_hPa = gamma_hPa, # Psychrometric constant (hPa/°C)
291
- rho_kgm3 = rho_kgm3, # Air density (kg/m^3)
292
- Cp_Jkg = Cp_Jkg, # Specific heat at constant pressure (J/kg/K)
293
- G_method = "santanello" # Method for calculating soil heat flux
294
- )
295
-
296
- if use_variable_alpha:
297
- alpha = alphaN
298
- logger.info(f"using variable Priestley-Taylor alpha with mean: {cl.val(np.round(np.nanmean(alpha), 3))}")
299
-
300
- # re-estimated conductances and states
301
- gB_ms, gS_ms, dT_C, EF = STIC_closure(
302
- delta_hPa=delta_hPa, # Slope of the saturation vapor pressure-temperature curve (hPa/°C)
303
- phi_Wm2=phi_Wm2, # available energy (W/m^2)
304
- Es_hPa=Es_hPa, # Vapor pressure at the reference height (hPa)
305
- Ea_hPa=Ea_hPa, # Actual vapor pressure (hPa)
306
- Estar_hPa=Estar_hPa, # Saturation vapor pressure at the reference height (hPa)
307
- SM=SM, # Soil moisture (m³/m³)
308
- gamma_hPa=gamma_hPa, # Psychrometric constant (hPa/°C)
309
- rho_kgm3=rho_kgm3, # Air density (kg/m³)
310
- Cp_Jkg=Cp_Jkg, # Specific heat capacity of air (J/kg/°C)
311
- alpha=alpha # Stability correction factor for conductance
312
- )
313
-
314
- gB_by_gS = rt.where(gS_ms == 0, 0, gB_ms / gS_ms)
315
- T0_C = dT_C + Ta_C
316
- # latent heat flux
317
- LE_Wm2_new = ((delta_hPa * phi_Wm2 + rho_kgm3 * Cp_Jkg * gB_ms * VPD_hPa) / (delta_hPa + gamma_hPa * (1 + gB_by_gS)))
318
- LE_Wm2_new = rt.where(LE_Wm2_new > phi_Wm2, phi_Wm2, LE_Wm2_new)
319
- # Sensible Heat Flux
320
- H_Wm2 = ((gamma_hPa * phi_Wm2 * (1 + gB_by_gS) - rho_kgm3 * Cp_Jkg * gB_ms * VPD_hPa) / (delta_hPa + gamma_hPa * (1 + (gB_by_gS))))
321
- # potential evaporation (Penman)
322
- PET_Wm2 = ((delta_hPa * phi_Wm2 + rho_kgm3 * Cp_Jkg * gB_ms * VPD_hPa) / (delta_hPa + gamma_hPa))
323
- # Potential Transpiration
324
- PT_Wm2 = (delta_hPa * phi_Wm2 + rho_kgm3 * Cp_Jkg * gB_ms * VPD_hPa) / (delta_hPa + gamma_hPa * (1 + SM * gB_by_gS)) # potential transpiration
325
- # ET PARTITIONING
326
- LE_soil_Wm2 = rt.clip(SM * PET_Wm2, 0, None)
327
- LE_transpiration_Wm2 = rt.clip(LE_Wm2_new - LE_soil_Wm2, 0, None)
328
- # change in latent heat flux estimate
329
- LE_Wm2_change = np.abs(LE_Wm2_old - LE_Wm2_new)
330
- LE_Wm2_new = rt.where(np.isnan(LE_Wm2_new), LE_Wm2_old, LE_Wm2_new)
331
- LE_Wm2_old = LE_Wm2_new
332
- LE_Wm2_max_change = np.nanmax(LE_Wm2_change)
333
- logger.info(
334
- f"completed STIC iteration {cl.val(iteration)} / {cl.val(max_iterations)} with max LE change: {cl.val(np.round(LE_Wm2_max_change, 3))} ({t} seconds)")
335
-
336
- diagnostic(SM, f"SM_{iteration}", **diag_kwargs)
337
- diagnostic(G, f"G_{iteration}", **diag_kwargs)
338
- diagnostic(LE_Wm2_new, f"LE_{iteration}", **diag_kwargs)
339
-
340
- if LE_Wm2_max_change <= LE_convergence_target:
341
- logger.info(f"max LE change {cl.val(np.round(LE_Wm2_max_change, 3))} within convergence target {cl.val(np.round(LE_convergence_target, 3))} with {cl.val(iteration)} iteration{'s' if iteration > 1 else ''}")
342
-
343
- iteration += 1
344
-
345
- iteration -= 1
346
- results["LE_max_change"] = LE_Wm2_max_change
347
- results["iteration"] = iteration
348
-
349
- LE = LE_Wm2_new
350
-
351
- results["LE"] = LE
352
- results["LE_change"] = LE_Wm2_change
353
- results["LEt"] = LE_transpiration_Wm2
354
- results["PT"] = PT_Wm2
355
- results["PET"] = PET_Wm2
356
- results["G"] = G
357
-
358
- if isinstance(geometry, RasterGeometry):
359
- for name, array in results.items():
360
- try:
361
- results[name] = Raster(array.reshape(geometry.shape), geometry=geometry)
362
- except Exception as e:
363
- pass
364
-
365
- results["LE"].cmap = ET_COLORMAP
366
- results["PET"].cmap = ET_COLORMAP
367
-
368
- warnings.resetwarnings()
369
-
370
- return results
1
+ from .model import *
2
+ from .generate_STIC_inputs import generate_STIC_inputs
3
+ from .process_STIC_table import process_STIC_table
@@ -0,0 +1,11 @@
1
+ from typing import Union
2
+ import numpy as np
3
+ from rasters import Raster
4
+
5
+ def celcius_to_kelvin(T_C: Union[Raster, np.ndarray]) -> Union[Raster, np.ndarray]:
6
+ """
7
+ convert temperature in celsius to kelvin.
8
+ :param T_C: temperature in celsius
9
+ :return: temperature in kelvin
10
+ """
11
+ return T_C + 273.15
@@ -0,0 +1,65 @@
1
+ import logging
2
+
3
+ import numpy as np
4
+ from dateutil import parser
5
+ from pandas import DataFrame
6
+ from rasters import Point
7
+ from sentinel_tiles import sentinel_tiles
8
+ from solar_apparent_time import UTC_to_solar
9
+ from SEBAL_soil_heat_flux import calculate_SEBAL_soil_heat_flux
10
+
11
+ from .model import STIC_JPL, MAX_ITERATIONS, USE_VARIABLE_ALPHA
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+ def generate_STIC_inputs(STIC_inputs_from_calval_df: DataFrame) -> DataFrame:
16
+ """
17
+ STIC_inputs_from_claval_df:
18
+ Pandas DataFrame containing the columns: tower, lat, lon, time_UTC, albedo, elevation_km
19
+ return:
20
+ Pandas DataFrame containing the columns: tower, lat, lon, time_UTC, doy, albedo, elevation_km, AOT, COT, vapor_gccm, ozone_cm, SZA, KG
21
+ """
22
+ # output_rows = []
23
+ STIC_inputs_df = STIC_inputs_from_calval_df.copy()
24
+
25
+ hour_of_day = []
26
+ doy = []
27
+ Topt = []
28
+ fAPARmax = []
29
+
30
+ for i, input_row in STIC_inputs_from_calval_df.iterrows():
31
+ tower = input_row.tower
32
+ lat = input_row.lat
33
+ lon = input_row.lon
34
+ time_UTC = input_row.time_UTC
35
+ albedo = input_row.albedo
36
+ elevation_km = input_row.elevation_km
37
+ logger.info(f"collecting STIC inputs for tower {tower} lat {lat} lon {lon} time {time_UTC} UTC")
38
+ time_UTC = parser.parse(str(time_UTC))
39
+ time_solar = UTC_to_solar(time_UTC, lon)
40
+ hour_of_day.append(time_solar.hour)
41
+ doy.append(time_UTC.timetuple().tm_yday)
42
+ date_UTC = time_UTC.date()
43
+ tile = sentinel_tiles.toMGRS(lat, lon)[:5]
44
+ tile_grid = sentinel_tiles.grid(tile=tile, cell_size=70)
45
+ rows, cols = tile_grid.shape
46
+ row, col = tile_grid.index_point(Point(lon, lat))
47
+ geometry = tile_grid[max(0, row - 1):min(row + 2, rows - 1),
48
+ max(0, col - 1):min(col + 2, cols - 1)]
49
+
50
+ if not "hour_of_day" in STIC_inputs_df.columns:
51
+ STIC_inputs_df["hour_of_day"] = hour_of_day
52
+
53
+ if not "doy" in STIC_inputs_df.columns:
54
+ STIC_inputs_df["doy"] = doy
55
+
56
+ if not "Topt" in STIC_inputs_df.columns:
57
+ STIC_inputs_df["Topt"] = Topt
58
+
59
+ if not "fAPARmax" in STIC_inputs_df.columns:
60
+ STIC_inputs_df["fAPARmax"] = fAPARmax
61
+
62
+ if "Ta" in STIC_inputs_df and "Ta_C" not in STIC_inputs_df:
63
+ STIC_inputs_df.rename({"Ta": "Ta_C"}, inplace=True)
64
+
65
+ return STIC_inputs_df
@@ -5,8 +5,7 @@ import rasters as rt
5
5
 
6
6
  from rasters import Raster
7
7
 
8
- from .vegetation_conversion.vegetation_conversion import FVC_from_NDVI
9
- from .soil_heat_flux import calculate_SEBAL_soil_heat_flux
8
+ from SEBAL_soil_heat_flux import calculate_SEBAL_soil_heat_flux
10
9
 
11
10
  from .constants import *
12
11
  from .soil_moisture_initialization import initialize_soil_moisture
@@ -5,7 +5,7 @@ import rasters as rt
5
5
 
6
6
  from rasters import Raster
7
7
 
8
- from .soil_heat_flux import calculate_SEBAL_soil_heat_flux
8
+ from SEBAL_soil_heat_flux import calculate_SEBAL_soil_heat_flux
9
9
 
10
10
  from .constants import *
11
11
  from .canopy_air_stream import calculate_canopy_air_stream_vapor_pressure