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}