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

Update app.R

Browse files
Files changed (1) hide show
  1. app.R +404 -518
app.R CHANGED
@@ -8,604 +8,490 @@ library(shinycssloaders)
8
  library(shinyjs)
9
  library(plotly)
10
  library(gridExtra)
 
11
 
12
- # --- Your custom data parser functions ---
13
  parse_custom_cross <- function(geno_path, pheno_path, cross_type = "f2") {
14
- geno_raw <- read.csv(geno_path, header=FALSE, stringsAsFactors=FALSE,
15
- check.names=FALSE, na.strings=c("NA","","N/A"))
16
- col_names <- as.character(geno_raw[1,])
17
- chr_row <- as.character(geno_raw[2,])
18
- pos_row <- as.character(geno_raw[3,])
19
- ind_data <- geno_raw[4:nrow(geno_raw),,drop=FALSE]
20
- n_cols <- ncol(geno_raw)
21
- marker_cols <- 2:n_cols
22
- marker_names <- col_names[marker_cols]
23
- chromosomes <- chr_row[marker_cols]
24
- positions <- suppressWarnings(as.numeric(pos_row[marker_cols]))
25
-
26
- # Clean chromosome labels
27
- chromosomes <- gsub("^[Cc]hr0*", "", chromosomes)
28
- chr_numeric <- suppressWarnings(as.integer(chromosomes))
29
- chromosomes <- ifelse(!is.na(chr_numeric), as.character(chr_numeric), chromosomes)
30
-
31
- ind_ids <- as.character(ind_data[,1])
32
- geno_mat <- as.matrix(ind_data[,marker_cols])
33
- class(geno_mat) <- "numeric"
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
-
38
- # Read phenotype
39
- pheno_raw <- read.csv(pheno_path, header=TRUE, stringsAsFactors=FALSE,
40
- check.names=FALSE, na.strings=c("NA","","N/A"))
41
- pheno_ids <- as.character(pheno_raw[,1])
42
- pheno_df <- pheno_raw[,-1,drop=FALSE]
43
- pheno_df <- as.data.frame(lapply(pheno_df, function(x) suppressWarnings(as.numeric(x))))
44
- rownames(pheno_df) <- pheno_ids
45
-
46
- # Match individuals
47
- common_ids <- intersect(ind_ids, pheno_ids)
48
- if (length(common_ids)==0) stop("No matching individual IDs.")
49
- geno_mat <- geno_mat[common_ids,]
50
- pheno_df <- pheno_df[common_ids,]
51
-
52
- # Build map list
53
- unique_chrs <- unique(chromosomes)
54
- chr_num <- suppressWarnings(as.integer(unique_chrs))
55
- ord <- order(ifelse(!is.na(chr_num), chr_num, 999), unique_chrs)
56
- unique_chrs <- unique_chrs[ord]
57
- map_list <- lapply(unique_chrs, function(ch) {
58
- idx <- which(chromosomes==ch)
59
- pos <- positions[idx]
60
- mnames <- marker_names[idx]
61
- ord2 <- order(pos)
62
- mnames <- mnames[ord2]
63
- mpos <- pos[ord2]
64
- names(mpos) <- mnames
65
- mpos
66
- })
67
- names(map_list) <- unique_chrs
68
-
69
- # Build geno list
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
- g_chr[g_chr==0] <- NA
78
- storage.mode(g_chr) <- "integer"
79
- list(data=g_chr, map=map_list[[ch]])
80
- })
81
- names(geno_list) <- unique_chrs
82
- for (ch in unique_chrs) class(geno_list[[ch]]$map) <- "A"
83
-
84
- cross_obj <- list(geno=geno_list, pheno=pheno_df)
85
- class(cross_obj) <- c(cross_type, "cross")
86
- cross_obj <- jittermap(cross_obj)
87
- if (cross_type=="f2") {
88
- cross_obj <- tryCatch(
89
- convert2bcsft(cross_obj, BC.gen=0, F.gen=2, estimate.map=FALSE),
90
- error=function(e) cross_obj
91
- )
92
- }
93
- cross_obj
94
- }
95
 
