softwareDevelopment commited on
Commit
4f3ffc2
ยท
verified ยท
1 Parent(s): bbef30f

Update app.R

Browse files
Files changed (1) hide show
  1. app.R +661 -316
app.R CHANGED
@@ -1,12 +1,13 @@
1
  # ============================================================
2
- # QTL-Mapper v6 โ€” Multi-Model QTL Mapping (Final)
3
  #
4
- # CHANGES vs fixed version:
5
- # - Ridge Regression removed from models
6
- # - Chat box removed entirely
7
- # - Common QTL tab added: markers significant across ALL
8
- # selected models, with overlap count, LOD summary, and
9
- # downloadable results
 
10
  # ============================================================
11
 
12
  options(repos = c(CRAN = "https://cloud.r-project.org"))
@@ -14,7 +15,8 @@ options(repos = c(CRAN = "https://cloud.r-project.org"))
14
  required_packages <- c(
15
  "shiny", "randomForest", "caret", "DT", "ggplot2", "plotly",
16
  "writexl", "viridis", "reshape2", "dplyr", "ggrepel", "glmnet",
17
- "shinyjs"
 
18
  )
19
 
20
  for (pkg in required_packages) {
@@ -25,13 +27,31 @@ for (pkg in required_packages) {
25
  }
26
 
27
  # ============================================================
28
- # MAPPING MODEL DEFINITIONS (Ridge removed)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  # ============================================================
30
  MAPPING_MODELS <- list(
31
- "SIM" = list(label = "Simple Interval Mapping (SIM)", desc = "Single-marker regression; LOD = -log10(p); no cofactors"),
32
- "CIM" = list(label = "Composite Interval Mapping (CIM)", desc = "CIM with RF-selected cofactors; semi-partial R2 PVE"),
33
- "MQM" = list(label = "Multiple QTL Model (MQM/stepwise)", desc = "Forward stepwise selection across all markers"),
34
- "LASSO" = list(label = "LASSO QTL (penalized)", desc = "L1 penalized regression; lambda by cross-validation")
 
 
35
  )
36
 
37
  # ============================================================
@@ -78,7 +98,6 @@ load_genotype_file <- function(filepath) {
78
 
79
  cat("LOADED:", nrow(gd), "samples,", ncol(gd), "markers,",
80
  length(unique(marker_info$Chromosome)), "chromosomes\n")
81
- cat("CHROMOSOMES:", paste(sort(unique(marker_info$Chromosome)), collapse = ", "), "\n")
82
 
83
  list(geno = gd, marker_info = marker_info,
84
  n_samples = nrow(gd), n_markers = ncol(gd),
@@ -86,7 +105,7 @@ load_genotype_file <- function(filepath) {
86
  }
87
 
88
  # ============================================================
89
- # QTL SCAN โ€” dispatcher
90
  # ============================================================
91
  qtl_scan <- function(genotype_matrix, phenotype_vector, marker_info,
92
  method = "CIM", n_cofactors = 10, window_size = 10) {
@@ -101,6 +120,8 @@ qtl_scan <- function(genotype_matrix, phenotype_vector, marker_info,
101
  cat("Markers after NZV removal:", ncol(X_valid), "\n")
102
 
103
  if (method == "LASSO") return(qtl_scan_lasso(X_valid, y_valid, marker_info))
 
 
104
  if (method == "MQM") return(qtl_scan_mqm(X_valid, y_valid, marker_info))
105
 
106
  # SIM / CIM per-marker scan
@@ -245,6 +266,97 @@ qtl_scan_lasso <- function(X, y, marker_info) {
245
  "Dominance_Ratio","Dominance_Class","N_Cofactors","N_Samples","Method")]
246
  }
247
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
248
  # ============================================================
249
  # MQM โ€” forward stepwise
250
  # ============================================================
@@ -350,28 +462,34 @@ add_lod_support_interval <- function(sig_df, all_df, lod_drop=1.5) {
350
  }
351
 
352
  # ============================================================
353
- # CHROMOSOME IDIOGRAM PLOT
354
  # ============================================================
355
  make_chromosome_idiogram <- function(qtl_list, all_markers_df,
356
  lod_threshold=2.0, trait_colors=NULL) {
357
  if (is.null(all_markers_df)||nrow(all_markers_df)==0) return(NULL)
358
- default_colors <- c("#C0392B","#2166AC","#1A7A4A","#E67E22","#8E44AD","#17A589","#F39C12","#2980B9")
 
 
359
  trait_names <- names(qtl_list)
360
  if (is.null(trait_colors))
361
  trait_colors <- setNames(default_colors[seq_along(trait_names)], trait_names)
362
  shapes <- c(16,17,18,15,3,4,8,9)
363
 
364
  chroms <- sort(unique(as.character(all_markers_df$Chromosome)))
365
- x_gap <- 1.2; bar_height <- 0.35
366
- par(mar=c(4,2,3,1), bg="white")
 
 
 
367
  plot(0,0,type="n",
368
  xlim=c(0,length(chroms)*x_gap+0.5),
369
- ylim=c(-2,max(all_markers_df$Position,na.rm=TRUE)*1.05),
370
- xaxt="n",yaxt="n",xlab="",ylab="cM",main="",frame.plot=FALSE)
 
371
  max_pos <- max(all_markers_df$Position,na.rm=TRUE)
372
  axis(2,at=pretty(c(0,max_pos),n=6),labels=pretty(c(0,max_pos),n=6),
373
- cex.axis=0.75,col="grey60",col.axis="grey30",las=1)
374
- mtext("cM",side=2,line=2.5,cex=0.8,col="grey40")
375
 
376
  for (ci in seq_along(chroms)) {
377
  chr <- chroms[ci]; x_cen <- (ci-1)*x_gap+0.7
@@ -381,51 +499,71 @@ make_chromosome_idiogram <- function(qtl_list, all_markers_df,
381
  chr_min <- min(chr_mk$Position,na.rm=TRUE)
382
  cap_h <- chr_len*0.02
383
 
384
- rect(x_cen-bar_height*0.6,chr_min,x_cen+bar_height*0.6,chr_len,col="grey88",border="grey60",lwd=1.2)
385
- rect(x_cen-bar_height*0.6,chr_min-cap_h,x_cen+bar_height*0.6,chr_min,col="grey75",border="grey60",lwd=0.8)
386
- rect(x_cen-bar_height*0.6,chr_len,x_cen+bar_height*0.6,chr_len+cap_h,col="grey75",border="grey60",lwd=0.8)
 
 
 
 
 
 
387
  cen_pos <- chr_min+(chr_len-chr_min)*0.4
388
- rect(x_cen-bar_height*0.6,cen_pos-chr_len*0.04,x_cen+bar_height*0.6,cen_pos+chr_len*0.04,col="grey50",border="grey40",lwd=0.5)
 
 
 
 
389
  for (mk_pos in chr_mk$Position)
390
- segments(x_cen-bar_height*0.55,mk_pos,x_cen+bar_height*0.55,mk_pos,col="grey70",lwd=0.4)
 
391
 
 
392
  for (ti in seq_along(trait_names)) {
393
  tr <- trait_names[ti]; qdf <- qtl_list[[tr]]
394
  if (is.null(qdf)||"Message"%in%colnames(qdf)) next
395
  sig <- qdf[as.character(qdf$Chromosome)==chr&!is.na(qdf$LOD)&qdf$LOD>=lod_threshold,]
396
  if (nrow(sig)==0) next
397
- col_ti <- trait_colors[[tr]]; pch_ti <- shapes[((ti-1)%%length(shapes))+1]
 
398
  x_off <- if(ti%%2==1) x_cen+bar_height*0.75 else x_cen-bar_height*0.75
399
  for (ri in 1:nrow(sig)) {
400
  pos <- sig$Position[ri]
401
  segments(if(ti%%2==1) x_cen+bar_height*0.6 else x_cen-bar_height*0.6,
402
- pos,x_off,pos,col=col_ti,lwd=0.8,lty=2)
403
  points(x_off,pos,pch=pch_ti,col=col_ti,bg=col_ti,
404
- cex=pmax(0.7,pmin(2.2,0.5+sig$LOD[ri]/4)))
405
  if (sig$LOD[ri]>=lod_threshold*1.5)
406
- text(x_off+ifelse(ti%%2==1,0.15,-0.15),pos,round(sig$LOD[ri],1),cex=0.55,col=col_ti,font=2)
 
407
  }
408
  }
409
- text(x_cen,chr_len+cap_h+chr_len*0.04,paste0("Chr",chr),cex=0.72,font=2,col="grey20")
 
 
410
  }
411
- if (length(trait_names)>0)
412
- legend(0.1,max_pos*0.98,
 
 
413
  legend=paste0(trait_names," (",sapply(trait_names,function(tr){
414
  qdf <- qtl_list[[tr]]
415
  if(is.null(qdf)||"Message"%in%colnames(qdf)) return("0")
416
  sum(!is.na(qdf$LOD)&qdf$LOD>=lod_threshold,na.rm=TRUE)
417
  })," QTL)"),
418
  col=unname(trait_colors[trait_names]),pch=shapes[seq_along(trait_names)],
419
- pt.cex=1.2,cex=0.75,bg="white",box.col="grey70",title="Methods",title.col="grey30")
420
- title(main=paste0("QTL Chromosome Map โ€” LOD >= ",lod_threshold),
421
- cex.main=0.9,font.main=1,col.main="grey20")
 
 
422
  }
423
 
424
  # ============================================================
425
- # PLOTLY MANHATTAN
426
  # ============================================================
427
  make_plotly_manhattan <- function(scan_all, lod_threshold=2.0, title="QTL Manhattan Plot") {
428
- blank <- plot_ly()%>%layout(title=title,plot_bgcolor="#FFF",paper_bgcolor="#FFF")
429
  if (is.null(scan_all)||"Message"%in%colnames(scan_all)) return(blank)
430
  pd <- scan_all[!is.na(scan_all$LOD)&!is.na(scan_all$Position)&!is.na(scan_all$Chromosome),]
431
  if (nrow(pd)==0) return(blank)
@@ -439,42 +577,50 @@ make_plotly_manhattan <- function(scan_all, lod_threshold=2.0, title="QTL Manhat
439
  pd$cum_pos <- pd$Position+offsets[pd$Chromosome]
440
  pd$sig <- pd$LOD>=lod_threshold
441
  chr_mids <- tapply(pd$cum_pos,pd$Chromosome,median,na.rm=TRUE)
442
- chr_colors <- rep(c("#1D4ED8","#64748B"),ceiling(length(chroms)/2))[seq_along(chroms)]
 
 
 
 
443
  names(chr_colors) <- chroms
444
 
445
  p <- plot_ly()
446
  for (ch in chroms) {
447
  sub <- pd[pd$Chromosome==ch,]
448
  p <- p%>%add_trace(data=sub,x=~cum_pos,y=~LOD,type="scatter",mode="markers",
449
- name=paste("Chr",ch),marker=list(size=5,color=chr_colors[ch],opacity=0.75),
450
- text=~paste0("Marker: ",Marker,"<br>Chr: ",Chromosome,"<br>Pos: ",round(Position,1),
451
- " cM<br>LOD: ",round(LOD,2),"<br>PVE: ",round(PVE_Marker_Percent,1),"%"),
 
 
452
  hoverinfo="text",showlegend=FALSE)
453
  }
454
  sig_pd <- pd[pd$sig,]
455
  if (nrow(sig_pd)>0)
456
  p <- p%>%add_trace(data=sig_pd,x=~cum_pos,y=~LOD,type="scatter",mode="markers",
457
- name="Significant",marker=list(size=9,color="#DC2626",symbol="diamond"),
458
- text=~paste0("<b>",Marker,"</b><br>Chr: ",Chromosome,"<br>LOD: ",round(LOD,2)),
 
 
459
  hoverinfo="text")
460
  p%>%add_segments(x=min(pd$cum_pos,na.rm=TRUE),xend=max(pd$cum_pos,na.rm=TRUE),
461
  y=lod_threshold,yend=lod_threshold,
462
- line=list(color="#DC2626",dash="dash",width=1.5),showlegend=FALSE)%>%
463
- layout(title=list(text=paste0(title," | ",sum(pd$sig,na.rm=TRUE)," sig. QTL(s)"),
464
- font=list(size=14,color="#1E293B")),
465
  xaxis=list(title="Chromosome",tickvals=as.list(chr_mids[chroms]),
466
- ticktext=as.list(paste0("Chr",chroms)),tickangle=45,
467
- gridcolor="#F1F5F9",color="#475569"),
468
- yaxis=list(title="LOD Score",gridcolor="#F1F5F9",color="#475569",zeroline=FALSE),
469
- plot_bgcolor="#FFF",paper_bgcolor="#FFF",font=list(color="#475569"),
470
- legend=list(orientation="h",y=-0.15))
 
471
  }
472
 
473
  # ============================================================
474
- # COMMON QTL HELPER โ€” markers significant in >= min_models
475
  # ============================================================
476
  find_common_qtl <- function(compare_res, lod_threshold, min_models=2, window_cM=5) {
477
- # Collect all significant markers per model
478
  sig_list <- list()
479
  for (mth in names(compare_res)) {
480
  r <- compare_res[[mth]]
@@ -489,16 +635,12 @@ find_common_qtl <- function(compare_res, lod_threshold, min_models=2, window_cM=
489
  all_sig <- do.call(rbind, sig_list)
490
  all_sig$Chromosome <- as.character(all_sig$Chromosome)
491
 
492
- # Group markers within window_cM on same chromosome as one QTL region
493
- # For each unique marker, count how many models detect it
494
  marker_counts <- table(all_sig$Marker)
495
  all_sig$N_Models_Detected <- as.integer(marker_counts[all_sig$Marker])
496
 
497
- # Keep only markers detected in >= min_models
498
  common <- all_sig[all_sig$N_Models_Detected >= min_models, ]
499
  if (nrow(common)==0) return(NULL)
500
 
501
- # Summarise: one row per marker, columns per model's LOD
502
  markers_uniq <- unique(common$Marker)
503
  summary_rows <- lapply(markers_uniq, function(mk) {
504
  rows <- common[common$Marker==mk, ]
@@ -508,7 +650,6 @@ find_common_qtl <- function(compare_res, lod_threshold, min_models=2, window_cM=
508
  base$Max_LOD <- round(max(rows$LOD, na.rm=TRUE), 3)
509
  base$Mean_PVE <- round(mean(rows$PVE_Marker_Percent, na.rm=TRUE), 3)
510
  base$Mean_Add_Eff <- round(mean(rows$Additive_Effect, na.rm=TRUE), 3)
511
- # Per-model LOD columns
512
  for (mth in names(compare_res)) {
513
  r_mth <- rows[rows$Model==mth, ]
514
  base[[paste0("LOD_",mth)]] <- if(nrow(r_mth)>0) round(r_mth$LOD[1],3) else NA
@@ -526,124 +667,266 @@ ui <- fluidPage(
526
  shinyjs::useShinyjs(),
527
  tags$head(
528
  tags$link(rel="stylesheet",
529
- href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;600&family=IBM+Plex+Sans:wght@300;400;500;600&display=swap"),
530
- tags$link(rel="stylesheet",
531
- href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css"),
532
  tags$style(HTML("
533
  :root{
534
- --bg:#F8FAFC;--card:#FFFFFF;--border:#E2E8F0;
535
- --txt:#1E293B;--muted:#64748B;--accent:#1D4ED8;
536
- --green:#15803D;--red:#DC2626;--orange:#C05621;
537
- --mono:'IBM Plex Mono',monospace;--sans:'IBM Plex Sans',sans-serif;
538
  }
539
  *{box-sizing:border-box;}
540
- body{font-family:var(--sans);background:var(--bg);color:var(--txt);font-size:14px;margin:0;}
541
- .navbar{background:#FFF!important;border-bottom:2px solid var(--accent)!important;}
542
- .navbar-brand{font-family:var(--mono);font-weight:600;color:var(--accent)!important;}
543
- .navbar-nav>li>a{color:var(--muted)!important;font-size:13px;}
544
- .navbar-nav>li.active>a{color:var(--accent)!important;background:transparent!important;}
545
- .card{background:var(--card);border:1px solid var(--border);border-radius:8px;margin-bottom:16px;}
546
- .card-hd{background:#F1F5F9;border-bottom:1px solid var(--border);padding:10px 14px;
547
- font-family:var(--mono);font-size:11px;color:var(--muted);letter-spacing:.5px;
548
- text-transform:uppercase;border-radius:8px 8px 0 0;font-weight:600;}
549
- .card-bd{padding:14px;}
550
- .info-box{background:#EFF6FF;border:1px solid #BFDBFE;border-left:3px solid var(--accent);
551
- border-radius:6px;padding:10px 14px;margin:8px 0;font-size:12px;color:#1E40AF;font-family:var(--mono);}
552
- .warn-box{background:#FEF9C3;border:1px solid #FDE047;border-left:3px solid #CA8A04;
553
- border-radius:6px;padding:10px 14px;margin:8px 0;font-size:12px;color:#713F12;font-family:var(--mono);}
554
- .good-box{background:#F0FDF4;border:1px solid #86EFAC;border-left:3px solid var(--green);
555
- border-radius:6px;padding:10px 14px;margin:8px 0;font-size:12px;color:#14532D;font-family:var(--mono);}
556
- .btn{border-radius:4px;font-family:var(--mono);font-size:12px;font-weight:600;border:1px solid;}
557
- .btn-primary{background:var(--accent);border-color:var(--accent);color:#FFF;}
558
- .btn-primary:hover{background:#1E40AF;color:#FFF;}
559
- .btn-success{background:var(--green);border-color:var(--green);color:#FFF;}
560
- .btn-info{background:transparent;border-color:#0F766E;color:#0F766E;}
561
- .btn-info:hover{background:#0F766E;color:#FFF;}
562
- .btn-warning{background:transparent;border-color:var(--orange);color:var(--orange);}
563
- .btn-warning:hover{background:var(--orange);color:#FFF;}
564
- .form-control,.selectize-input{background:#FFF!important;border:1px solid var(--border)!important;
565
- color:var(--txt)!important;font-size:13px;border-radius:4px;}
566
- label{font-size:12px;color:var(--muted);}
567
- .model-badge{display:inline-block;background:#EFF6FF;border:1px solid #BFDBFE;
568
- border-radius:12px;padding:2px 10px;font-size:11px;font-family:var(--mono);
569
- color:var(--accent);margin-right:6px;}
570
- .common-badge{display:inline-block;background:#F0FDF4;border:1px solid #86EFAC;
571
- border-radius:12px;padding:2px 10px;font-size:11px;font-family:var(--mono);
572
- color:#15803D;margin-right:6px;font-weight:600;}
573
- table.dataTable{background:#FFF!important;color:var(--txt)!important;}
574
- table.dataTable thead th{background:#F1F5F9!important;font-family:var(--mono);font-size:11px;}
575
- table.dataTable tbody tr:hover{background:#EFF6FF!important;}
576
- table.dataTable tbody td{font-size:12px;}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
577
  "))
578
  ),
579
 
580
  navbarPage(
581
- title = tags$span(tags$i(class="fas fa-dna",style="color:#1D4ED8;margin-right:6px;"), "QTL-Mapper v6"),
582
  id = "nav",
583
 
584
  # โ”€โ”€ DATA UPLOAD โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
585
- tabPanel("Data Upload", icon=icon("upload"),
586
  fluidRow(column(12,
587
  div(class="info-box",
588
- tags$b("QTL-Mapper v6 โ€” Multi-Model, Multi-Chromosome"),
 
589
  tags$br(),
590
- "Format: Row1=header (id,marker1,...), Row2=chromosomes, Row3=positions (cM), rows4+=samples. Genotypes coded 0/1/2."
591
  )
592
  )),
593
  fluidRow(
594
  column(4,
595
  div(class="card",
596
- div(class="card-hd",tags$i(class="fas fa-table",style="margin-right:5px;"),"Training Data"),
597
  div(class="card-bd",
598
- fileInput("geno_file","Training Genotype CSV",accept=".csv"),
599
- fileInput("pheno_file","Training Phenotype CSV",accept=".csv"),
600
  selectInput("pheno_col","Select Trait/Phenotype",choices=NULL),
601
- tags$hr(),
602
- fileInput("test_geno_file","Test Genotype CSV (optional)",accept=".csv"),
603
- fileInput("pop_file","Population Metadata CSV (optional)",accept=".csv"),
604
  helpText("Pop CSV: columns 'id' and 'population'")
605
  )
606
  )
607
  ),
608
  column(4,
609
  div(class="card",
610
- div(class="card-hd",tags$i(class="fas fa-sliders-h",style="margin-right:5px;color:#7C3AED;"),"Mapping Parameters"),
611
  div(class="card-bd",
612
- selectInput("mapping_method","Mapping Method",
613
  choices=setNames(names(MAPPING_MODELS), sapply(MAPPING_MODELS,`[[`,"label")),
614
  selected="CIM"),
615
  uiOutput("method_desc_ui"),
616
- sliderInput("lod_threshold","LOD Threshold",min=0.5,max=10,value=2.0,step=0.1),
617
- sliderInput("val_prop","Validation Proportion",min=0.1,max=0.4,value=0.2,step=0.05),
618
  conditionalPanel("input.mapping_method == 'CIM' || input.mapping_method == 'MQM'",
619
- numericInput("n_cofactors","Max Cofactors (K)",value=10,min=1,max=30,step=1),
620
- numericInput("window_size","Exclusion Window (ยฑmarkers)",value=10,min=1,max=30,step=1)
621
  ),
622
- numericInput("lod_drop","LOD Drop for Interval",value=1.5,min=0.5,max=3.0,step=0.5),
623
- actionButton("run_btn","Run QTL Analysis",class="btn btn-primary btn-block",
624
- style="margin-top:8px;width:100%;")
625
  )
626
  )
627
  ),
628
  column(4,
629
  div(class="card",
630
- div(class="card-hd",tags$i(class="fas fa-info-circle",style="margin-right:5px;"),"Dataset Info"),
631
  div(class="card-bd", uiOutput("dataset_info_ui"))
632
  ),
633
  div(class="card",
634
- div(class="card-hd","Predict Test Phenotypes"),
635
  div(class="card-bd",
636
- actionButton("pred_btn","Predict Test",class="btn btn-info btn-block"),
637
- tags$br(),tags$br(),
638
- downloadButton("dl_pred","Download Predicted (.xlsx)",class="btn btn-success btn-block",
639
- style="width:100%;")
640
  )
641
  )
642
  )
643
  ),
644
  fluidRow(column(12,
645
  div(class="card",
646
- div(class="card-hd","Data Preview"),
647
  div(class="card-bd",
648
  tabsetPanel(
649
  tabPanel("Training Genotype", DTOutput("prev_geno")),
@@ -657,67 +940,78 @@ ui <- fluidPage(
657
  ),
658
 
659
  # โ”€โ”€ RESULTS โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
660
- tabPanel("Results", icon=icon("chart-line"),
661
- fluidRow(column(12,
662
- div(style="display:flex;gap:10px;flex-wrap:wrap;margin-bottom:12px;",
663
- downloadButton("dl_manhattan","Manhattan (.png)",class="btn btn-primary"),
664
- downloadButton("dl_idiogram","Chromosome Map (.png)",class="btn btn-info"),
665
- downloadButton("dl_results","QTL Results (.xlsx)",class="btn btn-success")
 
 
666
  )
667
- )),
668
  fluidRow(
669
  column(7,
670
  div(class="card",
671
- div(class="card-hd","Manhattan Plot โ€” LOD Scores Across All Chromosomes"),
672
- div(class="card-bd",plotlyOutput("manhattan_plot",height="480px"))
673
  )
674
  ),
675
  column(5,
676
  div(class="card",
677
- div(class="card-hd","Chromosome Idiogram โ€” QTL Positions"),
678
- div(class="card-bd",plotOutput("idiogram_plot",height="480px"))
679
  )
680
  )
681
  ),
682
  fluidRow(
683
  column(4,
684
- div(class="card",div(class="card-hd","Model Performance"),
685
- div(class="card-bd",plotlyOutput("perf_plot",height="280px")))
 
 
686
  ),
687
  column(4,
688
- div(class="card",div(class="card-hd","Train: Predicted vs Observed"),
689
- div(class="card-bd",plotlyOutput("reg_train",height="280px")))
 
 
690
  ),
691
  column(4,
692
- div(class="card",div(class="card-hd","Validation: Predicted vs Observed"),
693
- div(class="card-bd",plotlyOutput("reg_val",height="280px")))
 
 
694
  )
695
  ),
696
  fluidRow(column(12,
697
  div(class="card",
698
- div(class="card-hd","QTL Effects Table โ€” Significant Markers (live LOD filter)"),
699
  div(class="card-bd",DTOutput("qtl_table"))
700
  )
701
  )),
702
  fluidRow(column(12,
703
  div(class="card",
704
- div(class="card-hd","Full Genome Scan Results"),
705
  div(class="card-bd",DTOutput("full_scan_table"))
706
  )
707
  ))
708
  ),
709
 
710
  # โ”€โ”€ COMPARE MODELS โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
711
- tabPanel("Compare Models", icon=icon("balance-scale"),
712
  fluidRow(column(12,
713
  div(class="card",
714
- div(class="card-hd","Run Multiple Models & Compare"),
715
  div(class="card-bd",
716
- div(class="warn-box","Select models to compare. Each will run a full genome scan."),
 
 
 
717
  checkboxGroupInput("compare_methods","Methods to Compare:",
718
  choices=setNames(names(MAPPING_MODELS),sapply(MAPPING_MODELS,`[[`,"label")),
719
- selected=c("SIM","CIM"),inline=TRUE),
720
- actionButton("run_compare","Run All Selected Models",class="btn btn-primary"),
721
  tags$br(),tags$br(),
722
  uiOutput("compare_status_ui")
723
  )
@@ -726,41 +1020,41 @@ ui <- fluidPage(
726
  fluidRow(
727
  column(6,
728
  div(class="card",
729
- div(class="card-hd","Multi-Model Chromosome Idiogram"),
730
- div(class="card-bd",plotOutput("compare_idiogram",height="500px"))
731
  )
732
  ),
733
  column(6,
734
  div(class="card",
735
- div(class="card-hd","QTL Count by Method & Chromosome"),
736
- div(class="card-bd",plotlyOutput("compare_bar",height="500px"))
737
  )
738
  )
739
  ),
740
  fluidRow(column(12,
741
  div(class="card",
742
- div(class="card-hd","All Significant QTLs โ€” All Models"),
743
  div(class="card-bd",DTOutput("compare_table"))
744
  )
745
  ))
746
  ),
747
 
748
  # โ”€โ”€ COMMON QTL โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
749
- tabPanel("Common QTL", icon=icon("bullseye"),
750
  fluidRow(column(12,
751
  div(class="card",
752
  div(class="card-hd",
753
- tags$i(class="fas fa-bullseye",style="margin-right:5px;color:#15803D;"),
754
  "Common QTL โ€” Markers Detected Across Multiple Models"),
755
  div(class="card-bd",
756
  fluidRow(
757
  column(4,
758
- sliderInput("min_models","Minimum Models Agreeing",
759
- min=2, max=4, value=2, step=1)
760
  ),
761
  column(4,
762
- div(style="margin-top:24px;",
763
- downloadButton("dl_common_qtl","Download Common QTL (.xlsx)",
764
  class="btn btn-success btn-block")
765
  )
766
  ),
@@ -776,25 +1070,26 @@ ui <- fluidPage(
776
  fluidRow(
777
  column(6,
778
  div(class="card",
779
- div(class="card-hd","Common QTL โ€” Chromosome Idiogram"),
780
- div(class="card-bd",plotOutput("common_idiogram",height="480px"))
781
  )
782
  ),
783
  column(6,
784
  div(class="card",
785
- div(class="card-hd","Model Agreement per Chromosome"),
786
- div(class="card-bd",plotlyOutput("common_bar",height="480px"))
787
  )
788
  )
789
  ),
790
  fluidRow(column(12,
791
  div(class="card",
792
- div(class="card-hd","Common QTL Details Table"),
793
  div(class="card-bd",
794
  div(class="good-box",
795
- "Markers shown here are significant (above LOD threshold) in at least the number of models set by the slider above.",
 
796
  tags$br(),
797
- "Run the Compare Models tab first to populate this table."
798
  ),
799
  tags$br(),
800
  DTOutput("common_qtl_table")
@@ -804,62 +1099,84 @@ ui <- fluidPage(
804
  ),
805
 
806
  # โ”€โ”€ DOMESTICATION โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
807
- tabPanel("Domestication", icon=icon("leaf"),
808
  fluidRow(
809
  column(4,
810
  div(class="card",
811
- div(class="card-hd","Parameters"),
812
  div(class="card-bd",
813
- numericInput("fst_thr","Fst Threshold",value=0.1,min=0.05,max=0.5,step=0.01),
814
- numericInput("tajima_thr","Tajima's D Threshold",value=-1,min=-5,max=0,step=0.1),
815
- actionButton("run_dom","Run Domestication",class="btn btn-primary btn-block")
816
  )
817
  )
818
  ),
819
  column(8,
820
  div(class="card",
821
- div(class="card-hd","Population Data Preview"),
822
  div(class="card-bd",DTOutput("prev_pop"))
823
  )
824
  )
825
  ),
826
  fluidRow(
827
- column(6,div(class="card",div(class="card-hd","Fst Manhattan"), div(class="card-bd",plotlyOutput("fst_plot",height="380px")))),
828
- column(6,div(class="card",div(class="card-hd","Tajima's D Manhattan"),div(class="card-bd",plotlyOutput("tajima_plot",height="380px"))))
 
 
 
 
 
 
 
 
 
 
829
  ),
830
  fluidRow(column(12,
831
  div(class="card",
832
- div(class="card-hd","Selection Signatures"),
833
- div(class="card-bd",DTOutput("sel_table"),tags$br(),
834
- downloadButton("dl_sel","Download (.xlsx)",class="btn btn-success"))
 
 
 
835
  )
836
  ))
837
  ),
838
 
839
  # โ”€โ”€ ABOUT โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
840
- tabPanel("About", icon=icon("info-circle"),
841
- fluidRow(column(8,offset=2,
842
  div(class="card",
843
  div(class="card-bd",
844
- tags$h4(style="color:var(--accent);font-family:var(--mono);","QTL-Mapper v6 โ€” Methods"),
845
- div(class="warn-box",
846
- tags$b("Changes in this version:"), tags$br(),
847
- "- Ridge Regression removed", tags$br(),
848
- "- Chat box removed", tags$br(),
849
- "- Common QTL tab: markers significant across multiple models", tags$br(),
850
- "- LOD slider is fully reactive (no re-scan needed)", tags$br(),
851
- "- Compare tab uses same validation proportion as main analysis"
 
 
852
  ),
853
- tags$h5(style="margin-top:16px;font-family:var(--mono);","Mapping Methods"),
854
- tags$ul(lapply(MAPPING_MODELS, function(m) tags$li(tags$b(m$label),"โ€”",m$desc))),
855
- tags$h5(style="margin-top:16px;font-family:var(--mono);","References"),
 
856
  tags$ul(
857
- tags$li("Zeng (1993) PNAS 90:10972 โ€” CIM"),
858
- tags$li("Zeng (1994) Genetics 136:1457 โ€” CIM"),
859
  tags$li("Lander & Botstein (1989) Genetics 121:185 โ€” LOD intervals"),
860
- tags$li("Lynch & Walsh (1998) โ€” Semi-partial R2"),
861
  tags$li("Tibshirani (1996) JRSS-B 58:267 โ€” LASSO"),
862
- tags$li("Contact: ashmithamganesan@gmail.com, P.sinha@cgiar.org")
 
 
 
 
 
 
 
 
863
  )
864
  )
865
  )
@@ -885,25 +1202,29 @@ server <- function(input, output, session) {
885
  compare_res = list()
886
  )
887
 
888
- # Reactive LOD threshold โ€” drives all outputs live
889
  lod_thr <- reactive({ input$lod_threshold })
890
 
891
  # โ”€โ”€ Method description โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
892
  output$method_desc_ui <- renderUI({
893
  m <- input$mapping_method
894
  if (is.null(m)||!m%in%names(MAPPING_MODELS)) return(NULL)
895
- div(class="info-box", MAPPING_MODELS[[m]]$desc)
896
  })
897
 
898
  # โ”€โ”€ Dataset info โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
899
  output$dataset_info_ui <- renderUI({
900
- if (is.null(rv$geno)) return(tags$p("No data loaded yet."))
 
901
  tagList(
902
- tags$p(tags$b("Samples:"), nrow(rv$geno)),
903
- tags$p(tags$b("Markers:"), ncol(rv$geno)),
904
- tags$p(tags$b("Chromosomes:"), length(unique(rv$marker_info$Chromosome))),
905
- tags$p(tags$b("Chr list:"), paste(sort(unique(rv$marker_info$Chromosome)),collapse=", ")),
906
- if(!is.null(rv$pheno)) tags$p(tags$b("Traits:"), ncol(rv$pheno))
 
 
 
 
907
  )
908
  })
909
 
@@ -912,10 +1233,12 @@ server <- function(input, output, session) {
912
  req(input$geno_file)
913
  tryCatch({
914
  res <- load_genotype_file(input$geno_file$datapath)
915
- rv$geno <- res$geno; rv$marker_info <- res$marker_info; rv$all_markers <- res$marker_info
916
- showNotification(paste(res$n_markers,"markers,",res$n_samples,"samples,",
917
- length(res$chromosomes),"chromosomes"), type="message")
918
- }, error=function(e) showNotification(paste("Geno error:",e$message),type="error"))
 
 
919
  })
920
 
921
  observeEvent(input$pheno_file, {
@@ -926,16 +1249,16 @@ server <- function(input, output, session) {
926
  for (col in colnames(pd)) pd[[col]] <- as.numeric(as.character(pd[[col]]))
927
  rv$pheno <- pd
928
  updateSelectInput(session,"pheno_col",choices=colnames(pd),selected=colnames(pd)[1])
929
- showNotification(paste(ncol(pd),"traits loaded"),type="message")
930
- }, error=function(e) showNotification(paste("Pheno error:",e$message),type="error"))
931
  })
932
 
933
  observeEvent(input$pop_file, {
934
  req(input$pop_file)
935
  tryCatch({
936
  rv$pop_data <- read.csv(input$pop_file$datapath)
937
- showNotification(paste("Pop data:",nrow(rv$pop_data),"samples"),type="message")
938
- }, error=function(e) showNotification(paste("Pop error:",e$message),type="error"))
939
  })
940
 
941
  observeEvent(input$test_geno_file, {
@@ -943,24 +1266,24 @@ server <- function(input, output, session) {
943
  tryCatch({
944
  res <- load_genotype_file(input$test_geno_file$datapath)
945
  rv$test_geno <- res$geno
946
- showNotification(paste("Test geno:",nrow(res$geno),"samples"),type="message")
947
- }, error=function(e) showNotification(paste("Test geno error:",e$message),type="error"))
948
  })
949
 
950
  # โ”€โ”€ Previews โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
951
- output$prev_geno <- renderDT({ req(input$geno_file); datatable(head(read.csv(input$geno_file$datapath),10), options=list(scrollX=TRUE,pageLength=5)) })
952
- output$prev_pheno <- renderDT({ req(input$pheno_file); datatable(head(read.csv(input$pheno_file$datapath),10),options=list(scrollX=TRUE,pageLength=5)) })
953
- output$prev_test_geno <- renderDT({ req(rv$test_geno); datatable(head(rv$test_geno,10),options=list(scrollX=TRUE,pageLength=5)) })
954
- output$prev_pred <- renderDT({ req(rv$pred_test); datatable(rv$pred_test,options=list(scrollX=TRUE,pageLength=8)) })
955
- output$prev_pop <- renderDT({ req(rv$pop_data); datatable(head(rv$pop_data,10),options=list(scrollX=TRUE,pageLength=5)) })
956
 
957
  # โ”€โ”€ MAIN ANALYSIS โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
958
  observeEvent(input$run_btn, {
959
  req(rv$geno, rv$pheno, input$pheno_col)
960
- showNotification(paste("Starting",input$mapping_method,"scan..."),type="message")
961
  tryCatch({
962
  cs <- intersect(rownames(rv$geno), rownames(rv$pheno))
963
- if (length(cs)==0) { showNotification("No common samples!",type="error"); return() }
964
  X <- rv$geno[cs,,drop=FALSE]; y <- as.numeric(rv$pheno[cs,input$pheno_col])
965
  set.seed(42)
966
  tr_idx <- caret::createDataPartition(y, p=1-input$val_prop, list=FALSE)
@@ -989,7 +1312,7 @@ server <- function(input, output, session) {
989
  ytr_p <- predict(fit,X_tr_rf); yv_p <- predict(fit,X_v_rf)
990
  tr_r2 <- 1-sum((y_tr-ytr_p)^2)/sum((y_tr-mean(y_tr))^2)
991
  v_r2 <- 1-sum((y_v-yv_p)^2)/sum((y_v-mean(y_v))^2)
992
- rv$perf <- data.frame(Metric=c("R2 Train","R Train","R2 Validation","R Validation"),
993
  Value=c(tr_r2,cor(y_tr,ytr_p),v_r2,cor(y_v,yv_p)))
994
  rv$tr_pred <- data.frame(Observed=y_tr, Predicted=ytr_p)
995
  rv$val_pred <- data.frame(Observed=y_v, Predicted=yv_p)
@@ -998,12 +1321,10 @@ server <- function(input, output, session) {
998
 
999
  n_sig <- if(!is.null(rv$scan_all)&&!"Message"%in%colnames(rv$scan_all))
1000
  sum(rv$scan_all$LOD>=lod_thr()&!is.na(rv$scan_all$LOD),na.rm=TRUE) else 0
1001
- n_chr <- if(!is.null(rv$scan_all)&&!"Message"%in%colnames(rv$scan_all))
1002
- length(unique(rv$scan_all$Chromosome)) else 0
1003
- showNotification(paste(input$mapping_method,"done:",n_sig,"QTLs on",n_chr,"chromosomes"),type="message")
1004
- updateTabsetPanel(session,"nav",selected="Results")
1005
  }, error=function(e) {
1006
- showNotification(paste("Analysis error:",e$message),type="error")
1007
  cat("ANALYSIS ERROR:",e$message,"\n")
1008
  })
1009
  })
@@ -1012,21 +1333,20 @@ server <- function(input, output, session) {
1012
  output$compare_status_ui <- renderUI({
1013
  if (length(rv$compare_res)==0) return(NULL)
1014
  tags$div(class="info-box",
1015
- tags$b("Completed: "), paste(names(rv$compare_res),collapse=", "),
1016
  tags$br(),
1017
  lapply(names(rv$compare_res), function(m) {
1018
  r <- rv$compare_res[[m]]
1019
- if(is.null(r)||"Message"%in%colnames(r)) return(tags$span(m,": 0 QTLs "))
1020
  n <- sum(r$LOD>=lod_thr(),na.rm=TRUE)
1021
- nc <- length(unique(r$Chromosome[!is.na(r$LOD)]))
1022
- tags$span(class="model-badge",paste0(m,": ",n," QTLs / ",nc," chr"))
1023
  })
1024
  )
1025
  })
1026
 
1027
  observeEvent(input$run_compare, {
1028
  req(rv$geno, rv$pheno, input$compare_methods, input$pheno_col)
1029
- if (length(input$compare_methods)==0) { showNotification("Select at least one method",type="warning"); return() }
1030
  cs <- intersect(rownames(rv$geno),rownames(rv$pheno))
1031
  X <- rv$geno[cs,,drop=FALSE]; y <- as.numeric(rv$pheno[cs,input$pheno_col])
1032
  set.seed(42)
@@ -1034,8 +1354,9 @@ server <- function(input, output, session) {
1034
  X_tr <- X[tr_idx,,drop=FALSE]; y_tr <- y[tr_idx]
1035
 
1036
  compare_list <- list()
1037
- withProgress(message="Comparing models...",value=0,{
1038
- for (mth in input$compare_methods) {
 
1039
  incProgress(1/length(input$compare_methods),detail=paste("Running",mth))
1040
  res <- tryCatch(
1041
  qtl_scan(X_tr,y_tr,rv$marker_info,method=mth,
@@ -1045,14 +1366,14 @@ server <- function(input, output, session) {
1045
  }
1046
  })
1047
  rv$compare_res <- compare_list
1048
- showNotification(paste("Compared",length(compare_list),"models"),type="message")
1049
  })
1050
 
1051
  output$compare_idiogram <- renderPlot({
1052
  req(length(rv$compare_res)>0, rv$all_markers)
1053
- par(bg="white")
1054
  make_chromosome_idiogram(rv$compare_res, rv$all_markers, lod_thr())
1055
- }, bg="white")
1056
 
1057
  output$compare_bar <- renderPlotly({
1058
  req(length(rv$compare_res)>0)
@@ -1069,10 +1390,14 @@ server <- function(input, output, session) {
1069
  if(length(rows)==0) return(plot_ly()%>%layout(title="No significant QTLs found"))
1070
  df <- do.call(rbind,rows)
1071
  df$Chromosome <- factor(df$Chromosome,levels=sort(unique(df$Chromosome)))
1072
- plot_ly(df,x=~Chromosome,y=~Count,color=~Method,type="bar")%>%
1073
- layout(barmode="group",title="QTL Count by Method & Chromosome",
1074
- xaxis=list(title="Chromosome"),yaxis=list(title="# Significant QTLs"),
1075
- plot_bgcolor="#FFF",paper_bgcolor="#FFF")
 
 
 
 
1076
  })
1077
 
1078
  output$compare_table <- renderDT({
@@ -1090,7 +1415,8 @@ server <- function(input, output, session) {
1090
  df <- do.call(rbind,rows)
1091
  df$N_Models <- as.integer(table(df$Marker)[df$Marker])
1092
  datatable(df[order(-df$N_Models,-df$LOD),],
1093
- options=list(scrollX=TRUE,pageLength=15),rownames=FALSE)%>%
 
1094
  formatRound(c("LOD","PVE_Marker_Percent","Position"),3)
1095
  })
1096
 
@@ -1103,16 +1429,18 @@ server <- function(input, output, session) {
1103
  output$common_qtl_summary_ui <- renderUI({
1104
  cq <- common_qtl_data()
1105
  if (is.null(cq)||nrow(cq)==0)
1106
- return(div(class="warn-box","No common QTLs found. Run Compare Models first."))
1107
  n_all <- nrow(cq)
1108
  n_max <- sum(cq$N_Models_Detected==length(rv$compare_res), na.rm=TRUE)
1109
  tagList(
1110
  div(class="good-box",
1111
- tags$b(n_all," common QTL(s)"),
 
1112
  tags$br(),
1113
- paste0(n_max," detected in ALL ", length(rv$compare_res)," models"),
 
1114
  tags$br(),
1115
- paste0("Chromosomes: ", paste(sort(unique(cq$Chromosome)),collapse=", "))
1116
  )
1117
  )
1118
  })
@@ -1124,14 +1452,15 @@ server <- function(input, output, session) {
1124
  options=list(dom="t")))
1125
  num_cols <- intersect(c("Position","Mean_LOD","Max_LOD","Mean_PVE","Mean_Add_Eff",
1126
  paste0("LOD_",names(rv$compare_res))), colnames(cq))
1127
- datatable(cq, options=list(scrollX=TRUE,pageLength=15), rownames=FALSE) %>%
 
1128
  formatRound(num_cols, 3) %>%
1129
  formatStyle("N_Models_Detected",
1130
- background=styleColorBar(range(cq$N_Models_Detected,na.rm=TRUE),"#86EFAC"),
1131
  backgroundSize="100% 80%", backgroundRepeat="no-repeat",
1132
  backgroundPosition="center") %>%
1133
  formatStyle("Max_LOD",
1134
- background=styleColorBar(range(cq$Max_LOD,na.rm=TRUE),"#BFDBFE"),
1135
  backgroundSize="100% 80%", backgroundRepeat="no-repeat",
1136
  backgroundPosition="center")
1137
  })
@@ -1139,10 +1468,8 @@ server <- function(input, output, session) {
1139
  output$common_idiogram <- renderPlot({
1140
  cq <- common_qtl_data()
1141
  req(!is.null(cq), nrow(cq)>0, rv$all_markers)
1142
- # Build a fake qtl_list with one entry per N_Models level for colour coding
1143
- # Simpler: colour by N_Models_Detected (1 entry per unique count)
1144
  n_levels <- sort(unique(cq$N_Models_Detected), decreasing=TRUE)
1145
- cols <- c("#15803D","#1D4ED8","#C05621","#7C3AED","#DC2626")
1146
  pal <- setNames(cols[seq_along(n_levels)], as.character(n_levels))
1147
 
1148
  qtl_list_cq <- lapply(setNames(n_levels, paste0(n_levels," model(s)")), function(nl) {
@@ -1153,16 +1480,16 @@ server <- function(input, output, session) {
1153
  sub$Method <- paste0(nl," models")
1154
  sub
1155
  })
1156
- par(bg="white")
1157
  make_chromosome_idiogram(qtl_list_cq, rv$all_markers, lod_thr(),
1158
  trait_colors=setNames(cols[seq_along(n_levels)],
1159
  paste0(n_levels," model(s)")))
1160
- }, bg="white")
1161
 
1162
  output$common_bar <- renderPlotly({
1163
  cq <- common_qtl_data()
1164
  if (is.null(cq)||nrow(cq)==0)
1165
- return(plot_ly()%>%layout(title="No common QTLs",plot_bgcolor="#FFF",paper_bgcolor="#FFF"))
1166
 
1167
  df <- cq %>%
1168
  dplyr::group_by(Chromosome, N_Models_Detected) %>%
@@ -1171,13 +1498,13 @@ server <- function(input, output, session) {
1171
  df$Chromosome <- factor(df$Chromosome, levels=sort(unique(as.character(df$Chromosome))))
1172
 
1173
  plot_ly(df,x=~Chromosome,y=~Count,color=~Label,type="bar",
1174
- colors=c("#15803D","#1D4ED8","#C05621","#7C3AED"))%>%
1175
  layout(barmode="stack",
1176
- title="Common QTL Count by Chromosome & Model Agreement",
1177
- xaxis=list(title="Chromosome"),
1178
  yaxis=list(title="# Common QTLs"),
1179
- plot_bgcolor="#FFF",paper_bgcolor="#FFF",
1180
- legend=list(title=list(text="Detected by")))
1181
  })
1182
 
1183
  # โ”€โ”€ MAIN PLOTS โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
@@ -1192,37 +1519,43 @@ server <- function(input, output, session) {
1192
  if(!is.null(rv$scan_all)&&!"Message"%in%colnames(rv$scan_all))
1193
  res_list[[input$mapping_method]] <- rv$scan_all
1194
  if(length(res_list)==0){ plot(0,0,type="n",axes=FALSE,xlab="",ylab=""); text(0,0,"Run analysis first",cex=1.2); return() }
1195
- par(bg="white")
1196
  make_chromosome_idiogram(res_list, rv$all_markers, lod_thr())
1197
- }, bg="white")
1198
 
1199
  output$perf_plot <- renderPlotly({
1200
  req(rv$perf)
1201
  plot_ly(rv$perf,x=~Metric,y=~Value,type="bar",
1202
- marker=list(color=c("#1D4ED8","#3B82F6","#15803D","#22C55E")),
1203
- text=~round(Value,3),textposition="outside")%>%
1204
- layout(title="Model Performance",yaxis=list(range=c(0,1.15),title="Value"),
1205
- plot_bgcolor="#FFF",paper_bgcolor="#FFF")
 
 
1206
  })
1207
 
1208
  output$reg_train <- renderPlotly({
1209
  req(rv$tr_pred)
1210
  plot_ly(rv$tr_pred,x=~Observed,y=~Predicted,type="scatter",mode="markers",
1211
- marker=list(size=5,color="#1D4ED8",opacity=.75))%>%
1212
  add_trace(x=range(rv$tr_pred$Observed),y=range(rv$tr_pred$Observed),
1213
- type="scatter",mode="lines",line=list(color="#DC2626",dash="dash"),showlegend=FALSE)%>%
1214
- layout(title="Training",plot_bgcolor="#FFF",paper_bgcolor="#FFF",
1215
- xaxis=list(title="Observed"),yaxis=list(title="Predicted"))
 
 
1216
  })
1217
 
1218
  output$reg_val <- renderPlotly({
1219
  req(rv$val_pred)
1220
  plot_ly(rv$val_pred,x=~Observed,y=~Predicted,type="scatter",mode="markers",
1221
- marker=list(size=5,color="#15803D",opacity=.75))%>%
1222
  add_trace(x=range(rv$val_pred$Observed),y=range(rv$val_pred$Observed),
1223
- type="scatter",mode="lines",line=list(color="#DC2626",dash="dash"),showlegend=FALSE)%>%
1224
- layout(title="Validation",plot_bgcolor="#FFF",paper_bgcolor="#FFF",
1225
- xaxis=list(title="Observed"),yaxis=list(title="Predicted"))
 
 
1226
  })
1227
 
1228
  # โ”€โ”€ TABLES โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
@@ -1240,7 +1573,8 @@ server <- function(input, output, session) {
1240
  "CI_Lower","CI_Upper","Dominance_Effect","Dominance_Ratio","Dominance_Class",
1241
  "N_Cofactors","N_Samples","Method","Interval_Start","Interval_End",
1242
  "Interval_Size_cM","Low_Flank","High_Flank"), colnames(sig))
1243
- datatable(sig[,disp],options=list(scrollX=TRUE,pageLength=10),rownames=FALSE)%>%
 
1244
  formatRound(intersect(c("LOD","PVE_Marker_Percent","PVE_CIM_Percent","Additive_Effect",
1245
  "SE_Additive","CI_Lower","CI_Upper","Dominance_Ratio","Interval_Size_cM"),disp),3)%>%
1246
  formatSignif(intersect("P_Value",disp),digits=3)
@@ -1250,17 +1584,17 @@ server <- function(input, output, session) {
1250
  req(rv$scan_all)
1251
  if("Message"%in%colnames(rv$scan_all))
1252
  return(datatable(data.frame(Status=rv$scan_all$Message[1]),options=list(dom="t")))
1253
- datatable(rv$scan_all,options=list(scrollX=TRUE,pageLength=15,order=list(list(4,"desc"))),
1254
- rownames=FALSE)%>%
1255
  formatRound(c("LOD","PVE_Marker_Percent","Additive_Effect"),3)%>%
1256
  formatSignif("P_Value",digits=3)
1257
  })
1258
 
1259
  # โ”€โ”€ PREDICT TEST โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
1260
  observeEvent(input$pred_btn, {
1261
- if(is.null(rv$model_fit)){ showNotification("Run analysis first",type="error"); return() }
1262
- if(is.null(rv$test_geno)){ showNotification("Upload test genotype first",type="error"); return() }
1263
- withProgress(message="Predicting...",value=0.2,{
1264
  train_cols <- rv$model_cols; test_raw <- rv$test_geno
1265
  common_m <- intersect(train_cols, colnames(test_raw))
1266
  X_pred <- as.data.frame(matrix(0,nrow=nrow(test_raw),ncol=length(train_cols),
@@ -1275,7 +1609,7 @@ server <- function(input, output, session) {
1275
  rv$pred_test <- data.frame(Sample_ID=rownames(test_raw),Predicted_Phenotype=round(preds,4))
1276
  incProgress(0.3)
1277
  })
1278
- showNotification(paste("Predicted",nrow(rv$pred_test),"test samples"),type="message")
1279
  })
1280
 
1281
  # โ”€โ”€ DOMESTICATION โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
@@ -1307,15 +1641,15 @@ server <- function(input, output, session) {
1307
  cs <- intersect(rownames(rv$geno),rv$pop_data$id)
1308
  X <- rv$geno[cs,,drop=FALSE]; ps <- rv$pop_data[rv$pop_data$id%in%cs,]
1309
  sel <- calc_sel(X,ps,rv$marker_info)
1310
- if(is.null(sel)){ showNotification("No selection metrics computed",type="error"); return() }
1311
  sel$Significant <- sel$Fst>input$fst_thr|sel$Tajima_D_Dom<input$tajima_thr
1312
  rv$sel_metrics <- sel
1313
- showNotification(paste(sum(sel$Significant,na.rm=TRUE),"selection signatures"),type="message")
1314
- }, error=function(e) showNotification(paste("Dom error:",e$message),type="error"))
1315
  })
1316
 
1317
  create_man_plotly <- function(data, y_col, title, threshold, y_label=y_col) {
1318
- blank <- plot_ly()%>%layout(title=title,plot_bgcolor="#FFF",paper_bgcolor="#FFF")
1319
  if(is.null(data)||nrow(data)==0||"Message"%in%colnames(data)) return(blank)
1320
  pd <- data[!is.na(data[[y_col]])&!is.na(data$Chromosome),]
1321
  if(nrow(pd)==0) return(blank)
@@ -1328,32 +1662,35 @@ server <- function(input, output, session) {
1328
  }
1329
  pd$cum_pos <- pd$Position+offsets[pd$Chromosome]
1330
  chr_mids <- tapply(pd$cum_pos,pd$Chromosome,median,na.rm=TRUE)
1331
- pal <- rep(c("#1D4ED8","#64748B"),ceiling(length(chroms)/2))[seq_along(chroms)]
1332
  names(pal) <- chroms
1333
  p <- plot_ly()
1334
  for (ch in chroms)
1335
  p <- p%>%add_trace(data=pd[pd$Chromosome==ch,],x=~cum_pos,
1336
  y=as.formula(paste0("~",y_col)),type="scatter",mode="markers",
1337
- name=paste("Chr",ch),marker=list(size=5,color=pal[ch],opacity=.75),showlegend=FALSE,
1338
- text=~paste0("Marker: ",Marker,"<br>Chr: ",Chromosome,"<br>",y_label,": ",round(get(y_col),3)),
 
 
1339
  hoverinfo="text")
1340
  if(!is.null(threshold))
1341
  p <- p%>%add_segments(x=min(pd$cum_pos,na.rm=TRUE),xend=max(pd$cum_pos,na.rm=TRUE),
1342
- y=threshold,yend=threshold,line=list(color="#DC2626",dash="dash",width=1.5),showlegend=FALSE)
1343
- p%>%layout(title=title,
1344
  xaxis=list(title="Chromosome",tickvals=as.list(chr_mids[chroms]),
1345
- ticktext=as.list(paste0("Chr",chroms)),tickangle=45,gridcolor="#F1F5F9"),
1346
- yaxis=list(title=y_label,gridcolor="#F1F5F9"),
1347
- plot_bgcolor="#FFF",paper_bgcolor="#FFF")
1348
  }
1349
 
1350
- output$fst_plot <- renderPlotly({ req(rv$sel_metrics); create_man_plotly(rv$sel_metrics,"Fst","Fst",input$fst_thr,"Fst") })
1351
- output$tajima_plot <- renderPlotly({ req(rv$sel_metrics); create_man_plotly(rv$sel_metrics,"Tajima_D_Dom","Tajima's D",input$tajima_thr,"Tajima D") })
1352
  output$sel_table <- renderDT({
1353
  req(rv$sel_metrics)
1354
  datatable(rv$sel_metrics[order(-rv$sel_metrics$Fst),],
1355
- options=list(scrollX=TRUE,pageLength=10),rownames=FALSE)%>%
1356
- formatRound(c("Fst","Pi_Dom","Pi_Wild","Tajima_D_Dom"),3)
 
1357
  })
1358
 
1359
  # โ”€โ”€ DOWNLOADS โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
@@ -1372,26 +1709,33 @@ server <- function(input, output, session) {
1372
  }
1373
  pd$cum_pos <- pd$Position+offsets[pd$Chromosome]
1374
  pd$sig <- pd$LOD>=lod_thr()
1375
- chr_colors <- rep(c("#2563EB","#64748B"),ceiling(length(chroms)/2))[seq_along(chroms)]
1376
  names(chr_colors) <- chroms
1377
  chr_mids <- tapply(pd$cum_pos,pd$Chromosome,median,na.rm=TRUE)
1378
  p <- ggplot(pd,aes(x=cum_pos,y=LOD))+
1379
- geom_point(aes(color=Chromosome),size=1.2,alpha=.7,show.legend=FALSE)+
1380
- geom_point(data=pd[pd$sig,],color="#DC2626",size=3,shape=18)+
1381
- geom_hline(yintercept=lod_thr(),linetype="dashed",color="#DC2626",linewidth=.6)+
1382
  scale_color_manual(values=chr_colors)+
1383
- scale_x_continuous(breaks=chr_mids[chroms],labels=paste0("Chr",chroms))+
1384
  labs(title=paste(input$mapping_method,"Manhattan Plot"),
1385
- subtitle=paste0("LOD >= ",lod_thr()," | ",sum(pd$sig,na.rm=TRUE)," sig. QTLs"),
1386
  x="Chromosome",y="LOD Score")+
1387
- theme_bw(base_size=12)+
1388
- theme(panel.background=element_rect(fill="white"),plot.background=element_rect(fill="white"),
1389
- panel.grid.minor=element_blank(),panel.grid.major.x=element_blank(),
1390
- axis.text.x=element_text(angle=45,hjust=1),plot.title=element_text(face="bold"))
 
 
 
 
 
 
 
1391
  if(sum(pd$sig,na.rm=TRUE)>0&&sum(pd$sig,na.rm=TRUE)<=30)
1392
  p <- p+ggrepel::geom_label_repel(data=pd[pd$sig,],aes(label=Marker),
1393
- size=2.5,max.overlaps=15,fill="white",color="#DC2626",segment.color="#DC2626")
1394
- ggsave(file,plot=p,width=14,height=6,dpi=200,bg="white")
1395
  }
1396
  )
1397
 
@@ -1407,8 +1751,8 @@ server <- function(input, output, session) {
1407
  if(!is.null(r)&&!"Message"%in%colnames(r)) res_list[[m]] <- r
1408
  }
1409
  if(length(res_list)==0) return()
1410
- png(file,width=1800,height=900,res=150,bg="white")
1411
- par(bg="white")
1412
  make_chromosome_idiogram(res_list, rv$all_markers, lod_thr())
1413
  dev.off()
1414
  }
@@ -1474,4 +1818,5 @@ server <- function(input, output, session) {
1474
  )
1475
  }
1476
 
 
1477
  shinyApp(ui=ui, server=server)
 
1
  # ============================================================
2
+ # QTL-Mapper v6 โ€” Multi-Model QTL Mapping (Complete Enhanced)
3
  #
4
+ # FEATURES:
5
+ # - 6 mapping models: SIM, CIM, MQM, LASSO, ElasticNet, RandomForest
6
+ # - Pastel/soft color theme for all plots
7
+ # - Interactive Manhattan plots with hover info
8
+ # - Chromosome idiogram with QTL positions
9
+ # - Common QTL tab for markers significant across models
10
+ # - Downloadable results in multiple formats
11
  # ============================================================
12
 
13
  options(repos = c(CRAN = "https://cloud.r-project.org"))
 
15
  required_packages <- c(
16
  "shiny", "randomForest", "caret", "DT", "ggplot2", "plotly",
17
  "writexl", "viridis", "reshape2", "dplyr", "ggrepel", "glmnet",
18
+ "shinyjs", "RColorBrewer", "scales", "gridExtra", "pheatmap",
19
+ "corrplot", "ggpubr", "GGally"
20
  )
21
 
22
  for (pkg in required_packages) {
 
27
  }
28
 
29
  # ============================================================
30
+ # PASTEL COLOR PALETTES
31
+ # ============================================================
32
+ PASTEL_COLORS <- c(
33
+ "#A8E6CF", "#DCEDC1", "#FFD3B6", "#FFAAA5", "#FF8B94",
34
+ "#B5EAD7", "#C7CEEA", "#E2F0CB", "#FFDAC1", "#E2F0CB",
35
+ "#B5EAD7", "#FFB7B2", "#C7CEEA", "#FFDAC1", "#E6C8A0"
36
+ )
37
+
38
+ CHROMOSOME_PALETTE <- c(
39
+ "#8DA0CB", "#66C2A5", "#FC8D62", "#E78AC3", "#A6D854",
40
+ "#FFD92F", "#E5C494", "#B3B3B3", "#7FBF7B", "#AF8DC3"
41
+ )
42
+
43
+ QTL_COLORS <- c("#E15759", "#4E79A7", "#59A14F", "#F28E2B", "#B07AA2", "#9C755F")
44
+
45
+ # ============================================================
46
+ # MAPPING MODEL DEFINITIONS (6 models)
47
  # ============================================================
48
  MAPPING_MODELS <- list(
49
+ "SIM" = list(label = "Simple Interval Mapping (SIM)", desc = "Single-marker regression; LOD = -log10(p); baseline model"),
50
+ "CIM" = list(label = "Composite Interval Mapping (CIM)", desc = "CIM with RF-selected cofactors; controls background genetic variation"),
51
+ "MQM" = list(label = "Multiple QTL Model (MQM)", desc = "Forward stepwise selection across all markers; multi-QTL detection"),
52
+ "LASSO" = list(label = "LASSO QTL (L1 penalized)", desc = "L1 penalized regression; sparse solution; lambda by CV"),
53
+ "ENET" = list(label = "Elastic Net (L1+L2)", desc = "Elastic net penalty; handles correlated markers; alpha=0.5"),
54
+ "RF" = list(label = "Random Forest QTL", desc = "Non-parametric; captures non-linear effects; variable importance")
55
  )
56
 
57
  # ============================================================
 
98
 
99
  cat("LOADED:", nrow(gd), "samples,", ncol(gd), "markers,",
100
  length(unique(marker_info$Chromosome)), "chromosomes\n")
 
101
 
102
  list(geno = gd, marker_info = marker_info,
103
  n_samples = nrow(gd), n_markers = ncol(gd),
 
105
  }
106
 
107
  # ============================================================
108
+ # QTL SCAN โ€” dispatcher with all 6 models
109
  # ============================================================
110
  qtl_scan <- function(genotype_matrix, phenotype_vector, marker_info,
111
  method = "CIM", n_cofactors = 10, window_size = 10) {
 
120
  cat("Markers after NZV removal:", ncol(X_valid), "\n")
121
 
122
  if (method == "LASSO") return(qtl_scan_lasso(X_valid, y_valid, marker_info))
123
+ if (method == "ENET") return(qtl_scan_enet(X_valid, y_valid, marker_info))
124
+ if (method == "RF") return(qtl_scan_rf(X_valid, y_valid, marker_info))
125
  if (method == "MQM") return(qtl_scan_mqm(X_valid, y_valid, marker_info))
126
 
127
  # SIM / CIM per-marker scan
 
266
  "Dominance_Ratio","Dominance_Class","N_Cofactors","N_Samples","Method")]
267
  }
268
 
269
+ # ============================================================
270
+ # Elastic Net QTL
271
+ # ============================================================
272
+ qtl_scan_enet <- function(X, y, marker_info) {
273
+ valid <- !is.na(y) & apply(X, 1, function(r) !any(is.na(r)))
274
+ X_v <- X[valid,,drop=FALSE]; y_v <- y[valid]
275
+ cv <- tryCatch(cv.glmnet(as.matrix(X_v), y_v, alpha=0.5, nfolds=5), error=function(e) NULL)
276
+ if (is.null(cv)) return(data.frame(Message="Elastic Net failed"))
277
+
278
+ coefs <- coef(cv, s=cv$lambda.1se)[-1]
279
+ coef_df <- data.frame(Marker=rownames(coef(cv,s=cv$lambda.1se))[-1], Effect=as.numeric(coefs))
280
+ coef_df <- coef_df[abs(coef_df$Effect) > 0, ]
281
+ if (nrow(coef_df)==0) return(data.frame(Message="No non-zero effects"))
282
+
283
+ coef_df <- merge(coef_df, marker_info, by="Marker", all.x=TRUE)
284
+ coef_df <- coef_df[!is.na(coef_df$Position), ]
285
+ max_eff <- max(abs(coef_df$Effect))
286
+ coef_df$LOD <- abs(coef_df$Effect) / max_eff * 10
287
+
288
+ r2_vec <- sapply(coef_df$Marker, function(m) {
289
+ g <- X_v[,m]; v <- !is.na(g)
290
+ if (sum(v)<5) return(NA)
291
+ summary(lm(y_v[v] ~ g[v]))$r.squared * 100
292
+ })
293
+ coef_df$PVE_Marker_Percent <- r2_vec
294
+ coef_df$PVE_CIM_Percent <- r2_vec
295
+ coef_df$Additive_Effect <- coef_df$Effect
296
+ coef_df$P_Value <- 10^(-coef_df$LOD)
297
+ coef_df$SE_Additive <- NA; coef_df$CI_Lower <- NA; coef_df$CI_Upper <- NA
298
+ coef_df$Dominance_Effect <- NA; coef_df$Dominance_Ratio <- NA
299
+ coef_df$Dominance_Class <- "Additive"
300
+ coef_df$N_Cofactors <- 0
301
+ coef_df$N_Samples <- sum(valid)
302
+ coef_df$Method <- "ENET"
303
+ coef_df <- coef_df[order(coef_df$Chromosome, coef_df$Position), ]
304
+ coef_df[, c("Marker","Chromosome","Position","LOD","P_Value",
305
+ "PVE_Marker_Percent","PVE_CIM_Percent","Additive_Effect",
306
+ "SE_Additive","CI_Lower","CI_Upper","Dominance_Effect",
307
+ "Dominance_Ratio","Dominance_Class","N_Cofactors","N_Samples","Method")]
308
+ }
309
+
310
+ # ============================================================
311
+ # Random Forest QTL
312
+ # ============================================================
313
+ qtl_scan_rf <- function(X, y, marker_info) {
314
+ valid <- !is.na(y) & apply(X, 1, function(r) !any(is.na(r)))
315
+ X_v <- X[valid,,drop=FALSE]; y_v <- y[valid]
316
+
317
+ rf_fit <- tryCatch(
318
+ randomForest(x = X_v, y = y_v, ntree = 500, importance = TRUE),
319
+ error = function(e) NULL)
320
+ if (is.null(rf_fit)) return(data.frame(Message="Random Forest failed"))
321
+
322
+ imp <- importance(rf_fit, type = 1)[, 1]
323
+ imp_df <- data.frame(Marker = names(imp), Importance = imp)
324
+ imp_df <- imp_df[imp_df$Importance > 0, ]
325
+ if (nrow(imp_df) == 0) return(data.frame(Message="No important markers"))
326
+
327
+ imp_df <- merge(imp_df, marker_info, by = "Marker", all.x = TRUE)
328
+ imp_df <- imp_df[!is.na(imp_df$Position), ]
329
+
330
+ max_imp <- max(imp_df$Importance)
331
+ imp_df$LOD <- imp_df$Importance / max_imp * 10
332
+
333
+ r2_vec <- sapply(imp_df$Marker, function(m) {
334
+ g <- X_v[,m]; v <- !is.na(g)
335
+ if (sum(v) < 5) return(NA)
336
+ summary(lm(y_v[v] ~ g[v]))$r.squared * 100
337
+ })
338
+
339
+ imp_df$PVE_Marker_Percent <- r2_vec
340
+ imp_df$PVE_CIM_Percent <- r2_vec
341
+ imp_df$Additive_Effect <- NA
342
+ imp_df$P_Value <- 10^(-imp_df$LOD)
343
+ imp_df$SE_Additive <- NA
344
+ imp_df$CI_Lower <- NA
345
+ imp_df$CI_Upper <- NA
346
+ imp_df$Dominance_Effect <- NA
347
+ imp_df$Dominance_Ratio <- NA
348
+ imp_df$Dominance_Class <- "Additive"
349
+ imp_df$N_Cofactors <- 0
350
+ imp_df$N_Samples <- sum(valid)
351
+ imp_df$Method <- "RF"
352
+
353
+ imp_df <- imp_df[order(imp_df$Chromosome, imp_df$Position), ]
354
+ imp_df[, c("Marker","Chromosome","Position","LOD","P_Value",
355
+ "PVE_Marker_Percent","PVE_CIM_Percent","Additive_Effect",
356
+ "SE_Additive","CI_Lower","CI_Upper","Dominance_Effect",
357
+ "Dominance_Ratio","Dominance_Class","N_Cofactors","N_Samples","Method")]
358
+ }
359
+
360
  # ============================================================
361
  # MQM โ€” forward stepwise
362
  # ============================================================
 
462
  }
463
 
464
  # ============================================================
465
+ # BEAUTIFUL CHROMOSOME IDIOGRAM PLOT (Pastel Theme)
466
  # ============================================================
467
  make_chromosome_idiogram <- function(qtl_list, all_markers_df,
468
  lod_threshold=2.0, trait_colors=NULL) {
469
  if (is.null(all_markers_df)||nrow(all_markers_df)==0) return(NULL)
470
+
471
+ # Use pastel colors for traits
472
+ default_colors <- PASTEL_COLORS
473
  trait_names <- names(qtl_list)
474
  if (is.null(trait_colors))
475
  trait_colors <- setNames(default_colors[seq_along(trait_names)], trait_names)
476
  shapes <- c(16,17,18,15,3,4,8,9)
477
 
478
  chroms <- sort(unique(as.character(all_markers_df$Chromosome)))
479
+ x_gap <- 1.2
480
+ bar_height <- 0.35
481
+
482
+ # Set up plot with pastel background
483
+ par(mar=c(4,3,3,1), bg="#FDFBF7", family="sans")
484
  plot(0,0,type="n",
485
  xlim=c(0,length(chroms)*x_gap+0.5),
486
+ ylim=c(-2,max(all_markers_df$Position,na.rm=TRUE)*1.08),
487
+ xaxt="n",yaxt="n",xlab="",ylab="",main="",frame.plot=FALSE)
488
+
489
  max_pos <- max(all_markers_df$Position,na.rm=TRUE)
490
  axis(2,at=pretty(c(0,max_pos),n=6),labels=pretty(c(0,max_pos),n=6),
491
+ cex.axis=0.75,col="#C9B99A",col.axis="#7B6E4A",las=1,line=-0.5)
492
+ mtext("Genetic Position (cM)",side=2,line=2,cex=0.8,col="#7B6E4A",font=2)
493
 
494
  for (ci in seq_along(chroms)) {
495
  chr <- chroms[ci]; x_cen <- (ci-1)*x_gap+0.7
 
499
  chr_min <- min(chr_mk$Position,na.rm=TRUE)
500
  cap_h <- chr_len*0.02
501
 
502
+ # Chromosome bar with pastel gradient
503
+ rect(x_cen-bar_height*0.6,chr_min,x_cen+bar_height*0.6,chr_len,
504
+ col="#E8E0D0",border="#C9B99A",lwd=1.5)
505
+ rect(x_cen-bar_height*0.6,chr_min-cap_h,x_cen+bar_height*0.6,chr_min,
506
+ col="#D5CCB8",border="#C9B99A",lwd=1)
507
+ rect(x_cen-bar_height*0.6,chr_len,x_cen+bar_height*0.6,chr_len+cap_h,
508
+ col="#D5CCB8",border="#C9B99A",lwd=1)
509
+
510
+ # Centromere
511
  cen_pos <- chr_min+(chr_len-chr_min)*0.4
512
+ rect(x_cen-bar_height*0.6,cen_pos-chr_len*0.04,
513
+ x_cen+bar_height*0.6,cen_pos+chr_len*0.04,
514
+ col="#B8A88A",border="#A89878",lwd=0.8)
515
+
516
+ # Marker tick marks
517
  for (mk_pos in chr_mk$Position)
518
+ segments(x_cen-bar_height*0.55,mk_pos,x_cen+bar_height*0.55,mk_pos,
519
+ col="#D5CCB8",lwd=0.5)
520
 
521
+ # Plot QTLs for each method
522
  for (ti in seq_along(trait_names)) {
523
  tr <- trait_names[ti]; qdf <- qtl_list[[tr]]
524
  if (is.null(qdf)||"Message"%in%colnames(qdf)) next
525
  sig <- qdf[as.character(qdf$Chromosome)==chr&!is.na(qdf$LOD)&qdf$LOD>=lod_threshold,]
526
  if (nrow(sig)==0) next
527
+ col_ti <- trait_colors[[tr]]
528
+ pch_ti <- shapes[((ti-1)%%length(shapes))+1]
529
  x_off <- if(ti%%2==1) x_cen+bar_height*0.75 else x_cen-bar_height*0.75
530
  for (ri in 1:nrow(sig)) {
531
  pos <- sig$Position[ri]
532
  segments(if(ti%%2==1) x_cen+bar_height*0.6 else x_cen-bar_height*0.6,
533
+ pos,x_off,pos,col=adjustcolor(col_ti,alpha.f=0.6),lwd=1.2,lty=2)
534
  points(x_off,pos,pch=pch_ti,col=col_ti,bg=col_ti,
535
+ cex=pmax(0.8,pmin(2.2,0.6+sig$LOD[ri]/4)))
536
  if (sig$LOD[ri]>=lod_threshold*1.5)
537
+ text(x_off+ifelse(ti%%2==1,0.15,-0.15),pos,
538
+ round(sig$LOD[ri],1),cex=0.55,col=col_ti,font=2)
539
  }
540
  }
541
+ # Chromosome label
542
+ text(x_cen,chr_len+cap_h+chr_len*0.05,paste0("Chr ",chr),
543
+ cex=0.75,font=2,col="#5D4E30")
544
  }
545
+
546
+ # Legend
547
+ if (length(trait_names)>0) {
548
+ legend("topright", inset=c(0.02,0.02),
549
  legend=paste0(trait_names," (",sapply(trait_names,function(tr){
550
  qdf <- qtl_list[[tr]]
551
  if(is.null(qdf)||"Message"%in%colnames(qdf)) return("0")
552
  sum(!is.na(qdf$LOD)&qdf$LOD>=lod_threshold,na.rm=TRUE)
553
  })," QTL)"),
554
  col=unname(trait_colors[trait_names]),pch=shapes[seq_along(trait_names)],
555
+ pt.cex=1.2,cex=0.75,bg="#FDFBF7",box.col="#D5CCB8",
556
+ title="Models",title.col="#5D4E30",text.col="#5D4E30")
557
+ }
558
+ title(main=paste0("๐ŸŽฏ QTL Chromosome Map โ€” LOD โ‰ฅ ",lod_threshold),
559
+ cex.main=0.95,font.main=1,col.main="#5D4E30",line=1)
560
  }
561
 
562
  # ============================================================
563
+ # BEAUTIFUL PLOTLY MANHATTAN (Pastel Theme)
564
  # ============================================================
565
  make_plotly_manhattan <- function(scan_all, lod_threshold=2.0, title="QTL Manhattan Plot") {
566
+ blank <- plot_ly()%>%layout(title=title,plot_bgcolor="#FDFBF7",paper_bgcolor="#FDFBF7")
567
  if (is.null(scan_all)||"Message"%in%colnames(scan_all)) return(blank)
568
  pd <- scan_all[!is.na(scan_all$LOD)&!is.na(scan_all$Position)&!is.na(scan_all$Chromosome),]
569
  if (nrow(pd)==0) return(blank)
 
577
  pd$cum_pos <- pd$Position+offsets[pd$Chromosome]
578
  pd$sig <- pd$LOD>=lod_threshold
579
  chr_mids <- tapply(pd$cum_pos,pd$Chromosome,median,na.rm=TRUE)
580
+
581
+ # Pastel colors for chromosomes
582
+ chr_colors <- rep(c("#A8E6CF", "#DCEDC1", "#FFD3B6", "#FFAAA5", "#FF8B94",
583
+ "#B5EAD7", "#C7CEEA", "#E2F0CB", "#FFDAC1", "#E6C8A0"),
584
+ ceiling(length(chroms)/10))[seq_along(chroms)]
585
  names(chr_colors) <- chroms
586
 
587
  p <- plot_ly()
588
  for (ch in chroms) {
589
  sub <- pd[pd$Chromosome==ch,]
590
  p <- p%>%add_trace(data=sub,x=~cum_pos,y=~LOD,type="scatter",mode="markers",
591
+ name=paste("Chr",ch),marker=list(size=6,color=chr_colors[ch],opacity=0.7,
592
+ line=list(width=0.5,color="#FFFFFF")),
593
+ text=~paste0("<b>",Marker,"</b><br>๐Ÿ“Š Chr: ",Chromosome,"<br>๐Ÿ“ Pos: ",round(Position,1),
594
+ " cM<br>๐Ÿ“ˆ LOD: ",round(LOD,2),"<br>๐ŸŽฏ PVE: ",round(PVE_Marker_Percent,1),"%",
595
+ "<br>โšก Additive: ",round(Additive_Effect,3)),
596
  hoverinfo="text",showlegend=FALSE)
597
  }
598
  sig_pd <- pd[pd$sig,]
599
  if (nrow(sig_pd)>0)
600
  p <- p%>%add_trace(data=sig_pd,x=~cum_pos,y=~LOD,type="scatter",mode="markers",
601
+ name="Significant",marker=list(size=11,color="#E15759",symbol="diamond",
602
+ line=list(width=1,color="#FFFFFF")),
603
+ text=~paste0("<b>๐Ÿ”ฅ ",Marker," ๐Ÿ”ฅ</b><br>๐Ÿ“Š Chr: ",Chromosome,"<br>๐Ÿ“ Pos: ",round(Position,1),
604
+ " cM<br>๐Ÿ“ˆ LOD: ",round(LOD,2),"<br>๐ŸŽฏ PVE: ",round(PVE_Marker_Percent,1),"%"),
605
  hoverinfo="text")
606
  p%>%add_segments(x=min(pd$cum_pos,na.rm=TRUE),xend=max(pd$cum_pos,na.rm=TRUE),
607
  y=lod_threshold,yend=lod_threshold,
608
+ line=list(color="#E15759",dash="dash",width=1.5),showlegend=FALSE)%>%
609
+ layout(title=list(text=paste0("๐Ÿงฌ ",title," | โœจ ",sum(pd$sig,na.rm=TRUE)," significant QTLs"),
610
+ font=list(size=15,color="#5D4E30",family="sans")),
611
  xaxis=list(title="Chromosome",tickvals=as.list(chr_mids[chroms]),
612
+ ticktext=as.list(paste0("Chr ",chroms)),tickangle=45,
613
+ gridcolor="#F0EBE0",color="#8B7A5A",zeroline=FALSE),
614
+ yaxis=list(title="LOD Score",gridcolor="#F0EBE0",color="#8B7A5A",zeroline=FALSE),
615
+ plot_bgcolor="#FDFBF7",paper_bgcolor="#FDFBF7",font=list(color="#5D4E30",family="sans"),
616
+ legend=list(orientation="h",y=-0.12,font=list(size=10)),
617
+ hoverlabel=list(bgcolor="#FFFFFF",font=list(color="#5D4E30",size=11)))
618
  }
619
 
620
  # ============================================================
621
+ # COMMON QTL HELPER
622
  # ============================================================
623
  find_common_qtl <- function(compare_res, lod_threshold, min_models=2, window_cM=5) {
 
624
  sig_list <- list()
625
  for (mth in names(compare_res)) {
626
  r <- compare_res[[mth]]
 
635
  all_sig <- do.call(rbind, sig_list)
636
  all_sig$Chromosome <- as.character(all_sig$Chromosome)
637
 
 
 
638
  marker_counts <- table(all_sig$Marker)
639
  all_sig$N_Models_Detected <- as.integer(marker_counts[all_sig$Marker])
640
 
 
641
  common <- all_sig[all_sig$N_Models_Detected >= min_models, ]
642
  if (nrow(common)==0) return(NULL)
643
 
 
644
  markers_uniq <- unique(common$Marker)
645
  summary_rows <- lapply(markers_uniq, function(mk) {
646
  rows <- common[common$Marker==mk, ]
 
650
  base$Max_LOD <- round(max(rows$LOD, na.rm=TRUE), 3)
651
  base$Mean_PVE <- round(mean(rows$PVE_Marker_Percent, na.rm=TRUE), 3)
652
  base$Mean_Add_Eff <- round(mean(rows$Additive_Effect, na.rm=TRUE), 3)
 
653
  for (mth in names(compare_res)) {
654
  r_mth <- rows[rows$Model==mth, ]
655
  base[[paste0("LOD_",mth)]] <- if(nrow(r_mth)>0) round(r_mth$LOD[1],3) else NA
 
667
  shinyjs::useShinyjs(),
668
  tags$head(
669
  tags$link(rel="stylesheet",
670
+ href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap"),
 
 
671
  tags$style(HTML("
672
  :root{
673
+ --bg:#FDFBF7;--card:#FFFFFF;--border:#EBE5D9;
674
+ --txt:#4A3B28;--muted:#8B7A5A;--accent:#7BA07A;
675
+ --green:#6B9E6B;--red:#D98A7A;--orange:#D9A87A;
676
+ --purple:#9B8BB0;--teal:#7AA89B;
677
  }
678
  *{box-sizing:border-box;}
679
+ body{
680
+ font-family:'Inter',sans-serif;
681
+ background:var(--bg);
682
+ color:var(--txt);
683
+ font-size:14px;
684
+ margin:0;
685
+ }
686
+ .navbar{
687
+ background:#FFFFFF!important;
688
+ border-bottom:2px solid var(--accent)!important;
689
+ box-shadow:0 2px 8px rgba(0,0,0,0.03);
690
+ }
691
+ .navbar-brand{
692
+ font-weight:600;
693
+ color:var(--accent)!important;
694
+ font-size:18px;
695
+ }
696
+ .navbar-nav>li>a{
697
+ color:var(--muted)!important;
698
+ font-size:13px;
699
+ font-weight:500;
700
+ }
701
+ .navbar-nav>li.active>a{
702
+ color:var(--accent)!important;
703
+ background:transparent!important;
704
+ border-bottom:2px solid var(--accent);
705
+ }
706
+ .card{
707
+ background:var(--card);
708
+ border:1px solid var(--border);
709
+ border-radius:12px;
710
+ margin-bottom:20px;
711
+ box-shadow:0 2px 6px rgba(0,0,0,0.03);
712
+ overflow:hidden;
713
+ }
714
+ .card-hd{
715
+ background:#F8F6F2;
716
+ border-bottom:1px solid var(--border);
717
+ padding:12px 16px;
718
+ font-size:12px;
719
+ color:var(--muted);
720
+ letter-spacing:.5px;
721
+ text-transform:uppercase;
722
+ font-weight:600;
723
+ }
724
+ .card-bd{
725
+ padding:16px;
726
+ }
727
+ .info-box{
728
+ background:#F2F6EF;
729
+ border:1px solid #D4E2D0;
730
+ border-left:3px solid var(--accent);
731
+ border-radius:8px;
732
+ padding:12px 16px;
733
+ margin:8px 0;
734
+ font-size:13px;
735
+ color:#5A7A4A;
736
+ }
737
+ .warn-box{
738
+ background:#FFF8F0;
739
+ border:1px solid #F5E6D0;
740
+ border-left:3px solid var(--orange);
741
+ border-radius:8px;
742
+ padding:12px 16px;
743
+ margin:8px 0;
744
+ font-size:13px;
745
+ color:#A87A4A;
746
+ }
747
+ .good-box{
748
+ background:#F0F6F0;
749
+ border:1px solid #D4E2D0;
750
+ border-left:3px solid var(--green);
751
+ border-radius:8px;
752
+ padding:12px 16px;
753
+ margin:8px 0;
754
+ font-size:13px;
755
+ color:#4A7A4A;
756
+ }
757
+ .btn{
758
+ border-radius:8px;
759
+ font-size:13px;
760
+ font-weight:500;
761
+ padding:8px 16px;
762
+ transition:all 0.2s ease;
763
+ }
764
+ .btn-primary{
765
+ background:var(--accent);
766
+ border-color:var(--accent);
767
+ color:#FFF;
768
+ }
769
+ .btn-primary:hover{
770
+ background:#5A8A5A;
771
+ border-color:#5A8A5A;
772
+ transform:translateY(-1px);
773
+ }
774
+ .btn-success{
775
+ background:var(--green);
776
+ border-color:var(--green);
777
+ color:#FFF;
778
+ }
779
+ .btn-success:hover{
780
+ background:#5A8A5A;
781
+ transform:translateY(-1px);
782
+ }
783
+ .btn-info{
784
+ background:var(--teal);
785
+ border-color:var(--teal);
786
+ color:#FFF;
787
+ }
788
+ .btn-info:hover{
789
+ background:#5A8A7A;
790
+ transform:translateY(-1px);
791
+ }
792
+ .btn-outline{
793
+ background:transparent;
794
+ border-color:var(--accent);
795
+ color:var(--accent);
796
+ }
797
+ .btn-outline:hover{
798
+ background:var(--accent);
799
+ color:#FFF;
800
+ }
801
+ .form-control,.selectize-input{
802
+ background:#FFF!important;
803
+ border:1px solid var(--border)!important;
804
+ color:var(--txt)!important;
805
+ font-size:13px;
806
+ border-radius:8px;
807
+ }
808
+ label{
809
+ font-size:12px;
810
+ color:var(--muted);
811
+ font-weight:500;
812
+ }
813
+ .model-badge{
814
+ display:inline-block;
815
+ background:#F2F6EF;
816
+ border:1px solid #D4E2D0;
817
+ border-radius:20px;
818
+ padding:4px 12px;
819
+ font-size:11px;
820
+ font-weight:600;
821
+ color:var(--accent);
822
+ margin-right:8px;
823
+ }
824
+ .common-badge{
825
+ display:inline-block;
826
+ background:#F0F6F0;
827
+ border:1px solid #D4E2D0;
828
+ border-radius:20px;
829
+ padding:4px 12px;
830
+ font-size:11px;
831
+ font-weight:600;
832
+ color:var(--green);
833
+ margin-right:8px;
834
+ }
835
+ table.dataTable{
836
+ background:#FFF!important;
837
+ border-radius:8px;
838
+ overflow:hidden;
839
+ }
840
+ table.dataTable thead th{
841
+ background:#F8F6F2!important;
842
+ font-weight:600;
843
+ font-size:12px;
844
+ color:var(--muted);
845
+ }
846
+ table.dataTable tbody tr:hover{
847
+ background:#F8F6F2!important;
848
+ }
849
+ .stat-value{
850
+ font-size:24px;
851
+ font-weight:700;
852
+ color:var(--accent);
853
+ }
854
+ .stat-label{
855
+ font-size:11px;
856
+ color:var(--muted);
857
+ text-transform:uppercase;
858
+ letter-spacing:1px;
859
+ }
860
  "))
861
  ),
862
 
863
  navbarPage(
864
+ title = tags$span(tags$i(class="fas fa-leaf",style="color:#7BA07A;margin-right:8px;"), "QTL-Mapper v6"),
865
  id = "nav",
866
 
867
  # โ”€โ”€ DATA UPLOAD โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
868
+ tabPanel("๐Ÿ“ Data Upload", icon=icon("upload"),
869
  fluidRow(column(12,
870
  div(class="info-box",
871
+ tags$i(class="fas fa-info-circle", style="margin-right:8px;"),
872
+ tags$b("QTL-Mapper v6 โ€” Multi-Model QTL Analysis"),
873
  tags$br(),
874
+ "Format: Row1=header (id,marker1,...), Row2=chromosomes, Row3=positions (cM), rows4+=samples. Genotypes coded 0/1/2 (homozygous/heterozygous/other homozygous)."
875
  )
876
  )),
877
  fluidRow(
878
  column(4,
879
  div(class="card",
880
+ div(class="card-hd",tags$i(class="fas fa-dna",style="margin-right:6px;"),"Training Data"),
881
  div(class="card-bd",
882
+ fileInput("geno_file","๐Ÿ“Š Genotype CSV",accept=".csv",buttonLabel="Browse",placeholder="No file selected"),
883
+ fileInput("pheno_file","๐Ÿ“ˆ Phenotype CSV",accept=".csv",buttonLabel="Browse",placeholder="No file selected"),
884
  selectInput("pheno_col","Select Trait/Phenotype",choices=NULL),
885
+ tags$hr(style="margin:12px 0;border-color:#EBE5D9;"),
886
+ fileInput("test_geno_file","๐Ÿงช Test Genotype CSV (optional)",accept=".csv"),
887
+ fileInput("pop_file","๐Ÿ‘ฅ Population Metadata CSV (optional)",accept=".csv"),
888
  helpText("Pop CSV: columns 'id' and 'population'")
889
  )
890
  )
891
  ),
892
  column(4,
893
  div(class="card",
894
+ div(class="card-hd",tags$i(class="fas fa-sliders-h",style="margin-right:6px;"),"Mapping Parameters"),
895
  div(class="card-bd",
896
+ selectInput("mapping_method","๐ŸŽฏ Mapping Method",
897
  choices=setNames(names(MAPPING_MODELS), sapply(MAPPING_MODELS,`[[`,"label")),
898
  selected="CIM"),
899
  uiOutput("method_desc_ui"),
900
+ sliderInput("lod_threshold","๐Ÿ“Š LOD Threshold",min=0.5,max=10,value=2.0,step=0.1),
901
+ sliderInput("val_prop","๐ŸŽฒ Validation Proportion",min=0.1,max=0.4,value=0.2,step=0.05),
902
  conditionalPanel("input.mapping_method == 'CIM' || input.mapping_method == 'MQM'",
903
+ numericInput("n_cofactors","๐Ÿ”ง Max Cofactors (K)",value=10,min=1,max=30,step=1),
904
+ numericInput("window_size","๐Ÿšซ Exclusion Window (ยฑmarkers)",value=10,min=1,max=30,step=1)
905
  ),
906
+ numericInput("lod_drop","๐Ÿ“ LOD Drop for Interval",value=1.5,min=0.5,max=3.0,step=0.5),
907
+ actionButton("run_btn","โ–ถ Run QTL Analysis",class="btn btn-primary btn-block",
908
+ style="margin-top:12px;width:100%;")
909
  )
910
  )
911
  ),
912
  column(4,
913
  div(class="card",
914
+ div(class="card-hd",tags$i(class="fas fa-chart-pie",style="margin-right:6px;"),"Dataset Summary"),
915
  div(class="card-bd", uiOutput("dataset_info_ui"))
916
  ),
917
  div(class="card",
918
+ div(class="card-hd",tags$i(class="fas fa-chart-line",style="margin-right:6px;"),"Predict Test Phenotypes"),
919
  div(class="card-bd",
920
+ actionButton("pred_btn","๐Ÿ”ฎ Predict Test Samples",class="btn btn-info btn-block"),
921
+ tags$br(),
922
+ downloadButton("dl_pred","๐Ÿ’พ Download Predictions (.xlsx)",class="btn btn-success btn-block")
 
923
  )
924
  )
925
  )
926
  ),
927
  fluidRow(column(12,
928
  div(class="card",
929
+ div(class="card-hd","๐Ÿ“‹ Data Preview"),
930
  div(class="card-bd",
931
  tabsetPanel(
932
  tabPanel("Training Genotype", DTOutput("prev_geno")),
 
940
  ),
941
 
942
  # โ”€โ”€ RESULTS โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
943
+ tabPanel("๐Ÿ“Š Results", icon=icon("chart-line"),
944
+ fluidRow(
945
+ column(12,
946
+ div(style="display:flex;gap:12px;flex-wrap:wrap;margin-bottom:16px;",
947
+ downloadButton("dl_manhattan","๐Ÿ“ธ Manhattan Plot",class="btn btn-primary"),
948
+ downloadButton("dl_idiogram","๐Ÿ—บ๏ธ Chromosome Map",class="btn btn-info"),
949
+ downloadButton("dl_results","๐Ÿ“ฅ Full Results (.xlsx)",class="btn btn-success")
950
+ )
951
  )
952
+ ),
953
  fluidRow(
954
  column(7,
955
  div(class="card",
956
+ div(class="card-hd","๐Ÿงฌ Manhattan Plot โ€” LOD Scores Across Genome"),
957
+ div(class="card-bd",plotlyOutput("manhattan_plot",height="500px"))
958
  )
959
  ),
960
  column(5,
961
  div(class="card",
962
+ div(class="card-hd","๐Ÿ—บ๏ธ Chromosome Idiogram โ€” QTL Positions"),
963
+ div(class="card-bd",plotOutput("idiogram_plot",height="500px"))
964
  )
965
  )
966
  ),
967
  fluidRow(
968
  column(4,
969
+ div(class="card",
970
+ div(class="card-hd","๐Ÿ“Š Model Performance Metrics"),
971
+ div(class="card-bd",plotlyOutput("perf_plot",height="280px"))
972
+ )
973
  ),
974
  column(4,
975
+ div(class="card",
976
+ div(class="card-hd","๐ŸŽฏ Training: Predicted vs Observed"),
977
+ div(class="card-bd",plotlyOutput("reg_train",height="280px"))
978
+ )
979
  ),
980
  column(4,
981
+ div(class="card",
982
+ div(class="card-hd","โœ… Validation: Predicted vs Observed"),
983
+ div(class="card-bd",plotlyOutput("reg_val",height="280px"))
984
+ )
985
  )
986
  ),
987
  fluidRow(column(12,
988
  div(class="card",
989
+ div(class="card-hd","๐Ÿ”ฅ Significant QTLs โ€” Above LOD Threshold"),
990
  div(class="card-bd",DTOutput("qtl_table"))
991
  )
992
  )),
993
  fluidRow(column(12,
994
  div(class="card",
995
+ div(class="card-hd","๐Ÿ“ˆ Full Genome Scan Results (All Markers)"),
996
  div(class="card-bd",DTOutput("full_scan_table"))
997
  )
998
  ))
999
  ),
1000
 
1001
  # โ”€โ”€ COMPARE MODELS โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
1002
+ tabPanel("โš–๏ธ Compare Models", icon=icon("balance-scale"),
1003
  fluidRow(column(12,
1004
  div(class="card",
1005
+ div(class="card-hd","๐Ÿ”„ Multi-Model Comparison"),
1006
  div(class="card-bd",
1007
+ div(class="warn-box",
1008
+ tags$i(class="fas fa-info-circle",style="margin-right:6px;"),
1009
+ "Select models to compare. Each will run a full genome scan. Results will be displayed across tabs."
1010
+ ),
1011
  checkboxGroupInput("compare_methods","Methods to Compare:",
1012
  choices=setNames(names(MAPPING_MODELS),sapply(MAPPING_MODELS,`[[`,"label")),
1013
+ selected=c("SIM","CIM","LASSO"),inline=TRUE),
1014
+ actionButton("run_compare","๐Ÿš€ Run All Selected Models",class="btn btn-primary"),
1015
  tags$br(),tags$br(),
1016
  uiOutput("compare_status_ui")
1017
  )
 
1020
  fluidRow(
1021
  column(6,
1022
  div(class="card",
1023
+ div(class="card-hd","๐Ÿ—บ๏ธ Multi-Model Chromosome Map"),
1024
+ div(class="card-bd",plotOutput("compare_idiogram",height="520px"))
1025
  )
1026
  ),
1027
  column(6,
1028
  div(class="card",
1029
+ div(class="card-hd","๐Ÿ“Š QTL Count by Method & Chromosome"),
1030
+ div(class="card-bd",plotlyOutput("compare_bar",height="520px"))
1031
  )
1032
  )
1033
  ),
1034
  fluidRow(column(12,
1035
  div(class="card",
1036
+ div(class="card-hd","๐Ÿ“‹ All Significant QTLs โ€” All Models"),
1037
  div(class="card-bd",DTOutput("compare_table"))
1038
  )
1039
  ))
1040
  ),
1041
 
1042
  # โ”€โ”€ COMMON QTL โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
1043
+ tabPanel("๐ŸŽฏ Common QTL", icon=icon("bullseye"),
1044
  fluidRow(column(12,
1045
  div(class="card",
1046
  div(class="card-hd",
1047
+ tags$i(class="fas fa-bullseye",style="margin-right:6px;color:#6B9E6B;"),
1048
  "Common QTL โ€” Markers Detected Across Multiple Models"),
1049
  div(class="card-bd",
1050
  fluidRow(
1051
  column(4,
1052
+ sliderInput("min_models","๐ŸŽฒ Minimum Models Agreeing",
1053
+ min=2, max=6, value=2, step=1)
1054
  ),
1055
  column(4,
1056
+ div(style="margin-top:28px;",
1057
+ downloadButton("dl_common_qtl","๐Ÿ’พ Download Common QTL (.xlsx)",
1058
  class="btn btn-success btn-block")
1059
  )
1060
  ),
 
1070
  fluidRow(
1071
  column(6,
1072
  div(class="card",
1073
+ div(class="card-hd","๐Ÿ—บ๏ธ Common QTL โ€” Chromosome Map"),
1074
+ div(class="card-bd",plotOutput("common_idiogram",height="500px"))
1075
  )
1076
  ),
1077
  column(6,
1078
  div(class="card",
1079
+ div(class="card-hd","๐Ÿ“Š Model Agreement by Chromosome"),
1080
+ div(class="card-bd",plotlyOutput("common_bar",height="500px"))
1081
  )
1082
  )
1083
  ),
1084
  fluidRow(column(12,
1085
  div(class="card",
1086
+ div(class="card-hd","๐Ÿ“‹ Common QTL Details"),
1087
  div(class="card-bd",
1088
  div(class="good-box",
1089
+ tags$i(class="fas fa-star",style="margin-right:6px;"),
1090
+ "Markers shown here are significant in at least the number of models selected above.",
1091
  tags$br(),
1092
+ "๐Ÿ‘‰ Run the Compare Models tab first to populate this table."
1093
  ),
1094
  tags$br(),
1095
  DTOutput("common_qtl_table")
 
1099
  ),
1100
 
1101
  # โ”€โ”€ DOMESTICATION โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
1102
+ tabPanel("๐ŸŒพ Domestication", icon=icon("leaf"),
1103
  fluidRow(
1104
  column(4,
1105
  div(class="card",
1106
+ div(class="card-hd","โš™๏ธ Selection Parameters"),
1107
  div(class="card-bd",
1108
+ numericInput("fst_thr","๐Ÿ“Š Fst Threshold",value=0.1,min=0.05,max=0.5,step=0.01),
1109
+ numericInput("tajima_thr","๐Ÿ“‰ Tajima's D Threshold",value=-1,min=-5,max=0,step=0.1),
1110
+ actionButton("run_dom","๐ŸŒฟ Run Domestication Analysis",class="btn btn-primary btn-block")
1111
  )
1112
  )
1113
  ),
1114
  column(8,
1115
  div(class="card",
1116
+ div(class="card-hd","๐Ÿ‘ฅ Population Data"),
1117
  div(class="card-bd",DTOutput("prev_pop"))
1118
  )
1119
  )
1120
  ),
1121
  fluidRow(
1122
+ column(6,
1123
+ div(class="card",
1124
+ div(class="card-hd","๐Ÿงฌ Fst Manhattan Plot"),
1125
+ div(class="card-bd",plotlyOutput("fst_plot",height="400px"))
1126
+ )
1127
+ ),
1128
+ column(6,
1129
+ div(class="card",
1130
+ div(class="card-hd","๐Ÿ“‰ Tajima's D Manhattan Plot"),
1131
+ div(class="card-bd",plotlyOutput("tajima_plot",height="400px"))
1132
+ )
1133
+ )
1134
  ),
1135
  fluidRow(column(12,
1136
  div(class="card",
1137
+ div(class="card-hd","๐Ÿ” Selection Signatures"),
1138
+ div(class="card-bd",
1139
+ DTOutput("sel_table"),
1140
+ tags$br(),
1141
+ downloadButton("dl_sel","๐Ÿ’พ Download Selection Results (.xlsx)",class="btn btn-success")
1142
+ )
1143
  )
1144
  ))
1145
  ),
1146
 
1147
  # โ”€โ”€ ABOUT โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
1148
+ tabPanel("โ„น๏ธ About", icon=icon("info-circle"),
1149
+ fluidRow(column(10,offset=1,
1150
  div(class="card",
1151
  div(class="card-bd",
1152
+ tags$h4(style="color:#7BA07A;margin-bottom:16px;","๐Ÿงฌ QTL-Mapper v6 โ€” Comprehensive QTL Analysis Platform"),
1153
+ div(class="info-box",
1154
+ tags$b("โœจ Key Features:"), tags$br(),
1155
+ "โ€ข 6 Mapping Models: SIM, CIM, MQM, LASSO, Elastic Net, Random Forest", tags$br(),
1156
+ "โ€ข Interactive Manhattan plots with hover information", tags$br(),
1157
+ "โ€ข Chromosome idiogram visualization", tags$br(),
1158
+ "โ€ข Multi-model comparison and common QTL detection", tags$br(),
1159
+ "โ€ข Domestication selection signature analysis (Fst, Tajima's D)", tags$br(),
1160
+ "โ€ข Test population prediction", tags$br(),
1161
+ "โ€ข Beautiful pastel-themed visualizations"
1162
  ),
1163
+ tags$h5(style="margin-top:20px;font-weight:600;","๐Ÿ“š Mapping Methods"),
1164
+ tags$ul(lapply(MAPPING_MODELS, function(m)
1165
+ tags$li(tags$b(m$label),"โ€”",m$desc,style="margin-bottom:6px;"))),
1166
+ tags$h5(style="margin-top:20px;font-weight:600;","๐Ÿ“– References"),
1167
  tags$ul(
 
 
1168
  tags$li("Lander & Botstein (1989) Genetics 121:185 โ€” LOD intervals"),
1169
+ tags$li("Zeng (1993) PNAS 90:10972; (1994) Genetics 136:1457 โ€” CIM"),
1170
  tags$li("Tibshirani (1996) JRSS-B 58:267 โ€” LASSO"),
1171
+ tags$li("Zou & Hastie (2005) JRSS-B 67:301 โ€” Elastic Net"),
1172
+ tags$li("Breiman (2001) Machine Learning 45:5 โ€” Random Forest"),
1173
+ tags$li("Wright (2016) Heredity 117:403 โ€” RF in plant breeding")
1174
+ ),
1175
+ tags$hr(),
1176
+ tags$p(style="text-align:center;color:#8B7A5A;font-size:12px;",
1177
+ "๐Ÿ“ง Contact: ashmithamganesan@gmail.com | P.sinha@cgiar.org",
1178
+ tags$br(),
1179
+ "ยฉ 2024 QTL-Mapper v6 โ€” All Rights Reserved"
1180
  )
1181
  )
1182
  )
 
1202
  compare_res = list()
1203
  )
1204
 
 
1205
  lod_thr <- reactive({ input$lod_threshold })
1206
 
1207
  # โ”€โ”€ Method description โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
1208
  output$method_desc_ui <- renderUI({
1209
  m <- input$mapping_method
1210
  if (is.null(m)||!m%in%names(MAPPING_MODELS)) return(NULL)
1211
+ div(class="info-box", tags$i(class="fas fa-flask",style="margin-right:6px;"), MAPPING_MODELS[[m]]$desc)
1212
  })
1213
 
1214
  # โ”€โ”€ Dataset info โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
1215
  output$dataset_info_ui <- renderUI({
1216
+ if (is.null(rv$geno))
1217
+ return(tags$div(class="warn-box","๐Ÿ“‚ No data loaded. Please upload genotype and phenotype files."))
1218
  tagList(
1219
+ div(style="display:flex;justify-content:space-between;margin-bottom:8px;",
1220
+ tags$span(class="stat-value",nrow(rv$geno)), tags$span(class="stat-label","Samples")),
1221
+ div(style="display:flex;justify-content:space-between;margin-bottom:8px;",
1222
+ tags$span(class="stat-value",ncol(rv$geno)), tags$span(class="stat-label","Markers")),
1223
+ div(style="display:flex;justify-content:space-between;margin-bottom:8px;",
1224
+ tags$span(class="stat-value",length(unique(rv$marker_info$Chromosome))),
1225
+ tags$span(class="stat-label","Chromosomes")),
1226
+ if(!is.null(rv$pheno)) div(style="display:flex;justify-content:space-between;",
1227
+ tags$span(class="stat-value",ncol(rv$pheno)), tags$span(class="stat-label","Traits"))
1228
  )
1229
  })
1230
 
 
1233
  req(input$geno_file)
1234
  tryCatch({
1235
  res <- load_genotype_file(input$geno_file$datapath)
1236
+ rv$geno <- res$geno
1237
+ rv$marker_info <- res$marker_info
1238
+ rv$all_markers <- res$marker_info
1239
+ showNotification(paste("โœ… Loaded",res$n_markers,"markers,",res$n_samples,"samples"),
1240
+ type="message",duration=3)
1241
+ }, error=function(e) showNotification(paste("โŒ Geno error:",e$message),type="error"))
1242
  })
1243
 
1244
  observeEvent(input$pheno_file, {
 
1249
  for (col in colnames(pd)) pd[[col]] <- as.numeric(as.character(pd[[col]]))
1250
  rv$pheno <- pd
1251
  updateSelectInput(session,"pheno_col",choices=colnames(pd),selected=colnames(pd)[1])
1252
+ showNotification(paste("โœ… Loaded",ncol(pd),"traits"),type="message",duration=3)
1253
+ }, error=function(e) showNotification(paste("โŒ Pheno error:",e$message),type="error"))
1254
  })
1255
 
1256
  observeEvent(input$pop_file, {
1257
  req(input$pop_file)
1258
  tryCatch({
1259
  rv$pop_data <- read.csv(input$pop_file$datapath)
1260
+ showNotification(paste("โœ… Loaded",nrow(rv$pop_data),"samples"),type="message")
1261
+ }, error=function(e) showNotification(paste("โŒ Pop error:",e$message),type="error"))
1262
  })
1263
 
1264
  observeEvent(input$test_geno_file, {
 
1266
  tryCatch({
1267
  res <- load_genotype_file(input$test_geno_file$datapath)
1268
  rv$test_geno <- res$geno
1269
+ showNotification(paste("โœ… Test geno:",nrow(res$geno),"samples"),type="message")
1270
+ }, error=function(e) showNotification(paste("โŒ Test geno error:",e$message),type="error"))
1271
  })
1272
 
1273
  # โ”€โ”€ Previews โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
1274
+ output$prev_geno <- renderDT({ req(input$geno_file); datatable(head(read.csv(input$geno_file$datapath),10), options=list(scrollX=TRUE,pageLength=5,dom='t')) })
1275
+ output$prev_pheno <- renderDT({ req(input$pheno_file); datatable(head(read.csv(input$pheno_file$datapath),10),options=list(scrollX=TRUE,pageLength=5,dom='t')) })
1276
+ output$prev_test_geno <- renderDT({ req(rv$test_geno); datatable(head(rv$test_geno,10),options=list(scrollX=TRUE,pageLength=5,dom='t')) })
1277
+ output$prev_pred <- renderDT({ req(rv$pred_test); datatable(rv$pred_test,options=list(scrollX=TRUE,pageLength=8,dom='t')) })
1278
+ output$prev_pop <- renderDT({ req(rv$pop_data); datatable(head(rv$pop_data,10),options=list(scrollX=TRUE,pageLength=5,dom='t')) })
1279
 
1280
  # โ”€โ”€ MAIN ANALYSIS โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
1281
  observeEvent(input$run_btn, {
1282
  req(rv$geno, rv$pheno, input$pheno_col)
1283
+ showNotification(paste("๐Ÿš€ Starting",input$mapping_method,"scan..."),type="message")
1284
  tryCatch({
1285
  cs <- intersect(rownames(rv$geno), rownames(rv$pheno))
1286
+ if (length(cs)==0) { showNotification("โŒ No common samples!",type="error"); return() }
1287
  X <- rv$geno[cs,,drop=FALSE]; y <- as.numeric(rv$pheno[cs,input$pheno_col])
1288
  set.seed(42)
1289
  tr_idx <- caret::createDataPartition(y, p=1-input$val_prop, list=FALSE)
 
1312
  ytr_p <- predict(fit,X_tr_rf); yv_p <- predict(fit,X_v_rf)
1313
  tr_r2 <- 1-sum((y_tr-ytr_p)^2)/sum((y_tr-mean(y_tr))^2)
1314
  v_r2 <- 1-sum((y_v-yv_p)^2)/sum((y_v-mean(y_v))^2)
1315
+ rv$perf <- data.frame(Metric=c("Rยฒ Train","R Train","Rยฒ Validation","R Validation"),
1316
  Value=c(tr_r2,cor(y_tr,ytr_p),v_r2,cor(y_v,yv_p)))
1317
  rv$tr_pred <- data.frame(Observed=y_tr, Predicted=ytr_p)
1318
  rv$val_pred <- data.frame(Observed=y_v, Predicted=yv_p)
 
1321
 
1322
  n_sig <- if(!is.null(rv$scan_all)&&!"Message"%in%colnames(rv$scan_all))
1323
  sum(rv$scan_all$LOD>=lod_thr()&!is.na(rv$scan_all$LOD),na.rm=TRUE) else 0
1324
+ showNotification(paste("โœ…",input$mapping_method,"done:",n_sig,"QTLs detected"),type="message")
1325
+ updateTabsetPanel(session,"nav",selected="๐Ÿ“Š Results")
 
 
1326
  }, error=function(e) {
1327
+ showNotification(paste("โŒ Analysis error:",e$message),type="error")
1328
  cat("ANALYSIS ERROR:",e$message,"\n")
1329
  })
1330
  })
 
1333
  output$compare_status_ui <- renderUI({
1334
  if (length(rv$compare_res)==0) return(NULL)
1335
  tags$div(class="info-box",
1336
+ tags$b("โœ… Completed: "), paste(names(rv$compare_res),collapse=", "),
1337
  tags$br(),
1338
  lapply(names(rv$compare_res), function(m) {
1339
  r <- rv$compare_res[[m]]
1340
+ if(is.null(r)||"Message"%in%colnames(r)) return(tags$span(class="model-badge",paste0(m,": 0 QTLs")))
1341
  n <- sum(r$LOD>=lod_thr(),na.rm=TRUE)
1342
+ tags$span(class="model-badge",paste0(m,": ",n," QTLs"))
 
1343
  })
1344
  )
1345
  })
1346
 
1347
  observeEvent(input$run_compare, {
1348
  req(rv$geno, rv$pheno, input$compare_methods, input$pheno_col)
1349
+ if (length(input$compare_methods)==0) { showNotification("โš ๏ธ Select at least one method",type="warning"); return() }
1350
  cs <- intersect(rownames(rv$geno),rownames(rv$pheno))
1351
  X <- rv$geno[cs,,drop=FALSE]; y <- as.numeric(rv$pheno[cs,input$pheno_col])
1352
  set.seed(42)
 
1354
  X_tr <- X[tr_idx,,drop=FALSE]; y_tr <- y[tr_idx]
1355
 
1356
  compare_list <- list()
1357
+ withProgress(message="๐Ÿ”„ Comparing models...",value=0,{
1358
+ for (i in seq_along(input$compare_methods)) {
1359
+ mth <- input$compare_methods[i]
1360
  incProgress(1/length(input$compare_methods),detail=paste("Running",mth))
1361
  res <- tryCatch(
1362
  qtl_scan(X_tr,y_tr,rv$marker_info,method=mth,
 
1366
  }
1367
  })
1368
  rv$compare_res <- compare_list
1369
+ showNotification(paste("โœ… Compared",length(compare_list),"models"),type="message")
1370
  })
1371
 
1372
  output$compare_idiogram <- renderPlot({
1373
  req(length(rv$compare_res)>0, rv$all_markers)
1374
+ par(bg="#FDFBF7")
1375
  make_chromosome_idiogram(rv$compare_res, rv$all_markers, lod_thr())
1376
+ }, bg="#FDFBF7")
1377
 
1378
  output$compare_bar <- renderPlotly({
1379
  req(length(rv$compare_res)>0)
 
1390
  if(length(rows)==0) return(plot_ly()%>%layout(title="No significant QTLs found"))
1391
  df <- do.call(rbind,rows)
1392
  df$Chromosome <- factor(df$Chromosome,levels=sort(unique(df$Chromosome)))
1393
+ plot_ly(df,x=~Chromosome,y=~Count,color=~Method,type="bar",
1394
+ colors=PASTEL_COLORS[1:length(unique(df$Method))])%>%
1395
+ layout(barmode="group",
1396
+ title=list(text="๐Ÿ“Š QTL Count by Method & Chromosome",font=list(size=14)),
1397
+ xaxis=list(title="Chromosome",tickangle=45),
1398
+ yaxis=list(title="# Significant QTLs"),
1399
+ plot_bgcolor="#FDFBF7",paper_bgcolor="#FDFBF7",
1400
+ legend=list(title=list(text="Method")))
1401
  })
1402
 
1403
  output$compare_table <- renderDT({
 
1415
  df <- do.call(rbind,rows)
1416
  df$N_Models <- as.integer(table(df$Marker)[df$Marker])
1417
  datatable(df[order(-df$N_Models,-df$LOD),],
1418
+ options=list(scrollX=TRUE,pageLength=15,dom='Blfrtip'),
1419
+ rownames=FALSE,class='cell-border stripe hover')%>%
1420
  formatRound(c("LOD","PVE_Marker_Percent","Position"),3)
1421
  })
1422
 
 
1429
  output$common_qtl_summary_ui <- renderUI({
1430
  cq <- common_qtl_data()
1431
  if (is.null(cq)||nrow(cq)==0)
1432
+ return(div(class="warn-box","โš ๏ธ No common QTLs found. Run Compare Models first."))
1433
  n_all <- nrow(cq)
1434
  n_max <- sum(cq$N_Models_Detected==length(rv$compare_res), na.rm=TRUE)
1435
  tagList(
1436
  div(class="good-box",
1437
+ tags$span(style="font-size:28px;font-weight:700;color:#6B9E6B;",n_all),
1438
+ tags$span(" common QTLs detected", style="font-weight:500;"),
1439
  tags$br(),
1440
+ tags$span(style="font-size:20px;font-weight:600;color:#7BA07A;",n_max),
1441
+ tags$span(" detected in ALL models", style="font-weight:500;"),
1442
  tags$br(),
1443
+ tags$small("๐Ÿ“Š Chromosomes: ", paste(sort(unique(cq$Chromosome)),collapse=", "))
1444
  )
1445
  )
1446
  })
 
1452
  options=list(dom="t")))
1453
  num_cols <- intersect(c("Position","Mean_LOD","Max_LOD","Mean_PVE","Mean_Add_Eff",
1454
  paste0("LOD_",names(rv$compare_res))), colnames(cq))
1455
+ datatable(cq, options=list(scrollX=TRUE,pageLength=15,dom='Blfrtip'),
1456
+ rownames=FALSE,class='cell-border stripe hover') %>%
1457
  formatRound(num_cols, 3) %>%
1458
  formatStyle("N_Models_Detected",
1459
+ background=styleColorBar(range(cq$N_Models_Detected,na.rm=TRUE),"#C8E6C8"),
1460
  backgroundSize="100% 80%", backgroundRepeat="no-repeat",
1461
  backgroundPosition="center") %>%
1462
  formatStyle("Max_LOD",
1463
+ background=styleColorBar(range(cq$Max_LOD,na.rm=TRUE),"#D4E2D0"),
1464
  backgroundSize="100% 80%", backgroundRepeat="no-repeat",
1465
  backgroundPosition="center")
1466
  })
 
1468
  output$common_idiogram <- renderPlot({
1469
  cq <- common_qtl_data()
1470
  req(!is.null(cq), nrow(cq)>0, rv$all_markers)
 
 
1471
  n_levels <- sort(unique(cq$N_Models_Detected), decreasing=TRUE)
1472
+ cols <- c("#6B9E6B","#8B9E6B","#AB9E6B","#CB9E6B","#EB9E6B")
1473
  pal <- setNames(cols[seq_along(n_levels)], as.character(n_levels))
1474
 
1475
  qtl_list_cq <- lapply(setNames(n_levels, paste0(n_levels," model(s)")), function(nl) {
 
1480
  sub$Method <- paste0(nl," models")
1481
  sub
1482
  })
1483
+ par(bg="#FDFBF7")
1484
  make_chromosome_idiogram(qtl_list_cq, rv$all_markers, lod_thr(),
1485
  trait_colors=setNames(cols[seq_along(n_levels)],
1486
  paste0(n_levels," model(s)")))
1487
+ }, bg="#FDFBF7")
1488
 
1489
  output$common_bar <- renderPlotly({
1490
  cq <- common_qtl_data()
1491
  if (is.null(cq)||nrow(cq)==0)
1492
+ return(plot_ly()%>%layout(title="No common QTLs",plot_bgcolor="#FDFBF7",paper_bgcolor="#FDFBF7"))
1493
 
1494
  df <- cq %>%
1495
  dplyr::group_by(Chromosome, N_Models_Detected) %>%
 
1498
  df$Chromosome <- factor(df$Chromosome, levels=sort(unique(as.character(df$Chromosome))))
1499
 
1500
  plot_ly(df,x=~Chromosome,y=~Count,color=~Label,type="bar",
1501
+ colors=c("#6B9E6B","#8B9E6B","#AB9E6B","#CB9E6B","#EB9E6B"))%>%
1502
  layout(barmode="stack",
1503
+ title=list(text="๐ŸŽฏ Common QTL Count by Chromosome",font=list(size=14)),
1504
+ xaxis=list(title="Chromosome",tickangle=45),
1505
  yaxis=list(title="# Common QTLs"),
1506
+ plot_bgcolor="#FDFBF7",paper_bgcolor="#FDFBF7",
1507
+ legend=list(title=list(text="Detected by"),orientation="h",y=-0.15))
1508
  })
1509
 
1510
  # โ”€โ”€ MAIN PLOTS โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
 
1519
  if(!is.null(rv$scan_all)&&!"Message"%in%colnames(rv$scan_all))
1520
  res_list[[input$mapping_method]] <- rv$scan_all
1521
  if(length(res_list)==0){ plot(0,0,type="n",axes=FALSE,xlab="",ylab=""); text(0,0,"Run analysis first",cex=1.2); return() }
1522
+ par(bg="#FDFBF7")
1523
  make_chromosome_idiogram(res_list, rv$all_markers, lod_thr())
1524
+ }, bg="#FDFBF7")
1525
 
1526
  output$perf_plot <- renderPlotly({
1527
  req(rv$perf)
1528
  plot_ly(rv$perf,x=~Metric,y=~Value,type="bar",
1529
+ marker=list(color=c("#7BA07A","#9BB89A","#5A8A5A","#7BA07A")),
1530
+ text=~round(Value,3),textposition="outside",textfont=list(size=10))%>%
1531
+ layout(title=list(text="๐Ÿ“Š Model Performance",font=list(size=14)),
1532
+ yaxis=list(range=c(0,1.15),title="Value",gridcolor="#F0EBE0"),
1533
+ xaxis=list(title="",tickangle=15),
1534
+ plot_bgcolor="#FDFBF7",paper_bgcolor="#FDFBF7")
1535
  })
1536
 
1537
  output$reg_train <- renderPlotly({
1538
  req(rv$tr_pred)
1539
  plot_ly(rv$tr_pred,x=~Observed,y=~Predicted,type="scatter",mode="markers",
1540
+ marker=list(size=8,color="#7BA07A",opacity=.7,line=list(width=0.5,color="#FFFFFF")))%>%
1541
  add_trace(x=range(rv$tr_pred$Observed),y=range(rv$tr_pred$Observed),
1542
+ type="scatter",mode="lines",line=list(color="#D98A7A",dash="dash",width=1.5),showlegend=FALSE)%>%
1543
+ layout(title=list(text="๐ŸŽฏ Training Set",font=list(size=14)),
1544
+ xaxis=list(title="Observed",gridcolor="#F0EBE0"),
1545
+ yaxis=list(title="Predicted",gridcolor="#F0EBE0"),
1546
+ plot_bgcolor="#FDFBF7",paper_bgcolor="#FDFBF7")
1547
  })
1548
 
1549
  output$reg_val <- renderPlotly({
1550
  req(rv$val_pred)
1551
  plot_ly(rv$val_pred,x=~Observed,y=~Predicted,type="scatter",mode="markers",
1552
+ marker=list(size=8,color="#5A8A5A",opacity=.7,line=list(width=0.5,color="#FFFFFF")))%>%
1553
  add_trace(x=range(rv$val_pred$Observed),y=range(rv$val_pred$Observed),
1554
+ type="scatter",mode="lines",line=list(color="#D98A7A",dash="dash",width=1.5),showlegend=FALSE)%>%
1555
+ layout(title=list(text="โœ… Validation Set",font=list(size=14)),
1556
+ xaxis=list(title="Observed",gridcolor="#F0EBE0"),
1557
+ yaxis=list(title="Predicted",gridcolor="#F0EBE0"),
1558
+ plot_bgcolor="#FDFBF7",paper_bgcolor="#FDFBF7")
1559
  })
1560
 
1561
  # โ”€โ”€ TABLES โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
 
1573
  "CI_Lower","CI_Upper","Dominance_Effect","Dominance_Ratio","Dominance_Class",
1574
  "N_Cofactors","N_Samples","Method","Interval_Start","Interval_End",
1575
  "Interval_Size_cM","Low_Flank","High_Flank"), colnames(sig))
1576
+ datatable(sig[,disp],options=list(scrollX=TRUE,pageLength=10,dom='Blfrtip'),
1577
+ rownames=FALSE,class='cell-border stripe hover')%>%
1578
  formatRound(intersect(c("LOD","PVE_Marker_Percent","PVE_CIM_Percent","Additive_Effect",
1579
  "SE_Additive","CI_Lower","CI_Upper","Dominance_Ratio","Interval_Size_cM"),disp),3)%>%
1580
  formatSignif(intersect("P_Value",disp),digits=3)
 
1584
  req(rv$scan_all)
1585
  if("Message"%in%colnames(rv$scan_all))
1586
  return(datatable(data.frame(Status=rv$scan_all$Message[1]),options=list(dom="t")))
1587
+ datatable(rv$scan_all,options=list(scrollX=TRUE,pageLength=15,order=list(list(4,"desc")),dom='Blfrtip'),
1588
+ rownames=FALSE,class='cell-border stripe hover')%>%
1589
  formatRound(c("LOD","PVE_Marker_Percent","Additive_Effect"),3)%>%
1590
  formatSignif("P_Value",digits=3)
1591
  })
1592
 
1593
  # โ”€โ”€ PREDICT TEST โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
1594
  observeEvent(input$pred_btn, {
1595
+ if(is.null(rv$model_fit)){ showNotification("โš ๏ธ Run analysis first",type="error"); return() }
1596
+ if(is.null(rv$test_geno)){ showNotification("โš ๏ธ Upload test genotype first",type="error"); return() }
1597
+ withProgress(message="๐Ÿ”ฎ Predicting...",value=0.2,{
1598
  train_cols <- rv$model_cols; test_raw <- rv$test_geno
1599
  common_m <- intersect(train_cols, colnames(test_raw))
1600
  X_pred <- as.data.frame(matrix(0,nrow=nrow(test_raw),ncol=length(train_cols),
 
1609
  rv$pred_test <- data.frame(Sample_ID=rownames(test_raw),Predicted_Phenotype=round(preds,4))
1610
  incProgress(0.3)
1611
  })
1612
+ showNotification(paste("โœ… Predicted",nrow(rv$pred_test),"test samples"),type="message")
1613
  })
1614
 
1615
  # โ”€โ”€ DOMESTICATION โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
 
1641
  cs <- intersect(rownames(rv$geno),rv$pop_data$id)
1642
  X <- rv$geno[cs,,drop=FALSE]; ps <- rv$pop_data[rv$pop_data$id%in%cs,]
1643
  sel <- calc_sel(X,ps,rv$marker_info)
1644
+ if(is.null(sel)){ showNotification("โŒ No selection metrics computed",type="error"); return() }
1645
  sel$Significant <- sel$Fst>input$fst_thr|sel$Tajima_D_Dom<input$tajima_thr
1646
  rv$sel_metrics <- sel
1647
+ showNotification(paste("โœ… Found",sum(sel$Significant,na.rm=TRUE),"selection signatures"),type="message")
1648
+ }, error=function(e) showNotification(paste("โŒ Dom error:",e$message),type="error"))
1649
  })
1650
 
1651
  create_man_plotly <- function(data, y_col, title, threshold, y_label=y_col) {
1652
+ blank <- plot_ly()%>%layout(title=title,plot_bgcolor="#FDFBF7",paper_bgcolor="#FDFBF7")
1653
  if(is.null(data)||nrow(data)==0||"Message"%in%colnames(data)) return(blank)
1654
  pd <- data[!is.na(data[[y_col]])&!is.na(data$Chromosome),]
1655
  if(nrow(pd)==0) return(blank)
 
1662
  }
1663
  pd$cum_pos <- pd$Position+offsets[pd$Chromosome]
1664
  chr_mids <- tapply(pd$cum_pos,pd$Chromosome,median,na.rm=TRUE)
1665
+ pal <- rep(c("#A8E6CF","#DCEDC1","#FFD3B6","#FFAAA5"),ceiling(length(chroms)/4))[seq_along(chroms)]
1666
  names(pal) <- chroms
1667
  p <- plot_ly()
1668
  for (ch in chroms)
1669
  p <- p%>%add_trace(data=pd[pd$Chromosome==ch,],x=~cum_pos,
1670
  y=as.formula(paste0("~",y_col)),type="scatter",mode="markers",
1671
+ name=paste("Chr",ch),marker=list(size=6,color=pal[ch],opacity=.7,line=list(width=0.5,color="#FFFFFF")),
1672
+ showlegend=FALSE,
1673
+ text=~paste0("<b>",Marker,"</b><br>๐Ÿ“ Chr: ",Chromosome,"<br>๐Ÿ“ Pos: ",round(Position,1),
1674
+ "<br>๐Ÿ“Š ",y_label,": ",round(get(y_col),4)),
1675
  hoverinfo="text")
1676
  if(!is.null(threshold))
1677
  p <- p%>%add_segments(x=min(pd$cum_pos,na.rm=TRUE),xend=max(pd$cum_pos,na.rm=TRUE),
1678
+ y=threshold,yend=threshold,line=list(color="#D98A7A",dash="dash",width=1.5),showlegend=FALSE)
1679
+ p%>%layout(title=list(text=title,font=list(size=14)),
1680
  xaxis=list(title="Chromosome",tickvals=as.list(chr_mids[chroms]),
1681
+ ticktext=as.list(paste0("Chr ",chroms)),tickangle=45,gridcolor="#F0EBE0"),
1682
+ yaxis=list(title=y_label,gridcolor="#F0EBE0"),
1683
+ plot_bgcolor="#FDFBF7",paper_bgcolor="#FDFBF7")
1684
  }
1685
 
1686
+ output$fst_plot <- renderPlotly({ req(rv$sel_metrics); create_man_plotly(rv$sel_metrics,"Fst","๐Ÿงฌ Fst Manhattan Plot",input$fst_thr,"Fst") })
1687
+ output$tajima_plot <- renderPlotly({ req(rv$sel_metrics); create_man_plotly(rv$sel_metrics,"Tajima_D_Dom","๐Ÿ“‰ Tajima's D Manhattan Plot",input$tajima_thr,"Tajima D") })
1688
  output$sel_table <- renderDT({
1689
  req(rv$sel_metrics)
1690
  datatable(rv$sel_metrics[order(-rv$sel_metrics$Fst),],
1691
+ options=list(scrollX=TRUE,pageLength=10,dom='Blfrtip'),
1692
+ rownames=FALSE,class='cell-border stripe hover')%>%
1693
+ formatRound(c("Fst","Pi_Dom","Pi_Wild","Tajima_D_Dom"),4)
1694
  })
1695
 
1696
  # โ”€โ”€ DOWNLOADS โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
 
1709
  }
1710
  pd$cum_pos <- pd$Position+offsets[pd$Chromosome]
1711
  pd$sig <- pd$LOD>=lod_thr()
1712
+ chr_colors <- rep(c("#A8E6CF","#DCEDC1","#FFD3B6","#FFAAA5"),ceiling(length(chroms)/4))[seq_along(chroms)]
1713
  names(chr_colors) <- chroms
1714
  chr_mids <- tapply(pd$cum_pos,pd$Chromosome,median,na.rm=TRUE)
1715
  p <- ggplot(pd,aes(x=cum_pos,y=LOD))+
1716
+ geom_point(aes(color=Chromosome),size=1.5,alpha=.7,show.legend=FALSE)+
1717
+ geom_point(data=pd[pd$sig,],color="#E15759",size=4,shape=18)+
1718
+ geom_hline(yintercept=lod_thr(),linetype="dashed",color="#E15759",linewidth=.8)+
1719
  scale_color_manual(values=chr_colors)+
1720
+ scale_x_continuous(breaks=chr_mids[chroms],labels=paste0("Chr ",chroms))+
1721
  labs(title=paste(input$mapping_method,"Manhattan Plot"),
1722
+ subtitle=paste0("LOD โ‰ฅ ",lod_thr()," | ",sum(pd$sig,na.rm=TRUE)," significant QTLs"),
1723
  x="Chromosome",y="LOD Score")+
1724
+ theme_minimal(base_size=12)+
1725
+ theme(panel.background=element_rect(fill="#FDFBF7",color=NA),
1726
+ plot.background=element_rect(fill="#FDFBF7",color=NA),
1727
+ panel.grid.minor=element_blank(),
1728
+ panel.grid.major.x=element_blank(),
1729
+ panel.grid.major.y=element_line(color="#F0EBE0"),
1730
+ axis.text.x=element_text(angle=45,hjust=1,color="#8B7A5A"),
1731
+ axis.text.y=element_text(color="#8B7A5A"),
1732
+ axis.title=element_text(color="#5D4E30",face="bold"),
1733
+ plot.title=element_text(face="bold",color="#5D4E30",size=14),
1734
+ plot.subtitle=element_text(color="#8B7A5A",size=11))
1735
  if(sum(pd$sig,na.rm=TRUE)>0&&sum(pd$sig,na.rm=TRUE)<=30)
1736
  p <- p+ggrepel::geom_label_repel(data=pd[pd$sig,],aes(label=Marker),
1737
+ size=2.5,max.overlaps=15,fill="white",color="#E15759",segment.color="#E15759")
1738
+ ggsave(file,plot=p,width=14,height=6,dpi=200,bg="#FDFBF7")
1739
  }
1740
  )
1741
 
 
1751
  if(!is.null(r)&&!"Message"%in%colnames(r)) res_list[[m]] <- r
1752
  }
1753
  if(length(res_list)==0) return()
1754
+ png(file,width=1800,height=900,res=150,bg="#FDFBF7")
1755
+ par(bg="#FDFBF7")
1756
  make_chromosome_idiogram(res_list, rv$all_markers, lod_thr())
1757
  dev.off()
1758
  }
 
1818
  )
1819
  }
1820
 
1821
+ # Run the app
1822
  shinyApp(ui=ui, server=server)