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

Update app.R

Browse files
Files changed (1) hide show
  1. app.R +77 -69
app.R CHANGED
@@ -13,8 +13,11 @@
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"))
@@ -119,12 +122,8 @@ dom_class <- function(a, d) {
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
 
@@ -134,7 +133,6 @@ safe_partition <- function(y, val_prop = 0.2) {
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))
@@ -147,7 +145,6 @@ safe_partition <- function(y, val_prop = 0.2) {
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)
@@ -164,17 +161,28 @@ safe_partition <- function(y, val_prop = 0.2) {
164
 
165
  # ============================================================
166
  # PRECISION SUPPORT INTERVAL
 
 
 
167
  # ============================================================
168
  find_interval_boundary <- function(lod_profile, positions, peak_idx, peak_lod,
169
  drop, direction = "left") {
170
  target_lod <- peak_lod - drop
 
171
 
172
  if (direction == "left") {
 
 
 
 
 
 
 
173
  for (i in seq(peak_idx, 2, by = -1)) {
174
- if (is.na(lod_profile[i]) || is.na(lod_profile[i-1])) next
175
- if (lod_profile[i] >= target_lod && lod_profile[i-1] < target_lod) {
176
- lod1 <- lod_profile[i-1]; lod2 <- lod_profile[i]
177
- pos1 <- positions[i-1]; pos2 <- positions[i]
178
  if (lod2 > lod1) {
179
  fraction <- (target_lod - lod1) / (lod2 - lod1)
180
  boundary_pos <- pos1 + fraction * (pos2 - pos1)
@@ -182,20 +190,27 @@ find_interval_boundary <- function(lod_profile, positions, peak_idx, peak_lod,
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
  }
188
  }
189
  return(list(position = positions[1],
190
  marker_left = NA_character_,
191
  marker_right = names(positions)[1]))
 
192
  } else {
193
- n <- length(lod_profile)
194
- for (i in seq(peak_idx, n-1, by = 1)) {
195
- if (is.na(lod_profile[i]) || is.na(lod_profile[i+1])) next
196
- if (lod_profile[i] >= target_lod && lod_profile[i+1] < target_lod) {
197
- lod1 <- lod_profile[i]; lod2 <- lod_profile[i+1]
198
- pos1 <- positions[i]; pos2 <- positions[i+1]
 
 
 
 
 
 
199
  if (lod1 > lod2) {
200
  fraction <- (target_lod - lod2) / (lod1 - lod2)
201
  boundary_pos <- pos2 + (1 - fraction) * (pos2 - pos1)
@@ -204,7 +219,7 @@ find_interval_boundary <- function(lod_profile, positions, peak_idx, peak_lod,
204
  }
205
  return(list(position = boundary_pos,
206
  marker_left = names(positions)[i],
207
- marker_right = names(positions)[i+1]))
208
  }
209
  }
210
  return(list(position = positions[n],
@@ -238,13 +253,13 @@ find_qtl_peaks <- function(scan_df, lod_threshold, min_distance_cM = 5) {
238
  if (chr_df$LOD[1] >= lod_threshold && chr_df$LOD[1] >= chr_df$LOD[2]) is_peak[1] <- TRUE
239
  if (chr_df$LOD[2] >= lod_threshold && chr_df$LOD[2] > chr_df$LOD[1]) is_peak[2] <- TRUE
240
  } else {
241
- for (i in 2:(n-1)) {
242
  if (chr_df$LOD[i] >= lod_threshold &&
243
- chr_df$LOD[i] > chr_df$LOD[i-1] &&
244
- chr_df$LOD[i] >= chr_df$LOD[i+1]) is_peak[i] <- TRUE
245
  }
246
- if (chr_df$LOD[1] >= lod_threshold && chr_df$LOD[1] > chr_df$LOD[2]) is_peak[1] <- TRUE
247
- if (chr_df$LOD[n] >= lod_threshold && chr_df$LOD[n] > chr_df$LOD[n-1]) is_peak[n] <- TRUE
248
  }
249
 
250
  peaks <- chr_df[is_peak, ]
@@ -358,11 +373,10 @@ load_genotype_file <- function(filepath) {
358
 
359
  target_n <- length(header_row)
360
  if (ncol(gd) < target_n)
361
- for (k in (ncol(gd)+1):target_n) gd[[paste0("V", k)]] <- NA
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
 
@@ -410,8 +424,8 @@ estimate_effects <- function(geno_v, pheno_v) {
410
  if (!is.null(fit)) {
411
  cf <- coef(fit); se <- coef(summary(fit))
412
  a_eff <- cf["a_code"]; d_eff <- cf["d_code"]
413
- se_a <- if ("a_code" %in% rownames(se)) se["a_code","Std. Error"] else NA_real_
414
- se_d <- if ("d_code" %in% rownames(se)) se["d_code","Std. Error"] else NA_real_
415
  if (!is.na(a_eff) && abs(a_eff) > 1e-10) dom_ratio <- abs(d_eff / a_eff)
416
  dom_cl <- dom_class(a_eff, d_eff)
417
  }
@@ -420,13 +434,13 @@ estimate_effects <- function(geno_v, pheno_v) {
420
  if (!is.null(fit)) {
421
  cf <- coef(fit); se <- coef(summary(fit))
422
  a_eff <- cf["a_code"]
423
- se_a <- if ("a_code" %in% rownames(se)) se["a_code","Std. Error"] else NA_real_
424
  d_eff <- 0; se_d <- 0; dom_ratio <- 0; dom_cl <- "Additive"
425
  }
426
  }
427
  list(a_eff = a_eff, se_a = se_a,
428
- ci_lo = if (!is.na(a_eff) && !is.na(se_a)) a_eff - 1.96*se_a else NA_real_,
429
- ci_hi = if (!is.na(a_eff) && !is.na(se_a)) a_eff + 1.96*se_a else NA_real_,
430
  d_eff = d_eff, se_d = se_d,
431
  dom_ratio = dom_ratio, dom_class = dom_cl)
432
  }
@@ -498,7 +512,7 @@ qtl_scan_cim <- function(X, y, marker_info, n_cofactors = 10, window_size = 10)
498
  if (!is.null(best_m) && best_lod > prev_lod + 0.5) {
499
  cofactors <- c(cofactors, best_m); remaining <- setdiff(remaining, best_m)
500
  prev_lod <- best_lod
501
- cat(" Cofactor", length(cofactors), ":", best_m, " LOD:", round(best_lod,2), "\n")
502
  } else break
503
  }
504
  cat(" Selected", length(cofactors), "cofactors\n")
@@ -533,19 +547,19 @@ qtl_scan_cim <- function(X, y, marker_info, n_cofactors = 10, window_size = 10)
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|)"]
549
  eff <- estimate_effects(gv, pv)
550
  res_list[[m]] <- data.frame(
551
  Marker=m, Chromosome=m_chr, Position=m_pos, LOD=lod, P_Value=pval,
@@ -629,19 +643,19 @@ qtl_scan_mqm <- function(X, y, marker_info, n_cofactors = 10, window_size = 10)
629
  pv_cc <- df$y
630
 
631
  if (length(active_cof) > 0) {
632
- fit_full <- lm(as.formula(paste("y ~ focal +", paste(active_cof, collapse="+"))), data=df)
633
- fit_null_cof <- lm(as.formula(paste("y ~", paste(active_cof, collapse="+"))), data=df)
634
  lod <- calc_lod(fit_full, fit_null_cof)
635
  } else {
636
- fit_full <- lm(y ~ focal, data=df)
637
- fit_null_cof <- lm(y ~ 1, data=df)
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|)"]
645
  eff <- estimate_effects(gv, pv)
646
  res_list[[m]] <- data.frame(
647
  Marker=m, Chromosome=m_chr, Position=m_pos, LOD=lod, P_Value=pval,
@@ -984,7 +998,7 @@ make_manhattan_ggplot <- function(scan_df, lod_threshold = 2.0, peaks_df = NULL,
984
  offsets <- setNames(numeric(length(chroms)), chroms)
985
  for (i in seq_along(chroms)) {
986
  if (i == 1) { offsets[chroms[1]] <- 0; next }
987
- prev <- chroms[i-1]
988
  offsets[chroms[i]] <- offsets[prev] +
989
  max(pd$Position[pd$Chromosome == prev], na.rm = TRUE) * 1.05
990
  }
@@ -1071,7 +1085,7 @@ make_plotly_manhattan <- function(scan_df, lod_threshold = 2.0, peaks_df = NULL,
1071
  offsets <- setNames(numeric(length(chroms)), chroms)
1072
  for (i in seq_along(chroms)) {
1073
  if (i == 1) { offsets[chroms[1]] <- 0; next }
1074
- prev <- chroms[i-1]
1075
  offsets[chroms[i]] <- offsets[prev] +
1076
  max(pd$Position[pd$Chromosome == prev], na.rm = TRUE) * 1.05
1077
  }
@@ -1324,7 +1338,8 @@ ui <- fluidPage(
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(
@@ -1608,10 +1623,17 @@ 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(" 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"),
@@ -1621,7 +1643,7 @@ ui <- fluidPage(
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:"),
@@ -1634,7 +1656,7 @@ ui <- fluidPage(
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."
@@ -1676,7 +1698,7 @@ server <- function(input, output, session) {
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 })
@@ -1717,9 +1739,7 @@ server <- function(input, output, session) {
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
 
@@ -1791,7 +1811,6 @@ server <- function(input, output, session) {
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]])))
@@ -1832,7 +1851,6 @@ server <- function(input, output, session) {
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")
@@ -1848,11 +1866,10 @@ server <- function(input, output, session) {
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
 
@@ -1872,7 +1889,6 @@ server <- function(input, output, session) {
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) {
@@ -1888,18 +1904,15 @@ server <- function(input, output, session) {
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)
@@ -1935,12 +1948,9 @@ server <- function(input, output, session) {
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
@@ -1948,7 +1958,6 @@ server <- function(input, output, session) {
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(
@@ -1997,7 +2006,6 @@ server <- function(input, output, session) {
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
 
 
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"))
 
122
 
123
  # ============================================================
124
  # ROBUST TRAIN/VAL SPLIT
 
 
 
125
  # ============================================================
126
  safe_partition <- function(y, val_prop = 0.2) {
 
127
  valid_idx <- which(!is.na(y))
128
  n_valid <- length(valid_idx)
129
 
 
133
  "phenotype files match exactly (case-sensitive, no spaces)."))
134
  }
135
 
 
136
  min_val <- ceiling(n_valid * 0.10)
137
  max_val <- floor(n_valid * 0.40)
138
  n_val <- max(5, min(floor(n_valid * val_prop), max_val))
 
145
 
146
  cat(" Partition: n_valid=", n_valid, " n_train=", n_train, " n_val=", n_val, "\n")
147
 
 
148
  tr_idx <- tryCatch({
149
  y_valid <- y[valid_idx]
150
  ci <- caret::createDataPartition(y_valid, p = n_train / n_valid, list = FALSE)
 
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") {
170
  target_lod <- peak_lod - drop
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_,
178
+ marker_right = names(positions)[1]))
179
+ }
180
+
181
  for (i in seq(peak_idx, 2, by = -1)) {
182
+ if (is.na(lod_profile[i]) || is.na(lod_profile[i - 1])) next
183
+ if (lod_profile[i] >= target_lod && lod_profile[i - 1] < target_lod) {
184
+ lod1 <- lod_profile[i - 1]; lod2 <- lod_profile[i]
185
+ pos1 <- positions[i - 1]; pos2 <- positions[i]
186
  if (lod2 > lod1) {
187
  fraction <- (target_lod - lod1) / (lod2 - lod1)
188
  boundary_pos <- pos1 + fraction * (pos2 - pos1)
 
190
  boundary_pos <- pos1
191
  }
192
  return(list(position = boundary_pos,
193
+ marker_left = names(positions)[i - 1],
194
  marker_right = names(positions)[i]))
195
  }
196
  }
197
  return(list(position = positions[1],
198
  marker_left = NA_character_,
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],
206
+ marker_right = NA_character_))
207
+ }
208
+
209
+ for (i in seq(peak_idx, n - 1, by = 1)) {
210
+ if (is.na(lod_profile[i]) || is.na(lod_profile[i + 1])) next
211
+ if (lod_profile[i] >= target_lod && lod_profile[i + 1] < target_lod) {
212
+ lod1 <- lod_profile[i]; lod2 <- lod_profile[i + 1]
213
+ pos1 <- positions[i]; pos2 <- positions[i + 1]
214
  if (lod1 > lod2) {
215
  fraction <- (target_lod - lod2) / (lod1 - lod2)
216
  boundary_pos <- pos2 + (1 - fraction) * (pos2 - pos1)
 
219
  }
220
  return(list(position = boundary_pos,
221
  marker_left = names(positions)[i],
222
+ marker_right = names(positions)[i + 1]))
223
  }
224
  }
225
  return(list(position = positions[n],
 
253
  if (chr_df$LOD[1] >= lod_threshold && chr_df$LOD[1] >= chr_df$LOD[2]) is_peak[1] <- TRUE
254
  if (chr_df$LOD[2] >= lod_threshold && chr_df$LOD[2] > chr_df$LOD[1]) is_peak[2] <- TRUE
255
  } else {
256
+ for (i in 2:(n - 1)) {
257
  if (chr_df$LOD[i] >= lod_threshold &&
258
+ chr_df$LOD[i] > chr_df$LOD[i - 1] &&
259
+ chr_df$LOD[i] >= chr_df$LOD[i + 1]) is_peak[i] <- TRUE
260
  }
261
+ if (chr_df$LOD[1] >= lod_threshold && chr_df$LOD[1] > chr_df$LOD[2]) is_peak[1] <- TRUE
262
+ if (chr_df$LOD[n] >= lod_threshold && chr_df$LOD[n] > chr_df$LOD[n - 1]) is_peak[n] <- TRUE
263
  }
264
 
265
  peaks <- chr_df[is_peak, ]
 
373
 
374
  target_n <- length(header_row)
375
  if (ncol(gd) < target_n)
376
+ for (k in (ncol(gd) + 1):target_n) gd[[paste0("V", k)]] <- NA
377
  if (ncol(gd) > target_n) gd <- gd[, seq_len(target_n)]
378
 
379
  colnames(gd) <- header_row
 
380
  rownames(gd) <- make.unique(normalize_id(as.character(gd[, 1])))
381
  gd <- gd[, -1, drop = FALSE]
382
 
 
424
  if (!is.null(fit)) {
425
  cf <- coef(fit); se <- coef(summary(fit))
426
  a_eff <- cf["a_code"]; d_eff <- cf["d_code"]
427
+ se_a <- if ("a_code" %in% rownames(se)) se["a_code", "Std. Error"] else NA_real_
428
+ se_d <- if ("d_code" %in% rownames(se)) se["d_code", "Std. Error"] else NA_real_
429
  if (!is.na(a_eff) && abs(a_eff) > 1e-10) dom_ratio <- abs(d_eff / a_eff)
430
  dom_cl <- dom_class(a_eff, d_eff)
431
  }
 
434
  if (!is.null(fit)) {
435
  cf <- coef(fit); se <- coef(summary(fit))
436
  a_eff <- cf["a_code"]
437
+ se_a <- if ("a_code" %in% rownames(se)) se["a_code", "Std. Error"] else NA_real_
438
  d_eff <- 0; se_d <- 0; dom_ratio <- 0; dom_cl <- "Additive"
439
  }
440
  }
441
  list(a_eff = a_eff, se_a = se_a,
442
+ ci_lo = if (!is.na(a_eff) && !is.na(se_a)) a_eff - 1.96 * se_a else NA_real_,
443
+ ci_hi = if (!is.na(a_eff) && !is.na(se_a)) a_eff + 1.96 * se_a else NA_real_,
444
  d_eff = d_eff, se_d = se_d,
445
  dom_ratio = dom_ratio, dom_class = dom_cl)
446
  }
 
512
  if (!is.null(best_m) && best_lod > prev_lod + 0.5) {
513
  cofactors <- c(cofactors, best_m); remaining <- setdiff(remaining, best_m)
514
  prev_lod <- best_lod
515
+ cat(" Cofactor", length(cofactors), ":", best_m, " LOD:", round(best_lod, 2), "\n")
516
  } else break
517
  }
518
  cat(" Selected", length(cofactors), "cofactors\n")
 
547
  pv_cc <- df$y
548
 
549
  if (length(active_cof) > 0) {
550
+ fit_full <- lm(as.formula(paste("y ~ focal +", paste(active_cof, collapse = "+"))), data = df)
551
+ fit_null_cof <- lm(as.formula(paste("y ~", paste(active_cof, collapse = "+"))), data = df)
552
  lod <- calc_lod(fit_full, fit_null_cof)
553
  } else {
554
+ fit_full <- lm(y ~ focal, data = df)
555
+ fit_null_cof <- lm(y ~ 1, data = df)
556
  lod <- calc_lod(fit_full, fit_null_cof)
557
  }
558
 
559
  pve <- calc_pve_total(fit_full, pv_cc)
560
  ct <- coef(summary(fit_full))
561
  if (!"focal" %in% rownames(ct)) next
562
+ pval <- ct["focal", "Pr(>|t|)"]
563
  eff <- estimate_effects(gv, pv)
564
  res_list[[m]] <- data.frame(
565
  Marker=m, Chromosome=m_chr, Position=m_pos, LOD=lod, P_Value=pval,
 
643
  pv_cc <- df$y
644
 
645
  if (length(active_cof) > 0) {
646
+ fit_full <- lm(as.formula(paste("y ~ focal +", paste(active_cof, collapse = "+"))), data = df)
647
+ fit_null_cof <- lm(as.formula(paste("y ~", paste(active_cof, collapse = "+"))), data = df)
648
  lod <- calc_lod(fit_full, fit_null_cof)
649
  } else {
650
+ fit_full <- lm(y ~ focal, data = df)
651
+ fit_null_cof <- lm(y ~ 1, data = df)
652
  lod <- calc_lod(fit_full, fit_null_cof)
653
  }
654
 
655
  pve <- calc_pve_total(fit_full, pv_cc)
656
  ct <- coef(summary(fit_full))
657
  if (!"focal" %in% rownames(ct)) next
658
+ pval <- ct["focal", "Pr(>|t|)"]
659
  eff <- estimate_effects(gv, pv)
660
  res_list[[m]] <- data.frame(
661
  Marker=m, Chromosome=m_chr, Position=m_pos, LOD=lod, P_Value=pval,
 
998
  offsets <- setNames(numeric(length(chroms)), chroms)
999
  for (i in seq_along(chroms)) {
1000
  if (i == 1) { offsets[chroms[1]] <- 0; next }
1001
+ prev <- chroms[i - 1]
1002
  offsets[chroms[i]] <- offsets[prev] +
1003
  max(pd$Position[pd$Chromosome == prev], na.rm = TRUE) * 1.05
1004
  }
 
1085
  offsets <- setNames(numeric(length(chroms)), chroms)
1086
  for (i in seq_along(chroms)) {
1087
  if (i == 1) { offsets[chroms[1]] <- 0; next }
1088
+ prev <- chroms[i - 1]
1089
  offsets[chroms[i]] <- offsets[prev] +
1090
  max(pd$Position[pd$Chromosome == prev], na.rm = TRUE) * 1.05
1091
  }
 
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(
 
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"),
 
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:"),
 
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."
 
1698
  compare_res = list(),
1699
  compare_peaks = list(),
1700
  perm_threshold = NULL,
1701
+ diag_info = NULL
1702
  )
1703
 
1704
  lod_thr <- reactive({ input$lod_threshold })
 
1739
  if (is.null(rv$geno))
1740
  return(div(class="warn-box","Upload genotype and phenotype files to begin."))
1741
 
 
1742
  diag_msgs <- character(0)
 
1743
  n_geno <- nrow(rv$geno)
1744
  n_pheno <- if (!is.null(rv$pheno)) nrow(rv$pheno) else 0
1745
 
 
1811
  req(input$pheno_file)
1812
  tryCatch({
1813
  pd <- read.csv(input$pheno_file$datapath)
 
1814
  rownames(pd) <- make.unique(normalize_id(as.character(pd[,1])))
1815
  pd <- pd[,-1,drop=FALSE]
1816
  for (col in colnames(pd)) pd[[col]] <- suppressWarnings(as.numeric(as.character(pd[[col]])))
 
1851
  showNotification(paste("Starting", input$mapping_method, "analysis..."), type="message")
1852
 
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")
 
1866
  return()
1867
  }
1868
 
1869
+ X <- rv$geno[cs, , drop=FALSE]
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
 
 
1889
  return()
1890
  }
1891
 
 
1892
  partition <- tryCatch(
1893
  safe_partition(y, val_prop = input$val_prop),
1894
  error = function(e) {
 
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
 
1914
  withProgress(message=paste("Running", input$mapping_method, "..."), value=0.1, {
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)
 
1948
  }
1949
  incProgress(0.15)
1950
 
 
1951
  nzv_i <- tryCatch(caret::nearZeroVar(X_tr), error=function(e) integer(0))
1952
  Xtr_rf <- if (length(nzv_i) > 0) X_tr[,-nzv_i,drop=FALSE] else X_tr
 
1953
  Xv_rf <- X_v[, intersect(colnames(Xtr_rf), colnames(X_v)), drop=FALSE]
 
1954
  missing_cols <- setdiff(colnames(Xtr_rf), colnames(Xv_rf))
1955
  if (length(missing_cols) > 0) {
1956
  for (mc in missing_cols) Xv_rf[[mc]] <- 0
 
1958
  }
1959
  rv$model_cols <- colnames(Xtr_rf)
1960
 
 
1961
  use_rf <- nrow(Xtr_rf) >= 20 && ncol(Xtr_rf) >= 2
1962
  fit <- if (use_rf) {
1963
  tryCatch(
 
2006
  }, error=function(e) {
2007
  showNotification(paste("Analysis error:", e$message), type="error", duration=10)
2008
  cat("ERROR:", e$message, "\n")
 
2009
  })
2010
  })
2011