meaning_stress_factor.ran.ipynb 632 KB
Newer Older
1
2
3
4
{
 "cells": [
  {
   "cell_type": "markdown",
5
   "id": "cooperative-notification",
6
7
   "metadata": {
    "papermill": {
8
9
     "duration": 0.071871,
     "end_time": "2021-07-20T13:15:55.071212",
10
     "exception": false,
11
     "start_time": "2021-07-20T13:15:54.999341",
12
13
14
15
16
17
18
19
20
21
     "status": "completed"
    },
    "tags": []
   },
   "source": [
    "# **Location of the stress factor in potential evapo-transpiration models**"
   ]
  },
  {
   "cell_type": "markdown",
22
   "id": "confident-account",
23
24
   "metadata": {
    "papermill": {
25
26
     "duration": 0.060225,
     "end_time": "2021-07-20T13:15:55.195448",
27
     "exception": false,
28
     "start_time": "2021-07-20T13:15:55.135223",
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",
64
   "id": "received-recognition",
65
66
   "metadata": {
    "papermill": {
67
68
     "duration": 0.060889,
     "end_time": "2021-07-20T13:15:55.329816",
69
     "exception": false,
70
     "start_time": "2021-07-20T13:15:55.268927",
71
72
73
74
75
76
77
78
79
80
     "status": "completed"
    },
    "tags": []
   },
   "source": [
    "# Part II - Functions set up"
   ]
  },
  {
   "cell_type": "markdown",
81
   "id": "indonesian-garden",
82
83
   "metadata": {
    "papermill": {
84
85
     "duration": 0.061149,
     "end_time": "2021-07-20T13:15:55.456208",
86
     "exception": false,
87
     "start_time": "2021-07-20T13:15:55.395059",
88
89
90
91
92
93
94
95
96
97
98
     "status": "completed"
    },
    "tags": []
   },
   "source": [
    "## Importing relevant packages"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
99
   "id": "frequent-logistics",
100
   "metadata": {
101
    "execution": {
102
103
104
105
     "iopub.execute_input": "2021-07-20T13:15:55.586604Z",
     "iopub.status.busy": "2021-07-20T13:15:55.581057Z",
     "iopub.status.idle": "2021-07-20T13:16:00.258883Z",
     "shell.execute_reply": "2021-07-20T13:16:00.259874Z"
106
    },
107
    "papermill": {
108
109
     "duration": 4.743091,
     "end_time": "2021-07-20T13:16:00.260468",
110
     "exception": false,
111
     "start_time": "2021-07-20T13:15:55.517377",
112
113
114
115
116
117
118
119
120
     "status": "completed"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
121
122
123
124
125
126
127
      "WARNING (aesara.link.c.cmodule): install mkl with `conda install mkl-service`: No module named 'mkl'\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
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
174
175
176
177
178
179
180
181
182
183
184
185
      "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",
186
   "id": "elegant-timeline",
187
188
   "metadata": {
    "papermill": {
189
190
     "duration": 0.064897,
     "end_time": "2021-07-20T13:16:00.401230",
191
     "exception": false,
192
     "start_time": "2021-07-20T13:16:00.336333",
193
194
195
196
197
198
199
200
201
202
203
     "status": "completed"
    },
    "tags": []
   },
   "source": [
    "## Path of the different files (pre-defined python functions, sympy equations, sympy variables)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
204
   "id": "indonesian-parker",
205
   "metadata": {
206
    "execution": {
207
208
209
210
     "iopub.execute_input": "2021-07-20T13:16:00.547540Z",
     "iopub.status.busy": "2021-07-20T13:16:00.545995Z",
     "iopub.status.idle": "2021-07-20T13:16:00.550599Z",
     "shell.execute_reply": "2021-07-20T13:16:00.549023Z"
211
    },
212
    "papermill": {
213
214
     "duration": 0.08518,
     "end_time": "2021-07-20T13:16:00.550946",
215
     "exception": false,
216
     "start_time": "2021-07-20T13:16:00.465766",
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
     "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,
239
   "id": "descending-rendering",
240
   "metadata": {
241
    "execution": {
242
243
244
245
     "iopub.execute_input": "2021-07-20T13:16:00.708377Z",
     "iopub.status.busy": "2021-07-20T13:16:00.707555Z",
     "iopub.status.idle": "2021-07-20T13:16:00.710880Z",
     "shell.execute_reply": "2021-07-20T13:16:00.711652Z"
246
    },
247
    "papermill": {
248
249
     "duration": 0.096747,
     "end_time": "2021-07-20T13:16:00.711948",
250
     "exception": false,
251
     "start_time": "2021-07-20T13:16:00.615201",
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
     "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",
279
   "id": "considered-texas",
280
281
   "metadata": {
    "papermill": {
282
283
     "duration": 0.060885,
     "end_time": "2021-07-20T13:16:00.845097",
284
     "exception": false,
285
     "start_time": "2021-07-20T13:16:00.784212",
286
287
288
289
290
291
292
293
294
295
296
     "status": "completed"
    },
    "tags": []
   },
   "source": [
    "## Importing the sympy variables and equations defined in the theory.ipynb notebook"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
297
   "id": "clear-bibliography",
298
   "metadata": {
299
    "execution": {
300
301
302
303
     "iopub.execute_input": "2021-07-20T13:16:01.004589Z",
     "iopub.status.busy": "2021-07-20T13:16:01.003422Z",
     "iopub.status.idle": "2021-07-20T13:16:02.594279Z",
     "shell.execute_reply": "2021-07-20T13:16:02.592960Z"
304
    },
305
    "papermill": {
306
307
     "duration": 1.668234,
     "end_time": "2021-07-20T13:16:02.594545",
308
     "exception": false,
309
     "start_time": "2021-07-20T13:16:00.926311",
310
311
312
313
314
315
     "status": "completed"
    },
    "tags": []
   },
   "outputs": [
    {
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "theta_sat\n",
      "theta_res\n",
      "alpha\n",
      "n\n",
      "m\n",
      "S_mvg\n",
      "theta\n",
      "h\n",
      "S\n",
      "theta_4\n",
      "theta_3\n",
      "theta_2\n",
      "theta_1\n",
      "L\n",
      "Mw\n",
      "Pv\n",
      "Pvs\n",
      "R\n",
      "T\n",
      "c1\n",
      "T0\n",
      "Delta\n",
      "E\n",
      "G\n",
      "H\n",
      "Rn\n",
      "LE\n",
      "gamma\n",
      "alpha_PT\n",
      "c_p\n",
      "w\n",
      "kappa\n",
      "z\n",
      "u_star\n",
      "VH\n",
      "d\n",
      "z_om\n",
      "z_oh\n",
      "r_a\n",
      "g_a\n",
      "r_s\n",
      "g_s\n",
      "c1_e\n",
      "c2_e\n",
      "e\n",
      "T_min\n",
      "T_max\n",
      "RH_max\n",
      "RH_min\n",
      "e_a\n",
      "e_s\n",
      "iv_T\n",
      "T_kv\n",
      "P\n",
      "rho_a\n",
      "VPD\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "eq_m_n\n",
      "eq_MVG_neg_case\n",
      "eq_MVG\n",
      "eq_sat_degree\n",
      "eq_MVG_h\n",
      "eq_h_FC\n",
      "eq_theta_4_3\n",
      "eq_theta_2_1\n",
      "eq_water_stress_simple\n",
      "eq_Pvs_T\n",
      "eq_Delta\n",
      "eq_PT\n",
      "eq_PM\n",
      "eq_PM_VPD\n",
      "eq_PM_g\n",
      "eq_PM_inv\n"
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
     ]
    }
   ],
   "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",
415
   "id": "extreme-amendment",
416
417
   "metadata": {
    "papermill": {
418
419
     "duration": 0.073848,
     "end_time": "2021-07-20T13:16:02.735363",
420
     "exception": false,
421
     "start_time": "2021-07-20T13:16:02.661515",
422
423
424
425
426
427
428
429
430
431
     "status": "completed"
    },
    "tags": []
   },
   "source": [
    "## Importing the performance assessment functions defined in the analysis_function.py file"
   ]
  },
  {
   "cell_type": "code",
432
   "execution_count": 5,
433
   "id": "mounted-exception",
434
   "metadata": {
435
    "execution": {
436
437
438
439
     "iopub.execute_input": "2021-07-20T13:16:02.876405Z",
     "iopub.status.busy": "2021-07-20T13:16:02.875613Z",
     "iopub.status.idle": "2021-07-20T13:16:02.890627Z",
     "shell.execute_reply": "2021-07-20T13:16:02.889703Z"
440
    },
441
    "papermill": {
442
443
     "duration": 0.092114,
     "end_time": "2021-07-20T13:16:02.890861",
444
     "exception": false,
445
     "start_time": "2021-07-20T13:16:02.798747",
446
447
448
449
     "status": "completed"
    },
    "tags": []
   },
450
451
452
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
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "AIC\n",
      "AME\n",
      "BIC\n",
      "CD\n",
      "CP\n",
      "IoA\n",
      "KGE\n",
      "MAE\n",
      "MARE\n",
      "ME\n",
      "MRE\n",
      "MSRE\n",
      "MdAPE\n",
      "NR4MS4E\n",
      "NRMSE\n",
      "NS\n",
      "NSC\n",
      "PDIFF\n",
      "PEP\n",
      "R4MS4E\n",
      "RAE\n",
      "RMSE\n",
      "RMedSE\n",
      "RVE\n",
      "bias\n",
      "np\n",
      "nt\n"
     ]
    }
   ],
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
   "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",
500
   "id": "american-soundtrack",
501
502
   "metadata": {
    "papermill": {
503
504
     "duration": 0.067871,
     "end_time": "2021-07-20T13:16:03.025469",
505
     "exception": false,
506
     "start_time": "2021-07-20T13:16:02.957598",
507
508
509
510
511
512
513
514
515
516
     "status": "completed"
    },
    "tags": []
   },
   "source": [
    "## Data import, preprocess and shape for the computations"
   ]
  },
  {
   "cell_type": "markdown",
517
   "id": "unauthorized-bullet",
518
519
   "metadata": {
    "papermill": {
520
521
     "duration": 0.063491,
     "end_time": "2021-07-20T13:16:03.155717",
522
     "exception": false,
523
     "start_time": "2021-07-20T13:16:03.092226",
524
525
526
527
528
529
530
531
532
533
534
535
     "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",
536
   "execution_count": 6,
537
   "id": "bigger-establishment",
538
   "metadata": {
539
    "execution": {
540
541
542
543
     "iopub.execute_input": "2021-07-20T13:16:03.294721Z",
     "iopub.status.busy": "2021-07-20T13:16:03.293304Z",
     "iopub.status.idle": "2021-07-20T13:16:03.298410Z",
     "shell.execute_reply": "2021-07-20T13:16:03.297251Z"
544
    },
545
    "papermill": {
546
547
     "duration": 0.076458,
     "end_time": "2021-07-20T13:16:03.298633",
548
     "exception": false,
549
     "start_time": "2021-07-20T13:16:03.222175",
550
551
552
553
     "status": "completed"
    },
    "tags": []
   },
554
555
556
557
558
559
560
561
562
563
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['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']\n",
      "['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']\n"
     ]
    }
   ],
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
   "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",
582
   "id": "behavioral-secret",
583
584
   "metadata": {
    "papermill": {
585
586
     "duration": 0.068208,
     "end_time": "2021-07-20T13:16:03.433215",
587
     "exception": false,
588
     "start_time": "2021-07-20T13:16:03.365007",
589
590
591
592
593
594
595
596
597
598
599
     "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",
600
   "execution_count": 7,
601
   "id": "extra-medicare",
602
   "metadata": {
603
    "execution": {
604
605
606
607
     "iopub.execute_input": "2021-07-20T13:16:03.580701Z",
     "iopub.status.busy": "2021-07-20T13:16:03.573567Z",
     "iopub.status.idle": "2021-07-20T13:16:03.585661Z",
     "shell.execute_reply": "2021-07-20T13:16:03.584558Z"
608
    },
609
    "papermill": {
610
611
     "duration": 0.089601,
     "end_time": "2021-07-20T13:16:03.586041",
612
     "exception": false,
613
     "start_time": "2021-07-20T13:16:03.496440",
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
     "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",
654
   "execution_count": 8,
655
   "id": "funky-speaking",
656
   "metadata": {
657
    "execution": {
658
659
660
661
     "iopub.execute_input": "2021-07-20T13:16:03.767261Z",
     "iopub.status.busy": "2021-07-20T13:16:03.758518Z",
     "iopub.status.idle": "2021-07-20T13:16:03.811022Z",
     "shell.execute_reply": "2021-07-20T13:16:03.810270Z"
662
    },
663
    "papermill": {
664
665
     "duration": 0.15361,
     "end_time": "2021-07-20T13:16:03.811272",
666
     "exception": false,
667
     "start_time": "2021-07-20T13:16:03.657662",
668
     "status": "completed"
669
670
671
    },
    "tags": []
   },
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>fPAR</th>\n",
       "      <th>Month</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>month</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>0.78</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>0.84</td>\n",
       "      <td>2</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>0.79</td>\n",
       "      <td>3</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>0.84</td>\n",
       "      <td>4</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>0.71</td>\n",
       "      <td>5</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>0.75</td>\n",
       "      <td>6</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>0.60</td>\n",
       "      <td>7</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>0.54</td>\n",
       "      <td>8</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>9</th>\n",
       "      <td>0.52</td>\n",
       "      <td>9</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>10</th>\n",
       "      <td>0.67</td>\n",
       "      <td>10</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>11</th>\n",
       "      <td>0.73</td>\n",
       "      <td>11</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>12</th>\n",
       "      <td>0.78</td>\n",
       "      <td>12</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "       fPAR  Month\n",
       "month             \n",
       "1      0.78      1\n",
       "2      0.84      2\n",
       "3      0.79      3\n",
       "4      0.84      4\n",
       "5      0.71      5\n",
       "6      0.75      6\n",
       "7      0.60      7\n",
       "8      0.54      8\n",
       "9      0.52      9\n",
       "10     0.67     10\n",
       "11     0.73     11\n",
       "12     0.78     12"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
790
791
792
793
794
795
   "source": [
    "fPAR_data_process(fPAR_files[3],dates_fPAR)"
   ]
  },
  {
   "cell_type": "markdown",
796
   "id": "premier-african",
797
798
   "metadata": {
    "papermill": {
799
800
     "duration": 0.06612,
     "end_time": "2021-07-20T13:16:03.971121",
801
     "exception": false,
802
     "start_time": "2021-07-20T13:16:03.905001",
803
     "status": "completed"
804
805
806
807
808
809
810
811
812
813
    },
    "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",
814
   "execution_count": 9,
815
   "id": "gross-photographer",
816
   "metadata": {
817
    "execution": {
818
819
820
821
     "iopub.execute_input": "2021-07-20T13:16:04.164691Z",
     "iopub.status.busy": "2021-07-20T13:16:04.163680Z",
     "iopub.status.idle": "2021-07-20T13:16:04.168039Z",
     "shell.execute_reply": "2021-07-20T13:16:04.167226Z"
822
    },
823
    "papermill": {
824
825
     "duration": 0.113578,
     "end_time": "2021-07-20T13:16:04.168281",
826
     "exception": false,
827
     "start_time": "2021-07-20T13:16:04.054703",
828
     "status": "completed"
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
    },
    "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",
861
   "id": "painted-figure",
862
863
   "metadata": {
    "papermill": {
864
865
     "duration": 0.071629,
     "end_time": "2021-07-20T13:16:04.309928",
866
     "exception": false,
867
     "start_time": "2021-07-20T13:16:04.238299",
868
     "status": "completed"
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
    },
    "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",
890
   "execution_count": 10,
891
   "id": "metropolitan-prevention",
892
   "metadata": {
893
    "execution": {
894
895
896
897
     "iopub.execute_input": "2021-07-20T13:16:04.467979Z",
     "iopub.status.busy": "2021-07-20T13:16:04.466466Z",
     "iopub.status.idle": "2021-07-20T13:16:04.471563Z",
     "shell.execute_reply": "2021-07-20T13:16:04.470476Z"
898
    },
899
    "papermill": {
900
901
     "duration": 0.089446,
     "end_time": "2021-07-20T13:16:04.471861",
902
     "exception": false,
903
     "start_time": "2021-07-20T13:16:04.382415",
904
     "status": "completed"
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
    },
    "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",
976
   "id": "fitted-impact",
977
978
   "metadata": {
    "papermill": {
979
980
     "duration": 0.132504,
     "end_time": "2021-07-20T13:16:04.687658",
981
     "exception": false,
982
     "start_time": "2021-07-20T13:16:04.555154",
983
     "status": "completed"
984
985
986
987
988
989
990
991
992
993
    },
    "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",
994
   "id": "artistic-wrapping",
995
996
   "metadata": {
    "papermill": {
997
998
     "duration": 0.071976,
     "end_time": "2021-07-20T13:16:04.845173",
999
     "exception": false,
1000
     "start_time": "2021-07-20T13:16:04.773197",
1001
     "status": "completed"
1002
1003
1004
1005
1006
1007
1008
1009
1010
    },
    "tags": []
   },
   "source": [
    "### Water stress functions"
   ]
  },
  {
   "cell_type": "code",
1011
   "execution_count": 11,
1012
   "id": "capital-porcelain",
1013
   "metadata": {
1014
    "execution": {
1015
1016
1017
1018
     "iopub.execute_input": "2021-07-20T13:16:04.978301Z",
     "iopub.status.busy": "2021-07-20T13:16:04.977164Z",
     "iopub.status.idle": "2021-07-20T13:16:04.980254Z",
     "shell.execute_reply": "2021-07-20T13:16:04.979659Z"
1019
    },
1020
    "papermill": {
1021
1022
     "duration": 0.073351,
     "end_time": "2021-07-20T13:16:04.980435",
1023
     "exception": false,
1024
     "start_time": "2021-07-20T13:16:04.907084",
1025
     "status": "completed"
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
    },
    "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",
1048
   "id": "beneficial-satisfaction",
1049
1050
   "metadata": {
    "papermill": {
1051
1052
     "duration": 0.059178,
     "end_time": "2021-07-20T13:16:05.104778",
1053
     "exception": false,
1054
     "start_time": "2021-07-20T13:16:05.045600",
1055
     "status": "completed"
1056
1057
1058
1059
1060
1061
1062
1063
1064
    },
    "tags": []
   },
   "source": [
    "### Soil water potential"
   ]
  },
  {
   "cell_type": "code",
1065
   "execution_count": 12,
1066
   "id": "superb-cutting",
1067
   "metadata": {
1068
    "execution": {
1069
1070
1071
1072
     "iopub.execute_input": "2021-07-20T13:16:05.232349Z",
     "iopub.status.busy": "2021-07-20T13:16:05.231710Z",
     "iopub.status.idle": "2021-07-20T13:16:05.235427Z",
     "shell.execute_reply": "2021-07-20T13:16:05.236017Z"
1073
    },
1074
    "papermill": {
1075
1076
     "duration": 0.068804,
     "end_time": "2021-07-20T13:16:05.236261",
1077
     "exception": false,
1078
     "start_time": "2021-07-20T13:16:05.167457",
1079
     "status": "completed"
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
    },
    "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",
1096
   "execution_count": 13,
1097
   "id": "different-mailing",
1098
   "metadata": {
1099
    "execution": {
1100
1101
1102
1103
     "iopub.execute_input": "2021-07-20T13:16:05.360123Z",
     "iopub.status.busy": "2021-07-20T13:16:05.357985Z",
     "iopub.status.idle": "2021-07-20T13:16:05.361561Z",
     "shell.execute_reply": "2021-07-20T13:16:05.362593Z"
1104
    },
1105
    "papermill": {
1106
1107
     "duration": 0.068855,
     "end_time": "2021-07-20T13:16:05.362944",
1108
     "exception": false,
1109
     "start_time": "2021-07-20T13:16:05.294089",
1110
     "status": "completed"
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
    },
    "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",
1129
   "id": "express-marks",
1130
1131
   "metadata": {
    "papermill": {
1132
1133
     "duration": 0.069082,
     "end_time": "2021-07-20T13:16:05.497517",
1134
     "exception": false,
1135
     "start_time": "2021-07-20T13:16:05.428435",
1136
     "status": "completed"
1137
1138
1139
1140
1141
1142
1143
1144
1145
    },
    "tags": []
   },
   "source": [
    "### Penman-Monteith"
   ]
  },
  {
   "cell_type": "code",
1146
   "execution_count": 14,
1147
   "id": "pending-outside",
1148
   "metadata": {
1149
    "execution": {
1150
1151
1152
1153
     "iopub.execute_input": "2021-07-20T13:16:05.629065Z",
     "iopub.status.busy": "2021-07-20T13:16:05.628246Z",
     "iopub.status.idle": "2021-07-20T13:16:05.632201Z",
     "shell.execute_reply": "2021-07-20T13:16:05.631569Z"
1154
    },
1155
    "papermill": {
1156
1157
     "duration": 0.07426,
     "end_time": "2021-07-20T13:16:05.632391",
1158
     "exception": false,
1159
     "start_time": "2021-07-20T13:16:05.558131",
1160
     "status": "completed"
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
    },
    "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",
1180
   "execution_count": 15,
1181
   "id": "supreme-oliver",
1182
   "metadata": {
1183
    "execution": {
1184
1185
1186
1187
     "iopub.execute_input": "2021-07-20T13:16:05.779806Z",
     "iopub.status.busy": "2021-07-20T13:16:05.778832Z",
     "iopub.status.idle": "2021-07-20T13:16:05.783558Z",
     "shell.execute_reply": "2021-07-20T13:16:05.782752Z"
1188
    },
1189
    "papermill": {
1190
1191
     "duration": 0.07987,
     "end_time": "2021-07-20T13:16:05.783835",
1192
     "exception": false,
1193
     "start_time": "2021-07-20T13:16:05.703965",
1194
     "status": "completed"
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
    },
    "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",
1223
   "execution_count": 16,
1224
   "id": "auburn-baker",
1225
   "metadata": {
1226
    "execution": {
1227
1228
1229
1230
     "iopub.execute_input": "2021-07-20T13:16:05.954191Z",
     "iopub.status.busy": "2021-07-20T13:16:05.953229Z",
     "iopub.status.idle": "2021-07-20T13:16:05.955613Z",
     "shell.execute_reply": "2021-07-20T13:16:05.956254Z"
1231
    },
1232
    "papermill": {
1233
1234
     "duration": 0.088342,
     "end_time": "2021-07-20T13:16:05.956509",
1235
     "exception": false,
1236
     "start_time": "2021-07-20T13:16:05.868167",
1237
     "status": "completed"
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
    },
    "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",
1260
   "execution_count": 17,
1261
   "id": "working-hungary",
1262
   "metadata": {
1263
    "execution": {
1264
1265
1266
1267
     "iopub.execute_input": "2021-07-20T13:16:06.118652Z",
     "iopub.status.busy": "2021-07-20T13:16:06.117586Z",
     "iopub.status.idle": "2021-07-20T13:16:06.123191Z",
     "shell.execute_reply": "2021-07-20T13:16:06.121868Z"
1268
    },
1269
    "papermill": {
1270
1271
     "duration": 0.090301,
     "end_time": "2021-07-20T13:16:06.123569",
1272
     "exception": false,
1273
     "start_time": "2021-07-20T13:16:06.033268",
1274
     "status": "completed"
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
    },
    "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",
1297
   "execution_count": 18,
1298
   "id": "electric-campaign",
1299
   "metadata": {
1300
    "execution": {
1301
1302
1303
1304
     "iopub.execute_input": "2021-07-20T13:16:06.285007Z",
     "iopub.status.busy": "2021-07-20T13:16:06.284112Z",
     "iopub.status.idle": "2021-07-20T13:16:06.288137Z",
     "shell.execute_reply": "2021-07-20T13:16:06.288844Z"
1305
    },
1306
    "papermill": {
1307
1308
     "duration": 0.080165,
     "end_time": "2021-07-20T13:16:06.289280",
1309
     "exception": false,
1310
     "start_time": "2021-07-20T13:16:06.209115",
1311
     "status": "completed"
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
    },
    "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",
1334
   "execution_count": 19,
1335
   "id": "regulated-bradley",
1336
   "metadata": {
1337
    "execution": {
1338
1339
1340
1341
     "iopub.execute_input": "2021-07-20T13:16:06.457143Z",
     "iopub.status.busy": "2021-07-20T13:16:06.455881Z",
     "iopub.status.idle": "2021-07-20T13:16:06.460237Z",
     "shell.execute_reply": "2021-07-20T13:16:06.459554Z"
1342
    },
1343
    "papermill": {
1344
1345
     "duration": 0.086256,
     "end_time": "2021-07-20T13:16:06.460448",
1346
     "exception": false,
1347
     "start_time": "2021-07-20T13:16:06.374192",
1348
     "status": "completed"
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "def ra_func_compiled(z_val):\n",
    "    \"\"\"Substitutes the different terms of the r_a expression\n",
    "    --------------------------------------------------------\n",
    "    z : height of the measurement (m)\n",
    "    \n",
    "    d : zero plane displacement height (m)\n",
    "    zoh_val : characteristic height of the heat transfert\n",
    "    zom_val : characteristic height of the momentum transfert\n",
    "    --------------------------------------------------------\n",
    "    \n",
    "    returns the compiled expression of r_a evaluable according to the wind speed\n",
    "    \"\"\"\n",
    "    # evaluate the values in the expression\n",
    "    Dict_value = {z:z_val,kappa:kappa.definition.default}\n",
    "    \n",
    "    # compile the function\n",
    "    ra_func = aesara_function([z_om,z_oh,d,w], [r_a.definition.expr.subs(Dict_value)], dims = {z_om:1,z_oh:1,d:1,w:1})\n",
    "    \n",
    "    return(ra_func)"
   ]
  },
  {
   "cell_type": "code",
1377
   "execution_count": 20,
1378
   "id": "coordinate-colony",
1379
   "metadata": {
1380
    "execution": {
1381
1382
1383
1384
     "iopub.execute_input": "2021-07-20T13:16:06.623178Z",
     "iopub.status.busy": "2021-07-20T13:16:06.622043Z",
     "iopub.status.idle": "2021-07-20T13:16:06.625317Z",
     "shell.execute_reply": "2021-07-20T13:16:06.625984Z"
1385
    },
1386
    "papermill": {
1387
1388
     "duration": 0.085833,
     "end_time": "2021-07-20T13:16:06.626330",
1389
     "exception": false,
1390
     "start_time": "2021-07-20T13:16:06.540497",
1391
     "status": "completed"
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "def PM_compiled():\n",
    "    \"\"\" Compute the compiled version of the PM VPD equation\n",
    "    --------------------------------------------------------\n",
    "    c_p : specific heat of the air\n",
    "    rho_a : mean air density\n",
    "    gamma : psychrometric constant\n",
    "    L : Latent heat flux\n",
    "    \n",
    "    r_s : Surface resistance -> given (can also be modeled)\n",
    "    G : ground heat flux -> comes from the data\n",
    "    Rn : net radiation flux -> comes from the data \n",
    "    Delta : slope of the saturation curve -> computed above\n",
    "    r_a : aerodynamic resistance -> computed above\n",
    "    --------------------------------------------------------\n",
    "    \n",
    "    returns the evaporation flux (in mm/time) with Delta, G, Rn, e_a, e_s, r_a as degrees of freedom\n",
    "    \"\"\"\n",
    "    \n",
    "    # get the constant values\n",
    "    Dict_value = {c_p:c_p.definition.default, rho_a:rho_a.definition.default, L:L.definition.default, gamma:gamma.definition.default}\n",
    "    \n",
    "    # compile the function\n",
    "    PM_func = aesara_function([G,Rn,Delta,VPD,g_a, g_s], [eq_PM_g.rhs.subs(Dict_value)], dims = {G:1,Rn:1,Delta:1,VPD:1,g_a:1, g_s:1})\n",
    "    \n",
    "    return(PM_func)"
   ]
  },
  {
   "cell_type": "code",
1426
   "execution_count": 21,
1427
   "id": "sufficient-found",
1428
   "metadata": {
1429
    "execution": {
1430
1431
1432
1433
     "iopub.execute_input": "2021-07-20T13:16:06.787231Z",
     "iopub.status.busy": "2021-07-20T13:16:06.786398Z",
     "iopub.status.idle": "2021-07-20T13:16:06.791241Z",
     "shell.execute_reply": "2021-07-20T13:16:06.790392Z"
1434
    },
1435
    "papermill": {
1436
1437
     "duration": 0.093666,
     "end_time": "2021-07-20T13:16:06.791434",
1438
     "exception": false,
1439
     "start_time": "2021-07-20T13:16:06.697768",
1440
     "status": "completed"
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "def PT_compiled():\n",
    "    \"\"\"Compute the Priestley-Taylor equation,\n",
    "    need 4 input : temperature, net radiations, ground heat flux and alpha PT parameter\n",
    "    Each must be given as np.array\n",
    "    Return the compiled function\n",
    "    \"\"\"\n",
    "    \n",
    "    # creating the dictionnary with all default values from the above defined constants\n",
    "    var_dict = Variable.__defaults__.copy()\n",
    "    \n",
    "    # Computing the values of evaporation using the Priestley-Taylor model\n",
    "    PT_func = aesara_function([Delta,Rn,G, alpha_PT],[eq_PT.rhs.subs(var_dict)],dims = {Delta:1,Rn:1,G:1, alpha_PT:1})\n",
    "\n",
    "    return(PT_func)"
   ]
  },
  {
   "cell_type": "code",
1464
   "execution_count": 22,
1465
   "id": "cubic-regression",
1466
   "metadata": {
1467
    "execution": {
1468
1469
1470
1471
     "iopub.execute_input": "2021-07-20T13:16:06.935274Z",
     "iopub.status.busy": "2021-07-20T13:16:06.934124Z",
     "iopub.status.idle": "2021-07-20T13:16:06.937504Z",
     "shell.execute_reply": "2021-07-20T13:16:06.938628Z"
1472
    },
1473
    "papermill": {
1474
1475
     "duration": 0.080689,
     "end_time": "2021-07-20T13:16:06.939107",
1476
     "exception": false,
1477
     "start_time": "2021-07-20T13:16:06.858418",
1478
     "status": "completed"
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "def rs_PM_inv():\n",
    "    \"Derive the time serie of the surface resistance out of the observed latent heat fluxes --> inverse modelling of the PM equation\"\n",
    "    \n",
    "    #get the constant values \n",
    "    Dict_value = {c_p:c_p.definition.default, rho_a:rho_a.definition.default, L:L.definition.default, gamma:gamma.definition.default}\n",
    "    \n",
    "    # compile the function\n",
    "    Inv_PM = aesara_function([E,G,Rn,Delta,VPD,r_a], [eq_PM_inv.rhs.subs(Dict_value)], dims = {E:1,G:1,Rn:1,Delta:1,VPD:1,r_a:1})\n",
    "    \n",
    "    return(Inv_PM)"
   ]
  },
  {
   "cell_type": "markdown",
1498
   "id": "weekly-fraction",
1499
1500
   "metadata": {
    "papermill": {
1501
1502
     "duration": 0.065141,
     "end_time": "2021-07-20T13:16:07.068542",
1503
     "exception": false,
1504
     "start_time": "2021-07-20T13:16:07.003401",
1505
     "status": "completed"
1506
1507
1508
1509
1510
1511
1512
1513
1514
    },
    "tags": []
   },
   "source": [
    "### Assign the different compiled functions to variables functions (create the functions in python)"
   ]
  },
  {
   "cell_type": "code",
1515
   "execution_count": 23,
1516
   "id": "forward-basement",
1517
   "metadata": {
1518
    "execution": {
1519
1520
1521
1522
     "iopub.execute_input": "2021-07-20T13:16:07.199948Z",
     "iopub.status.busy": "2021-07-20T13:16:07.198714Z",
     "iopub.status.idle": "2021-07-20T13:16:09.618139Z",
     "shell.execute_reply": "2021-07-20T13:16:09.616964Z"
1523
    },
1524
    "papermill": {
1525
1526
     "duration": 2.489337,
     "end_time": "2021-07-20T13:16:09.618441",
1527
     "exception": false,
1528
     "start_time": "2021-07-20T13:16:07.129104",
1529
     "status": "completed"
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# Water_stress properties: \n",
    "rising_slope = rising_slope_compiled() # takes theta, theta_3, theta_4 in this order as input\n",
    "desc_slope = desc_slope_compiled() # takes theta, theta_1, theta_2 in this order as input\n",
    "\n",
    "# properties : \n",
    "delta_func = Delta_compiled() # takes Ta as input\n",
    "z_val = 23 # change the values of the aerodynamic constants here !!!\n",
    "VH_func = VH_func_compiled(z_val)\n",
    "d_func = d_func_compiled()\n",
    "zom_func = zom_func_compiled()\n",
    "zoh_func = zoh_func_compiled()\n",
    "ra_func = ra_func_compiled(z_val)\n",
    "\n",
    "# models\n",
    "PM_func = PM_compiled()\n",
    "PT_func = PT_compiled()\n",
    "Inv_PM_func = rs_PM_inv()"
   ]
  },
  {
   "cell_type": "code",
1556
   "execution_count": 24,
1557
   "id": "alike-municipality",
1558
   "metadata": {
1559
    "execution": {
1560
1561
1562
1563
     "iopub.execute_input": "2021-07-20T13:16:09.761765Z",
     "iopub.status.busy": "2021-07-20T13:16:09.760909Z",
     "iopub.status.idle": "2021-07-20T13:16:09.765932Z",
     "shell.execute_reply": "2021-07-20T13:16:09.764821Z"
1564
    },
1565
    "papermill": {
1566
1567
     "duration": 0.083035,
     "end_time": "2021-07-20T13:16:09.766244",
1568
     "exception": false,
1569
     "start_time": "2021-07-20T13:16:09.683209",
1570
     "status": "completed"
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "def stress_factor_func(psi_vec,Psi_3,Psi_4):\n",
    "    \n",
    "    Length = psi_vec.size\n",
    "    \n",
    "    Stress_func = np.zeros((Length,))\n",
    "    Psi_3 = np.array([Psi_3])\n",
    "    Psi_4 = np.array([Psi_4])\n",
    "    for j in range(Length):\n",
    "        try:\n",
    "            Psi_val = psi_vec[j]\n",
    "        except Exception as error:\n",
    "            print(psi_vec,error)\n",
    "        # have to convert float to arrays in order to run the compiled functions\n",
    "        Psi_val = np.array([Psi_val])\n",
    "        if (Psi_val < Psi_4):\n",
    "            Stress_func[j] = 0\n",
    "        elif (Psi_val >= Psi_4) & (Psi_val < Psi_3):\n",
    "            Stress_func[j] = float(rising_slope(Psi_val,Psi_3,Psi_4))\n",
    "        else:\n",
    "            Stress_func[j] = 1\n",
    "    return(Stress_func)"
   ]
  },
  {
   "cell_type": "markdown",
1601
   "id": "liberal-theme",
1602
1603
   "metadata": {
    "papermill": {
1604
1605
     "duration": 0.068905,
     "end_time": "2021-07-20T13:16:09.903907",
1606
     "exception": false,
1607
     "start_time": "2021-07-20T13:16:09.835002",
1608
     "status": "completed"
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
    },
    "tags": []
   },
   "source": [
    "## Functions to run the different models\n",
    "Once the functions has been defined in sympy, compiled with aesara and assign to a useful python function, it is now time to link it with the data to carry out the final computations ! All the following functions take a dataframe as input, and the related parameters ($\\theta_3$ and $\\theta_4$ for the stress function) and return a numpy array and a dictionnary containing the values of the model run and some miscellaneous information."
   ]
  },
  {
   "cell_type": "markdown",
1619
   "id": "caroline-annex",
1620
1621
   "metadata": {
    "papermill": {