forked from OHDSI/ShinyDeploy
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.R
572 lines (534 loc) · 22.5 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
library(shiny)
library(DT)
mainColumns <- c("description",
"databaseId",
"rr",
"ci95Lb",
"ci95Ub",
"p",
"calibratedRr",
"calibratedCi95Lb",
"calibratedCi95Ub",
"calibratedP")
mainColumnNames <- c("<span title=\"Analysis\">Analysis</span>",
"<span title=\"Data source\">Data source</span>",
"<span title=\"Hazard ratio (uncalibrated)\">HR</span>",
"<span title=\"Lower bound of the 95 percent confidence interval (uncalibrated)\">LB</span>",
"<span title=\"Upper bound of the 95 percent confidence interval (uncalibrated)\">UB</span>",
"<span title=\"Two-sided p-value (uncalibrated)\">P</span>",
"<span title=\"Hazard ratio (calibrated)\">Cal.HR</span>",
"<span title=\"Lower bound of the 95 percent confidence interval (calibrated)\">Cal.LB</span>",
"<span title=\"Upper bound of the 95 percent confidence interval (calibrated)\">Cal.UB</span>",
"<span title=\"Two-sided p-value (calibrated)\">Cal.P</span>")
shinyServer(function(input, output, session) {
connection <- DatabaseConnector::connect(connectionDetails)
session$onSessionEnded(function() {
writeLines("Closing connection")
DatabaseConnector::disconnect(connection)
})
observe({
indicationId <- input$indication
updateSelectInput(session = session,
inputId = "exposureGroup",
choices = unique(exposureGroups$exposureGroup[exposureGroups$indicationId == indicationId]))
})
observe({
indicationId <- input$indication
exposureGroup <- input$exposureGroup
includeCombis <- input$includeCombis
filteredExposures <- exposures[exposures$indicationId == indicationId, ]
if (!includeCombis) {
filteredExposures <- filteredExposures[filteredExposures$combi == 0, ]
}
# filteredOutcomes <- outcomes[outcomes$indicationId == indicationId, ]
filteredExposures <- filteredExposures[filteredExposures$exposureGroup == exposureGroup, ]
updateSelectInput(session = session,
inputId = "target",
choices = unique(filteredExposures$exposureName))
updateSelectInput(session = session,
inputId = "comparator",
choices = unique(filteredExposures$exposureName))
})
resultSubset <- reactive({
targetId <- unique(exposures$exposureId[exposures$exposureName == input$target &
exposures$exposureGroup == input$exposureGroup])
comparatorId <- unique(exposures$exposureId[exposures$exposureName == input$comparator &
exposures$exposureGroup == input$exposureGroup])
if (length(targetId) == 0 || length(comparatorId) == 0) {
return(NULL)
}
outcomeId <- unique(outcomes$outcomeId[outcomes$outcomeName == input$outcome])
analysisIds <- analyses$analysisId[analyses$description %in% input$analysis]
databaseIds <- input$database
if (length(analysisIds) == 0) {
analysisIds <- -1
}
if (length(databaseIds) == 0) {
databaseIds <- "none"
}
results <- getMainResults(connection = connection,
targetIds = targetId,
comparatorIds = comparatorId,
outcomeIds = outcomeId,
databaseIds = databaseIds,
analysisIds = analysisIds)
results <- merge(results, analyses)
return(results)
})
selectedRow <- reactive({
idx <- input$mainTable_rows_selected
if (is.null(idx)) {
return(NULL)
} else {
subset <- resultSubset()
if (nrow(subset) == 0) {
return(NULL)
}
row <- subset[idx, ]
row$psStrategy <- gsub("^PS ", "", gsub(", .*$", "", analyses$description[analyses$analysisId == row$analysisId]))
return(row)
}
})
output$rowIsSelected <- reactive({
return(!is.null(selectedRow()))
})
outputOptions(output, "rowIsSelected", suspendWhenHidden = FALSE)
output$isMetaAnalysis <- reactive({
row <- selectedRow()
isMetaAnalysis <- !is.null(row) && (row$databaseId %in% metaAnalysisDbIds)
if (isMetaAnalysis) {
hideTab("detailsTabsetPanel", "Attrition")
hideTab("detailsTabsetPanel", "Population characteristics")
# hideTab("detailsTabsetPanel", "Propensity scores")
# hideTab("detailsTabsetPanel", "Covariate balance")
hideTab("detailsTabsetPanel", "Kaplan-Meier")
showTab("detailsTabsetPanel", "Forest plot")
} else {
hideTab("detailsTabsetPanel", "Forest plot")
showTab("detailsTabsetPanel", "Attrition")
showTab("detailsTabsetPanel", "Population characteristics")
# showTab("detailsTabsetPanel", "Propensity scores")
# showTab("detailsTabsetPanel", "Covariate balance")
showTab("detailsTabsetPanel", "Kaplan-Meier")
}
return(isMetaAnalysis)
})
outputOptions(output, "isMetaAnalysis", suspendWhenHidden = FALSE)
balance <- reactive({
row <- selectedRow()
if (is.null(row)) {
return(NULL)
} else {
analysisId <- row$analysisId
if (analysisId %in% c(1, 3)) {
# Only computed balance for ITT windows
analysisId <- analysisId + 1
}
writeLines("Fetching covariate balance")
balance <- getCovariateBalance(connection = connection,
targetId = row$targetId ,
comparatorId = row$comparatorId,
databaseId = row$databaseId,
analysisId = analysisId)
return(balance)
}
})
output$mainTable <- renderDataTable({
table <- resultSubset()
if (is.null(table) || nrow(table) == 0) {
return(NULL)
}
# table <- merge(table, analyses)
table <- table[, mainColumns]
table$rr <- prettyHr(table$rr)
table$ci95Lb <- prettyHr(table$ci95Lb)
table$ci95Ub <- prettyHr(table$ci95Ub)
table$p <- prettyHr(table$p)
table$calibratedRr <- prettyHr(table$calibratedRr)
table$calibratedCi95Lb <- prettyHr(table$calibratedCi95Lb)
table$calibratedCi95Ub <- prettyHr(table$calibratedCi95Ub)
table$calibratedP <- prettyHr(table$calibratedP)
colnames(table) <- mainColumnNames
options = list(pageLength = 15,
searching = FALSE,
lengthChange = TRUE,
ordering = TRUE,
paging = TRUE)
selection = list(mode = "single", target = "row")
table <- datatable(table,
options = options,
selection = selection,
rownames = FALSE,
escape = FALSE,
class = "stripe nowrap compact")
return(table)
})
output$powerTableCaption <- renderUI({
row <- selectedRow()
if (!is.null(row)) {
text <- "<strong>Table 1a.</strong> Number of subjects, follow-up time (in years), number of outcome
events, and event incidence rate (IR) per 1,000 patient years (PY) in the target (<em>%s</em>) and
comparator (<em>%s</em>) group after %s, as well as the minimum detectable relative risk (MDRR).
Note that the IR does not account for any stratification."
return(HTML(sprintf(text, input$target, input$comparator, row$psStrategy)))
} else {
return(NULL)
}
})
output$powerTable <- renderTable({
row <- selectedRow()
if (is.null(row)) {
return(NULL)
} else {
if (row$databaseId %in% metaAnalysisDbIds) {
results <- getMainResults(connection = connection,
targetIds = row$targetId,
comparatorIds = row$comparatorId,
outcomeIds = row$outcomeId,
analysisIds = row$analysisId)
table <- preparePowerTable(results, analyses, showDatabaseId = TRUE)
table$description <- NULL
table$databaseId[table$databaseId == "Meta-analysis"] <- "Summary"
colnames(table) <- c("Source",
"Target subjects",
"Comparator subjects",
"Target years",
"Comparator years",
"Target events",
"Comparator events",
"Target IR (per 1,000 PY)",
"Comparator IR (per 1,000 PY)",
"MDRR")
# table$i2 <- c(rep("", nrow(table) - 1), sprintf("%.2f", as.numeric(row$i2)))
} else {
table <- preparePowerTable(row, analyses)
table$description <- NULL
colnames(table) <- c("Target subjects",
"Comparator subjects",
"Target years",
"Comparator years",
"Target events",
"Comparator events",
"Target IR (per 1,000 PY)",
"Comparator IR (per 1,000 PY)",
"MDRR")
}
return(table)
}
})
output$timeAtRiskTableCaption <- renderUI({
row <- selectedRow()
if (is.null(row)) {
return(NULL)
} else {
text <- "<strong>Table 1b.</strong> Time (days) at risk distribution expressed as
minimum (min), 25th percentile (P25), median, 75th percentile (P75), and maximum (max) in the target
(<em>%s</em>) and comparator (<em>%s</em>) cohort after %s."
return(HTML(sprintf(text, input$target, input$comparator, row$psStrategy)))
}
})
output$timeAtRiskTable <- renderTable({
row <- selectedRow()
if (is.null(row)) {
return(NULL)
} else {
followUpDist <- getCmFollowUpDist(connection = connection,
targetId = row$targetId,
comparatorId = row$comparatorId,
outcomeId = row$outcomeId,
databaseId = row$databaseId,
analysisId = row$analysisId)
table <- prepareFollowUpDistTable(followUpDist)
return(table)
}
})
output$attritionPlot <- renderPlot({
row <- selectedRow()
if (is.null(row)) {
return(NULL)
} else {
attrition <- getAttrition(connection = connection,
targetId = row$targetId,
comparatorId = row$comparatorId,
outcomeId = row$outcomeId,
databaseId = row$databaseId,
analysisId = row$analysisId)
plot <- drawAttritionDiagram(attrition)
return(plot)
}
})
output$attritionPlotCaption <- renderUI({
row <- selectedRow()
if (is.null(row)) {
return(NULL)
} else {
text <- "<strong>Figure 1.</strong> Attrition diagram, showing the Number of subjectsin the target (<em>%s</em>) and
comparator (<em>%s</em>) group after various stages in the analysis."
return(HTML(sprintf(text, input$target, input$comparator)))
}
})
output$table1Caption <- renderUI({
row <- selectedRow()
if (is.null(row)) {
return(NULL)
} else {
text <- "<strong>Table 2.</strong> Select characteristics before and after %s, showing the (weighted)
percentage of subjects with the characteristics in the target (<em>%s</em>) and comparator (<em>%s</em>) group, as
well as the standardized difference of the means."
return(HTML(sprintf(text, row$psStrategy, input$target, input$comparator)))
}
})
output$table1Table <- renderDataTable({
row <- selectedRow()
if (is.null(row)) {
return(NULL)
} else {
chars <- getCovariateBalance(connection = connection,
targetId = row$targetId,
comparatorId = row$comparatorId,
outcomeId = row$outcomeId,
databaseId = row$databaseId,
analysisId = row$analysisId)
table1 <- prepareTable1(balance = chars,
beforeLabel = paste("Before" , row$psStrategy),
afterLabel = paste("After" , row$psStrategy),
output = "html")
container <- htmltools::withTags(table(
class = 'display',
thead(
tr(
th(rowspan = 3, "Characteristic"),
th(colspan = 3, class = "dt-center", paste("Before", row$psStrategy)),
th(colspan = 3, class = "dt-center", paste("After", row$psStrategy))
),
tr(
lapply(table1[1, 2:ncol(table1)], th)
),
tr(
lapply(table1[2, 2:ncol(table1)], th)
)
)
))
options <- list(columnDefs = list(list(className = 'dt-right', targets = 1:6)),
searching = FALSE,
ordering = FALSE,
paging = FALSE,
bInfo = FALSE)
table1 <- datatable(table1[3:nrow(table1), ],
options = options,
rownames = FALSE,
escape = FALSE,
container = container,
class = "stripe nowrap compact")
return(table1)
}
})
output$psDistPlot <- renderPlot({
row <- selectedRow()
if (is.null(row)) {
return(NULL)
} else {
if (row$databaseId %in% metaAnalysisDbIds) {
ps <- getPs(connection = connection,
targetIds = row$targetId,
comparatorIds = row$comparatorId)
} else {
ps <- getPs(connection = connection,
targetIds = row$targetId,
comparatorIds = row$comparatorId,
databaseId = row$databaseId)
}
plot <- plotPs(ps, input$target, input$comparator)
return(plot)
}
})
output$balancePlot <- renderPlot({
bal <- balance()
if (is.null(bal)) {
return(NULL)
} else {
row <- selectedRow()
writeLines("Plotting covariate balance")
plot <- plotCovariateBalanceScatterPlot(balance = bal,
beforeLabel = paste("Before", row$psStrategy),
afterLabel = paste("After", row$psStrategy),
showCovariateCountLabel = TRUE,
showMaxLabel = TRUE)
return(plot)
}
})
output$balancePlotCaption <- renderUI({
bal <- balance()
if (is.null(bal)) {
return(NULL)
} else {
row <- selectedRow()
text <- "<strong>Figure 3.</strong> Covariate balance before and after %s. Each dot represents
the standardized difference of means for a single covariate before and after %s on the propensity
score. Move the mouse arrow over a dot for more details."
return(HTML(sprintf(text, row$psStrategy, row$psStrategy)))
}
})
output$hoverInfoBalanceScatter <- renderUI({
bal <- balance()
if (is.null(bal)) {
return(NULL)
} else {
row <- selectedRow()
hover <- input$plotHoverBalanceScatter
point <- nearPoints(bal, hover, threshold = 5, maxpoints = 1, addDist = TRUE)
if (nrow(point) == 0) {
return(NULL)
}
left_pct <- (hover$x - hover$domain$left) / (hover$domain$right - hover$domain$left)
top_pct <- (hover$domain$top - hover$y) / (hover$domain$top - hover$domain$bottom)
left_px <- hover$range$left + left_pct * (hover$range$right - hover$range$left)
top_px <- hover$range$top + top_pct * (hover$range$bottom - hover$range$top)
style <- paste0("position:absolute; z-index:100; background-color: rgba(245, 245, 245, 0.85); ",
"left:",
left_px - 251,
"px; top:",
top_px - 150,
"px; width:500px;")
beforeMatchingStdDiff <- formatC(point$beforeMatchingStdDiff, digits = 2, format = "f")
afterMatchingStdDiff <- formatC(point$afterMatchingStdDiff, digits = 2, format = "f")
div(
style = "position: relative; width: 0; height: 0",
wellPanel(
style = style,
p(HTML(paste0("<b> Covariate: </b>", point$covariateName, "<br/>",
"<b> Std. diff before ",tolower(row$psStrategy),": </b>", beforeMatchingStdDiff, "<br/>",
"<b> Std. diff after ",tolower(row$psStrategy),": </b>", afterMatchingStdDiff)))
)
)
}
})
output$systematicErrorPlot <- renderPlot({
row <- selectedRow()
if (is.null(row)) {
return(NULL)
} else {
controlResults <- getControlResults(connection = connection,
targetId = row$targetId,
comparatorId = row$comparatorId,
analysisId = row$analysisId,
databaseId = row$databaseId)
plot <- plotScatter(controlResults)
return(plot)
}
})
output$kaplanMeierPlot <- renderPlot({
row <- selectedRow()
if (is.null(row)) {
return(NULL)
} else {
km <- getKaplanMeier(connection = connection,
targetId = row$targetId,
comparatorId = row$comparatorId,
outcomeId = row$outcomeId,
databaseId = row$databaseId,
analysisId = row$analysisId)
plot <- plotKaplanMeier(kaplanMeier = km,
targetName = input$target,
comparatorName = input$comparator)
return(plot)
}
}, res = 100)
output$kaplanMeierPlotPlotCaption <- renderUI({
row <- selectedRow()
if (is.null(row)) {
return(NULL)
} else {
text <- "<strong>Figure 5.</strong> Kaplan Meier plot, showing survival as a function of time. This plot
is adjusted for the propensity score %s: The target curve (<em>%s</em>) shows the actual observed survival. The
comparator curve (<em>%s</em>) applies reweighting to approximate the counterfactual of what the target survival
would look like had the target cohort been exposed to the comparator instead. The shaded area denotes
the 95 percent confidence interval."
return(HTML(sprintf(text, row$psStrategy, input$target, input$comparator)))
}
})
output$subgroupTableCaption <- renderUI({
row <- selectedRow()
if (is.null(row)) {
return(NULL)
} else {
text <- "<strong>Table 4.</strong> Subgroup interactions. For each subgroup, the number of subject within the subroup
in the target (<em>%s</em>) and comparator (<em>%s</em>) cohorts are provided, as well as the hazard ratio ratio (HRR)
with 95 percent confidence interval and p-value (uncalibrated and calibrated) for interaction of the main effect with
the subgroup."
return(HTML(sprintf(text, input$target, input$comparator)))
}
})
output$forestPlot <- renderPlot({
row <- selectedRow()
if (is.null(row)) {
return(NULL)
} else {
results <- getMainResults(connection = connection,
targetIds = row$targetId,
comparatorIds = row$comparatorId,
outcomeIds = row$outcomeId,
analysisIds = row$analysisId)
plot <- plotForest(results)
return(plot)
}
})
output$forestPlotCaption <- renderUI({
row <- selectedRow()
if (is.null(row)) {
return(NULL)
} else {
text <- "<strong>Figure 6.</strong> Forest plot showing the per-database and summary hazard ratios (and 95 percent confidence
intervals) comparing %s to %s for the outcome of %s, using %s. Estimates are shown both before and after empirical
calibration. The I2 is computed on the uncalibrated estimates."
return(HTML(sprintf(text, input$target, input$comparator, input$outcome, row$psStrategy)))
}
})
output$balanceSummaryPlot <- renderPlot({
row <- selectedRow()
if (is.null(row)) {
return(NULL)
} else {
analysisId <- row$analysisId
if (analysisId %in% c(1, 3)) {
# Only computed balance for ITT windows
analysisId <- analysisId + 1
}
balanceSummary <- getCovariateBalanceSummary(connection = connection,
targetId = row$targetId,
comparatorId = row$comparatorId,
analysisId = analysisId)
plot <- plotCovariateBalanceSummary(balanceSummary,
threshold = 0.1,
beforeLabel = paste("Before", row$psStrategy),
afterLabel = paste("After", row$psStrategy))
return(plot)
}
}, res = 100)
output$balanceSummaryPlotCaption <- renderUI({
row <- selectedRow()
if (is.null(row)) {
return(NULL)
} else {
text <- "<strong>Figure 7.</strong> Covariate balance before and after %s. The y axis represents
the standardized difference of mean before and after %s on the propensity
score. The whiskers show the minimum and maximum values across covariates. The box represents the
interquartile range, and the middle line represents the median. The dashed lines indicate a standardized
difference of 0.1."
return(HTML(sprintf(text, row$psStrategy, row$psStrategy)))
}
})
output$systematicErrorSummaryPlot <- renderPlot({
row <- selectedRow()
if (is.null(row)) {
return(NULL)
} else {
negativeControls <- getNegativeControlEstimates(connection = connection,
targetId = row$targetId,
comparatorId = row$comparatorId,
analysisId = row$analysisId)
plot <- plotEmpiricalNulls(negativeControls)
return(plot)
}
}, res = 100)
})