forked from OHDSI/ShinyDeploy
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.R
356 lines (284 loc) · 12.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
# @file server.R
#
# Copyright 2018 Observational Health Data Sciences and Informatics
#
# This file is part of PatientLevelPrediction
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
library(shiny)
library(plotly)
library(shinycssloaders)
source("helpers.R")
source("plots.R")
server <- shiny::shinyServer(function(input, output, session) {
session$onSessionEnded(shiny::stopApp)
filterIndex <- shiny::reactive({getFilter(summaryTable,input)})
print(summaryTable)
# need to remove over columns:
output$summaryTable <- DT::renderDataTable(DT::datatable(summaryTable[filterIndex(),!colnames(summaryTable)%in%c('addExposureDaysToStart','addExposureDaysToEnd', 'plpResultLocation', 'plpResultLoad')],
rownames= FALSE, selection = 'single',
extensions = 'Buttons', options = list(
dom = 'Bfrtip', buttons = I('colvis')
),
container = htmltools::withTags(table(
class = 'display',
thead(
#tags$th(title=active_columns[i], colnames(data)[i])
tr(apply(data.frame(colnames=c('Dev', 'Val', 'T','O', 'Model',
'TAR start', 'TAR end', 'AUC', 'AUPRC',
'T Size', 'O Count', 'O Incidence (%)'),
labels=c('Database used to develop the model', 'Database used to evaluate model', 'Target population - the patients you want to predict risk for','Outcome - what you want to predict',
'Model type','Time-at-risk start day', 'Time-at-risk end day', 'Area under the reciever operating characteristics (test or validation)', 'Area under the precision recall curve (test or validation)',
'Target population size of test or validation set', 'Outcome count in test or validation set', 'Percentage of target population that have outcome during time-at-risk')), 1,
function(x) th(title=x[2], x[1])))
)
))
)
)
selectedRow <- shiny::reactive({
if(is.null(input$summaryTable_rows_selected[1])){
return(1)
}else{
return(input$summaryTable_rows_selected[1])
}
})
plpResult <- shiny::reactive({getPlpResult(result,validation,summaryTable, inputType,filterIndex(), selectedRow())})
# covariate table
output$modelView <- DT::renderDataTable(editCovariates(plpResult()$covariateSummary)$table,
colnames = editCovariates(plpResult()$covariateSummary)$colnames)
output$modelCovariateInfo <- DT::renderDataTable(data.frame(covariates = nrow(plpResult()$covariateSummary),
nonZeroCount = sum(plpResult()$covariateSummary$covariateValue!=0)))
# Downloadable csv of model ----
output$downloadData <- shiny::downloadHandler(
filename = function(){'model.csv'},
content = function(file) {
write.csv(plpResult()$covariateSummary[plpResult()$covariateSummary$covariateValue!=0,c('covariateName','covariateValue','CovariateCount','CovariateMeanWithOutcome','CovariateMeanWithNoOutcome' )]
, file, row.names = FALSE)
}
)
# input tables
output$modelTable <- DT::renderDataTable(formatModSettings(plpResult()$model$modelSettings ))
output$covariateTable <- DT::renderDataTable(formatCovSettings(plpResult()$model$metaData$call$covariateSettings))
output$populationTable <- DT::renderDataTable(formatPopSettings(plpResult()$model$populationSettings))
# prediction text
output$info <- shiny::renderText(paste0('Within ', summaryTable[filterIndex(),'T'][selectedRow()],
' predict who will develop ', summaryTable[filterIndex(),'O'][selectedRow()],
' during ',summaryTable[filterIndex(),'TAR start'][selectedRow()], ' day/s',
' after ', ifelse(summaryTable[filterIndex(),'addExposureDaysToStart'][selectedRow()]==0, ' cohort start ', ' cohort end '),
' and ', summaryTable[filterIndex(),'TAR end'][selectedRow()], ' day/s',
' after ', ifelse(summaryTable[filterIndex(),'addExposureDaysToEnd'][selectedRow()]==0, ' cohort start ', ' cohort end '))
)
# PLOTTING FUNCTION
plotters <- shiny::reactive({
eval <- plpResult()$performanceEvaluation
if(is.null(eval)){return(NULL)}
calPlot <- NULL
rocPlot <- NULL
prPlot <- NULL
f1Plot <- NULL
if(!is.null(eval)){
#intPlot <- plotShiny(eval, input$slider1) -- RMS
intPlot <- plotShiny(eval)
rocPlot <- intPlot$roc
prPlot <- intPlot$pr
f1Plot <- intPlot$f1score
list(rocPlot= rocPlot,
prPlot=prPlot, f1Plot=f1Plot)
}
})
performance <- shiny::reactive({
eval <- plpResult()$performanceEvaluation
if(is.null(eval)){
return(NULL)
} else {
intPlot <- getORC(eval, input$slider1)
threshold <- intPlot$threshold
prefthreshold <- intPlot$prefthreshold
TP <- intPlot$TP
FP <- intPlot$FP
TN <- intPlot$TN
FN <- intPlot$FN
}
twobytwo <- as.data.frame(matrix(c(FP,TP,TN,FN), byrow=T, ncol=2))
colnames(twobytwo) <- c('Ground Truth Negative','Ground Truth Positive')
rownames(twobytwo) <- c('Predicted Positive','Predicted Negative')
list(threshold = threshold,
prefthreshold = prefthreshold,
twobytwo = twobytwo,
Incidence = (TP+FN)/(TP+TN+FP+FN),
Threshold = threshold,
Sensitivity = TP/(TP+FN),
Specificity = TN/(TN+FP),
PPV = TP/(TP+FP),
NPV = TN/(TN+FN) )
})
# preference plot
output$prefdist <- shiny::renderPlot({
if(is.null(plpResult()$performanceEvaluation)){
return(NULL)
} else{
plotPreferencePDF(plpResult()$performanceEvaluation,
type=plpResult()$type ) #+
# ggplot2::geom_vline(xintercept=plotters()$prefthreshold) -- RMS
}
})
output$preddist <- shiny::renderPlot({
if(is.null(plpResult()$performanceEvaluation)){
return(NULL)
} else{
plotPredictedPDF(plpResult()$performanceEvaluation,
type=plpResult()$type ) # +
#ggplot2::geom_vline(xintercept=plotters()$threshold) -- RMS
}
})
output$box <- shiny::renderPlot({
if(is.null(plpResult()$performanceEvaluation)){
return(NULL)
} else{
plotPredictionDistribution(plpResult()$performanceEvaluation, type=plpResult()$type )
}
})
output$cal <- shiny::renderPlot({
if(is.null(plpResult()$performanceEvaluation)){
return(NULL)
} else{
plotSparseCalibration2(plpResult()$performanceEvaluation, type=plpResult()$type )
}
})
output$demo <- shiny::renderPlot({
if(is.null(plpResult()$performanceEvaluation)){
return(NULL)
} else{
tryCatch(plotDemographicSummary(plpResult()$performanceEvaluation,
type=plpResult()$type ),
error= function(cond){return(NULL)})
}
})
# Do the tables and plots:
output$performance <- shiny::renderTable(performance()$performance,
rownames = F, digits = 3)
output$twobytwo <- shiny::renderTable(performance()$twobytwo,
rownames = T, digits = 0)
output$threshold <- shiny::renderText(format(performance()$threshold,digits=5))
output$roc <- plotly::renderPlotly({
plotters()$rocPlot
})
output$pr <- plotly::renderPlotly({
plotters()$prPlot
})
output$f1 <- plotly::renderPlotly({
plotters()$f1Plot
})
# covariate model plots
covs <- shiny::reactive({
if(is.null(plpResult()$covariateSummary))
return(NULL)
plotCovariateSummary(formatCovariateTable(plpResult()$covariateSummary))
})
output$covariateSummaryBinary <- plotly::renderPlotly({ covs()$binary })
output$covariateSummaryMeasure <- plotly::renderPlotly({ covs()$meas })
# LOG
output$log <- shiny::renderText( paste(plpResult()$log, collapse="\n") )
# dashboard
output$performanceBoxIncidence <- shinydashboard::renderInfoBox({
shinydashboard::infoBox(
"Incidence", paste0(round(performance()$Incidence*100, digits=3),'%'), icon = shiny::icon("ambulance"),
color = "green"
)
})
output$performanceBoxThreshold <- shinydashboard::renderInfoBox({
shinydashboard::infoBox(
"Threshold", format((performance()$Threshold), scientific = F, digits=3), icon = shiny::icon("edit"),
color = "yellow"
)
})
output$performanceBoxPPV <- shinydashboard::renderInfoBox({
shinydashboard::infoBox(
"PPV", paste0(round(performance()$PPV*1000)/10, "%"), icon = shiny::icon("thumbs-up"),
color = "orange"
)
})
output$performanceBoxSpecificity <- shinydashboard::renderInfoBox({
shinydashboard::infoBox(
"Specificity", paste0(round(performance()$Specificity*1000)/10, "%"), icon = shiny::icon("bullseye"),
color = "purple"
)
})
output$performanceBoxSensitivity <- shinydashboard::renderInfoBox({
shinydashboard::infoBox(
"Sensitivity", paste0(round(performance()$Sensitivity*1000)/10, "%"), icon = shiny::icon("low-vision"),
color = "blue"
)
})
output$performanceBoxNPV <- shinydashboard::renderInfoBox({
shinydashboard::infoBox(
"NPV", paste0(round(performance()$NPV*1000)/10, "%"), icon = shiny::icon("minus-square"),
color = "black"
)
})
# HELPER INFO
showInfoBox <- function(title, htmlFileName) {
shiny::showModal(shiny::modalDialog(
title = title,
easyClose = TRUE,
footer = NULL,
size = "l",
shiny::HTML(readChar(htmlFileName, file.info(htmlFileName)$size) )
))
}
observeEvent(input$DescriptionInfo, {
showInfoBox("Description", "html/Description.html")
})
observeEvent(input$SummaryInfo, {
showInfoBox("Summary", "html/Summary.html")
})
observeEvent(input$PerformanceInfo, {
showInfoBox("Performance", "html/Performance.html")
})
observeEvent(input$ModelInfo, {
showInfoBox("Model", "html/Model.html")
})
observeEvent(input$LogInfo, {
showInfoBox("Log", "html/Log.html")
})
observeEvent(input$DataInfoInfo, {
showInfoBox("DataInfo", "html/DataInfo.html")
})
observeEvent(input$HelpInfo, {
showInfoBox("HelpInfo", "html/Help.html")
})
observeEvent(input$rocHelp, {
showInfoBox("ROC Help", "html/rocHelp.html")
})
observeEvent(input$prcHelp, {
showInfoBox("PRC Help", "html/prcHelp.html")
})
observeEvent(input$f1Help, {
showInfoBox("F1 Score Plot Help", "html/f1Help.html")
})
observeEvent(input$boxHelp, {
showInfoBox("Box Plot Help", "html/boxHelp.html")
})
observeEvent(input$predDistHelp, {
showInfoBox("Predicted Risk Distribution Help", "html/predDistHelp.html")
})
observeEvent(input$prefDistHelp, {
showInfoBox("Preference Score Distribution Help", "html/prefDistHelp.html")
})
observeEvent(input$calHelp, {
showInfoBox("Calibration Help", "html/calHelp.html")
})
observeEvent(input$demoHelp, {
showInfoBox("Demographic Help", "html/demoHelp.html")
})
})