Commit e5d31b17 authored by Oscar Corvi's avatar Oscar Corvi
Browse files

presentation of the jupyter notebook location_stress_factor.ipynb

parent 8c8b2a62
Pipeline #228940 passed with stage
in 21 seconds
......@@ -59,3 +59,4 @@ notebooks/var_VS_cst/heat_map_var_cst_models.png filter=lfs diff=lfs merge=lfs -
notebooks/var_VS_cst/influence_atmospheric_factors.png filter=lfs diff=lfs merge=lfs -text
notebooks/var_VS_cst/localisation_model_performance.png filter=lfs diff=lfs merge=lfs -text
notebooks/var_VS_cst/sensitivity_varying_cst_model.png filter=lfs diff=lfs merge=lfs -text
notebooks/Finished_project/location_stress_factor/location_stress_factor.slides.html filter=lfs diff=lfs merge=lfs -text
%% Cell type:markdown id:advanced-precipitation tags:
%% Cell type:markdown id:experimental-dollar tags:
 
# **Location of the stress factor in potential evapo-transpiration models**
 
%% Cell type:markdown id:ideal-flower tags:
%% Cell type:markdown id:convinced-cargo tags:
 
# Part I - Methodology
 
## <u> Motivation </u>
 
### Theoretical background
 
In the literature, different approaches to scale potential evapo-transpiration to actual evapo-transpiration accouting for water stress conditions can be found. In this work we investigate only the approaches using a stress factor which lowers potential evapo-transpiration down to actual evapo-transpiration (Barton 1979, Fisher et al. 2008, Martens et al. 2017, Miralles et al. 2011). Different definitions of the stress factor can be encountered, with different mathematical shapes and taking different parameters into account. In this study, we only consider the soil water content, $\theta$, and we define the stress function as a simple piecewise linear function :
 
\begin{equation}
F(\theta) =
\begin{cases}
0 & \theta < \theta_4\\
\frac{\theta-\theta_4}{\theta_3 - \theta_4} & \theta_4 < \theta < \theta_3\\
1 & \theta > \theta_3
\end{cases}
\end{equation}
 
Different models are being developped out of different potential evapo-transpiration models to assess the potential of this method. Especially, we are here interested in assessing the position of this stress factor by combining it with the Penman-Monteith model :
 
\begin{equation}\label{PM_eq}
E_{p,PM} = \frac{1}{\lambda}\frac{\Delta (R_n - G) + \rho_a c_p g_a VPD}{\Delta + \gamma \left( 1- \frac{g_a}{g_s} \right)}
\end{equation}
 
Two new models accouting for a reduction in the evapo-transpirative rate are constructed. The first one in the *constant surface conductance model*:
\begin{align}
E_{a, cst} = f_{PAR}.S(\theta).E_{p,PM}(\textbf{X})
\end{align}
The second one is referred to as the *varying surface conductance model*:
\begin{align}
E_{a, var} = f_{PAR}.E_{p,PM}(\textbf{X},S(\theta))
\end{align}
 
### Modelling experiements
 
Different experiments are carried out to infer the best possible model between the constant surface conductance and varying surface conductance models:
1. Both models are calibrated for a single year and their ability to reproduce an observed time serie is assessed
2. Their prediction capability is evaluated by randomly taking one or several years of data from the Howard Springs dataset, calibrating the model for this specific year and predicting the evapo-transpiration time serie for the other years.
3. The same procedure is repeated across different sites in Australia
 
%% Cell type:markdown id:fantastic-supplement tags:
%% Cell type:markdown id:thrown-teddy tags:
 
# Part II - Functions set up
 
%% Cell type:markdown id:checked-bolivia tags:
%% Cell type:markdown id:chicken-campus tags:
 
## Importing relevant packages
 
%% Cell type:code id:narrow-psychology tags:
%% Cell type:code id:powered-representation tags:
 
