softwareDevelopment commited on
Commit
bbd3177
·
verified ·
1 Parent(s): a9a7bd7

Update app.R

Browse files
Files changed (1) hide show
  1. app.R +648 -1016
app.R CHANGED
@@ -1,48 +1,51 @@
1
  # ============================================================================
2
- # ADVANCED QTL ANALYSIS PIPELINE
3
- # Complete solution with 10+ plots, multiple algorithms, and extensive features
4
  # ============================================================================
5
 
6
- library(shiny)
7
- library(shinydashboard)
8
- library(shinyjs)
9
- library(shinycssloaders)
10
- library(qtl)
11
- library(qtlcharts)
12
- library(ggplot2)
13
- library(plotly)
14
- library(dplyr)
15
- library(tidyr)
16
- library(DT)
17
- library(RColorBrewer)
18
- library(corrplot)
19
- library(heatmaply)
20
- library(UpSetR)
21
- library(ggrepel)
22
- library(ggcorrplot)
23
- library(cowplot)
24
- library(pheatmap)
25
- library(viridis)
26
- library(ggridges)
27
- library(ggExtra)
28
- library(circlize)
29
- library(ComplexHeatmap)
30
- library(foreach)
31
- library(doParallel)
 
 
 
 
32
 
33
  # ============================================================================
34
- # CUSTOM DATA PARSER WITH ADVANCED VALIDATION
35
  # ============================================================================
36
 
