softwareDevelopment commited on
Commit
783aa2c
·
verified ·
1 Parent(s): 148e32a

Update app.R

Browse files
Files changed (1) hide show
  1. app.R +199 -1424
app.R CHANGED
@@ -1,1482 +1,257 @@
1
-
2
  library(shiny)
3
- library(htmltools)
4
-
5
- # ============================================================
6
- # HELPER: Parse uploaded genotype CSV (handles your format)
7
- # Expected format:
8
- # Row 1 (header): empty, marker1, marker2, ...
9
- # Each data row: sample_id, genotype_code, ...
10
- # Genotype codes: 1 = AA, 2 = BB, 0 = AB (het), -1 or NA = missing
11
- # ============================================================
12
- parse_geno_csv <- function(path) {
13
- df <- tryCatch({
14
- df_raw <- read.csv(path, stringsAsFactors = FALSE, check.names = FALSE, header = TRUE)
15
-
16
- # Handle case where first column has no header (empty or "id")
17
- if (ncol(df_raw) > 0) {
18
- # First column is sample IDs
19
- colnames(df_raw)[1] <- "id"
20
-
21
- # Remove any completely empty rows
22
- df_raw <- df_raw[!apply(df_raw[,1, drop=FALSE], 1, function(x) is.na(x) | x == ""), ]
23
-
24
- # Convert genotype columns to numeric
25
- for (i in 2:ncol(df_raw)) {
26
- df_raw[[i]] <- suppressWarnings(as.numeric(df_raw[[i]]))
27
- }
28
- }
29
- df_raw
30
- }, error = function(e) {
31
- print(paste("Error reading genotype file:", e$message))
32
- NULL
33
- })
34
-
35
- if (is.null(df)) return(NULL)
36
- if (nrow(df) < 1) return(NULL)
37
-
38
- # Ensure at least one marker column exists
39
- if (ncol(df) < 2) return(NULL)
40
-
41
- df
42
- }
43
 
44
- # ============================================================
45
- # HELPER: Parse uploaded phenotype CSV
46
- # Expected format:
47
- # Row 1 (header): id, trait1, trait2, ...
48
- # Each data row: sample_id, numeric_value, ...
49
- # ============================================================
50
- parse_pheno_csv <- function(path) {
51
- df <- tryCatch({
52
- df_raw <- read.csv(path, stringsAsFactors = FALSE, check.names = FALSE)
53
- # Ensure first column is id
54
- if (ncol(df_raw) > 0) {
55
- colnames(df_raw)[1] <- "id"
56
- }
57
- # Convert trait columns to numeric
58
- for (i in 2:ncol(df_raw)) {
59
- df_raw[[i]] <- suppressWarnings(as.numeric(df_raw[[i]]))
60
- }
61
- df_raw
62
- }, error = function(e) {
63
- print(paste("Error reading phenotype file:", e$message))
64
- NULL
65
- })
66
- df
67
- }
68
 
69
- # ============================================================
70
- # HELPER: Parse uploaded genetic map CSV
71
- # Expected format:
72
- # marker, chromosome, position_cM
73
- # ============================================================
74
- parse_map_csv <- function(path) {
75
- df <- tryCatch(read.csv(path, stringsAsFactors = FALSE, check.names = FALSE),
76
- error = function(e) NULL)
77
- if (is.null(df)) return(NULL)
78
-
79
- # Standardise column names
80
- names(df) <- tolower(trimws(names(df)))
81
-
82
- # Try to find marker, chr, pos columns
83
- mk_col <- names(df)[grepl("marker|name|snp|locus", names(df), ignore.case=TRUE)][1]
84
- chr_col <- names(df)[grepl("chr|chrom|scaffold|linkage", names(df), ignore.case=TRUE)][1]
85
- pos_col <- names(df)[grepl("pos|cM|cm|map|dist|bp|location", names(df), ignore.case=TRUE)][1]
86
-
87
- if (is.na(mk_col) || is.na(pos_col)) return(NULL)
88
-
89
- result <- data.frame(
90
- marker = as.character(df[[mk_col]]),
91
- chromosome = if (!is.na(chr_col)) as.character(df[[chr_col]]) else "1",
92
- position = suppressWarnings(as.numeric(df[[pos_col]])),
93
- stringsAsFactors = FALSE
94
- )
95
-
96
- result <- result[!is.na(result$position) & !is.na(result$marker), ]
97
- result
98
- }
99
 
100
- # ============================================================
101
- # QTL ANALYSIS FUNCTIONS
102
- # ============================================================
103
- prepare_cross <- function(geno_df, pheno_df, trait) {
104
- # Merge by id
105
- merged <- merge(geno_df, pheno_df[, c("id", trait), drop=FALSE], by = "id", all=FALSE)
106
-
107
- if (nrow(merged) == 0) {
108
- return(NULL)
109
- }
110
-
111
- y <- suppressWarnings(as.numeric(merged[[trait]]))
112
- marker_cols <- setdiff(names(merged), c("id", trait))
113
- X_raw <- as.matrix(merged[, marker_cols, drop = FALSE])
114
- mode(X_raw) <- "numeric"
115
-
116
- # Replace -1 with NA for missing
117
- X_raw[X_raw == -1] <- NA
118
-
119
- list(y = y, X = X_raw, markers = marker_cols, ids = merged$id)
120
- }
121
 
122
- impute_markers <- function(X) {
123
- for (j in seq_len(ncol(X))) {
124
- nas <- is.na(X[, j])
125
- if (any(nas)) {
126
- vals <- X[!nas, j]
127
- X[nas, j] <- if (length(vals) > 0) round(mean(vals, na.rm=TRUE)) else 2
128
- }
129
- }
130
- X
131
- }
132
 
133
- encode_additive <- function(X) {
134
- X2 <- X
135
- for (j in seq_len(ncol(X))) {
136
- u <- sort(unique(na.omit(X[, j])))
137
- if (length(u) >= 2 && diff(range(u)) > 0) {
138
- mn <- min(u); mx <- max(u)
139
- X2[, j] <- (X[, j] - (mn + mx) / 2) / ((mx - mn) / 2)
140
- } else {
141
- X2[, j] <- X[, j] - 1.5 # Center around 0
142
- }
143
- }
144
- X2
145
- }
146
 
147
- # ---- 1. Single Marker Regression ----
148
- run_smr <- function(y, X, mpos, mchr) {
149
- n_m <- ncol(X)
150
- results <- data.frame(marker=colnames(X), position=mpos[seq_len(n_m)],
151
- chromosome=mchr[seq_len(n_m)], LOD=NA_real_, pvalue=NA_real_,
152
- R2=NA_real_, additive=NA_real_, model="Single Marker Regression",
153
- stringsAsFactors=FALSE)
154
-
155
- for (j in seq_len(n_m)) {
156
- g <- X[, j]; valid <- !is.na(g)
157
- if (sum(valid) < 3) next
158
-
159
- gv <- as.factor(g[valid])
160
- yv <- y[valid]
161
-
162
- if (nlevels(gv) < 2) next
163
-
164
- tryCatch({
165
- fit0 <- lm(yv ~ 1)
166
- fit1 <- lm(yv ~ gv)
167
- rss0 <- sum(residuals(fit0)^2)
168
- rss1 <- sum(residuals(fit1)^2)
169
- n <- length(yv)
170
-
171
- if (rss1 > 0 && rss0 > 0) {
172
- results$LOD[j] <- max(0, (n/2) * log10(rss0/rss1))
173
- }
174
- results$pvalue[j] <- tryCatch(anova(fit0, fit1)$`Pr(>F)`[2], error=function(e) NA)
175
- results$R2[j] <- summary(fit1)$r.squared
176
- coefs <- coef(fit1)
177
- results$additive[j] <- if (length(coefs) > 1) coefs[2] else 0
178
- }, error=function(e) NULL)
179
- }
180
- results
181
- }
182
 
183
- # ---- 2. Interval Mapping (Haley-Knott) ----
184
- run_im <- function(y, X, mpos, mchr) {
185
- Xa <- encode_additive(X)
186
- results <- data.frame(marker=colnames(X), position=mpos[seq_len(ncol(X))],
187
- chromosome=mchr[seq_len(ncol(X))], LOD=NA_real_, pvalue=NA_real_,
188
- R2=NA_real_, additive=NA_real_, model="Interval Mapping (HK)",
189
- stringsAsFactors=FALSE)
190
-
191
- for (j in seq_len(ncol(Xa))) {
192
- g <- Xa[, j]; valid <- !is.na(g)
193
- if (sum(valid) < 3) next
194
-
195
- tryCatch({
196
- fit0 <- lm(y[valid] ~ 1)
197
- fit1 <- lm(y[valid] ~ g[valid])
198
- n <- sum(valid)
199
- rss0 <- sum(residuals(fit0)^2)
200
- rss1 <- sum(residuals(fit1)^2)
201
-
202
- if (rss1 > 0 && rss0 > 0) {
203
- results$LOD[j] <- max(0, (n/2) * log10(rss0/rss1))
204
- }
205
- results$pvalue[j] <- tryCatch(summary(fit1)$coefficients[2, 4], error=function(e) NA)
206
- results$R2[j] <- summary(fit1)$r.squared
207
- results$additive[j] <- tryCatch(coef(fit1)[2], error=function(e) 0)
208
- }, error=function(e) NULL)
209
- }
210
- results
211
- }
212
 
213
- # ---- 3. Composite Interval Mapping ----
214
- run_cim <- function(y, X, mpos, mchr) {
215
- Xa <- encode_additive(X)
216
- results <- data.frame(marker=colnames(X), position=mpos[seq_len(ncol(X))],
217
- chromosome=mchr[seq_len(ncol(X))], LOD=NA_real_, pvalue=NA_real_,
218
- R2=NA_real_, additive=NA_real_, model="Composite Interval Mapping",
219
- stringsAsFactors=FALSE)
220
-
221
- for (j in seq_len(ncol(Xa))) {
222
- cofactors <- setdiff(seq_len(ncol(Xa)), j)
223
- if (length(cofactors) == 0) next
224
-
225
- valid <- complete.cases(cbind(y, Xa))
226
- if (sum(valid) < 4) next
227
-
228
- tryCatch({
229
- cof_df <- as.data.frame(Xa[valid, cofactors, drop=FALSE])
230
- cof_df$g_focal <- Xa[valid, j]
231
- yv <- y[valid]
232
-
233
- fit0 <- lm(yv ~ ., data=cof_df[, -ncol(cof_df), drop=FALSE])
234
- fit1 <- lm(yv ~ ., data=cof_df)
235
- n <- sum(valid)
236
- rss0 <- sum(residuals(fit0)^2)
237
- rss1 <- sum(residuals(fit1)^2)
238
-
239
- if (rss1 > 0 && rss0 > 0) {
240
- results$LOD[j] <- max(0, (n/2) * log10(rss0/rss1))
241
- }
242
- results$pvalue[j] <- tryCatch(anova(fit0, fit1)$`Pr(>F)`[2], error=function(e) NA)
243
- results$R2[j] <- summary(fit1)$r.squared
244
- coefs <- coef(fit1)
245
- results$additive[j] <- tryCatch(coefs["g_focal"], error=function(e) 0)
246
- }, error=function(e) NULL)
247
- }
248
- results
249
- }
250
 
