modify this code so if the web browser is refreshed, we dont loose the data from the…
- User
modify this code so if the web browser is refreshed, we dont loose the data from the current session: packages <- c( "tidyverse", "shiny", "shinydashboard", "shinyFiles", "shinyWidgets", "shinythemes","RColorBrewer","ggthemes","plotly","shinyBS","processx" )
#Now load or install&load all packages package.check <- lapply( packages, FUN = function(x) { if (!require(x, character.only = TRUE)) { #install.packages(x, dependencies = TRUE) library(x, character.only = TRUE,lib.loc="/home/pxl10/R/x86_64-pc-linux-gnu-library/4.2/") } } )
options(shiny.port = 3142) options(shiny.host = "10.50.156.93")
loci <- "" sample_list <- ("")
ui <- dashboardPage( skin = "red", dashboardHeader(title = "Nanopore TB tNGS Assay",titleWidth = 300),
###side tab setup dashboardSidebar( width = 300,
br(),br(), ### shinyFiles::shinyDirButton("test_dir_select",label = "Select Nanopore Run Folder",title = "Directory selection",icon = shiny::icon("folder")), shiny::htmlOutput("test_dir_select_ready") ,br(),br(), fileInput(inputId = "file_sample",label = "Select Sample Sheet",multiple = FALSE), br(), selectizeInput(inputId = "workflow",label = "Select Amplicon Workflow",choices = c("Main AR Targets", "Extended AR Targets"),multiple = FALSE),br(), selectizeInput(inputId = "flowcell",label = "Flow Cell type",choices = c("R9","R10"),multiple = FALSE),br(), textInput("run_name", label="Enter Run Name", "", width = "600px"),br(),br(),br(),br(),br(),br(),br(),br(), bsButton(inputId = "go", width = "250px",label = " Start Pipeline", icon = icon("play-circle"), style = "success") ),dashboardBody( fluidRow( tabBox( # The id lets us use input$tabset1 on the server to find the current tab id = "tabset1", height = "1100px",width=12, tabPanel(title = "tNGS AMR Targets", # Select sample fluidRow( column(2, (selectInput(inputId = "sample", label = "Sample:",choices = sample_list, selected = sample_list[1])))), fluidRow( column(2, h3("Loci Status:"), tableOutput('table'),br(),
actionButton(inputId = "markdown_display", label = "Show Full Report", width = "300px",height = "100px") ,br(), h3("Time of last Analyses:"),br(), tableOutput('stamp')), column(9,offset = 0, plotlyOutput("plot", height = "800px", width = "100%")))), ))) )
#################################################################################################################################### #################################################################################################################################### ####################################################################################################################################
####### server side of things ####### ready_to_start <- 0 makeReactiveBinding("ready_to_start") server <- function(input, output, session) { whichbutton <- reactiveVal(TRUE) cancelbutton <- reactiveVal(TRUE) pid <- 0
###download button###
not working
def_reports_roots <- c(home = "/") shinyFileChoose(input, 'file_outputs', roots = def_reports_roots)
observeEvent(inputdownload_button, { print (paste("pushed...")) outputfile_outputs <- downloadHandler( filename <- function() { paste("output", "zip", sep=".") },
content <- function(file) { file.copy("/home/pxl10/out.zip", file) }, contentType = "application/zip" ) })
start/stop button actions
Cancel Button blocks
observeEvent(input$go, { if (whichbutton()) { showModal(modalDialog( title = "Retrieving data file", h3("Please wait for file to be generated!"), easyClose = FALSE, footer = tagList( actionButton("cancel", "Cancel")))) } whichbutton(!whichbutton())
})Cancel button actions
observeEvent(inputcancel, { whichbutton(!whichbutton()) cancelbutton(!cancelbutton()) ready_to_start <- 0 updateButton(session,inputId = "go",label = " Start Pipeline",icon = icon("play-circle"),style = "success") system(paste("kill -9 ",pid)) removeModal() showModal(modalDialog( title = "Success!", paste0("The pipeline has been successfully terminated."), easyClose = TRUE, footer = NULL )) sessionreload() path <- "NULL"
})
select directory button
def_roots <- c(home = "/local") shinyFiles::shinyDirChoose(input, 'test_dir_select', roots = def_roots)
test_dir_select_ready <- shiny::reactive({ if(length(inputtest_dir_select) == 1) { path <- "Directory not yet selected" } else { path <- file.path( shinyFiles::parseDirPath(def_roots, inputtest_dir_select) ) } return(path) }) output$test_dir_select_ready <- shiny::renderUI({ shiny::HTML("<font color="white">", test_dir_select_ready(), "") })Select sample sheet button
def_sheet_roots <- c(home = "/") shinyFileChoose(input, 'file_sample', roots = def_sheet_roots) sample_sheet_ready <- shiny::reactive({ if(length(inputfile_sample) == 1) { path_sheet <- "Sample Sheet not selected" } else { path_sheet <- file.path( shinyFiles::parseFilePaths(def_sheet_roots, inputfile_sample)datapath ) } return(path_sheet) }) outputsample_sheet_ready <- shiny::renderUI({ shiny::HTML("<font color="white">", sample_sheet_ready(), "") })
Trigger event Start/Stop Button
observe({ if (!whichbutton()) {
if(length(input$file_sample) == 0) { samplesheet <- "NULL" } else { samplesheet <- input$file_sample[4] ### need to check integrity of the sample sheet } if(length(input$test_dir_select) == 1) { path <- "NULL" } else { path <- file.path( shinyFiles::parseDirPath(def_roots, input$test_dir_select) ) } if (input$workflow == "Main AR Targets") { xworkflow <- "main_line" } else { xworkflow <- "extended" } if (input$run_name == "") { ##my_run_name <- "NULL" ### get run name from fasq path ### parts <- strsplit(path, "/")[[1]] my_run_name <- parts[4] fn <- paste0("/local/tNGS_TB/FASTQ/",my_run_name,"/locus_depth.txt") } else { my_run_name <- input$run_name fn <- paste0("/local/tNGS_TB/FASTQ/",my_run_name,"/locus_depth.txt") } # verify if fastq path given. if true, close and start pipeline if(path == "NULL") { whichbutton(!whichbutton()) # show pop-up ... showModal(modalDialog( title = "Oh no!", paste0("You have not selected a valid MinION FastQ repository, silly person!"), easyClose = TRUE, footer = NULL )) } else { updateButton(session,inputId = "go",label = " Stop Pipeline",icon = icon("stop-circle"),style = "danger") timestamp <- paste0("/local/tNGS_TB/FASTQ/",my_run_name,"/timestamp.txt") loci <- paste0("/local/tNGS_TB/FASTQ/",my_run_name,"/Loci_status_main.txt") print (paste(timestamp)) rundir <- (paste0("/local/tNGS_TB/FASTQ/",my_run_name)) if (dir.exists(rundir)) { system(paste("rm -r",rundir)) } if(samplesheet != "NULL") { sheet_renamed <- paste0("sample_sheet_",my_run_name,".txt") system(paste0("cp ",samplesheet," /local/tNGS_TB/sample_sheet_tmp/",sheet_renamed)) #system(paste("cp ",samplesheet,sheet_renamed)) #system (paste("rm",samplesheet)) samplesheet <- sheet_renamed } # Open the output file in write mode print(paste("/local/tNGS_TB/Real-time_wrapper/Amplicon_RT_analyzer_V0.4.3.pl -FASTQ", path ,"-Sheet",samplesheet,"-RUN", my_run_name," -Kit Auto -Flowcell", input$flowcell,"-Workflow", xworkflow,">","/local/tNGS_TB/Rlog.txt")) p <- process$new("/local/tNGS_TB/Real-time_wrapper/Amplicon_RT_analyzer_V0.4.3.pl",c("-FASTQ", path ,"-Sheet", samplesheet,"-RUN", my_run_name,"-Kit", "Auto", "-Flowcell", input$flowcell,"-Workflow", xworkflow,">","/local/tNGS_TB/Rlog.txt")) pid <<- p$get_pid() print(pid) ready_to_start <<- 2 } if ((!whichbutton()) && (ready_to_start==2)) {data_timestamp <- reactiveFileReader( intervalMillis = 100, session = NULL, filePath = timestamp, readFunc = function(filePath) { read.csv(filePath,header = TRUE, stringsAsFactors=FALSE) }
) loci_data_manipulated <- reactiveFileReader( intervalMillis = 100, session = NULL, filePath = loci, readFunc = function(filePath) { read.csv(filePath,header = TRUE, stringsAsFactors=FALSE) } )
observeEvent(inputmarkdown_display, { #filename <- paste0("/local/tNGS_TB/FASTQ/",my_run_name,"/",inputsample,"_Report.pdf") #
report <- paste0("/local/tNGS_TB/FASTQ/") filename <- paste0("my_pdf_resource/",my_run_name,"/",input$sample,"_Report.pdf") print (paste("xxxx ",filename)) addResourcePath(prefix = "my_pdf_resource", directoryPath = report) showModal(modalDialog(size="l",renderUI({ tags$iframe(style="height:650px; width:100%", src = filename)}), easyClose = TRUE))})
## wait for file to exists observe({ if ((!file.exists(fn)) && !whichbutton() && ready_to_start==2) { invalidateLater(1000, session) } ## when file present, if ((file.exists(fn)) && !whichbutton() && ready_to_start==2) { removeModal() data_manipulated <- reactiveFileReader( intervalMillis = 100, session = NULL, filePath = fn, readFunc = function(filePath) { read.csv(filePath,header = TRUE, stringsAsFactors=FALSE) } ) output$stamp <- renderTable({ data_timestamp() }) output$table <- renderTable({ xdata <- subset(loci_data_manipulated(), sample %in% input$sample) xdata[,3] <- as.integer(xdata[,3]) data <- xdata[,2:4] }) sample_original <- read.csv(fn, header = TRUE, stringsAsFactors=FALSE) sample_list <- unique(sample_original$sample) updateSelectInput(session, inputId = "sample", choices = sample_list, selected = sample_list[1]) ### Original target plot # Replace the `renderPlot()` with the plotly version output$plot <- renderPlotly({ # Convert the existing ggplot2 to a plotly plot ggplotly({ data <- subset(data_manipulated(), sample %in% input$sample ) p <- ggplot(data, aes(x = position, y = depth, group = sample, colour = gene)) + geom_line(linewidth=.3) + facet_wrap( ~ gene, ncol=4, nrow=4, scales = "free", shrink = FALSE) + theme_few() + theme(legend.position="none", strip.text = element_text(face="bold", size = 14), plot.title = element_text(face = "bold"), panel.spacing.y = unit(-0.4, "lines"), panel.spacing.x = unit(-0.4, "lines")) + scale_color_tableau("Tableau 20") + ylab("") + xlab("") + ggtitle(paste('Sample ',input$sample, sep='')) }) %>% config(p, displaylogo = FALSE) }) } })}
} ## if whichbutton
}) ## end observe loop
observe ({ if ((whichbutton()) && ready_to_start==2) { ### when stop button is pressed
if (pid > 0) { system(paste("kill -9 ",pid)) pid <<- 0 } ready_to_start <<- 0 updateButton(session,inputId = "go",label = " Start Pipeline",icon = icon("play-circle"),style = "success") showModal(modalDialog( title = "Success!", paste0("The pipeline has been successfully terminated."), easyClose = TRUE, footer = NULL )) ## stop pipeline at the system level session$reload() path <- "NULL" }})
} shinyApp(ui, server)
- Assistant
To prevent data loss when the web browser is refreshed, you can use the
reactiveValuesfunction to store reactive values in memory. Then, you can use theonSessionEndedfunction to save the reactive values to a file when the session ends, and theonSessionInitializedfunction to load the reactive values from the file when the session starts. Here's an example of how to modify the code:packages <- c( "tidyverse", "shiny", "shinydashboard", "shinyFiles", "shinyWidgets", "shinythemes","RColorBrewer","ggthemes","plotly","shinyBS","processx" ) #Now load or install&load all packages package.check <- lapply( packages, FUN = function(x) { if (!require(x, character.only = TRUE)) { #install.packages(x, dependencies = TRUE) library(x, character.only = TRUE,lib.loc="/home/pxl10/R/x86_64-pc-linux-gnu-library/4.2/") } } ) options(shiny.port = 3142) options(shiny.host = "10.50.156.93") # Initialize reactive values rv <- reactiveValues( loci = "", sample_list = "", whichbutton = TRUE, cancelbutton = TRUE, pid = 0, ready_to_start = 0, data_manipulated = NULL, data_timestamp = NULL, loci_data_manipulated = NULL, output_file = NULL ) # Save reactive values to file on session end onSessionEnded(function() { saveRDS(rv, "my_reactive_values.rds") }) # Load reactive values from file on session start onSessionInitialized(function() { if (file.exists("my_reactive_values.rds")) { rv_old <- readRDS("my_reactive_values.rds") rv$loci <- rv_old$loci rv$sample_list <- rv_old$sample_list rv$whichbutton <- rv_old$whichbutton rv$cancelbutton <- rv_old$cancelbutton rv$pid <- rv_old$pid rv$ready_to_start <- rv_old$ready_to_start rv$data_manipulated <- rv_old$data_manipulated rv$data_timestamp <- rv_old$data_timestamp rv$loci_data_manipulated <- rv_old$loci_data_manipulated rv$output_file <- rv_old$output_file } }) ui <- dashboardPage( skin = "red", dashboardHeader(title = "Nanopore TB tNGS Assay",titleWidth = 300), ###side tab setup dashboardSidebar( width = 300, br(),br(), ### shinyFiles::shinyDirButton("test_dir_select",label = "Select Nanopore Run Folder",title = "Directory selection",icon = shiny::icon("folder")), shiny::htmlOutput("test_dir_select_ready") ,br(),br(), fileInput(inputId = "file_sample",label = "Select Sample Sheet",multiple = FALSE), br(), selectizeInput(inputId = "workflow",label = "Select Amplicon Workflow",choices = c("Main AR Targets", "Extended AR Targets"),multiple = FALSE),br(), selectizeInput(inputId = "flowcell",label = "Flow Cell type",choices = c("R9","R10"),multiple = FALSE),br(), textInput("run_name", label="Enter Run Name", "", width = "600px"),br(),br(),br(),br(),br(),br(),br(),br(), bsButton(inputId = "go", width = "250px",label = " Start Pipeline", icon = icon("play-circle"), style = "success") ), dashboardBody( fluidRow( tabBox( # The id lets us use input$tabset1 on the server to find the current tab id = "tabset1", height = "1100px",width=12, tabPanel(title = "tNGS AMR Targets", # Select sample fluidRow(column(2, (selectInput(inputId = "sample", label = "Sample:",choices = rv$sample_list, selected = rv$
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.