96
- parse_custom_cross_base <- function(geno_path, pheno_path, cross_type="bc") {
97
- # Same as above but without convert2bcsft
98
- geno_raw <- read.csv(geno_path, header=FALSE, stringsAsFactors=FALSE,
99
- check.names=FALSE, na.strings=c("NA","","N/A"))
100
- col_names <- as.character(geno_raw[1,])
101
- chr_row <- as.character(geno_raw[2,])
102
- pos_row <- as.character(geno_raw[3,])
103
- ind_data <- geno_raw[4:nrow(geno_raw),,drop=FALSE]
104
- n_cols <- ncol(geno_raw)
105
- marker_cols <- 2:n_cols
106
- marker_names <- col_names[marker_cols]
107
- chromosomes <- chr_row[marker_cols]
108
- positions <- suppressWarnings(as.numeric(pos_row[marker_cols]))
109
-
110
- # Clean chromosome labels
111
- chromosomes <- gsub("^[Cc]hr0*", "", chromosomes)
112
- chr_numeric <- suppressWarnings(as.integer(chromosomes))
113
- chromosomes <- ifelse(!is.na(chr_numeric), as.character(chr_numeric), chromosomes)
114
-
115
- ind_ids <- as.character(ind_data[,1])
116
- geno_mat <- as.matrix(ind_data[,marker_cols])
117
- class(geno_mat) <- "numeric"
118
- geno_mat <- apply(geno_mat, 2, function(x) suppressWarnings(as.numeric(x)))
119
- rownames(geno_mat) <- ind_ids
120
- colnames(geno_mat) <- marker_names
121
-
122
- # Read phenotype
123
- pheno_raw <- read.csv(pheno_path, header=TRUE, stringsAsFactors=FALSE,
124
- check.names=FALSE, na.strings=c("NA","","N/A"))
125
- pheno_ids <- as.character(pheno_raw[,1])
126
- pheno_df <- pheno_raw[,-1,drop=FALSE]
127
- pheno_df <- as.data.frame(lapply(pheno_df, function(x) suppressWarnings(as.numeric(x))))
128
- rownames(pheno_df) <- pheno_ids
129
-
130
- # Match individuals
131
- common_ids <- intersect(ind_ids, pheno_ids)
132
- if (length(common_ids)==0) stop("No matching individual IDs.")
133
- geno_mat <- geno_mat[common_ids,]
134
- pheno_df <- pheno_df[common_ids,]
135
-
136
- # Map list
137
- unique_chrs <- unique(chromosomes)
138
- chr_num <- suppressWarnings(as.integer(unique_chrs))
139
- ord <- order(ifelse(!is.na(chr_num), chr_num, 999), unique_chrs)
140
- unique_chrs <- unique_chrs[ord]
141
- map_list <- lapply(unique_chrs, function(ch) {
142
- idx <- which(chromosomes==ch)
143
- pos <- positions[idx]
144
- mnames <- marker_names[idx]
145
- ord2 <- order(pos)
146
- mnames <- mnames[ord2]
147
- mpos <- pos[ord2]
148
- names(mpos) <- mnames
149
- mpos
150
- })
151
- names(map_list) <- unique_chrs
152
-
153
- # Build geno list without convert2bcsft
154
- geno_list <- lapply(unique_chrs, function(ch) {
155
- idx <- which(chromosomes==ch)
156
- mnames <- marker_names[idx]
157
- pos_ch <- positions[idx]
158
- ord2 <- order(pos_ch)
159
- mnames <- mnames[ord2]
160
- g_chr <- geno_mat[, mnames, drop=FALSE]
161
- g_chr[g_chr==0] <- NA
162
- storage.mode(g_chr) <- "integer"
163
- list(data=g_chr, map=map_list[[ch]])
164
- })
165
- names(geno_list) <- unique_chrs
166
- for (ch in unique_chrs) class(geno_list[[ch]]$map) <- "A"
167
 
168
- cross_obj <- list(geno=geno_list, pheno=pheno_df)
169
- class(cross_obj) <- c(cross_type, "cross")
170
- cross_obj <- jittermap(cross_obj)
171
- cross_obj
 
 
172
  }
