softwareDevelopment commited on
Commit
d8d24f8
Β·
verified Β·
1 Parent(s): 88c0d31

Update app.R

Browse files
Files changed (1) hide show
  1. app.R +1418 -386
app.R CHANGED
@@ -1,497 +1,1529 @@
1
- library(shiny)
2
- library(qtl)
3
- library(ggplot2)
4
- library(dplyr)
5
- library(tidyr)
6
- library(DT)
7
- library(shinycssloaders)
8
- library(shinyjs)
9
- library(plotly)
10
- library(gridExtra)
11
- library(scales)
12
-
13
- # ========================== CUSTOM PARSER ==========================
14
- parse_custom_cross <- function(geno_path, pheno_path, cross_type = "f2") {
15
- tryCatch({
16
- geno_raw <- read.csv(geno_path, header = FALSE, stringsAsFactors = FALSE,
17
- check.names = FALSE, na.strings = c("NA", "", "N/A"))
18
-
19
- col_names <- as.character(geno_raw[1, ])
20
- chr_row <- as.character(geno_raw[2, ])
21
- pos_row <- as.character(geno_raw[3, ])
22
- ind_data <- geno_raw[4:nrow(geno_raw), , drop = FALSE]
23
-
24
- marker_cols <- 2:ncol(geno_raw)
25
- marker_names <- col_names[marker_cols]
26
- chromosomes <- gsub("^[Cc]hr0*", "", chr_row[marker_cols])
27
- positions <- suppressWarnings(as.numeric(pos_row[marker_cols]))
28
-
29
- chr_num <- suppressWarnings(as.integer(chromosomes))
30
- chromosomes <- ifelse(!is.na(chr_num), as.character(chr_num), chromosomes)
31
-
32
- ind_ids <- as.character(ind_data[, 1])
33
- geno_mat <- as.matrix(ind_data[, marker_cols, drop = FALSE])
34
- geno_mat <- apply(geno_mat, 2, function(x) suppressWarnings(as.numeric(x)))
35
- rownames(geno_mat) <- ind_ids
36
- colnames(geno_mat) <- marker_names
37
- geno_mat[geno_mat == 0] <- NA
38
- storage.mode(geno_mat) <- "integer"
39
-
40
- # Phenotype
41
- pheno_raw <- read.csv(pheno_path, header = TRUE, stringsAsFactors = FALSE,
42
- check.names = FALSE, na.strings = c("NA", "", "N/A"))
43
- pheno_ids <- as.character(pheno_raw[, 1])
44
- pheno_df <- as.data.frame(lapply(pheno_raw[,-1, drop=FALSE],
45
- function(x) suppressWarnings(as.numeric(x))))
46
- rownames(pheno_df) <- pheno_ids
47
-
48
- common_ids <- intersect(ind_ids, pheno_ids)
49
- if (length(common_ids) == 0) stop("No matching IDs between genotype and phenotype files.")
50
-
51
- geno_mat <- geno_mat[common_ids, , drop = FALSE]
52
- pheno_df <- pheno_df[common_ids, , drop = FALSE]
53
-
54
- # Map
55
- unique_chrs <- unique(chromosomes)
56
- chr_num <- suppressWarnings(as.integer(unique_chrs))
57
- ord <- order(ifelse(!is.na(chr_num), chr_num, 999L), unique_chrs)
58
- unique_chrs <- unique_chrs[ord]
59
-
60
- map_list <- lapply(unique_chrs, function(ch) {
61
- idx <- which(chromosomes == ch)
62
- pos <- positions[idx]
63
- mnames <- marker_names[idx]
64
- ord2 <- order(pos)
65
- m <- pos[ord2]; names(m) <- mnames[ord2]; m
66
- })
67
- names(map_list) <- unique_chrs
68
-
69
- # Build cross
70
- geno_list <- lapply(unique_chrs, function(ch) {
71
- idx <- which(chromosomes == ch)
72
- mnames <- marker_names[idx]
73
- pos_ch <- positions[idx]
74
- ord2 <- order(pos_ch)
75
- mnames <- mnames[ord2]
76
- g_chr <- geno_mat[, mnames, drop = FALSE]
77
- list(data = g_chr, map = map_list[[ch]])
78
- })
79
- names(geno_list) <- unique_chrs
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
 
81
- cross_obj <- list(geno = geno_list, pheno = pheno_df)
82
- class(cross_obj) <- c(cross_type, "cross")
83
- cross_obj <- jittermap(cross_obj)
84
 
85
- if (cross_type == "f2") {
86
- cross_obj <- tryCatch(convert2bcsft(cross_obj, BC.gen = 0, F.gen = 2, estimate.map = FALSE),
87
- error = function(e) cross_obj)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88
  }
89
- cross_obj
90
- }, error = function(e) stop(e$message))
 
 
 
91
  }
92
 
