a b/app.R
1
library(shiny)
2
library(shinydashboard)
3
library(plotly)
4
library(reshape2)
5
library(survminer)
6
library(survival)
7
library(data.table)
8
library(dplyr)
9
library(scales)
10
11
load("LungDemoData.Rdata")
12
load("Results.Rdata")
13
load("Means.Rdata")
14
15
ui <- dashboardPage(
16
  dashboardHeader(title = "Prognostic models in metastatic lung adenocarcinoma (BETA)",titleWidth = 400),
17
  
18
  dashboardSidebar(width = 200,
19
                   sidebarMenu(
20
                     menuItem("Dashboard", tabName = "fixed", icon = icon("bar-chart")),
21
                     menuItem("Risk Group Stratification", tabName = "strat", icon = icon("scissors")),
22
                     menuItem("Gene View", tabName = "gene", icon = icon("gears")),
23
                     menuItem("Patient View", tabName = "patient", icon = icon("user-circle-o")),
24
                     menuItem("Generate Risk Score", tabName = "risk", icon = icon("gears"))
25
                   )
26
  ),
27
  
28
  dashboardBody(
29
    tabItems(
30
      # First tab content
31
      tabItem(tabName = "fixed",
32
              sidebarLayout(
33
                sidebarPanel(
34
                  width=12,
35
                  h2("Prognostic Performance")
36
                  # selectInput("StudyName", "Choose a Study :", 
37
                  #             choices = c("Lung"
38
                  #             )),
39
                  # checkboxInput("AddCNV", "Include copy number data", FALSE),
40
                  # checkboxInput("OnlyCNV", "Consider only copy number data", FALSE),
41
                  # 
42
                  # selectInput("Method", "Choose a Method :", 
43
                  #             choices = c("Penalized regression"="LASSO")),
44
                  # submitButton("Submit")
45
                ),
46
                mainPanel(width=12,
47
                          #htmlOutput("VariableHeader"),
48
                          htmlOutput("RiskHeader"),
49
                          plotOutput("RiskHistogram"),
50
                          tableOutput("RiskSummary"),
51
                          htmlOutput("CIHeader"),
52
                          tableOutput("CI"),
53
                          htmlOutput("RefitHeader"),
54
                          tableOutput("RefitRisk"),
55
                          htmlOutput("CommentPval"),
56
                          tableOutput("ClinRefit")#,
57
                          #htmlOutput("EffectHeader"),
58
                          #htmlOutput("FreqHeader")#,
59
                          #plotOutput("influencePlot"),
60
                )
61
              )
62
      ),
63
      # First tab content
64
      tabItem(tabName = "strat",
65
              #
66
              #   sidebarPanel( width = 12,
67
              #     checkboxInput("ShowVolvano", "Show Volcano Plot", TRUE),
68
              #                 checkboxInput("ShowPies", "Show Pie Charts", TRUE),
69
              #                 submitButton("Submit")
70
              # ),
71
              sidebarLayout(
72
                sidebarPanel(width = 12,
73
                             h2("Risk Group Stratification")
74
                ),
75
                mainPanel(width = 12,
76
                          htmlOutput("predRiskText"),
77
                          htmlOutput("KMText"),
78
                          plotOutput("KM"),
79
                          tableOutput("SurvSum"),
80
                          htmlOutput("MutGroupText"),
81
                          htmlOutput("MutBPText"),
82
                          plotOutput("Mut")
83
                )
84
              )
85
      ),
86
      
87
      tabItem(tabName = "gene",
88
              h2("Exploratory interactive gene plots"),
89
              #   sidebarPanel( width = 12,
90
              #     checkboxInput("ShowVolvano", "Show Volcano Plot", TRUE),
91
              #                 checkboxInput("ShowPies", "Show Pie Charts", TRUE),
92
              #                 submitButton("Submit")
93
              # ),
94
              sidebarLayout(
95
                sidebarPanel(width = 12,
96
                             textInput("GeneListRisk", 
97
                                       "Find gene(s) : ",
98
                                       value = ""),
99
                             submitButton("Submit")),
100
                mainPanel(
101
                  htmlOutput("VolcanoHeader"),width = 12,
102
                  plotlyOutput("effectPlot"),
103
                  htmlOutput("profiletext"),
104
                  plotlyOutput("ProfilePie")#, width="800px", height="400px")
105
                )
106
              )
107
      ),
108
      
109
      tabItem(tabName = "patient",
110
              h2("Predicting survival for an incoming patient"),
111
              sidebarLayout(
112
                sidebarPanel(width = 12,
113
                             textInput("GeneList", 
114
                                       "Names of the genes you wish to use to create predictive risk : example STK11,KEAP1,KRAS",
115
                                       value = ""),
116
                             ##### FOR LUNG ONLY #####
117
                             checkboxGroupInput(inputId = "Demographics", label = "Choose demographic variables :",
118
                                                choices = c("Male" = "Sex",
119
                                                            "Smoker" = "Smoker",
120
                                                            "Age > 65" = "Age"),
121
                                                inline = TRUE),
122
                             submitButton("Submit")
123
                ),
124
                mainPanel(width = 12,
125
                          htmlOutput("predtext"),
126
                          plotlyOutput("IndSurvKM"),
127
                          tableOutput("IndPredTable")
128
                )
129
              )
130
      ),
131
      tabItem(tabName = "risk",
132
              h2("Generate risk score in a new cohort"),
133
              #   sidebarPanel( width = 12,
134
              #     checkboxInput("ShowVolvano", "Show Volcano Plot", TRUE),
135
              #                 checkboxInput("ShowPies", "Show Pie Charts", TRUE),
136
              #                 submitButton("Submit")
137
              # ),
138
              sidebarLayout(
139
                sidebarPanel(width = 12,
140
                             fileInput(inputId = "File1", label = "Choose your dataset (.csv file)",
141
                                       accept = c(".csv")
142
                                       
143
                             )#,
144
                             # textInput("OutName", 
145
                             #           "Name or the output risk file :",
146
                             #           value = "")#,
147
                             #submitButton("Submit")
148
                ),
149
                mainPanel(
150
                  width = 12,
151
                  plotOutput("RiskHistogram.new"),
152
                  downloadLink("downloadData", "Download")
153
                )
154
              )
155
      )
156
      
157
    )
158
  )
159
)
160
161
162
163
164
# Define server logic required to draw a histogram
165
server <- function(input, output) {
166
  
167
  # load functions of interest
168
  source("./Scripts/GetResultsVarSelect.R")
169
  source("./Scripts/MakeKM.R")
170
  source("./Scripts/GetKMStuff.R")
171
  # source("./Scripts/PlotTree.R")
172
  source("./Scripts/PredictIncoming.R")
173
  
174
  # load("FirstRun.Rdata")
175
  # load("RiskGroupsResults.Rdata")
176
  
177
  output$VariableHeader <- renderText({ paste("<h3> <u> <font color=\"black\"><b>","Prognostic performance", "</b></font> </u> </h3>") })
178
  output$RiskHeader <- renderText({paste("<h4> <u> <font color=\"black\"><b>","Histogram of predicted risk score", "</b></font> </u> </h4>")})
179
  output$CIHeader <- renderText({paste("<h4> <u> <font color=\"black\"><b>","Concordance index in predicting overall survival", "</b></font> </u> </h4>")})
180
  output$RefitHeader <- renderText({paste("<h4> <u> <font color=\"black\"><b>","Cox regression estimates and significance P-values", "</b></font> </u> </h4>")})
181
  output$EffectHeader <- renderText({ paste("<h3> <u> <font color=\"black\"><b>","Individual gene effect size and relative importance", "</b></font> </u> </h3>") })
182
  output$FreqHeader <- renderText({paste("<h4> <u> <font color=\"black\"><b>","Gene selection frequency", "</b></font> </u> </h4>")})
183
  output$VolcanoHeader <- renderText({paste("<h4> <u> <font color=\"black\"><b>","Interactive Volcano plot", "</b></font> </u> </h4>")})
184
  output$CommentPval <- renderText({paste("<font color=\"black\">","*Note that the pvalue is 0 here because it goes beyond the precision of the machine.", "</font>")})
185
  
186
  output$RiskHistogram <- renderPlot({FirstRun$RiskHistogram})
187
  output$RiskSummary <- renderTable({FirstRun$RiskScoreSummary}, rownames = TRUE)
188
  output$CI <- renderTable({FirstRun$ciSummary}, rownames = TRUE)
189
  output$RefitRisk <- renderTable({FirstRun$RiskRefit}, rownames = TRUE)
190
  output$ClinRefit <- renderTable({FirstRun$ClinRefitTable}, rownames = TRUE)
191
  output$influencePlot <- renderPlot({FirstRun$inflPlot})
192
  
193
  output$predRiskText <- renderText({ paste("<h3> <u> <font color=\"black\"><b>","Risk group stratification", "</b></font> </u> </h3>") })
194
  GetResultsReactive <- reactive({getResults(studyType = "Lung",
195
                                             method="LASSO",
196
                                             geneList = unlist(strsplit(input$GeneListRisk, split ="," )))})
197
  
198
  output$effectPlot <- renderPlotly({GetResultsReactive()$selectInflPlot})
199
  #output$effectPlot <- renderPlotly({FirstRun$selectInflPlot})
200
  
201
  
202
  KMStuffReactive <- reactive({
203
    KMStuff(FirstRun$data.out,FirstRun$average.risk,
204
            FirstRun$topHits,4,
205
            c(0.25,0.75,0.9),
206
            geneList=unlist(strsplit(input$GeneListRisk, split ="," )))
207
  })
208
  output$KMText <- renderText({ paste("<h4> <u> <font color=\"black\"><b>","Kaplan-Meier plot of overall survival", "</b></font> </u> </h4>") })
209
  
210
  output$KM <- renderPlot(FirstRun$KM_Plot)
211
  output$SurvSum <- renderTable(FirstRun$SurvSum,rownames = TRUE)
212
  
213
  output$MutGroupText <- renderText({ paste("<h3> <u> <font color=\"black\"><b>","Mutation profiles by risk groups", "</b></font> </u> </h3>") })
214
  output$MutBPText <- renderText({ paste("<h4> <u> <font color=\"black\"><b>","Barplot of mutation frequency", "</b></font> </u> </h4>") })
215
  
216
  output$Mut <- renderPlot({
217
    print(FirstRun$mut_Plot)})
218
  
219
  ## Tab 2
220
  output$profiletext <- renderText({ paste("<h4> <u> <font color=\"black\"><b>","Piechart of most representative mutation profiles : ",
221
                                           KMStuffReactive()$GenesUsed, "</b></font> </u> </h4>") })
222
  output$ProfilePie <- renderPlotly({
223
    KMStuffReactive()$PieChart
224
  })
225
  
226
  
227
  makePredictionsReactive <- reactive({
228
    predictIncomingPatient(mutGenes = unlist(strsplit(input$GeneList, split =",")),
229
                           clinical=c(input$Demographics),
230
                           ClinRefit=FirstRun$ClinRefit,
231
                           time.type=FirstRun$time.type,
232
                           MD=FirstRun$MD,
233
                           LassoFits=FirstRun$LassoFits,
234
                           RiskScore=FirstRun$average.risk,
235
                           means.train=means.train)
236
  })
237
  
238
  output$IndSurvKM <- renderPlotly({makePredictionsReactive()$IndSurvKM})
239
  output$IndPredTable <- renderTable({makePredictionsReactive()$IndPredTable},rownames = TRUE)
240
  #output$IndSurvKM <- renderPlotly({FirstRun$IndSurvKM})
241
  # output$IndPredTable <- renderTable({FirstRun$IndPredTable},rownames = TRUE) 
242
  
243
  
244
  ### GENERATING THE RISK SCORE FOR NEW DATA ###
245
  
246
  ### GENERATING THE RISK SCORE FOR NEW DATA ###
247
  
248
  dset <- reactive({
249
    inFile <- input$File1
250
    if(is.null(inFile)) return(NULL)
251
    
252
    LassoFits <- as.matrix(Results$LassoFits)
253
    ori.risk <- Results$ori.risk
254
    
255
    file.rename(inFile$datapath, paste0(inFile$datapath, ".csv"))
256
    in.data <- read.csv(paste0(inFile$datapath, ".csv"), header = T,row.names = 1)
257
    
258
    features <- colnames(LassoFits)
259
    features[match(c("alk","ros1","ret"),features)] <- paste0(features[match(c("alk","ros1","ret"),features)],".fusion")
260
    colnames(LassoFits)[match(c("alk","ros1","ret"),colnames(LassoFits))] <- paste0(colnames(LassoFits)[match(c("alk","ros1","ret"),colnames(LassoFits))],".fusion")
261
    
262
    # in.data <- as.data.frame(matrix(rbinom(1100,1,prob=0.5),ncol =11))
263
    # colnames(in.data) <- c("KEAP1","STK11","TP53","EGFR","KRAS","SMARCA4","alk","ros1","BRCA1","AXIN1","noNameTest")
264
    
265
    if(!all(is.na(match(colnames(in.data),features)))){
266
      matched.genes <- c(na.omit(match(colnames(in.data),features)))
267
      new.dat <- in.data[,which(!is.na(match(colnames(in.data),features)))]
268
      
269
      ## ADD ALL MISSING GENES TO BE ALL zero ##
270
      missing <- features[which(is.na(match(features,colnames(new.dat))))]
271
      to.add <- as.data.frame(matrix(0L,nrow=nrow(new.dat),ncol=length(missing)))
272
      colnames(to.add) <- missing
273
      rownames(to.add) <- rownames(new.dat)
274
      new.dat <- as.data.frame(cbind(new.dat,to.add))
275
      
276
      new.dat <- new.dat[,match(features,colnames(new.dat))]
277
      
278
      #############################################
279
      
280
      all.pred <- lapply(1:nrow(LassoFits),function(x){
281
        
282
        ### Subset to the coefs of that cv ###
283
        coefs <- LassoFits[x,LassoFits[x,] != 0]
284
        new.temp <- select(new.dat,names(coefs))
285
        
286
        if(!all(is.na(match(c("alk","ros1","ret"),names(means.train[[x]]))))){
287
          names(means.train[[x]])[na.omit(match(c("alk","ros1","ret"),names(means.train[[x]])))] <- 
288
            paste0(names(means.train[[x]])[na.omit(match(c("alk","ros1","ret"),names(means.train[[x]])))],".fusion")
289
        }
290
        ## substract mean mutation rate of TRAINING SET !!!###
291
        new.x <- new.temp - rep(means.train[[x]][match(names(coefs),names(means.train[[x]]))], each = nrow(new.temp))
292
        cal.risk.test <- drop(as.matrix(new.x) %*% coefs)
293
        return(cal.risk.test)
294
      })
295
      
296
      all.pred <- do.call("cbind",all.pred)
297
      Risk <- apply(all.pred,1,mean)
298
      names(Risk) <- rownames(new.dat)
299
      # Risk.all <- as.matrix(coefs) %*% as.matrix(t(new.dat))
300
      # Risk <- apply(Risk.all,2,mean)
301
      #in.data$Risk <- Risk
302
      ##########################################
303
      ori.risk.range <- range(ori.risk)
304
      in.data$OncoCastRiskScore <- rescale(Risk, to = c(0, 10), from = ori.risk.range) #WithOriginal
305
      #in.data$rescaledRisk <- rescale(in.data$Risk, to = c(0, 10), from = range(in.data$Risk, na.rm = TRUE, finite = TRUE))
306
      RiskHistogram.new <- ggplot(in.data, aes(x = OncoCastRiskScore, y = ..density..)) +
307
        geom_histogram(show.legend = FALSE, aes(fill=..x..),
308
                       breaks=seq(min(in.data$OncoCastRiskScore,na.rm = T), max(in.data$OncoCastRiskScore,na.rm = T), by=20/nrow(in.data))) +
309
        geom_density(show.legend = FALSE) +
310
        theme_minimal() +
311
        labs(x = "Average risk score", y = "Density") +
312
        scale_fill_gradient(high = "red", low = "green")
313
      
314
      return(list("RiskHistogram.new"=RiskHistogram.new,"out.data"=in.data))
315
      
316
    }
317
    else{
318
      stop("No gene in your dataset overlapped with the IMPACT platform. Please rename genes or check your dataset.")
319
    }
320
    
321
  })
322
  
323
  output$RiskHistogram.new <- renderPlot(dset()$RiskHistogram.new)
324
  
325
  #data <- renderTable(dset()$out.data)
326
  output$downloadData <- downloadHandler(
327
    filename = function() {
328
      paste("NewRiskData.csv", sep="")
329
    },
330
    content = function(file) {
331
      write.csv(dset()$out.data, file)
332
    }
333
  )
334
  
335
}
336
shinyApp(ui, server)