softwareDevelopment commited on
Commit
e789b04
·
verified ·
1 Parent(s): a09c3c1

Update app.R

Browse files
Files changed (1) hide show
  1. app.R +279 -148
app.R CHANGED
@@ -3,28 +3,18 @@
3
  #
4
  # FIXES over v10:
5
  # 1. PVE DENOMINATOR FIX (CIM/MQM): PVE now uses SST = sum((y-mean(y))^2)
6
- # from the intercept-only null, NOT RSS from the cofactor model.
7
- # This gives the correct "proportion of total phenotypic variance
8
- # explained by the QTL" rather than partial variance explained.
9
- # 2. LOD THRESHOLD AFTER PERMUTATION: Permutation result is stored in
10
- # rv$perm_threshold and shown to the user, but the slider is NOT
11
- # automatically reset to that value (which caused snap-to-0.5 bug).
12
- # Instead, a button "Apply Permutation Threshold" lets the user
13
- # explicitly apply it. The effective LOD threshold used in all
14
- # analyses respects both the slider and the permutation value.
15
- # 3. PVE FUNCTION UNIFIED: calc_pve_total() always uses SST from
16
- # intercept-only null regardless of cofactors, so SIM/CIM/MQM
17
- # all report comparable PVE values on the same scale (0-100%).
18
- # 4. CIM/MQM PVE FIX: In CIM and MQM, fit_null was the cofactor model,
19
- # so calc_pve gave partial R². Now passing SST explicitly.
20
- # 5. LASSO/ENET LOD: Changed from arbitrary rescaling to a true
21
- # LOD-equivalent using (n/2)*log10(RSS0/RSS1) via leave-one-out
22
- # approximation so thresholds are on the same scale as SIM/CIM.
23
- # 6. RF IMPORTANCE → LOD: RF importance is still relative, but
24
- # now normalized with a note in the UI that permutation thresholds
25
- # are only strictly valid for regression-based methods.
26
- # 7. MIN LOD SLIDER: min is now 0.1 (not 0.5) so it never clamps
27
- # a legitimate low permutation threshold.
28
  # ============================================================
29
 
30
  options(repos = c(CRAN = "https://cloud.r-project.org"))
@@ -52,6 +42,9 @@ cn <- function(x) {
52
  trimws(gsub('[\r\n\"]', '', as.character(x)))
53
  }
54
 
 
 
 
55
  # ============================================================
56
  # COLOR PALETTES
57
  # ============================================================
