-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.R
1608 lines (1427 loc) · 74.9 KB
/
app.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
#Required R packages for application to run
library(deSolve)
library(ggplot2)
library(reshape2)
library(scales)
library(shiny)
library(shinyBS)
library(shinythemes)
#SERVER FUNCTION SECTION BEGINS HERE########################################################################################
############################################################################################################################
############################################################################################################################
############################################################################################################################
#SERVER FUNCTION GENERAL SECTION############################################################################################
############################################################################################################################
#Set parameter names for inputed conditions to pass to simulation function
sim_Names <- c("TOTCl_mgL", "TOTCl_gas_lbs", "TOTCl_liquid_lbs", "TOTCl_liquid_percent",
"TOTNH_mgL", "TOTNH_gas_lbs", "TOTNH_liquid_lbs", "TOTNH_liquid_percent", "ratio", "Q",
"Mono_mgL", "Di_mgL", "FreeNH_mgL",
"Mono_mgL_boost", "Di_mgL_boost", "TOTNH_mgL_boost", "TOTCl_mgL_boost",
"pH", "Alk", "T_C", "TOC", "fast", "slow", "time_input_m",
"time_input_h", "time_input_d", "Method", "ChlorineAdd", "AmmoniaAdd", "time_scale")
#Define colorblind friendly palette
cb_palette <- c("#000000", "#CC79A7", "#E69F00", "#56B4E9", "#009E73",
"#0072B2", "#D55E00", "#999999")
#Define basic theme used for all plots
mytheme <- theme(
panel.background = element_rect(fill = "white", colour = NA),
panel.grid.major = element_line(colour = "grey70", size = 0.2),
panel.grid.minor = element_line(colour = "grey85", size = 0.5),
legend.background = element_blank(),
legend.key = element_blank(),
legend.title = element_blank(),
legend.text = element_text(face = "bold", size = rel(1.25)),
legend.position = "top",
legend.direction = "horizontal",
strip.background = element_blank(),
strip.text = element_text(face = "bold", size = rel (1.5)),
axis.ticks = element_line(colour = "black", size = 1),
axis.line = element_line(colour = "black", size = 1, lineend = "square"),
axis.text.x = element_text(colour = "black", size = 12),
axis.text.y = element_text(colour = "black", size = 12),
axis.title.x = element_text(size = 14),
axis.title.y = element_text(size = 14))
#Define function that copies initial conditions from one simulation to another
update_IC <- function(session, from, to, input) {
#Update initial conditions for slider inputs
updateSliderInput(session, paste0(to, "_", "TOTCl_mgL"), value = input[[paste0(from, "_", "TOTCl_mgL")]])
updateSliderInput(session, paste0(to, "_", "TOTNH_mgL"), value = input[[paste0(from, "_", "TOTNH_mgL")]])
updateSliderInput(session, paste0(to, "_", "TOTCl_liquid_percent"), value = input[[paste0(from, "_", "TOTCl_liquid_percent")]])
updateSliderInput(session, paste0(to, "_", "TOTNH_liquid_percent"), value = input[[paste0(from, "_", "TOTNH_liquid_percent")]])
updateSliderInput(session, paste0(to, "_", "ratio"), value = input[[paste0(from, "_", "ratio")]])
updateSliderInput(session, paste0(to, "_", "Mono_mgL"), value = input[[paste0(from, "_", "Mono_mgL")]])
updateSliderInput(session, paste0(to, "_", "Di_mgL"), value = input[[paste0(from, "_", "Di_mgL")]])
updateSliderInput(session, paste0(to, "_", "FreeNH_mgL"), value = input[[paste0(from, "_", "FreeNH_mgL")]])
updateSliderInput(session, paste0(to, "_", "Mono_mgL_boost"), value = input[[paste0(from, "_", "Mono_mgL_boost")]])
updateSliderInput(session, paste0(to, "_", "Di_mgL_boost"), value = input[[paste0(from, "_", "Di_mgL_boost")]])
updateSliderInput(session, paste0(to, "_", "TOTNH_mgL_boost"), value = input[[paste0(from, "_", "TOTNH_mgL_boost")]])
updateSliderInput(session, paste0(to, "_", "TOTCl_mgL_boost"), value = input[[paste0(from, "_", "TOTCl_mgL_boost")]])
updateSliderInput(session, paste0(to, "_", "pH"), value = input[[paste0(from, "_", "pH")]])
updateSliderInput(session, paste0(to, "_", "Alk"), value = input[[paste0(from, "_", "Alk")]])
updateSliderInput(session, paste0(to, "_", "T_C"), value = input[[paste0(from, "_", "T_C")]])
updateSliderInput(session, paste0(to, "_", "TOC"), value = input[[paste0(from, "_", "TOC")]])
updateSliderInput(session, paste0(to, "_", "fast"), value = input[[paste0(from, "_", "fast")]])
updateSliderInput(session, paste0(to, "_", "slow"), value = input[[paste0(from, "_", "slow")]])
updateSliderInput(session, paste0(to, "_", "time_input_m"), value = input[[paste0(from, "_", "time_input_m")]])
updateSliderInput(session, paste0(to, "_", "time_input_h"), value = input[[paste0(from, "_", "time_input_h")]])
updateSliderInput(session, paste0(to, "_", "time_input_d"), value = input[[paste0(from, "_", "time_input_d")]])
#Update initial conditions for numeric inputs
updateNumericInput(session, paste0(to, "_", "TOTCl_gas_lbs"), value = input[[paste0(from, "_", "TOTCl_gas_lbs")]])
updateNumericInput(session, paste0(to, "_", "TOTNH_gas_lbs"), value = input[[paste0(from, "_", "TOTNH_gas_lbs")]])
updateNumericInput(session, paste0(to, "_", "TOTCl_liquid_lbs"), value = input[[paste0(from, "_", "TOTCl_liquid_lbs")]])
updateNumericInput(session, paste0(to, "_", "TOTNH_liquid_lbs"), value = input[[paste0(from, "_", "TOTNH_liquid_lbs")]])
updateNumericInput(session, paste0(to, "_", "Q"), value = input[[paste0(from, "_", "Q")]])
#Update initial conditions for select inputs
updateSelectInput(session, paste0(to, "_", "Method"), selected = input[[paste0(from, "_", "Method")]])
updateSelectInput(session, paste0(to, "_", "ChlorineAdd"), selected = input[[paste0(from, "_", "ChlorineAdd")]])
updateSelectInput(session, paste0(to, "_", "AmmoniaAdd"), selected = input[[paste0(from, "_", "AmmoniaAdd")]])
updateSelectInput(session, paste0(to, "_", "time_scale"), selected = input[[paste0(from, "_", "time_scale")]])
}
#Define function to extract initial conditions for reporting back out as a summary table
initial_conditions <- function(TOTCl_mgL, TOTCl_gas_lbs, TOTCl_liquid_lbs, TOTCl_liquid_percent,
TOTNH_mgL, TOTNH_gas_lbs, TOTNH_liquid_lbs, TOTNH_liquid_percent, ratio, Q,
Mono_mgL, Di_mgL, FreeNH_mgL,
Mono_mgL_boost, Di_mgL_boost, TOTNH_mgL_boost, TOTCl_mgL_boost,
pH, Alk, T_C, TOC, fast, slow, time_input_m,
time_input_h, time_input_d, Method, ChlorineAdd, AmmoniaAdd, time_scale) {
#Get initial conditions based on various possible input scenarios
#Simultaneous addition
if (Method == "simadd") {
Mono_ic <- 0.00
Di_ic <- 0.00
if (ChlorineAdd == "conc") {
TOTCl_ic <- TOTCl_mgL
}
if (ChlorineAdd == "gas") {
TOTCl_ic <- TOTCl_gas_lbs/Q/8.34
}
if (ChlorineAdd == "liquid") {
TOTCl_ic <- TOTCl_liquid_lbs * (TOTCl_liquid_percent/100)/Q/8.34
}
if (AmmoniaAdd == "conc") {
TOTNH_ic <- TOTNH_mgL
}
if (AmmoniaAdd == "ratio") {
TOTNH_ic <- TOTCl_ic/ratio
}
if (AmmoniaAdd == "gas") {
TOTNH_ic <- TOTNH_gas_lbs/Q/8.34 * 14/17
}
if (AmmoniaAdd == "liquid") {
TOTNH_ic <- TOTNH_liquid_lbs * (TOTNH_liquid_percent/100)/Q/8.34 * 14/17
}
}
#Preformed chloramines
if (Method == "preform") {
TOTCl_ic <- 0.00
TOTNH_ic <- FreeNH_mgL
Mono_ic <- Mono_mgL
Di_ic <- Di_mgL
}
#Booster chlorination
if (Method == "boost") {
TOTCl_ic <- TOTCl_mgL_boost
TOTNH_ic <- TOTNH_mgL_boost
Mono_ic <- Mono_mgL_boost
Di_ic <- Di_mgL_boost
}
#Initial chlorine to nitrogen ratio calculations common to all scenarios
ratio_ic_N <- (TOTCl_ic + Mono_ic + Di_ic)/(TOTNH_ic + Mono_ic*14/71 + Di_ic*14/(71*2))
ratio_ic_NH <- round(ratio_ic_N*14/17, digits = 2)
ratio_ic_N <- round(ratio_ic_N, digits = 2)
#Round concentration values
TOTCl_ic <- round(TOTCl_ic, digits = 2)
TOTNH_ic <- round(TOTNH_ic, digits = 2)
Mono_ic <- round(Mono_ic, digits = 2)
Di_ic <- round(Di_ic, digits = 2)
#Combine intial condition names and values in a table
Value <- c(TOTCl_ic, TOTNH_ic, Mono_ic, Di_ic, ratio_ic_N, ratio_ic_NH, pH, Alk, T_C, TOC, fast, slow)
Parameter <- c("Free Chlorine (mg Cl2/L) =",
"Free Ammonia (mg N/L) =",
"Monochloramine (mg Cl2/L) =",
"Dichloramine (mg Cl2/L) =",
"Chlorine:Nitrogen Ratio (X:1) =",
"Chlorine:Ammonia Ratio (X:1) =",
"pH =",
"Total Alkalinity (mg CaCO3/L) =",
"Temperature (Celsius) =",
"Total Organic Carbon (mg C/L) =",
"TOC Fast Site Fraction =",
"TOC Slow Site Fraction =")
ic <- cbind(Parameter, Value)
}
#Define function to simulate chloramine formation and decay
simulate_chloramine <- function(TOTCl_mgL, TOTCl_gas_lbs, TOTCl_liquid_lbs, TOTCl_liquid_percent,
TOTNH_mgL, TOTNH_gas_lbs, TOTNH_liquid_lbs, TOTNH_liquid_percent, ratio, Q,
Mono_mgL, Di_mgL, FreeNH_mgL,
Mono_mgL_boost, Di_mgL_boost, TOTNH_mgL_boost, TOTCl_mgL_boost,
pH, Alk, T_C, TOC, fast, slow, time_input_m,
time_input_h, time_input_d, Method, ChlorineAdd, AmmoniaAdd, time_scale) {
#Set initial concentrations based on various possible input scenarios
#Simultaneous addition
if (Method == "simadd") {
Mono_ini <- 0
Di_ini <- 0
if (ChlorineAdd == "conc") {
TOTCl_ini <- TOTCl_mgL/71000
}
if (ChlorineAdd == "gas") {
TOTCl_ini <- TOTCl_gas_lbs/Q/8.34/71000
}
if (ChlorineAdd == "liquid") {
TOTCl_ini <- TOTCl_liquid_lbs * (TOTCl_liquid_percent/100)/Q/8.34/71000
}
if (AmmoniaAdd == "conc") {
TOTNH_ini <- TOTNH_mgL/14000
}
if (AmmoniaAdd == "ratio") {
TOTNH_ini <- TOTCl_ini/(ratio*14/71)
}
if (AmmoniaAdd == "gas") {
TOTNH_ini <- TOTNH_gas_lbs/Q/8.34/17000
}
if (AmmoniaAdd == "liquid") {
TOTNH_ini <- TOTNH_liquid_lbs * (TOTNH_liquid_percent/100)/Q/8.34/17000
}
}
#Preformed chloramines
if (Method == "preform") {
TOTCl_ini <- 0
TOTNH_ini <- FreeNH_mgL/14000
Mono_ini <- Mono_mgL/71000
Di_ini <- Di_mgL/71000/2
}
#Booster chlorination
if (Method == "boost") {
TOTCl_ini <- TOTCl_mgL_boost/71000
TOTNH_ini <- TOTNH_mgL_boost/14000
Mono_ini <- Mono_mgL_boost/71000
Di_ini <- Di_mgL_boost/71000/2
}
#Convert temperature from Celsius to Kelvin
T_K <- T_C + 273.15
#Convert TOC into fast and slow fractions (moles C/L)
DOC1_ini <- TOC*fast/12000
DOC2_ini <- TOC*slow/12000
#Convert time into seconds and set time steps (creates more data points at short times)
#Minutes to seconds conversion
if (time_scale == "minutes") {
time_sim_s <- time_input_m * 60
time <- seq(from = 0, to = time_sim_s, by = 1)
}
#Hours to seconds conversion
if (time_scale == "hours") {
time_sim_s <- time_input_h * 60 * 60
time_fast <- seq(from = 0, to = 1799, by = 1)
time_mid <- seq(from = 1800, to = time_sim_s, by = 30)
time <- c(time_fast, time_mid, time_sim_s)
}
#Days to seconds conversion
if (time_scale == "days") {
time_sim_s <- time_input_d * 60 * 60 * 24
time_fast <- seq(from = 0, to = 1799, by = 1)
time_mid <- seq(from = 1800, to = 86370, by = 30)
time_slow <- seq(from = 86400, to = time_sim_s, by = 3600)
time <- c(time_fast, time_mid, time_slow, time_sim_s)
}
#Calculate equilibrium constants for chloramine system adjusted for temperature
KHOCl <- 10^(-(1.18e-4 * T_K^2 - 7.86e-2 * T_K + 20.5)) #10^-7.6
KNH4 <- 10^(-(1.03e-4 * T_K^2 - 9.21e-2 * T_K + 27.6)) #10^-9.25
KH2CO3 <- 10^(-(1.48e-4 * T_K^2 - 9.39e-2 * T_K + 21.2)) #10^-6.35
KHCO3 <- 10^(-(1.19e-4 * T_K^2 - 7.99e-2 * T_K + 23.6)) #10^-10.33
KW <- 10^(-(1.5e-4 * T_K^2 - 1.23e-1 * T_K + 37.3)) #10^-14
#Calculate water species concentrations (moles/L)
H <- 10^-pH
OH <- KW/H
#Calculate alpha values
#Free chlorine system
alpha0TOTCl <- 1/(1 + KHOCl/H)
alpha1TOTCl <- 1/(1 + H/KHOCl)
#Free ammonia system
alpha0TOTNH <- 1/(1 + KNH4/H)
alpha1TOTNH <- 1/(1 + H/KNH4)
#Carbonate system
alpha0TOTCO <- 1/(1 + KH2CO3/H + KH2CO3*KHCO3/H^2)
alpha1TOTCO <- 1/(1 + H/KH2CO3 + KHCO3/H)
alpha2TOTCO <- 1/(1 + H/KHCO3 + H^2/(KH2CO3*KHCO3))
#Calculate total carbonate concentration (moles/L) based on user-entered pH and alkalinity
TOTCO <- (Alk/50000 + H - OH)/(alpha1TOTCO + 2 * alpha2TOTCO)
#Calculate carbonate species concentrations (moles/L)
H2CO3 <- alpha0TOTCO*TOTCO
HCO3 <- alpha1TOTCO*TOTCO
CO3 <- alpha2TOTCO*TOTCO
#Calculated rate constants (moles/L and seconds) adjusted for temperature
k1 <- 6.6e8 * exp(-1510/T_K) #4.2e6
k2 <- 1.38e8 * exp(-8800/T_K) #2.1e-5
k3 <- 3.0e5 * exp(-2010/T_K) #2.8e2
k4 <- 6.5e-7
k5H <- 1.05e7 * exp(-2169/T_K) #6.9e3
k5HCO3 <- 4.2e31 * exp(-22144/T_K) #2.2e-1
k5H2CO3 <- 8.19e6 * exp(-4026/T_K) #1.1e1
k5 <- k5H*H + k5HCO3*HCO3 + k5H2CO3*H2CO3
k6 <- 6.0e4
k7 <- 1.1e2
k8 <- 2.8e4
k9 <- 8.3e3
k10 <- 1.5e-2
k11p <- 3.28e9*OH + 6.0e6*CO3
k11OCl <- 9e4
k12 <- 5.56e10
k13 <- 1.39e9
k14 <- 2.31e2
kDOC1 <- 5.4
kDOC2 <- 180
#Define function for chloramine system equations
chloramine <- function(t, y, parms) {
with(as.list(y), {
dTOTNH <- (-k1*alpha0TOTCl*TOTCl*alpha1TOTNH*TOTNH + k2*NH2Cl + k5*NH2Cl^2 - k6*NHCl2*alpha1TOTNH*TOTNH*H + kDOC1*NH2Cl*DOC1)
dTOTCl <- (-k1*alpha0TOTCl*TOTCl*alpha1TOTNH*TOTNH + k2*NH2Cl - k3*alpha0TOTCl*TOTCl*NH2Cl + k4*NHCl2 + k8*I*NHCl2 -
(k11p + k11OCl*alpha1TOTCl*TOTCl)*alpha0TOTCl*TOTCl*NHCl2 + 2*k12*NHCl2*NCl3*OH + k13*NH2Cl*NCl3*OH -
2*k14*NHCl2*alpha1TOTCl*TOTCl - kDOC2*alpha0TOTCl*TOTCl*DOC2)
dNH2Cl <- (k1*alpha0TOTCl*TOTCl*alpha1TOTNH*TOTNH - k2*NH2Cl - k3*alpha0TOTCl*TOTCl*NH2Cl + k4*NHCl2 - 2*k5*NH2Cl^2 +
2*k6*NHCl2*alpha1TOTNH*TOTNH*H - k9*I*NH2Cl - k10*NH2Cl*NHCl2 - k13*NH2Cl*NCl3*OH - kDOC1*NH2Cl*DOC1)
dNHCl2 <- (k3*alpha0TOTCl*TOTCl*NH2Cl - k4*NHCl2 + k5*NH2Cl^2 - k6*NHCl2*alpha1TOTNH*TOTNH*H - k7*NHCl2*OH - k8*I*NHCl2 -
k10*NH2Cl*NHCl2 - (k11p + k11OCl*alpha1TOTCl*TOTCl)*alpha0TOTCl*TOTCl*NHCl2 - k12*NHCl2*NCl3*OH -
k14*NHCl2*alpha1TOTCl*TOTCl)
dNCl3 <- ((k11p + k11OCl*alpha1TOTCl*TOTCl)*alpha0TOTCl*TOTCl*NHCl2 - k12*NHCl2*NCl3*OH - k13*NH2Cl*NCl3*OH)
dI <- (k7*NHCl2*OH - k8*I*NHCl2 - k9*I*NH2Cl)
dDOC1 <- (-kDOC1*NH2Cl*DOC1)
dDOC2 <- (-kDOC2*alpha0TOTCl*TOTCl*DOC2)
list(c(dTOTNH, dTOTCl, dNH2Cl, dNHCl2, dNCl3, dI, dDOC1, dDOC2))
})
}
#Set initial condition concentrations for simulation
yini <- c(TOTNH = TOTNH_ini, TOTCl = TOTCl_ini, NH2Cl = Mono_ini, NHCl2 = Di_ini, NCl3 = 0,
I = 0, DOC1 = DOC1_ini, DOC2 = DOC2_ini)
#Solve chloramine ODE system
sim <- ode(func = chloramine, parms = NULL, y = yini, times = time, atol = 1e-12, rtol = 1e-12)
#Extract concentrations (moles/L) and convert to typical units (e.g., mg Cl2/L or mg N/L)
sim_data <- as.data.frame(sim)
sim_data$Total_Chlorine <- (sim_data$NH2Cl + sim_data$NHCl2*2 + sim_data$NCl3*3 + sim_data$TOTCl)*71000
sim_data$Monochloramine <- sim_data$NH2Cl*71000
sim_data$Dichloramine <- sim_data$NHCl2*71000*2
sim_data$Trichloramine <- sim_data$NCl3*71000*3
sim_data$Free_Chlorine <- sim_data$TOTCl*71000
sim_data$Free_Ammonia <- sim_data$TOTNH*14000
sim_data$Total_Ammonia_N <- (sim_data$TOTNH + sim_data$NH2Cl + sim_data$NHCl2 + sim_data$NCl3)*14000
sim_data$Total_Ammonia_NH3 <- (sim_data$TOTNH + sim_data$NH2Cl + sim_data$NHCl2 + sim_data$NCl3)*17000
sim_data$Cl2N <- sim_data$Total_Chlorine/sim_data$Total_Ammonia_N
sim_data$Cl2NH3 <- sim_data$Total_Chlorine/sim_data$Total_Ammonia_NH3
sim <- melt(sim_data, id.vars="time", variable.name="chemical", value.name="concentration")
}
#Define function to plot simulation results in various formats based on user selected tab
plot_sim <- function(sim, chem, type, time_scale) {
#Extract concentrations to plot based on user selection
sim_simple <- sim[sim$chemical %in% c("Total_Chlorine", "Monochloramine", "Dichloramine",
"Trichloramine", "Free_Chlorine", "Free_Ammonia"),]
sim_simple$chemical <- factor(sim_simple$chemical)
levels(sim_simple$chemical) <- c("Total Chlorine", "Monochloramine", "Dichloramine",
"Trichloramine", "Free Chlorine", "Free Ammonia")
#Setup time units for plots based on user selection
#Minutes for time scale
if (time_scale == "minutes") {
sim_simple$time <- sim_simple$time/60
sim$time <- sim$time/60
timelabel <- "Time(minutes)"
}
#Hours for time scale
if (time_scale == "hours") {
sim_simple$time <- sim_simple$time/60/60
sim$time <- sim$time/60/60
timelabel <- "Time(hours)"
}
#Days for time scale
if (time_scale == "days") {
sim_simple$time <- sim_simple$time/60/60/24
sim$time <- sim$time/60/60/24
timelabel <- "Time(days)"
}
#Select plot type based on user selected tab
#Define and select plot of individual chemical concentrations versus time
if (type == "ind") {
plot <- ggplot(subset(sim_simple, chemical %in% chem), aes(x=time, y=concentration, colour=chemical)) +
geom_line(size = 1) +
xlab(timelabel) +
aes(ymin=0) +
ylab(expression(Chlorine~(mg~Cl[2]~L^-1)~and~Free~Ammonia~(mg~N~L^-1)~Concentrations)) +
facet_wrap(~ chemical, ncol = 1, scales = "free_y") +
annotate("segment", x = -Inf, xend = Inf, y = -Inf, yend = -Inf, size = 1) +
scale_colour_manual(guide = FALSE, values = cb_palette) +
mytheme
}
#Define and select chemical concentration composite plot versus time
if (type == "comp") {
plot <- ggplot(subset(sim_simple, chemical %in% chem), aes(x=time, y=concentration, colour=chemical)) +
geom_line(size = 1) +
xlab(timelabel) +
aes(ymin=0) +
ylab(expression(Chlorine~(mg~Cl[2]~L^-1)~and~Free~Ammonia~(mg~N~L^-1)~Concentrations)) +
guides(colour = guide_legend(ncol = 2)) +
scale_colour_manual (values = cb_palette) +
mytheme
}
#Define and select chlorine to nitrogen mass ratio plot versus time
if (type == "Cl2N") {
plot <- ggplot(subset(sim, chemical %in% c("Cl2N", "Cl2NH3")), aes(x=time, y=concentration, colour=chemical)) +
geom_line(size = 1) +
xlab(timelabel) +
aes(ymin=0) +
ylab(expression(Chlorine~to~Nitrogen~(Cl[2]:N)~or~Chlorine~to~Ammonia~(Cl[2]:NH[3])~Mass~Ratio)) +
scale_colour_manual(labels = c("Chlorine:Nitrogen", "Chlorine:Ammonia"), values = cb_palette) +
guides(colour = guide_legend(nrow = 2)) +
mytheme
}
return(plot)
}
#Define function to allow user to download simulation data
export_data <- function(sim) {
#Extract concentrations to export in typical units and create data frame
Time_minutes <- sim[sim$chemical == "Total_Chlorine", "time"]/60
Time_hours <- sim[sim$chemical == "Total_Chlorine", "time"]/60/60
Time_days <- sim[sim$chemical == "Total_Chlorine", "time"]/60/60/24
Total_Chlorine_mg_Cl2_L <- sim[sim$chemical == "Total_Chlorine", "concentration"]
Monochloramine_mg_Cl2_L <- sim[sim$chemical == "Monochloramine", "concentration"]
Dichloramine_mg_Cl2_L <- sim[sim$chemical == "Dichloramine", "concentration"]
Trichloramine_mg_Cl2_L <- sim[sim$chemical == "Trichloramine", "concentration"]
Free_Chlorine_mg_Cl2_L <- sim[sim$chemical == "Free_Chlorine", "concentration"]
Free_Ammonia_mg_N_L <- sim[sim$chemical == "Free_Ammonia", "concentration"]
data <- data.frame(Time_minutes,
Time_hours,
Time_days,
Total_Chlorine_mg_Cl2_L,
Monochloramine_mg_Cl2_L,
Dichloramine_mg_Cl2_L,
Trichloramine_mg_Cl2_L,
Free_Chlorine_mg_Cl2_L,
Free_Ammonia_mg_N_L)
}
#SERVER FUNCTION DEFINITION SECTION#########################################################################################
############################################################################################################################
#Define server logic required to run simulations and produce output
server <- function(input, output, session) {
# Set option for sticky sessions
options("Set-Cookie" = paste0("JSESSIONID=", session$token))
#Copy Simulation A's inputs to Simulation B's inputs
observe({
#Take a dependency on input$AtoBIC
if(input$A_to_B_IC == 0) return(NULL)
isolate(update_IC(session, "A", "B", input))
})
#Copy Simulation B's inputs to Simulation A's inputs
observe({
#Take a dependency on input$BtoAIC
if(input$B_to_A_IC == 0) return(NULL)
isolate(update_IC(session, "B", "A", input))
})
#Define function to get inputted initial conditions and states based on prefix provided
sim_Params <- function(prefix) {
params <- lapply(sim_Names, function(p) {
input[[paste0(prefix, "_", p)]]
})
}
#Run chloramine system simulation based on provided initial conditions
simA <- reactive({
#Take a dependency on input$simupdate
if(input$simupdateA == 0) return(NULL)
#Isolate simulation run only on input$simupdate button selection
isolate(do.call(simulate_chloramine, sim_Params("A")))
})
simB <- reactive({
#Take a dependency on input$simupdate
if(input$simupdateB == 0) return(NULL)
#Isolate simulation run only on input$simupdate button selection
isolate(do.call(simulate_chloramine, sim_Params("B")))
})
#Get initial conditions summary table
output$A_ic <- DT::renderDT({
#Take a dependency on input$simupdate
if(input$simupdateA == 0) return(NULL)
#Isolate simulation run only on input$simupdate button selection
isolate(DT::datatable(
do.call(initial_conditions, sim_Params("A")),
options = list(
dom = "t",
pageLength = 15,
columnDefs = list(
list(width = "90%", targets = 0),
list(width = "10%", targets = 1),
list(className = "alignRight", targets = c(0,1)),
list(orderable = FALSE, targets = c(0,1)),
list(searchable = FALSE, targets = c(0,1))
)
)
))
},
server = FALSE)
output$B_ic <- DT::renderDT({
#Take a dependency on input$simupdate
if(input$simupdateB == 0) return(NULL)
#Isolate simulation run only on input$simupdate button selection
isolate(DT::datatable(
do.call(initial_conditions, sim_Params("B")),
options = list(
dom = "t",
pageLength = 15,
columnDefs = list(
list(width = "90%", targets = 0),
list(width = "10%", targets = 1),
list(className = "alignRight", targets = c(0,1)),
list(orderable = FALSE, targets = c(0,1)),
list(searchable = FALSE, targets = c(0,1))
)
)
))
},
server = FALSE)
#Produce desired reactive plots
output$A_ind <- renderPlot({
#Take a dependency on input$plotupdate and input$simupdate
if(input$simupdateA == 0) return(NULL)
input$plotupdateA
#Isolate plot to update only on input$plotupdate and input$simupdate selection
isolate(plot_sim(simA(), input$A_chemicals, "ind", input$A_time_scale))
})
output$A_comp <- renderPlot({
#Take a dependency on input$plotupdate and input$simupdate
if(input$simupdateA == 0) return(NULL)
input$plotupdateA
#Isolate plot to update only on input$plotupdate and input$simupdate selection
isolate(plot_sim(simA(), input$A_chemicals, "comp", input$A_time_scale))
})
output$A_Cl2N <- renderPlot({
#Take a dependency on input$plotupdate and input$simupdate
if(input$simupdateA == 0) return(NULL)
input$plotupdateA
#Isolate plot to update only on input$plotupdate and input$simupdate selection
isolate(plot_sim(simA(), input$A_chemicals, "Cl2N", input$A_time_scale))
})
output$B_ind <- renderPlot({
#Take a dependency on input$plotupdate and input$simupdate
if(input$simupdateB == 0) return(NULL)
input$plotupdateB
#Isolate plot to update only on input$plotupdate and input$simupdate selection
isolate(plot_sim(simB(), input$B_chemicals, "ind", input$B_time_scale))
})
output$B_comp <- renderPlot({
#Take a dependency on input$plotupdate and input$simupdate
if(input$simupdateB == 0) return(NULL)
input$plotupdateB
#Isolate plot to update only on input$plotupdate and input$simupdate selection
isolate(plot_sim(simB(), input$B_chemicals, "comp", input$B_time_scale))
})
output$B_Cl2N <- renderPlot({
#Take a dependency on input$plotupdate and input$simupdate
if(input$simupdateB == 0) return(NULL)
input$plotupdateB
#Isolate plot to update only on input$plotupdate and input$simupdate selection
isolate(plot_sim(simB(), input$B_chemicals, "Cl2N", input$B_time_scale))
})
#Expression that gets data to be downloaded at user's request
output$A_downloadData <- downloadHandler(
filename = function() {
paste('A', '_', substr(as.character(Sys.time()),1,10),
'_', substr(as.character(Sys.time()),12,16), '.csv', sep='')
},
content = function(file) {write.csv(export_data(simA()), file, row.names=TRUE)
}
)
output$B_downloadData <- downloadHandler(
filename = function() {
paste('B', '_', substr(as.character(Sys.time()),1,10),
'_', substr(as.character(Sys.time()),12,16), '.csv', sep='')
},
content = function(file) {
write.csv(export_data(simB()), file, row.names=TRUE)
}
)
#Detects when tabs have been pressed
output$activeATab <- reactive({
return(input$Atabs)
})
output$activeBTab <- reactive({
return(input$Btabs)
})
outputOptions(output, 'activeATab', suspendWhenHidden=FALSE)
outputOptions(output, 'activeBTab', suspendWhenHidden=FALSE)
}
#UI OBJECT SECTION BEGINS HERE##############################################################################################
############################################################################################################################
############################################################################################################################
############################################################################################################################
#UI OBJECT GENERAL SECTION##################################################################################################
############################################################################################################################
#Define function to take inputs for initial conditions for simulations
render_data_inputs <- function(prefix, prefix2) {
wellPanel(
#Section title
h4(paste0("Simulation ", prefix, " Inputs")),
#Call to display initial simulation notification
conditionalPanel(condition = paste0("input.simupdate", prefix, "== 0"),
tags$div("Note: An initial simulation has not been run; therefore, no plots have been generated", id = "initialsim")
),
br(),
h4("Initial Conditions"),
fluidRow(
column(6,
#Create input and tooltip for method of chemical addition
selectInput(paste0(prefix, "_", "Method"),
label = h4("Chemical Addition Scenarios"),
choices = c("Simultaneous Addition" = "simadd",
"Preformed Chloramines" = "preform",
"Booster Chlorination" = "boost"),
selected = "simadd",
selectize = TRUE),
bsTooltip(id = paste0(prefix, "_", "Method"),
paste0("Select whether to simulate (1) Simultaneous Addition: free chlorine and free ammonia are present ",
"simultaneously from either free chlorine addition to a water containing free ammonia or free ammonia ",
"addition to a water containing free chlorine and you wish to simulate chloramine formation and subsequent decay ",
"(e.g., drinking water treatment plant chloramine formation); ",
"(2) Preformed Chloramines: known concentrations of chloramines and free ammonia already exist and you wish ",
"to simulate chloramine decay (e.g., drinking water distribution system samples)",
"; or (3) Booster Chlorination: known concentrations of chloramines and free ammonia already exist and you wish ",
"to simulate adding free chlorine to recombine the free ammonia into chloramines and the subsequent decay ",
"(e.g., distribution system free chlorine addition)"
),
"right",
options = list(container = "body")),
#Only show panel if simultaneous addition is selected
conditionalPanel(
condition = paste0("input.", prefix, "_", "Method == 'simadd'"),
#Create input and tooltip for free chlorine addition method
selectInput(paste0(prefix, "_", "ChlorineAdd"),
label = h5("Free Chlorine Addition Method"),
choices = c("Known Concentration" = "conc",
"Gas Feed" = "gas",
"Liquid Feed" = "liquid"),
selected = "conc",
selectize = TRUE),
bsTooltip(id = paste0(prefix, "_", "ChlorineAdd"),
"Select method of addition that sets free chlorine concentration at point of free ammonia addition",
"right",
options = list(container = "body")),
#Only show panel if free chlorine concentration is selected
conditionalPanel(
condition = paste0("input.", prefix, "_", "ChlorineAdd == 'conc'"),
#Create input and tooltip for free chlorine concentration addition
sliderInput(paste0(prefix, "_", "TOTCl_mgL"),
label = p(HTML("Free Chlorine Concentration (mg Cl<sub>2</sub>/L)"),
style = "font-size: 12px"),
min = 0.00,
max = 15.00,
value = 4.00,
step = 0.05
),
bsTooltip(id = paste0(prefix, "_", "TOTCl_mgL"),
"Set slider to known initial free chlorine concentration at point of free ammonia addition",
"right",
options = list(container = "body"))
),
#Only show panel if chlorine gas is selected
conditionalPanel(
condition = paste0("input.", prefix, "_", "ChlorineAdd == 'gas'"),
#Create input and tooltip for free chlorine gas addition
numericInput(paste0(prefix, "_", "TOTCl_gas_lbs"),
label = p(HTML("Gas Dose (pounds/day)"),
style = "font-size: 12px"),
min = 0,
max = 1e10,
value = 100,
step = 1),
bsTooltip(id = paste0(prefix, "_", "TOTCl_gas_lbs"),
"Enter known pounds/day addition of chlorine gas (Assumed 100% available chlorine)",
"right",
options = list(container = "body"))
),
#Only show panel if chlorine liquid is selected
conditionalPanel(
condition = paste0("input.", prefix, "_", "ChlorineAdd == 'liquid'"),
#Create input and tooltip for free chlorine liquid addition
numericInput(paste0(prefix, "_", "TOTCl_liquid_lbs"),
label = p(HTML("Liquid Dose (pounds/day)"),
style = "font-size: 12px"),
min = 0,
max = 1e10,
value = 100,
step = 1),
bsTooltip(id = paste0(prefix, "_", "TOTCl_liquid_lbs"),
"Enter known pounds/day addition of free chlorine solution",
"right",
options = list(container = "body")),
#Create input and tooltip for free chlorine liquid addition percent
sliderInput(paste0(prefix, "_", "TOTCl_liquid_percent"),
label = p(HTML("Liquid Strength (% available Cl<sub>2</sub>)"),
style = "font-size: 12px"),
min = 0,
max = 100,
value = 50,
step = 1),
bsTooltip(id = paste0(prefix, "_", "TOTCl_liquid_percent"),
"Set slider to known strength of free chlorine solution (set to 100% if already taken into account in liquid dose)",
"right",
options = list(container = "body"))
),
#Create input and tooltip for free ammonia addition method
selectInput(paste0(prefix, "_", "AmmoniaAdd"),
label = h5("Free Ammonia Addition Method"),
choices = c("Known Concentration" = "conc",
"Chlorine to Nitrogen Ratio" = "ratio",
"Gas Feed" = "gas",
"Liquid Feed" = "liquid"),
selected = "conc",
selectize = TRUE),
bsTooltip(id = paste0(prefix, "_", "AmmoniaAdd"),
"Select method of addition that sets free ammonia concentration at point of application to free chlorine",
"right",
options = list(container = "body")),
#Only show panel if free ammonia concentration is selected
conditionalPanel(
condition = paste0("input.", prefix, "_", "AmmoniaAdd == 'conc'"),
#Create input and tooltip for free ammonia concentration addition
sliderInput(paste0(prefix, "_", "TOTNH_mgL"),
label = p("Free Ammonia Concentration (mg N/L)",
style = "font-size: 12px"),
min = 0.00,
max = 5.00,
value = 1.00,
step = 0.05),
bsTooltip(id = paste0(prefix, "_", "TOTNH_mgL"),
"Use slider to set free ammonia concentration at point of application to free chlorine",
"right",
options = list(container = "body"))
),
#Only show panel if chlorine to nitrogen mass ratio is selected
conditionalPanel(
condition = paste0("input.", prefix, "_", "AmmoniaAdd == 'ratio'"),
#Create input and tooltip for chlorine to nitrogen mass ratio addition
sliderInput(paste0(prefix, "_", "ratio"),
label = p(HTML("Mass Ratio (Cl<sub>2</sub>:N)"),
style = "font-size: 12px"),
min = 0.05,
max = 15.00,
value = 4.00,
step = 0.05),
bsTooltip(id = paste0(prefix, "_", "ratio"),
"Use slider to set target chlorine to nitrogen mass ratio which will be used to calculated the free ammonia concentration at point of application of free chlorine",
"right",
options = list(container = "body"))
),
#Only show panel if free ammonia gas feed is selected
conditionalPanel(
condition = paste0("input.", prefix, "_", "AmmoniaAdd == 'gas'"),
#Create input and tooltip for free ammonia gas addition
numericInput(paste0(prefix, "_", "TOTNH_gas_lbs"),
label = p(HTML("Gas Dose (pounds/day)"),
style = "font-size: 12px"),
min = 0,
max = 1e10,
value = 15,
step = 1),
bsTooltip(id = paste0(prefix, "_", "TOTNH_gas_lbs"),
"Enter known pounds/day addition of ammonia gas (Assumed 100% available ammonia)",
"right",
options = list(container = "body"))
),
#Only show panel if free ammonia liquid feed is selected
conditionalPanel(
condition = paste0("input.", prefix, "_", "AmmoniaAdd == 'liquid'"),
#Create input and tooltip for free ammonia liquid addition
numericInput(paste0(prefix, "_", "TOTNH_liquid_lbs"),
label = p(HTML("Liquid Dose (pounds/day)"),
style = "font-size: 12px"),
min = 0,
max = 1e10,
value = 15,
step = 1),
bsTooltip(id = paste0(prefix, "_", "TOTNH_liquid_lbs"),
"Enter known pounds/day addition of free ammonia solution",
"right",
options = list(container = "body")),
#Create input and tooltip for free ammonia liquid addition percent
sliderInput(paste0(prefix, "_", "TOTNH_liquid_percent"),
label = p(HTML("Liquid Strength (% available NH<sub>3</sub>)"),
style = "font-size: 12px"),
min = 0,
max = 100,
value = 50,
step = 1),
bsTooltip(id = paste0(prefix, "_", "TOTNH_liquid_percent"),
"Set slider to known strength of free ammonia solution (set to 100% if already taken into account in liquid dose)",
"right",
options = list(container = "body"))
),
#Only show panel if free ammonia or free chlorine addition liquid or gas feed is selected
conditionalPanel(
condition = paste0("input.", prefix, "_", "ChlorineAdd == 'gas' ||
input.", prefix, "_", "ChlorineAdd == 'liquid' ||
input.", prefix, "_", "AmmoniaAdd == 'gas' ||
input.", prefix, "_", "AmmoniaAdd == 'liquid'"),
#Create input and tooltip for plant production
h5("Plant Information"),
numericInput(paste0(prefix, "_", "Q"),
label = p("Plant Production (MGD)",
style = "font-size: 12px"),
min = 0.1,
max = 1e10,
value = 2.0,
step = 0.1),
bsTooltip(id = paste0(prefix, "_", "Q"),
"Enter known plant production in million gallons per day (only required when entering gas or liquid chemical additions)",
"right",
options = list(container = "body"))
)
),
#Only show panel if preformed chloramines is selected
conditionalPanel(
condition = paste0("input.", prefix, "_", "Method == 'preform'"),
#Section title
h5("Known Chemical Concentrations"),
#Create input and tooltip for known monochloramine concentration
sliderInput(paste0(prefix, "_", "Mono_mgL"),
label = p(HTML("Monochloramine Concentration (mg Cl<sub>2</sub>/L)"),
style = "font-size: 12px"),
min = 0.00,
max = 10.00,
value = 4.00,
step = 0.05),
bsTooltip(id = paste0(prefix, "_", "Mono_mgL"),
"Set slider to known monochloramine concentration",
"right",
options = list(container = "body")),
br(),
#Create input and tooltip for known dichloramine concentration
sliderInput(paste0(prefix, "_", "Di_mgL"),
label = p(HTML("Dichloramine Concentration (mg Cl<sub>2</sub>/L)"),
style = "font-size: 12px"),
min = 0.00,
max = 10.00,
value = 0.00,
step = 0.05),
bsTooltip(id = paste0(prefix, "_", "Di_mgL"),
"Set slider to known dichloramine concentration (this can be estimated by measuring total chlorine and subtracting monochloramine)",
"right",
options = list(container = "body")),
br(),
#Create input and tooltip for known free ammonia concentration
sliderInput(paste0(prefix, "_", "FreeNH_mgL"),
label = p("Free Ammonia Concentration (mg N/L)",
style = "font-size: 12px"),
min = 0.00,
max = 5.00,
value = 0.10,
step = 0.05),
bsTooltip(id = paste0(prefix, "_", "FreeNH_mgL"),
"Set slider to known free ammonia concentration",
"right",
options = list(container = "body"))
),
#Only show panel if booster chlorination is selected
conditionalPanel(
condition = paste0("input.", prefix, "_", "Method == 'boost'"),
#Section title
h5("Known Chemical Concentrations"),
#Create input and tooltip for known monochloramine concentration
sliderInput(paste0(prefix, "_", "Mono_mgL_boost"),
label = p(HTML("Monochloramine Concentration (mg Cl<sub>2</sub>/L)"),
style = "font-size: 12px"),
min = 0.00,
max = 10.00,
value = 2.00,
step = 0.05),
bsTooltip(id = paste0(prefix, "_", "Mono_mgL_boost"),
"Set slider to known monochloramine concentration",
"right",
options = list(container = "body")),
br(),
#Create input and tooltip for known dichloramine concentration
sliderInput(paste0(prefix, "_", "Di_mgL_boost"),
label = p(HTML("Dichloramine Concentration (mg Cl<sub>2</sub>/L)"),
style = "font-size: 12px"),
min = 0.00,
max = 10.00,
value = 0.00,
step = 0.05),
bsTooltip(id = paste0(prefix, "_", "Di_mgL_boost"),
"Set slider to known dichloramine concentration (this can be estimated by measuring total chlorine and subtracting monochloramine)",
"right",
options = list(container = "body")),
br(),
#Create input and tooltip for known free ammonia concentration
sliderInput(paste0(prefix, "_", "TOTNH_mgL_boost"),
label = p("Free Ammonia Concentration (mg N/L)",
style = "font-size: 12px"),
min = 0.00,
max = 5.00,
value = 0.50,
step = 0.05),
bsTooltip(id = paste0(prefix, "_", "TOTNH_mgL_boost"),
"Set slider to known free ammonia concentration",
"right",
options = list(container = "body")),
#Section title
h5("Booster Free Chlorine Addition"),
#Create input and tooltip for known free chlorine concentration
sliderInput(paste0(prefix, "_", "TOTCl_mgL_boost"),
label = p(HTML("Added Free Chlorine Concentration (mg Cl<sub>2</sub>/L)"),
style = "font-size: 12px"),
min = 0.00,
max = 10.00,
value = 2.00,
step = 0.05),
bsTooltip(id = paste0(prefix, "_", "TOTCl_mgL_boost"),
"Set slider to known added free chlorine concentration to recombine free ammonia into chloramines",
"right",
options = list(container = "body"))
)
),