Commit fe1b4980 by Oscar Corvi

### add beginning of the meaning of the stress factor in meanin_stress_factor.ipynb

parent eaee969a
Pipeline #229137 passed with stage
in 28 seconds
 %% Cell type:markdown id:abstract-vacation tags: %% Cell type:markdown id:cheap-attribute tags: # **Location of the stress factor in potential evapo-transpiration models** %% Cell type:markdown id:capable-israel tags: %% Cell type:markdown id:based-knight tags: # Part I - Methodology ## Motivation ### 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 : 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} 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 : \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)} 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:nonprofit-ordering tags: %% Cell type:markdown id:touched-oliver tags: # Part II - Functions set up %% Cell type:markdown id:played-python tags: %% Cell type:markdown id:eligible-township tags: ## Importing relevant packages %% Cell type:code id:wrapped-attachment tags: %% Cell type:code id:religious-powder 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:informative-compiler tags: %% Cell type:markdown id:vietnamese-animation tags: ## Path of the different files (pre-defined python functions, sympy equations, sympy variables) %% Cell type:code id:forbidden-enzyme tags: %% Cell type:code id:empty-arrangement 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:representative-currency tags: %% Cell type:markdown id:distributed-accent tags: ## Importing the sympy variables and equations defined in the theory.ipynb notebook %% Cell type:code id:precise-temperature tags: %% Cell type:code id:improving-twins 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:seasonal-bristol tags: %% Cell type:markdown id:desirable-universal tags: ## Importing the performance assessment functions defined in the analysis_function.py file %% Cell type:code id:boxed-assessment tags: %% Cell type:code id:surprising-public 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:later-server tags: %% Cell type:markdown id:valuable-smart tags: ## Data import, preprocess and shape for the computations %% Cell type:markdown id:foster-legislation tags: %% Cell type:markdown id:piano-sharp 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:excess-printer tags: %% Cell type:code id:earlier-davis 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:blessed-organic tags: %% Cell type:markdown id:mexican-landscape 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:static-produce tags: %% Cell type:code id:disciplinary-clone 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:plastic-philippines tags: %% Cell type:code id:soviet-mobile 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:behind-blues tags: %% Cell type:markdown id:dated-issue 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:fitted-involvement tags: %% Cell type:code id:known-sport 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:outstanding-object tags: %% Cell type:markdown id:unnecessary-hunger 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:unavailable-drawing tags: %% Cell type:code id:latest-prerequisite 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:pregnant-success tags: %% Cell type:markdown id:third-optimization 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:incident-original tags: %% Cell type:markdown id:magnetic-slave tags: ### Water stress functions %% Cell type:code id:macro-ceremony tags: %% Cell type:code id:hundred-measurement 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:biblical-drama tags: %% Cell type:markdown id:regular-danish tags: ### Soil water potential %% Cell type:code id:suspected-guarantee tags: %% Cell type:code id:personalized-glenn 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:prepared-medline tags: %% Cell type:code id:naked-guard 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:configured-ethernet tags: %% Cell type:markdown id:bacterial-heater tags: ### Penman-Monteith %% Cell type:code id:boring-bread tags: %% Cell type:code id:established-serial 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:artificial-police tags: %% Cell type:code id:brilliant-dinner 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:partial-attempt tags: %% Cell type:code id:religious-underground tags: ` python def d_func_compiled(): """Compile the zero plane displacement height function -------------------------------------------------------- VH : Vegetation height -------------------------------------------------------- return a function with VH as degree of freedom """