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

Update app.R

Browse files
Files changed (1) hide show
  1. app.R +252 -486
app.R CHANGED
@@ -1,7 +1,6 @@
1
  # ============================================================================
2
- # ADVANCED QTL ANALYSIS PIPELINE
3
- # 10 Mapping Models + 10+ Unique Visualizations
4
- # COMPLETE FIXED VERSION
5
  # ============================================================================
6
 
7
  # Load libraries
@@ -31,14 +30,24 @@ if (!require("corrplot", quietly = TRUE)) {
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
 
@@ -81,6 +90,9 @@ parse_custom_cross <- function(geno_path, pheno_path, cross_type = "f2") {
81
  # Filter individuals
82
  missing_rate <- rowMeans(is.na(geno_mat))
83
  valid_inds <- missing_rate <= 0.5
 
 
 
84
  geno_mat <- geno_mat[valid_inds, , drop = FALSE]
85
  ind_ids <- ind_ids[valid_inds]
86
 
@@ -88,6 +100,10 @@ parse_custom_cross <- function(geno_path, pheno_path, cross_type = "f2") {
88
  pheno_raw <- read.csv(pheno_path, header = TRUE, stringsAsFactors = FALSE,
89
  check.names = FALSE, na.strings = c("NA", "", "N/A"))
90
 
 
 
 
 
91
  pheno_ids <- as.character(pheno_raw[, 1])
92
  if (any(duplicated(pheno_ids))) pheno_ids <- make.unique(pheno_ids)
93
  pheno_df <- pheno_raw[, -1, drop = FALSE]
@@ -99,7 +115,9 @@ parse_custom_cross <- function(geno_path, pheno_path, cross_type = "f2") {
99
 
100
  # Align
101
  common_ids <- intersect(ind_ids, pheno_ids)
102
- if (length(common_ids) == 0) stop("No matching IDs")
 
 
103
 
104
  geno_mat <- geno_mat[common_ids, , drop = FALSE]
105
  pheno_df <- pheno_df[common_ids, , drop = FALSE]
@@ -107,6 +125,9 @@ parse_custom_cross <- function(geno_path, pheno_path, cross_type = "f2") {
107
  # Filter markers
108
  marker_missing <- colMeans(is.na(geno_mat))
109
  valid_markers <- marker_missing <= 0.5
 
 
 
110
  geno_mat <- geno_mat[, valid_markers, drop = FALSE]
111
  chromosomes <- chromosomes[valid_markers]
112
  positions <- positions[valid_markers]
@@ -145,6 +166,10 @@ parse_custom_cross <- function(geno_path, pheno_path, cross_type = "f2") {
145
  }
146
  }
147
 
 
 
 
 
148
  cross <- list(geno = geno_list, pheno = pheno_df)
149
  class(cross) <- c(cross_type, "cross")
150
  cross <- jittermap(cross)
@@ -162,44 +187,37 @@ run_all_models <- function(cross, pheno_col) {
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,20 +226,17 @@ run_all_models <- function(cross, pheno_col) {
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)
@@ -296,10 +311,10 @@ find_qtls <- function(scan, threshold) {
296
  }
297
 
298
  # ============================================================================
299
- # 10+ UNIQUE VISUALIZATIONS
300
  # ============================================================================
301
 
302
- # Plot 1: Multi-Model Manhattan Comparison
303
  plot_multi_manhattan <- function(models, threshold = 3) {
304
  if (is.null(models) || length(models) == 0) return(NULL)
305
 
@@ -320,97 +335,34 @@ plot_multi_manhattan <- function(models, threshold = 3) {
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",
327
- strip.background = element_rect(fill = "lightblue", color = NA),
328
- strip.text = element_text(face = "bold"))
329
- }
330
-
331
- # Plot 2: Model Performance Heatmap
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
-
338
- for (name in names(models)) {
339
- scan <- models[[name]]
340
- if (!is.null(scan)) {
341
- model_names <- c(model_names, toupper(name))
342
- chr_lods <- tapply(scan$lod, scan$chr, max)
343
- if (length(perf_matrix) == 0) {
344
- perf_matrix <- matrix(chr_lods, nrow = 1)
345
- } else {
346
- perf_matrix <- rbind(perf_matrix, chr_lods[1:ncol(perf_matrix)])
347
- }
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
-
369
- df <- as.data.frame(scan)
370
- df$chr_num <- as.numeric(factor(df$chr, levels = unique(df$chr)))
371
-
372
- plot_ly(df, x = ~chr_num, y = ~pos, z = ~lod, type = "mesh3d",
373
- intensity = ~lod, colorscale = "Viridis",
374
- text = ~paste("Chr:", chr, "<br>Pos:", pos, "<br>LOD:", round(lod, 3)),
375
- hoverinfo = "text") %>%
376
- layout(title = "3D LOD Surface Plot",
377
- scene = list(xaxis = list(title = "Chromosome"),
378
- yaxis = list(title = "Position (cM)"),
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
 
386
- qq_data <- data.frame()
387
- for (name in names(models)) {
388
- scan <- models[[name]]
389
- if (!is.null(scan)) {
390
- expected <- -log10(ppoints(length(scan$lod)))
391
- observed <- -log10(rank(scan$lod, ties.method = "first") / (length(scan$lod) + 1))
392
- qq_data <- rbind(qq_data, data.frame(
393
- Model = toupper(name),
394
- Expected = expected,
395
- Observed = observed
396
- ))
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) +
405
- scale_color_brewer(palette = "Set2") +
406
- labs(title = "Q-Q Plot: Model Comparison",
407
- x = "Expected -log10(p)", y = "Observed -log10(p)") +
408
  theme_minimal() +
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
 
416
  df <- as.data.frame(scan)
@@ -418,102 +370,58 @@ plot_lod_ridges <- function(scan) {
418
 
419
  ggplot(df, aes(x = lod, y = chr, fill = after_stat(x))) +
420
  geom_density_ridges_gradient(scale = 2, rel_min_height = 0.01) +
421
- scale_fill_viridis_c(option = "C", name = "LOD Score") +
422
- labs(title = "LOD Score Distribution by Chromosome",
423
- x = "LOD Score", y = "Chromosome") +
424
- theme_ridges() +
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
 
432
  ggplot(qtls, aes(x = Chromosome, y = Position_cM, size = LOD, color = PVE_percent)) +
433
  geom_point(alpha = 0.7) +
434
- scale_size_continuous(range = c(3, 15), name = "LOD Score") +
435
- scale_color_gradientn(colors = c("blue", "green", "yellow", "red"), name = "PVE (%)") +
436
- labs(title = "QTL Effect Size Bubble Plot",
437
- x = "Chromosome", y = "Position (cM)") +
438
  theme_minimal() +
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
-
446
- cor_matrix <- cor(cross$pheno, use = "complete.obs")
447
-
448
- corrplot(cor_matrix,
449
- method = "circle",
450
- type = "upper",
451
- order = "hclust",
452
- addCoef.col = "black",
453
- tl.col = "black",
454
- tl.srt = 45,
455
- title = "Trait Correlation Circle",
456
- mar = c(0, 0, 2, 0))
457
- }
458
-
459
- # Plot 8: Genetic Map Density
460
- plot_map_density <- function(cross) {
461
- if (is.null(cross)) return(NULL)
462
-
463
- map <- pull.map(cross)
464
- density_data <- data.frame()
465
-
466
- for (chr in names(map)) {
467
- positions <- map[[chr]]
468
- if (length(positions) > 1) {
469
- gaps <- diff(positions)
470
- density_data <- rbind(density_data,
471
- data.frame(Chromosome = chr, Gap = gaps))
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") +
480
- labs(title = "Genetic Map Density",
481
- x = "Inter-marker Distance (cM)", y = "Count") +
482
- theme_minimal() +
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
-
493
- top_markers <- order(first_model$lod, decreasing = TRUE)[1:min(50, nrow(first_model))]
494
-
495
- parallel_data <- data.frame(Position = first_model$pos[top_markers])
496
  for (name in names(models)) {
497
  scan <- models[[name]]
498
  if (!is.null(scan)) {
499
- parallel_data[[toupper(name)]] <- scan$lod[top_markers]
 
 
 
 
500
  }
501
  }
502
 
503
- plot_data <- pivot_longer(parallel_data, cols = -Position,
504
- names_to = "Model", values_to = "LOD")
 
 
 
 
 
 
 
 
505
 
506
- ggplot(plot_data, aes(x = Position, y = LOD, color = Model, group = Model)) +
507
- geom_line(size = 1) +
508
- scale_color_brewer(palette = "Set1") +
509
- labs(title = "Model Comparison at Top Markers",
510
- x = "Position (cM)", y = "LOD Score") +
511
- theme_minimal() +
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])
@@ -527,54 +435,51 @@ plot_phenotype_genotype <- function(cross, qtl_row, trait) {
527
  genotypes <- pull.geno(cross)[, geno_idx]
528
  phenotypes <- cross$pheno[[trait]]
529
 
530
- df <- data.frame(
531
- Genotype = factor(genotypes, levels = sort(unique(genotypes))),
532
- Phenotype = phenotypes
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) {
540
- df$Genotype <- recode(df$Genotype, `1` = "A", `2` = "B")
541
- }
542
 
543
  ggplot(df, aes(x = Genotype, y = Phenotype, fill = Genotype)) +
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")
552
  }
553
 
554
- # Plot 11: LOD Contour Plot
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
 
561
- for (chr in chrs) {
562
- chr_data <- scan[scan$chr == chr, ]
563
- chr_data$chr_num <- as.numeric(factor(chr, levels = chrs))
564
- contour_data <- rbind(contour_data, chr_data)
 
 
 
 
 
 
 
565
  }
566
 
567
- ggplot(contour_data, aes(x = pos, y = chr_num, z = lod)) +
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()
@@ -593,23 +498,78 @@ plot_model_radar <- function(models) {
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")
605
 
606
  ggplot(radar_data, aes(x = Metric, y = Value, color = Model, group = Model)) +
607
- geom_line(size = 1) +
608
- geom_point(size = 3) +
609
- coord_polar() +
610
- scale_color_brewer(palette = "Set1") +
611
- labs(title = "Model Performance Radar Chart",
612
- y = "Normalized Score") +
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
613
  theme_minimal()
614
  }
615
 
@@ -618,37 +578,35 @@ plot_model_radar <- function(models) {
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
 
638
  selectInput("cross_type", "Cross Type",
639
- choices = c("F2 Intercross" = "f2", "Backcross" = "bc", "RIL" = "riself"),
640
- selected = "f2"),
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
 
649
  actionButton("run_analysis", "RUN 10 MODELS",
650
  icon = icon("play"),
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%;")
@@ -657,15 +615,12 @@ ui <- dashboardPage(
657
 
658
  dashboardBody(
659
  useShinyjs(),
660
- tags$head(
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
 
667
  tabItems(
668
- # Data Tab
669
  tabItem(tabName = "data",
670
  fluidRow(
671
  valueBoxOutput("n_individuals"),
@@ -673,144 +628,91 @@ ui <- dashboardPage(
673
  valueBoxOutput("n_chromosomes")
674
  ),
675
  fluidRow(
676
- box(title = "Data Summary", status = "primary", solidHeader = TRUE, width = 12,
677
- verbatimTextOutput("data_summary")
678
- )
679
  ),
680
  fluidRow(
681
  box(title = "Genetic Map", status = "info", width = 12,
682
- plotOutput("genetic_map", height = "500px") %>% withSpinner()
683
- )
684
  )
685
  ),
686
 
687
- # Models Tab
688
  tabItem(tabName = "models",
689
  fluidRow(
690
- box(title = "Analysis Status", status = "primary", solidHeader = TRUE, width = 12,
691
- verbatimTextOutput("analysis_status")
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
  )
709
  ),
710
 
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,
746
- plotOutput("map_density", height = "500px") %>% withSpinner()
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
- )
754
  )
755
  ),
756
 
757
- # Results Tab
758
  tabItem(tabName = "results",
759
  fluidRow(
760
  box(title = "Significant QTLs", status = "primary", width = 12,
761
- DTOutput("qtl_table") %>% withSpinner()
762
- )
763
  ),
764
  fluidRow(
765
  box(title = "Model Summary", status = "info", width = 12,
766
- DTOutput("model_summary") %>% withSpinner()
767
- )
768
  ),
769
  fluidRow(
770
  box(title = "Permutation Results", status = "success", width = 12,
771
- DTOutput("permutation_table") %>% withSpinner()
772
- )
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
  )
788
  ),
789
 
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
  )
815
  )
816
  )
@@ -823,7 +725,6 @@ ui <- dashboardPage(
823
 
824
  server <- function(input, output, session) {
825
 
826
- # Reactive values
827
  cross_data <- reactiveVal(NULL)
828
  all_models <- reactiveVal(NULL)
829
  qtl_results <- reactiveVal(NULL)
@@ -833,33 +734,27 @@ server <- function(input, output, session) {
833
  # Value boxes
834
  output$n_individuals <- renderValueBox({
835
  cross <- cross_data()
836
- valueBox(
837
- ifelse(is.null(cross), 0, nind(cross)),
838
- "Individuals", icon = icon("users"), color = "blue"
839
- )
840
  })
841
 
842
  output$n_markers <- renderValueBox({
843
  cross <- cross_data()
844
- valueBox(
845
- ifelse(is.null(cross), 0, totmar(cross)),
846
- "Markers", icon = icon("dna"), color = "green"
847
- )
848
  })
849
 
850
  output$n_chromosomes <- renderValueBox({
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
 
858
- # Load data
859
  observeEvent(c(input$geno_file, input$pheno_file), {
860
  req(input$geno_file, input$pheno_file)
861
 
862
- showNotification("Loading data...", type = "info", duration = 3)
863
 
864
  tryCatch({
865
  cross <- parse_custom_cross(
@@ -873,23 +768,24 @@ server <- function(input, output, session) {
873
  choices = names(cross$pheno),
874
  selected = names(cross$pheno)[1])
875
 
876
- showNotification("Data loaded successfully!", type = "success", duration = 3)
 
877
 
878
  }, error = function(e) {
879
- showNotification(paste("Error:", e$message), type = "error", duration = 10)
880
  })
881
  })
882
 
883
- # Run all models
884
  observeEvent(input$run_analysis, {
885
  cross <- cross_data()
886
  req(cross, input$pheno_trait)
887
 
888
- showNotification("Running 10 mapping models...", type = "info", duration = 5)
889
 
890
  withProgress(message = "Running 10 QTL Models", value = 0, {
891
 
892
- incProgress(0.2, detail = "Running all mapping algorithms...")
893
  pheno_idx <- which(names(cross$pheno) == input$pheno_trait)
894
  models <- run_all_models(cross, pheno_idx)
895
  all_models(models)
@@ -906,20 +802,19 @@ server <- function(input, output, session) {
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
  })
921
 
922
- # Data summary
923
  output$data_summary <- renderPrint({
924
  cross <- cross_data()
925
  if (is.null(cross)) {
@@ -929,106 +824,33 @@ server <- function(input, output, session) {
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)
951
-
952
- map <- pull.map(cross)
953
- df <- data.frame()
954
- for (chr in names(map)) {
955
- positions <- map[[chr]]
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) +
962
- labs(title = "Genetic Map", x = "Chromosome", y = "Position (cM)") +
963
- theme_minimal() +
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 != "")
@@ -1039,7 +861,7 @@ server <- function(input, output, session) {
1039
  qtl_idx <- which(paste0("Chr", qtls$Chromosome, "_", qtls$Position_cM, "cM") == input$effect_qtl)
1040
  if (length(qtl_idx) == 0) return(NULL)
1041
 
1042
- plot_phenotype_genotype(cross, qtls[qtl_idx[1], , drop = FALSE], input$pheno_trait)
1043
  })
1044
 
1045
  # Tables
@@ -1065,7 +887,6 @@ server <- function(input, output, session) {
1065
  ))
1066
  }
1067
  }
1068
-
1069
  datatable(summary_df, options = list(pageLength = 10), rownames = FALSE)
1070
  })
1071
 
@@ -1078,63 +899,8 @@ server <- function(input, output, session) {
1078
  thr <- summary(perms, alpha = a)[1]
1079
  if (is.na(thr)) NA else round(thr, 3)
1080
  })
1081
-
1082
- perm_df <- data.frame(Alpha = alphas, Threshold = thresholds)
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)
1089
-
1090
- comparison_df <- data.frame()
1091
- for (name in names(models)) {
1092
- scan <- models[[name]]
1093
- if (!is.null(scan)) {
1094
- comparison_df <- rbind(comparison_df, data.frame(
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
-
1114
- chrs <- unique(first_model$chr)
1115
- best_df <- data.frame()
1116
-
1117
- for (chr in chrs) {
1118
- best_lod <- -Inf
1119
- best_model <- ""
1120
- for (name in names(models)) {
1121
- scan <- models[[name]]
1122
- if (!is.null(scan)) {
1123
- chr_max <- max(scan$lod[scan$chr == chr], na.rm = TRUE)
1124
- if (chr_max > best_lod) {
1125
- best_lod <- chr_max
1126
- best_model <- name
1127
- }
1128
- }
1129
- }
1130
- best_df <- rbind(best_df, data.frame(
1131
- Chromosome = chr,
1132
- Best_Model = toupper(best_model),
1133
- Peak_LOD = round(best_lod, 3)
1134
- ))
1135
- }
1136
-
1137
- datatable(best_df, options = list(pageLength = 15), rownames = FALSE)
1138
  })
1139
 
1140
  # Download
@@ -1145,7 +911,7 @@ server <- function(input, output, session) {
1145
  if (!is.null(qtls) && nrow(qtls) > 0) {
1146
  write.csv(qtls, file, row.names = FALSE)
1147
  } else {
1148
- write.csv(data.frame(Message = "No significant QTLs found"), file, row.names = FALSE)
1149
  }
1150
  }
1151
  )
 
1
  # ============================================================================
2
+ # ADVANCED QTL ANALYSIS PIPELINE - FULLY FIXED
3
+ # 10 Models + 10+ Visualizations - No Notification Errors
 
4
  # ============================================================================
5
 
6
  # Load libraries
 
30
  }
31
 
32
  # ============================================================================
33
+ # SAFE NOTIFICATION FUNCTION - FIXED
34
  # ============================================================================
35
 
36
+ safe_notification <- function(msg, type = "default") {
37
  tryCatch({
38
+ if (type == "default") {
39
+ showNotification(msg, duration = 3)
40
+ } else if (type == "message") {
41
+ showNotification(msg, type = "message", duration = 3)
42
+ } else if (type == "warning") {
43
+ showNotification(msg, type = "warning", duration = 5)
44
+ } else if (type == "error") {
45
+ showNotification(msg, type = "error", duration = 8)
46
+ } else {
47
+ showNotification(msg, duration = 3)
48
+ }
49
  }, error = function(e) {
50
+ message(paste("Notification:", msg))
51
  })
52
  }
53
 
 
90
  # Filter individuals
91
  missing_rate <- rowMeans(is.na(geno_mat))
92
  valid_inds <- missing_rate <= 0.5
93
+ if (sum(valid_inds) == 0) {
94
+ stop("No valid individuals found")
95
+ }
96
  geno_mat <- geno_mat[valid_inds, , drop = FALSE]
97
  ind_ids <- ind_ids[valid_inds]
98
 
 
100
  pheno_raw <- read.csv(pheno_path, header = TRUE, stringsAsFactors = FALSE,
101
  check.names = FALSE, na.strings = c("NA", "", "N/A"))
102
 
103
+ if (ncol(pheno_raw) < 2) {
104
+ stop("Phenotype file must have at least 2 columns")
105
+ }
106
+
107
  pheno_ids <- as.character(pheno_raw[, 1])
108
  if (any(duplicated(pheno_ids))) pheno_ids <- make.unique(pheno_ids)
109
  pheno_df <- pheno_raw[, -1, drop = FALSE]
 
115
 
116
  # Align
117
  common_ids <- intersect(ind_ids, pheno_ids)
118
+ if (length(common_ids) == 0) {
119
+ stop("No matching IDs between genotype and phenotype files")
120
+ }
121
 
122
  geno_mat <- geno_mat[common_ids, , drop = FALSE]
123
  pheno_df <- pheno_df[common_ids, , drop = FALSE]
 
125
  # Filter markers
126
  marker_missing <- colMeans(is.na(geno_mat))
127
  valid_markers <- marker_missing <= 0.5
128
+ if (sum(valid_markers) == 0) {
129
+ stop("No valid markers found")
130
+ }
131
  geno_mat <- geno_mat[, valid_markers, drop = FALSE]
132
  chromosomes <- chromosomes[valid_markers]
133
  positions <- positions[valid_markers]
 
166
  }
167
  }
168
 
169
+ if (length(geno_list) == 0) {
170
+ stop("No valid chromosomes found")
171
+ }
172
+
173
  cross <- list(geno = geno_list, pheno = pheno_df)
174
  class(cross) <- c(cross_type, "cross")
175
  cross <- jittermap(cross)
 
187
  # Model 1: Haley-Knott Regression
188
  tryCatch({
189
  models$hk <- scanone(cross, pheno.col = pheno_col, method = "hk")
 
190
  }, error = function(e) message("HK failed: ", e$message))
191
 
192
  # Model 2: EM Algorithm
193
  tryCatch({
194
  models$em <- scanone(cross, pheno.col = pheno_col, method = "em")
 
195
  }, error = function(e) message("EM failed: ", e$message))
196
 
197
  # Model 3: Extended Haley-Knott
198
  tryCatch({
199
  models$ehk <- scanone(cross, pheno.col = pheno_col, method = "ehk")
 
200
  }, error = function(e) message("EHK failed: ", e$message))
201
 
202
  # Model 4: Multiple Imputation
203
  tryCatch({
204
  cross_sim <- sim.geno(cross, n.draws = 32, step = 1)
205
  models$imp <- scanone(cross_sim, pheno.col = pheno_col, method = "imp")
 
206
  }, error = function(e) message("IMP failed: ", e$message))
207
 
208
  # Model 5: Marker Regression
209
  tryCatch({
210
  models$mr <- scanone(cross, pheno.col = pheno_col, method = "mr")
 
211
  }, error = function(e) message("MR failed: ", e$message))
212
 
213
  # Model 6: Non-parametric
214
  tryCatch({
215
  models$np <- scanone(cross, pheno.col = pheno_col, method = "np")
 
216
  }, error = function(e) message("NP failed: ", e$message))
217
 
218
  # Model 7: Composite Interval Mapping
219
  tryCatch({
220
  models$cim <- cim(cross, pheno.col = pheno_col, method = "hk", window = 10)
 
221
  }, error = function(e) message("CIM failed: ", e$message))
222
 
223
  # Model 8: Multiple QTL Mapping
 
226
  cofactors <- which(scan_hk$lod > 2)
227
  if (length(cofactors) > 0) {
228
  models$mqm <- mqm(cross, pheno.col = pheno_col, cofactors = cofactors)
 
229
  }
230
  }, error = function(e) message("MQM failed: ", e$message))
231
 
232
  # Model 9: Binary Trait
233
  tryCatch({
234
  models$binary <- scanone(cross, pheno.col = pheno_col, method = "binary")
 
235
  }, error = function(e) message("Binary failed: ", e$message))
236
 
237
  # Model 10: Normal Model
238
  tryCatch({
239
  models$normal <- scanone(cross, pheno.col = pheno_col, method = "normal")
 
240
  }, error = function(e) message("Normal failed: ", e$message))
241
 
242
  return(models)
 
311
  }
312
 
313
  # ============================================================================
314
+ # PLOTTING FUNCTIONS (12+ Visualizations)
315
  # ============================================================================
316
 
317
+ # Plot 1: Multi-Model Manhattan
318
  plot_multi_manhattan <- function(models, threshold = 3) {
319
  if (is.null(models) || length(models) == 0) return(NULL)
320
 
 
335
  geom_hline(yintercept = threshold, color = "red", linetype = "dashed", size = 1) +
336
  facet_wrap(~chr, scales = "free_x", ncol = 3) +
337
  scale_color_brewer(palette = "Set1") +
338
+ labs(title = "Multi-Model QTL Comparison", x = "Position (cM)", y = "LOD Score") +
 
339
  theme_minimal() +
340
+ theme(legend.position = "bottom", legend.text = element_text(size = 8))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
341
  }
342
 
343
+ # Plot 2: Genetic Map
344
+ plot_genetic_map <- function(cross) {
345
+ if (is.null(cross)) return(NULL)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
346
 
347
+ map <- pull.map(cross)
348
+ df <- data.frame()
349
+ for (chr in names(map)) {
350
+ positions <- map[[chr]]
351
+ df <- rbind(df, data.frame(Chromosome = chr, Position = positions))
 
 
 
 
 
 
 
352
  }
353
 
354
+ df$Chromosome <- factor(df$Chromosome, levels = names(map))
355
 
356
+ ggplot(df, aes(x = Chromosome, y = Position)) +
357
+ geom_segment(aes(xend = Chromosome, yend = 0), color = "gray70", size = 1) +
358
+ geom_point(color = "steelblue", size = 2, alpha = 0.7) +
359
+ labs(title = "Genetic Map", x = "Chromosome", y = "Position (cM)") +
 
 
360
  theme_minimal() +
361
+ theme(axis.text.x = element_text(angle = 45, hjust = 1))
362
  }
363
 
364
+ # Plot 3: Ridge Plot
365
+ plot_ridge <- function(scan) {
366
  if (is.null(scan)) return(NULL)
367
 
368
  df <- as.data.frame(scan)
 
370
 
371
  ggplot(df, aes(x = lod, y = chr, fill = after_stat(x))) +
372
  geom_density_ridges_gradient(scale = 2, rel_min_height = 0.01) +
373
+ scale_fill_viridis_c(name = "LOD") +
374
+ labs(title = "LOD Distribution by Chromosome", x = "LOD", y = "Chromosome") +
375
+ theme_minimal()
 
 
376
  }
377
 
378
+ # Plot 4: Bubble Plot
379
+ plot_bubbles <- function(qtls) {
380
  if (is.null(qtls) || nrow(qtls) == 0) return(NULL)
381
 
382
  ggplot(qtls, aes(x = Chromosome, y = Position_cM, size = LOD, color = PVE_percent)) +
383
  geom_point(alpha = 0.7) +
384
+ scale_size_continuous(range = c(3, 15), name = "LOD") +
385
+ scale_color_gradientn(colors = c("blue", "green", "red"), name = "PVE %") +
386
+ labs(title = "QTL Effect Sizes", x = "Chromosome", y = "Position (cM)") +
 
387
  theme_minimal() +
388
  theme(axis.text.x = element_text(angle = 45, hjust = 1))
389
  }
390
 
391
+ # Plot 5: QQ Plot
392
+ plot_qq <- function(models) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
393
  if (is.null(models) || length(models) == 0) return(NULL)
394
 
395
+ qq_data <- data.frame()
 
 
 
 
 
396
  for (name in names(models)) {
397
  scan <- models[[name]]
398
  if (!is.null(scan)) {
399
+ expected <- -log10(ppoints(length(scan$lod)))
400
+ observed <- -log10(rank(scan$lod) / (length(scan$lod) + 1))
401
+ qq_data <- rbind(qq_data, data.frame(
402
+ Model = toupper(name), Expected = expected, Observed = observed
403
+ ))
404
  }
405
  }
406
 
407
+ ggplot(qq_data, aes(x = Expected, y = Observed, color = Model)) +
408
+ geom_point(size = 1, alpha = 0.6) +
409
+ geom_abline(intercept = 0, slope = 1, color = "red", linetype = "dashed") +
410
+ labs(title = "Q-Q Plot", x = "Expected", y = "Observed") +
411
+ theme_minimal()
412
+ }
413
+
414
+ # Plot 6: Correlation Circle
415
+ plot_correlation <- function(cross) {
416
+ if (is.null(cross) || ncol(cross$pheno) < 2) return(NULL)
417
 
418
+ cor_matrix <- cor(cross$pheno, use = "complete.obs")
419
+ corrplot(cor_matrix, method = "circle", type = "upper",
420
+ order = "hclust", addCoef.col = "black", tl.cex = 0.8)
 
 
 
 
421
  }
422
 
423
+ # Plot 7: Violin Plot
424
+ plot_violin <- function(cross, qtl_row, trait) {
425
  if (is.null(cross) || is.null(qtl_row) || nrow(qtl_row) == 0) return(NULL)
426
 
427
  chr_name <- as.character(qtl_row$Chromosome[1])
 
435
  genotypes <- pull.geno(cross)[, geno_idx]
436
  phenotypes <- cross$pheno[[trait]]
437
 
438
+ df <- data.frame(Genotype = factor(genotypes), Phenotype = phenotypes)
 
 
 
439
  df <- df[!is.na(df$Genotype) & !is.na(df$Phenotype), ]
440
 
441
+ if (nrow(df) == 0) return(NULL)
 
 
 
 
 
442
 
443
  ggplot(df, aes(x = Genotype, y = Phenotype, fill = Genotype)) +
444
  geom_violin(alpha = 0.6, trim = FALSE) +
445
  geom_boxplot(width = 0.2, alpha = 0.8) +
446
  stat_summary(fun = mean, geom = "point", shape = 18, size = 4, color = "red") +
447
+ labs(title = paste("Phenotype by Genotype at", marker_name), y = trait) +
 
 
448
  theme_minimal() +
449
  theme(legend.position = "none")
450
  }
451
 
452
+ # Plot 8: Model Heatmap
453
+ plot_heatmap <- function(models) {
454
+ if (is.null(models) || length(models) == 0) return(NULL)
455
 
456
+ perf_matrix <- matrix(NA, nrow = length(models), ncol = 0)
457
+ model_names <- c()
458
 
459
+ for (name in names(models)) {
460
+ scan <- models[[name]]
461
+ if (!is.null(scan)) {
462
+ model_names <- c(model_names, toupper(name))
463
+ chr_lods <- tapply(scan$lod, scan$chr, max)
464
+ if (length(perf_matrix) == 0) {
465
+ perf_matrix <- matrix(chr_lods, nrow = 1)
466
+ } else {
467
+ perf_matrix <- rbind(perf_matrix, chr_lods[1:ncol(perf_matrix)])
468
+ }
469
+ }
470
  }
471
 
472
+ if (nrow(perf_matrix) == 0) return(NULL)
473
+
474
+ rownames(perf_matrix) <- model_names
475
+ colnames(perf_matrix) <- names(chr_lods)
476
+
477
+ pheatmap(perf_matrix, color = viridis(100),
478
+ main = "Model Performance", display_numbers = TRUE, fontsize = 10)
479
  }
480
 
481
+ # Plot 9: Radar Chart
482
+ plot_radar <- function(models) {
483
  if (is.null(models) || length(models) == 0) return(NULL)
484
 
485
  metrics <- data.frame()
 
498
  if (nrow(metrics) == 0) return(NULL)
499
 
500
  # Normalize
 
501
  for (col in c("Max_LOD", "Mean_LOD", "N_Peaks")) {
502
+ metrics[[col]] <- (metrics[[col]] - min(metrics[[col]])) /
503
+ (max(metrics[[col]]) - min(metrics[[col]]))
504
  }
505
 
506
+ radar_data <- pivot_longer(metrics, cols = c("Max_LOD", "Mean_LOD", "N_Peaks"),
 
507
  names_to = "Metric", values_to = "Value")
508
 
509
  ggplot(radar_data, aes(x = Metric, y = Value, color = Model, group = Model)) +
510
+ geom_line(size = 1) + geom_point(size = 3) + coord_polar() +
511
+ labs(title = "Model Comparison") + theme_minimal()
512
+ }
513
+
514
+ # Plot 10: Parallel Coordinates
515
+ plot_parallel <- function(models) {
516
+ if (is.null(models) || length(models) == 0) return(NULL)
517
+
518
+ first_model <- models[[1]]
519
+ if (is.null(first_model)) return(NULL)
520
+
521
+ top_markers <- order(first_model$lod, decreasing = TRUE)[1:min(50, nrow(first_model))]
522
+
523
+ parallel_data <- data.frame(Position = first_model$pos[top_markers])
524
+ for (name in names(models)) {
525
+ scan <- models[[name]]
526
+ if (!is.null(scan)) {
527
+ parallel_data[[toupper(name)]] <- scan$lod[top_markers]
528
+ }
529
+ }
530
+
531
+ plot_data <- pivot_longer(parallel_data, cols = -Position,
532
+ names_to = "Model", values_to = "LOD")
533
+
534
+ ggplot(plot_data, aes(x = Position, y = LOD, color = Model, group = Model)) +
535
+ geom_line(size = 1) + labs(title = "Model Comparison at Top Markers") +
536
+ theme_minimal() + theme(legend.position = "bottom")
537
+ }
538
+
539
+ # Plot 11: 3D Surface
540
+ plot_3d <- function(scan) {
541
+ if (is.null(scan)) return(NULL)
542
+
543
+ df <- as.data.frame(scan)
544
+ df$chr_num <- as.numeric(factor(df$chr, levels = unique(df$chr)))
545
+
546
+ plot_ly(df, x = ~chr_num, y = ~pos, z = ~lod, type = "mesh3d",
547
+ intensity = ~lod, colorscale = "Viridis",
548
+ text = ~paste("Chr:", chr, "<br>Pos:", pos, "<br>LOD:", round(lod, 3))) %>%
549
+ layout(title = "3D LOD Surface", scene = list(
550
+ xaxis = list(title = "Chromosome"),
551
+ yaxis = list(title = "Position"),
552
+ zaxis = list(title = "LOD")))
553
+ }
554
+
555
+ # Plot 12: Contour Plot
556
+ plot_contour <- function(scan) {
557
+ if (is.null(scan)) return(NULL)
558
+
559
+ chrs <- unique(scan$chr)
560
+ contour_data <- data.frame()
561
+
562
+ for (chr in chrs) {
563
+ chr_data <- scan[scan$chr == chr, ]
564
+ chr_data$chr_num <- as.numeric(factor(chr, levels = chrs))
565
+ contour_data <- rbind(contour_data, chr_data)
566
+ }
567
+
568
+ ggplot(contour_data, aes(x = pos, y = chr_num, z = lod)) +
569
+ geom_contour_filled(bins = 10) +
570
+ scale_fill_viridis_d() +
571
+ scale_y_continuous(breaks = 1:length(chrs), labels = chrs) +
572
+ labs(title = "LOD Contour Plot", x = "Position", y = "Chromosome") +
573
  theme_minimal()
574
  }
575
 
 
578
  # ============================================================================
579
 
580
  ui <- dashboardPage(
581
+ dashboardHeader(title = "QTL Analysis - 10 Models"),
582
 
583
  dashboardSidebar(width = 320,
584
  sidebarMenu(
585
  menuItem("Data Input", tabName = "data", icon = icon("upload")),
586
  menuItem("10 Models", tabName = "models", icon = icon("cogs")),
587
+ menuItem("12+ Plots", tabName = "viz", icon = icon("chart-bar")),
588
  menuItem("Results", tabName = "results", icon = icon("table")),
 
589
  menuItem("Help", tabName = "help", icon = icon("question-circle"))
590
  ),
591
 
592
  div(style = "padding: 15px;",
593
+ h4("Upload Files"),
594
  fileInput("geno_file", "Genotype CSV", accept = ".csv"),
595
  fileInput("pheno_file", "Phenotype CSV", accept = ".csv"),
596
 
597
  selectInput("cross_type", "Cross Type",
598
+ choices = c("F2" = "f2", "Backcross" = "bc", "RIL" = "riself")),
 
599
 
600
  hr(),
601
 
602
  h4("Settings"),
603
+ selectInput("pheno_trait", "Phenotype", choices = NULL),
604
  numericInput("lod_threshold", "LOD Threshold", value = 3.0, min = 0, max = 20, step = 0.5),
605
  numericInput("n_permutations", "Permutations", value = 100, min = 0, max = 1000),
606
 
607
  actionButton("run_analysis", "RUN 10 MODELS",
608
  icon = icon("play"),
609
+ style = "background-color: #3c8dbc; color: white; width: 100%;"),
610
 
611
  br(), br(),
612
  downloadButton("download_results", "Download Results", style = "width: 100%;")
 
615
 
616
  dashboardBody(
617
  useShinyjs(),
618
+ tags$head(tags$style(HTML("
619
+ .content-wrapper, .right-side { background-color: #f4f4f4; }
620
+ .box { border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
621
+ "))),
 
 
622
 
623
  tabItems(
 
624
  tabItem(tabName = "data",
625
  fluidRow(
626
  valueBoxOutput("n_individuals"),
 
628
  valueBoxOutput("n_chromosomes")
629
  ),
630
  fluidRow(
631
+ box(title = "Data Summary", status = "primary", width = 12,
632
+ verbatimTextOutput("data_summary"))
 
633
  ),
634
  fluidRow(
635
  box(title = "Genetic Map", status = "info", width = 12,
636
+ plotOutput("genetic_map", height = "500px") %>% withSpinner())
 
637
  )
638
  ),
639
 
 
640
  tabItem(tabName = "models",
641
  fluidRow(
642
+ box(title = "Status", status = "primary", width = 12,
643
+ verbatimTextOutput("analysis_status"))
 
644
  ),
645
  fluidRow(
646
  box(title = "Multi-Model Manhattan", status = "info", width = 12,
647
+ plotOutput("multi_manhattan", height = "600px") %>% withSpinner())
 
648
  ),
649
  fluidRow(
650
  box(title = "Model Heatmap", status = "success", width = 12,
651
+ plotOutput("model_heatmap", height = "600px") %>% withSpinner())
 
652
  ),
653
  fluidRow(
654
  box(title = "Radar Chart", status = "warning", width = 12,
655
+ plotOutput("radar_chart", height = "500px") %>% withSpinner())
 
656
  )
657
  ),
658
 
 
659
  tabItem(tabName = "viz",
660
  fluidRow(
661
+ box(title = "3D Surface", status = "primary", width = 12,
662
+ plotlyOutput("surface_3d", height = "600px") %>% withSpinner())
 
663
  ),
664
  fluidRow(
665
  box(title = "Ridge Plot", status = "info", width = 6,
666
+ plotOutput("ridge_plot", height = "500px") %>% withSpinner()),
 
667
  box(title = "Contour Plot", status = "success", width = 6,
668
+ plotOutput("contour_plot", height = "500px") %>% withSpinner())
 
669
  ),
670
  fluidRow(
671
  box(title = "Bubble Plot", status = "warning", width = 12,
672
+ plotOutput("bubble_plot", height = "500px") %>% withSpinner())
 
673
  ),
674
  fluidRow(
675
  box(title = "Parallel Coordinates", status = "danger", width = 12,
676
+ plotOutput("parallel_plot", height = "500px") %>% withSpinner())
 
677
  ),
678
  fluidRow(
679
  box(title = "QQ Plot", status = "primary", width = 12,
680
+ plotOutput("qq_plot", height = "500px") %>% withSpinner())
 
681
  ),
682
  fluidRow(
683
  box(title = "Correlation Circle", status = "info", width = 6,
684
+ plotOutput("correlation_plot", height = "500px") %>% withSpinner()),
685
+ box(title = "Violin Plot", status = "success", width = 6,
 
 
 
 
 
 
686
  selectInput("effect_qtl", "Select QTL:", choices = NULL),
687
+ plotOutput("violin_plot", height = "400px") %>% withSpinner())
 
688
  )
689
  ),
690
 
 
691
  tabItem(tabName = "results",
692
  fluidRow(
693
  box(title = "Significant QTLs", status = "primary", width = 12,
694
+ DTOutput("qtl_table") %>% withSpinner())
 
695
  ),
696
  fluidRow(
697
  box(title = "Model Summary", status = "info", width = 12,
698
+ DTOutput("model_summary") %>% withSpinner())
 
699
  ),
700
  fluidRow(
701
  box(title = "Permutation Results", status = "success", width = 12,
702
+ DTOutput("permutation_table") %>% withSpinner())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
703
  )
704
  ),
705
 
 
706
  tabItem(tabName = "help",
707
  fluidRow(
708
  box(title = "Documentation", status = "primary", width = 12,
709
  HTML("
710
+ <h3>10 Mapping Models</h3>
711
+ <p>HK, EM, EHK, IMP, MR, NP, CIM, MQM, Binary, Normal</p>
712
+ <h3>File Format</h3>
713
+ <p>Genotype: Row1=headers, Row2=chr, Row3=pos, Row4+=data</p>
714
+ <p>Phenotype: First column=ID, rest=traits</p>
715
+ "))
 
 
 
 
 
 
 
 
 
 
 
 
 
716
  )
717
  )
718
  )
 
725
 
726
  server <- function(input, output, session) {
727
 
 
728
  cross_data <- reactiveVal(NULL)
729
  all_models <- reactiveVal(NULL)
730
  qtl_results <- reactiveVal(NULL)
 
734
  # Value boxes
735
  output$n_individuals <- renderValueBox({
736
  cross <- cross_data()
737
+ valueBox(ifelse(is.null(cross), 0, nind(cross)), "Individuals",
738
+ icon = icon("users"), color = "blue")
 
 
739
  })
740
 
741
  output$n_markers <- renderValueBox({
742
  cross <- cross_data()
743
+ valueBox(ifelse(is.null(cross), 0, totmar(cross)), "Markers",
744
+ icon = icon("dna"), color = "green")
 
 
745
  })
746
 
747
  output$n_chromosomes <- renderValueBox({
748
  cross <- cross_data()
749
+ valueBox(ifelse(is.null(cross), 0, nchr(cross)), "Chromosomes",
750
+ icon = icon("chart-line"), color = "yellow")
 
 
751
  })
752
 
753
+ # Load data - FIXED: Using safe_notification
754
  observeEvent(c(input$geno_file, input$pheno_file), {
755
  req(input$geno_file, input$pheno_file)
756
 
757
+ safe_notification("Loading data...", "message")
758
 
759
  tryCatch({
760
  cross <- parse_custom_cross(
 
768
  choices = names(cross$pheno),
769
  selected = names(cross$pheno)[1])
770
 
771
+ safe_notification(paste("Loaded:", nind(cross), "individuals,",
772
+ totmar(cross), "markers"), "message")
773
 
774
  }, error = function(e) {
775
+ safe_notification(paste("Error:", e$message), "error")
776
  })
777
  })
778
 
779
+ # Run analysis - FIXED: Using safe_notification
780
  observeEvent(input$run_analysis, {
781
  cross <- cross_data()
782
  req(cross, input$pheno_trait)
783
 
784
+ safe_notification("Running 10 models...", "message")
785
 
786
  withProgress(message = "Running 10 QTL Models", value = 0, {
787
 
788
+ incProgress(0.2, detail = "Running all models...")
789
  pheno_idx <- which(names(cross$pheno) == input$pheno_trait)
790
  models <- run_all_models(cross, pheno_idx)
791
  all_models(models)
 
802
  }
803
 
804
  if (input$n_permutations > 0 && !is.null(models$hk)) {
805
+ incProgress(0.3, detail = paste(input$n_permutations, "permutations..."))
806
  perms <- scanone(cross, pheno.col = pheno_idx,
807
  n.perm = input$n_permutations, method = "hk")
808
  perm_results(perms)
809
  }
810
 
811
  analysis_done(TRUE)
812
+ n_success <- sum(!sapply(models, is.null))
813
+ safe_notification(paste("Complete!", n_success, "models succeeded"), "message")
 
814
  })
815
  })
816
 
817
+ # Outputs
818
  output$data_summary <- renderPrint({
819
  cross <- cross_data()
820
  if (is.null(cross)) {
 
824
  cat("Individuals:", nind(cross), "\n")
825
  cat("Markers:", totmar(cross), "\n")
826
  cat("Chromosomes:", nchr(cross), "\n")
827
+ cat("Phenotypes:", paste(names(cross$pheno), collapse = ", "))
828
  }
829
  })
830
 
831
  output$analysis_status <- renderPrint({
 
832
  if (!analysis_done()) {
833
+ cat("Click 'RUN 10 MODELS' to start.")
834
  } else {
835
+ models <- all_models()
836
  n_success <- sum(!sapply(models, is.null))
837
  cat("Models completed:", n_success, "/10\n")
838
+ cat("Models:", paste(toupper(names(models)[!sapply(models, is.null)]), collapse = ", "))
839
  }
840
  })
841
 
842
  # Plots
843
+ output$genetic_map <- renderPlot({ plot_genetic_map(cross_data()) })
844
+ output$multi_manhattan <- renderPlot({ plot_multi_manhattan(all_models(), input$lod_threshold) })
845
+ output$model_heatmap <- renderPlot({ plot_heatmap(all_models()) })
846
+ output$radar_chart <- renderPlot({ plot_radar(all_models()) })
847
+ output$surface_3d <- renderPlotly({ plot_3d(all_models()$hk) })
848
+ output$ridge_plot <- renderPlot({ plot_ridge(all_models()$hk) })
849
+ output$contour_plot <- renderPlot({ plot_contour(all_models()$hk) })
850
+ output$bubble_plot <- renderPlot({ plot_bubbles(qtl_results()) })
851
+ output$parallel_plot <- renderPlot({ plot_parallel(all_models()) })
852
+ output$qq_plot <- renderPlot({ plot_qq(all_models()) })
853
+ output$correlation_plot <- renderPlot({ plot_correlation(cross_data()) })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
854
 
855
  output$violin_plot <- renderPlot({
856
  req(input$effect_qtl, input$effect_qtl != "")
 
861
  qtl_idx <- which(paste0("Chr", qtls$Chromosome, "_", qtls$Position_cM, "cM") == input$effect_qtl)
862
  if (length(qtl_idx) == 0) return(NULL)
863
 
864
+ plot_violin(cross, qtls[qtl_idx[1], , drop = FALSE], input$pheno_trait)
865
  })
866
 
867
  # Tables
 
887
  ))
888
  }
889
  }
 
890
  datatable(summary_df, options = list(pageLength = 10), rownames = FALSE)
891
  })
892
 
 
899
  thr <- summary(perms, alpha = a)[1]
900
  if (is.na(thr)) NA else round(thr, 3)
901
  })
902
+ datatable(data.frame(Alpha = alphas, Threshold = thresholds),
903
+ options = list(pageLength = 5, dom = 't'), rownames = FALSE)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
904
  })
905
 
906
  # Download
 
911
  if (!is.null(qtls) && nrow(qtls) > 0) {
912
  write.csv(qtls, file, row.names = FALSE)
913
  } else {
914
+ write.csv(data.frame(Message = "No QTLs found"), file, row.names = FALSE)
915
  }
916
  }
917
  )