-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.R
1135 lines (1034 loc) · 45.1 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
library(shiny)
library(dplyr)
library(data.table)
library(DT)
library(netmeta)
library(BUGSnet)
library(bslib) # used to override default bootstrap version (4 instead of 3)
require(tidyverse)
source("scripts/util.R")
source("scripts/netcontrib.R")
source("scripts/nmafunnel.R")
source("scripts/makeJagsNMAdata.R")
source("scripts/modelNMAContinuous.R")
source("scripts/modelNMRContinuous.R")
source("scripts/modelNMRContinuous_bExch.R")
source("scripts/outJagsNMAmedian.R")
library(R2jags)
server <- function(input, output, session) {
#-----------------------------------------------------------------------------
# State variables
#-----------------------------------------------------------------------------
state <- reactiveValues(data = {}, # list of state variables
parametersSet = FALSE,
analysisStarted = FALSE,
# analysis options
inputSM = "",
inputMod = "",
inputRef = "",
inputBH = "",
inputBeta = "",
treatments = "",
modelFixed = FALSE,
modelRandom = FALSE,
burnIn = 1000,
numIter = 10000,
thin = 1,
# analysis outputs and state
error = "",
nma = "",
nmaDone = FALSE,
bData = "",
bnma = "",
bnmaDone = FALSE,
bnmr = "",
bnmrDone = FALSE,
nmrData = NULL,
nmrLeague = "",
# tables calculated from results
contributionMatrix = "",
pairwiseTable = tibble(),
robTable = tibble()
)
#-----------------------------------------------------------------------------
# Reactives
#-----------------------------------------------------------------------------
dataset <- reactive({state$data$alldata}) # reactive value to store the data
directs <- reactive({state$data$directs}) # just the direct links
btab <- reactive({
validate(need(state$bData != "", "bData not ready"),
need(state$parametersSet, "parameters not set"))
net.tab(data = state$bData,
outcome = ifelse(state$inputSM =="OR" | state$inputSM == "RR", "r", "mean"),
N = "n",
type.outcome = ifelse(state$inputSM=="OR" | state$inputSM=="RR", "binomial", "continuous"))
})
#-----------------------------------------------------------------------------
# Observers
#-----------------------------------------------------------------------------
observeEvent(input$file, {
state$data <- read.data(input$file)
}, ignoreInit = TRUE)
observeEvent(state$data$directs, {
res <- unique(state$data$directs$t) %>% sort()
state$treatments <- res
})
# Analysis hook --------------------------------------------------------------
observeEvent(input$startAnalysis, {
print("starting analysis")
state$analysisStarted <- TRUE
}, ignoreInit = TRUE, once = TRUE)
observeEvent(state$analysisStarted, {
if (state$analysisStarted) {
print("starting NMA")
state$nma <- nma(state$data$directs, state$inputSM, state$modelFixed, state$modelRandom)
state$nmaDone <- TRUE
print("NMA done")
} else {
state$nma <- ""
state$nmaDone <- FALSE
}
}, ignoreNULL = TRUE)
# Analysis parameters --------------------------------------------------------
observeEvent(input$inputSM,{
state$inputSM <- input$inputSM
})
observeEvent(state$inputMod,{
state$modelFixed <- input$inputMod == "fixed"
state$modelRandom <- input$inputMod == "random"
}, ignoreNULL = TRUE)
observeEvent(input$numIter, {
state$numIter <- input$numIter
# AH: this enforces a minimum burn in, but the input does not necessarily reflect this
updateNumericInput(session, "burnIn", min = state$numIter * 0.1)
state$burnIn <- max(state$burnIn, state$numIter * 0.1)
})
observeEvent(input$burnIn, {
state$burnIn <- max(input$burnIn, state$numIter * 0.1)
})
observeEvent(input$thin,
state$thin <- input$thin)
observeEvent(input$inputMod,
state$inputMod <- input$inputMod
)
observeEvent(input$inputRef,
state$inputRef <- input$inputRef
)
observeEvent(input$inputBH,
state$inputBH <- input$inputBH
)
observeEvent(input$inputBeta,
state$inputBeta <- input$inputBeta
)
# Check that all parameters are set
observe({
validate(
need(state$inputSM != "", "SM not selected"),
need(state$inputMod != "", "Model not selected"),
need(state$inputRef != "", "Reference not selected"),
need(state$inputBH != "", "Value direction not selected"),
need(state$inputBeta != "", "Assumption coefficients not selected"),
need(state$burnIn >= (0.1 * state$numIter), "Burn-in must be at least 10% of iterations")
)
print("parameters set")
state$parametersSet <- TRUE
})
observe({
validate(
need(state$inputSM != "", "no sm"),
need(state$inputRef != "", "no ref")
)
state$bData <- bData(state$data$directs, state$inputSM, state$inputRef)
print("bData calculated")
print(state$bData)
})
# NMA completion status
observeEvent(state$nmaDone, {
validate(need(state$bData !="", "bData not ready"),
need(state$nmaDone, "nma not started"))
print("starting bnma")
state$bnma <- bnma(state$inputSM, state$bData, state$inputRef, state$inputMod)
state$bnmaDone <- TRUE
print("bnma done")
# calculate data for Bayesian NMR
print("Calculating pooled variance")
bnmrData <- pool_variances(state$nma, directs())
print(head(bnmrData))
if(state$inputSM == "SMD"){
state$nmrData <- makeJagsNMAdata(id, n=n, y=mean, sd=sd, t=t, data=bnmrData, reference = state$inputRef, othervar = pooled_var)
state$nmrData$orig <- state$nmrData$variab
state$nmrData$variab <- state$nmrData$orig - min(state$nmrData$orig)
} else {
state$nmrData <- data.prep(arm.data = bnmrData, varname.t = "t", varname.s = "id")
}
print("calculated nmrData")
}, ignoreNULL = TRUE, ignoreInit = TRUE)
# Bayesian NMA completion status
observeEvent(state$bnmaDone, {
validate(need(state$bnmaDone, "bnma not ready"),
need(state$nmrData != "", "nmrData not ready"))
print("calculating bnma league")
larger_better <- ifelse(input$inputBH == "good", FALSE, TRUE)
if (state$inputSM=="SMD") {
league <- outJagsNMAmedian(state$bnma, parameter = "SMD", treatnames = state$treatments)$leaguetable
colnames(league) <- state$treatments
rownames(league) <- state$treatments
state$bleague <- league
} else {
state$bleague <- BUGSnet::nma.league(state$bnma,
central.tdcy = "median",
order = nma.rank(state$bnma, largerbetter = larger_better)$order,
log.scale = FALSE)$table
}
print(state$bleague)
print(state$nmrData)
#output$league <- renderTable({ state$bleague })
# start Bayesian NMR
if (state$inputSM == "OR" | state$inputSM == "RR") {
model <- BUGSnet::nma.model(data=state$nmrData,
outcome="r",
N="n",
reference=input$inputRef,
family="binomial",
link=ifelse(state$inputSM=="OR","logit", "log"),
effects= input$inputMod,
covariate = "pooled_var",
prior.beta = input$inputBeta)
state$bnmr <- BUGSnet::nma.run(model,
n.burnin = state$burnIn,
n.iter = state$numIter,
thin = state$thin,
n.chains = 2,
DIC = F)
state$bnmrDone <- TRUE
} else if (state$inputSM == "SMD") {
# The model file used here is loaded directly from the `NMAJags` library or sourced from the directory (for modelNMRContinuous_bExch)
print("inputSM else")
if (input$inputBeta=="UNRELATED") {
state$bnmr <- jags(data = state$nmrData, inits = NULL,
parameters.to.save = c("SMD", "SMD.ref", "b", "tau"), n.chains = 2,
n.iter = state$numIter, n.burnin = state$burnIn,
DIC=F, n.thin=state$thin, model.file = modelNMRContinuous)
} else {
state$bnmr <- jags(data = state$nmrData, inits = NULL,
parameters.to.save = c("SMD", "SMD.ref", "B", "tau"), n.chains = 2,
n.iter = state$numIter, n.burnin = state$burnIn,
DIC=F, n.thin=state$thin, model.file = modelNMRContinuous_bExch)
}
state$bnmrDone <- TRUE
} else if (state$inputSM== "MD") {
model <- BUGSnet::nma.model(data=state$nmrData,
outcome="mean",
sd="sd",
N="n",
reference=input$inputRef,
family="normal",
link="identity",
effects= input$inputMod,
covariate = "pooled_var",
prior.beta = input$inputBeta)
state$bnmr <- BUGSnet::nma.run(model,
DIC=F,
n.burnin = state$burnIn,
n.iter = state$numIter,
thin = state$thin,
n.chains = 2)
state$bnmrDone <- TRUE
}
print("bnmr is Done")
# AH: this output must be inside an observer, as it uses a reactive value (inputBeta)
output$coefficients <- renderTable({
#coef <- NULL
if (state$inputBeta == "UNRELATED") {
if (state$inputSM== "SMD") {
print(state$bnmr$BUGSoutput$summary[grep("b", rownames(state$bnmr$BUGSoutput$summary)),"mean"])
coef <- state$bnmr$BUGSoutput$summary[grep("b", rownames(state$bnmr$BUGSoutput$summary)),"mean"]
} else {
c1 <- state$bnmr$samples[1][[1]][,grep("beta",colnames(state$bnmr$samples[1][[1]]))]
c2 <- state$bnmr$samples[2][[1]][,grep("beta",colnames(state$bnmr$samples[2][[1]]))]
coef <- colMeans(rbind(c1, c2))
}
coef
}
}, rownames = T, colnames = F)
output$coefficientMean <- renderText({
if (state$inputBeta == "EXCHANGEABLE") {
if (state$inputSM== "SMD") {
print(state$bnmr$BUGSoutput$summary[grep("B", rownames(state$bnmr$BUGSoutput$summary)),"mean"])
coef <- round(state$bnmr$BUGSoutput$mean$B, digits=3)
} else {
c1 <- state$bnmr$samples[1][[1]][,grep("beta",colnames(state$bnmr$samples[1][[1]]))]
c2 <- state$bnmr$samples[2][[1]][,grep("beta",colnames(state$bnmr$samples[2][[1]]))]
coef <- round(mean(rbind(c1, c2), digits=3))
}
coef
}
})
# build pairwise comparison table
state$pairwiseTable <- build_pairwise_table(state$treatments, state$data$directs, state$data$otherOutcomes, state$data$isBinary)
# create funnel plots
state$hasFunnels <- !is.null(fp())
}, ignoreNULL = TRUE, ignoreInit = TRUE)
# Bayesian NMR completion status
observeEvent(state$bnmrDone, {
validate(need(state$analysisStarted, "Analysis not started"),
need(state$bnmrDone, "bnmr not Done"))
# calculate contribution matrix
print("calculating contribution")
cm <- netcontrib(state$nma, state$inputMod)
#print(attributes(cm))
state$contributionMatrix <- round(cm, digits = 1) %>%
mutate(comparison=rownames(cm)) %>%
relocate(comparison)
print("calculated contribution matrix")
output$contributionMatrix <- shiny::renderTable(state$contributionMatrix, digits=1)
## calculate NMR league table
print("Calculating NMR league table")
#print(head(state$nmrData))
larger_better <- ifelse(input$inputBH == "good", FALSE, TRUE)
if (state$inputSM == "SMD") {
nmrLeague <- outJagsNMAmedian(state$bnmr, parameter = "SMD", treatnames = state$treatments)$leaguetable
colnames(nmrLeague) <- state$treatments
rownames(nmrLeague) <- state$treatments
} else {
cov_value <- min(state$nmrData$arm.data$pooled_var)
rank <- nma.rank(state$bnmr, largerbetter = larger_better, cov.value = cov_value)
nmrLeague <- BUGSnet::nma.league(state$bnmr,
central.tdcy = "median",
order = rank$order,
log.scale = FALSE,
cov.value = cov_value)$table
}
state$nmrLeague <- nmrLeague
output$nmr <- renderTable({
state$nmrLeague
}, rownames = TRUE)
}, ignoreInit = TRUE, ignoreNULL = T)
# Observers for pairwise table -----------------------------------------------
observeEvent(input$setNoBiasWithin, {
print("Setting within-study assessment as no bias")
state$pairwiseTable <- mutate(state$pairwiseTable, known_unknowns = 1)
# calculate the overall judgement according to known_unknowns and unknown_unknowns
state$pairwiseTable <- state$pairwiseTable %>%
mutate(overall_bias = proposed) %>%
mutate(proposed = mapply(proposeOverallJudgement, known_unknowns, unknown_unknowns))
})
observeEvent(input$setNoBiasAcross, {
print("Setting across-study assessment as no bias")
state$pairwiseTable <- mutate(state$pairwiseTable, unknown_unknowns = 1)
# calculate the overall judgement according to known_unknowns and unknown_unknowns
state$pairwiseTable <- state$pairwiseTable %>%
mutate(overall_bias = proposed) %>%
mutate(proposed = mapply(proposeOverallJudgement, known_unknowns, unknown_unknowns))
})
observeEvent(input$calculateOverallJudgement, {
print("Applying proposed to overall")
state$pairwiseTable <- state$pairwiseTable %>%
mutate(overall_bias = proposed) %>%
mutate(proposed = mapply(proposeOverallJudgement, known_unknowns, unknown_unknowns))
# AH: we only calculate the bias contributions when the calculate button is
# clicked because it is an expensive operation
print("Rebuilding RoB table")
state$robTable <- rebuildRobTable(state$pairwiseTable,
state$contributionMatrix,
state$bleague,
state$nmrLeague,
state$robTable)
})
observeEvent(input$pairwiseSelect, {
selected <- input$pairwiseSelect
sel <- unlist(strsplit(selected$id,"-vs-",fixed = TRUE))
icolumn <- sel[[1]]
icomparison <- sel[[2]]
chr <- state$pairwiseTable %>%
filter(make.names(comparison) == icomparison) %>%
mutate("{icolumn}" := as.integer(selected$value)) %>%
mutate(proposed = mapply(proposeOverallJudgement, known_unknowns, unknown_unknowns))
state$pairwiseTable <- rows_update(state$pairwiseTable, chr)
})
# observer to construct RoB table when all other tables exist
observe({
validate(need(state$analysisStarted, "Analysis in progress..."),
need(nrow(state$pairwiseTable) > "0", "pairwise comparison table not ready"),
need(state$contributionMatrix != "", "contribution matrix not ready"),
need(state$nmrLeague != "", "NMR league table not ready"))
isolate({
if (nrow(state$robTable) == 0) {
print(c("building not rebuilding",state$state2))
state$robTable <- buildRobTable(state$pairwiseTable, state$contributionMatrix, state$bleague, state$nmrLeague)
}
})
})
# Observers for RoB table ----------------------------------------------------
observeEvent(input$setSSEUndetected, {
print("Setting SSE to No bias detected")
state$robTable <- mutate(state$robTable, effectsEvaluation = 1)
state$robTable$proposedOverall <- ProposeOverallRob(state$robTable)
})
observeEvent(input$setNoContribution, {
print("Setting Evaluation of contribution to No contribution")
state$robTable <- mutate(state$robTable, contrEvaluation = 1)
state$robTable$proposedOverall <- ProposeOverallRob(state$robTable)
})
observeEvent(input$applyProposedRobTable, {
print("Applying proposed to Final")
state$robTable <- mutate(state$robTable, final = proposedOverall)
})
observeEvent(input$contrEval, {
selected <- input$contrEval
sel <- unlist(strsplit(selected$id, "-vs-", fixed = TRUE))
icomparison <- sel[[2]]
chr <- filter(state$robTable, icomparison == make.names(comparison)) %>%
mutate(contrEvaluation = as.integer(selected$value))
state$robTable <- rows_update(state$robTable, chr)
state$robTable$proposedOverall <- ProposeOverallRob(state$robTable)
}, ignoreNULL = TRUE, ignoreInit = TRUE)
observeEvent(input$studyEffects, {
selected <- input$studyEffects
sel <- unlist(strsplit(selected$id,"-vs-", fixed = TRUE))
icomparison <- sel[[2]]
chr <- filter(state$robTable, icomparison == make.names(comparison)) %>%
mutate(effectsEvaluation = as.integer(selected$value))
state$robTable <- rows_update(state$robTable, chr)
state$robTable$proposedOverall <- ProposeOverallRob(state$robTable)
}, ignoreNULL = TRUE, ignoreInit = TRUE)
observeEvent(input$overallRob, {
selected <- input$overallRob
sel <- unlist(strsplit(selected$id ,"-vs-", fixed = TRUE))
icomparison <- sel[[2]]
chr <- filter(state$robTable, icomparison == make.names(comparison)) %>%
mutate(final = as.integer(selected$value))
print(chr)
state$robTable <- rows_update(state$robTable, chr)
}, ignoreNULL = TRUE, ignoreInit = TRUE)
#-------------------------------------------------------------------------------
# Load tab UI components
#-------------------------------------------------------------------------------
output$contents <- DT::renderDataTable({ DT::datatable(dataset()) })
output$tabLoad <- renderUI({
fluidPage(theme = bs_theme(version = 4),
sidebarLayout(
sidebarPanel(
fileInput("file", "Upload data file",
accept = c("text/csv",
"text/comma-separated-values,text/plain",
".csv")),
width = 2),
mainPanel(
DT::dataTableOutput("contents"),
width = 10)
)
)
})
#-----------------------------------------------------------------------------
# Analysis tab UI components
#-----------------------------------------------------------------------------
output$smOptions <- renderUI({
chs <- state$inputSM
if (state$data$isBinary) {
if (!state$analysisStarted) {
chs <- c("Odds Ratio" = "OR", "Risk Ratio" = "RR")
}
} else {
if (!state$analysisStarted) {
chs <- c("Standardized mean difference" = "SMD",
"Mean difference" = "MD")
}
}
radioButtons(inputId = "inputSM",
label = "Summary measure",
choices = chs,
selected = state$inputSM)
})
output$bhOptions <- renderUI({
if (!state$analysisStarted) {
chs = c("Desirable" = "good", "Undesirable" = "bad")
} else {
if (state$inputBH == "good") {
chs = c("Desirable" = "good")
} else {
chs = c("Undesirable" = "bad")
}
}
radioButtons(inputId = "inputBH",
label = "Smaller outcome values are",
selected = state$inputBH,
choices = chs)
})
output$ModelOptions <- renderUI({
if (!state$analysisStarted){
chs = c("Random effects" = "random", "Common effects" = "fixed")
} else {
if (state$inputMod == "fixed") {
chs = c("Common effects" = "fixed")
} else {
chs = c("Random effects" = "random")
}
}
radioButtons(inputId = "inputMod",
label = "Synthesis model",
selected = state$inputMod,
choices = chs)
})
output$ref <- renderUI({
if (!state$analysisStarted) {
chs <- state$treatments
} else {
chs <- state$inputRef
}
radioButtons(inputId = "inputRef",
label = "Reference treatment",
selected = state$inputRef,
choices = chs)
})
output$bugsnetOptions <- renderUI({
if (!state$analysisStarted) {
bin <- state$burnIn
iter <- state$numIter
nt <- state$thin
tags$div(
numericInput(
inputId = "burnIn",
label = "Burn In",
value = bin,
min = (0.1 * state$numIter),
max = NA,
step = NA,
width = NULL
),
numericInput(
inputId = "numIter",
label = "Iterations",
value = iter,
min = 10000,
max = NA,
step = 10,
width = NULL
),
numericInput(
inputId = "thin",
label = "Thinning factor",
value = nt,
min = 1,
max = NA,
step = 1,
width = NULL
)
)
} else {
tags$div(
tags$div(class = "control-label", "Burn In"),
tags$p(state$burnIn),
tags$div(class = "control-label", "Iterations"),
tags$p(state$numIter),
tags$div(class = "control-label", "Thinning factor"),
tags$p(state$thin)
)
}
})
output$priorbeta <- renderUI({
if (!state$analysisStarted ){
chs <- c("Unrelated treatment-specific interactions" = "UNRELATED",
"Exchangeable/related treatment-specific interactions" = "EXCHANGEABLE")
} else {
if (state$inputBeta == "UNRELATED") {
chs <- c("Unrelated treatment-specific interactions" = "UNRELATED")
}else{
chs <- c("Exchangeable/related treatment-specific interactions" = "EXCHANGEABLE")
}
}
radioButtons(inputId = "inputBeta",
label = "Assumption for treatment-specific interactions",
selected = state$inputBeta,
choices = chs
)
})
output$args <- renderUI({
tags$div(
uiOutput("smOptions"),
# if(state$data$isBinary==F) {
# strong("NOTE: currently ROB-MEN cannot calculate standardised mean differences.", style = "color:blue")
# },
uiOutput("bhOptions"),
uiOutput("ModelOptions"),
uiOutput("ref"),
uiOutput("bugsnetOptions"),
uiOutput("priorbeta")
)
})
output$run <- reactive({
res <- ""
if (state$parametersSet & !state$analysisStarted) {
res <- paste0("<button class='btn btn-primary btn-block' ",
"onclick='startAnalysis()'>",
"<i class='fa-solid fa-play'></i> Start Analysis</button>")
} else {
res <- ""
}
return(res)
})
output$tabAnalysis <- renderUI({
if (!is.null(state$data$directs)) {
fluidPage(theme = bs_theme(version = 4),
sidebarLayout(
sidebarPanel(
uiOutput("args"),
uiOutput("run"),
width = 3
),
mainPanel(
uiOutput("mainAnalysis"),
width = 9
)
)
)
} else {
fluidPage(theme = bs_theme(version = 4), tags$h4("Dataset not present"))
}
})
output$mainAnalysis <- renderUI({
if (state$analysisStarted) {
tabsetPanel(
tabPanel("Data Summary",uiOutput("summary")),
tabPanel("Bayesian network meta-analysis", uiOutput("bayesianNMA")),
tabPanel("Bayesian network meta-regression", uiOutput("bayesianNMR")),
tabPanel("Funnel plots and test for small-study effects",
tabPanel("Contour-enhanced funnel plots",
uiOutput("funnelplots")
)
),
tabPanel("Contribution matrix", uiOutput("tabContributionMatrix"))
)
} else {
tagList(
conditionalPanel(condition = "!$('html').hasClass('shiny-busy')",
tags$h4("Analysis not started")),
conditionalPanel(condition = "$('html').hasClass('shiny-busy')",
tags$div(class = "loading", tags$img(src = "./loading.gif")))
)
}
})
output$summary <- renderUI({
validate(need(state$analysisStarted, "Analysis parameters not set"))
if (state$inputSM=="SMD") {
fluidPage(theme = bs_theme(version = 4),
h4("Network graph", align = "center"),
plotOutput("netgraph", width = "100%", height = "500px"),
tags$br(),
h6(paste("There are", state$nma$k, "studies reporting the outcome of interest.
Below are the total number of participants in each of the included interventions.")),
tableOutput("netchar")
)
}
else {
fluidPage(theme = bs_theme(version = 4),
h4("Network graph", align = "center"),
plotOutput("netgraph", width = "100%", height = "500px"),
tags$br(),
h4("Network characteristics", align = "left"),
tableOutput("netinfo"),
h4("Interventions characteristics", align = "left"),
tableOutput("intinfo"),
h4("Direct comparisons characteristics", align = "left"),
tableOutput("compinfo"))
}
})
output$netchar <- renderTable({
tapply(state$data$directs$n, state$data$directs$t, sum, na.rm=T)
}, colnames = FALSE, rownames = TRUE)
output$netgraph <- renderPlot({
netgraph(state$nma, col = "black", plastic=FALSE,
points = TRUE, col.points = "darkgreen", cex.points =10*sqrt(n.trts/max(n.trts)),
thickness="number.of.studies", lwd.max = 12, lwd.min = 1, multiarm=F)
})
output$netinfo <- renderTable({
btab()$network
}, colnames = FALSE)
output$intinfo <- renderTable({
out <- btab()$intervention
if (state$data$isBinary) {
colnames(out) <- c("Intervention","Total no. of studies", "Total no. of events",
"Total no. of patients","Min observed event rate", "Max observed event rate", "Average event rate")
} else {
colnames(out) <- c("Intervention","Total no. of studies", "Total no. of patients",
"Min outcome value","Max outcome value","Average outcome value")
}
out
})
output$compinfo <- renderTable({
if (state$data$isBinary) {
out <- btab()$comparison[,-5]
colnames(out) <- c("Comparison","Total no. of studies", "Total no. of patients","Total no. of events")
} else {
out <- btab()$comparison
colnames(out) <- c("Comparison","Total no. of studies", "Total no. of patients")
}
out
})
#-----------------------------------------------------------------------------
# Outputs for Bayesian NMA tab
#-----------------------------------------------------------------------------
output$plot_forest<- renderPlot({
if (state$inputSM!="SMD") {
BUGSnet::nma.forest(state$bnma, comparator = state$inputRef) +
ylab(paste(input$inputSM, "relative to", input$inputRef )) +
theme(axis.text = element_text(size=15))
}
})
output$tau <- renderText({
if (state$inputSM=="SMD") {
het <- round(state$bnma$BUGSoutput$mean$tau, 3)
}
else{
het <- round(mean(c(mean(state$bnma$samples[1][[1]][,"sigma"]), mean(state$bnma$samples[2][[1]][,"sigma"]))),3)
}
het
})
output$tab_league <- renderTable({
state$bleague
}, rownames = TRUE)
output$bayesianNMA <- renderUI({
validate(need(state$analysisStarted, "analysis not started"),
need(state$bnmaDone, "waiting for analysis"))
if (state$inputSM=="SMD") {
tags$div(
br(),
h6("The heterogeneity (tau) is estimated at ", textOutput("tau", inline = T), align = "center"),
br(),
h5("League table", align = "center"),
div(tableOutput("tab_league"), style = "font-size:80%", align = "center"),
p(paste(state$inputSM, "and 95% credible intervals of treatment in the row versus treatment in the column"), align = "center")
)
}
else {
tags$div(
h4("Posterior medians and 95% Cr.I.", align = "center"),
div(plotOutput("plot_forest", height = "500px", width = "800px"), align = "center"),
br(),
p("The heterogeneity (tau) is estimated at ", textOutput("tau", inline = T), align = "center"),
br(),
h5("League table", align = "center"),
div(tableOutput("tab_league"), style = "font-size:80%", align = "center"),
p(paste(state$inputSM, "and 95% credible intervals of treatment in the column versus treatment in the row"), align = "center")
)
}
})
#-----------------------------------------------------------------------------
# Outputs for Bayesian NMR tab
#-----------------------------------------------------------------------------
output$bayesianNMR <- renderUI({
validate(need(state$bnmrDone, "waiting for analysis"))
isolate({
if(state$inputSM=="SMD") {
tags$div (
h5("Checks for convergence of network meta-regression model", align = "center"),
p("Check the trace plots (download) and the Gelman-Rubin diagnostic values (table below) being close to 1 for convergence. If needed, increase number of iterations, burn-in and/or thinning factor, or change the assumption for treatment-specific interactions to 'Exchangeable' and rerun analysis"),
conditionalPanel(condition = "$('html').hasClass('shiny-busy')",
tags$div(class = "loading", tags$img(src = "./loading.gif"))),
div(tableOutput("rhat"), align= "center"),
downloadButton("downloadTrace", "Download Trace Plots as PDF", class = "btn-primary"),
h4("Network meta-regression for variance of the (linear) treatment effect", align = "center"),
p(ifelse(state$inputBeta=="UNRELATED", "Values of the coefficients (betas) in the regression model between relative treatment effects and study variance",
"The average value of the regression coefficients (betas) of the interaction between relative treatment effects and study variance is "),
textOutput("coefficientMean", inline = T), align="center"),
conditionalPanel(condition = "$('html').hasClass('shiny-busy')",
tags$div(class = "loading", tags$img(src = "./loading.gif"))),
div(tableOutput("coefficients"), align= "center"),
h5("League table", align = "center"),
p("League table showing results for the minimum observed variance of", textOutput("minvar", inline = T), align= "center"),
conditionalPanel(condition = "$('html').hasClass('shiny-busy')",
tags$div(class = "loading", tags$img(src = "./loading.gif"))),
div(tableOutput("nmr"), style = "font-size:80%", align = "center"),
p(paste(state$inputSM, "and 95% credible intervals of treatment in the row versus treatment in the column"), align = "center")
)
}
else {
tags$div (
h5("Checks for convergence of network meta-regression model", align = "center"),
p("Check the trace plots (download) and the Gelman-Rubin diagnostic values (table below) being close to 1 for convergence. If needed, increase number of iterations, burn-in and/or thinning factor, or change the assumption for treatment-specific interactions to 'Exchangeable' and rerun analysis"),
conditionalPanel(condition = "$('html').hasClass('shiny-busy')",
tags$div(class = "loading", tags$img(src = "./loading.gif"))),
div(tableOutput("rhat"), align= "center"),
downloadButton("downloadTrace", "Download Trace Plots as PDF", class = "btn-primary"),
h4("Network meta-regression for variance of the (linear) treatment effect", align = "center"),
p(ifelse(state$inputBeta=="UNRELATED", "Values of the coefficients (betas) in the regression model between relative treatment effects and study variance",
"The average value of the regression coefficients (betas) of the interaction between relative treatment effects and study variance is"),
textOutput("coefficientMean", inline = T), align="center"),
conditionalPanel(condition = "$('html').hasClass('shiny-busy')",
tags$div(class = "loading", tags$img(src = "./loading.gif"))),
div(tableOutput("coefficients"), align= "center"),
h6("Press the button below to download the network meta-regression plot as PDF."),
downloadButton("downloadNmr", "Download Regression Plot as PDF", class = "btn-primary"),
h5("League table", align = "center"),
p("League table showing results for the minimum observed variance of", textOutput("minvar", inline = T), align= "center"),
conditionalPanel(condition = "$('html').hasClass('shiny-busy')",
tags$div(class = "loading", tags$img(src = "./loading.gif"))),
div(tableOutput("nmr"), style = "font-size:80%", align = "center"),
p(paste(state$inputSM, "and 95% credible intervals of treatment in the column versus treatment in the row"), align = "center")
)
}
})
})
output$rhat <- renderTable({
if (state$inputSM=="SMD") {
nmaDiag <- state$bnmr$BUGSoutput$summary[grep("ref|tau", rownames(state$bnmr$BUGSoutput$summary)),"Rhat"]
print(nmaDiag)
}
else {
nmaDiag <- nma.diag(state$bnmr, plot_prompt = FALSE)
nmaDiag$gelman.rubin$psrf[, -2]
}
}, rownames = T, colnames = F)
output$downloadTrace <- downloadHandler(
filename = "traceplots.pdf",
content = function(file)
if (state$inputSM=="SMD") {
pdf(file)
R2jags::traceplot(state$bnmr, varname=c("SMD.ref","tau"), ask=FALSE)
dev.off()
} else {
pdf(file)
nma.diag(state$bnmr, plot_prompt = FALSE) # This has to be repeated on plot because the plots
dev.off() # are created as a side-effect.
},
contentType = 'pdf')
output$downloadNmr <- downloadHandler(
filename <- "nmrPlot.pdf",
content = function(file) {
plot <- nma.regplot(state$bnmr) +
xlab("Study variance of the (linear) treatment effect") +
ylab(paste("Treatment effect (linear scale) versus", input$inputRef))
ggsave(file, plot = plot, device = "pdf")
},
contentType = 'pdf')
output$minvar <- renderText({
if (state$inputSM=="SMD") {
minvar <- min(min(state$nmrData$orig))
} else {
minvar <- min(state$nmrData$arm.data$pooled_var)
}
minvar
})
#-----------------------------------------------------------------------------
# Outputs for funnel plots tab
#-----------------------------------------------------------------------------
output$funnelplots <- renderUI({
validate(need(state$nmaDone, "netmeta not ready"))
if (state$hasFunnels) {
fluidPage(theme = bs_theme(version = 4),
fluidRow(
# verbatimTextOutput("fpprint"),
dataTableOutput("fptable")),
hr(),
fluidRow(
tags$h6("Only some funnel plots are shown here. To view all plots, press the button below to download them as PDF."),
plotOutput("plot_funnel")
),
downloadButton("downloadFunnel", "Download funnel plots as PDF", class = "btn-primary")
)
} else {
tags$h6("All comparisons have fewer than 10 studies")
}
})
output$plot_funnel <- renderPlot({
validate(need(state$nmaDone, "netmeta not ready"))
par(mfrow=c(2,3))
fp()
})
fp <- function() {
nmafunnel(state$nma, small.values = state$inputBH)
}
output$fpprint <- renderPrint({
fp()
})
output$fptable <- DT::renderDataTable(fp()$tests)
output$downloadFunnel <- downloadHandler(
filename = "funnelPlots.pdf",
content = function(file) {
pdf(file)
fp()
dev.off()
},
contentType = "pdf")
#-----------------------------------------------------------------------------
# Outputs for contribution matrix tab
#-----------------------------------------------------------------------------
output$tabContributionMatrix <- renderUI({
validate(need(state$contributionMatrix != "", "contribution matrix not calculated"))
fluidPage(theme = bs_theme(version = 4),
tags$br(),
p("Each cell entry provides the percentage contribution that the direct comparison (column) makes to the calculation of the corresponding NMA relative treatment effect (row)."),
downloadButton("downloadContributionMatrix", "Download Contribution Matrix", class = "btn-primary"),
tags$br(),
tableOutput("contributionMatrix")
)
})
output$downloadContributionMatrix <- downloadHandler(
filename <- "contribution_matrix.csv",
content <- function(file) {
write.csv(state$contributonMatrix, file, row.names = FALSE)
}
)
#-------------------------------------------------------------------------------
# Output for pairwise comparison table
#-------------------------------------------------------------------------------
output$tabPairwise <- renderUI({
if (state$analysisStarted) {
fluidPage(theme = bs_theme(version = 4),
downloadButton("pairwiseTableDownload", "Download Pairwise Comparison Table", class = "btn-primary"),
tags$div(class = "with-overflow",
uiOutput("pairwiseTableHeader"),
DT::dataTableOutput("pairwiseTable"))
)
} else {
if (is.null(state$data$directs)) {
fluidPage(theme = bs_theme(version = 4), tags$h4("Dataset not present"))
} else {
fluidPage(theme = bs_theme(version = 4), tags$h4("Analysis not started"))
}
}
})
output$pairwiseTable <- DT::renderDataTable({
validate(need(state$nmaDone, "netmeta not ready"))
# format the HTML header for the table
pairwiseTableHeader <- htmltools::withTags(table(
class = 'display',
thead(
tr(
th(rowspan = 2, colspan = 1, ' '),
th(rowspan = 2, colspan = 1, 'Pairwise comparison'),
th(rowspan = 2, colspan = 1, 'group'),
th(rowspan = 1, colspan = 2, 'Number of studies in each comparison'),
th(rowspan = 2, colspan = 1, 'Within-study assessment of bias', br(),
actionButton("setNoBiasWithin", 'set all to "No bias"',
onclick = "Shiny.setInputValue(\'setNoBiasWithin\', this.id, {priority: \'event\'})",
class = "btn-secondary")),
th(rowspan = 2, colspan = 1, 'Across-study assessment of bias', br(),
actionButton("setNoBiasAcross", 'set all to "No bias"',
onclick = "Shiny.setInputValue(\'setNoBiasAcross\', this.id, {priority: \'event\'})",
class = "btn-secondary")),