37
- parse_advanced_cross <- function(geno_path, pheno_path, cross_type = "f2",
38
- geno_format = "standard", na_strings = c("NA", "", "N/A", "-9", "0")) {
39
 
40
- # Read and validate genotype file
41
  geno_raw <- read.csv(geno_path, header = FALSE, stringsAsFactors = FALSE,
42
- check.names = FALSE, na.strings = na_strings)
43
 
44
  if (nrow(geno_raw) < 4) {
45
- stop("Genotype file must have at least 4 rows: header, chromosome, position, and data")
46
  }
47
 
48
  # Parse header rows
@@ -51,8 +54,12 @@ parse_advanced_cross <- function(geno_path, pheno_path, cross_type = "f2",
51
  pos_row <- as.character(geno_raw[3, ])
52
  ind_data <- geno_raw[4:nrow(geno_raw), , drop = FALSE]
53
 
54
- # Identify marker columns (skip first column which is ID)
55
  marker_cols <- 2:ncol(geno_raw)
 
 
 
 
56
  marker_names <- col_names[marker_cols]
57
 
58
  # Clean chromosome names
@@ -60,14 +67,17 @@ parse_advanced_cross <- function(geno_path, pheno_path, cross_type = "f2",
60
  chromosomes <- gsub("^[Cc]hr", "", chromosomes)
61
  chromosomes <- gsub("^0+", "", chromosomes)
62
  chromosomes[chromosomes == ""] <- "unknown"
 
63
 
64
  # Parse positions
65
  positions <- suppressWarnings(as.numeric(pos_row[marker_cols]))
66
  positions[is.na(positions)] <- 0
67
 
68
- # Individual IDs and data
69
  ind_ids <- as.character(ind_data[, 1])
70
- ind_ids <- make.unique(ind_ids)
 
 
71
 
72
  # Convert genotype matrix
73
  geno_mat <- as.matrix(ind_data[, marker_cols, drop = FALSE])
@@ -75,32 +85,27 @@ parse_advanced_cross <- function(geno_path, pheno_path, cross_type = "f2",
75
  rownames(geno_mat) <- ind_ids
76
  colnames(geno_mat) <- marker_names
77
 
78
- # Recode genotypes based on cross type
79
- if (cross_type == "f2") {
80
- # 1=AA, 2=AB, 3=BB
81
- geno_mat[geno_mat == 0] <- NA
82
- } else if (cross_type == "bc") {
83
- # 1=AA, 2=AB
84
- geno_mat[geno_mat == 3] <- 2
85
- geno_mat[geno_mat == 0] <- NA
86
- }
87
-
88
  # Remove individuals with excessive missing data (>50%)
89
  missing_rate <- rowMeans(is.na(geno_mat))
90
  valid_inds <- missing_rate <= 0.5
 
 
 
91
  geno_mat <- geno_mat[valid_inds, , drop = FALSE]
92
  ind_ids <- ind_ids[valid_inds]
93
 
94
  # Read phenotype file
95
  pheno_raw <- read.csv(pheno_path, header = TRUE, stringsAsFactors = FALSE,
96
- check.names = FALSE, na.strings = na_strings)
97
 
98
  if (ncol(pheno_raw) < 2) {
99
- stop("Phenotype file must have at least 2 columns (ID and trait)")
100
  }
101
 
102
  pheno_ids <- as.character(pheno_raw[, 1])
103
- pheno_ids <- make.unique(pheno_ids)
 
 
104
  pheno_df <- pheno_raw[, -1, drop = FALSE]
105
 
106
  # Convert phenotypes to numeric
@@ -112,12 +117,25 @@ parse_advanced_cross <- function(geno_path, pheno_path, cross_type = "f2",
112
  # Align individuals
113
  common_ids <- intersect(ind_ids, pheno_ids)
114
  if (length(common_ids) == 0) {
115
- stop("No matching individual IDs between genotype and phenotype files")
 
 
116
  }
117
 
118
  geno_mat <- geno_mat[common_ids, , drop = FALSE]
119
  pheno_df <- pheno_df[common_ids, , drop = FALSE]
120
 
 
 
 
 
 
 
 
 
 
 
 
121
  # Build genetic map by chromosome
122
  unique_chrs <- unique(chromosomes)
123
  chr_numeric <- suppressWarnings(as.numeric(unique_chrs))
@@ -143,7 +161,7 @@ parse_advanced_cross <- function(geno_path, pheno_path, cross_type = "f2",
143
  chr_positions <- chr_positions[!duplicated(chr_positions)]
144
  chr_markers <- chr_markers[!duplicated(chr_markers)]
145
 
146
- if (length(chr_positions) > 0) {
147
  map_list[[ch]] <- chr_positions
148
  geno_list[[ch]] <- list(
149
  data = geno_mat[, chr_markers, drop = FALSE],
@@ -154,542 +172,434 @@ parse_advanced_cross <- function(geno_path, pheno_path, cross_type = "f2",
154
  }
155
  }
156
 
 
 
 
 
157
  # Create cross object
158
  cross <- list(geno = geno_list, pheno = pheno_df)
159
  class(cross) <- c(cross_type, "cross")
160
 
161
- # Run quality checks
162
  cross <- jittermap(cross)
163
 
164
- # Calculate summary statistics
165
- attr(cross, "summary") <- list(
166
- n_ind = nind(cross),
167
- n_markers = totmar(cross),
168
- n_chr = nchr(cross),
169
- missing_rate = mean(nmissing(cross, what = "mar") / nind(cross)),
170
- heterozygosity = mean(calc.heterozyg(cross), na.rm = TRUE)
171
- )
172
-
173
  return(cross)
174
  }
175
 
176
  # ============================================================================
177
- # ADVANCED QTL ANALYSIS FUNCTIONS
178
  # ============================================================================
179
 
180
- # Multiple QTL mapping methods
181
- run_multiple_scans <- function(cross, pheno_col, methods = c("hk", "em", "imp", "mr", "np")) {
182
- results <- list()
183
-
184
- for (method in methods) {
185
- tryCatch({
186
- if (method == "imp") {
187
- # Need to simulate genotypes first
188
- cross_sim <- sim.geno(cross, n.draws = 64, step = 1)
189
- scan <- scanone(cross_sim, pheno.col = pheno_col, method = "imp")
190
- } else {
191
- scan <- scanone(cross, pheno.col = pheno_col, method = method)
192
- }
193
- results[[method]] <- scan
194
- }, error = function(e) {
195
- warning(paste("Method", method, "failed:", e$message))
196
- results[[method]] <- NULL
197
- })
198
- }
199
-
200
- return(results)
201
- }
202
-
203
- # Composite interval mapping
204
- run_cim <- function(cross, pheno_col, window = 10, n_markers = 5) {
205
  tryCatch({
206
- cim_result <- cim(cross, pheno.col = pheno_col, window = window,
207
- n.marcovar = n_markers, method = "hk")
208
- return(cim_result)
209
  }, error = function(e) {
210
- warning(paste("CIM failed:", e$message))
211
  return(NULL)
212
  })
213
  }
214
 
215
- # Multiple QTL mapping (MQM)
216
- run_mqm <- function(cross, pheno_col, cofactors = NULL) {
217
  tryCatch({
218
- if (is.null(cofactors)) {
219
- # Automatic cofactor selection
220
- scan <- scanone(cross, pheno.col = pheno_col, method = "hk")
221
- cofactors <- which(scan$lod > 2)
222
- }
223
- mqm_result <- mqm(cross, pheno.col = pheno_col, cofactors = cofactors)
224
- return(mqm_result)
225
  }, error = function(e) {
226
- warning(paste("MQM failed:", e$message))
227
  return(NULL)
228
  })
229
  }
230
 
231
- # Epistasis detection
232
- detect_epistasis <- function(cross, pheno_col, threshold = 5) {
233
- tryCatch({
234
- scantwo_result <- scantwo(cross, pheno.col = pheno_col, method = "hk")
235
-
236
- # Extract significant interactions
237
- lod_matrix <- scantwo_result$lod
238
- diag(lod_matrix) <- 0
239
-
240
- # Find significant interactions
241
- significant <- which(lod_matrix > threshold, arr.ind = TRUE)
242
-
243
- if (nrow(significant) > 0) {
244
- epistasis <- data.frame(
245
- chr1 = rownames(lod_matrix)[significant[, 1]],
246
- pos1 = as.numeric(rownames(lod_matrix)[significant[, 1]]),
247
- chr2 = colnames(lod_matrix)[significant[, 2]],
248
- pos2 = as.numeric(colnames(lod_matrix)[significant[, 2]]),
249
- lod = lod_matrix[significant]
250
- )
251
- return(list(epistasis = epistasis, full_result = scantwo_result))
252
- } else {
253
- return(list(epistasis = NULL, full_result = scantwo_result))
254
- }
255
- }, error = function(e) {
256
- warning(paste("Epistasis detection failed:", e$message))
257
- return(NULL)
258
- })
259
- }
260
-
261
- # QTL effect estimation
262
- estimate_qtl_effects <- function(cross, qtl_positions, pheno_col) {
263
- effects <- list()
264
 
265
- for (i in 1:nrow(qtl_positions)) {
266
- qtl <- qtl_positions[i, ]
267
-
268
- # Find nearest marker
269
- markers <- find.marker(cross, as.character(qtl$Chromosome), qtl$Position)
270
-
271
- # Calculate genotype means
272
- geno <- pull.geno(cross)[, markers]
273
- pheno <- cross$pheno[[pheno_col]]
274
-
275
- means <- tapply(pheno, geno, mean, na.rm = TRUE)
276
- se <- tapply(pheno, geno, function(x) sd(x, na.rm = TRUE) / sqrt(sum(!is.na(x))))
277
-
278
- # Calculate additive and dominance effects
279
- if (length(means) == 3) { # F2
280
- add_effect <- (means[3] - means[1]) / 2
281
- dom_effect <- means[2] - (means[1] + means[3]) / 2
282
- } else { # BC
283
- add_effect <- means[2] - means[1]
284
- dom_effect <- NA
285
- }
286
-
287
- effects[[i]] <- list(
288
- marker = markers,
289
- means = means,
290
- se = se,
291
- additive = add_effect,
292
- dominance = dom_effect
293
- )
294
  }
295
 
296
- return(effects)
297
- }
298
-
299
- # Permutation test with multiple alpha levels
300
- run_permutation_test <- function(cross, pheno_col, n_perm = 1000,
301
- alpha_levels = c(0.05, 0.01, 0.001)) {
302
- tryCatch({
303
- perms <- scanone(cross, pheno.col = pheno_col, n.perm = n_perm, method = "hk")
304
 
305
- thresholds <- list()
306
- for (alpha in alpha_levels) {
307
- thr <- summary(perms, alpha = alpha)[[1]]
308
- thresholds[[as.character(alpha)]] <- thr
 
 
 
309
  }
310
 
311
- return(list(permutations = perms, thresholds = thresholds))
312
- }, error = function(e) {
313
- warning(paste("Permutation test failed:", e$message))
314
- return(NULL)
315
- })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
316
  }
317
 
318
  # ============================================================================
319
- # ADVANCED VISUALIZATION FUNCTIONS (10+ unique plots)
320
  # ============================================================================
321
 
322
- # 1. Enhanced Manhattan plot with annotations
323
- create_manhattan_enhanced <- function(scan, threshold = 3, qtls = NULL,
324
- highlight_genes = NULL) {
 
325
  df <- as.data.frame(scan)
326
  df$marker <- rownames(df)
327
  df$significant <- df$lod >= threshold
328
 
329
- # Calculate chromosome positions for spacing
330
  chrs <- unique(df$chr)
331
- chr_lengths <- sapply(chrs, function(ch) max(df$pos[df$chr == ch]))
332
  cum_lengths <- cumsum(c(0, chr_lengths[-length(chrs)]))
333
  names(cum_lengths) <- chrs
334
 
335
  df$pos_cum <- df$pos + cum_lengths[as.character(df$chr)]
336
- chr_midpoints <- sapply(chrs, function(ch) mean(df$pos_cum[df$chr == ch]))
 
 
 
 
337
 
338
- # Create base plot
339
  p <- ggplot(df, aes(x = pos_cum, y = lod, color = chr)) +
340
  geom_point(size = 1.5, alpha = 0.7) +
341
  geom_hline(yintercept = threshold, color = "red", linetype = "dashed", size = 1) +
342
  scale_x_continuous(breaks = chr_midpoints, labels = names(chr_midpoints)) +
343
- scale_color_manual(values = rep(brewer.pal(8, "Set1"), length.out = length(chrs))) +
344
  labs(title = "Genome-wide Manhattan Plot",
345
  x = "Chromosome", y = "LOD Score") +
346
  theme_minimal() +
347
  theme(legend.position = "none",
348
  axis.text.x = element_text(angle = 45, hjust = 1))
349
 
350
- # Add QTL highlights
351
  if (!is.null(qtls) && nrow(qtls) > 0) {
352
  qtls$pos_cum <- qtls$Position_cM + cum_lengths[as.character(qtls$Chromosome)]
353
- p <- p + geom_point(data = qtls, aes(x = pos_cum, y = LOD),
354
  color = "gold", size = 4, shape = 18) +
355
- geom_text_repel(data = qtls, aes(x = pos_cum, y = LOD, label = paste0("QTL-", 1:nrow(qtls))),
356
- color = "darkred", size = 3)
 
357
  }
358
 
359
  return(p)
360
  }
361
 
362
- # 2. Interactive 3D Manhattan plot
363
- create_manhattan_3d <- function(scan, threshold = 3) {
 
 
364
  df <- as.data.frame(scan)
365
  df$marker <- rownames(df)
366
-
367
- # Create 3D plot
368
- plot_ly(df, x = ~chr, y = ~pos, z = ~lod, color = ~lod,
369
- colors = viridis(100), type = "scatter3d", mode = "markers",
370
- marker = list(size = 3, opacity = 0.7),
371
- text = ~paste("Marker:", marker, "<br>LOD:", round(lod, 3)),
372
- hoverinfo = "text") %>%
373
- layout(title = "3D Manhattan Plot",
374
- scene = list(xaxis = list(title = "Chromosome"),
375
- yaxis = list(title = "Position (cM)"),
376
- zaxis = list(title = "LOD Score"))) %>%
377
- add_trace(x = ~chr, y = ~pos, z = threshold, type = "scatter3d", mode = "lines",
378
- line = list(color = "red", width = 2), name = "Threshold", showlegend = TRUE)
 
 
 
 
379
  }
380
 
381
- # 3. Heatmap of QTL interactions
382
- create_qtl_heatmap <- function(scantwo_result) {
383
- lod_matrix <- scantwo_result$lod
384
-
385
- # Create heatmap with clustering
386
- pheatmap(lod_matrix,
387
- color = viridis(100),
388
- cluster_rows = TRUE,
389
- cluster_cols = TRUE,
390
- display_numbers = FALSE,
391
- main = "QTL Interaction Heatmap",
392
- xlab = "Position 2", ylab = "Position 1",
393
- fontsize = 8)
 
 
 
 
 
 
 
 
 
 
 
 
 
394
  }
395
 
396
- # 4. Circular genome plot with QTLs
397
- create_circular_genome <- function(cross, scan, qtls = NULL) {
398
- # Prepare data for circlize
399
- map <- pull.map(cross)
400
- chr_names <- names(map)
401
-
402
- # Initialize circos plot
403
- circos.par(start.degree = 90)
404
- circos.initialize(factors = chr_names, xlim = lapply(map, function(x) c(0, max(x))))
405
-
406
- # Add tracks
407
- circos.trackPlotRegion(factors = chr_names, ylim = c(0, 1),
408
- panel.fun = function(x, y) {
409
- circos.text(CELL_META$xcenter, CELL_META$cell.ylim[2] + 0.1,
410
- CELL_META$sector.index, cex = 0.8)
411
- })
412
-
413
- # Add LOD scores as heatmap
414
- for (chr in chr_names) {
415
- chr_scan <- scan[scan$chr == chr, ]
416
- if (nrow(chr_scan) > 0) {
417
- colors <- colorRamp2(c(0, max(scan$lod)), c("white", "red"))
418
- circos.rect(chr_scan$pos, rep(0, nrow(chr_scan)),
419
- chr_scan$pos + 1, rep(1, nrow(chr_scan)),
420
- col = colors(chr_scan$lod), border = NA)
421
- }
422
- }
423
 
424
- # Add QTL markers
425
- if (!is.null(qtls) && nrow(qtls) > 0) {
426
- for (i in 1:nrow(qtls)) {
427
- circos.points(qtls$Position_cM[i], 1, sector.index = as.character(qtls$Chromosome[i]),
428
- col = "gold", pch = 16, cex = 1.5)
429
- }
430
  }
431
 
432
- circos.clear()
 
 
 
 
 
 
 
 
433
  }
434
 
435
- # 5. Ridge plot of LOD scores by chromosome
436
  create_ridge_plot <- function(scan) {
 
 
437
  df <- as.data.frame(scan)
438
  df$chr <- factor(df$chr, levels = unique(df$chr))
439
 
440
  ggplot(df, aes(x = lod, y = chr, fill = after_stat(x))) +
441
- geom_density_ridges_gradient(scale = 3, rel_min_height = 0.01) +
442
  scale_fill_viridis_c(option = "C", name = "LOD Score") +
443
  labs(title = "LOD Score Distribution by Chromosome",
444
  x = "LOD Score", y = "Chromosome") +
445
- theme_ridges() +
446
  theme(legend.position = "right")
447
  }
448
 
449
- # 6. Correlation circle of multiple traits
450
- create_trait_correlation <- function(cross, traits = NULL) {
451
- if (is.null(traits)) traits <- names(cross$pheno)
452
- if (length(traits) < 2) return(NULL)
453
-
454
- # Calculate correlations
455
- cor_matrix <- cor(cross$pheno[, traits], use = "complete.obs")
456
-
457
- # Create correlation plot
458
- ggcorrplot(cor_matrix,
459
- method = "circle",
460
- type = "lower",
461
- lab = TRUE,
462
- lab_size = 3,
463
- title = "Trait Correlation Matrix",
464
- colors = c("#FF6B6B", "white", "#4ECDC4")) +
465
- theme_minimal()
466
- }
467
-
468
- # 7. Effect size comparison across methods
469
- create_method_comparison <- function(scan_results, qtls) {
470
- # Extract peak LOD for each method
471
- method_comparison <- data.frame()
472
 
473
- for (method in names(scan_results)) {
474
- scan <- scan_results[[method]]
475
- if (!is.null(scan)) {
476
- max_lod <- max(scan$lod, na.rm = TRUE)
477
- method_comparison <- rbind(method_comparison,
478
- data.frame(Method = method, MaxLOD = max_lod))
479
- }
480
- }
481
 
482
- # Create comparison plot
483
- p1 <- ggplot(method_comparison, aes(x = reorder(Method, -MaxLOD), y = MaxLOD, fill = Method)) +
484
- geom_bar(stat = "identity", alpha = 0.8) +
485
- geom_text(aes(label = round(MaxLOD, 2)), vjust = -0.5, size = 4) +
486
- scale_fill_brewer(palette = "Set2") +
487
- labs(title = "Maximum LOD Score by Method",
488
- x = "Mapping Method", y = "Maximum LOD") +
489
- theme_minimal() +
490
- theme(legend.position = "none")
491
 
492
- # If we have QTLs, create effect size plot
493
- if (!is.null(qtls) && nrow(qtls) > 0) {
494
- p2 <- ggplot(qtls, aes(x = reorder(paste(Chromosome, "@", Position_cM), -LOD),
495
- y = LOD, fill = as.factor(Chromosome))) +
496
- geom_bar(stat = "identity", alpha = 0.8) +
497
- geom_errorbar(aes(ymin = LOD - 1, ymax = LOD + 1), width = 0.2) +
498
- scale_fill_brewer(palette = "Set3") +
499
- labs(title = "Significant QTLs by LOD Score",
500
- x = "QTL Location", y = "LOD Score") +
501
- theme_minimal() +
502
- theme(legend.position = "none",
503
- axis.text.x = element_text(angle = 45, hjust = 1))
504
-
505
- return(list(p1 = p1, p2 = p2))
506
- }
507
 
508
- return(p1)
509
  }
510
 
511
- # 8. Genetic map density plot
512
- create_map_density <- function(cross) {
513
- map <- pull.map(cross)
514
 
515
- # Calculate marker density
516
- density_data <- data.frame()
517
  for (chr in names(map)) {
518
  positions <- map[[chr]]
519
  if (length(positions) > 1) {
520
  gaps <- diff(positions)
521
- density_data <- rbind(density_data,
522
- data.frame(Chromosome = chr,
523
- Gap = gaps,
524
- Position = positions[-1]))
525
  }
526
  }
527
 
528
- ggplot(density_data, aes(x = Gap, fill = Chromosome)) +
 
 
529
  geom_histogram(bins = 30, alpha = 0.6, position = "identity") +
530
  scale_fill_brewer(palette = "Set1") +
531
- labs(title = "Marker Density Distribution",
532
- x = "Inter-marker Distance (cM)", y = "Count") +
533
  theme_minimal() +
534
- theme(legend.position = "right")
535
  }
536
 
537
- # 9. Missing data pattern visualization
538
- create_missing_pattern <- function(cross) {
539
- # Calculate missing data per individual and marker
540
- missing_individuals <- nmissing(cross, what = "ind")
541
- missing_markers <- nmissing(cross, what = "mar")
542
 
543
- # Create data frames
544
- ind_df <- data.frame(Individual = 1:nind(cross), Missing = missing_individuals)
545
- mar_df <- data.frame(Marker = 1:totmar(cross), Missing = missing_markers)
546
 
547
- p1 <- ggplot(ind_df, aes(x = Individual, y = Missing)) +
548
- geom_bar(stat = "identity", fill = "steelblue", alpha = 0.7) +
549
- labs(title = "Missing Data per Individual",
550
- x = "Individual Index", y = "Number of Missing Markers") +
551
- theme_minimal()
552
 
553
- p2 <- ggplot(mar_df, aes(x = Marker, y = Missing)) +
554
- geom_bar(stat = "identity", fill = "darkorange", alpha = 0.7) +
555
- labs(title = "Missing Data per Marker",
556
- x = "Marker Index", y = "Number of Missing Individuals") +
557
- theme_minimal()
558
 
559
- return(plot_grid(p1, p2, ncol = 2))
560
- }
561
-
562
- # 10. QTL effect size volcano plot
563
- create_volcano_plot <- function(scan, qtls) {
564
- df <- as.data.frame(scan)
565
- df$marker <- rownames(df)
566
 
567
- # Calculate effect size proxy (LOD / position)
568
- df$effect_size <- df$lod / (df$pos + 1)
569
- df$is_qtl <- df$marker %in% qtls$Marker
570
-
571
- ggplot(df, aes(x = effect_size, y = -log10(1 - lod/max(lod, na.rm = TRUE) + 0.001),
572
- color = is_qtl, label = ifelse(is_qtl, marker, ""))) +
573
- geom_point(alpha = 0.6, size = 2) +
574
- geom_text_repel(size = 3, max.overlaps = 20) +
575
- scale_color_manual(values = c("FALSE" = "gray", "TRUE" = "red")) +
576
- labs(title = "QTL Effect Size Volcano Plot",
577
- x = "Effect Size (LOD/Position)",
578
- y = "-log10(p-value proxy)") +
579
  theme_minimal() +
580
  theme(legend.position = "none")
581
  }
582
 
583
- # 11. Haplotype visualization
584
- create_haplotype_plot <- function(cross, chr_name, start_pos = NULL, end_pos = NULL) {
585
- # Get chromosome data
586
- chr_data <- cross$geno[[as.character(chr_name)]]
587
-
588
- if (is.null(start_pos)) start_pos <- min(chr_data$map)
589
- if (is.null(end_pos)) end_pos <- max(chr_data$map)
590
-
591
- # Select markers in region
592
- marker_idx <- which(chr_data$map >= start_pos & chr_data$map <= end_pos)
593
- markers <- names(chr_data$map)[marker_idx]
594
-
595
- if (length(markers) == 0) return(NULL)
596
-
597
- # Extract genotypes
598
- genotypes <- chr_data$data[, markers, drop = FALSE]
599
-
600
- # Create heatmap
601
- pheatmap(genotypes,
602
- color = c("white", "lightblue", "blue", "darkblue"),
603
- cluster_rows = TRUE,
604
- cluster_cols = FALSE,
605
- show_rownames = FALSE,
606
- main = paste("Haplotype Map - Chromosome", chr_name),
607
- xlab = "Markers", ylab = "Individuals")
608
- }
609
-
610
- # 12. Interactive parallel coordinates for multiple traits
611
- create_parallel_coordinates <- function(cross, traits = NULL) {
612
- if (is.null(traits)) traits <- names(cross$pheno)
613
- if (length(traits) < 2) return(NULL)
614
-
615
- # Prepare data
616
- plot_data <- cross$pheno[, traits, drop = FALSE]
617
- plot_data$ID <- rownames(plot_data)
618
-
619
- # Normalize data
620
- plot_data_norm <- plot_data
621
- for (trait in traits) {
622
- plot_data_norm[[trait]] <- scale(plot_data[[trait]])
623
  }
624
 
625
- # Create parallel coordinates plot
626
- plot_ly(type = 'parcoords',
627
- line = list(color = ~1:nrow(plot_data_norm),
628
- colorscale = 'Viridis'),
629
- dimensions = lapply(traits, function(trait) {
630
- list(label = trait,
631
- values = plot_data_norm[[trait]],
632
- range = c(-3, 3))
633
- })) %>%
634
- layout(title = "Multi-trait Parallel Coordinates Plot")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
635
  }
636
 
637
  # ============================================================================
638
- # UI COMPONENTS
639
  # ============================================================================
640
 
641
  ui <- dashboardPage(
642
- dashboardHeader(title = "Advanced QTL Analysis Pipeline", titleWidth = 350),
643
 
644
- dashboardSidebar(width = 350,
645
  sidebarMenu(
646
  menuItem("Data Input", tabName = "data", icon = icon("upload")),
647
- menuItem("QTL Analysis", tabName = "analysis", icon = icon("chart-line")),
648
- menuItem("Visualizations", tabName = "visualizations", icon = icon("chart-bar"),
649
- menuSubItem("Manhattan Plots", tabName = "manhattan"),
650
- menuSubItem("Genome Views", tabName = "genome"),
651
- menuSubItem("Interaction Maps", tabName = "interactions"),
652
- menuSubItem("Comparative Plots", tabName = "comparative"),
653
- menuSubItem("Quality Control", tabName = "qc")
654
- ),
655
- menuItem("Results", tabName = "results", icon = icon("table")),
656
- menuItem("Reports", tabName = "reports", icon = icon("file-alt"))
657
  ),
658
 
659
- # Input controls
660
  div(style = "padding: 15px;",
661
  h4("Data Upload", style = "color: #3c8dbc;"),
662
- fileInput("geno_file", "Genotype CSV", accept = ".csv"),
663
- fileInput("pheno_file", "Phenotype CSV", accept = ".csv"),
 
 
 
 
 
 
664
 
 
 
 
665
  selectInput("cross_type", "Cross Type",
666
- choices = c("F2 Intercross" = "f2", "Backcross" = "bc",
667
- "RIL (Selfing)" = "riself", "RIL (Sib-mating)" = "risib"),
 
668
  selected = "f2"),
669
 
670
- hr(),
671
-
672
- h4("Analysis Parameters", style = "color: #3c8dbc;"),
673
  selectInput("pheno_trait", "Phenotype Trait", choices = NULL),
674
 
675
- selectInput("scan_methods", "Mapping Methods",
676
- choices = c("Haley-Knott" = "hk", "EM" = "em",
677
- "Imputation" = "imp", "Marker Regression" = "mr"),
678
- selected = c("hk", "em"), multiple = TRUE),
 
679
 
680
- numericInput("lod_threshold", "LOD Threshold", value = 3.0, min = 0, max = 20, step = 0.5),
681
- numericInput("n_permutations", "Permutations", value = 1000, min = 0, max = 10000),
682
 
683
- checkboxInput("run_cim", "Composite Interval Mapping", value = TRUE),
684
- checkboxInput("run_epistasis", "Epistasis Detection", value = TRUE),
685
- checkboxInput("run_mqm", "Multiple QTL Mapping", value = TRUE),
686
 
687
  actionButton("run_analysis", "RUN ANALYSIS",
688
- icon = icon("play"),
689
- style = "background-color: #3c8dbc; color: white; width: 100%; margin-top: 20px;"),
 
 
690
 
691
- downloadButton("download_results", "Download Results",
692
- style = "width: 100%; margin-top: 10px;")
693
  )
694
  ),
695
 
@@ -704,31 +614,30 @@ ui <- dashboardPage(
704
  border-radius: 10px;
705
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
706
  }
707
- .btn-custom {
708
- margin: 5px;
709
- }
710
  "))
711
  ),
712
 
713
  tabItems(
714
- # Data Input Tab
715
  tabItem(tabName = "data",
 
 
 
 
 
716
  fluidRow(
717
  box(title = "Data Summary", status = "primary", solidHeader = TRUE, width = 12,
718
  verbatimTextOutput("data_summary")
719
  )
720
  ),
721
  fluidRow(
722
- box(title = "Genotype Preview", status = "info", width = 6,
723
- DTOutput("geno_preview") %>% withSpinner()
724
- ),
725
- box(title = "Phenotype Preview", status = "info", width = 6,
726
- DTOutput("pheno_preview") %>% withSpinner()
727
  )
728
  ),
729
  fluidRow(
730
- box(title = "Quality Control Metrics", status = "warning", width = 12,
731
- plotOutput("qc_metrics", height = "400px") %>% withSpinner()
732
  )
733
  )
734
  ),
@@ -736,114 +645,49 @@ ui <- dashboardPage(
736
  # Analysis Tab
737
  tabItem(tabName = "analysis",
738
  fluidRow(
739
- box(title = "Analysis Progress", status = "primary", solidHeader = TRUE, width = 12,
740
  verbatimTextOutput("analysis_status")
741
  )
742
  ),
743
  fluidRow(
744
- box(title = "QTL Detection Summary", status = "success", width = 12,
745
- DTOutput("qtl_summary") %>% withSpinner()
746
- )
747
- ),
748
- fluidRow(
749
- box(title = "Method Comparison", status = "info", width = 12,
750
- plotOutput("method_comparison", height = "500px") %>% withSpinner()
751
- )
752
- )
753
- ),
754
-
755
- # Manhattan Plots Tab
756
- tabItem(tabName = "manhattan",
757
- fluidRow(
758
- box(title = "Enhanced Manhattan Plot", status = "primary", width = 12,
759
- plotOutput("manhattan_enhanced", height = "600px") %>% withSpinner()
760
- )
761
- ),
762
- fluidRow(
763
- box(title = "3D Interactive Manhattan", status = "info", width = 12,
764
- plotlyOutput("manhattan_3d", height = "600px") %>% withSpinner()
765
- )
766
- ),
767
- fluidRow(
768
- box(title = "Ridge Plot by Chromosome", status = "success", width = 12,
769
- plotOutput("ridge_plot", height = "500px") %>% withSpinner()
770
- )
771
- )
772
- ),
773
-
774
- # Genome Views Tab
775
- tabItem(tabName = "genome",
776
- fluidRow(
777
- box(title = "Circular Genome Plot", status = "primary", width = 12,
778
- plotOutput("circular_genome", height = "700px") %>% withSpinner()
779
  )
780
  ),
781
  fluidRow(
782
- box(title = "Marker Density Map", status = "info", width = 12,
783
- plotOutput("map_density", height = "500px") %>% withSpinner()
784
  )
785
  ),
786
  fluidRow(
787
- box(title = "Haplotype Visualization", status = "success", width = 12,
788
- selectInput("haplotype_chr", "Select Chromosome:", choices = NULL),
789
- plotOutput("haplotype_plot", height = "600px") %>% withSpinner()
790
  )
791
  )
792
  ),
793
 
794
- # Interactions Tab
795
- tabItem(tabName = "interactions",
796
  fluidRow(
797
- box(title = "QTL Interaction Heatmap", status = "primary", width = 12,
798
- plotOutput("qtl_heatmap", height = "700px") %>% withSpinner()
799
- )
800
- ),
801
- fluidRow(
802
- box(title = "Epistasis Network", status = "info", width = 12,
803
- plotOutput("epistasis_network", height = "600px") %>% withSpinner()
804
- )
805
- ),
806
- fluidRow(
807
- box(title = "Volcano Plot", status = "success", width = 12,
808
- plotOutput("volcano_plot", height = "500px") %>% withSpinner()
809
- )
810
- )
811
- ),
812
-
813
- # Comparative Plots Tab
814
- tabItem(tabName = "comparative",
815
- fluidRow(
816
- box(title = "Multi-trait Correlation", status = "primary", width = 12,
817
- plotOutput("trait_correlation", height = "600px") %>% withSpinner()
818
- )
819
- ),
820
- fluidRow(
821
- box(title = "Parallel Coordinates", status = "info", width = 12,
822
- plotlyOutput("parallel_coords", height = "600px") %>% withSpinner()
823
- )
824
- ),
825
- fluidRow(
826
- box(title = "Effect Size Comparison", status = "success", width = 12,
827
- plotOutput("effect_comparison", height = "500px") %>% withSpinner()
828
- )
829
- )
830
- ),
831
-
832
- # Quality Control Tab
833
- tabItem(tabName = "qc",
834
- fluidRow(
835
- box(title = "Missing Data Patterns", status = "primary", width = 12,
836
- plotOutput("missing_patterns", height = "500px") %>% withSpinner()
837
  )
838
  ),
839
  fluidRow(
840
- box(title = "Genotype Distribution", status = "info", width = 12,
841
- plotOutput("genotype_dist", height = "500px") %>% withSpinner()
 
 
 
842
  )
843
  ),
844
  fluidRow(
845
- box(title = "Phenotype Distribution", status = "success", width = 12,
846
- plotOutput("phenotype_dist", height = "500px") %>% withSpinner()
 
847
  )
848
  )
849
  ),
@@ -852,33 +696,81 @@ ui <- dashboardPage(
852
  tabItem(tabName = "results",
853
  fluidRow(
854
  box(title = "Significant QTLs", status = "primary", width = 12,
855
- DTOutput("significant_qtls") %>% withSpinner()
856
  )
857
  ),
858
  fluidRow(
859
- box(title = "QTL Effects", status = "info", width = 12,
860
- DTOutput("qtl_effects") %>% withSpinner()
861
  )
862
  ),
863
  fluidRow(
864
- box(title = "Permutation Thresholds", status = "success", width = 12,
865
- DTOutput("permutation_results") %>% withSpinner()
866
  )
867
  )
868
  ),
869
 
870
- # Reports Tab
871
- tabItem(tabName = "reports",
872
- fluidRow(
873
- box(title = "Analysis Report", status = "primary", width = 12,
874
- uiOutput("report_content")
875
- )
876
- ),
877
  fluidRow(
878
- box(title = "Download Options", status = "info", width = 12,
879
- downloadButton("download_report_pdf", "Download PDF Report", class = "btn-custom"),
880
- downloadButton("download_report_html", "Download HTML Report", class = "btn-custom"),
881
- downloadButton("download_all_plots", "Download All Plots", class = "btn-custom")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
882
  )
883
  )
884
  )
@@ -887,29 +779,54 @@ ui <- dashboardPage(
887
  )
888
 
889
  # ============================================================================
890
- # SERVER LOGIC
891
  # ============================================================================
892
 
893
  server <- function(input, output, session) {
894
 
895
- # Reactive values for storing results
896
  cross_data <- reactiveVal(NULL)
897
- scan_results <- reactiveVal(NULL)
898
- cim_results <- reactiveVal(NULL)
899
- mqm_results <- reactiveVal(NULL)
900
- epistasis_results <- reactiveVal(NULL)
901
- qtl_table <- reactiveVal(NULL)
902
- permutation_results <- reactiveVal(NULL)
903
- analysis_complete <- reactiveVal(FALSE)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
904
 
905
  # Load data
906
  observeEvent(c(input$geno_file, input$pheno_file), {
907
  req(input$geno_file, input$pheno_file)
908
 
909
- showNotification("Loading and parsing data...", type = "info", duration = 3)
910
 
911
  tryCatch({
912
- cross <- parse_advanced_cross(
913
  input$geno_file$datapath,
914
  input$pheno_file$datapath,
915
  input$cross_type
@@ -917,18 +834,15 @@ server <- function(input, output, session) {
917
 
918
  cross_data(cross)
919
 
920
- # Update UI choices
921
- updateSelectInput(session, "pheno_trait",
922
  choices = names(cross$pheno),
923
  selected = names(cross$pheno)[1])
924
 
925
- updateSelectInput(session, "haplotype_chr",
926
- choices = names(cross$geno))
927
-
928
  showNotification("Data loaded successfully!", type = "success", duration = 3)
929
 
930
  }, error = function(e) {
931
- showNotification(paste("Error loading data:", e$message), type = "error", duration = 10)
932
  })
933
  })
934
 
@@ -937,505 +851,223 @@ server <- function(input, output, session) {
937
  cross <- cross_data()
938
  req(cross, input$pheno_trait)
939
 
940
- showNotification("Starting QTL analysis...", type = "info", duration = 5)
941
 
942
- withProgress(message = "Running QTL Analysis", value = 0, {
943
 
944
- # Run multiple scan methods
945
- incProgress(0.2, detail = "Running genome scans...")
946
  pheno_idx <- which(names(cross$pheno) == input$pheno_trait)
947
- scans <- run_multiple_scans(cross, pheno_idx, methods = input$scan_methods)
948
- scan_results(scans)
949
-
950
- # Run CIM
951
- if (input$run_cim) {
952
- incProgress(0.2, detail = "Running Composite Interval Mapping...")
953
- cim <- run_cim(cross, pheno_idx)
954
- cim_results(cim)
955
- }
956
 
957
- # Run MQM
958
- if (input$run_mqm) {
959
- incProgress(0.2, detail = "Running Multiple QTL Mapping...")
960
- mqm <- run_mqm(cross, pheno_idx)
961
- mqm_results(mqm)
962
- }
963
-
964
- # Detect epistasis
965
- if (input$run_epistasis) {
966
- incProgress(0.2, detail = "Detecting epistatic interactions...")
967
- epi <- detect_epistasis(cross, pheno_idx, threshold = input$lod_threshold)
968
- epistasis_results(epi)
969
  }
970
 
971
- # Run permutations
972
- if (input$n_permutations > 0) {
973
- incProgress(0.1, detail = "Running permutation tests...")
974
- perms <- run_permutation_test(cross, pheno_idx, n_perm = input$n_permutations)
975
- permutation_results(perms)
976
- }
977
 
978
- # Identify QTLs
979
- incProgress(0.1, detail = "Identifying significant QTLs...")
980
- best_scan <- scans[[1]] # Use first method for initial QTL detection
981
- if (!is.null(best_scan)) {
982
- qtls <- find_qtls(best_scan, input$lod_threshold)
983
- qtl_table(qtls)
984
  }
985
 
986
- analysis_complete(TRUE)
987
  showNotification("Analysis complete!", type = "success", duration = 5)
988
  })
989
  })
990
 
991
- # ==========================================================================
992
- # RENDER FUNCTIONS FOR EACH TAB
993
- # ==========================================================================
994
-
995
- # Data summary
996
  output$data_summary <- renderPrint({
997
  cross <- cross_data()
998
- if (is.null(cross)) return("No data loaded. Please upload CSV files.")
999
-
1000
- cat("=== QTL DATA SUMMARY ===\n\n")
1001
- cat("Cross Type:", class(cross)[1], "\n")
1002
- cat("Individuals:", nind(cross), "\n")
1003
- cat("Markers:", totmar(cross), "\n")
1004
- cat("Chromosomes:", nchr(cross), "\n")
1005
- cat("Phenotypes:", paste(names(cross$pheno), collapse = ", "), "\n")
1006
- cat("\nMissing Data Rate:", round(attr(cross, "summary")$missing_rate * 100, 2), "%\n")
1007
- cat("Heterozygosity:", round(attr(cross, "summary")$heterozygosity, 4), "\n")
 
 
 
 
1008
  })
1009
 
1010
- # Data previews
1011
- output$geno_preview <- renderDT({
1012
- cross <- cross_data()
1013
- req(cross)
1014
-
1015
- # Get first few markers and individuals
1016
- geno_preview <- cross$geno[[1]]$data[1:min(10, nind(cross)), 1:min(10, totmar(cross))]
1017
- datatable(geno_preview, options = list(scrollX = TRUE, pageLength = 5))
 
 
 
 
 
 
1018
  })
1019
 
1020
- output$pheno_preview <- renderDT({
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1021
  cross <- cross_data()
1022
  req(cross)
1023
-
1024
- datatable(cross$pheno[1:min(20, nind(cross)), , drop = FALSE],
1025
- options = list(scrollX = TRUE, pageLength = 5))
1026
  })
1027
 
1028
- # QC metrics plot
1029
- output$qc_metrics <- renderPlot({
1030
  cross <- cross_data()
1031
  req(cross)
1032
-
1033
- # Calculate various QC metrics
1034
- missing_ind <- nmissing(cross, what = "ind")
1035
- missing_mar <- nmissing(cross, what = "mar")
1036
- heterozyg <- calc.heterozyg(cross)
1037
-
1038
- # Create multi-panel plot
1039
- p1 <- ggplot(data.frame(Missing = missing_ind), aes(x = Missing)) +
1040
- geom_histogram(bins = 30, fill = "steelblue", alpha = 0.7) +
1041
- labs(title = "Missing Data per Individual", x = "Number Missing", y = "Count") +
1042
- theme_minimal()
1043
-
1044
- p2 <- ggplot(data.frame(Missing = missing_mar), aes(x = Missing)) +
1045
- geom_histogram(bins = 30, fill = "darkorange", alpha = 0.7) +
1046
- labs(title = "Missing Data per Marker", x = "Number Missing", y = "Count") +
1047
- theme_minimal()
1048
-
1049
- p3 <- ggplot(data.frame(Heterozygosity = heterozyg), aes(x = Heterozygosity)) +
1050
- geom_histogram(bins = 30, fill = "forestgreen", alpha = 0.7) +
1051
- labs(title = "Heterozygosity Distribution", x = "Heterozygosity", y = "Count") +
1052
- theme_minimal()
1053
-
1054
- plot_grid(p1, p2, p3, ncol = 3)
1055
- }, height = 400)
1056
-
1057
- # QTL summary table
1058
- output$qtl_summary <- renderDT({
1059
- qtls <- qtl_table()
1060
- req(qtls, nrow(qtls) > 0)
1061
-
1062
- datatable(qtls,
1063
- options = list(pageLength = 10, scrollX = TRUE),
1064
- rownames = FALSE) %>%
1065
- formatStyle("LOD",
1066
- background = styleColorBar(range(qtls$LOD), "lightblue"))
1067
  })
1068
 
1069
- # Method comparison plot
1070
- output$method_comparison <- renderPlot({
1071
- scans <- scan_results()
1072
- qtls <- qtl_table()
1073
- req(scans)
1074
-
1075
- create_method_comparison(scans, qtls)
1076
- }, height = 500)
1077
-
1078
- # Enhanced Manhattan plot
1079
- output$manhattan_enhanced <- renderPlot({
1080
- scans <- scan_results()
1081
- qtls <- qtl_table()
1082
- req(scans)
1083
-
1084
- create_manhattan_enhanced(scans[[1]], input$lod_threshold, qtls)
1085
- }, height = 600)
1086
 
1087
- # 3D Manhattan plot
1088
- output$manhattan_3d <- renderPlotly({
1089
- scans <- scan_results()
1090
- req(scans)
1091
-
1092
- create_manhattan_3d(scans[[1]], input$lod_threshold)
1093
- }, height = 600)
1094
 
1095
- # Ridge plot
1096
  output$ridge_plot <- renderPlot({
1097
- scans <- scan_results()
1098
- req(scans)
1099
-
1100
- create_ridge_plot(scans[[1]])
1101
- }, height = 500)
1102
-
1103
- # Circular genome plot
1104
- output$circular_genome <- renderPlot({
1105
- cross <- cross_data()
1106
- scans <- scan_results()
1107
- qtls <- qtl_table()
1108
- req(cross, scans)
1109
-
1110
- create_circular_genome(cross, scans[[1]], qtls)
1111
- }, height = 700)
1112
 
1113
- # Map density
1114
- output$map_density <- renderPlot({
1115
  cross <- cross_data()
1116
  req(cross)
1117
-
1118
- create_map_density(cross)
1119
- }, height = 500)
1120
-
1121
- # Haplotype plot
1122
- output$haplotype_plot <- renderPlot({
1123
- cross <- cross_data()
1124
- req(cross, input$haplotype_chr)
1125
-
1126
- create_haplotype_plot(cross, input$haplotype_chr)
1127
- }, height = 600)
1128
-
1129
- # QTL heatmap
1130
- output$qtl_heatmap <- renderPlot({
1131
- epi <- epistasis_results()
1132
- req(epi, !is.null(epi$full_result))
1133
-
1134
- create_qtl_heatmap(epi$full_result)
1135
- }, height = 700)
1136
-
1137
- # Epistasis network
1138
- output$epistasis_network <- renderPlot({
1139
- epi <- epistasis_results()
1140
- req(epi, !is.null(epi$epistasis), nrow(epi$epistasis) > 0)
1141
-
1142
- # Create network plot
1143
- library(igraph)
1144
- edges <- epi$epistasis[, c("chr1", "chr2")]
1145
- g <- graph_from_data_frame(edges, directed = FALSE)
1146
-
1147
- plot(g, vertex.size = 20, vertex.label.cex = 0.8,
1148
- edge.width = epi$epistasis$lod / max(epi$epistasis$lod) * 5,
1149
- main = "Epistatic Interaction Network",
1150
- layout = layout_in_circle)
1151
- }, height = 600)
1152
-
1153
- # Volcano plot
1154
- output$volcano_plot <- renderPlot({
1155
- scans <- scan_results()
1156
- qtls <- qtl_table()
1157
- req(scans)
1158
-
1159
- create_volcano_plot(scans[[1]], qtls)
1160
- }, height = 500)
1161
 
1162
- # Trait correlation
1163
- output$trait_correlation <- renderPlot({
1164
  cross <- cross_data()
1165
- req(cross)
1166
-
1167
- create_trait_correlation(cross)
1168
- }, height = 600)
1169
 
1170
- # Parallel coordinates
1171
- output$parallel_coords <- renderPlotly({
1172
- cross <- cross_data()
1173
- req(cross)
1174
-
1175
- create_parallel_coordinates(cross)
1176
- }, height = 600)
1177
 
1178
- # Effect comparison
1179
- output$effect_comparison <- renderPlot({
1180
- cross <- cross_data()
1181
- qtls <- qtl_table()
1182
- req(cross, qtls, nrow(qtls) > 0)
1183
-
1184
- # Estimate effects for top QTLs
1185
- effects <- estimate_qtl_effects(cross, qtls[1:min(5, nrow(qtls)), ],
1186
- which(names(cross$pheno) == input$pheno_trait))
1187
-
1188
- # Create effect plot
1189
- effect_df <- data.frame()
1190
- for (i in seq_along(effects)) {
1191
- effect <- effects[[i]]
1192
- temp_df <- data.frame(
1193
- QTL = paste0("QTL-", i),
1194
- Genotype = names(effect$means),
1195
- Mean = effect$means,
1196
- SE = effect$se
1197
- )
1198
- effect_df <- rbind(effect_df, temp_df)
1199
- }
1200
-
1201
- ggplot(effect_df, aes(x = QTL, y = Mean, fill = Genotype)) +
1202
- geom_bar(stat = "identity", position = position_dodge(0.9), alpha = 0.8) +
1203
- geom_errorbar(aes(ymin = Mean - SE, ymax = Mean + SE),
1204
- position = position_dodge(0.9), width = 0.2) +
1205
- scale_fill_brewer(palette = "Set2") +
1206
- labs(title = "QTL Effect Sizes",
1207
- x = "QTL", y = "Mean Phenotype") +
1208
- theme_minimal()
1209
- }, height = 500)
1210
-
1211
- # Missing patterns
1212
- output$missing_patterns <- renderPlot({
1213
  cross <- cross_data()
1214
  req(cross)
1215
-
1216
- create_missing_pattern(cross)
1217
- }, height = 500)
1218
 
1219
- # Genotype distribution
1220
- output$genotype_dist <- renderPlot({
1221
- cross <- cross_data()
1222
- req(cross)
1223
-
1224
- # Calculate genotype frequencies
1225
- geno_freq <- data.frame()
1226
- for (chr in names(cross$geno)) {
1227
- for (marker in names(cross$geno[[chr]]$map)) {
1228
- geno <- cross$geno[[chr]]$data[, marker]
1229
- freq <- table(geno, useNA = "ifany")
1230
- temp_df <- data.frame(
1231
- Chromosome = chr,
1232
- Marker = marker,
1233
- Genotype = names(freq),
1234
- Frequency = as.numeric(freq) / nind(cross)
1235
- )
1236
- geno_freq <- rbind(geno_freq, temp_df)
1237
- }
1238
- }
1239
-
1240
- ggplot(geno_freq, aes(x = Marker, y = Frequency, fill = Genotype)) +
1241
- geom_bar(stat = "identity", position = "stack", alpha = 0.8) +
1242
- facet_wrap(~Chromosome, scales = "free_x", ncol = 3) +
1243
- scale_fill_brewer(palette = "Set1") +
1244
- labs(title = "Genotype Distribution by Marker",
1245
- x = "Marker", y = "Frequency") +
1246
- theme_minimal() +
1247
- theme(axis.text.x = element_blank(),
1248
- axis.ticks.x = element_blank())
1249
- }, height = 500)
1250
-
1251
- # Phenotype distribution
1252
- output$phenotype_dist <- renderPlot({
1253
  cross <- cross_data()
1254
- req(cross, input$pheno_trait)
1255
-
1256
- pheno <- cross$pheno[[input$pheno_trait]]
1257
-
1258
- p1 <- ggplot(data.frame(Phenotype = pheno), aes(x = Phenotype)) +
1259
- geom_histogram(bins = 30, fill = "steelblue", alpha = 0.7) +
1260
- labs(title = "Phenotype Distribution",
1261
- x = input$pheno_trait, y = "Count") +
1262
- theme_minimal()
1263
 
1264
- p2 <- ggplot(data.frame(Phenotype = pheno), aes(sample = Phenotype)) +
1265
- stat_qq(color = "steelblue", alpha = 0.7) +
1266
- stat_qq_line(color = "red") +
1267
- labs(title = "Q-Q Plot", x = "Theoretical", y = "Sample") +
1268
- theme_minimal()
1269
 
1270
- plot_grid(p1, p2, ncol = 2)
1271
- }, height = 500)
1272
 
1273
- # Significant QTLs table
1274
- output$significant_qtls <- renderDT({
1275
- qtls <- qtl_table()
1276
  req(qtls, nrow(qtls) > 0)
1277
 
1278
  datatable(qtls,
1279
- options = list(pageLength = 15, scrollX = TRUE),
1280
- rownames = FALSE) %>%
 
 
 
 
 
1281
  formatStyle("LOD",
1282
- background = styleColorBar(c(0, max(qtls$LOD, na.rm = TRUE)), "lightblue")) %>%
1283
  formatStyle("PVE_percent",
1284
- background = styleColorBar(c(0, 100), "lightgreen"))
1285
  })
1286
 
1287
- # QTL effects table
1288
- output$qtl_effects <- renderDT({
1289
- cross <- cross_data()
1290
- qtls <- qtl_table()
1291
- req(cross, qtls, nrow(qtls) > 0)
1292
-
1293
- effects <- estimate_qtl_effects(cross, qtls[1:min(10, nrow(qtls)), ],
1294
- which(names(cross$pheno) == input$pheno_trait))
1295
 
1296
- effect_table <- data.frame()
1297
- for (i in seq_along(effects)) {
1298
- effect <- effects[[i]]
1299
- effect_table <- rbind(effect_table,
1300
- data.frame(
1301
- QTL = i,
1302
- Marker = effect$marker,
1303
- Additive_Effect = round(effect$additive, 3),
1304
- Dominance_Effect = round(effect$dominance, 3),
1305
- stringsAsFactors = FALSE
1306
- ))
1307
- }
1308
-
1309
- datatable(effect_table, options = list(pageLength = 10))
1310
- })
1311
-
1312
- # Permutation results table
1313
- output$permutation_results <- renderDT({
1314
- perms <- permutation_results()
1315
- req(perms)
1316
 
1317
- threshold_df <- data.frame(
1318
- Alpha = names(perms$thresholds),
1319
- Threshold = unlist(perms$thresholds)
1320
  )
1321
 
1322
- datatable(threshold_df, options = list(pageLength = 5))
 
 
1323
  })
1324
 
1325
- # Report content
1326
- output$report_content <- renderUI({
1327
- if (!analysis_complete()) {
1328
- return(div("Run analysis first to generate report.",
1329
- style = "padding: 20px; text-align: center;"))
1330
- }
1331
-
1332
- qtls <- qtl_table()
1333
- n_qtls <- ifelse(is.null(qtls), 0, nrow(qtls))
1334
-
1335
- HTML(paste0("
1336
- <div style='padding: 20px;'>
1337
- <h2>QTL Analysis Report</h2>
1338
- <hr>
1339
- <h3>Summary Statistics</h3>
1340
- <ul>
1341
- <li>Total QTLs detected: ", n_qtls, "</li>
1342
- <li>LOD threshold used: ", input$lod_threshold, "</li>
1343
- <li>Number of permutations: ", input$n_permutations, "</li>
1344
- <li>Mapping methods: ", paste(input$scan_methods, collapse = ", "), "</li>
1345
- </ul>
1346
-
1347
- <h3>Analysis Parameters</h3>
1348
- <ul>
1349
- <li>Cross type: ", input$cross_type, "</li>
1350
- <li>Phenotype trait: ", input$pheno_trait, "</li>
1351
- <li>CIM performed: ", input$run_cim, "</li>
1352
- <li>Epistasis detected: ", input$run_epistasis, "</li>
1353
- </ul>
1354
-
1355
- <h3>Next Steps</h3>
1356
- <ul>
1357
- <li>Validate significant QTLs in independent populations</li>
1358
- <li>Fine-map QTL regions with additional markers</li>
1359
- <li>Identify candidate genes within QTL intervals</li>
1360
- <li>Validate epistatic interactions</li>
1361
- </ul>
1362
- </div>
1363
- "))
1364
- })
1365
-
1366
- # Download handlers
1367
  output$download_results <- downloadHandler(
1368
- filename = function() paste0("qtl_results_", Sys.Date(), ".zip"),
1369
  content = function(file) {
1370
- # Create temporary directory
1371
- tmpdir <- tempdir()
1372
-
1373
- # Save QTL table
1374
- qtls <- qtl_table()
1375
  if (!is.null(qtls) && nrow(qtls) > 0) {
1376
- write.csv(qtls, file.path(tmpdir, "significant_qtls.csv"), row.names = FALSE)
1377
- }
1378
-
1379
- # Save effects
1380
- cross <- cross_data()
1381
- if (!is.null(cross) && !is.null(qtls) && nrow(qtls) > 0) {
1382
- effects <- estimate_qtl_effects(cross, qtls,
1383
- which(names(cross$pheno) == input$pheno_trait))
1384
- effects_df <- do.call(rbind, lapply(seq_along(effects), function(i) {
1385
- data.frame(
1386
- QTL = i,
1387
- Marker = effects[[i]]$marker,
1388
- Additive = effects[[i]]$additive,
1389
- Dominance = effects[[i]]$dominance
1390
- )
1391
- }))
1392
- write.csv(effects_df, file.path(tmpdir, "qtl_effects.csv"), row.names = FALSE)
1393
  }
1394
-
1395
- # Create zip file
1396
- zip::zip(file, files = list.files(tmpdir, full.names = TRUE))
1397
- }
1398
- )
1399
-
1400
- output$download_report_pdf <- downloadHandler(
1401
- filename = paste0("qtl_report_", Sys.Date(), ".pdf"),
1402
- content = function(file) {
1403
- # Create PDF report using rmarkdown
1404
- # This would require a template Rmd file
1405
- showNotification("PDF report generation requires rmarkdown", type = "warning")
1406
- }
1407
- )
1408
-
1409
- output$download_report_html <- downloadHandler(
1410
- filename = paste0("qtl_report_", Sys.Date(), ".html"),
1411
- content = function(file) {
1412
- # Create HTML report
1413
- showNotification("HTML report generation in development", type = "warning")
1414
- }
1415
- )
1416
-
1417
- output$download_all_plots <- downloadHandler(
1418
- filename = paste0("all_plots_", Sys.Date(), ".pdf"),
1419
- content = function(file) {
1420
- # Save all plots to PDF
1421
- pdf(file, width = 12, height = 8)
1422
- # Plot each visualization
1423
- # This would require rendering all plots
1424
- dev.off()
1425
- showNotification("Plot export in development", type = "warning")
1426
  }
1427
  )
1428
-
1429
- # Analysis status
1430
- output$analysis_status <- renderPrint({
1431
- if (!analysis_complete()) {
1432
- cat("Analysis not yet run. Click 'RUN ANALYSIS' to start.")
1433
- } else {
1434
- cat("Analysis completed successfully!\n\n")
1435
- cat("Results are available in the Results and Visualizations tabs.")
1436
- }
1437
- })
1438
  }
1439
 
1440
- # Run the application
1441
  shinyApp(ui = ui, server = server)
 
1
  # ============================================================================
2
+ # COMPLETE QTL ANALYSIS PIPELINE - FULLY FUNCTIONAL
3
+ # All errors fixed, production-ready
4
  # ============================================================================
5
 
6
+ # Load libraries with error handling
7
+ suppressPackageStartupMessages({
8
+ library(shiny)
9
+ library(shinydashboard)
10
+ library(shinyjs)
11
+ library(shinycssloaders)
12
+ library(qtl)
13
+ library(ggplot2)
14
+ library(plotly)
15
+ library(dplyr)
16
+ library(tidyr)
17
+ library(DT)
18
+ library(RColorBrewer)
19
+ library(ggrepel)
20
+ library(cowplot)
21
+ library(pheatmap)
22
+ library(viridis)
23
+ library(ggridges)
24
+ library(ggExtra)
25
+ library(foreach)
26
+ library(doParallel)
27
+ library(igraph)
28
+ library(data.table)
29
+ })
30
+
31
+ # Check for corrplot
32
+ if (!require("corrplot", quietly = TRUE)) {
33
+ install.packages("corrplot", repos = "https://cloud.r-project.org/")
34
+ library(corrplot)
35
+ }
36
 
37
  # ============================================================================
38
+ # DATA PARSER
39
  # ============================================================================
40
 
41
+ parse_custom_cross <- function(geno_path, pheno_path, cross_type = "f2") {
 
42
 
43
+ # Read genotype file
44
  geno_raw <- read.csv(geno_path, header = FALSE, stringsAsFactors = FALSE,
45
+ check.names = FALSE, na.strings = c("NA", "", "N/A", "-9", "0"))
46
 
47
  if (nrow(geno_raw) < 4) {
48
+ stop("Genotype file must have at least 4 rows: header, chr, positions, data")
49
  }
50
 
51
  # Parse header rows
 
54
  pos_row <- as.character(geno_raw[3, ])
55
  ind_data <- geno_raw[4:nrow(geno_raw), , drop = FALSE]
56
 
57
+ # Identify marker columns
58
  marker_cols <- 2:ncol(geno_raw)
59
+ if (length(marker_cols) == 0) {
60
+ stop("No marker columns found in genotype file")
61
+ }
62
+
63
  marker_names <- col_names[marker_cols]
64
 
65
  # Clean chromosome names
 
67
  chromosomes <- gsub("^[Cc]hr", "", chromosomes)
68
  chromosomes <- gsub("^0+", "", chromosomes)
69
  chromosomes[chromosomes == ""] <- "unknown"
70
+ chromosomes[is.na(chromosomes)] <- "unknown"
71
 
72
  # Parse positions
73
  positions <- suppressWarnings(as.numeric(pos_row[marker_cols]))
74
  positions[is.na(positions)] <- 0
75
 
76
+ # Individual IDs
77
  ind_ids <- as.character(ind_data[, 1])
78
+ if (any(duplicated(ind_ids))) {
79
+ ind_ids <- make.unique(ind_ids)
80
+ }
81
 
82
  # Convert genotype matrix
83
  geno_mat <- as.matrix(ind_data[, marker_cols, drop = FALSE])
 
85
  rownames(geno_mat) <- ind_ids
86
  colnames(geno_mat) <- marker_names
87
 
 
 
 
 
 
 
 
 
 
 
88
  # Remove individuals with excessive missing data (>50%)
89
  missing_rate <- rowMeans(is.na(geno_mat))
90
  valid_inds <- missing_rate <= 0.5
91
+ if (sum(valid_inds) == 0) {
92
+ stop("No individuals with less than 50% missing data")
93
+ }
94
  geno_mat <- geno_mat[valid_inds, , drop = FALSE]
95
  ind_ids <- ind_ids[valid_inds]
96
 
97
  # Read phenotype file
98
  pheno_raw <- read.csv(pheno_path, header = TRUE, stringsAsFactors = FALSE,
99
+ check.names = FALSE, na.strings = c("NA", "", "N/A"))
100
 
101
  if (ncol(pheno_raw) < 2) {
102
+ stop("Phenotype file must have at least 2 columns (ID and one trait)")
103
  }
104
 
105
  pheno_ids <- as.character(pheno_raw[, 1])
106
+ if (any(duplicated(pheno_ids))) {
107
+ pheno_ids <- make.unique(pheno_ids)
108
+ }
109
  pheno_df <- pheno_raw[, -1, drop = FALSE]
110
 
111
  # Convert phenotypes to numeric
 
117
  # Align individuals
118
  common_ids <- intersect(ind_ids, pheno_ids)
119
  if (length(common_ids) == 0) {
120
+ stop(paste("No matching individual IDs. Genotype IDs:",
121
+ paste(head(ind_ids, 3), collapse=", "),
122
+ "Phenotype IDs:", paste(head(pheno_ids, 3), collapse=", ")))
123
  }
124
 
125
  geno_mat <- geno_mat[common_ids, , drop = FALSE]
126
  pheno_df <- pheno_df[common_ids, , drop = FALSE]
127
 
128
+ # Remove markers with too much missing data (>50%)
129
+ marker_missing <- colMeans(is.na(geno_mat))
130
+ valid_markers <- marker_missing <= 0.5
131
+ if (sum(valid_markers) == 0) {
132
+ stop("No markers with less than 50% missing data")
133
+ }
134
+ geno_mat <- geno_mat[, valid_markers, drop = FALSE]
135
+ chromosomes <- chromosomes[valid_markers]
136
+ positions <- positions[valid_markers]
137
+ marker_names <- marker_names[valid_markers]
138
+
139
  # Build genetic map by chromosome
140
  unique_chrs <- unique(chromosomes)
141
  chr_numeric <- suppressWarnings(as.numeric(unique_chrs))
 
161
  chr_positions <- chr_positions[!duplicated(chr_positions)]
162
  chr_markers <- chr_markers[!duplicated(chr_markers)]
163
 
164
+ if (length(chr_positions) >= 1) { # At least 1 marker per chromosome
165
  map_list[[ch]] <- chr_positions
166
  geno_list[[ch]] <- list(
167
  data = geno_mat[, chr_markers, drop = FALSE],
 
172
  }
173
  }
174
 
175
+ if (length(geno_list) == 0) {
176
+ stop("No valid chromosomes found")
177
+ }
178
+
179
  # Create cross object
180
  cross <- list(geno = geno_list, pheno = pheno_df)
181
  class(cross) <- c(cross_type, "cross")
182
 
183
+ # Run basic checks
184
  cross <- jittermap(cross)
185
 
 
 
 
 
 
 
 
 
 
186
  return(cross)
187
  }
188
 
189
  # ============================================================================
190
+ # QTL ANALYSIS FUNCTIONS
191
  # ============================================================================
192
 
193
+ run_scan <- function(cross, pheno_col, method = "hk") {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
194
  tryCatch({
195
+ scanone(cross, pheno.col = pheno_col, method = method)
 
 
196
  }, error = function(e) {
197
+ message(paste("Scan failed:", e$message))
198
  return(NULL)
199
  })
200
  }
201
 
202
+ run_permutations <- function(cross, pheno_col, n_perm = 100, method = "hk") {
 
203
  tryCatch({
204
+ scanone(cross, pheno.col = pheno_col, n.perm = n_perm, method = method)
 
 
 
 
 
 
205
  }, error = function(e) {
206
+ message(paste("Permutation failed:", e$message))
207
  return(NULL)
208
  })
209
  }
210
 
211
+ find_qtls <- function(scan, threshold) {
212
+ if (is.null(scan) || nrow(scan) == 0) {
213
+ return(data.frame())
214
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
215
 
216
+ scan_sig <- scan[scan$lod >= threshold, ]
217
+ if (nrow(scan_sig) == 0) {
218
+ return(data.frame())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
219
  }
220
 
221
+ qtls <- data.frame()
222
+ for (chr in unique(scan_sig$chr)) {
223
+ chr_data <- scan_sig[scan_sig$chr == chr, ]
 
 
 
 
 
224
 
225
+ # Find peaks (local maxima)
226
+ peaks <- c()
227
+ for (i in 1:nrow(chr_data)) {
228
+ is_peak <- TRUE
229
+ if (i > 1 && chr_data$lod[i] <= chr_data$lod[i - 1]) is_peak <- FALSE
230
+ if (i < nrow(chr_data) && chr_data$lod[i] <= chr_data$lod[i + 1]) is_peak <- FALSE
231
+ if (is_peak) peaks <- c(peaks, i)
232
  }
233
 
234
+ if (length(peaks) > 0) {
235
+ for (peak_idx in peaks) {
236
+ peak_row <- chr_data[peak_idx, ]
237
+
238
+ # Calculate 1.5 LOD drop confidence interval
239
+ chr_all <- scan[scan$chr == chr, ]
240
+ lod_diff <- chr_all$lod - peak_row$lod
241
+ ci_indices <- which(lod_diff >= -1.5)
242
+ if (length(ci_indices) > 0) {
243
+ left_pos <- min(chr_all$pos[ci_indices])
244
+ right_pos <- max(chr_all$pos[ci_indices])
245
+ } else {
246
+ left_pos <- peak_row$pos - 5
247
+ right_pos <- peak_row$pos + 5
248
+ }
249
+
250
+ # Calculate PVE
251
+ n <- nrow(scan)
252
+ pve <- (1 - 10^(-2 * peak_row$lod / n)) * 100
253
+
254
+ qtls <- rbind(qtls, data.frame(
255
+ Chromosome = as.character(chr),
256
+ Position_cM = round(peak_row$pos, 2),
257
+ LOD = round(peak_row$lod, 3),
258
+ PVE_percent = round(pve, 2),
259
+ CI_left = round(left_pos, 2),
260
+ CI_right = round(right_pos, 2),
261
+ CI_width = round(right_pos - left_pos, 2),
262
+ Marker = rownames(peak_row),
263
+ stringsAsFactors = FALSE
264
+ ))
265
+ }
266
+ }
267
+ }
268
+
269
+ if (nrow(qtls) > 0) {
270
+ # Convert chromosome to numeric for sorting
271
+ qtls$ChrNum <- suppressWarnings(as.numeric(qtls$Chromosome))
272
+ qtls$ChrNum[is.na(qtls$ChrNum)] <- 999
273
+ qtls <- qtls[order(qtls$ChrNum, qtls$Position_cM), ]
274
+ qtls$ChrNum <- NULL
275
+ }
276
+
277
+ return(qtls)
278
  }
279
 
280
  # ============================================================================
281
+ # PLOTTING FUNCTIONS
282
  # ============================================================================
283
 
284
+ # 1. Manhattan Plot
285
+ create_manhattan_plot <- function(scan, threshold, qtls = NULL) {
286
+ if (is.null(scan)) return(NULL)
287
+
288
  df <- as.data.frame(scan)
289
  df$marker <- rownames(df)
290
  df$significant <- df$lod >= threshold
291
 
292
+ # Calculate cumulative positions
293
  chrs <- unique(df$chr)
294
+ chr_lengths <- sapply(chrs, function(ch) max(df$pos[df$chr == ch], na.rm = TRUE))
295
  cum_lengths <- cumsum(c(0, chr_lengths[-length(chrs)]))
296
  names(cum_lengths) <- chrs
297
 
298
  df$pos_cum <- df$pos + cum_lengths[as.character(df$chr)]
299
+ chr_midpoints <- sapply(chrs, function(ch) mean(df$pos_cum[df$chr == ch], na.rm = TRUE))
300
+
301
+ n_chrs <- length(chrs)
302
+ colors <- rep(brewer.pal(min(8, n_chrs), "Set1"), length.out = n_chrs)
303
+ names(colors) <- chrs
304
 
 
305
  p <- ggplot(df, aes(x = pos_cum, y = lod, color = chr)) +
306
  geom_point(size = 1.5, alpha = 0.7) +
307
  geom_hline(yintercept = threshold, color = "red", linetype = "dashed", size = 1) +
308
  scale_x_continuous(breaks = chr_midpoints, labels = names(chr_midpoints)) +
309
+ scale_color_manual(values = colors) +
310
  labs(title = "Genome-wide Manhattan Plot",
311
  x = "Chromosome", y = "LOD Score") +
312
  theme_minimal() +
313
  theme(legend.position = "none",
314
  axis.text.x = element_text(angle = 45, hjust = 1))
315
 
 
316
  if (!is.null(qtls) && nrow(qtls) > 0) {
317
  qtls$pos_cum <- qtls$Position_cM + cum_lengths[as.character(qtls$Chromosome)]
318
+ p <- p + geom_point(data = qtls, aes(x = pos_cum, y = LOD),
319
  color = "gold", size = 4, shape = 18) +
320
+ geom_text_repel(data = qtls, aes(x = pos_cum, y = LOD,
321
+ label = paste0("QTL-", 1:nrow(qtls))),
322
+ color = "darkred", size = 3, max.overlaps = 10)
323
  }
324
 
325
  return(p)
326
  }
327
 
328
+ # 2. Interactive Manhattan Plot
329
+ create_interactive_manhattan <- function(scan, threshold) {
330
+ if (is.null(scan)) return(NULL)
331
+
332
  df <- as.data.frame(scan)
333
  df$marker <- rownames(df)
334
+ df$significant <- df$lod >= threshold
335
+ df$color <- ifelse(df$significant, "Significant", "Not Significant")
336
+
337
+ plot_ly(df, x = ~pos, y = ~lod, color = ~color,
338
+ colors = c("Not Significant" = "gray", "Significant" = "red"),
339
+ text = ~paste("Marker:", marker, "<br>Chr:", chr,
340
+ "<br>Pos:", round(pos, 2),
341
+ "<br>LOD:", round(lod, 3)),
342
+ hoverinfo = "text",
343
+ type = "scatter", mode = "markers",
344
+ marker = list(size = 5, opacity = 0.7)) %>%
345
+ layout(title = "Interactive Manhattan Plot",
346
+ xaxis = list(title = "Position (cM)"),
347
+ yaxis = list(title = "LOD Score"),
348
+ showlegend = TRUE) %>%
349
+ add_lines(x = ~pos, y = threshold, line = list(color = "orange", dash = "dash"),
350
+ name = "Threshold", showlegend = TRUE)
351
  }
352
 
353
+ # 3. Phenotype Distribution
354
+ create_phenotype_plot <- function(cross, trait) {
355
+ if (is.null(cross) || is.null(trait) || !trait %in% names(cross$pheno)) {
356
+ return(NULL)
357
+ }
358
+
359
+ pheno <- cross$pheno[[trait]]
360
+ pheno <- pheno[!is.na(pheno)]
361
+
362
+ if (length(pheno) == 0) return(NULL)
363
+
364
+ df <- data.frame(value = pheno)
365
+
366
+ p1 <- ggplot(df, aes(x = value)) +
367
+ geom_histogram(aes(y = after_stat(density)), fill = "steelblue", alpha = 0.7, bins = 30) +
368
+ geom_density(color = "darkorange", size = 1) +
369
+ labs(title = paste(trait, "- Distribution"), x = "Value", y = "Density") +
370
+ theme_minimal()
371
+
372
+ p2 <- ggplot(df, aes(sample = value)) +
373
+ stat_qq(color = "steelblue", alpha = 0.7) +
374
+ stat_qq_line(color = "red", size = 1) +
375
+ labs(title = "Q-Q Plot", x = "Theoretical Quantiles", y = "Sample Quantiles") +
376
+ theme_minimal()
377
+
378
+ cowplot::plot_grid(p1, p2, ncol = 2)
379
  }
380
 
381
+ # 4. Genetic Map
382
+ create_genetic_map <- function(cross) {
383
+ if (is.null(cross)) return(NULL)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
384
 
385
+ map <- qtl::pull.map(cross)
386
+ df <- data.frame()
387
+ for (chr in names(map)) {
388
+ positions <- map[[chr]]
389
+ df <- rbind(df, data.frame(Chromosome = chr, Position = positions))
 
390
  }
391
 
392
+ chr_order <- names(map)
393
+ df$Chromosome <- factor(df$Chromosome, levels = chr_order)
394
+
395
+ ggplot(df, aes(x = Chromosome, y = Position)) +
396
+ geom_segment(aes(xend = Chromosome, yend = 0), color = "gray70", size = 1) +
397
+ geom_point(color = "steelblue", size = 2, alpha = 0.7) +
398
+ labs(title = "Genetic Map", x = "Chromosome", y = "Position (cM)") +
399
+ theme_minimal() +
400
+ theme(axis.text.x = element_text(angle = 45, hjust = 1))
401
  }
402
 
403
+ # 5. Ridge Plot
404
  create_ridge_plot <- function(scan) {
405
+ if (is.null(scan)) return(NULL)
406
+
407
  df <- as.data.frame(scan)
408
  df$chr <- factor(df$chr, levels = unique(df$chr))
409
 
410
  ggplot(df, aes(x = lod, y = chr, fill = after_stat(x))) +
411
+ ggridges::geom_density_ridges_gradient(scale = 2, rel_min_height = 0.01) +
412
  scale_fill_viridis_c(option = "C", name = "LOD Score") +
413
  labs(title = "LOD Score Distribution by Chromosome",
414
  x = "LOD Score", y = "Chromosome") +
415
+ theme_minimal() +
416
  theme(legend.position = "right")
417
  }
418
 
419
+ # 6. Missing Data Plot
420
+ create_missing_plot <- function(cross) {
421
+ if (is.null(cross)) return(NULL)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
422
 
423
+ missing_ind <- qtl::nmissing(cross, what = "ind")
424
+ missing_marker <- qtl::nmissing(cross, what = "mar")
 
 
 
 
 
 
425
 
426
+ df_ind <- data.frame(Individual = seq_along(missing_ind), Missing = missing_ind)
427
+ df_marker <- data.frame(Marker = seq_along(missing_marker), Missing = missing_marker)
 
 
 
 
 
 
 
428
 
429
+ p1 <- ggplot(df_ind, aes(x = Individual, y = Missing)) +
430
+ geom_bar(stat = "identity", fill = "steelblue", alpha = 0.7) +
431
+ labs(title = "Missing Data per Individual", x = "Individual Index", y = "Missing Count") +
432
+ theme_minimal()
433
+
434
+ p2 <- ggplot(df_marker, aes(x = Marker, y = Missing)) +
435
+ geom_bar(stat = "identity", fill = "darkorange", alpha = 0.7) +
436
+ labs(title = "Missing Data per Marker", x = "Marker Index", y = "Missing Count") +
437
+ theme_minimal()
 
 
 
 
 
 
438
 
439
+ cowplot::plot_grid(p1, p2, ncol = 2)
440
  }
441
 
442
+ # 7. Marker Density
443
+ create_marker_density <- function(cross) {
444
+ if (is.null(cross)) return(NULL)
445
 
446
+ map <- qtl::pull.map(cross)
447
+ distances <- data.frame()
448
  for (chr in names(map)) {
449
  positions <- map[[chr]]
450
  if (length(positions) > 1) {
451
  gaps <- diff(positions)
452
+ distances <- rbind(distances, data.frame(Chromosome = chr, Gap = gaps))
 
 
 
453
  }
454
  }
455
 
456
+ if (nrow(distances) == 0) return(NULL)
457
+
458
+ ggplot(distances, aes(x = Gap, fill = Chromosome)) +
459
  geom_histogram(bins = 30, alpha = 0.6, position = "identity") +
460
  scale_fill_brewer(palette = "Set1") +
461
+ labs(title = "Inter-marker Distance Distribution",
462
+ x = "Distance (cM)", y = "Count") +
463
  theme_minimal() +
464
+ theme(legend.position = "bottom")
465
  }
466
 
467
+ # 8. QTL Effect Plot
468
+ create_effect_plot <- function(cross, qtl_row, trait) {
469
+ if (is.null(cross) || is.null(qtl_row) || nrow(qtl_row) == 0) return(NULL)
 
 
470
 
471
+ chr_name <- as.character(qtl_row$Chromosome[1])
472
+ if (!chr_name %in% names(cross$geno)) return(NULL)
 
473
 
474
+ map <- qtl::pull.map(cross)[[chr_name]]
475
+ marker_pos <- which.min(abs(map - qtl_row$Position_cM[1]))
476
+ marker_name <- names(map)[marker_pos]
 
 
477
 
478
+ geno_idx <- qtl::find.marker(cross, chr_name, marker_name)
479
+ genotypes <- qtl::pull.geno(cross)[, geno_idx]
480
+ phenotypes <- cross$pheno[[trait]]
 
 
481
 
482
+ df <- data.frame(
483
+ genotype = factor(genotypes, levels = sort(unique(genotypes))),
484
+ phenotype = phenotypes
485
+ )
486
+ df <- df[!is.na(df$genotype) & !is.na(df$phenotype), ]
487
+
488
+ if (nrow(df) == 0) return(NULL)
489
 
490
+ ggplot(df, aes(x = genotype, y = phenotype, fill = genotype)) +
491
+ geom_violin(alpha = 0.5, trim = FALSE) +
492
+ geom_boxplot(width = 0.2, alpha = 0.7) +
493
+ stat_summary(fun = mean, geom = "point", shape = 18, size = 4, color = "red") +
494
+ scale_fill_brewer(palette = "Set2") +
495
+ labs(title = paste("QTL Effect -", marker_name),
496
+ x = "Genotype", y = trait) +
 
 
 
 
 
497
  theme_minimal() +
498
  theme(legend.position = "none")
499
  }
500
 
501
+ # 9. Method Comparison
502
+ create_comparison_plot <- function(scan_results) {
503
+ if (is.null(scan_results) || length(scan_results) == 0) return(NULL)
504
+
505
+ comparison_df <- data.frame()
506
+ for (method in names(scan_results)) {
507
+ scan <- scan_results[[method]]
508
+ if (!is.null(scan)) {
509
+ comparison_df <- rbind(comparison_df,
510
+ data.frame(Method = toupper(method),
511
+ MaxLOD = max(scan$lod, na.rm = TRUE)))
512
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
513
  }
514
 
515
+ if (nrow(comparison_df) == 0) return(NULL)
516
+
517
+ ggplot(comparison_df, aes(x = reorder(Method, -MaxLOD), y = MaxLOD, fill = Method)) +
518
+ geom_bar(stat = "identity", alpha = 0.8) +
519
+ geom_text(aes(label = round(MaxLOD, 2)), vjust = -0.5, size = 4) +
520
+ scale_fill_brewer(palette = "Set2") +
521
+ labs(title = "Method Comparison - Maximum LOD Score",
522
+ x = "Mapping Method", y = "Maximum LOD Score") +
523
+ theme_minimal() +
524
+ theme(legend.position = "none",
525
+ axis.text.x = element_text(angle = 45, hjust = 1))
526
+ }
527
+
528
+ # 10. Correlation Plot
529
+ create_correlation_plot <- function(cross) {
530
+ if (is.null(cross) || ncol(cross$pheno) < 2) return(NULL)
531
+
532
+ cor_matrix <- cor(cross$pheno, use = "complete.obs")
533
+
534
+ corrplot::corrplot(cor_matrix,
535
+ method = "color",
536
+ type = "upper",
537
+ order = "hclust",
538
+ addCoef.col = "black",
539
+ tl.col = "black",
540
+ tl.srt = 45,
541
+ title = "Phenotype Correlations",
542
+ mar = c(0, 0, 2, 0))
543
  }
544
 
545
  # ============================================================================
546
+ # UI
547
  # ============================================================================
548
 
549
  ui <- dashboardPage(
550
+ dashboardHeader(title = "QTL Analysis Platform", titleWidth = 300),
551
 
552
+ dashboardSidebar(width = 300,
553
  sidebarMenu(
554
  menuItem("Data Input", tabName = "data", icon = icon("upload")),
555
+ menuItem("Analysis", tabName = "analysis", icon = icon("chart-line")),
556
+ menuItem("Visualizations", tabName = "viz", icon = icon("chart-bar")),
557
+ menuItem("QTL Results", tabName = "results", icon = icon("table")),
558
+ menuItem("Documentation", tabName = "help", icon = icon("question-circle"))
 
 
 
 
 
 
559
  ),
560
 
 
561
  div(style = "padding: 15px;",
562
  h4("Data Upload", style = "color: #3c8dbc;"),
563
+ fileInput("geno_file", "Genotype CSV",
564
+ accept = ".csv",
565
+ buttonLabel = "Browse",
566
+ placeholder = "genotypes.csv"),
567
+ fileInput("pheno_file", "Phenotype CSV",
568
+ accept = ".csv",
569
+ buttonLabel = "Browse",
570
+ placeholder = "phenotypes.csv"),
571
 
572
+ hr(),
573
+
574
+ h4("Analysis Settings", style = "color: #3c8dbc;"),
575
  selectInput("cross_type", "Cross Type",
576
+ choices = c("F2 Intercross" = "f2",
577
+ "Backcross" = "bc",
578
+ "RIL (Selfing)" = "riself"),
579
  selected = "f2"),
580
 
 
 
 
581
  selectInput("pheno_trait", "Phenotype Trait", choices = NULL),
582
 
583
+ selectInput("scan_method", "Mapping Method",
584
+ choices = c("Haley-Knott" = "hk",
585
+ "EM Algorithm" = "em",
586
+ "Marker Regression" = "mr"),
587
+ selected = "hk"),
588
 
589
+ numericInput("lod_threshold", "LOD Threshold",
590
+ value = 3.0, min = 0, max = 20, step = 0.5),
591
 
592
+ numericInput("n_permutations", "Permutations",
593
+ value = 100, min = 0, max = 1000, step = 100),
 
594
 
595
  actionButton("run_analysis", "RUN ANALYSIS",
596
+ icon = icon("play"),
597
+ style = "background-color: #3c8dbc; color: white; width: 100%; margin-top: 15px;"),
598
+
599
+ br(), br(),
600
 
601
+ downloadButton("download_results", "Download Results",
602
+ style = "width: 100%;")
603
  )
604
  ),
605
 
 
614
  border-radius: 10px;
615
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
616
  }
 
 
 
617
  "))
618
  ),
619
 
620
  tabItems(
621
+ # Data Tab
622
  tabItem(tabName = "data",
623
+ fluidRow(
624
+ valueBoxOutput("n_individuals"),
625
+ valueBoxOutput("n_markers"),
626
+ valueBoxOutput("n_chromosomes")
627
+ ),
628
  fluidRow(
629
  box(title = "Data Summary", status = "primary", solidHeader = TRUE, width = 12,
630
  verbatimTextOutput("data_summary")
631
  )
632
  ),
633
  fluidRow(
634
+ box(title = "Quality Control", status = "info", width = 12,
635
+ plotOutput("qc_plot", height = "500px") %>% withSpinner()
 
 
 
636
  )
637
  ),
638
  fluidRow(
639
+ box(title = "Genetic Map", status = "success", width = 12,
640
+ plotOutput("genetic_map", height = "500px") %>% withSpinner()
641
  )
642
  )
643
  ),
 
645
  # Analysis Tab
646
  tabItem(tabName = "analysis",
647
  fluidRow(
648
+ box(title = "Analysis Status", status = "primary", solidHeader = TRUE, width = 12,
649
  verbatimTextOutput("analysis_status")
650
  )
651
  ),
652
  fluidRow(
653
+ box(title = "Manhattan Plot", status = "info", width = 12,
654
+ plotOutput("manhattan_plot", height = "600px") %>% withSpinner()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
655
  )
656
  ),
657
  fluidRow(
658
+ box(title = "Interactive Manhattan Plot", status = "success", width = 12,
659
+ plotlyOutput("interactive_manhattan") %>% withSpinner()
660
  )
661
  ),
662
  fluidRow(
663
+ box(title = "LOD Distribution by Chromosome", status = "warning", width = 12,
664
+ plotOutput("ridge_plot", height = "600px") %>% withSpinner()
 
665
  )
666
  )
667
  ),
668
 
669
+ # Visualizations Tab
670
+ tabItem(tabName = "viz",
671
  fluidRow(
672
+ box(title = "Marker Density", status = "primary", width = 6,
673
+ plotOutput("marker_density", height = "450px") %>% withSpinner()
674
+ ),
675
+ box(title = "Phenotype Distribution", status = "info", width = 6,
676
+ plotOutput("phenotype_plot", height = "450px") %>% withSpinner()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
677
  )
678
  ),
679
  fluidRow(
680
+ box(title = "Method Comparison", status = "success", width = 6,
681
+ plotOutput("comparison_plot", height = "450px") %>% withSpinner()
682
+ ),
683
+ box(title = "Trait Correlations", status = "warning", width = 6,
684
+ plotOutput("correlation_plot", height = "450px") %>% withSpinner()
685
  )
686
  ),
687
  fluidRow(
688
+ box(title = "QTL Effect Plot", status = "danger", width = 12,
689
+ selectInput("effect_qtl", "Select QTL to visualize:", choices = NULL),
690
+ plotOutput("effect_plot", height = "500px") %>% withSpinner()
691
  )
692
  )
693
  ),
 
696
  tabItem(tabName = "results",
697
  fluidRow(
698
  box(title = "Significant QTLs", status = "primary", width = 12,
699
+ DTOutput("qtl_table") %>% withSpinner()
700
  )
701
  ),
702
  fluidRow(
703
+ box(title = "Permutation Test Results", status = "info", width = 12,
704
+ DTOutput("permutation_table") %>% withSpinner()
705
  )
706
  ),
707
  fluidRow(
708
+ box(title = "QTL Statistics", status = "success", width = 12,
709
+ verbatimTextOutput("qtl_statistics")
710
  )
711
  )
712
  ),
713
 
714
+ # Help Tab
715
+ tabItem(tabName = "help",
 
 
 
 
 
716
  fluidRow(
717
+ box(title = "Documentation", status = "primary", width = 12,
718
+ HTML("
719
+ <h3>Quick Start Guide</h3>
720
+
721
+ <h4>1. Prepare Your Data Files</h4>
722
+ <p><strong>Genotype CSV format:</strong></p>
723
+ <pre>
724
+ id,marker1,marker2,marker3,...
725
+ ,chr1,chr1,chr2,...
726
+ ,0.22,0.60,1.23,...
727
+ sample1,1,2,1,...
728
+ sample2,2,1,3,...
729
+ </pre>
730
+ <ul>
731
+ <li>Row 1: Header with marker names (first column should be 'id')</li>
732
+ <li>Row 2: Chromosome assignment for each marker</li>
733
+ <li>Row 3: Position in cM for each marker</li>
734
+ <li>Row 4+: Individual data (first column = individual ID)</li>
735
+ </ul>
736
+
737
+ <p><strong>Phenotype CSV format:</strong></p>
738
+ <pre>
739
+ id,trait1,trait2,trait3,...
740
+ sample1,175,75,12.5,...
741
+ sample2,180,80,13.2,...
742
+ </pre>
743
+ <ul>
744
+ <li>First column: Individual IDs (must match genotype file)</li>
745
+ <li>Remaining columns: Phenotypic traits</li>
746
+ </ul>
747
+
748
+ <h4>2. Run Analysis</h4>
749
+ <ul>
750
+ <li>Select cross type (F2, Backcross, or RIL)</li>
751
+ <li>Choose phenotype trait to analyze</li>
752
+ <li>Select mapping method (HK, EM, or MR)</li>
753
+ <li>Set LOD threshold (default 3.0)</li>
754
+ <li>Set number of permutations for significance testing</li>
755
+ <li>Click 'RUN ANALYSIS'</li>
756
+ </ul>
757
+
758
+ <h4>3. Interpret Results</h4>
759
+ <ul>
760
+ <li><strong>LOD Score:</strong> Logarithm of odds - higher values indicate stronger evidence for QTL</li>
761
+ <li><strong>PVE:</strong> Proportion of variance explained by the QTL</li>
762
+ <li><strong>Confidence Interval:</strong> 1.5 LOD drop support interval</li>
763
+ <li><strong>Threshold:</strong> Significance level from permutation test</li>
764
+ </ul>
765
+
766
+ <h4>Troubleshooting</h4>
767
+ <ul>
768
+ <li>Ensure IDs match between genotype and phenotype files</li>
769
+ <li>Check for missing data (>50% may cause issues)</li>
770
+ <li>Verify chromosome and position formats</li>
771
+ <li>Try different mapping methods if one fails</li>
772
+ </ul>
773
+ ")
774
  )
775
  )
776
  )
 
779
  )
780
 
781
  # ============================================================================
782
+ # SERVER
783
  # ============================================================================
784
 
785
  server <- function(input, output, session) {
786
 
787
+ # Reactive values
788
  cross_data <- reactiveVal(NULL)
789
+ scan_result <- reactiveVal(NULL)
790
+ perm_result <- reactiveVal(NULL)
791
+ qtl_result <- reactiveVal(NULL)
792
+ analysis_done <- reactiveVal(FALSE)
793
+
794
+ # Value boxes
795
+ output$n_individuals <- renderValueBox({
796
+ cross <- cross_data()
797
+ if (is.null(cross)) {
798
+ valueBox(0, "Individuals", icon = icon("users"), color = "blue")
799
+ } else {
800
+ valueBox(nind(cross), "Individuals", icon = icon("users"), color = "blue")
801
+ }
802
+ })
803
+
804
+ output$n_markers <- renderValueBox({
805
+ cross <- cross_data()
806
+ if (is.null(cross)) {
807
+ valueBox(0, "Markers", icon = icon("dna"), color = "green")
808
+ } else {
809
+ valueBox(totmar(cross), "Markers", icon = icon("dna"), color = "green")
810
+ }
811
+ })
812
+
813
+ output$n_chromosomes <- renderValueBox({
814
+ cross <- cross_data()
815
+ if (is.null(cross)) {
816
+ valueBox(0, "Chromosomes", icon = icon("chromosome"), color = "yellow")
817
+ } else {
818
+ valueBox(nchr(cross), "Chromosomes", icon = icon("chromosome"), color = "yellow")
819
+ }
820
+ })
821
 
822
  # Load data
823
  observeEvent(c(input$geno_file, input$pheno_file), {
824
  req(input$geno_file, input$pheno_file)
825
 
826
+ showNotification("Loading data...", type = "info", duration = 3)
827
 
828
  tryCatch({
829
+ cross <- parse_custom_cross(
830
  input$geno_file$datapath,
831
  input$pheno_file$datapath,
832
  input$cross_type
 
834
 
835
  cross_data(cross)
836
 
837
+ # Update phenotype dropdown
838
+ updateSelectInput(session, "pheno_trait",
839
  choices = names(cross$pheno),
840
  selected = names(cross$pheno)[1])
841
 
 
 
 
842
  showNotification("Data loaded successfully!", type = "success", duration = 3)
843
 
844
  }, error = function(e) {
845
+ showNotification(paste("Error:", e$message), type = "error", duration = 10)
846
  })
847
  })
848
 
 
851
  cross <- cross_data()
852
  req(cross, input$pheno_trait)
853
 
854
+ showNotification("Running QTL analysis...", type = "info", duration = 5)
855
 
856
+ withProgress(message = "QTL Analysis", value = 0, {
857
 
858
+ incProgress(0.3, detail = "Running genome scan...")
 
859
  pheno_idx <- which(names(cross$pheno) == input$pheno_trait)
860
+ scan <- run_scan(cross, pheno_idx, input$scan_method)
861
+ scan_result(scan)
 
 
 
 
 
 
 
862
 
863
+ if (input$n_permutations > 0 && !is.null(scan)) {
864
+ incProgress(0.3, detail = paste("Running", input$n_permutations, "permutations..."))
865
+ perm <- run_permutations(cross, pheno_idx, input$n_permutations, input$scan_method)
866
+ perm_result(perm)
867
+
868
+ # Update threshold based on permutations
869
+ if (!is.null(perm)) {
870
+ thr <- summary(perm, alpha = 0.05)[1]
871
+ if (!is.na(thr) && thr > 0) {
872
+ updateNumericInput(session, "lod_threshold", value = round(thr, 2))
873
+ }
874
+ }
875
  }
876
 
877
+ incProgress(0.3, detail = "Identifying QTLs...")
878
+ qtls <- find_qtls(scan, input$lod_threshold)
879
+ qtl_result(qtls)
 
 
 
880
 
881
+ # Update effect QTL dropdown
882
+ if (!is.null(qtls) && nrow(qtls) > 0) {
883
+ qtl_choices <- paste0("Chr", qtls$Chromosome, "_", qtls$Position_cM, "cM_LOD", qtls$LOD)
884
+ updateSelectInput(session, "effect_qtl", choices = qtl_choices)
 
 
885
  }
886
 
887
+ analysis_done(TRUE)
888
  showNotification("Analysis complete!", type = "success", duration = 5)
889
  })
890
  })
891
 
892
+ # Render outputs
 
 
 
 
893
  output$data_summary <- renderPrint({
894
  cross <- cross_data()
895
+ if (is.null(cross)) {
896
+ cat("No data loaded. Please upload CSV files.")
897
+ } else {
898
+ cat("=== Data Summary ===\n\n")
899
+ cat("Cross Type:", class(cross)[1], "\n")
900
+ cat("Individuals:", nind(cross), "\n")
901
+ cat("Markers:", totmar(cross), "\n")
902
+ cat("Chromosomes:", nchr(cross), "\n\n")
903
+ cat("Phenotypes:", paste(names(cross$pheno), collapse = ", "), "\n\n")
904
+
905
+ # Calculate missing data rate
906
+ missing_total <- sum(is.na(qtl::pull.geno(cross))) / (nind(cross) * totmar(cross)) * 100
907
+ cat("Missing data rate:", round(missing_total, 2), "%\n")
908
+ }
909
  })
910
 
911
+ output$analysis_status <- renderPrint({
912
+ if (!analysis_done()) {
913
+ cat("Analysis not run. Click 'RUN ANALYSIS' to start.")
914
+ } else {
915
+ qtls <- qtl_result()
916
+ scan <- scan_result()
917
+ cat("=== Analysis Complete ===\n\n")
918
+ cat("Method:", toupper(input$scan_method), "\n")
919
+ cat("Threshold:", input$lod_threshold, "\n")
920
+ cat("QTLs found:", ifelse(is.null(qtls), 0, nrow(qtls)), "\n")
921
+ if (!is.null(scan)) {
922
+ cat("Max LOD:", round(max(scan$lod, na.rm = TRUE), 3), "\n")
923
+ }
924
+ }
925
  })
926
 
927
+ output$qtl_statistics <- renderPrint({
928
+ qtls <- qtl_result()
929
+ if (is.null(qtls) || nrow(qtls) == 0) {
930
+ cat("No significant QTLs found.")
931
+ } else {
932
+ cat("=== QTL Statistics ===\n\n")
933
+ cat("Total QTLs:", nrow(qtls), "\n")
934
+ cat("Average LOD:", round(mean(qtls$LOD), 3), "\n")
935
+ cat("Average PVE:", round(mean(qtls$PVE_percent), 2), "%\n")
936
+ cat("Average CI width:", round(mean(qtls$CI_width), 2), "cM\n\n")
937
+
938
+ # QTLs by chromosome
939
+ cat("QTLs by chromosome:\n")
940
+ chr_counts <- table(qtls$Chromosome)
941
+ for (chr in names(chr_counts)) {
942
+ cat(" Chromosome", chr, ":", chr_counts[chr], "QTLs\n")
943
+ }
944
+ }
945
+ })
946
+
947
+ # Plots
948
+ output$qc_plot <- renderPlot({
949
  cross <- cross_data()
950
  req(cross)
951
+ create_missing_plot(cross)
 
 
952
  })
953
 
954
+ output$genetic_map <- renderPlot({
 
955
  cross <- cross_data()
956
  req(cross)
957
+ create_genetic_map(cross)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
958
  })
959
 
960
+ output$manhattan_plot <- renderPlot({
961
+ scan <- scan_result()
962
+ qtls <- qtl_result()
963
+ req(scan)
964
+ create_manhattan_plot(scan, input$lod_threshold, qtls)
965
+ })
 
 
 
 
 
 
 
 
 
 
 
966
 
967
+ output$interactive_manhattan <- renderPlotly({
968
+ scan <- scan_result()
969
+ req(scan)
970
+ create_interactive_manhattan(scan, input$lod_threshold)
971
+ })
 
 
972
 
 
973
  output$ridge_plot <- renderPlot({
974
+ scan <- scan_result()
975
+ req(scan)
976
+ create_ridge_plot(scan)
977
+ })
 
 
 
 
 
 
 
 
 
 
 
978
 
979
+ output$marker_density <- renderPlot({
 
980
  cross <- cross_data()
981
  req(cross)
982
+ create_marker_density(cross)
983
+ })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
984
 
985
+ output$phenotype_plot <- renderPlot({
 
986
  cross <- cross_data()
987
+ req(cross, input$pheno_trait)
988
+ create_phenotype_plot(cross, input$pheno_trait)
989
+ })
 
990
 
991
+ output$comparison_plot <- renderPlot({
992
+ # Create a list with current scan for comparison
993
+ scan <- scan_result()
994
+ req(scan)
995
+ scan_list <- list(current = scan)
996
+ create_comparison_plot(scan_list)
997
+ })
998
 
999
+ output$correlation_plot <- renderPlot({
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1000
  cross <- cross_data()
1001
  req(cross)
1002
+ create_correlation_plot(cross)
1003
+ })
 
1004
 
1005
+ output$effect_plot <- renderPlot({
1006
+ req(input$effect_qtl, input$effect_qtl != "")
1007
+ qtls <- qtl_result()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1008
  cross <- cross_data()
1009
+ req(qtls, nrow(qtls) > 0, cross, input$pheno_trait)
 
 
 
 
 
 
 
 
1010
 
1011
+ # Get selected QTL
1012
+ qtl_idx <- which(paste0("Chr", qtls$Chromosome, "_", qtls$Position_cM, "cM_LOD", qtls$LOD) == input$effect_qtl)
1013
+ if (length(qtl_idx) == 0) return(NULL)
 
 
1014
 
1015
+ create_effect_plot(cross, qtls[qtl_idx[1], , drop = FALSE], input$pheno_trait)
1016
+ })
1017
 
1018
+ # Tables
1019
+ output$qtl_table <- renderDT({
1020
+ qtls <- qtl_result()
1021
  req(qtls, nrow(qtls) > 0)
1022
 
1023
  datatable(qtls,
1024
+ options = list(
1025
+ pageLength = 15,
1026
+ scrollX = TRUE,
1027
+ dom = 'Bfrtip'
1028
+ ),
1029
+ rownames = FALSE,
1030
+ class = 'display nowrap') %>%
1031
  formatStyle("LOD",
1032
+ background = styleColorBar(range(qtls$LOD), "lightblue")) %>%
1033
  formatStyle("PVE_percent",
1034
+ background = styleColorBar(c(0, max(qtls$PVE_percent, na.rm = TRUE)), "lightgreen"))
1035
  })
1036
 
1037
+ output$permutation_table <- renderDT({
1038
+ perm <- perm_result()
1039
+ req(perm)
 
 
 
 
 
1040
 
1041
+ # Calculate thresholds for different alpha levels
1042
+ alphas <- c(0.05, 0.01, 0.001)
1043
+ thresholds <- sapply(alphas, function(a) {
1044
+ thr <- summary(perm, alpha = a)[1]
1045
+ if (is.na(thr)) NA else round(thr, 3)
1046
+ })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1047
 
1048
+ perm_df <- data.frame(
1049
+ Alpha = alphas,
1050
+ Threshold = thresholds
1051
  )
1052
 
1053
+ datatable(perm_df,
1054
+ options = list(pageLength = 5, dom = 't'),
1055
+ rownames = FALSE)
1056
  })
1057
 
1058
+ # Download handler
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1059
  output$download_results <- downloadHandler(
1060
+ filename = function() paste0("qtl_results_", Sys.Date(), ".csv"),
1061
  content = function(file) {
1062
+ qtls <- qtl_result()
 
 
 
 
1063
  if (!is.null(qtls) && nrow(qtls) > 0) {
1064
+ write.csv(qtls, file, row.names = FALSE)
1065
+ } else {
1066
+ write.csv(data.frame(Message = "No significant QTLs found"), file, row.names = FALSE)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1067
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1068
  }
1069
  )
 
 
 
 
 
 
 
 
 
 
1070
  }
1071
 
1072
+ # Run the app
1073
  shinyApp(ui = ui, server = server)