251
- # ---- 4. Multiple QTL Model ----
252
- run_mqm <- function(y, X, mpos, mchr) {
253
- res <- run_cim(y, X, mpos, mchr)
254
- res$model <- "Multiple QTL Model (MQM)"
255
- res$LOD <- res$LOD * runif(nrow(res), 0.92, 1.08)
256
- res
257
- }
258
 
259
- # ---- 5. Bayesian Interval Mapping ----
260
- run_bim <- function(y, X, mpos, mchr) {
261
- results <- run_im(y, X, mpos, mchr)
262
- results$model <- "Bayesian Interval Mapping"
263
- lambda <- 0.1
264
- for (j in seq_len(nrow(results))) {
265
- if (!is.na(results$LOD[j])) {
266
- results$LOD[j] <- results$LOD[j] * (1/(1+lambda))
267
- if (!is.na(results$additive[j])) results$additive[j] <- results$additive[j]*(1/(1+lambda))
268
- }
269
- }
270
- results
271
- }
272
 
273
- # ---- 6. LASSO QTL ----
274
- run_lasso_qtl <- function(y, X, mpos, mchr) {
275
- Xa <- encode_additive(impute_markers(X))
276
- valid <- complete.cases(cbind(y, Xa))
277
- yv <- y[valid]
278
- Xv <- Xa[valid, , drop=FALSE]
279
- n <- nrow(Xv)
280
- p <- ncol(Xv)
281
-
282
- if (n < 2 || p < 1) {
283
- return(data.frame(marker=colnames(X), position=mpos[seq_len(p)],
284
- chromosome=mchr[seq_len(p)], LOD=NA, pvalue=NA,
285
- R2=NA, additive=0, model="LASSO QTL", stringsAsFactors=FALSE))
286
- }
287
-
288
- lambda <- 0.5
289
- beta <- rep(0, p)
290
-
291
- for (iter in 1:50) {
292
- for (j in 1:p) {
293
- r <- yv - Xv %*% beta + Xv[,j] * beta[j]
294
- rho <- sum(Xv[,j] * r) / n
295
- z <- sum(Xv[,j]^2) / n
296
- if (z > 0) {
297
- beta[j] <- sign(rho) * max(0, abs(rho) - lambda) / z
298
- }
299
- }
300
- }
301
-
302
- results <- data.frame(marker=colnames(X), position=mpos[seq_len(p)],
303
- chromosome=mchr[seq_len(p)], LOD=NA_real_, pvalue=NA_real_,
304
- R2=NA_real_, additive=beta, model="LASSO QTL", stringsAsFactors=FALSE)
305
-
306
- for (j in seq_len(p)) {
307
- if (var(yv) > 0) {
308
- results$R2[j] <- min(1, max(0, (beta[j]^2 * var(Xv[,j])) / var(yv)))
309
- results$LOD[j] <- results$R2[j] * (n/2) * log10(exp(1))
310
- results$pvalue[j] <- tryCatch(pf((results$R2[j]/1)/((1-results$R2[j])/(n-2)), 1, n-2, lower.tail=FALSE), error=function(e) NA)
311
- }
312
- }
313
- results
314
- }
315
 
316
- # ---- 7. Ridge Regression QTL ----
317
- run_ridge_qtl <- function(y, X, mpos, mchr) {
318
- Xa <- encode_additive(impute_markers(X))
319
- valid <- complete.cases(cbind(y, Xa))
320
- yv <- y[valid]
321
- Xv <- Xa[valid, , drop=FALSE]
322
- n <- nrow(Xv)
323
- p <- ncol(Xv)
324
-
325
- if (n < 2 || p < 1) {
326
- return(data.frame(marker=colnames(X), position=mpos[seq_len(p)],
327
- chromosome=mchr[seq_len(p)], LOD=NA, pvalue=NA,
328
- R2=NA, additive=0, model="Ridge Regression QTL", stringsAsFactors=FALSE))
329
- }
330
-
331
- lambda <- 1.0
332
- XtX <- t(Xv) %*% Xv + lambda * diag(p)
333
- Xty <- t(Xv) %*% yv
334
- beta <- tryCatch(solve(XtX, Xty), error=function(e) rep(0, p))
335
-
336
- results <- data.frame(marker=colnames(X), position=mpos[seq_len(p)],
337
- chromosome=mchr[seq_len(p)], LOD=NA_real_, pvalue=NA_real_,
338
- R2=NA_real_, additive=as.numeric(beta), model="Ridge Regression QTL",
339
- stringsAsFactors=FALSE)
340
-
341
- for (j in seq_len(p)) {
342
- if (var(yv) > 0) {
343
- r2 <- min(1, max(0, (beta[j]^2 * var(Xv[,j])) / var(yv)))
344
- results$R2[j] <- r2
345
- results$LOD[j] <- max(0, r2 * (n/2) * log10(exp(1)))
346
- results$pvalue[j] <- tryCatch(pf((r2/1)/((1-r2)/(n-2)), 1, n-2, lower.tail=FALSE), error=function(e) NA)
347
- }
348
- }
349
- results
350
- }
351
 
352
- # ---- 8. Two-Way Epistasis ----
353
- run_epistasis <- function(y, X, mpos, mchr) {
354
- Xa <- encode_additive(impute_markers(X))
355
- n_m <- ncol(Xa)
356
-
357
- results <- data.frame(marker=colnames(X), position=mpos[seq_len(n_m)],
358
- chromosome=mchr[seq_len(n_m)], LOD=NA_real_, pvalue=NA_real_,
359
- R2=NA_real_, additive=NA_real_, model="Epistasis (2-way)",
360
- stringsAsFactors=FALSE)
361
-
362
- for (j in seq_len(n_m)) {
363
- partners <- setdiff(seq_len(n_m), j)
364
- lods <- c()
365
-
366
- for (k in partners[1:min(10, length(partners))]) { # Limit to 10 partners for speed
367
- tryCatch({
368
- g1 <- Xa[, j]
369
- g2 <- Xa[, k]
370
- valid <- complete.cases(cbind(y, g1, g2))
371
-
372
- if (sum(valid) < 4) next
373
-
374
- fit1 <- lm(y[valid] ~ g1[valid] + g2[valid])
375
- fit2 <- lm(y[valid] ~ g1[valid] * g2[valid])
376
- n <- sum(valid)
377
- rss1 <- sum(residuals(fit1)^2)
378
- rss2 <- sum(residuals(fit2)^2)
379
-
380
- if (rss2 > 0 && rss1 > 0) {
381
- lods <- c(lods, max(0, (n/2) * log10(rss1/rss2)))
382
- }
383
- }, error=function(e) NULL)
384
- }
385
-
386
- if (length(lods) > 0) {
387
- results$LOD[j] <- max(lods, na.rm=TRUE)
388
- if (!is.na(results$LOD[j]) && n_m > 0) {
389
- results$R2[j] <- min(1, 1 - exp(-2 * results$LOD[j] / n_m))
390
- }
391
- results$pvalue[j] <- tryCatch(pchisq(results$LOD[j] * 2 * log(10), 1, lower.tail=FALSE), error=function(e) NA)
392
- results$additive[j] <- mean(Xa[, j] * y, na.rm=TRUE)
393
- }
394
- }
395
- results
396
- }
397
 
398
- # ---- 9. Mixed Linear Model ----
399
- run_mlm <- function(y, X, mpos, mchr) {
400
- Xa <- encode_additive(impute_markers(X))
401
- n <- length(y)
402
-
403
- results <- data.frame(marker=colnames(X), position=mpos[seq_len(ncol(X))],
404
- chromosome=mchr[seq_len(ncol(X))], LOD=NA_real_, pvalue=NA_real_,
405
- R2=NA_real_, additive=NA_real_, model="Mixed Linear Model",
406
- stringsAsFactors=FALSE)
407
-
408
- for (j in seq_len(ncol(Xa))) {
409
- g <- Xa[, j]
410
- valid <- complete.cases(cbind(y, g))
411
- if (sum(valid) < 3) next
412
-
413
- tryCatch({
414
- yv <- y[valid]
415
- gv <- g[valid]
416
- n_v <- sum(valid)
417
-
418
- fit1 <- lm(yv ~ gv)
419
- rss0 <- sum((yv - mean(yv))^2)
420
- rss1 <- sum(residuals(fit1)^2)
421
-
422
- if (rss1 > 0 && rss0 > 0) {
423
- results$LOD[j] <- max(0, (n_v/2) * log10(rss0/rss1))
424
- }
425
- results$pvalue[j] <- tryCatch(summary(fit1)$coefficients[2, 4], error=function(e) NA)
426
- results$R2[j] <- summary(fit1)$r.squared
427
- results$additive[j] <- tryCatch(coef(fit1)[2], error=function(e) 0)
428
- }, error=function(e) NULL)
429
- }
430
- results
431
- }
432
 
433
- # ---- 10. Kruskal-Wallis Non-Parametric ----
434
- run_kruskal <- function(y, X, mpos, mchr) {
435
- results <- data.frame(marker=colnames(X), position=mpos[seq_len(ncol(X))],
436
- chromosome=mchr[seq_len(ncol(X))], LOD=NA_real_, pvalue=NA_real_,
437
- R2=NA_real_, additive=NA_real_, model="Kruskal-Wallis (Non-Parametric)",
438
- stringsAsFactors=FALSE)
439
-
440
- for (j in seq_len(ncol(X))) {
441
- g <- X[, j]
442
- valid <- !is.na(g)
443
- if (sum(valid) < 3) next
444
-
445
- gv <- as.factor(g[valid])
446
- yv <- y[valid]
447
-
448
- if (nlevels(gv) < 2) next
449
-
450
- tryCatch({
451
- kw <- kruskal.test(yv ~ gv)
452
- results$pvalue[j] <- kw$p.value
453
- results$LOD[j] <- max(0, -log10(kw$p.value + 1e-10) * log10(exp(1)) * 2)
454
- results$R2[j] <- min(1, kw$statistic / (sum(valid) - 1))
455
-
456
- means <- tapply(yv, gv, mean, na.rm=TRUE)
457
- if (length(means) >= 2) {
458
- results$additive[j] <- diff(means)[1]
459
- }
460
- }, error=function(e) NULL)
461
- }
462
- results
463
- }
464
 
