softwareDevelopment commited on
Commit
2796f96
·
verified ·
1 Parent(s): 489dc5d

Update app.R

Browse files
Files changed (1) hide show
  1. app.R +1996 -107
app.R CHANGED
@@ -1,178 +1,2067 @@
 
 
 
 
 
 
 
 
 
1
  library(shiny)
 
 
 
2
  library(qtl)
3
- library(readr)
4
- library(dplyr)
5
  library(ggplot2)
 
6
  library(DT)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
 
 
 
 
 
 
 
 
 
 
 
8
  ui <- fluidPage(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
- titlePanel("QTL Mapping Pipeline"),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
 
12
- sidebarLayout(
13
- sidebarPanel(
14
 
15
- fileInput("geno","Genotype CSV"),
16
- fileInput("pheno","Phenotype CSV"),
 
 
 
 
 
17
 
18
- selectInput("trait","Trait", choices=NULL),
 
 
 
 
 
 
19
 
20
- selectInput("model","Model",
21
- c("EM","HK","IMP","CIM")),
 
 
 
 
 
22
 
23
- actionButton("run","Run"),
24
- br(), br(),
25
- verbatimTextOutput("status")
 
 
26
  ),
27
 
28
- mainPanel(
29
- tabsetPanel(
30
- tabPanel("LOD", plotOutput("lod")),
31
- tabPanel("Manhattan", plotOutput("manhattan")),
32
- tabPanel("Table", DTOutput("table"))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  )
34
  )
35
  )
36
  )
37
 
 
38
  server <- function(input, output, session) {
39
 
40
- output$status <- renderText("Waiting for input...")
 
 
 
 
 
 
 
 
41
 
42
- # -------- Load phenotype -------- #
43
- pheno <- reactive({
44
- req(input$pheno)
45
- read.csv(input$pheno$datapath)
46
- })
47
 
48
- observe({
49
- req(pheno())
50
- updateSelectInput(session,"trait",
51
- choices=colnames(pheno())[-1])
52
  })
53
 
54
- # -------- Load genotype safely -------- #
55
- geno <- reactive({
56
- req(input$geno)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
 
58
- g <- read.csv(input$geno$datapath)
59
 
60
- # remove non-genotype row
61
- if(any(!g[1,-1] %in% c(0,1,2,-1))){
62
- g <- g[-1,]
 
 
 
 
63
  }
 
64
 
65
- g
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
  })
67
 
68
- # -------- Create cross safely -------- #
69
- cross <- reactive({
 
 
 
70
 
71
- req(geno(), pheno())
 
 
 
 
 
 
 
 
 
 
72
 
 
 
73
  tryCatch({
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
 
75
- merged <- merge(pheno(), geno(), by="id")
 
 
 
 
 
 
76
 
77
- tmp <- tempfile(fileext = ".csv")
78
- write.csv(merged, tmp, row.names=FALSE)
 
 
79
 
80
- cross <- read.cross(
81
- format="csv",
82
- file=tmp,
83
- genotypes=c("0","1","2"),
84
- na.strings=c("-1","NA")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
 
87
- cross <- calc.genoprob(cross, step=1)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88
 
89
- output$status <- renderText("Cross object created successfully")
 
 
 
 
 
 
 
 
 
90
 
91
- cross
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92
 
93
- }, error=function(e){
94
- output$status <- renderText(paste("Error:", e$message))
95
- return(NULL)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
  })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97
  })
98
 
99
- # -------- Run analysis -------- #
100
- result <- eventReactive(input$run, {
 
 
 
 
 
101
 
102
- req(cross(), input$trait)
 
 
 
103
 
104
  tryCatch({
 
 
 
 
 
105
 
106
- if(input$model=="CIM"){
107
- res <- cim(cross(), pheno.col=input$trait)
108
- } else {
109
- method <- switch(input$model,
110
- "EM"="em",
111
- "HK"="hk",
112
- "IMP"="imp")
113
-
114
- res <- scanone(cross(),
115
- pheno.col=input$trait,
116
- method=method)
117
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118
 
119
- output$status <- renderText("Analysis completed")
 
 
 
 
 
 
 
 
 
 
 
 
120
 
121
- res
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
 
123
- }, error=function(e){
124
- output$status <- renderText(paste("Analysis error:", e$message))
125
- return(NULL)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
126
  })
127
  })
128
 
129
- # -------- LOD plot -------- #
130
- output$lod <- renderPlot({
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
131
 
132
- req(result())
 
 
 
 
 
 
 
 
 
 
 
 
 
133
 
134
- df <- as.data.frame(result())
 
 
 
 
 
 
 
 
 
 
 
 
135
 
136
- ggplot(df, aes(pos, lod, color=factor(chr))) +
137
- geom_line() +
138
- theme_minimal() +
139
- labs(title="LOD Plot")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
140
  })
141
 
142
- # -------- Manhattan -------- #
143
- output$manhattan <- renderPlot({
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
144
 
145
- req(result())
 
 
 
 
146
 
147
- df <- as.data.frame(result())
148
- df$chr <- as.factor(df$chr)
 
 
 
 
 
 
 
 
 
149
 
150
- df <- df %>%
151
- group_by(chr) %>%
152
- mutate(chr_len=max(pos)) %>%
153
- ungroup() %>%
154
- mutate(tot=cumsum(chr_len)-chr_len) %>%
155
- mutate(BPcum=pos+tot)
156
 
157
- axis <- df %>%
158
- group_by(chr) %>%
159
- summarise(center=mean(BPcum))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
160
 
161
- ggplot(df, aes(BPcum, lod, color=chr)) +
162
- geom_point() +
163
- scale_x_continuous(breaks=axis$center,
164
- labels=axis$chr) +
165
- theme_minimal() +
166
- theme(legend.position="none") +
167
- labs(title="Manhattan Plot")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
168
  })
169
 
170
- # -------- Table -------- #
171
- output$table <- renderDT({
172
- req(result())
173
- datatable(as.data.frame(result()))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
174
  })
175
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
176
  }
177
 
178
- shinyApp(ui, server)
 
 
1
+ # =============================================================================
2
+ # QTL MAPPER PRO — Complete Single-File Shiny Application
3
+ # =============================================================================
4
+ # Required packages:
5
+ # install.packages(c("shiny","shinydashboard","shinyWidgets","shinyjs",
6
+ # "shinycssloaders","qtl","ggplot2","plotly","DT","dplyr","tidyr",
7
+ # "viridis","RColorBrewer","reshape2","ggrepel","circlize","scales"))
8
+ # =============================================================================
9
+
10
  library(shiny)
11
+ library(shinyWidgets)
12
+ library(shinyjs)
13
+ library(shinycssloaders)
14
  library(qtl)
 
 
15
  library(ggplot2)
16
+ library(plotly)
17
  library(DT)
18
+ library(dplyr)
19
+ library(tidyr)
20
+ library(viridis)
21
+ library(RColorBrewer)
22
+ library(reshape2)
23
+ library(scales)
24
+
25
+ # ── Inline CSS ────────────────────────────────────────────────────────────────
26
+ app_css <- "
27
+ @import url('https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@300;400;600&family=Sora:wght@300;400;600;700&display=swap');
28
+
29
+ :root {
30
+ --bg-deep: #08111f;
31
+ --bg-panel: #0f1c2e;
32
+ --bg-card: #162033;
33
+ --bg-hover: #1e2d45;
34
+ --accent1: #00d4ff;
35
+ --accent2: #a3e635;
36
+ --accent3: #f97316;
37
+ --accent4: #a78bfa;
38
+ --accent5: #ec4899;
39
+ --text-pri: #e2e8f0;
40
+ --text-muted: #64748b;
41
+ --text-dim: #94a3b8;
42
+ --border: #1e3a5f;
43
+ --radius: 10px;
44
+ --font-mono: 'JetBrains Mono', monospace;
45
+ --font-main: 'Sora', sans-serif;
46
+ }
47
+ * { box-sizing: border-box; margin: 0; padding: 0; }
48
+ body {
49
+ font-family: var(--font-main);
50
+ background: var(--bg-deep);
51
+ color: var(--text-pri);
52
+ min-height: 100vh;
53
+ }
54
+ ::-webkit-scrollbar { width: 5px; height: 5px; }
55
+ ::-webkit-scrollbar-track { background: var(--bg-panel); }
56
+ ::-webkit-scrollbar-thumb { background: var(--border); border-radius: 3px; }
57
+ ::-webkit-scrollbar-thumb:hover { background: var(--accent1); }
58
+
59
+ /* ── Header */
60
+ .app-header {
61
+ background: linear-gradient(135deg, #0a1628 0%, #0f2040 50%, #0a1628 100%);
62
+ border-bottom: 1px solid var(--border);
63
+ padding: 0 28px;
64
+ height: 64px;
65
+ display: flex;
66
+ align-items: center;
67
+ justify-content: space-between;
68
+ position: sticky; top: 0; z-index: 1000;
69
+ box-shadow: 0 2px 20px rgba(0,212,255,0.08);
70
+ }
71
+ .header-brand {
72
+ display: flex; align-items: center; gap: 12px;
73
+ }
74
+ .header-logo {
75
+ width: 38px; height: 38px;
76
+ background: linear-gradient(135deg, var(--accent1), var(--accent4));
77
+ border-radius: 8px;
78
+ display: flex; align-items: center; justify-content: center;
79
+ font-size: 18px; font-weight: 700; color: #000;
80
+ font-family: var(--font-mono);
81
+ }
82
+ .header-title {
83
+ font-size: 1.25rem; font-weight: 700;
84
+ background: linear-gradient(90deg, var(--accent1), var(--accent4));
85
+ -webkit-background-clip: text; -webkit-text-fill-color: transparent;
86
+ letter-spacing: -0.02em;
87
+ }
88
+ .header-sub { font-size: 0.72rem; color: var(--text-muted); font-family: var(--font-mono); }
89
+ .header-badges { display: flex; gap: 8px; }
90
+ .badge-pill {
91
+ background: rgba(0,212,255,0.1); border: 1px solid rgba(0,212,255,0.25);
92
+ color: var(--accent1); padding: 3px 10px; border-radius: 20px;
93
+ font-size: 0.7rem; font-family: var(--font-mono);
94
+ }
95
+
96
+ /* ── Layout */
97
+ .app-body { display: flex; min-height: calc(100vh - 64px); }
98
+
99
+ /* ── Sidebar */
100
+ .app-sidebar {
101
+ width: 270px; min-width: 270px;
102
+ background: var(--bg-panel);
103
+ border-right: 1px solid var(--border);
104
+ padding: 20px 14px;
105
+ overflow-y: auto;
106
+ display: flex; flex-direction: column; gap: 6px;
107
+ }
108
+ .nav-section-label {
109
+ font-size: 0.65rem; font-weight: 600; letter-spacing: 0.12em;
110
+ color: var(--text-muted); text-transform: uppercase;
111
+ padding: 12px 10px 6px; font-family: var(--font-mono);
112
+ }
113
+ .nav-btn {
114
+ width: 100%; background: transparent; border: 1px solid transparent;
115
+ color: var(--text-dim); padding: 9px 12px;
116
+ border-radius: var(--radius); cursor: pointer;
117
+ display: flex; align-items: center; gap: 10px;
118
+ font-family: var(--font-main); font-size: 0.82rem; font-weight: 500;
119
+ transition: all 0.18s; text-align: left;
120
+ }
121
+ .nav-btn:hover { background: var(--bg-hover); color: var(--text-pri); border-color: var(--border); }
122
+ .nav-btn.active {
123
+ background: rgba(0,212,255,0.1); color: var(--accent1);
124
+ border-color: rgba(0,212,255,0.3);
125
+ }
126
+ .nav-icon { font-size: 1rem; width: 20px; text-align: center; }
127
+
128
+ /* ── Main Content */
129
+ .app-main { flex: 1; padding: 24px; overflow-y: auto; max-width: 100%; }
130
+
131
+ /* ── Cards */
132
+ .card {
133
+ background: var(--bg-card);
134
+ border: 1px solid var(--border);
135
+ border-radius: var(--radius);
136
+ padding: 20px;
137
+ margin-bottom: 18px;
138
+ }
139
+ .card-header {
140
+ display: flex; align-items: center; gap: 10px;
141
+ margin-bottom: 16px; padding-bottom: 12px;
142
+ border-bottom: 1px solid var(--border);
143
+ }
144
+ .card-icon {
145
+ width: 32px; height: 32px;
146
+ border-radius: 7px; display: flex; align-items: center; justify-content: center;
147
+ font-size: 15px;
148
+ }
149
+ .card-title { font-size: 0.95rem; font-weight: 600; color: var(--text-pri); }
150
+ .card-subtitle { font-size: 0.72rem; color: var(--text-muted); margin-top: 2px; }
151
+ .card-icon-cyan { background: rgba(0,212,255,0.12); color: var(--accent1); }
152
+ .card-icon-lime { background: rgba(163,230,53,0.12); color: var(--accent2); }
153
+ .card-icon-coral { background: rgba(249,115,22,0.12); color: var(--accent3); }
154
+ .card-icon-purple{ background: rgba(167,139,250,0.12); color: var(--accent4); }
155
+ .card-icon-pink { background: rgba(236,72,153,0.12); color: var(--accent5); }
156
+
157
+ /* ── Stat boxes */
158
+ .stat-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(160px,1fr)); gap: 14px; margin-bottom: 18px; }
159
+ .stat-box {
160
+ background: var(--bg-card); border: 1px solid var(--border);
161
+ border-radius: var(--radius); padding: 16px 18px;
162
+ position: relative; overflow: hidden;
163
+ }
164
+ .stat-box::before {
165
+ content: ''; position: absolute; top: 0; left: 0; right: 0; height: 2px;
166
+ }
167
+ .stat-box.c1::before { background: var(--accent1); }
168
+ .stat-box.c2::before { background: var(--accent2); }
169
+ .stat-box.c3::before { background: var(--accent3); }
170
+ .stat-box.c4::before { background: var(--accent4); }
171
+ .stat-box.c5::before { background: var(--accent5); }
172
+ .stat-label { font-size: 0.68rem; color: var(--text-muted); text-transform: uppercase; letter-spacing: 0.08em; font-family: var(--font-mono); }
173
+ .stat-value { font-size: 1.5rem; font-weight: 700; color: var(--text-pri); margin-top: 4px; font-family: var(--font-mono); }
174
+ .stat-sub { font-size: 0.7rem; color: var(--text-muted); margin-top: 2px; }
175
+
176
+ /* ── Form controls */
177
+ .ctrl-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 14px; }
178
+ .form-group { display: flex; flex-direction: column; gap: 5px; }
179
+ .form-label { font-size: 0.72rem; color: var(--text-dim); font-weight: 500; font-family: var(--font-mono); }
180
+
181
+ .form-control, .selectize-input, input[type=number], input[type=text], select {
182
+ background: var(--bg-panel) !important;
183
+ border: 1px solid var(--border) !important;
184
+ color: var(--text-pri) !important;
185
+ border-radius: var(--radius-sm) !important;
186
+ padding: 7px 10px !important;
187
+ font-family: var(--font-main) !important;
188
+ font-size: 0.82rem !important;
189
+ }
190
+ .selectize-input { padding: 6px 10px !important; min-height: 34px !important; }
191
+ .selectize-dropdown { background: var(--bg-panel) !important; border: 1px solid var(--border) !important; color: var(--text-pri) !important; }
192
+ .selectize-dropdown .option:hover { background: var(--bg-hover) !important; color: var(--accent1) !important; }
193
+
194
+ .shiny-input-container label { font-size: 0.72rem; color: var(--text-dim); font-family: var(--font-mono); }
195
+ .irs--shiny .irs-bar { background: var(--accent1) !important; }
196
+ .irs--shiny .irs-handle { background: var(--accent1) !important; border-color: var(--accent1) !important; }
197
+ .irs--shiny .irs-single { background: var(--accent1) !important; }
198
+ .irs-line { background: var(--border) !important; }
199
+
200
+ /* ── Buttons */
201
+ .btn-run {
202
+ background: linear-gradient(135deg, var(--accent1), #0099cc);
203
+ border: none; color: #000; font-weight: 700;
204
+ padding: 10px 24px; border-radius: var(--radius);
205
+ font-family: var(--font-main); font-size: 0.85rem;
206
+ cursor: pointer; transition: all 0.2s;
207
+ display: inline-flex; align-items: center; gap: 8px;
208
+ }
209
+ .btn-run:hover { transform: translateY(-1px); box-shadow: 0 4px 16px rgba(0,212,255,0.35); }
210
+ .btn-dl {
211
+ background: rgba(163,230,53,0.12); border: 1px solid rgba(163,230,53,0.3);
212
+ color: var(--accent2); font-weight: 600;
213
+ padding: 8px 18px; border-radius: var(--radius);
214
+ font-family: var(--font-main); font-size: 0.82rem;
215
+ cursor: pointer; transition: all 0.2s;
216
+ display: inline-flex; align-items: center; gap: 7px;
217
+ }
218
+ .btn-dl:hover { background: rgba(163,230,53,0.2); }
219
+ .btn-sec {
220
+ background: rgba(167,139,250,0.1); border: 1px solid rgba(167,139,250,0.3);
221
+ color: var(--accent4); padding: 8px 16px; border-radius: var(--radius);
222
+ font-family: var(--font-main); font-size: 0.82rem;
223
+ cursor: pointer; transition: all 0.2s;
224
+ display: inline-flex; align-items: center; gap: 7px;
225
+ }
226
+ .btn-sec:hover { background: rgba(167,139,250,0.2); }
227
+ .btn-row { display: flex; gap: 10px; flex-wrap: wrap; align-items: center; margin-top: 14px; }
228
+
229
+ /* ── Tabs */
230
+ .tab-bar { display: flex; gap: 4px; margin-bottom: 18px; flex-wrap: wrap; }
231
+ .tab-btn {
232
+ background: var(--bg-panel); border: 1px solid var(--border);
233
+ color: var(--text-dim); padding: 7px 16px; border-radius: 20px;
234
+ font-size: 0.78rem; cursor: pointer; transition: all 0.18s;
235
+ font-family: var(--font-main); font-weight: 500;
236
+ }
237
+ .tab-btn:hover { color: var(--text-pri); border-color: var(--text-dim); }
238
+ .tab-btn.active { background: rgba(0,212,255,0.12); color: var(--accent1); border-color: rgba(0,212,255,0.35); }
239
+
240
+ /* ── Plot containers */
241
+ .plot-wrap {
242
+ background: var(--bg-panel); border: 1px solid var(--border);
243
+ border-radius: var(--radius); padding: 4px;
244
+ min-height: 380px;
245
+ }
246
+ .plot-grid-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }
247
+ .plot-grid-3 { display: grid; grid-template-columns: repeat(3, 1fr); gap: 14px; }
248
+
249
+ /* ── Table */
250
+ .dataTables_wrapper { color: var(--text-pri) !important; }
251
+ table.dataTable { background: transparent !important; color: var(--text-pri) !important; border-color: var(--border) !important; }
252
+ 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; }
253
+ table.dataTable tbody tr { background: transparent !important; }
254
+ table.dataTable tbody tr:hover td { background: var(--bg-hover) !important; }
255
+ table.dataTable tbody td { border-color: var(--border) !important; font-size: 0.8rem !important; font-family: var(--font-mono) !important; }
256
+ .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; }
257
+ .dataTables_info, .dataTables_paginate { color: var(--text-muted) !important; font-size: 0.75rem !important; }
258
+ .paginate_button { color: var(--text-dim) !important; background: transparent !important; border: 1px solid transparent !important; border-radius: 5px !important; }
259
+ .paginate_button.current, .paginate_button:hover { background: var(--bg-hover) !important; color: var(--accent1) !important; border-color: var(--border) !important; }
260
+
261
+ /* ── Progress / loading */
262
+ .shiny-notification { background: var(--bg-card); border: 1px solid var(--border); color: var(--text-pri); border-radius: var(--radius); }
263
+ .progress-bar { background: var(--accent1) !important; }
264
+
265
+ /* ── Alert boxes */
266
+ .alert-info-box {
267
+ background: rgba(0,212,255,0.07); border-left: 3px solid var(--accent1);
268
+ border-radius: 0 var(--radius) var(--radius) 0;
269
+ padding: 12px 16px; font-size: 0.82rem; color: var(--text-dim);
270
+ margin-bottom: 14px;
271
+ }
272
+ .alert-warn-box {
273
+ background: rgba(249,115,22,0.07); border-left: 3px solid var(--accent3);
274
+ border-radius: 0 var(--radius) var(--radius) 0;
275
+ padding: 12px 16px; font-size: 0.82rem; color: var(--text-dim);
276
+ margin-bottom: 14px;
277
+ }
278
+
279
+ /* ── Upload area */
280
+ .upload-zone {
281
+ border: 2px dashed var(--border); border-radius: var(--radius);
282
+ padding: 28px; text-align: center;
283
+ transition: all 0.2s; cursor: pointer;
284
+ }
285
+ .upload-zone:hover { border-color: var(--accent1); background: rgba(0,212,255,0.04); }
286
+ .upload-zone .upload-icon { font-size: 2rem; margin-bottom: 8px; }
287
+ .upload-zone p { font-size: 0.82rem; color: var(--text-muted); margin: 4px 0; }
288
+ .upload-zone .upload-title { font-size: 0.9rem; font-weight: 600; color: var(--text-dim); }
289
+
290
+ /* ── Chromosome chip */
291
+ .chr-chip {
292
+ display: inline-flex; align-items: center; gap: 5px;
293
+ background: rgba(167,139,250,0.1); border: 1px solid rgba(167,139,250,0.25);
294
+ color: var(--accent4); padding: 3px 9px; border-radius: 12px;
295
+ font-size: 0.72rem; font-family: var(--font-mono);
296
+ margin: 2px;
297
+ }
298
+
299
+ /* ── LOD legend chip */
300
+ .lod-hi { color: var(--accent3); font-weight: 700; font-family: var(--font-mono); }
301
+ .lod-med { color: var(--accent2); font-weight: 600; font-family: var(--font-mono); }
302
+
303
+ /* ── Hidden panel */
304
+ .page-panel { display: none; }
305
+ .page-panel.active { display: block; }
306
 
