-
Notifications
You must be signed in to change notification settings - Fork 2
/
server.R
1709 lines (1462 loc) · 53.6 KB
/
server.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
# Define file upload limit, now 15 MB
options(shiny.maxRequestSize = 15*1024^2,
warn = -1)
shinyServer(function(input, output, session) {
######################
### Error messages ###
######################
message.fail.upload = "An error has occurred. Please check your upload settings and the required column names."
message.no.k = "HFD parameter K is not set."
message.no.sapflow = "No sap flow data available. \nMake sure that wood and sensor properties \nare entered correctly (see Settings)."
#' Function to return table with warning message
tab.with.message = function(message,
col = "#E56855", # theme red
background = "#cccccc" # theme grey
) {
m = matrix(data = c(message))
return(
datatable(m, options = list(dom = 't'), colnames = NULL) %>%
formatStyle(
1,
color = col,
backgroundColor = background,
fontWeight = 'bold'
)
)
}
observeEvent(input$saveallcsv, {
# Save settings
save.settings()
# Save data in long format
save.data.uploaded()
# Save measuring environment
save.measuring.env()
# Save filtered data
save.data.filtered()
# Save K values
save.k.values()
# Save sapflow metrics
save.sapflow.metrics()
# Save sapflow
save.sapflow()
# Save TWU
save.twu()
# Save Uncertainty Absolut values
save.uncertaintyOutputsAbs()
# Save Uncertainty Absolut values
save.uncertaintyOutputsRel()
})
################
### SETTINGS ###
################
##### Save and update Input ####
list_with_params = c(
# Wood properties
"stemDiameter", "barkThickness",
"sapWoodDepth", "swExact", "heartWoodDepth", "ThermalDiffusivity",
# Sensor properties,
"dist2first", "spacer", "Zax", "Ztg", "sensorType",
"thermoDistances", "thermoNumbering", "distInput", "depthInput",
# Project settings
"folder",
# Output
"fileFor", "figFor", "figTitle", "fileAppend", "fileAppendName",
"figTheme", "fillColors"
)
save.settings = function(){
inputs_ls = list()
for (i in 1:length(list_with_params)) {
inputs_ls[list_with_params[i]] = input[[list_with_params[i]]]
}
save.rds(path = projectPath(),
name = "inputs",
rdsObject = inputs_ls,
ui.input = input)
}
#' Eventlistener to all reactive inputs
#' (Menu bottom)
observeEvent(input$save.inputs, {
save.settings()
})
observeEvent(input$load.inputs,{
if(!file.exists(input$fileSettings$datapath)) {return(NULL)}
savedInputs <- readRDS(input$fileSettings$datapath)
for (i in 1:length(savedInputs)) {
id = names(savedInputs[i])[1]
v = savedInputs[id][[1]]
session$sendInputMessage(id, list(value = v))
}
})
#### Variables ####
#' Shiny function that returns 'available volumes on the system'
volumes = getVolumes()
#' Variable holding possible root directories
roots = c('working directory' = getwd(),
system = volumes())
#' Shiny function to 'to navigate the filesystem'
folderInput1 <- shinyDirChoose(input, 'folder',
roots = roots,
filetypes = c('', 'txt'))
#' Reactive variable holding the current project path
#' If not project is selected it returns the root directory
projectPath <- reactive({
if (!isTruthy(input$folder)){
roots[[1]]
} else {
parseDirPath(roots = roots, selection = input$folder)
}
})
#' Reactive variable holding the current project name
projectName <- reactive({
return(tail(unlist(strsplit(as.character(projectPath()), "/")), 1))
})
#' Reactive variable holding the name of plot titles
#' (for saved plots)
#' If not defined in the UI it returns "", i.e. no title appears
figTitle <- reactive({
return(input$figTitle)
})
#' Set default theme
theme_set(theme_bw())
#' Reactive variable holding ggplot theme
#' Can be defined in UI
plot_theme <- reactive({
themes[[input$figTheme]]
})
#' Reactive variable holding fill colors to be used in
#' all plots with discrete data
#' Can be defined in UI
fillcolors_react = reactive({
return(input$fillColors)
})
#' Global function (accessible from other scripts)
#' that returns a set of N fillcolors
fillcolors <<- function(N){
col = fillcolors_react()
return(col)
}
#' Reactive variable holding colors to be used in
#' all plots with gradient color scale
#' Can be defined in UI
gradientcolors_react = reactive({
opt = input$fillColors
return(get(opt)(2))
})
#' Global function (accessible from other scripts)
#' that returns 2 colors
gradientcolors <<- function(){
col = gradientcolors_react()
return(col)
}
#### UI output ####
#' Update diameter or circumference in the UI if one of them is provided
observeEvent(input$stemDiameter, {
updateNumericInput(session,
inputId = "stemCircumference",
value = round(input$stemDiameter*pi, 1))
})
observeEvent(input$stemCircumference, {
updateNumericInput(session,
inputId = "stemDiameter",
value = round(input$stemCircumference/pi, 1))
})
#' Function to render all ggplots with defined theme
output$theme_output <- renderUI({
#req(input$figTheme)
theme_set(plot_theme())
NULL
})
#' Show project path in Settings > Project
#' if a project folder is selected
output$prjDir <- renderPrint({
cat(projectPath())
})
#' Show string as default
output$prjName <- renderPrint({
cat("No project chosen")
})
#### Buttons ####
#' Button to create a project (Settings > Project)
#' Requires a folder to be selected (Folder select)
#' If directory does not exist create two folders:
#' 'csv-files', 'graphics'
#' Sets project name = project folder name
observeEvent(input$crtPrj, {
# If no folder have been selected show error
if (!isTruthy(input$folder)){
showNotification("Please choose a directory first!",
type = "error")
} else{
req(input$folder)
csvPath = paste(projectPath(),
"/csv-files/", sep = "")
figPath = paste(projectPath(),
"/graphics/", sep = "")
if (!dir.exists(csvPath)){
dir.create(csvPath)
}
if (!dir.exists(figPath)){
dir.create(figPath)
}
showNotification("Project set successfully!",
type = "message")
}
# Update project name in header
output$prjName <- renderPrint({
# If name is provided manually add it to header
cat(projectName())
})
})
#### Thermometer positions ####
#' Reactive variable holding thermometer positions
#' (a vector numbering the thermometers) derived from input file
positions <- reactive({
if (!is.null(input$file1)){
req(input$setData)
}
h = update.positions(data = rawData(),
ui.input = input,
reactive.value = values)
values = h[[1]]
positions = h[[2]]
return(positions)
})
#' Reactive variable holding depth of each thermometer positions
#' in cm
depths <- reactive({
if (!is.null(input$file1)){
req(input$setData)
}
out = try(
{
update.depths(ui.input = input,
positions = positions(),
swd = sapWoodDepth())
}
)
if (is.character(out)){
return(NULL)
} else {
return(out)
}
})
#' Table with thermometer data, i.e.
#' thermometer position, depth, area and circumference of ring
#' (Settings > Measuring environment)
get.depths.table <- reactive({
rawData = rawData()
# Conditions to determine whether processed data contains relevant
# wood properties
# If true, show them
cond1 = input$inputType == "HFD_processed_read"
cond2 = input$inputType == "HFD_processed_write" &
sapWoodDepth() == 0
cond3 = all(c("position", "R", "Aring", "Cring") %in% colnames(rawData))
if ((cond1 | cond2) & cond3) {
return(
rawData %>%
distinct(position, R, Aring, Cring) %>%
select(position, R, Aring, Cring) %>%
mutate_at(vars(2, 3, 4), round, 1) %>%
`colnames<-` (
c("Position", "Thermometer R (cm)", "Area (cm²)",
"Circ. (cm)")
)
)
} else {
depths = depths()
if (is.null(depths) | sum(depths$R) == 0) {
return(
tab.with.message(
message = "Specify wood and sensor properties. Make sure the number of inputs corresponds to your data."
)
)
} else {
return(
depths %>%
select(-R) %>%
mutate_at(vars(2), round, 2) %>%
mutate_at(vars(3, 4), round, 1) %>%
`colnames<-` (
c(
"Position",
"Thermometer R (cm)",
"Area (cm²)",
"Circ. (cm)"
)
)
)
}
}
})
#' UI depths table
output$depth.table <- DT::renderDataTable(rownames = FALSE, {
return(get.depths.table())
}, options = list(dom = 't'))
output$depth.table.info <- renderText({
depths = get.depths.table()
note = ""
if (!is.null(ncol(depths))){
if (min(depths[, 2]) < 0){
note = paste(
note,
"<b>Note:</b> negative values for 'Thermometer R' indicate that the sensor needles cross the center of the
tree (i.e. needle length > diameter / 2 - barkthickness) and the respective thermometer positions are on the
opposite side of the tree. ", sep="<br/>")
}
needle_cover = max(depths[, 2]) - min(depths[, 2])
if (needle_cover > (2*get.rxy(ui.input = input))){
note = paste(
note,
"<b>Note:</b> the sensors needles seem to be longer than the stem diameter.", sep="<br/>")
}
if (max(depths[, 2] > get.rxy(ui.input = input))){
note = paste(
note,
"<b>Note:</b> one or more thermometers are outside the stem.", sep="<br/>")
}
}
return(note)
})
save.measuring.env = function(){
save.csv(path = projectPath(),
name = "sensor_props",
csvObject = get.depths.table(),
ui.input = input)
}
#' Eventlistener to save thermometer depth table
#' (Settings > Measuring environment)
observeEvent(input$save.sensor_props, {
save.measuring.env()
})
############
### DATA ###
############
#### Variables ####
#' Reactive variable holding raw sap flow data
#' If no data set is defined, use default data set
rawData <- reactive({
if (is.null(input$file1)){
defaultData = "./data/default_Avicennia_g.csv"
print("Default data")
data = get.temperatures.HFD(defaultData)
} else {
data = get.rawData(input)
}
return(data)
})
#' Reactive variable holding sap flow data in long format
#' Unfiltered
#' Transformation of data set from wide to long depends on
#' input type: raw temperature (HFD sensor data),
#' temperature differences
deltaTempLongNoFilter <- reactive({
an.error.occured = F
tryCatch({
data = rawData()
positions = get.positionsFromRawData(dataSource = data,
input = input)
if (input$inputType == "HFD_raw"){
d = get.delta.from.temp(data, positions)
}
if (input$inputType == "HFD_delta"){
d = get.delta.temp(data, positions)
}
if (input$inputType == "HFD_processed_read" |
input$inputType == "HFD_processed_write"){
# if (c("datetime", "doy", "dTsym.dTas") %in% colnames(data)){
d = data
# }
}
return(d)
},
error = function(e) {an.error.occured <<- TRUE})
if (an.error.occured){
showNotification("Upload failed. Check upload settings.",
type = "error")
}
})
#' Create empty reactive value with a placeholder for the
#' data set in long format
values <- reactiveValues(deltaTempLong = NULL)
#' Reactive variable holding long-format data
#' Assigned to reactive value if empty
deltaTempLong <- reactive({
if (is.null(values$deltaTempLong)){
values$deltaTempLong <- deltaTempLongNoFilter()
}
return(values$deltaTempLong)
})
#' Trigger to update reactive data when 'Use data'
#' button is pressed
#' Updates data for the whole App
observeEvent(input$setData, {
values$deltaTempLong <- deltaTempLongNoFilter()
# Reset selected K values (empty table)
emptyKvalues()
})
#' Reactive variable holding long-format data for
#' specific UI-selected thermometer position
deltaTempLong.depth <- reactive({
req(input$kPositionSelect)
deltaTempLong() %>%
filter(position == input$kPositionSelect)
})
#### FILTER ####
#' Button to load filter options
#' Assigns unfiltered, long-format data as reactive
#' value 'deltaTempLong'
observeEvent(input$LoadFilter, {
if (input$inputType == "HFD_processed_read"){
showNotification("Read-only modus. Filter can't be applied.",
type = "warning")
} else {
values$deltaTempLong <- deltaTempLongNoFilter()
}
})
#' Button to apply filter
#' Assigns filterd, long-format data as reactive
#' value 'deltaTempLong'
observeEvent(input$FilterApply, {
if (input$inputType == "HFD_processed_read"){
showNotification("Read-only modus. Filter can't be applied.",
type = "warning")
} else {
values$deltaTempLong <- get.filteredData(data = values$deltaTempLong,
ui.input = input)
}
})
#' Button to delete filter
#' Assigns unfiltered, long-format data as reactive
#' value 'deltaTempLong'
observeEvent(input$FilterDelete, {
values$deltaTempLong <- deltaTempLongNoFilter()
})
#### UI ####
#' Reactive variable to get start and end data of data set
minMaxDatetime <- reactive({
if (!is.null(input$file1)){
req(input$setData)
}
d = rawData()
minDate = as.Date(d[which.min(as.POSIXct(d$datetime)),
"datetime"])
maxDate = as.Date(d[which.max(as.POSIXct(d$datetime)),
"datetime"])
return(c(minDate, maxDate))
})
#' Helper function to built Filter-UI (load or delete)
filter_helper = function(input, output){
if (!is.null(input$file1)){
req(input$setData)
}
output = update.filter.ui(ui.output = output, ui.input = input)
minMaxDatetime = minMaxDatetime()
updateDateRangeInput(session, "daterange",
start = minMaxDatetime[1],
end = minMaxDatetime[2],
min = minMaxDatetime[1],
max = minMaxDatetime[2])
}
#' Eventlistener to built Filter-UI
#' Calling helper function, same as delete filter
observeEvent(input$LoadFilter, {
filter_helper(input, output)
})
#' Eventlistener to built Filter-UI
#' Calling helper function, same as load filter
observeEvent(input$FilterDelete, {
filter_helper(input, output)
})
#### Table outputs #####
#' UI Table with raw data, wide-format
#' (Data > Upload > Preview data)
#' datatable options
#' dom: l - length, t - table, i - information
#' p - pagination control
output$raw.wide <- DT::renderDataTable(rownames = FALSE, {
rawData = rawData()
if ("dTime" %in% colnames(rawData)){
rawDataTable = rawData %>%
mutate(dTime = round(dTime, 2))
} else {
rawDataTable = tab.with.message(message.fail.upload)
}
return(rawDataTable)
}, options = list(dom = "ltip"))
#' UI Table with raw data, long-format
#' (Data > Upload > Preview data)
output$raw.long <- DT::renderDataTable(rownames = FALSE, {
an.error.occured = FALSE
tryCatch({
tab = deltaTempLongNoFilter() %>% ungroup() %>%
mutate_if(is.numeric, round, 3)
},
error = function(e) {
an.error.occured <<- TRUE
})
if (an.error.occured) {
tab = tab.with.message(message.fail.upload)
}
return(tab)
}, options = list(dom = "ltip"))
#### Text output ####
output$fileName <- renderPrint({
cat(input$file1$name)
})
output$manualName <- renderPrint({
if (input$fileAppend == "manual"){
cat(input$fileAppendName)
}
})
#' UI Text output of remaining data points after filtering
#' (Data > Filter > Subset data)
output$dataPoints <- renderText({
filtered_data = deltaTempLong()
n_diff = nrow(deltaTempLongNoFilter()) - nrow(filtered_data)
if (any(is.na(filtered_data))){
paste("Data set contains NA values. <br/><br/>",
n_diff, " data points removed.")
} else {
paste(n_diff, " data points removed.")
}
})
#### Graphics ####
#' Reactive variable holding the histogram-like
#' plot with (filtered) data
filterPlot <- reactive({
plot.histogram(data = deltaTempLong(),
ui.input = input)
})
#' UI plot of filtered data
#' (Data > Filter > Figures)
output$filterPlot <- renderPlot({
filterPlot()
})
##### Custom View ####
#' Assign empty reactive value holding ui inputs for
#' customized figure
values <- reactiveValues(plotSettings = NULL)
#' Eventlistener assigning ui inputs to customize figure
#' to reactive value
observeEvent(input$renderPlot, {
values$plotSettings <- get.customizedPlotSettings(ui.input = input)
})
#' Reactive variable holding ui inputs to customize figure
plotSettings <- reactive({
return(values$plotSettings)
})
#' Reactive variable holding the plot showing customized
#' temperature visualizations
custumPlot <- reactive({
req(input$renderPlot)
plot.customTemperature(data = deltaTempLong(),
ui.input.processed = plotSettings())
})
#' #' UI of customized plot
#' #' (Data > View > Figure)
output$custumPlot <- renderPlot({
if (input$renderPlot == 0){
plot.emptyMessage("Customize your figure (settings).")
} else {
custumPlot()
}
})
#### Buttons ####
save.data.uploaded = function(){
save.csv(path = projectPath(),
name = "dTemp",
csvObject = deltaTempLongNoFilter(),
ui.input = input)
}
#' Eventlistener to save unfiltered, long-format data
#' (Data > Upload > Preview data)
observeEvent(input$save_dat_upl, {
save.data.uploaded()
})
#' Eventlistener to save plot with customized temperatures
#' (Data > View > Figure)
observeEvent(input$save.custumPlot, {
name = paste("dT",
input$rawPlot.xcol,
input$rawPlot.ycol,
input$rawPlot.col,
input$rawPlot.shape,
input$rawPlot.facet, sep = "_")
save.figure(path = projectPath(),
name = name,
plotObject = custumPlot(),
ui.input = input)
})
save.data.filtered = function(){
save.csv(path = projectPath(),
name = "dTemp_filtered",
csvObject = values$deltaTempLong,
ui.input = input)
}
#' Eventlistener to save filtered, long-format data
#' (Data > Filter > Figures)
observeEvent(input$save_dat_filter, {
save.data.filtered()
})
#' Eventlistener to save plot with filtered data
#' (Data > Filter > Figures)
observeEvent(input$save_dat_filter_fig, {
name = paste("dT_filtered",
as.character(input$filterPlot_type),
as.character(input$filterPlot_X),
as.character(input$filterPlot_col), sep = "_")
save.figure(path = projectPath(),
name = name,
plotObject = filterPlot(),
ui.input = input)
})
####################
### K-ESTIMATION ###
####################
#### UI #####
#' UI radio buttons to select thermometer position
#' Derives positions from filtered data set
#' (K-value > Estimation > K-value estimation)
output$kPositionSelect <- renderUI({
positions = positions()
pre_selected = positions[1]
radioButtons("kPositionSelect", "Thermometer position",
choices = positions,
selected = pre_selected, inline = T)
})
#' UI numeric inputs to define range in k-plots
#' Only visible if 'fixed' range is enabled
#' (K-value > Estimation > Control plots)
output$xRangeSlider <- renderUI({
data = deltaTempLong.depth()
tagList(
conditionalPanel(
condition = "input.k1Plot_scales == 'TRUE'",
fluidRow(
column(6, numericInput("k1Plot.x.min", "Min. x-value",
round(min(data$dTsym.dTas, na.rm = T), 2))),
column(6, numericInput("k1Plot.x.max", "Max. x-value",
round(max(data$dTsym.dTas, na.rm = T), 2))))
))
})
#### Variables ####
#' Reactive variable holding a list with cleaned data,
#' positive and negative k-value (K.dTas, K.dTsa) for a
#' selected thermometer position
cleanedDataAndKvalues <- reactive({
data = deltaTempLong() %>%
filter(position == input$kPositionSelect)
data = get.time.filtered.data(data = data,
ui.input = input)
data = get.dTratio.filtered.data(data = data,
ui.input = input)
if (nrow(data) > 0){
return(clean.data.iteration(data))
} else {
return(list(data = NULL, K.dTas = NA, K.dTsa = NA))
}
})
#' Reactive variable holding k-values derived
#' based on selected method for selected thermometer
#' position
kValue <- reactive({
return(get.kByMethod(data = deltaTempLong(),
ui.input = input))
})
#' Reactive variable holding k-values derived
#' based on selected method (zero-flow and regression)
#' for all thermometer positions, shown in tables
kComplete <- reactive({
return(get.kByMethodAll(deltaTempLong(),
ui.input = input))
})
#' Reactive variable holding k-values derived
#' from csv-input for all thermometer positions
kFromCsv <- reactive({
req(input$file2)
return(get.csvKvalues(ui.input = input))
})
#' Reactive variable holding a helper to check
#' if any k-values have been set
click <- reactive({
click = input$setK[1] + input$setKfromCsv[1] + input$setKfromRegression[1] +
input$setKfromZeroFlow[1]
# check if values$kvalues is filled due to upload of processed data
if ((input$inputType == "HFD_processed_read" |
input$inputType == "HFD_processed_write") &
!is.null(values$kvalues)){
click = click + 1
}
return(click)
})
#### Store and display selected k-values ####
#' Reactive value: assign empty placeholder to
#' store selected k-values
values <- reactiveValues(kvalues = NULL)
#' Reactive helper function to clear reactive kvalues
emptyKvalues = reactive({
cond1 = input$inputType == "HFD_processed_read" |
input$inputType == "HFD_processed_write"
cond2 = FALSE
if (cond1) {
deltaTempLong = deltaTempLong()
cond2 = any(grepl("(?i)k", colnames(deltaTempLong)))
}
if (cond1 & cond2) {
values$kvalues <- deltaTempLong %>%
mutate(method = "HFD_processed") %>%
distinct(position, method, k) %>%
select(position, method, k)
}
an.error.occured = F
tryCatch({
if (!cond1 | !cond2) {
values$kvalues <- data.frame(position = positions(),
method = rep(NA),
k = rep(NA))
}
},
error = function(e) {
an.error.occured <<- TRUE
})
})
#' Eventlistener to set/ store k-value as reactive value
#' K-value is stored in reactive value
#' (K-value > Estimation > K-value estimation)
observeEvent(input$setK, {
click = click()
if (click == 1){
emptyKvalues()
}
if (input$inputType == "HFD_processed_read"){
showNotification("Read-only modus. K can't be modified.",
type = "warning")
} else {
if (input$kMethod == "nf.regression"){
method_name = method_name_reg(ui.input = input)
} else {
method_name = gsub(".", "-", input$kMethod, fixed = TRUE)
}
values$kvalues[values$kvalues$position == input$kPositionSelect, 2:3] <- cbind(
method = as.character(method_name),
k = kValue())
}
})
#' Eventlistener to store k-values from csv upload
#' as reactive values
#' (K-value > Estimation > K-value estimation)
observeEvent(input$setKfromCsv, {
emptyKvalues()
values = fill.k.table(method = "csv",
k.data = kFromCsv(),
ui.input = input,
reactive.value = values)
})
#' Eventlistener to store k-values from automatic
#' regression as reactive values
#' (K-value > Estimation > K-value estimation)
observeEvent(input$setKfromRegression, {
emptyKvalues()
values = fill.k.table(method = "nf.regression",
k.data = kComplete()$nf.regression %>% ungroup() %>%
mutate_if(is.numeric, round, 3),
ui.input = input,
reactive.value = values)
})
#' Eventlistener to store k-values from zero-flow
#' no-flow estimate as reactive values
#' (K-value > Estimation > K-value estimation)
observeEvent(input$setKfromZeroFlow, {
emptyKvalues()
values = fill.k.table(method = "nf.median",
k.data = kComplete()$nf.median %>% mutate_if(is.numeric, round, 3),
ui.input = input,
reactive.value = values)
})
#### Text outputs ####
#' UI text output of current k-value,
#' depending on selected position and method
#' (K-value > Estimation > K-value estimation)
output$kCurrent <- renderPrint({
req(input$kPositionSelect)
kValue = kValue()
if (is.numeric(kValue)){
paste("K:", round(kValue, 3))
} else {
paste("K:", kValue)
}
})
#### Table outputs ####
#' UI table output of selected k-values
#' (K-value > Estimation > K-value estimation > Selected)
output$kSelected <- DT::renderDataTable(rownames = FALSE, {
kvalues = values$kvalues
# If reactive values 'kvalues' already exist, i.e. is data.frame, prettify table
# else return empty reactive value
if (is.data.frame(kvalues)){
# Transform k column to numeric and round values
kvalues = kvalues %>% mutate(k = round(as.numeric(k), 2))
# If NAs are produced and the a method is already chosen
# show 'Error' in k column
kvalues[is.na(kvalues$k) & !is.na(kvalues$method), "k"] = "Error"
return(kvalues)
} else {
return(kvalues)
}
}, options = list(dom = 't'))
#' UI table output of auto. regression k-values
#' (K-value > Estimation > K-value estimation > Regression)
output$kRegression <- DT::renderDataTable(rownames = FALSE, {
return(kComplete()$nf.regression %>%
ungroup() %>%
mutate_if(is.numeric, round, 2))
}, options = list(dom = 't'))
#' UI table output of closest zero-flow k-values
#' (K-value > Estimation > K-value estimation > Zero-flow)
output$kZeroFlow <- DT::renderDataTable(rownames = FALSE, {
return(kComplete()$nf.median %>%
ungroup() %>%
mutate_if(is.numeric, round, 2))
}, options = list(dom = 't'))
#' UI table output of uploaded k-values
#' (K-value > Estimation > K-value estimation > Read csv)
output$uploadedKvalues <- DT::renderDataTable(rownames = FALSE, {
return(kFromCsv())
}, options = list(dom = 't'))
#### Graphics ####
#' Reactive variable holding the diurnal flow plot
#' ggplot warnings are suppressed
kplotDiurnalFlow <- reactive({
plot.nighttime(data.complete = deltaTempLong.depth())
})
#' UI output of diurnal flow plot
#' (K-value > Estimation > Control plots > Diurnal flow)
output$kDiurnalPlot <- renderPlot({ kplotDiurnalFlow() })
#' Reactive variable holding the k-diagram
kplot1 <- reactive({
suppressWarnings(print(
plot.kEst1(data.complete = deltaTempLong.depth(),
data.adj = cleanedDataAndKvalues()[[1]],
k = kValue(),
ui.input = input)
))
})
#' UI output of K-diagram
#' (K-value > Estimation > Control plots > K-diagram)
output$kvaluePlot1 <- renderPlot({ kplot1() })
#' Reactive variable holding the control-diagram 1
#' ggplot warnings are suppressed
kplot2 <- reactive({
plot.kEst2(
data.complete = deltaTempLong.depth(),
data.adj = cleanedDataAndKvalues()[[1]],
k = kValue(),
ui.input = input
)
})
#' UI output of Control-diagram 1
#' (K-value > Estimation > Control plots > Control-diagram 1)
output$kvaluePlot2 <- renderPlot({ kplot2() })