173
 
174
- # --- UI ---
175
-
176
  ui <- fluidPage(
177
  useShinyjs(),
178
- tags$head(HTML('/* your CSS styles here, omitted for brevity, include original styles */')),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
179
  div(class = "qtl-header",
180
  div(class = "logo-mark", "QTL"),
181
- div(tags$h1("QTL Mapper Pro"),
182
- div(class = "subtitle", "Quantitative Trait Loci Analysis Pipeline")),
183
- div(class = "header-badges",
184
- div(class = "badge-pill blue", "R/QTL ENGINE"),
185
- div(class = "badge-pill green", "10+ MODELS"),
186
- div(class = "badge-pill orange","MULTI-TRAIT"))
187
  ),
188
- div(class = "qtl-layout",
 
189
  # Sidebar
190
- div(class = "qtl-sidebar",
191
- div(class = "section-label", "Data Input"),
192
- div(class = "required-notice",
193
- "⚠ Upload both CSV files.", tags$br(),
194
- "Genotype: header + chr row + pos row + data rows.", tags$br(),
195
- "Phenotype: header + data rows."
196
- ),
197
- div(class = "qtl-upload",
198
- tags$label("Genotype CSV"),
199
- fileInput("geno_file", NULL, accept = ".csv", buttonLabel = "Browse", placeholder = "genotypes.csv"),
200
- div(class = "format-help",
201
- "Row 1: id | marker1 | marker2...", tags$br(),
202
- "Row 2: (blank) | chr1 | chr1...", tags$br(),
203
- "Row 3: (blank) | 0.22 | 0.60...", tags$br(),
204
- "Row 4+: sampleID | 1|2|3..."
205
- )
206
- ),
207
- div(class = "qtl-upload",
208
- tags$label("Phenotype CSV"),
209
- fileInput("pheno_file", NULL, accept = ".csv", buttonLabel = "Browse", placeholder = "phenotypes.csv"),
210
- div(class = "format-help",
211
- "Row 1: id | trait1 | trait2...", tags$br(),
212
- "Row 2+: sampleID | values..."
213
- )
214
- ),
215
- uiOutput("parse_preview_ui"),
216
- div(class = "section-label", "Cross Type"),
217
- div(class = "control-block",
218
- selectInput("cross_type", NULL,
219
- choices = c("Backcross" = "bc", "F2 Intercross" = "f2",
220
- "RIL (selfing)" = "riself", "RIL (sib-mating)" = "risib"),
221
- selected = "f2")
222
- ),
223
- div(class = "section-label", "Phenotype"),
224
- div(class = "control-block",
225
- selectInput("pheno_col", NULL, choices = NULL)
226
- ),
227
- div(class = "section-label", "Scan Models"),
228
- checkboxGroupInput("models", NULL,
229
- choices = c(
230
- "EM Algorithm (em)" = "em",
231
- "Haley-Knott (hk)" = "hk",
232
- "Extended HK (ehk)" = "ehk",
233
- "Multiple Imputation (imp)" = "imp",
234
- "Composite Interval (cim)" = "cim",
235
- "Non-Parametric (np)" = "np",
236
- "Marker Regression (mr)" = "mr"
237
- ),
238
- selected = c("hk","em","imp","np","mr")
239
- ),
240
- div(class = "section-label", "Permutation"),
241
- div(class = "control-block",
242
- tags$label("Permutations (0 = skip)"),
243
- numericInput("n_perm", NULL, value=100, min=0, max=1000, step=50)
244
- ),
245
- div(class = "control-block",
246
- tags$label("α threshold"),
247
- numericInput("alpha_thresh", NULL, value=0.05, min=0.01, max=0.1, step=0.01)
248
- ),
249
- div(class = "control-block",
250
- tags$label("Fixed LOD threshold"),
251
- numericInput("lod_thresh", NULL, value=3.0, min=1, max=10, step=0.5)
252
- ),
253
- div(class = "section-label", "Genome Scan"),
254
- div(class = "control-block",
255
- tags$label("Step (cM)"),
256
- numericInput("step_size", NULL, value=1, min=0.5, max=5, step=0.5)
257
- ),
258
- div(class = "control-block",
259
- tags$label("Error probability"),
260
- numericInput("error_prob", NULL, value=0.001, min=0.0001, max=0.01, step=0.001)
261
- ),
262
- actionButton("run_analysis", "▶ RUN ANALYSIS", class = "btn-run"),
263
- downloadButton("download_results", "⬇ EXPORT CSV", class = "btn-export"),
264
  div(class = "status-row",
265
- div(id="status_dot", class="status-dot"),
266
- textOutput("status_text", inline=TRUE)
267
  )
268
  ),
269
- # Main content
270
- div(class = "qtl-main",
271
- # Tabs ...
272
- # (unchanged, omitted for brevity, include your full tab structure here)
 
 
 
 
 
 
 
 
 
 
273
  )
274
- ),
275
- tags$script(HTML('/* tab switching script */'))
276
  )