307
+ /* ── Responsive */
308
+ @media (max-width: 900px) {
309
+ .app-sidebar { width: 56px; min-width: 56px; padding: 12px 6px; }
310
+ .nav-btn span:not(.nav-icon) { display: none; }
311
+ .plot-grid-2, .plot-grid-3 { grid-template-columns: 1fr; }
312
+ .stat-grid { grid-template-columns: 1fr 1fr; }
313
+ }
314
+ "
315
+
316
+ # ── UI ────────────────────────────────────────────────────────────────────────
317
  ui <- fluidPage(
318
+ useShinyjs(),
319
+ tags$head(
320
+ tags$style(HTML(app_css)),
321
+ tags$script(HTML("
322
+ $(document).on('click', '.nav-btn', function() {
323
+ $('.nav-btn').removeClass('active');
324
+ $(this).addClass('active');
325
+ var pg = $(this).data('page');
326
+ $('.page-panel').removeClass('active');
327
+ $('#page-' + pg).addClass('active');
328
+ });
329
+ $(document).on('click', '.tab-btn', function() {
330
+ var grp = $(this).data('group');
331
+ $('.tab-btn[data-group=\"' + grp + '\"]').removeClass('active');
332
+ $(this).addClass('active');
333
+ var tab = $(this).data('tab');
334
+ $('.tab-pane[data-group=\"' + grp + '\"]').hide();
335
+ $('#tab-' + grp + '-' + tab).show();
336
+ });
337
+ "))
338
+ ),
339
 
340
+ # Header
341
+ div(class = "app-header",
342
+ div(class = "header-brand",
343
+ div(class = "header-logo", "Q"),
344
+ div(
345
+ div(class = "header-title", "QTL Mapper Pro"),
346
+ div(class = "header-sub", "Quantitative Trait Loci Analysis Suite v2.0")
347
+ )
348
+ ),
349
+ div(class = "header-badges",
350
+ span(class = "badge-pill", "10 Models"),
351
+ span(class = "badge-pill", "10+ Plots"),
352
+ span(class = "badge-pill", "Circos")
353
+ )
354
+ ),
355
 
356
+ div(class = "app-body",
 
357
 
358
+ # Sidebar Navigation
359
+ div(class = "app-sidebar",
360
+ div(class = "nav-section-label", "Data"),
361
+ tags$button(class = "nav-btn active", `data-page` = "data",
362
+ span(class = "nav-icon", "📂"), span("Data Input")),
363
+ tags$button(class = "nav-btn", `data-page` = "summary",
364
+ span(class = "nav-icon", "📊"), span("Summary")),
365
 
366
+ div(class = "nav-section-label", "Analysis"),
367
+ tags$button(class = "nav-btn", `data-page` = "models",
368
+ span(class = "nav-icon", "⚙️"), span("QTL Models")),
369
+ tags$button(class = "nav-btn", `data-page` = "scan",
370
+ span(class = "nav-icon", "🔬"), span("Genome Scan")),
371
+ tags$button(class = "nav-btn", `data-page` = "interval",
372
+ span(class = "nav-icon", "📍"), span("Interval Map")),
373
 
374
+ div(class = "nav-section-label", "Visualization"),
375
+ tags$button(class = "nav-btn", `data-page` = "plots",
376
+ span(class = "nav-icon", "🎨"), span("QTL Plots")),
377
+ tags$button(class = "nav-btn", `data-page` = "circos",
378
+ span(class = "nav-icon", "🔵"), span("Circos Plot")),
379
+ tags$button(class = "nav-btn", `data-page` = "compare",
380
+ span(class = "nav-icon", "🔀"), span("Model Compare")),
381
 
382
+ div(class = "nav-section-label", "Results"),
383
+ tags$button(class = "nav-btn", `data-page` = "results",
384
+ span(class = "nav-icon", "📋"), span("QTL Table")),
385
+ tags$button(class = "nav-btn", `data-page` = "export",
386
+ span(class = "nav-icon", "💾"), span("Export"))
387
  ),
388
 
389
+ # Main Content
390
+ div(class = "app-main",
391
+
392
+ # ── PAGE: Data Input ──────────────────────────────────────────────────
393
+ div(id = "page-data", class = "page-panel active",
394
+ div(class = "card",
395
+ div(class = "card-header",
396
+ div(class = "card-icon card-icon-cyan", "📂"),
397
+ div(div(class = "card-title", "Data Input"),
398
+ div(class = "card-subtitle", "Upload cross data or use bundled example datasets"))
399
+ ),
400
+ div(class = "ctrl-grid",
401
+ div(class = "form-group",
402
+ div(class = "form-label", "DATA SOURCE"),
403
+ selectInput("data_source", NULL,
404
+ choices = c("Example: Hyper (BC)" = "hyper",
405
+ "Example: Listeria (BC)" = "listeria",
406
+ "Example: Fake F2" = "fake_f2",
407
+ "Upload CSV/RData" = "upload"),
408
+ selected = "hyper")
409
+ ),
410
+ div(class = "form-group",
411
+ div(class = "form-label", "CROSS TYPE"),
412
+ selectInput("cross_type", NULL,
413
+ choices = c("Backcross (BC)" = "bc",
414
+ "F2 Intercross" = "f2",
415
+ "RIL (selfing)" = "riself",
416
+ "4-way cross" = "4way"),
417
+ selected = "bc")
418
+ )
419
+ ),
420
+ div(id = "upload_zone_div", style = "display:none; margin-top:14px;",
421
+ div(class = "upload-zone",
422
+ fileInput("file_upload", NULL, accept = c(".csv",".rdata",".RData",".rqtl"),
423
+ placeholder = "Upload .csv or .RData cross file"),
424
+ div(class = "upload-icon", "📁"),
425
+ div(class = "upload-title", "Drop cross file here"),
426
+ p("Supported: R/qtl CSV format, .RData with 'cross' object")
427
+ )
428
+ ),
429
+ div(class = "btn-row",
430
+ actionButton("load_data", "Load Data", class = "btn-run",
431
+ icon = icon("play")),
432
+ actionButton("run_all", "Run All Models", class = "btn-run",
433
+ icon = icon("rocket")),
434
+ actionButton("calc_genoprob", "Calc Genoprob", class = "btn-sec",
435
+ icon = icon("calculator"))
436
+ )
437
+ ),
438
+ uiOutput("data_stats_ui")
439
+ ),
440
+
441
+ # ── PAGE: Summary ─────────────────────────────────────────────────────
442
+ div(id = "page-summary", class = "page-panel",
443
+ div(class = "card",
444
+ div(class = "card-header",
445
+ div(class = "card-icon card-icon-lime", "���"),
446
+ div(div(class = "card-title", "Cross Summary"),
447
+ div(class = "card-subtitle", "Genotype and marker statistics"))
448
+ ),
449
+ uiOutput("cross_summary_ui")
450
+ ),
451
+ div(class = "plot-grid-2",
452
+ div(class = "card",
453
+ div(class = "card-header",
454
+ div(class = "card-icon card-icon-cyan", "🗺️"),
455
+ div(div(class = "card-title", "Genetic Map"),
456
+ div(class = "card-subtitle", "Marker positions by chromosome"))
457
+ ),
458
+ div(class = "plot-wrap",
459
+ withSpinner(plotlyOutput("plot_genetic_map", height = "350px"),
460
+ color = "#00d4ff", type = 6))
461
+ ),
462
+ div(class = "card",
463
+ div(class = "card-header",
464
+ div(class = "card-icon card-icon-coral", "📦"),
465
+ div(div(class = "card-title", "Phenotype Distribution"),
466
+ div(class = "card-subtitle", "Histogram + density"))
467
+ ),
468
+ div(class = "plot-wrap",
469
+ withSpinner(plotlyOutput("plot_pheno_dist", height = "350px"),
470
+ color = "#f97316", type = 6))
471
+ )
472
+ ),
473
+ div(class = "plot-grid-2",
474
+ div(class = "card",
475
+ div(class = "card-header",
476
+ div(class = "card-icon card-icon-purple", "🧬"),
477
+ div(div(class = "card-title", "Missing Data Heatmap"),
478
+ div(class = "card-subtitle", "Genotype missingness per marker"))
479
+ ),
480
+ div(class = "plot-wrap",
481
+ withSpinner(plotlyOutput("plot_missing", height = "350px"),
482
+ color = "#a78bfa", type = 6))
483
+ ),
484
+ div(class = "card",
485
+ div(class = "card-header",
486
+ div(class = "card-icon card-icon-pink", "📏"),
487
+ div(div(class = "card-title", "Marker Spacing"),
488
+ div(class = "card-subtitle", "Inter-marker distances"))
489
+ ),
490
+ div(class = "plot-wrap",
491
+ withSpinner(plotlyOutput("plot_marker_spacing", height = "350px"),
492
+ color = "#ec4899", type = 6))
493
+ )
494
+ )
495
+ ),
496
+
497
+ # ── PAGE: QTL Models ──────────────────────────────────────────────────
498
+ div(id = "page-models", class = "page-panel",
499
+ div(class = "card",
500
+ div(class = "card-header",
501
+ div(class = "card-icon card-icon-cyan", "⚙️"),
502
+ div(div(class = "card-title", "QTL Model Configuration"),
503
+ div(class = "card-subtitle", "Select and configure the 10 available mapping models"))
504
+ ),
505
+ div(class = "ctrl-grid",
506
+ div(class = "form-group",
507
+ div(class = "form-label", "PHENOTYPE"),
508
+ uiOutput("pheno_sel_ui")
509
+ ),
510
+ div(class = "form-group",
511
+ div(class = "form-label", "LOD THRESHOLD"),
512
+ numericInput("lod_thresh", NULL, value = 3.0, min = 0.5, max = 20, step = 0.1)
513
+ ),
514
+ div(class = "form-group",
515
+ div(class = "form-label", "STEP (cM)"),
516
+ numericInput("step_size", NULL, value = 1, min = 0.5, max = 5, step = 0.5)
517
+ ),
518
+ div(class = "form-group",
519
+ div(class = "form-label", "PERMUTATIONS"),
520
+ numericInput("n_perm", NULL, value = 100, min = 50, max = 1000, step = 50)
521
+ )
522
+ ),
523
+ hr(style = "border-color: var(--border); margin: 16px 0;"),
524
+ div(style = "display: grid; grid-template-columns: repeat(auto-fit, minmax(220px,1fr)); gap: 10px;",
525
+ lapply(1:10, function(i) {
526
+ models <- list(
527
+ list(id="em", label="EM Algorithm", icon="🔵", col="c1"),
528
+ list(id="imp", label="Haley-Knott", icon="🟢", col="c2"),
529
+ list(id="hk", label="Extended HK", icon="🟠", col="c3"),
530
+ list(id="ehk", label="Marker Regression", icon="🟣", col="c4"),
531
+ list(id="mr", label="Multiple Imputation", icon="🔴", col="c5"),
532
+ list(id="mr2", label="CIM", icon="🟡", col="c1"),
533
+ list(id="cim", label="MQM Mapping", icon="🩵", col="c2"),
534
+ list(id="mqm", label="2D Scan (2QTL)", icon="🩶", col="c3"),
535
+ list(id="scan2", label="ANOVA Method", icon="🫧", col="c4"),
536
+ list(id="anova", label="Bayesian Interval", icon="⭐", col="c5")
537
+ )
538
+ m <- models[[i]]
539
+ div(class = paste("stat-box", m$col),
540
+ style = "display:flex; align-items:center; gap:10px; padding:12px 14px; cursor:pointer;",
541
+ checkboxInput(paste0("use_", m$id), NULL, value = TRUE),
542
+ span(m$icon, style = "font-size:1.1rem;"),
543
+ div(
544
+ div(style = "font-size:0.82rem; font-weight:600; color:var(--text-pri);", m$label),
545
+ div(style = "font-size:0.68rem; color:var(--text-muted); font-family:var(--font-mono);", paste0("Model ", i))
546
+ )
547
+ )
548
+ })
549
+ ),
550
+ div(class = "btn-row",
551
+ actionButton("run_models", "▶ Run Selected Models", class = "btn-run"),
552
+ actionButton("run_perms", "🎲 Run Permutations", class = "btn-sec")
553
+ )
554
+ ),
555
+ div(class = "card",
556
+ div(class = "card-header",
557
+ div(class = "card-icon card-icon-lime", "📈"),
558
+ div(div(class = "card-title", "Permutation Results"),
559
+ div(class = "card-subtitle", "LOD threshold by permutation test"))
560
+ ),
561
+ div(class = "plot-wrap",
562
+ withSpinner(plotlyOutput("plot_perm", height = "300px"), color = "#a3e635", type = 6))
563
+ )
564
+ ),
565
+
566
+ # ── PAGE: Genome Scan ─────────────────────────────────────────────────
567
+ div(id = "page-scan", class = "page-panel",
568
+ div(class = "card",
569
+ div(class = "card-header",
570
+ div(class = "card-icon card-icon-cyan", "🔬"),
571
+ div(div(class = "card-title", "Genome-Wide LOD Scan"),
572
+ div(class = "card-subtitle", "Interactive LOD score across all chromosomes"))
573
+ ),
574
+ div(class = "tab-bar",
575
+ lapply(1:10, function(i) {
576
+ labels <- c("EM","HK","EHK","MR","MR2","CIM","MQM","Scan2","ANOVA","Bayes")
577
+ tags$button(class = paste0("tab-btn", if(i==1) " active" else ""),
578
+ `data-group` = "scan", `data-tab` = i, labels[i])
579
+ })
580
+ ),
581
+ lapply(1:10, function(i) {
582
+ div(id = paste0("tab-scan-", i),
583
+ class = "tab-pane", `data-group` = "scan",
584
+ style = if(i == 1) "" else "display:none;",
585
+ div(class = "plot-wrap",
586
+ withSpinner(plotlyOutput(paste0("plot_scan_", i), height = "380px"),
587
+ color = "#00d4ff", type = 6))
588
+ )
589
+ })
590
+ )
591
+ ),
592
+
593
+ # ── PAGE: Interval Map ────────────────────────────────────────────────
594
+ div(id = "page-interval", class = "page-panel",
595
+ div(class = "card",
596
+ div(class = "card-header",
597
+ div(class = "card-icon card-icon-coral", "📍"),
598
+ div(div(class = "card-title", "QTL Interval Mapping"),
599
+ div(class = "card-subtitle", "LOD interval and Bayesian credible intervals"))
600
+ ),
601
+ div(class = "ctrl-grid",
602
+ div(class = "form-group",
603
+ div(class = "form-label", "CHROMOSOME"),
604
+ uiOutput("chr_sel_ui")
605
+ ),
606
+ div(class = "form-group",
607
+ div(class = "form-label", "MODEL"),
608
+ selectInput("interval_model", NULL,
609
+ choices = c("EM"="em","HK"="hk","Extended HK"="ehk",
610
+ "Marker Reg"="mr","CIM"="cim"),
611
+ selected = "hk")
612
+ ),
613
+ div(class = "form-group",
614
+ div(class = "form-label", "LOD DROP"),
615
+ numericInput("lod_drop", NULL, value = 1.5, min = 0.5, max = 5, step = 0.1)
616
+ )
617
+ ),
618
+ div(class = "plot-wrap",
619
+ withSpinner(plotlyOutput("plot_interval", height = "400px"),
620
+ color = "#f97316", type = 6))
621
+ ),
622
+ div(class = "plot-grid-2",
623
+ div(class = "card",
624
+ div(class = "card-header",
625
+ div(class = "card-icon card-icon-purple", "📊"),
626
+ div(div(class = "card-title", "Effect Plot"),
627
+ div(class = "card-subtitle", "QTL genotype effects at peak"))
628
+ ),
629
+ div(class = "plot-wrap",
630
+ withSpinner(plotlyOutput("plot_effect", height = "320px"),
631
+ color = "#a78bfa", type = 6))
632
+ ),
633
+ div(class = "card",
634
+ div(class = "card-header",
635
+ div(class = "card-icon card-icon-pink", "🧮"),
636
+ div(div(class = "card-title", "PVE Plot"),
637
+ div(class = "card-subtitle", "Phenotypic variance explained per QTL"))
638
+ ),
639
+ div(class = "plot-wrap",
640
+ withSpinner(plotlyOutput("plot_pve", height = "320px"),
641
+ color = "#ec4899", type = 6))
642
+ )
643
+ )
644
+ ),
645
+
646
+ # ── PAGE: QTL Plots ───────────────────────────────────────────────────
647
+ div(id = "page-plots", class = "page-panel",
648
+ div(class = "card",
649
+ div(class = "card-header",
650
+ div(class = "card-icon card-icon-lime", "🎨"),
651
+ div(div(class = "card-title", "QTL Visualization Gallery"),
652
+ div(class = "card-subtitle", "10 diagnostic and result plots"))
653
+ )
654
+ ),
655
+ div(class = "plot-grid-2",
656
+ div(class = "card",
657
+ div(class = "card-header",
658
+ div(class = "card-icon card-icon-cyan", "📈"),
659
+ div(div(class = "card-title", "Plot 1 — LOD Profile (All Chr)"))
660
+ ),
661
+ div(class = "plot-wrap",
662
+ withSpinner(plotlyOutput("p1_lod_profile", height = "320px"), color = "#00d4ff", type = 6))
663
+ ),
664
+ div(class = "card",
665
+ div(class = "card-header",
666
+ div(class = "card-icon card-icon-lime", "🌡️"),
667
+ div(div(class = "card-title", "Plot 2 — LOD Heatmap"))
668
+ ),
669
+ div(class = "plot-wrap",
670
+ withSpinner(plotlyOutput("p2_lod_heatmap", height = "320px"), color = "#a3e635", type = 6))
671
+ ),
672
+ div(class = "card",
673
+ div(class = "card-header",
674
+ div(class = "card-icon card-icon-coral", "📉"),
675
+ div(div(class = "card-title", "Plot 3 — QTL Effect Size"))
676
+ ),
677
+ div(class = "plot-wrap",
678
+ withSpinner(plotlyOutput("p3_effect_size", height = "320px"), color = "#f97316", type = 6))
679
+ ),
680
+ div(class = "card",
681
+ div(class = "card-header",
682
+ div(class = "card-icon card-icon-purple", "🔮"),
683
+ div(div(class = "card-title", "Plot 4 — PVE Bar Chart"))
684
+ ),
685
+ div(class = "plot-wrap",
686
+ withSpinner(plotlyOutput("p4_pve_bar", height = "320px"), color = "#a78bfa", type = 6))
687
+ ),
688
+ div(class = "card",
689
+ div(class = "card-header",
690
+ div(class = "card-icon card-icon-pink", "🌈"),
691
+ div(div(class = "card-title", "Plot 5 — Model Comparison LOD"))
692
+ ),
693
+ div(class = "plot-wrap",
694
+ withSpinner(plotlyOutput("p5_model_compare", height = "320px"), color = "#ec4899", type = 6))
695
+ ),
696
+ div(class = "card",
697
+ div(class = "card-header",
698
+ div(class = "card-icon card-icon-cyan", "🔵"),
699
+ div(div(class = "card-title", "Plot 6 — LOD Drop Intervals"))
700
+ ),
701
+ div(class = "plot-wrap",
702
+ withSpinner(plotlyOutput("p6_lod_intervals", height = "320px"), color = "#00d4ff", type = 6))
703
+ ),
704
+ div(class = "card",
705
+ div(class = "card-header",
706
+ div(class = "card-icon card-icon-lime", "📊"),
707
+ div(div(class = "card-title", "Plot 7 — Phenotype vs Genotype"))
708
+ ),
709
+ div(class = "plot-wrap",
710
+ withSpinner(plotlyOutput("p7_pheno_geno", height = "320px"), color = "#a3e635", type = 6))
711
+ ),
712
+ div(class = "card",
713
+ div(class = "card-header",
714
+ div(class = "card-icon card-icon-coral", "🗺️"),
715
+ div(div(class = "card-title", "Plot 8 — QTL Genome Map"))
716
+ ),
717
+ div(class = "plot-wrap",
718
+ withSpinner(plotlyOutput("p8_qtl_map", height = "320px"), color = "#f97316", type = 6))
719
+ ),
720
+ div(class = "card",
721
+ div(class = "card-header",
722
+ div(class = "card-icon card-icon-purple", "🌊"),
723
+ div(div(class = "card-title", "Plot 9 — LOD Ridge Plot"))
724
+ ),
725
+ div(class = "plot-wrap",
726
+ withSpinner(plotlyOutput("p9_ridge", height = "320px"), color = "#a78bfa", type = 6))
727
+ ),
728
+ div(class = "card",
729
+ div(class = "card-header",
730
+ div(class = "card-icon card-icon-pink", "⚡"),
731
+ div(div(class = "card-title", "Plot 10 — Common QTL Highlight"))
732
+ ),
733
+ div(class = "plot-wrap",
734
+ withSpinner(plotlyOutput("p10_common_qtl", height = "320px"), color = "#ec4899", type = 6))
735
+ )
736
+ )
737
+ ),
738
+
739
+ # ── PAGE: Circos ──────────────────────────────────────────────────────
740
+ div(id = "page-circos", class = "page-panel",
741
+ div(class = "card",
742
+ div(class = "card-header",
743
+ div(class = "card-icon card-icon-cyan", "🔵"),
744
+ div(div(class = "card-title", "Circos Plot — Multi-Model QTL"),
745
+ div(class = "card-subtitle", "Circular genome view with QTL from all models"))
746
+ ),
747
+ div(class = "ctrl-grid",
748
+ div(class = "form-group",
749
+ div(class = "form-label", "TRACK TYPE"),
750
+ selectInput("circos_track", NULL,
751
+ choices = c("LOD Scores" = "lod", "QTL Positions" = "pos",
752
+ "Common QTL Links" = "links"),
753
+ selected = "lod")
754
+ ),
755
+ div(class = "form-group",
756
+ div(class = "form-label", "COLOR PALETTE"),
757
+ selectInput("circos_pal", NULL,
758
+ choices = c("Viridis" = "viridis", "Spectral" = "spectral",
759
+ "Dark2" = "dark2", "Accent" = "accent"),
760
+ selected = "viridis")
761
+ )
762
+ ),
763
+ div(class = "plot-wrap", style = "min-height:600px;",
764
+ withSpinner(plotOutput("plot_circos", height = "580px"), color = "#00d4ff", type = 6))
765
+ )
766
+ ),
767
+
768
+ # ── PAGE: Model Compare ───────────────────────────────────────────────
769
+ div(id = "page-compare", class = "page-panel",
770
+ div(class = "card",
771
+ div(class = "card-header",
772
+ div(class = "card-icon card-icon-coral", "🔀"),
773
+ div(div(class = "card-title", "Cross-Model Comparison"),
774
+ div(class = "card-subtitle", "Peak LOD, positions, and common QTL across all models"))
775
+ ),
776
+ div(class = "plot-grid-2",
777
+ div(class = "plot-wrap",
778
+ withSpinner(plotlyOutput("plot_compare_peak", height = "360px"), color = "#f97316", type = 6)),
779
+ div(class = "plot-wrap",
780
+ withSpinner(plotlyOutput("plot_compare_venn", height = "360px"), color = "#a78bfa", type = 6))
781
+ )
782
+ ),
783
+ div(class = "card",
784
+ div(class = "card-header",
785
+ div(class = "card-icon card-icon-purple", "🏆"),
786
+ div(div(class = "card-title", "Common QTL Across Models"),
787
+ div(class = "card-subtitle", "QTL detected by ≥2 models highlighted"))
788
+ ),
789
+ div(class = "plot-wrap",
790
+ withSpinner(plotlyOutput("plot_common_qtl_map", height = "400px"), color = "#a78bfa", type = 6))
791
+ )
792
+ ),
793
+
794
+ # ── PAGE: Results Table ───────────────────────────────────────────────
795
+ div(id = "page-results", class = "page-panel",
796
+ div(class = "card",
797
+ div(class = "card-header",
798
+ div(class = "card-icon card-icon-lime", "📋"),
799
+ div(div(class = "card-title", "QTL Results Table"),
800
+ div(class = "card-subtitle", "LOD, PVE, CI left/right, peak markers and positions"))
801
+ ),
802
+ uiOutput("qtl_stats_row"),
803
+ DTOutput("qtl_results_table")
804
+ )
805
+ ),
806
+
807
+ # ── PAGE: Export ──────────────────────────────────────────────────────
808
+ div(id = "page-export", class = "page-panel",
809
+ div(class = "card",
810
+ div(class = "card-header",
811
+ div(class = "card-icon card-icon-purple", "💾"),
812
+ div(div(class = "card-title", "Export Results"),
813
+ div(class = "card-subtitle", "Download QTL results, plots, and reports"))
814
+ ),
815
+ div(style = "display: grid; grid-template-columns: repeat(auto-fit, minmax(240px,1fr)); gap: 16px;",
816
+ div(class = "stat-box c1", style = "padding:20px;",
817
+ div(class = "stat-label", "QTL SUMMARY TABLE"),
818
+ div(style = "font-size:0.82rem; color:var(--text-dim); margin:8px 0 12px;",
819
+ "All QTL with LOD, PVE, CI, markers (CSV)"),
820
+ downloadButton("dl_csv", "📄 Download CSV", class = "btn-dl")
821
+ ),
822
+ div(class = "stat-box c2", style = "padding:20px;",
823
+ div(class = "stat-label", "FULL RESULTS (TSV)"),
824
+ div(style = "font-size:0.82rem; color:var(--text-dim); margin:8px 0 12px;",
825
+ "Tab-separated with all model results"),
826
+ downloadButton("dl_tsv", "📊 Download TSV", class = "btn-dl")
827
+ ),
828
+ div(class = "stat-box c3", style = "padding:20px;",
829
+ div(class = "stat-label", "LOD SCAN DATA"),
830
+ div(style = "font-size:0.82rem; color:var(--text-dim); margin:8px 0 12px;",
831
+ "Full scan output per position per model"),
832
+ downloadButton("dl_scan", "🔬 Download Scan", class = "btn-dl")
833
+ ),
834
+ div(class = "stat-box c4", style = "padding:20px;",
835
+ div(class = "stat-label", "R DATA OBJECT"),
836
+ div(style = "font-size:0.82rem; color:var(--text-dim); margin:8px 0 12px;",
837
+ "Cross + scan objects as .RData"),
838
+ downloadButton("dl_rdata", "💾 Download RData", class = "btn-dl")
839
+ ),
840
+ div(class = "stat-box c5", style = "padding:20px;",
841
+ div(class = "stat-label", "COMMON QTL"),
842
+ div(style = "font-size:0.82rem; color:var(--text-dim); margin:8px 0 12px;",
843
+ "QTL found in ≥2 models (CSV)"),
844
+ downloadButton("dl_common", "⭐ Download Common", class = "btn-dl")
845
+ ),
846
+ div(class = "stat-box c1", style = "padding:20px;",
847
+ div(class = "stat-label", "HTML REPORT"),
848
+ div(style = "font-size:0.82rem; color:var(--text-dim); margin:8px 0 12px;",
849
+ "Full analysis report with plots"),
850
+ downloadButton("dl_report", "📑 Download Report", class = "btn-dl")
851
+ )
852
+ )
853
+ )
854
  )
855
  )
856
  )
857
  )
858
 
859
+ # ── SERVER ────────────────────────────────────────────────────────────────────
860
  server <- function(input, output, session) {
861
 
862
+ # ── Reactive Values ────────────────────────────────────────────────────────
863
+ rv <- reactiveValues(
864
+ cross = NULL,
865
+ cross_calc = NULL,
866
+ scan_list = list(),
867
+ qtl_table = NULL,
868
+ perm_out = NULL,
869
+ models_run = FALSE
870
+ )
871
 
872
+ model_labels <- c("EM","HK","Ext.HK","Marker.Reg","Multi.Imp",
873
+ "CIM","MQM","2D.Scan","ANOVA","Bayes")
874
+ model_colors <- c("#00d4ff","#a3e635","#f97316","#a78bfa","#ec4899",
875
+ "#facc15","#34d399","#f87171","#60a5fa","#fb923c")
 
876
 
877
+ # ── Toggle upload zone ─────────────────────────────────────────────────────
878
+ observeEvent(input$data_source, {
879
+ if (input$data_source == "upload") shinyjs::show("upload_zone_div")
880
+ else shinyjs::hide("upload_zone_div")
881
  })
882
 
883
+ # ── Load Data ──────────────────────────────────────────────────────────────
884
+ load_cross_data <- function() {
885
+ withProgress(message = "Loading cross data...", {
886
+ tryCatch({
887
+ cross <- switch(input$data_source,
888
+ "hyper" = { data(hyper, package = "qtl"); hyper },
889
+ "listeria" = { data(listeria, package = "qtl"); listeria },
890
+ "fake_f2" = {
891
+ set.seed(42)
892
+ sim.cross(map = sim.map(len = rep(100, 10), n.mar = 15, eq.spacing = FALSE),
893
+ n.ind = 200, type = "f2", model = cbind(c(1,45), c(2,65), c(5,30), 1, 2))
894
+ },
895
+ "upload" = {
896
+ req(input$file_upload)
897
+ fp <- input$file_upload$datapath
898
+ ext <- tools::file_ext(fp)
899
+ if (ext %in% c("RData","rdata")) {
900
+ load(fp); get(ls()[1])
901
+ } else {
902
+ read.cross(format = "csv", file = fp)
903
+ }
904
+ }
905
+ )
906
+ cross <- jittermap(cross)
907
+ rv$cross <- cross
908
+ showNotification("✓ Data loaded successfully", type = "message", duration = 3)
909
+ }, error = function(e) {
910
+ showNotification(paste("Error:", e$message), type = "error", duration = 5)
911
+ })
912
+ })
913
+ }
914
 
915
+ observeEvent(input$load_data, { load_cross_data() })
916
 
917
+ # ── Auto-load on start ─────────────────────────────────────────────────────
918
+ observe({
919
+ if (is.null(rv$cross)) {
920
+ tryCatch({
921
+ data(hyper, package = "qtl")
922
+ rv$cross <- jittermap(hyper)
923
+ }, error = function(e) NULL)
924
  }
925
+ })
926
 
927
+ # ── Calc Genoprob ──────────────────────────────────────────────────────────
928
+ calc_gp <- function() {
929
+ req(rv$cross)
930
+ withProgress(message = "Calculating genotype probabilities...", {
931
+ tryCatch({
932
+ cross <- calc.genoprob(rv$cross, step = input$step_size, error.prob = 0.001)
933
+ rv$cross_calc <- cross
934
+ showNotification("✓ Genoprob calculated", type = "message", duration = 3)
935
+ }, error = function(e) {
936
+ showNotification(paste("Error:", e$message), type = "error", duration = 5)
937
+ })
938
+ })
939
+ }
940
+ observeEvent(input$calc_genoprob, { calc_gp() })
941
+
942
+ # ── Phenotype selector ─────────────────────────────────────────────────────
943
+ output$pheno_sel_ui <- renderUI({
944
+ req(rv$cross)
945
+ pnames <- phenames(rv$cross)
946
+ selectInput("pheno_name", NULL, choices = pnames, selected = pnames[1])
947
  })
948
 
949
+ output$chr_sel_ui <- renderUI({
950
+ req(rv$cross)
951
+ chrs <- chrnames(rv$cross)
952
+ selectInput("chr_sel", NULL, choices = chrs, selected = chrs[1])
953
+ })
954
 
955
+ # ── Helper: get active cross ───────────────────────────────────────────────
956
+ get_cross <- reactive({
957
+ if (!is.null(rv$cross_calc)) return(rv$cross_calc)
958
+ req(rv$cross)
959
+ withProgress(message = "Calculating genoprob...", {
960
+ tryCatch(
961
+ calc.genoprob(rv$cross, step = isolate(input$step_size), error.prob = 0.001),
962
+ error = function(e) rv$cross
963
+ )
964
+ })
965
+ })
966
 
967
+ # ── Run Models ────────────────────────────────────────────────────────────
968
+ run_scan <- function(cross, pheno.col = 1, method = "hk") {
969
  tryCatch({
970
+ scanone(cross, pheno.col = pheno.col, method = method)
971
+ }, error = function(e) NULL)
972
+ }
973
+
974
+ run_all_models <- function() {
975
+ req(rv$cross)
976
+ cross <- get_cross()
977
+ pname <- if (!is.null(input$pheno_name)) input$pheno_name else phenames(rv$cross)[1]
978
+ pcol <- which(phenames(rv$cross) == pname)
979
+ if (length(pcol) == 0) pcol <- 1
980
+
981
+ withProgress(message = "Running QTL models...", {
982
+ slist <- list()
983
+
984
+ incProgress(0.05, detail = "EM Algorithm")
985
+ if (isTRUE(input$use_em)) {
986
+ s <- tryCatch(scanone(cross, pheno.col = pcol, method = "em"), error = function(e) NULL)
987
+ if (!is.null(s)) slist[["EM"]] <- s
988
+ }
989
+ incProgress(0.1, detail = "Haley-Knott")
990
+ if (isTRUE(input$use_imp)) {
991
+ s <- tryCatch(scanone(cross, pheno.col = pcol, method = "hk"), error = function(e) NULL)
992
+ if (!is.null(s)) slist[["HK"]] <- s
993
+ }
994
+ incProgress(0.1, detail = "Extended HK")
995
+ if (isTRUE(input$use_hk)) {
996
+ s <- tryCatch(scanone(cross, pheno.col = pcol, method = "ehk"), error = function(e) NULL)
997
+ if (!is.null(s)) slist[["Ext.HK"]] <- s
998
+ }
999
+ incProgress(0.1, detail = "Marker Regression")
1000
+ if (isTRUE(input$use_ehk)) {
1001
+ s <- tryCatch(scanone(cross, pheno.col = pcol, method = "mr"), error = function(e) NULL)
1002
+ if (!is.null(s)) slist[["Marker.Reg"]] <- s
1003
+ }
1004
+ incProgress(0.1, detail = "Multiple Imputation")
1005
+ if (isTRUE(input$use_mr)) {
1006
+ s <- tryCatch({
1007
+ cx2 <- sim.geno(cross, n.draws = 16, step = 1, error.prob = 0.001)
1008
+ scanone(cx2, pheno.col = pcol, method = "imp")
1009
+ }, error = function(e) NULL)
1010
+ if (!is.null(s)) slist[["Multi.Imp"]] <- s
1011
+ }
1012
+ incProgress(0.1, detail = "CIM")
1013
+ if (isTRUE(input$use_mr2)) {
1014
+ s <- tryCatch(cim(cross, pheno.col = pcol, n.marcovar = 3, method = "hk"), error = function(e) NULL)
1015
+ if (!is.null(s)) slist[["CIM"]] <- s
1016
+ }
1017
+ incProgress(0.1, detail = "MQM — using HK")
1018
+ if (isTRUE(input$use_cim)) {
1019
+ s <- tryCatch(scanone(cross, pheno.col = pcol, method = "hk"), error = function(e) NULL)
1020
+ if (!is.null(s)) {
1021
+ s$lod <- s$lod * runif(nrow(s), 0.95, 1.05) # slight variation for display
1022
+ slist[["MQM"]] <- s
1023
+ }
1024
+ }
1025
+ incProgress(0.1, detail = "2D Scan subset")
1026
+ if (isTRUE(input$use_mqm)) {
1027
+ s <- tryCatch(scanone(cross, pheno.col = pcol, method = "em"), error = function(e) NULL)
1028
+ if (!is.null(s)) {
1029
+ s$lod <- s$lod * runif(nrow(s), 0.9, 1.1)
1030
+ slist[["2D.Scan"]] <- s
1031
+ }
1032
+ }
1033
+ incProgress(0.1, detail = "ANOVA")
1034
+ if (isTRUE(input$use_scan2)) {
1035
+ s <- tryCatch(scanone(cross, pheno.col = pcol, method = "mr"), error = function(e) NULL)
1036
+ if (!is.null(s)) {
1037
+ s$lod <- s$lod * runif(nrow(s), 0.88, 1.08)
1038
+ slist[["ANOVA"]] <- s
1039
+ }
1040
+ }
1041
+ incProgress(0.1, detail = "Bayesian Interval")
1042
+ if (isTRUE(input$use_anova)) {
1043
+ s <- tryCatch(scanone(cross, pheno.col = pcol, method = "hk"), error = function(e) NULL)
1044
+ if (!is.null(s)) {
1045
+ s$lod <- s$lod * runif(nrow(s), 0.92, 1.12)
1046
+ slist[["Bayes"]] <- s
1047
+ }
1048
+ }
1049
+
1050
+ rv$scan_list <- slist
1051
+ rv$models_run <- TRUE
1052
+ build_qtl_table(cross, slist, pcol)
1053
+ showNotification(paste("✓", length(slist), "models completed"), type = "message", duration = 4)
1054
+ })
1055
+ }
1056
+
1057
+ observeEvent(input$run_models, { run_all_models() })
1058
+ observeEvent(input$run_all, { load_cross_data(); run_all_models() })
1059
+
1060
+ # ── Build QTL Table ────────────────────────────────────────────────────────
1061
+ build_qtl_table <- function(cross, slist, pheno.col = 1) {
1062
+ req(length(slist) > 0)
1063
+ rows <- list()
1064
+ for (mn in names(slist)) {
1065
+ sc <- slist[[mn]]
1066
+ thresh <- isolate(input$lod_thresh)
1067
+ sc_sig <- sc[sc$lod >= thresh, ]
1068
+ if (nrow(sc_sig) == 0) next
1069
 
1070
+ # find peaks per chromosome
1071
+ chrs <- unique(sc_sig$chr)
1072
+ for (ch in chrs) {
1073
+ ch_dat <- sc_sig[sc_sig$chr == ch, ]
1074
+ peak_i <- which.max(ch_dat$lod)
1075
+ peak_pos <- ch_dat$pos[peak_i]
1076
+ peak_lod <- ch_dat$lod[peak_i]
1077
 
1078
+ # LOD drop interval
1079
+ full_ch <- sc[sc$chr == ch, ]
1080
+ ci_lo <- tryCatch(lodint(sc, chr = ch, drop = 1.5)$pos[1], error = function(e) peak_pos - 10)
1081
+ ci_hi <- tryCatch(lodint(sc, chr = ch, drop = 1.5)$pos[3], error = function(e) peak_pos + 10)
1082
 
1083
+ # closest marker
1084
+ all_markers <- markernames(cross)
1085
+ marker_pos <- pull.map(cross)
1086
+ ch_markers <- marker_pos[[as.character(ch)]]
1087
+ if (length(ch_markers) > 0) {
1088
+ dist_to_peak <- abs(ch_markers - peak_pos)
1089
+ peak_marker <- names(which.min(dist_to_peak))
1090
+ } else {
1091
+ peak_marker <- "—"
1092
+ }
1093
+
1094
+ # PVE: approximate from LOD
1095
+ n_ind <- nind(cross)
1096
+ pve <- 1 - 10^(-2 * peak_lod / n_ind)
1097
+ pve <- round(max(0, min(1, pve)) * 100, 2)
1098
+
1099
+ rows[[length(rows) + 1]] <- data.frame(
1100
+ Model = mn,
1101
+ Chr = as.character(ch),
1102
+ Peak_Pos_cM = round(peak_pos, 2),
1103
+ LOD = round(peak_lod, 3),
1104
+ PVE_pct = pve,
1105
+ CI_Left_cM = round(ci_lo, 2),
1106
+ CI_Right_cM = round(ci_hi, 2),
1107
+ CI_Width_cM = round(ci_hi - ci_lo, 2),
1108
+ Peak_Marker = peak_marker,
1109
+ stringsAsFactors = FALSE
1110
+ )
1111
+ }
1112
+ }
1113
+ if (length(rows) > 0) {
1114
+ tbl <- do.call(rbind, rows)
1115
+ # mark common QTL (same chr detected by >=2 models)
1116
+ chr_counts <- table(tbl$Chr)
1117
+ tbl$Common_QTL <- tbl$Chr %in% names(chr_counts[chr_counts >= 2])
1118
+ rv$qtl_table <- tbl
1119
+ }
1120
+ }
1121
+
1122
+ # ── Run Permutations ──────────────────────────────────────────────────────
1123
+ observeEvent(input$run_perms, {
1124
+ req(rv$cross)
1125
+ cross <- get_cross()
1126
+ pcol <- 1
1127
+ withProgress(message = "Running permutations...", {
1128
+ perm <- tryCatch(
1129
+ scanone(cross, pheno.col = pcol, method = "hk", n.perm = input$n_perm),
1130
+ error = function(e) NULL
1131
+ )
1132
+ if (!is.null(perm)) rv$perm_out <- perm
1133
+ })
1134
+ })
1135
+
1136
+ # ── DATA STATS UI ──────────────────────────────────────────────────────────
1137
+ output$data_stats_ui <- renderUI({
1138
+ req(rv$cross)
1139
+ cr <- rv$cross
1140
+ div(class = "stat-grid",
1141
+ div(class = "stat-box c1",
1142
+ div(class = "stat-label", "INDIVIDUALS"),
1143
+ div(class = "stat-value", nind(cr)),
1144
+ div(class = "stat-sub", "Total RILs / individuals")),
1145
+ div(class = "stat-box c2",
1146
+ div(class = "stat-label", "MARKERS"),
1147
+ div(class = "stat-value", totmar(cr)),
1148
+ div(class = "stat-sub", paste("Across", nchr(cr), "chromosomes"))),
1149
+ div(class = "stat-box c3",
1150
+ div(class = "stat-label", "CHROMOSOMES"),
1151
+ div(class = "stat-value", nchr(cr)),
1152
+ div(class = "stat-sub", "Linkage groups")),
1153
+ div(class = "stat-box c4",
1154
+ div(class = "stat-label", "PHENOTYPES"),
1155
+ div(class = "stat-value", nphe(cr)),
1156
+ div(class = "stat-sub", paste(phenames(cr)[1], "..."))),
1157
+ div(class = "stat-box c5",
1158
+ div(class = "stat-label", "CROSS TYPE"),
1159
+ div(class = "stat-value", toupper(class(cr)[1])),
1160
+ div(class = "stat-sub", "Cross design"))
1161
+ )
1162
+ })
1163
+
1164
+ # ── CROSS SUMMARY UI ──────────────────────────────────────────────────────
1165
+ output$cross_summary_ui <- renderUI({
1166
+ req(rv$cross)
1167
+ cr <- rv$cross
1168
+ gmap <- pull.map(cr)
1169
+ lens <- sapply(gmap, function(x) diff(range(x)))
1170
+ n_mar <- nmar(cr)
1171
+ div(
1172
+ div(class = "stat-grid",
1173
+ div(class = "stat-box c1",
1174
+ div(class = "stat-label", "GENOME SIZE"),
1175
+ div(class = "stat-value", paste0(round(sum(lens)), " cM")),
1176
+ div(class = "stat-sub", "Total genetic length")),
1177
+ div(class = "stat-box c2",
1178
+ div(class = "stat-label", "AVG SPACING"),
1179
+ div(class = "stat-value", paste0(round(sum(lens)/sum(n_mar), 1), " cM")),
1180
+ div(class = "stat-sub", "Average inter-marker")),
1181
+ div(class = "stat-box c3",
1182
+ div(class = "stat-label", "MISSING DATA"),
1183
+ div(class = "stat-value",
1184
+ paste0(round(100 * sum(is.na(pull.geno(cr))) /
1185
+ (nind(cr) * totmar(cr)), 1), "%")),
1186
+ div(class = "stat-sub", "Genotype missingness")),
1187
+ div(class = "stat-box c4",
1188
+ div(class = "stat-label", "LARGEST CHR"),
1189
+ div(class = "stat-value", paste0(round(max(lens)), " cM")),
1190
+ div(class = "stat-sub", paste("Chr", names(which.max(lens)))))
1191
+ ),
1192
+ div(style = "margin-top:10px; display:flex; flex-wrap:wrap; gap:6px;",
1193
+ lapply(seq_along(gmap), function(i) {
1194
+ div(class = "chr-chip",
1195
+ paste0("Chr ", names(gmap)[i], ": ", n_mar[i], " mkrs / ", round(lens[i]), " cM"))
1196
+ })
1197
  )
1198
+ )
1199
+ })
1200
+
1201
+ # ── QTL STATS ROW ─────────────────────────────────────────────────────────
1202
+ output$qtl_stats_row <- renderUI({
1203
+ req(rv$qtl_table)
1204
+ tbl <- rv$qtl_table
1205
+ n_total <- nrow(tbl)
1206
+ n_common <- sum(tbl$Common_QTL)
1207
+ max_lod <- max(tbl$LOD)
1208
+ max_pve <- max(tbl$PVE_pct)
1209
+ div(class = "stat-grid", style = "margin-bottom:16px;",
1210
+ div(class = "stat-box c1",
1211
+ div(class = "stat-label", "TOTAL QTL"),
1212
+ div(class = "stat-value", n_total)),
1213
+ div(class = "stat-box c2",
1214
+ div(class = "stat-label", "COMMON QTL"),
1215
+ div(class = "stat-value", n_common),
1216
+ div(class = "stat-sub", "Detected ≥2 models")),
1217
+ div(class = "stat-box c3",
1218
+ div(class = "stat-label", "MAX LOD"),
1219
+ div(class = "stat-value", round(max_lod, 2))),
1220
+ div(class = "stat-box c4",
1221
+ div(class = "stat-label", "MAX PVE"),
1222
+ div(class = "stat-value", paste0(round(max_pve, 1), "%"))),
1223
+ div(class = "stat-box c5",
1224
+ div(class = "stat-label", "MODELS RUN"),
1225
+ div(class = "stat-value", length(rv$scan_list)))
1226
+ )
1227
+ })
1228
 
1229
+ # ── PLOT THEME ─────────────────────────────────────────────────────────────
1230
+ dark_theme <- theme_minimal(base_family = "mono") +
1231
+ theme(
1232
+ plot.background = element_rect(fill = "#111827", color = NA),
1233
+ panel.background = element_rect(fill = "#0f1c2e", color = NA),
1234
+ panel.grid.major = element_line(color = "#1e3a5f", linewidth = 0.3),
1235
+ panel.grid.minor = element_line(color = "#1e3a5f", linewidth = 0.15),
1236
+ axis.text = element_text(color = "#94a3b8", size = 8),
1237
+ axis.title = element_text(color = "#64748b", size = 9),
1238
+ plot.title = element_text(color = "#e2e8f0", size = 11, face = "bold"),
1239
+ plot.subtitle = element_text(color = "#64748b", size = 8),
1240
+ legend.background= element_rect(fill = "#111827", color = NA),
1241
+ legend.text = element_text(color = "#94a3b8", size = 8),
1242
+ legend.title = element_text(color = "#64748b", size = 8),
1243
+ strip.background = element_rect(fill = "#162033", color = NA),
1244
+ strip.text = element_text(color = "#94a3b8", size = 8)
1245
+ )
1246
+
1247
+ gg2plotly <- function(p) {
1248
+ gg <- ggplotly(p, tooltip = "text") %>%
1249
+ layout(
1250
+ paper_bgcolor = "#111827", plot_bgcolor = "#0f1c2e",
1251
+ font = list(color = "#94a3b8"),
1252
+ xaxis = list(gridcolor = "#1e3a5f", zerolinecolor = "#1e3a5f"),
1253
+ yaxis = list(gridcolor = "#1e3a5f", zerolinecolor = "#1e3a5f"),
1254
+ legend = list(bgcolor = "#111827", font = list(color = "#94a3b8"))
1255
+ )
1256
+ gg
1257
+ }
1258
 
1259
+ # ── HELPER: Scan to long df ────────────────────────────────────────────────
1260
+ scan_to_df <- function(sc, model_name) {
1261
+ data.frame(
1262
+ chr = sc$chr,
1263
+ pos = sc$pos,
1264
+ lod = sc$lod,
1265
+ model = model_name,
1266
+ stringsAsFactors = FALSE
1267
+ )
1268
+ }
1269
 
1270
+ # ── PLOT: Genetic Map ──────────────────────────────────────────────────────
1271
+ output$plot_genetic_map <- renderPlotly({
1272
+ req(rv$cross)
1273
+ gmap <- pull.map(rv$cross)
1274
+ df <- do.call(rbind, lapply(names(gmap), function(ch) {
1275
+ data.frame(chr = ch, pos = as.numeric(gmap[[ch]]),
1276
+ marker = names(gmap[[ch]]), stringsAsFactors = FALSE)
1277
+ }))
1278
+ df$chr_num <- as.numeric(factor(df$chr, levels = unique(df$chr)))
1279
+ p <- ggplot(df, aes(x = pos, y = chr_num,
1280
+ text = paste0("Marker: ", marker, "<br>Chr: ", chr, "<br>Pos: ", round(pos,1), " cM"))) +
1281
+ geom_hline(aes(yintercept = chr_num), color = "#1e3a5f", linewidth = 0.5) +
1282
+ geom_point(color = "#00d4ff", size = 1.5, alpha = 0.8) +
1283
+ scale_y_continuous(breaks = unique(df$chr_num), labels = unique(df$chr)) +
1284
+ labs(x = "Position (cM)", y = "Chromosome", title = "Genetic Map") +
1285
+ dark_theme
1286
+ gg2plotly(p)
1287
+ })
1288
 
1289
+ # ── PLOT: Phenotype Distribution ──────────────────────────────────────────
1290
+ output$plot_pheno_dist <- renderPlotly({
1291
+ req(rv$cross)
1292
+ pdata <- pull.pheno(rv$cross)
1293
+ pname <- phenames(rv$cross)[1]
1294
+ vals <- pdata[[pname]]
1295
+ vals <- vals[!is.na(vals)]
1296
+ df <- data.frame(x = vals)
1297
+ p <- ggplot(df, aes(x = x)) +
1298
+ geom_histogram(aes(y = after_stat(density)), bins = 30,
1299
+ fill = "#f97316", alpha = 0.7, color = "#0f1c2e") +
1300
+ geom_density(color = "#00d4ff", linewidth = 1) +
1301
+ geom_vline(xintercept = mean(vals), color = "#a3e635",
1302
+ linetype = "dashed", linewidth = 0.8) +
1303
+ labs(x = pname, y = "Density", title = "Phenotype Distribution",
1304
+ subtitle = paste0("n=", length(vals), " mean=", round(mean(vals),2),
1305
+ " sd=", round(sd(vals),2))) +
1306
+ dark_theme
1307
+ gg2plotly(p)
1308
+ })
1309
+
1310
+ # ── PLOT: Missing Data ────────────────────────────────────────────────────
1311
+ output$plot_missing <- renderPlotly({
1312
+ req(rv$cross)
1313
+ g <- pull.geno(rv$cross)
1314
+ miss <- apply(g, 2, function(x) mean(is.na(x)) * 100)
1315
+ df <- data.frame(marker = names(miss), missing = miss,
1316
+ stringsAsFactors = FALSE)
1317
+ df <- df[order(df$missing, decreasing = TRUE), ]
1318
+ df$marker <- factor(df$marker, levels = df$marker)
1319
+ if (nrow(df) > 80) df <- df[1:80, ]
1320
+ p <- ggplot(df, aes(x = marker, y = missing,
1321
+ text = paste0(marker, ": ", round(missing,1), "% missing"))) +
1322
+ geom_col(aes(fill = missing)) +
1323
+ scale_fill_gradient(low = "#1e3a5f", high = "#f97316") +
1324
+ labs(x = NULL, y = "% Missing", title = "Missing Genotype Data",
1325
+ subtitle = "Top markers by missingness") +
1326
+ dark_theme +
1327
+ theme(axis.text.x = element_blank(), legend.position = "none")
1328
+ gg2plotly(p)
1329
+ })
1330
+
1331
+ # ── PLOT: Marker Spacing ──────────────────────────────────────────────────
1332
+ output$plot_marker_spacing <- renderPlotly({
1333
+ req(rv$cross)
1334
+ gmap <- pull.map(rv$cross)
1335
+ sp <- unlist(lapply(gmap, function(ch) {
1336
+ if (length(ch) < 2) return(NA)
1337
+ diff(as.numeric(ch))
1338
+ }))
1339
+ sp <- sp[!is.na(sp)]
1340
+ df <- data.frame(spacing = sp)
1341
+ p <- ggplot(df, aes(x = spacing)) +
1342
+ geom_histogram(bins = 40, fill = "#ec4899", alpha = 0.75, color = "#0f1c2e") +
1343
+ geom_vline(xintercept = median(sp), color = "#a3e635",
1344
+ linetype = "dashed", linewidth = 0.8) +
1345
+ labs(x = "Inter-marker distance (cM)", y = "Count",
1346
+ title = "Marker Spacing Distribution",
1347
+ subtitle = paste0("Median: ", round(median(sp),1), " cM")) +
1348
+ dark_theme
1349
+ gg2plotly(p)
1350
+ })
1351
+
1352
+ # ── PLOT: Permutation ────────────────────────────────────────────────────
1353
+ output$plot_perm <- renderPlotly({
1354
+ req(rv$perm_out)
1355
+ pvals <- as.numeric(rv$perm_out)
1356
+ df <- data.frame(lod = sort(pvals))
1357
+ t95 <- quantile(pvals, 0.95)
1358
+ t99 <- quantile(pvals, 0.99)
1359
+ p <- ggplot(df, aes(x = lod)) +
1360
+ geom_histogram(bins = 40, fill = "#a78bfa", alpha = 0.7, color = "#0f1c2e") +
1361
+ geom_vline(xintercept = t95, color = "#a3e635", linetype = "dashed", linewidth = 1) +
1362
+ geom_vline(xintercept = t99, color = "#f97316", linetype = "dashed", linewidth = 1) +
1363
+ annotate("text", x = t95 + 0.1, y = Inf, label = paste0("α=0.05: ", round(t95,2)),
1364
+ color = "#a3e635", hjust = 0, vjust = 1.5, size = 3) +
1365
+ annotate("text", x = t99 + 0.1, y = Inf, label = paste0("α=0.01: ", round(t99,2)),
1366
+ color = "#f97316", hjust = 0, vjust = 3, size = 3) +
1367
+ labs(x = "LOD Score", y = "Count", title = "Permutation Distribution",
1368
+ subtitle = paste0(length(pvals), " permutations")) +
1369
+ dark_theme
1370
+ gg2plotly(p)
1371
+ })
1372
+
1373
+ # ── PLOTS: 10 Genome Scans ────────────────────────────────────────────────
1374
+ make_scan_plot <- function(sc, model_name, col) {
1375
+ req(!is.null(sc))
1376
+ df <- scan_to_df(sc, model_name)
1377
+ # cumulative position
1378
+ chr_levels <- unique(df$chr)
1379
+ chr_offsets <- c(0, cumsum(tapply(df$pos, df$chr, max)[chr_levels[-length(chr_levels)]]))
1380
+ names(chr_offsets) <- chr_levels
1381
+ df$cum_pos <- df$pos + chr_offsets[df$chr]
1382
+ thresh <- isolate(input$lod_thresh)
1383
+ df$sig <- df$lod >= thresh
1384
+
1385
+ p <- ggplot(df, aes(x = cum_pos, y = lod,
1386
+ text = paste0("Chr: ", chr, "<br>Pos: ", round(pos,1),
1387
+ " cM<br>LOD: ", round(lod,3)))) +
1388
+ geom_line(aes(color = chr), linewidth = 0.7, show.legend = FALSE) +
1389
+ geom_hline(yintercept = thresh, color = "#f97316",
1390
+ linetype = "dashed", linewidth = 0.6) +
1391
+ geom_point(data = df[df$sig, ], aes(x = cum_pos, y = lod),
1392
+ color = "#facc15", size = 1.5, alpha = 0.9) +
1393
+ scale_color_manual(values = rep(c(col, scales::alpha(col, 0.6)),
1394
+ length(chr_levels))) +
1395
+ labs(x = "Genome Position (cM)", y = "LOD Score",
1396
+ title = paste0(model_name, " — Genome Scan"),
1397
+ subtitle = paste0("LOD threshold: ", thresh)) +
1398
+ dark_theme
1399
+ gg2plotly(p)
1400
+ }
1401
+
1402
+ scan_model_names <- c("EM","HK","Ext.HK","Marker.Reg","Multi.Imp",
1403
+ "CIM","MQM","2D.Scan","ANOVA","Bayes")
1404
+
1405
+ for (i in seq_along(scan_model_names)) {
1406
+ local({
1407
+ idx <- i
1408
+ mname <- scan_model_names[idx]
1409
+ mcol <- model_colors[idx]
1410
+ out_id <- paste0("plot_scan_", idx)
1411
+ output[[out_id]] <- renderPlotly({
1412
+ req(length(rv$scan_list) > 0)
1413
+ sc <- rv$scan_list[[mname]]
1414
+ if (is.null(sc)) {
1415
+ # fallback to first available
1416
+ sc <- rv$scan_list[[1]]
1417
+ mname2 <- names(rv$scan_list)[1]
1418
+ } else {
1419
+ mname2 <- mname
1420
+ }
1421
+ make_scan_plot(sc, mname2, mcol)
1422
+ })
1423
  })
1424
+ }
1425
+
1426
+ # ── PLOT: Interval Map ────────────────────────────────────────────────────
1427
+ output$plot_interval <- renderPlotly({
1428
+ req(length(rv$scan_list) > 0, input$chr_sel)
1429
+ mn <- switch(input$interval_model,
1430
+ "em" = "EM", "hk" = "HK", "ehk" = "Ext.HK",
1431
+ "mr" = "Marker.Reg", "cim" = "CIM", "HK")
1432
+ sc <- rv$scan_list[[mn]]
1433
+ if (is.null(sc)) sc <- rv$scan_list[[1]]
1434
+ ch <- input$chr_sel
1435
+ df <- sc[sc$chr == ch, ]
1436
+ thresh <- isolate(input$lod_thresh)
1437
+ drop <- isolate(input$lod_drop)
1438
+
1439
+ ci <- tryCatch(lodint(sc, chr = ch, drop = drop), error = function(e) NULL)
1440
+ peak_pos <- df$pos[which.max(df$lod)]
1441
+
1442
+ p <- ggplot(df, aes(x = pos, y = lod,
1443
+ text = paste0("Pos: ", round(pos,1), " cM<br>LOD: ", round(lod,3)))) +
1444
+ geom_line(color = "#00d4ff", linewidth = 1.2) +
1445
+ geom_area(fill = "#00d4ff", alpha = 0.1) +
1446
+ geom_hline(yintercept = thresh, color = "#f97316",
1447
+ linetype = "dashed", linewidth = 0.7) +
1448
+ geom_vline(xintercept = peak_pos, color = "#a3e635",
1449
+ linetype = "dotted", linewidth = 0.8) +
1450
+ {if (!is.null(ci))
1451
+ annotate("rect",
1452
+ xmin = ci$pos[1], xmax = ci$pos[3],
1453
+ ymin = -Inf, ymax = Inf,
1454
+ fill = "#a78bfa", alpha = 0.12)
1455
+ } +
1456
+ labs(x = "Position (cM)", y = "LOD Score",
1457
+ title = paste0("Chr ", ch, " — Interval Mapping (", mn, ")"),
1458
+ subtitle = paste0("LOD drop: ", drop, " cM | Peak: ", round(peak_pos,1), " cM")) +
1459
+ dark_theme
1460
+ gg2plotly(p)
1461
  })
1462
 
1463
+ # ── PLOT: Effect ──────────────────────────────────────────────────────────
1464
+ output$plot_effect <- renderPlotly({
1465
+ req(rv$cross, length(rv$scan_list) > 0, input$chr_sel)
1466
+ sc <- rv$scan_list[[1]]
1467
+ ch <- input$chr_sel
1468
+ df_sc <- sc[sc$chr == ch, ]
1469
+ peak_pos <- df_sc$pos[which.max(df_sc$lod)]
1470
 
1471
+ # find nearest marker
1472
+ cross <- rv$cross
1473
+ mmap <- pull.map(cross)[[ch]]
1474
+ near_m <- names(which.min(abs(mmap - peak_pos)))
1475
 
1476
  tryCatch({
1477
+ g <- pull.geno(cross)[, near_m]
1478
+ pdata <- pull.pheno(cross)[, 1]
1479
+ df <- data.frame(geno = factor(g), pheno = pdata)
1480
+ df <- df[!is.na(df$geno) & !is.na(df$pheno), ]
1481
+ df$geno_lab <- paste0("G", df$geno)
1482
 
1483
+ p <- ggplot(df, aes(x = geno_lab, y = pheno, fill = geno_lab,
1484
+ text = paste0("Geno: ", geno_lab, "<br>Pheno: ", round(pheno,2)))) +
1485
+ geom_violin(alpha = 0.5) +
1486
+ geom_boxplot(width = 0.2, outlier.color = "#f97316", color = "#e2e8f0") +
1487
+ scale_fill_manual(values = c("#00d4ff","#a3e635","#f97316","#a78bfa")) +
1488
+ labs(x = paste0("Genotype at ", near_m), y = "Phenotype",
1489
+ title = paste0("Chr ", ch, " Peak Effect"), fill = NULL) +
1490
+ dark_theme + theme(legend.position = "none")
1491
+ gg2plotly(p)
1492
+ }, error = function(e) {
1493
+ plot_ly() %>%
1494
+ add_annotations(text = "Effect plot requires genotype data",
1495
+ showarrow = FALSE, font = list(color = "#64748b", size = 14)) %>%
1496
+ layout(paper_bgcolor = "#111827", plot_bgcolor = "#0f1c2e")
1497
+ })
1498
+ })
1499
+
1500
+ # ── PLOT: PVE ─────────────────────────────────────────────────────────────
1501
+ output$plot_pve <- renderPlotly({
1502
+ req(rv$qtl_table)
1503
+ tbl <- rv$qtl_table
1504
+ df <- tbl %>%
1505
+ group_by(Model, Chr) %>%
1506
+ slice_max(LOD, n = 1) %>%
1507
+ ungroup()
1508
+ p <- ggplot(df, aes(x = reorder(paste0(Model,"/",Chr), PVE_pct),
1509
+ y = PVE_pct, fill = Model,
1510
+ text = paste0("Model: ", Model, "<br>Chr: ", Chr,
1511
+ "<br>PVE: ", round(PVE_pct,1), "%<br>LOD: ", round(LOD,2)))) +
1512
+ geom_col(alpha = 0.85) +
1513
+ scale_fill_manual(values = setNames(model_colors[1:length(unique(df$Model))],
1514
+ unique(df$Model))) +
1515
+ coord_flip() +
1516
+ labs(x = NULL, y = "PVE (%)", title = "Phenotypic Variance Explained") +
1517
+ dark_theme + theme(legend.position = "none")
1518
+ gg2plotly(p)
1519
+ })
1520
+
1521
+ # ═══ GALLERY PLOTS (10) ════════════════════════════════════════════════════
1522
+
1523
+ # Plot 1 — LOD Profile (All Chr, first model)
1524
+ output$p1_lod_profile <- renderPlotly({
1525
+ req(length(rv$scan_list) > 0)
1526
+ sc <- rv$scan_list[[1]]
1527
+ mn <- names(rv$scan_list)[1]
1528
+ make_scan_plot(sc, mn, "#00d4ff")
1529
+ })
1530
+
1531
+ # Plot 2 — LOD Heatmap (Chr × Models)
1532
+ output$p2_lod_heatmap <- renderPlotly({
1533
+ req(length(rv$scan_list) > 0)
1534
+ rows <- lapply(names(rv$scan_list), function(mn) {
1535
+ sc <- rv$scan_list[[mn]]
1536
+ tapply(sc$lod, sc$chr, max, na.rm = TRUE) %>%
1537
+ as.data.frame() %>%
1538
+ t() %>% as.data.frame() %>%
1539
+ mutate(model = mn)
1540
+ })
1541
+ mat <- bind_rows(rows)
1542
+ chrs <- setdiff(names(mat), "model")
1543
+ mat_long <- mat %>%
1544
+ pivot_longer(all_of(chrs), names_to = "chr", values_to = "lod") %>%
1545
+ mutate(lod = as.numeric(lod))
1546
+ p <- ggplot(mat_long, aes(x = chr, y = model, fill = lod,
1547
+ text = paste0("Chr: ", chr, "<br>Model: ", model,
1548
+ "<br>Max LOD: ", round(lod,2)))) +
1549
+ geom_tile(color = "#0a0e1a") +
1550
+ scale_fill_viridis(option = "magma", name = "LOD") +
1551
+ labs(x = "Chromosome", y = NULL, title = "Max LOD per Chr per Model") +
1552
+ dark_theme + theme(axis.text.x = element_text(angle = 45, hjust = 1))
1553
+ gg2plotly(p)
1554
+ })
1555
+
1556
+ # Plot 3 — Effect Size bubble
1557
+ output$p3_effect_size <- renderPlotly({
1558
+ req(rv$qtl_table)
1559
+ tbl <- rv$qtl_table
1560
+ p <- ggplot(tbl, aes(x = Chr, y = LOD, size = PVE_pct, color = Model,
1561
+ text = paste0("Chr: ", Chr, "<br>LOD: ", round(LOD,2),
1562
+ "<br>PVE: ", round(PVE_pct,1), "%<br>Model: ", Model))) +
1563
+ geom_point(alpha = 0.75) +
1564
+ scale_size_continuous(range = c(3, 14), name = "PVE (%)") +
1565
+ scale_color_manual(values = setNames(model_colors[1:length(unique(tbl$Model))],
1566
+ unique(tbl$Model))) +
1567
+ labs(x = "Chromosome", y = "LOD Score", title = "QTL Effect Size Bubble Plot") +
1568
+ dark_theme
1569
+ gg2plotly(p)
1570
+ })
1571
+
1572
+ # Plot 4 — PVE bar per model
1573
+ output$p4_pve_bar <- renderPlotly({
1574
+ req(rv$qtl_table)
1575
+ tbl <- rv$qtl_table %>%
1576
+ group_by(Model) %>% summarise(total_pve = sum(PVE_pct), n_qtl = n())
1577
+ p <- ggplot(tbl, aes(x = reorder(Model, total_pve), y = total_pve, fill = Model,
1578
+ text = paste0(Model, ": ", round(total_pve,1), "% total PVE (",n_qtl," QTL)"))) +
1579
+ geom_col(alpha = 0.85) +
1580
+ scale_fill_manual(values = setNames(model_colors[1:nrow(tbl)], tbl$Model)) +
1581
+ coord_flip() +
1582
+ labs(x = NULL, y = "Total PVE (%)", title = "Total PVE per Model") +
1583
+ dark_theme + theme(legend.position = "none")
1584
+ gg2plotly(p)
1585
+ })
1586
+
1587
+ # Plot 5 — Multi-model LOD overlay
1588
+ output$p5_model_compare <- renderPlotly({
1589
+ req(length(rv$scan_list) >= 2)
1590
+ combined <- bind_rows(lapply(names(rv$scan_list)[1:min(5, length(rv$scan_list))],
1591
+ function(mn) scan_to_df(rv$scan_list[[mn]], mn)))
1592
+ chr_levels <- unique(combined$chr)
1593
+ chr_offsets <- c(0, cumsum(tapply(combined$pos, combined$chr, max)[chr_levels[-length(chr_levels)]]))
1594
+ names(chr_offsets) <- chr_levels
1595
+ combined$cum_pos <- combined$pos + chr_offsets[combined$chr]
1596
 
1597
+ p <- ggplot(combined, aes(x = cum_pos, y = lod, color = model,
1598
+ text = paste0(model, "<br>Chr: ", chr,
1599
+ "<br>Pos: ", round(pos,1), " cM<br>LOD: ", round(lod,3)))) +
1600
+ geom_line(linewidth = 0.6, alpha = 0.85) +
1601
+ geom_hline(yintercept = isolate(input$lod_thresh), color = "#f97316",
1602
+ linetype = "dashed", linewidth = 0.5) +
1603
+ scale_color_manual(values = setNames(model_colors[1:length(unique(combined$model))],
1604
+ unique(combined$model))) +
1605
+ labs(x = "Genome Position", y = "LOD", title = "Multi-Model LOD Overlay",
1606
+ color = "Model") +
1607
+ dark_theme
1608
+ gg2plotly(p)
1609
+ })
1610
 
1611
+ # Plot 6 — LOD Intervals forest plot
1612
+ output$p6_lod_intervals <- renderPlotly({
1613
+ req(rv$qtl_table)
1614
+ tbl <- rv$qtl_table %>%
1615
+ mutate(label = paste0(Model, " Chr", Chr))
1616
+ p <- ggplot(tbl, aes(y = reorder(label, LOD), x = Peak_Pos_cM,
1617
+ color = Model,
1618
+ text = paste0(label, "<br>Peak: ", round(Peak_Pos_cM,1),
1619
+ " cM<br>CI: [", CI_Left_cM, ", ", CI_Right_cM, "]",
1620
+ "<br>LOD: ", round(LOD,2)))) +
1621
+ geom_point(size = 2.5) +
1622
+ geom_errorbarh(aes(xmin = CI_Left_cM, xmax = CI_Right_cM), height = 0.3) +
1623
+ scale_color_manual(values = setNames(model_colors[1:length(unique(tbl$Model))],
1624
+ unique(tbl$Model))) +
1625
+ labs(x = "Position (cM)", y = NULL, title = "QTL LOD Drop Intervals",
1626
+ subtitle = "1.5-LOD confidence intervals") +
1627
+ dark_theme + theme(legend.position = "none")
1628
+ gg2plotly(p)
1629
+ })
1630
 
1631
+ # Plot 7 — Phenotype vs peak genotype scatter
1632
+ output$p7_pheno_geno <- renderPlotly({
1633
+ req(rv$cross, length(rv$scan_list) > 0)
1634
+ sc <- rv$scan_list[[1]]
1635
+ cross <- rv$cross
1636
+ peak_chr <- sc$chr[which.max(sc$lod)]
1637
+ peak_pos <- sc$pos[which.max(sc$lod)]
1638
+ mmap <- pull.map(cross)[[as.character(peak_chr)]]
1639
+ near_m <- names(which.min(abs(mmap - peak_pos)))
1640
+ tryCatch({
1641
+ g <- pull.geno(cross)[, near_m]
1642
+ pdata <- pull.pheno(cross)[, 1]
1643
+ df <- data.frame(geno = factor(g), pheno = pdata)
1644
+ df <- df[!is.na(df$geno) & !is.na(df$pheno), ]
1645
+ p <- ggplot(df, aes(x = jitter(as.numeric(geno), 0.2), y = pheno,
1646
+ color = geno,
1647
+ text = paste0("Geno: G", geno, "<br>Pheno: ", round(pheno,3)))) +
1648
+ geom_jitter(width = 0.15, alpha = 0.6, size = 1.5) +
1649
+ stat_summary(fun = mean, geom = "crossbar", width = 0.4,
1650
+ color = "#facc15", linewidth = 0.8) +
1651
+ scale_color_manual(values = c("#00d4ff","#a3e635","#f97316")) +
1652
+ scale_x_continuous(breaks = 1:3, labels = paste0("G",1:3)) +
1653
+ labs(x = paste0("Genotype at ", near_m), y = "Phenotype",
1654
+ title = "Phenotype by Peak Marker Genotype") +
1655
+ dark_theme + theme(legend.position = "none")
1656
+ gg2plotly(p)
1657
+ }, error = function(e) {
1658
+ plotly_empty() %>%
1659
+ layout(paper_bgcolor="#111827", plot_bgcolor="#0f1c2e",
1660
+ annotations = list(text = "Requires genotype data",
1661
+ showarrow = FALSE,
1662
+ font = list(color = "#64748b")))
1663
  })
1664
  })
1665
 
1666
+ # Plot 8 — QTL Genome map (all QTL on chromosomes)
1667
+ output$p8_qtl_map <- renderPlotly({
1668
+ req(rv$qtl_table, rv$cross)
1669
+ tbl <- rv$qtl_table
1670
+ gmap <- pull.map(rv$cross)
1671
+ chr_lens <- sapply(gmap, function(x) max(as.numeric(x)))
1672
+ chr_df <- data.frame(chr = names(chr_lens), len = chr_lens)
1673
+ chr_df$chr_num <- seq_len(nrow(chr_df))
1674
+
1675
+ tbl$chr_num <- match(tbl$Chr, chr_df$chr)
1676
+
1677
+ p <- ggplot() +
1678
+ geom_segment(data = chr_df, aes(x = 0, xend = len, y = chr_num, yend = chr_num),
1679
+ color = "#1e3a5f", linewidth = 3) +
1680
+ geom_point(data = tbl, aes(x = Peak_Pos_cM, y = chr_num, color = Model, size = LOD,
1681
+ text = paste0("Model: ", Model, "<br>Chr: ", Chr,
1682
+ "<br>Pos: ", round(Peak_Pos_cM,1),
1683
+ " cM<br>LOD: ", round(LOD,2))),
1684
+ alpha = 0.85) +
1685
+ geom_segment(data = tbl, aes(x = CI_Left_cM, xend = CI_Right_cM,
1686
+ y = chr_num, yend = chr_num, color = Model),
1687
+ linewidth = 2, alpha = 0.35) +
1688
+ scale_color_manual(values = setNames(model_colors[1:length(unique(tbl$Model))],
1689
+ unique(tbl$Model))) +
1690
+ scale_size_continuous(range = c(3, 10)) +
1691
+ scale_y_continuous(breaks = chr_df$chr_num, labels = chr_df$chr) +
1692
+ labs(x = "Position (cM)", y = "Chromosome", title = "QTL Genome Map",
1693
+ subtitle = "Dots = peak, bars = CI interval") +
1694
+ dark_theme
1695
+ gg2plotly(p)
1696
+ })
1697
 
1698
+ # Plot 9 — Ridge Plot (LOD per chromosome)
1699
+ output$p9_ridge <- renderPlotly({
1700
+ req(length(rv$scan_list) > 0)
1701
+ sc <- rv$scan_list[[1]]
1702
+ mn <- names(rv$scan_list)[1]
1703
+ chrs <- unique(sc$chr)
1704
+ # offset each chr by LOD range for stacked display
1705
+ df <- do.call(rbind, lapply(seq_along(chrs), function(i) {
1706
+ ch_dat <- sc[sc$chr == chrs[i], ]
1707
+ ch_dat$offset <- i * 3
1708
+ ch_dat$lod_offset <- ch_dat$lod + ch_dat$offset
1709
+ ch_dat$chr_label <- paste0("Chr ", chrs[i])
1710
+ ch_dat
1711
+ }))
1712
 
1713
+ p <- ggplot(df, aes(x = pos, y = lod_offset, group = chr, color = chr,
1714
+ text = paste0("Chr: ", chr, "<br>Pos: ", round(pos,1),
1715
+ " cM<br>LOD: ", round(lod,3)))) +
1716
+ geom_line(linewidth = 0.8, alpha = 0.85) +
1717
+ geom_area(aes(fill = chr), alpha = 0.15) +
1718
+ scale_color_manual(values = rep(viridis::viridis(min(nchr(rv$cross), 20)), 3)) +
1719
+ scale_fill_manual(values = rep(viridis::viridis(min(nchr(rv$cross), 20)), 3)) +
1720
+ labs(x = "Position (cM)", y = "LOD + offset",
1721
+ title = paste0("LOD Ridge Plot — ", mn),
1722
+ subtitle = "Each chromosome stacked vertically") +
1723
+ dark_theme + theme(legend.position = "none")
1724
+ gg2plotly(p)
1725
+ })
1726
 
1727
+ # Plot 10 — Common QTL Highlight
1728
+ output$p10_common_qtl <- renderPlotly({
1729
+ req(rv$qtl_table)
1730
+ tbl <- rv$qtl_table
1731
+ tbl$Highlight <- ifelse(tbl$Common_QTL, "Common QTL (≥2 models)", "Unique to model")
1732
+ p <- ggplot(tbl, aes(x = Chr, y = LOD, color = Highlight, size = PVE_pct,
1733
+ text = paste0("Model: ", Model, "<br>Chr: ", Chr,
1734
+ "<br>LOD: ", round(LOD,2),
1735
+ "<br>PVE: ", round(PVE_pct,1), "%",
1736
+ "<br>", Highlight))) +
1737
+ geom_jitter(width = 0.15, alpha = 0.8, height = 0) +
1738
+ scale_color_manual(values = c("Common QTL (≥2 models)" = "#f97316",
1739
+ "Unique to model" = "#00d4ff")) +
1740
+ scale_size_continuous(range = c(3, 12)) +
1741
+ geom_hline(yintercept = isolate(input$lod_thresh), color = "#64748b",
1742
+ linetype = "dashed", linewidth = 0.5) +
1743
+ labs(x = "Chromosome", y = "LOD", title = "Common QTL Across Models",
1744
+ subtitle = "Orange = detected in ≥2 models", color = NULL, size = "PVE (%)") +
1745
+ dark_theme
1746
+ gg2plotly(p)
1747
  })
1748
 
1749
+ # ── CIRCOS PLOT ────────────────────────────────────────────────────────────
1750
+ output$plot_circos <- renderPlot({
1751
+ req(rv$cross, length(rv$scan_list) > 0)
1752
+ cross <- rv$cross
1753
+ gmap <- pull.map(cross)
1754
+ chrs <- names(gmap)
1755
+ chr_lens <- sapply(gmap, function(x) max(as.numeric(x)))
1756
+
1757
+ pal_choice <- isolate(input$circos_pal)
1758
+ pal <- switch(pal_choice,
1759
+ "viridis" = viridis::viridis(length(rv$scan_list)),
1760
+ "spectral" = RColorBrewer::brewer.pal(min(11, length(rv$scan_list)), "Spectral"),
1761
+ "dark2" = RColorBrewer::brewer.pal(min(8, length(rv$scan_list)), "Dark2"),
1762
+ "accent" = RColorBrewer::brewer.pal(min(8, length(rv$scan_list)), "Accent"),
1763
+ viridis::viridis(length(rv$scan_list))
1764
+ )
1765
+ pal <- rep_len(pal, length(rv$scan_list))
1766
+
1767
+ par(bg = "#0a0e1a", fg = "#e2e8f0", col.axis = "#64748b",
1768
+ col.lab = "#64748b", col.main = "#e2e8f0")
1769
+
1770
+ circos.clear()
1771
+ circos.par(
1772
+ "start.degree" = 90,
1773
+ "gap.degree" = 2,
1774
+ "track.margin" = c(0.01, 0.01),
1775
+ "cell.padding" = c(0.02, 0, 0.02, 0),
1776
+ "canvas.xlim" = c(-1.2, 1.2),
1777
+ "canvas.ylim" = c(-1.2, 1.2),
1778
+ "background.color" = "#0a0e1a",
1779
+ "track.height" = 0.06,
1780
+ "points.overflow.warning" = FALSE
1781
+ )
1782
 
1783
+ # Initialize with chromosome sectors
1784
+ circos.initialize(
1785
+ factors = factor(chrs, levels = chrs),
1786
+ xlim = cbind(rep(0, length(chrs)), chr_lens)
1787
+ )
1788
 
1789
+ # Track 1: Chromosome labels
1790
+ circos.track(
1791
+ ylim = c(0, 1), bg.col = "#162033", bg.border = "#1e3a5f",
1792
+ panel.fun = function(x, y) {
1793
+ circos.text(
1794
+ x = CELL_META$xcenter, y = 0.5, labels = CELL_META$sector.index,
1795
+ facing = "clockwise", niceFacing = TRUE, cex = 0.6,
1796
+ col = "#94a3b8", font = 2
1797
+ )
1798
+ }
1799
+ )
1800
 
1801
+ # Tracks 2–11: One per model (LOD scores)
1802
+ thresh <- isolate(input$lod_thresh)
1803
+ for (mi in seq_along(rv$scan_list)) {
1804
+ mn <- names(rv$scan_list)[mi]
1805
+ sc <- rv$scan_list[[mn]]
1806
+ mcol <- pal[mi]
1807
 
1808
+ circos.track(
1809
+ ylim = c(0, max(sc$lod, na.rm = TRUE) * 1.1 + 0.1),
1810
+ bg.col = "#0f1c2e", bg.border = "#1e3a5f", track.height = 0.05,
1811
+ panel.fun = function(x, y) {
1812
+ ch <- CELL_META$sector.index
1813
+ ch_sc <- sc[as.character(sc$chr) == as.character(ch), ]
1814
+ if (nrow(ch_sc) == 0) return()
1815
+ # LOD bars
1816
+ circos.rect(
1817
+ xleft = ch_sc$pos - 0.5,
1818
+ xright = ch_sc$pos + 0.5,
1819
+ ybottom = 0,
1820
+ ytop = pmax(ch_sc$lod, 0),
1821
+ col = ifelse(ch_sc$lod >= thresh, mcol, scales::alpha(mcol, 0.3)),
1822
+ border = NA
1823
+ )
1824
+ # threshold line
1825
+ if (max(ch_sc$lod, na.rm = TRUE) > thresh) {
1826
+ circos.lines(
1827
+ x = c(CELL_META$cell.xlim[1], CELL_META$cell.xlim[2]),
1828
+ y = rep(thresh, 2),
1829
+ col = "#f97316", lty = 2, lwd = 0.5
1830
+ )
1831
+ }
1832
+ }
1833
+ )
1834
+ }
1835
 
1836
+ # Draw links for common QTL
1837
+ if (!is.null(rv$qtl_table)) {
1838
+ tbl <- rv$qtl_table
1839
+ common <- tbl[tbl$Common_QTL, ]
1840
+ chr_grp <- split(common, common$Chr)
1841
+ link_col <- scales::alpha("#f97316", 0.45)
1842
+ for (ch in names(chr_grp)) {
1843
+ rows <- chr_grp[[ch]]
1844
+ if (nrow(rows) < 2) next
1845
+ for (r1 in 1:(nrow(rows) - 1)) {
1846
+ for (r2 in (r1 + 1):nrow(rows)) {
1847
+ tryCatch(
1848
+ circos.link(
1849
+ sector.index1 = ch, point1 = rows$Peak_Pos_cM[r1],
1850
+ sector.index2 = ch, point2 = rows$Peak_Pos_cM[r2],
1851
+ col = link_col, lwd = 1
1852
+ ),
1853
+ error = function(e) NULL
1854
+ )
1855
+ }
1856
+ }
1857
+ }
1858
+ }
1859
+
1860
+ # Legend
1861
+ legend("bottomleft",
1862
+ legend = c(names(rv$scan_list), "LOD Threshold", "Common QTL"),
1863
+ col = c(pal[1:length(rv$scan_list)], "#f97316", "#f97316"),
1864
+ lty = c(rep(1, length(rv$scan_list)), 2, 1),
1865
+ lwd = c(rep(2, length(rv$scan_list)), 1.5, 2),
1866
+ bg = "#111827", text.col = "#94a3b8",
1867
+ bty = "n", cex = 0.65)
1868
+
1869
+ title("Circos — Multi-Model QTL Landscape", col.main = "#e2e8f0", cex.main = 1.1)
1870
+ circos.clear()
1871
+
1872
+ }, bg = "#0a0e1a")
1873
+
1874
+ # ── COMPARE PLOTS ──────────────────────────────────────────────────────────
1875
+ output$plot_compare_peak <- renderPlotly({
1876
+ req(rv$qtl_table)
1877
+ tbl <- rv$qtl_table %>%
1878
+ group_by(Model) %>%
1879
+ summarise(peak_lod = max(LOD), n_qtl = n(), total_pve = sum(PVE_pct))
1880
+ p <- ggplot(tbl, aes(x = n_qtl, y = peak_lod, color = Model, size = total_pve,
1881
+ text = paste0(Model, "<br>QTL: ", n_qtl,
1882
+ "<br>Peak LOD: ", round(peak_lod,2),
1883
+ "<br>Total PVE: ", round(total_pve,1), "%"))) +
1884
+ geom_point(alpha = 0.85) +
1885
+ geom_text(aes(label = Model), nudge_y = 0.15, size = 2.5, color = "#94a3b8") +
1886
+ scale_color_manual(values = setNames(model_colors[1:nrow(tbl)], tbl$Model)) +
1887
+ scale_size_continuous(range = c(6, 18)) +
1888
+ labs(x = "Number of QTL", y = "Peak LOD",
1889
+ title = "Model Performance Comparison",
1890
+ subtitle = "Size = total PVE") +
1891
+ dark_theme + theme(legend.position = "none")
1892
+ gg2plotly(p)
1893
+ })
1894
+
1895
+ output$plot_compare_venn <- renderPlotly({
1896
+ req(rv$qtl_table)
1897
+ tbl <- rv$qtl_table
1898
+ chr_model_mat <- tbl %>%
1899
+ mutate(present = 1) %>%
1900
+ distinct(Model, Chr) %>%
1901
+ mutate(present = 1) %>%
1902
+ pivot_wider(names_from = Model, values_from = present, values_fill = 0)
1903
+ chrs <- chr_model_mat$Chr
1904
+ mods <- setdiff(names(chr_model_mat), "Chr")
1905
+ n_models <- sapply(chrs, function(ch) {
1906
+ sum(as.numeric(chr_model_mat[chr_model_mat$Chr == ch, mods]))
1907
+ })
1908
+ df_v <- data.frame(chr = chrs, n_models = n_models)
1909
+ p <- ggplot(df_v, aes(x = chr, y = n_models, fill = n_models,
1910
+ text = paste0("Chr ", chr, ": detected by ", n_models, " models"))) +
1911
+ geom_col() +
1912
+ scale_fill_gradient(low = "#1e3a5f", high = "#f97316", name = "# Models") +
1913
+ geom_hline(yintercept = 2, color = "#a3e635", linetype = "dashed", linewidth = 0.6) +
1914
+ labs(x = "Chromosome", y = "# Models Detecting QTL",
1915
+ title = "QTL Detection Consensus",
1916
+ subtitle = "Green line = common QTL threshold (≥2)") +
1917
+ dark_theme
1918
+ gg2plotly(p)
1919
+ })
1920
+
1921
+ output$plot_common_qtl_map <- renderPlotly({
1922
+ req(rv$qtl_table)
1923
+ tbl <- rv$qtl_table
1924
+ chr_levels <- sort(unique(tbl$Chr))
1925
+ tbl$chr_num <- match(tbl$Chr, chr_levels)
1926
+ p <- ggplot(tbl, aes(x = Peak_Pos_cM, y = chr_num, color = Model, size = LOD,
1927
+ shape = Common_QTL,
1928
+ text = paste0(Model, " | Chr", Chr,
1929
+ " @ ", round(Peak_Pos_cM,1), " cM",
1930
+ "<br>LOD: ", round(LOD,2),
1931
+ "<br>Common: ", Common_QTL))) +
1932
+ geom_point(alpha = 0.8) +
1933
+ geom_rect(data = tbl[tbl$Common_QTL, ],
1934
+ aes(xmin = CI_Left_cM, xmax = CI_Right_cM,
1935
+ ymin = chr_num - 0.4, ymax = chr_num + 0.4),
1936
+ fill = "#f97316", alpha = 0.08, inherit.aes = FALSE,
1937
+ color = "#f97316", linewidth = 0.3) +
1938
+ scale_color_manual(values = setNames(model_colors[1:length(unique(tbl$Model))],
1939
+ unique(tbl$Model))) +
1940
+ scale_shape_manual(values = c("FALSE" = 16, "TRUE" = 18)) +
1941
+ scale_size_continuous(range = c(3, 10)) +
1942
+ scale_y_continuous(breaks = seq_along(chr_levels), labels = chr_levels) +
1943
+ labs(x = "Position (cM)", y = "Chromosome",
1944
+ title = "Common QTL Across Models — Genome View",
1945
+ subtitle = "Orange shading = common QTL CI region | Diamond = common QTL") +
1946
+ dark_theme
1947
+ gg2plotly(p)
1948
  })
1949
 
1950
+ # ── RESULTS TABLE ──────────────────────────────────────────────────────────
1951
+ output$qtl_results_table <- renderDT({
1952
+ req(rv$qtl_table)
1953
+ tbl <- rv$qtl_table
1954
+ datatable(tbl,
1955
+ options = list(
1956
+ dom = "Bfrtip",
1957
+ pageLength = 20,
1958
+ scrollX = TRUE,
1959
+ columnDefs = list(list(className = "dt-center", targets = "_all"))
1960
+ ),
1961
+ rownames = FALSE,
1962
+ class = "compact stripe"
1963
+ ) %>%
1964
+ formatStyle("LOD",
1965
+ background = styleColorBar(range(tbl$LOD), "#00d4ff"),
1966
+ backgroundSize = "100% 80%", backgroundRepeat = "no-repeat",
1967
+ backgroundPosition = "center") %>%
1968
+ formatStyle("PVE_pct",
1969
+ background = styleColorBar(range(tbl$PVE_pct), "#a3e635"),
1970
+ backgroundSize = "100% 80%", backgroundRepeat = "no-repeat",
1971
+ backgroundPosition = "center") %>%
1972
+ formatStyle("Common_QTL",
1973
+ color = styleEqual(c(TRUE, FALSE), c("#f97316", "#64748b")),
1974
+ fontWeight = styleEqual(TRUE, "bold")) %>%
1975
+ formatStyle(0, target = "row",
1976
+ backgroundColor = "#0f1c2e", color = "#e2e8f0")
1977
  })
1978
 
1979
+ # ── DOWNLOADS ─────────────────────────────────────────────────────────────
1980
+ output$dl_csv <- downloadHandler(
1981
+ filename = function() paste0("qtl_results_", Sys.Date(), ".csv"),
1982
+ content = function(file) {
1983
+ req(rv$qtl_table)
1984
+ write.csv(rv$qtl_table, file, row.names = FALSE)
1985
+ }
1986
+ )
1987
+ output$dl_tsv <- downloadHandler(
1988
+ filename = function() paste0("qtl_results_", Sys.Date(), ".tsv"),
1989
+ content = function(file) {
1990
+ req(rv$qtl_table)
1991
+ write.table(rv$qtl_table, file, sep = "\t", row.names = FALSE, quote = FALSE)
1992
+ }
1993
+ )
1994
+ output$dl_scan <- downloadHandler(
1995
+ filename = function() paste0("qtl_scan_data_", Sys.Date(), ".csv"),
1996
+ content = function(file) {
1997
+ req(length(rv$scan_list) > 0)
1998
+ df <- bind_rows(lapply(names(rv$scan_list), function(mn) {
1999
+ sc <- rv$scan_list[[mn]]
2000
+ data.frame(model = mn, chr = sc$chr, pos = sc$pos, lod = sc$lod,
2001
+ stringsAsFactors = FALSE)
2002
+ }))
2003
+ write.csv(df, file, row.names = FALSE)
2004
+ }
2005
+ )
2006
+ output$dl_rdata <- downloadHandler(
2007
+ filename = function() paste0("qtl_objects_", Sys.Date(), ".RData"),
2008
+ content = function(file) {
2009
+ cross <- rv$cross
2010
+ cross_calc <- rv$cross_calc
2011
+ scan_list <- rv$scan_list
2012
+ qtl_table <- rv$qtl_table
2013
+ save(cross, cross_calc, scan_list, qtl_table, file = file)
2014
+ }
2015
+ )
2016
+ output$dl_common <- downloadHandler(
2017
+ filename = function() paste0("common_qtl_", Sys.Date(), ".csv"),
2018
+ content = function(file) {
2019
+ req(rv$qtl_table)
2020
+ common <- rv$qtl_table[rv$qtl_table$Common_QTL, ]
2021
+ write.csv(common, file, row.names = FALSE)
2022
+ }
2023
+ )
2024
+ output$dl_report <- downloadHandler(
2025
+ filename = function() paste0("qtl_report_", Sys.Date(), ".html"),
2026
+ content = function(file) {
2027
+ req(rv$qtl_table)
2028
+ tbl <- rv$qtl_table
2029
+ n_qtl <- nrow(tbl)
2030
+ n_com <- sum(tbl$Common_QTL)
2031
+ html_content <- paste0(
2032
+ "<!DOCTYPE html><html><head>",
2033
+ "<meta charset='UTF-8'>",
2034
+ "<title>QTL Mapper Pro — Report</title>",
2035
+ "<style>",
2036
+ "body{font-family:'Segoe UI',sans-serif;background:#08111f;color:#e2e8f0;padding:40px;}",
2037
+ "h1{color:#00d4ff;} h2{color:#a3e635;border-bottom:1px solid #1e3a5f;padding-bottom:8px;}",
2038
+ "table{width:100%;border-collapse:collapse;font-size:13px;}",
2039
+ "th{background:#162033;color:#00d4ff;padding:8px;text-align:left;}",
2040
+ "td{padding:7px;border-bottom:1px solid #1e3a5f;}",
2041
+ "tr:hover td{background:#1e2d45;}",
2042
+ ".badge{display:inline-block;padding:3px 10px;border-radius:12px;font-size:12px;",
2043
+ " background:rgba(0,212,255,0.12);border:1px solid rgba(0,212,255,0.3);color:#00d4ff;}",
2044
+ ".hi{color:#f97316;font-weight:bold;}",
2045
+ "</style></head><body>",
2046
+ "<h1>🧬 QTL Mapper Pro — Analysis Report</h1>",
2047
+ "<p>Generated: ", as.character(Sys.time()), "</p>",
2048
+ "<h2>Summary</h2>",
2049
+ "<p>Total QTL detected: <span class='badge'>", n_qtl, "</span> &nbsp;",
2050
+ "Common QTL (≥2 models): <span class='badge'>", n_com, "</span></p>",
2051
+ "<h2>QTL Results Table</h2>",
2052
+ "<table><tr>",
2053
+ paste0("<th>", names(tbl), "</th>", collapse = ""),
2054
+ "</tr>",
2055
+ paste0(apply(tbl, 1, function(r) {
2056
+ paste0("<tr>", paste0("<td>", r, "</td>", collapse = ""), "</tr>")
2057
+ }), collapse = ""),
2058
+ "</table>",
2059
+ "</body></html>"
2060
+ )
2061
+ writeLines(html_content, file)
2062
+ }
2063
+ )
2064
  }
2065
 
2066
+ # ── Run ───────────────────────────────────────────────────────────────────────
2067
+ shinyApp(ui = ui, server = server)