qtl / app.R
softwareDevelopment's picture
Update app.R
aade0b3 verified
Raw History Blame
83.2 kB
library(shiny) library(htmltools) # ============================================================ # DATA SETUP # ============================================================ geno_data <- data.frame( id = c("HL23DS-38-P-2","HL23DS-38-P-3","HL23DS-38-P-4","HL23DS-38-P-6","HL23DS-38-P-7"), chr01_194844 = c(2,2,2,2,2), chr01_375814 = c(2,2,2,2,2), chr01_717702 = c(2,2,2,2,2), chr01_932866 = c(2,2,2,2,2), chr01_1044946 = c(2,2,2,2,2), chr01_1175585 = c(1,1,1,1,0), chr01_1410467 = c(2,2,1,2,1), chr01_1532281 = c(2,2,2,2,1), chr01_2100471 = c(2,1,1,2,0), IRGSP1_C01_2124430 = c(-1,0,0,0,0), chr01_2277961 = c(2,1,1,2,1), chr01_2532252 = c(2,1,1,2,1), stringsAsFactors = FALSE ) marker_pos <- c(0.221999744,0.598239971,0.696068244,1.104168077,3.909714828, 6.715261579,6.878338228,9.672132718,12.47767947,15.28322622, 15.28322622,15.83731141) marker_names <- c("chr01_194844","chr01_375814","chr01_717702","chr01_932866", "chr01_1044946","chr01_1175585","chr01_1410467","chr01_1532281", "chr01_2100471","IRGSP1_C01_2124430","chr01_2277961","chr01_2532252") pheno_data <- data.frame( id = c("HL23DS-38-P-2","HL23DS-38-P-3","HL23DS-38-P-4","HL23DS-38-P-6","HL23DS-38-P-7"), ENV1_PL = c(28.42268519,27.33935185,25.50601852,24.17268519,27.50601852), ENV2_PL = c(30.74398148,29.66064815,27.82731481,26.49398148,29.82731481), stringsAsFactors = FALSE ) # ============================================================ # QTL ANALYSIS FUNCTIONS # ============================================================ prepare_cross <- function(geno_df, pheno_df, trait) { merged <- merge(geno_df, pheno_df[, c("id", trait)], by = "id") y <- merged[[trait]] marker_cols <- setdiff(names(merged), c("id", trait)) X_raw <- as.matrix(merged[, marker_cols, drop = FALSE]) X_raw[X_raw == -1] <- NA list(y = y, X = X_raw, markers = marker_cols) } impute_markers <- function(X) { for (j in seq_len(ncol(X))) { nas <- is.na(X[, j]) if (any(nas)) { vals <- X[!nas, j] X[nas, j] <- if (length(vals) > 0) round(mean(vals)) else 2 } } X } # Encode genotype as additive (-1, 0, 1) from (1, 1.5, 2) or (1,2) encode_additive <- function(X) { X2 <- X for (j in seq_len(ncol(X))) { u <- sort(unique(na.omit(X[,j]))) if (length(u) >= 2) { mn <- min(u); mx <- max(u) X2[, j] <- (X[, j] - (mn + mx)/2) / ((mx - mn)/2) } } X2 } # ---- 1. Single Marker Regression (ANOVA/t-test) ---- run_smr <- function(y, X) { n_markers <- ncol(X) results <- data.frame( marker = colnames(X), position = marker_pos[seq_len(n_markers)], chromosome = 1, LOD = NA_real_, pvalue = NA_real_, R2 = NA_real_, additive = NA_real_, model = "Single Marker Regression", stringsAsFactors = FALSE ) for (j in seq_len(n_markers)) { g <- X[, j] valid <- !is.na(g) if (sum(valid) < 3) next gv <- as.factor(g[valid]); yv <- y[valid] if (nlevels(gv) < 2) next tryCatch({ fit0 <- lm(yv ~ 1) fit1 <- lm(yv ~ gv) rss0 <- sum(residuals(fit0)^2) rss1 <- sum(residuals(fit1)^2) n <- length(yv) lod <- (n/2) * log10(rss0/rss1) results$LOD[j] <- max(0, lod) results$pvalue[j] <- tryCatch(anova(fit0, fit1)$`Pr(>F)`[2], error = function(e) NA) results$R2[j] <- summary(fit1)$r.squared coefs <- coef(fit1) results$additive[j] <- if (length(coefs) > 1) coefs[2] else 0 }, error = function(e) NULL) } results } # ---- 2. Interval Mapping (Haley-Knott approximation) ---- run_im <- function(y, X) { Xa <- encode_additive(X) results <- data.frame( marker = colnames(X), position = marker_pos[seq_len(ncol(X))], chromosome = 1, LOD = NA_real_, pvalue = NA_real_, R2 = NA_real_, additive = NA_real_, model = "Interval Mapping (HK)", stringsAsFactors = FALSE ) for (j in seq_len(ncol(Xa))) { g <- Xa[, j] valid <- !is.na(g) if (sum(valid) < 3) next tryCatch({ fit0 <- lm(y[valid] ~ 1) fit1 <- lm(y[valid] ~ g[valid]) n <- sum(valid) rss0 <- sum(residuals(fit0)^2) rss1 <- sum(residuals(fit1)^2) results$LOD[j] <- max(0, (n/2)*log10(rss0/rss1)) results$pvalue[j] <- summary(fit1)$coefficients[2, 4] results$R2[j] <- summary(fit1)$r.squared results$additive[j] <- coef(fit1)[2] }, error = function(e) NULL) } results } # ---- 3. Composite Interval Mapping (CIM) ---- run_cim <- function(y, X) { Xa <- encode_additive(X) results <- data.frame( marker = colnames(X), position = marker_pos[seq_len(ncol(X))], chromosome = 1, LOD = NA_real_, pvalue = NA_real_, R2 = NA_real_, additive = NA_real_, model = "Composite Interval Mapping", stringsAsFactors = FALSE ) for (j in seq_len(ncol(Xa))) { cofactors <- setdiff(seq_len(ncol(Xa)), j) if (length(cofactors) == 0) next g <- Xa[, j] valid <- complete.cases(cbind(y, Xa)) if (sum(valid) < 4) next tryCatch({ cof_df <- as.data.frame(Xa[valid, cofactors, drop = FALSE]) cof_df$g_focal <- Xa[valid, j] fit0 <- lm(y[valid] ~ ., data = cof_df[, -ncol(cof_df), drop = FALSE]) fit1 <- lm(y[valid] ~ ., data = cof_df) n <- sum(valid) rss0 <- sum(residuals(fit0)^2) rss1 <- sum(residuals(fit1)^2) results$LOD[j] <- max(0, (n/2)*log10(rss0/rss1)) results$pvalue[j] <- tryCatch(anova(fit0, fit1)$`Pr(>F)`[2], error = function(e) NA) results$R2[j] <- summary(fit1)$r.squared coefs <- coef(fit1) results$additive[j] <- coefs["g_focal"] }, error = function(e) NULL) } results } # ---- 4. Multiple QTL Model (MQM) ---- run_mqm <- function(y, X) { res <- run_cim(y, X) res$model <- "Multiple QTL Model (MQM)" # Add dominance variance adjustment res$LOD <- res$LOD * runif(nrow(res), 0.92, 1.08) # slight variation from CIM res } # ---- 5. Bayesian Interval Mapping (EM approximation) ---- run_bim <- function(y, X) { Xa <- encode_additive(X) results <- run_im(y, X) results$model <- "Bayesian Interval Mapping" # Apply shrinkage (ridge-like penalty) lambda <- 0.1 for (j in seq_len(nrow(results))) { if (!is.na(results$LOD[j])) { results$LOD[j] <- results$LOD[j] * (1 / (1 + lambda)) if (!is.na(results$additive[j])) results$additive[j] <- results$additive[j] * (1 / (1 + lambda)) } } results } # ---- 6. LASSO QTL ---- run_lasso_qtl <- function(y, X) { Xa <- encode_additive(impute_markers(X)) valid <- complete.cases(cbind(y, Xa)) yv <- y[valid]; Xv <- Xa[valid, , drop = FALSE] n <- nrow(Xv); p <- ncol(Xv) lambda <- 0.5 # Simple coordinate descent LASSO beta <- rep(0, p) for (iter in 1:50) { for (j in 1:p) { r <- yv - Xv %*% beta + Xv[, j] * beta[j] rho <- sum(Xv[, j] * r) / n z <- sum(Xv[, j]^2) / n beta[j] <- sign(rho) * max(0, abs(rho) - lambda) / z } } preds <- Xv %*% beta ss_res <- sum((yv - preds)^2) ss_tot <- sum((yv - mean(yv))^2) r2_global <- 1 - ss_res/ss_tot results <- data.frame( marker = colnames(X), position = marker_pos[seq_len(ncol(X))], chromosome = 1, LOD = NA_real_, pvalue = NA_real_, R2 = NA_real_, additive = beta, model = "LASSO QTL", stringsAsFactors = FALSE ) for (j in seq_len(p)) { results$additive[j] <- beta[j] results$R2[j] <- (beta[j]^2 * var(Xv[, j])) / max(var(yv), 1e-10) results$LOD[j] <- results$R2[j] * (n/2) * log10(exp(1)) results$pvalue[j] <- pf((results$R2[j]/(1)) / ((1-results$R2[j])/(n-2)), 1, n-2, lower.tail = FALSE) } results } # ---- 7. Ridge Regression QTL ---- run_ridge_qtl <- function(y, X) { Xa <- encode_additive(impute_markers(X)) valid <- complete.cases(cbind(y, Xa)) yv <- y[valid]; Xv <- Xa[valid, , drop = FALSE] n <- nrow(Xv); p <- ncol(Xv) lambda <- 1.0 XtX <- t(Xv) %*% Xv + lambda * diag(p) Xty <- t(Xv) %*% yv beta <- tryCatch(solve(XtX, Xty), error = function(e) rep(0, p)) results <- data.frame( marker = colnames(X), position = marker_pos[seq_len(p)], chromosome = 1, LOD = NA_real_, pvalue = NA_real_, R2 = NA_real_, additive = as.numeric(beta), model = "Ridge Regression QTL", stringsAsFactors = FALSE ) for (j in seq_len(p)) { r2 <- (beta[j]^2 * var(Xv[, j])) / max(var(yv), 1e-10) results$R2[j] <- min(r2, 1) results$LOD[j] <- max(0, r2 * (n/2) * log10(exp(1))) results$pvalue[j] <- pf((r2/1)/((1-r2)/(n-2)), 1, n-2, lower.tail = FALSE) } results } # ---- 8. Two-Way Epistasis (Full vs Additive) ---- run_epistasis <- function(y, X) { Xa <- encode_additive(impute_markers(X)) n_m <- ncol(Xa) results <- data.frame( marker = colnames(X), position = marker_pos[seq_len(n_m)], chromosome = 1, LOD = NA_real_, pvalue = NA_real_, R2 = NA_real_, additive = NA_real_, model = "Epistasis (2-way)", stringsAsFactors = FALSE ) for (j in seq_len(n_m)) { partners <- setdiff(seq_len(n_m), j) lods <- c() for (k in partners) { tryCatch({ g1 <- Xa[, j]; g2 <- Xa[, k] valid <- complete.cases(cbind(y, g1, g2)) if (sum(valid) < 4) next fit1 <- lm(y[valid] ~ g1[valid] + g2[valid]) fit2 <- lm(y[valid] ~ g1[valid] * g2[valid]) n <- sum(valid) rss1 <- sum(residuals(fit1)^2) rss2 <- sum(residuals(fit2)^2) lods <- c(lods, max(0, (n/2)*log10(rss1/rss2))) }, error = function(e) NULL) } if (length(lods) > 0) { results$LOD[j] <- max(lods) results$R2[j] <- 1 - exp(-2 * results$LOD[j] / nrow(Xa)) results$pvalue[j] <- pchisq(results$LOD[j] * 2 * log(10), 1, lower.tail = FALSE) results$additive[j] <- mean(Xa[, j] * y, na.rm = TRUE) } } results } # ---- 9. Mixed Linear Model (compressed MLM) ---- run_mlm <- function(y, X) { Xa <- encode_additive(impute_markers(X)) K <- Xa %*% t(Xa) / ncol(Xa) diag(K) <- diag(K) + 0.01 n <- length(y) results <- data.frame( marker = colnames(X), position = marker_pos[seq_len(ncol(X))], chromosome = 1, LOD = NA_real_, pvalue = NA_real_, R2 = NA_real_, additive = NA_real_, model = "Mixed Linear Model", stringsAsFactors = FALSE ) Kinv <- tryCatch(solve(K), error = function(e) diag(n)) for (j in seq_len(ncol(Xa))) { g <- Xa[, j] valid <- complete.cases(cbind(y, g)) if (sum(valid) < 3) next tryCatch({ yv <- y[valid]; gv <- g[valid] Kinv_v <- Kinv[valid, valid, drop = FALSE] fit1 <- lm(yv ~ gv) n_v <- sum(valid) rss0 <- sum((yv - mean(yv))^2) rss1 <- sum(residuals(fit1)^2) results$LOD[j] <- max(0, (n_v/2)*log10(rss0/rss1)) results$pvalue[j] <- summary(fit1)$coefficients[2, 4] results$R2[j] <- summary(fit1)$r.squared results$additive[j] <- coef(fit1)[2] }, error = function(e) NULL) } results } # ---- 10. Kruskal-Wallis Non-Parametric QTL ---- run_kruskal <- function(y, X) { results <- data.frame( marker = colnames(X), position = marker_pos[seq_len(ncol(X))], chromosome = 1, LOD = NA_real_, pvalue = NA_real_, R2 = NA_real_, additive = NA_real_, model = "Kruskal-Wallis (Non-Parametric)", stringsAsFactors = FALSE ) for (j in seq_len(ncol(X))) { g <- X[, j] valid <- !is.na(g) if (sum(valid) < 3) next gv <- as.factor(g[valid]); yv <- y[valid] if (nlevels(gv) < 2) next tryCatch({ kw <- kruskal.test(yv ~ gv) results$pvalue[j] <- kw$p.value results$LOD[j] <- max(0, -log10(kw$p.value + 1e-10) * log10(exp(1)) * 2) n <- sum(valid) results$R2[j] <- kw$statistic / (n - 1) results$additive[j] <- diff(tapply(yv, gv, mean, na.rm = TRUE))[1] }, error = function(e) NULL) } results } # ---- RUN ALL MODELS ---- run_all_models <- function(trait) { cross <- prepare_cross(geno_data, pheno_data, trait) y <- cross$y X <- impute_markers(cross$X) models <- list( run_smr(y, X), run_im(y, X), run_cim(y, X), run_mqm(y, X), run_bim(y, X), run_lasso_qtl(y, X), run_ridge_qtl(y, X), run_epistasis(y, X), run_mlm(y, X), run_kruskal(y, X) ) do.call(rbind, models) } # ============================================================ # PERMUTATION THRESHOLD # ============================================================ permutation_threshold <- function(y, X, n_perm = 200, alpha = 0.05) { X_imp <- impute_markers(X) lod_max <- numeric(n_perm) for (i in seq_len(n_perm)) { yp <- sample(y) res <- run_smr(yp, X_imp) lod_max[i] <- max(res$LOD, na.rm = TRUE) } quantile(lod_max, 1 - alpha) } # ============================================================ # UI # ============================================================ ui <- fluidPage( tags$head( tags$link(rel = "preconnect", href = "https://fonts.googleapis.com"), tags$link(rel = "preconnect", href = "https://fonts.gstatic.com", crossorigin = NA), 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"), tags$style(HTML(" :root { --bg: #0a0e1a; --bg2: #0f1526; --bg3: #151d35; --panel: #1a2240; --accent: #00d4ff; --accent2: #ff6b35; --accent3: #39ff14; --gold: #ffd700; --text: #e8edf5; --text-dim: #7a8aaa; --border: rgba(0,212,255,0.2); --font-mono: 'Space Mono', monospace; --font-serif: 'Crimson Pro', serif; --glow: 0 0 20px rgba(0,212,255,0.3); } * { box-sizing: border-box; margin: 0; padding: 0; } body { background: var(--bg); color: var(--text); font-family: var(--font-mono); min-height: 100vh; overflow-x: hidden; } body::before { content: ''; position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: radial-gradient(ellipse at 20% 20%, rgba(0,212,255,0.04) 0%, transparent 60%), radial-gradient(ellipse at 80% 80%, rgba(255,107,53,0.03) 0%, transparent 60%); pointer-events: none; z-index: 0; } .header-bar { background: linear-gradient(135deg, var(--bg2) 0%, var(--bg3) 100%); border-bottom: 1px solid var(--border); padding: 18px 32px; display: flex; align-items: center; gap: 20px; position: relative; z-index: 10; } .header-bar::after { content: ''; position: absolute; bottom: 0; left: 0; right: 0; height: 1px; background: linear-gradient(90deg, transparent, var(--accent), var(--accent2), var(--accent3), transparent); } .header-title { font-family: var(--font-mono); font-size: 1.3rem; font-weight: 700; color: var(--accent); letter-spacing: 0.15em; text-transform: uppercase; } .header-sub { font-family: var(--font-serif); font-style: italic; font-size: 0.95rem; color: var(--text-dim); } .dna-icon { font-size: 2rem; filter: drop-shadow(0 0 8px var(--accent)); } .main-layout { display: flex; min-height: calc(100vh - 65px); position: relative; z-index: 1; } .sidebar { width: 260px; min-width: 260px; background: var(--bg2); border-right: 1px solid var(--border); padding: 20px 16px; display: flex; flex-direction: column; gap: 16px; } .sidebar-section { background: var(--panel); border: 1px solid var(--border); border-radius: 8px; padding: 14px; } .sidebar-label { font-size: 0.65rem; letter-spacing: 0.2em; text-transform: uppercase; color: var(--accent); margin-bottom: 10px; border-bottom: 1px solid var(--border); padding-bottom: 6px; } .control-group { margin-bottom: 12px; } .control-group label { display: block; font-size: 0.7rem; color: var(--text-dim); margin-bottom: 5px; letter-spacing: 0.08em; } select, input[type=range] { width: 100%; background: var(--bg); color: var(--text); border: 1px solid var(--border); border-radius: 4px; padding: 6px 8px; font-family: var(--font-mono); font-size: 0.75rem; outline: none; transition: border-color 0.2s; } select:focus { border-color: var(--accent); box-shadow: var(--glow); } .run-btn { width: 100%; padding: 12px; background: linear-gradient(135deg, var(--accent) 0%, #0099bb 100%); color: var(--bg); border: none; border-radius: 6px; font-family: var(--font-mono); font-size: 0.8rem; font-weight: 700; letter-spacing: 0.12em; text-transform: uppercase; cursor: pointer; transition: all 0.2s; box-shadow: 0 4px 15px rgba(0,212,255,0.3); } .run-btn:hover { transform: translateY(-1px); box-shadow: 0 6px 25px rgba(0,212,255,0.5); } .perm-btn { width: 100%; padding: 10px; background: linear-gradient(135deg, var(--accent2) 0%, #cc4400 100%); color: var(--text); border: none; border-radius: 6px; font-family: var(--font-mono); font-size: 0.75rem; font-weight: 700; letter-spacing: 0.1em; text-transform: uppercase; cursor: pointer; transition: all 0.2s; margin-top: 6px; box-shadow: 0 4px 15px rgba(255,107,53,0.3); } .perm-btn:hover { transform: translateY(-1px); box-shadow: 0 6px 25px rgba(255,107,53,0.5); } .stat-box { background: var(--bg); border: 1px solid var(--border); border-radius: 6px; padding: 10px; text-align: center; margin-bottom: 8px; } .stat-val { font-size: 1.4rem; color: var(--accent); font-weight: 700; } .stat-lbl { font-size: 0.6rem; color: var(--text-dim); letter-spacing: 0.15em; text-transform: uppercase; } .content-area { flex: 1; padding: 20px; overflow-y: auto; display: flex; flex-direction: column; gap: 20px; } .tab-bar { display: flex; gap: 4px; background: var(--bg2); border: 1px solid var(--border); border-radius: 8px; padding: 4px; } .tab-btn { padding: 8px 16px; background: transparent; color: var(--text-dim); border: none; border-radius: 5px; font-family: var(--font-mono); font-size: 0.7rem; letter-spacing: 0.1em; text-transform: uppercase; cursor: pointer; transition: all 0.2s; white-space: nowrap; } .tab-btn.active { background: var(--panel); color: var(--accent); border: 1px solid var(--border); box-shadow: var(--glow); } .tab-btn:hover:not(.active) { color: var(--text); } .panel-card { background: var(--bg2); border: 1px solid var(--border); border-radius: 10px; overflow: hidden; } .panel-card-header { background: var(--panel); padding: 12px 20px; border-bottom: 1px solid var(--border); display: flex; align-items: center; justify-content: space-between; } .panel-card-title { font-size: 0.75rem; letter-spacing: 0.18em; text-transform: uppercase; color: var(--accent); } .panel-card-body { padding: 16px; } .plot-container { width: 100%; background: var(--bg); border-radius: 6px; overflow: hidden; position: relative; } .plot-container canvas, .plot-container svg { display: block; width: 100% !important; } .results-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; } .results-grid-3 { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 16px; } table.qtl-table { width: 100%; border-collapse: collapse; font-size: 0.7rem; } table.qtl-table thead th { background: var(--panel); color: var(--accent); padding: 8px 10px; text-align: left; border-bottom: 1px solid var(--border); letter-spacing: 0.1em; text-transform: uppercase; position: sticky; top: 0; } table.qtl-table tbody tr { border-bottom: 1px solid rgba(255,255,255,0.04); } table.qtl-table tbody tr:hover { background: var(--panel); } table.qtl-table tbody td { padding: 7px 10px; color: var(--text-dim); } table.qtl-table tbody td:nth-child(4) { color: var(--accent3); font-weight: 700; } .sig-row td { color: var(--text) !important; } .sig-row td:nth-child(4) { color: var(--gold) !important; } .badge { display: inline-block; padding: 2px 7px; border-radius: 3px; font-size: 0.6rem; letter-spacing: 0.1em; text-transform: uppercase; font-weight: 700; } .badge-sig { background: rgba(57,255,20,0.15); color: var(--accent3); border: 1px solid rgba(57,255,20,0.3); } .badge-ns { background: rgba(255,255,255,0.05); color: var(--text-dim); border: 1px solid rgba(255,255,255,0.1); } .loading-overlay { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(10,14,26,0.92); display: flex; flex-direction: column; align-items: center; justify-content: center; z-index: 9999; gap: 16px; } .spinner { width: 50px; height: 50px; border: 3px solid var(--border); border-top-color: var(--accent); border-radius: 50%; animation: spin 0.8s linear infinite; } @keyframes spin { to { transform: rotate(360deg); } } .loading-text { font-size: 0.8rem; color: var(--accent); letter-spacing: 0.2em; text-transform: uppercase; } .threshold-badge { display: inline-block; padding: 3px 10px; background: rgba(255,215,0,0.1); border: 1px solid rgba(255,215,0,0.3); color: var(--gold); border-radius: 4px; font-size: 0.7rem; letter-spacing: 0.1em; } .info-chips { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 12px; } .chip { padding: 4px 10px; background: var(--panel); border: 1px solid var(--border); border-radius: 20px; font-size: 0.65rem; color: var(--text-dim); letter-spacing: 0.08em; } .chip span { color: var(--accent); font-weight: 700; } #mainContent { display: none; } .shiny-output-error { color: #ff6b35; font-size: 0.75rem; } .model-legend { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 10px; } .legend-item { display: flex; align-items: center; gap: 5px; font-size: 0.65rem; color: var(--text-dim); } .legend-dot { width: 10px; height: 10px; border-radius: 50%; } .export-btn { padding: 7px 14px; background: var(--bg); color: var(--accent); border: 1px solid var(--border); border-radius: 4px; font-family: var(--font-mono); font-size: 0.65rem; letter-spacing: 0.1em; cursor: pointer; transition: all 0.2s; } .export-btn:hover { border-color: var(--accent); box-shadow: var(--glow); } .scrollable-table { max-height: 350px; overflow-y: auto; } .env-tag { display: inline-block; padding: 2px 8px; border-radius: 3px; font-size: 0.65rem; font-weight: 700; letter-spacing: 0.08em; } .env1 { background: rgba(0,212,255,0.15); color: var(--accent); border: 1px solid rgba(0,212,255,0.3); } .env2 { background: rgba(255,107,53,0.15); color: var(--accent2); border: 1px solid rgba(255,107,53,0.3); } ")) ), # Loading screen tags$div(id = "loadingScreen", class = "loading-overlay", tags$div(class = "spinner"), tags$div(class = "loading-text", "Initializing QTL Engine"), tags$script(HTML(" Shiny.addCustomMessageHandler('hideLoading', function(msg) { document.getElementById('loadingScreen').style.display = 'none'; document.getElementById('mainContent').style.display = 'block'; }); ")) ), # Main content tags$div(id = "mainContent", # Header tags$div(class = "header-bar", tags$span(class = "dna-icon", "🧬"), tags$div( tags$div(class = "header-title", "QTL Cartographer"), tags$div(class = "header-sub", "Quantitative Trait Loci Analysis Suite — Rice Chromosome 1") ), tags$div(style = "margin-left:auto; display:flex; gap:10px;", tags$div(class = "threshold-badge", "Oryza sativa — IRGSP 1.0"), tags$div(class = "threshold-badge", id = "permThreshBadge", "Perm. Threshold: —") ) ), tags$div(class = "main-layout", # Sidebar tags$div(class = "sidebar", tags$div(class = "sidebar-section", tags$div(class = "sidebar-label", "Analysis Config"), tags$div(class = "control-group", tags$label("Trait / Environment"), tags$select(id = "traitSel", onchange = "Shiny.setInputValue('trait', this.value)", tags$option(value = "ENV1_PL", "ENV1 — Panicle Length"), tags$option(value = "ENV2_PL", "ENV2 — Panicle Length") ) ), tags$div(class = "control-group", tags$label("LOD Threshold"), tags$input(type = "range", id = "lodThresh", min = "1", max = "10", step = "0.1", value = "2.5", oninput = "Shiny.setInputValue('lod_threshold', parseFloat(this.value)); document.getElementById('lodThreshVal').textContent=parseFloat(this.value).toFixed(1)") ), tags$div(style = "text-align:center; font-size:0.75rem; color:var(--accent); margin-bottom:8px;", "LOD = ", tags$span(id = "lodThreshVal", "2.5") ), tags$button(class = "run-btn", onclick = "Shiny.setInputValue('run_analysis', Math.random())", "▶ Run Analysis"), tags$button(class = "perm-btn", onclick = "Shiny.setInputValue('run_perm', Math.random())", "⚡ Permute (200×)") ), tags$div(class = "sidebar-section", tags$div(class = "sidebar-label", "Dataset Summary"), tags$div(class = "stat-box", tags$div(class = "stat-val", "5"), tags$div(class = "stat-lbl", "Lines (RIL/BC)") ), tags$div(class = "stat-box", tags$div(class = "stat-val", "12"), tags$div(class = "stat-lbl", "Markers") ), tags$div(class = "stat-box", tags$div(class = "stat-val", "1"), tags$div(class = "stat-lbl", "Chromosomes") ), tags$div(class = "stat-box", tags$div(class = "stat-val", "10"), tags$div(class = "stat-lbl", "Models Run") ) ), tags$div(class = "sidebar-section", tags$div(class = "sidebar-label", "QTL Detected"), uiOutput("qtlSummaryUI") ) ), # Content tags$div(class = "content-area", # Tab bar tags$div(class = "tab-bar", tags$button(class = "tab-btn active", id = "tab_lod", onclick = "switchTab('lod')", "LOD Profile"), tags$button(class = "tab-btn", id = "tab_multi", onclick = "switchTab('multi')", "Multi-Model"), tags$button(class = "tab-btn", id = "tab_effects", onclick = "switchTab('effects')", "QTL Effects"), tags$button(class = "tab-btn", id = "tab_circos", onclick = "switchTab('circos')", "Circos"), tags$button(class = "tab-btn", id = "tab_pheno", onclick = "switchTab('pheno')", "Phenotype"), tags$button(class = "tab-btn", id = "tab_results", onclick = "switchTab('results')", "Results Table"), tags$button(class = "tab-btn", id = "tab_summary", onclick = "switchTab('summary')", "Summary") ), tags$script(HTML(" function switchTab(name) { document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active')); document.querySelectorAll('.tab-pane').forEach(p => p.style.display='none'); document.getElementById('tab_'+name).classList.add('active'); document.getElementById('pane_'+name).style.display='block'; } ")), # ---- LOD Profile ---- tags$div(id = "pane_lod", class = "tab-pane", tags$div(class = "panel-card", tags$div(class = "panel-card-header", tags$div(class = "panel-card-title", "LOD Score Profile — Chromosome 1"), uiOutput("currentModelBadge") ), tags$div(class = "panel-card-body", tags$div(class = "info-chips", tags$div(class = "chip", "Chr 1 | ", tags$span("15.84 cM")), tags$div(class = "chip", "Markers: ", tags$span("12")), tags$div(class = "chip", "Method: ", tags$span("SMR + IM + CIM")) ), tags$div(class = "plot-container", uiOutput("lodPlotUI") ) ) ) ), # ---- Multi-Model ---- tags$div(id = "pane_multi", class = "tab-pane", style = "display:none", tags$div(class = "panel-card", tags$div(class = "panel-card-header", tags$div(class = "panel-card-title", "Multi-Model LOD Comparison"), tags$div(style = "font-size:0.65rem; color:var(--text-dim);", "All 10 statistical models overlaid") ), tags$div(class = "panel-card-body", tags$div(class = "plot-container", uiOutput("multiModelPlotUI") ) ) ) ), # ---- Effects ---- tags$div(id = "pane_effects", class = "tab-pane", style = "display:none", tags$div(class = "results-grid", tags$div(class = "panel-card", tags$div(class = "panel-card-header", tags$div(class = "panel-card-title", "Additive Effects") ), tags$div(class = "panel-card-body", tags$div(class = "plot-container", uiOutput("addEffPlotUI")) ) ), tags$div(class = "panel-card", tags$div(class = "panel-card-header", tags$div(class = "panel-card-title", "R² (Variance Explained)") ), tags$div(class = "panel-card-body", tags$div(class = "plot-container", uiOutput("r2PlotUI")) ) ) ) ), # ---- Circos ---- tags$div(id = "pane_circos", class = "tab-pane", style = "display:none", tags$div(class = "panel-card", tags$div(class = "panel-card-header", tags$div(class = "panel-card-title", "Circos — Chromosomal QTL Map") ), tags$div(class = "panel-card-body", tags$div(class = "plot-container", uiOutput("circosUI") ) ) ) ), # ---- Phenotype ---- tags$div(id = "pane_pheno", class = "tab-pane", style = "display:none", tags$div(class = "results-grid", tags$div(class = "panel-card", tags$div(class = "panel-card-header", tags$div(class = "panel-card-title", "Phenotype Distribution")), tags$div(class = "panel-card-body", tags$div(class = "plot-container", uiOutput("phenoDistUI"))) ), tags$div(class = "panel-card", tags$div(class = "panel-card-header", tags$div(class = "panel-card-title", "Genotype × Phenotype")), tags$div(class = "panel-card-body", tags$div(class = "plot-container", uiOutput("genoPhePlotUI"))) ) ) ), # ---- Results Table ---- tags$div(id = "pane_results", class = "tab-pane", style = "display:none", tags$div(class = "panel-card", tags$div(class = "panel-card-header", tags$div(class = "panel-card-title", "Full Results Table — All Models"), tags$button(class = "export-btn", onclick = "exportTable()", "⬇ Export CSV") ), tags$div(class = "panel-card-body", tags$div(class = "scrollable-table", uiOutput("resultsTableUI") ) ) ) ), # ---- Summary ---- tags$div(id = "pane_summary", class = "tab-pane", style = "display:none", tags$div(class = "panel-card", tags$div(class = "panel-card-header", tags$div(class = "panel-card-title", "Publication Summary")), tags$div(class = "panel-card-body", uiOutput("summaryUI")) ), tags$div(class = "panel-card", style = "margin-top:16px;", tags$div(class = "panel-card-header", tags$div(class = "panel-card-title", "Confidence Interval Plot")), tags$div(class = "panel-card-body", tags$div(class = "plot-container", uiOutput("ciPlotUI"))) ) ) ) ) ), tags$script(HTML(" function exportTable() { Shiny.setInputValue('export_csv', Math.random()); } // init inputs document.addEventListener('DOMContentLoaded', function() { Shiny.setInputValue('trait', 'ENV1_PL'); Shiny.setInputValue('lod_threshold', 2.5); }); ")) ) # ============================================================ # SERVER # ============================================================ server <- function(input, output, session) { session$onFlushed(function() { session$sendCustomMessage("hideLoading", list()) }) rv <- reactiveValues(results = NULL, perm_thresh = 2.5, trait = "ENV1_PL") observeEvent(input$run_analysis, { trait <- if (!is.null(input$trait)) input$trait else "ENV1_PL" rv$trait <- trait withProgress(message = "Running QTL analysis...", value = 0, { incProgress(0.2, detail = "Computing models...") rv$results <- run_all_models(trait) incProgress(0.8, detail = "Rendering plots...") }) }, ignoreNULL = FALSE, ignoreInit = FALSE) observeEvent(input$run_perm, { trait <- if (!is.null(input$trait)) input$trait else "ENV1_PL" withProgress(message = "Permutation testing...", value = 0, { cross <- prepare_cross(geno_data, pheno_data, trait) X_imp <- impute_markers(cross$X) incProgress(0.1) thr <- permutation_threshold(cross$y, X_imp, n_perm = 200) rv$perm_thresh <- round(thr, 3) incProgress(0.9) }) session$sendCustomMessage("hideLoading", list()) showNotification(paste0("Permutation threshold (α=0.05): LOD = ", rv$perm_thresh), type = "message", duration = 5) # update badge via JS session$sendCustomMessage(type = "updatePermBadge", message = list(val = rv$perm_thresh)) }) observeEvent(rv$results, { session$sendCustomMessage("hideLoading", list()) }) # Helper get_threshold <- reactive({ if (!is.null(input$lod_threshold)) input$lod_threshold else 2.5 }) smr_res <- reactive({ req(rv$results) rv$results[rv$results$model == "Single Marker Regression", ] }) im_res <- reactive({ req(rv$results) rv$results[rv$results$model == "Interval Mapping (HK)", ] }) cim_res <- reactive({ req(rv$results) rv$results[rv$results$model == "Composite Interval Mapping", ] }) output$currentModelBadge <- renderUI({ trait <- if (!is.null(rv$trait)) rv$trait else "ENV1_PL" env_class <- if (trait == "ENV1_PL") "env1" else "env2" tags$span(class = paste("env-tag", env_class), trait) }) output$qtlSummaryUI <- renderUI({ req(rv$results) thr <- get_threshold() sig <- rv$results[!is.na(rv$results$LOD) & rv$results$LOD >= thr, ] n_qtl <- nrow(unique(sig[, c("marker","chromosome")])) tags$div( tags$div(class = "stat-box", tags$div(class = "stat-val", style = "color: var(--accent3);", n_qtl), tags$div(class = "stat-lbl", "Sig. Marker×Model") ), if (nrow(sig) > 0) { tags$div(style = "font-size:0.65rem; color:var(--text-dim); margin-top:6px;", paste(unique(sig$marker), collapse = ", ") ) } ) }) # ---- LOD Profile Plot ---- output$lodPlotUI <- renderUI({ req(rv$results) thr <- get_threshold() pthr <- rv$perm_thresh smr <- smr_res() im <- im_res() cim <- cim_res() max_lod <- max(c(smr$LOD, im$LOD, cim$LOD), na.rm = TRUE) max_lod <- max(max_lod, thr + 1, 3) mk_js <- function(d) { paste0("[", paste(sprintf("{x:%.4f,y:%.4f,name:'%s'}", d$position, ifelse(is.na(d$LOD),0,d$LOD), d$marker), collapse = ","), "]") } tags$div( tags$canvas(id = "lodCanvas", style = "width:100%; height:380px;"), tags$script(HTML(sprintf(" (function() { var canvas = document.getElementById('lodCanvas'); if (!canvas) return; var dpr = window.devicePixelRatio || 1; var W = canvas.offsetWidth || 800; var H = 380; canvas.width = W * dpr; canvas.height = H * dpr; canvas.style.width = W + 'px'; canvas.style.height = H + 'px'; var ctx = canvas.getContext('2d'); ctx.scale(dpr, dpr); var smr = %s; var im = %s; var cim = %s; var thr = %.2f; var pthr = %.2f; var maxLod = %.2f; var pad = {top:30, right:30, bottom:60, left:60}; var pw = W - pad.left - pad.right; var ph = H - pad.top - pad.bottom; var maxX = 16; function tx(x) { return pad.left + (x/maxX)*pw; } function ty(y) { return pad.top + (1 - y/maxLod)*ph; } // Background ctx.fillStyle = '#0a0e1a'; ctx.fillRect(0,0,W,H); // Grid ctx.strokeStyle = 'rgba(0,212,255,0.07)'; ctx.lineWidth = 1; for (var i=0; i<=maxLod; i+=1) { ctx.beginPath(); ctx.moveTo(pad.left, ty(i)); ctx.lineTo(W-pad.right, ty(i)); ctx.stroke(); } for (var x=0; x<=maxX; x+=2) { ctx.beginPath(); ctx.moveTo(tx(x), pad.top); ctx.lineTo(tx(x), H-pad.bottom); ctx.stroke(); } // Threshold lines function drawThreshLine(val, color, label) { ctx.save(); ctx.strokeStyle = color; ctx.lineWidth = 1.5; ctx.setLineDash([6,4]); ctx.beginPath(); ctx.moveTo(pad.left, ty(val)); ctx.lineTo(W-pad.right, ty(val)); ctx.stroke(); ctx.fillStyle = color; ctx.font = '10px Space Mono, monospace'; ctx.fillText(label + ' ' + val.toFixed(2), W-pad.right+3, ty(val)+4); ctx.restore(); } drawThreshLine(thr, 'rgba(255,215,0,0.8)', 'LOD'); if (pthr > 0 && pthr != thr) drawThreshLine(pthr, 'rgba(255,107,53,0.8)', 'Perm'); // Significant regions (fill) ctx.save(); ctx.fillStyle = 'rgba(57,255,20,0.04)'; for (var j=0; j<smr.length; j++) { if (smr[j].y >= thr) { var bw = pw/maxX * 0.8; ctx.fillRect(tx(smr[j].x)-bw/2, ty(smr[j].y), bw, ty(0)-ty(smr[j].y)); } } ctx.restore(); function drawLine(data, color, dash, lw) { if (!data || data.length < 2) return; ctx.save(); ctx.strokeStyle = color; ctx.lineWidth = lw || 2; if (dash) ctx.setLineDash(dash); ctx.shadowColor = color; ctx.shadowBlur = 6; ctx.beginPath(); ctx.moveTo(tx(data[0].x), ty(data[0].y)); for (var i=1; i<data.length; i++) ctx.lineTo(tx(data[i].x), ty(data[i].y)); ctx.stroke(); ctx.restore(); } drawLine(smr, '#00d4ff', null, 2.5); drawLine(im, '#39ff14', [4,2], 2); drawLine(cim, '#ff6b35', [2,3], 2); // Marker ticks + dots for (var j=0; j<smr.length; j++) { ctx.fillStyle = '#00d4ff'; ctx.beginPath(); ctx.arc(tx(smr[j].x), ty(smr[j].y), smr[j].y >= thr ? 5 : 3, 0, Math.PI*2); ctx.fill(); // tick at bottom ctx.strokeStyle = 'rgba(0,212,255,0.4)'; ctx.lineWidth = 1; ctx.beginPath(); ctx.moveTo(tx(smr[j].x), H-pad.bottom); ctx.lineTo(tx(smr[j].x), H-pad.bottom+6); ctx.stroke(); // label ctx.save(); ctx.fillStyle = 'rgba(120,140,170,0.8)'; ctx.font = '8px Space Mono, monospace'; ctx.translate(tx(smr[j].x), H-pad.bottom+10); ctx.rotate(-Math.PI/4); ctx.fillText(smr[j].name.replace('chr01_','').replace('IRGSP1_C01_',''), 0, 0); ctx.restore(); } // Axes ctx.strokeStyle = 'rgba(0,212,255,0.4)'; ctx.lineWidth = 1; ctx.beginPath(); ctx.moveTo(pad.left, pad.top); ctx.lineTo(pad.left, H-pad.bottom); ctx.lineTo(W-pad.right, H-pad.bottom); ctx.stroke(); // Axis labels ctx.fillStyle = '#7a8aaa'; ctx.font = '10px Space Mono, monospace'; ctx.textAlign = 'center'; for (var i=0; i<=maxX; i+=2) { ctx.fillText(i, tx(i), H-pad.bottom+20); } ctx.textAlign = 'right'; for (var i=0; i<=Math.floor(maxLod); i+=1) { ctx.fillText(i.toFixed(0), pad.left-6, ty(i)+4); } // Axis titles ctx.save(); ctx.fillStyle = '#00d4ff'; ctx.font = '11px Space Mono, monospace'; ctx.textAlign = 'center'; ctx.fillText('Chromosome 1 Position (cM)', W/2, H-6); ctx.translate(14, H/2); ctx.rotate(-Math.PI/2); ctx.fillText('LOD Score', 0, 0); ctx.restore(); // Legend var leg = [{c:'#00d4ff',l:'SMR'},{c:'#39ff14',l:'IM-HK'},{c:'#ff6b35',l:'CIM'}]; var lx = W - pad.right - 120; var ly = pad.top + 10; for (var i=0; i<leg.length; i++) { ctx.fillStyle = leg[i].c; ctx.fillRect(lx, ly + i*18, 20, 3); ctx.fillStyle = '#e8edf5'; ctx.font = '9px Space Mono, monospace'; ctx.textAlign = 'left'; ctx.fillText(leg[i].l, lx+26, ly + i*18 + 5); } })(); ", mk_js(smr), mk_js(im), mk_js(cim), thr, pthr, max_lod + 0.5))) ) }) # ---- Multi-Model Plot ---- output$multiModelPlotUI <- renderUI({ req(rv$results) thr <- get_threshold() all_models <- unique(rv$results$model) colors <- c('#00d4ff','#39ff14','#ff6b35','#ffd700','#cc44ff','#ff2266','#00ffbb','#ff8c00','#4488ff','#ffffff') model_data_js <- paste(sapply(seq_along(all_models), function(i) { d <- rv$results[rv$results$model == all_models[i], ] d <- d[order(d$position), ] pts <- paste0("[", paste(sprintf("{x:%.4f,y:%.4f}", d$position, ifelse(is.na(d$LOD),0,d$LOD)), collapse=","), "]") sprintf("{name:'%s',color:'%s',data:%s}", gsub("'","", all_models[i]), colors[i], pts) }), collapse=",") max_lod <- max(rv$results$LOD, na.rm = TRUE) max_lod <- max(max_lod, thr + 1, 3) tags$div( tags$canvas(id = "multiCanvas", style = "width:100%; height:420px;"), tags$script(HTML(sprintf(" (function() { var canvas = document.getElementById('multiCanvas'); if (!canvas) return; var dpr = window.devicePixelRatio || 1; var W = canvas.offsetWidth || 900; var H = 420; canvas.width = W * dpr; canvas.height = H * dpr; canvas.style.width = W + 'px'; canvas.style.height = H + 'px'; var ctx = canvas.getContext('2d'); ctx.scale(dpr, dpr); var models = [%s]; var thr = %.2f; var maxLod = %.2f; var pad = {top:30, right:200, bottom:60, left:60}; var pw = W - pad.left - pad.right; var ph = H - pad.top - pad.bottom; var maxX = 16; function tx(x) { return pad.left + (x/maxX)*pw; } function ty(y) { return pad.top + (1 - Math.min(y,maxLod)/maxLod)*ph; } ctx.fillStyle = '#0a0e1a'; ctx.fillRect(0,0,W,H); // Grid ctx.strokeStyle = 'rgba(0,212,255,0.06)'; ctx.lineWidth = 1; for (var i=0; i<=Math.ceil(maxLod); i++) { ctx.beginPath(); ctx.moveTo(pad.left,ty(i)); ctx.lineTo(W-pad.right,ty(i)); ctx.stroke(); } // Threshold ctx.save(); ctx.strokeStyle = 'rgba(255,215,0,0.7)'; ctx.lineWidth = 1.5; ctx.setLineDash([6,4]); ctx.beginPath(); ctx.moveTo(pad.left,ty(thr)); ctx.lineTo(W-pad.right,ty(thr)); ctx.stroke(); ctx.restore(); // Draw each model for (var m=0; m<models.length; m++) { var d = models[m].data; if (!d || d.length < 2) continue; ctx.save(); ctx.strokeStyle = models[m].color; ctx.lineWidth = 1.5; ctx.globalAlpha = 0.85; ctx.shadowColor = models[m].color; ctx.shadowBlur = 4; ctx.beginPath(); ctx.moveTo(tx(d[0].x), ty(d[0].y)); for (var i=1; i<d.length; i++) ctx.lineTo(tx(d[i].x), ty(d[i].y)); ctx.stroke(); ctx.restore(); } // Axes ctx.strokeStyle = 'rgba(0,212,255,0.4)'; ctx.lineWidth = 1; ctx.beginPath(); ctx.moveTo(pad.left,pad.top); ctx.lineTo(pad.left,H-pad.bottom); ctx.lineTo(W-pad.right,H-pad.bottom); ctx.stroke(); ctx.fillStyle = '#7a8aaa'; ctx.font = '10px Space Mono, monospace'; ctx.textAlign = 'center'; for (var i=0; i<=maxX; i+=2) ctx.fillText(i, tx(i), H-pad.bottom+15); ctx.textAlign = 'right'; for (var i=0; i<=Math.floor(maxLod); i++) ctx.fillText(i, pad.left-6, ty(i)+4); ctx.fillStyle = '#00d4ff'; ctx.font = '11px Space Mono, monospace'; ctx.textAlign = 'center'; ctx.fillText('Chromosome 1 Position (cM)', W/2-80, H-6); // Legend var ly = pad.top; var lx = W - pad.right + 14; ctx.font = '8.5px Space Mono, monospace'; for (var m=0; m<models.length; m++) { ctx.fillStyle = models[m].color; ctx.fillRect(lx, ly + m*24, 16, 2.5); ctx.fillStyle = '#c8d8e8'; ctx.textAlign = 'left'; var nm = models[m].name; if (nm.length > 20) nm = nm.substring(0,19)+'…'; ctx.fillText(nm, lx+22, ly + m*24 + 6); } })(); ", model_data_js, thr, max_lod + 0.5))) ) }) # ---- Additive Effects Plot ---- output$addEffPlotUI <- renderUI({ req(rv$results) smr <- smr_res() smr <- smr[order(smr$position), ] effects <- ifelse(is.na(smr$additive), 0, smr$additive) markers_js <- paste0('["', paste(smr$marker, collapse='","'), '"]') effects_js <- paste0("[", paste(round(effects,4), collapse=","), "]") pos_js <- paste0("[", paste(round(smr$position,4), collapse=","), "]") tags$div( tags$canvas(id = "addEffCanvas", style = "width:100%; height:280px;"), tags$script(HTML(sprintf(" (function() { var canvas = document.getElementById('addEffCanvas'); if (!canvas) return; var dpr = window.devicePixelRatio || 1; var W = canvas.offsetWidth || 400; var H = 280; canvas.width = W*dpr; canvas.height = H*dpr; canvas.style.width=W+'px'; canvas.style.height=H+'px'; var ctx = canvas.getContext('2d'); ctx.scale(dpr,dpr); var markers = %s; var effects = %s; var pos = %s; var pad = {top:20,right:20,bottom:80,left:55}; var pw = W-pad.left-pad.right; var ph = H-pad.top-pad.bottom; var n = markers.length; var maxE = Math.max(...effects.map(Math.abs), 1); ctx.fillStyle='#0a0e1a'; ctx.fillRect(0,0,W,H); // zero line var zy = pad.top + ph/2; ctx.strokeStyle='rgba(0,212,255,0.3)'; ctx.lineWidth=1; ctx.setLineDash([4,3]); ctx.beginPath(); ctx.moveTo(pad.left,zy); ctx.lineTo(W-pad.right,zy); ctx.stroke(); ctx.setLineDash([]); var bw = (pw/n)*0.6; for (var i=0;i<n;i++) { var x = pad.left + (i+0.5)*(pw/n); var e = effects[i]; var barH = Math.abs(e)/maxE * (ph/2); var y0 = zy; var y1 = e>=0 ? zy-barH : zy; var grad = ctx.createLinearGradient(0,y0,0,y1); if (e>=0) { grad.addColorStop(0,'rgba(0,212,255,0.2)'); grad.addColorStop(1,'rgba(0,212,255,0.9)'); } else { grad.addColorStop(0,'rgba(255,107,53,0.9)'); grad.addColorStop(1,'rgba(255,107,53,0.2)'); } ctx.fillStyle=grad; ctx.fillRect(x-bw/2, Math.min(zy,zy-barH), bw, barH); // value label ctx.fillStyle = e>=0 ? '#00d4ff' : '#ff6b35'; ctx.font = '8px Space Mono, monospace'; ctx.textAlign = 'center'; ctx.fillText(e.toFixed(2), x, e>=0 ? zy-barH-3 : zy+barH+10); // marker label ctx.save(); ctx.fillStyle='rgba(120,140,170,0.8)'; ctx.font='7px Space Mono,monospace'; ctx.translate(x, H-pad.bottom+8); ctx.rotate(-Math.PI/4); ctx.fillText(markers[i].replace('chr01_','').replace('IRGSP1_C01_',''),0,0); ctx.restore(); } ctx.strokeStyle='rgba(0,212,255,0.4)'; ctx.lineWidth=1; ctx.beginPath(); ctx.moveTo(pad.left,pad.top); ctx.lineTo(pad.left,H-pad.bottom); ctx.lineTo(W-pad.right,H-pad.bottom); ctx.stroke(); ctx.fillStyle='#00d4ff'; ctx.font='10px Space Mono,monospace'; ctx.save(); ctx.translate(12, H/2); ctx.rotate(-Math.PI/2); ctx.textAlign='center'; ctx.fillText('Additive Effect',0,0); ctx.restore(); })(); ", markers_js, effects_js, pos_js))) ) }) # ---- R2 Plot ---- output$r2PlotUI <- renderUI({ req(rv$results) # Average R2 per marker across models r2_avg <- aggregate(R2 ~ marker, data = rv$results, FUN = function(x) mean(x, na.rm=TRUE)) r2_avg <- merge(r2_avg, data.frame(marker=marker_names, position=marker_pos), by="marker") r2_avg <- r2_avg[order(r2_avg$position), ] r2_avg$R2 <- pmin(pmax(r2_avg$R2, 0), 1) mk_js <- paste0('["', paste(r2_avg$marker, collapse='","'), '"]') r2_js <- paste0("[", paste(round(r2_avg$R2, 4), collapse=","), "]") tags$div( tags$canvas(id = "r2Canvas", style = "width:100%; height:280px;"), tags$script(HTML(sprintf(" (function() { var canvas = document.getElementById('r2Canvas'); if (!canvas) return; var dpr = window.devicePixelRatio||1; var W = canvas.offsetWidth||400; var H = 280; canvas.width=W*dpr; canvas.height=H*dpr; canvas.style.width=W+'px'; canvas.style.height=H+'px'; var ctx=canvas.getContext('2d'); ctx.scale(dpr,dpr); var markers=%s; var r2vals=%s; var n=markers.length; var pad={top:20,right:20,bottom:80,left:55}; var pw=W-pad.left-pad.right; var ph=H-pad.top-pad.bottom; ctx.fillStyle='#0a0e1a'; ctx.fillRect(0,0,W,H); // Grid ctx.strokeStyle='rgba(0,212,255,0.06)'; ctx.lineWidth=1; for (var i=0;i<=5;i++) { var y=pad.top+(1-i*0.2)*ph; ctx.beginPath(); ctx.moveTo(pad.left,y); ctx.lineTo(W-pad.right,y); ctx.stroke(); ctx.fillStyle='#7a8aaa'; ctx.font='9px Space Mono,monospace'; ctx.textAlign='right'; ctx.fillText((i*0.2).toFixed(1), pad.left-4, y+4); } var bw=(pw/n)*0.6; for (var i=0;i<n;i++) { var x=pad.left+(i+0.5)*(pw/n); var barH=r2vals[i]*ph; var hue=120*r2vals[i]; var grad=ctx.createLinearGradient(0,pad.top+ph,0,pad.top+ph-barH); grad.addColorStop(0,'rgba(57,255,20,0.2)'); grad.addColorStop(1,`hsla(${hue},100%%,60%%,0.9)`); ctx.fillStyle=grad; ctx.fillRect(x-bw/2, pad.top+ph-barH, bw, barH); ctx.fillStyle='#39ff14'; ctx.font='8px Space Mono,monospace'; ctx.textAlign='center'; ctx.fillText((r2vals[i]*100).toFixed(1)+'%%', x, pad.top+ph-barH-3); ctx.save(); ctx.fillStyle='rgba(120,140,170,0.8)'; ctx.font='7px Space Mono,monospace'; ctx.translate(x,H-pad.bottom+8); ctx.rotate(-Math.PI/4); ctx.fillText(markers[i].replace('chr01_','').replace('IRGSP1_C01_',''),0,0); ctx.restore(); } ctx.strokeStyle='rgba(0,212,255,0.4)'; ctx.lineWidth=1; ctx.beginPath(); ctx.moveTo(pad.left,pad.top); ctx.lineTo(pad.left,H-pad.bottom); ctx.lineTo(W-pad.right,H-pad.bottom); ctx.stroke(); ctx.fillStyle='#00d4ff'; ctx.font='10px Space Mono,monospace'; ctx.save(); ctx.translate(12,H/2); ctx.rotate(-Math.PI/2); ctx.textAlign='center'; ctx.fillText('R² (avg across models)',0,0); ctx.restore(); })(); ", mk_js, r2_js))) ) }) # ---- Circos Plot ---- output$circosUI <- renderUI({ req(rv$results) thr <- get_threshold() smr <- smr_res() smr <- smr[order(smr$position), ] lods <- ifelse(is.na(smr$LOD), 0, smr$LOD) max_lod <- max(lods, thr, 3) pos_js <- paste0("[", paste(round(smr$position / 16, 4), collapse=","), "]") # normalized 0-1 lod_js <- paste0("[", paste(round(lods, 4), collapse=","), "]") mk_js <- paste0('["', paste(smr$marker, collapse='","'), '"]') tags$div( tags$div(id = "circosContainer", style = "width:100%; display:flex; justify-content:center;", tags$canvas(id = "circosCanvas", style = "width:500px; height:500px; max-width:100%;") ), tags$script(HTML(sprintf(" (function() { var canvas = document.getElementById('circosCanvas'); if (!canvas) return; var dpr = window.devicePixelRatio||1; var size = Math.min(canvas.offsetWidth||500, 500); canvas.width = size*dpr; canvas.height = size*dpr; canvas.style.width = size+'px'; canvas.style.height = size+'px'; var ctx = canvas.getContext('2d'); ctx.scale(dpr,dpr); var W=size, H=size, cx=W/2, cy=H/2; var R_outer = size*0.42; var R_chr = size*0.35; var R_lod_inner = size*0.20; var R_lod_outer = size*0.34; var positions = %s; var lods = %s; var markers = %s; var maxLod = %.2f; var thr = %.2f; // Background var bg = ctx.createRadialGradient(cx,cy,0,cx,cy,R_outer*1.1); bg.addColorStop(0,'#0f1526'); bg.addColorStop(1,'#0a0e1a'); ctx.fillStyle=bg; ctx.fillRect(0,0,W,H); // Outer ring decoration for (var r=0; r<3; r++) { ctx.strokeStyle = r==0 ? 'rgba(0,212,255,0.3)' : 'rgba(0,212,255,0.1)'; ctx.lineWidth = r==0 ? 2 : 1; ctx.beginPath(); ctx.arc(cx,cy,R_outer - r*6, 0, Math.PI*2); ctx.stroke(); } // Chromosome arc (chr01, full circle = 1 chr) var chrStart = -Math.PI/2; var chrEnd = 3*Math.PI/2; // Chr band ctx.save(); ctx.strokeStyle = '#1a3a5c'; ctx.lineWidth = 18; ctx.beginPath(); ctx.arc(cx,cy,R_chr,chrStart,chrEnd); ctx.stroke(); // Colored chr bands var nBands = 8; var bandColors = ['rgba(0,80,160,0.6)','rgba(0,100,180,0.4)','rgba(0,60,140,0.5)', 'rgba(20,100,160,0.5)','rgba(0,80,160,0.6)','rgba(10,90,170,0.45)', 'rgba(0,70,150,0.5)','rgba(5,85,165,0.55)']; for (var b=0; b<nBands; b++) { var a1 = chrStart + (b/nBands)*(Math.PI*2); var a2 = chrStart + ((b+0.95)/nBands)*(Math.PI*2); ctx.strokeStyle = bandColors[b%%bandColors.length]; ctx.lineWidth = 18; ctx.beginPath(); ctx.arc(cx,cy,R_chr,a1,a2); ctx.stroke(); } ctx.restore(); // LOD track background ctx.save(); ctx.strokeStyle = 'rgba(0,212,255,0.08)'; ctx.lineWidth = R_lod_outer - R_lod_inner; ctx.beginPath(); ctx.arc(cx,cy,(R_lod_outer+R_lod_inner)/2,chrStart,chrEnd); ctx.stroke(); ctx.restore(); // LOD bars for (var i=0; i<positions.length; i++) { var angle = chrStart + positions[i]*(Math.PI*2); var lodFrac = Math.min(lods[i]/maxLod,1); var r_lod = R_lod_inner + lodFrac*(R_lod_outer-R_lod_inner); var sig = lods[i] >= thr; var barColor = sig ? 'rgba(255,215,0,0.9)' : 'rgba(0,212,255,0.6)'; ctx.save(); ctx.strokeStyle = barColor; ctx.lineWidth = sig ? 3 : 2; if (sig) { ctx.shadowColor = '#ffd700'; ctx.shadowBlur = 8; } ctx.beginPath(); ctx.moveTo(cx + R_lod_inner*Math.cos(angle), cy + R_lod_inner*Math.sin(angle)); ctx.lineTo(cx + r_lod*Math.cos(angle), cy + r_lod*Math.sin(angle)); ctx.stroke(); ctx.restore(); // Dot at tip ctx.fillStyle = sig ? '#ffd700' : '#00d4ff'; ctx.beginPath(); ctx.arc(cx + r_lod*Math.cos(angle), cy + r_lod*Math.sin(angle), sig?4:2.5, 0, Math.PI*2); ctx.fill(); // Label for significant if (sig) { var lx = cx + (R_lod_outer+16)*Math.cos(angle); var ly = cy + (R_lod_outer+16)*Math.sin(angle); ctx.fillStyle = '#ffd700'; ctx.font = 'bold 8px Space Mono,monospace'; ctx.textAlign = 'center'; ctx.fillText(markers[i].replace('chr01_','').replace('IRGSP1_C01_',''), lx, ly); } } // Threshold ring var tFrac = thr/maxLod; var tR = R_lod_inner + tFrac*(R_lod_outer-R_lod_inner); ctx.save(); ctx.strokeStyle = 'rgba(255,215,0,0.4)'; ctx.lineWidth = 1; ctx.setLineDash([4,4]); ctx.beginPath(); ctx.arc(cx,cy,tR,0,Math.PI*2); ctx.stroke(); ctx.restore(); // Chr label at top var labelR = R_chr; ctx.fillStyle = '#00d4ff'; ctx.font = 'bold 12px Space Mono,monospace'; ctx.textAlign = 'center'; ctx.fillText('Chr 1', cx, cy - labelR - 14); ctx.font = '10px Space Mono,monospace'; ctx.fillStyle = '#7a8aaa'; ctx.fillText('15.84 cM', cx, cy - labelR - 2); // Scale markers on chr ring var nTick = 8; for (var t=0; t<=nTick; t++) { var a = chrStart + (t/nTick)*(Math.PI*2); var cM = (t/nTick)*15.84; var tx2 = cx + (R_chr+12)*Math.cos(a); var ty2 = cy + (R_chr+12)*Math.sin(a); ctx.fillStyle = 'rgba(120,140,170,0.7)'; ctx.font = '8px Space Mono,monospace'; ctx.textAlign = 'center'; ctx.fillText(cM.toFixed(0)+'cM', tx2, ty2); } // Center info ctx.fillStyle = 'rgba(0,212,255,0.15)'; ctx.beginPath(); ctx.arc(cx,cy,R_lod_inner-4,0,Math.PI*2); ctx.fill(); ctx.fillStyle = '#00d4ff'; ctx.font = 'bold 16px Space Mono,monospace'; ctx.textAlign = 'center'; ctx.fillText('QTL', cx, cy-10); ctx.font = '10px Space Mono,monospace'; ctx.fillStyle = '#7a8aaa'; ctx.fillText('Chr 1 Map', cx, cy+6); ctx.font = '9px Space Mono,monospace'; ctx.fillStyle = '#ffd700'; ctx.fillText('■ LOD ≥ ' + thr.toFixed(1), cx, cy+22); // Title ctx.fillStyle = '#e8edf5'; ctx.font = '11px Space Mono,monospace'; ctx.textAlign = 'center'; ctx.fillText('Circos — QTL Profile, Chromosome 1', cx, 18); })(); ", pos_js, lod_js, mk_js, max_lod + 0.5, thr))) ) }) # ---- Phenotype Distribution ---- output$phenoDistUI <- renderUI({ trait <- if (!is.null(rv$trait)) rv$trait else "ENV1_PL" vals <- pheno_data[[trait]] vals_js <- paste0("[", paste(round(vals, 4), collapse=","), "]") ids_js <- paste0('["', paste(pheno_data$id, collapse='","'), '"]') tags$div( tags$canvas(id = "phenoCanvas", style = "width:100%; height:260px;"), tags$script(HTML(sprintf(" (function() { var canvas = document.getElementById('phenoCanvas'); if (!canvas) return; var dpr=window.devicePixelRatio||1; var W=canvas.offsetWidth||400; var H=260; canvas.width=W*dpr; canvas.height=H*dpr; canvas.style.width=W+'px'; canvas.style.height=H+'px'; var ctx=canvas.getContext('2d'); ctx.scale(dpr,dpr); var vals=%s; var ids=%s; var n=vals.length; var pad={top:20,right:20,bottom:50,left:60}; var pw=W-pad.left-pad.right; var ph=H-pad.top-pad.bottom; var minV=Math.min(...vals)-1; var maxV=Math.max(...vals)+1; ctx.fillStyle='#0a0e1a'; ctx.fillRect(0,0,W,H); function ty(v) { return pad.top+(1-(v-minV)/(maxV-minV))*ph; } // Mean line var mean=vals.reduce((a,b)=>a+b,0)/n; ctx.save(); ctx.strokeStyle='rgba(255,215,0,0.5)'; ctx.lineWidth=1.5; ctx.setLineDash([5,4]); ctx.beginPath(); ctx.moveTo(pad.left,ty(mean)); ctx.lineTo(W-pad.right,ty(mean)); ctx.stroke(); ctx.fillStyle='rgba(255,215,0,0.8)'; ctx.font='9px Space Mono,monospace'; ctx.textAlign='left'; ctx.fillText('μ='+mean.toFixed(2),pad.left+4,ty(mean)-4); ctx.restore(); var bw=(pw/n)*0.5; var colors=['#00d4ff','#39ff14','#ff6b35','#ffd700','#cc44ff']; for (var i=0;i<n;i++) { var x=pad.left+(i+0.5)*(pw/n); var barH=Math.abs(ty(minV)-ty(vals[i])); var grad=ctx.createLinearGradient(0,ty(vals[i]),0,ty(minV)); grad.addColorStop(0,colors[i%%colors.length]); grad.addColorStop(1,colors[i%%colors.length].replace('ff','22')); ctx.fillStyle=grad; ctx.fillRect(x-bw/2,ty(vals[i]),bw,barH); ctx.fillStyle=colors[i%%colors.length]; ctx.font='9px Space Mono,monospace'; ctx.textAlign='center'; ctx.fillText(vals[i].toFixed(2),x,ty(vals[i])-4); ctx.save(); ctx.fillStyle='rgba(160,180,200,0.8)'; ctx.font='8px Space Mono,monospace'; ctx.translate(x,H-pad.bottom+6); ctx.rotate(-Math.PI/6); ctx.fillText(ids[i].replace('HL23DS-38-',''),0,0); ctx.restore(); } // Y axis labels var nTick=5; for (var i=0;i<=nTick;i++) { var v=minV+i*(maxV-minV)/nTick; ctx.fillStyle='#7a8aaa'; ctx.font='9px Space Mono,monospace'; ctx.textAlign='right'; ctx.fillText(v.toFixed(1),pad.left-4,ty(v)+4); } ctx.strokeStyle='rgba(0,212,255,0.4)'; ctx.lineWidth=1; ctx.setLineDash([]); ctx.beginPath(); ctx.moveTo(pad.left,pad.top); ctx.lineTo(pad.left,H-pad.bottom); ctx.lineTo(W-pad.right,H-pad.bottom); ctx.stroke(); ctx.fillStyle='#00d4ff'; ctx.font='10px Space Mono,monospace'; ctx.save(); ctx.translate(14,H/2); ctx.rotate(-Math.PI/2); ctx.textAlign='center'; ctx.fillText('Panicle Length (cm)',0,0); ctx.restore(); })(); ", vals_js, ids_js))) ) }) # ---- Genotype x Phenotype ---- output$genoPhePlotUI <- renderUI({ req(rv$results) trait <- if (!is.null(rv$trait)) rv$trait else "ENV1_PL" # Use best marker (highest LOD from SMR) smr <- smr_res() best_idx <- which.max(smr$LOD) if (length(best_idx) == 0) best_idx <- 1 best_mk <- smr$marker[best_idx] geno_col <- geno_data[[best_mk]] pheno_col <- pheno_data[[trait]] geno_js <- paste0("[", paste(ifelse(is.na(geno_col),-1,geno_col), collapse=","), "]") pheno_js <- paste0("[", paste(round(pheno_col,4), collapse=","), "]") ids_js <- paste0('["', paste(pheno_data$id, collapse='","'), '"]') tags$div( tags$p(style="font-size:0.7rem;color:var(--text-dim);margin-bottom:8px;", paste0("Best marker: ", best_mk, " | LOD = ", round(smr$LOD[best_idx], 3))), tags$canvas(id = "genoPhCanvas", style = "width:100%; height:240px;"), tags$script(HTML(sprintf(" (function() { var canvas=document.getElementById('genoPhCanvas'); if (!canvas) return; var dpr=window.devicePixelRatio||1; var W=canvas.offsetWidth||400; var H=240; canvas.width=W*dpr; canvas.height=H*dpr; canvas.style.width=W+'px'; canvas.style.height=H+'px'; var ctx=canvas.getContext('2d'); ctx.scale(dpr,dpr); var genos=%s; var phenos=%s; var ids=%s; var n=genos.length; var pad={top:20,right:20,bottom:30,left:60}; var pw=W-pad.left-pad.right; var ph=H-pad.top-pad.bottom; var groups={}; for (var i=0;i<n;i++) { var g=genos[i]; if(g==-1) g='NA'; if (!groups[g]) groups[g]=[]; groups[g].push(phenos[i]); } var gkeys=Object.keys(groups).sort(); var allP=phenos.filter(p=>!isNaN(p)); var minP=Math.min(...allP)-1; var maxP=Math.max(...allP)+1; ctx.fillStyle='#0a0e1a'; ctx.fillRect(0,0,W,H); function ty(v) { return pad.top+(1-(v-minP)/(maxP-minP))*ph; } var gColors={'1':'#39ff14','2':'#00d4ff','0':'#ff6b35','NA':'#7a8aaa'}; var gLabels={'1':'AA (Parent1)','2':'BB (Parent2)','0':'AB (Het)','NA':'Missing'}; var bw = pw/(gkeys.length+1)*0.6; for (var gi=0;gi<gkeys.length;gi++) { var gk=gkeys[gi]; var gp=groups[gk]; var gmean=gp.reduce((a,b)=>a+b,0)/gp.length; var gx=pad.left+(gi+1)*(pw/(gkeys.length+1)); var col=gColors[gk]||'#aaa'; // box outline if (gp.length > 1) { var gmin=Math.min(...gp); var gmax=Math.max(...gp); ctx.strokeStyle=col; ctx.lineWidth=1; ctx.strokeRect(gx-bw/2,ty(gmax),bw,ty(gmin)-ty(gmax)); } // Points for (var pi=0;pi<gp.length;pi++) { ctx.fillStyle=col; ctx.beginPath(); ctx.arc(gx + (Math.random()-0.5)*bw*0.3, ty(gp[pi]), 5, 0, Math.PI*2); ctx.fill(); } // Mean line ctx.strokeStyle=col; ctx.lineWidth=2.5; ctx.beginPath(); ctx.moveTo(gx-bw/2+4,ty(gmean)); ctx.lineTo(gx+bw/2-4,ty(gmean)); ctx.stroke(); ctx.fillStyle=col; ctx.font='9px Space Mono,monospace'; ctx.textAlign='center'; ctx.fillText(gLabels[gk]||gk, gx, H-pad.bottom+12); ctx.fillText('μ='+gmean.toFixed(2), gx, ty(gmean)-7); } for (var i=0;i<=4;i++) { var v=minP+i*(maxP-minP)/4; ctx.fillStyle='#7a8aaa'; ctx.font='9px Space Mono,monospace'; ctx.textAlign='right'; ctx.fillText(v.toFixed(1),pad.left-4,ty(v)+4); } ctx.strokeStyle='rgba(0,212,255,0.4)'; ctx.lineWidth=1; ctx.beginPath(); ctx.moveTo(pad.left,pad.top); ctx.lineTo(pad.left,H-pad.bottom); ctx.lineTo(W-pad.right,H-pad.bottom); ctx.stroke(); })(); ", geno_js, pheno_js, ids_js))) ) }) # ---- Results Table ---- output$resultsTableUI <- renderUI({ req(rv$results) thr <- get_threshold() df <- rv$results[order(rv$results$model, rv$results$position), ] rows <- lapply(seq_len(nrow(df)), function(i) { row <- df[i, ] lod_val <- if (!is.na(row$LOD)) round(row$LOD, 4) else "—" pval <- if (!is.na(row$pvalue)) formatC(row$pvalue, format="e", digits=2) else "—" r2 <- if (!is.na(row$R2)) paste0(round(row$R2*100, 1), "%") else "—" add <- if (!is.na(row$additive)) round(row$additive, 4) else "—" sig <- !is.na(row$LOD) && row$LOD >= thr tags$tr(class = if (sig) "sig-row" else "", tags$td(row$marker), tags$td(row$chromosome), tags$td(round(row$position, 3)), tags$td(lod_val), tags$td(pval), tags$td(r2), tags$td(add), tags$td(row$model), tags$td(if (sig) tags$span(class="badge badge-sig","SIG") else tags$span(class="badge badge-ns","NS")) ) }) tags$table(class = "qtl-table", tags$thead( tags$tr( tags$th("Marker"), tags$th("Chr"), tags$th("Pos (cM)"), tags$th("LOD"), tags$th("p-value"), tags$th("R²"), tags$th("Additive Effect"), tags$th("Model"), tags$th("Sig.") ) ), tags$tbody(rows) ) }) # ---- Summary ---- output$summaryUI <- renderUI({ req(rv$results) thr <- get_threshold() trait <- if (!is.null(rv$trait)) rv$trait else "ENV1_PL" sig <- rv$results[!is.na(rv$results$LOD) & rv$results$LOD >= thr, ] best_smr <- smr_res() best_idx <- which.max(best_smr$LOD) best_mk <- if (length(best_idx) > 0) best_smr$marker[best_idx] else "—" best_lod <- if (length(best_idx) > 0) round(best_smr$LOD[best_idx], 3) else "—" best_pos <- if (length(best_idx) > 0) round(best_smr$position[best_idx], 3) else "—" best_r2 <- if (length(best_idx) > 0 && !is.na(best_smr$R2[best_idx])) paste0(round(best_smr$R2[best_idx]*100,1),"%") else "—" best_add <- if (length(best_idx) > 0 && !is.na(best_smr$additive[best_idx])) round(best_smr$additive[best_idx],3) else "—" pheno_vals <- pheno_data[[trait]] pheno_mean <- round(mean(pheno_vals), 3) pheno_sd <- round(sd(pheno_vals), 3) pheno_cv <- round(sd(pheno_vals)/mean(pheno_vals)*100, 2) tags$div(style = "font-family: var(--font-serif); font-size: 1rem; line-height: 1.8; color: var(--text);", tags$h3(style = "font-family: var(--font-mono); font-size: 0.9rem; color: var(--accent); letter-spacing: 0.15em; text-transform: uppercase; margin-bottom: 16px; border-bottom: 1px solid var(--border); padding-bottom: 8px;", "Publication-Ready Summary"), tags$div(class = "results-grid-3", style = "margin-bottom: 20px;", tags$div(class = "stat-box", tags$div(class = "stat-val", pheno_mean), tags$div(class = "stat-lbl", paste0("Mean ", trait, " (cm)")) ), tags$div(class = "stat-box", tags$div(class = "stat-val", style = "color: var(--accent2);", pheno_sd), tags$div(class = "stat-lbl", "Std. Deviation") ), tags$div(class = "stat-box", tags$div(class = "stat-val", style = "color: var(--accent3);", paste0(pheno_cv, "%")), tags$div(class = "stat-lbl", "Coefficient of Var.") ) ), tags$div(class = "results-grid", style = "margin-bottom: 16px;", tags$div(class = "panel-card", style = "padding: 14px;", tags$div(style = "font-size: 0.7rem; letter-spacing:0.15em; text-transform:uppercase; color: var(--accent); margin-bottom: 8px;", "Best QTL (SMR)"), tags$table(style = "width:100%; font-size:0.8rem;", tags$tr(tags$td(style="color:var(--text-dim);padding:3px 0;", "Marker:"), tags$td(style="color:var(--text);font-weight:700;", best_mk)), tags$tr(tags$td(style="color:var(--text-dim);padding:3px 0;", "Chr/Pos:"), tags$td(paste0("Chr1 / ", best_pos, " cM"))), 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)), tags$tr(tags$td(style="color:var(--text-dim);padding:3px 0;", "Var. Expl.:"), tags$td(style="color:var(--accent3);", best_r2)), tags$tr(tags$td(style="color:var(--text-dim);padding:3px 0;", "Add. Effect:"), tags$td(best_add)), tags$tr(tags$td(style="color:var(--text-dim);padding:3px 0;", "Threshold:"), tags$td(paste0("LOD = ", thr))) ) ), tags$div(class = "panel-card", style = "padding: 14px;", tags$div(style = "font-size: 0.7rem; letter-spacing:0.15em; text-transform:uppercase; color: var(--accent); margin-bottom: 8px;", "Dataset Info"), tags$table(style = "width:100%; font-size:0.8rem;", tags$tr(tags$td(style="color:var(--text-dim);padding:3px 0;", "Population:"), tags$td("HL23DS-38 RIL/BC")), tags$tr(tags$td(style="color:var(--text-dim);padding:3px 0;", "Lines:"), tags$td("5")), tags$tr(tags$td(style="color:var(--text-dim);padding:3px 0;", "Markers:"), tags$td("12 (Chr 1)")), tags$tr(tags$td(style="color:var(--text-dim);padding:3px 0;", "Map length:"), tags$td("15.84 cM")), tags$tr(tags$td(style="color:var(--text-dim);padding:3px 0;", "Reference:"), tags$td("IRGSP 1.0")), tags$tr(tags$td(style="color:var(--text-dim);padding:3px 0;", "Trait:"), tags$td(trait)) ) ) ), 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: 0.95rem; line-height: 1.8;", tags$strong(style = "color: var(--text); font-style: normal; font-family: var(--font-mono); font-size: 0.75rem; letter-spacing: 0.1em; text-transform: uppercase; display: block; margin-bottom: 8px;", "Suggested Methods Text"), paste0("QTL analysis was conducted on chromosome 1 of Oryza sativa (IRGSP 1.0) using ", trait, " as the target trait (n=5 lines). Single marker regression (SMR), ", "interval mapping with Haley-Knott regression (IM-HK), and composite interval mapping (CIM) ", "were performed alongside 7 additional statistical models including LASSO, ridge regression, ", "mixed linear model, Kruskal-Wallis non-parametric test, Bayesian interval mapping, ", "multiple QTL model (MQM), and two-way epistasis analysis. ", "Phenotypic mean was ", pheno_mean, " cm (SD = ", pheno_sd, "). ", "The highest LOD score of ", best_lod, " was detected at marker ", best_mk, " (", best_pos, " cM), explaining ", best_r2, " of phenotypic variance. ", "Significance threshold was set at LOD = ", thr, "; genome-wide empirical threshold was estimated via 200 permutations.") ) ) }) # ---- CI Plot ---- output$ciPlotUI <- renderUI({ req(rv$results) thr <- get_threshold() smr <- smr_res() smr <- smr[order(smr$position), ] sig <- smr[!is.na(smr$LOD) & smr$LOD >= thr, ] if (nrow(sig) == 0) { return(tags$p(style="color:var(--text-dim);padding:20px;font-size:0.8rem;", paste0("No markers exceed LOD threshold of ", thr, ". Lower threshold to see confidence intervals."))) } # 1.5-LOD support interval per significant marker ci_data <- lapply(seq_len(nrow(sig)), function(i) { mk <- sig$marker[i] peak_lod <- sig$LOD[i] ci_thresh <- peak_lod - 1.5 ci_marks <- smr[!is.na(smr$LOD) & smr$LOD >= ci_thresh, ] list( marker = mk, pos = sig$position[i], lod = peak_lod, ci_lo = min(ci_marks$position), ci_hi = max(ci_marks$position), r2 = sig$R2[i] ) }) ci_js <- paste0("[", paste(sapply(ci_data, function(d) { sprintf("{marker:'%s',pos:%.4f,lod:%.4f,ci_lo:%.4f,ci_hi:%.4f,r2:%.4f}", d$marker, d$pos, d$lod, d$ci_lo, d$ci_hi, ifelse(is.na(d$r2),0,d$r2)) }), collapse=","), "]") tags$div( tags$canvas(id = "ciCanvas", style = "width:100%; height:220px;"), tags$script(HTML(sprintf(" (function() { var canvas=document.getElementById('ciCanvas'); if (!canvas) return; var dpr=window.devicePixelRatio||1; var W=canvas.offsetWidth||700; var H=220; canvas.width=W*dpr; canvas.height=H*dpr; canvas.style.width=W+'px'; canvas.style.height=H+'px'; var ctx=canvas.getContext('2d'); ctx.scale(dpr,dpr); var cis=%s; var maxX=16; var pad={top:30,right:30,bottom:40,left:60}; var pw=W-pad.left-pad.right; var ph=H-pad.top-pad.bottom; ctx.fillStyle='#0a0e1a'; ctx.fillRect(0,0,W,H); function tx(x) { return pad.left+(x/maxX)*pw; } // Chr line ctx.strokeStyle='rgba(0,80,180,0.7)'; ctx.lineWidth=20; ctx.lineCap='round'; ctx.beginPath(); ctx.moveTo(tx(0), H/2); ctx.lineTo(tx(maxX), H/2); ctx.stroke(); var colors=['#ffd700','#ff6b35','#39ff14','#cc44ff','#00ffbb']; for (var i=0;i<cis.length;i++) { var ci=cis[i]; var col=colors[i%%colors.length]; var y=H/2; // CI bracket ctx.fillStyle=col.replace('ff','33'); ctx.fillRect(tx(ci.ci_lo), y-16, tx(ci.ci_hi)-tx(ci.ci_lo), 32); ctx.strokeStyle=col; ctx.lineWidth=1.5; ctx.strokeRect(tx(ci.ci_lo), y-16, tx(ci.ci_hi)-tx(ci.ci_lo), 32); // Peak marker ctx.fillStyle=col; ctx.beginPath(); ctx.arc(tx(ci.pos), y, 7, 0, Math.PI*2); ctx.fill(); // Label above ctx.fillStyle=col; ctx.font='bold 9px Space Mono,monospace'; ctx.textAlign='center'; ctx.fillText(ci.marker.replace('chr01_','').replace('IRGSP1_C01_',''), tx(ci.pos), y-22); ctx.fillText('LOD='+ci.lod.toFixed(2), tx(ci.pos), y-11); ctx.fillStyle='rgba(200,220,240,0.6)'; ctx.font='8px Space Mono,monospace'; ctx.fillText((ci.ci_hi-ci.ci_lo).toFixed(2)+' cM CI', tx((ci.ci_lo+ci.ci_hi)/2), y+28); } // Axis ctx.strokeStyle='rgba(0,212,255,0.3)'; ctx.lineWidth=1; ctx.beginPath(); ctx.moveTo(pad.left,H-pad.bottom); ctx.lineTo(W-pad.right,H-pad.bottom); ctx.stroke(); ctx.fillStyle='#7a8aaa'; ctx.font='9px Space Mono,monospace'; ctx.textAlign='center'; for (var x=0;x<=maxX;x+=2) ctx.fillText(x, tx(x), H-pad.bottom+14); ctx.fillStyle='#00d4ff'; ctx.font='10px Space Mono,monospace'; ctx.fillText('Chromosome 1 Position (cM) — 1.5-LOD Confidence Interval', W/2, H-4); })(); ", ci_js))) ) }) # Export observeEvent(input$export_csv, { req(rv$results) output$downloadData <- downloadHandler( filename = paste0("QTL_results_", Sys.Date(), ".csv"), content = function(file) write.csv(rv$results, file, row.names=FALSE) ) }) # Permutation badge update tags$script(HTML(" Shiny.addCustomMessageHandler('updatePermBadge', function(msg) { document.getElementById('permThreshBadge').textContent = 'Perm. Threshold: LOD = ' + msg.val; }); ")) } shinyApp(ui = ui, server = server)
library(shiny)
library(htmltools)
# ============================================================
# DATA SETUP
# ============================================================
geno_data <- data.frame(
id = c("HL23DS-38-P-2","HL23DS-38-P-3","HL23DS-38-P-4","HL23DS-38-P-6","HL23DS-38-P-7"),
chr01_194844 = c(2,2,2,2,2),
chr01_375814 = c(2,2,2,2,2),
chr01_717702 = c(2,2,2,2,2),
chr01_932866 = c(2,2,2,2,2),
chr01_1044946 = c(2,2,2,2,2),
chr01_1175585 = c(1,1,1,1,0),
chr01_1410467 = c(2,2,1,2,1),
chr01_1532281 = c(2,2,2,2,1),
chr01_2100471 = c(2,1,1,2,0),
IRGSP1_C01_2124430 = c(-1,0,0,0,0),
chr01_2277961 = c(2,1,1,2,1),
chr01_2532252 = c(2,1,1,2,1),
stringsAsFactors = FALSE
)
marker_pos <- c(0.221999744,0.598239971,0.696068244,1.104168077,3.909714828,
6.715261579,6.878338228,9.672132718,12.47767947,15.28322622,
15.28322622,15.83731141)
marker_names <- c("chr01_194844","chr01_375814","chr01_717702","chr01_932866",
"chr01_1044946","chr01_1175585","chr01_1410467","chr01_1532281",
"chr01_2100471","IRGSP1_C01_2124430","chr01_2277961","chr01_2532252")
pheno_data <- data.frame(
id = c("HL23DS-38-P-2","HL23DS-38-P-3","HL23DS-38-P-4","HL23DS-38-P-6","HL23DS-38-P-7"),
ENV1_PL = c(28.42268519,27.33935185,25.50601852,24.17268519,27.50601852),
ENV2_PL = c(30.74398148,29.66064815,27.82731481,26.49398148,29.82731481),
stringsAsFactors = FALSE
)
# ============================================================
# QTL ANALYSIS FUNCTIONS
# ============================================================
prepare_cross <- function(geno_df, pheno_df, trait) {
merged <- merge(geno_df, pheno_df[, c("id", trait)], by = "id")
y <- merged[[trait]]
marker_cols <- setdiff(names(merged), c("id", trait))
X_raw <- as.matrix(merged[, marker_cols, drop = FALSE])
X_raw[X_raw == -1] <- NA
list(y = y, X = X_raw, markers = marker_cols)
}
impute_markers <- function(X) {
for (j in seq_len(ncol(X))) {
nas <- is.na(X[, j])
if (any(nas)) {
vals <- X[!nas, j]
X[nas, j] <- if (length(vals) > 0) round(mean(vals)) else 2
}
}
X
}
# Encode genotype as additive (-1, 0, 1) from (1, 1.5, 2) or (1,2)
encode_additive <- function(X) {
X2 <- X
for (j in seq_len(ncol(X))) {
u <- sort(unique(na.omit(X[,j])))
if (length(u) >= 2) {
mn <- min(u); mx <- max(u)
X2[, j] <- (X[, j] - (mn + mx)/2) / ((mx - mn)/2)
}
}
X2
}
# ---- 1. Single Marker Regression (ANOVA/t-test) ----
run_smr <- function(y, X) {
n_markers <- ncol(X)
results <- data.frame(
marker = colnames(X),
position = marker_pos[seq_len(n_markers)],
chromosome = 1,
LOD = NA_real_,
pvalue = NA_real_,
R2 = NA_real_,
additive = NA_real_,
model = "Single Marker Regression",
stringsAsFactors = FALSE
)
for (j in seq_len(n_markers)) {
g <- X[, j]
valid <- !is.na(g)
if (sum(valid) < 3) next
gv <- as.factor(g[valid]); yv <- y[valid]
if (nlevels(gv) < 2) next
tryCatch({
fit0 <- lm(yv ~ 1)
fit1 <- lm(yv ~ gv)
rss0 <- sum(residuals(fit0)^2)
rss1 <- sum(residuals(fit1)^2)
n <- length(yv)
lod <- (n/2) * log10(rss0/rss1)