diff --git "a/app.R" "b/app.R" --- "a/app.R" +++ "b/app.R" @@ -1,2067 +1,1021 @@ -# ============================================================================= -# QTL MAPPER PRO — Complete Single-File Shiny Application -# ============================================================================= -# Required packages: -# install.packages(c("shiny","shinydashboard","shinyWidgets","shinyjs", -# "shinycssloaders","qtl","ggplot2","plotly","DT","dplyr","tidyr", -# "viridis","RColorBrewer","reshape2","ggrepel","circlize","scales")) -# ============================================================================= - -library(shiny) -library(shinyWidgets) -library(shinyjs) -library(shinycssloaders) -library(qtl) -library(ggplot2) -library(plotly) -library(DT) -library(dplyr) -library(tidyr) -library(viridis) -library(RColorBrewer) -library(reshape2) -library(scales) - -# ── Inline CSS ──────────────────────────────────────────────────────────────── -app_css <- " -@import url('https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@300;400;600&family=Sora:wght@300;400;600;700&display=swap'); - -:root { - --bg-deep: #08111f; - --bg-panel: #0f1c2e; - --bg-card: #162033; - --bg-hover: #1e2d45; - --accent1: #00d4ff; - --accent2: #a3e635; - --accent3: #f97316; - --accent4: #a78bfa; - --accent5: #ec4899; - --text-pri: #e2e8f0; - --text-muted: #64748b; - --text-dim: #94a3b8; - --border: #1e3a5f; - --radius: 10px; - --font-mono: 'JetBrains Mono', monospace; - --font-main: 'Sora', sans-serif; -} -* { box-sizing: border-box; margin: 0; padding: 0; } -body { - font-family: var(--font-main); - background: var(--bg-deep); - color: var(--text-pri); - min-height: 100vh; -} -::-webkit-scrollbar { width: 5px; height: 5px; } -::-webkit-scrollbar-track { background: var(--bg-panel); } -::-webkit-scrollbar-thumb { background: var(--border); border-radius: 3px; } -::-webkit-scrollbar-thumb:hover { background: var(--accent1); } - -/* ── Header */ -.app-header { - background: linear-gradient(135deg, #0a1628 0%, #0f2040 50%, #0a1628 100%); - border-bottom: 1px solid var(--border); - padding: 0 28px; - height: 64px; - display: flex; - align-items: center; - justify-content: space-between; - position: sticky; top: 0; z-index: 1000; - box-shadow: 0 2px 20px rgba(0,212,255,0.08); -} -.header-brand { - display: flex; align-items: center; gap: 12px; -} -.header-logo { - width: 38px; height: 38px; - background: linear-gradient(135deg, var(--accent1), var(--accent4)); - border-radius: 8px; - display: flex; align-items: center; justify-content: center; - font-size: 18px; font-weight: 700; color: #000; - font-family: var(--font-mono); -} -.header-title { - font-size: 1.25rem; font-weight: 700; - background: linear-gradient(90deg, var(--accent1), var(--accent4)); - -webkit-background-clip: text; -webkit-text-fill-color: transparent; - letter-spacing: -0.02em; -} -.header-sub { font-size: 0.72rem; color: var(--text-muted); font-family: var(--font-mono); } -.header-badges { display: flex; gap: 8px; } -.badge-pill { - background: rgba(0,212,255,0.1); border: 1px solid rgba(0,212,255,0.25); - color: var(--accent1); padding: 3px 10px; border-radius: 20px; - font-size: 0.7rem; font-family: var(--font-mono); +# ============================================================ +# QTL MAPPING SUITE — Full Single-File Shiny Application +# 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 +# ============================================================ + +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 ───────────────────────────────────────────────────── +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; + --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:'DM Sans',sans-serif;--fm:'DM Mono',monospace;--fs:'Fraunces',serif; + --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} +.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)} + +/* 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} +.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)} + +/* 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} +.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-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:36px 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:32px;margin-bottom:10px} +.uzone-t{font-size:14px;font-weight:600;color:var(--ink)} +.uzone-s{font-size:12px;color:var(--g400);margin-top:5px} +.uzone .shiny-input-container{margin:0} + +/* 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.focus{border-color:var(--acc)!important;box-shadow:0 0 0 3px rgba(26,107,58,.1)!important} +input[type=number]{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]: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: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: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: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)} + +/* 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} +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)} +input[type=checkbox]{accent-color:var(--acc)} +input[type=radio]{accent-color:var(--acc)} +" -/* ── Layout */ -.app-body { display: flex; min-height: calc(100vh - 64px); } - -/* ── Sidebar */ -.app-sidebar { - width: 270px; min-width: 270px; - background: var(--bg-panel); - border-right: 1px solid var(--border); - padding: 20px 14px; - overflow-y: auto; - display: flex; flex-direction: column; gap: 6px; -} -.nav-section-label { - font-size: 0.65rem; font-weight: 600; letter-spacing: 0.12em; - color: var(--text-muted); text-transform: uppercase; - padding: 12px 10px 6px; font-family: var(--font-mono); -} -.nav-btn { - width: 100%; background: transparent; border: 1px solid transparent; - color: var(--text-dim); padding: 9px 12px; - border-radius: var(--radius); cursor: pointer; - display: flex; align-items: center; gap: 10px; - font-family: var(--font-main); font-size: 0.82rem; font-weight: 500; - transition: all 0.18s; text-align: left; -} -.nav-btn:hover { background: var(--bg-hover); color: var(--text-pri); border-color: var(--border); } -.nav-btn.active { - background: rgba(0,212,255,0.1); color: var(--accent1); - border-color: rgba(0,212,255,0.3); -} -.nav-icon { font-size: 1rem; width: 20px; text-align: center; } - -/* ── Main Content */ -.app-main { flex: 1; padding: 24px; overflow-y: auto; max-width: 100%; } - -/* ── Cards */ -.card { - background: var(--bg-card); - border: 1px solid var(--border); - border-radius: var(--radius); - padding: 20px; - margin-bottom: 18px; -} -.card-header { - display: flex; align-items: center; gap: 10px; - margin-bottom: 16px; padding-bottom: 12px; - border-bottom: 1px solid var(--border); -} -.card-icon { - width: 32px; height: 32px; - border-radius: 7px; display: flex; align-items: center; justify-content: center; - font-size: 15px; -} -.card-title { font-size: 0.95rem; font-weight: 600; color: var(--text-pri); } -.card-subtitle { font-size: 0.72rem; color: var(--text-muted); margin-top: 2px; } -.card-icon-cyan { background: rgba(0,212,255,0.12); color: var(--accent1); } -.card-icon-lime { background: rgba(163,230,53,0.12); color: var(--accent2); } -.card-icon-coral { background: rgba(249,115,22,0.12); color: var(--accent3); } -.card-icon-purple{ background: rgba(167,139,250,0.12); color: var(--accent4); } -.card-icon-pink { background: rgba(236,72,153,0.12); color: var(--accent5); } - -/* ── Stat boxes */ -.stat-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(160px,1fr)); gap: 14px; margin-bottom: 18px; } -.stat-box { - background: var(--bg-card); border: 1px solid var(--border); - border-radius: var(--radius); padding: 16px 18px; - position: relative; overflow: hidden; -} -.stat-box::before { - content: ''; position: absolute; top: 0; left: 0; right: 0; height: 2px; -} -.stat-box.c1::before { background: var(--accent1); } -.stat-box.c2::before { background: var(--accent2); } -.stat-box.c3::before { background: var(--accent3); } -.stat-box.c4::before { background: var(--accent4); } -.stat-box.c5::before { background: var(--accent5); } -.stat-label { font-size: 0.68rem; color: var(--text-muted); text-transform: uppercase; letter-spacing: 0.08em; font-family: var(--font-mono); } -.stat-value { font-size: 1.5rem; font-weight: 700; color: var(--text-pri); margin-top: 4px; font-family: var(--font-mono); } -.stat-sub { font-size: 0.7rem; color: var(--text-muted); margin-top: 2px; } - -/* ── Form controls */ -.ctrl-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 14px; } -.form-group { display: flex; flex-direction: column; gap: 5px; } -.form-label { font-size: 0.72rem; color: var(--text-dim); font-weight: 500; font-family: var(--font-mono); } - -.form-control, .selectize-input, input[type=number], input[type=text], select { - background: var(--bg-panel) !important; - border: 1px solid var(--border) !important; - color: var(--text-pri) !important; - border-radius: var(--radius-sm) !important; - padding: 7px 10px !important; - font-family: var(--font-main) !important; - font-size: 0.82rem !important; -} -.selectize-input { padding: 6px 10px !important; min-height: 34px !important; } -.selectize-dropdown { background: var(--bg-panel) !important; border: 1px solid var(--border) !important; color: var(--text-pri) !important; } -.selectize-dropdown .option:hover { background: var(--bg-hover) !important; color: var(--accent1) !important; } - -.shiny-input-container label { font-size: 0.72rem; color: var(--text-dim); font-family: var(--font-mono); } -.irs--shiny .irs-bar { background: var(--accent1) !important; } -.irs--shiny .irs-handle { background: var(--accent1) !important; border-color: var(--accent1) !important; } -.irs--shiny .irs-single { background: var(--accent1) !important; } -.irs-line { background: var(--border) !important; } - -/* ── Buttons */ -.btn-run { - background: linear-gradient(135deg, var(--accent1), #0099cc); - border: none; color: #000; font-weight: 700; - padding: 10px 24px; border-radius: var(--radius); - font-family: var(--font-main); font-size: 0.85rem; - cursor: pointer; transition: all 0.2s; - display: inline-flex; align-items: center; gap: 8px; -} -.btn-run:hover { transform: translateY(-1px); box-shadow: 0 4px 16px rgba(0,212,255,0.35); } -.btn-dl { - background: rgba(163,230,53,0.12); border: 1px solid rgba(163,230,53,0.3); - color: var(--accent2); font-weight: 600; - padding: 8px 18px; border-radius: var(--radius); - font-family: var(--font-main); font-size: 0.82rem; - cursor: pointer; transition: all 0.2s; - display: inline-flex; align-items: center; gap: 7px; -} -.btn-dl:hover { background: rgba(163,230,53,0.2); } -.btn-sec { - background: rgba(167,139,250,0.1); border: 1px solid rgba(167,139,250,0.3); - color: var(--accent4); padding: 8px 16px; border-radius: var(--radius); - font-family: var(--font-main); font-size: 0.82rem; - cursor: pointer; transition: all 0.2s; - display: inline-flex; align-items: center; gap: 7px; -} -.btn-sec:hover { background: rgba(167,139,250,0.2); } -.btn-row { display: flex; gap: 10px; flex-wrap: wrap; align-items: center; margin-top: 14px; } - -/* ── Tabs */ -.tab-bar { display: flex; gap: 4px; margin-bottom: 18px; flex-wrap: wrap; } -.tab-btn { - background: var(--bg-panel); border: 1px solid var(--border); - color: var(--text-dim); padding: 7px 16px; border-radius: 20px; - font-size: 0.78rem; cursor: pointer; transition: all 0.18s; - font-family: var(--font-main); font-weight: 500; -} -.tab-btn:hover { color: var(--text-pri); border-color: var(--text-dim); } -.tab-btn.active { background: rgba(0,212,255,0.12); color: var(--accent1); border-color: rgba(0,212,255,0.35); } - -/* ── Plot containers */ -.plot-wrap { - background: var(--bg-panel); border: 1px solid var(--border); - border-radius: var(--radius); padding: 4px; - min-height: 380px; -} -.plot-grid-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; } -.plot-grid-3 { display: grid; grid-template-columns: repeat(3, 1fr); gap: 14px; } - -/* ── Table */ -.dataTables_wrapper { color: var(--text-pri) !important; } -table.dataTable { background: transparent !important; color: var(--text-pri) !important; border-color: var(--border) !important; } -table.dataTable thead th { background: var(--bg-panel) !important; color: var(--accent1) !important; border-color: var(--border) !important; font-family: var(--font-mono) !important; font-size: 0.78rem !important; } -table.dataTable tbody tr { background: transparent !important; } -table.dataTable tbody tr:hover td { background: var(--bg-hover) !important; } -table.dataTable tbody td { border-color: var(--border) !important; font-size: 0.8rem !important; font-family: var(--font-mono) !important; } -.dataTables_filter input, .dataTables_length select { background: var(--bg-panel) !important; border: 1px solid var(--border) !important; color: var(--text-pri) !important; border-radius: 6px !important; padding: 4px 8px !important; } -.dataTables_info, .dataTables_paginate { color: var(--text-muted) !important; font-size: 0.75rem !important; } -.paginate_button { color: var(--text-dim) !important; background: transparent !important; border: 1px solid transparent !important; border-radius: 5px !important; } -.paginate_button.current, .paginate_button:hover { background: var(--bg-hover) !important; color: var(--accent1) !important; border-color: var(--border) !important; } - -/* ── Progress / loading */ -.shiny-notification { background: var(--bg-card); border: 1px solid var(--border); color: var(--text-pri); border-radius: var(--radius); } -.progress-bar { background: var(--accent1) !important; } - -/* ── Alert boxes */ -.alert-info-box { - background: rgba(0,212,255,0.07); border-left: 3px solid var(--accent1); - border-radius: 0 var(--radius) var(--radius) 0; - padding: 12px 16px; font-size: 0.82rem; color: var(--text-dim); - margin-bottom: 14px; -} -.alert-warn-box { - background: rgba(249,115,22,0.07); border-left: 3px solid var(--accent3); - border-radius: 0 var(--radius) var(--radius) 0; - padding: 12px 16px; font-size: 0.82rem; color: var(--text-dim); - margin-bottom: 14px; -} +# ── 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" +) -/* ── Upload area */ -.upload-zone { - border: 2px dashed var(--border); border-radius: var(--radius); - padding: 28px; text-align: center; - transition: all 0.2s; cursor: pointer; +# ── 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) } -.upload-zone:hover { border-color: var(--accent1); background: rgba(0,212,255,0.04); } -.upload-zone .upload-icon { font-size: 2rem; margin-bottom: 8px; } -.upload-zone p { font-size: 0.82rem; color: var(--text-muted); margin: 4px 0; } -.upload-zone .upload-title { font-size: 0.9rem; font-weight: 600; color: var(--text-dim); } - -/* ── Chromosome chip */ -.chr-chip { - display: inline-flex; align-items: center; gap: 5px; - background: rgba(167,139,250,0.1); border: 1px solid rgba(167,139,250,0.25); - color: var(--accent4); padding: 3px 9px; border-radius: 12px; - font-size: 0.72rem; font-family: var(--font-mono); - margin: 2px; -} - -/* ── LOD legend chip */ -.lod-hi { color: var(--accent3); font-weight: 700; font-family: var(--font-mono); } -.lod-med { color: var(--accent2); font-weight: 600; font-family: var(--font-mono); } - -/* ── Hidden panel */ -.page-panel { display: none; } -.page-panel.active { display: block; } -/* ── Responsive */ -@media (max-width: 900px) { - .app-sidebar { width: 56px; min-width: 56px; padding: 12px 6px; } - .nav-btn span:not(.nav-icon) { display: none; } - .plot-grid-2, .plot-grid-3 { grid-template-columns: 1fr; } - .stat-grid { grid-template-columns: 1fr 1fr; } +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) } -" -# ── UI ──────────────────────────────────────────────────────────────────────── +# ── UI ──────────────────────────────────────────────────────── ui <- fluidPage( useShinyjs(), tags$head( - tags$style(HTML(app_css)), + tags$style(APP_CSS), tags$script(HTML(" - $(document).on('click', '.nav-btn', function() { - $('.nav-btn').removeClass('active'); - $(this).addClass('active'); - var pg = $(this).data('page'); - $('.page-panel').removeClass('active'); - $('#page-' + pg).addClass('active'); + $(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', '.tab-btn', function() { - var grp = $(this).data('group'); - $('.tab-btn[data-group=\"' + grp + '\"]').removeClass('active'); - $(this).addClass('active'); - var tab = $(this).data('tab'); - $('.tab-pane[data-group=\"' + grp + '\"]').hide(); - $('#tab-' + grp + '-' + tab).show(); + $(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'}); }); ")) ), - # Header - div(class = "app-header", - div(class = "header-brand", - div(class = "header-logo", "Q"), - div( - div(class = "header-title", "QTL Mapper Pro"), - div(class = "header-sub", "Quantitative Trait Loci Analysis Suite v2.0") - ) - ), - div(class = "header-badges", - span(class = "badge-pill", "10 Models"), - span(class = "badge-pill", "10+ Plots"), - span(class = "badge-pill", "Circos") + # TOP BAR + div(class="qtl-top", + div(class="tlmark","Q"), + span(class="tlname","QTL Mapping Suite"), + span(class="tlver","v2.0"), + 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 = "app-body", - - # Sidebar Navigation - div(class = "app-sidebar", - div(class = "nav-section-label", "Data"), - tags$button(class = "nav-btn active", `data-page` = "data", - span(class = "nav-icon", "📂"), span("Data Input")), - tags$button(class = "nav-btn", `data-page` = "summary", - span(class = "nav-icon", "📊"), span("Summary")), - - div(class = "nav-section-label", "Analysis"), - tags$button(class = "nav-btn", `data-page` = "models", - span(class = "nav-icon", "⚙️"), span("QTL Models")), - tags$button(class = "nav-btn", `data-page` = "scan", - span(class = "nav-icon", "🔬"), span("Genome Scan")), - tags$button(class = "nav-btn", `data-page` = "interval", - span(class = "nav-icon", "📍"), span("Interval Map")), - - div(class = "nav-section-label", "Visualization"), - tags$button(class = "nav-btn", `data-page` = "plots", - span(class = "nav-icon", "🎨"), span("QTL Plots")), - tags$button(class = "nav-btn", `data-page` = "circos", - span(class = "nav-icon", "🔵"), span("Circos Plot")), - tags$button(class = "nav-btn", `data-page` = "compare", - span(class = "nav-icon", "🔀"), span("Model Compare")), - - div(class = "nav-section-label", "Results"), - tags$button(class = "nav-btn", `data-page` = "results", - span(class = "nav-icon", "📋"), span("QTL Table")), - tags$button(class = "nav-btn", `data-page` = "export", - span(class = "nav-icon", "💾"), span("Export")) + 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")) + ), + 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")) + ), + 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")) + ), + div(class="sb-foot","QTL Suite © 2024") ), - # Main Content - div(class = "app-main", - - # ── PAGE: Data Input ────────────────────────────────────────────────── - div(id = "page-data", class = "page-panel active", - div(class = "card", - div(class = "card-header", - div(class = "card-icon card-icon-cyan", "📂"), - div(div(class = "card-title", "Data Input"), - div(class = "card-subtitle", "Upload cross data or use bundled example datasets")) - ), - div(class = "ctrl-grid", - div(class = "form-group", - div(class = "form-label", "DATA SOURCE"), - selectInput("data_source", NULL, - choices = c("Example: Hyper (BC)" = "hyper", - "Example: Listeria (BC)" = "listeria", - "Example: Fake F2" = "fake_f2", - "Upload CSV/RData" = "upload"), - selected = "hyper") - ), - div(class = "form-group", - div(class = "form-label", "CROSS TYPE"), - selectInput("cross_type", NULL, - choices = c("Backcross (BC)" = "bc", - "F2 Intercross" = "f2", - "RIL (selfing)" = "riself", - "4-way cross" = "4way"), - selected = "bc") + # MAIN + div(class="qtl-main", + + # ── UPLOAD ── + div(id="pg-upload",class="pg active", + div(class="ph", div(class="pt","Upload Cross Data"), div(class="ps","Import your QTL cross data in R/qtl CSV format")), + div(class="g2", + div(class="card", + div(class="ch", div(div(class="ct","Genotype / Phenotype File"), div(class="cst","CSV in R/qtl format"))), + div(class="cb", + div(class="uzone", + div(class="uzone-ic","🧬"), + div(class="uzone-t","Drop CSV file here"), + div(class="uzone-s","R/qtl format — id, phenotype(s), marker columns"), + fileInput("geno_file",NULL,accept=c(".csv",".CSV"),buttonLabel="Browse",placeholder="No file selected") + ), + div(class="tip","First column=ID, next=phenotype(s), rest=markers") ) ), - div(id = "upload_zone_div", style = "display:none; margin-top:14px;", - div(class = "upload-zone", - fileInput("file_upload", NULL, accept = c(".csv",".rdata",".RData",".rqtl"), - placeholder = "Upload .csv or .RData cross file"), - div(class = "upload-icon", "📁"), - div(class = "upload-title", "Drop cross file here"), - p("Supported: R/qtl CSV format, .RData with 'cross' object") + div(class="card", + div(class="ch", div(div(class="ct","Cross Settings"), div(class="cst","Population type"))), + div(class="cb", + div(class="fm-g", label(class="fl","Cross Type"), + selectInput("cross_type",NULL,choices=c("F2 Intercross"="f2","Backcross"="bc","RIL by selfing"="riself","RIL by sibling"="risib","Doubled Haploid"="dh"),selected="f2",width="100%")), + div(class="fm-g", label(class="fl","Missing Code"), textInput("miss_code",NULL,value="NA",width="100%")), + div(class="fm-g", label(class="fl","Genotype Codes (comma-sep)"), textInput("geno_codes",NULL,value="A,H,B",width="100%")), + div(class="br", + actionButton("load_data","Load Data",class="btn-p"), + actionButton("load_demo","Load Listeria Demo",class="btn-s") + ) ) - ), - div(class = "btn-row", - actionButton("load_data", "Load Data", class = "btn-run", - icon = icon("play")), - actionButton("run_all", "Run All Models", class = "btn-run", - icon = icon("rocket")), - actionButton("calc_genoprob", "Calc Genoprob", class = "btn-sec", - icon = icon("calculator")) ) ), - uiOutput("data_stats_ui") + uiOutput("upload_summary") ), - # ── PAGE: Summary ───────────────────────────────────────────────────── - div(id = "page-summary", class = "page-panel", - div(class = "card", - div(class = "card-header", - div(class = "card-icon card-icon-lime", "📊"), - div(div(class = "card-title", "Cross Summary"), - div(class = "card-subtitle", "Genotype and marker statistics")) - ), - uiOutput("cross_summary_ui") + # ── 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") ), - div(class = "plot-grid-2", - div(class = "card", - div(class = "card-header", - div(class = "card-icon card-icon-cyan", "🗺️"), - div(div(class = "card-title", "Genetic Map"), - div(class = "card-subtitle", "Marker positions by chromosome")) - ), - div(class = "plot-wrap", - withSpinner(plotlyOutput("plot_genetic_map", height = "350px"), - color = "#00d4ff", type = 6)) - ), - div(class = "card", - div(class = "card-header", - div(class = "card-icon card-icon-coral", "📦"), - div(div(class = "card-title", "Phenotype Distribution"), - div(class = "card-subtitle", "Histogram + density")) - ), - div(class = "plot-wrap", - withSpinner(plotlyOutput("plot_pheno_dist", height = "350px"), - color = "#f97316", type = 6)) - ) - ), - div(class = "plot-grid-2", - div(class = "card", - div(class = "card-header", - div(class = "card-icon card-icon-purple", "🧬"), - div(div(class = "card-title", "Missing Data Heatmap"), - div(class = "card-subtitle", "Genotype missingness per marker")) - ), - div(class = "plot-wrap", - withSpinner(plotlyOutput("plot_missing", height = "350px"), - color = "#a78bfa", type = 6)) - ), - div(class = "card", - div(class = "card-header", - div(class = "card-icon card-icon-pink", "📏"), - div(div(class = "card-title", "Marker Spacing"), - div(class = "card-subtitle", "Inter-marker distances")) - ), - div(class = "plot-wrap", - withSpinner(plotlyOutput("plot_marker_spacing", height = "350px"), - color = "#ec4899", type = 6)) - ) - ) + uiOutput("explore_content") ), - # ── PAGE: QTL Models ────────────────────────────────────────────────── - div(id = "page-models", class = "page-panel", - div(class = "card", - div(class = "card-header", - div(class = "card-icon card-icon-cyan", "⚙️"), - div(div(class = "card-title", "QTL Model Configuration"), - div(class = "card-subtitle", "Select and configure the 10 available mapping models")) - ), - div(class = "ctrl-grid", - div(class = "form-group", - div(class = "form-label", "PHENOTYPE"), - uiOutput("pheno_sel_ui") - ), - div(class = "form-group", - div(class = "form-label", "LOD THRESHOLD"), - numericInput("lod_thresh", NULL, value = 3.0, min = 0.5, max = 20, step = 0.1) - ), - div(class = "form-group", - div(class = "form-label", "STEP (cM)"), - numericInput("step_size", NULL, value = 1, min = 0.5, max = 5, step = 0.5) - ), - div(class = "form-group", - div(class = "form-label", "PERMUTATIONS"), - numericInput("n_perm", NULL, value = 100, min = 50, max = 1000, step = 50) + # ── 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%")) ) ), - hr(style = "border-color: var(--border); margin: 16px 0;"), - div(style = "display: grid; grid-template-columns: repeat(auto-fit, minmax(220px,1fr)); gap: 10px;", - lapply(1:10, function(i) { - models <- list( - list(id="em", label="EM Algorithm", icon="🔵", col="c1"), - list(id="imp", label="Haley-Knott", icon="🟢", col="c2"), - list(id="hk", label="Extended HK", icon="🟠", col="c3"), - list(id="ehk", label="Marker Regression", icon="🟣", col="c4"), - list(id="mr", label="Multiple Imputation", icon="🔴", col="c5"), - list(id="mr2", label="CIM", icon="🟡", col="c1"), - list(id="cim", label="MQM Mapping", icon="🩵", col="c2"), - list(id="mqm", label="2D Scan (2QTL)", icon="🩶", col="c3"), - list(id="scan2", label="ANOVA Method", icon="🫧", col="c4"), - list(id="anova", label="Bayesian Interval", icon="⭐", col="c5") - ) - m <- models[[i]] - div(class = paste("stat-box", m$col), - style = "display:flex; align-items:center; gap:10px; padding:12px 14px; cursor:pointer;", - checkboxInput(paste0("use_", m$id), NULL, value = TRUE), - span(m$icon, style = "font-size:1.1rem;"), - div( - div(style = "font-size:0.82rem; font-weight:600; color:var(--text-pri);", m$label), - div(style = "font-size:0.68rem; color:var(--text-muted); font-family:var(--font-mono);", paste0("Model ", i)) + 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 = "btn-row", - actionButton("run_models", "▶ Run Selected Models", class = "btn-run"), - actionButton("run_perms", "🎲 Run Permutations", class = "btn-sec") + ), + 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%")) + ) ) - ), - div(class = "card", - div(class = "card-header", - div(class = "card-icon card-icon-lime", "📈"), - div(div(class = "card-title", "Permutation Results"), - div(class = "card-subtitle", "LOD threshold by permutation test")) - ), - div(class = "plot-wrap", - withSpinner(plotlyOutput("plot_perm", height = "300px"), color = "#a3e635", type = 6)) ) ), - # ── PAGE: Genome Scan ───────────────────────────────────────────────── - div(id = "page-scan", class = "page-panel", - div(class = "card", - div(class = "card-header", - div(class = "card-icon card-icon-cyan", "🔬"), - div(div(class = "card-title", "Genome-Wide LOD Scan"), - div(class = "card-subtitle", "Interactive LOD score across all chromosomes")) - ), - div(class = "tab-bar", - lapply(1:10, function(i) { - labels <- c("EM","HK","EHK","MR","MR2","CIM","MQM","Scan2","ANOVA","Bayes") - tags$button(class = paste0("tab-btn", if(i==1) " active" else ""), - `data-group` = "scan", `data-tab` = i, labels[i]) - }) - ), - lapply(1:10, function(i) { - div(id = paste0("tab-scan-", i), - class = "tab-pane", `data-group` = "scan", - style = if(i == 1) "" else "display:none;", - div(class = "plot-wrap", - withSpinner(plotlyOutput(paste0("plot_scan_", i), height = "380px"), - color = "#00d4ff", type = 6)) - ) - }) + # ── 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") + ) ) ), - # ── PAGE: Interval Map ──────────────────────────────────────────────── - div(id = "page-interval", class = "page-panel", - div(class = "card", - div(class = "card-header", - div(class = "card-icon card-icon-coral", "📍"), - div(div(class = "card-title", "QTL Interval Mapping"), - div(class = "card-subtitle", "LOD interval and Bayesian credible intervals")) + # ── 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(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 = "ctrl-grid", - div(class = "form-group", - div(class = "form-label", "CHROMOSOME"), - uiOutput("chr_sel_ui") - ), - div(class = "form-group", - div(class = "form-label", "MODEL"), - selectInput("interval_model", NULL, - choices = c("EM"="em","HK"="hk","Extended HK"="ehk", - "Marker Reg"="mr","CIM"="cim"), - selected = "hk") - ), - div(class = "form-group", - div(class = "form-label", "LOD DROP"), - numericInput("lod_drop", NULL, value = 1.5, min = 0.5, max = 5, step = 0.1) - ) - ), - div(class = "plot-wrap", - withSpinner(plotlyOutput("plot_interval", height = "400px"), - color = "#f97316", type = 6)) + div(class="cb", withSpinner(plotlyOutput("pl_genome",height="400px"),color="#1a6b3a")) ), - div(class = "plot-grid-2", - div(class = "card", - div(class = "card-header", - div(class = "card-icon card-icon-purple", "📊"), - div(div(class = "card-title", "Effect Plot"), - div(class = "card-subtitle", "QTL genotype effects at peak")) - ), - div(class = "plot-wrap", - withSpinner(plotlyOutput("plot_effect", height = "320px"), - color = "#a78bfa", type = 6)) + 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 = "card-header", - div(class = "card-icon card-icon-pink", "🧮"), - div(div(class = "card-title", "PVE Plot"), - div(class = "card-subtitle", "Phenotypic variance explained per QTL")) - ), - div(class = "plot-wrap", - withSpinner(plotlyOutput("plot_pve", height = "320px"), - color = "#ec4899", type = 6)) + div(class="card", + div(class="ch", div(div(class="ct","QQ Plot — LOD Scores"))), + div(class="cb", withSpinner(plotlyOutput("pl_qq",height="280px"),color="#1a6b3a")) ) ) ), - # ── PAGE: QTL Plots ──────────────────────────────────────────────���──── - div(id = "page-plots", class = "page-panel", - div(class = "card", - div(class = "card-header", - div(class = "card-icon card-icon-lime", "🎨"), - div(div(class = "card-title", "QTL Visualization Gallery"), - div(class = "card-subtitle", "10 diagnostic and result plots")) - ) - ), - div(class = "plot-grid-2", - div(class = "card", - div(class = "card-header", - div(class = "card-icon card-icon-cyan", "📈"), - div(div(class = "card-title", "Plot 1 — LOD Profile (All Chr)")) - ), - div(class = "plot-wrap", - withSpinner(plotlyOutput("p1_lod_profile", height = "320px"), color = "#00d4ff", type = 6)) - ), - div(class = "card", - div(class = "card-header", - div(class = "card-icon card-icon-lime", "🌡️"), - div(div(class = "card-title", "Plot 2 — LOD Heatmap")) - ), - div(class = "plot-wrap", - withSpinner(plotlyOutput("p2_lod_heatmap", height = "320px"), color = "#a3e635", type = 6)) - ), - div(class = "card", - div(class = "card-header", - div(class = "card-icon card-icon-coral", "📉"), - div(div(class = "card-title", "Plot 3 — QTL Effect Size")) - ), - div(class = "plot-wrap", - withSpinner(plotlyOutput("p3_effect_size", height = "320px"), color = "#f97316", type = 6)) - ), - div(class = "card", - div(class = "card-header", - div(class = "card-icon card-icon-purple", "🔮"), - div(div(class = "card-title", "Plot 4 — PVE Bar Chart")) - ), - div(class = "plot-wrap", - withSpinner(plotlyOutput("p4_pve_bar", height = "320px"), color = "#a78bfa", type = 6)) - ), - div(class = "card", - div(class = "card-header", - div(class = "card-icon card-icon-pink", "🌈"), - div(div(class = "card-title", "Plot 5 — Model Comparison LOD")) - ), - div(class = "plot-wrap", - withSpinner(plotlyOutput("p5_model_compare", height = "320px"), color = "#ec4899", type = 6)) + # ── 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(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(class = "card", - div(class = "card-header", - div(class = "card-icon card-icon-cyan", "🔵"), - div(div(class = "card-title", "Plot 6 — LOD Drop Intervals")) - ), - div(class = "plot-wrap", - withSpinner(plotlyOutput("p6_lod_intervals", height = "320px"), color = "#00d4ff", type = 6)) - ), - div(class = "card", - div(class = "card-header", - div(class = "card-icon card-icon-lime", "📊"), - div(div(class = "card-title", "Plot 7 — Phenotype vs Genotype")) - ), - div(class = "plot-wrap", - withSpinner(plotlyOutput("p7_pheno_geno", height = "320px"), color = "#a3e635", type = 6)) - ), - div(class = "card", - div(class = "card-header", - div(class = "card-icon card-icon-coral", "🗺️"), - div(div(class = "card-title", "Plot 8 — QTL Genome Map")) - ), - div(class = "plot-wrap", - withSpinner(plotlyOutput("p8_qtl_map", height = "320px"), color = "#f97316", type = 6)) - ), - div(class = "card", - div(class = "card-header", - div(class = "card-icon card-icon-purple", "🌊"), - div(div(class = "card-title", "Plot 9 — LOD Ridge Plot")) - ), - div(class = "plot-wrap", - withSpinner(plotlyOutput("p9_ridge", height = "320px"), color = "#a78bfa", type = 6)) + 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="cb", withSpinner(plotlyOutput("pl_interval",height="300px"),color="#1a6b3a")) ), - div(class = "card", - div(class = "card-header", - div(class = "card-icon card-icon-pink", "⚡"), - div(div(class = "card-title", "Plot 10 — Common QTL Highlight")) - ), - div(class = "plot-wrap", - withSpinner(plotlyOutput("p10_common_qtl", height = "320px"), color = "#ec4899", type = 6)) + div(class="card", + div(class="ch", div(div(class="ct","QTL Density"),div(class="cst","Density of significant peaks by chr"))), + div(class="cb", withSpinner(plotlyOutput("pl_density",height="300px"),color="#1a6b3a")) ) ) ), - # ── PAGE: Circos ────────────────────────────────────────────────────── - div(id = "page-circos", class = "page-panel", - div(class = "card", - div(class = "card-header", - div(class = "card-icon card-icon-cyan", "🔵"), - div(div(class = "card-title", "Circos Plot — Multi-Model QTL"), - div(class = "card-subtitle", "Circular genome view with QTL from all models")) + # ── 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="cst","Max PVE per chromosome by model"))), + div(class="cb", withSpinner(plotlyOutput("pl_pve",height="300px"),color="#1a6b3a")) ), - div(class = "ctrl-grid", - div(class = "form-group", - div(class = "form-label", "TRACK TYPE"), - selectInput("circos_track", NULL, - choices = c("LOD Scores" = "lod", "QTL Positions" = "pos", - "Common QTL Links" = "links"), - selected = "lod") - ), - div(class = "form-group", - div(class = "form-label", "COLOR PALETTE"), - selectInput("circos_pal", NULL, - choices = c("Viridis" = "viridis", "Spectral" = "spectral", - "Dark2" = "dark2", "Accent" = "accent"), - selected = "viridis") - ) - ), - div(class = "plot-wrap", style = "min-height:600px;", - withSpinner(plotOutput("plot_circos", height = "580px"), color = "#00d4ff", type = 6)) + div(class="card", + div(class="ch", div(div(class="ct","Additive Effects"),div(class="cst","Mean phenotype by genotype class at peak"))), + 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="cb", + div(class="fm-g", label(class="fl","Select QTL Peak"), uiOutput("peak_sel")), + withSpinner(plotlyOutput("pl_violin",height="300px"),color="#1a6b3a") + ) ) ), - # ── PAGE: Model Compare ─────────────────────────────────────────────── - div(id = "page-compare", class = "page-panel", - div(class = "card", - div(class = "card-header", - div(class = "card-icon card-icon-coral", "🔀"), - div(div(class = "card-title", "Cross-Model Comparison"), - div(class = "card-subtitle", "Peak LOD, positions, and common QTL across all models")) - ), - div(class = "plot-grid-2", - div(class = "plot-wrap", - withSpinner(plotlyOutput("plot_compare_peak", height = "360px"), color = "#f97316", type = 6)), - div(class = "plot-wrap", - withSpinner(plotlyOutput("plot_compare_venn", height = "360px"), color = "#a78bfa", type = 6)) - ) + # ── 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(class="card", + div(class="ch", div(div(class="ct","LOD Heatmap — Marker × Model"),div(class="cst","Top-60 markers by max LOD"))), + div(class="cb", withSpinner(plotlyOutput("pl_heatmap",height="380px"),color="#1a6b3a")) ), - div(class = "card", - div(class = "card-header", - div(class = "card-icon card-icon-purple", "🏆"), - div(div(class = "card-title", "Common QTL Across Models"), - div(class = "card-subtitle", "QTL detected by ≥2 models highlighted")) - ), - div(class = "plot-wrap", - withSpinner(plotlyOutput("plot_common_qtl_map", height = "400px"), color = "#a78bfa", type = 6)) + div(class="card", + div(class="ch", div(div(class="ct","Common QTL Highlighted"),div(class="cst","Amber = peaks found 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="cb", withSpinner(plotlyOutput("pl_pkcomp",height="300px"),color="#1a6b3a")) ) ), - # ── PAGE: Results Table ─────────────────────────────────────────────── - div(id = "page-results", class = "page-panel", - div(class = "card", - div(class = "card-header", - div(class = "card-icon card-icon-lime", "📋"), - div(div(class = "card-title", "QTL Results Table"), - div(class = "card-subtitle", "LOD, PVE, CI left/right, peak markers and positions")) + # ── 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(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") ), - uiOutput("qtl_stats_row"), - DTOutput("qtl_results_table") + div(class="cb", + div(style="display:flex;justify-content:center;", + withSpinner(plotOutput("pl_circos",width="680px",height="680px"),color="#1a6b3a") + ) + ) ) ), - # ── PAGE: Export ────────────────────────────────────────────────────── - div(id = "page-export", class = "page-panel", - div(class = "card", - div(class = "card-header", - div(class = "card-icon card-icon-purple", "💾"), - div(div(class = "card-title", "Export Results"), - div(class = "card-subtitle", "Download QTL results, plots, and reports")) - ), - div(style = "display: grid; grid-template-columns: repeat(auto-fit, minmax(240px,1fr)); gap: 16px;", - div(class = "stat-box c1", style = "padding:20px;", - div(class = "stat-label", "QTL SUMMARY TABLE"), - div(style = "font-size:0.82rem; color:var(--text-dim); margin:8px 0 12px;", - "All QTL with LOD, PVE, CI, markers (CSV)"), - downloadButton("dl_csv", "📄 Download CSV", class = "btn-dl") - ), - div(class = "stat-box c2", style = "padding:20px;", - div(class = "stat-label", "FULL RESULTS (TSV)"), - div(style = "font-size:0.82rem; color:var(--text-dim); margin:8px 0 12px;", - "Tab-separated with all model results"), - downloadButton("dl_tsv", "📊 Download TSV", class = "btn-dl") - ), - div(class = "stat-box c3", style = "padding:20px;", - div(class = "stat-label", "LOD SCAN DATA"), - div(style = "font-size:0.82rem; color:var(--text-dim); margin:8px 0 12px;", - "Full scan output per position per model"), - downloadButton("dl_scan", "🔬 Download Scan", class = "btn-dl") - ), - div(class = "stat-box c4", style = "padding:20px;", - div(class = "stat-label", "R DATA OBJECT"), - div(style = "font-size:0.82rem; color:var(--text-dim); margin:8px 0 12px;", - "Cross + scan objects as .RData"), - downloadButton("dl_rdata", "💾 Download RData", class = "btn-dl") - ), - div(class = "stat-box c5", style = "padding:20px;", - div(class = "stat-label", "COMMON QTL"), - div(style = "font-size:0.82rem; color:var(--text-dim); margin:8px 0 12px;", - "QTL found in ≥2 models (CSV)"), - downloadButton("dl_common", "⭐ Download Common", class = "btn-dl") - ), - div(class = "stat-box c1", style = "padding:20px;", - div(class = "stat-label", "HTML REPORT"), - div(style = "font-size:0.82rem; color:var(--text-dim); margin:8px 0 12px;", - "Full analysis report with plots"), - downloadButton("dl_report", "📑 Download Report", class = "btn-dl") + # ── TABLE ── + 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(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 ──────────────────────────────────────────────────── server <- function(input, output, session) { - # ── Reactive Values ──────────────────────────────────────────────────────── rv <- reactiveValues( - cross = NULL, - cross_calc = NULL, + cross = NULL, scan_list = list(), - qtl_table = NULL, - perm_out = NULL, - models_run = FALSE + sig_qtl = list(), + log_msgs = character(0), + running = FALSE, + pheno_name = "Phenotype" ) - model_labels <- c("EM","HK","Ext.HK","Marker.Reg","Multi.Imp", - "CIM","MQM","2D.Scan","ANOVA","Bayes") - model_colors <- c("#00d4ff","#a3e635","#f97316","#a78bfa","#ec4899", - "#facc15","#34d399","#f87171","#60a5fa","#fb923c") - - # ── Toggle upload zone ───────────────────────────────────────────────────── - observeEvent(input$data_source, { - if (input$data_source == "upload") shinyjs::show("upload_zone_div") - else shinyjs::hide("upload_zone_div") - }) + add_log <- function(msg) rv$log_msgs <- c(rv$log_msgs, paste0("[",format(Sys.time(),"%H:%M:%S"),"] ",msg)) - # ── Load Data ────────────────────────────────────────────────────────────── - load_cross_data <- function() { - withProgress(message = "Loading cross data...", { + # ── LOAD DEMO ── + observeEvent(input$load_demo, { + withProgress(message="Loading Listeria demo…",{ tryCatch({ - cross <- switch(input$data_source, - "hyper" = { data(hyper, package = "qtl"); hyper }, - "listeria" = { data(listeria, package = "qtl"); listeria }, - "fake_f2" = { - set.seed(42) - sim.cross(map = sim.map(len = rep(100, 10), n.mar = 15, eq.spacing = FALSE), - n.ind = 200, type = "f2", model = cbind(c(1,45), c(2,65), c(5,30), 1, 2)) - }, - "upload" = { - req(input$file_upload) - fp <- input$file_upload$datapath - ext <- tools::file_ext(fp) - if (ext %in% c("RData","rdata")) { - load(fp); get(ls()[1]) - } else { - read.cross(format = "csv", file = fp) - } - } - ) - cross <- jittermap(cross) - rv$cross <- cross - showNotification("✓ Data loaded successfully", type = "message", duration = 3) - }, error = function(e) { - showNotification(paste("Error:", e$message), type = "error", duration = 5) - }) + data(listeria, package="qtl") + rv$cross <- listeria + rv$log_msgs <- character(0) + add_log("Loaded Listeria demo (F2, 20 chr, 133 markers, 1 phenotype)") + 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) showNotification(paste("Error:",e$message),type="error")) }) - } - - observeEvent(input$load_data, { load_cross_data() }) - - # ── Auto-load on start ───────────────────────────────────────────────────── - observe({ - if (is.null(rv$cross)) { - tryCatch({ - data(hyper, package = "qtl") - rv$cross <- jittermap(hyper) - }, error = function(e) NULL) - } }) - # ── Calc Genoprob ────────────────────────────────────────────────────────── - calc_gp <- function() { - req(rv$cross) - withProgress(message = "Calculating genotype probabilities...", { + # ── LOAD USER FILE ── + observeEvent(input$load_data, { + req(input$geno_file) + withProgress(message="Reading CSV…",{ tryCatch({ - cross <- calc.genoprob(rv$cross, step = input$step_size, error.prob = 0.001) - rv$cross_calc <- cross - showNotification("✓ Genoprob calculated", type = "message", duration = 3) - }, error = function(e) { - showNotification(paste("Error:", e$message), type = "error", duration = 5) - }) + rv$cross <- read.cross(format="csv", file=input$geno_file$datapath, + genotypes=trimws(strsplit(input$geno_codes,",")[[1]]), na.strings=input$miss_code) + class(rv$cross)[1] <- input$cross_type + add_log(paste("Loaded:",input$geno_file$name)) + showNotification("Data loaded!",type="message",duration=3) + }, error=function(e) showNotification(paste("Load error:",e$message),type="error")) }) - } - observeEvent(input$calc_genoprob, { calc_gp() }) - - # ── Phenotype selector ───────────────────────────────────────────────────── - output$pheno_sel_ui <- renderUI({ - req(rv$cross) - pnames <- phenames(rv$cross) - selectInput("pheno_name", NULL, choices = pnames, selected = pnames[1]) }) - output$chr_sel_ui <- renderUI({ - req(rv$cross) - chrs <- chrnames(rv$cross) - selectInput("chr_sel", NULL, choices = chrs, selected = chrs[1]) - }) - - # ── Helper: get active cross ─────────────────────────────────────────────── - get_cross <- reactive({ - if (!is.null(rv$cross_calc)) return(rv$cross_calc) - req(rv$cross) - withProgress(message = "Calculating genoprob...", { - tryCatch( - calc.genoprob(rv$cross, step = isolate(input$step_size), error.prob = 0.001), - error = function(e) rv$cross + # ── UPLOAD SUMMARY ── + 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))) + ) ) - }) + ) }) - # ── Run Models ──────────────────────────────────────────────────────────── - run_scan <- function(cross, pheno.col = 1, method = "hk") { - tryCatch({ - scanone(cross, pheno.col = pheno.col, method = method) - }, error = function(e) NULL) - } + # ── STAT TILES ── + 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))) + ) + }) - run_all_models <- function() { + # ── EXPLORE ── + output$explore_content <- renderUI({ + tab <- if(is.null(input$tab_ex)) "pheno" else input$tab_ex req(rv$cross) - cross <- get_cross() - pname <- if (!is.null(input$pheno_name)) input$pheno_name else phenames(rv$cross)[1] - pcol <- which(phenames(rv$cross) == pname) - if (length(pcol) == 0) pcol <- 1 - - withProgress(message = "Running QTL models...", { - slist <- list() - - incProgress(0.05, detail = "EM Algorithm") - if (isTRUE(input$use_em)) { - s <- tryCatch(scanone(cross, pheno.col = pcol, method = "em"), error = function(e) NULL) - if (!is.null(s)) slist[["EM"]] <- s - } - incProgress(0.1, detail = "Haley-Knott") - if (isTRUE(input$use_imp)) { - s <- tryCatch(scanone(cross, pheno.col = pcol, method = "hk"), error = function(e) NULL) - if (!is.null(s)) slist[["HK"]] <- s - } - incProgress(0.1, detail = "Extended HK") - if (isTRUE(input$use_hk)) { - s <- tryCatch(scanone(cross, pheno.col = pcol, method = "ehk"), error = function(e) NULL) - if (!is.null(s)) slist[["Ext.HK"]] <- s - } - incProgress(0.1, detail = "Marker Regression") - if (isTRUE(input$use_ehk)) { - s <- tryCatch(scanone(cross, pheno.col = pcol, method = "mr"), error = function(e) NULL) - if (!is.null(s)) slist[["Marker.Reg"]] <- s - } - incProgress(0.1, detail = "Multiple Imputation") - if (isTRUE(input$use_mr)) { - s <- tryCatch({ - cx2 <- sim.geno(cross, n.draws = 16, step = 1, error.prob = 0.001) - scanone(cx2, pheno.col = pcol, method = "imp") - }, error = function(e) NULL) - if (!is.null(s)) slist[["Multi.Imp"]] <- s - } - incProgress(0.1, detail = "CIM") - if (isTRUE(input$use_mr2)) { - s <- tryCatch(cim(cross, pheno.col = pcol, n.marcovar = 3, method = "hk"), error = function(e) NULL) - if (!is.null(s)) slist[["CIM"]] <- s - } - incProgress(0.1, detail = "MQM — using HK") - if (isTRUE(input$use_cim)) { - s <- tryCatch(scanone(cross, pheno.col = pcol, method = "hk"), error = function(e) NULL) - if (!is.null(s)) { - s$lod <- s$lod * runif(nrow(s), 0.95, 1.05) # slight variation for display - slist[["MQM"]] <- s - } - } - incProgress(0.1, detail = "2D Scan subset") - if (isTRUE(input$use_mqm)) { - s <- tryCatch(scanone(cross, pheno.col = pcol, method = "em"), error = function(e) NULL) - if (!is.null(s)) { - s$lod <- s$lod * runif(nrow(s), 0.9, 1.1) - slist[["2D.Scan"]] <- s - } - } - incProgress(0.1, detail = "ANOVA") - if (isTRUE(input$use_scan2)) { - s <- tryCatch(scanone(cross, pheno.col = pcol, method = "mr"), error = function(e) NULL) - if (!is.null(s)) { - s$lod <- s$lod * runif(nrow(s), 0.88, 1.08) - slist[["ANOVA"]] <- s - } - } - incProgress(0.1, detail = "Bayesian Interval") - if (isTRUE(input$use_anova)) { - s <- tryCatch(scanone(cross, pheno.col = pcol, method = "hk"), error = function(e) NULL) - if (!is.null(s)) { - s$lod <- s$lod * runif(nrow(s), 0.92, 1.12) - slist[["Bayes"]] <- s - } - } + if (tab=="pheno") { + div(class="card",div(class="ch",div(class="ct","Phenotype Distribution")),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"))) + } + }) - rv$scan_list <- slist - rv$models_run <- TRUE - build_qtl_table(cross, slist, pcol) - showNotification(paste("✓", length(slist), "models completed"), type = "message", duration = 4) - }) - } + output$pl_ex_pheno <- renderPlotly({ + req(rv$cross); phe <- pull.pheno(rv$cross,1); pn <- phenames(rv$cross)[1] + df <- data.frame(y=phe) + 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=pn,y="Density",title=paste("Phenotype:",pn))+theme_minimal()+theme(panel.grid.minor=element_blank(),panel.grid.major=element_line(color="#f0f0ee")) + ggplotly(p)%>%layout(font=list(family="DM Sans")) + }) - observeEvent(input$run_models, { run_all_models() }) - observeEvent(input$run_all, { load_cross_data(); run_all_models() }) - - # ── Build QTL Table ──────────────────────────────────────────────────────── - build_qtl_table <- function(cross, slist, pheno.col = 1) { - req(length(slist) > 0) - rows <- list() - for (mn in names(slist)) { - sc <- slist[[mn]] - thresh <- isolate(input$lod_thresh) - sc_sig <- sc[sc$lod >= thresh, ] - if (nrow(sc_sig) == 0) next - - # find peaks per chromosome - chrs <- unique(sc_sig$chr) - for (ch in chrs) { - ch_dat <- sc_sig[sc_sig$chr == ch, ] - peak_i <- which.max(ch_dat$lod) - peak_pos <- ch_dat$pos[peak_i] - peak_lod <- ch_dat$lod[peak_i] - - # LOD drop interval - full_ch <- sc[sc$chr == ch, ] - ci_lo <- tryCatch(lodint(sc, chr = ch, drop = 1.5)$pos[1], error = function(e) peak_pos - 10) - ci_hi <- tryCatch(lodint(sc, chr = ch, drop = 1.5)$pos[3], error = function(e) peak_pos + 10) - - # closest marker - all_markers <- markernames(cross) - marker_pos <- pull.map(cross) - ch_markers <- marker_pos[[as.character(ch)]] - if (length(ch_markers) > 0) { - dist_to_peak <- abs(ch_markers - peak_pos) - peak_marker <- names(which.min(dist_to_peak)) - } else { - peak_marker <- "—" - } + 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")) + }) - # PVE: approximate from LOD - n_ind <- nind(cross) - pve <- 1 - 10^(-2 * peak_lod / n_ind) - pve <- round(max(0, min(1, pve)) * 100, 2) - - rows[[length(rows) + 1]] <- data.frame( - Model = mn, - Chr = as.character(ch), - Peak_Pos_cM = round(peak_pos, 2), - LOD = round(peak_lod, 3), - PVE_pct = pve, - CI_Left_cM = round(ci_lo, 2), - CI_Right_cM = round(ci_hi, 2), - CI_Width_cM = round(ci_hi - ci_lo, 2), - Peak_Marker = peak_marker, - stringsAsFactors = FALSE - ) - } - } - if (length(rows) > 0) { - tbl <- do.call(rbind, rows) - # mark common QTL (same chr detected by >=2 models) - chr_counts <- table(tbl$Chr) - tbl$Common_QTL <- tbl$Chr %in% names(chr_counts[chr_counts >= 2]) - rv$qtl_table <- tbl - } - } + 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")) + }) - # ── Run Permutations ────────────────────────────────────────────────────── - observeEvent(input$run_perms, { - req(rv$cross) - cross <- get_cross() - pcol <- 1 - withProgress(message = "Running permutations...", { - perm <- tryCatch( - scanone(cross, pheno.col = pcol, method = "hk", n.perm = input$n_perm), - error = function(e) NULL - ) - if (!is.null(perm)) rv$perm_out <- perm - }) + output$pl_ex_gf <- renderPlotly({ + req(rv$cross); gt <- pull.geno(rv$cross) + cnts <- apply(gt,2,function(x) table(factor(x,levels=1:3))) + df <- as.data.frame(t(cnts)); df$marker <- rownames(df); names(df)[1:3] <- c("AA","AB","BB") + dl <- tidyr::pivot_longer(df,c("AA","AB","BB"),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")) }) - # ── DATA STATS UI ────────────────────────────────────────────────────────── - output$data_stats_ui <- renderUI({ - req(rv$cross) - cr <- rv$cross - div(class = "stat-grid", - div(class = "stat-box c1", - div(class = "stat-label", "INDIVIDUALS"), - div(class = "stat-value", nind(cr)), - div(class = "stat-sub", "Total RILs / individuals")), - div(class = "stat-box c2", - div(class = "stat-label", "MARKERS"), - div(class = "stat-value", totmar(cr)), - div(class = "stat-sub", paste("Across", nchr(cr), "chromosomes"))), - div(class = "stat-box c3", - div(class = "stat-label", "CHROMOSOMES"), - div(class = "stat-value", nchr(cr)), - div(class = "stat-sub", "Linkage groups")), - div(class = "stat-box c4", - div(class = "stat-label", "PHENOTYPES"), - div(class = "stat-value", nphe(cr)), - div(class = "stat-sub", paste(phenames(cr)[1], "..."))), - div(class = "stat-box c5", - div(class = "stat-label", "CROSS TYPE"), - div(class = "stat-value", toupper(class(cr)[1])), - div(class = "stat-sub", "Cross design")) - ) + # ── CONFIG SELECTS ── + 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) }) - # ── CROSS SUMMARY UI ────────────────────────────────────────────────────── - output$cross_summary_ui <- renderUI({ - req(rv$cross) - cr <- rv$cross - gmap <- pull.map(cr) - lens <- sapply(gmap, function(x) diff(range(x))) - n_mar <- nmar(cr) + # ── 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 div( - div(class = "stat-grid", - div(class = "stat-box c1", - div(class = "stat-label", "GENOME SIZE"), - div(class = "stat-value", paste0(round(sum(lens)), " cM")), - div(class = "stat-sub", "Total genetic length")), - div(class = "stat-box c2", - div(class = "stat-label", "AVG SPACING"), - div(class = "stat-value", paste0(round(sum(lens)/sum(n_mar), 1), " cM")), - div(class = "stat-sub", "Average inter-marker")), - div(class = "stat-box c3", - div(class = "stat-label", "MISSING DATA"), - div(class = "stat-value", - paste0(round(100 * sum(is.na(pull.geno(cr))) / - (nind(cr) * totmar(cr)), 1), "%")), - div(class = "stat-sub", "Genotype missingness")), - div(class = "stat-box c4", - div(class = "stat-label", "LARGEST CHR"), - div(class = "stat-value", paste0(round(max(lens)), " cM")), - div(class = "stat-sub", paste("Chr", names(which.max(lens))))) - ), - div(style = "margin-top:10px; display:flex; flex-wrap:wrap; gap:6px;", - lapply(seq_along(gmap), function(i) { - div(class = "chr-chip", - paste0("Chr ", names(gmap)[i], ": ", n_mar[i], " mkrs / ", round(lens[i]), " cM")) - }) - ) + div(class="al al-info","ℹ",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]))) ) }) - # ── QTL STATS ROW ───────────────────────────────────────────────────────── - output$qtl_stats_row <- renderUI({ - req(rv$qtl_table) - tbl <- rv$qtl_table - n_total <- nrow(tbl) - n_common <- sum(tbl$Common_QTL) - max_lod <- max(tbl$LOD) - max_pve <- max(tbl$PVE_pct) - div(class = "stat-grid", style = "margin-bottom:16px;", - div(class = "stat-box c1", - div(class = "stat-label", "TOTAL QTL"), - div(class = "stat-value", n_total)), - div(class = "stat-box c2", - div(class = "stat-label", "COMMON QTL"), - div(class = "stat-value", n_common), - div(class = "stat-sub", "Detected ≥2 models")), - div(class = "stat-box c3", - div(class = "stat-label", "MAX LOD"), - div(class = "stat-value", round(max_lod, 2))), - div(class = "stat-box c4", - div(class = "stat-label", "MAX PVE"), - div(class = "stat-value", paste0(round(max_pve, 1), "%"))), - div(class = "stat-box c5", - div(class = "stat-label", "MODELS RUN"), - div(class = "stat-value", length(rv$scan_list))) - ) + 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","✓",div(div(style="font-weight:600;","Complete"),div(paste(length(rv$scan_list),"models done")))) + } }) - # ── PLOT THEME ───────────────────────────────────────────────────────────── - dark_theme <- theme_minimal(base_family = "mono") + - theme( - plot.background = element_rect(fill = "#111827", color = NA), - panel.background = element_rect(fill = "#0f1c2e", color = NA), - panel.grid.major = element_line(color = "#1e3a5f", linewidth = 0.3), - panel.grid.minor = element_line(color = "#1e3a5f", linewidth = 0.15), - axis.text = element_text(color = "#94a3b8", size = 8), - axis.title = element_text(color = "#64748b", size = 9), - plot.title = element_text(color = "#e2e8f0", size = 11, face = "bold"), - plot.subtitle = element_text(color = "#64748b", size = 8), - legend.background= element_rect(fill = "#111827", color = NA), - legend.text = element_text(color = "#94a3b8", size = 8), - legend.title = element_text(color = "#64748b", size = 8), - strip.background = element_rect(fill = "#162033", color = NA), - strip.text = element_text(color = "#94a3b8", size = 8) - ) - - gg2plotly <- function(p) { - gg <- ggplotly(p, tooltip = "text") %>% - layout( - paper_bgcolor = "#111827", plot_bgcolor = "#0f1c2e", - font = list(color = "#94a3b8"), - xaxis = list(gridcolor = "#1e3a5f", zerolinecolor = "#1e3a5f"), - yaxis = list(gridcolor = "#1e3a5f", zerolinecolor = "#1e3a5f"), - legend = list(bgcolor = "#111827", font = list(color = "#94a3b8")) + 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:'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")) ) - gg - } - - # ── HELPER: Scan to long df ──────────────────────────────────────────────── - scan_to_df <- function(sc, model_name) { - data.frame( - chr = sc$chr, - pos = sc$pos, - lod = sc$lod, - model = model_name, - stringsAsFactors = FALSE ) - } - - # ── PLOT: Genetic Map ────────────────────────────────────────────────────── - output$plot_genetic_map <- renderPlotly({ - req(rv$cross) - gmap <- pull.map(rv$cross) - df <- do.call(rbind, lapply(names(gmap), function(ch) { - data.frame(chr = ch, pos = as.numeric(gmap[[ch]]), - marker = names(gmap[[ch]]), stringsAsFactors = FALSE) - })) - df$chr_num <- as.numeric(factor(df$chr, levels = unique(df$chr))) - p <- ggplot(df, aes(x = pos, y = chr_num, - text = paste0("Marker: ", marker, "
Chr: ", chr, "
Pos: ", round(pos,1), " cM"))) + - geom_hline(aes(yintercept = chr_num), color = "#1e3a5f", linewidth = 0.5) + - geom_point(color = "#00d4ff", size = 1.5, alpha = 0.8) + - scale_y_continuous(breaks = unique(df$chr_num), labels = unique(df$chr)) + - labs(x = "Position (cM)", y = "Chromosome", title = "Genetic Map") + - dark_theme - gg2plotly(p) }) - # ── PLOT: Phenotype Distribution ────────────────────────────────────────── - output$plot_pheno_dist <- renderPlotly({ + # ── RUN SCAN ── + observeEvent(input$run_scan, { req(rv$cross) - pdata <- pull.pheno(rv$cross) - pname <- phenames(rv$cross)[1] - vals <- pdata[[pname]] - vals <- vals[!is.na(vals)] - df <- data.frame(x = vals) - p <- ggplot(df, aes(x = x)) + - geom_histogram(aes(y = after_stat(density)), bins = 30, - fill = "#f97316", alpha = 0.7, color = "#0f1c2e") + - geom_density(color = "#00d4ff", linewidth = 1) + - geom_vline(xintercept = mean(vals), color = "#a3e635", - linetype = "dashed", linewidth = 0.8) + - labs(x = pname, y = "Density", title = "Phenotype Distribution", - subtitle = paste0("n=", length(vals), " mean=", round(mean(vals),2), - " sd=", round(sd(vals),2))) + - dark_theme - gg2plotly(p) - }) + 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] + 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,":",e$message,"→ fallback HK")); scanone(rv$cross,pheno.col=phe_col,method="hk") }) - # ── PLOT: Missing Data ──────────────────────────────────────────────────── - output$plot_missing <- renderPlotly({ - req(rv$cross) - g <- pull.geno(rv$cross) - miss <- apply(g, 2, function(x) mean(is.na(x)) * 100) - df <- data.frame(marker = names(miss), missing = miss, - stringsAsFactors = FALSE) - df <- df[order(df$missing, decreasing = TRUE), ] - df$marker <- factor(df$marker, levels = df$marker) - if (nrow(df) > 80) df <- df[1:80, ] - p <- ggplot(df, aes(x = marker, y = missing, - text = paste0(marker, ": ", round(missing,1), "% missing"))) + - geom_col(aes(fill = missing)) + - scale_fill_gradient(low = "#1e3a5f", high = "#f97316") + - labs(x = NULL, y = "% Missing", title = "Missing Genotype Data", - subtitle = "Top markers by missingness") + - dark_theme + - theme(axis.text.x = element_blank(), legend.position = "none") - gg2plotly(p) + 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(" ✓",MODEL_LABELS[m],"peaks:",nrow(sig))) + } + 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") }) + }) }) - # ── PLOT: Marker Spacing ────────────────────────────────────────────────── - output$plot_marker_spacing <- renderPlotly({ - req(rv$cross) - gmap <- pull.map(rv$cross) - sp <- unlist(lapply(gmap, function(ch) { - if (length(ch) < 2) return(NA) - diff(as.numeric(ch)) + 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){ + 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) })) - sp <- sp[!is.na(sp)] - df <- data.frame(spacing = sp) - p <- ggplot(df, aes(x = spacing)) + - geom_histogram(bins = 40, fill = "#ec4899", alpha = 0.75, color = "#0f1c2e") + - geom_vline(xintercept = median(sp), color = "#a3e635", - linetype = "dashed", linewidth = 0.8) + - labs(x = "Inter-marker distance (cM)", y = "Count", - title = "Marker Spacing Distribution", - subtitle = paste0("Median: ", round(median(sp),1), " cM")) + - dark_theme - gg2plotly(p) }) - # ── PLOT: Permutation ──────────────────────────────────────────────────── - output$plot_perm <- renderPlotly({ - req(rv$perm_out) - pvals <- as.numeric(rv$perm_out) - df <- data.frame(lod = sort(pvals)) - t95 <- quantile(pvals, 0.95) - t99 <- quantile(pvals, 0.99) - p <- ggplot(df, aes(x = lod)) + - geom_histogram(bins = 40, fill = "#a78bfa", alpha = 0.7, color = "#0f1c2e") + - geom_vline(xintercept = t95, color = "#a3e635", linetype = "dashed", linewidth = 1) + - geom_vline(xintercept = t99, color = "#f97316", linetype = "dashed", linewidth = 1) + - annotate("text", x = t95 + 0.1, y = Inf, label = paste0("α=0.05: ", round(t95,2)), - color = "#a3e635", hjust = 0, vjust = 1.5, size = 3) + - annotate("text", x = t99 + 0.1, y = Inf, label = paste0("α=0.01: ", round(t99,2)), - color = "#f97316", hjust = 0, vjust = 3, size = 3) + - labs(x = "LOD Score", y = "Count", title = "Permutation Distribution", - subtitle = paste0(length(pvals), " permutations")) + - dark_theme - gg2plotly(p) + 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) }) - # ── PLOTS: 10 Genome Scans ──────────────────────────────────────────────── - make_scan_plot <- function(sc, model_name, col) { - req(!is.null(sc)) - df <- scan_to_df(sc, model_name) - # cumulative position - chr_levels <- unique(df$chr) - chr_offsets <- c(0, cumsum(tapply(df$pos, df$chr, max)[chr_levels[-length(chr_levels)]])) - names(chr_offsets) <- chr_levels - df$cum_pos <- df$pos + chr_offsets[df$chr] - thresh <- isolate(input$lod_thresh) - df$sig <- df$lod >= thresh - - p <- ggplot(df, aes(x = cum_pos, y = lod, - text = paste0("Chr: ", chr, "
Pos: ", round(pos,1), - " cM
LOD: ", round(lod,3)))) + - geom_line(aes(color = chr), linewidth = 0.7, show.legend = FALSE) + - geom_hline(yintercept = thresh, color = "#f97316", - linetype = "dashed", linewidth = 0.6) + - geom_point(data = df[df$sig, ], aes(x = cum_pos, y = lod), - color = "#facc15", size = 1.5, alpha = 0.9) + - scale_color_manual(values = rep(c(col, scales::alpha(col, 0.6)), - length(chr_levels))) + - labs(x = "Genome Position (cM)", y = "LOD Score", - title = paste0(model_name, " — Genome Scan"), - subtitle = paste0("LOD threshold: ", thresh)) + - dark_theme - gg2plotly(p) - } - - scan_model_names <- c("EM","HK","Ext.HK","Marker.Reg","Multi.Imp", - "CIM","MQM","2D.Scan","ANOVA","Bayes") - - for (i in seq_along(scan_model_names)) { - local({ - idx <- i - mname <- scan_model_names[idx] - mcol <- model_colors[idx] - out_id <- paste0("plot_scan_", idx) - output[[out_id]] <- renderPlotly({ - req(length(rv$scan_list) > 0) - sc <- rv$scan_list[[mname]] - if (is.null(sc)) { - # fallback to first available - sc <- rv$scan_list[[1]] - mname2 <- names(rv$scan_list)[1] - } else { - mname2 <- mname - } - make_scan_plot(sc, mname2, mcol) - }) - }) - } + thresh_val <- reactive({ if(is.null(input$lod_thr)) 3.0 else input$lod_thr }) - # ── PLOT: Interval Map ──────────────────────────────────────────────────── - output$plot_interval <- renderPlotly({ - req(length(rv$scan_list) > 0, input$chr_sel) - mn <- switch(input$interval_model, - "em" = "EM", "hk" = "HK", "ehk" = "Ext.HK", - "mr" = "Marker.Reg", "cim" = "CIM", "HK") - sc <- rv$scan_list[[mn]] - if (is.null(sc)) sc <- rv$scan_list[[1]] - ch <- input$chr_sel - df <- sc[sc$chr == ch, ] - thresh <- isolate(input$lod_thresh) - drop <- isolate(input$lod_drop) - - ci <- tryCatch(lodint(sc, chr = ch, drop = drop), error = function(e) NULL) - peak_pos <- df$pos[which.max(df$lod)] - - p <- ggplot(df, aes(x = pos, y = lod, - text = paste0("Pos: ", round(pos,1), " cM
LOD: ", round(lod,3)))) + - geom_line(color = "#00d4ff", linewidth = 1.2) + - geom_area(fill = "#00d4ff", alpha = 0.1) + - geom_hline(yintercept = thresh, color = "#f97316", - linetype = "dashed", linewidth = 0.7) + - geom_vline(xintercept = peak_pos, color = "#a3e635", - linetype = "dotted", linewidth = 0.8) + - {if (!is.null(ci)) - annotate("rect", - xmin = ci$pos[1], xmax = ci$pos[3], - ymin = -Inf, ymax = Inf, - fill = "#a78bfa", alpha = 0.12) - } + - labs(x = "Position (cM)", y = "LOD Score", - title = paste0("Chr ", ch, " — Interval Mapping (", mn, ")"), - subtitle = paste0("LOD drop: ", drop, " cM | Peak: ", round(peak_pos,1), " cM")) + - dark_theme - gg2plotly(p) + # ── 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") }) - # ── PLOT: Effect ────────────────────────────────────────────────────────── - output$plot_effect <- renderPlotly({ - req(rv$cross, length(rv$scan_list) > 0, input$chr_sel) - sc <- rv$scan_list[[1]] - ch <- input$chr_sel - df_sc <- sc[sc$chr == ch, ] - peak_pos <- df_sc$pos[which.max(df_sc$lod)] - - # find nearest marker - cross <- rv$cross - mmap <- pull.map(cross)[[ch]] - near_m <- names(which.min(abs(mmap - peak_pos))) - - tryCatch({ - g <- pull.geno(cross)[, near_m] - pdata <- pull.pheno(cross)[, 1] - df <- data.frame(geno = factor(g), pheno = pdata) - df <- df[!is.na(df$geno) & !is.na(df$pheno), ] - df$geno_lab <- paste0("G", df$geno) - - p <- ggplot(df, aes(x = geno_lab, y = pheno, fill = geno_lab, - text = paste0("Geno: ", geno_lab, "
Pheno: ", round(pheno,2)))) + - geom_violin(alpha = 0.5) + - geom_boxplot(width = 0.2, outlier.color = "#f97316", color = "#e2e8f0") + - scale_fill_manual(values = c("#00d4ff","#a3e635","#f97316","#a78bfa")) + - labs(x = paste0("Genotype at ", near_m), y = "Phenotype", - title = paste0("Chr ", ch, " Peak Effect"), fill = NULL) + - dark_theme + theme(legend.position = "none") - gg2plotly(p) - }, error = function(e) { - plot_ly() %>% - add_annotations(text = "Effect plot requires genotype data", - showarrow = FALSE, font = list(color = "#64748b", size = 14)) %>% - layout(paper_bgcolor = "#111827", plot_bgcolor = "#0f1c2e") - }) + 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"))) }) - # ── PLOT: PVE ───────────────────────────────────────────────────────────── - output$plot_pve <- renderPlotly({ - req(rv$qtl_table) - tbl <- rv$qtl_table - df <- tbl %>% - group_by(Model, Chr) %>% - slice_max(LOD, n = 1) %>% - ungroup() - p <- ggplot(df, aes(x = reorder(paste0(Model,"/",Chr), PVE_pct), - y = PVE_pct, fill = Model, - text = paste0("Model: ", Model, "
Chr: ", Chr, - "
PVE: ", round(PVE_pct,1), "%
LOD: ", round(LOD,2)))) + - geom_col(alpha = 0.85) + - scale_fill_manual(values = setNames(model_colors[1:length(unique(df$Model))], - unique(df$Model))) + - coord_flip() + - labs(x = NULL, y = "PVE (%)", title = "Phenotypic Variance Explained") + - dark_theme + theme(legend.position = "none") - gg2plotly(p) + 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")) }) - # ═══ GALLERY PLOTS (10) ════════════════════════════════════════════════════ - - # Plot 1 — LOD Profile (All Chr, first model) - output$p1_lod_profile <- renderPlotly({ - req(length(rv$scan_list) > 0) - sc <- rv$scan_list[[1]] - mn <- names(rv$scan_list)[1] - make_scan_plot(sc, mn, "#00d4ff") + 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")) }) - # Plot 2 — LOD Heatmap (Chr × Models) - output$p2_lod_heatmap <- renderPlotly({ - req(length(rv$scan_list) > 0) - rows <- lapply(names(rv$scan_list), function(mn) { - sc <- rv$scan_list[[mn]] - tapply(sc$lod, sc$chr, max, na.rm = TRUE) %>% - as.data.frame() %>% - t() %>% as.data.frame() %>% - mutate(model = mn) - }) - mat <- bind_rows(rows) - chrs <- setdiff(names(mat), "model") - mat_long <- mat %>% - pivot_longer(all_of(chrs), names_to = "chr", values_to = "lod") %>% - mutate(lod = as.numeric(lod)) - p <- ggplot(mat_long, aes(x = chr, y = model, fill = lod, - text = paste0("Chr: ", chr, "
Model: ", model, - "
Max LOD: ", round(lod,2)))) + - geom_tile(color = "#0a0e1a") + - scale_fill_viridis(option = "magma", name = "LOD") + - labs(x = "Chromosome", y = NULL, title = "Max LOD per Chr per Model") + - dark_theme + theme(axis.text.x = element_text(angle = 45, hjust = 1)) - gg2plotly(p) + # ── 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],] + 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"))) }) - # Plot 3 — Effect Size bubble - output$p3_effect_size <- renderPlotly({ - req(rv$qtl_table) - tbl <- rv$qtl_table - p <- ggplot(tbl, aes(x = Chr, y = LOD, size = PVE_pct, color = Model, - text = paste0("Chr: ", Chr, "
LOD: ", round(LOD,2), - "
PVE: ", round(PVE_pct,1), "%
Model: ", Model))) + - geom_point(alpha = 0.75) + - scale_size_continuous(range = c(3, 14), name = "PVE (%)") + - scale_color_manual(values = setNames(model_colors[1:length(unique(tbl$Model))], - unique(tbl$Model))) + - labs(x = "Chromosome", y = "LOD Score", title = "QTL Effect Size Bubble Plot") + - dark_theme - gg2plotly(p) + 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) + })) + 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")) }) - # Plot 4 — PVE bar per model - output$p4_pve_bar <- renderPlotly({ - req(rv$qtl_table) - tbl <- rv$qtl_table %>% - group_by(Model) %>% summarise(total_pve = sum(PVE_pct), n_qtl = n()) - p <- ggplot(tbl, aes(x = reorder(Model, total_pve), y = total_pve, fill = Model, - text = paste0(Model, ": ", round(total_pve,1), "% total PVE (",n_qtl," QTL)"))) + - geom_col(alpha = 0.85) + - scale_fill_manual(values = setNames(model_colors[1:nrow(tbl)], tbl$Model)) + - coord_flip() + - labs(x = NULL, y = "Total PVE (%)", title = "Total PVE per Model") + - dark_theme + theme(legend.position = "none") - gg2plotly(p) + 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")) }) - # Plot 5 — Multi-model LOD overlay - output$p5_model_compare <- renderPlotly({ - req(length(rv$scan_list) >= 2) - combined <- bind_rows(lapply(names(rv$scan_list)[1:min(5, length(rv$scan_list))], - function(mn) scan_to_df(rv$scan_list[[mn]], mn))) - chr_levels <- unique(combined$chr) - chr_offsets <- c(0, cumsum(tapply(combined$pos, combined$chr, max)[chr_levels[-length(chr_levels)]])) - names(chr_offsets) <- chr_levels - combined$cum_pos <- combined$pos + chr_offsets[combined$chr] - - p <- ggplot(combined, aes(x = cum_pos, y = lod, color = model, - text = paste0(model, "
Chr: ", chr, - "
Pos: ", round(pos,1), " cM
LOD: ", round(lod,3)))) + - geom_line(linewidth = 0.6, alpha = 0.85) + - geom_hline(yintercept = isolate(input$lod_thresh), color = "#f97316", - linetype = "dashed", linewidth = 0.5) + - scale_color_manual(values = setNames(model_colors[1:length(unique(combined$model))], - unique(combined$model))) + - labs(x = "Genome Position", y = "LOD", title = "Multi-Model LOD Overlay", - color = "Model") + - dark_theme - gg2plotly(p) + # ── 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") }) - # Plot 6 — LOD Intervals forest plot - output$p6_lod_intervals <- renderPlotly({ - req(rv$qtl_table) - tbl <- rv$qtl_table %>% - mutate(label = paste0(Model, " Chr", Chr)) - p <- ggplot(tbl, aes(y = reorder(label, LOD), x = Peak_Pos_cM, - color = Model, - text = paste0(label, "
Peak: ", round(Peak_Pos_cM,1), - " cM
CI: [", CI_Left_cM, ", ", CI_Right_cM, "]", - "
LOD: ", round(LOD,2)))) + - geom_point(size = 2.5) + - geom_errorbarh(aes(xmin = CI_Left_cM, xmax = CI_Right_cM), height = 0.3) + - scale_color_manual(values = setNames(model_colors[1:length(unique(tbl$Model))], - unique(tbl$Model))) + - labs(x = "Position (cM)", y = NULL, title = "QTL LOD Drop Intervals", - subtitle = "1.5-LOD confidence intervals") + - dark_theme + theme(legend.position = "none") - gg2plotly(p) + 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")) }) - # Plot 7 — Phenotype vs peak genotype scatter - output$p7_pheno_geno <- renderPlotly({ - req(rv$cross, length(rv$scan_list) > 0) - sc <- rv$scan_list[[1]] - cross <- rv$cross - peak_chr <- sc$chr[which.max(sc$lod)] - peak_pos <- sc$pos[which.max(sc$lod)] - mmap <- pull.map(cross)[[as.character(peak_chr)]] - near_m <- names(which.min(abs(mmap - peak_pos))) - tryCatch({ - g <- pull.geno(cross)[, near_m] - pdata <- pull.pheno(cross)[, 1] - df <- data.frame(geno = factor(g), pheno = pdata) - df <- df[!is.na(df$geno) & !is.na(df$pheno), ] - p <- ggplot(df, aes(x = jitter(as.numeric(geno), 0.2), y = pheno, - color = geno, - text = paste0("Geno: G", geno, "
Pheno: ", round(pheno,3)))) + - geom_jitter(width = 0.15, alpha = 0.6, size = 1.5) + - stat_summary(fun = mean, geom = "crossbar", width = 0.4, - color = "#facc15", linewidth = 0.8) + - scale_color_manual(values = c("#00d4ff","#a3e635","#f97316")) + - scale_x_continuous(breaks = 1:3, labels = paste0("G",1:3)) + - labs(x = paste0("Genotype at ", near_m), y = "Phenotype", - title = "Phenotype by Peak Marker Genotype") + - dark_theme + theme(legend.position = "none") - gg2plotly(p) - }, error = function(e) { - plotly_empty() %>% - layout(paper_bgcolor="#111827", plot_bgcolor="#0f1c2e", - annotations = list(text = "Requires genotype data", - showarrow = FALSE, - font = list(color = "#64748b"))) - }) + 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="DM Sans")) }) - # Plot 8 — QTL Genome map (all QTL on chromosomes) - output$p8_qtl_map <- renderPlotly({ - req(rv$qtl_table, rv$cross) - tbl <- rv$qtl_table - gmap <- pull.map(rv$cross) - chr_lens <- sapply(gmap, function(x) max(as.numeric(x))) - chr_df <- data.frame(chr = names(chr_lens), len = chr_lens) - chr_df$chr_num <- seq_len(nrow(chr_df)) - - tbl$chr_num <- match(tbl$Chr, chr_df$chr) - - p <- ggplot() + - geom_segment(data = chr_df, aes(x = 0, xend = len, y = chr_num, yend = chr_num), - color = "#1e3a5f", linewidth = 3) + - geom_point(data = tbl, aes(x = Peak_Pos_cM, y = chr_num, color = Model, size = LOD, - text = paste0("Model: ", Model, "
Chr: ", Chr, - "
Pos: ", round(Peak_Pos_cM,1), - " cM
LOD: ", round(LOD,2))), - alpha = 0.85) + - geom_segment(data = tbl, aes(x = CI_Left_cM, xend = CI_Right_cM, - y = chr_num, yend = chr_num, color = Model), - linewidth = 2, alpha = 0.35) + - scale_color_manual(values = setNames(model_colors[1:length(unique(tbl$Model))], - unique(tbl$Model))) + - scale_size_continuous(range = c(3, 10)) + - scale_y_continuous(breaks = chr_df$chr_num, labels = chr_df$chr) + - labs(x = "Position (cM)", y = "Chromosome", title = "QTL Genome Map", - subtitle = "Dots = peak, bars = CI interval") + - dark_theme - gg2plotly(p) + output$peak_sel <- renderUI({ + req(length(rv$sig_qtl)>0); sd <- sig_df(); req(!is.null(sd)) + lc <- ncol(rv$scan_list[[sd$model_id[1]]]) + ch <- paste0(sd$chr," @ ",round(sd$pos,1),"cM (",sd$model_id,")") + selectInput("pk_sel",NULL,choices=ch,width="100%") }) - # Plot 9 — Ridge Plot (LOD per chromosome) - output$p9_ridge <- renderPlotly({ - req(length(rv$scan_list) > 0) - sc <- rv$scan_list[[1]] - mn <- names(rv$scan_list)[1] - chrs <- unique(sc$chr) - # offset each chr by LOD range for stacked display - df <- do.call(rbind, lapply(seq_along(chrs), function(i) { - ch_dat <- sc[sc$chr == chrs[i], ] - ch_dat$offset <- i * 3 - ch_dat$lod_offset <- ch_dat$lod + ch_dat$offset - ch_dat$chr_label <- paste0("Chr ", chrs[i]) - ch_dat - })) - - p <- ggplot(df, aes(x = pos, y = lod_offset, group = chr, color = chr, - text = paste0("Chr: ", chr, "
Pos: ", round(pos,1), - " cM
LOD: ", round(lod,3)))) + - geom_line(linewidth = 0.8, alpha = 0.85) + - geom_area(aes(fill = chr), alpha = 0.15) + - scale_color_manual(values = rep(viridis::viridis(min(nchr(rv$cross), 20)), 3)) + - scale_fill_manual(values = rep(viridis::viridis(min(nchr(rv$cross), 20)), 3)) + - labs(x = "Position (cM)", y = "LOD + offset", - title = paste0("LOD Ridge Plot — ", mn), - subtitle = "Each chromosome stacked vertically") + - dark_theme + theme(legend.position = "none") - gg2plotly(p) + output$pl_violin <- renderPlotly({ + req(rv$cross,length(rv$sig_qtl)>0,!is.null(input$pk_sel)) + sd <- sig_df(); req(!is.null(sd)) + lc <- ncol(rv$scan_list[[sd$model_id[1]]]) + 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) + gl <- c("1"="AA","2"="AB","3"="BB") + bdf <- data.frame(geno=factor(gl[as.character(gt)],levels=c("AA","AB","BB")),pheno=phe)%>%filter(!is.na(geno),!is.na(pheno)) + 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=c(AA="#1a6b3a",AB="#c47c1a",BB="#1a4a8a"))+scale_color_manual(values=c(AA="#1a6b3a",AB="#c47c1a",BB="#1a4a8a"))+ + 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")) }) - # Plot 10 — Common QTL Highlight - output$p10_common_qtl <- renderPlotly({ - req(rv$qtl_table) - tbl <- rv$qtl_table - tbl$Highlight <- ifelse(tbl$Common_QTL, "Common QTL (≥2 models)", "Unique to model") - p <- ggplot(tbl, aes(x = Chr, y = LOD, color = Highlight, size = PVE_pct, - text = paste0("Model: ", Model, "
Chr: ", Chr, - "
LOD: ", round(LOD,2), - "
PVE: ", round(PVE_pct,1), "%", - "
", Highlight))) + - geom_jitter(width = 0.15, alpha = 0.8, height = 0) + - scale_color_manual(values = c("Common QTL (≥2 models)" = "#f97316", - "Unique to model" = "#00d4ff")) + - scale_size_continuous(range = c(3, 12)) + - geom_hline(yintercept = isolate(input$lod_thresh), color = "#64748b", - linetype = "dashed", linewidth = 0.5) + - labs(x = "Chromosome", y = "LOD", title = "Common QTL Across Models", - subtitle = "Orange = detected in ≥2 models", color = NULL, size = "PVE (%)") + - dark_theme - gg2plotly(p) + # ── 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() + 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))) }) - # ── CIRCOS PLOT ──────────────────────────────────────────────────────────── - output$plot_circos <- renderPlot({ - req(rv$cross, length(rv$scan_list) > 0) - cross <- rv$cross - gmap <- pull.map(cross) - chrs <- names(gmap) - chr_lens <- sapply(gmap, function(x) max(as.numeric(x))) - - pal_choice <- isolate(input$circos_pal) - pal <- switch(pal_choice, - "viridis" = viridis::viridis(length(rv$scan_list)), - "spectral" = RColorBrewer::brewer.pal(min(11, length(rv$scan_list)), "Spectral"), - "dark2" = RColorBrewer::brewer.pal(min(8, length(rv$scan_list)), "Dark2"), - "accent" = RColorBrewer::brewer.pal(min(8, length(rv$scan_list)), "Accent"), - viridis::viridis(length(rv$scan_list)) - ) - pal <- rep_len(pal, length(rv$scan_list)) + 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 } + 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")) + }) - par(bg = "#0a0e1a", fg = "#e2e8f0", col.axis = "#64748b", - col.lab = "#64748b", col.main = "#e2e8f0") + 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")) + }) + # ── CIRCOS ── + 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)) circos.clear() - circos.par( - "start.degree" = 90, - "gap.degree" = 2, - "track.margin" = c(0.01, 0.01), - "cell.padding" = c(0.02, 0, 0.02, 0), - "canvas.xlim" = c(-1.2, 1.2), - "canvas.ylim" = c(-1.2, 1.2), - "background.color" = "#0a0e1a", - "track.height" = 0.06, - "points.overflow.warning" = FALSE - ) - - # Initialize with chromosome sectors - circos.initialize( - factors = factor(chrs, levels = chrs), - xlim = cbind(rep(0, length(chrs)), chr_lens) - ) - - # Track 1: Chromosome labels - circos.track( - ylim = c(0, 1), bg.col = "#162033", bg.border = "#1e3a5f", - panel.fun = function(x, y) { - circos.text( - x = CELL_META$xcenter, y = 0.5, labels = CELL_META$sector.index, - facing = "clockwise", niceFacing = TRUE, cex = 0.6, - col = "#94a3b8", font = 2 - ) - } - ) - - # Tracks 2–11: One per model (LOD scores) - thresh <- isolate(input$lod_thresh) - for (mi in seq_along(rv$scan_list)) { - mn <- names(rv$scan_list)[mi] - sc <- rv$scan_list[[mn]] - mcol <- pal[mi] - - circos.track( - ylim = c(0, max(sc$lod, na.rm = TRUE) * 1.1 + 0.1), - bg.col = "#0f1c2e", bg.border = "#1e3a5f", track.height = 0.05, - panel.fun = function(x, y) { - ch <- CELL_META$sector.index - ch_sc <- sc[as.character(sc$chr) == as.character(ch), ] - if (nrow(ch_sc) == 0) return() - # LOD bars - circos.rect( - xleft = ch_sc$pos - 0.5, - xright = ch_sc$pos + 0.5, - ybottom = 0, - ytop = pmax(ch_sc$lod, 0), - col = ifelse(ch_sc$lod >= thresh, mcol, scales::alpha(mcol, 0.3)), - border = NA - ) - # threshold line - if (max(ch_sc$lod, na.rm = TRUE) > thresh) { - circos.lines( - x = c(CELL_META$cell.xlim[1], CELL_META$cell.xlim[2]), - y = rep(thresh, 2), - col = "#f97316", lty = 2, lwd = 0.5 - ) - } + 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) }) + 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) } } ) } - - # Draw links for common QTL - if (!is.null(rv$qtl_table)) { - tbl <- rv$qtl_table - common <- tbl[tbl$Common_QTL, ] - chr_grp <- split(common, common$Chr) - link_col <- scales::alpha("#f97316", 0.45) - for (ch in names(chr_grp)) { - rows <- chr_grp[[ch]] - if (nrow(rows) < 2) next - for (r1 in 1:(nrow(rows) - 1)) { - for (r2 in (r1 + 1):nrow(rows)) { - tryCatch( - circos.link( - sector.index1 = ch, point1 = rows$Peak_Pos_cM[r1], - sector.index2 = ch, point2 = rows$Peak_Pos_cM[r2], - col = link_col, lwd = 1 - ), - error = function(e) NULL - ) - } - } - } - } - - # Legend - legend("bottomleft", - legend = c(names(rv$scan_list), "LOD Threshold", "Common QTL"), - col = c(pal[1:length(rv$scan_list)], "#f97316", "#f97316"), - lty = c(rep(1, length(rv$scan_list)), 2, 1), - lwd = c(rep(2, length(rv$scan_list)), 1.5, 2), - bg = "#111827", text.col = "#94a3b8", - bty = "n", cex = 0.65) - - title("Circos — Multi-Model QTL Landscape", col.main = "#e2e8f0", cex.main = 1.1) + 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) circos.clear() + } - }, bg = "#0a0e1a") - - # ── COMPARE PLOTS ───────────────────────────────────────────────────────��── - output$plot_compare_peak <- renderPlotly({ - req(rv$qtl_table) - tbl <- rv$qtl_table %>% - group_by(Model) %>% - summarise(peak_lod = max(LOD), n_qtl = n(), total_pve = sum(PVE_pct)) - p <- ggplot(tbl, aes(x = n_qtl, y = peak_lod, color = Model, size = total_pve, - text = paste0(Model, "
QTL: ", n_qtl, - "
Peak LOD: ", round(peak_lod,2), - "
Total PVE: ", round(total_pve,1), "%"))) + - geom_point(alpha = 0.85) + - geom_text(aes(label = Model), nudge_y = 0.15, size = 2.5, color = "#94a3b8") + - scale_color_manual(values = setNames(model_colors[1:nrow(tbl)], tbl$Model)) + - scale_size_continuous(range = c(6, 18)) + - labs(x = "Number of QTL", y = "Peak LOD", - title = "Model Performance Comparison", - subtitle = "Size = total PVE") + - dark_theme + theme(legend.position = "none") - gg2plotly(p) - }) - - output$plot_compare_venn <- renderPlotly({ - req(rv$qtl_table) - tbl <- rv$qtl_table - chr_model_mat <- tbl %>% - mutate(present = 1) %>% - distinct(Model, Chr) %>% - mutate(present = 1) %>% - pivot_wider(names_from = Model, values_from = present, values_fill = 0) - chrs <- chr_model_mat$Chr - mods <- setdiff(names(chr_model_mat), "Chr") - n_models <- sapply(chrs, function(ch) { - sum(as.numeric(chr_model_mat[chr_model_mat$Chr == ch, mods])) + 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) + 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) }) - df_v <- data.frame(chr = chrs, n_models = n_models) - p <- ggplot(df_v, aes(x = chr, y = n_models, fill = n_models, - text = paste0("Chr ", chr, ": detected by ", n_models, " models"))) + - geom_col() + - scale_fill_gradient(low = "#1e3a5f", high = "#f97316", name = "# Models") + - geom_hline(yintercept = 2, color = "#a3e635", linetype = "dashed", linewidth = 0.6) + - labs(x = "Chromosome", y = "# Models Detecting QTL", - title = "QTL Detection Consensus", - subtitle = "Green line = common QTL threshold (≥2)") + - dark_theme - gg2plotly(p) + do.call(rbind,Filter(Negate(is.null),rows)) }) - output$plot_common_qtl_map <- renderPlotly({ - req(rv$qtl_table) - tbl <- rv$qtl_table - chr_levels <- sort(unique(tbl$Chr)) - tbl$chr_num <- match(tbl$Chr, chr_levels) - p <- ggplot(tbl, aes(x = Peak_Pos_cM, y = chr_num, color = Model, size = LOD, - shape = Common_QTL, - text = paste0(Model, " | Chr", Chr, - " @ ", round(Peak_Pos_cM,1), " cM", - "
LOD: ", round(LOD,2), - "
Common: ", Common_QTL))) + - geom_point(alpha = 0.8) + - geom_rect(data = tbl[tbl$Common_QTL, ], - aes(xmin = CI_Left_cM, xmax = CI_Right_cM, - ymin = chr_num - 0.4, ymax = chr_num + 0.4), - fill = "#f97316", alpha = 0.08, inherit.aes = FALSE, - color = "#f97316", linewidth = 0.3) + - scale_color_manual(values = setNames(model_colors[1:length(unique(tbl$Model))], - unique(tbl$Model))) + - scale_shape_manual(values = c("FALSE" = 16, "TRUE" = 18)) + - scale_size_continuous(range = c(3, 10)) + - scale_y_continuous(breaks = seq_along(chr_levels), labels = chr_levels) + - labs(x = "Position (cM)", y = "Chromosome", - title = "Common QTL Across Models — Genome View", - subtitle = "Orange shading = common QTL CI region | Diamond = common QTL") + - dark_theme - gg2plotly(p) + 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"))) }) - # ── RESULTS TABLE ────────────────────────────────────────────────────────── - output$qtl_results_table <- renderDT({ - req(rv$qtl_table) - tbl <- rv$qtl_table - datatable(tbl, - options = list( - dom = "Bfrtip", - pageLength = 20, - scrollX = TRUE, - columnDefs = list(list(className = "dt-center", targets = "_all")) - ), - rownames = FALSE, - class = "compact stripe" - ) %>% - formatStyle("LOD", - background = styleColorBar(range(tbl$LOD), "#00d4ff"), - backgroundSize = "100% 80%", backgroundRepeat = "no-repeat", - backgroundPosition = "center") %>% - formatStyle("PVE_pct", - background = styleColorBar(range(tbl$PVE_pct), "#a3e635"), - backgroundSize = "100% 80%", backgroundRepeat = "no-repeat", - backgroundPosition = "center") %>% - formatStyle("Common_QTL", - color = styleEqual(c(TRUE, FALSE), c("#f97316", "#64748b")), - fontWeight = styleEqual(TRUE, "bold")) %>% - formatStyle(0, target = "row", - backgroundColor = "#0f1c2e", color = "#e2e8f0") + 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") }) - # ── DOWNLOADS ───────────────────────────────────────────────────────────── + # ── DOWNLOADS ── output$dl_csv <- downloadHandler( - filename = function() paste0("qtl_results_", Sys.Date(), ".csv"), - content = function(file) { - req(rv$qtl_table) - write.csv(rv$qtl_table, file, row.names = FALSE) - } + 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(file) { - req(rv$qtl_table) - write.table(rv$qtl_table, file, sep = "\t", row.names = FALSE, quote = FALSE) - } + 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_scan <- downloadHandler( - filename = function() paste0("qtl_scan_data_", Sys.Date(), ".csv"), - content = function(file) { - req(length(rv$scan_list) > 0) - df <- bind_rows(lapply(names(rv$scan_list), function(mn) { - sc <- rv$scan_list[[mn]] - data.frame(model = mn, chr = sc$chr, pos = sc$pos, lod = sc$lod, - stringsAsFactors = FALSE) - })) - write.csv(df, file, row.names = FALSE) - } + 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_rdata <- downloadHandler( - filename = function() paste0("qtl_objects_", Sys.Date(), ".RData"), - content = function(file) { - cross <- rv$cross - cross_calc <- rv$cross_calc - scan_list <- rv$scan_list - qtl_table <- rv$qtl_table - save(cross, cross_calc, scan_list, qtl_table, file = file) - } + 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_common <- downloadHandler( - filename = function() paste0("common_qtl_", Sys.Date(), ".csv"), - content = function(file) { - req(rv$qtl_table) - common <- rv$qtl_table[rv$qtl_table$Common_QTL, ] - write.csv(common, file, row.names = FALSE) + 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; 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) + png(f,width=1400,height=500,res=120); print(p); dev.off() } ) - output$dl_report <- downloadHandler( - filename = function() paste0("qtl_report_", Sys.Date(), ".html"), - content = function(file) { - req(rv$qtl_table) - tbl <- rv$qtl_table - n_qtl <- nrow(tbl) - n_com <- sum(tbl$Common_QTL) - html_content <- paste0( - "", - "", - "QTL Mapper Pro — Report", - "", - "

🧬 QTL Mapper Pro — Analysis Report

", - "

Generated: ", as.character(Sys.time()), "

", - "

Summary

", - "

Total QTL detected: ", n_qtl, "  ", - "Common QTL (≥2 models): ", n_com, "

", - "

QTL Results Table

", - "", - paste0("", collapse = ""), - "", - paste0(apply(tbl, 1, function(r) { - paste0("", paste0("", collapse = ""), "") - }), collapse = ""), - "
", names(tbl), "
", r, "
", - "" - ) - writeLines(html_content, file) + 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() } + ) } -# ── Run ─────────────────────────────────────────────────────────────────────── -shinyApp(ui = ui, server = server) \ No newline at end of file +shinyApp(ui=ui, server=server) \ No newline at end of file