diff --git "a/app.R" "b/app.R" --- "a/app.R" +++ "b/app.R" @@ -1,1386 +1,1441 @@ +# ============================================================================ +# ADVANCED QTL ANALYSIS PIPELINE +# Complete solution with 10+ plots, multiple algorithms, and extensive features +# ============================================================================ + library(shiny) +library(shinydashboard) +library(shinyjs) +library(shinycssloaders) library(qtl) +library(qtlcharts) library(ggplot2) +library(plotly) library(dplyr) library(tidyr) library(DT) -library(shinycssloaders) -library(shinyjs) -library(plotly) library(RColorBrewer) -library(grid) -library(gridExtra) -library(scales) - -# ─── CUSTOM DATA PARSER ─────────────────────────────────────────────────────── -# Handles the user's specific CSV layout: -# Genotype file: -# Row 1 : header → id | marker1 | marker2 | ... -# Row 2 : chr → 1 | chr01 | chr01 | ... (numeric chromosome ID or name) -# Row 3 : pos(cM) → 0 | 0.22 | 0.60 | ... -# Rows 4+: data → sampleID | 1|2|3... genotype calls -# Phenotype file: -# Row 1 : header → id | trait1 | trait2 | ... -# Rows 2+: data → sampleID | numeric values - -parse_custom_cross <- function(geno_path, pheno_path, cross_type = "f2") { - - # ── 1. Read raw genotype table ────────────────────────────────────────────── +library(corrplot) +library(heatmaply) +library(UpSetR) +library(ggrepel) +library(ggcorrplot) +library(cowplot) +library(pheatmap) +library(viridis) +library(ggridges) +library(ggExtra) +library(circlize) +library(ComplexHeatmap) +library(foreach) +library(doParallel) + +# ============================================================================ +# CUSTOM DATA PARSER WITH ADVANCED VALIDATION +# ============================================================================ + +parse_advanced_cross <- function(geno_path, pheno_path, cross_type = "f2", + geno_format = "standard", na_strings = c("NA", "", "N/A", "-9", "0")) { + + # Read and validate genotype file geno_raw <- read.csv(geno_path, header = FALSE, stringsAsFactors = FALSE, - check.names = FALSE, na.strings = c("NA","","N/A")) - - # Row 1 = column names + check.names = FALSE, na.strings = na_strings) + + if (nrow(geno_raw) < 4) { + stop("Genotype file must have at least 4 rows: header, chromosome, position, and data") + } + + # Parse header rows col_names <- as.character(geno_raw[1, ]) - # Row 2 = chromosomes - chr_row <- as.character(geno_raw[2, ]) - # Row 3 = positions (cM) - pos_row <- as.character(geno_raw[3, ]) - # Rows 4+ = individual data - ind_data <- geno_raw[4:nrow(geno_raw), , drop = FALSE] - - # Identify which columns are markers (everything except col 1 = id) - n_cols <- ncol(geno_raw) - marker_cols <- 2:n_cols - - # Marker metadata + chr_row <- as.character(geno_raw[2, ]) + pos_row <- as.character(geno_raw[3, ]) + ind_data <- geno_raw[4:nrow(geno_raw), , drop = FALSE] + + # Identify marker columns (skip first column which is ID) + marker_cols <- 2:ncol(geno_raw) marker_names <- col_names[marker_cols] - chromosomes <- chr_row[marker_cols] - positions <- suppressWarnings(as.numeric(pos_row[marker_cols])) - - # Clean chromosome labels: remove "chr"/"Chr" prefix → keep number/name - chromosomes <- gsub("^[Cc]hr0*", "", chromosomes) - # If the chromosome value is purely numeric, ensure no leading zeros - chr_numeric <- suppressWarnings(as.integer(chromosomes)) - chromosomes <- ifelse(!is.na(chr_numeric), as.character(chr_numeric), chromosomes) - - # Individual IDs + + # Clean chromosome names + chromosomes <- chr_row[marker_cols] + chromosomes <- gsub("^[Cc]hr", "", chromosomes) + chromosomes <- gsub("^0+", "", chromosomes) + chromosomes[chromosomes == ""] <- "unknown" + + # Parse positions + positions <- suppressWarnings(as.numeric(pos_row[marker_cols])) + positions[is.na(positions)] <- 0 + + # Individual IDs and data ind_ids <- as.character(ind_data[, 1]) - - # Genotype matrix (individuals × markers) + ind_ids <- make.unique(ind_ids) + + # Convert genotype matrix geno_mat <- as.matrix(ind_data[, marker_cols, drop = FALSE]) - class(geno_mat) <- "numeric" - geno_mat <- apply(geno_mat, 2, function(x) suppressWarnings(as.numeric(x))) + mode(geno_mat) <- "numeric" rownames(geno_mat) <- ind_ids colnames(geno_mat) <- marker_names - - # ── 2. Read phenotype table ───────────────────────────────────────────────── - pheno_raw <- read.csv(pheno_path, header = TRUE, stringsAsFactors = FALSE, - check.names = FALSE, na.strings = c("NA","","N/A")) - - pheno_ids <- as.character(pheno_raw[, 1]) - pheno_df <- pheno_raw[, -1, drop = FALSE] - # Convert all phenotype columns to numeric - pheno_df <- as.data.frame(lapply(pheno_df, function(x) suppressWarnings(as.numeric(x)))) + + # Recode genotypes based on cross type + if (cross_type == "f2") { + # 1=AA, 2=AB, 3=BB + geno_mat[geno_mat == 0] <- NA + } else if (cross_type == "bc") { + # 1=AA, 2=AB + geno_mat[geno_mat == 3] <- 2 + geno_mat[geno_mat == 0] <- NA + } + + # Remove individuals with excessive missing data (>50%) + missing_rate <- rowMeans(is.na(geno_mat)) + valid_inds <- missing_rate <= 0.5 + geno_mat <- geno_mat[valid_inds, , drop = FALSE] + ind_ids <- ind_ids[valid_inds] + + # Read phenotype file + pheno_raw <- read.csv(pheno_path, header = TRUE, stringsAsFactors = FALSE, + check.names = FALSE, na.strings = na_strings) + + if (ncol(pheno_raw) < 2) { + stop("Phenotype file must have at least 2 columns (ID and trait)") + } + + pheno_ids <- as.character(pheno_raw[, 1]) + pheno_ids <- make.unique(pheno_ids) + pheno_df <- pheno_raw[, -1, drop = FALSE] + + # Convert phenotypes to numeric + for (i in 1:ncol(pheno_df)) { + pheno_df[, i] <- suppressWarnings(as.numeric(pheno_df[, i])) + } rownames(pheno_df) <- pheno_ids - - # ── 3. Align individuals ──────────────────────────────────────────────────── + + # Align individuals common_ids <- intersect(ind_ids, pheno_ids) - if (length(common_ids) == 0) - stop(paste0( - "No matching individual IDs between genotype and phenotype files.\n", - " Genotype IDs (first 5): ", paste(head(ind_ids, 5), collapse=", "), "\n", - " Phenotype IDs (first 5): ", paste(head(pheno_ids, 5), collapse=", ") - )) - - geno_mat <- geno_mat[common_ids, , drop = FALSE] - pheno_df <- pheno_df[common_ids, , drop = FALSE] - - # ── 4. Build the genetic map ──────────────────────────────────────────────── + if (length(common_ids) == 0) { + stop("No matching individual IDs between genotype and phenotype files") + } + + geno_mat <- geno_mat[common_ids, , drop = FALSE] + pheno_df <- pheno_df[common_ids, , drop = FALSE] + + # Build genetic map by chromosome unique_chrs <- unique(chromosomes) - - # Sort chromosomes intelligently (numeric first, then alpha) - chr_num <- suppressWarnings(as.integer(unique_chrs)) - ord <- order(ifelse(!is.na(chr_num), chr_num, 999L), unique_chrs) - unique_chrs <- unique_chrs[ord] - - map_list <- lapply(unique_chrs, function(ch) { - idx <- which(chromosomes == ch) - pos <- positions[idx] - mnames <- marker_names[idx] - ord2 <- order(pos) - m <- pos[ord2] - names(m) <- mnames[ord2] - m - }) - names(map_list) <- unique_chrs - - # ── 5. Construct the cross object manually ────────────────────────────────── - # Build geno list (one entry per chromosome) - geno_list <- lapply(unique_chrs, function(ch) { - idx <- which(chromosomes == ch) - mnames <- marker_names[idx] - pos_ch <- positions[idx] - ord2 <- order(pos_ch) - mnames <- mnames[ord2] - - g_chr <- geno_mat[, mnames, drop = FALSE] - - # Recode genotypes to qtl conventions - # Input: 1=homozygous parent A, 2=heterozygous, 3=homozygous parent B (F2) - # 1=homozygous A, 2=homozygous B (BC) - # qtl package: f2 → 1=AA, 2=AB, 3=BB; bc → 1=AA, 2=AB - g_chr[g_chr == 0] <- NA # 0 often means missing - storage.mode(g_chr) <- "integer" - - map_ch <- map_list[[ch]] - - list(data = g_chr, map = map_ch) - }) - names(geno_list) <- unique_chrs - - # Assign class to each chromosome's map + chr_numeric <- suppressWarnings(as.numeric(unique_chrs)) + chr_numeric[is.na(chr_numeric)] <- 999 + unique_chrs <- unique_chrs[order(chr_numeric, unique_chrs)] + + map_list <- list() + geno_list <- list() + for (ch in unique_chrs) { - class(geno_list[[ch]]$map) <- "A" # autosome + chr_idx <- which(chromosomes == ch) + if (length(chr_idx) > 0) { + chr_markers <- marker_names[chr_idx] + chr_positions <- positions[chr_idx] + names(chr_positions) <- chr_markers + + # Sort by position + ord <- order(chr_positions) + chr_positions <- chr_positions[ord] + chr_markers <- chr_markers[ord] + + # Remove duplicate positions + chr_positions <- chr_positions[!duplicated(chr_positions)] + chr_markers <- chr_markers[!duplicated(chr_markers)] + + if (length(chr_positions) > 0) { + map_list[[ch]] <- chr_positions + geno_list[[ch]] <- list( + data = geno_mat[, chr_markers, drop = FALSE], + map = chr_positions + ) + class(geno_list[[ch]]$map) <- "A" + } + } } - - # ── 6. Assemble cross ─────────────────────────────────────────��───────────── - cross_obj <- list( - geno = geno_list, - pheno = pheno_df + + # Create cross object + cross <- list(geno = geno_list, pheno = pheno_df) + class(cross) <- c(cross_type, "cross") + + # Run quality checks + cross <- jittermap(cross) + + # Calculate summary statistics + attr(cross, "summary") <- list( + n_ind = nind(cross), + n_markers = totmar(cross), + n_chr = nchr(cross), + missing_rate = mean(nmissing(cross, what = "mar") / nind(cross)), + heterozygosity = mean(calc.heterozyg(cross), na.rm = TRUE) ) - class(cross_obj) <- c(cross_type, "cross") - - # ── 7. Run basic checks / fixes ───────────────────────────────────────────── - cross_obj <- jittermap(cross_obj) # resolve duplicate positions - cross_obj <- convert2bcsft(cross_obj, BC.gen = 0, F.gen = 2, - estimate.map = FALSE) # only for f2; skip for others - # (this call is harmless for bc; if it errors, catch outside) - - cross_obj + + return(cross) } +# ============================================================================ +# ADVANCED QTL ANALYSIS FUNCTIONS +# ============================================================================ -# ─── SAFE CROSS BUILDER ─────────────────────────────────────────────────────── -safe_build_cross <- function(geno_path, pheno_path, cross_type) { - cross <- tryCatch( - parse_custom_cross(geno_path, pheno_path, cross_type), - error = function(e) { - # If the F2-specific convert call failed, retry without it - tryCatch({ - gp <- parse_custom_cross_base(geno_path, pheno_path, cross_type) - gp - }, error = function(e2) stop(e2)) - } - ) - cross +# Multiple QTL mapping methods +run_multiple_scans <- function(cross, pheno_col, methods = c("hk", "em", "imp", "mr", "np")) { + results <- list() + + for (method in methods) { + tryCatch({ + if (method == "imp") { + # Need to simulate genotypes first + cross_sim <- sim.geno(cross, n.draws = 64, step = 1) + scan <- scanone(cross_sim, pheno.col = pheno_col, method = "imp") + } else { + scan <- scanone(cross, pheno.col = pheno_col, method = method) + } + results[[method]] <- scan + }, error = function(e) { + warning(paste("Method", method, "failed:", e$message)) + results[[method]] <- NULL + }) + } + + return(results) } -# Version without convert2bcsft (for non-F2 cross types) -parse_custom_cross_base <- function(geno_path, pheno_path, cross_type = "bc") { - geno_raw <- read.csv(geno_path, header = FALSE, stringsAsFactors = FALSE, - check.names = FALSE, na.strings = c("NA","","N/A")) - col_names <- as.character(geno_raw[1, ]) - chr_row <- as.character(geno_raw[2, ]) - pos_row <- as.character(geno_raw[3, ]) - ind_data <- geno_raw[4:nrow(geno_raw), , drop = FALSE] - n_cols <- ncol(geno_raw) - marker_cols <- 2:n_cols - marker_names <- col_names[marker_cols] - chromosomes <- chr_row[marker_cols] - positions <- suppressWarnings(as.numeric(pos_row[marker_cols])) - chromosomes <- gsub("^[Cc]hr0*", "", chromosomes) - chr_numeric <- suppressWarnings(as.integer(chromosomes)) - chromosomes <- ifelse(!is.na(chr_numeric), as.character(chr_numeric), chromosomes) - ind_ids <- as.character(ind_data[, 1]) - geno_mat <- as.matrix(ind_data[, marker_cols, drop = FALSE]) - geno_mat <- apply(geno_mat, 2, function(x) suppressWarnings(as.numeric(x))) - rownames(geno_mat) <- ind_ids - colnames(geno_mat) <- marker_names - - pheno_raw <- read.csv(pheno_path, header = TRUE, stringsAsFactors = FALSE, - check.names = FALSE, na.strings = c("NA","","N/A")) - pheno_ids <- as.character(pheno_raw[, 1]) - pheno_df <- pheno_raw[, -1, drop = FALSE] - pheno_df <- as.data.frame(lapply(pheno_df, function(x) suppressWarnings(as.numeric(x)))) - rownames(pheno_df) <- pheno_ids - - common_ids <- intersect(ind_ids, pheno_ids) - if (length(common_ids) == 0) - stop(paste0("No matching IDs. Geno: ", paste(head(ind_ids,3), collapse=","), - " | Pheno: ", paste(head(pheno_ids,3), collapse=","))) - geno_mat <- geno_mat[common_ids, , drop = FALSE] - pheno_df <- pheno_df[common_ids, , drop = FALSE] - - unique_chrs <- unique(chromosomes) - chr_num <- suppressWarnings(as.integer(unique_chrs)) - ord <- order(ifelse(!is.na(chr_num), chr_num, 999L), unique_chrs) - unique_chrs <- unique_chrs[ord] - - map_list <- lapply(unique_chrs, function(ch) { - idx <- which(chromosomes == ch) - pos <- positions[idx] - mnames <- marker_names[idx] - ord2 <- order(pos); m <- pos[ord2]; names(m) <- mnames[ord2]; m +# Composite interval mapping +run_cim <- function(cross, pheno_col, window = 10, n_markers = 5) { + tryCatch({ + cim_result <- cim(cross, pheno.col = pheno_col, window = window, + n.marcovar = n_markers, method = "hk") + return(cim_result) + }, error = function(e) { + warning(paste("CIM failed:", e$message)) + return(NULL) }) - names(map_list) <- unique_chrs - - geno_list <- lapply(unique_chrs, function(ch) { - idx <- which(chromosomes == ch) - mnames <- marker_names[idx] - pos_ch <- positions[idx] - ord2 <- order(pos_ch); mnames <- mnames[ord2] - g_chr <- geno_mat[, mnames, drop = FALSE] - g_chr[g_chr == 0] <- NA - storage.mode(g_chr) <- "integer" - map_ch <- map_list[[ch]] - class(map_ch) <- "A" - list(data = g_chr, map = map_ch) - }) - names(geno_list) <- unique_chrs - - cross_obj <- list(geno = geno_list, pheno = pheno_df) - class(cross_obj) <- c(cross_type, "cross") - jittermap(cross_obj) } - -# ─── UI ─────────────────────────────────────────────────────────────────────── -ui <- fluidPage( - useShinyjs(), - tags$head( - tags$link( - href = "https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;600&family=IBM+Plex+Sans:wght@300;400;500;600&display=swap", - rel = "stylesheet" - ), - tags$style(HTML(" - :root { - --bg: #ffffff; - --panel: #f8f9fb; - --panel2: #f1f4f8; - --border: #dde2ea; - --accent1: #1a6cf5; - --accent2: #e8500a; - --accent3: #18a058; - --accent4: #c2185b; - --accent5: #7c3aed; - --text: #1a202c; - --text2: #4a5568; - --muted: #8a95a3; - --font-mono: 'IBM Plex Mono', monospace; - --font-body: 'IBM Plex Sans', sans-serif; - --shadow: 0 1px 4px rgba(0,0,0,0.07), 0 4px 16px rgba(0,0,0,0.05); - --shadow-lg: 0 2px 8px rgba(0,0,0,0.08), 0 8px 32px rgba(0,0,0,0.07); - } - * { box-sizing: border-box; margin: 0; padding: 0; } - body { - background: var(--bg); color: var(--text); - font-family: var(--font-body); min-height: 100vh; font-size: 14px; - } - .qtl-header { - background: #ffffff; border-bottom: 1.5px solid var(--border); - padding: 0 32px; height: 60px; display: flex; align-items: center; - gap: 16px; position: sticky; top: 0; z-index: 100; - box-shadow: 0 1px 6px rgba(0,0,0,0.06); - } - .qtl-header .logo-mark { - width: 36px; height: 36px; background: var(--accent1); border-radius: 8px; - display: flex; align-items: center; justify-content: center; - font-family: var(--font-mono); font-weight: 600; font-size: 13px; - color: #ffffff; flex-shrink: 0; letter-spacing: -0.5px; - } - .qtl-header h1 { font-family: var(--font-mono); font-size: 15px; color: var(--text); letter-spacing: 1px; font-weight: 600; } - .qtl-header .subtitle { font-size: 11px; color: var(--muted); letter-spacing: 0.3px; margin-top: 1px; } - .header-badges { margin-left: auto; display: flex; gap: 6px; } - .badge-pill { padding: 3px 10px; border-radius: 100px; font-size: 10px; font-family: var(--font-mono); letter-spacing: 0.5px; border: 1px solid; font-weight: 600; } - .badge-pill.blue { color: var(--accent1); border-color: #bcd0fc; background: #eef3fe; } - .badge-pill.green { color: var(--accent3); border-color: #b3dfc7; background: #edf7f2; } - .badge-pill.orange { color: var(--accent2); border-color: #f8c4a8; background: #fef4ee; } - .qtl-layout { display: grid; grid-template-columns: 280px 1fr; height: calc(100vh - 60px); } - .qtl-sidebar { background: var(--panel); border-right: 1.5px solid var(--border); overflow-y: auto; padding: 20px 16px 32px; } - .qtl-sidebar::-webkit-scrollbar { width: 4px; } - .qtl-sidebar::-webkit-scrollbar-thumb { background: var(--border); border-radius: 4px; } - .section-label { - font-family: var(--font-mono); font-size: 9px; letter-spacing: 2.5px; - color: var(--muted); text-transform: uppercase; margin-bottom: 10px; - margin-top: 22px; padding-left: 2px; display: flex; align-items: center; gap: 8px; - } - .section-label::after { content: ''; flex: 1; height: 1px; background: var(--border); } - .section-label:first-child { margin-top: 0; } - .qtl-upload { - border: 1.5px dashed var(--border); border-radius: 8px; padding: 12px; - transition: border-color .2s, background .2s; background: #ffffff; margin-bottom: 8px; - } - .qtl-upload:hover { border-color: var(--accent1); background: #f5f8ff; } - .qtl-upload label { font-size: 10px; color: var(--accent1); font-family: var(--font-mono); letter-spacing: 1px; margin-bottom: 5px; display: block; font-weight: 600; } - .qtl-upload .shiny-input-container { margin: 0 !important; } - .format-help { font-size: 10px; color: var(--muted); font-family: var(--font-mono); line-height: 1.6; margin-top: 4px; padding: 6px 8px; background: var(--panel2); border-radius: 4px; } - .required-notice { background: #fff8e1; border: 1px solid #f5c842; border-radius: 6px; padding: 8px 11px; font-size: 11px; color: #7a5800; font-family: var(--font-mono); line-height: 1.5; margin-bottom: 10px; } - .control-block { margin-bottom: 11px; } - .control-block label { font-size: 10px; color: var(--text2); letter-spacing: 0.8px; font-family: var(--font-mono); text-transform: uppercase; display: block; margin-bottom: 4px; font-weight: 600; } - select, input[type='number'], input[type='text'] { width: 100%; background: #ffffff; border: 1.5px solid var(--border); border-radius: 6px; color: var(--text); padding: 7px 10px; font-size: 12px; font-family: var(--font-body); outline: none; transition: border-color .2s; appearance: none; } - select:focus, input:focus { border-color: var(--accent1); box-shadow: 0 0 0 3px rgba(26,108,245,0.1); } - .shiny-input-checkboxgroup .checkbox label { font-size: 11px; color: var(--text2); display: flex; align-items: center; gap: 6px; } - .btn-run { width: 100%; padding: 11px; background: var(--accent1); border: none; border-radius: 8px; color: #ffffff; font-family: var(--font-mono); font-size: 12px; font-weight: 600; letter-spacing: 1.5px; cursor: pointer; transition: background .2s, transform .1s, box-shadow .2s; margin-top: 16px; box-shadow: 0 2px 8px rgba(26,108,245,0.25); } - .btn-run:hover { background: #1558d4; transform: translateY(-1px); box-shadow: 0 4px 14px rgba(26,108,245,0.3); } - .btn-run:active { transform: translateY(0); } - .btn-export { width: 100%; padding: 9px; background: #ffffff; border: 1.5px solid var(--accent3); border-radius: 8px; color: var(--accent3); font-family: var(--font-mono); font-size: 11px; font-weight: 600; letter-spacing: 1px; cursor: pointer; margin-top: 8px; transition: background .2s; } - .btn-export:hover { background: #edf7f2; } - .status-row { display: flex; align-items: center; gap: 8px; padding: 8px 10px; background: #ffffff; border: 1.5px solid var(--border); border-radius: 6px; margin-top: 12px; font-size: 11px; color: var(--muted); font-family: var(--font-mono); } - .status-dot { width: 7px; height: 7px; border-radius: 50%; background: var(--muted); flex-shrink: 0; } - .status-dot.active { background: var(--accent3); box-shadow: 0 0 5px rgba(24,160,88,0.5); } - .status-dot.error { background: var(--accent2); box-shadow: 0 0 5px rgba(232,80,10,0.5); } - .qtl-main { overflow-y: auto; background: var(--bg); } - .qtl-main::-webkit-scrollbar { width: 6px; } - .qtl-main::-webkit-scrollbar-thumb { background: var(--border); border-radius: 4px; } - .qtl-tabs { display: flex; gap: 0; padding: 0 24px; border-bottom: 1.5px solid var(--border); background: #ffffff; position: sticky; top: 0; z-index: 50; overflow-x: auto; box-shadow: 0 1px 4px rgba(0,0,0,0.04); } - .qtl-tabs::-webkit-scrollbar { display: none; } - .qtl-tab-btn { padding: 14px 16px; border: none; background: transparent; color: var(--muted); font-family: var(--font-mono); font-size: 10px; letter-spacing: 1px; text-transform: uppercase; cursor: pointer; border-bottom: 2.5px solid transparent; transition: color .2s, border-color .2s; white-space: nowrap; font-weight: 600; margin-bottom: -1.5px; } - .qtl-tab-btn:hover { color: var(--text); } - .qtl-tab-btn.active { color: var(--accent1); border-bottom-color: var(--accent1); } - .tab-content { display: none; padding: 24px; } - .tab-content.active { display: block; } - .plot-card { background: #ffffff; border: 1.5px solid var(--border); border-radius: 12px; overflow: hidden; margin-bottom: 20px; box-shadow: var(--shadow); } - .plot-card-header { display: flex; align-items: center; padding: 13px 18px; border-bottom: 1px solid var(--border); background: var(--panel); gap: 10px; } - .plot-card-icon { width: 28px; height: 28px; border-radius: 6px; display: flex; align-items: center; justify-content: center; font-size: 13px; flex-shrink: 0; } - .plot-card-icon.blue { background: #eef3fe; } - .plot-card-icon.orange { background: #fef4ee; } - .plot-card-icon.green { background: #edf7f2; } - .plot-card-icon.pink { background: #fce8f1; } - .plot-card-icon.purple { background: #f3effe; } - .plot-card-title { font-family: var(--font-mono); font-size: 12px; color: var(--text); letter-spacing: 0.8px; font-weight: 600; } - .plot-card-subtitle { font-size: 10px; color: var(--muted); margin-top: 1px; } - .plot-card-body { padding: 16px; } - .stat-row { display: flex; gap: 10px; flex-wrap: wrap; margin-bottom: 20px; } - .stat-chip { padding: 10px 18px; border-radius: 10px; font-family: var(--font-mono); font-size: 12px; border: 1.5px solid; font-weight: 600; box-shadow: var(--shadow); } - .stat-chip.blue { background: #eef3fe; color: var(--accent1); border-color: #bcd0fc; } - .stat-chip.orange { background: #fef4ee; color: var(--accent2); border-color: #f8c4a8; } - .stat-chip.green { background: #edf7f2; color: var(--accent3); border-color: #b3dfc7; } - .stat-chip.pink { background: #fce8f1; color: var(--accent4); border-color: #f0a8c8; } - .grid-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; } - .grid-3 { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 20px; } - @media (max-width: 1100px) { .grid-3 { grid-template-columns: 1fr 1fr; } } - @media (max-width: 800px) { .grid-2, .grid-3 { grid-template-columns: 1fr; } } - .empty-state { text-align: center; padding: 60px 24px; color: var(--muted); } - .empty-state .empty-icon { font-size: 48px; margin-bottom: 16px; } - .empty-state h3 { font-size: 16px; color: var(--text2); margin-bottom: 8px; font-family: var(--font-mono); } - .empty-state p { font-size: 13px; line-height: 1.6; max-width: 400px; margin: 0 auto; } - .dataTables_wrapper { color: var(--text) !important; font-size: 12px; } - table.dataTable { background: transparent !important; color: var(--text) !important; border-collapse: collapse !important; } - table.dataTable thead th { background: var(--panel) !important; color: var(--accent1) !important; font-family: var(--font-mono) !important; font-size: 10px !important; letter-spacing: 1px !important; border-bottom: 1.5px solid var(--border) !important; padding: 10px 12px !important; font-weight: 600 !important; } - table.dataTable tbody tr { background: transparent !important; } - table.dataTable tbody tr:hover td { background: #f5f8ff !important; } - table.dataTable tbody td { border-bottom: 1px solid var(--border) !important; padding: 8px 12px !important; color: var(--text) !important; } - .dataTables_info, .dataTables_paginate { color: var(--muted) !important; font-size: 11px !important; } - .paginate_button { color: var(--text2) !important; } - .paginate_button.current { background: var(--accent1) !important; color: #ffffff !important; border-radius: 4px !important; } - .dataTables_filter input, .dataTables_length select { background: #ffffff !important; border: 1.5px solid var(--border) !important; color: var(--text) !important; border-radius: 4px !important; padding: 4px 8px !important; } - .info-box { background: #f0f5ff; border: 1px solid #bcd0fc; border-radius: 8px; padding: 12px 16px; font-size: 12px; color: var(--text2); line-height: 1.6; margin-bottom: 16px; } - .error-box { background: #fff0ee; border: 1px solid #f8c4a8; border-radius: 8px; padding: 12px 16px; font-size: 12px; color: #7a1a00; line-height: 1.6; margin-bottom: 16px; font-family: var(--font-mono); } - hr.divider { border: none; border-top: 1px solid var(--border); margin: 20px 0; } - .parse-preview { font-family: var(--font-mono); font-size: 10px; color: var(--text2); background: var(--panel2); border-radius: 6px; padding: 10px 12px; margin-top: 8px; line-height: 1.7; border: 1px solid var(--border); } - ")) - ), - - div(class = "qtl-header", - div(class = "logo-mark", "QTL"), - div(tags$h1("QTL Mapper Pro"), - div(class = "subtitle", "Quantitative Trait Loci Analysis Pipeline")), - div(class = "header-badges", - div(class = "badge-pill blue", "R/QTL ENGINE"), - div(class = "badge-pill green", "10+ MODELS"), - div(class = "badge-pill orange","MULTI-TRAIT")) - ), - - div(class = "qtl-layout", - - # ── Sidebar ────────────────────────────────────────────────────────────── - div(class = "qtl-sidebar", - - div(class = "section-label", "Data Input"), - - div(class = "required-notice", - "⚠ Upload both CSV files.", tags$br(), - "Genotype: header + chr row + pos row + data rows.", tags$br(), - "Phenotype: header + data rows." - ), - - div(class = "qtl-upload", - tags$label("Genotype CSV"), - fileInput("geno_file", NULL, accept = ".csv", - buttonLabel = "Browse", placeholder = "genotypes.csv"), - div(class = "format-help", - "Row 1: id | marker1 | marker2...", tags$br(), - "Row 2: (blank) | chr1 | chr1...", tags$br(), - "Row 3: (blank) | 0.22 | 0.60...", tags$br(), - "Row 4+: sampleID | 1|2|3..." - ) - ), - - div(class = "qtl-upload", - tags$label("Phenotype CSV"), - fileInput("pheno_file", NULL, accept = ".csv", - buttonLabel = "Browse", placeholder = "phenotypes.csv"), - div(class = "format-help", - "Row 1: id | trait1 | trait2...", tags$br(), - "Row 2+: sampleID | values..." - ) - ), - - # Preview of parsed data - uiOutput("parse_preview_ui"), - - div(class = "section-label", "Cross Type"), - div(class = "control-block", - selectInput("cross_type", NULL, - choices = c("Backcross" = "bc", "F2 Intercross" = "f2", - "RIL (selfing)" = "riself", "RIL (sib-mating)" = "risib"), - selected = "f2") - ), - - div(class = "section-label", "Phenotype"), - div(class = "control-block", - selectInput("pheno_col", NULL, choices = NULL) - ), - - div(class = "section-label", "Scan Models"), - checkboxGroupInput("models", NULL, - choices = c( - "EM Algorithm (em)" = "em", - "Haley-Knott (hk)" = "hk", - "Extended HK (ehk)" = "ehk", - "Multiple Imputation (imp)" = "imp", - "Composite Interval (cim)" = "cim", - "Non-Parametric (np)" = "np", - "Marker Regression (mr)" = "mr" - ), - selected = c("hk","em","imp","np","mr") - ), - - div(class = "section-label", "Permutation"), - div(class = "control-block", - tags$label("Permutations (0 = skip)"), - numericInput("n_perm", NULL, value = 100, min = 0, max = 1000, step = 50) - ), - div(class = "control-block", - tags$label("α threshold"), - numericInput("alpha_thresh", NULL, value = 0.05, min = 0.01, max = 0.1, step = 0.01) - ), - div(class = "control-block", - tags$label("Fixed LOD threshold"), - numericInput("lod_thresh", NULL, value = 3.0, min = 1, max = 10, step = 0.5) - ), - - div(class = "section-label", "Genome Scan"), - div(class = "control-block", - tags$label("Step (cM)"), - numericInput("step_size", NULL, value = 1, min = 0.5, max = 5, step = 0.5) - ), - div(class = "control-block", - tags$label("Error probability"), - numericInput("error_prob", NULL, value = 0.001, min = 0.0001, max = 0.01, step = 0.001) - ), - - actionButton("run_analysis", "▶ RUN ANALYSIS", class = "btn-run"), - downloadButton("download_results", "⬇ EXPORT CSV", class = "btn-export"), - - div(class = "status-row", - div(id = "status_dot", class = "status-dot"), - textOutput("status_text", inline = TRUE) - ) - ), - - # ── Main ───────────────────────────────────────────────────────────────── - div(class = "qtl-main", - - div(class = "qtl-tabs", - tags$button(class = "qtl-tab-btn active", `data-tab` = "overview", "Overview"), - tags$button(class = "qtl-tab-btn", `data-tab` = "manhattan", "Manhattan"), - tags$button(class = "qtl-tab-btn", `data-tab` = "genome", "Genome Scan"), - tags$button(class = "qtl-tab-btn", `data-tab` = "chromosome", "Chr Plots"), - tags$button(class = "qtl-tab-btn", `data-tab` = "model_comp", "Model Compare"), - tags$button(class = "qtl-tab-btn", `data-tab` = "effects", "QTL Effects"), - tags$button(class = "qtl-tab-btn", `data-tab` = "pairwise", "2D Scan"), - tags$button(class = "qtl-tab-btn", `data-tab` = "diagnostics","Diagnostics"), - tags$button(class = "qtl-tab-btn", `data-tab` = "results", "QTL Table"), - tags$button(class = "qtl-tab-btn", `data-tab` = "summary", "Summary") - ), - - div(id = "tab_overview", class = "tab-content active", uiOutput("overview_content")), - div(id = "tab_manhattan", class = "tab-content", uiOutput("manhattan_content")), - div(id = "tab_genome", class = "tab-content", uiOutput("genome_content")), - div(id = "tab_chromosome", class = "tab-content", uiOutput("chromosome_content")), - div(id = "tab_model_comp", class = "tab-content", uiOutput("model_comp_content")), - div(id = "tab_effects", class = "tab-content", uiOutput("effects_content")), - div(id = "tab_pairwise", class = "tab-content", uiOutput("pairwise_content")), - div(id = "tab_diagnostics",class = "tab-content", uiOutput("diagnostics_content")), - div(id = "tab_results", class = "tab-content", uiOutput("results_content")), - div(id = "tab_summary", class = "tab-content", uiOutput("summary_content")) - ) - ), - - tags$script(HTML(" - document.querySelectorAll('.qtl-tab-btn').forEach(function(btn) { - btn.addEventListener('click', function() { - document.querySelectorAll('.qtl-tab-btn').forEach(b => b.classList.remove('active')); - document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active')); - btn.classList.add('active'); - document.getElementById('tab_' + btn.dataset.tab).classList.add('active'); - }); - }); - ")) -) - - -# ─── SERVER ─────────────────────────────────────────────────────────────────── -server <- function(input, output, session) { - - theme_qtl <- function(base_size = 11) { - theme_minimal(base_size = base_size) + - theme( - plot.background = element_rect(fill = "#ffffff", color = NA), - panel.background = element_rect(fill = "#f8f9fb", color = NA), - panel.grid.major = element_line(color = "#e8ecf2", linewidth = .45), - panel.grid.minor = element_line(color = "#f1f4f8", linewidth = .25), - panel.border = element_rect(color = "#dde2ea", fill = NA, linewidth = .8), - axis.text = element_text(color = "#8a95a3", size = 9, family = "mono"), - axis.title = element_text(color = "#4a5568", size = 10), - plot.title = element_text(color = "#1a202c", size = 12, face = "bold", family = "mono"), - plot.subtitle = element_text(color = "#8a95a3", size = 9), - legend.background = element_rect(fill = "#ffffff", color = "#dde2ea", linewidth = .5), - legend.text = element_text(color = "#4a5568", size = 9), - legend.title = element_text(color = "#8a95a3", size = 9), - strip.background = element_rect(fill = "#f1f4f8", color = "#dde2ea"), - strip.text = element_text(color = "#1a6cf5", size = 9, family = "mono", face = "bold"), - plot.margin = margin(12, 16, 12, 16) - ) - } - - model_colors <- c( - em = "#1a6cf5", hk = "#e8500a", ehk = "#18a058", imp = "#c2185b", - cim = "#7c3aed", np = "#0891b2", mr = "#dc2626" - ) - - empty_state_ui <- function(icon = "📂", title = "No Data Loaded", - msg = "Upload your genotype and phenotype CSV files, then click RUN ANALYSIS.") { - div(class = "empty-state", - div(class = "empty-icon", icon), - tags$h3(title), - tags$p(msg) - ) - } - - # ── Reactive: parse cross from uploaded CSVs ────────────────────────────── - cross_data <- reactive({ - req(input$geno_file, input$pheno_file) - tryCatch({ - cross <- parse_custom_cross_base( - geno_path = input$geno_file$datapath, - pheno_path = input$pheno_file$datapath, - cross_type = input$cross_type - ) - cross - }, error = function(e) { - showNotification(paste0("Data loading error: ", e$message), type = "error", duration = 12) - NULL - }) +# Multiple QTL mapping (MQM) +run_mqm <- function(cross, pheno_col, cofactors = NULL) { + tryCatch({ + if (is.null(cofactors)) { + # Automatic cofactor selection + scan <- scanone(cross, pheno.col = pheno_col, method = "hk") + cofactors <- which(scan$lod > 2) + } + mqm_result <- mqm(cross, pheno.col = pheno_col, cofactors = cofactors) + return(mqm_result) + }, error = function(e) { + warning(paste("MQM failed:", e$message)) + return(NULL) }) +} - # ── Parse preview ───────────────────────────────────────────────────────── - output$parse_preview_ui <- renderUI({ - req(input$geno_file, input$pheno_file) - cross <- cross_data() - if (is.null(cross)) { - div(class = "error-box", - "❌ Failed to parse files.", tags$br(), - "Check that your genotype CSV has chr/pos rows in rows 2 and 3, and that individual IDs match between files." +# Epistasis detection +detect_epistasis <- function(cross, pheno_col, threshold = 5) { + tryCatch({ + scantwo_result <- scantwo(cross, pheno.col = pheno_col, method = "hk") + + # Extract significant interactions + lod_matrix <- scantwo_result$lod + diag(lod_matrix) <- 0 + + # Find significant interactions + significant <- which(lod_matrix > threshold, arr.ind = TRUE) + + if (nrow(significant) > 0) { + epistasis <- data.frame( + chr1 = rownames(lod_matrix)[significant[, 1]], + pos1 = as.numeric(rownames(lod_matrix)[significant[, 1]]), + chr2 = colnames(lod_matrix)[significant[, 2]], + pos2 = as.numeric(colnames(lod_matrix)[significant[, 2]]), + lod = lod_matrix[significant] ) + return(list(epistasis = epistasis, full_result = scantwo_result)) } else { - div(class = "parse-preview", - paste0("✓ Loaded: ", totmar(cross), " markers, ", - nind(cross), " individuals, ", nchr(cross), " chromosomes"), tags$br(), - paste0(" Pheno traits: ", paste(names(cross$pheno), collapse=", ")) - ) + return(list(epistasis = NULL, full_result = scantwo_result)) } + }, error = function(e) { + warning(paste("Epistasis detection failed:", e$message)) + return(NULL) }) +} - # ── Update phenotype dropdown ───────────────────────────────────────────── - observe({ - cross <- cross_data(); req(cross) - pheno_names <- names(cross$pheno) - updateSelectInput(session, "pheno_col", choices = pheno_names, selected = pheno_names[1]) - runjs("document.getElementById('status_dot').classList.add('active')") - output$status_text <- renderText(paste0( - totmar(cross), " markers · ", nind(cross), " inds · ", nchr(cross), " chrs — Ready" - )) - }) - - # ── Analysis results ─────────────────────────────────���──────────────────── - analysis_results <- reactiveVal(NULL) - - observeEvent(input$run_analysis, { - cross <- cross_data() - if (is.null(cross)) { - showNotification("Please upload both CSV files first.", type = "warning"); return() +# QTL effect estimation +estimate_qtl_effects <- function(cross, qtl_positions, pheno_col) { + effects <- list() + + for (i in 1:nrow(qtl_positions)) { + qtl <- qtl_positions[i, ] + + # Find nearest marker + markers <- find.marker(cross, as.character(qtl$Chromosome), qtl$Position) + + # Calculate genotype means + geno <- pull.geno(cross)[, markers] + pheno <- cross$pheno[[pheno_col]] + + means <- tapply(pheno, geno, mean, na.rm = TRUE) + se <- tapply(pheno, geno, function(x) sd(x, na.rm = TRUE) / sqrt(sum(!is.na(x)))) + + # Calculate additive and dominance effects + if (length(means) == 3) { # F2 + add_effect <- (means[3] - means[1]) / 2 + dom_effect <- means[2] - (means[1] + means[3]) / 2 + } else { # BC + add_effect <- means[2] - means[1] + dom_effect <- NA } + + effects[[i]] <- list( + marker = markers, + means = means, + se = se, + additive = add_effect, + dominance = dom_effect + ) + } + + return(effects) +} - runjs("document.getElementById('status_dot').classList.remove('active')") - output$status_text <- renderText("Running analysis...") - - withProgress(message = "QTL Mapping in progress...", value = 0, { - - cross <- tryCatch( - calc.genoprob(cross, step = input$step_size, error.prob = input$error_prob), - error = function(e) { showNotification(paste("calc.genoprob failed:", e$message), type="error"); NULL } - ) - req(cross) - incProgress(0.1, detail = "Genoprobs calculated") - - cross <- tryCatch( - sim.geno(cross, n.draws = 64, step = input$step_size, error.prob = input$error_prob), - error = function(e) cross # non-fatal; some methods don't need it - ) - incProgress(0.1, detail = "Simulated genotypes done") - - pheno_idx <- which(names(cross$pheno) == input$pheno_col) - if (length(pheno_idx) == 0) pheno_idx <- 1 - - scan_results <- list() - perm_results <- list() - models_to_run <- input$models - if (length(models_to_run) == 0) models_to_run <- "hk" - - for (i in seq_along(models_to_run)) { - mdl <- models_to_run[i] - incProgress(0.5 / length(models_to_run), detail = paste("Scanning:", mdl)) - sc <- tryCatch( - scanone(cross, pheno.col = pheno_idx, method = mdl), - error = function(e) { message("scanone failed for ", mdl, ": ", e$message); NULL } - ) - if (!is.null(sc)) { - scan_results[[mdl]] <- sc - if (input$n_perm > 0) { - perm_results[[mdl]] <- tryCatch( - scanone(cross, pheno.col = pheno_idx, method = mdl, - n.perm = input$n_perm, verbose = FALSE), - error = function(e) NULL - ) - } - } - } - - if (length(scan_results) == 0) { - showNotification("All scan methods failed. Check your data.", type = "error"); return() - } - incProgress(0.1, detail = "Summarising QTLs") +# Permutation test with multiple alpha levels +run_permutation_test <- function(cross, pheno_col, n_perm = 1000, + alpha_levels = c(0.05, 0.01, 0.001)) { + tryCatch({ + perms <- scanone(cross, pheno.col = pheno_col, n.perm = n_perm, method = "hk") + + thresholds <- list() + for (alpha in alpha_levels) { + thr <- summary(perms, alpha = alpha)[[1]] + thresholds[[as.character(alpha)]] <- thr + } + + return(list(permutations = perms, thresholds = thresholds)) + }, error = function(e) { + warning(paste("Permutation test failed:", e$message)) + return(NULL) + }) +} - lod_thr <- input$lod_thresh - if (length(perm_results) > 0) { - first_perm <- perm_results[[1]] - if (!is.null(first_perm)) { - thr_try <- tryCatch(summary(first_perm, alpha = input$alpha_thresh)[[1]], error = function(e) NULL) - if (!is.null(thr_try) && is.numeric(thr_try)) lod_thr <- thr_try - } - } +# ============================================================================ +# ADVANCED VISUALIZATION FUNCTIONS (10+ unique plots) +# ============================================================================ + +# 1. Enhanced Manhattan plot with annotations +create_manhattan_enhanced <- function(scan, threshold = 3, qtls = NULL, + highlight_genes = NULL) { + df <- as.data.frame(scan) + df$marker <- rownames(df) + df$significant <- df$lod >= threshold + + # Calculate chromosome positions for spacing + chrs <- unique(df$chr) + chr_lengths <- sapply(chrs, function(ch) max(df$pos[df$chr == ch])) + cum_lengths <- cumsum(c(0, chr_lengths[-length(chrs)])) + names(cum_lengths) <- chrs + + df$pos_cum <- df$pos + cum_lengths[as.character(df$chr)] + chr_midpoints <- sapply(chrs, function(ch) mean(df$pos_cum[df$chr == ch])) + + # Create base plot + p <- ggplot(df, aes(x = pos_cum, y = lod, color = chr)) + + geom_point(size = 1.5, alpha = 0.7) + + geom_hline(yintercept = threshold, color = "red", linetype = "dashed", size = 1) + + scale_x_continuous(breaks = chr_midpoints, labels = names(chr_midpoints)) + + scale_color_manual(values = rep(brewer.pal(8, "Set1"), length.out = length(chrs))) + + labs(title = "Genome-wide Manhattan Plot", + x = "Chromosome", y = "LOD Score") + + theme_minimal() + + theme(legend.position = "none", + axis.text.x = element_text(angle = 45, hjust = 1)) + + # Add QTL highlights + if (!is.null(qtls) && nrow(qtls) > 0) { + qtls$pos_cum <- qtls$Position_cM + cum_lengths[as.character(qtls$Chromosome)] + p <- p + geom_point(data = qtls, aes(x = pos_cum, y = LOD), + color = "gold", size = 4, shape = 18) + + geom_text_repel(data = qtls, aes(x = pos_cum, y = LOD, label = paste0("QTL-", 1:nrow(qtls))), + color = "darkred", size = 3) + } + + return(p) +} - qtl_table <- build_qtl_table(cross, scan_results, lod_thr, pheno_idx) - incProgress(0.1, detail = "Done") +# 2. Interactive 3D Manhattan plot +create_manhattan_3d <- function(scan, threshold = 3) { + df <- as.data.frame(scan) + df$marker <- rownames(df) + + # Create 3D plot + plot_ly(df, x = ~chr, y = ~pos, z = ~lod, color = ~lod, + colors = viridis(100), type = "scatter3d", mode = "markers", + marker = list(size = 3, opacity = 0.7), + text = ~paste("Marker:", marker, "
LOD:", round(lod, 3)), + hoverinfo = "text") %>% + layout(title = "3D Manhattan Plot", + scene = list(xaxis = list(title = "Chromosome"), + yaxis = list(title = "Position (cM)"), + zaxis = list(title = "LOD Score"))) %>% + add_trace(x = ~chr, y = ~pos, z = threshold, type = "scatter3d", mode = "lines", + line = list(color = "red", width = 2), name = "Threshold", showlegend = TRUE) +} - analysis_results(list( - cross = cross, - scan_results = scan_results, - perm_results = perm_results, - lod_thr = lod_thr, - qtl_table = qtl_table, - pheno_idx = pheno_idx - )) - }) +# 3. Heatmap of QTL interactions +create_qtl_heatmap <- function(scantwo_result) { + lod_matrix <- scantwo_result$lod + + # Create heatmap with clustering + pheatmap(lod_matrix, + color = viridis(100), + cluster_rows = TRUE, + cluster_cols = TRUE, + display_numbers = FALSE, + main = "QTL Interaction Heatmap", + xlab = "Position 2", ylab = "Position 1", + fontsize = 8) +} - res <- analysis_results() - if (is.null(res)) return() +# 4. Circular genome plot with QTLs +create_circular_genome <- function(cross, scan, qtls = NULL) { + # Prepare data for circlize + map <- pull.map(cross) + chr_names <- names(map) + + # Initialize circos plot + circos.par(start.degree = 90) + circos.initialize(factors = chr_names, xlim = lapply(map, function(x) c(0, max(x)))) + + # Add tracks + circos.trackPlotRegion(factors = chr_names, ylim = c(0, 1), + panel.fun = function(x, y) { + circos.text(CELL_META$xcenter, CELL_META$cell.ylim[2] + 0.1, + CELL_META$sector.index, cex = 0.8) + }) + + # Add LOD scores as heatmap + for (chr in chr_names) { + chr_scan <- scan[scan$chr == chr, ] + if (nrow(chr_scan) > 0) { + colors <- colorRamp2(c(0, max(scan$lod)), c("white", "red")) + circos.rect(chr_scan$pos, rep(0, nrow(chr_scan)), + chr_scan$pos + 1, rep(1, nrow(chr_scan)), + col = colors(chr_scan$lod), border = NA) + } + } + + # Add QTL markers + if (!is.null(qtls) && nrow(qtls) > 0) { + for (i in 1:nrow(qtls)) { + circos.points(qtls$Position_cM[i], 1, sector.index = as.character(qtls$Chromosome[i]), + col = "gold", pch = 16, cex = 1.5) + } + } + + circos.clear() +} - model_choices <- names(res$scan_results) - updateSelectInput(session, "manhattan_model", choices = model_choices, selected = model_choices[1]) - updateSelectInput(session, "chr_plot_model", choices = model_choices, selected = model_choices[1]) +# 5. Ridge plot of LOD scores by chromosome +create_ridge_plot <- function(scan) { + df <- as.data.frame(scan) + df$chr <- factor(df$chr, levels = unique(df$chr)) + + ggplot(df, aes(x = lod, y = chr, fill = after_stat(x))) + + geom_density_ridges_gradient(scale = 3, rel_min_height = 0.01) + + scale_fill_viridis_c(option = "C", name = "LOD Score") + + labs(title = "LOD Score Distribution by Chromosome", + x = "LOD Score", y = "Chromosome") + + theme_ridges() + + theme(legend.position = "right") +} - qtl_choices <- if (!is.null(res$qtl_table) && nrow(res$qtl_table) > 0) - paste0(res$qtl_table$Chr, "@", res$qtl_table$Peak_Marker) else "none" - updateSelectInput(session, "effect_qtl", choices = qtl_choices) +# 6. Correlation circle of multiple traits +create_trait_correlation <- function(cross, traits = NULL) { + if (is.null(traits)) traits <- names(cross$pheno) + if (length(traits) < 2) return(NULL) + + # Calculate correlations + cor_matrix <- cor(cross$pheno[, traits], use = "complete.obs") + + # Create correlation plot + ggcorrplot(cor_matrix, + method = "circle", + type = "lower", + lab = TRUE, + lab_size = 3, + title = "Trait Correlation Matrix", + colors = c("#FF6B6B", "white", "#4ECDC4")) + + theme_minimal() +} - runjs("document.getElementById('status_dot').classList.add('active')") - output$status_text <- renderText(paste0( - "Done — ", length(model_choices), " models · ", - if (!is.null(res$qtl_table)) nrow(res$qtl_table) else 0, " QTLs" - )) - }) +# 7. Effect size comparison across methods +create_method_comparison <- function(scan_results, qtls) { + # Extract peak LOD for each method + method_comparison <- data.frame() + + for (method in names(scan_results)) { + scan <- scan_results[[method]] + if (!is.null(scan)) { + max_lod <- max(scan$lod, na.rm = TRUE) + method_comparison <- rbind(method_comparison, + data.frame(Method = method, MaxLOD = max_lod)) + } + } + + # Create comparison plot + p1 <- ggplot(method_comparison, aes(x = reorder(Method, -MaxLOD), y = MaxLOD, fill = Method)) + + geom_bar(stat = "identity", alpha = 0.8) + + geom_text(aes(label = round(MaxLOD, 2)), vjust = -0.5, size = 4) + + scale_fill_brewer(palette = "Set2") + + labs(title = "Maximum LOD Score by Method", + x = "Mapping Method", y = "Maximum LOD") + + theme_minimal() + + theme(legend.position = "none") + + # If we have QTLs, create effect size plot + if (!is.null(qtls) && nrow(qtls) > 0) { + p2 <- ggplot(qtls, aes(x = reorder(paste(Chromosome, "@", Position_cM), -LOD), + y = LOD, fill = as.factor(Chromosome))) + + geom_bar(stat = "identity", alpha = 0.8) + + geom_errorbar(aes(ymin = LOD - 1, ymax = LOD + 1), width = 0.2) + + scale_fill_brewer(palette = "Set3") + + labs(title = "Significant QTLs by LOD Score", + x = "QTL Location", y = "LOD Score") + + theme_minimal() + + theme(legend.position = "none", + axis.text.x = element_text(angle = 45, hjust = 1)) + + return(list(p1 = p1, p2 = p2)) + } + + return(p1) +} - # ── Build QTL table ─────────────────────────────────────────────────────── - build_qtl_table <- function(cross, scan_results, lod_thr, pheno_idx) { - rows <- list() - for (mdl in names(scan_results)) { - sc <- scan_results[[mdl]] - sig <- sc[sc$lod >= lod_thr, , drop = FALSE] - if (nrow(sig) == 0) next +# 8. Genetic map density plot +create_map_density <- function(cross) { + map <- pull.map(cross) + + # Calculate marker density + density_data <- data.frame() + for (chr in names(map)) { + positions <- map[[chr]] + if (length(positions) > 1) { + gaps <- diff(positions) + density_data <- rbind(density_data, + data.frame(Chromosome = chr, + Gap = gaps, + Position = positions[-1])) + } + } + + ggplot(density_data, aes(x = Gap, fill = Chromosome)) + + geom_histogram(bins = 30, alpha = 0.6, position = "identity") + + scale_fill_brewer(palette = "Set1") + + labs(title = "Marker Density Distribution", + x = "Inter-marker Distance (cM)", y = "Count") + + theme_minimal() + + theme(legend.position = "right") +} - for (ch in unique(sig$chr)) { - chr_sc <- sc[sc$chr == ch, ] - peak_row <- chr_sc[which.max(chr_sc$lod), ] - peak_pos <- peak_row$pos - peak_lod <- peak_row$lod - peak_marker <- rownames(peak_row) +# 9. Missing data pattern visualization +create_missing_pattern <- function(cross) { + # Calculate missing data per individual and marker + missing_individuals <- nmissing(cross, what = "ind") + missing_markers <- nmissing(cross, what = "mar") + + # Create data frames + ind_df <- data.frame(Individual = 1:nind(cross), Missing = missing_individuals) + mar_df <- data.frame(Marker = 1:totmar(cross), Missing = missing_markers) + + p1 <- ggplot(ind_df, aes(x = Individual, y = Missing)) + + geom_bar(stat = "identity", fill = "steelblue", alpha = 0.7) + + labs(title = "Missing Data per Individual", + x = "Individual Index", y = "Number of Missing Markers") + + theme_minimal() + + p2 <- ggplot(mar_df, aes(x = Marker, y = Missing)) + + geom_bar(stat = "identity", fill = "darkorange", alpha = 0.7) + + labs(title = "Missing Data per Marker", + x = "Marker Index", y = "Number of Missing Individuals") + + theme_minimal() + + return(plot_grid(p1, p2, ncol = 2)) +} - ci <- tryCatch(lodint(sc, chr = ch, drop = 1.5), error = function(e) NULL) - left_marker <- if (!is.null(ci)) rownames(ci)[1] else NA_character_ - right_marker <- if (!is.null(ci)) rownames(ci)[nrow(ci)] else NA_character_ - left_pos <- if (!is.null(ci)) ci$pos[1] else NA_real_ - right_pos <- if (!is.null(ci)) ci$pos[nrow(ci)] else NA_real_ +# 10. QTL effect size volcano plot +create_volcano_plot <- function(scan, qtls) { + df <- as.data.frame(scan) + df$marker <- rownames(df) + + # Calculate effect size proxy (LOD / position) + df$effect_size <- df$lod / (df$pos + 1) + df$is_qtl <- df$marker %in% qtls$Marker + + ggplot(df, aes(x = effect_size, y = -log10(1 - lod/max(lod, na.rm = TRUE) + 0.001), + color = is_qtl, label = ifelse(is_qtl, marker, ""))) + + geom_point(alpha = 0.6, size = 2) + + geom_text_repel(size = 3, max.overlaps = 20) + + scale_color_manual(values = c("FALSE" = "gray", "TRUE" = "red")) + + labs(title = "QTL Effect Size Volcano Plot", + x = "Effect Size (LOD/Position)", + y = "-log10(p-value proxy)") + + theme_minimal() + + theme(legend.position = "none") +} - n <- nind(cross) - pve <- round((1 - 10^(-2 * peak_lod / n)) * 100, 2) +# 11. Haplotype visualization +create_haplotype_plot <- function(cross, chr_name, start_pos = NULL, end_pos = NULL) { + # Get chromosome data + chr_data <- cross$geno[[as.character(chr_name)]] + + if (is.null(start_pos)) start_pos <- min(chr_data$map) + if (is.null(end_pos)) end_pos <- max(chr_data$map) + + # Select markers in region + marker_idx <- which(chr_data$map >= start_pos & chr_data$map <= end_pos) + markers <- names(chr_data$map)[marker_idx] + + if (length(markers) == 0) return(NULL) + + # Extract genotypes + genotypes <- chr_data$data[, markers, drop = FALSE] + + # Create heatmap + pheatmap(genotypes, + color = c("white", "lightblue", "blue", "darkblue"), + cluster_rows = TRUE, + cluster_cols = FALSE, + show_rownames = FALSE, + main = paste("Haplotype Map - Chromosome", chr_name), + xlab = "Markers", ylab = "Individuals") +} - rows[[length(rows) + 1]] <- data.frame( - Model = mdl, - Chr = as.character(ch), - Peak_Marker = peak_marker, - Peak_pos_cM = round(peak_pos, 2), - LOD = round(peak_lod, 3), - PVE_pct = pve, - Left_Marker = left_marker, - Left_pos_cM = round(left_pos, 2), - Right_Marker = right_marker, - Right_pos_cM = round(right_pos, 2), - CI_width_cM = round(right_pos - left_pos, 2), - stringsAsFactors = FALSE - ) - } - } - if (length(rows) == 0) return(data.frame()) - dplyr::bind_rows(rows) %>% dplyr::arrange(Chr, Peak_pos_cM) +# 12. Interactive parallel coordinates for multiple traits +create_parallel_coordinates <- function(cross, traits = NULL) { + if (is.null(traits)) traits <- names(cross$pheno) + if (length(traits) < 2) return(NULL) + + # Prepare data + plot_data <- cross$pheno[, traits, drop = FALSE] + plot_data$ID <- rownames(plot_data) + + # Normalize data + plot_data_norm <- plot_data + for (trait in traits) { + plot_data_norm[[trait]] <- scale(plot_data[[trait]]) } + + # Create parallel coordinates plot + plot_ly(type = 'parcoords', + line = list(color = ~1:nrow(plot_data_norm), + colorscale = 'Viridis'), + dimensions = lapply(traits, function(trait) { + list(label = trait, + values = plot_data_norm[[trait]], + range = c(-3, 3)) + })) %>% + layout(title = "Multi-trait Parallel Coordinates Plot") +} - output$status_text <- renderText("Upload CSV files to begin") - - # ══════════════════════════════════════════════════════════════════════════ - # TAB RENDERERS - # ══════════════════════════════════════════════════════════════════════════ - - output$overview_content <- renderUI({ - cross <- cross_data() - if (is.null(cross)) return(empty_state_ui()) - tagList( - div(class = "stat-row", - div(class = "stat-chip blue", paste0(totmar(cross), " MARKERS")), - div(class = "stat-chip orange", paste0(nind(cross), " INDIVIDUALS")), - div(class = "stat-chip green", paste0(nchr(cross), " CHROMOSOMES")), - div(class = "stat-chip pink", uiOutput("stat_qtls_inline")) +# ============================================================================ +# UI COMPONENTS +# ============================================================================ + +ui <- dashboardPage( + dashboardHeader(title = "Advanced QTL Analysis Pipeline", titleWidth = 350), + + dashboardSidebar(width = 350, + sidebarMenu( + menuItem("Data Input", tabName = "data", icon = icon("upload")), + menuItem("QTL Analysis", tabName = "analysis", icon = icon("chart-line")), + menuItem("Visualizations", tabName = "visualizations", icon = icon("chart-bar"), + menuSubItem("Manhattan Plots", tabName = "manhattan"), + menuSubItem("Genome Views", tabName = "genome"), + menuSubItem("Interaction Maps", tabName = "interactions"), + menuSubItem("Comparative Plots", tabName = "comparative"), + menuSubItem("Quality Control", tabName = "qc") ), - div(class = "grid-2", - div(class = "plot-card", - div(class = "plot-card-header", - div(class = "plot-card-icon blue", "📊"), - div(div(class = "plot-card-title", "GENOME MAP"), - div(class = "plot-card-subtitle", "Marker distribution per chromosome")) - ), - div(class = "plot-card-body", - plotOutput("plot_genome_map", height = "320px") %>% withSpinner(color = "#1a6cf5", type = 4)) + menuItem("Results", tabName = "results", icon = icon("table")), + menuItem("Reports", tabName = "reports", icon = icon("file-alt")) + ), + + # Input controls + div(style = "padding: 15px;", + h4("Data Upload", style = "color: #3c8dbc;"), + fileInput("geno_file", "Genotype CSV", accept = ".csv"), + fileInput("pheno_file", "Phenotype CSV", accept = ".csv"), + + selectInput("cross_type", "Cross Type", + choices = c("F2 Intercross" = "f2", "Backcross" = "bc", + "RIL (Selfing)" = "riself", "RIL (Sib-mating)" = "risib"), + selected = "f2"), + + hr(), + + h4("Analysis Parameters", style = "color: #3c8dbc;"), + selectInput("pheno_trait", "Phenotype Trait", choices = NULL), + + selectInput("scan_methods", "Mapping Methods", + choices = c("Haley-Knott" = "hk", "EM" = "em", + "Imputation" = "imp", "Marker Regression" = "mr"), + selected = c("hk", "em"), multiple = TRUE), + + numericInput("lod_threshold", "LOD Threshold", value = 3.0, min = 0, max = 20, step = 0.5), + numericInput("n_permutations", "Permutations", value = 1000, min = 0, max = 10000), + + checkboxInput("run_cim", "Composite Interval Mapping", value = TRUE), + checkboxInput("run_epistasis", "Epistasis Detection", value = TRUE), + checkboxInput("run_mqm", "Multiple QTL Mapping", value = TRUE), + + actionButton("run_analysis", "RUN ANALYSIS", + icon = icon("play"), + style = "background-color: #3c8dbc; color: white; width: 100%; margin-top: 20px;"), + + downloadButton("download_results", "Download Results", + style = "width: 100%; margin-top: 10px;") + ) + ), + + dashboardBody( + useShinyjs(), + tags$head( + tags$style(HTML(" + .content-wrapper, .right-side { + background-color: #f4f4f4; + } + .box { + border-radius: 10px; + box-shadow: 0 2px 10px rgba(0,0,0,0.1); + } + .btn-custom { + margin: 5px; + } + ")) + ), + + tabItems( + # Data Input Tab + tabItem(tabName = "data", + fluidRow( + box(title = "Data Summary", status = "primary", solidHeader = TRUE, width = 12, + verbatimTextOutput("data_summary") + ) ), - div(class = "plot-card", - div(class = "plot-card-header", - div(class = "plot-card-icon orange", "📈"), - div(div(class = "plot-card-title", "PHENOTYPE DIST"), - div(class = "plot-card-subtitle", "Histogram + Q-Q plot")) + fluidRow( + box(title = "Genotype Preview", status = "info", width = 6, + DTOutput("geno_preview") %>% withSpinner() ), - div(class = "plot-card-body", - plotOutput("plot_pheno_dist", height = "320px") %>% withSpinner(color = "#e8500a", type = 4)) + box(title = "Phenotype Preview", status = "info", width = 6, + DTOutput("pheno_preview") %>% withSpinner() + ) + ), + fluidRow( + box(title = "Quality Control Metrics", status = "warning", width = 12, + plotOutput("qc_metrics", height = "400px") %>% withSpinner() + ) ) ), - div(class = "plot-card", - div(class = "plot-card-header", - div(class = "plot-card-icon green", "🗺"), - div(div(class = "plot-card-title", "PHYSICAL MAP"), - div(class = "plot-card-subtitle", "All chromosomes — marker positions")) + + # Analysis Tab + tabItem(tabName = "analysis", + fluidRow( + box(title = "Analysis Progress", status = "primary", solidHeader = TRUE, width = 12, + verbatimTextOutput("analysis_status") + ) ), - div(class = "plot-card-body", - plotOutput("plot_physical_map", height = "260px") %>% withSpinner(color = "#18a058", type = 4)) - ) - ) - }) - - output$stat_qtls_inline <- renderUI({ - res <- analysis_results() - n <- if (!is.null(res) && !is.null(res$qtl_table)) nrow(res$qtl_table) else 0 - paste0(n, " QTLs FOUND") - }) - - output$manhattan_content <- renderUI({ - res <- analysis_results() - if (is.null(res)) return(empty_state_ui("🌃", "Run Analysis First", - "Upload your CSV files and click RUN ANALYSIS to generate the Manhattan plot.")) - tagList( - div(class = "info-box", - "Manhattan plot shows LOD score across all chromosomes. Red diamonds = significant QTLs above threshold."), - div(class = "plot-card", - div(class = "plot-card-header", - div(class = "plot-card-icon blue", "🌃"), - div(div(class = "plot-card-title", "MANHATTAN PLOT"), - div(class = "plot-card-subtitle", "LOD scores genome-wide")) + fluidRow( + box(title = "QTL Detection Summary", status = "success", width = 12, + DTOutput("qtl_summary") %>% withSpinner() + ) ), - div(class = "plot-card-body", - div(style = "max-width:200px; margin-bottom:12px;", - selectInput("manhattan_model", "Model:", choices = names(res$scan_results)) - ), - plotOutput("plot_manhattan", height = "420px") %>% withSpinner(color = "#1a6cf5", type = 4) + fluidRow( + box(title = "Method Comparison", status = "info", width = 12, + plotOutput("method_comparison", height = "500px") %>% withSpinner() + ) ) ), - div(class = "plot-card", - div(class = "plot-card-header", - div(class = "plot-card-icon pink", "🎯"), - div(div(class = "plot-card-title", "INTERACTIVE MANHATTAN"), - div(class = "plot-card-subtitle", "Hover for marker details")) + + # Manhattan Plots Tab + tabItem(tabName = "manhattan", + fluidRow( + box(title = "Enhanced Manhattan Plot", status = "primary", width = 12, + plotOutput("manhattan_enhanced", height = "600px") %>% withSpinner() + ) ), - div(class = "plot-card-body", - plotlyOutput("plot_manhattan_interactive", height = "380px") %>% withSpinner(color = "#c2185b", type = 4) + fluidRow( + box(title = "3D Interactive Manhattan", status = "info", width = 12, + plotlyOutput("manhattan_3d", height = "600px") %>% withSpinner() + ) + ), + fluidRow( + box(title = "Ridge Plot by Chromosome", status = "success", width = 12, + plotOutput("ridge_plot", height = "500px") %>% withSpinner() + ) ) - ) - ) - }) - - output$genome_content <- renderUI({ - res <- analysis_results() - if (is.null(res)) return(empty_state_ui("🔬", "Run Analysis First")) - div(class = "plot-card", - div(class = "plot-card-header", - div(class = "plot-card-icon blue", "🔬"), - div(div(class = "plot-card-title", "GENOME SCAN — ALL MODELS"), - div(class = "plot-card-subtitle", "LOD profiles overlaid")) ), - div(class = "plot-card-body", - plotOutput("plot_scan_all_models", height = "480px") %>% withSpinner(color = "#1a6cf5", type = 4)) - ) - }) - - output$chromosome_content <- renderUI({ - res <- analysis_results() - if (is.null(res)) return(empty_state_ui("📈", "Run Analysis First")) - tagList( - div(class = "info-box", "Per-chromosome LOD profiles. Red diamonds = significant QTL peaks."), - div(style = "max-width:200px; margin-bottom:16px;", - selectInput("chr_plot_model", "Model:", choices = names(res$scan_results)) - ), - plotOutput("plot_chr_grid", height = "900px") %>% withSpinner(color = "#18a058", type = 4) - ) - }) - - output$model_comp_content <- renderUI({ - res <- analysis_results() - if (is.null(res)) return(empty_state_ui("⚖️", "Run Analysis First")) - tagList( - div(class = "grid-2", - div(class = "plot-card", - div(class = "plot-card-header", - div(class = "plot-card-icon orange", "⚖️"), - div(div(class = "plot-card-title", "PEAK LOD COMPARISON"), - div(class = "plot-card-subtitle", "Max LOD per model")) - ), - div(class = "plot-card-body", - plotOutput("plot_model_bar", height = "340px") %>% withSpinner(color = "#e8500a", type = 4)) + + # Genome Views Tab + tabItem(tabName = "genome", + fluidRow( + box(title = "Circular Genome Plot", status = "primary", width = 12, + plotOutput("circular_genome", height = "700px") %>% withSpinner() + ) ), - div(class = "plot-card", - div(class = "plot-card-header", - div(class = "plot-card-icon pink", "🔷"), - div(div(class = "plot-card-title", "LOD HEATMAP"), - div(class = "plot-card-subtitle", "Top markers × models")) - ), - div(class = "plot-card-body", - plotOutput("plot_lod_heatmap", height = "340px") %>% withSpinner(color = "#c2185b", type = 4)) + fluidRow( + box(title = "Marker Density Map", status = "info", width = 12, + plotOutput("map_density", height = "500px") %>% withSpinner() + ) + ), + fluidRow( + box(title = "Haplotype Visualization", status = "success", width = 12, + selectInput("haplotype_chr", "Select Chromosome:", choices = NULL), + plotOutput("haplotype_plot", height = "600px") %>% withSpinner() + ) ) ), - div(class = "plot-card", - div(class = "plot-card-header", - div(class = "plot-card-icon blue", "📉"), - div(div(class = "plot-card-title", "MODEL CORRELATION"), - div(class = "plot-card-subtitle", "LOD score agreement across models")) + + # Interactions Tab + tabItem(tabName = "interactions", + fluidRow( + box(title = "QTL Interaction Heatmap", status = "primary", width = 12, + plotOutput("qtl_heatmap", height = "700px") %>% withSpinner() + ) ), - div(class = "plot-card-body", - plotOutput("plot_model_corr", height = "340px") %>% withSpinner(color = "#1a6cf5", type = 4)) - ) - ) - }) - - output$effects_content <- renderUI({ - res <- analysis_results() - if (is.null(res)) return(empty_state_ui("🎻", "Run Analysis First")) - qtl_choices <- if (!is.null(res$qtl_table) && nrow(res$qtl_table) > 0) - paste0(res$qtl_table$Chr, "@", res$qtl_table$Peak_Marker) else "none" - tagList( - div(class = "grid-2", - div(class = "plot-card", - div(class = "plot-card-header", - div(class = "plot-card-icon green", "🎻"), - div(div(class = "plot-card-title", "EFFECT PLOT"), - div(class = "plot-card-subtitle", "Mean phenotype per genotype class")) - ), - div(class = "plot-card-body", - div(style = "margin-bottom:10px;", - selectInput("effect_qtl", "Select QTL:", choices = qtl_choices) - ), - plotOutput("plot_effects", height = "320px") %>% withSpinner(color = "#18a058", type = 4) + fluidRow( + box(title = "Epistasis Network", status = "info", width = 12, + plotOutput("epistasis_network", height = "600px") %>% withSpinner() ) ), - div(class = "plot-card", - div(class = "plot-card-header", - div(class = "plot-card-icon orange", "📦"), - div(div(class = "plot-card-title", "PHENOTYPE × GENOTYPE"), - div(class = "plot-card-subtitle", "Violin + boxplot at peak marker")) - ), - div(class = "plot-card-body", - plotOutput("plot_pheno_geno", height = "320px") %>% withSpinner(color = "#e8500a", type = 4)) + fluidRow( + box(title = "Volcano Plot", status = "success", width = 12, + plotOutput("volcano_plot", height = "500px") %>% withSpinner() + ) ) ), - div(class = "plot-card", - div(class = "plot-card-header", - div(class = "plot-card-icon pink", "🌡"), - div(div(class = "plot-card-title", "PVE PROFILE"), - div(class = "plot-card-subtitle", "Proportion of variance explained per QTL")) + + # Comparative Plots Tab + tabItem(tabName = "comparative", + fluidRow( + box(title = "Multi-trait Correlation", status = "primary", width = 12, + plotOutput("trait_correlation", height = "600px") %>% withSpinner() + ) ), - div(class = "plot-card-body", - plotOutput("plot_pve", height = "280px") %>% withSpinner(color = "#c2185b", type = 4)) - ) - ) - }) - - output$pairwise_content <- renderUI({ - res <- analysis_results() - if (is.null(res)) return(empty_state_ui("🔲", "Run Analysis First")) - div(class = "plot-card", - div(class = "plot-card-header", - div(class = "plot-card-icon blue", "🔲"), - div(div(class = "plot-card-title", "2D GENOME SCAN"), - div(class = "plot-card-subtitle", "Pairwise LOD / epistasis (HK method)")) - ), - div(class = "plot-card-body", - plotOutput("plot_2d_scan", height = "560px") %>% withSpinner(color = "#1a6cf5", type = 4)) - ) - }) - - output$diagnostics_content <- renderUI({ - cross <- cross_data() - if (is.null(cross)) return(empty_state_ui("🔍", "No Data Loaded")) - tagList( - div(class = "grid-2", - div(class = "plot-card", - div(class = "plot-card-header", - div(class = "plot-card-icon orange", "🔍"), - div(div(class = "plot-card-title", "MISSING DATA"), - div(class = "plot-card-subtitle", "Genotype completeness per marker")) - ), - div(class = "plot-card-body", - plotOutput("plot_missing", height = "300px") %>% withSpinner(color = "#e8500a", type = 4)) + fluidRow( + box(title = "Parallel Coordinates", status = "info", width = 12, + plotlyOutput("parallel_coords", height = "600px") %>% withSpinner() + ) ), - div(class = "plot-card", - div(class = "plot-card-header", - div(class = "plot-card-icon green", "📐"), - div(div(class = "plot-card-title", "GENOTYPE FREQ"), - div(class = "plot-card-subtitle", "Allele frequency stacked per marker")) - ), - div(class = "plot-card-body", - plotOutput("plot_geno_freq", height = "300px") %>% withSpinner(color = "#18a058", type = 4)) + fluidRow( + box(title = "Effect Size Comparison", status = "success", width = 12, + plotOutput("effect_comparison", height = "500px") %>% withSpinner() + ) ) ), - div(class = "plot-card", - div(class = "plot-card-header", - div(class = "plot-card-icon pink", "🔗"), - div(div(class = "plot-card-title", "MARKER DISTANCE"), - div(class = "plot-card-subtitle", "Inter-marker spacing histogram")) + + # Quality Control Tab + tabItem(tabName = "qc", + fluidRow( + box(title = "Missing Data Patterns", status = "primary", width = 12, + plotOutput("missing_patterns", height = "500px") %>% withSpinner() + ) ), - div(class = "plot-card-body", - plotOutput("plot_marker_dist", height = "260px") %>% withSpinner(color = "#c2185b", type = 4)) - ) - ) - }) - - output$results_content <- renderUI({ - res <- analysis_results() - if (is.null(res)) return(empty_state_ui("📋", "Run Analysis First")) - div(class = "plot-card", - div(class = "plot-card-header", - div(class = "plot-card-icon blue", "📋"), - div(div(class = "plot-card-title", "QTL RESULTS TABLE"), - div(class = "plot-card-subtitle", "Peak marker, LOD, PVE, confidence interval")) + fluidRow( + box(title = "Genotype Distribution", status = "info", width = 12, + plotOutput("genotype_dist", height = "500px") %>% withSpinner() + ) + ), + fluidRow( + box(title = "Phenotype Distribution", status = "success", width = 12, + plotOutput("phenotype_dist", height = "500px") %>% withSpinner() + ) + ) ), - div(class = "plot-card-body", DTOutput("table_qtl_results")) - ) - }) - - output$summary_content <- renderUI({ - res <- analysis_results() - if (is.null(res)) return(empty_state_ui("📝", "Run Analysis First")) - tagList( - div(class = "plot-card", - div(class = "plot-card-header", - div(class = "plot-card-icon green", "📝"), - div(div(class = "plot-card-title", "MODEL SUMMARY"), - div(class = "plot-card-subtitle", "Max LOD, QTLs found, threshold")) + + # Results Tab + tabItem(tabName = "results", + fluidRow( + box(title = "Significant QTLs", status = "primary", width = 12, + DTOutput("significant_qtls") %>% withSpinner() + ) + ), + fluidRow( + box(title = "QTL Effects", status = "info", width = 12, + DTOutput("qtl_effects") %>% withSpinner() + ) ), - div(class = "plot-card-body", DTOutput("table_model_summary")) + fluidRow( + box(title = "Permutation Thresholds", status = "success", width = 12, + DTOutput("permutation_results") %>% withSpinner() + ) + ) ), - div(class = "plot-card", style = "margin-top:20px;", - div(class = "plot-card-header", - div(class = "plot-card-icon orange", "🏆"), - div(div(class = "plot-card-title", "PERMUTATION THRESHOLDS"), - div(class = "plot-card-subtitle", "Significance levels per model")) + + # Reports Tab + tabItem(tabName = "reports", + fluidRow( + box(title = "Analysis Report", status = "primary", width = 12, + uiOutput("report_content") + ) ), - div(class = "plot-card-body", DTOutput("table_perm_thresholds")) + fluidRow( + box(title = "Download Options", status = "info", width = 12, + downloadButton("download_report_pdf", "Download PDF Report", class = "btn-custom"), + downloadButton("download_report_html", "Download HTML Report", class = "btn-custom"), + downloadButton("download_all_plots", "Download All Plots", class = "btn-custom") + ) + ) ) ) - }) - - # ══════════════════════════════════════════════════════════════════════════ - # PLOTS - # ═════════════════════���════════════════════════════════════════════════════ - - output$plot_genome_map <- renderPlot({ - cross <- cross_data(); req(cross) - map <- pull.map(cross) - df <- do.call(rbind, lapply(names(map), function(ch) { - data.frame(chr = ch, pos = unname(map[[ch]]), stringsAsFactors = FALSE) - })) - df$chr <- factor(df$chr, levels = names(map)) - ggplot(df, aes(x = chr, y = pos)) + - geom_segment(aes(xend = chr, yend = pos), color = "#dde2ea", linewidth = 8) + - geom_point(color = "#1a6cf5", size = 1.5, alpha = .8) + - scale_y_reverse() + - labs(title = "Genetic Map", x = "Chromosome", y = "Position (cM)") + theme_qtl() - }, bg = "white") - - output$plot_pheno_dist <- renderPlot({ - cross <- cross_data(); req(cross, input$pheno_col) - ph <- cross$pheno[[input$pheno_col]] - df <- data.frame(value = ph[!is.na(ph)]) - p1 <- ggplot(df, aes(value)) + - geom_histogram(fill = "#1a6cf5", color = "#ffffff", bins = 30, alpha = .8) + - labs(title = input$pheno_col, x = "Value", y = "Count") + theme_qtl() - p2 <- ggplot(df, aes(sample = value)) + - stat_qq(color = "#18a058", size = 1.5, alpha = .8) + - stat_qq_line(color = "#c2185b", linewidth = .8) + - labs(title = "Q-Q Plot", x = "Theoretical", y = "Sample") + theme_qtl() - gridExtra::grid.arrange(p1, p2, ncol = 2) - }, bg = "white") - - output$plot_physical_map <- renderPlot({ - cross <- cross_data(); req(cross) - map <- pull.map(cross) - df <- do.call(rbind, lapply(names(map), function(ch) - data.frame(chr = ch, pos = unname(map[[ch]]), stringsAsFactors = FALSE))) - chr_len <- df %>% group_by(chr) %>% summarise(len = max(pos), .groups="drop") - chr_len$chr <- factor(chr_len$chr, levels = names(map)) - df$chr <- factor(df$chr, levels = names(map)) - ggplot() + - geom_rect(data = chr_len, - aes(xmin = as.numeric(chr)-.35, xmax = as.numeric(chr)+.35, ymin = 0, ymax = len), - fill = "#e8ecf2", color = "#c8d0dc", linewidth = .7) + - geom_point(data = df, aes(x = as.numeric(chr), y = pos), - color = "#1a6cf5", size = 1, alpha = .7) + - scale_x_continuous(breaks = seq_along(names(map)), labels = names(map)) + - scale_y_reverse() + - labs(title = "Physical Map Overview", x = "Chromosome", y = "cM") + theme_qtl() - }, bg = "white") - - output$plot_manhattan <- renderPlot({ - res <- analysis_results(); req(res) - mdl <- input$manhattan_model; req(mdl) - sc <- res$scan_results[[mdl]]; req(sc) - chrs <- unique(sc$chr) - chr_offsets <- setNames(cumsum(c(0, sapply(chrs[-length(chrs)], function(ch) max(sc[sc$chr==ch,"pos"])))), chrs) - sc$global_pos <- sc$pos + chr_offsets[as.character(sc$chr)] - sc$chr_num <- as.integer(factor(sc$chr, levels = chrs)) - sc$color <- ifelse(sc$chr_num %% 2 == 0, "#1a6cf5", "#5b9cf5") - sig <- sc[sc$lod >= res$lod_thr, ] - chr_mid <- tapply(sc$global_pos, sc$chr, mean) - ggplot(sc, aes(x = global_pos, y = lod)) + - geom_point(aes(color = color), size = 1.2, alpha = .75) + - scale_color_identity() + - geom_point(data = sig, aes(x = global_pos, y = lod), color = "#c2185b", size = 2.5, shape = 18) + - geom_hline(yintercept = res$lod_thr, color = "#e8500a", linetype = "dashed", linewidth = .8) + - scale_x_continuous(breaks = chr_mid, labels = names(chr_mid)) + - labs(title = paste("Manhattan —", toupper(mdl)), x = "Chromosome", y = "LOD Score") + - theme_qtl() + theme(panel.grid.major.x = element_blank()) - }, bg = "white") + ) +) - output$plot_manhattan_interactive <- renderPlotly({ - res <- analysis_results(); req(res) - mdl <- input$manhattan_model; req(mdl) - sc <- res$scan_results[[mdl]]; req(sc) - chrs <- unique(sc$chr) - chr_offsets <- setNames(cumsum(c(0, sapply(chrs[-length(chrs)], function(ch) max(sc[sc$chr==ch,"pos"])))), chrs) - sc$global_pos <- sc$pos + chr_offsets[as.character(sc$chr)] - sc$sig <- sc$lod >= res$lod_thr - sc$label <- paste0(rownames(sc), "
Chr:", sc$chr, " Pos:", round(sc$pos,1), " LOD:", round(sc$lod,2)) - plot_ly(sc, x = ~global_pos, y = ~lod, color = ~sig, colors = c("#1a6cf5","#c2185b"), - text = ~label, hovertemplate = "%{text}", - type = "scatter", mode = "markers", marker = list(size = 4, opacity = .8)) %>% - add_lines(y = res$lod_thr, line = list(color="#e8500a", dash="dash", width=1.5), - showlegend = FALSE, name = "Threshold") %>% - layout(paper_bgcolor="#ffffff", plot_bgcolor="#f8f9fb", - font = list(color="#4a5568", family="monospace"), - xaxis = list(title="Position", gridcolor="#e8ecf2"), - yaxis = list(title="LOD Score", gridcolor="#e8ecf2"), - margin = list(t=10,b=40,l=50,r=20)) - }) +# ============================================================================ +# SERVER LOGIC +# ============================================================================ - output$plot_scan_all_models <- renderPlot({ - res <- analysis_results(); req(res, length(res$scan_results) > 0) - dfs <- lapply(names(res$scan_results), function(mdl) { - sc <- res$scan_results[[mdl]] - chrs <- unique(sc$chr) - offsets <- setNames(cumsum(c(0, sapply(chrs[-length(chrs)], function(ch) max(sc[sc$chr==ch,"pos"])))), chrs) - sc$global_pos <- sc$pos + offsets[as.character(sc$chr)] - sc$model <- mdl; sc +server <- function(input, output, session) { + + # Reactive values for storing results + cross_data <- reactiveVal(NULL) + scan_results <- reactiveVal(NULL) + cim_results <- reactiveVal(NULL) + mqm_results <- reactiveVal(NULL) + epistasis_results <- reactiveVal(NULL) + qtl_table <- reactiveVal(NULL) + permutation_results <- reactiveVal(NULL) + analysis_complete <- reactiveVal(FALSE) + + # Load data + observeEvent(c(input$geno_file, input$pheno_file), { + req(input$geno_file, input$pheno_file) + + showNotification("Loading and parsing data...", type = "info", duration = 3) + + tryCatch({ + cross <- parse_advanced_cross( + input$geno_file$datapath, + input$pheno_file$datapath, + input$cross_type + ) + + cross_data(cross) + + # Update UI choices + updateSelectInput(session, "pheno_trait", + choices = names(cross$pheno), + selected = names(cross$pheno)[1]) + + updateSelectInput(session, "haplotype_chr", + choices = names(cross$geno)) + + showNotification("Data loaded successfully!", type = "success", duration = 3) + + }, error = function(e) { + showNotification(paste("Error loading data:", e$message), type = "error", duration = 10) }) - df_all <- dplyr::bind_rows(dfs) - sc_ref <- res$scan_results[[1]] - chrs <- unique(sc_ref$chr) - offsets <- setNames(cumsum(c(0, sapply(chrs[-length(chrs)], function(ch) max(sc_ref[sc_ref$chr==ch,"pos"])))), chrs) - vlines <- data.frame(x = offsets[-1]) - ggplot(df_all, aes(x = global_pos, y = lod, color = model)) + - geom_vline(data = vlines, aes(xintercept = x), color = "#e8ecf2", linewidth = .5) + - geom_line(linewidth = .6, alpha = .85) + - geom_hline(yintercept = res$lod_thr, color = "#e8500a", linetype = "dashed", linewidth = .7) + - scale_color_manual(values = model_colors) + - labs(title = "Genome Scan — All Models", x = "Genome Position (cM)", y = "LOD Score", color = "Model") + - theme_qtl() + theme(legend.position = "right") - }, bg = "white") - - output$plot_chr_grid <- renderPlot({ - res <- analysis_results(); req(res) - mdl <- input$chr_plot_model; req(mdl) - sc <- res$scan_results[[mdl]]; req(sc) - qt <- res$qtl_table - chrs <- unique(sc$chr) - n_cols <- min(4, length(chrs)); n_rows <- ceiling(length(chrs)/n_cols) - plots <- lapply(chrs, function(ch) { - chr_sc <- sc[sc$chr == ch, ] - p <- ggplot(chr_sc, aes(x = pos, y = lod)) + - geom_line(color = "#1a6cf5", linewidth = .9) + - geom_hline(yintercept = res$lod_thr, color = "#e8500a", linetype = "dashed", linewidth = .6) + - scale_y_continuous(limits = c(0, max(sc$lod) * 1.1)) + - labs(title = paste0("Chr ", ch), x = NULL, y = "LOD") + - theme_qtl(base_size = 9) + theme(plot.margin = margin(6,8,6,8)) - if (!is.null(qt) && nrow(qt) > 0) { - qt_chr <- qt[qt$Chr == ch & qt$Model == mdl, ] - if (nrow(qt_chr) > 0) - p <- p + geom_point(data = qt_chr, aes(x = Peak_pos_cM, y = LOD), - color = "#c2185b", size = 3, shape = 23, fill = "#c2185b") + }) + + # Run analysis + observeEvent(input$run_analysis, { + cross <- cross_data() + req(cross, input$pheno_trait) + + showNotification("Starting QTL analysis...", type = "info", duration = 5) + + withProgress(message = "Running QTL Analysis", value = 0, { + + # Run multiple scan methods + incProgress(0.2, detail = "Running genome scans...") + pheno_idx <- which(names(cross$pheno) == input$pheno_trait) + scans <- run_multiple_scans(cross, pheno_idx, methods = input$scan_methods) + scan_results(scans) + + # Run CIM + if (input$run_cim) { + incProgress(0.2, detail = "Running Composite Interval Mapping...") + cim <- run_cim(cross, pheno_idx) + cim_results(cim) } - p - }) - do.call(gridExtra::grid.arrange, c(plots, list(ncol = n_cols, nrow = n_rows))) - }, bg = "white") - - output$plot_model_bar <- renderPlot({ - res <- analysis_results(); req(res) - df <- data.frame(model = names(res$scan_results), - max_lod = sapply(res$scan_results, function(sc) max(sc$lod, na.rm=TRUE))) - df$model <- factor(df$model, levels = df$model[order(df$max_lod)]) - ggplot(df, aes(x = model, y = max_lod, fill = model)) + - geom_col(width = .6, alpha = .85) + - geom_hline(yintercept = res$lod_thr, color = "#e8500a", linetype = "dashed", linewidth = .8) + - geom_text(aes(label = round(max_lod, 2)), hjust = -0.2, color = "#1a202c", size = 3, family = "mono") + - scale_fill_manual(values = model_colors) + - coord_flip(ylim = c(0, max(df$max_lod) * 1.15)) + - labs(title = "Peak LOD by Model", x = NULL, y = "Max LOD") + - theme_qtl() + theme(legend.position = "none") - }, bg = "white") - - output$plot_lod_heatmap <- renderPlot({ - res <- analysis_results(); req(res) - all_sc <- dplyr::bind_rows(lapply(names(res$scan_results), function(m) { - sc <- res$scan_results[[m]]; sc$model <- m; sc$marker <- rownames(sc); sc - })) - top_markers <- all_sc %>% group_by(marker) %>% summarise(max_lod = max(lod), .groups="drop") %>% - arrange(desc(max_lod)) %>% slice_head(n = 40) %>% pull(marker) - hm <- all_sc %>% filter(marker %in% top_markers) %>% select(model, marker, lod) - ggplot(hm, aes(x = model, y = marker, fill = lod)) + - geom_tile(color = "#f8f9fb", linewidth = .3) + - scale_fill_gradientn(colors = c("#f8f9fb","#bcd0fc","#1a6cf5","#18a058","#c2185b"), name = "LOD") + - labs(title = "LOD Heatmap", x = "Model", y = "Marker") + - theme_qtl() + theme(axis.text.x = element_text(angle=30, hjust=1), axis.text.y = element_text(size=6)) - }, bg = "white") - - output$plot_model_corr <- renderPlot({ - res <- analysis_results(); req(res, length(res$scan_results) >= 2) - sc_list <- lapply(names(res$scan_results), function(m) { - sc <- res$scan_results[[m]] - data.frame(marker = rownames(sc), lod = sc$lod, stringsAsFactors = FALSE) + + # Run MQM + if (input$run_mqm) { + incProgress(0.2, detail = "Running Multiple QTL Mapping...") + mqm <- run_mqm(cross, pheno_idx) + mqm_results(mqm) + } + + # Detect epistasis + if (input$run_epistasis) { + incProgress(0.2, detail = "Detecting epistatic interactions...") + epi <- detect_epistasis(cross, pheno_idx, threshold = input$lod_threshold) + epistasis_results(epi) + } + + # Run permutations + if (input$n_permutations > 0) { + incProgress(0.1, detail = "Running permutation tests...") + perms <- run_permutation_test(cross, pheno_idx, n_perm = input$n_permutations) + permutation_results(perms) + } + + # Identify QTLs + incProgress(0.1, detail = "Identifying significant QTLs...") + best_scan <- scans[[1]] # Use first method for initial QTL detection + if (!is.null(best_scan)) { + qtls <- find_qtls(best_scan, input$lod_threshold) + qtl_table(qtls) + } + + analysis_complete(TRUE) + showNotification("Analysis complete!", type = "success", duration = 5) }) - names(sc_list) <- names(res$scan_results) - common_markers <- Reduce(intersect, lapply(sc_list, `[[`, "marker")) - mat <- sapply(sc_list, function(sc) sc$lod[match(common_markers, sc$marker)]) - corr_mat <- cor(mat, use = "complete.obs") - corr_df <- as.data.frame(as.table(corr_mat)); names(corr_df) <- c("m1","m2","corr") - ggplot(corr_df, aes(x = m1, y = m2, fill = corr)) + - geom_tile(color = "#ffffff", linewidth = .5) + - geom_text(aes(label = round(corr,2)), size = 3, color = "#1a202c", family = "mono") + - scale_fill_gradient2(low="#c2185b", mid="#f1f4f8", high="#1a6cf5", midpoint=0, limits=c(-1,1), name="r") + - labs(title = "Model LOD Correlation", x = NULL, y = NULL) + - theme_qtl() + theme(axis.text.x = element_text(angle=30, hjust=1)) - }, bg = "white") - - output$plot_effects <- renderPlot({ - res <- analysis_results(); req(res) - qtl_sel <- input$effect_qtl; req(qtl_sel, qtl_sel != "none") - parts <- strsplit(qtl_sel, "@")[[1]]; mk <- parts[2] - tryCatch({ - eff <- effectplot(res$cross, mname1 = mk, pheno.col = res$pheno_idx, draw = FALSE) - df <- data.frame(geno = names(eff$Means), mean = eff$Means, se = eff$SEs) - ggplot(df, aes(x = geno, y = mean, fill = geno)) + - geom_col(width = .5, alpha = .85) + - geom_errorbar(aes(ymin = mean-se, ymax = mean+se), width = .15, color = "#4a5568", linewidth = .8) + - scale_fill_manual(values = c("#1a6cf5","#c2185b","#18a058","#e8500a")) + - labs(title = paste("Effect Plot —", mk), x = "Genotype", y = "Mean Phenotype") + - theme_qtl() + theme(legend.position = "none") - }, error = function(e) - ggplot() + annotate("text",x=.5,y=.5,label=paste("Effect not available:", e$message),color="#8a95a3",size=4) + theme_qtl() - ) - }, bg = "white") - - output$plot_pheno_geno <- renderPlot({ - res <- analysis_results(); req(res) - qtl_sel <- input$effect_qtl; req(qtl_sel != "none") - parts <- strsplit(qtl_sel, "@")[[1]]; mk <- parts[2] - tryCatch({ - geno_idx <- find.markerindex(res$cross, mk) - geno_vec <- pull.geno(res$cross)[, geno_idx] - pheno_vec <- res$cross$pheno[[res$pheno_idx]] - df <- data.frame(geno = as.character(geno_vec), pheno = pheno_vec) %>% - filter(!is.na(geno), !is.na(pheno)) - geno_labs <- c("1" = "AA", "2" = "AB", "3" = "BB") - df$geno <- dplyr::recode(df$geno, !!!geno_labs) - ggplot(df, aes(x = geno, y = pheno, fill = geno)) + - geom_violin(alpha = .4, trim = FALSE) + - geom_boxplot(width = .15, outlier.color = "#c2185b", alpha = .7) + - scale_fill_manual(values = c("#1a6cf5","#e8500a","#18a058")) + - labs(title = paste("Phenotype by Genotype —", mk), x = "Genotype", y = input$pheno_col) + - theme_qtl() + theme(legend.position = "none") - }, error = function(e) - ggplot() + annotate("text",x=.5,y=.5,label=paste("Unavailable:", e$message),color="#8a95a3",size=4) + theme_qtl() - ) - }, bg = "white") - - output$plot_pve <- renderPlot({ - res <- analysis_results(); req(res) - qt <- res$qtl_table; req(!is.null(qt) && nrow(qt) > 0) - qt_avg <- qt %>% group_by(Chr, Peak_pos_cM) %>% - summarise(PVE = mean(PVE_pct, na.rm=TRUE), .groups="drop") - ggplot(qt_avg, aes(x = interaction(Chr, round(Peak_pos_cM)), y = PVE, fill = PVE)) + - geom_col(width = .7) + - scale_fill_gradientn(colors = c("#bcd0fc","#1a6cf5","#18a058","#c2185b"), name = "PVE%") + - geom_text(aes(label = paste0(round(PVE,1),"%")), vjust = -0.4, size = 3, color = "#1a202c", family = "mono") + - labs(title = "PVE per QTL", x = "Chr @ Position", y = "PVE (%)") + - theme_qtl() + theme(axis.text.x = element_text(angle=40, hjust=1)) - }, bg = "white") - - output$plot_2d_scan <- renderPlot({ - res <- analysis_results(); req(res) - sc2 <- tryCatch( - scantwo(res$cross, pheno.col = res$pheno_idx, method = "hk", verbose = FALSE), - error = function(e) NULL - ) - if (is.null(sc2)) { - ggplot() + annotate("text",x=.5,y=.5,label="2D scan failed or insufficient data",color="#8a95a3",size=5) + theme_qtl() - } else { - lod_mat <- sc2$lod; n <- nrow(lod_mat) - df2d <- expand.grid(x=1:n, y=1:n); df2d$lod <- as.vector(lod_mat) - ggplot(df2d, aes(x=x,y=y,fill=lod)) + - geom_tile() + - scale_fill_gradientn(colors=c("#f8f9fb","#bcd0fc","#1a6cf5","#18a058","#c2185b"), name="LOD", na.value="#f8f9fb") + - labs(title="2D Genome Scan (Pairwise)", x="Position 1", y="Position 2") + - theme_qtl() + coord_equal() + }) + + # ========================================================================== + # RENDER FUNCTIONS FOR EACH TAB + # ========================================================================== + + # Data summary + output$data_summary <- renderPrint({ + cross <- cross_data() + if (is.null(cross)) return("No data loaded. Please upload CSV files.") + + cat("=== QTL DATA SUMMARY ===\n\n") + cat("Cross Type:", class(cross)[1], "\n") + cat("Individuals:", nind(cross), "\n") + cat("Markers:", totmar(cross), "\n") + cat("Chromosomes:", nchr(cross), "\n") + cat("Phenotypes:", paste(names(cross$pheno), collapse = ", "), "\n") + cat("\nMissing Data Rate:", round(attr(cross, "summary")$missing_rate * 100, 2), "%\n") + cat("Heterozygosity:", round(attr(cross, "summary")$heterozygosity, 4), "\n") + }) + + # Data previews + output$geno_preview <- renderDT({ + cross <- cross_data() + req(cross) + + # Get first few markers and individuals + geno_preview <- cross$geno[[1]]$data[1:min(10, nind(cross)), 1:min(10, totmar(cross))] + datatable(geno_preview, options = list(scrollX = TRUE, pageLength = 5)) + }) + + output$pheno_preview <- renderDT({ + cross <- cross_data() + req(cross) + + datatable(cross$pheno[1:min(20, nind(cross)), , drop = FALSE], + options = list(scrollX = TRUE, pageLength = 5)) + }) + + # QC metrics plot + output$qc_metrics <- renderPlot({ + cross <- cross_data() + req(cross) + + # Calculate various QC metrics + missing_ind <- nmissing(cross, what = "ind") + missing_mar <- nmissing(cross, what = "mar") + heterozyg <- calc.heterozyg(cross) + + # Create multi-panel plot + p1 <- ggplot(data.frame(Missing = missing_ind), aes(x = Missing)) + + geom_histogram(bins = 30, fill = "steelblue", alpha = 0.7) + + labs(title = "Missing Data per Individual", x = "Number Missing", y = "Count") + + theme_minimal() + + p2 <- ggplot(data.frame(Missing = missing_mar), aes(x = Missing)) + + geom_histogram(bins = 30, fill = "darkorange", alpha = 0.7) + + labs(title = "Missing Data per Marker", x = "Number Missing", y = "Count") + + theme_minimal() + + p3 <- ggplot(data.frame(Heterozygosity = heterozyg), aes(x = Heterozygosity)) + + geom_histogram(bins = 30, fill = "forestgreen", alpha = 0.7) + + labs(title = "Heterozygosity Distribution", x = "Heterozygosity", y = "Count") + + theme_minimal() + + plot_grid(p1, p2, p3, ncol = 3) + }, height = 400) + + # QTL summary table + output$qtl_summary <- renderDT({ + qtls <- qtl_table() + req(qtls, nrow(qtls) > 0) + + datatable(qtls, + options = list(pageLength = 10, scrollX = TRUE), + rownames = FALSE) %>% + formatStyle("LOD", + background = styleColorBar(range(qtls$LOD), "lightblue")) + }) + + # Method comparison plot + output$method_comparison <- renderPlot({ + scans <- scan_results() + qtls <- qtl_table() + req(scans) + + create_method_comparison(scans, qtls) + }, height = 500) + + # Enhanced Manhattan plot + output$manhattan_enhanced <- renderPlot({ + scans <- scan_results() + qtls <- qtl_table() + req(scans) + + create_manhattan_enhanced(scans[[1]], input$lod_threshold, qtls) + }, height = 600) + + # 3D Manhattan plot + output$manhattan_3d <- renderPlotly({ + scans <- scan_results() + req(scans) + + create_manhattan_3d(scans[[1]], input$lod_threshold) + }, height = 600) + + # Ridge plot + output$ridge_plot <- renderPlot({ + scans <- scan_results() + req(scans) + + create_ridge_plot(scans[[1]]) + }, height = 500) + + # Circular genome plot + output$circular_genome <- renderPlot({ + cross <- cross_data() + scans <- scan_results() + qtls <- qtl_table() + req(cross, scans) + + create_circular_genome(cross, scans[[1]], qtls) + }, height = 700) + + # Map density + output$map_density <- renderPlot({ + cross <- cross_data() + req(cross) + + create_map_density(cross) + }, height = 500) + + # Haplotype plot + output$haplotype_plot <- renderPlot({ + cross <- cross_data() + req(cross, input$haplotype_chr) + + create_haplotype_plot(cross, input$haplotype_chr) + }, height = 600) + + # QTL heatmap + output$qtl_heatmap <- renderPlot({ + epi <- epistasis_results() + req(epi, !is.null(epi$full_result)) + + create_qtl_heatmap(epi$full_result) + }, height = 700) + + # Epistasis network + output$epistasis_network <- renderPlot({ + epi <- epistasis_results() + req(epi, !is.null(epi$epistasis), nrow(epi$epistasis) > 0) + + # Create network plot + library(igraph) + edges <- epi$epistasis[, c("chr1", "chr2")] + g <- graph_from_data_frame(edges, directed = FALSE) + + plot(g, vertex.size = 20, vertex.label.cex = 0.8, + edge.width = epi$epistasis$lod / max(epi$epistasis$lod) * 5, + main = "Epistatic Interaction Network", + layout = layout_in_circle) + }, height = 600) + + # Volcano plot + output$volcano_plot <- renderPlot({ + scans <- scan_results() + qtls <- qtl_table() + req(scans) + + create_volcano_plot(scans[[1]], qtls) + }, height = 500) + + # Trait correlation + output$trait_correlation <- renderPlot({ + cross <- cross_data() + req(cross) + + create_trait_correlation(cross) + }, height = 600) + + # Parallel coordinates + output$parallel_coords <- renderPlotly({ + cross <- cross_data() + req(cross) + + create_parallel_coordinates(cross) + }, height = 600) + + # Effect comparison + output$effect_comparison <- renderPlot({ + cross <- cross_data() + qtls <- qtl_table() + req(cross, qtls, nrow(qtls) > 0) + + # Estimate effects for top QTLs + effects <- estimate_qtl_effects(cross, qtls[1:min(5, nrow(qtls)), ], + which(names(cross$pheno) == input$pheno_trait)) + + # Create effect plot + effect_df <- data.frame() + for (i in seq_along(effects)) { + effect <- effects[[i]] + temp_df <- data.frame( + QTL = paste0("QTL-", i), + Genotype = names(effect$means), + Mean = effect$means, + SE = effect$se + ) + effect_df <- rbind(effect_df, temp_df) } - }, bg = "white") - - output$plot_missing <- renderPlot({ - cross <- cross_data(); req(cross) - miss <- nmissing(cross, what = "mar") - df <- data.frame(marker = names(miss), missing = miss) - ggplot(df, aes(x = reorder(marker, missing), y = missing, fill = missing)) + - geom_col() + - scale_fill_gradientn(colors = c("#bcd0fc","#1a6cf5","#c2185b"), guide = "none") + - labs(title = "Missing Genotype Data", x = "Marker", y = "# Missing") + - theme_qtl() + theme(axis.text.x = element_blank(), axis.ticks.x = element_blank()) - }, bg = "white") - - output$plot_geno_freq <- renderPlot({ - cross <- cross_data(); req(cross) - gt <- pull.geno(cross) - freq_A <- colMeans(gt == 1, na.rm=TRUE) - freq_B <- colMeans(gt == 2, na.rm=TRUE) - df <- data.frame(marker=names(freq_A), A=freq_A, B=freq_B) %>% - tidyr::pivot_longer(cols=c(A,B), names_to="allele", values_to="freq") - ggplot(df, aes(x=marker, y=freq, fill=allele)) + - geom_col(position="stack", width=1) + - scale_fill_manual(values=c(A="#1a6cf5", B="#e8500a")) + - labs(title="Allele Frequency per Marker", x="Marker", y="Frequency") + - theme_qtl() + theme(axis.text.x=element_blank(), axis.ticks.x=element_blank()) - }, bg = "white") - - output$plot_marker_dist <- renderPlot({ - cross <- cross_data(); req(cross) - map <- pull.map(cross) - diffs <- unlist(lapply(map, function(m) if (length(m)>1) diff(m) else numeric(0))) - df <- data.frame(dist = diffs) - ggplot(df, aes(x=dist)) + - geom_histogram(fill="#1a6cf5", color="#ffffff", bins=40, alpha=.8) + - geom_vline(xintercept=median(diffs), color="#c2185b", linetype="dashed", linewidth=.8) + - labs(title="Inter-Marker Distance", subtitle=paste0("Median: ",round(median(diffs),1)," cM"), - x="Distance (cM)", y="Count") + theme_qtl() - }, bg = "white") - - # ── TABLES ──────────────────────────────────────────────────────────────── - - output$table_qtl_results <- renderDT({ - res <- analysis_results(); req(res) - qt <- res$qtl_table; req(!is.null(qt) && nrow(qt) > 0) - datatable(qt, rownames=FALSE, - options=list(pageLength=20, scrollX=TRUE, dom="Blfrtip", - columnDefs=list(list(className="dt-center", targets="_all"))), - class="display nowrap") %>% + + ggplot(effect_df, aes(x = QTL, y = Mean, fill = Genotype)) + + geom_bar(stat = "identity", position = position_dodge(0.9), alpha = 0.8) + + geom_errorbar(aes(ymin = Mean - SE, ymax = Mean + SE), + position = position_dodge(0.9), width = 0.2) + + scale_fill_brewer(palette = "Set2") + + labs(title = "QTL Effect Sizes", + x = "QTL", y = "Mean Phenotype") + + theme_minimal() + }, height = 500) + + # Missing patterns + output$missing_patterns <- renderPlot({ + cross <- cross_data() + req(cross) + + create_missing_pattern(cross) + }, height = 500) + + # Genotype distribution + output$genotype_dist <- renderPlot({ + cross <- cross_data() + req(cross) + + # Calculate genotype frequencies + geno_freq <- data.frame() + for (chr in names(cross$geno)) { + for (marker in names(cross$geno[[chr]]$map)) { + geno <- cross$geno[[chr]]$data[, marker] + freq <- table(geno, useNA = "ifany") + temp_df <- data.frame( + Chromosome = chr, + Marker = marker, + Genotype = names(freq), + Frequency = as.numeric(freq) / nind(cross) + ) + geno_freq <- rbind(geno_freq, temp_df) + } + } + + ggplot(geno_freq, aes(x = Marker, y = Frequency, fill = Genotype)) + + geom_bar(stat = "identity", position = "stack", alpha = 0.8) + + facet_wrap(~Chromosome, scales = "free_x", ncol = 3) + + scale_fill_brewer(palette = "Set1") + + labs(title = "Genotype Distribution by Marker", + x = "Marker", y = "Frequency") + + theme_minimal() + + theme(axis.text.x = element_blank(), + axis.ticks.x = element_blank()) + }, height = 500) + + # Phenotype distribution + output$phenotype_dist <- renderPlot({ + cross <- cross_data() + req(cross, input$pheno_trait) + + pheno <- cross$pheno[[input$pheno_trait]] + + p1 <- ggplot(data.frame(Phenotype = pheno), aes(x = Phenotype)) + + geom_histogram(bins = 30, fill = "steelblue", alpha = 0.7) + + labs(title = "Phenotype Distribution", + x = input$pheno_trait, y = "Count") + + theme_minimal() + + p2 <- ggplot(data.frame(Phenotype = pheno), aes(sample = Phenotype)) + + stat_qq(color = "steelblue", alpha = 0.7) + + stat_qq_line(color = "red") + + labs(title = "Q-Q Plot", x = "Theoretical", y = "Sample") + + theme_minimal() + + plot_grid(p1, p2, ncol = 2) + }, height = 500) + + # Significant QTLs table + output$significant_qtls <- renderDT({ + qtls <- qtl_table() + req(qtls, nrow(qtls) > 0) + + datatable(qtls, + options = list(pageLength = 15, scrollX = TRUE), + rownames = FALSE) %>% formatStyle("LOD", - background=styleColorBar(range(qt$LOD), "#bcd0fc"), - backgroundSize="100% 80%", backgroundRepeat="no-repeat", backgroundPosition="center") %>% - formatStyle("PVE_pct", - background=styleColorBar(c(0,100), "#b3dfc7"), - backgroundSize="100% 80%", backgroundRepeat="no-repeat", backgroundPosition="center") %>% - formatRound(c("Peak_pos_cM","LOD","PVE_pct","Left_pos_cM","Right_pos_cM","CI_width_cM"), 3) + background = styleColorBar(c(0, max(qtls$LOD, na.rm = TRUE)), "lightblue")) %>% + formatStyle("PVE_percent", + background = styleColorBar(c(0, 100), "lightgreen")) }) - - output$table_model_summary <- renderDT({ - res <- analysis_results(); req(res) - df <- data.frame( - Model = names(res$scan_results), - Max_LOD = round(sapply(res$scan_results, function(sc) max(sc$lod,na.rm=TRUE)),3), - Mean_LOD = round(sapply(res$scan_results, function(sc) mean(sc$lod,na.rm=TRUE)),3), - QTLs_Found = sapply(names(res$scan_results), function(m) - if (!is.null(res$qtl_table) && nrow(res$qtl_table)>0) sum(res$qtl_table$Model==m) else 0), - Threshold = round(res$lod_thr,3) + + # QTL effects table + output$qtl_effects <- renderDT({ + cross <- cross_data() + qtls <- qtl_table() + req(cross, qtls, nrow(qtls) > 0) + + effects <- estimate_qtl_effects(cross, qtls[1:min(10, nrow(qtls)), ], + which(names(cross$pheno) == input$pheno_trait)) + + effect_table <- data.frame() + for (i in seq_along(effects)) { + effect <- effects[[i]] + effect_table <- rbind(effect_table, + data.frame( + QTL = i, + Marker = effect$marker, + Additive_Effect = round(effect$additive, 3), + Dominance_Effect = round(effect$dominance, 3), + stringsAsFactors = FALSE + )) + } + + datatable(effect_table, options = list(pageLength = 10)) + }) + + # Permutation results table + output$permutation_results <- renderDT({ + perms <- permutation_results() + req(perms) + + threshold_df <- data.frame( + Alpha = names(perms$thresholds), + Threshold = unlist(perms$thresholds) ) - datatable(df, rownames=FALSE, options=list(dom="t", pageLength=15), class="display") %>% - formatStyle("Max_LOD", color="#1a6cf5", fontWeight="bold") %>% - formatStyle("QTLs_Found", color="#c2185b", fontWeight="bold") + + datatable(threshold_df, options = list(pageLength = 5)) }) - - output$table_perm_thresholds <- renderDT({ - res <- analysis_results(); req(res, length(res$perm_results) > 0) - rows <- lapply(names(res$perm_results), function(m) { - p <- res$perm_results[[m]]; if (is.null(p)) return(NULL) - sm <- tryCatch(summary(p, alpha=c(0.05,0.1,0.2)), error=function(e) NULL) - if (is.null(sm)) return(NULL) - data.frame(Model=m, alpha_0.05=round(sm[1],3), alpha_0.10=round(sm[2],3), alpha_0.20=round(sm[3],3)) - }) - df <- dplyr::bind_rows(Filter(Negate(is.null), rows)); req(nrow(df) > 0) - datatable(df, rownames=FALSE, options=list(dom="t"), class="display") + + # Report content + output$report_content <- renderUI({ + if (!analysis_complete()) { + return(div("Run analysis first to generate report.", + style = "padding: 20px; text-align: center;")) + } + + qtls <- qtl_table() + n_qtls <- ifelse(is.null(qtls), 0, nrow(qtls)) + + HTML(paste0(" +
+