277
 
278
- # --- Server ---
279
  server <- function(input, output, session) {
280
 
281
- theme_qtl <- function(base_size=11) {
282
- theme_minimal(base_size=base_size) + theme(
283
- plot.background=element_rect(fill="#ffffff", color=NA),
284
- panel.background=element_rect(fill="#f8f9fb", color=NA),
285
- panel.grid.major=element_line(color="#e8ecf2", linewidth=0.45),
286
- panel.grid.minor=element_line(color="#f1f4f8", linewidth=0.25),
287
- panel.border=element_rect(color="#dde2ea", fill=NA, linewidth=0.8),
288
- axis.text=element_text(color="#8a95a3", size=9, family="mono"),
289
- axis.title=element_text(color="#4a5568", size=10),
290
- plot.title=element_text(color="#1a202c", size=12, face="bold", family="mono"),
291
- plot.subtitle=element_text(color="#8a95a3", size=9),
292
- legend.background=element_rect(fill="#ffffff", color="#dde2ea", linewidth=0.5),
293
- legend.text=element_text(color="#4a5568", size=9),
294
- legend.title=element_text(color="#8a95a3", size=9),
295
- strip.background=element_rect(fill="#f1f4f8", color="#dde2ea"),
296
- strip.text=element_text(color="#1a6cf5", size=9, family="mono", face="bold"),
297
- plot.margin=margin(12,16,12,16)
298
- )
299
- }
300
 
301
- # --- Parsing uploaded data ---
302
- cross_obj <- reactive({
303
  req(input$geno_file, input$pheno_file)
304
- tryCatch(
305
- parse_custom_cross(input$geno_file$datapath, input$pheno_file$datapath, input$cross_type),
306
- error=function(e) {
307
- showNotification(paste("Error parsing data:", e$message), type="error")
308
- NULL
309
- }
310
- )
311
  })
312
 
313
- # Update phenotype choices
314
- observeEvent(cross_obj(), {
315
- cross <- cross_obj()
316
- if (!is.null(cross)) {
317
- updateSelectInput(session, "pheno_col", choices=names(cross$pheno), selected=names(cross$pheno)[1])
318
- output$status_text <- renderText(paste0(totmar(cross), " markers · ", nind(cross), " inds · ", nchr(cross), " chrs — Ready"))
319
- }
320
  })
321
 
322
- # Parse and run analysis
323
- analysis_res <- reactiveVal(NULL)
324
-
325
- observeEvent(input$run_analysis, {
326
- cross <- cross_obj()
327
  req(cross)
328
- output$status_text <- renderText("Running analysis...")
329
- runjs("document.getElementById('status_dot').classList.remove('active')")
330
-
331
- withProgress(message="QTL Mapping in progress...", value=0, {
332
- # calc.genoprob
333
- cross <- tryCatch(
334
- calc.genoprob(cross, step=input$step_size, error.prob=input$error_prob),
335
- error=function(e) {showNotification(paste("calc.genoprob error:", e$message), type="error"); NULL}
336
- )
337
- req(cross); incProgress(0.2)
338
 
339
- # sim.geno
340
- cross <- tryCatch(
341
- sim.geno(cross, n.draws=64, step=input$step_size, error.prob=input$error_prob),
342
- error=function(e) cross
343
- )
344
- incProgress(0.2)
345
 
346
- # scanone
347
  pheno_idx <- which(names(cross$pheno) == input$pheno_col)
348
- if (length(pheno_idx)==0) pheno_idx <- 1
349
 
350
- models <- input$models
351
- if (length(models)==0) models <- "hk"
352
 
353
  scan_results <- list()
354
  perm_results <- list()
355
 
356
- for (mdl in models) {
357
- incProgress(0.4/length(models), detail=paste("Scanning:", mdl))
358
- sc <- tryCatch(
359
- scanone(cross, pheno.col=pheno_idx, method=mdl),
360
- error=function(e) {showNotification(paste("scanone failed for", mdl, e$message), type="error"); NULL}
361
- )
362
- if (!is.null(sc)) {
363
- scan_results[[mdl]] <- sc
364
- if (input$n_perm > 0) {
365
- perm_results[[mdl]] <- tryCatch(
366
- scanone(cross, pheno.col=pheno_idx, method=mdl, n.perm=input$n_perm, verbose=FALSE),
367
- error=function(e) NULL
368
- )
369
- }
370
  }
371
  }
372
- incProgress(0.2)
373
 
374
- # Determine threshold
375
- lod_thresh <- input$lod_thresh
376
  if (length(perm_results) > 0 && !is.null(perm_results[[1]])) {
377
- thr <- tryCatch(summary(perm_results[[1]], alpha=input$alpha_thresh)[[1]], error=function(e) NULL)
378
- if (!is.null(thr) && is.numeric(thr)) lod_thresh <- thr
379
  }
380
 
381
- # Build QTL table
382
- qtl_table <- build_qtl_table(cross, scan_results, lod_thresh, pheno_idx)
383
-
384
- # Save
385
- analysis_res(list(
386
- cross=cross,
387
- scan_results=scan_results,
388
- perm_results=perm_results,
389
- lod_thr=lod_thresh,
390
- qtl_table=qtl_table,
391
- pheno_idx=pheno_idx
392
- ))
393
 
394
- incProgress(0.1, detail="Finished")
 
395
  })
396
-
397
- # Update dropdowns
398
- res <- analysis_res()
399
- if (!is.null(res)){
400
- updateSelectInput(session, "manhattan_model", choices=names(res$scan_results), selected=names(res$scan_results)[1])
401
- updateSelectInput(session, "chr_plot_model", choices=names(res$scan_results), selected=names(res$scan_results)[1])
402
- qtl_choices <- if(nrow(res$qtl_table)>0) paste0(res$qtl_table$Chr, "@", res$qtl_table$Peak_Marker) else "none"
403
- updateSelectInput(session, "effect_qtl", choices=qtl_choices)
404
- }
405
-
406
- runjs("document.getElementById('status_dot').classList.add('active')")
407
- output$status_text <- renderText(paste0("Analysis complete"))
408
  })
409
 
410
- # Helper to build QTL table
411
- build_qtl_table <- function(cross, scan_results, lod_thresh, pheno_idx) {
412
  rows <- list()
413
  for (mdl in names(scan_results)) {
414
  sc <- scan_results[[mdl]]
415
- sigs <- sc[sc$lod >= lod_thresh,]
416
- if (nrow(sigs)==0) next
417
- for (ch in unique(sc$chr)){
418
- chr_sc <- sc[sc$chr==ch,]
419
- peak_row <- chr_sc[which.max(chr_sc$lod),]
420
- peak_pos <- peak_row$pos
421
- peak_lod <- peak_row$lod
422
- peak_marker <- rownames(peak_row)
423
- # CI
424
- ci <- tryCatch(lodint(sc, chr=ch, drop=1.5), error=function(e) NULL)
425
- left_marker <- if(!is.null(ci)) rownames(ci)[1] else NA
426
- right_marker <- if(!is.null(ci)) rownames(ci)[nrow(ci)] else NA
427
- left_pos <- if(!is.null(ci)) ci$pos[1] else NA
428
- right_pos <- if(!is.null(ci)) ci$pos[nrow(ci)] else NA
429
- n_ind <- nind(cross)
430
- pve <- round((1 - 10^(-2*peak_lod/n_ind))*100, 2)
431
- rows[[length(rows)+1]] <- data.frame(
432
- Model=mdl, Chr=ch, Peak_Marker=peak_marker, Peak_pos_cM=round(peak_pos,2),
433
- LOD=round(peak_lod,3), PVE_pct=pve,
434
- Left_Marker=left_marker, Left_pos_cM=round(left_pos,2),
435
- Right_Marker=right_marker, Right_pos_cM=round(right_pos,2),
436
- CI_width_cM=round(right_pos-left_pos,2),
437
- stringsAsFactors=FALSE
438
  )
439
  }
440
  }
441
- if (length(rows)==0) return(data.frame())
442
- bind_rows(rows) %>% arrange(Chr, Peak_pos_cM)
443
  }
444
 
445
- # --- Plots ---
446
- output$plot_genome_map <- renderPlot({
447
- cross <- cross_obj()
448
  req(cross)
449
- map <- pull.map(cross)
450
- df <- do.call(rbind, lapply(names(map), function(ch) {
451
- data.frame(chr=ch, pos=unname(map[[ch]]))
452
- }))
453
- df$chr <- factor(df$chr, levels=names(map))
454
- ggplot(df, aes(x=chr,y=pos)) +
455
- geom_segment(aes(xend=chr,yend=pos), color="#dde2ea", linewidth=8) +
456
- geom_point(color="#1a6cf5", size=1.5, alpha=0.8) +
457
- scale_y_reverse() +
458
- labs(title="Genetic Map", x="Chromosome", y="Position (cM)") + theme_qtl()
459
  })
460
 
461
- output$plot_pheno_dist <- renderPlot({
462
- cross <- cross_obj()
463
- req(cross, input$pheno_col)
464
- ph <- cross$pheno[[input$pheno_col]]
465
- df <- data.frame(value=ph[!is.na(ph)])
466
- p1 <- ggplot(df, aes(value)) +
467
- geom_histogram(fill="#1a6cf5", color="#ffffff", bins=30, alpha=0.8) +
468
- labs(title=input$pheno_col, x="Value", y="Count") + theme_qtl()
469
- p2 <- ggplot(df, aes(sample=value)) +
470
- stat_qq(color="#18a058", size=1.5, alpha=0.8) +
471
- stat_qq_line(color="#c2185b", linewidth=0.8) +
472
- labs(title="Q-Q Plot", x="Theoretical", y="Sample") + theme_qtl()
473
- gridExtra::grid.arrange(p1, p2, ncol=2)
474
  })
475
 
476
- output$plot_physical_map <- renderPlot({
477
- cross <- cross_obj()
478
- req(cross)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
479
  map <- pull.map(cross)
480
- df <- do.call(rbind, lapply(names(map), function(ch) {
481
- data.frame(chr=ch, pos=unname(map[[ch]]))
482
- }))
483
- chr_len <- df %>% group_by(chr) %>% summarise(len=max(pos))
484
- df$chr <- factor(df$chr, levels=names(map))
485
- ggplot() +
486
- geom_rect(data=chr_len,
487
- aes(xmin=as.numeric(chr)-0.35, xmax=as.numeric(chr)+0.35, ymin=0, ymax=len),
488
- fill="#e8ecf2", color="#c8d0dc", linewidth=0.7) +
489
- geom_point(data=df, aes(x=as.numeric(chr), y=pos), color="#1a6cf5", size=1, alpha=0.7) +
490
- scale_x_continuous(breaks=seq_along(names(map)), labels=names(map)) +
491
- scale_y_reverse() +
492
- labs(title="Physical Map Overview", x="Chromosome", y="cM") + theme_qtl()
 
 
 
 
493
  })
494
 
495
  output$plot_manhattan <- renderPlot({
496
- res <- analysis_res()
497
- req(res)
498
- mdl <- input$manhattan_model
499
- sc <- res$scan_results[[mdl]]
500
- req(sc)
501
- chrs <- unique(sc$chr)
502
- chr_offsets <- cumsum(c(0, sapply(chrs[-length(chrs)], function(ch) max(sc$pos[sc$chr==ch]))))
503
- sc$global_pos <- sc$pos + chr_offsets[as.character(sc$chr)]
504
- sc$chr_num <- as.integer(factor(sc$chr, levels=chrs))
505
- sc$color <- ifelse(sc$chr_num %% 2 == 0, "#1a6cf5", "#5b9cf5")
506
- sig <- sc[sc$lod >= res$lod_thr,]
507
- chr_mid <- tapply(sc$global_pos, sc$chr, mean)
508
- ggplot(sc, aes(x=global_pos,y=lod)) +
509
- geom_point(aes(color=color), size=1.2, alpha=0.75) +
510
- scale_color_identity() +
511
- geom_point(data=sig, aes(x=global_pos,y=lod), color="#c2185b", size=2.5, shape=18) +
512
- geom_hline(yintercept=res$lod_thr, color="#e8500a", linetype="dashed") +
513
- scale_x_continuous(breaks=chr_mid, labels=names(chr_mid)) +
514
- theme_qtl() + labs(title=paste("Manhattan -", mdl))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
515
  })
516
 
517
- output$plot_manhattan_interactive <- renderPlotly({
518
- res <- analysis_res()
519
- req(res)
520
- mdl <- input$manhattan_model
521
- sc <- res$scan_results[[mdl]]
522
- req(sc)
523
  chrs <- unique(sc$chr)
524
- chr_offsets <- cumsum(c(0, sapply(chrs[-length(chrs)], function(ch) max(sc$pos[sc$chr==ch]))))
525
- sc$global_pos <- sc$pos + chr_offsets[as.character(sc$chr)]
526
- sc$sig <- sc$lod >= res$lod_thr
527
- sc$label <- paste0(rownames(sc), "<br>Chr:", sc$chr, " Pos:", round(sc$pos,1), " LOD:", round(sc$lod,2))
528
- plot_ly(sc, x=~global_pos, y=~lod, color=~sig,
529
- colors=c("#1a6cf5","#c2185b"),
530
- text=~label, hoverinfo="text",
531
- type="scatter", mode="markers", marker=list(size=4, opacity=0.8)) %>%
532
- add_lines(y=~res$lod_thr, line=list(color="#e8500a", dash="dash", width=1.5),
533
- showlegend=FALSE, name="Threshold") %>%
534
- layout(paper_bgcolor="#ffffff", plot_bgcolor="#f8f9fb",
535
- font=list(color="#4a5568", family="monospace"),
536
- xaxis=list(title="Position", gridcolor="#e8ecf2"),
537
- yaxis=list(title="LOD Score", gridcolor="#e8ecf2"),
538
- margin=list(t=10,b=40,l=50,r=20))
 
 
 
 
 
539
  })
540
 
541
- # Other plots (e.g., genome scan, model comparison, effects, etc.) follow similar pattern
542
- # For brevity, you can implement them similarly, making sure to use reactive data and req()
543
-
544
- # --- Tables ---
545
- output$table_qtl_results <- renderDT({
546
- res <- analysis_res()
547
- req(res)
548
- qt <- res$qtl_table
549
- req(nrow(qt)>0)
550
- datatable(qt, rownames=FALSE,
551
- options=list(pageLength=20, scrollX=TRUE, dom="Blfrtip"),
552
- class="display nowrap") %>%
553
- formatStyle("LOD", background=styleColorBar(range(qt$LOD), "#bcd0fc")) %>%
554
- formatStyle("PVE_pct", background=styleColorBar(c(0,100), "#b3dfc7")) %>%
555
- formatRound(c("Peak_pos_cM","LOD","PVE_pct","Left_pos_cM","Right_pos_cM","CI_width_cM"), 3)
556
  })
557
 
558
- output$table_model_summary <- renderDT({
559
- res <- analysis_res()
560
- req(res)
561
- df <- data.frame(
562
- Model=names(res$scan_results),
563
- Max_LOD=round(sapply(res$scan_results, function(sc) max(sc$lod, na.rm=TRUE)),3),
564
- Mean_LOD=round(sapply(res$scan_results, function(sc) mean(sc$lod, na.rm=TRUE)),3),
565
- QTLs_Found=sapply(names(res$scan_results), function(m)
566
- if (!is.null(res$qtl_table) && nrow(res$qtl_table)>0) sum(res$qtl_table$Model==m) else 0),
567
- Threshold=round(res$lod_thr,3)
568
  )
569
- datatable(df, rownames=FALSE, options=list(dom="t", pageLength=15), class="display") %>%
570
- formatStyle("Max_LOD", color="#1a6cf5", fontWeight="bold") %>%
571
- formatStyle("QTLs_Found", color="#c2185b", fontWeight="bold")
572
  })
573
 
574
- output$table_perm_thresholds <- renderDT({
575
- res <- analysis_res()
576
- req(res)
577
- rows <- list()
578
- for (m in names(res$perm_results)) {
579
- p <- res$perm_results[[m]]
580
- if (is.null(p)) next
581
- sm <- tryCatch(summary(p, alpha=c(0.05,0.1,0.2)), error=function(e) NULL)
582
- if (is.null(sm)) next
583
- rows[[length(rows)+1]] <- data.frame(
584
- Model=m,
585
- alpha_0.05=round(sm[1],3),
586
- alpha_0.10=round(sm[2],3),
587
- alpha_0.20=round(sm[3],3)
588
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
589
  }
590
- df <- bind_rows(rows)
591
- req(nrow(df)>0)
592
- datatable(df, rownames=FALSE, options=list(dom="t"))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
593
  })
594
 
595
  # Download
596
  output$download_results <- downloadHandler(
597
- filename=function() paste0("qtl_results_", Sys.Date(), ".csv"),
598
- content=function(file) {
599
- res <- analysis_res()
600
- if (!is.null(res) && nrow(res$qtl_table)>0) {
601
- write.csv(res$qtl_table, file, row.names=FALSE)
602
  } else {
603
- write.csv(data.frame(Message="No significant QTLs"), file, row.names=FALSE)
604
  }
605
  }
606
  )
607
-
608
  }
609
 
610
- # Run app
611
- shinyApp(ui=ui, server=server)
 
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)