inst/shiny/UHRIonStar/app.R

options(shiny.maxRequestSize=20000*1024^2)
### Define UI ----
ui <- dashboardPage(
    dashboardHeader(title = "UHR-IonStar v1.5"),
    dashboardSidebar(
        sidebarMenu(
            menuItem("Homepage", tabName = "Homepage", icon = icon("home")),
            menuItem('Database Searching', tabName = 'DBsearch', icon = icon("file")),
            menuItem('PSM List Generation', tabName = 'PSMlistGen', icon = icon("edit")),
            menuItem("Protein Quantification", tabName = "ProteinQuan", icon = icon("edit")),
            menuItem('Quality Control', tabName = "QualIllstr", icon = icon("check")),
            menuItem("Statistics", tabName = "Statistics", icon = icon("edit")),
            menuItem("Visualization", tabName = "Visual", icon = icon("eye")),
            menuItem("Biomarker Discovery", tabName = "Biomarkers", icon = icon("filter"))
        )
    ),
    dashboardBody(
        tags$head(
            tags$style(
                "body{
          height: auto;
          margin: auto;
}"
            )
        ),

        tabItems(
            ##Homepage
            {
                tabItem(tabName = "Homepage",
                        fluidPage(
                            titlePanel(strong("UHR-IonStar")),
                            mainPanel(
                                img(src="logo.png",height=120,width=120),
                                h4(strong("UHR-IonStar app is a R Shiny-based interactive application designed for processing, visualization and analysis of quantitative proteomics data generated by UHR(ultra-high-resolution)-IonStar")),
                                h4("Fundamental components of UHR-IonStar app include:"),
                                h4(icon("check"),"Database searching"),
                                h4(icon("check"),"PSM list generation"),
                                h4(icon("check"),"Post-feature generation quality control and protein quantification"),
                                h4(icon("check"),"Case-control ratio calculation and statistical testing"),
                                h4(icon("check"),"Graphic depiction of quantitative results"),
                                h4(icon("check"),"Traditional data mining (e.g. Principle Component Analysis)"),
                                h4("Click the botton below to download the manual:"),
                                downloadButton("downloadManual", label="Download Manual", icon=icon("download")),
                                h4("For any questions, suggestions, and other relevant topics about UHR-IonStar, please contact the developers:"),
                                h4("Shuo Qian:",
                                   "sqian@buffalo.edu"),
                                h4("Shichen Shen:",
                                   "shichens@buffalo.edu"),
                                h4("Jun Qu:",
                                   "junqu@buffalo.edu")
                            )
                        )
                )},


            #DatabaseSearching
            {
                tabItem(tabName = "DBsearch",
                        fluidPage(
                            titlePanel(strong("Raw file conversion and Database searching")),
                            sidebarLayout(
                                position = "left",
                                sidebarPanel(
                                    verbatimTextOutput("raw_folder", placeholder = TRUE),
                                    actionButton("raw_folder", "Select the folder containing raw files and the fasta database",icon=icon("upload"),width="100%"),
                                    br(),
                                    br(),
                                    verbatimTextOutput("msgf_folder", placeholder = TRUE),
                                    actionButton("msgf_folder", "Select the folder containing the MSGF+ java file",icon=icon("upload"),width="100%"),
                                    br(),
                                    br(),
                                    sliderInput("threads","Set the number of processing threads:",
                                                min = 1,max = 12,value = 2),
                                    actionButton(inputId = "DBSGoButton",label = "Start formatting and searching",icon=icon("pencil"),width="100%"),
                                    shiny::span(textOutput("DBsearchingNotice"),style = 'color:green')
                                ),#sidebarpanel
                                mainPanel(
                                    h3(strong("MSGF+ Parameter Settings")),
                                    checkboxInput('add_decoys','Select if adding decoys or not.', value = TRUE),
                                    textInput('tolerance','Input precursor mass tolerance (ppm):', value = 20),
                                    textInput('iso_error','Input isotope error range (separated by comma):', value = '-1,2'),
                                    selectInput(inputId = "fragment",
                                                label = "Choose the fragmentation method:",
                                                choices = c("HCD", "CID","ETD")),
                                    radioButtons("instrument","Choose the MS instrument:",
                                                 c("QExactive"="QExactive", "TOF"="TOF")),
                                    selectInput(inputId = "enzyme",
                                                label = "Select the enzyme: ",
                                                choices = c("Trypsin", "Unspecific cleavage","Chymotrypsin","Lys-C","Lys-N",
                                                            "Glu-C","Arg-C","Asp-N","alphaLP","No cleavage")),
                                    selectInput(inputId = "protocol",
                                                label = "Select the sample treatment protocol: ",
                                                choices = c("No protocol", "Phosphorylation","iTRAQ","iTRAQPhospho")),
                                    radioButtons(inputId="ntt",label="Specify the cleavage specificity:",
                                                 c("Fully tryptic peptides"=2, "Semitryptic peptides"=1, "unspecific peptides"=0)),
                                    textInput('lengthRange','Input peptide length range (separated by comma):', '6,40'),
                                    textInput('chargeRange','Input peptide charge range (separated by comma):', '2,7'),
                                    textInput('matches','Input the number of matches to report per spectrum:', value = 1),
                                    textInput('nmod','Input the maximum modification number per peptide:', value = 3),
                                    # need to change in the future
                                    checkboxGroupInput("frag_modi","Specify the modifications:",
                                                       choices = list('Carbamidomethyl (C, Fixed)' = 'Carbamidomethyl',
                                                                      'Oxidation (M)' = 'Oxidation','Deamidated (NQ)'= 'Deamidated',
                                                                      'Methyl (K)'='Methyl','N-term Acetyl'='Acetyl',
                                                                      'Phospho (STY)'='Phospho','Pyro-glu from E'='Glu->pryo-Glu',
                                                                      'Pyro-glu from Q'='Gln->pryo-Glu'), selected = c('Carbamidomethyl',
                                                                                                                       'Oxidation',
                                                                                                                       'Acetyl'))
                                )
                            )#sidebarlayout
                        )#fieldpage
                )}, # tabItem


            #SpecRepoGen
            {
                tabItem(tabName = "PSMlistGen",
                        fluidPage(
                            titlePanel(strong("PSM List Generation")),
                            sidebarLayout(
                                position = "left",
                                sidebarPanel(
                                    fileInput("IDPprotein", "Upload Protein List from IDpicker:",
                                              accept=c(".tsv", ".csv")),
                                    fileInput("IDPpeptide", "Upload Peptide List from IDpicker:",
                                              accept=c(".tsv", ".csv")),
                                    fileInput("IDPspectrum", "Upload Spectrum List from IDpicker:",
                                              accept=c(".tsv", ".csv")),
                                    verbatimTextOutput("mzid_folder", placeholder = TRUE),
                                    actionButton("mzid_folder", "Select the folder containing mzid files",icon=icon("upload"),width="100%"),
                                    br(),
                                    br(),
                                    textInput("SpecName", "Name your PSM list ('.csv' is required):",
                                              value="PSM_list.csv"),
                                    br(),
                                    actionButton(inputId = "SpecGoButton",label = "Generate PSM list",icon=icon("pencil"),width="100%"),
                                    helpText('PSM list will be generated at the same folder with .mzid files.'),
                                    br()
                                ),#sidebarpanel
                                mainPanel(
                                    h3(strong("PSM List Generation"))
                                )
                            )#sidebarlayout
                        )#fieldpage
                )}, # tabItem


            #Protein Quantification
            {
                tabItem(tabName = "ProteinQuan",
                        fluidPage(
                            titlePanel(strong("Protein Quantification")),
                            sidebarLayout(
                                position = "left",
                                sidebarPanel(
                                    h4(strong("Frames Generation:")),
                                    fileInput("StatUploadSEIVE", "Upload SIEVE database (.sdb)",
                                              accept=c(".sdb")),
                                    helpText('Please upload PSM list after you see "Upload complete" on the bar above!', style = 'color:blue'),
                                    fileInput("StatUploadSR", "Upload PSM list (.csv):",
                                              accept=c(".tsv", ".csv")),
                                    h4(strong("Several settings in PSM list:")),
                                    textInput(inputId = "StatFileNumber",
                                              label = "Specify the number of column which contains filename information:", value = "1"),
                                    textInput(inputId = "StatScanNumber",
                                              label = "Specify the number of column which contains MS2 scan number:", value = "3"),
                                    textInput(inputId = "StatProAccession",
                                              label = "Specify the number of column which contains protein accessions:", value = "16"),
                                    textInput(inputId = "StatPepSeq",
                                              label = "Specify the number of column which contains peptide sequence:", value = "15"),
                                    actionButton(inputId = "StatGoButton2",label = "Generate Frames",icon=icon("pencil"),width="100%"),
                                    shiny::span(textOutput("StatFrameNotice"), style = 'color:green'),
                                    br(),
                                    downloadButton("StatFrameDownload", label="Download Annotated Frame List", icon=icon("download")),
                                    downloadButton("StatSampleIDDownload", label="Download Sample ID", icon=icon("download")),
                                    br(),
                                    tags$hr(),
                                    h4(strong("Protein Quantification:")),
                                    fileInput("StatUploadFrame", "Upload annotated frame List(.csv)",
                                              accept=c(".tsv", ".csv")),
                                    fileInput("StatUploadSampleID", "Upload sample id file (.csv)",
                                              accept=c(".tsv", ".csv")),
                                    #      helpText('Please upload the a fasta database if you would like to perform species deconvolution', style = 'color:blue'),
                                    #      fileInput("StatUploadDatabase", "Upload Database (.fasta)",
                                    #                accept=".fasta"),
                                    radioButtons("Norm_method","Select inter-group peptide normalization method:",
                                                 c("Total Ion Currents (TIC)"="TIC",
                                                   "Quantile"="quantile",
                                                   "No normalization" = 'none')),
                                    checkboxGroupInput("Frame_OR",
                                                       "Choose whether you would like to remove low-quality quantitative data at the frame level:",
                                                       choices = "Frame-level Quality Control"),
                                    checkboxGroupInput("Peptide_OR",
                                                       "Choose whether you would like to remove low-quality quantitative data at the peptide level:",
                                                       choices = "Peptide-level Quality Control"),
                                    radioButtons("Quan_method","Select the method that aggregates peptides to proteins",
                                                 c("The Sum of Intensities"="sum",
                                                   "General Linear Mixed Model (GLMM)"="fit")),
                                    #      checkboxGroupInput("Share_rm",
                                    #                         "Choose whether you would like to remove shared frames between two or more different species:",
                                    #                         choices = "Mixed Proteomes Deconvolution"),
                                    actionButton(inputId = "StatGoButton4",label = "Perform Protein Quantification",icon=icon("pencil"),width="100%"),
                                    shiny::span(textOutput("noticeStat8"),style = 'color:green'),
                                    br(),
                                    downloadButton("downloadDataStat4", label="Download Quantification Data", icon=icon("download")),
                                    downloadButton("downloadDataStat5", label="Download Peptides", icon=icon("download")),
                                    br(),
                                    tags$hr()

                                ),#sidebarpanel
                                mainPanel(
                                    h3(strong("IonStarStat")),
                                    textOutput("message1"),
                                    textOutput("message2")
                                )
                            )#sidebarlayout
                        )#fieldpage
                )}, # tabItem

            #Quality Control
            {tabItem(tabName = "QualIllstr",
                     fluidPage(
                         titlePanel(strong("Quality Control")),
                         sidebarLayout(
                             position = "left",
                             sidebarPanel(
                                 downloadButton("QIplots", label="Download all quality plots", icon=icon("download"))
                             ),
                             mainPanel(
                                 h4(strong("Intra-group CV plot")),
                                 plotOutput("IGCV"),
                                 h4(strong("Protein Rank plot")),
                                 plotOutput("PRank"),
                                 h4(strong("Mass Shift plot")),
                                 plotOutput("MSS")
                             )
                         )
                     )
            )}, # tabItem

            #Data processing
            {tabItem(tabName = "Statistics",
                     fluidPage(
                         titlePanel(strong("Protein Data Processing")),
                         sidebarLayout(
                             position = "left",
                             sidebarPanel(
                                 fileInput("file1", "Upload quantitative results (.csv):",
                                           accept=c("text/csv",
                                                    "text/comma-separated-values,text/plain",
                                                    ".csv")),
                                 fileInput("file2", "Upload group file (.csv):",
                                           accept=c("text/csv",
                                                    "text/comma-separated-values,text/plain",
                                                    ".csv")),
                                 tags$hr(),

                                 helpText("Please fill in your control group shown in the right, case sensitive (default is the first one):", style = 'color:blue'),
                                 #  selectInput(inputId = "ctrlGroup", label = "Assign control group", choices = " "),
                                 textInput(inputId = "ctrlGroup",
                                           label = "Assign control group", value="X"),
                                 selectInput(inputId = "testing",
                                             label = "Select method of statistical testing:",
                                             choices = c("Original t-test", "Paired t-test", "Wilcoxon signed-rank test",
                                                         "Kruskal-Wallis ANOVA")),
                                 radioButtons(inputId = "ttestopt",
                                              label = "Variance equality:",
                                              choices = c("TRUE", "FALSE")),
                                 textInput("decoy", "Decoy Protein identifier",
                                           value="XXX"),
                                 actionButton("calculate",label="Start Data Processing",icon=icon("pencil"),width="100%"),
                                 shiny::span(textOutput("notice1"),style = 'color:green'),
                                 downloadButton("downloadData", label="Download Processed Quantity Results", icon=icon("download")),
                                 downloadButton("downloadData2", label="Download Average Ratios", icon=icon("download"),width="100%"),
                                 downloadButton("downloadData_all", label="Download All Together", icon=icon("download"),width="100%"),
                                 helpText("Note: Decoy entries and proteins with missing data will be removed automatically during the data processing step.", style = 'color:blue')
                             ),
                             mainPanel(
                                 h4(strong("Quantitative Results")),
                                 DT::dataTableOutput("contents"),
                                 textOutput("submitted")
                             )
                         )
                     )
            )}, # tabItem

            ##Data visualization
            {tabItem(tabName = "Visual",
                     fluidPage(
                         titlePanel(strong("Data Visualization")),
                         sidebarLayout(
                             position = "left",
                             sidebarPanel(
                                 selectInput(inputId = "plotType",
                                             label = "Select plot type:",
                                             choices = c("Inter-group correlation plot",
                                                         "Pearson correlation matrix plot","Principal Component Analysis (PCA)")),
                                 p(strong("*For Inter-group correlation plot ONLY:")),
                                 helpText("Please fill in the groups you want to see, case sensitive ( Default is the first two groups):", style = 'color:blue'),
                                 textInput(inputId = "inter_group1",
                                           label = "Group 1", value = "XXX"),
                                 textInput(inputId = "inter_group2",
                                           label = "Group 2", value = "XXX"),

                                 actionButton("plot",label="Plot",icon=icon("paint-brush"),width="100%"),
                                 p(strong("Plot saving options:")),
                                 helpText("Recommends larger width and height values when plots for Pearson correlation matrix and PCA.", style = 'color:blue'),
                                 sliderInput("sliderwid","Plot width",
                                             min = 4,max = 20,value = 6),
                                 sliderInput("sliderhei","Plot height",
                                             min = 4,max = 20,value = 4),
                                 #   checkboxGroupInput("exporttype","Export format",
                                 #                       choices = list("Vector-PDF" = 1,
                                 #                                      "Bitmap-PNG" = 2,
                                 #                                      "Bitmap-TIFF" = 3)),
                                 downloadButton("downloadPlot", label="Download Current Plot",
                                                icon=icon("download"),width="100%"),
                                 br(),
                                 h4(strong("Ratio distribution plots settings:")),
                                 checkboxGroupInput("ratio_plot_selection",
                                                    "Choose group/groups you want to show in ratio distribution plot:",
                                                    choices = " ", selected = " "),
                                 checkboxGroupInput("dist_correction",
                                                    "Choose whether you want to do distribution correction:",
                                                    choices = "Correction"),
                                 actionButton("plot2",label="Plot for Ratio Distribution",
                                              icon=icon("paint-brush"),width="100%"),
                                 sliderInput("sliderwid2","Plot width",
                                             min = 4,max = 20,value = 6),
                                 sliderInput("sliderhei2","Plot height",
                                             min = 4,max = 20,value = 4),
                                 downloadButton("downloadPlot2", label="Download Current Plot",
                                                icon=icon("download"),width="100%"),
                                 downloadButton("downloadData4", label = "Download corrected ratio dataset",
                                                icon = icon("download"), width = "100%")

                             ),
                             mainPanel(
                                 h4(strong("Plot Area")),
                                 plotOutput("Plotting"),
                                 DT::dataTableOutput("setup"),
                                 h4(strong("Area for Ratio Distribution Plots")),
                                 plotOutput("Plotting2")
                             )
                         )
                     )
            )},# tabItem

            ## Biomarker Discovery
            {tabItem(tabName = "Biomarkers",
                     fluidPage(
                         titlePanel(strong("Discovery of Changes")),
                         sidebarLayout(
                             position = "left",
                             sidebarPanel(
                                 p(strong("Settings for finding significantly changed proteins")),
                                 selectInput(inputId = "select_group",
                                             label = "Select group",
                                             choices = ""),
                                 textInput("R_cutoff", "Set ratio cutoff",
                                           value=1.4),
                                 textInput("p_cutoff", "Set p-value cutoff",
                                           value=0.05),
                                 actionButton(inputId = "upload_cutoff",label = "Submit cutoff settings",
                                              icon=icon("upload"),width="100%"),
                                 downloadButton("downloadData3", label="Download Significantly Changed Data",
                                                icon=icon("download")),
                                 selectInput(inputId = "plotType2",
                                             label = "Select plot type:",
                                             choices = c("Valcano Plot",
                                                         "Intensity curve with changes highlighted",
                                                         "Plot for Up-regulated","Plot for Down-regulated")),
                                 helpText("*For up-/down-regulated proteins plot only:", style = 'color:blue'),
                                 textInput("TOPx",label = "Assign how many proteins shown in the plot:",value = 50),
                                 actionButton("plot3",label="Plot",icon=icon("paint-brush"),width="100%"),
                                 sliderInput("sliderwid3","Plot width",
                                             min = 4,max = 20,value = 6),
                                 sliderInput("sliderhei3","Plot height",
                                             min = 4,max = 20,value = 4),
                                 downloadButton("downloadPlot3", label="Download Current Plot",
                                                icon=icon("download"))

                             ),
                             mainPanel(
                                 h4(strong("Table Area")),
                                 DT::dataTableOutput("sign_contents"),
                                 h4(strong("Plot Area")),
                                 plotOutput("Plotting3")
                             )
                         )
                     )
            ) #tabItem
            }

        ) # tabItems
    ) #dashboardBody
) #dashboardPage