@@ -94,8 +87,6 @@ MAPPING_MODELS <- list(
94
  # CORE FUNCTIONS
95
  # ============================================================
96
 
97
- # LOD = (n/2) * log10(RSS0 / RSS1) — QTL Cartographer definition
98
- # Always pass fit_null as the INTERCEPT-ONLY model (y ~ 1) for correct LOD
99
  calc_lod <- function(fit_full, fit_null) {
100
  rss1 <- sum(residuals(fit_full)^2)
101
  rss0 <- sum(residuals(fit_null)^2)
@@ -104,20 +95,12 @@ calc_lod <- function(fit_full, fit_null) {
104
  max(0, (n / 2) * log10(rss0 / rss1))
105
  }
106
 
107
- # LOD using pre-computed SST (avoids re-fitting null)
108
  calc_lod_sst <- function(fit_full, sst, n) {
109
  rss1 <- sum(residuals(fit_full)^2)
110
  if (rss1 <= 0 || sst <= 0) return(0)
111
  max(0, (n / 2) * log10(sst / rss1))
112
  }
113
 
114
- # -----------------------------------------------------------------
115
- # PVE FIX: denominator is ALWAYS SST = sum((y - mean(y))^2)
116
- # This is the TOTAL phenotypic variance before any model adjustment.
117
- # For CIM/MQM the old code used RSS_cofactors as denominator which
118
- # gave partial R² (QTL effect / residual after cofactors), not
119
- # proportion of total variance — corrected here.
120
- # -----------------------------------------------------------------
121
  calc_pve_total <- function(fit_full, y_vec) {
122
  sst <- sum((y_vec - mean(y_vec))^2)
123
  rss1 <- sum(residuals(fit_full)^2)
@@ -135,7 +118,52 @@ dom_class <- function(a, d) {
135
  }
136
 
137
  # ============================================================
138
- # PRECISION SUPPORT INTERVAL (QTL Cartographer style)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
139
  # ============================================================
140
  find_interval_boundary <- function(lod_profile, positions, peak_idx, peak_lod,
141
  drop, direction = "left") {
@@ -153,7 +181,7 @@ find_interval_boundary <- function(lod_profile, positions, peak_idx, peak_lod,
153
  } else {
154
  boundary_pos <- pos1
155
  }
156
- return(list(position = boundary_pos,
157
  marker_left = names(positions)[i-1],
158
  marker_right = names(positions)[i]))
159
  }
@@ -263,9 +291,9 @@ add_precision_support_intervals <- function(peaks_df, full_scan_df, lod_drop = 1
263
  full_scan_df$Chromosome <- as.character(full_scan_df$Chromosome)
264
 
265
  for (i in seq_len(nrow(peaks_df))) {
266
- chr <- as.character(peaks_df$Chromosome[i])
267
- peak_lod <- peaks_df$LOD[i]
268
- peak_pos <- peaks_df$Position[i]
269
  peak_marker <- peaks_df$Marker[i]
270
 
271
  chr_data <- full_scan_df[full_scan_df$Chromosome == chr &
@@ -299,7 +327,6 @@ add_precision_support_intervals <- function(peaks_df, full_scan_df, lod_drop = 1
299
  peaks_df$Right_Interval_Marker[i] <- right_res$marker_left
300
  peaks_df$Interval_Size_cM[i] <- max(0, right_res$position - left_res$position)
301
 
302
- # Flanking markers: immediately outside the interval boundaries
303
  peaks_df$Left_Flanking_Marker[i] <- {
304
  lm <- chr_data$Marker[chr_data$Position < peaks_df$Interval_Start_cM[i]]
305
  if (length(lm) > 0) lm[length(lm)] else NA_character_
@@ -335,7 +362,8 @@ load_genotype_file <- function(filepath) {
335
  if (ncol(gd) > target_n) gd <- gd[, seq_len(target_n)]
336
 
337
  colnames(gd) <- header_row
338
- rownames(gd) <- make.unique(cn(as.character(gd[, 1])))
 
339
  gd <- gd[, -1, drop = FALSE]
340
 
341
  for (col in colnames(gd)) {
@@ -413,10 +441,6 @@ qtl_scan_sim <- function(X, y, marker_info) {
413
  nzv <- apply(X, 2, function(x) length(unique(na.omit(x))) < 2)
414
  X <- X[, !nzv, drop = FALSE]
415
 
416
- # Pre-compute SST once for the whole scan (intercept-only null)
417
- sst_all <- sum((y - mean(y))^2)
418
- n_all <- length(y)
419
-
420
  res_list <- vector("list", ncol(X)); names(res_list) <- colnames(X)
421
  for (m in colnames(X)) {
422
  g <- X[, m]; ok <- !is.na(g); gv <- g[ok]; pv <- y[ok]
@@ -424,13 +448,11 @@ qtl_scan_sim <- function(X, y, marker_info) {
424
  mi <- marker_info[marker_info$Marker == m, ]
425
  if (nrow(mi) == 0 || is.na(mi$Position[1])) next
426
  tryCatch({
427
- # LOD uses intercept-only null → SST denominator ✓
428
  fit_full <- lm(pv ~ gv)
429
  fit_null <- lm(pv ~ 1)
430
- sst_m <- sum((pv - mean(pv))^2)
431
  n_m <- length(pv)
432
- lod <- calc_lod(fit_full, fit_null) # (n/2)*log10(SST/RSS1)
433
- pve <- calc_pve_total(fit_full, pv) # (SST-RSS1)/SST * 100 ✓
434
  pval <- coef(summary(fit_full))[2, 4]
435
  eff <- estimate_effects(gv, pv)
436
  res_list[[m]] <- data.frame(
@@ -460,7 +482,6 @@ qtl_scan_cim <- function(X, y, marker_info, n_cofactors = 10, window_size = 10)
460
  n <- length(y)
461
  max_k <- max(3, min(n_cofactors, floor(sqrt(n))))
462
 
463
- # ---------- Cofactor selection via forward stepwise ----------
464
  cat(" Selecting cofactors...\n")
465
  cofactors <- character(0); remaining <- colnames(X); prev_lod <- 0
466
  for (step in seq_len(max_k)) {
@@ -482,7 +503,6 @@ qtl_scan_cim <- function(X, y, marker_info, n_cofactors = 10, window_size = 10)
482
  }
483
  cat(" Selected", length(cofactors), "cofactors\n")
484
 
485
- # ---------- Genome scan ----------
486
  res_list <- vector("list", ncol(X)); names(res_list) <- colnames(X)
487
  for (m in colnames(X)) {
488
  g <- X[, m]; ok <- !is.na(g); gv <- g[ok]; pv <- y[ok]
@@ -510,27 +530,19 @@ qtl_scan_cim <- function(X, y, marker_info, n_cofactors = 10, window_size = 10)
510
  }
511
  df <- df[complete.cases(df), ]
512
  if (nrow(df) < 8) return(NULL)
513
-
514
- pv_cc <- df$y # complete-case y for SST calculation
515
 
516
  if (length(active_cof) > 0) {
517
- fit_full <- lm(as.formula(paste("y ~ focal +", paste(active_cof, collapse="+"))), data=df)
518
- # LOD: test focal QTL against cofactor background
519
- # We compute LOD = (n/2)*log10(SST / RSS_full) where SST = sum((y-mean(y))^2)
520
- # This gives the QTL effect on the TOTAL scale, not partial residual scale
521
  fit_null_cof <- lm(as.formula(paste("y ~", paste(active_cof, collapse="+"))), data=df)
522
- # Use partial LOD (cofactor null) for the scan statistic as in QTL Cartographer
523
- # but PVE uses SST from intercept-only null for interpretability
524
- lod <- calc_lod(fit_full, fit_null_cof) # QTL LOD above cofactor background
525
  } else {
526
  fit_full <- lm(y ~ focal, data=df)
527
  fit_null_cof <- lm(y ~ 1, data=df)
528
  lod <- calc_lod(fit_full, fit_null_cof)
529
  }
530
 
531
- # PVE: always use SST denominator (TOTAL variance) — KEY FIX
532
  pve <- calc_pve_total(fit_full, pv_cc)
533
-
534
  ct <- coef(summary(fit_full))
535
  if (!"focal" %in% rownames(ct)) next
536
  pval <- ct["focal","Pr(>|t|)"]
@@ -626,9 +638,7 @@ qtl_scan_mqm <- function(X, y, marker_info, n_cofactors = 10, window_size = 10)
626
  lod <- calc_lod(fit_full, fit_null_cof)
627
  }
628
 
629
- # PVE: SST denominator (total variance) — KEY FIX
630
  pve <- calc_pve_total(fit_full, pv_cc)
631
-
632
  ct <- coef(summary(fit_full))
633
  if (!"focal" %in% rownames(ct)) next
634
  pval <- ct["focal","Pr(>|t|)"]
@@ -650,7 +660,7 @@ qtl_scan_mqm <- function(X, y, marker_info, n_cofactors = 10, window_size = 10)
650
  }
651
 
652
  # ============================================================
653
- # LASSO — LOD approximated via (n/2)*log10(SST / RSS_fitted)
654
  # ============================================================
655
  qtl_scan_lasso <- function(X, y, marker_info) {
656
  ok <- !is.na(y) & apply(X, 1, function(r) !any(is.na(r)))
@@ -665,10 +675,6 @@ qtl_scan_lasso <- function(X, y, marker_info) {
665
  cdf <- merge(cdf, marker_info, by = "Marker", all.x = TRUE)
666
  cdf <- cdf[!is.na(cdf$Position), ]
667
 
668
- sst_all <- sum((yv - mean(yv))^2)
669
- n_all <- length(yv)
670
-
671
- # Compute per-marker LOD and PVE using (n/2)*log10(SST/RSS_hat) — comparable to SIM
672
  cdf$LOD <- sapply(seq_len(nrow(cdf)), function(i) {
673
  m <- cdf$Marker[i]
674
  g <- Xv[, m]; v <- !is.na(g)
@@ -676,7 +682,6 @@ qtl_scan_lasso <- function(X, y, marker_info) {
676
  gv2 <- g[v]; pv2 <- yv[v]
677
  fit <- tryCatch(lm(pv2 ~ gv2), error = function(e) NULL)
678
  if (is.null(fit)) return(0)
679
- sst_m <- sum((pv2 - mean(pv2))^2)
680
  calc_lod(fit, lm(pv2 ~ 1))
681
  })
682
  cdf$P_Value <- 10^(-cdf$LOD)
@@ -704,7 +709,7 @@ qtl_scan_lasso <- function(X, y, marker_info) {
704
  }
705
 
706
  # ============================================================
707
- # Elastic Net — same LOD fix as LASSO
708
  # ============================================================
709
  qtl_scan_enet <- function(X, y, marker_info) {
710
  ok <- !is.na(y) & apply(X, 1, function(r) !any(is.na(r)))
@@ -769,7 +774,6 @@ qtl_scan_rf <- function(X, y, marker_info) {
769
  idf <- merge(idf, marker_info, by = "Marker", all.x = TRUE)
770
  idf <- idf[!is.na(idf$Position), ]
771
 
772
- # Scale importance to LOD-like values via per-marker regression
773
  idf$LOD <- sapply(seq_len(nrow(idf)), function(i) {
774
  m <- idf$Marker[i]; g <- Xv[, m]; v <- !is.na(g)
775
  if (sum(v) < 8) return(0)
@@ -855,7 +859,7 @@ permutation_threshold <- function(X, y, marker_info, method = "SIM",
855
  return(0)
856
  }
857
 
858
- seeds <- sample.int(1e6, n_perm)
859
  is_windows <- .Platform$OS.type == "windows"
860
 
861
  if (n_cores > 1) {
@@ -1074,11 +1078,10 @@ make_plotly_manhattan <- function(scan_df, lod_threshold = 2.0, peaks_df = NULL,
1074
  pd$cum_pos <- pd$Position + offsets[pd$Chromosome]
1075
  pd$sig <- pd$LOD >= lod_threshold
1076
 
1077
- chr_mids <- tapply(pd$cum_pos, pd$Chromosome, median, na.rm = TRUE)
1078
  chr_bg_colors <- rep(c("#3A86FF","#FB5607"), length.out = length(chroms))
1079
  names(chr_bg_colors) <- chroms
1080
 
1081
- # Determine PVE column name
1082
  pve_col <- if ("PVE_Percent" %in% colnames(pd)) "PVE_Percent" else
1083
  if ("PVE_Marker_Percent" %in% colnames(pd)) "PVE_Marker_Percent" else NULL
1084
 
@@ -1222,7 +1225,6 @@ make_idiogram_ggplot <- function(qtl_list, all_markers_df, lod_threshold = 2.0)
1222
  for (m in intersect(model_names, names(MODEL_COLORS)))
1223
  model_colors_use[m] <- MODEL_COLORS[m]
1224
 
1225
- # Detect PVE column
1226
  get_pve <- function(df) {
1227
  if ("PVE_Percent" %in% colnames(df)) df$PVE_Percent
1228
  else if ("PVE_Marker_Percent" %in% colnames(df)) df$PVE_Marker_Percent
@@ -1303,6 +1305,7 @@ ui <- fluidPage(
1303
  .perm-info{background:linear-gradient(135deg,#e8f4fd,#f0f8ff);border:1px solid #90caf9;border-left:4px solid #8338EC;border-radius:8px;padding:12px 16px;margin:8px 0;font-size:13px;}
1304
  .speed-badge{background:#8338EC;color:#fff;border-radius:12px;padding:2px 8px;font-size:10px;font-weight:700;letter-spacing:0.5px;}
1305
  .fix-badge{background:#06D6A0;color:#fff;border-radius:12px;padding:2px 8px;font-size:10px;font-weight:700;letter-spacing:0.5px;}
 
1306
  "))
1307
  ),
1308
 
@@ -1320,9 +1323,8 @@ ui <- fluidPage(
1320
  "Row3 = positions (cM) | Rows 4+ = samples. Genotypes coded 0/1/2.",
1321
  tags$br(),
1322
  tags$span(style="color:#06D6A0;font-weight:600;",
1323
- "v11 FIXES: PVE uses SST denominator (total variance) for ALL methods | ",
1324
- "Permutation threshold stored separately — slider never auto-resets | ",
1325
- "LASSO/ENET/RF LOD now computed as (n/2)*log10(SST/RSS) per marker")
1326
  )
1327
  )),
1328
  fluidRow(
@@ -1349,7 +1351,6 @@ ui <- fluidPage(
1349
  selected = "CIM"),
1350
  uiOutput("method_desc_ui"),
1351
 
1352
- # FIX: min = 0.1 so permutation thresholds are never clamped
1353
  sliderInput("lod_threshold","LOD Threshold (manual)",
1354
  min=0.1, max=10, value=2.0, step=0.1),
1355
 
@@ -1367,7 +1368,6 @@ ui <- fluidPage(
1367
  style="margin-top:10px;width:100%;"),
1368
  tags$hr(style="margin:10px 0;"),
1369
 
1370
- # FIX: permutation result shown separately; NOT auto-applied to slider
1371
  checkboxInput("run_permutation","Estimate LOD threshold by permutation",value=FALSE),
1372
  conditionalPanel("input.run_permutation",
1373
  div(class="perm-info",
@@ -1388,7 +1388,7 @@ ui <- fluidPage(
1388
  ),
1389
  column(4,
1390
  div(class="card",
1391
- div(class="card-hd","Dataset Summary"),
1392
  div(class="card-bd",uiOutput("dataset_info_ui"))
1393
  ),
1394
  div(class="card",
@@ -1608,36 +1608,36 @@ ui <- fluidPage(
1608
  div(class="info-box",
1609
  tags$b("v11 Bug Fixes:"), tags$br(),
1610
  tags$span(class="fix-badge","FIXED"),
 
 
 
 
 
 
 
 
 
 
 
 
1611
  tags$b(" PVE denominator (CIM/MQM):"),
1612
- " PVE now always = (SST − RSS_full) / SST × 100, where SST = Σ(y−ȳ)² ",
1613
- "from the intercept-only null. Previously CIM/MQM used RSS_cofactors as ",
1614
- "denominator, giving partial R² (QTL effect / residual after cofactors) — ",
1615
- "now all methods report % of total phenotypic variance explained.", tags$br(),tags$br(),
1616
  tags$span(class="fix-badge","FIXED"),
1617
- tags$b(" LOD slider auto-reset to 0.5 after permutation:"),
1618
- " Permutation threshold is now stored separately in rv$perm_threshold and ",
1619
- "displayed in a box. A dedicated 'Apply' button lets users explicitly push ",
1620
- "the permutation value to the slider. Slider minimum changed from 0.5 → 0.1.", tags$br(),tags$br(),
1621
  tags$span(class="fix-badge","FIXED"),
1622
  tags$b(" LASSO/ENET/RF LOD scale:"),
1623
- " LOD scores now computed as (n/2)·log10(SST/RSS) per-marker using univariate ",
1624
- "regression (same formula as SIM), so permutation thresholds are meaningful for ",
1625
- "all regression-based methods on the same LOD scale.", tags$br(),tags$br(),
1626
- tags$span(class="fix-badge","FIXED"),
1627
- tags$b(" PVE column name:"),
1628
- " Unified as 'PVE_Percent' across all methods and all tables."
1629
  ),
1630
  div(class="info-box",style="margin-top:12px;",
1631
  tags$b("Statistical Formulas:"), tags$br(),
1632
  tags$code("LOD = (n/2) × log10(SST / RSS_full)"), tags$br(),
1633
- "where SST = Σ(y−ȳ)² (total sum of squares from null y ~ 1)", tags$br(),
1634
- tags$br(),
1635
  tags$code("PVE = (SST − RSS_full) / SST × 100"), tags$br(),
1636
- "SST denominator is the SAME for SIM, CIM, and MQM, making PVE values comparable.", tags$br(),
1637
  tags$br(),
1638
  tags$b("CIM LOD scan statistic:"),
1639
- " LOD = (n/2)×log10(RSS_cofactors / RSS_full) — tests focal QTL above cofactor background (QTL Cartographer CIM3 style).", tags$br(),
1640
- "CIM PVE uses SST from y~1 (total variance denominator), NOT RSS_cofactors."
1641
  ),
1642
  tags$h5(style="margin-top:18px;font-weight:600;color:#3A86FF;","References"),
1643
  tags$ul(
@@ -1675,10 +1675,10 @@ server <- function(input, output, session) {
1675
  sel_metrics = NULL,
1676
  compare_res = list(),
1677
  compare_peaks = list(),
1678
- perm_threshold = NULL # stored separately — never auto-pushed to slider
 
1679
  )
1680
 
1681
- # Effective LOD threshold (slider value, unaffected by permutation automatically)
1682
  lod_thr <- reactive({ input$lod_threshold })
1683
 
1684
  # ---- Method description ----
@@ -1701,11 +1701,10 @@ server <- function(input, output, session) {
1701
  )
1702
  })
1703
 
1704
- # ---- Apply permutation threshold to slider (explicit user action) ----
1705
  observeEvent(input$apply_perm_thr, {
1706
  req(rv$perm_threshold)
1707
  thr <- round(rv$perm_threshold, 2)
1708
- # Clamp to slider range [0.1, 10]
1709
  thr <- max(0.1, min(10, thr))
1710
  updateSliderInput(session, "lod_threshold", value = thr)
1711
  showNotification(paste0("LOD threshold set to ", thr,
@@ -1713,15 +1712,46 @@ server <- function(input, output, session) {
1713
  type = "message", duration = 4)
1714
  })
1715
 
1716
- # ---- Dataset summary ----
1717
  output$dataset_info_ui <- renderUI({
1718
  if (is.null(rv$geno))
1719
  return(div(class="warn-box","Upload genotype and phenotype files to begin."))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1720
  tagList(
1721
  fluidRow(
1722
  column(6, div(class="stat-box",
1723
- tags$div(class="stat-value", nrow(rv$geno)),
1724
- tags$div(class="stat-label","Samples"))),
1725
  column(6, div(class="stat-box",
1726
  tags$div(class="stat-value", ncol(rv$geno)),
1727
  tags$div(class="stat-label","Markers")))
@@ -1731,9 +1761,12 @@ server <- function(input, output, session) {
1731
  tags$div(class="stat-value", length(unique(rv$marker_info$Chromosome))),
1732
  tags$div(class="stat-label","Chromosomes"))),
1733
  column(6, div(class="stat-box",
1734
- tags$div(class="stat-value", if (!is.null(rv$pheno)) ncol(rv$pheno) else "—"),
1735
- tags$div(class="stat-label","Traits")))
1736
  ),
 
 
 
1737
  if (!is.null(rv$perm_threshold))
1738
  div(class="perm-info",style="margin-top:8px;",
1739
  tags$span(class="speed-badge","FAST"),
@@ -1758,11 +1791,13 @@ server <- function(input, output, session) {
1758
  req(input$pheno_file)
1759
  tryCatch({
1760
  pd <- read.csv(input$pheno_file$datapath)
1761
- rownames(pd) <- pd[,1]; pd <- pd[,-1,drop=FALSE]
1762
- for (col in colnames(pd)) pd[[col]] <- as.numeric(as.character(pd[[col]]))
 
 
1763
  rv$pheno <- pd
1764
  updateSelectInput(session,"pheno_col",choices=colnames(pd),selected=colnames(pd)[1])
1765
- showNotification(paste("Loaded",ncol(pd),"traits"),type="message",duration=3)
1766
  }, error=function(e) showNotification(paste("Phenotype error:", e$message), type="error"))
1767
  })
1768
 
@@ -1795,19 +1830,76 @@ server <- function(input, output, session) {
1795
  observeEvent(input$run_btn, {
1796
  req(rv$geno, rv$pheno, input$pheno_col)
1797
  showNotification(paste("Starting", input$mapping_method, "analysis..."), type="message")
 
1798
  tryCatch({
 
1799
  cs <- intersect(rownames(rv$geno), rownames(rv$pheno))
1800
- if (length(cs) == 0) { showNotification("No common samples!", type="error"); return() }
 
 
 
 
 
 
 
 
 
 
 
 
 
1801
  X <- rv$geno[cs, , drop=FALSE]
1802
- y <- as.numeric(rv$pheno[cs, input$pheno_col])
1803
- set.seed(42)
1804
- tr_idx <- caret::createDataPartition(y, p=1-input$val_prop, list=FALSE)
1805
- X_tr <- X[tr_idx, , drop=FALSE]; y_tr <- y[tr_idx]
1806
- X_v <- X[-tr_idx, , drop=FALSE]; y_v <- y[-tr_idx]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1807
 
1808
  withProgress(message=paste("Running", input$mapping_method, "..."), value=0.1, {
1809
 
1810
- # --- Permutation (if requested) ---
1811
  if (isTRUE(input$run_permutation)) {
1812
  incProgress(0, detail="Running parallel permutations...")
1813
  n_cores_avail <- max(1, parallel::detectCores(logical=TRUE)-1)
@@ -1822,7 +1914,6 @@ server <- function(input, output, session) {
1822
  n_cofactors = input$n_cofactors,
1823
  window_size = input$window_size)
1824
  cat("Permutation LOD threshold:", rv$perm_threshold, "\n")
1825
- # NOTE: slider is NOT auto-updated here — user clicks Apply button
1826
  showNotification(
1827
  paste0("Permutation done. LOD threshold = ",
1828
  round(rv$perm_threshold, 3),
@@ -1837,7 +1928,6 @@ server <- function(input, output, session) {
1837
  window_size = input$window_size)
1838
  incProgress(0.35)
1839
 
1840
- # Find peaks using current slider value (not automatically replaced)
1841
  rv$qtl_peaks <- find_qtl_peaks(rv$scan_all, lod_thr(), input$min_peak_distance)
1842
  if (!is.null(rv$qtl_peaks) && nrow(rv$qtl_peaks) > 0) {
1843
  rv$qtl_peaks <- add_precision_support_intervals(rv$qtl_peaks, rv$scan_all, input$lod_drop)
@@ -1845,29 +1935,57 @@ server <- function(input, output, session) {
1845
  }
1846
  incProgress(0.15)
1847
 
1848
- # Prediction model
1849
- nzv_i <- caret::nearZeroVar(X_tr)
1850
  Xtr_rf <- if (length(nzv_i) > 0) X_tr[,-nzv_i,drop=FALSE] else X_tr
1851
- Xv_rf <- X_v[, colnames(Xtr_rf), drop=FALSE]
 
 
 
 
 
 
 
1852
  rv$model_cols <- colnames(Xtr_rf)
1853
 
1854
- fit <- tryCatch(
1855
- caret::train(x=Xtr_rf, y=y_tr, method="rf",
1856
- trControl=caret::trainControl(method="cv",number=5), tuneLength=3),
1857
- error=function(e)
 
 
 
 
 
 
 
 
 
 
 
 
1858
  caret::train(x=Xtr_rf, y=y_tr, method="lm",
1859
- trControl=caret::trainControl(method="cv",number=5)))
1860
- rv$model_fit <- fit
1861
-
1862
- ytr_p <- predict(fit, Xtr_rf); yv_p <- predict(fit, Xv_rf)
1863
- tr_r2 <- max(0, 1 - sum((y_tr-ytr_p)^2)/sum((y_tr-mean(y_tr))^2))
1864
- v_r2 <- max(0, 1 - sum((y_v-yv_p)^2) /sum((y_v-mean(y_v))^2))
1865
-
1866
- rv$perf <- data.frame(
1867
- Metric = c("R² Train","R Train","R² Validation","R Validation"),
1868
- Value = c(tr_r2, cor(y_tr,ytr_p), v_r2, cor(y_v,yv_p)))
1869
- rv$tr_pred <- data.frame(Observed=y_tr, Predicted=ytr_p)
1870
- rv$val_pred <- data.frame(Observed=y_v, Predicted=yv_p)
 
 
 
 
 
 
 
 
 
1871
  incProgress(0.35)
1872
  })
1873
 
@@ -1875,9 +1993,11 @@ server <- function(input, output, session) {
1875
  showNotification(paste(input$mapping_method,"done —",n_sig,"QTL peaks detected"),
1876
  type="message")
1877
  updateTabsetPanel(session,"nav",selected="📊 Results")
 
1878
  }, error=function(e) {
1879
- showNotification(paste("Analysis error:", e$message), type="error")
1880
  cat("ERROR:", e$message, "\n")
 
1881
  })
1882
  })
1883
 
@@ -1901,12 +2021,23 @@ server <- function(input, output, session) {
1901
  req(rv$geno, rv$pheno, input$compare_methods, input$pheno_col)
1902
  if (length(input$compare_methods) == 0) {
1903
  showNotification("Select at least one method", type="warning"); return() }
1904
- cs <- intersect(rownames(rv$geno), rownames(rv$pheno))
 
 
 
 
1905
  X <- rv$geno[cs, , drop=FALSE]
1906
- y <- as.numeric(rv$pheno[cs, input$pheno_col])
1907
- set.seed(42)
1908
- tr_i <- caret::createDataPartition(y, p=1-input$val_prop, list=FALSE)
1909
- X_tr <- X[tr_i, , drop=FALSE]; y_tr <- y[tr_i]
 
 
 
 
 
 
 
1910
  clist <- list(); peaks_list <- list()
1911
  withProgress(message="Comparing models...", value=0, {
1912
  for (mth in input$compare_methods) {
@@ -2296,9 +2427,9 @@ server <- function(input, output, session) {
2296
  sheets[["Selection_Signatures"]] <- rv$sel_metrics
2297
  if (!is.null(rv$perm_threshold))
2298
  sheets[["Permutation_Info"]] <- data.frame(
2299
- Method = input$mapping_method,
2300
- N_Perm = if (isTRUE(input$run_permutation)) input$n_perm else NA,
2301
- Alpha = if (isTRUE(input$run_permutation)) input$perm_alpha else NA,
2302
  LOD_Threshold = rv$perm_threshold)
2303
  if (length(sheets) == 0) sheets[["Empty"]] <- data.frame(msg="Run analysis first")
2304
  writexl::write_xlsx(sheets, file)
 
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
  # ============================================================
19
 
20
  options(repos = c(CRAN = "https://cloud.r-project.org"))
 
42
  trimws(gsub('[\r\n\"]', '', as.character(x)))
43
  }
44
 
45
+ # Normalize sample IDs for robust matching
46
+ normalize_id <- function(x) trimws(as.character(x))
47
+
48
  # ============================================================
49
  # COLOR PALETTES
50
  # ============================================================
 
87
  # CORE FUNCTIONS
88
  # ============================================================
89
 
 
 
90
  calc_lod <- function(fit_full, fit_null) {
91
  rss1 <- sum(residuals(fit_full)^2)
92
  rss0 <- sum(residuals(fit_null)^2)
 
95
  max(0, (n / 2) * log10(rss0 / rss1))
96
  }
97
 
 
98
  calc_lod_sst <- function(fit_full, sst, n) {
99
  rss1 <- sum(residuals(fit_full)^2)
100
  if (rss1 <= 0 || sst <= 0) return(0)
101
  max(0, (n / 2) * log10(sst / rss1))
102
  }
103
 
 
 
 
 
 
 
 
104
  calc_pve_total <- function(fit_full, y_vec) {
105
  sst <- sum((y_vec - mean(y_vec))^2)
106
  rss1 <- sum(residuals(fit_full)^2)
 
118
  }
119
 
120
  # ============================================================
121
+ # ROBUST TRAIN/VAL SPLIT
122
+ # FIX: replaces caret::createDataPartition with a safe wrapper
123
+ # that handles small N, all-NA y, zero-variance y, and
124
+ # partition sizes that would round to 0.
125
+ # ============================================================
126
+ safe_partition <- function(y, val_prop = 0.2) {
127
+ # Remove NAs first
128
+ valid_idx <- which(!is.na(y))
129
+ n_valid <- length(valid_idx)
130
+
131
+ if (n_valid < 10) {
132
+ stop(paste0("Only ", n_valid, " non-NA samples after matching. ",
133
+ "Need at least 10. Check that sample IDs in genotype and ",
134
+ "phenotype files match exactly (case-sensitive, no spaces)."))
135
+ }
136
+
137
+ # Clamp val_prop so both partitions have >= 5 samples
138
+ min_val <- ceiling(n_valid * 0.10)
139
+ max_val <- floor(n_valid * 0.40)
140
+ n_val <- max(5, min(floor(n_valid * val_prop), max_val))
141
+ n_train <- n_valid - n_val
142
+
143
+ if (n_train < 5) {
144
+ stop(paste0("Training set would have only ", n_train, " samples. ",
145
+ "Reduce validation proportion or add more samples."))
146
+ }
147
+
148
+ cat(" Partition: n_valid=", n_valid, " n_train=", n_train, " n_val=", n_val, "\n")
149
+
150
+ # Try caret first, fall back to simple random split
151
+ tr_idx <- tryCatch({
152
+ y_valid <- y[valid_idx]
153
+ ci <- caret::createDataPartition(y_valid, p = n_train / n_valid, list = FALSE)
154
+ valid_idx[ci[, 1]]
155
+ }, error = function(e) {
156
+ cat(" caret::createDataPartition failed:", e$message, "— using simple random split\n")
157
+ set.seed(42)
158
+ valid_idx[sample(n_valid, n_train)]
159
+ })
160
+
161
+ val_idx <- setdiff(valid_idx, tr_idx)
162
+ list(train = tr_idx, val = val_idx)
163
+ }
164
+
165
+ # ============================================================
166
+ # PRECISION SUPPORT INTERVAL
167
  # ============================================================
168
  find_interval_boundary <- function(lod_profile, positions, peak_idx, peak_lod,
169
  drop, direction = "left") {
 
181
  } else {
182
  boundary_pos <- pos1
183
  }
184
+ return(list(position = boundary_pos,
185
  marker_left = names(positions)[i-1],
186
  marker_right = names(positions)[i]))
187
  }
 
291
  full_scan_df$Chromosome <- as.character(full_scan_df$Chromosome)
292
 
293
  for (i in seq_len(nrow(peaks_df))) {
294
+ chr <- as.character(peaks_df$Chromosome[i])
295
+ peak_lod <- peaks_df$LOD[i]
296
+ peak_pos <- peaks_df$Position[i]
297
  peak_marker <- peaks_df$Marker[i]
298
 
299
  chr_data <- full_scan_df[full_scan_df$Chromosome == chr &
 
327
  peaks_df$Right_Interval_Marker[i] <- right_res$marker_left
328
  peaks_df$Interval_Size_cM[i] <- max(0, right_res$position - left_res$position)
329
 
 
330
  peaks_df$Left_Flanking_Marker[i] <- {
331
  lm <- chr_data$Marker[chr_data$Position < peaks_df$Interval_Start_cM[i]]
332
  if (length(lm) > 0) lm[length(lm)] else NA_character_
 
362
  if (ncol(gd) > target_n) gd <- gd[, seq_len(target_n)]
363
 
364
  colnames(gd) <- header_row
365
+ # FIX: normalize row names for consistent matching
366
+ rownames(gd) <- make.unique(normalize_id(as.character(gd[, 1])))
367
  gd <- gd[, -1, drop = FALSE]
368
 
369
  for (col in colnames(gd)) {
 
441
  nzv <- apply(X, 2, function(x) length(unique(na.omit(x))) < 2)
442
  X <- X[, !nzv, drop = FALSE]
443
 
 
 
 
 
444
  res_list <- vector("list", ncol(X)); names(res_list) <- colnames(X)
445
  for (m in colnames(X)) {
446
  g <- X[, m]; ok <- !is.na(g); gv <- g[ok]; pv <- y[ok]
 
448
  mi <- marker_info[marker_info$Marker == m, ]
449
  if (nrow(mi) == 0 || is.na(mi$Position[1])) next
450
  tryCatch({
 
451
  fit_full <- lm(pv ~ gv)
452
  fit_null <- lm(pv ~ 1)
 
453
  n_m <- length(pv)
454
+ lod <- calc_lod(fit_full, fit_null)
455
+ pve <- calc_pve_total(fit_full, pv)
456
  pval <- coef(summary(fit_full))[2, 4]
457
  eff <- estimate_effects(gv, pv)
458
  res_list[[m]] <- data.frame(
 
482
  n <- length(y)
483
  max_k <- max(3, min(n_cofactors, floor(sqrt(n))))
484
 
 
485
  cat(" Selecting cofactors...\n")
486
  cofactors <- character(0); remaining <- colnames(X); prev_lod <- 0
487
  for (step in seq_len(max_k)) {
 
503
  }
504
  cat(" Selected", length(cofactors), "cofactors\n")
505
 
 
506
  res_list <- vector("list", ncol(X)); names(res_list) <- colnames(X)
507
  for (m in colnames(X)) {
508
  g <- X[, m]; ok <- !is.na(g); gv <- g[ok]; pv <- y[ok]
 
530
  }
531
  df <- df[complete.cases(df), ]
532
  if (nrow(df) < 8) return(NULL)
533
+ pv_cc <- df$y
 
534
 
535
  if (length(active_cof) > 0) {
536
+ fit_full <- lm(as.formula(paste("y ~ focal +", paste(active_cof, collapse="+"))), data=df)
 
 
 
537
  fit_null_cof <- lm(as.formula(paste("y ~", paste(active_cof, collapse="+"))), data=df)
538
+ lod <- calc_lod(fit_full, fit_null_cof)
 
 
539
  } else {
540
  fit_full <- lm(y ~ focal, data=df)
541
  fit_null_cof <- lm(y ~ 1, data=df)
542
  lod <- calc_lod(fit_full, fit_null_cof)
543
  }
544
 
 
545
  pve <- calc_pve_total(fit_full, pv_cc)
 
546
  ct <- coef(summary(fit_full))
547
  if (!"focal" %in% rownames(ct)) next
548
  pval <- ct["focal","Pr(>|t|)"]
 
638
  lod <- calc_lod(fit_full, fit_null_cof)
639
  }
640
 
 
641
  pve <- calc_pve_total(fit_full, pv_cc)
 
642
  ct <- coef(summary(fit_full))
643
  if (!"focal" %in% rownames(ct)) next
644
  pval <- ct["focal","Pr(>|t|)"]
 
660
  }
661
 
662
  # ============================================================
663
+ # LASSO
664
  # ============================================================
665
  qtl_scan_lasso <- function(X, y, marker_info) {
666
  ok <- !is.na(y) & apply(X, 1, function(r) !any(is.na(r)))
 
675
  cdf <- merge(cdf, marker_info, by = "Marker", all.x = TRUE)
676
  cdf <- cdf[!is.na(cdf$Position), ]
677
 
 
 
 
 
678
  cdf$LOD <- sapply(seq_len(nrow(cdf)), function(i) {
679
  m <- cdf$Marker[i]
680
  g <- Xv[, m]; v <- !is.na(g)
 
682
  gv2 <- g[v]; pv2 <- yv[v]
683
  fit <- tryCatch(lm(pv2 ~ gv2), error = function(e) NULL)
684
  if (is.null(fit)) return(0)
 
685
  calc_lod(fit, lm(pv2 ~ 1))
686
  })
687
  cdf$P_Value <- 10^(-cdf$LOD)
 
709
  }
710
 
711
  # ============================================================
712
+ # Elastic Net
713
  # ============================================================
714
  qtl_scan_enet <- function(X, y, marker_info) {
715
  ok <- !is.na(y) & apply(X, 1, function(r) !any(is.na(r)))
 
774
  idf <- merge(idf, marker_info, by = "Marker", all.x = TRUE)
775
  idf <- idf[!is.na(idf$Position), ]
776
 
 
777
  idf$LOD <- sapply(seq_len(nrow(idf)), function(i) {
778
  m <- idf$Marker[i]; g <- Xv[, m]; v <- !is.na(g)
779
  if (sum(v) < 8) return(0)
 
859
  return(0)
860
  }
861
 
862
+ seeds <- sample.int(1e6, n_perm)
863
  is_windows <- .Platform$OS.type == "windows"
864
 
865
  if (n_cores > 1) {
 
1078
  pd$cum_pos <- pd$Position + offsets[pd$Chromosome]
1079
  pd$sig <- pd$LOD >= lod_threshold
1080
 
1081
+ chr_mids <- tapply(pd$cum_pos, pd$Chromosome, median, na.rm = TRUE)
1082
  chr_bg_colors <- rep(c("#3A86FF","#FB5607"), length.out = length(chroms))
1083
  names(chr_bg_colors) <- chroms
1084
 
 
1085
  pve_col <- if ("PVE_Percent" %in% colnames(pd)) "PVE_Percent" else
1086
  if ("PVE_Marker_Percent" %in% colnames(pd)) "PVE_Marker_Percent" else NULL
1087
 
 
1225
  for (m in intersect(model_names, names(MODEL_COLORS)))
1226
  model_colors_use[m] <- MODEL_COLORS[m]
1227
 
 
1228
  get_pve <- function(df) {
1229
  if ("PVE_Percent" %in% colnames(df)) df$PVE_Percent
1230
  else if ("PVE_Marker_Percent" %in% colnames(df)) df$PVE_Marker_Percent
 
1305
  .perm-info{background:linear-gradient(135deg,#e8f4fd,#f0f8ff);border:1px solid #90caf9;border-left:4px solid #8338EC;border-radius:8px;padding:12px 16px;margin:8px 0;font-size:13px;}
1306
  .speed-badge{background:#8338EC;color:#fff;border-radius:12px;padding:2px 8px;font-size:10px;font-weight:700;letter-spacing:0.5px;}
1307
  .fix-badge{background:#06D6A0;color:#fff;border-radius:12px;padding:2px 8px;font-size:10px;font-weight:700;letter-spacing:0.5px;}
1308
+ .diag-box{background:#fff3cd;border:1px solid #ffc107;border-left:4px solid #fd7e14;border-radius:6px;padding:10px 14px;margin:6px 0;font-size:12px;font-family:monospace;}
1309
  "))
1310
  ),
1311
 
 
1323
  "Row3 = positions (cM) | Rows 4+ = samples. Genotypes coded 0/1/2.",
1324
  tags$br(),
1325
  tags$span(style="color:#06D6A0;font-weight:600;",
1326
+ "v11 FIXES: PVE uses SST denominator | Permutation threshold stored separately | ",
1327
+ "LASSO/ENET/RF LOD = (n/2)*log10(SST/RSS) | Robust partition with safe_partition()")
 
1328
  )
1329
  )),
1330
  fluidRow(
 
1351
  selected = "CIM"),
1352
  uiOutput("method_desc_ui"),
1353
 
 
1354
  sliderInput("lod_threshold","LOD Threshold (manual)",
1355
  min=0.1, max=10, value=2.0, step=0.1),
1356
 
 
1368
  style="margin-top:10px;width:100%;"),
1369
  tags$hr(style="margin:10px 0;"),
1370
 
 
1371
  checkboxInput("run_permutation","Estimate LOD threshold by permutation",value=FALSE),
1372
  conditionalPanel("input.run_permutation",
1373
  div(class="perm-info",
 
1388
  ),
1389
  column(4,
1390
  div(class="card",
1391
+ div(class="card-hd","Dataset Summary & Diagnostics"),
1392
  div(class="card-bd",uiOutput("dataset_info_ui"))
1393
  ),
1394
  div(class="card",
 
1608
  div(class="info-box",
1609
  tags$b("v11 Bug Fixes:"), tags$br(),
1610
  tags$span(class="fix-badge","FIXED"),
1611
+ tags$b(" createDataPartition 'wrong sign in by argument' error:"),
1612
+ " Replaced with safe_partition() that: (a) removes NAs before splitting, ",
1613
+ "(b) enforces minimum 10 common samples with a clear error message, ",
1614
+ "(c) clamps val_prop to ensure train ≥ 5 and val ≥ 5 samples, ",
1615
+ "(d) falls back to simple random split if caret fails for any reason.",
1616
+ tags$br(),tags$br(),
1617
+ tags$span(class="fix-badge","FIXED"),
1618
+ tags$b(" Sample ID matching:"),
1619
+ " normalize_id() (trimws) applied to both geno and pheno rownames so ",
1620
+ "leading/trailing whitespace no longer causes zero intersection.",
1621
+ tags$br(),tags$br(),
1622
+ tags$span(class="fix-badge","FIXED"),
1623
  tags$b(" PVE denominator (CIM/MQM):"),
1624
+ " PVE = (SST − RSS_full) / SST × 100 for all methods.",
1625
+ tags$br(),tags$br(),
 
 
1626
  tags$span(class="fix-badge","FIXED"),
1627
+ tags$b(" LOD slider auto-reset:"),
1628
+ " Permutation threshold stored separately; explicit Apply button required.",
1629
+ tags$br(),tags$br(),
 
1630
  tags$span(class="fix-badge","FIXED"),
1631
  tags$b(" LASSO/ENET/RF LOD scale:"),
1632
+ " LOD = (n/2)·log10(SST/RSS) per-marker."
 
 
 
 
 
1633
  ),
1634
  div(class="info-box",style="margin-top:12px;",
1635
  tags$b("Statistical Formulas:"), tags$br(),
1636
  tags$code("LOD = (n/2) × log10(SST / RSS_full)"), tags$br(),
 
 
1637
  tags$code("PVE = (SST − RSS_full) / SST × 100"), tags$br(),
 
1638
  tags$br(),
1639
  tags$b("CIM LOD scan statistic:"),
1640
+ " LOD = (n/2)×log10(RSS_cofactors / RSS_full). PVE uses SST from y~1."
 
1641
  ),
1642
  tags$h5(style="margin-top:18px;font-weight:600;color:#3A86FF;","References"),
1643
  tags$ul(
 
1675
  sel_metrics = NULL,
1676
  compare_res = list(),
1677
  compare_peaks = list(),
1678
+ perm_threshold = NULL,
1679
+ diag_info = NULL # diagnostic messages
1680
  )
1681
 
 
1682
  lod_thr <- reactive({ input$lod_threshold })
1683
 
1684
  # ---- Method description ----
 
1701
  )
1702
  })
1703
 
1704
+ # ---- Apply permutation threshold ----
1705
  observeEvent(input$apply_perm_thr, {
1706
  req(rv$perm_threshold)
1707
  thr <- round(rv$perm_threshold, 2)
 
1708
  thr <- max(0.1, min(10, thr))
1709
  updateSliderInput(session, "lod_threshold", value = thr)
1710
  showNotification(paste0("LOD threshold set to ", thr,
 
1712
  type = "message", duration = 4)
1713
  })
1714
 
1715
+ # ---- Dataset summary with diagnostics ----
1716
  output$dataset_info_ui <- renderUI({
1717
  if (is.null(rv$geno))
1718
  return(div(class="warn-box","Upload genotype and phenotype files to begin."))
1719
+
1720
+ # Compute common samples and diagnostics
1721
+ diag_msgs <- character(0)
1722
+
1723
+ n_geno <- nrow(rv$geno)
1724
+ n_pheno <- if (!is.null(rv$pheno)) nrow(rv$pheno) else 0
1725
+
1726
+ if (!is.null(rv$pheno) && !is.null(input$pheno_col) && nchar(input$pheno_col) > 0) {
1727
+ cs <- intersect(rownames(rv$geno), rownames(rv$pheno))
1728
+ n_cs <- length(cs)
1729
+ if (n_cs == 0) {
1730
+ diag_msgs <- c(diag_msgs,
1731
+ paste0("⚠ 0 common samples! Geno IDs: '",
1732
+ paste(head(rownames(rv$geno), 3), collapse="', '"), "'... | Pheno IDs: '",
1733
+ paste(head(rownames(rv$pheno), 3), collapse="', '"), "'..."))
1734
+ } else {
1735
+ y_cs <- as.numeric(rv$pheno[cs, input$pheno_col])
1736
+ n_na <- sum(is.na(y_cs))
1737
+ n_valid <- n_cs - n_na
1738
+ if (n_valid < 10)
1739
+ diag_msgs <- c(diag_msgs,
1740
+ paste0("⚠ Only ", n_valid, " non-NA phenotype values. Need ≥10 to run analysis."))
1741
+ if (n_valid >= 2 && var(y_cs, na.rm=TRUE) < 1e-10)
1742
+ diag_msgs <- c(diag_msgs, "⚠ Phenotype has zero variance — check your data.")
1743
+ if (n_na > 0)
1744
+ diag_msgs <- c(diag_msgs, paste0("ℹ ", n_na, " samples have NA phenotype (will be excluded)."))
1745
+ }
1746
+ } else {
1747
+ n_cs <- 0
1748
+ }
1749
+
1750
  tagList(
1751
  fluidRow(
1752
  column(6, div(class="stat-box",
1753
+ tags$div(class="stat-value", n_geno),
1754
+ tags$div(class="stat-label","Geno Samples"))),
1755
  column(6, div(class="stat-box",
1756
  tags$div(class="stat-value", ncol(rv$geno)),
1757
  tags$div(class="stat-label","Markers")))
 
1761
  tags$div(class="stat-value", length(unique(rv$marker_info$Chromosome))),
1762
  tags$div(class="stat-label","Chromosomes"))),
1763
  column(6, div(class="stat-box",
1764
+ tags$div(class="stat-value", if (n_cs > 0) n_cs else "—"),
1765
+ tags$div(class="stat-label","Common Samples")))
1766
  ),
1767
+ if (length(diag_msgs) > 0)
1768
+ div(class="diag-box", tags$b("Diagnostics:"), tags$br(),
1769
+ lapply(diag_msgs, function(m) tagList(m, tags$br()))),
1770
  if (!is.null(rv$perm_threshold))
1771
  div(class="perm-info",style="margin-top:8px;",
1772
  tags$span(class="speed-badge","FAST"),
 
1791
  req(input$pheno_file)
1792
  tryCatch({
1793
  pd <- read.csv(input$pheno_file$datapath)
1794
+ # FIX: normalize phenotype row names
1795
+ rownames(pd) <- make.unique(normalize_id(as.character(pd[,1])))
1796
+ pd <- pd[,-1,drop=FALSE]
1797
+ for (col in colnames(pd)) pd[[col]] <- suppressWarnings(as.numeric(as.character(pd[[col]])))
1798
  rv$pheno <- pd
1799
  updateSelectInput(session,"pheno_col",choices=colnames(pd),selected=colnames(pd)[1])
1800
+ showNotification(paste("Loaded",ncol(pd),"traits,",nrow(pd),"samples"),type="message",duration=3)
1801
  }, error=function(e) showNotification(paste("Phenotype error:", e$message), type="error"))
1802
  })
1803
 
 
1830
  observeEvent(input$run_btn, {
1831
  req(rv$geno, rv$pheno, input$pheno_col)
1832
  showNotification(paste("Starting", input$mapping_method, "analysis..."), type="message")
1833
+
1834
  tryCatch({
1835
+ # --- Match samples ---
1836
  cs <- intersect(rownames(rv$geno), rownames(rv$pheno))
1837
+ cat("Common samples:", length(cs), "\n")
1838
+ cat("Geno IDs (first 5):", paste(head(rownames(rv$geno),5), collapse=", "), "\n")
1839
+ cat("Pheno IDs (first 5):", paste(head(rownames(rv$pheno),5), collapse=", "), "\n")
1840
+
1841
+ if (length(cs) == 0) {
1842
+ showNotification(
1843
+ paste0("No common samples between genotype and phenotype files. ",
1844
+ "Check that sample IDs match exactly. ",
1845
+ "Geno example: '", rownames(rv$geno)[1], "' | ",
1846
+ "Pheno example: '", rownames(rv$pheno)[1], "'"),
1847
+ type="error", duration=10)
1848
+ return()
1849
+ }
1850
+
1851
  X <- rv$geno[cs, , drop=FALSE]
1852
+ y_raw <- rv$pheno[cs, input$pheno_col]
1853
+ y <- suppressWarnings(as.numeric(as.character(y_raw)))
1854
+
1855
+ # --- Phenotype diagnostics ---
1856
+ cat("y length:", length(y), " NAs:", sum(is.na(y)),
1857
+ " range:", paste(range(y, na.rm=TRUE), collapse=" to "), "\n")
1858
+
1859
+ if (sum(!is.na(y)) < 10) {
1860
+ showNotification(
1861
+ paste0("Only ", sum(!is.na(y)), " non-NA phenotype values after matching. ",
1862
+ "Need at least 10. Check phenotype column '", input$pheno_col, "'."),
1863
+ type="error", duration=10)
1864
+ return()
1865
+ }
1866
+
1867
+ if (var(y, na.rm=TRUE) < 1e-10) {
1868
+ showNotification(
1869
+ paste0("Phenotype '", input$pheno_col, "' has zero or near-zero variance. ",
1870
+ "Select a different trait or check your data."),
1871
+ type="error", duration=8)
1872
+ return()
1873
+ }
1874
+
1875
+ # --- SAFE PARTITION (KEY FIX) ---
1876
+ partition <- tryCatch(
1877
+ safe_partition(y, val_prop = input$val_prop),
1878
+ error = function(e) {
1879
+ showNotification(paste("Partition error:", e$message), type="error", duration=10)
1880
+ NULL
1881
+ }
1882
+ )
1883
+ if (is.null(partition)) return()
1884
+
1885
+ tr_idx <- partition$train
1886
+ val_idx <- partition$val
1887
+
1888
+ X_tr <- X[tr_idx, , drop=FALSE]; y_tr <- y[tr_idx]
1889
+ X_v <- X[val_idx, , drop=FALSE]; y_v <- y[val_idx]
1890
+
1891
+ # Remove NAs from training set (safe_partition keeps valid_idx but y might still have NAs
1892
+ # if geno rows differ — do a final clean)
1893
+ tr_ok <- !is.na(y_tr)
1894
+ X_tr <- X_tr[tr_ok, , drop=FALSE]; y_tr <- y_tr[tr_ok]
1895
+ val_ok <- !is.na(y_v)
1896
+ X_v <- X_v[val_ok, , drop=FALSE]; y_v <- y_v[val_ok]
1897
+
1898
+ cat(" Final train N:", length(y_tr), " val N:", length(y_v), "\n")
1899
 
1900
  withProgress(message=paste("Running", input$mapping_method, "..."), value=0.1, {
1901
 
1902
+ # --- Permutation ---
1903
  if (isTRUE(input$run_permutation)) {
1904
  incProgress(0, detail="Running parallel permutations...")
1905
  n_cores_avail <- max(1, parallel::detectCores(logical=TRUE)-1)
 
1914
  n_cofactors = input$n_cofactors,
1915
  window_size = input$window_size)
1916
  cat("Permutation LOD threshold:", rv$perm_threshold, "\n")
 
1917
  showNotification(
1918
  paste0("Permutation done. LOD threshold = ",
1919
  round(rv$perm_threshold, 3),
 
1928
  window_size = input$window_size)
1929
  incProgress(0.35)
1930
 
 
1931
  rv$qtl_peaks <- find_qtl_peaks(rv$scan_all, lod_thr(), input$min_peak_distance)
1932
  if (!is.null(rv$qtl_peaks) && nrow(rv$qtl_peaks) > 0) {
1933
  rv$qtl_peaks <- add_precision_support_intervals(rv$qtl_peaks, rv$scan_all, input$lod_drop)
 
1935
  }
1936
  incProgress(0.15)
1937
 
1938
+ # --- Prediction model ---
1939
+ nzv_i <- tryCatch(caret::nearZeroVar(X_tr), error=function(e) integer(0))
1940
  Xtr_rf <- if (length(nzv_i) > 0) X_tr[,-nzv_i,drop=FALSE] else X_tr
1941
+ # Align validation set columns
1942
+ Xv_rf <- X_v[, intersect(colnames(Xtr_rf), colnames(X_v)), drop=FALSE]
1943
+ # Add any missing columns as 0
1944
+ missing_cols <- setdiff(colnames(Xtr_rf), colnames(Xv_rf))
1945
+ if (length(missing_cols) > 0) {
1946
+ for (mc in missing_cols) Xv_rf[[mc]] <- 0
1947
+ Xv_rf <- Xv_rf[, colnames(Xtr_rf), drop=FALSE]
1948
+ }
1949
  rv$model_cols <- colnames(Xtr_rf)
1950
 
1951
+ # Use RF if enough samples, else lm
1952
+ use_rf <- nrow(Xtr_rf) >= 20 && ncol(Xtr_rf) >= 2
1953
+ fit <- if (use_rf) {
1954
+ tryCatch(
1955
+ caret::train(x=Xtr_rf, y=y_tr, method="rf",
1956
+ trControl=caret::trainControl(method="cv",number=min(5,floor(nrow(Xtr_rf)/5))),
1957
+ tuneLength=3),
1958
+ error=function(e) {
1959
+ cat("RF train failed:", e$message, "— falling back to lm\n")
1960
+ tryCatch(
1961
+ caret::train(x=Xtr_rf, y=y_tr, method="lm",
1962
+ trControl=caret::trainControl(method="cv",number=min(5,floor(nrow(Xtr_rf)/5)))),
1963
+ error=function(e2) NULL)
1964
+ })
1965
+ } else {
1966
+ tryCatch(
1967
  caret::train(x=Xtr_rf, y=y_tr, method="lm",
1968
+ trControl=caret::trainControl(method="cv",number=min(5,floor(nrow(Xtr_rf)/5)))),
1969
+ error=function(e) NULL)
1970
+ }
1971
+
1972
+ if (is.null(fit)) {
1973
+ showNotification("Prediction model failed — QTL results still available", type="warning")
1974
+ rv$perf <- data.frame(Metric=c("R² Train","R Train","R² Validation","R Validation"),
1975
+ Value=rep(NA_real_,4))
1976
+ rv$tr_pred <- data.frame(Observed=y_tr, Predicted=rep(NA_real_,length(y_tr)))
1977
+ rv$val_pred<- data.frame(Observed=y_v, Predicted=rep(NA_real_,length(y_v)))
1978
+ } else {
1979
+ rv$model_fit <- fit
1980
+ ytr_p <- predict(fit, Xtr_rf); yv_p <- predict(fit, Xv_rf)
1981
+ tr_r2 <- max(0, 1 - sum((y_tr-ytr_p)^2)/sum((y_tr-mean(y_tr))^2))
1982
+ v_r2 <- max(0, 1 - sum((y_v-yv_p)^2) /sum((y_v-mean(y_v))^2))
1983
+ rv$perf <- data.frame(
1984
+ Metric = c("R² Train","R Train","R² Validation","R Validation"),
1985
+ Value = c(tr_r2, cor(y_tr,ytr_p), v_r2, cor(y_v,yv_p)))
1986
+ rv$tr_pred <- data.frame(Observed=y_tr, Predicted=ytr_p)
1987
+ rv$val_pred <- data.frame(Observed=y_v, Predicted=yv_p)
1988
+ }
1989
  incProgress(0.35)
1990
  })
1991
 
 
1993
  showNotification(paste(input$mapping_method,"done —",n_sig,"QTL peaks detected"),
1994
  type="message")
1995
  updateTabsetPanel(session,"nav",selected="📊 Results")
1996
+
1997
  }, error=function(e) {
1998
+ showNotification(paste("Analysis error:", e$message), type="error", duration=10)
1999
  cat("ERROR:", e$message, "\n")
2000
+ cat(traceback(), "\n")
2001
  })
2002
  })
2003
 
 
2021
  req(rv$geno, rv$pheno, input$compare_methods, input$pheno_col)
2022
  if (length(input$compare_methods) == 0) {
2023
  showNotification("Select at least one method", type="warning"); return() }
2024
+
2025
+ cs <- intersect(rownames(rv$geno), rownames(rv$pheno))
2026
+ if (length(cs) == 0) {
2027
+ showNotification("No common samples — check file IDs match", type="error"); return() }
2028
+
2029
  X <- rv$geno[cs, , drop=FALSE]
2030
+ y <- suppressWarnings(as.numeric(as.character(rv$pheno[cs, input$pheno_col])))
2031
+
2032
+ partition <- tryCatch(safe_partition(y, val_prop=input$val_prop),
2033
+ error=function(e) { showNotification(e$message, type="error"); NULL })
2034
+ if (is.null(partition)) return()
2035
+
2036
+ X_tr <- X[partition$train, , drop=FALSE]
2037
+ y_tr <- y[partition$train]
2038
+ ok <- !is.na(y_tr)
2039
+ X_tr <- X_tr[ok,,drop=FALSE]; y_tr <- y_tr[ok]
2040
+
2041
  clist <- list(); peaks_list <- list()
2042
  withProgress(message="Comparing models...", value=0, {
2043
  for (mth in input$compare_methods) {
 
2427
  sheets[["Selection_Signatures"]] <- rv$sel_metrics
2428
  if (!is.null(rv$perm_threshold))
2429
  sheets[["Permutation_Info"]] <- data.frame(
2430
+ Method = input$mapping_method,
2431
+ N_Perm = if (isTRUE(input$run_permutation)) input$n_perm else NA,
2432
+ Alpha = if (isTRUE(input$run_permutation)) input$perm_alpha else NA,
2433
  LOD_Threshold = rv$perm_threshold)
2434
  if (length(sheets) == 0) sheets[["Empty"]] <- data.frame(msg="Run analysis first")
2435
  writexl::write_xlsx(sheets, file)