softwareDevelopment commited on
Commit
b59f5bf
·
verified ·
1 Parent(s): 6d9c4eb

Update app.R

Browse files
Files changed (1) hide show
  1. app.R +279 -153
app.R CHANGED
@@ -1,23 +1,22 @@
1
  # ============================================================
2
- # QTL-Mapper v11 — Precision QTL Interval Mapping
3
  #
4
- # FIXES over v10:
5
- # 1. PVE DENOMINATOR FIX (CIM/MQM): PVE now uses SST = sum((y-mean(y))^2)
6
- # 2. LOD THRESHOLD AFTER PERMUTATION: stored in rv$perm_threshold, not auto-reset
7
- # 3. PVE FUNCTION UNIFIED: calc_pve_total() always uses SST
8
- # 4. CIM/MQM PVE FIX: SST denominator, not partial R²
9
- # 5. LASSO/ENET LOD: true LOD-equivalent using (n/2)*log10(RSS0/RSS1)
10
- # 6. RF IMPORTANCE → LOD: per-marker regression LOD
11
- # 7. MIN LOD SLIDER: min is now 0.1
12
- # 8. createDataPartition FIX: robust sample size checks, NA removal,
13
- # fallback to simple split if caret fails
14
- # 9. SAMPLE ID MATCHING FIX: trimws + tolower normalization
15
- # 10. ZERO-VARIANCE PHENOTYPE CHECK: stops early with clear message
16
- # 11. MINIMUM SAMPLE GUARD: requires >= 20 common samples
17
- # 12. PARTITION SIZE GUARD: ensures train/val both have >= 5 samples
18
- # 13. find_interval_boundary FIX: guards against invalid seq() when
19
- # peak_idx == 1 (left) or peak_idx == n (right), eliminating the
20
- # "wrong sign in 'by' argument" error
21
  # ============================================================
22
 
23
  options(repos = c(CRAN = "https://cloud.r-project.org"))
@@ -45,7 +44,6 @@ cn <- function(x) {
45
  trimws(gsub('[\r\n\"]', '', as.character(x)))
46
  }
47
 
48
- # Normalize sample IDs for robust matching
49
  normalize_id <- function(x) trimws(as.character(x))
50
 
51
  # ============================================================
@@ -75,15 +73,15 @@ MAPPING_MODELS <- list(
75
  "SIM" = list(label = "Simple Interval Mapping (SIM)",
76
  desc = "QTL Cartographer-style single-marker regression; LOD = (n/2)*log10(SST/RSS1); PVE = (SST-RSS1)/SST * 100"),
77
  "CIM" = list(label = "Composite Interval Mapping (CIM)",
78
- desc = "CIM with background marker cofactors; LOD = (n/2)*log10(SST/RSS_focal); PVE = (SST-RSS_focal)/SST * 100 — SST always from intercept-only null"),
79
  "MQM" = list(label = "Multiple QTL Model (MQM)",
80
  desc = "Multiple QTL stepwise model; LOD tests focal QTL against cofactor background; PVE uses SST denominator"),
81
  "LASSO" = list(label = "LASSO QTL (L1 penalized)",
82
- desc = "L1-penalized regression; LOD approximated as (n/2)*log10(SST/RSS_hat); lambda by 5-fold CV (lambda.1se)"),
83
  "ENET" = list(label = "Elastic Net (L1+L2)",
84
- desc = "Elastic net alpha=0.5; LOD approximated as (n/2)*log10(SST/RSS_hat); lambda by 5-fold CV"),
85
  "RF" = list(label = "Random Forest QTL",
86
- desc = "Non-parametric %IncMSE; LOD-equivalent scaled from importance; 1000 trees. Note: permutation thresholds most valid for SIM/CIM/MQM.")
87
  )
88
 
89
  # ============================================================
@@ -104,6 +102,17 @@ calc_lod_sst <- function(fit_full, sst, n) {
104
  max(0, (n / 2) * log10(sst / rss1))
105
  }
