softwareDevelopment commited on
Commit
ad737ae
·
verified ·
1 Parent(s): 257054c

Update app.R

Browse files
Files changed (1) hide show
  1. app.R +868 -686
app.R CHANGED
@@ -1,5 +1,7 @@
1
  library(shiny)
2
  library(htmltools)
 
 
3
 
4
  # ============================================================
5
  # HELPER: Parse uploaded genotype CSV (handles your format)
@@ -144,7 +146,7 @@ encode_additive <- function(X) {
144
  }
145
 
146
  # ---- 1. Single Marker Regression ----
147
- run_smr <- function(y, X, mpos, mchr) {
148
  n_m <- ncol(X)
149
  results <- data.frame(marker=colnames(X), position=mpos[seq_len(n_m)],
150
  chromosome=mchr[seq_len(n_m)], LOD=NA_real_, pvalue=NA_real_,
@@ -152,6 +154,10 @@ run_smr <- function(y, X, mpos, mchr) {
152
  stringsAsFactors=FALSE)
153
 
154
  for (j in seq_len(n_m)) {
 
 
 
 
155
  g <- X[, j]; valid <- !is.na(g)
156
  if (sum(valid) < 3) next
157
 
@@ -180,7 +186,7 @@ run_smr <- function(y, X, mpos, mchr) {
180
  }
181
 
182
  # ---- 2. Interval Mapping (Haley-Knott) ----
183
- run_im <- function(y, X, mpos, mchr) {
184
  Xa <- encode_additive(X)
185
  results <- data.frame(marker=colnames(X), position=mpos[seq_len(ncol(X))],
186
  chromosome=mchr[seq_len(ncol(X))], LOD=NA_real_, pvalue=NA_real_,
@@ -188,6 +194,10 @@ run_im <- function(y, X, mpos, mchr) {
188
  stringsAsFactors=FALSE)
189
 
190
  for (j in seq_len(ncol(Xa))) {
 
 
 
 
191
  g <- Xa[, j]; valid <- !is.na(g)
192
  if (sum(valid) < 3) next
193
 
@@ -210,7 +220,7 @@ run_im <- function(y, X, mpos, mchr) {
210
  }
211
 
212
  # ---- 3. Composite Interval Mapping ----
213
- run_cim <- function(y, X, mpos, mchr) {
214
  Xa <- encode_additive(X)
215
  results <- data.frame(marker=colnames(X), position=mpos[seq_len(ncol(X))],
216
  chromosome=mchr[seq_len(ncol(X))], LOD=NA_real_, pvalue=NA_real_,
@@ -218,6 +228,10 @@ run_cim <- function(y, X, mpos, mchr) {
218
  stringsAsFactors=FALSE)
219
 
220
  for (j in seq_len(ncol(Xa))) {
 
 
 
 
221
  cofactors <- setdiff(seq_len(ncol(Xa)), j)
222
  if (length(cofactors) == 0) next
223
 
@@ -248,16 +262,16 @@ run_cim <- function(y, X, mpos, mchr) {
248
  }
249
 
250
  # ---- 4. Multiple QTL Model ----
251
- run_mqm <- function(y, X, mpos, mchr) {
252
- res <- run_cim(y, X, mpos, mchr)
253
  res$model <- "Multiple QTL Model (MQM)"
254
  res$LOD <- res$LOD * runif(nrow(res), 0.92, 1.08)
255
  res
256
  }
257
 
258
  # ---- 5. Bayesian Interval Mapping ----
259
- run_bim <- function(y, X, mpos, mchr) {
260
- results <- run_im(y, X, mpos, mchr)
261
  results$model <- "Bayesian Interval Mapping"
262
  lambda <- 0.1
263
  for (j in seq_len(nrow(results))) {
@@ -270,7 +284,7 @@ run_bim <- function(y, X, mpos, mchr) {
270
  }
271
 
272
  # ---- 6. LASSO QTL ----
273
- run_lasso_qtl <- function(y, X, mpos, mchr) {
274
  Xa <- encode_additive(impute_markers(X))
275
  valid <- complete.cases(cbind(y, Xa))
276
  yv <- y[valid]
@@ -288,6 +302,9 @@ run_lasso_qtl <- function(y, X, mpos, mchr) {
288
  beta <- rep(0, p)
289
 
290
  for (iter in 1:50) {
 
 
 
291
  for (j in 1:p) {
292
  r <- yv - Xv %*% beta + Xv[,j] * beta[j]
293
  rho <- sum(Xv[,j] * r) / n
@@ -313,7 +330,7 @@ run_lasso_qtl <- function(y, X, mpos, mchr) {
313
  }
314
 
315
  # ---- 7. Ridge Regression QTL ----
316
- run_ridge_qtl <- function(y, X, mpos, mchr) {
317
  Xa <- encode_additive(impute_markers(X))
318
  valid <- complete.cases(cbind(y, Xa))
319
  yv <- y[valid]
@@ -327,6 +344,10 @@ run_ridge_qtl <- function(y, X, mpos, mchr) {
327
  R2=NA, additive=0, model="Ridge Regression QTL", stringsAsFactors=FALSE))
328
  }
329
 
 
 
 
 
330
  lambda <- 1.0
331
  XtX <- t(Xv) %*% Xv + lambda * diag(p)
332
  Xty <- t(Xv) %*% yv
@@ -349,7 +370,7 @@ run_ridge_qtl <- function(y, X, mpos, mchr) {
349
  }
350
 
351
  # ---- 8. Two-Way Epistasis ----
352
- run_epistasis <- function(y, X, mpos, mchr) {
353
  Xa <- encode_additive(impute_markers(X))
354
  n_m <- ncol(Xa)
355
 
@@ -359,10 +380,14 @@ run_epistasis <- function(y, X, mpos, mchr) {
359
  stringsAsFactors=FALSE)
360
 
361
  for (j in seq_len(n_m)) {
 
 
 
 
362
  partners <- setdiff(seq_len(n_m), j)
363
  lods <- c()
364
 
365
- for (k in partners[1:min(10, length(partners))]) { # Limit to 10 partners for speed
366
  tryCatch({
367
  g1 <- Xa[, j]
368
  g2 <- Xa[, k]
@@ -395,7 +420,7 @@ run_epistasis <- function(y, X, mpos, mchr) {
395
  }
396
 
397
  # ---- 9. Mixed Linear Model ----
398
- run_mlm <- function(y, X, mpos, mchr) {
399
  Xa <- encode_additive(impute_markers(X))
400
  n <- length(y)
401
 
@@ -405,6 +430,10 @@ run_mlm <- function(y, X, mpos, mchr) {
405
  stringsAsFactors=FALSE)
406
 
407
  for (j in seq_len(ncol(Xa))) {
 
 
 
 
408
  g <- Xa[, j]
409
  valid <- complete.cases(cbind(y, g))
410
  if (sum(valid) < 3) next
@@ -430,13 +459,17 @@ run_mlm <- function(y, X, mpos, mchr) {
430
  }
431
 
432
  # ---- 10. Kruskal-Wallis Non-Parametric ----
433
- run_kruskal <- function(y, X, mpos, mchr) {
434
  results <- data.frame(marker=colnames(X), position=mpos[seq_len(ncol(X))],
435
  chromosome=mchr[seq_len(ncol(X))], LOD=NA_real_, pvalue=NA_real_,
436
  R2=NA_real_, additive=NA_real_, model="Kruskal-Wallis (Non-Parametric)",
437
  stringsAsFactors=FALSE)
438
 
439
  for (j in seq_len(ncol(X))) {
 
 
 
 
440
  g <- X[, j]
441
  valid <- !is.na(g)
442
  if (sum(valid) < 3) next
@@ -462,7 +495,7 @@ run_kruskal <- function(y, X, mpos, mchr) {
462
  }
463
 
464
  # ---- Run all models ----
465
- run_all_models <- function(geno_df, pheno_df, trait, map_df) {
466
  cross <- prepare_cross(geno_df, pheno_df, trait)
467
  if (is.null(cross)) return(NULL)
468
 
@@ -487,30 +520,46 @@ run_all_models <- function(geno_df, pheno_df, trait, map_df) {
487
  mpos[is.na(mpos)] <- seq_pos[is.na(mpos)]
488
  }
489
 
490
- models <- list(
491
- run_smr(y, X, mpos, mchr),
492
- run_im(y, X, mpos, mchr),
493
- run_cim(y, X, mpos, mchr),
494
- run_mqm(y, X, mpos, mchr),
495
- run_bim(y, X, mpos, mchr),
496
- run_lasso_qtl(y, X, mpos, mchr),
497
- run_ridge_qtl(y, X, mpos, mchr),
498
- run_epistasis(y, X, mpos, mchr),
499
- run_mlm(y, X, mpos, mchr),
500
- run_kruskal(y, X, mpos, mchr)
501
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
502
 
503
  do.call(rbind, models)
504
  }
505
 
506
  # Permutation threshold
507
- permutation_threshold <- function(y, X, mpos, mchr, n_perm=100, alpha=0.05) {
508
  X_imp <- impute_markers(X)
509
  lod_max <- numeric(n_perm)
510
 
511
  for (i in seq_len(n_perm)) {
 
 
 
512
  yp <- sample(y)
513
- res <- run_smr(yp, X_imp, mpos, mchr)
514
  lod_max[i] <- max(res$LOD, na.rm=TRUE)
515
  }
516
 
@@ -554,474 +603,686 @@ make_map_template <- function() {
554
  # ============================================================
555
  ui <- fluidPage(
556
  tags$head(
557
- tags$link(rel="preconnect", href="https://fonts.googleapis.com"),
558
- tags$link(rel="preconnect", href="https://fonts.gstatic.com", crossorigin=NA),
559
- tags$link(href="https://fonts.googleapis.com/css2?family=Space+Mono:wght@400;700&family=Crimson+Pro:ital,wght@0,300;0,600;1,300&display=swap", rel="stylesheet"),
560
  tags$style(HTML("
 
561
  :root {
562
- --bg:#0a0e1a; --bg2:#0f1526; --bg3:#151d35; --panel:#1a2240;
563
- --accent:#00d4ff; --accent2:#ff6b35; --accent3:#39ff14; --gold:#ffd700;
564
- --text:#e8edf5; --text-dim:#7a8aaa; --border:rgba(0,212,255,0.2);
565
- --font-mono:'Space Mono',monospace; --font-serif:'Crimson Pro',serif;
566
- --glow:0 0 20px rgba(0,212,255,0.3);
567
- --ok:rgba(57,255,20,0.15); --warn:rgba(255,107,53,0.15);
568
- }
569
- *{box-sizing:border-box;margin:0;padding:0;}
570
- body{background:var(--bg);color:var(--text);font-family:var(--font-mono);min-height:100vh;overflow-x:hidden;}
571
- body::before{content:'';position:fixed;top:0;left:0;right:0;bottom:0;
572
- background:radial-gradient(ellipse at 20% 20%,rgba(0,212,255,0.04) 0%,transparent 60%),
573
- radial-gradient(ellipse at 80% 80%,rgba(255,107,53,0.03) 0%,transparent 60%);
574
- pointer-events:none;z-index:0;}
575
- .header-bar{background:linear-gradient(135deg,var(--bg2) 0%,var(--bg3) 100%);
576
- border-bottom:1px solid var(--border);padding:18px 32px;
577
- display:flex;align-items:center;gap:20px;position:relative;z-index:10;}
578
- .header-bar::after{content:'';position:absolute;bottom:0;left:0;right:0;height:1px;
579
- background:linear-gradient(90deg,transparent,var(--accent),var(--accent2),var(--accent3),transparent);}
580
- .header-title{font-family:var(--font-mono);font-size:1.3rem;font-weight:700;
581
- color:var(--accent);letter-spacing:.15em;text-transform:uppercase;}
582
- .header-sub{font-family:var(--font-serif);font-style:italic;font-size:.95rem;color:var(--text-dim);}
583
- .dna-icon{font-size:2rem;filter:drop-shadow(0 0 8px var(--accent));}
584
- .main-layout{display:flex;min-height:calc(100vh - 65px);position:relative;z-index:1;}
585
- .sidebar{width:270px;min-width:270px;background:var(--bg2);border-right:1px solid var(--border);
586
- padding:20px 16px;display:flex;flex-direction:column;gap:14px;overflow-y:auto;}
587
- .sidebar-section{background:var(--panel);border:1px solid var(--border);border-radius:8px;padding:14px;}
588
- .sidebar-label{font-size:.65rem;letter-spacing:.2em;text-transform:uppercase;color:var(--accent);
589
- margin-bottom:10px;border-bottom:1px solid var(--border);padding-bottom:6px;}
590
- .control-group{margin-bottom:12px;}
591
- .control-group label{display:block;font-size:.7rem;color:var(--text-dim);margin-bottom:5px;letter-spacing:.08em;}
592
- select,input[type=range]{width:100%;background:var(--bg);color:var(--text);
593
- border:1px solid var(--border);border-radius:4px;padding:6px 8px;
594
- font-family:var(--font-mono);font-size:.75rem;outline:none;transition:border-color .2s;}
595
- select:focus{border-color:var(--accent);box-shadow:var(--glow);}
596
- .run-btn{width:100%;padding:12px;background:linear-gradient(135deg,var(--accent) 0%,#0099bb 100%);
597
- color:var(--bg);border:none;border-radius:6px;font-family:var(--font-mono);font-size:.8rem;
598
- font-weight:700;letter-spacing:.12em;text-transform:uppercase;cursor:pointer;
599
- transition:all .2s;box-shadow:0 4px 15px rgba(0,212,255,.3);}
600
- .run-btn:hover{transform:translateY(-1px);box-shadow:0 6px 25px rgba(0,212,255,.5);}
601
- .perm-btn{width:100%;padding:10px;background:linear-gradient(135deg,var(--accent2) 0%,#cc4400 100%);
602
- color:var(--text);border:none;border-radius:6px;font-family:var(--font-mono);font-size:.75rem;
603
- font-weight:700;letter-spacing:.1em;text-transform:uppercase;cursor:pointer;
604
- transition:all .2s;margin-top:6px;box-shadow:0 4px 15px rgba(255,107,53,.3);}
605
- .perm-btn:hover{transform:translateY(-1px);box-shadow:0 6px 25px rgba(255,107,53,.5);}
606
- .stat-box{background:var(--bg);border:1px solid var(--border);border-radius:6px;
607
- padding:10px;text-align:center;margin-bottom:8px;}
608
- .stat-val{font-size:1.4rem;color:var(--accent);font-weight:700;}
609
- .stat-lbl{font-size:.6rem;color:var(--text-dim);letter-spacing:.15em;text-transform:uppercase;}
610
- .content-area{flex:1;padding:20px;overflow-y:auto;display:flex;flex-direction:column;gap:20px;}
611
- .tab-bar{display:flex;gap:4px;background:var(--bg2);border:1px solid var(--border);
612
- border-radius:8px;padding:4px;flex-wrap:wrap;}
613
- .tab-btn{padding:8px 14px;background:transparent;color:var(--text-dim);border:none;border-radius:5px;
614
- font-family:var(--font-mono);font-size:.7rem;letter-spacing:.1em;text-transform:uppercase;
615
- cursor:pointer;transition:all .2s;white-space:nowrap;}
616
- .tab-btn.active{background:var(--panel);color:var(--accent);border:1px solid var(--border);box-shadow:var(--glow);}
617
- .tab-btn:hover:not(.active){color:var(--text);}
618
- .panel-card{background:var(--bg2);border:1px solid var(--border);border-radius:10px;overflow:hidden;}
619
- .panel-card-header{background:var(--panel);padding:12px 20px;border-bottom:1px solid var(--border);
620
- display:flex;align-items:center;justify-content:space-between;}
621
- .panel-card-title{font-size:.75rem;letter-spacing:.18em;text-transform:uppercase;color:var(--accent);}
622
- .panel-card-body{padding:16px;}
623
- .plot-container{width:100%;background:var(--bg);border-radius:6px;overflow:hidden;position:relative;}
624
- .results-grid{display:grid;grid-template-columns:1fr 1fr;gap:16px;}
625
- .results-grid-3{display:grid;grid-template-columns:1fr 1fr 1fr;gap:16px;}
626
- table.qtl-table{width:100%;border-collapse:collapse;font-size:.7rem;}
627
- table.qtl-table thead th{background:var(--panel);color:var(--accent);padding:8px 10px;
628
- text-align:left;border-bottom:1px solid var(--border);letter-spacing:.1em;
629
- text-transform:uppercase;position:sticky;top:0;}
630
- table.qtl-table tbody tr{border-bottom:1px solid rgba(255,255,255,.04);}
631
- table.qtl-table tbody tr:hover{background:var(--panel);}
632
- table.qtl-table tbody td{padding:7px 10px;color:var(--text-dim);}
633
- table.qtl-table tbody td:nth-child(4){color:var(--accent3);font-weight:700;}
634
- .sig-row td{color:var(--text)!important;}.sig-row td:nth-child(4){color:var(--gold)!important;}
635
- .badge{display:inline-block;padding:2px 7px;border-radius:3px;font-size:.6rem;
636
- letter-spacing:.1em;text-transform:uppercase;font-weight:700;}
637
- .badge-sig{background:rgba(57,255,20,.15);color:var(--accent3);border:1px solid rgba(57,255,20,.3);}
638
- .badge-ns{background:rgba(255,255,255,.05);color:var(--text-dim);border:1px solid rgba(255,255,255,.1);}
639
- .threshold-badge{display:inline-block;padding:3px 10px;background:rgba(255,215,0,.1);
640
- border:1px solid rgba(255,215,0,.3);color:var(--gold);border-radius:4px;
641
- font-size:.7rem;letter-spacing:.1em;}
642
- .export-btn{padding:7px 14px;background:var(--bg);color:var(--accent);
643
- border:1px solid var(--border);border-radius:4px;font-family:var(--font-mono);
644
- font-size:.65rem;letter-spacing:.1em;cursor:pointer;transition:all .2s;}
645
- .export-btn:hover{border-color:var(--accent);box-shadow:var(--glow);}
646
- .scrollable-table{max-height:400px;overflow-y:auto;}
647
- .env-tag{display:inline-block;padding:2px 8px;border-radius:3px;font-size:.65rem;font-weight:700;letter-spacing:.08em;}
648
- .env1{background:rgba(0,212,255,.15);color:var(--accent);border:1px solid rgba(0,212,255,.3);}
649
- .env2{background:rgba(255,107,53,.15);color:var(--accent2);border:1px solid rgba(255,107,53,.3);}
650
-
651
- /* ====== UPLOAD STYLES (Fixed) ====== */
652
- .upload-file-input {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
653
  width: 100%;
654
  padding: 10px;
655
- background: var(--bg);
656
- color: var(--text);
657
- border: 1px solid var(--border);
658
- border-radius: 4px;
659
- font-family: var(--font-mono);
660
- font-size: .75rem;
661
  cursor: pointer;
 
 
 
 
 
 
 
 
 
 
 
 
662
  }
663
- .upload-file-input::-webkit-file-upload-button {
664
- background: var(--accent);
665
- color: var(--bg);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
666
  border: none;
667
- padding: 6px 12px;
668
- border-radius: 4px;
 
669
  cursor: pointer;
670
- font-family: var(--font-mono);
671
- font-weight: 700;
672
- margin-right: 10px;
673
- }
674
- .upload-file-input:hover {
675
- border-color: var(--accent);
676
- }
677
- .file-status{margin-top:8px;font-size:.65rem;padding:5px 8px;border-radius:4px;}
678
- .file-ok{background:var(--ok);color:var(--accent3);border:1px solid rgba(57,255,20,.3);}
679
- .file-warn{background:var(--warn);color:var(--accent2);border:1px solid rgba(255,107,53,.3);}
680
- .file-info{background:rgba(0,212,255,.08);color:var(--accent);border:1px solid var(--border);}
681
- .upload-sep{text-align:center;font-size:.6rem;color:var(--text-dim);margin:6px 0;letter-spacing:.15em;}
682
- .tmpl-btn{width:100%;padding:7px;background:transparent;color:var(--text-dim);
683
- border:1px solid var(--border);border-radius:4px;font-family:var(--font-mono);
684
- font-size:.65rem;letter-spacing:.08em;cursor:pointer;transition:all .2s;margin-top:4px;}
685
- .tmpl-btn:hover{color:var(--accent);border-color:var(--accent);}
686
- .data-preview{background:var(--bg);border:1px solid var(--border);border-radius:6px;
687
- padding:12px;font-size:.65rem;color:var(--text-dim);overflow-x:auto;max-height:180px;overflow-y:auto;}
688
- .data-preview table{width:100%;border-collapse:collapse;}
689
- .data-preview th{color:var(--accent);padding:4px 8px;border-bottom:1px solid var(--border);
690
- text-align:left;font-size:.62rem;letter-spacing:.08em;white-space:nowrap;}
691
- .data-preview td{padding:3px 8px;border-bottom:1px solid rgba(255,255,255,.04);white-space:nowrap;}
692
- .format-hint{background:rgba(0,212,255,.06);border:1px solid var(--border);border-radius:6px;
693
- padding:10px;font-size:.65rem;color:var(--text-dim);line-height:1.7;margin-top:8px;}
694
- .format-hint code{color:var(--accent3);font-family:var(--font-mono);}
695
- .spinner{width:36px;height:36px;border:3px solid var(--border);border-top-color:var(--accent);
696
- border-radius:50%;animation:spin .8s linear infinite;margin:0 auto;}
697
- @keyframes spin{to{transform:rotate(360deg);}}
698
- #loadingScreen{position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(10,14,26,.95);
699
- display:flex;flex-direction:column;align-items:center;justify-content:center;z-index:9999;gap:16px;}
700
- .loading-text{font-size:.8rem;color:var(--accent);letter-spacing:.2em;text-transform:uppercase;}
701
- #mainContent{display:none;}
702
- "))
703
- ),
704
-
705
- # Loading screen
706
- tags$div(id="loadingScreen",
707
- tags$div(class="spinner"),
708
- tags$div(class="loading-text", "Initializing QTL Engine"),
709
- tags$script(HTML("
710
- Shiny.addCustomMessageHandler('hideLoading', function(msg){
711
- document.getElementById('loadingScreen').style.display='none';
712
- document.getElementById('mainContent').style.display='block';
713
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
714
  "))
715
  ),
716
-
717
- tags$div(id="mainContent",
718
- # Header
719
- tags$div(class="header-bar",
720
- tags$span(class="dna-icon","🧬"),
721
- tags$div(
722
- tags$div(class="header-title","QTL Cartographer"),
723
- tags$div(class="header-sub","Quantitative Trait Loci Analysis Suite — Upload Your Data")
724
- ),
725
- tags$div(style="margin-left:auto;display:flex;gap:10px;",
726
- tags$div(class="threshold-badge","Oryza sativa / Any Organism"),
727
- tags$div(class="threshold-badge", id="permThreshBadge","Perm. Threshold: —")
728
- )
729
  ),
730
-
731
- tags$div(class="main-layout",
732
- # Sidebar
733
- tags$div(class="sidebar",
734
-
735
- # ---- DATA UPLOAD SECTION (Fixed) ----
736
- tags$div(class="sidebar-section",
737
- tags$div(class="sidebar-label","📂 Upload Your Data"),
738
-
739
- # Genotype file
740
- tags$div(class="control-group",
741
- tags$label("Genotype File (CSV)"),
742
- fileInput("geno_file", NULL, accept=".csv",
743
- buttonLabel="Browse...", placeholder="No file selected"),
744
- uiOutput("geno_status")
745
- ),
746
-
747
- # Phenotype file
748
- tags$div(class="control-group",
749
- tags$label("Phenotype File (CSV)"),
750
- fileInput("pheno_file", NULL, accept=".csv",
751
- buttonLabel="Browse...", placeholder="No file selected"),
752
- uiOutput("pheno_status")
753
- ),
754
-
755
- # Map file
756
- tags$div(class="control-group",
757
- tags$label("Genetic Map File (CSV)"),
758
- fileInput("map_file", NULL, accept=".csv",
759
- buttonLabel="Browse...", placeholder="No file selected"),
760
- uiOutput("map_status")
761
- ),
762
-
763
- tags$div(class="upload-sep","— OR DOWNLOAD TEMPLATES —"),
764
- downloadButton("dl_geno_tmpl", "⬇ Genotype Template", class="tmpl-btn"),
765
- downloadButton("dl_pheno_tmpl", "⬇ Phenotype Template", class="tmpl-btn"),
766
- downloadButton("dl_map_tmpl", "⬇ Map Template", class="tmpl-btn")
767
  ),
768
-
769
- # Analysis Config
770
- tags$div(class="sidebar-section",
771
- tags$div(class="sidebar-label","Analysis Config"),
772
- tags$div(class="control-group",
773
- tags$label("Select Trait"),
774
- uiOutput("trait_selector")
775
- ),
776
- tags$div(class="control-group",
777
- tags$label("LOD Threshold"),
778
- tags$input(type="range", id="lodThresh", min="1", max="10", step="0.1", value="2.5",
779
- oninput="Shiny.setInputValue('lod_threshold',parseFloat(this.value));document.getElementById('lodThreshVal').textContent=parseFloat(this.value).toFixed(1)")
780
- ),
781
- tags$div(style="text-align:center;font-size:.75rem;color:var(--accent);margin-bottom:8px;",
782
- "LOD = ", tags$span(id="lodThreshVal","2.5")
783
- ),
784
- tags$button(class="run-btn", onclick="Shiny.setInputValue('run_analysis',Math.random())","▶ Run Analysis"),
785
- tags$button(class="perm-btn",onclick="Shiny.setInputValue('run_perm',Math.random())","⚡ Permute (100×)")
786
  ),
787
-
788
- # Dataset Summary
789
- tags$div(class="sidebar-section",
790
- tags$div(class="sidebar-label","Dataset Summary"),
791
- uiOutput("dataset_summary_ui")
792
  ),
793
-
794
- # QTL Detected
795
- tags$div(class="sidebar-section",
796
- tags$div(class="sidebar-label","QTL Detected"),
797
- uiOutput("qtlSummaryUI")
798
- )
799
  ),
800
-
801
- # Content area
802
- tags$div(class="content-area",
803
- # Tab bar
804
- tags$div(class="tab-bar",
805
- tags$button(class="tab-btn active", id="tab_upload", onclick="switchTab('upload')", "📂 Data Upload"),
806
- tags$button(class="tab-btn", id="tab_lod", onclick="switchTab('lod')", "LOD Profile"),
807
- tags$button(class="tab-btn", id="tab_multi", onclick="switchTab('multi')", "Multi-Model"),
808
- tags$button(class="tab-btn", id="tab_effects",onclick="switchTab('effects')","QTL Effects"),
809
- tags$button(class="tab-btn", id="tab_circos", onclick="switchTab('circos')", "Circos"),
810
- tags$button(class="tab-btn", id="tab_pheno", onclick="switchTab('pheno')", "Phenotype"),
811
- tags$button(class="tab-btn", id="tab_results",onclick="switchTab('results')","Results Table"),
812
- tags$button(class="tab-btn", id="tab_summary",onclick="switchTab('summary')","Summary")
813
  ),
814
- tags$script(HTML("
815
- function switchTab(name){
816
- document.querySelectorAll('.tab-btn').forEach(b=>b.classList.remove('active'));
817
- document.querySelectorAll('.tab-pane').forEach(p=>p.style.display='none');
818
- document.getElementById('tab_'+name).classList.add('active');
819
- document.getElementById('pane_'+name).style.display='block';
820
- }
821
- ")),
822
-
823
- # ---- UPLOAD / DATA PREVIEW PANE ----
824
- tags$div(id="pane_upload", class="tab-pane",
825
- tags$div(class="panel-card",
826
- tags$div(class="panel-card-header",
827
- tags$div(class="panel-card-title","Data Upload & Format Guide"),
828
- uiOutput("data_ready_badge")
829
- ),
830
- tags$div(class="panel-card-body",
831
- tags$div(class="results-grid-3",
832
- # Genotype format
833
- tags$div(
834
- tags$div(class="panel-card-title", style="margin-bottom:8px;","Genotype CSV Format"),
835
- tags$div(class="format-hint",
836
- tags$b(style="color:var(--accent);","Required format:"), tags$br(),
837
- HTML("<code>id</code> — unique line/sample identifier (first column)"), tags$br(),
838
- HTML("<code>MarkerName</code> — one column per marker (marker names in row 1)"), tags$br(), tags$br(),
839
- tags$b(style="color:var(--accent);","Genotype codes:"), tags$br(),
840
- HTML("<code>1</code> = AA (Parent 1 homozygous)"), tags$br(),
841
- HTML("<code>2</code> = BB (Parent 2 homozygous)"), tags$br(),
842
- HTML("<code>0</code> = AB (Heterozygous)"), tags$br(),
843
- HTML("<code>-1</code> or blank = Missing data"), tags$br(), tags$br(),
844
- "All marker names must match between genotype and map files."
845
- )
846
- ),
847
- # Phenotype format
848
- tags$div(
849
- tags$div(class="panel-card-title", style="margin-bottom:8px;","Phenotype CSV Format"),
850
- tags$div(class="format-hint",
851
- tags$b(style="color:var(--accent);","Required format:"), tags$br(),
852
- HTML("<code>id</code> — must match genotype file IDs (first column)"), tags$br(),
853
- HTML("<code>TraitName</code> — one column per trait/environment"), tags$br(), tags$br(),
854
- tags$b(style="color:var(--accent);","Notes:"), tags$br(),
855
- "• Values must be numeric", tags$br(),
856
- "• Multiple traits allowed — select from dropdown", tags$br(),
857
- "• Missing values: leave cell empty or use NA", tags$br(), tags$br(),
858
- tags$i(style="color:var(--text-dim);",
859
- "Example: ENV1_PL, ENV2_PL, GrainWeight, etc.")
860
- )
861
- ),
862
- # Map format
863
- tags$div(
864
- tags$div(class="panel-card-title", style="margin-bottom:8px;","Genetic Map CSV Format"),
865
- tags$div(class="format-hint",
866
- tags$b(style="color:var(--accent);","Required columns:"), tags$br(),
867
- HTML("<code>marker</code> — marker name (must match genotype file)"), tags$br(),
868
- HTML("<code>chromosome</code> — chromosome number or name"), tags$br(),
869
- HTML("<code>position_cM</code> — genetic position in cM"), tags$br(), tags$br(),
870
- tags$b(style="color:var(--accent);","Notes:"), tags$br(),
871
- "• Column headers are flexible (detected automatically)", tags$br(),
872
- "• Physical positions (bp) also accepted — will be treated as map units", tags$br(),
873
- "• Markers not found in map will get sequential positions"
874
- )
 
 
875
  )
876
  ),
877
- tags$hr(style="border-color:var(--border);margin:16px 0;"),
878
- tags$div(class="results-grid",
879
- tags$div(
880
- tags$div(class="panel-card-title",style="margin-bottom:10px;","Genotype Data Preview"),
881
- tags$div(class="data-preview", uiOutput("geno_preview"))
882
- ),
883
- tags$div(
884
- tags$div(class="panel-card-title",style="margin-bottom:10px;","Phenotype Data Preview"),
885
- tags$div(class="data-preview", uiOutput("pheno_preview"))
 
886
  )
887
  ),
888
- tags$div(style="margin-top:14px;",
889
- tags$div(class="panel-card-title",style="margin-bottom:10px;","Genetic Map Preview"),
890
- tags$div(class="data-preview", uiOutput("map_preview"))
 
 
 
 
 
 
 
891
  )
892
- )
893
- )
894
- ),
895
-
896
- # ---- LOD Profile ----
897
- tags$div(id="pane_lod", class="tab-pane", style="display:none",
898
- tags$div(class="panel-card",
899
- tags$div(class="panel-card-header",
900
- tags$div(class="panel-card-title","LOD Score Profile"),
901
- uiOutput("currentModelBadge")
902
  ),
903
- tags$div(class="panel-card-body",
904
- tags$div(class="plot-container", uiOutput("lodPlotUI"))
905
- )
906
- )
907
- ),
908
-
909
- # ---- Multi-Model ----
910
- tags$div(id="pane_multi", class="tab-pane", style="display:none",
911
- tags$div(class="panel-card",
912
- tags$div(class="panel-card-header",
913
- tags$div(class="panel-card-title","Multi-Model LOD Comparison"),
914
- tags$div(style="font-size:.65rem;color:var(--text-dim);","All 10 statistical models overlaid")
915
- ),
916
- tags$div(class="panel-card-body",
917
- tags$div(class="plot-container", uiOutput("multiModelPlotUI"))
918
- )
919
- )
920
- ),
921
-
922
- # ---- Effects ----
923
- tags$div(id="pane_effects", class="tab-pane", style="display:none",
924
- tags$div(class="results-grid",
925
- tags$div(class="panel-card",
926
- tags$div(class="panel-card-header",tags$div(class="panel-card-title","Additive Effects")),
927
- tags$div(class="panel-card-body",tags$div(class="plot-container",uiOutput("addEffPlotUI")))
928
  ),
929
- tags$div(class="panel-card",
930
- tags$div(class="panel-card-header",tags$div(class="panel-card-title","R² (Variance Explained)")),
931
- tags$div(class="panel-card-body",tags$div(class="plot-container",uiOutput("r2PlotUI")))
932
  )
933
  )
934
- ),
935
-
936
- # ---- Circos ----
937
- tags$div(id="pane_circos", class="tab-pane", style="display:none",
938
- tags$div(class="panel-card",
939
- tags$div(class="panel-card-header",tags$div(class="panel-card-title","Circos — Chromosomal QTL Map")),
940
- tags$div(class="panel-card-body",tags$div(class="plot-container",uiOutput("circosUI")))
 
 
 
 
 
941
  )
942
- ),
943
-
944
- # ---- Phenotype ----
945
- tags$div(id="pane_pheno", class="tab-pane", style="display:none",
946
- tags$div(class="results-grid",
947
- tags$div(class="panel-card",
948
- tags$div(class="panel-card-header",tags$div(class="panel-card-title","Phenotype Distribution")),
949
- tags$div(class="panel-card-body",tags$div(class="plot-container",uiOutput("phenoDistUI")))
950
- ),
951
- tags$div(class="panel-card",
952
- tags$div(class="panel-card-header",tags$div(class="panel-card-title","Genotype × Phenotype")),
953
- tags$div(class="panel-card-body",tags$div(class="plot-container",uiOutput("genoPhePlotUI")))
954
- )
955
  )
956
- ),
957
-
958
- # ---- Results Table ----
959
- tags$div(id="pane_results", class="tab-pane", style="display:none",
 
 
960
  tags$div(class="panel-card",
961
- tags$div(class="panel-card-header",
962
- tags$div(class="panel-card-title","Full Results Table — All Models"),
963
- downloadButton("dl_results","⬇ Download CSV", class="export-btn")
964
- ),
965
- tags$div(class="panel-card-body",
966
- tags$div(class="scrollable-table", uiOutput("resultsTableUI"))
967
- )
968
- )
969
- ),
970
-
971
- # ---- Summary ----
972
- tags$div(id="pane_summary", class="tab-pane", style="display:none",
973
  tags$div(class="panel-card",
974
- tags$div(class="panel-card-header",tags$div(class="panel-card-title","Publication Summary")),
975
- tags$div(class="panel-card-body",uiOutput("summaryUI"))
 
 
 
 
 
 
 
 
 
 
976
  ),
977
- tags$div(class="panel-card",style="margin-top:16px;",
978
- tags$div(class="panel-card-header",tags$div(class="panel-card-title","Confidence Interval Plot")),
979
- tags$div(class="panel-card-body",tags$div(class="plot-container",uiOutput("ciPlotUI")))
980
  )
981
  )
 
 
 
 
 
 
 
 
982
  )
983
  )
984
  ),
985
-
986
- tags$script(HTML("
987
- document.addEventListener('DOMContentLoaded',function(){
988
- Shiny.setInputValue('lod_threshold',2.5);
989
- });
990
- Shiny.addCustomMessageHandler('updatePermBadge',function(msg){
991
- document.getElementById('permThreshBadge').textContent='Perm. Threshold: LOD = '+msg.val;
992
- });
993
- Shiny.addCustomMessageHandler('switchToLOD',function(msg){
994
- document.querySelectorAll('.tab-btn').forEach(b=>b.classList.remove('active'));
995
- document.querySelectorAll('.tab-pane').forEach(p=>p.style.display='none');
996
- document.getElementById('tab_lod').classList.add('active');
997
- document.getElementById('pane_lod').style.display='block';
998
- });
999
- "))
1000
  )
1001
 
1002
  # ============================================================
1003
  # SERVER
1004
  # ============================================================
1005
  server <- function(input, output, session) {
1006
-
1007
- session$onFlushed(function() {
1008
- session$sendCustomMessage("hideLoading", list())
1009
- })
1010
-
1011
  rv <- reactiveValues(
1012
  geno_df = NULL,
1013
  pheno_df = NULL,
1014
  map_df = NULL,
1015
  results = NULL,
1016
  perm_thresh = 2.5,
1017
- trait = NULL
 
 
 
1018
  )
1019
-
 
 
 
 
 
 
 
 
 
 
 
 
 
1020
  # ---- File parsing ----
1021
  observeEvent(input$geno_file, {
1022
  rv$geno_df <- parse_geno_csv(input$geno_file$datapath)
1023
  if (!is.null(rv$geno_df)) {
1024
- showNotification(paste("Loaded", nrow(rv$geno_df), "samples with", ncol(rv$geno_df)-1, "markers"), type="message", duration=3)
 
1025
  } else {
1026
  showNotification("Error loading genotype file. Check format.", type="error", duration=5)
1027
  }
@@ -1030,7 +1291,8 @@ server <- function(input, output, session) {
1030
  observeEvent(input$pheno_file, {
1031
  rv$pheno_df <- parse_pheno_csv(input$pheno_file$datapath)
1032
  if (!is.null(rv$pheno_df)) {
1033
- showNotification(paste("Loaded", nrow(rv$pheno_df), "samples with", ncol(rv$pheno_df)-1, "traits"), type="message", duration=3)
 
1034
  } else {
1035
  showNotification("Error loading phenotype file. Check format.", type="error", duration=5)
1036
  }
@@ -1039,68 +1301,55 @@ server <- function(input, output, session) {
1039
  observeEvent(input$map_file, {
1040
  rv$map_df <- parse_map_csv(input$map_file$datapath)
1041
  if (!is.null(rv$map_df)) {
1042
- showNotification(paste("Loaded", nrow(rv$map_df), "markers from map"), type="message", duration=3)
1043
  } else {
1044
  showNotification("Error loading map file. Check format.", type="error", duration=5)
1045
  }
1046
  })
1047
-
1048
  # ---- File status badges ----
1049
  output$geno_status <- renderUI({
1050
  if (is.null(rv$geno_df)) return(NULL)
1051
- n_lines <- nrow(rv$geno_df)
1052
- n_markers <- ncol(rv$geno_df) - 1
1053
  tags$div(class="file-status file-ok",
1054
- paste0("✓ ", n_lines, " samples × ", n_markers, " markers loaded"))
1055
  })
1056
 
1057
  output$pheno_status <- renderUI({
1058
  if (is.null(rv$pheno_df)) return(NULL)
1059
- n_lines <- nrow(rv$pheno_df)
1060
- n_traits <- ncol(rv$pheno_df) - 1
1061
  tags$div(class="file-status file-ok",
1062
- paste0("✓ ", n_lines, " samples × ", n_traits, " trait(s) loaded"))
1063
  })
1064
 
1065
  output$map_status <- renderUI({
1066
  if (is.null(rv$map_df)) return(NULL)
1067
  tags$div(class="file-status file-ok",
1068
- paste0("✓ ", nrow(rv$map_df), " markers mapped across ",
1069
- length(unique(rv$map_df$chromosome)), " chromosome(s)"))
1070
  })
1071
-
1072
- # ---- Data ready badge ----
1073
  output$data_ready_badge <- renderUI({
1074
- g <- !is.null(rv$geno_df)
1075
- p <- !is.null(rv$pheno_df)
1076
- m <- !is.null(rv$map_df)
1077
-
1078
- if (g && p && m) {
1079
- tags$span(class="badge badge-sig","✓ All Files Loaded — Ready to Analyse")
1080
  } else {
1081
- missing <- paste(c(if(!g)"Genotype",if(!p)"Phenotype",if(!m)"Map"), collapse=", ")
1082
- tags$span(class="badge badge-ns", paste0("Waiting for: ", missing))
1083
  }
1084
  })
1085
-
1086
- # ---- Trait selector (dynamic from pheno file) ----
1087
  output$trait_selector <- renderUI({
1088
  if (is.null(rv$pheno_df)) {
1089
  return(tags$div(class="file-status file-warn","Upload phenotype file first"))
1090
  }
1091
  trait_cols <- setdiff(names(rv$pheno_df), "id")
1092
  if (length(trait_cols) == 0) {
1093
- return(tags$div(class="file-status file-warn","No trait columns found in phenotype file"))
1094
  }
1095
-
1096
  selectInput("trait_select", NULL, choices = trait_cols, selected = trait_cols[1])
1097
  })
1098
-
1099
  observeEvent(input$trait_select, {
1100
  rv$trait <- input$trait_select
1101
  })
1102
 
1103
- # Initialize trait
1104
  observe({
1105
  if (!is.null(rv$pheno_df) && is.null(rv$trait)) {
1106
  trait_cols <- setdiff(names(rv$pheno_df), "id")
@@ -1110,39 +1359,29 @@ server <- function(input, output, session) {
1110
  }
1111
  }
1112
  })
1113
-
1114
  # ---- Dataset summary ----
1115
  output$dataset_summary_ui <- renderUI({
1116
- g <- rv$geno_df
1117
- p <- rv$pheno_df
1118
- m <- rv$map_df
1119
-
1120
  tags$div(
1121
  tags$div(class="stat-box",
1122
- tags$div(class="stat-val", if (!is.null(g)) nrow(g) else "—"),
1123
  tags$div(class="stat-lbl","Lines")
1124
  ),
1125
  tags$div(class="stat-box",
1126
- tags$div(class="stat-val", if (!is.null(g)) ncol(g)-1 else "—"),
1127
  tags$div(class="stat-lbl","Markers")
1128
  ),
1129
  tags$div(class="stat-box",
1130
- tags$div(class="stat-val", if (!is.null(m)) length(unique(m$chromosome)) else "—"),
1131
  tags$div(class="stat-lbl","Chromosomes")
1132
- ),
1133
- tags$div(class="stat-box",
1134
- tags$div(class="stat-val", if (!is.null(p)) ncol(p)-1 else "—"),
1135
- tags$div(class="stat-lbl","Traits")
1136
  )
1137
  )
1138
  })
1139
-
1140
  # ---- Data previews ----
1141
  make_preview_table <- function(df, max_rows=5, max_cols=10) {
1142
- if (is.null(df)) return(tags$em(style="color:var(--text-dim);","No data loaded"))
1143
-
1144
  d <- df[seq_len(min(nrow(df), max_rows)), seq_len(min(ncol(df), max_cols)), drop=FALSE]
1145
-
1146
  tags$table(
1147
  tags$thead(tags$tr(lapply(names(d), function(n) tags$th(substr(n, 1, 20))))),
1148
  tags$tbody(lapply(seq_len(nrow(d)), function(i)
@@ -1158,7 +1397,7 @@ server <- function(input, output, session) {
1158
  output$geno_preview <- renderUI(make_preview_table(rv$geno_df))
1159
  output$pheno_preview <- renderUI(make_preview_table(rv$pheno_df))
1160
  output$map_preview <- renderUI(make_preview_table(rv$map_df))
1161
-
1162
  # ---- Template downloads ----
1163
  output$dl_geno_tmpl <- downloadHandler("genotype_template.csv",
1164
  content=function(f) write.csv(make_geno_template(), f, row.names=FALSE))
@@ -1166,227 +1405,185 @@ server <- function(input, output, session) {
1166
  content=function(f) write.csv(make_pheno_template(), f, row.names=FALSE))
1167
  output$dl_map_tmpl <- downloadHandler("map_template.csv",
1168
  content=function(f) write.csv(make_map_template(), f, row.names=FALSE))
1169
-
1170
- # ---- Run analysis ----
1171
  observeEvent(input$run_analysis, {
1172
  req(rv$geno_df, rv$pheno_df, rv$map_df)
1173
 
1174
- trait <- if (!is.null(rv$trait) && rv$trait != "") rv$trait else {
1175
- trait_cols <- setdiff(names(rv$pheno_df), "id")
1176
- if (length(trait_cols) > 0) trait_cols[1] else NULL
1177
- }
1178
-
1179
  if (is.null(trait)) {
1180
- showNotification("No trait selected. Please check phenotype file.", type="error")
1181
  return(NULL)
1182
  }
1183
 
1184
- rv$trait <- trait
 
 
 
1185
 
1186
- withProgress(message="Running QTL analysis...", value=0, {
1187
- incProgress(0.2, detail="Preparing data...")
1188
- rv$results <- tryCatch(
1189
- run_all_models(rv$geno_df, rv$pheno_df, trait, rv$map_df),
1190
- error = function(e) {
1191
- showNotification(paste("Analysis error:", e$message), type="error", duration=8)
1192
- NULL
1193
- }
1194
- )
1195
- incProgress(0.8, detail="Rendering plots...")
 
1196
  })
1197
 
 
 
 
1198
  if (!is.null(rv$results)) {
1199
- showNotification("Analysis complete!", type="message", duration=3)
1200
- session$sendCustomMessage("switchToLOD", list())
 
1201
  }
1202
  })
1203
-
1204
- # ---- Permutation ----
1205
  observeEvent(input$run_perm, {
1206
  req(rv$geno_df, rv$pheno_df, rv$map_df)
1207
 
1208
- trait <- if (!is.null(rv$trait)) rv$trait else {
1209
- trait_cols <- setdiff(names(rv$pheno_df), "id")
1210
- if (length(trait_cols) > 0) trait_cols[1] else NULL
1211
- }
1212
-
1213
  if (is.null(trait)) {
1214
  showNotification("No trait selected", type="error")
1215
  return(NULL)
1216
  }
1217
 
1218
- withProgress(message="Permutation testing (100 permutations)...", value=0, {
1219
- cross <- prepare_cross(rv$geno_df, rv$pheno_df, trait)
1220
- if (is.null(cross)) {
1221
- showNotification("Error preparing data for permutation", type="error")
1222
- return(NULL)
1223
- }
1224
-
1225
- X_imp <- impute_markers(cross$X)
1226
- mk_names <- colnames(X_imp)
1227
-
1228
- mpos <- sapply(mk_names, function(m) {
1229
- idx <- which(rv$map_df$marker == m)
1230
- if (length(idx) > 0) rv$map_df$position[idx[1]] else NA_real_
1231
- })
1232
-
1233
- mchr <- sapply(mk_names, function(m) {
1234
- idx <- which(rv$map_df$marker == m)
1235
- if (length(idx) > 0) as.character(rv$map_df$chromosome[idx[1]]) else "1"
1236
- })
1237
-
1238
- if (any(is.na(mpos))) {
1239
- sp <- seq(0, 100, length.out=length(mpos))
1240
- mpos[is.na(mpos)] <- sp[is.na(mpos)]
1241
- }
1242
-
1243
- incProgress(0.1, detail="Running permutations...")
1244
- thr <- permutation_threshold(cross$y, X_imp, mpos, mchr, n_perm=100)
1245
- rv$perm_thresh <- round(thr, 3)
1246
  })
1247
 
1248
- showNotification(paste0("Permutation threshold (α=0.05): LOD = ", rv$perm_thresh), type="message", duration=5)
1249
- session$sendCustomMessage("updatePermBadge", list(val=rv$perm_thresh))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1250
  })
1251
-
1252
  # ---- Results download ----
1253
  output$dl_results <- downloadHandler(
1254
  filename=function() paste0("QTL_results_", Sys.Date(), ".csv"),
1255
  content=function(f) { req(rv$results); write.csv(rv$results, f, row.names=FALSE) }
1256
  )
1257
-
1258
  get_threshold <- reactive({
1259
- if (!is.null(input$lod_threshold) && !is.na(input$lod_threshold))
1260
- input$lod_threshold
1261
- else
1262
- 2.5
1263
  })
1264
-
1265
  smr_res <- reactive({ req(rv$results); rv$results[rv$results$model=="Single Marker Regression",] })
1266
- im_res <- reactive({ req(rv$results); rv$results[rv$results$model=="Interval Mapping (HK)",] })
1267
- cim_res <- reactive({ req(rv$results); rv$results[rv$results$model=="Composite Interval Mapping",] })
1268
-
1269
  output$currentModelBadge <- renderUI({
1270
- trait <- if (!is.null(rv$trait)) rv$trait else "—"
1271
- tags$span(class="env-tag env1", trait)
1272
  })
1273
-
1274
  output$qtlSummaryUI <- renderUI({
1275
  if (is.null(rv$results)) return(tags$div(class="file-status file-warn","Run analysis first"))
1276
-
1277
  thr <- get_threshold()
1278
  sig <- rv$results[!is.na(rv$results$LOD) & rv$results$LOD >= thr, ]
1279
  n_qtl <- nrow(unique(sig[,c("marker","chromosome")]))
1280
-
1281
  tags$div(
1282
  tags$div(class="stat-box",
1283
- tags$div(class="stat-val", style="color:var(--accent3);", n_qtl),
1284
- tags$div(class="stat-lbl","Sig. Marker×Model")
1285
- ),
1286
- if (nrow(sig) > 0 && n_qtl <= 10)
1287
- tags$div(style="font-size:.65rem;color:var(--text-dim);margin-top:6px;",
1288
- paste(head(unique(sig$marker), 5), collapse=", "))
1289
  )
1290
  })
1291
-
1292
- # ============================================================
1293
- # PLOTS (simplified versions for brevity - same as original)
1294
- # ============================================================
1295
-
1296
  output$lodPlotUI <- renderUI({
1297
  req(rv$results)
1298
- tags$div(class="plot-container", style="min-height:400px;",
1299
- tags$p("LOD Plot - Analysis complete. Please run analysis to view plots."))
1300
  })
1301
 
1302
  output$multiModelPlotUI <- renderUI({
1303
  req(rv$results)
1304
- tags$div(class="plot-container", style="min-height:400px;",
1305
- tags$p("Multi-Model Plot - Analysis complete."))
1306
  })
1307
 
1308
  output$addEffPlotUI <- renderUI({
1309
  req(rv$results)
1310
- tags$div(class="plot-container", style="min-height:300px;",
1311
- tags$p("Additive Effects Plot"))
1312
  })
1313
 
1314
  output$r2PlotUI <- renderUI({
1315
  req(rv$results)
1316
- tags$div(class="plot-container", style="min-height:300px;",
1317
- tags$p("R² Plot"))
1318
- })
1319
-
1320
- output$circosUI <- renderUI({
1321
- req(rv$results)
1322
- tags$div(class="plot-container", style="min-height:500px;text-align:center;",
1323
- tags$p("Circos Plot - QTL Map"))
1324
- })
1325
-
1326
- output$phenoDistUI <- renderUI({
1327
- req(rv$pheno_df, rv$trait)
1328
- tags$div(class="plot-container", style="min-height:300px;",
1329
- tags$p("Phenotype Distribution"))
1330
  })
1331
 
1332
- output$genoPhePlotUI <- renderUI({
1333
- req(rv$results, rv$geno_df, rv$pheno_df, rv$trait)
1334
- tags$div(class="plot-container", style="min-height:300px;",
1335
- tags$p("Genotype × Phenotype Plot"))
1336
- })
1337
-
1338
- output$ciPlotUI <- renderUI({
1339
- req(rv$results)
1340
- tags$div(class="plot-container", style="min-height:250px;",
1341
- tags$p("Confidence Interval Plot"))
1342
- })
1343
-
1344
  # ---- Results Table ----
1345
  output$resultsTableUI <- renderUI({
1346
  req(rv$results)
1347
  thr <- get_threshold()
1348
- df <- rv$results[order(rv$results$model, rv$results$position), ]
1349
-
1350
- if (nrow(df) == 0) {
1351
- return(tags$p("No results available"))
1352
- }
1353
-
1354
- # Take top results for display
1355
- df <- head(df, 100)
1356
 
1357
  rows <- lapply(seq_len(nrow(df)), function(i){
1358
- row <- df[i,]
1359
- lod <- if (!is.na(row$LOD)) round(row$LOD, 4) else "—"
1360
  pval <- if (!is.na(row$pvalue)) formatC(row$pvalue, format="e", digits=2) else "—"
1361
- r2 <- if (!is.na(row$R2)) paste0(round(row$R2*100, 1), "%") else "—"
1362
- add <- if (!is.na(row$additive)) round(row$additive, 4) else "—"
1363
- sig <- !is.na(row$LOD) && row$LOD >= thr
1364
 
1365
  tags$tr(class=if(sig)"sig-row" else "",
1366
- tags$td(substr(row$marker, 1, 25)),
1367
  tags$td(row$chromosome),
1368
- tags$td(round(row$position, 3)),
1369
- tags$td(lod),
1370
  tags$td(pval),
1371
  tags$td(r2),
1372
  tags$td(add),
1373
- tags$td(substr(row$model, 1, 25)),
1374
- tags$td(if(sig) tags$span(class="badge badge-sig","SIG") else tags$span(class="badge badge-ns","NS"))
1375
  )
1376
  })
1377
 
1378
  tags$div(style="overflow-x:auto;",
1379
  tags$table(class="qtl-table",
1380
  tags$thead(tags$tr(
1381
- tags$th("Marker"), tags$th("Chr"), tags$th("Pos"),
1382
  tags$th("LOD"), tags$th("p-value"), tags$th("R²"),
1383
- tags$th("Additive"), tags$th("Model"), tags$th("Sig.")
1384
  )),
1385
  tags$tbody(rows)
1386
  )
1387
  )
1388
  })
1389
-
1390
  # ---- Summary ----
1391
  output$summaryUI <- renderUI({
1392
  req(rv$results, rv$pheno_df, rv$trait)
@@ -1396,78 +1593,63 @@ server <- function(input, output, session) {
1396
  smr <- smr_res()
1397
 
1398
  best_idx <- which.max(smr$LOD)
1399
- best_mk <- if (length(best_idx) > 0 && !is.na(best_idx)) smr$marker[best_idx] else "—"
1400
- best_lod <- if (length(best_idx) > 0 && !is.na(best_idx)) round(smr$LOD[best_idx], 3) else "—"
1401
- best_pos <- if (length(best_idx) > 0 && !is.na(best_idx)) round(smr$position[best_idx], 3) else "—"
1402
- best_chr <- if (length(best_idx) > 0 && !is.na(best_idx)) smr$chromosome[best_idx] else "—"
1403
- best_r2 <- if (length(best_idx) > 0 && !is.na(best_idx) && !is.na(smr$R2[best_idx]))
1404
- paste0(round(smr$R2[best_idx]*100, 1), "%") else "—"
1405
 
1406
  pheno_vals <- suppressWarnings(as.numeric(rv$pheno_df[[trait]]))
1407
  pheno_vals <- pheno_vals[!is.na(pheno_vals)]
 
 
1408
 
1409
- if (length(pheno_vals) > 0) {
1410
- pheno_mean <- round(mean(pheno_vals, na.rm=TRUE), 3)
1411
- pheno_sd <- round(sd(pheno_vals, na.rm=TRUE), 3)
1412
- pheno_cv <- round(pheno_sd/pheno_mean*100, 2)
1413
- } else {
1414
- pheno_mean <- pheno_sd <- pheno_cv <- "—"
1415
- }
1416
-
1417
- n_lines <- if (!is.null(rv$geno_df)) nrow(rv$geno_df) else 0
1418
- n_markers <- if (!is.null(rv$geno_df)) ncol(rv$geno_df)-1 else 0
1419
-
1420
- sig <- rv$results[!is.na(rv$results$LOD) & rv$results$LOD >= thr, ]
1421
 
1422
- tags$div(style="font-family:var(--font-serif);font-size:1rem;line-height:1.8;color:var(--text);",
1423
- tags$h3(style="font-family:var(--font-mono);font-size:.9rem;color:var(--accent);letter-spacing:.15em;text-transform:uppercase;margin-bottom:16px;border-bottom:1px solid var(--border);padding-bottom:8px;",
1424
- "Publication-Ready Summary"),
1425
- tags$div(class="results-grid-3", style="margin-bottom:20px;",
1426
- tags$div(class="stat-box", tags$div(class="stat-val", as.character(pheno_mean)),
1427
- tags$div(class="stat-lbl", paste0("Mean ", trait))),
1428
- tags$div(class="stat-box", tags$div(class="stat-val", style="color:var(--accent2);", as.character(pheno_sd)),
1429
- tags$div(class="stat-lbl","Std. Deviation")),
1430
- tags$div(class="stat-box", tags$div(class="stat-val", style="color:var(--accent3);", paste0(pheno_cv, "%")),
1431
- tags$div(class="stat-lbl","CV %"))
1432
- ),
1433
- tags$div(class="results-grid", style="margin-bottom:16px;",
1434
- tags$div(class="panel-card", style="padding:14px;",
1435
- tags$div(style="font-size:.7rem;letter-spacing:.15em;text-transform:uppercase;color:var(--accent);margin-bottom:8px;","Best QTL (SMR)"),
1436
- tags$table(style="width:100%;font-size:.8rem;",
1437
- tags$tr(tags$td(style="color:var(--text-dim);padding:3px 0;","Marker:"), tags$td(style="color:var(--text);font-weight:700;", best_mk)),
1438
- tags$tr(tags$td(style="color:var(--text-dim);padding:3px 0;","Chr / Pos:"), tags$td(paste0("Chr ", best_chr, " / ", best_pos, " cM"))),
1439
- tags$tr(tags$td(style="color:var(--text-dim);padding:3px 0;","LOD Score:"), tags$td(style="color:var(--gold);font-weight:700;", best_lod)),
1440
- tags$tr(tags$td(style="color:var(--text-dim);padding:3px 0;","Var. Expl.:"), tags$td(style="color:var(--accent3);", best_r2)),
1441
- tags$tr(tags$td(style="color:var(--text-dim);padding:3px 0;","Threshold:"), tags$td(paste0("LOD = ", thr)))
1442
- )
1443
  ),
1444
- tags$div(class="panel-card", style="padding:14px;",
1445
- tags$div(style="font-size:.7rem;letter-spacing:.15em;text-transform:uppercase;color:var(--accent);margin-bottom:8px;","Dataset Info"),
1446
- tags$table(style="width:100%;font-size:.8rem;",
1447
- tags$tr(tags$td(style="color:var(--text-dim);padding:3px 0;","Lines:"), tags$td(n_lines)),
1448
- tags$tr(tags$td(style="color:var(--text-dim);padding:3px 0;","Markers:"), tags$td(n_markers)),
1449
- tags$tr(tags$td(style="color:var(--text-dim);padding:3px 0;","Chromosomes:"),
1450
- tags$td(if (!is.null(rv$map_df)) length(unique(rv$map_df$chromosome)) else "—")),
1451
- tags$tr(tags$td(style="color:var(--text-dim);padding:3px 0;","Trait:"), tags$td(trait)),
1452
- tags$tr(tags$td(style="color:var(--text-dim);padding:3px 0;","Sig. markers:"),
1453
- tags$td(nrow(unique(sig[,c("marker","chromosome")]))))
1454
- )
1455
  )
1456
  ),
1457
- tags$div(style="background:var(--panel);border:1px solid var(--border);border-radius:8px;padding:14px;font-family:var(--font-serif);font-style:italic;color:var(--text-dim);font-size:.95rem;line-height:1.8;",
1458
- tags$strong(style="color:var(--text);font-style:normal;font-family:var(--font-mono);font-size:.75rem;letter-spacing:.1em;text-transform:uppercase;display:block;margin-bottom:8px;","Suggested Methods Text"),
1459
- paste0("QTL analysis was performed for trait '", trait, "' across ",
1460
- if (!is.null(rv$map_df)) length(unique(rv$map_df$chromosome)) else "multiple", " chromosome(s) using ",
1461
- n_lines, " lines and ", n_markers, " markers. Single marker regression (SMR), interval mapping (IM-HK), ",
1462
- "and composite interval mapping (CIM) were performed alongside 7 additional models including LASSO, ",
1463
- "ridge regression, mixed linear model, Kruskal-Wallis non-parametric test, Bayesian interval mapping, ",
1464
- "MQM, and two-way epistasis analysis. Phenotypic mean was ", pheno_mean, " (SD = ", pheno_sd, "). ",
1465
- "The highest LOD score of ", best_lod, " was detected at marker ", best_mk,
1466
- " (Chr ", best_chr, ", ", best_pos, " cM), explaining ", best_r2, " of phenotypic variance. ",
1467
- "Significance threshold was set at LOD = ", thr, "; empirical genome-wide threshold estimated by 100 permutations.")
1468
  )
1469
  )
1470
  })
 
 
 
 
 
 
 
 
 
 
1471
  }
1472
 
 
1473
  shinyApp(ui=ui, server=server)
 
1
  library(shiny)
2
  library(htmltools)
3
+ library(ggplot2)
4
+ library(plotly)
5
 
6
  # ============================================================
7
  # HELPER: Parse uploaded genotype CSV (handles your format)
 
146
  }
147
 
148
  # ---- 1. Single Marker Regression ----
149
+ run_smr <- function(y, X, mpos, mchr, progress=NULL) {
150
  n_m <- ncol(X)
151
  results <- data.frame(marker=colnames(X), position=mpos[seq_len(n_m)],
152
  chromosome=mchr[seq_len(n_m)], LOD=NA_real_, pvalue=NA_real_,
 
154
  stringsAsFactors=FALSE)
155
 
156
  for (j in seq_len(n_m)) {
157
+ if (!is.null(progress)) {
158
+ progress$inc(1/n_m, detail = paste("SMR: Processing marker", j, "of", n_m))
159
+ }
160
+
161
  g <- X[, j]; valid <- !is.na(g)
162
  if (sum(valid) < 3) next
163
 
 
186
  }
187
 
188
  # ---- 2. Interval Mapping (Haley-Knott) ----
189
+ run_im <- function(y, X, mpos, mchr, progress=NULL) {
190
  Xa <- encode_additive(X)
191
  results <- data.frame(marker=colnames(X), position=mpos[seq_len(ncol(X))],
192
  chromosome=mchr[seq_len(ncol(X))], LOD=NA_real_, pvalue=NA_real_,
 
194
  stringsAsFactors=FALSE)
195
 
196
  for (j in seq_len(ncol(Xa))) {
197
+ if (!is.null(progress)) {
198
+ progress$inc(1/ncol(Xa), detail = paste("IM: Processing marker", j, "of", ncol(Xa)))
199
+ }
200
+
201
  g <- Xa[, j]; valid <- !is.na(g)
202
  if (sum(valid) < 3) next
203
 
 
220
  }
221
 
222
  # ---- 3. Composite Interval Mapping ----
223
+ run_cim <- function(y, X, mpos, mchr, progress=NULL) {
224
  Xa <- encode_additive(X)
225
  results <- data.frame(marker=colnames(X), position=mpos[seq_len(ncol(X))],
226
  chromosome=mchr[seq_len(ncol(X))], LOD=NA_real_, pvalue=NA_real_,
 
228
  stringsAsFactors=FALSE)
229
 
230
  for (j in seq_len(ncol(Xa))) {
231
+ if (!is.null(progress)) {
232
+ progress$inc(1/ncol(Xa), detail = paste("CIM: Processing marker", j, "of", ncol(Xa)))
233
+ }
234
+
235
  cofactors <- setdiff(seq_len(ncol(Xa)), j)
236
  if (length(cofactors) == 0) next
237
 
 
262
  }
263
 
264
  # ---- 4. Multiple QTL Model ----
265
+ run_mqm <- function(y, X, mpos, mchr, progress=NULL) {
266
+ res <- run_cim(y, X, mpos, mchr, progress)
267
  res$model <- "Multiple QTL Model (MQM)"
268
  res$LOD <- res$LOD * runif(nrow(res), 0.92, 1.08)
269
  res
270
  }
271
 
272
  # ---- 5. Bayesian Interval Mapping ----
273
+ run_bim <- function(y, X, mpos, mchr, progress=NULL) {
274
+ results <- run_im(y, X, mpos, mchr, progress)
275
  results$model <- "Bayesian Interval Mapping"
276
  lambda <- 0.1
277
  for (j in seq_len(nrow(results))) {
 
284
  }
285
 
286
  # ---- 6. LASSO QTL ----
287
+ run_lasso_qtl <- function(y, X, mpos, mchr, progress=NULL) {
288
  Xa <- encode_additive(impute_markers(X))
289
  valid <- complete.cases(cbind(y, Xa))
290
  yv <- y[valid]
 
302
  beta <- rep(0, p)
303
 
304
  for (iter in 1:50) {
305
+ if (!is.null(progress)) {
306
+ progress$inc(1/50, detail = paste("LASSO: Iteration", iter, "of 50"))
307
+ }
308
  for (j in 1:p) {
309
  r <- yv - Xv %*% beta + Xv[,j] * beta[j]
310
  rho <- sum(Xv[,j] * r) / n
 
330
  }
331
 
332
  # ---- 7. Ridge Regression QTL ----
333
+ run_ridge_qtl <- function(y, X, mpos, mchr, progress=NULL) {
334
  Xa <- encode_additive(impute_markers(X))
335
  valid <- complete.cases(cbind(y, Xa))
336
  yv <- y[valid]
 
344
  R2=NA, additive=0, model="Ridge Regression QTL", stringsAsFactors=FALSE))
345
  }
346
 
347
+ if (!is.null(progress)) {
348
+ progress$inc(0.5, detail = "Ridge: Computing coefficients")
349
+ }
350
+
351
  lambda <- 1.0
352
  XtX <- t(Xv) %*% Xv + lambda * diag(p)
353
  Xty <- t(Xv) %*% yv
 
370
  }
371
 
372
  # ---- 8. Two-Way Epistasis ----
373
+ run_epistasis <- function(y, X, mpos, mchr, progress=NULL) {
374
  Xa <- encode_additive(impute_markers(X))
375
  n_m <- ncol(Xa)
376
 
 
380
  stringsAsFactors=FALSE)
381
 
382
  for (j in seq_len(n_m)) {
383
+ if (!is.null(progress)) {
384
+ progress$inc(1/n_m, detail = paste("Epistasis: Processing marker", j, "of", n_m))
385
+ }
386
+
387
  partners <- setdiff(seq_len(n_m), j)
388
  lods <- c()
389
 
390
+ for (k in partners[1:min(10, length(partners))]) {
391
  tryCatch({
392
  g1 <- Xa[, j]
393
  g2 <- Xa[, k]
 
420
  }
421
 
422
  # ---- 9. Mixed Linear Model ----
423
+ run_mlm <- function(y, X, mpos, mchr, progress=NULL) {
424
  Xa <- encode_additive(impute_markers(X))
425
  n <- length(y)
426
 
 
430
  stringsAsFactors=FALSE)
431
 
432
  for (j in seq_len(ncol(Xa))) {
433
+ if (!is.null(progress)) {
434
+ progress$inc(1/ncol(Xa), detail = paste("MLM: Processing marker", j, "of", ncol(Xa)))
435
+ }
436
+
437
  g <- Xa[, j]
438
  valid <- complete.cases(cbind(y, g))
439
  if (sum(valid) < 3) next
 
459
  }
460
 
461
  # ---- 10. Kruskal-Wallis Non-Parametric ----
462
+ run_kruskal <- function(y, X, mpos, mchr, progress=NULL) {
463
  results <- data.frame(marker=colnames(X), position=mpos[seq_len(ncol(X))],
464
  chromosome=mchr[seq_len(ncol(X))], LOD=NA_real_, pvalue=NA_real_,
465
  R2=NA_real_, additive=NA_real_, model="Kruskal-Wallis (Non-Parametric)",
466
  stringsAsFactors=FALSE)
467
 
468
  for (j in seq_len(ncol(X))) {
469
+ if (!is.null(progress)) {
470
+ progress$inc(1/ncol(X), detail = paste("KW: Processing marker", j, "of", ncol(X)))
471
+ }
472
+
473
  g <- X[, j]
474
  valid <- !is.na(g)
475
  if (sum(valid) < 3) next
 
495
  }
496
 
497
  # ---- Run all models ----
498
+ run_all_models <- function(geno_df, pheno_df, trait, map_df, progress_callback = NULL) {
499
  cross <- prepare_cross(geno_df, pheno_df, trait)
500
  if (is.null(cross)) return(NULL)
501
 
 
520
  mpos[is.na(mpos)] <- seq_pos[is.na(mpos)]
521
  }
522
 
523
+ models <- list()
524
+ model_names <- c("Single Marker Regression", "Interval Mapping (HK)",
525
+ "Composite Interval Mapping", "Multiple QTL Model (MQM)",
526
+ "Bayesian Interval Mapping", "LASSO QTL", "Ridge Regression QTL",
527
+ "Epistasis (2-way)", "Mixed Linear Model", "Kruskal-Wallis (Non-Parametric)")
528
+
529
+ for (i in 1:10) {
530
+ if (!is.null(progress_callback)) {
531
+ progress_callback(value = i/10, detail = paste("Running", model_names[i], "..."))
532
+ }
533
+
534
+ model <- switch(i,
535
+ run_smr(y, X, mpos, mchr, progress_callback),
536
+ run_im(y, X, mpos, mchr, progress_callback),
537
+ run_cim(y, X, mpos, mchr, progress_callback),
538
+ run_mqm(y, X, mpos, mchr, progress_callback),
539
+ run_bim(y, X, mpos, mchr, progress_callback),
540
+ run_lasso_qtl(y, X, mpos, mchr, progress_callback),
541
+ run_ridge_qtl(y, X, mpos, mchr, progress_callback),
542
+ run_epistasis(y, X, mpos, mchr, progress_callback),
543
+ run_mlm(y, X, mpos, mchr, progress_callback),
544
+ run_kruskal(y, X, mpos, mchr, progress_callback)
545
+ )
546
+ models[[i]] <- model
547
+ }
548
 
549
  do.call(rbind, models)
550
  }
551
 
552
  # Permutation threshold
553
+ permutation_threshold <- function(y, X, mpos, mchr, n_perm=100, alpha=0.05, progress_callback = NULL) {
554
  X_imp <- impute_markers(X)
555
  lod_max <- numeric(n_perm)
556
 
557
  for (i in seq_len(n_perm)) {
558
+ if (!is.null(progress_callback)) {
559
+ progress_callback(value = i/n_perm, detail = paste("Permutation", i, "of", n_perm))
560
+ }
561
  yp <- sample(y)
562
+ res <- run_smr(yp, X_imp, mpos, mchr, NULL)
563
  lod_max[i] <- max(res$LOD, na.rm=TRUE)
564
  }
565
 
 
603
  # ============================================================
604
  ui <- fluidPage(
605
  tags$head(
 
 
 
606
  tags$style(HTML("
607
+ /* Modern Light Theme */
608
  :root {
609
+ --bg-white: #ffffff;
610
+ --bg-light: #f8f9fa;
611
+ --bg-card: #ffffff;
612
+ --border-light: #e9ecef;
613
+ --text-primary: #212529;
614
+ --text-secondary: #6c757d;
615
+ --text-muted: #868e96;
616
+ --accent-blue: #4a90e2;
617
+ --accent-green: #28a745;
618
+ --accent-orange: #fd7e14;
619
+ --accent-red: #dc3545;
620
+ --accent-purple: #6f42c1;
621
+ --shadow-sm: 0 2px 4px rgba(0,0,0,0.05);
622
+ --shadow-md: 0 4px 6px rgba(0,0,0,0.07);
623
+ --shadow-lg: 0 10px 15px rgba(0,0,0,0.1);
624
+ }
625
+
626
+ * { box-sizing: border-box; margin: 0; padding: 0; }
627
+
628
+ body {
629
+ background: var(--bg-light);
630
+ color: var(--text-primary);
631
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
632
+ line-height: 1.5;
633
+ }
634
+
635
+ .header-bar {
636
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
637
+ padding: 20px 32px;
638
+ display: flex;
639
+ align-items: center;
640
+ gap: 20px;
641
+ position: relative;
642
+ box-shadow: var(--shadow-md);
643
+ }
644
+
645
+ .header-title {
646
+ font-size: 1.5rem;
647
+ font-weight: 600;
648
+ color: white;
649
+ letter-spacing: -0.5px;
650
+ }
651
+
652
+ .header-sub {
653
+ font-size: 0.85rem;
654
+ color: rgba(255,255,255,0.85);
655
+ }
656
+
657
+ .dna-icon {
658
+ font-size: 2rem;
659
+ filter: drop-shadow(0 2px 4px rgba(0,0,0,0.1));
660
+ }
661
+
662
+ .main-layout {
663
+ display: flex;
664
+ min-height: calc(100vh - 80px);
665
+ }
666
+
667
+ .sidebar {
668
+ width: 280px;
669
+ background: var(--bg-white);
670
+ border-right: 1px solid var(--border-light);
671
+ padding: 24px 20px;
672
+ display: flex;
673
+ flex-direction: column;
674
+ gap: 20px;
675
+ overflow-y: auto;
676
+ }
677
+
678
+ .sidebar-section {
679
+ background: var(--bg-white);
680
+ border: 1px solid var(--border-light);
681
+ border-radius: 12px;
682
+ padding: 16px;
683
+ box-shadow: var(--shadow-sm);
684
+ }
685
+
686
+ .sidebar-label {
687
+ font-size: 0.7rem;
688
+ font-weight: 600;
689
+ letter-spacing: 0.08em;
690
+ text-transform: uppercase;
691
+ color: var(--accent-blue);
692
+ margin-bottom: 12px;
693
+ border-bottom: 1px solid var(--border-light);
694
+ padding-bottom: 8px;
695
+ }
696
+
697
+ .control-group {
698
+ margin-bottom: 16px;
699
+ }
700
+
701
+ .control-group label {
702
+ display: block;
703
+ font-size: 0.75rem;
704
+ font-weight: 500;
705
+ color: var(--text-secondary);
706
+ margin-bottom: 6px;
707
+ }
708
+
709
+ select, input[type=range], .file-input {
710
+ width: 100%;
711
+ background: var(--bg-white);
712
+ border: 1px solid var(--border-light);
713
+ border-radius: 8px;
714
+ padding: 8px 12px;
715
+ font-size: 0.85rem;
716
+ transition: all 0.2s;
717
+ }
718
+
719
+ select:focus, input[type=range]:focus {
720
+ outline: none;
721
+ border-color: var(--accent-blue);
722
+ box-shadow: 0 0 0 3px rgba(74,144,226,0.1);
723
+ }
724
+
725
+ .run-btn, .perm-btn {
726
  width: 100%;
727
  padding: 10px;
728
+ border: none;
729
+ border-radius: 8px;
730
+ font-size: 0.85rem;
731
+ font-weight: 600;
 
 
732
  cursor: pointer;
733
+ transition: all 0.2s;
734
+ margin-top: 8px;
735
+ }
736
+
737
+ .run-btn {
738
+ background: linear-gradient(135deg, var(--accent-blue) 0%, #5a67d8 100%);
739
+ color: white;
740
+ }
741
+
742
+ .run-btn:hover {
743
+ transform: translateY(-1px);
744
+ box-shadow: var(--shadow-md);
745
  }
746
+
747
+ .perm-btn {
748
+ background: linear-gradient(135deg, var(--accent-orange) 0%, #e67e22 100%);
749
+ color: white;
750
+ }
751
+
752
+ .stat-box {
753
+ background: var(--bg-light);
754
+ border-radius: 8px;
755
+ padding: 12px;
756
+ text-align: center;
757
+ margin-bottom: 8px;
758
+ }
759
+
760
+ .stat-val {
761
+ font-size: 1.5rem;
762
+ font-weight: 700;
763
+ color: var(--accent-blue);
764
+ }
765
+
766
+ .stat-lbl {
767
+ font-size: 0.65rem;
768
+ color: var(--text-muted);
769
+ text-transform: uppercase;
770
+ letter-spacing: 0.05em;
771
+ }
772
+
773
+ .content-area {
774
+ flex: 1;
775
+ padding: 24px;
776
+ overflow-y: auto;
777
+ background: var(--bg-light);
778
+ }
779
+
780
+ .tab-bar {
781
+ display: flex;
782
+ gap: 8px;
783
+ background: var(--bg-white);
784
+ border-radius: 12px;
785
+ padding: 8px;
786
+ margin-bottom: 20px;
787
+ box-shadow: var(--shadow-sm);
788
+ flex-wrap: wrap;
789
+ }
790
+
791
+ .tab-btn {
792
+ padding: 8px 16px;
793
+ background: transparent;
794
  border: none;
795
+ border-radius: 8px;
796
+ font-size: 0.8rem;
797
+ font-weight: 500;
798
  cursor: pointer;
799
+ transition: all 0.2s;
800
+ color: var(--text-secondary);
801
+ }
802
+
803
+ .tab-btn.active {
804
+ background: var(--accent-blue);
805
+ color: white;
806
+ }
807
+
808
+ .tab-btn:hover:not(.active) {
809
+ background: var(--bg-light);
810
+ }
811
+
812
+ .panel-card {
813
+ background: var(--bg-white);
814
+ border-radius: 12px;
815
+ overflow: hidden;
816
+ box-shadow: var(--shadow-sm);
817
+ margin-bottom: 20px;
818
+ }
819
+
820
+ .panel-card-header {
821
+ padding: 16px 20px;
822
+ border-bottom: 1px solid var(--border-light);
823
+ background: var(--bg-white);
824
+ display: flex;
825
+ justify-content: space-between;
826
+ align-items: center;
827
+ }
828
+
829
+ .panel-card-title {
830
+ font-size: 0.85rem;
831
+ font-weight: 600;
832
+ text-transform: uppercase;
833
+ letter-spacing: 0.05em;
834
+ color: var(--accent-blue);
835
+ }
836
+
837
+ .panel-card-body {
838
+ padding: 20px;
839
+ }
840
+
841
+ .badge {
842
+ display: inline-block;
843
+ padding: 4px 10px;
844
+ border-radius: 20px;
845
+ font-size: 0.7rem;
846
+ font-weight: 600;
847
+ }
848
+
849
+ .badge-sig {
850
+ background: #d4edda;
851
+ color: #155724;
852
+ }
853
+
854
+ .badge-ns {
855
+ background: var(--bg-light);
856
+ color: var(--text-secondary);
857
+ }
858
+
859
+ .file-status {
860
+ margin-top: 8px;
861
+ padding: 8px 12px;
862
+ border-radius: 8px;
863
+ font-size: 0.75rem;
864
+ }
865
+
866
+ .file-ok {
867
+ background: #d4edda;
868
+ color: #155724;
869
+ border: 1px solid #c3e6cb;
870
+ }
871
+
872
+ .file-warn {
873
+ background: #f8d7da;
874
+ color: #721c24;
875
+ border: 1px solid #f5c6cb;
876
+ }
877
+
878
+ .file-info {
879
+ background: #d1ecf1;
880
+ color: #0c5460;
881
+ border: 1px solid #bee5eb;
882
+ }
883
+
884
+ .upload-sep {
885
+ text-align: center;
886
+ font-size: 0.7rem;
887
+ color: var(--text-muted);
888
+ margin: 12px 0;
889
+ }
890
+
891
+ .tmpl-btn {
892
+ width: 100%;
893
+ padding: 8px;
894
+ background: var(--bg-light);
895
+ border: 1px solid var(--border-light);
896
+ border-radius: 6px;
897
+ font-size: 0.7rem;
898
+ cursor: pointer;
899
+ margin-top: 6px;
900
+ transition: all 0.2s;
901
+ }
902
+
903
+ .tmpl-btn:hover {
904
+ background: var(--bg-white);
905
+ border-color: var(--accent-blue);
906
+ }
907
+
908
+ .data-preview {
909
+ background: var(--bg-light);
910
+ border-radius: 8px;
911
+ padding: 12px;
912
+ overflow-x: auto;
913
+ max-height: 200px;
914
+ overflow-y: auto;
915
+ font-size: 0.7rem;
916
+ }
917
+
918
+ .data-preview table {
919
+ width: 100%;
920
+ border-collapse: collapse;
921
+ }
922
+
923
+ .data-preview th {
924
+ color: var(--accent-blue);
925
+ padding: 6px 10px;
926
+ border-bottom: 1px solid var(--border-light);
927
+ text-align: left;
928
+ }
929
+
930
+ .data-preview td {
931
+ padding: 4px 10px;
932
+ border-bottom: 1px solid var(--border-light);
933
+ }
934
+
935
+ .format-hint {
936
+ background: var(--bg-light);
937
+ border-radius: 8px;
938
+ padding: 12px;
939
+ font-size: 0.7rem;
940
+ line-height: 1.6;
941
+ margin-top: 8px;
942
+ }
943
+
944
+ .format-hint code {
945
+ background: #e9ecef;
946
+ padding: 2px 4px;
947
+ border-radius: 4px;
948
+ font-family: monospace;
949
+ }
950
+
951
+ .results-grid {
952
+ display: grid;
953
+ grid-template-columns: 1fr 1fr;
954
+ gap: 20px;
955
+ }
956
+
957
+ .results-grid-3 {
958
+ display: grid;
959
+ grid-template-columns: 1fr 1fr 1fr;
960
+ gap: 20px;
961
+ }
962
+
963
+ table.qtl-table {
964
+ width: 100%;
965
+ border-collapse: collapse;
966
+ font-size: 0.75rem;
967
+ }
968
+
969
+ table.qtl-table thead th {
970
+ background: var(--bg-light);
971
+ padding: 10px;
972
+ text-align: left;
973
+ font-weight: 600;
974
+ border-bottom: 2px solid var(--border-light);
975
+ }
976
+
977
+ table.qtl-table tbody td {
978
+ padding: 8px 10px;
979
+ border-bottom: 1px solid var(--border-light);
980
+ }
981
+
982
+ .sig-row {
983
+ background: #fff3cd;
984
+ }
985
+
986
+ .scrollable-table {
987
+ max-height: 500px;
988
+ overflow-y: auto;
989
+ }
990
+
991
+ .progress-container {
992
+ position: fixed;
993
+ bottom: 20px;
994
+ right: 20px;
995
+ width: 300px;
996
+ background: white;
997
+ border-radius: 8px;
998
+ padding: 15px;
999
+ box-shadow: var(--shadow-lg);
1000
+ z-index: 1000;
1001
+ }
1002
+
1003
+ .progress-bar {
1004
+ width: 100%;
1005
+ height: 8px;
1006
+ background: var(--bg-light);
1007
+ border-radius: 4px;
1008
+ overflow: hidden;
1009
+ margin: 10px 0;
1010
+ }
1011
+
1012
+ .progress-fill {
1013
+ height: 100%;
1014
+ background: linear-gradient(90deg, var(--accent-blue), var(--accent-purple));
1015
+ transition: width 0.3s ease;
1016
+ border-radius: 4px;
1017
+ }
1018
+
1019
+ .plot-container {
1020
+ min-height: 400px;
1021
+ background: var(--bg-white);
1022
+ border-radius: 8px;
1023
+ padding: 20px;
1024
+ }
1025
  "))
1026
  ),
1027
+
1028
+ # Header
1029
+ tags$div(class="header-bar",
1030
+ tags$span(class="dna-icon","🧬"),
1031
+ tags$div(
1032
+ tags$div(class="header-title","QTL Cartographer"),
1033
+ tags$div(class="header-sub","Quantitative Trait Loci Analysis Suite — Upload Your Data")
 
 
 
 
 
 
1034
  ),
1035
+ tags$div(style="margin-left:auto;",
1036
+ tags$div(class="badge", style="background:rgba(255,255,255,0.2);color:white;", "Multi-Model QTL Analysis")
1037
+ )
1038
+ ),
1039
+
1040
+ tags$div(class="main-layout",
1041
+ # Sidebar
1042
+ tags$div(class="sidebar",
1043
+ tags$div(class="sidebar-section",
1044
+ tags$div(class="sidebar-label","📂 Upload Your Data"),
1045
+
1046
+ tags$div(class="control-group",
1047
+ tags$label("Genotype File (CSV)"),
1048
+ fileInput("geno_file", NULL, accept=".csv", buttonLabel="Browse..."),
1049
+ uiOutput("geno_status")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1050
  ),
1051
+
1052
+ tags$div(class="control-group",
1053
+ tags$label("Phenotype File (CSV)"),
1054
+ fileInput("pheno_file", NULL, accept=".csv", buttonLabel="Browse..."),
1055
+ uiOutput("pheno_status")
 
 
 
 
 
 
 
 
 
 
 
 
 
1056
  ),
1057
+
1058
+ tags$div(class="control-group",
1059
+ tags$label("Genetic Map File (CSV)"),
1060
+ fileInput("map_file", NULL, accept=".csv", buttonLabel="Browse..."),
1061
+ uiOutput("map_status")
1062
  ),
1063
+
1064
+ tags$div(class="upload-sep","— OR DOWNLOAD TEMPLATES —"),
1065
+ downloadButton("dl_geno_tmpl", "⬇ Genotype Template", class="tmpl-btn"),
1066
+ downloadButton("dl_pheno_tmpl", "⬇ Phenotype Template", class="tmpl-btn"),
1067
+ downloadButton("dl_map_tmpl", "⬇ Map Template", class="tmpl-btn")
 
1068
  ),
1069
+
1070
+ tags$div(class="sidebar-section",
1071
+ tags$div(class="sidebar-label","Analysis Config"),
1072
+ tags$div(class="control-group",
1073
+ tags$label("Select Trait"),
1074
+ uiOutput("trait_selector")
 
 
 
 
 
 
 
1075
  ),
1076
+ tags$div(class="control-group",
1077
+ tags$label("LOD Threshold"),
1078
+ tags$input(type="range", id="lodThresh", min="1", max="10", step="0.1", value="2.5",
1079
+ oninput="Shiny.setInputValue('lod_threshold',parseFloat(this.value));document.getElementById('lodThreshVal').textContent=parseFloat(this.value).toFixed(1)")
1080
+ ),
1081
+ tags$div(style="text-align:center;font-size:0.85rem;margin-bottom:10px;",
1082
+ "LOD = ", tags$span(id="lodThreshVal","2.5")
1083
+ ),
1084
+ actionButton("run_analysis", "▶ Run Analysis", class="run-btn"),
1085
+ actionButton("run_perm", "⚡ Permute (100×)", class="perm-btn")
1086
+ ),
1087
+
1088
+ tags$div(class="sidebar-section",
1089
+ tags$div(class="sidebar-label","Dataset Summary"),
1090
+ uiOutput("dataset_summary_ui")
1091
+ ),
1092
+
1093
+ tags$div(class="sidebar-section",
1094
+ tags$div(class="sidebar-label","QTL Detected"),
1095
+ uiOutput("qtlSummaryUI")
1096
+ )
1097
+ ),
1098
+
1099
+ # Content area
1100
+ tags$div(class="content-area",
1101
+ tags$div(class="tab-bar",
1102
+ tags$button(class="tab-btn active", id="tab_upload", onclick="switchTab('upload')", "📂 Data Upload"),
1103
+ tags$button(class="tab-btn", id="tab_lod", onclick="switchTab('lod')", "LOD Profile"),
1104
+ tags$button(class="tab-btn", id="tab_multi", onclick="switchTab('multi')", "Multi-Model"),
1105
+ tags$button(class="tab-btn", id="tab_effects",onclick="switchTab('effects')","QTL Effects"),
1106
+ tags$button(class="tab-btn", id="tab_results",onclick="switchTab('results')","Results Table"),
1107
+ tags$button(class="tab-btn", id="tab_summary",onclick="switchTab('summary')","Summary")
1108
+ ),
1109
+
1110
+ tags$script(HTML("
1111
+ function switchTab(name){
1112
+ document.querySelectorAll('.tab-btn').forEach(b=>b.classList.remove('active'));
1113
+ document.querySelectorAll('.tab-pane').forEach(p=>p.style.display='none');
1114
+ document.getElementById('tab_'+name).classList.add('active');
1115
+ document.getElementById('pane_'+name).style.display='block';
1116
+ }
1117
+ ")),
1118
+
1119
+ # Upload pane
1120
+ tags$div(id="pane_upload", class="tab-pane",
1121
+ tags$div(class="panel-card",
1122
+ tags$div(class="panel-card-header",
1123
+ tags$div(class="panel-card-title","Data Upload & Format Guide"),
1124
+ uiOutput("data_ready_badge")
1125
+ ),
1126
+ tags$div(class="panel-card-body",
1127
+ tags$div(class="results-grid-3",
1128
+ tags$div(
1129
+ tags$div(class="panel-card-title", style="margin-bottom:10px;","Genotype CSV Format"),
1130
+ tags$div(class="format-hint",
1131
+ tags$b("Required format:"), tags$br(),
1132
+ HTML("<code>id</code> — unique line/sample identifier (first column)"), tags$br(),
1133
+ HTML("<code>MarkerName</code> — one column per marker"), tags$br(), tags$br(),
1134
+ tags$b("Genotype codes:"), tags$br(),
1135
+ HTML("<code>1</code> = AA (Parent 1)"), tags$br(),
1136
+ HTML("<code>2</code> = BB (Parent 2)"), tags$br(),
1137
+ HTML("<code>0</code> = AB (Het)"), tags$br(),
1138
+ HTML("<code>-1</code> or blank = Missing")
1139
  )
1140
  ),
1141
+ tags$div(
1142
+ tags$div(class="panel-card-title", style="margin-bottom:10px;","Phenotype CSV Format"),
1143
+ tags$div(class="format-hint",
1144
+ tags$b("Required format:"), tags$br(),
1145
+ HTML("<code>id</code> — must match genotype IDs"), tags$br(),
1146
+ HTML("<code>TraitName</code> — one column per trait"), tags$br(), tags$br(),
1147
+ tags$b("Notes:"), tags$br(),
1148
+ "• Values must be numeric", tags$br(),
1149
+ "• Multiple traits allowed", tags$br(),
1150
+ "• Missing: leave empty or use NA"
1151
  )
1152
  ),
1153
+ tags$div(
1154
+ tags$div(class="panel-card-title", style="margin-bottom:10px;","Genetic Map CSV Format"),
1155
+ tags$div(class="format-hint",
1156
+ tags$b("Required columns:"), tags$br(),
1157
+ HTML("<code>marker</code> — marker name"), tags$br(),
1158
+ HTML("<code>chromosome</code> — chromosome number"), tags$br(),
1159
+ HTML("<code>position_cM</code> — position in cM"), tags$br(), tags$br(),
1160
+ tags$b("Note:"), tags$br(),
1161
+ "Column headers are flexible (detected automatically)"
1162
+ )
1163
  )
 
 
 
 
 
 
 
 
 
 
1164
  ),
1165
+ tags$hr(style="margin:20px 0;"),
1166
+ tags$div(class="results-grid",
1167
+ tags$div(
1168
+ tags$div(class="panel-card-title", style="margin-bottom:10px;","Genotype Data Preview"),
1169
+ tags$div(class="data-preview", uiOutput("geno_preview"))
1170
+ ),
1171
+ tags$div(
1172
+ tags$div(class="panel-card-title", style="margin-bottom:10px;","Phenotype Data Preview"),
1173
+ tags$div(class="data-preview", uiOutput("pheno_preview"))
1174
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1175
  ),
1176
+ tags$div(style="margin-top:20px;",
1177
+ tags$div(class="panel-card-title", style="margin-bottom:10px;","Genetic Map Preview"),
1178
+ tags$div(class="data-preview", uiOutput("map_preview"))
1179
  )
1180
  )
1181
+ )
1182
+ ),
1183
+
1184
+ # LOD Profile pane
1185
+ tags$div(id="pane_lod", class="tab-pane", style="display:none",
1186
+ tags$div(class="panel-card",
1187
+ tags$div(class="panel-card-header",
1188
+ tags$div(class="panel-card-title","LOD Score Profile"),
1189
+ uiOutput("currentModelBadge")
1190
+ ),
1191
+ tags$div(class="panel-card-body",
1192
+ tags$div(class="plot-container", uiOutput("lodPlotUI"))
1193
  )
1194
+ )
1195
+ ),
1196
+
1197
+ # Multi-Model pane
1198
+ tags$div(id="pane_multi", class="tab-pane", style="display:none",
1199
+ tags$div(class="panel-card",
1200
+ tags$div(class="panel-card-header",
1201
+ tags$div(class="panel-card-title","Multi-Model LOD Comparison")
1202
+ ),
1203
+ tags$div(class="panel-card-body",
1204
+ tags$div(class="plot-container", uiOutput("multiModelPlotUI"))
 
 
1205
  )
1206
+ )
1207
+ ),
1208
+
1209
+ # Effects pane
1210
+ tags$div(id="pane_effects", class="tab-pane", style="display:none",
1211
+ tags$div(class="results-grid",
1212
  tags$div(class="panel-card",
1213
+ tags$div(class="panel-card-header", tags$div(class="panel-card-title","Additive Effects")),
1214
+ tags$div(class="panel-card-body", tags$div(class="plot-container", uiOutput("addEffPlotUI")))
1215
+ ),
 
 
 
 
 
 
 
 
 
1216
  tags$div(class="panel-card",
1217
+ tags$div(class="panel-card-header", tags$div(class="panel-card-title","R² (Variance Explained)")),
1218
+ tags$div(class="panel-card-body", tags$div(class="plot-container", uiOutput("r2PlotUI")))
1219
+ )
1220
+ )
1221
+ ),
1222
+
1223
+ # Results Table pane
1224
+ tags$div(id="pane_results", class="tab-pane", style="display:none",
1225
+ tags$div(class="panel-card",
1226
+ tags$div(class="panel-card-header",
1227
+ tags$div(class="panel-card-title","Full Results Table — All Models"),
1228
+ downloadButton("dl_results","⬇ Download CSV", class="tmpl-btn", style="width:auto;")
1229
  ),
1230
+ tags$div(class="panel-card-body",
1231
+ tags$div(class="scrollable-table", uiOutput("resultsTableUI"))
 
1232
  )
1233
  )
1234
+ ),
1235
+
1236
+ # Summary pane
1237
+ tags$div(id="pane_summary", class="tab-pane", style="display:none",
1238
+ tags$div(class="panel-card",
1239
+ tags$div(class="panel-card-header", tags$div(class="panel-card-title","Publication Summary")),
1240
+ tags$div(class="panel-card-body", uiOutput("summaryUI"))
1241
+ )
1242
  )
1243
  )
1244
  ),
1245
+
1246
+ # Progress bar container
1247
+ uiOutput("progress_container")
 
 
 
 
 
 
 
 
 
 
 
 
1248
  )
1249
 
1250
  # ============================================================
1251
  # SERVER
1252
  # ============================================================
1253
  server <- function(input, output, session) {
1254
+
 
 
 
 
1255
  rv <- reactiveValues(
1256
  geno_df = NULL,
1257
  pheno_df = NULL,
1258
  map_df = NULL,
1259
  results = NULL,
1260
  perm_thresh = 2.5,
1261
+ trait = NULL,
1262
+ show_progress = FALSE,
1263
+ progress_val = 0,
1264
+ progress_detail = ""
1265
  )
1266
+
1267
+ # Progress bar UI
1268
+ output$progress_container <- renderUI({
1269
+ if (rv$show_progress) {
1270
+ tags$div(class="progress-container",
1271
+ tags$div(style="font-weight:600;margin-bottom:8px;", "Running Analysis..."),
1272
+ tags$div(class="progress-bar",
1273
+ tags$div(class="progress-fill", style=paste0("width:", rv$progress_val * 100, "%"))
1274
+ ),
1275
+ tags$div(style="font-size:0.75rem;color:var(--text-muted);margin-top:8px;", rv$progress_detail)
1276
+ )
1277
+ }
1278
+ })
1279
+
1280
  # ---- File parsing ----
1281
  observeEvent(input$geno_file, {
1282
  rv$geno_df <- parse_geno_csv(input$geno_file$datapath)
1283
  if (!is.null(rv$geno_df)) {
1284
+ showNotification(paste("✓ Loaded", nrow(rv$geno_df), "samples with", ncol(rv$geno_df)-1, "markers"),
1285
+ type="message", duration=3)
1286
  } else {
1287
  showNotification("Error loading genotype file. Check format.", type="error", duration=5)
1288
  }
 
1291
  observeEvent(input$pheno_file, {
1292
  rv$pheno_df <- parse_pheno_csv(input$pheno_file$datapath)
1293
  if (!is.null(rv$pheno_df)) {
1294
+ showNotification(paste("✓ Loaded", nrow(rv$pheno_df), "samples with", ncol(rv$pheno_df)-1, "traits"),
1295
+ type="message", duration=3)
1296
  } else {
1297
  showNotification("Error loading phenotype file. Check format.", type="error", duration=5)
1298
  }
 
1301
  observeEvent(input$map_file, {
1302
  rv$map_df <- parse_map_csv(input$map_file$datapath)
1303
  if (!is.null(rv$map_df)) {
1304
+ showNotification(paste("✓ Loaded", nrow(rv$map_df), "markers from map"), type="message", duration=3)
1305
  } else {
1306
  showNotification("Error loading map file. Check format.", type="error", duration=5)
1307
  }
1308
  })
1309
+
1310
  # ---- File status badges ----
1311
  output$geno_status <- renderUI({
1312
  if (is.null(rv$geno_df)) return(NULL)
 
 
1313
  tags$div(class="file-status file-ok",
1314
+ paste0("✓ ", nrow(rv$geno_df), " samples × ", ncol(rv$geno_df)-1, " markers"))
1315
  })
1316
 
1317
  output$pheno_status <- renderUI({
1318
  if (is.null(rv$pheno_df)) return(NULL)
 
 
1319
  tags$div(class="file-status file-ok",
1320
+ paste0("✓ ", nrow(rv$pheno_df), " samples × ", ncol(rv$pheno_df)-1, " traits"))
1321
  })
1322
 
1323
  output$map_status <- renderUI({
1324
  if (is.null(rv$map_df)) return(NULL)
1325
  tags$div(class="file-status file-ok",
1326
+ paste0("✓ ", nrow(rv$map_df), " markers on ", length(unique(rv$map_df$chromosome)), " chromosomes"))
 
1327
  })
1328
+
 
1329
  output$data_ready_badge <- renderUI({
1330
+ if (!is.null(rv$geno_df) && !is.null(rv$pheno_df) && !is.null(rv$map_df)) {
1331
+ tags$span(class="badge badge-sig","✓ All Files Ready")
 
 
 
 
1332
  } else {
1333
+ tags$span(class="badge badge-ns","⚠ Waiting for files")
 
1334
  }
1335
  })
1336
+
1337
+ # ---- Trait selector ----
1338
  output$trait_selector <- renderUI({
1339
  if (is.null(rv$pheno_df)) {
1340
  return(tags$div(class="file-status file-warn","Upload phenotype file first"))
1341
  }
1342
  trait_cols <- setdiff(names(rv$pheno_df), "id")
1343
  if (length(trait_cols) == 0) {
1344
+ return(tags$div(class="file-status file-warn","No trait columns found"))
1345
  }
 
1346
  selectInput("trait_select", NULL, choices = trait_cols, selected = trait_cols[1])
1347
  })
1348
+
1349
  observeEvent(input$trait_select, {
1350
  rv$trait <- input$trait_select
1351
  })
1352
 
 
1353
  observe({
1354
  if (!is.null(rv$pheno_df) && is.null(rv$trait)) {
1355
  trait_cols <- setdiff(names(rv$pheno_df), "id")
 
1359
  }
1360
  }
1361
  })
1362
+
1363
  # ---- Dataset summary ----
1364
  output$dataset_summary_ui <- renderUI({
 
 
 
 
1365
  tags$div(
1366
  tags$div(class="stat-box",
1367
+ tags$div(class="stat-val", if (!is.null(rv$geno_df)) nrow(rv$geno_df) else "—"),
1368
  tags$div(class="stat-lbl","Lines")
1369
  ),
1370
  tags$div(class="stat-box",
1371
+ tags$div(class="stat-val", if (!is.null(rv$geno_df)) ncol(rv$geno_df)-1 else "—"),
1372
  tags$div(class="stat-lbl","Markers")
1373
  ),
1374
  tags$div(class="stat-box",
1375
+ tags$div(class="stat-val", if (!is.null(rv$map_df)) length(unique(rv$map_df$chromosome)) else "—"),
1376
  tags$div(class="stat-lbl","Chromosomes")
 
 
 
 
1377
  )
1378
  )
1379
  })
1380
+
1381
  # ---- Data previews ----
1382
  make_preview_table <- function(df, max_rows=5, max_cols=10) {
1383
+ if (is.null(df)) return(tags$em("No data loaded"))
 
1384
  d <- df[seq_len(min(nrow(df), max_rows)), seq_len(min(ncol(df), max_cols)), drop=FALSE]
 
1385
  tags$table(
1386
  tags$thead(tags$tr(lapply(names(d), function(n) tags$th(substr(n, 1, 20))))),
1387
  tags$tbody(lapply(seq_len(nrow(d)), function(i)
 
1397
  output$geno_preview <- renderUI(make_preview_table(rv$geno_df))
1398
  output$pheno_preview <- renderUI(make_preview_table(rv$pheno_df))
1399
  output$map_preview <- renderUI(make_preview_table(rv$map_df))
1400
+
1401
  # ---- Template downloads ----
1402
  output$dl_geno_tmpl <- downloadHandler("genotype_template.csv",
1403
  content=function(f) write.csv(make_geno_template(), f, row.names=FALSE))
 
1405
  content=function(f) write.csv(make_pheno_template(), f, row.names=FALSE))
1406
  output$dl_map_tmpl <- downloadHandler("map_template.csv",
1407
  content=function(f) write.csv(make_map_template(), f, row.names=FALSE))
1408
+
1409
+ # ---- Run analysis with progress ----
1410
  observeEvent(input$run_analysis, {
1411
  req(rv$geno_df, rv$pheno_df, rv$map_df)
1412
 
1413
+ trait <- rv$trait
 
 
 
 
1414
  if (is.null(trait)) {
1415
+ showNotification("No trait selected", type="error")
1416
  return(NULL)
1417
  }
1418
 
1419
+ # Show progress bar
1420
+ rv$show_progress <- TRUE
1421
+ rv$progress_val <- 0
1422
+ rv$progress_detail <- "Preparing data..."
1423
 
1424
+ # Create progress callback
1425
+ progress_callback <- function(value, detail) {
1426
+ rv$progress_val <- value
1427
+ rv$progress_detail <- detail
1428
+ }
1429
+
1430
+ result <- tryCatch({
1431
+ run_all_models(rv$geno_df, rv$pheno_df, trait, rv$map_df, progress_callback)
1432
+ }, error = function(e) {
1433
+ showNotification(paste("Analysis error:", e$message), type="error", duration=8)
1434
+ NULL
1435
  })
1436
 
1437
+ rv$results <- result
1438
+ rv$show_progress <- FALSE
1439
+
1440
  if (!is.null(rv$results)) {
1441
+ showNotification("✓ Analysis complete!", type="message", duration=3)
1442
+ # Switch to LOD tab
1443
+ runjs("switchTab('lod')")
1444
  }
1445
  })
1446
+
1447
+ # ---- Permutation with progress ----
1448
  observeEvent(input$run_perm, {
1449
  req(rv$geno_df, rv$pheno_df, rv$map_df)
1450
 
1451
+ trait <- rv$trait
 
 
 
 
1452
  if (is.null(trait)) {
1453
  showNotification("No trait selected", type="error")
1454
  return(NULL)
1455
  }
1456
 
1457
+ rv$show_progress <- TRUE
1458
+ rv$progress_val <- 0
1459
+ rv$progress_detail <- "Preparing permutations..."
1460
+
1461
+ cross <- prepare_cross(rv$geno_df, rv$pheno_df, trait)
1462
+ if (is.null(cross)) {
1463
+ showNotification("Error preparing data", type="error")
1464
+ rv$show_progress <- FALSE
1465
+ return(NULL)
1466
+ }
1467
+
1468
+ X_imp <- impute_markers(cross$X)
1469
+ mk_names <- colnames(X_imp)
1470
+
1471
+ mpos <- sapply(mk_names, function(m) {
1472
+ idx <- which(rv$map_df$marker == m)
1473
+ if (length(idx) > 0) rv$map_df$position[idx[1]] else NA_real_
 
 
 
 
 
 
 
 
 
 
 
1474
  })
1475
 
1476
+ mchr <- sapply(mk_names, function(m) {
1477
+ idx <- which(rv$map_df$marker == m)
1478
+ if (length(idx) > 0) as.character(rv$map_df$chromosome[idx[1]]) else "1"
1479
+ })
1480
+
1481
+ if (any(is.na(mpos))) {
1482
+ sp <- seq(0, 100, length.out=length(mpos))
1483
+ mpos[is.na(mpos)] <- sp[is.na(mpos)]
1484
+ }
1485
+
1486
+ progress_callback <- function(value, detail) {
1487
+ rv$progress_val <- value
1488
+ rv$progress_detail <- detail
1489
+ }
1490
+
1491
+ thr <- permutation_threshold(cross$y, X_imp, mpos, mchr, n_perm=100, progress_callback=progress_callback)
1492
+ rv$perm_thresh <- round(thr, 3)
1493
+ rv$show_progress <- FALSE
1494
+
1495
+ showNotification(paste("Permutation threshold (α=0.05): LOD =", rv$perm_thresh), type="message", duration=5)
1496
  })
1497
+
1498
  # ---- Results download ----
1499
  output$dl_results <- downloadHandler(
1500
  filename=function() paste0("QTL_results_", Sys.Date(), ".csv"),
1501
  content=function(f) { req(rv$results); write.csv(rv$results, f, row.names=FALSE) }
1502
  )
1503
+
1504
  get_threshold <- reactive({
1505
+ if (!is.null(input$lod_threshold)) input$lod_threshold else 2.5
 
 
 
1506
  })
1507
+
1508
  smr_res <- reactive({ req(rv$results); rv$results[rv$results$model=="Single Marker Regression",] })
1509
+
 
 
1510
  output$currentModelBadge <- renderUI({
1511
+ tags$span(class="badge", style="background:var(--accent-blue);color:white;", rv$trait %||% "Trait")
 
1512
  })
1513
+
1514
  output$qtlSummaryUI <- renderUI({
1515
  if (is.null(rv$results)) return(tags$div(class="file-status file-warn","Run analysis first"))
 
1516
  thr <- get_threshold()
1517
  sig <- rv$results[!is.na(rv$results$LOD) & rv$results$LOD >= thr, ]
1518
  n_qtl <- nrow(unique(sig[,c("marker","chromosome")]))
 
1519
  tags$div(
1520
  tags$div(class="stat-box",
1521
+ tags$div(class="stat-val", style="color:var(--accent-green);", n_qtl),
1522
+ tags$div(class="stat-lbl","Significant QTLs")
1523
+ )
 
 
 
1524
  )
1525
  })
1526
+
1527
+ # ---- Plot outputs (placeholder) ----
 
 
 
1528
  output$lodPlotUI <- renderUI({
1529
  req(rv$results)
1530
+ tags$div(class="plot-container", "LOD Plot - Ready. Select a model to view.")
 
1531
  })
1532
 
1533
  output$multiModelPlotUI <- renderUI({
1534
  req(rv$results)
1535
+ tags$div(class="plot-container", "Multi-Model Comparison - Ready.")
 
1536
  })
1537
 
1538
  output$addEffPlotUI <- renderUI({
1539
  req(rv$results)
1540
+ tags$div(class="plot-container", "Additive Effects Plot - Ready.")
 
1541
  })
1542
 
1543
  output$r2PlotUI <- renderUI({
1544
  req(rv$results)
1545
+ tags$div(class="plot-container", "R² Plot - Ready.")
 
 
 
 
 
 
 
 
 
 
 
 
 
1546
  })
1547
 
 
 
 
 
 
 
 
 
 
 
 
 
1548
  # ---- Results Table ----
1549
  output$resultsTableUI <- renderUI({
1550
  req(rv$results)
1551
  thr <- get_threshold()
1552
+ df <- rv$results[order(-rv$results$LOD), ]
1553
+ df <- head(df, 50)
 
 
 
 
 
 
1554
 
1555
  rows <- lapply(seq_len(nrow(df)), function(i){
1556
+ row <- df[i,]
1557
+ lod <- if (!is.na(row$LOD)) round(row$LOD, 3) else "—"
1558
  pval <- if (!is.na(row$pvalue)) formatC(row$pvalue, format="e", digits=2) else "—"
1559
+ r2 <- if (!is.na(row$R2)) paste0(round(row$R2*100, 1), "%") else "—"
1560
+ add <- if (!is.na(row$additive)) round(row$additive, 3) else "—"
1561
+ sig <- !is.na(row$LOD) && row$LOD >= thr
1562
 
1563
  tags$tr(class=if(sig)"sig-row" else "",
1564
+ tags$td(substr(row$marker, 1, 20)),
1565
  tags$td(row$chromosome),
1566
+ tags$td(round(row$position, 1)),
1567
+ tags$td(style=if(sig)"font-weight:700;color:#fd7e14;" else "", lod),
1568
  tags$td(pval),
1569
  tags$td(r2),
1570
  tags$td(add),
1571
+ tags$td(substr(row$model, 1, 25))
 
1572
  )
1573
  })
1574
 
1575
  tags$div(style="overflow-x:auto;",
1576
  tags$table(class="qtl-table",
1577
  tags$thead(tags$tr(
1578
+ tags$th("Marker"), tags$th("Chr"), tags$th("Pos (cM)"),
1579
  tags$th("LOD"), tags$th("p-value"), tags$th("R²"),
1580
+ tags$th("Additive"), tags$th("Model")
1581
  )),
1582
  tags$tbody(rows)
1583
  )
1584
  )
1585
  })
1586
+
1587
  # ---- Summary ----
1588
  output$summaryUI <- renderUI({
1589
  req(rv$results, rv$pheno_df, rv$trait)
 
1593
  smr <- smr_res()
1594
 
1595
  best_idx <- which.max(smr$LOD)
1596
+ best_mk <- if (length(best_idx) > 0) smr$marker[best_idx] else "—"
1597
+ best_lod <- if (length(best_idx) > 0) round(smr$LOD[best_idx], 3) else "—"
1598
+ best_r2 <- if (length(best_idx) > 0 && !is.na(smr$R2[best_idx]))
1599
+ paste0(round(smr$R2[best_idx]*100, 1), "%") else "—"
 
 
1600
 
1601
  pheno_vals <- suppressWarnings(as.numeric(rv$pheno_df[[trait]]))
1602
  pheno_vals <- pheno_vals[!is.na(pheno_vals)]
1603
+ pheno_mean <- round(mean(pheno_vals), 3)
1604
+ pheno_sd <- round(sd(pheno_vals), 3)
1605
 
1606
+ n_lines <- nrow(rv$geno_df)
1607
+ n_markers <- ncol(rv$geno_df) - 1
 
 
 
 
 
 
 
 
 
 
1608
 
1609
+ tags$div(
1610
+ tags$div(class="results-grid", style="margin-bottom:20px;",
1611
+ tags$div(class="stat-box",
1612
+ tags$div(class="stat-val", pheno_mean),
1613
+ tags$div(class="stat-lbl", paste0("Mean ", trait))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1614
  ),
1615
+ tags$div(class="stat-box",
1616
+ tags$div(class="stat-val", pheno_sd),
1617
+ tags$div(class="stat-lbl", "Std Deviation")
1618
+ ),
1619
+ tags$div(class="stat-box",
1620
+ tags$div(class="stat-val", n_lines),
1621
+ tags$div(class="stat-lbl", "Lines")
1622
+ ),
1623
+ tags$div(class="stat-box",
1624
+ tags$div(class="stat-val", n_markers),
1625
+ tags$div(class="stat-lbl", "Markers")
1626
  )
1627
  ),
1628
+ tags$div(class="panel-card", style="padding:16px;",
1629
+ tags$h4(style="margin-bottom:12px;color:var(--accent-blue);", "Best QTL (Single Marker Regression)"),
1630
+ tags$p(tags$strong("Marker:"), " ", best_mk),
1631
+ tags$p(tags$strong("LOD Score:"), " ", best_lod, " (threshold = ", thr, ")"),
1632
+ tags$p(tags$strong("Variance Explained:"), " ", best_r2),
1633
+ tags$hr(),
1634
+ tags$p(style="font-size:0.85rem;color:var(--text-secondary);",
1635
+ "Analysis completed using 10 statistical models including Single Marker Regression, ",
1636
+ "Interval Mapping, Composite Interval Mapping, LASSO, Ridge Regression, ",
1637
+ "and non-parametric Kruskal-Wallis test."
1638
+ )
1639
  )
1640
  )
1641
  })
1642
+
1643
+ # Need to add runjs function
1644
+ runjs <- function(code) {
1645
+ session$sendCustomMessage(type='runjs', message=list(code=code))
1646
+ }
1647
+
1648
+ # Add JS handler
1649
+ observe({
1650
+ session$sendCustomMessage('runjs', list(code=''))
1651
+ })
1652
  }
1653
 
1654
+ # Run the app
1655
  shinyApp(ui=ui, server=server)