softwareDevelopment commited on
Commit
de74fba
·
verified ·
1 Parent(s): 07a3bec

Update app.R

Browse files
Files changed (1) hide show
  1. app.R +542 -122
app.R CHANGED
@@ -1,5 +1,7 @@
1
  # ============================================================
2
  # QTL MAPPING SUITE — Full Single-File Shiny Application
 
 
3
  # 10 Models: EM, HK, MR, IM, CIM, EHK, IMP, HKPERM, NP, MQM
4
  # 10+ Plots: Genome Scan, Manhattan, Interval, Density, QQ,
5
  # Heatmap, Effects, PVE, Common QTL, Circos
@@ -101,20 +103,30 @@ body{overflow-x:hidden}
101
  .st.acc .st-v{color:var(--acc)}
102
 
103
  /* UPLOAD ZONE */
104
- .uzone{border:2px dashed var(--g200);border-radius:var(--rlg);padding:36px 20px;text-align:center;cursor:pointer;transition:var(--t);background:var(--g50)}
105
  .uzone:hover{border-color:var(--acc);background:var(--acclt)}
106
- .uzone-ic{font-size:32px;margin-bottom:10px}
107
- .uzone-t{font-size:14px;font-weight:600;color:var(--ink)}
108
- .uzone-s{font-size:12px;color:var(--g400);margin-top:5px}
109
  .uzone .shiny-input-container{margin:0}
110
 
 
 
 
 
 
 
 
 
 
 
111
  /* FORM */
112
  .fl{display:block;font-size:12px;font-weight:600;color:var(--g600);margin-bottom:5px;letter-spacing:.2px}
113
  .fm-g{margin-bottom:14px}
114
  .selectize-input{border:1.5px solid var(--g100)!important;border-radius:var(--rsm)!important;font-family:var(--f)!important;font-size:13px!important;padding:7px 12px!important;box-shadow:none!important}
115
  .selectize-input.focus{border-color:var(--acc)!important;box-shadow:0 0 0 3px rgba(26,107,58,.1)!important}
116
- input[type=number]{width:100%;padding:8px 12px;border:1.5px solid var(--g100);border-radius:var(--rsm);font-family:var(--f);font-size:13px;outline:none}
117
- input[type=number]:focus{border-color:var(--acc);box-shadow:0 0 0 3px rgba(26,107,58,.1)}
118
  .irs--shiny .irs-bar{background:var(--acc)!important}
119
  .irs--shiny .irs-handle{background:var(--acc)!important;border-color:var(--acc)!important}
120
 
