softwareDevelopment commited on
Commit
51174c1
·
verified ·
1 Parent(s): 03151af

Update app.R

Browse files
Files changed (1) hide show
  1. app.R +181 -167
app.R CHANGED
@@ -1,7 +1,7 @@
1
  # ============================================================================
2
  # ADVANCED QTL ANALYSIS PIPELINE
3
  # 10 Mapping Models + 10+ Unique Visualizations
4
- # Complete Production-Ready Application
5
  # ============================================================================
6
 
7
  # Load libraries
@@ -22,9 +22,26 @@ suppressPackageStartupMessages({
22
  library(viridis)
23
  library(ggridges)
24
  library(pheatmap)
25
- library(corrplot)
26
  })
27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  # ============================================================================
29
  # DATA PARSER
30
  # ============================================================================
@@ -145,37 +162,44 @@ run_all_models <- function(cross, pheno_col) {
145
  # Model 1: Haley-Knott Regression
146
  tryCatch({
147
  models$hk <- scanone(cross, pheno.col = pheno_col, method = "hk")
 
148
  }, error = function(e) message("HK failed: ", e$message))
149
 
150
  # Model 2: EM Algorithm
151
  tryCatch({
152
  models$em <- scanone(cross, pheno.col = pheno_col, method = "em")
 
153
  }, error = function(e) message("EM failed: ", e$message))
154
 
155
  # Model 3: Extended Haley-Knott
156
  tryCatch({
157
  models$ehk <- scanone(cross, pheno.col = pheno_col, method = "ehk")
 
158
  }, error = function(e) message("EHK failed: ", e$message))
159
 
160
  # Model 4: Multiple Imputation
161
  tryCatch({
162
  cross_sim <- sim.geno(cross, n.draws = 32, step = 1)
163
  models$imp <- scanone(cross_sim, pheno.col = pheno_col, method = "imp")
 
164
  }, error = function(e) message("IMP failed: ", e$message))
165
 
166
  # Model 5: Marker Regression
167
  tryCatch({
168
  models$mr <- scanone(cross, pheno.col = pheno_col, method = "mr")
 
169
  }, error = function(e) message("MR failed: ", e$message))
170
 
171
  # Model 6: Non-parametric
172
  tryCatch({
173
  models$np <- scanone(cross, pheno.col = pheno_col, method = "np")
 
174
  }, error = function(e) message("NP failed: ", e$message))
175
 
176
  # Model 7: Composite Interval Mapping
177
  tryCatch({
178
  models$cim <- cim(cross, pheno.col = pheno_col, method = "hk", window = 10)
 
179
  }, error = function(e) message("CIM failed: ", e$message))
180
 
181
  # Model 8: Multiple QTL Mapping
@@ -184,22 +208,93 @@ run_all_models <- function(cross, pheno_col) {
184
  cofactors <- which(scan_hk$lod > 2)
185
  if (length(cofactors) > 0) {
186
  models$mqm <- mqm(cross, pheno.col = pheno_col, cofactors = cofactors)
 
187
  }
188
  }, error = function(e) message("MQM failed: ", e$message))
189
 
190
  # Model 9: Binary Trait
191
  tryCatch({
192
  models$binary <- scanone(cross, pheno.col = pheno_col, method = "binary")
 
193
  }, error = function(e) message("Binary failed: ", e$message))
194
 
195
  # Model 10: Normal Model
196
  tryCatch({
197
  models$normal <- scanone(cross, pheno.col = pheno_col, method = "normal")
 
198
  }, error = function(e) message("Normal failed: ", e$message))
199
 
200
  return(models)
201
  }
202
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
203
  # ============================================================================
204
  # 10+ UNIQUE VISUALIZATIONS
205
  # ============================================================================
