softwareDevelopment commited on
Commit
8a1b63f
Β·
verified Β·
1 Parent(s): 36e0051

Update app.R

Browse files
Files changed (1) hide show
  1. app.R +1543 -58
app.R CHANGED
@@ -1,63 +1,1548 @@
1
- # prepare_data.R
2
- # Helper script to prepare CSV files for QTL analysis
3
-
4
- # Example: Prepare genotype data
5
- prepare_genotype_file <- function() {
6
- # Genotype file should have:
7
- # - First column: Marker names
8
- # - Subsequent columns: Individual genotypes
9
- # - Values: A, H, B (for riself cross type)
10
-
11
- # Example structure:
12
- # marker, ind1, ind2, ind3, ...
13
- # marker1, A, B, A, ...
14
- # marker2, A, A, B, ...
15
-
16
- # Save as CSV
17
- # write.csv(genotype_data, "genotypes.csv", row.names = FALSE)
18
- }
19
 
20
- # Example: Prepare phenotype file
21
- prepare_phenotype_file <- function() {
22
- # Phenotype file should have:
23
- # - First column: Individual IDs (matching genotype file columns)
24
- # - Subsequent columns: Phenotype measurements
25
-
26
- # Example structure:
27
- # id, height, weight
28
- # ind1, 10.5, 20.3
29
- # ind2, 11.2, 21.1
30
-
31
- # Save as CSV
32
- # write.csv(phenotype_data, "phenotypes.csv", row.names = FALSE)
33
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
 
35
- # Example data generation for testing
36
- create_example_data <- function(n_individuals = 100, n_markers = 50) {
37
- # Create example genotype data
38
- markers <- paste0("M", 1:n_markers)
39
- genotypes <- matrix(sample(c("A", "B"), n_markers * n_individuals,
40
- replace = TRUE), nrow = n_markers)
41
- colnames(genotypes) <- paste0("ind", 1:n_individuals)
42
- genotype_df <- cbind(marker = markers, genotypes)
43
-
44
- # Create example phenotype data
45
- phenotype_df <- data.frame(
46
- id = paste0("ind", 1:n_individuals),
47
- trait1 = rnorm(n_individuals, mean = 10, sd = 2),
48
- trait2 = rnorm(n_individuals, mean = 20, sd = 3)
49
  )
50
-
51
- # Save to files
52
- write.csv(genotype_df, "example_genotypes.csv", row.names = FALSE)
53
- write.csv(phenotype_df, "example_phenotypes.csv", row.names = FALSE)
54
-
55
- message("Example files created:")
56
- message("- example_genotypes.csv")
57
- message("- example_phenotypes.csv")
58
  }
59
 
60
- # Run this to create example data
61
- create_example_data()
62
- # Run the Shiny app
63
- shiny::runApp("app.R")
 
1
+ library(shiny)
2
+ library(qtl)
3
+ library(ggplot2)
4
+ library(dplyr)
5
+ library(tidyr)
6
+ library(DT)
7
+ library(shinycssloaders)
8
+ library(shinyjs)
9
+ library(plotly)
10
+ library(RColorBrewer)
11
+ library(grid)
12
+ library(gridExtra)
13
+ library(scales)
 
 
 
 
 
14
 
15
+ # ─── UI ───────────────────────────────────────────────────────────────────────
16
+ ui <- fluidPage(
17
+ useShinyjs(),
18
+ tags$head(
19
+ tags$link(
20
+ href = "https://fonts.googleapis.com/css2?family=Space+Mono:wght@400;700&family=DM+Sans:wght@300;400;500;600&display=swap",
21
+ rel = "stylesheet"
22
+ ),
23
+ tags$style(HTML("
24
+ :root {
25
+ --bg: #0a0e1a;
26
+ --panel: #111827;
27
+ --border: #1e2d40;
28
+ --accent1: #00d4ff;
29
+ --accent2: #ff6b35;
30
+ --accent3: #7cfc00;
31
+ --accent4: #ff3e8a;
32
+ --text: #e2e8f0;
33
+ --muted: #64748b;
34
+ --font-mono: 'Space Mono', monospace;
35
+ --font-body: 'DM Sans', sans-serif;
36
+ }
37
+
38
+ * { box-sizing: border-box; margin: 0; padding: 0; }
39
+
40
+ body {
41
+ background: var(--bg);
42
+ color: var(--text);
43
+ font-family: var(--font-body);
44
+ min-height: 100vh;
45
+ }
46
+
47
+ /* ── Header ── */
48
+ .qtl-header {
49
+ background: linear-gradient(135deg, #0a0e1a 0%, #0d1b2a 50%, #0a0e1a 100%);
50
+ border-bottom: 1px solid var(--border);
51
+ padding: 18px 32px;
52
+ display: flex;
53
+ align-items: center;
54
+ gap: 16px;
55
+ position: sticky;
56
+ top: 0;
57
+ z-index: 100;
58
+ }
59
+ .qtl-header .logo-mark {
60
+ width: 38px; height: 38px;
61
+ background: var(--accent1);
62
+ border-radius: 8px;
63
+ display: flex; align-items: center; justify-content: center;
64
+ font-family: var(--font-mono);
65
+ font-weight: 700;
66
+ font-size: 14px;
67
+ color: var(--bg);
68
+ letter-spacing: -1px;
69
+ flex-shrink: 0;
70
+ }
71
+ .qtl-header h1 {
72
+ font-family: var(--font-mono);
73
+ font-size: 18px;
74
+ color: var(--accent1);
75
+ letter-spacing: 2px;
76
+ text-transform: uppercase;
77
+ }
78
+ .qtl-header .subtitle {
79
+ font-size: 12px;
80
+ color: var(--muted);
81
+ letter-spacing: 1px;
82
+ margin-top: 2px;
83
+ }
84
+ .header-badges {
85
+ margin-left: auto;
86
+ display: flex; gap: 8px;
87
+ }
88
+ .badge-pill {
89
+ padding: 4px 12px;
90
+ border-radius: 100px;
91
+ font-size: 10px;
92
+ font-family: var(--font-mono);
93
+ letter-spacing: 1px;
94
+ border: 1px solid;
95
+ }
96
+ .badge-pill.green { color: var(--accent3); border-color: var(--accent3); background: rgba(124,252,0,.07); }
97
+ .badge-pill.blue { color: var(--accent1); border-color: var(--accent1); background: rgba(0,212,255,.07); }
98
+ .badge-pill.orange { color: var(--accent2); border-color: var(--accent2); background: rgba(255,107,53,.07); }
99
+
100
+ /* ── Layout ── */
101
+ .qtl-layout {
102
+ display: grid;
103
+ grid-template-columns: 280px 1fr;
104
+ height: calc(100vh - 65px);
105
+ }
106
+
107
+ /* ── Sidebar ── */
108
+ .qtl-sidebar {
109
+ background: var(--panel);
110
+ border-right: 1px solid var(--border);
111
+ overflow-y: auto;
112
+ padding: 20px 16px;
113
+ }
114
+ .qtl-sidebar::-webkit-scrollbar { width: 4px; }
115
+ .qtl-sidebar::-webkit-scrollbar-thumb { background: var(--border); border-radius: 4px; }
116
+
117
+ .section-label {
118
+ font-family: var(--font-mono);
119
+ font-size: 9px;
120
+ letter-spacing: 3px;
121
+ color: var(--muted);
122
+ text-transform: uppercase;
123
+ margin-bottom: 10px;
124
+ margin-top: 20px;
125
+ padding-left: 4px;
126
+ display: flex;
127
+ align-items: center;
128
+ gap: 8px;
129
+ }
130
+ .section-label::after {
131
+ content: '';
132
+ flex: 1;
133
+ height: 1px;
134
+ background: var(--border);
135
+ }
136
+ .section-label:first-child { margin-top: 0; }
137
+
138
+ /* file upload */
139
+ .qtl-upload {
140
+ border: 1.5px dashed var(--border);
141
+ border-radius: 10px;
142
+ padding: 14px;
143
+ transition: border-color .2s;
144
+ background: rgba(255,255,255,.015);
145
+ margin-bottom: 8px;
146
+ }
147
+ .qtl-upload:hover { border-color: var(--accent1); }
148
+ .qtl-upload label {
149
+ font-size: 11px;
150
+ color: var(--accent1);
151
+ font-family: var(--font-mono);
152
+ letter-spacing: 1px;
153
+ margin-bottom: 6px;
154
+ display: block;
155
+ }
156
+ .qtl-upload .shiny-input-container { margin: 0 !important; }
157
+ .shiny-input-container { color: var(--text) !important; }
158
+
159
+ /* selects / inputs */
160
+ .control-block { margin-bottom: 12px; }
161
+ .control-block label {
162
+ font-size: 10px;
163
+ color: var(--muted);
164
+ letter-spacing: 1px;
165
+ font-family: var(--font-mono);
166
+ text-transform: uppercase;
167
+ display: block;
168
+ margin-bottom: 4px;
169
+ }
170
+ select, input[type='number'], input[type='text'] {
171
+ width: 100%;
172
+ background: #0d1421;
173
+ border: 1px solid var(--border);
174
+ border-radius: 6px;
175
+ color: var(--text);
176
+ padding: 7px 10px;
177
+ font-size: 12px;
178
+ font-family: var(--font-body);
179
+ outline: none;
180
+ transition: border-color .2s;
181
+ appearance: none;
182
+ }
183
+ select:focus, input:focus { border-color: var(--accent1); }
184
+
185
+ /* checkbox group */
186
+ .shiny-input-checkboxgroup .checkbox label {
187
+ font-size: 11px;
188
+ color: var(--text);
189
+ display: flex;
190
+ align-items: center;
191
+ gap: 6px;
192
+ }
193
+
194
+ /* run button */
195
+ .btn-run {
196
+ width: 100%;
197
+ padding: 12px;
198
+ background: linear-gradient(135deg, var(--accent1), #0099cc);
199
+ border: none;
200
+ border-radius: 8px;
201
+ color: var(--bg);
202
+ font-family: var(--font-mono);
203
+ font-size: 12px;
204
+ font-weight: 700;
205
+ letter-spacing: 2px;
206
+ cursor: pointer;
207
+ transition: opacity .2s, transform .1s;
208
+ margin-top: 16px;
209
+ }
210
+ .btn-run:hover { opacity: .9; transform: translateY(-1px); }
211
+ .btn-run:active { transform: translateY(0); }
212
+
213
+ .btn-export {
214
+ width: 100%;
215
+ padding: 10px;
216
+ background: transparent;
217
+ border: 1px solid var(--accent3);
218
+ border-radius: 8px;
219
+ color: var(--accent3);
220
+ font-family: var(--font-mono);
221
+ font-size: 11px;
222
+ letter-spacing: 1px;
223
+ cursor: pointer;
224
+ margin-top: 8px;
225
+ transition: background .2s;
226
+ }
227
+ .btn-export:hover { background: rgba(124,252,0,.08); }
228
+
229
+ /* status indicator */
230
+ .status-row {
231
+ display: flex;
232
+ align-items: center;
233
+ gap: 8px;
234
+ padding: 8px 10px;
235
+ background: rgba(0,212,255,.05);
236
+ border: 1px solid var(--border);
237
+ border-radius: 6px;
238
+ margin-top: 12px;
239
+ font-size: 11px;
240
+ color: var(--muted);
241
+ font-family: var(--font-mono);
242
+ }
243
+ .status-dot {
244
+ width: 7px; height: 7px;
245
+ border-radius: 50%;
246
+ background: var(--muted);
247
+ flex-shrink: 0;
248
+ }
249
+ .status-dot.active { background: var(--accent3); box-shadow: 0 0 6px var(--accent3); }
250
+
251
+ /* ── Main content ── */
252
+ .qtl-main {
253
+ overflow-y: auto;
254
+ background: var(--bg);
255
+ }
256
+ .qtl-main::-webkit-scrollbar { width: 6px; }
257
+ .qtl-main::-webkit-scrollbar-thumb { background: var(--border); border-radius: 4px; }
258
+
259
+ /* tab bar */
260
+ .qtl-tabs {
261
+ display: flex;
262
+ gap: 2px;
263
+ padding: 12px 24px 0;
264
+ border-bottom: 1px solid var(--border);
265
+ background: var(--panel);
266
+ position: sticky;
267
+ top: 0;
268
+ z-index: 50;
269
+ overflow-x: auto;
270
+ }
271
+ .qtl-tabs::-webkit-scrollbar { display: none; }
272
+ .qtl-tab-btn {
273
+ padding: 9px 16px;
274
+ border: none;
275
+ background: transparent;
276
+ color: var(--muted);
277
+ font-family: var(--font-mono);
278
+ font-size: 10px;
279
+ letter-spacing: 1px;
280
+ text-transform: uppercase;
281
+ cursor: pointer;
282
+ border-bottom: 2px solid transparent;
283
+ transition: color .2s, border-color .2s;
284
+ white-space: nowrap;
285
+ border-radius: 4px 4px 0 0;
286
+ }
287
+ .qtl-tab-btn:hover { color: var(--text); }
288
+ .qtl-tab-btn.active { color: var(--accent1); border-bottom-color: var(--accent1); }
289
+
290
+ /* content panels */
291
+ .tab-content { display: none; padding: 24px; }
292
+ .tab-content.active { display: block; }
293
+
294
+ /* plot cards */
295
+ .plot-card {
296
+ background: var(--panel);
297
+ border: 1px solid var(--border);
298
+ border-radius: 12px;
299
+ overflow: hidden;
300
+ margin-bottom: 20px;
301
+ }
302
+ .plot-card-header {
303
+ display: flex;
304
+ align-items: center;
305
+ padding: 14px 18px;
306
+ border-bottom: 1px solid var(--border);
307
+ background: rgba(255,255,255,.02);
308
+ gap: 10px;
309
+ }
310
+ .plot-card-icon {
311
+ width: 28px; height: 28px;
312
+ border-radius: 6px;
313
+ display: flex; align-items: center; justify-content: center;
314
+ font-size: 13px;
315
+ flex-shrink: 0;
316
+ }
317
+ .plot-card-icon.cyan { background: rgba(0,212,255,.15); }
318
+ .plot-card-icon.orange { background: rgba(255,107,53,.15); }
319
+ .plot-card-icon.green { background: rgba(124,252,0,.15); }
320
+ .plot-card-icon.pink { background: rgba(255,62,138,.15); }
321
+ .plot-card-title {
322
+ font-family: var(--font-mono);
323
+ font-size: 12px;
324
+ color: var(--text);
325
+ letter-spacing: 1px;
326
+ }
327
+ .plot-card-subtitle { font-size: 10px; color: var(--muted); margin-top: 1px; }
328
+ .plot-card-body { padding: 16px; }
329
+
330
+ /* stat chips */
331
+ .stat-row {
332
+ display: flex;
333
+ gap: 10px;
334
+ flex-wrap: wrap;
335
+ margin-bottom: 16px;
336
+ }
337
+ .stat-chip {
338
+ padding: 6px 14px;
339
+ border-radius: 6px;
340
+ font-family: var(--font-mono);
341
+ font-size: 11px;
342
+ }
343
+ .stat-chip.blue { background: rgba(0,212,255,.1); color: var(--accent1); border: 1px solid rgba(0,212,255,.2); }
344
+ .stat-chip.orange { background: rgba(255,107,53,.1); color: var(--accent2); border: 1px solid rgba(255,107,53,.2); }
345
+ .stat-chip.green { background: rgba(124,252,0,.1); color: var(--accent3); border: 1px solid rgba(124,252,0,.2); }
346
+ .stat-chip.pink { background: rgba(255,62,138,.1); color: var(--accent4); border: 1px solid rgba(255,62,138,.2); }
347
+
348
+ /* grid layouts */
349
+ .grid-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; }
350
+ .grid-3 { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 20px; }
351
+ @media (max-width: 1100px) { .grid-3 { grid-template-columns: 1fr 1fr; } }
352
+ @media (max-width: 800px) { .grid-2, .grid-3 { grid-template-columns: 1fr; } }
353
+
354
+ /* DataTable */
355
+ .dataTables_wrapper { color: var(--text) !important; font-size: 12px; }
356
+ table.dataTable { background: transparent !important; color: var(--text) !important; border-collapse: collapse !important; }
357
+ table.dataTable thead th {
358
+ background: #0d1421 !important;
359
+ color: var(--accent1) !important;
360
+ font-family: var(--font-mono) !important;
361
+ font-size: 10px !important;
362
+ letter-spacing: 1px !important;
363
+ border-bottom: 1px solid var(--border) !important;
364
+ padding: 10px 12px !important;
365
+ }
366
+ table.dataTable tbody tr { background: transparent !important; }
367
+ table.dataTable tbody tr:hover td { background: rgba(0,212,255,.04) !important; }
368
+ table.dataTable tbody td { border-bottom: 1px solid var(--border) !important; padding: 8px 12px !important; }
369
+ .dataTables_info, .dataTables_paginate { color: var(--muted) !important; font-size: 11px !important; }
370
+ .paginate_button { color: var(--muted) !important; }
371
+ .paginate_button.current { background: var(--accent1) !important; color: var(--bg) !important; border-radius: 4px !important; }
372
+ .dataTables_filter input, .dataTables_length select {
373
+ background: #0d1421 !important;
374
+ border: 1px solid var(--border) !important;
375
+ color: var(--text) !important;
376
+ border-radius: 4px !important;
377
+ padding: 4px 8px !important;
378
+ }
379
+
380
+ /* ggplot backgrounds */
381
+ .shiny-plot-output { background: transparent !important; }
382
+
383
+ /* loading overlay */
384
+ .loading-overlay {
385
+ position: fixed;
386
+ inset: 0;
387
+ background: rgba(10,14,26,.85);
388
+ z-index: 9999;
389
+ display: flex;
390
+ flex-direction: column;
391
+ align-items: center;
392
+ justify-content: center;
393
+ gap: 16px;
394
+ }
395
+ .spinner {
396
+ width: 48px; height: 48px;
397
+ border: 3px solid var(--border);
398
+ border-top-color: var(--accent1);
399
+ border-radius: 50%;
400
+ animation: spin .8s linear infinite;
401
+ }
402
+ @keyframes spin { to { transform: rotate(360deg); } }
403
+ .loading-text { font-family: var(--font-mono); font-size: 12px; color: var(--accent1); letter-spacing: 2px; }
404
+
405
+ /* misc */
406
+ .info-box {
407
+ background: rgba(0,212,255,.05);
408
+ border: 1px solid rgba(0,212,255,.2);
409
+ border-radius: 8px;
410
+ padding: 12px 16px;
411
+ font-size: 12px;
412
+ color: var(--muted);
413
+ line-height: 1.6;
414
+ margin-bottom: 16px;
415
+ }
416
+ .model-tag {
417
+ display: inline-block;
418
+ padding: 2px 8px;
419
+ border-radius: 4px;
420
+ font-size: 10px;
421
+ font-family: var(--font-mono);
422
+ margin: 2px;
423
+ background: rgba(255,255,255,.05);
424
+ border: 1px solid var(--border);
425
+ color: var(--muted);
426
+ }
427
+ hr.divider { border: none; border-top: 1px solid var(--border); margin: 20px 0; }
428
+ "))
429
+ ),
430
+
431
+ # ── Header ──────────────────────────────────────────────────────────────────
432
+ div(class = "qtl-header",
433
+ div(class = "logo-mark", "QTL"),
434
+ div(
435
+ tags$h1("QTL Mapper Pro"),
436
+ div(class = "subtitle", "Quantitative Trait Loci Analysis Pipeline")
437
+ ),
438
+ div(class = "header-badges",
439
+ div(class = "badge-pill blue", "R/QTL ENGINE"),
440
+ div(class = "badge-pill green", "10+ MODELS"),
441
+ div(class = "badge-pill orange","MULTI-TRAIT")
442
+ )
443
+ ),
444
+
445
+ # ── Main layout ─────────────────────────────────────────────────────────────
446
+ div(class = "qtl-layout",
447
+
448
+ # ── Sidebar ───────────────────────────────────────────────────────────────
449
+ div(class = "qtl-sidebar",
450
+
451
+ div(class = "section-label", "Data Input"),
452
+
453
+ div(class = "qtl-upload",
454
+ tags$label("Genotype CSV"),
455
+ fileInput("geno_file", NULL, accept = ".csv",
456
+ buttonLabel = "Browse", placeholder = "genotypes.csv")
457
+ ),
458
+ div(class = "qtl-upload",
459
+ tags$label("Phenotype CSV"),
460
+ fileInput("pheno_file", NULL, accept = ".csv",
461
+ buttonLabel = "Browse", placeholder = "phenotypes.csv")
462
+ ),
463
+
464
+ checkboxInput("use_example", "Use built-in example data", value = TRUE),
465
+
466
+ div(class = "section-label", "Cross Type"),
467
+ div(class = "control-block",
468
+ selectInput("cross_type", NULL,
469
+ choices = c("Backcross" = "bc",
470
+ "F2 Intercross" = "f2",
471
+ "RIL (selfing)" = "riself",
472
+ "RIL (sib-mating)" = "risib",
473
+ "4-way cross" = "4way"),
474
+ selected = "riself")
475
+ ),
476
+
477
+ div(class = "section-label", "Phenotype"),
478
+ div(class = "control-block",
479
+ selectInput("pheno_col", NULL, choices = NULL)
480
+ ),
481
+
482
+ div(class = "section-label", "Scan Models"),
483
+ checkboxGroupInput("models", NULL,
484
+ choices = c(
485
+ "EM Algorithm (em)" = "em",
486
+ "Haley-Knott (hk)" = "hk",
487
+ "Extended HK (ehk)" = "ehk",
488
+ "Multiple Imputation (imp)" = "imp",
489
+ "Composite Interval (cim)" = "cim",
490
+ "Two-Part Model (2part)" = "2part",
491
+ "Non-Parametric (np)" = "np",
492
+ "Marker Regression (mr)" = "mr",
493
+ "MR + Imputation (mr-imp)" = "mr-imp",
494
+ "MR + HK (mr-argmax)" = "mr-argmax"
495
+ ),
496
+ selected = c("em","hk","ehk","imp","cim","np","mr")
497
+ ),
498
+
499
+ div(class = "section-label", "Permutation"),
500
+ div(class = "control-block",
501
+ tags$label("Permutations (0 = skip)"),
502
+ numericInput("n_perm", NULL, value = 100, min = 0, max = 1000, step = 50)
503
+ ),
504
+ div(class = "control-block",
505
+ tags$label("Ξ± threshold"),
506
+ numericInput("alpha_thresh", NULL, value = 0.05, min = 0.01, max = 0.1, step = 0.01)
507
+ ),
508
+ div(class = "control-block",
509
+ tags$label("Fixed LOD threshold"),
510
+ numericInput("lod_thresh", NULL, value = 3.0, min = 1, max = 10, step = 0.5)
511
+ ),
512
+
513
+ div(class = "section-label", "Genome Scan"),
514
+ div(class = "control-block",
515
+ tags$label("Step (cM)"),
516
+ numericInput("step_size", NULL, value = 1, min = 0.5, max = 5, step = 0.5)
517
+ ),
518
+ div(class = "control-block",
519
+ tags$label("Error probability"),
520
+ numericInput("error_prob", NULL, value = 0.001, min = 0.0001, max = 0.01, step = 0.001)
521
+ ),
522
+
523
+ actionButton("run_analysis", "β–Ά RUN ANALYSIS", class = "btn-run"),
524
+ downloadButton("download_results", "⬇ EXPORT CSV", class = "btn-export"),
525
+
526
+ div(class = "status-row",
527
+ div(id = "status_dot", class = "status-dot"),
528
+ textOutput("status_text", inline = TRUE)
529
+ )
530
+ ),
531
+
532
+ # ── Main panel ────────────────────────────────────────────────────────────
533
+ div(class = "qtl-main",
534
+
535
+ # Tab bar
536
+ div(class = "qtl-tabs",
537
+ tags$button(class = "qtl-tab-btn active", `data-tab` = "overview", "Overview"),
538
+ tags$button(class = "qtl-tab-btn", `data-tab` = "manhattan", "Manhattan"),
539
+ tags$button(class = "qtl-tab-btn", `data-tab` = "genome", "Genome Scan"),
540
+ tags$button(class = "qtl-tab-btn", `data-tab` = "chromosome", "Chr Plots"),
541
+ tags$button(class = "qtl-tab-btn", `data-tab` = "model_comp", "Model Compare"),
542
+ tags$button(class = "qtl-tab-btn", `data-tab` = "effects", "QTL Effects"),
543
+ tags$button(class = "qtl-tab-btn", `data-tab` = "pairwise", "2D Scan"),
544
+ tags$button(class = "qtl-tab-btn", `data-tab` = "diagnostics", "Diagnostics"),
545
+ tags$button(class = "qtl-tab-btn", `data-tab` = "results", "QTL Table"),
546
+ tags$button(class = "qtl-tab-btn", `data-tab` = "summary", "Summary")
547
+ ),
548
+
549
+ # ── OVERVIEW ────────────────────────────────────────────────────────────
550
+ div(id = "tab_overview", class = "tab-content active",
551
+ div(class = "stat-row",
552
+ uiOutput("stat_markers"),
553
+ uiOutput("stat_inds"),
554
+ uiOutput("stat_chrs"),
555
+ uiOutput("stat_qtls")
556
+ ),
557
+ div(class = "grid-2",
558
+ div(class = "plot-card",
559
+ div(class = "plot-card-header",
560
+ div(class = "plot-card-icon cyan", "πŸ“Š"),
561
+ div(div(class = "plot-card-title", "GENOME MAP"), div(class = "plot-card-subtitle", "Marker distribution"))
562
+ ),
563
+ div(class = "plot-card-body", plotOutput("plot_genome_map", height = "320px") %>% withSpinner(color = "#00d4ff", type = 4))
564
+ ),
565
+ div(class = "plot-card",
566
+ div(class = "plot-card-header",
567
+ div(class = "plot-card-icon orange", "πŸ“ˆ"),
568
+ div(div(class = "plot-card-title", "PHENOTYPE DIST"), div(class = "plot-card-subtitle", "Distribution & QQ"))
569
+ ),
570
+ div(class = "plot-card-body", plotOutput("plot_pheno_dist", height = "320px") %>% withSpinner(color = "#ff6b35", type = 4))
571
+ )
572
+ ),
573
+ div(class = "plot-card",
574
+ div(class = "plot-card-header",
575
+ div(class = "plot-card-icon green", "πŸ—Ί"),
576
+ div(div(class = "plot-card-title", "PHYSICAL MAP"), div(class = "plot-card-subtitle", "All chromosomes β€” marker positions"))
577
+ ),
578
+ div(class = "plot-card-body", plotOutput("plot_physical_map", height = "260px") %>% withSpinner(color = "#7cfc00", type = 4))
579
+ )
580
+ ),
581
+
582
+ # ── MANHATTAN ───────────────────────────────────────────────────────────
583
+ div(id = "tab_manhattan", class = "tab-content",
584
+ div(class = "info-box",
585
+ "Manhattan plot shows βˆ’log10(p-value) or LOD score across all chromosomes. Peaks above the threshold line are candidate QTL regions."
586
+ ),
587
+ div(class = "plot-card",
588
+ div(class = "plot-card-header",
589
+ div(class = "plot-card-icon cyan", "πŸŒƒ"),
590
+ div(div(class = "plot-card-title", "MANHATTAN PLOT"), div(class = "plot-card-subtitle", "LOD scores genome-wide"))
591
+ ),
592
+ div(class = "plot-card-body",
593
+ div(class = "control-block", style = "max-width:200px; margin-bottom:12px;",
594
+ selectInput("manhattan_model", "Model:", choices = NULL)
595
+ ),
596
+ plotOutput("plot_manhattan", height = "420px") %>% withSpinner(color = "#00d4ff", type = 4)
597
+ )
598
+ ),
599
+ div(class = "plot-card",
600
+ div(class = "plot-card-header",
601
+ div(class = "plot-card-icon pink", "🎯"),
602
+ div(div(class = "plot-card-title", "INTERACTIVE MANHATTAN"), div(class = "plot-card-subtitle", "Hover for marker details"))
603
+ ),
604
+ div(class = "plot-card-body",
605
+ plotlyOutput("plot_manhattan_interactive", height = "380px") %>% withSpinner(color = "#ff3e8a", type = 4)
606
+ )
607
+ )
608
+ ),
609
+
610
+ # ── GENOME SCAN ─────────────────────────────────────────────────────────
611
+ div(id = "tab_genome", class = "tab-content",
612
+ div(class = "plot-card",
613
+ div(class = "plot-card-header",
614
+ div(class = "plot-card-icon cyan", "πŸ”¬"),
615
+ div(div(class = "plot-card-title", "GENOME SCAN β€” ALL MODELS"), div(class = "plot-card-subtitle", "LOD profiles overlaid"))
616
+ ),
617
+ div(class = "plot-card-body",
618
+ plotOutput("plot_scan_all_models", height = "480px") %>% withSpinner(color = "#00d4ff", type = 4)
619
+ )
620
+ )
621
+ ),
622
+
623
+ # ── CHROMOSOME PLOTS ────────────────────────────────────────────────────
624
+ div(id = "tab_chromosome", class = "tab-content",
625
+ div(class = "info-box",
626
+ "Per-chromosome LOD profiles styled like R/qtl's plotQTL. Significant peaks are labelled with QTL names."
627
+ ),
628
+ div(class = "control-block", style = "max-width:200px; margin-bottom:16px;",
629
+ selectInput("chr_plot_model", "Model:", choices = NULL)
630
+ ),
631
+ plotOutput("plot_chr_grid", height = "900px") %>% withSpinner(color = "#7cfc00", type = 4)
632
+ ),
633
+
634
+ # ── MODEL COMPARISON ───────��────────────────────────────────────────────
635
+ div(id = "tab_model_comp", class = "tab-content",
636
+ div(class = "grid-2",
637
+ div(class = "plot-card",
638
+ div(class = "plot-card-header",
639
+ div(class = "plot-card-icon orange", "βš–οΈ"),
640
+ div(div(class = "plot-card-title", "PEAK LOD COMPARISON"), div(class = "plot-card-subtitle", "Max LOD per model"))
641
+ ),
642
+ div(class = "plot-card-body", plotOutput("plot_model_bar", height = "340px") %>% withSpinner(color="#ff6b35",type=4))
643
+ ),
644
+ div(class = "plot-card",
645
+ div(class = "plot-card-header",
646
+ div(class = "plot-card-icon pink", "πŸ”·"),
647
+ div(div(class = "plot-card-title", "LOD HEATMAP"), div(class = "plot-card-subtitle", "Marker Γ— Model"))
648
+ ),
649
+ div(class = "plot-card-body", plotOutput("plot_lod_heatmap", height = "340px") %>% withSpinner(color="#ff3e8a",type=4))
650
+ )
651
+ ),
652
+ div(class = "plot-card",
653
+ div(class = "plot-card-header",
654
+ div(class = "plot-card-icon cyan", "πŸ“‰"),
655
+ div(div(class = "plot-card-title", "MODEL CORRELATION"), div(class = "plot-card-subtitle", "LOD score agreement across models"))
656
+ ),
657
+ div(class = "plot-card-body", plotOutput("plot_model_corr", height = "340px") %>% withSpinner(color="#00d4ff",type=4))
658
+ )
659
+ ),
660
+
661
+ # ── QTL EFFECTS ─────────────────────────────────────────────────────────
662
+ div(id = "tab_effects", class = "tab-content",
663
+ div(class = "grid-2",
664
+ div(class = "plot-card",
665
+ div(class = "plot-card-header",
666
+ div(class = "plot-card-icon green", "🎻"),
667
+ div(div(class = "plot-card-title", "EFFECT PLOT"), div(class = "plot-card-subtitle", "Genotype effect at peak markers"))
668
+ ),
669
+ div(class = "plot-card-body",
670
+ div(class = "control-block", style = "margin-bottom:10px;",
671
+ selectInput("effect_qtl", "Select QTL:", choices = NULL)
672
+ ),
673
+ plotOutput("plot_effects", height = "320px") %>% withSpinner(color="#7cfc00",type=4)
674
+ )
675
+ ),
676
+ div(class = "plot-card",
677
+ div(class = "plot-card-header",
678
+ div(class = "plot-card-icon orange", "πŸ“¦"),
679
+ div(div(class = "plot-card-title", "PHENOTYPE Γ— GENOTYPE"), div(class = "plot-card-subtitle", "Boxplot at peak marker"))
680
+ ),
681
+ div(class = "plot-card-body",
682
+ plotOutput("plot_pheno_geno", height = "320px") %>% withSpinner(color="#ff6b35",type=4)
683
+ )
684
+ )
685
+ ),
686
+ div(class = "plot-card",
687
+ div(class = "plot-card-header",
688
+ div(class = "plot-card-icon pink", "🌑"),
689
+ div(div(class = "plot-card-title", "PVE PROFILE"), div(class = "plot-card-subtitle", "Proportion of variance explained per position"))
690
+ ),
691
+ div(class = "plot-card-body", plotOutput("plot_pve", height = "280px") %>% withSpinner(color="#ff3e8a",type=4))
692
+ )
693
+ ),
694
+
695
+ # ── 2D SCAN ─────────────────────────────────────────────────────────────
696
+ div(id = "tab_pairwise", class = "tab-content",
697
+ div(class = "plot-card",
698
+ div(class = "plot-card-header",
699
+ div(class = "plot-card-icon cyan", "πŸ”²"),
700
+ div(div(class = "plot-card-title", "2D GENOME SCAN"), div(class = "plot-card-subtitle", "Pairwise LOD / epistasis"))
701
+ ),
702
+ div(class = "plot-card-body", plotOutput("plot_2d_scan", height = "560px") %>% withSpinner(color="#00d4ff",type=4))
703
+ )
704
+ ),
705
+
706
+ # ── DIAGNOSTICS ─────────────────────────────────────────────────────────
707
+ div(id = "tab_diagnostics", class = "tab-content",
708
+ div(class = "grid-2",
709
+ div(class = "plot-card",
710
+ div(class = "plot-card-header",
711
+ div(class = "plot-card-icon orange", "πŸ”"),
712
+ div(div(class = "plot-card-title", "MISSING DATA"), div(class = "plot-card-subtitle", "Genotype completeness"))
713
+ ),
714
+ div(class = "plot-card-body", plotOutput("plot_missing", height = "300px") %>% withSpinner(color="#ff6b35",type=4))
715
+ ),
716
+ div(class = "plot-card",
717
+ div(class = "plot-card-header",
718
+ div(class = "plot-card-icon green", "πŸ“"),
719
+ div(div(class = "plot-card-title", "GENOTYPE FREQ"), div(class = "plot-card-subtitle", "Allele frequency per marker"))
720
+ ),
721
+ div(class = "plot-card-body", plotOutput("plot_geno_freq", height = "300px") %>% withSpinner(color="#7cfc00",type=4))
722
+ )
723
+ ),
724
+ div(class = "plot-card",
725
+ div(class = "plot-card-header",
726
+ div(class = "plot-card-icon pink", "πŸ”—"),
727
+ div(div(class = "plot-card-title", "MARKER DISTANCE"), div(class = "plot-card-subtitle", "Inter-marker spacing"))
728
+ ),
729
+ div(class = "plot-card-body", plotOutput("plot_marker_dist", height = "260px") %>% withSpinner(color="#ff3e8a",type=4))
730
+ )
731
+ ),
732
+
733
+ # ── RESULTS TABLE ───────────────────────────────────────────────────────
734
+ div(id = "tab_results", class = "tab-content",
735
+ div(class = "plot-card",
736
+ div(class = "plot-card-header",
737
+ div(class = "plot-card-icon cyan", "πŸ“‹"),
738
+ div(div(class = "plot-card-title", "QTL RESULTS TABLE"),
739
+ div(class = "plot-card-subtitle", "Peak marker, flanking markers, LOD, PVE, effects, CI"))
740
+ ),
741
+ div(class = "plot-card-body",
742
+ DTOutput("table_qtl_results")
743
+ )
744
+ )
745
+ ),
746
+
747
+ # ── SUMMARY ─────────────────────────────────────────────────────────────
748
+ div(id = "tab_summary", class = "tab-content",
749
+ div(class = "plot-card",
750
+ div(class = "plot-card-header",
751
+ div(class = "plot-card-icon green", "πŸ“"),
752
+ div(div(class = "plot-card-title", "ANALYSIS SUMMARY"), div(class = "plot-card-subtitle", "All models"))
753
+ ),
754
+ div(class = "plot-card-body",
755
+ DTOutput("table_model_summary")
756
+ )
757
+ ),
758
+ div(class = "plot-card", style = "margin-top:20px;",
759
+ div(class = "plot-card-header",
760
+ div(class = "plot-card-icon orange", "πŸ†"),
761
+ div(div(class = "plot-card-title", "PERMUTATION THRESHOLDS"), div(class = "plot-card-subtitle", "Significance levels per model"))
762
+ ),
763
+ div(class = "plot-card-body",
764
+ DTOutput("table_perm_thresholds")
765
+ )
766
+ )
767
+ )
768
+ )
769
+ ),
770
+
771
+ # JS for tab switching
772
+ tags$script(HTML("
773
+ document.querySelectorAll('.qtl-tab-btn').forEach(function(btn) {
774
+ btn.addEventListener('click', function() {
775
+ document.querySelectorAll('.qtl-tab-btn').forEach(b => b.classList.remove('active'));
776
+ document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
777
+ btn.classList.add('active');
778
+ document.getElementById('tab_' + btn.dataset.tab).classList.add('active');
779
+ });
780
+ });
781
+ "))
782
+ )
783
+
784
+ # ─── SERVER ───────────────────────────────────────────────────────────────────
785
+ server <- function(input, output, session) {
786
+
787
+ # dark ggplot theme ──────────────────────────────────────────────────────────
788
+ theme_qtl <- function(base_size = 11) {
789
+ theme_minimal(base_size = base_size) +
790
+ theme(
791
+ plot.background = element_rect(fill = "#111827", color = NA),
792
+ panel.background = element_rect(fill = "#0d1421", color = NA),
793
+ panel.grid.major = element_line(color = "#1e2d40", linewidth = .4),
794
+ panel.grid.minor = element_line(color = "#161f2e", linewidth = .2),
795
+ panel.border = element_rect(color = "#1e2d40", fill = NA),
796
+ axis.text = element_text(color = "#64748b", size = 9, family = "mono"),
797
+ axis.title = element_text(color = "#94a3b8", size = 10),
798
+ plot.title = element_text(color = "#e2e8f0", size = 12, face = "bold", family = "mono"),
799
+ plot.subtitle = element_text(color = "#64748b", size = 9),
800
+ legend.background = element_rect(fill = "#111827", color = NA),
801
+ legend.text = element_text(color = "#94a3b8", size = 9),
802
+ legend.title = element_text(color = "#64748b", size = 9),
803
+ strip.background = element_rect(fill = "#0d1421", color = "#1e2d40"),
804
+ strip.text = element_text(color = "#00d4ff", size = 9, family = "mono"),
805
+ plot.margin = margin(12, 16, 12, 16)
806
+ )
807
+ }
808
+
809
+ model_colors <- c(
810
+ em = "#00d4ff",
811
+ hk = "#ff6b35",
812
+ ehk = "#7cfc00",
813
+ imp = "#ff3e8a",
814
+ cim = "#a78bfa",
815
+ `2part` = "#fbbf24",
816
+ np = "#34d399",
817
+ mr = "#f87171",
818
+ `mr-imp` = "#60a5fa",
819
+ `mr-argmax` = "#fb923c"
820
+ )
821
+
822
+ # ── reactive cross object ──────────────────────────────────────────────────
823
+ cross_data <- reactive({
824
+ if (input$use_example || (is.null(input$geno_file) && is.null(input$pheno_file))) {
825
+ data(hyper, package = "qtl")
826
+ return(hyper)
827
+ }
828
+ req(input$geno_file, input$pheno_file)
829
+ tryCatch({
830
+ read.cross(format = "csv",
831
+ genfile = input$geno_file$datapath,
832
+ phefile = input$pheno_file$datapath,
833
+ crosstype = input$cross_type)
834
+ }, error = function(e) {
835
+ showNotification(paste("Error loading data:", e$message), type = "error")
836
+ NULL
837
+ })
838
+ })
839
+
840
+ # update UI dropdowns after cross loads ─────────────────────────────────────
841
+ observe({
842
+ cross <- cross_data()
843
+ req(cross)
844
+ pheno_names <- names(cross$pheno)
845
+ updateSelectInput(session, "pheno_col", choices = pheno_names, selected = pheno_names[1])
846
+ })
847
+
848
+ # ── analysis results (reactive) ─────────────────────────────────────────────
849
+ analysis_results <- reactiveVal(NULL)
850
+
851
+ observeEvent(input$run_analysis, {
852
+ cross <- cross_data()
853
+ req(cross)
854
+
855
+ runjs("document.getElementById('status_dot').classList.add('active')")
856
+ output$status_text <- renderText("Running analysis...")
857
+
858
+ withProgress(message = "QTL Mapping in progress...", value = 0, {
859
+
860
+ cross <- calc.genoprob(cross,
861
+ step = input$step_size,
862
+ error.prob = input$error_prob)
863
+ incProgress(0.1, detail = "Genoprobs calculated")
864
+
865
+ cross <- sim.geno(cross, n.draws = 64, step = input$step_size, error.prob = input$error_prob)
866
+ incProgress(0.1, detail = "Simulated genotypes done")
867
+
868
+ pheno_idx <- which(names(cross$pheno) == input$pheno_col)
869
+
870
+ scan_results <- list()
871
+ models_to_run <- input$models
872
+ n_models <- length(models_to_run)
873
+ perm_results <- list()
874
+
875
+ for (i in seq_along(models_to_run)) {
876
+ mdl <- models_to_run[i]
877
+ incProgress(0.5 / n_models, detail = paste("Scanning:", mdl))
878
+
879
+ sc <- tryCatch(
880
+ scanone(cross, pheno.col = pheno_idx, method = mdl),
881
+ error = function(e) NULL
882
+ )
883
+ if (!is.null(sc)) {
884
+ scan_results[[mdl]] <- sc
885
+
886
+ if (input$n_perm > 0) {
887
+ perm_results[[mdl]] <- tryCatch(
888
+ scanone(cross, pheno.col = pheno_idx, method = mdl,
889
+ n.perm = input$n_perm, verbose = FALSE),
890
+ error = function(e) NULL
891
+ )
892
+ }
893
+ }
894
+ }
895
+ incProgress(0.1, detail = "Summarising QTLs")
896
+
897
+ # Threshold
898
+ lod_thr <- input$lod_thresh
899
+ if (length(perm_results) > 0) {
900
+ first_perm <- perm_results[[1]]
901
+ if (!is.null(first_perm))
902
+ lod_thr <- summary(first_perm, alpha = input$alpha_thresh)[1]
903
+ }
904
+
905
+ # Build results table
906
+ qtl_table <- build_qtl_table(cross, scan_results, lod_thr, pheno_idx)
907
+
908
+ analysis_results(list(
909
+ cross = cross,
910
+ scan_results = scan_results,
911
+ perm_results = perm_results,
912
+ lod_thr = lod_thr,
913
+ qtl_table = qtl_table,
914
+ pheno_idx = pheno_idx
915
+ ))
916
+
917
+ incProgress(0.1, detail = "Done")
918
+ })
919
+
920
+ # update dropdowns that depend on results
921
+ res <- analysis_results()
922
+ model_choices <- names(res$scan_results)
923
+ updateSelectInput(session, "manhattan_model", choices = model_choices, selected = model_choices[1])
924
+ updateSelectInput(session, "chr_plot_model", choices = model_choices, selected = model_choices[1])
925
+
926
+ qtl_choices <- if (!is.null(res$qtl_table) && nrow(res$qtl_table) > 0)
927
+ paste0(res$qtl_table$Chr, "@", res$qtl_table$Peak_Marker) else "none"
928
+ updateSelectInput(session, "effect_qtl", choices = qtl_choices)
929
+
930
+ runjs("document.getElementById('status_dot').classList.add('active')")
931
+ output$status_text <- renderText(paste("Done β€”", length(model_choices), "models"))
932
+ })
933
+
934
+ # ── Helper: build QTL summary table ─────────────────────────────────────────
935
+ build_qtl_table <- function(cross, scan_results, lod_thr, pheno_idx) {
936
+ rows <- list()
937
+ for (mdl in names(scan_results)) {
938
+ sc <- scan_results[[mdl]]
939
+ sig <- sc[sc$lod >= lod_thr, , drop = FALSE]
940
+ if (nrow(sig) == 0) next
941
+
942
+ # find peaks per chromosome
943
+ for (ch in unique(sig$chr)) {
944
+ chr_sc <- sc[sc$chr == ch, ]
945
+ peak_row <- chr_sc[which.max(chr_sc$lod), ]
946
+ peak_pos <- peak_row$pos
947
+ peak_lod <- peak_row$lod
948
+ peak_marker <- rownames(peak_row)
949
+
950
+ # CI via drop-1.5 LOD
951
+ ci <- tryCatch(lodint(sc, chr = ch, drop = 1.5), error = function(e) NULL)
952
+ left_marker <- if (!is.null(ci)) rownames(ci)[1] else NA_character_
953
+ right_marker <- if (!is.null(ci)) rownames(ci)[nrow(ci)] else NA_character_
954
+ left_pos <- if (!is.null(ci)) ci$pos[1] else NA_real_
955
+ right_pos <- if (!is.null(ci)) ci$pos[nrow(ci)] else NA_real_
956
+
957
+ # additive/dom effects (try)
958
+ eff <- tryCatch({
959
+ m <- find.marker(cross, chr = ch, pos = peak_pos)
960
+ effectplot(cross, mname1 = m, pheno.col = pheno_idx, draw = FALSE)
961
+ }, error = function(e) NULL)
962
+
963
+ add_eff <- if (!is.null(eff)) round(diff(range(eff$Means)), 4) else NA
964
+ dom_eff <- NA
965
+
966
+ # PVE approx: r2 from lod
967
+ n <- nind(cross)
968
+ pve <- round((1 - 10^(-2 * peak_lod / n)) * 100, 2)
969
+
970
+ rows[[length(rows) + 1]] <- data.frame(
971
+ Model = mdl,
972
+ Chr = as.character(ch),
973
+ Peak_Marker = peak_marker,
974
+ Peak_pos_cM = round(peak_pos, 2),
975
+ LOD = round(peak_lod, 3),
976
+ PVE_pct = pve,
977
+ Additive_Eff = add_eff,
978
+ Dom_Eff = dom_eff,
979
+ Left_Marker = left_marker,
980
+ Left_pos_cM = round(left_pos, 2),
981
+ Right_Marker = right_marker,
982
+ Right_pos_cM = round(right_pos, 2),
983
+ CI_width_cM = round(right_pos - left_pos, 2),
984
+ stringsAsFactors = FALSE
985
+ )
986
+ }
987
+ }
988
+ if (length(rows) == 0) return(data.frame())
989
+ dplyr::bind_rows(rows) %>% dplyr::arrange(Chr, Peak_pos_cM)
990
+ }
991
+
992
+ # ── Stat chips ──────────────────────────────────────────────────────────────
993
+ output$stat_markers <- renderUI({
994
+ cross <- cross_data(); req(cross)
995
+ div(class = "stat-chip blue", paste0(totmar(cross), " MARKERS"))
996
+ })
997
+ output$stat_inds <- renderUI({
998
+ cross <- cross_data(); req(cross)
999
+ div(class = "stat-chip orange", paste0(nind(cross), " INDIVIDUALS"))
1000
+ })
1001
+ output$stat_chrs <- renderUI({
1002
+ cross <- cross_data(); req(cross)
1003
+ div(class = "stat-chip green", paste0(nchr(cross), " CHROMOSOMES"))
1004
+ })
1005
+ output$stat_qtls <- renderUI({
1006
+ res <- analysis_results()
1007
+ n <- if (!is.null(res) && !is.null(res$qtl_table)) nrow(res$qtl_table) else 0
1008
+ div(class = "stat-chip pink", paste0(n, " QTLs FOUND"))
1009
+ })
1010
+
1011
+ output$status_text <- renderText("Ready β€” load data and run")
1012
+
1013
+ # ── PLOT: genome map ─────────────────────────────────────────────────────────
1014
+ output$plot_genome_map <- renderPlot({
1015
+ cross <- cross_data(); req(cross)
1016
+ map <- pull.map(cross)
1017
+ df <- do.call(rbind, lapply(names(map), function(ch) {
1018
+ data.frame(chr = ch, pos = unname(map[[ch]]), stringsAsFactors = FALSE)
1019
+ }))
1020
+ df$chr <- factor(df$chr, levels = names(map))
1021
+
1022
+ ggplot(df, aes(x = chr, y = pos)) +
1023
+ geom_segment(aes(xend = chr, yend = pos), color = "#1e2d40", linewidth = 8) +
1024
+ geom_point(color = "#00d4ff", size = 1.2, alpha = .7) +
1025
+ scale_y_reverse() +
1026
+ labs(title = "Genetic Map", x = "Chromosome", y = "Position (cM)") +
1027
+ theme_qtl()
1028
+ }, bg = "transparent")
1029
+
1030
+ # ── PLOT: phenotype distribution ─────────────────────────────────────────────
1031
+ output$plot_pheno_dist <- renderPlot({
1032
+ cross <- cross_data(); req(cross)
1033
+ req(input$pheno_col)
1034
+ ph <- cross$pheno[[input$pheno_col]]
1035
+ df <- data.frame(value = ph[!is.na(ph)])
1036
+
1037
+ p1 <- ggplot(df, aes(value)) +
1038
+ geom_histogram(fill = "#ff6b35", color = "#0a0e1a", bins = 30, alpha = .85) +
1039
+ geom_density(aes(y = after_stat(count)), color = "#00d4ff", linewidth = 1) +
1040
+ labs(title = input$pheno_col, x = "Value", y = "Count") +
1041
+ theme_qtl()
1042
+
1043
+ p2 <- ggplot(df, aes(sample = value)) +
1044
+ stat_qq(color = "#7cfc00", size = 1.5, alpha = .7) +
1045
+ stat_qq_line(color = "#ff3e8a", linewidth = .8) +
1046
+ labs(title = "Q-Q Plot", x = "Theoretical", y = "Sample") +
1047
+ theme_qtl()
1048
+
1049
+ gridExtra::grid.arrange(p1, p2, ncol = 2)
1050
+ }, bg = "transparent")
1051
+
1052
+ # ── PLOT: physical map strip ─────────────────────────────────────────────────
1053
+ output$plot_physical_map <- renderPlot({
1054
+ cross <- cross_data(); req(cross)
1055
+ map <- pull.map(cross)
1056
+ df <- do.call(rbind, lapply(names(map), function(ch) {
1057
+ data.frame(chr = ch, pos = unname(map[[ch]]), stringsAsFactors = FALSE)
1058
+ }))
1059
+ chr_len <- df %>% group_by(chr) %>% summarise(len = max(pos))
1060
+ chr_len$chr <- factor(chr_len$chr, levels = names(map))
1061
+
1062
+ ggplot() +
1063
+ geom_rect(data = chr_len,
1064
+ aes(xmin = as.numeric(chr) - .35, xmax = as.numeric(chr) + .35,
1065
+ ymin = 0, ymax = len),
1066
+ fill = "#1e2d40", color = "#2d3f55", linewidth = .6) +
1067
+ geom_point(data = df %>% mutate(chr = factor(chr, levels = names(map))),
1068
+ aes(x = as.numeric(chr), y = pos),
1069
+ color = "#00d4ff", size = .8, alpha = .6) +
1070
+ scale_x_continuous(breaks = seq_along(names(map)), labels = names(map)) +
1071
+ scale_y_reverse() +
1072
+ labs(title = "Physical Map Overview", x = "Chromosome", y = "cM") +
1073
+ theme_qtl()
1074
+ }, bg = "transparent")
1075
+
1076
+ # ── PLOT: Manhattan ──────────────────────────────────────────────────────────
1077
+ output$plot_manhattan <- renderPlot({
1078
+ res <- analysis_results(); req(res)
1079
+ mdl <- input$manhattan_model; req(mdl)
1080
+ sc <- res$scan_results[[mdl]]; req(sc)
1081
+
1082
+ chrs <- unique(sc$chr)
1083
+ chr_offsets <- setNames(cumsum(c(0, sapply(chrs[-length(chrs)], function(ch) {
1084
+ max(sc[sc$chr == ch, "pos"])
1085
+ }))), chrs)
1086
+
1087
+ sc$global_pos <- sc$pos + chr_offsets[as.character(sc$chr)]
1088
+ sc$chr_num <- as.integer(factor(sc$chr, levels = chrs))
1089
+ sc$color <- ifelse(sc$chr_num %% 2 == 0, "#00d4ff", "#0099bb")
1090
+ sig <- sc[sc$lod >= res$lod_thr, ]
1091
+
1092
+ chr_mid <- tapply(sc$global_pos, sc$chr, mean)
1093
+
1094
+ ggplot(sc, aes(x = global_pos, y = lod)) +
1095
+ geom_point(aes(color = color), size = 1.2, alpha = .75) +
1096
+ scale_color_identity() +
1097
+ geom_point(data = sig, aes(x = global_pos, y = lod),
1098
+ color = "#ff3e8a", size = 2.5, shape = 18) +
1099
+ geom_hline(yintercept = res$lod_thr, color = "#ff6b35",
1100
+ linetype = "dashed", linewidth = .8) +
1101
+ annotate("text", x = max(sc$global_pos) * .98, y = res$lod_thr + .15,
1102
+ label = paste0("LOD = ", round(res$lod_thr, 2)),
1103
+ color = "#ff6b35", size = 3, hjust = 1, family = "mono") +
1104
+ scale_x_continuous(breaks = chr_mid, labels = names(chr_mid)) +
1105
+ labs(title = paste("Manhattan Plot β€”", toupper(mdl)),
1106
+ x = "Chromosome", y = "LOD Score") +
1107
+ theme_qtl() +
1108
+ theme(panel.grid.major.x = element_blank())
1109
+ }, bg = "transparent")
1110
+
1111
+ # ── PLOT: Interactive Manhattan ──────────────────────────────────────────────
1112
+ output$plot_manhattan_interactive <- renderPlotly({
1113
+ res <- analysis_results(); req(res)
1114
+ mdl <- input$manhattan_model; req(mdl)
1115
+ sc <- res$scan_results[[mdl]]; req(sc)
1116
+
1117
+ chrs <- unique(sc$chr)
1118
+ chr_offsets <- setNames(cumsum(c(0, sapply(chrs[-length(chrs)], function(ch)
1119
+ max(sc[sc$chr == ch, "pos"])))), chrs)
1120
+ sc$global_pos <- sc$pos + chr_offsets[as.character(sc$chr)]
1121
+ sc$sig <- sc$lod >= res$lod_thr
1122
+ sc$label <- paste0(rownames(sc), "<br>Chr:", sc$chr, " Pos:", round(sc$pos,1), " LOD:", round(sc$lod,2))
1123
+
1124
+ p <- plot_ly(sc, x = ~global_pos, y = ~lod,
1125
+ color = ~sig, colors = c("#00d4ff","#ff3e8a"),
1126
+ text = ~label, hovertemplate = "%{text}<extra></extra>",
1127
+ type = "scatter", mode = "markers",
1128
+ marker = list(size = 4, opacity = .8)) %>%
1129
+ add_lines(y = res$lod_thr,
1130
+ line = list(color = "#ff6b35", dash = "dash", width = 1.5),
1131
+ showlegend = FALSE, name = "Threshold") %>%
1132
+ layout(
1133
+ paper_bgcolor = "#111827",
1134
+ plot_bgcolor = "#0d1421",
1135
+ font = list(color = "#94a3b8", family = "monospace"),
1136
+ xaxis = list(title = "Position", gridcolor = "#1e2d40", color = "#64748b"),
1137
+ yaxis = list(title = "LOD Score", gridcolor = "#1e2d40", color = "#64748b"),
1138
+ legend = list(font = list(color = "#94a3b8")),
1139
+ margin = list(t = 10, b = 40, l = 50, r = 20)
1140
+ )
1141
+ p
1142
+ })
1143
+
1144
+ # ── PLOT: All models genome scan ─────────────────────────────────────────────
1145
+ output$plot_scan_all_models <- renderPlot({
1146
+ res <- analysis_results(); req(res)
1147
+ req(length(res$scan_results) > 0)
1148
+
1149
+ dfs <- lapply(names(res$scan_results), function(mdl) {
1150
+ sc <- res$scan_results[[mdl]]
1151
+ chrs <- unique(sc$chr)
1152
+ offsets <- setNames(cumsum(c(0, sapply(chrs[-length(chrs)], function(ch)
1153
+ max(sc[sc$chr == ch,"pos"])))), chrs)
1154
+ sc$global_pos <- sc$pos + offsets[as.character(sc$chr)]
1155
+ sc$model <- mdl; sc
1156
+ })
1157
+ df_all <- dplyr::bind_rows(dfs)
1158
+ df_all$model <- factor(df_all$model)
1159
+
1160
+ sc_ref <- res$scan_results[[1]]
1161
+ chrs <- unique(sc_ref$chr)
1162
+ offsets <- setNames(cumsum(c(0, sapply(chrs[-length(chrs)], function(ch)
1163
+ max(sc_ref[sc_ref$chr==ch,"pos"])))), chrs)
1164
+ vlines <- data.frame(x = offsets[-1])
1165
+
1166
+ ggplot(df_all, aes(x = global_pos, y = lod, color = model)) +
1167
+ geom_vline(data = vlines, aes(xintercept = x), color = "#1e2d40", linewidth = .5) +
1168
+ geom_line(linewidth = .6, alpha = .85) +
1169
+ geom_hline(yintercept = res$lod_thr, color = "#ff6b35",
1170
+ linetype = "dashed", linewidth = .7) +
1171
+ scale_color_manual(values = model_colors) +
1172
+ labs(title = "Genome Scan β€” All Models",
1173
+ x = "Genome Position (cM)", y = "LOD Score", color = "Model") +
1174
+ theme_qtl() +
1175
+ theme(legend.position = "right")
1176
+ }, bg = "transparent")
1177
+
1178
+ # ── PLOT: Chromosome grid ────────────────────────────────────────────────────
1179
+ output$plot_chr_grid <- renderPlot({
1180
+ res <- analysis_results(); req(res)
1181
+ mdl <- input$chr_plot_model; req(mdl)
1182
+ sc <- res$scan_results[[mdl]]; req(sc)
1183
+ qt <- res$qtl_table
1184
+
1185
+ chrs <- unique(sc$chr)
1186
+ n_chr <- length(chrs)
1187
+ n_cols <- min(6, n_chr)
1188
+ n_rows <- ceiling(n_chr / n_cols)
1189
+
1190
+ plots <- lapply(chrs, function(ch) {
1191
+ chr_sc <- sc[sc$chr == ch, ]
1192
+ p <- ggplot(chr_sc, aes(x = pos, y = lod)) +
1193
+ geom_line(color = "#00d4ff", linewidth = .9) +
1194
+ geom_hline(yintercept = res$lod_thr, color = "#ff6b35",
1195
+ linetype = "dashed", linewidth = .6) +
1196
+ scale_x_continuous(expand = c(.02,.02)) +
1197
+ scale_y_continuous(limits = c(0, max(sc$lod) * 1.1)) +
1198
+ labs(title = paste0("Chr ", ch), x = NULL, y = "LOD") +
1199
+ theme_qtl(base_size = 9) +
1200
+ theme(plot.title = element_text(size = 9, color = "#00d4ff"),
1201
+ axis.title.y = element_text(size = 7),
1202
+ plot.margin = margin(6, 8, 6, 8))
1203
+
1204
+ # label significant QTLs
1205
+ if (!is.null(qt) && nrow(qt) > 0) {
1206
+ qt_chr <- qt[qt$Chr == ch & qt$Model == mdl, ]
1207
+ if (nrow(qt_chr) > 0) {
1208
+ p <- p +
1209
+ geom_point(data = qt_chr,
1210
+ aes(x = Peak_pos_cM, y = LOD),
1211
+ color = "#ff3e8a", size = 3, shape = 23, fill = "#ff3e8a") +
1212
+ ggrepel::geom_label_repel(
1213
+ data = qt_chr,
1214
+ aes(x = Peak_pos_cM, y = LOD,
1215
+ label = paste0("q", toupper(substr(mdl,1,1)), "R", ch)),
1216
+ fill = "#0d1421", color = "#7cfc00",
1217
+ size = 2.5, label.padding = unit(.15,"lines"),
1218
+ min.segment.length = 0
1219
+ )
1220
+ }
1221
+ }
1222
+ p
1223
+ })
1224
+
1225
+ do.call(gridExtra::grid.arrange,
1226
+ c(plots, list(ncol = n_cols, nrow = n_rows)))
1227
+ }, bg = "transparent")
1228
+
1229
+ # ── PLOT: Model bar comparison ───────────────────────────────────────────────
1230
+ output$plot_model_bar <- renderPlot({
1231
+ res <- analysis_results(); req(res)
1232
+ df <- data.frame(
1233
+ model = names(res$scan_results),
1234
+ max_lod = sapply(res$scan_results, function(sc) max(sc$lod, na.rm = TRUE))
1235
+ )
1236
+ df$model <- factor(df$model, levels = df$model[order(df$max_lod)])
1237
+
1238
+ ggplot(df, aes(x = model, y = max_lod, fill = model)) +
1239
+ geom_col(width = .6, alpha = .85) +
1240
+ geom_hline(yintercept = res$lod_thr, color = "#ff6b35",
1241
+ linetype = "dashed", linewidth = .8) +
1242
+ geom_text(aes(label = round(max_lod, 2)), hjust = -0.2,
1243
+ color = "#e2e8f0", size = 3, family = "mono") +
1244
+ scale_fill_manual(values = model_colors) +
1245
+ coord_flip(ylim = c(0, max(df$max_lod) * 1.15)) +
1246
+ labs(title = "Peak LOD by Model", x = NULL, y = "Max LOD") +
1247
+ theme_qtl() + theme(legend.position = "none")
1248
+ }, bg = "transparent")
1249
+
1250
+ # ── PLOT: LOD heatmap ────────────────────────────────────────────────────────
1251
+ output$plot_lod_heatmap <- renderPlot({
1252
+ res <- analysis_results(); req(res)
1253
+
1254
+ # thin to top 50 markers by max LOD across models
1255
+ all_sc <- dplyr::bind_rows(lapply(names(res$scan_results), function(m) {
1256
+ sc <- res$scan_results[[m]]
1257
+ sc$model <- m; sc$marker <- rownames(sc); sc
1258
+ }))
1259
+ top_markers <- all_sc %>%
1260
+ group_by(marker) %>%
1261
+ summarise(max_lod = max(lod)) %>%
1262
+ arrange(desc(max_lod)) %>%
1263
+ slice_head(n = 40) %>%
1264
+ pull(marker)
1265
+
1266
+ hm <- all_sc %>%
1267
+ filter(marker %in% top_markers) %>%
1268
+ select(model, marker, lod)
1269
+
1270
+ ggplot(hm, aes(x = model, y = marker, fill = lod)) +
1271
+ geom_tile(color = "#0a0e1a", linewidth = .2) +
1272
+ scale_fill_gradientn(
1273
+ colors = c("#0d1421","#00d4ff","#7cfc00","#fbbf24","#ff3e8a"),
1274
+ name = "LOD"
1275
+ ) +
1276
+ labs(title = "LOD Heatmap", x = "Model", y = "Marker") +
1277
+ theme_qtl() +
1278
+ theme(axis.text.x = element_text(angle = 30, hjust = 1),
1279
+ axis.text.y = element_text(size = 6))
1280
+ }, bg = "transparent")
1281
+
1282
+ # ── PLOT: Model correlation ──────────────────────────────────────────────────
1283
+ output$plot_model_corr <- renderPlot({
1284
+ res <- analysis_results(); req(res)
1285
+ req(length(res$scan_results) >= 2)
1286
+
1287
+ # build wide LOD matrix
1288
+ sc_list <- lapply(names(res$scan_results), function(m) {
1289
+ sc <- res$scan_results[[m]]
1290
+ data.frame(marker = rownames(sc), lod = sc$lod, stringsAsFactors = FALSE)
1291
+ })
1292
+ names(sc_list) <- names(res$scan_results)
1293
+
1294
+ common_markers <- Reduce(intersect, lapply(sc_list, `[[`, "marker"))
1295
+ mat <- sapply(sc_list, function(sc) sc$lod[match(common_markers, sc$marker)])
1296
+ corr_mat <- cor(mat, use = "complete.obs")
1297
+
1298
+ corr_df <- as.data.frame(as.table(corr_mat))
1299
+ names(corr_df) <- c("m1","m2","corr")
1300
+
1301
+ ggplot(corr_df, aes(x = m1, y = m2, fill = corr)) +
1302
+ geom_tile(color = "#0a0e1a") +
1303
+ geom_text(aes(label = round(corr, 2)), size = 3, color = "#e2e8f0", family = "mono") +
1304
+ scale_fill_gradient2(low = "#ff3e8a", mid = "#1e2d40", high = "#00d4ff",
1305
+ midpoint = 0, limits = c(-1,1), name = "r") +
1306
+ labs(title = "Model LOD Correlation", x = NULL, y = NULL) +
1307
+ theme_qtl() +
1308
+ theme(axis.text.x = element_text(angle = 30, hjust = 1))
1309
+ }, bg = "transparent")
1310
+
1311
+ # ── PLOT: Effects ────────────────────────────────────────────────────────────
1312
+ output$plot_effects <- renderPlot({
1313
+ res <- analysis_results(); req(res)
1314
+ qtl_sel <- input$effect_qtl; req(qtl_sel)
1315
+ req(qtl_sel != "none")
1316
+
1317
+ parts <- strsplit(qtl_sel, "@")[[1]]
1318
+ ch <- parts[1]; mk <- parts[2]
1319
+
1320
+ tryCatch({
1321
+ eff <- effectplot(res$cross, mname1 = mk,
1322
+ pheno.col = res$pheno_idx, draw = FALSE)
1323
+ df <- data.frame(geno = names(eff$Means), mean = eff$Means, se = eff$SEs)
1324
+ ggplot(df, aes(x = geno, y = mean, fill = geno)) +
1325
+ geom_col(width = .5, alpha = .8) +
1326
+ geom_errorbar(aes(ymin = mean - se, ymax = mean + se),
1327
+ width = .15, color = "#e2e8f0", linewidth = .8) +
1328
+ scale_fill_manual(values = c("#00d4ff","#ff3e8a","#7cfc00")) +
1329
+ labs(title = paste("Effect Plot β€”", mk),
1330
+ x = "Genotype", y = "Mean Phenotype") +
1331
+ theme_qtl() + theme(legend.position = "none")
1332
+ }, error = function(e) {
1333
+ ggplot() + annotate("text", x=.5, y=.5, label="Effect not available",
1334
+ color="#64748b") + theme_qtl()
1335
+ })
1336
+ }, bg = "transparent")
1337
+
1338
+ # ── PLOT: Phenotype Γ— genotype boxplot ───────────────────────────────────────
1339
+ output$plot_pheno_geno <- renderPlot({
1340
+ res <- analysis_results(); req(res)
1341
+ qtl_sel <- input$effect_qtl; req(qtl_sel != "none")
1342
+
1343
+ parts <- strsplit(qtl_sel, "@")[[1]]; mk <- parts[2]
1344
+ tryCatch({
1345
+ geno_idx <- find.markerindex(res$cross, mk)
1346
+ geno_vec <- pull.geno(res$cross)[, geno_idx]
1347
+ pheno_vec <- res$cross$pheno[[res$pheno_idx]]
1348
+ df <- data.frame(geno = as.character(geno_vec), pheno = pheno_vec) %>% filter(!is.na(geno), !is.na(pheno))
1349
+ geno_labs <- c("1" = "AA", "2" = "AB", "3" = "BB")
1350
+ df$geno <- dplyr::recode(df$geno, !!!geno_labs)
1351
+
1352
+ ggplot(df, aes(x = geno, y = pheno, fill = geno)) +
1353
+ geom_violin(alpha = .4, trim = FALSE) +
1354
+ geom_boxplot(width = .15, outlier.color = "#ff3e8a", alpha = .7) +
1355
+ scale_fill_manual(values = c("#00d4ff","#ff6b35","#7cfc00")) +
1356
+ labs(title = paste("Phenotype by Genotype β€”", mk),
1357
+ x = "Genotype", y = input$pheno_col) +
1358
+ theme_qtl() + theme(legend.position = "none")
1359
+ }, error = function(e) {
1360
+ ggplot() + annotate("text", x=.5, y=.5, label = "Unavailable", color="#64748b") + theme_qtl()
1361
+ })
1362
+ }, bg = "transparent")
1363
+
1364
+ # ── PLOT: PVE ────────────────────────────────────────────────────────────────
1365
+ output$plot_pve <- renderPlot({
1366
+ res <- analysis_results(); req(res)
1367
+ qt <- res$qtl_table; req(!is.null(qt) && nrow(qt) > 0)
1368
+
1369
+ qt_avg <- qt %>%
1370
+ group_by(Chr, Peak_pos_cM) %>%
1371
+ summarise(PVE = mean(PVE_pct, na.rm = TRUE),
1372
+ LOD = mean(LOD, na.rm=TRUE), .groups = "drop")
1373
+
1374
+ ggplot(qt_avg, aes(x = interaction(Chr, round(Peak_pos_cM)), y = PVE, fill = PVE)) +
1375
+ geom_col(width = .7) +
1376
+ scale_fill_gradientn(colors = c("#00d4ff","#7cfc00","#fbbf24","#ff3e8a"), name = "PVE%") +
1377
+ geom_text(aes(label = paste0(round(PVE,1),"%")), vjust = -0.4, size = 3,
1378
+ color = "#e2e8f0", family = "mono") +
1379
+ labs(title = "PVE per QTL", x = "Chr @ Position", y = "PVE (%)") +
1380
+ theme_qtl() +
1381
+ theme(axis.text.x = element_text(angle = 40, hjust = 1))
1382
+ }, bg = "transparent")
1383
+
1384
+ # ── PLOT: 2D scan ────────────────────────────────────────────────────────────
1385
+ output$plot_2d_scan <- renderPlot({
1386
+ res <- analysis_results(); req(res)
1387
+
1388
+ sc2 <- tryCatch(
1389
+ scantwo(res$cross, pheno.col = res$pheno_idx, method = "hk", verbose = FALSE),
1390
+ error = function(e) NULL
1391
+ )
1392
+ if (is.null(sc2)) {
1393
+ ggplot() + annotate("text", x=.5, y=.5, label = "2D scan failed or insufficient data",
1394
+ color = "#64748b", size=5) + theme_qtl()
1395
+ } else {
1396
+ # Extract the full 2D LOD matrix
1397
+ lod_mat <- sc2$lod
1398
+ n <- nrow(lod_mat)
1399
+ df2d <- expand.grid(x = 1:n, y = 1:n)
1400
+ df2d$lod <- as.vector(lod_mat)
1401
+
1402
+ ggplot(df2d, aes(x=x, y=y, fill=lod)) +
1403
+ geom_tile() +
1404
+ scale_fill_gradientn(
1405
+ colors = c("#0d1421","#00d4ff","#7cfc00","#fbbf24","#ff3e8a"),
1406
+ name = "LOD", na.value = "#0d1421"
1407
+ ) +
1408
+ labs(title = "2D Genome Scan (Pairwise)", x = "Position 1", y = "Position 2") +
1409
+ theme_qtl() + coord_equal()
1410
+ }
1411
+ }, bg = "transparent")
1412
+
1413
+ # ── PLOT: missing data ───────────────────────────────────────────────────────
1414
+ output$plot_missing <- renderPlot({
1415
+ cross <- cross_data(); req(cross)
1416
+ miss <- nmissing(cross, what = "mar")
1417
+ df <- data.frame(marker = names(miss), missing = miss)
1418
+
1419
+ ggplot(df, aes(x = reorder(marker, missing), y = missing, fill = missing)) +
1420
+ geom_col() +
1421
+ scale_fill_gradientn(colors = c("#00d4ff","#7cfc00","#ff3e8a"), guide = "none") +
1422
+ labs(title = "Missing Genotype Data", x = "Marker", y = "# Missing") +
1423
+ theme_qtl() +
1424
+ theme(axis.text.x = element_blank(), axis.ticks.x = element_blank())
1425
+ }, bg = "transparent")
1426
+
1427
+ # ── PLOT: genotype frequency ─────────────────────────────────────────────────
1428
+ output$plot_geno_freq <- renderPlot({
1429
+ cross <- cross_data(); req(cross)
1430
+ gt <- pull.geno(cross)
1431
+ freq_A <- colMeans(gt == 1, na.rm = TRUE)
1432
+ freq_B <- colMeans(gt == 2, na.rm = TRUE)
1433
+ df <- data.frame(
1434
+ marker = names(freq_A),
1435
+ A = freq_A, B = freq_B
1436
+ ) %>% tidyr::pivot_longer(cols = c(A, B), names_to = "allele", values_to = "freq")
1437
+
1438
+ ggplot(df, aes(x = marker, y = freq, fill = allele)) +
1439
+ geom_col(position = "stack", width = 1) +
1440
+ scale_fill_manual(values = c(A = "#00d4ff", B = "#ff6b35")) +
1441
+ labs(title = "Allele Frequency per Marker", x = "Marker", y = "Frequency") +
1442
+ theme_qtl() +
1443
+ theme(axis.text.x = element_blank(), axis.ticks.x = element_blank())
1444
+ }, bg = "transparent")
1445
+
1446
+ # ── PLOT: marker distance ────────────────────────────────────────────────────
1447
+ output$plot_marker_dist <- renderPlot({
1448
+ cross <- cross_data(); req(cross)
1449
+ map <- pull.map(cross)
1450
+ diffs <- unlist(lapply(map, function(m) {
1451
+ if (length(m) > 1) diff(m) else numeric(0)
1452
+ }))
1453
+ df <- data.frame(dist = diffs)
1454
+
1455
+ ggplot(df, aes(x = dist)) +
1456
+ geom_histogram(fill = "#7cfc00", color = "#0a0e1a", bins = 40, alpha = .8) +
1457
+ geom_vline(xintercept = median(diffs), color = "#ff3e8a",
1458
+ linetype = "dashed", linewidth = .8) +
1459
+ labs(title = "Inter-Marker Distance",
1460
+ subtitle = paste0("Median: ", round(median(diffs),1), " cM"),
1461
+ x = "Distance (cM)", y = "Count") +
1462
+ theme_qtl()
1463
+ }, bg = "transparent")
1464
+
1465
+ # ── TABLE: QTL results ───────────────────────────────────────────────────────
1466
+ output$table_qtl_results <- renderDT({
1467
+ res <- analysis_results(); req(res)
1468
+ qt <- res$qtl_table
1469
+ req(!is.null(qt) && nrow(qt) > 0)
1470
+
1471
+ datatable(qt,
1472
+ rownames = FALSE,
1473
+ options = list(
1474
+ pageLength = 20,
1475
+ scrollX = TRUE,
1476
+ dom = "Blfrtip",
1477
+ columnDefs = list(list(className = "dt-center", targets = "_all"))
1478
+ ),
1479
+ class = "display nowrap"
1480
+ ) %>%
1481
+ formatStyle("LOD",
1482
+ background = styleColorBar(range(qt$LOD), "#00d4ff"),
1483
+ backgroundSize = "100% 80%", backgroundRepeat = "no-repeat", backgroundPosition = "center"
1484
+ ) %>%
1485
+ formatStyle("PVE_pct",
1486
+ background = styleColorBar(c(0,100), "#7cfc00"),
1487
+ backgroundSize = "100% 80%", backgroundRepeat = "no-repeat", backgroundPosition = "center"
1488
+ ) %>%
1489
+ formatStyle(0, color = "#e2e8f0") %>%
1490
+ formatRound(c("Peak_pos_cM","LOD","PVE_pct","Left_pos_cM","Right_pos_cM","CI_width_cM"), 3)
1491
+ })
1492
+
1493
+ # ── TABLE: Model summary ─────────────────────────────────────────────────────
1494
+ output$table_model_summary <- renderDT({
1495
+ res <- analysis_results(); req(res)
1496
+ df <- data.frame(
1497
+ Model = names(res$scan_results),
1498
+ Max_LOD = round(sapply(res$scan_results, function(sc) max(sc$lod, na.rm=TRUE)), 3),
1499
+ Mean_LOD = round(sapply(res$scan_results, function(sc) mean(sc$lod, na.rm=TRUE)), 3),
1500
+ QTLs_Found = sapply(names(res$scan_results), function(m) {
1501
+ if (!is.null(res$qtl_table) && nrow(res$qtl_table) > 0)
1502
+ sum(res$qtl_table$Model == m) else 0
1503
+ }),
1504
+ Threshold = round(res$lod_thr, 3)
1505
+ )
1506
+ datatable(df, rownames = FALSE,
1507
+ options = list(dom = "t", pageLength = 15),
1508
+ class = "display") %>%
1509
+ formatStyle(0, color = "#e2e8f0") %>%
1510
+ formatStyle("Max_LOD", color = "#00d4ff") %>%
1511
+ formatStyle("QTLs_Found", color = "#ff3e8a")
1512
+ })
1513
+
1514
+ # ── TABLE: Permutation thresholds ───────────────────────────────────────────
1515
+ output$table_perm_thresholds <- renderDT({
1516
+ res <- analysis_results(); req(res)
1517
+ req(length(res$perm_results) > 0)
1518
+
1519
+ rows <- lapply(names(res$perm_results), function(m) {
1520
+ p <- res$perm_results[[m]]
1521
+ if (is.null(p)) return(NULL)
1522
+ sm <- tryCatch(summary(p, alpha = c(0.05, 0.1, 0.2)), error = function(e) NULL)
1523
+ if (is.null(sm)) return(NULL)
1524
+ data.frame(Model = m,
1525
+ alpha_0.05 = round(sm[1], 3),
1526
+ alpha_0.10 = round(sm[2], 3),
1527
+ alpha_0.20 = round(sm[3], 3))
1528
+ })
1529
+ df <- dplyr::bind_rows(Filter(Negate(is.null), rows))
1530
+ req(nrow(df) > 0)
1531
+ datatable(df, rownames = FALSE, options = list(dom = "t"), class = "display") %>%
1532
+ formatStyle(0, color = "#e2e8f0")
1533
+ })
1534
 
1535
+ # ── Download CSV ─────────────────────────────────────────────────────────────
1536
+ output$download_results <- downloadHandler(
1537
+ filename = function() paste0("qtl_results_", Sys.Date(), ".csv"),
1538
+ content = function(file) {
1539
+ res <- analysis_results()
1540
+ if (!is.null(res) && !is.null(res$qtl_table) && nrow(res$qtl_table) > 0)
1541
+ write.csv(res$qtl_table, file, row.names = FALSE)
1542
+ else
1543
+ write.csv(data.frame(message = "No significant QTLs found"), file, row.names = FALSE)
1544
+ }
 
 
 
 
1545
  )
 
 
 
 
 
 
 
 
1546
  }
1547
 
1548
+ shinyApp(ui = ui, server = server)