library(shiny) library(shinyjs) library(shinythemes) library(shinyBS) library(plotly) library(DT) library(QTLseqr) library(data.table) library(dplyr) library(tidyr) library(vcfR) library(ggplot2) library(dbscan) library(factoextra) library(cluster) library(viridis) options(shiny.maxRequestSize = 100 * 1024^2) # Modified qtlseq function qtlseq <- function(input_csv = NULL, refAlleleFreq = 0.20, minTotalDepth = 100, maxTotalDepth = 400, minSampleDepth = 40, minGQ = 99, windowSize = NULL, popStruc = NULL, bulkSize = NULL, replications = 10000, intervals = c(95, 99), alpha = 0.01, save_plot = FALSE, save_csv = FALSE) { data <- read.csv(input_csv) output_table <- tempfile(fileext = ".table") write.table(data, file = output_table, sep = "\t", row.names = FALSE, quote = FALSE) col_data <- colnames(data[5:ncol(data)]) unique_samples <- unique(sub("\\..*", "", col_data)) HighBulk <- unique_samples[1] LowBulk <- unique_samples[2] df <- importFromGATK(file = output_table, highBulk = HighBulk, lowBulk = LowBulk) df_filt <- filterSNPs( SNPset = df, refAlleleFreq = refAlleleFreq, minTotalDepth = minTotalDepth, maxTotalDepth = maxTotalDepth, minSampleDepth = minSampleDepth, minGQ = minGQ ) df_filt <- runGprimeAnalysis( SNPset = df_filt, windowSize = windowSize, outlierFilter = "deltaSNP" ) df_filt1 <- runQTLseqAnalysis( SNPset = df_filt, windowSize = windowSize, popStruc = popStruc, bulkSize = bulkSize, replications = replications, intervals = intervals ) p <- ggplot(df_filt1, aes(x = POS / 1e6)) + geom_point(aes(y = deltaSNP), color = "blue", size = 0.5, alpha = 0.6) + geom_line(aes(y = tricubeDeltaSNP), color = "red", size = 0.8) + geom_line(aes(y = CI_95), color = "orange", linetype = "solid", size = 0.6) + geom_line(aes(y = -CI_95), color = "orange", linetype = "solid", size = 0.6) + geom_line(aes(y = CI_99), color = "green", linetype = "solid", size = 0.6) + geom_line(aes(y = -CI_99), color = "green", linetype = "solid", size = 0.6) + geom_hline(yintercept = c(-1, 0, 1), linetype = "dashed", color = "skyblue", alpha = 0.7) + facet_wrap(~CHROM, ncol = 4, scales = "free_x") + labs(x = "Position (Mb)", y = expression(Delta *"SNP-index"), title = "QTLseq Analysis: Delta SNP-index across Chromosomes") + theme_minimal(base_size = 12) + theme( strip.text = element_text(face = "bold", size = 10), axis.title = element_text(face = "bold"), plot.title = element_text(face = "bold", hjust = 0.5) ) if (save_plot) ggsave("deltaSNPIndex.png", plot = p, dpi = 600, width = 12, height = 10, units = "in") qtl_table <- getQTLTable(SNPset = df_filt1, alpha = alpha, export = save_csv, fileName = "BSA_QTLseq.csv") return(list(QTLseqResults = df_filt1, GprimeResults = df_filt, plot = p, qtl_table = qtl_table)) } # UI ui <- fluidPage( theme = shinytheme("cerulean"), useShinyjs(), tags$head( tags$style(HTML(" body { background-color: #f4f4f9; font-family: Arial, sans-serif; } .well { background-color: #ffffff; border: 1px solid #ddd; border-radius: 8px; padding: 20px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); } .btn-primary { background-color: #4CAF50; border-color: #4CAF50; } .btn-primary:hover { background-color: #45a049; } h3 { color: #333; font-weight: bold; } .infographic { border: 2px solid #2196F3; border-radius: 15px; padding: 20px; margin: 15px 0; background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%); box-shadow: 0 4px 8px rgba(0,0,0,0.1); } .info-header { color: #1976d2; border-bottom: 2px solid #64b5f6; padding-bottom: 10px; margin-bottom: 15px; } .ml-card { background: white; border-radius: 10px; padding: 15px; margin: 10px 0; box-shadow: 0 2px 4px rgba(0,0,0,0.1); border-left: 4px solid #4CAF50; } ")) ), titlePanel("QTLseq Shiny App: Advanced BSA with Machine Learning Insights"), sidebarLayout( sidebarPanel( fileInput("input_csv", "Upload Input CSV", accept = ".csv"), numericInput("refAlleleFreq", "Reference Allele Frequency", value = 0.20, min = 0, max = 1, step = 0.01), bsTooltip("refAlleleFreq", "Fraction of reads matching reference allele", placement = "right"), numericInput("minTotalDepth", "Min Total Depth", value = 100), bsTooltip("minTotalDepth", "Minimum total read depth for SNPs", placement = "right"), numericInput("maxTotalDepth", "Max Total Depth", value = 400), numericInput("minSampleDepth", "Min Sample Depth", value = 40), numericInput("minGQ", "Min GQ", value = 99), numericInput("windowSize", "Window Size", value = 5e5), selectInput("popStruc", "Population Structure", choices = c("F2", "RIL", "BC1")), textInput("bulkSize", "Bulk Size (e.g., 20,20)", value = "20,20"), numericInput("replications", "Replications", value = 10000), textInput("intervals", "Intervals (e.g., 95,99)", value = "95,99"), numericInput("alpha", "Alpha", value = 0.01, min = 0, max = 1, step = 0.01), actionButton("runAnalysis", "Run Analysis", class = "btn-primary") ), mainPanel( tabsetPanel( tabPanel("QTLseq Results", plotlyOutput("deltaPlot"), downloadButton("downloadPlot", "Download Plot"), DTOutput("qtlTable"), downloadButton("downloadCSV", "Download QTL CSV") ), tabPanel("ML Insights", h3("Machine Learning Integrations for Enhanced BSA Analysis"), tabsetPanel( tabPanel("K-Means Clustering", div(class = "infographic", h4("🎯 Automated Region Clustering with K-Means", class = "info-header"), p("K-Means clustering automatically groups genomic regions based on their deltaSNP patterns, revealing natural groupings without manual threshold setting."), plotlyOutput("clusterPlot"), DTOutput("clusterSummary") ) ), tabPanel("Outlier Detection", div(class = "infographic", h4("🔍 DBSCAN Outlier SNP Detection", class = "info-header"), p("DBSCAN identifies statistical outliers that may represent key causative variants, sequencing artifacts, or novel biological phenomena worth investigating."), plotlyOutput("outlierPlot"), DTOutput("outlierTable") ) ), tabPanel("PCA Overview", div(class = "infographic", h4("📊 Genome-wide Pattern Analysis with PCA", class = "info-header"), p("Principal Component Analysis provides a big-picture view of genomic patterns, helping identify batch effects, population structure, or technical artifacts."), plotlyOutput("pcaPlot"), plotOutput("pcaVariancePlot") ) ) ) ), tabPanel("Advanced Visualizations", h3("Enhanced Interactive Infographics"), div(class = "infographic", h4("📈 Interactive Chromosome Explorer", class = "info-header"), p("Explore each chromosome individually with enhanced zoom and hover capabilities for detailed QTL region investigation."), selectInput("chromSelect", "Select Chromosome:", choices = NULL), plotlyOutput("chromosomePlot") ), div(class = "infographic", h4("🌊 3D DeltaSNP Landscape", class = "info-header"), p("Visualize the deltaSNP landscape across chromosomes in 3D, revealing spatial patterns and relationships between genomic regions."), plotlyOutput("threeDPlot") ) ) ) ) ) ) # Server server <- function(input, output, session) { results <- reactiveVal() observeEvent(input$runAnalysis, { req(input$input_csv) showNotification("Running QTLseq analysis...", type = "message") bulkSize_vec <- as.numeric(unlist(strsplit(input$bulkSize, ","))) intervals_vec <- as.numeric(unlist(strsplit(input$intervals, ","))) tryCatch({ res <- qtlseq( input_csv = input$input_csv$datapath, refAlleleFreq = input$refAlleleFreq, minTotalDepth = input$minTotalDepth, maxTotalDepth = input$maxTotalDepth, minSampleDepth = input$minSampleDepth, minGQ = input$minGQ, windowSize = input$windowSize, popStruc = input$popStruc, bulkSize = bulkSize_vec, replications = input$replications, intervals = intervals_vec, alpha = input$alpha ) results(res) showNotification("Analysis completed successfully!", type = "message") # Update chromosome selector chrom_choices <- unique(res$QTLseqResults$CHROM) updateSelectInput(session, "chromSelect", choices = chrom_choices) }, error = function(e) { showNotification(paste("Error:", e$message), type = "error") }) }) # QTLseq Plot output$deltaPlot <- renderPlotly({ req(results()) ggplotly(results()$plot, tooltip = c("x", "y", "CHROM")) %>% layout(height = 800) }) # Download Plot output$downloadPlot <- downloadHandler( filename = "deltaSNPIndex.png", content = function(file) { ggsave(file, plot = results()$plot, dpi = 600, width = 12, height = 10, units = "in") } ) # QTL Table output$qtlTable <- renderDT({ req(results()) datatable(results()$qtl_table, options = list(pageLength = 10, scrollX = TRUE), caption = "Significant QTL Regions") }) # Download CSV output$downloadCSV <- downloadHandler( filename = "BSA_QTLseq.csv", content = function(file) { write.csv(results()$qtl_table, file, row.names = FALSE) } ) # K-Means Clustering output$clusterPlot <- renderPlotly({ req(results()) df <- results()$QTLseqResults # Prepare data for clustering cluster_data <- df %>% select(POS, tricubeDeltaSNP) %>% drop_na() %>% sample_n(min(10000, nrow(.))) # Sample for performance # Perform K-Means Clustering set.seed(123) kmeans_result <- kmeans(cluster_data, centers = 3) # Add cluster assignment df_sample <- df %>% filter(row_number() %in% as.numeric(rownames(cluster_data))) %>% mutate(Cluster = as.factor(kmeans_result$cluster)) p <- ggplot(df_sample, aes(x = POS/1e6, y = tricubeDeltaSNP, color = Cluster, text = paste("CHROM:", CHROM, "
POS:", POS, "
Cluster:", Cluster))) + geom_point(alpha = 0.7, size = 2) + scale_color_viridis_d(option = "plasma") + labs(x = "Position (Mb)", y = "Tricube Delta SNP-index", title = "K-Means Clustering of Genomic Regions", subtitle = "Colors represent automated grouping based on deltaSNP patterns") + theme_minimal() + theme(legend.position = "bottom") ggplotly(p, tooltip = "text") %>% layout(height = 500) }) output$clusterSummary <- renderDT({ req(results()) df <- results()$QTLseqResults cluster_data <- df %>% select(POS, tricubeDeltaSNP) %>% drop_na() set.seed(123) kmeans_result <- kmeans(cluster_data, centers = 3) summary_df <- data.frame( Cluster = 1:3, Size = as.numeric(table(kmeans_result$cluster)), Center_Position = kmeans_result$centers[,1], Center_DeltaSNP = kmeans_result$centers[,2] ) datatable(summary_df, options = list(dom = 't'), caption = "Cluster Summary Statistics") }) # DBSCAN Outlier Detection output$outlierPlot <- renderPlotly({ req(results()) df <- results()$QTLseqResults # Prepare data dbscan_data <- df %>% select(POS, deltaSNP) %>% drop_na() %>% sample_n(min(5000, nrow(.))) # Sample for performance # Scale data scaled_data <- scale(dbscan_data) # Perform DBSCAN dbscan_result <- dbscan(scaled_data, eps = 0.5, minPts = 10) # Add outlier status df_sample <- df %>% filter(row_number() %in% as.numeric(rownames(dbscan_data))) %>% mutate(Outlier = ifelse(dbscan_result$cluster == 0, "Outlier", "Normal")) p <- ggplot(df_sample, aes(x = POS/1e6, y = deltaSNP, color = Outlier, text = paste("CHROM:", CHROM, "
POS:", POS, "
Status:", Outlier))) + geom_point(alpha = 0.7, size = 2) + scale_color_manual(values = c("Outlier" = "red", "Normal" = "blue")) + labs(x = "Position (Mb)", y = "Delta SNP-index", title = "DBSCAN Outlier Detection", subtitle = "Red points represent statistical outliers") + theme_minimal() + theme(legend.position = "bottom") ggplotly(p, tooltip = "text") %>% layout(height = 500) }) output$outlierTable <- renderDT({ req(results()) df <- results()$QTLseqResults dbscan_data <- df %>% select(POS, deltaSNP) %>% drop_na() scaled_data <- scale(dbscan_data) dbscan_result <- dbscan(scaled_data, eps = 0.5, minPts = 10) outlier_df <- df %>% filter(row_number() %in% as.numeric(rownames(dbscan_data))) %>% mutate(Outlier = ifelse(dbscan_result$cluster == 0, "Yes", "No")) %>% filter(Outlier == "Yes") %>% select(CHROM, POS, deltaSNP, tricubeDeltaSNP, REF_FRQ) datatable(outlier_df, options = list(pageLength = 5, scrollX = TRUE), caption = "Detected Outlier SNPs") }) # PCA Analysis output$pcaPlot <- renderPlotly({ req(results()) df <- results()$QTLseqResults # Sample data for PCA (for performance) pca_data <- df %>% group_by(CHROM) %>% sample_n(min(50, n())) %>% ungroup() %>% select(POS, REF_FRQ, deltaSNP) %>% drop_na() # Perform PCA pca_result <- prcomp(pca_data, scale. = TRUE) pca_df <- as.data.frame(pca_result$x) pca_df$CHROM <- df$CHROM[1:nrow(pca_df)] p <- ggplot(pca_df, aes(x = PC1, y = PC2, color = CHROM, text = paste("PC1: ", round(PC1, 2), "
PC2: ", round(PC2, 2)))) + geom_point(alpha = 0.7, size = 3) + scale_color_viridis_d(option = "magma") + labs(title = "PCA of Genomic Features", subtitle = "Each point represents a genomic region") + theme_minimal() ggplotly(p, tooltip = "text") %>% layout(height = 500) }) output$pcaVariancePlot <- renderPlot({ req(results()) df <- results()$QTLseqResults pca_data <- df %>% group_by(CHROM) %>% sample_n(min(50, n())) %>% ungroup() %>% select(POS, REF_FRQ, deltaSNP) %>% drop_na() pca_result <- prcomp(pca_data, scale. = TRUE) fviz_eig(pca_result, addlabels = TRUE, main = "PCA - Variance Explained by Principal Components", barfill = "#4CAF50", barcolor = "#4CAF50") + theme_minimal() }) # Chromosome-specific plot output$chromosomePlot <- renderPlotly({ req(results(), input$chromSelect) df <- results()$QTLseqResults chrom_df <- df %>% filter(CHROM == input$chromSelect) p <- ggplot(chrom_df, aes(x = POS/1e6, y = tricubeDeltaSNP, text = paste("Position:", POS, "
DeltaSNP:", round(tricubeDeltaSNP, 3)))) + geom_line(color = "red", size = 1) + geom_ribbon(aes(ymin = -CI_99, ymax = CI_99), fill = "green", alpha = 0.1) + geom_hline(yintercept = 0, linetype = "dashed", color = "gray") + labs(x = "Position (Mb)", y = "Tricube Delta SNP-index", title = paste("Chromosome", input$chromSelect, "Detailed View")) + theme_minimal() ggplotly(p, tooltip = "text") %>% layout(height = 400) }) # 3D Plot output$threeDPlot <- renderPlotly({ req(results()) df <- results()$QTLseqResults # Sample data for 3D plot plot_data <- df %>% group_by(CHROM) %>% sample_n(min(100, n())) %>% ungroup() plot_ly(plot_data, x = ~POS/1e6, y = ~as.numeric(factor(CHROM)), z = ~tricubeDeltaSNP, type = 'scatter3d', mode = 'markers', color = ~tricubeDeltaSNP, colors = viridis::viridis(100), marker = list(size = 3), text = ~paste("CHROM:", CHROM, "
POS:", POS, "
DeltaSNP:", round(tricubeDeltaSNP, 3))) %>% layout(scene = list( xaxis = list(title = 'Position (Mb)'), yaxis = list(title = 'Chromosome'), zaxis = list(title = 'Delta SNP-index') ), title = "3D Genomic Landscape of Delta SNP-index" ) }) } # Run the app shinyApp(ui = ui, server = server)