diff --git "a/app.R" "b/app.R" --- "a/app.R" +++ "b/app.R" @@ -1,1229 +1,1386 @@ -# ============================================================================ -# COMPLETE QTL ANALYSIS PIPELINE - ALL BUGS FIXED -# Fix summary: -# 1. safe_notify: added "success" type mapping to "message" -# 2. Model 8 MQM: replaced non-existent mqm() with mqmaugment()+mqmscan() -# 3. Model 9 Binary: fixed method -> model="binary" for scanone -# 4. Model 10 Normal: fixed method -> model="normal" for scanone -# 5. plot_manhattan_enhanced: fixed cumulative position calculation -# 6. detect_comprehensive_qtls: fixed peak detection to use full chr data -# 7. plot_genotype_violin: fixed recode() -> proper factor relabeling -# 8. find.marker / pull.geno: fixed genotype extraction by marker name -# 9. parse_advanced_cross: fixed map class assignment on final cross object -# 10. observeEvent: fixed double-trigger on dual file inputs -# 11. calculate_heterozygosity: added cross-type awareness for het coding -# 12. CIM: wrapped with tryCatch for version-safe method param -# 13. IMP: increased n.draws, added error recovery -# 14. QTL peak detection: now scans full chromosome LOD profile -# ============================================================================ - -suppressPackageStartupMessages({ - library(shiny) - library(shinydashboard) - library(shinyjs) - library(shinycssloaders) - library(qtl) - library(ggplot2) - library(plotly) - library(dplyr) - library(tidyr) - library(DT) - library(RColorBrewer) - library(ggrepel) - library(cowplot) - library(viridis) - library(ggridges) - library(pheatmap) -}) - -if (!require("corrplot", quietly = TRUE)) { - install.packages("corrplot", repos = "https://cloud.r-project.org/") - library(corrplot) -} - -# ============================================================================ -# SAFE NOTIFICATION FUNCTION [FIX #1: added "success" type] -# ============================================================================ - -safe_notify <- function(msg, type = "default") { - tryCatch({ - if (type %in% c("message", "success")) showNotification(msg, type = "message", duration = 3) - else if (type == "warning") showNotification(msg, type = "warning", duration = 5) - else if (type == "error") showNotification(msg, type = "error", duration = 8) - else showNotification(msg, duration = 3) - }, error = function(e) message(msg)) -} - -# ============================================================================ -# HELPER: Calculate Heterozygosity [FIX #11: cross-type aware het code] -# ============================================================================ - -calculate_heterozygosity <- function(cross) { - cross_type <- class(cross)[1] - # In R/qtl: 1=AA, 2=AB, 3=BB for F2; 1=AA, 2=AB for BC; 1=AA, 2=BB for RIL - het_code <- if (cross_type %in% c("f2", "bc")) 2L else NULL - - geno_all <- pull.geno(cross) - if (is.null(het_code)) { - # RIL / selfing: expect no heterozygotes - return(rep(0, nrow(geno_all))) - } - apply(geno_all, 1, function(row) mean(row == het_code, na.rm = TRUE)) -} - -# ============================================================================ -# ADVANCED DATA PARSER [FIX #9: correct map class assignment] -# ============================================================================ - -parse_advanced_cross <- function(geno_path, pheno_path, cross_type = "f2") { - +library(shiny) +library(qtl) +library(ggplot2) +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 ────────────────────────────────────────────── geno_raw <- read.csv(geno_path, header = FALSE, stringsAsFactors = FALSE, - check.names = FALSE, - na.strings = c("NA", "", "N/A", "-9", "0", ".")) - - if (nrow(geno_raw) < 4) - stop("Genotype file must have at least 4 rows: header, chr, pos, data") - - 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] - - marker_cols <- 2:ncol(geno_raw) - if (length(marker_cols) == 0) stop("No marker columns found") - + check.names = FALSE, na.strings = c("NA","","N/A")) + + # Row 1 = column names + 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 marker_names <- col_names[marker_cols] + chromosomes <- chr_row[marker_cols] + positions <- suppressWarnings(as.numeric(pos_row[marker_cols])) - chromosomes <- chr_row[marker_cols] - chromosomes <- gsub("^[Cc]hr", "", chromosomes) - chromosomes <- gsub("^0+", "", chromosomes) - chromosomes[chromosomes == "" | is.na(chromosomes)] <- "unknown" - - positions <- suppressWarnings(as.numeric(pos_row[marker_cols])) - positions[is.na(positions)] <- 0 + # 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 ind_ids <- as.character(ind_data[, 1]) - if (any(duplicated(ind_ids))) ind_ids <- make.unique(ind_ids) + # Genotype matrix (individuals × markers) geno_mat <- as.matrix(ind_data[, marker_cols, drop = FALSE]) - mode(geno_mat) <- "numeric" + class(geno_mat) <- "numeric" + geno_mat <- apply(geno_mat, 2, function(x) suppressWarnings(as.numeric(x))) rownames(geno_mat) <- ind_ids colnames(geno_mat) <- marker_names - # Remove individuals with >50% missing - miss_ind <- rowMeans(is.na(geno_mat)) - geno_mat <- geno_mat[miss_ind <= 0.5, , drop = FALSE] - ind_ids <- rownames(geno_mat) - if (nrow(geno_mat) == 0) stop("No individuals with <50% missing data") - - # Phenotype - pheno_raw <- read.csv(pheno_path, header = TRUE, stringsAsFactors = FALSE, - check.names = FALSE, - na.strings = c("NA", "", "N/A", ".")) - if (ncol(pheno_raw) < 2) stop("Phenotype file must have at least 2 columns") - - pheno_ids <- as.character(pheno_raw[, 1]) - if (any(duplicated(pheno_ids))) pheno_ids <- make.unique(pheno_ids) - pheno_df <- pheno_raw[, -1, drop = FALSE] - for (i in seq_len(ncol(pheno_df))) - pheno_df[, i] <- suppressWarnings(as.numeric(pheno_df[, i])) + # ── 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)))) rownames(pheno_df) <- pheno_ids - # Align + # ── 3. Align individuals ──────────────────────────────────────────────────── common_ids <- intersect(ind_ids, pheno_ids) if (length(common_ids) == 0) - stop(paste("No matching IDs between geno/pheno files.", - "Geno sample:", paste(head(ind_ids, 3), collapse = ","), - "Pheno sample:", paste(head(pheno_ids, 3), collapse = ","))) - - geno_mat <- geno_mat[common_ids, , drop = FALSE] - pheno_df <- pheno_df[common_ids, , drop = FALSE] - - # Remove markers with >50% missing - miss_mar <- colMeans(is.na(geno_mat)) - keep_mar <- miss_mar <= 0.5 - if (sum(keep_mar) == 0) stop("No markers with <50% missing data") - geno_mat <- geno_mat[, keep_mar, drop = FALSE] - chromosomes <- chromosomes[keep_mar] - positions <- positions[keep_mar] - marker_names <- marker_names[keep_mar] - - # Build genetic map per chromosome - unique_chrs <- unique(chromosomes) - chr_order <- order(suppressWarnings(as.numeric(unique_chrs)), - unique_chrs, na.last = TRUE) - unique_chrs <- unique_chrs[chr_order] - - geno_list <- list() - for (ch in unique_chrs) { - idx <- which(chromosomes == ch) - if (length(idx) < 1) next - - mk_names <- marker_names[idx] - mk_pos <- positions[idx] - names(mk_pos) <- mk_names - - ord <- order(mk_pos) - mk_pos <- mk_pos[ord] - mk_names <- mk_names[ord] - - # Remove position duplicates - dup_pos <- duplicated(mk_pos) - mk_pos <- mk_pos[!dup_pos] - mk_names <- mk_names[!dup_pos] - dup_nm <- duplicated(mk_names) - mk_pos <- mk_pos[!dup_nm] - mk_names <- mk_names[!dup_nm] - - if (length(mk_pos) < 1) next - - chr_geno <- geno_mat[, mk_names, drop = FALSE] - geno_list[[ch]] <- list(data = chr_geno, map = mk_pos) - # FIX #9: assign correct class to map (A = autosome) - class(geno_list[[ch]]$map) <- "A" - } + 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=", ") + )) - if (length(geno_list) == 0) stop("No valid chromosomes found") + geno_mat <- geno_mat[common_ids, , drop = FALSE] + pheno_df <- pheno_df[common_ids, , drop = FALSE] - cross <- list(geno = geno_list, pheno = pheno_df) - class(cross) <- c(cross_type, "cross") - cross <- jittermap(cross) - - het_rates <- calculate_heterozygosity(cross) - 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), na.rm = TRUE), - heterozygosity = mean(het_rates, na.rm = TRUE) - ) - - return(cross) -} - -# ============================================================================ -# 10 MAPPING MODELS [FIX #2,3,4,12,13: MQM, Binary, Normal, CIM, IMP] -# ============================================================================ - -run_all_ten_models <- function(cross, pheno_col) { - models <- list() - model_status <- list() - - # --- Model 1: Haley-Knott --- - safe_notify("Running Model 1/10: Haley-Knott (HK)...", "message") - tryCatch({ - models$hk <- scanone(cross, pheno.col = pheno_col, method = "hk") - model_status$hk <- "Success" - }, error = function(e) { - model_status$hk <<- paste("Failed:", e$message) - safe_notify(paste("HK failed:", e$message), "warning") - }) + # ── 4. Build the genetic map ──────────────────────────────────────────────── + unique_chrs <- unique(chromosomes) - # --- Model 2: EM Algorithm --- - safe_notify("Running Model 2/10: EM Algorithm...", "message") - tryCatch({ - models$em <- scanone(cross, pheno.col = pheno_col, method = "em") - model_status$em <- "Success" - }, error = function(e) { - model_status$em <<- paste("Failed:", e$message) - safe_notify(paste("EM failed:", e$message), "warning") + # 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 - # --- Model 3: Extended Haley-Knott --- - safe_notify("Running Model 3/10: Extended Haley-Knott (EHK)...", "message") - tryCatch({ - models$ehk <- scanone(cross, pheno.col = pheno_col, method = "ehk") - model_status$ehk <- "Success" - }, error = function(e) { - model_status$ehk <<- paste("Failed:", e$message) - safe_notify(paste("EHK failed:", e$message), "warning") - }) + # ── 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] - # --- Model 4: Multiple Imputation [FIX #13: n.draws=64 for better accuracy] --- - safe_notify("Running Model 4/10: Multiple Imputation (IMP)...", "message") - tryCatch({ - cross_sim <- sim.geno(cross, n.draws = 64, step = 2, - error.prob = 0.001, map.function = "kosambi") - models$imp <- scanone(cross_sim, pheno.col = pheno_col, method = "imp") - model_status$imp <- "Success" - }, error = function(e) { - model_status$imp <<- paste("Failed:", e$message) - safe_notify(paste("IMP failed:", e$message), "warning") - # Fallback: use HK result - if (!is.null(models$hk)) { - models$imp <<- models$hk - model_status$imp <<- "Fallback to HK" - } - }) + g_chr <- geno_mat[, mnames, drop = FALSE] - # --- Model 5: Marker Regression --- - safe_notify("Running Model 5/10: Marker Regression (MR)...", "message") - tryCatch({ - models$mr <- scanone(cross, pheno.col = pheno_col, method = "mr") - model_status$mr <- "Success" - }, error = function(e) { - model_status$mr <<- paste("Failed:", e$message) - safe_notify(paste("MR failed:", e$message), "warning") - }) + # 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" - # --- Model 6: Non-parametric --- - safe_notify("Running Model 6/10: Non-parametric (NP)...", "message") - tryCatch({ - models$np <- scanone(cross, pheno.col = pheno_col, method = "np") - model_status$np <- "Success" - }, error = function(e) { - model_status$np <<- paste("Failed:", e$message) - safe_notify(paste("NP failed:", e$message), "warning") - }) + map_ch <- map_list[[ch]] - # --- Model 7: Composite Interval Mapping [FIX #12: version-safe cim()] --- - safe_notify("Running Model 7/10: Composite Interval Mapping (CIM)...", "message") - tryCatch({ - # calc.genoprob needed before cim() - cross_gp <- calc.genoprob(cross, step = 2, error.prob = 0.001) - models$cim <- tryCatch( - cim(cross_gp, pheno.col = pheno_col, method = "hk", window = 10), - error = function(e2) cim(cross_gp, pheno.col = pheno_col, window = 10) - ) - model_status$cim <- "Success" - }, error = function(e) { - model_status$cim <<- paste("Failed:", e$message) - safe_notify(paste("CIM failed:", e$message), "warning") + list(data = g_chr, map = map_ch) }) + names(geno_list) <- unique_chrs - # --- Model 8: MQM [FIX #2: use mqmaugment + mqmscan, fallback gracefully] --- - safe_notify("Running Model 8/10: MQM Mapping...", "message") - tryCatch({ - # mqmaugment fills in missing genotypes; mqmscan is the actual scan - cross_aug <- mqmaugment(cross, missingval = "missing", verbose = FALSE) - # auto-select cofactors using initial scanone - scan_init <- scanone(cross, pheno.col = pheno_col, method = "hk") - cofactors <- mqmsetcofactors(cross_aug, each = 5) # every 5 markers - models$mqm <- mqmscan(cross_aug, cofactors = cofactors, - pheno.col = pheno_col, verbose = FALSE) - model_status$mqm <- "Success" - }, error = function(e) { - model_status$mqm <<- paste("Failed:", e$message) - safe_notify(paste("MQM failed:", e$message), "warning") - # Fallback: use HK - if (!is.null(models$hk)) { - models$mqm <<- models$hk - model_status$mqm <<- "Fallback to HK" - } - }) + # Assign class to each chromosome's map + for (ch in unique_chrs) { + class(geno_list[[ch]]$map) <- "A" # autosome + } - # --- Model 9: Binary Trait [FIX #3: use model="binary" not method="binary"] --- - safe_notify("Running Model 9/10: Binary Model...", "message") - tryCatch({ - # Binarize phenotype at median for applicability to any trait - pheno_vec <- cross$pheno[[pheno_col]] - cross_bin <- cross - med_val <- median(pheno_vec, na.rm = TRUE) - cross_bin$pheno[[pheno_col]] <- as.numeric(pheno_vec > med_val) - models$binary <- scanone(cross_bin, pheno.col = pheno_col, - method = "em", model = "binary") - model_status$binary <- "Success (binarized at median)" - }, error = function(e) { - model_status$binary <<- paste("Failed:", e$message) - safe_notify(paste("Binary failed:", e$message), "warning") - }) + # ── 6. Assemble cross ─────────────────────────────────────────────────────── + cross_obj <- list( + geno = geno_list, + pheno = pheno_df + ) + class(cross_obj) <- c(cross_type, "cross") - # --- Model 10: Normal (Gaussian) [FIX #4: use model="normal"] --- - safe_notify("Running Model 10/10: Normal (Gaussian) Model...", "message") - tryCatch({ - models$normal <- scanone(cross, pheno.col = pheno_col, - method = "em", model = "normal") - model_status$normal <- "Success" - }, error = function(e) { - model_status$normal <<- paste("Failed:", e$message) - safe_notify(paste("Normal failed:", e$message), "warning") - }) + # ── 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) - attr(models, "status") <- model_status - return(models) + cross_obj } -# ============================================================================ -# QTL DETECTION [FIX #8: peak detection now uses full chr profile] -# ============================================================================ - -detect_comprehensive_qtls <- function(scan, threshold, cross = NULL, pheno_col = NULL) { - if (is.null(scan) || nrow(scan) == 0) return(data.frame()) - - qtls <- data.frame() - - for (chr in unique(scan$chr)) { - chr_all <- scan[scan$chr == chr, ] - if (nrow(chr_all) == 0) next - - lods <- chr_all$lod - n <- nrow(chr_all) - # Find local maxima above threshold in full chromosome profile - is_peak <- logical(n) - for (i in seq_len(n)) { - if (lods[i] < threshold) next - left_ok <- (i == 1) || (lods[i] >= lods[i - 1]) - right_ok <- (i == n) || (lods[i] >= lods[i + 1]) - if (left_ok && right_ok) is_peak[i] <- TRUE +# ─── 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)) } - - peak_indices <- which(is_peak) - if (length(peak_indices) == 0) next - - for (pi in peak_indices) { - peak_row <- chr_all[pi, ] - peak_marker <- rownames(peak_row) - - # 1.5 LOD drop CI - in_ci15 <- which((peak_row$lod - chr_all$lod) <= 1.5) - left_pos <- if (length(in_ci15)) chr_all$pos[min(in_ci15)] else peak_row$pos - 5 - right_pos <- if (length(in_ci15)) chr_all$pos[max(in_ci15)] else peak_row$pos + 5 - left_mk <- if (length(in_ci15)) rownames(chr_all)[min(in_ci15)] else NA - right_mk <- if (length(in_ci15)) rownames(chr_all)[max(in_ci15)] else NA - - # 2 LOD drop CI - in_ci2 <- which((peak_row$lod - chr_all$lod) <= 2) - left2_pos <- if (length(in_ci2)) chr_all$pos[min(in_ci2)] else peak_row$pos - 3 - right2_pos <- if (length(in_ci2)) chr_all$pos[max(in_ci2)] else peak_row$pos + 3 - - # PVE: Lander-Botstein approximation - n_ind <- if (!is.null(cross)) nind(cross) else 200 - pve <- (1 - 10^(-2 * peak_row$lod / n_ind)) * 100 - - # Additive/dominance effects - add_effect <- NA_real_ - dom_effect <- NA_real_ - if (!is.null(cross) && !is.null(pheno_col)) { - tryCatch({ - # FIX #8: use find.marker then pull genotype by name safely - chr_str <- as.character(chr) - mk_name <- find.marker(cross, chr_str, peak_row$pos) - if (!is.null(mk_name) && length(mk_name) == 1) { - geno_col_nm <- mk_name - if (geno_col_nm %in% colnames(pull.geno(cross))) { - genotypes <- pull.geno(cross)[, geno_col_nm] - phenotypes <- cross$pheno[[pheno_col]] - means <- tapply(phenotypes, genotypes, mean, na.rm = TRUE) - if (length(means) == 3) { - add_effect <- (means["3"] - means["1"]) / 2 - dom_effect <- means["2"] - (means["1"] + means["3"]) / 2 - } else if (length(means) == 2) { - add_effect <- means[2] - means[1] - } - } - } - }, error = function(e) NULL) - } - - qtls <- rbind(qtls, data.frame( - Chromosome = as.character(chr), - Peak_Position_cM = round(peak_row$pos, 2), - Peak_Marker = peak_marker, - LOD_Score = round(peak_row$lod, 3), - PVE_Percent = round(max(pve, 0), 2), - CI_1.5LOD_Left_cM = round(left_pos, 2), - CI_1.5LOD_Right_cM = round(right_pos, 2), - CI_1.5LOD_Width_cM = round(right_pos - left_pos, 2), - CI_2LOD_Left_cM = round(left2_pos, 2), - CI_2LOD_Right_cM = round(right2_pos, 2), - CI_2LOD_Width_cM = round(right2_pos - left2_pos, 2), - Left_Flanking_Marker = left_mk, - Right_Flanking_Marker = right_mk, - Additive_Effect = round(add_effect, 4), - Dominance_Effect = round(dom_effect, 4), - stringsAsFactors = FALSE - )) - } - } - - if (nrow(qtls) > 0) { - qtls$ChrNum <- suppressWarnings(as.numeric(qtls$Chromosome)) - qtls$ChrNum[is.na(qtls$ChrNum)] <- 999 - qtls <- qtls[order(qtls$ChrNum, qtls$Peak_Position_cM), ] - qtls$ChrNum <- NULL - rownames(qtls) <- NULL - } - return(qtls) -} - -# ============================================================================ -# PERMUTATION TEST -# ============================================================================ - -run_permutation_analysis <- function(cross, pheno_col, n_perm = 1000) { - tryCatch({ - perms <- scanone(cross, pheno.col = pheno_col, - n.perm = n_perm, method = "hk", verbose = FALSE) - alphas <- c(0.001, 0.01, 0.05, 0.1, 0.2) - thr_vals <- sapply(alphas, function(a) { - tryCatch(as.numeric(summary(perms, alpha = a)[1]), error = function(e) NA) - }) - thresholds <- data.frame(Alpha = alphas, - LOD_Threshold = round(thr_vals, 3)) - list(permutations = perms, thresholds = thresholds) - }, error = function(e) { - safe_notify(paste("Permutation failed:", e$message), "warning") - NULL - }) + ) + cross } -# ============================================================================ -# MODEL COMPARISON TABLE -# ============================================================================ - -create_model_comparison <- function(models, threshold) { - if (is.null(models) || length(models) == 0) return(data.frame()) - statuses <- attr(models, "status") - - do.call(rbind, lapply(names(models), function(nm) { - scan <- models[[nm]] - if (is.null(scan) || !inherits(scan, "scanone")) return(NULL) - max_lod <- max(scan$lod, na.rm = TRUE) - mean_lod <- mean(scan$lod, na.rm = TRUE) - n_peaks <- nrow(scan[scan$lod >= threshold, ]) - peak_i <- which.max(scan$lod) - data.frame( - Model = toupper(nm), - Status = ifelse(!is.null(statuses[[nm]]), statuses[[nm]], "Unknown"), - Max_LOD = round(max_lod, 3), - Mean_LOD = round(mean_lod, 3), - N_Significant_Peaks = n_peaks, - Peak_Chromosome = as.character(scan$chr[peak_i]), - Peak_Position_cM = round(scan$pos[peak_i], 2), - stringsAsFactors = FALSE - ) - })) -> df - if (is.null(df)) return(data.frame()) - df[order(-df$Max_LOD), ] -} +# 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 -# ============================================================================ -# PLOTTING FUNCTIONS -# ============================================================================ - -# Plot 1: Manhattan [FIX #7: correct cumulative position] -plot_manhattan_enhanced <- function(scan, qtls, threshold) { - if (is.null(scan)) return(NULL) - - df <- as.data.frame(scan) - df$marker <- rownames(df) - chrs <- unique(df$chr) - - # Build per-chromosome max position and cumulative offset - chr_maxpos <- sapply(chrs, function(ch) max(df$pos[df$chr == ch], na.rm = TRUE)) - # Offset for chr i = sum of max positions of all chrs before i - chr_offset <- c(0, cumsum(chr_maxpos[-length(chr_maxpos)])) - names(chr_offset) <- chrs - - df$pos_cum <- df$pos + chr_offset[as.character(df$chr)] - chr_mid <- sapply(chrs, function(ch) - mean(df$pos_cum[df$chr == ch], na.rm = TRUE)) - - colors <- rep(brewer.pal(min(8, length(chrs)), "Set1"), - length.out = length(chrs)) - names(colors) <- chrs - - p <- ggplot(df, aes(x = pos_cum, y = lod, color = as.character(chr))) + - geom_point(size = 1.5, alpha = 0.7) + - geom_hline(yintercept = threshold, color = "red", - linetype = "dashed", linewidth = 1.2) + - scale_x_continuous(breaks = chr_mid, labels = names(chr_mid)) + - scale_color_manual(values = colors, guide = "none") + - labs(title = "Genome-wide Manhattan Plot", - x = "Chromosome", y = "LOD Score") + - theme_minimal(base_size = 13) + - theme(axis.text.x = element_text(angle = 45, hjust = 1)) - - if (!is.null(qtls) && nrow(qtls) > 0) { - qtls$pos_cum <- qtls$Peak_Position_cM + - chr_offset[as.character(qtls$Chromosome)] - p <- p + geom_point(data = qtls, - aes(x = pos_cum, y = LOD_Score), - color = "gold", size = 5, shape = 18, - inherit.aes = FALSE) - } - p -} + 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 -# Plot 2: Per-chromosome LOD profiles (replaces broken contour) -plot_chr_lod_profiles <- function(scan, threshold) { - if (is.null(scan)) return(NULL) - - df <- as.data.frame(scan) - df$chr <- factor(df$chr, levels = unique(df$chr)) - n_chrs <- nlevels(df$chr) - pal <- colorRampPalette(brewer.pal(9, "Set1"))(n_chrs) - - ggplot(df, aes(x = pos, y = lod, color = chr)) + - geom_line(linewidth = 0.8) + - geom_hline(yintercept = threshold, color = "red", - linetype = "dashed", linewidth = 0.8) + - facet_wrap(~chr, scales = "free_x", ncol = 4) + - scale_color_manual(values = pal, guide = "none") + - labs(title = "Per-Chromosome LOD Profiles", - x = "Position (cM)", y = "LOD Score") + - theme_bw(base_size = 11) + - theme(strip.background = element_rect(fill = "steelblue"), - strip.text = element_text(color = "white", face = "bold")) -} + 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] -# Plot 3: QTL Bubble Plot -plot_qtl_bubble <- function(qtls) { - if (is.null(qtls) || nrow(qtls) == 0) return(NULL) - - qtls$Chromosome <- factor(qtls$Chromosome, - levels = unique(qtls$Chromosome)) - ggplot(qtls, aes(x = Chromosome, y = Peak_Position_cM, - size = LOD_Score, color = PVE_Percent)) + - geom_point(alpha = 0.85) + - scale_size_continuous(range = c(4, 20), name = "LOD Score") + - scale_color_gradientn(colors = c("#2166ac","#92c5de","#f7f7f7", - "#f4a582","#d6604d"), - name = "PVE (%)") + - labs(title = "QTL Effect Size Bubble Plot", - x = "Chromosome", y = "Peak Position (cM)") + - theme_minimal(base_size = 13) + - theme(axis.text.x = element_text(angle = 45, hjust = 1)) -} + 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 + }) + 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 -# Plot 4: Ridge Plot -plot_ridge_distribution <- function(scan) { - if (is.null(scan)) return(NULL) - - df <- as.data.frame(scan) - df$chr <- factor(df$chr, levels = rev(unique(df$chr))) - - ggplot(df, aes(x = lod, y = chr, fill = after_stat(x))) + - geom_density_ridges_gradient(scale = 2.5, rel_min_height = 0.01, - color = "white") + - scale_fill_viridis_c(option = "C", name = "LOD") + - labs(title = "LOD Score Distribution per Chromosome", - x = "LOD Score", y = "Chromosome") + - theme_ridges(grid = FALSE) + - theme(legend.position = "right") + cross_obj <- list(geno = geno_list, pheno = pheno_df) + class(cross_obj) <- c(cross_type, "cross") + jittermap(cross_obj) } -# Plot 5: Violin + Boxplot [FIX #5: proper factor relabeling; FIX #6: safe geno extraction] -plot_genotype_violin <- function(cross, qtl_row, trait) { - if (is.null(cross) || is.null(qtl_row) || nrow(qtl_row) == 0) return(NULL) - chr_name <- as.character(qtl_row$Chromosome[1]) - if (!chr_name %in% names(cross$geno)) { - message("Chromosome '", chr_name, "' not found in cross object") - return(NULL) - } +# ─── 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); } + ")) + ), - # FIX #6: find.marker returns marker name; use it directly to index pull.geno() - mk_name <- tryCatch( - find.marker(cross, chr_name, qtl_row$Peak_Position_cM[1]), - error = function(e) NULL - ) - if (is.null(mk_name) || length(mk_name) == 0) { - message("Could not find marker near QTL peak") - return(NULL) - } - mk_name <- mk_name[1] + 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")) + ), - geno_mat <- pull.geno(cross) - if (!mk_name %in% colnames(geno_mat)) { - message("Marker '", mk_name, "' not found in genotype matrix") - return(NULL) - } + div(class = "qtl-layout", - genotypes <- geno_mat[, mk_name] - phenotypes <- cross$pheno[[trait]] - - df <- data.frame(Geno = genotypes, Pheno = phenotypes) - df <- df[!is.na(df$Geno) & !is.na(df$Pheno), ] - if (nrow(df) == 0) return(NULL) - - # FIX #5: proper factor relabeling (no dplyr::recode on numerics) - cross_type <- class(cross)[1] - uni_genos <- sort(unique(df$Geno)) - if (length(uni_genos) == 3 && cross_type == "f2") { - df$Geno <- factor(df$Geno, levels = uni_genos, - labels = c("AA", "AB", "BB")) - } else if (length(uni_genos) == 2) { - df$Geno <- factor(df$Geno, levels = uni_genos, - labels = c("AA", "BB")) - } else { - df$Geno <- factor(df$Geno) - } + # ── Sidebar ────────────────────────────────────────────────────────────── + div(class = "qtl-sidebar", - ggplot(df, aes(x = Geno, y = Pheno, fill = Geno)) + - geom_violin(alpha = 0.55, trim = FALSE, color = NA) + - geom_boxplot(width = 0.18, alpha = 0.85, outlier.size = 1) + - stat_summary(fun = mean, geom = "point", - shape = 18, size = 5, color = "#c0392b") + - scale_fill_brewer(palette = "Set2", guide = "none") + - labs(title = paste0("Phenotype Distribution at ", mk_name, - " (Chr ", chr_name, ")"), - x = "Genotype Class", y = trait) + - theme_minimal(base_size = 13) -} + div(class = "section-label", "Data Input"), -# Plot 6: Genetic Map Density -plot_genetic_density <- function(cross) { - if (is.null(cross)) return(NULL) - - map <- pull.map(cross) - df <- do.call(rbind, lapply(names(map), function(ch) { - data.frame(Chromosome = ch, Position_cM = as.numeric(map[[ch]])) - })) - - df$Chromosome <- factor(df$Chromosome, levels = names(map)) - - # Spacing between adjacent markers - df <- df[order(df$Chromosome, df$Position_cM), ] - df <- df %>% - group_by(Chromosome) %>% - mutate(Spacing = c(NA, diff(Position_cM))) %>% - ungroup() - - ggplot(df, aes(x = Chromosome, y = Position_cM)) + - geom_segment(aes(xend = Chromosome, yend = 0), - color = "gray80", linewidth = 0.6) + - geom_point(aes(color = Spacing), size = 2, alpha = 0.8) + - scale_color_viridis_c(option = "D", na.value = "gray50", - name = "Gap (cM)") + - scale_y_reverse() + - labs(title = "Genetic Marker Map", - x = "Chromosome", y = "Position (cM, top=0)") + - theme_minimal(base_size = 13) + - theme(axis.text.x = element_text(angle = 45, hjust = 1)) -} - -# Plot 7: Model Comparison Bar Plot -plot_model_comparison <- function(comparison_df) { - if (is.null(comparison_df) || nrow(comparison_df) == 0) return(NULL) - - ggplot(comparison_df, - aes(x = reorder(Model, Max_LOD), y = Max_LOD, fill = Model)) + - geom_col(alpha = 0.85, width = 0.7) + - geom_text(aes(label = sprintf("%.2f", Max_LOD)), - hjust = -0.15, size = 3.5, color = "gray20") + - coord_flip() + - scale_fill_manual(values = colorRampPalette(brewer.pal(10, "Paired"))(10), - guide = "none") + - labs(title = "Model Performance Comparison (Max LOD)", - x = NULL, y = "Max LOD Score") + - expand_limits(y = max(comparison_df$Max_LOD) * 1.15) + - theme_minimal(base_size = 13) -} + div(class = "required-notice", + "⚠ Upload both CSV files.", tags$br(), + "Genotype: header + chr row + pos row + data rows.", tags$br(), + "Phenotype: header + data rows." + ), -# Plot 8: QTL Interval map (chromosome ideogram-style) -plot_qtl_intervals <- function(qtls, cross) { - if (is.null(qtls) || nrow(qtls) == 0 || is.null(cross)) return(NULL) - - map <- pull.map(cross) - chr_df <- do.call(rbind, lapply(names(map), function(ch) { - data.frame(Chromosome = ch, - chr_max = max(as.numeric(map[[ch]]), na.rm = TRUE)) - })) - - qtls$Chromosome <- factor(qtls$Chromosome, - levels = unique(chr_df$Chromosome)) - - ggplot() + - geom_segment(data = chr_df, - aes(x = 0, xend = chr_max, - y = Chromosome, yend = Chromosome), - color = "gray70", linewidth = 4, lineend = "round") + - geom_segment(data = qtls, - aes(x = CI_1.5LOD_Left_cM, xend = CI_1.5LOD_Right_cM, - y = Chromosome, yend = Chromosome, - color = LOD_Score), - linewidth = 6, alpha = 0.7, lineend = "round") + - geom_point(data = qtls, - aes(x = Peak_Position_cM, y = Chromosome, - size = PVE_Percent), - color = "gold", shape = 18) + - scale_color_gradient(low = "#2166ac", high = "#d73027", - name = "LOD") + - scale_size_continuous(range = c(3, 10), name = "PVE (%)") + - labs(title = "QTL Confidence Intervals", - x = "Position (cM)", y = "Chromosome") + - theme_minimal(base_size = 13) -} + 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..." + ) + ), -# ============================================================================ -# UI -# ============================================================================ - -ui <- dashboardPage( - skin = "blue", - dashboardHeader(title = "QTL Analysis Suite"), - - dashboardSidebar(width = 310, - sidebarMenu(id = "tabs", - menuItem("Data Input", tabName = "data", icon = icon("upload")), - menuItem("10 Models", tabName = "models", icon = icon("cogs")), - menuItem("QTL Results", tabName = "results", icon = icon("table")), - menuItem("Visualizations",tabName = "plots", icon = icon("chart-bar")), - menuItem("Downloads", tabName = "download", icon = icon("download")), - menuItem("Help", tabName = "help", icon = icon("question-circle")) - ), + 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..." + ) + ), - div(style = "padding: 12px;", - tags$hr(), - h4("1. Upload Files", style = "color:#ecf0f1"), - fileInput("geno_file", "Genotype CSV", accept = ".csv", - placeholder = "row1=names,row2=chr,row3=pos..."), - fileInput("pheno_file", "Phenotype CSV", accept = ".csv", - placeholder = "col1=ID, col2+= traits"), - - selectInput("cross_type", "Cross Type", - choices = c("F2 Intercross" = "f2", - "Backcross" = "bc", - "RIL (selfing)" = "riself"), - selected = "f2"), - - tags$hr(), - h4("2. Analysis Parameters", style = "color:#ecf0f1"), - selectInput("pheno_trait", "Phenotype Trait", choices = NULL), - numericInput("lod_threshold", "LOD Threshold", value = 3.0, - min = 0, max = 20, step = 0.5), - numericInput("n_permutations", "Permutations (0 = skip)", - value = 100, min = 0, max = 5000, step = 100), - - tags$hr(), - actionButton("run_analysis", "RUN ALL 10 MODELS", - icon = icon("play"), - style = paste("background:#27ae60;color:white;", - "width:100%;font-weight:bold;font-size:15px;")) - ) - ), + # Preview of parsed data + uiOutput("parse_preview_ui"), - dashboardBody( - useShinyjs(), - tags$head(tags$style(HTML(" - .content-wrapper, .right-side { background-color:#f0f3f7; } - .box { border-radius:8px; box-shadow: 0 2px 8px rgba(0,0,0,0.08); } - .info-box { border-radius:8px; } - "))), - - tabItems( - - # ---- DATA TAB ---- - tabItem(tabName = "data", - fluidRow( - infoBoxOutput("ib_individuals", width = 4), - infoBoxOutput("ib_markers", width = 4), - infoBoxOutput("ib_chromosomes", width = 4) - ), - fluidRow( - box(title = "Data Summary", status = "primary", - solidHeader = TRUE, width = 6, - verbatimTextOutput("data_summary")), - box(title = "Cross Quality Metrics", status = "info", - solidHeader = TRUE, width = 6, - verbatimTextOutput("quality_metrics")) - ), - fluidRow( - box(title = "Genetic Marker Map", status = "info", - solidHeader = TRUE, width = 12, - plotOutput("genetic_map", height = "520px") %>% withSpinner(color = "#3498db")) - ) + 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") ), - # ---- MODELS TAB ---- - tabItem(tabName = "models", - fluidRow( - box(title = "Analysis Status", status = "primary", - solidHeader = TRUE, width = 12, - verbatimTextOutput("analysis_status")) - ), - fluidRow( - box(title = "Model Comparison Table", status = "info", - solidHeader = TRUE, width = 12, - DTOutput("model_comparison_table") %>% withSpinner(color = "#3498db")) - ), - fluidRow( - box(title = "Model Performance Bar Chart", status = "success", - solidHeader = TRUE, width = 12, - plotOutput("model_barplot", height = "420px") %>% withSpinner(color = "#27ae60")) - ) + div(class = "section-label", "Phenotype"), + div(class = "control-block", + selectInput("pheno_col", NULL, choices = NULL) ), - # ---- RESULTS TAB ---- - tabItem(tabName = "results", - fluidRow( - box(title = "Significant QTLs (all details)", status = "primary", - solidHeader = TRUE, width = 12, - DTOutput("qtl_table") %>% withSpinner(color = "#3498db")) + 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" ), - fluidRow( - box(title = "Permutation Thresholds", status = "warning", - solidHeader = TRUE, width = 12, - DTOutput("permutation_table") %>% withSpinner(color = "#e67e22")) - ) + selected = c("hk","em","imp","np","mr") ), - # ---- PLOTS TAB ---- - tabItem(tabName = "plots", - fluidRow( - box(title = "Manhattan Plot (all models → HK shown)", - status = "primary", solidHeader = TRUE, width = 12, - plotOutput("manhattan_plot", height = "480px") %>% withSpinner(color = "#3498db")) - ), - fluidRow( - box(title = "Per-Chromosome LOD Profiles", - status = "info", solidHeader = TRUE, width = 12, - plotOutput("chr_profiles_plot", height = "560px") %>% withSpinner(color = "#3498db")) - ), - fluidRow( - box(title = "Ridge Density Plot", - status = "success", solidHeader = TRUE, width = 6, - plotOutput("ridge_plot", height = "480px") %>% withSpinner(color = "#27ae60")), - box(title = "QTL Bubble Plot", - status = "warning", solidHeader = TRUE, width = 6, - plotOutput("bubble_plot", height = "480px") %>% withSpinner(color = "#e67e22")) - ), - fluidRow( - box(title = "QTL Confidence Intervals (Chromosome Ideogram)", - status = "danger", solidHeader = TRUE, width = 12, - plotOutput("qtl_interval_plot", height = "400px") %>% withSpinner(color = "#e74c3c")) - ), - fluidRow( - box(title = "Genotype-Phenotype Violin Plot", - status = "primary", solidHeader = TRUE, width = 12, - selectInput("violin_qtl", "Select QTL:", choices = NULL, - width = "350px"), - plotOutput("violin_plot", height = "440px") %>% withSpinner(color = "#3498db")) - ) + 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) ), - # ---- DOWNLOAD TAB ---- - tabItem(tabName = "download", - fluidRow( - box(title = "Download Analysis Results", status = "primary", - solidHeader = TRUE, width = 12, - br(), - downloadButton("dl_qtl", "Download QTL Results (CSV)", - style = "margin:8px; background:#3498db; color:white;"), - downloadButton("dl_model", "Download Model Comparison (CSV)", - style = "margin:8px; background:#27ae60; color:white;"), - downloadButton("dl_perms", "Download Permutation Thresholds (CSV)", - style = "margin:8px; background:#e67e22; color:white;"), - br(), br(), - helpText("Run 10 Models first to generate downloadable results.") - ) - ) + 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) ), - # ---- HELP TAB ---- - tabItem(tabName = "help", - fluidRow( - box(title = "File Format", status = "primary", - solidHeader = TRUE, width = 6, - HTML(" -