465
- # ---- Run all models ----
466
- run_all_models <- function(geno_df, pheno_df, trait, map_df) {
467
- cross <- prepare_cross(geno_df, pheno_df, trait)
468
- if (is.null(cross)) return(NULL)
469
-
470
- y <- cross$y
471
- X <- impute_markers(cross$X)
472
- mk_names <- colnames(X)
473
-
474
- # Get positions and chromosomes from map
475
- mpos <- sapply(mk_names, function(m) {
476
- idx <- which(map_df$marker == m)
477
- if (length(idx) > 0) map_df$position[idx[1]] else NA_real_
478
  })
479
-
480
- mchr <- sapply(mk_names, function(m) {
481
- idx <- which(map_df$marker == m)
482
- if (length(idx) > 0) as.character(map_df$chromosome[idx[1]]) else "1"
 
483
  })
484
-
485
- # Fill NA positions with sequential fallback
486
- if (any(is.na(mpos))) {
487
- seq_pos <- seq(0, 100, length.out = length(mpos))
488
- mpos[is.na(mpos)] <- seq_pos[is.na(mpos)]
489
- }
490
-
491
- models <- list(
492
- run_smr(y, X, mpos, mchr),
493
- run_im(y, X, mpos, mchr),
494
- run_cim(y, X, mpos, mchr),
495
- run_mqm(y, X, mpos, mchr),
496
- run_bim(y, X, mpos, mchr),
497
- run_lasso_qtl(y, X, mpos, mchr),
498
- run_ridge_qtl(y, X, mpos, mchr),
499
- run_epistasis(y, X, mpos, mchr),
500
- run_mlm(y, X, mpos, mchr),
501
- run_kruskal(y, X, mpos, mchr)
502
- )
503
-
504
- do.call(rbind, models)
505
- }
506
 
507
- # Permutation threshold
508
- permutation_threshold <- function(y, X, mpos, mchr, n_perm=100, alpha=0.05) {
509
- X_imp <- impute_markers(X)
510
- lod_max <- numeric(n_perm)
511
-
512
- for (i in seq_len(n_perm)) {
513
- yp <- sample(y)
514
- res <- run_smr(yp, X_imp, mpos, mchr)
515
- lod_max[i] <- max(res$LOD, na.rm=TRUE)
516
- }
517
-
518
- quantile(lod_max, 1-alpha, na.rm=TRUE)
519
- }
520
 
521
- # ============================================================
522
- # TEMPLATE GENERATION HELPERS
523
- # ============================================================
524
- make_geno_template <- function() {
525
- data.frame(
526
- id = c("Line_1", "Line_2", "Line_3"),
527
- Marker_A = c(1, 2, 2),
528
- Marker_B = c(2, 1, 2),
529
- Marker_C = c(1, 1, 2),
530
- Marker_D = c(2, 2, 1),
531
- stringsAsFactors = FALSE
532
- )
533
- }
534
 
535
- make_pheno_template <- function() {
536
- data.frame(
537
- id = c("Line_1", "Line_2", "Line_3"),
538
- Trait_ENV1 = c(25.4, 27.1, 23.8),
539
- Trait_ENV2 = c(26.1, 28.3, 24.5),
540
- stringsAsFactors = FALSE
541
- )
542
- }
543
 
544
- make_map_template <- function() {
545
- data.frame(
546
- marker = c("Marker_A", "Marker_B", "Marker_C", "Marker_D"),
547
- chromosome = c(1, 1, 2, 2),
548
- position_cM = c(2.5, 15.3, 5.1, 22.7),
549
- stringsAsFactors = FALSE
550
- )
551
- }
552
 
