softwareDevelopment commited on
Commit
db1d3d8
Β·
verified Β·
1 Parent(s): 212274a

Update app.R

Browse files
Files changed (1) hide show
  1. app.R +514 -776
app.R CHANGED
@@ -12,6 +12,228 @@ library(grid)
12
  library(gridExtra)
13
  library(scales)
14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
  # ─── UI ───────────────────────────────────────────────────────────────────────
16
  ui <- fluidPage(
17
  useShinyjs(),
@@ -39,441 +261,137 @@ ui <- fluidPage(
39
  --shadow: 0 1px 4px rgba(0,0,0,0.07), 0 4px 16px rgba(0,0,0,0.05);
40
  --shadow-lg: 0 2px 8px rgba(0,0,0,0.08), 0 8px 32px rgba(0,0,0,0.07);
41
  }
42
-
43
  * { box-sizing: border-box; margin: 0; padding: 0; }
44
-
45
  body {
46
- background: var(--bg);
47
- color: var(--text);
48
- font-family: var(--font-body);
49
- min-height: 100vh;
50
- font-size: 14px;
51
  }
52
-
53
- /* ── Header ── */
54
  .qtl-header {
55
- background: #ffffff;
56
- border-bottom: 1.5px solid var(--border);
57
- padding: 0 32px;
58
- height: 60px;
59
- display: flex;
60
- align-items: center;
61
- gap: 16px;
62
- position: sticky;
63
- top: 0;
64
- z-index: 100;
65
  box-shadow: 0 1px 6px rgba(0,0,0,0.06);
66
  }
67
  .qtl-header .logo-mark {
68
- width: 36px; height: 36px;
69
- background: var(--accent1);
70
- border-radius: 8px;
71
  display: flex; align-items: center; justify-content: center;
72
- font-family: var(--font-mono);
73
- font-weight: 600;
74
- font-size: 13px;
75
- color: #ffffff;
76
- flex-shrink: 0;
77
- letter-spacing: -0.5px;
78
- }
79
- .qtl-header h1 {
80
- font-family: var(--font-mono);
81
- font-size: 15px;
82
- color: var(--text);
83
- letter-spacing: 1px;
84
- font-weight: 600;
85
- }
86
- .qtl-header .subtitle {
87
- font-size: 11px;
88
- color: var(--muted);
89
- letter-spacing: 0.3px;
90
- margin-top: 1px;
91
- }
92
- .header-badges {
93
- margin-left: auto;
94
- display: flex; gap: 6px;
95
- }
96
- .badge-pill {
97
- padding: 3px 10px;
98
- border-radius: 100px;
99
- font-size: 10px;
100
- font-family: var(--font-mono);
101
- letter-spacing: 0.5px;
102
- border: 1px solid;
103
- font-weight: 600;
104
  }
 
 
 
 
105
  .badge-pill.blue { color: var(--accent1); border-color: #bcd0fc; background: #eef3fe; }
106
  .badge-pill.green { color: var(--accent3); border-color: #b3dfc7; background: #edf7f2; }
107
  .badge-pill.orange { color: var(--accent2); border-color: #f8c4a8; background: #fef4ee; }
108
-
109
- /* ── Layout ── */
110
- .qtl-layout {
111
- display: grid;
112
- grid-template-columns: 272px 1fr;
113
- height: calc(100vh - 60px);
114
- }
115
-
116
- /* ── Sidebar ── */
117
- .qtl-sidebar {
118
- background: var(--panel);
119
- border-right: 1.5px solid var(--border);
120
- overflow-y: auto;
121
- padding: 20px 16px 32px;
122
- }
123
  .qtl-sidebar::-webkit-scrollbar { width: 4px; }
124
  .qtl-sidebar::-webkit-scrollbar-thumb { background: var(--border); border-radius: 4px; }
125
-
126
  .section-label {
127
- font-family: var(--font-mono);
128
- font-size: 9px;
129
- letter-spacing: 2.5px;
130
- color: var(--muted);
131
- text-transform: uppercase;
132
- margin-bottom: 10px;
133
- margin-top: 22px;
134
- padding-left: 2px;
135
- display: flex;
136
- align-items: center;
137
- gap: 8px;
138
- }
139
- .section-label::after {
140
- content: '';
141
- flex: 1;
142
- height: 1px;
143
- background: var(--border);
144
  }
 
145
  .section-label:first-child { margin-top: 0; }
146
-
147
- /* file upload */
148
  .qtl-upload {
149
- border: 1.5px dashed var(--border);
150
- border-radius: 8px;
151
- padding: 12px;
152
- transition: border-color .2s, background .2s;
153
- background: #ffffff;
154
- margin-bottom: 8px;
155
  }
156
  .qtl-upload:hover { border-color: var(--accent1); background: #f5f8ff; }
157
- .qtl-upload label {
158
- font-size: 10px;
159
- color: var(--accent1);
160
- font-family: var(--font-mono);
161
- letter-spacing: 1px;
162
- margin-bottom: 5px;
163
- display: block;
164
- font-weight: 600;
165
- }
166
  .qtl-upload .shiny-input-container { margin: 0 !important; }
167
-
168
- /* ── Required file notice ── */
169
- .required-notice {
170
- background: #fff8e1;
171
- border: 1px solid #f5c842;
172
- border-radius: 6px;
173
- padding: 8px 11px;
174
- font-size: 11px;
175
- color: #7a5800;
176
- font-family: var(--font-mono);
177
- line-height: 1.5;
178
- margin-bottom: 10px;
179
- }
180
-
181
- /* controls */
182
  .control-block { margin-bottom: 11px; }
183
- .control-block label {
184
- font-size: 10px;
185
- color: var(--text2);
186
- letter-spacing: 0.8px;
187
- font-family: var(--font-mono);
188
- text-transform: uppercase;
189
- display: block;
190
- margin-bottom: 4px;
191
- font-weight: 600;
192
- }
193
- select, input[type='number'], input[type='text'] {
194
- width: 100%;
195
- background: #ffffff;
196
- border: 1.5px solid var(--border);
197
- border-radius: 6px;
198
- color: var(--text);
199
- padding: 7px 10px;
200
- font-size: 12px;
201
- font-family: var(--font-body);
202
- outline: none;
203
- transition: border-color .2s;
204
- appearance: none;
205
- }
206
  select:focus, input:focus { border-color: var(--accent1); box-shadow: 0 0 0 3px rgba(26,108,245,0.1); }
207
-
208
- .shiny-input-checkboxgroup .checkbox label {
209
- font-size: 11px;
210
- color: var(--text2);
211
- display: flex;
212
- align-items: center;
213
- gap: 6px;
214
- }
215
-
216
- /* buttons */
217
- .btn-run {
218
- width: 100%;
219
- padding: 11px;
220
- background: var(--accent1);
221
- border: none;
222
- border-radius: 8px;
223
- color: #ffffff;
224
- font-family: var(--font-mono);
225
- font-size: 12px;
226
- font-weight: 600;
227
- letter-spacing: 1.5px;
228
- cursor: pointer;
229
- transition: background .2s, transform .1s, box-shadow .2s;
230
- margin-top: 16px;
231
- box-shadow: 0 2px 8px rgba(26,108,245,0.25);
232
- }
233
  .btn-run:hover { background: #1558d4; transform: translateY(-1px); box-shadow: 0 4px 14px rgba(26,108,245,0.3); }
234
  .btn-run:active { transform: translateY(0); }
235
- .btn-run:disabled { background: var(--muted); cursor: not-allowed; box-shadow: none; }
236
-
237
- .btn-export {
238
- width: 100%;
239
- padding: 9px;
240
- background: #ffffff;
241
- border: 1.5px solid var(--accent3);
242
- border-radius: 8px;
243
- color: var(--accent3);
244
- font-family: var(--font-mono);
245
- font-size: 11px;
246
- font-weight: 600;
247
- letter-spacing: 1px;
248
- cursor: pointer;
249
- margin-top: 8px;
250
- transition: background .2s;
251
- }
252
  .btn-export:hover { background: #edf7f2; }
253
-
254
- /* status */
255
- .status-row {
256
- display: flex;
257
- align-items: center;
258
- gap: 8px;
259
- padding: 8px 10px;
260
- background: #ffffff;
261
- border: 1.5px solid var(--border);
262
- border-radius: 6px;
263
- margin-top: 12px;
264
- font-size: 11px;
265
- color: var(--muted);
266
- font-family: var(--font-mono);
267
- }
268
- .status-dot {
269
- width: 7px; height: 7px;
270
- border-radius: 50%;
271
- background: var(--muted);
272
- flex-shrink: 0;
273
- }
274
  .status-dot.active { background: var(--accent3); box-shadow: 0 0 5px rgba(24,160,88,0.5); }
275
  .status-dot.error { background: var(--accent2); box-shadow: 0 0 5px rgba(232,80,10,0.5); }
276
-
277
- /* ── Main content ── */
278
- .qtl-main {
279
- overflow-y: auto;
280
- background: var(--bg);
281
- }
282
  .qtl-main::-webkit-scrollbar { width: 6px; }
283
  .qtl-main::-webkit-scrollbar-thumb { background: var(--border); border-radius: 4px; }
284
-
285
- /* tabs */
286
- .qtl-tabs {
287
- display: flex;
288
- gap: 0;
289
- padding: 0 24px;
290
- border-bottom: 1.5px solid var(--border);
291
- background: #ffffff;
292
- position: sticky;
293
- top: 0;
294
- z-index: 50;
295
- overflow-x: auto;
296
- box-shadow: 0 1px 4px rgba(0,0,0,0.04);
297
- }
298
  .qtl-tabs::-webkit-scrollbar { display: none; }
299
- .qtl-tab-btn {
300
- padding: 14px 16px;
301
- border: none;
302
- background: transparent;
303
- color: var(--muted);
304
- font-family: var(--font-mono);
305
- font-size: 10px;
306
- letter-spacing: 1px;
307
- text-transform: uppercase;
308
- cursor: pointer;
309
- border-bottom: 2.5px solid transparent;
310
- transition: color .2s, border-color .2s;
311
- white-space: nowrap;
312
- font-weight: 600;
313
- margin-bottom: -1.5px;
314
- }
315
  .qtl-tab-btn:hover { color: var(--text); }
316
  .qtl-tab-btn.active { color: var(--accent1); border-bottom-color: var(--accent1); }
317
-
318
- /* content panels */
319
  .tab-content { display: none; padding: 24px; }
320
  .tab-content.active { display: block; }
321
-
322
- /* cards */
323
- .plot-card {
324
- background: #ffffff;
325
- border: 1.5px solid var(--border);
326
- border-radius: 12px;
327
- overflow: hidden;
328
- margin-bottom: 20px;
329
- box-shadow: var(--shadow);
330
- }
331
- .plot-card-header {
332
- display: flex;
333
- align-items: center;
334
- padding: 13px 18px;
335
- border-bottom: 1px solid var(--border);
336
- background: var(--panel);
337
- gap: 10px;
338
- }
339
- .plot-card-icon {
340
- width: 28px; height: 28px;
341
- border-radius: 6px;
342
- display: flex; align-items: center; justify-content: center;
343
- font-size: 13px;
344
- flex-shrink: 0;
345
- }
346
  .plot-card-icon.blue { background: #eef3fe; }
347
  .plot-card-icon.orange { background: #fef4ee; }
348
  .plot-card-icon.green { background: #edf7f2; }
349
  .plot-card-icon.pink { background: #fce8f1; }
350
  .plot-card-icon.purple { background: #f3effe; }
351
- .plot-card-title {
352
- font-family: var(--font-mono);
353
- font-size: 12px;
354
- color: var(--text);
355
- letter-spacing: 0.8px;
356
- font-weight: 600;
357
- }
358
  .plot-card-subtitle { font-size: 10px; color: var(--muted); margin-top: 1px; }
359
  .plot-card-body { padding: 16px; }
360
-
361
- /* stat chips */
362
- .stat-row {
363
- display: flex;
364
- gap: 10px;
365
- flex-wrap: wrap;
366
- margin-bottom: 20px;
367
- }
368
- .stat-chip {
369
- padding: 10px 18px;
370
- border-radius: 10px;
371
- font-family: var(--font-mono);
372
- font-size: 12px;
373
- border: 1.5px solid;
374
- font-weight: 600;
375
- box-shadow: var(--shadow);
376
- }
377
  .stat-chip.blue { background: #eef3fe; color: var(--accent1); border-color: #bcd0fc; }
378
  .stat-chip.orange { background: #fef4ee; color: var(--accent2); border-color: #f8c4a8; }
379
  .stat-chip.green { background: #edf7f2; color: var(--accent3); border-color: #b3dfc7; }
380
  .stat-chip.pink { background: #fce8f1; color: var(--accent4); border-color: #f0a8c8; }
381
-
382
- /* grids */
383
  .grid-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; }
384
  .grid-3 { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 20px; }
385
  @media (max-width: 1100px) { .grid-3 { grid-template-columns: 1fr 1fr; } }
386
  @media (max-width: 800px) { .grid-2, .grid-3 { grid-template-columns: 1fr; } }
387
-
388
- /* empty state */
389
- .empty-state {
390
- text-align: center;
391
- padding: 60px 24px;
392
- color: var(--muted);
393
- }
394
  .empty-state .empty-icon { font-size: 48px; margin-bottom: 16px; }
395
  .empty-state h3 { font-size: 16px; color: var(--text2); margin-bottom: 8px; font-family: var(--font-mono); }
396
  .empty-state p { font-size: 13px; line-height: 1.6; max-width: 400px; margin: 0 auto; }
397
-
398
- /* DataTable */
399
  .dataTables_wrapper { color: var(--text) !important; font-size: 12px; }
400
  table.dataTable { background: transparent !important; color: var(--text) !important; border-collapse: collapse !important; }
401
- table.dataTable thead th {
402
- background: var(--panel) !important;
403
- color: var(--accent1) !important;
404
- font-family: var(--font-mono) !important;
405
- font-size: 10px !important;
406
- letter-spacing: 1px !important;
407
- border-bottom: 1.5px solid var(--border) !important;
408
- padding: 10px 12px !important;
409
- font-weight: 600 !important;
410
- }
411
  table.dataTable tbody tr { background: transparent !important; }
412
  table.dataTable tbody tr:hover td { background: #f5f8ff !important; }
413
  table.dataTable tbody td { border-bottom: 1px solid var(--border) !important; padding: 8px 12px !important; color: var(--text) !important; }
414
  .dataTables_info, .dataTables_paginate { color: var(--muted) !important; font-size: 11px !important; }
415
  .paginate_button { color: var(--text2) !important; }
416
  .paginate_button.current { background: var(--accent1) !important; color: #ffffff !important; border-radius: 4px !important; }
417
- .dataTables_filter input, .dataTables_length select {
418
- background: #ffffff !important;
419
- border: 1.5px solid var(--border) !important;
420
- color: var(--text) !important;
421
- border-radius: 4px !important;
422
- padding: 4px 8px !important;
423
- }
424
-
425
- .info-box {
426
- background: #f0f5ff;
427
- border: 1px solid #bcd0fc;
428
- border-radius: 8px;
429
- padding: 12px 16px;
430
- font-size: 12px;
431
- color: var(--text2);
432
- line-height: 1.6;
433
- margin-bottom: 16px;
434
- }
435
-
436
  hr.divider { border: none; border-top: 1px solid var(--border); margin: 20px 0; }
437
-
438
- /* file format help */
439
- .format-help {
440
- font-size: 10px;
441
- color: var(--muted);
442
- font-family: var(--font-mono);
443
- line-height: 1.6;
444
- margin-top: 4px;
445
- padding: 6px 8px;
446
- background: var(--panel2);
447
- border-radius: 4px;
448
- }
449
  "))
450
  ),
451
 
452
- # ── Header ──────────────────────────────────────────────────────────────────
453
  div(class = "qtl-header",
454
  div(class = "logo-mark", "QTL"),
455
- div(
456
- tags$h1("QTL Mapper Pro"),
457
- div(class = "subtitle", "Quantitative Trait Loci Analysis Pipeline")
458
- ),
459
  div(class = "header-badges",
460
  div(class = "badge-pill blue", "R/QTL ENGINE"),
461
  div(class = "badge-pill green", "10+ MODELS"),
462
- div(class = "badge-pill orange","MULTI-TRAIT")
463
- )
464
  ),
465
 
466
- # ── Main layout ─────────────────────────────────────────────────────────────
467
  div(class = "qtl-layout",
468
 
469
- # ── Sidebar ───────────────────────────────────────────────────────────────
470
  div(class = "qtl-sidebar",
471
 
472
  div(class = "section-label", "Data Input"),
473
 
474
  div(class = "required-notice",
475
- "⚠ Both CSV files are required.", tags$br(),
476
- "No example/simulated data is used."
 
477
  ),
478
 
479
  div(class = "qtl-upload",
@@ -481,10 +399,10 @@ ui <- fluidPage(
481
  fileInput("geno_file", NULL, accept = ".csv",
482
  buttonLabel = "Browse", placeholder = "genotypes.csv"),
483
  div(class = "format-help",
484
- "Row 1: marker IDs", tags$br(),
485
- "Row 2: chromosome", tags$br(),
486
- "Row 3: position (cM)", tags$br(),
487
- "Rows 4+: individual genotypes"
488
  )
489
  ),
490
 
@@ -493,19 +411,19 @@ ui <- fluidPage(
493
  fileInput("pheno_file", NULL, accept = ".csv",
494
  buttonLabel = "Browse", placeholder = "phenotypes.csv"),
495
  div(class = "format-help",
496
- "Col 1: individual IDs", tags$br(),
497
- "Col 2+: phenotype values"
498
  )
499
  ),
500
 
 
 
 
501
  div(class = "section-label", "Cross Type"),
502
  div(class = "control-block",
503
  selectInput("cross_type", NULL,
504
- choices = c("Backcross" = "bc",
505
- "F2 Intercross" = "f2",
506
- "RIL (selfing)" = "riself",
507
- "RIL (sib-mating)" = "risib",
508
- "4-way cross" = "4way"),
509
  selected = "f2")
510
  ),
511
 
@@ -522,13 +440,10 @@ ui <- fluidPage(
522
  "Extended HK (ehk)" = "ehk",
523
  "Multiple Imputation (imp)" = "imp",
524
  "Composite Interval (cim)" = "cim",
525
- "Two-Part Model (2part)" = "2part",
526
  "Non-Parametric (np)" = "np",
527
- "Marker Regression (mr)" = "mr",
528
- "MR + Imputation (mr-imp)" = "mr-imp",
529
- "MR + HK (mr-argmax)" = "mr-argmax"
530
  ),
531
- selected = c("em","hk","ehk","imp","cim","np","mr")
532
  ),
533
 
534
  div(class = "section-label", "Permutation"),
@@ -564,76 +479,35 @@ ui <- fluidPage(
564
  )
565
  ),
566
 
567
- # ── Main panel ────────────────────────────────────────────────────────────
568
  div(class = "qtl-main",
569
 
570
- # Tab bar
571
  div(class = "qtl-tabs",
572
- tags$button(class = "qtl-tab-btn active", `data-tab` = "overview", "Overview"),
573
- tags$button(class = "qtl-tab-btn", `data-tab` = "manhattan", "Manhattan"),
574
- tags$button(class = "qtl-tab-btn", `data-tab` = "genome", "Genome Scan"),
575
- tags$button(class = "qtl-tab-btn", `data-tab` = "chromosome", "Chr Plots"),
576
- tags$button(class = "qtl-tab-btn", `data-tab` = "model_comp", "Model Compare"),
577
- tags$button(class = "qtl-tab-btn", `data-tab` = "effects", "QTL Effects"),
578
- tags$button(class = "qtl-tab-btn", `data-tab` = "pairwise", "2D Scan"),
579
- tags$button(class = "qtl-tab-btn", `data-tab` = "diagnostics", "Diagnostics"),
580
- tags$button(class = "qtl-tab-btn", `data-tab` = "results", "QTL Table"),
581
- tags$button(class = "qtl-tab-btn", `data-tab` = "summary", "Summary")
582
- ),
583
-
584
- # ── OVERVIEW ────────────────────────────────────────────────────────────
585
- div(id = "tab_overview", class = "tab-content active",
586
- uiOutput("overview_content")
587
- ),
588
-
589
- # ── MANHATTAN ───────────────────────────────────────────────────────────
590
- div(id = "tab_manhattan", class = "tab-content",
591
- uiOutput("manhattan_content")
592
  ),
593
 
594
- # ── GENOME SCAN ─────────────────────────────────────────────────────────
595
- div(id = "tab_genome", class = "tab-content",
596
- uiOutput("genome_content")
597
- ),
598
-
599
- # ── CHROMOSOME PLOTS ────────────────────────────────────────────────────
600
- div(id = "tab_chromosome", class = "tab-content",
601
- uiOutput("chromosome_content")
602
- ),
603
-
604
- # ── MODEL COMPARISON ────────────────────────────────────────────────────
605
- div(id = "tab_model_comp", class = "tab-content",
606
- uiOutput("model_comp_content")
607
- ),
608
-
609
- # ── QTL EFFECTS ─────────────────────────────────────────────────────────
610
- div(id = "tab_effects", class = "tab-content",
611
- uiOutput("effects_content")
612
- ),
613
-
614
- # ── 2D SCAN ─────────────────────────────────────────────────────────────
615
- div(id = "tab_pairwise", class = "tab-content",
616
- uiOutput("pairwise_content")
617
- ),
618
-
619
- # ── DIAGNOSTICS ─────────────────────────────────────────────────────────
620
- div(id = "tab_diagnostics", class = "tab-content",
621
- uiOutput("diagnostics_content")
622
- ),
623
-
624
- # ── RESULTS TABLE ───────────────────────────────────────────────────────
625
- div(id = "tab_results", class = "tab-content",
626
- uiOutput("results_content")
627
- ),
628
-
629
- # ── SUMMARY ─────────────────────────────────────────────────────────────
630
- div(id = "tab_summary", class = "tab-content",
631
- uiOutput("summary_content")
632
- )
633
  )
634
  ),
635
 
636
- # JS for tab switching
637
  tags$script(HTML("
638
  document.querySelectorAll('.qtl-tab-btn').forEach(function(btn) {
639
  btn.addEventListener('click', function() {
@@ -646,45 +520,36 @@ ui <- fluidPage(
646
  "))
647
  )
648
 
 
649
  # ─── SERVER ───────────────────────────────────────────────────────────────────
650
  server <- function(input, output, session) {
651
 
652
- # ── Light ggplot theme ─────────────────────────────────────────────────────
653
  theme_qtl <- function(base_size = 11) {
654
  theme_minimal(base_size = base_size) +
655
  theme(
656
- plot.background = element_rect(fill = "#ffffff", color = NA),
657
- panel.background = element_rect(fill = "#f8f9fb", color = NA),
658
- panel.grid.major = element_line(color = "#e8ecf2", linewidth = .45),
659
- panel.grid.minor = element_line(color = "#f1f4f8", linewidth = .25),
660
- panel.border = element_rect(color = "#dde2ea", fill = NA, linewidth = .8),
661
- axis.text = element_text(color = "#8a95a3", size = 9, family = "mono"),
662
- axis.title = element_text(color = "#4a5568", size = 10),
663
- plot.title = element_text(color = "#1a202c", size = 12, face = "bold", family = "mono"),
664
- plot.subtitle = element_text(color = "#8a95a3", size = 9),
665
- legend.background = element_rect(fill = "#ffffff", color = "#dde2ea", linewidth = .5),
666
- legend.text = element_text(color = "#4a5568", size = 9),
667
- legend.title = element_text(color = "#8a95a3", size = 9),
668
- strip.background = element_rect(fill = "#f1f4f8", color = "#dde2ea"),
669
- strip.text = element_text(color = "#1a6cf5", size = 9, family = "mono", face = "bold"),
670
- plot.margin = margin(12, 16, 12, 16)
671
  )
672
  }
673
 
674
  model_colors <- c(
675
- em = "#1a6cf5",
676
- hk = "#e8500a",
677
- ehk = "#18a058",
678
- imp = "#c2185b",
679
- cim = "#7c3aed",
680
- `2part` = "#d97706",
681
- np = "#0891b2",
682
- mr = "#dc2626",
683
- `mr-imp` = "#2563eb",
684
- `mr-argmax` = "#ea580c"
685
  )
686
 
687
- # ── Helper: empty state UI ─────────────────────────────────────────────────
688
  empty_state_ui <- function(icon = "πŸ“‚", title = "No Data Loaded",
689
  msg = "Upload your genotype and phenotype CSV files, then click RUN ANALYSIS.") {
690
  div(class = "empty-state",
@@ -694,45 +559,58 @@ server <- function(input, output, session) {
694
  )
695
  }
696
 
697
- # ── reactive: cross object from CSV only ──────────────────────────────────
698
  cross_data <- reactive({
699
  req(input$geno_file, input$pheno_file)
700
  tryCatch({
701
- cross <- read.cross(
702
- format = "csv",
703
- genfile = input$geno_file$datapath,
704
- phefile = input$pheno_file$datapath,
705
- crosstype = input$cross_type
706
  )
707
  cross
708
  }, error = function(e) {
709
- showNotification(paste("Error loading data:", e$message), type = "error", duration = 8)
710
  NULL
711
  })
712
  })
713
 
714
- # ── Update phenotype dropdown when cross loads ─────────────────────────────
715
- observe({
 
716
  cross <- cross_data()
717
- req(cross)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
718
  pheno_names <- names(cross$pheno)
719
  updateSelectInput(session, "pheno_col", choices = pheno_names, selected = pheno_names[1])
720
  runjs("document.getElementById('status_dot').classList.add('active')")
721
  output$status_text <- renderText(paste0(
722
- totmar(cross), " markers Β· ",
723
- nind(cross), " inds Β· ",
724
- nchr(cross), " chrs β€” Ready"
725
  ))
726
  })
727
 
728
- # ── analysis results ───────────────────────────────────────────────────────
729
  analysis_results <- reactiveVal(NULL)
730
 
731
  observeEvent(input$run_analysis, {
732
  cross <- cross_data()
733
  if (is.null(cross)) {
734
- showNotification("Please upload both CSV files first.", type = "warning")
735
- return()
736
  }
737
 
738
  runjs("document.getElementById('status_dot').classList.remove('active')")
@@ -740,34 +618,36 @@ server <- function(input, output, session) {
740
 
741
  withProgress(message = "QTL Mapping in progress...", value = 0, {
742
 
743
- cross <- calc.genoprob(cross,
744
- step = input$step_size,
745
- error.prob = input$error_prob)
 
 
746
  incProgress(0.1, detail = "Genoprobs calculated")
747
 
748
- cross <- sim.geno(cross, n.draws = 64,
749
- step = input$step_size,
750
- error.prob = input$error_prob)
 
751
  incProgress(0.1, detail = "Simulated genotypes done")
752
 
753
  pheno_idx <- which(names(cross$pheno) == input$pheno_col)
 
754
 
755
  scan_results <- list()
756
  perm_results <- list()
757
  models_to_run <- input$models
758
- n_models <- length(models_to_run)
759
 
760
  for (i in seq_along(models_to_run)) {
761
  mdl <- models_to_run[i]
762
- incProgress(0.5 / n_models, detail = paste("Scanning:", mdl))
763
-
764
  sc <- tryCatch(
765
  scanone(cross, pheno.col = pheno_idx, method = mdl),
766
- error = function(e) NULL
767
  )
768
  if (!is.null(sc)) {
769
  scan_results[[mdl]] <- sc
770
-
771
  if (input$n_perm > 0) {
772
  perm_results[[mdl]] <- tryCatch(
773
  scanone(cross, pheno.col = pheno_idx, method = mdl,
@@ -777,18 +657,23 @@ server <- function(input, output, session) {
777
  }
778
  }
779
  }
 
 
 
 
780
  incProgress(0.1, detail = "Summarising QTLs")
781
 
782
  lod_thr <- input$lod_thresh
783
  if (length(perm_results) > 0) {
784
  first_perm <- perm_results[[1]]
785
  if (!is.null(first_perm)) {
786
- thr_try <- tryCatch(summary(first_perm, alpha = input$alpha_thresh)[1], error = function(e) NULL)
787
- if (!is.null(thr_try)) lod_thr <- thr_try
788
  }
789
  }
790
 
791
  qtl_table <- build_qtl_table(cross, scan_results, lod_thr, pheno_idx)
 
792
 
793
  analysis_results(list(
794
  cross = cross,
@@ -798,11 +683,11 @@ server <- function(input, output, session) {
798
  qtl_table = qtl_table,
799
  pheno_idx = pheno_idx
800
  ))
801
-
802
- incProgress(0.1, detail = "Done")
803
  })
804
 
805
  res <- analysis_results()
 
 
806
  model_choices <- names(res$scan_results)
807
  updateSelectInput(session, "manhattan_model", choices = model_choices, selected = model_choices[1])
808
  updateSelectInput(session, "chr_plot_model", choices = model_choices, selected = model_choices[1])
@@ -818,7 +703,7 @@ server <- function(input, output, session) {
818
  ))
819
  })
820
 
821
- # ── Helper: build QTL table ────────────────────────────────────────────────
822
  build_qtl_table <- function(cross, scan_results, lod_thr, pheno_idx) {
823
  rows <- list()
824
  for (mdl in names(scan_results)) {
@@ -834,17 +719,10 @@ server <- function(input, output, session) {
834
  peak_marker <- rownames(peak_row)
835
 
836
  ci <- tryCatch(lodint(sc, chr = ch, drop = 1.5), error = function(e) NULL)
837
- left_marker <- if (!is.null(ci)) rownames(ci)[1] else NA_character_
838
  right_marker <- if (!is.null(ci)) rownames(ci)[nrow(ci)] else NA_character_
839
- left_pos <- if (!is.null(ci)) ci$pos[1] else NA_real_
840
- right_pos <- if (!is.null(ci)) ci$pos[nrow(ci)] else NA_real_
841
-
842
- eff <- tryCatch({
843
- m <- find.marker(cross, chr = ch, pos = peak_pos)
844
- effectplot(cross, mname1 = m, pheno.col = pheno_idx, draw = FALSE)
845
- }, error = function(e) NULL)
846
-
847
- add_eff <- if (!is.null(eff)) round(diff(range(eff$Means)), 4) else NA
848
 
849
  n <- nind(cross)
850
  pve <- round((1 - 10^(-2 * peak_lod / n)) * 100, 2)
@@ -856,8 +734,6 @@ server <- function(input, output, session) {
856
  Peak_pos_cM = round(peak_pos, 2),
857
  LOD = round(peak_lod, 3),
858
  PVE_pct = pve,
859
- Additive_Eff = add_eff,
860
- Dom_Eff = NA,
861
  Left_Marker = left_marker,
862
  Left_pos_cM = round(left_pos, 2),
863
  Right_Marker = right_marker,
@@ -871,18 +747,15 @@ server <- function(input, output, session) {
871
  dplyr::bind_rows(rows) %>% dplyr::arrange(Chr, Peak_pos_cM)
872
  }
873
 
874
- # ── Status text default ────────────────────────────────────────────────────
875
  output$status_text <- renderText("Upload CSV files to begin")
876
 
877
  # ══════════════════════════════════════════════════════════════════════════
878
- # TAB CONTENT RENDERERS (show empty state until data loaded)
879
  # ══════════════════════════════════════════════════════════════════════════
880
 
881
- # ── OVERVIEW ──────────────────────────────────────────────────────────────
882
  output$overview_content <- renderUI({
883
  cross <- cross_data()
884
  if (is.null(cross)) return(empty_state_ui())
885
-
886
  tagList(
887
  div(class = "stat-row",
888
  div(class = "stat-chip blue", paste0(totmar(cross), " MARKERS")),
@@ -895,7 +768,7 @@ server <- function(input, output, session) {
895
  div(class = "plot-card-header",
896
  div(class = "plot-card-icon blue", "πŸ“Š"),
897
  div(div(class = "plot-card-title", "GENOME MAP"),
898
- div(class = "plot-card-subtitle", "Marker distribution"))
899
  ),
900
  div(class = "plot-card-body",
901
  plotOutput("plot_genome_map", height = "320px") %>% withSpinner(color = "#1a6cf5", type = 4))
@@ -904,7 +777,7 @@ server <- function(input, output, session) {
904
  div(class = "plot-card-header",
905
  div(class = "plot-card-icon orange", "πŸ“ˆ"),
906
  div(div(class = "plot-card-title", "PHENOTYPE DIST"),
907
- div(class = "plot-card-subtitle", "Distribution & QQ"))
908
  ),
909
  div(class = "plot-card-body",
910
  plotOutput("plot_pheno_dist", height = "320px") %>% withSpinner(color = "#e8500a", type = 4))
@@ -928,15 +801,13 @@ server <- function(input, output, session) {
928
  paste0(n, " QTLs FOUND")
929
  })
930
 
931
- # ── MANHATTAN ─────────────────────────────────────────────────────────────
932
  output$manhattan_content <- renderUI({
933
  res <- analysis_results()
934
  if (is.null(res)) return(empty_state_ui("πŸŒƒ", "Run Analysis First",
935
  "Upload your CSV files and click RUN ANALYSIS to generate the Manhattan plot."))
936
  tagList(
937
  div(class = "info-box",
938
- "Manhattan plot shows LOD score across all chromosomes. Peaks above the threshold line are candidate QTL regions."
939
- ),
940
  div(class = "plot-card",
941
  div(class = "plot-card-header",
942
  div(class = "plot-card-icon blue", "πŸŒƒ"),
@@ -944,7 +815,7 @@ server <- function(input, output, session) {
944
  div(class = "plot-card-subtitle", "LOD scores genome-wide"))
945
  ),
946
  div(class = "plot-card-body",
947
- div(class = "control-block", style = "max-width:200px; margin-bottom:12px;",
948
  selectInput("manhattan_model", "Model:", choices = names(res$scan_results))
949
  ),
950
  plotOutput("plot_manhattan", height = "420px") %>% withSpinner(color = "#1a6cf5", type = 4)
@@ -963,7 +834,6 @@ server <- function(input, output, session) {
963
  )
964
  })
965
 
966
- # ── GENOME SCAN ───────────────────────────────────────────────────────────
967
  output$genome_content <- renderUI({
968
  res <- analysis_results()
969
  if (is.null(res)) return(empty_state_ui("πŸ”¬", "Run Analysis First"))
@@ -974,25 +844,22 @@ server <- function(input, output, session) {
974
  div(class = "plot-card-subtitle", "LOD profiles overlaid"))
975
  ),
976
  div(class = "plot-card-body",
977
- plotOutput("plot_scan_all_models", height = "480px") %>% withSpinner(color = "#1a6cf5", type = 4)
978
- )
979
  )
980
  })
981
 
982
- # ── CHROMOSOME PLOTS ──────────────────────────────────────────────────────
983
  output$chromosome_content <- renderUI({
984
  res <- analysis_results()
985
  if (is.null(res)) return(empty_state_ui("πŸ“ˆ", "Run Analysis First"))
986
  tagList(
987
- div(class = "info-box", "Per-chromosome LOD profiles. Significant peaks are labelled with QTL names."),
988
- div(class = "control-block", style = "max-width:200px; margin-bottom:16px;",
989
  selectInput("chr_plot_model", "Model:", choices = names(res$scan_results))
990
  ),
991
  plotOutput("plot_chr_grid", height = "900px") %>% withSpinner(color = "#18a058", type = 4)
992
  )
993
  })
994
 
995
- # ── MODEL COMPARISON ──────────────────────────────────────────────────────
996
  output$model_comp_content <- renderUI({
997
  res <- analysis_results()
998
  if (is.null(res)) return(empty_state_ui("βš–οΈ", "Run Analysis First"))
@@ -1011,7 +878,7 @@ server <- function(input, output, session) {
1011
  div(class = "plot-card-header",
1012
  div(class = "plot-card-icon pink", "πŸ”·"),
1013
  div(div(class = "plot-card-title", "LOD HEATMAP"),
1014
- div(class = "plot-card-subtitle", "Marker Γ— Model"))
1015
  ),
1016
  div(class = "plot-card-body",
1017
  plotOutput("plot_lod_heatmap", height = "340px") %>% withSpinner(color = "#c2185b", type = 4))
@@ -1029,7 +896,6 @@ server <- function(input, output, session) {
1029
  )
1030
  })
1031
 
1032
- # ── QTL EFFECTS ───────────────────────────────────────────────────────────
1033
  output$effects_content <- renderUI({
1034
  res <- analysis_results()
1035
  if (is.null(res)) return(empty_state_ui("🎻", "Run Analysis First"))
@@ -1041,10 +907,10 @@ server <- function(input, output, session) {
1041
  div(class = "plot-card-header",
1042
  div(class = "plot-card-icon green", "🎻"),
1043
  div(div(class = "plot-card-title", "EFFECT PLOT"),
1044
- div(class = "plot-card-subtitle", "Genotype effect at peak markers"))
1045
  ),
1046
  div(class = "plot-card-body",
1047
- div(class = "control-block", style = "margin-bottom:10px;",
1048
  selectInput("effect_qtl", "Select QTL:", choices = qtl_choices)
1049
  ),
1050
  plotOutput("plot_effects", height = "320px") %>% withSpinner(color = "#18a058", type = 4)
@@ -1054,7 +920,7 @@ server <- function(input, output, session) {
1054
  div(class = "plot-card-header",
1055
  div(class = "plot-card-icon orange", "πŸ“¦"),
1056
  div(div(class = "plot-card-title", "PHENOTYPE Γ— GENOTYPE"),
1057
- div(class = "plot-card-subtitle", "Boxplot at peak marker"))
1058
  ),
1059
  div(class = "plot-card-body",
1060
  plotOutput("plot_pheno_geno", height = "320px") %>% withSpinner(color = "#e8500a", type = 4))
@@ -1064,7 +930,7 @@ server <- function(input, output, session) {
1064
  div(class = "plot-card-header",
1065
  div(class = "plot-card-icon pink", "🌑"),
1066
  div(div(class = "plot-card-title", "PVE PROFILE"),
1067
- div(class = "plot-card-subtitle", "Proportion of variance explained per position"))
1068
  ),
1069
  div(class = "plot-card-body",
1070
  plotOutput("plot_pve", height = "280px") %>% withSpinner(color = "#c2185b", type = 4))
@@ -1072,7 +938,6 @@ server <- function(input, output, session) {
1072
  )
1073
  })
1074
 
1075
- # ── 2D SCAN ───────────────────────────────────────────────────────────────
1076
  output$pairwise_content <- renderUI({
1077
  res <- analysis_results()
1078
  if (is.null(res)) return(empty_state_ui("πŸ”²", "Run Analysis First"))
@@ -1080,24 +945,23 @@ server <- function(input, output, session) {
1080
  div(class = "plot-card-header",
1081
  div(class = "plot-card-icon blue", "πŸ”²"),
1082
  div(div(class = "plot-card-title", "2D GENOME SCAN"),
1083
- div(class = "plot-card-subtitle", "Pairwise LOD / epistasis"))
1084
  ),
1085
  div(class = "plot-card-body",
1086
  plotOutput("plot_2d_scan", height = "560px") %>% withSpinner(color = "#1a6cf5", type = 4))
1087
  )
1088
  })
1089
 
1090
- # ── DIAGNOSTICS ───────────────────────────────────────────────────────────
1091
  output$diagnostics_content <- renderUI({
1092
  cross <- cross_data()
1093
- if (is.null(cross)) return(empty_state_ui("πŸ”", "No Data Loaded", "Upload CSV files to view diagnostics."))
1094
  tagList(
1095
  div(class = "grid-2",
1096
  div(class = "plot-card",
1097
  div(class = "plot-card-header",
1098
  div(class = "plot-card-icon orange", "πŸ”"),
1099
  div(div(class = "plot-card-title", "MISSING DATA"),
1100
- div(class = "plot-card-subtitle", "Genotype completeness"))
1101
  ),
1102
  div(class = "plot-card-body",
1103
  plotOutput("plot_missing", height = "300px") %>% withSpinner(color = "#e8500a", type = 4))
@@ -1106,7 +970,7 @@ server <- function(input, output, session) {
1106
  div(class = "plot-card-header",
1107
  div(class = "plot-card-icon green", "πŸ“"),
1108
  div(div(class = "plot-card-title", "GENOTYPE FREQ"),
1109
- div(class = "plot-card-subtitle", "Allele frequency per marker"))
1110
  ),
1111
  div(class = "plot-card-body",
1112
  plotOutput("plot_geno_freq", height = "300px") %>% withSpinner(color = "#18a058", type = 4))
@@ -1116,7 +980,7 @@ server <- function(input, output, session) {
1116
  div(class = "plot-card-header",
1117
  div(class = "plot-card-icon pink", "πŸ”—"),
1118
  div(div(class = "plot-card-title", "MARKER DISTANCE"),
1119
- div(class = "plot-card-subtitle", "Inter-marker spacing"))
1120
  ),
1121
  div(class = "plot-card-body",
1122
  plotOutput("plot_marker_dist", height = "260px") %>% withSpinner(color = "#c2185b", type = 4))
@@ -1124,7 +988,6 @@ server <- function(input, output, session) {
1124
  )
1125
  })
1126
 
1127
- # ── RESULTS TABLE ─────────────────────────────────────────────────────────
1128
  output$results_content <- renderUI({
1129
  res <- analysis_results()
1130
  if (is.null(res)) return(empty_state_ui("πŸ“‹", "Run Analysis First"))
@@ -1132,13 +995,12 @@ server <- function(input, output, session) {
1132
  div(class = "plot-card-header",
1133
  div(class = "plot-card-icon blue", "πŸ“‹"),
1134
  div(div(class = "plot-card-title", "QTL RESULTS TABLE"),
1135
- div(class = "plot-card-subtitle", "Peak marker, flanking markers, LOD, PVE, effects, CI"))
1136
  ),
1137
  div(class = "plot-card-body", DTOutput("table_qtl_results"))
1138
  )
1139
  })
1140
 
1141
- # ── SUMMARY ───────────────────────────────────────────────────────────────
1142
  output$summary_content <- renderUI({
1143
  res <- analysis_results()
1144
  if (is.null(res)) return(empty_state_ui("πŸ“", "Run Analysis First"))
@@ -1146,8 +1008,8 @@ server <- function(input, output, session) {
1146
  div(class = "plot-card",
1147
  div(class = "plot-card-header",
1148
  div(class = "plot-card-icon green", "πŸ“"),
1149
- div(div(class = "plot-card-title", "ANALYSIS SUMMARY"),
1150
- div(class = "plot-card-subtitle", "All models"))
1151
  ),
1152
  div(class = "plot-card-body", DTOutput("table_model_summary"))
1153
  ),
@@ -1173,85 +1035,64 @@ server <- function(input, output, session) {
1173
  data.frame(chr = ch, pos = unname(map[[ch]]), stringsAsFactors = FALSE)
1174
  }))
1175
  df$chr <- factor(df$chr, levels = names(map))
1176
-
1177
  ggplot(df, aes(x = chr, y = pos)) +
1178
  geom_segment(aes(xend = chr, yend = pos), color = "#dde2ea", linewidth = 8) +
1179
  geom_point(color = "#1a6cf5", size = 1.5, alpha = .8) +
1180
  scale_y_reverse() +
1181
- labs(title = "Genetic Map", x = "Chromosome", y = "Position (cM)") +
1182
- theme_qtl()
1183
  }, bg = "white")
1184
 
1185
  output$plot_pheno_dist <- renderPlot({
1186
- cross <- cross_data(); req(cross); req(input$pheno_col)
1187
  ph <- cross$pheno[[input$pheno_col]]
1188
  df <- data.frame(value = ph[!is.na(ph)])
1189
-
1190
  p1 <- ggplot(df, aes(value)) +
1191
  geom_histogram(fill = "#1a6cf5", color = "#ffffff", bins = 30, alpha = .8) +
1192
- geom_density(aes(y = after_stat(count)), color = "#e8500a", linewidth = 1) +
1193
- labs(title = input$pheno_col, x = "Value", y = "Count") +
1194
- theme_qtl()
1195
-
1196
  p2 <- ggplot(df, aes(sample = value)) +
1197
  stat_qq(color = "#18a058", size = 1.5, alpha = .8) +
1198
  stat_qq_line(color = "#c2185b", linewidth = .8) +
1199
- labs(title = "Q-Q Plot", x = "Theoretical", y = "Sample") +
1200
- theme_qtl()
1201
-
1202
  gridExtra::grid.arrange(p1, p2, ncol = 2)
1203
  }, bg = "white")
1204
 
1205
  output$plot_physical_map <- renderPlot({
1206
  cross <- cross_data(); req(cross)
1207
  map <- pull.map(cross)
1208
- df <- do.call(rbind, lapply(names(map), function(ch) {
1209
- data.frame(chr = ch, pos = unname(map[[ch]]), stringsAsFactors = FALSE)
1210
- }))
1211
- chr_len <- df %>% group_by(chr) %>% summarise(len = max(pos))
1212
  chr_len$chr <- factor(chr_len$chr, levels = names(map))
1213
-
1214
  ggplot() +
1215
  geom_rect(data = chr_len,
1216
- aes(xmin = as.numeric(chr) - .35, xmax = as.numeric(chr) + .35,
1217
- ymin = 0, ymax = len),
1218
  fill = "#e8ecf2", color = "#c8d0dc", linewidth = .7) +
1219
- geom_point(data = df %>% mutate(chr = factor(chr, levels = names(map))),
1220
- aes(x = as.numeric(chr), y = pos),
1221
  color = "#1a6cf5", size = 1, alpha = .7) +
1222
  scale_x_continuous(breaks = seq_along(names(map)), labels = names(map)) +
1223
  scale_y_reverse() +
1224
- labs(title = "Physical Map Overview", x = "Chromosome", y = "cM") +
1225
- theme_qtl()
1226
  }, bg = "white")
1227
 
1228
  output$plot_manhattan <- renderPlot({
1229
  res <- analysis_results(); req(res)
1230
  mdl <- input$manhattan_model; req(mdl)
1231
  sc <- res$scan_results[[mdl]]; req(sc)
1232
-
1233
  chrs <- unique(sc$chr)
1234
- chr_offsets <- setNames(cumsum(c(0, sapply(chrs[-length(chrs)], function(ch)
1235
- max(sc[sc$chr == ch, "pos"])))), chrs)
1236
  sc$global_pos <- sc$pos + chr_offsets[as.character(sc$chr)]
1237
  sc$chr_num <- as.integer(factor(sc$chr, levels = chrs))
1238
  sc$color <- ifelse(sc$chr_num %% 2 == 0, "#1a6cf5", "#5b9cf5")
1239
  sig <- sc[sc$lod >= res$lod_thr, ]
1240
  chr_mid <- tapply(sc$global_pos, sc$chr, mean)
1241
-
1242
  ggplot(sc, aes(x = global_pos, y = lod)) +
1243
  geom_point(aes(color = color), size = 1.2, alpha = .75) +
1244
  scale_color_identity() +
1245
- geom_point(data = sig, aes(x = global_pos, y = lod),
1246
- color = "#c2185b", size = 2.5, shape = 18) +
1247
- geom_hline(yintercept = res$lod_thr, color = "#e8500a",
1248
- linetype = "dashed", linewidth = .8) +
1249
- annotate("text", x = max(sc$global_pos) * .98, y = res$lod_thr + .15,
1250
- label = paste0("LOD = ", round(res$lod_thr, 2)),
1251
- color = "#e8500a", size = 3, hjust = 1, family = "mono") +
1252
  scale_x_continuous(breaks = chr_mid, labels = names(chr_mid)) +
1253
- labs(title = paste("Manhattan Plot β€”", toupper(mdl)),
1254
- x = "Chromosome", y = "LOD Score") +
1255
  theme_qtl() + theme(panel.grid.major.x = element_blank())
1256
  }, bg = "white")
1257
 
@@ -1259,63 +1100,43 @@ server <- function(input, output, session) {
1259
  res <- analysis_results(); req(res)
1260
  mdl <- input$manhattan_model; req(mdl)
1261
  sc <- res$scan_results[[mdl]]; req(sc)
1262
-
1263
  chrs <- unique(sc$chr)
1264
- chr_offsets <- setNames(cumsum(c(0, sapply(chrs[-length(chrs)], function(ch)
1265
- max(sc[sc$chr == ch, "pos"])))), chrs)
1266
  sc$global_pos <- sc$pos + chr_offsets[as.character(sc$chr)]
1267
- sc$sig <- sc$lod >= res$lod_thr
1268
- sc$label <- paste0(rownames(sc), "<br>Chr:", sc$chr,
1269
- " Pos:", round(sc$pos,1), " LOD:", round(sc$lod,2))
1270
-
1271
- plot_ly(sc, x = ~global_pos, y = ~lod,
1272
- color = ~sig, colors = c("#1a6cf5","#c2185b"),
1273
  text = ~label, hovertemplate = "%{text}<extra></extra>",
1274
- type = "scatter", mode = "markers",
1275
- marker = list(size = 4, opacity = .8)) %>%
1276
- add_lines(y = res$lod_thr,
1277
- line = list(color = "#e8500a", dash = "dash", width = 1.5),
1278
  showlegend = FALSE, name = "Threshold") %>%
1279
- layout(
1280
- paper_bgcolor = "#ffffff",
1281
- plot_bgcolor = "#f8f9fb",
1282
- font = list(color = "#4a5568", family = "monospace"),
1283
- xaxis = list(title = "Position", gridcolor = "#e8ecf2", color = "#8a95a3"),
1284
- yaxis = list(title = "LOD Score", gridcolor = "#e8ecf2", color = "#8a95a3"),
1285
- legend = list(font = list(color = "#4a5568")),
1286
- margin = list(t = 10, b = 40, l = 50, r = 20)
1287
- )
1288
  })
1289
 
1290
  output$plot_scan_all_models <- renderPlot({
1291
- res <- analysis_results(); req(res)
1292
- req(length(res$scan_results) > 0)
1293
-
1294
  dfs <- lapply(names(res$scan_results), function(mdl) {
1295
  sc <- res$scan_results[[mdl]]
1296
  chrs <- unique(sc$chr)
1297
- offsets <- setNames(cumsum(c(0, sapply(chrs[-length(chrs)], function(ch)
1298
- max(sc[sc$chr == ch,"pos"])))), chrs)
1299
  sc$global_pos <- sc$pos + offsets[as.character(sc$chr)]
1300
  sc$model <- mdl; sc
1301
  })
1302
  df_all <- dplyr::bind_rows(dfs)
1303
- df_all$model <- factor(df_all$model)
1304
-
1305
  sc_ref <- res$scan_results[[1]]
1306
  chrs <- unique(sc_ref$chr)
1307
- offsets <- setNames(cumsum(c(0, sapply(chrs[-length(chrs)], function(ch)
1308
- max(sc_ref[sc_ref$chr==ch,"pos"])))), chrs)
1309
  vlines <- data.frame(x = offsets[-1])
1310
-
1311
  ggplot(df_all, aes(x = global_pos, y = lod, color = model)) +
1312
  geom_vline(data = vlines, aes(xintercept = x), color = "#e8ecf2", linewidth = .5) +
1313
  geom_line(linewidth = .6, alpha = .85) +
1314
- geom_hline(yintercept = res$lod_thr, color = "#e8500a",
1315
- linetype = "dashed", linewidth = .7) +
1316
  scale_color_manual(values = model_colors) +
1317
- labs(title = "Genome Scan β€” All Models",
1318
- x = "Genome Position (cM)", y = "LOD Score", color = "Model") +
1319
  theme_qtl() + theme(legend.position = "right")
1320
  }, bg = "white")
1321
 
@@ -1324,61 +1145,36 @@ server <- function(input, output, session) {
1324
  mdl <- input$chr_plot_model; req(mdl)
1325
  sc <- res$scan_results[[mdl]]; req(sc)
1326
  qt <- res$qtl_table
1327
-
1328
- chrs <- unique(sc$chr)
1329
- n_chr <- length(chrs)
1330
- n_cols <- min(6, n_chr)
1331
- n_rows <- ceiling(n_chr / n_cols)
1332
-
1333
  plots <- lapply(chrs, function(ch) {
1334
  chr_sc <- sc[sc$chr == ch, ]
1335
  p <- ggplot(chr_sc, aes(x = pos, y = lod)) +
1336
  geom_line(color = "#1a6cf5", linewidth = .9) +
1337
- geom_hline(yintercept = res$lod_thr, color = "#e8500a",
1338
- linetype = "dashed", linewidth = .6) +
1339
- scale_x_continuous(expand = c(.02,.02)) +
1340
  scale_y_continuous(limits = c(0, max(sc$lod) * 1.1)) +
1341
  labs(title = paste0("Chr ", ch), x = NULL, y = "LOD") +
1342
- theme_qtl(base_size = 9) +
1343
- theme(plot.title = element_text(size = 9, color = "#1a6cf5"),
1344
- axis.title.y = element_text(size = 7),
1345
- plot.margin = margin(6, 8, 6, 8))
1346
-
1347
  if (!is.null(qt) && nrow(qt) > 0) {
1348
  qt_chr <- qt[qt$Chr == ch & qt$Model == mdl, ]
1349
- if (nrow(qt_chr) > 0) {
1350
- p <- p +
1351
- geom_point(data = qt_chr, aes(x = Peak_pos_cM, y = LOD),
1352
- color = "#c2185b", size = 3, shape = 23, fill = "#c2185b") +
1353
- ggrepel::geom_label_repel(
1354
- data = qt_chr,
1355
- aes(x = Peak_pos_cM, y = LOD,
1356
- label = paste0("q", toupper(substr(mdl,1,1)), "R", ch)),
1357
- fill = "#ffffff", color = "#18a058", size = 2.5,
1358
- label.padding = unit(.15,"lines"), min.segment.length = 0
1359
- )
1360
- }
1361
  }
1362
  p
1363
  })
1364
-
1365
  do.call(gridExtra::grid.arrange, c(plots, list(ncol = n_cols, nrow = n_rows)))
1366
  }, bg = "white")
1367
 
1368
  output$plot_model_bar <- renderPlot({
1369
  res <- analysis_results(); req(res)
1370
- df <- data.frame(
1371
- model = names(res$scan_results),
1372
- max_lod = sapply(res$scan_results, function(sc) max(sc$lod, na.rm = TRUE))
1373
- )
1374
  df$model <- factor(df$model, levels = df$model[order(df$max_lod)])
1375
-
1376
  ggplot(df, aes(x = model, y = max_lod, fill = model)) +
1377
  geom_col(width = .6, alpha = .85) +
1378
- geom_hline(yintercept = res$lod_thr, color = "#e8500a",
1379
- linetype = "dashed", linewidth = .8) +
1380
- geom_text(aes(label = round(max_lod, 2)), hjust = -0.2,
1381
- color = "#1a202c", size = 3, family = "mono") +
1382
  scale_fill_manual(values = model_colors) +
1383
  coord_flip(ylim = c(0, max(df$max_lod) * 1.15)) +
1384
  labs(title = "Peak LOD by Model", x = NULL, y = "Max LOD") +
@@ -1387,83 +1183,59 @@ server <- function(input, output, session) {
1387
 
1388
  output$plot_lod_heatmap <- renderPlot({
1389
  res <- analysis_results(); req(res)
1390
-
1391
  all_sc <- dplyr::bind_rows(lapply(names(res$scan_results), function(m) {
1392
- sc <- res$scan_results[[m]]
1393
- sc$model <- m; sc$marker <- rownames(sc); sc
1394
  }))
1395
- top_markers <- all_sc %>%
1396
- group_by(marker) %>%
1397
- summarise(max_lod = max(lod)) %>%
1398
- arrange(desc(max_lod)) %>%
1399
- slice_head(n = 40) %>%
1400
- pull(marker)
1401
-
1402
  hm <- all_sc %>% filter(marker %in% top_markers) %>% select(model, marker, lod)
1403
-
1404
  ggplot(hm, aes(x = model, y = marker, fill = lod)) +
1405
  geom_tile(color = "#f8f9fb", linewidth = .3) +
1406
- scale_fill_gradientn(
1407
- colors = c("#f8f9fb","#bcd0fc","#1a6cf5","#18a058","#c2185b"),
1408
- name = "LOD"
1409
- ) +
1410
  labs(title = "LOD Heatmap", x = "Model", y = "Marker") +
1411
- theme_qtl() +
1412
- theme(axis.text.x = element_text(angle = 30, hjust = 1),
1413
- axis.text.y = element_text(size = 6))
1414
  }, bg = "white")
1415
 
1416
  output$plot_model_corr <- renderPlot({
1417
- res <- analysis_results(); req(res)
1418
- req(length(res$scan_results) >= 2)
1419
-
1420
  sc_list <- lapply(names(res$scan_results), function(m) {
1421
  sc <- res$scan_results[[m]]
1422
  data.frame(marker = rownames(sc), lod = sc$lod, stringsAsFactors = FALSE)
1423
  })
1424
  names(sc_list) <- names(res$scan_results)
1425
-
1426
  common_markers <- Reduce(intersect, lapply(sc_list, `[[`, "marker"))
1427
  mat <- sapply(sc_list, function(sc) sc$lod[match(common_markers, sc$marker)])
1428
  corr_mat <- cor(mat, use = "complete.obs")
1429
- corr_df <- as.data.frame(as.table(corr_mat))
1430
- names(corr_df) <- c("m1","m2","corr")
1431
-
1432
  ggplot(corr_df, aes(x = m1, y = m2, fill = corr)) +
1433
  geom_tile(color = "#ffffff", linewidth = .5) +
1434
- geom_text(aes(label = round(corr, 2)), size = 3, color = "#1a202c", family = "mono") +
1435
- scale_fill_gradient2(low = "#c2185b", mid = "#f1f4f8", high = "#1a6cf5",
1436
- midpoint = 0, limits = c(-1,1), name = "r") +
1437
  labs(title = "Model LOD Correlation", x = NULL, y = NULL) +
1438
- theme_qtl() + theme(axis.text.x = element_text(angle = 30, hjust = 1))
1439
  }, bg = "white")
1440
 
1441
  output$plot_effects <- renderPlot({
1442
  res <- analysis_results(); req(res)
1443
- qtl_sel <- input$effect_qtl; req(qtl_sel); req(qtl_sel != "none")
1444
-
1445
- parts <- strsplit(qtl_sel, "@")[[1]]
1446
- ch <- parts[1]; mk <- parts[2]
1447
-
1448
  tryCatch({
1449
  eff <- effectplot(res$cross, mname1 = mk, pheno.col = res$pheno_idx, draw = FALSE)
1450
  df <- data.frame(geno = names(eff$Means), mean = eff$Means, se = eff$SEs)
1451
  ggplot(df, aes(x = geno, y = mean, fill = geno)) +
1452
  geom_col(width = .5, alpha = .85) +
1453
- geom_errorbar(aes(ymin = mean - se, ymax = mean + se),
1454
- width = .15, color = "#4a5568", linewidth = .8) +
1455
- scale_fill_manual(values = c("#1a6cf5","#c2185b","#18a058")) +
1456
  labs(title = paste("Effect Plot β€”", mk), x = "Genotype", y = "Mean Phenotype") +
1457
  theme_qtl() + theme(legend.position = "none")
1458
- }, error = function(e) {
1459
- ggplot() + annotate("text", x=.5, y=.5, label="Effect not available", color="#8a95a3", size=5) + theme_qtl()
1460
- })
1461
  }, bg = "white")
1462
 
1463
  output$plot_pheno_geno <- renderPlot({
1464
  res <- analysis_results(); req(res)
1465
  qtl_sel <- input$effect_qtl; req(qtl_sel != "none")
1466
-
1467
  parts <- strsplit(qtl_sel, "@")[[1]]; mk <- parts[2]
1468
  tryCatch({
1469
  geno_idx <- find.markerindex(res$cross, mk)
@@ -1473,60 +1245,45 @@ server <- function(input, output, session) {
1473
  filter(!is.na(geno), !is.na(pheno))
1474
  geno_labs <- c("1" = "AA", "2" = "AB", "3" = "BB")
1475
  df$geno <- dplyr::recode(df$geno, !!!geno_labs)
1476
-
1477
  ggplot(df, aes(x = geno, y = pheno, fill = geno)) +
1478
  geom_violin(alpha = .4, trim = FALSE) +
1479
  geom_boxplot(width = .15, outlier.color = "#c2185b", alpha = .7) +
1480
  scale_fill_manual(values = c("#1a6cf5","#e8500a","#18a058")) +
1481
- labs(title = paste("Phenotype by Genotype β€”", mk),
1482
- x = "Genotype", y = input$pheno_col) +
1483
  theme_qtl() + theme(legend.position = "none")
1484
- }, error = function(e) {
1485
- ggplot() + annotate("text", x=.5, y=.5, label="Unavailable", color="#8a95a3", size=5) + theme_qtl()
1486
- })
1487
  }, bg = "white")
1488
 
1489
  output$plot_pve <- renderPlot({
1490
  res <- analysis_results(); req(res)
1491
  qt <- res$qtl_table; req(!is.null(qt) && nrow(qt) > 0)
1492
-
1493
- qt_avg <- qt %>%
1494
- group_by(Chr, Peak_pos_cM) %>%
1495
- summarise(PVE = mean(PVE_pct, na.rm = TRUE), .groups = "drop")
1496
-
1497
  ggplot(qt_avg, aes(x = interaction(Chr, round(Peak_pos_cM)), y = PVE, fill = PVE)) +
1498
  geom_col(width = .7) +
1499
  scale_fill_gradientn(colors = c("#bcd0fc","#1a6cf5","#18a058","#c2185b"), name = "PVE%") +
1500
- geom_text(aes(label = paste0(round(PVE,1),"%")), vjust = -0.4, size = 3,
1501
- color = "#1a202c", family = "mono") +
1502
  labs(title = "PVE per QTL", x = "Chr @ Position", y = "PVE (%)") +
1503
- theme_qtl() + theme(axis.text.x = element_text(angle = 40, hjust = 1))
1504
  }, bg = "white")
1505
 
1506
  output$plot_2d_scan <- renderPlot({
1507
  res <- analysis_results(); req(res)
1508
-
1509
  sc2 <- tryCatch(
1510
  scantwo(res$cross, pheno.col = res$pheno_idx, method = "hk", verbose = FALSE),
1511
  error = function(e) NULL
1512
  )
1513
  if (is.null(sc2)) {
1514
- ggplot() + annotate("text", x=.5, y=.5,
1515
- label = "2D scan failed or insufficient data",
1516
- color = "#8a95a3", size=5) + theme_qtl()
1517
  } else {
1518
- lod_mat <- sc2$lod
1519
- n <- nrow(lod_mat)
1520
- df2d <- expand.grid(x = 1:n, y = 1:n)
1521
- df2d$lod <- as.vector(lod_mat)
1522
-
1523
- ggplot(df2d, aes(x=x, y=y, fill=lod)) +
1524
  geom_tile() +
1525
- scale_fill_gradientn(
1526
- colors = c("#f8f9fb","#bcd0fc","#1a6cf5","#18a058","#c2185b"),
1527
- name = "LOD", na.value = "#f8f9fb"
1528
- ) +
1529
- labs(title = "2D Genome Scan (Pairwise)", x = "Position 1", y = "Position 2") +
1530
  theme_qtl() + coord_equal()
1531
  }
1532
  }, bg = "white")
@@ -1535,45 +1292,37 @@ server <- function(input, output, session) {
1535
  cross <- cross_data(); req(cross)
1536
  miss <- nmissing(cross, what = "mar")
1537
  df <- data.frame(marker = names(miss), missing = miss)
1538
-
1539
  ggplot(df, aes(x = reorder(marker, missing), y = missing, fill = missing)) +
1540
  geom_col() +
1541
  scale_fill_gradientn(colors = c("#bcd0fc","#1a6cf5","#c2185b"), guide = "none") +
1542
  labs(title = "Missing Genotype Data", x = "Marker", y = "# Missing") +
1543
- theme_qtl() +
1544
- theme(axis.text.x = element_blank(), axis.ticks.x = element_blank())
1545
  }, bg = "white")
1546
 
1547
  output$plot_geno_freq <- renderPlot({
1548
  cross <- cross_data(); req(cross)
1549
  gt <- pull.geno(cross)
1550
- freq_A <- colMeans(gt == 1, na.rm = TRUE)
1551
- freq_B <- colMeans(gt == 2, na.rm = TRUE)
1552
- df <- data.frame(marker = names(freq_A), A = freq_A, B = freq_B) %>%
1553
- tidyr::pivot_longer(cols = c(A, B), names_to = "allele", values_to = "freq")
1554
-
1555
- ggplot(df, aes(x = marker, y = freq, fill = allele)) +
1556
- geom_col(position = "stack", width = 1) +
1557
- scale_fill_manual(values = c(A = "#1a6cf5", B = "#e8500a")) +
1558
- labs(title = "Allele Frequency per Marker", x = "Marker", y = "Frequency") +
1559
- theme_qtl() +
1560
- theme(axis.text.x = element_blank(), axis.ticks.x = element_blank())
1561
  }, bg = "white")
1562
 
1563
  output$plot_marker_dist <- renderPlot({
1564
  cross <- cross_data(); req(cross)
1565
  map <- pull.map(cross)
1566
- diffs <- unlist(lapply(map, function(m) if (length(m) > 1) diff(m) else numeric(0)))
1567
  df <- data.frame(dist = diffs)
1568
-
1569
- ggplot(df, aes(x = dist)) +
1570
- geom_histogram(fill = "#1a6cf5", color = "#ffffff", bins = 40, alpha = .8) +
1571
- geom_vline(xintercept = median(diffs), color = "#c2185b",
1572
- linetype = "dashed", linewidth = .8) +
1573
- labs(title = "Inter-Marker Distance",
1574
- subtitle = paste0("Median: ", round(median(diffs),1), " cM"),
1575
- x = "Distance (cM)", y = "Count") +
1576
- theme_qtl()
1577
  }, bg = "white")
1578
 
1579
  # ── TABLES ────────────────────────────────────────────────────────────────
@@ -1581,19 +1330,16 @@ server <- function(input, output, session) {
1581
  output$table_qtl_results <- renderDT({
1582
  res <- analysis_results(); req(res)
1583
  qt <- res$qtl_table; req(!is.null(qt) && nrow(qt) > 0)
1584
-
1585
- datatable(qt, rownames = FALSE,
1586
- options = list(pageLength = 20, scrollX = TRUE, dom = "Blfrtip",
1587
- columnDefs = list(list(className = "dt-center", targets = "_all"))),
1588
- class = "display nowrap") %>%
1589
  formatStyle("LOD",
1590
- background = styleColorBar(range(qt$LOD), "#bcd0fc"),
1591
- backgroundSize = "100% 80%", backgroundRepeat = "no-repeat",
1592
- backgroundPosition = "center") %>%
1593
  formatStyle("PVE_pct",
1594
- background = styleColorBar(c(0,100), "#b3dfc7"),
1595
- backgroundSize = "100% 80%", backgroundRepeat = "no-repeat",
1596
- backgroundPosition = "center") %>%
1597
  formatRound(c("Peak_pos_cM","LOD","PVE_pct","Left_pos_cM","Right_pos_cM","CI_width_cM"), 3)
1598
  })
1599
 
@@ -1601,35 +1347,27 @@ server <- function(input, output, session) {
1601
  res <- analysis_results(); req(res)
1602
  df <- data.frame(
1603
  Model = names(res$scan_results),
1604
- Max_LOD = round(sapply(res$scan_results, function(sc) max(sc$lod, na.rm=TRUE)), 3),
1605
- Mean_LOD = round(sapply(res$scan_results, function(sc) mean(sc$lod, na.rm=TRUE)), 3),
1606
- QTLs_Found = sapply(names(res$scan_results), function(m) {
1607
- if (!is.null(res$qtl_table) && nrow(res$qtl_table) > 0)
1608
- sum(res$qtl_table$Model == m) else 0
1609
- }),
1610
- Threshold = round(res$lod_thr, 3)
1611
  )
1612
- datatable(df, rownames = FALSE,
1613
- options = list(dom = "t", pageLength = 15),
1614
- class = "display") %>%
1615
- formatStyle("Max_LOD", color = "#1a6cf5", fontWeight = "bold") %>%
1616
- formatStyle("QTLs_Found", color = "#c2185b", fontWeight = "bold")
1617
  })
1618
 
1619
  output$table_perm_thresholds <- renderDT({
1620
- res <- analysis_results(); req(res)
1621
- req(length(res$perm_results) > 0)
1622
-
1623
  rows <- lapply(names(res$perm_results), function(m) {
1624
  p <- res$perm_results[[m]]; if (is.null(p)) return(NULL)
1625
- sm <- tryCatch(summary(p, alpha = c(0.05, 0.1, 0.2)), error = function(e) NULL)
1626
  if (is.null(sm)) return(NULL)
1627
- data.frame(Model = m, alpha_0.05 = round(sm[1],3),
1628
- alpha_0.10 = round(sm[2],3), alpha_0.20 = round(sm[3],3))
1629
  })
1630
- df <- dplyr::bind_rows(Filter(Negate(is.null), rows))
1631
- req(nrow(df) > 0)
1632
- datatable(df, rownames = FALSE, options = list(dom = "t"), class = "display")
1633
  })
1634
 
1635
  # ── Download ──────────────────────────────────────────────────────────────
@@ -1638,9 +1376,9 @@ server <- function(input, output, session) {
1638
  content = function(file) {
1639
  res <- analysis_results()
1640
  if (!is.null(res) && !is.null(res$qtl_table) && nrow(res$qtl_table) > 0)
1641
- write.csv(res$qtl_table, file, row.names = FALSE)
1642
  else
1643
- write.csv(data.frame(message = "No significant QTLs found"), file, row.names = FALSE)
1644
  }
1645
  )
1646
  }
 
12
  library(gridExtra)
13
  library(scales)
14
 
15
+ # ─── CUSTOM DATA PARSER ───────────────────────────────────────────────────────
16
+ # Handles the user's specific CSV layout:
17
+ # Genotype file:
18
+ # Row 1 : header β†’ id | marker1 | marker2 | ...
19
+ # Row 2 : chr β†’ 1 | chr01 | chr01 | ... (numeric chromosome ID or name)
20
+ # Row 3 : pos(cM) β†’ 0 | 0.22 | 0.60 | ...
21
+ # Rows 4+: data β†’ sampleID | 1|2|3... genotype calls
22
+ # Phenotype file:
23
+ # Row 1 : header β†’ id | trait1 | trait2 | ...
24
+ # Rows 2+: data β†’ sampleID | numeric values
25
+
26
+ parse_custom_cross <- function(geno_path, pheno_path, cross_type = "f2") {
27
+
28
+ # ── 1. Read raw genotype table ──────────────────────────────────────────────
29
+ geno_raw <- read.csv(geno_path, header = FALSE, stringsAsFactors = FALSE,
30
+ check.names = FALSE, na.strings = c("NA","","N/A"))
31
+
32
+ # Row 1 = column names
33
+ col_names <- as.character(geno_raw[1, ])
34
+ # Row 2 = chromosomes
35
+ chr_row <- as.character(geno_raw[2, ])
36
+ # Row 3 = positions (cM)
37
+ pos_row <- as.character(geno_raw[3, ])
38
+ # Rows 4+ = individual data
39
+ ind_data <- geno_raw[4:nrow(geno_raw), , drop = FALSE]
40
+
41
+ # Identify which columns are markers (everything except col 1 = id)
42
+ n_cols <- ncol(geno_raw)
43
+ marker_cols <- 2:n_cols
44
+
45
+ # Marker metadata
46
+ marker_names <- col_names[marker_cols]
47
+ chromosomes <- chr_row[marker_cols]
48
+ positions <- suppressWarnings(as.numeric(pos_row[marker_cols]))
49
+
50
+ # Clean chromosome labels: remove "chr"/"Chr" prefix β†’ keep number/name
51
+ chromosomes <- gsub("^[Cc]hr0*", "", chromosomes)
52
+ # If the chromosome value is purely numeric, ensure no leading zeros
53
+ chr_numeric <- suppressWarnings(as.integer(chromosomes))
54
+ chromosomes <- ifelse(!is.na(chr_numeric), as.character(chr_numeric), chromosomes)
55
+
56
+ # Individual IDs
57
+ ind_ids <- as.character(ind_data[, 1])
58
+
59
+ # Genotype matrix (individuals Γ— markers)
60
+ geno_mat <- as.matrix(ind_data[, marker_cols, drop = FALSE])
61
+ class(geno_mat) <- "numeric"
62
+ geno_mat <- apply(geno_mat, 2, function(x) suppressWarnings(as.numeric(x)))
63
+ rownames(geno_mat) <- ind_ids
64
+ colnames(geno_mat) <- marker_names
65
+
66
+ # ── 2. Read phenotype table ─────────────────────────────────────────────────
67
+ pheno_raw <- read.csv(pheno_path, header = TRUE, stringsAsFactors = FALSE,
68
+ check.names = FALSE, na.strings = c("NA","","N/A"))
69
+
70
+ pheno_ids <- as.character(pheno_raw[, 1])
71
+ pheno_df <- pheno_raw[, -1, drop = FALSE]
72
+ # Convert all phenotype columns to numeric
73
+ pheno_df <- as.data.frame(lapply(pheno_df, function(x) suppressWarnings(as.numeric(x))))
74
+ rownames(pheno_df) <- pheno_ids
75
+
76
+ # ── 3. Align individuals ────────────────────────────────────────────────────
77
+ common_ids <- intersect(ind_ids, pheno_ids)
78
+ if (length(common_ids) == 0)
79
+ stop(paste0(
80
+ "No matching individual IDs between genotype and phenotype files.\n",
81
+ " Genotype IDs (first 5): ", paste(head(ind_ids, 5), collapse=", "), "\n",
82
+ " Phenotype IDs (first 5): ", paste(head(pheno_ids, 5), collapse=", ")
83
+ ))
84
+
85
+ geno_mat <- geno_mat[common_ids, , drop = FALSE]
86
+ pheno_df <- pheno_df[common_ids, , drop = FALSE]
87
+
88
+ # ── 4. Build the genetic map ────────────────────────────────────────────────
89
+ unique_chrs <- unique(chromosomes)
90
+
91
+ # Sort chromosomes intelligently (numeric first, then alpha)
92
+ chr_num <- suppressWarnings(as.integer(unique_chrs))
93
+ ord <- order(ifelse(!is.na(chr_num), chr_num, 999L), unique_chrs)
94
+ unique_chrs <- unique_chrs[ord]
95
+
96
+ map_list <- lapply(unique_chrs, function(ch) {
97
+ idx <- which(chromosomes == ch)
98
+ pos <- positions[idx]
99
+ mnames <- marker_names[idx]
100
+ ord2 <- order(pos)
101
+ m <- pos[ord2]
102
+ names(m) <- mnames[ord2]
103
+ m
104
+ })
105
+ names(map_list) <- unique_chrs
106
+
107
+ # ── 5. Construct the cross object manually ──────────────────────────────────
108
+ # Build geno list (one entry per chromosome)
109
+ geno_list <- lapply(unique_chrs, function(ch) {
110
+ idx <- which(chromosomes == ch)
111
+ mnames <- marker_names[idx]
112
+ pos_ch <- positions[idx]
113
+ ord2 <- order(pos_ch)
114
+ mnames <- mnames[ord2]
115
+
116
+ g_chr <- geno_mat[, mnames, drop = FALSE]
117
+
118
+ # Recode genotypes to qtl conventions
119
+ # Input: 1=homozygous parent A, 2=heterozygous, 3=homozygous parent B (F2)
120
+ # 1=homozygous A, 2=homozygous B (BC)
121
+ # qtl package: f2 β†’ 1=AA, 2=AB, 3=BB; bc β†’ 1=AA, 2=AB
122
+ g_chr[g_chr == 0] <- NA # 0 often means missing
123
+ storage.mode(g_chr) <- "integer"
124
+
125
+ map_ch <- map_list[[ch]]
126
+
127
+ list(data = g_chr, map = map_ch)
128
+ })
129
+ names(geno_list) <- unique_chrs
130
+
131
+ # Assign class to each chromosome's map
132
+ for (ch in unique_chrs) {
133
+ class(geno_list[[ch]]$map) <- "A" # autosome
134
+ }
135
+
136
+ # ── 6. Assemble cross ───────────────────────────────────────────────────────
137
+ cross_obj <- list(
138
+ geno = geno_list,
139
+ pheno = pheno_df
140
+ )
141
+ class(cross_obj) <- c(cross_type, "cross")
142
+
143
+ # ── 7. Run basic checks / fixes ─────────────────────────────────────────────
144
+ cross_obj <- jittermap(cross_obj) # resolve duplicate positions
145
+ cross_obj <- convert2bcsft(cross_obj, BC.gen = 0, F.gen = 2,
146
+ estimate.map = FALSE) # only for f2; skip for others
147
+ # (this call is harmless for bc; if it errors, catch outside)
148
+
149
+ cross_obj
150
+ }
151
+
152
+
153
+ # ─── SAFE CROSS BUILDER ───────────────────────────────────────────────────────
154
+ safe_build_cross <- function(geno_path, pheno_path, cross_type) {
155
+ cross <- tryCatch(
156
+ parse_custom_cross(geno_path, pheno_path, cross_type),
157
+ error = function(e) {
158
+ # If the F2-specific convert call failed, retry without it
159
+ tryCatch({
160
+ gp <- parse_custom_cross_base(geno_path, pheno_path, cross_type)
161
+ gp
162
+ }, error = function(e2) stop(e2))
163
+ }
164
+ )
165
+ cross
166
+ }
167
+
168
+ # Version without convert2bcsft (for non-F2 cross types)
169
+ parse_custom_cross_base <- function(geno_path, pheno_path, cross_type = "bc") {
170
+ geno_raw <- read.csv(geno_path, header = FALSE, stringsAsFactors = FALSE,
171
+ check.names = FALSE, na.strings = c("NA","","N/A"))
172
+ col_names <- as.character(geno_raw[1, ])
173
+ chr_row <- as.character(geno_raw[2, ])
174
+ pos_row <- as.character(geno_raw[3, ])
175
+ ind_data <- geno_raw[4:nrow(geno_raw), , drop = FALSE]
176
+ n_cols <- ncol(geno_raw)
177
+ marker_cols <- 2:n_cols
178
+ marker_names <- col_names[marker_cols]
179
+ chromosomes <- chr_row[marker_cols]
180
+ positions <- suppressWarnings(as.numeric(pos_row[marker_cols]))
181
+ chromosomes <- gsub("^[Cc]hr0*", "", chromosomes)
182
+ chr_numeric <- suppressWarnings(as.integer(chromosomes))
183
+ chromosomes <- ifelse(!is.na(chr_numeric), as.character(chr_numeric), chromosomes)
184
+ ind_ids <- as.character(ind_data[, 1])
185
+ geno_mat <- as.matrix(ind_data[, marker_cols, drop = FALSE])
186
+ geno_mat <- apply(geno_mat, 2, function(x) suppressWarnings(as.numeric(x)))
187
+ rownames(geno_mat) <- ind_ids
188
+ colnames(geno_mat) <- marker_names
189
+
190
+ pheno_raw <- read.csv(pheno_path, header = TRUE, stringsAsFactors = FALSE,
191
+ check.names = FALSE, na.strings = c("NA","","N/A"))
192
+ pheno_ids <- as.character(pheno_raw[, 1])
193
+ pheno_df <- pheno_raw[, -1, drop = FALSE]
194
+ pheno_df <- as.data.frame(lapply(pheno_df, function(x) suppressWarnings(as.numeric(x))))
195
+ rownames(pheno_df) <- pheno_ids
196
+
197
+ common_ids <- intersect(ind_ids, pheno_ids)
198
+ if (length(common_ids) == 0)
199
+ stop(paste0("No matching IDs. Geno: ", paste(head(ind_ids,3), collapse=","),
200
+ " | Pheno: ", paste(head(pheno_ids,3), collapse=",")))
201
+ geno_mat <- geno_mat[common_ids, , drop = FALSE]
202
+ pheno_df <- pheno_df[common_ids, , drop = FALSE]
203
+
204
+ unique_chrs <- unique(chromosomes)
205
+ chr_num <- suppressWarnings(as.integer(unique_chrs))
206
+ ord <- order(ifelse(!is.na(chr_num), chr_num, 999L), unique_chrs)
207
+ unique_chrs <- unique_chrs[ord]
208
+
209
+ map_list <- lapply(unique_chrs, function(ch) {
210
+ idx <- which(chromosomes == ch)
211
+ pos <- positions[idx]
212
+ mnames <- marker_names[idx]
213
+ ord2 <- order(pos); m <- pos[ord2]; names(m) <- mnames[ord2]; m
214
+ })
215
+ names(map_list) <- unique_chrs
216
+
217
+ geno_list <- lapply(unique_chrs, function(ch) {
218
+ idx <- which(chromosomes == ch)
219
+ mnames <- marker_names[idx]
220
+ pos_ch <- positions[idx]
221
+ ord2 <- order(pos_ch); mnames <- mnames[ord2]
222
+ g_chr <- geno_mat[, mnames, drop = FALSE]
223
+ g_chr[g_chr == 0] <- NA
224
+ storage.mode(g_chr) <- "integer"
225
+ map_ch <- map_list[[ch]]
226
+ class(map_ch) <- "A"
227
+ list(data = g_chr, map = map_ch)
228
+ })
229
+ names(geno_list) <- unique_chrs
230
+
231
+ cross_obj <- list(geno = geno_list, pheno = pheno_df)
232
+ class(cross_obj) <- c(cross_type, "cross")
233
+ jittermap(cross_obj)
234
+ }
235
+
236
+
237
  # ─── UI ───────────────────────────────────────────────────────────────────────
238
  ui <- fluidPage(
239
  useShinyjs(),
 
261
  --shadow: 0 1px 4px rgba(0,0,0,0.07), 0 4px 16px rgba(0,0,0,0.05);
262
  --shadow-lg: 0 2px 8px rgba(0,0,0,0.08), 0 8px 32px rgba(0,0,0,0.07);
263
  }
 
264
  * { box-sizing: border-box; margin: 0; padding: 0; }
 
265
  body {
266
+ background: var(--bg); color: var(--text);
267
+ font-family: var(--font-body); min-height: 100vh; font-size: 14px;
 
 
 
268
  }
 
 
269
  .qtl-header {
270
+ background: #ffffff; border-bottom: 1.5px solid var(--border);
271
+ padding: 0 32px; height: 60px; display: flex; align-items: center;
272
+ gap: 16px; position: sticky; top: 0; z-index: 100;
 
 
 
 
 
 
 
273
  box-shadow: 0 1px 6px rgba(0,0,0,0.06);
274
  }
275
  .qtl-header .logo-mark {
276
+ width: 36px; height: 36px; background: var(--accent1); border-radius: 8px;
 
 
277
  display: flex; align-items: center; justify-content: center;
278
+ font-family: var(--font-mono); font-weight: 600; font-size: 13px;
279
+ color: #ffffff; flex-shrink: 0; letter-spacing: -0.5px;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
280
  }
281
+ .qtl-header h1 { font-family: var(--font-mono); font-size: 15px; color: var(--text); letter-spacing: 1px; font-weight: 600; }
282
+ .qtl-header .subtitle { font-size: 11px; color: var(--muted); letter-spacing: 0.3px; margin-top: 1px; }
283
+ .header-badges { margin-left: auto; display: flex; gap: 6px; }
284
+ .badge-pill { padding: 3px 10px; border-radius: 100px; font-size: 10px; font-family: var(--font-mono); letter-spacing: 0.5px; border: 1px solid; font-weight: 600; }
285
  .badge-pill.blue { color: var(--accent1); border-color: #bcd0fc; background: #eef3fe; }
286
  .badge-pill.green { color: var(--accent3); border-color: #b3dfc7; background: #edf7f2; }
287
  .badge-pill.orange { color: var(--accent2); border-color: #f8c4a8; background: #fef4ee; }
288
+ .qtl-layout { display: grid; grid-template-columns: 280px 1fr; height: calc(100vh - 60px); }
289
+ .qtl-sidebar { background: var(--panel); border-right: 1.5px solid var(--border); overflow-y: auto; padding: 20px 16px 32px; }
 
 
 
 
 
 
 
 
 
 
 
 
 
290
  .qtl-sidebar::-webkit-scrollbar { width: 4px; }
291
  .qtl-sidebar::-webkit-scrollbar-thumb { background: var(--border); border-radius: 4px; }
 
292
  .section-label {
293
+ font-family: var(--font-mono); font-size: 9px; letter-spacing: 2.5px;
294
+ color: var(--muted); text-transform: uppercase; margin-bottom: 10px;
295
+ margin-top: 22px; padding-left: 2px; display: flex; align-items: center; gap: 8px;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
296
  }
297
+ .section-label::after { content: ''; flex: 1; height: 1px; background: var(--border); }
298
  .section-label:first-child { margin-top: 0; }
 
 
299
  .qtl-upload {
300
+ border: 1.5px dashed var(--border); border-radius: 8px; padding: 12px;
301
+ transition: border-color .2s, background .2s; background: #ffffff; margin-bottom: 8px;
 
 
 
 
302
  }
303
  .qtl-upload:hover { border-color: var(--accent1); background: #f5f8ff; }
304
+ .qtl-upload label { font-size: 10px; color: var(--accent1); font-family: var(--font-mono); letter-spacing: 1px; margin-bottom: 5px; display: block; font-weight: 600; }
 
 
 
 
 
 
 
 
305
  .qtl-upload .shiny-input-container { margin: 0 !important; }
306
+ .format-help { font-size: 10px; color: var(--muted); font-family: var(--font-mono); line-height: 1.6; margin-top: 4px; padding: 6px 8px; background: var(--panel2); border-radius: 4px; }
307
+ .required-notice { background: #fff8e1; border: 1px solid #f5c842; border-radius: 6px; padding: 8px 11px; font-size: 11px; color: #7a5800; font-family: var(--font-mono); line-height: 1.5; margin-bottom: 10px; }
 
 
 
 
 
 
 
 
 
 
 
 
 
308
  .control-block { margin-bottom: 11px; }
309
+ .control-block label { font-size: 10px; color: var(--text2); letter-spacing: 0.8px; font-family: var(--font-mono); text-transform: uppercase; display: block; margin-bottom: 4px; font-weight: 600; }
310
+ select, input[type='number'], input[type='text'] { width: 100%; background: #ffffff; border: 1.5px solid var(--border); border-radius: 6px; color: var(--text); padding: 7px 10px; font-size: 12px; font-family: var(--font-body); outline: none; transition: border-color .2s; appearance: none; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
311
  select:focus, input:focus { border-color: var(--accent1); box-shadow: 0 0 0 3px rgba(26,108,245,0.1); }
312
+ .shiny-input-checkboxgroup .checkbox label { font-size: 11px; color: var(--text2); display: flex; align-items: center; gap: 6px; }
313
+ .btn-run { width: 100%; padding: 11px; background: var(--accent1); border: none; border-radius: 8px; color: #ffffff; font-family: var(--font-mono); font-size: 12px; font-weight: 600; letter-spacing: 1.5px; cursor: pointer; transition: background .2s, transform .1s, box-shadow .2s; margin-top: 16px; box-shadow: 0 2px 8px rgba(26,108,245,0.25); }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
314
  .btn-run:hover { background: #1558d4; transform: translateY(-1px); box-shadow: 0 4px 14px rgba(26,108,245,0.3); }
315
  .btn-run:active { transform: translateY(0); }
316
+ .btn-export { width: 100%; padding: 9px; background: #ffffff; border: 1.5px solid var(--accent3); border-radius: 8px; color: var(--accent3); font-family: var(--font-mono); font-size: 11px; font-weight: 600; letter-spacing: 1px; cursor: pointer; margin-top: 8px; transition: background .2s; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
317
  .btn-export:hover { background: #edf7f2; }
318
+ .status-row { display: flex; align-items: center; gap: 8px; padding: 8px 10px; background: #ffffff; border: 1.5px solid var(--border); border-radius: 6px; margin-top: 12px; font-size: 11px; color: var(--muted); font-family: var(--font-mono); }
319
+ .status-dot { width: 7px; height: 7px; border-radius: 50%; background: var(--muted); flex-shrink: 0; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
320
  .status-dot.active { background: var(--accent3); box-shadow: 0 0 5px rgba(24,160,88,0.5); }
321
  .status-dot.error { background: var(--accent2); box-shadow: 0 0 5px rgba(232,80,10,0.5); }
322
+ .qtl-main { overflow-y: auto; background: var(--bg); }
 
 
 
 
 
323
  .qtl-main::-webkit-scrollbar { width: 6px; }
324
  .qtl-main::-webkit-scrollbar-thumb { background: var(--border); border-radius: 4px; }
325
+ .qtl-tabs { display: flex; gap: 0; padding: 0 24px; border-bottom: 1.5px solid var(--border); background: #ffffff; position: sticky; top: 0; z-index: 50; overflow-x: auto; box-shadow: 0 1px 4px rgba(0,0,0,0.04); }
 
 
 
 
 
 
 
 
 
 
 
 
 
326
  .qtl-tabs::-webkit-scrollbar { display: none; }
327
+ .qtl-tab-btn { padding: 14px 16px; border: none; background: transparent; color: var(--muted); font-family: var(--font-mono); font-size: 10px; letter-spacing: 1px; text-transform: uppercase; cursor: pointer; border-bottom: 2.5px solid transparent; transition: color .2s, border-color .2s; white-space: nowrap; font-weight: 600; margin-bottom: -1.5px; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
328
  .qtl-tab-btn:hover { color: var(--text); }
329
  .qtl-tab-btn.active { color: var(--accent1); border-bottom-color: var(--accent1); }
 
 
330
  .tab-content { display: none; padding: 24px; }
331
  .tab-content.active { display: block; }
332
+ .plot-card { background: #ffffff; border: 1.5px solid var(--border); border-radius: 12px; overflow: hidden; margin-bottom: 20px; box-shadow: var(--shadow); }
333
+ .plot-card-header { display: flex; align-items: center; padding: 13px 18px; border-bottom: 1px solid var(--border); background: var(--panel); gap: 10px; }
334
+ .plot-card-icon { width: 28px; height: 28px; border-radius: 6px; display: flex; align-items: center; justify-content: center; font-size: 13px; flex-shrink: 0; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
335
  .plot-card-icon.blue { background: #eef3fe; }
336
  .plot-card-icon.orange { background: #fef4ee; }
337
  .plot-card-icon.green { background: #edf7f2; }
338
  .plot-card-icon.pink { background: #fce8f1; }
339
  .plot-card-icon.purple { background: #f3effe; }
340
+ .plot-card-title { font-family: var(--font-mono); font-size: 12px; color: var(--text); letter-spacing: 0.8px; font-weight: 600; }
 
 
 
 
 
 
341
  .plot-card-subtitle { font-size: 10px; color: var(--muted); margin-top: 1px; }
342
  .plot-card-body { padding: 16px; }
343
+ .stat-row { display: flex; gap: 10px; flex-wrap: wrap; margin-bottom: 20px; }
344
+ .stat-chip { padding: 10px 18px; border-radius: 10px; font-family: var(--font-mono); font-size: 12px; border: 1.5px solid; font-weight: 600; box-shadow: var(--shadow); }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
345
  .stat-chip.blue { background: #eef3fe; color: var(--accent1); border-color: #bcd0fc; }
346
  .stat-chip.orange { background: #fef4ee; color: var(--accent2); border-color: #f8c4a8; }
347
  .stat-chip.green { background: #edf7f2; color: var(--accent3); border-color: #b3dfc7; }
348
  .stat-chip.pink { background: #fce8f1; color: var(--accent4); border-color: #f0a8c8; }
 
 
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
+ .empty-state { text-align: center; padding: 60px 24px; color: var(--muted); }
 
 
 
 
 
 
354
  .empty-state .empty-icon { font-size: 48px; margin-bottom: 16px; }
355
  .empty-state h3 { font-size: 16px; color: var(--text2); margin-bottom: 8px; font-family: var(--font-mono); }
356
  .empty-state p { font-size: 13px; line-height: 1.6; max-width: 400px; margin: 0 auto; }
 
 
357
  .dataTables_wrapper { color: var(--text) !important; font-size: 12px; }
358
  table.dataTable { background: transparent !important; color: var(--text) !important; border-collapse: collapse !important; }
359
+ table.dataTable thead th { background: var(--panel) !important; color: var(--accent1) !important; font-family: var(--font-mono) !important; font-size: 10px !important; letter-spacing: 1px !important; border-bottom: 1.5px solid var(--border) !important; padding: 10px 12px !important; font-weight: 600 !important; }
 
 
 
 
 
 
 
 
 
360
  table.dataTable tbody tr { background: transparent !important; }
361
  table.dataTable tbody tr:hover td { background: #f5f8ff !important; }
362
  table.dataTable tbody td { border-bottom: 1px solid var(--border) !important; padding: 8px 12px !important; color: var(--text) !important; }
363
  .dataTables_info, .dataTables_paginate { color: var(--muted) !important; font-size: 11px !important; }
364
  .paginate_button { color: var(--text2) !important; }
365
  .paginate_button.current { background: var(--accent1) !important; color: #ffffff !important; border-radius: 4px !important; }
366
+ .dataTables_filter input, .dataTables_length select { background: #ffffff !important; border: 1.5px solid var(--border) !important; color: var(--text) !important; border-radius: 4px !important; padding: 4px 8px !important; }
367
+ .info-box { background: #f0f5ff; border: 1px solid #bcd0fc; border-radius: 8px; padding: 12px 16px; font-size: 12px; color: var(--text2); line-height: 1.6; margin-bottom: 16px; }
368
+ .error-box { background: #fff0ee; border: 1px solid #f8c4a8; border-radius: 8px; padding: 12px 16px; font-size: 12px; color: #7a1a00; line-height: 1.6; margin-bottom: 16px; font-family: var(--font-mono); }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
369
  hr.divider { border: none; border-top: 1px solid var(--border); margin: 20px 0; }
370
+ .parse-preview { font-family: var(--font-mono); font-size: 10px; color: var(--text2); background: var(--panel2); border-radius: 6px; padding: 10px 12px; margin-top: 8px; line-height: 1.7; border: 1px solid var(--border); }
 
 
 
 
 
 
 
 
 
 
 
371
  "))
372
  ),
373
 
 
374
  div(class = "qtl-header",
375
  div(class = "logo-mark", "QTL"),
376
+ div(tags$h1("QTL Mapper Pro"),
377
+ div(class = "subtitle", "Quantitative Trait Loci Analysis Pipeline")),
 
 
378
  div(class = "header-badges",
379
  div(class = "badge-pill blue", "R/QTL ENGINE"),
380
  div(class = "badge-pill green", "10+ MODELS"),
381
+ div(class = "badge-pill orange","MULTI-TRAIT"))
 
382
  ),
383
 
 
384
  div(class = "qtl-layout",
385
 
386
+ # ── Sidebar ──────────────────────────────────────────────────────────────
387
  div(class = "qtl-sidebar",
388
 
389
  div(class = "section-label", "Data Input"),
390
 
391
  div(class = "required-notice",
392
+ "⚠ Upload both CSV files.", tags$br(),
393
+ "Genotype: header + chr row + pos row + data rows.", tags$br(),
394
+ "Phenotype: header + data rows."
395
  ),
396
 
397
  div(class = "qtl-upload",
 
399
  fileInput("geno_file", NULL, accept = ".csv",
400
  buttonLabel = "Browse", placeholder = "genotypes.csv"),
401
  div(class = "format-help",
402
+ "Row 1: id | marker1 | marker2...", tags$br(),
403
+ "Row 2: (blank) | chr1 | chr1...", tags$br(),
404
+ "Row 3: (blank) | 0.22 | 0.60...", tags$br(),
405
+ "Row 4+: sampleID | 1|2|3..."
406
  )
407
  ),
408
 
 
411
  fileInput("pheno_file", NULL, accept = ".csv",
412
  buttonLabel = "Browse", placeholder = "phenotypes.csv"),
413
  div(class = "format-help",
414
+ "Row 1: id | trait1 | trait2...", tags$br(),
415
+ "Row 2+: sampleID | values..."
416
  )
417
  ),
418
 
419
+ # Preview of parsed data
420
+ uiOutput("parse_preview_ui"),
421
+
422
  div(class = "section-label", "Cross Type"),
423
  div(class = "control-block",
424
  selectInput("cross_type", NULL,
425
+ choices = c("Backcross" = "bc", "F2 Intercross" = "f2",
426
+ "RIL (selfing)" = "riself", "RIL (sib-mating)" = "risib"),
 
 
 
427
  selected = "f2")
428
  ),
429
 
 
440
  "Extended HK (ehk)" = "ehk",
441
  "Multiple Imputation (imp)" = "imp",
442
  "Composite Interval (cim)" = "cim",
 
443
  "Non-Parametric (np)" = "np",
444
+ "Marker Regression (mr)" = "mr"
 
 
445
  ),
446
+ selected = c("hk","em","imp","np","mr")
447
  ),
448
 
449
  div(class = "section-label", "Permutation"),
 
479
  )
480
  ),
481
 
482
+ # ── Main ─────────────────────────────────────────────────────────────────
483
  div(class = "qtl-main",
484
 
 
485
  div(class = "qtl-tabs",
486
+ tags$button(class = "qtl-tab-btn active", `data-tab` = "overview", "Overview"),
487
+ tags$button(class = "qtl-tab-btn", `data-tab` = "manhattan", "Manhattan"),
488
+ tags$button(class = "qtl-tab-btn", `data-tab` = "genome", "Genome Scan"),
489
+ tags$button(class = "qtl-tab-btn", `data-tab` = "chromosome", "Chr Plots"),
490
+ tags$button(class = "qtl-tab-btn", `data-tab` = "model_comp", "Model Compare"),
491
+ tags$button(class = "qtl-tab-btn", `data-tab` = "effects", "QTL Effects"),
492
+ tags$button(class = "qtl-tab-btn", `data-tab` = "pairwise", "2D Scan"),
493
+ tags$button(class = "qtl-tab-btn", `data-tab` = "diagnostics","Diagnostics"),
494
+ tags$button(class = "qtl-tab-btn", `data-tab` = "results", "QTL Table"),
495
+ tags$button(class = "qtl-tab-btn", `data-tab` = "summary", "Summary")
 
 
 
 
 
 
 
 
 
 
496
  ),
497
 
498
+ div(id = "tab_overview", class = "tab-content active", uiOutput("overview_content")),
499
+ div(id = "tab_manhattan", class = "tab-content", uiOutput("manhattan_content")),
500
+ div(id = "tab_genome", class = "tab-content", uiOutput("genome_content")),
501
+ div(id = "tab_chromosome", class = "tab-content", uiOutput("chromosome_content")),
502
+ div(id = "tab_model_comp", class = "tab-content", uiOutput("model_comp_content")),
503
+ div(id = "tab_effects", class = "tab-content", uiOutput("effects_content")),
504
+ div(id = "tab_pairwise", class = "tab-content", uiOutput("pairwise_content")),
505
+ div(id = "tab_diagnostics",class = "tab-content", uiOutput("diagnostics_content")),
506
+ div(id = "tab_results", class = "tab-content", uiOutput("results_content")),
507
+ div(id = "tab_summary", class = "tab-content", uiOutput("summary_content"))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
508
  )
509
  ),
510
 
 
511
  tags$script(HTML("
512
  document.querySelectorAll('.qtl-tab-btn').forEach(function(btn) {
513
  btn.addEventListener('click', function() {
 
520
  "))
521
  )
522
 
523
+
524
  # ─── SERVER ───────────────────────────────────────────────────────────────────
525
  server <- function(input, output, session) {
526
 
 
527
  theme_qtl <- function(base_size = 11) {
528
  theme_minimal(base_size = base_size) +
529
  theme(
530
+ plot.background = element_rect(fill = "#ffffff", color = NA),
531
+ panel.background = element_rect(fill = "#f8f9fb", color = NA),
532
+ panel.grid.major = element_line(color = "#e8ecf2", linewidth = .45),
533
+ panel.grid.minor = element_line(color = "#f1f4f8", linewidth = .25),
534
+ panel.border = element_rect(color = "#dde2ea", fill = NA, linewidth = .8),
535
+ axis.text = element_text(color = "#8a95a3", size = 9, family = "mono"),
536
+ axis.title = element_text(color = "#4a5568", size = 10),
537
+ plot.title = element_text(color = "#1a202c", size = 12, face = "bold", family = "mono"),
538
+ plot.subtitle = element_text(color = "#8a95a3", size = 9),
539
+ legend.background = element_rect(fill = "#ffffff", color = "#dde2ea", linewidth = .5),
540
+ legend.text = element_text(color = "#4a5568", size = 9),
541
+ legend.title = element_text(color = "#8a95a3", size = 9),
542
+ strip.background = element_rect(fill = "#f1f4f8", color = "#dde2ea"),
543
+ strip.text = element_text(color = "#1a6cf5", size = 9, family = "mono", face = "bold"),
544
+ plot.margin = margin(12, 16, 12, 16)
545
  )
546
  }
547
 
548
  model_colors <- c(
549
+ em = "#1a6cf5", hk = "#e8500a", ehk = "#18a058", imp = "#c2185b",
550
+ cim = "#7c3aed", np = "#0891b2", mr = "#dc2626"
 
 
 
 
 
 
 
 
551
  )
552
 
 
553
  empty_state_ui <- function(icon = "πŸ“‚", title = "No Data Loaded",
554
  msg = "Upload your genotype and phenotype CSV files, then click RUN ANALYSIS.") {
555
  div(class = "empty-state",
 
559
  )
560
  }
561
 
562
+ # ── Reactive: parse cross from uploaded CSVs ──────────────────────────────
563
  cross_data <- reactive({
564
  req(input$geno_file, input$pheno_file)
565
  tryCatch({
566
+ cross <- parse_custom_cross_base(
567
+ geno_path = input$geno_file$datapath,
568
+ pheno_path = input$pheno_file$datapath,
569
+ cross_type = input$cross_type
 
570
  )
571
  cross
572
  }, error = function(e) {
573
+ showNotification(paste0("Data loading error: ", e$message), type = "error", duration = 12)
574
  NULL
575
  })
576
  })
577
 
578
+ # ── Parse preview ─────────────────────────────────────────────────────────
579
+ output$parse_preview_ui <- renderUI({
580
+ req(input$geno_file, input$pheno_file)
581
  cross <- cross_data()
582
+ if (is.null(cross)) {
583
+ div(class = "error-box",
584
+ "❌ Failed to parse files.", tags$br(),
585
+ "Check that your genotype CSV has chr/pos rows in rows 2 and 3, and that individual IDs match between files."
586
+ )
587
+ } else {
588
+ div(class = "parse-preview",
589
+ paste0("βœ“ Loaded: ", totmar(cross), " markers, ",
590
+ nind(cross), " individuals, ", nchr(cross), " chromosomes"), tags$br(),
591
+ paste0(" Pheno traits: ", paste(names(cross$pheno), collapse=", "))
592
+ )
593
+ }
594
+ })
595
+
596
+ # ── Update phenotype dropdown ─────────────────────────────────────────────
597
+ observe({
598
+ cross <- cross_data(); req(cross)
599
  pheno_names <- names(cross$pheno)
600
  updateSelectInput(session, "pheno_col", choices = pheno_names, selected = pheno_names[1])
601
  runjs("document.getElementById('status_dot').classList.add('active')")
602
  output$status_text <- renderText(paste0(
603
+ totmar(cross), " markers Β· ", nind(cross), " inds Β· ", nchr(cross), " chrs β€” Ready"
 
 
604
  ))
605
  })
606
 
607
+ # ── Analysis results ──────────────────────────────────────────────────────
608
  analysis_results <- reactiveVal(NULL)
609
 
610
  observeEvent(input$run_analysis, {
611
  cross <- cross_data()
612
  if (is.null(cross)) {
613
+ showNotification("Please upload both CSV files first.", type = "warning"); return()
 
614
  }
615
 
616
  runjs("document.getElementById('status_dot').classList.remove('active')")
 
618
 
619
  withProgress(message = "QTL Mapping in progress...", value = 0, {
620
 
621
+ cross <- tryCatch(
622
+ calc.genoprob(cross, step = input$step_size, error.prob = input$error_prob),
623
+ error = function(e) { showNotification(paste("calc.genoprob failed:", e$message), type="error"); NULL }
624
+ )
625
+ req(cross)
626
  incProgress(0.1, detail = "Genoprobs calculated")
627
 
628
+ cross <- tryCatch(
629
+ sim.geno(cross, n.draws = 64, step = input$step_size, error.prob = input$error_prob),
630
+ error = function(e) cross # non-fatal; some methods don't need it
631
+ )
632
  incProgress(0.1, detail = "Simulated genotypes done")
633
 
634
  pheno_idx <- which(names(cross$pheno) == input$pheno_col)
635
+ if (length(pheno_idx) == 0) pheno_idx <- 1
636
 
637
  scan_results <- list()
638
  perm_results <- list()
639
  models_to_run <- input$models
640
+ if (length(models_to_run) == 0) models_to_run <- "hk"
641
 
642
  for (i in seq_along(models_to_run)) {
643
  mdl <- models_to_run[i]
644
+ incProgress(0.5 / length(models_to_run), detail = paste("Scanning:", mdl))
 
645
  sc <- tryCatch(
646
  scanone(cross, pheno.col = pheno_idx, method = mdl),
647
+ error = function(e) { message("scanone failed for ", mdl, ": ", e$message); NULL }
648
  )
649
  if (!is.null(sc)) {
650
  scan_results[[mdl]] <- sc
 
651
  if (input$n_perm > 0) {
652
  perm_results[[mdl]] <- tryCatch(
653
  scanone(cross, pheno.col = pheno_idx, method = mdl,
 
657
  }
658
  }
659
  }
660
+
661
+ if (length(scan_results) == 0) {
662
+ showNotification("All scan methods failed. Check your data.", type = "error"); return()
663
+ }
664
  incProgress(0.1, detail = "Summarising QTLs")
665
 
666
  lod_thr <- input$lod_thresh
667
  if (length(perm_results) > 0) {
668
  first_perm <- perm_results[[1]]
669
  if (!is.null(first_perm)) {
670
+ thr_try <- tryCatch(summary(first_perm, alpha = input$alpha_thresh)[[1]], error = function(e) NULL)
671
+ if (!is.null(thr_try) && is.numeric(thr_try)) lod_thr <- thr_try
672
  }
673
  }
674
 
675
  qtl_table <- build_qtl_table(cross, scan_results, lod_thr, pheno_idx)
676
+ incProgress(0.1, detail = "Done")
677
 
678
  analysis_results(list(
679
  cross = cross,
 
683
  qtl_table = qtl_table,
684
  pheno_idx = pheno_idx
685
  ))
 
 
686
  })
687
 
688
  res <- analysis_results()
689
+ if (is.null(res)) return()
690
+
691
  model_choices <- names(res$scan_results)
692
  updateSelectInput(session, "manhattan_model", choices = model_choices, selected = model_choices[1])
693
  updateSelectInput(session, "chr_plot_model", choices = model_choices, selected = model_choices[1])
 
703
  ))
704
  })
705
 
706
+ # ── Build QTL table ───────────────────────────────────────────────────────
707
  build_qtl_table <- function(cross, scan_results, lod_thr, pheno_idx) {
708
  rows <- list()
709
  for (mdl in names(scan_results)) {
 
719
  peak_marker <- rownames(peak_row)
720
 
721
  ci <- tryCatch(lodint(sc, chr = ch, drop = 1.5), error = function(e) NULL)
722
+ left_marker <- if (!is.null(ci)) rownames(ci)[1] else NA_character_
723
  right_marker <- if (!is.null(ci)) rownames(ci)[nrow(ci)] else NA_character_
724
+ left_pos <- if (!is.null(ci)) ci$pos[1] else NA_real_
725
+ right_pos <- if (!is.null(ci)) ci$pos[nrow(ci)] else NA_real_
 
 
 
 
 
 
 
726
 
727
  n <- nind(cross)
728
  pve <- round((1 - 10^(-2 * peak_lod / n)) * 100, 2)
 
734
  Peak_pos_cM = round(peak_pos, 2),
735
  LOD = round(peak_lod, 3),
736
  PVE_pct = pve,
 
 
737
  Left_Marker = left_marker,
738
  Left_pos_cM = round(left_pos, 2),
739
  Right_Marker = right_marker,
 
747
  dplyr::bind_rows(rows) %>% dplyr::arrange(Chr, Peak_pos_cM)
748
  }
749
 
 
750
  output$status_text <- renderText("Upload CSV files to begin")
751
 
752
  # ══════════════════════════════════════════════════════════════════════════
753
+ # TAB RENDERERS
754
  # ══════════════════════════════════════════════════════════════════════════
755
 
 
756
  output$overview_content <- renderUI({
757
  cross <- cross_data()
758
  if (is.null(cross)) return(empty_state_ui())
 
759
  tagList(
760
  div(class = "stat-row",
761
  div(class = "stat-chip blue", paste0(totmar(cross), " MARKERS")),
 
768
  div(class = "plot-card-header",
769
  div(class = "plot-card-icon blue", "πŸ“Š"),
770
  div(div(class = "plot-card-title", "GENOME MAP"),
771
+ div(class = "plot-card-subtitle", "Marker distribution per chromosome"))
772
  ),
773
  div(class = "plot-card-body",
774
  plotOutput("plot_genome_map", height = "320px") %>% withSpinner(color = "#1a6cf5", type = 4))
 
777
  div(class = "plot-card-header",
778
  div(class = "plot-card-icon orange", "πŸ“ˆ"),
779
  div(div(class = "plot-card-title", "PHENOTYPE DIST"),
780
+ div(class = "plot-card-subtitle", "Histogram + Q-Q plot"))
781
  ),
782
  div(class = "plot-card-body",
783
  plotOutput("plot_pheno_dist", height = "320px") %>% withSpinner(color = "#e8500a", type = 4))
 
801
  paste0(n, " QTLs FOUND")
802
  })
803
 
 
804
  output$manhattan_content <- renderUI({
805
  res <- analysis_results()
806
  if (is.null(res)) return(empty_state_ui("πŸŒƒ", "Run Analysis First",
807
  "Upload your CSV files and click RUN ANALYSIS to generate the Manhattan plot."))
808
  tagList(
809
  div(class = "info-box",
810
+ "Manhattan plot shows LOD score across all chromosomes. Red diamonds = significant QTLs above threshold."),
 
811
  div(class = "plot-card",
812
  div(class = "plot-card-header",
813
  div(class = "plot-card-icon blue", "πŸŒƒ"),
 
815
  div(class = "plot-card-subtitle", "LOD scores genome-wide"))
816
  ),
817
  div(class = "plot-card-body",
818
+ div(style = "max-width:200px; margin-bottom:12px;",
819
  selectInput("manhattan_model", "Model:", choices = names(res$scan_results))
820
  ),
821
  plotOutput("plot_manhattan", height = "420px") %>% withSpinner(color = "#1a6cf5", type = 4)
 
834
  )
835
  })
836
 
 
837
  output$genome_content <- renderUI({
838
  res <- analysis_results()
839
  if (is.null(res)) return(empty_state_ui("πŸ”¬", "Run Analysis First"))
 
844
  div(class = "plot-card-subtitle", "LOD profiles overlaid"))
845
  ),
846
  div(class = "plot-card-body",
847
+ plotOutput("plot_scan_all_models", height = "480px") %>% withSpinner(color = "#1a6cf5", type = 4))
 
848
  )
849
  })
850
 
 
851
  output$chromosome_content <- renderUI({
852
  res <- analysis_results()
853
  if (is.null(res)) return(empty_state_ui("πŸ“ˆ", "Run Analysis First"))
854
  tagList(
855
+ div(class = "info-box", "Per-chromosome LOD profiles. Red diamonds = significant QTL peaks."),
856
+ div(style = "max-width:200px; margin-bottom:16px;",
857
  selectInput("chr_plot_model", "Model:", choices = names(res$scan_results))
858
  ),
859
  plotOutput("plot_chr_grid", height = "900px") %>% withSpinner(color = "#18a058", type = 4)
860
  )
861
  })
862
 
 
863
  output$model_comp_content <- renderUI({
864
  res <- analysis_results()
865
  if (is.null(res)) return(empty_state_ui("βš–οΈ", "Run Analysis First"))
 
878
  div(class = "plot-card-header",
879
  div(class = "plot-card-icon pink", "πŸ”·"),
880
  div(div(class = "plot-card-title", "LOD HEATMAP"),
881
+ div(class = "plot-card-subtitle", "Top markers Γ— models"))
882
  ),
883
  div(class = "plot-card-body",
884
  plotOutput("plot_lod_heatmap", height = "340px") %>% withSpinner(color = "#c2185b", type = 4))
 
896
  )
897
  })
898
 
 
899
  output$effects_content <- renderUI({
900
  res <- analysis_results()
901
  if (is.null(res)) return(empty_state_ui("🎻", "Run Analysis First"))
 
907
  div(class = "plot-card-header",
908
  div(class = "plot-card-icon green", "🎻"),
909
  div(div(class = "plot-card-title", "EFFECT PLOT"),
910
+ div(class = "plot-card-subtitle", "Mean phenotype per genotype class"))
911
  ),
912
  div(class = "plot-card-body",
913
+ div(style = "margin-bottom:10px;",
914
  selectInput("effect_qtl", "Select QTL:", choices = qtl_choices)
915
  ),
916
  plotOutput("plot_effects", height = "320px") %>% withSpinner(color = "#18a058", type = 4)
 
920
  div(class = "plot-card-header",
921
  div(class = "plot-card-icon orange", "πŸ“¦"),
922
  div(div(class = "plot-card-title", "PHENOTYPE Γ— GENOTYPE"),
923
+ div(class = "plot-card-subtitle", "Violin + boxplot at peak marker"))
924
  ),
925
  div(class = "plot-card-body",
926
  plotOutput("plot_pheno_geno", height = "320px") %>% withSpinner(color = "#e8500a", type = 4))
 
930
  div(class = "plot-card-header",
931
  div(class = "plot-card-icon pink", "🌑"),
932
  div(div(class = "plot-card-title", "PVE PROFILE"),
933
+ div(class = "plot-card-subtitle", "Proportion of variance explained per QTL"))
934
  ),
935
  div(class = "plot-card-body",
936
  plotOutput("plot_pve", height = "280px") %>% withSpinner(color = "#c2185b", type = 4))
 
938
  )
939
  })
940
 
 
941
  output$pairwise_content <- renderUI({
942
  res <- analysis_results()
943
  if (is.null(res)) return(empty_state_ui("πŸ”²", "Run Analysis First"))
 
945
  div(class = "plot-card-header",
946
  div(class = "plot-card-icon blue", "πŸ”²"),
947
  div(div(class = "plot-card-title", "2D GENOME SCAN"),
948
+ div(class = "plot-card-subtitle", "Pairwise LOD / epistasis (HK method)"))
949
  ),
950
  div(class = "plot-card-body",
951
  plotOutput("plot_2d_scan", height = "560px") %>% withSpinner(color = "#1a6cf5", type = 4))
952
  )
953
  })
954
 
 
955
  output$diagnostics_content <- renderUI({
956
  cross <- cross_data()
957
+ if (is.null(cross)) return(empty_state_ui("πŸ”", "No Data Loaded"))
958
  tagList(
959
  div(class = "grid-2",
960
  div(class = "plot-card",
961
  div(class = "plot-card-header",
962
  div(class = "plot-card-icon orange", "πŸ”"),
963
  div(div(class = "plot-card-title", "MISSING DATA"),
964
+ div(class = "plot-card-subtitle", "Genotype completeness per marker"))
965
  ),
966
  div(class = "plot-card-body",
967
  plotOutput("plot_missing", height = "300px") %>% withSpinner(color = "#e8500a", type = 4))
 
970
  div(class = "plot-card-header",
971
  div(class = "plot-card-icon green", "πŸ“"),
972
  div(div(class = "plot-card-title", "GENOTYPE FREQ"),
973
+ div(class = "plot-card-subtitle", "Allele frequency stacked per marker"))
974
  ),
975
  div(class = "plot-card-body",
976
  plotOutput("plot_geno_freq", height = "300px") %>% withSpinner(color = "#18a058", type = 4))
 
980
  div(class = "plot-card-header",
981
  div(class = "plot-card-icon pink", "πŸ”—"),
982
  div(div(class = "plot-card-title", "MARKER DISTANCE"),
983
+ div(class = "plot-card-subtitle", "Inter-marker spacing histogram"))
984
  ),
985
  div(class = "plot-card-body",
986
  plotOutput("plot_marker_dist", height = "260px") %>% withSpinner(color = "#c2185b", type = 4))
 
988
  )
989
  })
990
 
 
991
  output$results_content <- renderUI({
992
  res <- analysis_results()
993
  if (is.null(res)) return(empty_state_ui("πŸ“‹", "Run Analysis First"))
 
995
  div(class = "plot-card-header",
996
  div(class = "plot-card-icon blue", "πŸ“‹"),
997
  div(div(class = "plot-card-title", "QTL RESULTS TABLE"),
998
+ div(class = "plot-card-subtitle", "Peak marker, LOD, PVE, confidence interval"))
999
  ),
1000
  div(class = "plot-card-body", DTOutput("table_qtl_results"))
1001
  )
1002
  })
1003
 
 
1004
  output$summary_content <- renderUI({
1005
  res <- analysis_results()
1006
  if (is.null(res)) return(empty_state_ui("πŸ“", "Run Analysis First"))
 
1008
  div(class = "plot-card",
1009
  div(class = "plot-card-header",
1010
  div(class = "plot-card-icon green", "πŸ“"),
1011
+ div(div(class = "plot-card-title", "MODEL SUMMARY"),
1012
+ div(class = "plot-card-subtitle", "Max LOD, QTLs found, threshold"))
1013
  ),
1014
  div(class = "plot-card-body", DTOutput("table_model_summary"))
1015
  ),
 
1035
  data.frame(chr = ch, pos = unname(map[[ch]]), stringsAsFactors = FALSE)
1036
  }))
1037
  df$chr <- factor(df$chr, levels = names(map))
 
1038
  ggplot(df, aes(x = chr, y = pos)) +
1039
  geom_segment(aes(xend = chr, yend = pos), color = "#dde2ea", linewidth = 8) +
1040
  geom_point(color = "#1a6cf5", size = 1.5, alpha = .8) +
1041
  scale_y_reverse() +
1042
+ labs(title = "Genetic Map", x = "Chromosome", y = "Position (cM)") + theme_qtl()
 
1043
  }, bg = "white")
1044
 
1045
  output$plot_pheno_dist <- renderPlot({
1046
+ cross <- cross_data(); req(cross, input$pheno_col)
1047
  ph <- cross$pheno[[input$pheno_col]]
1048
  df <- data.frame(value = ph[!is.na(ph)])
 
1049
  p1 <- ggplot(df, aes(value)) +
1050
  geom_histogram(fill = "#1a6cf5", color = "#ffffff", bins = 30, alpha = .8) +
1051
+ labs(title = input$pheno_col, x = "Value", y = "Count") + theme_qtl()
 
 
 
1052
  p2 <- ggplot(df, aes(sample = value)) +
1053
  stat_qq(color = "#18a058", size = 1.5, alpha = .8) +
1054
  stat_qq_line(color = "#c2185b", linewidth = .8) +
1055
+ labs(title = "Q-Q Plot", x = "Theoretical", y = "Sample") + theme_qtl()
 
 
1056
  gridExtra::grid.arrange(p1, p2, ncol = 2)
1057
  }, bg = "white")
1058
 
1059
  output$plot_physical_map <- renderPlot({
1060
  cross <- cross_data(); req(cross)
1061
  map <- pull.map(cross)
1062
+ df <- do.call(rbind, lapply(names(map), function(ch)
1063
+ data.frame(chr = ch, pos = unname(map[[ch]]), stringsAsFactors = FALSE)))
1064
+ chr_len <- df %>% group_by(chr) %>% summarise(len = max(pos), .groups="drop")
 
1065
  chr_len$chr <- factor(chr_len$chr, levels = names(map))
1066
+ df$chr <- factor(df$chr, levels = names(map))
1067
  ggplot() +
1068
  geom_rect(data = chr_len,
1069
+ aes(xmin = as.numeric(chr)-.35, xmax = as.numeric(chr)+.35, ymin = 0, ymax = len),
 
1070
  fill = "#e8ecf2", color = "#c8d0dc", linewidth = .7) +
1071
+ geom_point(data = df, aes(x = as.numeric(chr), y = pos),
 
1072
  color = "#1a6cf5", size = 1, alpha = .7) +
1073
  scale_x_continuous(breaks = seq_along(names(map)), labels = names(map)) +
1074
  scale_y_reverse() +
1075
+ labs(title = "Physical Map Overview", x = "Chromosome", y = "cM") + theme_qtl()
 
1076
  }, bg = "white")
1077
 
1078
  output$plot_manhattan <- renderPlot({
1079
  res <- analysis_results(); req(res)
1080
  mdl <- input$manhattan_model; req(mdl)
1081
  sc <- res$scan_results[[mdl]]; req(sc)
 
1082
  chrs <- unique(sc$chr)
1083
+ chr_offsets <- setNames(cumsum(c(0, sapply(chrs[-length(chrs)], function(ch) max(sc[sc$chr==ch,"pos"])))), chrs)
 
1084
  sc$global_pos <- sc$pos + chr_offsets[as.character(sc$chr)]
1085
  sc$chr_num <- as.integer(factor(sc$chr, levels = chrs))
1086
  sc$color <- ifelse(sc$chr_num %% 2 == 0, "#1a6cf5", "#5b9cf5")
1087
  sig <- sc[sc$lod >= res$lod_thr, ]
1088
  chr_mid <- tapply(sc$global_pos, sc$chr, mean)
 
1089
  ggplot(sc, aes(x = global_pos, y = lod)) +
1090
  geom_point(aes(color = color), size = 1.2, alpha = .75) +
1091
  scale_color_identity() +
1092
+ geom_point(data = sig, aes(x = global_pos, y = lod), color = "#c2185b", size = 2.5, shape = 18) +
1093
+ geom_hline(yintercept = res$lod_thr, color = "#e8500a", linetype = "dashed", linewidth = .8) +
 
 
 
 
 
1094
  scale_x_continuous(breaks = chr_mid, labels = names(chr_mid)) +
1095
+ labs(title = paste("Manhattan β€”", toupper(mdl)), x = "Chromosome", y = "LOD Score") +
 
1096
  theme_qtl() + theme(panel.grid.major.x = element_blank())
1097
  }, bg = "white")
1098
 
 
1100
  res <- analysis_results(); req(res)
1101
  mdl <- input$manhattan_model; req(mdl)
1102
  sc <- res$scan_results[[mdl]]; req(sc)
 
1103
  chrs <- unique(sc$chr)
1104
+ chr_offsets <- setNames(cumsum(c(0, sapply(chrs[-length(chrs)], function(ch) max(sc[sc$chr==ch,"pos"])))), chrs)
 
1105
  sc$global_pos <- sc$pos + chr_offsets[as.character(sc$chr)]
1106
+ sc$sig <- sc$lod >= res$lod_thr
1107
+ sc$label <- paste0(rownames(sc), "<br>Chr:", sc$chr, " Pos:", round(sc$pos,1), " LOD:", round(sc$lod,2))
1108
+ plot_ly(sc, x = ~global_pos, y = ~lod, color = ~sig, colors = c("#1a6cf5","#c2185b"),
 
 
 
1109
  text = ~label, hovertemplate = "%{text}<extra></extra>",
1110
+ type = "scatter", mode = "markers", marker = list(size = 4, opacity = .8)) %>%
1111
+ add_lines(y = res$lod_thr, line = list(color="#e8500a", dash="dash", width=1.5),
 
 
1112
  showlegend = FALSE, name = "Threshold") %>%
1113
+ layout(paper_bgcolor="#ffffff", plot_bgcolor="#f8f9fb",
1114
+ font = list(color="#4a5568", family="monospace"),
1115
+ xaxis = list(title="Position", gridcolor="#e8ecf2"),
1116
+ yaxis = list(title="LOD Score", gridcolor="#e8ecf2"),
1117
+ margin = list(t=10,b=40,l=50,r=20))
 
 
 
 
1118
  })
1119
 
1120
  output$plot_scan_all_models <- renderPlot({
1121
+ res <- analysis_results(); req(res, length(res$scan_results) > 0)
 
 
1122
  dfs <- lapply(names(res$scan_results), function(mdl) {
1123
  sc <- res$scan_results[[mdl]]
1124
  chrs <- unique(sc$chr)
1125
+ offsets <- setNames(cumsum(c(0, sapply(chrs[-length(chrs)], function(ch) max(sc[sc$chr==ch,"pos"])))), chrs)
 
1126
  sc$global_pos <- sc$pos + offsets[as.character(sc$chr)]
1127
  sc$model <- mdl; sc
1128
  })
1129
  df_all <- dplyr::bind_rows(dfs)
 
 
1130
  sc_ref <- res$scan_results[[1]]
1131
  chrs <- unique(sc_ref$chr)
1132
+ offsets <- setNames(cumsum(c(0, sapply(chrs[-length(chrs)], function(ch) max(sc_ref[sc_ref$chr==ch,"pos"])))), chrs)
 
1133
  vlines <- data.frame(x = offsets[-1])
 
1134
  ggplot(df_all, aes(x = global_pos, y = lod, color = model)) +
1135
  geom_vline(data = vlines, aes(xintercept = x), color = "#e8ecf2", linewidth = .5) +
1136
  geom_line(linewidth = .6, alpha = .85) +
1137
+ geom_hline(yintercept = res$lod_thr, color = "#e8500a", linetype = "dashed", linewidth = .7) +
 
1138
  scale_color_manual(values = model_colors) +
1139
+ labs(title = "Genome Scan β€” All Models", x = "Genome Position (cM)", y = "LOD Score", color = "Model") +
 
1140
  theme_qtl() + theme(legend.position = "right")
1141
  }, bg = "white")
1142
 
 
1145
  mdl <- input$chr_plot_model; req(mdl)
1146
  sc <- res$scan_results[[mdl]]; req(sc)
1147
  qt <- res$qtl_table
1148
+ chrs <- unique(sc$chr)
1149
+ n_cols <- min(4, length(chrs)); n_rows <- ceiling(length(chrs)/n_cols)
 
 
 
 
1150
  plots <- lapply(chrs, function(ch) {
1151
  chr_sc <- sc[sc$chr == ch, ]
1152
  p <- ggplot(chr_sc, aes(x = pos, y = lod)) +
1153
  geom_line(color = "#1a6cf5", linewidth = .9) +
1154
+ geom_hline(yintercept = res$lod_thr, color = "#e8500a", linetype = "dashed", linewidth = .6) +
 
 
1155
  scale_y_continuous(limits = c(0, max(sc$lod) * 1.1)) +
1156
  labs(title = paste0("Chr ", ch), x = NULL, y = "LOD") +
1157
+ theme_qtl(base_size = 9) + theme(plot.margin = margin(6,8,6,8))
 
 
 
 
1158
  if (!is.null(qt) && nrow(qt) > 0) {
1159
  qt_chr <- qt[qt$Chr == ch & qt$Model == mdl, ]
1160
+ if (nrow(qt_chr) > 0)
1161
+ p <- p + geom_point(data = qt_chr, aes(x = Peak_pos_cM, y = LOD),
1162
+ color = "#c2185b", size = 3, shape = 23, fill = "#c2185b")
 
 
 
 
 
 
 
 
 
1163
  }
1164
  p
1165
  })
 
1166
  do.call(gridExtra::grid.arrange, c(plots, list(ncol = n_cols, nrow = n_rows)))
1167
  }, bg = "white")
1168
 
1169
  output$plot_model_bar <- renderPlot({
1170
  res <- analysis_results(); req(res)
1171
+ df <- data.frame(model = names(res$scan_results),
1172
+ max_lod = sapply(res$scan_results, function(sc) max(sc$lod, na.rm=TRUE)))
 
 
1173
  df$model <- factor(df$model, levels = df$model[order(df$max_lod)])
 
1174
  ggplot(df, aes(x = model, y = max_lod, fill = model)) +
1175
  geom_col(width = .6, alpha = .85) +
1176
+ geom_hline(yintercept = res$lod_thr, color = "#e8500a", linetype = "dashed", linewidth = .8) +
1177
+ geom_text(aes(label = round(max_lod, 2)), hjust = -0.2, color = "#1a202c", size = 3, family = "mono") +
 
 
1178
  scale_fill_manual(values = model_colors) +
1179
  coord_flip(ylim = c(0, max(df$max_lod) * 1.15)) +
1180
  labs(title = "Peak LOD by Model", x = NULL, y = "Max LOD") +
 
1183
 
1184
  output$plot_lod_heatmap <- renderPlot({
1185
  res <- analysis_results(); req(res)
 
1186
  all_sc <- dplyr::bind_rows(lapply(names(res$scan_results), function(m) {
1187
+ sc <- res$scan_results[[m]]; sc$model <- m; sc$marker <- rownames(sc); sc
 
1188
  }))
1189
+ top_markers <- all_sc %>% group_by(marker) %>% summarise(max_lod = max(lod), .groups="drop") %>%
1190
+ arrange(desc(max_lod)) %>% slice_head(n = 40) %>% pull(marker)
 
 
 
 
 
1191
  hm <- all_sc %>% filter(marker %in% top_markers) %>% select(model, marker, lod)
 
1192
  ggplot(hm, aes(x = model, y = marker, fill = lod)) +
1193
  geom_tile(color = "#f8f9fb", linewidth = .3) +
1194
+ scale_fill_gradientn(colors = c("#f8f9fb","#bcd0fc","#1a6cf5","#18a058","#c2185b"), name = "LOD") +
 
 
 
1195
  labs(title = "LOD Heatmap", x = "Model", y = "Marker") +
1196
+ theme_qtl() + theme(axis.text.x = element_text(angle=30, hjust=1), axis.text.y = element_text(size=6))
 
 
1197
  }, bg = "white")
1198
 
1199
  output$plot_model_corr <- renderPlot({
1200
+ res <- analysis_results(); req(res, length(res$scan_results) >= 2)
 
 
1201
  sc_list <- lapply(names(res$scan_results), function(m) {
1202
  sc <- res$scan_results[[m]]
1203
  data.frame(marker = rownames(sc), lod = sc$lod, stringsAsFactors = FALSE)
1204
  })
1205
  names(sc_list) <- names(res$scan_results)
 
1206
  common_markers <- Reduce(intersect, lapply(sc_list, `[[`, "marker"))
1207
  mat <- sapply(sc_list, function(sc) sc$lod[match(common_markers, sc$marker)])
1208
  corr_mat <- cor(mat, use = "complete.obs")
1209
+ corr_df <- as.data.frame(as.table(corr_mat)); names(corr_df) <- c("m1","m2","corr")
 
 
1210
  ggplot(corr_df, aes(x = m1, y = m2, fill = corr)) +
1211
  geom_tile(color = "#ffffff", linewidth = .5) +
1212
+ geom_text(aes(label = round(corr,2)), size = 3, color = "#1a202c", family = "mono") +
1213
+ scale_fill_gradient2(low="#c2185b", mid="#f1f4f8", high="#1a6cf5", midpoint=0, limits=c(-1,1), name="r") +
 
1214
  labs(title = "Model LOD Correlation", x = NULL, y = NULL) +
1215
+ theme_qtl() + theme(axis.text.x = element_text(angle=30, hjust=1))
1216
  }, bg = "white")
1217
 
1218
  output$plot_effects <- renderPlot({
1219
  res <- analysis_results(); req(res)
1220
+ qtl_sel <- input$effect_qtl; req(qtl_sel, qtl_sel != "none")
1221
+ parts <- strsplit(qtl_sel, "@")[[1]]; mk <- parts[2]
 
 
 
1222
  tryCatch({
1223
  eff <- effectplot(res$cross, mname1 = mk, pheno.col = res$pheno_idx, draw = FALSE)
1224
  df <- data.frame(geno = names(eff$Means), mean = eff$Means, se = eff$SEs)
1225
  ggplot(df, aes(x = geno, y = mean, fill = geno)) +
1226
  geom_col(width = .5, alpha = .85) +
1227
+ geom_errorbar(aes(ymin = mean-se, ymax = mean+se), width = .15, color = "#4a5568", linewidth = .8) +
1228
+ scale_fill_manual(values = c("#1a6cf5","#c2185b","#18a058","#e8500a")) +
 
1229
  labs(title = paste("Effect Plot β€”", mk), x = "Genotype", y = "Mean Phenotype") +
1230
  theme_qtl() + theme(legend.position = "none")
1231
+ }, error = function(e)
1232
+ ggplot() + annotate("text",x=.5,y=.5,label=paste("Effect not available:", e$message),color="#8a95a3",size=4) + theme_qtl()
1233
+ )
1234
  }, bg = "white")
1235
 
1236
  output$plot_pheno_geno <- renderPlot({
1237
  res <- analysis_results(); req(res)
1238
  qtl_sel <- input$effect_qtl; req(qtl_sel != "none")
 
1239
  parts <- strsplit(qtl_sel, "@")[[1]]; mk <- parts[2]
1240
  tryCatch({
1241
  geno_idx <- find.markerindex(res$cross, mk)
 
1245
  filter(!is.na(geno), !is.na(pheno))
1246
  geno_labs <- c("1" = "AA", "2" = "AB", "3" = "BB")
1247
  df$geno <- dplyr::recode(df$geno, !!!geno_labs)
 
1248
  ggplot(df, aes(x = geno, y = pheno, fill = geno)) +
1249
  geom_violin(alpha = .4, trim = FALSE) +
1250
  geom_boxplot(width = .15, outlier.color = "#c2185b", alpha = .7) +
1251
  scale_fill_manual(values = c("#1a6cf5","#e8500a","#18a058")) +
1252
+ labs(title = paste("Phenotype by Genotype β€”", mk), x = "Genotype", y = input$pheno_col) +
 
1253
  theme_qtl() + theme(legend.position = "none")
1254
+ }, error = function(e)
1255
+ ggplot() + annotate("text",x=.5,y=.5,label=paste("Unavailable:", e$message),color="#8a95a3",size=4) + theme_qtl()
1256
+ )
1257
  }, bg = "white")
1258
 
1259
  output$plot_pve <- renderPlot({
1260
  res <- analysis_results(); req(res)
1261
  qt <- res$qtl_table; req(!is.null(qt) && nrow(qt) > 0)
1262
+ qt_avg <- qt %>% group_by(Chr, Peak_pos_cM) %>%
1263
+ summarise(PVE = mean(PVE_pct, na.rm=TRUE), .groups="drop")
 
 
 
1264
  ggplot(qt_avg, aes(x = interaction(Chr, round(Peak_pos_cM)), y = PVE, fill = PVE)) +
1265
  geom_col(width = .7) +
1266
  scale_fill_gradientn(colors = c("#bcd0fc","#1a6cf5","#18a058","#c2185b"), name = "PVE%") +
1267
+ geom_text(aes(label = paste0(round(PVE,1),"%")), vjust = -0.4, size = 3, color = "#1a202c", family = "mono") +
 
1268
  labs(title = "PVE per QTL", x = "Chr @ Position", y = "PVE (%)") +
1269
+ theme_qtl() + theme(axis.text.x = element_text(angle=40, hjust=1))
1270
  }, bg = "white")
1271
 
1272
  output$plot_2d_scan <- renderPlot({
1273
  res <- analysis_results(); req(res)
 
1274
  sc2 <- tryCatch(
1275
  scantwo(res$cross, pheno.col = res$pheno_idx, method = "hk", verbose = FALSE),
1276
  error = function(e) NULL
1277
  )
1278
  if (is.null(sc2)) {
1279
+ ggplot() + annotate("text",x=.5,y=.5,label="2D scan failed or insufficient data",color="#8a95a3",size=5) + theme_qtl()
 
 
1280
  } else {
1281
+ lod_mat <- sc2$lod; n <- nrow(lod_mat)
1282
+ df2d <- expand.grid(x=1:n, y=1:n); df2d$lod <- as.vector(lod_mat)
1283
+ ggplot(df2d, aes(x=x,y=y,fill=lod)) +
 
 
 
1284
  geom_tile() +
1285
+ scale_fill_gradientn(colors=c("#f8f9fb","#bcd0fc","#1a6cf5","#18a058","#c2185b"), name="LOD", na.value="#f8f9fb") +
1286
+ labs(title="2D Genome Scan (Pairwise)", x="Position 1", y="Position 2") +
 
 
 
1287
  theme_qtl() + coord_equal()
1288
  }
1289
  }, bg = "white")
 
1292
  cross <- cross_data(); req(cross)
1293
  miss <- nmissing(cross, what = "mar")
1294
  df <- data.frame(marker = names(miss), missing = miss)
 
1295
  ggplot(df, aes(x = reorder(marker, missing), y = missing, fill = missing)) +
1296
  geom_col() +
1297
  scale_fill_gradientn(colors = c("#bcd0fc","#1a6cf5","#c2185b"), guide = "none") +
1298
  labs(title = "Missing Genotype Data", x = "Marker", y = "# Missing") +
1299
+ theme_qtl() + theme(axis.text.x = element_blank(), axis.ticks.x = element_blank())
 
1300
  }, bg = "white")
1301
 
1302
  output$plot_geno_freq <- renderPlot({
1303
  cross <- cross_data(); req(cross)
1304
  gt <- pull.geno(cross)
1305
+ freq_A <- colMeans(gt == 1, na.rm=TRUE)
1306
+ freq_B <- colMeans(gt == 2, na.rm=TRUE)
1307
+ df <- data.frame(marker=names(freq_A), A=freq_A, B=freq_B) %>%
1308
+ tidyr::pivot_longer(cols=c(A,B), names_to="allele", values_to="freq")
1309
+ ggplot(df, aes(x=marker, y=freq, fill=allele)) +
1310
+ geom_col(position="stack", width=1) +
1311
+ scale_fill_manual(values=c(A="#1a6cf5", B="#e8500a")) +
1312
+ labs(title="Allele Frequency per Marker", x="Marker", y="Frequency") +
1313
+ theme_qtl() + theme(axis.text.x=element_blank(), axis.ticks.x=element_blank())
 
 
1314
  }, bg = "white")
1315
 
1316
  output$plot_marker_dist <- renderPlot({
1317
  cross <- cross_data(); req(cross)
1318
  map <- pull.map(cross)
1319
+ diffs <- unlist(lapply(map, function(m) if (length(m)>1) diff(m) else numeric(0)))
1320
  df <- data.frame(dist = diffs)
1321
+ ggplot(df, aes(x=dist)) +
1322
+ geom_histogram(fill="#1a6cf5", color="#ffffff", bins=40, alpha=.8) +
1323
+ geom_vline(xintercept=median(diffs), color="#c2185b", linetype="dashed", linewidth=.8) +
1324
+ labs(title="Inter-Marker Distance", subtitle=paste0("Median: ",round(median(diffs),1)," cM"),
1325
+ x="Distance (cM)", y="Count") + theme_qtl()
 
 
 
 
1326
  }, bg = "white")
1327
 
1328
  # ── TABLES ────────────────────────────────────────────────────────────────
 
1330
  output$table_qtl_results <- renderDT({
1331
  res <- analysis_results(); req(res)
1332
  qt <- res$qtl_table; req(!is.null(qt) && nrow(qt) > 0)
1333
+ datatable(qt, rownames=FALSE,
1334
+ options=list(pageLength=20, scrollX=TRUE, dom="Blfrtip",
1335
+ columnDefs=list(list(className="dt-center", targets="_all"))),
1336
+ class="display nowrap") %>%
 
1337
  formatStyle("LOD",
1338
+ background=styleColorBar(range(qt$LOD), "#bcd0fc"),
1339
+ backgroundSize="100% 80%", backgroundRepeat="no-repeat", backgroundPosition="center") %>%
 
1340
  formatStyle("PVE_pct",
1341
+ background=styleColorBar(c(0,100), "#b3dfc7"),
1342
+ backgroundSize="100% 80%", backgroundRepeat="no-repeat", backgroundPosition="center") %>%
 
1343
  formatRound(c("Peak_pos_cM","LOD","PVE_pct","Left_pos_cM","Right_pos_cM","CI_width_cM"), 3)
1344
  })
1345
 
 
1347
  res <- analysis_results(); req(res)
1348
  df <- data.frame(
1349
  Model = names(res$scan_results),
1350
+ Max_LOD = round(sapply(res$scan_results, function(sc) max(sc$lod,na.rm=TRUE)),3),
1351
+ Mean_LOD = round(sapply(res$scan_results, function(sc) mean(sc$lod,na.rm=TRUE)),3),
1352
+ QTLs_Found = sapply(names(res$scan_results), function(m)
1353
+ if (!is.null(res$qtl_table) && nrow(res$qtl_table)>0) sum(res$qtl_table$Model==m) else 0),
1354
+ Threshold = round(res$lod_thr,3)
 
 
1355
  )
1356
+ datatable(df, rownames=FALSE, options=list(dom="t", pageLength=15), class="display") %>%
1357
+ formatStyle("Max_LOD", color="#1a6cf5", fontWeight="bold") %>%
1358
+ formatStyle("QTLs_Found", color="#c2185b", fontWeight="bold")
 
 
1359
  })
1360
 
1361
  output$table_perm_thresholds <- renderDT({
1362
+ res <- analysis_results(); req(res, length(res$perm_results) > 0)
 
 
1363
  rows <- lapply(names(res$perm_results), function(m) {
1364
  p <- res$perm_results[[m]]; if (is.null(p)) return(NULL)
1365
+ sm <- tryCatch(summary(p, alpha=c(0.05,0.1,0.2)), error=function(e) NULL)
1366
  if (is.null(sm)) return(NULL)
1367
+ data.frame(Model=m, alpha_0.05=round(sm[1],3), alpha_0.10=round(sm[2],3), alpha_0.20=round(sm[3],3))
 
1368
  })
1369
+ df <- dplyr::bind_rows(Filter(Negate(is.null), rows)); req(nrow(df) > 0)
1370
+ datatable(df, rownames=FALSE, options=list(dom="t"), class="display")
 
1371
  })
1372
 
1373
  # ── Download ──────────────────────────────────────────────────────────────
 
1376
  content = function(file) {
1377
  res <- analysis_results()
1378
  if (!is.null(res) && !is.null(res$qtl_table) && nrow(res$qtl_table) > 0)
1379
+ write.csv(res$qtl_table, file, row.names=FALSE)
1380
  else
1381
+ write.csv(data.frame(message="No significant QTLs found"), file, row.names=FALSE)
1382
  }
1383
  )
1384
  }