``` python
# data manipulation and plotting
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib._layoutgrid import plot_children
from collections import OrderedDict
from IPython.display import display
import os # to look into the other folders of the project
import importlib.util # to open the .py files written somewhere else
#sns.set_theme(style="whitegrid")
 
# Sympy and sympbolic mathematics
from sympy import (asin, cos, diff, Eq, exp, init_printing, log, pi, sin,
solve, sqrt, Symbol, symbols, tan, Abs)
from sympy.physics.units import convert_to
init_printing()
from sympy.printing import StrPrinter
from sympy import Piecewise
StrPrinter._print_Quantity = lambda self, expr: str(expr.abbrev) # displays short units (m instead of meter)
from sympy.printing.aesaracode import aesara_function
from sympy.physics.units import * # Import all units and dimensions from sympy
from sympy.physics.units.systems.si import dimsys_SI, SI
 
# for ESSM, environmental science for symbolic math, see https://github.com/environmentalscience/essm
from essm.variables._core import BaseVariable, Variable
from essm.equations import Equation
from essm.variables.units import derive_unit, SI, Quantity
from essm.variables.utils import (extract_variables, generate_metadata_table, markdown,
replace_defaults, replace_variables, subs_eq)
from essm.variables.units import (SI_BASE_DIMENSIONS, SI_EXTENDED_DIMENSIONS, SI_EXTENDED_UNITS,
derive_unit, derive_baseunit, derive_base_dimension)
 
# For netCDF
import netCDF4
import numpy as np
import xarray as xr
import warnings
from netCDF4 import Dataset
 
# For regressions
from sklearn.linear_model import LinearRegression
 
# Deactivate unncessary warning messages related to a bug in Numpy
warnings.simplefilter(action='ignore', category=FutureWarning)
 
# for calibration
from scipy import optimize
 
from random import random
```
 
%%%% Output: stream
 
WARNING (aesara.link.c.cmodule): install mkl with `conda install mkl-service`: No module named 'mkl'
WARNING (aesara.tensor.blas): Using NumPy C-API based implementation for BLAS functions.
 
%% Cell type:markdown id:analyzed-christianity tags:
%% Cell type:markdown id:blocked-calendar tags:
 
## Path of the different files (pre-defined python functions, sympy equations, sympy variables)
 
%% Cell type:code id:focal-board tags:
%% Cell type:code id:acoustic-limitation tags:
 
``` python
path_variable = '../../theory/pyFile_storage/theory_variable.py'
path_equation = '../../theory/pyFile_storage/theory_equation.py'
path_analysis_functions = '../../theory/pyFile_storage/analysis_functions.py'
path_data = '../../../data/eddycovdata/'
```
 
%% Cell type:markdown id:regional-tractor tags:
%% Cell type:markdown id:thirty-liberty tags:
 
## Importing the sympy variables and equations defined in the theory.ipynb notebook
 
%% Cell type:code id:metallic-transition tags:
%% Cell type:code id:heard-pricing tags:
 
``` python
for code in [path_variable,path_equation]:
name_code = code[-20:-3]
spec = importlib.util.spec_from_file_location(name_code, code)
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
names = getattr(mod, '__all__', [n for n in dir(mod) if not n.startswith('_')])
glob = globals()
for name in names:
print(name)
glob[name] = getattr(mod, name)
```
 
%%%% Output: stream
 
theta_sat
theta_res
alpha
n
m
S_mvg
theta
h
S
theta_4
theta_3
theta_2
theta_1
L
Mw
Pv
Pvs
R
T
c1
T0
Delta
E
G
H
Rn
LE
gamma
alpha_PT
c_p
w
kappa
z
u_star
VH
d
z_om
z_oh
r_a
g_a
r_s
g_s
c1_e
c2_e
e
T_min
T_max
RH_max
RH_min
e_a
e_s
iv_T
T_kv
P
rho_a
VPD
eq_m_n
eq_MVG_neg_case
eq_MVG
eq_sat_degree
eq_MVG_h
eq_h_FC
eq_theta_4_3
eq_theta_2_1
eq_water_stress_simple
eq_Pvs_T
eq_Delta
eq_PT
eq_PM
eq_PM_VPD
eq_PM_g
eq_PM_inv
 
%% Cell type:markdown id:greatest-lucas tags:
%% Cell type:markdown id:weighted-toilet tags:
 
## Importing the performance assessment functions defined in the analysis_function.py file
 
%% Cell type:code id:communist-throw tags:
%% Cell type:code id:removed-three tags:
 
``` python
for code in [path_analysis_functions]:
name_code = code[-20:-3]
spec = importlib.util.spec_from_file_location(name_code, code)
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
names = getattr(mod, '__all__', [n for n in dir(mod) if not n.startswith('_')])
glob = globals()
for name in names:
print(name)
glob[name] = getattr(mod, name)
```
 
%%%% Output: stream
 
AIC
AME
BIC
CD
CP
IoA
KGE
MAE
MARE
ME
MRE
MSRE
MdAPE
NR4MS4E
NRMSE
NS
NSC
PDIFF
PEP
R4MS4E
RAE
RMSE
RVE
np
nt
 
