-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.R
1298 lines (1067 loc) · 57.8 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 server logic
server <- function(input, output, session) {
output$priors <- renderUI({
if (input$cal.bayesian) {
conditionalPanel(
condition = "input$cal.bayesian",
style = "margin-left: 20px;",
checkboxInput("priors", label = "Weak priors (Recommended)", value = TRUE)
)
}
})
options(shiny.maxRequestSize=800*1024^2)
# Show package citations
get_path <- reactive({
path <- file.path(paste0(getwd()), paste("Rpackages", ".bib", sep=""))
return(path)
})
get_bib <- reactive({
## Bib logic here
pkgbib <- bibtex::read.bib("Rpackages.bib")
df <- bib2df(get_path()) %>% dplyr::select(BIBTEXKEY, NOTE, AUTHOR, TITLE, YEAR, JOURNAL, VOLUME, PAGES, URL)
df$AUTHOR <- unlist(lapply(df$AUTHOR, paste, collapse = ", "))
df <- df %>% arrange(AUTHOR)
return(df)
})
output$bibTable <- DT::renderDataTable({
bib <- get_bib()
bib
}, caption = "This is an automatically generated list of R packages used to render and run BayClump. Citation information is provided by package authors.", options = list(pageLength = 20, info = FALSE))
# Calibration tab
output$BayClump_cal_temp <- downloadHandler(
filename = "BayClump_calibration_template.csv",
content = function(file) {
write.csv(BayClump_calibration_template, file, row.names = FALSE)
}
)
calibrationData = reactive({
switch(input$calset,
"model1" = return(Petersen),
"model2" = return(Anderson),
"model1and2" = return(PetersenAnderson),
"mycal" = reactiveValues({
req(input$calibrationdata)
n_rows = length(count.fields(input$calibrationdata$datapath))
df_out = read.csv(input$calibrationdata$datapath)
return(df_out)
}),
"all" = reactiveValues({
req(input$calibrationdata)
n_rows = length(count.fields(input$calibrationdata$datapath))
df_out = read.csv(input$calibrationdata$datapath)
alldat <- rbind(df_out, PetersenAnderson)
return(alldat)
})
)
})
#For parameter estimates
if(exists("wb")) rm(wb) # Delete any existing workbook in preparation for new results
wb <- createWorkbook("calibration output") # Prepare a workbook for calibration outputs
#For convergence
if(exists("wb3")) rm(wb3) # Delete any existing workbook in preparation for new results
wb3 <- createWorkbook("Bayesian output") # Prepare a workbook for calibration outputs
if(exists("wb4")) rm(wb4) # Delete any existing workbook in preparation for new results
wb4 <- createWorkbook("Bayesian posterior output") # Prepare a workbook for calibration outputs
#For convergence
if(exists("wb5")) rm(wb5) # Delete any existing workbook in preparation for new results
wb5 <- createWorkbook("Bayesian reconstruction posterior output") # Prepare a workbook for calibration outputs
observeEvent(input$calset,{
req(input$calset == "mycal")
showModal(modalDialog(
fileInput("calibrationdata", "Select calibration data file", accept = ".csv" )
))}
)
observe({
output$contents <- renderTable({
calsummary <- calibrationData() %>%
summarize(
"Samples" = length(calibrationData()$Sample.Name),
#"Unique samples" = length(unique(calibrationData()$Sample.Name)),
#"Total replicates" = sum(calibrationData()$N),
"Materials" = length(unique(calibrationData()$Material))
)
return(calsummary)
},
rownames=FALSE, options = list(pageLength = 1, info = FALSE)
)
})
toListen <- reactive({
list(input$runmods)
})
modresult <- eventReactive(toListen() , {
if ("all" %in% input$calibrationdata) {
print(noquote("Please upload calibration data first"))
}
priors <<- input$priors
priors <<- ifelse(isTRUE(priors), "Weak", "Informative")
replicates <<- input$replication
ngenerationsBayes <<- input$generations
ngenerationsrec.bayesian <<- input$generations
##Download priors
if(exists("wb6")) rm(wb6)
wb6 <- createWorkbook("Priors - Calibration")
if("Settings" %in% names(wb6) == TRUE)
{removeWorksheet(wb6, "Settings")}
if("Distributions" %in% names(wb6) == TRUE)
{removeWorksheet(wb6, "Distributions") }
pd <- cal.prior(prior = priors)
addWorksheet(wb6, "Settings") # Add a blank sheet
writeData(wb6, sheet = "Settings", attr(pd, "params")) # Write regression data
addWorksheet(wb6, "Distributions") # Add a blank sheet
writeData(wb6, sheet = "Distributions", pd) # Write regression data
output$downloadPriorsCalibration <- downloadHandler(
filename = function() {
paste("Priors_calibration_", Sys.time(), ".xlsx", sep="")
},
content = function(file) {
saveWorkbook(wb6, file, overwrite = TRUE)
}
)
##Download priors (reconstructions)
if(exists("wb7")) rm(wb7)
wb7 <- createWorkbook("Priors - Reconstruction")
if("Settings" %in% names(wb7) == TRUE)
{removeWorksheet(wb7, "Settings")}
if("Distributions" %in% names(wb7) == TRUE)
{removeWorksheet(wb7, "Distributions") }
pd <- rec.prior(prior = priors)
addWorksheet(wb7, "Settings") # Add a blank sheet
writeData(wb7, sheet = "Settings", attr(pd, "params")) # Write regression data
addWorksheet(wb7, "Distributions") # Add a blank sheet
writeData(wb7, sheet = "Distributions", pd) # Write regression data
output$downloadPriorsReconstruction <- downloadHandler(
filename = function() {
paste("Priors_reconstruction_", Sys.time(), ".xlsx", sep="")
},
content = function(file) {
saveWorkbook(wb7, file, overwrite = TRUE)
}
)
# Remove existing worksheets from wb on "run" click, if any
if("Linear regression" %in% names(wb) == TRUE)
{removeWorksheet(wb, "Linear regression") & removeWorksheet(wb, "Linear regression CI")}
if("Inverse linear regression" %in% names(wb) == TRUE)
{removeWorksheet(wb, "Inverse linear regression") & removeWorksheet(wb, "Inverse linear regression CI")}
if("York regression" %in% names(wb) == TRUE)
{removeWorksheet(wb, "York regression") & removeWorksheet(wb, "York regression CI")}
if("Deming regression" %in% names(wb) == TRUE)
{removeWorksheet(wb, "Deming regression") & removeWorksheet(wb, "Deming regression CI")}
if("Bayesian model no errors" %in% names(wb) == TRUE)
{removeWorksheet(wb, "Bayesian model no errors") & removeWorksheet(wb, "Bayesian model no errors CI")}
if("Bayesian model with errors" %in% names(wb) == TRUE)
{removeWorksheet(wb, "Bayesian model with errors") & removeWorksheet(wb, "Bayesian model with errors CI")}
if("Bayesian mixed w errors" %in% names(wb) == TRUE)
{removeWorksheet(wb, "Bayesian mixed w errors") & removeWorksheet(wb, "Bayesian mixed w errors CI")}
##Also for the Bayesian sheet
if("Bayesian model no errors" %in% names(wb3) == TRUE)
{removeWorksheet(wb3, "Bayesian model no errors")}
if("Bayesian model with errors" %in% names(wb3) == TRUE)
{removeWorksheet(wb3, "Bayesian model with errors") }
if("Bayesian mixed w errors" %in% names(wb3) == TRUE)
{removeWorksheet(wb3, "Bayesian mixed w errors")}
##Also for the Bayesian posterior sheet
if("Bayesian model no errors" %in% names(wb4) == TRUE)
{removeWorksheet(wb4, "Bayesian model no errors")}
if("Bayesian model with errors" %in% names(wb4) == TRUE)
{removeWorksheet(wb4, "Bayesian model with errors") }
if("Bayesian mixed w errors" %in% names(wb4) == TRUE)
{removeWorksheet(wb4, "Bayesian mixed w errors")}
lmcals <<- NULL
lminversecals <<- NULL
yorkcals <<- NULL
demingcals <<- NULL
bayeslincals <<- NULL
# Calibration data
calData <<- NULL
calData <<- calibrationData()
# Recode NA or 0 error values to dummy value
calData$D47error[calData$D47error == 0] <<- 0.000001
calData$TempError[calData$TempError == 0] <<- 0.000001
calData$D47error[is.na(calData$D47error)] <<- 0.000001
calData$TempError[is.na(calData$TempError)] <<- 0.000001
calData$Material[is.na(calData$Material)] <<- 1
calData$D47error <<- abs(calData$D47error)
calData$TempError <<- abs(calData$TempError)
calData$Material <<- factor(calData$Material, labels = seq(1:length(unique(calData$Material))))
if(min(as.numeric(calData$Material)) != 1){
print(noquote("The sequence of Materials now start from 1"))
}
##Limits of the CI
minLim <- min(calData$Temperature)
maxLim <- max(calData$Temperature)
observeEvent(input$max, {
updateSliderInput(inputId = "n", max = input$max)
})
if(input$cal.ols != FALSE |
input$cal.wols != FALSE |
input$cal.york != FALSE |
input$cal.deming != FALSE |
input$cal.bayesian != FALSE) {
withProgress(message = "Running selected models, please wait", {
if(input$cal.ols == FALSE) {
}
if(input$cal.wols == FALSE) {
}
if(input$cal.york == FALSE) {
}
if(input$cal.deming == FALSE) {
}
if(input$cal.bayesian == FALSE) {
}
totalModels <- c(input$cal.ols, input$cal.wols, input$cal.york,
input$cal.deming, input$cal.bayesian)
TotProgress <- length(which(totalModels == TRUE))
if(input$cal.ols != FALSE) {
#sink(file = "out/linmodtext.txt", type = "output")
lmcals <<- cal.ols(calData, replicates = replicates)
#sink()
incProgress(1/TotProgress, detail="...Done fitting the OLS...")
lmci <<- cal.ci(data = lmcals, from = minLim, to = maxLim)
lmcalci <- as.data.frame(lmci)
output$lmcalibration <- renderPlotly({
lmfig <- plot_ly(calibrationData()
)
lmfig <- lmfig %>%
add_trace(x = ~calibrationData()$Temperature,
y = ~D47,
type = "scatter",
mode = "markers",
marker = list(color = "black"),
opacity = 0.5,
name = "Raw data",
text = as.character(calibrationData()$Sample.Name),
hovertemplate = paste(
"<b>Sample: %{text}</b><br><br>",
"Temperature (10<sup>6</sup>/T<sup>2</sup>): %{x}<br>",
"Δ<sub>47</sub> (‰): %{y}<br>",
"Mineralogy: ", as.character(calibrationData()$Mineralogy),"<br>",
"Material: ", as.character(calibrationData()$Material),
"<extra></extra>"))
lmfig <- lmfig %>%
add_ribbons(data = lmcalci,
x = ~x,
y = ~median_est,
ymin = ~ci_lower_est,
ymax = ~ci_upper_est,
line = list(color = "#ffd166"),
fillcolor = "#ffd166",
opacity = 0.5,
name = "95% CI",
hovertemplate = paste(
"Temperature (10<sup>6</sup>/T<sup>2</sup>): %{x}<br>",
"Δ<sub>47</sub> (‰): %{y}<br>")) %>%
add_lines(data = lmcalci,
x = ~x,
y = ~median_est,
name = "Mean estimate",
line = list(color = "black", dash = "dash"),
hovertemplate = paste(
"Temperature (10<sup>6</sup>/T<sup>2</sup>): %{x}<br>",
"Δ<sub>47</sub> (‰): %{y}<br>"))
lmfig <- lmfig %>% layout(title = "<b> Linear calibration model </b>",
legend=list(title=list(text="Legend")),
xaxis = list(title = "Temperature (10<sup>6</sup>/T<sup>2</sup>)", hoverformat = ".1f"),
yaxis = list(title = "Δ<sub>47</sub> (‰)", hoverformat = ".3f"))
return(lmfig)
})
addWorksheet(wb, "Linear regression") # Add a blank sheet
addWorksheet(wb, "Linear regression CI") # Add a blank sheet
lmcalci2 <- lmcalci
names(lmcalci2) <- c("10^6/T^2", "D47_median_est", "D47_ci_lower_est", "D47_ci_upper_est")
writeData(wb, sheet = "Linear regression", lmcals) # Write regression data
writeData(wb, sheet = "Linear regression CI", lmcalci2)
output$lmcal <- renderPrint({
do.call(rbind.data.frame,apply(lmcals, 2, function(x){
cbind.data.frame(Mean= round(mean(x), 4), `SD`=round(sd(x),7))
}))
})
}
if(input$cal.wols != FALSE) {
#sink(file = "out/inverselinmodtext.txt", type = "output")
lminversecals <<- cal.wols(calData, replicates = replicates)
#sink()
incProgress(1/TotProgress, detail="...Done fitting weighted OLS...")
lminverseci <- cal.ci(data = lminversecals, from = minLim, to = maxLim)
lminversecalci <- as.data.frame(lminverseci)
output$lminversecalibration <- renderPlotly({
lminversefig <- plot_ly(data = calibrationData()
)
lminversefig <- lminversefig %>%
add_trace(x = ~calibrationData()$Temperature,
y = ~D47,
type = "scatter",
mode = "markers",
marker = list(color = "black"),
opacity = 0.5,
name = "Raw data",
text = as.character(calibrationData()$Sample.Name),
hovertemplate = paste(
"<b>Sample: %{text}</b><br><br>",
"Temperature (10<sup>6</sup>/T<sup>2</sup>): %{x}<br>",
"Δ<sub>47</sub> (‰): %{y}<br>",
"Mineralogy: ", as.character(calibrationData()$Mineralogy),"<br>",
"Material: ", as.character(calibrationData()$Material),
"<extra></extra>")) %>%
add_ribbons(data = lminversecalci,
x = ~x,
y = ~median_est,
ymin = ~ci_lower_est,
ymax = ~ci_upper_est,
line = list(color = "#ffd166"),
fillcolor = "#ffd166",
opacity = 0.5,
name = "95% CI",
hovertemplate = paste(
"Temperature (10<sup>6</sup>/T<sup>2</sup>): %{x}<br>",
"Δ<sub>47</sub> (‰): %{y}<br>")) %>%
add_lines(data = lminversecalci,
x = ~x,
y = ~median_est,
name = "Mean estimate",
line = list(color = "black", dash = "dash"),
hovertemplate = paste(
"Temperature (10<sup>6</sup>/T<sup>2</sup>): %{x}<br>",
"Δ<sub>47</sub> (‰): %{y}<br>"))
lminversefig <- lminversefig %>% layout(title = "<b> Inverse linear calibration model </b>",
legend=list(title=list(text="Legend")),
xaxis = list(title = "Temperature (10<sup>6</sup>/T<sup>2</sup>)", hoverformat = ".1f"),
yaxis = list(title = "Δ<sub>47</sub> (‰)", hoverformat = ".3f"))
return(lminversefig)
})
addWorksheet(wb, "Inverse linear regression") # Add a blank sheet
addWorksheet(wb, "Inverse linear regression CI") # Add a blank sheet
lminversecalci2 <- lminversecalci
names(lminversecalci2) <- c("10^6/T^2", "D47_median_est", "D47_ci_lower_est", "D47_ci_upper_est")
writeData(wb, sheet = "Inverse linear regression", lminversecals) # Write regression data
writeData(wb, sheet = "Inverse linear regression CI", lminversecalci2)
# cat("\nInverse regression complete \n *R^2=", round(unlist(attributes(lminversecals)$R2[1],4)),
# " (95% CI, ",round(unlist(attributes(lminversecals)$R2[2],4)),"-",round(unlist(attributes(lminversecals)$R2[3],4)),")"
# )
output$lminversecal <- renderPrint({
do.call(rbind.data.frame,apply(lminversecals, 2, function(x){
cbind.data.frame(Mean= round(mean(x), 4),`SD` = round(sd(x),7))
}))
})
}
if(input$cal.york != FALSE) {
#sink(file = "out/yorkmodtext.txt", type = "output")
yorkcals <<- cal.york(calData, replicates = replicates)
#sink()
incProgress(1/TotProgress, detail="...Done fitting York regression...")
yorkci <- cal.ci(data = yorkcals, from = minLim, to = maxLim)
yorkcalci <- as.data.frame(yorkci)
output$yorkcalibration <- renderPlotly({
yorkfig <- plot_ly(data = calibrationData()
)
yorkfig <- yorkfig %>%
add_trace(x = ~calibrationData()$Temperature,
y = ~D47,
type = "scatter",
mode = "markers",
marker = list(color = "black"),
opacity = 0.5,
name = "Raw data",
text = as.character(calibrationData()$Sample.Name),
hovertemplate = paste(
"<b>Sample: %{text}</b><br><br>",
"Temperature (10<sup>6</sup>/T<sup>2</sup>): %{x}<br>",
"Δ<sub>47</sub> (‰): %{y}<br>",
"Mineralogy: ", as.character(calibrationData()$Mineralogy),"<br>",
"Material: ", as.character(calibrationData()$Material),
"<extra></extra>")) %>%
add_ribbons(data = yorkcalci,
x = ~x,
y = ~median_est,
ymin = ~ci_lower_est,
ymax = ~ci_upper_est,
line = list(color = "#ffd166"),
fillcolor = "#ffd166",
opacity = 0.5,
name = "95% CI",
hovertemplate = paste(
"Temperature (10<sup>6</sup>/T<sup>2</sup>): %{x}<br>",
"Δ<sub>47</sub> (‰): %{y}<br>")) %>%
add_lines(data = yorkcalci,
x = ~x,
y = ~median_est,
name = "Mean estimate",
line = list(color = "black", dash = "dash"),
hovertemplate = paste(
"Temperature (10<sup>6</sup>/T<sup>2</sup>): %{x}<br>",
"Δ<sub>47</sub> (‰): %{y}<br>"))
yorkfig <- yorkfig %>% layout(title = "<b> York calibration model </b>",
legend=list(title=list(text="Legend")),
xaxis = list(title = "Temperature (10<sup>6</sup>/T<sup>2</sup>)", hoverformat = ".1f"),
yaxis = list(title = "Δ<sub>47</sub> (‰)", hoverformat = ".3f"))
return(yorkfig)
})
addWorksheet(wb, "York regression") # Add a blank sheet
addWorksheet(wb, "York regression CI") # Add a blank sheet
yorkcalci2 <- yorkcalci
names(yorkcalci2) <- c("10^6/T^2", "D47_median_est", "D47_ci_lower_est", "D47_ci_upper_est")
writeData(wb, sheet = "York regression", yorkcals) # Write regression data
writeData(wb, sheet = "York regression CI", yorkcalci2)
output$york <- renderPrint({
do.call(rbind.data.frame,apply(yorkcals, 2, function(x){
cbind.data.frame(Mean= round(mean(x), 4),`SD`=round(sd(x),7))
}))
})
}
if(input$cal.deming != FALSE) {
#sink(file = "out/demingmodtext.txt", type = "output")
demingcals <<- cal.deming(calData, replicates = replicates)
#sink()
incProgress(1/TotProgress, detail="...Done fitting Deming regression model...")
demingci <- cal.ci(data = demingcals, from = minLim, to = maxLim)
demingcalci <- as.data.frame(demingci)
output$demingcalibration <- renderPlotly({
demingfig <- plot_ly(data = calibrationData()
)
demingfig <- demingfig %>%
add_trace(x = ~calibrationData()$Temperature,
y = ~D47,
type = "scatter",
mode = "markers",
marker = list(color = "black"),
opacity = 0.5,
name = "Raw data",
text = as.character(calibrationData()$Sample.Name),
hovertemplate = paste(
"<b>Sample: %{text}</b><br><br>",
"Temperature (10<sup>6</sup>/T<sup>2</sup>): %{x}<br>",
"Δ<sub>47</sub> (‰): %{y}<br>",
"Mineralogy: ", as.character(calibrationData()$Mineralogy),"<br>",
"Material: ", as.character(calibrationData()$Material),
"<extra></extra>")) %>%
add_ribbons(data = demingcalci,
x = ~x,
y = ~median_est,
ymin = ~ci_lower_est,
ymax = ~ci_upper_est,
line = list(color = "#ffd166"),
fillcolor = "#ffd166",
opacity = 0.5,
name = "95% CI",
hovertemplate = paste(
"Temperature (10<sup>6</sup>/T<sup>2</sup>): %{x}<br>",
"Δ<sub>47</sub> (‰): %{y}<br>")) %>%
add_lines(data = demingcalci,
x = ~x,
y = ~median_est,
name = "Mean estimate",
line = list(color = "black", dash = "dash"),
hovertemplate = paste(
"Temperature (10<sup>6</sup>/T<sup>2</sup>): %{x}<br>",
"Δ<sub>47</sub> (‰): %{y}<br>"))
demingfig <- demingfig %>% layout(title = "<b> Deming calibration model </b>",
legend=list(title=list(text="Legend")),
xaxis = list(title = "Temperature (10<sup>6</sup>/T<sup>2</sup>)", hoverformat = ".1f"),
yaxis = list(title = "Δ<sub>47</sub> (‰)", hoverformat = ".3f"))
return(demingfig)
})
addWorksheet(wb, "Deming regression") # Add a blank sheet
addWorksheet(wb, "Deming regression CI") # Add a blank sheet
demingcalci2 <- demingcalci
names(demingcalci2) <- c("10^6/T^2", "D47_median_est", "D47_ci_lower_est", "D47_ci_upper_est")
writeData(wb, sheet = "Deming regression", demingcals) # Write regression data
writeData(wb, sheet = "Deming regression CI", demingcalci2)
output$deming <- renderPrint({
do.call(rbind.data.frame,apply(demingcals, 2, function(x){
cbind.data.frame(Mean= round(mean(x), 4),`SD`=round(sd(x),7))
}))
})
}
if(input$cal.bayesian != FALSE) {
#sink(file = "out/Bayeslinmodtext.txt", type = "output")
bayeslincals <<- cal.bayesian(calibrationData = calData,
priors = priors,
numSavedSteps = ngenerationsBayes)
PostBLM1_fit_NoErrors <-do.call(rbind, mcmc.list(
lapply(1:ncol(bayeslincals$BLM1_fit_NoErrors), function(x) {
mcmc(as.array(bayeslincals$BLM1_fit_NoErrors)[,x,])
})))
PostBLM1_fit_NoErrors <- PostBLM1_fit_NoErrors[,-grep("log_lik", colnames(PostBLM1_fit_NoErrors))]
PostBLM1_fit <- do.call(rbind, mcmc.list(
lapply(1:ncol(bayeslincals$BLM1_fit), function(x) {
mcmc(as.array(bayeslincals$BLM1_fit)[,x,])
})))
PostBLM1_fit <- PostBLM1_fit[,-grep("log_lik", colnames(PostBLM1_fit))]
PostBLM3_fit <- do.call(rbind, mcmc.list(
lapply(1:ncol(bayeslincals$BLM3_fit), function(x) {
mcmc(as.array(bayeslincals$BLM3_fit)[,x,])
})))
PostBLM3_fit <- PostBLM3_fit[,-grep("log_lik", colnames(PostBLM3_fit))]
#sink()
incProgress(1/TotProgress, detail="...Done fitting the Bayesian linear regression model...")
bayeslincinoerror <- cal.ci(data = PostBLM1_fit_NoErrors, from = minLim, to = maxLim)
bayeslincalcinoerror <- as.data.frame(bayeslincinoerror)
bayeslinciwitherror <- cal.ci(data = PostBLM1_fit, from = minLim, to = maxLim)
bayeslincalciwitherror <- as.data.frame(bayeslinciwitherror)
output$bayeslincalibration <- renderPlotly({
bayeslinfig <- plot_ly(data = calibrationData()
)
bayeslinfig <- bayeslinfig %>%
add_trace(x = ~calibrationData()$Temperature,
y = ~D47,
type = "scatter",
mode = "markers",
marker = list(color = "black"),
opacity = 0.5,
name = "Raw data",
text = as.character(calibrationData()$Sample.Name),
hovertemplate = paste(
"<b>Sample: %{text}</b><br><br>",
"Temperature (10<sup>6</sup>/T<sup>2</sup>): %{x}<br>",
"Δ<sub>47</sub> (‰): %{y}<br>",
"Mineralogy: ", as.character(calibrationData()$Mineralogy),"<br>",
"Material: ", as.character(calibrationData()$Material),
"<extra></extra>")) %>%
add_ribbons(data = bayeslincalcinoerror,
x = ~x,
y = ~median_est,
ymin = ~ci_lower_est,
ymax = ~ci_upper_est,
line = list(color = "#ffd166"),
fillcolor = "#ffd166",
opacity = 0.5,
name = "95% CI - no error",
hovertemplate = paste(
"Temperature (10<sup>6</sup>/T<sup>2</sup>): %{x}<br>",
"Δ<sub>47</sub> (‰): %{y}<br>")) %>%
add_lines(data = bayeslincalcinoerror,
x = ~x,
y = ~median_est,
name = "Mean estimate - no error",
line = list(color = "black", dash = "dash"),
hovertemplate = paste(
"Temperature (10<sup>6</sup>/T<sup>2</sup>): %{x}<br>",
"Δ<sub>47</sub> (‰): %{y}<br>")) %>%
add_ribbons(data = bayeslincalciwitherror,
x = ~x,
y = ~median_est,
ymin = ~ci_lower_est,
ymax = ~ci_upper_est,
line = list(color = "#446455"),
fillcolor = "#446455",
opacity = 0.5,
name = "95% CI - with error",
hovertemplate = paste(
"Temperature (10<sup>6</sup>/T<sup>2</sup>): %{x}<br>",
"Δ<sub>47</sub> (‰): %{y}<br>")) %>%
add_lines(data = bayeslincalciwitherror,
x = ~x,
y = ~median_est,
name = "Mean estimate - with error",
line = list(color = "#446455", dash = "dash"),
hovertemplate = paste(
"Temperature (10<sup>6</sup>/T<sup>2</sup>): %{x}<br>",
"Δ<sub>47</sub> (‰): %{y}<br>"))
bayeslinfig <- bayeslinfig %>% layout(title = "<b> Bayesian linear calibration model </b>",
legend=list(title=list(text="Legend")),
xaxis = list(title = "Temperature (10<sup>6</sup>/T<sup>2</sup>)", hoverformat = ".1f"),
yaxis = list(title = "Δ<sub>47</sub> (‰)", hoverformat = ".3f"))
return(bayeslinfig)
})
addWorksheet(wb, "Bayesian model no errors") # Add a blank sheet
addWorksheet(wb, "Bayesian model no errors CI") # Add a blank sheet
addWorksheet(wb, "Bayesian model with errors") # Add a blank sheet
addWorksheet(wb, "Bayesian model with errors CI") # Add a blank sheet
bayeslincalcinoerror2 <- bayeslincalcinoerror
names(bayeslincalcinoerror2) <- c("10^6/T^2", "D47_median_est", "D47_ci_lower_est", "D47_ci_upper_est")
bayeslincalciwitherror2 <- bayeslincalciwitherror
names(bayeslincalciwitherror2) <- c("10^6/T^2", "D47_median_est", "D47_ci_lower_est", "D47_ci_upper_est")
writeData(wb, sheet = "Bayesian model no errors", PostBLM1_fit_NoErrors) # Write regression data
writeData(wb, sheet = "Bayesian model no errors CI", bayeslincalcinoerror2)
writeData(wb, sheet = "Bayesian model with errors", PostBLM1_fit) # Write regression data
writeData(wb, sheet = "Bayesian model with errors CI", bayeslincalciwitherror2)
##For the Bayesian sheet
conv_BLM <- summary(bayeslincals$BLM1_fit_NoErrors)$summary
conv_BLM_errors <- summary(bayeslincals$BLM1_fit)$summary
conv_BLM <- cbind.data.frame(parameter=row.names(conv_BLM),conv_BLM)
conv_BLM_errors <- cbind.data.frame(parameter=row.names(conv_BLM_errors),conv_BLM_errors)
addWorksheet(wb3, "Bayesian model no errors") # Add a blank sheet
addWorksheet(wb3, "Bayesian model with errors") # Add a blank sheet
writeData(wb3, sheet = "Bayesian model no errors", conv_BLM) # Write regression data
writeData(wb3, sheet = "Bayesian model with errors", conv_BLM_errors) # Write regression data
##For the posterior sheet
addWorksheet(wb4, "Bayesian model no errors") # Add a blank sheet
addWorksheet(wb4, "Bayesian model with errors") # Add a blank sheet
writeData(wb4, sheet = "Bayesian model no errors", PostBLM1_fit_NoErrors) # Write regression data
writeData(wb4, sheet = "Bayesian model with errors", PostBLM1_fit) # Write regression data
outBLM <- summary(bayeslincals$BLM1_fit_NoErrors)$summary
output$blinnoerr <- renderPrint({
ret <- outBLM[c(1:2),c(1,3)]
cbind.data.frame(Mean= round(ret[,1], 4),`SD`=round(ret[,2],7))
})
outBLMerrors <- summary(bayeslincals$BLM1_fit)$summary
output$blinwerr <- renderPrint({
ret <- outBLMerrors[c(1:2),c(1,3)]
cbind.data.frame(Mean= round(ret[,1], 4),`SD`=round(ret[,2],7))
})
outBLMM <- summary(bayeslincals$BLM3_fit)$summary
outBLMM <- as.data.frame(outBLMM[grep("alpha|beta", row.names(outBLMM)),] )
output$blinmwerr <- renderPrint({
ret <- outBLMM[,c(1,3)]
ret2 <- cbind.data.frame(Mean= round(ret[,1], 4),`SD`=round(ret[,2],7))
row.names(ret2) <- row.names(ret)
ret2
}
)
outBLMM2 <- PostBLM3_fit
outBLMM2 <- as.data.frame(outBLMM2[,grep("alpha|beta", colnames(outBLMM2))] )
nmat <- ncol(outBLMM2)/2
outBLMM2_alpha <- as.data.frame(outBLMM2[,grep("alpha", colnames(outBLMM2))])
outBLMM2_beta <- as.data.frame(outBLMM2[,grep("beta", colnames(outBLMM2))])
bayeslmminciwitherror <- lapply(1:nmat, function(x){
subset <- cbind.data.frame("alpha" = outBLMM2_alpha[,x], "beta" = outBLMM2_beta[,x])
cal.ci(data = subset, from = minLim, to = maxLim)[[1]]
})
bayeslmminciwitherror <- rbindlist(bayeslmminciwitherror, idcol="Material")
bayeslmmincalciwitherror <- as.data.frame(bayeslmminciwitherror)
addWorksheet(wb, "Bayesian mixed w errors") # Add a blank sheet
addWorksheet(wb, "Bayesian mixed w errors CI") # Add a blank sheet
bayeslmmincalciwitherror2 <- bayeslmmincalciwitherror
names(bayeslmmincalciwitherror2) <- c("material", "10^6/T^2", "D47_median_est", "D47_ci_lower_est", "D47_ci_upper_est")
writeData(wb, sheet = "Bayesian mixed w errors", PostBLM3_fit) # Write regression data
writeData(wb, sheet = "Bayesian mixed w errors CI", bayeslmmincalciwitherror2)
##For the Bayesian sheet
conv_BLMM <- summary(bayeslincals$BLM3_fit)$summary
conv_BLMM <- cbind.data.frame(parameter=row.names(conv_BLMM),conv_BLMM)
addWorksheet(wb3, "Bayesian mixed w errors") # Add a blank sheet
writeData(wb3, sheet = "Bayesian mixed w errors", conv_BLMM) # Write regression data
addWorksheet(wb4, "Bayesian mixed w errors") # Add a blank sheet
writeData(wb4, sheet = "Bayesian mixed w errors", PostBLM3_fit) # Write regression data
output$bayesmixedcalibration <- renderPlotly({
bayesmixedfig <- plot_ly(data = calibrationData()
)
bayesmixedfig <- bayesmixedfig %>%
add_trace(x = ~calibrationData()$Temperature,
y = ~D47,
type = "scatter",
mode = "markers",
marker = list(color = "black"),
opacity = 0.5,
name = "Raw data",
text = as.character(calibrationData()$Sample.Name),
hovertemplate = paste(
"<b>Sample: %{text}</b><br><br>",
"Temperature (10<sup>6</sup>/T<sup>2</sup>): %{x}<br>",
"Δ<sub>47</sub> (‰): %{y}<br>",
"Mineralogy: ", as.character(calibrationData()$Mineralogy),"<br>",
"Material: ", as.character(calibrationData()$Material),
"<extra></extra>"))
colsTarget <- viridis(nmat, option = "D", end = 0.9)
materials <- unique(bayeslmmincalciwitherror$Material)
for(y in 1:nmat){
bayesmixedfig <- bayesmixedfig %>%
add_ribbons(data = bayeslmmincalciwitherror[bayeslmmincalciwitherror$Material==materials[y],],
x = ~x,
y = ~median_est,
ymin = ~ci_lower_est,
ymax = ~ci_upper_est,
line = list(color = colsTarget[y]),
fillcolor = colsTarget[y],
opacity = 0.5,
name = paste("95% CI - with error, Material ", materials[y]),
hovertemplate = paste(
"Temperature (10<sup>6</sup>/T<sup>2</sup>): %{x}<br>",
"Δ<sub>47</sub> (‰): %{y}<br>")) %>%
add_lines(data = bayeslmmincalciwitherror[bayeslmmincalciwitherror$Material==materials[y],],
x = ~x,
y = ~median_est,
name = paste("Mean estimate - with error, Material ", materials[y]),
line = list(color = colsTarget[y], dash = "dash"),
hovertemplate = paste(
"Temperature (10<sup>6</sup>/T<sup>2</sup>): %{x}<br>",
"Δ<sub>47</sub> (‰): %{y}<br>"))
}
bayesmixedfig <- bayesmixedfig %>% layout(title = "<b> Bayesian mixed model </b>",
legend=list(title=list(text="Legend")),
xaxis = list(title = "Temperature (10<sup>6</sup>/T<sup>2</sup>)", hoverformat = ".1f"),
yaxis = list(title = "Δ<sub>47</sub> (‰)", hoverformat = ".3f"))
return(bayesmixedfig)
})
lootab <- attr(bayeslincals,"loo")
cat("Model comparison in loo\n\n")
cat("")
print(lootab)
}
})
}
})
output$modresults <- renderPrint({
modresult()
})
output$downloadcalibrations <- downloadHandler(
filename = function() {
paste("Calibration_output_", Sys.time(), ".xlsx", sep="")
},
content = function(file) {
saveWorkbook(wb, file, overwrite = TRUE)
}
)
output$downloadBayesian <- downloadHandler(
filename = function() {
paste("Bayesian_output_", Sys.time(), ".xlsx", sep="")
},
content = function(file) {
saveWorkbook(wb3, file, overwrite = TRUE)
}
)
output$downloadPosteriorCalibration <- downloadHandler(
filename = function() {
paste("Bayesian_posterior_output_", Sys.time(), ".xlsx", sep="")
},
content = function(file) {
saveWorkbook(wb4, file, overwrite = TRUE)
}
)
# Calibration plots tab
observe({
minlength <- length(unique(calibrationData()$Mineralogy))
if( !all(is.na(calibrationData()$Mineralogy)) == TRUE ){
output$rawcaldata <- renderPlotly({
rawcalfig <- plot_ly(calibrationData(),
x = ~Temperature,
y = ~D47,
type = "scatter",
mode = "markers",
#linetype = ~as.factor(Material),
color = ~as.factor(Mineralogy),
colors = viridis_pal(option = "D", end = 0.9)(minlength),
opacity = 0.6,
error_y = ~list(array = ~D47error, color = "#000000"),
error_x = ~list(array = ~TempError, color = "#000000"),
text = as.character(calibrationData()$Sample.Name),
hovertemplate = paste(
"<b>Sample: %{text}</b><br><br>",
"Temperature (10<sup>6</sup>/T<sup>2</sup>): %{x}<br>",
"Δ<sub>47</sub> (‰): %{y}<br>",
"Mineralogy: ", as.character(calibrationData()$Mineralogy),"<br>",
"Material: ", as.character(calibrationData()$Material),
"<extra></extra>"))
rawcalfig <- rawcalfig %>% layout(title = "<b> Raw calibration data from user input </b>",
legend=list(title=list(text="Material and mineralogy")),
xaxis = list(title = "Temperature (10<sup>6</sup>/T<sup>2</sup>)"),
yaxis = list(title = "Δ<sub>47</sub> (‰)", hoverformat = ".3f"))
return(rawcalfig)
})
}else{
output$rawcaldata <- renderPlotly({
rawcalfig <- plot_ly(calibrationData(),
x = ~Temperature,
y = ~D47,
type = "scatter",
mode = "lines+markers",
linetype = ~as.factor(Material),
color = ~as.factor(Material),
colors = viridis_pal(option = "D", end = 0.9)(length(unique(calibrationData()$Material))),
opacity = 0.6,
error_y = ~list(array = ~D47error, color = "#000000"),
error_x = ~list(array = ~TempError, color = "#000000"),
text = as.character(calibrationData()$Sample.Name),
hovertemplate = paste(
"<b>Sample: %{text}</b><br><br>",
"Temperature (10<sup>6</sup>/T<sup>2</sup>): %{x}<br>",
"Δ<sub>47</sub> (‰): %{y}<br>",
"Material: ", as.character(calibrationData()$Material),
"<extra></extra>"))
rawcalfig <- rawcalfig %>% layout(title = "<b> Raw calibration data from user input </b>",
legend=list(title=list(text="Material")),
xaxis = list(title = "Temperature (10<sup>6</sup>/T<sup>2</sup>)"),
yaxis = list(title = "Δ<sub>47</sub> (‰)", hoverformat = ".3f"))
return(rawcalfig)
})
}
})
# Reconstruction tab
output$BayClump_reconstruction_template.csv <- downloadHandler(
filename = "BayClump_reconstruction_template.csv",
content = function(file) {
write.csv(BayClump_reconstruction_template, file, row.names = FALSE)
}
)
reconstructionData = reactive({
req(input$reconstructiondata)
n_rows = length(count.fields(input$reconstructiondata$datapath))
df_out = read.csv(input$reconstructiondata$datapath)
return(df_out)
})
if(exists("wb2")) rm(wb2) # Delete any existing workbook in preparation for new results
wb2 <- createWorkbook("reconstruction output") # Prepare a workbook for reconstruction outputs
observe({
output$contents2 <- renderTable({
recsummary <- reconstructionData() %>%
summarize(
"Unique samples" = length(unique(reconstructionData()$Sample)),
"Total replicates" = sum(reconstructionData()$N),
"Materials" = length(unique(reconstructionData()$Material))
)
return(recsummary)
},
rownames=FALSE, options = list(pageLength = 1, info = FALSE)
)
})
recresult <- eventReactive(input$runrec, {
if(is.null(input$reconstructiondata)) {print(noquote("Please upload reconstruction data first"))}
if(!is.null(input$reconstructiondata)) {
recData <- NULL
recData <- reconstructionData()
# Remove existing worksheets from wb2 on "run" click, if any
if("Linear" %in% names(wb2) == TRUE)
{removeWorksheet(wb2, "Linear")}
if("Linear w no uncertainty" %in% names(wb2) == TRUE)
{removeWorksheet(wb2, "Linear w no uncertainty")}
if("Inverse linear" %in% names(wb2) == TRUE)
{removeWorksheet(wb2, "Inverse linear")}
if("Inverse linear w no uncertainty" %in% names(wb2) == TRUE)
{removeWorksheet(wb2, "Inverse linear w no uncertainty")}
if("York" %in% names(wb2) == TRUE)
{removeWorksheet(wb2, "York")}
if("York w no uncertainty" %in% names(wb2) == TRUE)
{removeWorksheet(wb2, "York w no uncertainty")}
if("Deming" %in% names(wb2) == TRUE)
{removeWorksheet(wb2, "Deming")}
if("Deming w no uncertainty" %in% names(wb2) == TRUE)
{removeWorksheet(wb2, "Deming w no uncertainty")}
if("Bayes and error" %in% names(wb2) == TRUE)
{removeWorksheet(wb2, "Bayes and error") }
if("Bayes w error no uncertainty" %in% names(wb2) == TRUE)
{removeWorksheet(wb2, "Bayes w error no uncertainty") }
if("Bayesian predictions" %in% names(wb2) == TRUE)
{removeWorksheet(wb2, "Bayesian predictions")}
if("Bayesian mixed model" %in% names(wb2) == TRUE)
{removeWorksheet(wb2, "Bayesian mixed model")}
if("Bayesian linear model, errors" %in% names(wb2) == TRUE)
{removeWorksheet(wb2, "Bayesian linear model, errors")}
if("Bayesian linear model" %in% names(wb2) == TRUE)
{removeWorksheet(wb2, "Bayesian linear model")}
if("Bayesian linear mixed model" %in% names(wb2) == TRUE)
{removeWorksheet(wb2, "Bayesian linear mixed model")}
##Also for the Bayesian posterior sheet