QTL Analysis Report

+
+

Summary Statistics

+ + +

Analysis Parameters

+ + +

Next Steps

+ +
+ ")) }) - - # ── Download ────────────────────────────────────────────────────────────── + + # Download handlers output$download_results <- downloadHandler( - filename = function() paste0("qtl_results_", Sys.Date(), ".csv"), - content = function(file) { - res <- analysis_results() - if (!is.null(res) && !is.null(res$qtl_table) && nrow(res$qtl_table) > 0) - write.csv(res$qtl_table, file, row.names=FALSE) - else - write.csv(data.frame(message="No significant QTLs found"), file, row.names=FALSE) + filename = function() paste0("qtl_results_", Sys.Date(), ".zip"), + content = function(file) { + # Create temporary directory + tmpdir <- tempdir() + + # Save QTL table + qtls <- qtl_table() + if (!is.null(qtls) && nrow(qtls) > 0) { + write.csv(qtls, file.path(tmpdir, "significant_qtls.csv"), row.names = FALSE) + } + + # Save effects + cross <- cross_data() + if (!is.null(cross) && !is.null(qtls) && nrow(qtls) > 0) { + effects <- estimate_qtl_effects(cross, qtls, + which(names(cross$pheno) == input$pheno_trait)) + effects_df <- do.call(rbind, lapply(seq_along(effects), function(i) { + data.frame( + QTL = i, + Marker = effects[[i]]$marker, + Additive = effects[[i]]$additive, + Dominance = effects[[i]]$dominance + ) + })) + write.csv(effects_df, file.path(tmpdir, "qtl_effects.csv"), row.names = FALSE) + } + + # Create zip file + zip::zip(file, files = list.files(tmpdir, full.names = TRUE)) + } + ) + + output$download_report_pdf <- downloadHandler( + filename = paste0("qtl_report_", Sys.Date(), ".pdf"), + content = function(file) { + # Create PDF report using rmarkdown + # This would require a template Rmd file + showNotification("PDF report generation requires rmarkdown", type = "warning") + } + ) + + output$download_report_html <- downloadHandler( + filename = paste0("qtl_report_", Sys.Date(), ".html"), + content = function(file) { + # Create HTML report + showNotification("HTML report generation in development", type = "warning") } ) + + output$download_all_plots <- downloadHandler( + filename = paste0("all_plots_", Sys.Date(), ".pdf"), + content = function(file) { + # Save all plots to PDF + pdf(file, width = 12, height = 8) + # Plot each visualization + # This would require rendering all plots + dev.off() + showNotification("Plot export in development", type = "warning") + } + ) + + # Analysis status + output$analysis_status <- renderPrint({ + if (!analysis_complete()) { + cat("Analysis not yet run. Click 'RUN ANALYSIS' to start.") + } else { + cat("Analysis completed successfully!\n\n") + cat("Results are available in the Results and Visualizations tabs.") + } + }) } +# Run the application shinyApp(ui = ui, server = server) \ No newline at end of file