%% Cell type:markdown id:serial-carolina tags:
%% Cell type:markdown id:residential-framework tags:
 
## Data import, preprocess and shape for the computations
 
%% Cell type:markdown id:dense-animal tags:
%% Cell type:markdown id:canadian-response tags:
 
### Get the different files where data are stored
 
Eddy-covariance data from the OzFlux network are stored in **.nc** files (NetCDF4 files) which is roughly a panda data frame with meta-data (see https://www.unidata.ucar.edu/software/netcdf/ for more details about NetCDF4 file format). fPAR data are stored in **.txt** files
 
%% Cell type:code id:institutional-finger tags:
%% Cell type:code id:stupid-brick tags:
 
``` python
fPAR_files = []
eddy_files = []
 
for file in os.listdir(path_data):
if file.endswith(".txt"):
fPAR_files.append(os.path.join(path_data, file))
elif file.endswith(".nc"):
eddy_files.append(os.path.join(path_data, file))
 
fPAR_files.sort()
print(fPAR_files)
eddy_files.sort()
print(eddy_files)
```
 
%%%% Output: stream
 
['../../../data/eddycovdata/fpar_adelaide_v5.txt', '../../../data/eddycovdata/fpar_daly_v5.txt', '../../../data/eddycovdata/fpar_dry_v5.txt', '../../../data/eddycovdata/fpar_howard_v5.txt', '../../../data/eddycovdata/fpar_sturt_v5.txt']
['../../../data/eddycovdata/AdelaideRiver_L4.nc', '../../../data/eddycovdata/DalyUncleared_L4.nc', '../../../data/eddycovdata/DryRiver_L4.nc', '../../../data/eddycovdata/HowardSprings_L4.nc', '../../../data/eddycovdata/SturtPlains_L4.nc']
 
%% Cell type:markdown id:moderate-likelihood tags:
%% Cell type:markdown id:sunset-pizza tags:
 
### Define and test a function that process the fPAR data
In the **.txt** files, only one value per month is given for the fPAR. The following function takes one .txt file containing data about the fPAR coefficients, and the related dates, stored in the a seperate file. The fPAR data (date and coefficients) are cleaned (good string formatting), mapped together and averaged to output one value per month (the fPAR measurement period doesn't spans the measurement period of the eddy covariance data)
 
%% Cell type:code id:ranging-objective tags:
%% Cell type:code id:tribal-johnson tags:
 
``` python
dates_fPAR = '../../../data/fpar_howard_spring/dates_v5'
 
def fPAR_data_process(fPAR_file,dates_fPAR):
 
fparv5_dates = np.genfromtxt(dates_fPAR, dtype='str', delimiter=',')
fparv5_dates = pd.to_datetime(fparv5_dates[:,1], format="%Y%m")
dates_pd = pd.date_range(fparv5_dates[0], fparv5_dates[-1], freq='MS')
 
fparv5_howard = np.loadtxt(fPAR_file,delimiter=',', usecols=3 )
fparv5_howard[fparv5_howard == -999] = np.nan
fparv5_howard_pd = pd.Series(fparv5_howard, index = fparv5_dates)
fparv5_howard_pd = fparv5_howard_pd.resample('MS').max()
 
# convert fparv5_howard_pd to dataframe
fPAR_pd = pd.DataFrame(fparv5_howard_pd)
fPAR_pd = fPAR_pd.rename(columns={0:"fPAR"})
fPAR_pd.index = fPAR_pd.index.rename("time")
 
# convert fPAR_pd to xarray to aggregate the data
fPAR_xr = fPAR_pd.to_xarray()
fPAR_agg = fPAR_xr.fPAR.groupby('time.month').max()
 
# convert back to dataframe
fPAR_pd = fPAR_agg.to_dataframe()
Month = np.arange(1,13)
Month_df = pd.DataFrame(Month)
Month_df.index = fPAR_pd.index
Month_df = Month_df.rename(columns={0:"Month"})
 
fPAR_mon = pd.concat([fPAR_pd,Month_df], axis = 1)
 
return(fPAR_mon)
```
 
%% Cell type:code id:suburban-consumption tags:
%% Cell type:code id:finished-montana tags:
 
``` python
fPAR_data_process(fPAR_files[3],dates_fPAR)
```
 
%%%% Output: execute_result
 
fPAR Month
month
1 0.78 1
2 0.84 2
3 0.79 3
4 0.84 4
5 0.71 5
6 0.75 6
7 0.60 7
8 0.54 8
9 0.52 9
10 0.67 10
11 0.73 11
12 0.78 12
 
%% Cell type:markdown id:drawn-settlement tags:
%% Cell type:markdown id:moral-small tags:
 
### fPARSet function
Map the fPAR time serie to the given eddy-covariance data. Takes two dataframes as input (one containing the fPAR data, the other containing the eddy-covariance data) and returns a data frame where the fPAR monthly values have been scaled to the time scale of the eddy covariance data
 
%% Cell type:code id:infectious-transcript tags:
%% Cell type:code id:adjusted-forwarding tags:
 
``` python
def fPARSet(df_add, fPAR_pd):
 
# construct the time serie of the fPAR coefficients
dummy_len = df_add["Fe"].size
fPAR_val = np.zeros((dummy_len,))
 
dummy_pd = df_add
dummy_pd.reset_index(inplace=True)
dummy_pd.index=dummy_pd.time
 
month_pd = dummy_pd['time'].dt.month
 
for i in range(dummy_len):
current_month = month_pd.iloc[i]
line_fPAR = fPAR_pd[fPAR_pd['Month'] == current_month]
fPAR_val[i] = line_fPAR['fPAR']
 
# transform fPAR_val into dataframe to concatenate to df:
fPAR = pd.DataFrame(fPAR_val, index = df_add.index)
df_add = pd.concat([df_add,fPAR], axis = 1)
df_add = df_add.rename(columns = {0:"fPAR"})
 
return(df_add)
```
 
%% Cell type:markdown id:later-tampa tags:
%% Cell type:markdown id:eight-publisher tags:
 
### DataChose function
 
Function taking the raw netcdf4 data file from the eddy covariance measurement and shape it such that it can be used for the computations. Only relevant variables are kept (latent heat flux, net radiation, ground heat flux, soil water content, wind speed, air temperature, VPD, bed shear stress). The desired data period is selected and is reshaped at the desired time scale (daily by default). Uses the fPARSet function defined above
 
List of variable abbreviation :
* `Rn` : Net radiation flux
* `G` : Ground heat flux
* `Sws` : soil moisture
* `Ta` : Air temperature
* `RH` : Relative humidity
* `W` : Wind speed
* `E` : measured evaporation
* `VPD` : Vapour pressure deficit
 
%% Cell type:code id:worst-identification tags:
%% Cell type:code id:pacific-group tags:
 
``` python
def DataChose(ds_ref, period_sel, fPAR_given, Freq = "D", sel_period_flag = True):
"""Take subset of dataset if Flag == True, entire dataset else
 
ds_ref: xarray object to be considered as the ref for selecting attributes
agg_flag: aggregate the data at daily time scale if true
Flag: select specific period if true (by default)
period: time period to be selected
----------
Method :
- transform the xarray in panda dataframe for faster iteration
- keep only the necessary columns : Fe, Fn, Fg, Ws, Sws, Ta, ustar, RH
- transform / create new variables : Temperature in °C, T_min/T_max, RH_min/RH_max
- create the Data vector (numpy arrays)
- create back a xarray
- return an xarray
----------
 
Returns an xarray and a Data vector
"""
 
if sel_period_flag:
df = ds_ref.sel(time = period_sel)
# nameXarray_output = period + "_" + nameXarray_output
else :
df = ds_ref
 
# keep only the columns of interest
df = df[["Fe","Fn","Fg","Ws","Sws","Ta","ustar","RH", "VPD","ps","Fe_QCFlag","Fn_QCFlag","Fg_QCFlag","Ws_QCFlag","Sws_QCFlag","Ta_QCFlag","ustar_QCFlag","RH_QCFlag", "VPD_QCFlag"]]
 
# convert to dataframe
df = df.to_dataframe()
 
# aggregate following the rule stated in freq
df = df.groupby([pd.Grouper(level = "latitude"), pd.Grouper(level = "longitude"), pd.Grouper(level = "time", freq = Freq)]).mean()
 
# convert data to the good units :
df["Fe"] = df["Fe"]/2.45e6 # divide by latent heat of vaporization
df["Ta"] = df["Ta"]+273 # convert to kelvin
df["VPD"] = df["VPD"]*1000 # convert from kPa to Pa
 
# construct the time serie of the fPAR coefficients
df = fPARSet(df,fPAR_given)
 
# initialise array for the error
Error_obs = np.zeros((df.Fe.size,))
 
for i in range(df.Fe.size):
size_window_left, size_window_right = min(i,7),min(df.Fe.size - i-1, 7)
#print(size_window_left, size_window_right)
sub_set = df.Fe[i-size_window_left : i+size_window_right].to_numpy()
mean_set = np.mean(sub_set)
sdt_set = np.std(sub_set)
error_obs = 2*sdt_set
Error_obs[i] = error_obs
 
ErrorObs = pd.DataFrame(Error_obs, index = df.index)
 
df = pd.concat([df,ErrorObs], axis = 1)
df = df.rename(columns = {0:"error"})
 
 
return(df)
```
 
%% Cell type:markdown id:viral-colon tags:
%% Cell type:markdown id:opponent-circuit tags:
 
## Compile the different functions defined in the symbolic domain
All functions defined with sympy and ESSM are defined in the symbolic domain. In order to be efficiently evaluated, they need to be vectorized to allow computations with numpu arrays. We use the *aesara* printing compiler from the sympy package. Note that this printer replace the older one (*theano*) which is deprecated. A comparison of the performances between the two packages can be found in the aesara repository.
 
%% Cell type:markdown id:silver-bracket tags:
%% Cell type:markdown id:southeast-yield tags:
 
### Water stress functions
 
%% Cell type:code id:deluxe-testimony tags:
%% Cell type:code id:billion-revolution tags:
 
``` python
def rising_slope_compiled():
"""Compile the slope of the function between theta 4 and theta 3"""
 
rising_slope = aesara_function([theta,theta_3, theta_4], [eq_theta_4_3.rhs], dims = {theta:1, theta_3:1, theta_4:1})
 
return(rising_slope)
 
def desc_slope_compiled():
"""Compile the slope of the function between theta 2 and theta 1"""
 
desc_slope = aesara_function([theta,theta_1, theta_2], [eq_theta_2_1.rhs], dims = {theta:1, theta_1:1, theta_2:1})
 
return(desc_slope)
```
 
%% Cell type:markdown id:consistent-atlanta tags:
%% Cell type:markdown id:spatial-economics tags:
 
### Soil water potential
 
%% Cell type:code id:bearing-yukon tags:
%% Cell type:code id:geographic-affiliate tags:
 
``` python
def relative_saturation_compiled(ThetaRes, ThetaSat):
"""Compile the relative saturation function of a soil"""
Dict_value = {theta_res : ThetaRes, theta_sat : ThetaSat}
 
S_mvg_func = aesara_function([theta], [eq_sat_degree.rhs.subs(Dict_value)], dims = {theta:1})
 
return(S_mvg_func)
```
 
%% Cell type:code id:insured-sheet tags:
%% Cell type:code id:incident-ghana tags:
 
``` python
def Psi_compiled(alphaVal, nVal):
"""Compile the soil water retention function as function of theta"""
mVal = 1-1/nVal
 
Dict_value = {alpha : alphaVal, n : nVal, m : mVal}
 
Psi_function = aesara_function([S_mvg], [eq_MVG_h.rhs.subs(Dict_value)], dims = {S_mvg:1})
 
return(Psi_function)
```
 
%% Cell type:markdown id:assumed-coverage tags:
%% Cell type:markdown id:lonely-audio tags:
 
### Penman-Monteith
 
%% Cell type:code id:measured-challenge tags:
%% Cell type:code id:large-property tags:
 
``` python
def Delta_compiled():
"""Compile the Delta function"""
 
# creating the dictionnary with all default values from the above defined constants
var_dict = Variable.__defaults__.copy()
 
# computing delta values out of temperature values (slope of the water pressure curve)
Delta_func = aesara_function([T],[eq_Delta.rhs.subs(var_dict)], dims = {T:1})
 
return(Delta_func)
```
 
%% Cell type:code id:twenty-marketplace tags:
%% Cell type:code id:aggressive-miller tags:
 
``` python
def VH_func_compiled(z_val):
"""Compute the vegetation height function
--------------------------------------------------------
z : height of the measurements (m)
kappa : Von Karman constant
 
w : wind velocity (m/s)
u_star : shear stress velocity (m/s)
--------------------------------------------------------
 
Return a function with w and u_star as degrees of freedom
"""
# get the constant values
Dict_value = {z:z_val,kappa:kappa.definition.default}
 
# compile the function
VH_func = aesara_function([w,u_star],[VH.definition.expr.subs(Dict_value)], dims = {w:1, u_star:1})
 
return(VH_func)
```
 
%% Cell type:code id:proof-conjunction tags:
%% Cell type:code id:disturbed-retention tags:
 
``` python
def d_func_compiled():