93
- # ========================== UI ==========================
 
 
94
  ui <- fluidPage(
95
  useShinyjs(),
96
  tags$head(
97
- tags$link(href = "https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;600&family=IBM+Plex+Sans:wght@300;400;500;600&display=swap", rel = "stylesheet"),
 
98
  tags$style(HTML("
99
- body { font-family: 'IBM Plex Sans', sans-serif; background: #f8f9fb; }
100
- .qtl-header { background: white; padding: 12px 24px; border-bottom: 2px solid #dde2ea; display: flex; align-items: center; gap: 15px; position: sticky; top: 0; z-index: 100; }
101
- .logo-mark { width: 40px; height: 40px; background: #1a6cf5; color: white; border-radius: 8px; display: flex; align-items: center; justify-content: center; font-weight: 700; font-size: 16px; }
102
- .btn-run { width: 100%; padding: 12px; background: #1a6cf5; color: white; border: none; border-radius: 8px; font-weight: 600; }
103
- .btn-run:disabled { background: #94a3b8; }
104
- .plot-card { background: white; border-radius: 12px; box-shadow: 0 4px 15px rgba(0,0,0,0.08); margin-bottom: 20px; overflow: hidden; }
105
- .plot-card-header { padding: 14px 18px; background: #f1f4f8; border-bottom: 1px solid #dde2ea; font-weight: 600; }
106
- .empty-state { padding: 80px 20px; text-align: center; color: #8a95a3; font-size: 18px; }
107
- .status-row { padding: 10px; background: white; border: 1px solid #dde2ea; border-radius: 8px; margin-top: 10px; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
108
  "))
109
  ),
110
 
111
- div(class = "qtl-header",
112
- div(class = "logo-mark", "QTL"),
113
- h1("QTL Mapper Pro", style = "margin:0; font-size:20px;")
 
 
 
 
 
114
  ),
115
 
116
- div(style = "display: grid; grid-template-columns: 310px 1fr; height: calc(100vh - 65px);",
117
- # Sidebar
118
- div(style = "background: #f1f4f8; padding: 20px; overflow-y: auto; border-right: 2px solid #dde2ea;",
119
- h4("Data Input"),
120
- fileInput("geno_file", "Genotype CSV", accept = ".csv", width = "100%"),
121
- fileInput("pheno_file", "Phenotype CSV", accept = ".csv", width = "100%"),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
 
123
- h4("Settings", style = "margin-top:25px;"),
124
- selectInput("cross_type", "Cross Type",
125
- choices = c("F2 Intercross"="f2", "Backcross"="bc", "RIL Self"="riself", "RIL Sib"="risib"),
126
- selected = "f2"),
127
- selectInput("pheno_col", "Select Trait", choices = NULL),
 
 
 
 
 
 
 
128
 
129
- checkboxGroupInput("models", "Mapping Methods",
130
- choices = c("hk","em","ehk","imp","cim","np","mr"),
131
- selected = c("hk","em","imp"),
132
- inline = FALSE),
 
 
 
 
 
 
133
 
134
- numericInput("step_size", "Step (cM)", 2, min = 1, max = 10, step = 0.5),
135
- numericInput("n_perm", "Permutations (0=skip)", 100, min = 0, max = 1000, step = 50),
136
- numericInput("lod_thresh", "LOD Threshold", 3.0, min = 1, max = 15, step = 0.5),
 
 
 
 
 
 
 
137
 
138
- actionButton("run_analysis", "β–Ά RUN ANALYSIS", class = "btn-run"),
139
- downloadButton("download_results", "Download Results", style = "width:100%; margin-top:10px;"),
 
140
 
141
  div(class = "status-row",
142
- div(id = "status_dot", style = "display:inline-block;width:10px;height:10px;border-radius:50%;background:#94a3b8;"),
143
- textOutput("status_text", inline = TRUE)
144
- )
145
  ),
146
 
147
- # Main Content
148
- div(style = "padding: 20px; overflow-y: auto;",
149
- tabsetPanel(
150
- tabPanel("Overview", uiOutput("overview_content")),
151
- tabPanel("Manhattan", uiOutput("manhattan_content")),
152
- tabPanel("Genome Scan", uiOutput("genome_content")),
153
- tabPanel("Chr Plots", uiOutput("chromosome_content")),
154
- tabPanel("Model Compare", uiOutput("model_comp_content")),
155
- tabPanel("QTL Effects", uiOutput("effects_content")),
156
- tabPanel("2D Scan", uiOutput("pairwise_content")),
157
- tabPanel("Diagnostics", uiOutput("diagnostics_content")),
158
- tabPanel("Results", uiOutput("results_content"))
159
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
160
  )
161
- )
 
 
 
 
 
 
 
 
 
 
 
162
  )
163
 
164
- # ========================== SERVER ==========================
 
 
165
  server <- function(input, output, session) {
166
 
167
- model_colors <- c(hk="#e8500a", em="#1a6cf5", ehk="#18a058", imp="#c2185b",
168
- cim="#7c3aed", np="#0891b2", mr="#dc2626")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
169
 
170
- # Reactive Cross
171
- cross_data <- reactive({
172
  req(input$geno_file, input$pheno_file)
173
- parse_custom_cross(input$geno_file$datapath, input$pheno_file$datapath, input$cross_type)
 
 
 
 
 
 
174
  })
175
 
176
- # Pre-compute genotype probabilities (expensive, done once)
177
- cross_with_probs <- reactive({
178
- cross <- cross_data()
179
- req(cross)
180
- calc.genoprob(cross, step = input$step_size, error.prob = 0.001)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
181
  })
182
 
183
- # Main Analysis
184
- analysis_results <- eventReactive(input$run_analysis, {
185
- cross <- cross_with_probs()
186
- req(cross)
187
 
188
- shinyjs::disable("run_analysis")
189
- on.exit(shinyjs::enable("run_analysis"), add = TRUE)
190
 
191
- withProgress(message = "QTL Analysis in progress...", value = 0, {
192
- pheno_idx <- which(names(cross$pheno) == input$pheno_col)
193
- if (length(pheno_idx) == 0) pheno_idx <- 1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
194
 
195
- models_to_run <- input$models
196
- if (length(models_to_run) == 0) models_to_run <- "hk"
 
 
 
 
 
 
 
197
 
198
  scan_results <- list()
199
  perm_results <- list()
200
 
201
- for (mdl in models_to_run) {
202
- incProgress(0.6/length(models_to_run), detail = paste("Scanning with", mdl))
203
- sc <- tryCatch(scanone(cross, pheno.col = pheno_idx, method = mdl), error = function(e) NULL)
204
- if (!is.null(sc)) scan_results[[mdl]] <- sc
205
 
206
- if (input$n_perm > 0) {
207
- incProgress(0.3/length(models_to_run), detail = paste("Permuting", mdl))
208
- perm <- tryCatch(scanone(cross, pheno.col = pheno_idx, method = mdl,
209
- n.perm = input$n_perm, verbose = FALSE), error = function(e) NULL)
210
- if (!is.null(perm)) perm_results[[mdl]] <- perm
211
  }
212
  }
213
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
214
  lod_thr <- input$lod_thresh
215
- if (length(perm_results) > 0 && !is.null(perm_results[[1]])) {
216
- thr <- tryCatch(summary(perm_results[[1]], alpha = 0.05)[1], error = function(e) NULL)
217
- if (!is.null(thr)) lod_thr <- thr
 
 
 
 
 
 
 
 
 
 
 
218
  }
219
 
220
- qtl_table <- build_qtl_table(cross, scan_results, lod_thr, pheno_idx)
 
221
 
222
- list(cross = cross, scan_results = scan_results, perm_results = perm_results,
223
- lod_thr = lod_thr, qtl_table = qtl_table, pheno_idx = pheno_idx)
 
 
 
 
 
 
 
224
  })
225
- })
226
 
227
- build_qtl_table <- function(cross, scan_results, lod_thr, pheno_idx) {
228
- rows <- list()
229
- for (mdl in names(scan_results)) {
230
- sc <- scan_results[[mdl]]
231
- sig <- sc[sc$lod >= lod_thr, , drop = FALSE]
232
- if (nrow(sig) == 0) next
233
- for (ch in unique(sig$chr)) {
234
- chr_sc <- sc[sc$chr == ch, ]
235
- peak <- chr_sc[which.max(chr_sc$lod), ]
236
- ci <- tryCatch(lodint(sc, chr = ch, drop = 1.5), error = function(e) NULL)
237
-
238
- rows[[length(rows) + 1]] <- data.frame(
239
- Model = mdl,
240
- Chr = ch,
241
- Peak_Marker = rownames(peak),
242
- Peak_cM = round(peak$pos, 2),
243
- LOD = round(peak$lod, 3),
244
- PVE = round((1 - 10^(-2 * peak$lod / nind(cross))) * 100, 1),
245
- CI_Left_cM = ifelse(!is.null(ci), round(ci$pos[1], 2), NA),
246
- CI_Right_cM = ifelse(!is.null(ci), round(ci$pos[nrow(ci)], 2), NA),
247
- stringsAsFactors = FALSE
248
- )
249
- }
250
- }
251
- if (length(rows) == 0) return(data.frame())
252
- bind_rows(rows) %>% arrange(Chr, Peak_cM)
253
- }
254
 
255
- # Update phenotype dropdown
256
- observe({
257
- cross <- cross_data()
258
- req(cross)
259
- updateSelectInput(session, "pheno_col", choices = names(cross$pheno))
260
  })
261
 
262
- output$status_text <- renderText({
263
- if (is.null(cross_data())) "Upload files"
264
- else if (is.null(analysis_results())) "Ready - Click RUN ANALYSIS"
265
- else "Analysis Completed"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
266
  })
267
 
268
- # ====================== ALL TABS & PLOTS ======================
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
269
 
270
- output$overview_content <- renderUI({
271
- cross <- cross_data()
272
- if (is.null(cross)) return(div(class = "empty-state", "πŸ“‚ Please upload genotype and phenotype files"))
273
- res <- analysis_results()
274
- nqtl <- if(!is.null(res)) nrow(res$qtl_table) else 0
 
 
 
 
 
275
 
 
 
 
 
276
  tagList(
277
- fluidRow(
278
- column(3, div(style="background:#eef3fe;padding:20px;border-radius:10px;text-align:center;", h3(totmar(cross)), p("Markers"))),
279
- column(3, div(style="background:#fef4ee;padding:20px;border-radius:10px;text-align:center;", h3(nind(cross)), p("Individuals"))),
280
- column(3, div(style="background:#edf7f2;padding:20px;border-radius:10px;text-align:center;", h3(nchr(cross)), p("Chromosomes"))),
281
- column(3, div(style="background:#fce8f1;padding:20px;border-radius:10px;text-align:center;", h3(nqtl), p("Significant QTLs")))
282
- ),
283
- div(class = "plot-card", div(class = "plot-card-header", "Genome Map"), plotOutput("plot_genome_map", height = "380px") %>% withSpinner())
284
  )
285
  })
286
 
287
- output$plot_genome_map <- renderPlot({
288
- cross <- cross_data(); req(cross)
289
- map <- pull.map(cross)
290
- df <- do.call(rbind, lapply(names(map), function(ch) data.frame(chr=ch, pos=unname(map[[ch]]))))
291
- ggplot(df, aes(x=chr, y=pos)) +
292
- geom_segment(aes(xend=chr, yend=0), color="#e0e7ff", linewidth=12) +
293
- geom_point(color="#1a6cf5", size=2.5) +
294
- scale_y_reverse() + labs(y="Position (cM)", title="Genetic Map") +
295
- theme_minimal(base_size=13)
 
 
 
 
 
 
 
 
 
 
 
296
  })
297
 
298
- # Manhattan
299
- output$manhattan_content <- renderUI({
300
- res <- analysis_results()
301
- if (is.null(res)) return(div(class="empty-state", "Run analysis first"))
 
 
 
 
302
  tagList(
303
- selectInput("manhattan_model", "Model", choices=names(res$scan_results)),
304
- div(class="plot-card", div(class="plot-card-header", "Manhattan Plot"),
305
- plotOutput("plot_manhattan", height="520px") %>% withSpinner())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
306
  )
307
  })
308
 
309
- output$plot_manhattan <- renderPlot({
310
- res <- analysis_results(); req(res, input$manhattan_model)
311
- sc <- res$scan_results[[input$manhattan_model]]
312
- ggplot(sc, aes(x=pos, y=lod, color=factor(chr))) +
313
- geom_point(size=1.3, alpha=0.85) +
314
- geom_hline(yintercept=res$lod_thr, color="red", linetype="dashed", linewidth=0.8) +
315
- facet_wrap(~chr, scales="free_x", ncol=4) +
316
- labs(y="LOD Score", title=paste("Manhattan -", input$manhattan_model)) +
317
- theme_minimal() + theme(legend.position="none")
318
  })
319
 
320
- # Genome Scan (All Models)
321
- output$genome_content <- renderUI({
322
- res <- analysis_results()
323
- if (is.null(res)) return(div(class="empty-state", "Run analysis first"))
324
- div(class="plot-card", div(class="plot-card-header", "Genome Scan - All Models"),
325
- plotOutput("plot_scan_all", height="520px") %>% withSpinner())
 
 
 
 
 
 
 
 
 
326
  })
327
 
328
- output$plot_scan_all <- renderPlot({
329
- res <- analysis_results(); req(res)
330
- df <- bind_rows(lapply(names(res$scan_results), function(m) {
331
- sc <- res$scan_results[[m]]
332
- sc$model <- m
333
- sc
334
- }))
335
- ggplot(df, aes(x=pos, y=lod, color=model)) +
336
- geom_line(linewidth=0.7, alpha=0.9) +
337
- geom_hline(yintercept=res$lod_thr, color="red", linetype="dashed") +
338
- facet_wrap(~chr, scales="free_x", ncol=4) +
339
- scale_color_manual(values=model_colors) +
340
- labs(y="LOD", title="Genome Scan - All Models") + theme_minimal()
 
 
 
 
 
 
 
 
 
 
 
 
 
341
  })
342
 
343
- # Chromosome Grid
344
- output$chromosome_content <- renderUI({
345
- res <- analysis_results()
346
- if (is.null(res)) return(div(class="empty-state", "Run analysis first"))
 
 
 
 
 
 
 
 
 
 
347
  tagList(
348
- selectInput("chr_model", "Model", choices=names(res$scan_results)),
349
- div(class="plot-card", div(class="plot-card-header", "Per Chromosome LOD Profiles"),
350
- plotOutput("plot_chr_grid", height="800px") %>% withSpinner())
 
 
 
 
 
351
  )
352
  })
353
 
354
- output$plot_chr_grid <- renderPlot({
355
- res <- analysis_results(); req(res, input$chr_model)
356
- sc <- res$scan_results[[input$chr_model]]
357
- chrs <- unique(sc$chr)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
358
  plots <- lapply(chrs, function(ch) {
359
- p <- ggplot(sc[sc$chr==ch,], aes(x=pos, y=lod)) +
360
- geom_line(color="#1a6cf5", linewidth=0.9) +
361
- geom_hline(yintercept=res$lod_thr, color="red", linetype="dashed") +
362
- labs(title=paste("Chr", ch), x="cM", y="LOD") + theme_minimal(base_size=10)
363
- if (nrow(res$qtl_table) > 0) {
364
- qt_chr <- res$qtl_table[res$qtl_table$Chr == ch & res$qtl_table$Model == input$chr_model, ]
365
- if (nrow(qt_chr) > 0) p <- p + geom_point(data=qt_chr, aes(x=Peak_cM, y=LOD), color="red", size=4, shape=23, fill="yellow")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
366
  }
367
  p
368
  })
369
- do.call(grid.arrange, c(plots, ncol = min(3, length(chrs))))
370
- })
371
 
372
- # Model Comparison
373
- output$model_comp_content <- renderUI({
374
- res <- analysis_results()
375
- if (is.null(res)) return(div(class="empty-state", "Run analysis first"))
376
- div(class="plot-card", div(class="plot-card-header", "Model Comparison"),
377
- plotOutput("plot_model_bar", height="400px") %>% withSpinner())
378
- })
 
 
 
 
 
 
 
 
 
 
379
 
380
- output$plot_model_bar <- renderPlot({
381
- res <- analysis_results(); req(res)
382
- df <- data.frame(Model = names(res$scan_results),
383
- MaxLOD = sapply(res$scan_results, function(x) max(x$lod, na.rm=TRUE)))
384
- ggplot(df, aes(x=reorder(Model, MaxLOD), y=MaxLOD, fill=Model)) +
385
- geom_col() + coord_flip() +
386
- scale_fill_manual(values=model_colors) +
387
- geom_hline(yintercept=res$lod_thr, color="red", linetype="dashed") +
388
- labs(title="Maximum LOD per Model", y="Max LOD") + theme_minimal()
389
- })
 
 
 
 
 
 
390
 
391
- # QTL Effects
392
- output$effects_content <- renderUI({
393
- res <- analysis_results()
394
- if (is.null(res) || nrow(res$qtl_table)==0)
395
- return(div(class="empty-state", "No significant QTLs found"))
396
- qtl_choices <- paste0(res$qtl_table$Chr, "@", res$qtl_table$Peak_Marker)
397
- tagList(
398
- selectInput("effect_qtl", "Select QTL", choices=qtl_choices),
399
- div(class="plot-card", div(class="plot-card-header", "QTL Effect Plot"),
400
- plotOutput("plot_effects", height="380px") %>% withSpinner())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
401
  )
402
- })
403
 
404
- output$plot_effects <- renderPlot({
405
- res <- analysis_results(); req(res, input$effect_qtl)
406
- parts <- strsplit(input$effect_qtl, "@")[[1]]
407
- marker <- parts[2]
 
 
408
  tryCatch({
409
- eff <- effectplot(res$cross, mname1=marker, pheno.col=res$pheno_idx, draw=FALSE)
410
- df <- data.frame(Genotype=names(eff$Means), Mean=eff$Means, SE=eff$SEs)
411
- ggplot(df, aes(x=Genotype, y=Mean, fill=Genotype)) +
412
- geom_col(alpha=0.85) +
413
- geom_errorbar(aes(ymin=Mean-SE, ymax=Mean+SE), width=0.3) +
414
- labs(title=paste("Effect at", marker)) + theme_minimal()
415
- }, error = function(e) ggplot() + annotate("text", x=0.5, y=0.5, label="Effect plot unavailable") + theme_void())
416
- })
 
 
 
 
 
 
 
 
 
 
 
 
 
417
 
418
- # 2D Scan (Epistasis)
419
- output$pairwise_content <- renderUI({
420
- res <- analysis_results()
421
- if (is.null(res)) return(div(class="empty-state", "Run analysis first"))
422
- div(class="plot-card", div(class="plot-card-header", "2D Genome Scan (Epistasis)"),
423
- plotOutput("plot_2d", height="600px") %>% withSpinner())
424
- })
 
 
 
 
 
 
 
425
 
426
- output$plot_2d <- renderPlot({
427
- res <- analysis_results(); req(res)
428
- sc2 <- tryCatch(scantwo(res$cross, pheno.col=res$pheno_idx, method="hk", verbose=FALSE),
429
- error = function(e) NULL)
 
 
 
430
  if (is.null(sc2)) {
431
- ggplot() + annotate("text", x=0.5, y=0.5, label="2D scan not available") + theme_void()
 
432
  } else {
433
- plot(sc2, main="Pairwise LOD Scan")
 
 
 
 
 
 
 
 
 
 
 
434
  }
435
- })
436
 
437
- # Diagnostics
438
- output$diagnostics_content <- renderUI({
439
- cross <- cross_data()
440
- if (is.null(cross)) return(div(class="empty-state", "Upload data"))
441
- tagList(
442
- div(class="plot-card", div(class="plot-card-header", "Missing Genotypes"),
443
- plotOutput("plot_missing", height="320px")),
444
- div(class="plot-card", div(class="plot-card-header", "Genotype Frequencies"),
445
- plotOutput("plot_geno_freq", height="320px"))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
446
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
447
  })
448
 
449
- output$plot_missing <- renderPlot({
450
- cross <- cross_data(); req(cross)
451
- miss <- nmissing(cross, what="mar")
452
- df <- data.frame(Marker=names(miss), Missing=miss)
453
- ggplot(df, aes(x=reorder(Marker, Missing), y=Missing)) +
454
- geom_col(fill="#1a6cf5") + theme_minimal() +
455
- theme(axis.text.x = element_blank()) + labs(x="Marker", y="Missing Count")
 
 
 
 
 
456
  })
457
 
458
- output$plot_geno_freq <- renderPlot({
459
- cross <- cross_data(); req(cross)
460
- gt <- pull.geno(cross)
461
- freq <- colMeans(gt == 1, na.rm=TRUE)
462
- df <- data.frame(Marker=names(freq), Freq_A=freq, Freq_B=1-freq)
463
- df_long <- pivot_longer(df, cols=c(Freq_A, Freq_B))
464
- ggplot(df_long, aes(x=Marker, y=value, fill=name)) +
465
- geom_col(position="stack") + theme_minimal() +
466
- theme(axis.text.x = element_blank()) + labs(y="Frequency")
 
 
 
467
  })
468
 
469
- # Results Table
470
- output$results_content <- renderUI({
471
- res <- analysis_results()
472
- if (is.null(res) || nrow(res$qtl_table)==0)
473
- return(div(class="empty-state", "No significant QTLs detected"))
474
- div(class="plot-card", div(class="plot-card-header", "QTL Results Table"),
475
- DTOutput("table_qtl") %>% withSpinner())
 
 
 
 
 
 
 
476
  })
477
 
478
- output$table_qtl <- renderDT({
479
- res <- analysis_results()
480
- datatable(res$qtl_table, options=list(pageLength=15, scrollX=TRUE), rownames=FALSE)
 
 
 
 
 
 
 
 
 
 
481
  })
482
 
483
- # Download
484
- output$download_results <- downloadHandler(
485
- filename = function() paste0("QTL_Results_", Sys.Date(), ".csv"),
486
- content = function(file) {
487
- res <- analysis_results()
488
- if (!is.null(res) && nrow(res$qtl_table) > 0) {
489
- write.csv(res$qtl_table, file, row.names = FALSE)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
490
  } else {
491
- write.csv(data.frame(Note="No significant QTLs found"), file, row.names = FALSE)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
492
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
493
  }
494
  )
495
  }
496
 
 
 
 
497
  shinyApp(ui = ui, server = server)
 
1
+ # ═══════════════════════════════════════════════════════════════════════════════
2
+ # QTL MAPPER PRO β€” Complete Fixed Pipeline
3
+ # Matches Cartographer-compatible logic; 10 models; 10+ plots; Excel export
4
+ # ═══════════════════════════════════════════════════════════════════════════════
5
+ # Install missing packages on first run:
6
+ # install.packages(c("shiny","qtl","ggplot2","dplyr","tidyr","DT",
7
+ # "shinycssloaders","shinyjs","plotly","RColorBrewer",
8
+ # "gridExtra","openxlsx","scales","reshape2"))
9
+ # ═══════════════════════════════════════════════════════════════════════════════
10
+
11
+ suppressPackageStartupMessages({
12
+ library(shiny)
13
+ library(qtl)
14
+ library(ggplot2)
15
+ library(dplyr)
16
+ library(tidyr)
17
+ library(DT)
18
+ library(shinycssloaders)
19
+ library(shinyjs)
20
+ library(plotly)
21
+ library(gridExtra)
22
+ library(scales)
23
+ library(openxlsx) # for Excel export
24
+ library(reshape2)
25
+ })
26
+
27
+ # ─── CUSTOM DATA PARSER ────────────────────────────────────────────────────────
28
+ # Genotype CSV layout:
29
+ # Row 1 : id | marker1 | marker2 | ...
30
+ # Row 2 : (blank) | chr1 | chr1 | ...
31
+ # Row 3 : (blank) | pos1 | pos2 | ... (cM)
32
+ # Rows 4+: sampleID | 1|2|3 (1=AA, 2=AB, 3=BB for F2; 1=AA, 2=AB for BC)
33
+ # Phenotype CSV layout:
34
+ # Row 1 : id | trait1 | trait2 | ...
35
+ # Rows 2+: sampleID | numeric values
36
+
37
+ parse_cross <- function(geno_path, pheno_path, cross_type = "f2") {
38
+
39
+ # 1. Read raw genotype file
40
+ graw <- read.csv(geno_path, header = FALSE, stringsAsFactors = FALSE,
41
+ check.names = FALSE, na.strings = c("NA","","N/A","."))
42
+
43
+ col_names <- as.character(graw[1, ])
44
+ chr_row <- as.character(graw[2, ])
45
+ pos_row <- as.character(graw[3, ])
46
+ ind_data <- graw[seq(4, nrow(graw)), , drop = FALSE]
47
+
48
+ marker_cols <- seq(2, ncol(graw))
49
+ marker_names <- col_names[marker_cols]
50
+ chromosomes <- gsub("^[Cc]hr0*", "", chr_row[marker_cols])
51
+ chr_int <- suppressWarnings(as.integer(chromosomes))
52
+ chromosomes <- ifelse(!is.na(chr_int), as.character(chr_int), chromosomes)
53
+ positions <- suppressWarnings(as.numeric(pos_row[marker_cols]))
54
+
55
+ ind_ids <- as.character(ind_data[, 1])
56
+ geno_mat <- apply(ind_data[, marker_cols, drop = FALSE], 2,
57
+ function(x) suppressWarnings(as.numeric(x)))
58
+ rownames(geno_mat) <- ind_ids
59
+ colnames(geno_mat) <- marker_names
60
+
61
+ # 2. Read phenotype file
62
+ praw <- read.csv(pheno_path, header = TRUE, stringsAsFactors = FALSE,
63
+ check.names = FALSE, na.strings = c("NA","","N/A","."))
64
+ pheno_ids <- as.character(praw[, 1])
65
+ pheno_df <- as.data.frame(lapply(praw[, -1, drop = FALSE],
66
+ function(x) suppressWarnings(as.numeric(x))))
67
+ rownames(pheno_df) <- pheno_ids
68
+
69
+ # 3. Align individuals
70
+ common_ids <- intersect(ind_ids, pheno_ids)
71
+ if (length(common_ids) == 0)
72
+ stop(sprintf("No matching IDs.\n Geno (first 5): %s\n Pheno (first 5): %s",
73
+ paste(head(ind_ids,5), collapse=", "),
74
+ paste(head(pheno_ids,5), collapse=", ")))
75
+
76
+ geno_mat <- geno_mat[common_ids, , drop = FALSE]
77
+ pheno_df <- pheno_df[common_ids, , drop = FALSE]
78
+
79
+ # 4. Build sorted chromosome map
80
+ unique_chrs <- unique(chromosomes)
81
+ chr_int2 <- suppressWarnings(as.integer(unique_chrs))
82
+ chr_ord <- order(ifelse(!is.na(chr_int2), chr_int2, 999L), unique_chrs)
83
+ unique_chrs <- unique_chrs[chr_ord]
84
+
85
+ geno_list <- lapply(unique_chrs, function(ch) {
86
+ idx <- which(chromosomes == ch)
87
+ ord2 <- order(positions[idx])
88
+ mnames <- marker_names[idx][ord2]
89
+ pos_ch <- positions[idx][ord2]
90
+ names(pos_ch) <- mnames
91
+ class(pos_ch) <- "A" # autosome
92
+
93
+ g_ch <- geno_mat[, mnames, drop = FALSE]
94
+ g_ch[g_ch == 0] <- NA
95
+ storage.mode(g_ch) <- "integer"
96
+
97
+ list(data = g_ch, map = pos_ch)
98
+ })
99
+ names(geno_list) <- unique_chrs
100
+
101
+ cross_obj <- structure(
102
+ list(geno = geno_list, pheno = pheno_df),
103
+ class = c(cross_type, "cross")
104
+ )
105
+
106
+ # jittermap resolves duplicate cM positions
107
+ cross_obj <- jittermap(cross_obj)
108
+ cross_obj
109
+ }
110
+
111
+ # ─── HELPER: safe scanone wrapper ─────────────────────────────────────────────
112
+ safe_scanone <- function(cross, pheno_idx, method, step, err) {
113
+ tryCatch(
114
+ scanone(cross, pheno.col = pheno_idx, method = method),
115
+ error = function(e) { message("scanone [", method, "] failed: ", e$message); NULL }
116
+ )
117
+ }
118
+
119
+ # ─── HELPER: safe permutation ─────────────────────────────────────────────────
120
+ safe_perm <- function(cross, pheno_idx, method, n_perm) {
121
+ tryCatch(
122
+ scanone(cross, pheno.col = pheno_idx, method = method,
123
+ n.perm = n_perm, verbose = FALSE),
124
+ error = function(e) NULL
125
+ )
126
+ }
127
+
128
+ # ─── HELPER: Build QTL results table ──────────────────────────────────────────
129
+ build_qtl_table <- function(cross, scan_results, lod_thr) {
130
+ rows <- list()
131
+ n <- nind(cross)
132
+
133
+ for (mdl in names(scan_results)) {
134
+ sc <- scan_results[[mdl]]
135
+ for (ch in unique(as.character(sc$chr))) {
136
+ sc_ch <- sc[as.character(sc$chr) == ch, , drop = FALSE]
137
+ if (max(sc_ch$lod, na.rm = TRUE) < lod_thr) next
138
+
139
+ peak_row <- sc_ch[which.max(sc_ch$lod), , drop = FALSE]
140
+ peak_pos <- peak_row$pos
141
+ peak_lod <- peak_row$lod
142
+ peak_marker <- rownames(peak_row)
143
+
144
+ # 1.5-LOD confidence interval
145
+ ci <- tryCatch(
146
+ lodint(sc, chr = ch, expandtomarkers = TRUE, drop = 1.5),
147
+ error = function(e) NULL
148
+ )
149
+
150
+ left_marker <- if (!is.null(ci) && nrow(ci) >= 1) rownames(ci)[1] else NA_character_
151
+ right_marker <- if (!is.null(ci) && nrow(ci) >= 1) rownames(ci)[nrow(ci)] else NA_character_
152
+ left_pos <- if (!is.null(ci) && nrow(ci) >= 1) ci$pos[1] else NA_real_
153
+ right_pos <- if (!is.null(ci) && nrow(ci) >= 1) ci$pos[nrow(ci)] else NA_real_
154
 
155
+ # PVE using Lande-Thompson formula: 1 - 10^(-2*LOD/N)
156
+ pve <- round((1 - 10^(-2 * peak_lod / n)) * 100, 3)
 
157
 
158
+ # Additive / dominance effects (F2 only)
159
+ add_eff <- NA_real_; dom_eff <- NA_real_
160
+ if (inherits(cross, "f2")) {
161
+ tryCatch({
162
+ eff <- effectplot(cross, mname1 = peak_marker,
163
+ pheno.col = which(names(cross$pheno) %in%
164
+ names(cross$pheno)[1]),
165
+ draw = FALSE)
166
+ mn <- eff$Means
167
+ if (length(mn) == 3) {
168
+ add_eff <- round((mn[3] - mn[1]) / 2, 4)
169
+ dom_eff <- round(mn[2] - (mn[1] + mn[3]) / 2, 4)
170
+ }
171
+ }, error = function(e) NULL)
172
+ }
173
+
174
+ rows[[length(rows) + 1]] <- data.frame(
175
+ Model = mdl,
176
+ Chr = ch,
177
+ Peak_Marker = peak_marker,
178
+ Peak_pos_cM = round(peak_pos, 3),
179
+ LOD = round(peak_lod, 4),
180
+ PVE_pct = pve,
181
+ Additive_eff = add_eff,
182
+ Dom_eff = dom_eff,
183
+ Left_Marker = left_marker,
184
+ Left_pos_cM = round(left_pos, 3),
185
+ Right_Marker = right_marker,
186
+ Right_pos_cM = round(right_pos, 3),
187
+ CI_width_cM = round(right_pos - left_pos, 3),
188
+ stringsAsFactors = FALSE
189
+ )
190
  }
191
+ }
192
+
193
+ if (length(rows) == 0) return(data.frame())
194
+ dplyr::bind_rows(rows) %>%
195
+ dplyr::arrange(Chr, Peak_pos_cM, Model)
196
  }
197
 
198
+ # ═══════════════════════════════════════════════════════════════════════════════
199
+ # UI
200
+ # ═══════════════════════════════════════════════════════════════════════════════
201
  ui <- fluidPage(
202
  useShinyjs(),
203
  tags$head(
204
+ tags$link(href = "https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;600;700&family=Syne:wght@400;600;700;800&display=swap",
205
+ rel = "stylesheet"),
206
  tags$style(HTML("
207
+ :root {
208
+ --bg: #0d0f14;
209
+ --panel: #13161d;
210
+ --panel2: #1a1e28;
211
+ --border: #252a38;
212
+ --border2: #2e3548;
213
+ --a1: #4fffb0;
214
+ --a2: #ff6b6b;
215
+ --a3: #4fc3f7;
216
+ --a4: #ffb347;
217
+ --a5: #c77dff;
218
+ --text: #e8edf5;
219
+ --text2: #a0aabb;
220
+ --muted: #5a6478;
221
+ --mono: 'JetBrains Mono', monospace;
222
+ --sans: 'Syne', sans-serif;
223
+ --r: 8px;
224
+ }
225
+ * { box-sizing:border-box; margin:0; padding:0; }
226
+ body { background:var(--bg); color:var(--text); font-family:var(--sans); font-size:13px; min-height:100vh; }
227
+
228
+ /* ── Header ── */
229
+ .hdr {
230
+ background:var(--panel); border-bottom:1px solid var(--border2);
231
+ padding:0 28px; height:56px; display:flex; align-items:center; gap:14px;
232
+ position:sticky; top:0; z-index:200;
233
+ }
234
+ .hdr-logo {
235
+ width:34px; height:34px; background:var(--a1); border-radius:7px;
236
+ display:flex; align-items:center; justify-content:center;
237
+ font-family:var(--mono); font-size:11px; font-weight:700; color:#0d0f14;
238
+ }
239
+ .hdr h1 { font-family:var(--mono); font-size:14px; letter-spacing:2px; color:var(--text); font-weight:700; }
240
+ .hdr-sub { font-size:10px; color:var(--muted); margin-top:2px; letter-spacing:.3px; }
241
+ .hdr-badges { margin-left:auto; display:flex; gap:6px; }
242
+ .badge {
243
+ padding:3px 9px; border-radius:100px; font-size:9px; font-family:var(--mono);
244
+ letter-spacing:.8px; font-weight:700; border:1px solid;
245
+ }
246
+ .badge.g { color:var(--a1); border-color:rgba(79,255,176,.3); background:rgba(79,255,176,.08); }
247
+ .badge.b { color:var(--a3); border-color:rgba(79,195,247,.3); background:rgba(79,195,247,.08); }
248
+ .badge.o { color:var(--a4); border-color:rgba(255,179,71,.3); background:rgba(255,179,71,.08); }
249
+
250
+ /* ── Layout ── */
251
+ .layout { display:grid; grid-template-columns:270px 1fr; height:calc(100vh - 56px); }
252
+ .sidebar {
253
+ background:var(--panel); border-right:1px solid var(--border2);
254
+ overflow-y:auto; padding:18px 14px 32px;
255
+ }
256
+ .sidebar::-webkit-scrollbar { width:3px; }
257
+ .sidebar::-webkit-scrollbar-thumb { background:var(--border2); border-radius:3px; }
258
+
259
+ /* ── Sidebar sections ── */
260
+ .sec-label {
261
+ font-family:var(--mono); font-size:9px; letter-spacing:2.5px; color:var(--muted);
262
+ text-transform:uppercase; margin:20px 0 8px; padding-left:2px;
263
+ display:flex; align-items:center; gap:8px;
264
+ }
265
+ .sec-label:first-child { margin-top:0; }
266
+ .sec-label::after { content:''; flex:1; height:1px; background:var(--border); }
267
+
268
+ .upload-box {
269
+ border:1px dashed var(--border2); border-radius:var(--r); padding:10px;
270
+ background:var(--panel2); margin-bottom:8px; transition:.2s;
271
+ }
272
+ .upload-box:hover { border-color:var(--a1); }
273
+ .upload-box label.upload-lbl { font-size:9px; color:var(--a1); font-family:var(--mono); letter-spacing:1px; margin-bottom:4px; display:block; font-weight:700; }
274
+ .fmt-help { font-size:9px; color:var(--muted); font-family:var(--mono); line-height:1.7; margin-top:4px; padding:5px 7px; background:var(--bg); border-radius:4px; }
275
+ .notice { background:rgba(255,179,71,.08); border:1px solid rgba(255,179,71,.25); border-radius:6px; padding:8px 10px; font-size:10px; color:var(--a4); font-family:var(--mono); line-height:1.5; margin-bottom:10px; }
276
+ .ctl-block { margin-bottom:9px; }
277
+ .ctl-block label { font-size:9px; color:var(--text2); letter-spacing:.8px; font-family:var(--mono); text-transform:uppercase; display:block; margin-bottom:3px; font-weight:700; }
278
+
279
+ select, input[type='number'] {
280
+ width:100%; background:var(--panel2); border:1px solid var(--border2);
281
+ border-radius:5px; color:var(--text); padding:6px 9px; font-size:11px;
282
+ font-family:var(--mono); outline:none; transition:.2s; appearance:none;
283
+ }
284
+ select:focus, input:focus { border-color:var(--a1); box-shadow:0 0 0 2px rgba(79,255,176,.12); }
285
+ .shiny-input-checkboxgroup label { font-size:10px; color:var(--text2) !important; }
286
+ .shiny-input-checkboxgroup input[type=checkbox] { accent-color:var(--a1); }
287
+
288
+ .btn-run {
289
+ width:100%; padding:10px; background:var(--a1); border:none; border-radius:var(--r);
290
+ color:#0d0f14; font-family:var(--mono); font-size:11px; font-weight:700;
291
+ letter-spacing:2px; cursor:pointer; transition:.2s; margin-top:14px;
292
+ box-shadow:0 0 20px rgba(79,255,176,.25);
293
+ }
294
+ .btn-run:hover { box-shadow:0 0 30px rgba(79,255,176,.4); transform:translateY(-1px); }
295
+ .btn-export {
296
+ width:100%; padding:8px; background:transparent; border:1px solid var(--a3);
297
+ border-radius:var(--r); color:var(--a3); font-family:var(--mono); font-size:10px;
298
+ font-weight:700; letter-spacing:1px; cursor:pointer; margin-top:7px; transition:.2s;
299
+ }
300
+ .btn-export:hover { background:rgba(79,195,247,.1); }
301
+ .status-row {
302
+ display:flex; align-items:center; gap:7px; padding:7px 9px;
303
+ background:var(--panel2); border:1px solid var(--border2); border-radius:5px;
304
+ margin-top:10px; font-size:10px; color:var(--muted); font-family:var(--mono);
305
+ }
306
+ .sdot { width:6px; height:6px; border-radius:50%; background:var(--muted); flex-shrink:0; }
307
+ .sdot.on { background:var(--a1); box-shadow:0 0 6px rgba(79,255,176,.6); }
308
+ .sdot.err { background:var(--a2); box-shadow:0 0 6px rgba(255,107,107,.6); }
309
+ .parse-prev {
310
+ font-family:var(--mono); font-size:9px; color:var(--a1); background:rgba(79,255,176,.06);
311
+ border:1px solid rgba(79,255,176,.2); border-radius:5px; padding:8px 10px;
312
+ margin-top:8px; line-height:1.8;
313
+ }
314
+ .err-box {
315
+ font-family:var(--mono); font-size:9px; color:var(--a2); background:rgba(255,107,107,.07);
316
+ border:1px solid rgba(255,107,107,.25); border-radius:5px; padding:8px 10px; margin-top:8px; line-height:1.8;
317
+ }
318
+
319
+ /* ── Main ── */
320
+ .main-area { overflow-y:auto; background:var(--bg); }
321
+ .main-area::-webkit-scrollbar { width:5px; }
322
+ .main-area::-webkit-scrollbar-thumb { background:var(--border2); border-radius:3px; }
323
+
324
+ .tabs-bar {
325
+ display:flex; padding:0 24px; border-bottom:1px solid var(--border2);
326
+ background:var(--panel); position:sticky; top:0; z-index:100;
327
+ overflow-x:auto; gap:0;
328
+ }
329
+ .tabs-bar::-webkit-scrollbar { display:none; }
330
+ .tab-btn {
331
+ padding:13px 14px; border:none; background:transparent; color:var(--muted);
332
+ font-family:var(--mono); font-size:9px; letter-spacing:1.2px; text-transform:uppercase;
333
+ cursor:pointer; border-bottom:2px solid transparent; white-space:nowrap;
334
+ transition:.15s; margin-bottom:-1px; font-weight:700;
335
+ }
336
+ .tab-btn:hover { color:var(--text); }
337
+ .tab-btn.active { color:var(--a1); border-bottom-color:var(--a1); }
338
+
339
+ .tab-pane { display:none; padding:22px; }
340
+ .tab-pane.active { display:block; }
341
+
342
+ /* ── Cards ── */
343
+ .card {
344
+ background:var(--panel); border:1px solid var(--border2);
345
+ border-radius:12px; overflow:hidden; margin-bottom:18px;
346
+ }
347
+ .card-hdr {
348
+ display:flex; align-items:center; padding:11px 16px;
349
+ border-bottom:1px solid var(--border2); background:var(--panel2); gap:9px;
350
+ }
351
+ .card-icon { width:26px; height:26px; border-radius:5px; display:flex; align-items:center; justify-content:center; font-size:12px; flex-shrink:0; }
352
+ .card-icon.g { background:rgba(79,255,176,.12); }
353
+ .card-icon.b { background:rgba(79,195,247,.12); }
354
+ .card-icon.o { background:rgba(255,179,71,.12); }
355
+ .card-icon.r { background:rgba(255,107,107,.12); }
356
+ .card-icon.p { background:rgba(199,125,255,.12); }
357
+ .card-title { font-family:var(--mono); font-size:11px; color:var(--text); letter-spacing:.8px; font-weight:700; }
358
+ .card-sub { font-size:9px; color:var(--muted); margin-top:1px; }
359
+ .card-body { padding:14px; }
360
+
361
+ .stat-row { display:flex; gap:9px; flex-wrap:wrap; margin-bottom:18px; }
362
+ .stat-chip {
363
+ padding:9px 16px; border-radius:8px; font-family:var(--mono); font-size:11px;
364
+ border:1px solid; font-weight:700;
365
+ }
366
+ .stat-chip.g { background:rgba(79,255,176,.08); color:var(--a1); border-color:rgba(79,255,176,.2); }
367
+ .stat-chip.b { background:rgba(79,195,247,.08); color:var(--a3); border-color:rgba(79,195,247,.2); }
368
+ .stat-chip.o { background:rgba(255,179,71,.08); color:var(--a4); border-color:rgba(255,179,71,.2); }
369
+ .stat-chip.r { background:rgba(255,107,107,.08); color:var(--a2); border-color:rgba(255,107,107,.2); }
370
+
371
+ .grid2 { display:grid; grid-template-columns:1fr 1fr; gap:18px; }
372
+ .grid3 { display:grid; grid-template-columns:1fr 1fr 1fr; gap:18px; }
373
+ @media(max-width:1100px){.grid3{grid-template-columns:1fr 1fr;}}
374
+ @media(max-width:800px){.grid2,.grid3{grid-template-columns:1fr;}}
375
+
376
+ .empty { text-align:center; padding:60px 24px; color:var(--muted); }
377
+ .empty .ei { font-size:44px; margin-bottom:14px; }
378
+ .empty h3 { font-size:15px; color:var(--text2); margin-bottom:7px; font-family:var(--mono); }
379
+ .empty p { font-size:12px; line-height:1.6; max-width:380px; margin:0 auto; }
380
+
381
+ .info-box { background:rgba(79,195,247,.07); border:1px solid rgba(79,195,247,.2); border-radius:7px; padding:10px 14px; font-size:11px; color:var(--text2); line-height:1.6; margin-bottom:14px; }
382
+
383
+ /* ── DataTables override ── */
384
+ .dataTables_wrapper { color:var(--text) !important; font-size:11px; }
385
+ table.dataTable { background:transparent !important; color:var(--text) !important; border-collapse:collapse !important; }
386
+ table.dataTable thead th { background:var(--panel2) !important; color:var(--a1) !important; font-family:var(--mono) !important; font-size:9px !important; letter-spacing:1px !important; border-bottom:1px solid var(--border2) !important; padding:9px 11px !important; font-weight:700 !important; }
387
+ table.dataTable tbody tr { background:transparent !important; }
388
+ table.dataTable tbody tr:hover td { background:rgba(79,255,176,.04) !important; }
389
+ table.dataTable tbody td { border-bottom:1px solid var(--border) !important; padding:7px 11px !important; color:var(--text) !important; }
390
+ .dataTables_info,.dataTables_paginate { color:var(--muted) !important; font-size:10px !important; }
391
+ .paginate_button.current { background:var(--a1) !important; color:#0d0f14 !important; border-radius:3px !important; border:none !important; }
392
+ .dataTables_filter input,.dataTables_length select { background:var(--panel2) !important; border:1px solid var(--border2) !important; color:var(--text) !important; border-radius:4px !important; padding:4px 7px !important; }
393
  "))
394
  ),
395
 
396
+ div(class = "hdr",
397
+ div(class = "hdr-logo", "QTL"),
398
+ div(tags$h1("QTL MAPPER PRO"),
399
+ div(class = "hdr-sub", "Quantitative Trait Loci Analysis Pipeline Β· R/qtl Engine")),
400
+ div(class = "hdr-badges",
401
+ div(class = "badge g", "10 MODELS"),
402
+ div(class = "badge b", "CARTOGRAPHER-MATCH"),
403
+ div(class = "badge o", "EXCEL EXPORT"))
404
  ),
405
 
406
+ div(class = "layout",
407
+
408
+ # ─── SIDEBAR ─────────────────────────────────────────────────────────────
409
+ div(class = "sidebar",
410
+
411
+ div(class = "sec-label", "Data Input"),
412
+ div(class = "notice", "⚠ Upload both CSV files before running."),
413
+
414
+ div(class = "upload-box",
415
+ tags$label("Genotype CSV", class = "upload-lbl"),
416
+ fileInput("geno_file", NULL, accept = ".csv",
417
+ buttonLabel = "Browse", placeholder = "genotypes.csv"),
418
+ div(class = "fmt-help",
419
+ "Row1: id|m1|m2...", tags$br(),
420
+ "Row2: (id)|chr|chr...", tags$br(),
421
+ "Row3: (id)|pos(cM)|...", tags$br(),
422
+ "Row4+: sampleID|1/2/3...")
423
+ ),
424
+ div(class = "upload-box",
425
+ tags$label("Phenotype CSV", class = "upload-lbl"),
426
+ fileInput("pheno_file", NULL, accept = ".csv",
427
+ buttonLabel = "Browse", placeholder = "phenotypes.csv"),
428
+ div(class = "fmt-help", "Row1: id|trait1|...", tags$br(), "Row2+: sampleID|values...")
429
+ ),
430
+ uiOutput("parse_preview_ui"),
431
+
432
+ div(class = "sec-label", "Cross Type"),
433
+ div(class = "ctl-block",
434
+ selectInput("cross_type", NULL,
435
+ choices = c("F2 Intercross" = "f2", "Backcross" = "bc",
436
+ "RIL (selfing)" = "riself", "RIL (sib)" = "risib"),
437
+ selected = "f2")),
438
+
439
+ div(class = "sec-label", "Phenotype"),
440
+ div(class = "ctl-block", selectInput("pheno_col", NULL, choices = NULL)),
441
 
442
+ div(class = "sec-label", "Scan Models"),
443
+ checkboxGroupInput("models", NULL,
444
+ choices = c(
445
+ "EM Algorithm (em)" = "em",
446
+ "Haley-Knott (hk)" = "hk",
447
+ "Extended HK (ehk)" = "ehk",
448
+ "Multiple Imputation (imp)" = "imp",
449
+ "Non-Parametric (np)" = "np",
450
+ "Marker Regression (mr)" = "mr",
451
+ "Composite Interval (cim)" = "cim"
452
+ ),
453
+ selected = c("em","hk","ehk","imp","np","mr")),
454
 
455
+ div(class = "sec-label", "Permutation"),
456
+ div(class = "ctl-block",
457
+ tags$label("Permutations (0 = skip)"),
458
+ numericInput("n_perm", NULL, value = 100, min = 0, max = 2000, step = 50)),
459
+ div(class = "ctl-block",
460
+ tags$label("Ξ± significance"),
461
+ numericInput("alpha_thresh", NULL, value = 0.05, min = 0.01, max = 0.2, step = 0.01)),
462
+ div(class = "ctl-block",
463
+ tags$label("Fixed LOD (if no perm)"),
464
+ numericInput("lod_thresh", NULL, value = 3.0, min = 1, max = 15, step = 0.5)),
465
 
466
+ div(class = "sec-label", "Scan Settings"),
467
+ div(class = "ctl-block",
468
+ tags$label("Step size (cM)"),
469
+ numericInput("step_size", NULL, value = 1, min = 0.5, max = 5, step = 0.5)),
470
+ div(class = "ctl-block",
471
+ tags$label("Genotyping error prob"),
472
+ numericInput("error_prob", NULL, value = 0.001, min = 0.0001, max = 0.05, step = 0.001)),
473
+ div(class = "ctl-block",
474
+ tags$label("Imputation draws"),
475
+ numericInput("n_draws", NULL, value = 32, min = 8, max = 128, step = 8)),
476
 
477
+ actionButton("run_analysis", "β–Ά RUN ANALYSIS", class = "btn-run"),
478
+ downloadButton("dl_excel", "⬇ EXPORT EXCEL", class = "btn-export"),
479
+ downloadButton("dl_csv", "⬇ EXPORT CSV", class = "btn-export"),
480
 
481
  div(class = "status-row",
482
+ div(id = "sdot", class = "sdot"),
483
+ textOutput("status_text", inline = TRUE))
 
484
  ),
485
 
486
+ # ─── MAIN ────────────────────────────────────────────────────────────────
487
+ div(class = "main-area",
488
+ div(class = "tabs-bar",
489
+ tags$button(class = "tab-btn active", `data-tab` = "overview", "Overview"),
490
+ tags$button(class = "tab-btn", `data-tab` = "manhattan", "Manhattan"),
491
+ tags$button(class = "tab-btn", `data-tab` = "genome", "Genome Scan"),
492
+ tags$button(class = "tab-btn", `data-tab` = "chrom", "Chr Plots"),
493
+ tags$button(class = "tab-btn", `data-tab` = "modelcomp", "Model Compare"),
494
+ tags$button(class = "tab-btn", `data-tab` = "effects", "QTL Effects"),
495
+ tags$button(class = "tab-btn", `data-tab` = "pairwise", "2D Scan"),
496
+ tags$button(class = "tab-btn", `data-tab` = "perm", "Permutations"),
497
+ tags$button(class = "tab-btn", `data-tab` = "diag", "Diagnostics"),
498
+ tags$button(class = "tab-btn", `data-tab` = "results", "QTL Table"),
499
+ tags$button(class = "tab-btn", `data-tab` = "summary", "Summary")
500
+ ),
501
+ div(id="pane_overview", class="tab-pane active", uiOutput("ui_overview")),
502
+ div(id="pane_manhattan", class="tab-pane", uiOutput("ui_manhattan")),
503
+ div(id="pane_genome", class="tab-pane", uiOutput("ui_genome")),
504
+ div(id="pane_chrom", class="tab-pane", uiOutput("ui_chrom")),
505
+ div(id="pane_modelcomp", class="tab-pane", uiOutput("ui_modelcomp")),
506
+ div(id="pane_effects", class="tab-pane", uiOutput("ui_effects")),
507
+ div(id="pane_pairwise", class="tab-pane", uiOutput("ui_pairwise")),
508
+ div(id="pane_perm", class="tab-pane", uiOutput("ui_perm")),
509
+ div(id="pane_diag", class="tab-pane", uiOutput("ui_diag")),
510
+ div(id="pane_results", class="tab-pane", uiOutput("ui_results")),
511
+ div(id="pane_summary", class="tab-pane", uiOutput("ui_summary"))
512
  )
513
+ ),
514
+
515
+ tags$script(HTML("
516
+ document.querySelectorAll('.tab-btn').forEach(function(btn){
517
+ btn.addEventListener('click',function(){
518
+ document.querySelectorAll('.tab-btn').forEach(b=>b.classList.remove('active'));
519
+ document.querySelectorAll('.tab-pane').forEach(p=>p.classList.remove('active'));
520
+ btn.classList.add('active');
521
+ document.getElementById('pane_'+btn.dataset.tab).classList.add('active');
522
+ });
523
+ });
524
+ "))
525
  )
526
 
527
+ # ═══════════════════════════════════════════════════════════════════════════════
528
+ # SERVER
529
+ # ═══════════════════════════════════════════════════════════════════════════════
530
  server <- function(input, output, session) {
531
 
532
+ # ── Theme for ggplot ──────────────────────────────────────────────────────
533
+ tq <- function(bs = 11) {
534
+ theme_minimal(base_size = bs) +
535
+ theme(
536
+ plot.background = element_rect(fill = "#13161d", color = NA),
537
+ panel.background = element_rect(fill = "#1a1e28", color = NA),
538
+ panel.grid.major = element_line(color = "#252a38", linewidth = .4),
539
+ panel.grid.minor = element_line(color = "#1e2230", linewidth = .2),
540
+ panel.border = element_rect(color = "#2e3548", fill = NA, linewidth = .7),
541
+ axis.text = element_text(color = "#5a6478", size = 8, family = "mono"),
542
+ axis.title = element_text(color = "#a0aabb", size = 9),
543
+ plot.title = element_text(color = "#e8edf5", size = 12, face = "bold", family = "mono"),
544
+ plot.subtitle = element_text(color = "#5a6478", size = 9),
545
+ legend.background = element_rect(fill = "#13161d", color = "#252a38", linewidth = .5),
546
+ legend.text = element_text(color = "#a0aabb", size = 8),
547
+ legend.title = element_text(color = "#5a6478", size = 8),
548
+ strip.background = element_rect(fill = "#1a1e28", color = "#252a38"),
549
+ strip.text = element_text(color = "#4fffb0", size = 8, family = "mono", face = "bold"),
550
+ plot.margin = margin(12, 14, 12, 14)
551
+ )
552
+ }
553
+
554
+ MC <- c(em="#4fffb0", hk="#4fc3f7", ehk="#ffb347", imp="#ff6b6b",
555
+ np="#c77dff", mr="#f06292", cim="#81ecec")
556
+
557
+ empty_ui <- function(icon="πŸ“‚", title="No Data", msg="Upload CSV files and click RUN ANALYSIS.") {
558
+ div(class="empty",
559
+ div(class="ei", icon),
560
+ tags$h3(title),
561
+ tags$p(msg))
562
+ }
563
 
564
+ # ── REACTIVE: parse cross ─────────────────────────────────────────────────
565
+ cross_rv <- reactive({
566
  req(input$geno_file, input$pheno_file)
567
+ tryCatch(
568
+ parse_cross(input$geno_file$datapath, input$pheno_file$datapath, input$cross_type),
569
+ error = function(e) {
570
+ showNotification(paste0("Parse error: ", e$message), type = "error", duration = 15)
571
+ NULL
572
+ }
573
+ )
574
  })
575
 
576
+ output$parse_preview_ui <- renderUI({
577
+ req(input$geno_file, input$pheno_file)
578
+ cr <- cross_rv()
579
+ if (is.null(cr)) {
580
+ div(class = "err-box",
581
+ "❌ Parse failed. Check:", tags$br(),
582
+ "β€’ Row 2 = chromosome names", tags$br(),
583
+ "β€’ Row 3 = cM positions", tags$br(),
584
+ "β€’ Matching sample IDs in both files")
585
+ } else {
586
+ div(class = "parse-prev",
587
+ paste0("βœ“ ", totmar(cr), " markers Β· ", nind(cr), " individuals Β· ", nchr(cr), " chromosomes"),
588
+ tags$br(),
589
+ paste0(" Traits: ", paste(names(cr$pheno), collapse=", ")))
590
+ }
591
+ })
592
+
593
+ observe({
594
+ cr <- cross_rv(); req(cr)
595
+ pnames <- names(cr$pheno)
596
+ updateSelectInput(session, "pheno_col", choices = pnames, selected = pnames[1])
597
+ runjs("document.getElementById('sdot').className='sdot on'")
598
+ output$status_text <- renderText(paste0(totmar(cr)," markers Β· ", nind(cr)," inds Β· ",nchr(cr)," chrs β€” Ready"))
599
  })
600
 
601
+ output$status_text <- renderText("Upload CSV files to begin")
 
 
 
602
 
603
+ # ── REACTIVE: analysis results ────────────────────────────────────────────
604
+ res_rv <- reactiveVal(NULL)
605
 
606
+ observeEvent(input$run_analysis, {
607
+ cr <- cross_rv()
608
+ if (is.null(cr)) { showNotification("Load data first.", type = "warning"); return() }
609
+
610
+ runjs("document.getElementById('sdot').className='sdot'")
611
+ output$status_text <- renderText("Running…")
612
+
613
+ withProgress(message = "QTL Mapping…", value = 0, {
614
+
615
+ # ── calc.genoprob ──────────────────────────────────────────────────────
616
+ cr <- tryCatch(
617
+ calc.genoprob(cr, step = input$step_size, error.prob = input$error_prob,
618
+ map.function = "kosambi"),
619
+ error = function(e) { showNotification(paste("calc.genoprob:", e$message), type="error"); NULL }
620
+ )
621
+ req(cr)
622
+ incProgress(0.08, detail = "Genoprobs OK")
623
+
624
+ # ── sim.geno (for imp method + effectplot) ─────────────────────────────
625
+ cr <- tryCatch(
626
+ sim.geno(cr, n.draws = input$n_draws, step = input$step_size,
627
+ error.prob = input$error_prob, map.function = "kosambi"),
628
+ error = function(e) cr
629
+ )
630
+ incProgress(0.07, detail = "Sim.geno OK")
631
 
632
+ pheno_idx <- match(input$pheno_col, names(cr$pheno))
633
+ if (is.na(pheno_idx)) pheno_idx <- 1L
634
+
635
+ models_sel <- input$models
636
+ if (length(models_sel) == 0) models_sel <- "hk"
637
+
638
+ # CIM needs special handling β€” separate step after main scan
639
+ base_models <- setdiff(models_sel, "cim")
640
+ do_cim <- "cim" %in% models_sel
641
 
642
  scan_results <- list()
643
  perm_results <- list()
644
 
645
+ # ── Run base scanone models ────────────────────────────────────────────
646
+ for (i in seq_along(base_models)) {
647
+ mdl <- base_models[i]
648
+ incProgress(0.45 / max(length(models_sel),1), detail = paste("Scanning:", mdl))
649
 
650
+ sc <- safe_scanone(cr, pheno_idx, mdl, input$step_size, input$error_prob)
651
+ if (!is.null(sc)) {
652
+ scan_results[[mdl]] <- sc
653
+ if (input$n_perm > 0)
654
+ perm_results[[mdl]] <- safe_perm(cr, pheno_idx, mdl, input$n_perm)
655
  }
656
  }
657
 
658
+ # ── CIM ───────────────────────────────────────────────────────────────
659
+ if (do_cim) {
660
+ incProgress(0.1, detail = "CIM scan")
661
+ cim_sc <- tryCatch(
662
+ cim(cr, pheno.col = pheno_idx, n.marcovar = 3, window = 10),
663
+ error = function(e) { message("CIM failed: ", e$message); NULL }
664
+ )
665
+ if (!is.null(cim_sc)) {
666
+ scan_results[["cim"]] <- cim_sc
667
+ # CIM permutation via scanone ehk as approximation
668
+ if (input$n_perm > 0)
669
+ perm_results[["cim"]] <- safe_perm(cr, pheno_idx, "hk", input$n_perm)
670
+ }
671
+ }
672
+
673
+ if (length(scan_results) == 0) {
674
+ showNotification("All scan methods failed. Check data.", type = "error"); return()
675
+ }
676
+ incProgress(0.1, detail = "Summarising")
677
+
678
+ # ── Determine LOD threshold ────────────────────────────────────────────
679
  lod_thr <- input$lod_thresh
680
+ if (length(perm_results) > 0) {
681
+ # Use first non-null perm result
682
+ for (pm in perm_results) {
683
+ if (!is.null(pm)) {
684
+ t_try <- tryCatch(
685
+ {sm <- summary(pm, alpha = input$alpha_thresh); sm[[1]]},
686
+ error = function(e) NULL
687
+ )
688
+ if (!is.null(t_try) && is.numeric(t_try) && !is.na(t_try)) {
689
+ lod_thr <- as.numeric(t_try)
690
+ break
691
+ }
692
+ }
693
+ }
694
  }
695
 
696
+ qtl_table <- build_qtl_table(cr, scan_results, lod_thr)
697
+ incProgress(0.1, detail = "Done")
698
 
699
+ res_rv(list(
700
+ cross = cr,
701
+ scan_results = scan_results,
702
+ perm_results = perm_results,
703
+ lod_thr = lod_thr,
704
+ qtl_table = qtl_table,
705
+ pheno_idx = pheno_idx,
706
+ pheno_col = input$pheno_col
707
+ ))
708
  })
 
709
 
710
+ res <- res_rv()
711
+ if (is.null(res)) return()
712
+ mdl_choices <- names(res$scan_results)
713
+ updateSelectInput(session, "man_model", choices = mdl_choices, selected = mdl_choices[1])
714
+ updateSelectInput(session, "chr_model", choices = mdl_choices, selected = mdl_choices[1])
715
+ qt <- res$qtl_table
716
+ qtl_sel <- if (!is.null(qt) && nrow(qt) > 0)
717
+ setNames(seq_len(nrow(qt)), paste0("Chr",qt$Chr," @ ",qt$Peak_Marker," [",qt$Model,"]"))
718
+ else c("No QTLs" = 0)
719
+ updateSelectInput(session, "eff_qtl_sel", choices = qtl_sel)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
720
 
721
+ runjs("document.getElementById('sdot').className='sdot on'")
722
+ n_qtl <- if (!is.null(qt)) nrow(qt) else 0
723
+ output$status_text <- renderText(paste0(
724
+ length(mdl_choices)," models Β· LODβ‰₯",round(lod_thr,2)," Β· ",n_qtl," QTLs found"))
 
725
  })
726
 
727
+ # ════════════════════════════════════════════════════════════════════════════
728
+ # TAB UIs
729
+ # ════════════════════════════════════════════════════════════════════════════
730
+
731
+ # ── Overview ──────────────────────────────────────────────────────────────
732
+ output$ui_overview <- renderUI({
733
+ cr <- cross_rv()
734
+ if (is.null(cr)) return(empty_ui())
735
+ res <- res_rv()
736
+ n_qtl <- if (!is.null(res) && !is.null(res$qtl_table)) nrow(res$qtl_table) else 0
737
+
738
+ tagList(
739
+ div(class="stat-row",
740
+ div(class="stat-chip g", paste0(totmar(cr)," MARKERS")),
741
+ div(class="stat-chip b", paste0(nind(cr)," INDIVIDUALS")),
742
+ div(class="stat-chip o", paste0(nchr(cr)," CHROMOSOMES")),
743
+ div(class="stat-chip r", paste0(n_qtl," QTLs FOUND"))
744
+ ),
745
+ div(class="grid2",
746
+ div(class="card",
747
+ div(class="card-hdr", div(class="card-icon b","πŸ—Ί"),
748
+ div(div(class="card-title","GENETIC MAP"),div(class="card-sub","Marker density per chromosome"))),
749
+ div(class="card-body", plotOutput("plt_map", height="300px") %>% withSpinner(color="#4fffb0",type=4))),
750
+ div(class="card",
751
+ div(class="card-hdr", div(class="card-icon o","πŸ“Š"),
752
+ div(div(class="card-title","PHENOTYPE DISTRIBUTION"),div(class="card-sub","Histogram + Q-Q"))),
753
+ div(class="card-body", plotOutput("plt_pheno", height="300px") %>% withSpinner(color="#ffb347",type=4)))
754
+ ),
755
+ div(class="card",
756
+ div(class="card-hdr", div(class="card-icon g","πŸ“"),
757
+ div(div(class="card-title","INTER-MARKER DISTANCE"),div(class="card-sub","cM spacing histogram across genome"))),
758
+ div(class="card-body", plotOutput("plt_spacing", height="220px") %>% withSpinner(color="#4fffb0",type=4)))
759
+ )
760
  })
761
 
762
+ # ── Manhattan ─────────────────────────────────────────────────────────────
763
+ output$ui_manhattan <- renderUI({
764
+ res <- res_rv()
765
+ if (is.null(res)) return(empty_ui("πŸŒƒ","Run Analysis First"))
766
+ tagList(
767
+ div(class="info-box","Red diamonds = QTLs above LOD threshold. Alternating chr colours."),
768
+ div(class="card",
769
+ div(class="card-hdr", div(class="card-icon b","πŸŒƒ"),
770
+ div(div(class="card-title","MANHATTAN PLOT"),div(class="card-sub","Genome-wide LOD scores"))),
771
+ div(class="card-body",
772
+ div(style="max-width:200px;margin-bottom:10px;",
773
+ selectInput("man_model","Model:",choices=names(res$scan_results))),
774
+ plotOutput("plt_manhattan",height="380px") %>% withSpinner(color="#4fc3f7",type=4))),
775
+ div(class="card",
776
+ div(class="card-hdr", div(class="card-icon p","🎯"),
777
+ div(div(class="card-title","INTERACTIVE MANHATTAN"),div(class="card-sub","Hover for details"))),
778
+ div(class="card-body",
779
+ plotlyOutput("plt_man_int",height="340px") %>% withSpinner(color="#c77dff",type=4)))
780
+ )
781
+ })
782
 
783
+ # ── Genome Scan ───────────────────────────────────────────────────────────
784
+ output$ui_genome <- renderUI({
785
+ res <- res_rv()
786
+ if (is.null(res)) return(empty_ui("πŸ”¬","Run Analysis First"))
787
+ div(class="card",
788
+ div(class="card-hdr", div(class="card-icon g","πŸ”¬"),
789
+ div(div(class="card-title","GENOME SCAN β€” ALL MODELS"),div(class="card-sub","LOD profiles overlaid"))),
790
+ div(class="card-body",
791
+ plotOutput("plt_genome",height="460px") %>% withSpinner(color="#4fffb0",type=4)))
792
+ })
793
 
794
+ # ── Chr Plots ─────────────────────────────────────────────────────────────
795
+ output$ui_chrom <- renderUI({
796
+ res <- res_rv()
797
+ if (is.null(res)) return(empty_ui("πŸ“ˆ","Run Analysis First"))
798
  tagList(
799
+ div(class="info-box","Per-chromosome LOD profile. Red β—† = significant QTL peak. Shaded region = 1.5-LOD CI."),
800
+ div(style="max-width:200px;margin-bottom:14px;",
801
+ selectInput("chr_model","Model:",choices=names(res$scan_results))),
802
+ plotOutput("plt_chrs", height="860px") %>% withSpinner(color="#4fc3f7",type=4)
 
 
 
803
  )
804
  })
805
 
806
+ # ── Model Compare ─────────────────────────────────────────────────────────
807
+ output$ui_modelcomp <- renderUI({
808
+ res <- res_rv()
809
+ if (is.null(res)) return(empty_ui("βš–οΈ","Run Analysis First"))
810
+ tagList(
811
+ div(class="grid2",
812
+ div(class="card",
813
+ div(class="card-hdr", div(class="card-icon o","βš–οΈ"),
814
+ div(div(class="card-title","PEAK LOD COMPARISON"),div(class="card-sub","Max LOD per model"))),
815
+ div(class="card-body", plotOutput("plt_mbar",height="300px") %>% withSpinner(color="#ffb347",type=4))),
816
+ div(class="card",
817
+ div(class="card-hdr", div(class="card-icon r","πŸ”₯"),
818
+ div(div(class="card-title","LOD HEATMAP"),div(class="card-sub","Top 40 markers Γ— models"))),
819
+ div(class="card-body", plotOutput("plt_heat",height="300px") %>% withSpinner(color="#ff6b6b",type=4)))
820
+ ),
821
+ div(class="card",
822
+ div(class="card-hdr", div(class="card-icon b","πŸ”—"),
823
+ div(div(class="card-title","MODEL CORRELATION"),div(class="card-sub","LOD agreement matrix"))),
824
+ div(class="card-body", plotOutput("plt_corr",height="300px") %>% withSpinner(color="#4fc3f7",type=4)))
825
+ )
826
  })
827
 
828
+ # ── QTL Effects ───────────────────────────────────────────────────────────
829
+ output$ui_effects <- renderUI({
830
+ res <- res_rv()
831
+ if (is.null(res)) return(empty_ui("🎻","Run Analysis First"))
832
+ qt <- res$qtl_table
833
+ qtl_sel <- if (!is.null(qt) && nrow(qt)>0)
834
+ setNames(seq_len(nrow(qt)), paste0("Chr",qt$Chr," @ ",qt$Peak_Marker," [",qt$Model,"]"))
835
+ else c("No QTLs"=0)
836
  tagList(
837
+ div(class="grid2",
838
+ div(class="card",
839
+ div(class="card-hdr", div(class="card-icon g","🎻"),
840
+ div(div(class="card-title","EFFECT PLOT"),div(class="card-sub","Mean phenotype by genotype class"))),
841
+ div(class="card-body",
842
+ div(style="margin-bottom:8px;",
843
+ selectInput("eff_qtl_sel","Select QTL:",choices=qtl_sel)),
844
+ plotOutput("plt_eff",height="280px") %>% withSpinner(color="#4fffb0",type=4))),
845
+ div(class="card",
846
+ div(class="card-hdr", div(class="card-icon o","πŸ“¦"),
847
+ div(div(class="card-title","PHENOTYPE Γ— GENOTYPE"),div(class="card-sub","Violin + boxplot"))),
848
+ div(class="card-body",
849
+ plotOutput("plt_violin",height="280px") %>% withSpinner(color="#ffb347",type=4)))
850
+ ),
851
+ div(class="card",
852
+ div(class="card-hdr", div(class="card-icon r","πŸ“‰"),
853
+ div(div(class="card-title","PVE PROFILE"),div(class="card-sub","% variance explained per QTL"))),
854
+ div(class="card-body", plotOutput("plt_pve",height="240px") %>% withSpinner(color="#ff6b6b",type=4)))
855
  )
856
  })
857
 
858
+ # ── 2D Scan ───────────────────────────────────────────────────────────────
859
+ output$ui_pairwise <- renderUI({
860
+ res <- res_rv()
861
+ if (is.null(res)) return(empty_ui("πŸ”²","Run Analysis First"))
862
+ div(class="card",
863
+ div(class="card-hdr", div(class="card-icon p","πŸ”²"),
864
+ div(div(class="card-title","2D GENOME SCAN"),div(class="card-sub","Pairwise LOD / epistasis (HK)"))),
865
+ div(class="card-body",
866
+ plotOutput("plt_2d",height="520px") %>% withSpinner(color="#c77dff",type=4)))
867
  })
868
 
869
+ # ── Permutations ──────────────────────────────────────────────────────────
870
+ output$ui_perm <- renderUI({
871
+ res <- res_rv()
872
+ if (is.null(res)) return(empty_ui("🎲","Run Analysis First"))
873
+ tagList(
874
+ div(class="card",
875
+ div(class="card-hdr", div(class="card-icon g","🎲"),
876
+ div(div(class="card-title","PERMUTATION DISTRIBUTIONS"),div(class="card-sub","Null LOD histograms per model"))),
877
+ div(class="card-body",
878
+ plotOutput("plt_perm",height="400px") %>% withSpinner(color="#4fffb0",type=4))),
879
+ div(class="card",
880
+ div(class="card-hdr", div(class="card-icon b","πŸ“‹"),
881
+ div(div(class="card-title","THRESHOLD TABLE"),div(class="card-sub","LOD thresholds at Ξ± = 0.05, 0.10, 0.20"))),
882
+ div(class="card-body", DTOutput("tbl_perm")))
883
+ )
884
  })
885
 
886
+ # ── Diagnostics ───────────────────────────────────────────────────────────
887
+ output$ui_diag <- renderUI({
888
+ cr <- cross_rv()
889
+ if (is.null(cr)) return(empty_ui("πŸ”","No Data Loaded"))
890
+ tagList(
891
+ div(class="grid2",
892
+ div(class="card",
893
+ div(class="card-hdr", div(class="card-icon o","πŸ”"),
894
+ div(div(class="card-title","MISSING DATA"),div(class="card-sub","Genotype completeness per marker"))),
895
+ div(class="card-body", plotOutput("plt_miss",height="260px") %>% withSpinner(color="#ffb347",type=4))),
896
+ div(class="card",
897
+ div(class="card-hdr", div(class="card-icon g","πŸ“Š"),
898
+ div(div(class="card-title","GENOTYPE FREQ"),div(class="card-sub","Allele frequency per marker"))),
899
+ div(class="card-body", plotOutput("plt_freq",height="260px") %>% withSpinner(color="#4fffb0",type=4)))
900
+ ),
901
+ div(class="grid2",
902
+ div(class="card",
903
+ div(class="card-hdr", div(class="card-icon b","πŸ“"),
904
+ div(div(class="card-title","MARKER SPACING"),div(class="card-sub","Inter-marker distance histogram"))),
905
+ div(class="card-body", plotOutput("plt_mspace",height="220px") %>% withSpinner(color="#4fc3f7",type=4))),
906
+ div(class="card",
907
+ div(class="card-hdr", div(class="card-icon r","🧬"),
908
+ div(div(class="card-title","CHR SUMMARY"),div(class="card-sub","Markers and span per chromosome"))),
909
+ div(class="card-body", DTOutput("tbl_chrsum")))
910
+ )
911
+ )
912
  })
913
 
914
+ # ── Results ───────────────────────────────────────────────────────────────
915
+ output$ui_results <- renderUI({
916
+ res <- res_rv()
917
+ if (is.null(res)) return(empty_ui("πŸ“‹","Run Analysis First"))
918
+ div(class="card",
919
+ div(class="card-hdr", div(class="card-icon g","πŸ“‹"),
920
+ div(div(class="card-title","QTL RESULTS TABLE"),div(class="card-sub","Peak, left/right markers, LOD, PVE, CI"))),
921
+ div(class="card-body", DTOutput("tbl_qtl")))
922
+ })
923
+
924
+ # ── Summary ───────────────────────────────────────────────────────────────
925
+ output$ui_summary <- renderUI({
926
+ res <- res_rv()
927
+ if (is.null(res)) return(empty_ui("πŸ“","Run Analysis First"))
928
  tagList(
929
+ div(class="card",
930
+ div(class="card-hdr", div(class="card-icon g","πŸ“"),
931
+ div(div(class="card-title","MODEL SUMMARY"))),
932
+ div(class="card-body", DTOutput("tbl_modsum"))),
933
+ div(class="card", style="margin-top:16px;",
934
+ div(class="card-hdr", div(class="card-icon o","πŸ†"),
935
+ div(div(class="card-title","LOD THRESHOLDS FROM PERMUTATION"))),
936
+ div(class="card-body", DTOutput("tbl_permthresh")))
937
  )
938
  })
939
 
940
+ # ════════════════════════════════════════════════════════════════════════════
941
+ # PLOTS
942
+ # ════════════════════════════════════════════════════════════════════════════
943
+
944
+ bg_plot <- "#13161d"
945
+
946
+ # ── genetic map ───────────────────────────────────────────────────────────
947
+ output$plt_map <- renderPlot({
948
+ cr <- cross_rv(); req(cr)
949
+ mp <- pull.map(cr)
950
+ df <- do.call(rbind, lapply(names(mp), function(ch)
951
+ data.frame(chr=ch, pos=unname(mp[[ch]]), stringsAsFactors=FALSE)))
952
+ df$chr <- factor(df$chr, levels=names(mp))
953
+ ggplot(df, aes(x=chr, y=pos)) +
954
+ geom_linerange(aes(ymin=0, ymax=pos), color="#252a38", linewidth=8) +
955
+ geom_point(color="#4fffb0", size=1.2, alpha=.8) +
956
+ scale_y_reverse() +
957
+ labs(title="Genetic Map", x="Chromosome", y="Position (cM)") + tq()
958
+ }, bg=bg_plot)
959
+
960
+ # ── phenotype dist ────────────────────────────────────────────────────────
961
+ output$plt_pheno <- renderPlot({
962
+ cr <- cross_rv(); req(cr, input$pheno_col)
963
+ ph <- cr$pheno[[input$pheno_col]]
964
+ df <- data.frame(v = ph[!is.na(ph)])
965
+ p1 <- ggplot(df, aes(v)) +
966
+ geom_histogram(fill="#4fffb0", color="#13161d", bins=30, alpha=.8) +
967
+ labs(title=input$pheno_col, x="Value", y="Count") + tq()
968
+ p2 <- ggplot(df, aes(sample=v)) +
969
+ stat_qq(color="#4fc3f7", size=1.5, alpha=.8) +
970
+ stat_qq_line(color="#ff6b6b", linewidth=.8) +
971
+ labs(title="Q-Q Plot", x="Theoretical", y="Sample") + tq()
972
+ gridExtra::grid.arrange(p1, p2, ncol=2)
973
+ }, bg=bg_plot)
974
+
975
+ # ── spacing histogram ─────────────────────────────────────────────────────
976
+ output$plt_spacing <- renderPlot({
977
+ cr <- cross_rv(); req(cr)
978
+ mp <- pull.map(cr)
979
+ diffs <- unlist(lapply(mp, function(m) if (length(m)>1) diff(m) else numeric(0)))
980
+ df <- data.frame(d=diffs)
981
+ ggplot(df, aes(x=d)) +
982
+ geom_histogram(fill="#c77dff", color="#13161d", bins=40, alpha=.85) +
983
+ geom_vline(xintercept=median(diffs,na.rm=TRUE), color="#ff6b6b", linetype="dashed", linewidth=.9) +
984
+ labs(title="Inter-Marker Distance", subtitle=paste0("Median: ",round(median(diffs,na.rm=TRUE),2)," cM"),
985
+ x="Distance (cM)", y="Count") + tq()
986
+ }, bg=bg_plot)
987
+
988
+ # ── helper: compute genome-wide offsets ──────────────────────────────────
989
+ genome_offsets <- function(sc) {
990
+ chrs <- as.character(unique(sc$chr))
991
+ chr_max <- sapply(chrs, function(ch) max(sc$pos[as.character(sc$chr)==ch], na.rm=TRUE))
992
+ offsets <- setNames(cumsum(c(0, chr_max[-length(chr_max)])), chrs)
993
+ offsets
994
+ }
995
+
996
+ # ── Manhattan ─────────────────────────────────────────────────────────────
997
+ output$plt_manhattan <- renderPlot({
998
+ res <- res_rv(); req(res)
999
+ mdl <- input$man_model; req(mdl)
1000
+ sc <- res$scan_results[[mdl]]; req(sc)
1001
+ sc$chr_c <- as.character(sc$chr)
1002
+ off <- genome_offsets(sc)
1003
+ sc$gx <- sc$pos + off[sc$chr_c]
1004
+ sc$alt <- as.integer(factor(sc$chr_c, levels=names(off))) %% 2 == 0
1005
+ sc$col <- ifelse(sc$alt, "#4fc3f7", "#4fffb0")
1006
+ sig <- sc[sc$lod >= res$lod_thr, ]
1007
+ chr_mid <- tapply(sc$gx, sc$chr_c, mean)
1008
+ ggplot(sc, aes(x=gx, y=lod)) +
1009
+ geom_point(aes(color=col), size=1, alpha=.7) +
1010
+ scale_color_identity() +
1011
+ { if (nrow(sig)>0) geom_point(data=sig, aes(x=gx,y=lod), color="#ff6b6b", size=3, shape=18) } +
1012
+ geom_hline(yintercept=res$lod_thr, color="#ffb347", linetype="dashed", linewidth=.8) +
1013
+ scale_x_continuous(breaks=chr_mid, labels=names(chr_mid)) +
1014
+ labs(title=paste0("Manhattan β€” ",toupper(mdl)," | LOD threshold = ",round(res$lod_thr,2)),
1015
+ x="Chromosome", y="LOD Score") +
1016
+ tq() + theme(panel.grid.major.x=element_blank())
1017
+ }, bg=bg_plot)
1018
+
1019
+ # ── Interactive Manhattan ─────────────────────────────────────────────────
1020
+ output$plt_man_int <- renderPlotly({
1021
+ res <- res_rv(); req(res)
1022
+ mdl <- input$man_model; req(mdl)
1023
+ sc <- res$scan_results[[mdl]]; req(sc)
1024
+ sc$chr_c <- as.character(sc$chr)
1025
+ off <- genome_offsets(sc)
1026
+ sc$gx <- sc$pos + off[sc$chr_c]
1027
+ sc$sig <- sc$lod >= res$lod_thr
1028
+ sc$lbl <- paste0(rownames(sc),"<br>Chr:",sc$chr," Pos:",round(sc$pos,1)," LOD:",round(sc$lod,3))
1029
+ plot_ly(sc, x=~gx, y=~lod, color=~sig, colors=c("#4fffb0","#ff6b6b"),
1030
+ text=~lbl, hovertemplate="%{text}<extra></extra>",
1031
+ type="scatter", mode="markers", marker=list(size=4, opacity=.8)) %>%
1032
+ add_lines(y=res$lod_thr, line=list(color="#ffb347",dash="dash",width=1.5),
1033
+ showlegend=FALSE, name="Threshold") %>%
1034
+ layout(paper_bgcolor=bg_plot, plot_bgcolor="#1a1e28",
1035
+ font=list(color="#a0aabb", family="monospace"),
1036
+ xaxis=list(title="Genome Position",gridcolor="#252a38"),
1037
+ yaxis=list(title="LOD Score",gridcolor="#252a38"),
1038
+ margin=list(t=10,b=40,l=50,r=20),
1039
+ legend=list(font=list(color="#a0aabb")))
1040
+ })
1041
+
1042
+ # ── Genome scan all models ────────────────────────────────────────────────
1043
+ output$plt_genome <- renderPlot({
1044
+ res <- res_rv(); req(res)
1045
+ sc_ref <- res$scan_results[[1]]
1046
+ off <- genome_offsets(sc_ref)
1047
+ dfs <- lapply(names(res$scan_results), function(mdl) {
1048
+ sc <- res$scan_results[[mdl]]
1049
+ sc$chr_c <- as.character(sc$chr)
1050
+ sc$gx <- sc$pos + off[sc$chr_c]
1051
+ sc$model <- mdl; sc
1052
+ })
1053
+ df_all <- dplyr::bind_rows(dfs)
1054
+ vls <- data.frame(x = off[-1])
1055
+ ggplot(df_all, aes(x=gx, y=lod, color=model)) +
1056
+ geom_vline(data=vls, aes(xintercept=x), color="#252a38", linewidth=.4) +
1057
+ geom_line(linewidth=.6, alpha=.85) +
1058
+ geom_hline(yintercept=res$lod_thr, color="#ffb347", linetype="dashed", linewidth=.7) +
1059
+ scale_color_manual(values=MC, na.value="#5a6478") +
1060
+ labs(title="Genome Scan β€” All Models", x="Genome Position (cM)", y="LOD Score", color="Model") +
1061
+ tq() + theme(legend.position="right")
1062
+ }, bg=bg_plot)
1063
+
1064
+ # ── Per-chromosome grid ────────────────────────────────────────────────────
1065
+ output$plt_chrs <- renderPlot({
1066
+ res <- res_rv(); req(res)
1067
+ mdl <- input$chr_model; req(mdl)
1068
+ sc <- res$scan_results[[mdl]]; req(sc)
1069
+ qt <- res$qtl_table
1070
+ chrs <- as.character(unique(sc$chr))
1071
+ nc <- min(4L, length(chrs)); nr <- ceiling(length(chrs)/nc)
1072
+ y_max <- max(sc$lod, na.rm=TRUE) * 1.1
1073
+
1074
  plots <- lapply(chrs, function(ch) {
1075
+ sc_ch <- sc[as.character(sc$chr)==ch,]
1076
+ p <- ggplot(sc_ch, aes(x=pos, y=lod)) +
1077
+ geom_ribbon(aes(ymin=0, ymax=lod), fill="#4fffb0", alpha=.12) +
1078
+ geom_line(color="#4fffb0", linewidth=.9) +
1079
+ geom_hline(yintercept=res$lod_thr, color="#ffb347", linetype="dashed", linewidth=.5) +
1080
+ scale_y_continuous(limits=c(0, y_max)) +
1081
+ labs(title=paste0("Chr ",ch), x=NULL, y="LOD") +
1082
+ tq(bs=8) + theme(plot.margin=margin(5,7,5,7))
1083
+
1084
+ if (!is.null(qt) && nrow(qt)>0) {
1085
+ qt_sub <- qt[qt$Chr==ch & qt$Model==mdl,]
1086
+ if (nrow(qt_sub)>0) {
1087
+ # shade CI
1088
+ for (i in seq_len(nrow(qt_sub))) {
1089
+ if (!is.na(qt_sub$Left_pos_cM[i]) && !is.na(qt_sub$Right_pos_cM[i]))
1090
+ p <- p + annotate("rect",
1091
+ xmin=qt_sub$Left_pos_cM[i], xmax=qt_sub$Right_pos_cM[i],
1092
+ ymin=-Inf, ymax=Inf, fill="#ff6b6b", alpha=.12)
1093
+ }
1094
+ p <- p + geom_point(data=qt_sub, aes(x=Peak_pos_cM, y=LOD),
1095
+ color="#ff6b6b", size=3, shape=18)
1096
+ }
1097
  }
1098
  p
1099
  })
1100
+ do.call(gridExtra::grid.arrange, c(plots, list(ncol=nc, nrow=nr)))
1101
+ }, bg=bg_plot)
1102
 
1103
+ # ── Model bar ─────────────────────────────────────────────────────────────
1104
+ output$plt_mbar <- renderPlot({
1105
+ res <- res_rv(); req(res)
1106
+ df <- data.frame(
1107
+ model = names(res$scan_results),
1108
+ max_lod = sapply(res$scan_results, function(s) max(s$lod, na.rm=TRUE))
1109
+ )
1110
+ df$model <- factor(df$model, levels=df$model[order(df$max_lod)])
1111
+ ggplot(df, aes(x=model, y=max_lod, fill=model)) +
1112
+ geom_col(width=.6, alpha=.85) +
1113
+ geom_hline(yintercept=res$lod_thr, color="#ffb347", linetype="dashed", linewidth=.8) +
1114
+ geom_text(aes(label=round(max_lod,2)), hjust=-0.15, color="#e8edf5", size=3, family="mono") +
1115
+ scale_fill_manual(values=MC, na.value="#5a6478") +
1116
+ coord_flip(ylim=c(0, max(df$max_lod)*1.2)) +
1117
+ labs(title="Peak LOD per Model", x=NULL, y="Max LOD") +
1118
+ tq() + theme(legend.position="none")
1119
+ }, bg=bg_plot)
1120
 
1121
+ # ── Heatmap ───────────────────────────────────────────────────────────────
1122
+ output$plt_heat <- renderPlot({
1123
+ res <- res_rv(); req(res)
1124
+ all_sc <- dplyr::bind_rows(lapply(names(res$scan_results), function(m) {
1125
+ sc <- res$scan_results[[m]]; sc$model <- m; sc$marker <- rownames(sc); sc
1126
+ }))
1127
+ top_mk <- all_sc %>% group_by(marker) %>% summarise(ml=max(lod),.groups="drop") %>%
1128
+ arrange(desc(ml)) %>% slice_head(n=40) %>% pull(marker)
1129
+ hm <- all_sc %>% filter(marker %in% top_mk)
1130
+ ggplot(hm, aes(x=model, y=marker, fill=lod)) +
1131
+ geom_tile(color="#0d0f14", linewidth=.3) +
1132
+ scale_fill_gradientn(colors=c("#1a1e28","#4fffb0","#ffb347","#ff6b6b"), name="LOD") +
1133
+ labs(title="LOD Heatmap", x="Model", y="Marker") +
1134
+ tq() + theme(axis.text.x=element_text(angle=30,hjust=1),
1135
+ axis.text.y=element_text(size=6))
1136
+ }, bg=bg_plot)
1137
 
1138
+ # ── Model correlation ─────────────────────────────────────────────────────
1139
+ output$plt_corr <- renderPlot({
1140
+ res <- res_rv(); req(res, length(res$scan_results)>=2)
1141
+ sc_list <- lapply(names(res$scan_results), function(m) {
1142
+ sc <- res$scan_results[[m]]
1143
+ data.frame(marker=rownames(sc), lod=sc$lod, stringsAsFactors=FALSE)
1144
+ }); names(sc_list) <- names(res$scan_results)
1145
+ cmk <- Reduce(intersect, lapply(sc_list,`[[`,"marker"))
1146
+ mat <- sapply(sc_list, function(s) s$lod[match(cmk, s$marker)])
1147
+ cr_m <- cor(mat, use="complete.obs")
1148
+ df <- reshape2::melt(cr_m); names(df) <- c("m1","m2","corr")
1149
+ ggplot(df, aes(x=m1, y=m2, fill=corr)) +
1150
+ geom_tile(color="#0d0f14", linewidth=.5) +
1151
+ geom_text(aes(label=round(corr,2)), size=3, color="#e8edf5", family="mono") +
1152
+ scale_fill_gradient2(low="#ff6b6b", mid="#1a1e28", high="#4fffb0", midpoint=0, limits=c(-1,1), name="r") +
1153
+ labs(title="Model LOD Correlation", x=NULL, y=NULL) +
1154
+ tq() + theme(axis.text.x=element_text(angle=30,hjust=1))
1155
+ }, bg=bg_plot)
1156
+
1157
+ # ── Effect plot ───────────────────────────────────────────────────────────
1158
+ output$plt_eff <- renderPlot({
1159
+ res <- res_rv(); req(res)
1160
+ sel <- as.integer(input$eff_qtl_sel); req(!is.null(sel), sel > 0)
1161
+ qt <- res$qtl_table; req(nrow(qt)>=sel)
1162
+ mk <- qt$Peak_Marker[sel]
1163
+ tryCatch({
1164
+ eff <- effectplot(res$cross, mname1=mk, pheno.col=res$pheno_idx, draw=FALSE)
1165
+ mns <- eff$Means; ses <- eff$SEs
1166
+ df <- data.frame(geno=names(mns), mean=as.numeric(mns), se=as.numeric(ses))
1167
+ ggplot(df, aes(x=geno, y=mean, fill=geno)) +
1168
+ geom_col(width=.5, alpha=.85) +
1169
+ geom_errorbar(aes(ymin=mean-se, ymax=mean+se), width=.13, color="#e8edf5", linewidth=.8) +
1170
+ scale_fill_manual(values=c("#4fffb0","#ff6b6b","#4fc3f7","#ffb347")) +
1171
+ labs(title=paste0("Effect: ",mk), x="Genotype", y=res$pheno_col) +
1172
+ tq() + theme(legend.position="none")
1173
+ }, error = function(e)
1174
+ ggplot()+annotate("text",x=.5,y=.5,label=paste("Effect unavailable:",e$message),
1175
+ color="#5a6478",size=4)+tq()
1176
  )
1177
+ }, bg=bg_plot)
1178
 
1179
+ # ── Violin ────────────────────────────────────────────────────────────────
1180
+ output$plt_violin <- renderPlot({
1181
+ res <- res_rv(); req(res)
1182
+ sel <- as.integer(input$eff_qtl_sel); req(!is.null(sel), sel > 0)
1183
+ qt <- res$qtl_table; req(nrow(qt)>=sel)
1184
+ mk <- qt$Peak_Marker[sel]
1185
  tryCatch({
1186
+ # pull.geno returns inds x markers matrix
1187
+ gm <- pull.geno(res$cross)
1188
+ req(mk %in% colnames(gm))
1189
+ gv <- gm[, mk]
1190
+ pv <- res$cross$pheno[[res$pheno_idx]]
1191
+ df <- data.frame(geno=as.character(gv), pheno=pv) %>%
1192
+ filter(!is.na(geno), !is.na(pheno))
1193
+ lab_map <- c("1"="AA","2"="AB","3"="BB")
1194
+ df$geno <- ifelse(df$geno %in% names(lab_map), lab_map[df$geno], df$geno)
1195
+ df$geno <- factor(df$geno)
1196
+ ggplot(df, aes(x=geno, y=pheno, fill=geno)) +
1197
+ geom_violin(alpha=.4, trim=FALSE) +
1198
+ geom_boxplot(width=.12, outlier.color="#ff6b6b", alpha=.7) +
1199
+ scale_fill_manual(values=c("#4fffb0","#ff6b6b","#4fc3f7")) +
1200
+ labs(title=paste0("PhenoΓ—Geno: ",mk), x="Genotype", y=res$pheno_col) +
1201
+ tq() + theme(legend.position="none")
1202
+ }, error = function(e)
1203
+ ggplot()+annotate("text",x=.5,y=.5,label=paste("Unavailable:",e$message),
1204
+ color="#5a6478",size=4)+tq()
1205
+ )
1206
+ }, bg=bg_plot)
1207
 
1208
+ # ── PVE ───────────────────────────────────────────────────────────────────
1209
+ output$plt_pve <- renderPlot({
1210
+ res <- res_rv(); req(res)
1211
+ qt <- res$qtl_table; req(!is.null(qt), nrow(qt)>0)
1212
+ qt_avg <- qt %>% group_by(Chr, Peak_pos_cM) %>%
1213
+ summarise(PVE=mean(PVE_pct, na.rm=TRUE), .groups="drop") %>%
1214
+ mutate(label=paste0("Chr",Chr,"@",round(Peak_pos_cM,1)))
1215
+ ggplot(qt_avg, aes(x=reorder(label, PVE), y=PVE, fill=PVE)) +
1216
+ geom_col(width=.65) +
1217
+ geom_text(aes(label=paste0(round(PVE,1),"%")), hjust=-0.15, size=3, color="#e8edf5", family="mono") +
1218
+ scale_fill_gradientn(colors=c("#4fc3f7","#4fffb0","#ffb347","#ff6b6b"), guide="none") +
1219
+ coord_flip(ylim=c(0, max(qt_avg$PVE)*1.2)) +
1220
+ labs(title="PVE per QTL (mean across models)", x=NULL, y="PVE (%)") + tq()
1221
+ }, bg=bg_plot)
1222
 
1223
+ # ── 2D scan ───────────────────────────────────────────────────────────────
1224
+ output$plt_2d <- renderPlot({
1225
+ res <- res_rv(); req(res)
1226
+ sc2 <- tryCatch(
1227
+ scantwo(res$cross, pheno.col=res$pheno_idx, method="hk", verbose=FALSE),
1228
+ error = function(e) NULL
1229
+ )
1230
  if (is.null(sc2)) {
1231
+ ggplot()+annotate("text",x=.5,y=.5,label="2D scan unavailable (need β‰₯2 chromosomes and genoprobs)",
1232
+ color="#5a6478",size=4)+tq()
1233
  } else {
1234
+ # sc2$lod is a matrix; use the full LOD (interaction) component
1235
+ lm <- sc2$lod
1236
+ n <- nrow(lm)
1237
+ df2 <- expand.grid(x=1:n, y=1:n)
1238
+ df2$lod <- as.vector(lm)
1239
+ ggplot(df2, aes(x=x,y=y,fill=lod)) +
1240
+ geom_tile() +
1241
+ scale_fill_gradientn(
1242
+ colors=c("#1a1e28","#4fffb0","#ffb347","#ff6b6b"),
1243
+ name="LOD", na.value="#1a1e28") +
1244
+ labs(title="2D Genome Scan (Pairwise LOD)", x="Position 1", y="Position 2") +
1245
+ tq() + coord_equal()
1246
  }
1247
+ }, bg=bg_plot)
1248
 
1249
+ # ── Permutation histograms ────────────────────────────────────────────────
1250
+ output$plt_perm <- renderPlot({
1251
+ res <- res_rv(); req(res, length(res$perm_results)>0)
1252
+ valid_perms <- Filter(Negate(is.null), res$perm_results)
1253
+ if (length(valid_perms)==0) {
1254
+ ggplot()+annotate("text",x=.5,y=.5,label="No permutation results available",
1255
+ color="#5a6478",size=5)+tq()
1256
+ return()
1257
+ }
1258
+ nc <- min(3L, length(valid_perms)); nr <- ceiling(length(valid_perms)/nc)
1259
+ plots <- lapply(names(valid_perms), function(mdl) {
1260
+ pm <- valid_perms[[mdl]]
1261
+ lv <- as.numeric(pm)
1262
+ df <- data.frame(lod=lv)
1263
+ thr <- tryCatch(as.numeric(summary(pm, alpha=0.05)[[1]]), error=function(e) res$lod_thr)
1264
+ ggplot(df, aes(x=lod)) +
1265
+ geom_histogram(fill=MC[mdl] %||% "#4fffb0", color="#13161d", bins=30, alpha=.8) +
1266
+ geom_vline(xintercept=thr, color="#ff6b6b", linetype="dashed", linewidth=.9) +
1267
+ labs(title=paste0(toupper(mdl)," β€” Ξ±=0.05 thr=",round(thr,2)),
1268
+ x="Max LOD", y="Count") + tq(bs=9)
1269
+ })
1270
+ do.call(gridExtra::grid.arrange, c(plots, list(ncol=nc)))
1271
+ }, bg=bg_plot)
1272
+
1273
+ # ── Diagnostics: missing ─────────────────────────────────────────────────
1274
+ output$plt_miss <- renderPlot({
1275
+ cr <- cross_rv(); req(cr)
1276
+ ms <- nmissing(cr, what="mar")
1277
+ df <- data.frame(marker=names(ms), miss=ms)
1278
+ ggplot(df, aes(x=reorder(marker,-miss), y=miss, fill=miss)) +
1279
+ geom_col() +
1280
+ scale_fill_gradientn(colors=c("#4fffb0","#ffb347","#ff6b6b"), guide="none") +
1281
+ labs(title="Missing Genotype Data per Marker", x="Marker", y="# Missing") +
1282
+ tq() + theme(axis.text.x=element_blank(), axis.ticks.x=element_blank())
1283
+ }, bg=bg_plot)
1284
+
1285
+ # ── Diagnostics: allele freq ──────────────────────────────────────────────
1286
+ output$plt_freq <- renderPlot({
1287
+ cr <- cross_rv(); req(cr)
1288
+ gt <- pull.geno(cr)
1289
+ df <- data.frame(
1290
+ marker = rep(colnames(gt), 3),
1291
+ allele = rep(c("AA","AB","BB"), each=ncol(gt)),
1292
+ freq = c(colMeans(gt==1, na.rm=TRUE),
1293
+ colMeans(gt==2, na.rm=TRUE),
1294
+ colMeans(gt==3, na.rm=TRUE))
1295
  )
1296
+ ggplot(df, aes(x=marker, y=freq, fill=allele)) +
1297
+ geom_col(position="stack", width=1) +
1298
+ scale_fill_manual(values=c(AA="#4fffb0", AB="#ffb347", BB="#ff6b6b")) +
1299
+ labs(title="Genotype Frequency per Marker", x="Marker", y="Frequency") +
1300
+ tq() + theme(axis.text.x=element_blank(), axis.ticks.x=element_blank())
1301
+ }, bg=bg_plot)
1302
+
1303
+ # ── Diagnostics: marker spacing ───────────────────────────────────────────
1304
+ output$plt_mspace <- renderPlot({
1305
+ cr <- cross_rv(); req(cr)
1306
+ mp <- pull.map(cr)
1307
+ diffs <- unlist(lapply(mp, function(m) if (length(m)>1) diff(m) else numeric(0)))
1308
+ df <- data.frame(d=diffs)
1309
+ ggplot(df, aes(x=d)) +
1310
+ geom_histogram(fill="#4fc3f7", color="#13161d", bins=35, alpha=.8) +
1311
+ geom_vline(xintercept=median(diffs,na.rm=TRUE), color="#ffb347", linetype="dashed", linewidth=.9) +
1312
+ labs(title="Inter-Marker Spacing", subtitle=paste0("Median: ",round(median(diffs,na.rm=TRUE),2)," cM"),
1313
+ x="Distance (cM)", y="Count") + tq()
1314
+ }, bg=bg_plot)
1315
+
1316
+ # ════════════════════════════════════════════════════════════════════════════
1317
+ # TABLES
1318
+ # ══════════════════════════════════════════════════��═════════════════════════
1319
+
1320
+ output$tbl_qtl <- renderDT({
1321
+ res <- res_rv(); req(res)
1322
+ qt <- res$qtl_table; req(!is.null(qt), nrow(qt)>0)
1323
+ datatable(qt, rownames=FALSE, filter="top",
1324
+ options=list(pageLength=25, scrollX=TRUE, dom="Blfrtip",
1325
+ columnDefs=list(list(className="dt-center",targets="_all"))),
1326
+ class="display compact nowrap") %>%
1327
+ formatStyle("LOD", background=styleColorBar(range(qt$LOD),"#4fffb0"),
1328
+ backgroundSize="100% 75%", backgroundRepeat="no-repeat", backgroundPosition="center") %>%
1329
+ formatStyle("PVE_pct", background=styleColorBar(c(0,max(qt$PVE_pct,na.rm=TRUE)),"#4fc3f7"),
1330
+ backgroundSize="100% 75%", backgroundRepeat="no-repeat", backgroundPosition="center") %>%
1331
+ formatRound(c("Peak_pos_cM","LOD","PVE_pct","Left_pos_cM","Right_pos_cM","CI_width_cM"), 3)
1332
  })
1333
 
1334
+ output$tbl_chrsum <- renderDT({
1335
+ cr <- cross_rv(); req(cr)
1336
+ mp <- pull.map(cr)
1337
+ df <- data.frame(
1338
+ Chr = names(mp),
1339
+ Markers = sapply(mp, length),
1340
+ Start_cM = round(sapply(mp, min),2),
1341
+ End_cM = round(sapply(mp, max),2),
1342
+ Span_cM = round(sapply(mp, function(m) max(m)-min(m)),2),
1343
+ Mean_gap = round(sapply(mp, function(m) if(length(m)>1) mean(diff(m)) else NA),2)
1344
+ )
1345
+ datatable(df, rownames=FALSE, options=list(dom="t",pageLength=50), class="display compact")
1346
  })
1347
 
1348
+ output$tbl_perm <- renderDT({
1349
+ res <- res_rv(); req(res, length(res$perm_results)>0)
1350
+ rows <- lapply(names(res$perm_results), function(m) {
1351
+ p <- res$perm_results[[m]]; if (is.null(p)) return(NULL)
1352
+ sm <- tryCatch(summary(p, alpha=c(0.05,0.10,0.20)), error=function(e) NULL)
1353
+ if (is.null(sm)) return(NULL)
1354
+ sv <- as.numeric(sm)
1355
+ data.frame(Model=m, `Ξ±0.05`=round(sv[1],3), `Ξ±0.10`=round(sv[2],3), `Ξ±0.20`=round(sv[3],3),
1356
+ N_perm=length(as.numeric(p)), check.names=FALSE)
1357
+ })
1358
+ df <- dplyr::bind_rows(Filter(Negate(is.null), rows)); req(nrow(df)>0)
1359
+ datatable(df, rownames=FALSE, options=list(dom="t"), class="display compact")
1360
  })
1361
 
1362
+ output$tbl_modsum <- renderDT({
1363
+ res <- res_rv(); req(res)
1364
+ df <- data.frame(
1365
+ Model = names(res$scan_results),
1366
+ Max_LOD = round(sapply(res$scan_results, function(s) max(s$lod,na.rm=TRUE)),4),
1367
+ Mean_LOD = round(sapply(res$scan_results, function(s) mean(s$lod,na.rm=TRUE)),4),
1368
+ QTLs_Found = sapply(names(res$scan_results), function(m)
1369
+ if (!is.null(res$qtl_table) && nrow(res$qtl_table)>0) sum(res$qtl_table$Model==m) else 0L),
1370
+ LOD_Thresh = round(res$lod_thr,3),
1371
+ Perm_run = sapply(names(res$scan_results), function(m) !is.null(res$perm_results[[m]]))
1372
+ )
1373
+ datatable(df, rownames=FALSE, options=list(dom="t",pageLength=20), class="display compact") %>%
1374
+ formatStyle("Max_LOD", color="#4fffb0", fontWeight="bold") %>%
1375
+ formatStyle("QTLs_Found", color="#ff6b6b", fontWeight="bold")
1376
  })
1377
 
1378
+ output$tbl_permthresh <- renderDT({
1379
+ res <- res_rv(); req(res)
1380
+ rows <- lapply(names(res$perm_results), function(m) {
1381
+ p <- res$perm_results[[m]]; if (is.null(p)) return(NULL)
1382
+ sm <- tryCatch(summary(p, alpha=c(0.05,0.10,0.20)), error=function(e) NULL)
1383
+ if (is.null(sm)) return(NULL)
1384
+ sv <- as.numeric(sm)
1385
+ data.frame(Model=m, alpha_0.05=round(sv[1],3), alpha_0.10=round(sv[2],3),
1386
+ alpha_0.20=round(sv[3],3), check.names=FALSE)
1387
+ })
1388
+ df <- dplyr::bind_rows(Filter(Negate(is.null), rows))
1389
+ if (nrow(df)==0) df <- data.frame(Note="No permutation data available")
1390
+ datatable(df, rownames=FALSE, options=list(dom="t"), class="display compact")
1391
  })
1392
 
1393
+ # ════════════════════════════════════════════════════════════════════════════
1394
+ # EXPORTS
1395
+ # ════════════════════════════════════════════════════════════════════════════
1396
+
1397
+ # ── Excel export with formatted workbook ─────────────────────────────────
1398
+ output$dl_excel <- downloadHandler(
1399
+ filename = function() paste0("QTL_Results_", Sys.Date(), ".xlsx"),
1400
+ content = function(file) {
1401
+ res <- res_rv()
1402
+ wb <- createWorkbook()
1403
+
1404
+ hdr_style <- createStyle(fontColour="#FFFFFF", fgFill="#1a6cf5",
1405
+ fontSize=10, fontName="Courier New",
1406
+ halign="CENTER", textDecoration="bold",
1407
+ border="Bottom", borderColour="#aaaaaa")
1408
+ row_even <- createStyle(fgFill="#f0f4fb")
1409
+ num3 <- createStyle(numFmt="0.000", halign="CENTER")
1410
+ num4 <- createStyle(numFmt="0.0000", halign="CENTER")
1411
+ cen <- createStyle(halign="CENTER")
1412
+ bold <- createStyle(textDecoration="bold", halign="CENTER")
1413
+
1414
+ # Sheet 1: QTL Results
1415
+ addWorksheet(wb, "QTL_Results")
1416
+ if (!is.null(res) && !is.null(res$qtl_table) && nrow(res$qtl_table)>0) {
1417
+ qt <- res$qtl_table
1418
+ writeDataTable(wb, "QTL_Results", qt, tableStyle="TableStyleMedium2",
1419
+ startRow=1, startCol=1)
1420
+ addStyle(wb, "QTL_Results", hdr_style, rows=1, cols=seq_len(ncol(qt)), gridExpand=TRUE)
1421
+ num_cols <- which(names(qt) %in% c("Peak_pos_cM","LOD","PVE_pct","Left_pos_cM",
1422
+ "Right_pos_cM","CI_width_cM","Additive_eff","Dom_eff"))
1423
+ if (length(num_cols)>0)
1424
+ addStyle(wb, "QTL_Results", num3, rows=seq(2, nrow(qt)+1),
1425
+ cols=num_cols, gridExpand=TRUE, stack=TRUE)
1426
+ lod_col <- which(names(qt)=="LOD")
1427
+ conditionalFormatting(wb, "QTL_Results", cols=lod_col,
1428
+ rows=seq(2, nrow(qt)+1), type="colorScale",
1429
+ style=c("#ffffcc","#41ab5d","#084594"))
1430
+ pve_col <- which(names(qt)=="PVE_pct")
1431
+ conditionalFormatting(wb, "QTL_Results", cols=pve_col,
1432
+ rows=seq(2, nrow(qt)+1), type="colorScale",
1433
+ style=c("#f7fbff","#74c476","#006d2c"))
1434
+ setColWidths(wb, "QTL_Results", cols=seq_len(ncol(qt)),
1435
+ widths=pmax(nchar(names(qt))+3, 12))
1436
  } else {
1437
+ writeData(wb, "QTL_Results", data.frame(Note="No significant QTLs found above threshold."))
1438
+ }
1439
+
1440
+ # Sheet 2: All scan data (each model gets sub-block)
1441
+ if (!is.null(res)) {
1442
+ addWorksheet(wb, "Scan_Profiles")
1443
+ start_col <- 1
1444
+ for (mdl in names(res$scan_results)) {
1445
+ sc <- res$scan_results[[mdl]]
1446
+ df <- data.frame(Chr=sc$chr, Pos_cM=round(sc$pos,3), LOD=round(sc$lod,4))
1447
+ names(df)[3] <- paste0("LOD_",mdl)
1448
+ hdr_df <- data.frame(x=paste0("=== ",toupper(mdl)," ==="))
1449
+ names(hdr_df) <- " "
1450
+ writeData(wb, "Scan_Profiles", hdr_df, startRow=1, startCol=start_col,
1451
+ colNames=TRUE)
1452
+ writeData(wb, "Scan_Profiles", df, startRow=2, startCol=start_col,
1453
+ colNames=TRUE)
1454
+ addStyle(wb, "Scan_Profiles", hdr_style, rows=2,
1455
+ cols=start_col:(start_col+2), gridExpand=TRUE)
1456
+ setColWidths(wb, "Scan_Profiles", cols=start_col:(start_col+2),
1457
+ widths=c(8,10,14))
1458
+ start_col <- start_col + 4
1459
+ }
1460
  }
1461
+
1462
+ # Sheet 3: Model Summary
1463
+ if (!is.null(res)) {
1464
+ addWorksheet(wb, "Model_Summary")
1465
+ df_sum <- data.frame(
1466
+ Model = names(res$scan_results),
1467
+ Max_LOD = round(sapply(res$scan_results, function(s) max(s$lod,na.rm=TRUE)),4),
1468
+ Mean_LOD = round(sapply(res$scan_results, function(s) mean(s$lod,na.rm=TRUE)),4),
1469
+ QTLs_Found = sapply(names(res$scan_results), function(m)
1470
+ if (!is.null(res$qtl_table) && nrow(res$qtl_table)>0) sum(res$qtl_table$Model==m) else 0L),
1471
+ LOD_Threshold = round(res$lod_thr, 3)
1472
+ )
1473
+ writeDataTable(wb, "Model_Summary", df_sum, tableStyle="TableStyleMedium3")
1474
+ addStyle(wb, "Model_Summary", hdr_style, rows=1, cols=1:5, gridExpand=TRUE)
1475
+ setColWidths(wb, "Model_Summary", cols=1:5, widths=c(16,12,12,14,16))
1476
+ }
1477
+
1478
+ # Sheet 4: Permutation Thresholds
1479
+ if (!is.null(res) && length(res$perm_results)>0) {
1480
+ addWorksheet(wb, "Perm_Thresholds")
1481
+ rows_p <- lapply(names(res$perm_results), function(m) {
1482
+ p <- res$perm_results[[m]]; if (is.null(p)) return(NULL)
1483
+ sm <- tryCatch(summary(p, alpha=c(0.05,0.10,0.20)), error=function(e) NULL)
1484
+ if (is.null(sm)) return(NULL)
1485
+ sv <- as.numeric(sm)
1486
+ data.frame(Model=m, alpha_0.05=round(sv[1],3), alpha_0.10=round(sv[2],3),
1487
+ alpha_0.20=round(sv[3],3), N_perm=length(as.numeric(p)),
1488
+ check.names=FALSE)
1489
+ })
1490
+ df_p <- dplyr::bind_rows(Filter(Negate(is.null), rows_p))
1491
+ if (nrow(df_p)>0) {
1492
+ writeDataTable(wb, "Perm_Thresholds", df_p, tableStyle="TableStyleMedium4")
1493
+ addStyle(wb, "Perm_Thresholds", hdr_style, rows=1, cols=1:5, gridExpand=TRUE)
1494
+ setColWidths(wb, "Perm_Thresholds", cols=1:5, widths=c(12,12,12,12,10))
1495
+ }
1496
+ }
1497
+
1498
+ # Sheet 5: Chromosome Map
1499
+ addWorksheet(wb, "Chr_Map")
1500
+ cr <- res$cross
1501
+ mp <- pull.map(cr)
1502
+ df_map <- do.call(rbind, lapply(names(mp), function(ch)
1503
+ data.frame(Chr=ch, Marker=names(mp[[ch]]), Pos_cM=round(unname(mp[[ch]]),3),
1504
+ stringsAsFactors=FALSE)))
1505
+ writeDataTable(wb, "Chr_Map", df_map, tableStyle="TableStyleMedium5")
1506
+ addStyle(wb, "Chr_Map", hdr_style, rows=1, cols=1:3, gridExpand=TRUE)
1507
+ setColWidths(wb, "Chr_Map", cols=1:3, widths=c(8,24,12))
1508
+
1509
+ saveWorkbook(wb, file, overwrite=TRUE)
1510
+ }
1511
+ )
1512
+
1513
+ # ── CSV export ────────────────────────────────────────────────────────────
1514
+ output$dl_csv <- downloadHandler(
1515
+ filename = function() paste0("QTL_Results_", Sys.Date(), ".csv"),
1516
+ content = function(file) {
1517
+ res <- res_rv()
1518
+ if (!is.null(res) && !is.null(res$qtl_table) && nrow(res$qtl_table)>0)
1519
+ write.csv(res$qtl_table, file, row.names=FALSE)
1520
+ else
1521
+ write.csv(data.frame(Note="No QTLs above threshold"), file, row.names=FALSE)
1522
  }
1523
  )
1524
  }
1525
 
1526
+ # ── Pipe-safe null-coalescing ─────────────────────────────────────────────────
1527
+ `%||%` <- function(a, b) if (!is.null(a) && !is.na(a)) a else b
1528
+
1529
  shinyApp(ui = ui, server = server)