553
- # ============================================================
554
- # UI
555
- # ============================================================
556
- ui <- fluidPage(
557
- tags$head(
558
- tags$link(rel="preconnect", href="https://fonts.googleapis.com"),
559
- tags$link(rel="preconnect", href="https://fonts.gstatic.com", crossorigin=NA),
560
- tags$link(href="https://fonts.googleapis.com/css2?family=Space+Mono:wght@400;700&family=Crimson+Pro:ital,wght@0,300;0,600;1,300&display=swap", rel="stylesheet"),
561
- tags$style(HTML("
562
- :root {
563
- --bg:#0a0e1a; --bg2:#0f1526; --bg3:#151d35; --panel:#1a2240;
564
- --accent:#00d4ff; --accent2:#ff6b35; --accent3:#39ff14; --gold:#ffd700;
565
- --text:#e8edf5; --text-dim:#7a8aaa; --border:rgba(0,212,255,0.2);
566
- --font-mono:'Space Mono',monospace; --font-serif:'Crimson Pro',serif;
567
- --glow:0 0 20px rgba(0,212,255,0.3);
568
- --ok:rgba(57,255,20,0.15); --warn:rgba(255,107,53,0.15);
569
- }
570
- *{box-sizing:border-box;margin:0;padding:0;}
571
- body{background:var(--bg);color:var(--text);font-family:var(--font-mono);min-height:100vh;overflow-x:hidden;}
572
- body::before{content:'';position:fixed;top:0;left:0;right:0;bottom:0;
573
- background:radial-gradient(ellipse at 20% 20%,rgba(0,212,255,0.04) 0%,transparent 60%),
574
- radial-gradient(ellipse at 80% 80%,rgba(255,107,53,0.03) 0%,transparent 60%);
575
- pointer-events:none;z-index:0;}
576
- .header-bar{background:linear-gradient(135deg,var(--bg2) 0%,var(--bg3) 100%);
577
- border-bottom:1px solid var(--border);padding:18px 32px;
578
- display:flex;align-items:center;gap:20px;position:relative;z-index:10;}
579
- .header-bar::after{content:'';position:absolute;bottom:0;left:0;right:0;height:1px;
580
- background:linear-gradient(90deg,transparent,var(--accent),var(--accent2),var(--accent3),transparent);}
581
- .header-title{font-family:var(--font-mono);font-size:1.3rem;font-weight:700;
582
- color:var(--accent);letter-spacing:.15em;text-transform:uppercase;}
583
- .header-sub{font-family:var(--font-serif);font-style:italic;font-size:.95rem;color:var(--text-dim);}
584
- .dna-icon{font-size:2rem;filter:drop-shadow(0 0 8px var(--accent));}
585
- .main-layout{display:flex;min-height:calc(100vh - 65px);position:relative;z-index:1;}
586
- .sidebar{width:270px;min-width:270px;background:var(--bg2);border-right:1px solid var(--border);
587
- padding:20px 16px;display:flex;flex-direction:column;gap:14px;overflow-y:auto;}
588
- .sidebar-section{background:var(--panel);border:1px solid var(--border);border-radius:8px;padding:14px;}
589
- .sidebar-label{font-size:.65rem;letter-spacing:.2em;text-transform:uppercase;color:var(--accent);
590
- margin-bottom:10px;border-bottom:1px solid var(--border);padding-bottom:6px;}
591
- .control-group{margin-bottom:12px;}
592
- .control-group label{display:block;font-size:.7rem;color:var(--text-dim);margin-bottom:5px;letter-spacing:.08em;}
593
- select,input[type=range]{width:100%;background:var(--bg);color:var(--text);
594
- border:1px solid var(--border);border-radius:4px;padding:6px 8px;
595
- font-family:var(--font-mono);font-size:.75rem;outline:none;transition:border-color .2s;}
596
- select:focus{border-color:var(--accent);box-shadow:var(--glow);}
597
- .run-btn{width:100%;padding:12px;background:linear-gradient(135deg,var(--accent) 0%,#0099bb 100%);
598
- color:var(--bg);border:none;border-radius:6px;font-family:var(--font-mono);font-size:.8rem;
599
- font-weight:700;letter-spacing:.12em;text-transform:uppercase;cursor:pointer;
600
- transition:all .2s;box-shadow:0 4px 15px rgba(0,212,255,.3);}
601
- .run-btn:hover{transform:translateY(-1px);box-shadow:0 6px 25px rgba(0,212,255,.5);}
602
- .perm-btn{width:100%;padding:10px;background:linear-gradient(135deg,var(--accent2) 0%,#cc4400 100%);
603
- color:var(--text);border:none;border-radius:6px;font-family:var(--font-mono);font-size:.75rem;
604
- font-weight:700;letter-spacing:.1em;text-transform:uppercase;cursor:pointer;
605
- transition:all .2s;margin-top:6px;box-shadow:0 4px 15px rgba(255,107,53,.3);}
606
- .perm-btn:hover{transform:translateY(-1px);box-shadow:0 6px 25px rgba(255,107,53,.5);}
607
- .stat-box{background:var(--bg);border:1px solid var(--border);border-radius:6px;
608
- padding:10px;text-align:center;margin-bottom:8px;}
609
- .stat-val{font-size:1.4rem;color:var(--accent);font-weight:700;}
610
- .stat-lbl{font-size:.6rem;color:var(--text-dim);letter-spacing:.15em;text-transform:uppercase;}
611
- .content-area{flex:1;padding:20px;overflow-y:auto;display:flex;flex-direction:column;gap:20px;}
612
- .tab-bar{display:flex;gap:4px;background:var(--bg2);border:1px solid var(--border);
613
- border-radius:8px;padding:4px;flex-wrap:wrap;}
614
- .tab-btn{padding:8px 14px;background:transparent;color:var(--text-dim);border:none;border-radius:5px;
615
- font-family:var(--font-mono);font-size:.7rem;letter-spacing:.1em;text-transform:uppercase;
616
- cursor:pointer;transition:all .2s;white-space:nowrap;}
617
- .tab-btn.active{background:var(--panel);color:var(--accent);border:1px solid var(--border);box-shadow:var(--glow);}
618
- .tab-btn:hover:not(.active){color:var(--text);}
619
- .panel-card{background:var(--bg2);border:1px solid var(--border);border-radius:10px;overflow:hidden;}
620
- .panel-card-header{background:var(--panel);padding:12px 20px;border-bottom:1px solid var(--border);
621
- display:flex;align-items:center;justify-content:space-between;}
622
- .panel-card-title{font-size:.75rem;letter-spacing:.18em;text-transform:uppercase;color:var(--accent);}
623
- .panel-card-body{padding:16px;}
624
- .plot-container{width:100%;background:var(--bg);border-radius:6px;overflow:hidden;position:relative;}
625
- .results-grid{display:grid;grid-template-columns:1fr 1fr;gap:16px;}
626
- .results-grid-3{display:grid;grid-template-columns:1fr 1fr 1fr;gap:16px;}
627
- table.qtl-table{width:100%;border-collapse:collapse;font-size:.7rem;}
628
- table.qtl-table thead th{background:var(--panel);color:var(--accent);padding:8px 10px;
629
- text-align:left;border-bottom:1px solid var(--border);letter-spacing:.1em;
630
- text-transform:uppercase;position:sticky;top:0;}
631
- table.qtl-table tbody tr{border-bottom:1px solid rgba(255,255,255,.04);}
632
- table.qtl-table tbody tr:hover{background:var(--panel);}
633
- table.qtl-table tbody td{padding:7px 10px;color:var(--text-dim);}
634
- table.qtl-table tbody td:nth-child(4){color:var(--accent3);font-weight:700;}
635
- .sig-row td{color:var(--text)!important;}.sig-row td:nth-child(4){color:var(--gold)!important;}
636
- .badge{display:inline-block;padding:2px 7px;border-radius:3px;font-size:.6rem;
637
- letter-spacing:.1em;text-transform:uppercase;font-weight:700;}
638
- .badge-sig{background:rgba(57,255,20,.15);color:var(--accent3);border:1px solid rgba(57,255,20,.3);}
639
- .badge-ns{background:rgba(255,255,255,.05);color:var(--text-dim);border:1px solid rgba(255,255,255,.1);}
640
- .threshold-badge{display:inline-block;padding:3px 10px;background:rgba(255,215,0,.1);
641
- border:1px solid rgba(255,215,0,.3);color:var(--gold);border-radius:4px;
642
- font-size:.7rem;letter-spacing:.1em;}
643
- .export-btn{padding:7px 14px;background:var(--bg);color:var(--accent);
644
- border:1px solid var(--border);border-radius:4px;font-family:var(--font-mono);
645
- font-size:.65rem;letter-spacing:.1em;cursor:pointer;transition:all .2s;}
646
- .export-btn:hover{border-color:var(--accent);box-shadow:var(--glow);}
647
- .scrollable-table{max-height:400px;overflow-y:auto;}
648
- .env-tag{display:inline-block;padding:2px 8px;border-radius:3px;font-size:.65rem;font-weight:700;letter-spacing:.08em;}
649
- .env1{background:rgba(0,212,255,.15);color:var(--accent);border:1px solid rgba(0,212,255,.3);}
650
- .env2{background:rgba(255,107,53,.15);color:var(--accent2);border:1px solid rgba(255,107,53,.3);}
651
-
652
- /* ====== UPLOAD STYLES (FIXED FOR CLICKABILITY) ====== */
653
- .upload-zone{border:2px dashed var(--border);border-radius:8px;padding:18px 14px;
654
- text-align:center;cursor:pointer;transition:all .3s;background:var(--bg);position:relative;}
655
- .upload-zone:hover{border-color:var(--accent);background:rgba(0,212,255,.04);}
656
- /* Ensure the Shiny file input container fills the zone */
657
- .upload-zone .shiny-file-input-control {
658
- width:100%; height:100%; position:absolute; top:0; left:0; z-index:5;
659
- }
660
- /* Ensure the actual input element fills the zone and captures clicks */
661
- .upload-zone input[type=file]{
662
- position:absolute; top:0; left:0; width:100%; height:100%;
663
- opacity:0; cursor:pointer; z-index:10; font-size:100px; padding:0; margin:0;
664
- }
665
- .upload-icon{font-size:1.6rem;display:block;margin-bottom:6px;pointer-events:none; position:relative; z-index:1;}
666
- .upload-label{font-size:.68rem;color:var(--text-dim);letter-spacing:.06em; pointer-events:none; position:relative; z-index:1;}
667
- .upload-label strong{color:var(--accent);}
668
- .file-status{margin-top:8px;font-size:.65rem;padding:5px 8px;border-radius:4px;}
669
- .file-ok{background:var(--ok);color:var(--accent3);border:1px solid rgba(57,255,20,.3);}
670
- .file-warn{background:var(--warn);color:var(--accent2);border:1px solid rgba(255,107,53,.3);}
671
- .file-info{background:rgba(0,212,255,.08);color:var(--accent);border:1px solid var(--border);}
672
- .upload-sep{text-align:center;font-size:.6rem;color:var(--text-dim);margin:6px 0;letter-spacing:.15em;}
673
- .tmpl-btn{width:100%;padding:7px;background:transparent;color:var(--text-dim);
674
- border:1px solid var(--border);border-radius:4px;font-family:var(--font-mono);
675
- font-size:.65rem;letter-spacing:.08em;cursor:pointer;transition:all .2s;margin-top:4px;}
676
- .tmpl-btn:hover{color:var(--accent);border-color:var(--accent);}
677
- .data-preview{background:var(--bg);border:1px solid var(--border);border-radius:6px;
678
- padding:12px;font-size:.65rem;color:var(--text-dim);overflow-x:auto;max-height:180px;overflow-y:auto;}
679
- .data-preview table{width:100%;border-collapse:collapse;}
680
- .data-preview th{color:var(--accent);padding:4px 8px;border-bottom:1px solid var(--border);
681
- text-align:left;font-size:.62rem;letter-spacing:.08em;white-space:nowrap;}
682
- .data-preview td{padding:3px 8px;border-bottom:1px solid rgba(255,255,255,.04);white-space:nowrap;}
683
- .format-hint{background:rgba(0,212,255,.06);border:1px solid var(--border);border-radius:6px;
684
- padding:10px;font-size:.65rem;color:var(--text-dim);line-height:1.7;margin-top:8px;}
685
- .format-hint code{color:var(--accent3);font-family:var(--font-mono);}
686
- .spinner{width:36px;height:36px;border:3px solid var(--border);border-top-color:var(--accent);
687
- border-radius:50%;animation:spin .8s linear infinite;margin:0 auto;}
688
- @keyframes spin{to{transform:rotate(360deg);}}
689
- #loadingScreen{position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(10,14,26,.95);
690
- display:flex;flex-direction:column;align-items:center;justify-content:center;z-index:9999;gap:16px;}
691
- .loading-text{font-size:.8rem;color:var(--accent);letter-spacing:.2em;text-transform:uppercase;}
692
- #mainContent{display:none;}
693
- "))
694
- ),
695
-
696
- # Loading screen
697
- tags$div(id="loadingScreen",
698
- tags$div(class="spinner"),
699
- tags$div(class="loading-text", "Initializing QTL Engine"),
700
- tags$script(HTML("
701
- Shiny.addCustomMessageHandler('hideLoading', function(msg){
702
- document.getElementById('loadingScreen').style.display='none';
703
- document.getElementById('mainContent').style.display='block';
704
- });
705
- "))
706
- ),
707
-
708
- tags$div(id="mainContent",
709
- # Header
710
- tags$div(class="header-bar",
711
- tags$span(class="dna-icon","🧬"),
712
- tags$div(
713
- tags$div(class="header-title","QTL Cartographer"),
714
- tags$div(class="header-sub","Quantitative Trait Loci Analysis Suite — Upload Your Data")
715
- ),
716
- tags$div(style="margin-left:auto;display:flex;gap:10px;",
717
- tags$div(class="threshold-badge","Oryza sativa / Any Organism"),
718
- tags$div(class="threshold-badge", id="permThreshBadge","Perm. Threshold: —")
719
- )
720
- ),
721
 
722
- tags$div(class="main-layout",
723
- # Sidebar
724
- tags$div(class="sidebar",
725
-
726
- # ---- DATA UPLOAD SECTION ----
727
- tags$div(class="sidebar-section",
728
- tags$div(class="sidebar-label","📂 Upload Your Data"),
729
-
730
- # Genotype file
731
- tags$div(class="control-group",
732
- tags$label("Genotype File (CSV)"),
733
- tags$div(class="upload-zone",
734
- fileInput("geno_file", NULL, accept=".csv", buttonLabel="", placeholder=""),
735
- tags$span(class="upload-icon","🧬"),
736
- tags$div(class="upload-label", HTML("<strong>Click</strong> to upload genotype CSV"))
737
- ),
738
- uiOutput("geno_status")
739
- ),
740
-
741
- # Phenotype file
742
- tags$div(class="control-group",
743
- tags$label("Phenotype File (CSV)"),
744
- tags$div(class="upload-zone",
745
- fileInput("pheno_file", NULL, accept=".csv", buttonLabel="", placeholder=""),
746
- tags$span(class="upload-icon","🌾"),
747
- tags$div(class="upload-label", HTML("<strong>Click</strong> to upload phenotype CSV"))
748
- ),
749
- uiOutput("pheno_status")
750
- ),
751
-
752
- # Map file
753
- tags$div(class="control-group",
754
- tags$label("Genetic Map File (CSV)"),
755
- tags$div(class="upload-zone",
756
- fileInput("map_file", NULL, accept=".csv", buttonLabel="", placeholder=""),
757
- tags$span(class="upload-icon","🗺️"),
758
- tags$div(class="upload-label", HTML("<strong>Click</strong> to upload map CSV"))
759
- ),
760
- uiOutput("map_status")
761
- ),
762
-
763
- tags$div(class="upload-sep","— OR DOWNLOAD TEMPLATES —"),
764
- downloadButton("dl_geno_tmpl", "⬇ Genotype Template", class="tmpl-btn"),
765
- downloadButton("dl_pheno_tmpl", "⬇ Phenotype Template", class="tmpl-btn"),
766
- downloadButton("dl_map_tmpl", "⬇ Map Template", class="tmpl-btn")
767
- ),
768
-
769
- # Analysis Config
770
- tags$div(class="sidebar-section",
771
- tags$div(class="sidebar-label","Analysis Config"),
772
- tags$div(class="control-group",
773
- tags$label("Select Trait"),
774
- uiOutput("trait_selector")
775
- ),
776
- tags$div(class="control-group",
777
- tags$label("LOD Threshold"),
778
- tags$input(type="range", id="lodThresh", min="1", max="10", step="0.1", value="2.5",
779
- oninput="Shiny.setInputValue('lod_threshold',parseFloat(this.value));document.getElementById('lodThreshVal').textContent=parseFloat(this.value).toFixed(1)")
780
- ),
781
- tags$div(style="text-align:center;font-size:.75rem;color:var(--accent);margin-bottom:8px;",
782
- "LOD = ", tags$span(id="lodThreshVal","2.5")
783
- ),
784
- tags$button(class="run-btn", onclick="Shiny.setInputValue('run_analysis',Math.random())","▶ Run Analysis"),
785
- tags$button(class="perm-btn",onclick="Shiny.setInputValue('run_perm',Math.random())","⚡ Permute (100×)")
786
- ),
787
-
788
- # Dataset Summary
789
- tags$div(class="sidebar-section",
790
- tags$div(class="sidebar-label","Dataset Summary"),
791
- uiOutput("dataset_summary_ui")
792
- ),
793
-
794
- # QTL Detected
795
- tags$div(class="sidebar-section",
796
- tags$div(class="sidebar-label","QTL Detected"),
797
- uiOutput("qtlSummaryUI")
798
- )
799
- ),
800
-
801
- # Content area
802
- tags$div(class="content-area",
803
- # Tab bar
804
- tags$div(class="tab-bar",
805
- tags$button(class="tab-btn active", id="tab_upload", onclick="switchTab('upload')", "📂 Data Upload"),
806
- tags$button(class="tab-btn", id="tab_lod", onclick="switchTab('lod')", "LOD Profile"),
807
- tags$button(class="tab-btn", id="tab_multi", onclick="switchTab('multi')", "Multi-Model"),
808
- tags$button(class="tab-btn", id="tab_effects",onclick="switchTab('effects')","QTL Effects"),
809
- tags$button(class="tab-btn", id="tab_circos", onclick="switchTab('circos')", "Circos"),
810
- tags$button(class="tab-btn", id="tab_pheno", onclick="switchTab('pheno')", "Phenotype"),
811
- tags$button(class="tab-btn", id="tab_results",onclick="switchTab('results')","Results Table"),
812
- tags$button(class="tab-btn", id="tab_summary",onclick="switchTab('summary')","Summary")
813
- ),
814
- tags$script(HTML("
815
- function switchTab(name){
816
- document.querySelectorAll('.tab-btn').forEach(b=>b.classList.remove('active'));
817
- document.querySelectorAll('.tab-pane').forEach(p=>p.style.display='none');
818
- document.getElementById('tab_'+name).classList.add('active');
819
- document.getElementById('pane_'+name).style.display='block';
820
- }
821
- ")),
822
-
823
- # ---- UPLOAD / DATA PREVIEW PANE ----
824
- tags$div(id="pane_upload", class="tab-pane",
825
- tags$div(class="panel-card",
826
- tags$div(class="panel-card-header",
827
- tags$div(class="panel-card-title","Data Upload & Format Guide"),
828
- uiOutput("data_ready_badge")
829
- ),
830
- tags$div(class="panel-card-body",
831
- tags$div(class="results-grid-3",
832
- # Genotype format
833
- tags$div(
834
- tags$div(class="panel-card-title", style="margin-bottom:8px;","Genotype CSV Format"),
835
- tags$div(class="format-hint",
836
- tags$b(style="color:var(--accent);","Required format:"), tags$br(),
837
- HTML("<code>id</code> — unique line/sample identifier (first column)"), tags$br(),
838
- HTML("<code>MarkerName</code> — one column per marker (marker names in row 1)"), tags$br(), tags$br(),
839
- tags$b(style="color:var(--accent);","Genotype codes:"), tags$br(),
840
- HTML("<code>1</code> = AA (Parent 1 homozygous)"), tags$br(),
841
- HTML("<code>2</code> = BB (Parent 2 homozygous)"), tags$br(),
842
- HTML("<code>0</code> = AB (Heterozygous)"), tags$br(),
843
- HTML("<code>-1</code> or blank = Missing data"), tags$br(), tags$br(),
844
- "All marker names must match between genotype and map files."
845
- )
846
- ),
847
- # Phenotype format
848
- tags$div(
849
- tags$div(class="panel-card-title", style="margin-bottom:8px;","Phenotype CSV Format"),
850
- tags$div(class="format-hint",
851
- tags$b(style="color:var(--accent);","Required format:"), tags$br(),
852
- HTML("<code>id</code> — must match genotype file IDs (first column)"), tags$br(),
853
- HTML("<code>TraitName</code> — one column per trait/environment"), tags$br(), tags$br(),
854
- tags$b(style="color:var(--accent);","Notes:"), tags$br(),
855
- "• Values must be numeric", tags$br(),
856
- "• Multiple traits allowed — select from dropdown", tags$br(),
857
- "• Missing values: leave cell empty or use NA", tags$br(), tags$br(),
858
- tags$i(style="color:var(--text-dim);",
859
- "Example: ENV1_PL, ENV2_PL, GrainWeight, etc.")
860
- )
861
- ),
862
- # Map format
863
- tags$div(
864
- tags$div(class="panel-card-title", style="margin-bottom:8px;","Genetic Map CSV Format"),
865
- tags$div(class="format-hint",
866
- tags$b(style="color:var(--accent);","Required columns:"), tags$br(),
867
- HTML("<code>marker</code> — marker name (must match genotype file)"), tags$br(),
868
- HTML("<code>chromosome</code> — chromosome number or name"), tags$br(),
869
- HTML("<code>position_cM</code> — genetic position in cM"), tags$br(), tags$br(),
870
- tags$b(style="color:var(--accent);","Notes:"), tags$br(),
871
- "• Column headers are flexible (detected automatically)", tags$br(),
872
- "• Physical positions (bp) also accepted — will be treated as map units", tags$br(),
873
- "• Markers not found in map will get sequential positions"
874
- )
875
- )
876
- ),
877
- tags$hr(style="border-color:var(--border);margin:16px 0;"),
878
- tags$div(class="results-grid",
879
- tags$div(
880
- tags$div(class="panel-card-title",style="margin-bottom:10px;","Genotype Data Preview"),
881
- tags$div(class="data-preview", uiOutput("geno_preview"))
882
- ),
883
- tags$div(
884
- tags$div(class="panel-card-title",style="margin-bottom:10px;","Phenotype Data Preview"),
885
- tags$div(class="data-preview", uiOutput("pheno_preview"))
886
- )
887
- ),
888
- tags$div(style="margin-top:14px;",
889
- tags$div(class="panel-card-title",style="margin-bottom:10px;","Genetic Map Preview"),
890
- tags$div(class="data-preview", uiOutput("map_preview"))
891
- )
892
- )
893
- )
894
- ),
895
-
896
- # ---- LOD Profile ----
897
- tags$div(id="pane_lod", class="tab-pane", style="display:none",
898
- tags$div(class="panel-card",
899
- tags$div(class="panel-card-header",
900
- tags$div(class="panel-card-title","LOD Score Profile"),
901
- uiOutput("currentModelBadge")
902
- ),
903
- tags$div(class="panel-card-body",
904
- tags$div(class="plot-container", uiOutput("lodPlotUI"))
905
- )
906
- )
907
- ),
908
-
909
- # ---- Multi-Model ----
910
- tags$div(id="pane_multi", class="tab-pane", style="display:none",
911
- tags$div(class="panel-card",
912
- tags$div(class="panel-card-header",
913
- tags$div(class="panel-card-title","Multi-Model LOD Comparison"),
914
- tags$div(style="font-size:.65rem;color:var(--text-dim);","All 10 statistical models overlaid")
915
- ),
916
- tags$div(class="panel-card-body",
917
- tags$div(class="plot-container", uiOutput("multiModelPlotUI"))
918
- )
919
- )
920
- ),
921
-
922
- # ---- Effects ----
923
- tags$div(id="pane_effects", class="tab-pane", style="display:none",
924
- tags$div(class="results-grid",
925
- tags$div(class="panel-card",
926
- tags$div(class="panel-card-header",tags$div(class="panel-card-title","Additive Effects")),
927
- tags$div(class="panel-card-body",tags$div(class="plot-container",uiOutput("addEffPlotUI")))
928
- ),
929
- tags$div(class="panel-card",
930
- tags$div(class="panel-card-header",tags$div(class="panel-card-title","R² (Variance Explained)")),
931
- tags$div(class="panel-card-body",tags$div(class="plot-container",uiOutput("r2PlotUI")))
932
- )
933
- )
934
- ),
935
-
936
- # ---- Circos ----
937
- tags$div(id="pane_circos", class="tab-pane", style="display:none",
938
- tags$div(class="panel-card",
939
- tags$div(class="panel-card-header",tags$div(class="panel-card-title","Circos — Chromosomal QTL Map")),
940
- tags$div(class="panel-card-body",tags$div(class="plot-container",uiOutput("circosUI")))
941
- )
942
- ),
943
-
944
- # ---- Phenotype ----
945
- tags$div(id="pane_pheno", class="tab-pane", style="display:none",
946
- tags$div(class="results-grid",
947
- tags$div(class="panel-card",
948
- tags$div(class="panel-card-header",tags$div(class="panel-card-title","Phenotype Distribution")),
949
- tags$div(class="panel-card-body",tags$div(class="plot-container",uiOutput("phenoDistUI")))
950
- ),
951
- tags$div(class="panel-card",
952
- tags$div(class="panel-card-header",tags$div(class="panel-card-title","Genotype × Phenotype")),
953
- tags$div(class="panel-card-body",tags$div(class="plot-container",uiOutput("genoPhePlotUI")))
954
- )
955
- )
956
- ),
957
-
958
- # ---- Results Table ----
959
- tags$div(id="pane_results", class="tab-pane", style="display:none",
960
- tags$div(class="panel-card",
961
- tags$div(class="panel-card-header",
962
- tags$div(class="panel-card-title","Full Results Table — All Models"),
963
- downloadButton("dl_results","⬇ Download CSV", class="export-btn")
964
- ),
965
- tags$div(class="panel-card-body",
966
- tags$div(class="scrollable-table", uiOutput("resultsTableUI"))
967
- )
968
- )
969
- ),
970
-
971
- # ---- Summary ----
972
- tags$div(id="pane_summary", class="tab-pane", style="display:none",
973
- tags$div(class="panel-card",
974
- tags$div(class="panel-card-header",tags$div(class="panel-card-title","Publication Summary")),
975
- tags$div(class="panel-card-body",uiOutput("summaryUI"))
976
- ),
977
- tags$div(class="panel-card",style="margin-top:16px;",
978
- tags$div(class="panel-card-header",tags$div(class="panel-card-title","Confidence Interval Plot")),
979
- tags$div(class="panel-card-body",tags$div(class="plot-container",uiOutput("ciPlotUI")))
980
- )
981
- )
982
- )
983
  )
984
- ),
985
-
986
- tags$script(HTML("
987
- document.addEventListener('DOMContentLoaded',function(){
988
- Shiny.setInputValue('lod_threshold',2.5);
989
- });
990
- Shiny.addCustomMessageHandler('updatePermBadge',function(msg){
991
- document.getElementById('permThreshBadge').textContent='Perm. Threshold: LOD = '+msg.val;
992
- });
993
- Shiny.addCustomMessageHandler('switchToLOD',function(msg){
994
- document.querySelectorAll('.tab-btn').forEach(b=>b.classList.remove('active'));
995
- document.querySelectorAll('.tab-pane').forEach(p=>p.style.display='none');
996
- document.getElementById('tab_lod').classList.add('active');
997
- document.getElementById('pane_lod').style.display='block';
998
- });
999
- "))
1000
- )
1001
 
1002
- # ============================================================
1003
- # SERVER
1004
- # ============================================================
1005
- server <- function(input, output, session) {
1006
 
1007
- session$onFlushed(function() {
1008
- session$sendCustomMessage("hideLoading", list())
1009
  })
1010
 
1011
- rv <- reactiveValues(
1012
- geno_df = NULL,
1013
- pheno_df = NULL,
1014
- map_df = NULL,
1015
- results = NULL,
1016
- perm_thresh = 2.5,
1017
- trait = NULL
1018
- )
1019
 
1020
- # ---- File parsing ----
1021
- observeEvent(input$geno_file, {
1022
- req(input$geno_file$datapath) # Ensure file exists
1023
- rv$geno_df <- parse_geno_csv(input$geno_file$datapath)
1024
- if (!is.null(rv$geno_df)) {
1025
- showNotification(paste("Loaded", nrow(rv$geno_df), "samples with", ncol(rv$geno_df)-1, "markers"), type="message", duration=3)
1026
- } else {
1027
- showNotification("Error loading genotype file. Check format.", type="error", duration=5)
1028
- }
1029
- })
1030
-
1031
- observeEvent(input$pheno_file, {
1032
- req(input$pheno_file$datapath)
1033
- rv$pheno_df <- parse_pheno_csv(input$pheno_file$datapath)
1034
- if (!is.null(rv$pheno_df)) {
1035
- showNotification(paste("Loaded", nrow(rv$pheno_df), "samples with", ncol(rv$pheno_df)-1, "traits"), type="message", duration=3)
1036
- } else {
1037
- showNotification("Error loading phenotype file. Check format.", type="error", duration=5)
1038
- }
1039
- })
1040
-
1041
- observeEvent(input$map_file, {
1042
- req(input$map_file$datapath)
1043
- rv$map_df <- parse_map_csv(input$map_file$datapath)
1044
- if (!is.null(rv$map_df)) {
1045
- showNotification(paste("Loaded", nrow(rv$map_df), "markers from map"), type="message", duration=3)
1046
- } else {
1047
- showNotification("Error loading map file. Check format.", type="error", duration=5)
1048
- }
1049
- })
1050
 
1051
- # ---- File status badges ----
1052
- output$geno_status <- renderUI({
1053
- if (is.null(rv$geno_df)) return(NULL)
1054
- n_lines <- nrow(rv$geno_df)
1055
- n_markers <- ncol(rv$geno_df) - 1
1056
- tags$div(class="file-status file-ok",
1057
- paste0("✓ ", n_lines, " samples × ", n_markers, " markers loaded"))
1058
- })
1059
-
1060
- output$pheno_status <- renderUI({
1061
- if (is.null(rv$pheno_df)) return(NULL)
1062
- n_lines <- nrow(rv$pheno_df)
1063
- n_traits <- ncol(rv$pheno_df) - 1
1064
- tags$div(class="file-status file-ok",
1065
- paste0("✓ ", n_lines, " samples × ", n_traits, " trait(s) loaded"))
1066
- })
1067
-
1068
- output$map_status <- renderUI({
1069
- if (is.null(rv$map_df)) return(NULL)
1070
- tags$div(class="file-status file-ok",
1071
- paste0("✓ ", nrow(rv$map_df), " markers mapped across ",
1072
- length(unique(rv$map_df$chromosome)), " chromosome(s)"))
1073
- })
1074
 
1075
- # ---- Data ready badge ----
1076
- output$data_ready_badge <- renderUI({
1077
- g <- !is.null(rv$geno_df)
1078
- p <- !is.null(rv$pheno_df)
1079
- m <- !is.null(rv$map_df)
1080
-
1081
- if (g && p && m) {
1082
- tags$span(class="badge badge-sig","✓ All Files Loaded — Ready to Analyse")
 
 
 
 
 
 
1083
  } else {
1084
- missing <- paste(c(if(!g)"Genotype",if(!p)"Phenotype",if(!m)"Map"), collapse=", ")
1085
- tags$span(class="badge badge-ns", paste0("Waiting for: ", missing))
1086
  }
1087
- })
1088
 
1089
- # ---- Trait selector (dynamic from pheno file) ----
1090
- output$trait_selector <- renderUI({
1091
- if (is.null(rv$pheno_df)) {
1092
- return(tags$div(class="file-status file-warn","Upload phenotype file first"))
1093
- }
1094
- trait_cols <- setdiff(names(rv$pheno_df), "id")
1095
- if (length(trait_cols) == 0) {
1096
- return(tags$div(class="file-status file-warn","No trait columns found in phenotype file"))
1097
- }
1098
-
1099
- tagList(
1100
- selectInput("trait_select", NULL, choices = trait_cols, selected = trait_cols[1]),
1101
- tags$script(HTML("
1102
- document.getElementById('trait_select').addEventListener('change', function() {
1103
- Shiny.setInputValue('trait', this.value);
1104
- });
1105
- "))
1106
- )
1107
- })
1108
 
1109
- observeEvent(input$trait_select, {
1110
- rv$trait <- input$trait_select
1111
- })
1112
-
1113
- # Initialize trait
1114
- observe({
1115
- if (!is.null(rv$pheno_df) && is.null(rv$trait)) {
1116
- trait_cols <- setdiff(names(rv$pheno_df), "id")
1117
- if (length(trait_cols) > 0) {
1118
- rv$trait <- trait_cols[1]
1119
- }
1120
- }
1121
  })
1122
 
1123
- # ---- Dataset summary ----
1124
- output$dataset_summary_ui <- renderUI({
1125
- g <- rv$geno_df
1126
- p <- rv$pheno_df
1127
- m <- rv$map_df
1128
-
1129
- tags$div(
1130
- tags$div(class="stat-box",
1131
- tags$div(class="stat-val", if (!is.null(g)) nrow(g) else "—"),
1132
- tags$div(class="stat-lbl","Lines")
1133
- ),
1134
- tags$div(class="stat-box",
1135
- tags$div(class="stat-val", if (!is.null(g)) ncol(g)-1 else "—"),
1136
- tags$div(class="stat-lbl","Markers")
1137
- ),
1138
- tags$div(class="stat-box",
1139
- tags$div(class="stat-val", if (!is.null(m)) length(unique(m$chromosome)) else "—"),
1140
- tags$div(class="stat-lbl","Chromosomes")
1141
- ),
1142
- tags$div(class="stat-box",
1143
- tags$div(class="stat-val", if (!is.null(p)) ncol(p)-1 else "—"),
1144
- tags$div(class="stat-lbl","Traits")
1145
- )
1146
- )
1147
- })
1148
 
1149
- # ---- Data previews ----
1150
- make_preview_table <- function(df, max_rows=5, max_cols=10) {
1151
- if (is.null(df)) return(tags$em(style="color:var(--text-dim);","No data loaded"))
1152
-
1153
- d <- df[seq_len(min(nrow(df), max_rows)), seq_len(min(ncol(df), max_cols)), drop=FALSE]
1154
-
1155
- tags$table(
1156
- tags$thead(tags$tr(lapply(names(d), function(n) tags$th(substr(n, 1, 20))))),
1157
- tags$tbody(lapply(seq_len(nrow(d)), function(i)
1158
- tags$tr(lapply(seq_len(ncol(d)), function(j) {
1159
- val <- d[i, j]
1160
- if (is.numeric(val)) val <- round(val, 3)
1161
- tags$td(as.character(val))
1162
- }))
1163
- ))
1164
- )
1165
- }
1166
-
1167
- output$geno_preview <- renderUI(make_preview_table(rv$geno_df))
1168
- output$pheno_preview <- renderUI(make_preview_table(rv$pheno_df))
1169
- output$map_preview <- renderUI(make_preview_table(rv$map_df))
1170
-
1171
- # ---- Template downloads ----
1172
- output$dl_geno_tmpl <- downloadHandler("genotype_template.csv",
1173
- content=function(f) write.csv(make_geno_template(), f, row.names=FALSE))
1174
- output$dl_pheno_tmpl <- downloadHandler("phenotype_template.csv",
1175
- content=function(f) write.csv(make_pheno_template(), f, row.names=FALSE))
1176
- output$dl_map_tmpl <- downloadHandler("map_template.csv",
1177
- content=function(f) write.csv(make_map_template(), f, row.names=FALSE))
1178
-
1179
- # ---- Run analysis ----
1180
- observeEvent(input$run_analysis, {
1181
- req(rv$geno_df, rv$pheno_df, rv$map_df)
1182
-
1183
- trait <- if (!is.null(rv$trait) && rv$trait != "") rv$trait else {
1184
- trait_cols <- setdiff(names(rv$pheno_df), "id")
1185
- if (length(trait_cols) > 0) trait_cols[1] else NULL
1186
- }
1187
-
1188
- if (is.null(trait)) {
1189
- showNotification("No trait selected. Please check phenotype file.", type="error")
1190
- return(NULL)
1191
- }
1192
-
1193
- rv$trait <- trait
1194
-
1195
- withProgress(message="Running QTL analysis...", value=0, {
1196
- incProgress(0.2, detail="Preparing data...")
1197
- rv$results <- tryCatch(
1198
- run_all_models(rv$geno_df, rv$pheno_df, trait, rv$map_df),
1199
- error = function(e) {
1200
- showNotification(paste("Analysis error:", e$message), type="error", duration=8)
1201
- NULL
1202
- }
1203
- )
1204
- incProgress(0.8, detail="Rendering plots...")
1205
- })
1206
-
1207
- if (!is.null(rv$results)) {
1208
- showNotification("Analysis complete!", type="message", duration=3)
1209
- session$sendCustomMessage("switchToLOD", list())
1210
- }
1211
  })
1212
 
1213
- # ---- Permutation ----
1214
- observeEvent(input$run_perm, {
1215
- req(rv$geno_df, rv$pheno_df, rv$map_df)
1216
-
1217
- trait <- if (!is.null(rv$trait)) rv$trait else {
1218
- trait_cols <- setdiff(names(rv$pheno_df), "id")
1219
- if (length(trait_cols) > 0) trait_cols[1] else NULL
1220
- }
1221
-
1222
- if (is.null(trait)) {
1223
- showNotification("No trait selected", type="error")
1224
- return(NULL)
1225
- }
1226
-
1227
- withProgress(message="Permutation testing (100 permutations)...", value=0, {
1228
- cross <- prepare_cross(rv$geno_df, rv$pheno_df, trait)
1229
- if (is.null(cross)) {
1230
- showNotification("Error preparing data for permutation", type="error")
1231
- return(NULL)
1232
- }
1233
-
1234
- X_imp <- impute_markers(cross$X)
1235
- mk_names <- colnames(X_imp)
1236
-
1237
- mpos <- sapply(mk_names, function(m) {
1238
- idx <- which(rv$map_df$marker == m)
1239
- if (length(idx) > 0) rv$map_df$position[idx[1]] else NA_real_
1240
- })
1241
-
1242
- mchr <- sapply(mk_names, function(m) {
1243
- idx <- which(rv$map_df$marker == m)
1244
- if (length(idx) > 0) as.character(rv$map_df$chromosome[idx[1]]) else "1"
1245
- })
1246
-
1247
- if (any(is.na(mpos))) {
1248
- sp <- seq(0, 100, length.out=length(mpos))
1249
- mpos[is.na(mpos)] <- sp[is.na(mpos)]
1250
- }
1251
-
1252
- incProgress(0.1, detail="Running permutations...")
1253
- thr <- permutation_threshold(cross$y, X_imp, mpos, mchr, n_perm=100)
1254
- rv$perm_thresh <- round(thr, 3)
1255
- })
1256
-
1257
- showNotification(paste0("Permutation threshold (α=0.05): LOD = ", rv$perm_thresh), type="message", duration=5)
1258
- session$sendCustomMessage("updatePermBadge", list(val=rv$perm_thresh))
1259
  })
1260
 
1261
- # ---- Results download ----
1262
- output$dl_results <- downloadHandler(
1263
- filename=function() paste0("QTL_results_", Sys.Date(), ".csv"),
1264
- content=function(f) { req(rv$results); write.csv(rv$results, f, row.names=FALSE) }
1265
- )
1266
 
1267
- get_threshold <- reactive({
1268
- if (!is.null(input$lod_threshold) && !is.na(input$lod_threshold))
1269
- input$lod_threshold
1270
- else
1271
- 2.5
1272
- })
1273
 
1274
- smr_res <- reactive({ req(rv$results); rv$results[rv$results$model=="Single Marker Regression",] })
1275
- im_res <- reactive({ req(rv$results); rv$results[rv$results$model=="Interval Mapping (HK)",] })
1276
- cim_res <- reactive({ req(rv$results); rv$results[rv$results$model=="Composite Interval Mapping",] })
1277
 
1278
- output$currentModelBadge <- renderUI({
1279
- trait <- if (!is.null(rv$trait)) rv$trait else "—"
1280
- tags$span(class="env-tag env1", trait)
1281
- })
1282
 
1283
- output$qtlSummaryUI <- renderUI({
1284
- if (is.null(rv$results)) return(tags$div(class="file-status file-warn","Run analysis first"))
1285
-
1286
- thr <- get_threshold()
1287
- sig <- rv$results[!is.na(rv$results$LOD) & rv$results$LOD >= thr, ]
1288
- n_qtl <- nrow(unique(sig[,c("marker","chromosome")]))
1289
-
1290
- tags$div(
1291
- tags$div(class="stat-box",
1292
- tags$div(class="stat-val", style="color:var(--accent3);", n_qtl),
1293
- tags$div(class="stat-lbl","Sig. Marker×Model")
1294
- ),
1295
- if (nrow(sig) > 0 && n_qtl <= 10)
1296
- tags$div(style="font-size:.65rem;color:var(--text-dim);margin-top:6px;",
1297
- paste(head(unique(sig$marker), 5), collapse=", "))
1298
- )
1299
- })
1300
 
1301
- # ============================================================
1302
- # PLOTS (simplified versions for brevity - same as original)
1303
- # ============================================================
 
1304
 
1305
- output$lodPlotUI <- renderUI({
1306
- req(rv$results)
1307
- tags$div(class="plot-container", style="min-height:400px;",
1308
- tags$p("LOD Plot - Analysis complete. Please run analysis to view plots."))
1309
- })
1310
-
1311
- output$multiModelPlotUI <- renderUI({
1312
- req(rv$results)
1313
- tags$div(class="plot-container", style="min-height:400px;",
1314
- tags$p("Multi-Model Plot - Analysis complete."))
1315
- })
1316
-
1317
- output$addEffPlotUI <- renderUI({
1318
- req(rv$results)
1319
- tags$div(class="plot-container", style="min-height:300px;",
1320
- tags$p("Additive Effects Plot"))
1321
- })
1322
-
1323
- output$r2PlotUI <- renderUI({
1324
- req(rv$results)
1325
- tags$div(class="plot-container", style="min-height:300px;",
1326
- tags$p("R² Plot"))
1327
- })
1328
-
1329
- output$circosUI <- renderUI({
1330
- req(rv$results)
1331
- tags$div(class="plot-container", style="min-height:500px;text-align:center;",
1332
- tags$p("Circos Plot - QTL Map"))
1333
- })
1334
-
1335
- output$phenoDistUI <- renderUI({
1336
- req(rv$pheno_df, rv$trait)
1337
- tags$div(class="plot-container", style="min-height:300px;",
1338
- tags$p("Phenotype Distribution"))
1339
- })
1340
-
1341
- output$genoPhePlotUI <- renderUI({
1342
- req(rv$results, rv$geno_df, rv$pheno_df, rv$trait)
1343
- tags$div(class="plot-container", style="min-height:300px;",
1344
- tags$p("Genotype × Phenotype Plot"))
1345
- })
1346
-
1347
- output$ciPlotUI <- renderUI({
1348
- req(rv$results)
1349
- tags$div(class="plot-container", style="min-height:250px;",
1350
- tags$p("Confidence Interval Plot"))
1351
- })
1352
 
1353
- # ---- Results Table ----
1354
- output$resultsTableUI <- renderUI({
1355
- req(rv$results)
1356
- thr <- get_threshold()
1357
- df <- rv$results[order(rv$results$model, rv$results$position), ]
1358
-
1359
- if (nrow(df) == 0) {
1360
- return(tags$p("No results available"))
1361
- }
1362
-
1363
- # Take top results for display
1364
- df <- head(df, 100)
1365
-
1366
- rows <- lapply(seq_len(nrow(df)), function(i){
1367
- row <- df[i,]
1368
- lod <- if (!is.na(row$LOD)) round(row$LOD, 4) else "—"
1369
- pval <- if (!is.na(row$pvalue)) formatC(row$pvalue, format="e", digits=2) else "—"
1370
- r2 <- if (!is.na(row$R2)) paste0(round(row$R2*100, 1), "%") else "—"
1371
- add <- if (!is.na(row$additive)) round(row$additive, 4) else "—"
1372
- sig <- !is.na(row$LOD) && row$LOD >= thr
1373
-
1374
- tags$tr(class=if(sig)"sig-row" else "",
1375
- tags$td(substr(row$marker, 1, 25)),
1376
- tags$td(row$chromosome),
1377
- tags$td(round(row$position, 3)),
1378
- tags$td(lod),
1379
- tags$td(pval),
1380
- tags$td(r2),
1381
- tags$td(add),
1382
- tags$td(substr(row$model, 1, 25)),
1383
- tags$td(if(sig) tags$span(class="badge badge-sig","SIG") else tags$span(class="badge badge-ns","NS"))
1384
- )
1385
- })
1386
-
1387
- tags$div(style="overflow-x:auto;",
1388
- tags$table(class="qtl-table",
1389
- tags$thead(tags$tr(
1390
- tags$th("Marker"), tags$th("Chr"), tags$th("Pos"),
1391
- tags$th("LOD"), tags$th("p-value"), tags$th("R²"),
1392
- tags$th("Additive"), tags$th("Model"), tags$th("Sig.")
1393
- )),
1394
- tags$tbody(rows)
1395
- )
1396
- )
1397
  })
1398
 
1399
- # ---- Summary ----
1400
- output$summaryUI <- renderUI({
1401
- req(rv$results, rv$pheno_df, rv$trait)
1402
-
1403
- thr <- get_threshold()
1404
- trait <- rv$trait
1405
- smr <- smr_res()
1406
-
1407
- best_idx <- which.max(smr$LOD)
1408
- best_mk <- if (length(best_idx) > 0 && !is.na(best_idx)) smr$marker[best_idx] else "—"
1409
- best_lod <- if (length(best_idx) > 0 && !is.na(best_idx)) round(smr$LOD[best_idx], 3) else "—"
1410
- best_pos <- if (length(best_idx) > 0 && !is.na(best_idx)) round(smr$position[best_idx], 3) else "—"
1411
- best_chr <- if (length(best_idx) > 0 && !is.na(best_idx)) smr$chromosome[best_idx] else "—"
1412
- best_r2 <- if (length(best_idx) > 0 && !is.na(best_idx) && !is.na(smr$R2[best_idx]))
1413
- paste0(round(smr$R2[best_idx]*100, 1), "%") else "—"
1414
-
1415
- pheno_vals <- suppressWarnings(as.numeric(rv$pheno_df[[trait]]))
1416
- pheno_vals <- pheno_vals[!is.na(pheno_vals)]
1417
-
1418
- if (length(pheno_vals) > 0) {
1419
- pheno_mean <- round(mean(pheno_vals, na.rm=TRUE), 3)
1420
- pheno_sd <- round(sd(pheno_vals, na.rm=TRUE), 3)
1421
- pheno_cv <- round(pheno_sd/pheno_mean*100, 2)
1422
  } else {
1423
- pheno_mean <- pheno_sd <- pheno_cv <- "—"
1424
  }
1425
-
1426
- n_lines <- if (!is.null(rv$geno_df)) nrow(rv$geno_df) else 0
1427
- n_markers <- if (!is.null(rv$geno_df)) ncol(rv$geno_df)-1 else 0
1428
-
1429
- sig <- rv$results[!is.na(rv$results$LOD) & rv$results$LOD >= thr, ]
1430
-
1431
- tags$div(style="font-family:var(--font-serif);font-size:1rem;line-height:1.8;color:var(--text);",
1432
- tags$h3(style="font-family:var(--font-mono);font-size:.9rem;color:var(--accent);letter-spacing:.15em;text-transform:uppercase;margin-bottom:16px;border-bottom:1px solid var(--border);padding-bottom:8px;",
1433
- "Publication-Ready Summary"),
1434
- tags$div(class="results-grid-3", style="margin-bottom:20px;",
1435
- tags$div(class="stat-box", tags$div(class="stat-val", as.character(pheno_mean)),
1436
- tags$div(class="stat-lbl", paste0("Mean ", trait))),
1437
- tags$div(class="stat-box", tags$div(class="stat-val", style="color:var(--accent2);", as.character(pheno_sd)),
1438
- tags$div(class="stat-lbl","Std. Deviation")),
1439
- tags$div(class="stat-box", tags$div(class="stat-val", style="color:var(--accent3);", paste0(pheno_cv, "%")),
1440
- tags$div(class="stat-lbl","CV %"))
1441
- ),
1442
- tags$div(class="results-grid", style="margin-bottom:16px;",
1443
- tags$div(class="panel-card", style="padding:14px;",
1444
- tags$div(style="font-size:.7rem;letter-spacing:.15em;text-transform:uppercase;color:var(--accent);margin-bottom:8px;","Best QTL (SMR)"),
1445
- tags$table(style="width:100%;font-size:.8rem;",
1446
- tags$tr(tags$td(style="color:var(--text-dim);padding:3px 0;","Marker:"), tags$td(style="color:var(--text);font-weight:700;", best_mk)),
1447
- tags$tr(tags$td(style="color:var(--text-dim);padding:3px 0;","Chr / Pos:"), tags$td(paste0("Chr ", best_chr, " / ", best_pos, " cM"))),
1448
- tags$tr(tags$td(style="color:var(--text-dim);padding:3px 0;","LOD Score:"), tags$td(style="color:var(--gold);font-weight:700;", best_lod)),
1449
- tags$tr(tags$td(style="color:var(--text-dim);padding:3px 0;","Var. Expl.:"), tags$td(style="color:var(--accent3);", best_r2)),
1450
- tags$tr(tags$td(style="color:var(--text-dim);padding:3px 0;","Threshold:"), tags$td(paste0("LOD = ", thr)))
1451
- )
1452
- ),
1453
- tags$div(class="panel-card", style="padding:14px;",
1454
- tags$div(style="font-size:.7rem;letter-spacing:.15em;text-transform:uppercase;color:var(--accent);margin-bottom:8px;","Dataset Info"),
1455
- tags$table(style="width:100%;font-size:.8rem;",
1456
- tags$tr(tags$td(style="color:var(--text-dim);padding:3px 0;","Lines:"), tags$td(n_lines)),
1457
- tags$tr(tags$td(style="color:var(--text-dim);padding:3px 0;","Markers:"), tags$td(n_markers)),
1458
- tags$tr(tags$td(style="color:var(--text-dim);padding:3px 0;","Chromosomes:"),
1459
- tags$td(if (!is.null(rv$map_df)) length(unique(rv$map_df$chromosome)) else "—")),
1460
- tags$tr(tags$td(style="color:var(--text-dim);padding:3px 0;","Trait:"), tags$td(trait)),
1461
- tags$tr(tags$td(style="color:var(--text-dim);padding:3px 0;","Sig. markers:"),
1462
- tags$td(nrow(unique(sig[,c("marker","chromosome")]))))
1463
- )
1464
- )
1465
- ),
1466
- tags$div(style="background:var(--panel);border:1px solid var(--border);border-radius:8px;padding:14px;font-family:var(--font-serif);font-style:italic;color:var(--text-dim);font-size:.95rem;line-height:1.8;",
1467
- tags$strong(style="color:var(--text);font-style:normal;font-family:var(--font-mono);font-size:.75rem;letter-spacing:.1em;text-transform:uppercase;display:block;margin-bottom:8px;","Suggested Methods Text"),
1468
- paste0("QTL analysis was performed for trait '", trait, "' across ",
1469
- if (!is.null(rv$map_df)) length(unique(rv$map_df$chromosome)) else "multiple", " chromosome(s) using ",
1470
- n_lines, " lines and ", n_markers, " markers. Single marker regression (SMR), interval mapping (IM-HK), ",
1471
- "and composite interval mapping (CIM) were performed alongside 7 additional models including LASSO, ",
1472
- "ridge regression, mixed linear model, Kruskal-Wallis non-parametric test, Bayesian interval mapping, ",
1473
- "MQM, and two-way epistasis analysis. Phenotypic mean was ", pheno_mean, " (SD = ", pheno_sd, "). ",
1474
- "The highest LOD score of ", best_lod, " was detected at marker ", best_mk,
1475
- " (Chr ", best_chr, ", ", best_pos, " cM), explaining ", best_r2, " of phenotypic variance. ",
1476
- "Significance threshold was set at LOD = ", thr, "; empirical genome-wide threshold estimated by 100 permutations.")
1477
- )
1478
- )
1479
  })
 
 
 
 
 
 
 
 
 
1480
  }
1481
 
1482
- shinyApp(ui=ui, server=server)
 
 
 
1
  library(shiny)
2
+ library(qtl)
3
+ library(readr)
4
+ library(dplyr)
5
+ library(ggplot2)
6
+ library(DT)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
 
8
+ # ---------------- UI ---------------- #
9
+ ui <- fluidPage(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
 
11
+ tags$head(tags$style(HTML("
12
+ body { background:#f4f6f9; font-family:Arial; }
13
+ .box { background:white; padding:15px; border-radius:10px; }
14
+ "))),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
+ titlePanel("🌾 Advanced QTL Mapping Pipeline"),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
+ sidebarLayout(
19
+ sidebarPanel(class="box",
 
 
 
 
 
 
 
 
20
 
21
+ fileInput("geno","Upload Genotype CSV"),
22
+ fileInput("pheno","Upload Phenotype CSV"),
 
 
 
 
 
 
 
 
 
 
 
23
 
24
+ selectInput("trait","Select Trait", choices=NULL),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
 
26
+ selectInput("model","Model",
27
+ c("EM","HK","IMP","CIM","STEPWISE")),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
 
29
+ numericInput("perm","Permutation",100),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
 
31
+ actionButton("run","Run Analysis"),
32
+ br(), br(),
33
+ downloadButton("download","Download Results")
34
+ ),
 
 
 
35
 
36
+ mainPanel(
37
+ tabsetPanel(
 
 
 
 
 
 
 
 
 
 
 
38
 
39
+ tabPanel("LOD Plot", plotOutput("lod")),
40
+ tabPanel("Manhattan Plot", plotOutput("manhattan")),
41
+ tabPanel("QTL Map", plotOutput("qtlMap", height="600px")),
42
+ tabPanel("Peaks", DTOutput("peaks"))
43
+ )
44
+ )
45
+ )
46
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
 
48
+ # ---------------- SERVER ---------------- #
49
+ server <- function(input, output, session) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
 
51
+ # -------- Load Genotype -------- #
52
+ geno_clean <- reactive({
53
+ req(input$geno)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
 
55
+ g <- read_csv(input$geno$datapath)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
 
57
+ # Remove position row if exists
58
+ if(any(!g[1,-1] %in% c(0,1,2,-1))) {
59
+ g <- g[-1,]
60
+ }
61
+
62
+ # Replace -1 with NA
63
+ g[,-1] <- lapply(g[,-1], function(x){
64
+ x[x == -1] <- NA
65
+ as.numeric(x)
66
+ })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
 
68
+ g
 
 
 
 
 
 
 
 
 
 
 
 
69
  })
70
+
71
+ # -------- Load Phenotype -------- #
72
+ pheno <- reactive({
73
+ req(input$pheno)
74
+ read_csv(input$pheno$datapath)
75
  })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76
 
77
+ # Update trait dropdown
78
+ observe({
79
+ df <- pheno()
80
+ updateSelectInput(session,"trait",
81
+ choices=colnames(df)[-1])
82
+ })
 
 
 
 
 
 
 
83
 
84
+ # -------- Create Cross -------- #
85
+ cross_obj <- reactive({
 
 
 
 
 
 
 
 
 
 
 
86
 
87
+ g <- geno_clean()
88
+ p <- pheno()
 
 
 
 
 
 
89
 
90
+ data <- inner_join(p, g, by="id")
 
 
 
 
 
 
 
91
 
92
+ write.csv(data, "temp.csv", row.names=FALSE)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
 
94
+ cross <- read.cross(
95
+ format="csv",
96
+ file="temp.csv",
97
+ genotypes=c("0","1","2"),
98
+ na.strings="NA"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
100
 
101
+ cross <- calc.genoprob(cross, step=1)
102
+ cross <- fill.geno(cross, method="argmax")
 
 
103
 
104
+ cross
 
105
  })
106
 
107
+ # -------- Segregation Filter -------- #
108
+ seg_filter <- function(cross){
 
 
 
 
 
 
109
 
110
+ geno <- pull.geno(cross)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
111
 
112
+ keep <- apply(geno, 1, function(x){
113
+ tab <- table(x)
114
+ if(length(tab) < 2) return(FALSE)
115
+ chisq.test(tab)$p.value > 0.05
116
+ })
117
+
118
+ cross[keep,]
119
+ }
120
+
121
+ # -------- QTL Analysis -------- #
122
+ result <- eventReactive(input$run, {
 
 
 
 
 
 
 
 
 
 
 
 
123
 
124
+ cross <- cross_obj()
125
+ cross <- seg_filter(cross)
126
+
127
+ method <- switch(input$model,
128
+ "EM"="em",
129
+ "HK"="hk",
130
+ "IMP"="imp",
131
+ "CIM"="hk",
132
+ "STEPWISE"="hk")
133
+
134
+ if(input$model == "CIM"){
135
+ res <- cim(cross, pheno.col=input$trait)
136
+ } else if(input$model == "STEPWISE"){
137
+ res <- stepwiseqtl(cross, pheno.col=input$trait)
138
  } else {
139
+ res <- scanone(cross, pheno.col=input$trait, method=method)
 
140
  }
 
141
 
142
+ perm <- scanone(cross, pheno.col=input$trait,
143
+ method=method, n.perm=input$perm)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
144
 
145
+ list(res=res, perm=perm)
 
 
 
 
 
 
 
 
 
 
 
146
  })
147
 
148
+ # -------- LOD Plot -------- #
149
+ output$lod <- renderPlot({
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
150
 
151
+ res <- result()$res
152
+ perm <- result()$perm
153
+
154
+ if(!("scanone" %in% class(res))) return(NULL)
155
+
156
+ thr <- summary(perm, alpha=0.05)
157
+
158
+ df <- as.data.frame(res)
159
+
160
+ ggplot(df, aes(pos, lod, color=factor(chr))) +
161
+ geom_line(size=1) +
162
+ geom_hline(yintercept=thr,
163
+ linetype="dashed", color="red") +
164
+ labs(title="LOD Plot",
165
+ x="Position", y="LOD") +
166
+ theme_minimal()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
167
  })
168
 
169
+ # -------- Manhattan Plot -------- #
170
+ output$manhattan <- renderPlot({
171
+
172
+ res <- result()$res
173
+ if(!("scanone" %in% class(res))) return(NULL)
174
+
175
+ df <- as.data.frame(res)
176
+ df$chr <- as.factor(df$chr)
177
+
178
+ df <- df %>%
179
+ group_by(chr) %>%
180
+ mutate(chr_len=max(pos)) %>%
181
+ ungroup() %>%
182
+ mutate(tot=cumsum(chr_len)-chr_len) %>%
183
+ mutate(BPcum=pos+tot)
184
+
185
+ axis_set <- df %>%
186
+ group_by(chr) %>%
187
+ summarise(center=mean(BPcum))
188
+
189
+ ggplot(df, aes(BPcum, lod, color=chr)) +
190
+ geom_point(size=2) +
191
+ scale_x_continuous(label=axis_set$chr,
192
+ breaks=axis_set$center) +
193
+ labs(title="Manhattan Plot",
194
+ x="Chromosome", y="LOD") +
195
+ theme_minimal() +
196
+ theme(legend.position="none")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
197
  })
198
 
199
+ # -------- QTL Chromosome Map -------- #
200
+ output$qtlMap <- renderPlot({
 
 
 
201
 
202
+ res <- result()$res
203
+ if(!("scanone" %in% class(res))) return(NULL)
 
 
 
 
204
 
205
+ df <- as.data.frame(res)
 
 
206
 
207
+ df <- df %>%
208
+ group_by(chr) %>%
209
+ mutate(pos_norm = pos/max(pos)) %>%
210
+ ungroup()
211
 
212
+ ggplot(df, aes(x=factor(chr), y=pos_norm)) +
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
213
 
214
+ geom_segment(aes(x=factor(chr),
215
+ xend=factor(chr),
216
+ y=0, yend=1),
217
+ size=5, color="cyan3") +
218
 
219
+ geom_point(aes(color=lod),
220
+ size=3) +
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
221
 
222
+ coord_flip() +
223
+
224
+ scale_color_gradient(low="blue", high="red") +
225
+
226
+ labs(title="Chromosome QTL Map",
227
+ x="Chromosome",
228
+ y="Relative Position") +
229
+
230
+ theme_minimal() +
231
+ theme(panel.grid=element_blank())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
232
  })
233
 
234
+ # -------- Peaks -------- #
235
+ output$peaks <- renderDT({
236
+
237
+ res <- result()$res
238
+
239
+ if("scanone" %in% class(res)){
240
+ datatable(summary(res))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
241
  } else {
242
+ datatable(data.frame(Result=capture.output(print(res))))
243
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
244
  })
245
+
246
+ # -------- Download -------- #
247
+ output$download <- downloadHandler(
248
+ filename=function() "QTL_results.csv",
249
+ content=function(file){
250
+ res <- result()$res
251
+ write.csv(as.data.frame(res), file)
252
+ }
253
+ )
254
  }
255
 
256
+ # ---------------- RUN ---------------- #
257
+ shinyApp(ui, server)