@@ -208,14 +303,12 @@ run_all_models <- function(cross, pheno_col) {
208
  plot_multi_manhattan <- function(models, threshold = 3) {
209
  if (is.null(models) || length(models) == 0) return(NULL)
210
 
211
- # Combine all models
212
  combined <- data.frame()
213
  for (name in names(models)) {
214
  scan <- models[[name]]
215
  if (!is.null(scan)) {
216
  df <- as.data.frame(scan)
217
  df$model <- toupper(name)
218
- df$pos_cum <- df$pos
219
  combined <- rbind(combined, df)
220
  }
221
  }
@@ -223,11 +316,11 @@ plot_multi_manhattan <- function(models, threshold = 3) {
223
  if (nrow(combined) == 0) return(NULL)
224
 
225
  ggplot(combined, aes(x = pos, y = lod, color = model)) +
226
- geom_line(size = 0.8, alpha = 0.7) +
227
  geom_hline(yintercept = threshold, color = "red", linetype = "dashed", size = 1) +
228
  facet_wrap(~chr, scales = "free_x", ncol = 3) +
229
  scale_color_brewer(palette = "Set1") +
230
- labs(title = "Multi-Model QTL Comparison Across Chromosomes",
231
  x = "Position (cM)", y = "LOD Score", color = "Model") +
232
  theme_minimal() +
233
  theme(legend.position = "bottom",
@@ -239,7 +332,6 @@ plot_multi_manhattan <- function(models, threshold = 3) {
239
  plot_model_heatmap <- function(models) {
240
  if (is.null(models) || length(models) == 0) return(NULL)
241
 
242
- # Extract peak LOD per chromosome per model
243
  perf_matrix <- matrix(0, nrow = length(models), ncol = 0)
244
  model_names <- c()
245
 
@@ -256,20 +348,21 @@ plot_model_heatmap <- function(models) {
256
  }
257
  }
258
 
 
 
259
  rownames(perf_matrix) <- model_names
260
  colnames(perf_matrix) <- names(chr_lods)
261
 
262
  pheatmap(perf_matrix,
263
  color = viridis(100),
264
- main = "Model Performance Heatmap\n(Peak LOD per Chromosome)",
265
  cluster_rows = TRUE,
266
  cluster_cols = TRUE,
267
  display_numbers = TRUE,
268
- fontsize = 10,
269
- angle_col = 45)
270
  }
271
 
272
- # Plot 3: 3D Surface Plot of LOD Scores
273
  plot_3d_surface <- function(scan) {
274
  if (is.null(scan)) return(NULL)
275
 
@@ -286,7 +379,7 @@ plot_3d_surface <- function(scan) {
286
  zaxis = list(title = "LOD Score")))
287
  }
288
 
289
- # Plot 4: QQ Plot for Model Comparison
290
  plot_qq_comparison <- function(models) {
291
  if (is.null(models) || length(models) == 0) return(NULL)
292
 
@@ -304,6 +397,8 @@ plot_qq_comparison <- function(models) {
304
  }
305
  }
306
 
 
 
307
  ggplot(qq_data, aes(x = Expected, y = Observed, color = Model)) +
308
  geom_point(size = 1, alpha = 0.6) +
309
  geom_abline(intercept = 0, slope = 1, color = "red", linetype = "dashed", size = 1) +
@@ -314,7 +409,7 @@ plot_qq_comparison <- function(models) {
314
  theme(legend.position = "bottom")
315
  }
316
 
317
- # Plot 5: Ridge Plot of LOD Distributions
318
  plot_lod_ridges <- function(scan) {
319
  if (is.null(scan)) return(NULL)
320
 
@@ -330,7 +425,7 @@ plot_lod_ridges <- function(scan) {
330
  theme(legend.position = "right")
331
  }
332
 
333
- # Plot 6: QTL Effect Size Bubble Plot
334
  plot_qtl_bubbles <- function(qtls) {
335
  if (is.null(qtls) || nrow(qtls) == 0) return(NULL)
336
 
@@ -344,7 +439,7 @@ plot_qtl_bubbles <- function(qtls) {
344
  theme(axis.text.x = element_text(angle = 45, hjust = 1))
345
  }
346
 
347
- # Plot 7: Correlation Circle of Traits
348
  plot_trait_circle <- function(cross) {
349
  if (is.null(cross) || ncol(cross$pheno) < 2) return(NULL)
350
 
@@ -377,6 +472,8 @@ plot_map_density <- function(cross) {
377
  }
378
  }
379
 
 
 
380
  ggplot(density_data, aes(x = Gap, fill = Chromosome)) +
381
  geom_histogram(bins = 30, alpha = 0.6, position = "stack") +
382
  scale_fill_brewer(palette = "Set3") +
@@ -386,11 +483,10 @@ plot_map_density <- function(cross) {
386
  theme(legend.position = "bottom")
387
  }
388
 
389
- # Plot 9: Parallel Coordinates for Models
390
  plot_parallel_models <- function(models) {
391
  if (is.null(models) || length(models) == 0) return(NULL)
392
 
393
- # Extract top 50 markers
394
  first_model <- models[[1]]
395
  if (is.null(first_model)) return(NULL)
396
 
@@ -404,7 +500,6 @@ plot_parallel_models <- function(models) {
404
  }
405
  }
406
 
407
- # Reshape for plotting
408
  plot_data <- pivot_longer(parallel_data, cols = -Position,
409
  names_to = "Model", values_to = "LOD")
410
 
@@ -417,11 +512,10 @@ plot_parallel_models <- function(models) {
417
  theme(legend.position = "bottom")
418
  }
419
 
420
- # Plot 10: Violin Plot of Phenotype by Genotype
421
  plot_phenotype_genotype <- function(cross, qtl_row, trait) {
422
  if (is.null(cross) || is.null(qtl_row) || nrow(qtl_row) == 0) return(NULL)
423
 
424
- # Find nearest marker
425
  chr_name <- as.character(qtl_row$Chromosome[1])
426
  if (!chr_name %in% names(cross$geno)) return(NULL)
427
 
@@ -429,7 +523,6 @@ plot_phenotype_genotype <- function(cross, qtl_row, trait) {
429
  marker_pos <- which.min(abs(map - qtl_row$Position_cM[1]))
430
  marker_name <- names(map)[marker_pos]
431
 
432
- # Get data
433
  geno_idx <- find.marker(cross, chr_name, marker_name)
434
  genotypes <- pull.geno(cross)[, geno_idx]
435
  phenotypes <- cross$pheno[[trait]]
@@ -440,7 +533,7 @@ plot_phenotype_genotype <- function(cross, qtl_row, trait) {
440
  )
441
  df <- df[!is.na(df$Genotype) & !is.na(df$Phenotype), ]
442
 
443
- # Recode genotypes for better labels
444
  if (length(unique(df$Genotype)) == 3) {
445
  df$Genotype <- recode(df$Genotype, `1` = "AA", `2` = "AB", `3` = "BB")
446
  } else if (length(unique(df$Genotype)) == 2) {
@@ -451,10 +544,8 @@ plot_phenotype_genotype <- function(cross, qtl_row, trait) {
451
  geom_violin(alpha = 0.6, trim = FALSE) +
452
  geom_boxplot(width = 0.2, alpha = 0.8) +
453
  stat_summary(fun = mean, geom = "point", shape = 18, size = 4, color = "red") +
454
- stat_summary(fun = mean, geom = "text", aes(label = round(..y.., 2)),
455
- vjust = -1, size = 3) +
456
  scale_fill_brewer(palette = "Set2") +
457
- labs(title = paste("Phenotype Distribution by Genotype at", marker_name),
458
  x = "Genotype", y = trait) +
459
  theme_minimal() +
460
  theme(legend.position = "none")
@@ -464,7 +555,6 @@ plot_phenotype_genotype <- function(cross, qtl_row, trait) {
464
  plot_lod_contour <- function(scan) {
465
  if (is.null(scan)) return(NULL)
466
 
467
- # Create grid for contour
468
  chrs <- unique(scan$chr)
469
  contour_data <- data.frame()
470
 
@@ -478,16 +568,15 @@ plot_lod_contour <- function(scan) {
478
  geom_contour_filled(bins = 10) +
479
  scale_fill_viridis_d(name = "LOD") +
480
  scale_y_continuous(breaks = 1:length(chrs), labels = chrs) +
481
- labs(title = "LOD Contour Plot Across Genome",
482
  x = "Position (cM)", y = "Chromosome") +
483
  theme_minimal()
484
  }
485
 
486
- # Plot 12: Radar Chart for Model Metrics
487
  plot_model_radar <- function(models) {
488
  if (is.null(models) || length(models) == 0) return(NULL)
489
 
490
- # Calculate metrics
491
  metrics <- data.frame()
492
  for (name in names(models)) {
493
  scan <- models[[name]]
@@ -496,20 +585,20 @@ plot_model_radar <- function(models) {
496
  Model = toupper(name),
497
  Max_LOD = max(scan$lod, na.rm = TRUE),
498
  Mean_LOD = mean(scan$lod, na.rm = TRUE),
499
- N_Peaks = sum(scan$lod > 3, na.rm = TRUE),
500
- Max_Position = scan$pos[which.max(scan$lod)]
501
  ))
502
  }
503
  }
504
 
505
- # Normalize for radar
 
 
506
  metrics_norm <- metrics
507
  for (col in c("Max_LOD", "Mean_LOD", "N_Peaks")) {
508
  metrics_norm[[col]] <- (metrics_norm[[col]] - min(metrics_norm[[col]])) /
509
  (max(metrics_norm[[col]]) - min(metrics_norm[[col]]))
510
  }
511
 
512
- # Reshape for plotting
513
  radar_data <- pivot_longer(metrics_norm,
514
  cols = c("Max_LOD", "Mean_LOD", "N_Peaks"),
515
  names_to = "Metric", values_to = "Value")
@@ -529,20 +618,20 @@ plot_model_radar <- function(models) {
529
  # ============================================================================
530
 
531
  ui <- dashboardPage(
532
- dashboardHeader(title = "QTL Analysis Pipeline - 10 Models"),
533
 
534
  dashboardSidebar(width = 320,
535
  sidebarMenu(
536
  menuItem("Data Input", tabName = "data", icon = icon("upload")),
537
- menuItem("10 Models Analysis", tabName = "models", icon = icon("chart-line")),
538
- menuItem("10+ Visualizations", tabName = "viz", icon = icon("chart-bar")),
539
- menuItem("QTL Results", tabName = "results", icon = icon("table")),
540
- menuItem("Model Comparison", tabName = "comparison", icon = icon("compare")),
541
- menuItem("Documentation", tabName = "help", icon = icon("question-circle"))
542
  ),
543
 
544
  div(style = "padding: 15px;",
545
- h4("Data Upload", style = "color: #3c8dbc;"),
546
  fileInput("geno_file", "Genotype CSV", accept = ".csv"),
547
  fileInput("pheno_file", "Phenotype CSV", accept = ".csv"),
548
 
@@ -552,9 +641,8 @@ ui <- dashboardPage(
552
 
553
  hr(),
554
 
555
- h4("Analysis Settings", style = "color: #3c8dbc;"),
556
  selectInput("pheno_trait", "Phenotype Trait", choices = NULL),
557
-
558
  numericInput("lod_threshold", "LOD Threshold", value = 3.0, min = 0, max = 20, step = 0.5),
559
  numericInput("n_permutations", "Permutations", value = 100, min = 0, max = 1000),
560
 
@@ -563,7 +651,6 @@ ui <- dashboardPage(
563
  style = "background-color: #3c8dbc; color: white; width: 100%; margin-top: 15px;"),
564
 
565
  br(), br(),
566
-
567
  downloadButton("download_results", "Download Results", style = "width: 100%;")
568
  )
569
  ),
@@ -574,7 +661,6 @@ ui <- dashboardPage(
574
  tags$style(HTML("
575
  .content-wrapper, .right-side { background-color: #f4f4f4; }
576
  .box { border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
577
- .small-box { border-radius: 10px; }
578
  "))
579
  ),
580
 
@@ -598,7 +684,7 @@ ui <- dashboardPage(
598
  )
599
  ),
600
 
601
- # 10 Models Tab
602
  tabItem(tabName = "models",
603
  fluidRow(
604
  box(title = "Analysis Status", status = "primary", solidHeader = TRUE, width = 12,
@@ -606,17 +692,17 @@ ui <- dashboardPage(
606
  )
607
  ),
608
  fluidRow(
609
- box(title = "Multi-Model Manhattan Plot", status = "info", width = 12,
610
  plotOutput("multi_manhattan", height = "600px") %>% withSpinner()
611
  )
612
  ),
613
  fluidRow(
614
- box(title = "Model Performance Heatmap", status = "success", width = 12,
615
  plotOutput("model_heatmap", height = "600px") %>% withSpinner()
616
  )
617
  ),
618
  fluidRow(
619
- box(title = "Model Radar Chart", status = "warning", width = 12,
620
  plotOutput("radar_chart", height = "500px") %>% withSpinner()
621
  )
622
  )
@@ -625,35 +711,35 @@ ui <- dashboardPage(
625
  # Visualizations Tab
626
  tabItem(tabName = "viz",
627
  fluidRow(
628
- box(title = "3D LOD Surface Plot", status = "primary", width = 12,
629
  plotlyOutput("surface_3d", height = "600px") %>% withSpinner()
630
  )
631
  ),
632
  fluidRow(
633
- box(title = "LOD Ridge Plot", status = "info", width = 6,
634
  plotOutput("ridge_plot", height = "500px") %>% withSpinner()
635
  ),
636
- box(title = "LOD Contour Plot", status = "success", width = 6,
637
  plotOutput("contour_plot", height = "500px") %>% withSpinner()
638
  )
639
  ),
640
  fluidRow(
641
- box(title = "QTL Effect Bubble Plot", status = "warning", width = 12,
642
  plotOutput("bubble_plot", height = "500px") %>% withSpinner()
643
  )
644
  ),
645
  fluidRow(
646
- box(title = "Parallel Coordinates Comparison", status = "danger", width = 12,
647
  plotOutput("parallel_plot", height = "500px") %>% withSpinner()
648
  )
649
  ),
650
  fluidRow(
651
- box(title = "QQ Plot Model Comparison", status = "primary", width = 12,
652
  plotOutput("qq_plot", height = "500px") %>% withSpinner()
653
  )
654
  ),
655
  fluidRow(
656
- box(title = "Trait Correlation Circle", status = "info", width = 6,
657
  plotOutput("correlation_circle", height = "500px") %>% withSpinner()
658
  ),
659
  box(title = "Map Density", status = "success", width = 6,
@@ -661,7 +747,7 @@ ui <- dashboardPage(
661
  )
662
  ),
663
  fluidRow(
664
- box(title = "Genotype-Phenotype Association", status = "warning", width = 12,
665
  selectInput("effect_qtl", "Select QTL:", choices = NULL),
666
  plotOutput("violin_plot", height = "500px") %>% withSpinner()
667
  )
@@ -676,7 +762,7 @@ ui <- dashboardPage(
676
  )
677
  ),
678
  fluidRow(
679
- box(title = "Model Performance Summary", status = "info", width = 12,
680
  DTOutput("model_summary") %>% withSpinner()
681
  )
682
  ),
@@ -687,15 +773,15 @@ ui <- dashboardPage(
687
  )
688
  ),
689
 
690
- # Model Comparison Tab
691
  tabItem(tabName = "comparison",
692
  fluidRow(
693
- box(title = "Model Performance Metrics", status = "primary", width = 12,
694
  DTOutput("comparison_table") %>% withSpinner()
695
  )
696
  ),
697
  fluidRow(
698
- box(title = "Best Model per Chromosome", status = "info", width = 12,
699
  DTOutput("best_model_table") %>% withSpinner()
700
  )
701
  )
@@ -704,52 +790,25 @@ ui <- dashboardPage(
704
  # Help Tab
705
  tabItem(tabName = "help",
706
  fluidRow(
707
- box(title = "Documentation - 10 Models & 10+ Plots", status = "primary", width = 12,
708
  HTML("
709
- <h3>10 Mapping Models Included:</h3>
710
  <ol>
711
- <li><strong>Haley-Knott (HK)</strong> - Fast regression-based method</li>
712
- <li><strong>EM Algorithm</strong> - Expectation-maximization for missing data</li>
713
- <li><strong>Extended Haley-Knott (EHK)</strong> - Improved HK method</li>
714
- <li><strong>Multiple Imputation (IMP)</strong> - Handles missing genotypes</li>
715
- <li><strong>Marker Regression (MR)</strong> - Simple marker-by-marker regression</li>
716
- <li><strong>Non-parametric (NP)</strong> - Distribution-free method</li>
717
- <li><strong>Composite Interval Mapping (CIM)</strong> - Controls for background QTLs</li>
718
- <li><strong>Multiple QTL Mapping (MQM)</strong> - Uses cofactors</li>
719
- <li><strong>Binary Trait</strong> - For case/control studies</li>
720
- <li><strong>Normal Model</strong> - Assumes normal distribution</li>
721
- </ol>
722
-
723
- <h3>10+ Unique Visualizations:</h3>
724
- <ol>
725
- <li>Multi-Model Manhattan Plot</li>
726
- <li>Model Performance Heatmap</li>
727
- <li>3D LOD Surface Plot</li>
728
- <li>QQ Plot for Model Comparison</li>
729
- <li>LOD Score Ridge Plot</li>
730
- <li>QTL Effect Bubble Plot</li>
731
- <li>Trait Correlation Circle</li>
732
- <li>Genetic Map Density</li>
733
- <li>Parallel Coordinates Comparison</li>
734
- <li>Violin Plot by Genotype</li>
735
- <li>LOD Contour Plot</li>
736
- <li>Model Radar Chart</li>
737
  </ol>
738
 
739
  <h3>File Format:</h3>
740
- <p><strong>Genotype CSV:</strong></p>
741
- <pre>
742
- id,marker1,marker2,marker3
743
- ,chr1,chr1,chr2
744
- ,0,5.2,10.1
745
- sample1,1,2,1
746
- sample2,2,1,3</pre>
747
-
748
- <p><strong>Phenotype CSV:</strong></p>
749
- <pre>
750
- id,trait1,trait2
751
- sample1,12.5,175
752
- sample2,13.2,180</pre>
753
  ")
754
  )
755
  )
@@ -792,7 +851,7 @@ server <- function(input, output, session) {
792
  cross <- cross_data()
793
  valueBox(
794
  ifelse(is.null(cross), 0, nchr(cross)),
795
- "Chromosomes", icon = icon("chromosome"), color = "yellow"
796
  )
797
  })
798
 
@@ -821,7 +880,7 @@ server <- function(input, output, session) {
821
  })
822
  })
823
 
824
- # Run all 10 models
825
  observeEvent(input$run_analysis, {
826
  cross <- cross_data()
827
  req(cross, input$pheno_trait)
@@ -835,8 +894,8 @@ server <- function(input, output, session) {
835
  models <- run_all_models(cross, pheno_idx)
836
  all_models(models)
837
 
838
- # Find QTLs from best model (use HK if available)
839
  if (!is.null(models$hk)) {
 
840
  qtls <- find_qtls(models$hk, input$lod_threshold)
841
  qtl_results(qtls)
842
 
@@ -846,16 +905,16 @@ server <- function(input, output, session) {
846
  }
847
  }
848
 
849
- # Run permutations if requested
850
  if (input$n_permutations > 0 && !is.null(models$hk)) {
851
- incProgress(0.2, detail = paste("Running", input$n_permutations, "permutations..."))
852
  perms <- scanone(cross, pheno.col = pheno_idx,
853
  n.perm = input$n_permutations, method = "hk")
854
  perm_results(perms)
855
  }
856
 
857
  analysis_done(TRUE)
858
- showNotification(paste("Analysis complete!", length(models), "models run successfully"),
 
859
  type = "success", duration = 5)
860
  })
861
  })
@@ -864,46 +923,28 @@ server <- function(input, output, session) {
864
  output$data_summary <- renderPrint({
865
  cross <- cross_data()
866
  if (is.null(cross)) {
867
- cat("No data loaded. Please upload CSV files.")
868
  } else {
869
- cat("=== Data Summary ===\n\n")
870
  cat("Cross Type:", class(cross)[1], "\n")
871
  cat("Individuals:", nind(cross), "\n")
872
  cat("Markers:", totmar(cross), "\n")
873
- cat("Chromosomes:", nchr(cross), "\n\n")
874
  cat("Phenotypes:", paste(names(cross$pheno), collapse = ", "), "\n")
875
-
876
- missing_total <- sum(is.na(pull.geno(cross))) / (nind(cross) * totmar(cross)) * 100
877
- cat("\nMissing data rate:", round(missing_total, 2), "%\n")
878
  }
879
  })
880
 
881
  output$analysis_status <- renderPrint({
882
  models <- all_models()
883
  if (!analysis_done()) {
884
- cat("Analysis not run. Click 'RUN 10 MODELS' to start.")
885
  } else {
886
- cat("=== Analysis Complete ===\n\n")
887
- cat("Models run:", length(models), "/10\n")
888
- cat("Models:", paste(toupper(names(models)), collapse = ", "), "\n\n")
889
-
890
- # Best model
891
- best_lod <- 0
892
- best_model <- ""
893
- for (name in names(models)) {
894
- if (!is.null(models[[name]])) {
895
- max_lod <- max(models[[name]]$lod, na.rm = TRUE)
896
- if (max_lod > best_lod) {
897
- best_lod <- max_lod
898
- best_model <- name
899
- }
900
- }
901
- }
902
- cat("Best model:", toupper(best_model), "(Max LOD =", round(best_lod, 3), ")\n")
903
  }
904
  })
905
 
906
- # Genetic map
907
  output$genetic_map <- renderPlot({
908
  cross <- cross_data()
909
  req(cross)
@@ -915,8 +956,6 @@ server <- function(input, output, session) {
915
  df <- rbind(df, data.frame(Chromosome = chr, Position = positions))
916
  }
917
 
918
- df$Chromosome <- factor(df$Chromosome, levels = names(map))
919
-
920
  ggplot(df, aes(x = Chromosome, y = Position)) +
921
  geom_segment(aes(xend = Chromosome, yend = 0), color = "gray70", size = 1) +
922
  geom_point(color = "steelblue", size = 2, alpha = 0.7) +
@@ -925,84 +964,72 @@ server <- function(input, output, session) {
925
  theme(axis.text.x = element_text(angle = 45, hjust = 1))
926
  })
927
 
928
- # Multi-model Manhattan
929
  output$multi_manhattan <- renderPlot({
930
  models <- all_models()
931
  req(models, length(models) > 0)
932
  plot_multi_manhattan(models, input$lod_threshold)
933
  })
934
 
935
- # Model heatmap
936
  output$model_heatmap <- renderPlot({
937
  models <- all_models()
938
  req(models)
939
  plot_model_heatmap(models)
940
  })
941
 
942
- # Radar chart
943
  output$radar_chart <- renderPlot({
944
  models <- all_models()
945
  req(models)
946
  plot_model_radar(models)
947
  })
948
 
949
- # 3D surface
950
  output$surface_3d <- renderPlotly({
951
  models <- all_models()
952
  req(models, !is.null(models$hk))
953
  plot_3d_surface(models$hk)
954
  })
955
 
956
- # Ridge plot
957
  output$ridge_plot <- renderPlot({
958
  models <- all_models()
959
  req(models, !is.null(models$hk))
960
  plot_lod_ridges(models$hk)
961
  })
962
 
963
- # Contour plot
964
  output$contour_plot <- renderPlot({
965
  models <- all_models()
966
  req(models, !is.null(models$hk))
967
  plot_lod_contour(models$hk)
968
  })
969
 
970
- # Bubble plot
971
  output$bubble_plot <- renderPlot({
972
  qtls <- qtl_results()
973
  req(qtls, nrow(qtls) > 0)
974
  plot_qtl_bubbles(qtls)
975
  })
976
 
977
- # Parallel plot
978
  output$parallel_plot <- renderPlot({
979
  models <- all_models()
980
  req(models, length(models) > 0)
981
  plot_parallel_models(models)
982
  })
983
 
984
- # QQ plot
985
  output$qq_plot <- renderPlot({
986
  models <- all_models()
987
  req(models, length(models) > 0)
988
  plot_qq_comparison(models)
989
  })
990
 
991
- # Correlation circle
992
  output$correlation_circle <- renderPlot({
993
  cross <- cross_data()
994
  req(cross)
995
  plot_trait_circle(cross)
996
  })
997
 
998
- # Map density
999
  output$map_density <- renderPlot({
1000
  cross <- cross_data()
1001
  req(cross)
1002
  plot_map_density(cross)
1003
  })
1004
 
1005
- # Violin plot
1006
  output$violin_plot <- renderPlot({
1007
  req(input$effect_qtl, input$effect_qtl != "")
1008
  qtls <- qtl_results()
@@ -1015,16 +1042,13 @@ server <- function(input, output, session) {
1015
  plot_phenotype_genotype(cross, qtls[qtl_idx[1], , drop = FALSE], input$pheno_trait)
1016
  })
1017
 
1018
- # QTL table
1019
  output$qtl_table <- renderDT({
1020
  qtls <- qtl_results()
1021
  req(qtls, nrow(qtls) > 0)
1022
-
1023
- datatable(qtls, options = list(pageLength = 15, scrollX = TRUE), rownames = FALSE) %>%
1024
- formatStyle("LOD", background = styleColorBar(range(qtls$LOD), "lightblue"))
1025
  })
1026
 
1027
- # Model summary
1028
  output$model_summary <- renderDT({
1029
  models <- all_models()
1030
  req(models)
@@ -1037,9 +1061,7 @@ server <- function(input, output, session) {
1037
  Model = toupper(name),
1038
  Max_LOD = round(max(scan$lod, na.rm = TRUE), 3),
1039
  Mean_LOD = round(mean(scan$lod, na.rm = TRUE), 3),
1040
- N_Peaks = sum(scan$lod > input$lod_threshold, na.rm = TRUE),
1041
- Chromosome = scan$chr[which.max(scan$lod)],
1042
- Position = round(scan$pos[which.max(scan$lod)], 2)
1043
  ))
1044
  }
1045
  }
@@ -1047,7 +1069,6 @@ server <- function(input, output, session) {
1047
  datatable(summary_df, options = list(pageLength = 10), rownames = FALSE)
1048
  })
1049
 
1050
- # Permutation table
1051
  output$permutation_table <- renderDT({
1052
  perms <- perm_results()
1053
  req(perms)
@@ -1062,7 +1083,6 @@ server <- function(input, output, session) {
1062
  datatable(perm_df, options = list(pageLength = 5, dom = 't'), rownames = FALSE)
1063
  })
1064
 
1065
- # Comparison table
1066
  output$comparison_table <- renderDT({
1067
  models <- all_models()
1068
  req(models)
@@ -1075,25 +1095,19 @@ server <- function(input, output, session) {
1075
  Model = toupper(name),
1076
  Max_LOD = round(max(scan$lod, na.rm = TRUE), 3),
1077
  Mean_LOD = round(mean(scan$lod, na.rm = TRUE), 3),
1078
- Median_LOD = round(median(scan$lod, na.rm = TRUE), 3),
1079
- SD_LOD = round(sd(scan$lod, na.rm = TRUE), 3),
1080
- CV_LOD = round(sd(scan$lod, na.rm = TRUE) / mean(scan$lod, na.rm = TRUE) * 100, 2),
1081
- Top_Chromosome = scan$chr[which.max(scan$lod)],
1082
- Top_Position = round(scan$pos[which.max(scan$lod)], 2)
1083
  ))
1084
  }
1085
  }
1086
 
1087
- datatable(comparison_df, options = list(pageLength = 10, scrollX = TRUE), rownames = FALSE) %>%
1088
- formatStyle("Max_LOD", background = styleColorBar(range(comparison_df$Max_LOD), "lightgreen"))
1089
  })
1090
 
1091
- # Best model table
1092
  output$best_model_table <- renderDT({
1093
  models <- all_models()
1094
  req(models)
1095
 
1096
- # Get all chromosomes
1097
  first_model <- models[[1]]
1098
  if (is.null(first_model)) return(NULL)
1099
 
@@ -1123,9 +1137,9 @@ server <- function(input, output, session) {
1123
  datatable(best_df, options = list(pageLength = 15), rownames = FALSE)
1124
  })
1125
 
1126
- # Download handler
1127
  output$download_results <- downloadHandler(
1128
- filename = function() paste0("qtl_10models_", Sys.Date(), ".csv"),
1129
  content = function(file) {
1130
  qtls <- qtl_results()
1131
  if (!is.null(qtls) && nrow(qtls) > 0) {
 
1
  # ============================================================================
2
  # ADVANCED QTL ANALYSIS PIPELINE
3
  # 10 Mapping Models + 10+ Unique Visualizations
4
+ # COMPLETE FIXED VERSION
5
  # ============================================================================
6
 
7
  # Load libraries
 
22
  library(viridis)
23
  library(ggridges)
24
  library(pheatmap)
 
25
  })
26
 
27
+ # Check for corrplot
28
+ if (!require("corrplot", quietly = TRUE)) {
29
+ install.packages("corrplot", repos = "https://cloud.r-project.org/")
30
+ library(corrplot)
31
+ }
32
+
33
+ # ============================================================================
34
+ # HELPER FUNCTIONS - FIXED
35
+ # ============================================================================
36
+
37
+ show_notification_safe <- function(msg, type = "default") {
38
+ tryCatch({
39
+ showNotification(msg, type = type, duration = 5)
40
+ }, error = function(e) {
41
+ message(msg)
42
+ })
43
+ }
44
+
45
  # ============================================================================
46
  # DATA PARSER
47
  # ============================================================================
 
162
  # Model 1: Haley-Knott Regression
163
  tryCatch({
164
  models$hk <- scanone(cross, pheno.col = pheno_col, method = "hk")
165
+ message("HK model completed")
166
  }, error = function(e) message("HK failed: ", e$message))
167
 
168
  # Model 2: EM Algorithm
169
  tryCatch({
170
  models$em <- scanone(cross, pheno.col = pheno_col, method = "em")
171
+ message("EM model completed")
172
  }, error = function(e) message("EM failed: ", e$message))
173
 
174
  # Model 3: Extended Haley-Knott
175
  tryCatch({
176
  models$ehk <- scanone(cross, pheno.col = pheno_col, method = "ehk")
177
+ message("EHK model completed")
178
  }, error = function(e) message("EHK failed: ", e$message))
179
 
180
  # Model 4: Multiple Imputation
181
  tryCatch({
182
  cross_sim <- sim.geno(cross, n.draws = 32, step = 1)
183
  models$imp <- scanone(cross_sim, pheno.col = pheno_col, method = "imp")
184
+ message("IMP model completed")
185
  }, error = function(e) message("IMP failed: ", e$message))
186
 
187
  # Model 5: Marker Regression
188
  tryCatch({
189
  models$mr <- scanone(cross, pheno.col = pheno_col, method = "mr")
190
+ message("MR model completed")
191
  }, error = function(e) message("MR failed: ", e$message))
192
 
193
  # Model 6: Non-parametric
194
  tryCatch({
195
  models$np <- scanone(cross, pheno.col = pheno_col, method = "np")
196
+ message("NP model completed")
197
  }, error = function(e) message("NP failed: ", e$message))
198
 
199
  # Model 7: Composite Interval Mapping
200
  tryCatch({
201
  models$cim <- cim(cross, pheno.col = pheno_col, method = "hk", window = 10)
202
+ message("CIM model completed")
203
  }, error = function(e) message("CIM failed: ", e$message))
204
 
205
  # Model 8: Multiple QTL Mapping
 
208
  cofactors <- which(scan_hk$lod > 2)
209
  if (length(cofactors) > 0) {
210
  models$mqm <- mqm(cross, pheno.col = pheno_col, cofactors = cofactors)
211
+ message("MQM model completed")
212
  }
213
  }, error = function(e) message("MQM failed: ", e$message))
214
 
215
  # Model 9: Binary Trait
216
  tryCatch({
217
  models$binary <- scanone(cross, pheno.col = pheno_col, method = "binary")
218
+ message("Binary model completed")
219
  }, error = function(e) message("Binary failed: ", e$message))
220
 
221
  # Model 10: Normal Model
222
  tryCatch({
223
  models$normal <- scanone(cross, pheno.col = pheno_col, method = "normal")
224
+ message("Normal model completed")
225
  }, error = function(e) message("Normal failed: ", e$message))
226
 
227
  return(models)
228
  }
229
 
230
+ find_qtls <- function(scan, threshold) {
231
+ if (is.null(scan) || nrow(scan) == 0) {
232
+ return(data.frame())
233
+ }
234
+
235
+ scan_sig <- scan[scan$lod >= threshold, ]
236
+ if (nrow(scan_sig) == 0) {
237
+ return(data.frame())
238
+ }
239
+
240
+ qtls <- data.frame()
241
+ for (chr in unique(scan_sig$chr)) {
242
+ chr_data <- scan_sig[scan_sig$chr == chr, ]
243
+
244
+ # Find peaks
245
+ peaks <- c()
246
+ for (i in 1:nrow(chr_data)) {
247
+ is_peak <- TRUE
248
+ if (i > 1 && chr_data$lod[i] <= chr_data$lod[i - 1]) is_peak <- FALSE
249
+ if (i < nrow(chr_data) && chr_data$lod[i] <= chr_data$lod[i + 1]) is_peak <- FALSE
250
+ if (is_peak) peaks <- c(peaks, i)
251
+ }
252
+
253
+ if (length(peaks) > 0) {
254
+ for (peak_idx in peaks) {
255
+ peak_row <- chr_data[peak_idx, ]
256
+
257
+ # Calculate CI
258
+ chr_all <- scan[scan$chr == chr, ]
259
+ lod_diff <- chr_all$lod - peak_row$lod
260
+ ci_indices <- which(lod_diff >= -1.5)
261
+ if (length(ci_indices) > 0) {
262
+ left_pos <- min(chr_all$pos[ci_indices])
263
+ right_pos <- max(chr_all$pos[ci_indices])
264
+ } else {
265
+ left_pos <- peak_row$pos - 5
266
+ right_pos <- peak_row$pos + 5
267
+ }
268
+
269
+ # Calculate PVE
270
+ n <- nrow(scan)
271
+ pve <- (1 - 10^(-2 * peak_row$lod / n)) * 100
272
+
273
+ qtls <- rbind(qtls, data.frame(
274
+ Chromosome = as.character(chr),
275
+ Position_cM = round(peak_row$pos, 2),
276
+ LOD = round(peak_row$lod, 3),
277
+ PVE_percent = round(pve, 2),
278
+ CI_left = round(left_pos, 2),
279
+ CI_right = round(right_pos, 2),
280
+ CI_width = round(right_pos - left_pos, 2),
281
+ Marker = rownames(peak_row),
282
+ stringsAsFactors = FALSE
283
+ ))
284
+ }
285
+ }
286
+ }
287
+
288
+ if (nrow(qtls) > 0) {
289
+ qtls$ChrNum <- suppressWarnings(as.numeric(qtls$Chromosome))
290
+ qtls$ChrNum[is.na(qtls$ChrNum)] <- 999
291
+ qtls <- qtls[order(qtls$ChrNum, qtls$Position_cM), ]
292
+ qtls$ChrNum <- NULL
293
+ }
294
+
295
+ return(qtls)
296
+ }
297
+
298
  # ============================================================================
299
  # 10+ UNIQUE VISUALIZATIONS
300
  # ============================================================================
 
303
  plot_multi_manhattan <- function(models, threshold = 3) {
304
  if (is.null(models) || length(models) == 0) return(NULL)
305
 
 
306
  combined <- data.frame()
307
  for (name in names(models)) {
308
  scan <- models[[name]]
309
  if (!is.null(scan)) {
310
  df <- as.data.frame(scan)
311
  df$model <- toupper(name)
 
312
  combined <- rbind(combined, df)
313
  }
314
  }
 
316
  if (nrow(combined) == 0) return(NULL)
317
 
318
  ggplot(combined, aes(x = pos, y = lod, color = model)) +
319
+ geom_line(size = 0.6, alpha = 0.7) +
320
  geom_hline(yintercept = threshold, color = "red", linetype = "dashed", size = 1) +
321
  facet_wrap(~chr, scales = "free_x", ncol = 3) +
322
  scale_color_brewer(palette = "Set1") +
323
+ labs(title = "Multi-Model QTL Comparison",
324
  x = "Position (cM)", y = "LOD Score", color = "Model") +
325
  theme_minimal() +
326
  theme(legend.position = "bottom",
 
332
  plot_model_heatmap <- function(models) {
333
  if (is.null(models) || length(models) == 0) return(NULL)
334
 
 
335
  perf_matrix <- matrix(0, nrow = length(models), ncol = 0)
336
  model_names <- c()
337
 
 
348
  }
349
  }
350
 
351
+ if (nrow(perf_matrix) == 0) return(NULL)
352
+
353
  rownames(perf_matrix) <- model_names
354
  colnames(perf_matrix) <- names(chr_lods)
355
 
356
  pheatmap(perf_matrix,
357
  color = viridis(100),
358
+ main = "Model Performance Heatmap",
359
  cluster_rows = TRUE,
360
  cluster_cols = TRUE,
361
  display_numbers = TRUE,
362
+ fontsize = 10)
 
363
  }
364
 
365
+ # Plot 3: 3D Surface Plot
366
  plot_3d_surface <- function(scan) {
367
  if (is.null(scan)) return(NULL)
368
 
 
379
  zaxis = list(title = "LOD Score")))
380
  }
381
 
382
+ # Plot 4: QQ Plot
383
  plot_qq_comparison <- function(models) {
384
  if (is.null(models) || length(models) == 0) return(NULL)
385
 
 
397
  }
398
  }
399
 
400
+ if (nrow(qq_data) == 0) return(NULL)
401
+
402
  ggplot(qq_data, aes(x = Expected, y = Observed, color = Model)) +
403
  geom_point(size = 1, alpha = 0.6) +
404
  geom_abline(intercept = 0, slope = 1, color = "red", linetype = "dashed", size = 1) +
 
409
  theme(legend.position = "bottom")
410
  }
411
 
412
+ # Plot 5: Ridge Plot
413
  plot_lod_ridges <- function(scan) {
414
  if (is.null(scan)) return(NULL)
415
 
 
425
  theme(legend.position = "right")
426
  }
427
 
428
+ # Plot 6: QTL Effect Bubble Plot
429
  plot_qtl_bubbles <- function(qtls) {
430
  if (is.null(qtls) || nrow(qtls) == 0) return(NULL)
431
 
 
439
  theme(axis.text.x = element_text(angle = 45, hjust = 1))
440
  }
441
 
442
+ # Plot 7: Trait Correlation Circle
443
  plot_trait_circle <- function(cross) {
444
  if (is.null(cross) || ncol(cross$pheno) < 2) return(NULL)
445
 
 
472
  }
473
  }
474
 
475
+ if (nrow(density_data) == 0) return(NULL)
476
+
477
  ggplot(density_data, aes(x = Gap, fill = Chromosome)) +
478
  geom_histogram(bins = 30, alpha = 0.6, position = "stack") +
479
  scale_fill_brewer(palette = "Set3") +
 
483
  theme(legend.position = "bottom")
484
  }
485
 
486
+ # Plot 9: Parallel Coordinates
487
  plot_parallel_models <- function(models) {
488
  if (is.null(models) || length(models) == 0) return(NULL)
489
 
 
490
  first_model <- models[[1]]
491
  if (is.null(first_model)) return(NULL)
492
 
 
500
  }
501
  }
502
 
 
503
  plot_data <- pivot_longer(parallel_data, cols = -Position,
504
  names_to = "Model", values_to = "LOD")
505
 
 
512
  theme(legend.position = "bottom")
513
  }
514
 
515
+ # Plot 10: Violin Plot
516
  plot_phenotype_genotype <- function(cross, qtl_row, trait) {
517
  if (is.null(cross) || is.null(qtl_row) || nrow(qtl_row) == 0) return(NULL)
518
 
 
519
  chr_name <- as.character(qtl_row$Chromosome[1])
520
  if (!chr_name %in% names(cross$geno)) return(NULL)
521
 
 
523
  marker_pos <- which.min(abs(map - qtl_row$Position_cM[1]))
524
  marker_name <- names(map)[marker_pos]
525
 
 
526
  geno_idx <- find.marker(cross, chr_name, marker_name)
527
  genotypes <- pull.geno(cross)[, geno_idx]
528
  phenotypes <- cross$pheno[[trait]]
 
533
  )
534
  df <- df[!is.na(df$Genotype) & !is.na(df$Phenotype), ]
535
 
536
+ # Recode genotypes
537
  if (length(unique(df$Genotype)) == 3) {
538
  df$Genotype <- recode(df$Genotype, `1` = "AA", `2` = "AB", `3` = "BB")
539
  } else if (length(unique(df$Genotype)) == 2) {
 
544
  geom_violin(alpha = 0.6, trim = FALSE) +
545
  geom_boxplot(width = 0.2, alpha = 0.8) +
546
  stat_summary(fun = mean, geom = "point", shape = 18, size = 4, color = "red") +
 
 
547
  scale_fill_brewer(palette = "Set2") +
548
+ labs(title = paste("Phenotype by Genotype at", marker_name),
549
  x = "Genotype", y = trait) +
550
  theme_minimal() +
551
  theme(legend.position = "none")
 
555
  plot_lod_contour <- function(scan) {
556
  if (is.null(scan)) return(NULL)
557
 
 
558
  chrs <- unique(scan$chr)
559
  contour_data <- data.frame()
560
 
 
568
  geom_contour_filled(bins = 10) +
569
  scale_fill_viridis_d(name = "LOD") +
570
  scale_y_continuous(breaks = 1:length(chrs), labels = chrs) +
571
+ labs(title = "LOD Contour Plot",
572
  x = "Position (cM)", y = "Chromosome") +
573
  theme_minimal()
574
  }
575
 
576
+ # Plot 12: Radar Chart
577
  plot_model_radar <- function(models) {
578
  if (is.null(models) || length(models) == 0) return(NULL)
579
 
 
580
  metrics <- data.frame()
581
  for (name in names(models)) {
582
  scan <- models[[name]]
 
585
  Model = toupper(name),
586
  Max_LOD = max(scan$lod, na.rm = TRUE),
587
  Mean_LOD = mean(scan$lod, na.rm = TRUE),
588
+ N_Peaks = sum(scan$lod > 3, na.rm = TRUE)
 
589
  ))
590
  }
591
  }
592
 
593
+ if (nrow(metrics) == 0) return(NULL)
594
+
595
+ # Normalize
596
  metrics_norm <- metrics
597
  for (col in c("Max_LOD", "Mean_LOD", "N_Peaks")) {
598
  metrics_norm[[col]] <- (metrics_norm[[col]] - min(metrics_norm[[col]])) /
599
  (max(metrics_norm[[col]]) - min(metrics_norm[[col]]))
600
  }
601
 
 
602
  radar_data <- pivot_longer(metrics_norm,
603
  cols = c("Max_LOD", "Mean_LOD", "N_Peaks"),
604
  names_to = "Metric", values_to = "Value")
 
618
  # ============================================================================
619
 
620
  ui <- dashboardPage(
621
+ dashboardHeader(title = "QTL Pipeline - 10 Models"),
622
 
623
  dashboardSidebar(width = 320,
624
  sidebarMenu(
625
  menuItem("Data Input", tabName = "data", icon = icon("upload")),
626
+ menuItem("10 Models", tabName = "models", icon = icon("cogs")),
627
+ menuItem("10+ Plots", tabName = "viz", icon = icon("chart-bar")),
628
+ menuItem("Results", tabName = "results", icon = icon("table")),
629
+ menuItem("Comparison", tabName = "comparison", icon = icon("balance-scale")),
630
+ menuItem("Help", tabName = "help", icon = icon("question-circle"))
631
  ),
632
 
633
  div(style = "padding: 15px;",
634
+ h4("Data Upload"),
635
  fileInput("geno_file", "Genotype CSV", accept = ".csv"),
636
  fileInput("pheno_file", "Phenotype CSV", accept = ".csv"),
637
 
 
641
 
642
  hr(),
643
 
644
+ h4("Settings"),
645
  selectInput("pheno_trait", "Phenotype Trait", choices = NULL),
 
646
  numericInput("lod_threshold", "LOD Threshold", value = 3.0, min = 0, max = 20, step = 0.5),
647
  numericInput("n_permutations", "Permutations", value = 100, min = 0, max = 1000),
648
 
 
651
  style = "background-color: #3c8dbc; color: white; width: 100%; margin-top: 15px;"),
652
 
653
  br(), br(),
 
654
  downloadButton("download_results", "Download Results", style = "width: 100%;")
655
  )
656
  ),
 
661
  tags$style(HTML("
662
  .content-wrapper, .right-side { background-color: #f4f4f4; }
663
  .box { border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
 
664
  "))
665
  ),
666
 
 
684
  )
685
  ),
686
 
687
+ # Models Tab
688
  tabItem(tabName = "models",
689
  fluidRow(
690
  box(title = "Analysis Status", status = "primary", solidHeader = TRUE, width = 12,
 
692
  )
693
  ),
694
  fluidRow(
695
+ box(title = "Multi-Model Manhattan", status = "info", width = 12,
696
  plotOutput("multi_manhattan", height = "600px") %>% withSpinner()
697
  )
698
  ),
699
  fluidRow(
700
+ box(title = "Model Heatmap", status = "success", width = 12,
701
  plotOutput("model_heatmap", height = "600px") %>% withSpinner()
702
  )
703
  ),
704
  fluidRow(
705
+ box(title = "Radar Chart", status = "warning", width = 12,
706
  plotOutput("radar_chart", height = "500px") %>% withSpinner()
707
  )
708
  )
 
711
  # Visualizations Tab
712
  tabItem(tabName = "viz",
713
  fluidRow(
714
+ box(title = "3D Surface Plot", status = "primary", width = 12,
715
  plotlyOutput("surface_3d", height = "600px") %>% withSpinner()
716
  )
717
  ),
718
  fluidRow(
719
+ box(title = "Ridge Plot", status = "info", width = 6,
720
  plotOutput("ridge_plot", height = "500px") %>% withSpinner()
721
  ),
722
+ box(title = "Contour Plot", status = "success", width = 6,
723
  plotOutput("contour_plot", height = "500px") %>% withSpinner()
724
  )
725
  ),
726
  fluidRow(
727
+ box(title = "Bubble Plot", status = "warning", width = 12,
728
  plotOutput("bubble_plot", height = "500px") %>% withSpinner()
729
  )
730
  ),
731
  fluidRow(
732
+ box(title = "Parallel Coordinates", status = "danger", width = 12,
733
  plotOutput("parallel_plot", height = "500px") %>% withSpinner()
734
  )
735
  ),
736
  fluidRow(
737
+ box(title = "QQ Plot", status = "primary", width = 12,
738
  plotOutput("qq_plot", height = "500px") %>% withSpinner()
739
  )
740
  ),
741
  fluidRow(
742
+ box(title = "Correlation Circle", status = "info", width = 6,
743
  plotOutput("correlation_circle", height = "500px") %>% withSpinner()
744
  ),
745
  box(title = "Map Density", status = "success", width = 6,
 
747
  )
748
  ),
749
  fluidRow(
750
+ box(title = "Genotype-Phenotype", status = "warning", width = 12,
751
  selectInput("effect_qtl", "Select QTL:", choices = NULL),
752
  plotOutput("violin_plot", height = "500px") %>% withSpinner()
753
  )
 
762
  )
763
  ),
764
  fluidRow(
765
+ box(title = "Model Summary", status = "info", width = 12,
766
  DTOutput("model_summary") %>% withSpinner()
767
  )
768
  ),
 
773
  )
774
  ),
775
 
776
+ # Comparison Tab
777
  tabItem(tabName = "comparison",
778
  fluidRow(
779
+ box(title = "Performance Metrics", status = "primary", width = 12,
780
  DTOutput("comparison_table") %>% withSpinner()
781
  )
782
  ),
783
  fluidRow(
784
+ box(title = "Best Model per Chr", status = "info", width = 12,
785
  DTOutput("best_model_table") %>% withSpinner()
786
  )
787
  )
 
790
  # Help Tab
791
  tabItem(tabName = "help",
792
  fluidRow(
793
+ box(title = "Documentation", status = "primary", width = 12,
794
  HTML("
795
+ <h3>10 Mapping Models:</h3>
796
  <ol>
797
+ <li><strong>HK</strong> - Haley-Knott regression</li>
798
+ <li><strong>EM</strong> - Expectation-Maximization</li>
799
+ <li><strong>EHK</strong> - Extended Haley-Knott</li>
800
+ <li><strong>IMP</strong> - Multiple Imputation</li>
801
+ <li><strong>MR</strong> - Marker Regression</li>
802
+ <li><strong>NP</strong> - Non-parametric</li>
803
+ <li><strong>CIM</strong> - Composite Interval Mapping</li>
804
+ <li><strong>MQM</strong> - Multiple QTL Mapping</li>
805
+ <li><strong>Binary</strong> - Binary trait analysis</li>
806
+ <li><strong>Normal</strong> - Normal model</li>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
807
  </ol>
808
 
809
  <h3>File Format:</h3>
810
+ <p>Genotype CSV: Row1=headers, Row2=chromosomes, Row3=positions, Row4+=data</p>
811
+ <p>Phenotype CSV: First column=IDs, remaining=traits</p>
 
 
 
 
 
 
 
 
 
 
 
812
  ")
813
  )
814
  )
 
851
  cross <- cross_data()
852
  valueBox(
853
  ifelse(is.null(cross), 0, nchr(cross)),
854
+ "Chromosomes", icon = icon("chart-line"), color = "yellow"
855
  )
856
  })
857
 
 
880
  })
881
  })
882
 
883
+ # Run all models
884
  observeEvent(input$run_analysis, {
885
  cross <- cross_data()
886
  req(cross, input$pheno_trait)
 
894
  models <- run_all_models(cross, pheno_idx)
895
  all_models(models)
896
 
 
897
  if (!is.null(models$hk)) {
898
+ incProgress(0.3, detail = "Identifying QTLs...")
899
  qtls <- find_qtls(models$hk, input$lod_threshold)
900
  qtl_results(qtls)
901
 
 
905
  }
906
  }
907
 
 
908
  if (input$n_permutations > 0 && !is.null(models$hk)) {
909
+ incProgress(0.3, detail = paste("Running", input$n_permutations, "permutations..."))
910
  perms <- scanone(cross, pheno.col = pheno_idx,
911
  n.perm = input$n_permutations, method = "hk")
912
  perm_results(perms)
913
  }
914
 
915
  analysis_done(TRUE)
916
+ n_models <- sum(!sapply(models, is.null))
917
+ showNotification(paste("Complete!", n_models, "models ran successfully"),
918
  type = "success", duration = 5)
919
  })
920
  })
 
923
  output$data_summary <- renderPrint({
924
  cross <- cross_data()
925
  if (is.null(cross)) {
926
+ cat("No data loaded.")
927
  } else {
 
928
  cat("Cross Type:", class(cross)[1], "\n")
929
  cat("Individuals:", nind(cross), "\n")
930
  cat("Markers:", totmar(cross), "\n")
931
+ cat("Chromosomes:", nchr(cross), "\n")
932
  cat("Phenotypes:", paste(names(cross$pheno), collapse = ", "), "\n")
 
 
 
933
  }
934
  })
935
 
936
  output$analysis_status <- renderPrint({
937
  models <- all_models()
938
  if (!analysis_done()) {
939
+ cat("Click 'RUN 10 MODELS' to start analysis.")
940
  } else {
941
+ n_success <- sum(!sapply(models, is.null))
942
+ cat("Models completed:", n_success, "/10\n")
943
+ cat("Models:", paste(toupper(names(models)[!sapply(models, is.null)]), collapse = ", "), "\n")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
944
  }
945
  })
946
 
947
+ # Plots
948
  output$genetic_map <- renderPlot({
949
  cross <- cross_data()
950
  req(cross)
 
956
  df <- rbind(df, data.frame(Chromosome = chr, Position = positions))
957
  }
958
 
 
 
959
  ggplot(df, aes(x = Chromosome, y = Position)) +
960
  geom_segment(aes(xend = Chromosome, yend = 0), color = "gray70", size = 1) +
961
  geom_point(color = "steelblue", size = 2, alpha = 0.7) +
 
964
  theme(axis.text.x = element_text(angle = 45, hjust = 1))
965
  })
966
 
 
967
  output$multi_manhattan <- renderPlot({
968
  models <- all_models()
969
  req(models, length(models) > 0)
970
  plot_multi_manhattan(models, input$lod_threshold)
971
  })
972
 
 
973
  output$model_heatmap <- renderPlot({
974
  models <- all_models()
975
  req(models)
976
  plot_model_heatmap(models)
977
  })
978
 
 
979
  output$radar_chart <- renderPlot({
980
  models <- all_models()
981
  req(models)
982
  plot_model_radar(models)
983
  })
984
 
 
985
  output$surface_3d <- renderPlotly({
986
  models <- all_models()
987
  req(models, !is.null(models$hk))
988
  plot_3d_surface(models$hk)
989
  })
990
 
 
991
  output$ridge_plot <- renderPlot({
992
  models <- all_models()
993
  req(models, !is.null(models$hk))
994
  plot_lod_ridges(models$hk)
995
  })
996
 
 
997
  output$contour_plot <- renderPlot({
998
  models <- all_models()
999
  req(models, !is.null(models$hk))
1000
  plot_lod_contour(models$hk)
1001
  })
1002
 
 
1003
  output$bubble_plot <- renderPlot({
1004
  qtls <- qtl_results()
1005
  req(qtls, nrow(qtls) > 0)
1006
  plot_qtl_bubbles(qtls)
1007
  })
1008
 
 
1009
  output$parallel_plot <- renderPlot({
1010
  models <- all_models()
1011
  req(models, length(models) > 0)
1012
  plot_parallel_models(models)
1013
  })
1014
 
 
1015
  output$qq_plot <- renderPlot({
1016
  models <- all_models()
1017
  req(models, length(models) > 0)
1018
  plot_qq_comparison(models)
1019
  })
1020
 
 
1021
  output$correlation_circle <- renderPlot({
1022
  cross <- cross_data()
1023
  req(cross)
1024
  plot_trait_circle(cross)
1025
  })
1026
 
 
1027
  output$map_density <- renderPlot({
1028
  cross <- cross_data()
1029
  req(cross)
1030
  plot_map_density(cross)
1031
  })
1032
 
 
1033
  output$violin_plot <- renderPlot({
1034
  req(input$effect_qtl, input$effect_qtl != "")
1035
  qtls <- qtl_results()
 
1042
  plot_phenotype_genotype(cross, qtls[qtl_idx[1], , drop = FALSE], input$pheno_trait)
1043
  })
1044
 
1045
+ # Tables
1046
  output$qtl_table <- renderDT({
1047
  qtls <- qtl_results()
1048
  req(qtls, nrow(qtls) > 0)
1049
+ datatable(qtls, options = list(pageLength = 15, scrollX = TRUE), rownames = FALSE)
 
 
1050
  })
1051
 
 
1052
  output$model_summary <- renderDT({
1053
  models <- all_models()
1054
  req(models)
 
1061
  Model = toupper(name),
1062
  Max_LOD = round(max(scan$lod, na.rm = TRUE), 3),
1063
  Mean_LOD = round(mean(scan$lod, na.rm = TRUE), 3),
1064
+ N_Peaks = sum(scan$lod > input$lod_threshold, na.rm = TRUE)
 
 
1065
  ))
1066
  }
