Newer
Older
{
"cells": [
{
"cell_type": "markdown",
Oscar Corvi
committed
"id": "freelance-regression",
"duration": 0.0592,
"end_time": "2021-07-14T08:10:32.620877",
"start_time": "2021-07-14T08:10:32.561677",
"status": "completed"
},
"tags": []
},
"source": [
"# **Location of the stress factor in potential evapo-transpiration models**"
]
},
{
"cell_type": "markdown",
Oscar Corvi
committed
"id": "confused-special",
"duration": 0.039443,
"end_time": "2021-07-14T08:10:32.700359",
"start_time": "2021-07-14T08:10:32.660916",
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
"status": "completed"
},
"slideshow": {
"slide_type": "slide"
},
"tags": []
},
"source": [
"# Part I - Methodology \n",
"\n",
"## <u> Motivation </u> \n",
"\n",
"### Theoretical background\n",
"\n",
"This notebook focuses mainly on the physical meaning of the stress factor whenn put in front of the potential evapo-transpiration model. Thus it will mainly investigate the *constant surface conductance model* which is expressed as: \n",
"\n",
"\\begin{align}\n",
" E_{a, cst} = f_{PAR}.S(\\theta).E_{p,PM}(\\textbf{X})\n",
"\\end{align}\n",
"\n",
"For more details about the formulation of the model and the associated potential evapo-transpiration model, see *location_stress_factor.ipynb* notebook. \n",
"\n",
"In the literature, the stress factor put in front of the potential evapo-transpiration model is often interpretated as the shrinkage in the leaf area cover over time. In this notebook we investigate the information contained within the stress factor and the meaning of the stress factor in order to better interprete this coefficient\n",
"\n",
"### Modelling experiements\n",
"\n",
"Two main experiments are carried out to infer the hypothesis : \n",
"1. The stress factor is reconstructed out of the observations and compared to our artificial stress factor\n",
"2. The model is computed with and without the fPAR coefficient to infer the information contained in this time serie\n",
"\n",
"🚧 All the newly constructed models in this notebook are not multiply by the fPAR factor (classical Penman-Monteith model, varying surface conductance and constant surface conductance models) 🚧"
]
},
{
"cell_type": "markdown",
Oscar Corvi
committed
"id": "qualified-brooklyn",
"duration": 0.041269,
"end_time": "2021-07-14T08:10:32.782574",
"start_time": "2021-07-14T08:10:32.741305",
"status": "completed"
},
"tags": []
},
"source": [
"# Part II - Functions set up"
]
},
{
"cell_type": "markdown",
Oscar Corvi
committed
"id": "direct-florida",
"duration": 0.041576,
"end_time": "2021-07-14T08:10:32.888116",
"start_time": "2021-07-14T08:10:32.846540",
"status": "completed"
},
"tags": []
},
"source": [
"## Importing relevant packages"
]
},
{
"cell_type": "code",
"execution_count": 1,
Oscar Corvi
committed
"id": "sought-alpha",
"duration": 3.72075,
"end_time": "2021-07-14T08:10:36.650740",
"start_time": "2021-07-14T08:10:32.929990",
"status": "completed"
},
"tags": []
},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
Oscar Corvi
committed
"WARNING (aesara.link.c.cmodule): install mkl with `conda install mkl-service`: No module named 'mkl'\n",
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
"WARNING (aesara.tensor.blas): Using NumPy C-API based implementation for BLAS functions.\n"
]
}
],
"source": [
"# data manipulation and plotting\n",
"import pandas as pd\n",
"import matplotlib.pyplot as plt\n",
"from matplotlib._layoutgrid import plot_children\n",
"from matplotlib.patches import Polygon\n",
"from collections import OrderedDict\n",
"from IPython.display import display\n",
"import os # to look into the other folders of the project\n",
"import importlib.util # to open the .py files written somewhere else\n",
"#sns.set_theme(style=\"whitegrid\")\n",
"\n",
"# Sympy and sympbolic mathematics\n",
"from sympy import (asin, cos, diff, Eq, exp, init_printing, log, pi, sin, \n",
" solve, sqrt, Symbol, symbols, tan, Abs)\n",
"from sympy.physics.units import convert_to\n",
"init_printing() \n",
"from sympy.printing import StrPrinter\n",
"from sympy import Piecewise\n",
"StrPrinter._print_Quantity = lambda self, expr: str(expr.abbrev) # displays short units (m instead of meter)\n",
"from sympy.printing.aesaracode import aesara_function\n",
"from sympy.physics.units import * # Import all units and dimensions from sympy\n",
"from sympy.physics.units.systems.si import dimsys_SI, SI\n",
"\n",
"# for ESSM, environmental science for symbolic math, see https://github.com/environmentalscience/essm\n",
"from essm.variables._core import BaseVariable, Variable\n",
"from essm.equations import Equation\n",
"from essm.variables.units import derive_unit, SI, Quantity\n",
"from essm.variables.utils import (extract_variables, generate_metadata_table, markdown, \n",
" replace_defaults, replace_variables, subs_eq)\n",
"from essm.variables.units import (SI_BASE_DIMENSIONS, SI_EXTENDED_DIMENSIONS, SI_EXTENDED_UNITS,\n",
" derive_unit, derive_baseunit, derive_base_dimension)\n",
"\n",
"# For netCDF\n",
"import netCDF4\n",
"import numpy as np\n",
"import xarray as xr\n",
"import warnings\n",
"from netCDF4 import Dataset\n",
"\n",
"# For regressions\n",
"from sklearn.linear_model import LinearRegression\n",
"\n",
"# Deactivate unncessary warning messages related to a bug in Numpy\n",
"warnings.simplefilter(action='ignore', category=FutureWarning)\n",
"\n",
"# for calibration\n",
"from scipy import optimize\n",
"\n",
"from random import random"
]
},
{
"cell_type": "markdown",
Oscar Corvi
committed
"id": "systematic-direction",
"duration": 0.041355,
"end_time": "2021-07-14T08:10:36.745575",
"start_time": "2021-07-14T08:10:36.704220",
"status": "completed"
},
"tags": []
},
"source": [
"## Path of the different files (pre-defined python functions, sympy equations, sympy variables)"
]
},
{
"cell_type": "code",
"execution_count": 2,
Oscar Corvi
committed
"id": "excessive-serbia",
"duration": 0.057001,
"end_time": "2021-07-14T08:10:36.868031",
"start_time": "2021-07-14T08:10:36.811030",
"status": "completed"
},
"tags": [
"parameters"
]
},
"outputs": [],
"source": [
"path_variable = '../../theory/pyFile_storage/theory_variable.py'\n",
"path_equation = '../../theory/pyFile_storage/theory_equation.py' \n",
"path_analysis_functions = '../../theory/pyFile_storage/analysis_functions.py'\n",
"path_data = '../../../data/eddycovdata/'\n",
"dates_fPAR = '../../../data/fpar_howard_spring/dates_v5'\n",
"\n",
"stress_factor_reconstruct = \"stress_factor_reconstruct.png\"\n",
"constant_VS_fPAR = \"constant_VS_fPAR.png\"\n",
"complete_VS_incomplete = \"complete_VS_incomplete.png\""
]
},
{
"cell_type": "code",
"execution_count": 3,
Oscar Corvi
committed
"id": "european-volleyball",
"duration": 0.052884,
"end_time": "2021-07-14T08:10:36.968510",
"start_time": "2021-07-14T08:10:36.915626",
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
"status": "completed"
},
"tags": [
"injected-parameters"
]
},
"outputs": [],
"source": [
"# Parameters\n",
"path_variable = \"notebooks/theory/pyFile_storage/theory_variable.py\"\n",
"path_equation = \"notebooks/theory/pyFile_storage/theory_equation.py\"\n",
"path_analysis_functions = \"notebooks/theory/pyFile_storage/analysis_functions.py\"\n",
"path_data = \"data/eddycovdata/\"\n",
"dates_fPAR = \"data/fpar_howard_spring/dates_v5\"\n",
"stress_factor_reconstruct = (\n",
" \"notebooks/Finished_project/meaning_stress_factor/stress_factor_reconstruct.png\"\n",
")\n",
"constant_VS_fPAR = (\n",
" \"notebooks/Finished_project/meaning_stress_factor/constant_VS_fPAR.png\"\n",
")\n",
"complete_VS_incomplete = (\n",
" \"notebooks/Finished_project/meaning_stress_factor/complete_VS_incomplete.png\"\n",
")\n"
]
},
{
"cell_type": "markdown",
Oscar Corvi
committed
"id": "catholic-chair",
"duration": 0.039846,
"end_time": "2021-07-14T08:10:37.050415",
"start_time": "2021-07-14T08:10:37.010569",
"status": "completed"
},
"tags": []
},
"source": [
"## Importing the sympy variables and equations defined in the theory.ipynb notebook"
]
},
{
"cell_type": "code",
"execution_count": 4,
Oscar Corvi
committed
"id": "dimensional-stadium",
"duration": 1.031068,
"end_time": "2021-07-14T08:10:38.124485",
"start_time": "2021-07-14T08:10:37.093417",
"status": "completed"
},
"tags": []
},
"outputs": [
{
Oscar Corvi
committed
"ename": "FileNotFoundError",
"evalue": "[Errno 2] No such file or directory: 'notebooks/theory/pyFile_storage/theory_variable.py'",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mFileNotFoundError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-4-2f6bab27e197>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[0mspec\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mimportlib\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mutil\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mspec_from_file_location\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mname_code\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mcode\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[0mmod\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mimportlib\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mutil\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mmodule_from_spec\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mspec\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 5\u001b[0;31m \u001b[0mspec\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mloader\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mexec_module\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mmod\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 6\u001b[0m \u001b[0mnames\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mgetattr\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mmod\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m'__all__'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m[\u001b[0m\u001b[0mn\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mn\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mdir\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mmod\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0;32mnot\u001b[0m \u001b[0mn\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mstartswith\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'_'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 7\u001b[0m \u001b[0mglob\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mglobals\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;32m/opt/conda/lib/python3.8/importlib/_bootstrap_external.py\u001b[0m in \u001b[0;36mexec_module\u001b[0;34m(self, module)\u001b[0m\n",
"\u001b[0;32m/opt/conda/lib/python3.8/importlib/_bootstrap_external.py\u001b[0m in \u001b[0;36mget_code\u001b[0;34m(self, fullname)\u001b[0m\n",
"\u001b[0;32m/opt/conda/lib/python3.8/importlib/_bootstrap_external.py\u001b[0m in \u001b[0;36mget_data\u001b[0;34m(self, path)\u001b[0m\n",
"\u001b[0;31mFileNotFoundError\u001b[0m: [Errno 2] No such file or directory: 'notebooks/theory/pyFile_storage/theory_variable.py'"
]
}
],
"source": [
"for code in [path_variable,path_equation]:\n",
" name_code = code[-20:-3]\n",
" spec = importlib.util.spec_from_file_location(name_code, code)\n",
" mod = importlib.util.module_from_spec(spec)\n",
" spec.loader.exec_module(mod)\n",
" names = getattr(mod, '__all__', [n for n in dir(mod) if not n.startswith('_')])\n",
" glob = globals()\n",
" for name in names:\n",
" print(name)\n",
" glob[name] = getattr(mod, name)"
]
},
{
"cell_type": "markdown",
Oscar Corvi
committed
"id": "exterior-juvenile",
"duration": 0.042755,
"end_time": "2021-07-14T08:10:38.223363",
"start_time": "2021-07-14T08:10:38.180608",
"status": "completed"
},
"tags": []
},
"source": [
"## Importing the performance assessment functions defined in the analysis_function.py file"
]
},
{
"cell_type": "code",
Oscar Corvi
committed
"execution_count": null,
"id": "color-soldier",
"duration": 0.073377,
"end_time": "2021-07-14T08:10:38.337504",
"start_time": "2021-07-14T08:10:38.264127",
"status": "completed"
},
"tags": []
},
Oscar Corvi
committed
"outputs": [],
"source": [
"for code in [path_analysis_functions]:\n",
" name_code = code[-20:-3]\n",
" spec = importlib.util.spec_from_file_location(name_code, code)\n",
" mod = importlib.util.module_from_spec(spec)\n",
" spec.loader.exec_module(mod)\n",
" names = getattr(mod, '__all__', [n for n in dir(mod) if not n.startswith('_')])\n",
" glob = globals()\n",
" for name in names:\n",
" print(name)\n",
" glob[name] = getattr(mod, name)"
]
},
{
"cell_type": "markdown",
Oscar Corvi
committed
"id": "starting-increase",
"duration": 0.045483,
"end_time": "2021-07-14T08:10:38.431044",
"start_time": "2021-07-14T08:10:38.385561",
"status": "completed"
},
"tags": []
},
"source": [
"## Data import, preprocess and shape for the computations"
]
},
{
"cell_type": "markdown",
Oscar Corvi
committed
"id": "engaged-individual",
"duration": 0.042185,
"end_time": "2021-07-14T08:10:38.519083",
"start_time": "2021-07-14T08:10:38.476898",
"status": "completed"
},
"tags": []
},
"source": [
"### Get the different files where data are stored\n",
"\n",
"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",
Oscar Corvi
committed
"execution_count": null,
"id": "continued-convert",
"duration": 0.066559,
"end_time": "2021-07-14T08:10:38.626555",
"start_time": "2021-07-14T08:10:38.559996",
"status": "completed"
},
"tags": []
},
Oscar Corvi
committed
"outputs": [],
"source": [
"fPAR_files = []\n",
"eddy_files = []\n",
"\n",
"for file in os.listdir(path_data):\n",
" if file.endswith(\".txt\"):\n",
" fPAR_files.append(os.path.join(path_data, file))\n",
" elif file.endswith(\".nc\"):\n",
" eddy_files.append(os.path.join(path_data, file))\n",
" \n",
"fPAR_files.sort()\n",
"print(fPAR_files)\n",
"eddy_files.sort()\n",
"print(eddy_files)"
]
},
{
"cell_type": "markdown",
Oscar Corvi
committed
"id": "composite-postage",
"duration": 0.042106,
"end_time": "2021-07-14T08:10:38.718167",
"start_time": "2021-07-14T08:10:38.676061",
"status": "completed"
},
"tags": []
},
"source": [
"### Define and test a function that process the fPAR data\n",
"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",
Oscar Corvi
committed
"execution_count": null,
"id": "fitted-covering",
"duration": 0.062848,
"end_time": "2021-07-14T08:10:38.822883",
"start_time": "2021-07-14T08:10:38.760035",
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
"status": "completed"
},
"tags": []
},
"outputs": [],
"source": [
"def fPAR_data_process(fPAR_file,dates_fPAR):\n",
" \n",
" fparv5_dates = np.genfromtxt(dates_fPAR, dtype='str', delimiter=',')\n",
" fparv5_dates = pd.to_datetime(fparv5_dates[:,1], format=\"%Y%m\")\n",
" dates_pd = pd.date_range(fparv5_dates[0], fparv5_dates[-1], freq='MS')\n",
"\n",
" fparv5_howard = np.loadtxt(fPAR_file,delimiter=',', usecols=3 )\n",
" fparv5_howard[fparv5_howard == -999] = np.nan\n",
" fparv5_howard_pd = pd.Series(fparv5_howard, index = fparv5_dates)\n",
" fparv5_howard_pd = fparv5_howard_pd.resample('MS').max()\n",
"\n",
" # convert fparv5_howard_pd to dataframe\n",
" fPAR_pd = pd.DataFrame(fparv5_howard_pd)\n",
" fPAR_pd = fPAR_pd.rename(columns={0:\"fPAR\"})\n",
" fPAR_pd.index = fPAR_pd.index.rename(\"time\")\n",
"\n",
" # convert fPAR_pd to xarray to aggregate the data\n",
" fPAR_xr = fPAR_pd.to_xarray()\n",
" fPAR_agg = fPAR_xr.fPAR.groupby('time.month').max()\n",
"\n",
" # convert back to dataframe\n",
" fPAR_pd = fPAR_agg.to_dataframe()\n",
" Month = np.arange(1,13)\n",
" Month_df = pd.DataFrame(Month)\n",
" Month_df.index = fPAR_pd.index\n",
" Month_df = Month_df.rename(columns={0:\"Month\"})\n",
"\n",
" fPAR_mon = pd.concat([fPAR_pd,Month_df], axis = 1)\n",
" \n",
" return(fPAR_mon)"
]
},
{
"cell_type": "code",
Oscar Corvi
committed
"execution_count": null,
"id": "applicable-democrat",
"duration": 0.104666,
"end_time": "2021-07-14T08:10:38.976656",
"exception": false,
"start_time": "2021-07-14T08:10:38.871990",
"status": "completed"
Oscar Corvi
committed
"outputs": [],
"source": [
"fPAR_data_process(fPAR_files[3],dates_fPAR)"
]
},
{
"cell_type": "markdown",
Oscar Corvi
committed
"id": "elder-hungarian",
"duration": 0.041494,
"end_time": "2021-07-14T08:10:39.073683",
"exception": false,
"start_time": "2021-07-14T08:10:39.032189",
"status": "completed"
},
"tags": []
},
"source": [
"### fPARSet function\n",
"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",
Oscar Corvi
committed
"execution_count": null,
"id": "wicked-cheat",
"duration": 0.061067,
"end_time": "2021-07-14T08:10:39.177546",
"exception": false,
"start_time": "2021-07-14T08:10:39.116479",
"status": "completed"
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
},
"tags": []
},
"outputs": [],
"source": [
"def fPARSet(df_add, fPAR_pd):\n",
" \n",
" # construct the time serie of the fPAR coefficients\n",
" dummy_len = df_add[\"Fe\"].size\n",
" fPAR_val = np.zeros((dummy_len,))\n",
" \n",
" dummy_pd = df_add\n",
" dummy_pd.reset_index(inplace=True)\n",
" dummy_pd.index=dummy_pd.time\n",
" \n",
" month_pd = dummy_pd['time'].dt.month\n",
" \n",
" for i in range(dummy_len):\n",
" current_month = month_pd.iloc[i]\n",
" line_fPAR = fPAR_pd[fPAR_pd['Month'] == current_month]\n",
" fPAR_val[i] = line_fPAR['fPAR']\n",
" \n",
" # transform fPAR_val into dataframe to concatenate to df:\n",
" fPAR = pd.DataFrame(fPAR_val, index = df_add.index)\n",
" df_add = pd.concat([df_add,fPAR], axis = 1)\n",
" df_add = df_add.rename(columns = {0:\"fPAR\"})\n",
" \n",
" return(df_add)"
]
},
{
"cell_type": "markdown",
Oscar Corvi
committed
"id": "critical-concentrate",
"duration": 0.040534,
"end_time": "2021-07-14T08:10:39.266361",
"exception": false,
"start_time": "2021-07-14T08:10:39.225827",
"status": "completed"
},
"tags": []
},
"source": [
"### DataChose function\n",
"\n",
"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\n",
"\n",
"List of variable abbreviation : \n",
"* `Rn` : Net radiation flux\n",
"* `G` : Ground heat flux \n",
"* `Sws` : soil moisture\n",
"* `Ta` : Air temperature\n",
"* `RH` : Relative humidity\n",
"* `W` : Wind speed\n",
"* `E` : measured evaporation\n",
"* `VPD` : Vapour pressure deficit"
]
},
{
"cell_type": "code",
Oscar Corvi
committed
"execution_count": null,
"id": "wrapped-portfolio",
"duration": 0.069988,
"end_time": "2021-07-14T08:10:39.378864",
"exception": false,
"start_time": "2021-07-14T08:10:39.308876",
"status": "completed"
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
},
"tags": []
},
"outputs": [],
"source": [
"def DataChose(ds_ref, period_sel, fPAR_given, Freq = \"D\", sel_period_flag = True):\n",
" \"\"\"Take subset of dataset if Flag == True, entire dataset else\n",
" \n",
" ds_ref: xarray object to be considered as the ref for selecting attributes\n",
" agg_flag: aggregate the data at daily time scale if true\n",
" Flag: select specific period if true (by default)\n",
" period: time period to be selected\n",
" ----------\n",
" Method : \n",
" - transform the xarray in panda dataframe for faster iteration\n",
" - keep only the necessary columns : Fe, Fn, Fg, Ws, Sws, Ta, ustar, RH\n",
" - transform / create new variables : Temperature in °C, T_min/T_max, RH_min/RH_max\n",
" - create the Data vector (numpy arrays)\n",
" - create back a xarray \n",
" - return an xarray\n",
" ----------\n",
" \n",
" Returns an xarray and a Data vector\n",
" \"\"\"\n",
" \n",
" if sel_period_flag:\n",
" df = ds_ref.sel(time = period_sel) \n",
" # nameXarray_output = period + \"_\" + nameXarray_output\n",
" else : \n",
" df = ds_ref\n",
" \n",
" # keep only the columns of interest\n",
" 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\"]]\n",
" \n",
" # convert to dataframe\n",
" df = df.to_dataframe()\n",
" \n",
" # aggregate following the rule stated in freq\n",
" df = df.groupby([pd.Grouper(level = \"latitude\"), pd.Grouper(level = \"longitude\"), pd.Grouper(level = \"time\", freq = Freq)]).mean()\n",
" \n",
" # convert data to the good units : \n",
" df[\"Fe\"] = df[\"Fe\"]/2.45e6 # divide by latent heat of vaporization\n",
" df[\"Ta\"] = df[\"Ta\"]+273 # convert to kelvin\n",
" df[\"VPD\"] = df[\"VPD\"]*1000 # convert from kPa to Pa\n",
" \n",
" # construct the time serie of the fPAR coefficients\n",
" df = fPARSet(df,fPAR_given)\n",
" \n",
" # initialise array for the error\n",
" Error_obs = np.zeros((df.Fe.size,))\n",
" \n",
" for i in range(df.Fe.size):\n",
" size_window_left, size_window_right = min(i,7),min(df.Fe.size - i-1, 7)\n",
" #print(size_window_left, size_window_right)\n",
" sub_set = df.Fe[i-size_window_left : i+size_window_right].to_numpy()\n",
" mean_set = np.mean(sub_set)\n",
" sdt_set = np.std(sub_set)\n",
" error_obs = 2*sdt_set\n",
" Error_obs[i] = error_obs\n",
" \n",
" ErrorObs = pd.DataFrame(Error_obs, index = df.index)\n",
" \n",
" df = pd.concat([df,ErrorObs], axis = 1)\n",
" df = df.rename(columns = {0:\"error\"})\n",
"\n",
" \n",
" return(df)"
]
},
{
"cell_type": "markdown",
Oscar Corvi
committed
"id": "elder-revolution",
"duration": 0.075969,
"end_time": "2021-07-14T08:10:39.514180",
"exception": false,
"start_time": "2021-07-14T08:10:39.438211",
"status": "completed"
},
"tags": []
},
"source": [
"## Compile the different functions defined in the symbolic domain\n",
"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",
Oscar Corvi
committed
"id": "invisible-elephant",
"duration": 0.041165,
"end_time": "2021-07-14T08:10:39.596338",
"exception": false,
"start_time": "2021-07-14T08:10:39.555173",
"status": "completed"
},
"tags": []
},
"source": [
"### Water stress functions"
]
},
{
"cell_type": "code",
Oscar Corvi
committed
"execution_count": null,
"id": "subtle-playlist",
"duration": 0.060137,
"end_time": "2021-07-14T08:10:39.699375",
"exception": false,
"start_time": "2021-07-14T08:10:39.639238",
"status": "completed"
},
"tags": []
},
"outputs": [],
"source": [
"def rising_slope_compiled():\n",
" \"\"\"Compile the slope of the function between theta 4 and theta 3\"\"\"\n",
" \n",
" rising_slope = aesara_function([theta,theta_3, theta_4], [eq_theta_4_3.rhs], dims = {theta:1, theta_3:1, theta_4:1})\n",
" \n",
" return(rising_slope)\n",
"\n",
"def desc_slope_compiled():\n",
" \"\"\"Compile the slope of the function between theta 2 and theta 1\"\"\"\n",
" \n",
" desc_slope = aesara_function([theta,theta_1, theta_2], [eq_theta_2_1.rhs], dims = {theta:1, theta_1:1, theta_2:1})\n",
" \n",
" return(desc_slope)"
]
},
{
"cell_type": "markdown",
Oscar Corvi
committed
"id": "wanted-waters",
"duration": 0.042043,
"end_time": "2021-07-14T08:10:39.787729",
"exception": false,
"start_time": "2021-07-14T08:10:39.745686",
"status": "completed"
},
"tags": []
},
"source": [
"### Soil water potential"
]
},
{
"cell_type": "code",
Oscar Corvi
committed
"execution_count": null,
"id": "prostate-greene",
"duration": 0.056894,
"end_time": "2021-07-14T08:10:39.885852",
"exception": false,
"start_time": "2021-07-14T08:10:39.828958",
"status": "completed"
},
"tags": []
},
"outputs": [],
"source": [
"def relative_saturation_compiled(ThetaRes, ThetaSat):\n",
" \"\"\"Compile the relative saturation function of a soil\"\"\"\n",
" Dict_value = {theta_res : ThetaRes, theta_sat : ThetaSat}\n",
" \n",
" S_mvg_func = aesara_function([theta], [eq_sat_degree.rhs.subs(Dict_value)], dims = {theta:1})\n",
" \n",
" return(S_mvg_func)"
]
},
{
"cell_type": "code",
Oscar Corvi
committed
"execution_count": null,
"id": "western-former",
"duration": 0.052,
"end_time": "2021-07-14T08:10:39.981810",
"exception": false,
"start_time": "2021-07-14T08:10:39.929810",
"status": "completed"
},
"tags": []
},
"outputs": [],
"source": [
"def Psi_compiled(alphaVal, nVal):\n",
" \"\"\"Compile the soil water retention function as function of theta\"\"\"\n",
" mVal = 1-1/nVal\n",
" \n",
" Dict_value = {alpha : alphaVal, n : nVal, m : mVal}\n",
" \n",
" Psi_function = aesara_function([S_mvg], [eq_MVG_h.rhs.subs(Dict_value)], dims = {S_mvg:1})\n",
" \n",
" return(Psi_function)"
]
},
{
"cell_type": "markdown",
Oscar Corvi
committed
"id": "hispanic-clothing",
"duration": 0.042184,
"end_time": "2021-07-14T08:10:40.066191",
"exception": false,
"start_time": "2021-07-14T08:10:40.024007",
"status": "completed"
},
"tags": []
},
"source": [
"### Penman-Monteith"
]
},
{
"cell_type": "code",
Oscar Corvi
committed
"execution_count": null,
"id": "available-speech",
"duration": 0.0561,
"end_time": "2021-07-14T08:10:40.164341",
"exception": false,
"start_time": "2021-07-14T08:10:40.108241",
"status": "completed"
},
"tags": []
},
"outputs": [],
"source": [
"def Delta_compiled():\n",
" \"\"\"Compile the Delta function\"\"\"\n",
" \n",
" # creating the dictionnary with all default values from the above defined constants\n",
" var_dict = Variable.__defaults__.copy()\n",
" \n",
" # computing delta values out of temperature values (slope of the water pressure curve)\n",
" Delta_func = aesara_function([T],[eq_Delta.rhs.subs(var_dict)], dims = {T:1})\n",
" \n",
" return(Delta_func)"
]
},
{
"cell_type": "code",
Oscar Corvi
committed
"execution_count": null,
"id": "civilian-internet",
"duration": 0.054693,
"end_time": "2021-07-14T08:10:40.263957",
"exception": false,
"start_time": "2021-07-14T08:10:40.209264",
"status": "completed"
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
},
"tags": []
},
"outputs": [],
"source": [
"def VH_func_compiled(z_val):\n",
" \"\"\"Compute the vegetation height function\n",
" --------------------------------------------------------\n",
" z : height of the measurements (m)\n",
" kappa : Von Karman constant\n",
" \n",
" w : wind velocity (m/s)\n",
" u_star : shear stress velocity (m/s)\n",
" --------------------------------------------------------\n",
" \n",
" Return a function with w and u_star as degrees of freedom\n",
" \"\"\"\n",
" # get the constant values\n",
" Dict_value = {z:z_val,kappa:kappa.definition.default}\n",
" \n",
" # compile the function\n",
" VH_func = aesara_function([w,u_star],[VH.definition.expr.subs(Dict_value)], dims = {w:1, u_star:1})\n",
" \n",
" return(VH_func)"
]
},
{
"cell_type": "code",
Oscar Corvi
committed
"execution_count": null,
"id": "verbal-attribute",
"duration": 0.055865,
"end_time": "2021-07-14T08:10:40.366001",
"exception": false,
"start_time": "2021-07-14T08:10:40.310136",
"status": "completed"
},
"tags": []
},
"outputs": [],
"source": [
"def d_func_compiled():\n",
" \"\"\"Compile the zero plane displacement height function\n",
" --------------------------------------------------------\n",
" VH : Vegetation height\n",
" --------------------------------------------------------\n",
" \n",
" return a function with VH as degree of freedom\n",
" \"\"\"\n",
" \n",
" # compile the function \n",
" d_func = aesara_function([VH], [d.definition.expr], dims = {VH:1})\n",
" \n",
" return(d_func)"
]
},
{
"cell_type": "code",
Oscar Corvi
committed
"execution_count": null,
"id": "polyphonic-allocation",
"duration": 0.060782,
"end_time": "2021-07-14T08:10:40.472892",
"exception": false,
"start_time": "2021-07-14T08:10:40.412110",
"status": "completed"
},
"tags": []
},
"outputs": [],
"source": [
"def zom_func_compiled():\n",
" \"\"\"Compile the characteristic momentum height exchange\n",
" --------------------------------------------------------\n",
" VH : Vegetation height\n",
" --------------------------------------------------------\n",
" \n",
" return a function with VH as degree of freedom\n",
" \"\"\"\n",
" \n",
" # compile the function \n",
" zom_func = aesara_function([VH], [z_om.definition.expr], dims = {VH:1})\n",
" \n",
" return(zom_func)"
]
},
{
"cell_type": "code",
Oscar Corvi
committed
"execution_count": null,
"id": "overall-squad",
"duration": 0.055894,
"end_time": "2021-07-14T08:10:40.584745",
"exception": false,
"start_time": "2021-07-14T08:10:40.528851",
"status": "completed"
},
"tags": []
},
"outputs": [],
"source": [
"def zoh_func_compiled():\n",
" \"\"\"Compile the characteristic heat height exchange\n",
" --------------------------------------------------------\n",
" VH : Vegetation height\n",
" --------------------------------------------------------\n",
" \n",
" return a function with VH as degree of freedom\n",
" \"\"\"\n",
" \n",
" # compile the function \n",
" zoh_func = aesara_function([z_om], [z_oh.definition.expr], dims = {z_om:1})\n",
" \n",
" return(zoh_func)"
]
},
{
"cell_type": "code",
Oscar Corvi
committed
"execution_count": null,
"id": "graduate-genome",
"duration": 0.061431,
"end_time": "2021-07-14T08:10:40.693945",
"exception": false,
"start_time": "2021-07-14T08:10:40.632514",
"status": "completed"