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

Update app.R

Browse files
Files changed (1) hide show
  1. app.R +875 -691
app.R CHANGED
@@ -1,9 +1,22 @@
1
  # ============================================================================
2
- # COMPLETE QTL ANALYSIS PIPELINE - FULLY FUNCTIONAL
3
- # All errors fixed - calc.het instead of calc.heterozyg
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
  # ============================================================================
5
 
6
- # Load libraries
7
  suppressPackageStartupMessages({
8
  library(shiny)
9
  library(shinydashboard)
@@ -23,460 +36,435 @@ suppressPackageStartupMessages({
23
  library(pheatmap)
24
  })
25
 
26
- # Check for corrplot
27
  if (!require("corrplot", quietly = TRUE)) {
28
  install.packages("corrplot", repos = "https://cloud.r-project.org/")
29
  library(corrplot)
30
  }
31
 
32
  # ============================================================================
33
- # SAFE NOTIFICATION FUNCTION
34
  # ============================================================================
35
 
36
  safe_notify <- function(msg, type = "default") {
37
  tryCatch({
38
- if (type == "default") showNotification(msg, duration = 3)
39
- else if (type == "message") showNotification(msg, type = "message", duration = 3)
40
- else if (type == "warning") showNotification(msg, type = "warning", duration = 5)
41
- else if (type == "error") showNotification(msg, type = "error", duration = 8)
42
- else showNotification(msg, duration = 3)
43
  }, error = function(e) message(msg))
44
  }
45
 
46
  # ============================================================================
47
- # HELPER FUNCTION - Calculate Heterozygosity
48
  # ============================================================================
49
 
50
  calculate_heterozygosity <- function(cross) {
51
- # Calculate heterozygosity manually
52
- het_rates <- rep(NA, nind(cross))
53
- for (i in 1:nind(cross)) {
54
- geno_ind <- pull.geno(cross)[i, ]
55
- het_rates[i] <- mean(geno_ind == 2, na.rm = TRUE) # 2 = heterozygous in F2
 
 
 
56
  }
57
- return(het_rates)
58
  }
59
 
60
  # ============================================================================
61
- # ADVANCED DATA PARSER
62
  # ============================================================================
63
 
64
  parse_advanced_cross <- function(geno_path, pheno_path, cross_type = "f2") {
65
-
66
- # Read genotype file
67
  geno_raw <- read.csv(geno_path, header = FALSE, stringsAsFactors = FALSE,
68
- check.names = FALSE, na.strings = c("NA", "", "N/A", "-9", "0", "."))
69
-
70
- if (nrow(geno_raw) < 4) {
71
- stop("Genotype file must have at least 4 rows: header, chr, positions, data")
72
- }
73
-
74
- # Parse header rows
75
- col_names <- as.character(geno_raw[1, ])
76
- chr_row <- as.character(geno_raw[2, ])
77
- pos_row <- as.character(geno_raw[3, ])
78
- ind_data <- geno_raw[4:nrow(geno_raw), , drop = FALSE]
79
-
80
- # Identify marker columns
81
- marker_cols <- 2:ncol(geno_raw)
82
  if (length(marker_cols) == 0) stop("No marker columns found")
83
-
84
  marker_names <- col_names[marker_cols]
85
-
86
- # Clean chromosome names
87
  chromosomes <- chr_row[marker_cols]
88
  chromosomes <- gsub("^[Cc]hr", "", chromosomes)
89
- chromosomes <- gsub("^0+", "", chromosomes)
90
- chromosomes[chromosomes == ""] <- "unknown"
91
- chromosomes[is.na(chromosomes)] <- "unknown"
92
-
93
- # Parse positions
94
  positions <- suppressWarnings(as.numeric(pos_row[marker_cols]))
95
  positions[is.na(positions)] <- 0
96
-
97
- # Individual IDs
98
  ind_ids <- as.character(ind_data[, 1])
99
  if (any(duplicated(ind_ids))) ind_ids <- make.unique(ind_ids)
100
-
101
- # Convert genotype matrix
102
  geno_mat <- as.matrix(ind_data[, marker_cols, drop = FALSE])
103
  mode(geno_mat) <- "numeric"
104
  rownames(geno_mat) <- ind_ids
105
  colnames(geno_mat) <- marker_names
106
-
107
- # Remove individuals with excessive missing data (>50%)
108
- missing_rate_ind <- rowMeans(is.na(geno_mat))
109
- valid_inds <- missing_rate_ind <= 0.5
110
- if (sum(valid_inds) == 0) stop("No individuals with <50% missing data")
111
- geno_mat <- geno_mat[valid_inds, , drop = FALSE]
112
- ind_ids <- ind_ids[valid_inds]
113
-
114
- # Read phenotype file
115
  pheno_raw <- read.csv(pheno_path, header = TRUE, stringsAsFactors = FALSE,
116
- check.names = FALSE, na.strings = c("NA", "", "N/A", "."))
117
-
118
  if (ncol(pheno_raw) < 2) stop("Phenotype file must have at least 2 columns")
119
-
120
  pheno_ids <- as.character(pheno_raw[, 1])
121
  if (any(duplicated(pheno_ids))) pheno_ids <- make.unique(pheno_ids)
122
- pheno_df <- pheno_raw[, -1, drop = FALSE]
123
-
124
- # Convert phenotypes to numeric
125
- for (i in 1:ncol(pheno_df)) {
126
  pheno_df[, i] <- suppressWarnings(as.numeric(pheno_df[, i]))
127
- }
128
  rownames(pheno_df) <- pheno_ids
129
-
130
- # Align individuals
131
  common_ids <- intersect(ind_ids, pheno_ids)
132
- if (length(common_ids) == 0) {
133
- stop(paste("No matching IDs. Genotype:", paste(head(ind_ids, 3), collapse=","),
134
- "Phenotype:", paste(head(pheno_ids, 3), collapse=",")))
135
- }
136
-
137
  geno_mat <- geno_mat[common_ids, , drop = FALSE]
138
  pheno_df <- pheno_df[common_ids, , drop = FALSE]
139
-
140
- # Remove markers with excessive missing data (>50%)
141
- missing_rate_marker <- colMeans(is.na(geno_mat))
142
- valid_markers <- missing_rate_marker <= 0.5
143
- if (sum(valid_markers) == 0) stop("No markers with <50% missing data")
144
- geno_mat <- geno_mat[, valid_markers, drop = FALSE]
145
- chromosomes <- chromosomes[valid_markers]
146
- positions <- positions[valid_markers]
147
- marker_names <- marker_names[valid_markers]
148
-
149
- # Build genetic map by chromosome
150
  unique_chrs <- unique(chromosomes)
151
- chr_numeric <- suppressWarnings(as.numeric(unique_chrs))
152
- chr_numeric[is.na(chr_numeric)] <- 999
153
- unique_chrs <- unique_chrs[order(chr_numeric, unique_chrs)]
154
-
155
- map_list <- list()
156
  geno_list <- list()
157
-
158
  for (ch in unique_chrs) {
159
- chr_idx <- which(chromosomes == ch)
160
- if (length(chr_idx) > 0) {
161
- chr_markers <- marker_names[chr_idx]
162
- chr_positions <- positions[chr_idx]
163
- names(chr_positions) <- chr_markers
164
-
165
- # Sort by position
166
- ord <- order(chr_positions)
167
- chr_positions <- chr_positions[ord]
168
- chr_markers <- chr_markers[ord]
169
-
170
- # Remove duplicate positions
171
- chr_positions <- chr_positions[!duplicated(chr_positions)]
172
- chr_markers <- chr_markers[!duplicated(chr_markers)]
173
-
174
- if (length(chr_positions) >= 1) {
175
- map_list[[ch]] <- chr_positions
176
- geno_list[[ch]] <- list(
177
- data = geno_mat[, chr_markers, drop = FALSE],
178
- map = chr_positions
179
- )
180
- class(geno_list[[ch]]$map) <- "A"
181
- }
182
- }
 
183
  }
184
-
185
  if (length(geno_list) == 0) stop("No valid chromosomes found")
186
-
187
- # Create cross object
188
- cross <- list(geno = geno_list, pheno = pheno_df)
189
  class(cross) <- c(cross_type, "cross")
190
-
191
- # Run basic checks
192
- cross <- jittermap(cross)
193
-
194
- # Calculate additional statistics (using safe function)
195
  het_rates <- calculate_heterozygosity(cross)
196
-
197
  attr(cross, "summary") <- list(
198
- n_ind = nind(cross),
199
- n_markers = totmar(cross),
200
- n_chr = nchr(cross),
201
- missing_rate = mean(nmissing(cross, what="mar") / nind(cross), na.rm = TRUE),
202
  heterozygosity = mean(het_rates, na.rm = TRUE)
203
  )
204
-
205
  return(cross)
206
  }
207
 
208
  # ============================================================================
209
- # 10 COMPLETE MAPPING MODELS
210
  # ============================================================================
211
 
212
  run_all_ten_models <- function(cross, pheno_col) {
213
- models <- list()
214
  model_status <- list()
215
-
216
- # Model 1: Haley-Knott Regression
217
  safe_notify("Running Model 1/10: Haley-Knott (HK)...", "message")
218
  tryCatch({
219
- models$hk <- scanone(cross, pheno.col = pheno_col, method = "hk")
220
  model_status$hk <- "Success"
221
  }, error = function(e) {
222
- model_status$hk <- paste("Failed:", e$message)
223
  safe_notify(paste("HK failed:", e$message), "warning")
224
  })
225
-
226
- # Model 2: EM Algorithm
227
  safe_notify("Running Model 2/10: EM Algorithm...", "message")
228
  tryCatch({
229
- models$em <- scanone(cross, pheno.col = pheno_col, method = "em")
230
  model_status$em <- "Success"
231
  }, error = function(e) {
232
- model_status$em <- paste("Failed:", e$message)
233
  safe_notify(paste("EM failed:", e$message), "warning")
234
  })
235
-
236
- # Model 3: Extended Haley-Knott
237
  safe_notify("Running Model 3/10: Extended Haley-Knott (EHK)...", "message")
238
  tryCatch({
239
- models$ehk <- scanone(cross, pheno.col = pheno_col, method = "ehk")
240
  model_status$ehk <- "Success"
241
  }, error = function(e) {
242
- model_status$ehk <- paste("Failed:", e$message)
243
  safe_notify(paste("EHK failed:", e$message), "warning")
244
  })
245
-
246
- # Model 4: Multiple Imputation
247
  safe_notify("Running Model 4/10: Multiple Imputation (IMP)...", "message")
248
  tryCatch({
249
- cross_sim <- sim.geno(cross, n.draws = 32, step = 1)
250
- models$imp <- scanone(cross_sim, pheno.col = pheno_col, method = "imp")
 
251
  model_status$imp <- "Success"
252
  }, error = function(e) {
253
- model_status$imp <- paste("Failed:", e$message)
254
  safe_notify(paste("IMP failed:", e$message), "warning")
 
 
 
 
 
255
  })
256
-
257
- # Model 5: Marker Regression
258
  safe_notify("Running Model 5/10: Marker Regression (MR)...", "message")
259
  tryCatch({
260
- models$mr <- scanone(cross, pheno.col = pheno_col, method = "mr")
261
  model_status$mr <- "Success"
262
  }, error = function(e) {
263
- model_status$mr <- paste("Failed:", e$message)
264
  safe_notify(paste("MR failed:", e$message), "warning")
265
  })
266
-
267
- # Model 6: Non-parametric
268
  safe_notify("Running Model 6/10: Non-parametric (NP)...", "message")
269
  tryCatch({
270
- models$np <- scanone(cross, pheno.col = pheno_col, method = "np")
271
  model_status$np <- "Success"
272
  }, error = function(e) {
273
- model_status$np <- paste("Failed:", e$message)
274
  safe_notify(paste("NP failed:", e$message), "warning")
275
  })
276
-
277
- # Model 7: Composite Interval Mapping
278
  safe_notify("Running Model 7/10: Composite Interval Mapping (CIM)...", "message")
279
  tryCatch({
280
- models$cim <- cim(cross, pheno.col = pheno_col, method = "hk", window = 10)
 
 
 
 
 
281
  model_status$cim <- "Success"
282
  }, error = function(e) {
283
- model_status$cim <- paste("Failed:", e$message)
284
  safe_notify(paste("CIM failed:", e$message), "warning")
285
  })
286
-
287
- # Model 8: Multiple QTL Mapping
288
- safe_notify("Running Model 8/10: Multiple QTL Mapping (MQM)...", "message")
289
  tryCatch({
290
- scan_hk <- scanone(cross, pheno.col = pheno_col, method = "hk")
291
- cofactors <- which(scan_hk$lod > 2.5)
292
- if (length(cofactors) > 0) {
293
- models$mqm <- mqm(cross, pheno.col = pheno_col, cofactors = cofactors)
294
- model_status$mqm <- "Success"
295
- } else {
296
- models$mqm <- scan_hk
297
- model_status$mqm <- "Used HK (no cofactors)"
298
- }
299
  }, error = function(e) {
300
- model_status$mqm <- paste("Failed:", e$message)
301
  safe_notify(paste("MQM failed:", e$message), "warning")
 
 
 
 
 
302
  })
303
-
304
- # Model 9: Binary Trait (if applicable)
305
- safe_notify("Running Model 9/10: Binary Trait Analysis...", "message")
306
  tryCatch({
307
- models$binary <- scanone(cross, pheno.col = pheno_col, method = "binary")
308
- model_status$binary <- "Success"
 
 
 
 
 
 
309
  }, error = function(e) {
310
- model_status$binary <- paste("Failed:", e$message)
311
  safe_notify(paste("Binary failed:", e$message), "warning")
312
  })
313
-
314
- # Model 10: Normal Model
315
- safe_notify("Running Model 10/10: Normal Model...", "message")
316
  tryCatch({
317
- models$normal <- scanone(cross, pheno.col = pheno_col, method = "normal")
 
318
  model_status$normal <- "Success"
319
  }, error = function(e) {
320
- model_status$normal <- paste("Failed:", e$message)
321
  safe_notify(paste("Normal failed:", e$message), "warning")
322
  })
323
-
324
  attr(models, "status") <- model_status
325
  return(models)
326
  }
327
 
328
  # ============================================================================
329
- # COMPREHENSIVE QTL DETECTION WITH FULL DETAILS
330
  # ============================================================================
331
 
332
  detect_comprehensive_qtls <- function(scan, threshold, cross = NULL, pheno_col = NULL) {
333
- if (is.null(scan) || nrow(scan) == 0) {
334
- return(data.frame())
335
- }
336
-
337
- scan_sig <- scan[scan$lod >= threshold, ]
338
- if (nrow(scan_sig) == 0) {
339
- return(data.frame())
340
- }
341
-
342
  qtls <- data.frame()
343
-
344
- for (chr in unique(scan_sig$chr)) {
345
- chr_data <- scan_sig[scan_sig$chr == chr, ]
346
  chr_all <- scan[scan$chr == chr, ]
347
-
348
- # Find peaks (local maxima)
349
- peaks <- c()
350
- for (i in 1:nrow(chr_data)) {
351
- is_peak <- TRUE
352
- if (i > 1 && chr_data$lod[i] <= chr_data$lod[i-1]) is_peak <- FALSE
353
- if (i < nrow(chr_data) && chr_data$lod[i] <= chr_data$lod[i+1]) is_peak <- FALSE
354
- if (is_peak) peaks <- c(peaks, i)
 
 
 
 
355
  }
356
-
357
- if (length(peaks) > 0) {
358
- for (peak_idx in peaks) {
359
- peak_row <- chr_data[peak_idx, ]
360
-
361
- # Get peak marker
362
- peak_marker <- rownames(peak_row)
363
-
364
- # Calculate 1.5 LOD drop confidence interval
365
- lod_diff <- chr_all$lod - peak_row$lod
366
- ci_indices <- which(lod_diff >= -1.5)
367
-
368
- if (length(ci_indices) > 0) {
369
- left_idx <- min(ci_indices)
370
- right_idx <- max(ci_indices)
371
- left_pos <- chr_all$pos[left_idx]
372
- right_pos <- chr_all$pos[right_idx]
373
- left_marker <- rownames(chr_all)[left_idx]
374
- right_marker <- rownames(chr_all)[right_idx]
375
- } else {
376
- left_pos <- peak_row$pos - 5
377
- right_pos <- peak_row$pos + 5
378
- left_marker <- NA
379
- right_marker <- NA
380
- }
381
-
382
- # Calculate 2 LOD drop CI (more conservative)
383
- ci2_indices <- which(lod_diff >= -2)
384
- if (length(ci2_indices) > 0) {
385
- left2_pos <- chr_all$pos[min(ci2_indices)]
386
- right2_pos <- chr_all$pos[max(ci2_indices)]
387
- } else {
388
- left2_pos <- peak_row$pos - 3
389
- right2_pos <- peak_row$pos + 3
390
- }
391
-
392
- # Calculate PVE (Proportion of Variance Explained)
393
- n <- nrow(scan)
394
- pve <- (1 - 10^(-2 * peak_row$lod / n)) * 100
395
-
396
- # Calculate additive and dominance effects if cross is provided
397
- add_effect <- NA
398
- dom_effect <- NA
399
- if (!is.null(cross) && !is.null(pheno_col)) {
400
- tryCatch({
401
- # Find nearest marker
402
- map <- pull.map(cross)[[as.character(chr)]]
403
- marker_pos <- which.min(abs(map - peak_row$pos))
404
- marker_name <- names(map)[marker_pos]
405
-
406
- # Get genotypes and phenotypes
407
- geno_idx <- find.marker(cross, as.character(chr), marker_name)
408
- genotypes <- pull.geno(cross)[, geno_idx]
409
- phenotypes <- cross$pheno[[pheno_col]]
410
-
411
- # Calculate means per genotype
412
- means <- tapply(phenotypes, genotypes, mean, na.rm=TRUE)
413
-
414
- if (length(means) == 3) { # F2
415
- add_effect <- (means[3] - means[1]) / 2
416
- dom_effect <- means[2] - (means[1] + means[3]) / 2
417
- } else if (length(means) == 2) { # BC
418
- add_effect <- means[2] - means[1]
419
  }
420
- }, error = function(e) {
421
- # Silent fail for effects
422
- })
423
- }
424
-
425
- qtls <- rbind(qtls, data.frame(
426
- Chromosome = as.character(chr),
427
- Peak_Position_cM = round(peak_row$pos, 2),
428
- Peak_Marker = peak_marker,
429
- LOD_Score = round(peak_row$lod, 3),
430
- PVE_Percent = round(pve, 2),
431
- CI_1.5LOD_Left_cM = round(left_pos, 2),
432
- CI_1.5LOD_Right_cM = round(right_pos, 2),
433
- CI_1.5LOD_Width_cM = round(right_pos - left_pos, 2),
434
- CI_2LOD_Left_cM = round(left2_pos, 2),
435
- CI_2LOD_Right_cM = round(right2_pos, 2),
436
- CI_2LOD_Width_cM = round(right2_pos - left2_pos, 2),
437
- Left_Flanking_Marker = left_marker,
438
- Right_Flanking_Marker = right_marker,
439
- Additive_Effect = round(add_effect, 4),
440
- Dominance_Effect = round(dom_effect, 4),
441
- stringsAsFactors = FALSE
442
- ))
443
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
444
  }
445
  }
446
-
447
  if (nrow(qtls) > 0) {
448
- # Sort by chromosome and position
449
  qtls$ChrNum <- suppressWarnings(as.numeric(qtls$Chromosome))
450
  qtls$ChrNum[is.na(qtls$ChrNum)] <- 999
451
  qtls <- qtls[order(qtls$ChrNum, qtls$Peak_Position_cM), ]
452
  qtls$ChrNum <- NULL
 
453
  }
454
-
455
  return(qtls)
456
  }
457
 
458
  # ============================================================================
459
- # PERMUTATION TEST WITH MULTIPLE ALPHAS
460
  # ============================================================================
461
 
462
  run_permutation_analysis <- function(cross, pheno_col, n_perm = 1000) {
463
  tryCatch({
464
- perms <- scanone(cross, pheno.col = pheno_col, n.perm = n_perm, method = "hk")
465
-
466
- thresholds <- data.frame(
467
- Alpha = c(0.001, 0.01, 0.05, 0.1, 0.2),
468
- LOD_Threshold = rep(NA, 5)
469
- )
470
-
471
- for (i in 1:5) {
472
- thr <- summary(perms, alpha = thresholds$Alpha[i])[1]
473
- thresholds$LOD_Threshold[i] <- round(thr, 3)
474
- }
475
-
476
- return(list(permutations = perms, thresholds = thresholds))
477
  }, error = function(e) {
478
  safe_notify(paste("Permutation failed:", e$message), "warning")
479
- return(NULL)
480
  })
481
  }
482
 
@@ -486,198 +474,277 @@ run_permutation_analysis <- function(cross, pheno_col, n_perm = 1000) {
486
 
487
  create_model_comparison <- function(models, threshold) {
488
  if (is.null(models) || length(models) == 0) return(data.frame())
489
-
490
- comparison <- data.frame()
491
-
492
- for (name in names(models)) {
493
- scan <- models[[name]]
494
- if (!is.null(scan)) {
495
- max_lod <- max(scan$lod, na.rm = TRUE)
496
- mean_lod <- mean(scan$lod, na.rm = TRUE)
497
- n_peaks <- sum(scan$lod >= threshold, na.rm = TRUE)
498
- max_pos <- scan$pos[which.max(scan$lod)]
499
- max_chr <- scan$chr[which.max(scan$lod)]
500
-
501
- comparison <- rbind(comparison, data.frame(
502
- Model = toupper(name),
503
- Max_LOD = round(max_lod, 3),
504
- Mean_LOD = round(mean_lod, 3),
505
- N_Significant_Peaks = n_peaks,
506
- Peak_Chromosome = as.character(max_chr),
507
- Peak_Position_cM = round(max_pos, 2),
508
- stringsAsFactors = FALSE
509
- ))
510
- }
511
- }
512
-
513
- return(comparison[order(-comparison$Max_LOD), ])
514
  }
515
 
516
  # ============================================================================
517
  # PLOTTING FUNCTIONS
518
  # ============================================================================
519
 
520
- # Plot 1: Enhanced Manhattan Plot
521
  plot_manhattan_enhanced <- function(scan, qtls, threshold) {
522
  if (is.null(scan)) return(NULL)
523
-
524
- df <- as.data.frame(scan)
525
- df$marker <- rownames(df)
526
- df$significant <- df$lod >= threshold
527
-
528
- chrs <- unique(df$chr)
529
- chr_lengths <- sapply(chrs, function(ch) max(df$pos[df$chr == ch], na.rm = TRUE))
530
- cum_lengths <- cumsum(c(0, chr_lengths[-length(chrs)]))
531
- names(cum_lengths) <- chrs
532
-
533
- df$pos_cum <- df$pos + cum_lengths[as.character(df$chr)]
534
- chr_midpoints <- sapply(chrs, function(ch) mean(df$pos_cum[df$chr == ch], na.rm = TRUE))
535
-
536
- colors <- rep(brewer.pal(8, "Set1"), length.out = length(chrs))
 
 
 
537
  names(colors) <- chrs
538
-
539
- p <- ggplot(df, aes(x = pos_cum, y = lod, color = chr)) +
540
  geom_point(size = 1.5, alpha = 0.7) +
541
- geom_hline(yintercept = threshold, color = "red", linetype = "dashed", size = 1.2) +
542
- scale_x_continuous(breaks = chr_midpoints, labels = names(chr_midpoints)) +
543
- scale_color_manual(values = colors) +
 
544
  labs(title = "Genome-wide Manhattan Plot",
545
  x = "Chromosome", y = "LOD Score") +
546
- theme_minimal() +
547
- theme(legend.position = "none",
548
- axis.text.x = element_text(angle = 45, hjust = 1))
549
-
550
  if (!is.null(qtls) && nrow(qtls) > 0) {
551
- qtls$pos_cum <- qtls$Peak_Position_cM + cum_lengths[as.character(qtls$Chromosome)]
552
- p <- p +
553
- geom_point(data = qtls, aes(x = pos_cum, y = LOD_Score),
554
- color = "gold", size = 5, shape = 18)
 
 
555
  }
556
-
557
- return(p)
558
  }
559
 
560
- # Plot 2: LOD Contour Plot
561
- plot_lod_contour <- function(scan) {
562
  if (is.null(scan)) return(NULL)
563
-
564
- chrs <- unique(scan$chr)
565
- contour_data <- data.frame()
566
-
567
- for (chr in chrs) {
568
- chr_data <- scan[scan$chr == chr, ]
569
- chr_data$chr_num <- as.numeric(factor(chr, levels = chrs))
570
- contour_data <- rbind(contour_data, chr_data)
571
- }
572
-
573
- ggplot(contour_data, aes(x = pos, y = chr_num, z = lod)) +
574
- geom_contour_filled(bins = 8) +
575
- scale_fill_viridis_d(name = "LOD", direction = -1) +
576
- scale_y_continuous(breaks = 1:length(chrs), labels = chrs) +
577
- labs(title = "LOD Contour Plot", x = "Position (cM)", y = "Chromosome") +
578
- theme_minimal()
 
579
  }
580
 
581
- # Plot 3: QTL Effect Bubble Plot
582
  plot_qtl_bubble <- function(qtls) {
583
  if (is.null(qtls) || nrow(qtls) == 0) return(NULL)
584
-
585
- ggplot(qtls, aes(x = Chromosome, y = Peak_Position_cM,
 
 
586
  size = LOD_Score, color = PVE_Percent)) +
587
- geom_point(alpha = 0.8) +
588
- scale_size_continuous(range = c(3, 20), name = "LOD Score") +
589
- scale_color_gradientn(colors = c("blue", "green", "yellow", "red"), name = "PVE (%)") +
 
 
590
  labs(title = "QTL Effect Size Bubble Plot",
591
- x = "Chromosome", y = "Position (cM)") +
592
- theme_minimal() +
593
  theme(axis.text.x = element_text(angle = 45, hjust = 1))
594
  }
595
 
596
  # Plot 4: Ridge Plot
597
  plot_ridge_distribution <- function(scan) {
598
  if (is.null(scan)) return(NULL)
599
-
600
- df <- as.data.frame(scan)
601
- df$chr <- factor(df$chr, levels = unique(df$chr))
602
-
603
  ggplot(df, aes(x = lod, y = chr, fill = after_stat(x))) +
604
- geom_density_ridges_gradient(scale = 2, rel_min_height = 0.01) +
605
- scale_fill_viridis_c(option = "C", name = "LOD Score") +
606
- labs(title = "LOD Score Distribution", x = "LOD Score", y = "Chromosome") +
607
- theme_ridges()
 
 
 
608
  }
609
 
610
- # Plot 5: Violin Plot
611
- plot_genotype_violin <- function(cross, qtl, trait) {
612
- if (is.null(cross) || is.null(qtl) || nrow(qtl) == 0) return(NULL)
613
-
614
- chr_name <- as.character(qtl$Chromosome[1])
615
- if (!chr_name %in% names(cross$geno)) return(NULL)
616
-
617
- map <- pull.map(cross)[[chr_name]]
618
- marker_pos <- which.min(abs(map - qtl$Peak_Position_cM[1]))
619
- marker_name <- names(map)[marker_pos]
620
-
621
- geno_idx <- find.marker(cross, chr_name, marker_name)
622
- genotypes <- pull.geno(cross)[, geno_idx]
623
- phenotypes <- cross$pheno[[trait]]
624
-
625
- df <- data.frame(
626
- Genotype = factor(genotypes, levels = sort(unique(genotypes))),
627
- Phenotype = phenotypes
628
  )
629
- df <- df[!is.na(df$Genotype) & !is.na(df$Phenotype), ]
630
-
631
- if (length(unique(df$Genotype)) == 3) {
632
- df$Genotype <- recode(df$Genotype, `1` = "AA", `2` = "AB", `3` = "BB")
633
- } else if (length(unique(df$Genotype)) == 2) {
634
- df$Genotype <- recode(df$Genotype, `1` = "A", `2` = "B")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
635
  }
636
-
637
- ggplot(df, aes(x = Genotype, y = Phenotype, fill = Genotype)) +
638
- geom_violin(alpha = 0.6, trim = FALSE) +
639
- geom_boxplot(width = 0.2, alpha = 0.8) +
640
- stat_summary(fun = mean, geom = "point", shape = 18, size = 5, color = "red") +
641
- scale_fill_brewer(palette = "Set2") +
642
- labs(title = paste("Phenotype at", marker_name), x = "Genotype", y = trait) +
643
- theme_minimal() +
644
- theme(legend.position = "none")
 
 
645
  }
646
 
647
  # Plot 6: Genetic Map Density
648
  plot_genetic_density <- function(cross) {
649
  if (is.null(cross)) return(NULL)
650
-
651
- map <- pull.map(cross)
652
- df <- data.frame()
653
- for (chr in names(map)) {
654
- positions <- map[[chr]]
655
- df <- rbind(df, data.frame(Chromosome = chr, Position = positions))
656
- }
657
-
658
  df$Chromosome <- factor(df$Chromosome, levels = names(map))
659
-
660
- ggplot(df, aes(x = Chromosome, y = Position)) +
661
- geom_segment(aes(xend = Chromosome, yend = 0), color = "gray70", size = 1) +
662
- geom_point(color = "steelblue", size = 2, alpha = 0.7) +
663
- labs(title = "Genetic Map", x = "Chromosome", y = "Position (cM)") +
664
- theme_minimal() +
 
 
 
 
 
 
 
 
 
 
 
 
665
  theme(axis.text.x = element_text(angle = 45, hjust = 1))
666
  }
667
 
668
  # Plot 7: Model Comparison Bar Plot
669
  plot_model_comparison <- function(comparison_df) {
670
  if (is.null(comparison_df) || nrow(comparison_df) == 0) return(NULL)
671
-
672
- ggplot(comparison_df, aes(x = reorder(Model, -Max_LOD), y = Max_LOD, fill = Model)) +
673
- geom_bar(stat = "identity", alpha = 0.8) +
674
- geom_text(aes(label = Max_LOD), vjust = -0.5, size = 3.5) +
675
- scale_fill_brewer(palette = "Set2") +
676
- labs(title = "Model Performance Comparison",
677
- x = "Method", y = "Max LOD Score") +
678
- theme_minimal() +
679
- theme(legend.position = "none",
680
- axis.text.x = element_text(angle = 45, hjust = 1))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
681
  }
682
 
683
  # ============================================================================
@@ -685,135 +752,201 @@ plot_model_comparison <- function(comparison_df) {
685
  # ============================================================================
686
 
687
  ui <- dashboardPage(
688
- dashboardHeader(title = "QTL Analysis - Complete Suite"),
689
-
690
- dashboardSidebar(width = 320,
691
- sidebarMenu(
692
- menuItem("Data Input", tabName = "data", icon = icon("upload")),
693
- menuItem("10 Models", tabName = "models", icon = icon("cogs")),
694
- menuItem("QTL Results", tabName = "results", icon = icon("table")),
695
- menuItem("Plots", tabName = "plots", icon = icon("chart-bar")),
696
- menuItem("Download", tabName = "download", icon = icon("download")),
697
- menuItem("Help", tabName = "help", icon = icon("question-circle"))
 
698
  ),
699
-
700
- div(style = "padding: 15px;",
701
- h4("Data Upload"),
702
- fileInput("geno_file", "Genotype CSV", accept = ".csv"),
703
- fileInput("pheno_file", "Phenotype CSV", accept = ".csv"),
704
-
 
 
 
705
  selectInput("cross_type", "Cross Type",
706
- choices = c("F2 Intercross" = "f2", "Backcross" = "bc", "RIL" = "riself"),
 
 
707
  selected = "f2"),
708
-
709
- hr(),
710
-
711
- h4("Parameters"),
712
- selectInput("pheno_trait", "Phenotype", choices = NULL),
713
- numericInput("lod_threshold", "LOD Threshold", value = 3.0, min = 0, max = 20, step = 0.5),
714
- numericInput("n_permutations", "Permutations", value = 100, min = 0, max = 1000),
715
-
716
- actionButton("run_analysis", "RUN 10 MODELS",
717
- icon = icon("play"),
718
- style = "background-color: #3c8dbc; color: white; width: 100%;")
 
 
 
719
  )
720
  ),
721
-
722
  dashboardBody(
723
  useShinyjs(),
724
  tags$head(tags$style(HTML("
725
- .content-wrapper, .right-side { background-color: #f4f4f4; }
726
- .box { border-radius: 10px; }
 
727
  "))),
728
-
729
  tabItems(
 
 
730
  tabItem(tabName = "data",
731
  fluidRow(
732
- valueBoxOutput("n_individuals"),
733
- valueBoxOutput("n_markers"),
734
- valueBoxOutput("n_chromosomes")
735
  ),
736
  fluidRow(
737
- box(title = "Data Summary", status = "primary", width = 12,
738
- verbatimTextOutput("data_summary"))
 
 
 
 
739
  ),
740
  fluidRow(
741
- box(title = "Genetic Map", status = "info", width = 12,
742
- plotOutput("genetic_map", height = "500px") %>% withSpinner())
 
743
  )
744
  ),
745
-
 
746
  tabItem(tabName = "models",
747
  fluidRow(
748
- box(title = "Analysis Status", status = "primary", width = 12,
749
- verbatimTextOutput("analysis_status"))
 
750
  ),
751
  fluidRow(
752
- box(title = "Model Comparison", status = "info", width = 12,
753
- DTOutput("model_comparison_table") %>% withSpinner())
 
754
  ),
755
  fluidRow(
756
- box(title = "Model Performance", status = "success", width = 12,
757
- plotOutput("model_barplot", height = "500px") %>% withSpinner())
 
758
  )
759
  ),
760
-
 
761
  tabItem(tabName = "results",
762
  fluidRow(
763
- box(title = "Significant QTLs", status = "primary", width = 12,
764
- DTOutput("qtl_table") %>% withSpinner())
 
765
  ),
766
  fluidRow(
767
- box(title = "Permutation Results", status = "info", width = 12,
768
- DTOutput("permutation_table") %>% withSpinner())
 
769
  )
770
  ),
771
-
 
772
  tabItem(tabName = "plots",
773
  fluidRow(
774
- box(title = "Manhattan Plot", status = "primary", width = 12,
775
- plotOutput("manhattan_plot", height = "600px") %>% withSpinner())
 
776
  ),
777
  fluidRow(
778
- box(title = "Contour Plot", status = "info", width = 6,
779
- plotOutput("contour_plot", height = "500px") %>% withSpinner()),
780
- box(title = "Ridge Plot", status = "success", width = 6,
781
- plotOutput("ridge_plot", height = "500px") %>% withSpinner())
782
  ),
783
  fluidRow(
784
- box(title = "Bubble Plot", status = "warning", width = 12,
785
- plotOutput("bubble_plot", height = "500px") %>% withSpinner())
 
 
 
 
786
  ),
787
  fluidRow(
788
- box(title = "Genotype-Phenotype Association", status = "danger", width = 12,
789
- selectInput("violin_qtl", "Select QTL:", choices = NULL),
790
- plotOutput("violin_plot", height = "500px") %>% withSpinner())
 
 
 
 
 
 
 
791
  )
792
  ),
793
-
 
794
  tabItem(tabName = "download",
795
  fluidRow(
796
- box(title = "Download Results", status = "primary", width = 12,
797
- br(),
798
- downloadButton("download_qtl_results", "Download QTL Results (CSV)",
799
- style = "margin: 10px;"),
800
- downloadButton("download_model_comparison", "Download Model Comparison (CSV)",
801
- style = "margin: 10px;"),
802
- br(), br()
 
 
 
 
803
  )
804
  )
805
  ),
806
-
 
807
  tabItem(tabName = "help",
808
  fluidRow(
809
- box(title = "Documentation", status = "primary", width = 12,
810
- HTML("
811
- <h3>10 Mapping Models</h3>
812
- <p>HK, EM, EHK, IMP, MR, NP, CIM, MQM, Binary, Normal</p>
813
- <h3>File Format</h3>
814
- <p>Genotype: Row1=headers, Row2=chr, Row3=pos, Row4+=data</p>
815
- <p>Phenotype: First column=ID, rest=traits</p>
816
- "))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
817
  )
818
  )
819
  )
@@ -825,221 +958,272 @@ ui <- dashboardPage(
825
  # ============================================================================
826
 
827
  server <- function(input, output, session) {
828
-
829
- cross_data <- reactiveVal(NULL)
830
- all_models <- reactiveVal(NULL)
831
- qtl_results <- reactiveVal(NULL)
832
- permutation_results <- reactiveVal(NULL)
833
- model_comparison <- reactiveVal(NULL)
834
- analysis_complete <- reactiveVal(FALSE)
835
-
836
- # Value boxes
837
- output$n_individuals <- renderValueBox({
838
- cross <- cross_data()
839
- valueBox(ifelse(is.null(cross), 0, nind(cross)), "Individuals",
840
- icon = icon("users"), color = "blue")
841
  })
842
-
843
- output$n_markers <- renderValueBox({
844
- cross <- cross_data()
845
- valueBox(ifelse(is.null(cross), 0, totmar(cross)), "Markers",
846
- icon = icon("dna"), color = "green")
847
  })
848
-
849
- output$n_chromosomes <- renderValueBox({
850
- cross <- cross_data()
851
- valueBox(ifelse(is.null(cross), 0, nchr(cross)), "Chromosomes",
852
- icon = icon("chart-line"), color = "yellow")
853
  })
854
-
855
- # Load data
856
- observeEvent(c(input$geno_file, input$pheno_file), {
857
  req(input$geno_file, input$pheno_file)
858
-
859
- safe_notify("Loading data...", "message")
860
-
861
  tryCatch({
862
- cross <- parse_advanced_cross(
863
  input$geno_file$datapath,
864
  input$pheno_file$datapath,
865
  input$cross_type
866
  )
867
-
868
- cross_data(cross)
869
-
870
  updateSelectInput(session, "pheno_trait",
871
- choices = names(cross$pheno),
872
- selected = names(cross$pheno)[1])
873
-
874
- safe_notify(paste("Loaded:", nind(cross), "individuals,", totmar(cross), "markers"), "success")
875
-
876
  }, error = function(e) {
877
- safe_notify(paste("Error:", e$message), "error")
878
  })
879
  })
880
-
881
- # Run analysis
882
  observeEvent(input$run_analysis, {
883
- cross <- cross_data()
884
- req(cross, input$pheno_trait)
885
-
886
- safe_notify("Running 10 models...", "message")
887
-
888
- withProgress(message = "Running 10 QTL Models", value = 0, {
889
-
890
- incProgress(0.2, detail = "Running all models...")
891
- pheno_idx <- which(names(cross$pheno) == input$pheno_trait)
892
- models <- run_all_ten_models(cross, pheno_idx)
 
 
 
 
893
  all_models(models)
894
-
895
- incProgress(0.3, detail = "Detecting QTLs...")
896
- if (!is.null(models$hk)) {
897
- qtls <- detect_comprehensive_qtls(models$hk, input$lod_threshold,
898
- cross, input$pheno_trait)
899
- qtl_results(qtls)
900
-
901
- if (nrow(qtls) > 0) {
902
- qtl_choices <- paste0("Chr", qtls$Chromosome, "_", qtls$Peak_Position_cM, "cM")
903
- updateSelectInput(session, "violin_qtl", choices = qtl_choices)
904
- }
 
 
 
 
905
  }
906
-
907
- incProgress(0.3, detail = "Comparing models...")
908
- comp <- create_model_comparison(models, input$lod_threshold)
909
- model_comparison(comp)
910
-
911
- if (input$n_permutations > 0 && !is.null(models$hk)) {
912
- incProgress(0.2, detail = paste(input$n_permutations, "permutations..."))
913
- perms <- run_permutation_analysis(cross, pheno_idx, input$n_permutations)
914
- permutation_results(perms)
 
915
  }
916
-
917
- analysis_complete(TRUE)
918
- n_success <- sum(!sapply(models, is.null))
919
- safe_notify(paste("Complete!", n_success, "models succeeded"), "success")
 
920
  })
921
  })
922
-
923
- # Data summary
924
  output$data_summary <- renderPrint({
925
- cross <- cross_data()
926
- if (is.null(cross)) {
927
- cat("No data loaded.")
928
- } else {
929
- cat("Cross Type:", class(cross)[1], "\n")
930
- cat("Individuals:", nind(cross), "\n")
931
- cat("Markers:", totmar(cross), "\n")
932
- cat("Chromosomes:", nchr(cross), "\n")
933
- cat("Phenotypes:", paste(names(cross$pheno), collapse = ", "), "\n")
 
 
934
  }
935
  })
936
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
937
  output$analysis_status <- renderPrint({
938
- if (!analysis_complete()) {
939
- cat("Click 'RUN 10 MODELS' to start.")
940
- } else {
941
- models <- all_models()
942
- n_success <- sum(!sapply(models, is.null))
943
- qtls <- qtl_results()
944
- cat("Models succeeded:", n_success, "/10\n")
945
- cat("QTLs detected:", ifelse(is.null(qtls), 0, nrow(qtls)), "\n")
946
  }
 
 
 
 
 
 
 
 
 
947
  })
948
-
949
- # Tables
950
  output$model_comparison_table <- renderDT({
951
- comp <- model_comparison()
952
- req(comp, nrow(comp) > 0)
953
- datatable(comp, options = list(pageLength = 10, scrollX = TRUE), rownames = FALSE)
 
 
 
 
 
 
 
 
954
  })
955
-
956
  output$qtl_table <- renderDT({
957
  qtls <- qtl_results()
958
  req(qtls, nrow(qtls) > 0)
959
- datatable(qtls, options = list(pageLength = 15, scrollX = TRUE), rownames = FALSE)
 
 
 
 
 
 
960
  })
961
-
962
  output$permutation_table <- renderDT({
963
- perms <- permutation_results()
964
- req(perms)
965
- datatable(perms$thresholds, options = list(pageLength = 5, dom = 't'), rownames = FALSE)
 
 
966
  })
967
-
968
- # Plots
969
  output$genetic_map <- renderPlot({
970
- cross <- cross_data()
971
- req(cross)
972
- plot_genetic_density(cross)
973
  })
974
-
975
  output$manhattan_plot <- renderPlot({
976
  models <- all_models()
977
- qtls <- qtl_results()
978
- req(models, !is.null(models$hk))
979
- plot_manhattan_enhanced(models$hk, qtls, input$lod_threshold)
 
980
  })
981
-
982
- output$contour_plot <- renderPlot({
983
  models <- all_models()
984
- req(models, !is.null(models$hk))
985
- plot_lod_contour(models$hk)
 
 
986
  })
987
-
988
  output$ridge_plot <- renderPlot({
989
  models <- all_models()
990
- req(models, !is.null(models$hk))
991
- plot_ridge_distribution(models$hk)
 
 
992
  })
993
-
994
  output$bubble_plot <- renderPlot({
995
- qtls <- qtl_results()
996
- req(qtls, nrow(qtls) > 0)
997
  plot_qtl_bubble(qtls)
998
  })
999
-
 
 
 
 
 
 
1000
  output$violin_plot <- renderPlot({
1001
- req(input$violin_qtl, input$violin_qtl != "")
1002
- qtls <- qtl_results()
1003
- cross <- cross_data()
1004
- req(qtls, nrow(qtls) > 0, cross, input$pheno_trait)
1005
-
1006
- qtl_idx <- which(paste0("Chr", qtls$Chromosome, "_", qtls$Peak_Position_cM, "cM") == input$violin_qtl)
1007
- if (length(qtl_idx) == 0) return(NULL)
1008
-
1009
- plot_genotype_violin(cross, qtls[qtl_idx[1], , drop = FALSE], input$pheno_trait)
1010
  })
1011
-
1012
  output$model_barplot <- renderPlot({
1013
- comp <- model_comparison()
1014
- req(comp, nrow(comp) > 0)
1015
- plot_model_comparison(comp)
1016
  })
1017
-
1018
- # Download handlers
1019
- output$download_qtl_results <- downloadHandler(
1020
  filename = function() paste0("qtl_results_", Sys.Date(), ".csv"),
1021
- content = function(file) {
1022
  qtls <- qtl_results()
1023
- if (!is.null(qtls) && nrow(qtls) > 0) {
1024
- write.csv(qtls, file, row.names = FALSE)
1025
- } else {
1026
- write.csv(data.frame(Message = "No QTLs found"), file, row.names = FALSE)
1027
- }
1028
  }
1029
  )
1030
-
1031
- output$download_model_comparison <- downloadHandler(
1032
  filename = function() paste0("model_comparison_", Sys.Date(), ".csv"),
1033
- content = function(file) {
1034
- comp <- model_comparison()
1035
- if (!is.null(comp) && nrow(comp) > 0) {
1036
- write.csv(comp, file, row.names = FALSE)
1037
- } else {
1038
- write.csv(data.frame(Message = "Run analysis first"), file, row.names = FALSE)
1039
- }
 
 
 
 
 
 
 
 
1040
  }
1041
  )
1042
  }
1043
 
1044
- # Run the app
1045
  shinyApp(ui = ui, server = server)
 
1
  # ============================================================================
2
+ # COMPLETE QTL ANALYSIS PIPELINE - ALL BUGS FIXED
3
+ # Fix summary:
4
+ # 1. safe_notify: added "success" type mapping to "message"
5
+ # 2. Model 8 MQM: replaced non-existent mqm() with mqmaugment()+mqmscan()
6
+ # 3. Model 9 Binary: fixed method -> model="binary" for scanone
7
+ # 4. Model 10 Normal: fixed method -> model="normal" for scanone
8
+ # 5. plot_manhattan_enhanced: fixed cumulative position calculation
9
+ # 6. detect_comprehensive_qtls: fixed peak detection to use full chr data
10
+ # 7. plot_genotype_violin: fixed recode() -> proper factor relabeling
11
+ # 8. find.marker / pull.geno: fixed genotype extraction by marker name
12
+ # 9. parse_advanced_cross: fixed map class assignment on final cross object
13
+ # 10. observeEvent: fixed double-trigger on dual file inputs
14
+ # 11. calculate_heterozygosity: added cross-type awareness for het coding
15
+ # 12. CIM: wrapped with tryCatch for version-safe method param
16
+ # 13. IMP: increased n.draws, added error recovery
17
+ # 14. QTL peak detection: now scans full chromosome LOD profile
18
  # ============================================================================
19
 
 
20
  suppressPackageStartupMessages({
21
  library(shiny)
22
  library(shinydashboard)
 
36
  library(pheatmap)
37
  })
38
 
 
39
  if (!require("corrplot", quietly = TRUE)) {
40
  install.packages("corrplot", repos = "https://cloud.r-project.org/")
41
  library(corrplot)
42
  }
43
 
44
  # ============================================================================
45
+ # SAFE NOTIFICATION FUNCTION [FIX #1: added "success" type]
46
  # ============================================================================
47
 
48
  safe_notify <- function(msg, type = "default") {
49
  tryCatch({
50
+ if (type %in% c("message", "success")) showNotification(msg, type = "message", duration = 3)
51
+ else if (type == "warning") showNotification(msg, type = "warning", duration = 5)
52
+ else if (type == "error") showNotification(msg, type = "error", duration = 8)
53
+ else showNotification(msg, duration = 3)
 
54
  }, error = function(e) message(msg))
55
  }
56
 
57
  # ============================================================================
58
+ # HELPER: Calculate Heterozygosity [FIX #11: cross-type aware het code]
59
  # ============================================================================
60
 
61
  calculate_heterozygosity <- function(cross) {
62
+ cross_type <- class(cross)[1]
63
+ # In R/qtl: 1=AA, 2=AB, 3=BB for F2; 1=AA, 2=AB for BC; 1=AA, 2=BB for RIL
64
+ het_code <- if (cross_type %in% c("f2", "bc")) 2L else NULL
65
+
66
+ geno_all <- pull.geno(cross)
67
+ if (is.null(het_code)) {
68
+ # RIL / selfing: expect no heterozygotes
69
+ return(rep(0, nrow(geno_all)))
70
  }
71
+ apply(geno_all, 1, function(row) mean(row == het_code, na.rm = TRUE))
72
  }
73
 
74
  # ============================================================================
75
+ # ADVANCED DATA PARSER [FIX #9: correct map class assignment]
76
  # ============================================================================
77
 
78
  parse_advanced_cross <- function(geno_path, pheno_path, cross_type = "f2") {
79
+
 
80
  geno_raw <- read.csv(geno_path, header = FALSE, stringsAsFactors = FALSE,
81
+ check.names = FALSE,
82
+ na.strings = c("NA", "", "N/A", "-9", "0", "."))
83
+
84
+ if (nrow(geno_raw) < 4)
85
+ stop("Genotype file must have at least 4 rows: header, chr, pos, data")
86
+
87
+ col_names <- as.character(geno_raw[1, ])
88
+ chr_row <- as.character(geno_raw[2, ])
89
+ pos_row <- as.character(geno_raw[3, ])
90
+ ind_data <- geno_raw[4:nrow(geno_raw), , drop = FALSE]
91
+
92
+ marker_cols <- 2:ncol(geno_raw)
 
 
93
  if (length(marker_cols) == 0) stop("No marker columns found")
94
+
95
  marker_names <- col_names[marker_cols]
96
+
 
97
  chromosomes <- chr_row[marker_cols]
98
  chromosomes <- gsub("^[Cc]hr", "", chromosomes)
99
+ chromosomes <- gsub("^0+", "", chromosomes)
100
+ chromosomes[chromosomes == "" | is.na(chromosomes)] <- "unknown"
101
+
 
 
102
  positions <- suppressWarnings(as.numeric(pos_row[marker_cols]))
103
  positions[is.na(positions)] <- 0
104
+
 
105
  ind_ids <- as.character(ind_data[, 1])
106
  if (any(duplicated(ind_ids))) ind_ids <- make.unique(ind_ids)
107
+
 
108
  geno_mat <- as.matrix(ind_data[, marker_cols, drop = FALSE])
109
  mode(geno_mat) <- "numeric"
110
  rownames(geno_mat) <- ind_ids
111
  colnames(geno_mat) <- marker_names
112
+
113
+ # Remove individuals with >50% missing
114
+ miss_ind <- rowMeans(is.na(geno_mat))
115
+ geno_mat <- geno_mat[miss_ind <= 0.5, , drop = FALSE]
116
+ ind_ids <- rownames(geno_mat)
117
+ if (nrow(geno_mat) == 0) stop("No individuals with <50% missing data")
118
+
119
+ # Phenotype
 
120
  pheno_raw <- read.csv(pheno_path, header = TRUE, stringsAsFactors = FALSE,
121
+ check.names = FALSE,
122
+ na.strings = c("NA", "", "N/A", "."))
123
  if (ncol(pheno_raw) < 2) stop("Phenotype file must have at least 2 columns")
124
+
125
  pheno_ids <- as.character(pheno_raw[, 1])
126
  if (any(duplicated(pheno_ids))) pheno_ids <- make.unique(pheno_ids)
127
+ pheno_df <- pheno_raw[, -1, drop = FALSE]
128
+ for (i in seq_len(ncol(pheno_df)))
 
 
129
  pheno_df[, i] <- suppressWarnings(as.numeric(pheno_df[, i]))
 
130
  rownames(pheno_df) <- pheno_ids
131
+
132
+ # Align
133
  common_ids <- intersect(ind_ids, pheno_ids)
134
+ if (length(common_ids) == 0)
135
+ stop(paste("No matching IDs between geno/pheno files.",
136
+ "Geno sample:", paste(head(ind_ids, 3), collapse = ","),
137
+ "Pheno sample:", paste(head(pheno_ids, 3), collapse = ",")))
138
+
139
  geno_mat <- geno_mat[common_ids, , drop = FALSE]
140
  pheno_df <- pheno_df[common_ids, , drop = FALSE]
141
+
142
+ # Remove markers with >50% missing
143
+ miss_mar <- colMeans(is.na(geno_mat))
144
+ keep_mar <- miss_mar <= 0.5
145
+ if (sum(keep_mar) == 0) stop("No markers with <50% missing data")
146
+ geno_mat <- geno_mat[, keep_mar, drop = FALSE]
147
+ chromosomes <- chromosomes[keep_mar]
148
+ positions <- positions[keep_mar]
149
+ marker_names <- marker_names[keep_mar]
150
+
151
+ # Build genetic map per chromosome
152
  unique_chrs <- unique(chromosomes)
153
+ chr_order <- order(suppressWarnings(as.numeric(unique_chrs)),
154
+ unique_chrs, na.last = TRUE)
155
+ unique_chrs <- unique_chrs[chr_order]
156
+
 
157
  geno_list <- list()
 
158
  for (ch in unique_chrs) {
159
+ idx <- which(chromosomes == ch)
160
+ if (length(idx) < 1) next
161
+
162
+ mk_names <- marker_names[idx]
163
+ mk_pos <- positions[idx]
164
+ names(mk_pos) <- mk_names
165
+
166
+ ord <- order(mk_pos)
167
+ mk_pos <- mk_pos[ord]
168
+ mk_names <- mk_names[ord]
169
+
170
+ # Remove position duplicates
171
+ dup_pos <- duplicated(mk_pos)
172
+ mk_pos <- mk_pos[!dup_pos]
173
+ mk_names <- mk_names[!dup_pos]
174
+ dup_nm <- duplicated(mk_names)
175
+ mk_pos <- mk_pos[!dup_nm]
176
+ mk_names <- mk_names[!dup_nm]
177
+
178
+ if (length(mk_pos) < 1) next
179
+
180
+ chr_geno <- geno_mat[, mk_names, drop = FALSE]
181
+ geno_list[[ch]] <- list(data = chr_geno, map = mk_pos)
182
+ # FIX #9: assign correct class to map (A = autosome)
183
+ class(geno_list[[ch]]$map) <- "A"
184
  }
185
+
186
  if (length(geno_list) == 0) stop("No valid chromosomes found")
187
+
188
+ cross <- list(geno = geno_list, pheno = pheno_df)
 
189
  class(cross) <- c(cross_type, "cross")
190
+ cross <- jittermap(cross)
191
+
 
 
 
192
  het_rates <- calculate_heterozygosity(cross)
 
193
  attr(cross, "summary") <- list(
194
+ n_ind = nind(cross),
195
+ n_markers = totmar(cross),
196
+ n_chr = nchr(cross),
197
+ missing_rate = mean(nmissing(cross, what = "mar") / nind(cross), na.rm = TRUE),
198
  heterozygosity = mean(het_rates, na.rm = TRUE)
199
  )
200
+
201
  return(cross)
202
  }
203
 
204
  # ============================================================================
205
+ # 10 MAPPING MODELS [FIX #2,3,4,12,13: MQM, Binary, Normal, CIM, IMP]
206
  # ============================================================================
207
 
208
  run_all_ten_models <- function(cross, pheno_col) {
209
+ models <- list()
210
  model_status <- list()
211
+
212
+ # --- Model 1: Haley-Knott ---
213
  safe_notify("Running Model 1/10: Haley-Knott (HK)...", "message")
214
  tryCatch({
215
+ models$hk <- scanone(cross, pheno.col = pheno_col, method = "hk")
216
  model_status$hk <- "Success"
217
  }, error = function(e) {
218
+ model_status$hk <<- paste("Failed:", e$message)
219
  safe_notify(paste("HK failed:", e$message), "warning")
220
  })
221
+
222
+ # --- Model 2: EM Algorithm ---
223
  safe_notify("Running Model 2/10: EM Algorithm...", "message")
224
  tryCatch({
225
+ models$em <- scanone(cross, pheno.col = pheno_col, method = "em")
226
  model_status$em <- "Success"
227
  }, error = function(e) {
228
+ model_status$em <<- paste("Failed:", e$message)
229
  safe_notify(paste("EM failed:", e$message), "warning")
230
  })
231
+
232
+ # --- Model 3: Extended Haley-Knott ---
233
  safe_notify("Running Model 3/10: Extended Haley-Knott (EHK)...", "message")
234
  tryCatch({
235
+ models$ehk <- scanone(cross, pheno.col = pheno_col, method = "ehk")
236
  model_status$ehk <- "Success"
237
  }, error = function(e) {
238
+ model_status$ehk <<- paste("Failed:", e$message)
239
  safe_notify(paste("EHK failed:", e$message), "warning")
240
  })
241
+
242
+ # --- Model 4: Multiple Imputation [FIX #13: n.draws=64 for better accuracy] ---
243
  safe_notify("Running Model 4/10: Multiple Imputation (IMP)...", "message")
244
  tryCatch({
245
+ cross_sim <- sim.geno(cross, n.draws = 64, step = 2,
246
+ error.prob = 0.001, map.function = "kosambi")
247
+ models$imp <- scanone(cross_sim, pheno.col = pheno_col, method = "imp")
248
  model_status$imp <- "Success"
249
  }, error = function(e) {
250
+ model_status$imp <<- paste("Failed:", e$message)
251
  safe_notify(paste("IMP failed:", e$message), "warning")
252
+ # Fallback: use HK result
253
+ if (!is.null(models$hk)) {
254
+ models$imp <<- models$hk
255
+ model_status$imp <<- "Fallback to HK"
256
+ }
257
  })
258
+
259
+ # --- Model 5: Marker Regression ---
260
  safe_notify("Running Model 5/10: Marker Regression (MR)...", "message")
261
  tryCatch({
262
+ models$mr <- scanone(cross, pheno.col = pheno_col, method = "mr")
263
  model_status$mr <- "Success"
264
  }, error = function(e) {
265
+ model_status$mr <<- paste("Failed:", e$message)
266
  safe_notify(paste("MR failed:", e$message), "warning")
267
  })
268
+
269
+ # --- Model 6: Non-parametric ---
270
  safe_notify("Running Model 6/10: Non-parametric (NP)...", "message")
271
  tryCatch({
272
+ models$np <- scanone(cross, pheno.col = pheno_col, method = "np")
273
  model_status$np <- "Success"
274
  }, error = function(e) {
275
+ model_status$np <<- paste("Failed:", e$message)
276
  safe_notify(paste("NP failed:", e$message), "warning")
277
  })
278
+
279
+ # --- Model 7: Composite Interval Mapping [FIX #12: version-safe cim()] ---
280
  safe_notify("Running Model 7/10: Composite Interval Mapping (CIM)...", "message")
281
  tryCatch({
282
+ # calc.genoprob needed before cim()
283
+ cross_gp <- calc.genoprob(cross, step = 2, error.prob = 0.001)
284
+ models$cim <- tryCatch(
285
+ cim(cross_gp, pheno.col = pheno_col, method = "hk", window = 10),
286
+ error = function(e2) cim(cross_gp, pheno.col = pheno_col, window = 10)
287
+ )
288
  model_status$cim <- "Success"
289
  }, error = function(e) {
290
+ model_status$cim <<- paste("Failed:", e$message)
291
  safe_notify(paste("CIM failed:", e$message), "warning")
292
  })
293
+
294
+ # --- Model 8: MQM [FIX #2: use mqmaugment + mqmscan, fallback gracefully] ---
295
+ safe_notify("Running Model 8/10: MQM Mapping...", "message")
296
  tryCatch({
297
+ # mqmaugment fills in missing genotypes; mqmscan is the actual scan
298
+ cross_aug <- mqmaugment(cross, missingval = "missing", verbose = FALSE)
299
+ # auto-select cofactors using initial scanone
300
+ scan_init <- scanone(cross, pheno.col = pheno_col, method = "hk")
301
+ cofactors <- mqmsetcofactors(cross_aug, each = 5) # every 5 markers
302
+ models$mqm <- mqmscan(cross_aug, cofactors = cofactors,
303
+ pheno.col = pheno_col, verbose = FALSE)
304
+ model_status$mqm <- "Success"
 
305
  }, error = function(e) {
306
+ model_status$mqm <<- paste("Failed:", e$message)
307
  safe_notify(paste("MQM failed:", e$message), "warning")
308
+ # Fallback: use HK
309
+ if (!is.null(models$hk)) {
310
+ models$mqm <<- models$hk
311
+ model_status$mqm <<- "Fallback to HK"
312
+ }
313
  })
314
+
315
+ # --- Model 9: Binary Trait [FIX #3: use model="binary" not method="binary"] ---
316
+ safe_notify("Running Model 9/10: Binary Model...", "message")
317
  tryCatch({
318
+ # Binarize phenotype at median for applicability to any trait
319
+ pheno_vec <- cross$pheno[[pheno_col]]
320
+ cross_bin <- cross
321
+ med_val <- median(pheno_vec, na.rm = TRUE)
322
+ cross_bin$pheno[[pheno_col]] <- as.numeric(pheno_vec > med_val)
323
+ models$binary <- scanone(cross_bin, pheno.col = pheno_col,
324
+ method = "em", model = "binary")
325
+ model_status$binary <- "Success (binarized at median)"
326
  }, error = function(e) {
327
+ model_status$binary <<- paste("Failed:", e$message)
328
  safe_notify(paste("Binary failed:", e$message), "warning")
329
  })
330
+
331
+ # --- Model 10: Normal (Gaussian) [FIX #4: use model="normal"] ---
332
+ safe_notify("Running Model 10/10: Normal (Gaussian) Model...", "message")
333
  tryCatch({
334
+ models$normal <- scanone(cross, pheno.col = pheno_col,
335
+ method = "em", model = "normal")
336
  model_status$normal <- "Success"
337
  }, error = function(e) {
338
+ model_status$normal <<- paste("Failed:", e$message)
339
  safe_notify(paste("Normal failed:", e$message), "warning")
340
  })
341
+
342
  attr(models, "status") <- model_status
343
  return(models)
344
  }
345
 
346
  # ============================================================================
347
+ # QTL DETECTION [FIX #8: peak detection now uses full chr profile]
348
  # ============================================================================
349
 
350
  detect_comprehensive_qtls <- function(scan, threshold, cross = NULL, pheno_col = NULL) {
351
+ if (is.null(scan) || nrow(scan) == 0) return(data.frame())
352
+
 
 
 
 
 
 
 
353
  qtls <- data.frame()
354
+
355
+ for (chr in unique(scan$chr)) {
 
356
  chr_all <- scan[scan$chr == chr, ]
357
+ if (nrow(chr_all) == 0) next
358
+
359
+ lods <- chr_all$lod
360
+ n <- nrow(chr_all)
361
+
362
+ # Find local maxima above threshold in full chromosome profile
363
+ is_peak <- logical(n)
364
+ for (i in seq_len(n)) {
365
+ if (lods[i] < threshold) next
366
+ left_ok <- (i == 1) || (lods[i] >= lods[i - 1])
367
+ right_ok <- (i == n) || (lods[i] >= lods[i + 1])
368
+ if (left_ok && right_ok) is_peak[i] <- TRUE
369
  }
370
+
371
+ peak_indices <- which(is_peak)
372
+ if (length(peak_indices) == 0) next
373
+
374
+ for (pi in peak_indices) {
375
+ peak_row <- chr_all[pi, ]
376
+ peak_marker <- rownames(peak_row)
377
+
378
+ # 1.5 LOD drop CI
379
+ in_ci15 <- which((peak_row$lod - chr_all$lod) <= 1.5)
380
+ left_pos <- if (length(in_ci15)) chr_all$pos[min(in_ci15)] else peak_row$pos - 5
381
+ right_pos <- if (length(in_ci15)) chr_all$pos[max(in_ci15)] else peak_row$pos + 5
382
+ left_mk <- if (length(in_ci15)) rownames(chr_all)[min(in_ci15)] else NA
383
+ right_mk <- if (length(in_ci15)) rownames(chr_all)[max(in_ci15)] else NA
384
+
385
+ # 2 LOD drop CI
386
+ in_ci2 <- which((peak_row$lod - chr_all$lod) <= 2)
387
+ left2_pos <- if (length(in_ci2)) chr_all$pos[min(in_ci2)] else peak_row$pos - 3
388
+ right2_pos <- if (length(in_ci2)) chr_all$pos[max(in_ci2)] else peak_row$pos + 3
389
+
390
+ # PVE: Lander-Botstein approximation
391
+ n_ind <- if (!is.null(cross)) nind(cross) else 200
392
+ pve <- (1 - 10^(-2 * peak_row$lod / n_ind)) * 100
393
+
394
+ # Additive/dominance effects
395
+ add_effect <- NA_real_
396
+ dom_effect <- NA_real_
397
+ if (!is.null(cross) && !is.null(pheno_col)) {
398
+ tryCatch({
399
+ # FIX #8: use find.marker then pull genotype by name safely
400
+ chr_str <- as.character(chr)
401
+ mk_name <- find.marker(cross, chr_str, peak_row$pos)
402
+ if (!is.null(mk_name) && length(mk_name) == 1) {
403
+ geno_col_nm <- mk_name
404
+ if (geno_col_nm %in% colnames(pull.geno(cross))) {
405
+ genotypes <- pull.geno(cross)[, geno_col_nm]
406
+ phenotypes <- cross$pheno[[pheno_col]]
407
+ means <- tapply(phenotypes, genotypes, mean, na.rm = TRUE)
408
+ if (length(means) == 3) {
409
+ add_effect <- (means["3"] - means["1"]) / 2
410
+ dom_effect <- means["2"] - (means["1"] + means["3"]) / 2
411
+ } else if (length(means) == 2) {
412
+ add_effect <- means[2] - means[1]
413
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
414
  }
415
+ }
416
+ }, error = function(e) NULL)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
417
  }
418
+
419
+ qtls <- rbind(qtls, data.frame(
420
+ Chromosome = as.character(chr),
421
+ Peak_Position_cM = round(peak_row$pos, 2),
422
+ Peak_Marker = peak_marker,
423
+ LOD_Score = round(peak_row$lod, 3),
424
+ PVE_Percent = round(max(pve, 0), 2),
425
+ CI_1.5LOD_Left_cM = round(left_pos, 2),
426
+ CI_1.5LOD_Right_cM = round(right_pos, 2),
427
+ CI_1.5LOD_Width_cM = round(right_pos - left_pos, 2),
428
+ CI_2LOD_Left_cM = round(left2_pos, 2),
429
+ CI_2LOD_Right_cM = round(right2_pos, 2),
430
+ CI_2LOD_Width_cM = round(right2_pos - left2_pos, 2),
431
+ Left_Flanking_Marker = left_mk,
432
+ Right_Flanking_Marker = right_mk,
433
+ Additive_Effect = round(add_effect, 4),
434
+ Dominance_Effect = round(dom_effect, 4),
435
+ stringsAsFactors = FALSE
436
+ ))
437
  }
438
  }
439
+
440
  if (nrow(qtls) > 0) {
 
441
  qtls$ChrNum <- suppressWarnings(as.numeric(qtls$Chromosome))
442
  qtls$ChrNum[is.na(qtls$ChrNum)] <- 999
443
  qtls <- qtls[order(qtls$ChrNum, qtls$Peak_Position_cM), ]
444
  qtls$ChrNum <- NULL
445
+ rownames(qtls) <- NULL
446
  }
 
447
  return(qtls)
448
  }
449
 
450
  # ============================================================================
451
+ # PERMUTATION TEST
452
  # ============================================================================
453
 
454
  run_permutation_analysis <- function(cross, pheno_col, n_perm = 1000) {
455
  tryCatch({
456
+ perms <- scanone(cross, pheno.col = pheno_col,
457
+ n.perm = n_perm, method = "hk", verbose = FALSE)
458
+ alphas <- c(0.001, 0.01, 0.05, 0.1, 0.2)
459
+ thr_vals <- sapply(alphas, function(a) {
460
+ tryCatch(as.numeric(summary(perms, alpha = a)[1]), error = function(e) NA)
461
+ })
462
+ thresholds <- data.frame(Alpha = alphas,
463
+ LOD_Threshold = round(thr_vals, 3))
464
+ list(permutations = perms, thresholds = thresholds)
 
 
 
 
465
  }, error = function(e) {
466
  safe_notify(paste("Permutation failed:", e$message), "warning")
467
+ NULL
468
  })
469
  }
470
 
 
474
 
475
  create_model_comparison <- function(models, threshold) {
476
  if (is.null(models) || length(models) == 0) return(data.frame())
477
+ statuses <- attr(models, "status")
478
+
479
+ do.call(rbind, lapply(names(models), function(nm) {
480
+ scan <- models[[nm]]
481
+ if (is.null(scan) || !inherits(scan, "scanone")) return(NULL)
482
+ max_lod <- max(scan$lod, na.rm = TRUE)
483
+ mean_lod <- mean(scan$lod, na.rm = TRUE)
484
+ n_peaks <- nrow(scan[scan$lod >= threshold, ])
485
+ peak_i <- which.max(scan$lod)
486
+ data.frame(
487
+ Model = toupper(nm),
488
+ Status = ifelse(!is.null(statuses[[nm]]), statuses[[nm]], "Unknown"),
489
+ Max_LOD = round(max_lod, 3),
490
+ Mean_LOD = round(mean_lod, 3),
491
+ N_Significant_Peaks = n_peaks,
492
+ Peak_Chromosome = as.character(scan$chr[peak_i]),
493
+ Peak_Position_cM = round(scan$pos[peak_i], 2),
494
+ stringsAsFactors = FALSE
495
+ )
496
+ })) -> df
497
+ if (is.null(df)) return(data.frame())
498
+ df[order(-df$Max_LOD), ]
 
 
 
499
  }
500
 
501
  # ============================================================================
502
  # PLOTTING FUNCTIONS
503
  # ============================================================================
504
 
505
+ # Plot 1: Manhattan [FIX #7: correct cumulative position]
506
  plot_manhattan_enhanced <- function(scan, qtls, threshold) {
507
  if (is.null(scan)) return(NULL)
508
+
509
+ df <- as.data.frame(scan)
510
+ df$marker <- rownames(df)
511
+ chrs <- unique(df$chr)
512
+
513
+ # Build per-chromosome max position and cumulative offset
514
+ chr_maxpos <- sapply(chrs, function(ch) max(df$pos[df$chr == ch], na.rm = TRUE))
515
+ # Offset for chr i = sum of max positions of all chrs before i
516
+ chr_offset <- c(0, cumsum(chr_maxpos[-length(chr_maxpos)]))
517
+ names(chr_offset) <- chrs
518
+
519
+ df$pos_cum <- df$pos + chr_offset[as.character(df$chr)]
520
+ chr_mid <- sapply(chrs, function(ch)
521
+ mean(df$pos_cum[df$chr == ch], na.rm = TRUE))
522
+
523
+ colors <- rep(brewer.pal(min(8, length(chrs)), "Set1"),
524
+ length.out = length(chrs))
525
  names(colors) <- chrs
526
+
527
+ p <- ggplot(df, aes(x = pos_cum, y = lod, color = as.character(chr))) +
528
  geom_point(size = 1.5, alpha = 0.7) +
529
+ geom_hline(yintercept = threshold, color = "red",
530
+ linetype = "dashed", linewidth = 1.2) +
531
+ scale_x_continuous(breaks = chr_mid, labels = names(chr_mid)) +
532
+ scale_color_manual(values = colors, guide = "none") +
533
  labs(title = "Genome-wide Manhattan Plot",
534
  x = "Chromosome", y = "LOD Score") +
535
+ theme_minimal(base_size = 13) +
536
+ theme(axis.text.x = element_text(angle = 45, hjust = 1))
537
+
 
538
  if (!is.null(qtls) && nrow(qtls) > 0) {
539
+ qtls$pos_cum <- qtls$Peak_Position_cM +
540
+ chr_offset[as.character(qtls$Chromosome)]
541
+ p <- p + geom_point(data = qtls,
542
+ aes(x = pos_cum, y = LOD_Score),
543
+ color = "gold", size = 5, shape = 18,
544
+ inherit.aes = FALSE)
545
  }
546
+ p
 
547
  }
548
 
549
+ # Plot 2: Per-chromosome LOD profiles (replaces broken contour)
550
+ plot_chr_lod_profiles <- function(scan, threshold) {
551
  if (is.null(scan)) return(NULL)
552
+
553
+ df <- as.data.frame(scan)
554
+ df$chr <- factor(df$chr, levels = unique(df$chr))
555
+ n_chrs <- nlevels(df$chr)
556
+ pal <- colorRampPalette(brewer.pal(9, "Set1"))(n_chrs)
557
+
558
+ ggplot(df, aes(x = pos, y = lod, color = chr)) +
559
+ geom_line(linewidth = 0.8) +
560
+ geom_hline(yintercept = threshold, color = "red",
561
+ linetype = "dashed", linewidth = 0.8) +
562
+ facet_wrap(~chr, scales = "free_x", ncol = 4) +
563
+ scale_color_manual(values = pal, guide = "none") +
564
+ labs(title = "Per-Chromosome LOD Profiles",
565
+ x = "Position (cM)", y = "LOD Score") +
566
+ theme_bw(base_size = 11) +
567
+ theme(strip.background = element_rect(fill = "steelblue"),
568
+ strip.text = element_text(color = "white", face = "bold"))
569
  }
570
 
571
+ # Plot 3: QTL Bubble Plot
572
  plot_qtl_bubble <- function(qtls) {
573
  if (is.null(qtls) || nrow(qtls) == 0) return(NULL)
574
+
575
+ qtls$Chromosome <- factor(qtls$Chromosome,
576
+ levels = unique(qtls$Chromosome))
577
+ ggplot(qtls, aes(x = Chromosome, y = Peak_Position_cM,
578
  size = LOD_Score, color = PVE_Percent)) +
579
+ geom_point(alpha = 0.85) +
580
+ scale_size_continuous(range = c(4, 20), name = "LOD Score") +
581
+ scale_color_gradientn(colors = c("#2166ac","#92c5de","#f7f7f7",
582
+ "#f4a582","#d6604d"),
583
+ name = "PVE (%)") +
584
  labs(title = "QTL Effect Size Bubble Plot",
585
+ x = "Chromosome", y = "Peak Position (cM)") +
586
+ theme_minimal(base_size = 13) +
587
  theme(axis.text.x = element_text(angle = 45, hjust = 1))
588
  }
589
 
590
  # Plot 4: Ridge Plot
591
  plot_ridge_distribution <- function(scan) {
592
  if (is.null(scan)) return(NULL)
593
+
594
+ df <- as.data.frame(scan)
595
+ df$chr <- factor(df$chr, levels = rev(unique(df$chr)))
596
+
597
  ggplot(df, aes(x = lod, y = chr, fill = after_stat(x))) +
598
+ geom_density_ridges_gradient(scale = 2.5, rel_min_height = 0.01,
599
+ color = "white") +
600
+ scale_fill_viridis_c(option = "C", name = "LOD") +
601
+ labs(title = "LOD Score Distribution per Chromosome",
602
+ x = "LOD Score", y = "Chromosome") +
603
+ theme_ridges(grid = FALSE) +
604
+ theme(legend.position = "right")
605
  }
606
 
607
+ # Plot 5: Violin + Boxplot [FIX #5: proper factor relabeling; FIX #6: safe geno extraction]
608
+ plot_genotype_violin <- function(cross, qtl_row, trait) {
609
+ if (is.null(cross) || is.null(qtl_row) || nrow(qtl_row) == 0) return(NULL)
610
+
611
+ chr_name <- as.character(qtl_row$Chromosome[1])
612
+ if (!chr_name %in% names(cross$geno)) {
613
+ message("Chromosome '", chr_name, "' not found in cross object")
614
+ return(NULL)
615
+ }
616
+
617
+ # FIX #6: find.marker returns marker name; use it directly to index pull.geno()
618
+ mk_name <- tryCatch(
619
+ find.marker(cross, chr_name, qtl_row$Peak_Position_cM[1]),
620
+ error = function(e) NULL
 
 
 
 
621
  )
622
+ if (is.null(mk_name) || length(mk_name) == 0) {
623
+ message("Could not find marker near QTL peak")
624
+ return(NULL)
625
+ }
626
+ mk_name <- mk_name[1]
627
+
628
+ geno_mat <- pull.geno(cross)
629
+ if (!mk_name %in% colnames(geno_mat)) {
630
+ message("Marker '", mk_name, "' not found in genotype matrix")
631
+ return(NULL)
632
+ }
633
+
634
+ genotypes <- geno_mat[, mk_name]
635
+ phenotypes <- cross$pheno[[trait]]
636
+
637
+ df <- data.frame(Geno = genotypes, Pheno = phenotypes)
638
+ df <- df[!is.na(df$Geno) & !is.na(df$Pheno), ]
639
+ if (nrow(df) == 0) return(NULL)
640
+
641
+ # FIX #5: proper factor relabeling (no dplyr::recode on numerics)
642
+ cross_type <- class(cross)[1]
643
+ uni_genos <- sort(unique(df$Geno))
644
+ if (length(uni_genos) == 3 && cross_type == "f2") {
645
+ df$Geno <- factor(df$Geno, levels = uni_genos,
646
+ labels = c("AA", "AB", "BB"))
647
+ } else if (length(uni_genos) == 2) {
648
+ df$Geno <- factor(df$Geno, levels = uni_genos,
649
+ labels = c("AA", "BB"))
650
+ } else {
651
+ df$Geno <- factor(df$Geno)
652
  }
653
+
654
+ ggplot(df, aes(x = Geno, y = Pheno, fill = Geno)) +
655
+ geom_violin(alpha = 0.55, trim = FALSE, color = NA) +
656
+ geom_boxplot(width = 0.18, alpha = 0.85, outlier.size = 1) +
657
+ stat_summary(fun = mean, geom = "point",
658
+ shape = 18, size = 5, color = "#c0392b") +
659
+ scale_fill_brewer(palette = "Set2", guide = "none") +
660
+ labs(title = paste0("Phenotype Distribution at ", mk_name,
661
+ " (Chr ", chr_name, ")"),
662
+ x = "Genotype Class", y = trait) +
663
+ theme_minimal(base_size = 13)
664
  }
665
 
666
  # Plot 6: Genetic Map Density
667
  plot_genetic_density <- function(cross) {
668
  if (is.null(cross)) return(NULL)
669
+
670
+ map <- pull.map(cross)
671
+ df <- do.call(rbind, lapply(names(map), function(ch) {
672
+ data.frame(Chromosome = ch, Position_cM = as.numeric(map[[ch]]))
673
+ }))
674
+
 
 
675
  df$Chromosome <- factor(df$Chromosome, levels = names(map))
676
+
677
+ # Spacing between adjacent markers
678
+ df <- df[order(df$Chromosome, df$Position_cM), ]
679
+ df <- df %>%
680
+ group_by(Chromosome) %>%
681
+ mutate(Spacing = c(NA, diff(Position_cM))) %>%
682
+ ungroup()
683
+
684
+ ggplot(df, aes(x = Chromosome, y = Position_cM)) +
685
+ geom_segment(aes(xend = Chromosome, yend = 0),
686
+ color = "gray80", linewidth = 0.6) +
687
+ geom_point(aes(color = Spacing), size = 2, alpha = 0.8) +
688
+ scale_color_viridis_c(option = "D", na.value = "gray50",
689
+ name = "Gap (cM)") +
690
+ scale_y_reverse() +
691
+ labs(title = "Genetic Marker Map",
692
+ x = "Chromosome", y = "Position (cM, top=0)") +
693
+ theme_minimal(base_size = 13) +
694
  theme(axis.text.x = element_text(angle = 45, hjust = 1))
695
  }
696
 
697
  # Plot 7: Model Comparison Bar Plot
698
  plot_model_comparison <- function(comparison_df) {
699
  if (is.null(comparison_df) || nrow(comparison_df) == 0) return(NULL)
700
+
701
+ ggplot(comparison_df,
702
+ aes(x = reorder(Model, Max_LOD), y = Max_LOD, fill = Model)) +
703
+ geom_col(alpha = 0.85, width = 0.7) +
704
+ geom_text(aes(label = sprintf("%.2f", Max_LOD)),
705
+ hjust = -0.15, size = 3.5, color = "gray20") +
706
+ coord_flip() +
707
+ scale_fill_manual(values = colorRampPalette(brewer.pal(10, "Paired"))(10),
708
+ guide = "none") +
709
+ labs(title = "Model Performance Comparison (Max LOD)",
710
+ x = NULL, y = "Max LOD Score") +
711
+ expand_limits(y = max(comparison_df$Max_LOD) * 1.15) +
712
+ theme_minimal(base_size = 13)
713
+ }
714
+
715
+ # Plot 8: QTL Interval map (chromosome ideogram-style)
716
+ plot_qtl_intervals <- function(qtls, cross) {
717
+ if (is.null(qtls) || nrow(qtls) == 0 || is.null(cross)) return(NULL)
718
+
719
+ map <- pull.map(cross)
720
+ chr_df <- do.call(rbind, lapply(names(map), function(ch) {
721
+ data.frame(Chromosome = ch,
722
+ chr_max = max(as.numeric(map[[ch]]), na.rm = TRUE))
723
+ }))
724
+
725
+ qtls$Chromosome <- factor(qtls$Chromosome,
726
+ levels = unique(chr_df$Chromosome))
727
+
728
+ ggplot() +
729
+ geom_segment(data = chr_df,
730
+ aes(x = 0, xend = chr_max,
731
+ y = Chromosome, yend = Chromosome),
732
+ color = "gray70", linewidth = 4, lineend = "round") +
733
+ geom_segment(data = qtls,
734
+ aes(x = CI_1.5LOD_Left_cM, xend = CI_1.5LOD_Right_cM,
735
+ y = Chromosome, yend = Chromosome,
736
+ color = LOD_Score),
737
+ linewidth = 6, alpha = 0.7, lineend = "round") +
738
+ geom_point(data = qtls,
739
+ aes(x = Peak_Position_cM, y = Chromosome,
740
+ size = PVE_Percent),
741
+ color = "gold", shape = 18) +
742
+ scale_color_gradient(low = "#2166ac", high = "#d73027",
743
+ name = "LOD") +
744
+ scale_size_continuous(range = c(3, 10), name = "PVE (%)") +
745
+ labs(title = "QTL Confidence Intervals",
746
+ x = "Position (cM)", y = "Chromosome") +
747
+ theme_minimal(base_size = 13)
748
  }
749
 
750
  # ============================================================================
 
752
  # ============================================================================
753
 
754
  ui <- dashboardPage(
755
+ skin = "blue",
756
+ dashboardHeader(title = "QTL Analysis Suite"),
757
+
758
+ dashboardSidebar(width = 310,
759
+ sidebarMenu(id = "tabs",
760
+ menuItem("Data Input", tabName = "data", icon = icon("upload")),
761
+ menuItem("10 Models", tabName = "models", icon = icon("cogs")),
762
+ menuItem("QTL Results", tabName = "results", icon = icon("table")),
763
+ menuItem("Visualizations",tabName = "plots", icon = icon("chart-bar")),
764
+ menuItem("Downloads", tabName = "download", icon = icon("download")),
765
+ menuItem("Help", tabName = "help", icon = icon("question-circle"))
766
  ),
767
+
768
+ div(style = "padding: 12px;",
769
+ tags$hr(),
770
+ h4("1. Upload Files", style = "color:#ecf0f1"),
771
+ fileInput("geno_file", "Genotype CSV", accept = ".csv",
772
+ placeholder = "row1=names,row2=chr,row3=pos..."),
773
+ fileInput("pheno_file", "Phenotype CSV", accept = ".csv",
774
+ placeholder = "col1=ID, col2+= traits"),
775
+
776
  selectInput("cross_type", "Cross Type",
777
+ choices = c("F2 Intercross" = "f2",
778
+ "Backcross" = "bc",
779
+ "RIL (selfing)" = "riself"),
780
  selected = "f2"),
781
+
782
+ tags$hr(),
783
+ h4("2. Analysis Parameters", style = "color:#ecf0f1"),
784
+ selectInput("pheno_trait", "Phenotype Trait", choices = NULL),
785
+ numericInput("lod_threshold", "LOD Threshold", value = 3.0,
786
+ min = 0, max = 20, step = 0.5),
787
+ numericInput("n_permutations", "Permutations (0 = skip)",
788
+ value = 100, min = 0, max = 5000, step = 100),
789
+
790
+ tags$hr(),
791
+ actionButton("run_analysis", "RUN ALL 10 MODELS",
792
+ icon = icon("play"),
793
+ style = paste("background:#27ae60;color:white;",
794
+ "width:100%;font-weight:bold;font-size:15px;"))
795
  )
796
  ),
797
+
798
  dashboardBody(
799
  useShinyjs(),
800
  tags$head(tags$style(HTML("
801
+ .content-wrapper, .right-side { background-color:#f0f3f7; }
802
+ .box { border-radius:8px; box-shadow: 0 2px 8px rgba(0,0,0,0.08); }
803
+ .info-box { border-radius:8px; }
804
  "))),
805
+
806
  tabItems(
807
+
808
+ # ---- DATA TAB ----
809
  tabItem(tabName = "data",
810
  fluidRow(
811
+ infoBoxOutput("ib_individuals", width = 4),
812
+ infoBoxOutput("ib_markers", width = 4),
813
+ infoBoxOutput("ib_chromosomes", width = 4)
814
  ),
815
  fluidRow(
816
+ box(title = "Data Summary", status = "primary",
817
+ solidHeader = TRUE, width = 6,
818
+ verbatimTextOutput("data_summary")),
819
+ box(title = "Cross Quality Metrics", status = "info",
820
+ solidHeader = TRUE, width = 6,
821
+ verbatimTextOutput("quality_metrics"))
822
  ),
823
  fluidRow(
824
+ box(title = "Genetic Marker Map", status = "info",
825
+ solidHeader = TRUE, width = 12,
826
+ plotOutput("genetic_map", height = "520px") %>% withSpinner(color = "#3498db"))
827
  )
828
  ),
829
+
830
+ # ---- MODELS TAB ----
831
  tabItem(tabName = "models",
832
  fluidRow(
833
+ box(title = "Analysis Status", status = "primary",
834
+ solidHeader = TRUE, width = 12,
835
+ verbatimTextOutput("analysis_status"))
836
  ),
837
  fluidRow(
838
+ box(title = "Model Comparison Table", status = "info",
839
+ solidHeader = TRUE, width = 12,
840
+ DTOutput("model_comparison_table") %>% withSpinner(color = "#3498db"))
841
  ),
842
  fluidRow(
843
+ box(title = "Model Performance Bar Chart", status = "success",
844
+ solidHeader = TRUE, width = 12,
845
+ plotOutput("model_barplot", height = "420px") %>% withSpinner(color = "#27ae60"))
846
  )
847
  ),
848
+
849
+ # ---- RESULTS TAB ----
850
  tabItem(tabName = "results",
851
  fluidRow(
852
+ box(title = "Significant QTLs (all details)", status = "primary",
853
+ solidHeader = TRUE, width = 12,
854
+ DTOutput("qtl_table") %>% withSpinner(color = "#3498db"))
855
  ),
856
  fluidRow(
857
+ box(title = "Permutation Thresholds", status = "warning",
858
+ solidHeader = TRUE, width = 12,
859
+ DTOutput("permutation_table") %>% withSpinner(color = "#e67e22"))
860
  )
861
  ),
862
+
863
+ # ---- PLOTS TAB ----
864
  tabItem(tabName = "plots",
865
  fluidRow(
866
+ box(title = "Manhattan Plot (all models → HK shown)",
867
+ status = "primary", solidHeader = TRUE, width = 12,
868
+ plotOutput("manhattan_plot", height = "480px") %>% withSpinner(color = "#3498db"))
869
  ),
870
  fluidRow(
871
+ box(title = "Per-Chromosome LOD Profiles",
872
+ status = "info", solidHeader = TRUE, width = 12,
873
+ plotOutput("chr_profiles_plot", height = "560px") %>% withSpinner(color = "#3498db"))
 
874
  ),
875
  fluidRow(
876
+ box(title = "Ridge Density Plot",
877
+ status = "success", solidHeader = TRUE, width = 6,
878
+ plotOutput("ridge_plot", height = "480px") %>% withSpinner(color = "#27ae60")),
879
+ box(title = "QTL Bubble Plot",
880
+ status = "warning", solidHeader = TRUE, width = 6,
881
+ plotOutput("bubble_plot", height = "480px") %>% withSpinner(color = "#e67e22"))
882
  ),
883
  fluidRow(
884
+ box(title = "QTL Confidence Intervals (Chromosome Ideogram)",
885
+ status = "danger", solidHeader = TRUE, width = 12,
886
+ plotOutput("qtl_interval_plot", height = "400px") %>% withSpinner(color = "#e74c3c"))
887
+ ),
888
+ fluidRow(
889
+ box(title = "Genotype-Phenotype Violin Plot",
890
+ status = "primary", solidHeader = TRUE, width = 12,
891
+ selectInput("violin_qtl", "Select QTL:", choices = NULL,
892
+ width = "350px"),
893
+ plotOutput("violin_plot", height = "440px") %>% withSpinner(color = "#3498db"))
894
  )
895
  ),
896
+
897
+ # ---- DOWNLOAD TAB ----
898
  tabItem(tabName = "download",
899
  fluidRow(
900
+ box(title = "Download Analysis Results", status = "primary",
901
+ solidHeader = TRUE, width = 12,
902
+ br(),
903
+ downloadButton("dl_qtl", "Download QTL Results (CSV)",
904
+ style = "margin:8px; background:#3498db; color:white;"),
905
+ downloadButton("dl_model", "Download Model Comparison (CSV)",
906
+ style = "margin:8px; background:#27ae60; color:white;"),
907
+ downloadButton("dl_perms", "Download Permutation Thresholds (CSV)",
908
+ style = "margin:8px; background:#e67e22; color:white;"),
909
+ br(), br(),
910
+ helpText("Run 10 Models first to generate downloadable results.")
911
  )
912
  )
913
  ),
914
+
915
+ # ---- HELP TAB ----
916
  tabItem(tabName = "help",
917
  fluidRow(
918
+ box(title = "File Format", status = "primary",
919
+ solidHeader = TRUE, width = 6,
920
+ HTML("
921
+ <h4>Genotype CSV</h4>
922
+ <ul>
923
+ <li>Row 1: ID label + marker names</li>
924
+ <li>Row 2: blank + chromosome identifiers</li>
925
+ <li>Row 3: blank + cM positions</li>
926
+ <li>Row 4+: individual ID + genotype codes (1/2/3 for F2)</li>
927
+ </ul>
928
+ <h4>Phenotype CSV</h4>
929
+ <ul>
930
+ <li>Header row: ID column + trait names</li>
931
+ <li>Data rows: individual ID + numeric trait values</li>
932
+ </ul>
933
+ ")),
934
+ box(title = "10 Models Explained", status = "info",
935
+ solidHeader = TRUE, width = 6,
936
+ HTML("
937
+ <ol>
938
+ <li><b>HK</b>: Haley-Knott Regression – fast, robust</li>
939
+ <li><b>EM</b>: Expectation-Maximisation – exact but slower</li>
940
+ <li><b>EHK</b>: Extended HK – handles missing data better</li>
941
+ <li><b>IMP</b>: Multiple Imputation – most accurate CI</li>
942
+ <li><b>MR</b>: Marker Regression – no imputation needed</li>
943
+ <li><b>NP</b>: Non-parametric – robust to non-normality</li>
944
+ <li><b>CIM</b>: Composite Interval Mapping – controls for background</li>
945
+ <li><b>MQM</b>: Multiple QTL Mapping – simultaneous multi-QTL</li>
946
+ <li><b>Binary</b>: Logistic model (phenotype binarized at median)</li>
947
+ <li><b>Normal</b>: Explicit Gaussian model via EM</li>
948
+ </ol>
949
+ "))
950
  )
951
  )
952
  )
 
958
  # ============================================================================
959
 
960
  server <- function(input, output, session) {
961
+
962
+ cross_data <- reactiveVal(NULL)
963
+ all_models <- reactiveVal(NULL)
964
+ qtl_results <- reactiveVal(NULL)
965
+ perm_results <- reactiveVal(NULL)
966
+ model_comp <- reactiveVal(NULL)
967
+ analysis_done <- reactiveVal(FALSE)
968
+
969
+ # ---- Info Boxes ----
970
+ output$ib_individuals <- renderInfoBox({
971
+ cr <- cross_data()
972
+ infoBox("Individuals", ifelse(is.null(cr), "—", nind(cr)),
973
+ icon = icon("users"), color = "blue")
974
  })
975
+ output$ib_markers <- renderInfoBox({
976
+ cr <- cross_data()
977
+ infoBox("Markers", ifelse(is.null(cr), "—", totmar(cr)),
978
+ icon = icon("dna"), color = "green")
 
979
  })
980
+ output$ib_chromosomes <- renderInfoBox({
981
+ cr <- cross_data()
982
+ infoBox("Chromosomes", ifelse(is.null(cr), "—", nchr(cr)),
983
+ icon = icon("chart-line"), color = "yellow")
 
984
  })
985
+
986
+ # ---- Load data [FIX #10: single observeEvent with req(both)] ----
987
+ observeEvent(list(input$geno_file, input$pheno_file), {
988
  req(input$geno_file, input$pheno_file)
989
+ safe_notify("Loading and parsing data...", "message")
 
 
990
  tryCatch({
991
+ cr <- parse_advanced_cross(
992
  input$geno_file$datapath,
993
  input$pheno_file$datapath,
994
  input$cross_type
995
  )
996
+ cross_data(cr)
 
 
997
  updateSelectInput(session, "pheno_trait",
998
+ choices = names(cr$pheno),
999
+ selected = names(cr$pheno)[1])
1000
+ safe_notify(paste("Loaded:", nind(cr), "individuals,",
1001
+ totmar(cr), "markers,", nchr(cr), "chromosomes"), "success")
 
1002
  }, error = function(e) {
1003
+ safe_notify(paste("Load error:", e$message), "error")
1004
  })
1005
  })
1006
+
1007
+ # ---- Run Analysis ----
1008
  observeEvent(input$run_analysis, {
1009
+ cr <- cross_data()
1010
+ req(cr, input$pheno_trait)
1011
+
1012
+ analysis_done(FALSE)
1013
+ safe_notify("Starting 10-model QTL analysis...", "message")
1014
+ pheno_idx <- which(names(cr$pheno) == input$pheno_trait)
1015
+ if (length(pheno_idx) == 0) {
1016
+ safe_notify("Selected phenotype not found", "error"); return()
1017
+ }
1018
+
1019
+ withProgress(message = "QTL Analysis in Progress", value = 0, {
1020
+
1021
+ incProgress(0.15, detail = "Step 1: Running 10 mapping models...")
1022
+ models <- run_all_ten_models(cr, pheno_idx)
1023
  all_models(models)
1024
+
1025
+ incProgress(0.25, detail = "Step 2: Detecting significant QTLs...")
1026
+ base_scan <- if (!is.null(models$hk)) models$hk else models[[1]]
1027
+ qtls <- if (!is.null(base_scan))
1028
+ detect_comprehensive_qtls(base_scan, input$lod_threshold,
1029
+ cr, input$pheno_trait)
1030
+ else data.frame()
1031
+ qtl_results(qtls)
1032
+
1033
+ if (!is.null(qtls) && nrow(qtls) > 0) {
1034
+ qlabels <- paste0("Chr", qtls$Chromosome, " @ ",
1035
+ qtls$Peak_Position_cM, "cM (LOD=",
1036
+ round(qtls$LOD_Score, 2), ")")
1037
+ updateSelectInput(session, "violin_qtl",
1038
+ choices = setNames(seq_len(nrow(qtls)), qlabels))
1039
  }
1040
+
1041
+ incProgress(0.25, detail = "Step 3: Building model comparison...")
1042
+ mc <- create_model_comparison(models, input$lod_threshold)
1043
+ model_comp(mc)
1044
+
1045
+ if (input$n_permutations > 0 && !is.null(base_scan)) {
1046
+ incProgress(0.35, detail = paste0("Step 4: ",
1047
+ input$n_permutations, " permutations..."))
1048
+ pr <- run_permutation_analysis(cr, pheno_idx, input$n_permutations)
1049
+ perm_results(pr)
1050
  }
1051
+
1052
+ analysis_done(TRUE)
1053
+ n_ok <- sum(sapply(models, function(m) !is.null(m) && inherits(m, "scanone")))
1054
+ safe_notify(paste0("Analysis complete! ", n_ok, "/10 models succeeded, ",
1055
+ ifelse(is.null(qtls), 0, nrow(qtls)), " QTLs detected."), "success")
1056
  })
1057
  })
1058
+
1059
+ # ---- Data Summary ----
1060
  output$data_summary <- renderPrint({
1061
+ cr <- cross_data()
1062
+ if (is.null(cr)) { cat("No data loaded yet.\n"); return() }
1063
+ cat("Cross Type :", class(cr)[1], "\n")
1064
+ cat("Individuals :", nind(cr), "\n")
1065
+ cat("Total Markers:", totmar(cr), "\n")
1066
+ cat("Chromosomes :", nchr(cr), "\n")
1067
+ cat("Phenotypes :", paste(names(cr$pheno), collapse = ", "), "\n")
1068
+ summ <- attr(cr, "summary")
1069
+ if (!is.null(summ)) {
1070
+ cat("Missing Rate :", round(summ$missing_rate * 100, 2), "%\n")
1071
+ cat("Heterozygosity:", round(summ$heterozygosity * 100, 2), "%\n")
1072
  }
1073
  })
1074
+
1075
+ output$quality_metrics <- renderPrint({
1076
+ cr <- cross_data()
1077
+ if (is.null(cr)) { cat("Load data to see quality metrics.\n"); return() }
1078
+ cat("=== Per-Chromosome Marker Counts ===\n")
1079
+ nmar_vec <- nmar(cr)
1080
+ for (i in seq_along(nmar_vec))
1081
+ cat(sprintf(" Chr %-6s : %d markers\n", names(nmar_vec)[i], nmar_vec[i]))
1082
+ cat("\n=== Phenotype Summary ===\n")
1083
+ for (pn in names(cr$pheno)) {
1084
+ pv <- cr$pheno[[pn]]
1085
+ cat(sprintf(" %-20s mean=%.3f sd=%.3f N=%d\n",
1086
+ pn, mean(pv,na.rm=T), sd(pv,na.rm=T), sum(!is.na(pv))))
1087
+ }
1088
+ })
1089
+
1090
  output$analysis_status <- renderPrint({
1091
+ if (!analysis_done()) {
1092
+ cat("Upload genotype + phenotype files, then click 'RUN ALL 10 MODELS'.\n")
1093
+ return()
 
 
 
 
 
1094
  }
1095
+ models <- all_models()
1096
+ statuses <- attr(models, "status")
1097
+ cat("=== Model Run Status ===\n")
1098
+ for (nm in names(statuses))
1099
+ cat(sprintf(" %-10s : %s\n", toupper(nm), statuses[[nm]]))
1100
+ cat("\n")
1101
+ qtls <- qtl_results()
1102
+ cat("QTLs detected (LOD >=", input$lod_threshold, "):",
1103
+ ifelse(is.null(qtls), 0, nrow(qtls)), "\n")
1104
  })
1105
+
1106
+ # ---- Tables ----
1107
  output$model_comparison_table <- renderDT({
1108
+ mc <- model_comp()
1109
+ req(mc, nrow(mc) > 0)
1110
+ datatable(mc,
1111
+ options = list(pageLength = 12, scrollX = TRUE,
1112
+ columnDefs = list(list(className = 'dt-center', targets = '_all'))),
1113
+ rownames = FALSE) %>%
1114
+ formatStyle("Max_LOD",
1115
+ background = styleColorBar(range(mc$Max_LOD), "#3498db"),
1116
+ backgroundSize = "90% 80%",
1117
+ backgroundRepeat = "no-repeat",
1118
+ backgroundPosition = "center")
1119
  })
1120
+
1121
  output$qtl_table <- renderDT({
1122
  qtls <- qtl_results()
1123
  req(qtls, nrow(qtls) > 0)
1124
+ datatable(qtls,
1125
+ options = list(pageLength = 20, scrollX = TRUE,
1126
+ columnDefs = list(list(className = 'dt-center', targets = '_all'))),
1127
+ rownames = FALSE) %>%
1128
+ formatStyle("LOD_Score",
1129
+ color = styleInterval(c(3, 5), c("black","#e67e22","#c0392b")),
1130
+ fontWeight = "bold")
1131
  })
1132
+
1133
  output$permutation_table <- renderDT({
1134
+ pr <- perm_results()
1135
+ req(pr)
1136
+ datatable(pr$thresholds,
1137
+ options = list(pageLength = 5, dom = 't'),
1138
+ rownames = FALSE)
1139
  })
1140
+
1141
+ # ---- Plots ----
1142
  output$genetic_map <- renderPlot({
1143
+ cr <- cross_data(); req(cr)
1144
+ plot_genetic_density(cr)
 
1145
  })
1146
+
1147
  output$manhattan_plot <- renderPlot({
1148
  models <- all_models()
1149
+ req(models)
1150
+ base_scan <- if (!is.null(models$hk)) models$hk else models[[1]]
1151
+ req(base_scan)
1152
+ plot_manhattan_enhanced(base_scan, qtl_results(), input$lod_threshold)
1153
  })
1154
+
1155
+ output$chr_profiles_plot <- renderPlot({
1156
  models <- all_models()
1157
+ req(models)
1158
+ base_scan <- if (!is.null(models$hk)) models$hk else models[[1]]
1159
+ req(base_scan)
1160
+ plot_chr_lod_profiles(base_scan, input$lod_threshold)
1161
  })
1162
+
1163
  output$ridge_plot <- renderPlot({
1164
  models <- all_models()
1165
+ req(models)
1166
+ base_scan <- if (!is.null(models$hk)) models$hk else models[[1]]
1167
+ req(base_scan)
1168
+ plot_ridge_distribution(base_scan)
1169
  })
1170
+
1171
  output$bubble_plot <- renderPlot({
1172
+ qtls <- qtl_results(); req(qtls, nrow(qtls) > 0)
 
1173
  plot_qtl_bubble(qtls)
1174
  })
1175
+
1176
+ output$qtl_interval_plot <- renderPlot({
1177
+ qtls <- qtl_results(); cr <- cross_data()
1178
+ req(qtls, nrow(qtls) > 0, cr)
1179
+ plot_qtl_intervals(qtls, cr)
1180
+ })
1181
+
1182
  output$violin_plot <- renderPlot({
1183
+ req(input$violin_qtl, nchar(input$violin_qtl) > 0)
1184
+ qtls <- qtl_results(); cr <- cross_data()
1185
+ req(qtls, nrow(qtls) > 0, cr, input$pheno_trait)
1186
+ idx <- as.integer(input$violin_qtl)
1187
+ req(!is.na(idx), idx >= 1, idx <= nrow(qtls))
1188
+ plot_genotype_violin(cr, qtls[idx, , drop = FALSE], input$pheno_trait)
 
 
 
1189
  })
1190
+
1191
  output$model_barplot <- renderPlot({
1192
+ mc <- model_comp(); req(mc, nrow(mc) > 0)
1193
+ plot_model_comparison(mc)
 
1194
  })
1195
+
1196
+ # ---- Downloads ----
1197
+ output$dl_qtl <- downloadHandler(
1198
  filename = function() paste0("qtl_results_", Sys.Date(), ".csv"),
1199
+ content = function(file) {
1200
  qtls <- qtl_results()
1201
+ write.csv(if (!is.null(qtls) && nrow(qtls) > 0) qtls
1202
+ else data.frame(Note = "No QTLs detected"),
1203
+ file, row.names = FALSE)
 
 
1204
  }
1205
  )
1206
+
1207
+ output$dl_model <- downloadHandler(
1208
  filename = function() paste0("model_comparison_", Sys.Date(), ".csv"),
1209
+ content = function(file) {
1210
+ mc <- model_comp()
1211
+ write.csv(if (!is.null(mc) && nrow(mc) > 0) mc
1212
+ else data.frame(Note = "Run analysis first"),
1213
+ file, row.names = FALSE)
1214
+ }
1215
+ )
1216
+
1217
+ output$dl_perms <- downloadHandler(
1218
+ filename = function() paste0("permutation_thresholds_", Sys.Date(), ".csv"),
1219
+ content = function(file) {
1220
+ pr <- perm_results()
1221
+ write.csv(if (!is.null(pr)) pr$thresholds
1222
+ else data.frame(Note = "No permutations run"),
1223
+ file, row.names = FALSE)
1224
  }
1225
  )
1226
  }
1227
 
1228
+ # ============================================================================
1229
  shinyApp(ui = ui, server = server)