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6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
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, "<br>POS:", POS, 
                                         "<br>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, "<br>POS:", POS,
                                         "<br>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), 
                                      "<br>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, 
                                        "<br>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, "<br>POS:", POS, 
                         "<br>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)