### Define server logic ----
server <- function(input, output, session) {

    #### Data Raw file processing & database searching ###
    global_raw_folder <- reactiveValues(datapath = getwd())

    raw_folder <- reactive({
        return(parseDirPath(volumes, input$raw_folder))
    })

    output$raw_folder <- renderText({
        global_raw_folder$datapath
    })

    observeEvent(input$raw_folder, {

        if(Sys.info()["sysname"] != "Darwin")
        {
            selected_folder <- rchoose.dir(caption = "Choose folder containing .raw files",default = "~")
        }else
        {
            selected_folder <- tcltk::tk_choose.dir(caption = "Choose folder containing .raw files",default = "~")
        }
        if(length(selected_folder)>0)
        {
            if(!is.na(selected_folder))
            {
                selected_folder <- gsub("\\\\","/",selected_folder)
                global_raw_folder$datapath <- paste0(selected_folder,"/")
            }
        }
    })
    global_msgf_folder <- reactiveValues(datapath = getwd())

    msgf_folder <- reactive({
        return(parseDirPath(volumes, input$msgf_folder))
    })

    output$msgf_folder <- renderText({
        global_msgf_folder$datapath
    })


    observeEvent(input$msgf_folder, {

        if(Sys.info()["sysname"] != "Darwin")
        {
            selected_folder <- rchoose.dir(caption = "Choose folder containing the msgfplus java file",default = "~")
        }else
        {
            selected_folder <- tcltk::tk_choose.dir(caption = "Choose folder containing the msgfplus java file",default = "~")
        }

        if(length(selected_folder)>0)
        {
            if(!is.na(selected_folder))
            {
                selected_folder <- gsub("\\\\","/",selected_folder)
                global_msgf_folder$datapath <- paste0(selected_folder,"/")
            }
        }
    })

    #### .raw to .mzXML
    observeEvent(input$DBSGoButton, {
        selected_modi <- match(input$frag_modi, modi_names)
        currtent_modi <- modification_list[selected_modi]
        fasta_dir <- list.files(global_raw_folder$datapath)
        fasta_name <- fasta_dir[grep('.fasta', fasta_dir)]
        msgfpar <- msgfPar(tda = input$add_decoys, # add_decoys = true
                           tolerance = paste(input$tolerance, 'ppm', sep = ' '),
                           isotopeError = as.numeric(unlist(strsplit(input$iso_error,','))),
                           fragmentation = input$fragment,
                           instrument = input$instrument,
                           enzyme = input$enzyme,
                           protocol = input$protocol,
                           ntt = as.numeric(input$ntt), # tryptic = fully
                           chargeRange = as.numeric(unlist(strsplit(input$chargeRange,','))),
                           database = paste(global_raw_folder$datapath, fasta_name, sep = '/'),
                           lengthRange = as.numeric(unlist(strsplit(input$lengthRange,','))),
                           matches = as.numeric(input$matches), # matches_per_spec = 1
                           modification = list(
                               nMod = as.numeric(input$nmod), # max_mods = 3
                               modifications=currtent_modi
                           )
        )
        DBS <- DBsearching(path = global_raw_folder$datapath, msgfpar = msgfpar,
                           msgfpath = paste(global_msgf_folder$datapath,'MSGFPlus.jar',sep = '/'))
        output$DBsearchingNotice <- renderText({
            'Database searching is finished!'
        })
    })




    #### Spectrum Report Generation ####

    global_mzid_folder <- reactiveValues(datapath = getwd())

    mzid_folder <- reactive({
        return(parseDirPath(volumes, input$mzid_folder))
    })

    output$mzid_folder <- renderText({
        global_mzid_folder$datapath
    })

    observeEvent(input$mzid_folder, {

        if(Sys.info()["sysname"] != "Darwin")
        {
            selected_folder <- rchoose.dir(caption = "Choose folder containing .mzid files",default = "~")
        }else
        {
            selected_folder <- tcltk::tk_choose.dir(caption = "Choose folder containing .mzid files",default = "~")
        }
        if(length(selected_folder)>0)
        {
            if(!is.na(selected_folder))
            {
                selected_folder <- gsub("\\\\","/",selected_folder)
                global_mzid_folder$datapath <- paste0(selected_folder,"/")
            }
        }
    })



    Protein <- reactive({
        req(input$IDPprotein)
        ext <- tools::file_ext(input$IDPprotein$name)
        switch(ext,
               csv = read.csv(input$IDPprotein$datapath),
               tsv = read.csv(input$IDPprotein$datapath, sep="\t",fileEncoding="windows-1252"),
               validate("Invalid file; Please upload a .csv or .tsv file")
        )
    })

    Peptide <- reactive({
        req(input$IDPpeptide)
        ext <- tools::file_ext(input$IDPpeptide$name)
        switch(ext,
               csv = read.csv(input$IDPpeptide$datapath),
               tsv = read.csv(input$IDPpeptide$datapath, sep="\t",fileEncoding="windows-1252"),
               validate("Invalid file; Please upload a .csv or .tsv file")
        )
    })

    Spectrum <- reactive({
        req(input$IDPspectrum)
        ext <- tools::file_ext(input$IDPspectrum$name)
        switch(ext,
               csv = read.csv(input$IDPspectrum$datapath),
               tsv = read.csv(input$IDPspectrum$datapath, sep="\t",fileEncoding="windows-1252"),
               validate("Invalid file; Please upload a .csv or .tsv file")
        )
    })

    observeEvent(input$SpecGoButton, {
        SpecRepoGen(protein = Protein(), peptide = Peptide(), spectrum = Spectrum(),
                    mziddir = global_mzid_folder$datapath, MSGFdir = global_msgf_folder$datapath,
                    output_name = input$SpecName)
    })

    #### IonStarStat ####
    ## Frame Generation##
    dbStat <- reactive({
        req(input$StatUploadSEIVE)
        ext <- tools::file_ext(input$StatUploadSEIVE$name)
        switch(ext,
               sdb = dbConnect(dbDriver("SQLite"),dbname = input$StatUploadSEIVE$datapath),
               validate("Invalid file; Please upload a .sdb file")
        )
    })

    spStat <- reactive({
        req(input$StatUploadSR)
        ext <- tools::file_ext(input$StatUploadSR$name)
        switch(ext,
               csv = read.csv(input$StatUploadSR$datapath)
        )
    })

    testStat2 <- eventReactive(input$StatGoButton2,FrameGen(dbStat(),spStat(),input$StatFileNumber,input$StatScanNumber,
                                                            input$StatProAccession, input$StatPepSeq))
    output$StatFrameNotice <- renderText({
        testStat2()$notice
    })
    output$message1 <- renderText({
        testStat2()$message1
    })
    output$message2 <- renderText({
        testStat2()$message2
    })

    output$StatFrameDownload <- downloadHandler(
        filename = function() {
            paste('Annotated_Frames-', gsub(" ","-",date()), '.csv', sep='')
        },
        content = function(con) {
            write.csv(testStat2()$framelist, row.names = FALSE, con)
        }
    )
    output$StatSampleIDDownload <- downloadHandler(
        filename = function() {
            paste('Sample_ID-', gsub(" ","-",date()), '.csv')
        },
        content = function(con) {
            write.csv(testStat2()$sampleid, con, sep='', row.names = FALSE)
        }
    )

    ## Protein Quantification ##

    framelist <- reactive({
        req(input$StatUploadFrame)
        ext <- tools::file_ext(input$StatUploadFrame$name)
        switch(ext,
               csv = read.csv(input$StatUploadFrame$datapath, check.names = FALSE, stringsAsFactors = FALSE))
    })
    sampleid <- reactive({
        req(input$StatUploadSampleID)
        ext <- tools::file_ext(input$StatUploadSampleID$name)
        switch(ext,
               csv = read.csv(input$StatUploadSampleID$datapath)
        )
    })
    database <- reactive({
        req(input$StatUploadDatabase)
        ext <- tools::file_ext(input$StatUploadDatabase$name)
        switch(ext,
               fasta = read.fasta(input$StatUploadDatabase$datapath, seqtype = "AA", as.string = TRUE),
               validate("Invalid file; Please upload a .fasta file")
        )
    })

    test <- eventReactive(input$calculate,
                          Ratio_p(quan_file(),group_file(),
                                  decoy = input$decoy, control_group = input$ctrlGroup,
                                  test_type = input$testing, equalVar = input$ttestopt))

    output$notice1 <- renderText({
        test()$notice
    })

    testStat3 <- eventReactive(input$StatGoButton4,
                               IonStar_DPpipeline(raw = framelist(), cond = sampleid(), norm_method = input$Norm_method, frameOR=input$Frame_OR,
                                                  pepOR=input$Peptide_OR, quan_method = input$Quan_method))
    output$noticeStat8 <- renderText({
        testStat3()$notice
    })

    QC <- eventReactive(input$StatGoButton4,
                        Quality_check(testStat3()$protein, group = sampleid()))

    #    if(is.null(input$Share_rm)){
    #      ProQuant(framelist(),sampleid(),rm = input$Share_rm,
    #              norm_method = input$Norm_method, quan_method = input$Quan_method,
    #              outlier = input$Outlier_rejection)}else{
    #                ProQuant(framelist(),sampleid(),database(),rm = input$Share_rm,
    #                         norm_method = input$Norm_method, quan_method = input$Quan_method,
    #                         outlier = input$Outlier_rejection)
    #              }

    output$downloadDataStat4 <- downloadHandler(
        filename = function() {
            paste('Quan_data-', gsub(" ","-",date()), '.csv', sep='')
        },
        content = function(con) {
            write.csv(testStat3()$protein, con)
        }
    )
    output$downloadDataStat5 <- downloadHandler(
        filename = function() {
            paste('Pep_data-', gsub(" ","-",date()), '.csv', sep='')
        },
        content = function(con) {
            write.csv(testStat3()$peptide, con)
        }
    )

    ## Quality Check ##
    output$IGCV <- renderPlot({
        QC()$CVplot
    })
    output$PRank <- renderPlot({
        QC()$PRplot
    })


    #### Processing ####
    {

        output$downloadManual <- downloadHandler(
            filename <- function(){
                paste("Manual","pdf",sep = ".")
            },

            content <- function(file){
                file.copy("Manual.pdf",file)
            },
            contentType = "application/pdf"
        )


        ## input quan_file and group_file

        quan_file <- reactive({
            req(input$file1)
            ext <- tools::file_ext(input$file1$name)
            switch(ext,
                   csv = read.csv(input$file1$datapath, row.names = 1),
                   tsv = read.csv(input$file1$datapath, sep="\t",fileEncoding="windows-1252", row.names = 1),
                   validate("Invalid file; Please upload a .csv or .tsv file")
            )
        })

        group_file <- reactive({
            req(input$file2)
            ext <- tools::file_ext(input$file2$name)
            switch(ext,
                   csv = read.csv(input$file2$datapath),
                   tsv = read.csv(input$file2$datapath, sep="\t",fileEncoding="windows-1252"),
                   validate("Invalid file; Please upload a .csv or .tsv file")
            )
        })

        output$contents <- DT::renderDataTable({
            group_file()
        })



        test <- eventReactive(input$calculate,
                              Ratio_p(quan_file(),group_file(),
                                      decoy = input$decoy, control_group = input$ctrlGroup,
                                      test_type = input$testing, equalVar = input$ttestopt))

        output$notice1 <- renderText({
            test()$notice
        })

        output$downloadData <- downloadHandler(
            filename = function() {
                paste('quan_results-', gsub(" ","-",date()), '.csv', sep='')
            },
            content = function(con) {
                write.csv(test()$quan_results, con)
            }
        )
        output$downloadData2 <- downloadHandler(
            filename = function() {
                paste('ave_ratios-', gsub(" ","-",date()), '.csv', sep='')
            },
            content = function(con) {
                write.csv(test()$ave_ratio, con)
            }
        )
        output$downloadData_all <- downloadHandler(
            filename = function() {
                paste('quan&ratios-', gsub(" ","-",date()), '.csv', sep='')
            },
            content = function(con) {
                write.csv(test()$all, con)
            }
        )

    }
    #### Visualization ####

    # plot for all
    test2 <- eventReactive(input$plot, plot_for_all(
        quan=test()$quan_results, group=test()$group_ordered,
        plot_selection=input$plotType,Group1 = input$inter_group1,
        Group2= input$inter_group2))
    output$Plotting <- renderPlot({
        test2()
    })

    output$downloadPlot <- downloadHandler(
        filename = function() {
            paste('Plot-', gsub(" ","-",date()),'.png', sep='')
        },
        content = function(con4) {
            device <- function(..., width, height) grDevices::png(..., width = input$sliderwid, height = input$sliderhei, res = 300, units = "in")
            ggsave(con4, plot=test2(),device = device)
        }
    )

    #update seletions
    observe({
        input$calculate
        x <- test()$group_char[test()$group_char != test()$control_group]

        if (is.null(x))
            x <- character(0)

        updateCheckboxGroupInput(session, "ratio_plot_selection",
                                 label = "Choose group/groups you want to show in ratio distribution plot:",
                                 choices = x,
                                 selected = x[1]
        )
        updateSelectInput(session, inputId = "select_group",
                          label = "Select group",
                          choices = x)
    })

    # ratio distribution (density) plot
    test3 <- eventReactive(input$plot2, plot_ratio_distribution(
        ave_ratio = test()$ave_ratio,group = test()$group_ordered,
        selected = input$ratio_plot_selection, dist_corr = input$dist_correction))
    output$Plotting2 <- renderPlot({
        test3()$plotting
    })

    output$downloadPlot2 <- downloadHandler(
        filename = function() {
            paste('ratio_plot-', gsub(" ","-",date()), '.png', sep='')
        },
        content = function(con2) {
            device <- function(..., width, height) grDevices::png(..., width = input$sliderwid2, height = input$sliderhei2, res = 300, units = "in")
            ggsave(con2, plot=test3()$plotting,device = device)
        }
    )

    output$downloadData4 <- downloadHandler(
        filename = function() {
            paste('corrected_ratios-', gsub(" ","-",date()), '.csv', sep='')
        },
        content = function(con) {
            write.csv(test3()$correction_ratio, con)
        }
    )

    #########Discovery of Changes#############
    # finding significantly changed proteins
    test4 <- eventReactive(input$upload_cutoff, sign_changes(
        quan_all=test()$all, test_type=test()$test_type,
        chosen_group=input$select_group, R_cutoff=input$R_cutoff, p_cutoff=input$p_cutoff))
    output$sign_contents <- DT::renderDataTable({
        input$upload_cutoff
        test4()$quan_changed
    })
    output$downloadData3 <- downloadHandler(
        filename = function() {
            paste('sign-changed', gsub(" ","-",date()), '.csv', sep='')
        },
        content = function(con3) {
            write.csv(test4()$quan_changed, con3)
        }
    )
    # plot for all 2
    test5 <- eventReactive(input$plot3,plot_for_all2(
        sig_list=test4(), quan=test()$quan_results,
        plot_selection=input$plotType2, TOPx=input$TOPx))
    output$Plotting3 <- renderPlot({
        test5()
    })
    output$downloadPlot3 <- downloadHandler(
        filename = function() {
            paste('sign_plot-', gsub(" ","-",date()), '.png', sep='')
        },
        content = function(con3) {
            device <- function(..., width, height) grDevices::png(..., width = input$sliderwid3, height = input$sliderhei3, res = 300, units = "in")
            ggsave(con3, plot=test5(),device = device)
        }
    )
}


# Run the application
shinyApp(ui = ui, server = server)
JunQu-Lab/UHRIonStarApp documentation built on July 2, 2022, 12:47 a.m.