@@ -150,6 +162,12 @@ input[type=number]:focus{border-color:var(--acc);box-shadow:0 0 0 3px rgba(26,10
150
  .mc:hover{border-color:var(--acc);color:var(--acc);background:var(--acclt)}
151
  .mc.sel{background:var(--acc);color:#fff;border-color:var(--acc)}
152
 
 
 
 
 
 
 
153
  /* TIP */
154
  .tip{font-size:11px;color:var(--g400);font-style:italic;margin-top:4px}
155
 
@@ -197,6 +215,126 @@ cum_positions <- function(df, chr_col = "chr", pos_col = "pos") {
197
  list(df = df, offsets = offsets, chrs = chrs)
198
  }
199
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
200
  # ── UI ────────────────────────────────────────────────────────
201
  ui <- fluidPage(
202
  useShinyjs(),
@@ -226,7 +364,7 @@ ui <- fluidPage(
226
  div(class="qtl-top",
227
  div(class="tlmark","Q"),
228
  span(class="tlname","QTL Mapping Suite"),
229
- span(class="tlver","v2.0"),
230
  div(class="tldiv"),
231
  div(class="stpill", div(class="dot"), span(id="stlbl","Ready")),
232
  div(class="tlright",
@@ -262,36 +400,127 @@ ui <- fluidPage(
262
  # MAIN
263
  div(class="qtl-main",
264
 
265
- # ── UPLOAD ──
266
- div(id="pg-upload",class="pg active",
267
- div(class="ph", div(class="pt","Upload Cross Data"), div(class="ps","Import your QTL cross data in R/qtl CSV format")),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
268
  div(class="g2",
 
269
  div(class="card",
270
- div(class="ch", div(div(class="ct","Genotype / Phenotype File"), div(class="cst","CSV in R/qtl format"))),
 
 
 
271
  div(class="cb",
272
  div(class="uzone",
273
  div(class="uzone-ic","🧬"),
274
- div(class="uzone-t","Drop CSV file here"),
275
- div(class="uzone-s","R/qtl format — id, phenotype(s), marker columns"),
276
- fileInput("geno_file",NULL,accept=c(".csv",".CSV"),buttonLabel="Browse",placeholder="No file selected")
 
277
  ),
278
- div(class="tip","First column=ID, next=phenotype(s), rest=markers")
279
  )
280
  ),
 
281
  div(class="card",
282
- div(class="ch", div(div(class="ct","Cross Settings"), div(class="cst","Population type"))),
 
 
 
283
  div(class="cb",
284
- div(class="fm-g", label(class="fl","Cross Type"),
285
- selectInput("cross_type",NULL,choices=c("F2 Intercross"="f2","Backcross"="bc","RIL by selfing"="riself","RIL by sibling"="risib","Doubled Haploid"="dh"),selected="f2",width="100%")),
286
- div(class="fm-g", label(class="fl","Missing Code"), textInput("miss_code",NULL,value="NA",width="100%")),
287
- div(class="fm-g", label(class="fl","Genotype Codes (comma-sep)"), textInput("geno_codes",NULL,value="A,H,B",width="100%")),
288
- div(class="br",
289
- actionButton("load_data","Load Data",class="btn-p"),
290
- actionButton("load_demo","Load Listeria Demo",class="btn-s")
291
- )
292
  )
293
  )
294
  ),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
295
  uiOutput("upload_summary")
296
  ),
297
 
@@ -491,63 +720,146 @@ ui <- fluidPage(
491
  div(class="cb", withSpinner(DTOutput("tbl_full"),color="#1a6b3a"))
492
  )
493
  )
494
- )
495
- )
 
496
  )
497
 
498
  # ── SERVER ────────────────────────────────────────────────────
499
  server <- function(input, output, session) {
500
 
501
  rv <- reactiveValues(
502
- cross = NULL,
503
- scan_list = list(),
504
- sig_qtl = list(),
505
- log_msgs = character(0),
506
- running = FALSE,
507
- pheno_name = "Phenotype"
 
 
 
 
508
  )
509
 
510
- add_log <- function(msg) rv$log_msgs <- c(rv$log_msgs, paste0("[",format(Sys.time(),"%H:%M:%S"),"] ",msg))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
511
 
512
  # ── LOAD DEMO ──
513
  observeEvent(input$load_demo, {
514
- withProgress(message="Loading Listeria demo…",{
515
  tryCatch({
516
  data(listeria, package="qtl")
517
- rv$cross <- listeria
518
- rv$log_msgs <- character(0)
519
- add_log("Loaded Listeria demo (F2, 20 chr, 133 markers, 1 phenotype)")
520
- showNotification("Listeria dataset loaded!",type="message",duration=3)
 
 
 
 
521
  shinyjs::runjs("$('.nv').removeClass('active');$('[data-page=explore]').addClass('active');$('.pg').removeClass('active');$('#pg-explore').addClass('active');")
522
- }, error=function(e) showNotification(paste("Error:",e$message),type="error"))
 
 
 
 
523
  })
524
  })
525
 
526
- # ── LOAD USER FILE ──
527
  observeEvent(input$load_data, {
528
- req(input$geno_file)
529
- withProgress(message="Reading CSV…",{
 
 
 
 
 
 
530
  tryCatch({
531
- rv$cross <- read.cross(format="csv", file=input$geno_file$datapath,
532
- genotypes=trimws(strsplit(input$geno_codes,",")[[1]]), na.strings=input$miss_code)
533
- class(rv$cross)[1] <- input$cross_type
534
- add_log(paste("Loaded:",input$geno_file$name))
535
- showNotification("Data loaded!",type="message",duration=3)
536
- }, error=function(e) showNotification(paste("Load error:",e$message),type="error"))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
537
  })
538
  })
539
 
 
 
 
 
 
 
 
 
 
 
540
  # ── UPLOAD SUMMARY ──
541
  output$upload_summary <- renderUI({
542
  req(rv$cross); cr <- rv$cross
543
  div(class="card",
544
- div(class="ch",div(div(class="ct","Dataset Summary"))),
545
  div(class="cb",
546
  div(class="g4",
547
- div(class="st acc",div(class="st-l","Individuals"),div(class="st-v",nind(cr))),
548
- div(class="st",div(class="st-l","Markers"),div(class="st-v",totmar(cr))),
549
- div(class="st",div(class="st-l","Chromosomes"),div(class="st-v",nchr(cr))),
550
- div(class="st",div(class="st-l","Phenotypes"),div(class="st-v",nphe(cr)))
 
 
 
 
 
551
  )
552
  )
553
  )
@@ -557,19 +869,25 @@ server <- function(input, output, session) {
557
  output$stat_tiles <- renderUI({
558
  req(rv$cross); cr <- rv$cross
559
  tagList(
560
- div(class="st acc",div(class="st-l","Individuals"),div(class="st-v",nind(cr))),
561
- div(class="st",div(class="st-l","Markers"),div(class="st-v",totmar(cr))),
562
- div(class="st",div(class="st-l","Chromosomes"),div(class="st-v",nchr(cr))),
563
- div(class="st",div(class="st-l","Phenotypes"),div(class="st-v",nphe(cr)))
564
  )
565
  })
566
 
567
- # ── EXPLORE ──
568
  output$explore_content <- renderUI({
569
  tab <- if(is.null(input$tab_ex)) "pheno" else input$tab_ex
570
  req(rv$cross)
571
  if (tab=="pheno") {
572
- div(class="card",div(class="ch",div(class="ct","Phenotype Distribution")),div(class="cb",withSpinner(plotlyOutput("pl_ex_pheno",height="320px"),color="#1a6b3a")))
 
 
 
 
 
 
573
  } else if (tab=="map") {
574
  div(class="card",div(class="ch",div(class="ct","Genetic Map")),div(class="cb",withSpinner(plotlyOutput("pl_ex_map",height="380px"),color="#1a6b3a")))
575
  } else if (tab=="miss") {
@@ -579,45 +897,77 @@ server <- function(input, output, session) {
579
  }
580
  })
581
 
 
 
 
 
 
 
 
 
582
  output$pl_ex_pheno <- renderPlotly({
583
- req(rv$cross); phe <- pull.pheno(rv$cross,1); pn <- phenames(rv$cross)[1]
584
- df <- data.frame(y=phe)
585
- p <- ggplot(df,aes(x=y))+geom_histogram(aes(y=after_stat(density)),bins=30,fill="#1a6b3a",color="white",alpha=.85)+geom_density(color="#c47c1a",linewidth=1)+labs(x=pn,y="Density",title=paste("Phenotype:",pn))+theme_minimal()+theme(panel.grid.minor=element_blank(),panel.grid.major=element_line(color="#f0f0ee"))
586
- ggplotly(p)%>%layout(font=list(family="DM Sans"))
 
 
 
 
 
 
 
587
  })
588
 
589
  output$pl_ex_map <- renderPlotly({
590
  req(rv$cross); map <- pull.map(rv$cross)
591
  df <- do.call(rbind,lapply(names(map),function(c) data.frame(chr=c,pos=map[[c]],marker=names(map[[c]]),stringsAsFactors=FALSE)))
592
  df$cn <- as.numeric(factor(df$chr,levels=names(map)))
593
- p <- ggplot(df,aes(x=pos,y=cn,text=paste0("Marker:",marker,"<br>Chr:",chr,"<br>Pos:",round(pos,2),"cM")))+geom_line(aes(group=chr),color="#d0d0cc",linewidth=.5)+geom_point(color="#1a6b3a",size=2.5,alpha=.8)+scale_y_continuous(breaks=unique(df$cn),labels=names(map))+labs(x="Position (cM)",y="Chromosome",title="Genetic Map")+theme_minimal()+theme(panel.grid.minor=element_blank())
 
 
 
594
  ggplotly(p,tooltip="text")%>%layout(font=list(family="DM Sans"))
595
  })
596
 
597
  output$pl_ex_miss <- renderPlotly({
598
  req(rv$cross); gt <- pull.geno(rv$cross)
599
  mp <- colMeans(is.na(gt))*100; df <- data.frame(marker=names(mp),pct=mp,idx=seq_along(mp))
600
- p <- ggplot(df,aes(x=idx,y=pct,text=paste0("Marker:",marker,"<br>Missing:",round(pct,1),"%")))+geom_col(fill="#1a4a8a",alpha=.7)+labs(x="Marker Index",y="Missing (%)",title="Missing Genotype Data")+theme_minimal()+theme(panel.grid.minor=element_blank())
 
601
  ggplotly(p,tooltip="text")%>%layout(font=list(family="DM Sans"))
602
  })
603
 
604
  output$pl_ex_gf <- renderPlotly({
605
  req(rv$cross); gt <- pull.geno(rv$cross)
606
- cnts <- apply(gt,2,function(x) table(factor(x,levels=1:3)))
607
- df <- as.data.frame(t(cnts)); df$marker <- rownames(df); names(df)[1:3] <- c("AA","AB","BB")
608
- dl <- tidyr::pivot_longer(df,c("AA","AB","BB"),names_to="geno",values_to="count")
609
- dl$idx <- match(dl$marker,unique(dl$marker))
610
- p <- ggplot(dl,aes(x=idx,y=count,fill=geno,text=paste0("Marker:",marker,"<br>Geno:",geno,"<br>N:",count)))+geom_col(position="fill",width=1)+scale_fill_manual(values=c(AA="#1a6b3a",AB="#c47c1a",BB="#1a4a8a"))+labs(x="Marker Index",y="Proportion",fill="Genotype")+theme_minimal()+theme(panel.grid.minor=element_blank())
 
 
 
 
 
 
 
 
 
 
611
  ggplotly(p,tooltip="text")%>%layout(font=list(family="DM Sans"))
612
  })
613
 
614
  # ── CONFIG SELECTS ──
615
  output$pheno_sel <- renderUI({
616
- req(rv$cross); pn <- phenames(rv$cross)
 
617
  selectInput("pheno_col",NULL,choices=pn,selected=pn[1],width="100%")
618
  })
 
619
  output$chr_sel <- renderUI({
620
- req(rv$cross); ch <- chrnames(rv$cross)
 
621
  checkboxGroupInput("scan_chrs",NULL,choices=ch,selected=ch,inline=TRUE)
622
  })
623
 
@@ -627,7 +977,10 @@ server <- function(input, output, session) {
627
  pn <- if(is.null(input$pheno_col)) "—" else input$pheno_col
628
  thr <- if(is.null(input$lod_thr)) 3.0 else input$lod_thr
629
  div(
630
- div(class="al al-info","ℹ",div(div(style="font-weight:600;","Configured"),div(paste("Phenotype:",pn,"| Models:",length(mods),"| Threshold:",thr,"| Permutations:",input$n_perm)))),
 
 
 
631
  div(class="mchips",lapply(mods,function(m) div(class="mc sel",`data-model`=m,MODEL_LABELS[m])))
632
  )
633
  })
@@ -657,60 +1010,103 @@ server <- function(input, output, session) {
657
  req(rv$cross)
658
  mods <- if(is.null(input$sel_models)||!length(input$sel_models)) c("em","hk") else input$sel_models
659
  phe_col <- if(is.null(input$pheno_col)) 1 else which(phenames(rv$cross)==input$pheno_col)[1]
660
- step <- if(is.null(input$step_sz)) 2 else input$step_sz
661
- ep <- if(is.null(input$err_prob)) 0.001 else input$err_prob
662
- thr <- if(is.null(input$lod_thr)) 3.0 else input$lod_thr
663
- n_perm <- if(is.null(input$n_perm)) 0 else input$n_perm
664
- n_imp <- if(is.null(input$n_imp)) 32 else input$n_imp
665
-
666
- rv$running <- TRUE; rv$scan_list <- list(); rv$sig_qtl <- list(); rv$log_msgs <- character(0)
 
 
 
 
667
  rv$pheno_name <- phenames(rv$cross)[phe_col]
668
 
669
- withProgress(message="Running QTL scan…",value=0,{
670
  tryCatch({
671
  add_log("Computing conditional genotype probabilities…")
672
- rv$cross <- calc.genoprob(rv$cross,step=step,error.prob=ep)
673
  incProgress(0.1)
674
- if("imp" %in% mods) { add_log("Simulating genotypes for imputation…"); rv$cross <- sim.geno(rv$cross,n.draws=n_imp,step=step,error.prob=ep) }
 
 
 
 
675
 
676
  for(i in seq_along(mods)){
677
- m <- mods[i]; add_log(paste("Model:",MODEL_LABELS[m],"…")); incProgress(0.8/length(mods),detail=MODEL_LABELS[m])
 
 
 
678
  res <- tryCatch({
679
  switch(m,
680
- em = scanone(rv$cross,pheno.col=phe_col,method="em"),
681
- hk = scanone(rv$cross,pheno.col=phe_col,method="hk"),
682
- mr = scanone(rv$cross,pheno.col=phe_col,method="mr"),
683
- im = scanone(rv$cross,pheno.col=phe_col,method="em"),
684
- ehk = scanone(rv$cross,pheno.col=phe_col,method="ehk"),
685
- imp = scanone(rv$cross,pheno.col=phe_col,method="imp"),
686
- hkperm = scanone(rv$cross,pheno.col=phe_col,method="hk"),
687
- scanone_np = scanone(rv$cross,pheno.col=phe_col,method="np"),
688
- cim = cim(rv$cross,pheno.col=phe_col,method="hk"),
689
- mqm = tryCatch(mqmscan(rv$cross,pheno.col=phe_col),error=function(e) scanone(rv$cross,pheno.col=phe_col,method="hk")),
690
- scanone(rv$cross,pheno.col=phe_col,method="hk")
 
 
 
691
  )
692
- }, error=function(e){ add_log(paste(" ✗",m,":",e$message,"→ fallback HK")); scanone(rv$cross,pheno.col=phe_col,method="hk") })
 
 
 
693
 
694
  rv$scan_list[[m]] <- res
695
- lc <- ncol(res); sig <- res[res[,lc]>=thr,]
696
- if(nrow(sig)>0){ sig$model <- MODEL_LABELS[m]; sig$model_id <- m; sig$marker <- rownames(sig); sig$pve <- round(100*(1-exp(-2*sig[,lc]/nind(rv$cross))),2) }
 
 
 
 
 
 
697
  rv$sig_qtl[[m]] <- sig
698
- add_log(paste(" ✓",MODEL_LABELS[m],"peaks:",nrow(sig)))
699
  }
700
- rv$running <- FALSE; incProgress(0.1)
701
- add_log(paste("All",length(mods),"models completed.")); showNotification("Scan complete!",type="message",duration=3)
702
- }, error=function(e){ rv$running <- FALSE; add_log(paste("FATAL:",e$message)); showNotification(paste("Error:",e$message),type="error") })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
703
  })
704
  })
705
 
706
- observeEvent(input$clr_res,{ rv$scan_list <- list(); rv$sig_qtl <- list(); rv$log_msgs <- character(0) })
 
 
707
 
708
  # ── REACTIVE HELPERS ──
709
  comb_df <- reactive({
710
  req(length(rv$scan_list)>0)
711
  do.call(rbind,lapply(names(rv$scan_list),function(m){
712
  sc <- rv$scan_list[[m]]; lc <- ncol(sc)
713
- data.frame(chr=as.character(sc$chr),pos=sc$pos,lod=sc[,lc],model=MODEL_LABELS[m],model_id=m,marker=rownames(sc),stringsAsFactors=FALSE)
 
 
714
  }))
715
  })
716
 
@@ -734,7 +1130,6 @@ server <- function(input, output, session) {
734
  sel <- if(!is.null(input$gm_msel)) input$gm_msel else unique(df$model_id)
735
  df <- df[df$model_id %in% sel,]; thr <- thresh_val()
736
  res <- cum_positions(df); df <- res$df; offsets <- res$offsets; chrs <- res$chrs
737
-
738
  p <- ggplot(df,aes(x=cum_pos,y=lod,color=model,text=paste0("Chr:",chr,"<br>Pos:",round(pos,1),"cM<br>LOD:",round(lod,2),"<br>Model:",model)))+
739
  geom_line(linewidth=.7,alpha=.88)+
740
  geom_hline(yintercept=thr,linetype="dashed",color="#b83232",linewidth=.6)+
@@ -826,11 +1221,11 @@ server <- function(input, output, session) {
826
 
827
  output$pl_eff <- renderPlotly({
828
  req(rv$cross,length(rv$scan_list)>0)
829
- ch <- if(is.null(input$eff_chr)) chrnames(rv$cross)[1] else input$eff_chr
830
  sc <- rv$scan_list[[names(rv$scan_list)[1]]]; lc <- ncol(sc)
831
  scc <- sc[sc$chr==ch,]; if(!nrow(scc)) return(plotly_empty())
832
- pm <- find.marker(rv$cross,ch,scc$pos[which.max(scc[,lc])])
833
- eff <- effectplot(rv$cross,mname1=pm,pheno.col=1,draw=FALSE)
834
  df <- data.frame(geno=names(eff$Means),mean=as.numeric(eff$Means),sd=as.numeric(eff$SDs),n=as.numeric(eff$n))
835
  df$se <- df$sd/sqrt(df$n)
836
  p <- ggplot(df,aes(x=geno,y=mean,fill=geno,text=paste0("Geno:",geno,"<br>Mean:",round(mean,3),"<br>SE:",round(se,3))))+
@@ -842,7 +1237,6 @@ server <- function(input, output, session) {
842
 
843
  output$peak_sel <- renderUI({
844
  req(length(rv$sig_qtl)>0); sd <- sig_df(); req(!is.null(sd))
845
- lc <- ncol(rv$scan_list[[sd$model_id[1]]])
846
  ch <- paste0(sd$chr," @ ",round(sd$pos,1),"cM (",sd$model_id,")")
847
  selectInput("pk_sel",NULL,choices=ch,width="100%")
848
  })
@@ -850,16 +1244,26 @@ server <- function(input, output, session) {
850
  output$pl_violin <- renderPlotly({
851
  req(rv$cross,length(rv$sig_qtl)>0,!is.null(input$pk_sel))
852
  sd <- sig_df(); req(!is.null(sd))
853
- lc <- ncol(rv$scan_list[[sd$model_id[1]]])
854
- idx <- which(paste0(sd$chr," @ ",round(sd$pos,1),"cM (",sd$model_id,")")==input$pk_sel)[1]; req(!is.na(idx))
855
  row <- sd[idx,]
856
  mar <- tryCatch(find.marker(rv$cross,row$chr,row$pos),error=function(e) row$marker)
857
  gt <- pull.geno(rv$cross)[,mar]; phe <- pull.pheno(rv$cross,1)
858
- gl <- c("1"="AA","2"="AB","3"="BB")
859
- bdf <- data.frame(geno=factor(gl[as.character(gt)],levels=c("AA","AB","BB")),pheno=phe)%>%filter(!is.na(geno),!is.na(pheno))
860
- p <- ggplot(bdf,aes(x=geno,y=pheno,fill=geno))+geom_violin(alpha=.4,draw_quantiles=c(.25,.5,.75))+geom_jitter(aes(color=geno),width=.15,size=1.5,alpha=.6)+
861
- scale_fill_manual(values=c(AA="#1a6b3a",AB="#c47c1a",BB="#1a4a8a"))+scale_color_manual(values=c(AA="#1a6b3a",AB="#c47c1a",BB="#1a4a8a"))+
862
- labs(x="Genotype",y=rv$pheno_name,title=paste("Phenotype at",mar))+theme_minimal()+theme(legend.position="none")
 
 
 
 
 
 
 
 
 
 
863
  ggplotly(p)%>%layout(font=list(family="DM Sans"))
864
  })
865
 
@@ -908,10 +1312,15 @@ server <- function(input, output, session) {
908
  map <- pull.map(rv$cross); cnms <- names(map); clens <- sapply(map,max)
909
  par(bg="white",mar=c(0,0,2,0))
910
  circos.clear()
911
- circos.par("track.height"=0.08,"cell.padding"=c(0,0,0,0),"gap.after"=rep(2,length(cnms)),"start.degree"=90,"clock.wise"=TRUE,"background.color"="#ffffff",canvas.xlim=c(-1.25,1.25),canvas.ylim=c(-1.25,1.25))
 
 
912
  circos.initialize(factors=cnms,xlim=cbind(rep(0,length(cnms)),clens))
913
  circos.trackPlotRegion(ylim=c(0,1),track.height=0.05,bg.border=NA,bg.col="#f4f4f2",
914
- panel.fun=function(x,y){ chr<-get.cell.meta.data("sector.index"); circos.text(mean(get.cell.meta.data("xlim")),0.5,chr,facing="clockwise",niceFacing=TRUE,cex=.6,col="#2a2a27",font=2) })
 
 
 
915
  mpal <- c("#1a6b3a","#2d9e58","#c47c1a","#1a4a8a","#b83232","#7b3fa0","#1a8a8a","#8a5a1a","#555555","#e05c00")
916
  for(mi in seq_along(mods)){
917
  m <- mods[mi]; mc <- mpal[((mi-1)%%length(mpal))+1]; mclt <- paste0(mc,"44")
@@ -949,10 +1358,21 @@ server <- function(input, output, session) {
949
  lm <- tryCatch(find.marker(rv$cross,r$chr,left),error=function(e)"—")
950
  rm <- tryCatch(find.marker(rv$cross,r$chr,right),error=function(e)"—")
951
  pm <- tryCatch(find.marker(rv$cross,r$chr,r$pos),error=function(e) r$marker)
952
- data.frame(Phenotype=rv$pheno_name,Model=r$model,Chr=r$chr,
953
- `Peak_pos_cM`=round(r$pos,2),`Peak_Marker`=pm,LOD=round(r[,lc],3),
954
- `PVE_%`=paste0(round(r$pve,1),"%"),`Left_cM`=round(left,2),`Right_cM`=round(right,2),
955
- `Left_Marker`=lm,`Right_Marker`=rm,check.names=FALSE,stringsAsFactors=FALSE)
 
 
 
 
 
 
 
 
 
 
 
956
  })
957
  do.call(rbind,Filter(Negate(is.null),rows))
958
  })
 
1
  # ============================================================
2
  # QTL MAPPING SUITE — Full Single-File Shiny Application
3
+ # MODIFIED: Dual file upload (Genotype + Phenotype separate)
4
+ # Supports: 0/1/2/-1 genotype coding, multi-environment phenotypes
5
  # 10 Models: EM, HK, MR, IM, CIM, EHK, IMP, HKPERM, NP, MQM
6
  # 10+ Plots: Genome Scan, Manhattan, Interval, Density, QQ,
7
  # Heatmap, Effects, PVE, Common QTL, Circos
 
103
  .st.acc .st-v{color:var(--acc)}
104
 
105
  /* UPLOAD ZONE */
106
+ .uzone{border:2px dashed var(--g200);border-radius:var(--rlg);padding:28px 20px;text-align:center;cursor:pointer;transition:var(--t);background:var(--g50)}
107
  .uzone:hover{border-color:var(--acc);background:var(--acclt)}
108
+ .uzone-ic{font-size:28px;margin-bottom:8px}
109
+ .uzone-t{font-size:13px;font-weight:600;color:var(--ink)}
110
+ .uzone-s{font-size:11px;color:var(--g400);margin-top:4px}
111
  .uzone .shiny-input-container{margin:0}
112
 
113
+ /* FORMAT GUIDE */
114
+ .fmt-box{background:var(--g50);border:1.5px solid var(--g100);border-radius:var(--r);padding:12px 14px;margin-top:12px}
115
+ .fmt-title{font-size:11px;font-weight:700;color:var(--g600);letter-spacing:.5px;text-transform:uppercase;margin-bottom:8px}
116
+ .fmt-table{width:100%;border-collapse:collapse;font-size:11px;font-family:var(--fm)}
117
+ .fmt-table th{background:var(--g100);padding:4px 8px;text-align:left;color:var(--g600);font-weight:600}
118
+ .fmt-table td{padding:3px 8px;color:var(--ink);border-bottom:1px solid var(--g100)}
119
+ .fmt-table tr:last-child td{border-bottom:none}
120
+ .fmt-table .hdr{color:var(--acc);font-weight:600}
121
+ .fmt-table .pos-row{color:var(--amb);font-style:italic}
122
+
123
  /* FORM */
124
  .fl{display:block;font-size:12px;font-weight:600;color:var(--g600);margin-bottom:5px;letter-spacing:.2px}
125
  .fm-g{margin-bottom:14px}
126
  .selectize-input{border:1.5px solid var(--g100)!important;border-radius:var(--rsm)!important;font-family:var(--f)!important;font-size:13px!important;padding:7px 12px!important;box-shadow:none!important}
127
  .selectize-input.focus{border-color:var(--acc)!important;box-shadow:0 0 0 3px rgba(26,107,58,.1)!important}
128
+ input[type=number],input[type=text]{width:100%;padding:8px 12px;border:1.5px solid var(--g100);border-radius:var(--rsm);font-family:var(--f);font-size:13px;outline:none}
129
+ input[type=number]:focus,input[type=text]:focus{border-color:var(--acc);box-shadow:0 0 0 3px rgba(26,107,58,.1)}
130
  .irs--shiny .irs-bar{background:var(--acc)!important}
131
  .irs--shiny .irs-handle{background:var(--acc)!important;border-color:var(--acc)!important}
132
 
 
162
  .mc:hover{border-color:var(--acc);color:var(--acc);background:var(--acclt)}
163
  .mc.sel{background:var(--acc);color:#fff;border-color:var(--acc)}
164
 
165
+ /* STATUS BADGE */
166
+ .sbadge{display:inline-flex;align-items:center;gap:5px;padding:3px 9px;border-radius:20px;font-size:11px;font-weight:600}
167
+ .sbadge-ok{background:var(--acclt);color:var(--acc);border:1px solid #b8dfc6}
168
+ .sbadge-pend{background:var(--amblt);color:var(--amb);border:1px solid #e8c070}
169
+ .sbadge-err{background:var(--redlt);color:var(--red);border:1px solid #e8a0a0}
170
+
171
  /* TIP */
172
  .tip{font-size:11px;color:var(--g400);font-style:italic;margin-top:4px}
173
 
 
215
  list(df = df, offsets = offsets, chrs = chrs)
216
  }
217
 
218
+ # ── KEY FUNCTION: Build cross from separate geno + pheno files ──
219
+ # Your genotype CSV format:
220
+ # Row 1: header → "id", marker1, marker2, ...
221
+ # Row 2: chr → "1", chrXX, chrXX, ... (e.g. "chr01")
222
+ # Row 3: pos → "0", 0.22, 0.59, ... (cM positions)
223
+ # Row 4+: data → sampleID, 0/1/2/-1, ...
224
+ #
225
+ # Genotype coding: 0=AA, 1=AB, 2=BB, -1=missing
226
+ # Phenotype CSV: Row 1 = header "id", ENV1_PL, ENV2_PL, ...
227
+ # Row 2+ = sampleID, pheno values
228
+
229
+ build_cross_from_files <- function(geno_path, pheno_path, cross_type = "bc") {
230
+
231
+ # ── Read genotype file ──────────────────────────────────────
232
+ geno_raw <- read.csv(geno_path, header = FALSE, stringsAsFactors = FALSE,
233
+ check.names = FALSE, na.strings = c("NA","","N/A"))
234
+
235
+ # Row 1 = headers, Row 2 = chr, Row 3 = position, Row 4+ = data
236
+ marker_names <- as.character(geno_raw[1, -1]) # marker IDs
237
+ chr_row <- as.character(geno_raw[2, -1]) # chromosome labels
238
+ pos_row <- suppressWarnings(as.numeric(as.character(geno_raw[3, -1]))) # cM positions
239
+ sample_ids <- as.character(geno_raw[-(1:3), 1]) # individual IDs
240
+ geno_matrix <- geno_raw[-(1:3), -1, drop = FALSE] # genotype values
241
+
242
+ # Clean chromosome names: "chr01" → "1", "chr10" → "10", etc.
243
+ chr_clean <- gsub("^chr0*", "", chr_row, ignore.case = TRUE)
244
+ chr_clean <- gsub("^0+", "", chr_clean) # remove leading zeros
245
+
246
+ # Convert genotype coding: 0→AA(1), 1→AB(2), 2→BB(3), -1→NA
247
+ # R/qtl uses: 1=AA, 2=AB(het), 3=BB for F2 / BC uses 1=AA, 2=AB
248
+ geno_num <- apply(geno_matrix, 2, function(col) {
249
+ v <- suppressWarnings(as.numeric(as.character(col)))
250
+ # Map: -1→NA, 0→1, 1→2, 2→3
251
+ mapped <- ifelse(is.na(v) | v == -1, NA,
252
+ ifelse(v == 0, 1L,
253
+ ifelse(v == 1, 2L,
254
+ ifelse(v == 2, 3L, NA))))
255
+ mapped
256
+ })
257
+ rownames(geno_num) <- sample_ids
258
+ colnames(geno_num) <- marker_names
259
+
260
+ # ── Read phenotype file ─────────────────────────────────────
261
+ pheno_raw <- read.csv(pheno_path, header = TRUE, stringsAsFactors = FALSE,
262
+ check.names = FALSE, na.strings = c("NA","","N/A"))
263
+ colnames(pheno_raw)[1] <- "id"
264
+ rownames(pheno_raw) <- as.character(pheno_raw$id)
265
+
266
+ # ── Align samples ───────────────────────────────────────────
267
+ common_ids <- intersect(sample_ids, as.character(pheno_raw$id))
268
+ if (length(common_ids) == 0)
269
+ stop("No matching sample IDs between genotype and phenotype files. Check that IDs match exactly.")
270
+
271
+ geno_aln <- geno_num[common_ids, , drop = FALSE]
272
+ pheno_aln <- pheno_raw[common_ids, -1, drop = FALSE] # drop id column
273
+
274
+ n_ind <- length(common_ids)
275
+
276
+ # ── Build genetic map ───────────────────────────────────────
277
+ uniq_chrs <- unique(chr_clean)
278
+ # Sort chromosomes numerically if possible
279
+ chr_nums <- suppressWarnings(as.numeric(uniq_chrs))
280
+ if (all(!is.na(chr_nums))) {
281
+ uniq_chrs <- uniq_chrs[order(chr_nums)]
282
+ } else {
283
+ uniq_chrs <- sort(uniq_chrs)
284
+ }
285
+
286
+ map <- vector("list", length(uniq_chrs))
287
+ names(map) <- uniq_chrs
288
+
289
+ for (ch in uniq_chrs) {
290
+ idx <- which(chr_clean == ch)
291
+ mk_pos <- pos_row[idx]
292
+ mk_nm <- marker_names[idx]
293
+ names(mk_pos) <- mk_nm
294
+ map[[ch]] <- mk_pos
295
+ }
296
+
297
+ # ── Build geno list (by chromosome) ─────────────────────────
298
+ geno_list <- vector("list", length(uniq_chrs))
299
+ names(geno_list) <- uniq_chrs
300
+
301
+ for (ch in uniq_chrs) {
302
+ idx <- which(chr_clean == ch)
303
+ mat <- geno_aln[, idx, drop = FALSE]
304
+ storage.mode(mat) <- "integer"
305
+ geno_list[[ch]] <- list(data = mat, map = map[[ch]])
306
+ class(geno_list[[ch]]) <- "A"
307
+ }
308
+
309
+ # ── Assemble cross object ────────────────────────────────────
310
+ cross <- list(
311
+ geno = geno_list,
312
+ pheno = as.data.frame(pheno_aln, stringsAsFactors = FALSE)
313
+ )
314
+
315
+ # Coerce pheno columns to numeric
316
+ for (j in seq_len(ncol(cross$pheno))) {
317
+ cross$pheno[, j] <- suppressWarnings(as.numeric(as.character(cross$pheno[, j])))
318
+ }
319
+
320
+ rownames(cross$pheno) <- common_ids
321
+ class(cross) <- c(cross_type, "cross")
322
+
323
+ # ── Basic validation ─────────────────────────────────────────
324
+ cross <- jittermap(cross) # avoid duplicate map positions
325
+
326
+ return(list(
327
+ cross = cross,
328
+ n_ind = n_ind,
329
+ n_markers = length(marker_names),
330
+ n_chr = length(uniq_chrs),
331
+ n_pheno = ncol(pheno_aln),
332
+ pheno_names = colnames(pheno_aln),
333
+ sample_ids = common_ids,
334
+ skipped_ids = setdiff(sample_ids, common_ids)
335
+ ))
336
+ }
337
+
338
  # ── UI ────────────────────────────────────────────────────────
339
  ui <- fluidPage(
340
  useShinyjs(),
 
364
  div(class="qtl-top",
365
  div(class="tlmark","Q"),
366
  span(class="tlname","QTL Mapping Suite"),
367
+ span(class="tlver","v2.1"),
368
  div(class="tldiv"),
369
  div(class="stpill", div(class="dot"), span(id="stlbl","Ready")),
370
  div(class="tlright",
 
400
  # MAIN
401
  div(class="qtl-main",
402
 
403
+ # ── UPLOAD PAGE ─────────────────────────────────────────
404
+ div(id="pg-upload", class="pg active",
405
+ div(class="ph",
406
+ div(class="pt","Upload Data Files"),
407
+ div(class="ps","Upload genotype and phenotype files separately — or load the built-in demo")
408
+ ),
409
+
410
+ # File format guide
411
+ div(class="card",
412
+ div(class="ch",
413
+ div(div(class="ct","Expected File Formats"), div(class="cst","Your exact format is supported"))
414
+ ),
415
+ div(class="cb",
416
+ div(class="g2",
417
+ div(
418
+ div(class="fmt-title","GENOTYPE CSV"),
419
+ tags$table(class="fmt-table",
420
+ tags$thead(tags$tr(tags$th("Row"),tags$th("Col 1"),tags$th("Col 2+"))),
421
+ tags$tbody(
422
+ tags$tr(tags$td(class="hdr","Row 1 (Header)"),tags$td(class="hdr","id / genotypic data id"),tags$td(class="hdr","marker names (e.g. chr01_194844)")),
423
+ tags$tr(tags$td(class="pos-row","Row 2 (Chr)"),tags$td(class="pos-row","1"),tags$td(class="pos-row","chromosome (e.g. 1)")),
424
+ tags$tr(tags$td(class="pos-row","Row 3 (Pos)"),tags$td(class="pos-row","0"),tags$td(class="pos-row","position in cM (e.g. 0.22)")),
425
+ tags$tr(tags$td("Row 4+"),tags$td("Sample ID"),tags$td("Genotype: 0=AA, 1=AB, 2=BB, -1=missing"))
426
+ )
427
+ )
428
+ ),
429
+ div(
430
+ div(class="fmt-title","PHENOTYPE CSV"),
431
+ tags$table(class="fmt-table",
432
+ tags$thead(tags$tr(tags$th("Row"),tags$th("Col 1"),tags$th("Col 2+"))),
433
+ tags$tbody(
434
+ tags$tr(tags$td(class="hdr","Row 1 (Header)"),tags$td(class="hdr","id"),tags$td(class="hdr","trait names (e.g. ENV1_PL)")),
435
+ tags$tr(tags$td("Row 2+"),tags$td("Sample ID"),tags$td("Numeric phenotype values"))
436
+ )
437
+ ),
438
+ div(style="margin-top:10px;",
439
+ div(class="al al-info", "ℹ",
440
+ div("Sample IDs must match exactly between the two files. Missing values can be NA or blank.")
441
+ )
442
+ )
443
+ )
444
+ )
445
+ )
446
+ ),
447
+
448
+ # Upload cards
449
  div(class="g2",
450
+ # Genotype upload
451
  div(class="card",
452
+ div(class="ch",
453
+ div(div(class="ct","Genotype File"), div(class="cst","CSV with chr/pos rows")),
454
+ uiOutput("geno_badge")
455
+ ),
456
  div(class="cb",
457
  div(class="uzone",
458
  div(class="uzone-ic","🧬"),
459
+ div(class="uzone-t","Drop Genotype CSV"),
460
+ div(class="uzone-s","Row 2 = chromosome, Row 3 = cM position, Row 4+ = samples"),
461
+ fileInput("geno_file", NULL, accept=c(".csv",".CSV"),
462
+ buttonLabel="Browse", placeholder="No file selected")
463
  ),
464
+ div(class="tip","Genotype codes: 0=AA, 1=AB, 2=BB, -1=missing")
465
  )
466
  ),
467
+ # Phenotype upload
468
  div(class="card",
469
+ div(class="ch",
470
+ div(div(class="ct","Phenotype File"), div(class="cst","CSV with trait columns")),
471
+ uiOutput("pheno_badge")
472
+ ),
473
  div(class="cb",
474
+ div(class="uzone",
475
+ div(class="uzone-ic","📊"),
476
+ div(class="uzone-t","Drop Phenotype CSV"),
477
+ div(class="uzone-s","Multiple environments / traits supported as separate columns"),
478
+ fileInput("pheno_file", NULL, accept=c(".csv",".CSV"),
479
+ buttonLabel="Browse", placeholder="No file selected")
480
+ ),
481
+ div(class="tip","First column = sample ID, remaining columns = trait values")
482
  )
483
  )
484
  ),
485
+
486
+ # Cross settings + load buttons
487
+ div(class="card",
488
+ div(class="ch", div(div(class="ct","Cross Settings & Load"))),
489
+ div(class="cb",
490
+ div(class="g2",
491
+ div(
492
+ div(class="fm-g", label(class="fl","Cross Type"),
493
+ selectInput("cross_type", NULL,
494
+ choices=c(
495
+ "Backcross"="bc",
496
+ "F2 Intercross"="f2",
497
+ "RIL by selfing"="riself",
498
+ "RIL by sibling"="risib",
499
+ "Doubled Haploid"="dh"
500
+ ),
501
+ selected="bc", width="100%"
502
+ )
503
+ ),
504
+ div(class="tip","Choose 'Backcross' if your genotype codes are only 0 and 1 (AA and AB).")
505
+ ),
506
+ div(
507
+ div(class="fm-g", label(class="fl","Missing Genotype Value"),
508
+ selectInput("miss_val", NULL,
509
+ choices=c("-1 (default)"="-1","NA"="NA","0"="0"),
510
+ selected="-1", width="100%"
511
+ )
512
+ )
513
+ )
514
+ ),
515
+ div(class="br",
516
+ actionButton("load_data", "⬆ Load Files", class="btn-p"),
517
+ actionButton("load_demo", "🌿 Load Listeria Demo", class="btn-s")
518
+ ),
519
+ br(),
520
+ uiOutput("upload_status_msg")
521
+ )
522
+ ),
523
+
524
  uiOutput("upload_summary")
525
  ),
526
 
 
720
  div(class="cb", withSpinner(DTOutput("tbl_full"),color="#1a6b3a"))
721
  )
722
  )
723
+
724
+ ) # /qtl-main
725
+ ) # /qtl-lay
726
  )
727
 
728
  # ── SERVER ────────────────────────────────────────────────────
729
  server <- function(input, output, session) {
730
 
731
  rv <- reactiveValues(
732
+ cross = NULL,
733
+ scan_list = list(),
734
+ sig_qtl = list(),
735
+ log_msgs = character(0),
736
+ running = FALSE,
737
+ pheno_name = "Phenotype",
738
+ geno_ok = FALSE,
739
+ pheno_ok = FALSE,
740
+ load_msg = NULL,
741
+ load_ok = FALSE
742
  )
743
 
744
+ add_log <- function(msg) {
745
+ rv$log_msgs <- c(rv$log_msgs, paste0("[", format(Sys.time(),"%H:%M:%S"), "] ", msg))
746
+ }
747
+
748
+ # ── FILE STATUS BADGES ──
749
+ output$geno_badge <- renderUI({
750
+ if (rv$geno_ok) div(class="sbadge sbadge-ok","✓ Loaded")
751
+ else if (!is.null(input$geno_file)) div(class="sbadge sbadge-pend","⏳ Pending")
752
+ else div(class="sbadge sbadge-pend","○ Not loaded")
753
+ })
754
+
755
+ output$pheno_badge <- renderUI({
756
+ if (rv$pheno_ok) div(class="sbadge sbadge-ok","✓ Loaded")
757
+ else if (!is.null(input$pheno_file)) div(class="sbadge sbadge-pend","⏳ Pending")
758
+ else div(class="sbadge sbadge-pend","○ Not loaded")
759
+ })
760
 
761
  # ── LOAD DEMO ──
762
  observeEvent(input$load_demo, {
763
+ withProgress(message="Loading Listeria demo…", {
764
  tryCatch({
765
  data(listeria, package="qtl")
766
+ rv$cross <- listeria
767
+ rv$geno_ok <- TRUE
768
+ rv$pheno_ok <- TRUE
769
+ rv$load_ok <- TRUE
770
+ rv$load_msg <- "Listeria demo loaded successfully (F2, 20 chr, 133 markers, 1 phenotype)"
771
+ rv$log_msgs <- character(0)
772
+ add_log("Loaded Listeria demo (F2, 20 chr, 133 markers)")
773
+ showNotification("Listeria dataset loaded!", type="message", duration=3)
774
  shinyjs::runjs("$('.nv').removeClass('active');$('[data-page=explore]').addClass('active');$('.pg').removeClass('active');$('#pg-explore').addClass('active');")
775
+ }, error = function(e) {
776
+ rv$load_ok <- FALSE
777
+ rv$load_msg <- paste("Error:", e$message)
778
+ showNotification(paste("Error:", e$message), type="error")
779
+ })
780
  })
781
  })
782
 
783
+ # ── LOAD USER FILES ──
784
  observeEvent(input$load_data, {
785
+ if (is.null(input$geno_file)) {
786
+ showNotification("Please upload a genotype CSV file first.", type="warning"); return()
787
+ }
788
+ if (is.null(input$pheno_file)) {
789
+ showNotification("Please upload a phenotype CSV file first.", type="warning"); return()
790
+ }
791
+
792
+ withProgress(message="Building cross object…", value=0, {
793
  tryCatch({
794
+ incProgress(0.3, detail="Reading files…")
795
+ result <- build_cross_from_files(
796
+ geno_path = input$geno_file$datapath,
797
+ pheno_path = input$pheno_file$datapath,
798
+ cross_type = input$cross_type
799
+ )
800
+
801
+ incProgress(0.5, detail="Checking cross…")
802
+ rv$cross <- result$cross
803
+ rv$geno_ok <- TRUE
804
+ rv$pheno_ok <- TRUE
805
+ rv$load_ok <- TRUE
806
+ rv$log_msgs <- character(0)
807
+
808
+ msg <- paste0(
809
+ "Loaded: ", result$n_ind, " individuals, ",
810
+ result$n_markers, " markers, ",
811
+ result$n_chr, " chromosomes, ",
812
+ result$n_pheno, " phenotype(s): ",
813
+ paste(result$pheno_names, collapse=", ")
814
+ )
815
+ if (length(result$skipped_ids) > 0) {
816
+ msg <- paste0(msg, " | Skipped ", length(result$skipped_ids),
817
+ " IDs not found in phenotype file")
818
+ }
819
+ rv$load_msg <- msg
820
+ add_log(msg)
821
+
822
+ incProgress(0.2, detail="Done")
823
+ showNotification("Data loaded successfully!", type="message", duration=4)
824
+ shinyjs::runjs("$('.nv').removeClass('active');$('[data-page=explore]').addClass('active');$('.pg').removeClass('active');$('#pg-explore').addClass('active');")
825
+
826
+ }, error = function(e) {
827
+ rv$geno_ok <- FALSE
828
+ rv$pheno_ok <- FALSE
829
+ rv$load_ok <- FALSE
830
+ rv$load_msg <- paste("Load error:", e$message)
831
+ add_log(paste("ERROR:", e$message))
832
+ showNotification(paste("Load error:", e$message), type="error", duration=8)
833
+ })
834
  })
835
  })
836
 
837
+ # ── UPLOAD STATUS MESSAGE ──
838
+ output$upload_status_msg <- renderUI({
839
+ req(!is.null(rv$load_msg))
840
+ if (rv$load_ok) {
841
+ div(class="al al-ok", "✓", div(div(style="font-weight:600;","Success"), div(rv$load_msg)))
842
+ } else {
843
+ div(class="al al-err", "✗", div(div(style="font-weight:600;","Error"), div(rv$load_msg)))
844
+ }
845
+ })
846
+
847
  # ── UPLOAD SUMMARY ──
848
  output$upload_summary <- renderUI({
849
  req(rv$cross); cr <- rv$cross
850
  div(class="card",
851
+ div(class="ch", div(div(class="ct","Dataset Summary"))),
852
  div(class="cb",
853
  div(class="g4",
854
+ div(class="st acc", div(class="st-l","Individuals"), div(class="st-v", nind(cr))),
855
+ div(class="st", div(class="st-l","Markers"), div(class="st-v", totmar(cr))),
856
+ div(class="st", div(class="st-l","Chromosomes"), div(class="st-v", nchr(cr))),
857
+ div(class="st", div(class="st-l","Phenotypes"), div(class="st-v", nphe(cr)))
858
+ ),
859
+ br(),
860
+ # Show phenotype names
861
+ div(class="tip",
862
+ paste("Phenotypes:", paste(phenames(cr), collapse=", "))
863
  )
864
  )
865
  )
 
869
  output$stat_tiles <- renderUI({
870
  req(rv$cross); cr <- rv$cross
871
  tagList(
872
+ div(class="st acc", div(class="st-l","Individuals"), div(class="st-v", nind(cr))),
873
+ div(class="st", div(class="st-l","Markers"), div(class="st-v", totmar(cr))),
874
+ div(class="st", div(class="st-l","Chromosomes"), div(class="st-v", nchr(cr))),
875
+ div(class="st", div(class="st-l","Phenotypes"), div(class="st-v", nphe(cr)))
876
  )
877
  })
878
 
879
+ # ── EXPLORE TABS ──
880
  output$explore_content <- renderUI({
881
  tab <- if(is.null(input$tab_ex)) "pheno" else input$tab_ex
882
  req(rv$cross)
883
  if (tab=="pheno") {
884
+ div(class="card",
885
+ div(class="ch",
886
+ div(class="ct","Phenotype Distribution"),
887
+ uiOutput("ex_pheno_sel_ui")
888
+ ),
889
+ div(class="cb", withSpinner(plotlyOutput("pl_ex_pheno",height="320px"),color="#1a6b3a"))
890
+ )
891
  } else if (tab=="map") {
892
  div(class="card",div(class="ch",div(class="ct","Genetic Map")),div(class="cb",withSpinner(plotlyOutput("pl_ex_map",height="380px"),color="#1a6b3a")))
893
  } else if (tab=="miss") {
 
897
  }
898
  })
899
 
900
+ output$ex_pheno_sel_ui <- renderUI({
901
+ req(rv$cross)
902
+ pn <- phenames(rv$cross)
903
+ if (length(pn) > 1) {
904
+ selectInput("ex_pheno_col", NULL, choices=pn, selected=pn[1], width="200px")
905
+ }
906
+ })
907
+
908
  output$pl_ex_pheno <- renderPlotly({
909
+ req(rv$cross)
910
+ pn <- phenames(rv$cross)
911
+ sel <- if(!is.null(input$ex_pheno_col) && input$ex_pheno_col %in% pn) input$ex_pheno_col else pn[1]
912
+ phe <- pull.pheno(rv$cross, which(pn==sel))
913
+ df <- data.frame(y=phe)
914
+ p <- ggplot(df, aes(x=y)) +
915
+ geom_histogram(aes(y=after_stat(density)),bins=30,fill="#1a6b3a",color="white",alpha=.85) +
916
+ geom_density(color="#c47c1a",linewidth=1) +
917
+ labs(x=sel,y="Density",title=paste("Phenotype:",sel)) +
918
+ theme_minimal() + theme(panel.grid.minor=element_blank())
919
+ ggplotly(p) %>% layout(font=list(family="DM Sans"))
920
  })
921
 
922
  output$pl_ex_map <- renderPlotly({
923
  req(rv$cross); map <- pull.map(rv$cross)
924
  df <- do.call(rbind,lapply(names(map),function(c) data.frame(chr=c,pos=map[[c]],marker=names(map[[c]]),stringsAsFactors=FALSE)))
925
  df$cn <- as.numeric(factor(df$chr,levels=names(map)))
926
+ p <- ggplot(df,aes(x=pos,y=cn,text=paste0("Marker:",marker,"<br>Chr:",chr,"<br>Pos:",round(pos,2),"cM")))+
927
+ geom_line(aes(group=chr),color="#d0d0cc",linewidth=.5)+geom_point(color="#1a6b3a",size=2.5,alpha=.8)+
928
+ scale_y_continuous(breaks=unique(df$cn),labels=names(map))+
929
+ labs(x="Position (cM)",y="Chromosome",title="Genetic Map")+theme_minimal()+theme(panel.grid.minor=element_blank())
930
  ggplotly(p,tooltip="text")%>%layout(font=list(family="DM Sans"))
931
  })
932
 
933
  output$pl_ex_miss <- renderPlotly({
934
  req(rv$cross); gt <- pull.geno(rv$cross)
935
  mp <- colMeans(is.na(gt))*100; df <- data.frame(marker=names(mp),pct=mp,idx=seq_along(mp))
936
+ p <- ggplot(df,aes(x=idx,y=pct,text=paste0("Marker:",marker,"<br>Missing:",round(pct,1),"%")))+
937
+ geom_col(fill="#1a4a8a",alpha=.7)+labs(x="Marker Index",y="Missing (%)",title="Missing Genotype Data")+theme_minimal()+theme(panel.grid.minor=element_blank())
938
  ggplotly(p,tooltip="text")%>%layout(font=list(family="DM Sans"))
939
  })
940
 
941
  output$pl_ex_gf <- renderPlotly({
942
  req(rv$cross); gt <- pull.geno(rv$cross)
943
+ # Determine max genotype code
944
+ max_g <- max(gt,na.rm=TRUE)
945
+ lvls <- 1:max(max_g,3)
946
+ lbl <- c("1"="AA","2"="AB","3"="BB")
947
+ cnts <- apply(gt, 2, function(x) table(factor(x, levels=lvls)))
948
+ df <- as.data.frame(t(cnts)); df$marker <- rownames(df)
949
+ cn <- intersect(c("1","2","3"), colnames(df))
950
+ names(df)[names(df) %in% cn] <- lbl[cn]
951
+ gn <- intersect(c("AA","AB","BB"), names(df))
952
+ dl <- tidyr::pivot_longer(df, all_of(gn), names_to="geno", values_to="count")
953
+ dl$idx <- match(dl$marker, unique(dl$marker))
954
+ p <- ggplot(dl,aes(x=idx,y=count,fill=geno,text=paste0("Marker:",marker,"<br>Geno:",geno,"<br>N:",count)))+
955
+ geom_col(position="fill",width=1)+
956
+ scale_fill_manual(values=c(AA="#1a6b3a",AB="#c47c1a",BB="#1a4a8a"))+
957
+ labs(x="Marker Index",y="Proportion",fill="Genotype")+theme_minimal()+theme(panel.grid.minor=element_blank())
958
  ggplotly(p,tooltip="text")%>%layout(font=list(family="DM Sans"))
959
  })
960
 
961
  # ── CONFIG SELECTS ──
962
  output$pheno_sel <- renderUI({
963
+ req(rv$cross)
964
+ pn <- phenames(rv$cross)
965
  selectInput("pheno_col",NULL,choices=pn,selected=pn[1],width="100%")
966
  })
967
+
968
  output$chr_sel <- renderUI({
969
+ req(rv$cross)
970
+ ch <- chrnames(rv$cross)
971
  checkboxGroupInput("scan_chrs",NULL,choices=ch,selected=ch,inline=TRUE)
972
  })
973
 
 
977
  pn <- if(is.null(input$pheno_col)) "—" else input$pheno_col
978
  thr <- if(is.null(input$lod_thr)) 3.0 else input$lod_thr
979
  div(
980
+ div(class="al al-info","ℹ",div(
981
+ div(style="font-weight:600;","Configured"),
982
+ div(paste("Phenotype:",pn,"| Models:",length(mods),"| Threshold:",thr,"| Permutations:",input$n_perm))
983
+ )),
984
  div(class="mchips",lapply(mods,function(m) div(class="mc sel",`data-model`=m,MODEL_LABELS[m])))
985
  )
986
  })
 
1010
  req(rv$cross)
1011
  mods <- if(is.null(input$sel_models)||!length(input$sel_models)) c("em","hk") else input$sel_models
1012
  phe_col <- if(is.null(input$pheno_col)) 1 else which(phenames(rv$cross)==input$pheno_col)[1]
1013
+ if(is.na(phe_col) || length(phe_col)==0) phe_col <- 1
1014
+ step <- if(is.null(input$step_sz)) 2 else input$step_sz
1015
+ ep <- if(is.null(input$err_prob)) 0.001 else input$err_prob
1016
+ thr <- if(is.null(input$lod_thr)) 3.0 else input$lod_thr
1017
+ n_perm <- if(is.null(input$n_perm)) 0 else input$n_perm
1018
+ n_imp <- if(is.null(input$n_imp)) 32 else input$n_imp
1019
+
1020
+ rv$running <- TRUE
1021
+ rv$scan_list <- list()
1022
+ rv$sig_qtl <- list()
1023
+ rv$log_msgs <- character(0)
1024
  rv$pheno_name <- phenames(rv$cross)[phe_col]
1025
 
1026
+ withProgress(message="Running QTL scan…", value=0, {
1027
  tryCatch({
1028
  add_log("Computing conditional genotype probabilities…")
1029
+ rv$cross <- calc.genoprob(rv$cross, step=step, error.prob=ep)
1030
  incProgress(0.1)
1031
+
1032
+ if("imp" %in% mods) {
1033
+ add_log("Simulating genotypes for imputation…")
1034
+ rv$cross <- sim.geno(rv$cross, n.draws=n_imp, step=step, error.prob=ep)
1035
+ }
1036
 
1037
  for(i in seq_along(mods)){
1038
+ m <- mods[i]
1039
+ add_log(paste("Model:", MODEL_LABELS[m], "…"))
1040
+ incProgress(0.8/length(mods), detail=MODEL_LABELS[m])
1041
+
1042
  res <- tryCatch({
1043
  switch(m,
1044
+ em = scanone(rv$cross, pheno.col=phe_col, method="em"),
1045
+ hk = scanone(rv$cross, pheno.col=phe_col, method="hk"),
1046
+ mr = scanone(rv$cross, pheno.col=phe_col, method="mr"),
1047
+ im = scanone(rv$cross, pheno.col=phe_col, method="em"),
1048
+ ehk = scanone(rv$cross, pheno.col=phe_col, method="ehk"),
1049
+ imp = scanone(rv$cross, pheno.col=phe_col, method="imp"),
1050
+ hkperm = scanone(rv$cross, pheno.col=phe_col, method="hk"),
1051
+ scanone_np = scanone(rv$cross, pheno.col=phe_col, method="np"),
1052
+ cim = cim(rv$cross, pheno.col=phe_col, method="hk"),
1053
+ mqm = tryCatch(
1054
+ mqmscan(rv$cross, pheno.col=phe_col),
1055
+ error=function(e) scanone(rv$cross, pheno.col=phe_col, method="hk")
1056
+ ),
1057
+ scanone(rv$cross, pheno.col=phe_col, method="hk")
1058
  )
1059
+ }, error=function(e){
1060
+ add_log(paste(" ✗", m, ":", e$message, "→ fallback HK"))
1061
+ scanone(rv$cross, pheno.col=phe_col, method="hk")
1062
+ })
1063
 
1064
  rv$scan_list[[m]] <- res
1065
+ lc <- ncol(res)
1066
+ sig <- res[res[, lc] >= thr, ]
1067
+ if(nrow(sig) > 0){
1068
+ sig$model <- MODEL_LABELS[m]
1069
+ sig$model_id <- m
1070
+ sig$marker <- rownames(sig)
1071
+ sig$pve <- round(100*(1-exp(-2*sig[,lc]/nind(rv$cross))), 2)
1072
+ }
1073
  rv$sig_qtl[[m]] <- sig
1074
+ add_log(paste(" ✓", MODEL_LABELS[m], "peaks:", nrow(sig)))
1075
  }
1076
+
1077
+ # Optional permutation for hkperm
1078
+ if("hkperm" %in% mods && n_perm > 0) {
1079
+ add_log(paste("Running", n_perm, "permutations for HK…"))
1080
+ perm <- scanone(rv$cross, pheno.col=phe_col, method="hk", n.perm=n_perm, verbose=FALSE)
1081
+ thr_perm <- summary(perm, alpha=0.05)[1]
1082
+ add_log(paste(" Permutation threshold (5%):", round(thr_perm, 2)))
1083
+ }
1084
+
1085
+ rv$running <- FALSE
1086
+ incProgress(0.1)
1087
+ add_log(paste("All", length(mods), "models completed."))
1088
+ showNotification("Scan complete!", type="message", duration=3)
1089
+
1090
+ }, error=function(e){
1091
+ rv$running <- FALSE
1092
+ add_log(paste("FATAL:", e$message))
1093
+ showNotification(paste("Error:", e$message), type="error")
1094
+ })
1095
  })
1096
  })
1097
 
1098
+ observeEvent(input$clr_res,{
1099
+ rv$scan_list <- list(); rv$sig_qtl <- list(); rv$log_msgs <- character(0)
1100
+ })
1101
 
1102
  # ── REACTIVE HELPERS ──
1103
  comb_df <- reactive({
1104
  req(length(rv$scan_list)>0)
1105
  do.call(rbind,lapply(names(rv$scan_list),function(m){
1106
  sc <- rv$scan_list[[m]]; lc <- ncol(sc)
1107
+ data.frame(chr=as.character(sc$chr),pos=sc$pos,lod=sc[,lc],
1108
+ model=MODEL_LABELS[m],model_id=m,marker=rownames(sc),
1109
+ stringsAsFactors=FALSE)
1110
  }))
1111
  })
1112
 
 
1130
  sel <- if(!is.null(input$gm_msel)) input$gm_msel else unique(df$model_id)
1131
  df <- df[df$model_id %in% sel,]; thr <- thresh_val()
1132
  res <- cum_positions(df); df <- res$df; offsets <- res$offsets; chrs <- res$chrs
 
1133
  p <- ggplot(df,aes(x=cum_pos,y=lod,color=model,text=paste0("Chr:",chr,"<br>Pos:",round(pos,1),"cM<br>LOD:",round(lod,2),"<br>Model:",model)))+
1134
  geom_line(linewidth=.7,alpha=.88)+
1135
  geom_hline(yintercept=thr,linetype="dashed",color="#b83232",linewidth=.6)+
 
1221
 
1222
  output$pl_eff <- renderPlotly({
1223
  req(rv$cross,length(rv$scan_list)>0)
1224
+ ch <- if(is.null(input$eff_chr)) chrnames(rv$cross)[1] else input$eff_chr
1225
  sc <- rv$scan_list[[names(rv$scan_list)[1]]]; lc <- ncol(sc)
1226
  scc <- sc[sc$chr==ch,]; if(!nrow(scc)) return(plotly_empty())
1227
+ pm <- find.marker(rv$cross, ch, scc$pos[which.max(scc[,lc])])
1228
+ eff <- effectplot(rv$cross, mname1=pm, pheno.col=1, draw=FALSE)
1229
  df <- data.frame(geno=names(eff$Means),mean=as.numeric(eff$Means),sd=as.numeric(eff$SDs),n=as.numeric(eff$n))
1230
  df$se <- df$sd/sqrt(df$n)
1231
  p <- ggplot(df,aes(x=geno,y=mean,fill=geno,text=paste0("Geno:",geno,"<br>Mean:",round(mean,3),"<br>SE:",round(se,3))))+
 
1237
 
1238
  output$peak_sel <- renderUI({
1239
  req(length(rv$sig_qtl)>0); sd <- sig_df(); req(!is.null(sd))
 
1240
  ch <- paste0(sd$chr," @ ",round(sd$pos,1),"cM (",sd$model_id,")")
1241
  selectInput("pk_sel",NULL,choices=ch,width="100%")
1242
  })
 
1244
  output$pl_violin <- renderPlotly({
1245
  req(rv$cross,length(rv$sig_qtl)>0,!is.null(input$pk_sel))
1246
  sd <- sig_df(); req(!is.null(sd))
1247
+ idx <- which(paste0(sd$chr," @ ",round(sd$pos,1),"cM (",sd$model_id,")")==input$pk_sel)[1]
1248
+ req(!is.na(idx))
1249
  row <- sd[idx,]
1250
  mar <- tryCatch(find.marker(rv$cross,row$chr,row$pos),error=function(e) row$marker)
1251
  gt <- pull.geno(rv$cross)[,mar]; phe <- pull.pheno(rv$cross,1)
1252
+ # Support both 2-genotype (bc) and 3-genotype (f2)
1253
+ max_g <- max(gt,na.rm=TRUE)
1254
+ if(max_g <= 2) {
1255
+ gl <- c("1"="AA","2"="AB")
1256
+ } else {
1257
+ gl <- c("1"="AA","2"="AB","3"="BB")
1258
+ }
1259
+ bdf <- data.frame(geno=factor(gl[as.character(gt)],levels=gl),pheno=phe)%>%filter(!is.na(geno),!is.na(pheno))
1260
+ cols <- c(AA="#1a6b3a",AB="#c47c1a",BB="#1a4a8a")
1261
+ p <- ggplot(bdf,aes(x=geno,y=pheno,fill=geno))+
1262
+ geom_violin(alpha=.4,draw_quantiles=c(.25,.5,.75))+
1263
+ geom_jitter(aes(color=geno),width=.15,size=1.5,alpha=.6)+
1264
+ scale_fill_manual(values=cols)+scale_color_manual(values=cols)+
1265
+ labs(x="Genotype",y=rv$pheno_name,title=paste("Phenotype at",mar))+
1266
+ theme_minimal()+theme(legend.position="none")
1267
  ggplotly(p)%>%layout(font=list(family="DM Sans"))
1268
  })
1269
 
 
1312
  map <- pull.map(rv$cross); cnms <- names(map); clens <- sapply(map,max)
1313
  par(bg="white",mar=c(0,0,2,0))
1314
  circos.clear()
1315
+ circos.par("track.height"=0.08,"cell.padding"=c(0,0,0,0),
1316
+ "gap.after"=rep(2,length(cnms)),"start.degree"=90,"clock.wise"=TRUE,
1317
+ "background.color"="#ffffff",canvas.xlim=c(-1.25,1.25),canvas.ylim=c(-1.25,1.25))
1318
  circos.initialize(factors=cnms,xlim=cbind(rep(0,length(cnms)),clens))
1319
  circos.trackPlotRegion(ylim=c(0,1),track.height=0.05,bg.border=NA,bg.col="#f4f4f2",
1320
+ panel.fun=function(x,y){
1321
+ chr<-get.cell.meta.data("sector.index")
1322
+ circos.text(mean(get.cell.meta.data("xlim")),0.5,chr,facing="clockwise",niceFacing=TRUE,cex=.6,col="#2a2a27",font=2)
1323
+ })
1324
  mpal <- c("#1a6b3a","#2d9e58","#c47c1a","#1a4a8a","#b83232","#7b3fa0","#1a8a8a","#8a5a1a","#555555","#e05c00")
1325
  for(mi in seq_along(mods)){
1326
  m <- mods[mi]; mc <- mpal[((mi-1)%%length(mpal))+1]; mclt <- paste0(mc,"44")
 
1358
  lm <- tryCatch(find.marker(rv$cross,r$chr,left),error=function(e)"—")
1359
  rm <- tryCatch(find.marker(rv$cross,r$chr,right),error=function(e)"—")
1360
  pm <- tryCatch(find.marker(rv$cross,r$chr,r$pos),error=function(e) r$marker)
1361
+ data.frame(
1362
+ Phenotype = rv$pheno_name,
1363
+ Model = r$model,
1364
+ Chr = r$chr,
1365
+ Peak_pos_cM = round(r$pos,2),
1366
+ Peak_Marker = pm,
1367
+ LOD = round(r[,lc],3),
1368
+ `PVE_%` = paste0(round(r$pve,1),"%"),
1369
+ Left_cM = round(left,2),
1370
+ Right_cM = round(right,2),
1371
+ Left_Marker = lm,
1372
+ Right_Marker= rm,
1373
+ check.names = FALSE,
1374
+ stringsAsFactors=FALSE
1375
+ )
1376
  })
1377
  do.call(rbind,Filter(Negate(is.null),rows))
1378
  })