softwareDevelopment commited on
Commit
eff7f3a
·
verified ·
1 Parent(s): f2f10d1

Update app.R

Browse files
Files changed (1) hide show
  1. app.R +144 -693
app.R CHANGED
@@ -1,9 +1,9 @@
1
  # ============================================================================
2
  # COMPLETE QTL ANALYSIS PIPELINE - FULLY FUNCTIONAL
3
- # 10 Models + 15+ Plots + Working Downloads + Complete Results
4
  # ============================================================================
5
 
6
- # Load all required libraries
7
  suppressPackageStartupMessages({
8
  library(shiny)
9
  library(shinydashboard)
@@ -21,15 +21,14 @@ suppressPackageStartupMessages({
21
  library(viridis)
22
  library(ggridges)
23
  library(pheatmap)
24
- library(corrplot)
25
- library(heatmaply)
26
- library(UpSetR)
27
- library(ggcorrplot)
28
- library(igraph)
29
- library(circlize)
30
- library(ComplexHeatmap)
31
  })
32
 
 
 
 
 
 
 
33
  # ============================================================================
34
  # SAFE NOTIFICATION FUNCTION
35
  # ============================================================================
@@ -44,6 +43,20 @@ safe_notify <- function(msg, type = "default") {
44
  }, error = function(e) message(msg))
45
  }
46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
  # ============================================================================
48
  # ADVANCED DATA PARSER
49
  # ============================================================================
