Spaces:
Sleeping
Sleeping
International Rice Research Institute commited on
Update app.R
Browse files
app.R
CHANGED
|
@@ -1,5 +1,20 @@
|
|
| 1 |
# ============================================================
|
| 2 |
# QTL-Mapper - With Model Selection & File Upload
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
# ============================================================
|
| 4 |
|
| 5 |
options(repos = c(CRAN = "https://cloud.r-project.org"))
|
|
@@ -20,21 +35,17 @@ for (pkg in required_packages) {
|
|
| 20 |
# ============================================================
|
| 21 |
# TOKEN DEBUG
|
| 22 |
# ============================================================
|
| 23 |
-
# STEP 1 - Get token
|
| 24 |
token <- Sys.getenv("GROQ_API_KEY")
|
| 25 |
|
| 26 |
-
# STEP 2 - Check token (must come right after)
|
| 27 |
token_exists <- token != ""
|
| 28 |
token_length <- if(token_exists) nchar(token) else 0
|
| 29 |
|
| 30 |
-
|
| 31 |
-
print("=== HUGGING FACE API TOKEN DEBUG ===")
|
| 32 |
print(paste("Token exists:", token_exists))
|
| 33 |
print(paste("Token length:", token_length))
|
| 34 |
if(token_exists) print(paste("Token starts with:", substr(token, 1, 10)))
|
| 35 |
print("===================================")
|
| 36 |
|
| 37 |
-
# STEP 4 - API config
|
| 38 |
HF_API_TOKEN <- token
|
| 39 |
HF_API_URL <- "https://api.groq.com/openai/v1/chat/completions"
|
| 40 |
default_model <- "llama-3.1-8b-instant"
|
|
@@ -46,8 +57,8 @@ default_model <- "llama-3.1-8b-instant"
|
|
| 46 |
available_models <- list(
|
| 47 |
list(id = "llama-3.1-8b-instant", label = "Llama 3.1 8B", provider = "groq", tier = "free"),
|
| 48 |
list(id = "llama-3.3-70b-versatile", label = "Llama 3.3 70B", provider = "groq", tier = "free"),
|
| 49 |
-
list(id = "meta-llama/llama-4-maverick-17b-128e-instruct",
|
| 50 |
-
list(id = "moonshotai/kimi-k2-instruct-0905", label = "
|
| 51 |
)
|
| 52 |
|
| 53 |
model_choices <- setNames(
|
|
@@ -55,23 +66,13 @@ model_choices <- setNames(
|
|
| 55 |
sapply(available_models, function(m) paste0(m$label, " [", m$tier, "]"))
|
| 56 |
)
|
| 57 |
|
| 58 |
-
# ============================================================
|
| 59 |
-
# API CONFIGURATION
|
| 60 |
-
# ============================================================
|
| 61 |
-
|
| 62 |
-
HF_API_TOKEN <- Sys.getenv("GROQ_API_KEY")
|
| 63 |
-
HF_API_URL <- "https://api.groq.com/openai/v1/chat/completions"
|
| 64 |
-
|
| 65 |
-
# Default model
|
| 66 |
-
default_model <- "llama-3.1-8b-instant"
|
| 67 |
-
|
| 68 |
# ============================================================
|
| 69 |
# TEST CONNECTION
|
| 70 |
# ============================================================
|
| 71 |
|
| 72 |
test_api_connection <- function(model_id = default_model) {
|
| 73 |
if (!token_exists) return(list(success = FALSE, error = "No token found"))
|
| 74 |
-
|
| 75 |
tryCatch({
|
| 76 |
response <- POST(
|
| 77 |
url = HF_API_URL,
|
|
@@ -87,10 +88,10 @@ test_api_connection <- function(model_id = default_model) {
|
|
| 87 |
encode = "json",
|
| 88 |
timeout(15)
|
| 89 |
)
|
| 90 |
-
|
| 91 |
status <- status_code(response)
|
| 92 |
if (status == 200) return(list(success = TRUE))
|
| 93 |
-
|
| 94 |
err <- tryCatch(content(response, "text", encoding = "UTF-8"),
|
| 95 |
error = function(e) paste("Status:", status))
|
| 96 |
return(list(success = FALSE,
|
|
@@ -114,7 +115,7 @@ if (use_hf_api) {
|
|
| 114 |
|
| 115 |
query_hf_api <- function(prompt, model_id = default_model, max_length = 500, temperature = 0.7) {
|
| 116 |
if (!token_exists) return(list(success = FALSE, error = "HF_API_TOKEN not set"))
|
| 117 |
-
|
| 118 |
tryCatch({
|
| 119 |
response <- POST(
|
| 120 |
url = HF_API_URL,
|
|
@@ -135,15 +136,15 @@ query_hf_api <- function(prompt, model_id = default_model, max_length = 500, tem
|
|
| 135 |
encode = "json",
|
| 136 |
timeout(60)
|
| 137 |
)
|
| 138 |
-
|
| 139 |
status <- status_code(response)
|
| 140 |
-
|
| 141 |
if (status == 200) {
|
| 142 |
result <- content(response, as = "parsed", encoding = "UTF-8")
|
| 143 |
text <- result$choices[[1]]$message$content
|
| 144 |
return(list(success = TRUE, text = text))
|
| 145 |
}
|
| 146 |
-
|
| 147 |
err <- tryCatch(content(response, "text", encoding = "UTF-8"),
|
| 148 |
error = function(e) paste("Status:", status))
|
| 149 |
return(list(success = FALSE,
|
|
@@ -157,25 +158,26 @@ query_hf_api <- function(prompt, model_id = default_model, max_length = 500, tem
|
|
| 157 |
|
| 158 |
build_system_prompt <- function(rv) {
|
| 159 |
context_parts <- c("CURRENT ANALYSIS RESULTS:")
|
| 160 |
-
|
| 161 |
if (!is.null(rv$qtl_effects_train) && !"Message" %in% colnames(rv$qtl_effects_train)) {
|
| 162 |
n_qtl <- nrow(rv$qtl_effects_train)
|
| 163 |
total_pve <- sum(rv$qtl_effects_train$PVE_Percent, na.rm = TRUE)
|
| 164 |
-
|
| 165 |
context_parts <- c(context_parts,
|
| 166 |
sprintf("\nQTL Results: %d significant QTLs detected above LOD %.1f.", n_qtl, rv$lod_threshold),
|
| 167 |
-
sprintf("Total variance explained by QTLs: %.1f%%.", total_pve))
|
| 168 |
-
|
| 169 |
top_qtls <- head(rv$qtl_effects_train[order(-rv$qtl_effects_train$LOD), ], 3)
|
| 170 |
context_parts <- c(context_parts, "\nTop QTLs:")
|
| 171 |
for (i in 1:nrow(top_qtls)) {
|
| 172 |
row <- top_qtls[i, ]
|
| 173 |
context_parts <- c(context_parts,
|
| 174 |
-
sprintf(" %d. %s (Chr %s): LOD=%.2f, PVE=%.1f%%, Additive=%.3f",
|
| 175 |
-
i, row$Marker, row$Chromosome, row$LOD, row$PVE_Percent,
|
|
|
|
| 176 |
}
|
| 177 |
}
|
| 178 |
-
|
| 179 |
if (!is.null(rv$performance_metrics)) {
|
| 180 |
pm <- rv$performance_metrics
|
| 181 |
train_r2 <- pm$Value[pm$Metric == "R\u00b2 (Train)"]
|
|
@@ -185,7 +187,7 @@ build_system_prompt <- function(rv) {
|
|
| 185 |
sprintf(" Training R\u00b2: %.3f", train_r2),
|
| 186 |
sprintf(" Validation R\u00b2: %.3f", val_r2))
|
| 187 |
}
|
| 188 |
-
|
| 189 |
if (!is.null(rv$epistasis_sig) && !"Message" %in% colnames(rv$epistasis_sig) && nrow(rv$epistasis_sig) > 0) {
|
| 190 |
n_epi <- nrow(rv$epistasis_sig)
|
| 191 |
top_epi <- rv$epistasis_sig[order(rv$epistasis_sig$Interaction_p), ][1, ]
|
|
@@ -193,13 +195,13 @@ build_system_prompt <- function(rv) {
|
|
| 193 |
sprintf("\nEpistasis: %d significant pairwise interactions detected.", n_epi),
|
| 194 |
sprintf(" Strongest: %s x %s (p=%.4f)", top_epi$QTL1, top_epi$QTL2, top_epi$Interaction_p))
|
| 195 |
}
|
| 196 |
-
|
| 197 |
if (!is.null(rv$selection_metrics) && !"Message" %in% colnames(rv$selection_metrics)) {
|
| 198 |
n_sig <- sum(rv$selection_metrics$Significant, na.rm = TRUE)
|
| 199 |
context_parts <- c(context_parts,
|
| 200 |
sprintf("\nDomestication: %d markers with selection signatures.", n_sig))
|
| 201 |
}
|
| 202 |
-
|
| 203 |
paste(context_parts, collapse = "\n")
|
| 204 |
}
|
| 205 |
|
|
@@ -209,20 +211,22 @@ build_system_prompt <- function(rv) {
|
|
| 209 |
|
| 210 |
enhanced_rule_response <- function(user_message, rv) {
|
| 211 |
q <- tolower(trimws(user_message))
|
| 212 |
-
|
| 213 |
has_qtl <- !is.null(rv$qtl_effects_train) && !"Message" %in% colnames(rv$qtl_effects_train)
|
| 214 |
has_perf <- !is.null(rv$performance_metrics)
|
| 215 |
has_epi <- !is.null(rv$epistasis_sig) && !"Message" %in% colnames(rv$epistasis_sig) && nrow(rv$epistasis_sig) > 0
|
| 216 |
has_sel <- !is.null(rv$selection_metrics) && !"Message" %in% colnames(rv$selection_metrics)
|
| 217 |
-
|
| 218 |
if (grepl("pve|variance explained|how much variance|percent variance|what is pve", q)) {
|
| 219 |
if (has_qtl) {
|
| 220 |
df <- rv$qtl_effects_train
|
| 221 |
total_pve <- sum(df$PVE_Percent, na.rm = TRUE)
|
| 222 |
top_pve <- df[which.max(df$PVE_Percent), ]
|
| 223 |
-
|
| 224 |
response <- paste0(
|
| 225 |
"\U0001f4ca **PVE (Phenotypic Variance Explained) Analysis**\n\n",
|
|
|
|
|
|
|
| 226 |
"**Your Results:**\n",
|
| 227 |
"\u2022 Total variance explained by all QTLs: **", round(total_pve, 1), "%**\n",
|
| 228 |
"\u2022 Number of QTLs detected: **", nrow(df), "**\n\n",
|
|
@@ -230,9 +234,11 @@ enhanced_rule_response <- function(user_message, rv) {
|
|
| 230 |
"\u2022 Marker: **", top_pve$Marker, "**\n",
|
| 231 |
"\u2022 Chromosome: ", top_pve$Chromosome, "\n",
|
| 232 |
"\u2022 PVE: **", round(top_pve$PVE_Percent, 1), "%**\n",
|
| 233 |
-
"\u2022 LOD: ", round(top_pve$LOD, 2), "\n
|
|
|
|
|
|
|
| 234 |
)
|
| 235 |
-
|
| 236 |
if (top_pve$PVE_Percent > 10) {
|
| 237 |
response <- paste0(response, "\U0001f4a1 This is a **major-effect QTL** (>10% PVE).\n\n")
|
| 238 |
} else if (top_pve$PVE_Percent > 5) {
|
|
@@ -240,31 +246,33 @@ enhanced_rule_response <- function(user_message, rv) {
|
|
| 240 |
} else {
|
| 241 |
response <- paste0(response, "\U0001f4a1 This is a **minor-effect QTL** (<5% PVE).\n\n")
|
| 242 |
}
|
| 243 |
-
|
| 244 |
response <- paste0(response, "**All QTLs by PVE:**\n")
|
| 245 |
df_sorted <- df[order(-df$PVE_Percent), ]
|
| 246 |
for (i in 1:min(5, nrow(df_sorted))) {
|
| 247 |
row <- df_sorted[i, ]
|
| 248 |
-
response <- paste0(response, sprintf(" %d. %s: %.1f%%
|
|
|
|
|
|
|
| 249 |
}
|
| 250 |
return(response)
|
| 251 |
} else {
|
| 252 |
return("No QTL results yet. Please run the QTL analysis first to see PVE values.")
|
| 253 |
}
|
| 254 |
}
|
| 255 |
-
|
| 256 |
if (grepl("model performance|r2|r squared|how good is my model|validation|negative r2", q)) {
|
| 257 |
if (has_perf) {
|
| 258 |
pm <- rv$performance_metrics
|
| 259 |
train_r2 <- pm$Value[pm$Metric == "R\u00b2 (Train)"]
|
| 260 |
val_r2 <- pm$Value[pm$Metric == "R\u00b2 (Validation)"]
|
| 261 |
-
|
| 262 |
response <- paste0(
|
| 263 |
"\U0001f4c8 **Model Performance Summary**\n\n",
|
| 264 |
"\u2022 Training R\u00b2: **", round(train_r2, 3), "**\n",
|
| 265 |
"\u2022 Validation R\u00b2: **", round(val_r2, 3), "**\n\n"
|
| 266 |
)
|
| 267 |
-
|
| 268 |
if (val_r2 < 0) {
|
| 269 |
response <- paste0(response,
|
| 270 |
"\u26a0\ufe0f **Your validation R\u00b2 is negative** (", round(val_r2, 3), ").\n\n",
|
|
@@ -288,31 +296,33 @@ enhanced_rule_response <- function(user_message, rv) {
|
|
| 288 |
return("Run the QTL analysis first to see model performance metrics.")
|
| 289 |
}
|
| 290 |
}
|
| 291 |
-
|
| 292 |
if (grepl("top qtl|best qtl|highest lod|significant qtl|list qtl|show qtl", q)) {
|
| 293 |
if (has_qtl) {
|
| 294 |
df <- rv$qtl_effects_train[order(-rv$qtl_effects_train$LOD), ]
|
| 295 |
top5 <- head(df, 5)
|
| 296 |
-
|
| 297 |
response <- "\U0001f3af **Top 5 QTLs by LOD Score**\n\n"
|
| 298 |
for (i in 1:nrow(top5)) {
|
| 299 |
row <- top5[i, ]
|
|
|
|
| 300 |
response <- paste0(response,
|
| 301 |
i, ". **", row$Marker, "** (Chr ", row$Chromosome, ")\n",
|
| 302 |
" \u2022 LOD: **", round(row$LOD, 2), "**\n",
|
| 303 |
-
" \u2022 PVE: ", round(row$PVE_Percent, 1), "%\n",
|
| 304 |
-
" \u2022 Additive effect: ", round(row$Additive_Effect, 3), "\n
|
|
|
|
| 305 |
}
|
| 306 |
return(response)
|
| 307 |
} else {
|
| 308 |
return("No significant QTLs detected. Try lowering the LOD threshold.")
|
| 309 |
}
|
| 310 |
}
|
| 311 |
-
|
| 312 |
if (grepl("next steps|what next|recommendations|suggest|advice|what should i do", q)) {
|
| 313 |
if (has_qtl || has_perf || has_epi || has_sel) {
|
| 314 |
response <- "\U0001f52c **Recommended Next Steps**\n\n"
|
| 315 |
-
|
| 316 |
if (has_qtl) {
|
| 317 |
top_qtl <- rv$qtl_effects_train[which.max(rv$qtl_effects_train$LOD), ]
|
| 318 |
response <- paste0(response,
|
|
@@ -328,7 +338,7 @@ enhanced_rule_response <- function(user_message, rv) {
|
|
| 328 |
response <- paste0(response, "**3. Domestication Analysis**\n",
|
| 329 |
" \u2022 ", sum(rv$selection_metrics$Significant, na.rm = TRUE), " selection signatures\n\n")
|
| 330 |
}
|
| 331 |
-
|
| 332 |
response <- paste0(response,
|
| 333 |
"**4. Functional Analysis**\n",
|
| 334 |
" \u2022 Annotate QTL regions for candidate genes\n\n",
|
|
@@ -339,7 +349,7 @@ enhanced_rule_response <- function(user_message, rv) {
|
|
| 339 |
return("Run the QTL analysis first to get recommendations.")
|
| 340 |
}
|
| 341 |
}
|
| 342 |
-
|
| 343 |
available <- c()
|
| 344 |
if (has_qtl) available <- c(available, paste(nrow(rv$qtl_effects_train), "QTLs"))
|
| 345 |
if (has_perf) {
|
|
@@ -348,7 +358,7 @@ enhanced_rule_response <- function(user_message, rv) {
|
|
| 348 |
}
|
| 349 |
if (has_epi) available <- c(available, paste(nrow(rv$epistasis_sig), "interactions"))
|
| 350 |
if (has_sel) available <- c(available, paste(sum(rv$selection_metrics$Significant), "selection signatures"))
|
| 351 |
-
|
| 352 |
if (length(available) > 0) {
|
| 353 |
return(paste0(
|
| 354 |
"I can see you have: ", paste(available, collapse = ", "), ".\n\n",
|
|
@@ -358,16 +368,15 @@ enhanced_rule_response <- function(user_message, rv) {
|
|
| 358 |
"\u2022 **Model performance**\n",
|
| 359 |
"\u2022 **Next steps**"))
|
| 360 |
}
|
| 361 |
-
|
| 362 |
return(paste0(
|
| 363 |
"\U0001f44b Vanakam! I'm TerraByte-AI powered Companion.\n\n",
|
| 364 |
"**I can help you with:**\n",
|
| 365 |
-
"\u2022 Understanding PVE\n",
|
| 366 |
"\u2022 Interpreting LOD scores\n",
|
| 367 |
"\u2022 Evaluating model performance\n",
|
| 368 |
"\u2022 Detecting epistatic interactions\n\n",
|
| 369 |
"\u2022 any query? contact : ashmithamganesan@gmail.com, P.sinha@cgiar.org\n\n",
|
| 370 |
-
|
| 371 |
"Try: **'What is PVE?'** or **'Show me my top QTLs'**"))
|
| 372 |
}
|
| 373 |
|
|
@@ -377,9 +386,9 @@ enhanced_rule_response <- function(user_message, rv) {
|
|
| 377 |
|
| 378 |
generate_ai_response <- function(user_message, rv, model_id = default_model) {
|
| 379 |
context <- build_system_prompt(rv)
|
| 380 |
-
|
| 381 |
current_use_api <- token_exists
|
| 382 |
-
|
| 383 |
if (current_use_api) {
|
| 384 |
prompt <- paste(
|
| 385 |
"CONTEXT:", context,
|
|
@@ -387,9 +396,9 @@ generate_ai_response <- function(user_message, rv, model_id = default_model) {
|
|
| 387 |
"\n\nProvide a specific, helpful answer based ONLY on the context above. Be concise but informative.",
|
| 388 |
sep = "\n"
|
| 389 |
)
|
| 390 |
-
|
| 391 |
result <- query_hf_api(prompt, model_id = model_id)
|
| 392 |
-
|
| 393 |
if (result$success) {
|
| 394 |
return(result$text)
|
| 395 |
} else {
|
|
@@ -397,7 +406,7 @@ generate_ai_response <- function(user_message, rv, model_id = default_model) {
|
|
| 397 |
return(enhanced_rule_response(user_message, rv))
|
| 398 |
}
|
| 399 |
}
|
| 400 |
-
|
| 401 |
return(enhanced_rule_response(user_message, rv))
|
| 402 |
}
|
| 403 |
|
|
@@ -407,7 +416,7 @@ generate_ai_response <- function(user_message, rv, model_id = default_model) {
|
|
| 407 |
|
| 408 |
ui <- fluidPage(
|
| 409 |
shinyjs::useShinyjs(),
|
| 410 |
-
|
| 411 |
tags$head(
|
| 412 |
tags$link(rel = "stylesheet", type = "text/css",
|
| 413 |
href = "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css"),
|
|
@@ -436,29 +445,18 @@ ui <- fluidPage(
|
|
| 436 |
}
|
| 437 |
Shiny.addCustomMessageHandler('simulateQTLDiscovery', function(message) { simulateQTLDiscovery(); });
|
| 438 |
Shiny.addCustomMessageHandler('resetAnimation', function(message) { resetAnimation(); });
|
| 439 |
-
|
| 440 |
Shiny.addCustomMessageHandler('scrollChatBottom', function(message) {
|
| 441 |
setTimeout(function() {
|
| 442 |
var chatBox = document.getElementById('chat_messages');
|
| 443 |
if (chatBox) chatBox.scrollTop = chatBox.scrollHeight;
|
| 444 |
}, 100);
|
| 445 |
});
|
| 446 |
-
|
| 447 |
$(document).on('keydown', '#chat_input', function(e) {
|
| 448 |
if (e.key === 'Enter' && !e.shiftKey) {
|
| 449 |
e.preventDefault();
|
| 450 |
$('#send_chat').click();
|
| 451 |
}
|
| 452 |
});
|
| 453 |
-
|
| 454 |
-
// File preview in chat
|
| 455 |
-
function previewChatFile(input) {
|
| 456 |
-
const file = input.files[0];
|
| 457 |
-
if (!file) return;
|
| 458 |
-
const preview = document.getElementById('chat_file_preview');
|
| 459 |
-
preview.innerHTML = '<span style=\"color:#58a6ff\"><i class=\"fas fa-paperclip\"></i> ' + file.name + ' (' + (file.size/1024).toFixed(1) + ' KB)</span>';
|
| 460 |
-
preview.style.display = 'block';
|
| 461 |
-
}
|
| 462 |
")),
|
| 463 |
tags$style(HTML("
|
| 464 |
:root {
|
|
@@ -478,6 +476,8 @@ ui <- fluidPage(
|
|
| 478 |
.main-header { background: linear-gradient(135deg, #1c2b3a 0%, #0d1117 100%); border: 1px solid var(--border); border-left: 3px solid var(--accent); color: var(--text-primary); padding: 20px 24px; border-radius: 6px; margin-bottom: 20px; }
|
| 479 |
.main-header h2 { font-family: var(--font-mono); font-size: 1.3rem; font-weight: 600; color: var(--accent); }
|
| 480 |
.main-header p { color: var(--text-secondary); margin-top: 6px; font-size: 13px; }
|
|
|
|
|
|
|
| 481 |
.card { background-color: var(--bg-secondary); border: 1px solid var(--border); border-radius: 6px; margin-bottom: 20px; }
|
| 482 |
.card-header { background-color: var(--bg-tertiary); border-bottom: 1px solid var(--border); padding: 12px 16px; font-family: var(--font-mono); font-size: 12px; color: var(--text-secondary); letter-spacing: 0.5px; text-transform: uppercase; }
|
| 483 |
.card-body { padding: 16px; }
|
|
@@ -516,7 +516,6 @@ ui <- fluidPage(
|
|
| 516 |
.simulation-controls { margin: 12px 0; display: flex; gap: 8px; }
|
| 517 |
.simulation-btn { background-color: transparent; color: var(--purple); border: 1px solid var(--purple); padding: 5px 12px; border-radius: 4px; cursor: pointer; font-family: var(--font-mono); font-size: 11px; transition: all 0.15s; }
|
| 518 |
.simulation-btn:hover { background-color: var(--purple); color: #0d1117; }
|
| 519 |
-
|
| 520 |
/* ---- Chat Panel ---- */
|
| 521 |
#chat-panel { position: fixed; bottom: 20px; right: 20px; z-index: 9999; width: 440px; display: flex; flex-direction: column; }
|
| 522 |
#chat-toggle-btn { align-self: flex-end; width: 56px; height: 56px; border-radius: 50%; background: linear-gradient(135deg, var(--accent), var(--purple)); border: none; cursor: pointer; display: flex; align-items: center; justify-content: center; box-shadow: 0 4px 20px rgba(88,166,255,0.4); transition: all 0.2s; color: #0d1117; font-size: 24px; }
|
|
@@ -533,8 +532,6 @@ ui <- fluidPage(
|
|
| 533 |
#chat-header p.rule-mode { color: var(--warning); }
|
| 534 |
#chat-close-btn { background: none; border: none; color: var(--text-muted); cursor: pointer; font-size: 18px; padding: 4px; transition: color 0.15s; flex-shrink: 0; }
|
| 535 |
#chat-close-btn:hover { color: var(--text-primary); }
|
| 536 |
-
|
| 537 |
-
/* Model selector in chat */
|
| 538 |
.chat-model-selector { display: flex; align-items: center; gap: 8px; padding: 4px 0; }
|
| 539 |
.chat-model-selector label { color: var(--text-muted); font-size: 10px; font-family: var(--font-mono); white-space: nowrap; margin: 0; }
|
| 540 |
.chat-model-selector select { flex: 1; background: var(--bg-primary) !important; border: 1px solid var(--border) !important; color: var(--text-secondary) !important; border-radius: 4px; font-size: 11px; font-family: var(--font-mono); padding: 3px 6px; cursor: pointer; }
|
|
@@ -544,7 +541,6 @@ ui <- fluidPage(
|
|
| 544 |
.model-status-dot.offline { background: var(--warning); box-shadow: 0 0 6px var(--warning); }
|
| 545 |
.test-model-btn { background: transparent; border: 1px solid var(--border); color: var(--text-muted); border-radius: 3px; padding: 2px 7px; font-size: 10px; font-family: var(--font-mono); cursor: pointer; transition: all 0.15s; white-space: nowrap; }
|
| 546 |
.test-model-btn:hover { border-color: var(--accent); color: var(--accent); }
|
| 547 |
-
|
| 548 |
#chat_messages { flex: 1; overflow-y: auto; padding: 16px; display: flex; flex-direction: column; gap: 12px; background: var(--bg-primary); }
|
| 549 |
.chat-msg { max-width: 92%; animation: fadeIn 0.3s ease; }
|
| 550 |
@keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
|
|
@@ -561,18 +557,12 @@ ui <- fluidPage(
|
|
| 561 |
.typing-dot:nth-child(2) { animation-delay: 0.2s; }
|
| 562 |
.typing-dot:nth-child(3) { animation-delay: 0.4s; }
|
| 563 |
@keyframes typingBounce { 0%, 60%, 100% { transform: translateY(0); } 30% { transform: translateY(-8px); } }
|
| 564 |
-
|
| 565 |
-
/* Chat quick questions */
|
| 566 |
.quick-questions { padding: 8px 16px; display: flex; flex-wrap: wrap; gap: 6px; border-bottom: 1px solid var(--border); background: var(--bg-secondary); }
|
| 567 |
.quick-q-btn { background: var(--bg-tertiary); border: 1px solid var(--border); color: var(--text-secondary); border-radius: 16px; padding: 4px 12px; font-size: 11px; cursor: pointer; transition: all 0.15s; }
|
| 568 |
.quick-q-btn:hover { border-color: var(--accent); color: var(--accent); background: rgba(88,166,255,0.1); }
|
| 569 |
-
|
| 570 |
-
/* Chat footer */
|
| 571 |
#chat-footer { padding: 12px 16px; border-top: 1px solid var(--border); background: var(--bg-tertiary); }
|
| 572 |
#chat_input { width: 100%; background: var(--bg-secondary) !important; border: 1px solid var(--border) !important; border-radius: 8px; color: var(--text-primary) !important; font-size: 13px; resize: none; padding: 10px 12px; font-family: var(--font-sans); margin-bottom: 8px; }
|
| 573 |
#chat_input:focus { border-color: var(--accent) !important; outline: none; }
|
| 574 |
-
|
| 575 |
-
/* File upload in chat */
|
| 576 |
.chat-file-row { display: flex; align-items: center; gap: 8px; margin-bottom: 8px; }
|
| 577 |
#chat_file_upload_btn { background: transparent; border: 1px solid var(--border); color: var(--text-muted); border-radius: 6px; padding: 6px 10px; font-size: 12px; cursor: pointer; transition: all 0.15s; display: flex; align-items: center; gap: 5px; white-space: nowrap; }
|
| 578 |
#chat_file_upload_btn:hover { border-color: var(--accent); color: var(--accent); }
|
|
@@ -585,23 +575,34 @@ ui <- fluidPage(
|
|
| 585 |
#send_chat:disabled { opacity: 0.5; cursor: not-allowed; }
|
| 586 |
#clear_chat { background: transparent; color: var(--text-muted); border: 1px solid var(--border); border-radius: 6px; padding: 8px 12px; font-family: var(--font-mono); font-size: 12px; cursor: pointer; transition: all 0.15s; }
|
| 587 |
#clear_chat:hover { border-color: var(--danger); color: var(--danger); }
|
| 588 |
-
|
| 589 |
-
/* File message bubble in chat */
|
| 590 |
-
.chat-file-bubble { background: rgba(88,166,255,0.1); border: 1px solid rgba(88,166,255,0.3); border-radius: 8px; padding: 8px 12px; margin-bottom: 4px; font-size: 12px; font-family: var(--font-mono); color: var(--accent); display: flex; align-items: center; gap: 8px; }
|
| 591 |
-
.chat-file-bubble i { font-size: 14px; }
|
| 592 |
"))
|
| 593 |
),
|
| 594 |
-
|
| 595 |
navbarPage(
|
| 596 |
title = tags$span(tags$i(class = "fas fa-dna", style = "margin-right:8px; color:#58a6ff;"), "QTL-Mapper AI"),
|
| 597 |
id = "nav",
|
| 598 |
-
|
| 599 |
# ---- Data Upload tab ----
|
| 600 |
tabPanel("Data Upload", icon = icon("upload"),
|
| 601 |
div(class = "main-header",
|
| 602 |
h2(tags$i(class = "fas fa-upload", style = "margin-right:8px;"), "Data Upload"),
|
| 603 |
p("Upload genotype, phenotype, and population data for comprehensive QTL analysis with AI assistance")
|
| 604 |
),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 605 |
fluidRow(
|
| 606 |
column(4,
|
| 607 |
div(class = "card",
|
|
@@ -653,7 +654,7 @@ ui <- fluidPage(
|
|
| 653 |
)
|
| 654 |
)
|
| 655 |
),
|
| 656 |
-
|
| 657 |
# ---- Domestication tab ----
|
| 658 |
tabPanel("Domestication", icon = icon("leaf"),
|
| 659 |
div(class = "main-header",
|
|
@@ -697,12 +698,12 @@ ui <- fluidPage(
|
|
| 697 |
)
|
| 698 |
)
|
| 699 |
),
|
| 700 |
-
|
| 701 |
# ---- Results tab ----
|
| 702 |
tabPanel("Results", icon = icon("chart-line"),
|
| 703 |
div(class = "main-header",
|
| 704 |
h2(tags$i(class = "fas fa-chart-line", style = "margin-right:8px;"), "QTL Analysis Results"),
|
| 705 |
-
p("LOD scores, QTL effects, model performance, and epistasis analysis")
|
| 706 |
),
|
| 707 |
fluidRow(
|
| 708 |
column(6, div(class = "card", div(class = "card-header", "Manhattan Plot (LOD Scores)"), div(class = "card-body", plotlyOutput("lod_plot_2d", height = "500px")))),
|
|
@@ -724,7 +725,7 @@ ui <- fluidPage(
|
|
| 724 |
),
|
| 725 |
fluidRow(
|
| 726 |
column(12, div(class = "card",
|
| 727 |
-
div(class = "card-header", "QTL Effects
|
| 728 |
div(class = "card-body", DTOutput("qtl_effects_table_train"), tags$br(), downloadButton("download_train_results", "Download"))
|
| 729 |
))
|
| 730 |
),
|
|
@@ -738,22 +739,22 @@ ui <- fluidPage(
|
|
| 738 |
))
|
| 739 |
)
|
| 740 |
),
|
| 741 |
-
|
| 742 |
# ---- Interpretation tab ----
|
| 743 |
tabPanel("Interpretation", icon = icon("lightbulb"),
|
| 744 |
div(class = "main-header",
|
| 745 |
h2(tags$i(class = "fas fa-lightbulb", style = "margin-right:8px;"), "Results Interpretation"),
|
| 746 |
-
p("Comprehensive interpretation of QTL and domestication analysis")
|
| 747 |
),
|
| 748 |
fluidRow(column(12, div(class = "card", div(class = "card-header", "Analysis Summary"), div(class = "card-body", uiOutput("analysis_summary"))))),
|
| 749 |
fluidRow(
|
| 750 |
column(6, div(class = "card", div(class = "card-header", "QTL Significance"), div(class = "card-body", uiOutput("qtl_interpretation")))),
|
| 751 |
-
column(6, div(class = "card", div(class = "card-header", "Effect Sizes"),
|
| 752 |
),
|
| 753 |
fluidRow(column(12, div(class = "card", div(class = "card-header", "Epistasis"), div(class = "card-body", uiOutput("epistasis_interpretation"))))),
|
| 754 |
fluidRow(column(12, div(class = "card", div(class = "card-header", "Recommendations"), div(class = "card-body", uiOutput("recommendations")))))
|
| 755 |
),
|
| 756 |
-
|
| 757 |
# ---- About tab ----
|
| 758 |
tabPanel("About", icon = icon("info-circle"),
|
| 759 |
div(class = "main-header",
|
|
@@ -764,43 +765,30 @@ ui <- fluidPage(
|
|
| 764 |
column(8, offset = 2,
|
| 765 |
div(class = "card",
|
| 766 |
div(class = "card-body",
|
| 767 |
-
h4(style = "color:#58a6ff; font-family:'IBM Plex Mono'; margin-bottom:12px;", "
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 768 |
tags$ul(style = "color:#8b949e; line-height:2;",
|
| 769 |
tags$li("Random Forest for QTL mapping with variable importance scoring"),
|
| 770 |
tags$li("LOD scores derived from marker importance (-log10 scale)"),
|
| 771 |
-
tags$li("Additive and dominance effects
|
|
|
|
|
|
|
| 772 |
tags$li("Epistasis analysis: pairwise QTL x marker interactions"),
|
| 773 |
-
tags$li("Domestication: Fst, nucleotide diversity (Pi), Tajima's D")
|
| 774 |
-
tags$li("AI Assistant powered by multiple transformer models via Hugging Face Router API")
|
| 775 |
-
),
|
| 776 |
-
h4(style = "color:#58a6ff; font-family:'IBM Plex Mono'; margin:12px 0;", "Available AI Models"),
|
| 777 |
-
tags$table(style = "width:100%; color:#8b949e; border-collapse: collapse;",
|
| 778 |
-
tags$thead(tags$tr(
|
| 779 |
-
tags$th(style = "text-align:left; padding:6px; border-bottom:1px solid #30363d; color:#58a6ff;", "Model"),
|
| 780 |
-
tags$th(style = "text-align:left; padding:6px; border-bottom:1px solid #30363d; color:#58a6ff;", "Provider"),
|
| 781 |
-
tags$th(style = "text-align:left; padding:6px; border-bottom:1px solid #30363d; color:#58a6ff;", "Tier")
|
| 782 |
-
)),
|
| 783 |
-
tags$tbody(
|
| 784 |
-
lapply(available_models, function(m) {
|
| 785 |
-
tags$tr(
|
| 786 |
-
tags$td(style = "padding:6px; border-bottom:1px solid #21262d;", m$label),
|
| 787 |
-
tags$td(style = "padding:6px; border-bottom:1px solid #21262d;", m$provider),
|
| 788 |
-
tags$td(style = "padding:6px; border-bottom:1px solid #21262d;", tags$span(style = "color:#3fb950;", m$tier))
|
| 789 |
-
)
|
| 790 |
-
})
|
| 791 |
-
)
|
| 792 |
-
),
|
| 793 |
-
h4(style = "color:#58a6ff; font-family:'IBM Plex Mono'; margin:12px 0;", "AI Assistant Status"),
|
| 794 |
-
p(style = "color:#8b949e;",
|
| 795 |
-
if (token_exists) paste("\u2705 HF_API_TOKEN found. Select a model in the chat panel to get started.")
|
| 796 |
-
else "\u26a0\ufe0f No HF_API_TOKEN found. Set it in Space secrets to enable AI mode."
|
| 797 |
),
|
| 798 |
h4(style = "color:#58a6ff; font-family:'IBM Plex Mono'; margin:12px 0;", "Interpretation Thresholds"),
|
| 799 |
tags$ul(style = "color:#8b949e; line-height:2;",
|
| 800 |
tags$li("LOD > 3: Suggestive QTL | LOD > 5: Significant QTL"),
|
|
|
|
|
|
|
| 801 |
tags$li("Fst > 0.2: Strong population differentiation"),
|
| 802 |
-
tags$li("Tajima's D < -2: Potential selective sweep")
|
| 803 |
-
tags$li("PVE > 10%: Major-effect QTL")
|
| 804 |
)
|
| 805 |
)
|
| 806 |
)
|
|
@@ -808,14 +796,13 @@ ui <- fluidPage(
|
|
| 808 |
)
|
| 809 |
)
|
| 810 |
),
|
| 811 |
-
|
| 812 |
# ============================================================
|
| 813 |
-
# FLOATING CHAT PANEL
|
| 814 |
# ============================================================
|
| 815 |
tags$div(id = "chat-panel",
|
| 816 |
tags$div(id = "chat-window",
|
| 817 |
-
|
| 818 |
-
# Chat header
|
| 819 |
tags$div(id = "chat-header",
|
| 820 |
tags$div(class = "chat-header-top",
|
| 821 |
tags$div(class = "chat-title",
|
|
@@ -831,8 +818,6 @@ ui <- fluidPage(
|
|
| 831 |
onclick = "document.getElementById('chat-window').classList.remove('open');",
|
| 832 |
tags$i(class = "fas fa-times"))
|
| 833 |
),
|
| 834 |
-
|
| 835 |
-
# Model selector row
|
| 836 |
tags$div(class = "chat-model-selector",
|
| 837 |
tags$label(tags$i(class = "fas fa-robot"), " Model:"),
|
| 838 |
tags$div(id = "model_status_dot", class = paste0("model-status-dot ", if (token_exists) "online" else "offline")),
|
|
@@ -843,22 +828,17 @@ ui <- fluidPage(
|
|
| 843 |
actionButton("test_model_btn", "Test", class = "test-model-btn")
|
| 844 |
)
|
| 845 |
),
|
| 846 |
-
|
| 847 |
-
# Quick question buttons
|
| 848 |
tags$div(class = "quick-questions",
|
| 849 |
tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q','What is PVE?',{priority:'event'});", "PVE meaning"),
|
| 850 |
tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q','What are my top QTLs?',{priority:'event'});", "Top QTLs"),
|
| 851 |
tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q','Why is my R2 negative?',{priority:'event'});","Negative R2"),
|
| 852 |
tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q','What should I do next?',{priority:'event'});","Next steps")
|
| 853 |
),
|
| 854 |
-
|
| 855 |
-
# Messages area
|
| 856 |
tags$div(id = "chat_messages", uiOutput("chat_display")),
|
| 857 |
-
|
| 858 |
-
# Footer
|
| 859 |
tags$div(id = "chat-footer",
|
| 860 |
-
|
| 861 |
-
# File upload row
|
| 862 |
tags$div(class = "chat-file-row",
|
| 863 |
tags$label(
|
| 864 |
id = "chat_file_upload_btn",
|
|
@@ -875,27 +855,20 @@ ui <- fluidPage(
|
|
| 875 |
onclick = "document.getElementById('chat_file_preview').style.display='none'; document.getElementById('chat_file_preview').innerHTML=''; Shiny.setInputValue('clear_chat_file', Math.random());",
|
| 876 |
tags$i(class = "fas fa-times"))
|
| 877 |
),
|
| 878 |
-
|
| 879 |
-
# Text input
|
| 880 |
tags$textarea(id = "chat_input",
|
| 881 |
placeholder = "Ask about your results... (Enter to send)",
|
| 882 |
rows = "2"),
|
| 883 |
-
|
| 884 |
-
# Action buttons
|
| 885 |
tags$div(class = "chat-actions",
|
| 886 |
actionButton("send_chat", "Send", icon = icon("paper-plane"), class = "btn-primary"),
|
| 887 |
actionButton("clear_chat", "Clear", icon = icon("trash-alt"), class = "btn-danger")
|
| 888 |
)
|
| 889 |
)
|
| 890 |
),
|
| 891 |
-
|
| 892 |
-
# Toggle button
|
| 893 |
tags$button(id = "chat-toggle-btn",
|
| 894 |
onclick = "document.getElementById('chat-window').classList.toggle('open');",
|
| 895 |
tags$i(class = "fas fa-robot"))
|
| 896 |
),
|
| 897 |
-
|
| 898 |
-
# JS to show filename on file selection
|
| 899 |
tags$script(HTML("
|
| 900 |
$(document).on('change', '#chat_file_upload', function() {
|
| 901 |
var file = this.files[0];
|
|
@@ -913,7 +886,7 @@ ui <- fluidPage(
|
|
| 913 |
# ============================================================
|
| 914 |
|
| 915 |
server <- function(input, output, session) {
|
| 916 |
-
|
| 917 |
values <- reactiveValues(
|
| 918 |
genotype_data = NULL,
|
| 919 |
phenotype_data = NULL,
|
|
@@ -927,7 +900,6 @@ server <- function(input, output, session) {
|
|
| 927 |
model_fit = NULL,
|
| 928 |
phenotype_values = NULL,
|
| 929 |
qtl_effects_train = NULL,
|
| 930 |
-
qtl_effects_test = NULL,
|
| 931 |
performance_metrics = NULL,
|
| 932 |
train_predictions = NULL,
|
| 933 |
test_predictions = NULL,
|
|
@@ -940,42 +912,34 @@ server <- function(input, output, session) {
|
|
| 940 |
is_typing = FALSE,
|
| 941 |
lod_threshold = 2,
|
| 942 |
current_model = default_model,
|
| 943 |
-
model_test_status = if (use_hf_api) "online" else "offline",
|
| 944 |
pending_file_content = NULL,
|
| 945 |
pending_file_name = NULL
|
| 946 |
)
|
| 947 |
-
|
| 948 |
-
# ----
|
| 949 |
observe({
|
| 950 |
req(input$selected_model)
|
| 951 |
values$current_model <- input$selected_model
|
| 952 |
-
|
| 953 |
-
# Update status display
|
| 954 |
model_label <- names(model_choices)[model_choices == input$selected_model]
|
| 955 |
-
if (is.null(model_label) || length(model_label) == 0)
|
| 956 |
-
model_label <- gsub(".*/([^:]+):.*", "\\1", input$selected_model)
|
| 957 |
-
|
| 958 |
shinyjs::html("model_status_text",
|
| 959 |
if (token_exists) paste("AI:", gsub(".*\\[(.*)\\]", "\\1", model_label), "- ready")
|
| 960 |
else "Rule-based mode (no token)")
|
| 961 |
})
|
| 962 |
-
|
| 963 |
-
# ---- Test model
|
| 964 |
observeEvent(input$test_model_btn, {
|
| 965 |
req(input$selected_model)
|
| 966 |
add_message("assistant", paste0("\u23f3 Testing model: **", gsub(".*/", "", input$selected_model), "**..."))
|
| 967 |
-
|
| 968 |
result <- test_api_connection(input$selected_model)
|
| 969 |
if (result$success) {
|
| 970 |
-
add_message("assistant", paste0("\u2705 **", gsub(".*/", "", input$selected_model), "** is working!
|
| 971 |
shinyjs::runjs("document.getElementById('model_status_dot').className = 'model-status-dot online';")
|
| 972 |
} else {
|
| 973 |
-
add_message("assistant", paste0("\u274c
|
| 974 |
-
"\n\nTry another model or check your HF_API_TOKEN."))
|
| 975 |
shinyjs::runjs("document.getElementById('model_status_dot').className = 'model-status-dot offline';")
|
| 976 |
}
|
| 977 |
})
|
| 978 |
-
|
| 979 |
# ---- Chat helpers ----
|
| 980 |
add_message <- function(role, content, model_used = NULL) {
|
| 981 |
timestamp <- format(Sys.time(), "%H:%M")
|
|
@@ -986,11 +950,10 @@ server <- function(input, output, session) {
|
|
| 986 |
values$chat_messages <- tail(values$chat_messages, 100)
|
| 987 |
session$sendCustomMessage("scrollChatBottom", list())
|
| 988 |
}
|
| 989 |
-
|
| 990 |
process_message <- function(user_text, file_content = NULL, file_name = NULL) {
|
| 991 |
if (nchar(trimws(user_text)) == 0 && is.null(file_content)) return()
|
| 992 |
-
|
| 993 |
-
# Build full message including file content if present
|
| 994 |
full_message <- user_text
|
| 995 |
if (!is.null(file_content) && nchar(trimws(file_content)) > 0) {
|
| 996 |
full_message <- paste0(user_text,
|
|
@@ -999,116 +962,104 @@ server <- function(input, output, session) {
|
|
| 999 |
substr(file_content, 1, 3000),
|
| 1000 |
if (nchar(file_content) > 3000) "\n[... truncated ...]" else "")
|
| 1001 |
}
|
| 1002 |
-
|
| 1003 |
add_message("user", full_message)
|
| 1004 |
values$is_typing <- TRUE
|
| 1005 |
-
|
| 1006 |
model_id <- isolate(values$current_model)
|
| 1007 |
response <- generate_ai_response(full_message, values, model_id = model_id)
|
| 1008 |
-
|
| 1009 |
values$is_typing <- FALSE
|
| 1010 |
model_short <- gsub(".*/([^:]+):.*", "\\1", model_id)
|
| 1011 |
add_message("assistant", response, model_used = if (token_exists) model_short else NULL)
|
| 1012 |
-
|
| 1013 |
-
# Clear pending file
|
| 1014 |
values$pending_file_content <- NULL
|
| 1015 |
values$pending_file_name <- NULL
|
| 1016 |
}
|
| 1017 |
-
|
| 1018 |
-
# ---- Handle chat file upload ----
|
| 1019 |
observeEvent(input$chat_file_upload, {
|
| 1020 |
req(input$chat_file_upload)
|
| 1021 |
file_path <- input$chat_file_upload$datapath
|
| 1022 |
file_name <- input$chat_file_upload$name
|
| 1023 |
ext <- tolower(tools::file_ext(file_name))
|
| 1024 |
-
|
| 1025 |
tryCatch({
|
| 1026 |
file_content <- if (ext %in% c("csv", "txt", "tsv")) {
|
| 1027 |
paste(readLines(file_path, n = 200), collapse = "\n")
|
| 1028 |
} else {
|
| 1029 |
paste0("[Binary file: ", file_name, " - ", round(file.info(file_path)$size / 1024, 1), " KB]")
|
| 1030 |
}
|
| 1031 |
-
|
| 1032 |
values$pending_file_content <- file_content
|
| 1033 |
values$pending_file_name <- file_name
|
| 1034 |
}, error = function(e) {
|
| 1035 |
showNotification(paste("Could not read file:", e$message), type = "warning")
|
| 1036 |
})
|
| 1037 |
})
|
| 1038 |
-
|
| 1039 |
-
# ---- Clear chat file ----
|
| 1040 |
observeEvent(input$clear_chat_file, {
|
| 1041 |
values$pending_file_content <- NULL
|
| 1042 |
values$pending_file_name <- NULL
|
| 1043 |
})
|
| 1044 |
-
|
| 1045 |
-
# ---- Send chat ----
|
| 1046 |
observeEvent(input$send_chat, {
|
| 1047 |
-
user_text
|
| 1048 |
file_content <- isolate(values$pending_file_content)
|
| 1049 |
file_name <- isolate(values$pending_file_name)
|
| 1050 |
-
|
| 1051 |
if (nchar(user_text) == 0 && is.null(file_content)) return()
|
| 1052 |
-
|
| 1053 |
updateTextAreaInput(session, "chat_input", value = "")
|
| 1054 |
-
# Clear file preview via JS
|
| 1055 |
shinyjs::runjs("
|
| 1056 |
document.getElementById('chat_file_preview').style.display = 'none';
|
| 1057 |
document.getElementById('chat_file_preview').innerHTML = '';
|
| 1058 |
")
|
| 1059 |
-
|
| 1060 |
process_message(user_text, file_content, file_name)
|
| 1061 |
})
|
| 1062 |
-
|
| 1063 |
observeEvent(input$quick_q, { req(input$quick_q); process_message(input$quick_q) })
|
| 1064 |
-
|
| 1065 |
observeEvent(input$clear_chat, {
|
| 1066 |
values$chat_messages <- list()
|
| 1067 |
add_message("assistant", "Chat cleared. How can I help?")
|
| 1068 |
})
|
| 1069 |
-
|
| 1070 |
-
# ---- Initial greeting ----
|
| 1071 |
observe({
|
| 1072 |
if (length(values$chat_messages) == 0) {
|
| 1073 |
mode_msg <- if (token_exists) {
|
| 1074 |
-
paste0("I have access to **", length(available_models), " AI models** via
|
| 1075 |
"Select a model above and click **Test** to verify it's working!")
|
| 1076 |
} else {
|
| 1077 |
-
"I'm using rule-based responses. Set **
|
| 1078 |
}
|
| 1079 |
add_message("assistant", paste0(
|
| 1080 |
"\U0001f44b Vanakam! I'm TerraByte - An AI powered companion.\n\n",
|
| 1081 |
mode_msg,
|
| 1082 |
-
"\n\n**
|
| 1083 |
-
"
|
| 1084 |
-
"\u2022 **
|
|
|
|
| 1085 |
"\u2022 **Model performance** - Why is my R\u00b2 negative?\n",
|
| 1086 |
"\u2022 **Next steps** - Recommendations\n",
|
| 1087 |
"\u2022 **Upload files** - Use the paperclip to attach CSV/TXT data\n\n",
|
| 1088 |
-
"Try
|
| 1089 |
))
|
| 1090 |
}
|
| 1091 |
})
|
| 1092 |
-
|
| 1093 |
-
# ---- Chat display ----
|
| 1094 |
output$chat_display <- renderUI({
|
| 1095 |
messages <- values$chat_messages
|
| 1096 |
if (length(messages) == 0) return(NULL)
|
| 1097 |
-
|
| 1098 |
elems <- lapply(messages, function(msg) {
|
| 1099 |
content_html <- HTML(gsub("\n", "<br>", htmltools::htmlEscape(msg$content)))
|
| 1100 |
-
|
| 1101 |
meta_content <- tagList(
|
| 1102 |
span(msg$time),
|
| 1103 |
if (!is.null(msg$model) && msg$role == "assistant")
|
| 1104 |
span(class = "model-tag", paste0("[", msg$model, "]"))
|
| 1105 |
)
|
| 1106 |
-
|
| 1107 |
div(class = paste("chat-msg", msg$role),
|
| 1108 |
div(class = "chat-bubble", content_html),
|
| 1109 |
div(class = "chat-meta", meta_content))
|
| 1110 |
})
|
| 1111 |
-
|
| 1112 |
if (values$is_typing) {
|
| 1113 |
elems <- c(elems, list(
|
| 1114 |
div(class = "chat-msg assistant",
|
|
@@ -1117,64 +1068,64 @@ server <- function(input, output, session) {
|
|
| 1117 |
}
|
| 1118 |
do.call(tagList, elems)
|
| 1119 |
})
|
| 1120 |
-
|
| 1121 |
# ============================================================
|
| 1122 |
# DATA LOADING
|
| 1123 |
# ============================================================
|
| 1124 |
-
|
| 1125 |
observeEvent(input$genotype_file, {
|
| 1126 |
req(input$genotype_file)
|
| 1127 |
tryCatch({
|
| 1128 |
all_data <- readLines(input$genotype_file$datapath)
|
| 1129 |
if (length(all_data) < 4) { showNotification("Genotype file must have at least 4 rows", type = "error"); return() }
|
| 1130 |
-
|
| 1131 |
header <- strsplit(all_data[1], ",")[[1]]
|
| 1132 |
chromosome_row <- strsplit(all_data[2], ",")[[1]]
|
| 1133 |
position_row <- strsplit(all_data[3], ",")[[1]]
|
| 1134 |
-
|
| 1135 |
genotype_data <- read.csv(text = all_data[-(1:3)], header = FALSE)
|
| 1136 |
colnames(genotype_data) <- header
|
| 1137 |
rownames(genotype_data) <- genotype_data[, 1]
|
| 1138 |
genotype_data <- genotype_data[, -1]
|
| 1139 |
-
|
| 1140 |
for (col in colnames(genotype_data))
|
| 1141 |
genotype_data[[col]] <- as.numeric(as.character(genotype_data[[col]]))
|
| 1142 |
-
|
| 1143 |
values$all_markers <- data.frame(
|
| 1144 |
Marker = colnames(genotype_data),
|
| 1145 |
Chromosome = chromosome_row[-1],
|
| 1146 |
Position = as.numeric(position_row[-1]),
|
| 1147 |
stringsAsFactors = FALSE)
|
| 1148 |
-
|
| 1149 |
values$genotype_data <- genotype_data
|
| 1150 |
values$chromosome_info <- chromosome_row[-1]
|
| 1151 |
values$position_info <- as.numeric(position_row[-1])
|
| 1152 |
-
|
| 1153 |
showNotification("Genotype data loaded", type = "message")
|
| 1154 |
add_message("assistant", paste0("\u2705 Loaded genotype data: **", ncol(genotype_data), " markers**, **", nrow(genotype_data), " samples**"))
|
| 1155 |
}, error = function(e) showNotification(paste("Error:", e$message), type = "error"))
|
| 1156 |
})
|
| 1157 |
-
|
| 1158 |
observeEvent(input$phenotype_file, {
|
| 1159 |
req(input$phenotype_file)
|
| 1160 |
tryCatch({
|
| 1161 |
phenotype_data <- read.csv(input$phenotype_file$datapath)
|
| 1162 |
rownames(phenotype_data) <- phenotype_data[, 1]
|
| 1163 |
phenotype_data <- phenotype_data[, -1]
|
| 1164 |
-
|
| 1165 |
for (col in colnames(phenotype_data))
|
| 1166 |
phenotype_data[[col]] <- as.numeric(as.character(phenotype_data[[col]]))
|
| 1167 |
-
|
| 1168 |
values$phenotype_data <- phenotype_data
|
| 1169 |
updateSelectInput(session, "phenotype_column",
|
| 1170 |
choices = colnames(phenotype_data),
|
| 1171 |
selected = colnames(phenotype_data)[1])
|
| 1172 |
-
|
| 1173 |
showNotification("Phenotype data loaded", type = "message")
|
| 1174 |
add_message("assistant", paste0("\u2705 Loaded phenotype data: **", ncol(phenotype_data), " traits**, **", nrow(phenotype_data), " samples**"))
|
| 1175 |
}, error = function(e) showNotification(paste("Error:", e$message), type = "error"))
|
| 1176 |
})
|
| 1177 |
-
|
| 1178 |
observeEvent(input$pop_file, {
|
| 1179 |
req(input$pop_file)
|
| 1180 |
tryCatch({
|
|
@@ -1187,112 +1138,170 @@ server <- function(input, output, session) {
|
|
| 1187 |
add_message("assistant", paste0("\u2705 Loaded population data (", nrow(pop_data), " samples)"))
|
| 1188 |
}, error = function(e) showNotification(paste("Error:", e$message), type = "error"))
|
| 1189 |
})
|
| 1190 |
-
|
| 1191 |
observeEvent(input$test_genotype_file, {
|
| 1192 |
req(input$test_genotype_file)
|
| 1193 |
tryCatch({
|
| 1194 |
all_data <- readLines(input$test_genotype_file$datapath)
|
| 1195 |
header <- strsplit(all_data[1], ",")[[1]]
|
| 1196 |
-
|
| 1197 |
genotype_data <- read.csv(text = all_data[-(1:3)], header = FALSE)
|
| 1198 |
colnames(genotype_data) <- header
|
| 1199 |
rownames(genotype_data) <- genotype_data[, 1]
|
| 1200 |
genotype_data <- genotype_data[, -1]
|
| 1201 |
-
|
| 1202 |
for (col in colnames(genotype_data))
|
| 1203 |
genotype_data[[col]] <- as.numeric(as.character(genotype_data[[col]]))
|
| 1204 |
-
|
| 1205 |
values$test_genotype_data <- genotype_data
|
| 1206 |
values$has_test_data <- TRUE
|
| 1207 |
showNotification("Test genotype data loaded", type = "message")
|
| 1208 |
}, error = function(e) showNotification(paste("Error:", e$message), type = "error"))
|
| 1209 |
})
|
| 1210 |
-
|
| 1211 |
-
# ---- Data previews ----
|
| 1212 |
output$geno_preview <- renderDT({ req(input$genotype_file); datatable(head(read.csv(input$genotype_file$datapath), 10), options = list(scrollX = TRUE, pageLength = 5)) })
|
| 1213 |
output$pheno_preview <- renderDT({ req(input$phenotype_file); datatable(head(read.csv(input$phenotype_file$datapath), 10), options = list(scrollX = TRUE, pageLength = 5)) })
|
| 1214 |
output$test_geno_preview <- renderDT({ req(input$test_genotype_file); datatable(head(read.csv(input$test_genotype_file$datapath), 10), options = list(scrollX = TRUE, pageLength = 5)) })
|
| 1215 |
output$pop_preview <- renderDT({ req(input$pop_file); datatable(head(read.csv(input$pop_file$datapath), 10), options = list(scrollX = TRUE, pageLength = 5)) })
|
| 1216 |
output$predicted_test_pheno_preview <- renderDT({ req(values$predicted_test_phenotype_data); datatable(values$predicted_test_phenotype_data, options = list(scrollX = TRUE, pageLength = 5)) })
|
| 1217 |
-
|
|
|
|
|
|
|
| 1218 |
# ============================================================
|
| 1219 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1220 |
# ============================================================
|
| 1221 |
-
|
| 1222 |
calculate_qtl_effects <- function(genotype_matrix, phenotype_vector, marker_names) {
|
| 1223 |
effects_list <- list()
|
| 1224 |
-
|
| 1225 |
for (marker in marker_names) {
|
| 1226 |
if (!marker %in% colnames(genotype_matrix)) next
|
| 1227 |
-
|
| 1228 |
geno <- genotype_matrix[, marker]
|
| 1229 |
pheno <- phenotype_vector
|
| 1230 |
valid_idx <- !is.na(geno) & !is.na(pheno)
|
| 1231 |
geno <- geno[valid_idx]
|
| 1232 |
pheno <- pheno[valid_idx]
|
| 1233 |
-
|
| 1234 |
-
if (length(unique(geno)) < 2) next
|
| 1235 |
-
|
| 1236 |
-
|
| 1237 |
-
|
| 1238 |
-
|
| 1239 |
-
|
| 1240 |
-
|
| 1241 |
-
|
| 1242 |
-
|
| 1243 |
-
|
| 1244 |
-
|
| 1245 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1246 |
}
|
| 1247 |
-
|
| 1248 |
-
r_squared <- summary(lm_fit)$r.squared
|
| 1249 |
-
se_additive <- tryCatch(summary(lm_fit)$coefficients[2, 2], error = function(e) NA)
|
| 1250 |
-
|
| 1251 |
effects_list[[marker]] <- data.frame(
|
| 1252 |
-
Marker
|
| 1253 |
-
Additive_Effect
|
| 1254 |
-
|
| 1255 |
-
|
| 1256 |
-
|
| 1257 |
-
|
| 1258 |
-
|
| 1259 |
-
|
| 1260 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1261 |
}
|
| 1262 |
-
|
| 1263 |
if (length(effects_list) == 0) return(NULL)
|
| 1264 |
do.call(rbind, effects_list)
|
| 1265 |
}
|
| 1266 |
-
|
| 1267 |
# ============================================================
|
| 1268 |
# MAIN QTL ANALYSIS
|
| 1269 |
# ============================================================
|
| 1270 |
-
|
| 1271 |
observeEvent(input$run_analysis, {
|
| 1272 |
req(values$genotype_data, values$phenotype_data, input$phenotype_column)
|
| 1273 |
showNotification("Starting QTL analysis...", type = "message")
|
| 1274 |
values$lod_threshold <- input$lod_threshold
|
| 1275 |
-
|
| 1276 |
tryCatch({
|
| 1277 |
common_samples <- intersect(rownames(values$genotype_data), rownames(values$phenotype_data))
|
| 1278 |
if (length(common_samples) == 0) { showNotification("No common samples", type = "error"); return() }
|
| 1279 |
-
|
| 1280 |
X <- values$genotype_data[common_samples, , drop = FALSE]
|
| 1281 |
y <- as.numeric(values$phenotype_data[common_samples, input$phenotype_column])
|
| 1282 |
nzv <- nearZeroVar(X)
|
| 1283 |
if (length(nzv) > 0) X <- X[, -nzv, drop = FALSE]
|
| 1284 |
-
|
| 1285 |
set.seed(123)
|
| 1286 |
train_index <- createDataPartition(y, p = 1 - input$test_size, list = FALSE)
|
| 1287 |
X_train <- X[train_index, , drop = FALSE]; X_val <- X[-train_index, , drop = FALSE]
|
| 1288 |
y_train <- y[train_index]; y_val <- y[-train_index]
|
| 1289 |
-
|
| 1290 |
model <- train(x = X_train, y = y_train, method = "rf",
|
| 1291 |
trControl = trainControl(method = "cv", number = 5),
|
| 1292 |
importance = TRUE, tuneLength = 3)
|
| 1293 |
-
|
| 1294 |
values$model_fit <- model
|
| 1295 |
-
|
| 1296 |
imp <- varImp(model, scale = FALSE)$importance
|
| 1297 |
importance_scores <- data.frame(
|
| 1298 |
Marker = rownames(imp),
|
|
@@ -1300,14 +1309,14 @@ server <- function(input, output, session) {
|
|
| 1300 |
Chromosome = values$chromosome_info[match(rownames(imp), colnames(X))],
|
| 1301 |
Position = as.numeric(values$position_info[match(rownames(imp), colnames(X))]),
|
| 1302 |
stringsAsFactors = FALSE)
|
| 1303 |
-
|
| 1304 |
values$importance_scores <- importance_scores
|
| 1305 |
lod_sig <- importance_scores[importance_scores$LOD > input$lod_threshold, , drop = FALSE]
|
| 1306 |
-
|
| 1307 |
if (nrow(lod_sig) > 0) {
|
| 1308 |
lod_sig$Low_Flank <- NA
|
| 1309 |
lod_sig$High_Flank <- NA
|
| 1310 |
-
|
| 1311 |
for (i in 1:nrow(lod_sig)) {
|
| 1312 |
chr_m <- values$all_markers[values$all_markers$Chromosome == lod_sig$Chromosome[i], ]
|
| 1313 |
chr_m <- chr_m[order(chr_m$Position), ]
|
|
@@ -1317,10 +1326,12 @@ server <- function(input, output, session) {
|
|
| 1317 |
lod_sig$High_Flank[i] <- if (idx < nrow(chr_m)) chr_m$Marker[idx + 1] else lod_sig$Marker[i]
|
| 1318 |
}
|
| 1319 |
}
|
| 1320 |
-
|
| 1321 |
values$lod_scores_train <- lod_sig
|
|
|
|
|
|
|
| 1322 |
qtl_fx <- calculate_qtl_effects(X_train, y_train, lod_sig$Marker)
|
| 1323 |
-
|
| 1324 |
if (!is.null(qtl_fx)) {
|
| 1325 |
values$qtl_effects_train <- merge(lod_sig, qtl_fx, by = "Marker")
|
| 1326 |
} else {
|
|
@@ -1330,26 +1341,26 @@ server <- function(input, output, session) {
|
|
| 1330 |
values$lod_scores_train <- data.frame(Message = paste("No QTLs above LOD", input$lod_threshold))
|
| 1331 |
values$qtl_effects_train <- data.frame(Message = paste("No QTLs above LOD", input$lod_threshold))
|
| 1332 |
}
|
| 1333 |
-
|
| 1334 |
y_train_pred <- predict(model, X_train)
|
| 1335 |
y_val_pred <- predict(model, X_val)
|
| 1336 |
train_r2 <- 1 - sum((y_train - y_train_pred)^2) / sum((y_train - mean(y_train))^2)
|
| 1337 |
val_r2 <- 1 - sum((y_val - y_val_pred)^2) / sum((y_val - mean(y_val))^2)
|
| 1338 |
-
|
| 1339 |
values$performance_metrics <- data.frame(
|
| 1340 |
Metric = c("R\u00b2 (Train)", "R (Train)", "R\u00b2 (Validation)", "R (Validation)"),
|
| 1341 |
Value = c(train_r2, cor(y_train, y_train_pred), val_r2, cor(y_val, y_val_pred)),
|
| 1342 |
stringsAsFactors = FALSE)
|
| 1343 |
-
|
| 1344 |
values$train_predictions <- data.frame(Observed = y_train, Predicted = y_train_pred)
|
| 1345 |
values$test_predictions <- data.frame(Observed = y_val, Predicted = y_val_pred)
|
| 1346 |
-
|
| 1347 |
# Epistasis
|
| 1348 |
if (nrow(lod_sig) > 0) {
|
| 1349 |
sig_markers <- lod_sig$Marker[lod_sig$Marker %in% colnames(X_train)]
|
| 1350 |
all_markers_v <- colnames(X_train)
|
| 1351 |
epistasis_list <- list()
|
| 1352 |
-
|
| 1353 |
withProgress(message = "Calculating epistasis...", value = 0, {
|
| 1354 |
total <- length(sig_markers) * length(all_markers_v)
|
| 1355 |
for (m1 in sig_markers) {
|
|
@@ -1373,7 +1384,7 @@ server <- function(input, output, session) {
|
|
| 1373 |
}
|
| 1374 |
}
|
| 1375 |
})
|
| 1376 |
-
|
| 1377 |
if (length(epistasis_list) > 0) {
|
| 1378 |
epistasis_all <- do.call(rbind, epistasis_list)
|
| 1379 |
values$epistasis_all <- epistasis_all
|
|
@@ -1383,54 +1394,55 @@ server <- function(input, output, session) {
|
|
| 1383 |
values$epistasis_sig <- data.frame(Message = "No epistatic interactions")
|
| 1384 |
}
|
| 1385 |
}
|
| 1386 |
-
|
| 1387 |
showNotification("QTL analysis completed!", type = "message")
|
| 1388 |
n_qtl <- if (!is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train)) nrow(values$qtl_effects_train) else 0
|
| 1389 |
add_message("assistant", paste0(
|
| 1390 |
"\u2705 **QTL analysis complete!**\n\n",
|
| 1391 |
"\u2022 Found **", n_qtl, " QTLs** above LOD ", input$lod_threshold, "\n",
|
| 1392 |
-
"\u2022 Validation R\u00b2: **", round(val_r2, 3), "**\n
|
|
|
|
| 1393 |
"Ask me about PVE, top QTLs, or next steps!"))
|
| 1394 |
updateTabsetPanel(session, "nav", selected = "Results")
|
| 1395 |
-
|
| 1396 |
}, error = function(e) showNotification(paste("Error:", e$message), type = "error"))
|
| 1397 |
})
|
| 1398 |
-
|
| 1399 |
# ============================================================
|
| 1400 |
# DOMESTICATION ANALYSIS
|
| 1401 |
# ============================================================
|
| 1402 |
-
|
| 1403 |
calculate_selection_metrics <- function(genotype_matrix, pop_data, marker_info) {
|
| 1404 |
metrics_list <- list()
|
| 1405 |
-
|
| 1406 |
for (marker in colnames(genotype_matrix)) {
|
| 1407 |
geno <- genotype_matrix[, marker]
|
| 1408 |
pop <- pop_data$population[match(rownames(genotype_matrix), pop_data$id)]
|
| 1409 |
valid_idx <- !is.na(geno) & !is.na(pop)
|
| 1410 |
geno <- geno[valid_idx]; pop <- pop[valid_idx]
|
| 1411 |
-
|
| 1412 |
if (length(unique(pop)) < 2) next
|
| 1413 |
geno_dom <- geno[pop == "Domesticated"]
|
| 1414 |
geno_wild <- geno[pop == "Wild"]
|
| 1415 |
if (length(geno_dom) < 3 || length(geno_wild) < 3) next
|
| 1416 |
-
|
| 1417 |
freq_dom <- mean(geno_dom, na.rm = TRUE) / 2
|
| 1418 |
freq_wild <- mean(geno_wild, na.rm = TRUE) / 2
|
| 1419 |
p_avg <- (freq_dom + freq_wild) / 2
|
| 1420 |
-
|
| 1421 |
fst <- if (p_avg > 0 && p_avg < 1) {
|
| 1422 |
f <- (freq_dom - freq_wild)^2 / (p_avg * (1 - p_avg))
|
| 1423 |
f / (1 + f)
|
| 1424 |
} else 0
|
| 1425 |
-
|
| 1426 |
pi_dom <- 2 * freq_dom * (1 - freq_dom)
|
| 1427 |
pi_wild <- 2 * freq_wild * (1 - freq_wild)
|
| 1428 |
n_dom <- length(geno_dom)
|
| 1429 |
n_wild <- length(geno_wild)
|
| 1430 |
-
|
| 1431 |
-
tajima_d_dom <- (pi_dom - 1/n_dom) / sqrt(var(geno_dom) /n_dom)
|
| 1432 |
-
tajima_d_wild <- (pi_wild - 1/n_wild) / sqrt(var(geno_wild)/n_wild)
|
| 1433 |
-
|
| 1434 |
marker_row <- marker_info[marker_info$Marker == marker, ]
|
| 1435 |
metrics_list[[marker]] <- data.frame(
|
| 1436 |
Marker = marker,
|
|
@@ -1440,71 +1452,71 @@ server <- function(input, output, session) {
|
|
| 1440 |
Tajima_D_Dom = tajima_d_dom, Tajima_D_Wild = tajima_d_wild,
|
| 1441 |
stringsAsFactors = FALSE)
|
| 1442 |
}
|
| 1443 |
-
|
| 1444 |
if (length(metrics_list) == 0) return(NULL)
|
| 1445 |
do.call(rbind, metrics_list)
|
| 1446 |
}
|
| 1447 |
-
|
| 1448 |
observeEvent(input$run_domestication, {
|
| 1449 |
req(values$genotype_data, values$pop_data, values$all_markers)
|
| 1450 |
tryCatch({
|
| 1451 |
common_samples <- intersect(rownames(values$genotype_data), values$pop_data$id)
|
| 1452 |
if (length(common_samples) == 0) { showNotification("No common samples", type = "error"); return() }
|
| 1453 |
-
|
| 1454 |
X <- values$genotype_data[common_samples, , drop = FALSE]
|
| 1455 |
pop_subset <- values$pop_data[values$pop_data$id %in% common_samples, ]
|
| 1456 |
sel_metrics <- calculate_selection_metrics(X, pop_subset, values$all_markers)
|
| 1457 |
-
|
| 1458 |
if (is.null(sel_metrics)) { showNotification("Could not calculate selection metrics", type = "error"); return() }
|
| 1459 |
-
|
| 1460 |
sel_metrics$Significant <-
|
| 1461 |
sel_metrics$Fst > input$fst_threshold |
|
| 1462 |
sel_metrics$Tajima_D_Dom < input$tajima_threshold |
|
| 1463 |
sel_metrics$Tajima_D_Wild < input$tajima_threshold
|
| 1464 |
-
|
| 1465 |
values$selection_metrics <- sel_metrics
|
| 1466 |
showNotification("Domestication analysis completed!", type = "message")
|
| 1467 |
n_sig <- sum(sel_metrics$Significant, na.rm = TRUE)
|
| 1468 |
add_message("assistant", paste0("\u2705 Domestication analysis complete!\n\n\u2022 Found **", n_sig, " markers** with selection signatures"))
|
| 1469 |
}, error = function(e) showNotification(paste("Error:", e$message), type = "error"))
|
| 1470 |
})
|
| 1471 |
-
|
| 1472 |
# ============================================================
|
| 1473 |
# PREDICT TEST PHENOTYPES
|
| 1474 |
# ============================================================
|
| 1475 |
-
|
| 1476 |
observeEvent(input$predict_test_phenotype, {
|
| 1477 |
req(values$model_fit, values$test_genotype_data)
|
| 1478 |
tryCatch({
|
| 1479 |
common_markers <- intersect(colnames(values$test_genotype_data), colnames(values$genotype_data))
|
| 1480 |
if (length(common_markers) == 0) { showNotification("No common markers", type = "error"); return() }
|
| 1481 |
-
|
| 1482 |
X_test <- values$test_genotype_data[, common_markers, drop = FALSE]
|
| 1483 |
predictions <- predict(values$model_fit, newdata = X_test)
|
| 1484 |
-
|
| 1485 |
values$predicted_test_phenotype_data <- data.frame(
|
| 1486 |
id = rownames(X_test),
|
| 1487 |
Predicted_Phenotype = as.numeric(predictions),
|
| 1488 |
stringsAsFactors = FALSE)
|
| 1489 |
-
|
| 1490 |
showNotification("Predictions completed!", type = "message")
|
| 1491 |
}, error = function(e) showNotification(paste("Error:", e$message), type = "error"))
|
| 1492 |
})
|
| 1493 |
-
|
| 1494 |
# ============================================================
|
| 1495 |
# MANHATTAN PLOT HELPER
|
| 1496 |
# ============================================================
|
| 1497 |
-
|
| 1498 |
create_manhattan <- function(data, y_col, title, threshold, y_label = y_col) {
|
| 1499 |
if (is.null(data) || nrow(data) == 0 || "Message" %in% colnames(data))
|
| 1500 |
return(plot_ly() %>% layout(title = "No data available",
|
| 1501 |
plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e")))
|
| 1502 |
-
|
| 1503 |
plot_data <- data[!is.na(data[[y_col]]), ]
|
| 1504 |
if (nrow(plot_data) == 0)
|
| 1505 |
return(plot_ly() %>% layout(title = "No valid data",
|
| 1506 |
plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e")))
|
| 1507 |
-
|
| 1508 |
chroms <- unique(plot_data$Chromosome)
|
| 1509 |
chrom_pos <- data.frame()
|
| 1510 |
for (i in seq_along(chroms)) {
|
|
@@ -1515,7 +1527,7 @@ server <- function(input, output, session) {
|
|
| 1515 |
chrom_pos <- rbind(chrom_pos, chr_data)
|
| 1516 |
}
|
| 1517 |
}
|
| 1518 |
-
|
| 1519 |
p <- plot_ly() %>%
|
| 1520 |
add_trace(data = chrom_pos, x = ~PosScaled, y = as.formula(paste0("~", y_col)),
|
| 1521 |
type = "scatter", mode = "markers", color = ~factor(Chromosome),
|
|
@@ -1523,13 +1535,13 @@ server <- function(input, output, session) {
|
|
| 1523 |
text = ~paste("Marker:", Marker, "<br>Chr:", Chromosome, "<br>Pos:", Position,
|
| 1524 |
"<br>", y_label, ":", round(get(y_col), 3)),
|
| 1525 |
hoverinfo = "text", showlegend = FALSE)
|
| 1526 |
-
|
| 1527 |
if (!is.null(threshold) && !is.na(threshold))
|
| 1528 |
p <- p %>% add_segments(
|
| 1529 |
x = min(chrom_pos$PosScaled, na.rm = TRUE), xend = max(chrom_pos$PosScaled, na.rm = TRUE),
|
| 1530 |
y = threshold, yend = threshold,
|
| 1531 |
line = list(color = "red", dash = "dash", width = 1), name = "Threshold")
|
| 1532 |
-
|
| 1533 |
p %>% layout(title = title,
|
| 1534 |
xaxis = list(title = "Chromosome",
|
| 1535 |
ticktext = chroms,
|
|
@@ -1538,26 +1550,26 @@ server <- function(input, output, session) {
|
|
| 1538 |
yaxis = list(title = y_label),
|
| 1539 |
plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))
|
| 1540 |
}
|
| 1541 |
-
|
| 1542 |
# ============================================================
|
| 1543 |
# PLOTS
|
| 1544 |
# ============================================================
|
| 1545 |
-
|
| 1546 |
output$lod_plot_2d <- renderPlotly({
|
| 1547 |
req(values$importance_scores)
|
| 1548 |
create_manhattan(values$importance_scores, "LOD", "QTL Manhattan Plot", input$lod_threshold, "LOD Score")
|
| 1549 |
})
|
| 1550 |
-
|
| 1551 |
output$fst_plot <- renderPlotly({
|
| 1552 |
req(values$selection_metrics)
|
| 1553 |
create_manhattan(values$selection_metrics, "Fst", "Fst Manhattan Plot", input$fst_threshold, "Fst")
|
| 1554 |
})
|
| 1555 |
-
|
| 1556 |
output$tajima_plot <- renderPlotly({
|
| 1557 |
req(values$selection_metrics)
|
| 1558 |
if ("Message" %in% colnames(values$selection_metrics))
|
| 1559 |
return(plot_ly() %>% layout(title = "No data available", plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e")))
|
| 1560 |
-
|
| 1561 |
data <- values$selection_metrics
|
| 1562 |
chroms <- unique(data$Chromosome)
|
| 1563 |
chrom_pos <- data.frame()
|
|
@@ -1569,7 +1581,7 @@ server <- function(input, output, session) {
|
|
| 1569 |
chrom_pos <- rbind(chrom_pos, chr_data)
|
| 1570 |
}
|
| 1571 |
}
|
| 1572 |
-
|
| 1573 |
plot_ly() %>%
|
| 1574 |
add_trace(data = chrom_pos, x = ~PosScaled, y = ~Tajima_D_Dom, type = "scatter", mode = "markers",
|
| 1575 |
name = "Domesticated", marker = list(size = 5, color = "#58a6ff", opacity = 0.7),
|
|
@@ -1588,7 +1600,7 @@ server <- function(input, output, session) {
|
|
| 1588 |
yaxis = list(title = "Tajima's D"),
|
| 1589 |
plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))
|
| 1590 |
})
|
| 1591 |
-
|
| 1592 |
output$performance_plot <- renderPlotly({
|
| 1593 |
req(values$performance_metrics)
|
| 1594 |
plot_ly(data = values$performance_metrics, x = ~Metric, y = ~Value, type = "bar",
|
|
@@ -1598,7 +1610,7 @@ server <- function(input, output, session) {
|
|
| 1598 |
yaxis = list(title = "Value", range = c(0, 1.1)),
|
| 1599 |
plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))
|
| 1600 |
})
|
| 1601 |
-
|
| 1602 |
output$regression_plot_train <- renderPlotly({
|
| 1603 |
req(values$train_predictions)
|
| 1604 |
plot_ly(data = values$train_predictions, x = ~Observed, y = ~Predicted,
|
|
@@ -1608,7 +1620,7 @@ server <- function(input, output, session) {
|
|
| 1608 |
layout(title = "Training Set", xaxis = list(title = "Observed"), yaxis = list(title = "Predicted"),
|
| 1609 |
plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))
|
| 1610 |
})
|
| 1611 |
-
|
| 1612 |
output$regression_plot_test <- renderPlotly({
|
| 1613 |
req(values$test_predictions)
|
| 1614 |
plot_ly(data = values$test_predictions, x = ~Observed, y = ~Predicted,
|
|
@@ -1618,13 +1630,13 @@ server <- function(input, output, session) {
|
|
| 1618 |
layout(title = "Validation Set", xaxis = list(title = "Observed"), yaxis = list(title = "Predicted"),
|
| 1619 |
plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))
|
| 1620 |
})
|
| 1621 |
-
|
| 1622 |
output$epistasis_heatmap <- renderPlotly({
|
| 1623 |
req(values$epistasis_all)
|
| 1624 |
if ("Message" %in% colnames(values$epistasis_all))
|
| 1625 |
return(plot_ly() %>% layout(title = values$epistasis_all$Message[1],
|
| 1626 |
plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e")))
|
| 1627 |
-
|
| 1628 |
qtls <- unique(values$epistasis_all$QTL1)
|
| 1629 |
markers <- unique(values$epistasis_all$QTL2)
|
| 1630 |
p_mat <- matrix(NA, nrow = length(qtls), ncol = length(markers),
|
|
@@ -1632,7 +1644,7 @@ server <- function(input, output, session) {
|
|
| 1632 |
for (i in 1:nrow(values$epistasis_all))
|
| 1633 |
p_mat[values$epistasis_all$QTL1[i], values$epistasis_all$QTL2[i]] <-
|
| 1634 |
-log10(values$epistasis_all$Interaction_p[i])
|
| 1635 |
-
|
| 1636 |
plot_ly(x = colnames(p_mat), y = rownames(p_mat), z = p_mat,
|
| 1637 |
type = "heatmap", colorscale = "Viridis",
|
| 1638 |
hovertemplate = "QTL: %{y}<br>Marker: %{x}<br>-log10(p): %{z:.2f}") %>%
|
|
@@ -1640,24 +1652,34 @@ server <- function(input, output, session) {
|
|
| 1640 |
xaxis = list(title = "Marker", tickangle = 45), yaxis = list(title = "QTL"),
|
| 1641 |
plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))
|
| 1642 |
})
|
| 1643 |
-
|
| 1644 |
# ============================================================
|
| 1645 |
# TABLES
|
| 1646 |
# ============================================================
|
| 1647 |
-
|
| 1648 |
output$qtl_effects_table_train <- renderDT({
|
| 1649 |
req(values$qtl_effects_train)
|
| 1650 |
if ("Message" %in% colnames(values$qtl_effects_train))
|
| 1651 |
return(datatable(data.frame(Status = values$qtl_effects_train$Message[1]), options = list(dom = "t")))
|
| 1652 |
-
|
|
|
|
| 1653 |
display_cols <- intersect(
|
| 1654 |
-
c("Marker", "Chromosome", "Position", "LOD",
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1655 |
colnames(values$qtl_effects_train))
|
|
|
|
| 1656 |
df <- values$qtl_effects_train[order(-values$qtl_effects_train$LOD), display_cols]
|
| 1657 |
-
datatable(df,
|
| 1658 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1659 |
})
|
| 1660 |
-
|
| 1661 |
output$epistasis_table <- renderDT({
|
| 1662 |
req(values$epistasis_sig)
|
| 1663 |
if ("Message" %in% colnames(values$epistasis_sig))
|
|
@@ -1666,47 +1688,47 @@ server <- function(input, output, session) {
|
|
| 1666 |
options = list(pageLength = 10, scrollX = TRUE), rownames = FALSE) %>%
|
| 1667 |
formatSignif(columns = c("Interaction_p", "Effect_Size"), digits = 4)
|
| 1668 |
})
|
| 1669 |
-
|
| 1670 |
output$selection_table <- renderDT({
|
| 1671 |
req(values$selection_metrics)
|
| 1672 |
if ("Message" %in% colnames(values$selection_metrics))
|
| 1673 |
return(datatable(data.frame(Status = values$selection_metrics$Message[1]), options = list(dom = "t")))
|
| 1674 |
-
|
| 1675 |
df <- values$selection_metrics
|
| 1676 |
if (!is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train))
|
| 1677 |
df$QTL_Overlap <- df$Marker %in% values$qtl_effects_train$Marker
|
| 1678 |
-
|
| 1679 |
display_cols <- intersect(
|
| 1680 |
c("Marker", "Chromosome", "Fst", "Pi_Dom", "Pi_Wild", "Tajima_D_Dom", "Significant", "QTL_Overlap"),
|
| 1681 |
colnames(df))
|
| 1682 |
datatable(df[order(-df$Fst), display_cols], options = list(pageLength = 10, scrollX = TRUE), rownames = FALSE) %>%
|
| 1683 |
formatRound(c("Fst", "Pi_Dom", "Pi_Wild", "Tajima_D_Dom"), 3)
|
| 1684 |
})
|
| 1685 |
-
|
| 1686 |
# ============================================================
|
| 1687 |
# CHROMOSOME VISUALIZATION
|
| 1688 |
# ============================================================
|
| 1689 |
-
|
| 1690 |
output$chromosome_viz <- renderUI({
|
| 1691 |
req(values$lod_scores_train, values$all_markers)
|
| 1692 |
if ("Message" %in% colnames(values$lod_scores_train))
|
| 1693 |
return(div(class = "alert alert-info", values$lod_scores_train$Message[1]))
|
| 1694 |
-
|
| 1695 |
chromosomes <- unique(values$lod_scores_train$Chromosome)
|
| 1696 |
tagList(lapply(chromosomes, function(chr) {
|
| 1697 |
chr_markers <- values$all_markers[values$all_markers$Chromosome == chr, ]
|
| 1698 |
chr_markers <- chr_markers[order(chr_markers$Position), ]
|
| 1699 |
chr_qtls <- values$lod_scores_train[values$lod_scores_train$Chromosome == chr, ]
|
| 1700 |
-
|
| 1701 |
sel_markers <- NULL
|
| 1702 |
if (!is.null(values$selection_metrics) && !"Message" %in% colnames(values$selection_metrics))
|
| 1703 |
sel_markers <- values$selection_metrics[
|
| 1704 |
values$selection_metrics$Chromosome == chr & values$selection_metrics$Significant, ]
|
| 1705 |
-
|
| 1706 |
min_pos <- min(chr_markers$Position, na.rm = TRUE)
|
| 1707 |
max_pos <- max(chr_markers$Position, na.rm = TRUE)
|
| 1708 |
range_pos <- max_pos - min_pos
|
| 1709 |
-
|
| 1710 |
div(class = "chromosome-container",
|
| 1711 |
div(class = "chromosome-title", paste("Chromosome", chr)),
|
| 1712 |
div(class = "chromosome",
|
|
@@ -1714,7 +1736,7 @@ server <- function(input, output, session) {
|
|
| 1714 |
marker <- chr_markers[i, ]
|
| 1715 |
left <- if (range_pos > 0) ((marker$Position - min_pos) / range_pos) * 100
|
| 1716 |
else (i / nrow(chr_markers)) * 100
|
| 1717 |
-
|
| 1718 |
marker_class <- "chromosome-marker"
|
| 1719 |
if (marker$Marker %in% chr_qtls$Marker) {
|
| 1720 |
marker_class <- paste(marker_class, "significant")
|
|
@@ -1732,97 +1754,156 @@ server <- function(input, output, session) {
|
|
| 1732 |
)
|
| 1733 |
}))
|
| 1734 |
})
|
| 1735 |
-
|
| 1736 |
-
# ---- Simulation animations ----
|
| 1737 |
observeEvent(input$simulate_btn, session$sendCustomMessage("simulateQTLDiscovery", list()))
|
| 1738 |
observeEvent(input$reset_btn, session$sendCustomMessage("resetAnimation", list()))
|
| 1739 |
-
|
| 1740 |
# ============================================================
|
| 1741 |
# INTERPRETATION OUTPUTS
|
| 1742 |
# ============================================================
|
| 1743 |
-
|
| 1744 |
output$analysis_summary <- renderUI({
|
| 1745 |
has_qtl <- !is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train)
|
| 1746 |
has_perf <- !is.null(values$performance_metrics)
|
| 1747 |
has_epi <- !is.null(values$epistasis_sig) && !"Message" %in% colnames(values$epistasis_sig) && nrow(values$epistasis_sig) > 0
|
| 1748 |
has_sel <- !is.null(values$selection_metrics) && !"Message" %in% colnames(values$selection_metrics)
|
| 1749 |
-
|
| 1750 |
n_qtl <- if (has_qtl) nrow(values$qtl_effects_train) else 0
|
| 1751 |
n_epi <- if (has_epi) nrow(values$epistasis_sig) else 0
|
| 1752 |
n_sel <- if (has_sel) sum(values$selection_metrics$Significant, na.rm = TRUE) else 0
|
| 1753 |
val_r2 <- if (has_perf) round(values$performance_metrics$Value[values$performance_metrics$Metric == "R\u00b2 (Validation)"], 3) else "N/A"
|
| 1754 |
-
|
| 1755 |
div(class = "interpretation-section",
|
| 1756 |
tags$h5("Analysis Summary"),
|
| 1757 |
tags$p(paste("Found", n_qtl, "QTLs above LOD", input$lod_threshold,
|
| 1758 |
if (has_perf) paste0("(validation R\u00b2 = ", val_r2, ")"),
|
| 1759 |
if (has_epi) paste0("with ", n_epi, " epistatic interactions"),
|
| 1760 |
-
if (has_sel) paste0("and ", n_sel, " selection signatures.")))
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1761 |
})
|
| 1762 |
-
|
| 1763 |
output$qtl_interpretation <- renderUI({
|
| 1764 |
if (is.null(values$qtl_effects_train) || "Message" %in% colnames(values$qtl_effects_train))
|
| 1765 |
return(div(class = "interpretation-section", tags$h5("QTL Significance"), tags$p("No significant QTLs detected.")))
|
| 1766 |
-
|
| 1767 |
top_qtl <- values$qtl_effects_train[which.max(values$qtl_effects_train$LOD), ]
|
| 1768 |
div(class = "interpretation-section",
|
| 1769 |
tags$h5("QTL Significance"),
|
| 1770 |
tags$p(paste("Top QTL:", top_qtl$Marker, "(Chr", top_qtl$Chromosome, ") with LOD =", round(top_qtl$LOD, 2))))
|
| 1771 |
})
|
| 1772 |
-
|
| 1773 |
output$effect_interpretation <- renderUI({
|
| 1774 |
if (is.null(values$qtl_effects_train) || "Message" %in% colnames(values$qtl_effects_train))
|
| 1775 |
return(div(class = "interpretation-section", tags$h5("Effect Sizes"), tags$p("No QTL effects to interpret.")))
|
| 1776 |
-
|
| 1777 |
top_pve <- values$qtl_effects_train[which.max(values$qtl_effects_train$PVE_Percent), ]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1778 |
div(class = "interpretation-section",
|
| 1779 |
-
tags$h5("Effect Sizes"),
|
| 1780 |
-
tags$p(paste("Largest
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1781 |
})
|
| 1782 |
-
|
| 1783 |
output$epistasis_interpretation <- renderUI({
|
| 1784 |
if (is.null(values$epistasis_sig) || "Message" %in% colnames(values$epistasis_sig) || nrow(values$epistasis_sig) == 0)
|
| 1785 |
return(div(class = "interpretation-section", tags$h5("Epistasis"), tags$p("No significant epistatic interactions detected.")))
|
| 1786 |
-
|
| 1787 |
top_epi <- values$epistasis_sig[which.min(values$epistasis_sig$Interaction_p), ]
|
| 1788 |
div(class = "interpretation-section",
|
| 1789 |
tags$h5("Epistasis"),
|
| 1790 |
tags$p(paste("Detected", nrow(values$epistasis_sig), "interactions. Strongest:",
|
| 1791 |
top_epi$QTL1, "x", top_epi$QTL2, "(p =", format.pval(top_epi$Interaction_p), ")")))
|
| 1792 |
})
|
| 1793 |
-
|
| 1794 |
output$recommendations <- renderUI({
|
| 1795 |
has_qtl <- !is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train)
|
|
|
|
| 1796 |
recs <- if (has_qtl) {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1797 |
c("Validate top QTLs in independent populations",
|
| 1798 |
"Use flanking markers for fine-mapping",
|
| 1799 |
-
"Check gene annotations in QTL regions"
|
|
|
|
| 1800 |
} else {
|
| 1801 |
c("Upload data and run QTL analysis",
|
| 1802 |
"Consider lowering LOD threshold",
|
| 1803 |
"Check data quality")
|
| 1804 |
}
|
|
|
|
| 1805 |
div(class = "interpretation-section",
|
| 1806 |
tags$h5("Recommendations"),
|
| 1807 |
tags$ul(lapply(recs, tags$li), style = "color:#8b949e;"))
|
| 1808 |
})
|
| 1809 |
-
|
| 1810 |
# ============================================================
|
| 1811 |
# DOWNLOAD HANDLERS
|
| 1812 |
# ============================================================
|
| 1813 |
-
|
| 1814 |
output$download_train_results <- downloadHandler(
|
| 1815 |
filename = function() paste0("qtl_results_", Sys.Date(), ".xlsx"),
|
| 1816 |
content = function(file) {
|
| 1817 |
sheets <- list()
|
| 1818 |
if (!is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train))
|
| 1819 |
-
sheets[["
|
| 1820 |
if (!is.null(values$performance_metrics))
|
| 1821 |
sheets[["Performance"]] <- values$performance_metrics
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1822 |
write_xlsx(sheets, file)
|
| 1823 |
}
|
| 1824 |
)
|
| 1825 |
-
|
| 1826 |
output$download_selection <- downloadHandler(
|
| 1827 |
filename = function() paste0("selection_", Sys.Date(), ".xlsx"),
|
| 1828 |
content = function(file) {
|
|
@@ -1836,7 +1917,7 @@ server <- function(input, output, session) {
|
|
| 1836 |
}
|
| 1837 |
|
| 1838 |
# ============================================================
|
| 1839 |
-
# RUN APP
|
| 1840 |
# ============================================================
|
| 1841 |
|
| 1842 |
shinyApp(ui = ui, server = server)
|
|
|
|
| 1 |
# ============================================================
|
| 2 |
# QTL-Mapper - With Model Selection & File Upload
|
| 3 |
+
# FIXED: PVE formula now includes BOTH additive AND dominance effects
|
| 4 |
+
#
|
| 5 |
+
# CORRECTION DETAILS:
|
| 6 |
+
# OLD (WRONG): PVE = RΒ² from lm(pheno ~ geno) β additive only, ignores dominance
|
| 7 |
+
#
|
| 8 |
+
# NEW (CORRECT):
|
| 9 |
+
# Additive coding: a = geno (0, 1, 2)
|
| 10 |
+
# Dominance coding: d = ifelse(geno == 1, 1, 0) (heterozygote indicator)
|
| 11 |
+
# Full model: lm(pheno ~ a + d)
|
| 12 |
+
# PVE_Percent = RΒ²_full Γ 100
|
| 13 |
+
# Additive_Effect = Ξ²_a (coefficient of 'a')
|
| 14 |
+
# Dominance_Effect = Ξ²_d (coefficient of 'd')
|
| 15 |
+
#
|
| 16 |
+
# This follows standard quantitative genetics:
|
| 17 |
+
# Falconer & Mackay (1996); Lynch & Walsh (1998)
|
| 18 |
# ============================================================
|
| 19 |
|
| 20 |
options(repos = c(CRAN = "https://cloud.r-project.org"))
|
|
|
|
| 35 |
# ============================================================
|
| 36 |
# TOKEN DEBUG
|
| 37 |
# ============================================================
|
|
|
|
| 38 |
token <- Sys.getenv("GROQ_API_KEY")
|
| 39 |
|
|
|
|
| 40 |
token_exists <- token != ""
|
| 41 |
token_length <- if(token_exists) nchar(token) else 0
|
| 42 |
|
| 43 |
+
print("=== GROQ API TOKEN DEBUG ===")
|
|
|
|
| 44 |
print(paste("Token exists:", token_exists))
|
| 45 |
print(paste("Token length:", token_length))
|
| 46 |
if(token_exists) print(paste("Token starts with:", substr(token, 1, 10)))
|
| 47 |
print("===================================")
|
| 48 |
|
|
|
|
| 49 |
HF_API_TOKEN <- token
|
| 50 |
HF_API_URL <- "https://api.groq.com/openai/v1/chat/completions"
|
| 51 |
default_model <- "llama-3.1-8b-instant"
|
|
|
|
| 57 |
available_models <- list(
|
| 58 |
list(id = "llama-3.1-8b-instant", label = "Llama 3.1 8B", provider = "groq", tier = "free"),
|
| 59 |
list(id = "llama-3.3-70b-versatile", label = "Llama 3.3 70B", provider = "groq", tier = "free"),
|
| 60 |
+
list(id = "meta-llama/llama-4-maverick-17b-128e-instruct", label = "Llama 4 Maverick 17B", provider = "groq", tier = "free"),
|
| 61 |
+
list(id = "moonshotai/kimi-k2-instruct-0905", label = "Kimi K2", provider = "groq", tier = "free")
|
| 62 |
)
|
| 63 |
|
| 64 |
model_choices <- setNames(
|
|
|
|
| 66 |
sapply(available_models, function(m) paste0(m$label, " [", m$tier, "]"))
|
| 67 |
)
|
| 68 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
# ============================================================
|
| 70 |
# TEST CONNECTION
|
| 71 |
# ============================================================
|
| 72 |
|
| 73 |
test_api_connection <- function(model_id = default_model) {
|
| 74 |
if (!token_exists) return(list(success = FALSE, error = "No token found"))
|
| 75 |
+
|
| 76 |
tryCatch({
|
| 77 |
response <- POST(
|
| 78 |
url = HF_API_URL,
|
|
|
|
| 88 |
encode = "json",
|
| 89 |
timeout(15)
|
| 90 |
)
|
| 91 |
+
|
| 92 |
status <- status_code(response)
|
| 93 |
if (status == 200) return(list(success = TRUE))
|
| 94 |
+
|
| 95 |
err <- tryCatch(content(response, "text", encoding = "UTF-8"),
|
| 96 |
error = function(e) paste("Status:", status))
|
| 97 |
return(list(success = FALSE,
|
|
|
|
| 115 |
|
| 116 |
query_hf_api <- function(prompt, model_id = default_model, max_length = 500, temperature = 0.7) {
|
| 117 |
if (!token_exists) return(list(success = FALSE, error = "HF_API_TOKEN not set"))
|
| 118 |
+
|
| 119 |
tryCatch({
|
| 120 |
response <- POST(
|
| 121 |
url = HF_API_URL,
|
|
|
|
| 136 |
encode = "json",
|
| 137 |
timeout(60)
|
| 138 |
)
|
| 139 |
+
|
| 140 |
status <- status_code(response)
|
| 141 |
+
|
| 142 |
if (status == 200) {
|
| 143 |
result <- content(response, as = "parsed", encoding = "UTF-8")
|
| 144 |
text <- result$choices[[1]]$message$content
|
| 145 |
return(list(success = TRUE, text = text))
|
| 146 |
}
|
| 147 |
+
|
| 148 |
err <- tryCatch(content(response, "text", encoding = "UTF-8"),
|
| 149 |
error = function(e) paste("Status:", status))
|
| 150 |
return(list(success = FALSE,
|
|
|
|
| 158 |
|
| 159 |
build_system_prompt <- function(rv) {
|
| 160 |
context_parts <- c("CURRENT ANALYSIS RESULTS:")
|
| 161 |
+
|
| 162 |
if (!is.null(rv$qtl_effects_train) && !"Message" %in% colnames(rv$qtl_effects_train)) {
|
| 163 |
n_qtl <- nrow(rv$qtl_effects_train)
|
| 164 |
total_pve <- sum(rv$qtl_effects_train$PVE_Percent, na.rm = TRUE)
|
| 165 |
+
|
| 166 |
context_parts <- c(context_parts,
|
| 167 |
sprintf("\nQTL Results: %d significant QTLs detected above LOD %.1f.", n_qtl, rv$lod_threshold),
|
| 168 |
+
sprintf("Total variance explained by QTLs: %.1f%% (additive + dominance model).", total_pve))
|
| 169 |
+
|
| 170 |
top_qtls <- head(rv$qtl_effects_train[order(-rv$qtl_effects_train$LOD), ], 3)
|
| 171 |
context_parts <- c(context_parts, "\nTop QTLs:")
|
| 172 |
for (i in 1:nrow(top_qtls)) {
|
| 173 |
row <- top_qtls[i, ]
|
| 174 |
context_parts <- c(context_parts,
|
| 175 |
+
sprintf(" %d. %s (Chr %s): LOD=%.2f, PVE=%.1f%%, Additive=%.3f, Dominance=%.3f",
|
| 176 |
+
i, row$Marker, row$Chromosome, row$LOD, row$PVE_Percent,
|
| 177 |
+
row$Additive_Effect, ifelse(is.na(row$Dominance_Effect), 0, row$Dominance_Effect)))
|
| 178 |
}
|
| 179 |
}
|
| 180 |
+
|
| 181 |
if (!is.null(rv$performance_metrics)) {
|
| 182 |
pm <- rv$performance_metrics
|
| 183 |
train_r2 <- pm$Value[pm$Metric == "R\u00b2 (Train)"]
|
|
|
|
| 187 |
sprintf(" Training R\u00b2: %.3f", train_r2),
|
| 188 |
sprintf(" Validation R\u00b2: %.3f", val_r2))
|
| 189 |
}
|
| 190 |
+
|
| 191 |
if (!is.null(rv$epistasis_sig) && !"Message" %in% colnames(rv$epistasis_sig) && nrow(rv$epistasis_sig) > 0) {
|
| 192 |
n_epi <- nrow(rv$epistasis_sig)
|
| 193 |
top_epi <- rv$epistasis_sig[order(rv$epistasis_sig$Interaction_p), ][1, ]
|
|
|
|
| 195 |
sprintf("\nEpistasis: %d significant pairwise interactions detected.", n_epi),
|
| 196 |
sprintf(" Strongest: %s x %s (p=%.4f)", top_epi$QTL1, top_epi$QTL2, top_epi$Interaction_p))
|
| 197 |
}
|
| 198 |
+
|
| 199 |
if (!is.null(rv$selection_metrics) && !"Message" %in% colnames(rv$selection_metrics)) {
|
| 200 |
n_sig <- sum(rv$selection_metrics$Significant, na.rm = TRUE)
|
| 201 |
context_parts <- c(context_parts,
|
| 202 |
sprintf("\nDomestication: %d markers with selection signatures.", n_sig))
|
| 203 |
}
|
| 204 |
+
|
| 205 |
paste(context_parts, collapse = "\n")
|
| 206 |
}
|
| 207 |
|
|
|
|
| 211 |
|
| 212 |
enhanced_rule_response <- function(user_message, rv) {
|
| 213 |
q <- tolower(trimws(user_message))
|
| 214 |
+
|
| 215 |
has_qtl <- !is.null(rv$qtl_effects_train) && !"Message" %in% colnames(rv$qtl_effects_train)
|
| 216 |
has_perf <- !is.null(rv$performance_metrics)
|
| 217 |
has_epi <- !is.null(rv$epistasis_sig) && !"Message" %in% colnames(rv$epistasis_sig) && nrow(rv$epistasis_sig) > 0
|
| 218 |
has_sel <- !is.null(rv$selection_metrics) && !"Message" %in% colnames(rv$selection_metrics)
|
| 219 |
+
|
| 220 |
if (grepl("pve|variance explained|how much variance|percent variance|what is pve", q)) {
|
| 221 |
if (has_qtl) {
|
| 222 |
df <- rv$qtl_effects_train
|
| 223 |
total_pve <- sum(df$PVE_Percent, na.rm = TRUE)
|
| 224 |
top_pve <- df[which.max(df$PVE_Percent), ]
|
| 225 |
+
|
| 226 |
response <- paste0(
|
| 227 |
"\U0001f4ca **PVE (Phenotypic Variance Explained) Analysis**\n\n",
|
| 228 |
+
"**PVE Model Used:** Full additive + dominance model\n",
|
| 229 |
+
" lm(phenotype ~ additive_code + dominance_code)\n\n",
|
| 230 |
"**Your Results:**\n",
|
| 231 |
"\u2022 Total variance explained by all QTLs: **", round(total_pve, 1), "%**\n",
|
| 232 |
"\u2022 Number of QTLs detected: **", nrow(df), "**\n\n",
|
|
|
|
| 234 |
"\u2022 Marker: **", top_pve$Marker, "**\n",
|
| 235 |
"\u2022 Chromosome: ", top_pve$Chromosome, "\n",
|
| 236 |
"\u2022 PVE: **", round(top_pve$PVE_Percent, 1), "%**\n",
|
| 237 |
+
"\u2022 LOD: ", round(top_pve$LOD, 2), "\n",
|
| 238 |
+
"\u2022 Additive effect: ", round(top_pve$Additive_Effect, 3), "\n",
|
| 239 |
+
"\u2022 Dominance effect: ", ifelse(is.na(top_pve$Dominance_Effect), "NA (no het)", round(top_pve$Dominance_Effect, 3)), "\n\n"
|
| 240 |
)
|
| 241 |
+
|
| 242 |
if (top_pve$PVE_Percent > 10) {
|
| 243 |
response <- paste0(response, "\U0001f4a1 This is a **major-effect QTL** (>10% PVE).\n\n")
|
| 244 |
} else if (top_pve$PVE_Percent > 5) {
|
|
|
|
| 246 |
} else {
|
| 247 |
response <- paste0(response, "\U0001f4a1 This is a **minor-effect QTL** (<5% PVE).\n\n")
|
| 248 |
}
|
| 249 |
+
|
| 250 |
response <- paste0(response, "**All QTLs by PVE:**\n")
|
| 251 |
df_sorted <- df[order(-df$PVE_Percent), ]
|
| 252 |
for (i in 1:min(5, nrow(df_sorted))) {
|
| 253 |
row <- df_sorted[i, ]
|
| 254 |
+
response <- paste0(response, sprintf(" %d. %s: %.1f%% (A=%.3f, D=%s)\n",
|
| 255 |
+
i, row$Marker, row$PVE_Percent, row$Additive_Effect,
|
| 256 |
+
ifelse(is.na(row$Dominance_Effect), "NA", round(row$Dominance_Effect, 3))))
|
| 257 |
}
|
| 258 |
return(response)
|
| 259 |
} else {
|
| 260 |
return("No QTL results yet. Please run the QTL analysis first to see PVE values.")
|
| 261 |
}
|
| 262 |
}
|
| 263 |
+
|
| 264 |
if (grepl("model performance|r2|r squared|how good is my model|validation|negative r2", q)) {
|
| 265 |
if (has_perf) {
|
| 266 |
pm <- rv$performance_metrics
|
| 267 |
train_r2 <- pm$Value[pm$Metric == "R\u00b2 (Train)"]
|
| 268 |
val_r2 <- pm$Value[pm$Metric == "R\u00b2 (Validation)"]
|
| 269 |
+
|
| 270 |
response <- paste0(
|
| 271 |
"\U0001f4c8 **Model Performance Summary**\n\n",
|
| 272 |
"\u2022 Training R\u00b2: **", round(train_r2, 3), "**\n",
|
| 273 |
"\u2022 Validation R\u00b2: **", round(val_r2, 3), "**\n\n"
|
| 274 |
)
|
| 275 |
+
|
| 276 |
if (val_r2 < 0) {
|
| 277 |
response <- paste0(response,
|
| 278 |
"\u26a0\ufe0f **Your validation R\u00b2 is negative** (", round(val_r2, 3), ").\n\n",
|
|
|
|
| 296 |
return("Run the QTL analysis first to see model performance metrics.")
|
| 297 |
}
|
| 298 |
}
|
| 299 |
+
|
| 300 |
if (grepl("top qtl|best qtl|highest lod|significant qtl|list qtl|show qtl", q)) {
|
| 301 |
if (has_qtl) {
|
| 302 |
df <- rv$qtl_effects_train[order(-rv$qtl_effects_train$LOD), ]
|
| 303 |
top5 <- head(df, 5)
|
| 304 |
+
|
| 305 |
response <- "\U0001f3af **Top 5 QTLs by LOD Score**\n\n"
|
| 306 |
for (i in 1:nrow(top5)) {
|
| 307 |
row <- top5[i, ]
|
| 308 |
+
dom_str <- ifelse(is.na(row$Dominance_Effect), "NA", as.character(round(row$Dominance_Effect, 3)))
|
| 309 |
response <- paste0(response,
|
| 310 |
i, ". **", row$Marker, "** (Chr ", row$Chromosome, ")\n",
|
| 311 |
" \u2022 LOD: **", round(row$LOD, 2), "**\n",
|
| 312 |
+
" \u2022 PVE: ", round(row$PVE_Percent, 1), "% (additive + dominance)\n",
|
| 313 |
+
" \u2022 Additive effect: ", round(row$Additive_Effect, 3), "\n",
|
| 314 |
+
" \u2022 Dominance effect: ", dom_str, "\n\n")
|
| 315 |
}
|
| 316 |
return(response)
|
| 317 |
} else {
|
| 318 |
return("No significant QTLs detected. Try lowering the LOD threshold.")
|
| 319 |
}
|
| 320 |
}
|
| 321 |
+
|
| 322 |
if (grepl("next steps|what next|recommendations|suggest|advice|what should i do", q)) {
|
| 323 |
if (has_qtl || has_perf || has_epi || has_sel) {
|
| 324 |
response <- "\U0001f52c **Recommended Next Steps**\n\n"
|
| 325 |
+
|
| 326 |
if (has_qtl) {
|
| 327 |
top_qtl <- rv$qtl_effects_train[which.max(rv$qtl_effects_train$LOD), ]
|
| 328 |
response <- paste0(response,
|
|
|
|
| 338 |
response <- paste0(response, "**3. Domestication Analysis**\n",
|
| 339 |
" \u2022 ", sum(rv$selection_metrics$Significant, na.rm = TRUE), " selection signatures\n\n")
|
| 340 |
}
|
| 341 |
+
|
| 342 |
response <- paste0(response,
|
| 343 |
"**4. Functional Analysis**\n",
|
| 344 |
" \u2022 Annotate QTL regions for candidate genes\n\n",
|
|
|
|
| 349 |
return("Run the QTL analysis first to get recommendations.")
|
| 350 |
}
|
| 351 |
}
|
| 352 |
+
|
| 353 |
available <- c()
|
| 354 |
if (has_qtl) available <- c(available, paste(nrow(rv$qtl_effects_train), "QTLs"))
|
| 355 |
if (has_perf) {
|
|
|
|
| 358 |
}
|
| 359 |
if (has_epi) available <- c(available, paste(nrow(rv$epistasis_sig), "interactions"))
|
| 360 |
if (has_sel) available <- c(available, paste(sum(rv$selection_metrics$Significant), "selection signatures"))
|
| 361 |
+
|
| 362 |
if (length(available) > 0) {
|
| 363 |
return(paste0(
|
| 364 |
"I can see you have: ", paste(available, collapse = ", "), ".\n\n",
|
|
|
|
| 368 |
"\u2022 **Model performance**\n",
|
| 369 |
"\u2022 **Next steps**"))
|
| 370 |
}
|
| 371 |
+
|
| 372 |
return(paste0(
|
| 373 |
"\U0001f44b Vanakam! I'm TerraByte-AI powered Companion.\n\n",
|
| 374 |
"**I can help you with:**\n",
|
| 375 |
+
"\u2022 Understanding PVE (additive + dominance model)\n",
|
| 376 |
"\u2022 Interpreting LOD scores\n",
|
| 377 |
"\u2022 Evaluating model performance\n",
|
| 378 |
"\u2022 Detecting epistatic interactions\n\n",
|
| 379 |
"\u2022 any query? contact : ashmithamganesan@gmail.com, P.sinha@cgiar.org\n\n",
|
|
|
|
| 380 |
"Try: **'What is PVE?'** or **'Show me my top QTLs'**"))
|
| 381 |
}
|
| 382 |
|
|
|
|
| 386 |
|
| 387 |
generate_ai_response <- function(user_message, rv, model_id = default_model) {
|
| 388 |
context <- build_system_prompt(rv)
|
| 389 |
+
|
| 390 |
current_use_api <- token_exists
|
| 391 |
+
|
| 392 |
if (current_use_api) {
|
| 393 |
prompt <- paste(
|
| 394 |
"CONTEXT:", context,
|
|
|
|
| 396 |
"\n\nProvide a specific, helpful answer based ONLY on the context above. Be concise but informative.",
|
| 397 |
sep = "\n"
|
| 398 |
)
|
| 399 |
+
|
| 400 |
result <- query_hf_api(prompt, model_id = model_id)
|
| 401 |
+
|
| 402 |
if (result$success) {
|
| 403 |
return(result$text)
|
| 404 |
} else {
|
|
|
|
| 406 |
return(enhanced_rule_response(user_message, rv))
|
| 407 |
}
|
| 408 |
}
|
| 409 |
+
|
| 410 |
return(enhanced_rule_response(user_message, rv))
|
| 411 |
}
|
| 412 |
|
|
|
|
| 416 |
|
| 417 |
ui <- fluidPage(
|
| 418 |
shinyjs::useShinyjs(),
|
| 419 |
+
|
| 420 |
tags$head(
|
| 421 |
tags$link(rel = "stylesheet", type = "text/css",
|
| 422 |
href = "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css"),
|
|
|
|
| 445 |
}
|
| 446 |
Shiny.addCustomMessageHandler('simulateQTLDiscovery', function(message) { simulateQTLDiscovery(); });
|
| 447 |
Shiny.addCustomMessageHandler('resetAnimation', function(message) { resetAnimation(); });
|
|
|
|
| 448 |
Shiny.addCustomMessageHandler('scrollChatBottom', function(message) {
|
| 449 |
setTimeout(function() {
|
| 450 |
var chatBox = document.getElementById('chat_messages');
|
| 451 |
if (chatBox) chatBox.scrollTop = chatBox.scrollHeight;
|
| 452 |
}, 100);
|
| 453 |
});
|
|
|
|
| 454 |
$(document).on('keydown', '#chat_input', function(e) {
|
| 455 |
if (e.key === 'Enter' && !e.shiftKey) {
|
| 456 |
e.preventDefault();
|
| 457 |
$('#send_chat').click();
|
| 458 |
}
|
| 459 |
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 460 |
")),
|
| 461 |
tags$style(HTML("
|
| 462 |
:root {
|
|
|
|
| 476 |
.main-header { background: linear-gradient(135deg, #1c2b3a 0%, #0d1117 100%); border: 1px solid var(--border); border-left: 3px solid var(--accent); color: var(--text-primary); padding: 20px 24px; border-radius: 6px; margin-bottom: 20px; }
|
| 477 |
.main-header h2 { font-family: var(--font-mono); font-size: 1.3rem; font-weight: 600; color: var(--accent); }
|
| 478 |
.main-header p { color: var(--text-secondary); margin-top: 6px; font-size: 13px; }
|
| 479 |
+
.pve-formula-box { background: #0d1a0d; border: 1px solid var(--success); border-left: 3px solid var(--success); border-radius: 6px; padding: 12px 16px; margin: 10px 0; font-family: var(--font-mono); font-size: 12px; color: #7ee787; }
|
| 480 |
+
.pve-formula-box .formula-title { font-weight: 600; color: var(--success); margin-bottom: 6px; }
|
| 481 |
.card { background-color: var(--bg-secondary); border: 1px solid var(--border); border-radius: 6px; margin-bottom: 20px; }
|
| 482 |
.card-header { background-color: var(--bg-tertiary); border-bottom: 1px solid var(--border); padding: 12px 16px; font-family: var(--font-mono); font-size: 12px; color: var(--text-secondary); letter-spacing: 0.5px; text-transform: uppercase; }
|
| 483 |
.card-body { padding: 16px; }
|
|
|
|
| 516 |
.simulation-controls { margin: 12px 0; display: flex; gap: 8px; }
|
| 517 |
.simulation-btn { background-color: transparent; color: var(--purple); border: 1px solid var(--purple); padding: 5px 12px; border-radius: 4px; cursor: pointer; font-family: var(--font-mono); font-size: 11px; transition: all 0.15s; }
|
| 518 |
.simulation-btn:hover { background-color: var(--purple); color: #0d1117; }
|
|
|
|
| 519 |
/* ---- Chat Panel ---- */
|
| 520 |
#chat-panel { position: fixed; bottom: 20px; right: 20px; z-index: 9999; width: 440px; display: flex; flex-direction: column; }
|
| 521 |
#chat-toggle-btn { align-self: flex-end; width: 56px; height: 56px; border-radius: 50%; background: linear-gradient(135deg, var(--accent), var(--purple)); border: none; cursor: pointer; display: flex; align-items: center; justify-content: center; box-shadow: 0 4px 20px rgba(88,166,255,0.4); transition: all 0.2s; color: #0d1117; font-size: 24px; }
|
|
|
|
| 532 |
#chat-header p.rule-mode { color: var(--warning); }
|
| 533 |
#chat-close-btn { background: none; border: none; color: var(--text-muted); cursor: pointer; font-size: 18px; padding: 4px; transition: color 0.15s; flex-shrink: 0; }
|
| 534 |
#chat-close-btn:hover { color: var(--text-primary); }
|
|
|
|
|
|
|
| 535 |
.chat-model-selector { display: flex; align-items: center; gap: 8px; padding: 4px 0; }
|
| 536 |
.chat-model-selector label { color: var(--text-muted); font-size: 10px; font-family: var(--font-mono); white-space: nowrap; margin: 0; }
|
| 537 |
.chat-model-selector select { flex: 1; background: var(--bg-primary) !important; border: 1px solid var(--border) !important; color: var(--text-secondary) !important; border-radius: 4px; font-size: 11px; font-family: var(--font-mono); padding: 3px 6px; cursor: pointer; }
|
|
|
|
| 541 |
.model-status-dot.offline { background: var(--warning); box-shadow: 0 0 6px var(--warning); }
|
| 542 |
.test-model-btn { background: transparent; border: 1px solid var(--border); color: var(--text-muted); border-radius: 3px; padding: 2px 7px; font-size: 10px; font-family: var(--font-mono); cursor: pointer; transition: all 0.15s; white-space: nowrap; }
|
| 543 |
.test-model-btn:hover { border-color: var(--accent); color: var(--accent); }
|
|
|
|
| 544 |
#chat_messages { flex: 1; overflow-y: auto; padding: 16px; display: flex; flex-direction: column; gap: 12px; background: var(--bg-primary); }
|
| 545 |
.chat-msg { max-width: 92%; animation: fadeIn 0.3s ease; }
|
| 546 |
@keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
|
|
|
|
| 557 |
.typing-dot:nth-child(2) { animation-delay: 0.2s; }
|
| 558 |
.typing-dot:nth-child(3) { animation-delay: 0.4s; }
|
| 559 |
@keyframes typingBounce { 0%, 60%, 100% { transform: translateY(0); } 30% { transform: translateY(-8px); } }
|
|
|
|
|
|
|
| 560 |
.quick-questions { padding: 8px 16px; display: flex; flex-wrap: wrap; gap: 6px; border-bottom: 1px solid var(--border); background: var(--bg-secondary); }
|
| 561 |
.quick-q-btn { background: var(--bg-tertiary); border: 1px solid var(--border); color: var(--text-secondary); border-radius: 16px; padding: 4px 12px; font-size: 11px; cursor: pointer; transition: all 0.15s; }
|
| 562 |
.quick-q-btn:hover { border-color: var(--accent); color: var(--accent); background: rgba(88,166,255,0.1); }
|
|
|
|
|
|
|
| 563 |
#chat-footer { padding: 12px 16px; border-top: 1px solid var(--border); background: var(--bg-tertiary); }
|
| 564 |
#chat_input { width: 100%; background: var(--bg-secondary) !important; border: 1px solid var(--border) !important; border-radius: 8px; color: var(--text-primary) !important; font-size: 13px; resize: none; padding: 10px 12px; font-family: var(--font-sans); margin-bottom: 8px; }
|
| 565 |
#chat_input:focus { border-color: var(--accent) !important; outline: none; }
|
|
|
|
|
|
|
| 566 |
.chat-file-row { display: flex; align-items: center; gap: 8px; margin-bottom: 8px; }
|
| 567 |
#chat_file_upload_btn { background: transparent; border: 1px solid var(--border); color: var(--text-muted); border-radius: 6px; padding: 6px 10px; font-size: 12px; cursor: pointer; transition: all 0.15s; display: flex; align-items: center; gap: 5px; white-space: nowrap; }
|
| 568 |
#chat_file_upload_btn:hover { border-color: var(--accent); color: var(--accent); }
|
|
|
|
| 575 |
#send_chat:disabled { opacity: 0.5; cursor: not-allowed; }
|
| 576 |
#clear_chat { background: transparent; color: var(--text-muted); border: 1px solid var(--border); border-radius: 6px; padding: 8px 12px; font-family: var(--font-mono); font-size: 12px; cursor: pointer; transition: all 0.15s; }
|
| 577 |
#clear_chat:hover { border-color: var(--danger); color: var(--danger); }
|
|
|
|
|
|
|
|
|
|
|
|
|
| 578 |
"))
|
| 579 |
),
|
| 580 |
+
|
| 581 |
navbarPage(
|
| 582 |
title = tags$span(tags$i(class = "fas fa-dna", style = "margin-right:8px; color:#58a6ff;"), "QTL-Mapper AI"),
|
| 583 |
id = "nav",
|
| 584 |
+
|
| 585 |
# ---- Data Upload tab ----
|
| 586 |
tabPanel("Data Upload", icon = icon("upload"),
|
| 587 |
div(class = "main-header",
|
| 588 |
h2(tags$i(class = "fas fa-upload", style = "margin-right:8px;"), "Data Upload"),
|
| 589 |
p("Upload genotype, phenotype, and population data for comprehensive QTL analysis with AI assistance")
|
| 590 |
),
|
| 591 |
+
fluidRow(
|
| 592 |
+
column(12,
|
| 593 |
+
div(class = "pve-formula-box",
|
| 594 |
+
div(class = "formula-title", tags$i(class = "fas fa-square-root-alt", style = "margin-right:6px;"), "PVE Formula (FIXED) β Additive + Dominance Model"),
|
| 595 |
+
tags$pre(style = "background:transparent; border:none; margin:0; color:#7ee787; font-size:11px;",
|
| 596 |
+
"Additive code: a = genotype (0, 1, 2)\n",
|
| 597 |
+
"Dominance code: d = ifelse(genotype == 1, 1, 0) [heterozygote indicator]\n",
|
| 598 |
+
"Full model: lm(phenotype ~ a + d)\n",
|
| 599 |
+
"PVE (%) = RΒ²_full Γ 100\n",
|
| 600 |
+
"Additive_Effect = Ξ²_a [allele substitution effect]\n",
|
| 601 |
+
"Dominance_Effect = Ξ²_d [deviation of heterozygote from midparent]\n",
|
| 602 |
+
"Reference: Falconer & Mackay (1996); Lynch & Walsh (1998)")
|
| 603 |
+
)
|
| 604 |
+
)
|
| 605 |
+
),
|
| 606 |
fluidRow(
|
| 607 |
column(4,
|
| 608 |
div(class = "card",
|
|
|
|
| 654 |
)
|
| 655 |
)
|
| 656 |
),
|
| 657 |
+
|
| 658 |
# ---- Domestication tab ----
|
| 659 |
tabPanel("Domestication", icon = icon("leaf"),
|
| 660 |
div(class = "main-header",
|
|
|
|
| 698 |
)
|
| 699 |
)
|
| 700 |
),
|
| 701 |
+
|
| 702 |
# ---- Results tab ----
|
| 703 |
tabPanel("Results", icon = icon("chart-line"),
|
| 704 |
div(class = "main-header",
|
| 705 |
h2(tags$i(class = "fas fa-chart-line", style = "margin-right:8px;"), "QTL Analysis Results"),
|
| 706 |
+
p("LOD scores, QTL effects (additive + dominance), model performance, and epistasis analysis")
|
| 707 |
),
|
| 708 |
fluidRow(
|
| 709 |
column(6, div(class = "card", div(class = "card-header", "Manhattan Plot (LOD Scores)"), div(class = "card-body", plotlyOutput("lod_plot_2d", height = "500px")))),
|
|
|
|
| 725 |
),
|
| 726 |
fluidRow(
|
| 727 |
column(12, div(class = "card",
|
| 728 |
+
div(class = "card-header", "QTL Effects β Training Set (Additive + Dominance PVE)"),
|
| 729 |
div(class = "card-body", DTOutput("qtl_effects_table_train"), tags$br(), downloadButton("download_train_results", "Download"))
|
| 730 |
))
|
| 731 |
),
|
|
|
|
| 739 |
))
|
| 740 |
)
|
| 741 |
),
|
| 742 |
+
|
| 743 |
# ---- Interpretation tab ----
|
| 744 |
tabPanel("Interpretation", icon = icon("lightbulb"),
|
| 745 |
div(class = "main-header",
|
| 746 |
h2(tags$i(class = "fas fa-lightbulb", style = "margin-right:8px;"), "Results Interpretation"),
|
| 747 |
+
p("Comprehensive interpretation of QTL (additive + dominance) and domestication analysis")
|
| 748 |
),
|
| 749 |
fluidRow(column(12, div(class = "card", div(class = "card-header", "Analysis Summary"), div(class = "card-body", uiOutput("analysis_summary"))))),
|
| 750 |
fluidRow(
|
| 751 |
column(6, div(class = "card", div(class = "card-header", "QTL Significance"), div(class = "card-body", uiOutput("qtl_interpretation")))),
|
| 752 |
+
column(6, div(class = "card", div(class = "card-header", "Effect Sizes (Additive + Dominance)"), div(class = "card-body", uiOutput("effect_interpretation"))))
|
| 753 |
),
|
| 754 |
fluidRow(column(12, div(class = "card", div(class = "card-header", "Epistasis"), div(class = "card-body", uiOutput("epistasis_interpretation"))))),
|
| 755 |
fluidRow(column(12, div(class = "card", div(class = "card-header", "Recommendations"), div(class = "card-body", uiOutput("recommendations")))))
|
| 756 |
),
|
| 757 |
+
|
| 758 |
# ---- About tab ----
|
| 759 |
tabPanel("About", icon = icon("info-circle"),
|
| 760 |
div(class = "main-header",
|
|
|
|
| 765 |
column(8, offset = 2,
|
| 766 |
div(class = "card",
|
| 767 |
div(class = "card-body",
|
| 768 |
+
h4(style = "color:#58a6ff; font-family:'IBM Plex Mono'; margin-bottom:12px;", "PVE Formula β FIXED (v2)"),
|
| 769 |
+
div(class = "pve-formula-box",
|
| 770 |
+
tags$pre(style = "background:transparent; border:none; margin:0; color:#7ee787; font-size:11px;",
|
| 771 |
+
"OLD (incorrect):\n lm(phenotype ~ additive_code) β PVE = RΒ² Γ 100\n [Ignores dominance; underestimates PVE for dominant loci]\n\n",
|
| 772 |
+
"NEW (correct β this version):\n a = additive code (0, 1, 2)\n d = dominance code (ifelse(geno==1, 1, 0))\n lm(phenotype ~ a + d) β PVE = RΒ²_full Γ 100\n Additive_Effect = Ξ²_a\n Dominance_Effect = Ξ²_d\n [Correctly partitions additive & dominance variance]\n\n",
|
| 773 |
+
"Ref: Falconer & Mackay (1996); Lynch & Walsh (1998)")
|
| 774 |
+
),
|
| 775 |
+
h4(style = "color:#58a6ff; font-family:'IBM Plex Mono'; margin:12px 0;", "Methodology"),
|
| 776 |
tags$ul(style = "color:#8b949e; line-height:2;",
|
| 777 |
tags$li("Random Forest for QTL mapping with variable importance scoring"),
|
| 778 |
tags$li("LOD scores derived from marker importance (-log10 scale)"),
|
| 779 |
+
tags$li("Additive (Ξ²_a) and dominance (Ξ²_d) effects via full linear model lm(y ~ a + d)"),
|
| 780 |
+
tags$li("PVE = RΒ²_full Γ 100 β accounts for both additive and dominance variance"),
|
| 781 |
+
tags$li("Dominance ratio = |Ξ²_d / Ξ²_a|: >1 overdominance, ~1 complete dominance, <0.5 additive"),
|
| 782 |
tags$li("Epistasis analysis: pairwise QTL x marker interactions"),
|
| 783 |
+
tags$li("Domestication: Fst, nucleotide diversity (Pi), Tajima's D")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 784 |
),
|
| 785 |
h4(style = "color:#58a6ff; font-family:'IBM Plex Mono'; margin:12px 0;", "Interpretation Thresholds"),
|
| 786 |
tags$ul(style = "color:#8b949e; line-height:2;",
|
| 787 |
tags$li("LOD > 3: Suggestive QTL | LOD > 5: Significant QTL"),
|
| 788 |
+
tags$li("PVE > 10%: Major-effect QTL (full additive+dominance model)"),
|
| 789 |
+
tags$li("|Dominance/Additive| > 1: Overdominance"),
|
| 790 |
tags$li("Fst > 0.2: Strong population differentiation"),
|
| 791 |
+
tags$li("Tajima's D < -2: Potential selective sweep")
|
|
|
|
| 792 |
)
|
| 793 |
)
|
| 794 |
)
|
|
|
|
| 796 |
)
|
| 797 |
)
|
| 798 |
),
|
| 799 |
+
|
| 800 |
# ============================================================
|
| 801 |
+
# FLOATING CHAT PANEL
|
| 802 |
# ============================================================
|
| 803 |
tags$div(id = "chat-panel",
|
| 804 |
tags$div(id = "chat-window",
|
| 805 |
+
|
|
|
|
| 806 |
tags$div(id = "chat-header",
|
| 807 |
tags$div(class = "chat-header-top",
|
| 808 |
tags$div(class = "chat-title",
|
|
|
|
| 818 |
onclick = "document.getElementById('chat-window').classList.remove('open');",
|
| 819 |
tags$i(class = "fas fa-times"))
|
| 820 |
),
|
|
|
|
|
|
|
| 821 |
tags$div(class = "chat-model-selector",
|
| 822 |
tags$label(tags$i(class = "fas fa-robot"), " Model:"),
|
| 823 |
tags$div(id = "model_status_dot", class = paste0("model-status-dot ", if (token_exists) "online" else "offline")),
|
|
|
|
| 828 |
actionButton("test_model_btn", "Test", class = "test-model-btn")
|
| 829 |
)
|
| 830 |
),
|
| 831 |
+
|
|
|
|
| 832 |
tags$div(class = "quick-questions",
|
| 833 |
tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q','What is PVE?',{priority:'event'});", "PVE meaning"),
|
| 834 |
tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q','What are my top QTLs?',{priority:'event'});", "Top QTLs"),
|
| 835 |
tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q','Why is my R2 negative?',{priority:'event'});","Negative R2"),
|
| 836 |
tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q','What should I do next?',{priority:'event'});","Next steps")
|
| 837 |
),
|
| 838 |
+
|
|
|
|
| 839 |
tags$div(id = "chat_messages", uiOutput("chat_display")),
|
| 840 |
+
|
|
|
|
| 841 |
tags$div(id = "chat-footer",
|
|
|
|
|
|
|
| 842 |
tags$div(class = "chat-file-row",
|
| 843 |
tags$label(
|
| 844 |
id = "chat_file_upload_btn",
|
|
|
|
| 855 |
onclick = "document.getElementById('chat_file_preview').style.display='none'; document.getElementById('chat_file_preview').innerHTML=''; Shiny.setInputValue('clear_chat_file', Math.random());",
|
| 856 |
tags$i(class = "fas fa-times"))
|
| 857 |
),
|
|
|
|
|
|
|
| 858 |
tags$textarea(id = "chat_input",
|
| 859 |
placeholder = "Ask about your results... (Enter to send)",
|
| 860 |
rows = "2"),
|
|
|
|
|
|
|
| 861 |
tags$div(class = "chat-actions",
|
| 862 |
actionButton("send_chat", "Send", icon = icon("paper-plane"), class = "btn-primary"),
|
| 863 |
actionButton("clear_chat", "Clear", icon = icon("trash-alt"), class = "btn-danger")
|
| 864 |
)
|
| 865 |
)
|
| 866 |
),
|
|
|
|
|
|
|
| 867 |
tags$button(id = "chat-toggle-btn",
|
| 868 |
onclick = "document.getElementById('chat-window').classList.toggle('open');",
|
| 869 |
tags$i(class = "fas fa-robot"))
|
| 870 |
),
|
| 871 |
+
|
|
|
|
| 872 |
tags$script(HTML("
|
| 873 |
$(document).on('change', '#chat_file_upload', function() {
|
| 874 |
var file = this.files[0];
|
|
|
|
| 886 |
# ============================================================
|
| 887 |
|
| 888 |
server <- function(input, output, session) {
|
| 889 |
+
|
| 890 |
values <- reactiveValues(
|
| 891 |
genotype_data = NULL,
|
| 892 |
phenotype_data = NULL,
|
|
|
|
| 900 |
model_fit = NULL,
|
| 901 |
phenotype_values = NULL,
|
| 902 |
qtl_effects_train = NULL,
|
|
|
|
| 903 |
performance_metrics = NULL,
|
| 904 |
train_predictions = NULL,
|
| 905 |
test_predictions = NULL,
|
|
|
|
| 912 |
is_typing = FALSE,
|
| 913 |
lod_threshold = 2,
|
| 914 |
current_model = default_model,
|
|
|
|
| 915 |
pending_file_content = NULL,
|
| 916 |
pending_file_name = NULL
|
| 917 |
)
|
| 918 |
+
|
| 919 |
+
# ---- Selected model ----
|
| 920 |
observe({
|
| 921 |
req(input$selected_model)
|
| 922 |
values$current_model <- input$selected_model
|
|
|
|
|
|
|
| 923 |
model_label <- names(model_choices)[model_choices == input$selected_model]
|
|
|
|
|
|
|
|
|
|
| 924 |
shinyjs::html("model_status_text",
|
| 925 |
if (token_exists) paste("AI:", gsub(".*\\[(.*)\\]", "\\1", model_label), "- ready")
|
| 926 |
else "Rule-based mode (no token)")
|
| 927 |
})
|
| 928 |
+
|
| 929 |
+
# ---- Test model ----
|
| 930 |
observeEvent(input$test_model_btn, {
|
| 931 |
req(input$selected_model)
|
| 932 |
add_message("assistant", paste0("\u23f3 Testing model: **", gsub(".*/", "", input$selected_model), "**..."))
|
|
|
|
| 933 |
result <- test_api_connection(input$selected_model)
|
| 934 |
if (result$success) {
|
| 935 |
+
add_message("assistant", paste0("\u2705 **", gsub(".*/", "", input$selected_model), "** is working!"))
|
| 936 |
shinyjs::runjs("document.getElementById('model_status_dot').className = 'model-status-dot online';")
|
| 937 |
} else {
|
| 938 |
+
add_message("assistant", paste0("\u274c Test failed: ", result$error))
|
|
|
|
| 939 |
shinyjs::runjs("document.getElementById('model_status_dot').className = 'model-status-dot offline';")
|
| 940 |
}
|
| 941 |
})
|
| 942 |
+
|
| 943 |
# ---- Chat helpers ----
|
| 944 |
add_message <- function(role, content, model_used = NULL) {
|
| 945 |
timestamp <- format(Sys.time(), "%H:%M")
|
|
|
|
| 950 |
values$chat_messages <- tail(values$chat_messages, 100)
|
| 951 |
session$sendCustomMessage("scrollChatBottom", list())
|
| 952 |
}
|
| 953 |
+
|
| 954 |
process_message <- function(user_text, file_content = NULL, file_name = NULL) {
|
| 955 |
if (nchar(trimws(user_text)) == 0 && is.null(file_content)) return()
|
| 956 |
+
|
|
|
|
| 957 |
full_message <- user_text
|
| 958 |
if (!is.null(file_content) && nchar(trimws(file_content)) > 0) {
|
| 959 |
full_message <- paste0(user_text,
|
|
|
|
| 962 |
substr(file_content, 1, 3000),
|
| 963 |
if (nchar(file_content) > 3000) "\n[... truncated ...]" else "")
|
| 964 |
}
|
| 965 |
+
|
| 966 |
add_message("user", full_message)
|
| 967 |
values$is_typing <- TRUE
|
| 968 |
+
|
| 969 |
model_id <- isolate(values$current_model)
|
| 970 |
response <- generate_ai_response(full_message, values, model_id = model_id)
|
| 971 |
+
|
| 972 |
values$is_typing <- FALSE
|
| 973 |
model_short <- gsub(".*/([^:]+):.*", "\\1", model_id)
|
| 974 |
add_message("assistant", response, model_used = if (token_exists) model_short else NULL)
|
| 975 |
+
|
|
|
|
| 976 |
values$pending_file_content <- NULL
|
| 977 |
values$pending_file_name <- NULL
|
| 978 |
}
|
| 979 |
+
|
|
|
|
| 980 |
observeEvent(input$chat_file_upload, {
|
| 981 |
req(input$chat_file_upload)
|
| 982 |
file_path <- input$chat_file_upload$datapath
|
| 983 |
file_name <- input$chat_file_upload$name
|
| 984 |
ext <- tolower(tools::file_ext(file_name))
|
| 985 |
+
|
| 986 |
tryCatch({
|
| 987 |
file_content <- if (ext %in% c("csv", "txt", "tsv")) {
|
| 988 |
paste(readLines(file_path, n = 200), collapse = "\n")
|
| 989 |
} else {
|
| 990 |
paste0("[Binary file: ", file_name, " - ", round(file.info(file_path)$size / 1024, 1), " KB]")
|
| 991 |
}
|
|
|
|
| 992 |
values$pending_file_content <- file_content
|
| 993 |
values$pending_file_name <- file_name
|
| 994 |
}, error = function(e) {
|
| 995 |
showNotification(paste("Could not read file:", e$message), type = "warning")
|
| 996 |
})
|
| 997 |
})
|
| 998 |
+
|
|
|
|
| 999 |
observeEvent(input$clear_chat_file, {
|
| 1000 |
values$pending_file_content <- NULL
|
| 1001 |
values$pending_file_name <- NULL
|
| 1002 |
})
|
| 1003 |
+
|
|
|
|
| 1004 |
observeEvent(input$send_chat, {
|
| 1005 |
+
user_text <- trimws(input$chat_input)
|
| 1006 |
file_content <- isolate(values$pending_file_content)
|
| 1007 |
file_name <- isolate(values$pending_file_name)
|
|
|
|
| 1008 |
if (nchar(user_text) == 0 && is.null(file_content)) return()
|
|
|
|
| 1009 |
updateTextAreaInput(session, "chat_input", value = "")
|
|
|
|
| 1010 |
shinyjs::runjs("
|
| 1011 |
document.getElementById('chat_file_preview').style.display = 'none';
|
| 1012 |
document.getElementById('chat_file_preview').innerHTML = '';
|
| 1013 |
")
|
|
|
|
| 1014 |
process_message(user_text, file_content, file_name)
|
| 1015 |
})
|
| 1016 |
+
|
| 1017 |
observeEvent(input$quick_q, { req(input$quick_q); process_message(input$quick_q) })
|
| 1018 |
+
|
| 1019 |
observeEvent(input$clear_chat, {
|
| 1020 |
values$chat_messages <- list()
|
| 1021 |
add_message("assistant", "Chat cleared. How can I help?")
|
| 1022 |
})
|
| 1023 |
+
|
|
|
|
| 1024 |
observe({
|
| 1025 |
if (length(values$chat_messages) == 0) {
|
| 1026 |
mode_msg <- if (token_exists) {
|
| 1027 |
+
paste0("I have access to **", length(available_models), " AI models** via Groq.\n",
|
| 1028 |
"Select a model above and click **Test** to verify it's working!")
|
| 1029 |
} else {
|
| 1030 |
+
"I'm using rule-based responses. Set **GROQ_API_KEY** in Space secrets to enable AI models."
|
| 1031 |
}
|
| 1032 |
add_message("assistant", paste0(
|
| 1033 |
"\U0001f44b Vanakam! I'm TerraByte - An AI powered companion.\n\n",
|
| 1034 |
mode_msg,
|
| 1035 |
+
"\n\n**PVE is now calculated using the full additive + dominance model.**\n\n",
|
| 1036 |
+
"**I can help you with:**\n",
|
| 1037 |
+
"\u2022 **What is PVE?** - Full additive + dominance variance explained\n",
|
| 1038 |
+
"\u2022 **Show top QTLs** - Including dominance effects\n",
|
| 1039 |
"\u2022 **Model performance** - Why is my R\u00b2 negative?\n",
|
| 1040 |
"\u2022 **Next steps** - Recommendations\n",
|
| 1041 |
"\u2022 **Upload files** - Use the paperclip to attach CSV/TXT data\n\n",
|
| 1042 |
+
"Try: **'What is PVE?'**"
|
| 1043 |
))
|
| 1044 |
}
|
| 1045 |
})
|
| 1046 |
+
|
|
|
|
| 1047 |
output$chat_display <- renderUI({
|
| 1048 |
messages <- values$chat_messages
|
| 1049 |
if (length(messages) == 0) return(NULL)
|
| 1050 |
+
|
| 1051 |
elems <- lapply(messages, function(msg) {
|
| 1052 |
content_html <- HTML(gsub("\n", "<br>", htmltools::htmlEscape(msg$content)))
|
|
|
|
| 1053 |
meta_content <- tagList(
|
| 1054 |
span(msg$time),
|
| 1055 |
if (!is.null(msg$model) && msg$role == "assistant")
|
| 1056 |
span(class = "model-tag", paste0("[", msg$model, "]"))
|
| 1057 |
)
|
|
|
|
| 1058 |
div(class = paste("chat-msg", msg$role),
|
| 1059 |
div(class = "chat-bubble", content_html),
|
| 1060 |
div(class = "chat-meta", meta_content))
|
| 1061 |
})
|
| 1062 |
+
|
| 1063 |
if (values$is_typing) {
|
| 1064 |
elems <- c(elems, list(
|
| 1065 |
div(class = "chat-msg assistant",
|
|
|
|
| 1068 |
}
|
| 1069 |
do.call(tagList, elems)
|
| 1070 |
})
|
| 1071 |
+
|
| 1072 |
# ============================================================
|
| 1073 |
# DATA LOADING
|
| 1074 |
# ============================================================
|
| 1075 |
+
|
| 1076 |
observeEvent(input$genotype_file, {
|
| 1077 |
req(input$genotype_file)
|
| 1078 |
tryCatch({
|
| 1079 |
all_data <- readLines(input$genotype_file$datapath)
|
| 1080 |
if (length(all_data) < 4) { showNotification("Genotype file must have at least 4 rows", type = "error"); return() }
|
| 1081 |
+
|
| 1082 |
header <- strsplit(all_data[1], ",")[[1]]
|
| 1083 |
chromosome_row <- strsplit(all_data[2], ",")[[1]]
|
| 1084 |
position_row <- strsplit(all_data[3], ",")[[1]]
|
| 1085 |
+
|
| 1086 |
genotype_data <- read.csv(text = all_data[-(1:3)], header = FALSE)
|
| 1087 |
colnames(genotype_data) <- header
|
| 1088 |
rownames(genotype_data) <- genotype_data[, 1]
|
| 1089 |
genotype_data <- genotype_data[, -1]
|
| 1090 |
+
|
| 1091 |
for (col in colnames(genotype_data))
|
| 1092 |
genotype_data[[col]] <- as.numeric(as.character(genotype_data[[col]]))
|
| 1093 |
+
|
| 1094 |
values$all_markers <- data.frame(
|
| 1095 |
Marker = colnames(genotype_data),
|
| 1096 |
Chromosome = chromosome_row[-1],
|
| 1097 |
Position = as.numeric(position_row[-1]),
|
| 1098 |
stringsAsFactors = FALSE)
|
| 1099 |
+
|
| 1100 |
values$genotype_data <- genotype_data
|
| 1101 |
values$chromosome_info <- chromosome_row[-1]
|
| 1102 |
values$position_info <- as.numeric(position_row[-1])
|
| 1103 |
+
|
| 1104 |
showNotification("Genotype data loaded", type = "message")
|
| 1105 |
add_message("assistant", paste0("\u2705 Loaded genotype data: **", ncol(genotype_data), " markers**, **", nrow(genotype_data), " samples**"))
|
| 1106 |
}, error = function(e) showNotification(paste("Error:", e$message), type = "error"))
|
| 1107 |
})
|
| 1108 |
+
|
| 1109 |
observeEvent(input$phenotype_file, {
|
| 1110 |
req(input$phenotype_file)
|
| 1111 |
tryCatch({
|
| 1112 |
phenotype_data <- read.csv(input$phenotype_file$datapath)
|
| 1113 |
rownames(phenotype_data) <- phenotype_data[, 1]
|
| 1114 |
phenotype_data <- phenotype_data[, -1]
|
| 1115 |
+
|
| 1116 |
for (col in colnames(phenotype_data))
|
| 1117 |
phenotype_data[[col]] <- as.numeric(as.character(phenotype_data[[col]]))
|
| 1118 |
+
|
| 1119 |
values$phenotype_data <- phenotype_data
|
| 1120 |
updateSelectInput(session, "phenotype_column",
|
| 1121 |
choices = colnames(phenotype_data),
|
| 1122 |
selected = colnames(phenotype_data)[1])
|
| 1123 |
+
|
| 1124 |
showNotification("Phenotype data loaded", type = "message")
|
| 1125 |
add_message("assistant", paste0("\u2705 Loaded phenotype data: **", ncol(phenotype_data), " traits**, **", nrow(phenotype_data), " samples**"))
|
| 1126 |
}, error = function(e) showNotification(paste("Error:", e$message), type = "error"))
|
| 1127 |
})
|
| 1128 |
+
|
| 1129 |
observeEvent(input$pop_file, {
|
| 1130 |
req(input$pop_file)
|
| 1131 |
tryCatch({
|
|
|
|
| 1138 |
add_message("assistant", paste0("\u2705 Loaded population data (", nrow(pop_data), " samples)"))
|
| 1139 |
}, error = function(e) showNotification(paste("Error:", e$message), type = "error"))
|
| 1140 |
})
|
| 1141 |
+
|
| 1142 |
observeEvent(input$test_genotype_file, {
|
| 1143 |
req(input$test_genotype_file)
|
| 1144 |
tryCatch({
|
| 1145 |
all_data <- readLines(input$test_genotype_file$datapath)
|
| 1146 |
header <- strsplit(all_data[1], ",")[[1]]
|
| 1147 |
+
|
| 1148 |
genotype_data <- read.csv(text = all_data[-(1:3)], header = FALSE)
|
| 1149 |
colnames(genotype_data) <- header
|
| 1150 |
rownames(genotype_data) <- genotype_data[, 1]
|
| 1151 |
genotype_data <- genotype_data[, -1]
|
| 1152 |
+
|
| 1153 |
for (col in colnames(genotype_data))
|
| 1154 |
genotype_data[[col]] <- as.numeric(as.character(genotype_data[[col]]))
|
| 1155 |
+
|
| 1156 |
values$test_genotype_data <- genotype_data
|
| 1157 |
values$has_test_data <- TRUE
|
| 1158 |
showNotification("Test genotype data loaded", type = "message")
|
| 1159 |
}, error = function(e) showNotification(paste("Error:", e$message), type = "error"))
|
| 1160 |
})
|
| 1161 |
+
|
|
|
|
| 1162 |
output$geno_preview <- renderDT({ req(input$genotype_file); datatable(head(read.csv(input$genotype_file$datapath), 10), options = list(scrollX = TRUE, pageLength = 5)) })
|
| 1163 |
output$pheno_preview <- renderDT({ req(input$phenotype_file); datatable(head(read.csv(input$phenotype_file$datapath), 10), options = list(scrollX = TRUE, pageLength = 5)) })
|
| 1164 |
output$test_geno_preview <- renderDT({ req(input$test_genotype_file); datatable(head(read.csv(input$test_genotype_file$datapath), 10), options = list(scrollX = TRUE, pageLength = 5)) })
|
| 1165 |
output$pop_preview <- renderDT({ req(input$pop_file); datatable(head(read.csv(input$pop_file$datapath), 10), options = list(scrollX = TRUE, pageLength = 5)) })
|
| 1166 |
output$predicted_test_pheno_preview <- renderDT({ req(values$predicted_test_phenotype_data); datatable(values$predicted_test_phenotype_data, options = list(scrollX = TRUE, pageLength = 5)) })
|
| 1167 |
+
|
| 1168 |
+
# ============================================================
|
| 1169 |
+
# QTL EFFECT CALCULATION β FIXED PVE (ADDITIVE + DOMINANCE)
|
| 1170 |
# ============================================================
|
| 1171 |
+
#
|
| 1172 |
+
# STATISTICAL MODEL (Falconer & Mackay 1996; Lynch & Walsh 1998):
|
| 1173 |
+
#
|
| 1174 |
+
# For a biallelic marker with genotypes AA(0), Aa(1), aa(2):
|
| 1175 |
+
# Additive code: a_i = genotype value (0, 1, 2)
|
| 1176 |
+
# Dominance code: d_i = ifelse(genotype == 1, 1, 0) [1 only for heterozygotes]
|
| 1177 |
+
#
|
| 1178 |
+
# Full model: Y = mu + beta_a * a + beta_d * d + epsilon
|
| 1179 |
+
#
|
| 1180 |
+
# Interpretation:
|
| 1181 |
+
# beta_a = Additive_Effect = allele substitution effect (per allele copy)
|
| 1182 |
+
# beta_d = Dominance_Effect = deviation of heterozygote from midparent value
|
| 1183 |
+
# RΒ²_full = proportion of phenotypic variance explained by BOTH effects
|
| 1184 |
+
# PVE (%) = RΒ²_full Γ 100
|
| 1185 |
+
#
|
| 1186 |
+
# Dominance ratio = |beta_d / beta_a|:
|
| 1187 |
+
# ~0 β purely additive
|
| 1188 |
+
# ~0.5 β partial dominance
|
| 1189 |
+
# ~1 β complete dominance
|
| 1190 |
+
# >1 β overdominance
|
| 1191 |
# ============================================================
|
| 1192 |
+
|
| 1193 |
calculate_qtl_effects <- function(genotype_matrix, phenotype_vector, marker_names) {
|
| 1194 |
effects_list <- list()
|
| 1195 |
+
|
| 1196 |
for (marker in marker_names) {
|
| 1197 |
if (!marker %in% colnames(genotype_matrix)) next
|
| 1198 |
+
|
| 1199 |
geno <- genotype_matrix[, marker]
|
| 1200 |
pheno <- phenotype_vector
|
| 1201 |
valid_idx <- !is.na(geno) & !is.na(pheno)
|
| 1202 |
geno <- geno[valid_idx]
|
| 1203 |
pheno <- pheno[valid_idx]
|
| 1204 |
+
|
| 1205 |
+
if (length(unique(geno)) < 2 || length(pheno) < 5) next
|
| 1206 |
+
|
| 1207 |
+
# ----- Additive coding: use raw 0/1/2 values -----
|
| 1208 |
+
a_code <- geno
|
| 1209 |
+
|
| 1210 |
+
# ----- Dominance coding: heterozygote indicator -----
|
| 1211 |
+
# d = 1 for Aa (genotype == 1), 0 for AA (0) and aa (2)
|
| 1212 |
+
d_code <- as.numeric(geno == 1)
|
| 1213 |
+
|
| 1214 |
+
# ----- Determine if dominance term is estimable -----
|
| 1215 |
+
has_het <- length(unique(d_code)) > 1 # need at least one heterozygote
|
| 1216 |
+
|
| 1217 |
+
# ----- Fit full model (additive + dominance) -----
|
| 1218 |
+
if (has_het) {
|
| 1219 |
+
# Full model: lm(pheno ~ a + d) β both additive and dominance
|
| 1220 |
+
lm_full <- lm(pheno ~ a_code + d_code)
|
| 1221 |
+
sm <- summary(lm_full)
|
| 1222 |
+
pve_percent <- sm$r.squared * 100 # RΒ²_full Γ 100
|
| 1223 |
+
|
| 1224 |
+
coefs <- coef(lm_full)
|
| 1225 |
+
additive_effect <- coefs["a_code"]
|
| 1226 |
+
dominance_effect <- coefs["d_code"]
|
| 1227 |
+
|
| 1228 |
+
se_table <- sm$coefficients
|
| 1229 |
+
se_add <- if ("a_code" %in% rownames(se_table)) se_table["a_code", "Std. Error"] else NA
|
| 1230 |
+
se_dom <- if ("d_code" %in% rownames(se_table)) se_table["d_code", "Std. Error"] else NA
|
| 1231 |
+
|
| 1232 |
+
dom_ratio <- if (!is.na(additive_effect) && additive_effect != 0)
|
| 1233 |
+
abs(dominance_effect / additive_effect) else NA
|
| 1234 |
+
|
| 1235 |
+
} else {
|
| 1236 |
+
# No heterozygotes β fit additive-only model
|
| 1237 |
+
lm_add <- lm(pheno ~ a_code)
|
| 1238 |
+
sm <- summary(lm_add)
|
| 1239 |
+
pve_percent <- sm$r.squared * 100
|
| 1240 |
+
|
| 1241 |
+
coefs <- coef(lm_add)
|
| 1242 |
+
additive_effect <- coefs["a_code"]
|
| 1243 |
+
dominance_effect <- NA
|
| 1244 |
+
|
| 1245 |
+
se_table <- sm$coefficients
|
| 1246 |
+
se_add <- if ("a_code" %in% rownames(se_table)) se_table["a_code", "Std. Error"] else NA
|
| 1247 |
+
se_dom <- NA
|
| 1248 |
+
dom_ratio <- NA
|
| 1249 |
}
|
| 1250 |
+
|
|
|
|
|
|
|
|
|
|
| 1251 |
effects_list[[marker]] <- data.frame(
|
| 1252 |
+
Marker = marker,
|
| 1253 |
+
Additive_Effect = additive_effect,
|
| 1254 |
+
SE_Additive = se_add,
|
| 1255 |
+
CI_Lower = ifelse(is.na(se_add), NA, additive_effect - 1.96 * se_add),
|
| 1256 |
+
CI_Upper = ifelse(is.na(se_add), NA, additive_effect + 1.96 * se_add),
|
| 1257 |
+
Dominance_Effect = dominance_effect,
|
| 1258 |
+
SE_Dominance = se_dom,
|
| 1259 |
+
Dominance_Ratio = dom_ratio,
|
| 1260 |
+
Dominance_Class = ifelse(is.na(dom_ratio), "Additive",
|
| 1261 |
+
ifelse(dom_ratio > 1, "Overdominance",
|
| 1262 |
+
ifelse(dom_ratio > 0.5, "Dominance",
|
| 1263 |
+
ifelse(dom_ratio > 0.2, "Partial Dom.",
|
| 1264 |
+
"Additive")))),
|
| 1265 |
+
PVE_Percent = pve_percent,
|
| 1266 |
+
N_Samples = length(pheno),
|
| 1267 |
+
N_Heterozygotes = sum(geno == 1),
|
| 1268 |
+
stringsAsFactors = FALSE
|
| 1269 |
+
)
|
| 1270 |
}
|
| 1271 |
+
|
| 1272 |
if (length(effects_list) == 0) return(NULL)
|
| 1273 |
do.call(rbind, effects_list)
|
| 1274 |
}
|
| 1275 |
+
|
| 1276 |
# ============================================================
|
| 1277 |
# MAIN QTL ANALYSIS
|
| 1278 |
# ============================================================
|
| 1279 |
+
|
| 1280 |
observeEvent(input$run_analysis, {
|
| 1281 |
req(values$genotype_data, values$phenotype_data, input$phenotype_column)
|
| 1282 |
showNotification("Starting QTL analysis...", type = "message")
|
| 1283 |
values$lod_threshold <- input$lod_threshold
|
| 1284 |
+
|
| 1285 |
tryCatch({
|
| 1286 |
common_samples <- intersect(rownames(values$genotype_data), rownames(values$phenotype_data))
|
| 1287 |
if (length(common_samples) == 0) { showNotification("No common samples", type = "error"); return() }
|
| 1288 |
+
|
| 1289 |
X <- values$genotype_data[common_samples, , drop = FALSE]
|
| 1290 |
y <- as.numeric(values$phenotype_data[common_samples, input$phenotype_column])
|
| 1291 |
nzv <- nearZeroVar(X)
|
| 1292 |
if (length(nzv) > 0) X <- X[, -nzv, drop = FALSE]
|
| 1293 |
+
|
| 1294 |
set.seed(123)
|
| 1295 |
train_index <- createDataPartition(y, p = 1 - input$test_size, list = FALSE)
|
| 1296 |
X_train <- X[train_index, , drop = FALSE]; X_val <- X[-train_index, , drop = FALSE]
|
| 1297 |
y_train <- y[train_index]; y_val <- y[-train_index]
|
| 1298 |
+
|
| 1299 |
model <- train(x = X_train, y = y_train, method = "rf",
|
| 1300 |
trControl = trainControl(method = "cv", number = 5),
|
| 1301 |
importance = TRUE, tuneLength = 3)
|
| 1302 |
+
|
| 1303 |
values$model_fit <- model
|
| 1304 |
+
|
| 1305 |
imp <- varImp(model, scale = FALSE)$importance
|
| 1306 |
importance_scores <- data.frame(
|
| 1307 |
Marker = rownames(imp),
|
|
|
|
| 1309 |
Chromosome = values$chromosome_info[match(rownames(imp), colnames(X))],
|
| 1310 |
Position = as.numeric(values$position_info[match(rownames(imp), colnames(X))]),
|
| 1311 |
stringsAsFactors = FALSE)
|
| 1312 |
+
|
| 1313 |
values$importance_scores <- importance_scores
|
| 1314 |
lod_sig <- importance_scores[importance_scores$LOD > input$lod_threshold, , drop = FALSE]
|
| 1315 |
+
|
| 1316 |
if (nrow(lod_sig) > 0) {
|
| 1317 |
lod_sig$Low_Flank <- NA
|
| 1318 |
lod_sig$High_Flank <- NA
|
| 1319 |
+
|
| 1320 |
for (i in 1:nrow(lod_sig)) {
|
| 1321 |
chr_m <- values$all_markers[values$all_markers$Chromosome == lod_sig$Chromosome[i], ]
|
| 1322 |
chr_m <- chr_m[order(chr_m$Position), ]
|
|
|
|
| 1326 |
lod_sig$High_Flank[i] <- if (idx < nrow(chr_m)) chr_m$Marker[idx + 1] else lod_sig$Marker[i]
|
| 1327 |
}
|
| 1328 |
}
|
| 1329 |
+
|
| 1330 |
values$lod_scores_train <- lod_sig
|
| 1331 |
+
|
| 1332 |
+
# --- Use the FIXED PVE calculation function ---
|
| 1333 |
qtl_fx <- calculate_qtl_effects(X_train, y_train, lod_sig$Marker)
|
| 1334 |
+
|
| 1335 |
if (!is.null(qtl_fx)) {
|
| 1336 |
values$qtl_effects_train <- merge(lod_sig, qtl_fx, by = "Marker")
|
| 1337 |
} else {
|
|
|
|
| 1341 |
values$lod_scores_train <- data.frame(Message = paste("No QTLs above LOD", input$lod_threshold))
|
| 1342 |
values$qtl_effects_train <- data.frame(Message = paste("No QTLs above LOD", input$lod_threshold))
|
| 1343 |
}
|
| 1344 |
+
|
| 1345 |
y_train_pred <- predict(model, X_train)
|
| 1346 |
y_val_pred <- predict(model, X_val)
|
| 1347 |
train_r2 <- 1 - sum((y_train - y_train_pred)^2) / sum((y_train - mean(y_train))^2)
|
| 1348 |
val_r2 <- 1 - sum((y_val - y_val_pred)^2) / sum((y_val - mean(y_val))^2)
|
| 1349 |
+
|
| 1350 |
values$performance_metrics <- data.frame(
|
| 1351 |
Metric = c("R\u00b2 (Train)", "R (Train)", "R\u00b2 (Validation)", "R (Validation)"),
|
| 1352 |
Value = c(train_r2, cor(y_train, y_train_pred), val_r2, cor(y_val, y_val_pred)),
|
| 1353 |
stringsAsFactors = FALSE)
|
| 1354 |
+
|
| 1355 |
values$train_predictions <- data.frame(Observed = y_train, Predicted = y_train_pred)
|
| 1356 |
values$test_predictions <- data.frame(Observed = y_val, Predicted = y_val_pred)
|
| 1357 |
+
|
| 1358 |
# Epistasis
|
| 1359 |
if (nrow(lod_sig) > 0) {
|
| 1360 |
sig_markers <- lod_sig$Marker[lod_sig$Marker %in% colnames(X_train)]
|
| 1361 |
all_markers_v <- colnames(X_train)
|
| 1362 |
epistasis_list <- list()
|
| 1363 |
+
|
| 1364 |
withProgress(message = "Calculating epistasis...", value = 0, {
|
| 1365 |
total <- length(sig_markers) * length(all_markers_v)
|
| 1366 |
for (m1 in sig_markers) {
|
|
|
|
| 1384 |
}
|
| 1385 |
}
|
| 1386 |
})
|
| 1387 |
+
|
| 1388 |
if (length(epistasis_list) > 0) {
|
| 1389 |
epistasis_all <- do.call(rbind, epistasis_list)
|
| 1390 |
values$epistasis_all <- epistasis_all
|
|
|
|
| 1394 |
values$epistasis_sig <- data.frame(Message = "No epistatic interactions")
|
| 1395 |
}
|
| 1396 |
}
|
| 1397 |
+
|
| 1398 |
showNotification("QTL analysis completed!", type = "message")
|
| 1399 |
n_qtl <- if (!is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train)) nrow(values$qtl_effects_train) else 0
|
| 1400 |
add_message("assistant", paste0(
|
| 1401 |
"\u2705 **QTL analysis complete!**\n\n",
|
| 1402 |
"\u2022 Found **", n_qtl, " QTLs** above LOD ", input$lod_threshold, "\n",
|
| 1403 |
+
"\u2022 Validation R\u00b2: **", round(val_r2, 3), "**\n",
|
| 1404 |
+
"\u2022 PVE calculated using **full additive + dominance model**\n\n",
|
| 1405 |
"Ask me about PVE, top QTLs, or next steps!"))
|
| 1406 |
updateTabsetPanel(session, "nav", selected = "Results")
|
| 1407 |
+
|
| 1408 |
}, error = function(e) showNotification(paste("Error:", e$message), type = "error"))
|
| 1409 |
})
|
| 1410 |
+
|
| 1411 |
# ============================================================
|
| 1412 |
# DOMESTICATION ANALYSIS
|
| 1413 |
# ============================================================
|
| 1414 |
+
|
| 1415 |
calculate_selection_metrics <- function(genotype_matrix, pop_data, marker_info) {
|
| 1416 |
metrics_list <- list()
|
| 1417 |
+
|
| 1418 |
for (marker in colnames(genotype_matrix)) {
|
| 1419 |
geno <- genotype_matrix[, marker]
|
| 1420 |
pop <- pop_data$population[match(rownames(genotype_matrix), pop_data$id)]
|
| 1421 |
valid_idx <- !is.na(geno) & !is.na(pop)
|
| 1422 |
geno <- geno[valid_idx]; pop <- pop[valid_idx]
|
| 1423 |
+
|
| 1424 |
if (length(unique(pop)) < 2) next
|
| 1425 |
geno_dom <- geno[pop == "Domesticated"]
|
| 1426 |
geno_wild <- geno[pop == "Wild"]
|
| 1427 |
if (length(geno_dom) < 3 || length(geno_wild) < 3) next
|
| 1428 |
+
|
| 1429 |
freq_dom <- mean(geno_dom, na.rm = TRUE) / 2
|
| 1430 |
freq_wild <- mean(geno_wild, na.rm = TRUE) / 2
|
| 1431 |
p_avg <- (freq_dom + freq_wild) / 2
|
| 1432 |
+
|
| 1433 |
fst <- if (p_avg > 0 && p_avg < 1) {
|
| 1434 |
f <- (freq_dom - freq_wild)^2 / (p_avg * (1 - p_avg))
|
| 1435 |
f / (1 + f)
|
| 1436 |
} else 0
|
| 1437 |
+
|
| 1438 |
pi_dom <- 2 * freq_dom * (1 - freq_dom)
|
| 1439 |
pi_wild <- 2 * freq_wild * (1 - freq_wild)
|
| 1440 |
n_dom <- length(geno_dom)
|
| 1441 |
n_wild <- length(geno_wild)
|
| 1442 |
+
|
| 1443 |
+
tajima_d_dom <- tryCatch((pi_dom - 1/n_dom) / sqrt(var(geno_dom) /n_dom), error = function(e) NA)
|
| 1444 |
+
tajima_d_wild <- tryCatch((pi_wild - 1/n_wild) / sqrt(var(geno_wild)/n_wild), error = function(e) NA)
|
| 1445 |
+
|
| 1446 |
marker_row <- marker_info[marker_info$Marker == marker, ]
|
| 1447 |
metrics_list[[marker]] <- data.frame(
|
| 1448 |
Marker = marker,
|
|
|
|
| 1452 |
Tajima_D_Dom = tajima_d_dom, Tajima_D_Wild = tajima_d_wild,
|
| 1453 |
stringsAsFactors = FALSE)
|
| 1454 |
}
|
| 1455 |
+
|
| 1456 |
if (length(metrics_list) == 0) return(NULL)
|
| 1457 |
do.call(rbind, metrics_list)
|
| 1458 |
}
|
| 1459 |
+
|
| 1460 |
observeEvent(input$run_domestication, {
|
| 1461 |
req(values$genotype_data, values$pop_data, values$all_markers)
|
| 1462 |
tryCatch({
|
| 1463 |
common_samples <- intersect(rownames(values$genotype_data), values$pop_data$id)
|
| 1464 |
if (length(common_samples) == 0) { showNotification("No common samples", type = "error"); return() }
|
| 1465 |
+
|
| 1466 |
X <- values$genotype_data[common_samples, , drop = FALSE]
|
| 1467 |
pop_subset <- values$pop_data[values$pop_data$id %in% common_samples, ]
|
| 1468 |
sel_metrics <- calculate_selection_metrics(X, pop_subset, values$all_markers)
|
| 1469 |
+
|
| 1470 |
if (is.null(sel_metrics)) { showNotification("Could not calculate selection metrics", type = "error"); return() }
|
| 1471 |
+
|
| 1472 |
sel_metrics$Significant <-
|
| 1473 |
sel_metrics$Fst > input$fst_threshold |
|
| 1474 |
sel_metrics$Tajima_D_Dom < input$tajima_threshold |
|
| 1475 |
sel_metrics$Tajima_D_Wild < input$tajima_threshold
|
| 1476 |
+
|
| 1477 |
values$selection_metrics <- sel_metrics
|
| 1478 |
showNotification("Domestication analysis completed!", type = "message")
|
| 1479 |
n_sig <- sum(sel_metrics$Significant, na.rm = TRUE)
|
| 1480 |
add_message("assistant", paste0("\u2705 Domestication analysis complete!\n\n\u2022 Found **", n_sig, " markers** with selection signatures"))
|
| 1481 |
}, error = function(e) showNotification(paste("Error:", e$message), type = "error"))
|
| 1482 |
})
|
| 1483 |
+
|
| 1484 |
# ============================================================
|
| 1485 |
# PREDICT TEST PHENOTYPES
|
| 1486 |
# ============================================================
|
| 1487 |
+
|
| 1488 |
observeEvent(input$predict_test_phenotype, {
|
| 1489 |
req(values$model_fit, values$test_genotype_data)
|
| 1490 |
tryCatch({
|
| 1491 |
common_markers <- intersect(colnames(values$test_genotype_data), colnames(values$genotype_data))
|
| 1492 |
if (length(common_markers) == 0) { showNotification("No common markers", type = "error"); return() }
|
| 1493 |
+
|
| 1494 |
X_test <- values$test_genotype_data[, common_markers, drop = FALSE]
|
| 1495 |
predictions <- predict(values$model_fit, newdata = X_test)
|
| 1496 |
+
|
| 1497 |
values$predicted_test_phenotype_data <- data.frame(
|
| 1498 |
id = rownames(X_test),
|
| 1499 |
Predicted_Phenotype = as.numeric(predictions),
|
| 1500 |
stringsAsFactors = FALSE)
|
| 1501 |
+
|
| 1502 |
showNotification("Predictions completed!", type = "message")
|
| 1503 |
}, error = function(e) showNotification(paste("Error:", e$message), type = "error"))
|
| 1504 |
})
|
| 1505 |
+
|
| 1506 |
# ============================================================
|
| 1507 |
# MANHATTAN PLOT HELPER
|
| 1508 |
# ============================================================
|
| 1509 |
+
|
| 1510 |
create_manhattan <- function(data, y_col, title, threshold, y_label = y_col) {
|
| 1511 |
if (is.null(data) || nrow(data) == 0 || "Message" %in% colnames(data))
|
| 1512 |
return(plot_ly() %>% layout(title = "No data available",
|
| 1513 |
plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e")))
|
| 1514 |
+
|
| 1515 |
plot_data <- data[!is.na(data[[y_col]]), ]
|
| 1516 |
if (nrow(plot_data) == 0)
|
| 1517 |
return(plot_ly() %>% layout(title = "No valid data",
|
| 1518 |
plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e")))
|
| 1519 |
+
|
| 1520 |
chroms <- unique(plot_data$Chromosome)
|
| 1521 |
chrom_pos <- data.frame()
|
| 1522 |
for (i in seq_along(chroms)) {
|
|
|
|
| 1527 |
chrom_pos <- rbind(chrom_pos, chr_data)
|
| 1528 |
}
|
| 1529 |
}
|
| 1530 |
+
|
| 1531 |
p <- plot_ly() %>%
|
| 1532 |
add_trace(data = chrom_pos, x = ~PosScaled, y = as.formula(paste0("~", y_col)),
|
| 1533 |
type = "scatter", mode = "markers", color = ~factor(Chromosome),
|
|
|
|
| 1535 |
text = ~paste("Marker:", Marker, "<br>Chr:", Chromosome, "<br>Pos:", Position,
|
| 1536 |
"<br>", y_label, ":", round(get(y_col), 3)),
|
| 1537 |
hoverinfo = "text", showlegend = FALSE)
|
| 1538 |
+
|
| 1539 |
if (!is.null(threshold) && !is.na(threshold))
|
| 1540 |
p <- p %>% add_segments(
|
| 1541 |
x = min(chrom_pos$PosScaled, na.rm = TRUE), xend = max(chrom_pos$PosScaled, na.rm = TRUE),
|
| 1542 |
y = threshold, yend = threshold,
|
| 1543 |
line = list(color = "red", dash = "dash", width = 1), name = "Threshold")
|
| 1544 |
+
|
| 1545 |
p %>% layout(title = title,
|
| 1546 |
xaxis = list(title = "Chromosome",
|
| 1547 |
ticktext = chroms,
|
|
|
|
| 1550 |
yaxis = list(title = y_label),
|
| 1551 |
plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))
|
| 1552 |
}
|
| 1553 |
+
|
| 1554 |
# ============================================================
|
| 1555 |
# PLOTS
|
| 1556 |
# ============================================================
|
| 1557 |
+
|
| 1558 |
output$lod_plot_2d <- renderPlotly({
|
| 1559 |
req(values$importance_scores)
|
| 1560 |
create_manhattan(values$importance_scores, "LOD", "QTL Manhattan Plot", input$lod_threshold, "LOD Score")
|
| 1561 |
})
|
| 1562 |
+
|
| 1563 |
output$fst_plot <- renderPlotly({
|
| 1564 |
req(values$selection_metrics)
|
| 1565 |
create_manhattan(values$selection_metrics, "Fst", "Fst Manhattan Plot", input$fst_threshold, "Fst")
|
| 1566 |
})
|
| 1567 |
+
|
| 1568 |
output$tajima_plot <- renderPlotly({
|
| 1569 |
req(values$selection_metrics)
|
| 1570 |
if ("Message" %in% colnames(values$selection_metrics))
|
| 1571 |
return(plot_ly() %>% layout(title = "No data available", plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e")))
|
| 1572 |
+
|
| 1573 |
data <- values$selection_metrics
|
| 1574 |
chroms <- unique(data$Chromosome)
|
| 1575 |
chrom_pos <- data.frame()
|
|
|
|
| 1581 |
chrom_pos <- rbind(chrom_pos, chr_data)
|
| 1582 |
}
|
| 1583 |
}
|
| 1584 |
+
|
| 1585 |
plot_ly() %>%
|
| 1586 |
add_trace(data = chrom_pos, x = ~PosScaled, y = ~Tajima_D_Dom, type = "scatter", mode = "markers",
|
| 1587 |
name = "Domesticated", marker = list(size = 5, color = "#58a6ff", opacity = 0.7),
|
|
|
|
| 1600 |
yaxis = list(title = "Tajima's D"),
|
| 1601 |
plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))
|
| 1602 |
})
|
| 1603 |
+
|
| 1604 |
output$performance_plot <- renderPlotly({
|
| 1605 |
req(values$performance_metrics)
|
| 1606 |
plot_ly(data = values$performance_metrics, x = ~Metric, y = ~Value, type = "bar",
|
|
|
|
| 1610 |
yaxis = list(title = "Value", range = c(0, 1.1)),
|
| 1611 |
plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))
|
| 1612 |
})
|
| 1613 |
+
|
| 1614 |
output$regression_plot_train <- renderPlotly({
|
| 1615 |
req(values$train_predictions)
|
| 1616 |
plot_ly(data = values$train_predictions, x = ~Observed, y = ~Predicted,
|
|
|
|
| 1620 |
layout(title = "Training Set", xaxis = list(title = "Observed"), yaxis = list(title = "Predicted"),
|
| 1621 |
plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))
|
| 1622 |
})
|
| 1623 |
+
|
| 1624 |
output$regression_plot_test <- renderPlotly({
|
| 1625 |
req(values$test_predictions)
|
| 1626 |
plot_ly(data = values$test_predictions, x = ~Observed, y = ~Predicted,
|
|
|
|
| 1630 |
layout(title = "Validation Set", xaxis = list(title = "Observed"), yaxis = list(title = "Predicted"),
|
| 1631 |
plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))
|
| 1632 |
})
|
| 1633 |
+
|
| 1634 |
output$epistasis_heatmap <- renderPlotly({
|
| 1635 |
req(values$epistasis_all)
|
| 1636 |
if ("Message" %in% colnames(values$epistasis_all))
|
| 1637 |
return(plot_ly() %>% layout(title = values$epistasis_all$Message[1],
|
| 1638 |
plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e")))
|
| 1639 |
+
|
| 1640 |
qtls <- unique(values$epistasis_all$QTL1)
|
| 1641 |
markers <- unique(values$epistasis_all$QTL2)
|
| 1642 |
p_mat <- matrix(NA, nrow = length(qtls), ncol = length(markers),
|
|
|
|
| 1644 |
for (i in 1:nrow(values$epistasis_all))
|
| 1645 |
p_mat[values$epistasis_all$QTL1[i], values$epistasis_all$QTL2[i]] <-
|
| 1646 |
-log10(values$epistasis_all$Interaction_p[i])
|
| 1647 |
+
|
| 1648 |
plot_ly(x = colnames(p_mat), y = rownames(p_mat), z = p_mat,
|
| 1649 |
type = "heatmap", colorscale = "Viridis",
|
| 1650 |
hovertemplate = "QTL: %{y}<br>Marker: %{x}<br>-log10(p): %{z:.2f}") %>%
|
|
|
|
| 1652 |
xaxis = list(title = "Marker", tickangle = 45), yaxis = list(title = "QTL"),
|
| 1653 |
plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))
|
| 1654 |
})
|
| 1655 |
+
|
| 1656 |
# ============================================================
|
| 1657 |
# TABLES
|
| 1658 |
# ============================================================
|
| 1659 |
+
|
| 1660 |
output$qtl_effects_table_train <- renderDT({
|
| 1661 |
req(values$qtl_effects_train)
|
| 1662 |
if ("Message" %in% colnames(values$qtl_effects_train))
|
| 1663 |
return(datatable(data.frame(Status = values$qtl_effects_train$Message[1]), options = list(dom = "t")))
|
| 1664 |
+
|
| 1665 |
+
# Show all effect columns including dominance
|
| 1666 |
display_cols <- intersect(
|
| 1667 |
+
c("Marker", "Chromosome", "Position", "LOD",
|
| 1668 |
+
"Additive_Effect", "SE_Additive", "CI_Lower", "CI_Upper",
|
| 1669 |
+
"Dominance_Effect", "SE_Dominance", "Dominance_Ratio", "Dominance_Class",
|
| 1670 |
+
"PVE_Percent", "N_Samples", "N_Heterozygotes",
|
| 1671 |
+
"Low_Flank", "High_Flank"),
|
| 1672 |
colnames(values$qtl_effects_train))
|
| 1673 |
+
|
| 1674 |
df <- values$qtl_effects_train[order(-values$qtl_effects_train$LOD), display_cols]
|
| 1675 |
+
datatable(df,
|
| 1676 |
+
options = list(pageLength = 10, scrollX = TRUE),
|
| 1677 |
+
rownames = FALSE,
|
| 1678 |
+
caption = "PVE = RΒ² Γ 100 from lm(phenotype ~ additive_code + dominance_code)") %>%
|
| 1679 |
+
formatRound(intersect(c("LOD", "Additive_Effect", "SE_Additive", "CI_Lower", "CI_Upper",
|
| 1680 |
+
"Dominance_Effect", "SE_Dominance", "Dominance_Ratio", "PVE_Percent"), colnames(df)), 3)
|
| 1681 |
})
|
| 1682 |
+
|
| 1683 |
output$epistasis_table <- renderDT({
|
| 1684 |
req(values$epistasis_sig)
|
| 1685 |
if ("Message" %in% colnames(values$epistasis_sig))
|
|
|
|
| 1688 |
options = list(pageLength = 10, scrollX = TRUE), rownames = FALSE) %>%
|
| 1689 |
formatSignif(columns = c("Interaction_p", "Effect_Size"), digits = 4)
|
| 1690 |
})
|
| 1691 |
+
|
| 1692 |
output$selection_table <- renderDT({
|
| 1693 |
req(values$selection_metrics)
|
| 1694 |
if ("Message" %in% colnames(values$selection_metrics))
|
| 1695 |
return(datatable(data.frame(Status = values$selection_metrics$Message[1]), options = list(dom = "t")))
|
| 1696 |
+
|
| 1697 |
df <- values$selection_metrics
|
| 1698 |
if (!is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train))
|
| 1699 |
df$QTL_Overlap <- df$Marker %in% values$qtl_effects_train$Marker
|
| 1700 |
+
|
| 1701 |
display_cols <- intersect(
|
| 1702 |
c("Marker", "Chromosome", "Fst", "Pi_Dom", "Pi_Wild", "Tajima_D_Dom", "Significant", "QTL_Overlap"),
|
| 1703 |
colnames(df))
|
| 1704 |
datatable(df[order(-df$Fst), display_cols], options = list(pageLength = 10, scrollX = TRUE), rownames = FALSE) %>%
|
| 1705 |
formatRound(c("Fst", "Pi_Dom", "Pi_Wild", "Tajima_D_Dom"), 3)
|
| 1706 |
})
|
| 1707 |
+
|
| 1708 |
# ============================================================
|
| 1709 |
# CHROMOSOME VISUALIZATION
|
| 1710 |
# ============================================================
|
| 1711 |
+
|
| 1712 |
output$chromosome_viz <- renderUI({
|
| 1713 |
req(values$lod_scores_train, values$all_markers)
|
| 1714 |
if ("Message" %in% colnames(values$lod_scores_train))
|
| 1715 |
return(div(class = "alert alert-info", values$lod_scores_train$Message[1]))
|
| 1716 |
+
|
| 1717 |
chromosomes <- unique(values$lod_scores_train$Chromosome)
|
| 1718 |
tagList(lapply(chromosomes, function(chr) {
|
| 1719 |
chr_markers <- values$all_markers[values$all_markers$Chromosome == chr, ]
|
| 1720 |
chr_markers <- chr_markers[order(chr_markers$Position), ]
|
| 1721 |
chr_qtls <- values$lod_scores_train[values$lod_scores_train$Chromosome == chr, ]
|
| 1722 |
+
|
| 1723 |
sel_markers <- NULL
|
| 1724 |
if (!is.null(values$selection_metrics) && !"Message" %in% colnames(values$selection_metrics))
|
| 1725 |
sel_markers <- values$selection_metrics[
|
| 1726 |
values$selection_metrics$Chromosome == chr & values$selection_metrics$Significant, ]
|
| 1727 |
+
|
| 1728 |
min_pos <- min(chr_markers$Position, na.rm = TRUE)
|
| 1729 |
max_pos <- max(chr_markers$Position, na.rm = TRUE)
|
| 1730 |
range_pos <- max_pos - min_pos
|
| 1731 |
+
|
| 1732 |
div(class = "chromosome-container",
|
| 1733 |
div(class = "chromosome-title", paste("Chromosome", chr)),
|
| 1734 |
div(class = "chromosome",
|
|
|
|
| 1736 |
marker <- chr_markers[i, ]
|
| 1737 |
left <- if (range_pos > 0) ((marker$Position - min_pos) / range_pos) * 100
|
| 1738 |
else (i / nrow(chr_markers)) * 100
|
| 1739 |
+
|
| 1740 |
marker_class <- "chromosome-marker"
|
| 1741 |
if (marker$Marker %in% chr_qtls$Marker) {
|
| 1742 |
marker_class <- paste(marker_class, "significant")
|
|
|
|
| 1754 |
)
|
| 1755 |
}))
|
| 1756 |
})
|
| 1757 |
+
|
|
|
|
| 1758 |
observeEvent(input$simulate_btn, session$sendCustomMessage("simulateQTLDiscovery", list()))
|
| 1759 |
observeEvent(input$reset_btn, session$sendCustomMessage("resetAnimation", list()))
|
| 1760 |
+
|
| 1761 |
# ============================================================
|
| 1762 |
# INTERPRETATION OUTPUTS
|
| 1763 |
# ============================================================
|
| 1764 |
+
|
| 1765 |
output$analysis_summary <- renderUI({
|
| 1766 |
has_qtl <- !is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train)
|
| 1767 |
has_perf <- !is.null(values$performance_metrics)
|
| 1768 |
has_epi <- !is.null(values$epistasis_sig) && !"Message" %in% colnames(values$epistasis_sig) && nrow(values$epistasis_sig) > 0
|
| 1769 |
has_sel <- !is.null(values$selection_metrics) && !"Message" %in% colnames(values$selection_metrics)
|
| 1770 |
+
|
| 1771 |
n_qtl <- if (has_qtl) nrow(values$qtl_effects_train) else 0
|
| 1772 |
n_epi <- if (has_epi) nrow(values$epistasis_sig) else 0
|
| 1773 |
n_sel <- if (has_sel) sum(values$selection_metrics$Significant, na.rm = TRUE) else 0
|
| 1774 |
val_r2 <- if (has_perf) round(values$performance_metrics$Value[values$performance_metrics$Metric == "R\u00b2 (Validation)"], 3) else "N/A"
|
| 1775 |
+
|
| 1776 |
div(class = "interpretation-section",
|
| 1777 |
tags$h5("Analysis Summary"),
|
| 1778 |
tags$p(paste("Found", n_qtl, "QTLs above LOD", input$lod_threshold,
|
| 1779 |
if (has_perf) paste0("(validation R\u00b2 = ", val_r2, ")"),
|
| 1780 |
if (has_epi) paste0("with ", n_epi, " epistatic interactions"),
|
| 1781 |
+
if (has_sel) paste0("and ", n_sel, " selection signatures."))),
|
| 1782 |
+
tags$p(style = "color:#3fb950; font-size:12px; margin-top:6px;",
|
| 1783 |
+
tags$i(class = "fas fa-check-circle"),
|
| 1784 |
+
" PVE estimated using full additive + dominance model: lm(phenotype ~ a + d)")
|
| 1785 |
+
)
|
| 1786 |
})
|
| 1787 |
+
|
| 1788 |
output$qtl_interpretation <- renderUI({
|
| 1789 |
if (is.null(values$qtl_effects_train) || "Message" %in% colnames(values$qtl_effects_train))
|
| 1790 |
return(div(class = "interpretation-section", tags$h5("QTL Significance"), tags$p("No significant QTLs detected.")))
|
| 1791 |
+
|
| 1792 |
top_qtl <- values$qtl_effects_train[which.max(values$qtl_effects_train$LOD), ]
|
| 1793 |
div(class = "interpretation-section",
|
| 1794 |
tags$h5("QTL Significance"),
|
| 1795 |
tags$p(paste("Top QTL:", top_qtl$Marker, "(Chr", top_qtl$Chromosome, ") with LOD =", round(top_qtl$LOD, 2))))
|
| 1796 |
})
|
| 1797 |
+
|
| 1798 |
output$effect_interpretation <- renderUI({
|
| 1799 |
if (is.null(values$qtl_effects_train) || "Message" %in% colnames(values$qtl_effects_train))
|
| 1800 |
return(div(class = "interpretation-section", tags$h5("Effect Sizes"), tags$p("No QTL effects to interpret.")))
|
| 1801 |
+
|
| 1802 |
top_pve <- values$qtl_effects_train[which.max(values$qtl_effects_train$PVE_Percent), ]
|
| 1803 |
+
|
| 1804 |
+
dom_text <- if (!is.na(top_pve$Dominance_Effect) && !is.na(top_pve$Dominance_Ratio)) {
|
| 1805 |
+
paste0("Dominance effect = ", round(top_pve$Dominance_Effect, 3),
|
| 1806 |
+
" (ratio d/a = ", round(top_pve$Dominance_Ratio, 2),
|
| 1807 |
+
" β ", top_pve$Dominance_Class, ")")
|
| 1808 |
+
} else {
|
| 1809 |
+
"No heterozygotes detected β additive model only"
|
| 1810 |
+
}
|
| 1811 |
+
|
| 1812 |
div(class = "interpretation-section",
|
| 1813 |
+
tags$h5("Effect Sizes (Additive + Dominance)"),
|
| 1814 |
+
tags$p(paste("Largest PVE:", top_pve$Marker, "explains",
|
| 1815 |
+
round(top_pve$PVE_Percent, 1), "% of variance (full model)")),
|
| 1816 |
+
tags$p(paste("Additive effect =", round(top_pve$Additive_Effect, 3))),
|
| 1817 |
+
tags$p(dom_text),
|
| 1818 |
+
tags$p(style = "color:#8b949e; font-size:11px;",
|
| 1819 |
+
"PVE = R\u00b2 from lm(y ~ additive_code + dominance_code) \u00d7 100"))
|
| 1820 |
})
|
| 1821 |
+
|
| 1822 |
output$epistasis_interpretation <- renderUI({
|
| 1823 |
if (is.null(values$epistasis_sig) || "Message" %in% colnames(values$epistasis_sig) || nrow(values$epistasis_sig) == 0)
|
| 1824 |
return(div(class = "interpretation-section", tags$h5("Epistasis"), tags$p("No significant epistatic interactions detected.")))
|
| 1825 |
+
|
| 1826 |
top_epi <- values$epistasis_sig[which.min(values$epistasis_sig$Interaction_p), ]
|
| 1827 |
div(class = "interpretation-section",
|
| 1828 |
tags$h5("Epistasis"),
|
| 1829 |
tags$p(paste("Detected", nrow(values$epistasis_sig), "interactions. Strongest:",
|
| 1830 |
top_epi$QTL1, "x", top_epi$QTL2, "(p =", format.pval(top_epi$Interaction_p), ")")))
|
| 1831 |
})
|
| 1832 |
+
|
| 1833 |
output$recommendations <- renderUI({
|
| 1834 |
has_qtl <- !is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train)
|
| 1835 |
+
|
| 1836 |
recs <- if (has_qtl) {
|
| 1837 |
+
# Add dominance-specific recommendations
|
| 1838 |
+
has_dom <- any(!is.na(values$qtl_effects_train$Dominance_Ratio))
|
| 1839 |
+
dom_recs <- if (has_dom) {
|
| 1840 |
+
ovdom_count <- sum(values$qtl_effects_train$Dominance_Class == "Overdominance", na.rm = TRUE)
|
| 1841 |
+
if (ovdom_count > 0)
|
| 1842 |
+
c(paste0("Overdominance detected at ", ovdom_count, " QTL(s) β consider heterosis in breeding"),
|
| 1843 |
+
"For dominant QTLs, both additive and dominance variance matter for selection")
|
| 1844 |
+
else
|
| 1845 |
+
"Dominance effects estimated; consider dominance variance in heritability estimates"
|
| 1846 |
+
} else NULL
|
| 1847 |
+
|
| 1848 |
c("Validate top QTLs in independent populations",
|
| 1849 |
"Use flanking markers for fine-mapping",
|
| 1850 |
+
"Check gene annotations in QTL regions",
|
| 1851 |
+
dom_recs)
|
| 1852 |
} else {
|
| 1853 |
c("Upload data and run QTL analysis",
|
| 1854 |
"Consider lowering LOD threshold",
|
| 1855 |
"Check data quality")
|
| 1856 |
}
|
| 1857 |
+
|
| 1858 |
div(class = "interpretation-section",
|
| 1859 |
tags$h5("Recommendations"),
|
| 1860 |
tags$ul(lapply(recs, tags$li), style = "color:#8b949e;"))
|
| 1861 |
})
|
| 1862 |
+
|
| 1863 |
# ============================================================
|
| 1864 |
# DOWNLOAD HANDLERS
|
| 1865 |
# ============================================================
|
| 1866 |
+
|
| 1867 |
output$download_train_results <- downloadHandler(
|
| 1868 |
filename = function() paste0("qtl_results_", Sys.Date(), ".xlsx"),
|
| 1869 |
content = function(file) {
|
| 1870 |
sheets <- list()
|
| 1871 |
if (!is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train))
|
| 1872 |
+
sheets[["QTLs_AdditiveDominance"]] <- values$qtl_effects_train
|
| 1873 |
if (!is.null(values$performance_metrics))
|
| 1874 |
sheets[["Performance"]] <- values$performance_metrics
|
| 1875 |
+
|
| 1876 |
+
# Add formula documentation sheet
|
| 1877 |
+
sheets[["PVE_Formula"]] <- data.frame(
|
| 1878 |
+
Description = c(
|
| 1879 |
+
"PVE Formula (FIXED v2)",
|
| 1880 |
+
"Additive code (a)",
|
| 1881 |
+
"Dominance code (d)",
|
| 1882 |
+
"Full model",
|
| 1883 |
+
"PVE (%)",
|
| 1884 |
+
"Additive_Effect",
|
| 1885 |
+
"Dominance_Effect",
|
| 1886 |
+
"Dominance_Ratio",
|
| 1887 |
+
"Reference"
|
| 1888 |
+
),
|
| 1889 |
+
Value = c(
|
| 1890 |
+
"Full additive + dominance model",
|
| 1891 |
+
"0, 1, 2 (raw genotype value)",
|
| 1892 |
+
"ifelse(genotype == 1, 1, 0) β heterozygote indicator",
|
| 1893 |
+
"lm(phenotype ~ a + d)",
|
| 1894 |
+
"RΒ²_full Γ 100",
|
| 1895 |
+
"beta_a β allele substitution effect",
|
| 1896 |
+
"beta_d β deviation of heterozygote from midparent",
|
| 1897 |
+
"|beta_d / beta_a| β 0=additive, ~1=dominance, >1=overdominance",
|
| 1898 |
+
"Falconer & Mackay (1996); Lynch & Walsh (1998)"
|
| 1899 |
+
),
|
| 1900 |
+
stringsAsFactors = FALSE
|
| 1901 |
+
)
|
| 1902 |
+
|
| 1903 |
write_xlsx(sheets, file)
|
| 1904 |
}
|
| 1905 |
)
|
| 1906 |
+
|
| 1907 |
output$download_selection <- downloadHandler(
|
| 1908 |
filename = function() paste0("selection_", Sys.Date(), ".xlsx"),
|
| 1909 |
content = function(file) {
|
|
|
|
| 1917 |
}
|
| 1918 |
|
| 1919 |
# ============================================================
|
| 1920 |
+
# RUN APP
|
| 1921 |
# ============================================================
|
| 1922 |
|
| 1923 |
shinyApp(ui = ui, server = server)
|