forked from tamnva/R-SWAT
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.R
2667 lines (2214 loc) · 108 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
# maximum upload file 500 MB
options(shiny.maxRequestSize = 500*1024^2)
# Creating server
server <- function(input, output, session) {
#-----------------------------------------------------------------------------
# Global variables (use <<- for saving globalVariable inside observe)
# These variables are set by default, when opening the tool, will be updated
# according the user define in later steps
#-----------------------------------------------------------------------------
globalVariable <<- list()
displayOutput <<- list()
displayOutput$plotHru <<- FALSE
displayOutput$plotSub <<- FALSE
globalVariable$checkSimComplete <<- FALSE
globalVariable$loadProject <<- FALSE
globalVariable$TxtInOutSWAT <<- FALSE
globalVariable$TxtInOutSWATPlus <<- FALSE
globalVariable$SWATProject <<- TRUE
globalVariable$paraSelection <<- dataParaSelectionSWAT
globalVariable$HTMLdir <<- getwd()
globalVariable$nCaliParam <<- nrow(globalVariable$paraSelection)
globalVariable$runManualCaliSuccess <<- FALSE
#-----------------------------------------------------------------------------
# Global function for running SWAT
#-----------------------------------------------------------------------------
SWAT <- function(parameterValue){
# Make sure that parameterValue is data frame or matrix
if (is.matrix(parameterValue) |
is.data.frame(parameterValue)){
# Numbering the parameter set number and add it to the 1st column
nrow <- nrow(parameterValue)
parameterValue <- cbind(c(1:nrow), parameterValue)
} else {
# Convert input vector to matrix, add 1 to 1st column as the parameter set number
parameterValue <- matrix(c(1,parameterValue), nrow = 1)
}
#Remove row and column names
rownames(parameterValue) <- NULL
colnames(parameterValue) <- NULL
# Save parameter value to the globalVariable
globalVariable$parameterValue <<- rbind(globalVariable$parameterValue, parameterValue)
# Number of parallel runs cannot be higher than number of input parameter sets
globalVariable$ncores <<- min(globalVariable$ncores, nrow(parameterValue))
# Convert input parameter to matrix
parameterValue <- as.matrix(parameterValue)
# Run SWAT model
runSWATpar(globalVariable$workingFolder,
globalVariable$TxtInOutFolder,
globalVariable$outputExtraction,
globalVariable$ncores,
globalVariable$SWATexeFile,
parameterValue,
globalVariable$paraSelection,
globalVariable$caliParam,
globalVariable$copyUnchangeFiles,
globalVariable$fileCioInfo,
globalVariable$dateRangeCali,
globalVariable$firstRun)
# Objective function with initial parameter set
temp <- calObjFunction(parameterValue,
globalVariable$ncores,
globalVariable$nOutputVar,
globalVariable$userReadSwatOutput,
globalVariable$observedData,
globalVariable$workingFolder,
globalVariable$objFunction)
# If this is a first run
if (is.null(globalVariable$simData)){
globalVariable$simData <<- temp$simData
globalVariable$objValueCali <<- temp$objValueCali
globalVariable$objValueValid <<- temp$objValueValid
# If this is not the first run, then combine result with the existing data
} else {
globalVariable$simData <<- bindList(globalVariable$simData, temp$simData)
globalVariable$objValueCali <<- c(globalVariable$objValueCali, temp$objValueCali)
globalVariable$objValueValid <<- c(globalVariable$objValueValid, temp$objValueValid)
}
# Next run, no need to copy unchanged SWAT input files
globalVariable$copyUnchangeFiles <<- FALSE
# Parameter optimization: convert to the minimize problem, regardless of input
if (globalVariable$minOrmax == "Minimize"){
output <- temp$objValueCali
} else {
output <- - temp$objValueCali
}
# Return output
return(output)
}
#-----------------------------------------------------------------------------
# Save project setting
#-----------------------------------------------------------------------------
observeEvent(input$saveProject, {
# Check if working directory exists
if(dir.exists(globalVariable$workingFolder)){
# Display message that save was done
showNotification("Project settings were saved as 'RSWATproject.rds'
in the working folder", type = "message", duration = 10)
# Save project setting
shinyCatch(
saveRDS(globalVariable, file = paste(globalVariable$workingFolder, '/',
'RSWATproject.rds', sep ='')),
blocking_level = "error"
)
} else {
# Display error message
showNotification("Working folder does not exist, please define in
1.General setting => 1. Working folder",
type = "error", duration = 10)
}
})
#-----------------------------------------------------------------------------
# Load project setting
#-----------------------------------------------------------------------------
observe({
req(input$loadProject)
# Get full link of the selected file
shinyjs::disable("loadProject")
shinyCatch(RSWATProjectFile <- file.choose(), blocking_level = "none")
shinyjs::enable("loadProject")
shinyCatch(
if(substr(RSWATProjectFile, nchar(RSWATProjectFile) - 15,
nchar(RSWATProjectFile)) == "RSWATproject.rds"){
# Read data in this file
globalVariable <<- readRDS(RSWATProjectFile)
# Now the load project is true (because the RSWATproject.rds was given)
globalVariable$loadProject <<- TRUE
#-------------------------------------------------------------------------
# Update Tab 1: General Setting
#-------------------------------------------------------------------------
# Update select SWAT project
if(globalVariable$SWATProject){
updateSelectInput(session,
"SWATorSWATplus",
label = "1. SWAT or SWAT+ project",
choices = c('SWAT', 'SWAT+'),
selected = "SWAT")
} else {
updateSelectInput(session,
"SWATorSWATplus",
label = "1. SWAT or SWAT+ project",
choices = c('SWAT', 'SWAT+'),
selected = "SWAT+")
}
# Update working folder
updateTextInput(session, "workingFolder",
label = "2. Working folder",
value = globalVariable$workingFolder)
# Update TxtInOut folder
updateTextInput(session, "TxtInOutFolder",
label = "3. TxtInOut folder",
value = globalVariable$TxtInOutFolder)
# Update Select executable SWAT file Help
output$printSWATexe <- renderText(globalVariable$SWATexeFile)
# Update Files with list of all SWAT parameters
output$printSWATParamFile <- renderText(globalVariable$SWATParamFile)
# Update display content of the SWAT parameter file
output$tableSWATParam <- renderDataTable(globalVariable$SWATParam)
#-------------------------------------------------------------------------
# Update Tab 2: Parameter sampling
#-------------------------------------------------------------------------
# Update Select SWAT parameters for calibration and/or sensitivity analysis
if(globalVariable$SWATProject){
output$tableParaSelection <- renderExcel(
excelTable(data = globalVariable$paraSelection,
columns = columnsParaSelectionSWAT,
editable = TRUE,
allowInsertRow = TRUE,
allowInsertColumn = TRUE,
allowDeleteColumn = TRUE,
allowDeleteRow = TRUE,
rowDrag = TRUE,
columnResize = FALSE,
wordWrap = TRUE)
)
} else {
output$tableParaSelection <- renderExcel(
excelTable(data = globalVariable$paraSelection,
columns = columnsParaSelectionSWATPlus,
editable = TRUE,
allowInsertRow = TRUE,
allowInsertColumn = TRUE,
allowDeleteColumn = TRUE,
allowDeleteRow = TRUE,
rowDrag = TRUE,
columnResize = FALSE,
wordWrap = TRUE)
)
}
# Update Select sensitivity or calibration approach
updateSelectInput(session,
"samplingApproach",
label = "2. Select sensitivity or calibration approach",
choices = c('Sensi_Cali_(uniform_Latin_Hypercube_Sampling)',
'Sensi_(from_sensitivity_package)',
'Sensi_(from_userDefined_package)',
'Cali_(from_optimization_package)',
'Cali_(from_hydroPSO_package)',
'Cali_(from_nloptr_package)',
'Cali_(Dynamically_Dimensioned_Search)',
'Cali_(Generalized_Likelihood_Uncertainty_Estimation)',
'Cali_(from_userDefined_package)',
'Read_User_Parameter_File'),
selected = globalVariable$samplingApproach)
# Update Additional information about the selected sensitivity/calibration approach
updateTextAreaInput(session,
"inputInfo",
"3. Additional infomation about the selected sensitivity/calibration approach",
globalVariable$sensCaliCommand)
# Update define model output for extraction
if (globalVariable$SWATProject){
output$tableOutputExtraction <- renderExcel(
excelTable(data = globalVariable$outputExtraction,
columns = columnsOutputExtractionSWAT,
editable = TRUE,
allowInsertRow = TRUE,
allowInsertColumn = FALSE,
allowDeleteColumn = FALSE,
allowDeleteRow = TRUE,
rowDrag = FALSE,
columnResize = FALSE,
wordWrap = TRUE)
)
} else {
output$tableOutputExtraction <- renderExcel(
excelTable(data = globalVariable$outputExtraction,
columns = columnsOutputExtractionSWATPlus,
editable = TRUE,
allowInsertRow = TRUE,
allowInsertColumn = FALSE,
allowDeleteColumn = FALSE,
allowDeleteRow = TRUE,
rowDrag = FALSE,
columnResize = FALSE,
wordWrap = TRUE)
)
}
# Update display corresponding observed file names
output$tableOutputExtractionDisplayOnly <- renderDataTable(
printVariableNameObservedFiles(globalVariable$outputExtraction))
# Update select date range
updateDateRangeInput(session,
"dateRangeCali",
"2. Select date range",
start = globalVariable$dateRangeCali[1],
end = globalVariable$dateRangeCali[2])
# Update number of parallel runs
updateSliderInput(session,
"ncores",
"3. Select number of parallel runs (cores)",
value = globalVariable$ncores,
min = 1,
max = detectCores())
# Update objective function
updateSelectInput(session,
"objFunction",
label = "1. Select objective function",
choices = c('NSE', 'KGE', 'R2', 'RMSE', 'aBIAS',
'userObjFunction'),
selected = globalVariable$objFunction)
# Update get observed data files
output$printObservedDataFile <<- renderText(globalVariable$observedDataFile)
# remove slider input when parameter selection was updated
for (i in 2:30){
removeUI(selector = paste0("div:has(> #parameter", i, ")"),
multiple = TRUE,
immediate = TRUE,
session)
}
# Min and max value of parameter 1
minVal <- as.numeric(globalVariable$paraSelection$Min[1])
maxVal <- as.numeric(globalVariable$paraSelection$Max[1])
# Update slider input
updateSliderInput(session,
inputId = "parameter1",
label = globalVariable$paraSelection$Parameter[1],
min = minVal,
max = maxVal,
value = minVal,
step = (maxVal - minVal)/50)
# Update number of calibrated parameter
globalVariable$nCaliParam <<- nrow(globalVariable$paraSelection)
# Add slider input for other parameters
if (nrow(globalVariable$paraSelection) > 1){
lapply(1:(nrow(globalVariable$paraSelection)-1), FUN = function(i) {
if (check_null_na_empty(globalVariable$paraSelection$Min[i+1]) &
check_null_na_empty(globalVariable$paraSelection$Max[i+1])){
# Min and max value
minVal <- as.numeric(globalVariable$paraSelection$Min[i+1])
maxVal <- as.numeric(globalVariable$paraSelection$Max[i+1])
insertUI(
selector = "#parameter1",
where = "afterEnd",
ui = sliderInput(
inputId = paste0("parameter", i+1),
label = globalVariable$paraSelection$Parameter[i+1],
min = minVal,
max = maxVal,
value = minVal,
step = (maxVal - minVal)/50
)
)
}
})
}
# Show meesage
showNotification("All project settings were loaded",
type = "message",
duration = 10)
} else {
# Show meesage
showNotification("Error: Input file must be 'RSWATproject.rds'",
type = "error",
duration = 10)
},
blocking_level = "error")
# Update number of plots in Manual calibration
shinyCatch(
updateSelectInput(session,
"showPlotVariables",
label = "",
choices = paste0("variable ", c(1:globalVariable$nOutputVar)),
selected = 1),
blocking_level = "error")
})
#-----------------------------------------------------------------------------
# Tab 1. General Setting
#-----------------------------------------------------------------------------
# ****************************************************************************
# Check SWAT or SWAT+ project
# ****************************************************************************
observe({
req(input$SWATorSWATplus)
# Check SWAT or SWAT+ project
if (input$SWATorSWATplus == "SWAT"){
globalVariable$SWATProject <<- TRUE
globalVariable$SWATPlusProject <<- FALSE
} else {
globalVariable$SWATProject <<- FALSE
globalVariable$SWATPlusProject <<- TRUE
}
# Initially there is no warning message
output$checkTxtInOutFolder <- renderText(" ")
# Check if the TxtInOut matches the SWAT project
if (globalVariable$SWATPlusProject){
if(globalVariable$TxtInOutSWAT){
output$checkTxtInOutFolder <- renderText(
"ERROR: This should be TxtInOut of SWAT+"
)
}
} else {
if(globalVariable$TxtInOutSWATPlus){
output$checkTxtInOutFolder <- renderText(
"ERROR: This should be TxtInOut of SWAT"
)
}
}
# ****************************************************************************
# Select SWAT parameters for calibration and/or sensitivity: Default setting
# ****************************************************************************
if (!globalVariable$loadProject){
# Update template for parameter and output extraction according to the SWAT project
if (globalVariable$SWATProject){
# Example of parameter selection for SWAT project
output$tableParaSelection <-
renderExcel(excelTable(data = dataParaSelectionSWAT,
columns = columnsParaSelectionSWAT,
editable = TRUE,
allowInsertRow = TRUE,
allowInsertColumn = TRUE,
allowDeleteColumn = TRUE,
allowDeleteRow = TRUE,
rowDrag = TRUE,
columnResize = FALSE,
wordWrap = TRUE))
# Example of output extraction for SWAT project
output$tableOutputExtraction <-
renderExcel(excelTable(data = dataOutputExtractionSWAT,
columns = columnsOutputExtractionSWAT,
editable = TRUE,
allowInsertRow = TRUE,
allowInsertColumn = FALSE,
allowDeleteColumn = FALSE,
allowDeleteRow = TRUE,
rowDrag = FALSE,
columnResize = FALSE,
wordWrap = TRUE))
# If this is SWAT+ project
} else {
# Example of parameter selection for SWAT+ project
output$tableParaSelection <-
renderExcel(excelTable(data = dataParaSelectionSWATPlus,
columns = columnsParaSelectionSWATPlus,
editable = TRUE,
allowInsertRow = TRUE,
allowInsertColumn = TRUE,
allowDeleteColumn = TRUE,
allowDeleteRow = TRUE,
rowDrag = TRUE,
columnResize = FALSE,
wordWrap = TRUE))
# Example of output extraction for SWAT+ project
output$tableOutputExtraction <-
renderExcel(excelTable(data = dataOutputExtractionSWATPlus,
columns = columnsOutputExtractionSWATPlus,
editable = TRUE,
allowInsertRow = TRUE,
allowInsertColumn = FALSE,
allowDeleteColumn = FALSE,
allowDeleteRow = TRUE,
rowDrag = FALSE,
columnResize = FALSE,
wordWrap = TRUE))
globalVariable$paraSelection <<- dataParaSelectionSWATPlus
}
}
})
# ****************************************************************************
# Help button select SWAT or SWAT+ project
# ****************************************************************************
observe({
req(input$helpSWATorSWATplus)
showModal(modalDialog(
title = "Help: 1. SWAT or SWAT+ project",
"Please select SWAT or SWAT+ model, the graphical user interface will be
changed after the selection",
easyClose = TRUE
))
})
# ****************************************************************************
# Get working folder
# ****************************************************************************
observe({
req(input$workingFolder)
# Save working directory in the global variable
globalVariable$workingFolder <<- trimws(input$workingFolder)
# Save link to the simulation report log file to the global variable
globalVariable$CurrentSimulationReportFile <<- paste(
globalVariable$workingFolder,
'/Output/CurrentSimulationReport.log',
sep =''
)
# Check if working folder exists
if(!dir.exists(globalVariable$workingFolder)){
# Print out message if working dir does not exist
output$checkWorkingFolder <- renderText("Input folder does not exist")
} else {
# If exists, does not display anything
output$checkWorkingFolder <- renderText(" ")
}
})
# ****************************************************************************
# Help button select working folder
# ****************************************************************************
observe({
req(input$helpworkingFolder)
showModal(modalDialog(
title = "Help: 2. Working folder",
"All files created by R-SWAT will be saved in this folder, for example,
project setting file 'RSWATproject.rds' when you save your project,
this file also can be used to load project settings from previous setup,
simulation outputs, TxtInOut folders for parallel runs, etc...",
easyClose = TRUE
))
})
# ****************************************************************************
# TxtInOut folder: Display HRU info from TxtInOut folder
# ****************************************************************************
observe({
req(input$TxtInOutFolder)
# Check if TxtInOut folder exists
if(!dir.exists(trimws(input$TxtInOutFolder))){
output$checkTxtInOutFolder <- renderText("Input folder does not exist")
} else {
output$checkTxtInOutFolder <- renderText(" ")
}
# Check if .hru files exist in this folder
if (checkDirFileExist(trimws(input$TxtInOutFolder), "", ".cio")){
# Is this TxtInOut of SWAT or SWAT plus
globalVariable$TxtInOutSWAT <<- checkSWATorSWATplus(trimws(input$TxtInOutFolder))$SWAT
globalVariable$TxtInOutSWATPlus <<- checkSWATorSWATplus(trimws(input$TxtInOutFolder))$SWATPlus
# Check if the TxtInOut matches the SWAT project
if (globalVariable$SWATPlusProject){
if(globalVariable$TxtInOutSWAT){
output$checkTxtInOutFolder <- renderText(
"ERROR: This should be TxtInOut of SWAT+"
)
}
} else {
if(globalVariable$TxtInOutSWATPlus){
output$checkTxtInOutFolder <- renderText(
"ERROR: This should be TxtInOut of SWAT"
)
}
}
# Save link to TxtInout Folder to the global variable
globalVariable$TxtInOutFolder <<- trimws(input$TxtInOutFolder)
# If this is a SWAT project
if (globalVariable$SWATProject & globalVariable$TxtInOutSWAT){
# Get HRU information (land use, slope, soil, sub)
globalVariable$HRUinfo <<- getHruInfo(globalVariable$TxtInOutFolder)
# Get unique soil, land use, slope, max number of subbasins
uniqueSoil <- unique(globalVariable$HRUinfo$soil)
uniqueLandUse <- unique(globalVariable$HRUinfo$lu)
uniqueSlope <- unique(globalVariable$HRUinfo$slope)
minMaxSubbasin <- range(globalVariable$HRUinfo$sub)
# Number of soil, land use, slope
nSoil <- length(uniqueSoil)
nLU <- length(uniqueLandUse)
nSlope <- length(uniqueSlope)
nRow <- max(nSoil, nLU, nSlope, 2)
# Display unique land use, soil, slope
displayOutput$uniqueHruProperties <<- data.frame(
minMaxSubbasin = c(minMaxSubbasin,rep(NA, nRow - 2)),
Landuse = c(uniqueLandUse,rep(NA, nRow - nLU)),
soilName = c(uniqueSoil,rep(NA, nRow - nSoil)),
slopeClass = c(uniqueSlope,rep(NA, nRow - nSlope))
)
# If this is a SWAT+ project
} else if (globalVariable$SWATPlusProject & globalVariable$TxtInOutSWATPlus){
displayOutput$uniqueHruProperties <<- NULL
globalVariable$HRUinfo <<- read.table(
file = paste(globalVariable$TxtInOutFolder,
"/hru-data.hru", sep =""),
header = TRUE, skip = 1, sep = ""
)
# Find maximum number of HRU
} else {
displayOutput$uniqueHruProperties <<- NULL
globalVariable$HRUinfo <<- NULL
}
# Display table of HRU information (land use, soil, slope)
output$tableHRUinfo <<- renderDataTable(globalVariable$HRUinfo)
} else {
# If this is not TxtInOut folder, assign global variables to NULL
globalVariable$HRUinfo <<- NULL
globalVariable$TxtInOutFolder <<- NULL
output$tableHRUinfo <<- NULL
displayOutput$uniqueHruProperties <<- NULL
}
})
# ****************************************************************************
# Help button select TxtInOut folder
# ****************************************************************************
observe({
req(input$helpTxtInOutFolder)
showModal(modalDialog(
title = "Help: 3. TxtInOut folder",
"Path to the TxtInOut directory which contains all original SWAT (or SWAT+)
input files. These files will not be changed by R-SWAT",
easyClose = TRUE
))
})
# ****************************************************************************
# Get executable SWAT file
# ****************************************************************************
observe({
req(input$getSWATexe)
# Get full path to SWAT exe file
shinyjs::disable("getSWATexe")
shinyCatch(globalVariable$SWATexeFile <<- file.choose(),
blocking_level = "none")
shinyjs::enable("getSWATexe")
shinyCatch(
if (grepl(".exe", globalVariable$SWATexeFile, fixed = TRUE)){
output$printSWATexe <- renderText(globalVariable$SWATexeFile)
} else {
output$printSWATexe <- renderText("Error: The selected file must have '.exe' extention")
},
blocking_level = "error")
})
# ****************************************************************************
# Help button select executable SWAT
# ****************************************************************************
observe({
req(input$helpgetSWATexe)
showModal(modalDialog(
title = "Help: 4. Select executable SWAT",
"Select the executable SWAT or SWAT+ file, for example, swat_32debug.exe",
easyClose = TRUE
))
})
# ****************************************************************************
# Files with list of all SWAT parameters (get file) + display content of file
# ****************************************************************************
observe({
req(input$getSWATParamFile)
# Get full path to SWAT exe file
shinyjs::disable("getSWATParamFile")
shinyCatch(globalVariable$SWATParamFile <<- file.choose(),
blocking_level = "none")
shinyjs::enable("getSWATParamFile")
shinyCatch(
if (grepl("swatParam.txt", globalVariable$SWATParamFile, fixed = TRUE) |
grepl("cal_parms.cal", globalVariable$SWATParamFile, fixed = TRUE)){
globalVariable$SWATParam <<- loadSwatParam(globalVariable$SWATParamFile)
output$printSWATParamFile <- renderText(globalVariable$SWATParamFile)
output$tableSWATParam <- renderDataTable(globalVariable$SWATParam)
} else {
output$printSWATParamFile <- renderText(
paste("Error: The selected file must be either 'swatParam.txt'",
"or 'cal_parms.cal'")
)
},
blocking_level = "error")
})
# ****************************************************************************
# Help button select file SWAT (or SWAT+) parameter file
# ****************************************************************************
observe({
req(input$helpSWATparamFile)
showModal(modalDialog(
title = "Help: 5. File with list of SWAT or SWAT+ parameters",
renderUI(HTML(readLines(paste(globalVariable$HTMLdir,
"/HTML/helpSWATparamFile.html",
sep = "")))),
easyClose = TRUE
))
})
#-----------------------------------------------------------------------------
# Tab 2. Parameter sampling
#-----------------------------------------------------------------------------
# ****************************************************************************
# Display help for parameter selection
# ****************************************************************************
observe({
# Requirement for activation these command
req(input$helpParameterSelection)
# This first if command prevents the app crashed when no input is given
if (is.data.frame(globalVariable$SWATParam)){
# Check if there is no input SWAT parameter file
if (is.null(globalVariable$SWATParam$parameter)){
output$tableHelpParameterSelection <-
renderDataTable(displayOutput$uniqueHruProperties)
} else {
SWATParamName <- globalVariable$SWATParam$parameter
nSWATParamName <- length(SWATParamName)
if(is.null(displayOutput$uniqueHruProperties)){
output$tableHelpParameterSelection <- NULL
} else {
nRowUniqueHRU <- nrow(displayOutput$uniqueHruProperties)
compareLength <- max(nRowUniqueHRU, nSWATParamName)
if (nRowUniqueHRU < compareLength){
newRow <- data.frame(matrix(rep(NA, (compareLength - nRowUniqueHRU)*4),
ncol = 4))
names(newRow) <- names(displayOutput$uniqueHruProperties)
tempUniqueHruProperties <- rbind(displayOutput$uniqueHruProperties,
newRow)
} else {
SWATParamName <- c(SWATParamName, rep(NA, compareLength - nSWATParamName))
}
tempUniqueHruProperties <- cbind(SWATParamName,tempUniqueHruProperties)
output$tableHelpParameterSelection <- renderDataTable(tempUniqueHruProperties)
}
}
# If this is a SWAT+ project
if (ncol(globalVariable$SWATParam) != 7){
# Get SWAT+ parameter name
temp <- paste(globalVariable$SWATParam[, 1], ".", globalVariable$SWATParam[, 2],
sep = "")
# Display SWAT+ help table
output$tableHelpParameterSelection <-
renderDataTable(data.frame(Parameter = temp))
}
} else {
# Display SWAT+ help table
output$tableHelpParameterSelection <- NULL
}
})
# ****************************************************************************
# Help parameter selection
# ****************************************************************************
observe({
req(input$helpParam)
showModal(modalDialog(
title = "Help: 1. Display help for parameter selection",
"If you don't know the parameter, subbasin, land use, and slope names,
check this box. We will get this information from the TxtInOut folder for you",
easyClose = TRUE
))
})
# ****************************************************************************
# Check input 'Select SWAT parameters for calibration'
# ****************************************************************************
observeEvent(input$checkParameterTableButton, {
shinyCatch(
checkParameterTable <- checkSwatParameterName(globalVariable$paraSelection,
globalVariable$SWATParam,
globalVariable$HRUinfo,
globalVariable$SWATProject),
blocking_level = "error"
)
output$checkParameterTableTxtOuput <- renderText(checkParameterTable$checkMessage)
})
# ****************************************************************************
# Save "SWAT parameters for calibration" to global variable
# ****************************************************************************
observe({
req(input$tableParaSelection)
# Parameter selection
paraSelection <- excel_to_R(input$tableParaSelection)
# Check if no input data
if(is.null(paraSelection)) {
# Check if this is SWAT or SWAT+ project
if(globalVariable$SWATProject){
paraSelection <- dataParaSelectionSWAT
} else {
paraSelection <- dataParaSelectionSWATPlus
}
}
# Save parameter selection to the global variable
globalVariable$paraSelection <<- paraSelection
globalVariable$paraSelection[,1] <<- trimws(paraSelection[,1])
shinyCatch(
if(check_null_na_empty(globalVariable$paraSelection$Min[1]) &
check_null_na_empty(globalVariable$paraSelection$Max[1])){
# Min and max value
minVal <- as.numeric(globalVariable$paraSelection$Min[1])
maxVal <- as.numeric(globalVariable$paraSelection$Max[1])
# Update slider input
updateSliderInput(session,
inputId = "parameter1",
label = globalVariable$paraSelection$Parameter[1],
min = minVal,
max = maxVal,
value = minVal,
step = (maxVal - minVal)/50
)
},
blocking_level = "warning"
)
# remove slider input when parameter selection was updated
shinyCatch(
if(globalVariable$nCaliParam > 1){
for (i in 2:globalVariable$nCaliParam){
removeUI(selector = paste0("div:has(> #parameter", i, ")"),
multiple = TRUE,
immediate = TRUE,
session)
}
},
blocking_level = "warning"
)
# Update number of calibrated parameter
globalVariable$nCaliParam <<- nrow(globalVariable$paraSelection)
# Add slider input for other parameters
shinyCatch(
if (nrow(globalVariable$paraSelection) > 1){
lapply(1:(nrow(globalVariable$paraSelection)-1), FUN = function(i) {
if (check_null_na_empty(globalVariable$paraSelection$Min[i+1]) &
check_null_na_empty(globalVariable$paraSelection$Max[i+1])){
# Min and max value
minVal <- as.numeric(globalVariable$paraSelection$Min[i+1])
maxVal <- as.numeric(globalVariable$paraSelection$Max[i+1])
# Update slider input
insertUI(
selector = "#parameter1",
where = "afterEnd",
ui = sliderInput(
inputId = paste0("parameter", i+1),
label = globalVariable$paraSelection$Parameter[i+1],
min = minVal,
max = maxVal,
value = minVal,
step = (maxVal - minVal)/50
)
)
}
})
},
blocking_level = "error"
)
})
# ****************************************************************************
# Help button parameter change selection
# ****************************************************************************
observe({
req(input$helpParamSelection)
showModal(modalDialog(
title = "Help: Parameter Selection",
renderUI(HTML(readLines(paste(globalVariable$HTMLdir,
"/HTML/helpParamSelection.html",
sep = "")))),
easyClose = TRUE
))
})
# ****************************************************************************
# Parameter sampling: Default setting
# ****************************************************************************
output$tableParaSampling <- renderExcel(excelTable(data = dataParaSampling,
columns = ColumnsParaSampling,
editable = TRUE,
allowInsertRow = FALSE,
allowInsertColumn = FALSE,
allowDeleteColumn = FALSE,
allowDeleteRow = FALSE,
rowDrag = FALSE,
columnResize = FALSE,
wordWrap = TRUE))
# ****************************************************************************
# Parameter sampling: Get user input for parameter sampling
# ****************************************************************************
observe({
req(input$samplingApproach)
# Save sampling approach to the global variable
globalVariable$samplingApproach <<- input$samplingApproach
# SUFI2 approach
if (input$samplingApproach == 'Sensi_Cali_(uniform_Latin_Hypercube_Sampling)'){
updateTextAreaInput(session, "inputInfo",
paste("3. Additional infomation about the selected",
"sensitivity/calibration approach"),
"100")
outputText <- paste("Please input the number of iterations, e.g., 100")
# From optimization package
} else if (input$samplingApproach == 'Cali_(from_optimization_package)'){
updateTextAreaInput(session, "inputInfo",
paste("3. Additional infomation about the selected",
"sensitivity/calibration approach"),
paste("optim_sa(fun = SWAT, start = c(runif(nParam,",
"min = minCol, max = maxCol)), lower = minCol,",
"upper = maxCol, trace = TRUE, control = list(t0 = 10,",
"nlimit = 5,t_min = 0.1, dyn_rf = FALSE,rf = 1,r = 0.7)))"))
outputText <- helpTextCali
# From hydroPSO package
} else if (input$samplingApproach == 'Cali_(from_hydroPSO_package)'){
updateTextAreaInput(session, "inputInfo",
paste("3. Additional infomation about the selected",
"sensitivity/calibration approach"),
paste("hydroPSO(fn = SWAT, lower=minCol, upper=maxCol,",
"control=list(maxit=1))"))
outputText <- helpTextCali