-
Notifications
You must be signed in to change notification settings - Fork 5
/
WEPPCLIFF.R
2891 lines (2286 loc) · 125 KB
/
WEPPCLIFF.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
#############################################################################
############################## PROGRAM METADATA #############################
#############################################################################
# Version: 1.7
# Last Updated by: Ryan P. McGehee
# Last Updated on: 15 February 2023
# Purpose: This program was first designed to create an appropriate input
# climate file (.cli) for a WEPP model run. However, the program
# has evolved into a much more advanced and capable tool. See the
# accompanying documentation for more information.
#############################################################################
############################## DEFINE FUNCTIONS #############################
#############################################################################
# A function to print the WEPPCLIFF logo to screen.
print_weppcliff_logo = function() {
LOGO = {"
________________________________________________________________________________
________________________________________________________________________________
___ ___ _______ _______ _______ _______ ___ _______ _______ _______
| | __ | | | ___/ | __ | | __ | | ___/ | | |__ __| | ___/ | ___/
| | / \\ | | | |___ | |__| | | |__| | | | | | | | | |___ | |___
| |/ /\\ \\| | | __/ | ____| | ____| | | | | | | | __/ | __/
\\ / \\ / | |___ | | | | | |___ | |___ _| |_ | | | |
\\_/ \\_/ |_____| |_| |_| |_____| |_____| |_____| |_| |_|
________________________________________________________________________________
________________________________________________________________________________
"}
cat(rep(lr, 30))
cat(LOGO)}
# A function to print a license agreement.
print_license_agreement = function() {
LICENSE = {"
WEPP Climate File Formatter (WEPPCLIFF) Version 1.7
Copyright (c) 2023 Ryan P. McGehee
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation (GNU GPL v3.0).
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Please provide an appropriate citation in any published work as follows:
McGehee, R.P., D.C. Flanagan, and P. Srivastava. 2020. WEPPCLIFF:
A command-line tool to process climate inputs for soil loss models.
Journal of Open Source Software. https://doi.org/10.21105/joss.02029
Repository available at: https://github.com/ryanpmcg/WEPPCLIFF
Corresponding Author: R.P. McGehee
E-mail: [email protected]"}
cat(lr)
cat(LICENSE)
cat(lr)}
# A function to prompt a license agreement and accept user response.
prompt_license_agreement = function() {
print_license_agreement()
cat(lr, lr, "Do you accept these conditions? (Y/N)", lr, lr, collapse = "")
stdin = file("stdin")
response = readLines(stdin, n = 1L)
close(stdin)
if (toupper(response) != "Y"){
stop("You must acknowledge your agreement to the license conditions with 'Y or y' to use this software.")}}
# A function to create directories if they do not exist.
create_directory = function(var) {
logic = dir.exists(toupper(var))
if (logic == F){dir.create(var)}}
# A function to create the WEPPCLIFF base directory.
create_base_directory = function() {
dirs = c(l, d, o, e, p)
for (i in dirs){create_directory(i)}}
# A function to find this file location. Credit: Katie Barnhart @kbarnhart
find_this_file = function() {
cmdArgs = commandArgs(trailingOnly = FALSE)
needle = "--file="
match = grep(needle, cmdArgs)
if (length(match) > 0) {return(normalizePath(sub(needle, "", cmdArgs[match])))
} else {return(normalizePath(sys.frames()[[1]]$ofile))}}
# A function to determine directory location.
set_wds = function() {
# Set a global home directory.
home.dir <<- dirname(find_this_file())
# Set base directories.
dir.names = c("lib.dir", "in.dir", "out.dir", "ex.dir", "plot.dir")
dir.locs = c(l, d, o, e, p)
for (i in 1:length(dir.names)) {assign(dir.names[i], dir.locs[i], envir = .GlobalEnv)}}
# A function to install R package dependencies on the first run.
install_dependencies = function() {
cat("Installing R package dependencies...", lr, lr, sep = "")
lapply(package.list, install.packages, lib = lib.dir, type = "binary", repos = "http://cran.us.r-project.org")
cat(lr, lr, "Done.", lr, lr, sep = "")}
# A function to locate acceptable arguments.
parse_arg_locations = function() {
for (i in flags){
x = which(args == paste("-", i, sep = ""))
assign(paste(i, ".loc", sep = ""), x, envir = .GlobalEnv)}}
# A function to assign an early license agreement to a variable.
early_license_agreement = function() {
# Get the argument location and value to assign to a variable.
la <<- 'NULL'
value = args[get("la.loc") + 1]
if (length(value) > 0){assign('la', value, envir = .GlobalEnv)}}
# A function to assign arguments to global variables and print to screen.
assign_args_to_vars = function() {
# Print argument header.
cat(rep(lr, 2))
cat(paste(rep("*", 80), collapse = ""), lr, lr)
cat(paste(" User Specified Arguments:", length(grep("-", args)) - 1, "of", length(flags), "possible arguments.", lr, lr, collapse = ""))
cat(paste(rep("*", 80), collapse = ""), lr)
cat(rep(lr, 2))
# Reset counters.
counter = 1
flagcounter = 1
# Loop over arguments.
for (i in flags){
# Print for each argument grouping.
if (counter %in% flagcount) {
if (counter != 1) {
cat(rep(lr, 2))
cat(" ", paste(rep("*", 44), collapse = ""), lr, lr)}
spaces = floor((45 - nchar(flagtypes[flagcounter])) / 2)
cat(paste(rep(" ", spaces), collapse = ""),flagtypes[flagcounter], lr)
flagcounter = flagcounter + 1}
# Get the argument location and value to assign to a variable.
x = get(paste(i, ".loc", sep = ""))
value = args[x + 1]
if (length(value) > 0){assign(paste(i), value, envir = .GlobalEnv)}
if (length(value) == 0){assign(paste(i), NULL, envir = .GlobalEnv)}
# Determine leader length and print arguments to screen.
leader = paste(rep("-", 40 - nchar(flagnames[counter]) - nchar(i)), collapse = "")
cat(paste(lr,"",flagnames[counter], leader, i, ":\t", args[x + 1], "",collapse = ""))
counter = counter + 1}
# End argument printing.
cat(rep(lr, 3))
cat(paste(rep("*", 80), collapse = ""), lr)
cat(rep(lr, 2))}
# A function to fill unspecified arguments with defaults (# Def:).
assign_empty_args = function() {
# Execute initial assignment.
runif(1) #Forces creation of the global variable: .Random.seed
if (length(d) == 0){assign("d", paste(home.dir, "/INPUT", sep = ""), envir = .GlobalEnv)} # Def: current directory
if (length(o) == 0){assign("o", paste(home.dir, "/OUTPUT", sep = ""), envir = .GlobalEnv)} # Def: current directory
if (length(e) == 0){assign("e", paste(home.dir, "/EXPORT", sep = ""), envir = .GlobalEnv)} # Def: current directory
if (length(p) == 0){assign("p", paste(home.dir, "/PLOTS", sep = ""), envir = .GlobalEnv)} # Def: current directory
if (length(l) == 0){assign("l", paste(home.dir, "/LIBRARY", sep = ""), envir = .GlobalEnv)} # Def: current directory
if (length(u) == 0){assign("u", "m", envir = .GlobalEnv)} # Def: metric units
if (length(fn) == 0){assign("fn", "station", envir = .GlobalEnv)} # Def: output file name will be "out.cli"
if (length(fr) == 0){assign("fr", "f", envir = .GlobalEnv)} # Def: not first run
if (length(la) == 0){assign("la", NULL, envir = .GlobalEnv)} # Def: NULL placeholder
if (length(mp) == 0){assign("mp", "t", envir = .GlobalEnv)} # Def: multicore operation
if (length(qc) == 0){assign("qc", "f", envir = .GlobalEnv)} # Def: do not check quality
if (length(rp) == 0){assign("rp", 1000, envir = .GlobalEnv)} # Def: 1000-year or higher return period events are removed
if (length(id) == 0){assign("id", "f", envir = .GlobalEnv)} # Def: do not fill data
if (length(pd) == 0){assign("pd", "f", envir = .GlobalEnv)} # Def: do not plot data
if (length(ed) == 0){assign("ed", 0, envir = .GlobalEnv)} # Def: do not export data
if (length(cp) == 0){assign("cp", "f", envir = .GlobalEnv)} # Def: non-cumulative precipitation data
if (length(pi) == 0){assign("pi", "f", envir = .GlobalEnv)} # Def: breakpoint format assumed
if (length(ai) == 0){assign("ai", "f", envir = .GlobalEnv)} # Def: no aggregation performed
if (length(cv) == 0){assign("cv", "0.0", envir = .GlobalEnv)} # Def: CLIGEN Version Unspecified
if (length(sm) == 0){assign("sm", 1, envir = .GlobalEnv)} # Def: continuous simulation mode
if (length(bf) == 0){assign("bf", 1, envir = .GlobalEnv)} # Def: breakpoint format CLI file
if (length(wi) == 0){assign("wi", 1, envir = .GlobalEnv)} # Def: wind information provided
if (length(ei) == 0){assign("ei", "f", envir = .GlobalEnv)} # Def: do not calculate erosion indices
if (length(ee) == 0){assign("ee", "R2", envir = .GlobalEnv)} # Def: use the RUSLE2 energy equation
if (length(im) == 0){assign("im", "DEFAULT", envir = .GlobalEnv)} # Def: use the default WEPPCLIFF imputation design
if (length(io) == 0){assign("io", 100, envir = .GlobalEnv)} # Def: use up to 100 iterations
if (length(qi) == 0){assign("qi", "f", envir = .GlobalEnv)} # Def: do not cut corners on imputation
if (length(iv) == 0){assign("iv", "f", envir = .GlobalEnv)} # Def: do not print imputation progress
if (length(tz) == 0){assign("tz", "GMT", envir = .GlobalEnv)} # Def: use GMT for the time zone
if (length(rs) == 0){assign("rs", "f", envir = .GlobalEnv)} # Def: do not use recursive search
if (length(fsp) == 0){assign("fsp", NULL, envir = .GlobalEnv)} # Def: no search pattern
if (length(isc) == 0){assign("isc", "f", envir = .GlobalEnv)} # Def: does not ignore search case
if (length(alt) == 0){assign("alt", "f", envir = .GlobalEnv)} # Def: alternative data provided
if (length(pmd) == 0){assign("pmd", "f", envir = .GlobalEnv)} # Def: do not preserve missingness
if (length(sid) == 0){assign("sid", 1, envir = .GlobalEnv)} # Def: use first storm in list
if (length(sdt) == 0){assign("sdt", "start", envir = .GlobalEnv)} # Def: use earliest acceptable datetime
if (length(edt) == 0){assign("edt", "end", envir = .GlobalEnv)} # Def: use latest acceptable datetime
if (length(ipb) == 0){assign("ipb", "f", envir = .GlobalEnv)} # Def: do not ignore precipitation for rounding
if (length(rtb) == 0){assign("rtb", "m", envir = .GlobalEnv)} # Def: do not round start and end times
if (length(tth) == 0){assign("tth", 6, envir = .GlobalEnv)} # Def: 6-hour time (break b/w storms)
if (length(dth) == 0){assign("dth", 1.27, envir = .GlobalEnv)} # Def: 1.27 mm depth (break b/w storms)
if (length(qcop) == 0){assign("qcop", "b", envir = .GlobalEnv)} # Def: uses physical and empirical methods for quality control
if (length(dtf1) == 0){assign("dtf1", "%Y-%m-%d %H:%M:%S", envir = .GlobalEnv)} # Def: a standard datetime format
if (length(dtf2) == 0){assign("dtf2", dtf1, envir = .GlobalEnv)} # Def: same as dtf1 (input or default)
if (length(dtf3) == 0){assign("dtf3", dtf1, envir = .GlobalEnv)} # Def: same as dtf1 (input or default)
if (length(prof) == 0){assign("prof", "f", envir = .GlobalEnv)} # Def: production mode (as opposed to profiling mode)
if (length(pint) == 0){assign("pint", 0.02, envir = .GlobalEnv)} # Def: time in seconds between profile sampling
if (length(mepr) == 0){assign("mepr", "f", envir = .GlobalEnv)} # Def: exclude memory profiling
if (length(gcpr) == 0){assign("gcpr", "f", envir = .GlobalEnv)} # Def: exclude garbage collect profiling
if (length(lnpr) == 0){assign("lnpr", "f", envir = .GlobalEnv)} # Def: exclude line profiling
if (length(warn) == 0){assign("warn", "f", envir = .GlobalEnv)} # Def: turn off warnings
if (length(verb) == 0){assign("verb", "f", envir = .GlobalEnv)} # Def: verbosity off
if (length(chkth) == 0){assign("chkth", 0.9, envir = .GlobalEnv)} # Def: check the most extreme 10% of data
if (length(spkth) == 0){assign("spkth", 0.9, envir = .GlobalEnv)} # Def: 90% recovery indicates a spike
if (length(strth) == 0){assign("strth", 2, envir = .GlobalEnv)} # Def: anything more than 2 consecutive identical values can be a streak
if (length(stkth) == 0){assign("stkth", 4, envir = .GlobalEnv)} # Def: anything separated by 4 or less observations can be a stick
if (length(delim) == 0){assign("delim", " ", envir = .GlobalEnv)}} # Def: space delimiter
# A function to halt execution for invalid arguments.
check_args = function() {
# Create patterns for grep searching.
u.patterns = paste("m", "e", collapse = "|")
tf.patterns = paste("t", "f", collapse = "|")
ed.patterns = paste(0:6, collapse = "|")
sm.patterns = paste("1", "2", collapse = "|")
bf.patterns = paste("0", "1", collapse = "|")
wi.patterns = paste("0", "1", collapse = "|")
mp.patterns = paste("t", "f", 1:10000, collapse = "|")
pi.patterns = paste("f", 1:1440, collapse = "|")
cv.patterns = paste("f", "0.0", "4.3", "5.3", collapse = "|")
rtb.patterns = paste("m", "d", "h", "f", collapse = "|")
# Perform grep searching.
if (length(grepl(u, u.patterns, ignore.case = T)) == 0){stop("Invalid Argument: [-u] must be specified as 'm' (metric) or 'e' (english) followed by any exceptions.")}
if (grepl(fr, tf.patterns, ignore.case = T) != T){stop("Invalid Argument: [-fr] must be specified as 't' (true) or 'f' (false).")}
if (grepl(mp, mp.patterns, ignore.case = T) != T){stop("Invalid Argument: [-mp] must be specified as 't' (true), 'f' (false), or an integer number of cores.")}
if (grepl(qc, tf.patterns, ignore.case = T) != T){stop("Invalid Argument: [-qc] must be specified as 't' (true) or 'f' (false).")}
if (grepl(id, tf.patterns, ignore.case = T) != T){stop("Invalid Argument: [-id] must be specified as 't' (true) or 'f' (false).")}
if (grepl(pd, tf.patterns, ignore.case = T) != T){stop("Invalid Argument: [-pd] must be specified as 't' (true) or 'f' (false).")}
if (grepl(ed, ed.patterns, ignore.case = T) != T){stop("Invalid Argument: [-ed] must be specified as '0' (off), '1' (all), '2' (rds), '3-6' (precip, daily, storm or breakpoint csv).")}
if (grepl(cp, tf.patterns, ignore.case = T) != T){stop("Invalid Argument: [-cp] must be specified as 't' (true) or 'f' (false).")}
if (grepl(pi, pi.patterns, ignore.case = T) != T){stop("Invalid Argument: [-pi] must be specified as 'f' (false) or an integer up to 1440 (in minutes).")}
if (grepl(ai, pi.patterns, ignore.case = T) != T){stop("Invalid Argument: [-ai] must be specified as 'f' (false) or an integer up to 1440 (in minutes).")}
if (grepl(sm, sm.patterns, ignore.case = T) != T){stop("Invalid Argument: [-sm] must be specified as '1' (continuous) or '2' (event).")}
if (grepl(bf, bf.patterns, ignore.case = T) != T){stop("Invalid Argument: [-bf] must be specified as '0' (daily) or '1' (breakpoint).")}
if (grepl(wi, wi.patterns, ignore.case = T) != T){stop("Invalid Argument: [-wi] must be specified as '0' (exclude) or '1' (include).")}
if (grepl(ei, tf.patterns, ignore.case = T) != T){stop("Invalid Argument: [-ei] must be specified as 't' (true) or 'f' (false).")}
if (grepl(cv, cv.patterns, ignore.case = T) != T){stop("Invalid Argument: [-cv] must be specified as 'f' (false) or one of the supported CLIGEN version control numbers (0.0, 4.3, or 5.3).")}
if (grepl(rs, tf.patterns, ignore.case = T) != T){stop("Invalid Argument: [-rs] must be specified as 't' (true) or 'f' (false).")}
if (grepl(isc, tf.patterns, ignore.case = T) != T){stop("Invalid Argument: [-isc] must be specified as 't' (true) or 'f' (false).")}
if (grepl(ipb, tf.patterns, ignore.case = T) != T){stop("Invalid Argument: [-ipb] must be specified as 't' (true) or 'f' (false).")}
if (grepl(rtb, rtb.patterns, ignore.case = T) != T){stop("Invalid Argument: [-rtb] must be specified as 'm' (month), 'd' (day), 'h' (hour), or 'f' (false).")}
if (grepl(alt, tf.patterns, ignore.case = T) != T){stop("Invalid Argument: [-alt] must be specified as 't' (true) or 'f' (false).")}
if (grepl(pmd, tf.patterns, ignore.case = T) != T){stop("Invalid Argument: [-pmd] must be specified as 't' (true) or 'f' (false).")}
if (toupper(ai) != "F") {if (1440 %% as.numeric(ai) > 0) {stop("Invalid Argument: [-ai]; 1440 must be perfectly divisible by the specified integer.")}}}
# A function to assign final values to arguments.
assign_final_args = function() {
# Execute final assignment.
if (toupper(pmd) == "T") {pmd <<- T}
if (toupper(pmd) == "F") {pmd <<- F}}
# A function to load all R package dependencies.
load_packages = function() {
t.time = system.time({
cat("Loading R package dependencies... ")
lapply(package.list, library, lib.loc = lib.dir, character.only = T, quietly = T, verbose = F, attach.required = T)})
cat("Completed in", t.time[3],"seconds.", lr, lr)}
# A function to load the input file used in calculations.
load_input_file = function(f) {
setwd(d)
t.time = system.time({
# Search for file type.
txt = grep(".txt", f, ignore.case = T)
tsv = grep(".tsv", f, ignore.case = T)
csv = grep(".csv", f, ignore.case = T)
# Handle common errors.
if (sum(txt, tsv, csv) == 0) {stop("The input file does not contain an acceptable extension (.txt or .csv).")}
if (sum(txt, tsv, csv) > 1) {stop("The input file contains more than one acceptable extension.")}
# Load file otherwise.
if (toupper(verb) == "T") {cat(lr, "Loading input file... ")}
if (length(txt) == 1){file = suppressMessages(read_table(f, delim, col_types=cols(DT_1="c", DT_2="c", DT_3="c")))}
if (length(tsv) == 1){file = suppressMessages(read_tsv(f, col_types=cols(DT_1="c", DT_2="c", DT_3="c")))}
if (length(csv) == 1){file = suppressMessages(read_csv(f, col_types=cols(DT_1="c", DT_2="c", DT_3="c")))}})
setwd(home.dir)
return(file)}
# A function to check the input file format.
check_input_format = function(file) {
file = as.data.frame(file)
# Check R data conversion.
if(is.data.frame(file) == F){stop("The input file could not be stored as a data frame.")}
# Check input variables.
oldNames = colnames(file)
vars = c("DT_1", "PRECIP", "DT_3", "MAX_TEMP", "MIN_TEMP", "SO_RAD", "W_VEL", "W_DIR", "DP_TEMP")
if (toupper(alt) == "T") {vars = c("DT_1", "PRECIP", "DT_2", "AIR_TEMP", "REL_HUM", "DT_3", "SO_RAD", "W_VEL", "W_DIR")}
if (toupper(cv) == "F") {vars = c("DT_1", "PRECIP")}
present = which(vars %in% oldNames)
missing = vars[-present]
if(length(missing) > 0){cat("Some expected variables are missing:", missing, "", lr, lr); stop()}
return(file)}
# A function to load input files in a directory.
load_input_directory = function() {
t.time = system.time({
cat("Parsing input files... ")
# Get list of files.
if (toupper(rs) == "T") {rs = T}
if (toupper(rs) == "F") {rs = F}
if (toupper(isc) == "T") {isc = T}
if (toupper(isc) == "F") {isc = F}
files = dir(d, full.names = T, pattern = fsp, recursive = rs, ignore.case = isc)
# Parse file types.
txt = grep(".txt", files)
tsv = grep(".tsv", files)
csv = grep(".csv", files)
# Handle errors.
all = c(txt, tsv, csv)
if (sum(duplicated(all)) > 0) {files = files[-all[duplicated(all)]]}})
cat("Completed in", t.time[3],"seconds.", lr, lr)
return(files)}
# A function to check for missing columns and pad them with NA.
preprocess_file = function(file) {
t.time = system.time({
if (toupper(verb) == "T") {cat(lr, "Preprocessing data... ")}
vars = c("STATION", "LAT", "LON", "ELEV", "DT_1", "PRECIP", "DT_2", "AIR_TEMP", "REL_HUM",
"DT_3", "MAX_TEMP", "MIN_TEMP", "SO_RAD","W_VEL", "W_DIR", "DP_TEMP")
for (i in vars){
logic = i %in% colnames(file)
if (logic == F){
old_names = colnames(file)
file = cbind(file, NA)
colnames(file) = c(old_names, i)}}})
return(file)}
# A function to create the multiprocessing virtual cluster environment.
create_cluster = function(s, mp) {
cat("Creating multiprocessing virtual cluster... ")
# Determine a good number of cores to use.
tmp = mp
cores = detectCores()
cores.90 = floor(cores * 0.90)
cores.4b = cores - 4
max.cores = max(1, cores.90, cores.4b)
# Create a cluster based on user input, stations detected, and available cores.
if (length(na.omit(as.numeric(mp))) >= 1) {max.cores = as.numeric(mp)}
if (length(na.omit(as.numeric(mp))) == 0) {tmp = mp; mp = s}
cluster = makeCluster(min(s, max.cores))
registerDoParallel(cluster)
cat("Done. Cores deployed:", min(s, max.cores), "", lr, lr)
mp = tmp}
# A function to store data for processing.
store_data = function(file) {
if (toupper(verb) == "T") {cat(lr,"Storing in memory...")}
# Convert to dataframe and read variables.
file = as.data.frame(file[[1]], stringsAsFactors = F)
long.vars = c("DT_1", "PRECIP", "DT_2", "AIR_TEMP", "REL_HUM", "DT_3", "MAX_TEMP", "MIN_TEMP", "SO_RAD","W_VEL", "W_DIR", "DP_TEMP")
short.vars = c("STATION", "LAT", "LON", "ELEV", "OBS_YRS", "B_YR", "YRS_SIM")
# Store time series variables.
for (j in long.vars){
if (is.null(file[[j]]) == T){assign(j, NA)}
if (is.null(file[[j]]) == F){assign(j, file[[j]])}}
# Store scalars.
for (j in short.vars){
if (is.null(file[[j]]) == T){assign(j, NA)}
if (is.null(file[[j]]) == F){assign(j, file[[j]][1])}}
# Create the primary data structure and fill.
data = list()
data[[1]] = data.frame(DT_1, PRECIP)
data[[2]] = data.frame(DT_2, AIR_TEMP, REL_HUM)
data[[3]] = data.frame(DT_3, MIN_TEMP, MAX_TEMP, SO_RAD, W_VEL, W_DIR, DP_TEMP)
data[[4]] = c(STATION, LAT, LON, ELEV, OBS_YRS, B_YR, YRS_SIM)
names(data[[4]]) = short.vars
return(data)}
# A function to change type to dataframe and class to numeric.
convert_data = function(data) {
if (toupper(verb) == "T") {cat(lr,"Converting data format...")}
for (j in 1:3){
data[[j]] = as.data.frame(data[[j]], stringsAsFactors = F)
data[[j]] = convert_df_type(data[[j]], 2:ncol(data[[j]]), "ftn")}
return(data)}
# A function to remove dataframe rows with no datetime.
remove_missing_datetime_rows = function(data) {
for (j in 1:3) {data[[j]] = data[[j]][!is.na(data[[j]][,1]),]}
return(data)}
# A function to find and replace missing or unuseable data values.
preserve_missing_data = function(data, group) {
for (j in group) {data[[j]] = df_find_replace(df = data[[j]], cols = 2:ncol(data[[j]]), find = T, null = T, nan = T, na = T, inf = T, vals = -99999, replace = NA)}
return(data)}
# A function to change columns in a dataframe to numeric or character.
convert_df_type = function(df, cols, type) {
if (type == "c" | type == "ftn") {for (j in cols) {df[,j] = as.character(df[,j])}}
if (type == "n" | type == "ftn") {for (j in cols) {df[,j] = as.numeric(df[,j])}}
return(df)}
# A function to find and replace values in a dataframe.
df_find_replace = function(df, cols, find, null, nan, na, inf, vals, replace) {
for (j in cols) {df[,j] = vec_find_replace(vec = df[,j], find = find, null = null, nan = nan, na = na, inf = inf, vals = vals, replace = replace)}
return(df)}
# A function to find and replace values in a vector.
vec_find_replace = function(vec, find, inf, null, nan, na, vals, replace) {
# Set conditions.
if (length(null) == 0) {null = F}
if (length(find) == 0) {find = F}
if (length(inf) == 0) {inf = F}
if (length(nan) == 0) {nan = F}
if (length(na) == 0) {na = F}
# Execute.
if (null == T) {vec[is.null(vec)] = replace}
if (find == T) {vec[vec %in% vals] = replace}
if (inf == T) {vec[is.infinite(vec)] = replace}
if (nan == T) {vec[is.nan(vec)] = replace}
if (na == T) {vec[is.na(vec)] = replace}
return(vec)}
# A function to calculate duration data.
create_duration_data = function(data, x) {
if (toupper(verb) == "T") {cat(lr,"Analyzing data intervals...")}
# Loop over each of the variable groups.
dt_list = c("DT_1", "DT_2", "DT_3")
dtf_list = c(dtf1, dtf2, dtf3)
# Loop over each variable grouping.
for (j in x){
# Convert to datetime (POSIX Count).
if (length(na.omit(data[[j]][[dt_list[j]]])) == 0) {stop("Datetime data may not be handled correctly. Please check the input file(s) and arguments.")}
if (length(na.omit(data[[j]][[dt_list[j]]])) > 0) {
data[[j]][[dt_list[j]]] = format(as.POSIXct(gsub("T|Z", " ", as.character(data[[j]][[dt_list[j]]])), format = dtf_list[j]), format = "%Y-%m-%d %H:%M:%S")
data[[j]] = data[[j]][complete.cases(data[[j]][,1]),]}
# Handle precipitation and non-precipitation breaks.
if (j == 1) {
# Convert fixed format to breakpoint format if appropriate.
if (toupper(pi) != "F") {
precip.interval = as.numeric(pi)
new.dates = as.POSIXct(data[[j]][[dt_list[j]]]) - (60 * precip.interval)
rmv.dates = which(new.dates %in% data[[j]][[dt_list[j]]])
if (length(rmv.dates) > 0) {
add.dates = new.dates[-rmv.dates]
zeroes = c(rep(0, length(add.dates)))
new.rows = data.frame(add.dates, zeroes)
names(new.rows) = c("DT_1", "PRECIP")
data[[j]] = rbind(data[[j]], new.rows)
}
}
}
# Sort data.
data[[j]] = data[[j]][order(data[[j]][[dt_list[j]]]),]
# Calculate time differences in minutes.
dif = difftime(tail(data[[j]][[dt_list[j]]], -1), head(data[[j]][[dt_list[j]]], -1), units = "mins")
dif = as.numeric(dif)
dif = c(dif[1], dif)
data[[j]]$DUR = dif
data[[j]][[dt_list[j]]] = as.POSIXlt(data[[j]][[dt_list[j]]])}
# Keep only positive precipitation values and potential storm starts.
p_rows = which(data[[1]]$PRECIP != 0)
z_rows = which(data[[1]]$PRECIP == 0)
s_rows = p_rows-1
b_rows = intersect(z_rows, s_rows)
data[[1]] = data[[1]][union(p_rows, b_rows),]
data[[1]] = data[[1]][order(data[[1]]$DT_1),]
# Modify midnight breakpoint crossings.
data[[1]] = modify_midnight_breakpoints(df = data[[1]], dtf = dtf1)
return(data)}
# A function to modify breakpoints that cross midnight.
modify_midnight_breakpoints = function(df, dtf) {
# Calculate time from midnight.
df$TFM = sapply(as.POSIXlt(as.character(df$DT_1), format = dtf), function(x) x$hour * 60 + x$min + x$sec / 60)
# Compare time from midnight to break duration.
dif.vec = df$TFM - df$DUR
# Keep crosses only if precipitation is occurring.
crosses = intersect(which(dif.vec < 0), which(df$PRECIP > 0))
# Calculate new midnight break chracteristics.
pcp.frac = -dif.vec[crosses] / df$DUR[crosses]
pcp.new = pcp.frac * df$PRECIP[crosses]
dt.new = format(as.POSIXlt(as.POSIXct(df$DT_1[crosses]) - df$TFM[crosses] * 60), "%Y-%m-%d %H:%M:%S")
dur.new = df$DUR[crosses] - df$TFM[crosses]
# Reduce the original precipitation after the midnight break
df$PRECIP[crosses] = df$PRECIP[crosses] - pcp.new
df$DUR[crosses] = df$DUR[crosses] - dur.new
# Remove the TFM column.
df = df[,-4]
# Create a new dataframe with midnight breakpoints.
df.new = data.frame(dt.new, pcp.new, dur.new)
names(df.new) = names(df)
# Combine dataframes.
df.out = rbind(df, df.new)
df.out = df.out[order(df.out$DT_1),]
return(df.out)}
# A function to aggregate precipitation breakpoints to a specific interval.
aggregate_precip_data = function(data) {
# Subset Precipitation Dataframe
df = data[[1]]
# Create Columns for Clustering
minDate = as.Date(substr(min(df$DT_1), 1, 10))
maxDate = as.Date(substr(max(df$DT_1), 1, 10))
df$Year = as.numeric(substr(df$DT_1, 1, 4))
df$Month = as.numeric(substr(df$DT_1, 6, 7))
df$Day = as.numeric(substr(df$DT_1, 9, 10))
df$Hour = as.numeric(substr(df$DT_1, 12, 13))
df$Minute = as.numeric(substr(df$DT_1, 15, 16))
df$Cluster = (df$Hour*60 + df$Minute) %/% as.numeric(ai)
# Aggregate Data
aggDF = aggregate(PRECIP ~ Year + Month + Day + Cluster, data = df, function(x) sum(x, na.rm = T))
aggDF$Cluster = aggDF$Cluster*as.numeric(ai)
aggDF$Hour = aggDF$Cluster%/%60
aggDF$Minute = aggDF$Cluster - aggDF$Hour*60
aggDF$DT_1 = as.POSIXct(paste(aggDF$Year, "-", aggDF$Month, "-", aggDF$Day, " ", formatC(aggDF$Hour, width = 2, format = "d", flag = "0"), ":", formatC(aggDF$Minute, width = 2, format = "d", flag = "0"), ":00", sep = ""), format = "%Y-%m-%d %H:%M:%S")
aggDF$DT_2 = aggDF$DT_1 - as.numeric(ai)*60
# Reformat Output
outDF = data.frame(sort(unique(c(aggDF$DT_1, aggDF$DT_2))))
names(outDF) = c("DT_1")
outDF = merge(outDF, aggDF[,c(5,8)], by = c("DT_1"), all = T)
outDF$DUR = as.numeric(ai)
outDF$PRECIP[is.na(outDF$PRECIP)] = 0
data[[1]] = outDF
return(data)
}
# A function to convert units from English to metric.
convert_units = function(data) {
if (toupper(verb) == "T") {cat(lr,"Converting units...")}
var.list = c("PRECIP", "AIR_TEMP", "MAX_TEMP", "MIN_TEMP", "SO_RAD", "W_VEL", "DP_TEMP", "ELEV")
# Parse arguments.
if (length(u.loc) == 0){vars = NULL}
if (length(u.loc) > 0){
x = grep("-", args)
x = x[x >= u.loc]
start = x[1]+2
end = min(x[2]-1, max(length(args)), na.rm = T)
vars = toupper(args[start:end])
if (start > end){vars = NA}}
# Handle solar radiation (which must be in english units as opposed to metric units).
if (length(grep("SO_RAD", vars, ignore.case = T)) > 0){vars = vars[!grepl("SO_RAD", vars, ignore.case = T)]}
else {vars = na.omit(c(vars, "SO_RAD"))}
# Handle missing elevation data.
if (is.na(data[[4]][["ELEV"]]) == T) {data[[4]][["ELEV"]] = "0"}
if (as.numeric(data[[4]][["ELEV"]]) == -99999) {data[[4]][["ELEV"]] = "0"}
# Most or all units are metric (convert exceptions).
if (toupper(u) == "M"){}
# Most or all units are english (do not convert exceptions).
if (length(vars) == 0){vars = NA}
if (toupper(u) == "E"){vars = var.list[!grepl(paste(vars, collapse = "|"), var.list, ignore.case = T)]}
# Perform simple conversions.
if ("PRECIP" %in% vars){data[[1]]$PRECIP = data[[1]]$PRECIP*25.4} # Conversion from in to mm
if ("MAX_TEMP" %in% vars){data[[3]]$MAX_TEMP = (data[[3]]$MAX_TEMP - 32) * 5/9} # Conversion from F to C
if ("MIN_TEMP" %in% vars){data[[3]]$MIN_TEMP = (data[[3]]$MIN_TEMP - 32) * 5/9} # Conversion from F to C
if ("AIR_TEMP" %in% vars){data[[2]]$AIR_TEMP = (data[[2]]$AIR_TEMP - 32) * 5/9} # Conversion from F to C
if ("DP_TEMP" %in% vars){data[[3]]$DP_TEMP = (data[[3]]$DP_TEMP - 32) * 5/9} # Conversion from F to C
if ("SO_RAD" %in% vars){data[[3]]$SO_RAD = data[[3]]$SO_RAD * data[[3]]$DUR * 60 / 41840} # Conversion from W/m^2 to Langleys
if ("W_VEL" %in% vars){data[[3]]$W_VEL = data[[3]]$W_VEL * 0.44704} # Conversion from mph to m/s
if ("ELEV" %in% vars & length(na.omit(data[[4]][["ELEV"]])) > 0){ # Make sure elevation was provided
data[[4]][["ELEV"]] = as.numeric(data[[4]][["ELEV"]]) * 0.3048} # Conversion from ft to m
# Replace missing metadata with zero values.
if (is.na(data[[4]][["STATION"]])) {data[[4]][["STATION"]] = "STATION"}
if (is.na(data[[4]][["LAT"]])) {data[[4]][["LAT"]] = "0"}
if (is.na(data[[4]][["LON"]])) {data[[4]][["LON"]] = "0"}
if (is.na(data[[4]][["ELEV"]])) {data[[4]][["ELEV"]] = "0"}
return(data)}
# A function to initialize quality checking data.
initialize_qc_data = function(data) {
for (j in 1:3) {data[[j + 4]] = data[[j]]}
return(data)}
# A function to check input data quality.
quality_check_inputs = function(data) {
if (toupper(verb) == "T") {cat(lr,"Checking input data quality...")}
chkth = as.numeric(chkth)
spkth = as.numeric(spkth)
strth = as.numeric(strth)
stkth = as.numeric(stkth)
data = create_rate_qc_data(data)
data = run_nonprecip_checks(data)
data = run_precip_checks(data)
data = remove_qc_fails(data)
return(data)}
# A function to extract rates from breakpoint format data.
create_rate_qc_data = function(data) {
# Set variable name and location vectors.
nm = c("PRECIP", "AIR_TEMP", "REL_HUM", "MIN_TEMP", "MAX_TEMP", "SO_RAD", "W_VEL", "W_DIR", "DP_TEMP")
r.loc = c(5, 6, 6, 7, 7, 7, 7, 7, 7)
# Use variable data and duration data to determine rates of change.
for (j in 1:length(nm)) {
VAR = data[[r.loc[j]]][[nm[j]]]
DUR = data[[r.loc[j]]]$DUR
DEL = c(0, diff(VAR))
if (length(DEL) == length(VAR)) {data[[r.loc[j]]][[paste(nm[j], "_DEL", sep = "")]] = DEL}
data[[r.loc[j]]][[paste(nm[j], "_QC", sep = "")]] = rep("PASS", length(VAR))}
return(data)}
# A function to impose non-precipitation quality checks on the data.
run_nonprecip_checks = function(data) {
# Set variable name, limit, and location vectors.
nm = c("PRECIP", "AIR_TEMP", "REL_HUM", "MIN_TEMP", "MAX_TEMP", "SO_RAD", "W_VEL", "W_DIR", "DP_TEMP")
i.uv.lims = c(2000, 70, 1000, 45, 60, 2865, 120, 360, 40)
i.lv.lims = c(0, -100, 0, -90, -20, 0, 0, 0, -25)
i.r.lims = c(35, 1, 1, 1, 1, 30, 1, 360, 1)
i.loc = c(5, 6, 6, 7, 7, 7, 7, 7, 7)
fnm = paste(nm, "_DEL", sep = "")
qcnm = paste(nm, "_QC", sep = "")
# Record QC failures.
for (j in 2:length(nm)) {
if (nrow(data[[i.loc[j]]]) > 0) {
dur.vec = data[[i.loc[j]]]$DUR
var.vec = data[[i.loc[j]]][[nm[j]]]
del.vec = data[[i.loc[j]]][[fnm[j]]]
rat.vec = del.vec / dur.vec
qcr.vec = data[[i.loc[j]]][[qcnm[j]]]
# Perform physical quality checking.
if (toupper(qcop) %in% c("B", "P")) {
qcr.vec = extreme_limit_test(var.vec, qcr.vec, i.uv.lims[j], i.lv.lims[j], "VALUE")
qcr.vec = extreme_limit_test(rat.vec, qcr.vec, i.r.lims[j], -i.r.lims[j], "RATE")}
# Perform empirical quality checking
if (toupper(qcop) %in% c("B", "E")) {
qcr.vec = rle_streak_test(var.vec, qcr.vec, strth, "STREAK")
qcr.vec = snr_spike_test(dur.vec, del.vec, rat.vec, qcr.vec, chkth, spkth, "SPIKE")
qcr.vec = rle_stick_test(qcr.vec, stkth, "STICK")}
# Store results.
data[[i.loc[j]]][[qcnm[j]]] = qcr.vec}}
return(data)}
# A function to record extreme values from a data vector in a data quality vector.
extreme_limit_test = function(data.vec, qcr.vec, upper.limit, lower.limit, flag) {
num.loc = !is.na(data.vec)
if (sum(num.loc) > 0) {
qcr.vec[num.loc][data.vec[num.loc] > upper.limit] = flag
qcr.vec[num.loc][data.vec[num.loc] < lower.limit] = flag}
return(qcr.vec)}
# A function to record streaks from a data vector in a data quality vector.
rle_streak_test = function(data.vec, qcr.vec, str.th, flag) {
rle.data = rle(data.vec)
loc.data = cumsum(rle.data$lengths)
streak.intersect = which(rle.data$lengths >= str.th)
streak.ends = loc.data[streak.intersect]
streak.lengths = rle.data$lengths[streak.intersect]
streak.begins = streak.ends - (streak.lengths - 1)
streaks = unlist(mapply(function(x, y) x:y, streak.begins, streak.ends))
qcr.vec[streaks] = flag
return(qcr.vec)}
# A function to record spikes from a data vector in a data quality vector.
snr_spike_test = function(dur.vec, del.vec, rat.vec, qcr.vec, chk.th, spk.th, flag) {
# Perform basic calculations and setup.
noise = var(rat.vec, na.rm = T)
snr.vec = abs(rat.vec) / noise
lcrit = length(snr.vec)
crit.diff = 1 - spk.th
# Limit how much data to check.
short.dur = which(dur.vec <= 360)
high.dels = which(abs(del.vec) > quantile(abs(del.vec), chk.th, na.rm = T))
high.rats = which(abs(rat.vec) > quantile(abs(rat.vec), chk.th, na.rm = T))
high.snrs = which(snr.vec > quantile(snr.vec, chk.th, na.rm = T))
highs = Reduce(intersect, list(short.dur, high.dels, high.rats, high.snrs))
if (lcrit %in% highs) {highs = highs[-which(highs == lcrit)]}
# Continue calculations.
heads = rat.vec[highs]
tails = rat.vec[highs + 1]
norm.diff = abs(heads + tails) / (abs(heads) + abs(tails))
results = norm.diff < crit.diff
qcr.vec[results] = flag
return(qcr.vec)}
# A function to record sticks from a data quality vector in a data quality vector.
rle_stick_test = function(qcr.vec, stk.th, flag) {
# Setup rle analysis.
rle.data = rle(qcr.vec)
loc.data = cumsum(rle.data$lengths)
short.lengths = which(rle.data$lengths <= stk.th)
qcr.passes = which(rle.data$values == "PASS")
qcr.checks = intersect(short.lengths, qcr.passes)
# Check potential sticks.
if (length(qcr.checks) > 0) {
qcr.starts = qcr.checks - 1
qcr.ends = qcr.checks + 1
qcr.identical = which(rle.data$values[qcr.starts] == rle.data$values[qcr.ends])
# Record actual sticks.
if (length(qcr.identical) > 0) {
qcr.vec[loc.data[qcr.checks[qcr.identical]]] = flag}}
return(qcr.vec)}
# A function to impose precipitation quality checks on the data.
run_precip_checks = function(data) {
var.vec = data[[5]][["PRECIP"]]
# Perform empirical quality checking
if (toupper(qcop) %in% c("B", "E")) {
data[[5]][["PRECIP_QC"]] = return_period_test(var.vec, data[[5]][["PRECIP_QC"]], rp, "RARE")}
return(data)}
# A function to handle quality checking failures.
return_period_test = function(data.vec, qcr.vec, max.return.period, flag) {
return(qcr.vec)}
# A function to handle quality checking failures.
remove_qc_fails = function(data) {
# Set variable name and location vectors.
nm = c("PRECIP", "AIR_TEMP", "REL_HUM", "MIN_TEMP", "MAX_TEMP", "SO_RAD", "W_VEL", "W_DIR", "DP_TEMP")
i.loc = c(5, 6, 6, 7, 7, 7, 7, 7, 7)
qcnm = paste(nm, "_QC", sep = "")
# Replace QC failures.
for (j in 1:length(nm)) {
if (nrow(data[[i.loc[j]]]) > 0) {
var.vec = data[[i.loc[j]]][[nm[j]]]
qcr.vec = data[[i.loc[j]]][[qcnm[j]]]
var.vec[qcr.vec != "PASS"] = NA
data[[i.loc[j]]][[nm[j]]] = var.vec}}
return(data)}
# A function to check output daily data quality.
quality_check_outputs = function(data, dly.df) {
if (toupper(verb) == "T") {cat(lr,"Checking output data quality...")}
data = impose_daily_value_limits(data, dly.df)
return(data)}
# A function to impose physical limitations on data.
impose_daily_value_limits = function(data, dly.df) {
# Set daily value limits.
d.u.lims = c(2000, 60, 500, 45, 60, 1432, 60, 360, 40)
d.l.lims = c(0, -90, 0, -90, -20, 1, 0, 0, -25)
# Set names.
nm = c("PRECIP", "AIR_TEMP", "REL_HUM", "MIN_TEMP", "MAX_TEMP", "SO_RAD", "W_VEL", "W_DIR", "DP_TEMP")
names(d.u.lims) = nm
names(d.l.lims) = nm
# Replace extreme values with NA.
for (j in nm) {data[[dly.df]][[j]] = extreme_limit_replace(data[[dly.df]][[j]], d.u.lims[[j]], d.l.lims[[j]], NA)}
return(data)}
# A function to record extreme value failures in a vector.
extreme_limit_replace = function(data.vec, upper.limit, lower.limit, flag) {
num.loc = !is.na(data.vec)
if (sum(num.loc) > 0) {
data.vec[num.loc][data.vec[num.loc] > upper.limit] = flag
data.vec[num.loc][data.vec[num.loc] < lower.limit] = flag}
return(data.vec)}
# A function to obtain an acceptable period of data (sm = 1) or storm event (sm = 2).
trim_data = function(data, precip.ts.df, alt.ts.df, d.ts.df, event.list) {
if (toupper(verb) == "T") {cat(lr,"Trimming to specified time period...")}
# General Setup
data = break_storms(data, precip.ts.df, event.list)
# Use all variables for time bounds.
if (toupper(alt) == "T" & toupper(ipb) == "F" & toupper(cv) != "F"){
maxs = c(max(data[[precip.ts.df]]$DT_1, na.rm = T), max(data[[alt.ts.df]]$DT_2, na.rm = T), max(data[[d.ts.df]]$DT_3, na.rm = T))
mins = c(min(data[[precip.ts.df]]$DT_1, na.rm = T), min(data[[alt.ts.df]]$DT_2, na.rm = T), min(data[[d.ts.df]]$DT_3, na.rm = T))}
# Exclude only alternative variables for time
if (toupper(alt) == "F" & toupper(ipb) == "F" & toupper(cv) != "F"){
maxs = c(max(data[[precip.ts.df]]$DT_1, na.rm = T), max(data[[d.ts.df]]$DT_3, na.rm = T))
mins = c(min(data[[precip.ts.df]]$DT_1, na.rm = T), min(data[[d.ts.df]]$DT_3, na.rm = T))}
# Exclude only precipitation variables for time bounds.
if (toupper(alt) == "T" & toupper(ipb) == "T" & toupper(cv) != "F"){
maxs = c(max(data[[alt.ts.df]]$DT_2, na.rm = T), max(data[[d.ts.df]]$DT_3, na.rm = T))
mins = c(min(data[[alt.ts.df]]$DT_2, na.rm = T), min(data[[d.ts.df]]$DT_3, na.rm = T))}
# Use only daily variables for time bounds.
if (toupper(alt) == "F" & toupper(ipb) == "T" & toupper(cv) != "F"){
maxs = c(max(data[[d.ts.df]]$DT_3, na.rm = T))
mins = c(min(data[[d.ts.df]]$DT_3, na.rm = T))}
# Use only precipitation variables for time bounds.
if (toupper(cv) == "F"){
maxs = c(max(data[[precip.ts.df]]$DT_1, na.rm = T))
mins = c(min(data[[precip.ts.df]]$DT_1, na.rm = T))}
# Record Bounds
start = max(mins, na.rm = T)
end = min(maxs, na.rm = T)
# Trim data to exact bounds based on user inputs.
if (toupper(alt) == "T") {groups = 5:7}
if (toupper(alt) == "F") {groups = c(5, 7)}
if (toupper(cv) == "F") {groups = 5}
bounds = time_bounds(start, end)
dt_list = c("DT_1", "DT_2", "DT_3")
for (j in groups){
data[[j]] = data[[j]][data[[j]][[dt_list[j - 4]]] >= bounds[1],]
data[[j]] = data[[j]][data[[j]][[dt_list[j - 4]]] <= bounds[2],]}
# Store expected number of days for final checking.
daysCount <<- difftime(bounds[2], bounds[1], units = "days")
# Record station observation data.
data[[4]][["B_YR"]] = format(bounds[1], format = "%Y")
data[[4]][["OBS_YRS"]] = as.numeric(diff.Date(c(bounds[3], bounds[4])))/365.2425
data[[4]][["YRS_SIM"]] = as.numeric(diff.Date(c(bounds[1], bounds[2])))/365.2425
return(data)}
# A function to calculate breaks between storms.
break_storms = function(data, in.index, out.index) {
if (toupper(verb) == "T") {cat(lr,"Separating storms...")}
data[[in.index]] = data[[in.index]][complete.cases(data[[in.index]]$PRECIP),]
data[[in.index]] = cum_to_inc(data[[in.index]])
data[[in.index]] = identify_storms(data[[in.index]])
if (toupper(ei) == "T"){data[[in.index]] = int_30m(data[[in.index]])}
data[[out.index]] = split(data[[in.index]], data[[in.index]]$SID)
return(data)}
# A function to convert cumulative precipitation data to incremental data.
cum_to_inc = function(df) {
if (toupper(cp) == "T"){
if (toupper(verb) == "T") {cat(lr,"Converting to incremental precipitation...")}
difs = c(0, diff(as.numeric(df$PRECIP)))
difs[which(difs < 0)] = df$PRECIP[which(difs < 0)]
df$PRECIP = as.numeric(difs)}
zeros = which(df$PRECIP == 0)
if (length(zeros) > 0){df = df[-zeros,]}
df$INT = df$PRECIP / (df$DUR / 60)
return(df)}
# A function to identify storm events.
identify_storms = function(df) {
# Create antecedent and cumulative time counts.
dif = c(df$DUR[1], difftime(tail(df$DT_1, -1), head(df$DT_1, -1), units = "mins"))
df$ANT = dif
df$BTW = df$ANT - df$DUR
df$CUM = cumsum(df$ANT)
# Determine connectivity.
df = evaluate_connectivity(df)
# Increase event count unless connected.
d.logic = c(1, as.numeric(!(tail(df$D_CON, length(df$D_CON) - 1) * head(df$D_CON, length(df$D_CON) - 1))))
t.logic = as.numeric(df$T_CON)
e.logic = as.numeric(d.logic == 1 | t.logic == 1)
e.id = cumsum(e.logic)
# Save and return results.
df$SID = e.id
return(df)}
# A function to evaluate storm event connectivity.
evaluate_connectivity = function(df) {
# Determine rows for more optimal performance (by subsetting).
minutes = as.numeric(tth) * 60
rows = ceiling(minutes / min(df$DUR[df$DUR > 0], na.rm = T))
# Determine storm connectivity.