softwareDevelopment commited on
Commit
e0172b7
Β·
verified Β·
1 Parent(s): 7f2b863

Update app.R

Browse files
Files changed (1) hide show
  1. app.R +290 -230
app.R CHANGED
@@ -16,15 +16,18 @@
16
  #
17
  # 3. QTL SUPPORT INTERVAL: LOD-1.5 drop (kept from v4)
18
  #
19
- # 4. SIMULATED CHROMOSOME VIZ DOWNLOAD: The interactive chromosome
20
- # visualization is now rendered via ggplot2 and downloadable as PNG,
21
- # matching the on-screen display.
22
  #
23
  # 5. COFACTOR VARIANCE INFLATION FIX:
24
  # When n_cofactors is large, cofactors pre-absorb marker signal.
25
  # v5 uses adaptive cofactor count = min(K, sqrt(n_samples)) and
26
  # ensures the focal marker is never a cofactor for itself.
27
  #
 
 
 
28
  # PVE FORMULAS (v5 β€” corrected):
29
  # a_code = genotype - 1 (-1, 0, +1 for AA, Aa, aa)
30
  # d_code = 1 if het, else 0
@@ -205,8 +208,7 @@ run_cim <- function(genotype_matrix, phenotype_vector, marker_info,
205
  SS_marker_given_cofactors <- RSS_reduced - RSS_full
206
 
207
  # v5 KEY FIX: denominator = SS of cofactor residuals (not raw SS_total)
208
- # This prevents near-zero PVE_CIM when cofactors dominate
209
- SS_denom_cim <- RSS_reduced # variance remaining AFTER cofactors
210
  pve_cim <- if (SS_denom_cim > 0)
211
  (SS_marker_given_cofactors / SS_denom_cim) * 100
212
  else NA
@@ -223,7 +225,7 @@ run_cim <- function(genotype_matrix, phenotype_vector, marker_info,
223
  lm_eff <- lm(df_model$y ~ a_code)
224
  }
225
 
226
- # PVE_marker: unconditional RΒ² (marker alone vs null)
227
  pve_marker <- summary(lm_eff)$r.squared * 100
228
  pve_marker <- max(0, pve_marker, na.rm = TRUE)
229
 
@@ -330,8 +332,8 @@ add_lod_support_interval <- function(sig_df, cim_all_df, lod_drop = 1.5) {
330
  } else {
331
  idx <- which(chr_data$Marker == focal_marker)
332
  if (length(idx) > 0) {
333
- sig_df$Low_Flank[i] <- if (idx > 1) chr_data$Marker[idx - 1] else focal_marker
334
- sig_df$High_Flank[i] <- if (idx < nrow(chr_data)) chr_data$Marker[idx + 1] else focal_marker
335
  sig_df$Interval_Start[i] <- sig_df$Position[i]
336
  sig_df$Interval_End[i] <- sig_df$Position[i]
337
  sig_df$Interval_Size_Mb[i] <- 0
@@ -392,25 +394,17 @@ make_ggplot_manhattan <- function(cim_all, lod_threshold = 2.0, title = "CIM Man
392
  }
393
 
394
  # ============================================================
395
- # GGPLOT2 CHROMOSOME VISUALIZATION β€” EXACT pixel match of on-screen HTML viz
396
- #
397
- # Replicates the HTML/CSS display faithfully:
398
- # - Grey rounded chromosome bar (y = 0.35 to 0.65, same as CSS height 24px)
399
- # - Red interval-band shading (rgba(220,38,38,0.12) = #FEE2E2 alpha)
400
- # - Grey background marker ticks (color:#94A3B8, thin, short = CSS default)
401
- # - Blue flanking marker ticks (color:#1D4ED8, taller)
402
- # - Red significant QTL ticks (color:#DC2626, tallest, widest)
403
- # - bp labels at left and right ends exactly like chromosome-legend div
404
- # - Title: "Chromosome X β€” N markers, N QTLs (LOD-1.5: X Mb)"
405
- # - Legend row: Redβ–  Significant QTL Blueβ–  Flanking marker Pinkβ–  LOD-1.5 interval Greyβ–  All markers
406
  # ============================================================
407
- make_ggplot_chromosome_viz <- function(qtl_effects, all_markers_df, cim_all = NULL,
408
- lod_threshold = 2.0) {
409
  if (is.null(qtl_effects) || "Message" %in% colnames(qtl_effects)) return(NULL)
410
  if (is.null(all_markers_df) || nrow(all_markers_df) == 0) return(NULL)
411
 
412
  chromosomes <- unique(qtl_effects$Chromosome)
413
- plot_list <- list()
414
 
415
  for (chr in chromosomes) {
416
  chr_markers <- all_markers_df[all_markers_df$Chromosome == chr, ]
@@ -422,176 +416,212 @@ make_ggplot_chromosome_viz <- function(qtl_effects, all_markers_df, cim_all = NU
422
  max_pos <- max(chr_markers$Position, na.rm = TRUE)
423
  range_pos <- max_pos - min_pos
424
 
425
- # Classify markers exactly as the HTML renderUI does
426
- flank_mks <- c(chr_qtls$Low_Flank, chr_qtls$High_Flank)
427
- flank_mks <- flank_mks[!is.na(flank_mks) & flank_mks != ""]
428
-
429
- chr_markers$mtype <- "background"
430
- chr_markers$mtype[chr_markers$Marker %in% flank_mks] <- "flanking"
431
- chr_markers$mtype[chr_markers$Marker %in% chr_qtls$Marker] <- "significant" # significant wins
432
-
433
- # y-ranges matching CSS pixel heights (normalised to 0-1 chromosome bar space):
434
- # chromosome bar: y 0.30 – 0.70 (matches CSS height:24px within 34px total marker space)
435
- # background tick: y 0.25 – 0.75 (CSS: height:34px, top:-5px β†’ covers bar Β± small extension)
436
- # flanking tick: y 0.10 – 0.90 (CSS: height:30px, top:-3px β†’ taller)
437
- # significant tick: y 0.00 – 1.00 (CSS: height:42px, top:-9px β†’ full height)
438
-
439
- bg_mk <- chr_markers[chr_markers$mtype == "background", ]
440
- fl_mk <- chr_markers[chr_markers$mtype == "flanking", ]
441
- sig_mk <- chr_markers[chr_markers$mtype == "significant", ]
442
-
443
- # Build interval rectangles from the HTML logic:
444
- # left% = (Interval_Start - min_pos) / range_pos * 100
445
- # width% = (Interval_End - Interval_Start) / range_pos * 100
446
- has_intervals <- nrow(chr_qtls) > 0 &&
447
- "Interval_Start" %in% colnames(chr_qtls) &&
448
- any(!is.na(chr_qtls$Interval_Start))
449
-
450
- # Title string identical to HTML chromosome-title div
451
- int_sizes <- if ("Interval_Size_Mb" %in% colnames(chr_qtls)) {
452
- sz <- chr_qtls$Interval_Size_Mb[!is.na(chr_qtls$Interval_Size_Mb)]
453
- if (length(sz) > 0) paste0(" (LOD-1.5: ", paste(round(sz, 2), collapse = ", "), " Mb)") else ""
454
- } else ""
455
- title_str <- paste0("Chromosome ", chr, " β€” ", nrow(chr_markers),
456
- " markers, ", nrow(chr_qtls), " QTLs", int_sizes)
457
-
458
- # x-axis bp labels identical to chromosome-legend (format with commas, "bp" suffix)
459
- left_label <- paste0(format(min_pos, big.mark = ","), " bp")
460
- right_label <- paste0(format(max_pos, big.mark = ","), " bp")
461
-
462
- p <- ggplot() +
463
-
464
- # ── Chromosome body (rounded rect, CSS: background:#E2E8F0, border:#CBD5E1) ──
465
- annotate("rect",
466
- xmin = min_pos, xmax = max_pos, ymin = 0.30, ymax = 0.70,
467
- fill = "#E2E8F0", color = "#CBD5E1", linewidth = 0.6) +
468
-
469
- # ── LOD-1.5 interval shading (CSS: interval-band rgba(220,38,38,0.12)) ──
470
- {
471
- if (has_intervals) {
472
- qtl_int <- chr_qtls[!is.na(chr_qtls$Interval_Start) & !is.na(chr_qtls$Interval_End), ]
473
- if (nrow(qtl_int) > 0) {
474
- # clamp interval to chromosome bounds
475
- qtl_int$xs <- pmax(qtl_int$Interval_Start, min_pos)
476
- qtl_int$xe <- pmin(qtl_int$Interval_End, max_pos)
477
- annotate("rect",
478
- xmin = qtl_int$xs, xmax = qtl_int$xe,
479
- ymin = 0.00, ymax = 1.00,
480
- fill = "#FEE2E2", alpha = 0.7,
481
- color = "#FCA5A5", linewidth = 0.35)
482
- } else list()
483
- } else list()
484
- } +
485
-
486
- # ── Background markers (CSS: color:#94A3B8, thin grey tick) ──
487
- {
488
- if (nrow(bg_mk) > 0)
489
- geom_segment(data = bg_mk,
490
- aes(x = Position, xend = Position, y = 0.25, yend = 0.75),
491
- color = "#94A3B8", linewidth = 0.35, alpha = 0.6)
492
- else list()
493
- } +
494
-
495
- # ── Flanking markers (CSS: color:#1D4ED8, taller blue tick) ──
496
- {
497
- if (nrow(fl_mk) > 0)
498
- geom_segment(data = fl_mk,
499
- aes(x = Position, xend = Position, y = 0.10, yend = 0.90),
500
- color = "#1D4ED8", linewidth = 0.9)
501
- else list()
502
- } +
503
-
504
- # ── Significant QTL markers (CSS: color:#DC2626, full-height red tick) ──
505
- {
506
- if (nrow(sig_mk) > 0)
507
- geom_segment(data = sig_mk,
508
- aes(x = Position, xend = Position, y = 0.00, yend = 1.00),
509
- color = "#DC2626", linewidth = 2.0)
510
- else list()
511
- } +
512
-
513
- # ── bp labels at ends β€” replicate chromosome-legend div ──
514
- annotate("text", x = min_pos, y = -0.08,
515
- label = left_label, hjust = 0, size = 3.0,
516
- color = "#94A3B8", family = "mono") +
517
- annotate("text", x = max_pos, y = -0.08,
518
- label = right_label, hjust = 1.0, size = 3.0,
519
- color = "#94A3B8", family = "mono") +
520
-
521
- # ── Axis: show actual bp positions (not scaled), x-axis removed (legend handles it) ──
522
- scale_x_continuous(expand = expansion(mult = 0.02)) +
523
- coord_cartesian(ylim = c(-0.22, 1.22), xlim = c(min_pos, max_pos)) +
524
-
525
- labs(title = title_str, x = NULL, y = NULL) +
526
-
527
- theme_void(base_size = 11) +
528
- theme(
529
- plot.background = element_rect(fill = "white", color = "#E2E8F0", linewidth = 0.5),
530
- panel.background = element_rect(fill = "white"),
531
- plot.title = element_text(face = "bold", size = 10.5, color = "#1D4ED8",
532
- family = "mono", margin = margin(b = 4)),
533
- plot.margin = margin(t = 8, r = 12, b = 8, l = 12)
534
- )
535
 
536
- plot_list[[as.character(chr)]] <- p
537
- }
 
 
 
 
 
 
 
538
 
539
- if (length(plot_list) == 0) return(NULL)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
540
 
541
- # ── Legend row β€” matches chr-legend div ──
542
- legend_grob <- grid::textGrob(
543
- paste0(
544
- "\u25A0 Significant QTL ",
545
- "\u25A0 Flanking marker ",
546
- "\u25A0 LOD-1.5 interval ",
547
- "\u25A0 All markers"
548
- ),
549
- gp = grid::gpar(
550
- fontsize = 9,
551
- col = c("#DC2626","#1D4ED8","#FCA5A5","#94A3B8")[1], # textGrob is monochrome; use subtitle instead
552
- col = "#475569"
553
- )
554
- )
555
 
556
- # Build coloured legend via a tiny ggplot
557
- legend_df <- data.frame(
558
- label = c("Significant QTL", "Flanking marker", "LOD-1.5 interval", "All markers"),
559
- col = c("#DC2626", "#1D4ED8", "#FCA5A5", "#94A3B8"),
560
- x = c(1, 2, 3, 4),
561
- stringsAsFactors = FALSE
562
- )
563
- leg_plot <- ggplot(legend_df) +
564
- geom_point(aes(x = x, y = 1, color = label), shape = 15, size = 5, show.legend = FALSE) +
565
- geom_text(aes(x = x + 0.15, y = 1, label = label, color = label),
566
- hjust = 0, size = 3.2, show.legend = FALSE) +
567
- scale_color_manual(values = setNames(legend_df$col, legend_df$label)) +
568
- scale_x_continuous(limits = c(0.8, 5.5)) +
569
- theme_void() +
570
- theme(plot.background = element_rect(fill = "white", color = NA),
571
- plot.margin = margin(4, 4, 4, 4))
572
-
573
- n_cols <- min(2, length(plot_list))
574
-
575
- gridExtra::arrangeGrob(
576
- grobs = c(plot_list, list(leg_plot)),
577
- layout_matrix = {
578
- n <- length(plot_list)
579
- nc <- n_cols
580
- nr <- ceiling(n / nc)
581
- # chromosome plots fill the grid; legend spans full bottom row
582
- mat <- matrix(seq_len(n), nrow = nr, ncol = nc, byrow = TRUE)
583
- mat[mat > n] <- NA
584
- rbind(mat, rep(n + 1L, nc)) # legend row at bottom
585
- },
586
- heights = c(rep(1, ceiling(length(plot_list) / n_cols)), 0.18),
587
- top = grid::textGrob(
588
- "QTL Chromosome Map β€” CIM v5",
589
- gp = grid::gpar(fontsize = 13, fontface = "bold", col = "#1E3A5F")),
590
- bottom = grid::textGrob(
591
- paste0("Generated: ", format(Sys.time(), "%Y-%m-%d %H:%M"),
592
- " | LOD-1.5 support intervals | -1/0/+1 additive coding"),
593
- gp = grid::gpar(fontsize = 7.5, col = "#94A3B8"))
594
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
595
  }
596
 
597
  # ============================================================
@@ -736,11 +766,12 @@ enhanced_rule_response <- function(user_message, rv) {
736
  }
737
 
738
  paste0("πŸ‘‹ Vanakam! TerraByte-AI (CIM v5 β€” PVE fixed)\n\n",
739
- "Key fix in v5:\n",
740
  "β€’ PVE_CIM now uses semi-partial RΒ² (denominator = residual SS after cofactors)\n",
741
  "β€’ PVE_marker = unconditional RΒ² of marker-only model\n",
742
  "β€’ Adaptive cofactor count = min(K, √n) to prevent over-absorption\n",
743
- "β€’ Chromosome viz is now downloadable as PNG (same as on-screen)\n\n",
 
744
  "Ask about: **PVE / low PVE** | **Intervals** | **Top QTLs** | **Performance**\n\n",
745
  "Contact: ashmithamganesan@gmail.com, P.sinha@cgiar.org")
746
  }
@@ -920,11 +951,11 @@ ui <- fluidPage(
920
  tabPanel("Data Upload", icon = icon("upload"),
921
  div(class = "main-header",
922
  h2(tags$i(class = "fas fa-upload", style = "margin-right:8px;"), "Data Upload β€” CIM v5"),
923
- p("Semi-partial RΒ² PVE | -1/0/+1 coding | LOD-1.5 intervals | downloadable chromosome viz")
924
  ),
925
  fluidRow(column(12,
926
  div(class = "cim-box",
927
- div(class = "box-title", tags$i(class = "fas fa-check-circle", style = "margin-right:6px;"), "CIM v5 β€” PVE Formula Fix"),
928
  tags$pre(style = "background:transparent;border:none;margin:0;color:#166534;font-size:11px;",
929
  "WHY PVE WAS LOW IN v4:\n",
930
  " Partial RΒ² = (RSS_reduced - RSS_full) / SS_total_raw\n",
@@ -934,11 +965,9 @@ ui <- fluidPage(
934
  " SS_denom = RSS_reduced = residual SS after cofactors alone\n",
935
  " PVE_CIM = (RSS_reduced - RSS_full) / RSS_reduced Γ— 100\n",
936
  " Same example: 20/100 = 20% ← fraction of REMAINING variance explained\n\n",
937
- "ADDITIONAL v5 FIX β€” Adaptive cofactor count:\n",
938
- " Max cofactors = min(K_user, sqrt(n_samples)) ← prevents over-absorption\n",
939
- " With n=100 samples: max cofactors = 10 regardless of user setting\n\n",
940
- "PVE_marker = unconditional RΒ² of lm(Y ~ a_code + d_code) Γ— 100 [no cofactors]\n",
941
- " This is always >= PVE_CIM and shows total marker association strength")
942
  )
943
  )),
944
  fluidRow(
@@ -978,7 +1007,12 @@ ui <- fluidPage(
978
  tags$br(),
979
  fileInput("pop_file", "Population Metadata CSV", accept = ".csv", buttonLabel = "Browse"),
980
  helpText("Columns: id, population (e.g. Domesticated/Wild)."),
981
- actionButton("predict_test_phenotype", "Predict Test Phenotypes", class = "btn-info btn-block", icon = icon("magic"))
 
 
 
 
 
982
  )
983
  )
984
  )
@@ -1008,14 +1042,15 @@ ui <- fluidPage(
1008
  div(class = "download-bar",
1009
  tags$span(tags$i(class = "fas fa-download"), " Download:"),
1010
  downloadButton("download_manhattan_plot", "Manhattan Plot (.png)", class = "btn btn-primary"),
1011
- downloadButton("download_chromosome_plot", "Chromosome Map (.png)", class = "btn btn-info"),
 
1012
  downloadButton("download_train_results", "CIM Results (.xlsx)", class = "btn btn-success")
1013
  )
1014
  )),
1015
  fluidRow(
1016
  column(6, div(class = "card", div(class = "card-header", "CIM Manhattan Plot (LOD Scores)"), div(class = "card-body", plotlyOutput("lod_plot_2d", height = "500px")))),
1017
  column(6, div(class = "card",
1018
- div(class = "card-header", "Chromosome Visualization β€” LOD-1.5 Intervals (matches download PNG)"),
1019
  div(class = "card-body",
1020
  div(class = "chr-legend",
1021
  div(class = "legend-item", div(class = "legend-dot", style = "background:#DC2626;"), "Significant QTL"),
@@ -1122,7 +1157,7 @@ ui <- fluidPage(
1122
  fluidRow(column(8, offset = 2,
1123
  div(class = "card",
1124
  div(class = "card-body",
1125
- h4(style = "color:#1D4ED8;font-family:'IBM Plex Mono';margin-bottom:12px;", "Changes in v5 (PVE Fix)"),
1126
  div(class = "fix-box",
1127
  tags$pre(style = "background:transparent;border:none;margin:0;color:#92400E;font-size:11px;",
1128
  "v4 BUG: PVE very low / near-zero\n\n",
@@ -1138,9 +1173,13 @@ ui <- fluidPage(
1138
  "v5 FIX 2 β€” Adaptive cofactor cap:\n",
1139
  " n_cofactors_used = min(n_cofactors_user, floor(sqrt(n_samples)))\n",
1140
  " Prevents too many cofactors absorbing all marker signal\n\n",
1141
- "v5 FIX 3 β€” Chromosome viz download:\n",
1142
- " ggplot2 PNG export now shows SAME layout as on-screen display\n",
1143
- " Includes LOD-1.5 intervals, QTL labels with LOD + PVE, flanking markers\n\n",
 
 
 
 
1144
  "KEPT FROM v4:\n",
1145
  " Additive coding: -1/0/+1 | LOD-1.5 support intervals\n",
1146
  " PVE_marker = unconditional RΒ² (marker alone vs null)")
@@ -1283,11 +1322,11 @@ server <- function(input, output, session) {
1283
  if (length(values$chat_messages) == 0) {
1284
  add_message("assistant", paste0(
1285
  "πŸ‘‹ Vanakam! TerraByte-AI (CIM v5 β€” PVE fixed)\n\n",
1286
- "**v5 Key Fix β€” Semi-Partial RΒ²:**\n",
1287
- "β€’ PVE_CIM now uses RSS_cofactors as denominator (not SS_total_raw)\n",
1288
- "β€’ This prevents near-zero PVE when cofactors dominate\n",
1289
  "β€’ Adaptive cofactor cap = min(K, √n_samples)\n",
1290
- "β€’ Chromosome viz is downloadable as PNG (same as on-screen)\n\n",
 
1291
  "Click 'Low PVE fix' above for a detailed explanation.\n",
1292
  "Contact: ashmithamganesan@gmail.com, P.sinha@cgiar.org"
1293
  ))
@@ -1386,7 +1425,10 @@ server <- function(input, output, session) {
1386
  output$pheno_preview <- renderDT({ req(input$phenotype_file); datatable(head(read.csv(input$phenotype_file$datapath), 10), options = list(scrollX = TRUE, pageLength = 5)) })
1387
  output$test_geno_preview <- renderDT({ req(input$test_genotype_file); datatable(head(read.csv(input$test_genotype_file$datapath), 10), options = list(scrollX = TRUE, pageLength = 5)) })
1388
  output$pop_preview <- renderDT({ req(input$pop_file); datatable(head(read.csv(input$pop_file$datapath), 10), options = list(scrollX = TRUE, pageLength = 5)) })
1389
- output$predicted_test_pheno_preview <- renderDT({ req(values$predicted_test_phenotype_data); datatable(values$predicted_test_phenotype_data, options = list(scrollX = TRUE, pageLength = 5)) })
 
 
 
1390
 
1391
  # ============================================================
1392
  # MAIN CIM ANALYSIS
@@ -1509,7 +1551,7 @@ server <- function(input, output, session) {
1509
  "β€’ Validation RΒ²: **", round(val_r2, 3), "**\n",
1510
  "β€’ PVE formula: semi-partial RΒ² βœ…\n",
1511
  "β€’ Cofactor cap: min(", input$n_cofactors, ", √", length(y_train), ") = ", min(input$n_cofactors, floor(sqrt(length(y_train)))), " βœ…\n\n",
1512
- "Click 'Low PVE fix' in chat or check the Results tab!"
1513
  ))
1514
  updateTabsetPanel(session, "nav", selected = "Results")
1515
 
@@ -1531,7 +1573,12 @@ server <- function(input, output, session) {
1531
  preds <- predict(values$model_fit, newdata = X_test)
1532
  values$predicted_test_phenotype_data <- data.frame(
1533
  id = rownames(X_test), Predicted_Phenotype = as.numeric(preds), stringsAsFactors = FALSE)
1534
- showNotification("Predictions done!", type = "message")
 
 
 
 
 
1535
  }, error = function(e) showNotification(paste("Predict error:", e$message), type = "error"))
1536
  })
1537
 
@@ -1798,6 +1845,8 @@ server <- function(input, output, session) {
1798
  # ============================================================
1799
  # DOWNLOADS
1800
  # ============================================================
 
 
1801
  output$download_manhattan_plot <- downloadHandler(
1802
  filename = function() paste0("manhattan_cim_v5_", Sys.Date(), ".png"),
1803
  content = function(file) {
@@ -1808,35 +1857,32 @@ server <- function(input, output, session) {
1808
  }
1809
  )
1810
 
 
1811
  output$download_chromosome_plot <- downloadHandler(
1812
- filename = function() paste0("chromosome_map_v5_", Sys.Date(), ".png"),
1813
  content = function(file) {
1814
  req(values$qtl_effects_train, values$all_markers)
1815
- grob <- make_ggplot_chromosome_viz(
 
 
 
 
 
 
 
1816
  qtl_effects = values$qtl_effects_train,
1817
  all_markers_df = values$all_markers,
1818
- cim_all = values$cim_all,
1819
  lod_threshold = values$lod_threshold
1820
  )
1821
- if (is.null(grob)) {
1822
- p <- ggplot() + labs(title = "No QTL data") + theme_bw() +
1823
- theme(plot.background = element_rect(fill = "white"),
1824
- panel.background = element_rect(fill = "white"))
1825
- ggsave(file, plot = p, width = 10, height = 4, dpi = 200, bg = "white")
1826
  } else {
1827
- # Each chromosome row ~1.1 inches at 200 dpi; header+legend+padding ~1.2 in
1828
- n_chrs <- length(unique(values$qtl_effects_train$Chromosome))
1829
- n_rows <- ceiling(n_chrs / 2)
1830
- img_h_in <- 1.2 + n_rows * 1.1
1831
- img_w_in <- 16
1832
- png(file, width = round(img_w_in * 200), height = round(img_h_in * 200),
1833
- res = 200, bg = "white")
1834
- grid::grid.draw(grob)
1835
- dev.off()
1836
  }
1837
  }
1838
  )
1839
 
 
1840
  output$download_train_results <- downloadHandler(
1841
  filename = function() paste0("cim_results_v5_", Sys.Date(), ".xlsx"),
1842
  content = function(file) {
@@ -1865,6 +1911,19 @@ server <- function(input, output, session) {
1865
  }
1866
  )
1867
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1868
  output$download_selection <- downloadHandler(
1869
  filename = function() paste0("selection_", Sys.Date(), ".xlsx"),
1870
  content = function(file) {
@@ -1895,7 +1954,7 @@ server <- function(input, output, session) {
1895
  if (!is.na(avg_int)) tags$p(paste("Mean LOD-1.5 interval:", avg_int, "Mb")),
1896
  tags$p(style = "color:#15803D;font-size:12px;",
1897
  tags$i(class = "fas fa-check-circle"),
1898
- " v5: semi-partial RΒ² βœ“ | -1/0/+1 coding βœ“ | LOD-1.5 intervals βœ“ | adaptive cofactors βœ“")
1899
  )
1900
  })
1901
 
@@ -1949,7 +2008,8 @@ server <- function(input, output, session) {
1949
  "Use Interval_Start / Interval_End (LOD-1.5) for fine-mapping candidate gene annotation",
1950
  "PVE_CIM = semi-partial RΒ² (% of residual variance after cofactors) β€” compare markers on same scale",
1951
  "PVE_marker = unconditional RΒ² β€” use this to compare QTL sizes across studies",
1952
- "Sum of PVE_marker across QTLs approximates total marker-explained variance"
 
1953
  )
1954
  if (n_ovdom > 0) r <- c(r, paste(n_ovdom, "overdominant QTL(s) β€” consider heterosis breeding"))
1955
  if (large_int > 0) r <- c(r, paste(large_int, "QTL(s) with LOD-1.5 interval >10 Mb β€” increase marker density for fine-mapping"))
 
16
  #
17
  # 3. QTL SUPPORT INTERVAL: LOD-1.5 drop (kept from v4)
18
  #
19
+ # 4. CHROMOSOME VIZ DOWNLOAD: Now exports as HTML matching the on-screen
20
+ # interactive display exactly (same CSS markers, interval bands, colors).
21
+ # FIX: Previously used ggplot2 PNG which looked different from on-screen.
22
  #
23
  # 5. COFACTOR VARIANCE INFLATION FIX:
24
  # When n_cofactors is large, cofactors pre-absorb marker signal.
25
  # v5 uses adaptive cofactor count = min(K, sqrt(n_samples)) and
26
  # ensures the focal marker is never a cofactor for itself.
27
  #
28
+ # 6. PREDICTED TEST PHENOTYPE DOWNLOAD: Added missing downloadHandler
29
+ # for predicted test phenotype data (was missing in previous versions).
30
+ #
31
  # PVE FORMULAS (v5 β€” corrected):
32
  # a_code = genotype - 1 (-1, 0, +1 for AA, Aa, aa)
33
  # d_code = 1 if het, else 0
 
208
  SS_marker_given_cofactors <- RSS_reduced - RSS_full
209
 
210
  # v5 KEY FIX: denominator = SS of cofactor residuals (not raw SS_total)
211
+ SS_denom_cim <- RSS_reduced
 
212
  pve_cim <- if (SS_denom_cim > 0)
213
  (SS_marker_given_cofactors / SS_denom_cim) * 100
214
  else NA
 
225
  lm_eff <- lm(df_model$y ~ a_code)
226
  }
227
 
228
+ # PVE_marker: unconditional RΒ²
229
  pve_marker <- summary(lm_eff)$r.squared * 100
230
  pve_marker <- max(0, pve_marker, na.rm = TRUE)
231
 
 
332
  } else {
333
  idx <- which(chr_data$Marker == focal_marker)
334
  if (length(idx) > 0) {
335
+ sig_df$Low_Flank[i] <- if (idx > 1) chr_data$Marker[idx - 1] else focal_marker
336
+ sig_df$High_Flank[i] <- if (idx < nrow(chr_data)) chr_data$Marker[idx + 1] else focal_marker
337
  sig_df$Interval_Start[i] <- sig_df$Position[i]
338
  sig_df$Interval_End[i] <- sig_df$Position[i]
339
  sig_df$Interval_Size_Mb[i] <- 0
 
394
  }
395
 
396
  # ============================================================
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
 
409
  for (chr in chromosomes) {
410
  chr_markers <- all_markers_df[all_markers_df$Chromosome == chr, ]
 
416
  max_pos <- max(chr_markers$Position, na.rm = TRUE)
417
  range_pos <- max_pos - min_pos
418
 
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)) {
426
+ qtl_row <- chr_qtls[j, ]
427
+ if (!is.na(qtl_row$Interval_Start) && !is.na(qtl_row$Interval_End) && range_pos > 0) {
428
+ left_pct <- ((qtl_row$Interval_Start - min_pos) / range_pos) * 100
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, ]
442
+ left <- if (range_pos > 0 && !is.na(range_pos)) {
443
+ ((marker$Position - min_pos) / range_pos) * 100
444
+ } else {
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>
508
+ <meta charset="UTF-8">
509
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
510
+ <title>QTL Chromosome Map β€” CIM v5</title>
511
+ <link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;600&family=IBM+Plex+Sans:wght@300;400;500;600&display=swap" rel="stylesheet">
512
+ <style>
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>
571
+ <body>
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;
579
+ Generated: %s
580
+ </p>
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>
618
+ </body>
619
+ </html>',
620
+ lod_threshold,
621
+ format(Sys.time(), "%Y-%m-%d %H:%M"),
622
+ chr_html)
623
+
624
+ return(html_content)
625
  }
626
 
627
  # ============================================================
 
766
  }
767
 
768
  paste0("πŸ‘‹ Vanakam! TerraByte-AI (CIM v5 β€” PVE fixed)\n\n",
769
+ "Key fixes in v5:\n",
770
  "β€’ PVE_CIM now uses semi-partial RΒ² (denominator = residual SS after cofactors)\n",
771
  "β€’ PVE_marker = unconditional RΒ² of marker-only model\n",
772
  "β€’ Adaptive cofactor count = min(K, √n) to prevent over-absorption\n",
773
+ "β€’ Chromosome viz is now downloadable as HTML (same as on-screen)\n",
774
+ "β€’ Predicted test phenotype download is now available\n\n",
775
  "Ask about: **PVE / low PVE** | **Intervals** | **Top QTLs** | **Performance**\n\n",
776
  "Contact: ashmithamganesan@gmail.com, P.sinha@cgiar.org")
777
  }
 
951
  tabPanel("Data Upload", icon = icon("upload"),
952
  div(class = "main-header",
953
  h2(tags$i(class = "fas fa-upload", style = "margin-right:8px;"), "Data Upload β€” CIM v5"),
954
+ p("Semi-partial RΒ² PVE | -1/0/+1 coding | LOD-1.5 intervals | downloadable chromosome viz (HTML) | predicted test phenotype download")
955
  ),
956
  fluidRow(column(12,
957
  div(class = "cim-box",
958
+ div(class = "box-title", tags$i(class = "fas fa-check-circle", style = "margin-right:6px;"), "CIM v5 β€” PVE Formula Fix + New Downloads"),
959
  tags$pre(style = "background:transparent;border:none;margin:0;color:#166534;font-size:11px;",
960
  "WHY PVE WAS LOW IN v4:\n",
961
  " Partial RΒ² = (RSS_reduced - RSS_full) / SS_total_raw\n",
 
965
  " SS_denom = RSS_reduced = residual SS after cofactors alone\n",
966
  " PVE_CIM = (RSS_reduced - RSS_full) / RSS_reduced Γ— 100\n",
967
  " Same example: 20/100 = 20% ← fraction of REMAINING variance explained\n\n",
968
+ "NEW IN THIS BUILD:\n",
969
+ " 1. Chromosome viz downloads as HTML β€” pixel-identical to on-screen display\n",
970
+ " 2. Predicted test phenotype download button added to Test Data card")
 
 
971
  )
972
  )),
973
  fluidRow(
 
1007
  tags$br(),
1008
  fileInput("pop_file", "Population Metadata CSV", accept = ".csv", buttonLabel = "Browse"),
1009
  helpText("Columns: id, population (e.g. Domesticated/Wild)."),
1010
+ actionButton("predict_test_phenotype", "Predict Test Phenotypes", class = "btn-info btn-block", icon = icon("magic")),
1011
+ tags$br(),
1012
+ # ── FIX: Added predicted test phenotype download button ──
1013
+ downloadButton("download_predicted_test", "Download Predicted Phenotypes (.xlsx)",
1014
+ class = "btn btn-success btn-block",
1015
+ style = "width:100%;margin-top:8px;")
1016
  )
1017
  )
1018
  )
 
1042
  div(class = "download-bar",
1043
  tags$span(tags$i(class = "fas fa-download"), " Download:"),
1044
  downloadButton("download_manhattan_plot", "Manhattan Plot (.png)", class = "btn btn-primary"),
1045
+ # ── FIX: Changed label from .png to .html β€” now exports HTML matching on-screen ──
1046
+ downloadButton("download_chromosome_plot", "Chromosome Map (.html)", class = "btn btn-info"),
1047
  downloadButton("download_train_results", "CIM Results (.xlsx)", class = "btn btn-success")
1048
  )
1049
  )),
1050
  fluidRow(
1051
  column(6, div(class = "card", div(class = "card-header", "CIM Manhattan Plot (LOD Scores)"), div(class = "card-body", plotlyOutput("lod_plot_2d", height = "500px")))),
1052
  column(6, div(class = "card",
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"),
 
1157
  fluidRow(column(8, offset = 2,
1158
  div(class = "card",
1159
  div(class = "card-body",
1160
+ h4(style = "color:#1D4ED8;font-family:'IBM Plex Mono';margin-bottom:12px;", "Changes in v5 (PVE Fix + New Downloads)"),
1161
  div(class = "fix-box",
1162
  tags$pre(style = "background:transparent;border:none;margin:0;color:#92400E;font-size:11px;",
1163
  "v4 BUG: PVE very low / near-zero\n\n",
 
1173
  "v5 FIX 2 β€” Adaptive cofactor cap:\n",
1174
  " n_cofactors_used = min(n_cofactors_user, floor(sqrt(n_samples)))\n",
1175
  " Prevents too many cofactors absorbing all marker signal\n\n",
1176
+ "v5 FIX 3 β€” Chromosome viz download (HTML, not PNG):\n",
1177
+ " Now exports the same HTML/CSS layout as the on-screen display\n",
1178
+ " Same red QTL ticks, blue flanking markers, pink LOD-1.5 interval bands\n",
1179
+ " Hover markers for LOD + PVE tooltip. Opens in any browser.\n\n",
1180
+ "v5 FIX 4 β€” Predicted test phenotype download:\n",
1181
+ " Download button added to Test Data card\n",
1182
+ " Exports id + Predicted_Phenotype to .xlsx\n\n",
1183
  "KEPT FROM v4:\n",
1184
  " Additive coding: -1/0/+1 | LOD-1.5 support intervals\n",
1185
  " PVE_marker = unconditional RΒ² (marker alone vs null)")
 
1322
  if (length(values$chat_messages) == 0) {
1323
  add_message("assistant", paste0(
1324
  "πŸ‘‹ Vanakam! TerraByte-AI (CIM v5 β€” PVE fixed)\n\n",
1325
+ "**v5 Key Fixes:**\n",
1326
+ "β€’ PVE_CIM now uses RSS_cofactors as denominator (semi-partial RΒ²)\n",
 
1327
  "β€’ Adaptive cofactor cap = min(K, √n_samples)\n",
1328
+ "β€’ Chromosome viz downloads as HTML β€” same as on-screen βœ…\n",
1329
+ "β€’ Predicted test phenotype download now available βœ…\n\n",
1330
  "Click 'Low PVE fix' above for a detailed explanation.\n",
1331
  "Contact: ashmithamganesan@gmail.com, P.sinha@cgiar.org"
1332
  ))
 
1425
  output$pheno_preview <- renderDT({ req(input$phenotype_file); datatable(head(read.csv(input$phenotype_file$datapath), 10), options = list(scrollX = TRUE, pageLength = 5)) })
1426
  output$test_geno_preview <- renderDT({ req(input$test_genotype_file); datatable(head(read.csv(input$test_genotype_file$datapath), 10), options = list(scrollX = TRUE, pageLength = 5)) })
1427
  output$pop_preview <- renderDT({ req(input$pop_file); datatable(head(read.csv(input$pop_file$datapath), 10), options = list(scrollX = TRUE, pageLength = 5)) })
1428
+ output$predicted_test_pheno_preview <- renderDT({
1429
+ req(values$predicted_test_phenotype_data)
1430
+ datatable(values$predicted_test_phenotype_data, options = list(scrollX = TRUE, pageLength = 5))
1431
+ })
1432
 
1433
  # ============================================================
1434
  # MAIN CIM ANALYSIS
 
1551
  "β€’ Validation RΒ²: **", round(val_r2, 3), "**\n",
1552
  "β€’ PVE formula: semi-partial RΒ² βœ…\n",
1553
  "β€’ Cofactor cap: min(", input$n_cofactors, ", √", length(y_train), ") = ", min(input$n_cofactors, floor(sqrt(length(y_train)))), " βœ…\n\n",
1554
+ "Download: Chromosome Map (.html) = same as on-screen view βœ…"
1555
  ))
1556
  updateTabsetPanel(session, "nav", selected = "Results")
1557
 
 
1573
  preds <- predict(values$model_fit, newdata = X_test)
1574
  values$predicted_test_phenotype_data <- data.frame(
1575
  id = rownames(X_test), Predicted_Phenotype = as.numeric(preds), stringsAsFactors = FALSE)
1576
+ showNotification("Predictions done! Use the Download button below to save.", type = "message")
1577
+ add_message("assistant", paste0(
1578
+ "βœ… **Test phenotypes predicted!**\n\n",
1579
+ "β€’ ", nrow(values$predicted_test_phenotype_data), " samples predicted\n",
1580
+ "β€’ Preview in Data Upload β†’ 'Predicted Test Phenotype' tab\n",
1581
+ "β€’ Click **Download Predicted Phenotypes (.xlsx)** to save"))
1582
  }, error = function(e) showNotification(paste("Predict error:", e$message), type = "error"))
1583
  })
1584
 
 
1845
  # ============================================================
1846
  # DOWNLOADS
1847
  # ============================================================
1848
+
1849
+ # Manhattan plot β€” ggplot2 PNG (unchanged)
1850
  output$download_manhattan_plot <- downloadHandler(
1851
  filename = function() paste0("manhattan_cim_v5_", Sys.Date(), ".png"),
1852
  content = function(file) {
 
1857
  }
1858
  )
1859
 
1860
+ # ── FIX: Chromosome map now downloads as HTML identical to on-screen display ──
1861
  output$download_chromosome_plot <- downloadHandler(
1862
+ filename = function() paste0("chromosome_map_v5_", Sys.Date(), ".html"),
1863
  content = function(file) {
1864
  req(values$qtl_effects_train, values$all_markers)
1865
+ if ("Message" %in% colnames(values$qtl_effects_train)) {
1866
+ writeLines(paste0(
1867
+ '<!DOCTYPE html><html><body style="font-family:sans-serif;padding:24px;">',
1868
+ '<p style="color:#DC2626;">No QTL data available. Run CIM analysis first.</p>',
1869
+ '</body></html>'), file)
1870
+ return()
1871
+ }
1872
+ html_content <- make_html_chromosome_viz(
1873
  qtl_effects = values$qtl_effects_train,
1874
  all_markers_df = values$all_markers,
 
1875
  lod_threshold = values$lod_threshold
1876
  )
1877
+ if (is.null(html_content)) {
1878
+ writeLines('<html><body><p>Error generating chromosome visualization.</p></body></html>', file)
 
 
 
1879
  } else {
1880
+ writeLines(html_content, file)
 
 
 
 
 
 
 
 
1881
  }
1882
  }
1883
  )
1884
 
1885
+ # CIM results XLSX (unchanged)
1886
  output$download_train_results <- downloadHandler(
1887
  filename = function() paste0("cim_results_v5_", Sys.Date(), ".xlsx"),
1888
  content = function(file) {
 
1911
  }
1912
  )
1913
 
1914
+ # ── FIX: Added predicted test phenotype download handler ──
1915
+ output$download_predicted_test <- downloadHandler(
1916
+ filename = function() paste0("predicted_test_phenotype_", Sys.Date(), ".xlsx"),
1917
+ content = function(file) {
1918
+ req(values$predicted_test_phenotype_data)
1919
+ write_xlsx(
1920
+ list(Predicted_Phenotypes = values$predicted_test_phenotype_data),
1921
+ file
1922
+ )
1923
+ }
1924
+ )
1925
+
1926
+ # Selection results XLSX (unchanged)
1927
  output$download_selection <- downloadHandler(
1928
  filename = function() paste0("selection_", Sys.Date(), ".xlsx"),
1929
  content = function(file) {
 
1954
  if (!is.na(avg_int)) tags$p(paste("Mean LOD-1.5 interval:", avg_int, "Mb")),
1955
  tags$p(style = "color:#15803D;font-size:12px;",
1956
  tags$i(class = "fas fa-check-circle"),
1957
+ " v5: semi-partial RΒ² βœ“ | -1/0/+1 coding βœ“ | LOD-1.5 intervals βœ“ | adaptive cofactors βœ“ | HTML chr download βœ“ | predicted phenotype download βœ“")
1958
  )
1959
  })
1960
 
 
2008
  "Use Interval_Start / Interval_End (LOD-1.5) for fine-mapping candidate gene annotation",
2009
  "PVE_CIM = semi-partial RΒ² (% of residual variance after cofactors) β€” compare markers on same scale",
2010
  "PVE_marker = unconditional RΒ² β€” use this to compare QTL sizes across studies",
2011
+ "Sum of PVE_marker across QTLs approximates total marker-explained variance",
2012
+ "Chromosome Map (.html) download = same view as on-screen; open in any browser for sharing"
2013
  )
2014
  if (n_ovdom > 0) r <- c(r, paste(n_ovdom, "overdominant QTL(s) β€” consider heterosis breeding"))
2015
  if (large_int > 0) r <- c(r, paste(large_int, "QTL(s) with LOD-1.5 interval >10 Mb β€” increase marker density for fine-mapping"))