R/mod_upload.R

Defines functions mod_upload_server mod_upload_ui

#' upload UI Function
#'
#' @description A shiny Module.
#'
#' @param id,input,output,session Internal parameters for {shiny}.
#'
#' @noRd 
#'
#' @importFrom shiny NS tagList fluidRow column selectInput conditionalPanel 
#' textOutput tabPanel
#' @importFrom shinyFiles shinyDirButton shinyDirChoose getVolumes parseDirPath
#' @importFrom shinydashboard tabBox 
#' @importFrom fs path_home


mod_upload_ui <- function(id){
  ns <- NS(id)
  
  supported.tools.list <- list("CellPhoneDB v2" = "cpdbv2",
                               "CellChat" = "cellchat",
                               "ICELLNET" = "icellnet",
                               "SingleCellSignalR" = "scsignalR"
                               )
  
  
  text.cpdb <- "Please select the output folder generated by CPDB (v2). When the
  statistical analysis was run, this folder contains 4 .txt files 
  (<em>deconvoluted</em>, <em>means</em>, <em>pvalues</em> and 
  <em>significant_means</em>). In this case, InterCellar will use results stored
  in <em>significant_means</em> for further analyses. If no statistical analysis
  was run, InterCellar will rely on <em>means</em>."
  text.scsignalR <- "Please select the output folder generated by 
  SingleCellSignalR. This is by default named <em>cell-signaling</em> and 
  contains a collection of .txt files, one for each clusters pair considered."
  text.cellchat <- "InterCellar expects a dataframe consisting of inferred cell-cell 
  communications at the level of ligand-receptor interactions. This can be obtained
  by running CellChat's function <em>subsetCommunication (with param slot.name = 'net')</em>. 
  We recommend saving this dataframe as a .csv file (quote = FALSE), but .tsv and .xlsx files are also supported."
  text.icellnet <- "InterCellar accepts a dataframe obtained by running ICELLNET's function <em>icellnet.score</em>. Please 
  specifiy the direction of communication ('out' or 'in') and give a name to the <em>central cell</em>. The dataframe should 
  be saved as a .csv file (with row.names = TRUE)."
  
  tagList(
    fluidRow(
      column(width = 6,
             h2("Upload cell-cell interactions")),
      
      
    ),
    fluidRow(
      box(width = 12,
          title = h3("Analysis setup"),
          column(width = 6,
                 h4("Please select an existing local folder where InterCellar will save all results of your analysis."),
                 ),
          column(width = 6,
                 shinyFiles::shinyDirButton(ns("out_folder"), 
                                            "Select folder", 
                                            "Please select a folder",
                                            icon = icon("folder")),
                 verbatimTextOutput(ns("path_out_folder"))
                 )
          
          )
    ),
    
      tabBox(
        width = NULL,
        
        
        tabPanel(h4("From supported tools"),
                 fluidRow(
                   box(width = 12,
                       title = "CCI data #1",
                       status = "primary",
                       collapsible = TRUE,
                       solidHeader = TRUE,
                       column(6,
                              textInput(ns("db1_name"),
                                        label = h4("CCI data ID"),
                                        placeholder = "my_CCI_data1"),
                              textInput(ns("db1_out_folder"),
                                        label = h4("Output folder tag"),
                                        value = NULL,
                                        placeholder = "my_out_folder1")
                              
                              ),
                       column(6,
                              selectInput(ns("select_input_tool1"),
                                          label = h4("Select tool:"),
                                          choices = supported.tools.list,
                                          multiple = FALSE),
                              # Conditional panels
                              conditionalPanel(
                                condition = "input.select_input_tool1 == 'cpdbv2'",
                                ns = ns,
                                p(div(HTML(text.cpdb)))
                                
                                
                              ),
                              conditionalPanel(
                                condition = "input.select_input_tool1 == 'scsignalR'",
                                ns = ns,
                                p(div(HTML(text.scsignalR)))
                                
                                
                              ),
                              conditionalPanel(
                                condition = "input.select_input_tool1 == 'cellchat'",
                                ns = ns,
                                p(div(HTML(text.cellchat)))
                                
                                
                              ),
                              conditionalPanel(
                                condition = "input.select_input_tool1 == 'icellnet'",
                                ns = ns,
                                p(div(HTML(text.icellnet)))
                                
                                
                              ),
                              conditionalPanel(
                                condition = "input.select_input_tool1 == 'cpdbv2' | input.select_input_tool1 == 'scsignalR'",
                                ns = ns,
                                shinyFiles::shinyDirButton(ns("directory1"), 
                                                           "Select folder", 
                                                           "Please select a folder"),
                                verbatimTextOutput(ns("selected_folder1"))
                              ),
                              conditionalPanel(
                                condition = "input.select_input_tool1 == 'cellchat' | input.select_input_tool1 == 'icellnet'",
                                ns = ns,
                                fileInput(ns("input_file1"), 
                                          "Choose Input File (.csv/.tsv/.xlsx)", 
                                          multiple = FALSE, 
                                          accept = c(".csv", ".tsv", ".xlsx"))
                                
                              ),
                              conditionalPanel(
                                condition = "input.select_input_tool1 == 'icellnet'",
                                ns = ns,
                                radioButtons(ns("icellnet_dir_1"),
                                             label = "Select direction:",
                                             choices = list("out", "in"),
                                             inline = TRUE),
                                textInput(ns("icellnet_CC_1"),
                                          label = "Central cell name",
                                          value = NULL, 
                                          placeholder = "B cells")
                              )
                              ##
                   ),
                   fluidRow(column(width = 1, offset = 11,
                                   actionButton(ns("input_file_button1"), 
                                                label = h4("GO!"),
                                                class = "btn-primary")
                   ))
                   )),
                 fluidRow(
                   box(width = 12,
                       title = "CCI data #2",
                       status = "warning",
                       collapsible = TRUE,
                       collapsed = TRUE,
                       solidHeader = TRUE,
                       column(6,
                              textInput(ns("db2_name"),
                                        label = h4("CCI data ID"),
                                        placeholder = "my_CCI_data2"),
                              textInput(ns("db2_out_folder"),
                                        label = h4("Output folder tag"),
                                        value = NULL,
                                        placeholder = "my_out_folder2")
                       ),
                       column(6,
                              selectInput(ns("select_input_tool2"),
                                          label = h4("Select tool:"),
                                          choices = supported.tools.list,
                                          multiple = FALSE),
                              # Conditional panels
                              conditionalPanel(
                                condition = "input.select_input_tool2 == 'cpdbv2'",
                                ns = ns,
                                p(div(HTML(text.cpdb)))
                                
                                
                              ),
                              conditionalPanel(
                                condition = "input.select_input_tool2 == 'scsignalR'",
                                ns = ns,
                                p(div(HTML(text.scsignalR)))
                                
                                
                              ),
                              conditionalPanel(
                                condition = "input.select_input_tool2 == 'cellchat'",
                                ns = ns,
                                p(div(HTML(text.cellchat)))
                                
                                
                              ),
                              conditionalPanel(
                                condition = "input.select_input_tool2 == 'icellnet'",
                                ns = ns,
                                p(div(HTML(text.icellnet)))
                                
                                
                              ),
                              conditionalPanel(
                                condition = "input.select_input_tool2 == 'cpdbv2' | input.select_input_tool2 == 'scsignalR'",
                                ns = ns,
                                shinyFiles::shinyDirButton(ns("directory2"), 
                                                           "Select folder", 
                                                           "Please select a folder"),
                                verbatimTextOutput(ns("selected_folder2"))
                              ),
                              conditionalPanel(
                                condition = "input.select_input_tool2 == 'cellchat' | input.select_input_tool2 == 'icellnet'",
                                ns = ns,
                                fileInput(ns("input_file2"), 
                                          "Choose Input File (.csv/.tsv/.xlsx)", 
                                          multiple = FALSE, 
                                          accept = c(".csv", ".tsv", ".xlsx"))
                                
                              ),
                              conditionalPanel(
                                condition = "input.select_input_tool2 == 'icellnet'",
                                ns = ns,
                                radioButtons(ns("icellnet_dir_2"),
                                             label = "Select direction:",
                                             choices = list("out", "in"),
                                             inline = TRUE),
                                textInput(ns("icellnet_CC_2"),
                                          label = "Central cell name",
                                          value = NULL, 
                                          placeholder = "B cells")
                              )
                              ##
                       ),
                       fluidRow(column(width = 1, offset = 11,
                                       actionButton(ns("input_file_button2"), 
                                                    label = h4("GO!"),
                                                    class = "btn-warning")
                       ))
                   )),
                 fluidRow(
                   box(width = 12,
                       title = "CCI data #3",
                       status = "danger",
                       collapsible = TRUE,
                       collapsed = TRUE,
                       solidHeader = TRUE,
                       column(6,
                              textInput(ns("db3_name"),
                                        label = h4("CCI data ID"),
                                        placeholder = "my_CCI_data3"),
                              textInput(ns("db3_out_folder"),
                                        label = h4("Output folder tag"),
                                        value = NULL,
                                        placeholder = "my_out_folder3")
                       ),
                       column(6,
                              selectInput(ns("select_input_tool3"),
                                          label = h4("Select tool:"),
                                          choices = supported.tools.list,
                                          multiple = FALSE),
                              # Conditional panels
                              conditionalPanel(
                                condition = "input.select_input_tool3 == 'cpdbv2'",
                                ns = ns,
                                p(div(HTML(text.cpdb)))
                                
                                
                              ),
                              conditionalPanel(
                                condition = "input.select_input_tool3 == 'scsignalR'",
                                ns = ns,
                                p(div(HTML(text.scsignalR)))
                                
                                
                              ),
                              conditionalPanel(
                                condition = "input.select_input_tool3 == 'cellchat'",
                                ns = ns,
                                p(div(HTML(text.cellchat)))
                                
                                
                              ),
                              conditionalPanel(
                                condition = "input.select_input_tool3 == 'icellnet'",
                                ns = ns,
                                p(div(HTML(text.icellnet)))
                                
                                
                              ),
                              conditionalPanel(
                                condition = "input.select_input_tool3 == 'cpdbv2' | input.select_input_tool3 == 'scsignalR'",
                                ns = ns,
                                shinyFiles::shinyDirButton(ns("directory3"), 
                                                           "Select folder", 
                                                           "Please select a folder"),
                                verbatimTextOutput(ns("selected_folder3"))
                              ),
                              conditionalPanel(
                                condition = "input.select_input_tool3 == 'cellchat' | input.select_input_tool3 == 'icellnet'",
                                ns = ns,
                                fileInput(ns("input_file3"), 
                                          "Choose Input File (.csv/.tsv/.xlsx)", 
                                          multiple = FALSE, 
                                          accept = c(".csv", ".tsv", ".xlsx"))
                                
                              ),
                              conditionalPanel(
                                condition = "input.select_input_tool3 == 'icellnet'",
                                ns = ns,
                                radioButtons(ns("icellnet_dir_3"),
                                             label = "Select direction:",
                                             choices = list("out", "in"),
                                             inline = TRUE),
                                textInput(ns("icellnet_CC_3"),
                                          label = "Central cell name",
                                          value = NULL, 
                                          placeholder = "B cells")
                              )
                              ##
                       ),
                       fluidRow(column(width = 1, offset = 11,
                                       actionButton(ns("input_file_button3"), 
                                                    label = h4("GO!"),
                                                    class = "btn-danger")
                       ))
                   ))
        ), #tabpanel
        tabPanel(h4("From custom analysis"),
                 mod_upload_custom_ui("upload_custom_ui_1")
        )
      )#tabbox
      
             
             
      
  )
  
  
}
    
