qtl / app.R
International Rice Research Institute
Update app.R
eec0d95 verified
Raw History Blame
82.7 kB
options(repos = c(CRAN = "https://cloud.r-project.org")) required_packages <- c( "shiny", "randomForest", "caret", "DT", "ggplot2", "plotly", "writexl", "viridis", "reshape2", "dplyr", "httr", "jsonlite", "shinyjs", "markdown", "base64enc" ) for (pkg in required_packages) { if (!require(pkg, character.only = TRUE)) { install.packages(pkg, dependencies = TRUE) library(pkg, character.only = TRUE) } } # ============================================================ # TOKEN / API SETUP # ============================================================ token <- Sys.getenv("GROQ_API_KEY") token_exists <- token != "" token_length <- if (token_exists) nchar(token) else 0 cat("=== GROQ API TOKEN DEBUG ===\n") cat("Token exists:", token_exists, "\n") cat("Token length:", token_length, "\n") if (token_exists) cat("Token starts with:", substr(token, 1, 10), "\n") cat("===================================\n") HF_API_TOKEN <- token HF_API_URL <- "https://api.groq.com/openai/v1/chat/completions" default_model <- "llama-3.1-8b-instant" available_models <- list( list(id = "llama-3.1-8b-instant", label = "Llama 3.1 8B", provider = "groq", tier = "free"), list(id = "llama-3.3-70b-versatile", label = "Llama 3.3 70B", provider = "groq", tier = "free"), list(id = "meta-llama/llama-4-maverick-17b-128e-instruct", label = "Llama 4 Maverick 17B", provider = "groq", tier = "free"), list(id = "moonshotai/kimi-k2-instruct-0905", label = "Kimi K2", provider = "groq", tier = "free") ) model_choices <- setNames( sapply(available_models, function(m) m$id), sapply(available_models, function(m) paste0(m$label, " [", m$tier, "]")) ) run_cim <- function(genotype_matrix, phenotype_vector, marker_info, n_cofactors = 10, window_size = 10, lod_threshold = 2.0) { markers <- colnames(genotype_matrix) n_markers <- length(markers) n_samples <- length(phenotype_vector) cat("CIM: Starting with", n_markers, "markers,", n_samples, "samples\n") # ---- Step 1: Select cofactors via RF ---- valid_rows <- !is.na(phenotype_vector) X_valid <- genotype_matrix[valid_rows, , drop = FALSE] y_valid <- phenotype_vector[valid_rows] # Remove zero-variance markers before RF nzv <- apply(X_valid, 2, function(x) length(unique(na.omit(x))) < 2) X_valid <- X_valid[, !nzv, drop = FALSE] rf_model <- tryCatch( randomForest(x = X_valid, y = y_valid, ntree = 500, importance = TRUE), error = function(e) NULL ) if (!is.null(rf_model)) { imp_scores <- importance(rf_model, type = 1)[, 1] top_cofactors <- names(sort(imp_scores, decreasing = TRUE))[1:min(n_cofactors * 2, length(imp_scores))] } else { # Fallback: single-marker regression ranking p_vals <- sapply(colnames(X_valid), function(m) { fit <- lm(y_valid ~ X_valid[, m]) coef(summary(fit))[2, 4] }) top_cofactors <- names(sort(p_vals))[1:min(n_cofactors * 2, length(p_vals))] } cat("CIM: Selected", length(top_cofactors), "candidate cofactors\n") # ---- Step 2: Scan each marker with CIM ---- results_list <- list() for (i in seq_along(markers)) { m <- markers[i] geno <- genotype_matrix[, m] valid_idx <- !is.na(geno) & !is.na(phenotype_vector) geno_v <- geno[valid_idx] pheno_v <- phenotype_vector[valid_idx] if (length(unique(geno_v)) < 2 || length(pheno_v) < 5) next # Get marker info m_info <- marker_info[marker_info$Marker == m, ] if (nrow(m_info) == 0) next m_chr <- m_info$Chromosome[1] m_pos <- m_info$Position[1] # ---- Exclude cofactors within window_size positions on same chromosome ---- chr_markers <- marker_info[marker_info$Chromosome == m_chr, ] chr_markers <- chr_markers[order(chr_markers$Position), ] m_idx <- which(chr_markers$Marker == m) if (length(m_idx) > 0) { nearby_range <- max(1, m_idx - window_size):min(nrow(chr_markers), m_idx + window_size) nearby_mks <- chr_markers$Marker[nearby_range] } else { nearby_mks <- m } active_cofactors <- setdiff(top_cofactors, c(m, nearby_mks)) active_cofactors <- active_cofactors[active_cofactors %in% colnames(genotype_matrix)] active_cofactors <- head(active_cofactors, n_cofactors) # ---- Build data frame for model ---- df_model <- data.frame(y = pheno_v, focal = geno_v[valid_idx]) # Add cofactors if (length(active_cofactors) > 0) { cof_mat <- genotype_matrix[valid_idx, active_cofactors, drop = FALSE] # Handle NAs in cofactors cof_mat[is.na(cof_mat)] <- 0 df_model <- cbind(df_model, cof_mat) } df_model <- df_model[complete.cases(df_model), ] if (nrow(df_model) < 5) next # ---- Fit CIM model ---- tryCatch({ if (length(active_cofactors) > 0) { cof_formula <- paste(active_cofactors, collapse = " + ") full_formula <- as.formula(paste("y ~ focal +", cof_formula)) } else { full_formula <- as.formula("y ~ focal") } fit <- lm(full_formula, data = df_model) sm <- summary(fit) coef_t <- sm$coefficients if (!"focal" %in% rownames(coef_t)) next p_val <- coef_t["focal", "Pr(>|t|)"] lod <- -log10(p_val + 1e-300) # avoid log(0) r2_full <- sm$r.squared # ---- Additive + Dominance effects (on this marker) ---- a_code <- df_model$focal d_code <- as.numeric(a_code == 1) has_het <- length(unique(d_code)) > 1 if (has_het) { lm_eff <- lm(y ~ a_code + d_code, data = df_model) sm_eff <- summary(lm_eff) pve_ad <- sm_eff$r.squared * 100 # PVE from add+dom ALONE (marker only) c_eff <- coef(lm_eff) a_eff <- c_eff["a_code"] d_eff <- c_eff["d_code"] se_t <- sm_eff$coefficients se_a <- se_t["a_code", "Std. Error"] se_d <- se_t["d_code", "Std. Error"] d_rat <- if (!is.na(a_eff) && a_eff != 0) abs(d_eff / a_eff) else NA } else { lm_eff <- lm(y ~ a_code, data = df_model) sm_eff <- summary(lm_eff) pve_ad <- sm_eff$r.squared * 100 c_eff <- coef(lm_eff) a_eff <- c_eff["a_code"] d_eff <- NA; se_a <- NA; se_d <- NA; d_rat <- NA } # PVE from full CIM model (marker + cofactors) — this is the HIGH PVE pve_cim <- r2_full * 100 dom_class <- if (is.na(d_rat)) "Additive" else if (d_rat > 1) "Overdominance" else if (d_rat > 0.5) "Dominance" else if (d_rat > 0.2) "Partial Dom." else "Additive" results_list[[m]] <- data.frame( Marker = m, Chromosome = m_chr, Position = m_pos, LOD = lod, P_Value = p_val, PVE_Marker_Percent = pve_ad, # PVE of marker alone (add+dom) PVE_CIM_Percent = pve_cim, # PVE of full CIM model (marker + cofactors) Additive_Effect = a_eff, SE_Additive = se_a, CI_Lower = ifelse(is.na(se_a), NA, a_eff - 1.96 * se_a), CI_Upper = ifelse(is.na(se_a), NA, a_eff + 1.96 * se_a), Dominance_Effect = d_eff, SE_Dominance = se_d, Dominance_Ratio = d_rat, Dominance_Class = dom_class, N_Cofactors = length(active_cofactors), N_Samples = nrow(df_model), N_Heterozygotes = sum(df_model$focal == 1), stringsAsFactors = FALSE ) }, error = function(e) { cat("CIM error at marker", m, ":", e$message, "\n") }) } if (length(results_list) == 0) { return(data.frame(Message = "CIM produced no results — check data format")) } cim_result <- do.call(rbind, results_list) cim_result <- cim_result[order(-cim_result$LOD), ] cat("CIM: Completed scan,", nrow(cim_result), "markers evaluated\n") return(cim_result) } # ============================================================ # FLANKING MARKER FUNCTION — FIXED # Uses the FULL all_markers table (not post-NZV subset) # ============================================================ add_flanking_markers <- function(sig_df, all_markers_df) { sig_df$Low_Flank <- NA_character_ sig_df$High_Flank <- NA_character_ for (i in 1:nrow(sig_df)) { focal_marker <- sig_df$Marker[i] focal_chr <- sig_df$Chromosome[i] focal_pos <- sig_df$Position[i] # Get ALL markers on same chromosome, sorted by position chr_markers <- all_markers_df[all_markers_df$Chromosome == focal_chr, ] chr_markers <- chr_markers[order(chr_markers$Position), ] if (nrow(chr_markers) == 0) next # Find position of focal marker in sorted list idx <- which(chr_markers$Marker == focal_marker) if (length(idx) > 0) { sig_df$Low_Flank[i] <- if (idx > 1) chr_markers$Marker[idx - 1] else focal_marker sig_df$High_Flank[i] <- if (idx < nrow(chr_markers)) chr_markers$Marker[idx + 1] else focal_marker } else { # Marker not found by name — find by closest position dists <- abs(chr_markers$Position - focal_pos) idx <- which.min(dists) sig_df$Low_Flank[i] <- if (idx > 1) chr_markers$Marker[idx - 1] else focal_marker sig_df$High_Flank[i] <- if (idx < nrow(chr_markers)) chr_markers$Marker[idx + 1] else focal_marker } } return(sig_df) } # ============================================================ # API / AI FUNCTIONS (unchanged) # ============================================================ test_api_connection <- function(model_id = default_model) { if (!token_exists) return(list(success = FALSE, error = "No token found")) tryCatch({ response <- POST( url = HF_API_URL, add_headers(Authorization = paste("Bearer", HF_API_TOKEN), "Content-Type" = "application/json"), body = toJSON(list(model = model_id, messages = list(list(role = "user", content = "Hi")), max_tokens = 10L), auto_unbox = TRUE), encode = "json", timeout(15)) if (status_code(response) == 200) return(list(success = TRUE)) err <- tryCatch(content(response, "text", encoding = "UTF-8"), error = function(e) paste("Status:", status_code(response))) list(success = FALSE, error = paste("Status:", status_code(response), "-", substr(err, 1, 200))) }, error = function(e) list(success = FALSE, error = e$message)) } api_test <- test_api_connection(default_model) use_hf_api <- token_exists && api_test$success cat("API Test:", if (api_test$success) "SUCCESS" else paste("FAILED -", api_test$error), "\n") query_hf_api <- function(prompt, model_id = default_model, max_length = 500, temperature = 0.7) { if (!token_exists) return(list(success = FALSE, error = "HF_API_TOKEN not set")) tryCatch({ response <- POST( url = HF_API_URL, add_headers(Authorization = paste("Bearer", HF_API_TOKEN), "Content-Type" = "application/json"), body = toJSON(list( model = model_id, messages = list( list(role = "system", content = "You are an expert bioinformatics assistant specializing in QTL analysis using Composite Interval Mapping. Be concise and helpful."), list(role = "user", content = prompt)), max_tokens = as.integer(max_length), temperature = temperature), auto_unbox = TRUE), encode = "json", timeout(60)) if (status_code(response) == 200) { result <- content(response, as = "parsed", encoding = "UTF-8") return(list(success = TRUE, text = result$choices[[1]]$message$content)) } err <- tryCatch(content(response, "text", encoding = "UTF-8"), error = function(e) paste("Status:", status_code(response))) list(success = FALSE, error = paste("API error:", status_code(response), "-", substr(err, 1, 200))) }, error = function(e) list(success = FALSE, error = e$message)) } build_system_prompt <- function(rv) { ctx <- c("CURRENT ANALYSIS RESULTS (Composite Interval Mapping):") if (!is.null(rv$cim_all) && !"Message" %in% colnames(rv$cim_all)) { sig <- rv$cim_all[rv$cim_all$LOD >= rv$lod_threshold, ] ctx <- c(ctx, sprintf("\nCIM Results: %d significant QTLs above LOD %.1f", nrow(sig), rv$lod_threshold), sprintf("Total PVE (CIM model, marker+cofactors): %.1f%%", if (nrow(sig) > 0) max(sig$PVE_CIM_Percent) else 0)) if (nrow(sig) > 0) { top3 <- head(sig, 3) ctx <- c(ctx, "\nTop QTLs:") for (i in 1:nrow(top3)) { r <- top3[i, ] ctx <- c(ctx, sprintf(" %d. %s (Chr %s): LOD=%.2f, PVE_marker=%.1f%%, PVE_CIM=%.1f%%, A=%.3f, D=%s", i, r$Marker, r$Chromosome, r$LOD, r$PVE_Marker_Percent, r$PVE_CIM_Percent, r$Additive_Effect, ifelse(is.na(r$Dominance_Effect), "NA", as.character(round(r$Dominance_Effect, 3))))) } } } if (!is.null(rv$performance_metrics)) { pm <- rv$performance_metrics ctx <- c(ctx, sprintf("\nModel R² (Train): %.3f, R² (Validation): %.3f", pm$Value[pm$Metric == "R² (Train)"], pm$Value[pm$Metric == "R² (Validation)"])) } paste(ctx, collapse = "\n") } enhanced_rule_response <- function(user_message, rv) { q <- tolower(trimws(user_message)) has_cim <- !is.null(rv$cim_all) && !"Message" %in% colnames(rv$cim_all) has_qtl <- has_cim && any(rv$cim_all$LOD >= rv$lod_threshold) has_perf <- !is.null(rv$performance_metrics) if (grepl("pve|variance explained|how much variance|percent variance|what is pve|cim", q)) { if (has_qtl) { sig <- rv$cim_all[rv$cim_all$LOD >= rv$lod_threshold, ] top_pve <- sig[which.max(sig$PVE_CIM_Percent), ] return(paste0( "📊 **PVE in Composite Interval Mapping**\n\n", "**Two PVE values are reported:**\n", "• `PVE_Marker_%` = R² from lm(y ~ a + d) — marker alone\n", "• `PVE_CIM_%` = R² from full CIM model (marker + cofactors) — HIGHER\n\n", "**Top QTL:** ", top_pve$Marker, " (Chr ", top_pve$Chromosome, ")\n", "• LOD: ", round(top_pve$LOD, 2), "\n", "• PVE (marker alone): ", round(top_pve$PVE_Marker_Percent, 1), "%\n", "• PVE (CIM full model): ", round(top_pve$PVE_CIM_Percent, 1), "%\n", "• Additive: ", round(top_pve$Additive_Effect, 3), "\n", "• Dominance: ", ifelse(is.na(top_pve$Dominance_Effect), "NA", round(top_pve$Dominance_Effect, 3)), "\n\n", "CIM PVE is higher because cofactors absorb background genetic variance,\n", "letting each QTL's true contribution be measured more accurately." )) } return("Run CIM analysis first to see PVE values.") } if (grepl("top qtl|best qtl|highest lod|significant qtl|list qtl|show qtl", q)) { if (has_qtl) { sig <- rv$cim_all[rv$cim_all$LOD >= rv$lod_threshold, ] top5 <- head(sig, 5) out <- "🎯 **Top QTLs by LOD (Composite Interval Mapping)**\n\n" for (i in 1:nrow(top5)) { r <- top5[i, ] dom <- ifelse(is.na(r$Dominance_Effect), "NA", as.character(round(r$Dominance_Effect, 3))) out <- paste0(out, i, ". **", r$Marker, "** (Chr ", r$Chromosome, ")\n", " • LOD: **", round(r$LOD, 2), "**\n", " • PVE_marker: ", round(r$PVE_Marker_Percent, 1), "% | PVE_CIM: ", round(r$PVE_CIM_Percent, 1), "%\n", " • Flanking: ", r$Low_Flank, " ↔ ", r$High_Flank, "\n\n") } return(out) } return("No significant QTLs detected. Try lowering the LOD threshold.") } if (grepl("flank|interval|region|boundary", q)) { if (has_qtl) { sig <- rv$cim_all[rv$cim_all$LOD >= rv$lod_threshold, ] out <- "🧬 **QTL Flanking Markers (Fixed)**\n\n" for (i in 1:min(5, nrow(sig))) { r <- sig[i, ] out <- paste0(out, r$Marker, ": [", r$Low_Flank, "] ← QTL → [", r$High_Flank, "]\n") } return(out) } return("Run analysis first to see flanking markers.") } if (grepl("model performance|r2|r squared|validation|negative r2", q) && has_perf) { pm <- rv$performance_metrics val_r2 <- pm$Value[pm$Metric == "R² (Validation)"] out <- paste0("📈 **Model Performance**\n\n• Training R²: ", round(pm$Value[pm$Metric == "R² (Train)"], 3), "\n• Validation R²: **", round(val_r2, 3), "**\n\n") if (val_r2 < 0) { out <- paste0(out, "⚠️ Negative validation R² — likely overfitting or small sample.\n", "Try increasing sample size or reducing cofactors (lower n_cofactors).") } else if (val_r2 >= 0.5) { out <- paste0(out, "🎯 Excellent validation R²!") } return(out) } paste0("👋 Hello! TerraByte-AI here (CIM mode).\n\n", "Ask me about:\n• **PVE / CIM** — how variance is explained\n", "• **Top QTLs** — flanking markers included\n• **Model performance**\n", "• **What is CIM?** — Composite Interval Mapping explained\n\n", "Contact: ashmithamganesan@gmail.com, P.sinha@cgiar.org") } generate_ai_response <- function(user_message, rv, model_id = default_model) { if (token_exists) { context <- build_system_prompt(rv) prompt <- paste("CONTEXT:", context, "\n\nUSER:", user_message, "\n\nAnswer specifically using the context above. Be concise.") result <- query_hf_api(prompt, model_id = model_id) if (result$success) return(result$text) } enhanced_rule_response(user_message, rv) } # ============================================================ # UI # ============================================================ ui <- fluidPage( shinyjs::useShinyjs(), tags$head( tags$link(rel = "stylesheet", href = "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css"), tags$link(rel = "stylesheet", href = "https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;600&family=IBM+Plex+Sans:wght@300;400;500;600&display=swap"), tags$script(HTML(" function simulateQTLDiscovery() { setTimeout(function() { const markers = document.querySelectorAll('.chromosome-marker'); let delay = 0; markers.forEach(function(marker) { setTimeout(function() { marker.classList.add('highlighted'); setTimeout(function() { marker.classList.add('pulse'); }, 300); }, delay); delay += 100; }); }, 100); } function resetAnimation() { const markers = document.querySelectorAll('.chromosome-marker'); markers.forEach(function(marker) { marker.classList.remove('highlighted', 'pulse'); }); } Shiny.addCustomMessageHandler('simulateQTLDiscovery', function(m) { simulateQTLDiscovery(); }); Shiny.addCustomMessageHandler('resetAnimation', function(m) { resetAnimation(); }); Shiny.addCustomMessageHandler('scrollChatBottom', function(m) { setTimeout(function() { var cb = document.getElementById('chat_messages'); if (cb) cb.scrollTop = cb.scrollHeight; }, 100); }); $(document).on('keydown', '#chat_input', function(e) { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); $('#send_chat').click(); } }); ")), tags$style(HTML(" :root { --bg-primary:#0d1117;--bg-secondary:#161b22;--bg-tertiary:#21262d; --border:#30363d;--text-primary:#e6edf3;--text-secondary:#8b949e; --text-muted:#6e7681;--accent:#58a6ff;--accent-hover:#79c0ff; --success:#3fb950;--warning:#d29922;--danger:#f85149; --purple:#bc8cff;--teal:#39d353; --font-mono:'IBM Plex Mono',monospace;--font-sans:'IBM Plex Sans',sans-serif; } *{box-sizing:border-box;margin:0;padding:0;} body{font-family:var(--font-sans);background:var(--bg-primary);color:var(--text-primary);font-size:14px;} .navbar{background:var(--bg-secondary)!important;border-bottom:1px solid var(--border);} .navbar-brand{color:var(--text-primary)!important;font-family:var(--font-mono);font-weight:600;} .navbar-nav>li>a{color:var(--text-secondary)!important;font-size:13px;} .navbar-nav>li.active>a,.navbar-nav>li>a:hover{color:var(--accent)!important;background:transparent!important;} .main-header{background:linear-gradient(135deg,#1c2b3a,#0d1117);border:1px solid var(--border);border-left:3px solid var(--accent);padding:20px 24px;border-radius:6px;margin-bottom:20px;} .main-header h2{font-family:var(--font-mono);font-size:1.3rem;font-weight:600;color:var(--accent);} .main-header p{color:var(--text-secondary);margin-top:6px;font-size:13px;} .cim-box{background:#0d1a0d;border:1px solid var(--success);border-left:3px solid var(--success);border-radius:6px;padding:12px 16px;margin:10px 0;font-family:var(--font-mono);font-size:12px;color:#7ee787;} .cim-box .box-title{font-weight:600;color:var(--success);margin-bottom:6px;} .card{background:var(--bg-secondary);border:1px solid var(--border);border-radius:6px;margin-bottom:20px;} .card-header{background:var(--bg-tertiary);border-bottom:1px solid var(--border);padding:12px 16px;font-family:var(--font-mono);font-size:12px;color:var(--text-secondary);letter-spacing:.5px;text-transform:uppercase;} .card-body{padding:16px;} .form-control,.selectize-input{background:var(--bg-tertiary)!important;border:1px solid var(--border)!important;color:var(--text-primary)!important;border-radius:4px;font-size:13px;} .form-control:focus{border-color:var(--accent)!important;box-shadow:0 0 0 2px rgba(88,166,255,.2)!important;} label{color:var(--text-secondary);font-size:12px;margin-bottom:4px;} .btn{border-radius:4px;font-family:var(--font-mono);font-size:12px;font-weight:600;transition:all .15s;border:1px solid;} .btn-primary{background:var(--accent);border-color:var(--accent);color:#0d1117;} .btn-primary:hover{background:var(--accent-hover);border-color:var(--accent-hover);color:#0d1117;} .btn-info{background:transparent;border-color:var(--teal);color:var(--teal);} .btn-info:hover{background:var(--teal);color:#0d1117;} .btn-danger{background:transparent;border-color:var(--danger);color:var(--danger);} .btn-danger:hover{background:var(--danger);color:white;} .help-block{color:var(--text-muted);font-size:11px;margin-top:4px;} .dataTables_wrapper{color:var(--text-secondary)!important;} table.dataTable{background:var(--bg-secondary)!important;color:var(--text-primary)!important;border-color:var(--border)!important;} table.dataTable thead th{background:var(--bg-tertiary)!important;color:var(--text-secondary)!important;border-bottom:1px solid var(--border)!important;font-family:var(--font-mono);font-size:11px;letter-spacing:.5px;} table.dataTable tbody tr:hover{background:var(--bg-tertiary)!important;} table.dataTable tbody td{border-bottom:1px solid var(--border)!important;font-size:12px;} .dataTables_info,.dataTables_length,.dataTables_filter,.dataTables_paginate{color:var(--text-muted)!important;font-size:12px;} .dataTables_filter input,.dataTables_length select{background:var(--bg-tertiary)!important;border:1px solid var(--border)!important;color:var(--text-primary)!important;border-radius:3px;} .paginate_button{color:var(--text-secondary)!important;} .paginate_button.current{background:var(--accent)!important;color:#0d1117!important;border-color:var(--accent)!important;} .chromosome-container{margin:12px 0;padding:12px 16px;background:var(--bg-tertiary);border-radius:4px;border:1px solid var(--border);} .chromosome{height:24px;background:linear-gradient(to right,var(--bg-primary),var(--border));border-radius:12px;margin:8px 0;position:relative;overflow:hidden;border:1px solid var(--border);} .chromosome-marker{position:absolute;height:34px;width:6px;background:var(--text-muted);border-radius:3px;top:-5px;transform:translateX(-50%);transition:all .3s ease;} .chromosome-marker.significant{background:var(--danger)!important;height:40px!important;width:8px!important;top:-8px!important;} .chromosome-marker.flanking{background:var(--accent)!important;height:30px!important;width:5px!important;top:-3px!important;} .chromosome-marker.selection{background:var(--success)!important;} .chromosome-marker.highlighted{background:var(--warning)!important;box-shadow:0 0 10px rgba(210,153,34,.6);} .chromosome-marker.pulse{animation:pulse 1.5s infinite;} @keyframes pulse{0%,100%{transform:translateX(-50%) scale(1);}50%{transform:translateX(-50%) scale(1.3);opacity:.7;}} .chromosome-legend{display:flex;justify-content:space-between;font-size:10px;color:var(--text-muted);font-family:var(--font-mono);margin-top:2px;} .chromosome-title{font-family:var(--font-mono);font-size:11px;color:var(--accent);margin-bottom:4px;} #chat-panel{position:fixed;bottom:20px;right:20px;z-index:9999;width:440px;display:flex;flex-direction:column;} #chat-toggle-btn{align-self:flex-end;width:56px;height:56px;border-radius:50%;background:linear-gradient(135deg,var(--accent),var(--purple));border:none;cursor:pointer;display:flex;align-items:center;justify-content:center;box-shadow:0 4px 20px rgba(88,166,255,.4);transition:all .2s;color:#0d1117;font-size:24px;} #chat-toggle-btn:hover{transform:scale(1.05);} #chat-window{display:none;flex-direction:column;background:var(--bg-secondary);border:1px solid var(--accent);border-radius:12px;overflow:hidden;box-shadow:0 8px 40px rgba(0,0,0,.5);margin-bottom:10px;height:640px;} #chat-window.open{display:flex;} #chat-header{background:linear-gradient(135deg,var(--bg-tertiary),#1c2b3a);border-bottom:1px solid var(--border);padding:12px 16px;display:flex;flex-direction:column;gap:8px;} .chat-header-top{display:flex;align-items:center;justify-content:space-between;} .chat-title{display:flex;align-items:center;gap:10px;} .chat-avatar{width:32px;height:32px;background:linear-gradient(135deg,var(--accent),var(--purple));border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:16px;color:#0d1117;font-weight:bold;flex-shrink:0;} #chat-header h4{font-family:var(--font-mono);font-size:13px;font-weight:600;color:var(--text-primary);margin:0;} #chat-header p{font-size:11px;color:var(--text-muted);margin:0;} #chat-header p.ai-mode{color:var(--success);} #chat-close-btn{background:none;border:none;color:var(--text-muted);cursor:pointer;font-size:18px;padding:4px;transition:color .15s;} #chat-close-btn:hover{color:var(--text-primary);} .chat-model-selector{display:flex;align-items:center;gap:8px;padding:4px 0;} .chat-model-selector label{color:var(--text-muted);font-size:10px;font-family:var(--font-mono);white-space:nowrap;margin:0;} .chat-model-selector select{flex:1;background:var(--bg-primary)!important;border:1px solid var(--border)!important;color:var(--text-secondary)!important;border-radius:4px;font-size:11px;font-family:var(--font-mono);padding:3px 6px;} .model-status-dot{width:7px;height:7px;border-radius:50%;flex-shrink:0;} .model-status-dot.online{background:var(--success);box-shadow:0 0 6px var(--success);} .model-status-dot.offline{background:var(--warning);box-shadow:0 0 6px var(--warning);} .test-model-btn{background:transparent;border:1px solid var(--border);color:var(--text-muted);border-radius:3px;padding:2px 7px;font-size:10px;font-family:var(--font-mono);cursor:pointer;transition:all .15s;white-space:nowrap;} .test-model-btn:hover{border-color:var(--accent);color:var(--accent);} #chat_messages{flex:1;overflow-y:auto;padding:16px;display:flex;flex-direction:column;gap:12px;background:var(--bg-primary);} .chat-msg{max-width:92%;animation:fadeIn .3s ease;} @keyframes fadeIn{from{opacity:0;transform:translateY(10px);}to{opacity:1;transform:translateY(0);}} .chat-msg.user{align-self:flex-end;} .chat-msg.assistant{align-self:flex-start;} .chat-bubble{padding:12px 16px;border-radius:16px;font-size:13px;line-height:1.6;word-wrap:break-word;white-space:pre-wrap;} .chat-msg.user .chat-bubble{background:linear-gradient(135deg,var(--accent),#3a7bd5);color:#0d1117;border-bottom-right-radius:4px;} .chat-msg.assistant .chat-bubble{background:var(--bg-tertiary);color:var(--text-primary);border:1px solid var(--border);border-bottom-left-radius:4px;} .chat-bubble strong{color:var(--accent);} .chat-meta{font-size:10px;color:var(--text-muted);margin-top:4px;font-family:var(--font-mono);padding:0 4px;display:flex;align-items:center;gap:6px;} .chat-meta .model-tag{color:var(--purple);font-size:9px;} .typing-indicator{display:flex;gap:4px;padding:12px 16px;background:var(--bg-tertiary);border:1px solid var(--border);border-radius:16px;border-bottom-left-radius:4px;width:fit-content;} .typing-dot{width:8px;height:8px;background:var(--text-muted);border-radius:50%;animation:typingBounce 1.4s infinite;} .typing-dot:nth-child(2){animation-delay:.2s;} .typing-dot:nth-child(3){animation-delay:.4s;} @keyframes typingBounce{0%,60%,100%{transform:translateY(0);}30%{transform:translateY(-8px);}} .quick-questions{padding:8px 16px;display:flex;flex-wrap:wrap;gap:6px;border-bottom:1px solid var(--border);background:var(--bg-secondary);} .quick-q-btn{background:var(--bg-tertiary);border:1px solid var(--border);color:var(--text-secondary);border-radius:16px;padding:4px 12px;font-size:11px;cursor:pointer;transition:all .15s;} .quick-q-btn:hover{border-color:var(--accent);color:var(--accent);background:rgba(88,166,255,.1);} #chat-footer{padding:12px 16px;border-top:1px solid var(--border);background:var(--bg-tertiary);} #chat_input{width:100%;background:var(--bg-secondary)!important;border:1px solid var(--border)!important;border-radius:8px;color:var(--text-primary)!important;font-size:13px;resize:none;padding:10px 12px;font-family:var(--font-sans);margin-bottom:8px;} #chat_input:focus{border-color:var(--accent)!important;outline:none;} .chat-actions{display:flex;gap:8px;} #send_chat{flex:1;background:linear-gradient(135deg,var(--accent),#3a7bd5);color:#0d1117;border:none;border-radius:6px;padding:8px 16px;font-family:var(--font-mono);font-size:12px;font-weight:600;cursor:pointer;transition:all .15s;display:flex;align-items:center;justify-content:center;gap:6px;} #send_chat:hover:not(:disabled){transform:translateY(-1px);box-shadow:0 4px 12px rgba(88,166,255,.4);} #send_chat:disabled{opacity:.5;cursor:not-allowed;} #clear_chat{background:transparent;color:var(--text-muted);border:1px solid var(--border);border-radius:6px;padding:8px 12px;font-family:var(--font-mono);font-size:12px;cursor:pointer;transition:all .15s;} #clear_chat:hover{border-color:var(--danger);color:var(--danger);} ")) ), navbarPage( title = tags$span(tags$i(class = "fas fa-dna", style = "margin-right:8px;color:#58a6ff;"), "QTL-Mapper CIM"), id = "nav", # ---- DATA UPLOAD ---- tabPanel("Data Upload", icon = icon("upload"), div(class = "main-header", h2(tags$i(class = "fas fa-upload", style = "margin-right:8px;"), "Data Upload — CIM Mode"), p("Composite Interval Mapping: higher power, correct flanking markers, better PVE estimation") ), fluidRow( column(12, div(class = "cim-box", div(class = "box-title", tags$i(class = "fas fa-chart-line", style = "margin-right:6px;"), "CIM Method + PVE Formula"), tags$pre(style = "background:transparent;border:none;margin:0;color:#7ee787;font-size:11px;", "Composite Interval Mapping (Zeng 1993, 1994):\n", " For each marker m:\n", " 1. Cofactors = top K markers from RF (excluding nearby markers ±window on same chr)\n", " 2. Fit: lm(Y ~ marker_m + cofactors) → LOD = -log10(p_marker)\n", " 3. PVE_CIM (%) = R²_full × 100 [marker + cofactors — higher than single-marker PVE]\n", " 4. PVE_marker (%) = R² from lm(Y ~ a + d) [marker alone, add+dom model]\n\n", "Flanking fix: uses FULL marker table (not post-NZV subset)\n", "Ref: Zeng (1993) PNAS; Falconer & Mackay (1996); Lynch & Walsh (1998)") ) ) ), fluidRow( column(4, div(class = "card", div(class = "card-header", tags$i(class = "fas fa-table", style = "margin-right:6px;"), "Training Data"), div(class = "card-body", fileInput("genotype_file", "Training Genotype CSV", accept = ".csv", buttonLabel = "Browse"), helpText("Row1=header(id,markers), Row2=chromosomes, Row3=positions, rest=samples. Coded 0/1/2."), fileInput("phenotype_file", "Training Phenotype CSV", accept = ".csv", buttonLabel = "Browse"), helpText("id column + numeric trait columns."), selectInput("phenotype_column", "Select Phenotype Column", choices = NULL) ) ) ), column(4, div(class = "card", div(class = "card-header", tags$i(class = "fas fa-sliders-h", style = "margin-right:6px;color:#bc8cff;"), "CIM Parameters"), div(class = "card-body", sliderInput("test_size", "Validation Proportion", min = 0.1, max = 0.5, value = 0.2, step = 0.05), numericInput("lod_threshold","LOD Threshold", value = 2.0, min = 0.5, max = 10.0, step = 0.1), numericInput("n_cofactors", "CIM Cofactors (K)", value = 10, min = 1, max = 30, step = 1), helpText("More cofactors = better background control, slower. Try 5-15."), numericInput("window_size", "Exclusion Window (±markers)", value = 10, min = 1, max = 30, step = 1), helpText("Nearby markers excluded from cofactors to avoid collinearity."), actionButton("run_analysis", "Run CIM Analysis", class = "btn-primary btn-block", icon = icon("play")) ) ) ), column(4, div(class = "card", div(class = "card-header", tags$i(class = "fas fa-vial", style = "margin-right:6px;color:#3fb950;"), "Test Data (Optional)"), div(class = "card-body", fileInput("test_genotype_file", "Test Genotype CSV", accept = ".csv", buttonLabel = "Browse"), helpText("Same format as training genotype."), tags$br(), fileInput("pop_file", "Population Metadata CSV", accept = ".csv", buttonLabel = "Browse"), helpText("Columns: id, population (e.g. Domesticated/Wild)."), actionButton("predict_test_phenotype", "Predict Test Phenotypes", class = "btn-info btn-block", icon = icon("magic")) ) ) ) ), fluidRow( column(12, div(class = "card", div(class = "card-header", "Data Preview"), div(class = "card-body", tabsetPanel( tabPanel("Training Genotype", DTOutput("geno_preview")), tabPanel("Training Phenotype", DTOutput("pheno_preview")), tabPanel("Test Genotype", DTOutput("test_geno_preview")), tabPanel("Predicted Test Phenotype", DTOutput("predicted_test_pheno_preview")) ) ) ) ) ) ), # ---- RESULTS ---- tabPanel("Results", icon = icon("chart-line"), div(class = "main-header", h2(tags$i(class = "fas fa-chart-line", style = "margin-right:8px;"), "CIM Results"), p("LOD genome scan, flanking markers, additive + dominance PVE, model performance") ), fluidRow( column(6, div(class = "card", div(class = "card-header", "CIM Manhattan Plot (LOD Scores)"), div(class = "card-body", plotlyOutput("lod_plot_2d", height = "500px")))), column(6, div(class = "card", div(class = "card-header", "Chromosome Visualization"), div(class = "card-body", uiOutput("chromosome_viz"), div(style = "margin:12px 0;display:flex;gap:8px;", actionButton("simulate_btn", "Simulate Discovery", class = "btn-info"), actionButton("reset_btn", "Reset", class = "btn-danger") ) ) )) ), fluidRow( column(4, div(class = "card", div(class = "card-header", "Model Performance"), div(class = "card-body", plotlyOutput("performance_plot")))), column(4, div(class = "card", div(class = "card-header", "Train: Predicted vs Observed"), div(class = "card-body", plotlyOutput("regression_plot_train", height = "300px")))), column(4, div(class = "card", div(class = "card-header", "Validation: Predicted vs Observed"), div(class = "card-body", plotlyOutput("regression_plot_test", height = "300px")))) ), fluidRow( column(12, div(class = "card", div(class = "card-header", "CIM QTL Effects — All markers scanned (Additive + Dominance PVE)"), div(class = "card-body", DTOutput("qtl_effects_table_train"), tags$br(), downloadButton("download_train_results", "Download CIM Results (.xlsx)") ) )) ), fluidRow( column(12, div(class = "card", div(class = "card-header", "Epistasis Analysis"), div(class = "card-body", DTOutput("epistasis_table"), plotlyOutput("epistasis_heatmap", height = "400px") ) )) ) ), # ---- DOMESTICATION ---- tabPanel("Domestication", icon = icon("leaf"), div(class = "main-header", h2(tags$i(class = "fas fa-leaf", style = "margin-right:8px;"), "Domestication Analysis"), p("Fst, Tajima's D, nucleotide diversity — needs population metadata") ), fluidRow( column(4, div(class = "card", div(class = "card-header", "Parameters"), div(class = "card-body", numericInput("fst_threshold", "Fst Threshold", value = 0.1, min = 0.05, max = 0.5, step = 0.01), numericInput("tajima_threshold", "Tajima's D Threshold", value = -1, min = -5, max = 0, step = 0.1), actionButton("run_domestication", "Run Domestication Analysis", class = "btn-primary btn-block", icon = icon("play")) ) ) ), column(8, div(class = "card", div(class = "card-header", "Population Data Preview"), div(class = "card-body", DTOutput("pop_preview")) ) ) ), fluidRow( column(6, div(class = "card", div(class = "card-header", "Fst Manhattan Plot"), div(class = "card-body", plotlyOutput("fst_plot", height = "400px")))), column(6, div(class = "card", div(class = "card-header", "Tajima's D Manhattan Plot"),div(class = "card-body", plotlyOutput("tajima_plot", height = "400px")))) ), fluidRow( column(12, div(class = "card", div(class = "card-header", "Selection Signatures"), div(class = "card-body", DTOutput("selection_table"), tags$br(), downloadButton("download_selection", "Download Selection Results") ) ) ) ) ), # ---- INTERPRETATION ---- tabPanel("Interpretation", icon = icon("lightbulb"), div(class = "main-header", h2(tags$i(class = "fas fa-lightbulb", style = "margin-right:8px;"), "Results Interpretation"), p("CIM QTL interpretation: PVE_marker vs PVE_CIM, flanking regions, dominance class") ), fluidRow(column(12, div(class = "card", div(class = "card-header", "Analysis Summary"), div(class = "card-body", uiOutput("analysis_summary"))))), fluidRow( column(6, div(class = "card", div(class = "card-header", "QTL Significance"), div(class = "card-body", uiOutput("qtl_interpretation")))), column(6, div(class = "card", div(class = "card-header", "Effect Sizes (Add + Dom)"), div(class = "card-body", uiOutput("effect_interpretation")))) ), fluidRow(column(12, div(class = "card", div(class = "card-header", "Epistasis"), div(class = "card-body", uiOutput("epistasis_interpretation"))))), fluidRow(column(12, div(class = "card", div(class = "card-header", "Recommendations"), div(class = "card-body", uiOutput("recommendations"))))) ), # ---- ABOUT ---- tabPanel("About", icon = icon("info-circle"), div(class = "main-header", h2(tags$i(class = "fas fa-info-circle", style = "margin-right:8px;"), "About QTL-Mapper CIM v3") ), fluidRow( column(8, offset = 2, div(class = "card", div(class = "card-body", h4(style = "color:#58a6ff;font-family:'IBM Plex Mono';margin-bottom:12px;", "What Changed in v3"), div(class = "cim-box", tags$pre(style = "background:transparent;border:none;margin:0;color:#7ee787;font-size:11px;", "FIX 1 — PVE now reports two values:\n", " PVE_Marker_% = R² from lm(y ~ a + d) [marker alone]\n", " PVE_CIM_% = R² from lm(y ~ marker + cofactors) [full CIM model]\n", " → PVE_CIM is always ≥ PVE_Marker; often much higher\n\n", "FIX 2 — Flanking markers fixed:\n", " OLD: used colnames(X_train) after NZV removal → flanking lookup FAILED\n", " NEW: uses all_markers table (full set before NZV removal)\n", " Position-based fallback if marker not found by name\n\n", "METHOD — Composite Interval Mapping (Zeng 1993, PNAS):\n", " For each marker: fit lm(Y ~ focal_marker + K_cofactors)\n", " Cofactors selected by RF importance, excluding nearby markers\n", " LOD = -log10(p-value of focal marker term)\n", " This controls background genetic variance → higher power & PVE") ), h4(style = "color:#58a6ff;font-family:'IBM Plex Mono';margin:16px 0 8px;", "Thresholds"), tags$ul(style = "color:#8b949e;line-height:2;", tags$li("LOD > 2: Suggestive QTL | LOD > 3: Significant | LOD > 5: Highly significant"), tags$li("PVE_CIM > 20%: Major QTL | 10-20%: Moderate | <10%: Minor"), tags$li("|d/a| > 1: Overdominance | ~1: Complete dominance | <0.5: Additive"), tags$li("Fst > 0.2: Strong differentiation | Tajima's D < -2: Selective sweep") ) ) ) ) ) ) ), # ============================================================ # FLOATING CHAT # ============================================================ tags$div(id = "chat-panel", tags$div(id = "chat-window", tags$div(id = "chat-header", tags$div(class = "chat-header-top", tags$div(class = "chat-title", tags$div(class = "chat-avatar", "AI"), tags$div( tags$h4("QTL-CIM AI Assistant"), tags$p(id = "model_status_text", if (token_exists) "AI mode ready" else "Rule-based mode", class = if (token_exists) "ai-mode" else "") ) ), tags$button(id = "chat-close-btn", onclick = "document.getElementById('chat-window').classList.remove('open');", tags$i(class = "fas fa-times")) ), tags$div(class = "chat-model-selector", tags$label(tags$i(class = "fas fa-robot"), " Model:"), tags$div(id = "model_status_dot", class = paste0("model-status-dot ", if (token_exists) "online" else "offline")), selectInput("selected_model", label = NULL, choices = model_choices, selected = default_model, width = "100%"), actionButton("test_model_btn", "Test", class = "test-model-btn") ) ), tags$div(class = "quick-questions", tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q','What is PVE in CIM?',{priority:'event'});", "PVE / CIM"), tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q','Show top QTLs',{priority:'event'});", "Top QTLs"), tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q','Show flanking markers',{priority:'event'});", "Flanking"), tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q','Why is my R2 negative?',{priority:'event'});","Negative R²") ), tags$div(id = "chat_messages", uiOutput("chat_display")), tags$div(id = "chat-footer", tags$textarea(id = "chat_input", placeholder = "Ask about CIM results... (Enter to send)", rows = "2"), tags$div(class = "chat-actions", actionButton("send_chat", "Send", icon = icon("paper-plane"), class = "btn-primary"), actionButton("clear_chat", "Clear", icon = icon("trash-alt"), class = "btn-danger") ) ) ), tags$button(id = "chat-toggle-btn", onclick = "document.getElementById('chat-window').classList.toggle('open');", tags$i(class = "fas fa-robot")) ) ) # ============================================================ # SERVER # ============================================================ server <- function(input, output, session) { values <- reactiveValues( genotype_data = NULL, phenotype_data = NULL, test_genotype_data = NULL, predicted_test_phenotype_data = NULL, all_markers = NULL, chromosome_info = NULL, position_info = NULL, cim_all = NULL, # Full CIM scan results qtl_effects_train = NULL, # Significant QTLs with flanking performance_metrics = NULL, train_predictions = NULL, test_predictions = NULL, epistasis_all = NULL, epistasis_sig = NULL, pop_data = NULL, selection_metrics = NULL, model_fit = NULL, chat_messages = list(), is_typing = FALSE, lod_threshold = 2, current_model = default_model ) # ---- Model selector ---- observe({ req(input$selected_model) values$current_model <- input$selected_model }) observeEvent(input$test_model_btn, { req(input$selected_model) add_message("assistant", paste0("⏳ Testing model: **", input$selected_model, "**...")) result <- test_api_connection(input$selected_model) if (result$success) { add_message("assistant", paste0("✅ **", input$selected_model, "** is working!")) shinyjs::runjs("document.getElementById('model_status_dot').className='model-status-dot online';") } else { add_message("assistant", paste0("❌ Failed: ", result$error)) shinyjs::runjs("document.getElementById('model_status_dot').className='model-status-dot offline';") } }) # ---- Chat helpers ---- add_message <- function(role, content, model_used = NULL) { values$chat_messages <- c(values$chat_messages, list(list(role = role, content = content, time = format(Sys.time(), "%H:%M"), model = model_used))) if (length(values$chat_messages) > 100) values$chat_messages <- tail(values$chat_messages, 100) session$sendCustomMessage("scrollChatBottom", list()) } process_message <- function(user_text) { if (nchar(trimws(user_text)) == 0) return() add_message("user", user_text) values$is_typing <- TRUE model_id <- isolate(values$current_model) response <- generate_ai_response(user_text, values, model_id = model_id) values$is_typing <- FALSE add_message("assistant", response, model_used = if (token_exists) gsub(".*/", "", model_id) else NULL) } observeEvent(input$send_chat, { user_text <- trimws(input$chat_input) if (nchar(user_text) == 0) return() updateTextAreaInput(session, "chat_input", value = "") process_message(user_text) }) observeEvent(input$quick_q, { req(input$quick_q); process_message(input$quick_q) }) observeEvent(input$clear_chat, { values$chat_messages <- list() add_message("assistant", "Chat cleared. How can I help?") }) observe({ if (length(values$chat_messages) == 0) { add_message("assistant", paste0( "👋 Vanakam! I'm TerraByte-AI powered assistant (CIM v3)\n\n", "**What's new:**\n", "• CIM (Composite Interval Mapping) — higher PVE, better power\n", "• Flanking markers fixed — uses full marker table\n", "• Two PVE values: PVE_marker (add+dom alone) & PVE_CIM (full model)\n\n", "Upload data and run CIM analysis to get started!\n", " Query : contact at ashmithamganesan@gmail.com, P.sinha@cgiar.org" )) } }) output$chat_display <- renderUI({ msgs <- values$chat_messages if (length(msgs) == 0) return(NULL) elems <- lapply(msgs, function(msg) { content_html <- HTML(gsub("\n", "<br>", htmltools::htmlEscape(msg$content))) div(class = paste("chat-msg", msg$role), div(class = "chat-bubble", content_html), div(class = "chat-meta", span(msg$time), if (!is.null(msg$model) && msg$role == "assistant") span(class = "model-tag", paste0("[", msg$model, "]")) ) ) }) if (values$is_typing) { elems <- c(elems, list(div(class = "chat-msg assistant", div(class = "typing-indicator", div(class = "typing-dot"), div(class = "typing-dot"), div(class = "typing-dot"))))) } do.call(tagList, elems) }) # ============================================================ # DATA LOADING # ============================================================ observeEvent(input$genotype_file, { req(input$genotype_file) tryCatch({ all_data <- readLines(input$genotype_file$datapath) if (length(all_data) < 4) { showNotification("Need ≥4 rows", type = "error"); return() } header <- strsplit(all_data[1], ",")[[1]] chromosome_row <- strsplit(all_data[2], ",")[[1]] position_row <- strsplit(all_data[3], ",")[[1]] genotype_data <- read.csv(text = paste(all_data[-(1:3)], collapse = "\n"), header = FALSE) colnames(genotype_data) <- header rownames(genotype_data) <- genotype_data[, 1] genotype_data <- genotype_data[, -1] for (col in colnames(genotype_data)) genotype_data[[col]] <- as.numeric(as.character(genotype_data[[col]])) values$genotype_data <- genotype_data values$chromosome_info <- chromosome_row[-1] values$position_info <- suppressWarnings(as.numeric(position_row[-1])) values$all_markers <- data.frame( Marker = colnames(genotype_data), Chromosome = chromosome_row[-1], Position = suppressWarnings(as.numeric(position_row[-1])), stringsAsFactors = FALSE) showNotification(paste("Loaded", ncol(genotype_data), "markers,", nrow(genotype_data), "samples"), type = "message") add_message("assistant", paste0("✅ Genotype: **", ncol(genotype_data), " markers**, **", nrow(genotype_data), " samples**")) }, error = function(e) showNotification(paste("Geno error:", e$message), type = "error")) }) observeEvent(input$phenotype_file, { req(input$phenotype_file) tryCatch({ pd <- read.csv(input$phenotype_file$datapath) rownames(pd) <- pd[, 1]; pd <- pd[, -1] for (col in colnames(pd)) pd[[col]] <- as.numeric(as.character(pd[[col]])) values$phenotype_data <- pd updateSelectInput(session, "phenotype_column", choices = colnames(pd), selected = colnames(pd)[1]) showNotification(paste("Loaded", ncol(pd), "traits"), type = "message") add_message("assistant", paste0("✅ Phenotype: **", ncol(pd), " traits**, **", nrow(pd), " samples**")) }, error = function(e) showNotification(paste("Pheno error:", e$message), type = "error")) }) observeEvent(input$pop_file, { req(input$pop_file) tryCatch({ pd <- read.csv(input$pop_file$datapath) if (!all(c("id", "population") %in% colnames(pd))) { showNotification("Need 'id' and 'population' columns", type = "error"); return() } values$pop_data <- pd showNotification(paste("Population data:", nrow(pd), "samples"), type = "message") }, error = function(e) showNotification(paste("Pop error:", e$message), type = "error")) }) observeEvent(input$test_genotype_file, { req(input$test_genotype_file) tryCatch({ all_data <- readLines(input$test_genotype_file$datapath) header <- strsplit(all_data[1], ",")[[1]] gd <- read.csv(text = paste(all_data[-(1:3)], collapse = "\n"), header = FALSE) colnames(gd) <- header; rownames(gd) <- gd[, 1]; gd <- gd[, -1] for (col in colnames(gd)) gd[[col]] <- as.numeric(as.character(gd[[col]])) values$test_genotype_data <- gd showNotification("Test genotype loaded", type = "message") }, error = function(e) showNotification(paste("Test geno error:", e$message), type = "error")) }) output$geno_preview <- renderDT({ req(input$genotype_file); datatable(head(read.csv(input$genotype_file$datapath), 10), options = list(scrollX = TRUE, pageLength = 5)) }) output$pheno_preview <- renderDT({ req(input$phenotype_file); datatable(head(read.csv(input$phenotype_file$datapath), 10), options = list(scrollX = TRUE, pageLength = 5)) }) output$test_geno_preview <- renderDT({ req(input$test_genotype_file); datatable(head(read.csv(input$test_genotype_file$datapath), 10), options = list(scrollX = TRUE, pageLength = 5)) }) output$pop_preview <- renderDT({ req(input$pop_file); datatable(head(read.csv(input$pop_file$datapath), 10), options = list(scrollX = TRUE, pageLength = 5)) }) output$predicted_test_pheno_preview <- renderDT({ req(values$predicted_test_phenotype_data); datatable(values$predicted_test_phenotype_data, options = list(scrollX = TRUE, pageLength = 5)) }) # ============================================================ # MAIN CIM ANALYSIS # ============================================================ observeEvent(input$run_analysis, { req(values$genotype_data, values$phenotype_data, input$phenotype_column) showNotification("Starting CIM analysis...", type = "message") values$lod_threshold <- input$lod_threshold tryCatch({ common_samples <- intersect(rownames(values$genotype_data), rownames(values$phenotype_data)) if (length(common_samples) == 0) { showNotification("No common samples", type = "error"); return() } X <- values$genotype_data[common_samples, , drop = FALSE] y <- as.numeric(values$phenotype_data[common_samples, input$phenotype_column]) set.seed(123) train_index <- createDataPartition(y, p = 1 - input$test_size, list = FALSE) X_train <- X[train_index, , drop = FALSE]; X_val <- X[-train_index, , drop = FALSE] y_train <- y[train_index]; y_val <- y[-train_index] # ---- Run CIM scan ---- withProgress(message = "Running CIM genome scan...", value = 0.1, { cim_results <- run_cim( genotype_matrix = X_train, phenotype_vector = y_train, marker_info = values$all_markers, # FULL marker table — key fix n_cofactors = input$n_cofactors, window_size = input$window_size, lod_threshold = input$lod_threshold ) incProgress(0.7) }) values$cim_all <- cim_results # ---- Extract significant QTLs and add FIXED flanking ---- if (!"Message" %in% colnames(cim_results)) { sig_qtls <- cim_results[cim_results$LOD >= input$lod_threshold, ] if (nrow(sig_qtls) > 0) { # Add flanking using FULL all_markers table sig_qtls <- add_flanking_markers(sig_qtls, values$all_markers) values$qtl_effects_train <- sig_qtls[order(-sig_qtls$LOD), ] } else { values$qtl_effects_train <- data.frame(Message = paste("No QTLs above LOD", input$lod_threshold)) } } else { values$qtl_effects_train <- cim_results } # ---- RF model for prediction (separate from CIM mapping) ---- nzv <- nearZeroVar(X_train) X_tr_rf <- if (length(nzv) > 0) X_train[, -nzv, drop = FALSE] else X_train X_v_rf <- X_val[, colnames(X_tr_rf), drop = FALSE] model <- tryCatch( train(x = X_tr_rf, y = y_train, method = "rf", trControl = trainControl(method = "cv", number = 5), importance = TRUE, tuneLength = 3), error = function(e) { train(x = X_tr_rf, y = y_train, method = "lm", trControl = trainControl(method = "cv", number = 5)) }) values$model_fit <- model y_train_pred <- predict(model, X_tr_rf) y_val_pred <- predict(model, X_v_rf) train_r2 <- 1 - sum((y_train - y_train_pred)^2) / sum((y_train - mean(y_train))^2) val_r2 <- 1 - sum((y_val - y_val_pred)^2) / sum((y_val - mean(y_val))^2) values$performance_metrics <- data.frame( Metric = c("R² (Train)", "R (Train)", "R² (Validation)", "R (Validation)"), Value = c(train_r2, cor(y_train, y_train_pred), val_r2, cor(y_val, y_val_pred)), stringsAsFactors = FALSE) values$train_predictions <- data.frame(Observed = y_train, Predicted = y_train_pred) values$test_predictions <- data.frame(Observed = y_val, Predicted = y_val_pred) # ---- Epistasis ---- if (!is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train)) { sig_markers <- values$qtl_effects_train$Marker all_markers_v <- colnames(X_train) epi_list <- list() withProgress(message = "Calculating epistasis...", value = 0, { for (m1 in sig_markers) { for (m2 in all_markers_v) { if (m1 == m2) next tryCatch({ d <- data.frame(y = y_train, m1 = X_train[, m1], m2 = X_train[, m2]) d <- na.omit(d) if (nrow(d) < 10) next fit <- lm(y ~ m1 * m2, data = d) ct <- summary(fit)$coefficients if ("m1:m2" %in% rownames(ct)) { epi_list[[length(epi_list) + 1]] <- data.frame( QTL1 = m1, QTL2 = m2, Interaction_p = ct["m1:m2", "Pr(>|t|)"], Effect_Size = coef(fit)["m1:m2"], stringsAsFactors = FALSE) } }, error = function(e) {}) } } }) if (length(epi_list) > 0) { ea <- do.call(rbind, epi_list) values$epistasis_all <- ea values$epistasis_sig <- ea[ea$Interaction_p < 0.05, ] } else { values$epistasis_all <- data.frame(Message = "No epistatic interactions found") values$epistasis_sig <- data.frame(Message = "No epistatic interactions found") } } n_qtl <- if (!is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train)) nrow(values$qtl_effects_train) else 0 max_pve_cim <- if (n_qtl > 0) round(max(values$qtl_effects_train$PVE_CIM_Percent), 1) else 0 showNotification("CIM analysis completed!", type = "message") add_message("assistant", paste0( "✅ **CIM analysis complete!**\n\n", "• Found **", n_qtl, " QTLs** above LOD ", input$lod_threshold, "\n", "• Top QTL PVE_CIM: **", max_pve_cim, "%** (full CIM model)\n", "• Validation R²: **", round(val_r2, 3), "**\n", "• Flanking markers: ✅ fixed (uses full marker table)\n\n", "Ask me about PVE, flanking markers, or top QTLs!" )) updateTabsetPanel(session, "nav", selected = "Results") }, error = function(e) { showNotification(paste("CIM Error:", e$message), type = "error") cat("CIM ERROR:", e$message, "\n") }) }) # ============================================================ # PREDICT TEST PHENOTYPES # ============================================================ observeEvent(input$predict_test_phenotype, { req(values$model_fit, values$test_genotype_data) tryCatch({ common_m <- intersect(colnames(values$test_genotype_data), colnames(values$genotype_data)) if (length(common_m) == 0) { showNotification("No common markers", type = "error"); return() } X_test <- values$test_genotype_data[, common_m, drop = FALSE] preds <- predict(values$model_fit, newdata = X_test) values$predicted_test_phenotype_data <- data.frame( id = rownames(X_test), Predicted_Phenotype = as.numeric(preds), stringsAsFactors = FALSE) showNotification("Predictions done!", type = "message") }, error = function(e) showNotification(paste("Predict error:", e$message), type = "error")) }) # ============================================================ # DOMESTICATION # ============================================================ calculate_selection_metrics <- function(geno_mat, pop_data, marker_info) { metrics_list <- list() for (marker in colnames(geno_mat)) { geno <- geno_mat[, marker] pop <- pop_data$population[match(rownames(geno_mat), pop_data$id)] valid_idx <- !is.na(geno) & !is.na(pop) geno <- geno[valid_idx]; pop <- pop[valid_idx] if (length(unique(pop)) < 2) next gd <- geno[pop == "Domesticated"]; gw <- geno[pop == "Wild"] if (length(gd) < 3 || length(gw) < 3) next fd <- mean(gd, na.rm = TRUE) / 2; fw <- mean(gw, na.rm = TRUE) / 2 pa <- (fd + fw) / 2 fst <- if (pa > 0 && pa < 1) { f <- (fd - fw)^2 / (pa * (1 - pa)); f / (1 + f) } else 0 pi_d <- 2 * fd * (1 - fd); pi_w <- 2 * fw * (1 - fw) td_d <- tryCatch((pi_d - 1/length(gd)) / sqrt(var(gd)/length(gd)), error = function(e) NA) td_w <- tryCatch((pi_w - 1/length(gw)) / sqrt(var(gw)/length(gw)), error = function(e) NA) mr <- marker_info[marker_info$Marker == marker, ] metrics_list[[marker]] <- data.frame( Marker = marker, Chromosome = ifelse(nrow(mr) > 0, mr$Chromosome[1], NA), Position = ifelse(nrow(mr) > 0, mr$Position[1], NA), Fst = fst, Pi_Dom = pi_d, Pi_Wild = pi_w, Tajima_D_Dom = td_d, Tajima_D_Wild = td_w, stringsAsFactors = FALSE) } if (length(metrics_list) == 0) return(NULL) do.call(rbind, metrics_list) } observeEvent(input$run_domestication, { req(values$genotype_data, values$pop_data, values$all_markers) tryCatch({ cs <- intersect(rownames(values$genotype_data), values$pop_data$id) if (length(cs) == 0) { showNotification("No common samples", type = "error"); return() } X <- values$genotype_data[cs, , drop = FALSE] ps <- values$pop_data[values$pop_data$id %in% cs, ] sel <- calculate_selection_metrics(X, ps, values$all_markers) if (is.null(sel)) { showNotification("No selection metrics", type = "error"); return() } sel$Significant <- sel$Fst > input$fst_threshold | sel$Tajima_D_Dom < input$tajima_threshold values$selection_metrics <- sel showNotification(paste("Domestication done:", sum(sel$Significant, na.rm = TRUE), "signatures"), type = "message") }, error = function(e) showNotification(paste("Dom error:", e$message), type = "error")) }) # ============================================================ # MANHATTAN HELPER # ============================================================ create_manhattan <- function(data, y_col, title, threshold, y_label = y_col) { if (is.null(data) || nrow(data) == 0 || "Message" %in% colnames(data)) return(plot_ly() %>% layout(title = "No data — run analysis first", plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))) pd <- data[!is.na(data[[y_col]]) & !is.na(data$Chromosome), ] if (nrow(pd) == 0) return(plot_ly() %>% layout(title = "No valid data", plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))) chroms <- unique(pd$Chromosome) chrom_pos <- data.frame() for (i in seq_along(chroms)) { cd <- pd[pd$Chromosome == chroms[i], ] if (nrow(cd) > 0) { cd$ChromIndex <- i cd$PosScaled <- cd$Position / max(cd$Position, na.rm = TRUE) + (i - 1) chrom_pos <- rbind(chrom_pos, cd) } } p <- plot_ly() %>% add_trace(data = chrom_pos, x = ~PosScaled, y = as.formula(paste0("~", y_col)), type = "scatter", mode = "markers", color = ~factor(Chromosome), colors = viridis(length(chroms)), marker = list(size = 6, opacity = 0.7), text = ~paste("Marker:", Marker, "<br>Chr:", Chromosome, "<br>Pos:", Position, "<br>", y_label, ":", round(get(y_col), 3)), hoverinfo = "text", showlegend = FALSE) if (!is.null(threshold) && !is.na(threshold)) p <- p %>% add_segments( x = min(chrom_pos$PosScaled, na.rm = TRUE), xend = max(chrom_pos$PosScaled, na.rm = TRUE), y = threshold, yend = threshold, line = list(color = "red", dash = "dash", width = 1)) p %>% layout(title = title, xaxis = list(title = "Chromosome", ticktext = chroms, tickvals = tapply(chrom_pos$PosScaled, chrom_pos$Chromosome, median, na.rm = TRUE), tickangle = 45), yaxis = list(title = y_label), plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e")) } # ============================================================ # PLOTS # ============================================================ output$lod_plot_2d <- renderPlotly({ req(values$cim_all) create_manhattan(values$cim_all, "LOD", "CIM Manhattan Plot (LOD Scores)", input$lod_threshold, "LOD Score") }) output$fst_plot <- renderPlotly({ req(values$selection_metrics); create_manhattan(values$selection_metrics, "Fst", "Fst Plot", input$fst_threshold, "Fst") }) output$tajima_plot <- renderPlotly({ req(values$selection_metrics) if ("Message" %in% colnames(values$selection_metrics)) return(plot_ly() %>% layout(title = "No data", plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))) d <- values$selection_metrics chroms <- unique(d$Chromosome) cp <- data.frame() for (i in seq_along(chroms)) { cd <- d[d$Chromosome == chroms[i], ] if (nrow(cd) > 0) { cd$PosScaled <- cd$Position / max(cd$Position, na.rm = TRUE) + (i - 1); cp <- rbind(cp, cd) } } plot_ly() %>% add_trace(data = cp, x = ~PosScaled, y = ~Tajima_D_Dom, type = "scatter", mode = "markers", name = "Domesticated", marker = list(size = 5, color = "#58a6ff", opacity = .7)) %>% add_trace(data = cp, x = ~PosScaled, y = ~Tajima_D_Wild, type = "scatter", mode = "markers", name = "Wild", marker = list(size = 5, color = "#f97316", opacity = .7)) %>% add_segments(x = min(cp$PosScaled, na.rm = TRUE), xend = max(cp$PosScaled, na.rm = TRUE), y = input$tajima_threshold, yend = input$tajima_threshold, line = list(color = "red", dash = "dash", width = 1)) %>% layout(title = "Tajima's D", xaxis = list(title = "Chromosome", ticktext = chroms, tickvals = tapply(cp$PosScaled, cp$Chromosome, median, na.rm = TRUE), tickangle = 45), yaxis = list(title = "Tajima's D"), plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e")) }) output$performance_plot <- renderPlotly({ req(values$performance_metrics) plot_ly(data = values$performance_metrics, x = ~Metric, y = ~Value, type = "bar", marker = list(color = c("#58a6ff","#58a6ff","#3fb950","#3fb950")), text = ~round(Value, 3), textposition = "outside") %>% layout(title = "Model Performance (RF for Prediction)", yaxis = list(title = "Value", range = c(0, 1.1)), plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e")) }) output$regression_plot_train <- renderPlotly({ req(values$train_predictions) plot_ly(data = values$train_predictions, x = ~Observed, y = ~Predicted, type = "scatter", mode = "markers", marker = list(size = 6, color = "#58a6ff", opacity = .7)) %>% add_trace(x = range(values$train_predictions$Observed), y = range(values$train_predictions$Observed), type = "scatter", mode = "lines", line = list(color = "#f85149", dash = "dash")) %>% layout(title = "Training Set", xaxis = list(title = "Observed"), yaxis = list(title = "Predicted"), plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e")) }) output$regression_plot_test <- renderPlotly({ req(values$test_predictions) plot_ly(data = values$test_predictions, x = ~Observed, y = ~Predicted, type = "scatter", mode = "markers", marker = list(size = 6, color = "#3fb950", opacity = .7)) %>% add_trace(x = range(values$test_predictions$Observed), y = range(values$test_predictions$Observed), type = "scatter", mode = "lines", line = list(color = "#f85149", dash = "dash")) %>% layout(title = "Validation Set", xaxis = list(title = "Observed"), yaxis = list(title = "Predicted"), plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e")) }) output$epistasis_heatmap <- renderPlotly({ req(values$epistasis_all) if ("Message" %in% colnames(values$epistasis_all)) return(plot_ly() %>% layout(title = values$epistasis_all$Message[1], plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))) qtls <- unique(values$epistasis_all$QTL1) mks <- unique(values$epistasis_all$QTL2) pm <- matrix(NA, nrow = length(qtls), ncol = length(mks), dimnames = list(qtls, mks)) for (i in 1:nrow(values$epistasis_all)) pm[values$epistasis_all$QTL1[i], values$epistasis_all$QTL2[i]] <- -log10(values$epistasis_all$Interaction_p[i]) plot_ly(x = colnames(pm), y = rownames(pm), z = pm, type = "heatmap", colorscale = "Viridis") %>% layout(title = "Epistatic Interactions (-log10 p)", xaxis = list(title = "Marker", tickangle = 45), yaxis = list(title = "QTL"), plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e")) }) # ============================================================ # TABLES # ============================================================ output$qtl_effects_table_train <- renderDT({ req(values$qtl_effects_train) if ("Message" %in% colnames(values$qtl_effects_train)) return(datatable(data.frame(Status = values$qtl_effects_train$Message[1]), options = list(dom = "t"))) display_cols <- intersect( c("Marker", "Chromosome", "Position", "LOD", "P_Value", "PVE_Marker_Percent", "PVE_CIM_Percent", "Additive_Effect", "SE_Additive", "CI_Lower", "CI_Upper", "Dominance_Effect", "SE_Dominance", "Dominance_Ratio", "Dominance_Class", "N_Cofactors", "N_Samples", "N_Heterozygotes", "Low_Flank", "High_Flank"), colnames(values$qtl_effects_train)) datatable(values$qtl_effects_train[, display_cols], options = list(pageLength = 10, scrollX = TRUE), rownames = FALSE, caption = "PVE_Marker = R²(lm(y~a+d))×100 | PVE_CIM = R²(lm(y~marker+cofactors))×100") %>% formatRound(intersect(c("LOD","PVE_Marker_Percent","PVE_CIM_Percent", "Additive_Effect","SE_Additive","CI_Lower","CI_Upper", "Dominance_Effect","SE_Dominance","Dominance_Ratio"), display_cols), 3) %>% formatSignif(intersect(c("P_Value"), display_cols), digits = 3) }) output$epistasis_table <- renderDT({ req(values$epistasis_sig) if ("Message" %in% colnames(values$epistasis_sig)) return(datatable(data.frame(Status = values$epistasis_sig$Message[1]), options = list(dom = "t"))) datatable(values$epistasis_sig[order(values$epistasis_sig$Interaction_p), ], options = list(pageLength = 10, scrollX = TRUE), rownames = FALSE) %>% formatSignif(c("Interaction_p", "Effect_Size"), digits = 4) }) output$selection_table <- renderDT({ req(values$selection_metrics) if ("Message" %in% colnames(values$selection_metrics)) return(datatable(data.frame(Status = values$selection_metrics$Message[1]), options = list(dom = "t"))) df <- values$selection_metrics if (!is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train)) df$QTL_Overlap <- df$Marker %in% values$qtl_effects_train$Marker dc <- intersect(c("Marker","Chromosome","Fst","Pi_Dom","Pi_Wild","Tajima_D_Dom","Significant","QTL_Overlap"), colnames(df)) datatable(df[order(-df$Fst), dc], options = list(pageLength = 10, scrollX = TRUE), rownames = FALSE) %>% formatRound(c("Fst","Pi_Dom","Pi_Wild","Tajima_D_Dom"), 3) }) # ============================================================ # CHROMOSOME VISUALIZATION (uses FULL all_markers — flanking fixed) # ============================================================ output$chromosome_viz <- renderUI({ req(values$qtl_effects_train, values$all_markers) if ("Message" %in% colnames(values$qtl_effects_train)) return(div(class = "alert alert-info", values$qtl_effects_train$Message[1])) chromosomes <- unique(values$qtl_effects_train$Chromosome) tagList(lapply(chromosomes, function(chr) { # Use FULL all_markers (not post-NZV subset) chr_markers <- values$all_markers[values$all_markers$Chromosome == chr, ] chr_markers <- chr_markers[order(chr_markers$Position), ] chr_qtls <- values$qtl_effects_train[values$qtl_effects_train$Chromosome == chr, ] sel_markers <- NULL if (!is.null(values$selection_metrics) && !"Message" %in% colnames(values$selection_metrics)) sel_markers <- values$selection_metrics[ values$selection_metrics$Chromosome == chr & isTRUE(values$selection_metrics$Significant), ] min_pos <- min(chr_markers$Position, na.rm = TRUE) max_pos <- max(chr_markers$Position, na.rm = TRUE) range_pos <- max_pos - min_pos flanking_markers <- c(chr_qtls$Low_Flank, chr_qtls$High_Flank) flanking_markers <- flanking_markers[!is.na(flanking_markers)] div(class = "chromosome-container", div(class = "chromosome-title", paste("Chromosome", chr, " —", nrow(chr_markers), "markers,", nrow(chr_qtls), "QTLs")), div(class = "chromosome", lapply(1:nrow(chr_markers), function(i) { marker <- chr_markers[i, ] left <- if (range_pos > 0 && !is.na(range_pos)) ((marker$Position - min_pos) / range_pos) * 100 else (i / nrow(chr_markers)) * 100 mclass <- "chromosome-marker" if (marker$Marker %in% chr_qtls$Marker) { mclass <- paste(mclass, "significant") } else if (!is.null(sel_markers) && nrow(sel_markers) > 0 && marker$Marker %in% sel_markers$Marker) { mclass <- paste(mclass, "selection") } else if (marker$Marker %in% flanking_markers) { mclass <- paste(mclass, "flanking") } div(class = mclass, style = paste0("left:", round(left, 2), "%;"), title = paste0(marker$Marker, " pos:", marker$Position)) }) ), div(class = "chromosome-legend", span(paste(format(min_pos, big.mark = ","), "bp")), span(paste(format(max_pos, big.mark = ","), "bp")) ) ) })) }) observeEvent(input$simulate_btn, session$sendCustomMessage("simulateQTLDiscovery", list())) observeEvent(input$reset_btn, session$sendCustomMessage("resetAnimation", list())) # ============================================================ # INTERPRETATION # ============================================================ output$analysis_summary <- renderUI({ has_qtl <- !is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train) has_perf <- !is.null(values$performance_metrics) n_qtl <- if (has_qtl) nrow(values$qtl_effects_train) else 0 val_r2 <- if (has_perf) round(values$performance_metrics$Value[values$performance_metrics$Metric == "R² (Validation)"], 3) else "N/A" max_pve <- if (has_qtl) round(max(values$qtl_effects_train$PVE_CIM_Percent), 1) else NA div( tags$h5("CIM Analysis Summary"), tags$p(paste(n_qtl, "QTLs detected above LOD", input$lod_threshold, "| Validation R²:", val_r2)), if (!is.na(max_pve)) tags$p(paste("Max PVE_CIM:", max_pve, "% (marker + cofactors)")), tags$p(style = "color:#3fb950;font-size:12px;", tags$i(class = "fas fa-check-circle"), " CIM: flanking markers use full marker table ✓") ) }) output$qtl_interpretation <- renderUI({ if (is.null(values$qtl_effects_train) || "Message" %in% colnames(values$qtl_effects_train)) return(div(tags$h5("QTL Significance"), tags$p("No significant QTLs. Try lower LOD threshold."))) top <- values$qtl_effects_train[which.max(values$qtl_effects_train$LOD), ] div( tags$h5("Top QTL"), tags$p(paste(top$Marker, "— Chr", top$Chromosome, "— LOD =", round(top$LOD, 2))), tags$p(paste("Flanking:", top$Low_Flank, "↔", top$High_Flank)), tags$p(paste("PVE_marker:", round(top$PVE_Marker_Percent, 1), "% | PVE_CIM:", round(top$PVE_CIM_Percent, 1), "%")) ) }) output$effect_interpretation <- renderUI({ if (is.null(values$qtl_effects_train) || "Message" %in% colnames(values$qtl_effects_train)) return(div(tags$h5("Effect Sizes"), tags$p("No QTL effects yet."))) top <- values$qtl_effects_train[which.max(values$qtl_effects_train$PVE_CIM_Percent), ] dom <- if (!is.na(top$Dominance_Effect)) paste0("Dominance = ", round(top$Dominance_Effect, 3), " (", top$Dominance_Class, ")") else "No heterozygotes (additive model)" div( tags$h5("Largest PVE_CIM QTL"), tags$p(paste(top$Marker, "—", round(top$PVE_CIM_Percent, 1), "% PVE (CIM model)")), tags$p(paste("Additive effect =", round(top$Additive_Effect, 3))), tags$p(dom) ) }) output$epistasis_interpretation <- renderUI({ if (is.null(values$epistasis_sig) || "Message" %in% colnames(values$epistasis_sig) || nrow(values$epistasis_sig) == 0) return(div(tags$h5("Epistasis"), tags$p("No significant interactions."))) top <- values$epistasis_sig[which.min(values$epistasis_sig$Interaction_p), ] div(tags$h5("Epistasis"), tags$p(paste(nrow(values$epistasis_sig), "interactions. Strongest:", top$QTL1, "×", top$QTL2, "(p =", format.pval(top$Interaction_p), ")"))) }) output$recommendations <- renderUI({ has_qtl <- !is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train) recs <- if (has_qtl) { n_ovdom <- sum(values$qtl_effects_train$Dominance_Class == "Overdominance", na.rm = TRUE) r <- c("Validate top CIM QTLs in independent populations", "Use Low_Flank / High_Flank for fine-mapping intervals", "Annotate QTL regions for candidate genes") if (n_ovdom > 0) r <- c(r, paste(n_ovdom, "overdominant QTL(s) — consider heterosis breeding")) r <- c(r, "PVE_CIM includes cofactor variance — use PVE_Marker for single-QTL estimates") r } else { c("Upload genotype + phenotype CSV files", "Click 'Run CIM Analysis'", "Try LOD threshold = 2 to start") } div(tags$h5("Recommendations"), tags$ul(lapply(recs, tags$li), style = "color:#8b949e;")) }) # ============================================================ # DOWNLOADS # ============================================================ output$download_train_results <- downloadHandler( filename = function() paste0("cim_results_", Sys.Date(), ".xlsx"), content = function(file) { sheets <- list() if (!is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train)) sheets[["CIM_QTL_Results"]] <- values$qtl_effects_train if (!is.null(values$cim_all) && !"Message" %in% colnames(values$cim_all)) sheets[["CIM_Full_Scan"]] <- values$cim_all if (!is.null(values$performance_metrics)) sheets[["Performance"]] <- values$performance_metrics sheets[["Method_Documentation"]] <- data.frame( Item = c("Method","Cofactor selection","LOD formula","PVE_Marker","PVE_CIM", "Additive_Effect","Dominance_Effect","Flanking fix","Reference"), Description = c( "Composite Interval Mapping (CIM)", "Top K markers by RF importance, excluding ±window on same chromosome", "-log10(p-value of focal marker in lm(Y ~ marker + cofactors))", "R² from lm(Y ~ additive_code + dominance_code) × 100 — marker alone", "R² from full CIM model (marker + cofactors) × 100 — includes background", "beta_a from lm(Y ~ a + d) — allele substitution effect", "beta_d from lm(Y ~ a + d) — heterozygote deviation from midparent", "Uses full all_markers table (not post-NZV subset)", "Zeng (1993) PNAS; Falconer & Mackay (1996); Lynch & Walsh (1998)"), stringsAsFactors = FALSE) write_xlsx(sheets, file) } ) output$download_selection <- downloadHandler( filename = function() paste0("selection_", Sys.Date(), ".xlsx"), content = function(file) { if (!is.null(values$selection_metrics) && !"Message" %in% colnames(values$selection_metrics)) write_xlsx(list(Selection = values$selection_metrics), file) else write_xlsx(list(Message = data.frame(msg = "No results yet")), file) } ) } shinyApp(ui = ui, server = server)
options(repos = c(CRAN = "https://cloud.r-project.org"))
required_packages <- c(
"shiny", "randomForest", "caret", "DT", "ggplot2", "plotly",
"writexl", "viridis", "reshape2", "dplyr", "httr", "jsonlite",
"shinyjs", "markdown", "base64enc"
)
for (pkg in required_packages) {
if (!require(pkg, character.only = TRUE)) {
install.packages(pkg, dependencies = TRUE)
library(pkg, character.only = TRUE)
}
}
# ============================================================
# TOKEN / API SETUP
# ============================================================
token <- Sys.getenv("GROQ_API_KEY")
token_exists <- token != ""
token_length <- if (token_exists) nchar(token) else 0
cat("=== GROQ API TOKEN DEBUG ===\n")
cat("Token exists:", token_exists, "\n")
cat("Token length:", token_length, "\n")
if (token_exists) cat("Token starts with:", substr(token, 1, 10), "\n")
cat("===================================\n")
HF_API_TOKEN <- token
HF_API_URL <- "https://api.groq.com/openai/v1/chat/completions"
default_model <- "llama-3.1-8b-instant"
available_models <- list(
list(id = "llama-3.1-8b-instant", label = "Llama 3.1 8B", provider = "groq", tier = "free"),
list(id = "llama-3.3-70b-versatile", label = "Llama 3.3 70B", provider = "groq", tier = "free"),
list(id = "meta-llama/llama-4-maverick-17b-128e-instruct", label = "Llama 4 Maverick 17B", provider = "groq", tier = "free"),
list(id = "moonshotai/kimi-k2-instruct-0905", label = "Kimi K2", provider = "groq", tier = "free")
)
model_choices <- setNames(
sapply(available_models, function(m) m$id),
sapply(available_models, function(m) paste0(m$label, " [", m$tier, "]"))
)
run_cim <- function(genotype_matrix, phenotype_vector, marker_info,
n_cofactors = 10, window_size = 10,
lod_threshold = 2.0) {
markers <- colnames(genotype_matrix)
n_markers <- length(markers)
n_samples <- length(phenotype_vector)
cat("CIM: Starting with", n_markers, "markers,", n_samples, "samples\n")
# ---- Step 1: Select cofactors via RF ----
valid_rows <- !is.na(phenotype_vector)
X_valid <- genotype_matrix[valid_rows, , drop = FALSE]
y_valid <- phenotype_vector[valid_rows]
# Remove zero-variance markers before RF
nzv <- apply(X_valid, 2, function(x) length(unique(na.omit(x))) < 2)
X_valid <- X_valid[, !nzv, drop = FALSE]
rf_model <- tryCatch(
randomForest(x = X_valid, y = y_valid, ntree = 500, importance = TRUE),
error = function(e) NULL
)
if (!is.null(rf_model)) {
imp_scores <- importance(rf_model, type = 1)[, 1]
top_cofactors <- names(sort(imp_scores, decreasing = TRUE))[1:min(n_cofactors * 2, length(imp_scores))]
} else {
# Fallback: single-marker regression ranking
p_vals <- sapply(colnames(X_valid), function(m) {
fit <- lm(y_valid ~ X_valid[, m])
coef(summary(fit))[2, 4]
})
top_cofactors <- names(sort(p_vals))[1:min(n_cofactors * 2, length(p_vals))]
}
cat("CIM: Selected", length(top_cofactors), "candidate cofactors\n")
# ---- Step 2: Scan each marker with CIM ----
results_list <- list()
for (i in seq_along(markers)) {
m <- markers[i]
geno <- genotype_matrix[, m]
valid_idx <- !is.na(geno) & !is.na(phenotype_vector)
geno_v <- geno[valid_idx]
pheno_v <- phenotype_vector[valid_idx]
if (length(unique(geno_v)) < 2 || length(pheno_v) < 5) next
# Get marker info