diff --git "a/app.R" "b/app.R" --- "a/app.R" +++ "b/app.R" @@ -1,10 +1,6 @@ # ============================================================ # QTL MAPPING SUITE — Full Single-File Shiny Application -# MODIFIED: Dual file upload (Genotype + Phenotype separate) -# Supports: 0/1/2/-1 genotype coding, multi-environment phenotypes -# 10 Models: EM, HK, MR, IM, CIM, EHK, IMP, HKPERM, NP, MQM -# 10+ Plots: Genome Scan, Manhattan, Interval, Density, QQ, -# Heatmap, Effects, PVE, Common QTL, Circos +# FIXED: HuggingFace compatible # ============================================================ suppressPackageStartupMessages({ @@ -23,9 +19,8 @@ suppressPackageStartupMessages({ library(scales) }) -# ── CSS ───────────────────────────────────────────────────── +# ── CSS (Google Fonts removed — safe system fonts only) ──── APP_CSS <- " -@import url('https://fonts.googleapis.com/css2?family=DM+Sans:opsz,wght@9..40,300;9..40,400;9..40,500;9..40,600;9..40,700&family=DM+Mono:wght@400;500&family=Fraunces:opsz,wght@9..144,700;9..144,900&display=swap'); *,*::before,*::after{box-sizing:border-box;margin:0;padding:0} :root{ --white:#ffffff;--off:#f8f8f6;--g50:#f4f4f2;--g100:#e8e8e5;--g200:#d0d0cc; @@ -36,17 +31,16 @@ APP_CSS <- " --blu:#1a4a8a;--blult:#e8eef8; --rsm:4px;--r:8px;--rlg:14px; --sh:0 2px 12px rgba(0,0,0,.09);--shsm:0 1px 3px rgba(0,0,0,.07); - --f:'DM Sans',sans-serif;--fm:'DM Mono',monospace;--fs:'Fraunces',serif; + --f:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif; + --fm:'Courier New',Courier,monospace; --t:0.18s ease; } html,body{height:100%;background:var(--off);font-family:var(--f);color:var(--ink);font-size:14px;line-height:1.5} body{overflow-x:hidden} .container-fluid{padding:0!important} - -/* TOP BAR */ .qtl-top{height:56px;background:var(--white);border-bottom:1.5px solid var(--g100);display:flex;align-items:center;padding:0 24px;gap:16px;position:sticky;top:0;z-index:1000;box-shadow:var(--shsm)} -.tlmark{width:30px;height:30px;background:var(--acc);border-radius:var(--rsm);display:flex;align-items:center;justify-content:center;color:#fff;font-family:var(--fs);font-size:15px;font-weight:700} -.tlname{font-family:var(--fs);font-size:17px;font-weight:700;color:var(--ink);letter-spacing:-.3px} +.tlmark{width:30px;height:30px;background:var(--acc);border-radius:var(--rsm);display:flex;align-items:center;justify-content:center;color:#fff;font-size:15px;font-weight:700} +.tlname{font-size:17px;font-weight:700;color:var(--ink);letter-spacing:-.3px} .tlver{font-size:10px;color:var(--g400);font-family:var(--fm);background:var(--g50);padding:1px 6px;border-radius:20px;border:1px solid var(--g100)} .tldiv{width:1px;height:22px;background:var(--g100)} .stpill{display:flex;align-items:center;gap:5px;padding:3px 10px;border-radius:20px;background:var(--acclt);border:1px solid #b8dfc6;font-size:11px;font-weight:500;color:var(--acc)} @@ -55,11 +49,7 @@ body{overflow-x:hidden} .tlright{margin-left:auto;display:flex;align-items:center;gap:10px} .btn-tn{padding:6px 14px;border-radius:var(--rsm);border:1.5px solid var(--g100);background:#fff;color:var(--g600);font-family:var(--f);font-size:12px;font-weight:500;cursor:pointer;transition:var(--t)} .btn-tn:hover{border-color:var(--acc);color:var(--acc);background:var(--acclt)} - -/* LAYOUT */ .qtl-lay{display:flex;height:calc(100vh - 56px);overflow:hidden} - -/* SIDEBAR */ .qtl-sb{width:232px;min-width:232px;background:var(--white);border-right:1.5px solid var(--g100);display:flex;flex-direction:column;overflow-y:auto} .sb-sec{padding:18px 14px 6px} .sb-sec-t{font-size:9px;font-weight:700;letter-spacing:1.4px;text-transform:uppercase;color:var(--g400);padding:0 8px 7px} @@ -68,49 +58,35 @@ body{overflow-x:hidden} .nv.active{background:var(--acclt);color:var(--acc);border-color:#b8dfc6;font-weight:600} .nv-ic{font-size:14px;width:18px;text-align:center} .sb-foot{margin-top:auto;padding:12px 14px;border-top:1px solid var(--g100);font-size:11px;color:var(--g400)} - -/* MAIN */ .qtl-main{flex:1;overflow-y:auto;background:var(--off)} .pg{display:none;padding:26px 28px;animation:fu .22s ease} .pg.active{display:block} @keyframes fu{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:translateY(0)}} - -/* PAGE HEADER */ .ph{margin-bottom:22px} -.pt{font-family:var(--fs);font-size:24px;font-weight:700;color:var(--ink);line-height:1.2} +.pt{font-size:24px;font-weight:700;color:var(--ink);line-height:1.2} .ps{font-size:12px;color:var(--g600);margin-top:3px} .phr{display:flex;align-items:flex-start;justify-content:space-between;gap:14px} - -/* CARD */ .card{background:var(--white);border-radius:var(--rlg);border:1.5px solid var(--g100);box-shadow:var(--shsm);margin-bottom:18px;overflow:hidden} .ch{padding:14px 18px 12px;border-bottom:1px solid var(--g100);display:flex;align-items:center;justify-content:space-between;background:var(--white)} .ct{font-size:13px;font-weight:600;color:var(--ink)} .cst{font-size:11px;color:var(--g400);margin-top:2px} .cb{padding:18px} - -/* GRID */ .g2{display:grid;grid-template-columns:1fr 1fr;gap:18px} .g3{display:grid;grid-template-columns:1fr 1fr 1fr;gap:18px} .g4{display:grid;grid-template-columns:repeat(4,1fr);gap:14px} - -/* STAT TILE */ .st{background:var(--white);border-radius:var(--r);border:1.5px solid var(--g100);padding:14px 16px;transition:var(--t)} .st:hover{box-shadow:var(--sh);border-color:var(--g200)} .st-l{font-size:9px;font-weight:700;letter-spacing:1px;text-transform:uppercase;color:var(--g400);margin-bottom:5px} -.st-v{font-family:var(--fs);font-size:26px;font-weight:700;color:var(--ink);line-height:1} +.st-v{font-size:26px;font-weight:700;color:var(--ink);line-height:1} .st-s{font-size:11px;color:var(--g400);margin-top:3px} .st.acc{border-color:#b8dfc6;background:var(--acclt)} .st.acc .st-v{color:var(--acc)} - -/* UPLOAD ZONE */ .uzone{border:2px dashed var(--g200);border-radius:var(--rlg);padding:28px 20px;text-align:center;cursor:pointer;transition:var(--t);background:var(--g50)} .uzone:hover{border-color:var(--acc);background:var(--acclt)} .uzone-ic{font-size:28px;margin-bottom:8px} .uzone-t{font-size:13px;font-weight:600;color:var(--ink)} .uzone-s{font-size:11px;color:var(--g400);margin-top:4px} .uzone .shiny-input-container{margin:0} - -/* FORMAT GUIDE */ .fmt-box{background:var(--g50);border:1.5px solid var(--g100);border-radius:var(--r);padding:12px 14px;margin-top:12px} .fmt-title{font-size:11px;font-weight:700;color:var(--g600);letter-spacing:.5px;text-transform:uppercase;margin-bottom:8px} .fmt-table{width:100%;border-collapse:collapse;font-size:11px;font-family:var(--fm)} @@ -119,78 +95,56 @@ body{overflow-x:hidden} .fmt-table tr:last-child td{border-bottom:none} .fmt-table .hdr{color:var(--acc);font-weight:600} .fmt-table .pos-row{color:var(--amb);font-style:italic} - -/* FORM */ .fl{display:block;font-size:12px;font-weight:600;color:var(--g600);margin-bottom:5px;letter-spacing:.2px} .fm-g{margin-bottom:14px} -.selectize-input{border:1.5px solid var(--g100)!important;border-radius:var(--rsm)!important;font-family:var(--f)!important;font-size:13px!important;padding:7px 12px!important;box-shadow:none!important} +.selectize-input{border:1.5px solid var(--g100)!important;border-radius:var(--rsm)!important;font-size:13px!important;padding:7px 12px!important;box-shadow:none!important} .selectize-input.focus{border-color:var(--acc)!important;box-shadow:0 0 0 3px rgba(26,107,58,.1)!important} -input[type=number],input[type=text]{width:100%;padding:8px 12px;border:1.5px solid var(--g100);border-radius:var(--rsm);font-family:var(--f);font-size:13px;outline:none} +input[type=number],input[type=text]{width:100%;padding:8px 12px;border:1.5px solid var(--g100);border-radius:var(--rsm);font-size:13px;outline:none} input[type=number]:focus,input[type=text]:focus{border-color:var(--acc);box-shadow:0 0 0 3px rgba(26,107,58,.1)} .irs--shiny .irs-bar{background:var(--acc)!important} .irs--shiny .irs-handle{background:var(--acc)!important;border-color:var(--acc)!important} - -/* BUTTONS */ -.btn-p{background:var(--acc);color:#fff;border:none;padding:9px 20px;border-radius:var(--rsm);font-family:var(--f);font-size:13px;font-weight:600;cursor:pointer;transition:var(--t);display:inline-flex;align-items:center;gap:6px} +.btn-p{background:var(--acc);color:#fff;border:none;padding:9px 20px;border-radius:var(--rsm);font-size:13px;font-weight:600;cursor:pointer;transition:var(--t);display:inline-flex;align-items:center;gap:6px} .btn-p:hover{background:#155a30;box-shadow:var(--sh);transform:translateY(-1px)} -.btn-s{background:#fff;color:var(--g600);border:1.5px solid var(--g100);padding:7px 16px;border-radius:var(--rsm);font-family:var(--f);font-size:13px;font-weight:500;cursor:pointer;transition:var(--t)} +.btn-s{background:#fff;color:var(--g600);border:1.5px solid var(--g100);padding:7px 16px;border-radius:var(--rsm);font-size:13px;font-weight:500;cursor:pointer;transition:var(--t)} .btn-s:hover{border-color:var(--g200);color:var(--ink);background:var(--g50)} -.btn-dl{background:#fff;color:var(--acc);border:1.5px solid var(--acc);padding:6px 14px;border-radius:var(--rsm);font-family:var(--f);font-size:12px;font-weight:600;cursor:pointer;transition:var(--t);display:inline-flex;align-items:center;gap:5px} +.btn-dl{background:#fff;color:var(--acc);border:1.5px solid var(--acc);padding:6px 14px;border-radius:var(--rsm);font-size:12px;font-weight:600;cursor:pointer;transition:var(--t);display:inline-flex;align-items:center;gap:5px} .btn-dl:hover{background:var(--acc);color:#fff} .br{display:flex;gap:8px;align-items:center;flex-wrap:wrap;margin-top:6px} - -/* TABS */ .qtabs{display:flex;gap:2px;border-bottom:1.5px solid var(--g100);margin-bottom:18px} .qtab{padding:8px 16px;font-size:12px;font-weight:600;cursor:pointer;color:var(--g400);border-bottom:2px solid transparent;margin-bottom:-1.5px;transition:var(--t)} .qtab:hover{color:var(--ink)} .qtab.active{color:var(--acc);border-bottom-color:var(--acc)} - -/* PROGRESS */ .prog-out{height:5px;background:var(--g100);border-radius:20px;overflow:hidden;margin:7px 0} .prog-in{height:100%;background:linear-gradient(90deg,var(--acc),var(--accmd));border-radius:20px;transition:width .4s ease} - -/* ALERTS */ .al{padding:11px 14px;border-radius:var(--rsm);font-size:13px;margin-bottom:12px;border-left:3px solid;display:flex;align-items:flex-start;gap:9px} .al-ok{background:var(--acclt);border-color:var(--accmd);color:#0f4a28} .al-warn{background:var(--amblt);border-color:var(--amb);color:#6b4000} .al-err{background:var(--redlt);border-color:var(--red);color:#6b0000} .al-info{background:var(--blult);border-color:var(--blu);color:#0a2a5a} - -/* MODEL CHIPS */ .mchips{display:flex;flex-wrap:wrap;gap:7px} .mc{padding:5px 12px;border-radius:var(--rsm);font-size:12px;font-weight:500;cursor:pointer;border:1.5px solid var(--g100);background:#fff;color:var(--g600);transition:var(--t);user-select:none} .mc:hover{border-color:var(--acc);color:var(--acc);background:var(--acclt)} .mc.sel{background:var(--acc);color:#fff;border-color:var(--acc)} - -/* STATUS BADGE */ .sbadge{display:inline-flex;align-items:center;gap:5px;padding:3px 9px;border-radius:20px;font-size:11px;font-weight:600} .sbadge-ok{background:var(--acclt);color:var(--acc);border:1px solid #b8dfc6} .sbadge-pend{background:var(--amblt);color:var(--amb);border:1px solid #e8c070} .sbadge-err{background:var(--redlt);color:var(--red);border:1px solid #e8a0a0} - -/* TIP */ .tip{font-size:11px;color:var(--g400);font-style:italic;margin-top:4px} - -/* DATATABLE */ -.dataTables_wrapper{font-family:var(--f);font-size:13px} -.dataTables_wrapper .dataTables_filter input{border:1.5px solid var(--g100);border-radius:var(--rsm);padding:5px 10px;font-family:var(--f);font-size:12px;outline:none} +.dataTables_wrapper{font-size:13px} +.dataTables_wrapper .dataTables_filter input{border:1.5px solid var(--g100);border-radius:var(--rsm);padding:5px 10px;font-size:12px;outline:none} table.dataTable thead th{background:var(--g50);font-size:10px;font-weight:700;letter-spacing:.5px;text-transform:uppercase;color:var(--g600);padding:9px 11px!important;border-bottom:1.5px solid var(--g100)!important} table.dataTable tbody td{padding:8px 11px!important;font-size:12px} table.dataTable tbody tr:hover{background:var(--g50)!important} - -/* SCROLLBAR */ ::-webkit-scrollbar{width:5px;height:5px} ::-webkit-scrollbar-thumb{background:var(--g200);border-radius:20px} ::-webkit-scrollbar-thumb:hover{background:var(--g400)} - -/* MISC */ .well{background:var(--g50);border:1.5px solid var(--g100);border-radius:var(--r);box-shadow:none;padding:14px} -.shiny-input-checkboxgroup label,.shiny-input-radiogroup label{font-size:12px;color:var(--g600);font-family:var(--f)} +.shiny-input-checkboxgroup label,.shiny-input-radiogroup label{font-size:12px;color:var(--g600)} input[type=checkbox]{accent-color:var(--acc)} input[type=radio]{accent-color:var(--acc)} " -# ── Model metadata ─────────────────────────────────────────── +# ── Model metadata ──────────────────────────────────────── MODEL_LABELS <- c( em="EM Algorithm", hk="Haley-Knott", mr="Marker Regression", im="Interval Mapping", cim="CIM", ehk="Extended HK", @@ -201,141 +155,89 @@ MODEL_COLORS <- c( ehk="#7b3fa0", imp="#1a8a8a", hkperm="#8a5a1a", scanone_np="#555555", mqm="#e05c00" ) -# ── HELPERS ────────────────────────────────────────────────── +# ── HELPERS ─────────────────────────────────────────────── chr_order_fn <- function(x) { nums <- suppressWarnings(as.numeric(x)) if (any(!is.na(nums))) order(ifelse(is.na(nums), Inf, nums)) else order(x) } -cum_positions <- function(df, chr_col = "chr", pos_col = "pos") { - chrs <- unique(df[[chr_col]])[chr_order_fn(unique(df[[chr_col]]))] - chr_lens <- sapply(chrs, function(c) max(df[[pos_col]][df[[chr_col]] == c])) - offsets <- c(0, cumsum(chr_lens[-length(chr_lens)])); names(offsets) <- chrs +cum_positions <- function(df, chr_col="chr", pos_col="pos") { + chrs <- unique(df[[chr_col]])[chr_order_fn(unique(df[[chr_col]]))] + chr_lens <- sapply(chrs, function(c) max(df[[pos_col]][df[[chr_col]] == c])) + offsets <- c(0, cumsum(chr_lens[-length(chr_lens)])); names(offsets) <- chrs df$cum_pos <- df[[pos_col]] + offsets[df[[chr_col]]] - list(df = df, offsets = offsets, chrs = chrs) + list(df=df, offsets=offsets, chrs=chrs) } -# ── KEY FUNCTION: Build cross from separate geno + pheno files ── -# Your genotype CSV format: -# Row 1: header → "id", marker1, marker2, ... -# Row 2: chr → "1", chrXX, chrXX, ... (e.g. "chr01") -# Row 3: pos → "0", 0.22, 0.59, ... (cM positions) -# Row 4+: data → sampleID, 0/1/2/-1, ... -# -# Genotype coding: 0=AA, 1=AB, 2=BB, -1=missing -# Phenotype CSV: Row 1 = header "id", ENV1_PL, ENV2_PL, ... -# Row 2+ = sampleID, pheno values - -build_cross_from_files <- function(geno_path, pheno_path, cross_type = "bc") { - - # ── Read genotype file ────────────────────────────────────── - geno_raw <- read.csv(geno_path, header = FALSE, stringsAsFactors = FALSE, - check.names = FALSE, na.strings = c("NA","","N/A")) - - # Row 1 = headers, Row 2 = chr, Row 3 = position, Row 4+ = data - marker_names <- as.character(geno_raw[1, -1]) # marker IDs - chr_row <- as.character(geno_raw[2, -1]) # chromosome labels - pos_row <- suppressWarnings(as.numeric(as.character(geno_raw[3, -1]))) # cM positions - sample_ids <- as.character(geno_raw[-(1:3), 1]) # individual IDs - geno_matrix <- geno_raw[-(1:3), -1, drop = FALSE] # genotype values - - # Clean chromosome names: "chr01" → "1", "chr10" → "10", etc. - chr_clean <- gsub("^chr0*", "", chr_row, ignore.case = TRUE) - chr_clean <- gsub("^0+", "", chr_clean) # remove leading zeros - - # Convert genotype coding: 0→AA(1), 1→AB(2), 2→BB(3), -1→NA - # R/qtl uses: 1=AA, 2=AB(het), 3=BB for F2 / BC uses 1=AA, 2=AB +build_cross_from_files <- 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")) + marker_names <- as.character(geno_raw[1, -1]) + chr_row <- as.character(geno_raw[2, -1]) + pos_row <- suppressWarnings(as.numeric(as.character(geno_raw[3, -1]))) + sample_ids <- as.character(geno_raw[-(1:3), 1]) + geno_matrix <- geno_raw[-(1:3), -1, drop=FALSE] + + chr_clean <- gsub("^chr0*", "", chr_row, ignore.case=TRUE) + chr_clean <- gsub("^0+", "", chr_clean) + geno_num <- apply(geno_matrix, 2, function(col) { v <- suppressWarnings(as.numeric(as.character(col))) - # Map: -1→NA, 0→1, 1→2, 2→3 - mapped <- ifelse(is.na(v) | v == -1, NA, - ifelse(v == 0, 1L, - ifelse(v == 1, 2L, - ifelse(v == 2, 3L, NA)))) - mapped + ifelse(is.na(v) | v == -1, NA, + ifelse(v == 0, 1L, + ifelse(v == 1, 2L, + ifelse(v == 2, 3L, NA)))) }) rownames(geno_num) <- sample_ids colnames(geno_num) <- marker_names - # ── Read phenotype file ───────────────────────────────────── - pheno_raw <- read.csv(pheno_path, header = TRUE, stringsAsFactors = FALSE, - check.names = FALSE, na.strings = c("NA","","N/A")) + pheno_raw <- read.csv(pheno_path, header=TRUE, stringsAsFactors=FALSE, + check.names=FALSE, na.strings=c("NA","","N/A")) colnames(pheno_raw)[1] <- "id" rownames(pheno_raw) <- as.character(pheno_raw$id) - # ── Align samples ─────────────────────────────────────────── common_ids <- intersect(sample_ids, as.character(pheno_raw$id)) if (length(common_ids) == 0) - stop("No matching sample IDs between genotype and phenotype files. Check that IDs match exactly.") - - geno_aln <- geno_num[common_ids, , drop = FALSE] - pheno_aln <- pheno_raw[common_ids, -1, drop = FALSE] # drop id column + stop("No matching sample IDs between genotype and phenotype files.") - n_ind <- length(common_ids) + geno_aln <- geno_num[common_ids, , drop=FALSE] + pheno_aln <- pheno_raw[common_ids, -1, drop=FALSE] + n_ind <- length(common_ids) - # ── Build genetic map ─────────────────────────────────────── uniq_chrs <- unique(chr_clean) - # Sort chromosomes numerically if possible - chr_nums <- suppressWarnings(as.numeric(uniq_chrs)) - if (all(!is.na(chr_nums))) { - uniq_chrs <- uniq_chrs[order(chr_nums)] - } else { - uniq_chrs <- sort(uniq_chrs) - } - - map <- vector("list", length(uniq_chrs)) - names(map) <- uniq_chrs + chr_nums <- suppressWarnings(as.numeric(uniq_chrs)) + uniq_chrs <- if (all(!is.na(chr_nums))) uniq_chrs[order(chr_nums)] else sort(uniq_chrs) + map <- setNames(vector("list", length(uniq_chrs)), uniq_chrs) for (ch in uniq_chrs) { idx <- which(chr_clean == ch) - mk_pos <- pos_row[idx] - mk_nm <- marker_names[idx] - names(mk_pos) <- mk_nm + mk_pos <- pos_row[idx]; names(mk_pos) <- marker_names[idx] map[[ch]] <- mk_pos } - # ── Build geno list (by chromosome) ───────────────────────── - geno_list <- vector("list", length(uniq_chrs)) - names(geno_list) <- uniq_chrs - + geno_list <- setNames(vector("list", length(uniq_chrs)), uniq_chrs) for (ch in uniq_chrs) { - idx <- which(chr_clean == ch) - mat <- geno_aln[, idx, drop = FALSE] + idx <- which(chr_clean == ch) + mat <- geno_aln[, idx, drop=FALSE] storage.mode(mat) <- "integer" - geno_list[[ch]] <- list(data = mat, map = map[[ch]]) + geno_list[[ch]] <- list(data=mat, map=map[[ch]]) class(geno_list[[ch]]) <- "A" } - # ── Assemble cross object ──────────────────────────────────── - cross <- list( - geno = geno_list, - pheno = as.data.frame(pheno_aln, stringsAsFactors = FALSE) - ) - - # Coerce pheno columns to numeric - for (j in seq_len(ncol(cross$pheno))) { + cross <- list(geno=geno_list, pheno=as.data.frame(pheno_aln, stringsAsFactors=FALSE)) + for (j in seq_len(ncol(cross$pheno))) cross$pheno[, j] <- suppressWarnings(as.numeric(as.character(cross$pheno[, j]))) - } - rownames(cross$pheno) <- common_ids class(cross) <- c(cross_type, "cross") + cross <- jittermap(cross) - # ── Basic validation ───────────────────────────────────────── - cross <- jittermap(cross) # avoid duplicate map positions - - return(list( - cross = cross, - n_ind = n_ind, - n_markers = length(marker_names), - n_chr = length(uniq_chrs), - n_pheno = ncol(pheno_aln), - pheno_names = colnames(pheno_aln), - sample_ids = common_ids, - skipped_ids = setdiff(sample_ids, common_ids) - )) + list(cross=cross, n_ind=n_ind, n_markers=length(marker_names), + n_chr=length(uniq_chrs), n_pheno=ncol(pheno_aln), + pheno_names=colnames(pheno_aln), sample_ids=common_ids, + skipped_ids=setdiff(sample_ids, common_ids)) } -# ── UI ──────────────────────────────────────────────────────── +# ── UI ──────────────────────────────────────────────────── ui <- fluidPage( useShinyjs(), tags$head( @@ -360,58 +262,49 @@ ui <- fluidPage( ")) ), - # TOP BAR div(class="qtl-top", div(class="tlmark","Q"), span(class="tlname","QTL Mapping Suite"), span(class="tlver","v2.1"), div(class="tldiv"), div(class="stpill", div(class="dot"), span(id="stlbl","Ready")), - div(class="tlright", - downloadButton("dl_full","⬇ Export All",class="btn-tn") - ) + div(class="tlright", downloadButton("dl_full","Export All",class="btn-tn")) ), div(class="qtl-lay", - # SIDEBAR div(class="qtl-sb", div(class="sb-sec", div(class="sb-sec-t","Data"), - tags$div(class="nv active",`data-page`="upload", span(class="nv-ic","⬆"), span("Upload Data")), - tags$div(class="nv",`data-page`="explore", span(class="nv-ic","🔍"), span("Data Explorer")) + tags$div(class="nv active",`data-page`="upload", span(class="nv-ic","U"), span("Upload Data")), + tags$div(class="nv",`data-page`="explore", span(class="nv-ic","E"), span("Data Explorer")) ), div(class="sb-sec", div(class="sb-sec-t","Analysis"), - tags$div(class="nv",`data-page`="config", span(class="nv-ic","⚙"), span("Configure")), - tags$div(class="nv",`data-page`="run", span(class="nv-ic","▶"), span("Run Scan")) + tags$div(class="nv",`data-page`="config", span(class="nv-ic","C"), span("Configure")), + tags$div(class="nv",`data-page`="run", span(class="nv-ic","R"), span("Run Scan")) ), div(class="sb-sec", div(class="sb-sec-t","Results"), - tags$div(class="nv",`data-page`="genome", span(class="nv-ic","📈"), span("Genome Scan")), - tags$div(class="nv",`data-page`="qtlmap", span(class="nv-ic","🗺"), span("QTL Map")), - tags$div(class="nv",`data-page`="effects", span(class="nv-ic","📊"), span("Effects & PVE")), - tags$div(class="nv",`data-page`="compare", span(class="nv-ic","⚖"), span("Model Compare")), - tags$div(class="nv",`data-page`="circos", span(class="nv-ic","○"), span("Circos Plot")), - tags$div(class="nv",`data-page`="table", span(class="nv-ic","📋"), span("Results Table")) + tags$div(class="nv",`data-page`="genome", span(class="nv-ic","G"), span("Genome Scan")), + tags$div(class="nv",`data-page`="qtlmap", span(class="nv-ic","M"), span("QTL Map")), + tags$div(class="nv",`data-page`="effects", span(class="nv-ic","F"), span("Effects & PVE")), + tags$div(class="nv",`data-page`="compare", span(class="nv-ic","V"), span("Model Compare")), + tags$div(class="nv",`data-page`="circos", span(class="nv-ic","O"), span("Circos Plot")), + tags$div(class="nv",`data-page`="table", span(class="nv-ic","T"), span("Results Table")) ), - div(class="sb-foot","QTL Suite © 2024") + div(class="sb-foot","QTL Suite 2024") ), - # MAIN div(class="qtl-main", - # ── UPLOAD PAGE ───────────────────────────────────────── + # ── UPLOAD ── div(id="pg-upload", class="pg active", div(class="ph", div(class="pt","Upload Data Files"), - div(class="ps","Upload genotype and phenotype files separately — or load the built-in demo") + div(class="ps","Upload genotype and phenotype files separately or load the built-in demo") ), - - # File format guide div(class="card", - div(class="ch", - div(div(class="ct","Expected File Formats"), div(class="cst","Your exact format is supported")) - ), + div(class="ch", div(div(class="ct","Expected File Formats"), div(class="cst","Your exact format is supported"))), div(class="cb", div(class="g2", div( @@ -419,10 +312,10 @@ ui <- fluidPage( tags$table(class="fmt-table", tags$thead(tags$tr(tags$th("Row"),tags$th("Col 1"),tags$th("Col 2+"))), tags$tbody( - tags$tr(tags$td(class="hdr","Row 1 (Header)"),tags$td(class="hdr","id / genotypic data id"),tags$td(class="hdr","marker names (e.g. chr01_194844)")), - tags$tr(tags$td(class="pos-row","Row 2 (Chr)"),tags$td(class="pos-row","1"),tags$td(class="pos-row","chromosome (e.g. 1)")), - tags$tr(tags$td(class="pos-row","Row 3 (Pos)"),tags$td(class="pos-row","0"),tags$td(class="pos-row","position in cM (e.g. 0.22)")), - tags$tr(tags$td("Row 4+"),tags$td("Sample ID"),tags$td("Genotype: 0=AA, 1=AB, 2=BB, -1=missing")) + tags$tr(tags$td(class="hdr","Row 1 (Header)"),tags$td(class="hdr","id"),tags$td(class="hdr","marker names")), + tags$tr(tags$td(class="pos-row","Row 2 (Chr)"),tags$td(class="pos-row","1"),tags$td(class="pos-row","chromosome")), + tags$tr(tags$td(class="pos-row","Row 3 (Pos)"),tags$td(class="pos-row","0"),tags$td(class="pos-row","position cM")), + tags$tr(tags$td("Row 4+"),tags$td("Sample ID"),tags$td("0=AA, 1=AB, 2=BB, -1=missing")) ) ) ), @@ -431,23 +324,18 @@ ui <- fluidPage( tags$table(class="fmt-table", tags$thead(tags$tr(tags$th("Row"),tags$th("Col 1"),tags$th("Col 2+"))), tags$tbody( - tags$tr(tags$td(class="hdr","Row 1 (Header)"),tags$td(class="hdr","id"),tags$td(class="hdr","trait names (e.g. ENV1_PL)")), + tags$tr(tags$td(class="hdr","Row 1 (Header)"),tags$td(class="hdr","id"),tags$td(class="hdr","trait names")), tags$tr(tags$td("Row 2+"),tags$td("Sample ID"),tags$td("Numeric phenotype values")) ) ), div(style="margin-top:10px;", - div(class="al al-info", "ℹ", - div("Sample IDs must match exactly between the two files. Missing values can be NA or blank.") - ) + div(class="al al-info","i",div("Sample IDs must match exactly between the two files.")) ) ) ) ) ), - - # Upload cards div(class="g2", - # Genotype upload div(class="card", div(class="ch", div(div(class="ct","Genotype File"), div(class="cst","CSV with chr/pos rows")), @@ -455,16 +343,14 @@ ui <- fluidPage( ), div(class="cb", div(class="uzone", - div(class="uzone-ic","🧬"), + div(class="uzone-ic","[G]"), div(class="uzone-t","Drop Genotype CSV"), - div(class="uzone-s","Row 2 = chromosome, Row 3 = cM position, Row 4+ = samples"), - fileInput("geno_file", NULL, accept=c(".csv",".CSV"), - buttonLabel="Browse", placeholder="No file selected") + div(class="uzone-s","Row 2=chromosome, Row 3=cM position, Row 4+=samples"), + fileInput("geno_file", NULL, accept=c(".csv",".CSV"), buttonLabel="Browse", placeholder="No file selected") ), div(class="tip","Genotype codes: 0=AA, 1=AB, 2=BB, -1=missing") ) ), - # Phenotype upload div(class="card", div(class="ch", div(div(class="ct","Phenotype File"), div(class="cst","CSV with trait columns")), @@ -472,18 +358,15 @@ ui <- fluidPage( ), div(class="cb", div(class="uzone", - div(class="uzone-ic","📊"), + div(class="uzone-ic","[P]"), div(class="uzone-t","Drop Phenotype CSV"), - div(class="uzone-s","Multiple environments / traits supported as separate columns"), - fileInput("pheno_file", NULL, accept=c(".csv",".CSV"), - buttonLabel="Browse", placeholder="No file selected") + div(class="uzone-s","Multiple environments/traits supported as separate columns"), + fileInput("pheno_file", NULL, accept=c(".csv",".CSV"), buttonLabel="Browse", placeholder="No file selected") ), div(class="tip","First column = sample ID, remaining columns = trait values") ) ) ), - - # Cross settings + load buttons div(class="card", div(class="ch", div(div(class="ct","Cross Settings & Load"))), div(class="cb", @@ -491,41 +374,27 @@ ui <- fluidPage( div( div(class="fm-g", label(class="fl","Cross Type"), selectInput("cross_type", NULL, - choices=c( - "Backcross"="bc", - "F2 Intercross"="f2", - "RIL by selfing"="riself", - "RIL by sibling"="risib", - "Doubled Haploid"="dh" - ), - selected="bc", width="100%" - ) - ), - div(class="tip","Choose 'Backcross' if your genotype codes are only 0 and 1 (AA and AB).") + choices=c("Backcross"="bc","F2 Intercross"="f2","RIL by selfing"="riself","RIL by sibling"="risib","Doubled Haploid"="dh"), + selected="bc", width="100%")) ), div( div(class="fm-g", label(class="fl","Missing Genotype Value"), - selectInput("miss_val", NULL, - choices=c("-1 (default)"="-1","NA"="NA","0"="0"), - selected="-1", width="100%" - ) - ) + selectInput("miss_val", NULL, choices=c("-1 (default)"="-1","NA"="NA","0"="0"), selected="-1", width="100%")) ) ), div(class="br", - actionButton("load_data", "⬆ Load Files", class="btn-p"), - actionButton("load_demo", "🌿 Load Listeria Demo", class="btn-s") + actionButton("load_data","Load Files", class="btn-p"), + actionButton("load_demo","Load Listeria Demo", class="btn-s") ), br(), uiOutput("upload_status_msg") ) ), - uiOutput("upload_summary") ), # ── EXPLORE ── - div(id="pg-explore",class="pg", + div(id="pg-explore", class="pg", div(class="ph", div(class="pt","Data Explorer"), div(class="ps","Inspect genotype, phenotype and map structure")), div(class="g4", uiOutput("stat_tiles")), br(), @@ -539,7 +408,7 @@ ui <- fluidPage( ), # ── CONFIG ── - div(id="pg-config",class="pg", + div(id="pg-config", class="pg", div(class="ph", div(class="pt","Configure Analysis"), div(class="ps","Select phenotype, models, and scan parameters")), div(class="g2", div(class="card", @@ -582,16 +451,15 @@ ui <- fluidPage( ), # ── RUN ── - div(id="pg-run",class="pg", + div(id="pg-run", class="pg", div(class="ph", div(class="pt","Run QTL Scan"), div(class="ps","Execute selected models across the genome")), div(class="card", div(class="ch", div(div(class="ct","Analysis Pipeline"))), div(class="cb", - uiOutput("run_summary"), - br(), + uiOutput("run_summary"), br(), div(class="br", - actionButton("run_scan","▶ Run QTL Scan",class="btn-p"), - actionButton("clr_res","✕ Clear",class="btn-s") + actionButton("run_scan","Run QTL Scan",class="btn-p"), + actionButton("clr_res","Clear",class="btn-s") ), br(), uiOutput("prog_ui"), @@ -601,12 +469,12 @@ ui <- fluidPage( ), # ── GENOME SCAN ── - div(id="pg-genome",class="pg", - div(class="ph", div(class="pt","Genome Scan"), div(class="ps","LOD score profiles — all models overlaid")), + div(id="pg-genome", class="pg", + div(class="ph", div(class="pt","Genome Scan"), div(class="ps","LOD score profiles")), div(class="card", div(class="ch", - div(div(class="ct","LOD Profiles"),div(class="cst","All selected models")), - div(class="br", uiOutput("gm_model_sel"), downloadButton("dl_genome","⬇ PNG",class="btn-dl")) + div(div(class="ct","LOD Profiles"), div(class="cst","All selected models")), + div(class="br", uiOutput("gm_model_sel"), downloadButton("dl_genome","PNG",class="btn-dl")) ), div(class="cb", withSpinner(plotlyOutput("pl_genome",height="400px"),color="#1a6b3a")) ), @@ -616,49 +484,49 @@ ui <- fluidPage( div(class="cb", withSpinner(plotlyOutput("pl_chr_bar",height="280px"),color="#1a6b3a")) ), div(class="card", - div(class="ch", div(div(class="ct","QQ Plot — LOD Scores"))), + div(class="ch", div(div(class="ct","QQ Plot"))), div(class="cb", withSpinner(plotlyOutput("pl_qq",height="280px"),color="#1a6b3a")) ) ) ), # ── QTL MAP ── - div(id="pg-qtlmap",class="pg", - div(class="ph", div(class="pt","QTL Map"), div(class="ps","Significant QTL locations and confidence intervals")), + div(id="pg-qtlmap", class="pg", + div(class="ph", div(class="pt","QTL Map"), div(class="ps","Significant QTL locations")), div(class="card", div(class="ch", - div(div(class="ct","Manhattan Plot"),div(class="cst","Genome-wide LOD; red = significant")), - downloadButton("dl_manh","⬇ PNG",class="btn-dl") + div(div(class="ct","Manhattan Plot"), div(class="cst","Red = significant")), + downloadButton("dl_manh","PNG",class="btn-dl") ), div(class="cb", withSpinner(plotlyOutput("pl_manh",height="340px"),color="#1a6b3a")) ), div(class="g2", div(class="card", - div(class="ch", div(div(class="ct","1.5-LOD Interval Plot"),div(class="cst","Confidence intervals per model"))), + div(class="ch", div(div(class="ct","1.5-LOD Interval Plot"))), div(class="cb", withSpinner(plotlyOutput("pl_interval",height="300px"),color="#1a6b3a")) ), div(class="card", - div(class="ch", div(div(class="ct","QTL Density"),div(class="cst","Density of significant peaks by chr"))), + div(class="ch", div(div(class="ct","QTL Density"))), div(class="cb", withSpinner(plotlyOutput("pl_density",height="300px"),color="#1a6b3a")) ) ) ), # ── EFFECTS ── - div(id="pg-effects",class="pg", + div(id="pg-effects", class="pg", div(class="ph", div(class="pt","Effects & PVE"), div(class="ps","QTL effect sizes and percent variance explained")), div(class="g2", div(class="card", - div(class="ch", div(div(class="ct","Percent Variance Explained"),div(class="cst","Max PVE per chromosome by model"))), + div(class="ch", div(div(class="ct","Percent Variance Explained"))), div(class="cb", withSpinner(plotlyOutput("pl_pve",height="300px"),color="#1a6b3a")) ), div(class="card", - div(class="ch", div(div(class="ct","Additive Effects"),div(class="cst","Mean phenotype by genotype class at peak"))), + div(class="ch", div(div(class="ct","Additive Effects"))), div(class="cb", uiOutput("eff_chr_ui"), withSpinner(plotlyOutput("pl_eff",height="280px"),color="#1a6b3a")) ) ), div(class="card", - div(class="ch", div(div(class="ct","Phenotype × Genotype Violin"),div(class="cst","Distribution at selected QTL peak"))), + div(class="ch", div(div(class="ct","Phenotype x Genotype Violin"))), div(class="cb", div(class="fm-g", label(class="fl","Select QTL Peak"), uiOutput("peak_sel")), withSpinner(plotlyOutput("pl_violin",height="300px"),color="#1a6b3a") @@ -667,29 +535,29 @@ ui <- fluidPage( ), # ── COMPARE ── - div(id="pg-compare",class="pg", - div(class="ph", div(class="pt","Model Comparison"), div(class="ps","LOD profiles and common QTL across all models")), + div(id="pg-compare", class="pg", + div(class="ph", div(class="pt","Model Comparison"), div(class="ps","LOD profiles across all models")), div(class="card", - div(class="ch", div(div(class="ct","LOD Heatmap — Marker × Model"),div(class="cst","Top-60 markers by max LOD"))), + div(class="ch", div(div(class="ct","LOD Heatmap — Marker x Model"))), div(class="cb", withSpinner(plotlyOutput("pl_heatmap",height="380px"),color="#1a6b3a")) ), div(class="card", - div(class="ch", div(div(class="ct","Common QTL Highlighted"),div(class="cst","Amber = peaks found in ≥2 models"))), + div(class="ch", div(div(class="ct","Common QTL"), div(class="cst","Amber = peaks in 2+ models"))), div(class="cb", withSpinner(plotlyOutput("pl_common",height="340px"),color="#1a6b3a")) ), div(class="card", - div(class="ch", div(div(class="ct","Peak LOD Parallel Lines"),div(class="cst","Max LOD per chromosome by model"))), + div(class="ch", div(div(class="ct","Peak LOD Parallel Lines"))), div(class="cb", withSpinner(plotlyOutput("pl_pkcomp",height="300px"),color="#1a6b3a")) ) ), # ── CIRCOS ── - div(id="pg-circos",class="pg", - div(class="ph", div(class="pt","Circos Plot"), div(class="ps","Circular genome view of QTL across all models")), + div(id="pg-circos", class="pg", + div(class="ph", div(class="pt","Circos Plot"), div(class="ps","Circular genome view of QTL")), div(class="card", div(class="ch", - div(div(class="ct","Circular QTL View"),div(class="cst","Each ring = one model; red dots = significant peaks")), - downloadButton("dl_circos","⬇ PNG",class="btn-dl") + div(div(class="ct","Circular QTL View"), div(class="cst","Each ring = one model")), + downloadButton("dl_circos","PNG",class="btn-dl") ), div(class="cb", div(style="display:flex;justify-content:center;", @@ -700,19 +568,19 @@ ui <- fluidPage( ), # ── TABLE ── - div(id="pg-table",class="pg", + div(id="pg-table", class="pg", div(class="ph", div(class="phr", - div(div(class="pt","Results Table"), div(class="ps","Significant QTL — LOD, PVE, intervals, markers")), + div(div(class="pt","Results Table"), div(class="ps","Significant QTL")), div(class="br", - downloadButton("dl_csv","⬇ CSV",class="btn-dl"), - downloadButton("dl_tsv","⬇ TSV",class="btn-dl"), - downloadButton("dl_rds","⬇ RData",class="btn-dl") + downloadButton("dl_csv","CSV",class="btn-dl"), + downloadButton("dl_tsv","TSV",class="btn-dl"), + downloadButton("dl_rds","RData",class="btn-dl") ) ) ), div(class="card", - div(class="ch", div(div(class="ct","Significant QTL"), div(class="cst","LOD ≥ threshold"))), + div(class="ch", div(div(class="ct","Significant QTL"), div(class="cst","LOD >= threshold"))), div(class="cb", withSpinner(DTOutput("tbl_qtl"),color="#1a6b3a")) ), div(class="card", @@ -720,59 +588,50 @@ ui <- fluidPage( div(class="cb", withSpinner(DTOutput("tbl_full"),color="#1a6b3a")) ) ) - - ) # /qtl-main - ) # /qtl-lay + ) + ) ) -# ── SERVER ──────────────────────────────────────────────────── +# ── SERVER ──────────────────────────────────────────────── server <- function(input, output, session) { rv <- reactiveValues( - cross = NULL, - scan_list = list(), - sig_qtl = list(), - log_msgs = character(0), - running = FALSE, - pheno_name = "Phenotype", - geno_ok = FALSE, - pheno_ok = FALSE, - load_msg = NULL, - load_ok = FALSE + cross=NULL, scan_list=list(), sig_qtl=list(), + log_msgs=character(0), running=FALSE, + pheno_name="Phenotype", geno_ok=FALSE, pheno_ok=FALSE, + load_msg=NULL, load_ok=FALSE ) add_log <- function(msg) { - rv$log_msgs <- c(rv$log_msgs, paste0("[", format(Sys.time(),"%H:%M:%S"), "] ", msg)) + rv$log_msgs <- c(rv$log_msgs, paste0("[",format(Sys.time(),"%H:%M:%S"),"] ",msg)) } - # ── FILE STATUS BADGES ── output$geno_badge <- renderUI({ - if (rv$geno_ok) div(class="sbadge sbadge-ok","✓ Loaded") - else if (!is.null(input$geno_file)) div(class="sbadge sbadge-pend","⏳ Pending") - else div(class="sbadge sbadge-pend","○ Not loaded") + if (rv$geno_ok) div(class="sbadge sbadge-ok","Loaded") + else if (!is.null(input$geno_file)) div(class="sbadge sbadge-pend","Pending") + else div(class="sbadge sbadge-pend","Not loaded") }) output$pheno_badge <- renderUI({ - if (rv$pheno_ok) div(class="sbadge sbadge-ok","✓ Loaded") - else if (!is.null(input$pheno_file)) div(class="sbadge sbadge-pend","⏳ Pending") - else div(class="sbadge sbadge-pend","○ Not loaded") + if (rv$pheno_ok) div(class="sbadge sbadge-ok","Loaded") + else if (!is.null(input$pheno_file)) div(class="sbadge sbadge-pend","Pending") + else div(class="sbadge sbadge-pend","Not loaded") }) - # ── LOAD DEMO ── observeEvent(input$load_demo, { - withProgress(message="Loading Listeria demo…", { + withProgress(message="Loading Listeria demo...", { tryCatch({ data(listeria, package="qtl") - rv$cross <- listeria - rv$geno_ok <- TRUE - rv$pheno_ok <- TRUE - rv$load_ok <- TRUE - rv$load_msg <- "Listeria demo loaded successfully (F2, 20 chr, 133 markers, 1 phenotype)" - rv$log_msgs <- character(0) - add_log("Loaded Listeria demo (F2, 20 chr, 133 markers)") + rv$cross <- listeria + rv$geno_ok <- TRUE + rv$pheno_ok <- TRUE + rv$load_ok <- TRUE + rv$load_msg <- "Listeria demo loaded (F2, 20 chr, 133 markers, 1 phenotype)" + rv$log_msgs <- character(0) + add_log("Loaded Listeria demo") showNotification("Listeria dataset loaded!", type="message", duration=3) shinyjs::runjs("$('.nv').removeClass('active');$('[data-page=explore]').addClass('active');$('.pg').removeClass('active');$('#pg-explore').addClass('active');") - }, error = function(e) { + }, error=function(e) { rv$load_ok <- FALSE rv$load_msg <- paste("Error:", e$message) showNotification(paste("Error:", e$message), type="error") @@ -780,50 +639,30 @@ server <- function(input, output, session) { }) }) - # ── LOAD USER FILES ── observeEvent(input$load_data, { - if (is.null(input$geno_file)) { - showNotification("Please upload a genotype CSV file first.", type="warning"); return() - } - if (is.null(input$pheno_file)) { - showNotification("Please upload a phenotype CSV file first.", type="warning"); return() - } - - withProgress(message="Building cross object…", value=0, { + if (is.null(input$geno_file)) { showNotification("Please upload a genotype CSV file first.", type="warning"); return() } + if (is.null(input$pheno_file)) { showNotification("Please upload a phenotype CSV file first.", type="warning"); return() } + withProgress(message="Building cross object...", value=0, { tryCatch({ - incProgress(0.3, detail="Reading files…") - result <- build_cross_from_files( - geno_path = input$geno_file$datapath, - pheno_path = input$pheno_file$datapath, - cross_type = input$cross_type - ) - - incProgress(0.5, detail="Checking cross…") + incProgress(0.3, detail="Reading files...") + result <- build_cross_from_files(input$geno_file$datapath, input$pheno_file$datapath, input$cross_type) + incProgress(0.5, detail="Checking cross...") rv$cross <- result$cross rv$geno_ok <- TRUE rv$pheno_ok <- TRUE rv$load_ok <- TRUE rv$log_msgs <- character(0) - - msg <- paste0( - "Loaded: ", result$n_ind, " individuals, ", - result$n_markers, " markers, ", - result$n_chr, " chromosomes, ", - result$n_pheno, " phenotype(s): ", - paste(result$pheno_names, collapse=", ") - ) - if (length(result$skipped_ids) > 0) { - msg <- paste0(msg, " | Skipped ", length(result$skipped_ids), - " IDs not found in phenotype file") - } + msg <- paste0("Loaded: ",result$n_ind," individuals, ",result$n_markers," markers, ", + result$n_chr," chromosomes, ",result$n_pheno," phenotype(s): ", + paste(result$pheno_names,collapse=", ")) + if (length(result$skipped_ids) > 0) + msg <- paste0(msg," | Skipped ",length(result$skipped_ids)," unmatched IDs") rv$load_msg <- msg add_log(msg) - incProgress(0.2, detail="Done") showNotification("Data loaded successfully!", type="message", duration=4) shinyjs::runjs("$('.nv').removeClass('active');$('[data-page=explore]').addClass('active');$('.pg').removeClass('active');$('#pg-explore').addClass('active');") - - }, error = function(e) { + }, error=function(e) { rv$geno_ok <- FALSE rv$pheno_ok <- FALSE rv$load_ok <- FALSE @@ -834,17 +673,12 @@ server <- function(input, output, session) { }) }) - # ── UPLOAD STATUS MESSAGE ── output$upload_status_msg <- renderUI({ req(!is.null(rv$load_msg)) - if (rv$load_ok) { - div(class="al al-ok", "✓", div(div(style="font-weight:600;","Success"), div(rv$load_msg))) - } else { - div(class="al al-err", "✗", div(div(style="font-weight:600;","Error"), div(rv$load_msg))) - } + if (rv$load_ok) div(class="al al-ok","OK",div(div(style="font-weight:600;","Success"),div(rv$load_msg))) + else div(class="al al-err","!",div(div(style="font-weight:600;","Error"),div(rv$load_msg))) }) - # ── UPLOAD SUMMARY ── output$upload_summary <- renderUI({ req(rv$cross); cr <- rv$cross div(class="card", @@ -857,15 +691,11 @@ server <- function(input, output, session) { div(class="st", div(class="st-l","Phenotypes"), div(class="st-v", nphe(cr))) ), br(), - # Show phenotype names - div(class="tip", - paste("Phenotypes:", paste(phenames(cr), collapse=", ")) - ) + div(class="tip", paste("Phenotypes:", paste(phenames(cr), collapse=", "))) ) ) }) - # ── STAT TILES ── output$stat_tiles <- renderUI({ req(rv$cross); cr <- rv$cross tagList( @@ -876,21 +706,17 @@ server <- function(input, output, session) { ) }) - # ── EXPLORE TABS ── output$explore_content <- renderUI({ - tab <- if(is.null(input$tab_ex)) "pheno" else input$tab_ex + tab <- if (is.null(input$tab_ex)) "pheno" else input$tab_ex req(rv$cross) - if (tab=="pheno") { + if (tab == "pheno") { div(class="card", - div(class="ch", - div(class="ct","Phenotype Distribution"), - uiOutput("ex_pheno_sel_ui") - ), + div(class="ch", div(class="ct","Phenotype Distribution"), uiOutput("ex_pheno_sel_ui")), div(class="cb", withSpinner(plotlyOutput("pl_ex_pheno",height="320px"),color="#1a6b3a")) ) - } else if (tab=="map") { + } else if (tab == "map") { div(class="card",div(class="ch",div(class="ct","Genetic Map")),div(class="cb",withSpinner(plotlyOutput("pl_ex_map",height="380px"),color="#1a6b3a"))) - } else if (tab=="miss") { + } else if (tab == "miss") { div(class="card",div(class="ch",div(class="ct","Missing Genotypes")),div(class="cb",withSpinner(plotlyOutput("pl_ex_miss",height="350px"),color="#1a6b3a"))) } else { div(class="card",div(class="ch",div(class="ct","Genotype Frequencies")),div(class="cb",withSpinner(plotlyOutput("pl_ex_gf",height="350px"),color="#1a6b3a"))) @@ -898,145 +724,144 @@ server <- function(input, output, session) { }) output$ex_pheno_sel_ui <- renderUI({ - req(rv$cross) - pn <- phenames(rv$cross) - if (length(pn) > 1) { - selectInput("ex_pheno_col", NULL, choices=pn, selected=pn[1], width="200px") - } + req(rv$cross); pn <- phenames(rv$cross) + if (length(pn) > 1) selectInput("ex_pheno_col",NULL,choices=pn,selected=pn[1],width="200px") }) output$pl_ex_pheno <- renderPlotly({ req(rv$cross) pn <- phenames(rv$cross) - sel <- if(!is.null(input$ex_pheno_col) && input$ex_pheno_col %in% pn) input$ex_pheno_col else pn[1] - phe <- pull.pheno(rv$cross, which(pn==sel)) - df <- data.frame(y=phe) + sel <- if (!is.null(input$ex_pheno_col) && input$ex_pheno_col %in% pn) input$ex_pheno_col else pn[1] + phe <- pull.pheno(rv$cross, which(pn == sel)) + df <- data.frame(y=phe[!is.na(phe)]) + # FIX: use stat(density) instead of after_stat(density) for compatibility p <- ggplot(df, aes(x=y)) + - geom_histogram(aes(y=after_stat(density)),bins=30,fill="#1a6b3a",color="white",alpha=.85) + - geom_density(color="#c47c1a",linewidth=1) + - labs(x=sel,y="Density",title=paste("Phenotype:",sel)) + + geom_histogram(aes(y=stat(density)), bins=30, fill="#1a6b3a", color="white", alpha=.85) + + geom_density(color="#c47c1a", linewidth=1) + + labs(x=sel, y="Density", title=paste("Phenotype:",sel)) + theme_minimal() + theme(panel.grid.minor=element_blank()) - ggplotly(p) %>% layout(font=list(family="DM Sans")) + ggplotly(p) %>% layout(font=list(family="sans-serif")) }) output$pl_ex_map <- renderPlotly({ req(rv$cross); map <- pull.map(rv$cross) - df <- do.call(rbind,lapply(names(map),function(c) data.frame(chr=c,pos=map[[c]],marker=names(map[[c]]),stringsAsFactors=FALSE))) - df$cn <- as.numeric(factor(df$chr,levels=names(map))) - p <- ggplot(df,aes(x=pos,y=cn,text=paste0("Marker:",marker,"
Chr:",chr,"
Pos:",round(pos,2),"cM")))+ - geom_line(aes(group=chr),color="#d0d0cc",linewidth=.5)+geom_point(color="#1a6b3a",size=2.5,alpha=.8)+ - scale_y_continuous(breaks=unique(df$cn),labels=names(map))+ - labs(x="Position (cM)",y="Chromosome",title="Genetic Map")+theme_minimal()+theme(panel.grid.minor=element_blank()) - ggplotly(p,tooltip="text")%>%layout(font=list(family="DM Sans")) + df <- do.call(rbind, lapply(names(map), function(c) + data.frame(chr=c, pos=map[[c]], marker=names(map[[c]]), stringsAsFactors=FALSE))) + df$cn <- as.numeric(factor(df$chr, levels=names(map))) + p <- ggplot(df, aes(x=pos, y=cn, text=paste0("Marker:",marker,"
Chr:",chr,"
Pos:",round(pos,2),"cM"))) + + geom_line(aes(group=chr), color="#d0d0cc", linewidth=.5) + + geom_point(color="#1a6b3a", size=2.5, alpha=.8) + + scale_y_continuous(breaks=unique(df$cn), labels=names(map)) + + labs(x="Position (cM)", y="Chromosome", title="Genetic Map") + + theme_minimal() + theme(panel.grid.minor=element_blank()) + ggplotly(p, tooltip="text") %>% layout(font=list(family="sans-serif")) }) output$pl_ex_miss <- renderPlotly({ req(rv$cross); gt <- pull.geno(rv$cross) - mp <- colMeans(is.na(gt))*100; df <- data.frame(marker=names(mp),pct=mp,idx=seq_along(mp)) - p <- ggplot(df,aes(x=idx,y=pct,text=paste0("Marker:",marker,"
Missing:",round(pct,1),"%")))+ - geom_col(fill="#1a4a8a",alpha=.7)+labs(x="Marker Index",y="Missing (%)",title="Missing Genotype Data")+theme_minimal()+theme(panel.grid.minor=element_blank()) - ggplotly(p,tooltip="text")%>%layout(font=list(family="DM Sans")) + mp <- colMeans(is.na(gt)) * 100 + df <- data.frame(marker=names(mp), pct=mp, idx=seq_along(mp)) + p <- ggplot(df, aes(x=idx, y=pct, text=paste0("Marker:",marker,"
Missing:",round(pct,1),"%"))) + + geom_col(fill="#1a4a8a", alpha=.7) + + labs(x="Marker Index", y="Missing (%)", title="Missing Genotype Data") + + theme_minimal() + theme(panel.grid.minor=element_blank()) + ggplotly(p, tooltip="text") %>% layout(font=list(family="sans-serif")) }) output$pl_ex_gf <- renderPlotly({ req(rv$cross); gt <- pull.geno(rv$cross) - # Determine max genotype code - max_g <- max(gt,na.rm=TRUE) - lvls <- 1:max(max_g,3) + max_g <- max(gt, na.rm=TRUE) + lvls <- 1:max(max_g, 3) lbl <- c("1"="AA","2"="AB","3"="BB") cnts <- apply(gt, 2, function(x) table(factor(x, levels=lvls))) df <- as.data.frame(t(cnts)); df$marker <- rownames(df) cn <- intersect(c("1","2","3"), colnames(df)) names(df)[names(df) %in% cn] <- lbl[cn] gn <- intersect(c("AA","AB","BB"), names(df)) - dl <- tidyr::pivot_longer(df, all_of(gn), names_to="geno", values_to="count") + # FIX: use tidyr::pivot_longer safely + dl <- tidyr::pivot_longer(df, cols=all_of(gn), names_to="geno", values_to="count") dl$idx <- match(dl$marker, unique(dl$marker)) - p <- ggplot(dl,aes(x=idx,y=count,fill=geno,text=paste0("Marker:",marker,"
Geno:",geno,"
N:",count)))+ - geom_col(position="fill",width=1)+ - scale_fill_manual(values=c(AA="#1a6b3a",AB="#c47c1a",BB="#1a4a8a"))+ - labs(x="Marker Index",y="Proportion",fill="Genotype")+theme_minimal()+theme(panel.grid.minor=element_blank()) - ggplotly(p,tooltip="text")%>%layout(font=list(family="DM Sans")) + p <- ggplot(dl, aes(x=idx, y=count, fill=geno, text=paste0("Marker:",marker,"
Geno:",geno,"
N:",count))) + + geom_col(position="fill", width=1) + + scale_fill_manual(values=c(AA="#1a6b3a",AB="#c47c1a",BB="#1a4a8a")) + + labs(x="Marker Index", y="Proportion", fill="Genotype") + + theme_minimal() + theme(panel.grid.minor=element_blank()) + ggplotly(p, tooltip="text") %>% layout(font=list(family="sans-serif")) }) - # ── CONFIG SELECTS ── output$pheno_sel <- renderUI({ - req(rv$cross) - pn <- phenames(rv$cross) - selectInput("pheno_col",NULL,choices=pn,selected=pn[1],width="100%") + req(rv$cross); pn <- phenames(rv$cross) + selectInput("pheno_col", NULL, choices=pn, selected=pn[1], width="100%") }) output$chr_sel <- renderUI({ - req(rv$cross) - ch <- chrnames(rv$cross) - checkboxGroupInput("scan_chrs",NULL,choices=ch,selected=ch,inline=TRUE) + req(rv$cross); ch <- chrnames(rv$cross) + checkboxGroupInput("scan_chrs", NULL, choices=ch, selected=ch, inline=TRUE) }) - # ── RUN SUMMARY ── output$run_summary <- renderUI({ - mods <- if(is.null(input$sel_models)||!length(input$sel_models)) c("em","hk") else input$sel_models - pn <- if(is.null(input$pheno_col)) "—" else input$pheno_col - thr <- if(is.null(input$lod_thr)) 3.0 else input$lod_thr + mods <- if (is.null(input$sel_models) || !length(input$sel_models)) c("em","hk") else input$sel_models + pn <- if (is.null(input$pheno_col)) "?" else input$pheno_col + thr <- if (is.null(input$lod_thr)) 3.0 else input$lod_thr div( - div(class="al al-info","ℹ",div( + div(class="al al-info","i",div( div(style="font-weight:600;","Configured"), div(paste("Phenotype:",pn,"| Models:",length(mods),"| Threshold:",thr,"| Permutations:",input$n_perm)) )), - div(class="mchips",lapply(mods,function(m) div(class="mc sel",`data-model`=m,MODEL_LABELS[m]))) + div(class="mchips", lapply(mods, function(m) div(class="mc sel",`data-model`=m, MODEL_LABELS[m]))) ) }) output$prog_ui <- renderUI({ - if(!rv$running && !length(rv$scan_list)) return(NULL) - if(rv$running) { - tagList(div(class="prog-out",div(class="prog-in",style="width:60%")),div(class="tip","Scanning…")) + if (!rv$running && !length(rv$scan_list)) return(NULL) + if (rv$running) { + tagList(div(class="prog-out",div(class="prog-in",style="width:60%")), div(class="tip","Scanning...")) } else { - div(class="al al-ok","✓",div(div(style="font-weight:600;","Complete"),div(paste(length(rv$scan_list),"models done")))) + div(class="al al-ok","OK",div(div(style="font-weight:600;","Complete"),div(paste(length(rv$scan_list),"models done")))) } }) output$log_ui <- renderUI({ - if(!length(rv$log_msgs)) return(NULL) - div(class="card",style="margin-top:10px;", - div(class="ch",div(class="ct","Run Log")), + if (!length(rv$log_msgs)) return(NULL) + div(class="card", style="margin-top:10px;", + div(class="ch", div(class="ct","Run Log")), div(class="cb", - tags$pre(style="font-family:'DM Mono',monospace;font-size:11px;color:#5c5c58;background:#f8f8f6;padding:10px;border-radius:6px;max-height:180px;overflow-y:auto;", - paste(rv$log_msgs,collapse="\n")) + tags$pre(style="font-family:monospace;font-size:11px;color:#5c5c58;background:#f8f8f6;padding:10px;border-radius:6px;max-height:180px;overflow-y:auto;", + paste(rv$log_msgs, collapse="\n")) ) ) }) - # ── RUN SCAN ── observeEvent(input$run_scan, { req(rv$cross) - mods <- if(is.null(input$sel_models)||!length(input$sel_models)) c("em","hk") else input$sel_models - phe_col <- if(is.null(input$pheno_col)) 1 else which(phenames(rv$cross)==input$pheno_col)[1] - if(is.na(phe_col) || length(phe_col)==0) phe_col <- 1 - step <- if(is.null(input$step_sz)) 2 else input$step_sz - ep <- if(is.null(input$err_prob)) 0.001 else input$err_prob - thr <- if(is.null(input$lod_thr)) 3.0 else input$lod_thr - n_perm <- if(is.null(input$n_perm)) 0 else input$n_perm - n_imp <- if(is.null(input$n_imp)) 32 else input$n_imp - - rv$running <- TRUE - rv$scan_list <- list() - rv$sig_qtl <- list() - rv$log_msgs <- character(0) + mods <- if (is.null(input$sel_models) || !length(input$sel_models)) c("em","hk") else input$sel_models + phe_col <- if (is.null(input$pheno_col)) 1 else { v <- which(phenames(rv$cross)==input$pheno_col)[1]; if(is.na(v)) 1 else v } + step <- if (is.null(input$step_sz)) 2 else input$step_sz + ep <- if (is.null(input$err_prob)) 0.001 else input$err_prob + thr <- if (is.null(input$lod_thr)) 3.0 else input$lod_thr + n_perm <- if (is.null(input$n_perm)) 0 else input$n_perm + n_imp <- if (is.null(input$n_imp)) 32 else input$n_imp + + rv$running <- TRUE + rv$scan_list <- list() + rv$sig_qtl <- list() + rv$log_msgs <- character(0) rv$pheno_name <- phenames(rv$cross)[phe_col] - withProgress(message="Running QTL scan…", value=0, { + withProgress(message="Running QTL scan...", value=0, { tryCatch({ - add_log("Computing conditional genotype probabilities…") + add_log("Computing conditional genotype probabilities...") rv$cross <- calc.genoprob(rv$cross, step=step, error.prob=ep) incProgress(0.1) - if("imp" %in% mods) { - add_log("Simulating genotypes for imputation…") + if ("imp" %in% mods) { + add_log("Simulating genotypes for imputation...") rv$cross <- sim.geno(rv$cross, n.draws=n_imp, step=step, error.prob=ep) } - for(i in seq_along(mods)){ + for (i in seq_along(mods)) { m <- mods[i] - add_log(paste("Model:", MODEL_LABELS[m], "…")) + add_log(paste("Model:", MODEL_LABELS[m], "...")) incProgress(0.8/length(mods), detail=MODEL_LABELS[m]) res <- tryCatch({ @@ -1050,34 +875,31 @@ server <- function(input, output, session) { hkperm = scanone(rv$cross, pheno.col=phe_col, method="hk"), scanone_np = scanone(rv$cross, pheno.col=phe_col, method="np"), cim = cim(rv$cross, pheno.col=phe_col, method="hk"), - mqm = tryCatch( - mqmscan(rv$cross, pheno.col=phe_col), - error=function(e) scanone(rv$cross, pheno.col=phe_col, method="hk") - ), + mqm = tryCatch(mqmscan(rv$cross, pheno.col=phe_col), + error=function(e) scanone(rv$cross, pheno.col=phe_col, method="hk")), scanone(rv$cross, pheno.col=phe_col, method="hk") ) - }, error=function(e){ - add_log(paste(" ✗", m, ":", e$message, "→ fallback HK")) + }, error=function(e) { + add_log(paste(" ", m, "failed:", e$message, "-> fallback HK")) scanone(rv$cross, pheno.col=phe_col, method="hk") }) rv$scan_list[[m]] <- res lc <- ncol(res) sig <- res[res[, lc] >= thr, ] - if(nrow(sig) > 0){ + if (nrow(sig) > 0) { sig$model <- MODEL_LABELS[m] sig$model_id <- m sig$marker <- rownames(sig) sig$pve <- round(100*(1-exp(-2*sig[,lc]/nind(rv$cross))), 2) } rv$sig_qtl[[m]] <- sig - add_log(paste(" ✓", MODEL_LABELS[m], "peaks:", nrow(sig))) + add_log(paste(" OK", MODEL_LABELS[m], "peaks:", nrow(sig))) } - # Optional permutation for hkperm - if("hkperm" %in% mods && n_perm > 0) { - add_log(paste("Running", n_perm, "permutations for HK…")) - perm <- scanone(rv$cross, pheno.col=phe_col, method="hk", n.perm=n_perm, verbose=FALSE) + if ("hkperm" %in% mods && n_perm > 0) { + add_log(paste("Running", n_perm, "permutations for HK...")) + perm <- scanone(rv$cross, pheno.col=phe_col, method="hk", n.perm=n_perm, verbose=FALSE) thr_perm <- summary(perm, alpha=0.05)[1] add_log(paste(" Permutation threshold (5%):", round(thr_perm, 2))) } @@ -1087,7 +909,7 @@ server <- function(input, output, session) { add_log(paste("All", length(mods), "models completed.")) showNotification("Scan complete!", type="message", duration=3) - }, error=function(e){ + }, error=function(e) { rv$running <- FALSE add_log(paste("FATAL:", e$message)) showNotification(paste("Error:", e$message), type="error") @@ -1095,346 +917,401 @@ server <- function(input, output, session) { }) }) - observeEvent(input$clr_res,{ + observeEvent(input$clr_res, { rv$scan_list <- list(); rv$sig_qtl <- list(); rv$log_msgs <- character(0) }) - # ── REACTIVE HELPERS ── comb_df <- reactive({ - req(length(rv$scan_list)>0) - do.call(rbind,lapply(names(rv$scan_list),function(m){ + req(length(rv$scan_list) > 0) + do.call(rbind, lapply(names(rv$scan_list), function(m) { sc <- rv$scan_list[[m]]; lc <- ncol(sc) - data.frame(chr=as.character(sc$chr),pos=sc$pos,lod=sc[,lc], - model=MODEL_LABELS[m],model_id=m,marker=rownames(sc), + data.frame(chr=as.character(sc$chr), pos=sc$pos, lod=sc[,lc], + model=MODEL_LABELS[m], model_id=m, marker=rownames(sc), stringsAsFactors=FALSE) })) }) sig_df <- reactive({ - req(length(rv$sig_qtl)>0) - dfs <- Filter(function(d) nrow(d)>0, rv$sig_qtl) - if(!length(dfs)) return(NULL) - do.call(rbind,dfs) + req(length(rv$sig_qtl) > 0) + dfs <- Filter(function(d) nrow(d) > 0, rv$sig_qtl) + if (!length(dfs)) return(NULL) + do.call(rbind, dfs) }) - thresh_val <- reactive({ if(is.null(input$lod_thr)) 3.0 else input$lod_thr }) + thresh_val <- reactive({ if (is.null(input$lod_thr)) 3.0 else input$lod_thr }) - # ── GENOME SCAN ── output$gm_model_sel <- renderUI({ - req(length(rv$scan_list)>0) - selectInput("gm_msel",NULL,choices=setNames(names(rv$scan_list),MODEL_LABELS[names(rv$scan_list)]),multiple=TRUE,selected=names(rv$scan_list),width="260px") + req(length(rv$scan_list) > 0) + selectInput("gm_msel", NULL, + choices=setNames(names(rv$scan_list), MODEL_LABELS[names(rv$scan_list)]), + multiple=TRUE, selected=names(rv$scan_list), width="260px") }) output$pl_genome <- renderPlotly({ - req(length(rv$scan_list)>0); df <- comb_df() - sel <- if(!is.null(input$gm_msel)) input$gm_msel else unique(df$model_id) - df <- df[df$model_id %in% sel,]; thr <- thresh_val() - res <- cum_positions(df); df <- res$df; offsets <- res$offsets; chrs <- res$chrs - p <- ggplot(df,aes(x=cum_pos,y=lod,color=model,text=paste0("Chr:",chr,"
Pos:",round(pos,1),"cM
LOD:",round(lod,2),"
Model:",model)))+ - geom_line(linewidth=.7,alpha=.88)+ - geom_hline(yintercept=thr,linetype="dashed",color="#b83232",linewidth=.6)+ - scale_color_manual(values=setNames(unname(MODEL_COLORS[names(MODEL_LABELS)]),MODEL_LABELS))+ - labs(x="Genomic Position (cM)",y="LOD Score",color="Model")+ - theme_minimal()+theme(panel.grid.minor=element_blank(),panel.grid.major.x=element_blank(),legend.position="bottom") - for(nm in names(offsets)[-1]) p <- p+geom_vline(xintercept=offsets[nm],color="#e0e0dc",linewidth=.35) - mids <- tapply(df$cum_pos,df$chr,mean) - ggplotly(p,tooltip="text")%>%layout(font=list(family="DM Sans"), - annotations=lapply(chrs,function(c) list(x=mids[c],y=-0.4,text=c,showarrow=FALSE,font=list(size=8,color="#9a9a94"),xanchor="center"))) + req(length(rv$scan_list) > 0); df <- comb_df() + sel <- if (!is.null(input$gm_msel)) input$gm_msel else unique(df$model_id) + df <- df[df$model_id %in% sel, ]; thr <- thresh_val() + res <- cum_positions(df); df <- res$df; offsets <- res$offsets; chrs <- res$chrs + p <- ggplot(df, aes(x=cum_pos, y=lod, color=model, + text=paste0("Chr:",chr,"
Pos:",round(pos,1),"cM
LOD:",round(lod,2),"
Model:",model))) + + geom_line(linewidth=.7, alpha=.88) + + geom_hline(yintercept=thr, linetype="dashed", color="#b83232", linewidth=.6) + + scale_color_manual(values=setNames(unname(MODEL_COLORS[names(MODEL_LABELS)]), MODEL_LABELS)) + + labs(x="Genomic Position (cM)", y="LOD Score", color="Model") + + theme_minimal() + theme(panel.grid.minor=element_blank(), panel.grid.major.x=element_blank(), legend.position="bottom") + for (nm in names(offsets)[-1]) p <- p + geom_vline(xintercept=offsets[nm], color="#e0e0dc", linewidth=.35) + mids <- tapply(df$cum_pos, df$chr, mean) + ggplotly(p, tooltip="text") %>% layout(font=list(family="sans-serif"), + annotations=lapply(chrs, function(c) list(x=mids[c],y=-0.4,text=c,showarrow=FALSE,font=list(size=8,color="#9a9a94"),xanchor="center"))) }) output$pl_chr_bar <- renderPlotly({ - req(length(rv$scan_list)>0); df <- comb_df(); thr <- thresh_val() - pk <- df%>%group_by(chr,model)%>%summarise(mx=max(lod),.groups="drop") - p <- ggplot(pk,aes(x=chr,y=mx,fill=model,text=paste0("Chr:",chr,"
",model,"
Max LOD:",round(mx,2))))+ - geom_col(position="dodge",alpha=.85)+ - geom_hline(yintercept=thr,linetype="dashed",color="#b83232")+ - scale_fill_manual(values=setNames(unname(MODEL_COLORS[names(MODEL_LABELS)]),MODEL_LABELS))+ - labs(x="Chromosome",y="Max LOD",fill="Model")+theme_minimal()+theme(panel.grid.minor=element_blank(),legend.position="none") - ggplotly(p,tooltip="text")%>%layout(font=list(family="DM Sans")) + req(length(rv$scan_list) > 0); df <- comb_df(); thr <- thresh_val() + pk <- df %>% group_by(chr, model) %>% summarise(mx=max(lod), .groups="drop") + p <- ggplot(pk, aes(x=chr, y=mx, fill=model, text=paste0("Chr:",chr,"
",model,"
Max LOD:",round(mx,2)))) + + geom_col(position="dodge", alpha=.85) + + geom_hline(yintercept=thr, linetype="dashed", color="#b83232") + + scale_fill_manual(values=setNames(unname(MODEL_COLORS[names(MODEL_LABELS)]), MODEL_LABELS)) + + labs(x="Chromosome", y="Max LOD", fill="Model") + + theme_minimal() + theme(panel.grid.minor=element_blank(), legend.position="none") + ggplotly(p, tooltip="text") %>% layout(font=list(family="sans-serif")) }) output$pl_qq <- renderPlotly({ - req(length(rv$scan_list)>0); df <- comb_df() - df1 <- df[df$model_id==names(rv$scan_list)[1],]; lods <- sort(df1$lod); n <- length(lods) - qq <- data.frame(ex=-log10(seq(n,1)/n),ob=lods) - p <- ggplot(qq,aes(x=ex,y=ob))+geom_point(color="#1a6b3a",alpha=.6,size=1.5)+geom_abline(slope=1,intercept=0,color="#b83232",linetype="dashed")+labs(x="Expected LOD",y="Observed LOD",title="QQ Plot")+theme_minimal()+theme(panel.grid.minor=element_blank()) - ggplotly(p)%>%layout(font=list(family="DM Sans")) + req(length(rv$scan_list) > 0); df <- comb_df() + df1 <- df[df$model_id == names(rv$scan_list)[1], ] + lods <- sort(df1$lod); n <- length(lods) + qq <- data.frame(ex=-log10(seq(n,1)/n), ob=lods) + p <- ggplot(qq, aes(x=ex, y=ob)) + + geom_point(color="#1a6b3a", alpha=.6, size=1.5) + + geom_abline(slope=1, intercept=0, color="#b83232", linetype="dashed") + + labs(x="Expected LOD", y="Observed LOD", title="QQ Plot") + + theme_minimal() + theme(panel.grid.minor=element_blank()) + ggplotly(p) %>% layout(font=list(family="sans-serif")) }) - # ── MANHATTAN ── output$pl_manh <- renderPlotly({ - req(length(rv$scan_list)>0); df <- comb_df(); thr <- thresh_val() - df1 <- df[df$model_id==names(rv$scan_list)[1],] + req(length(rv$scan_list) > 0); df <- comb_df(); thr <- thresh_val() + df1 <- df[df$model_id == names(rv$scan_list)[1], ] res <- cum_positions(df1); df1 <- res$df; chrs <- res$chrs; offsets <- res$offsets - df1$sig <- df1$lod>=thr - df1$cn <- match(df1$chr,chrs) - pal <- rep(c("#1a6b3a","#6aab87"),ceiling(length(chrs)/2))[seq_along(chrs)] - df1$ptcol <- ifelse(df1$sig,"#b83232",pal[df1$cn]) - p <- ggplot(df1,aes(x=cum_pos,y=lod,color=ptcol,text=paste0("Chr:",chr,"
Pos:",round(pos,1),"cM
",marker,"
LOD:",round(lod,2))))+ - geom_point(size=ifelse(df1$sig,2.5,1.2),alpha=ifelse(df1$sig,1,.7))+ - geom_hline(yintercept=thr,linetype="dashed",color="#b83232")+ - scale_color_identity()+labs(x="Position (cM)",y="LOD")+ - theme_minimal()+theme(panel.grid.minor=element_blank(),panel.grid.major.x=element_blank()) - mids <- tapply(df1$cum_pos,df1$chr,mean) - ggplotly(p,tooltip="text")%>%layout(font=list(family="DM Sans"), - annotations=lapply(chrs,function(c) list(x=mids[c],y=-0.3,text=c,showarrow=FALSE,font=list(size=8,color="#9a9a94"),xanchor="center"))) + df1$sig <- df1$lod >= thr + df1$cn <- match(df1$chr, chrs) + pal <- rep(c("#1a6b3a","#6aab87"), ceiling(length(chrs)/2))[seq_along(chrs)] + df1$ptcol <- ifelse(df1$sig, "#b83232", pal[df1$cn]) + p <- ggplot(df1, aes(x=cum_pos, y=lod, color=ptcol, + text=paste0("Chr:",chr,"
Pos:",round(pos,1),"cM
",marker,"
LOD:",round(lod,2)))) + + geom_point(size=ifelse(df1$sig,2.5,1.2), alpha=ifelse(df1$sig,1,.7)) + + geom_hline(yintercept=thr, linetype="dashed", color="#b83232") + + scale_color_identity() + + labs(x="Position (cM)", y="LOD") + + theme_minimal() + theme(panel.grid.minor=element_blank(), panel.grid.major.x=element_blank()) + mids <- tapply(df1$cum_pos, df1$chr, mean) + ggplotly(p, tooltip="text") %>% layout(font=list(family="sans-serif"), + annotations=lapply(chrs, function(c) list(x=mids[c],y=-0.3,text=c,showarrow=FALSE,font=list(size=8,color="#9a9a94"),xanchor="center"))) }) output$pl_interval <- renderPlotly({ - req(length(rv$scan_list)>0); df <- comb_df(); thr <- thresh_val() - pk <- df%>%filter(lod>=thr)%>%group_by(model,chr)%>%slice_max(lod,n=1)%>%ungroup() - if(!nrow(pk)) return(plotly_empty()%>%layout(title="No significant QTL")) - int_df <- do.call(rbind,lapply(seq_len(nrow(pk)),function(i){ - r <- pk[i,]; sub <- df[df$model==r$model & df$chr==r$chr,]; sub <- sub[order(sub$pos),] - hl <- r$lod-1.5; left <- min(sub$pos[sub$lod>=hl],na.rm=TRUE); right <- max(sub$pos[sub$lod>=hl],na.rm=TRUE) - data.frame(model=r$model,chr=r$chr,peak=r$pos,lod=r$lod,left=left,right=right,label=paste0(r$chr,"@",round(r$pos,1)),stringsAsFactors=FALSE) + req(length(rv$scan_list) > 0); df <- comb_df(); thr <- thresh_val() + # FIX: use base R instead of slice_max + pk <- do.call(rbind, lapply(split(df[df$lod >= thr, ], interaction(df[df$lod >= thr, "model"], df[df$lod >= thr, "chr"])), function(sub) { + if (!nrow(sub)) return(NULL) + sub[which.max(sub$lod), ] })) - p <- ggplot(int_df,aes(y=label,color=model,text=paste0(chr," @ ",round(peak,1),"cM
LOD:",round(lod,2),"
[",round(left,1),"–",round(right,1),"] cM")))+ - geom_segment(aes(x=left,xend=right,yend=label),linewidth=3,alpha=.5)+geom_point(aes(x=peak),size=4)+ - scale_color_manual(values=setNames(unname(MODEL_COLORS[names(MODEL_LABELS)]),MODEL_LABELS))+ - labs(x="Position (cM)",y="QTL")+theme_minimal()+theme(panel.grid.minor=element_blank()) - ggplotly(p,tooltip="text")%>%layout(font=list(family="DM Sans")) + pk <- pk[!sapply(pk, is.null), ] + if (is.null(pk) || nrow(pk) == 0) return(plotly_empty() %>% layout(title="No significant QTL")) + int_df <- do.call(rbind, lapply(seq_len(nrow(pk)), function(i) { + r <- pk[i, ]; sub <- df[df$model == r$model & df$chr == r$chr, ]; sub <- sub[order(sub$pos), ] + hl <- r$lod - 1.5 + lft <- min(sub$pos[sub$lod >= hl], na.rm=TRUE) + rgt <- max(sub$pos[sub$lod >= hl], na.rm=TRUE) + data.frame(model=r$model, chr=r$chr, peak=r$pos, lod=r$lod, left=lft, right=rgt, + label=paste0(r$chr,"@",round(r$pos,1)), stringsAsFactors=FALSE) + })) + p <- ggplot(int_df, aes(y=label, color=model, + text=paste0(chr," @ ",round(peak,1),"cM
LOD:",round(lod,2),"
[",round(left,1),"-",round(right,1),"] cM"))) + + geom_segment(aes(x=left, xend=right, yend=label), linewidth=3, alpha=.5) + + geom_point(aes(x=peak), size=4) + + scale_color_manual(values=setNames(unname(MODEL_COLORS[names(MODEL_LABELS)]), MODEL_LABELS)) + + labs(x="Position (cM)", y="QTL") + + theme_minimal() + theme(panel.grid.minor=element_blank()) + ggplotly(p, tooltip="text") %>% layout(font=list(family="sans-serif")) }) output$pl_density <- renderPlotly({ - req(length(rv$scan_list)>0); df <- comb_df(); thr <- thresh_val() - sig <- df[df$lod>=thr,] - if(!nrow(sig)) return(plotly_empty()%>%layout(title="No significant QTL")) - p <- ggplot(sig,aes(x=pos,fill=chr))+geom_density(alpha=.6)+facet_wrap(~chr,scales="free")+scale_fill_viridis_d()+labs(x="Position (cM)",y="Density")+theme_minimal()+theme(legend.position="none",panel.grid.minor=element_blank()) - ggplotly(p)%>%layout(font=list(family="DM Sans")) + req(length(rv$scan_list) > 0); df <- comb_df(); thr <- thresh_val() + sig <- df[df$lod >= thr, ] + if (!nrow(sig)) return(plotly_empty() %>% layout(title="No significant QTL")) + p <- ggplot(sig, aes(x=pos, fill=chr)) + + geom_density(alpha=.6) + facet_wrap(~chr, scales="free") + + scale_fill_viridis_d() + labs(x="Position (cM)", y="Density") + + theme_minimal() + theme(legend.position="none", panel.grid.minor=element_blank()) + ggplotly(p) %>% layout(font=list(family="sans-serif")) }) - # ── EFFECTS ── output$eff_chr_ui <- renderUI({ - req(rv$cross,length(rv$scan_list)>0) - selectInput("eff_chr","Select Chromosome:",choices=chrnames(rv$cross),width="180px") + req(rv$cross, length(rv$scan_list) > 0) + selectInput("eff_chr", "Select Chromosome:", choices=chrnames(rv$cross), width="180px") }) output$pl_pve <- renderPlotly({ - req(length(rv$sig_qtl)>0); sd <- sig_df(); req(!is.null(sd),nrow(sd)>0) - pv <- sd%>%group_by(chr,model)%>%summarise(mp=max(pve,na.rm=TRUE),.groups="drop") - p <- ggplot(pv,aes(x=chr,y=mp,fill=model,text=paste0("Chr:",chr,"
",model,"
Max PVE:",round(mp,1),"%")))+ - geom_col(position="dodge",alpha=.85)+scale_fill_manual(values=setNames(unname(MODEL_COLORS[names(MODEL_LABELS)]),MODEL_LABELS))+ - labs(x="Chromosome",y="Max PVE (%)",fill="Model")+theme_minimal()+theme(panel.grid.minor=element_blank()) - ggplotly(p,tooltip="text")%>%layout(font=list(family="DM Sans")) + req(length(rv$sig_qtl) > 0); sd <- sig_df(); req(!is.null(sd), nrow(sd) > 0) + pv <- sd %>% group_by(chr, model) %>% summarise(mp=max(pve, na.rm=TRUE), .groups="drop") + p <- ggplot(pv, aes(x=chr, y=mp, fill=model, text=paste0("Chr:",chr,"
",model,"
Max PVE:",round(mp,1),"%"))) + + geom_col(position="dodge", alpha=.85) + + scale_fill_manual(values=setNames(unname(MODEL_COLORS[names(MODEL_LABELS)]), MODEL_LABELS)) + + labs(x="Chromosome", y="Max PVE (%)", fill="Model") + + theme_minimal() + theme(panel.grid.minor=element_blank()) + ggplotly(p, tooltip="text") %>% layout(font=list(family="sans-serif")) }) output$pl_eff <- renderPlotly({ - req(rv$cross,length(rv$scan_list)>0) - ch <- if(is.null(input$eff_chr)) chrnames(rv$cross)[1] else input$eff_chr + req(rv$cross, length(rv$scan_list) > 0) + ch <- if (is.null(input$eff_chr)) chrnames(rv$cross)[1] else input$eff_chr sc <- rv$scan_list[[names(rv$scan_list)[1]]]; lc <- ncol(sc) - scc <- sc[sc$chr==ch,]; if(!nrow(scc)) return(plotly_empty()) - pm <- find.marker(rv$cross, ch, scc$pos[which.max(scc[,lc])]) + scc <- sc[sc$chr == ch, ]; if (!nrow(scc)) return(plotly_empty()) + pm <- find.marker(rv$cross, ch, scc$pos[which.max(scc[, lc])]) eff <- effectplot(rv$cross, mname1=pm, pheno.col=1, draw=FALSE) - df <- data.frame(geno=names(eff$Means),mean=as.numeric(eff$Means),sd=as.numeric(eff$SDs),n=as.numeric(eff$n)) - df$se <- df$sd/sqrt(df$n) - p <- ggplot(df,aes(x=geno,y=mean,fill=geno,text=paste0("Geno:",geno,"
Mean:",round(mean,3),"
SE:",round(se,3))))+ - geom_col(alpha=.85)+geom_errorbar(aes(ymin=mean-se,ymax=mean+se),width=.25)+ - scale_fill_manual(values=c("#1a6b3a","#c47c1a","#1a4a8a","#b83232"))+ - labs(x="Genotype",y=rv$pheno_name,title=paste("Effects at",pm))+theme_minimal()+theme(legend.position="none",panel.grid.minor=element_blank()) - ggplotly(p,tooltip="text")%>%layout(font=list(family="DM Sans")) + df <- data.frame(geno=names(eff$Means), mean=as.numeric(eff$Means), + sd=as.numeric(eff$SDs), n=as.numeric(eff$n)) + df$se <- df$sd / sqrt(df$n) + p <- ggplot(df, aes(x=geno, y=mean, fill=geno, text=paste0("Geno:",geno,"
Mean:",round(mean,3),"
SE:",round(se,3)))) + + geom_col(alpha=.85) + + geom_errorbar(aes(ymin=mean-se, ymax=mean+se), width=.25) + + scale_fill_manual(values=c("#1a6b3a","#c47c1a","#1a4a8a","#b83232")) + + labs(x="Genotype", y=rv$pheno_name, title=paste("Effects at",pm)) + + theme_minimal() + theme(legend.position="none", panel.grid.minor=element_blank()) + ggplotly(p, tooltip="text") %>% layout(font=list(family="sans-serif")) }) output$peak_sel <- renderUI({ - req(length(rv$sig_qtl)>0); sd <- sig_df(); req(!is.null(sd)) + req(length(rv$sig_qtl) > 0); sd <- sig_df(); req(!is.null(sd)) ch <- paste0(sd$chr," @ ",round(sd$pos,1),"cM (",sd$model_id,")") - selectInput("pk_sel",NULL,choices=ch,width="100%") + selectInput("pk_sel", NULL, choices=ch, width="100%") }) output$pl_violin <- renderPlotly({ - req(rv$cross,length(rv$sig_qtl)>0,!is.null(input$pk_sel)) + req(rv$cross, length(rv$sig_qtl) > 0, !is.null(input$pk_sel)) sd <- sig_df(); req(!is.null(sd)) idx <- which(paste0(sd$chr," @ ",round(sd$pos,1),"cM (",sd$model_id,")")==input$pk_sel)[1] req(!is.na(idx)) - row <- sd[idx,] - mar <- tryCatch(find.marker(rv$cross,row$chr,row$pos),error=function(e) row$marker) - gt <- pull.geno(rv$cross)[,mar]; phe <- pull.pheno(rv$cross,1) - # Support both 2-genotype (bc) and 3-genotype (f2) - max_g <- max(gt,na.rm=TRUE) - if(max_g <= 2) { - gl <- c("1"="AA","2"="AB") - } else { - gl <- c("1"="AA","2"="AB","3"="BB") - } - bdf <- data.frame(geno=factor(gl[as.character(gt)],levels=gl),pheno=phe)%>%filter(!is.na(geno),!is.na(pheno)) - cols <- c(AA="#1a6b3a",AB="#c47c1a",BB="#1a4a8a") - p <- ggplot(bdf,aes(x=geno,y=pheno,fill=geno))+ - geom_violin(alpha=.4,draw_quantiles=c(.25,.5,.75))+ - geom_jitter(aes(color=geno),width=.15,size=1.5,alpha=.6)+ - scale_fill_manual(values=cols)+scale_color_manual(values=cols)+ - labs(x="Genotype",y=rv$pheno_name,title=paste("Phenotype at",mar))+ - theme_minimal()+theme(legend.position="none") - ggplotly(p)%>%layout(font=list(family="DM Sans")) + row <- sd[idx, ] + mar <- tryCatch(find.marker(rv$cross, row$chr, row$pos), error=function(e) row$marker) + gt <- pull.geno(rv$cross)[, mar]; phe <- pull.pheno(rv$cross, 1) + max_g <- max(gt, na.rm=TRUE) + gl <- if (max_g <= 2) c("1"="AA","2"="AB") else c("1"="AA","2"="AB","3"="BB") + bdf <- data.frame(geno=factor(gl[as.character(gt)], levels=gl), pheno=phe) + bdf <- bdf[!is.na(bdf$geno) & !is.na(bdf$pheno), ] + cols <- c(AA="#1a6b3a", AB="#c47c1a", BB="#1a4a8a") + p <- ggplot(bdf, aes(x=geno, y=pheno, fill=geno)) + + geom_violin(alpha=.4, draw_quantiles=c(.25,.5,.75)) + + geom_jitter(aes(color=geno), width=.15, size=1.5, alpha=.6) + + scale_fill_manual(values=cols) + scale_color_manual(values=cols) + + labs(x="Genotype", y=rv$pheno_name, title=paste("Phenotype at",mar)) + + theme_minimal() + theme(legend.position="none") + ggplotly(p) %>% layout(font=list(family="sans-serif")) }) - # ── COMPARE ── output$pl_heatmap <- renderPlotly({ - req(length(rv$scan_list)>1); df <- comb_df() - top <- df%>%group_by(marker)%>%summarise(mx=max(lod))%>%slice_max(mx,n=60)%>%pull(marker) - hm <- df%>%filter(marker %in% top)%>%select(marker,model,lod)%>%pivot_wider(names_from=model,values_from=lod,values_fill=0)%>%as.data.frame() + req(length(rv$scan_list) > 1); df <- comb_df() + # FIX: use base R instead of slice_max + top_mk <- names(sort(tapply(df$lod, df$marker, max), decreasing=TRUE)[1:min(60,length(unique(df$marker)))]) + hm <- df[df$marker %in% top_mk, c("marker","model","lod")] + hm <- tidyr::pivot_wider(hm, names_from=model, values_from=lod, values_fill=0) + hm <- as.data.frame(hm) rn <- hm$marker; hm$marker <- NULL; mat <- as.matrix(hm) - plot_ly(z=mat,x=colnames(mat),y=rn,type="heatmap",colorscale="Viridis", - hovertemplate="Model: %{x}
Marker: %{y}
LOD: %{z:.2f}")%>% - layout(font=list(family="DM Sans"),xaxis=list(title="Model"),yaxis=list(title="Marker",tickfont=list(size=8))) + plot_ly(z=mat, x=colnames(mat), y=rn, type="heatmap", colorscale="Viridis", + hovertemplate="Model: %{x}
Marker: %{y}
LOD: %{z:.2f}") %>% + layout(font=list(family="sans-serif"), xaxis=list(title="Model"), yaxis=list(title="Marker",tickfont=list(size=8))) }) output$pl_common <- renderPlotly({ - req(length(rv$scan_list)>0); df <- comb_df(); thr <- thresh_val() - sig <- df%>%filter(lod>=thr)%>%group_by(chr,pos)%>%summarise(nm=n_distinct(model),mx=max(lod),.groups="drop") - df1 <- df[df$model_id==names(rv$scan_list)[1],]; df1$common <- FALSE - if(nrow(sig)>0) for(i in seq_len(nrow(df1))){ ms <- sig[sig$chr==df1$chr[i] & abs(sig$pos-df1$pos[i])<5 & sig$nm>=2,]; if(nrow(ms)>0) df1$common[i] <- TRUE } + req(length(rv$scan_list) > 0); df <- comb_df(); thr <- thresh_val() + sig <- df[df$lod >= thr, ] + sig_agg <- if (nrow(sig) > 0) { + do.call(rbind, lapply(split(sig, paste(sig$chr, round(sig$pos))), function(s) + data.frame(chr=s$chr[1], pos=s$pos[1], nm=length(unique(s$model)), mx=max(s$lod)))) + } else data.frame(chr=character(0), pos=numeric(0), nm=integer(0), mx=numeric(0)) + + df1 <- df[df$model_id == names(rv$scan_list)[1], ] + df1$common <- FALSE + if (nrow(sig_agg) > 0) { + for (i in seq_len(nrow(df1))) { + ms <- sig_agg[sig_agg$chr == df1$chr[i] & abs(sig_agg$pos - df1$pos[i]) < 5 & sig_agg$nm >= 2, ] + if (nrow(ms) > 0) df1$common[i] <- TRUE + } + } res <- cum_positions(df1); df1 <- res$df; offsets <- res$offsets; chrs <- res$chrs - p <- ggplot(df1,aes(x=cum_pos,y=lod,color=common,size=common,text=paste0("Chr:",chr,"
Pos:",round(pos,1),"cM
LOD:",round(lod,2),ifelse(common,"
★ COMMON QTL",""))))+ - geom_line(aes(group=chr),color="#d0d0cc",linewidth=.5)+geom_point(alpha=.8)+ - geom_hline(yintercept=thr,linetype="dashed",color="#888",linewidth=.5)+ - scale_color_manual(values=c("FALSE"="#1a6b3a","TRUE"="#c47c1a"),labels=c("FALSE"="Single model","TRUE"="Common (≥2)"))+ - scale_size_manual(values=c("FALSE"=1,"TRUE"=3))+ - labs(x="Genomic Position (cM)",y="LOD",color="QTL")+theme_minimal()+theme(panel.grid.minor=element_blank(),panel.grid.major.x=element_blank()) - for(nm in names(offsets)[-1]) p <- p+geom_vline(xintercept=offsets[nm],color="#e0e0dc",linewidth=.3) - ggplotly(p,tooltip="text")%>%layout(font=list(family="DM Sans")) + p <- ggplot(df1, aes(x=cum_pos, y=lod, color=common, size=common, + text=paste0("Chr:",chr,"
Pos:",round(pos,1),"cM
LOD:",round(lod,2),ifelse(common,"
COMMON QTL","")))) + + geom_line(aes(group=chr), color="#d0d0cc", linewidth=.5) + + geom_point(alpha=.8) + + geom_hline(yintercept=thr, linetype="dashed", color="#888", linewidth=.5) + + scale_color_manual(values=c("FALSE"="#1a6b3a","TRUE"="#c47c1a"), labels=c("FALSE"="Single model","TRUE"="Common (>=2)")) + + scale_size_manual(values=c("FALSE"=1,"TRUE"=3)) + + labs(x="Genomic Position (cM)", y="LOD", color="QTL") + + theme_minimal() + theme(panel.grid.minor=element_blank(), panel.grid.major.x=element_blank()) + for (nm in names(offsets)[-1]) p <- p + geom_vline(xintercept=offsets[nm], color="#e0e0dc", linewidth=.3) + ggplotly(p, tooltip="text") %>% layout(font=list(family="sans-serif")) }) output$pl_pkcomp <- renderPlotly({ - req(length(rv$scan_list)>0); df <- comb_df(); thr <- thresh_val() - pk <- df%>%group_by(chr,model)%>%summarise(mx=max(lod),.groups="drop") - p <- ggplot(pk,aes(x=chr,y=mx,color=model,group=model,text=paste0("Chr:",chr,"
",model,"
LOD:",round(mx,2))))+ - geom_line(linewidth=.8,alpha=.8)+geom_point(size=3)+ - geom_hline(yintercept=thr,linetype="dashed",color="#b83232")+ - scale_color_manual(values=setNames(unname(MODEL_COLORS[names(MODEL_LABELS)]),MODEL_LABELS))+ - labs(x="Chromosome",y="Peak LOD",color="Model")+theme_minimal()+theme(panel.grid.minor=element_blank()) - ggplotly(p,tooltip="text")%>%layout(font=list(family="DM Sans")) + req(length(rv$scan_list) > 0); df <- comb_df(); thr <- thresh_val() + pk <- df %>% group_by(chr, model) %>% summarise(mx=max(lod), .groups="drop") + p <- ggplot(pk, aes(x=chr, y=mx, color=model, group=model, text=paste0("Chr:",chr,"
",model,"
LOD:",round(mx,2)))) + + geom_line(linewidth=.8, alpha=.8) + geom_point(size=3) + + geom_hline(yintercept=thr, linetype="dashed", color="#b83232") + + scale_color_manual(values=setNames(unname(MODEL_COLORS[names(MODEL_LABELS)]), MODEL_LABELS)) + + labs(x="Chromosome", y="Peak LOD", color="Model") + + theme_minimal() + theme(panel.grid.minor=element_blank()) + ggplotly(p, tooltip="text") %>% layout(font=list(family="sans-serif")) }) - # ── CIRCOS ── + # ── CIRCOS — fixed: removed unsupported canvas params ──── circos_render <- function() { - req(rv$cross,length(rv$scan_list)>0) - df <- comb_df(); thr <- thresh_val(); mods <- names(rv$scan_list) - map <- pull.map(rv$cross); cnms <- names(map); clens <- sapply(map,max) - par(bg="white",mar=c(0,0,2,0)) + req(rv$cross, length(rv$scan_list) > 0) + df <- comb_df(); thr <- thresh_val(); mods <- names(rv$scan_list) + map <- pull.map(rv$cross); cnms <- names(map) + clens <- sapply(map, max) + par(bg="white", mar=c(1,1,3,1)) circos.clear() - circos.par("track.height"=0.08,"cell.padding"=c(0,0,0,0), - "gap.after"=rep(2,length(cnms)),"start.degree"=90,"clock.wise"=TRUE, - "background.color"="#ffffff",canvas.xlim=c(-1.25,1.25),canvas.ylim=c(-1.25,1.25)) - circos.initialize(factors=cnms,xlim=cbind(rep(0,length(cnms)),clens)) - circos.trackPlotRegion(ylim=c(0,1),track.height=0.05,bg.border=NA,bg.col="#f4f4f2", - panel.fun=function(x,y){ - chr<-get.cell.meta.data("sector.index") - circos.text(mean(get.cell.meta.data("xlim")),0.5,chr,facing="clockwise",niceFacing=TRUE,cex=.6,col="#2a2a27",font=2) + # FIX: removed canvas.xlim/canvas.ylim — not supported in all versions + circos.par( + "track.height" = 0.08, + "cell.padding" = c(0,0,0,0), + "gap.after" = rep(2, length(cnms)), + "start.degree" = 90, + "clock.wise" = TRUE + ) + circos.initialize(factors=cnms, xlim=cbind(rep(0,length(cnms)), clens)) + circos.trackPlotRegion(ylim=c(0,1), track.height=0.05, bg.border=NA, bg.col="#f4f4f2", + panel.fun=function(x,y) { + chr <- get.cell.meta.data("sector.index") + circos.text(mean(get.cell.meta.data("xlim")), 0.5, chr, + facing="clockwise", niceFacing=TRUE, cex=.6, col="#2a2a27", font=2) }) mpal <- c("#1a6b3a","#2d9e58","#c47c1a","#1a4a8a","#b83232","#7b3fa0","#1a8a8a","#8a5a1a","#555555","#e05c00") - for(mi in seq_along(mods)){ - m <- mods[mi]; mc <- mpal[((mi-1)%%length(mpal))+1]; mclt <- paste0(mc,"44") - sc <- rv$scan_list[[m]]; lc <- ncol(sc) - dfm <- data.frame(chr=as.character(sc$chr),pos=sc$pos,lod=sc[,lc],stringsAsFactors=FALSE) - dfm <- dfm[dfm$chr %in% cnms,]; mxl <- max(dfm$lod,na.rm=TRUE); if(mxl<.01) mxl <- 1 - circos.trackPlotRegion(ylim=c(0,mxl),track.height=0.07,bg.border="#e8e8e5",bg.col="#fafafa", - panel.fun=function(x,y){ - cs <- get.cell.meta.data("sector.index"); sub <- dfm[dfm$chr==cs,,drop=FALSE] - if(!nrow(sub)) return(); sub <- sub[order(sub$pos),] - xs <- c(sub$pos[1],sub$pos,sub$pos[nrow(sub)]); ys <- c(0,sub$lod,0) - circos.polygon(xs,ys,col=mclt,border=NA) - circos.lines(sub$pos,sub$lod,col=mc,lwd=1.2) - circos.lines(range(sub$pos),c(thr,thr),col="#b83232",lwd=.7,lty=2) - ss <- sub[sub$lod>=thr,] - if(nrow(ss)>0){ pk <- ss[which.max(ss$lod),]; circos.points(pk$pos,pk$lod,col="#b83232",pch=19,cex=.9) } + for (mi in seq_along(mods)) { + m <- mods[mi] + mc <- mpal[((mi-1) %% length(mpal)) + 1] + mclt <- paste0(mc,"44") + sc <- rv$scan_list[[m]]; lc <- ncol(sc) + dfm <- data.frame(chr=as.character(sc$chr), pos=sc$pos, lod=sc[,lc], stringsAsFactors=FALSE) + dfm <- dfm[dfm$chr %in% cnms, ] + mxl <- max(dfm$lod, na.rm=TRUE); if (mxl < .01) mxl <- 1 + circos.trackPlotRegion(ylim=c(0,mxl), track.height=0.07, bg.border="#e8e8e5", bg.col="#fafafa", + panel.fun=function(x,y) { + cs <- get.cell.meta.data("sector.index") + sub <- dfm[dfm$chr == cs, , drop=FALSE] + if (!nrow(sub)) return() + sub <- sub[order(sub$pos), ] + xs <- c(sub$pos[1], sub$pos, sub$pos[nrow(sub)]) + ys <- c(0, sub$lod, 0) + circos.polygon(xs, ys, col=mclt, border=NA) + circos.lines(sub$pos, sub$lod, col=mc, lwd=1.2) + circos.lines(range(sub$pos), c(thr,thr), col="#b83232", lwd=.7, lty=2) + ss <- sub[sub$lod >= thr, ] + if (nrow(ss) > 0) { + pk <- ss[which.max(ss$lod), ] + circos.points(pk$pos, pk$lod, col="#b83232", pch=19, cex=.9) + } } ) } - legend("bottomright",inset=c(-.04,-.04),legend=MODEL_LABELS[mods],col=mpal[seq_along(mods)],lwd=2.5,bty="n",cex=.65,text.col="#2a2a27",title="Models",title.col="#2a2a27") - title(main=paste("Circos QTL —",rv$pheno_name),line=-1,cex.main=.95,col.main="#0f0f0d",font.main=2) + legend("bottomright", legend=MODEL_LABELS[mods], col=mpal[seq_along(mods)], + lwd=2.5, bty="n", cex=.65, text.col="#2a2a27", title="Models", title.col="#2a2a27") + title(main=paste("Circos QTL -", rv$pheno_name), cex.main=.95, col.main="#0f0f0d", font.main=2) circos.clear() } output$pl_circos <- renderPlot({ circos_render() }, bg="white") - # ── RESULTS TABLE ── build_qtl_table <- reactive({ - req(length(rv$sig_qtl)>0); sd <- sig_df(); req(!is.null(sd),nrow(sd)>0) - rows <- lapply(seq_len(nrow(sd)),function(i){ - r <- sd[i,]; sc <- rv$scan_list[[r$model_id]]; if(is.null(sc)) return(NULL) - lc <- ncol(sc); sch <- sc[sc$chr==r$chr,]; hl <- r[,lc]-1.5 - left <- suppressWarnings(min(sch$pos[sch[,lc]>=hl],na.rm=TRUE)) - right <- suppressWarnings(max(sch$pos[sch[,lc]>=hl],na.rm=TRUE)) - lm <- tryCatch(find.marker(rv$cross,r$chr,left),error=function(e)"—") - rm <- tryCatch(find.marker(rv$cross,r$chr,right),error=function(e)"—") - pm <- tryCatch(find.marker(rv$cross,r$chr,r$pos),error=function(e) r$marker) + req(length(rv$sig_qtl) > 0); sd <- sig_df(); req(!is.null(sd), nrow(sd) > 0) + rows <- lapply(seq_len(nrow(sd)), function(i) { + r <- sd[i, ]; sc <- rv$scan_list[[r$model_id]]; if (is.null(sc)) return(NULL) + lc <- ncol(sc); sch <- sc[sc$chr == r$chr, ]; hl <- r[, lc] - 1.5 + left <- suppressWarnings(min(sch$pos[sch[, lc] >= hl], na.rm=TRUE)) + right <- suppressWarnings(max(sch$pos[sch[, lc] >= hl], na.rm=TRUE)) + lm <- tryCatch(find.marker(rv$cross, r$chr, left), error=function(e) "?") + rm <- tryCatch(find.marker(rv$cross, r$chr, right), error=function(e) "?") + pm <- tryCatch(find.marker(rv$cross, r$chr, r$pos), error=function(e) r$marker) data.frame( - Phenotype = rv$pheno_name, - Model = r$model, - Chr = r$chr, - Peak_pos_cM = round(r$pos,2), - Peak_Marker = pm, - LOD = round(r[,lc],3), - `PVE_%` = paste0(round(r$pve,1),"%"), - Left_cM = round(left,2), - Right_cM = round(right,2), - Left_Marker = lm, - Right_Marker= rm, - check.names = FALSE, - stringsAsFactors=FALSE + Phenotype=rv$pheno_name, Model=r$model, Chr=r$chr, + Peak_pos_cM=round(r$pos,2), Peak_Marker=pm, LOD=round(r[,lc],3), + PVE_pct=paste0(round(r$pve,1),"%"), + Left_cM=round(left,2), Right_cM=round(right,2), + Left_Marker=lm, Right_Marker=rm, + check.names=FALSE, stringsAsFactors=FALSE ) }) - do.call(rbind,Filter(Negate(is.null),rows)) + do.call(rbind, Filter(Negate(is.null), rows)) }) output$tbl_qtl <- renderDT({ tryCatch({ df <- build_qtl_table() - datatable(df,rownames=FALSE,extensions="Buttons", - options=list(dom="Bfrtip",buttons=c("copy","csv","excel"),pageLength=20,scrollX=TRUE, - columnDefs=list(list(className="dt-center",targets="_all"))))%>% - formatStyle("LOD",background=styleColorBar(range(df$LOD,na.rm=TRUE),"#e8f4ed")) - }, error=function(e) datatable(data.frame(Status="No significant QTL found"),options=list(dom="t"))) + datatable(df, rownames=FALSE, extensions="Buttons", + options=list(dom="Bfrtip", buttons=c("copy","csv","excel"), pageLength=20, scrollX=TRUE, + columnDefs=list(list(className="dt-center", targets="_all")))) %>% + formatStyle("LOD", background=styleColorBar(range(df$LOD, na.rm=TRUE),"#e8f4ed")) + }, error=function(e) datatable(data.frame(Status="No significant QTL found"), options=list(dom="t"))) }) output$tbl_full <- renderDT({ - req(length(rv$scan_list)>0); df <- comb_df() - df$lod <- round(df$lod,4); df$pos <- round(df$pos,2); df$sig <- df$lod>=thresh_val() - datatable(df[,c("chr","pos","marker","model","lod","sig")],rownames=FALSE, - options=list(pageLength=15,scrollX=TRUE,columnDefs=list(list(className="dt-center",targets="_all"))))%>% - formatStyle("sig",target="row",backgroundColor=styleEqual(c(TRUE,FALSE),c("#e8f4ed","white")))%>% - formatStyle("lod",fontFamily="'DM Mono',monospace") + req(length(rv$scan_list) > 0); df <- comb_df() + df$lod <- round(df$lod,4); df$pos <- round(df$pos,2); df$sig <- df$lod >= thresh_val() + datatable(df[, c("chr","pos","marker","model","lod","sig")], rownames=FALSE, + options=list(pageLength=15, scrollX=TRUE, + columnDefs=list(list(className="dt-center", targets="_all")))) %>% + formatStyle("sig", target="row", + backgroundColor=styleEqual(c(TRUE,FALSE), c("#e8f4ed","white"))) %>% + formatStyle("lod", fontFamily="monospace") }) - # ── DOWNLOADS ── output$dl_csv <- downloadHandler( filename=function() paste0("qtl_results_",Sys.Date(),".csv"), - content=function(f) tryCatch(write.csv(build_qtl_table(),f,row.names=FALSE),error=function(e) write.csv(data.frame(note="No results"),f)) + content=function(f) tryCatch(write.csv(build_qtl_table(),f,row.names=FALSE), error=function(e) write.csv(data.frame(note="No results"),f)) ) output$dl_tsv <- downloadHandler( filename=function() paste0("qtl_results_",Sys.Date(),".tsv"), - content=function(f) tryCatch(write.table(build_qtl_table(),f,sep="\t",row.names=FALSE),error=function(e) write.table(data.frame(note="No results"),f,sep="\t")) + content=function(f) tryCatch(write.table(build_qtl_table(),f,sep="\t",row.names=FALSE), error=function(e) write.table(data.frame(note="No results"),f,sep="\t")) ) output$dl_rds <- downloadHandler( filename=function() paste0("qtl_results_",Sys.Date(),".RData"), - content=function(f){ scan_list<-rv$scan_list;sig_qtl<-rv$sig_qtl;cross<-rv$cross;save(scan_list,sig_qtl,cross,file=f) } + content=function(f) { scan_list<-rv$scan_list; sig_qtl<-rv$sig_qtl; cross<-rv$cross; save(scan_list,sig_qtl,cross,file=f) } ) output$dl_full <- downloadHandler( filename=function() paste0("qtl_full_scan_",Sys.Date(),".csv"), - content=function(f) if(length(rv$scan_list)>0) write.csv(comb_df(),f,row.names=FALSE) else write.csv(data.frame(note="No scan"),f) + content=function(f) if (length(rv$scan_list)>0) write.csv(comb_df(),f,row.names=FALSE) else write.csv(data.frame(note="No scan"),f) ) output$dl_genome <- downloadHandler( filename=function() paste0("genome_scan_",Sys.Date(),".png"), - content=function(f){ + content=function(f) { req(length(rv$scan_list)>0); df <- comb_df(); thr <- thresh_val() - res <- cum_positions(df); df <- res$df; offsets <- res$offsets - p <- ggplot(df,aes(x=cum_pos,y=lod,color=model))+geom_line(linewidth=.7)+geom_hline(yintercept=thr,linetype="dashed",color="#b83232")+scale_color_manual(values=setNames(unname(MODEL_COLORS[names(MODEL_LABELS)]),MODEL_LABELS))+labs(x="Position (cM)",y="LOD",title=paste("Genome Scan —",rv$pheno_name))+theme_minimal(base_size=12) + res <- cum_positions(df); df <- res$df + p <- ggplot(df,aes(x=cum_pos,y=lod,color=model))+geom_line(linewidth=.7)+ + geom_hline(yintercept=thr,linetype="dashed",color="#b83232")+ + scale_color_manual(values=setNames(unname(MODEL_COLORS[names(MODEL_LABELS)]),MODEL_LABELS))+ + labs(x="Position (cM)",y="LOD",title=paste("Genome Scan -",rv$pheno_name))+theme_minimal(base_size=12) png(f,width=1400,height=500,res=120); print(p); dev.off() } ) output$dl_manh <- downloadHandler( filename=function() paste0("manhattan_",Sys.Date(),".png"), - content=function(f){ + content=function(f) { req(length(rv$scan_list)>0); df <- comb_df(); thr <- thresh_val() df1 <- df[df$model_id==names(rv$scan_list)[1],]; res <- cum_positions(df1); df1 <- res$df df1$sig <- df1$lod>=thr - p <- ggplot(df1,aes(x=cum_pos,y=lod,color=sig))+geom_point(size=1.5,alpha=.8)+geom_hline(yintercept=thr,linetype="dashed",color="#b83232")+scale_color_manual(values=c("FALSE"="#1a6b3a","TRUE"="#b83232"))+labs(x="Position (cM)",y="LOD",title="Manhattan Plot")+theme_minimal(base_size=12)+theme(legend.position="none") + p <- ggplot(df1,aes(x=cum_pos,y=lod,color=sig))+geom_point(size=1.5,alpha=.8)+ + geom_hline(yintercept=thr,linetype="dashed",color="#b83232")+ + scale_color_manual(values=c("FALSE"="#1a6b3a","TRUE"="#b83232"))+ + labs(x="Position (cM)",y="LOD",title="Manhattan Plot")+theme_minimal(base_size=12)+theme(legend.position="none") png(f,width=1400,height=500,res=120); print(p); dev.off() } ) output$dl_circos <- downloadHandler( filename=function() paste0("circos_",Sys.Date(),".png"), - content=function(f){ png(f,width=900,height=900,res=120,bg="white"); circos_render(); dev.off() } + content=function(f) { png(f,width=900,height=900,res=120,bg="white"); circos_render(); dev.off() } ) }