# ============================================================ # QTL MAPPING SUITE — Full Single-File Shiny Application # FIXED: HuggingFace compatible # ============================================================ suppressPackageStartupMessages({ library(shiny) library(shinyWidgets) library(shinyjs) library(shinycssloaders) library(qtl) library(ggplot2) library(plotly) library(DT) library(dplyr) library(tidyr) library(viridis) library(circlize) library(scales) }) # ── CSS (Google Fonts removed — safe system fonts only) ──── APP_CSS <- " *,*::before,*::after{box-sizing:border-box;margin:0;padding:0} :root{ --white:#ffffff;--off:#f8f8f6;--g50:#f4f4f2;--g100:#e8e8e5;--g200:#d0d0cc; --g400:#9a9a94;--g600:#5c5c58;--g800:#2a2a27;--ink:#1a1a18; --acc:#1a6b3a;--acclt:#e8f4ed;--accmd:#2d9e58; --amb:#c47c1a;--amblt:#fef3e2; --red:#b83232;--redlt:#fdeaea; --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:-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} .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-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)} .stpill .dot{width:6px;height:6px;border-radius:50%;background:var(--accmd);animation:pulse 2s infinite} @keyframes pulse{0%,100%{opacity:1}50%{opacity:.4}} .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)} .qtl-lay{display:flex;height:calc(100vh - 56px);overflow:hidden} .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} .nv{display:flex;align-items:center;gap:10px;padding:8px 14px;border-radius:var(--rsm);cursor:pointer;color:var(--g600);font-size:13px;font-weight:500;transition:var(--t);margin:1px 0;border:1.5px solid transparent} .nv:hover{background:var(--g50);color:var(--ink)} .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)} .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)}} .ph{margin-bottom:22px} .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{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} .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} .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-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)} .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} .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)} .fmt-table th{background:var(--g100);padding:4px 8px;text-align:left;color:var(--g600);font-weight:600} .fmt-table td{padding:3px 8px;color:var(--ink);border-bottom:1px solid var(--g100)} .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} .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-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-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} .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-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-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} .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)} .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} .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} .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)} .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{font-size:11px;color:var(--g400);font-style:italic;margin-top:4px} .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} ::-webkit-scrollbar{width:5px;height:5px} ::-webkit-scrollbar-thumb{background:var(--g200);border-radius:20px} ::-webkit-scrollbar-thumb:hover{background:var(--g400)} .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)} input[type=checkbox]{accent-color:var(--acc)} input[type=radio]{accent-color:var(--acc)} " # ── Model metadata ──────────────────────────────────────── MODEL_LABELS <- c( em="EM Algorithm", hk="Haley-Knott", mr="Marker Regression", im="Interval Mapping", cim="CIM", ehk="Extended HK", imp="Imputation", hkperm="HK+Permutation", scanone_np="Non-parametric", mqm="MQM" ) MODEL_COLORS <- c( em="#1a6b3a", hk="#2d9e58", mr="#c47c1a", im="#1a4a8a", cim="#b83232", ehk="#7b3fa0", imp="#1a8a8a", hkperm="#8a5a1a", scanone_np="#555555", mqm="#e05c00" ) # ── 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 df$cum_pos <- df[[pos_col]] + offsets[df[[chr_col]]] list(df=df, offsets=offsets, chrs=chrs) } 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))) 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 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) 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.") geno_aln <- geno_num[common_ids, , drop=FALSE] pheno_aln <- pheno_raw[common_ids, -1, drop=FALSE] n_ind <- length(common_ids) uniq_chrs <- unique(chr_clean) 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]; names(mk_pos) <- marker_names[idx] map[[ch]] <- mk_pos } 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] storage.mode(mat) <- "integer" geno_list[[ch]] <- list(data=mat, map=map[[ch]]) class(geno_list[[ch]]) <- "A" } 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) 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 <- fluidPage( useShinyjs(), tags$head( tags$style(APP_CSS), tags$script(HTML(" $(document).on('click','.nv',function(){ var pg=$(this).data('page'); if(!pg)return; $('.nv').removeClass('active'); $(this).addClass('active'); $('.pg').removeClass('active'); $('#pg-'+pg).addClass('active'); Shiny.setInputValue('active_page',pg,{priority:'event'}); }); $(document).on('click','.qtab',function(){ var g=$(this).data('group'),t=$(this).data('tab'); $('.qtab[data-group='+g+']').removeClass('active'); $(this).addClass('active'); Shiny.setInputValue('tab_'+g,t,{priority:'event'}); }); $(document).on('click','.mc',function(){ $(this).toggleClass('sel'); var sel=[];$('.mc.sel').each(function(){sel.push($(this).data('model'));}); Shiny.setInputValue('sel_models',sel,{priority:'event'}); }); ")) ), 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="qtl-lay", 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","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","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","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="qtl-main", # ── 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="card", 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( div(class="fmt-title","GENOTYPE CSV"), 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","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")) ) ) ), div( div(class="fmt-title","PHENOTYPE CSV"), 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")), 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","i",div("Sample IDs must match exactly between the two files.")) ) ) ) ) ), div(class="g2", div(class="card", div(class="ch", div(div(class="ct","Genotype File"), div(class="cst","CSV with chr/pos rows")), uiOutput("geno_badge") ), div(class="cb", div(class="uzone", 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="tip","Genotype codes: 0=AA, 1=AB, 2=BB, -1=missing") ) ), div(class="card", div(class="ch", div(div(class="ct","Phenotype File"), div(class="cst","CSV with trait columns")), uiOutput("pheno_badge") ), div(class="cb", div(class="uzone", 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="tip","First column = sample ID, remaining columns = trait values") ) ) ), div(class="card", div(class="ch", div(div(class="ct","Cross Settings & Load"))), div(class="cb", div(class="g2", 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( 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%")) ) ), div(class="br", 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(class="ph", div(class="pt","Data Explorer"), div(class="ps","Inspect genotype, phenotype and map structure")), div(class="g4", uiOutput("stat_tiles")), br(), div(class="qtabs", div(class="qtab active",`data-group`="ex",`data-tab`="pheno","Phenotype"), div(class="qtab",`data-group`="ex",`data-tab`="map","Genetic Map"), div(class="qtab",`data-group`="ex",`data-tab`="miss","Missing Data"), div(class="qtab",`data-group`="ex",`data-tab`="gfreq","Genotype Freq") ), uiOutput("explore_content") ), # ── CONFIG ── 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", div(class="ch", div(div(class="ct","Phenotype & Scan Settings"))), div(class="cb", div(class="fm-g", label(class="fl","Phenotype"), uiOutput("pheno_sel")), div(class="fm-g", label(class="fl","Chromosomes to Scan"), uiOutput("chr_sel")), div(class="fm-g", label(class="fl","Step Size (cM)"), sliderInput("step_sz",NULL,min=1,max=10,value=2,step=1,width="100%")), div(class="fm-g", label(class="fl","Error Probability"), sliderInput("err_prob",NULL,min=0.001,max=0.05,value=0.001,step=0.001,width="100%")) ) ), div(class="card", div(class="ch", div(div(class="ct","QTL Models"), div(class="cst","Click chips to select/deselect"))), div(class="cb", div(class="fm-g", label(class="fl","Available Models"), div(class="mchips", div(class="mc sel",`data-model`="em","EM Algorithm"), div(class="mc sel",`data-model`="hk","Haley-Knott"), div(class="mc",`data-model`="mr","Marker Regression"), div(class="mc",`data-model`="im","Interval Mapping"), div(class="mc",`data-model`="cim","CIM"), div(class="mc",`data-model`="ehk","Extended HK"), div(class="mc",`data-model`="imp","Imputation"), div(class="mc",`data-model`="hkperm","HK+Permutation"), div(class="mc",`data-model`="scanone_np","Non-parametric"), div(class="mc",`data-model`="mqm","MQM") ) ), div(class="fm-g", label(class="fl","LOD Threshold"), numericInput("lod_thr",NULL,value=3.0,min=1,max=10,step=0.1,width="100%")), div(class="fm-g", label(class="fl","Permutations (0=skip)"), numericInput("n_perm",NULL,value=0,min=0,max=1000,step=100,width="100%")), div(class="fm-g", label(class="fl","Imputations (for imp model)"), numericInput("n_imp",NULL,value=32,min=8,max=128,step=8,width="100%")) ) ) ) ), # ── RUN ── 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(), div(class="br", actionButton("run_scan","Run QTL Scan",class="btn-p"), actionButton("clr_res","Clear",class="btn-s") ), br(), uiOutput("prog_ui"), uiOutput("log_ui") ) ) ), # ── GENOME SCAN ── 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(class="cb", withSpinner(plotlyOutput("pl_genome",height="400px"),color="#1a6b3a")) ), div(class="g2", div(class="card", div(class="ch", div(div(class="ct","Per-Chromosome Max LOD"))), div(class="cb", withSpinner(plotlyOutput("pl_chr_bar",height="280px"),color="#1a6b3a")) ), div(class="card", 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")), div(class="card", div(class="ch", 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="cb", withSpinner(plotlyOutput("pl_interval",height="300px"),color="#1a6b3a")) ), div(class="card", 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(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="cb", withSpinner(plotlyOutput("pl_pve",height="300px"),color="#1a6b3a")) ), div(class="card", 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 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") ) ) ), # ── COMPARE ── 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 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"), 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="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")), div(class="card", div(class="ch", 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;", withSpinner(plotOutput("pl_circos",width="680px",height="680px"),color="#1a6b3a") ) ) ) ), # ── TABLE ── div(id="pg-table", class="pg", div(class="ph", div(class="phr", 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") ) ) ), div(class="card", 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", div(class="ch", div(div(class="ct","Full Scan Output"))), div(class="cb", withSpinner(DTOutput("tbl_full"),color="#1a6b3a")) ) ) ) ) ) # ── 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 ) add_log <- function(msg) { rv$log_msgs <- c(rv$log_msgs, paste0("[",format(Sys.time(),"%H:%M:%S"),"] ",msg)) } 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") }) 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") }) observeEvent(input$load_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 (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) { rv$load_ok <- FALSE rv$load_msg <- paste("Error:", e$message) showNotification(paste("Error:", e$message), type="error") }) }) }) 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, { tryCatch({ 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)," 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) { rv$geno_ok <- FALSE rv$pheno_ok <- FALSE rv$load_ok <- FALSE rv$load_msg <- paste("Load error:", e$message) add_log(paste("ERROR:", e$message)) showNotification(paste("Load error:", e$message), type="error", duration=8) }) }) }) output$upload_status_msg <- renderUI({ req(!is.null(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))) }) output$upload_summary <- renderUI({ req(rv$cross); cr <- rv$cross div(class="card", div(class="ch", div(div(class="ct","Dataset Summary"))), div(class="cb", div(class="g4", div(class="st acc", div(class="st-l","Individuals"), div(class="st-v", nind(cr))), div(class="st", div(class="st-l","Markers"), div(class="st-v", totmar(cr))), div(class="st", div(class="st-l","Chromosomes"), div(class="st-v", nchr(cr))), div(class="st", div(class="st-l","Phenotypes"), div(class="st-v", nphe(cr))) ), br(), div(class="tip", paste("Phenotypes:", paste(phenames(cr), collapse=", "))) ) ) }) output$stat_tiles <- renderUI({ req(rv$cross); cr <- rv$cross tagList( div(class="st acc", div(class="st-l","Individuals"), div(class="st-v", nind(cr))), div(class="st", div(class="st-l","Markers"), div(class="st-v", totmar(cr))), div(class="st", div(class="st-l","Chromosomes"), div(class="st-v", nchr(cr))), div(class="st", div(class="st-l","Phenotypes"), div(class="st-v", nphe(cr))) ) }) output$explore_content <- renderUI({ tab <- if (is.null(input$tab_ex)) "pheno" else input$tab_ex req(rv$cross) if (tab == "pheno") { div(class="card", 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") { 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") { 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"))) } }) 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") }) 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[!is.na(phe)]) # FIX: use stat(density) instead of after_stat(density) for compatibility p <- ggplot(df, aes(x=y)) + 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="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="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="sans-serif")) }) output$pl_ex_gf <- renderPlotly({ req(rv$cross); gt <- pull.geno(rv$cross) 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)) # 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="sans-serif")) }) output$pheno_sel <- renderUI({ 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) }) 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 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]))) ) }) 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...")) } else { 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")), div(class="cb", 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")) ) ) }) 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 { 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, { tryCatch({ 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...") rv$cross <- sim.geno(rv$cross, n.draws=n_imp, step=step, error.prob=ep) } for (i in seq_along(mods)) { m <- mods[i] add_log(paste("Model:", MODEL_LABELS[m], "...")) incProgress(0.8/length(mods), detail=MODEL_LABELS[m]) res <- tryCatch({ switch(m, em = scanone(rv$cross, pheno.col=phe_col, method="em"), hk = scanone(rv$cross, pheno.col=phe_col, method="hk"), mr = scanone(rv$cross, pheno.col=phe_col, method="mr"), im = scanone(rv$cross, pheno.col=phe_col, method="em"), ehk = scanone(rv$cross, pheno.col=phe_col, method="ehk"), imp = scanone(rv$cross, pheno.col=phe_col, method="imp"), 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")), scanone(rv$cross, pheno.col=phe_col, method="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) { 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(" OK", MODEL_LABELS[m], "peaks:", nrow(sig))) } 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))) } rv$running <- FALSE incProgress(0.1) add_log(paste("All", length(mods), "models completed.")) showNotification("Scan complete!", type="message", duration=3) }, error=function(e) { rv$running <- FALSE add_log(paste("FATAL:", e$message)) showNotification(paste("Error:", e$message), type="error") }) }) }) observeEvent(input$clr_res, { rv$scan_list <- list(); rv$sig_qtl <- list(); rv$log_msgs <- character(0) }) comb_df <- reactive({ 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), 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) }) thresh_val <- reactive({ if (is.null(input$lod_thr)) 3.0 else input$lod_thr }) 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") }) 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="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="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="sans-serif")) }) 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], ] 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="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() # 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), ] })) 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="sans-serif")) }) output$eff_chr_ui <- renderUI({ 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="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 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])]) 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="sans-serif")) }) output$peak_sel <- renderUI({ 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%") }) output$pl_violin <- renderPlotly({ 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) 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")) }) output$pl_heatmap <- renderPlotly({ 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="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[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="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="sans-serif")) }) # ── 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(1,1,3,1)) circos.clear() # 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) } } ) } 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") 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) 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_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)) }) 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"))) }) 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="monospace") }) 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)) ) 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")) ) 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) } ) 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) ) output$dl_genome <- downloadHandler( filename=function() paste0("genome_scan_",Sys.Date(),".png"), content=function(f) { req(length(rv$scan_list)>0); df <- comb_df(); thr <- thresh_val() 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) { 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") 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() } ) } shinyApp(ui=ui, server=server)