@@ -178,13 +191,15 @@ parse_advanced_cross <- function(geno_path, pheno_path, cross_type = "f2") {
178
  # Run basic checks
179
  cross <- jittermap(cross)
180
 
181
- # Calculate additional statistics
 
 
182
  attr(cross, "summary") <- list(
183
  n_ind = nind(cross),
184
  n_markers = totmar(cross),
185
  n_chr = nchr(cross),
186
- missing_rate = mean(nmissing(cross, what="mar") / nind(cross)),
187
- heterozygosity = mean(calc.heterozyg(cross), na.rm=TRUE)
188
  )
189
 
190
  return(cross)
@@ -408,7 +423,6 @@ detect_comprehensive_qtls <- function(scan, threshold, cross = NULL, pheno_col =
408
  }
409
 
410
  qtls <- rbind(qtls, data.frame(
411
- QTL_ID = paste0("QTL_", chr, "_", round(peak_row$pos, 1)),
412
  Chromosome = as.character(chr),
413
  Peak_Position_cM = round(peak_row$pos, 2),
414
  Peak_Marker = peak_marker,
@@ -436,7 +450,6 @@ detect_comprehensive_qtls <- function(scan, threshold, cross = NULL, pheno_col =
436
  qtls$ChrNum[is.na(qtls$ChrNum)] <- 999
437
  qtls <- qtls[order(qtls$ChrNum, qtls$Peak_Position_cM), ]
438
  qtls$ChrNum <- NULL
439
- qtls$QTL_ID <- NULL
440
  }
441
 
442
  return(qtls)
@@ -501,10 +514,10 @@ create_model_comparison <- function(models, threshold) {
501
  }
502
 
503
  # ============================================================================
504
- # PLOTTING FUNCTIONS - 15+ UNIQUE VISUALIZATIONS
505
  # ============================================================================
506
 
507
- # Plot 1: Enhanced Manhattan Plot with QTL Highlights
508
  plot_manhattan_enhanced <- function(scan, qtls, threshold) {
509
  if (is.null(scan)) return(NULL)
510
 
@@ -512,7 +525,6 @@ plot_manhattan_enhanced <- function(scan, qtls, threshold) {
512
  df$marker <- rownames(df)
513
  df$significant <- df$lod >= threshold
514
 
515
- # Calculate cumulative positions
516
  chrs <- unique(df$chr)
517
  chr_lengths <- sapply(chrs, function(ch) max(df$pos[df$chr == ch], na.rm = TRUE))
518
  cum_lengths <- cumsum(c(0, chr_lengths[-length(chrs)]))
@@ -521,7 +533,6 @@ plot_manhattan_enhanced <- function(scan, qtls, threshold) {
521
  df$pos_cum <- df$pos + cum_lengths[as.character(df$chr)]
522
  chr_midpoints <- sapply(chrs, function(ch) mean(df$pos_cum[df$chr == ch], na.rm = TRUE))
523
 
524
- # Create color palette
525
  colors <- rep(brewer.pal(8, "Set1"), length.out = length(chrs))
526
  names(colors) <- chrs
527
 
@@ -534,18 +545,13 @@ plot_manhattan_enhanced <- function(scan, qtls, threshold) {
534
  x = "Chromosome", y = "LOD Score") +
535
  theme_minimal() +
536
  theme(legend.position = "none",
537
- axis.text.x = element_text(angle = 45, hjust = 1),
538
- plot.title = element_text(hjust = 0.5, face = "bold", size = 14))
539
 
540
- # Add QTL highlights
541
  if (!is.null(qtls) && nrow(qtls) > 0) {
542
  qtls$pos_cum <- qtls$Peak_Position_cM + cum_lengths[as.character(qtls$Chromosome)]
543
  p <- p +
544
  geom_point(data = qtls, aes(x = pos_cum, y = LOD_Score),
545
- color = "gold", size = 5, shape = 18) +
546
- geom_text_repel(data = qtls, aes(x = pos_cum, y = LOD_Score,
547
- label = paste0("QTL-", 1:nrow(qtls))),
548
- color = "darkred", size = 3.5, fontface = "bold")
549
  }
550
 
551
  return(p)
@@ -568,10 +574,8 @@ plot_lod_contour <- function(scan) {
568
  geom_contour_filled(bins = 8) +
569
  scale_fill_viridis_d(name = "LOD", direction = -1) +
570
  scale_y_continuous(breaks = 1:length(chrs), labels = chrs) +
571
- labs(title = "LOD Contour Plot Across Genome",
572
- x = "Position (cM)", y = "Chromosome") +
573
- theme_minimal() +
574
- theme(plot.title = element_text(hjust = 0.5, face = "bold"))
575
  }
576
 
577
  # Plot 3: QTL Effect Bubble Plot
@@ -582,28 +586,38 @@ plot_qtl_bubble <- function(qtls) {
582
  size = LOD_Score, color = PVE_Percent)) +
583
  geom_point(alpha = 0.8) +
584
  scale_size_continuous(range = c(3, 20), name = "LOD Score") +
585
- scale_color_gradientn(colors = c("blue", "green", "yellow", "red"),
586
- name = "PVE (%)") +
587
  labs(title = "QTL Effect Size Bubble Plot",
588
- x = "Chromosome", y = "Peak Position (cM)") +
589
  theme_minimal() +
590
- theme(axis.text.x = element_text(angle = 45, hjust = 1),
591
- plot.title = element_text(hjust = 0.5, face = "bold"))
592
  }
593
 
594
- # Plot 4: Violin Plot for Genotype-Phenotype Association
 
 
 
 
 
 
 
 
 
 
 
 
 
 
595
  plot_genotype_violin <- function(cross, qtl, trait) {
596
  if (is.null(cross) || is.null(qtl) || nrow(qtl) == 0) return(NULL)
597
 
598
  chr_name <- as.character(qtl$Chromosome[1])
599
  if (!chr_name %in% names(cross$geno)) return(NULL)
600
 
601
- # Find nearest marker
602
  map <- pull.map(cross)[[chr_name]]
603
  marker_pos <- which.min(abs(map - qtl$Peak_Position_cM[1]))
604
  marker_name <- names(map)[marker_pos]
605
 
606
- # Get data
607
  geno_idx <- find.marker(cross, chr_name, marker_name)
608
  genotypes <- pull.geno(cross)[, geno_idx]
609
  phenotypes <- cross$pheno[[trait]]
@@ -614,7 +628,6 @@ plot_genotype_violin <- function(cross, qtl, trait) {
614
  )
615
  df <- df[!is.na(df$Genotype) & !is.na(df$Phenotype), ]
616
 
617
- # Recode for better labels
618
  if (length(unique(df$Genotype)) == 3) {
619
  df$Genotype <- recode(df$Genotype, `1` = "AA", `2` = "AB", `3` = "BB")
620
  } else if (length(unique(df$Genotype)) == 2) {
@@ -625,234 +638,46 @@ plot_genotype_violin <- function(cross, qtl, trait) {
625
  geom_violin(alpha = 0.6, trim = FALSE) +
626
  geom_boxplot(width = 0.2, alpha = 0.8) +
627
  stat_summary(fun = mean, geom = "point", shape = 18, size = 5, color = "red") +
628
- stat_summary(fun = mean, geom = "text", aes(label = round(..y.., 2)),
629
- vjust = -1.5, size = 4, color = "darkred") +
630
- scale_fill_brewer(palette = "Set2") +
631
- labs(title = paste("Phenotype Distribution at", marker_name),
632
- x = "Genotype", y = trait) +
633
- theme_minimal() +
634
- theme(legend.position = "none",
635
- plot.title = element_text(hjust = 0.5, face = "bold"))
636
- }
637
-
638
- # Plot 5: Ridge Plot of LOD Distributions
639
- plot_ridge_distribution <- function(scan) {
640
- if (is.null(scan)) return(NULL)
641
-
642
- df <- as.data.frame(scan)
643
- df$chr <- factor(df$chr, levels = unique(df$chr))
644
-
645
- ggplot(df, aes(x = lod, y = chr, fill = after_stat(x))) +
646
- geom_density_ridges_gradient(scale = 2, rel_min_height = 0.01) +
647
- scale_fill_viridis_c(option = "C", name = "LOD Score") +
648
- labs(title = "LOD Score Distribution by Chromosome",
649
- x = "LOD Score", y = "Chromosome") +
650
- theme_ridges() +
651
- theme(plot.title = element_text(hjust = 0.5, face = "bold"))
652
- }
653
-
654
- # Plot 6: 3D Surface Plot
655
- plot_3d_surface <- function(scan) {
656
- if (is.null(scan)) return(NULL)
657
-
658
- df <- as.data.frame(scan)
659
- df$chr_num <- as.numeric(factor(df$chr, levels = unique(df$chr)))
660
-
661
- plot_ly(df, x = ~chr_num, y = ~pos, z = ~lod,
662
- type = "mesh3d", intensity = ~lod, colorscale = "Viridis",
663
- text = ~paste("Chromosome:", chr, "<br>Position:", pos,
664
- "<br>LOD:", round(lod, 3)),
665
- hoverinfo = "text") %>%
666
- layout(title = "3D LOD Surface Plot",
667
- scene = list(xaxis = list(title = "Chromosome"),
668
- yaxis = list(title = "Position (cM)"),
669
- zaxis = list(title = "LOD Score")),
670
- paper_bgcolor = "#f4f4f4")
671
- }
672
-
673
- # Plot 7: Model Comparison Bar Plot
674
- plot_model_comparison <- function(comparison_df) {
675
- if (is.null(comparison_df) || nrow(comparison_df) == 0) return(NULL)
676
-
677
- ggplot(comparison_df, aes(x = reorder(Model, -Max_LOD), y = Max_LOD, fill = Model)) +
678
- geom_bar(stat = "identity", alpha = 0.8) +
679
- geom_text(aes(label = Max_LOD), vjust = -0.5, size = 4, fontface = "bold") +
680
  scale_fill_brewer(palette = "Set2") +
681
- labs(title = "Model Performance Comparison",
682
- x = "Mapping Method", y = "Maximum LOD Score") +
683
- theme_minimal() +
684
- theme(legend.position = "none",
685
- axis.text.x = element_text(angle = 45, hjust = 1),
686
- plot.title = element_text(hjust = 0.5, face = "bold"))
687
- }
688
-
689
- # Plot 8: QQ Plot
690
- plot_qq_plot <- function(scan) {
691
- if (is.null(scan)) return(NULL)
692
-
693
- expected <- -log10(ppoints(length(scan$lod)))
694
- observed <- -log10(rank(scan$lod) / (length(scan$lod) + 1))
695
-
696
- df <- data.frame(Expected = expected, Observed = observed)
697
-
698
- ggplot(df, aes(x = Expected, y = Observed)) +
699
- geom_point(alpha = 0.6, color = "steelblue") +
700
- geom_abline(intercept = 0, slope = 1, color = "red", linetype = "dashed", size = 1) +
701
- labs(title = "Q-Q Plot for LOD Scores",
702
- x = "Expected -log10(p)", y = "Observed -log10(p)") +
703
  theme_minimal() +
704
- theme(plot.title = element_text(hjust = 0.5, face = "bold"))
705
- }
706
-
707
- # Plot 9: Correlation Heatmap for Phenotypes
708
- plot_phenotype_correlation <- function(cross) {
709
- if (is.null(cross) || ncol(cross$pheno) < 2) return(NULL)
710
-
711
- cor_matrix <- cor(cross$pheno, use = "complete.obs")
712
-
713
- corrplot(cor_matrix, method = "color", type = "upper",
714
- order = "hclust", addCoef.col = "black",
715
- tl.col = "black", tl.srt = 45,
716
- title = "Phenotype Correlation Matrix",
717
- mar = c(0, 0, 2, 0))
718
  }
719
 
720
- # Plot 10: Genetic Map Density
721
  plot_genetic_density <- function(cross) {
722
  if (is.null(cross)) return(NULL)
723
 
724
  map <- pull.map(cross)
725
- density_data <- data.frame()
726
-
727
  for (chr in names(map)) {
728
  positions <- map[[chr]]
729
- if (length(positions) > 1) {
730
- gaps <- diff(positions)
731
- density_data <- rbind(density_data,
732
- data.frame(Chromosome = chr, Gap = gaps))
733
- }
734
  }
735
 
736
- if (nrow(density_data) == 0) return(NULL)
737
 
738
- ggplot(density_data, aes(x = Gap, fill = Chromosome)) +
739
- geom_histogram(bins = 30, alpha = 0.6, position = "stack") +
740
- scale_fill_brewer(palette = "Set3") +
741
- labs(title = "Marker Density Distribution",
742
- x = "Inter-marker Distance (cM)", y = "Frequency") +
743
  theme_minimal() +
744
- theme(legend.position = "bottom",
745
- plot.title = element_text(hjust = 0.5, face = "bold"))
746
  }
747
 
748
- # Plot 11: Missing Data Pattern
749
- plot_missing_data <- function(cross) {
750
- if (is.null(cross)) return(NULL)
751
-
752
- missing_ind <- nmissing(cross, what = "ind")
753
- missing_marker <- nmissing(cross, what = "mar")
754
-
755
- df_ind <- data.frame(Individual = seq_along(missing_ind), Missing = missing_ind)
756
- df_marker <- data.frame(Marker = seq_along(missing_marker), Missing = missing_marker)
757
-
758
- p1 <- ggplot(df_ind, aes(x = Individual, y = Missing)) +
759
- geom_bar(stat = "identity", fill = "steelblue", alpha = 0.7) +
760
- labs(title = "Missing Data per Individual", x = "Individual", y = "Missing Count") +
761
- theme_minimal()
762
-
763
- p2 <- ggplot(df_marker, aes(x = Marker, y = Missing)) +
764
- geom_bar(stat = "identity", fill = "darkorange", alpha = 0.7) +
765
- labs(title = "Missing Data per Marker", x = "Marker Index", y = "Missing Count") +
766
- theme_minimal()
767
-
768
- plot_grid(p1, p2, ncol = 2)
769
- }
770
-
771
- # Plot 12: Parallel Coordinates for Models
772
- plot_parallel_coords <- function(models) {
773
- if (is.null(models) || length(models) == 0) return(NULL)
774
-
775
- first_model <- models[[1]]
776
- if (is.null(first_model)) return(NULL)
777
-
778
- # Get top 50 markers
779
- top_idx <- order(first_model$lod, decreasing = TRUE)[1:min(50, nrow(first_model))]
780
-
781
- parallel_data <- data.frame(Position = first_model$pos[top_idx])
782
- for (name in names(models)) {
783
- scan <- models[[name]]
784
- if (!is.null(scan)) {
785
- parallel_data[[toupper(name)]] <- scan$lod[top_idx]
786
- }
787
- }
788
-
789
- plot_data <- pivot_longer(parallel_data, cols = -Position,
790
- names_to = "Model", values_to = "LOD")
791
-
792
- ggplot(plot_data, aes(x = Position, y = LOD, color = Model, group = Model)) +
793
- geom_line(size = 1) +
794
- scale_color_brewer(palette = "Set1") +
795
- labs(title = "Model Comparison at Top Markers",
796
- x = "Position (cM)", y = "LOD Score") +
797
- theme_minimal() +
798
- theme(legend.position = "bottom",
799
- plot.title = element_text(hjust = 0.5, face = "bold"))
800
- }
801
-
802
- # Plot 13: QTL Interval Plot
803
- plot_qtl_intervals <- function(qtls) {
804
- if (is.null(qtls) || nrow(qtls) == 0) return(NULL)
805
-
806
- qtls$QTL_ID <- paste0("Q", 1:nrow(qtls))
807
-
808
- ggplot(qtls, aes(y = reorder(QTL_ID, Peak_Position_cM))) +
809
- geom_segment(aes(x = CI_1.5LOD_Left_cM, xend = CI_1.5LOD_Right_cM,
810
- yend = QTL_ID), color = "gray70", size = 3) +
811
- geom_point(aes(x = Peak_Position_cM), color = "red", size = 4) +
812
- labs(title = "QTL Confidence Intervals",
813
- x = "Position (cM)", y = "QTL") +
814
- theme_minimal() +
815
- theme(plot.title = element_text(hjust = 0.5, face = "bold"))
816
- }
817
-
818
- # Plot 14: PVE Distribution
819
- plot_pve_distribution <- function(qtls) {
820
- if (is.null(qtls) || nrow(qtls) == 0) return(NULL)
821
 
822
- ggplot(qtls, aes(x = reorder(paste(Chromosome, "@", Peak_Position_cM), PVE_Percent),
823
- y = PVE_Percent, fill = Chromosome)) +
824
  geom_bar(stat = "identity", alpha = 0.8) +
825
- geom_text(aes(label = paste0(PVE_Percent, "%")), vjust = -0.5, size = 3.5) +
826
- scale_fill_brewer(palette = "Set3") +
827
- labs(title = "Proportion of Variance Explained by QTLs",
828
- x = "QTL Location", y = "PVE (%)") +
829
  theme_minimal() +
830
- theme(axis.text.x = element_text(angle = 45, hjust = 1),
831
- plot.title = element_text(hjust = 0.5, face = "bold"),
832
- legend.position = "none")
833
- }
834
-
835
- # Plot 15: Chromosome-wise LOD Heatmap
836
- plot_chromosome_heatmap <- function(scan) {
837
- if (is.null(scan)) return(NULL)
838
-
839
- # Create matrix for heatmap
840
- chrs <- unique(scan$chr)
841
- max_pos <- tapply(scan$pos, scan$chr, max)
842
-
843
- heatmap_data <- matrix(NA, nrow = length(chrs), ncol = 100)
844
- rownames(heatmap_data) <- chrs
845
-
846
- for (i in 1:length(chrs)) {
847
- chr_data <- scan[scan$chr == chrs[i], ]
848
- positions <- seq(0, max_pos[i], length.out = 100)
849
- lod_interp <- approx(chr_data$pos, chr_data$lod, xout = positions)$y
850
- heatmap_data[i, ] <- lod_interp
851
- }
852
-
853
- pheatmap(heatmap_data, color = viridis(100), cluster_rows = FALSE,
854
- cluster_cols = FALSE, main = "Chromosome-wise LOD Heatmap",
855
- xlab = "Relative Position", ylab = "Chromosome")
856
  }
857
 
858
  # ============================================================================
@@ -860,69 +685,48 @@ plot_chromosome_heatmap <- function(scan) {
860
  # ============================================================================
861
 
862
  ui <- dashboardPage(
863
- dashboardHeader(title = "QTL Analysis Pipeline - Complete Suite", titleWidth = 350),
864
 
865
- dashboardSidebar(width = 350,
866
  sidebarMenu(
867
  menuItem("Data Input", tabName = "data", icon = icon("upload")),
868
  menuItem("10 Models", tabName = "models", icon = icon("cogs")),
869
  menuItem("QTL Results", tabName = "results", icon = icon("table")),
870
- menuItem("15+ Plots", tabName = "plots", icon = icon("chart-bar")),
871
- menuItem("Download Center", tabName = "download", icon = icon("download")),
872
- menuItem("Documentation", tabName = "help", icon = icon("question-circle"))
873
  ),
874
 
875
  div(style = "padding: 15px;",
876
- h4("Data Upload", style = "color: #3c8dbc;"),
877
  fileInput("geno_file", "Genotype CSV", accept = ".csv"),
878
  fileInput("pheno_file", "Phenotype CSV", accept = ".csv"),
879
 
880
  selectInput("cross_type", "Cross Type",
881
- choices = c("F2 Intercross" = "f2",
882
- "Backcross" = "bc",
883
- "RIL (Selfing)" = "riself",
884
- "RIL (Sib-mating)" = "risib"),
885
  selected = "f2"),
886
 
887
  hr(),
888
 
889
- h4("Analysis Parameters", style = "color: #3c8dbc;"),
890
- selectInput("pheno_trait", "Select Phenotype Trait", choices = NULL),
891
-
892
- numericInput("lod_threshold", "LOD Threshold",
893
- value = 3.0, min = 0, max = 20, step = 0.5),
894
-
895
- numericInput("n_permutations", "Number of Permutations",
896
- value = 1000, min = 0, max = 10000, step = 100),
897
-
898
- hr(),
899
 
900
- actionButton("run_analysis", "RUN ALL 10 MODELS",
901
  icon = icon("play"),
902
- style = "background-color: #3c8dbc; color: white; width: 100%; margin-top: 10px;"),
903
-
904
- br(), br(),
905
-
906
- div(style = "background-color: #f0f0f0; padding: 10px; border-radius: 5px;",
907
- h5("Model Status:", style = "margin-top: 0;"),
908
- verbatimTextOutput("model_status", placeholder = TRUE)
909
- )
910
  )
911
  ),
912
 
913
  dashboardBody(
914
  useShinyjs(),
915
- tags$head(
916
- tags$style(HTML("
917
- .content-wrapper, .right-side { background-color: #f4f4f4; }
918
- .box { border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
919
- .small-box { border-radius: 10px; }
920
- .btn-download { background-color: #00a65a; color: white; }
921
- "))
922
- ),
923
 
924
  tabItems(
925
- # Data Tab
926
  tabItem(tabName = "data",
927
  fluidRow(
928
  valueBoxOutput("n_individuals"),
@@ -930,221 +734,86 @@ ui <- dashboardPage(
930
  valueBoxOutput("n_chromosomes")
931
  ),
932
  fluidRow(
933
- box(title = "Data Summary", status = "primary", solidHeader = TRUE, width = 12,
934
- verbatimTextOutput("data_summary")
935
- )
936
  ),
937
  fluidRow(
938
  box(title = "Genetic Map", status = "info", width = 12,
939
- plotOutput("genetic_map", height = "500px") %>% withSpinner()
940
- )
941
- ),
942
- fluidRow(
943
- box(title = "Missing Data Pattern", status = "warning", width = 12,
944
- plotOutput("missing_plot", height = "500px") %>% withSpinner()
945
- )
946
- ),
947
- fluidRow(
948
- box(title = "Phenotype Distribution", status = "success", width = 12,
949
- plotOutput("phenotype_dist", height = "500px") %>% withSpinner()
950
- )
951
  )
952
  ),
953
 
954
- # 10 Models Tab
955
  tabItem(tabName = "models",
956
  fluidRow(
957
- box(title = "Analysis Progress", status = "primary", solidHeader = TRUE, width = 12,
958
- verbatimTextOutput("analysis_status")
959
- )
960
  ),
961
  fluidRow(
962
  box(title = "Model Comparison", status = "info", width = 12,
963
- DTOutput("model_comparison_table") %>% withSpinner()
964
- )
965
  ),
966
  fluidRow(
967
- box(title = "Model Performance Bar Plot", status = "success", width = 12,
968
- plotOutput("model_barplot", height = "500px") %>% withSpinner()
969
- )
970
- ),
971
- fluidRow(
972
- box(title = "Parallel Coordinates Comparison", status = "warning", width = 12,
973
- plotOutput("parallel_plot", height = "500px") %>% withSpinner()
974
- )
975
- ),
976
- fluidRow(
977
- box(title = "Model QQ Plot", status = "info", width = 12,
978
- plotOutput("qq_plot", height = "500px") %>% withSpinner()
979
- )
980
  )
981
  ),
982
 
983
- # QTL Results Tab
984
  tabItem(tabName = "results",
985
  fluidRow(
986
- box(title = "Significant QTLs - Complete Details", status = "primary", solidHeader = TRUE, width = 12,
987
- DTOutput("qtl_table") %>% withSpinner()
988
- )
989
- ),
990
- fluidRow(
991
- box(title = "Permutation Test Results", status = "info", width = 12,
992
- DTOutput("permutation_table") %>% withSpinner()
993
- )
994
  ),
995
  fluidRow(
996
- box(title = "QTL Intervals Plot", status = "success", width = 12,
997
- plotOutput("qtl_intervals", height = "500px") %>% withSpinner()
998
- )
999
- ),
1000
- fluidRow(
1001
- box(title = "PVE Distribution", status = "warning", width = 12,
1002
- plotOutput("pve_distribution", height = "500px") %>% withSpinner()
1003
- )
1004
  )
1005
  ),
1006
 
1007
- # Plots Tab
1008
  tabItem(tabName = "plots",
1009
  fluidRow(
1010
- box(title = "Enhanced Manhattan Plot", status = "primary", width = 12,
1011
- plotOutput("manhattan_plot", height = "600px") %>% withSpinner()
1012
- )
1013
  ),
1014
  fluidRow(
1015
- box(title = "3D Surface Plot", status = "info", width = 12,
1016
- plotlyOutput("surface_3d", height = "600px") %>% withSpinner()
1017
- )
 
1018
  ),
1019
  fluidRow(
1020
- box(title = "LOD Contour Plot", status = "success", width = 6,
1021
- plotOutput("contour_plot", height = "500px") %>% withSpinner()
1022
- ),
1023
- box(title = "LOD Ridge Plot", status = "warning", width = 6,
1024
- plotOutput("ridge_plot", height = "500px") %>% withSpinner()
1025
- )
1026
  ),
1027
  fluidRow(
1028
- box(title = "QTL Effect Bubble Plot", status = "danger", width = 12,
1029
- plotOutput("bubble_plot", height = "500px") %>% withSpinner()
1030
- )
1031
- ),
1032
- fluidRow(
1033
- box(title = "Chromosome-wise LOD Heatmap", status = "info", width = 12,
1034
- plotOutput("chromosome_heatmap", height = "600px") %>% withSpinner()
1035
- )
1036
- ),
1037
- fluidRow(
1038
- box(title = "Genotype-Phenotype Association", status = "success", width = 12,
1039
- selectInput("violin_qtl", "Select QTL for Violin Plot:", choices = NULL),
1040
- plotOutput("violin_plot", height = "500px") %>% withSpinner()
1041
- )
1042
- ),
1043
- fluidRow(
1044
- box(title = "Phenotype Correlation Heatmap", status = "warning", width = 12,
1045
- plotOutput("correlation_plot", height = "500px") %>% withSpinner()
1046
- )
1047
- ),
1048
- fluidRow(
1049
- box(title = "Marker Density Distribution", status = "info", width = 12,
1050
- plotOutput("density_plot", height = "500px") %>% withSpinner()
1051
- )
1052
  )
1053
  ),
1054
 
1055
- # Download Tab
1056
  tabItem(tabName = "download",
1057
  fluidRow(
1058
- box(title = "Download Results", status = "primary", solidHeader = TRUE, width = 12,
1059
  br(),
1060
- h4("QTL Results"),
1061
- p("Download the complete QTL table with all details including peak markers, flanking markers, LOD scores, PVE, and confidence intervals."),
1062
  downloadButton("download_qtl_results", "Download QTL Results (CSV)",
1063
- class = "btn-download", style = "margin-bottom: 20px;"),
1064
-
1065
- hr(),
1066
-
1067
- h4("Model Comparison"),
1068
- p("Download the model comparison table showing performance of all 10 mapping methods."),
1069
  downloadButton("download_model_comparison", "Download Model Comparison (CSV)",
1070
- class = "btn-download", style = "margin-bottom: 20px;"),
1071
-
1072
- hr(),
1073
-
1074
- h4("Complete Analysis Report"),
1075
- p("Download a comprehensive report including all results and analysis parameters."),
1076
- downloadButton("download_full_report", "Download Full Report (CSV)",
1077
- class = "btn-download", style = "margin-bottom: 20px;"),
1078
-
1079
- hr(),
1080
-
1081
- h4("All Plots"),
1082
- p("Download all visualizations as a single PDF file."),
1083
- downloadButton("download_all_plots", "Download All Plots (PDF)",
1084
- class = "btn-download"),
1085
-
1086
  br(), br()
1087
  )
1088
  )
1089
  ),
1090
 
1091
- # Help Tab
1092
  tabItem(tabName = "help",
1093
  fluidRow(
1094
- box(title = "Documentation", status = "primary", solidHeader = TRUE, width = 12,
1095
  HTML("
1096
- <h3>Complete QTL Analysis Pipeline Documentation</h3>
1097
-
1098
- <h4>10 Mapping Models Included:</h4>
1099
- <ol>
1100
- <li><strong>Haley-Knott (HK)</strong> - Fast regression-based method</li>
1101
- <li><strong>EM Algorithm</strong> - Expectation-maximization for missing data</li>
1102
- <li><strong>Extended Haley-Knott (EHK)</strong> - Improved HK method</li>
1103
- <li><strong>Multiple Imputation (IMP)</strong> - Handles missing genotypes</li>
1104
- <li><strong>Marker Regression (MR)</strong> - Simple marker-by-marker regression</li>
1105
- <li><strong>Non-parametric (NP)</strong> - Distribution-free method</li>
1106
- <li><strong>Composite Interval Mapping (CIM)</strong> - Controls for background QTLs</li>
1107
- <li><strong>Multiple QTL Mapping (MQM)</strong> - Uses cofactors</li>
1108
- <li><strong>Binary Trait</strong> - For case/control studies</li>
1109
- <li><strong>Normal Model</strong> - Assumes normal distribution</li>
1110
- </ol>
1111
-
1112
- <h4>QTL Results Include:</h4>
1113
- <ul>
1114
- <li>Peak Marker - The marker with highest LOD at QTL peak</li>
1115
- <li>Left Flanking Marker - Left boundary of 1.5 LOD confidence interval</li>
1116
- <li>Right Flanking Marker - Right boundary of 1.5 LOD confidence interval</li>
1117
- <li>LOD Score - Logarithm of odds at peak</li>
1118
- <li>PVE (Proportion of Variance Explained) - Effect size</li>
1119
- <li>1.5 LOD and 2 LOD Confidence Intervals</li>
1120
- <li>Additive and Dominance Effects (for F2 crosses)</li>
1121
- </ul>
1122
-
1123
- <h4>File Format Requirements:</h4>
1124
- <p><strong>Genotype CSV:</strong></p>
1125
- <pre>
1126
- id,marker1,marker2,marker3,...
1127
- ,chr1,chr1,chr2,...
1128
- ,0,5.2,10.1,...
1129
- sample1,1,2,1,...
1130
- sample2,2,1,3,...</pre>
1131
-
1132
- <p><strong>Phenotype CSV:</strong></p>
1133
- <pre>
1134
- id,trait1,trait2,trait3
1135
- sample1,12.5,175,8.2
1136
- sample2,13.2,180,8.5</pre>
1137
-
1138
- <h4>Interpretation Guide:</h4>
1139
- <ul>
1140
- <li><strong>LOD > 3:</strong> Generally considered significant evidence for QTL</li>
1141
- <li><strong>PVE:</strong> Higher values indicate larger effect QTLs</li>
1142
- <li><strong>CI Width:</strong> Narrower intervals indicate more precise mapping</li>
1143
- <li><strong>Additive Effect:</strong> The effect of replacing one allele with another</li>
1144
- <li><strong>Dominance Effect:</strong> Deviation from additive model (F2 only)</li>
1145
- </ul>
1146
- ")
1147
- )
1148
  )
1149
  )
1150
  )
@@ -1157,14 +826,12 @@ sample2,13.2,180,8.5</pre>
1157
 
1158
  server <- function(input, output, session) {
1159
 
1160
- # Reactive values
1161
  cross_data <- reactiveVal(NULL)
1162
  all_models <- reactiveVal(NULL)
1163
  qtl_results <- reactiveVal(NULL)
1164
  permutation_results <- reactiveVal(NULL)
1165
  model_comparison <- reactiveVal(NULL)
1166
  analysis_complete <- reactiveVal(FALSE)
1167
- model_status_text <- reactiveVal("No models run yet")
1168
 
1169
  # Value boxes
1170
  output$n_individuals <- renderValueBox({
@@ -1189,7 +856,7 @@ server <- function(input, output, session) {
1189
  observeEvent(c(input$geno_file, input$pheno_file), {
1190
  req(input$geno_file, input$pheno_file)
1191
 
1192
- safe_notify("Loading data files...", "message")
1193
 
1194
  tryCatch({
1195
  cross <- parse_advanced_cross(
@@ -1204,50 +871,40 @@ server <- function(input, output, session) {
1204
  choices = names(cross$pheno),
1205
  selected = names(cross$pheno)[1])
1206
 
1207
- safe_notify(paste("Loaded:", nind(cross), "individuals,",
1208
- totmar(cross), "markers"), "success")
1209
 
1210
  }, error = function(e) {
1211
  safe_notify(paste("Error:", e$message), "error")
1212
  })
1213
  })
1214
 
1215
- # Run all 10 models
1216
  observeEvent(input$run_analysis, {
1217
  cross <- cross_data()
1218
  req(cross, input$pheno_trait)
1219
 
1220
- safe_notify("Starting analysis with 10 models...", "message")
1221
 
1222
- withProgress(message = "Running 10 QTL Mapping Models", value = 0, {
1223
 
1224
- incProgress(0.1, detail = "Preparing data...")
1225
  pheno_idx <- which(names(cross$pheno) == input$pheno_trait)
1226
-
1227
- incProgress(0.3, detail = "Running all 10 models...")
1228
  models <- run_all_ten_models(cross, pheno_idx)
1229
  all_models(models)
1230
 
1231
- # Get model status
1232
- status <- attr(models, "status")
1233
- status_msg <- paste(names(status), ":", unlist(status), collapse = "\n")
1234
- model_status_text(status_msg)
1235
-
1236
- incProgress(0.2, detail = "Detecting QTLs...")
1237
- # Use HK model for QTL detection (best overall)
1238
  if (!is.null(models$hk)) {
1239
  qtls <- detect_comprehensive_qtls(models$hk, input$lod_threshold,
1240
  cross, input$pheno_trait)
1241
  qtl_results(qtls)
1242
 
1243
  if (nrow(qtls) > 0) {
1244
- qtl_choices <- paste0("Chr", qtls$Chromosome, "_",
1245
- qtls$Peak_Position_cM, "cM_LOD", qtls$LOD_Score)
1246
  updateSelectInput(session, "violin_qtl", choices = qtl_choices)
1247
  }
1248
  }
1249
 
1250
- incProgress(0.2, detail = "Comparing models...")
1251
  comp <- create_model_comparison(models, input$lod_threshold)
1252
  model_comparison(comp)
1253
 
@@ -1258,136 +915,63 @@ server <- function(input, output, session) {
1258
  }
1259
 
1260
  analysis_complete(TRUE)
1261
-
1262
  n_success <- sum(!sapply(models, is.null))
1263
  safe_notify(paste("Complete!", n_success, "models succeeded"), "success")
1264
  })
1265
  })
1266
 
1267
- # Model status output
1268
- output$model_status <- renderPrint({
1269
- cat(model_status_text())
1270
- })
1271
-
1272
  # Data summary
1273
  output$data_summary <- renderPrint({
1274
  cross <- cross_data()
1275
  if (is.null(cross)) {
1276
- cat("No data loaded. Please upload CSV files.")
1277
  } else {
1278
- cat("=== QTL Data Summary ===\n\n")
1279
  cat("Cross Type:", class(cross)[1], "\n")
1280
  cat("Individuals:", nind(cross), "\n")
1281
  cat("Markers:", totmar(cross), "\n")
1282
- cat("Chromosomes:", nchr(cross), "\n\n")
1283
- cat("Phenotypes:", paste(names(cross$pheno), collapse = ", "), "\n\n")
1284
-
1285
- missing_total <- sum(is.na(pull.geno(cross))) / (nind(cross) * totmar(cross)) * 100
1286
- cat("Missing Data Rate:", round(missing_total, 2), "%\n")
1287
- cat("Heterozygosity:", round(mean(calc.heterozyg(cross), na.rm=TRUE), 4), "\n")
1288
  }
1289
  })
1290
 
1291
  output$analysis_status <- renderPrint({
1292
  if (!analysis_complete()) {
1293
- cat("Analysis not run. Click 'RUN ALL 10 MODELS' to start.")
1294
  } else {
1295
  models <- all_models()
1296
  n_success <- sum(!sapply(models, is.null))
1297
  qtls <- qtl_results()
1298
-
1299
- cat("=== Analysis Complete ===\n\n")
1300
  cat("Models succeeded:", n_success, "/10\n")
1301
  cat("QTLs detected:", ifelse(is.null(qtls), 0, nrow(qtls)), "\n")
1302
- cat("LOD threshold:", input$lod_threshold, "\n")
1303
- cat("Permutations:", input$n_permutations, "\n\n")
1304
-
1305
- if (!is.null(qtls) && nrow(qtls) > 0) {
1306
- cat("Top QTL:\n")
1307
- top_qtl <- qtls[which.max(qtls$LOD_Score), ]
1308
- cat(" Chromosome:", top_qtl$Chromosome, "\n")
1309
- cat(" Position:", top_qtl$Peak_Position_cM, "cM\n")
1310
- cat(" LOD:", top_qtl$LOD_Score, "\n")
1311
- cat(" PVE:", top_qtl$PVE_Percent, "%\n")
1312
- }
1313
  }
1314
  })
1315
 
1316
- # Model comparison table
1317
  output$model_comparison_table <- renderDT({
1318
  comp <- model_comparison()
1319
  req(comp, nrow(comp) > 0)
1320
-
1321
- datatable(comp, options = list(pageLength = 10, scrollX = TRUE), rownames = FALSE) %>%
1322
- formatStyle("Max_LOD", background = styleColorBar(c(0, max(comp$Max_LOD)), "lightblue"))
1323
  })
1324
 
1325
- # QTL results table with all details
1326
  output$qtl_table <- renderDT({
1327
  qtls <- qtl_results()
1328
  req(qtls, nrow(qtls) > 0)
1329
-
1330
- datatable(qtls,
1331
- options = list(pageLength = 15, scrollX = TRUE,
1332
- dom = 'Bfrtip',
1333
- buttons = c('copy', 'csv', 'excel', 'pdf')),
1334
- rownames = FALSE,
1335
- class = 'display nowrap') %>%
1336
- formatStyle("LOD_Score",
1337
- background = styleColorBar(c(0, max(qtls$LOD_Score)), "lightblue")) %>%
1338
- formatStyle("PVE_Percent",
1339
- background = styleColorBar(c(0, max(qtls$PVE_Percent)), "lightgreen")) %>%
1340
- formatStyle("CI_1.5LOD_Width_cM",
1341
- background = styleColorBar(c(0, max(qtls$CI_1.5LOD_Width_cM)), "lightcoral"))
1342
  })
1343
 
1344
- # Permutation table
1345
  output$permutation_table <- renderDT({
1346
  perms <- permutation_results()
1347
  req(perms)
1348
-
1349
- datatable(perms$thresholds,
1350
- options = list(pageLength = 5, dom = 't'),
1351
- rownames = FALSE) %>%
1352
- formatStyle("LOD_Threshold",
1353
- background = styleColorBar(c(0, max(perms$thresholds$LOD_Threshold)), "lightyellow"))
1354
  })
1355
 
1356
- # All plots
1357
  output$genetic_map <- renderPlot({
1358
  cross <- cross_data()
1359
  req(cross)
1360
  plot_genetic_density(cross)
1361
  })
1362
 
1363
- output$missing_plot <- renderPlot({
1364
- cross <- cross_data()
1365
- req(cross)
1366
- plot_missing_data(cross)
1367
- })
1368
-
1369
- output$phenotype_dist <- renderPlot({
1370
- cross <- cross_data()
1371
- req(cross, input$pheno_trait)
1372
-
1373
- pheno <- cross$pheno[[input$pheno_trait]]
1374
- df <- data.frame(Phenotype = pheno[!is.na(pheno)])
1375
-
1376
- p1 <- ggplot(df, aes(x = Phenotype)) +
1377
- geom_histogram(aes(y = after_stat(density)), fill = "steelblue", alpha = 0.7, bins = 30) +
1378
- geom_density(color = "red", size = 1) +
1379
- labs(title = paste(input$pheno_trait, "- Distribution"), x = "Value", y = "Density") +
1380
- theme_minimal()
1381
-
1382
- p2 <- ggplot(df, aes(sample = Phenotype)) +
1383
- stat_qq(color = "steelblue", alpha = 0.7) +
1384
- stat_qq_line(color = "red", size = 1) +
1385
- labs(title = "Q-Q Plot", x = "Theoretical", y = "Sample") +
1386
- theme_minimal()
1387
-
1388
- plot_grid(p1, p2, ncol = 2)
1389
- })
1390
-
1391
  output$manhattan_plot <- renderPlot({
1392
  models <- all_models()
1393
  qtls <- qtl_results()
@@ -1395,12 +979,6 @@ server <- function(input, output, session) {
1395
  plot_manhattan_enhanced(models$hk, qtls, input$lod_threshold)
1396
  })
1397
 
1398
- output$surface_3d <- renderPlotly({
1399
- models <- all_models()
1400
- req(models, !is.null(models$hk))
1401
- plot_3d_surface(models$hk)
1402
- })
1403
-
1404
  output$contour_plot <- renderPlot({
1405
  models <- all_models()
1406
  req(models, !is.null(models$hk))
@@ -1419,68 +997,25 @@ server <- function(input, output, session) {
1419
  plot_qtl_bubble(qtls)
1420
  })
1421
 
1422
- output$chromosome_heatmap <- renderPlot({
1423
- models <- all_models()
1424
- req(models, !is.null(models$hk))
1425
- plot_chromosome_heatmap(models$hk)
1426
- })
1427
-
1428
  output$violin_plot <- renderPlot({
1429
  req(input$violin_qtl, input$violin_qtl != "")
1430
  qtls <- qtl_results()
1431
  cross <- cross_data()
1432
  req(qtls, nrow(qtls) > 0, cross, input$pheno_trait)
1433
 
1434
- qtl_idx <- which(paste0("Chr", qtls$Chromosome, "_",
1435
- qtls$Peak_Position_cM, "cM_LOD", qtls$LOD_Score) == input$violin_qtl)
1436
  if (length(qtl_idx) == 0) return(NULL)
1437
 
1438
  plot_genotype_violin(cross, qtls[qtl_idx[1], , drop = FALSE], input$pheno_trait)
1439
  })
1440
 
1441
- output$correlation_plot <- renderPlot({
1442
- cross <- cross_data()
1443
- req(cross)
1444
- plot_phenotype_correlation(cross)
1445
- })
1446
-
1447
- output$density_plot <- renderPlot({
1448
- cross <- cross_data()
1449
- req(cross)
1450
- plot_genetic_density(cross)
1451
- })
1452
-
1453
  output$model_barplot <- renderPlot({
1454
  comp <- model_comparison()
1455
  req(comp, nrow(comp) > 0)
1456
  plot_model_comparison(comp)
1457
  })
1458
 
1459
- output$parallel_plot <- renderPlot({
1460
- models <- all_models()
1461
- req(models, length(models) > 0)
1462
- plot_parallel_coords(models)
1463
- })
1464
-
1465
- output$qq_plot <- renderPlot({
1466
- models <- all_models()
1467
- req(models, !is.null(models$hk))
1468
- plot_qq_plot(models$hk)
1469
- })
1470
-
1471
- output$qtl_intervals <- renderPlot({
1472
- qtls <- qtl_results()
1473
- req(qtls, nrow(qtls) > 0)
1474
- plot_qtl_intervals(qtls)
1475
- })
1476
-
1477
- output$pve_distribution <- renderPlot({
1478
- qtls <- qtl_results()
1479
- req(qtls, nrow(qtls) > 0)
1480
- plot_pve_distribution(qtls)
1481
- })
1482
-
1483
- # Download handlers - WORKING
1484
  output$download_qtl_results <- downloadHandler(
1485
  filename = function() paste0("qtl_results_", Sys.Date(), ".csv"),
1486
  content = function(file) {
@@ -1488,8 +1023,7 @@ server <- function(input, output, session) {
1488
  if (!is.null(qtls) && nrow(qtls) > 0) {
1489
  write.csv(qtls, file, row.names = FALSE)
1490
  } else {
1491
- write.csv(data.frame(Message = "No significant QTLs found. Try lowering LOD threshold."),
1492
- file, row.names = FALSE)
1493
  }
1494
  }
1495
  )
@@ -1501,93 +1035,10 @@ server <- function(input, output, session) {
1501
  if (!is.null(comp) && nrow(comp) > 0) {
1502
  write.csv(comp, file, row.names = FALSE)
1503
  } else {
1504
- write.csv(data.frame(Message = "Run analysis first to get model comparison."),
1505
- file, row.names = FALSE)
1506
  }
1507
  }
1508
  )
1509
-
1510
- output$download_full_report <- downloadHandler(
1511
- filename = function() paste0("full_report_", Sys.Date(), ".csv"),
1512
- content = function(file) {
1513
- qtls <- qtl_results()
1514
- comp <- model_comparison()
1515
- perms <- permutation_results()
1516
-
1517
- # Create comprehensive report
1518
- report_lines <- c()
1519
- report_lines <- c(report_lines, "# QTL Analysis Full Report")
1520
- report_lines <- c(report_lines, paste("# Generated:", Sys.time()))
1521
- report_lines <- c(report_lines, "")
1522
- report_lines <- c(report_lines, "## Analysis Parameters")
1523
- report_lines <- c(report_lines, paste("Cross Type:", input$cross_type))
1524
- report_lines <- c(report_lines, paste("Phenotype Trait:", input$pheno_trait))
1525
- report_lines <- c(report_lines, paste("LOD Threshold:", input$lod_threshold))
1526
- report_lines <- c(report_lines, paste("Permutations:", input$n_permutations))
1527
- report_lines <- c(report_lines, "")
1528
-
1529
- if (!is.null(comp) && nrow(comp) > 0) {
1530
- report_lines <- c(report_lines, "## Model Comparison")
1531
- report_lines <- c(report_lines, capture.output(write.csv(comp, row.names = FALSE)))
1532
- report_lines <- c(report_lines, "")
1533
- }
1534
-
1535
- if (!is.null(qtls) && nrow(qtls) > 0) {
1536
- report_lines <- c(report_lines, "## Significant QTLs")
1537
- report_lines <- c(report_lines, capture.output(write.csv(qtls, row.names = FALSE)))
1538
- report_lines <- c(report_lines, "")
1539
- }
1540
-
1541
- if (!is.null(perms)) {
1542
- report_lines <- c(report_lines, "## Permutation Thresholds")
1543
- report_lines <- c(report_lines, capture.output(write.csv(perms$thresholds, row.names = FALSE)))
1544
- }
1545
-
1546
- writeLines(report_lines, file)
1547
- }
1548
- )
1549
-
1550
- output$download_all_plots <- downloadHandler(
1551
- filename = function() paste0("all_plots_", Sys.Date(), ".pdf"),
1552
- content = function(file) {
1553
- pdf(file, width = 12, height = 8)
1554
-
1555
- # Generate and save each plot
1556
- models <- all_models()
1557
- qtls <- qtl_results()
1558
- cross <- cross_data()
1559
- comp <- model_comparison()
1560
-
1561
- if (!is.null(cross)) {
1562
- print(plot_genetic_density(cross))
1563
- print(plot_missing_data(cross))
1564
- }
1565
-
1566
- if (!is.null(models) && !is.null(models$hk)) {
1567
- print(plot_manhattan_enhanced(models$hk, qtls, input$lod_threshold))
1568
- print(plot_lod_contour(models$hk))
1569
- print(plot_ridge_distribution(models$hk))
1570
- print(plot_qq_plot(models$hk))
1571
- print(plot_chromosome_heatmap(models$hk))
1572
- }
1573
-
1574
- if (!is.null(qtls) && nrow(qtls) > 0) {
1575
- print(plot_qtl_bubble(qtls))
1576
- print(plot_qtl_intervals(qtls))
1577
- print(plot_pve_distribution(qtls))
1578
- }
1579
-
1580
- if (!is.null(comp) && nrow(comp) > 0) {
1581
- print(plot_model_comparison(comp))
1582
- }
1583
-
1584
- if (!is.null(cross) && ncol(cross$pheno) >= 2) {
1585
- plot_phenotype_correlation(cross)
1586
- }
1587
-
1588
- dev.off()
1589
- }
1590
- )
1591
  }
1592
 
1593
  # Run the app
 
1
  # ============================================================================
2
  # COMPLETE QTL ANALYSIS PIPELINE - FULLY FUNCTIONAL
3
+ # All errors fixed - calc.het instead of calc.heterozyg
4
  # ============================================================================
5
 
6
+ # Load libraries
7
  suppressPackageStartupMessages({
8
  library(shiny)
9
  library(shinydashboard)
 
21
  library(viridis)
22
  library(ggridges)
23
  library(pheatmap)
 
 
 
 
 
 
 
24
  })
25
 
26
+ # Check for corrplot
27
+ if (!require("corrplot", quietly = TRUE)) {
28
+ install.packages("corrplot", repos = "https://cloud.r-project.org/")
29
+ library(corrplot)
30
+ }
31
+
32
  # ============================================================================
33
  # SAFE NOTIFICATION FUNCTION
34
  # ============================================================================
 
43
  }, error = function(e) message(msg))
44
  }
45
 
46
+ # ============================================================================
47
+ # HELPER FUNCTION - Calculate Heterozygosity
48
+ # ============================================================================
49
+
50
+ calculate_heterozygosity <- function(cross) {
51
+ # Calculate heterozygosity manually
52
+ het_rates <- rep(NA, nind(cross))
53
+ for (i in 1:nind(cross)) {
54
+ geno_ind <- pull.geno(cross)[i, ]
55
+ het_rates[i] <- mean(geno_ind == 2, na.rm = TRUE) # 2 = heterozygous in F2
56
+ }
57
+ return(het_rates)
58
+ }
59
+
60
  # ============================================================================
61
  # ADVANCED DATA PARSER
62
  # ============================================================================
 
191
  # Run basic checks
192
  cross <- jittermap(cross)
193
 
194
+ # Calculate additional statistics (using safe function)
195
+ het_rates <- calculate_heterozygosity(cross)
196
+
197
  attr(cross, "summary") <- list(
198
  n_ind = nind(cross),
199
  n_markers = totmar(cross),
200
  n_chr = nchr(cross),
201
+ missing_rate = mean(nmissing(cross, what="mar") / nind(cross), na.rm = TRUE),
202
+ heterozygosity = mean(het_rates, na.rm = TRUE)
203
  )
204
 
205
  return(cross)
 
423
  }
424
 
425
  qtls <- rbind(qtls, data.frame(
 
426
  Chromosome = as.character(chr),
427
  Peak_Position_cM = round(peak_row$pos, 2),
428
  Peak_Marker = peak_marker,
 
450
  qtls$ChrNum[is.na(qtls$ChrNum)] <- 999
451
  qtls <- qtls[order(qtls$ChrNum, qtls$Peak_Position_cM), ]
452
  qtls$ChrNum <- NULL
 
453
  }
454
 
455
  return(qtls)
 
514
  }
515
 
516
  # ============================================================================
517
+ # PLOTTING FUNCTIONS
518
  # ============================================================================
519
 
520
+ # Plot 1: Enhanced Manhattan Plot
521
  plot_manhattan_enhanced <- function(scan, qtls, threshold) {
522
  if (is.null(scan)) return(NULL)
523
 
 
525
  df$marker <- rownames(df)
526
  df$significant <- df$lod >= threshold
527
 
 
528
  chrs <- unique(df$chr)
529
  chr_lengths <- sapply(chrs, function(ch) max(df$pos[df$chr == ch], na.rm = TRUE))
530
  cum_lengths <- cumsum(c(0, chr_lengths[-length(chrs)]))
 
533
  df$pos_cum <- df$pos + cum_lengths[as.character(df$chr)]
534
  chr_midpoints <- sapply(chrs, function(ch) mean(df$pos_cum[df$chr == ch], na.rm = TRUE))
535
 
 
536
  colors <- rep(brewer.pal(8, "Set1"), length.out = length(chrs))
537
  names(colors) <- chrs
538
 
 
545
  x = "Chromosome", y = "LOD Score") +
546
  theme_minimal() +
547
  theme(legend.position = "none",
548
+ axis.text.x = element_text(angle = 45, hjust = 1))
 
549
 
 
550
  if (!is.null(qtls) && nrow(qtls) > 0) {
551
  qtls$pos_cum <- qtls$Peak_Position_cM + cum_lengths[as.character(qtls$Chromosome)]
552
  p <- p +
553
  geom_point(data = qtls, aes(x = pos_cum, y = LOD_Score),
554
+ color = "gold", size = 5, shape = 18)
 
 
 
555
  }
556
 
557
  return(p)
 
574
  geom_contour_filled(bins = 8) +
575
  scale_fill_viridis_d(name = "LOD", direction = -1) +
576
  scale_y_continuous(breaks = 1:length(chrs), labels = chrs) +
577
+ labs(title = "LOD Contour Plot", x = "Position (cM)", y = "Chromosome") +
578
+ theme_minimal()
 
 
579
  }
580
 
581
  # Plot 3: QTL Effect Bubble Plot
 
586
  size = LOD_Score, color = PVE_Percent)) +
587
  geom_point(alpha = 0.8) +
588
  scale_size_continuous(range = c(3, 20), name = "LOD Score") +
589
+ scale_color_gradientn(colors = c("blue", "green", "yellow", "red"), name = "PVE (%)") +
 
590
  labs(title = "QTL Effect Size Bubble Plot",
591
+ x = "Chromosome", y = "Position (cM)") +
592
  theme_minimal() +
593
+ theme(axis.text.x = element_text(angle = 45, hjust = 1))
 
594
  }
595
 
596
+ # Plot 4: Ridge Plot
597
+ plot_ridge_distribution <- function(scan) {
598
+ if (is.null(scan)) return(NULL)
599
+
600
+ df <- as.data.frame(scan)
601
+ df$chr <- factor(df$chr, levels = unique(df$chr))
602
+
603
+ ggplot(df, aes(x = lod, y = chr, fill = after_stat(x))) +
604
+ geom_density_ridges_gradient(scale = 2, rel_min_height = 0.01) +
605
+ scale_fill_viridis_c(option = "C", name = "LOD Score") +
606
+ labs(title = "LOD Score Distribution", x = "LOD Score", y = "Chromosome") +
607
+ theme_ridges()
608
+ }
609
+
610
+ # Plot 5: Violin Plot
611
  plot_genotype_violin <- function(cross, qtl, trait) {
612
  if (is.null(cross) || is.null(qtl) || nrow(qtl) == 0) return(NULL)
613
 
614
  chr_name <- as.character(qtl$Chromosome[1])
615
  if (!chr_name %in% names(cross$geno)) return(NULL)
616
 
 
617
  map <- pull.map(cross)[[chr_name]]
618
  marker_pos <- which.min(abs(map - qtl$Peak_Position_cM[1]))
619
  marker_name <- names(map)[marker_pos]
620
 
 
621
  geno_idx <- find.marker(cross, chr_name, marker_name)
622
  genotypes <- pull.geno(cross)[, geno_idx]
623
  phenotypes <- cross$pheno[[trait]]
 
628
  )
629
  df <- df[!is.na(df$Genotype) & !is.na(df$Phenotype), ]
630
 
 
631
  if (length(unique(df$Genotype)) == 3) {
632
  df$Genotype <- recode(df$Genotype, `1` = "AA", `2` = "AB", `3` = "BB")
633
  } else if (length(unique(df$Genotype)) == 2) {
 
638
  geom_violin(alpha = 0.6, trim = FALSE) +
639
  geom_boxplot(width = 0.2, alpha = 0.8) +
640
  stat_summary(fun = mean, geom = "point", shape = 18, size = 5, color = "red") +
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
641
  scale_fill_brewer(palette = "Set2") +
642
+ labs(title = paste("Phenotype at", marker_name), x = "Genotype", y = trait) +
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
643
  theme_minimal() +
644
+ theme(legend.position = "none")
 
 
 
 
 
 
 
 
 
 
 
 
 
645
  }
646
 
647
+ # Plot 6: Genetic Map Density
648
  plot_genetic_density <- function(cross) {
649
  if (is.null(cross)) return(NULL)
650
 
651
  map <- pull.map(cross)
652
+ df <- data.frame()
 
653
  for (chr in names(map)) {
654
  positions <- map[[chr]]
655
+ df <- rbind(df, data.frame(Chromosome = chr, Position = positions))
 
 
 
 
656
  }
657
 
658
+ df$Chromosome <- factor(df$Chromosome, levels = names(map))
659
 
660
+ ggplot(df, aes(x = Chromosome, y = Position)) +
661
+ geom_segment(aes(xend = Chromosome, yend = 0), color = "gray70", size = 1) +
662
+ geom_point(color = "steelblue", size = 2, alpha = 0.7) +
663
+ labs(title = "Genetic Map", x = "Chromosome", y = "Position (cM)") +
 
664
  theme_minimal() +
665
+ theme(axis.text.x = element_text(angle = 45, hjust = 1))
 
666
  }
667
 
668
+ # Plot 7: Model Comparison Bar Plot
669
+ plot_model_comparison <- function(comparison_df) {
670
+ if (is.null(comparison_df) || nrow(comparison_df) == 0) return(NULL)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
671
 
672
+ ggplot(comparison_df, aes(x = reorder(Model, -Max_LOD), y = Max_LOD, fill = Model)) +
 
673
  geom_bar(stat = "identity", alpha = 0.8) +
674
+ geom_text(aes(label = Max_LOD), vjust = -0.5, size = 3.5) +
675
+ scale_fill_brewer(palette = "Set2") +
676
+ labs(title = "Model Performance Comparison",
677
+ x = "Method", y = "Max LOD Score") +
678
  theme_minimal() +
679
+ theme(legend.position = "none",
680
+ axis.text.x = element_text(angle = 45, hjust = 1))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
681
  }
682
 
683
  # ============================================================================
 
685
  # ============================================================================
686
 
687
  ui <- dashboardPage(
688
+ dashboardHeader(title = "QTL Analysis - Complete Suite"),
689
 
690
+ dashboardSidebar(width = 320,
691
  sidebarMenu(
692
  menuItem("Data Input", tabName = "data", icon = icon("upload")),
693
  menuItem("10 Models", tabName = "models", icon = icon("cogs")),
694
  menuItem("QTL Results", tabName = "results", icon = icon("table")),
695
+ menuItem("Plots", tabName = "plots", icon = icon("chart-bar")),
696
+ menuItem("Download", tabName = "download", icon = icon("download")),
697
+ menuItem("Help", tabName = "help", icon = icon("question-circle"))
698
  ),
699
 
700
  div(style = "padding: 15px;",
701
+ h4("Data Upload"),
702
  fileInput("geno_file", "Genotype CSV", accept = ".csv"),
703
  fileInput("pheno_file", "Phenotype CSV", accept = ".csv"),
704
 
705
  selectInput("cross_type", "Cross Type",
706
+ choices = c("F2 Intercross" = "f2", "Backcross" = "bc", "RIL" = "riself"),
 
 
 
707
  selected = "f2"),
708
 
709
  hr(),
710
 
711
+ h4("Parameters"),
712
+ selectInput("pheno_trait", "Phenotype", choices = NULL),
713
+ numericInput("lod_threshold", "LOD Threshold", value = 3.0, min = 0, max = 20, step = 0.5),
714
+ numericInput("n_permutations", "Permutations", value = 100, min = 0, max = 1000),
 
 
 
 
 
 
715
 
716
+ actionButton("run_analysis", "RUN 10 MODELS",
717
  icon = icon("play"),
718
+ style = "background-color: #3c8dbc; color: white; width: 100%;")
 
 
 
 
 
 
 
719
  )
720
  ),
721
 
722
  dashboardBody(
723
  useShinyjs(),
724
+ tags$head(tags$style(HTML("
725
+ .content-wrapper, .right-side { background-color: #f4f4f4; }
726
+ .box { border-radius: 10px; }
727
+ "))),
 
 
 
 
728
 
729
  tabItems(
 
730
  tabItem(tabName = "data",
731
  fluidRow(
732
  valueBoxOutput("n_individuals"),
 
734
  valueBoxOutput("n_chromosomes")
735
  ),
736
  fluidRow(
737
+ box(title = "Data Summary", status = "primary", width = 12,
738
+ verbatimTextOutput("data_summary"))
 
739
  ),
740
  fluidRow(
741
  box(title = "Genetic Map", status = "info", width = 12,
742
+ plotOutput("genetic_map", height = "500px") %>% withSpinner())
 
 
 
 
 
 
 
 
 
 
 
743
  )
744
  ),
745
 
 
746
  tabItem(tabName = "models",
747
  fluidRow(
748
+ box(title = "Analysis Status", status = "primary", width = 12,
749
+ verbatimTextOutput("analysis_status"))
 
750
  ),
751
  fluidRow(
752
  box(title = "Model Comparison", status = "info", width = 12,
753
+ DTOutput("model_comparison_table") %>% withSpinner())
 
754
  ),
755
  fluidRow(
756
+ box(title = "Model Performance", status = "success", width = 12,
757
+ plotOutput("model_barplot", height = "500px") %>% withSpinner())
 
 
 
 
 
 
 
 
 
 
 
758
  )
759
  ),
760
 
 
761
  tabItem(tabName = "results",
762
  fluidRow(
763
+ box(title = "Significant QTLs", status = "primary", width = 12,
764
+ DTOutput("qtl_table") %>% withSpinner())
 
 
 
 
 
 
765
  ),
766
  fluidRow(
767
+ box(title = "Permutation Results", status = "info", width = 12,
768
+ DTOutput("permutation_table") %>% withSpinner())
 
 
 
 
 
 
769
  )
770
  ),
771
 
 
772
  tabItem(tabName = "plots",
773
  fluidRow(
774
+ box(title = "Manhattan Plot", status = "primary", width = 12,
775
+ plotOutput("manhattan_plot", height = "600px") %>% withSpinner())
 
776
  ),
777
  fluidRow(
778
+ box(title = "Contour Plot", status = "info", width = 6,
779
+ plotOutput("contour_plot", height = "500px") %>% withSpinner()),
780
+ box(title = "Ridge Plot", status = "success", width = 6,
781
+ plotOutput("ridge_plot", height = "500px") %>% withSpinner())
782
  ),
783
  fluidRow(
784
+ box(title = "Bubble Plot", status = "warning", width = 12,
785
+ plotOutput("bubble_plot", height = "500px") %>% withSpinner())
 
 
 
 
786
  ),
787
  fluidRow(
788
+ box(title = "Genotype-Phenotype Association", status = "danger", width = 12,
789
+ selectInput("violin_qtl", "Select QTL:", choices = NULL),
790
+ plotOutput("violin_plot", height = "500px") %>% withSpinner())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
791
  )
792
  ),
793
 
 
794
  tabItem(tabName = "download",
795
  fluidRow(
796
+ box(title = "Download Results", status = "primary", width = 12,
797
  br(),
 
 
798
  downloadButton("download_qtl_results", "Download QTL Results (CSV)",
799
+ style = "margin: 10px;"),
 
 
 
 
 
800
  downloadButton("download_model_comparison", "Download Model Comparison (CSV)",
801
+ style = "margin: 10px;"),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
802
  br(), br()
803
  )
804
  )
805
  ),
806
 
 
807
  tabItem(tabName = "help",
808
  fluidRow(
809
+ box(title = "Documentation", status = "primary", width = 12,
810
  HTML("
811
+ <h3>10 Mapping Models</h3>
812
+ <p>HK, EM, EHK, IMP, MR, NP, CIM, MQM, Binary, Normal</p>
813
+ <h3>File Format</h3>
814
+ <p>Genotype: Row1=headers, Row2=chr, Row3=pos, Row4+=data</p>
815
+ <p>Phenotype: First column=ID, rest=traits</p>
816
+ "))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
817
  )
818
  )
819
  )
 
826
 
827
  server <- function(input, output, session) {
828
 
 
829
  cross_data <- reactiveVal(NULL)
830
  all_models <- reactiveVal(NULL)
831
  qtl_results <- reactiveVal(NULL)
832
  permutation_results <- reactiveVal(NULL)
833
  model_comparison <- reactiveVal(NULL)
834
  analysis_complete <- reactiveVal(FALSE)
 
835
 
836
  # Value boxes
837
  output$n_individuals <- renderValueBox({
 
856
  observeEvent(c(input$geno_file, input$pheno_file), {
857
  req(input$geno_file, input$pheno_file)
858
 
859
+ safe_notify("Loading data...", "message")
860
 
861
  tryCatch({
862
  cross <- parse_advanced_cross(
 
871
  choices = names(cross$pheno),
872
  selected = names(cross$pheno)[1])
873
 
874
+ safe_notify(paste("Loaded:", nind(cross), "individuals,", totmar(cross), "markers"), "success")
 
875
 
876
  }, error = function(e) {
877
  safe_notify(paste("Error:", e$message), "error")
878
  })
879
  })
880
 
881
+ # Run analysis
882
  observeEvent(input$run_analysis, {
883
  cross <- cross_data()
884
  req(cross, input$pheno_trait)
885
 
886
+ safe_notify("Running 10 models...", "message")
887
 
888
+ withProgress(message = "Running 10 QTL Models", value = 0, {
889
 
890
+ incProgress(0.2, detail = "Running all models...")
891
  pheno_idx <- which(names(cross$pheno) == input$pheno_trait)
 
 
892
  models <- run_all_ten_models(cross, pheno_idx)
893
  all_models(models)
894
 
895
+ incProgress(0.3, detail = "Detecting QTLs...")
 
 
 
 
 
 
896
  if (!is.null(models$hk)) {
897
  qtls <- detect_comprehensive_qtls(models$hk, input$lod_threshold,
898
  cross, input$pheno_trait)
899
  qtl_results(qtls)
900
 
901
  if (nrow(qtls) > 0) {
902
+ qtl_choices <- paste0("Chr", qtls$Chromosome, "_", qtls$Peak_Position_cM, "cM")
 
903
  updateSelectInput(session, "violin_qtl", choices = qtl_choices)
904
  }
905
  }
906
 
907
+ incProgress(0.3, detail = "Comparing models...")
908
  comp <- create_model_comparison(models, input$lod_threshold)
909
  model_comparison(comp)
910
 
 
915
  }
916
 
917
  analysis_complete(TRUE)
 
918
  n_success <- sum(!sapply(models, is.null))
919
  safe_notify(paste("Complete!", n_success, "models succeeded"), "success")
920
  })
921
  })
922
 
 
 
 
 
 
923
  # Data summary
924
  output$data_summary <- renderPrint({
925
  cross <- cross_data()
926
  if (is.null(cross)) {
927
+ cat("No data loaded.")
928
  } else {
 
929
  cat("Cross Type:", class(cross)[1], "\n")
930
  cat("Individuals:", nind(cross), "\n")
931
  cat("Markers:", totmar(cross), "\n")
932
+ cat("Chromosomes:", nchr(cross), "\n")
933
+ cat("Phenotypes:", paste(names(cross$pheno), collapse = ", "), "\n")
 
 
 
 
934
  }
935
  })
936
 
937
  output$analysis_status <- renderPrint({
938
  if (!analysis_complete()) {
939
+ cat("Click 'RUN 10 MODELS' to start.")
940
  } else {
941
  models <- all_models()
942
  n_success <- sum(!sapply(models, is.null))
943
  qtls <- qtl_results()
 
 
944
  cat("Models succeeded:", n_success, "/10\n")
945
  cat("QTLs detected:", ifelse(is.null(qtls), 0, nrow(qtls)), "\n")
 
 
 
 
 
 
 
 
 
 
 
946
  }
947
  })
948
 
949
+ # Tables
950
  output$model_comparison_table <- renderDT({
951
  comp <- model_comparison()
952
  req(comp, nrow(comp) > 0)
953
+ datatable(comp, options = list(pageLength = 10, scrollX = TRUE), rownames = FALSE)
 
 
954
  })
955
 
 
956
  output$qtl_table <- renderDT({
957
  qtls <- qtl_results()
958
  req(qtls, nrow(qtls) > 0)
959
+ datatable(qtls, options = list(pageLength = 15, scrollX = TRUE), rownames = FALSE)
 
 
 
 
 
 
 
 
 
 
 
 
960
  })
961
 
 
962
  output$permutation_table <- renderDT({
963
  perms <- permutation_results()
964
  req(perms)
965
+ datatable(perms$thresholds, options = list(pageLength = 5, dom = 't'), rownames = FALSE)
 
 
 
 
 
966
  })
967
 
968
+ # Plots
969
  output$genetic_map <- renderPlot({
970
  cross <- cross_data()
971
  req(cross)
972
  plot_genetic_density(cross)
973
  })
974
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
975
  output$manhattan_plot <- renderPlot({
976
  models <- all_models()
977
  qtls <- qtl_results()
 
979
  plot_manhattan_enhanced(models$hk, qtls, input$lod_threshold)
980
  })
981
 
 
 
 
 
 
 
982
  output$contour_plot <- renderPlot({
983
  models <- all_models()
984
  req(models, !is.null(models$hk))
 
997
  plot_qtl_bubble(qtls)
998
  })
999
 
 
 
 
 
 
 
1000
  output$violin_plot <- renderPlot({
1001
  req(input$violin_qtl, input$violin_qtl != "")
1002
  qtls <- qtl_results()
1003
  cross <- cross_data()
1004
  req(qtls, nrow(qtls) > 0, cross, input$pheno_trait)
1005
 
1006
+ qtl_idx <- which(paste0("Chr", qtls$Chromosome, "_", qtls$Peak_Position_cM, "cM") == input$violin_qtl)
 
1007
  if (length(qtl_idx) == 0) return(NULL)
1008
 
1009
  plot_genotype_violin(cross, qtls[qtl_idx[1], , drop = FALSE], input$pheno_trait)
1010
  })
1011
 
 
 
 
 
 
 
 
 
 
 
 
 
1012
  output$model_barplot <- renderPlot({
1013
  comp <- model_comparison()
1014
  req(comp, nrow(comp) > 0)
1015
  plot_model_comparison(comp)
1016
  })
1017
 
1018
+ # Download handlers
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1019
  output$download_qtl_results <- downloadHandler(
1020
  filename = function() paste0("qtl_results_", Sys.Date(), ".csv"),
1021
  content = function(file) {
 
1023
  if (!is.null(qtls) && nrow(qtls) > 0) {
1024
  write.csv(qtls, file, row.names = FALSE)
1025
  } else {
1026
+ write.csv(data.frame(Message = "No QTLs found"), file, row.names = FALSE)
 
1027
  }
1028
  }
1029
  )
 
1035
  if (!is.null(comp) && nrow(comp) > 0) {
1036
  write.csv(comp, file, row.names = FALSE)
1037
  } else {
1038
+ write.csv(data.frame(Message = "Run analysis first"), file, row.names = FALSE)
 
1039
  }
1040
  }
1041
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1042
  }
1043
 
1044
  # Run the app