diff --git "a/app.R" "b/app.R" --- "a/app.R" +++ "b/app.R" @@ -1,58 +1,2136 @@ library(shiny) -library(bslib) -library(dplyr) +library(randomForest) +library(caret) +library(DT) library(ggplot2) +library(plotly) +library(writexl) +library(viridis) +library(reshape2) +library(dplyr) +library(httr) +library(jsonlite) -df <- readr::read_csv("penguins.csv") -# Find subset of columns that are suitable for scatter plot -df_num <- df |> select(where(is.numeric), -Year) - -ui <- page_sidebar( - theme = bs_theme(bootswatch = "minty"), - title = "Penguins explorer", - sidebar = sidebar( - varSelectInput("xvar", "X variable", df_num, selected = "Bill Length (mm)"), - varSelectInput("yvar", "Y variable", df_num, selected = "Bill Depth (mm)"), - checkboxGroupInput("species", "Filter by species", - choices = unique(df$Species), selected = unique(df$Species) - ), - hr(), # Add a horizontal rule - checkboxInput("by_species", "Show species", TRUE), - checkboxInput("show_margins", "Show marginal plots", TRUE), - checkboxInput("smooth", "Add smoother"), +# ============================================================ +# RAG SYSTEM - Knowledge Base & Retrieval +# ============================================================ + +# Static knowledge base about QTL analysis concepts +qtl_knowledge_base <- list( + list( + id = "lod_scores", + topic = "LOD Scores", + keywords = c("lod", "score", "threshold", "significant", "suggestive"), + content = "LOD (Logarithm of Odds) scores measure the statistical evidence for a QTL at a specific genomic position. A LOD score > 3 indicates a suggestive QTL, while LOD > 5 indicates a significant QTL. LOD scores are calculated as -log10(p-value) from marker importance in the Random Forest model. The LOD threshold can be adjusted in the Analysis Parameters panel. Higher LOD scores indicate stronger evidence for a QTL at that position." + ), + list( + id = "qtl_effects", + topic = "QTL Effects", + keywords = c("additive", "dominance", "effect", "pve", "variance", "explained"), + content = "QTL effects describe how a marker influences the phenotype. Additive Effect is half the difference between the two homozygote means - a positive value means the alternative allele increases the trait. Dominance Effect measures heterozygote deviation from the midparent value - positive values indicate positive dominance. PVE (Phenotypic Variance Explained) shows what proportion of trait variation is explained by the QTL, expressed as a percentage. Higher PVE indicates a more important QTL." + ), + list( + id = "epistasis", + topic = "Epistasis Analysis", + keywords = c("epistasis", "interaction", "epistatic", "pair", "pairwise"), + content = "Epistasis refers to interactions between QTLs where the effect of one locus depends on the genotype at another locus. Additive epistasis (QTL1 x QTL2 interaction) is tested using linear models. Significant interactions (p < 0.05) suggest that the combined effect of two markers differs from their individual additive effects. The epistasis heatmap shows p-values for all pairwise interactions - darker colors indicate stronger interactions." + ), + list( + id = "fst", + topic = "Fst and Population Differentiation", + keywords = c("fst", "differentiation", "population", "divergence", "wild", "domesticated"), + content = "Fst (Fixation Index) measures genetic differentiation between populations. Values range from 0 (no differentiation) to 1 (complete differentiation). Fst > 0.1 indicates moderate differentiation; Fst > 0.2 indicates strong differentiation. High Fst in QTL regions suggests these loci may have been under selection during domestication. The Fst Manhattan plot shows differentiation across all chromosomes." + ), + list( + id = "tajima_d", + topic = "Tajima's D", + keywords = c("tajima", "tajimas", "sweep", "selection", "diversity", "neutral"), + content = "Tajima's D tests for deviations from neutral evolution. Values near 0 suggest neutral evolution. Negative Tajima's D (< -2) indicates positive selection or selective sweeps, where beneficial alleles swept through the population rapidly, reducing diversity. Positive Tajima's D (> 2) suggests balancing selection or population contraction. In domestication, negative Tajima's D in QTL regions suggests these genes were targets of artificial selection." + ), + list( + id = "nucleotide_diversity", + topic = "Nucleotide Diversity (Pi)", + keywords = c("pi", "nucleotide", "diversity", "polymorphism"), + content = "Nucleotide diversity (Pi) measures the average number of nucleotide differences per site between two sequences. Lower Pi in domesticated populations compared to wild populations at a QTL region suggests a selective sweep occurred during domestication, reducing genetic diversity. Pi_Dom refers to domesticated population diversity; Pi_Wild refers to wild population diversity." ), - plotOutput("scatter") + list( + id = "model_performance", + topic = "Model Performance Metrics", + keywords = c("r2", "r squared", "performance", "accuracy", "validation", "train", "correlation"), + content = "Model performance is evaluated using R² (coefficient of determination) and R (Pearson correlation). R² measures the proportion of variance explained by the model - higher is better (0-1 scale). R measures the linear correlation between predicted and observed values. Training R² shows fit on the training set; Validation R² shows generalization to unseen data. A large gap between training and validation R² indicates overfitting." + ), + list( + id = "random_forest", + topic = "Random Forest QTL Mapping", + keywords = c("random forest", "rf", "machine learning", "importance", "variable"), + content = "This app uses Random Forest (RF) for QTL mapping. RF builds many decision trees and averages their predictions. Variable importance scores indicate how much each marker contributes to predicting the phenotype - these are converted to LOD scores. RF handles non-linear relationships, interactions, and missing data well. The model is trained with 5-fold cross-validation to optimize parameters." + ), + list( + id = "flanking_markers", + topic = "Flanking Markers and QTL Intervals", + keywords = c("flank", "flanking", "interval", "confidence", "region", "low flank", "high flank"), + content = "Flanking markers define the confidence interval around each QTL. Low_Flank is the nearest marker with lower position; High_Flank is the nearest marker with higher position. The region between flanking markers represents the QTL confidence interval - the genomic region likely containing the causative gene. Narrower intervals indicate more precise QTL localization." + ), + list( + id = "chromosome_viz", + topic = "Chromosome Visualization", + keywords = c("chromosome", "visualization", "red", "blue", "green", "marker", "position"), + content = "The chromosome visualization shows marker positions on each chromosome. Red/significant markers (darker) = QTL peaks above LOD threshold. Blue/flanking markers = markers flanking QTL peaks, defining the confidence interval. Green/selection markers = markers showing significant selection signatures. The Simulate Discovery button animates the QTL detection process. Use this view to understand the genomic architecture of the trait." + ), + list( + id = "domestication", + topic = "Domestication Analysis Overview", + keywords = c("domestication", "domesticated", "wild", "adaptation", "artificial", "selection"), + content = "Domestication analysis compares genetic patterns between domesticated and wild populations to identify regions under artificial selection. The app calculates Fst (differentiation), Pi (nucleotide diversity), and Tajima's D for each marker. Regions with high Fst AND negative Tajima's D in the domesticated population are strong candidates for domestication loci. QTL-overlapping selection markers suggest these traits were targeted during domestication." + ), + list( + id = "data_format", + topic = "Input Data Format", + keywords = c("format", "csv", "upload", "genotype", "phenotype", "header", "chromosome", "position"), + content = "Genotype CSV format: Row 1 = header (id, marker1, marker2...), Row 2 = chromosome numbers, Row 3 = physical positions (bp), Rows 4+ = sample data (0/1/2 coding). Phenotype CSV: Row 1 = header (id, trait1, trait2...), Rows 2+ = sample data with numeric trait values. Population CSV: Two columns - 'id' (sample ID) and 'population' (e.g., 'Domesticated' or 'Wild'). All files must use comma separation." + ), + list( + id = "interpretation", + topic = "Interpreting Results", + keywords = c("interpret", "meaning", "result", "significant", "important", "what does"), + content = "When interpreting QTL results: (1) Focus on LOD > 5 QTLs as most significant; (2) Large PVE (>10%) indicates major effect QTLs; (3) Significant epistasis suggests complex trait architecture; (4) QTLs with high Fst overlap suggest selection during domestication; (5) Consistent effects across training and validation sets indicate robust QTLs; (6) Multiple QTLs on the same chromosome may be the same locus or separate linked loci." + ) ) -server <- function(input, output, session) { - subsetted <- reactive({ - req(input$species) - df |> filter(Species %in% input$species) +# RAG: Simple TF-IDF-like retrieval +compute_relevance <- function(query, doc) { + query_lower <- tolower(query) + score <- 0 + + # Check keyword matches + for (kw in doc$keywords) { + if (grepl(kw, query_lower, fixed = TRUE)) { + score <- score + 3 + } + } + + # Check topic match + if (grepl(tolower(doc$topic), query_lower, fixed = TRUE)) { + score <- score + 5 + } + + # Check content word overlap + query_words <- unlist(strsplit(query_lower, "\\W+")) + query_words <- query_words[nchar(query_words) > 3] + content_lower <- tolower(doc$content) + for (word in query_words) { + if (grepl(word, content_lower, fixed = TRUE)) { + score <- score + 1 + } + } + score +} + +retrieve_context <- function(query, top_k = 3) { + scores <- sapply(qtl_knowledge_base, function(doc) compute_relevance(query, doc)) + top_indices <- order(scores, decreasing = TRUE)[1:min(top_k, length(scores))] + + # Only return docs with some relevance + relevant <- top_indices[scores[top_indices] > 0] + if (length(relevant) == 0) relevant <- top_indices[1] + + context_parts <- sapply(qtl_knowledge_base[relevant], function(doc) { + paste0("[", doc$topic, "]: ", doc$content) }) + + paste(context_parts, collapse = "\n\n") +} - output$scatter <- renderPlot( - { - p <- ggplot(subsetted(), aes(!!input$xvar, !!input$yvar)) + - theme_light() + - list( - theme(legend.position = "bottom"), - if (input$by_species) aes(color = Species), - geom_point(), - if (input$smooth) geom_smooth() - ) +# Build dynamic context from analysis results +build_results_context <- function(rv) { + parts <- character(0) + + if (!is.null(rv$qtl_effects_train) && !"Message" %in% colnames(rv$qtl_effects_train)) { + n_qtl <- nrow(rv$qtl_effects_train) + top_qtl <- rv$qtl_effects_train[order(-rv$qtl_effects_train$LOD), ][1,] + parts <- c(parts, paste0( + "[CURRENT ANALYSIS - QTL Results]: ", + n_qtl, " significant QTLs found. ", + "Top QTL: Marker ", top_qtl$Marker, + " on Chromosome ", top_qtl$Chromosome, + " at Position ", top_qtl$Position, + " with LOD=", round(top_qtl$LOD, 2), + ", Additive Effect=", round(top_qtl$Additive_Effect, 3), + ", PVE=", round(top_qtl$PVE_Percent, 2), "%." + )) + } + + if (!is.null(rv$performance_metrics)) { + pm <- rv$performance_metrics + parts <- c(parts, paste0( + "[CURRENT ANALYSIS - Model Performance]: ", + "R²(Train)=", round(pm$Value[pm$Metric == "R² (Train)"], 3), + ", R²(Validation)=", round(pm$Value[pm$Metric == "R² (Validation)"], 3), + ", R(Train)=", round(pm$Value[pm$Metric == "R (Train)"], 3), + ", R(Validation)=", round(pm$Value[pm$Metric == "R (Validation)"], 3) + )) + } + + if (!is.null(rv$epistasis_sig) && !"Message" %in% colnames(rv$epistasis_sig)) { + n_epi <- nrow(rv$epistasis_sig) + top_epi <- rv$epistasis_sig[order(rv$epistasis_sig$Interaction_p), ][1, ] + parts <- c(parts, paste0( + "[CURRENT ANALYSIS - Epistasis]: ", + n_epi, " significant epistatic interactions found. ", + "Strongest: ", top_epi$QTL1, " x ", top_epi$QTL2, + " (p=", round(top_epi$Interaction_p, 4), + ", effect=", round(top_epi$Effect_Size, 3), ")." + )) + } + + if (!is.null(rv$selection_metrics) && !"Message" %in% colnames(rv$selection_metrics)) { + n_sig <- sum(rv$selection_metrics$Significant, na.rm = TRUE) + top_fst <- rv$selection_metrics[which.max(rv$selection_metrics$Fst), ] + parts <- c(parts, paste0( + "[CURRENT ANALYSIS - Domestication]: ", + n_sig, " markers with significant selection signatures. ", + "Highest Fst marker: ", top_fst$Marker, + " (Fst=", round(top_fst$Fst, 3), + ", Chr ", top_fst$Chromosome, + ", Pos ", top_fst$Position, ")." + )) + } + + if (length(parts) == 0) return("") + paste(parts, collapse = "\n") +} - if (input$show_margins) { - margin_type <- if (input$by_species) "density" else "histogram" - p <- p |> ggExtra::ggMarginal( - type = margin_type, margins = "both", - size = 8, groupColour = input$by_species, groupFill = input$by_species +# ============================================================ +# LLM QUERY FUNCTION - Ollama (local) with fallback +# ============================================================ + +query_llm <- function(user_message, rag_context, chat_history, + model = "llama3.2", ollama_url = "http://localhost:11434") { + + system_prompt <- paste0( + "You are a specialized bioinformatics assistant for QTL (Quantitative Trait Loci) mapping and ", + "domestication analysis. You help researchers understand their genomic analysis results.\n\n", + "KNOWLEDGE BASE:\n", rag_context, "\n\n", + "Answer questions clearly and concisely. When referring to specific results, ", + "use the data provided in the CURRENT ANALYSIS sections above. ", + "If asked about methodology, explain it in accessible terms. ", + "Always relate your answers back to what the analysis results mean biologically." + ) + + # Build messages for Ollama + messages <- list(list(role = "system", content = system_prompt)) + + # Add chat history (last 6 messages for context) + if (length(chat_history) > 0) { + history_to_include <- tail(chat_history, 6) + messages <- c(messages, history_to_include) + } + + messages <- c(messages, list(list(role = "user", content = user_message))) + + tryCatch({ + response <- POST( + url = paste0(ollama_url, "/api/chat"), + body = toJSON(list( + model = model, + messages = messages, + stream = FALSE, + options = list( + temperature = 0.7, + num_predict = 512 ) + ), auto_unbox = TRUE), + content_type_json(), + timeout(30) + ) + + if (status_code(response) == 200) { + result <- content(response, as = "parsed") + return(list( + success = TRUE, + text = result$message$content, + model_used = model + )) + } else { + return(list(success = FALSE, error = paste("Ollama returned status:", status_code(response)))) + } + }, error = function(e) { + return(list(success = FALSE, error = e$message)) + }) +} + +# ============================================================ +# SMART RULE-BASED RESPONSE ENGINE +# ============================================================ + +# Helper: format top N QTLs as readable text +format_top_qtls <- function(rv, n = 5) { + if (is.null(rv$qtl_effects_train) || "Message" %in% colnames(rv$qtl_effects_train)) return(NULL) + df <- rv$qtl_effects_train + df <- df[order(-df$LOD), ] + top <- head(df, n) + lines <- sapply(1:nrow(top), function(i) { + row <- top[i, ] + sprintf(" %d. %s | Chr %s | Pos %.1f | LOD=%.2f | PVE=%.1f%% | Additive=%.3f", + i, row$Marker, row$Chromosome, as.numeric(row$Position), + row$LOD, row$PVE_Percent, row$Additive_Effect) + }) + paste(lines, collapse = "\n") +} + +# Helper: get last assistant topic from chat history +get_last_topic <- function(messages) { + if (length(messages) < 2) return(NULL) + # Walk backwards through messages to find last assistant reply + for (i in rev(seq_along(messages))) { + if (messages[[i]]$role == "assistant") { + txt <- tolower(messages[[i]]$text) + if (grepl("lod|qtl|marker", txt)) return("qtl") + if (grepl("pve|variance|effect", txt)) return("pve") + if (grepl("epistasis|interaction", txt)) return("epistasis") + if (grepl("fst|domestication|wild", txt)) return("domestication") + if (grepl("tajima", txt)) return("tajima") + if (grepl("r2|r\\.squared|performance|validation", txt)) return("performance") + if (grepl("additive|dominance|allele", txt)) return("effects") + } + } + return(NULL) +} + +# Helper: low-PVE actionable advice +low_pve_advice <- function(rv) { + if (is.null(rv$qtl_effects_train) || "Message" %in% colnames(rv$qtl_effects_train)) { + return("Run QTL analysis first to evaluate PVE values.") + } + df <- rv$qtl_effects_train + max_pve <- max(df$PVE_Percent, na.rm = TRUE) + n_qtl <- nrow(df) + total_pve <- sum(df$PVE_Percent, na.rm = TRUE) + + pm <- rv$performance_metrics + val_r2 <- if (!is.null(pm)) round(pm$Value[pm$Metric == "R\u00b2 (Validation)"], 3) else NA + + advice <- paste0( + "Your QTLs have low individual PVE (max=", round(max_pve, 1), "%, total combined=", round(total_pve, 1), "%). ", + "This is actually common in complex polygenic traits. Here is what you can do:\n\n", + "1. LOWER LOD THRESHOLD: You found ", n_qtl, " QTLs at your current threshold. Lowering it may reveal additional small-effect QTLs that together explain more variance.\n\n", + "2. CHECK EPISTASIS: You have ", if (!is.null(rv$epistasis_sig) && !"Message" %in% colnames(rv$epistasis_sig)) nrow(rv$epistasis_sig) else 0, " epistatic interactions. Interactions between QTLs often explain variance not captured by individual loci.\n\n", + "3. INCREASE SAMPLE SIZE: Small samples reduce statistical power to detect QTLs with small effects.\n\n", + "4. CONSIDER POLYGENIC ARCHITECTURE: Many traits are controlled by hundreds of tiny-effect loci. A Random Forest model R\u00b2 of ", ifelse(is.na(val_r2), "N/A", val_r2), " on validation captures the combined predictive power better than individual PVE.\n\n", + "5. VERIFY DATA QUALITY: Check for genotyping errors, outlier phenotypes, or population stratification that may dilute QTL signals." + ) + advice +} + +# Main smart response function +rule_based_response <- function(user_message, rag_context, rv, chat_messages = list()) { + q <- tolower(trimws(user_message)) + last_topic <- get_last_topic(chat_messages) + has_results <- !is.null(rv$qtl_effects_train) && !"Message" %in% colnames(rv$qtl_effects_train) + has_sel <- !is.null(rv$selection_metrics) && !"Message" %in% colnames(rv$selection_metrics) + has_epi <- !is.null(rv$epistasis_sig) && !"Message" %in% colnames(rv$epistasis_sig) + has_perf <- !is.null(rv$performance_metrics) + + # ---- Greetings ---- + if (grepl("^(hi|hello|hey|greetings|good morning|good afternoon)", q)) { + return(paste0( + "Hello! I am your QTL analysis assistant.\n\n", + if (has_results) paste0("I can see you have results loaded: ", nrow(rv$qtl_effects_train), " significant QTLs detected. ") else "", + "You can ask me:\n", + "- Show my top QTLs\n", + "- Explain my model performance\n", + "- What do my epistasis results mean?\n", + "- My PVE is low, what should I do?\n", + "- Interpret my Fst / Tajima results\n", + "- What are my next steps?" + )) + } + + # ---- TOP QTLs - list them out ---- + if (grepl("top qtl|best qtl|highest lod|show.*qtl|list.*qtl|qtl.*result|qtl.*rank|all qtl|which qtl|my qtl", q) || + (grepl("qtl", q) && grepl("top|best|list|show|result|what are", q))) { + if (!has_results) return("No QTL results yet. Please upload your genotype and phenotype files and click 'Run QTL Analysis'.") + df <- rv$qtl_effects_train[order(-rv$qtl_effects_train$LOD), ] + n_show <- min(nrow(df), 10) + top_table <- format_top_qtls(rv, n_show) + top1 <- df[1, ] + sig_count <- sum(df$LOD >= 5) + sug_count <- sum(df$LOD >= 3 & df$LOD < 5) + return(paste0( + "Here are your top ", n_show, " QTLs ranked by LOD score:\n\n", + top_table, "\n\n", + "Summary: ", sig_count, " significant (LOD\u22655) and ", sug_count, " suggestive (LOD 3-5) QTLs detected.\n\n", + "Top QTL is ", top1$Marker, " on Chr ", top1$Chromosome, " — it explains ", + round(top1$PVE_Percent, 1), "% of phenotypic variance with an additive effect of ", round(top1$Additive_Effect, 3), ".\n\n", + "Want me to explain any specific QTL in more detail, or interpret the effect sizes?" + )) + } + + # ---- LOD threshold / QTLs above a value ---- + if (grepl("lod.*above|above.*lod|lod.*threshold|significant.*lod|lod.*cutoff|lod.*greater|lod.*more than", q)) { + if (!has_results) return("Run QTL analysis first to see LOD scores.") + df <- rv$qtl_effects_train + # Try to extract a number from the query + num_match <- regmatches(q, regexpr("[0-9]+\\.?[0-9]*", q)) + cutoff <- if (length(num_match) > 0) as.numeric(num_match[1]) else 3.0 + filtered <- df[df$LOD >= cutoff, ] + if (nrow(filtered) == 0) { + return(paste0("No QTLs have LOD \u2265 ", cutoff, ". Your highest LOD is ", round(max(df$LOD), 2), " for marker ", df$Marker[which.max(df$LOD)], ". Consider lowering the threshold.")) + } + filtered <- filtered[order(-filtered$LOD), ] + lines <- sapply(1:nrow(filtered), function(i) { + r <- filtered[i,] + sprintf(" %s | Chr %s | LOD=%.2f | PVE=%.1f%%", r$Marker, r$Chromosome, r$LOD, r$PVE_Percent) + }) + return(paste0(nrow(filtered), " QTLs with LOD \u2265 ", cutoff, ":\n\n", paste(lines, collapse="\n"))) + } + + # ---- LOD general questions ---- + if (grepl("lod|log.*odds", q) && !grepl("above|threshold|cutoff", q)) { + base <- "LOD (Logarithm of Odds) scores measure statistical evidence for a QTL at each marker position. LOD > 3 = suggestive, LOD > 5 = significant, LOD > 10 = highly significant.\n\n" + if (has_results) { + df <- rv$qtl_effects_train[order(-rv$qtl_effects_train$LOD), ] + top <- df[1, ] + return(paste0(base, "In your analysis: strongest QTL is ", top$Marker, " (LOD=", round(top$LOD, 2), + ") on Chr ", top$Chromosome, ". ", + sum(df$LOD >= 5), " markers exceed LOD 5 (significant) and ", + sum(df$LOD >= 3), " exceed LOD 3 (suggestive).")) + } + return(base) + } + + # ---- PVE low / what to do about PVE ---- + if (grepl("pve.*low|low.*pve|pve.*small|small.*pve|pve.*less|less.*pve|pve.*poor|poor.*pve|pve.*not|improve.*pve|increase.*pve", q) || + (grepl("pve|variance explain", q) && grepl("low|small|less|poor|not|what to do|improve|increase|why", q))) { + return(low_pve_advice(rv)) + } + + # ---- PVE general ---- + if (grepl("pve|phenotypic variance|variance explain|how much.*explain|explain.*variance", q)) { + if (has_results) { + df <- rv$qtl_effects_train[order(-rv$qtl_effects_train$PVE_Percent), ] + top <- df[1, ] + total <- sum(df$PVE_Percent, na.rm = TRUE) + lines <- sapply(1:min(5, nrow(df)), function(i) { + r <- df[i,] + sprintf(" %s: %.1f%% (Chr %s)", r$Marker, r$PVE_Percent, r$Chromosome) + }) + return(paste0( + "PVE (Phenotypic Variance Explained) shows each QTL's contribution to trait variation.\n\n", + "Top 5 QTLs by PVE:\n", paste(lines, collapse="\n"), "\n\n", + "Combined PVE of all QTLs: ", round(total, 1), "% (note: QTLs can have overlapping variance).\n", + "Your highest single-QTL PVE is ", round(top$PVE_Percent, 1), "%. ", + if (top$PVE_Percent < 5) "Values below 5% indicate minor-effect QTLs — this is common for polygenic traits." + else if (top$PVE_Percent < 10) "Values 5-10% indicate moderate-effect QTLs." + else "Values above 10% indicate major-effect QTLs — these are high-priority targets." + )) + } + return("PVE measures what proportion of trait variance each QTL explains. Run analysis to see your PVE values.") + } + + # ---- Epistasis detailed ---- + if (grepl("epistasis|epistatic|interaction.*qtl|qtl.*interaction|gene.*gene|loci.*interact", q)) { + if (!has_epi) return("No epistasis results yet. Run QTL analysis first. Epistasis tests all pairwise QTL x marker interactions using linear models.") + epi <- rv$epistasis_sig[order(rv$epistasis_sig$Interaction_p), ] + n <- nrow(epi) + top5 <- head(epi, 5) + lines <- sapply(1:nrow(top5), function(i) { + r <- top5[i, ] + sprintf(" %d. %s \u00d7 %s | p=%.4f | effect=%.3f", i, r$QTL1, r$QTL2, r$Interaction_p, r$Effect_Size) + }) + pos_count <- sum(epi$Effect_Size > 0) + neg_count <- sum(epi$Effect_Size < 0) + return(paste0( + "Your epistasis analysis found ", n, " significant pairwise interactions (p<0.05).\n\n", + "Top 5 strongest interactions:\n", paste(lines, collapse="\n"), "\n\n", + "Effect direction: ", pos_count, " synergistic (positive) and ", neg_count, " antagonistic (negative) interactions.\n\n", + "What this means: The top pair ", top5$QTL1[1], " \u00d7 ", top5$QTL2[1], + " shows that these two loci interact non-additively. ", + if (top5$Effect_Size[1] > 0) "Their combined effect is greater than the sum of individual effects (synergy)." + else "Their combined effect is less than the sum of individual effects (antagonism).", + "\n\nWith ", n, " interactions, your trait has a complex genetic architecture. Consider multi-locus models for breeding." + )) + } + + # ---- Fst / domestication ---- + if (grepl("fst|domestication|domesticat|wild.*population|population.*differ|selection.*signature|artificial.*select", q)) { + if (!has_sel) return("No domestication results yet. Upload a population CSV with 'id' and 'population' columns (values: Domesticated / Wild), then click 'Run Domestication Analysis'.") + sel <- rv$selection_metrics + n_sig <- sum(sel$Significant, na.rm = TRUE) + top_fst <- sel[which.max(sel$Fst), ] + high_fst <- sel[sel$Fst > 0.3, ] + + qtl_overlap <- if (has_results) sel[sel$Marker %in% rv$qtl_effects_train$Marker, ] else data.frame() + sig_overlap <- if (nrow(qtl_overlap) > 0) qtl_overlap[!is.na(qtl_overlap$Significant) & qtl_overlap$Significant, ] else data.frame() + + return(paste0( + "Domestication analysis results:\n\n", + "Total markers analyzed: ", nrow(sel), "\n", + "Significant selection signatures: ", n_sig, " markers (high Fst or negative Tajima's D)\n", + "Strongly differentiated markers (Fst > 0.3): ", nrow(high_fst), "\n\n", + "Highest Fst marker: ", top_fst$Marker, " (Fst=", round(top_fst$Fst, 3), + ", Chr ", top_fst$Chromosome, ", Pos ", top_fst$Position, ")\n", + "Pi in Domesticated: ", round(top_fst$Pi_Dom, 4), " | Pi in Wild: ", round(top_fst$Pi_Wild, 4), "\n\n", + if (nrow(sig_overlap) > 0) paste0( + "IMPORTANT: ", nrow(sig_overlap), " QTL markers overlap with selection signatures. ", + "This strongly suggests these QTLs were targets of artificial selection during domestication: ", + paste(sig_overlap$Marker, collapse=", "), "\n\n" + ) else "No overlap between your QTLs and selection signatures detected at current thresholds.\n\n", + "Fst interpretation: 0-0.05=low differentiation, 0.05-0.15=moderate, 0.15-0.25=high, >0.25=very high." + )) + } + + # ---- Tajima's D ---- + if (grepl("tajima|selective sweep|neutral evolution|positive select", q)) { + base <- paste0( + "Tajima's D tests for deviation from neutral evolution:\n\n", + " D near 0 = neutral evolution (no selection)\n", + " D < -2 = positive selection / selective sweep (beneficial allele spread rapidly)\n", + " D > +2 = balancing selection or population bottleneck\n\n" + ) + if (has_sel) { + sel <- rv$selection_metrics + dom_sweeps <- sel[!is.na(sel$Tajima_D_Dom) & sel$Tajima_D_Dom < -1, ] + wild_sweeps <- sel[!is.na(sel$Tajima_D_Wild) & sel$Tajima_D_Wild < -1, ] + min_dom <- sel[which.min(sel$Tajima_D_Dom), ] + return(paste0( + base, + "In your data:\n", + " Domesticated population: ", nrow(dom_sweeps), " markers with D < -1 (potential sweeps)\n", + " Wild population: ", nrow(wild_sweeps), " markers with D < -1\n", + " Most negative (Dom): ", min_dom$Marker, " (D=", round(min_dom$Tajima_D_Dom, 3), + ", Chr ", min_dom$Chromosome, ")\n\n", + if (!is.null(rv$qtl_effects_train) && !"Message" %in% colnames(rv$qtl_effects_train)) { + qtl_tajima <- sel[sel$Marker %in% rv$qtl_effects_train$Marker & !is.na(sel$Tajima_D_Dom) & sel$Tajima_D_Dom < -1, ] + if (nrow(qtl_tajima) > 0) paste0("Markers overlapping with your QTLs AND showing sweeps: ", paste(qtl_tajima$Marker, collapse=", "), " — strong domestication candidates!") + else "None of your QTL markers show a selective sweep at the Tajima's D < -1 threshold." + } else "" + )) + } + return(paste0(base, "Upload population data and run Domestication Analysis to see Tajima's D values for your markers.")) + } + + # ---- Model performance ---- + if (grepl("model|r2|r\\.squared|r squared|performance|accuracy|prediction|validation|overfit|train.*result|result.*train", q)) { + if (!has_perf) return("Run QTL analysis first to see model performance metrics.") + pm <- rv$performance_metrics + train_r2 <- round(pm$Value[pm$Metric == "R\u00b2 (Train)"], 3) + val_r2 <- round(pm$Value[pm$Metric == "R\u00b2 (Validation)"], 3) + train_r <- round(pm$Value[pm$Metric == "R (Train)"], 3) + val_r <- round(pm$Value[pm$Metric == "R (Validation)"], 3) + gap <- train_r2 - val_r2 + quality <- if (val_r2 > 0.7) "excellent" else if (val_r2 > 0.5) "good" else if (val_r2 > 0.3) "moderate" else "low" + overfit_msg <- if (gap > 0.3) "\n\u26a0\ufe0f Large train/validation gap (overfitting). Try: increase training data, reduce markers using feature selection, or increase CV folds." else if (gap > 0.15) "\nMild overfitting detected. Consider regularization or larger training set." else "\nTrain/validation gap is acceptable." + return(paste0( + "Model Performance Summary:\n\n", + " R\u00b2 (Train): ", train_r2, " \u2192 ", round(train_r2*100, 0), "% variance explained in training\n", + " R\u00b2 (Validation): ", val_r2, " \u2192 ", round(val_r2*100, 0), "% variance explained in validation\n", + " R (Train): ", train_r, "\n", + " R (Validation): ", val_r, "\n\n", + "Overall quality: ", toupper(quality), overfit_msg, "\n\n", + if (val_r2 < 0.3) "Low R\u00b2 suggests the genotype markers have limited predictive power for this phenotype. Consider: more markers, larger sample size, or checking for genotyping errors." else "" + )) + } + + # ---- Additive / dominance effects ---- + if (grepl("additive|dominance|effect size|allele effect|genetic effect", q)) { + base <- "Genetic effect types:\n\n Additive Effect: half the difference between AA and aa means. Positive = alternative allele increases the trait.\n Dominance Effect: heterozygote deviation from midparent. Near 0 = additive; large value = dominant/recessive.\n SE: standard error of the additive estimate. Wide CI means uncertain effect.\n\n" + if (has_results) { + df <- rv$qtl_effects_train[order(-abs(rv$qtl_effects_train$Additive_Effect)), ] + top <- df[1, ] + return(paste0(base, "Your largest additive effect: ", top$Marker, " (effect=", round(top$Additive_Effect, 3), + ", 95% CI: [", round(top$CI_Lower, 3), ", ", round(top$CI_Upper, 3), "]).\n", + if (!is.na(top$Dominance_Effect)) paste0("Dominance: ", round(top$Dominance_Effect, 3), + if (abs(top$Dominance_Effect) > abs(top$Additive_Effect * 0.5)) " — notable dominance effect detected." else " — mostly additive.") else "Dominance could not be estimated (requires 3 genotype classes).")) + } + return(base) + } + + # ---- Next steps / what to do / recommend ---- + if (grepl("next step|what.*do|how.*improve|recommend|suggest|advice|should i|what now|what can|help me|guide", q)) { + # Context-aware: use last topic if available + if (!is.null(last_topic)) { + if (last_topic == "pve") return(low_pve_advice(rv)) + if (last_topic == "epistasis" && has_epi) { + return(paste0("For your ", nrow(rv$epistasis_sig), " epistatic interactions, next steps:\n\n", + "1. FOCUS on pairs with smallest p-values for experimental validation\n", + "2. CHECK if epistatic QTLs overlap — linked markers can show spurious interactions\n", + "3. TEST multi-locus models combining the top interacting markers\n", + "4. CONSIDER the biological pathway: do these markers map to genes that interact biochemically?\n", + "5. VALIDATE in an independent population to confirm interactions are real")) } + if (last_topic == "performance" && has_perf) { + pm <- rv$performance_metrics + val_r2 <- round(pm$Value[pm$Metric == "R\u00b2 (Validation)"], 3) + if (val_r2 < 0.4) return("To improve your model performance:\n\n1. ADD more samples — Random Forest needs sufficient data to generalize\n2. REDUCE marker redundancy — remove highly correlated markers\n3. INCREASE CV folds from 5 to 10 in the source code\n4. TRY different methods — ridge regression or LASSO may work better for this trait\n5. CHECK phenotype quality — outliers strongly reduce R\u00b2") + } + } + # Generic next steps + if (has_results) { + df <- rv$qtl_effects_train + top <- df[which.max(df$LOD), ] + return(paste0( + "Recommended next steps based on your results:\n\n", + "1. VALIDATE top QTLs: Focus on ", top$Marker, " (LOD=", round(top$LOD,2), ") — test in an independent population\n", + "2. FINE-MAP QTL intervals: Use flanking markers (Low_Flank/High_Flank) to narrow candidate regions\n", + "3. ", if (has_epi && nrow(rv$epistasis_sig) > 0) paste0("INVESTIGATE epistasis: You have ", nrow(rv$epistasis_sig), " interactions — test multi-locus models") else "RUN EPISTASIS: Check for QTL interactions that may explain additional variance","\n", + "4. ", if (has_sel) paste0("CROSS-REFERENCE with selection: ", sum(rv$selection_metrics$Significant, na.rm=TRUE), " markers show selection signatures") else "RUN DOMESTICATION ANALYSIS: Upload population metadata to identify selection signatures","\n", + "5. ANNOTATE QTL REGIONS: Look up your marker positions in a genome browser for candidate genes\n", + "6. CONSIDER MAS: Markers explaining >5% PVE are candidates for marker-assisted selection" + )) + } + return("To get started:\n1. Upload training genotype CSV (id + marker columns with chromosome/position rows)\n2. Upload phenotype CSV (id + trait columns)\n3. Click 'Run QTL Analysis'\n4. Optionally upload population CSV for domestication analysis\n\nI will then be able to give you specific advice about your results.") + } + + # ---- Flanking markers / confidence interval ---- + if (grepl("flank|confidence interval|qtl region|interval|boundary|range", q)) { + base <- "Flanking markers define the QTL confidence interval — the genomic region likely containing the causative gene. Low_Flank is the nearest lower-position marker; High_Flank is the nearest higher-position marker.\n\n" + if (has_results) { + df <- rv$qtl_effects_train[order(-rv$qtl_effects_train$LOD), ] + top <- df[1, ] + return(paste0(base, "Your top QTL (", top$Marker, ") has:\n Lower flank: ", top$Low_Flank, "\n Upper flank: ", top$High_Flank, "\n\nThe region between these flanking markers is your primary candidate interval for gene discovery.")) + } + return(base) + } + + # ---- "but I did not" / incomplete follow-ups using context ---- + if (nchar(q) < 30 && !is.null(last_topic)) { + follow_up_map <- list( + qtl = "Which aspect of the QTL results would you like to explore? You can ask about: specific markers, LOD scores, PVE, additive effects, or flanking markers.", + pve = low_pve_advice(rv), + epistasis = if (has_epi) paste0("Your ", nrow(rv$epistasis_sig), " epistatic interactions are listed in the Results tab under 'Epistasis Analysis'. The strongest is between ", rv$epistasis_sig$QTL1[which.min(rv$epistasis_sig$Interaction_p)], " and ", rv$epistasis_sig$QTL2[which.min(rv$epistasis_sig$Interaction_p)], ". Would you like me to explain what this means biologically?") else "No significant epistasis detected yet.", + domestication = if (has_sel) "For domestication analysis, I can show you: Fst values, Tajima's D patterns, or QTL-selection overlap. What would you like to know?" else "Run domestication analysis by uploading population metadata first.", + tajima = if (has_sel) paste0("Tajima's D in your data: ", nrow(rv$selection_metrics[!is.na(rv$selection_metrics$Tajima_D_Dom) & rv$selection_metrics$Tajima_D_Dom < -1, ]), " markers show potential selective sweeps in the domesticated population. Would you like the full breakdown?") else "Upload population data to see Tajima's D values.", + performance = "Your model performance is shown in the Results tab. Would you like me to explain how to improve R\u00b2 or interpret the train/validation gap?", + effects = "Would you like me to list all QTL effect sizes, or explain a specific marker's additive/dominance effects?" + ) + if (last_topic %in% names(follow_up_map)) return(follow_up_map[[last_topic]]) + } + + # ---- Data format / upload ---- + if (grepl("format|upload|csv|file.*structure|column|how.*load|how.*input", q)) { + return("Input file formats:\n\nGENOTYPE CSV:\n Row 1: header (id, marker1, marker2, ...)\n Row 2: chromosome numbers (e.g., 1, 1, 2, 3...)\n Row 3: physical positions in bp\n Rows 4+: sample data with 0/1/2 coding (homozygous ref / heterozygous / homozygous alt)\n\nPHENOTYPE CSV:\n Row 1: header (id, trait1, trait2, ...)\n Rows 2+: numeric trait measurements\n\nPOPULATION CSV:\n Two columns: 'id' and 'population'\n Population values must be exactly: Domesticated / Wild\n\nAll files must be comma-separated (.csv).") + } + + # ---- Default: smart fallback with data context ---- + # Instead of dumping raw RAG text, give a helpful summary of what IS available + available <- c() + if (has_results) available <- c(available, paste0(nrow(rv$qtl_effects_train), " QTLs detected")) + if (has_perf) { + val_r2 <- round(rv$performance_metrics$Value[rv$performance_metrics$Metric == "R\u00b2 (Validation)"], 3) + available <- c(available, paste0("model R\u00b2=", val_r2)) + } + if (has_epi) available <- c(available, paste0(nrow(rv$epistasis_sig), " epistatic interactions")) + if (has_sel) available <- c(available, paste0(sum(rv$selection_metrics$Significant, na.rm=TRUE), " selection signatures")) + + if (length(available) > 0) { + return(paste0( + "I have your results loaded (", paste(available, collapse=", "), ").\n\n", + "Could you be more specific? For example:\n", + "- 'Show my top QTLs'\n", + "- 'What does my epistasis mean?'\n", + "- 'My PVE is low, what should I do?'\n", + "- 'How is my model performing?'\n", + "- 'Explain Fst results'\n", + "- 'What are my next steps?'" + )) + } + + return("I can help with QTL results, LOD scores, PVE, epistasis, Fst, Tajima's D, model performance, and next steps. Could you be more specific about what you need? Try: 'show my top QTLs', 'what does PVE mean', or 'explain epistasis results'.") +} - p - }, - res = 100 +# ============================================================ +# UI +# ============================================================ + +ui <- fluidPage( + tags$head( + tags$link(rel = "stylesheet", type = "text/css", + href = "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css"), + tags$link(rel = "stylesheet", type = "text/css", + 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(marker => { + setTimeout(() => { + marker.classList.add('highlighted'); + setTimeout(() => { marker.classList.add('pulse'); }, 300); + }, delay); + delay += 100; + }); + }, 100); + } + function resetAnimation() { + const markers = document.querySelectorAll('.chromosome-marker'); + markers.forEach(marker => { + marker.classList.remove('highlighted'); + marker.classList.remove('pulse'); + }); + } + Shiny.addCustomMessageHandler('simulateQTLDiscovery', function(message) { simulateQTLDiscovery(); }); + Shiny.addCustomMessageHandler('resetAnimation', function(message) { resetAnimation(); }); + + // Auto-scroll chat to bottom + Shiny.addCustomMessageHandler('scrollChatBottom', function(message) { + setTimeout(function() { + var chatBox = document.getElementById('chat_messages'); + if (chatBox) chatBox.scrollTop = chatBox.scrollHeight; + }, 100); + }); + + // Enter key to send chat + $(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-color: var(--bg-primary); + color: var(--text-primary); + font-size: 14px; + } + + .navbar { background-color: 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; letter-spacing: -0.5px; } + .navbar-nav > li > a { color: var(--text-secondary) !important; font-family: var(--font-sans); 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 0%, #0d1117 100%); + border: 1px solid var(--border); + border-left: 3px solid var(--accent); + color: var(--text-primary); + 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; } + + .card { + background-color: var(--bg-secondary); + border: 1px solid var(--border); + border-radius: 6px; + margin-bottom: 20px; + } + .card-header { + background-color: 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: 0.5px; + text-transform: uppercase; + } + .card-body { padding: 16px; } + + /* Form inputs */ + .form-control, .selectize-input { + background-color: var(--bg-tertiary) !important; + border: 1px solid var(--border) !important; + color: var(--text-primary) !important; + border-radius: 4px; + font-family: var(--font-sans); + font-size: 13px; + } + .form-control:focus { border-color: var(--accent) !important; box-shadow: 0 0 0 2px rgba(88, 166, 255, 0.2) !important; } + label { color: var(--text-secondary); font-size: 12px; margin-bottom: 4px; } + + /* Buttons */ + .btn { border-radius: 4px; font-family: var(--font-mono); font-size: 12px; font-weight: 600; letter-spacing: 0.3px; transition: all 0.15s; border: 1px solid; } + .btn-primary { background-color: var(--accent); border-color: var(--accent); color: #0d1117; } + .btn-primary:hover { background-color: var(--accent-hover); border-color: var(--accent-hover); color: #0d1117; } + .btn-info { background-color: transparent; border-color: var(--teal); color: var(--teal); } + .btn-info:hover { background-color: var(--teal); color: #0d1117; } + .btn-danger { background-color: transparent; border-color: var(--danger); color: var(--danger); } + .btn-danger:hover { background-color: var(--danger); color: white; } + + /* Help text */ + .help-block, .shiny-input-container .help-block { color: var(--text-muted); font-size: 11px; margin-top: 4px; } + + /* File input */ + .btn-file { background-color: var(--bg-tertiary); border-color: var(--border); color: var(--text-secondary); } + + /* DataTables */ + .dataTables_wrapper { color: var(--text-secondary) !important; } + table.dataTable { background-color: var(--bg-secondary) !important; color: var(--text-primary) !important; border-color: var(--border) !important; } + table.dataTable thead th { background-color: 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: 0.5px; } + table.dataTable tbody tr:hover { background-color: 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 styles */ + .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-color: var(--text-muted); border-radius: 3px; top: -5px; transform: translateX(-50%); transition: all 0.3s ease; } + .chromosome-marker.significant { background-color: var(--danger) !important; height: 40px !important; width: 8px !important; top: -8px !important; } + .chromosome-marker.flanking { background-color: var(--accent) !important; height: 30px !important; width: 5px !important; top: -3px !important; } + .chromosome-marker.selection { background-color: var(--success) !important; height: 34px !important; width: 6px !important; top: -5px !important; } + .chromosome-marker.highlighted { background-color: var(--warning) !important; box-shadow: 0 0 10px rgba(210, 153, 34, 0.6); } + .chromosome-marker.pulse { animation: pulse 1.5s infinite; } + @keyframes pulse { + 0% { transform: translateX(-50%) scale(1); } + 50% { transform: translateX(-50%) scale(1.3); opacity: 0.7; } + 100% { transform: translateX(-50%) scale(1); } + } + .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; } + + /* Simulation buttons */ + .simulation-controls { margin: 12px 0; display: flex; gap: 8px; } + .simulation-btn { background-color: transparent; color: var(--purple); border: 1px solid var(--purple); padding: 5px 12px; border-radius: 4px; cursor: pointer; font-family: var(--font-mono); font-size: 11px; transition: all 0.15s; } + .simulation-btn:hover { background-color: var(--purple); color: #0d1117; } + + /* Notification */ + .shiny-notification { background-color: var(--bg-tertiary); color: var(--text-primary); border: 1px solid var(--accent); border-radius: 4px; font-size: 12px; font-family: var(--font-sans); } + + /* ============================================================ + CHATBOT STYLES + ============================================================ */ + + #chat-panel { + position: fixed; + bottom: 20px; + right: 20px; + z-index: 9999; + width: 380px; + display: flex; + flex-direction: column; + font-family: var(--font-sans); + } + + #chat-toggle-btn { + align-self: flex-end; + width: 52px; + height: 52px; + 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, 0.4); + transition: all 0.2s; + color: #0d1117; + font-size: 20px; + } + #chat-toggle-btn:hover { transform: scale(1.05); box-shadow: 0 6px 24px rgba(88, 166, 255, 0.6); } + + #chat-window { + display: none; + flex-direction: column; + background: var(--bg-secondary); + border: 1px solid var(--border); + border-radius: 10px; + overflow: hidden; + box-shadow: 0 8px 40px rgba(0,0,0,0.5); + margin-bottom: 10px; + height: 520px; + } + #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; + align-items: center; + justify-content: space-between; + } + #chat-header .chat-title { + display: flex; + align-items: center; + gap: 10px; + } + #chat-header .chat-avatar { + width: 30px; height: 30px; + background: linear-gradient(135deg, var(--accent), var(--purple)); + border-radius: 50%; + display: flex; align-items: center; justify-content: center; + font-size: 14px; color: #0d1117; font-weight: bold; + } + #chat-header h4 { + font-family: var(--font-mono); + font-size: 12px; + font-weight: 600; + color: var(--text-primary); + margin: 0; + } + #chat-header p { font-size: 10px; color: var(--text-muted); margin: 0; } + #chat-close-btn { background: none; border: none; color: var(--text-muted); cursor: pointer; font-size: 16px; padding: 4px; transition: color 0.15s; } + #chat-close-btn:hover { color: var(--text-primary); } + + #chat_messages { + flex: 1; + overflow-y: auto; + padding: 16px; + display: flex; + flex-direction: column; + gap: 12px; + scrollbar-width: thin; + scrollbar-color: var(--border) transparent; + } + + .chat-msg { + max-width: 88%; + animation: fadeInUp 0.2s ease; + } + @keyframes fadeInUp { + from { opacity: 0; transform: translateY(8px); } + to { opacity: 1; transform: translateY(0); } + } + .chat-msg.user { align-self: flex-end; } + .chat-msg.assistant { align-self: flex-start; } + + .chat-bubble { + padding: 10px 14px; + border-radius: 14px; + font-size: 13px; + line-height: 1.5; + word-wrap: break-word; + } + .chat-msg.user .chat-bubble { + background: linear-gradient(135deg, var(--accent), #3a7bd5); + color: #0d1117; + border-bottom-right-radius: 4px; + font-weight: 500; + } + .chat-msg.assistant .chat-bubble { + background: var(--bg-tertiary); + color: var(--text-primary); + border: 1px solid var(--border); + border-bottom-left-radius: 4px; + white-space: pre-wrap; + line-height: 1.7; + } + .chat-meta { font-size: 10px; color: var(--text-muted); margin-top: 4px; font-family: var(--font-mono); padding: 0 4px; } + .chat-msg.user .chat-meta { text-align: right; } + + .chat-typing { + display: flex; + gap: 4px; + align-items: center; + padding: 10px 14px; + background: var(--bg-tertiary); + border: 1px solid var(--border); + border-radius: 14px; + border-bottom-left-radius: 4px; + width: fit-content; + } + .typing-dot { + width: 6px; height: 6px; + background: var(--text-muted); + border-radius: 50%; + animation: typingBounce 1.4s infinite; + } + .typing-dot:nth-child(2) { animation-delay: 0.2s; } + .typing-dot:nth-child(3) { animation-delay: 0.4s; } + @keyframes typingBounce { + 0%, 60%, 100% { transform: translateY(0); } + 30% { transform: translateY(-6px); } + } + + #chat-footer { + padding: 12px; + border-top: 1px solid var(--border); + background: var(--bg-tertiary); + display: flex; + flex-direction: column; + gap: 8px; + } + + #chat_input { + background: var(--bg-secondary) !important; + border: 1px solid var(--border) !important; + border-radius: 6px; + color: var(--text-primary) !important; + font-size: 13px; + resize: none; + padding: 10px 12px; + font-family: var(--font-sans); + transition: border-color 0.15s; + } + #chat_input:focus { border-color: var(--accent) !important; outline: none; box-shadow: 0 0 0 2px rgba(88, 166, 255, 0.15); } + #chat_input::placeholder { color: var(--text-muted); } + + .chat-actions { display: flex; gap: 8px; align-items: center; justify-content: space-between; } + + #send_chat { + background: linear-gradient(135deg, var(--accent), #3a7bd5); + color: #0d1117; + border: none; + border-radius: 6px; + padding: 8px 16px; + font-family: var(--font-mono); + font-size: 11px; + font-weight: 600; + cursor: pointer; + transition: all 0.15s; + display: flex; + align-items: center; + gap: 6px; + } + #send_chat:hover { transform: translateY(-1px); box-shadow: 0 4px 12px rgba(88, 166, 255, 0.4); } + #send_chat:disabled { opacity: 0.5; cursor: not-allowed; transform: none; } + + #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: 11px; + cursor: pointer; + transition: all 0.15s; + } + #clear_chat:hover { border-color: var(--danger); color: var(--danger); } + + #ollama_status { + font-family: var(--font-mono); + font-size: 10px; + color: var(--text-muted); + display: flex; + align-items: center; + gap: 6px; + } + .status-dot { width: 6px; height: 6px; border-radius: 50%; display: inline-block; } + .status-dot.online { background: var(--success); box-shadow: 0 0 4px var(--success); } + .status-dot.offline { background: var(--warning); } + + .quick-questions { + display: flex; + flex-wrap: wrap; + gap: 6px; + padding: 0 16px 12px; + } + .quick-q-btn { + background: var(--bg-tertiary); + border: 1px solid var(--border); + color: var(--text-secondary); + border-radius: 12px; + padding: 4px 10px; + font-size: 11px; + cursor: pointer; + transition: all 0.15s; + font-family: var(--font-sans); + } + .quick-q-btn:hover { border-color: var(--accent); color: var(--accent); background: rgba(88, 166, 255, 0.08); } + + /* Interpretation sections */ + .interpretation-section { background: var(--bg-tertiary); padding: 16px; border-radius: 6px; border: 1px solid var(--border); border-left: 3px solid var(--accent); margin-bottom: 16px; } + .interpretation-section h5 { font-family: var(--font-mono); font-size: 11px; color: var(--accent); text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 10px; } + .interpretation-section p { color: var(--text-secondary); font-size: 13px; line-height: 1.6; } + + /* Progress bar */ + .progress { background-color: var(--bg-tertiary); border: 1px solid var(--border); } + .progress-bar { background-color: var(--accent); } + + /* Alerts */ + .alert { border-radius: 4px; font-size: 13px; border: 1px solid; } + .alert-info { background: rgba(88, 166, 255, 0.1); border-color: var(--accent); color: var(--text-secondary); } + .alert-warning { background: rgba(210, 153, 34, 0.1); border-color: var(--warning); color: var(--text-secondary); } + ")) + ), + + navbarPage( + title = tags$span(tags$i(class="fas fa-dna", style="margin-right:8px; color:#58a6ff;"), "QTL-Mapper"), + id = "nav", + + # ---- DATA UPLOAD TAB ---- + tabPanel("Data Upload", icon = icon("upload"), + div(class = "main-header", + h2(tags$i(class="fas fa-upload", style="margin-right:8px;"), "Data Upload"), + p("Upload genotype, phenotype, and population data for comprehensive QTL analysis") + ), + fluidRow( + column(4, + div(class = "card", + div(class = "card-header", tags$i(class="fas fa-table", style="margin-right:6px; color:#58a6ff;"), "Training Data"), + div(class = "card-body", + fileInput("genotype_file", "Training Genotype CSV", accept = c(".csv"), buttonLabel = "Browse"), + helpText("CSV: Row1=header(id,markers), Row2=chromosomes, Row3=positions, rows=samples. Genotype coded 0/1/2."), + fileInput("phenotype_file", "Training Phenotype CSV", accept = c(".csv"), buttonLabel = "Browse"), + helpText("CSV: 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-vial", style="margin-right:6px; color:#3fb950;"), "Test Data (Optional)"), + div(class = "card-body", + fileInput("test_genotype_file", "Test Genotype CSV", accept = c(".csv"), buttonLabel = "Browse"), + helpText("Optional: Same format as training genotype data."), + tags$br(), + actionButton("predict_test_phenotype", "Predict Test Phenotypes", class = "btn-info btn-block", icon = icon("magic")), + helpText("Predict phenotypes for test data using trained model.") + ) + ) + ), + column(4, + div(class = "card", + div(class = "card-header", tags$i(class="fas fa-sliders-h", style="margin-right:6px; color:#bc8cff;"), "Analysis Parameters"), + div(class = "card-body", + sliderInput("test_size", "Validation Set Proportion", min = 0.1, max = 0.5, value = 0.2, step = 0.05), + numericInput("lod_threshold", "LOD Threshold", value = 2.0, min = 1.0, max = 10.0, step = 0.1), + actionButton("run_analysis", "Run QTL Analysis", class = "btn-primary btn-block", icon = icon("play")) + ) + ) + ) + ), + 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")) + ) + ) + ) + ) + ) + ), + + # ---- DOMESTICATION TAB ---- + tabPanel("Domestication", icon = icon("leaf"), + div(class = "main-header", + h2(tags$i(class="fas fa-leaf", style="margin-right:8px;"), "Domestication Analysis"), + p("Analyze selection signatures: Fst, Tajima's D, and nucleotide diversity") + ), + fluidRow( + column(4, + div(class = "card", + div(class = "card-header", "Population Metadata"), + div(class = "card-body", + fileInput("pop_file", "Population Metadata CSV", accept = c(".csv"), buttonLabel = "Browse"), + helpText("CSV with 'id' and 'population' columns (e.g., Domesticated, Wild)."), + 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") + ) + ) + ) + ), + fluidRow( + column(12, + div(class = "card", + div(class = "card-header", "Selection Interpretation"), + div(class = "card-body", uiOutput("selection_interpretation")) + ) + ) + ) + ), + + # ---- RESULTS TAB ---- + tabPanel("Results", icon = icon("chart-line"), + div(class = "main-header", + h2(tags$i(class="fas fa-chart-line", style="margin-right:8px;"), "QTL Analysis Results"), + p("LOD scores, QTL effects, model performance, and epistasis analysis") + ), + fluidRow( + column(6, div(class = "card", div(class = "card-header", "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(class = "simulation-controls", + actionButton("simulate_btn", "Simulate Discovery", class = "simulation-btn"), + actionButton("reset_btn", "Reset", class = "simulation-btn") + ) + ) + )) + ), + 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", "QTL Effects — Training Set"), + div(class = "card-body", DTOutput("qtl_effects_table_train"), tags$br(), downloadButton("download_train_results", "Download")) + )) + ), + fluidRow( + column(12, div(class = "card", + div(class = "card-header", "QTL Effects — Test Set (Predicted)"), + div(class = "card-body", DTOutput("qtl_effects_table_test"), tags$br(), downloadButton("download_test_results", "Download")) + )) + ), + fluidRow( + column(12, div(class = "card", + div(class = "card-header", "Epistasis Analysis"), + div(class = "card-body", + DTOutput("epistasis_table"), + plotlyOutput("epistasis_heatmap", height = "400px"), + uiOutput("epistasis_warnings") + ) + )) + ) + ), + + # ---- INTERPRETATION TAB ---- + tabPanel("Interpretation", icon = icon("lightbulb"), + div(class = "main-header", + h2(tags$i(class="fas fa-lightbulb", style="margin-right:8px;"), "Results Interpretation"), + p("Comprehensive interpretation of QTL and domestication analysis") + ), + 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"), 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 TAB ---- + tabPanel("About", icon = icon("info-circle"), + div(class = "main-header", + h2(tags$i(class="fas fa-info-circle", style="margin-right:8px;"), "About"), + p("QTL Mapping with Domestication Analysis — RAG-Enhanced Version") + ), + fluidRow( + column(8, offset = 2, + div(class = "card", + div(class = "card-body", + h4(style="color:#58a6ff; font-family: 'IBM Plex Mono'; margin-bottom:12px;", "Methodology"), + tags$ul(style="color: #8b949e; line-height: 2;", + tags$li("Random Forest for QTL mapping with variable importance scoring"), + tags$li("LOD scores derived from marker importance (-log10 scale)"), + tags$li("Additive and dominance effects estimated via linear regression"), + tags$li("Epistasis analysis: pairwise QTL x marker interactions"), + tags$li("Domestication: Fst, nucleotide diversity (Pi), Tajima's D"), + tags$li("RAG chatbot: context-aware Q&A powered by Ollama (local LLM)") + ), + h4(style="color:#58a6ff; font-family: 'IBM Plex Mono'; margin: 12px 0;", "AI Assistant Setup"), + p(style="color: #8b949e; line-height: 1.7;", + "The AI assistant uses Retrieval-Augmented Generation (RAG) with a local LLM via Ollama. ", + "Install Ollama from ", tags$a("ollama.ai", href="https://ollama.ai", style="color:#58a6ff;"), + " and run: ", tags$code(style="background:#21262d; padding:2px 6px; border-radius:3px; color:#e6edf3;", "ollama pull llama3.2"), + " then start with: ", tags$code(style="background:#21262d; padding:2px 6px; border-radius:3px; color:#e6edf3;", "ollama serve"), + ". Without Ollama, the chatbot uses built-in rule-based responses." + ), + h4(style="color:#58a6ff; font-family: 'IBM Plex Mono'; margin: 12px 0;", "Interpretation Thresholds"), + tags$ul(style="color: #8b949e; line-height: 2;", + tags$li("LOD > 3: Suggestive QTL | LOD > 5: Significant QTL"), + tags$li("Fst > 0.2: Strong population differentiation"), + tags$li("Tajima's D < -2: Potential selective sweep"), + tags$li("PVE > 10%: Major-effect QTL") + ) + ) + ) + ) + ) + ) + ), + + # ============================================================ + # FLOATING CHATBOT PANEL + # ============================================================ + tags$div(id = "chat-panel", + + tags$div(id = "chat-window", + # Header + tags$div(id = "chat-header", + tags$div(class = "chat-title", + tags$div(class = "chat-avatar", "Q"), + tags$div( + tags$h4("QTL Analysis Assistant"), + tags$p(id = "ollama_status", + tags$span(class = "status-dot online", id = "status_dot"), + span(id = "status_text", " AI Assistant Ready") + ) + ) + ), + tags$button(id = "chat-close-btn", onclick = "document.getElementById('chat-window').classList.remove('open');", + tags$i(class = "fas fa-times") + ) + ), + + # Quick question chips + tags$div(class = "quick-questions", + tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q', 'What are my top QTLs?', {priority: 'event'});", "Top QTLs"), + tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q', 'How is the model performing?', {priority: 'event'});", "Model performance"), + tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q', 'What is epistasis?', {priority: 'event'});", "Epistasis"), + tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q', 'Explain Fst results', {priority: 'event'});", "Fst results"), + tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q', 'What does Tajima\\'s D mean?', {priority: 'event'});", "Tajima's D"), + tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q', 'How to interpret PVE?', {priority: 'event'});", "PVE meaning") + ), + + # Messages + tags$div(id = "chat_messages", + uiOutput("chat_display") + ), + + # Footer + tags$div(id = "chat-footer", + tags$textarea( + id = "chat_input", + placeholder = "Ask about your QTL results... (Enter to send)", + rows = "2", + style = "width:100%;" + ), + tags$div(class = "chat-actions", + tags$button(id = "send_chat", onclick = "Shiny.setInputValue('send_clicked', Math.random());", + tags$i(class = "fas fa-paper-plane"), "Send" + ), + tags$button(id = "clear_chat", onclick = "Shiny.setInputValue('clear_chat', Math.random());", + tags$i(class = "fas fa-trash-alt"), "Clear" + ) + ) + ) + ), + + # Toggle button + 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, + chromosome_info = NULL, position_info = NULL, + all_markers = NULL, importance_scores = NULL, + lod_scores_train = NULL, model_fit = NULL, + phenotype_values = NULL, qtl_effects_train = NULL, + qtl_effects_test = NULL, performance_metrics = NULL, + train_predictions = NULL, test_predictions = NULL, + epistasis_all = NULL, epistasis_sig = NULL, epistasis_warnings = NULL, + pop_data = NULL, selection_metrics = NULL, + has_test_data = FALSE, + genotype_preview_data = NULL, phenotype_preview_data = NULL, + test_genotype_preview_data = NULL, pop_preview_data = NULL, + # Chat state + chat_history = list(), + chat_messages = list(), + is_typing = FALSE, + ollama_available = FALSE + ) + + # Add JS handler for eval messages + tags$script(HTML("Shiny.addCustomMessageHandler('eval', function(msg) { eval(msg.code); });")) + + # ---- No Ollama check - rule-based mode is instant and always ready ---- + # If you have Ollama running locally, set values$ollama_available <- TRUE manually below + values$ollama_available <- FALSE + session$sendCustomMessage(type = "eval", list( + code = "document.getElementById('status_dot').className='status-dot online'; document.getElementById('status_text').innerText=' AI Assistant Ready';" + )) + + # ---- CHAT LOGIC ---- + + add_message <- function(role, text) { + timestamp <- format(Sys.time(), "%H:%M") + values$chat_messages <- c(values$chat_messages, list(list(role = role, text = text, time = timestamp))) + } + + process_chat <- function(user_text) { + if (nchar(trimws(user_text)) == 0) return() + + # Add user message + add_message("user", user_text) + + # Retrieve RAG context + static_ctx <- retrieve_context(user_text, top_k = 3) + dynamic_ctx <- build_results_context(values) + full_context <- paste(c(dynamic_ctx, static_ctx), collapse = "\n\n") + + # Get response + if (values$ollama_available) { + # Build simplified history for API + api_history <- lapply(tail(values$chat_messages, 8), function(m) { + list(role = m$role, content = m$text) + }) + api_history <- api_history[sapply(api_history, function(m) m$role != "user" || m$content != user_text)] + + result <- query_llm(user_text, full_context, api_history) + + if (result$success) { + add_message("assistant", result$text) + # Update chat history for context + values$chat_history <- c(values$chat_history, + list(list(role = "user", content = user_text)), + list(list(role = "assistant", content = result$text)) + ) + if (length(values$chat_history) > 20) values$chat_history <- tail(values$chat_history, 20) + } else { + # Ollama failed, use rule-based + resp_text <- rule_based_response(user_text, full_context, values, values$chat_messages) + add_message("assistant", resp_text) + } + } else { + resp_text <- rule_based_response(user_text, full_context, values, values$chat_messages) + add_message("assistant", resp_text) + } + + session$sendCustomMessage("scrollChatBottom", list()) + } + + # Handle send button + observeEvent(input$send_clicked, { + req(input$chat_input) + user_text <- trimws(input$chat_input) + if (nchar(user_text) == 0) return() + + updateTextAreaInput(session, "chat_input", value = "") + process_chat(user_text) + }) + + # Handle quick questions + observeEvent(input$quick_q, { + req(input$quick_q) + process_chat(input$quick_q) + }) + + # Clear chat + observeEvent(input$clear_chat, { + values$chat_messages <- list() + values$chat_history <- list() + }) + + # Initialize with welcome message + observe({ + if (length(values$chat_messages) == 0) { + add_message("assistant", paste0( + "Hello! I'm your QTL analysis assistant powered by RAG. ", + "I can help you interpret LOD scores, QTL effects, epistasis, Fst, Tajima's D, and more. ", + "Upload your data and run the analysis, then ask me anything about your results! ", + "Try the quick question buttons above to get started." + )) + } + }) + + # Render chat messages + output$chat_display <- renderUI({ + msgs <- values$chat_messages + if (length(msgs) == 0) return(NULL) + + tagList(lapply(msgs, function(m) { + # Split text on newlines for formatted rendering + text_lines <- strsplit(m$text, "\n", fixed = TRUE)[[1]] + + # Style each line based on content type + bubble_content <- tagList(lapply(text_lines, function(line) { + if (nchar(trimws(line)) == 0) { + tags$div(style = "height: 6px;") + } else if (grepl("^[0-9]+\\.", trimws(line))) { + tags$div(style = "margin: 3px 0; padding-left: 2px;", line) + } else if (grepl("^[-]", trimws(line))) { + tags$div(style = "margin: 2px 0; padding-left: 8px;", line) + } else if (grepl("^[A-Z][A-Z].*:", line)) { + tags$div(style = "margin: 5px 0 2px 0; font-weight: 600; color: #79c0ff;", line) + } else { + tags$div(line) + } + })) + + div(class = paste("chat-msg", m$role), + div(class = "chat-bubble", bubble_content), + div(class = "chat-meta", m$time) + ) + })) + }) + + # ---- HELPER FUNCTIONS ---- + + calculate_qtl_effects <- function(genotype_matrix, phenotype_vector, marker_names, dataset_name = "Training") { + effects_list <- list() + for (marker in marker_names) { + if (!marker %in% colnames(genotype_matrix)) next + geno <- genotype_matrix[, marker] + pheno <- phenotype_vector + valid_idx <- !is.na(geno) & !is.na(pheno) + geno <- geno[valid_idx]; pheno <- pheno[valid_idx] + if (length(unique(geno)) < 2) next + unique_genos <- sort(unique(geno)) + if (length(unique_genos) >= 2) { + lm_fit <- lm(pheno ~ geno) + additive_effect <- coef(lm_fit)[2] + dominance_effect <- NA + if (length(unique_genos) == 3) { + geno_means <- tapply(pheno, geno, mean, na.rm = TRUE) + het_mean <- geno_means[as.character(unique_genos[2])] + midparent <- (geno_means[as.character(unique_genos[1])] + geno_means[as.character(unique_genos[3])]) / 2 + dominance_effect <- het_mean - midparent + } + r_squared <- summary(lm_fit)$r.squared + se_additive <- summary(lm_fit)$coefficients[2, 2] + effects_list[[marker]] <- list( + Marker = marker, Additive_Effect = additive_effect, + Dominance_Effect = dominance_effect, PVE_Percent = r_squared * 100, + SE_Additive = se_additive, + CI_Lower = additive_effect - 1.96 * se_additive, + CI_Upper = additive_effect + 1.96 * se_additive, + N_Samples = length(pheno), Dataset = dataset_name + ) + } + } + if (length(effects_list) == 0) return(NULL) + do.call(rbind, lapply(effects_list, function(x) { + data.frame( + Marker = x$Marker, Additive_Effect = round(x$Additive_Effect, 4), + Dominance_Effect = ifelse(is.na(x$Dominance_Effect), NA, round(x$Dominance_Effect, 4)), + PVE_Percent = round(x$PVE_Percent, 2), SE_Additive = round(x$SE_Additive, 4), + CI_Lower = round(x$CI_Lower, 4), CI_Upper = round(x$CI_Upper, 4), + N_Samples = x$N_Samples, Dataset = x$Dataset, stringsAsFactors = FALSE + ) + })) + } + + calculate_selection_metrics <- function(genotype_matrix, pop_data, all_markers) { + selection_metrics <- list() + for (marker in colnames(genotype_matrix)) { + geno <- genotype_matrix[, marker] + pop <- pop_data$population[match(rownames(genotype_matrix), pop_data$id)] + valid_idx <- !is.na(geno) & !is.na(pop) + geno <- geno[valid_idx]; pop <- pop[valid_idx] + if (length(unique(geno)) < 2 || length(unique(pop)) < 2) next + geno_dom <- geno[pop == "Domesticated"]; geno_wild <- geno[pop == "Wild"] + if (length(geno_dom) < 2 || length(geno_wild) < 2) next + freq_dom <- mean(geno_dom, na.rm = TRUE) / 2 + freq_wild <- mean(geno_wild, na.rm = TRUE) / 2 + p_avg <- (freq_dom + freq_wild) / 2 + fst <- if (p_avg > 0 && p_avg < 1) { + val <- (mean((freq_dom - freq_wild)^2) / (p_avg * (1 - p_avg))) + max(0, min(1, val / (1 + val))) + } else 0 + pi_dom <- 2 * freq_dom * (1 - freq_dom) + pi_wild <- 2 * freq_wild * (1 - freq_wild) + n_dom <- length(geno_dom); n_wild <- length(geno_wild) + tajima_d_dom <- pi_dom - (1 / (1 + 2 * n_dom * (n_dom - 1) / (2 * n_dom - 1))) + tajima_d_wild <- pi_wild - (1 / (1 + 2 * n_wild * (n_wild - 1) / (2 * n_wild - 1))) + selection_metrics[[marker]] <- list( + Marker = marker, + Chromosome = all_markers$Chromosome[all_markers$Marker == marker], + Position = all_markers$Position[all_markers$Marker == marker], + Fst = fst, Pi_Dom = pi_dom, Pi_Wild = pi_wild, + Tajima_D_Dom = tajima_d_dom, Tajima_D_Wild = tajima_d_wild + ) + } + if (length(selection_metrics) == 0) return(NULL) + do.call(rbind, lapply(selection_metrics, function(x) { + data.frame(Marker=x$Marker, Chromosome=x$Chromosome, Position=x$Position, + Fst=round(x$Fst,4), Pi_Dom=round(x$Pi_Dom,4), Pi_Wild=round(x$Pi_Wild,4), + Tajima_D_Dom=round(x$Tajima_D_Dom,4), Tajima_D_Wild=round(x$Tajima_D_Wild,4), + stringsAsFactors=FALSE) + })) + } + + # ---- DATA LOADING ---- + + observeEvent(input$genotype_file, { + req(input$genotype_file) + tryCatch({ + values$genotype_preview_data <- read.csv(input$genotype_file$datapath) + all_data <- readLines(input$genotype_file$datapath) + if (length(all_data) < 4) { showNotification("Genotype file must have at least four 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 = all_data[-(1:3)], header = FALSE) + colnames(genotype_data) <- header + rownames(genotype_data) <- genotype_data[, 1] + genotype_data <- genotype_data[, -1] + pos_numeric <- as.numeric(position_row[-1]) + if (any(is.na(pos_numeric))) { showNotification("Position row contains non-numeric values.", type = "error"); return() } + values$all_markers <- data.frame(Marker = colnames(genotype_data), Chromosome = chromosome_row[-1], Position = pos_numeric, stringsAsFactors = FALSE) + values$genotype_data <- genotype_data + values$chromosome_info <- chromosome_row[-1] + values$position_info <- pos_numeric + showNotification("Training genotype data loaded.", type = "message") + }, error = function(e) { showNotification(paste("Error:", e$message), type = "error") }) + }) + + observeEvent(input$phenotype_file, { + req(input$phenotype_file) + tryCatch({ + values$phenotype_preview_data <- read.csv(input$phenotype_file$datapath) + phenotype_data <- read.csv(input$phenotype_file$datapath) + rownames(phenotype_data) <- phenotype_data[, 1] + phenotype_data <- phenotype_data[, -1] + for (col in colnames(phenotype_data)) { + phenotype_data[[col]] <- as.numeric(as.character(phenotype_data[[col]])) + } + values$phenotype_data <- phenotype_data + updateSelectInput(session, "phenotype_column", choices = colnames(phenotype_data), selected = colnames(phenotype_data)[1]) + showNotification("Training phenotype data loaded.", type = "message") + }, error = function(e) { showNotification(paste("Error:", e$message), type = "error") }) + }) + + observeEvent(input$test_genotype_file, { + req(input$test_genotype_file) + tryCatch({ + values$test_genotype_preview_data <- read.csv(input$test_genotype_file$datapath) + all_data <- readLines(input$test_genotype_file$datapath) + 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 = all_data[-(1:3)], header = FALSE) + colnames(genotype_data) <- header + rownames(genotype_data) <- genotype_data[, 1] + genotype_data <- genotype_data[, -1] + pos_numeric <- as.numeric(position_row[-1]) + test_markers <- data.frame(Marker = colnames(genotype_data), Chromosome = chromosome_row[-1], Position = pos_numeric, stringsAsFactors = FALSE) + if (!is.null(values$all_markers)) { + values$all_markers <- unique(rbind(values$all_markers, test_markers)) + } + values$test_genotype_data <- genotype_data + values$has_test_data <- TRUE + showNotification("Test genotype data loaded.", type = "message") + }, error = function(e) { showNotification(paste("Error:", e$message), type = "error") }) + }) + + observeEvent(input$pop_file, { + req(input$pop_file) + tryCatch({ + pop_data <- read.csv(input$pop_file$datapath) + values$pop_preview_data <- pop_data + if (!"id" %in% colnames(pop_data) || !"population" %in% colnames(pop_data)) { + showNotification("Population file must have 'id' and 'population' columns.", type = "error"); return() + } + values$pop_data <- pop_data + showNotification("Population data loaded.", type = "message") + }, error = function(e) { showNotification(paste("Error:", e$message), type = "error") }) + }) + + # ---- DATA PREVIEWS ---- + output$geno_preview <- renderDT({ req(values$genotype_preview_data); datatable(values$genotype_preview_data, options = list(pageLength = 5, scrollX = TRUE)) }) + output$pheno_preview <- renderDT({ req(values$phenotype_preview_data); datatable(values$phenotype_preview_data, options = list(pageLength = 5, scrollX = TRUE)) }) + output$test_geno_preview <- renderDT({ req(values$test_genotype_preview_data); datatable(values$test_genotype_preview_data, options = list(pageLength = 5, scrollX = TRUE)) }) + output$pop_preview <- renderDT({ req(values$pop_preview_data); datatable(values$pop_preview_data, options = list(pageLength = 5, scrollX = TRUE)) }) + output$predicted_test_pheno_preview <- renderDT({ req(values$predicted_test_phenotype_data); datatable(values$predicted_test_phenotype_data, options = list(pageLength = 5, scrollX = TRUE)) }) + + # ---- PREDICT TEST PHENOTYPE ---- + observeEvent(input$predict_test_phenotype, { + req(values$model_fit, values$test_genotype_data) + tryCatch({ + common_markers <- intersect(colnames(values$test_genotype_data), colnames(values$genotype_data)) + if (length(common_markers) == 0) { showNotification("No common markers.", type = "error"); return() } + X_test <- values$test_genotype_data[, common_markers, drop = FALSE] + predictions <- predict(values$model_fit, newdata = X_test) + values$predicted_test_phenotype_data <- data.frame(id = rownames(X_test), Predicted_Phenotype = as.numeric(predictions), stringsAsFactors = FALSE) + showNotification("Test phenotype prediction completed!", type = "message") + }, error = function(e) { showNotification(paste("Error:", e$message), type = "error") }) + }) + + # ---- RUN QTL ANALYSIS ---- + observeEvent(input$run_analysis, { + req(values$genotype_data, values$phenotype_data, input$phenotype_column) + showNotification("Running QTL analysis...", type = "message") + 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_train <- values$genotype_data[common_samples, , drop = FALSE] + y_train <- as.numeric(values$phenotype_data[common_samples, input$phenotype_column]) + values$phenotype_values <- y_train + + nzv <- nearZeroVar(X_train) + if (length(nzv) > 0) X_train <- X_train[, -nzv, drop = FALSE] + + set.seed(123) + trainIndex <- createDataPartition(y_train, p = 1 - input$test_size, list = FALSE) + X_tr <- X_train[trainIndex, , drop = FALSE]; X_val <- X_train[-trainIndex, , drop = FALSE] + y_tr <- y_train[trainIndex]; y_val <- y_train[-trainIndex] + + model <- train(x = X_tr, y = y_tr, method = "rf", + trControl = trainControl(method = "cv", number = 5), + importance = TRUE, tuneLength = 3) + values$model_fit <- model + + imp <- varImp(model, scale = FALSE)$importance + importance_scores <- data.frame( + Marker = rownames(imp), LOD = imp$Overall, + Chromosome = values$chromosome_info[match(rownames(imp), colnames(values$genotype_data))], + Position = as.numeric(values$position_info[match(rownames(imp), colnames(values$genotype_data))]), + stringsAsFactors = FALSE + ) + values$importance_scores <- importance_scores + + lod_sig <- importance_scores[importance_scores$LOD > input$lod_threshold, , drop = FALSE] + + if (nrow(lod_sig) > 0) { + lod_sig$Low_Flank <- NA; lod_sig$High_Flank <- NA + for (i in 1:nrow(lod_sig)) { + chr_m <- values$all_markers[values$all_markers$Chromosome == lod_sig$Chromosome[i], ] + chr_m <- chr_m[order(chr_m$Position), ] + idx <- which(chr_m$Marker == lod_sig$Marker[i]) + lod_sig$Low_Flank[i] <- if (idx > 1) chr_m$Marker[idx-1] else lod_sig$Marker[i] + lod_sig$High_Flank[i] <- if (idx < nrow(chr_m)) chr_m$Marker[idx+1] else lod_sig$Marker[i] + } + values$lod_scores_train <- lod_sig + + qtl_fx <- calculate_qtl_effects(X_train, y_train, lod_sig$Marker, "Training") + values$qtl_effects_train <- if (!is.null(qtl_fx)) merge(lod_sig, qtl_fx, by = "Marker") else data.frame(Message = "No QTL effects calculated.") + } else { + values$lod_scores_train <- lod_sig + values$qtl_effects_train <- data.frame(Message = paste("No significant QTLs above LOD", input$lod_threshold)) + } + + # Performance + y_tr_pred <- predict(model, X_tr); y_val_pred <- predict(model, X_val) + values$performance_metrics <- data.frame( + Metric = c("R² (Train)", "R (Train)", "R² (Validation)", "R (Validation)"), + Value = c( + 1 - sum((y_tr - y_tr_pred)^2) / sum((y_tr - mean(y_tr))^2), + cor(y_tr, y_tr_pred), + 1 - sum((y_val - y_val_pred)^2) / sum((y_val - mean(y_val))^2), + cor(y_val, y_val_pred) + ), stringsAsFactors = FALSE + ) + values$train_predictions <- data.frame(Observed = y_tr, Predicted = y_tr_pred) + values$test_predictions <- data.frame(Observed = y_val, Predicted = y_val_pred) + + # Epistasis + values$epistasis_warnings <- character() + if (nrow(values$lod_scores_train) >= 1) { + sig_markers <- values$lod_scores_train$Marker[values$lod_scores_train$Marker %in% colnames(X_train)] + all_m <- colnames(X_train) + epistasis_all <- data.frame(); epistasis_sig <- data.frame() + total_pairs <- length(sig_markers) * length(all_m) + withProgress(message = 'Epistasis analysis', value = 0, { + pair_count <- 0 + for (m1 in sig_markers) { + for (m2 in all_m) { + if (m1 == m2) next + pair_count <- pair_count + 1 + incProgress(1/total_pairs, detail = sprintf("Pair %d/%d", pair_count, total_pairs)) + tryCatch({ + ds <- data.frame(y=y_train, m1=X_train[common_samples, m1], m2=X_train[common_samples, m2]) + if (any(is.na(ds))) next + fit <- lm(y ~ m1 + m2 + m1:m2, data = ds) + cs <- summary(fit)$coefficients + if ("m1:m2" %in% rownames(cs)) { + p_val <- cs["m1:m2", "Pr(>|t|)"] + eff <- coef(fit)["m1:m2"] + row <- data.frame(QTL1=m1, QTL2=m2, Interaction_p=round(p_val,4), Effect_Size=round(eff,4), stringsAsFactors=FALSE) + epistasis_all <- rbind(epistasis_all, row) + if (p_val < 0.05) epistasis_sig <- rbind(epistasis_sig, row) + } + }, error = function(e) {}) + } + } + }) + values$epistasis_all <- if (nrow(epistasis_all) == 0) data.frame(Message = "No valid interactions.") else epistasis_all + values$epistasis_sig <- if (nrow(epistasis_sig) == 0) data.frame(Message = "No significant interactions (p<0.05).") else epistasis_sig + } else { + values$epistasis_all <- data.frame(Message = "No significant QTLs for epistasis.") + values$epistasis_sig <- data.frame(Message = "No significant QTLs for epistasis.") + } + + showNotification("QTL analysis completed!", type = "message") + updateTabsetPanel(session, "nav", selected = "Results") + }, error = function(e) { showNotification(paste("Error:", e$message), type = "error") }) + }) + + # ---- RUN DOMESTICATION ANALYSIS ---- + observeEvent(input$run_domestication, { + req(values$genotype_data, values$pop_data, values$all_markers) + showNotification("Running domestication analysis...", type = "message") + tryCatch({ + common_samples <- intersect(rownames(values$genotype_data), values$pop_data$id) + if (length(common_samples) == 0) { showNotification("No common samples.", type = "error"); return() } + X <- values$genotype_data[common_samples, , drop = FALSE] + pop_data <- values$pop_data[values$pop_data$id %in% common_samples, ] + sel_metrics <- calculate_selection_metrics(X, pop_data, values$all_markers) + if (is.null(sel_metrics)) { showNotification("No valid selection metrics.", type = "error"); return() } + sel_metrics$Significant <- sel_metrics$Fst > input$fst_threshold | sel_metrics$Tajima_D_Dom < input$tajima_threshold | sel_metrics$Tajima_D_Wild < input$tajima_threshold + values$selection_metrics <- sel_metrics + showNotification("Domestication analysis completed!", type = "message") + updateTabsetPanel(session, "nav", selected = "Domestication") + }, error = function(e) { showNotification(paste("Error:", e$message), type = "error") }) + }) + + # ---- SIMULATION ---- + observeEvent(input$simulate_btn, { session$sendCustomMessage("simulateQTLDiscovery", list()) }) + observeEvent(input$reset_btn, { session$sendCustomMessage("resetAnimation", list()) }) + + # ---- PLOTS ---- + + make_manhattan <- function(data, y_col, title, threshold_val, threshold_col = "red", color_col = "Chromosome") { + if (nrow(data) == 0) return(plotly_empty() %>% layout(title = "No data available")) + unique_chroms <- unique(data[[color_col]]) + chrom_labels <- paste0("Chr", seq_along(unique_chroms)) + data[[color_col]] <- factor(data[[color_col]], levels = unique_chroms, labels = chrom_labels) + max_pos <- tapply(data$Position, data[[color_col]], max, na.rm = TRUE) + offsets <- cumsum(as.numeric(max_pos)) + seq_along(max_pos) * max(max_pos, na.rm = TRUE) * 0.05 + offsets <- c(0, offsets[-length(offsets)]); names(offsets) <- chrom_labels + data$CumPos <- data$Position + offsets[as.character(data[[color_col]])] + tick_vals <- tapply(data$CumPos, data[[color_col]], mean, na.rm = TRUE) + + plot_ly(data = data, x = ~CumPos, y = as.formula(paste0("~", y_col)), + color = as.formula(paste0("~", color_col)), type = 'scatter', mode = 'markers', + marker = list(size = 5, opacity = 0.8), + colors = viridis(length(unique_chroms)), + text = ~paste("Marker:", Marker, "| Chr:", get(color_col), "| Pos:", Position, "|", y_col, ":", round(get(y_col), 3)), + hoverinfo = 'text') %>% + layout( + title = list(text = title, font = list(family = "IBM Plex Mono", size = 13, color = "#8b949e")), + plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", + font = list(color = "#8b949e", family = "IBM Plex Sans"), + xaxis = list(title = "Chromosome", ticktext = chrom_labels, tickvals = tick_vals, tickangle = 45, gridcolor = "#21262d", zeroline = FALSE), + yaxis = list(title = y_col, gridcolor = "#21262d", zeroline = FALSE), + shapes = list(list(type = "line", x0 = min(data$CumPos, na.rm = TRUE), x1 = max(data$CumPos, na.rm = TRUE), + y0 = threshold_val, y1 = threshold_val, line = list(color = threshold_col, dash = "dash", width = 1.5))), + legend = list(bgcolor = "#21262d", bordercolor = "#30363d") + ) + } + + output$lod_plot_2d <- renderPlotly({ + req(values$importance_scores) + p <- make_manhattan(values$importance_scores, "LOD", "Manhattan Plot — LOD Scores", input$lod_threshold) + if (!is.null(values$lod_scores_train) && nrow(values$lod_scores_train) > 0) { + lod_sig <- values$lod_scores_train + unique_chroms <- unique(values$importance_scores$Chromosome) + chrom_labels <- paste0("Chr", seq_along(unique_chroms)) + lod_sig$Chromosome <- factor(lod_sig$Chromosome, levels = unique_chroms, labels = chrom_labels) + max_pos <- tapply(values$importance_scores$Position, factor(values$importance_scores$Chromosome, levels = unique_chroms, labels = chrom_labels), max, na.rm = TRUE) + offsets <- cumsum(as.numeric(max_pos)) + seq_along(max_pos) * max(max_pos, na.rm = TRUE) * 0.05 + offsets <- c(0, offsets[-length(offsets)]); names(offsets) <- chrom_labels + lod_sig$CumPos <- lod_sig$Position + offsets[as.character(lod_sig$Chromosome)] + p <- p %>% add_trace(data = lod_sig, x = ~CumPos, y = ~LOD, type = 'scatter', mode = 'markers', + name = 'Significant QTL', marker = list(size = 10, color = '#f85149', symbol = 'diamond', line = list(color = '#ff7b7b', width = 1.5)), + text = ~paste("QTL:", Marker, "| Chr:", Chromosome, "| LOD:", round(LOD, 2)), hoverinfo = 'text') + } + p + }) + + output$fst_plot <- renderPlotly({ + req(values$selection_metrics) + if ("Message" %in% colnames(values$selection_metrics)) return(plotly_empty()) + make_manhattan(values$selection_metrics, "Fst", "Manhattan Plot — Fst", input$fst_threshold) + }) + + output$tajima_plot <- renderPlotly({ + req(values$selection_metrics) + if ("Message" %in% colnames(values$selection_metrics)) return(plotly_empty()) + sel <- values$selection_metrics + unique_chroms <- unique(sel$Chromosome); chrom_labels <- paste0("Chr", seq_along(unique_chroms)) + sel$Chromosome <- factor(sel$Chromosome, levels = unique_chroms, labels = chrom_labels) + max_pos <- tapply(sel$Position, sel$Chromosome, max, na.rm = TRUE) + offsets <- cumsum(as.numeric(max_pos)) + seq_along(max_pos) * max(max_pos, na.rm = TRUE) * 0.05 + offsets <- c(0, offsets[-length(offsets)]); names(offsets) <- chrom_labels + sel$CumPos <- sel$Position + offsets[as.character(sel$Chromosome)] + tick_vals <- tapply(sel$CumPos, sel$Chromosome, mean, na.rm = TRUE) + plot_ly() %>% + add_trace(data=sel, x=~CumPos, y=~Tajima_D_Dom, color=~Chromosome, type='scatter', mode='markers', + marker=list(size=5), colors=viridis(length(unique_chroms)), name="Domesticated", + text=~paste("Marker:", Marker, "| Chr:", Chromosome, "| D(Dom):", round(Tajima_D_Dom,3)), hoverinfo='text') %>% + add_trace(data=sel, x=~CumPos, y=~Tajima_D_Wild, type='scatter', mode='markers', name="Wild", + marker=list(size=5, color='#f97316', opacity=0.7), + text=~paste("Marker:", Marker, "| D(Wild):", round(Tajima_D_Wild,3)), hoverinfo='text') %>% + layout( + title=list(text="Manhattan Plot — Tajima's D", font=list(family="IBM Plex Mono", size=13, color="#8b949e")), + plot_bgcolor="#0d1117", paper_bgcolor="#161b22", + font=list(color="#8b949e", family="IBM Plex Sans"), + xaxis=list(title="Chromosome", ticktext=chrom_labels, tickvals=tick_vals, tickangle=45, gridcolor="#21262d"), + yaxis=list(title="Tajima's D", gridcolor="#21262d"), + shapes=list(list(type="line", x0=min(sel$CumPos,na.rm=TRUE), x1=max(sel$CumPos,na.rm=TRUE), + y0=input$tajima_threshold, y1=input$tajima_threshold, line=list(color="red",dash="dash",width=1.5))), + legend=list(bgcolor="#21262d", bordercolor="#30363d") + ) + }) + + output$performance_plot <- renderPlotly({ + req(values$performance_metrics) + pm <- values$performance_metrics + plot_ly(data=pm, x=~Metric, y=~Value, type='bar', + marker=list(color=c('#58a6ff','#58a6ff','#3fb950','#3fb950'), opacity=0.85, + line=list(color=c('#79c0ff','#79c0ff','#56d364','#56d364'), width=1.5)), + text=~round(Value,3), textposition='outside') %>% + layout( + title=list(text="Model Performance", font=list(family="IBM Plex Mono",size=13,color="#8b949e")), + plot_bgcolor="#0d1117", paper_bgcolor="#161b22", + font=list(color="#8b949e", family="IBM Plex Sans"), + xaxis=list(gridcolor="#21262d", tickangle=15), + yaxis=list(title="Value", range=c(0,1.1), gridcolor="#21262d") + ) + }) + + output$regression_plot_train <- renderPlotly({ + req(values$train_predictions) + df <- values$train_predictions + plot_ly(data=df, x=~Observed, y=~Predicted, type='scatter', mode='markers', + marker=list(size=6, color='#58a6ff', opacity=0.7)) %>% + add_lines(x=range(df$Observed), y=range(df$Observed), name="1:1 line", + line=list(color='#f85149', dash='dash', width=1.5)) %>% + layout(title=list(text="Training Set", font=list(family="IBM Plex Mono",size=12,color="#8b949e")), + plot_bgcolor="#0d1117", paper_bgcolor="#161b22", + font=list(color="#8b949e"), xaxis=list(gridcolor="#21262d"), yaxis=list(gridcolor="#21262d"), + showlegend=FALSE) + }) + + output$regression_plot_test <- renderPlotly({ + req(values$test_predictions) + df <- values$test_predictions + plot_ly(data=df, x=~Observed, y=~Predicted, type='scatter', mode='markers', + marker=list(size=6, color='#3fb950', opacity=0.7)) %>% + add_lines(x=range(df$Observed), y=range(df$Observed), name="1:1 line", + line=list(color='#f85149', dash='dash', width=1.5)) %>% + layout(title=list(text="Validation Set", font=list(family="IBM Plex Mono",size=12,color="#8b949e")), + plot_bgcolor="#0d1117", paper_bgcolor="#161b22", + font=list(color="#8b949e"), xaxis=list(gridcolor="#21262d"), yaxis=list(gridcolor="#21262d"), + showlegend=FALSE) + }) + + output$epistasis_heatmap <- renderPlotly({ + req(values$epistasis_all) + if ("Message" %in% colnames(values$epistasis_all)) return(plotly_empty() %>% layout(title=values$epistasis_all$Message[1])) + qtls <- unique(values$epistasis_all$QTL1); markers <- unique(values$epistasis_all$QTL2) + p_mat <- matrix(NA, nrow=length(qtls), ncol=length(markers), dimnames=list(qtls, markers)) + for (i in 1:nrow(values$epistasis_all)) { + if (!is.na(values$epistasis_all$Interaction_p[i])) p_mat[values$epistasis_all$QTL1[i], values$epistasis_all$QTL2[i]] <- values$epistasis_all$Interaction_p[i] + } + p_melt <- melt(p_mat, na.rm=TRUE); colnames(p_melt) <- c("QTL1","QTL2","p_value") + plot_ly(data=p_melt, x=~QTL2, y=~QTL1, z=~p_value, type="heatmap", colorscale="Viridis", + hovertemplate="QTL: %{y}
Marker: %{x}
p-value: %{z:.4f}") %>% + layout(title=list(text="Epistatic Interactions (p-values)", font=list(family="IBM Plex Mono",size=13,color="#8b949e")), + plot_bgcolor="#0d1117", paper_bgcolor="#161b22", font=list(color="#8b949e"), + xaxis=list(title="Marker", gridcolor="#21262d"), yaxis=list(title="QTL", gridcolor="#21262d")) + }) + + # ---- TABLES ---- + output$qtl_effects_table_train <- renderDT({ + req(values$qtl_effects_train) + if ("Message" %in% colnames(values$qtl_effects_train)) return(datatable(values$qtl_effects_train, options=list(dom='t'))) + cols <- intersect(c("Marker","Chromosome","Position","LOD","Additive_Effect","Dominance_Effect","PVE_Percent","CI_Lower","CI_Upper","Low_Flank","High_Flank"), colnames(values$qtl_effects_train)) + d <- values$qtl_effects_train[order(-values$qtl_effects_train$LOD), cols, drop=FALSE] + datatable(d, options=list(pageLength=10, scrollX=TRUE, dom='Bfrtip'), rownames=FALSE) %>% + formatRound(intersect(c("LOD","Additive_Effect","PVE_Percent"), colnames(d)), 3) + }) + + output$qtl_effects_table_test <- renderDT({ + req(values$qtl_effects_test) + if ("Message" %in% colnames(values$qtl_effects_test)) return(datatable(values$qtl_effects_test, options=list(dom='t'))) + cols <- intersect(c("Marker","Chromosome","Position","LOD","Additive_Effect","Dominance_Effect","PVE_Percent","CI_Lower","CI_Upper","Low_Flank","High_Flank","Dataset"), colnames(values$qtl_effects_test)) + datatable(values$qtl_effects_test[order(-values$qtl_effects_test$LOD), cols, drop=FALSE], options=list(pageLength=10, scrollX=TRUE), rownames=FALSE) + }) + + output$epistasis_table <- renderDT({ + req(values$epistasis_sig) + if ("Message" %in% colnames(values$epistasis_sig)) return(datatable(data.frame(Message=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) + }) + + output$selection_table <- renderDT({ + req(values$selection_metrics) + if ("Message" %in% colnames(values$selection_metrics)) return(datatable(data.frame(Message=values$selection_metrics$Message[1]), options=list(dom='t'))) + sel <- values$selection_metrics + if (!is.null(values$lod_scores_train)) sel$QTL_Overlap <- sel$Marker %in% values$lod_scores_train$Marker + cols <- intersect(c("Marker","Chromosome","Position","Fst","Pi_Dom","Pi_Wild","Tajima_D_Dom","Tajima_D_Wild","Significant","QTL_Overlap"), colnames(sel)) + datatable(sel[, cols], options=list(pageLength=10, scrollX=TRUE, dom='Bfrtip'), rownames=FALSE) %>% + formatRound(c("Fst","Pi_Dom","Pi_Wild","Tajima_D_Dom","Tajima_D_Wild"), 3) + }) + + # ---- CHROMOSOME VIZ ---- + output$chromosome_viz <- renderUI({ + req(values$lod_scores_train, values$all_markers) + sel_metrics <- if (!is.null(values$selection_metrics) && !"Message" %in% colnames(values$selection_metrics)) values$selection_metrics else data.frame(Marker=character(0), Significant=logical(0), Chromosome=character(0)) + if (nrow(values$lod_scores_train) == 0) return(div(class="alert alert-info", paste("No significant QTLs above LOD", input$lod_threshold))) + + tagList(lapply(unique(values$lod_scores_train$Chromosome), function(chr) { + chr_m <- values$all_markers[values$all_markers$Chromosome == chr, ] + chr_m <- chr_m[order(chr_m$Position),] + sig_m <- values$lod_scores_train[values$lod_scores_train$Chromosome == chr, ] + sel_m <- sel_metrics[sel_metrics$Chromosome == chr & !is.na(sel_metrics$Significant) & sel_metrics$Significant, ] + min_p <- min(chr_m$Position, na.rm=TRUE); max_p <- max(chr_m$Position, na.rm=TRUE) + range_p <- max_p - min_p + div(class="chromosome-container", + div(class="chromosome-title", paste("CHR", chr)), + div(class="chromosome", + lapply(1:nrow(chr_m), function(i) { + mk <- chr_m[i, ] + left <- if (range_p > 0) ((mk$Position - min_p) / range_p) * 100 else (i / nrow(chr_m)) * 100 + is_qtl <- mk$Marker %in% sig_m$Marker + is_flank <- mk$Marker %in% c(sig_m$Low_Flank, sig_m$High_Flank) + is_sel <- mk$Marker %in% sel_m$Marker + cls <- "chromosome-marker" + if (is_qtl) cls <- paste(cls, "significant") + if (is_flank) cls <- paste(cls, "flanking") + if (is_sel) cls <- paste(cls, "selection") + div(class=cls, style=paste0("left:", left, "%;"), `data-marker`=mk$Marker) + }) + ), + div(class="chromosome-legend", span(paste0(min_p, " bp")), span(paste0(max_p, " bp"))) + ) + })) + }) + + # ---- EPISTASIS WARNINGS ---- + output$epistasis_warnings <- renderUI({ + req(values$epistasis_warnings) + if (length(values$epistasis_warnings) > 0) { + div(class="alert alert-warning", strong("Warnings:"), + tags$ul(lapply(values$epistasis_warnings, tags$li))) + } + }) + + # ---- INTERPRETATION OUTPUTS ---- + + mk_section <- function(title, content) { + div(class="interpretation-section", tags$h5(title), tags$p(content)) + } + + output$analysis_summary <- renderUI({ + req(values$qtl_effects_train, values$performance_metrics) + n_qtl <- if ("Message" %in% colnames(values$qtl_effects_train)) 0 else nrow(values$qtl_effects_train) + pm <- values$performance_metrics + train_r2 <- round(pm$Value[pm$Metric == "R² (Train)"], 3) + val_r2 <- round(pm$Value[pm$Metric == "R² (Validation)"], 3) + n_epi <- if (is.null(values$epistasis_sig) || "Message" %in% colnames(values$epistasis_sig)) 0 else nrow(values$epistasis_sig) + n_sel <- if (is.null(values$selection_metrics) || "Message" %in% colnames(values$selection_metrics)) 0 else sum(values$selection_metrics$Significant, na.rm=TRUE) + div( + mk_section("QTL MAPPING", paste(n_qtl, "significant QTLs detected above LOD threshold of", input$lod_threshold, ". Random Forest model explains", paste0(round(val_r2*100,1),"%"), "of variance on validation set.")), + mk_section("MODEL PERFORMANCE", paste("R²(Train)=", train_r2, "| R²(Validation)=", val_r2, ". A gap >0.2 suggests overfitting.")), + mk_section("EPISTASIS", paste(n_epi, "significant pairwise interactions detected (p<0.05).")), + mk_section("DOMESTICATION", paste(n_sel, "markers show significant selection signatures.")) + ) + }) + + output$qtl_interpretation <- renderUI({ + req(values$qtl_effects_train) + if ("Message" %in% colnames(values$qtl_effects_train)) return(mk_section("QTL SIGNIFICANCE", paste("No significant QTLs found above LOD", input$lod_threshold, ". Try lowering the threshold or increasing sample size."))) + top <- values$qtl_effects_train[which.max(values$qtl_effects_train$LOD), ] + mk_section("TOP QTL", paste0("Marker ", top$Marker, " on Chr ", top$Chromosome, " (pos ", top$Position, ") has the highest LOD score of ", round(top$LOD, 2), ". ", if(top$LOD > 5) "This is a significant QTL (LOD>5)." else if(top$LOD > 3) "This is a suggestive QTL (LOD>3)." else "This is below standard significance thresholds.")) + }) + + output$effect_interpretation <- renderUI({ + req(values$qtl_effects_train) + if ("Message" %in% colnames(values$qtl_effects_train)) return(mk_section("EFFECT SIZES", "Run analysis to see QTL effect sizes.")) + top_pve <- values$qtl_effects_train[which.max(values$qtl_effects_train$PVE_Percent), ] + top_add <- values$qtl_effects_train[which.max(abs(values$qtl_effects_train$Additive_Effect)), ] + div( + mk_section("HIGHEST PVE", paste0("Marker ", top_pve$Marker, " explains ", round(top_pve$PVE_Percent, 1), "% of phenotypic variance.", if(top_pve$PVE_Percent > 10) " This is a major-effect QTL." else " This is a minor-effect QTL.")), + mk_section("ADDITIVE EFFECT", paste0("Marker ", top_add$Marker, " has the largest additive effect (", round(top_add$Additive_Effect, 3), "). 95% CI: [", round(top_add$CI_Lower, 3), ", ", round(top_add$CI_Upper, 3), "].")) + ) + }) + + output$epistasis_interpretation <- renderUI({ + req(values$epistasis_sig) + if ("Message" %in% colnames(values$epistasis_sig)) return(mk_section("EPISTASIS", values$epistasis_sig$Message[1])) + top <- values$epistasis_sig[order(values$epistasis_sig$Interaction_p), ][1,] + mk_section("TOP INTERACTION", paste0("Strongest epistasis: ", top$QTL1, " × ", top$QTL2, " (p=", round(top$Interaction_p, 4), ", effect=", round(top$Effect_Size, 3), "). This interaction suggests the two loci have non-additive effects on the trait.")) + }) + + output$selection_interpretation <- renderUI({ + req(values$selection_metrics) + if ("Message" %in% colnames(values$selection_metrics)) return(mk_section("SELECTION SIGNATURES", "Run domestication analysis to see selection metrics.")) + n_sig <- sum(values$selection_metrics$Significant, na.rm=TRUE) + top_fst <- values$selection_metrics[which.max(values$selection_metrics$Fst), ] + mk_section("DOMESTICATION SIGNATURES", paste0(n_sig, " markers show significant selection. Highest Fst at ", top_fst$Marker, " (Fst=", round(top_fst$Fst, 3), ", Chr ", top_fst$Chromosome, "). High Fst and negative Tajima's D together indicate candidate domestication loci.")) + }) + + output$recommendations <- renderUI({ + req(values$qtl_effects_train) + n_qtl <- if ("Message" %in% colnames(values$qtl_effects_train)) 0 else nrow(values$qtl_effects_train) + recs <- if (n_qtl == 0) { + c("No significant QTLs detected. Consider lowering the LOD threshold or increasing sample size.", "Ensure genotype data uses 0/1/2 coding for biallelic markers.", "Check if phenotype values are numeric and correctly formatted.") + } else { + top <- values$qtl_effects_train[which.max(values$qtl_effects_train$LOD), ] + c(paste0("Prioritize marker ", top$Marker, " (LOD=", round(top$LOD,2), ") for functional validation."), + "Validate significant QTLs in an independent population or F2 cross.", + if (!is.null(values$epistasis_sig) && !"Message" %in% colnames(values$epistasis_sig)) "Investigate epistatic pairs — test combined marker effects in breeding programs." else "Run analysis to check for epistatic interactions.", + if (!is.null(values$selection_metrics) && !"Message" %in% colnames(values$selection_metrics) && any(values$selection_metrics$QTL_Overlap, na.rm=TRUE)) "QTL-selection overlap detected — these regions are strong domestication candidates." else "Upload population data to check for domestication signatures at QTL regions.", + "Use flanking markers to fine-map QTL intervals and identify candidate genes.") + } + div(mk_section("NEXT STEPS", + tags$ul(style="margin-top:8px; color:#8b949e; line-height:2;", + lapply(recs, function(r) tags$li(r)) + ) + )) + }) + + # ---- DOWNLOAD HANDLERS ---- + output$download_train_results <- downloadHandler( + filename = function() paste0("train_qtl_results_", Sys.Date(), ".xlsx"), + content = function(file) { + sheets <- list(Training_QTL_Effects = if (!is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train)) values$qtl_effects_train else data.frame(Message="No significant QTLs")) + if (!is.null(values$performance_metrics)) sheets$Model_Performance <- values$performance_metrics + write_xlsx(sheets, file) + } + ) + output$download_test_results <- downloadHandler( + filename = function() paste0("test_qtl_results_", Sys.Date(), ".xlsx"), + content = function(file) { + write_xlsx(list(Test_QTL_Effects = if (!is.null(values$qtl_effects_test) && !"Message" %in% colnames(values$qtl_effects_test)) values$qtl_effects_test else data.frame(Message="No data")), file) + } + ) + output$download_selection <- downloadHandler( + filename = function() paste0("selection_results_", Sys.Date(), ".xlsx"), + content = function(file) { + write_xlsx(list(Selection_Metrics = if (!is.null(values$selection_metrics) && !"Message" %in% colnames(values$selection_metrics)) values$selection_metrics else data.frame(Message="No data")), file) + } ) } -shinyApp(ui, server) +shinyApp(ui = ui, server = server) \ No newline at end of file