-
Notifications
You must be signed in to change notification settings - Fork 20
/
get_obs_bysite_fluxnet.R
1454 lines (1219 loc) · 43.9 KB
/
get_obs_bysite_fluxnet.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
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
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
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
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
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
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
861
862
863
864
865
866
867
868
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
897
898
899
900
901
902
903
904
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
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#' Get FLUXNET observational data for one site.
#'
#' Function for reading observational GPP data from FLUXNET dataset
#' and defining calibration target (which flux decomposition method etc.)
#'
#' @param sitename A character string specifying the site name for which
#' FLUXNET data is searched (based on the site name appearing as part
#' of the respective file name). Defaults to NA.
#' @param dir A character string specifying the local path of
#' FLUXNET data.
#' @param dir_hh A character string specifying the local path of
#' half-hourly FLUXNET data, required to get daytime VPD and daily minimum
#' temperature. Defaults to \code{NULL} (no daytime VPD or daily minimum
#' temperature is calculated).
#' @param dir_hr A character string specifying the local path of
#' hourly FLUXNET data, required to get daytime VPD. Defaults to
#' \code{NULL} (no daytime VPD is calculated).
#' @param timescale A character specifying the time scale of FLUXNET
#' data. Any of \code{c("d", "w", "m", "y")} for daily, weekly, monthly,
#' or yearly, respectively.
#' @param getvars A vector of character strings corresponding to the
#' FLUXNET variable names as used in the original data files. See
#' \url{https://fluxnet.fluxdata.org/data/fluxnet2015-dataset/}. If argument
#' \code{getswc==TRUE}, then soil water content data (variables starting with
#' \code{SWC_}) are read.
#' @param getswc If \code{getswc==TRUE}, then all soil water content data
#' (variables starting with \code{"SWC_}) are read. Defaults to \code{TRUE}.
#' @param threshold_GPP A numeric value (between 0 and 1 for daily, weekly,
#' monthly, and annual data or 0 [measured], 1 [good quality gapfill], 2 [
#' medium], 3 [poor] for half-hourly data). The value specifies the
#' threshold for excluding data during data cleaning. The threshold is
#' with respect to the data quality flag in the FLUXNET data, indicating
#' the fraction of measured and good quality gapfilled data for daily, weekly,
#' monthly, and annual data and 0 [measured], 1 [good quality gapfill], 2 [
#' medium], 3 [poor] for half-hourly data. Defaults to \code{threshold_GPP=0}
#' meaning no data is excluded.
#' @param threshold_LE A numeric value (between 0 and 1 for daily, weekly,
#' monthly, and annual data or 0 [measured], 1 [good quality gapfill], 2 [
#' medium], 3 [poor] for half-hourly data). The value specifies the
#' threshold for excluding data during data cleaning. The threshold is
#' with respect to the data quality flag in the FLUXNET data, indicating
#' the fraction of measured and good quality gapfilled data for daily, weekly,
#' monthly, and annual data and 0 [measured], 1 [good quality gapfill], 2 [
#' medium], 3 [poor] for half-hourly data. Defaults to \code{threshold_GPP=0}
#' meaning no data is excluded.
#' @param threshold_H A numeric value (between 0 and 1 for daily, weekly,
#' monthly, and annual data or 0 [measured], 1 [good quality gapfill], 2 [
#' medium], 3 [poor] for half-hourly data). The value specifies the
#' threshold for excluding data during data cleaning. The threshold is
#' with respect to the data quality flag in the FLUXNET data, indicating
#' the fraction of measured and good quality gapfilled data for daily, weekly,
#' monthly, and annual data and 0 [measured], 1 [good quality gapfill], 2 [
#' medium], 3 [poor] for half-hourly data. Defaults to \code{threshold_GPP=0}
#' meaning no data is excluded.
#' @param threshold_SWC A numeric value (between 0 and 1 for daily, weekly,
#' monthly, and annual data or 0 [measured], 1 [good quality gapfill], 2 [
#' medium], 3 [poor] for half-hourly data). The value specifies the
#' threshold for excluding data during data cleaning. The threshold is
#' with respect to the data quality flag in the FLUXNET data, indicating
#' the fraction of measured and good quality gapfilled data for daily, weekly,
#' monthly, and annual data and 0 [measured], 1 [good quality gapfill], 2 [
#' medium], 3 [poor] for half-hourly data. Defaults to \code{threshold_GPP=0}
#' meaning no data is excluded.
#' @param threshold_WS A numeric value (between 0 and 1 for daily, weekly,
#' monthly, and annual data or 0 [measured], 1 [good quality gapfill], 2 [
#' medium], 3 [poor] for half-hourly data). The value specifies the
#' threshold for excluding data during data cleaning. The threshold is
#' with respect to the data quality flag in the FLUXNET data, indicating
#' the fraction of measured and good quality gapfilled data for daily, weekly,
#' monthly, and annual data and 0 [measured], 1 [good quality gapfill], 2 [
#' medium], 3 [poor] for half-hourly data. Defaults to \code{threshold_GPP=0}
#' meaning no data is excluded.
#' @param threshold_USTAR A numeric value (between 0 and 1 for daily, weekly,
#' monthly, and annual data or 0 [measured], 1 [good quality gapfill], 2 [
#' medium], 3 [poor] for half-hourly data). The value specifies the
#' threshold for excluding data during data cleaning. The threshold is
#' with respect to the data quality flag in the FLUXNET data, indicating
#' the fraction of measured and good quality gapfilled data for daily, weekly,
#' monthly, and annual data and 0 [measured], 1 [good quality gapfill], 2 [
#' medium], 3 [poor] for half-hourly data. Defaults to \code{threshold_GPP=0}
#' meaning no data is excluded.
#' @param threshold_T A numeric value (between 0 and 1 for daily, weekly,
#' monthly, and annual data or 0 [measured], 1 [good quality gapfill], 2 [
#' medium], 3 [poor] for half-hourly data). The value specifies the
#' threshold for excluding data during data cleaning. The threshold is
#' with respect to the data quality flag in the FLUXNET data, indicating
#' the fraction of measured and good quality gapfilled data for daily, weekly,
#' monthly, and annual data and 0 [measured], 1 [good quality gapfill], 2 [
#' medium], 3 [poor] for half-hourly data. Defaults to \code{threshold_GPP=0}
#' meaning no data is excluded.
#' @param threshold_NETRAD A numeric value (between 0 and 1 for daily, weekly,
#' monthly, and annual data or 0 [measured], 1 [good quality gapfill], 2 [
#' medium], 3 [poor] for half-hourly data). The value specifies the
#' threshold for excluding data during data cleaning. The threshold is
#' with respect to the data quality flag in the FLUXNET data, indicating
#' the fraction of measured and good quality gapfilled data for daily, weekly,
#' monthly, and annual data and 0 [measured], 1 [good quality gapfill], 2 [
#' medium], 3 [poor] for half-hourly data. Defaults to \code{threshold_GPP=0}
#' meaning no data is excluded.
#' @param filter_ntdt A logical specifying whether agreement of daytime
#' and nighttime-based GPP estimates is to be used as a filter.
#' Data points are removed where their difference is below the the 97.5% and
#' above the 2.5% quantile of all difference values per site.
#' Defaults to \code{FALSE}.
#' @param return_qc A logical specifying whether quality control variables
#' should be returned.
#' @param remove_neg A logical specifying whether negative GPP values are to
#' be removed (replaces with NA).
#' @param getswc include soil water content (TRUE/FALSE, default = TRUE)
#' @param verbose verbose output
#'
#' @return A data frame (tibble) containing cleaned observational data,
#' named and in units corresponding to rsofun standard.
#' @export
#'
#' @examples \dontrun{
#' df <- get_obs_bysite_fluxnet
#' }
#'
get_obs_bysite_fluxnet <- function(
sitename,
dir,
dir_hh=NULL,
dir_hr = NULL,
timescale,
getvars,
getswc = TRUE,
threshold_GPP = 0.0,
threshold_LE = 0.0,
threshold_H = 0.0,
threshold_SWC = 0.0,
threshold_WS = 0.0,
threshold_USTAR = 0.0,
threshold_T = 0.0,
threshold_NETRAD = 0.0,
filter_ntdt = FALSE,
return_qc = FALSE,
remove_neg = FALSE,
verbose = TRUE
){
# CRAN compliance, define variables
year <- week <- VPD_F <- VPD_F_QC <- VPD_F_MDS <- VPD_ERA <-
moy <- TA_F <- . <- res <- soilm_obs_mean <- vpd_day <-
TA_F_QC <- TA_F_MDS <- TA_F_MDS_QC <- TA_ERA <- VPD_F_MDS_QC <-
vpd <- patm <- ppfd <- prec <- NULL
if (verbose) print(paste("Getting FLUXNET data for", sitename, "..."))
# Define what exactly is to be read
# make a vector
getvars_orig <- getvars
getvars <- getvars %>%
unlist() %>%
unname()
# complement getvars if necessary, i.e. when filter_ntdt is TRUE
added <- c("")
if (is.null(filter_ntdt)) filter_ntdt <- FALSE
if (filter_ntdt && timescale == "d"){
# NEEDS DIFFERENT COLUMNS FOR HH OR DD
if ("GPP_NT_VUT_REF" %in% getvars){
toadd <- c("GPP_DT_VUT_REF", "NEE_VUT_REF_DAY_QC", "NEE_VUT_REF_NIGHT_QC")
getvars <- c(getvars, toadd) %>%
unique()
added <- c(added, toadd)
}
if ("GPP_DT_VUT_REF" %in% getvars){
toadd <- c( "GPP_NT_VUT_REF", "NEE_VUT_REF_NIGHT_QC", "NEE_VUT_REF_DAY_QC")
getvars <- c(getvars, toadd) %>%
unique()
added <- c(added, toadd)
}
}
if (any(grepl("GPP_", getvars))) {
if ("GPP_NT_VUT_REF" %in% getvars) {
toadd <- c("NEE_VUT_REF_NIGHT_QC","NEE_VUT_REF_QC")
getvars <- c(getvars, toadd) %>%
unique()
added <- c(added, toadd)
}
if ("GPP_DT_VUT_REF" %in% getvars) {
toadd <- c("NEE_VUT_REF_DAY_QC","NEE_VUT_REF_QC")
getvars <- c(getvars, toadd) %>%
unique()
added <- c(added, toadd)
}
}
if (any(grepl("LE_", getvars))) {
if ("LE_F_MDS" %in% getvars) {
toadd <- "LE_F_MDS_QC"
getvars <- c(getvars, toadd) %>%
unique()
added <- c(added, toadd)
}
}
# Take only file for this site
if (timescale == "d") {
# Daily
filn <- list.files(dir,
pattern = paste0("FLX_", sitename, ".*_FULLSET_DD.*.csv"),
recursive = TRUE
)
} else if (timescale == "w") {
# Weekly
filn <- list.files(dir,
pattern = paste0("FLX_", sitename, ".*_FULLSET_WW.*.csv"),
recursive = TRUE
)
} else if (timescale == "m") {
# Monthly
filn <- list.files(dir,
pattern = paste0("FLX_", sitename, ".*_FULLSET_MM.*.csv"),
recursive = TRUE
)
} else if (timescale=="y" || timescale == "a") {
# Annual
filn <- list.files(dir,
pattern = paste0("FLX_", sitename, ".*_FULLSET_YY.*.csv"),
recursive = TRUE
)
} else if (timescale == "hh") {
# half-hourly
filn <- list.files( dir,
pattern = paste0( "FLX_", sitename, ".*_FULLSET_HH.*.csv" ),
recursive = TRUE
)
}
if (length(filn) == 0) {
stop(
paste0("No files found for timescale ",
timescale,
" in sub-directories of ",
dir))
}
if (length(filn) > 1) {
file.info_getsize <- function(filn){
file.info(filn)$size
}
warning("Reading only largest daily file available")
path_dd <- file.path(dir, filn)
size_vec <- purrr::map_dbl(as.list(path_dd), ~file.info_getsize(.))
path_dd <- path_dd[which.max(size_vec)]
filn <- basename(path_dd)
}
#---- Actually read data ----
# This returns a data frame with columns
# (date, temp, prec, nrad, ppfd, vpd, ccov)
df <- get_obs_fluxnet2015_raw(
sitename,
path = file.path(dir, filn),
freq = timescale
)
# For some sites, the NETRAD column is missing.
if ("NETRAD" %in% getvars && !("NETRAD" %in% names(df))) {
df <- df %>%
mutate(
NETRAD = NA,
NETRAD_QC = 0.0
)
}
# Get daytime VPD
merge_df_vpd_day_dd <- FALSE
if ("VPD_F_DAY" %in% getvars && !(timescale == "hh")) {
# 1. Check whether daily file for daytime VPD is already available
# get file name(s) of file containing daily daytime VPD derived from half-hourly data
filename_dd_vpd <- list.files(
dir,
pattern = paste0("FLX_", sitename, ".*_VPD_DAY.csv"),
recursive = FALSE
)
if (length(filename_dd_vpd)>0){
# Read available file
if (length(filename_dd_vpd)>1){
file.info_getsize <- function(filn){
file.info(filn)$size
}
warning("Reading only largest daily VPD file available")
path_dd_vpd <- file.path(dir_hh, filename_dd_vpd)
size_vec <- purrr::map_dbl(as.list(path_dd_vpd), ~file.info_getsize(.))
path_dd_vpd <- path_dd_vpd[which.max(size_vec)]
filename_dd_vpd <- basename(path_dd_vpd)
}
# read directly
if (verbose) print(paste("Reading daytime VPD directly from:",
paste0(dir_hh, filename_dd_vpd)))
df_vpd_day_dd <- readr::read_csv(file.path(dir, filename_dd_vpd))
merge_df_vpd_day_dd <- TRUE
} else {
# Create new daily daytime-VPD file from half-hourly data
if (is.null(dir_hh)){
warning("
Argument dir_hh is not provided.
Daytime VPD could not be calculated.
")
} else {
# get half-hourly file name(s)
filn_hh <- list.files(
dir_hh,
pattern = paste0("FLX_",sitename, ".*_FLUXNET2015_FULLSET_HH.*.csv" ),
recursive = TRUE
)
if (length(filn_hh)>0){
path_hh <- file.path(dir_hh, filn_hh)
if (length(filn_hh)>1){
file.info_getsize <- function(filn){
file.info(filn)$size
}
warning("Reading only largest half-hourly file available")
size_vec <- purrr::map_dbl(as.list(path_hh), ~file.info_getsize(.))
path_hh <- path_hh[which.max(size_vec)]
}
message("Reading half-hourly data to calculate daytime VPD ...")
df_vpd_day_dd <- get_vpd_day_fluxnet2015_byfile(path_hh, write = TRUE)
merge_df_vpd_day_dd <- TRUE
} else {
warning(
paste0(
"No half-hourly data found in ",
dir_hh,
". Looking for hourly data in ",
dir_hr, "...")
)
# get hourly file name(s)
filn_hr <- list.files(
dir_hr,
pattern = paste0( "FLX_",
sitename,
".*_FLUXNET2015_FULLSET_HR.*.csv" ),
recursive = TRUE
)
if (length(filn_hr)>0){
path_hr <- paste0(dir_hr, filn_hr)
if (length(filn_hr)>1){
file.info_getsize <- function(filn){
file.info(filn)$size
}
warning("Reading only largest half-hourly file available")
size_vec <- purrr::map_dbl(as.list(path_hr), ~file.info_getsize(.))
path_hr <- path_hr[which.max(size_vec)]
}
message("Reading hourly data to calculate daytime VPD ...")
df_vpd_day_dd <- get_vpd_day_fluxnet2015_byfile(
path_hr,
write = TRUE
)
merge_df_vpd_day_dd <- TRUE
}
}
}
}
if (merge_df_vpd_day_dd){
if (timescale=="d"){
# daily
df <- df %>% dplyr::left_join(df_vpd_day_dd, by="date")
} else if (timescale=="w"){
# weekly
df <- df_vpd_day_dd %>%
dplyr::mutate(year = lubridate::year(date),
week = lubridate::week(date)) %>%
dplyr::group_by(sitename, year, week) %>%
dplyr::summarise(VPD_F_DAY = mean(VPD_F, na.rm=TRUE),
VPD_F_DAY_QC = mean(VPD_F_QC, na.rm=TRUE),
VPD_F_DAY_MDS = mean(VPD_F_MDS, na.rm=TRUE),
VPD_F_DAY_MDS_QC = mean(VPD_F_MDS_QC, na.rm=TRUE),
VPD_DAY_ERA = mean(VPD_ERA, na.rm=TRUE) ) %>%
dplyr::right_join(df, by="date")
} else if (timescale=="m"){
# monthly
df <- df_vpd_day_dd %>%
dplyr::mutate(year = lubridate::year(date),
moy = lubridate::month(date)) %>%
dplyr::group_by(sitename, year, moy) %>%
dplyr::summarise(VPD_F_DAY = mean(VPD_F, na.rm=TRUE),
VPD_F_DAY_QC = mean(VPD_F_QC, na.rm=TRUE),
VPD_F_DAY_MDS = mean(VPD_F_MDS, na.rm=TRUE),
VPD_F_DAY_MDS_QC = mean(VPD_F_MDS_QC, na.rm=TRUE),
VPD_DAY_ERA = mean(VPD_ERA, na.rm=TRUE) ) %>%
dplyr::right_join(df, by="date")
} else if (timescale=="y"){
# annual
df <- df_vpd_day_dd %>%
dplyr::mutate(year = lubridate::year(date)) %>%
dplyr::group_by(sitename, year) %>%
dplyr::summarise(VPD_F_DAY = mean(VPD_F, na.rm=TRUE),
VPD_F_DAY_QC = mean(VPD_F_QC, na.rm=TRUE),
VPD_F_DAY_MDS = mean(VPD_F_MDS, na.rm=TRUE),
VPD_F_DAY_MDS_QC = mean(VPD_F_MDS_QC, na.rm=TRUE),
VPD_DAY_ERA = mean(VPD_ERA, na.rm=TRUE) ) %>%
dplyr::right_join(df, by="date")
}
}
}
#---- Get minimum temperature ----
merge_df_tmin_dd <- FALSE
if ("TMIN_F" %in% getvars && !(timescale == "hh")) {
# 1. Check whether daily file for daily mimimum temperature is already available
# get file name(s) of file containing daily daytime VPD derived from half-hourly data
filename_dd_tmin <- list.files(
dir,
pattern = paste0("FLX_", sitename, ".*_TMIN.csv"),
recursive = FALSE
)
if (length(filename_dd_tmin)>0){
# Read available file
if (length(filename_dd_tmin)>1){
file.info_getsize <- function(filn){
file.info(filn)$size
}
warning("Reading only largest TMIN file available")
path_dd_tmin <- paste0(dir_hh, filename_dd_tmin)
size_vec <- purrr::map_dbl(as.list(path_dd_tmin), ~file.info_getsize(.))
path_dd_tmin <- path_dd_tmin[which.max(size_vec)]
filename_dd_tmin <- basename(path_dd_tmin)
}
# read directly
if (verbose){
message(paste(
"Reading daytime tmin directly from:",
paste0(dir_hh, filename_dd_tmin)
)
)
}
df_tmin_dd <- readr::read_csv(paste0(dir, filename_dd_tmin))
merge_df_tmin_dd <- TRUE
} else {
# Create new daily tmin file from half-hourly data
if (is.null(dir_hh)){
warning(
"Argument dir_hh is not provided.
Daytime tmin could not be calculated."
)
} else {
# get half-hourly file name(s)
filn_hh <- list.files(
dir_hh,
pattern = paste0( "FLX_", sitename, ".*_FULLSET_HH.*.csv" ),
recursive = TRUE
)
if (length(filn_hh)>0){
path_hh <- paste0(dir_hh, filn_hh)
if (length(filn_hh)>1){
file.info_getsize <- function(filn){
file.info(filn)$size
}
warning("Reading only largest half-hourly file available")
size_vec <- purrr::map_dbl(as.list(path_hh), ~file.info_getsize(.))
path_hh <- path_hh[which.max(size_vec)]
}
message("Reading half-hourly data to calculate daytime tmin ...")
df_tmin_dd <- get_tmin_fluxnet2015_byfile(path_hh, write = TRUE)
merge_df_tmin_dd <- TRUE
} else {
warning(
paste0("No half-hourly data found in ",
dir_hh,
". Looking for hourly data in ", dir_hr, "...")
)
# get hourly file name(s)
filn_hr <- list.files( dir_hr,
pattern = paste0( "FLX_", sitename, ".*_FULLSET_HR.*.csv" ),
recursive = TRUE
)
if (length(filn_hr)>0){
path_hr <- paste0(dir_hr, filn_hr)
if (length(filn_hr)>1){
file.info_getsize <- function(filn){
file.info(filn)$size
}
warning("Reading only largest hourly file available")
size_vec <- purrr::map_dbl(as.list(path_hr), ~file.info_getsize(.))
path_hr <- path_hr[which.max(size_vec)]
}
message("Reading hourly data to calculate tmin ...")
df_tmin_dd <- get_tmin_fluxnet2015_byfile(path_hr, write = TRUE)
merge_df_tmin_dd <- TRUE
}
}
}
}
if (merge_df_tmin_dd){
if (timescale=="d"){
# daily
df <- df %>% dplyr::left_join(df_tmin_dd, by="date")
} else if (timescale=="w"){
# weekly
df <- df_tmin_dd %>%
dplyr::mutate(year = lubridate::year(date),
week = lubridate::week(date)) %>%
dplyr::group_by(sitename, year, week) %>%
dplyr::summarise(
TMIN_F = min(TA_F, na.rm=TRUE),
TMIN_F_QC = sum(is.element(TA_F_QC, c(0,1)))/n(),
TMIN_F_MDS = min(TA_F_MDS, na.rm=TRUE),
TMIN_F_MDS_QC = sum(is.element(TA_F_MDS_QC, c(0,1)))/n(),
TMIN_ERA = min(TA_ERA, na.rm=TRUE) ) %>%
dplyr::right_join(df, by="date")
} else if (timescale=="m"){
# monthly
df <- df_tmin_dd %>%
dplyr::mutate(year = lubridate::year(date),
moy = lubridate::month(date)) %>%
dplyr::group_by(sitename, year, moy) %>%
dplyr::summarise(
TMIN_F = min(TA_F, na.rm=TRUE),
TMIN_F_QC = sum(is.element(TA_F_QC, c(0,1)))/n(),
TMIN_F_MDS = min(TA_F_MDS, na.rm=TRUE),
TMIN_F_MDS_QC = sum(is.element(TA_F_MDS_QC, c(0,1)))/n(),
TMIN_ERA = min(TA_ERA, na.rm=TRUE) ) %>%
dplyr::right_join(df, by="date")
} else if (timescale=="y"){
# annual
df <- df_tmin_dd %>%
dplyr::mutate(year = lubridate::year(date)) %>%
dplyr::group_by(sitename, year) %>%
dplyr::summarise(
TMIN_F = min(TA_F, na.rm=TRUE),
TMIN_F_QC = sum(is.element(TA_F_QC, c(0,1)))/n(),
TMIN_F_MDS = min(TA_F_MDS, na.rm=TRUE),
TMIN_F_MDS_QC = sum(is.element(TA_F_MDS_QC, c(0,1)))/n(),
TMIN_ERA = min(TA_ERA, na.rm=TRUE) ) %>%
dplyr::right_join(df, by="date")
}
}
}
#---- Get maximum temperature ----
merge_df_tmax_dd <- FALSE
if ("TMAX_F" %in% getvars && !(timescale == "hh")) {
# 1. Check whether daily file for daily mimimum temperature is already available
# get file name(s) of file containing daily daytime VPD derived from half-hourly data
filename_dd_tmax <- list.files(
dir,
pattern = paste0("FLX_", sitename, ".*_TMAX.csv"),
recursive = FALSE
)
if (length(filename_dd_tmax)>0){
# Read available file
if (length(filename_dd_tmax)>1){
file.info_getsize <- function(filn){
file.info(filn)$size
}
warning("Reading only largest tmax file available")
path_dd_tmax <- paste0(dir_hh, filename_dd_tmax)
size_vec <- purrr::map_dbl(as.list(path_dd_tmax), ~file.info_getsize(.))
path_dd_tmax <- path_dd_tmax[which.max(size_vec)]
filename_dd_tmax <- basename(path_dd_tmax)
}
# read directly
if (verbose) print(paste("Reading daytime tmax directly from:", paste0(dir_hh, filename_dd_tmax)))
df_tmax_dd <- readr::read_csv(paste0(dir, filename_dd_tmax))
merge_df_tmax_dd <- TRUE
} else {
# Create new daily tmax file from half-hourly data
if (is.null(dir_hh)){
warning(
"Argument dir_hh is not provided.
Daytime tmax could not be calculated."
)
} else {
# get half-hourly file name(s)
filn_hh <- list.files(
dir_hh,
pattern = paste0( "FLX_", sitename, ".*_FULLSET_HH.*.csv" ),
recursive = TRUE
)
if (length(filn_hh)>0){
path_hh <- paste0(dir_hh, filn_hh)
if (length(filn_hh)>1){
file.info_getsize <- function(filn){
file.info(filn)$size
}
warning("Reading only largest half-hourly file available")
size_vec <- purrr::map_dbl(as.list(path_hh), ~file.info_getsize(.))
path_hh <- path_hh[which.max(size_vec)]
}
message("Reading half-hourly data to calculate daytime tmax ...")
df_tmax_dd <- get_tmax_fluxnet2015_byfile(path_hh, write = TRUE)
merge_df_tmax_dd <- TRUE
} else {
warning(
paste0(
"No half-hourly data found in ",
dir_hh,
". Looking for hourly data in ",
dir_hr, "..."
)
)
# get hourly file name(s)
filn_hr <- list.files(
dir_hr,
pattern = paste0( "FLX_", sitename, ".*_FULLSET_HR.*.csv" ),
recursive = TRUE
)
if (length(filn_hr)>0){
path_hr <- paste0(dir_hr, filn_hr)
if (length(filn_hr)>1){
file.info_getsize <- function(filn){
file.info(filn)$size
}
warning("Reading only largest hourly file available")
size_vec <- purrr::map_dbl(as.list(path_hr), ~file.info_getsize(.))
path_hr <- path_hr[which.max(size_vec)]
}
message("Reading hourly data to calculate tmax ...")
df_tmax_dd <- get_tmax_fluxnet2015_byfile(path_hr, write = TRUE)
merge_df_tmax_dd <- TRUE
}
}
}
}
if (merge_df_tmax_dd){
if (timescale == "d"){
# daily
df <- df %>% dplyr::left_join(df_tmax_dd, by="date")
} else if (timescale == "w"){
# weekly
df <- df_tmax_dd %>%
dplyr::mutate(year = lubridate::year(date),
week = lubridate::week(date)) %>%
dplyr::group_by(sitename, year, week) %>%
dplyr::summarise(
TMAX_F = max(TA_F, na.rm=TRUE),
TMAX_F_QC = sum(is.element(TA_F_QC, c(0,1)))/n(),
TMAX_F_MDS = max(TA_F_MDS, na.rm=TRUE),
TMAX_F_MDS_QC = sum(is.element(TA_F_MDS_QC, c(0,1)))/n(),
TMAX_ERA = max(TA_ERA, na.rm=TRUE) ) %>%
dplyr::right_join(df, by="date")
} else if (timescale=="m"){
# monthly
df <- df_tmax_dd %>%
dplyr::mutate(year = lubridate::year(date),
moy = lubridate::month(date)) %>%
dplyr::group_by(sitename, year, moy) %>%
dplyr::summarise(
TMAX_F = max(TA_F, na.rm=TRUE),
TMAX_F_QC = sum(is.element(TA_F_QC, c(0,1)))/n(),
TMAX_F_MDS = max(TA_F_MDS, na.rm=TRUE),
TMAX_F_MDS_QC = sum(is.element(TA_F_MDS_QC, c(0,1)))/n(),
TMAX_ERA = max(TA_ERA, na.rm=TRUE) ) %>%
dplyr::right_join(df, by="date")
} else if (timescale=="y"){
# annual
df <- df_tmax_dd %>%
dplyr::mutate(year = lubridate::year(date)) %>%
dplyr::group_by(sitename, year) %>%
dplyr::summarise(
TMAX_F = max(TA_F, na.rm=TRUE),
TMAX_F_QC = sum(is.element(TA_F_QC, c(0,1)))/n(),
TMAX_F_MDS = max(TA_F_MDS, na.rm=TRUE),
TMAX_F_MDS_QC = sum(is.element(TA_F_MDS_QC, c(0,1)))/n(),
TMAX_ERA = max(TA_ERA, na.rm=TRUE) ) %>%
dplyr::right_join(df, by="date")
}
}
}
#---- Reduce data to getvars ----
# retain all getvars, plus soil moisture if required
if (getswc){
df <- df %>%
dplyr::select( ., date, one_of(getvars), starts_with("SWC_") )
# dplyr::mutate_at(., vars(starts_with("SWC_")), list(~as.numeric) ) # this has caused error
} else {
df <- df %>% dplyr::select( ., date, one_of(getvars) )
}
#---- Filter / clean data ----
TA_vars <- getvars[which(grepl("TA_", getvars))]
TA_vars <- TA_vars[-which(grepl("_QC", TA_vars))]
for (ivar in TA_vars){
df <- df %>%
clean_fluxnet_byvar(
ivar,
threshold_T
)
}
# wind speed
WS_vars <- getvars[which(grepl("WS_", getvars))]
WS_vars <- WS_vars[-which(grepl("_QC", WS_vars))]
for (ivar in WS_vars){
df <- df %>%
clean_fluxnet_byvar(
ivar,
threshold_WS
)
}
# u-star
USTAR_vars <- getvars[which(grepl("USTAR_", getvars))]
USTAR_vars <- USTAR_vars[-which(grepl("_QC", USTAR_vars))]
for (ivar in USTAR_vars){
df <- df %>%
clean_fluxnet_byvar(
ivar,
threshold_USTAR
)
}
# net radiation
NETRAD_vars <- getvars[which(grepl("NETRAD", getvars))]
NETRAD_vars <- NETRAD_vars[-which(grepl("_QC", NETRAD_vars))]
for (ivar in NETRAD_vars){
df <- df %>%
clean_fluxnet_byvar(
ivar,
threshold_NETRAD
)
}
# energyvars <- df %>%
# dplyr::select(starts_with("LE_"), starts_with("H_")) %>%
# dplyr::select(-ends_with("_QC")) %>%
# names()
#
# df <- df %>%
# # Unit conversion for sensible and latent heat flux: W m-2 -> J m-2 d-1
# dplyr::mutate_at( vars(one_of(energyvars)), convert_energy_fluxnet2015)
# clean GPP data
if (any(grepl("GPP_", getvars))){
error <- try(
df <- df %>%
clean_fluxnet_gpp(
threshold = threshold_GPP,
remove_neg = remove_neg,
filter_ntdt = filter_ntdt,
freq = timescale
) %>%
dplyr::select(-res),
silent = TRUE
)
if(inherits(error, "try-error")) {
message(
"
Missing nighttime/ daytime QC data.
Data is not screened - taken as is.
Is this plumber2 data converted by read_plumber()?"
)
}
}
# clean energy data (sensible and latent heat flux) data - often has spuriously equal values
if (any(grepl("LE_", getvars))){
if (any( !(c("LE_F_MDS", "LE_F_MDS_QC") %in% getvars) )){
stop("Not all variables read from file that are needed for data cleaning.")
}
df$LE_F_MDS <- clean_fluxnet_energy(
df$LE_F_MDS,
df$LE_F_MDS_QC,
threshold = threshold_LE
)
}
if (any(grepl("H_", getvars))){
if (any( !(c("H_F_MDS", "H_F_MDS_QC") %in% getvars) )){
stop("Not all variables read from file that are needed for data cleaning.")
}
df$H_F_MDS <- clean_fluxnet_energy(
df$H_F_MDS,
df$H_F_MDS_QC,
threshold=threshold_H
)
}
#---- Process soil moisture data ----
# Soil moisture related stuff for daily data
if (timescale=="d" && getswc){
tmp <- df %>% dplyr::select( starts_with("SWC") )
if (ncol(tmp)>0){
swcvars <- tmp %>%
dplyr::select( -ends_with("QC") ) %>%
names()
swcqcvars <- tmp %>%
dplyr::select( ends_with("QC") ) %>%
names()
if (length(swcvars)>0){
for (ivar in 1:length(swcvars)){
df[[ swcvars[ivar] ]] <- clean_fluxnet_swc(
df[[ swcvars[ivar] ]],
df[[ swcqcvars[ivar] ]],
frac_data_thresh = threshold_SWC
)
}
}
df <- df %>%
# Normalise mean observational soil moisture to
# within minimum (=0) and maximum (=1), and
dplyr::mutate_at(
vars(one_of(swcvars)),
list(~norm_to_max(.))
) %>%
# get mean observational soil moisture across
# different depths (if available)
dplyr::mutate(
soilm_obs_mean = apply(
dplyr::select( ., one_of(swcvars) ),
1, FUN = mean, na.rm = TRUE )
) %>%
dplyr::mutate(
soilm_obs_mean = ifelse(is.nan(soilm_obs_mean), NA, soilm_obs_mean )
)
if (verbose){
message(
"Converting: soilm_obs_mean =
mean across different soil depths (SWC_F_MDS), with na.rm = TRUE" )
}
}
}
#---- check if anything is missing ----
if (any(!(getvars %in% names(df)))){
message(
paste("Not all getvars were found in file. Missing variable: ",
paste(getvars[which(!(getvars %in% names(df)))], collapse = ", "),
"for site: ", sitename))
}
if (!return_qc){
df <- df %>%
dplyr::select(
-ends_with("_QC")
)
}
#---- Make unit conversions and shorter names ----
outgetvars <- c()
#---- Rename variables to names provided by argument 'getvars' ----
rename_byvar <- function(df, list_var, verbose){
name_in <- list_var %>%
unlist() %>%
unname()
name_out <- list_var %>%
names()
if (verbose){
message(paste0("Renaming: ", name_out, " = ", name_in, " \n"))
}
df %>%
dplyr::rename_at(
vars(matches({{name_in}})),
list(~stringr::str_replace(., {{name_in}}, {{name_out}}))
)
}
for (ivar in seq(length(getvars_orig))){
df <- df %>%
rename_byvar(
getvars_orig[ivar],
verbose = verbose
)
}
#---- Convert units to ingestr-standards ----
# conversion factor from SPLASH: flux to energy conversion,
# umol/J (Meek et al., 1984)
kfFEC <- 2.04
if ("vpd_day" %in% names(df)){
if (verbose){
message(
"Converting: vpd_day = vpd_day * 1e2
(given in hPa, required in Pa)"
)
}