softwareDevelopment commited on
Commit
c3e74b5
Β·
verified Β·
1 Parent(s): c43e3f2

Update app.R

Browse files
Files changed (1) hide show
  1. app.R +169 -101
app.R CHANGED
@@ -397,12 +397,19 @@ make_ggplot_manhattan <- function(cim_all, lod_threshold = 2.0, title = "CIM Man
397
  # HTML CHROMOSOME VISUALIZATION β€” matches on-screen display exactly
398
  # FIX: Replaced ggplot2 PNG export with HTML generator that replicates
399
  # the exact CSS/marker structure shown on-screen (same colors, interval
400
- # bands, tick heights, bp labels, legend).
401
  # ============================================================
402
  make_html_chromosome_viz <- function(qtl_effects, all_markers_df, lod_threshold = 2.0) {
403
  if (is.null(qtl_effects) || "Message" %in% colnames(qtl_effects)) return(NULL)
404
  if (is.null(all_markers_df) || nrow(all_markers_df) == 0) return(NULL)
405
 
 
 
 
 
 
 
 
406
  chromosomes <- unique(qtl_effects$Chromosome)
407
  chr_html <- ""
408
 
@@ -419,7 +426,7 @@ make_html_chromosome_viz <- function(qtl_effects, all_markers_df, lod_threshold
419
  flanking_markers <- c(chr_qtls$Low_Flank, chr_qtls$High_Flank)
420
  flanking_markers <- flanking_markers[!is.na(flanking_markers) & flanking_markers != ""]
421
 
422
- # Interval bands HTML (LOD-1.5 shading)
423
  interval_html <- ""
424
  if ("Interval_Start" %in% colnames(chr_qtls)) {
425
  for (j in 1:nrow(chr_qtls)) {
@@ -429,13 +436,17 @@ make_html_chromosome_viz <- function(qtl_effects, all_markers_df, lod_threshold
429
  right_pct <- ((qtl_row$Interval_End - min_pos) / range_pos) * 100
430
  width_pct <- max(0.5, right_pct - left_pct)
431
  interval_html <- paste0(interval_html, sprintf(
432
- '<div style="position:absolute;top:0;bottom:0;left:%.2f%%;width:%.2f%%;background:rgba(220,38,38,0.12);border-left:1px solid rgba(220,38,38,0.3);border-right:1px solid rgba(220,38,38,0.3);"></div>',
433
- left_pct, width_pct))
434
  }
435
  }
436
  }
437
 
438
- # Marker ticks HTML β€” replicates CSS classes exactly
 
 
 
 
439
  markers_html <- ""
440
  for (i in 1:nrow(chr_markers)) {
441
  marker <- chr_markers[i, ]
@@ -445,63 +456,62 @@ make_html_chromosome_viz <- function(qtl_effects, all_markers_df, lod_threshold
445
  (i / nrow(chr_markers)) * 100
446
  }
447
 
448
- tooltip <- paste0(marker$Marker, " | pos: ", format(marker$Position, big.mark = ","), " bp")
449
 
450
  if (marker$Marker %in% chr_qtls$Marker) {
451
- # Significant QTL β€” tallest, red, widest (matches .chromosome-marker.significant)
452
- lod_val <- chr_qtls$LOD[chr_qtls$Marker == marker$Marker][1]
453
- pve_val <- chr_qtls$PVE_Marker_Percent[chr_qtls$Marker == marker$Marker][1]
454
- tooltip <- paste0(marker$Marker, " | LOD: ", round(lod_val, 2),
455
- " | PVE_marker: ", round(pve_val, 1), "% | pos: ",
456
- format(marker$Position, big.mark = ","), " bp")
457
  style <- sprintf(
458
- 'position:absolute;left:%.2f%%;transform:translateX(-50%%);width:9px;height:42px;top:-9px;background:#DC2626;border-radius:3px;box-shadow:0 0 6px rgba(220,38,38,0.4);cursor:pointer;',
459
- left)
460
  } else if (marker$Marker %in% flanking_markers) {
461
- # Flanking marker β€” taller, blue (matches .chromosome-marker.flanking)
462
  style <- sprintf(
463
- 'position:absolute;left:%.2f%%;transform:translateX(-50%%);width:5px;height:30px;top:-3px;background:#1D4ED8;border-radius:3px;cursor:pointer;',
464
- left)
465
  } else {
466
- # Background marker β€” grey, short (matches .chromosome-marker default)
467
  style <- sprintf(
468
- 'position:absolute;left:%.2f%%;transform:translateX(-50%%);width:6px;height:34px;top:-5px;background:#94A3B8;border-radius:3px;opacity:0.6;',
469
- left)
470
  }
471
  markers_html <- paste0(markers_html,
472
  sprintf('<div style="%s" title="%s"></div>', style, tooltip))
473
  }
474
 
475
- # Title with interval sizes
476
  int_sizes_str <- ""
477
  if ("Interval_Size_Mb" %in% colnames(chr_qtls)) {
478
  sizes <- chr_qtls$Interval_Size_Mb[!is.na(chr_qtls$Interval_Size_Mb)]
479
  if (length(sizes) > 0)
480
  int_sizes_str <- paste0(
481
- ' <span style="color:#B45309;font-size:10px;">(LOD-1.5: ',
482
- paste(round(sizes, 2), collapse = ", "), ' Mb)</span>')
483
  }
484
 
485
  chr_html <- paste0(chr_html, sprintf('
486
- <div style="margin:12px 0;padding:12px 16px;background:#FFFFFF;border-radius:6px;border:1px solid #E2E8F0;box-shadow:0 1px 2px rgba(0,0,0,0.04);">
487
- <div style="font-family:IBM Plex Mono,monospace;font-size:11px;color:#1D4ED8;margin-bottom:4px;font-weight:600;">
488
  Chromosome %s &mdash; %d markers, %d QTLs%s
489
  </div>
490
- <div style="height:24px;background:linear-gradient(to right,#F1F5F9,#E2E8F0);border-radius:12px;margin:8px 0;position:relative;overflow:visible;border:1px solid #CBD5E1;">
491
  %s%s
492
  </div>
493
- <div style="display:flex;justify-content:space-between;font-size:10px;color:#94A3B8;font-family:IBM Plex Mono,monospace;margin-top:4px;">
494
- <span>%s bp</span>
495
- <span>%s bp</span>
496
  </div>
497
  </div>',
498
  chr, nrow(chr_markers), nrow(chr_qtls), int_sizes_str,
499
  interval_html, markers_html,
500
- format(min_pos, big.mark = ","),
501
- format(max_pos, big.mark = ",")))
502
  }
503
 
504
- # Full HTML page with same styling as on-screen
505
  html_content <- sprintf('<!DOCTYPE html>
506
  <html lang="en">
507
  <head>
@@ -513,58 +523,62 @@ make_html_chromosome_viz <- function(qtl_effects, all_markers_df, lod_threshold
513
  * { box-sizing: border-box; margin: 0; padding: 0; }
514
  body {
515
  font-family: "IBM Plex Sans", sans-serif;
516
- background: #F8FAFC;
517
- color: #1E293B;
518
- padding: 24px;
519
  font-size: 14px;
 
 
520
  }
521
  .page-header {
522
- background: linear-gradient(135deg, #EFF6FF, #DBEAFE);
523
- border: 1px solid #BFDBFE;
524
- border-left: 4px solid #1D4ED8;
525
  padding: 16px 20px;
526
  border-radius: 8px;
527
  margin-bottom: 20px;
 
528
  }
529
  .page-header h2 {
530
  font-family: "IBM Plex Mono", monospace;
531
- font-size: 1.1rem;
532
- color: #1D4ED8;
533
- margin-bottom: 6px;
 
534
  }
535
- .page-header p { color: #475569; font-size: 12px; }
536
  .chr-legend {
537
  display: flex;
538
- gap: 16px;
539
  padding: 10px 16px;
540
  font-size: 11px;
541
  flex-wrap: wrap;
542
  background: #FFFFFF;
543
- border: 1px solid #E2E8F0;
544
  border-radius: 6px;
545
  margin-bottom: 16px;
546
  align-items: center;
547
  }
548
- .legend-item { display: flex; align-items: center; gap: 5px; color: #475569; }
549
- .legend-dot { width: 10px; height: 10px; border-radius: 2px; flex-shrink: 0; }
550
  .note-box {
551
- background: #FEF9C3;
552
- border: 1px solid #FDE047;
553
  border-radius: 6px;
554
  padding: 10px 14px;
555
  margin-bottom: 16px;
556
- font-size: 11px;
557
  font-family: "IBM Plex Mono", monospace;
558
- color: #713F12;
559
  }
560
  .footer {
561
  text-align: center;
562
  font-size: 10px;
563
- color: #94A3B8;
564
  margin-top: 24px;
565
  font-family: "IBM Plex Mono", monospace;
566
  padding-top: 12px;
567
- border-top: 1px solid #E2E8F0;
568
  }
569
  </style>
570
  </head>
@@ -572,7 +586,7 @@ make_html_chromosome_viz <- function(qtl_effects, all_markers_df, lod_threshold
572
  <div class="page-header">
573
  <h2>&#x1F9EC; QTL Chromosome Map &mdash; CIM v5</h2>
574
  <p>
575
- Semi-partial R&sup2; PVE (fixed) &nbsp;|&nbsp;
576
  LOD-1.5 support intervals &nbsp;|&nbsp;
577
  &minus;1/0/+1 additive coding &nbsp;|&nbsp;
578
  LOD threshold: %.1f &nbsp;|&nbsp;
@@ -581,37 +595,38 @@ make_html_chromosome_viz <- function(qtl_effects, all_markers_df, lod_threshold
581
  </div>
582
 
583
  <div class="chr-legend">
584
- <strong style="font-family:IBM Plex Mono,monospace;font-size:10px;color:#475569;margin-right:4px;">LEGEND:</strong>
585
  <div class="legend-item">
586
- <div class="legend-dot" style="background:#DC2626;box-shadow:0 0 4px rgba(220,38,38,0.4);"></div>
587
  Significant QTL
588
  </div>
589
  <div class="legend-item">
590
- <div class="legend-dot" style="background:#1D4ED8;"></div>
591
  Flanking marker
592
  </div>
593
  <div class="legend-item">
594
- <div class="legend-dot" style="background:rgba(220,38,38,0.12);border:1px solid rgba(220,38,38,0.3);"></div>
595
  LOD-1.5 interval
596
  </div>
597
  <div class="legend-item">
598
- <div class="legend-dot" style="background:#94A3B8;opacity:0.6;"></div>
599
  All markers
600
  </div>
601
- <span style="color:#94A3B8;font-size:10px;margin-left:auto;">Hover markers for details</span>
602
  </div>
603
 
604
  <div class="note-box">
605
- PVE_CIM = semi-partial R&sup2; (fraction of cofactor-residual variance) &nbsp;|&nbsp;
606
- PVE_marker = unconditional R&sup2; (marker alone vs null) &nbsp;|&nbsp;
607
- Interval = all markers within 1.5 LOD of peak
 
608
  </div>
609
 
610
  %s
611
 
612
  <div class="footer">
613
  QTL-Mapper CIM v5 &nbsp;|&nbsp;
614
- LOD-1.5 support intervals (Lander &amp; Botstein 1989) &nbsp;|&nbsp;
615
  Semi-partial R&sup2; (Lynch &amp; Walsh 1998) &nbsp;|&nbsp;
616
  Contact: ashmithamganesan@gmail.com, P.sinha@cgiar.org
617
  </div>
@@ -872,19 +887,19 @@ ui <- fluidPage(
872
  .dataTables_filter input,.dataTables_length select{background:#FFFFFF!important;border:1px solid var(--border)!important;color:var(--text-primary)!important;border-radius:3px;}
873
  .paginate_button{color:var(--text-secondary)!important;}
874
  .paginate_button.current{background:var(--accent)!important;color:white!important;border-color:var(--accent)!important;}
875
- .chromosome-container{margin:12px 0;padding:12px 16px;background:#FFFFFF;border-radius:6px;border:1px solid var(--border);box-shadow:0 1px 2px rgba(0,0,0,.04);}
876
- .chromosome{height:24px;background:linear-gradient(to right,#F1F5F9,#E2E8F0);border-radius:12px;margin:8px 0;position:relative;overflow:hidden;border:1px solid #CBD5E1;}
877
- .chromosome-marker{position:absolute;height:34px;width:6px;background:#94A3B8;border-radius:3px;top:-5px;transform:translateX(-50%);transition:all .3s ease;}
878
- .chromosome-marker.significant{background:var(--danger)!important;height:42px!important;width:9px!important;top:-9px!important;box-shadow:0 0 6px rgba(220,38,38,.4);}
879
- .chromosome-marker.flanking{background:var(--accent)!important;height:30px!important;width:5px!important;top:-3px!important;}
880
- .chromosome-marker.selection{background:var(--success)!important;}
881
- .chromosome-marker.interval{background:#FBBF24!important;height:26px!important;width:4px!important;top:-1px!important;opacity:.7;}
882
- .chromosome-marker.highlighted{background:var(--warning)!important;box-shadow:0 0 10px rgba(180,83,9,.5);}
883
  .chromosome-marker.pulse{animation:pulse 1.5s infinite;}
884
- @keyframes pulse{0%,100%{transform:translateX(-50%) scale(1);}50%{transform:translateX(-50%) scale(1.3);opacity:.7;}}
885
- .chromosome-legend{display:flex;justify-content:space-between;font-size:10px;color:var(--text-muted);font-family:var(--font-mono);margin-top:2px;}
886
- .chromosome-title{font-family:var(--font-mono);font-size:11px;color:var(--accent);margin-bottom:4px;}
887
- .interval-band{position:absolute;top:0;bottom:0;background:rgba(220,38,38,.12);border:1px solid rgba(220,38,38,.2);}
888
  .chr-legend{display:flex;gap:16px;padding:8px 0;font-size:11px;flex-wrap:wrap;}
889
  .legend-item{display:flex;align-items:center;gap:5px;color:var(--text-secondary);}
890
  .legend-dot{width:10px;height:10px;border-radius:2px;}
@@ -1053,10 +1068,10 @@ ui <- fluidPage(
1053
  div(class = "card-header", "Chromosome Visualization β€” LOD-1.5 Intervals (download .html = same as this)"),
1054
  div(class = "card-body",
1055
  div(class = "chr-legend",
1056
- div(class = "legend-item", div(class = "legend-dot", style = "background:#DC2626;"), "Significant QTL"),
1057
- div(class = "legend-item", div(class = "legend-dot", style = "background:#1D4ED8;"), "Flanking marker"),
1058
- div(class = "legend-item", div(class = "legend-dot", style = "background:#FCA5A5;border:1px solid #DC2626;"), "LOD-1.5 interval"),
1059
- div(class = "legend-item", div(class = "legend-dot", style = "background:#CBD5E1;"), "All markers")
1060
  ),
1061
  uiOutput("chromosome_viz"),
1062
  div(style = "margin:12px 0;display:flex;gap:8px;",
@@ -1271,6 +1286,7 @@ server <- function(input, output, session) {
1271
  pop_data = NULL,
1272
  selection_metrics = NULL,
1273
  model_fit = NULL,
 
1274
  chat_messages = list(),
1275
  is_typing = FALSE,
1276
  lod_threshold = 2,
@@ -1490,7 +1506,8 @@ server <- function(input, output, session) {
1490
  train(x = X_tr_rf, y = y_train, method = "lm",
1491
  trControl = trainControl(method = "cv", number = 5))
1492
  })
1493
- values$model_fit <- model
 
1494
 
1495
  y_train_pred <- predict(model, X_tr_rf)
1496
  y_val_pred <- predict(model, X_v_rf)
@@ -1569,31 +1586,69 @@ server <- function(input, output, session) {
1569
  tryCatch({
1570
  withProgress(message = "Predicting test phenotypes...", value = 0, {
1571
 
1572
- incProgress(0.15, detail = "Checking test genotype data...")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1573
  Sys.sleep(0.1)
1574
 
1575
- common_m <- intersect(colnames(values$test_genotype_data), colnames(values$genotype_data))
1576
  if (length(common_m) == 0) {
1577
- showNotification("No common markers between test and training genotype.", type = "error")
 
 
 
1578
  return()
1579
  }
1580
 
1581
- incProgress(0.20, detail = paste0("Matched ", length(common_m), " markers to training set..."))
 
 
 
 
 
 
 
1582
  Sys.sleep(0.1)
1583
 
 
 
1584
  X_test <- values$test_genotype_data[, common_m, drop = FALSE]
1585
- n_test <- nrow(X_test)
1586
 
1587
- incProgress(0.25, detail = paste0("Prepared ", n_test, " test samples..."))
1588
- Sys.sleep(0.1)
 
 
 
 
 
 
 
 
 
 
 
 
1589
 
1590
- incProgress(0.25, detail = paste0("Running RF model on ", n_test, " samples..."))
1591
  preds <- predict(values$model_fit, newdata = X_test)
1592
 
1593
- incProgress(0.10, detail = "Assembling predictions table...")
 
1594
  values$predicted_test_phenotype_data <- data.frame(
1595
  id = rownames(X_test),
1596
- Predicted_Phenotype = as.numeric(preds),
1597
  stringsAsFactors = FALSE
1598
  )
1599
 
@@ -1601,19 +1656,32 @@ server <- function(input, output, session) {
1601
  Sys.sleep(0.15)
1602
  })
1603
 
 
1604
  showNotification(
1605
- paste0("βœ… Predicted ", nrow(values$predicted_test_phenotype_data),
1606
- " samples. Use Download button to save."),
1607
  type = "message", duration = 5
1608
  )
1609
  add_message("assistant", paste0(
1610
  "βœ… **Test phenotypes predicted!**\n\n",
1611
- "β€’ ", nrow(values$predicted_test_phenotype_data), " samples predicted\n",
1612
- "β€’ Markers used: ", length(intersect(colnames(values$test_genotype_data), colnames(values$genotype_data))), "\n",
1613
- "β€’ Preview in Data Upload β†’ 'Predicted Test Phenotype' tab\n",
 
 
1614
  "β€’ Click **Download Predicted Phenotypes (.xlsx)** to save"
1615
  ))
1616
- }, error = function(e) showNotification(paste("Predict error:", e$message), type = "error"))
 
 
 
 
 
 
 
 
 
 
 
1617
  })
1618
 
1619
  # ============================================================
@@ -1837,8 +1905,8 @@ server <- function(input, output, session) {
1837
  paste("Chromosome", chr, "β€”", nrow(chr_markers), "markers,", nrow(chr_qtls), "QTLs"),
1838
  if (nrow(chr_qtls) > 0 && "Interval_Size_Mb" %in% colnames(chr_qtls)) {
1839
  sizes <- chr_qtls$Interval_Size_Mb[!is.na(chr_qtls$Interval_Size_Mb)]
1840
- if (length(sizes) > 0) tags$span(style = "color:#B45309;margin-left:8px;",
1841
- paste0("(LOD-1.5: ", paste(round(sizes, 2), collapse=", "), " Mb)"))
1842
  }
1843
  ),
1844
  div(class = "chromosome", style = "position:relative;",
@@ -1862,12 +1930,12 @@ server <- function(input, output, session) {
1862
  mclass <- paste(mclass, "flanking")
1863
  }
1864
  div(class = mclass, style = paste0("left:", round(left, 2), "%;"),
1865
- title = paste0(marker$Marker, " pos:", marker$Position))
1866
  })
1867
  ),
1868
  div(class = "chromosome-legend",
1869
- span(paste(format(min_pos, big.mark=","), "bp")),
1870
- span(paste(format(max_pos, big.mark=","), "bp"))
1871
  )
1872
  )
1873
  }))
 
397
  # HTML CHROMOSOME VISUALIZATION β€” matches on-screen display exactly
398
  # FIX: Replaced ggplot2 PNG export with HTML generator that replicates
399
  # the exact CSS/marker structure shown on-screen (same colors, interval
400
+ # bands, tick heights, cM labels, publication colors).
401
  # ============================================================
402
  make_html_chromosome_viz <- function(qtl_effects, all_markers_df, lod_threshold = 2.0) {
403
  if (is.null(qtl_effects) || "Message" %in% colnames(qtl_effects)) return(NULL)
404
  if (is.null(all_markers_df) || nrow(all_markers_df) == 0) return(NULL)
405
 
406
+ # Publication color palette (RColorBrewer Set1 / Nature-style)
407
+ COL_QTL <- "#C0392B" # Pompeii red β€” significant QTL
408
+ COL_FLANK <- "#2166AC" # Steel blue β€” flanking markers
409
+ COL_BG <- "#6B7280" # Warm grey β€” background markers
410
+ COL_INTERVAL <- "rgba(192,57,43,0.14)" # translucent red β€” LOD-1.5 band
411
+ COL_INT_BDR <- "rgba(192,57,43,0.40)" # interval border
412
+
413
  chromosomes <- unique(qtl_effects$Chromosome)
414
  chr_html <- ""
415
 
 
426
  flanking_markers <- c(chr_qtls$Low_Flank, chr_qtls$High_Flank)
427
  flanking_markers <- flanking_markers[!is.na(flanking_markers) & flanking_markers != ""]
428
 
429
+ # ── Interval bands β€” contained inside bar (top:0;bottom:0) ──
430
  interval_html <- ""
431
  if ("Interval_Start" %in% colnames(chr_qtls)) {
432
  for (j in 1:nrow(chr_qtls)) {
 
436
  right_pct <- ((qtl_row$Interval_End - min_pos) / range_pos) * 100
437
  width_pct <- max(0.5, right_pct - left_pct)
438
  interval_html <- paste0(interval_html, sprintf(
439
+ '<div style="position:absolute;top:0;bottom:0;left:%.2f%%;width:%.2f%%;background:%s;border-left:1px solid %s;border-right:1px solid %s;pointer-events:none;"></div>',
440
+ left_pct, width_pct, COL_INTERVAL, COL_INT_BDR, COL_INT_BDR))
441
  }
442
  }
443
  }
444
 
445
+ # ── Marker ticks β€” ALL confined inside 28px bar (top:2px to top:6px range) ──
446
+ # Bar height = 28px. Ticks must stay within: top >= 1px, top+height <= 27px
447
+ # Significant: height=22px top=3px (3+22=25 ≀ 27 βœ“)
448
+ # Flanking: height=18px top=5px (5+18=23 ≀ 27 βœ“)
449
+ # Background: height=14px top=7px (7+14=21 ≀ 27 βœ“)
450
  markers_html <- ""
451
  for (i in 1:nrow(chr_markers)) {
452
  marker <- chr_markers[i, ]
 
456
  (i / nrow(chr_markers)) * 100
457
  }
458
 
459
+ pos_cm <- round(marker$Position, 1)
460
 
461
  if (marker$Marker %in% chr_qtls$Marker) {
462
+ lod_val <- chr_qtls$LOD[chr_qtls$Marker == marker$Marker][1]
463
+ pve_val <- chr_qtls$PVE_Marker_Percent[chr_qtls$Marker == marker$Marker][1]
464
+ tooltip <- paste0(marker$Marker,
465
+ " | LOD: ", round(lod_val, 2),
466
+ " | PVE: ", round(pve_val, 1), "%",
467
+ " | ", pos_cm, " cM")
468
  style <- sprintf(
469
+ 'position:absolute;left:%.2f%%;transform:translateX(-50%%);width:7px;height:22px;top:3px;background:%s;border-radius:2px;box-shadow:0 0 5px rgba(192,57,43,0.5);cursor:pointer;z-index:2;',
470
+ left, COL_QTL)
471
  } else if (marker$Marker %in% flanking_markers) {
472
+ tooltip <- paste0(marker$Marker, " (flanking) | ", pos_cm, " cM")
473
  style <- sprintf(
474
+ 'position:absolute;left:%.2f%%;transform:translateX(-50%%);width:4px;height:18px;top:5px;background:%s;border-radius:2px;cursor:pointer;z-index:1;',
475
+ left, COL_FLANK)
476
  } else {
477
+ tooltip <- paste0(marker$Marker, " | ", pos_cm, " cM")
478
  style <- sprintf(
479
+ 'position:absolute;left:%.2f%%;transform:translateX(-50%%);width:3px;height:14px;top:7px;background:%s;border-radius:1px;opacity:0.55;',
480
+ left, COL_BG)
481
  }
482
  markers_html <- paste0(markers_html,
483
  sprintf('<div style="%s" title="%s"></div>', style, tooltip))
484
  }
485
 
486
+ # Title with interval sizes in cM
487
  int_sizes_str <- ""
488
  if ("Interval_Size_Mb" %in% colnames(chr_qtls)) {
489
  sizes <- chr_qtls$Interval_Size_Mb[!is.na(chr_qtls$Interval_Size_Mb)]
490
  if (length(sizes) > 0)
491
  int_sizes_str <- paste0(
492
+ ' <span style="color:', COL_QTL, ';font-size:10px;font-weight:normal;">(LOD-1.5: ',
493
+ paste(round(sizes, 2), collapse = ", "), ' cM)</span>')
494
  }
495
 
496
  chr_html <- paste0(chr_html, sprintf('
497
+ <div style="margin:14px 0;padding:14px 18px;background:#FFFFFF;border-radius:8px;border:1px solid #D1D5DB;box-shadow:0 1px 4px rgba(0,0,0,0.06);">
498
+ <div style="font-family:IBM Plex Mono,monospace;font-size:11px;color:#1F3A6E;margin-bottom:6px;font-weight:600;">
499
  Chromosome %s &mdash; %d markers, %d QTLs%s
500
  </div>
501
+ <div style="height:28px;background:linear-gradient(to right,#E5E7EB,#D1D5DB);border-radius:14px;margin:8px 0;position:relative;overflow:hidden;border:1px solid #9CA3AF;">
502
  %s%s
503
  </div>
504
+ <div style="display:flex;justify-content:space-between;font-size:10px;color:#6B7280;font-family:IBM Plex Mono,monospace;margin-top:4px;letter-spacing:0.2px;">
505
+ <span>%.1f cM</span>
506
+ <span>%.1f cM</span>
507
  </div>
508
  </div>',
509
  chr, nrow(chr_markers), nrow(chr_qtls), int_sizes_str,
510
  interval_html, markers_html,
511
+ min_pos, max_pos))
 
512
  }
513
 
514
+ # Full HTML page β€” publication style
515
  html_content <- sprintf('<!DOCTYPE html>
516
  <html lang="en">
517
  <head>
 
523
  * { box-sizing: border-box; margin: 0; padding: 0; }
524
  body {
525
  font-family: "IBM Plex Sans", sans-serif;
526
+ background: #F9FAFB;
527
+ color: #111827;
528
+ padding: 28px;
529
  font-size: 14px;
530
+ max-width: 1100px;
531
+ margin: 0 auto;
532
  }
533
  .page-header {
534
+ background: #FFFFFF;
535
+ border: 1px solid #D1D5DB;
536
+ border-left: 4px solid #1F3A6E;
537
  padding: 16px 20px;
538
  border-radius: 8px;
539
  margin-bottom: 20px;
540
+ box-shadow: 0 1px 3px rgba(0,0,0,0.06);
541
  }
542
  .page-header h2 {
543
  font-family: "IBM Plex Mono", monospace;
544
+ font-size: 1.05rem;
545
+ color: #1F3A6E;
546
+ margin-bottom: 5px;
547
+ font-weight: 600;
548
  }
549
+ .page-header p { color: #6B7280; font-size: 11.5px; }
550
  .chr-legend {
551
  display: flex;
552
+ gap: 20px;
553
  padding: 10px 16px;
554
  font-size: 11px;
555
  flex-wrap: wrap;
556
  background: #FFFFFF;
557
+ border: 1px solid #D1D5DB;
558
  border-radius: 6px;
559
  margin-bottom: 16px;
560
  align-items: center;
561
  }
562
+ .legend-item { display: flex; align-items: center; gap: 6px; color: #374151; font-size: 11px; }
563
+ .legend-dot { width: 11px; height: 11px; border-radius: 2px; flex-shrink: 0; }
564
  .note-box {
565
+ background: #FFFBEB;
566
+ border: 1px solid #FCD34D;
567
  border-radius: 6px;
568
  padding: 10px 14px;
569
  margin-bottom: 16px;
570
+ font-size: 10.5px;
571
  font-family: "IBM Plex Mono", monospace;
572
+ color: #78350F;
573
  }
574
  .footer {
575
  text-align: center;
576
  font-size: 10px;
577
+ color: #9CA3AF;
578
  margin-top: 24px;
579
  font-family: "IBM Plex Mono", monospace;
580
  padding-top: 12px;
581
+ border-top: 1px solid #E5E7EB;
582
  }
583
  </style>
584
  </head>
 
586
  <div class="page-header">
587
  <h2>&#x1F9EC; QTL Chromosome Map &mdash; CIM v5</h2>
588
  <p>
589
+ Semi-partial R&sup2; PVE &nbsp;|&nbsp;
590
  LOD-1.5 support intervals &nbsp;|&nbsp;
591
  &minus;1/0/+1 additive coding &nbsp;|&nbsp;
592
  LOD threshold: %.1f &nbsp;|&nbsp;
 
595
  </div>
596
 
597
  <div class="chr-legend">
598
+ <strong style="font-family:IBM Plex Mono,monospace;font-size:10px;color:#6B7280;margin-right:2px;">LEGEND:</strong>
599
  <div class="legend-item">
600
+ <div class="legend-dot" style="background:#C0392B;box-shadow:0 0 4px rgba(192,57,43,0.4);"></div>
601
  Significant QTL
602
  </div>
603
  <div class="legend-item">
604
+ <div class="legend-dot" style="background:#2166AC;"></div>
605
  Flanking marker
606
  </div>
607
  <div class="legend-item">
608
+ <div class="legend-dot" style="background:rgba(192,57,43,0.14);border:1px solid rgba(192,57,43,0.4);"></div>
609
  LOD-1.5 interval
610
  </div>
611
  <div class="legend-item">
612
+ <div class="legend-dot" style="background:#6B7280;opacity:0.55;"></div>
613
  All markers
614
  </div>
615
+ <span style="color:#9CA3AF;font-size:10px;margin-left:auto;font-style:italic;">Hover markers for details</span>
616
  </div>
617
 
618
  <div class="note-box">
619
+ PVE_CIM = semi-partial R&sup2; &nbsp;|&nbsp;
620
+ PVE_marker = unconditional R&sup2; &nbsp;|&nbsp;
621
+ Interval = markers within 1.5 LOD of peak &nbsp;|&nbsp;
622
+ Positions in cM
623
  </div>
624
 
625
  %s
626
 
627
  <div class="footer">
628
  QTL-Mapper CIM v5 &nbsp;|&nbsp;
629
+ LOD-1.5 intervals (Lander &amp; Botstein 1989) &nbsp;|&nbsp;
630
  Semi-partial R&sup2; (Lynch &amp; Walsh 1998) &nbsp;|&nbsp;
631
  Contact: ashmithamganesan@gmail.com, P.sinha@cgiar.org
632
  </div>
 
887
  .dataTables_filter input,.dataTables_length select{background:#FFFFFF!important;border:1px solid var(--border)!important;color:var(--text-primary)!important;border-radius:3px;}
888
  .paginate_button{color:var(--text-secondary)!important;}
889
  .paginate_button.current{background:var(--accent)!important;color:white!important;border-color:var(--accent)!important;}
890
+ .chromosome-container{margin:14px 0;padding:14px 18px;background:#FFFFFF;border-radius:8px;border:1px solid #D1D5DB;box-shadow:0 1px 4px rgba(0,0,0,.06);}
891
+ .chromosome{height:28px;background:linear-gradient(to right,#E5E7EB,#D1D5DB);border-radius:14px;margin:10px 0;position:relative;overflow:hidden;border:1px solid #9CA3AF;}
892
+ .chromosome-marker{position:absolute;height:20px;width:4px;background:#6B7280;border-radius:1px;top:4px;transform:translateX(-50%);transition:all .3s ease;}
893
+ .chromosome-marker.significant{background:#C0392B!important;height:22px!important;width:7px!important;top:3px!important;box-shadow:0 0 5px rgba(192,57,43,.5);}
894
+ .chromosome-marker.flanking{background:#2166AC!important;height:20px!important;width:4px!important;top:4px!important;}
895
+ .chromosome-marker.selection{background:#1A7A4A!important;}
896
+ .chromosome-marker.interval{background:#E67E22!important;height:18px!important;width:3px!important;top:5px!important;opacity:.8;}
897
+ .chromosome-marker.highlighted{background:#8E44AD!important;box-shadow:0 0 8px rgba(142,68,173,.5);}
898
  .chromosome-marker.pulse{animation:pulse 1.5s infinite;}
899
+ @keyframes pulse{0%,100%{transform:translateX(-50%) scale(1);}50%{transform:translateX(-50%) scale(1.25);opacity:.75;}}
900
+ .chromosome-legend{display:flex;justify-content:space-between;font-size:10px;color:#6B7280;font-family:var(--font-mono);margin-top:3px;letter-spacing:0.3px;}
901
+ .chromosome-title{font-family:var(--font-mono);font-size:11px;color:#1F3A6E;margin-bottom:4px;font-weight:600;}
902
+ .interval-band{position:absolute;top:0;bottom:0;background:rgba(192,57,43,.13);border-left:1px solid rgba(192,57,43,.35);border-right:1px solid rgba(192,57,43,.35);}
903
  .chr-legend{display:flex;gap:16px;padding:8px 0;font-size:11px;flex-wrap:wrap;}
904
  .legend-item{display:flex;align-items:center;gap:5px;color:var(--text-secondary);}
905
  .legend-dot{width:10px;height:10px;border-radius:2px;}
 
1068
  div(class = "card-header", "Chromosome Visualization β€” LOD-1.5 Intervals (download .html = same as this)"),
1069
  div(class = "card-body",
1070
  div(class = "chr-legend",
1071
+ div(class = "legend-item", div(class = "legend-dot", style = "background:#C0392B;"), "Significant QTL"),
1072
+ div(class = "legend-item", div(class = "legend-dot", style = "background:#2166AC;"), "Flanking marker"),
1073
+ div(class = "legend-item", div(class = "legend-dot", style = "background:rgba(192,57,43,0.18);border:1px solid rgba(192,57,43,0.4);"), "LOD-1.5 interval"),
1074
+ div(class = "legend-item", div(class = "legend-dot", style = "background:#6B7280;"), "All markers")
1075
  ),
1076
  uiOutput("chromosome_viz"),
1077
  div(style = "margin:12px 0;display:flex;gap:8px;",
 
1286
  pop_data = NULL,
1287
  selection_metrics = NULL,
1288
  model_fit = NULL,
1289
+ model_train_cols = NULL, # exact columns used to train RF (after NZV removal)
1290
  chat_messages = list(),
1291
  is_typing = FALSE,
1292
  lod_threshold = 2,
 
1506
  train(x = X_tr_rf, y = y_train, method = "lm",
1507
  trControl = trainControl(method = "cv", number = 5))
1508
  })
1509
+ values$model_fit <- model
1510
+ values$model_train_cols <- colnames(X_tr_rf) # store exact training columns for test prediction
1511
 
1512
  y_train_pred <- predict(model, X_tr_rf)
1513
  y_val_pred <- predict(model, X_v_rf)
 
1586
  tryCatch({
1587
  withProgress(message = "Predicting test phenotypes...", value = 0, {
1588
 
1589
+ incProgress(0.10, detail = "Checking test genotype data...")
1590
+ Sys.sleep(0.1)
1591
+
1592
+ # ── Use the exact columns the RF model was trained on (after NZV removal) ──
1593
+ # Falling back to full genotype cols if model_train_cols wasn't saved (older session)
1594
+ train_cols <- if (!is.null(values$model_train_cols)) {
1595
+ values$model_train_cols
1596
+ } else {
1597
+ colnames(values$genotype_data)
1598
+ }
1599
+
1600
+ test_cols <- colnames(values$test_genotype_data)
1601
+ common_m <- intersect(train_cols, test_cols)
1602
+ missing_m <- setdiff(train_cols, test_cols)
1603
+
1604
+ incProgress(0.15, detail = paste0("Matched ", length(common_m), " / ",
1605
+ length(train_cols), " training markers..."))
1606
  Sys.sleep(0.1)
1607
 
 
1608
  if (length(common_m) == 0) {
1609
+ showNotification(
1610
+ paste0("No markers in common between test genotype and training model. ",
1611
+ "Ensure test CSV has the same marker column names as training CSV."),
1612
+ type = "error", duration = 10)
1613
  return()
1614
  }
1615
 
1616
+ if (length(missing_m) > 0) {
1617
+ showNotification(
1618
+ paste0(length(missing_m), " training markers missing from test data β€” ",
1619
+ "filling with column mean (0 = major homozygote). Predictions may be less accurate."),
1620
+ type = "warning", duration = 8)
1621
+ }
1622
+
1623
+ incProgress(0.20, detail = paste0("Building aligned test matrix (", nrow(values$test_genotype_data), " samples)..."))
1624
  Sys.sleep(0.1)
1625
 
1626
+ # Build test matrix aligned to ALL training columns in the correct order
1627
+ # Missing columns get filled with 0 (safe default = major homozygote)
1628
  X_test <- values$test_genotype_data[, common_m, drop = FALSE]
 
1629
 
1630
+ if (length(missing_m) > 0) {
1631
+ fill_mat <- matrix(0, nrow = nrow(X_test), ncol = length(missing_m),
1632
+ dimnames = list(rownames(X_test), missing_m))
1633
+ X_test <- cbind(X_test, fill_mat)
1634
+ }
1635
+
1636
+ # Reorder to exactly match training column order
1637
+ X_test <- X_test[, train_cols, drop = FALSE]
1638
+
1639
+ # Replace any NAs in test data with 0
1640
+ X_test[is.na(X_test)] <- 0
1641
+
1642
+ incProgress(0.30, detail = paste0("Running prediction model on ",
1643
+ nrow(X_test), " samples..."))
1644
 
 
1645
  preds <- predict(values$model_fit, newdata = X_test)
1646
 
1647
+ incProgress(0.20, detail = "Assembling results table...")
1648
+
1649
  values$predicted_test_phenotype_data <- data.frame(
1650
  id = rownames(X_test),
1651
+ Predicted_Phenotype = round(as.numeric(preds), 4),
1652
  stringsAsFactors = FALSE
1653
  )
1654
 
 
1656
  Sys.sleep(0.15)
1657
  })
1658
 
1659
+ n_pred <- nrow(values$predicted_test_phenotype_data)
1660
  showNotification(
1661
+ paste0("βœ… Predicted ", n_pred, " test samples. Use Download button to save."),
 
1662
  type = "message", duration = 5
1663
  )
1664
  add_message("assistant", paste0(
1665
  "βœ… **Test phenotypes predicted!**\n\n",
1666
+ "β€’ **", n_pred, "** samples predicted\n",
1667
+ "β€’ Training markers used: **", length(train_cols), "**\n",
1668
+ "β€’ Matched from test data: **", length(common_m), "**",
1669
+ if (length(missing_m) > 0) paste0(" (", length(missing_m), " missing β†’ filled with 0)") else " βœ“",
1670
+ "\nβ€’ Preview in Data Upload β†’ 'Predicted Test Phenotype' tab\n",
1671
  "β€’ Click **Download Predicted Phenotypes (.xlsx)** to save"
1672
  ))
1673
+ }, error = function(e) {
1674
+ showNotification(paste("Prediction error:", e$message), type = "error", duration = 10)
1675
+ cat("PREDICT ERROR:", e$message, "\n")
1676
+ add_message("assistant", paste0(
1677
+ "❌ **Prediction failed**\n\n",
1678
+ "Error: ", e$message, "\n\n",
1679
+ "Common causes:\n",
1680
+ "β€’ Test genotype has different marker names than training\n",
1681
+ "β€’ Model not trained yet (run CIM Analysis first)\n",
1682
+ "β€’ Test CSV format issue (needs same 3-row header as training)"
1683
+ ))
1684
+ })
1685
  })
1686
 
1687
  # ============================================================
 
1905
  paste("Chromosome", chr, "β€”", nrow(chr_markers), "markers,", nrow(chr_qtls), "QTLs"),
1906
  if (nrow(chr_qtls) > 0 && "Interval_Size_Mb" %in% colnames(chr_qtls)) {
1907
  sizes <- chr_qtls$Interval_Size_Mb[!is.na(chr_qtls$Interval_Size_Mb)]
1908
+ if (length(sizes) > 0) tags$span(style = "color:#C0392B;margin-left:8px;font-weight:normal;",
1909
+ paste0("(LOD-1.5: ", paste(round(sizes, 2), collapse=", "), " cM)"))
1910
  }
1911
  ),
1912
  div(class = "chromosome", style = "position:relative;",
 
1930
  mclass <- paste(mclass, "flanking")
1931
  }
1932
  div(class = mclass, style = paste0("left:", round(left, 2), "%;"),
1933
+ title = paste0(marker$Marker, " pos:", round(marker$Position, 1), " cM"))
1934
  })
1935
  ),
1936
  div(class = "chromosome-legend",
1937
+ span(paste(round(min_pos, 1), "cM")),
1938
+ span(paste(round(max_pos, 1), "cM"))
1939
  )
1940
  )
1941
  }))