diff --git "a/app.R" "b/app.R"
--- "a/app.R"
+++ "b/app.R"
@@ -1,642 +1,198 @@
-library(shiny)
-library(randomForest)
-library(caret)
-library(DT)
-library(ggplot2)
-library(plotly)
-library(writexl)
-library(viridis)
-library(reshape2)
-library(dplyr)
-library(httr)
-library(jsonlite)
-
# ============================================================
-# RAG SYSTEM - Knowledge Base & Retrieval
+# QTL-Mapper - Enhanced with Transformer-based LLM for Hugging Face Spaces
# ============================================================
-# 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."
- ),
- 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."
- )
+# Package installation for Hugging Face
+options(repos = c(CRAN = "https://cloud.r-project.org"))
+
+# Install required packages if missing
+required_packages <- c(
+ "shiny", "randomForest", "caret", "DT", "ggplot2", "plotly",
+ "writexl", "viridis", "reshape2", "dplyr", "httr", "jsonlite",
+ "reticulate", "shinyjs", "markdown"
)
-# 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
- }
+for (pkg in required_packages) {
+ if (!require(pkg, character.only = TRUE)) {
+ install.packages(pkg, dependencies = TRUE)
+ library(pkg, character.only = TRUE)
}
-
- # 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")
}
-# 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")
-}
+# Initialize reticulate for Python-based transformers
+use_python("/usr/local/bin/python3", required = FALSE)
# ============================================================
-# LLM QUERY FUNCTION - Ollama (local) with fallback
+# TRANSFORMER-BASED LLM SYSTEM
# ============================================================
-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)
+# Check if we should use Hugging Face API or local model
+use_hf_api <- Sys.getenv("HF_API_TOKEN") != "" # Set this in Spaces secrets
+
+# Configuration
+hf_model <- "microsoft/phi-2" # Smaller model suitable for Q&A
+# Alternative models: "google/flan-t5-large", "microsoft/phi-2", "mistralai/Mistral-7B-Instruct-v0.1"
+
+# Hugging Face API configuration
+HF_API_TOKEN <- Sys.getenv("HF_API_TOKEN") # Set in Spaces secrets
+HF_API_URL <- paste0("https://api-inference.huggingface.co/models/", hf_model)
+
+# Function to query Hugging Face API
+query_hf_api <- function(prompt, max_length = 500, temperature = 0.7) {
+ if (HF_API_TOKEN == "") {
+ return(list(success = FALSE, error = "HF_API_TOKEN not set"))
}
- messages <- c(messages, list(list(role = "user", content = user_message)))
-
tryCatch({
response <- POST(
- url = paste0(ollama_url, "/api/chat"),
+ url = HF_API_URL,
+ add_headers(Authorization = paste("Bearer", HF_API_TOKEN)),
body = toJSON(list(
- model = model,
- messages = messages,
- stream = FALSE,
- options = list(
- temperature = 0.7,
- num_predict = 512
+ inputs = prompt,
+ parameters = list(
+ max_new_tokens = max_length,
+ temperature = temperature,
+ do_sample = TRUE,
+ top_p = 0.95
)
), auto_unbox = TRUE),
content_type_json(),
- timeout(30)
+ timeout(60)
)
if (status_code(response) == 200) {
result <- content(response, as = "parsed")
- return(list(
- success = TRUE,
- text = result$message$content,
- model_used = model
- ))
+ if (is.list(result) && !is.null(result$generated_text)) {
+ return(list(success = TRUE, text = result$generated_text))
+ } else if (is.list(result) && length(result) > 0 && !is.null(result[[1]]$generated_text)) {
+ return(list(success = TRUE, text = result[[1]]$generated_text))
+ } else {
+ return(list(success = FALSE, error = "Unexpected API response format"))
+ }
} else {
- return(list(success = FALSE, error = paste("Ollama returned status:", status_code(response))))
+ return(list(success = FALSE, error = paste("API 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)
+# Function to query local transformer model (if resources allow)
+# This will work if the model can fit in Spaces memory
+setup_local_model <- function() {
+ tryCatch({
+ # Import transformers via reticulate
+ transformers <- import("transformers")
+ torch <- import("torch")
+
+ # Load a small model suitable for CPU
+ model_name <- "microsoft/phi-2"
+
+ tokenizer <- transformers$AutoTokenizer$from_pretrained(model_name)
+ model <- transformers$AutoModelForCausalLM$from_pretrained(
+ model_name,
+ torch_dtype = "auto",
+ device_map = "auto",
+ low_cpu_mem_usage = TRUE
+ )
+
+ return(list(
+ success = TRUE,
+ tokenizer = tokenizer,
+ model = model
+ ))
+ }, error = function(e) {
+ return(list(success = FALSE, error = e$message))
})
- 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")
+query_local_model <- function(prompt, model_objects, max_length = 500) {
+ tryCatch({
+ tokenizer <- model_objects$tokenizer
+ model <- model_objects$model
+
+ inputs <- tokenizer$encode(prompt, return_tensors = "pt")
+
+ with(torch$no_grad(), {
+ outputs <- model$generate(
+ inputs,
+ max_length = max_length,
+ temperature = 0.7,
+ do_sample = TRUE,
+ pad_token_id = tokenizer$eos_token_id
+ )
+ })
+
+ response <- tokenizer$decode(outputs[1], skip_special_tokens = TRUE)
+
+ # Remove the prompt from response
+ if (startsWith(response, prompt)) {
+ response <- substring(response, nchar(prompt) + 1)
}
- }
- 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
+
+ return(list(success = TRUE, text = trimws(response)))
+ }, error = function(e) {
+ return(list(success = FALSE, error = e$message))
+ })
}
-# 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?"
- ))
- }
+# ============================================================
+# SYSTEM PROMPT CONSTRUCTION
+# ============================================================
- # ---- 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."
- ))
- }
+build_system_prompt <- function(rv) {
+ # Build context from current analysis results
+ context_parts <- c(
+ "You are a specialized bioinformatics assistant for QTL (Quantitative Trait Loci) mapping and domestication analysis. You help researchers understand their genomic analysis results.",
+ "\nCURRENT ANALYSIS RESULTS:"
+ )
- # ---- 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."
+ # Add QTL results
+ 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,]
+ context_parts <- c(context_parts, sprintf(
+ "\n- QTL Results: %d significant QTLs detected. Top QTL: %s (Chr %s, Pos %s) with LOD=%.2f, PVE=%.1f%%, Additive Effect=%.3f",
+ n_qtl, top_qtl$Marker, top_qtl$Chromosome, top_qtl$Position,
+ top_qtl$LOD, top_qtl$PVE_Percent, top_qtl$Additive_Effect
))
}
- # ---- 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.")
+ # Add performance metrics
+ if (!is.null(rv$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 ""
+ train_r2 <- round(pm$Value[pm$Metric == "R² (Train)"], 3)
+ val_r2 <- round(pm$Value[pm$Metric == "R² (Validation)"], 3)
+ context_parts <- c(context_parts, sprintf(
+ "\n- Model Performance: Training R²=%.3f, Validation R²=%.3f",
+ train_r2, val_r2
))
}
- # ---- 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).")
+ # Add epistasis results
+ if (!is.null(rv$epistasis_sig) && !"Message" %in% colnames(rv$epistasis_sig)) {
+ n_epi <- nrow(rv$epistasis_sig)
+ context_parts <- c(context_parts, sprintf(
+ "\n- Epistasis: %d significant pairwise interactions detected",
+ n_epi
+ ))
}
- # ---- 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?'"
+ # Add domestication results
+ if (!is.null(rv$selection_metrics) && !"Message" %in% colnames(rv$selection_metrics)) {
+ n_sel <- sum(rv$selection_metrics$Significant, na.rm = TRUE)
+ context_parts <- c(context_parts, sprintf(
+ "\n- Domestication: %d markers with significant selection signatures",
+ n_sel
))
}
- 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'.")
+ context_parts <- c(context_parts,
+ "\n\nAnswer questions clearly and concisely. When referring to specific results, use the data provided above. If asked about methodology, explain it in accessible terms. Always relate your answers back to what the analysis results mean biologically.",
+ "\nKeep responses focused on QTL analysis, genetics, and domestication. If you're not sure about something, admit it and suggest what the user could check."
+ )
+
+ paste(context_parts, collapse = "")
}
# ============================================================
@@ -644,10 +200,13 @@ rule_based_response <- function(user_message, rag_context, rv, chat_messages = l
# ============================================================
ui <- fluidPage(
+ # Use shinyjs for enhanced UI interactions
+ shinyjs::useShinyjs(),
+
tags$head(
- tags$link(rel = "stylesheet", type = "text/css",
+ 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",
+ 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() {
@@ -813,28 +372,21 @@ ui <- fluidPage(
.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
- ============================================================ */
-
+ /* Chatbot Styles */
#chat-panel {
position: fixed;
bottom: 20px;
right: 20px;
z-index: 9999;
- width: 380px;
+ width: 400px;
display: flex;
flex-direction: column;
- font-family: var(--font-sans);
}
#chat-toggle-btn {
align-self: flex-end;
- width: 52px;
- height: 52px;
+ width: 56px;
+ height: 56px;
border-radius: 50%;
background: linear-gradient(135deg, var(--accent), var(--purple));
border: none;
@@ -845,7 +397,7 @@ ui <- fluidPage(
box-shadow: 0 4px 20px rgba(88, 166, 255, 0.4);
transition: all 0.2s;
color: #0d1117;
- font-size: 20px;
+ font-size: 24px;
}
#chat-toggle-btn:hover { transform: scale(1.05); box-shadow: 0 6px 24px rgba(88, 166, 255, 0.6); }
@@ -854,11 +406,12 @@ ui <- fluidPage(
flex-direction: column;
background: var(--bg-secondary);
border: 1px solid var(--border);
- border-radius: 10px;
+ border-radius: 12px;
overflow: hidden;
box-shadow: 0 8px 40px rgba(0,0,0,0.5);
margin-bottom: 10px;
- height: 520px;
+ height: 600px;
+ border: 1px solid var(--accent);
}
#chat-window.open { display: flex; }
@@ -870,27 +423,17 @@ ui <- fluidPage(
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;
+ .chat-title { display: flex; align-items: center; gap: 10px; }
+ .chat-avatar {
+ width: 32px; height: 32px;
background: linear-gradient(135deg, var(--accent), var(--purple));
border-radius: 50%;
display: flex; align-items: center; justify-content: center;
- font-size: 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;
+ font-size: 16px; color: #0d1117; font-weight: bold;
}
- #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-header h4 { font-family: var(--font-mono); font-size: 13px; font-weight: 600; color: var(--text-primary); margin: 0; }
+ #chat-header p { font-size: 11px; color: var(--text-muted); margin: 0; }
+ #chat-close-btn { background: none; border: none; color: var(--text-muted); cursor: pointer; font-size: 18px; padding: 4px; transition: color 0.15s; }
#chat-close-btn:hover { color: var(--text-primary); }
#chat_messages {
@@ -900,58 +443,53 @@ ui <- fluidPage(
display: flex;
flex-direction: column;
gap: 12px;
- scrollbar-width: thin;
- scrollbar-color: var(--border) transparent;
+ background: var(--bg-primary);
}
.chat-msg {
- max-width: 88%;
- animation: fadeInUp 0.2s ease;
+ max-width: 85%;
+ animation: fadeIn 0.3s ease;
}
- @keyframes fadeInUp {
- from { opacity: 0; transform: translateY(8px); }
+ @keyframes fadeIn {
+ from { opacity: 0; transform: translateY(10px); }
to { opacity: 1; transform: translateY(0); }
}
.chat-msg.user { align-self: flex-end; }
.chat-msg.assistant { align-self: flex-start; }
.chat-bubble {
- padding: 10px 14px;
- border-radius: 14px;
+ padding: 12px 16px;
+ border-radius: 16px;
font-size: 13px;
line-height: 1.5;
word-wrap: break-word;
+ white-space: pre-wrap;
}
.chat-msg.user .chat-bubble {
background: linear-gradient(135deg, var(--accent), #3a7bd5);
color: #0d1117;
border-bottom-right-radius: 4px;
- 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 {
+ .typing-indicator {
display: flex;
gap: 4px;
- align-items: center;
- padding: 10px 14px;
+ padding: 12px 16px;
background: var(--bg-tertiary);
border: 1px solid var(--border);
- border-radius: 14px;
+ border-radius: 16px;
border-bottom-left-radius: 4px;
width: fit-content;
}
.typing-dot {
- width: 6px; height: 6px;
+ width: 8px; height: 8px;
background: var(--text-muted);
border-radius: 50%;
animation: typingBounce 1.4s infinite;
@@ -960,51 +498,53 @@ ui <- fluidPage(
.typing-dot:nth-child(3) { animation-delay: 0.4s; }
@keyframes typingBounce {
0%, 60%, 100% { transform: translateY(0); }
- 30% { transform: translateY(-6px); }
+ 30% { transform: translateY(-8px); }
}
#chat-footer {
- padding: 12px;
+ padding: 16px;
border-top: 1px solid var(--border);
background: var(--bg-tertiary);
- display: flex;
- flex-direction: column;
- gap: 8px;
}
#chat_input {
+ width: 100%;
background: var(--bg-secondary) !important;
border: 1px solid var(--border) !important;
- border-radius: 6px;
+ border-radius: 8px;
color: var(--text-primary) !important;
font-size: 13px;
resize: none;
padding: 10px 12px;
font-family: var(--font-sans);
- transition: border-color 0.15s;
+ margin-bottom: 8px;
}
- #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_input:focus { border-color: var(--accent) !important; outline: none; }
- .chat-actions { display: flex; gap: 8px; align-items: center; justify-content: space-between; }
+ .chat-actions {
+ display: flex;
+ gap: 8px;
+ }
#send_chat {
+ flex: 1;
background: linear-gradient(135deg, var(--accent), #3a7bd5);
color: #0d1117;
border: none;
border-radius: 6px;
padding: 8px 16px;
font-family: var(--font-mono);
- font-size: 11px;
+ font-size: 12px;
font-weight: 600;
cursor: pointer;
transition: all 0.15s;
display: flex;
align-items: center;
+ justify-content: 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; }
+ #send_chat:hover:not(:disabled) { transform: translateY(-1px); box-shadow: 0 4px 12px rgba(88, 166, 255, 0.4); }
+ #send_chat:disabled { opacity: 0.5; cursor: not-allowed; }
#clear_chat {
background: transparent;
@@ -1013,73 +553,59 @@ ui <- fluidPage(
border-radius: 6px;
padding: 8px 12px;
font-family: var(--font-mono);
- font-size: 11px;
+ font-size: 12px;
cursor: pointer;
transition: all 0.15s;
}
#clear_chat:hover { border-color: var(--danger); color: var(--danger); }
- #ollama_status {
- font-family: var(--font-mono);
+ .model-badge {
+ display: inline-block;
+ background: var(--bg-secondary);
+ border: 1px solid var(--border);
+ border-radius: 12px;
+ padding: 2px 8px;
font-size: 10px;
color: var(--text-muted);
- display: flex;
- align-items: center;
- gap: 6px;
+ margin-left: 8px;
}
- .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 {
+ padding: 8px 16px;
display: flex;
flex-wrap: wrap;
gap: 6px;
- padding: 0 16px 12px;
+ border-bottom: 1px solid var(--border);
}
.quick-q-btn {
background: var(--bg-tertiary);
border: 1px solid var(--border);
color: var(--text-secondary);
- border-radius: 12px;
- padding: 4px 10px;
+ border-radius: 16px;
+ padding: 4px 12px;
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); }
+ .quick-q-btn:hover { border-color: var(--accent); color: var(--accent); background: rgba(88, 166, 255, 0.1); }
"))
),
+ # Navigation bar
navbarPage(
- title = tags$span(tags$i(class="fas fa-dna", style="margin-right:8px; color:#58a6ff;"), "QTL-Mapper"),
+ title = tags$span(tags$i(class = "fas fa-dna", style = "margin-right:8px; color:#58a6ff;"), "QTL-Mapper AI"),
id = "nav",
- # ---- DATA UPLOAD TAB ----
+ # 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")
+ h2(tags$i(class = "fas fa-upload", style = "margin-right:8px;"), "Data Upload"),
+ p("Upload genotype, phenotype, and population data for comprehensive QTL analysis with AI assistance")
),
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-header", tags$i(class = "fas fa-table", style = "margin-right:6px;"), "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."),
@@ -1091,19 +617,18 @@ ui <- fluidPage(
),
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-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.")
+ actionButton("predict_test_phenotype", "Predict Test Phenotypes", class = "btn-info btn-block", icon = icon("magic"))
)
)
),
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-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),
@@ -1129,10 +654,10 @@ ui <- fluidPage(
)
),
- # ---- DOMESTICATION TAB ----
+ # Domestication Tab
tabPanel("Domestication", icon = icon("leaf"),
div(class = "main-header",
- h2(tags$i(class="fas fa-leaf", style="margin-right:8px;"), "Domestication Analysis"),
+ 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(
@@ -1170,21 +695,13 @@ ui <- fluidPage(
)
)
)
- ),
- fluidRow(
- column(12,
- div(class = "card",
- div(class = "card-header", "Selection Interpretation"),
- div(class = "card-body", uiOutput("selection_interpretation"))
- )
- )
)
),
- # ---- RESULTS TAB ----
+ # 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"),
+ 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(
@@ -1211,68 +728,64 @@ ui <- fluidPage(
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")
+ plotlyOutput("epistasis_heatmap", height = "400px")
)
))
)
),
- # ---- INTERPRETATION TAB ----
+ # Interpretation Tab
tabPanel("Interpretation", icon = icon("lightbulb"),
div(class = "main-header",
- h2(tags$i(class="fas fa-lightbulb", style="margin-right:8px;"), "Results Interpretation"),
+ 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(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")))))
+ 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 ----
+ # 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")
+ h2(tags$i(class = "fas fa-info-circle", style = "margin-right:8px;"), "About QTL-Mapper AI"),
+ p("QTL Mapping with Transformer-based AI Assistant")
),
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;",
+ 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)")
+ tags$li("AI Assistant powered by ", tags$code("microsoft/phi-2"), " transformer model via Hugging Face Inference API")
),
- 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;", "AI Assistant Features"),
+ p(style = "color: #8b949e; line-height: 1.7;",
+ "The AI assistant uses a transformer-based language model to provide intelligent, context-aware responses about your QTL analysis results. ",
+ "It understands questions about LOD scores, QTL effects, epistasis, domestication signatures, and can provide tailored recommendations based on your specific results."
),
- h4(style="color:#58a6ff; font-family: 'IBM Plex Mono'; margin: 12px 0;", "Interpretation Thresholds"),
- tags$ul(style="color: #8b949e; line-height: 2;",
+ 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"),
@@ -1285,22 +798,18 @@ ui <- fluidPage(
)
),
- # ============================================================
- # FLOATING CHATBOT PANEL
- # ============================================================
+ # 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(class = "chat-avatar", "AI"),
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$h4("QTL Analysis AI Assistant",
+ tags$span(class = "model-badge", "phi-2")
+ ),
+ tags$p(id = "model_status", "Transformer model ready")
)
),
tags$button(id = "chat-close-btn", onclick = "document.getElementById('chat-window').classList.remove('open');",
@@ -1308,14 +817,14 @@ ui <- fluidPage(
)
),
- # Quick question chips
+ # Quick questions
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")
+ tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q', 'How is my model performing?', {priority: 'event'});", "Model performance"),
+ tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q', 'Explain epistasis results', {priority: 'event'});", "Epistasis"),
+ tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q', 'What does Fst mean?', {priority: 'event'});", "Fst meaning"),
+ tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q', 'Any selection signatures?', {priority: 'event'});", "Selection"),
+ tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q', 'Next steps?', {priority: 'event'});", "Next steps")
),
# Messages
@@ -1326,18 +835,13 @@ ui <- fluidPage(
# Footer
tags$div(id = "chat-footer",
tags$textarea(
- id = "chat_input",
+ id = "chat_input",
placeholder = "Ask about your QTL results... (Enter to send)",
- rows = "2",
- style = "width:100%;"
+ rows = "2"
),
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"
- )
+ actionButton("send_chat", "Send", icon = icon("paper-plane"), class = "btn-primary"),
+ actionButton("clear_chat", "Clear", icon = icon("trash-alt"), class = "btn-danger")
)
)
),
@@ -1356,781 +860,1630 @@ ui <- fluidPage(
server <- function(input, output, session) {
+ # Reactive values for data storage
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,
+ 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,
+ 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
+ # Model objects
+ hf_model_loaded = FALSE,
+ local_model = NULL,
+ using_api = use_hf_api
)
- # 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 ----
+ # Initialize model status
+ observe({
+ if (values$using_api) {
+ if (HF_API_TOKEN != "") {
+ values$hf_model_loaded <- TRUE
+ shinyjs::html("model_status", "Hugging Face API connected")
+ } else {
+ values$using_api <- FALSE
+ shinyjs::html("model_status", "Using rule-based fallback (set HF_API_TOKEN for AI)")
+ }
+ } else {
+ # Try to load local model (will likely fail in Spaces due to memory)
+ # This is optional and commented out for Spaces deployment
+ # model_objects <- setup_local_model()
+ # if (model_objects$success) {
+ # values$local_model <- model_objects
+ # values$hf_model_loaded <- TRUE
+ # shinyjs::html("model_status", "Local transformer model loaded")
+ # } else {
+ # shinyjs::html("model_status", "Using rule-based responses")
+ # }
+ shinyjs::html("model_status", "Using enhanced rule-based AI")
+ }
+ })
- 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)))
- }
+ # ============================================================
+ # ENHANCED RULE-BASED RESPONSES (Fallback when transformer not available)
+ # ============================================================
- process_chat <- function(user_text) {
- if (nchar(trimws(user_text)) == 0) return()
+ enhanced_rule_response <- function(user_message, rv) {
+ q <- tolower(trimws(user_message))
- # Add user message
- add_message("user", user_text)
+ # Check for results availability
+ has_qtl <- !is.null(rv$qtl_effects_train) && !"Message" %in% colnames(rv$qtl_effects_train)
+ has_perf <- !is.null(rv$performance_metrics)
+ has_epi <- !is.null(rv$epistasis_sig) && !"Message" %in% colnames(rv$epistasis_sig)
+ has_sel <- !is.null(rv$selection_metrics) && !"Message" %in% colnames(rv$selection_metrics)
- # 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")
+ # Comprehensive response patterns
+ responses <- list()
- # 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)
+ # QTL-related queries
+ if (grepl("qtl|quantitative trait|marker", q)) {
+ if (has_qtl) {
+ df <- rv$qtl_effects_train
+ top <- df[which.max(df$LOD), ]
+ responses <- c(responses, paste(
+ "Based on your QTL analysis:",
+ paste0("- You have ", nrow(df), " significant QTLs above LOD ", input$lod_threshold),
+ paste0("- Top QTL: ", top$Marker, " on chromosome ", top$Chromosome),
+ paste0(" • LOD score: ", round(top$LOD, 2)),
+ paste0(" • PVE: ", round(top$PVE_Percent, 1), "%"),
+ paste0(" • Additive effect: ", round(top$Additive_Effect, 3)),
+ "",
+ "This QTL explains the most variance in your trait. The flanking markers ",
+ top$Low_Flank, " and ", top$High_Flank, " define the confidence interval.",
+ sep = "\n"
+ ))
} else {
- # Ollama failed, use rule-based
- resp_text <- rule_based_response(user_text, full_context, values, values$chat_messages)
- add_message("assistant", resp_text)
+ responses <- c(responses, "No QTL results yet. Please upload your data and run the analysis first.")
}
- } 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()
+ # Performance queries
+ if (grepl("performance|model|r2|accuracy|predict", q)) {
+ if (has_perf) {
+ pm <- rv$performance_metrics
+ train_r2 <- pm$Value[pm$Metric == "R² (Train)"]
+ val_r2 <- pm$Value[pm$Metric == "R² (Validation)"]
+ train_r <- pm$Value[pm$Metric == "R (Train)"]
+ val_r <- pm$Value[pm$Metric == "R (Validation)"]
+
+ quality <- if (val_r2 > 0.7) "excellent"
+ else if (val_r2 > 0.5) "good"
+ else if (val_r2 > 0.3) "moderate"
+ else "modest"
+
+ responses <- c(responses, paste(
+ "Model Performance Summary:",
+ paste0("- Training R²: ", round(train_r2, 3), " (", round(train_r2*100, 1), "% variance explained)"),
+ paste0("- Validation R²: ", round(val_r2, 3), " (", round(val_r2*100, 1), "% variance explained)"),
+ paste0("- Training R: ", round(train_r, 3)),
+ paste0("- Validation R: ", round(val_r, 3)),
+ "",
+ paste0("Overall predictive power is ", quality, "."),
+ if (train_r2 - val_r2 > 0.2) "⚠️ There may be some overfitting - consider simplifying the model or increasing sample size." else "✅ The model generalizes well to validation data.",
+ sep = "\n"
+ ))
+ } else {
+ responses <- c(responses, "Run the QTL analysis first to see model performance metrics.")
+ }
+ }
- 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
+ # Domestication queries
+ if (grepl("domestication|selection|fst|tajima|wild|domesticated", q)) {
+ if (has_sel) {
+ sel <- rv$selection_metrics
+ n_sig <- sum(sel$Significant, na.rm = TRUE)
+ top_fst <- sel[which.max(sel$Fst), ]
+
+ responses <- c(responses, paste(
+ "Domestication Analysis Results:",
+ paste0("- ", n_sig, " markers show significant selection signatures"),
+ paste0("- Strongest differentiation: ", top_fst$Marker, " (Fst = ", round(top_fst$Fst, 3), ")"),
+ paste0(" • Pi (Domesticated): ", round(top_fst$Pi_Dom, 4)),
+ paste0(" • Pi (Wild): ", round(top_fst$Pi_Wild, 4)),
+ paste0(" • Tajima's D (Dom): ", round(top_fst$Tajima_D_Dom, 3)),
+ "",
+ if (has_qtl) {
+ overlap <- sel$Marker[sel$Marker %in% rv$qtl_effects_train$Marker & sel$Significant]
+ if (length(overlap) > 0) {
+ paste("🔬 QTLs under selection:", paste(overlap, collapse = ", "),
+ "- these are strong domestication candidates!")
+ } else {
+ "No overlap between QTLs and selection signatures detected."
+ }
+ } else {
+ "Run QTL analysis to check if these selection signatures overlap with trait-associated loci."
+ },
+ sep = "\n"
+ ))
+ } else {
+ responses <- c(responses, "No domestication results yet. Upload population data and run the analysis.")
+ }
+ }
+
+ # Epistasis queries
+ if (grepl("epistasis|interaction|epistatic", q)) {
+ if (has_epi) {
+ epi <- rv$epistasis_sig
+ top_epi <- epi[which.min(epi$Interaction_p), ]
+
+ responses <- c(responses, paste(
+ "Epistasis Analysis:",
+ paste0("- Found ", nrow(epi), " significant pairwise interactions (p < 0.05)"),
+ paste0("- Strongest interaction: ", top_epi$QTL1, " × ", top_epi$QTL2),
+ paste0(" • p-value: ", format.pval(top_epi$Interaction_p)),
+ paste0(" • Effect size: ", round(top_epi$Effect_Size, 3)),
+ "",
+ "This suggests the effect of one QTL depends on the genotype at the other locus.",
+ "Consider these interactions in breeding programs or functional studies.",
+ sep = "\n"
+ ))
+ } else {
+ responses <- c(responses, "No significant epistatic interactions detected in your analysis.")
+ }
+ }
+
+ # Return appropriate response or default
+ if (length(responses) > 0) {
+ return(paste(responses[[1]], collapse = "\n"))
+ } else {
+ # Default response with available information
+ available <- c()
+ if (has_qtl) available <- c(available, paste(nrow(rv$qtl_effects_train), "QTLs"))
+ if (has_perf) available <- c(available, "performance metrics")
+ if (has_epi) available <- c(available, paste(nrow(rv$epistasis_sig), "epistatic interactions"))
+ if (has_sel) available <- c(available, paste(sum(rv$selection_metrics$Significant), "selection signatures"))
+
+ if (length(available) > 0) {
+ return(paste0(
+ "I can see you have: ", paste(available, collapse = ", "), ".\n\n",
+ "What would you like to know? Try asking about:\n",
+ "- Top QTLs and their effects\n",
+ "- Model performance and reliability\n",
+ "- Domestication signatures and selection\n",
+ "- Epistatic interactions\n",
+ "- Next steps for your analysis"
+ ))
+ } else {
+ return(paste0(
+ "Hello! I'm your QTL analysis assistant. I can help you with:\n\n",
+ "• Uploading and analyzing your data\n",
+ "• Understanding LOD scores and QTL effects\n",
+ "• Interpreting model performance\n",
+ "• Detecting selection signatures (Fst, Tajima's D)\n",
+ "• Identifying epistatic interactions\n\n",
+ "To get started, upload your genotype and phenotype files and click 'Run QTL Analysis'."
+ ))
+ }
+ }
+ }
+
+ # ============================================================
+ # AI RESPONSE GENERATION
+ # ============================================================
+
+ generate_ai_response <- function(user_message) {
+ # Build context
+ context <- build_system_prompt(values)
+
+ # Construct prompt
+ prompt <- paste(
+ context,
+ "\n\nUser Question: ", user_message,
+ "\n\nProvide a helpful, concise response based on the analysis results above. Focus on biological interpretation and practical recommendations.",
+ sep = ""
+ )
+
+ # Try transformer if available
+ if (values$using_api && values$hf_model_loaded) {
+ result <- query_hf_api(prompt)
+ if (result$success) {
+ return(result$text)
+ }
+ }
+
+ # Fallback to enhanced rule-based
+ return(enhanced_rule_response(user_message, values))
+ }
+
+ # ============================================================
+ # CHAT FUNCTIONS
+ # ============================================================
+
+ # Add message to chat history
+ add_message <- function(role, content) {
+ timestamp <- format(Sys.time(), "%H:%M")
+ values$chat_messages <- c(values$chat_messages, list(list(
+ role = role,
+ content = content,
+ time = timestamp
+ )))
+
+ # Keep only last 50 messages
+ if (length(values$chat_messages) > 50) {
+ values$chat_messages <- tail(values$chat_messages, 50)
+ }
+
+ # Scroll to bottom
+ session$sendCustomMessage("scrollChatBottom", list())
+ }
+
+ # Process user message
+ process_message <- function(user_text) {
+ if (nchar(trimws(user_text)) == 0) return()
+
+ # Add user message
+ add_message("user", user_text)
+
+ # Show typing indicator
+ values$is_typing <- TRUE
+
+ # Generate response
+ response <- generate_ai_response(user_text)
+
+ # Hide typing indicator
+ values$is_typing <- FALSE
+
+ # Add assistant response
+ add_message("assistant", response)
+ }
+
+ # Send message handler
+ observeEvent(input$send_chat, {
+ req(input$chat_input)
+ user_text <- trimws(input$chat_input)
+ if (nchar(user_text) == 0) return()
+
+ # Clear input
+ updateTextAreaInput(session, "chat_input", value = "")
+
+ # Process message
+ process_message(user_text)
+ })
+
+ # Quick question handler
+ observeEvent(input$quick_q, {
+ req(input$quick_q)
+ process_message(input$quick_q)
+ })
+
+ # Clear chat handler
observeEvent(input$clear_chat, {
values$chat_messages <- list()
- values$chat_history <- list()
+ add_message("assistant", "Chat cleared. How can I help you with your QTL analysis?")
})
- # Initialize with welcome message
+ # Initialize chat
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."
+ add_message("assistant", paste(
+ "👋 Hello! I'm your AI-powered QTL analysis assistant.",
+ "",
+ "I can help you interpret your results and answer questions about:",
+ "• QTL detection and LOD scores",
+ "• Model performance (R², predictions)",
+ "• Epistatic interactions",
+ "• Domestication signatures (Fst, Tajima's D)",
+ "• Next steps and recommendations",
+ "",
+ "Upload your data, run the analysis, and ask me anything!",
+ sep = "\n"
))
}
})
# 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)
+ messages <- values$chat_messages
+
+ if (length(messages) == 0) return(NULL)
+
+ message_elements <- lapply(messages, function(msg) {
+ div(class = paste("chat-msg", msg$role),
+ div(class = "chat-bubble",
+ HTML(gsub("\n", "
", htmltools::htmlEscape(msg$content)))
+ ),
+ div(class = "chat-meta", msg$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
+ })
+
+ # Add typing indicator if needed
+ if (values$is_typing) {
+ message_elements <- c(message_elements, list(
+ div(class = "chat-msg assistant",
+ div(class = "typing-indicator",
+ div(class = "typing-dot"),
+ div(class = "typing-dot"),
+ div(class = "typing-dot")
+ )
)
- }
- }
- 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)
- }))
- }
+
+ do.call(tagList, message_elements)
+ })
- # ---- DATA LOADING ----
+ # ============================================================
+ # DATA LOADING FUNCTIONS
+ # ============================================================
+ # Load genotype data
observeEvent(input$genotype_file, {
req(input$genotype_file)
tryCatch({
- values$genotype_preview_data <- read.csv(input$genotype_file$datapath)
+ # Read file
all_data <- readLines(input$genotype_file$datapath)
- if (length(all_data) < 4) { showNotification("Genotype file must have at least four rows.", type = "error"); return() }
+ if (length(all_data) < 4) {
+ showNotification("Genotype file must have at least 4 rows (header, chromosome, position, and data)", type = "error")
+ return()
+ }
+
+ # Parse header
header <- strsplit(all_data[1], ",")[[1]]
chromosome_row <- strsplit(all_data[2], ",")[[1]]
position_row <- strsplit(all_data[3], ",")[[1]]
+
+ # Read data
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)
+
+ # Convert to numeric
+ for (col in colnames(genotype_data)) {
+ genotype_data[[col]] <- as.numeric(as.character(genotype_data[[col]]))
+ }
+
+ # Store marker information
+ values$all_markers <- data.frame(
+ Marker = colnames(genotype_data),
+ Chromosome = chromosome_row[-1],
+ Position = as.numeric(position_row[-1]),
+ 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") })
+ values$position_info <- as.numeric(position_row[-1])
+
+ showNotification("Genotype data loaded successfully", type = "message")
+
+ # Add to chat
+ add_message("assistant", paste0(
+ "✅ Loaded genotype data with ", ncol(genotype_data), " markers and ",
+ nrow(genotype_data), " samples."
+ ))
+
+ }, error = function(e) {
+ showNotification(paste("Error loading genotype file:", e$message), type = "error")
+ })
})
+ # Load phenotype data
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)
+
+ # Set row names
rownames(phenotype_data) <- phenotype_data[, 1]
phenotype_data <- phenotype_data[, -1]
+
+ # Convert to numeric
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") })
+
+ # Update phenotype selector
+ updateSelectInput(session, "phenotype_column",
+ choices = colnames(phenotype_data),
+ selected = colnames(phenotype_data)[1])
+
+ showNotification("Phenotype data loaded successfully", type = "message")
+
+ # Add to chat
+ add_message("assistant", paste0(
+ "✅ Loaded phenotype data with ", ncol(phenotype_data),
+ " traits and ", nrow(phenotype_data), " samples."
+ ))
+
+ }, error = function(e) {
+ showNotification(paste("Error loading phenotype file:", e$message), type = "error")
+ })
})
+ # Load population data
+ observeEvent(input$pop_file, {
+ req(input$pop_file)
+ tryCatch({
+ pop_data <- read.csv(input$pop_file$datapath)
+
+ # Validate columns
+ if (!all(c("id", "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 successfully", type = "message")
+
+ # Add to chat
+ add_message("assistant", paste0(
+ "✅ Loaded population data with ", nrow(pop_data), " samples.\n",
+ "Populations: ", paste(unique(pop_data$population), collapse = ", ")
+ ))
+
+ }, error = function(e) {
+ showNotification(paste("Error loading population file:", e$message), type = "error")
+ })
+ })
+
+ # Load test genotype data
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))
+
+ for (col in colnames(genotype_data)) {
+ genotype_data[[col]] <- as.numeric(as.character(genotype_data[[col]]))
}
+
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") })
+
+ showNotification("Test genotype data loaded successfully", type = "message")
+
+ }, error = function(e) {
+ showNotification(paste("Error loading test genotype file:", 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(input$genotype_file)
+ datatable(head(read.csv(input$genotype_file$datapath), 10),
+ options = list(scrollX = TRUE, pageLength = 5))
})
- # ---- 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)) })
+ output$pheno_preview <- renderDT({
+ req(input$phenotype_file)
+ datatable(head(read.csv(input$phenotype_file$datapath), 10),
+ options = list(scrollX = TRUE, pageLength = 5))
+ })
- # ---- 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") })
+ output$test_geno_preview <- renderDT({
+ req(input$test_genotype_file)
+ datatable(head(read.csv(input$test_genotype_file$datapath), 10),
+ options = list(scrollX = TRUE, pageLength = 5))
+ })
+
+ output$pop_preview <- renderDT({
+ req(input$pop_file)
+ datatable(head(read.csv(input$pop_file$datapath), 10),
+ options = list(scrollX = TRUE, pageLength = 5))
+ })
+
+ output$predicted_test_pheno_preview <- renderDT({
+ req(values$predicted_test_phenotype_data)
+ datatable(values$predicted_test_phenotype_data,
+ options = list(scrollX = TRUE, pageLength = 5))
})
- # ---- RUN QTL ANALYSIS ----
+ # ============================================================
+ # QTL ANALYSIS
+ # ============================================================
+
+ # Function to calculate QTL effects
+ calculate_qtl_effects <- function(genotype_matrix, phenotype_vector, marker_names) {
+ effects_list <- list()
+
+ for (marker in marker_names) {
+ if (!marker %in% colnames(genotype_matrix)) next
+
+ # Get genotype and phenotype for this marker
+ geno <- genotype_matrix[, marker]
+ pheno <- phenotype_vector
+
+ # Remove missing values
+ valid_idx <- !is.na(geno) & !is.na(pheno)
+ geno <- geno[valid_idx]
+ pheno <- pheno[valid_idx]
+
+ if (length(unique(geno)) < 2) next
+
+ # Fit linear model
+ lm_fit <- lm(pheno ~ geno)
+
+ # Calculate additive effect
+ additive_effect <- coef(lm_fit)[2]
+
+ # Calculate dominance effect if possible
+ dominance_effect <- NA
+ if (length(unique(geno)) == 3) {
+ geno_means <- tapply(pheno, geno, mean, na.rm = TRUE)
+ het_mean <- geno_means[as.character(sort(unique(geno))[2])]
+ midparent <- (geno_means[as.character(sort(unique(geno))[1])] +
+ geno_means[as.character(sort(unique(geno))[3])]) / 2
+ dominance_effect <- het_mean - midparent
+ }
+
+ # Calculate PVE
+ r_squared <- summary(lm_fit)$r.squared
+
+ # Standard error and CI
+ se_additive <- summary(lm_fit)$coefficients[2, 2]
+
+ effects_list[[marker]] <- data.frame(
+ 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),
+ stringsAsFactors = FALSE
+ )
+ }
+
+ if (length(effects_list) == 0) return(NULL)
+ do.call(rbind, effects_list)
+ }
+
+ # Main analysis
observeEvent(input$run_analysis, {
req(values$genotype_data, values$phenotype_data, input$phenotype_column)
- showNotification("Running QTL analysis...", type = "message")
+
+ showNotification("Starting 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() }
+ # Get common samples
+ common_samples <- intersect(rownames(values$genotype_data),
+ rownames(values$phenotype_data))
- 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
+ if (length(common_samples) == 0) {
+ showNotification("No common samples between genotype and phenotype data", type = "error")
+ return()
+ }
+
+ # Prepare data
+ X <- values$genotype_data[common_samples, , drop = FALSE]
+ y <- as.numeric(values$phenotype_data[common_samples, input$phenotype_column])
- nzv <- nearZeroVar(X_train)
- if (length(nzv) > 0) X_train <- X_train[, -nzv, drop = FALSE]
+ # Remove near-zero variance predictors
+ nzv <- nearZeroVar(X)
+ if (length(nzv) > 0) {
+ X <- X[, -nzv, drop = FALSE]
+ }
+ # Split data
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]
+ train_index <- createDataPartition(y, p = 1 - input$test_size, list = FALSE)
+
+ X_train <- X[train_index, , drop = FALSE]
+ X_val <- X[-train_index, , drop = FALSE]
+ y_train <- y[train_index]
+ y_val <- y[-train_index]
+
+ # Train Random Forest model
+ model <- train(
+ x = X_train,
+ y = y_train,
+ method = "rf",
+ trControl = trainControl(method = "cv", number = 5),
+ importance = TRUE,
+ tuneLength = 3
+ )
- model <- train(x = X_tr, y = y_tr, method = "rf",
- trControl = trainControl(method = "cv", number = 5),
- importance = TRUE, tuneLength = 3)
values$model_fit <- model
+ # Get variable importance
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))]),
+ Marker = rownames(imp),
+ LOD = imp$Overall,
+ Chromosome = values$chromosome_info[match(rownames(imp), colnames(X))],
+ Position = as.numeric(values$position_info[match(rownames(imp), colnames(X))]),
stringsAsFactors = FALSE
)
+
values$importance_scores <- importance_scores
+ # Get significant QTLs
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
+ # Add flanking markers
+ 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]
+
+ if (length(idx) > 0) {
+ 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.")
+ # Calculate QTL effects
+ qtl_fx <- calculate_qtl_effects(X_train, y_train, lod_sig$Marker)
+
+ if (!is.null(qtl_fx)) {
+ values$qtl_effects_train <- merge(lod_sig, qtl_fx, by = "Marker")
+ } else {
+ values$qtl_effects_train <- data.frame(Message = "Could not calculate QTL effects")
+ }
} else {
- values$lod_scores_train <- lod_sig
- values$qtl_effects_train <- data.frame(Message = paste("No significant QTLs above LOD", input$lod_threshold))
+ values$lod_scores_train <- data.frame(Message = paste("No QTLs above LOD", input$lod_threshold))
+ values$qtl_effects_train <- data.frame(Message = paste("No QTLs above LOD", input$lod_threshold))
}
- # Performance
- y_tr_pred <- predict(model, X_tr); y_val_pred <- predict(model, X_val)
+ # Calculate performance metrics
+ y_train_pred <- predict(model, X_train)
+ y_val_pred <- predict(model, X_val)
+
+ train_r2 <- 1 - sum((y_train - y_train_pred)^2) / sum((y_train - mean(y_train))^2)
+ val_r2 <- 1 - sum((y_val - y_val_pred)^2) / sum((y_val - mean(y_val))^2)
+
values$performance_metrics <- data.frame(
Metric = c("R² (Train)", "R (Train)", "R² (Validation)", "R (Validation)"),
Value = c(
- 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),
+ train_r2,
+ cor(y_train, y_train_pred),
+ val_r2,
cor(y_val, y_val_pred)
- ), stringsAsFactors = FALSE
+ ),
+ stringsAsFactors = FALSE
)
- values$train_predictions <- data.frame(Observed = y_tr, Predicted = y_tr_pred)
+
+ values$train_predictions <- data.frame(Observed = y_train, Predicted = y_train_pred)
values$test_predictions <- data.frame(Observed = y_val, Predicted = y_val_pred)
- # Epistasis
- 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
+ # Calculate epistasis if we have QTLs
+ if (nrow(lod_sig) > 0) {
+ sig_markers <- lod_sig$Marker[lod_sig$Marker %in% colnames(X_train)]
+ all_markers <- colnames(X_train)
+
+ epistasis_list <- list()
+
+ withProgress(message = 'Calculating epistasis...', value = 0, {
+ total <- length(sig_markers) * length(all_markers)
+ count <- 0
+
for (m1 in sig_markers) {
- for (m2 in all_m) {
+ for (m2 in all_markers) {
if (m1 == m2) next
- pair_count <- pair_count + 1
- incProgress(1/total_pairs, detail = sprintf("Pair %d/%d", pair_count, total_pairs))
+
+ count <- count + 1
+ incProgress(1/total, detail = paste("Testing", m1, "x", m2))
+
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)
+ data_epi <- data.frame(
+ y = y_train,
+ m1 = X_train[, m1],
+ m2 = X_train[, m2]
+ )
+
+ # Remove missing values
+ data_epi <- na.omit(data_epi)
+
+ if (nrow(data_epi) < 10) next
+
+ # Fit model with interaction
+ fit <- lm(y ~ m1 * m2, data = data_epi)
+ coef_summary <- summary(fit)$coefficients
+
+ if ("m1:m2" %in% rownames(coef_summary)) {
+ p_val <- coef_summary["m1:m2", "Pr(>|t|)"]
+ effect <- coef(fit)["m1:m2"]
+
+ epistasis_list[[length(epistasis_list) + 1]] <- data.frame(
+ QTL1 = m1,
+ QTL2 = m2,
+ Interaction_p = p_val,
+ Effect_Size = effect,
+ stringsAsFactors = FALSE
+ )
}
}, 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.")
+
+ if (length(epistasis_list) > 0) {
+ epistasis_all <- do.call(rbind, epistasis_list)
+ values$epistasis_all <- epistasis_all
+ values$epistasis_sig <- epistasis_all[epistasis_all$Interaction_p < 0.05, ]
+ } else {
+ values$epistasis_all <- data.frame(Message = "No epistatic interactions computed")
+ values$epistasis_sig <- data.frame(Message = "No epistatic interactions computed")
+ }
}
- showNotification("QTL analysis completed!", type = "message")
+ showNotification("QTL analysis completed successfully!", type = "message")
+
+ # Add to chat
+ n_qtl <- if ("Message" %in% colnames(values$qtl_effects_train)) 0 else nrow(values$qtl_effects_train)
+ add_message("assistant", paste(
+ "✅ QTL analysis complete!",
+ paste0("• Found ", n_qtl, " significant QTLs"),
+ paste0("• Model validation R²: ", round(val_r2, 3)),
+ paste0("• Check the Results tab for details"),
+ "",
+ "What would you like to know about your results?",
+ sep = "\n"
+ ))
+
+ # Switch to results tab
updateTabsetPanel(session, "nav", selected = "Results")
- }, error = function(e) { showNotification(paste("Error:", e$message), type = "error") })
+
+ }, error = function(e) {
+ showNotification(paste("Error in analysis:", e$message), type = "error")
+
+ # Add to chat
+ add_message("assistant", paste(
+ "❌ Error during analysis:",
+ e$message,
+ "Please check your data and try again.",
+ sep = "\n"
+ ))
+ })
})
- # ---- RUN DOMESTICATION ANALYSIS ----
+ # ============================================================
+ # DOMESTICATION ANALYSIS
+ # ============================================================
+
+ # Function to calculate selection metrics
+ calculate_selection_metrics <- function(genotype_matrix, pop_data, marker_info) {
+ metrics_list <- list()
+
+ for (marker in colnames(genotype_matrix)) {
+ # Get genotype and population for this marker
+ geno <- genotype_matrix[, marker]
+ pop <- pop_data$population[match(rownames(genotype_matrix), pop_data$id)]
+
+ # Remove missing
+ valid_idx <- !is.na(geno) & !is.na(pop)
+ geno <- geno[valid_idx]
+ pop <- pop[valid_idx]
+
+ if (length(unique(pop)) < 2) next
+
+ # Split by population
+ geno_dom <- geno[pop == "Domesticated"]
+ geno_wild <- geno[pop == "Wild"]
+
+ if (length(geno_dom) < 3 || length(geno_wild) < 3) next
+
+ # Calculate allele frequencies
+ freq_dom <- mean(geno_dom, na.rm = TRUE) / 2
+ freq_wild <- mean(geno_wild, na.rm = TRUE) / 2
+
+ # Calculate Fst
+ p_avg <- (freq_dom + freq_wild) / 2
+ if (p_avg > 0 && p_avg < 1) {
+ fst <- (freq_dom - freq_wild)^2 / (p_avg * (1 - p_avg))
+ fst <- fst / (1 + fst) # Scale to [0,1]
+ } else {
+ fst <- 0
+ }
+
+ # Calculate nucleotide diversity (π)
+ pi_dom <- 2 * freq_dom * (1 - freq_dom)
+ pi_wild <- 2 * freq_wild * (1 - freq_wild)
+
+ # Simple Tajima's D approximation
+ n_dom <- length(geno_dom)
+ n_wild <- length(geno_wild)
+
+ tajima_d_dom <- (pi_dom - 1/n_dom) / sqrt(var(geno_dom)/n_dom)
+ tajima_d_wild <- (pi_wild - 1/n_wild) / sqrt(var(geno_wild)/n_wild)
+
+ # Get chromosome and position
+ marker_row <- marker_info[marker_info$Marker == marker, ]
+
+ metrics_list[[marker]] <- data.frame(
+ Marker = marker,
+ Chromosome = ifelse(nrow(marker_row) > 0, marker_row$Chromosome[1], NA),
+ Position = ifelse(nrow(marker_row) > 0, marker_row$Position[1], NA),
+ Fst = fst,
+ Pi_Dom = pi_dom,
+ Pi_Wild = pi_wild,
+ Tajima_D_Dom = tajima_d_dom,
+ Tajima_D_Wild = tajima_d_wild,
+ stringsAsFactors = FALSE
+ )
+ }
+
+ if (length(metrics_list) == 0) return(NULL)
+ do.call(rbind, metrics_list)
+ }
+
+ # Run domestication analysis
observeEvent(input$run_domestication, {
req(values$genotype_data, values$pop_data, values$all_markers)
+
showNotification("Running domestication analysis...", type = "message")
+
tryCatch({
+ # Get common samples
common_samples <- intersect(rownames(values$genotype_data), values$pop_data$id)
- if (length(common_samples) == 0) { showNotification("No common samples.", type = "error"); return() }
+
+ if (length(common_samples) == 0) {
+ showNotification("No common samples between genotype and population data", type = "error")
+ return()
+ }
+
+ # Subset data
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
+ pop_subset <- values$pop_data[values$pop_data$id %in% common_samples, ]
+
+ # Calculate metrics
+ sel_metrics <- calculate_selection_metrics(X, pop_subset, values$all_markers)
+
+ if (is.null(sel_metrics)) {
+ showNotification("Could not calculate selection metrics", type = "error")
+ return()
+ }
+
+ # Add significance
+ 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") })
+
+ # Add to chat
+ n_sig <- sum(sel_metrics$Significant, na.rm = TRUE)
+ top_fst <- sel_metrics[which.max(sel_metrics$Fst), ]
+
+ add_message("assistant", paste(
+ "✅ Domestication analysis complete!",
+ paste0("• Found ", n_sig, " markers with selection signatures"),
+ paste0("• Highest Fst: ", round(top_fst$Fst, 3), " at ", top_fst$Marker),
+ "",
+ "Check the Domestication tab for detailed results.",
+ sep = "\n"
+ ))
+
+ }, error = function(e) {
+ showNotification(paste("Error in domestication analysis:", 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")
+ # ============================================================
+ # PREDICT TEST PHENOTYPES
+ # ============================================================
+
+ observeEvent(input$predict_test_phenotype, {
+ req(values$model_fit, values$test_genotype_data)
+
+ tryCatch({
+ # Find common markers
+ common_markers <- intersect(colnames(values$test_genotype_data),
+ colnames(values$genotype_data))
+
+ if (length(common_markers) == 0) {
+ showNotification("No common markers between training and test data", type = "error")
+ return()
+ }
+
+ # Prepare test data
+ X_test <- values$test_genotype_data[, common_markers, drop = FALSE]
+
+ # Make predictions
+ 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")
+
+ # Add to chat
+ add_message("assistant", paste(
+ "✅ Predicted phenotypes for", nrow(X_test), "test samples.",
+ "You can download the predictions from the Data Upload tab.",
+ sep = "\n"
+ ))
+
+ }, error = function(e) {
+ showNotification(paste("Error in prediction:", e$message), type = "error")
+ })
+ })
+
+ # ============================================================
+ # PLOTS
+ # ============================================================
+
+ # Helper function for Manhattan plots
+ create_manhattan <- function(data, y_col, title, threshold, y_label = y_col) {
+ if (is.null(data) || nrow(data) == 0 || "Message" %in% colnames(data)) {
+ return(plot_ly() %>% layout(title = "No data available"))
+ }
+
+ # Prepare data
+ plot_data <- data[!is.na(data[[y_col]]), ]
+ if (nrow(plot_data) == 0) return(plot_ly() %>% layout(title = "No valid data"))
+
+ # Create chromosome positions
+ chroms <- unique(plot_data$Chromosome)
+ chrom_pos <- data.frame()
+
+ for (i in seq_along(chroms)) {
+ chr_data <- plot_data[plot_data$Chromosome == chroms[i], ]
+ if (nrow(chr_data) > 0) {
+ chr_data$ChromIndex <- i
+ chr_data$PosScaled <- chr_data$Position / max(chr_data$Position, na.rm = TRUE) + (i - 1)
+ chrom_pos <- rbind(chrom_pos, chr_data)
+ }
+ }
+
+ if (nrow(chrom_pos) == 0) return(plot_ly() %>% layout(title = "No valid data"))
+
+ # Create plot
+ p <- plot_ly() %>%
+ add_trace(
+ data = chrom_pos,
+ x = ~PosScaled,
+ y = as.formula(paste0("~", y_col)),
+ type = 'scatter',
+ mode = 'markers',
+ color = ~factor(Chromosome),
+ colors = viridis(length(chroms)),
+ marker = list(size = 6, opacity = 0.7),
+ text = ~paste("Marker:", Marker,
+ "
Chr:", Chromosome,
+ "
Pos:", Position,
+ "
", y_label, ":", round(get(y_col), 3)),
+ hoverinfo = 'text',
+ showlegend = FALSE
+ )
+
+ # Add threshold line
+ if (!is.null(threshold)) {
+ p <- p %>% add_segments(
+ x = min(chrom_pos$PosScaled, na.rm = TRUE),
+ xend = max(chrom_pos$PosScaled, na.rm = TRUE),
+ y = threshold,
+ yend = threshold,
+ line = list(color = 'red', dash = 'dash', width = 1),
+ name = 'Threshold',
+ showlegend = TRUE
+ )
+ }
+
+ # Layout
+ p %>% layout(
+ title = list(text = title, font = list(size = 14)),
+ xaxis = list(
+ title = "Chromosome",
+ ticktext = chroms,
+ tickvals = tapply(chrom_pos$PosScaled, chrom_pos$Chromosome, median, na.rm = TRUE),
+ tickangle = 45
+ ),
+ yaxis = list(title = y_label),
+ hoverlabel = list(bgcolor = "#21262d"),
+ plot_bgcolor = "#0d1117",
+ paper_bgcolor = "#161b22",
+ font = list(color = "#8b949e")
+ )
}
+ # LOD Manhattan plot
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
+ create_manhattan(values$importance_scores, "LOD", "QTL Manhattan Plot", input$lod_threshold, "LOD Score")
})
+ # Fst Manhattan plot
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)
+ create_manhattan(values$selection_metrics, "Fst", "Fst Manhattan Plot", input$fst_threshold, "Fst")
})
+ # Tajima's D plot
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)
+
+ if (is.null(values$selection_metrics) || "Message" %in% colnames(values$selection_metrics)) {
+ return(plot_ly() %>% layout(title = "No data available"))
+ }
+
+ data <- values$selection_metrics
+
+ # Prepare data
+ chroms <- unique(data$Chromosome)
+ chrom_pos <- data.frame()
+
+ for (i in seq_along(chroms)) {
+ chr_data <- data[data$Chromosome == chroms[i], ]
+ if (nrow(chr_data) > 0) {
+ chr_data$ChromIndex <- i
+ chr_data$PosScaled <- chr_data$Position / max(chr_data$Position, na.rm = TRUE) + (i - 1)
+ chrom_pos <- rbind(chrom_pos, chr_data)
+ }
+ }
+
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') %>%
+ add_trace(
+ data = chrom_pos,
+ x = ~PosScaled,
+ y = ~Tajima_D_Dom,
+ type = 'scatter',
+ mode = 'markers',
+ name = 'Domesticated',
+ marker = list(size = 5, color = '#58a6ff', opacity = 0.7),
+ text = ~paste("Marker:", Marker, "
Chr:", Chromosome, "
D(Dom):", round(Tajima_D_Dom, 3)),
+ hoverinfo = 'text'
+ ) %>%
+ add_trace(
+ data = chrom_pos,
+ x = ~PosScaled,
+ y = ~Tajima_D_Wild,
+ type = 'scatter',
+ mode = 'markers',
+ name = 'Wild',
+ marker = list(size = 5, color = '#f97316', opacity = 0.7),
+ text = ~paste("Marker:", Marker, "
Chr:", Chromosome, "
D(Wild):", round(Tajima_D_Wild, 3)),
+ hoverinfo = 'text'
+ ) %>%
+ add_segments(
+ x = min(chrom_pos$PosScaled, na.rm = TRUE),
+ xend = max(chrom_pos$PosScaled, na.rm = TRUE),
+ y = input$tajima_threshold,
+ yend = input$tajima_threshold,
+ line = list(color = 'red', dash = 'dash', width = 1),
+ name = 'Threshold'
+ ) %>%
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")
+ title = "Tajima's D Manhattan Plot",
+ xaxis = list(
+ title = "Chromosome",
+ ticktext = chroms,
+ tickvals = tapply(chrom_pos$PosScaled, chrom_pos$Chromosome, median, na.rm = TRUE),
+ tickangle = 45
+ ),
+ yaxis = list(title = "Tajima's D"),
+ hoverlabel = list(bgcolor = "#21262d"),
+ plot_bgcolor = "#0d1117",
+ paper_bgcolor = "#161b22",
+ font = list(color = "#8b949e")
)
})
+ # Performance plot
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') %>%
+
+ plot_ly(
+ data = values$performance_metrics,
+ x = ~Metric,
+ y = ~Value,
+ type = 'bar',
+ marker = list(
+ color = c('#58a6ff', '#58a6ff', '#3fb950', '#3fb950'),
+ line = list(color = '#ffffff', width = 1)
+ ),
+ 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")
+ title = "Model Performance Metrics",
+ yaxis = list(title = "Value", range = c(0, 1.1)),
+ plot_bgcolor = "#0d1117",
+ paper_bgcolor = "#161b22",
+ font = list(color = "#8b949e")
)
})
+ # Regression plots
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)
+
+ plot_ly(
+ data = values$train_predictions,
+ x = ~Observed,
+ y = ~Predicted,
+ type = 'scatter',
+ mode = 'markers',
+ marker = list(size = 6, color = '#58a6ff', opacity = 0.7)
+ ) %>%
+ add_trace(
+ x = range(values$train_predictions$Observed),
+ y = range(values$train_predictions$Observed),
+ type = 'scatter',
+ mode = 'lines',
+ line = list(color = '#f85149', dash = 'dash'),
+ name = '1:1 line',
+ showlegend = FALSE
+ ) %>%
+ layout(
+ title = "Training Set",
+ xaxis = list(title = "Observed"),
+ yaxis = list(title = "Predicted"),
+ plot_bgcolor = "#0d1117",
+ paper_bgcolor = "#161b22",
+ font = list(color = "#8b949e")
+ )
})
output$regression_plot_test <- renderPlotly({
req(values$test_predictions)
- 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)
+
+ plot_ly(
+ data = values$test_predictions,
+ x = ~Observed,
+ y = ~Predicted,
+ type = 'scatter',
+ mode = 'markers',
+ marker = list(size = 6, color = '#3fb950', opacity = 0.7)
+ ) %>%
+ add_trace(
+ x = range(values$test_predictions$Observed),
+ y = range(values$test_predictions$Observed),
+ type = 'scatter',
+ mode = 'lines',
+ line = list(color = '#f85149', dash = 'dash'),
+ name = '1:1 line',
+ showlegend = FALSE
+ ) %>%
+ layout(
+ title = "Validation Set",
+ xaxis = list(title = "Observed"),
+ yaxis = list(title = "Predicted"),
+ plot_bgcolor = "#0d1117",
+ paper_bgcolor = "#161b22",
+ font = list(color = "#8b949e")
+ )
})
+ # Epistasis heatmap
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))
+
+ if ("Message" %in% colnames(values$epistasis_all)) {
+ return(plot_ly() %>% layout(title = values$epistasis_all$Message[1]))
+ }
+
+ # Create matrix for heatmap
+ qtls <- unique(values$epistasis_all$QTL1)
+ markers <- unique(values$epistasis_all$QTL2)
+
+ p_matrix <- matrix(NA, nrow = length(qtls), ncol = length(markers))
+ rownames(p_matrix) <- qtls
+ colnames(p_matrix) <- 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_matrix[values$epistasis_all$QTL1[i], values$epistasis_all$QTL2[i]] <-
+ -log10(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"))
+
+ plot_ly(
+ x = colnames(p_matrix),
+ y = rownames(p_matrix),
+ z = p_matrix,
+ type = "heatmap",
+ colorscale = "Viridis",
+ hovertemplate = "QTL: %{y}
Marker: %{x}
-log10(p): %{z:.2f}"
+ ) %>%
+ layout(
+ title = "Epistatic Interactions (-log10 p-value)",
+ xaxis = list(title = "Marker", tickangle = 45),
+ yaxis = list(title = "QTL"),
+ plot_bgcolor = "#0d1117",
+ paper_bgcolor = "#161b22",
+ font = list(color = "#8b949e")
+ )
})
- # ---- TABLES ----
+ # ============================================================
+ # 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)
+
+ if ("Message" %in% colnames(values$qtl_effects_train)) {
+ return(datatable(data.frame(Status = values$qtl_effects_train$Message[1]),
+ options = list(dom = 't')))
+ }
+
+ # Select columns to display
+ display_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)
+ )
+
+ df <- values$qtl_effects_train[order(-values$qtl_effects_train$LOD), display_cols]
+
+ datatable(
+ df,
+ options = list(
+ pageLength = 10,
+ scrollX = TRUE,
+ dom = 'Bfrtip',
+ buttons = c('copy', 'csv', 'excel')
+ ),
+ rownames = FALSE,
+ class = 'cell-border stripe'
+ ) %>%
+ formatRound(columns = intersect(c("LOD", "Additive_Effect", "PVE_Percent"), colnames(df)), digits = 3)
})
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)
+
+ if ("Message" %in% colnames(values$epistasis_sig)) {
+ return(datatable(data.frame(Status = values$epistasis_sig$Message[1]),
+ options = list(dom = 't')))
+ }
+
+ datatable(
+ values$epistasis_sig[order(values$epistasis_sig$Interaction_p), ],
+ options = list(
+ pageLength = 10,
+ scrollX = TRUE,
+ dom = 'Bfrtip'
+ ),
+ rownames = FALSE
+ ) %>%
+ formatSignif(columns = c("Interaction_p", "Effect_Size"), digits = 4)
})
output$selection_table <- renderDT({
req(values$selection_metrics)
- if ("Message" %in% colnames(values$selection_metrics)) return(datatable(data.frame(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)
+
+ if ("Message" %in% colnames(values$selection_metrics)) {
+ return(datatable(data.frame(Status = values$selection_metrics$Message[1]),
+ options = list(dom = 't')))
+ }
+
+ # Add QTL overlap column
+ df <- values$selection_metrics
+ if (!is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train)) {
+ df$QTL_Overlap <- df$Marker %in% values$qtl_effects_train$Marker
+ }
+
+ display_cols <- intersect(
+ c("Marker", "Chromosome", "Position", "Fst", "Pi_Dom", "Pi_Wild",
+ "Tajima_D_Dom", "Tajima_D_Wild", "Significant", "QTL_Overlap"),
+ colnames(df)
+ )
+
+ datatable(
+ df[order(-df$Fst), display_cols],
+ options = list(
+ pageLength = 10,
+ scrollX = TRUE,
+ dom = 'Bfrtip'
+ ),
+ rownames = FALSE
+ ) %>%
+ formatRound(columns = intersect(c("Fst", "Pi_Dom", "Pi_Wild", "Tajima_D_Dom", "Tajima_D_Wild"),
+ colnames(df)), digits = 3)
})
- # ---- CHROMOSOME VIZ ----
+ # ============================================================
+ # CHROMOSOME VISUALIZATION
+ # ============================================================
+
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")))
- )
- }))
+
+ if ("Message" %in% colnames(values$lod_scores_train)) {
+ return(div(class = "alert alert-info", values$lod_scores_train$Message[1]))
+ }
+
+ # Get chromosomes with QTLs
+ chromosomes <- unique(values$lod_scores_train$Chromosome)
+
+ tagList(
+ lapply(chromosomes, function(chr) {
+ # Get markers on this chromosome
+ chr_markers <- values$all_markers[values$all_markers$Chromosome == chr, ]
+ chr_markers <- chr_markers[order(chr_markers$Position), ]
+
+ # Get QTLs on this chromosome
+ chr_qtls <- values$lod_scores_train[values$lod_scores_train$Chromosome == chr, ]
+
+ # Get selection markers on this chromosome
+ sel_markers <- NULL
+ if (!is.null(values$selection_metrics) && !"Message" %in% colnames(values$selection_metrics)) {
+ sel_markers <- values$selection_metrics[
+ values$selection_metrics$Chromosome == chr &
+ values$selection_metrics$Significant,
+ ]
+ }
+
+ # Calculate positions
+ min_pos <- min(chr_markers$Position, na.rm = TRUE)
+ max_pos <- max(chr_markers$Position, na.rm = TRUE)
+ range_pos <- max_pos - min_pos
+
+ div(class = "chromosome-container",
+ div(class = "chromosome-title", paste("Chromosome", chr)),
+ div(class = "chromosome",
+ # Add all markers as subtle background
+ lapply(1:nrow(chr_markers), function(i) {
+ marker <- chr_markers[i, ]
+ left <- if (range_pos > 0) {
+ ((marker$Position - min_pos) / range_pos) * 100
+ } else {
+ (i / nrow(chr_markers)) * 100
+ }
+
+ # Determine marker class
+ marker_class <- "chromosome-marker"
+ if (marker$Marker %in% chr_qtls$Marker) {
+ marker_class <- paste(marker_class, "significant")
+ } else if (!is.null(sel_markers) && marker$Marker %in% sel_markers$Marker) {
+ marker_class <- paste(marker_class, "selection")
+ } else if (marker$Marker %in% c(chr_qtls$Low_Flank, chr_qtls$High_Flank)) {
+ marker_class <- paste(marker_class, "flanking")
+ }
+
+ div(
+ class = marker_class,
+ style = paste0("left: ", left, "%;"),
+ `data-marker` = marker$Marker
+ )
+ })
+ ),
+ div(class = "chromosome-legend",
+ span(paste(format(min_pos, big.mark = ","), "bp")),
+ span(paste(format(max_pos, big.mark = ","), "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)))
- }
+ # Simulation animations
+ observeEvent(input$simulate_btn, {
+ session$sendCustomMessage("simulateQTLDiscovery", list())
})
- # ---- INTERPRETATION OUTPUTS ----
+ observeEvent(input$reset_btn, {
+ session$sendCustomMessage("resetAnimation", list())
+ })
- mk_section <- function(title, content) {
- div(class="interpretation-section", tags$h5(title), tags$p(content))
- }
+ # ============================================================
+ # INTERPRETATION OUTPUTS
+ # ============================================================
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."))
+ has_qtl <- !is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train)
+ has_perf <- !is.null(values$performance_metrics)
+ has_epi <- !is.null(values$epistasis_sig) && !"Message" %in% colnames(values$epistasis_sig)
+ has_sel <- !is.null(values$selection_metrics) && !"Message" %in% colnames(values$selection_metrics)
+
+ n_qtl <- if (has_qtl) nrow(values$qtl_effects_train) else 0
+ n_epi <- if (has_epi) nrow(values$epistasis_sig) else 0
+ n_sel <- if (has_sel) sum(values$selection_metrics$Significant, na.rm = TRUE) else 0
+
+ val_r2 <- if (has_perf) round(values$performance_metrics$Value[values$performance_metrics$Metric == "R² (Validation)"], 3) else "N/A"
+
+ div(class = "interpretation-section",
+ tags$h5("Analysis Summary"),
+ tags$p(paste(
+ "Your analysis identified", n_qtl, "significant QTLs above LOD", input$lod_threshold,
+ if (has_perf) paste0("with a validation R² of ", val_r2, ".") else ".",
+ if (has_epi) paste("Detected", n_epi, "epistatic interactions.") else "",
+ if (has_sel) paste("Found", n_sel, "markers with selection signatures.") else "",
+ sep = " "
+ ))
)
})
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."))
+ if (is.null(values$qtl_effects_train) || "Message" %in% colnames(values$qtl_effects_train)) {
+ return(div(class = "interpretation-section",
+ tags$h5("QTL Significance"),
+ tags$p("No significant QTLs detected. Try lowering the LOD threshold or check your data quality.")
+ ))
+ }
+
+ top_qtl <- values$qtl_effects_train[which.max(values$qtl_effects_train$LOD), ]
+ sig_count <- sum(values$qtl_effects_train$LOD >= 5)
+ sug_count <- sum(values$qtl_effects_train$LOD >= 3 & values$qtl_effects_train$LOD < 5)
+
+ div(class = "interpretation-section",
+ tags$h5("QTL Significance"),
+ tags$p(paste(
+ "Top QTL:", top_qtl$Marker, "on chromosome", top_qtl$Chromosome,
+ "with LOD =", round(top_qtl$LOD, 2), ".",
+ if (top_qtl$LOD >= 5) "This is a highly significant QTL."
+ else if (top_qtl$LOD >= 3) "This is a suggestive QTL."
+ else "This is below standard significance thresholds.",
+ paste0("Overall, you have ", sig_count, " significant (LOD≥5) and ",
+ sug_count, " suggestive (LOD 3-5) QTLs.")
+ ))
+ )
})
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."))
+ if (is.null(values$qtl_effects_train) || "Message" %in% colnames(values$qtl_effects_train)) {
+ return(div(class = "interpretation-section",
+ tags$h5("Effect Sizes"),
+ tags$p("No QTL effects to interpret.")
+ ))
+ }
+
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), "]."))
+
+ div(class = "interpretation-section",
+ tags$h5("Effect Sizes"),
+ tags$p(paste0(
+ "The largest effect QTL is ", top_pve$Marker, " explaining ",
+ round(top_pve$PVE_Percent, 1), "% of phenotypic variance. ",
+ if (top_pve$PVE_Percent > 10) "This is a major-effect QTL suitable for marker-assisted selection."
+ else if (top_pve$PVE_Percent > 5) "This is a moderate-effect QTL."
+ else "This is a minor-effect QTL, typical for polygenic traits.",
+ " The largest additive effect is ", round(top_add$Additive_Effect, 3),
+ " at ", top_add$Marker, "."
+ ))
)
})
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."))
+ if (is.null(values$epistasis_sig) || "Message" %in% colnames(values$epistasis_sig)) {
+ return(div(class = "interpretation-section",
+ tags$h5("Epistasis"),
+ tags$p("No significant epistatic interactions detected.")
+ ))
+ }
+
+ n_epi <- nrow(values$epistasis_sig)
+ top_epi <- values$epistasis_sig[which.min(values$epistasis_sig$Interaction_p), ]
+
+ div(class = "interpretation-section",
+ tags$h5("Epistasis"),
+ tags$p(paste0(
+ "Detected ", n_epi, " significant pairwise interactions. ",
+ "The strongest interaction is between ", top_epi$QTL1, " and ", top_epi$QTL2,
+ " (p = ", format.pval(top_epi$Interaction_p), ", effect = ", round(top_epi$Effect_Size, 3), "). ",
+ "This suggests non-additive genetic effects that could be important for trait expression."
+ ))
+ )
})
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.")
+ has_qtl <- !is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train)
+ has_epi <- !is.null(values$epistasis_sig) && !"Message" %in% colnames(values$epistasis_sig)
+ has_sel <- !is.null(values$selection_metrics) && !"Message" %in% colnames(values$selection_metrics)
+
+ recs <- character()
+
+ if (has_qtl) {
+ top_qtl <- values$qtl_effects_train[which.max(values$qtl_effects_train$LOD), ]
+ recs <- c(recs, paste("• Prioritize", top_qtl$Marker, "for validation and fine-mapping"))
+
+ if (has_epi && nrow(values$epistasis_sig) > 0) {
+ recs <- c(recs, paste("• Investigate epistatic interactions in breeding programs"))
+ }
+
+ if (has_sel) {
+ overlap <- values$selection_metrics$Marker[
+ values$selection_metrics$Marker %in% values$qtl_effects_train$Marker &
+ values$selection_metrics$Significant
+ ]
+ if (length(overlap) > 0) {
+ recs <- c(recs, paste("• QTLs under selection:", paste(overlap, collapse = ", ")))
+ }
+ }
+
+ # Add general recommendations
+ recs <- c(recs,
+ "• Validate QTLs in independent populations",
+ "• Use flanking markers for marker-assisted selection",
+ "• Consider multi-locus models for prediction"
+ )
} 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.")
+ recs <- c(
+ "• Upload genotype and phenotype data",
+ "• Run QTL analysis with appropriate LOD threshold",
+ "• Consider increasing sample size for more power",
+ "• Check data quality and format"
+ )
}
- div(mk_section("NEXT STEPS",
- tags$ul(style="margin-top:8px; color:#8b949e; line-height:2;",
- lapply(recs, function(r) tags$li(r))
+
+ div(class = "interpretation-section",
+ tags$h5("Recommendations"),
+ tags$ul(
+ lapply(recs, function(r) tags$li(r)),
+ style = "color: #8b949e; line-height: 1.8;"
)
- ))
+ )
})
- # ---- DOWNLOAD HANDLERS ----
+ # ============================================================
+ # DOWNLOAD HANDLERS
+ # ============================================================
+
output$download_train_results <- downloadHandler(
- filename = function() paste0("train_qtl_results_", Sys.Date(), ".xlsx"),
+ filename = function() {
+ paste0("qtl_results_train_", 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
+ sheets <- list()
+
+ if (!is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train)) {
+ sheets[["QTL_Effects"]] <- values$qtl_effects_train
+ }
+
+ if (!is.null(values$performance_metrics)) {
+ sheets[["Performance"]] <- values$performance_metrics
+ }
+
+ if (!is.null(values$epistasis_sig) && !"Message" %in% colnames(values$epistasis_sig)) {
+ sheets[["Epistasis"]] <- values$epistasis_sig
+ }
+
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"),
+ 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)
+ if (!is.null(values$selection_metrics) && !"Message" %in% colnames(values$selection_metrics)) {
+ write_xlsx(list(Selection_Metrics = values$selection_metrics), file)
+ } else {
+ write_xlsx(list(Message = "No selection results available"), file)
+ }
}
)
}
-shinyApp(ui = ui, server = server)
+# ============================================================
+# RUN APP
+# ============================================================
+
+shinyApp(ui = ui, server = server)
\ No newline at end of file