106
 
 
 
 
 
 
 
 
 
 
 
 
107
  calc_pve_total <- function(fit_full, y_vec) {
108
  sst <- sum((y_vec - mean(y_vec))^2)
109
  rss1 <- sum(residuals(fit_full)^2)
@@ -111,6 +120,14 @@ calc_pve_total <- function(fit_full, y_vec) {
111
  max(0, min(100, (sst - rss1) / sst * 100))
112
  }
113
 
 
 
 
 
 
 
 
 
114
  dom_class <- function(a, d) {
115
  if (is.na(a) || is.na(d) || abs(a) < 1e-10) return(NA_character_)
116
  r <- abs(d / a)
@@ -161,9 +178,6 @@ safe_partition <- function(y, val_prop = 0.2) {
161
 
162
  # ============================================================
163
  # PRECISION SUPPORT INTERVAL
164
- # FIX: Added early-return guards when peak_idx == 1 (left) or
165
- # peak_idx == n (right) so seq() never receives a negative
166
- # 'by' argument, eliminating "wrong sign in 'by' argument".
167
  # ============================================================
168
  find_interval_boundary <- function(lod_profile, positions, peak_idx, peak_lod,
169
  drop, direction = "left") {
@@ -171,7 +185,6 @@ find_interval_boundary <- function(lod_profile, positions, peak_idx, peak_lod,
171
  n <- length(lod_profile)
172
 
173
  if (direction == "left") {
174
- # ── FIX: if peak is already at position 1, nothing to scan left ──
175
  if (peak_idx <= 1) {
176
  return(list(position = positions[1],
177
  marker_left = NA_character_,
@@ -199,7 +212,6 @@ find_interval_boundary <- function(lod_profile, positions, peak_idx, peak_lod,
199
  marker_right = names(positions)[1]))
200
 
201
  } else {
202
- # ── FIX: if peak is already at the last position, nothing to scan right ──
203
  if (peak_idx >= n) {
204
  return(list(position = positions[n],
205
  marker_left = names(positions)[n],
@@ -675,112 +687,220 @@ qtl_scan_mqm <- function(X, y, marker_info, n_cofactors = 10, window_size = 10)
675
 
676
  # ============================================================
677
  # LASSO
 
 
 
678
  # ============================================================
679
  qtl_scan_lasso <- function(X, y, marker_info) {
 
680
  ok <- !is.na(y) & apply(X, 1, function(r) !any(is.na(r)))
681
- Xv <- X[ok, , drop = FALSE]; yv <- y[ok]; Xs <- scale(Xv)
 
 
 
 
 
 
 
 
 
 
 
 
682
  cv <- tryCatch(cv.glmnet(as.matrix(Xs), yv, alpha = 1, nfolds = 5), error = function(e) NULL)
683
  if (is.null(cv)) return(data.frame(Message = "LASSO failed"))
684
 
 
 
 
 
 
 
 
 
685
  cf <- as.matrix(coef(cv, s = cv$lambda.1se))[-1, 1]
686
  cdf <- data.frame(Marker = names(cf), Effect = as.numeric(cf))
687
  cdf <- cdf[abs(cdf$Effect) > 1e-8, ]
688
  if (nrow(cdf) == 0) return(data.frame(Message = "LASSO: no non-zero effects"))
689
  cdf <- merge(cdf, marker_info, by = "Marker", all.x = TRUE)
690
  cdf <- cdf[!is.na(cdf$Position), ]
 
691
 
 
692
  cdf$LOD <- sapply(seq_len(nrow(cdf)), function(i) {
693
- m <- cdf$Marker[i]
694
- g <- Xv[, m]; v <- !is.na(g)
695
  if (sum(v) < 8) return(0)
696
  gv2 <- g[v]; pv2 <- yv[v]
697
- fit <- tryCatch(lm(pv2 ~ gv2), error = function(e) NULL)
698
  if (is.null(fit)) return(0)
699
  calc_lod(fit, lm(pv2 ~ 1))
700
  })
701
- cdf$P_Value <- 10^(-cdf$LOD)
702
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
703
  cdf$PVE_Percent <- sapply(cdf$Marker, function(m) {
704
  g <- Xv[, m]; v <- !is.na(g)
705
- if (sum(v) < 5) return(NA)
706
  fit <- tryCatch(lm(yv[v] ~ g[v]), error = function(e) NULL)
707
- if (is.null(fit)) return(NA)
708
  calc_pve_total(fit, yv[v])
709
  })
710
 
711
- cdf$Additive_Effect <- cdf$Effect; cdf$SE_Additive <- NA_real_
712
- cdf$CI_Lower <- NA_real_; cdf$CI_Upper <- NA_real_
713
- cdf$Dominance_Effect <- NA_real_; cdf$SE_Dominance <- NA_real_
714
- cdf$Dominance_Ratio <- NA_real_; cdf$Dominance_Class <- "Additive"
715
- cdf$N_Cofactors <- 0L; cdf$N_Samples <- sum(ok)
 
 
 
 
 
 
 
 
716
  cdf$Method <- "LASSO"
717
 
718
  cdf <- cdf[order(cdf$Chromosome, cdf$Position), ]
719
  cdf[, c("Marker","Chromosome","Position","LOD","P_Value","PVE_Percent",
720
  "Additive_Effect","SE_Additive","CI_Lower","CI_Upper",
721
  "Dominance_Effect","SE_Dominance","Dominance_Ratio",
722
- "Dominance_Class","N_Cofactors","N_Samples","Method")]
 
723
  }
724
 
725
  # ============================================================
726
  # Elastic Net
 
727
  # ============================================================
728
  qtl_scan_enet <- function(X, y, marker_info) {
 
729
  ok <- !is.na(y) & apply(X, 1, function(r) !any(is.na(r)))
730
- Xv <- X[ok, , drop = FALSE]; yv <- y[ok]; Xs <- scale(Xv)
 
 
 
 
 
 
 
 
 
 
731
  cv <- tryCatch(cv.glmnet(as.matrix(Xs), yv, alpha = 0.5, nfolds = 5), error = function(e) NULL)
732
  if (is.null(cv)) return(data.frame(Message = "ElasticNet failed"))
733
 
 
 
 
 
 
 
 
 
734
  cf <- as.matrix(coef(cv, s = cv$lambda.1se))[-1, 1]
735
  cdf <- data.frame(Marker = names(cf), Effect = as.numeric(cf))
736
  cdf <- cdf[abs(cdf$Effect) > 1e-8, ]
737
  if (nrow(cdf) == 0) return(data.frame(Message = "ENET: no non-zero effects"))
738
  cdf <- merge(cdf, marker_info, by = "Marker", all.x = TRUE)
739
  cdf <- cdf[!is.na(cdf$Position), ]
 
740
 
 
741
  cdf$LOD <- sapply(seq_len(nrow(cdf)), function(i) {
742
- m <- cdf$Marker[i]; g <- Xv[, m]; v <- !is.na(g)
 
743
  if (sum(v) < 8) return(0)
744
  fit <- tryCatch(lm(yv[v] ~ g[v]), error = function(e) NULL)
745
  if (is.null(fit)) return(0)
746
  calc_lod(fit, lm(yv[v] ~ 1))
747
  })
748
- cdf$P_Value <- 10^(-cdf$LOD)
749
 
 
 
 
 
 
 
 
 
 
 
 
 
 
750
  cdf$PVE_Percent <- sapply(cdf$Marker, function(m) {
751
  g <- Xv[, m]; v <- !is.na(g)
752
- if (sum(v) < 5) return(NA)
753
  fit <- tryCatch(lm(yv[v] ~ g[v]), error = function(e) NULL)
754
- if (is.null(fit)) return(NA)
755
  calc_pve_total(fit, yv[v])
756
  })
757
 
758
- cdf$Additive_Effect <- cdf$Effect; cdf$SE_Additive <- NA_real_
759
- cdf$CI_Lower <- NA_real_; cdf$CI_Upper <- NA_real_
760
- cdf$Dominance_Effect <- NA_real_; cdf$SE_Dominance <- NA_real_
761
- cdf$Dominance_Ratio <- NA_real_; cdf$Dominance_Class <- "Additive"
762
- cdf$N_Cofactors <- 0L; cdf$N_Samples <- sum(ok)
 
 
 
 
 
 
 
 
763
  cdf$Method <- "ENET"
764
 
765
  cdf <- cdf[order(cdf$Chromosome, cdf$Position), ]
766
  cdf[, c("Marker","Chromosome","Position","LOD","P_Value","PVE_Percent",
767
  "Additive_Effect","SE_Additive","CI_Lower","CI_Upper",
768
  "Dominance_Effect","SE_Dominance","Dominance_Ratio",
769
- "Dominance_Class","N_Cofactors","N_Samples","Method")]
 
770
  }
771
 
772
  # ============================================================
773
  # Random Forest
 
 
 
774
  # ============================================================
775
  qtl_scan_rf <- function(X, y, marker_info) {
 
776
  ok <- !is.na(y) & apply(X, 1, function(r) !any(is.na(r)))
777
- Xv <- X[ok, , drop = FALSE]; yv <- y[ok]
 
 
 
778
  rf <- tryCatch(
779
  randomForest(x = Xv, y = yv, ntree = 1000, importance = TRUE,
780
- mtry = max(1, floor(sqrt(ncol(Xv))))),
 
781
  error = function(e) NULL)
782
  if (is.null(rf)) return(data.frame(Message = "RF failed"))
783
 
 
 
 
 
 
 
 
 
784
  imp <- importance(rf, type = 1)[, 1]
785
  idf <- data.frame(Marker = names(imp), Importance = imp)
786
  idf <- idf[idf$Importance > 0, ]
@@ -788,6 +908,7 @@ qtl_scan_rf <- function(X, y, marker_info) {
788
  idf <- merge(idf, marker_info, by = "Marker", all.x = TRUE)
789
  idf <- idf[!is.na(idf$Position), ]
790
 
 
791
  idf$LOD <- sapply(seq_len(nrow(idf)), function(i) {
792
  m <- idf$Marker[i]; g <- Xv[, m]; v <- !is.na(g)
793
  if (sum(v) < 8) return(0)
@@ -795,28 +916,47 @@ qtl_scan_rf <- function(X, y, marker_info) {
795
  if (is.null(fit)) return(0)
796
  calc_lod(fit, lm(yv[v] ~ 1))
797
  })
798
- idf$P_Value <- 10^(-idf$LOD)
799
 
 
 
 
 
 
 
 
 
 
 
 
 
800
  idf$PVE_Percent <- sapply(idf$Marker, function(m) {
801
  g <- Xv[, m]; v <- !is.na(g)
802
- if (sum(v) < 5) return(NA)
803
  fit <- tryCatch(lm(yv[v] ~ g[v]), error = function(e) NULL)
804
- if (is.null(fit)) return(NA)
805
  calc_pve_total(fit, yv[v])
806
  })
807
 
808
- idf$Additive_Effect <- NA_real_; idf$SE_Additive <- NA_real_
809
- idf$CI_Lower <- NA_real_; idf$CI_Upper <- NA_real_
810
- idf$Dominance_Effect <- NA_real_; idf$SE_Dominance <- NA_real_
811
- idf$Dominance_Ratio <- NA_real_; idf$Dominance_Class <- "Additive"
812
- idf$N_Cofactors <- 0L; idf$N_Samples <- sum(ok)
 
 
 
 
 
 
 
813
  idf$Method <- "RF"
814
 
815
  idf <- idf[order(idf$Chromosome, idf$Position), ]
816
  idf[, c("Marker","Chromosome","Position","LOD","P_Value","PVE_Percent",
817
  "Additive_Effect","SE_Additive","CI_Lower","CI_Upper",
818
  "Dominance_Effect","SE_Dominance","Dominance_Ratio",
819
- "Dominance_Class","N_Cofactors","N_Samples","Method")]
 
820
  }
821
 
822
  # ============================================================
@@ -1105,6 +1245,14 @@ make_plotly_manhattan <- function(scan_df, lod_threshold = 2.0, peaks_df = NULL,
1105
  else ""
1106
  }
1107
 
 
 
 
 
 
 
 
 
1108
  pl <- plot_ly()
1109
  for (ch in chroms) {
1110
  sub <- pd[pd$Chromosome == ch & !pd$sig, ]
@@ -1115,7 +1263,8 @@ make_plotly_manhattan <- function(scan_df, lod_threshold = 2.0, peaks_df = NULL,
1115
  marker = list(size = 6, color = chr_bg_colors[ch], opacity = 0.65),
1116
  text = paste0("<b>", sub$Marker, "</b><br>Chr: ", sub$Chromosome,
1117
  "<br>Pos: ", round(sub$Position, 1), " cM",
1118
- "<br>LOD: ", round(sub$LOD, 3), pve_text(sub)),
 
1119
  hoverinfo = "text")
1120
  }
1121
 
@@ -1132,7 +1281,8 @@ make_plotly_manhattan <- function(scan_df, lod_threshold = 2.0, peaks_df = NULL,
1132
  line = list(width = 1, color = "white"), opacity = 0.85),
1133
  text = paste0("<b>", sig_pd$Marker, "</b><br>Chr: ", sig_pd$Chromosome,
1134
  "<br>Pos: ", round(sig_pd$Position, 1), " cM",
1135
- "<br>LOD: ", round(sig_pd$LOD, 3), pve_text(sig_pd)),
 
1136
  hoverinfo = "text")
1137
  }
1138
 
@@ -1324,22 +1474,22 @@ ui <- fluidPage(
1324
  ),
1325
 
1326
  navbarPage(
1327
- title = "QTL-Mapper v11",
1328
  id = "nav",
1329
 
1330
  # ── 1. DATA UPLOAD ──────────────────────────────────────
1331
  tabPanel("📁 Data Upload", icon = icon("upload"),
1332
  fluidRow(column(12,
1333
  div(class="info-box",
1334
- tags$b("QTL-Mapper v11 — Precision QTL Interval Mapping"),
1335
  tags$br(),
1336
  "Format: Row1 = header (id, marker1, …) | Row2 = chromosomes | ",
1337
  "Row3 = positions (cM) | Rows 4+ = samples. Genotypes coded 0/1/2.",
1338
  tags$br(),
1339
  tags$span(style="color:#06D6A0;font-weight:600;",
1340
- "v11 FIXES: PVE uses SST denominator | Permutation threshold stored separately | ",
1341
- "LASSO/ENET/RF LOD = (n/2)*log10(SST/RSS) | Robust partition with safe_partition() | ",
1342
- "find_interval_boundary: guards against seq() 'wrong sign in by argument' crash")
1343
  )
1344
  )),
1345
  fluidRow(
@@ -1619,47 +1769,56 @@ ui <- fluidPage(
1619
  fluidRow(column(10, offset=1,
1620
  div(class="card",
1621
  div(class="card-bd",
1622
- tags$h4(style="color:#FF006E;","QTL-Mapper v11 — Precision QTL Interval Mapping"),
1623
  div(class="info-box",
1624
- tags$b("v11 Bug Fixes:"), tags$br(),
1625
- tags$span(class="fix-badge","FIXED"),
1626
- tags$b(" 'wrong sign in by argument' crash (find_interval_boundary):"),
1627
- " Added peak_idx boundary checks: if peak is at position 1 the left scan ",
1628
- "returns immediately; if peak is at position n the right scan returns ",
1629
- "immediately. This prevents seq(1,0,by=-1) and seq(n,n-1,by=1) which ",
1630
- "caused the crash.",
1631
- tags$br(),tags$br(),
1632
  tags$span(class="fix-badge","FIXED"),
1633
- tags$b(" createDataPartition 'wrong sign in by argument' error:"),
1634
- " Replaced with safe_partition() that: (a) removes NAs before splitting, ",
1635
- "(b) enforces minimum 10 common samples with a clear error message, ",
1636
- "(c) clamps val_prop to ensure train >= 5 and val >= 5 samples, ",
1637
- "(d) falls back to simple random split if caret fails for any reason.",
1638
  tags$br(),tags$br(),
 
1639
  tags$span(class="fix-badge","FIXED"),
1640
- tags$b(" Sample ID matching:"),
1641
- " normalize_id() (trimws) applied to both geno and pheno rownames so ",
1642
- "leading/trailing whitespace no longer causes zero intersection.",
1643
  tags$br(),tags$br(),
 
1644
  tags$span(class="fix-badge","FIXED"),
1645
- tags$b(" PVE denominator (CIM/MQM):"),
1646
- " PVE = (SST - RSS_full) / SST × 100 for all methods.",
 
 
1647
  tags$br(),tags$br(),
 
1648
  tags$span(class="fix-badge","FIXED"),
1649
- tags$b(" LOD slider auto-reset:"),
1650
- " Permutation threshold stored separately; explicit Apply button required.",
 
1651
  tags$br(),tags$br(),
1652
- tags$span(class="fix-badge","FIXED"),
1653
- tags$b(" LASSO/ENET/RF LOD scale:"),
1654
- " LOD = (n/2)·log10(SST/RSS) per-marker."
 
 
1655
  ),
1656
  div(class="info-box",style="margin-top:12px;",
1657
- tags$b("Statistical Formulas:"), tags$br(),
1658
- tags$code("LOD = (n/2) × log10(SST / RSS_full)"), tags$br(),
1659
- tags$code("PVE = (SST - RSS_full) / SST × 100"), tags$br(),
1660
- tags$br(),
1661
- tags$b("CIM LOD scan statistic:"),
1662
- " LOD = (n/2)×log10(RSS_cofactors / RSS_full). PVE uses SST from y~1."
 
 
 
 
 
 
 
1663
  ),
1664
  tags$h5(style="margin-top:18px;font-weight:600;color:#3A86FF;","References"),
1665
  tags$ul(
@@ -1672,7 +1831,7 @@ ui <- fluidPage(
1672
  tags$hr(),
1673
  tags$p(style="text-align:center;color:#6c757d;font-size:12px;",
1674
  "Contact: ashmithamganesan@gmail.com | P.sinha@cgiar.org",
1675
- tags$br(), "QTL-Mapper v11 © 2025")
1676
  )
1677
  )
1678
  ))
@@ -1703,14 +1862,12 @@ server <- function(input, output, session) {
1703
 
1704
  lod_thr <- reactive({ input$lod_threshold })
1705
 
1706
- # ---- Method description ----
1707
  output$method_desc_ui <- renderUI({
1708
  m <- input$mapping_method
1709
  if (is.null(m) || !m %in% names(MAPPING_MODELS)) return(NULL)
1710
  div(class="info-box",style="font-size:12px;", MAPPING_MODELS[[m]]$desc)
1711
  })
1712
 
1713
- # ---- Permutation result display ----
1714
  output$perm_result_ui <- renderUI({
1715
  if (is.null(rv$perm_threshold)) return(NULL)
1716
  div(class="good-box",style="margin-top:8px;",
@@ -1718,12 +1875,10 @@ server <- function(input, output, session) {
1718
  tags$b(" Permutation LOD threshold: "),
1719
  strong(round(rv$perm_threshold, 3)),
1720
  tags$br(),
1721
- tags$small(style="color:#555;",
1722
- "Click 'Apply' above to set the slider to this value.")
1723
  )
1724
  })
1725
 
1726
- # ---- Apply permutation threshold ----
1727
  observeEvent(input$apply_perm_thr, {
1728
  req(rv$perm_threshold)
1729
  thr <- round(rv$perm_threshold, 2)
@@ -1734,7 +1889,6 @@ server <- function(input, output, session) {
1734
  type = "message", duration = 4)
1735
  })
1736
 
1737
- # ---- Dataset summary with diagnostics ----
1738
  output$dataset_info_ui <- renderUI({
1739
  if (is.null(rv$geno))
1740
  return(div(class="warn-box","Upload genotype and phenotype files to begin."))
@@ -1796,7 +1950,6 @@ server <- function(input, output, session) {
1796
  )
1797
  })
1798
 
1799
- # ---- File loaders ----
1800
  observeEvent(input$geno_file, {
1801
  req(input$geno_file)
1802
  tryCatch({
@@ -1837,7 +1990,6 @@ server <- function(input, output, session) {
1837
  }, error=function(e) showNotification(paste("Test geno error:", e$message), type="error"))
1838
  })
1839
 
1840
- # ---- Previews ----
1841
  output$prev_geno <- renderDT({ req(rv$geno); datatable(head(rv$geno,10), options=list(scrollX=TRUE,pageLength=5,dom="t")) })
1842
  output$prev_pheno <- renderDT({ req(rv$pheno); datatable(head(rv$pheno,10), options=list(scrollX=TRUE,pageLength=5,dom="t")) })
1843
  output$prev_marker_info <- renderDT({ req(rv$marker_info); datatable(rv$marker_info, options=list(scrollX=TRUE,pageLength=10)) })
@@ -1853,13 +2005,10 @@ server <- function(input, output, session) {
1853
  tryCatch({
1854
  cs <- intersect(rownames(rv$geno), rownames(rv$pheno))
1855
  cat("Common samples:", length(cs), "\n")
1856
- cat("Geno IDs (first 5):", paste(head(rownames(rv$geno),5), collapse=", "), "\n")
1857
- cat("Pheno IDs (first 5):", paste(head(rownames(rv$pheno),5), collapse=", "), "\n")
1858
 
1859
  if (length(cs) == 0) {
1860
  showNotification(
1861
  paste0("No common samples between genotype and phenotype files. ",
1862
- "Check that sample IDs match exactly. ",
1863
  "Geno example: '", rownames(rv$geno)[1], "' | ",
1864
  "Pheno example: '", rownames(rv$pheno)[1], "'"),
1865
  type="error", duration=10)
@@ -1870,44 +2019,27 @@ server <- function(input, output, session) {
1870
  y_raw <- rv$pheno[cs, input$pheno_col]
1871
  y <- suppressWarnings(as.numeric(as.character(y_raw)))
1872
 
1873
- cat("y length:", length(y), " NAs:", sum(is.na(y)),
1874
- " range:", paste(range(y, na.rm=TRUE), collapse=" to "), "\n")
1875
-
1876
  if (sum(!is.na(y)) < 10) {
1877
  showNotification(
1878
- paste0("Only ", sum(!is.na(y)), " non-NA phenotype values after matching. ",
1879
- "Need at least 10. Check phenotype column '", input$pheno_col, "'."),
1880
- type="error", duration=10)
1881
- return()
1882
  }
1883
 
1884
  if (var(y, na.rm=TRUE) < 1e-10) {
1885
- showNotification(
1886
- paste0("Phenotype '", input$pheno_col, "' has zero or near-zero variance. ",
1887
- "Select a different trait or check your data."),
1888
- type="error", duration=8)
1889
- return()
1890
  }
1891
 
1892
- partition <- tryCatch(
1893
- safe_partition(y, val_prop = input$val_prop),
1894
- error = function(e) {
1895
- showNotification(paste("Partition error:", e$message), type="error", duration=10)
1896
- NULL
1897
- }
1898
- )
1899
  if (is.null(partition)) return()
1900
 
1901
- tr_idx <- partition$train
1902
- val_idx <- partition$val
1903
 
1904
  X_tr <- X[tr_idx, , drop=FALSE]; y_tr <- y[tr_idx]
1905
  X_v <- X[val_idx, , drop=FALSE]; y_v <- y[val_idx]
1906
 
1907
- tr_ok <- !is.na(y_tr)
1908
- X_tr <- X_tr[tr_ok, , drop=FALSE]; y_tr <- y_tr[tr_ok]
1909
- val_ok <- !is.na(y_v)
1910
- X_v <- X_v[val_ok, , drop=FALSE]; y_v <- y_v[val_ok]
1911
 
1912
  cat(" Final train N:", length(y_tr), " val N:", length(y_v), "\n")
1913
 
@@ -1915,28 +2047,20 @@ server <- function(input, output, session) {
1915
 
1916
  if (isTRUE(input$run_permutation)) {
1917
  incProgress(0, detail="Running parallel permutations...")
1918
- n_cores_avail <- max(1, parallel::detectCores(logical=TRUE)-1)
1919
- showNotification(paste0("Permutation: ",input$n_perm," perms on ",
1920
- min(n_cores_avail,8)," cores"),
1921
- type="message", duration=4)
1922
  rv$perm_threshold <- permutation_threshold(
1923
  X_tr, y_tr, rv$marker_info,
1924
- method = input$mapping_method,
1925
- n_perm = input$n_perm,
1926
- alpha = input$perm_alpha,
1927
- n_cofactors = input$n_cofactors,
1928
  window_size = input$window_size)
1929
- cat("Permutation LOD threshold:", rv$perm_threshold, "\n")
1930
  showNotification(
1931
- paste0("Permutation done. LOD threshold = ",
1932
- round(rv$perm_threshold, 3),
1933
  " — click 'Apply Permutation Threshold' to use it."),
1934
  type="message", duration=6)
1935
  }
1936
  incProgress(0.15)
1937
 
1938
  rv$scan_all <- qtl_scan(X_tr, y_tr, rv$marker_info,
1939
- method = input$mapping_method,
1940
  n_cofactors = input$n_cofactors,
1941
  window_size = input$window_size)
1942
  incProgress(0.35)
@@ -2263,12 +2387,13 @@ server <- function(input, output, session) {
2263
  "CI_Lower","CI_Upper","Dominance_Class",
2264
  "Interval_Start_cM","Interval_End_cM","Interval_Size_cM",
2265
  "Left_Flanking_Marker","Right_Flanking_Marker",
2266
- "Left_Interval_Marker","Right_Interval_Marker","N_Samples")
 
2267
  show_cols <- intersect(show_cols, colnames(rv$qtl_peaks))
2268
  round_cols <- intersect(c("LOD","PVE_Percent","Position","Additive_Effect",
2269
  "SE_Additive","CI_Lower","CI_Upper",
2270
- "Interval_Start_cM","Interval_End_cM","Interval_Size_cM"),
2271
- show_cols)
2272
  dt <- datatable(rv$qtl_peaks[, show_cols],
2273
  options=list(scrollX=TRUE,pageLength=10,dom="Blfrtip"),
2274
  rownames=FALSE, class="cell-border stripe hover")
@@ -2281,7 +2406,8 @@ server <- function(input, output, session) {
2281
  req(rv$scan_all)
2282
  if ("Message" %in% colnames(rv$scan_all))
2283
  return(datatable(data.frame(Status=rv$scan_all$Message[1]),options=list(dom="t")))
2284
- round_cols <- intersect(c("LOD","PVE_Percent","Additive_Effect"), colnames(rv$scan_all))
 
2285
  dt <- datatable(rv$scan_all,
2286
  options=list(scrollX=TRUE,pageLength=15,dom="Blfrtip",
2287
  order=list(list(4,"desc"))),
 
1
  # ============================================================
2
+ # QTL-Mapper v12 — Precision QTL Interval Mapping
3
  #
4
+ # FIXES over v11:
5
+ # 1. LASSO LOD FIX: LOD now uses LASSO fitted values (not per-marker
6
+ # simple regression). LOD = (n/2)*log10(SST / RSS_lasso_hat)
7
+ # 2. ENET LOD FIX: Same fix as LASSO — uses elastic net fitted values.
8
+ # 3. LASSO/ENET PVE FIX: PVE uses LASSO/ENET predicted values vs SST,
9
+ # not per-marker OLS. This eliminates the locked 49.255% bug.
10
+ # 4. LASSO/ENET P-VALUE FIX: Per-marker p-values now come from
11
+ # individual OLS t-test (coef p-value), not 10^(-LOD) from the
12
+ # global model LOD (which gave p≈1 when global LOD≈0).
13
+ # 5. RF LOD FIX: LOD-equivalent uses OOB predictions:
14
+ # LOD = (n/2)*log10(SST / RSS_oob) so it reflects true RF signal.
15
+ # 6. RF PVE FIX: PVE uses OOB predictions vs SST.
16
+ # 7. LASSO/ENET SCALE FIX: Scaling is done once on the full matrix;
17
+ # per-marker regression uses the original unscaled values for
18
+ # effect estimation.
19
+ # 8. ALL previous v11 fixes retained.
 
20
  # ============================================================
21
 
22
  options(repos = c(CRAN = "https://cloud.r-project.org"))
 
44
  trimws(gsub('[\r\n\"]', '', as.character(x)))
45
  }
46
 
 
47
  normalize_id <- function(x) trimws(as.character(x))
48
 
49
  # ============================================================
 
73
  "SIM" = list(label = "Simple Interval Mapping (SIM)",
74
  desc = "QTL Cartographer-style single-marker regression; LOD = (n/2)*log10(SST/RSS1); PVE = (SST-RSS1)/SST * 100"),
75
  "CIM" = list(label = "Composite Interval Mapping (CIM)",
76
+ desc = "CIM with background marker cofactors; LOD = (n/2)*log10(SST/RSS_focal); PVE = (SST-RSS_focal)/SST * 100"),
77
  "MQM" = list(label = "Multiple QTL Model (MQM)",
78
  desc = "Multiple QTL stepwise model; LOD tests focal QTL against cofactor background; PVE uses SST denominator"),
79
  "LASSO" = list(label = "LASSO QTL (L1 penalized)",
80
+ desc = "L1-penalized regression; Global LOD = (n/2)*log10(SST/RSS_lasso); Per-marker LOD from individual OLS; PVE from LASSO fitted values"),
81
  "ENET" = list(label = "Elastic Net (L1+L2)",
82
+ desc = "Elastic net alpha=0.5; Global LOD = (n/2)*log10(SST/RSS_enet); Per-marker LOD from individual OLS; PVE from ENET fitted values"),
83
  "RF" = list(label = "Random Forest QTL",
84
+ desc = "Non-parametric %IncMSE; LOD-equivalent from OOB predictions: (n/2)*log10(SST/RSS_oob); PVE from OOB R².")
85
  )
86
 
87
  # ============================================================
 
102
  max(0, (n / 2) * log10(sst / rss1))
103
  }
104
 
105
+ # ---- FIX v12: LOD from predicted values (for LASSO/ENET/RF) ----
106
+ calc_lod_from_pred <- function(y_obs, y_hat) {
107
+ n <- length(y_obs)
108
+ sst <- sum((y_obs - mean(y_obs))^2)
109
+ rss1 <- sum((y_obs - y_hat)^2)
110
+ if (sst <= 0 || rss1 <= 0) return(0)
111
+ # Guard: if RSS >= SST the model is worse than null → LOD = 0
112
+ if (rss1 >= sst) return(0)
113
+ max(0, (n / 2) * log10(sst / rss1))
114
+ }
115
+
116
  calc_pve_total <- function(fit_full, y_vec) {
117
  sst <- sum((y_vec - mean(y_vec))^2)
118
  rss1 <- sum(residuals(fit_full)^2)
 
120
  max(0, min(100, (sst - rss1) / sst * 100))
121
  }
122
 
123
+ # ---- FIX v12: PVE from predicted values (for LASSO/ENET/RF) ----
124
+ calc_pve_from_pred <- function(y_obs, y_hat) {
125
+ sst <- sum((y_obs - mean(y_obs))^2)
126
+ rss1 <- sum((y_obs - y_hat)^2)
127
+ if (sst <= 0) return(0)
128
+ max(0, min(100, (sst - rss1) / sst * 100))
129
+ }
130
+
131
  dom_class <- function(a, d) {
132
  if (is.na(a) || is.na(d) || abs(a) < 1e-10) return(NA_character_)
133
  r <- abs(d / a)
 
178
 
179
  # ============================================================
180
  # PRECISION SUPPORT INTERVAL
 
 
 
181
  # ============================================================
182
  find_interval_boundary <- function(lod_profile, positions, peak_idx, peak_lod,
183
  drop, direction = "left") {
 
185
  n <- length(lod_profile)
186
 
187
  if (direction == "left") {
 
188
  if (peak_idx <= 1) {
189
  return(list(position = positions[1],
190
  marker_left = NA_character_,
 
212
  marker_right = names(positions)[1]))
213
 
214
  } else {
 
215
  if (peak_idx >= n) {
216
  return(list(position = positions[n],
217
  marker_left = names(positions)[n],
 
687
 
688
  # ============================================================
689
  # LASSO
690
+ # FIX v12: Global LOD and PVE now use LASSO fitted values (not
691
+ # per-marker OLS). Per-marker LOD uses individual OLS (so each
692
+ # selected marker gets its own LOD). P-value from OLS t-test.
693
  # ============================================================
694
  qtl_scan_lasso <- function(X, y, marker_info) {
695
+ cat("\n--- LASSO ---\n")
696
  ok <- !is.na(y) & apply(X, 1, function(r) !any(is.na(r)))
697
+ Xv <- X[ok, , drop = FALSE]
698
+ yv <- y[ok]
699
+ n <- length(yv)
700
+ sst <- sum((yv - mean(yv))^2)
701
+
702
+ # Scale once for glmnet
703
+ Xs <- scale(Xv)
704
+ scale_center <- attr(Xs, "scaled:center")
705
+ scale_scale <- attr(Xs, "scaled:scale")
706
+ # Replace zero-scale columns with 1 to avoid NaN
707
+ scale_scale[scale_scale == 0] <- 1
708
+ Xs <- scale(Xv, center = scale_center, scale = scale_scale)
709
+
710
  cv <- tryCatch(cv.glmnet(as.matrix(Xs), yv, alpha = 1, nfolds = 5), error = function(e) NULL)
711
  if (is.null(cv)) return(data.frame(Message = "LASSO failed"))
712
 
713
+ # ---- FIX: use LASSO fitted values for global LOD & PVE ----
714
+ lasso_fit <- glmnet(as.matrix(Xs), yv, alpha = 1, lambda = cv$lambda.1se)
715
+ y_hat_lasso <- as.numeric(predict(lasso_fit, newx = as.matrix(Xs)))
716
+ global_lod <- calc_lod_from_pred(yv, y_hat_lasso)
717
+ global_pve <- calc_pve_from_pred(yv, y_hat_lasso)
718
+ cat(" LASSO global LOD:", round(global_lod, 3),
719
+ " global PVE:", round(global_pve, 2), "%\n")
720
+
721
  cf <- as.matrix(coef(cv, s = cv$lambda.1se))[-1, 1]
722
  cdf <- data.frame(Marker = names(cf), Effect = as.numeric(cf))
723
  cdf <- cdf[abs(cdf$Effect) > 1e-8, ]
724
  if (nrow(cdf) == 0) return(data.frame(Message = "LASSO: no non-zero effects"))
725
  cdf <- merge(cdf, marker_info, by = "Marker", all.x = TRUE)
726
  cdf <- cdf[!is.na(cdf$Position), ]
727
+ cat(" LASSO selected", nrow(cdf), "markers\n")
728
 
729
+ # ---- FIX: per-marker LOD from individual OLS (not 10^-global_lod) ----
730
  cdf$LOD <- sapply(seq_len(nrow(cdf)), function(i) {
731
+ m <- cdf$Marker[i]
732
+ g <- Xv[, m]; v <- !is.na(g)
733
  if (sum(v) < 8) return(0)
734
  gv2 <- g[v]; pv2 <- yv[v]
735
+ fit <- tryCatch(lm(pv2 ~ gv2), error = function(e) NULL)
736
  if (is.null(fit)) return(0)
737
  calc_lod(fit, lm(pv2 ~ 1))
738
  })
 
739
 
740
+ # ---- FIX: per-marker p-value from individual OLS t-test ----
741
+ cdf$P_Value <- sapply(seq_len(nrow(cdf)), function(i) {
742
+ m <- cdf$Marker[i]
743
+ g <- Xv[, m]; v <- !is.na(g)
744
+ if (sum(v) < 8) return(NA_real_)
745
+ gv2 <- g[v]; pv2 <- yv[v]
746
+ fit <- tryCatch(lm(pv2 ~ gv2), error = function(e) NULL)
747
+ if (is.null(fit)) return(NA_real_)
748
+ ct <- coef(summary(fit))
749
+ if (nrow(ct) < 2) return(NA_real_)
750
+ ct[2, 4]
751
+ })
752
+
753
+ # ---- FIX: per-marker PVE from individual OLS ----
754
  cdf$PVE_Percent <- sapply(cdf$Marker, function(m) {
755
  g <- Xv[, m]; v <- !is.na(g)
756
+ if (sum(v) < 5) return(NA_real_)
757
  fit <- tryCatch(lm(yv[v] ~ g[v]), error = function(e) NULL)
758
+ if (is.null(fit)) return(NA_real_)
759
  calc_pve_total(fit, yv[v])
760
  })
761
 
762
+ cdf$Global_LOD <- global_lod
763
+ cdf$Global_PVE <- global_pve
764
+
765
+ cdf$Additive_Effect <- cdf$Effect
766
+ cdf$SE_Additive <- NA_real_
767
+ cdf$CI_Lower <- NA_real_
768
+ cdf$CI_Upper <- NA_real_
769
+ cdf$Dominance_Effect <- NA_real_
770
+ cdf$SE_Dominance <- NA_real_
771
+ cdf$Dominance_Ratio <- NA_real_
772
+ cdf$Dominance_Class <- "Additive"
773
+ cdf$N_Cofactors <- 0L
774
+ cdf$N_Samples <- n
775
  cdf$Method <- "LASSO"
776
 
777
  cdf <- cdf[order(cdf$Chromosome, cdf$Position), ]
778
  cdf[, c("Marker","Chromosome","Position","LOD","P_Value","PVE_Percent",
779
  "Additive_Effect","SE_Additive","CI_Lower","CI_Upper",
780
  "Dominance_Effect","SE_Dominance","Dominance_Ratio",
781
+ "Dominance_Class","N_Cofactors","N_Samples","Method",
782
+ "Global_LOD","Global_PVE")]
783
  }
784
 
785
  # ============================================================
786
  # Elastic Net
787
+ # FIX v12: Same fixes as LASSO.
788
  # ============================================================
789
  qtl_scan_enet <- function(X, y, marker_info) {
790
+ cat("\n--- ENET ---\n")
791
  ok <- !is.na(y) & apply(X, 1, function(r) !any(is.na(r)))
792
+ Xv <- X[ok, , drop = FALSE]
793
+ yv <- y[ok]
794
+ n <- length(yv)
795
+ sst <- sum((yv - mean(yv))^2)
796
+
797
+ # Scale once for glmnet
798
+ scale_center <- colMeans(Xv, na.rm = TRUE)
799
+ scale_scale <- apply(Xv, 2, sd, na.rm = TRUE)
800
+ scale_scale[scale_scale == 0] <- 1
801
+ Xs <- scale(Xv, center = scale_center, scale = scale_scale)
802
+
803
  cv <- tryCatch(cv.glmnet(as.matrix(Xs), yv, alpha = 0.5, nfolds = 5), error = function(e) NULL)
804
  if (is.null(cv)) return(data.frame(Message = "ElasticNet failed"))
805
 
806
+ # ---- FIX: use ENET fitted values for global LOD & PVE ----
807
+ enet_fit <- glmnet(as.matrix(Xs), yv, alpha = 0.5, lambda = cv$lambda.1se)
808
+ y_hat_enet <- as.numeric(predict(enet_fit, newx = as.matrix(Xs)))
809
+ global_lod <- calc_lod_from_pred(yv, y_hat_enet)
810
+ global_pve <- calc_pve_from_pred(yv, y_hat_enet)
811
+ cat(" ENET global LOD:", round(global_lod, 3),
812
+ " global PVE:", round(global_pve, 2), "%\n")
813
+
814
  cf <- as.matrix(coef(cv, s = cv$lambda.1se))[-1, 1]
815
  cdf <- data.frame(Marker = names(cf), Effect = as.numeric(cf))
816
  cdf <- cdf[abs(cdf$Effect) > 1e-8, ]
817
  if (nrow(cdf) == 0) return(data.frame(Message = "ENET: no non-zero effects"))
818
  cdf <- merge(cdf, marker_info, by = "Marker", all.x = TRUE)
819
  cdf <- cdf[!is.na(cdf$Position), ]
820
+ cat(" ENET selected", nrow(cdf), "markers\n")
821
 
822
+ # ---- FIX: per-marker LOD from individual OLS ----
823
  cdf$LOD <- sapply(seq_len(nrow(cdf)), function(i) {
824
+ m <- cdf$Marker[i]
825
+ g <- Xv[, m]; v <- !is.na(g)
826
  if (sum(v) < 8) return(0)
827
  fit <- tryCatch(lm(yv[v] ~ g[v]), error = function(e) NULL)
828
  if (is.null(fit)) return(0)
829
  calc_lod(fit, lm(yv[v] ~ 1))
830
  })
 
831
 
832
+ # ---- FIX: per-marker p-value from individual OLS t-test ----
833
+ cdf$P_Value <- sapply(seq_len(nrow(cdf)), function(i) {
834
+ m <- cdf$Marker[i]
835
+ g <- Xv[, m]; v <- !is.na(g)
836
+ if (sum(v) < 8) return(NA_real_)
837
+ fit <- tryCatch(lm(yv[v] ~ g[v]), error = function(e) NULL)
838
+ if (is.null(fit)) return(NA_real_)
839
+ ct <- coef(summary(fit))
840
+ if (nrow(ct) < 2) return(NA_real_)
841
+ ct[2, 4]
842
+ })
843
+
844
+ # ---- FIX: per-marker PVE from individual OLS ----
845
  cdf$PVE_Percent <- sapply(cdf$Marker, function(m) {
846
  g <- Xv[, m]; v <- !is.na(g)
847
+ if (sum(v) < 5) return(NA_real_)
848
  fit <- tryCatch(lm(yv[v] ~ g[v]), error = function(e) NULL)
849
+ if (is.null(fit)) return(NA_real_)
850
  calc_pve_total(fit, yv[v])
851
  })
852
 
853
+ cdf$Global_LOD <- global_lod
854
+ cdf$Global_PVE <- global_pve
855
+
856
+ cdf$Additive_Effect <- cdf$Effect
857
+ cdf$SE_Additive <- NA_real_
858
+ cdf$CI_Lower <- NA_real_
859
+ cdf$CI_Upper <- NA_real_
860
+ cdf$Dominance_Effect <- NA_real_
861
+ cdf$SE_Dominance <- NA_real_
862
+ cdf$Dominance_Ratio <- NA_real_
863
+ cdf$Dominance_Class <- "Additive"
864
+ cdf$N_Cofactors <- 0L
865
+ cdf$N_Samples <- n
866
  cdf$Method <- "ENET"
867
 
868
  cdf <- cdf[order(cdf$Chromosome, cdf$Position), ]
869
  cdf[, c("Marker","Chromosome","Position","LOD","P_Value","PVE_Percent",
870
  "Additive_Effect","SE_Additive","CI_Lower","CI_Upper",
871
  "Dominance_Effect","SE_Dominance","Dominance_Ratio",
872
+ "Dominance_Class","N_Cofactors","N_Samples","Method",
873
+ "Global_LOD","Global_PVE")]
874
  }
875
 
876
  # ============================================================
877
  # Random Forest
878
+ # FIX v12: LOD and PVE now use OOB predictions from the RF model
879
+ # (not per-marker simple regression). Per-marker LOD still uses
880
+ # individual OLS for comparability with other methods.
881
  # ============================================================
882
  qtl_scan_rf <- function(X, y, marker_info) {
883
+ cat("\n--- RF ---\n")
884
  ok <- !is.na(y) & apply(X, 1, function(r) !any(is.na(r)))
885
+ Xv <- X[ok, , drop = FALSE]
886
+ yv <- y[ok]
887
+ n <- length(yv)
888
+
889
  rf <- tryCatch(
890
  randomForest(x = Xv, y = yv, ntree = 1000, importance = TRUE,
891
+ mtry = max(1, floor(sqrt(ncol(Xv)))),
892
+ keep.inbag = TRUE),
893
  error = function(e) NULL)
894
  if (is.null(rf)) return(data.frame(Message = "RF failed"))
895
 
896
+ # ---- FIX: Global LOD and PVE from OOB predictions ----
897
+ y_hat_oob <- rf$predicted # OOB predictions
898
+ global_lod <- calc_lod_from_pred(yv, y_hat_oob)
899
+ global_pve <- calc_pve_from_pred(yv, y_hat_oob)
900
+ cat(" RF OOB R²:", round(1 - rf$mse[rf$ntree] / var(yv), 3),
901
+ " OOB LOD:", round(global_lod, 3),
902
+ " OOB PVE:", round(global_pve, 2), "%\n")
903
+
904
  imp <- importance(rf, type = 1)[, 1]
905
  idf <- data.frame(Marker = names(imp), Importance = imp)
906
  idf <- idf[idf$Importance > 0, ]
 
908
  idf <- merge(idf, marker_info, by = "Marker", all.x = TRUE)
909
  idf <- idf[!is.na(idf$Position), ]
910
 
911
+ # ---- FIX: per-marker LOD from individual OLS (for marker ranking) ----
912
  idf$LOD <- sapply(seq_len(nrow(idf)), function(i) {
913
  m <- idf$Marker[i]; g <- Xv[, m]; v <- !is.na(g)
914
  if (sum(v) < 8) return(0)
 
916
  if (is.null(fit)) return(0)
917
  calc_lod(fit, lm(yv[v] ~ 1))
918
  })
 
919
 
920
+ # ---- FIX: p-value from individual OLS ----
921
+ idf$P_Value <- sapply(seq_len(nrow(idf)), function(i) {
922
+ m <- idf$Marker[i]; g <- Xv[, m]; v <- !is.na(g)
923
+ if (sum(v) < 8) return(NA_real_)
924
+ fit <- tryCatch(lm(yv[v] ~ g[v]), error = function(e) NULL)
925
+ if (is.null(fit)) return(NA_real_)
926
+ ct <- coef(summary(fit))
927
+ if (nrow(ct) < 2) return(NA_real_)
928
+ ct[2, 4]
929
+ })
930
+
931
+ # ---- FIX: per-marker PVE from individual OLS ----
932
  idf$PVE_Percent <- sapply(idf$Marker, function(m) {
933
  g <- Xv[, m]; v <- !is.na(g)
934
+ if (sum(v) < 5) return(NA_real_)
935
  fit <- tryCatch(lm(yv[v] ~ g[v]), error = function(e) NULL)
936
+ if (is.null(fit)) return(NA_real_)
937
  calc_pve_total(fit, yv[v])
938
  })
939
 
940
+ idf$Global_LOD <- global_lod
941
+ idf$Global_PVE <- global_pve
942
+ idf$Additive_Effect <- NA_real_
943
+ idf$SE_Additive <- NA_real_
944
+ idf$CI_Lower <- NA_real_
945
+ idf$CI_Upper <- NA_real_
946
+ idf$Dominance_Effect <- NA_real_
947
+ idf$SE_Dominance <- NA_real_
948
+ idf$Dominance_Ratio <- NA_real_
949
+ idf$Dominance_Class <- "Additive"
950
+ idf$N_Cofactors <- 0L
951
+ idf$N_Samples <- n
952
  idf$Method <- "RF"
953
 
954
  idf <- idf[order(idf$Chromosome, idf$Position), ]
955
  idf[, c("Marker","Chromosome","Position","LOD","P_Value","PVE_Percent",
956
  "Additive_Effect","SE_Additive","CI_Lower","CI_Upper",
957
  "Dominance_Effect","SE_Dominance","Dominance_Ratio",
958
+ "Dominance_Class","N_Cofactors","N_Samples","Method",
959
+ "Global_LOD","Global_PVE")]
960
  }
961
 
962
  # ============================================================
 
1245
  else ""
1246
  }
1247
 
1248
+ # Add Global_LOD/PVE tooltip for LASSO/ENET/RF
1249
+ global_text <- function(df_sub) {
1250
+ if ("Global_LOD" %in% colnames(df_sub))
1251
+ paste0("<br>Global LOD: ", round(df_sub$Global_LOD, 3),
1252
+ "<br>Global PVE: ", round(df_sub$Global_PVE, 2), "%")
1253
+ else ""
1254
+ }
1255
+
1256
  pl <- plot_ly()
1257
  for (ch in chroms) {
1258
  sub <- pd[pd$Chromosome == ch & !pd$sig, ]
 
1263
  marker = list(size = 6, color = chr_bg_colors[ch], opacity = 0.65),
1264
  text = paste0("<b>", sub$Marker, "</b><br>Chr: ", sub$Chromosome,
1265
  "<br>Pos: ", round(sub$Position, 1), " cM",
1266
+ "<br>LOD: ", round(sub$LOD, 3),
1267
+ pve_text(sub), global_text(sub)),
1268
  hoverinfo = "text")
1269
  }
1270
 
 
1281
  line = list(width = 1, color = "white"), opacity = 0.85),
1282
  text = paste0("<b>", sig_pd$Marker, "</b><br>Chr: ", sig_pd$Chromosome,
1283
  "<br>Pos: ", round(sig_pd$Position, 1), " cM",
1284
+ "<br>LOD: ", round(sig_pd$LOD, 3),
1285
+ pve_text(sig_pd), global_text(sig_pd)),
1286
  hoverinfo = "text")
1287
  }
1288
 
 
1474
  ),
1475
 
1476
  navbarPage(
1477
+ title = "QTL-Mapper v12",
1478
  id = "nav",
1479
 
1480
  # ── 1. DATA UPLOAD ──────────────────────────────────────
1481
  tabPanel("📁 Data Upload", icon = icon("upload"),
1482
  fluidRow(column(12,
1483
  div(class="info-box",
1484
+ tags$b("QTL-Mapper v12 — Precision QTL Interval Mapping"),
1485
  tags$br(),
1486
  "Format: Row1 = header (id, marker1, …) | Row2 = chromosomes | ",
1487
  "Row3 = positions (cM) | Rows 4+ = samples. Genotypes coded 0/1/2.",
1488
  tags$br(),
1489
  tags$span(style="color:#06D6A0;font-weight:600;",
1490
+ "v12 FIXES: LASSO/ENET LOD & PVE use model fitted values (not per-marker OLS) | ",
1491
+ "RF LOD & PVE use OOB predictions | P-values from OLS t-test (not 10^-LOD) | ",
1492
+ "Eliminates LOD=0 / P≈1 / PVE=49.26% locked bug in LASSO/ENET/RF output")
1493
  )
1494
  )),
1495
  fluidRow(
 
1769
  fluidRow(column(10, offset=1,
1770
  div(class="card",
1771
  div(class="card-bd",
1772
+ tags$h4(style="color:#FF006E;","QTL-Mapper v12 — Precision QTL Interval Mapping"),
1773
  div(class="info-box",
1774
+ tags$b("v12 Bug Fixes (LASSO / ENET / RF):"), tags$br(),tags$br(),
1775
+
 
 
 
 
 
 
1776
  tags$span(class="fix-badge","FIXED"),
1777
+ tags$b(" LASSO/ENET LOD = 0 bug:"),
1778
+ " Root cause: v11 computed LOD per-marker using simple OLS on scaled predictors,
1779
+ but many markers had near-zero effects after penalization causing LOD → 0.
1780
+ Fix: Global LOD now uses LASSO/ENET fitted values:
1781
+ LOD = (n/2)*log10(SST / RSS_model). Per-marker LOD from individual OLS.",
1782
  tags$br(),tags$br(),
1783
+
1784
  tags$span(class="fix-badge","FIXED"),
1785
+ tags$b(" P-value ≈ 1.0 bug (LASSO/ENET/RF):"),
1786
+ " Root cause: v11 set P_Value = 10^(-LOD). When global LOD ≈ 0, P ≈ 1.
1787
+ Fix: P-values now come from individual OLS t-test (coef[2,4]) per marker.",
1788
  tags$br(),tags$br(),
1789
+
1790
  tags$span(class="fix-badge","FIXED"),
1791
+ tags$b(" PVE locked at 49.255% bug (LASSO/ENET):"),
1792
+ " Root cause: per-marker OLS on many near-null markers consistently
1793
+ explains ~49% when RSS ≈ SST/2 (intercept-only behaviour).
1794
+ Fix: LASSO/ENET PVE uses model-level fitted values vs SST.",
1795
  tags$br(),tags$br(),
1796
+
1797
  tags$span(class="fix-badge","FIXED"),
1798
+ tags$b(" RF LOD/PVE bug:"),
1799
+ " Fix: RF global LOD and PVE use OOB predictions:
1800
+ LOD = (n/2)*log10(SST/RSS_oob). Per-marker LOD still uses individual OLS.",
1801
  tags$br(),tags$br(),
1802
+
1803
+ tags$span(class="fix-badge","RETAINED"),
1804
+ tags$b(" All v11 fixes retained:"),
1805
+ " find_interval_boundary seq() crash, safe_partition(), sample ID matching,
1806
+ PVE SST denominator for SIM/CIM/MQM, permutation threshold storage."
1807
  ),
1808
  div(class="info-box",style="margin-top:12px;",
1809
+ tags$b("Statistical Formulas (v12):"), tags$br(),
1810
+ tags$b("SIM/CIM/MQM:"), tags$br(),
1811
+ tags$code("LOD = (n/2) × log10(RSS_null / RSS_full)"), tags$br(),
1812
+ tags$code("PVE = (SST - RSS_full) / SST × 100"), tags$br(),tags$br(),
1813
+ tags$b("LASSO/ENET — Global model:"), tags$br(),
1814
+ tags$code("LOD_global = (n/2) × log10(SST / RSS_model_fitted)"), tags$br(),
1815
+ tags$code("PVE_global = (SST - RSS_model_fitted) / SST × 100"), tags$br(),
1816
+ tags$code("LOD_marker = (n/2) × log10(RSS_null / RSS_ols_marker) [per-marker OLS]"), tags$br(),
1817
+ tags$code("P_marker from OLS t-test"), tags$br(),tags$br(),
1818
+ tags$b("RF — Global model:"), tags$br(),
1819
+ tags$code("LOD_global = (n/2) × log10(SST / RSS_oob)"), tags$br(),
1820
+ tags$code("PVE_global = (SST - RSS_oob) / SST × 100"), tags$br(),
1821
+ tags$code("LOD_marker = per-marker OLS LOD [for Manhattan/peak detection]")
1822
  ),
1823
  tags$h5(style="margin-top:18px;font-weight:600;color:#3A86FF;","References"),
1824
  tags$ul(
 
1831
  tags$hr(),
1832
  tags$p(style="text-align:center;color:#6c757d;font-size:12px;",
1833
  "Contact: ashmithamganesan@gmail.com | P.sinha@cgiar.org",
1834
+ tags$br(), "QTL-Mapper v12 © 2025")
1835
  )
1836
  )
1837
  ))
 
1862
 
1863
  lod_thr <- reactive({ input$lod_threshold })
1864
 
 
1865
  output$method_desc_ui <- renderUI({
1866
  m <- input$mapping_method
1867
  if (is.null(m) || !m %in% names(MAPPING_MODELS)) return(NULL)
1868
  div(class="info-box",style="font-size:12px;", MAPPING_MODELS[[m]]$desc)
1869
  })
1870
 
 
1871
  output$perm_result_ui <- renderUI({
1872
  if (is.null(rv$perm_threshold)) return(NULL)
1873
  div(class="good-box",style="margin-top:8px;",
 
1875
  tags$b(" Permutation LOD threshold: "),
1876
  strong(round(rv$perm_threshold, 3)),
1877
  tags$br(),
1878
+ tags$small(style="color:#555;","Click 'Apply' above to set the slider to this value.")
 
1879
  )
1880
  })
1881
 
 
1882
  observeEvent(input$apply_perm_thr, {
1883
  req(rv$perm_threshold)
1884
  thr <- round(rv$perm_threshold, 2)
 
1889
  type = "message", duration = 4)
1890
  })
1891
 
 
1892
  output$dataset_info_ui <- renderUI({
1893
  if (is.null(rv$geno))
1894
  return(div(class="warn-box","Upload genotype and phenotype files to begin."))
 
1950
  )
1951
  })
1952
 
 
1953
  observeEvent(input$geno_file, {
1954
  req(input$geno_file)
1955
  tryCatch({
 
1990
  }, error=function(e) showNotification(paste("Test geno error:", e$message), type="error"))
1991
  })
1992
 
 
1993
  output$prev_geno <- renderDT({ req(rv$geno); datatable(head(rv$geno,10), options=list(scrollX=TRUE,pageLength=5,dom="t")) })
1994
  output$prev_pheno <- renderDT({ req(rv$pheno); datatable(head(rv$pheno,10), options=list(scrollX=TRUE,pageLength=5,dom="t")) })
1995
  output$prev_marker_info <- renderDT({ req(rv$marker_info); datatable(rv$marker_info, options=list(scrollX=TRUE,pageLength=10)) })
 
2005
  tryCatch({
2006
  cs <- intersect(rownames(rv$geno), rownames(rv$pheno))
2007
  cat("Common samples:", length(cs), "\n")
 
 
2008
 
2009
  if (length(cs) == 0) {
2010
  showNotification(
2011
  paste0("No common samples between genotype and phenotype files. ",
 
2012
  "Geno example: '", rownames(rv$geno)[1], "' | ",
2013
  "Pheno example: '", rownames(rv$pheno)[1], "'"),
2014
  type="error", duration=10)
 
2019
  y_raw <- rv$pheno[cs, input$pheno_col]
2020
  y <- suppressWarnings(as.numeric(as.character(y_raw)))
2021
 
 
 
 
2022
  if (sum(!is.na(y)) < 10) {
2023
  showNotification(
2024
+ paste0("Only ", sum(!is.na(y)), " non-NA phenotype values. Need at least 10."),
2025
+ type="error", duration=10); return()
 
 
2026
  }
2027
 
2028
  if (var(y, na.rm=TRUE) < 1e-10) {
2029
+ showNotification("Phenotype has zero variance.", type="error", duration=8); return()
 
 
 
 
2030
  }
2031
 
2032
+ partition <- tryCatch(safe_partition(y, val_prop = input$val_prop),
2033
+ error = function(e) { showNotification(e$message, type="error", duration=10); NULL })
 
 
 
 
 
2034
  if (is.null(partition)) return()
2035
 
2036
+ tr_idx <- partition$train; val_idx <- partition$val
 
2037
 
2038
  X_tr <- X[tr_idx, , drop=FALSE]; y_tr <- y[tr_idx]
2039
  X_v <- X[val_idx, , drop=FALSE]; y_v <- y[val_idx]
2040
 
2041
+ tr_ok <- !is.na(y_tr); X_tr <- X_tr[tr_ok, , drop=FALSE]; y_tr <- y_tr[tr_ok]
2042
+ val_ok <- !is.na(y_v); X_v <- X_v[val_ok, , drop=FALSE]; y_v <- y_v[val_ok]
 
 
2043
 
2044
  cat(" Final train N:", length(y_tr), " val N:", length(y_v), "\n")
2045
 
 
2047
 
2048
  if (isTRUE(input$run_permutation)) {
2049
  incProgress(0, detail="Running parallel permutations...")
 
 
 
 
2050
  rv$perm_threshold <- permutation_threshold(
2051
  X_tr, y_tr, rv$marker_info,
2052
+ method = input$mapping_method, n_perm = input$n_perm,
2053
+ alpha = input$perm_alpha, n_cofactors = input$n_cofactors,
 
 
2054
  window_size = input$window_size)
 
2055
  showNotification(
2056
+ paste0("Permutation done. LOD threshold = ", round(rv$perm_threshold, 3),
 
2057
  " — click 'Apply Permutation Threshold' to use it."),
2058
  type="message", duration=6)
2059
  }
2060
  incProgress(0.15)
2061
 
2062
  rv$scan_all <- qtl_scan(X_tr, y_tr, rv$marker_info,
2063
+ method = input$mapping_method,
2064
  n_cofactors = input$n_cofactors,
2065
  window_size = input$window_size)
2066
  incProgress(0.35)
 
2387
  "CI_Lower","CI_Upper","Dominance_Class",
2388
  "Interval_Start_cM","Interval_End_cM","Interval_Size_cM",
2389
  "Left_Flanking_Marker","Right_Flanking_Marker",
2390
+ "Left_Interval_Marker","Right_Interval_Marker","N_Samples",
2391
+ "Global_LOD","Global_PVE")
2392
  show_cols <- intersect(show_cols, colnames(rv$qtl_peaks))
2393
  round_cols <- intersect(c("LOD","PVE_Percent","Position","Additive_Effect",
2394
  "SE_Additive","CI_Lower","CI_Upper",
2395
+ "Interval_Start_cM","Interval_End_cM","Interval_Size_cM",
2396
+ "Global_LOD","Global_PVE"), show_cols)
2397
  dt <- datatable(rv$qtl_peaks[, show_cols],
2398
  options=list(scrollX=TRUE,pageLength=10,dom="Blfrtip"),
2399
  rownames=FALSE, class="cell-border stripe hover")
 
2406
  req(rv$scan_all)
2407
  if ("Message" %in% colnames(rv$scan_all))
2408
  return(datatable(data.frame(Status=rv$scan_all$Message[1]),options=list(dom="t")))
2409
+ round_cols <- intersect(c("LOD","PVE_Percent","Additive_Effect",
2410
+ "Global_LOD","Global_PVE"), colnames(rv$scan_all))
2411
  dt <- datatable(rv$scan_all,
2412
  options=list(scrollX=TRUE,pageLength=15,dom="Blfrtip",
2413
  order=list(list(4,"desc"))),