#' upload Server Function
#'
#' @importFrom shinyalert shinyalert
#' @noRd 
mod_upload_server <- function(id) {
  moduleServer(id, function(input, output, session) {
    
    rv <- reactiveValues(data = list(db1 = NULL,
                                     db2 = NULL,
                                     db3 = NULL), 
                         db_names = list(db1 = NULL,
                                         db2 = NULL,
                                         db3 = NULL),
                         output_folders_path = list(db1 = NULL,
                                                    db2 = NULL,
                                                    db3 = NULL),
                         output_folder = NULL,
                         output_tags = list(db1 = NULL,
                                            db2 = NULL,
                                            db3 = NULL))
    
    
    ### For supported tools requiring folders
    volumes <- c(Home = fs::path_home(), getVolumes()())
    ## CCI data 1
    shinyDirChoose(input, "directory1", roots = volumes, session = session, 
                   restrictions = system.file(package = "base"))
    
    input_folder1 <- reactive({
      req(input$directory1)
      parseDirPath(volumes, input$directory1)
    })
    
    output$selected_folder1 <- renderText({
      input_folder1()
    })
    ## CCI data 2
    shinyDirChoose(input, "directory2", roots = volumes, session = session, 
                   restrictions = system.file(package = "base"))
    
    input_folder2 <- reactive({
      req(input$directory2)
      parseDirPath(volumes, input$directory2)
    })
    
    output$selected_folder2 <- renderText({
      input_folder2()
    })
    ## CCI data 3
    shinyDirChoose(input, "directory3", roots = volumes, session = session, 
                   restrictions = system.file(package = "base"))
    
    input_folder3 <- reactive({
      req(input$directory3)
      parseDirPath(volumes, input$directory3)
    })
    
    output$selected_folder3 <- renderText({
      input_folder3()
    })
    
    
    ### Output folder
    
    shinyDirChoose(input, "out_folder", roots = volumes, session = session, 
                   restrictions = system.file(package = "base"))
    
    output_folder <- reactive({
      #req(input$out_folder)
      parseDirPath(volumes, input$out_folder)
    })
    
    output$path_out_folder <- renderText({
      output_folder()
    })
    
    observeEvent(output_folder(), {
      rv$output_folder <- output_folder()
    })
    
    
    
    ### CCI data 1
    ### Read input and construct datatable 
    observeEvent(input$input_file_button1, {
      
      if(input$db1_name == ""){
        shinyalert(text = "Please specify an ID for your CCI data #1!", type = "error",
                   showCancelButton = FALSE)
      }
      if(input$db1_out_folder == ""){
        shinyalert(text = "Please specify an output folder tag for your CCI data #1!", type = "error",
                   showCancelButton = FALSE)
      }
      if(identical(output_folder(), character(0))){
        shinyalert(text = "Please select an output folder!", 
                   type = "error",
                   showCancelButton = FALSE)
      }
      req(output_folder())
      req(input$db1_name, input$db1_out_folder)
      
      #check that tags are not repeated
      tags <- c(input$db1_out_folder, input$db2_out_folder, input$db3_out_folder)
      tags <- tags[!(tags == "")]
      if(any(duplicated(tags))){
        shinyalert(text = "It looks like tags for output folders are not unique! Please re-upload your data after changing repeated tags 
                   to avoid overwriting results!", 
                   type = "error",
                   showCancelButton = FALSE)
      } else {
        # create directory with tags
        dir.create(file.path(output_folder(), paste0("InterCellar_results_", input$db1_out_folder)))
        shinyalert(text = paste0("Directory created: ", file.path(output_folder(), paste0("InterCellar_results_", input$db1_out_folder))), 
                   type = "success",
                   showCancelButton = FALSE,
                   timer = 4000)
        rv$output_folders_path$db1 <- file.path(output_folder(), paste0("InterCellar_results_", input$db1_out_folder))
      }
       
      
      
      
      rv$db_names$db1 <- as.character(input$db1_name)
      rv$output_tags$db1 <- input$db1_out_folder
      
      if(input$select_input_tool1 == 'cpdbv2'){
       
        req(input_folder1())
        files <- list.files(input_folder1())
        if("means.txt" %in% files){
          rv$data$db1 <- read.CPDBv2(folder = input_folder1())
          shinyalert(text = "Your data was successfully loaded and preprocessed!", 
                     type = "success",
                     showCancelButton = FALSE)
        } else {
          shinyalert(text = "The selected folder does not contain CPDB output files!
                     Please select the correct folder.", 
                     type = "error",
                     showCancelButton = FALSE)
        }
        
      }
      else if(input$select_input_tool1 == 'scsignalR'){

        req(input_folder1())
        files <- list.files(input_folder1())
        if(all(grep("LR_interactions", files))){
          rv$data$db1 <- read.SCsignalR(folder = input_folder1())
          shinyalert(text = "Your data was successfully loaded and preprocessed!", 
                     type = "success",
                     showCancelButton = FALSE)
        } else{
          shinyalert(text = "The selected folder does not contain 
          SingleCellSignalR output files!
                     Please select the correct folder.", 
                     type = "error",
                     showCancelButton = FALSE)
        }
        
      } else if(input$select_input_tool1 == 'cellchat'){ 
        file <- input$input_file1
        req(file)
       
        ext <- tools::file_ext(file$datapath)
        
        validate(need(ext %in% c("csv", "tsv", "xlsx"), "Please choose a file
                    with the required extension (.csv/.tsv/.xlsx)."))
        switch (ext,
                csv = {tryCatch({
                  tab <- read.csv(file$datapath, header = TRUE)
                  if("X" %in% colnames(tab)){
                    tab <- tab[, !colnames(tab) == "X"]
                  }
                },
                error = function(e) {
                  # return a safeError if a parsing error occurs
                  stop(safeError("Error reading input file"))
                }
                )},
                tsv = {tryCatch({
                  tab <- read.table(file$datapath, sep = "\t", 
                                    header = TRUE)
                },
                error = function(e) {
                  # return a safeError if a parsing error occurs
                  stop(safeError("Error reading input file"))
                }
                )},
                xlsx = {tryCatch({
                  tab <- read_excel(file$datapath, col_names = TRUE)
                },
                error = function(e) {
                  # return a safeError if a parsing error occurs
                  stop(safeError("Error reading input file"))
                }
                )}
        )
        
        # Checks on required columns
        req.columns <- c("source", "target", "ligand", "receptor", "prob", "pval", 
                         "interaction_name", "interaction_name_2", "pathway_name",
                         "annotation", "evidence")
        if(!all(req.columns %in% colnames(tab))){
          missing.col <- req.columns[!(req.columns %in% colnames(tab))]
          shinyalert(text = paste("Looks like these required columns are missing:", 
                                  paste(missing.col, collapse = " "), sep = " "), 
                     type = "error",
                     showCancelButton = FALSE)
        } else {
          rv$data$db1 <- suppressWarnings(read.cellchat(tab))
          shinyalert(text = "Your data was successfully loaded and preprocessed!", 
                     type = "success",
                     showCancelButton = FALSE)
        }
          
      } else if(input$select_input_tool1 == 'icellnet'){
        file <- input$input_file1
        req(file)
        
        ext <- tools::file_ext(file$datapath)
        
        validate(need(ext %in% c("csv"), "Please choose a file
                    with the required extension (.csv)."))
        switch (ext,
                csv = {tryCatch({
                  tab <- read.csv(file$datapath)
                },
                error = function(e) {
                  # return a safeError if a parsing error occurs
                  stop(safeError("Error reading input file"))
                }
                )}
                
        )
        
        validate(need(input$icellnet_CC_1, "Please give a name to the central cell!"))
        rv$data$db1 <- suppressWarnings(read.icellnet(tab, input$icellnet_CC_1, input$icellnet_dir_1))
        shinyalert(text = "Your data was successfully loaded and preprocessed!", 
                   type = "success",
                   showCancelButton = FALSE)
          
        
      }
      
    })
    
    
    ### CCI data 2
    ### Read input and construct datatable
    observeEvent(input$input_file_button2, {

      if(input$db2_name == ""){
        shinyalert(text = "Please specify an ID for your CCI data #2!", type = "error",
                   showCancelButton = FALSE)
      }
      if(input$db2_out_folder == ""){
        shinyalert(text = "Please specify an output folder tag for your CCI data #2!", type = "error",
                   showCancelButton = FALSE)
      }
      if(identical(output_folder(), character(0))){
        shinyalert(text = "Please select an output folder!", 
                   type = "error",
                   showCancelButton = FALSE)
      }
      req(output_folder())
      req(input$db2_name, input$db2_out_folder)
      
      #check that tags are not repeated
      tags <- c(input$db1_out_folder, input$db2_out_folder, input$db3_out_folder)
      tags <- tags[!(tags == "")]
      if(any(duplicated(tags))){
        shinyalert(text = "It looks like tags for output folders are not unique! Please re-upload your data after changing repeated tags 
                   to avoid overwriting results!", 
                   type = "error",
                   showCancelButton = FALSE)
      } else {
        # create directory with tags
        dir.create(file.path(output_folder(), paste0("InterCellar_results_", input$db2_out_folder)))
        shinyalert(text = paste0("Directory created: ", file.path(output_folder(), paste0("InterCellar_results_", input$db2_out_folder))), 
                   type = "success",
                   showCancelButton = FALSE,
                   timer = 4000)
        rv$output_folders_path$db2 <- file.path(output_folder(), paste0("InterCellar_results_", input$db2_out_folder))
      }

      rv$db_names$db2 <- as.character(input$db2_name)
      rv$output_tags$db2 <- input$db2_out_folder
      
      if(input$select_input_tool2 == 'cpdbv2'){
        
        req(input_folder2())
        files <- list.files(input_folder2())
        if("means.txt" %in% files){
          rv$data$db2 <- read.CPDBv2(folder = input_folder2())
          shinyalert(text = "Your data was successfully loaded and preprocessed!", 
                     type = "success",
                     showCancelButton = FALSE)
        } else {
          shinyalert(text = "The selected folder does not contain CPDB output files!
                     Please select the correct folder.",
                     type = "error",
                     showCancelButton = FALSE)
        }

      }
      else if(input$select_input_tool2 == 'scsignalR'){
        
        req(input_folder2())
        files <- list.files(input_folder2())
        if(all(grep("LR_interactions", files))){
          rv$data$db2 <- read.SCsignalR(folder = input_folder2())
          shinyalert(text = "Your data was successfully loaded and preprocessed!", 
                     type = "success",
                     showCancelButton = FALSE)
        } else{
          shinyalert(text = "The selected folder does not contain
          SingleCellSignalR output files!
                     Please select the correct folder.",
                     type = "error",
                     showCancelButton = FALSE)
        }

      } else if(input$select_input_tool2 == 'cellchat'){ # add here other file input tools
        file <- input$input_file2
        req(file)
        
        ext <- tools::file_ext(file$datapath)

        validate(need(ext %in% c("csv", "tsv", "xlsx"), "Please choose a file
                    with the required extension (.csv/.tsv/.xlsx)."))
        switch (ext,
                csv = {tryCatch({
                  tab <- read.csv(file$datapath, header = TRUE)
                  if("X" %in% colnames(tab)){
                    tab <- tab[, !colnames(tab) == "X"]
                  }
                },
                error = function(e) {
                  # return a safeError if a parsing error occurs
                  stop(safeError("Error reading input file"))
                }
                )},
                tsv = {tryCatch({
                  tab <- read.table(file$datapath, sep = "\t",
                                    header = TRUE)
                },
                error = function(e) {
                  # return a safeError if a parsing error occurs
                  stop(safeError("Error reading input file"))
                }
                )},
                xlsx = {tryCatch({
                  tab <- read_excel(file$datapath, col_names = TRUE)
                },
                error = function(e) {
                  # return a safeError if a parsing error occurs
                  stop(safeError("Error reading input file"))
                }
                )}
        )

        # Checks on required columns
        req.columns <- c("source", "target", "ligand", "receptor", "prob", "pval",
                         "interaction_name", "interaction_name_2", "pathway_name",
                         "annotation", "evidence")
        if(!all(req.columns %in% colnames(tab))){
          missing.col <- req.columns[!(req.columns %in% colnames(tab))]
          shinyalert(text = paste("Looks like these required columns are missing:",
                                  paste(missing.col, collapse = " "), sep = " "),
                     type = "error",
                     showCancelButton = FALSE)
        } else {
          rv$data$db2 <- suppressWarnings(read.cellchat(tab))
          shinyalert(text = "Your data was successfully loaded and preprocessed!", 
                     type = "success",
                     showCancelButton = FALSE)
        }
          
        

      } else if(input$select_input_tool2 == 'icellnet'){
        file <- input$input_file2
        req(file)
        
        ext <- tools::file_ext(file$datapath)
        
        validate(need(ext %in% c("csv"), "Please choose a file
                    with the required extension (.csv)."))
        switch (ext,
                csv = {tryCatch({
                  tab <- read.csv(file$datapath)
                },
                error = function(e) {
                  # return a safeError if a parsing error occurs
                  stop(safeError("Error reading input file"))
                }
                )}
                
        )
        
        validate(need(input$icellnet_CC_2, "Please give a name to the central cell!"))
        rv$data$db2 <- suppressWarnings(read.icellnet(tab, input$icellnet_CC_2, input$icellnet_dir_2))
        shinyalert(text = "Your data was successfully loaded and preprocessed!", 
                   type = "success",
                   showCancelButton = FALSE)
        
        
      }

    })


    ### CCI data 3
    ### Read input and construct datatable
    observeEvent(input$input_file_button3, {

      if(input$db3_name == ""){
        shinyalert(text = "Please specify an ID for your CCI data #3!", type = "error",
                   showCancelButton = FALSE)
      }
      if(input$db3_out_folder == ""){
        shinyalert(text = "Please specify an output folder tag for your CCI data #3!", type = "error",
                   showCancelButton = FALSE)
      }
      if(identical(output_folder(), character(0))){
        shinyalert(text = "Please select an output folder!", 
                   type = "error",
                   showCancelButton = FALSE)
      }
      req(output_folder())
      req(input$db3_name, input$db3_out_folder)
      
      #check that tags are not repeated
      tags <- c(input$db1_out_folder, input$db2_out_folder, input$db3_out_folder)
      tags <- tags[!(tags == "")]
      if(any(duplicated(tags))){
        shinyalert(text = "It looks like tags for output folders are not unique! Please re-upload your data after changing repeated tags 
                   to avoid overwriting results!", 
                   type = "error",
                   showCancelButton = FALSE)
      } else {
        # create directory with tags
        dir.create(file.path(output_folder(), paste0("InterCellar_results_", input$db3_out_folder)))
        shinyalert(text = paste0("Directory created: ", file.path(output_folder(), paste0("InterCellar_results_", input$db3_out_folder))), 
                   type = "success",
                   showCancelButton = FALSE,
                   timer = 4000)
        rv$output_folders_path$db3 <- file.path(output_folder(), paste0("InterCellar_results_", input$db3_out_folder))
      }

      rv$db_names$db3 <- as.character(input$db3_name)
      rv$output_tags$db3 <- input$db3_out_folder
      
      if(input$select_input_tool3 == 'cpdbv2'){
        
        req(input_folder3())
        files <- list.files(input_folder3())
        if("means.txt" %in% files){
          rv$data$db3 <- read.CPDBv2(folder = input_folder3())
          shinyalert(text = "Your data was successfully loaded and preprocessed!", 
                     type = "success",
                     showCancelButton = FALSE)
        } else {
          shinyalert(text = "The selected folder does not contain CPDB output files!
                     Please select the correct folder.",
                     type = "error",
                     showCancelButton = FALSE)
        }

      }
      else if(input$select_input_tool3 == 'scsignalR'){
        
        req(input_folder3())
        files <- list.files(input_folder3())
        if(all(grep("LR_interactions", files))){
          rv$data$db3 <- read.SCsignalR(folder = input_folder3())
          shinyalert(text = "Your data was successfully loaded and preprocessed!", 
                     type = "success",
                     showCancelButton = FALSE)
        } else{
          shinyalert(text = "The selected folder does not contain
          SingleCellSignalR output files!
                     Please select the correct folder.",
                     type = "error",
                     showCancelButton = FALSE)
        }

      } else if(input$select_input_tool3 == 'cellchat'){ # add here other file input tools
        file <- input$input_file3
        req(file)
        ext <- tools::file_ext(file$datapath)

        validate(need(ext %in% c("csv", "tsv", "xlsx"), "Please choose a file
                    with the required extension (.csv/.tsv/.xlsx)."))
        switch (ext,
                csv = {tryCatch({
                  tab <- read.csv(file$datapath, header = TRUE)
                  if("X" %in% colnames(tab)){
                    tab <- tab[, !colnames(tab) == "X"]
                  }
                },
                error = function(e) {
                  # return a safeError if a parsing error occurs
                  stop(safeError("Error reading input file"))
                }
                )},
                tsv = {tryCatch({
                  tab <- read.table(file$datapath, sep = "\t",
                                    header = TRUE)
                },
                error = function(e) {
                  # return a safeError if a parsing error occurs
                  stop(safeError("Error reading input file"))
                }
                )},
                xlsx = {tryCatch({
                  tab <- read_excel(file$datapath, col_names = TRUE)
                },
                error = function(e) {
                  # return a safeError if a parsing error occurs
                  stop(safeError("Error reading input file"))
                }
                )}
        )

        # Checks on required columns
        req.columns <- c("source", "target", "ligand", "receptor", "prob", "pval",
                         "interaction_name", "interaction_name_2", "pathway_name",
                         "annotation", "evidence")
        if(!all(req.columns %in% colnames(tab))){
          missing.col <- req.columns[!(req.columns %in% colnames(tab))]
          shinyalert(text = paste("Looks like these required columns are missing:",
                                  paste(missing.col, collapse = " "), sep = " "),
                     type = "error",
                     showCancelButton = FALSE)
        } else {
          rv$data$db3 <- suppressWarnings(read.cellchat(tab))
          shinyalert(text = "Your data was successfully loaded and preprocessed!", 
                     type = "success",
                     showCancelButton = FALSE)
        }
          
        

      } else if(input$select_input_tool3 == 'icellnet'){
        file <- input$input_file3
        req(file)
        
        ext <- tools::file_ext(file$datapath)
        
        validate(need(ext %in% c("csv"), "Please choose a file
                    with the required extension (.csv)."))
        switch (ext,
                csv = {tryCatch({
                  tab <- read.csv(file$datapath)
                },
                error = function(e) {
                  # return a safeError if a parsing error occurs
                  stop(safeError("Error reading input file"))
                }
                )}
                
        )
        
        validate(need(input$icellnet_CC_3, "Please give a name to the central cell!"))
        rv$data$db3 <- suppressWarnings(read.icellnet(tab, input$icellnet_CC_3, input$icellnet_dir_3))
        shinyalert(text = "Your data was successfully loaded and preprocessed!", 
                   type = "success",
                   showCancelButton = FALSE)
        
        
      }

    })





    
    
    return(rv)
  })
}
    
martaint/InterCellar documentation built on April 7, 2022, 11:44 a.m.