1067
  }
 
1069
  datatable(summary_df, options = list(pageLength = 10), rownames = FALSE)
1070
  })
1071
 
 
1072
  output$permutation_table <- renderDT({
1073
  perms <- perm_results()
1074
  req(perms)
 
1083
  datatable(perm_df, options = list(pageLength = 5, dom = 't'), rownames = FALSE)
1084
  })
1085
 
 
1086
  output$comparison_table <- renderDT({
1087
  models <- all_models()
1088
  req(models)
 
1095
  Model = toupper(name),
1096
  Max_LOD = round(max(scan$lod, na.rm = TRUE), 3),
1097
  Mean_LOD = round(mean(scan$lod, na.rm = TRUE), 3),
1098
+ Top_Chr = scan$chr[which.max(scan$lod)],
1099
+ Top_Pos = round(scan$pos[which.max(scan$lod)], 2)
 
 
 
1100
  ))
1101
  }
1102
  }
1103
 
1104
+ datatable(comparison_df, options = list(pageLength = 10), rownames = FALSE)
 
1105
  })
1106
 
 
1107
  output$best_model_table <- renderDT({
1108
  models <- all_models()
1109
  req(models)
1110
 
 
1111
  first_model <- models[[1]]
1112
  if (is.null(first_model)) return(NULL)
1113
 
 
1137
  datatable(best_df, options = list(pageLength = 15), rownames = FALSE)
1138
  })
1139
 
1140
+ # Download
1141
  output$download_results <- downloadHandler(
1142
+ filename = function() paste0("qtl_results_", Sys.Date(), ".csv"),
1143
  content = function(file) {
1144
  qtls <- qtl_results()
1145
  if (!is.null(qtls) && nrow(qtls) > 0) {