Spaces:
Sleeping
Sleeping
International Rice Research Institute commited on
Update app.R
Browse files
app.R
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
# ============================================================
|
| 2 |
-
# QTL-Mapper -
|
| 3 |
# ============================================================
|
| 4 |
|
| 5 |
# Package installation for Hugging Face
|
|
@@ -9,7 +9,7 @@ options(repos = c(CRAN = "https://cloud.r-project.org"))
|
|
| 9 |
required_packages <- c(
|
| 10 |
"shiny", "randomForest", "caret", "DT", "ggplot2", "plotly",
|
| 11 |
"writexl", "viridis", "reshape2", "dplyr", "httr", "jsonlite",
|
| 12 |
-
"
|
| 13 |
)
|
| 14 |
|
| 15 |
for (pkg in required_packages) {
|
|
@@ -19,31 +19,23 @@ for (pkg in required_packages) {
|
|
| 19 |
}
|
| 20 |
}
|
| 21 |
|
| 22 |
-
# Initialize reticulate for Python-based transformers
|
| 23 |
-
tryCatch({
|
| 24 |
-
use_python("/usr/local/bin/python3", required = FALSE)
|
| 25 |
-
}, error = function(e) {
|
| 26 |
-
message("Python not available, using API mode only")
|
| 27 |
-
})
|
| 28 |
-
|
| 29 |
# ============================================================
|
| 30 |
-
# TRANSFORMER-BASED LLM SYSTEM
|
| 31 |
# ============================================================
|
| 32 |
|
| 33 |
-
# Configuration - Load token from environment variable
|
| 34 |
HF_API_TOKEN <- Sys.getenv("HF_API_TOKEN")
|
| 35 |
use_hf_api <- HF_API_TOKEN != ""
|
| 36 |
|
| 37 |
-
#
|
| 38 |
-
hf_model <- "
|
| 39 |
-
# Alternative models if
|
| 40 |
-
# hf_model <- "
|
| 41 |
# hf_model <- "mistralai/Mistral-7B-Instruct-v0.2"
|
| 42 |
-
# hf_model <- "HuggingFaceH4/zephyr-7b-beta"
|
| 43 |
|
| 44 |
HF_API_URL <- paste0("https://api-inference.huggingface.co/models/", hf_model)
|
| 45 |
|
| 46 |
-
# Function to query Hugging Face API
|
| 47 |
query_hf_api <- function(prompt, max_length = 500, temperature = 0.7) {
|
| 48 |
if (HF_API_TOKEN == "") {
|
| 49 |
return(list(success = FALSE, error = "HF_API_TOKEN not set"))
|
|
@@ -51,9 +43,9 @@ query_hf_api <- function(prompt, max_length = 500, temperature = 0.7) {
|
|
| 51 |
|
| 52 |
# Format prompt for better responses
|
| 53 |
formatted_prompt <- paste0(
|
| 54 |
-
"You are an expert bioinformatics assistant specializing in QTL
|
| 55 |
-
"
|
| 56 |
-
"
|
| 57 |
)
|
| 58 |
|
| 59 |
tryCatch({
|
|
@@ -70,8 +62,6 @@ query_hf_api <- function(prompt, max_length = 500, temperature = 0.7) {
|
|
| 70 |
temperature = temperature,
|
| 71 |
do_sample = TRUE,
|
| 72 |
top_p = 0.95,
|
| 73 |
-
top_k = 50,
|
| 74 |
-
repetition_penalty = 1.1,
|
| 75 |
return_full_text = FALSE
|
| 76 |
)
|
| 77 |
), auto_unbox = TRUE),
|
|
@@ -79,8 +69,9 @@ query_hf_api <- function(prompt, max_length = 500, temperature = 0.7) {
|
|
| 79 |
timeout(60)
|
| 80 |
)
|
| 81 |
|
| 82 |
-
|
| 83 |
-
|
|
|
|
| 84 |
result <- content(response, as = "parsed", encoding = "UTF-8")
|
| 85 |
|
| 86 |
# Handle different response formats
|
|
@@ -90,25 +81,23 @@ query_hf_api <- function(prompt, max_length = 500, temperature = 0.7) {
|
|
| 90 |
} else if (length(result) > 0 && !is.null(result[[1]]$generated_text)) {
|
| 91 |
return(list(success = TRUE, text = result[[1]]$generated_text))
|
| 92 |
} else {
|
| 93 |
-
# Try to extract text from response
|
| 94 |
return(list(success = TRUE, text = as.character(result)))
|
| 95 |
}
|
| 96 |
} else {
|
| 97 |
return(list(success = TRUE, text = as.character(result)))
|
| 98 |
}
|
| 99 |
-
} else if (
|
| 100 |
-
|
| 101 |
-
return(list(success = FALSE, error = "Model is loading, please try again in a few seconds", loading = TRUE))
|
| 102 |
} else {
|
| 103 |
error_content <- tryCatch({
|
| 104 |
content(response, "text", encoding = "UTF-8")
|
| 105 |
}, error = function(e) {
|
| 106 |
-
paste("Status:",
|
| 107 |
})
|
| 108 |
|
| 109 |
return(list(
|
| 110 |
success = FALSE,
|
| 111 |
-
error = paste("API
|
| 112 |
))
|
| 113 |
}
|
| 114 |
}, error = function(e) {
|
|
@@ -121,125 +110,65 @@ query_hf_api <- function(prompt, max_length = 500, temperature = 0.7) {
|
|
| 121 |
# ============================================================
|
| 122 |
|
| 123 |
build_system_prompt <- function(rv) {
|
| 124 |
-
|
| 125 |
-
context_parts <- c(
|
| 126 |
-
"CURRENT ANALYSIS RESULTS:"
|
| 127 |
-
)
|
| 128 |
|
| 129 |
# Add QTL results
|
| 130 |
if (!is.null(rv$qtl_effects_train) && !"Message" %in% colnames(rv$qtl_effects_train)) {
|
| 131 |
n_qtl <- nrow(rv$qtl_effects_train)
|
| 132 |
-
top_qtl <- rv$qtl_effects_train[order(-rv$qtl_effects_train$LOD), ][1,]
|
| 133 |
total_pve <- sum(rv$qtl_effects_train$PVE_Percent, na.rm = TRUE)
|
| 134 |
|
| 135 |
-
context_parts <- c(context_parts,
|
| 136 |
-
"\nQTL Results: %d significant QTLs detected
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
))
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
context_parts <- c(context_parts, sprintf(
|
| 150 |
-
"Confidence interval: from %s to %s.",
|
| 151 |
-
top_qtl$Low_Flank, top_qtl$High_Flank
|
| 152 |
-
))
|
| 153 |
}
|
| 154 |
}
|
| 155 |
|
| 156 |
# Add performance metrics
|
| 157 |
if (!is.null(rv$performance_metrics)) {
|
| 158 |
pm <- rv$performance_metrics
|
| 159 |
-
train_r2 <-
|
| 160 |
-
val_r2 <-
|
| 161 |
-
train_r <- round(pm$Value[pm$Metric == "R (Train)"], 3)
|
| 162 |
-
val_r <- round(pm$Value[pm$Metric == "R (Validation)"], 3)
|
| 163 |
-
|
| 164 |
-
context_parts <- c(context_parts, sprintf(
|
| 165 |
-
"\nModel Performance: Training R²=%.3f, Validation R²=%.3f, Training R=%.3f, Validation R=%.3f.",
|
| 166 |
-
train_r2, val_r2, train_r, val_r
|
| 167 |
-
))
|
| 168 |
-
|
| 169 |
-
# Add interpretation
|
| 170 |
-
if (val_r2 < 0) {
|
| 171 |
-
context_parts <- c(context_parts, "Note: Negative validation R² indicates poor model generalization.")
|
| 172 |
-
} else if (val_r2 < 0.2) {
|
| 173 |
-
context_parts <- c(context_parts, "Note: Low validation R² suggests weak predictive power.")
|
| 174 |
-
} else if (val_r2 > 0.5) {
|
| 175 |
-
context_parts <- c(context_parts, "Note: Good validation R² indicates strong predictive power.")
|
| 176 |
-
}
|
| 177 |
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
|
|
|
| 181 |
}
|
| 182 |
|
| 183 |
# Add epistasis results
|
| 184 |
if (!is.null(rv$epistasis_sig) && !"Message" %in% colnames(rv$epistasis_sig) && nrow(rv$epistasis_sig) > 0) {
|
| 185 |
n_epi <- nrow(rv$epistasis_sig)
|
| 186 |
-
|
|
|
|
| 187 |
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
))
|
| 192 |
-
|
| 193 |
-
context_parts <- c(context_parts, sprintf(
|
| 194 |
-
"Strongest interaction: %s × %s (p=%.4f, effect=%.3f).",
|
| 195 |
-
top_epi$QTL1, top_epi$QTL2, top_epi$Interaction_p, top_epi$Effect_Size
|
| 196 |
-
))
|
| 197 |
}
|
| 198 |
|
| 199 |
# Add domestication results
|
| 200 |
if (!is.null(rv$selection_metrics) && !"Message" %in% colnames(rv$selection_metrics)) {
|
| 201 |
n_sig <- sum(rv$selection_metrics$Significant, na.rm = TRUE)
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
context_parts <- c(context_parts, sprintf(
|
| 205 |
-
"\nDomestication: %d markers with significant selection signatures.",
|
| 206 |
-
n_sig
|
| 207 |
-
))
|
| 208 |
-
|
| 209 |
-
context_parts <- c(context_parts, sprintf(
|
| 210 |
-
"Highest Fst: %s on Chr %s (Fst=%.3f, Pi_Dom=%.4f, Pi_Wild=%.4f, Tajima_D_Dom=%.3f).",
|
| 211 |
-
top_fst$Marker, top_fst$Chromosome, top_fst$Fst,
|
| 212 |
-
top_fst$Pi_Dom, top_fst$Pi_Wild, top_fst$Tajima_D_Dom
|
| 213 |
-
))
|
| 214 |
-
|
| 215 |
-
# Check QTL overlap
|
| 216 |
-
if (!is.null(rv$qtl_effects_train) && !"Message" %in% colnames(rv$qtl_effects_train)) {
|
| 217 |
-
overlap <- rv$selection_metrics$Marker[
|
| 218 |
-
rv$selection_metrics$Marker %in% rv$qtl_effects_train$Marker &
|
| 219 |
-
rv$selection_metrics$Significant
|
| 220 |
-
]
|
| 221 |
-
if (length(overlap) > 0) {
|
| 222 |
-
context_parts <- c(context_parts, sprintf(
|
| 223 |
-
"QTLs under selection: %s.",
|
| 224 |
-
paste(overlap, collapse = ", ")
|
| 225 |
-
))
|
| 226 |
-
}
|
| 227 |
-
}
|
| 228 |
}
|
| 229 |
|
| 230 |
-
|
| 231 |
-
if (!is.null(rv$genotype_data)) {
|
| 232 |
-
context_parts <- c(context_parts, sprintf(
|
| 233 |
-
"\nData Summary: %d samples, %d markers.",
|
| 234 |
-
nrow(rv$genotype_data), ncol(rv$genotype_data)
|
| 235 |
-
))
|
| 236 |
-
}
|
| 237 |
-
|
| 238 |
-
paste(context_parts, collapse = " ")
|
| 239 |
}
|
| 240 |
|
| 241 |
# ============================================================
|
| 242 |
-
# ENHANCED RULE-BASED RESPONSES
|
| 243 |
# ============================================================
|
| 244 |
|
| 245 |
enhanced_rule_response <- function(user_message, rv) {
|
|
@@ -252,7 +181,7 @@ enhanced_rule_response <- function(user_message, rv) {
|
|
| 252 |
has_sel <- !is.null(rv$selection_metrics) && !"Message" %in% colnames(rv$selection_metrics)
|
| 253 |
|
| 254 |
# PVE-specific questions
|
| 255 |
-
if (grepl("pve|variance explained|how much variance|percent variance", q)) {
|
| 256 |
if (has_qtl) {
|
| 257 |
df <- rv$qtl_effects_train
|
| 258 |
total_pve <- sum(df$PVE_Percent, na.rm = TRUE)
|
|
@@ -260,39 +189,32 @@ enhanced_rule_response <- function(user_message, rv) {
|
|
| 260 |
|
| 261 |
response <- paste0(
|
| 262 |
"📊 **PVE (Phenotypic Variance Explained) Analysis**\n\n",
|
| 263 |
-
"Your
|
|
|
|
|
|
|
| 264 |
"**Top QTL by PVE:**\n",
|
| 265 |
-
"• Marker: ", top_pve$Marker, "\n",
|
| 266 |
"• Chromosome: ", top_pve$Chromosome, "\n",
|
| 267 |
-
"• PVE: ", round(top_pve$PVE_Percent, 1), "%\n",
|
| 268 |
"• LOD: ", round(top_pve$LOD, 2), "\n\n"
|
| 269 |
)
|
| 270 |
|
| 271 |
if (top_pve$PVE_Percent > 10) {
|
| 272 |
-
response <- paste0(response, "This is a **major-effect QTL** (>10% PVE) - excellent candidate for marker-assisted selection.\n\n")
|
| 273 |
} else if (top_pve$PVE_Percent > 5) {
|
| 274 |
-
response <- paste0(response, "This is a **moderate-effect QTL** (5-10% PVE) - useful for polygenic breeding approaches.\n\n")
|
| 275 |
} else {
|
| 276 |
-
response <- paste0(response, "This is a **minor-effect QTL** (<5% PVE) - typical for complex polygenic traits.\n\n")
|
| 277 |
}
|
| 278 |
|
| 279 |
-
#
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
)
|
| 286 |
}
|
| 287 |
|
| 288 |
-
# Add recommendations
|
| 289 |
-
response <- paste0(response,
|
| 290 |
-
"**Recommendations:**\n",
|
| 291 |
-
"• Focus on QTLs with PVE >5% for validation\n",
|
| 292 |
-
"• Consider that QTLs may share overlapping variance\n",
|
| 293 |
-
"• Use flanking markers for fine-mapping\n"
|
| 294 |
-
)
|
| 295 |
-
|
| 296 |
return(response)
|
| 297 |
} else {
|
| 298 |
return("No QTL results yet. Please run the QTL analysis first to see PVE values.")
|
|
@@ -300,7 +222,7 @@ enhanced_rule_response <- function(user_message, rv) {
|
|
| 300 |
}
|
| 301 |
|
| 302 |
# Model performance questions
|
| 303 |
-
if (grepl("model performance|r2|r squared|how good is my model|validation", q)) {
|
| 304 |
if (has_perf) {
|
| 305 |
pm <- rv$performance_metrics
|
| 306 |
train_r2 <- pm$Value[pm$Metric == "R² (Train)"]
|
|
@@ -308,36 +230,36 @@ enhanced_rule_response <- function(user_message, rv) {
|
|
| 308 |
|
| 309 |
response <- paste0(
|
| 310 |
"📈 **Model Performance Summary**\n\n",
|
| 311 |
-
"• Training R²: ", round(train_r2, 3), "\n",
|
| 312 |
-
"• Validation R²: ", round(val_r2, 3), "\n\n"
|
| 313 |
)
|
| 314 |
|
| 315 |
if (val_r2 < 0) {
|
| 316 |
response <- paste0(response,
|
| 317 |
-
"⚠️ **
|
| 318 |
-
"
|
| 319 |
-
"
|
| 320 |
-
"•
|
| 321 |
-
"•
|
| 322 |
-
"**
|
| 323 |
-
"
|
| 324 |
-
"
|
| 325 |
-
"
|
|
|
|
|
|
|
| 326 |
)
|
| 327 |
} else if (val_r2 < 0.2) {
|
| 328 |
response <- paste0(response,
|
| 329 |
"📉 **Low validation R²** (<0.2) suggests modest predictive power.\n\n",
|
| 330 |
-
"This is common for complex traits. Focus on individual QTL interpretation
|
| 331 |
)
|
| 332 |
} else if (val_r2 < 0.5) {
|
| 333 |
response <- paste0(response,
|
| 334 |
-
"📊 **Moderate validation R²** (0.2-0.5) - your model has decent predictive ability.\n\n"
|
| 335 |
-
"The identified QTLs explain a meaningful portion of trait variation.\n"
|
| 336 |
)
|
| 337 |
} else {
|
| 338 |
response <- paste0(response,
|
| 339 |
-
"🎯 **Excellent validation R²** (>0.5) - your model has strong predictive power!\n\n"
|
| 340 |
-
"The identified QTLs capture most of the genetic architecture.\n"
|
| 341 |
)
|
| 342 |
}
|
| 343 |
|
|
@@ -348,7 +270,7 @@ enhanced_rule_response <- function(user_message, rv) {
|
|
| 348 |
}
|
| 349 |
|
| 350 |
# Top QTLs question
|
| 351 |
-
if (grepl("top qtl|best qtl|highest lod|significant qtl", q)) {
|
| 352 |
if (has_qtl) {
|
| 353 |
df <- rv$qtl_effects_train[order(-rv$qtl_effects_train$LOD), ]
|
| 354 |
top5 <- head(df, 5)
|
|
@@ -359,7 +281,7 @@ enhanced_rule_response <- function(user_message, rv) {
|
|
| 359 |
row <- top5[i, ]
|
| 360 |
response <- paste0(response,
|
| 361 |
i, ". **", row$Marker, "** (Chr ", row$Chromosome, ")\n",
|
| 362 |
-
" • LOD: ", round(row$LOD, 2), "\n",
|
| 363 |
" • PVE: ", round(row$PVE_Percent, 1), "%\n",
|
| 364 |
" • Additive effect: ", round(row$Additive_Effect, 3), "\n"
|
| 365 |
)
|
|
@@ -375,7 +297,61 @@ enhanced_rule_response <- function(user_message, rv) {
|
|
| 375 |
}
|
| 376 |
}
|
| 377 |
|
| 378 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 379 |
available <- c()
|
| 380 |
if (has_qtl) available <- c(available, paste(nrow(rv$qtl_effects_train), "QTLs"))
|
| 381 |
if (has_perf) {
|
|
@@ -389,11 +365,9 @@ enhanced_rule_response <- function(user_message, rv) {
|
|
| 389 |
return(paste0(
|
| 390 |
"I can see you have: ", paste(available, collapse = ", "), ".\n\n",
|
| 391 |
"What would you like to know? Try asking about:\n",
|
| 392 |
-
"• **PVE** -
|
| 393 |
-
"• **Top QTLs** - List
|
| 394 |
-
"• **Model performance** - R²
|
| 395 |
-
"• **Epistasis** - Interactions between QTLs\n",
|
| 396 |
-
"• **Selection signatures** - Domestication analysis\n",
|
| 397 |
"• **Next steps** - Recommendations for your results"
|
| 398 |
))
|
| 399 |
}
|
|
@@ -401,25 +375,59 @@ enhanced_rule_response <- function(user_message, rv) {
|
|
| 401 |
return(paste0(
|
| 402 |
"👋 Hello! I'm your QTL analysis assistant.\n\n",
|
| 403 |
"**I can help you with:**\n",
|
| 404 |
-
"• Understanding
|
| 405 |
-
"• Interpreting
|
| 406 |
"• Evaluating model performance (R²)\n",
|
| 407 |
-
"• Detecting epistatic interactions\n",
|
| 408 |
-
"• Analyzing selection signatures (Fst, Tajima's D)\n\n",
|
| 409 |
"**To get started:**\n",
|
| 410 |
"1. Upload your genotype and phenotype files\n",
|
| 411 |
"2. Click 'Run QTL Analysis'\n",
|
| 412 |
-
"3. Ask me specific questions
|
| 413 |
-
"Try: 'What is PVE?' or 'Show me my top QTLs'"
|
| 414 |
))
|
| 415 |
}
|
| 416 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 417 |
# ============================================================
|
| 418 |
# UI
|
| 419 |
# ============================================================
|
| 420 |
|
| 421 |
ui <- fluidPage(
|
| 422 |
-
# Use shinyjs for enhanced UI interactions
|
| 423 |
shinyjs::useShinyjs(),
|
| 424 |
|
| 425 |
tags$head(
|
|
@@ -812,12 +820,10 @@ ui <- fluidPage(
|
|
| 812 |
"))
|
| 813 |
),
|
| 814 |
|
| 815 |
-
# Navigation bar
|
| 816 |
navbarPage(
|
| 817 |
title = tags$span(tags$i(class = "fas fa-dna", style = "margin-right:8px; color:#58a6ff;"), "QTL-Mapper AI"),
|
| 818 |
id = "nav",
|
| 819 |
|
| 820 |
-
# Data Upload Tab
|
| 821 |
tabPanel("Data Upload", icon = icon("upload"),
|
| 822 |
div(class = "main-header",
|
| 823 |
h2(tags$i(class = "fas fa-upload", style = "margin-right:8px;"), "Data Upload"),
|
|
@@ -875,7 +881,6 @@ ui <- fluidPage(
|
|
| 875 |
)
|
| 876 |
),
|
| 877 |
|
| 878 |
-
# Domestication Tab
|
| 879 |
tabPanel("Domestication", icon = icon("leaf"),
|
| 880 |
div(class = "main-header",
|
| 881 |
h2(tags$i(class = "fas fa-leaf", style = "margin-right:8px;"), "Domestication Analysis"),
|
|
@@ -919,7 +924,6 @@ ui <- fluidPage(
|
|
| 919 |
)
|
| 920 |
),
|
| 921 |
|
| 922 |
-
# Results Tab
|
| 923 |
tabPanel("Results", icon = icon("chart-line"),
|
| 924 |
div(class = "main-header",
|
| 925 |
h2(tags$i(class = "fas fa-chart-line", style = "margin-right:8px;"), "QTL Analysis Results"),
|
|
@@ -960,7 +964,6 @@ ui <- fluidPage(
|
|
| 960 |
)
|
| 961 |
),
|
| 962 |
|
| 963 |
-
# Interpretation Tab
|
| 964 |
tabPanel("Interpretation", icon = icon("lightbulb"),
|
| 965 |
div(class = "main-header",
|
| 966 |
h2(tags$i(class = "fas fa-lightbulb", style = "margin-right:8px;"), "Results Interpretation"),
|
|
@@ -981,7 +984,6 @@ ui <- fluidPage(
|
|
| 981 |
)
|
| 982 |
),
|
| 983 |
|
| 984 |
-
# About Tab
|
| 985 |
tabPanel("About", icon = icon("info-circle"),
|
| 986 |
div(class = "main-header",
|
| 987 |
h2(tags$i(class = "fas fa-info-circle", style = "margin-right:8px;"), "About QTL-Mapper AI"),
|
|
@@ -998,7 +1000,7 @@ ui <- fluidPage(
|
|
| 998 |
tags$li("Additive and dominance effects estimated via linear regression"),
|
| 999 |
tags$li("Epistasis analysis: pairwise QTL x marker interactions"),
|
| 1000 |
tags$li("Domestication: Fst, nucleotide diversity (Pi), Tajima's D"),
|
| 1001 |
-
tags$li("AI Assistant powered by
|
| 1002 |
),
|
| 1003 |
h4(style = "color:#58a6ff; font-family: 'IBM Plex Mono'; margin: 12px 0;", "AI Assistant Status"),
|
| 1004 |
p(style = "color: #8b949e; line-height: 1.7;",
|
|
@@ -1022,19 +1024,18 @@ ui <- fluidPage(
|
|
| 1022 |
)
|
| 1023 |
),
|
| 1024 |
|
| 1025 |
-
# Floating Chatbot Panel
|
| 1026 |
tags$div(id = "chat-panel",
|
| 1027 |
tags$div(id = "chat-window",
|
| 1028 |
-
# Header
|
| 1029 |
tags$div(id = "chat-header",
|
| 1030 |
tags$div(class = "chat-title",
|
| 1031 |
tags$div(class = "chat-avatar", "AI"),
|
| 1032 |
tags$div(
|
| 1033 |
tags$h4("QTL Analysis AI Assistant",
|
| 1034 |
-
tags$span(class = "model-badge",
|
|
|
|
| 1035 |
),
|
| 1036 |
tags$p(id = "model_status",
|
| 1037 |
-
if
|
| 1038 |
)
|
| 1039 |
)
|
| 1040 |
),
|
|
@@ -1043,27 +1044,21 @@ ui <- fluidPage(
|
|
| 1043 |
)
|
| 1044 |
),
|
| 1045 |
|
| 1046 |
-
# Quick questions
|
| 1047 |
tags$div(class = "quick-questions",
|
| 1048 |
tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q', 'What is PVE?', {priority: 'event'});", "PVE meaning"),
|
| 1049 |
tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q', 'What are my top QTLs?', {priority: 'event'});", "Top QTLs"),
|
| 1050 |
-
tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q', '
|
| 1051 |
-
tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q', '
|
| 1052 |
-
tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q', 'What does Fst mean?', {priority: 'event'});", "Fst meaning"),
|
| 1053 |
-
tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q', 'Any selection signatures?', {priority: 'event'});", "Selection"),
|
| 1054 |
-
tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q', 'Next steps?', {priority: 'event'});", "Next steps")
|
| 1055 |
),
|
| 1056 |
|
| 1057 |
-
# Messages
|
| 1058 |
tags$div(id = "chat_messages",
|
| 1059 |
uiOutput("chat_display")
|
| 1060 |
),
|
| 1061 |
|
| 1062 |
-
# Footer
|
| 1063 |
tags$div(id = "chat-footer",
|
| 1064 |
tags$textarea(
|
| 1065 |
id = "chat_input",
|
| 1066 |
-
placeholder = "Ask about your
|
| 1067 |
rows = "2"
|
| 1068 |
),
|
| 1069 |
tags$div(class = "chat-actions",
|
|
@@ -1073,7 +1068,6 @@ ui <- fluidPage(
|
|
| 1073 |
)
|
| 1074 |
),
|
| 1075 |
|
| 1076 |
-
# Toggle button
|
| 1077 |
tags$button(id = "chat-toggle-btn",
|
| 1078 |
onclick = "document.getElementById('chat-window').classList.toggle('open');",
|
| 1079 |
tags$i(class = "fas fa-robot")
|
|
@@ -1087,7 +1081,6 @@ ui <- fluidPage(
|
|
| 1087 |
|
| 1088 |
server <- function(input, output, session) {
|
| 1089 |
|
| 1090 |
-
# Reactive values for data storage
|
| 1091 |
values <- reactiveValues(
|
| 1092 |
genotype_data = NULL,
|
| 1093 |
phenotype_data = NULL,
|
|
@@ -1110,174 +1103,93 @@ server <- function(input, output, session) {
|
|
| 1110 |
pop_data = NULL,
|
| 1111 |
selection_metrics = NULL,
|
| 1112 |
has_test_data = FALSE,
|
| 1113 |
-
# Chat state
|
| 1114 |
chat_messages = list(),
|
| 1115 |
is_typing = FALSE,
|
| 1116 |
-
|
| 1117 |
-
|
| 1118 |
-
lod_threshold = 2 # Default threshold
|
| 1119 |
)
|
| 1120 |
|
| 1121 |
-
#
|
| 1122 |
observe({
|
| 1123 |
-
if (
|
| 1124 |
-
|
| 1125 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1126 |
} else {
|
| 1127 |
-
|
| 1128 |
-
shinyjs::html("model_status", "Rule-based mode (set HF_API_TOKEN for AI)")
|
| 1129 |
}
|
| 1130 |
})
|
| 1131 |
|
| 1132 |
-
# ============================================================
|
| 1133 |
-
# AI RESPONSE GENERATION
|
| 1134 |
-
# ============================================================
|
| 1135 |
-
|
| 1136 |
-
generate_ai_response <- function(user_message) {
|
| 1137 |
-
# Build context
|
| 1138 |
-
context <- build_system_prompt(values)
|
| 1139 |
-
|
| 1140 |
-
# Construct prompt
|
| 1141 |
-
prompt <- paste(
|
| 1142 |
-
"CONTEXT:",
|
| 1143 |
-
context,
|
| 1144 |
-
"\n\nUSER QUESTION:", user_message,
|
| 1145 |
-
"\n\nProvide a detailed, helpful response based on the analysis results above. Be specific about marker names, LOD scores, and PVE values when relevant.",
|
| 1146 |
-
sep = "\n"
|
| 1147 |
-
)
|
| 1148 |
-
|
| 1149 |
-
# Try transformer if available
|
| 1150 |
-
if (use_hf_api && values$hf_model_loaded) {
|
| 1151 |
-
# Show thinking indicator
|
| 1152 |
-
values$is_typing <- TRUE
|
| 1153 |
-
|
| 1154 |
-
result <- query_hf_api(prompt)
|
| 1155 |
-
|
| 1156 |
-
values$is_typing <- FALSE
|
| 1157 |
-
|
| 1158 |
-
if (result$success) {
|
| 1159 |
-
return(result$text)
|
| 1160 |
-
} else {
|
| 1161 |
-
# Log error
|
| 1162 |
-
print(paste("API Error:", result$error))
|
| 1163 |
-
# Fallback to rule-based
|
| 1164 |
-
return(enhanced_rule_response(user_message, values))
|
| 1165 |
-
}
|
| 1166 |
-
}
|
| 1167 |
-
|
| 1168 |
-
# Fallback to enhanced rule-based
|
| 1169 |
-
return(enhanced_rule_response(user_message, values))
|
| 1170 |
-
}
|
| 1171 |
-
|
| 1172 |
# ============================================================
|
| 1173 |
# CHAT FUNCTIONS
|
| 1174 |
# ============================================================
|
| 1175 |
|
| 1176 |
-
|
| 1177 |
-
add_message <- function(role, content, temporary = FALSE) {
|
| 1178 |
timestamp <- format(Sys.time(), "%H:%M")
|
| 1179 |
-
|
| 1180 |
-
# If temporary, replace last message if it's also temporary
|
| 1181 |
-
if (temporary && length(values$chat_messages) > 0) {
|
| 1182 |
-
last_msg <- values$chat_messages[[length(values$chat_messages)]]
|
| 1183 |
-
if (!is.null(last_msg$temporary) && last_msg$temporary) {
|
| 1184 |
-
values$chat_messages <- values$chat_messages[-length(values$chat_messages)]
|
| 1185 |
-
}
|
| 1186 |
-
}
|
| 1187 |
-
|
| 1188 |
values$chat_messages <- c(values$chat_messages, list(list(
|
| 1189 |
-
role = role,
|
| 1190 |
-
content = content,
|
| 1191 |
-
time = timestamp,
|
| 1192 |
-
temporary = temporary
|
| 1193 |
)))
|
| 1194 |
-
|
| 1195 |
-
# Keep only last 50 messages
|
| 1196 |
if (length(values$chat_messages) > 50) {
|
| 1197 |
values$chat_messages <- tail(values$chat_messages, 50)
|
| 1198 |
}
|
| 1199 |
-
|
| 1200 |
session$sendCustomMessage("scrollChatBottom", list())
|
| 1201 |
}
|
| 1202 |
|
| 1203 |
-
# Process user message
|
| 1204 |
process_message <- function(user_text) {
|
| 1205 |
if (nchar(trimws(user_text)) == 0) return()
|
| 1206 |
|
| 1207 |
-
# Add user message
|
| 1208 |
add_message("user", user_text)
|
|
|
|
| 1209 |
|
| 1210 |
-
|
| 1211 |
-
response <- generate_ai_response(user_text)
|
| 1212 |
|
| 1213 |
-
|
| 1214 |
add_message("assistant", response)
|
| 1215 |
}
|
| 1216 |
|
| 1217 |
-
# Send message handler
|
| 1218 |
observeEvent(input$send_chat, {
|
| 1219 |
req(input$chat_input)
|
| 1220 |
user_text <- trimws(input$chat_input)
|
| 1221 |
if (nchar(user_text) == 0) return()
|
| 1222 |
-
|
| 1223 |
-
# Clear input
|
| 1224 |
updateTextAreaInput(session, "chat_input", value = "")
|
| 1225 |
-
|
| 1226 |
-
# Process message
|
| 1227 |
process_message(user_text)
|
| 1228 |
})
|
| 1229 |
|
| 1230 |
-
# Quick question handler
|
| 1231 |
observeEvent(input$quick_q, {
|
| 1232 |
req(input$quick_q)
|
| 1233 |
process_message(input$quick_q)
|
| 1234 |
})
|
| 1235 |
|
| 1236 |
-
# Clear chat handler
|
| 1237 |
observeEvent(input$clear_chat, {
|
| 1238 |
values$chat_messages <- list()
|
| 1239 |
-
add_message("assistant", "Chat cleared. How can I help
|
| 1240 |
})
|
| 1241 |
|
| 1242 |
-
# Initialize chat
|
| 1243 |
observe({
|
| 1244 |
if (length(values$chat_messages) == 0) {
|
| 1245 |
-
|
| 1246 |
-
|
| 1247 |
-
"👋 Hello! I'm your AI-powered QTL analysis assistant powered by the phi-2 transformer model.\n\n",
|
| 1248 |
-
"I can help you interpret your results and answer questions about:\n",
|
| 1249 |
-
"• **PVE** - How much variance each QTL explains\n",
|
| 1250 |
-
"• **QTL detection** - LOD scores and significance\n",
|
| 1251 |
-
"• **Model performance** - R² and predictions\n",
|
| 1252 |
-
"• **Epistatic interactions** - QTL × QTL effects\n",
|
| 1253 |
-
"• **Domestication signatures** - Fst and Tajima's D\n",
|
| 1254 |
-
"• **Next steps** - Recommendations for your results\n\n",
|
| 1255 |
-
"Upload your data, run the analysis, and ask me anything!"
|
| 1256 |
-
)
|
| 1257 |
} else {
|
| 1258 |
-
|
| 1259 |
-
"👋 Hello! I'm your QTL analysis assistant.\n\n",
|
| 1260 |
-
"I can help you with:\n",
|
| 1261 |
-
"• Understanding LOD scores and QTL significance\n",
|
| 1262 |
-
"• Interpreting PVE (variance explained)\n",
|
| 1263 |
-
"• Evaluating model performance (R²)\n",
|
| 1264 |
-
"• Detecting epistatic interactions\n",
|
| 1265 |
-
"• Analyzing selection signatures (Fst, Tajima's D)\n\n",
|
| 1266 |
-
"**To get started:**\n",
|
| 1267 |
-
"1. Upload your genotype and phenotype files\n",
|
| 1268 |
-
"2. Click 'Run QTL Analysis'\n",
|
| 1269 |
-
"3. Ask me specific questions about your results!\n\n",
|
| 1270 |
-
"Try: 'What is PVE?' or 'Show me my top QTLs'"
|
| 1271 |
-
)
|
| 1272 |
}
|
| 1273 |
-
add_message("assistant",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1274 |
}
|
| 1275 |
})
|
| 1276 |
|
| 1277 |
-
# Render chat messages
|
| 1278 |
output$chat_display <- renderUI({
|
| 1279 |
messages <- values$chat_messages
|
| 1280 |
-
|
| 1281 |
if (length(messages) == 0) return(NULL)
|
| 1282 |
|
| 1283 |
message_elements <- lapply(messages, function(msg) {
|
|
@@ -1289,14 +1201,11 @@ server <- function(input, output, session) {
|
|
| 1289 |
)
|
| 1290 |
})
|
| 1291 |
|
| 1292 |
-
# Add typing indicator if needed
|
| 1293 |
if (values$is_typing) {
|
| 1294 |
message_elements <- c(message_elements, list(
|
| 1295 |
div(class = "chat-msg assistant",
|
| 1296 |
div(class = "typing-indicator",
|
| 1297 |
-
div(class = "typing-dot"),
|
| 1298 |
-
div(class = "typing-dot"),
|
| 1299 |
-
div(class = "typing-dot")
|
| 1300 |
)
|
| 1301 |
)
|
| 1302 |
))
|
|
@@ -1309,34 +1218,28 @@ server <- function(input, output, session) {
|
|
| 1309 |
# DATA LOADING FUNCTIONS
|
| 1310 |
# ============================================================
|
| 1311 |
|
| 1312 |
-
# Load genotype data
|
| 1313 |
observeEvent(input$genotype_file, {
|
| 1314 |
req(input$genotype_file)
|
| 1315 |
tryCatch({
|
| 1316 |
-
# Read file
|
| 1317 |
all_data <- readLines(input$genotype_file$datapath)
|
| 1318 |
if (length(all_data) < 4) {
|
| 1319 |
-
showNotification("Genotype file must have at least 4 rows
|
| 1320 |
return()
|
| 1321 |
}
|
| 1322 |
|
| 1323 |
-
# Parse header
|
| 1324 |
header <- strsplit(all_data[1], ",")[[1]]
|
| 1325 |
chromosome_row <- strsplit(all_data[2], ",")[[1]]
|
| 1326 |
position_row <- strsplit(all_data[3], ",")[[1]]
|
| 1327 |
|
| 1328 |
-
# Read data
|
| 1329 |
genotype_data <- read.csv(text = all_data[-(1:3)], header = FALSE)
|
| 1330 |
colnames(genotype_data) <- header
|
| 1331 |
rownames(genotype_data) <- genotype_data[, 1]
|
| 1332 |
genotype_data <- genotype_data[, -1]
|
| 1333 |
|
| 1334 |
-
# Convert to numeric
|
| 1335 |
for (col in colnames(genotype_data)) {
|
| 1336 |
genotype_data[[col]] <- as.numeric(as.character(genotype_data[[col]]))
|
| 1337 |
}
|
| 1338 |
|
| 1339 |
-
# Store marker information
|
| 1340 |
values$all_markers <- data.frame(
|
| 1341 |
Marker = colnames(genotype_data),
|
| 1342 |
Chromosome = chromosome_row[-1],
|
|
@@ -1348,82 +1251,54 @@ server <- function(input, output, session) {
|
|
| 1348 |
values$chromosome_info <- chromosome_row[-1]
|
| 1349 |
values$position_info <- as.numeric(position_row[-1])
|
| 1350 |
|
| 1351 |
-
showNotification("Genotype data loaded
|
| 1352 |
-
|
| 1353 |
-
# Add to chat
|
| 1354 |
-
add_message("assistant", paste0(
|
| 1355 |
-
"✅ Loaded genotype data with ", ncol(genotype_data), " markers and ",
|
| 1356 |
-
nrow(genotype_data), " samples."
|
| 1357 |
-
))
|
| 1358 |
|
| 1359 |
}, error = function(e) {
|
| 1360 |
-
showNotification(paste("Error
|
| 1361 |
})
|
| 1362 |
})
|
| 1363 |
|
| 1364 |
-
# Load phenotype data
|
| 1365 |
observeEvent(input$phenotype_file, {
|
| 1366 |
req(input$phenotype_file)
|
| 1367 |
tryCatch({
|
| 1368 |
phenotype_data <- read.csv(input$phenotype_file$datapath)
|
| 1369 |
-
|
| 1370 |
-
# Set row names
|
| 1371 |
rownames(phenotype_data) <- phenotype_data[, 1]
|
| 1372 |
phenotype_data <- phenotype_data[, -1]
|
| 1373 |
|
| 1374 |
-
# Convert to numeric
|
| 1375 |
for (col in colnames(phenotype_data)) {
|
| 1376 |
phenotype_data[[col]] <- as.numeric(as.character(phenotype_data[[col]]))
|
| 1377 |
}
|
| 1378 |
|
| 1379 |
values$phenotype_data <- phenotype_data
|
| 1380 |
-
|
| 1381 |
-
# Update phenotype selector
|
| 1382 |
updateSelectInput(session, "phenotype_column",
|
| 1383 |
choices = colnames(phenotype_data),
|
| 1384 |
selected = colnames(phenotype_data)[1])
|
| 1385 |
|
| 1386 |
-
showNotification("Phenotype data loaded
|
| 1387 |
-
|
| 1388 |
-
# Add to chat
|
| 1389 |
-
add_message("assistant", paste0(
|
| 1390 |
-
"✅ Loaded phenotype data with ", ncol(phenotype_data),
|
| 1391 |
-
" traits and ", nrow(phenotype_data), " samples."
|
| 1392 |
-
))
|
| 1393 |
|
| 1394 |
}, error = function(e) {
|
| 1395 |
-
showNotification(paste("Error
|
| 1396 |
})
|
| 1397 |
})
|
| 1398 |
|
| 1399 |
-
# Load population data
|
| 1400 |
observeEvent(input$pop_file, {
|
| 1401 |
req(input$pop_file)
|
| 1402 |
tryCatch({
|
| 1403 |
pop_data <- read.csv(input$pop_file$datapath)
|
| 1404 |
-
|
| 1405 |
-
# Validate columns
|
| 1406 |
if (!all(c("id", "population") %in% colnames(pop_data))) {
|
| 1407 |
showNotification("Population file must have 'id' and 'population' columns", type = "error")
|
| 1408 |
return()
|
| 1409 |
}
|
| 1410 |
-
|
| 1411 |
values$pop_data <- pop_data
|
| 1412 |
-
|
| 1413 |
-
|
| 1414 |
-
|
| 1415 |
-
# Add to chat
|
| 1416 |
-
add_message("assistant", paste0(
|
| 1417 |
-
"✅ Loaded population data with ", nrow(pop_data), " samples.\n",
|
| 1418 |
-
"Populations: ", paste(unique(pop_data$population), collapse = ", ")
|
| 1419 |
-
))
|
| 1420 |
-
|
| 1421 |
}, error = function(e) {
|
| 1422 |
-
showNotification(paste("Error
|
| 1423 |
})
|
| 1424 |
})
|
| 1425 |
|
| 1426 |
-
# Load test genotype data
|
| 1427 |
observeEvent(input$test_genotype_file, {
|
| 1428 |
req(input$test_genotype_file)
|
| 1429 |
tryCatch({
|
|
@@ -1443,11 +1318,10 @@ server <- function(input, output, session) {
|
|
| 1443 |
|
| 1444 |
values$test_genotype_data <- genotype_data
|
| 1445 |
values$has_test_data <- TRUE
|
| 1446 |
-
|
| 1447 |
-
showNotification("Test genotype data loaded successfully", type = "message")
|
| 1448 |
|
| 1449 |
}, error = function(e) {
|
| 1450 |
-
showNotification(paste("Error
|
| 1451 |
})
|
| 1452 |
})
|
| 1453 |
|
|
@@ -1486,34 +1360,26 @@ server <- function(input, output, session) {
|
|
| 1486 |
})
|
| 1487 |
|
| 1488 |
# ============================================================
|
| 1489 |
-
# QTL ANALYSIS
|
| 1490 |
# ============================================================
|
| 1491 |
|
| 1492 |
-
# Function to calculate QTL effects
|
| 1493 |
calculate_qtl_effects <- function(genotype_matrix, phenotype_vector, marker_names) {
|
| 1494 |
effects_list <- list()
|
| 1495 |
|
| 1496 |
for (marker in marker_names) {
|
| 1497 |
if (!marker %in% colnames(genotype_matrix)) next
|
| 1498 |
|
| 1499 |
-
# Get genotype and phenotype for this marker
|
| 1500 |
geno <- genotype_matrix[, marker]
|
| 1501 |
pheno <- phenotype_vector
|
| 1502 |
-
|
| 1503 |
-
# Remove missing values
|
| 1504 |
valid_idx <- !is.na(geno) & !is.na(pheno)
|
| 1505 |
geno <- geno[valid_idx]
|
| 1506 |
pheno <- pheno[valid_idx]
|
| 1507 |
|
| 1508 |
if (length(unique(geno)) < 2) next
|
| 1509 |
|
| 1510 |
-
# Fit linear model
|
| 1511 |
lm_fit <- lm(pheno ~ geno)
|
| 1512 |
-
|
| 1513 |
-
# Calculate additive effect
|
| 1514 |
additive_effect <- coef(lm_fit)[2]
|
| 1515 |
|
| 1516 |
-
# Calculate dominance effect if possible
|
| 1517 |
dominance_effect <- NA
|
| 1518 |
if (length(unique(geno)) == 3) {
|
| 1519 |
geno_means <- tapply(pheno, geno, mean, na.rm = TRUE)
|
|
@@ -1523,20 +1389,15 @@ server <- function(input, output, session) {
|
|
| 1523 |
dominance_effect <- het_mean - midparent
|
| 1524 |
}
|
| 1525 |
|
| 1526 |
-
# Calculate PVE
|
| 1527 |
r_squared <- summary(lm_fit)$r.squared
|
| 1528 |
-
|
| 1529 |
-
# Standard error and CI
|
| 1530 |
-
se_additive <- tryCatch({
|
| 1531 |
-
summary(lm_fit)$coefficients[2, 2]
|
| 1532 |
-
}, error = function(e) NA)
|
| 1533 |
|
| 1534 |
effects_list[[marker]] <- data.frame(
|
| 1535 |
Marker = marker,
|
| 1536 |
Additive_Effect = additive_effect,
|
| 1537 |
Dominance_Effect = dominance_effect,
|
| 1538 |
PVE_Percent = r_squared * 100,
|
| 1539 |
-
SE_Additive =
|
| 1540 |
CI_Lower = ifelse(is.na(se_additive), NA, additive_effect - 1.96 * se_additive),
|
| 1541 |
CI_Upper = ifelse(is.na(se_additive), NA, additive_effect + 1.96 * se_additive),
|
| 1542 |
N_Samples = length(pheno),
|
|
@@ -1553,31 +1414,23 @@ server <- function(input, output, session) {
|
|
| 1553 |
req(values$genotype_data, values$phenotype_data, input$phenotype_column)
|
| 1554 |
|
| 1555 |
showNotification("Starting QTL analysis...", type = "message")
|
|
|
|
| 1556 |
|
| 1557 |
tryCatch({
|
| 1558 |
-
# Update threshold
|
| 1559 |
-
values$lod_threshold <- input$lod_threshold
|
| 1560 |
-
|
| 1561 |
-
# Get common samples
|
| 1562 |
common_samples <- intersect(rownames(values$genotype_data),
|
| 1563 |
rownames(values$phenotype_data))
|
| 1564 |
|
| 1565 |
if (length(common_samples) == 0) {
|
| 1566 |
-
showNotification("No common samples
|
| 1567 |
return()
|
| 1568 |
}
|
| 1569 |
|
| 1570 |
-
# Prepare data
|
| 1571 |
X <- values$genotype_data[common_samples, , drop = FALSE]
|
| 1572 |
y <- as.numeric(values$phenotype_data[common_samples, input$phenotype_column])
|
| 1573 |
|
| 1574 |
-
# Remove near-zero variance predictors
|
| 1575 |
nzv <- nearZeroVar(X)
|
| 1576 |
-
if (length(nzv) > 0)
|
| 1577 |
-
X <- X[, -nzv, drop = FALSE]
|
| 1578 |
-
}
|
| 1579 |
|
| 1580 |
-
# Split data
|
| 1581 |
set.seed(123)
|
| 1582 |
train_index <- createDataPartition(y, p = 1 - input$test_size, list = FALSE)
|
| 1583 |
|
|
@@ -1586,7 +1439,6 @@ server <- function(input, output, session) {
|
|
| 1586 |
y_train <- y[train_index]
|
| 1587 |
y_val <- y[-train_index]
|
| 1588 |
|
| 1589 |
-
# Train Random Forest model
|
| 1590 |
model <- train(
|
| 1591 |
x = X_train,
|
| 1592 |
y = y_train,
|
|
@@ -1598,7 +1450,6 @@ server <- function(input, output, session) {
|
|
| 1598 |
|
| 1599 |
values$model_fit <- model
|
| 1600 |
|
| 1601 |
-
# Get variable importance
|
| 1602 |
imp <- varImp(model, scale = FALSE)$importance
|
| 1603 |
importance_scores <- data.frame(
|
| 1604 |
Marker = rownames(imp),
|
|
@@ -1609,12 +1460,9 @@ server <- function(input, output, session) {
|
|
| 1609 |
)
|
| 1610 |
|
| 1611 |
values$importance_scores <- importance_scores
|
| 1612 |
-
|
| 1613 |
-
# Get significant QTLs
|
| 1614 |
lod_sig <- importance_scores[importance_scores$LOD > input$lod_threshold, , drop = FALSE]
|
| 1615 |
|
| 1616 |
if (nrow(lod_sig) > 0) {
|
| 1617 |
-
# Add flanking markers
|
| 1618 |
lod_sig$Low_Flank <- NA
|
| 1619 |
lod_sig$High_Flank <- NA
|
| 1620 |
|
|
@@ -1630,8 +1478,6 @@ server <- function(input, output, session) {
|
|
| 1630 |
}
|
| 1631 |
|
| 1632 |
values$lod_scores_train <- lod_sig
|
| 1633 |
-
|
| 1634 |
-
# Calculate QTL effects
|
| 1635 |
qtl_fx <- calculate_qtl_effects(X_train, y_train, lod_sig$Marker)
|
| 1636 |
|
| 1637 |
if (!is.null(qtl_fx)) {
|
|
@@ -1644,7 +1490,6 @@ server <- function(input, output, session) {
|
|
| 1644 |
values$qtl_effects_train <- data.frame(Message = paste("No QTLs above LOD", input$lod_threshold))
|
| 1645 |
}
|
| 1646 |
|
| 1647 |
-
# Calculate performance metrics
|
| 1648 |
y_train_pred <- predict(model, X_train)
|
| 1649 |
y_val_pred <- predict(model, X_val)
|
| 1650 |
|
|
@@ -1653,49 +1498,31 @@ server <- function(input, output, session) {
|
|
| 1653 |
|
| 1654 |
values$performance_metrics <- data.frame(
|
| 1655 |
Metric = c("R² (Train)", "R (Train)", "R² (Validation)", "R (Validation)"),
|
| 1656 |
-
Value = c(
|
| 1657 |
-
train_r2,
|
| 1658 |
-
cor(y_train, y_train_pred),
|
| 1659 |
-
val_r2,
|
| 1660 |
-
cor(y_val, y_val_pred)
|
| 1661 |
-
),
|
| 1662 |
stringsAsFactors = FALSE
|
| 1663 |
)
|
| 1664 |
|
| 1665 |
values$train_predictions <- data.frame(Observed = y_train, Predicted = y_train_pred)
|
| 1666 |
values$test_predictions <- data.frame(Observed = y_val, Predicted = y_val_pred)
|
| 1667 |
|
| 1668 |
-
#
|
| 1669 |
if (nrow(lod_sig) > 0) {
|
| 1670 |
sig_markers <- lod_sig$Marker[lod_sig$Marker %in% colnames(X_train)]
|
| 1671 |
all_markers <- colnames(X_train)
|
| 1672 |
-
|
| 1673 |
epistasis_list <- list()
|
| 1674 |
|
| 1675 |
withProgress(message = 'Calculating epistasis...', value = 0, {
|
| 1676 |
total <- length(sig_markers) * length(all_markers)
|
| 1677 |
-
count <- 0
|
| 1678 |
-
|
| 1679 |
for (m1 in sig_markers) {
|
| 1680 |
for (m2 in all_markers) {
|
| 1681 |
if (m1 == m2) next
|
| 1682 |
-
|
| 1683 |
-
count <- count + 1
|
| 1684 |
-
incProgress(1/total, detail = paste("Testing", m1, "x", m2))
|
| 1685 |
|
| 1686 |
tryCatch({
|
| 1687 |
-
data_epi <- data.frame(
|
| 1688 |
-
y = y_train,
|
| 1689 |
-
m1 = X_train[, m1],
|
| 1690 |
-
m2 = X_train[, m2]
|
| 1691 |
-
)
|
| 1692 |
-
|
| 1693 |
-
# Remove missing values
|
| 1694 |
data_epi <- na.omit(data_epi)
|
| 1695 |
-
|
| 1696 |
if (nrow(data_epi) < 10) next
|
| 1697 |
|
| 1698 |
-
# Fit model with interaction
|
| 1699 |
fit <- lm(y ~ m1 * m2, data = data_epi)
|
| 1700 |
coef_summary <- summary(fit)$coefficients
|
| 1701 |
|
|
@@ -1704,8 +1531,7 @@ server <- function(input, output, session) {
|
|
| 1704 |
effect <- coef(fit)["m1:m2"]
|
| 1705 |
|
| 1706 |
epistasis_list[[length(epistasis_list) + 1]] <- data.frame(
|
| 1707 |
-
QTL1 = m1,
|
| 1708 |
-
QTL2 = m2,
|
| 1709 |
Interaction_p = p_val,
|
| 1710 |
Effect_Size = effect,
|
| 1711 |
stringsAsFactors = FALSE
|
|
@@ -1721,40 +1547,25 @@ server <- function(input, output, session) {
|
|
| 1721 |
values$epistasis_all <- epistasis_all
|
| 1722 |
values$epistasis_sig <- epistasis_all[epistasis_all$Interaction_p < 0.05, ]
|
| 1723 |
} else {
|
| 1724 |
-
values$epistasis_all <- data.frame(Message = "No epistatic interactions
|
| 1725 |
-
values$epistasis_sig <- data.frame(Message = "No epistatic interactions
|
| 1726 |
}
|
| 1727 |
}
|
| 1728 |
|
| 1729 |
-
showNotification("QTL analysis completed
|
| 1730 |
|
| 1731 |
-
# Add to chat
|
| 1732 |
n_qtl <- if (!is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train)) nrow(values$qtl_effects_train) else 0
|
| 1733 |
-
val_r2 <- if (!is.null(values$performance_metrics)) round(values$performance_metrics$Value[values$performance_metrics$Metric == "R² (Validation)"], 3) else "N/A"
|
| 1734 |
-
|
| 1735 |
add_message("assistant", paste(
|
| 1736 |
"✅ QTL analysis complete!",
|
| 1737 |
-
paste0("• Found ", n_qtl, "
|
| 1738 |
-
paste0("•
|
| 1739 |
-
|
| 1740 |
-
"",
|
| 1741 |
-
"What would you like to know about your results? Try asking about PVE or top QTLs!",
|
| 1742 |
-
sep = "\n"
|
| 1743 |
))
|
| 1744 |
|
| 1745 |
-
# Switch to results tab
|
| 1746 |
updateTabsetPanel(session, "nav", selected = "Results")
|
| 1747 |
|
| 1748 |
}, error = function(e) {
|
| 1749 |
-
showNotification(paste("Error
|
| 1750 |
-
|
| 1751 |
-
# Add to chat
|
| 1752 |
-
add_message("assistant", paste(
|
| 1753 |
-
"❌ Error during analysis:",
|
| 1754 |
-
e$message,
|
| 1755 |
-
"Please check your data and try again.",
|
| 1756 |
-
sep = "\n"
|
| 1757 |
-
))
|
| 1758 |
})
|
| 1759 |
})
|
| 1760 |
|
|
@@ -1762,53 +1573,43 @@ server <- function(input, output, session) {
|
|
| 1762 |
# DOMESTICATION ANALYSIS
|
| 1763 |
# ============================================================
|
| 1764 |
|
| 1765 |
-
# Function to calculate selection metrics
|
| 1766 |
calculate_selection_metrics <- function(genotype_matrix, pop_data, marker_info) {
|
| 1767 |
metrics_list <- list()
|
| 1768 |
|
| 1769 |
for (marker in colnames(genotype_matrix)) {
|
| 1770 |
-
# Get genotype and population for this marker
|
| 1771 |
geno <- genotype_matrix[, marker]
|
| 1772 |
pop <- pop_data$population[match(rownames(genotype_matrix), pop_data$id)]
|
| 1773 |
-
|
| 1774 |
-
# Remove missing
|
| 1775 |
valid_idx <- !is.na(geno) & !is.na(pop)
|
| 1776 |
geno <- geno[valid_idx]
|
| 1777 |
pop <- pop[valid_idx]
|
| 1778 |
|
| 1779 |
if (length(unique(pop)) < 2) next
|
| 1780 |
|
| 1781 |
-
# Split by population
|
| 1782 |
geno_dom <- geno[pop == "Domesticated"]
|
| 1783 |
geno_wild <- geno[pop == "Wild"]
|
| 1784 |
|
| 1785 |
if (length(geno_dom) < 3 || length(geno_wild) < 3) next
|
| 1786 |
|
| 1787 |
-
# Calculate allele frequencies
|
| 1788 |
freq_dom <- mean(geno_dom, na.rm = TRUE) / 2
|
| 1789 |
freq_wild <- mean(geno_wild, na.rm = TRUE) / 2
|
| 1790 |
|
| 1791 |
-
# Calculate Fst
|
| 1792 |
p_avg <- (freq_dom + freq_wild) / 2
|
| 1793 |
if (p_avg > 0 && p_avg < 1) {
|
| 1794 |
fst <- (freq_dom - freq_wild)^2 / (p_avg * (1 - p_avg))
|
| 1795 |
-
fst <- fst / (1 + fst)
|
| 1796 |
} else {
|
| 1797 |
fst <- 0
|
| 1798 |
}
|
| 1799 |
|
| 1800 |
-
# Calculate nucleotide diversity (π)
|
| 1801 |
pi_dom <- 2 * freq_dom * (1 - freq_dom)
|
| 1802 |
pi_wild <- 2 * freq_wild * (1 - freq_wild)
|
| 1803 |
|
| 1804 |
-
# Simple Tajima's D approximation
|
| 1805 |
n_dom <- length(geno_dom)
|
| 1806 |
n_wild <- length(geno_wild)
|
| 1807 |
|
| 1808 |
tajima_d_dom <- (pi_dom - 1/n_dom) / sqrt(var(geno_dom)/n_dom)
|
| 1809 |
tajima_d_wild <- (pi_wild - 1/n_wild) / sqrt(var(geno_wild)/n_wild)
|
| 1810 |
|
| 1811 |
-
# Get chromosome and position
|
| 1812 |
marker_row <- marker_info[marker_info$Marker == marker, ]
|
| 1813 |
|
| 1814 |
metrics_list[[marker]] <- data.frame(
|
|
@@ -1828,26 +1629,20 @@ server <- function(input, output, session) {
|
|
| 1828 |
do.call(rbind, metrics_list)
|
| 1829 |
}
|
| 1830 |
|
| 1831 |
-
# Run domestication analysis
|
| 1832 |
observeEvent(input$run_domestication, {
|
| 1833 |
req(values$genotype_data, values$pop_data, values$all_markers)
|
| 1834 |
|
| 1835 |
-
showNotification("Running domestication analysis...", type = "message")
|
| 1836 |
-
|
| 1837 |
tryCatch({
|
| 1838 |
-
# Get common samples
|
| 1839 |
common_samples <- intersect(rownames(values$genotype_data), values$pop_data$id)
|
| 1840 |
|
| 1841 |
if (length(common_samples) == 0) {
|
| 1842 |
-
showNotification("No common samples
|
| 1843 |
return()
|
| 1844 |
}
|
| 1845 |
|
| 1846 |
-
# Subset data
|
| 1847 |
X <- values$genotype_data[common_samples, , drop = FALSE]
|
| 1848 |
pop_subset <- values$pop_data[values$pop_data$id %in% common_samples, ]
|
| 1849 |
|
| 1850 |
-
# Calculate metrics
|
| 1851 |
sel_metrics <- calculate_selection_metrics(X, pop_subset, values$all_markers)
|
| 1852 |
|
| 1853 |
if (is.null(sel_metrics)) {
|
|
@@ -1855,31 +1650,22 @@ server <- function(input, output, session) {
|
|
| 1855 |
return()
|
| 1856 |
}
|
| 1857 |
|
| 1858 |
-
# Add significance
|
| 1859 |
sel_metrics$Significant <-
|
| 1860 |
sel_metrics$Fst > input$fst_threshold |
|
| 1861 |
sel_metrics$Tajima_D_Dom < input$tajima_threshold |
|
| 1862 |
sel_metrics$Tajima_D_Wild < input$tajima_threshold
|
| 1863 |
|
| 1864 |
values$selection_metrics <- sel_metrics
|
| 1865 |
-
|
| 1866 |
showNotification("Domestication analysis completed!", type = "message")
|
| 1867 |
|
| 1868 |
-
# Add to chat
|
| 1869 |
n_sig <- sum(sel_metrics$Significant, na.rm = TRUE)
|
| 1870 |
-
top_fst <- sel_metrics[which.max(sel_metrics$Fst), ]
|
| 1871 |
-
|
| 1872 |
add_message("assistant", paste(
|
| 1873 |
"✅ Domestication analysis complete!",
|
| 1874 |
-
paste0("• Found ", n_sig, " markers with selection signatures")
|
| 1875 |
-
paste0("• Highest Fst: ", round(top_fst$Fst, 3), " at ", top_fst$Marker),
|
| 1876 |
-
"",
|
| 1877 |
-
"Check the Domestication tab for detailed results.",
|
| 1878 |
-
sep = "\n"
|
| 1879 |
))
|
| 1880 |
|
| 1881 |
}, error = function(e) {
|
| 1882 |
-
showNotification(paste("Error
|
| 1883 |
})
|
| 1884 |
})
|
| 1885 |
|
|
@@ -1891,19 +1677,15 @@ server <- function(input, output, session) {
|
|
| 1891 |
req(values$model_fit, values$test_genotype_data)
|
| 1892 |
|
| 1893 |
tryCatch({
|
| 1894 |
-
# Find common markers
|
| 1895 |
common_markers <- intersect(colnames(values$test_genotype_data),
|
| 1896 |
colnames(values$genotype_data))
|
| 1897 |
|
| 1898 |
if (length(common_markers) == 0) {
|
| 1899 |
-
showNotification("No common markers
|
| 1900 |
return()
|
| 1901 |
}
|
| 1902 |
|
| 1903 |
-
# Prepare test data
|
| 1904 |
X_test <- values$test_genotype_data[, common_markers, drop = FALSE]
|
| 1905 |
-
|
| 1906 |
-
# Make predictions
|
| 1907 |
predictions <- predict(values$model_fit, newdata = X_test)
|
| 1908 |
|
| 1909 |
values$predicted_test_phenotype_data <- data.frame(
|
|
@@ -1912,17 +1694,10 @@ server <- function(input, output, session) {
|
|
| 1912 |
stringsAsFactors = FALSE
|
| 1913 |
)
|
| 1914 |
|
| 1915 |
-
showNotification("
|
| 1916 |
-
|
| 1917 |
-
# Add to chat
|
| 1918 |
-
add_message("assistant", paste(
|
| 1919 |
-
"✅ Predicted phenotypes for", nrow(X_test), "test samples.",
|
| 1920 |
-
"You can download the predictions from the Data Upload tab.",
|
| 1921 |
-
sep = "\n"
|
| 1922 |
-
))
|
| 1923 |
|
| 1924 |
}, error = function(e) {
|
| 1925 |
-
showNotification(paste("Error
|
| 1926 |
})
|
| 1927 |
})
|
| 1928 |
|
|
@@ -1930,17 +1705,14 @@ server <- function(input, output, session) {
|
|
| 1930 |
# PLOTS
|
| 1931 |
# ============================================================
|
| 1932 |
|
| 1933 |
-
# Helper function for Manhattan plots
|
| 1934 |
create_manhattan <- function(data, y_col, title, threshold, y_label = y_col) {
|
| 1935 |
if (is.null(data) || nrow(data) == 0 || "Message" %in% colnames(data)) {
|
| 1936 |
return(plot_ly() %>% layout(title = "No data available"))
|
| 1937 |
}
|
| 1938 |
|
| 1939 |
-
# Prepare data
|
| 1940 |
plot_data <- data[!is.na(data[[y_col]]), ]
|
| 1941 |
if (nrow(plot_data) == 0) return(plot_ly() %>% layout(title = "No valid data"))
|
| 1942 |
|
| 1943 |
-
# Create chromosome positions
|
| 1944 |
chroms <- unique(plot_data$Chromosome)
|
| 1945 |
chrom_pos <- data.frame()
|
| 1946 |
|
|
@@ -1953,9 +1725,6 @@ server <- function(input, output, session) {
|
|
| 1953 |
}
|
| 1954 |
}
|
| 1955 |
|
| 1956 |
-
if (nrow(chrom_pos) == 0) return(plot_ly() %>% layout(title = "No valid data"))
|
| 1957 |
-
|
| 1958 |
-
# Create plot
|
| 1959 |
p <- plot_ly() %>%
|
| 1960 |
add_trace(
|
| 1961 |
data = chrom_pos,
|
|
@@ -1966,15 +1735,12 @@ server <- function(input, output, session) {
|
|
| 1966 |
color = ~factor(Chromosome),
|
| 1967 |
colors = viridis(length(chroms)),
|
| 1968 |
marker = list(size = 6, opacity = 0.7),
|
| 1969 |
-
text = ~paste("Marker:", Marker,
|
| 1970 |
-
"<br>Chr:", Chromosome,
|
| 1971 |
-
"<br>Pos:", Position,
|
| 1972 |
"<br>", y_label, ":", round(get(y_col), 3)),
|
| 1973 |
hoverinfo = 'text',
|
| 1974 |
showlegend = FALSE
|
| 1975 |
)
|
| 1976 |
|
| 1977 |
-
# Add threshold line
|
| 1978 |
if (!is.null(threshold) && !is.na(threshold)) {
|
| 1979 |
p <- p %>% add_segments(
|
| 1980 |
x = min(chrom_pos$PosScaled, na.rm = TRUE),
|
|
@@ -1982,41 +1748,33 @@ server <- function(input, output, session) {
|
|
| 1982 |
y = threshold,
|
| 1983 |
yend = threshold,
|
| 1984 |
line = list(color = 'red', dash = 'dash', width = 1),
|
| 1985 |
-
name = 'Threshold'
|
| 1986 |
-
showlegend = TRUE
|
| 1987 |
)
|
| 1988 |
}
|
| 1989 |
|
| 1990 |
-
# Layout
|
| 1991 |
p %>% layout(
|
| 1992 |
-
title =
|
| 1993 |
-
xaxis = list(
|
| 1994 |
-
|
| 1995 |
-
|
| 1996 |
-
|
| 1997 |
-
tickangle = 45
|
| 1998 |
-
),
|
| 1999 |
yaxis = list(title = y_label),
|
| 2000 |
-
hoverlabel = list(bgcolor = "#21262d"),
|
| 2001 |
plot_bgcolor = "#0d1117",
|
| 2002 |
paper_bgcolor = "#161b22",
|
| 2003 |
font = list(color = "#8b949e")
|
| 2004 |
)
|
| 2005 |
}
|
| 2006 |
|
| 2007 |
-
# LOD Manhattan plot
|
| 2008 |
output$lod_plot_2d <- renderPlotly({
|
| 2009 |
req(values$importance_scores)
|
| 2010 |
create_manhattan(values$importance_scores, "LOD", "QTL Manhattan Plot", input$lod_threshold, "LOD Score")
|
| 2011 |
})
|
| 2012 |
|
| 2013 |
-
# Fst Manhattan plot
|
| 2014 |
output$fst_plot <- renderPlotly({
|
| 2015 |
req(values$selection_metrics)
|
| 2016 |
create_manhattan(values$selection_metrics, "Fst", "Fst Manhattan Plot", input$fst_threshold, "Fst")
|
| 2017 |
})
|
| 2018 |
|
| 2019 |
-
# Tajima's D plot
|
| 2020 |
output$tajima_plot <- renderPlotly({
|
| 2021 |
req(values$selection_metrics)
|
| 2022 |
|
|
@@ -2025,8 +1783,6 @@ server <- function(input, output, session) {
|
|
| 2025 |
}
|
| 2026 |
|
| 2027 |
data <- values$selection_metrics
|
| 2028 |
-
|
| 2029 |
-
# Prepare data
|
| 2030 |
chroms <- unique(data$Chromosome)
|
| 2031 |
chrom_pos <- data.frame()
|
| 2032 |
|
|
@@ -2048,7 +1804,7 @@ server <- function(input, output, session) {
|
|
| 2048 |
mode = 'markers',
|
| 2049 |
name = 'Domesticated',
|
| 2050 |
marker = list(size = 5, color = '#58a6ff', opacity = 0.7),
|
| 2051 |
-
text = ~paste("Marker:", Marker, "<br>
|
| 2052 |
hoverinfo = 'text'
|
| 2053 |
) %>%
|
| 2054 |
add_trace(
|
|
@@ -2059,7 +1815,7 @@ server <- function(input, output, session) {
|
|
| 2059 |
mode = 'markers',
|
| 2060 |
name = 'Wild',
|
| 2061 |
marker = list(size = 5, color = '#f97316', opacity = 0.7),
|
| 2062 |
-
text = ~paste("Marker:", Marker, "<br>
|
| 2063 |
hoverinfo = 'text'
|
| 2064 |
) %>%
|
| 2065 |
add_segments(
|
|
@@ -2067,26 +1823,21 @@ server <- function(input, output, session) {
|
|
| 2067 |
xend = max(chrom_pos$PosScaled, na.rm = TRUE),
|
| 2068 |
y = input$tajima_threshold,
|
| 2069 |
yend = input$tajima_threshold,
|
| 2070 |
-
line = list(color = 'red', dash = 'dash', width = 1)
|
| 2071 |
-
name = 'Threshold'
|
| 2072 |
) %>%
|
| 2073 |
layout(
|
| 2074 |
title = "Tajima's D Manhattan Plot",
|
| 2075 |
-
xaxis = list(
|
| 2076 |
-
|
| 2077 |
-
|
| 2078 |
-
|
| 2079 |
-
tickangle = 45
|
| 2080 |
-
),
|
| 2081 |
yaxis = list(title = "Tajima's D"),
|
| 2082 |
-
hoverlabel = list(bgcolor = "#21262d"),
|
| 2083 |
plot_bgcolor = "#0d1117",
|
| 2084 |
paper_bgcolor = "#161b22",
|
| 2085 |
font = list(color = "#8b949e")
|
| 2086 |
)
|
| 2087 |
})
|
| 2088 |
|
| 2089 |
-
# Performance plot
|
| 2090 |
output$performance_plot <- renderPlotly({
|
| 2091 |
req(values$performance_metrics)
|
| 2092 |
|
|
@@ -2095,15 +1846,12 @@ server <- function(input, output, session) {
|
|
| 2095 |
x = ~Metric,
|
| 2096 |
y = ~Value,
|
| 2097 |
type = 'bar',
|
| 2098 |
-
marker = list(
|
| 2099 |
-
color = c('#58a6ff', '#58a6ff', '#3fb950', '#3fb950'),
|
| 2100 |
-
line = list(color = '#ffffff', width = 1)
|
| 2101 |
-
),
|
| 2102 |
text = ~round(Value, 3),
|
| 2103 |
textposition = 'outside'
|
| 2104 |
) %>%
|
| 2105 |
layout(
|
| 2106 |
-
title = "Model Performance
|
| 2107 |
yaxis = list(title = "Value", range = c(0, 1.1)),
|
| 2108 |
plot_bgcolor = "#0d1117",
|
| 2109 |
paper_bgcolor = "#161b22",
|
|
@@ -2111,26 +1859,19 @@ server <- function(input, output, session) {
|
|
| 2111 |
)
|
| 2112 |
})
|
| 2113 |
|
| 2114 |
-
# Regression plots
|
| 2115 |
output$regression_plot_train <- renderPlotly({
|
| 2116 |
req(values$train_predictions)
|
| 2117 |
-
|
| 2118 |
plot_ly(
|
| 2119 |
data = values$train_predictions,
|
| 2120 |
-
x = ~Observed,
|
| 2121 |
-
|
| 2122 |
-
type = 'scatter',
|
| 2123 |
-
mode = 'markers',
|
| 2124 |
marker = list(size = 6, color = '#58a6ff', opacity = 0.7)
|
| 2125 |
) %>%
|
| 2126 |
add_trace(
|
| 2127 |
x = range(values$train_predictions$Observed),
|
| 2128 |
y = range(values$train_predictions$Observed),
|
| 2129 |
-
type = 'scatter',
|
| 2130 |
-
|
| 2131 |
-
line = list(color = '#f85149', dash = 'dash'),
|
| 2132 |
-
name = '1:1 line',
|
| 2133 |
-
showlegend = FALSE
|
| 2134 |
) %>%
|
| 2135 |
layout(
|
| 2136 |
title = "Training Set",
|
|
@@ -2144,23 +1885,17 @@ server <- function(input, output, session) {
|
|
| 2144 |
|
| 2145 |
output$regression_plot_test <- renderPlotly({
|
| 2146 |
req(values$test_predictions)
|
| 2147 |
-
|
| 2148 |
plot_ly(
|
| 2149 |
data = values$test_predictions,
|
| 2150 |
-
x = ~Observed,
|
| 2151 |
-
|
| 2152 |
-
type = 'scatter',
|
| 2153 |
-
mode = 'markers',
|
| 2154 |
marker = list(size = 6, color = '#3fb950', opacity = 0.7)
|
| 2155 |
) %>%
|
| 2156 |
add_trace(
|
| 2157 |
x = range(values$test_predictions$Observed),
|
| 2158 |
y = range(values$test_predictions$Observed),
|
| 2159 |
-
type = 'scatter',
|
| 2160 |
-
|
| 2161 |
-
line = list(color = '#f85149', dash = 'dash'),
|
| 2162 |
-
name = '1:1 line',
|
| 2163 |
-
showlegend = FALSE
|
| 2164 |
) %>%
|
| 2165 |
layout(
|
| 2166 |
title = "Validation Set",
|
|
@@ -2172,7 +1907,6 @@ server <- function(input, output, session) {
|
|
| 2172 |
)
|
| 2173 |
})
|
| 2174 |
|
| 2175 |
-
# Epistasis heatmap
|
| 2176 |
output$epistasis_heatmap <- renderPlotly({
|
| 2177 |
req(values$epistasis_all)
|
| 2178 |
|
|
@@ -2180,7 +1914,6 @@ server <- function(input, output, session) {
|
|
| 2180 |
return(plot_ly() %>% layout(title = values$epistasis_all$Message[1]))
|
| 2181 |
}
|
| 2182 |
|
| 2183 |
-
# Create matrix for heatmap
|
| 2184 |
qtls <- unique(values$epistasis_all$QTL1)
|
| 2185 |
markers <- unique(values$epistasis_all$QTL2)
|
| 2186 |
|
|
@@ -2194,15 +1927,12 @@ server <- function(input, output, session) {
|
|
| 2194 |
}
|
| 2195 |
|
| 2196 |
plot_ly(
|
| 2197 |
-
x = colnames(p_matrix),
|
| 2198 |
-
|
| 2199 |
-
|
| 2200 |
-
type = "heatmap",
|
| 2201 |
-
colorscale = "Viridis",
|
| 2202 |
-
hovertemplate = "QTL: %{y}<br>Marker: %{x}<br>-log10(p): %{z:.2f}<extra></extra>"
|
| 2203 |
) %>%
|
| 2204 |
layout(
|
| 2205 |
-
title = "Epistatic Interactions
|
| 2206 |
xaxis = list(title = "Marker", tickangle = 45),
|
| 2207 |
yaxis = list(title = "QTL"),
|
| 2208 |
plot_bgcolor = "#0d1117",
|
|
@@ -2223,27 +1953,16 @@ server <- function(input, output, session) {
|
|
| 2223 |
options = list(dom = 't')))
|
| 2224 |
}
|
| 2225 |
|
| 2226 |
-
# Select columns to display
|
| 2227 |
display_cols <- intersect(
|
| 2228 |
c("Marker", "Chromosome", "Position", "LOD", "Additive_Effect",
|
| 2229 |
-
"
|
| 2230 |
colnames(values$qtl_effects_train)
|
| 2231 |
)
|
| 2232 |
|
| 2233 |
df <- values$qtl_effects_train[order(-values$qtl_effects_train$LOD), display_cols]
|
| 2234 |
|
| 2235 |
-
datatable(
|
| 2236 |
-
df,
|
| 2237 |
-
options = list(
|
| 2238 |
-
pageLength = 10,
|
| 2239 |
-
scrollX = TRUE,
|
| 2240 |
-
dom = 'Bfrtip',
|
| 2241 |
-
buttons = c('copy', 'csv', 'excel')
|
| 2242 |
-
),
|
| 2243 |
-
rownames = FALSE,
|
| 2244 |
-
class = 'cell-border stripe'
|
| 2245 |
-
) %>%
|
| 2246 |
-
formatRound(columns = intersect(c("LOD", "Additive_Effect", "PVE_Percent"), colnames(df)), digits = 3)
|
| 2247 |
})
|
| 2248 |
|
| 2249 |
output$epistasis_table <- renderDT({
|
|
@@ -2256,11 +1975,7 @@ server <- function(input, output, session) {
|
|
| 2256 |
|
| 2257 |
datatable(
|
| 2258 |
values$epistasis_sig[order(values$epistasis_sig$Interaction_p), ],
|
| 2259 |
-
options = list(
|
| 2260 |
-
pageLength = 10,
|
| 2261 |
-
scrollX = TRUE,
|
| 2262 |
-
dom = 'Bfrtip'
|
| 2263 |
-
),
|
| 2264 |
rownames = FALSE
|
| 2265 |
) %>%
|
| 2266 |
formatSignif(columns = c("Interaction_p", "Effect_Size"), digits = 4)
|
|
@@ -2274,29 +1989,20 @@ server <- function(input, output, session) {
|
|
| 2274 |
options = list(dom = 't')))
|
| 2275 |
}
|
| 2276 |
|
| 2277 |
-
# Add QTL overlap column
|
| 2278 |
df <- values$selection_metrics
|
| 2279 |
if (!is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train)) {
|
| 2280 |
df$QTL_Overlap <- df$Marker %in% values$qtl_effects_train$Marker
|
| 2281 |
}
|
| 2282 |
|
| 2283 |
display_cols <- intersect(
|
| 2284 |
-
c("Marker", "Chromosome", "
|
| 2285 |
-
"Tajima_D_Dom", "Tajima_D_Wild", "Significant", "QTL_Overlap"),
|
| 2286 |
colnames(df)
|
| 2287 |
)
|
| 2288 |
|
| 2289 |
-
datatable(
|
| 2290 |
-
|
| 2291 |
-
|
| 2292 |
-
|
| 2293 |
-
scrollX = TRUE,
|
| 2294 |
-
dom = 'Bfrtip'
|
| 2295 |
-
),
|
| 2296 |
-
rownames = FALSE
|
| 2297 |
-
) %>%
|
| 2298 |
-
formatRound(columns = intersect(c("Fst", "Pi_Dom", "Pi_Wild", "Tajima_D_Dom", "Tajima_D_Wild"),
|
| 2299 |
-
colnames(df)), digits = 3)
|
| 2300 |
})
|
| 2301 |
|
| 2302 |
# ============================================================
|
|
@@ -2310,28 +2016,21 @@ server <- function(input, output, session) {
|
|
| 2310 |
return(div(class = "alert alert-info", values$lod_scores_train$Message[1]))
|
| 2311 |
}
|
| 2312 |
|
| 2313 |
-
# Get chromosomes with QTLs
|
| 2314 |
chromosomes <- unique(values$lod_scores_train$Chromosome)
|
| 2315 |
|
| 2316 |
tagList(
|
| 2317 |
lapply(chromosomes, function(chr) {
|
| 2318 |
-
# Get markers on this chromosome
|
| 2319 |
chr_markers <- values$all_markers[values$all_markers$Chromosome == chr, ]
|
| 2320 |
chr_markers <- chr_markers[order(chr_markers$Position), ]
|
| 2321 |
-
|
| 2322 |
-
# Get QTLs on this chromosome
|
| 2323 |
chr_qtls <- values$lod_scores_train[values$lod_scores_train$Chromosome == chr, ]
|
| 2324 |
|
| 2325 |
-
# Get selection markers on this chromosome
|
| 2326 |
sel_markers <- NULL
|
| 2327 |
if (!is.null(values$selection_metrics) && !"Message" %in% colnames(values$selection_metrics)) {
|
| 2328 |
sel_markers <- values$selection_metrics[
|
| 2329 |
-
values$selection_metrics$Chromosome == chr &
|
| 2330 |
-
values$selection_metrics$Significant,
|
| 2331 |
]
|
| 2332 |
}
|
| 2333 |
|
| 2334 |
-
# Calculate positions
|
| 2335 |
min_pos <- min(chr_markers$Position, na.rm = TRUE)
|
| 2336 |
max_pos <- max(chr_markers$Position, na.rm = TRUE)
|
| 2337 |
range_pos <- max_pos - min_pos
|
|
@@ -2339,16 +2038,11 @@ server <- function(input, output, session) {
|
|
| 2339 |
div(class = "chromosome-container",
|
| 2340 |
div(class = "chromosome-title", paste("Chromosome", chr)),
|
| 2341 |
div(class = "chromosome",
|
| 2342 |
-
# Add all markers as subtle background
|
| 2343 |
lapply(1:nrow(chr_markers), function(i) {
|
| 2344 |
marker <- chr_markers[i, ]
|
| 2345 |
-
left <- if (range_pos > 0)
|
| 2346 |
-
|
| 2347 |
-
} else {
|
| 2348 |
-
(i / nrow(chr_markers)) * 100
|
| 2349 |
-
}
|
| 2350 |
|
| 2351 |
-
# Determine marker class
|
| 2352 |
marker_class <- "chromosome-marker"
|
| 2353 |
if (marker$Marker %in% chr_qtls$Marker) {
|
| 2354 |
marker_class <- paste(marker_class, "significant")
|
|
@@ -2358,11 +2052,7 @@ server <- function(input, output, session) {
|
|
| 2358 |
marker_class <- paste(marker_class, "flanking")
|
| 2359 |
}
|
| 2360 |
|
| 2361 |
-
div(
|
| 2362 |
-
class = marker_class,
|
| 2363 |
-
style = paste0("left: ", left, "%;"),
|
| 2364 |
-
`data-marker` = marker$Marker
|
| 2365 |
-
)
|
| 2366 |
})
|
| 2367 |
),
|
| 2368 |
div(class = "chromosome-legend",
|
|
@@ -2374,7 +2064,10 @@ server <- function(input, output, session) {
|
|
| 2374 |
)
|
| 2375 |
})
|
| 2376 |
|
| 2377 |
-
#
|
|
|
|
|
|
|
|
|
|
| 2378 |
observeEvent(input$simulate_btn, {
|
| 2379 |
session$sendCustomMessage("simulateQTLDiscovery", list())
|
| 2380 |
})
|
|
@@ -2402,11 +2095,10 @@ server <- function(input, output, session) {
|
|
| 2402 |
div(class = "interpretation-section",
|
| 2403 |
tags$h5("Analysis Summary"),
|
| 2404 |
tags$p(paste(
|
| 2405 |
-
"
|
| 2406 |
-
if (has_perf) paste0("
|
| 2407 |
-
if (has_epi)
|
| 2408 |
-
if (has_sel)
|
| 2409 |
-
sep = " "
|
| 2410 |
))
|
| 2411 |
)
|
| 2412 |
})
|
|
@@ -2415,24 +2107,17 @@ server <- function(input, output, session) {
|
|
| 2415 |
if (is.null(values$qtl_effects_train) || "Message" %in% colnames(values$qtl_effects_train)) {
|
| 2416 |
return(div(class = "interpretation-section",
|
| 2417 |
tags$h5("QTL Significance"),
|
| 2418 |
-
tags$p("No significant QTLs detected.
|
| 2419 |
))
|
| 2420 |
}
|
| 2421 |
|
| 2422 |
top_qtl <- values$qtl_effects_train[which.max(values$qtl_effects_train$LOD), ]
|
| 2423 |
-
sig_count <- sum(values$qtl_effects_train$LOD >= 5)
|
| 2424 |
-
sug_count <- sum(values$qtl_effects_train$LOD >= 3 & values$qtl_effects_train$LOD < 5)
|
| 2425 |
|
| 2426 |
div(class = "interpretation-section",
|
| 2427 |
tags$h5("QTL Significance"),
|
| 2428 |
tags$p(paste(
|
| 2429 |
-
"Top QTL:", top_qtl$Marker, "
|
| 2430 |
-
"with LOD =", round(top_qtl$LOD, 2)
|
| 2431 |
-
if (top_qtl$LOD >= 5) "This is a highly significant QTL."
|
| 2432 |
-
else if (top_qtl$LOD >= 3) "This is a suggestive QTL."
|
| 2433 |
-
else "This is below standard significance thresholds.",
|
| 2434 |
-
paste0("Overall, you have ", sig_count, " significant (LOD≥5) and ",
|
| 2435 |
-
sug_count, " suggestive (LOD 3-5) QTLs.")
|
| 2436 |
))
|
| 2437 |
)
|
| 2438 |
})
|
|
@@ -2446,18 +2131,12 @@ server <- function(input, output, session) {
|
|
| 2446 |
}
|
| 2447 |
|
| 2448 |
top_pve <- values$qtl_effects_train[which.max(values$qtl_effects_train$PVE_Percent), ]
|
| 2449 |
-
top_add <- values$qtl_effects_train[which.max(abs(values$qtl_effects_train$Additive_Effect)), ]
|
| 2450 |
|
| 2451 |
div(class = "interpretation-section",
|
| 2452 |
tags$h5("Effect Sizes"),
|
| 2453 |
-
tags$p(
|
| 2454 |
-
"
|
| 2455 |
-
round(top_pve$PVE_Percent, 1), "% of
|
| 2456 |
-
if (top_pve$PVE_Percent > 10) "This is a major-effect QTL suitable for marker-assisted selection."
|
| 2457 |
-
else if (top_pve$PVE_Percent > 5) "This is a moderate-effect QTL."
|
| 2458 |
-
else "This is a minor-effect QTL, typical for polygenic traits.",
|
| 2459 |
-
" The largest additive effect is ", round(top_add$Additive_Effect, 3),
|
| 2460 |
-
" at ", top_add$Marker, "."
|
| 2461 |
))
|
| 2462 |
)
|
| 2463 |
})
|
|
@@ -2475,69 +2154,34 @@ server <- function(input, output, session) {
|
|
| 2475 |
|
| 2476 |
div(class = "interpretation-section",
|
| 2477 |
tags$h5("Epistasis"),
|
| 2478 |
-
tags$p(
|
| 2479 |
-
"Detected
|
| 2480 |
-
|
| 2481 |
-
"
|
| 2482 |
-
"This suggests non-additive genetic effects that could be important for trait expression."
|
| 2483 |
))
|
| 2484 |
)
|
| 2485 |
})
|
| 2486 |
|
| 2487 |
output$recommendations <- renderUI({
|
| 2488 |
has_qtl <- !is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train)
|
| 2489 |
-
has_epi <- !is.null(values$epistasis_sig) && !"Message" %in% colnames(values$epistasis_sig) && nrow(values$epistasis_sig) > 0
|
| 2490 |
-
has_sel <- !is.null(values$selection_metrics) && !"Message" %in% colnames(values$selection_metrics)
|
| 2491 |
-
has_perf <- !is.null(values$performance_metrics)
|
| 2492 |
-
|
| 2493 |
-
recs <- character()
|
| 2494 |
|
| 2495 |
-
if (has_qtl) {
|
| 2496 |
-
|
| 2497 |
-
|
| 2498 |
-
|
| 2499 |
-
|
| 2500 |
-
recs <- c(recs, paste("• **Investigate** epistatic interactions in breeding programs"))
|
| 2501 |
-
}
|
| 2502 |
-
|
| 2503 |
-
if (has_sel) {
|
| 2504 |
-
overlap <- values$selection_metrics$Marker[
|
| 2505 |
-
values$selection_metrics$Marker %in% values$qtl_effects_train$Marker &
|
| 2506 |
-
values$selection_metrics$Significant
|
| 2507 |
-
]
|
| 2508 |
-
if (length(overlap) > 0) {
|
| 2509 |
-
recs <- c(recs, paste("• **QTLs under selection**:", paste(overlap, collapse = ", ")))
|
| 2510 |
-
}
|
| 2511 |
-
}
|
| 2512 |
-
|
| 2513 |
-
if (has_perf) {
|
| 2514 |
-
val_r2 <- values$performance_metrics$Value[values$performance_metrics$Metric == "R² (Validation)"]
|
| 2515 |
-
if (val_r2 < 0.2) {
|
| 2516 |
-
recs <- c(recs, "• **Consider** increasing sample size or reducing marker number")
|
| 2517 |
-
}
|
| 2518 |
-
}
|
| 2519 |
-
|
| 2520 |
-
# Add general recommendations
|
| 2521 |
-
recs <- c(recs,
|
| 2522 |
-
"• **Validate** QTLs in independent populations",
|
| 2523 |
-
"• **Use** flanking markers for marker-assisted selection",
|
| 2524 |
-
"• **Consider** multi-locus models for prediction"
|
| 2525 |
)
|
| 2526 |
} else {
|
| 2527 |
-
|
| 2528 |
-
"•
|
| 2529 |
-
"•
|
| 2530 |
-
"•
|
| 2531 |
-
"• **Check** data quality and format"
|
| 2532 |
)
|
| 2533 |
}
|
| 2534 |
|
| 2535 |
div(class = "interpretation-section",
|
| 2536 |
tags$h5("Recommendations"),
|
| 2537 |
-
tags$ul(
|
| 2538 |
-
lapply(recs, function(r) tags$li(HTML(r))),
|
| 2539 |
-
style = "color: #8b949e; line-height: 1.8;"
|
| 2540 |
-
)
|
| 2541 |
)
|
| 2542 |
})
|
| 2543 |
|
|
@@ -2546,37 +2190,26 @@ server <- function(input, output, session) {
|
|
| 2546 |
# ============================================================
|
| 2547 |
|
| 2548 |
output$download_train_results <- downloadHandler(
|
| 2549 |
-
filename = function()
|
| 2550 |
-
paste0("qtl_results_train_", Sys.Date(), ".xlsx")
|
| 2551 |
-
},
|
| 2552 |
content = function(file) {
|
| 2553 |
sheets <- list()
|
| 2554 |
-
|
| 2555 |
if (!is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train)) {
|
| 2556 |
-
sheets[["
|
| 2557 |
}
|
| 2558 |
-
|
| 2559 |
if (!is.null(values$performance_metrics)) {
|
| 2560 |
sheets[["Performance"]] <- values$performance_metrics
|
| 2561 |
}
|
| 2562 |
-
|
| 2563 |
-
if (!is.null(values$epistasis_sig) && !"Message" %in% colnames(values$epistasis_sig)) {
|
| 2564 |
-
sheets[["Epistasis"]] <- values$epistasis_sig
|
| 2565 |
-
}
|
| 2566 |
-
|
| 2567 |
write_xlsx(sheets, file)
|
| 2568 |
}
|
| 2569 |
)
|
| 2570 |
|
| 2571 |
output$download_selection <- downloadHandler(
|
| 2572 |
-
filename = function()
|
| 2573 |
-
paste0("selection_results_", Sys.Date(), ".xlsx")
|
| 2574 |
-
},
|
| 2575 |
content = function(file) {
|
| 2576 |
if (!is.null(values$selection_metrics) && !"Message" %in% colnames(values$selection_metrics)) {
|
| 2577 |
-
write_xlsx(list(
|
| 2578 |
} else {
|
| 2579 |
-
write_xlsx(list(Message = "No
|
| 2580 |
}
|
| 2581 |
}
|
| 2582 |
)
|
|
|
|
| 1 |
# ============================================================
|
| 2 |
+
# QTL-Mapper - Complete Fixed Version with Transformer AI
|
| 3 |
# ============================================================
|
| 4 |
|
| 5 |
# Package installation for Hugging Face
|
|
|
|
| 9 |
required_packages <- c(
|
| 10 |
"shiny", "randomForest", "caret", "DT", "ggplot2", "plotly",
|
| 11 |
"writexl", "viridis", "reshape2", "dplyr", "httr", "jsonlite",
|
| 12 |
+
"shinyjs", "markdown"
|
| 13 |
)
|
| 14 |
|
| 15 |
for (pkg in required_packages) {
|
|
|
|
| 19 |
}
|
| 20 |
}
|
| 21 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
# ============================================================
|
| 23 |
+
# TRANSFORMER-BASED LLM SYSTEM - FIXED VERSION
|
| 24 |
# ============================================================
|
| 25 |
|
| 26 |
+
# Configuration - Load token from environment variable
|
| 27 |
HF_API_TOKEN <- Sys.getenv("HF_API_TOKEN")
|
| 28 |
use_hf_api <- HF_API_TOKEN != ""
|
| 29 |
|
| 30 |
+
# Using FLAN-T5 which is more reliable for instruction following
|
| 31 |
+
hf_model <- "google/flan-t5-large" # Good for Q&A tasks
|
| 32 |
+
# Alternative models if needed:
|
| 33 |
+
# hf_model <- "microsoft/phi-2"
|
| 34 |
# hf_model <- "mistralai/Mistral-7B-Instruct-v0.2"
|
|
|
|
| 35 |
|
| 36 |
HF_API_URL <- paste0("https://api-inference.huggingface.co/models/", hf_model)
|
| 37 |
|
| 38 |
+
# Function to query Hugging Face API
|
| 39 |
query_hf_api <- function(prompt, max_length = 500, temperature = 0.7) {
|
| 40 |
if (HF_API_TOKEN == "") {
|
| 41 |
return(list(success = FALSE, error = "HF_API_TOKEN not set"))
|
|
|
|
| 43 |
|
| 44 |
# Format prompt for better responses
|
| 45 |
formatted_prompt <- paste0(
|
| 46 |
+
"You are an expert bioinformatics assistant specializing in QTL analysis.\n\n",
|
| 47 |
+
"Based on this data:\n", prompt, "\n\n",
|
| 48 |
+
"Answer the question accurately and concisely. Be specific about the results shown."
|
| 49 |
)
|
| 50 |
|
| 51 |
tryCatch({
|
|
|
|
| 62 |
temperature = temperature,
|
| 63 |
do_sample = TRUE,
|
| 64 |
top_p = 0.95,
|
|
|
|
|
|
|
| 65 |
return_full_text = FALSE
|
| 66 |
)
|
| 67 |
), auto_unbox = TRUE),
|
|
|
|
| 69 |
timeout(60)
|
| 70 |
)
|
| 71 |
|
| 72 |
+
status <- status_code(response)
|
| 73 |
+
|
| 74 |
+
if (status == 200) {
|
| 75 |
result <- content(response, as = "parsed", encoding = "UTF-8")
|
| 76 |
|
| 77 |
# Handle different response formats
|
|
|
|
| 81 |
} else if (length(result) > 0 && !is.null(result[[1]]$generated_text)) {
|
| 82 |
return(list(success = TRUE, text = result[[1]]$generated_text))
|
| 83 |
} else {
|
|
|
|
| 84 |
return(list(success = TRUE, text = as.character(result)))
|
| 85 |
}
|
| 86 |
} else {
|
| 87 |
return(list(success = TRUE, text = as.character(result)))
|
| 88 |
}
|
| 89 |
+
} else if (status == 503) {
|
| 90 |
+
return(list(success = FALSE, error = "Model is loading, please wait...", loading = TRUE))
|
|
|
|
| 91 |
} else {
|
| 92 |
error_content <- tryCatch({
|
| 93 |
content(response, "text", encoding = "UTF-8")
|
| 94 |
}, error = function(e) {
|
| 95 |
+
paste("Status:", status)
|
| 96 |
})
|
| 97 |
|
| 98 |
return(list(
|
| 99 |
success = FALSE,
|
| 100 |
+
error = paste("API error:", status, "-", substr(error_content, 1, 200))
|
| 101 |
))
|
| 102 |
}
|
| 103 |
}, error = function(e) {
|
|
|
|
| 110 |
# ============================================================
|
| 111 |
|
| 112 |
build_system_prompt <- function(rv) {
|
| 113 |
+
context_parts <- c("CURRENT ANALYSIS RESULTS:")
|
|
|
|
|
|
|
|
|
|
| 114 |
|
| 115 |
# Add QTL results
|
| 116 |
if (!is.null(rv$qtl_effects_train) && !"Message" %in% colnames(rv$qtl_effects_train)) {
|
| 117 |
n_qtl <- nrow(rv$qtl_effects_train)
|
|
|
|
| 118 |
total_pve <- sum(rv$qtl_effects_train$PVE_Percent, na.rm = TRUE)
|
| 119 |
|
| 120 |
+
context_parts <- c(context_parts,
|
| 121 |
+
sprintf("\nQTL Results: %d significant QTLs detected above LOD %.1f.",
|
| 122 |
+
n_qtl, rv$lod_threshold))
|
| 123 |
+
context_parts <- c(context_parts,
|
| 124 |
+
sprintf("Total variance explained by QTLs: %.1f%%.", total_pve))
|
| 125 |
+
|
| 126 |
+
# Add top 3 QTLs
|
| 127 |
+
top_qtls <- head(rv$qtl_effects_train[order(-rv$qtl_effects_train$LOD), ], 3)
|
| 128 |
+
context_parts <- c(context_parts, "\nTop QTLs:")
|
| 129 |
+
for (i in 1:nrow(top_qtls)) {
|
| 130 |
+
row <- top_qtls[i, ]
|
| 131 |
+
context_parts <- c(context_parts,
|
| 132 |
+
sprintf(" %d. %s (Chr %s): LOD=%.2f, PVE=%.1f%%, Additive=%.3f",
|
| 133 |
+
i, row$Marker, row$Chromosome, row$LOD, row$PVE_Percent, row$Additive_Effect))
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
}
|
| 135 |
}
|
| 136 |
|
| 137 |
# Add performance metrics
|
| 138 |
if (!is.null(rv$performance_metrics)) {
|
| 139 |
pm <- rv$performance_metrics
|
| 140 |
+
train_r2 <- pm$Value[pm$Metric == "R² (Train)"]
|
| 141 |
+
val_r2 <- pm$Value[pm$Metric == "R² (Validation)"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 142 |
|
| 143 |
+
context_parts <- c(context_parts,
|
| 144 |
+
sprintf("\nModel Performance:"),
|
| 145 |
+
sprintf(" Training R²: %.3f", train_r2),
|
| 146 |
+
sprintf(" Validation R²: %.3f", val_r2))
|
| 147 |
}
|
| 148 |
|
| 149 |
# Add epistasis results
|
| 150 |
if (!is.null(rv$epistasis_sig) && !"Message" %in% colnames(rv$epistasis_sig) && nrow(rv$epistasis_sig) > 0) {
|
| 151 |
n_epi <- nrow(rv$epistasis_sig)
|
| 152 |
+
context_parts <- c(context_parts,
|
| 153 |
+
sprintf("\nEpistasis: %d significant pairwise interactions detected.", n_epi))
|
| 154 |
|
| 155 |
+
top_epi <- rv$epistasis_sig[order(rv$epistasis_sig$Interaction_p), ][1, ]
|
| 156 |
+
context_parts <- c(context_parts,
|
| 157 |
+
sprintf(" Strongest: %s × %s (p=%.4f)", top_epi$QTL1, top_epi$QTL2, top_epi$Interaction_p))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
}
|
| 159 |
|
| 160 |
# Add domestication results
|
| 161 |
if (!is.null(rv$selection_metrics) && !"Message" %in% colnames(rv$selection_metrics)) {
|
| 162 |
n_sig <- sum(rv$selection_metrics$Significant, na.rm = TRUE)
|
| 163 |
+
context_parts <- c(context_parts,
|
| 164 |
+
sprintf("\nDomestication: %d markers with selection signatures.", n_sig))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 165 |
}
|
| 166 |
|
| 167 |
+
paste(context_parts, collapse = "\n")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 168 |
}
|
| 169 |
|
| 170 |
# ============================================================
|
| 171 |
+
# ENHANCED RULE-BASED RESPONSES
|
| 172 |
# ============================================================
|
| 173 |
|
| 174 |
enhanced_rule_response <- function(user_message, rv) {
|
|
|
|
| 181 |
has_sel <- !is.null(rv$selection_metrics) && !"Message" %in% colnames(rv$selection_metrics)
|
| 182 |
|
| 183 |
# PVE-specific questions
|
| 184 |
+
if (grepl("pve|variance explained|how much variance|percent variance|what is pve", q)) {
|
| 185 |
if (has_qtl) {
|
| 186 |
df <- rv$qtl_effects_train
|
| 187 |
total_pve <- sum(df$PVE_Percent, na.rm = TRUE)
|
|
|
|
| 189 |
|
| 190 |
response <- paste0(
|
| 191 |
"📊 **PVE (Phenotypic Variance Explained) Analysis**\n\n",
|
| 192 |
+
"**Your Results:**\n",
|
| 193 |
+
"• Total variance explained by all QTLs: **", round(total_pve, 1), "%**\n",
|
| 194 |
+
"• Number of QTLs detected: **", nrow(df), "**\n\n",
|
| 195 |
"**Top QTL by PVE:**\n",
|
| 196 |
+
"• Marker: **", top_pve$Marker, "**\n",
|
| 197 |
"• Chromosome: ", top_pve$Chromosome, "\n",
|
| 198 |
+
"• PVE: **", round(top_pve$PVE_Percent, 1), "%**\n",
|
| 199 |
"• LOD: ", round(top_pve$LOD, 2), "\n\n"
|
| 200 |
)
|
| 201 |
|
| 202 |
if (top_pve$PVE_Percent > 10) {
|
| 203 |
+
response <- paste0(response, "💡 This is a **major-effect QTL** (>10% PVE) - excellent candidate for marker-assisted selection.\n\n")
|
| 204 |
} else if (top_pve$PVE_Percent > 5) {
|
| 205 |
+
response <- paste0(response, "💡 This is a **moderate-effect QTL** (5-10% PVE) - useful for polygenic breeding approaches.\n\n")
|
| 206 |
} else {
|
| 207 |
+
response <- paste0(response, "💡 This is a **minor-effect QTL** (<5% PVE) - typical for complex polygenic traits.\n\n")
|
| 208 |
}
|
| 209 |
|
| 210 |
+
# All QTLs PVE
|
| 211 |
+
response <- paste0(response, "**All QTLs by PVE:**\n")
|
| 212 |
+
df_sorted <- df[order(-df$PVE_Percent), ]
|
| 213 |
+
for (i in 1:min(5, nrow(df_sorted))) {
|
| 214 |
+
row <- df_sorted[i, ]
|
| 215 |
+
response <- paste0(response, sprintf(" %d. %s: %.1f%%\n", i, row$Marker, row$PVE_Percent))
|
|
|
|
| 216 |
}
|
| 217 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 218 |
return(response)
|
| 219 |
} else {
|
| 220 |
return("No QTL results yet. Please run the QTL analysis first to see PVE values.")
|
|
|
|
| 222 |
}
|
| 223 |
|
| 224 |
# Model performance questions
|
| 225 |
+
if (grepl("model performance|r2|r squared|how good is my model|validation|negative r2", q)) {
|
| 226 |
if (has_perf) {
|
| 227 |
pm <- rv$performance_metrics
|
| 228 |
train_r2 <- pm$Value[pm$Metric == "R² (Train)"]
|
|
|
|
| 230 |
|
| 231 |
response <- paste0(
|
| 232 |
"📈 **Model Performance Summary**\n\n",
|
| 233 |
+
"• Training R²: **", round(train_r2, 3), "**\n",
|
| 234 |
+
"• Validation R²: **", round(val_r2, 3), "**\n\n"
|
| 235 |
)
|
| 236 |
|
| 237 |
if (val_r2 < 0) {
|
| 238 |
response <- paste0(response,
|
| 239 |
+
"⚠️ **Your validation R² is negative** (", round(val_r2, 3), ").\n\n",
|
| 240 |
+
"This means the model performs worse than simply predicting the mean.\n\n",
|
| 241 |
+
"**Common causes:**\n",
|
| 242 |
+
"• **Small sample size** relative to number of markers\n",
|
| 243 |
+
"• **Overfitting** - model learned noise instead of signal\n",
|
| 244 |
+
"• **Population structure** in your data\n\n",
|
| 245 |
+
"**Recommendations:**\n",
|
| 246 |
+
"1. Increase sample size if possible\n",
|
| 247 |
+
"2. Reduce marker number (use feature selection)\n",
|
| 248 |
+
"3. Try simpler models or increase cross-validation folds\n",
|
| 249 |
+
"4. Focus on individual QTL interpretation rather than prediction\n"
|
| 250 |
)
|
| 251 |
} else if (val_r2 < 0.2) {
|
| 252 |
response <- paste0(response,
|
| 253 |
"📉 **Low validation R²** (<0.2) suggests modest predictive power.\n\n",
|
| 254 |
+
"This is common for complex traits. Focus on individual QTL interpretation.\n"
|
| 255 |
)
|
| 256 |
} else if (val_r2 < 0.5) {
|
| 257 |
response <- paste0(response,
|
| 258 |
+
"📊 **Moderate validation R²** (0.2-0.5) - your model has decent predictive ability.\n\n"
|
|
|
|
| 259 |
)
|
| 260 |
} else {
|
| 261 |
response <- paste0(response,
|
| 262 |
+
"🎯 **Excellent validation R²** (>0.5) - your model has strong predictive power!\n\n"
|
|
|
|
| 263 |
)
|
| 264 |
}
|
| 265 |
|
|
|
|
| 270 |
}
|
| 271 |
|
| 272 |
# Top QTLs question
|
| 273 |
+
if (grepl("top qtl|best qtl|highest lod|significant qtl|list qtl|show qtl", q)) {
|
| 274 |
if (has_qtl) {
|
| 275 |
df <- rv$qtl_effects_train[order(-rv$qtl_effects_train$LOD), ]
|
| 276 |
top5 <- head(df, 5)
|
|
|
|
| 281 |
row <- top5[i, ]
|
| 282 |
response <- paste0(response,
|
| 283 |
i, ". **", row$Marker, "** (Chr ", row$Chromosome, ")\n",
|
| 284 |
+
" • LOD: **", round(row$LOD, 2), "**\n",
|
| 285 |
" • PVE: ", round(row$PVE_Percent, 1), "%\n",
|
| 286 |
" • Additive effect: ", round(row$Additive_Effect, 3), "\n"
|
| 287 |
)
|
|
|
|
| 297 |
}
|
| 298 |
}
|
| 299 |
|
| 300 |
+
# Next steps question
|
| 301 |
+
if (grepl("next steps|what next|recommendations|suggest|advice|what should i do", q)) {
|
| 302 |
+
if (has_qtl || has_perf || has_epi || has_sel) {
|
| 303 |
+
response <- "🔬 **Recommended Next Steps**\n\n"
|
| 304 |
+
|
| 305 |
+
if (has_qtl) {
|
| 306 |
+
top_qtl <- rv$qtl_effects_train[which.max(rv$qtl_effects_train$LOD), ]
|
| 307 |
+
response <- paste0(response,
|
| 308 |
+
"**1. Validate Top QTLs**\n",
|
| 309 |
+
" • Prioritize **", top_qtl$Marker, "** (LOD=", round(top_qtl$LOD, 2),
|
| 310 |
+
", PVE=", round(top_qtl$PVE_Percent, 1), "%)\n",
|
| 311 |
+
" • Test in independent population or F2 cross\n",
|
| 312 |
+
" • Use flanking markers for fine-mapping\n\n"
|
| 313 |
+
)
|
| 314 |
+
}
|
| 315 |
+
|
| 316 |
+
if (has_epi) {
|
| 317 |
+
n_epi <- nrow(rv$epistasis_sig)
|
| 318 |
+
response <- paste0(response,
|
| 319 |
+
"**2. Investigate Epistasis**\n",
|
| 320 |
+
" • ", n_epi, " significant interactions detected\n",
|
| 321 |
+
" • Test multi-locus models in breeding programs\n",
|
| 322 |
+
" • Check if interacting QTLs map to same pathways\n\n"
|
| 323 |
+
)
|
| 324 |
+
}
|
| 325 |
+
|
| 326 |
+
if (has_sel) {
|
| 327 |
+
n_sel <- sum(rv$selection_metrics$Significant, na.rm = TRUE)
|
| 328 |
+
response <- paste0(response,
|
| 329 |
+
"**3. Domestication Analysis**\n",
|
| 330 |
+
" • ", n_sel, " markers show selection signatures\n",
|
| 331 |
+
" • Cross-reference with QTL positions\n",
|
| 332 |
+
" • Candidate domestication genes\n\n"
|
| 333 |
+
)
|
| 334 |
+
}
|
| 335 |
+
|
| 336 |
+
response <- paste0(response,
|
| 337 |
+
"**4. Functional Analysis**\n",
|
| 338 |
+
" • Annotate QTL regions for candidate genes\n",
|
| 339 |
+
" • Check gene expression databases\n",
|
| 340 |
+
" • Design validation experiments\n\n",
|
| 341 |
+
|
| 342 |
+
"**5. Breeding Applications**\n",
|
| 343 |
+
" • Develop markers for MAS\n",
|
| 344 |
+
" • Design crossing schemes\n",
|
| 345 |
+
" • Predict breeding values\n"
|
| 346 |
+
)
|
| 347 |
+
|
| 348 |
+
return(response)
|
| 349 |
+
} else {
|
| 350 |
+
return("Run the QTL analysis first to get recommendations.")
|
| 351 |
+
}
|
| 352 |
+
}
|
| 353 |
+
|
| 354 |
+
# Default response
|
| 355 |
available <- c()
|
| 356 |
if (has_qtl) available <- c(available, paste(nrow(rv$qtl_effects_train), "QTLs"))
|
| 357 |
if (has_perf) {
|
|
|
|
| 365 |
return(paste0(
|
| 366 |
"I can see you have: ", paste(available, collapse = ", "), ".\n\n",
|
| 367 |
"What would you like to know? Try asking about:\n",
|
| 368 |
+
"• **What is PVE?** - Understand variance explained\n",
|
| 369 |
+
"• **Top QTLs** - List most significant markers\n",
|
| 370 |
+
"• **Model performance** - Why is R² negative?\n",
|
|
|
|
|
|
|
| 371 |
"• **Next steps** - Recommendations for your results"
|
| 372 |
))
|
| 373 |
}
|
|
|
|
| 375 |
return(paste0(
|
| 376 |
"👋 Hello! I'm your QTL analysis assistant.\n\n",
|
| 377 |
"**I can help you with:**\n",
|
| 378 |
+
"• Understanding PVE (variance explained)\n",
|
| 379 |
+
"• Interpreting LOD scores and QTL significance\n",
|
| 380 |
"• Evaluating model performance (R²)\n",
|
| 381 |
+
"• Detecting epistatic interactions\n\n",
|
|
|
|
| 382 |
"**To get started:**\n",
|
| 383 |
"1. Upload your genotype and phenotype files\n",
|
| 384 |
"2. Click 'Run QTL Analysis'\n",
|
| 385 |
+
"3. Ask me specific questions!\n\n",
|
| 386 |
+
"Try: **'What is PVE?'** or **'Show me my top QTLs'**"
|
| 387 |
))
|
| 388 |
}
|
| 389 |
|
| 390 |
+
# ============================================================
|
| 391 |
+
# AI RESPONSE GENERATION
|
| 392 |
+
# ============================================================
|
| 393 |
+
|
| 394 |
+
generate_ai_response <- function(user_message, rv) {
|
| 395 |
+
# Build context
|
| 396 |
+
context <- build_system_prompt(rv)
|
| 397 |
+
|
| 398 |
+
# Check if we should use API
|
| 399 |
+
if (use_hf_api) {
|
| 400 |
+
# Construct prompt for API
|
| 401 |
+
prompt <- paste(
|
| 402 |
+
"CONTEXT:",
|
| 403 |
+
context,
|
| 404 |
+
"\n\nUSER QUESTION:", user_message,
|
| 405 |
+
"\n\nProvide a specific, helpful answer based ONLY on the context above. Be concise but informative.",
|
| 406 |
+
sep = "\n"
|
| 407 |
+
)
|
| 408 |
+
|
| 409 |
+
# Try API
|
| 410 |
+
result <- query_hf_api(prompt)
|
| 411 |
+
|
| 412 |
+
if (result$success) {
|
| 413 |
+
return(result$text)
|
| 414 |
+
} else {
|
| 415 |
+
# Log error but don't show to user
|
| 416 |
+
message("API Error: ", result$error)
|
| 417 |
+
# Fallback to rule-based
|
| 418 |
+
return(enhanced_rule_response(user_message, rv))
|
| 419 |
+
}
|
| 420 |
+
}
|
| 421 |
+
|
| 422 |
+
# Use rule-based
|
| 423 |
+
return(enhanced_rule_response(user_message, rv))
|
| 424 |
+
}
|
| 425 |
+
|
| 426 |
# ============================================================
|
| 427 |
# UI
|
| 428 |
# ============================================================
|
| 429 |
|
| 430 |
ui <- fluidPage(
|
|
|
|
| 431 |
shinyjs::useShinyjs(),
|
| 432 |
|
| 433 |
tags$head(
|
|
|
|
| 820 |
"))
|
| 821 |
),
|
| 822 |
|
|
|
|
| 823 |
navbarPage(
|
| 824 |
title = tags$span(tags$i(class = "fas fa-dna", style = "margin-right:8px; color:#58a6ff;"), "QTL-Mapper AI"),
|
| 825 |
id = "nav",
|
| 826 |
|
|
|
|
| 827 |
tabPanel("Data Upload", icon = icon("upload"),
|
| 828 |
div(class = "main-header",
|
| 829 |
h2(tags$i(class = "fas fa-upload", style = "margin-right:8px;"), "Data Upload"),
|
|
|
|
| 881 |
)
|
| 882 |
),
|
| 883 |
|
|
|
|
| 884 |
tabPanel("Domestication", icon = icon("leaf"),
|
| 885 |
div(class = "main-header",
|
| 886 |
h2(tags$i(class = "fas fa-leaf", style = "margin-right:8px;"), "Domestication Analysis"),
|
|
|
|
| 924 |
)
|
| 925 |
),
|
| 926 |
|
|
|
|
| 927 |
tabPanel("Results", icon = icon("chart-line"),
|
| 928 |
div(class = "main-header",
|
| 929 |
h2(tags$i(class = "fas fa-chart-line", style = "margin-right:8px;"), "QTL Analysis Results"),
|
|
|
|
| 964 |
)
|
| 965 |
),
|
| 966 |
|
|
|
|
| 967 |
tabPanel("Interpretation", icon = icon("lightbulb"),
|
| 968 |
div(class = "main-header",
|
| 969 |
h2(tags$i(class = "fas fa-lightbulb", style = "margin-right:8px;"), "Results Interpretation"),
|
|
|
|
| 984 |
)
|
| 985 |
),
|
| 986 |
|
|
|
|
| 987 |
tabPanel("About", icon = icon("info-circle"),
|
| 988 |
div(class = "main-header",
|
| 989 |
h2(tags$i(class = "fas fa-info-circle", style = "margin-right:8px;"), "About QTL-Mapper AI"),
|
|
|
|
| 1000 |
tags$li("Additive and dominance effects estimated via linear regression"),
|
| 1001 |
tags$li("Epistasis analysis: pairwise QTL x marker interactions"),
|
| 1002 |
tags$li("Domestication: Fst, nucleotide diversity (Pi), Tajima's D"),
|
| 1003 |
+
tags$li("AI Assistant powered by transformer models via Hugging Face Inference API")
|
| 1004 |
),
|
| 1005 |
h4(style = "color:#58a6ff; font-family: 'IBM Plex Mono'; margin: 12px 0;", "AI Assistant Status"),
|
| 1006 |
p(style = "color: #8b949e; line-height: 1.7;",
|
|
|
|
| 1024 |
)
|
| 1025 |
),
|
| 1026 |
|
|
|
|
| 1027 |
tags$div(id = "chat-panel",
|
| 1028 |
tags$div(id = "chat-window",
|
|
|
|
| 1029 |
tags$div(id = "chat-header",
|
| 1030 |
tags$div(class = "chat-title",
|
| 1031 |
tags$div(class = "chat-avatar", "AI"),
|
| 1032 |
tags$div(
|
| 1033 |
tags$h4("QTL Analysis AI Assistant",
|
| 1034 |
+
tags$span(class = "model-badge",
|
| 1035 |
+
if(use_hf_api) "AI mode" else "rules")
|
| 1036 |
),
|
| 1037 |
tags$p(id = "model_status",
|
| 1038 |
+
if(use_hf_api) "🤖 Connected" else "📝 Rule-based"
|
| 1039 |
)
|
| 1040 |
)
|
| 1041 |
),
|
|
|
|
| 1044 |
)
|
| 1045 |
),
|
| 1046 |
|
|
|
|
| 1047 |
tags$div(class = "quick-questions",
|
| 1048 |
tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q', 'What is PVE?', {priority: 'event'});", "PVE meaning"),
|
| 1049 |
tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q', 'What are my top QTLs?', {priority: 'event'});", "Top QTLs"),
|
| 1050 |
+
tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q', 'Why is my R² negative?', {priority: 'event'});", "Negative R²"),
|
| 1051 |
+
tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q', 'What should I do next?', {priority: 'event'});", "Next steps")
|
|
|
|
|
|
|
|
|
|
| 1052 |
),
|
| 1053 |
|
|
|
|
| 1054 |
tags$div(id = "chat_messages",
|
| 1055 |
uiOutput("chat_display")
|
| 1056 |
),
|
| 1057 |
|
|
|
|
| 1058 |
tags$div(id = "chat-footer",
|
| 1059 |
tags$textarea(
|
| 1060 |
id = "chat_input",
|
| 1061 |
+
placeholder = "Ask about your results... (Enter to send)",
|
| 1062 |
rows = "2"
|
| 1063 |
),
|
| 1064 |
tags$div(class = "chat-actions",
|
|
|
|
| 1068 |
)
|
| 1069 |
),
|
| 1070 |
|
|
|
|
| 1071 |
tags$button(id = "chat-toggle-btn",
|
| 1072 |
onclick = "document.getElementById('chat-window').classList.toggle('open');",
|
| 1073 |
tags$i(class = "fas fa-robot")
|
|
|
|
| 1081 |
|
| 1082 |
server <- function(input, output, session) {
|
| 1083 |
|
|
|
|
| 1084 |
values <- reactiveValues(
|
| 1085 |
genotype_data = NULL,
|
| 1086 |
phenotype_data = NULL,
|
|
|
|
| 1103 |
pop_data = NULL,
|
| 1104 |
selection_metrics = NULL,
|
| 1105 |
has_test_data = FALSE,
|
|
|
|
| 1106 |
chat_messages = list(),
|
| 1107 |
is_typing = FALSE,
|
| 1108 |
+
lod_threshold = 2,
|
| 1109 |
+
use_ai = use_hf_api
|
|
|
|
| 1110 |
)
|
| 1111 |
|
| 1112 |
+
# Update status
|
| 1113 |
observe({
|
| 1114 |
+
if (values$use_ai) {
|
| 1115 |
+
shinyjs::html("model_status", "🤖 AI mode active")
|
| 1116 |
+
# Test connection
|
| 1117 |
+
test_result <- query_hf_api("Hello")
|
| 1118 |
+
if (!test_result$success) {
|
| 1119 |
+
values$use_ai <- FALSE
|
| 1120 |
+
shinyjs::html("model_status", "📝 Rule-based mode (API unavailable)")
|
| 1121 |
+
}
|
| 1122 |
} else {
|
| 1123 |
+
shinyjs::html("model_status", "📝 Rule-based mode")
|
|
|
|
| 1124 |
}
|
| 1125 |
})
|
| 1126 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1127 |
# ============================================================
|
| 1128 |
# CHAT FUNCTIONS
|
| 1129 |
# ============================================================
|
| 1130 |
|
| 1131 |
+
add_message <- function(role, content) {
|
|
|
|
| 1132 |
timestamp <- format(Sys.time(), "%H:%M")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1133 |
values$chat_messages <- c(values$chat_messages, list(list(
|
| 1134 |
+
role = role, content = content, time = timestamp
|
|
|
|
|
|
|
|
|
|
| 1135 |
)))
|
|
|
|
|
|
|
| 1136 |
if (length(values$chat_messages) > 50) {
|
| 1137 |
values$chat_messages <- tail(values$chat_messages, 50)
|
| 1138 |
}
|
|
|
|
| 1139 |
session$sendCustomMessage("scrollChatBottom", list())
|
| 1140 |
}
|
| 1141 |
|
|
|
|
| 1142 |
process_message <- function(user_text) {
|
| 1143 |
if (nchar(trimws(user_text)) == 0) return()
|
| 1144 |
|
|
|
|
| 1145 |
add_message("user", user_text)
|
| 1146 |
+
values$is_typing <- TRUE
|
| 1147 |
|
| 1148 |
+
response <- generate_ai_response(user_text, values)
|
|
|
|
| 1149 |
|
| 1150 |
+
values$is_typing <- FALSE
|
| 1151 |
add_message("assistant", response)
|
| 1152 |
}
|
| 1153 |
|
|
|
|
| 1154 |
observeEvent(input$send_chat, {
|
| 1155 |
req(input$chat_input)
|
| 1156 |
user_text <- trimws(input$chat_input)
|
| 1157 |
if (nchar(user_text) == 0) return()
|
|
|
|
|
|
|
| 1158 |
updateTextAreaInput(session, "chat_input", value = "")
|
|
|
|
|
|
|
| 1159 |
process_message(user_text)
|
| 1160 |
})
|
| 1161 |
|
|
|
|
| 1162 |
observeEvent(input$quick_q, {
|
| 1163 |
req(input$quick_q)
|
| 1164 |
process_message(input$quick_q)
|
| 1165 |
})
|
| 1166 |
|
|
|
|
| 1167 |
observeEvent(input$clear_chat, {
|
| 1168 |
values$chat_messages <- list()
|
| 1169 |
+
add_message("assistant", "Chat cleared. How can I help?")
|
| 1170 |
})
|
| 1171 |
|
|
|
|
| 1172 |
observe({
|
| 1173 |
if (length(values$chat_messages) == 0) {
|
| 1174 |
+
mode_msg <- if (values$use_ai) {
|
| 1175 |
+
"I'm using a transformer AI model to help you!"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1176 |
} else {
|
| 1177 |
+
"I'm using rule-based responses."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1178 |
}
|
| 1179 |
+
add_message("assistant", paste(
|
| 1180 |
+
"👋 Hello! I'm your QTL analysis assistant.", mode_msg,
|
| 1181 |
+
"\n\n**I can help you with:**",
|
| 1182 |
+
"• **What is PVE?** - Understand variance explained",
|
| 1183 |
+
"• **Show top QTLs** - List your most significant markers",
|
| 1184 |
+
"• **Model performance** - Why is my R² negative?",
|
| 1185 |
+
"• **Next steps** - Recommendations",
|
| 1186 |
+
"\nTry asking: **'What is PVE?'**"
|
| 1187 |
+
))
|
| 1188 |
}
|
| 1189 |
})
|
| 1190 |
|
|
|
|
| 1191 |
output$chat_display <- renderUI({
|
| 1192 |
messages <- values$chat_messages
|
|
|
|
| 1193 |
if (length(messages) == 0) return(NULL)
|
| 1194 |
|
| 1195 |
message_elements <- lapply(messages, function(msg) {
|
|
|
|
| 1201 |
)
|
| 1202 |
})
|
| 1203 |
|
|
|
|
| 1204 |
if (values$is_typing) {
|
| 1205 |
message_elements <- c(message_elements, list(
|
| 1206 |
div(class = "chat-msg assistant",
|
| 1207 |
div(class = "typing-indicator",
|
| 1208 |
+
div(class = "typing-dot"), div(class = "typing-dot"), div(class = "typing-dot")
|
|
|
|
|
|
|
| 1209 |
)
|
| 1210 |
)
|
| 1211 |
))
|
|
|
|
| 1218 |
# DATA LOADING FUNCTIONS
|
| 1219 |
# ============================================================
|
| 1220 |
|
|
|
|
| 1221 |
observeEvent(input$genotype_file, {
|
| 1222 |
req(input$genotype_file)
|
| 1223 |
tryCatch({
|
|
|
|
| 1224 |
all_data <- readLines(input$genotype_file$datapath)
|
| 1225 |
if (length(all_data) < 4) {
|
| 1226 |
+
showNotification("Genotype file must have at least 4 rows", type = "error")
|
| 1227 |
return()
|
| 1228 |
}
|
| 1229 |
|
|
|
|
| 1230 |
header <- strsplit(all_data[1], ",")[[1]]
|
| 1231 |
chromosome_row <- strsplit(all_data[2], ",")[[1]]
|
| 1232 |
position_row <- strsplit(all_data[3], ",")[[1]]
|
| 1233 |
|
|
|
|
| 1234 |
genotype_data <- read.csv(text = all_data[-(1:3)], header = FALSE)
|
| 1235 |
colnames(genotype_data) <- header
|
| 1236 |
rownames(genotype_data) <- genotype_data[, 1]
|
| 1237 |
genotype_data <- genotype_data[, -1]
|
| 1238 |
|
|
|
|
| 1239 |
for (col in colnames(genotype_data)) {
|
| 1240 |
genotype_data[[col]] <- as.numeric(as.character(genotype_data[[col]]))
|
| 1241 |
}
|
| 1242 |
|
|
|
|
| 1243 |
values$all_markers <- data.frame(
|
| 1244 |
Marker = colnames(genotype_data),
|
| 1245 |
Chromosome = chromosome_row[-1],
|
|
|
|
| 1251 |
values$chromosome_info <- chromosome_row[-1]
|
| 1252 |
values$position_info <- as.numeric(position_row[-1])
|
| 1253 |
|
| 1254 |
+
showNotification("Genotype data loaded", type = "message")
|
| 1255 |
+
add_message("assistant", paste0("✅ Loaded ", ncol(genotype_data), " markers, ", nrow(genotype_data), " samples"))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1256 |
|
| 1257 |
}, error = function(e) {
|
| 1258 |
+
showNotification(paste("Error:", e$message), type = "error")
|
| 1259 |
})
|
| 1260 |
})
|
| 1261 |
|
|
|
|
| 1262 |
observeEvent(input$phenotype_file, {
|
| 1263 |
req(input$phenotype_file)
|
| 1264 |
tryCatch({
|
| 1265 |
phenotype_data <- read.csv(input$phenotype_file$datapath)
|
|
|
|
|
|
|
| 1266 |
rownames(phenotype_data) <- phenotype_data[, 1]
|
| 1267 |
phenotype_data <- phenotype_data[, -1]
|
| 1268 |
|
|
|
|
| 1269 |
for (col in colnames(phenotype_data)) {
|
| 1270 |
phenotype_data[[col]] <- as.numeric(as.character(phenotype_data[[col]]))
|
| 1271 |
}
|
| 1272 |
|
| 1273 |
values$phenotype_data <- phenotype_data
|
|
|
|
|
|
|
| 1274 |
updateSelectInput(session, "phenotype_column",
|
| 1275 |
choices = colnames(phenotype_data),
|
| 1276 |
selected = colnames(phenotype_data)[1])
|
| 1277 |
|
| 1278 |
+
showNotification("Phenotype data loaded", type = "message")
|
| 1279 |
+
add_message("assistant", paste0("✅ Loaded ", ncol(phenotype_data), " traits, ", nrow(phenotype_data), " samples"))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1280 |
|
| 1281 |
}, error = function(e) {
|
| 1282 |
+
showNotification(paste("Error:", e$message), type = "error")
|
| 1283 |
})
|
| 1284 |
})
|
| 1285 |
|
|
|
|
| 1286 |
observeEvent(input$pop_file, {
|
| 1287 |
req(input$pop_file)
|
| 1288 |
tryCatch({
|
| 1289 |
pop_data <- read.csv(input$pop_file$datapath)
|
|
|
|
|
|
|
| 1290 |
if (!all(c("id", "population") %in% colnames(pop_data))) {
|
| 1291 |
showNotification("Population file must have 'id' and 'population' columns", type = "error")
|
| 1292 |
return()
|
| 1293 |
}
|
|
|
|
| 1294 |
values$pop_data <- pop_data
|
| 1295 |
+
showNotification("Population data loaded", type = "message")
|
| 1296 |
+
add_message("assistant", paste0("✅ Loaded population data (", nrow(pop_data), " samples)"))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1297 |
}, error = function(e) {
|
| 1298 |
+
showNotification(paste("Error:", e$message), type = "error")
|
| 1299 |
})
|
| 1300 |
})
|
| 1301 |
|
|
|
|
| 1302 |
observeEvent(input$test_genotype_file, {
|
| 1303 |
req(input$test_genotype_file)
|
| 1304 |
tryCatch({
|
|
|
|
| 1318 |
|
| 1319 |
values$test_genotype_data <- genotype_data
|
| 1320 |
values$has_test_data <- TRUE
|
| 1321 |
+
showNotification("Test genotype data loaded", type = "message")
|
|
|
|
| 1322 |
|
| 1323 |
}, error = function(e) {
|
| 1324 |
+
showNotification(paste("Error:", e$message), type = "error")
|
| 1325 |
})
|
| 1326 |
})
|
| 1327 |
|
|
|
|
| 1360 |
})
|
| 1361 |
|
| 1362 |
# ============================================================
|
| 1363 |
+
# QTL ANALYSIS FUNCTIONS
|
| 1364 |
# ============================================================
|
| 1365 |
|
|
|
|
| 1366 |
calculate_qtl_effects <- function(genotype_matrix, phenotype_vector, marker_names) {
|
| 1367 |
effects_list <- list()
|
| 1368 |
|
| 1369 |
for (marker in marker_names) {
|
| 1370 |
if (!marker %in% colnames(genotype_matrix)) next
|
| 1371 |
|
|
|
|
| 1372 |
geno <- genotype_matrix[, marker]
|
| 1373 |
pheno <- phenotype_vector
|
|
|
|
|
|
|
| 1374 |
valid_idx <- !is.na(geno) & !is.na(pheno)
|
| 1375 |
geno <- geno[valid_idx]
|
| 1376 |
pheno <- pheno[valid_idx]
|
| 1377 |
|
| 1378 |
if (length(unique(geno)) < 2) next
|
| 1379 |
|
|
|
|
| 1380 |
lm_fit <- lm(pheno ~ geno)
|
|
|
|
|
|
|
| 1381 |
additive_effect <- coef(lm_fit)[2]
|
| 1382 |
|
|
|
|
| 1383 |
dominance_effect <- NA
|
| 1384 |
if (length(unique(geno)) == 3) {
|
| 1385 |
geno_means <- tapply(pheno, geno, mean, na.rm = TRUE)
|
|
|
|
| 1389 |
dominance_effect <- het_mean - midparent
|
| 1390 |
}
|
| 1391 |
|
|
|
|
| 1392 |
r_squared <- summary(lm_fit)$r.squared
|
| 1393 |
+
se_additive <- tryCatch(summary(lm_fit)$coefficients[2, 2], error = function(e) NA)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1394 |
|
| 1395 |
effects_list[[marker]] <- data.frame(
|
| 1396 |
Marker = marker,
|
| 1397 |
Additive_Effect = additive_effect,
|
| 1398 |
Dominance_Effect = dominance_effect,
|
| 1399 |
PVE_Percent = r_squared * 100,
|
| 1400 |
+
SE_Additive = se_additive,
|
| 1401 |
CI_Lower = ifelse(is.na(se_additive), NA, additive_effect - 1.96 * se_additive),
|
| 1402 |
CI_Upper = ifelse(is.na(se_additive), NA, additive_effect + 1.96 * se_additive),
|
| 1403 |
N_Samples = length(pheno),
|
|
|
|
| 1414 |
req(values$genotype_data, values$phenotype_data, input$phenotype_column)
|
| 1415 |
|
| 1416 |
showNotification("Starting QTL analysis...", type = "message")
|
| 1417 |
+
values$lod_threshold <- input$lod_threshold
|
| 1418 |
|
| 1419 |
tryCatch({
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1420 |
common_samples <- intersect(rownames(values$genotype_data),
|
| 1421 |
rownames(values$phenotype_data))
|
| 1422 |
|
| 1423 |
if (length(common_samples) == 0) {
|
| 1424 |
+
showNotification("No common samples", type = "error")
|
| 1425 |
return()
|
| 1426 |
}
|
| 1427 |
|
|
|
|
| 1428 |
X <- values$genotype_data[common_samples, , drop = FALSE]
|
| 1429 |
y <- as.numeric(values$phenotype_data[common_samples, input$phenotype_column])
|
| 1430 |
|
|
|
|
| 1431 |
nzv <- nearZeroVar(X)
|
| 1432 |
+
if (length(nzv) > 0) X <- X[, -nzv, drop = FALSE]
|
|
|
|
|
|
|
| 1433 |
|
|
|
|
| 1434 |
set.seed(123)
|
| 1435 |
train_index <- createDataPartition(y, p = 1 - input$test_size, list = FALSE)
|
| 1436 |
|
|
|
|
| 1439 |
y_train <- y[train_index]
|
| 1440 |
y_val <- y[-train_index]
|
| 1441 |
|
|
|
|
| 1442 |
model <- train(
|
| 1443 |
x = X_train,
|
| 1444 |
y = y_train,
|
|
|
|
| 1450 |
|
| 1451 |
values$model_fit <- model
|
| 1452 |
|
|
|
|
| 1453 |
imp <- varImp(model, scale = FALSE)$importance
|
| 1454 |
importance_scores <- data.frame(
|
| 1455 |
Marker = rownames(imp),
|
|
|
|
| 1460 |
)
|
| 1461 |
|
| 1462 |
values$importance_scores <- importance_scores
|
|
|
|
|
|
|
| 1463 |
lod_sig <- importance_scores[importance_scores$LOD > input$lod_threshold, , drop = FALSE]
|
| 1464 |
|
| 1465 |
if (nrow(lod_sig) > 0) {
|
|
|
|
| 1466 |
lod_sig$Low_Flank <- NA
|
| 1467 |
lod_sig$High_Flank <- NA
|
| 1468 |
|
|
|
|
| 1478 |
}
|
| 1479 |
|
| 1480 |
values$lod_scores_train <- lod_sig
|
|
|
|
|
|
|
| 1481 |
qtl_fx <- calculate_qtl_effects(X_train, y_train, lod_sig$Marker)
|
| 1482 |
|
| 1483 |
if (!is.null(qtl_fx)) {
|
|
|
|
| 1490 |
values$qtl_effects_train <- data.frame(Message = paste("No QTLs above LOD", input$lod_threshold))
|
| 1491 |
}
|
| 1492 |
|
|
|
|
| 1493 |
y_train_pred <- predict(model, X_train)
|
| 1494 |
y_val_pred <- predict(model, X_val)
|
| 1495 |
|
|
|
|
| 1498 |
|
| 1499 |
values$performance_metrics <- data.frame(
|
| 1500 |
Metric = c("R² (Train)", "R (Train)", "R² (Validation)", "R (Validation)"),
|
| 1501 |
+
Value = c(train_r2, cor(y_train, y_train_pred), val_r2, cor(y_val, y_val_pred)),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1502 |
stringsAsFactors = FALSE
|
| 1503 |
)
|
| 1504 |
|
| 1505 |
values$train_predictions <- data.frame(Observed = y_train, Predicted = y_train_pred)
|
| 1506 |
values$test_predictions <- data.frame(Observed = y_val, Predicted = y_val_pred)
|
| 1507 |
|
| 1508 |
+
# Epistasis
|
| 1509 |
if (nrow(lod_sig) > 0) {
|
| 1510 |
sig_markers <- lod_sig$Marker[lod_sig$Marker %in% colnames(X_train)]
|
| 1511 |
all_markers <- colnames(X_train)
|
|
|
|
| 1512 |
epistasis_list <- list()
|
| 1513 |
|
| 1514 |
withProgress(message = 'Calculating epistasis...', value = 0, {
|
| 1515 |
total <- length(sig_markers) * length(all_markers)
|
|
|
|
|
|
|
| 1516 |
for (m1 in sig_markers) {
|
| 1517 |
for (m2 in all_markers) {
|
| 1518 |
if (m1 == m2) next
|
| 1519 |
+
incProgress(1/total)
|
|
|
|
|
|
|
| 1520 |
|
| 1521 |
tryCatch({
|
| 1522 |
+
data_epi <- data.frame(y = y_train, m1 = X_train[, m1], m2 = X_train[, m2])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1523 |
data_epi <- na.omit(data_epi)
|
|
|
|
| 1524 |
if (nrow(data_epi) < 10) next
|
| 1525 |
|
|
|
|
| 1526 |
fit <- lm(y ~ m1 * m2, data = data_epi)
|
| 1527 |
coef_summary <- summary(fit)$coefficients
|
| 1528 |
|
|
|
|
| 1531 |
effect <- coef(fit)["m1:m2"]
|
| 1532 |
|
| 1533 |
epistasis_list[[length(epistasis_list) + 1]] <- data.frame(
|
| 1534 |
+
QTL1 = m1, QTL2 = m2,
|
|
|
|
| 1535 |
Interaction_p = p_val,
|
| 1536 |
Effect_Size = effect,
|
| 1537 |
stringsAsFactors = FALSE
|
|
|
|
| 1547 |
values$epistasis_all <- epistasis_all
|
| 1548 |
values$epistasis_sig <- epistasis_all[epistasis_all$Interaction_p < 0.05, ]
|
| 1549 |
} else {
|
| 1550 |
+
values$epistasis_all <- data.frame(Message = "No epistatic interactions")
|
| 1551 |
+
values$epistasis_sig <- data.frame(Message = "No epistatic interactions")
|
| 1552 |
}
|
| 1553 |
}
|
| 1554 |
|
| 1555 |
+
showNotification("QTL analysis completed!", type = "message")
|
| 1556 |
|
|
|
|
| 1557 |
n_qtl <- if (!is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train)) nrow(values$qtl_effects_train) else 0
|
|
|
|
|
|
|
| 1558 |
add_message("assistant", paste(
|
| 1559 |
"✅ QTL analysis complete!",
|
| 1560 |
+
paste0("• Found ", n_qtl, " QTLs"),
|
| 1561 |
+
paste0("• Validation R²: ", round(val_r2, 3)),
|
| 1562 |
+
"Ask me about PVE or top QTLs!"
|
|
|
|
|
|
|
|
|
|
| 1563 |
))
|
| 1564 |
|
|
|
|
| 1565 |
updateTabsetPanel(session, "nav", selected = "Results")
|
| 1566 |
|
| 1567 |
}, error = function(e) {
|
| 1568 |
+
showNotification(paste("Error:", e$message), type = "error")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1569 |
})
|
| 1570 |
})
|
| 1571 |
|
|
|
|
| 1573 |
# DOMESTICATION ANALYSIS
|
| 1574 |
# ============================================================
|
| 1575 |
|
|
|
|
| 1576 |
calculate_selection_metrics <- function(genotype_matrix, pop_data, marker_info) {
|
| 1577 |
metrics_list <- list()
|
| 1578 |
|
| 1579 |
for (marker in colnames(genotype_matrix)) {
|
|
|
|
| 1580 |
geno <- genotype_matrix[, marker]
|
| 1581 |
pop <- pop_data$population[match(rownames(genotype_matrix), pop_data$id)]
|
|
|
|
|
|
|
| 1582 |
valid_idx <- !is.na(geno) & !is.na(pop)
|
| 1583 |
geno <- geno[valid_idx]
|
| 1584 |
pop <- pop[valid_idx]
|
| 1585 |
|
| 1586 |
if (length(unique(pop)) < 2) next
|
| 1587 |
|
|
|
|
| 1588 |
geno_dom <- geno[pop == "Domesticated"]
|
| 1589 |
geno_wild <- geno[pop == "Wild"]
|
| 1590 |
|
| 1591 |
if (length(geno_dom) < 3 || length(geno_wild) < 3) next
|
| 1592 |
|
|
|
|
| 1593 |
freq_dom <- mean(geno_dom, na.rm = TRUE) / 2
|
| 1594 |
freq_wild <- mean(geno_wild, na.rm = TRUE) / 2
|
| 1595 |
|
|
|
|
| 1596 |
p_avg <- (freq_dom + freq_wild) / 2
|
| 1597 |
if (p_avg > 0 && p_avg < 1) {
|
| 1598 |
fst <- (freq_dom - freq_wild)^2 / (p_avg * (1 - p_avg))
|
| 1599 |
+
fst <- fst / (1 + fst)
|
| 1600 |
} else {
|
| 1601 |
fst <- 0
|
| 1602 |
}
|
| 1603 |
|
|
|
|
| 1604 |
pi_dom <- 2 * freq_dom * (1 - freq_dom)
|
| 1605 |
pi_wild <- 2 * freq_wild * (1 - freq_wild)
|
| 1606 |
|
|
|
|
| 1607 |
n_dom <- length(geno_dom)
|
| 1608 |
n_wild <- length(geno_wild)
|
| 1609 |
|
| 1610 |
tajima_d_dom <- (pi_dom - 1/n_dom) / sqrt(var(geno_dom)/n_dom)
|
| 1611 |
tajima_d_wild <- (pi_wild - 1/n_wild) / sqrt(var(geno_wild)/n_wild)
|
| 1612 |
|
|
|
|
| 1613 |
marker_row <- marker_info[marker_info$Marker == marker, ]
|
| 1614 |
|
| 1615 |
metrics_list[[marker]] <- data.frame(
|
|
|
|
| 1629 |
do.call(rbind, metrics_list)
|
| 1630 |
}
|
| 1631 |
|
|
|
|
| 1632 |
observeEvent(input$run_domestication, {
|
| 1633 |
req(values$genotype_data, values$pop_data, values$all_markers)
|
| 1634 |
|
|
|
|
|
|
|
| 1635 |
tryCatch({
|
|
|
|
| 1636 |
common_samples <- intersect(rownames(values$genotype_data), values$pop_data$id)
|
| 1637 |
|
| 1638 |
if (length(common_samples) == 0) {
|
| 1639 |
+
showNotification("No common samples", type = "error")
|
| 1640 |
return()
|
| 1641 |
}
|
| 1642 |
|
|
|
|
| 1643 |
X <- values$genotype_data[common_samples, , drop = FALSE]
|
| 1644 |
pop_subset <- values$pop_data[values$pop_data$id %in% common_samples, ]
|
| 1645 |
|
|
|
|
| 1646 |
sel_metrics <- calculate_selection_metrics(X, pop_subset, values$all_markers)
|
| 1647 |
|
| 1648 |
if (is.null(sel_metrics)) {
|
|
|
|
| 1650 |
return()
|
| 1651 |
}
|
| 1652 |
|
|
|
|
| 1653 |
sel_metrics$Significant <-
|
| 1654 |
sel_metrics$Fst > input$fst_threshold |
|
| 1655 |
sel_metrics$Tajima_D_Dom < input$tajima_threshold |
|
| 1656 |
sel_metrics$Tajima_D_Wild < input$tajima_threshold
|
| 1657 |
|
| 1658 |
values$selection_metrics <- sel_metrics
|
|
|
|
| 1659 |
showNotification("Domestication analysis completed!", type = "message")
|
| 1660 |
|
|
|
|
| 1661 |
n_sig <- sum(sel_metrics$Significant, na.rm = TRUE)
|
|
|
|
|
|
|
| 1662 |
add_message("assistant", paste(
|
| 1663 |
"✅ Domestication analysis complete!",
|
| 1664 |
+
paste0("• Found ", n_sig, " markers with selection signatures")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1665 |
))
|
| 1666 |
|
| 1667 |
}, error = function(e) {
|
| 1668 |
+
showNotification(paste("Error:", e$message), type = "error")
|
| 1669 |
})
|
| 1670 |
})
|
| 1671 |
|
|
|
|
| 1677 |
req(values$model_fit, values$test_genotype_data)
|
| 1678 |
|
| 1679 |
tryCatch({
|
|
|
|
| 1680 |
common_markers <- intersect(colnames(values$test_genotype_data),
|
| 1681 |
colnames(values$genotype_data))
|
| 1682 |
|
| 1683 |
if (length(common_markers) == 0) {
|
| 1684 |
+
showNotification("No common markers", type = "error")
|
| 1685 |
return()
|
| 1686 |
}
|
| 1687 |
|
|
|
|
| 1688 |
X_test <- values$test_genotype_data[, common_markers, drop = FALSE]
|
|
|
|
|
|
|
| 1689 |
predictions <- predict(values$model_fit, newdata = X_test)
|
| 1690 |
|
| 1691 |
values$predicted_test_phenotype_data <- data.frame(
|
|
|
|
| 1694 |
stringsAsFactors = FALSE
|
| 1695 |
)
|
| 1696 |
|
| 1697 |
+
showNotification("Predictions completed!", type = "message")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1698 |
|
| 1699 |
}, error = function(e) {
|
| 1700 |
+
showNotification(paste("Error:", e$message), type = "error")
|
| 1701 |
})
|
| 1702 |
})
|
| 1703 |
|
|
|
|
| 1705 |
# PLOTS
|
| 1706 |
# ============================================================
|
| 1707 |
|
|
|
|
| 1708 |
create_manhattan <- function(data, y_col, title, threshold, y_label = y_col) {
|
| 1709 |
if (is.null(data) || nrow(data) == 0 || "Message" %in% colnames(data)) {
|
| 1710 |
return(plot_ly() %>% layout(title = "No data available"))
|
| 1711 |
}
|
| 1712 |
|
|
|
|
| 1713 |
plot_data <- data[!is.na(data[[y_col]]), ]
|
| 1714 |
if (nrow(plot_data) == 0) return(plot_ly() %>% layout(title = "No valid data"))
|
| 1715 |
|
|
|
|
| 1716 |
chroms <- unique(plot_data$Chromosome)
|
| 1717 |
chrom_pos <- data.frame()
|
| 1718 |
|
|
|
|
| 1725 |
}
|
| 1726 |
}
|
| 1727 |
|
|
|
|
|
|
|
|
|
|
| 1728 |
p <- plot_ly() %>%
|
| 1729 |
add_trace(
|
| 1730 |
data = chrom_pos,
|
|
|
|
| 1735 |
color = ~factor(Chromosome),
|
| 1736 |
colors = viridis(length(chroms)),
|
| 1737 |
marker = list(size = 6, opacity = 0.7),
|
| 1738 |
+
text = ~paste("Marker:", Marker, "<br>Chr:", Chromosome, "<br>Pos:", Position,
|
|
|
|
|
|
|
| 1739 |
"<br>", y_label, ":", round(get(y_col), 3)),
|
| 1740 |
hoverinfo = 'text',
|
| 1741 |
showlegend = FALSE
|
| 1742 |
)
|
| 1743 |
|
|
|
|
| 1744 |
if (!is.null(threshold) && !is.na(threshold)) {
|
| 1745 |
p <- p %>% add_segments(
|
| 1746 |
x = min(chrom_pos$PosScaled, na.rm = TRUE),
|
|
|
|
| 1748 |
y = threshold,
|
| 1749 |
yend = threshold,
|
| 1750 |
line = list(color = 'red', dash = 'dash', width = 1),
|
| 1751 |
+
name = 'Threshold'
|
|
|
|
| 1752 |
)
|
| 1753 |
}
|
| 1754 |
|
|
|
|
| 1755 |
p %>% layout(
|
| 1756 |
+
title = title,
|
| 1757 |
+
xaxis = list(title = "Chromosome",
|
| 1758 |
+
ticktext = chroms,
|
| 1759 |
+
tickvals = tapply(chrom_pos$PosScaled, chrom_pos$Chromosome, median, na.rm = TRUE),
|
| 1760 |
+
tickangle = 45),
|
|
|
|
|
|
|
| 1761 |
yaxis = list(title = y_label),
|
|
|
|
| 1762 |
plot_bgcolor = "#0d1117",
|
| 1763 |
paper_bgcolor = "#161b22",
|
| 1764 |
font = list(color = "#8b949e")
|
| 1765 |
)
|
| 1766 |
}
|
| 1767 |
|
|
|
|
| 1768 |
output$lod_plot_2d <- renderPlotly({
|
| 1769 |
req(values$importance_scores)
|
| 1770 |
create_manhattan(values$importance_scores, "LOD", "QTL Manhattan Plot", input$lod_threshold, "LOD Score")
|
| 1771 |
})
|
| 1772 |
|
|
|
|
| 1773 |
output$fst_plot <- renderPlotly({
|
| 1774 |
req(values$selection_metrics)
|
| 1775 |
create_manhattan(values$selection_metrics, "Fst", "Fst Manhattan Plot", input$fst_threshold, "Fst")
|
| 1776 |
})
|
| 1777 |
|
|
|
|
| 1778 |
output$tajima_plot <- renderPlotly({
|
| 1779 |
req(values$selection_metrics)
|
| 1780 |
|
|
|
|
| 1783 |
}
|
| 1784 |
|
| 1785 |
data <- values$selection_metrics
|
|
|
|
|
|
|
| 1786 |
chroms <- unique(data$Chromosome)
|
| 1787 |
chrom_pos <- data.frame()
|
| 1788 |
|
|
|
|
| 1804 |
mode = 'markers',
|
| 1805 |
name = 'Domesticated',
|
| 1806 |
marker = list(size = 5, color = '#58a6ff', opacity = 0.7),
|
| 1807 |
+
text = ~paste("Marker:", Marker, "<br>D(Dom):", round(Tajima_D_Dom, 3)),
|
| 1808 |
hoverinfo = 'text'
|
| 1809 |
) %>%
|
| 1810 |
add_trace(
|
|
|
|
| 1815 |
mode = 'markers',
|
| 1816 |
name = 'Wild',
|
| 1817 |
marker = list(size = 5, color = '#f97316', opacity = 0.7),
|
| 1818 |
+
text = ~paste("Marker:", Marker, "<br>D(Wild):", round(Tajima_D_Wild, 3)),
|
| 1819 |
hoverinfo = 'text'
|
| 1820 |
) %>%
|
| 1821 |
add_segments(
|
|
|
|
| 1823 |
xend = max(chrom_pos$PosScaled, na.rm = TRUE),
|
| 1824 |
y = input$tajima_threshold,
|
| 1825 |
yend = input$tajima_threshold,
|
| 1826 |
+
line = list(color = 'red', dash = 'dash', width = 1)
|
|
|
|
| 1827 |
) %>%
|
| 1828 |
layout(
|
| 1829 |
title = "Tajima's D Manhattan Plot",
|
| 1830 |
+
xaxis = list(title = "Chromosome",
|
| 1831 |
+
ticktext = chroms,
|
| 1832 |
+
tickvals = tapply(chrom_pos$PosScaled, chrom_pos$Chromosome, median, na.rm = TRUE),
|
| 1833 |
+
tickangle = 45),
|
|
|
|
|
|
|
| 1834 |
yaxis = list(title = "Tajima's D"),
|
|
|
|
| 1835 |
plot_bgcolor = "#0d1117",
|
| 1836 |
paper_bgcolor = "#161b22",
|
| 1837 |
font = list(color = "#8b949e")
|
| 1838 |
)
|
| 1839 |
})
|
| 1840 |
|
|
|
|
| 1841 |
output$performance_plot <- renderPlotly({
|
| 1842 |
req(values$performance_metrics)
|
| 1843 |
|
|
|
|
| 1846 |
x = ~Metric,
|
| 1847 |
y = ~Value,
|
| 1848 |
type = 'bar',
|
| 1849 |
+
marker = list(color = c('#58a6ff', '#58a6ff', '#3fb950', '#3fb950')),
|
|
|
|
|
|
|
|
|
|
| 1850 |
text = ~round(Value, 3),
|
| 1851 |
textposition = 'outside'
|
| 1852 |
) %>%
|
| 1853 |
layout(
|
| 1854 |
+
title = "Model Performance",
|
| 1855 |
yaxis = list(title = "Value", range = c(0, 1.1)),
|
| 1856 |
plot_bgcolor = "#0d1117",
|
| 1857 |
paper_bgcolor = "#161b22",
|
|
|
|
| 1859 |
)
|
| 1860 |
})
|
| 1861 |
|
|
|
|
| 1862 |
output$regression_plot_train <- renderPlotly({
|
| 1863 |
req(values$train_predictions)
|
|
|
|
| 1864 |
plot_ly(
|
| 1865 |
data = values$train_predictions,
|
| 1866 |
+
x = ~Observed, y = ~Predicted,
|
| 1867 |
+
type = 'scatter', mode = 'markers',
|
|
|
|
|
|
|
| 1868 |
marker = list(size = 6, color = '#58a6ff', opacity = 0.7)
|
| 1869 |
) %>%
|
| 1870 |
add_trace(
|
| 1871 |
x = range(values$train_predictions$Observed),
|
| 1872 |
y = range(values$train_predictions$Observed),
|
| 1873 |
+
type = 'scatter', mode = 'lines',
|
| 1874 |
+
line = list(color = '#f85149', dash = 'dash')
|
|
|
|
|
|
|
|
|
|
| 1875 |
) %>%
|
| 1876 |
layout(
|
| 1877 |
title = "Training Set",
|
|
|
|
| 1885 |
|
| 1886 |
output$regression_plot_test <- renderPlotly({
|
| 1887 |
req(values$test_predictions)
|
|
|
|
| 1888 |
plot_ly(
|
| 1889 |
data = values$test_predictions,
|
| 1890 |
+
x = ~Observed, y = ~Predicted,
|
| 1891 |
+
type = 'scatter', mode = 'markers',
|
|
|
|
|
|
|
| 1892 |
marker = list(size = 6, color = '#3fb950', opacity = 0.7)
|
| 1893 |
) %>%
|
| 1894 |
add_trace(
|
| 1895 |
x = range(values$test_predictions$Observed),
|
| 1896 |
y = range(values$test_predictions$Observed),
|
| 1897 |
+
type = 'scatter', mode = 'lines',
|
| 1898 |
+
line = list(color = '#f85149', dash = 'dash')
|
|
|
|
|
|
|
|
|
|
| 1899 |
) %>%
|
| 1900 |
layout(
|
| 1901 |
title = "Validation Set",
|
|
|
|
| 1907 |
)
|
| 1908 |
})
|
| 1909 |
|
|
|
|
| 1910 |
output$epistasis_heatmap <- renderPlotly({
|
| 1911 |
req(values$epistasis_all)
|
| 1912 |
|
|
|
|
| 1914 |
return(plot_ly() %>% layout(title = values$epistasis_all$Message[1]))
|
| 1915 |
}
|
| 1916 |
|
|
|
|
| 1917 |
qtls <- unique(values$epistasis_all$QTL1)
|
| 1918 |
markers <- unique(values$epistasis_all$QTL2)
|
| 1919 |
|
|
|
|
| 1927 |
}
|
| 1928 |
|
| 1929 |
plot_ly(
|
| 1930 |
+
x = colnames(p_matrix), y = rownames(p_matrix), z = p_matrix,
|
| 1931 |
+
type = "heatmap", colorscale = "Viridis",
|
| 1932 |
+
hovertemplate = "QTL: %{y}<br>Marker: %{x}<br>-log10(p): %{z:.2f}"
|
|
|
|
|
|
|
|
|
|
| 1933 |
) %>%
|
| 1934 |
layout(
|
| 1935 |
+
title = "Epistatic Interactions",
|
| 1936 |
xaxis = list(title = "Marker", tickangle = 45),
|
| 1937 |
yaxis = list(title = "QTL"),
|
| 1938 |
plot_bgcolor = "#0d1117",
|
|
|
|
| 1953 |
options = list(dom = 't')))
|
| 1954 |
}
|
| 1955 |
|
|
|
|
| 1956 |
display_cols <- intersect(
|
| 1957 |
c("Marker", "Chromosome", "Position", "LOD", "Additive_Effect",
|
| 1958 |
+
"PVE_Percent", "Low_Flank", "High_Flank"),
|
| 1959 |
colnames(values$qtl_effects_train)
|
| 1960 |
)
|
| 1961 |
|
| 1962 |
df <- values$qtl_effects_train[order(-values$qtl_effects_train$LOD), display_cols]
|
| 1963 |
|
| 1964 |
+
datatable(df, options = list(pageLength = 10, scrollX = TRUE), rownames = FALSE) %>%
|
| 1965 |
+
formatRound(intersect(c("LOD", "Additive_Effect", "PVE_Percent"), colnames(df)), 3)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1966 |
})
|
| 1967 |
|
| 1968 |
output$epistasis_table <- renderDT({
|
|
|
|
| 1975 |
|
| 1976 |
datatable(
|
| 1977 |
values$epistasis_sig[order(values$epistasis_sig$Interaction_p), ],
|
| 1978 |
+
options = list(pageLength = 10, scrollX = TRUE),
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1979 |
rownames = FALSE
|
| 1980 |
) %>%
|
| 1981 |
formatSignif(columns = c("Interaction_p", "Effect_Size"), digits = 4)
|
|
|
|
| 1989 |
options = list(dom = 't')))
|
| 1990 |
}
|
| 1991 |
|
|
|
|
| 1992 |
df <- values$selection_metrics
|
| 1993 |
if (!is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train)) {
|
| 1994 |
df$QTL_Overlap <- df$Marker %in% values$qtl_effects_train$Marker
|
| 1995 |
}
|
| 1996 |
|
| 1997 |
display_cols <- intersect(
|
| 1998 |
+
c("Marker", "Chromosome", "Fst", "Pi_Dom", "Pi_Wild", "Tajima_D_Dom", "Significant", "QTL_Overlap"),
|
|
|
|
| 1999 |
colnames(df)
|
| 2000 |
)
|
| 2001 |
|
| 2002 |
+
datatable(df[order(-df$Fst), display_cols],
|
| 2003 |
+
options = list(pageLength = 10, scrollX = TRUE),
|
| 2004 |
+
rownames = FALSE) %>%
|
| 2005 |
+
formatRound(c("Fst", "Pi_Dom", "Pi_Wild", "Tajima_D_Dom"), 3)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2006 |
})
|
| 2007 |
|
| 2008 |
# ============================================================
|
|
|
|
| 2016 |
return(div(class = "alert alert-info", values$lod_scores_train$Message[1]))
|
| 2017 |
}
|
| 2018 |
|
|
|
|
| 2019 |
chromosomes <- unique(values$lod_scores_train$Chromosome)
|
| 2020 |
|
| 2021 |
tagList(
|
| 2022 |
lapply(chromosomes, function(chr) {
|
|
|
|
| 2023 |
chr_markers <- values$all_markers[values$all_markers$Chromosome == chr, ]
|
| 2024 |
chr_markers <- chr_markers[order(chr_markers$Position), ]
|
|
|
|
|
|
|
| 2025 |
chr_qtls <- values$lod_scores_train[values$lod_scores_train$Chromosome == chr, ]
|
| 2026 |
|
|
|
|
| 2027 |
sel_markers <- NULL
|
| 2028 |
if (!is.null(values$selection_metrics) && !"Message" %in% colnames(values$selection_metrics)) {
|
| 2029 |
sel_markers <- values$selection_metrics[
|
| 2030 |
+
values$selection_metrics$Chromosome == chr & values$selection_metrics$Significant,
|
|
|
|
| 2031 |
]
|
| 2032 |
}
|
| 2033 |
|
|
|
|
| 2034 |
min_pos <- min(chr_markers$Position, na.rm = TRUE)
|
| 2035 |
max_pos <- max(chr_markers$Position, na.rm = TRUE)
|
| 2036 |
range_pos <- max_pos - min_pos
|
|
|
|
| 2038 |
div(class = "chromosome-container",
|
| 2039 |
div(class = "chromosome-title", paste("Chromosome", chr)),
|
| 2040 |
div(class = "chromosome",
|
|
|
|
| 2041 |
lapply(1:nrow(chr_markers), function(i) {
|
| 2042 |
marker <- chr_markers[i, ]
|
| 2043 |
+
left <- if (range_pos > 0) ((marker$Position - min_pos) / range_pos) * 100
|
| 2044 |
+
else (i / nrow(chr_markers)) * 100
|
|
|
|
|
|
|
|
|
|
| 2045 |
|
|
|
|
| 2046 |
marker_class <- "chromosome-marker"
|
| 2047 |
if (marker$Marker %in% chr_qtls$Marker) {
|
| 2048 |
marker_class <- paste(marker_class, "significant")
|
|
|
|
| 2052 |
marker_class <- paste(marker_class, "flanking")
|
| 2053 |
}
|
| 2054 |
|
| 2055 |
+
div(class = marker_class, style = paste0("left: ", left, "%;"))
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2056 |
})
|
| 2057 |
),
|
| 2058 |
div(class = "chromosome-legend",
|
|
|
|
| 2064 |
)
|
| 2065 |
})
|
| 2066 |
|
| 2067 |
+
# ============================================================
|
| 2068 |
+
# SIMULATION ANIMATIONS
|
| 2069 |
+
# ============================================================
|
| 2070 |
+
|
| 2071 |
observeEvent(input$simulate_btn, {
|
| 2072 |
session$sendCustomMessage("simulateQTLDiscovery", list())
|
| 2073 |
})
|
|
|
|
| 2095 |
div(class = "interpretation-section",
|
| 2096 |
tags$h5("Analysis Summary"),
|
| 2097 |
tags$p(paste(
|
| 2098 |
+
"Found", n_qtl, "QTLs above LOD", input$lod_threshold,
|
| 2099 |
+
if (has_perf) paste0("(validation R² = ", val_r2, ")"),
|
| 2100 |
+
if (has_epi) paste0("with", n_epi, "epistatic interactions"),
|
| 2101 |
+
if (has_sel) paste0("and", n_sel, "selection signatures.")
|
|
|
|
| 2102 |
))
|
| 2103 |
)
|
| 2104 |
})
|
|
|
|
| 2107 |
if (is.null(values$qtl_effects_train) || "Message" %in% colnames(values$qtl_effects_train)) {
|
| 2108 |
return(div(class = "interpretation-section",
|
| 2109 |
tags$h5("QTL Significance"),
|
| 2110 |
+
tags$p("No significant QTLs detected.")
|
| 2111 |
))
|
| 2112 |
}
|
| 2113 |
|
| 2114 |
top_qtl <- values$qtl_effects_train[which.max(values$qtl_effects_train$LOD), ]
|
|
|
|
|
|
|
| 2115 |
|
| 2116 |
div(class = "interpretation-section",
|
| 2117 |
tags$h5("QTL Significance"),
|
| 2118 |
tags$p(paste(
|
| 2119 |
+
"Top QTL:", top_qtl$Marker, "(Chr", top_qtl$Chromosome,
|
| 2120 |
+
") with LOD =", round(top_qtl$LOD, 2)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2121 |
))
|
| 2122 |
)
|
| 2123 |
})
|
|
|
|
| 2131 |
}
|
| 2132 |
|
| 2133 |
top_pve <- values$qtl_effects_train[which.max(values$qtl_effects_train$PVE_Percent), ]
|
|
|
|
| 2134 |
|
| 2135 |
div(class = "interpretation-section",
|
| 2136 |
tags$h5("Effect Sizes"),
|
| 2137 |
+
tags$p(paste(
|
| 2138 |
+
"Largest effect:", top_pve$Marker, "explains",
|
| 2139 |
+
round(top_pve$PVE_Percent, 1), "% of variance"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2140 |
))
|
| 2141 |
)
|
| 2142 |
})
|
|
|
|
| 2154 |
|
| 2155 |
div(class = "interpretation-section",
|
| 2156 |
tags$h5("Epistasis"),
|
| 2157 |
+
tags$p(paste(
|
| 2158 |
+
"Detected", n_epi, "interactions. Strongest:",
|
| 2159 |
+
top_epi$QTL1, "×", top_epi$QTL2,
|
| 2160 |
+
"(p =", format.pval(top_epi$Interaction_p), ")"
|
|
|
|
| 2161 |
))
|
| 2162 |
)
|
| 2163 |
})
|
| 2164 |
|
| 2165 |
output$recommendations <- renderUI({
|
| 2166 |
has_qtl <- !is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2167 |
|
| 2168 |
+
recs <- if (has_qtl) {
|
| 2169 |
+
c(
|
| 2170 |
+
"• Validate top QTLs in independent populations",
|
| 2171 |
+
"• Use flanking markers for fine-mapping",
|
| 2172 |
+
"• Check gene annotations in QTL regions"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2173 |
)
|
| 2174 |
} else {
|
| 2175 |
+
c(
|
| 2176 |
+
"• Upload data and run QTL analysis",
|
| 2177 |
+
"• Consider lowering LOD threshold",
|
| 2178 |
+
"• Check data quality"
|
|
|
|
| 2179 |
)
|
| 2180 |
}
|
| 2181 |
|
| 2182 |
div(class = "interpretation-section",
|
| 2183 |
tags$h5("Recommendations"),
|
| 2184 |
+
tags$ul(lapply(recs, tags$li), style = "color: #8b949e;")
|
|
|
|
|
|
|
|
|
|
| 2185 |
)
|
| 2186 |
})
|
| 2187 |
|
|
|
|
| 2190 |
# ============================================================
|
| 2191 |
|
| 2192 |
output$download_train_results <- downloadHandler(
|
| 2193 |
+
filename = function() paste0("qtl_results_", Sys.Date(), ".xlsx"),
|
|
|
|
|
|
|
| 2194 |
content = function(file) {
|
| 2195 |
sheets <- list()
|
|
|
|
| 2196 |
if (!is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train)) {
|
| 2197 |
+
sheets[["QTLs"]] <- values$qtl_effects_train
|
| 2198 |
}
|
|
|
|
| 2199 |
if (!is.null(values$performance_metrics)) {
|
| 2200 |
sheets[["Performance"]] <- values$performance_metrics
|
| 2201 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2202 |
write_xlsx(sheets, file)
|
| 2203 |
}
|
| 2204 |
)
|
| 2205 |
|
| 2206 |
output$download_selection <- downloadHandler(
|
| 2207 |
+
filename = function() paste0("selection_", Sys.Date(), ".xlsx"),
|
|
|
|
|
|
|
| 2208 |
content = function(file) {
|
| 2209 |
if (!is.null(values$selection_metrics) && !"Message" %in% colnames(values$selection_metrics)) {
|
| 2210 |
+
write_xlsx(list(Selection = values$selection_metrics), file)
|
| 2211 |
} else {
|
| 2212 |
+
write_xlsx(list(Message = "No results"), file)
|
| 2213 |
}
|
| 2214 |
}
|
| 2215 |
)
|