Spaces:
Sleeping
Sleeping
Download app.R from softwareDevelopment/qtl: direct link, hf CLI and curl.
- Browser
- Download file 85.3 kB
-
https://huggingface.co/spaces/softwareDevelopment/qtl/resolve/98fbb779757d4c161ebfc8a09ae9cd6db45abb57/app.R
- Command line
-
hf download hf://spaces/softwareDevelopment/qtl@98fbb779757d4c161ebfc8a09ae9cd6db45abb57/app.R
-
curl -L -o app.R https://huggingface.co/spaces/softwareDevelopment/qtl/resolve/98fbb779757d4c161ebfc8a09ae9cd6db45abb57/app.R
85.3 kB
# ============================================================
# QTL-Mapper - Fixed API Connection
# ============================================================
options(repos = c(CRAN = "https://cloud.r-project.org"))
required_packages <- c(
"shiny", "randomForest", "caret", "DT", "ggplot2", "plotly",
"writexl", "viridis", "reshape2", "dplyr", "httr", "jsonlite",
"shinyjs", "markdown"
)
for (pkg in required_packages) {
if (!require(pkg, character.only = TRUE)) {
install.packages(pkg, dependencies = TRUE)
library(pkg, character.only = TRUE)
}
}
# ============================================================
# TOKEN DEBUG
# ============================================================
token <- Sys.getenv("HF_API_TOKEN")
token_exists <- token != ""
token_length <- if(token_exists) nchar(token) else 0
print("=== HUGGING FACE API TOKEN DEBUG ===")
print(paste("Token exists:", token_exists))
print(paste("Token length:", token_length))
if(token_exists) print(paste("Token starts with:", substr(token, 1, 10)))
print("===================================")
# ============================================================
# API CONFIGURATION (single, clean definition)
# ============================================================
HF_API_TOKEN <- token
HF_API_URL <- "https://router.huggingface.co/v1/chat/completions"
#hf_model <- "HuggingFaceTB/SmolLM3-3B:hf-inference"
hf_model <- "meta-llama/Llama-3.2-3B-Instruct:together"
# ============================================================
# TEST CONNECTION
# ============================================================
test_api_connection <- function() {
if (!token_exists) return(list(success = FALSE, error = "No token found"))
tryCatch({
response <- POST(
url = HF_API_URL,
add_headers(
Authorization = paste("Bearer", HF_API_TOKEN),
"Content-Type" = "application/json"
),
body = toJSON(list(
model = hf_model,
messages = list(list(role = "user", content = "Hi")),
max_tokens = 10L
), auto_unbox = TRUE),
encode = "json",
timeout(15)
)
status <- status_code(response)
if (status == 200) return(list(success = TRUE))
err <- tryCatch(content(response, "text", encoding = "UTF-8"),
error = function(e) paste("Status:", status))
return(list(success = FALSE,
error = paste("Status:", status, "-", substr(err, 1, 200))))
}, error = function(e) list(success = FALSE, error = e$message))
}
api_test <- test_api_connection()
use_hf_api <- token_exists && api_test$success
print(paste("API Test result:", if(api_test$success) "SUCCESS" else paste("FAILED -", api_test$error)))
if (use_hf_api) {
print(paste("✅ API working with model:", hf_model, "- AI mode enabled"))
} else {
print("⚠️ API not available - using rule-based mode")
}
# ============================================================
# QUERY FUNCTION (single, OpenAI-compatible version)
# ============================================================
query_hf_api <- function(prompt, max_length = 500, temperature = 0.7) {
if (!token_exists) return(list(success = FALSE, error = "HF_API_TOKEN not set"))
tryCatch({
response <- POST(
url = HF_API_URL,
add_headers(
Authorization = paste("Bearer", HF_API_TOKEN),
"Content-Type" = "application/json"
),
body = toJSON(list(
model = hf_model,
messages = list(
list(role = "system",
content = "You are an expert bioinformatics assistant specializing in QTL analysis. Be concise and helpful."),
list(role = "user", content = prompt)
),
max_tokens = as.integer(max_length),
temperature = temperature
), auto_unbox = TRUE),
encode = "json",
timeout(60)
)
status <- status_code(response)
if (status == 200) {
result <- content(response, as = "parsed", encoding = "UTF-8")
text <- result$choices[[1]]$message$content
return(list(success = TRUE, text = text))
}
err <- tryCatch(content(response, "text", encoding = "UTF-8"),
error = function(e) paste("Status:", status))
return(list(success = FALSE,
error = paste("API error:", status, "-", substr(err, 1, 200))))
}, error = function(e) list(success = FALSE, error = e$message))
}
# ============================================================
# SYSTEM PROMPT CONSTRUCTION
# ============================================================
build_system_prompt <- function(rv) {
context_parts <- c("CURRENT ANALYSIS RESULTS:")
if (!is.null(rv$qtl_effects_train) && !"Message" %in% colnames(rv$qtl_effects_train)) {
n_qtl <- nrow(rv$qtl_effects_train)
total_pve <- sum(rv$qtl_effects_train$PVE_Percent, na.rm = TRUE)
context_parts <- c(context_parts,
sprintf("\nQTL Results: %d significant QTLs detected above LOD %.1f.", n_qtl, rv$lod_threshold),
sprintf("Total variance explained by QTLs: %.1f%%.", total_pve))
top_qtls <- head(rv$qtl_effects_train[order(-rv$qtl_effects_train$LOD), ], 3)
context_parts <- c(context_parts, "\nTop QTLs:")
for (i in 1:nrow(top_qtls)) {
row <- top_qtls[i, ]
context_parts <- c(context_parts,
sprintf(" %d. %s (Chr %s): LOD=%.2f, PVE=%.1f%%, Additive=%.3f",
i, row$Marker, row$Chromosome, row$LOD, row$PVE_Percent, row$Additive_Effect))
}
}
if (!is.null(rv$performance_metrics)) {
pm <- rv$performance_metrics
train_r2 <- pm$Value[pm$Metric == "R\u00b2 (Train)"]
val_r2 <- pm$Value[pm$Metric == "R\u00b2 (Validation)"]
context_parts <- c(context_parts,
sprintf("\nModel Performance:"),
sprintf(" Training R\u00b2: %.3f", train_r2),
sprintf(" Validation R\u00b2: %.3f", val_r2))
}
if (!is.null(rv$epistasis_sig) && !"Message" %in% colnames(rv$epistasis_sig) && nrow(rv$epistasis_sig) > 0) {
n_epi <- nrow(rv$epistasis_sig)
top_epi <- rv$epistasis_sig[order(rv$epistasis_sig$Interaction_p), ][1, ]
context_parts <- c(context_parts,
sprintf("\nEpistasis: %d significant pairwise interactions detected.", n_epi),
sprintf(" Strongest: %s x %s (p=%.4f)", top_epi$QTL1, top_epi$QTL2, top_epi$Interaction_p))
}
if (!is.null(rv$selection_metrics) && !"Message" %in% colnames(rv$selection_metrics)) {
n_sig <- sum(rv$selection_metrics$Significant, na.rm = TRUE)
context_parts <- c(context_parts,
sprintf("\nDomestication: %d markers with selection signatures.", n_sig))
}
paste(context_parts, collapse = "\n")
}
# ============================================================
# ENHANCED RULE-BASED RESPONSES
# ============================================================
enhanced_rule_response <- function(user_message, rv) {
q <- tolower(trimws(user_message))
has_qtl <- !is.null(rv$qtl_effects_train) && !"Message" %in% colnames(rv$qtl_effects_train)
has_perf <- !is.null(rv$performance_metrics)
has_epi <- !is.null(rv$epistasis_sig) && !"Message" %in% colnames(rv$epistasis_sig) && nrow(rv$epistasis_sig) > 0
has_sel <- !is.null(rv$selection_metrics) && !"Message" %in% colnames(rv$selection_metrics)
# PVE questions
if (grepl("pve|variance explained|how much variance|percent variance|what is pve", q)) {
if (has_qtl) {
df <- rv$qtl_effects_train
total_pve <- sum(df$PVE_Percent, na.rm = TRUE)
top_pve <- df[which.max(df$PVE_Percent), ]
response <- paste0(
"\U0001f4ca **PVE (Phenotypic Variance Explained) Analysis**\n\n",
"**Your Results:**\n",
"\u2022 Total variance explained by all QTLs: **", round(total_pve, 1), "%**\n",
"\u2022 Number of QTLs detected: **", nrow(df), "**\n\n",
"**Top QTL by PVE:**\n",
"\u2022 Marker: **", top_pve$Marker, "**\n",
"\u2022 Chromosome: ", top_pve$Chromosome, "\n",
"\u2022 PVE: **", round(top_pve$PVE_Percent, 1), "%**\n",
"\u2022 LOD: ", round(top_pve$LOD, 2), "\n\n"
)
if (top_pve$PVE_Percent > 10) {
response <- paste0(response, "\U0001f4a1 This is a **major-effect QTL** (>10% PVE) - excellent candidate for marker-assisted selection.\n\n")
} else if (top_pve$PVE_Percent > 5) {
response <- paste0(response, "\U0001f4a1 This is a **moderate-effect QTL** (5-10% PVE) - useful for polygenic breeding approaches.\n\n")
} else {
response <- paste0(response, "\U0001f4a1 This is a **minor-effect QTL** (<5% PVE) - typical for complex polygenic traits.\n\n")
}
response <- paste0(response, "**All QTLs by PVE:**\n")
df_sorted <- df[order(-df$PVE_Percent), ]
for (i in 1:min(5, nrow(df_sorted))) {
row <- df_sorted[i, ]
response <- paste0(response, sprintf(" %d. %s: %.1f%%\n", i, row$Marker, row$PVE_Percent))
}
return(response)
} else {
return("No QTL results yet. Please run the QTL analysis first to see PVE values.")
}
}
# Model performance questions
if (grepl("model performance|r2|r squared|how good is my model|validation|negative r2", q)) {
if (has_perf) {
pm <- rv$performance_metrics
train_r2 <- pm$Value[pm$Metric == "R\u00b2 (Train)"]
val_r2 <- pm$Value[pm$Metric == "R\u00b2 (Validation)"]
response <- paste0(
"\U0001f4c8 **Model Performance Summary**\n\n",
"\u2022 Training R\u00b2: **", round(train_r2, 3), "**\n",
"\u2022 Validation R\u00b2: **", round(val_r2, 3), "**\n\n"
)
if (val_r2 < 0) {
response <- paste0(response,
"\u26a0\ufe0f **Your validation R\u00b2 is negative** (", round(val_r2, 3), ").\n\n",
"This means the model performs worse than simply predicting the mean.\n\n",
"**Common causes:**\n",
"\u2022 **Small sample size** relative to number of markers\n",
"\u2022 **Overfitting** - model learned noise instead of signal\n",
"\u2022 **Population structure** in your data\n\n",
"**Recommendations:**\n",
"1. Increase sample size if possible\n",
"2. Reduce marker number (use feature selection)\n",
"3. Try simpler models or increase cross-validation folds\n",
"4. Focus on individual QTL interpretation rather than prediction\n")
} else if (val_r2 < 0.2) {
response <- paste0(response,
"\U0001f4c9 **Low validation R\u00b2** (<0.2) suggests modest predictive power.\n\n",
"This is common for complex traits. Focus on individual QTL interpretation.\n")
} else if (val_r2 < 0.5) {
response <- paste0(response,
"\U0001f4ca **Moderate validation R\u00b2** (0.2-0.5) - your model has decent predictive ability.\n\n")
} else {
response <- paste0(response,
"\U0001f3af **Excellent validation R\u00b2** (>0.5) - your model has strong predictive power!\n\n")
}
return(response)
} else {
return("Run the QTL analysis first to see model performance metrics.")
}
}
# Top QTLs question
if (grepl("top qtl|best qtl|highest lod|significant qtl|list qtl|show qtl", q)) {
if (has_qtl) {
df <- rv$qtl_effects_train[order(-rv$qtl_effects_train$LOD), ]
top5 <- head(df, 5)
response <- "\U0001f3af **Top 5 QTLs by LOD Score**\n\n"
for (i in 1:nrow(top5)) {
row <- top5[i, ]
response <- paste0(response,
i, ". **", row$Marker, "** (Chr ", row$Chromosome, ")\n",
" \u2022 LOD: **", round(row$LOD, 2), "**\n",
" \u2022 PVE: ", round(row$PVE_Percent, 1), "%\n",
" \u2022 Additive effect: ", round(row$Additive_Effect, 3), "\n")
if (!is.null(row$Low_Flank) && !is.na(row$Low_Flank) && row$Low_Flank != "NA") {
response <- paste0(response, " \u2022 Interval: ", row$Low_Flank, " - ", row$High_Flank, "\n")
}
response <- paste0(response, "\n")
}
return(response)
} else {
return("No significant QTLs detected. Try lowering the LOD threshold or check your data.")
}
}
# Next steps question
if (grepl("next steps|what next|recommendations|suggest|advice|what should i do", q)) {
if (has_qtl || has_perf || has_epi || has_sel) {
response <- "\U0001f52c **Recommended Next Steps**\n\n"
if (has_qtl) {
top_qtl <- rv$qtl_effects_train[which.max(rv$qtl_effects_train$LOD), ]
response <- paste0(response,
"**1. Validate Top QTLs**\n",
" \u2022 Prioritize **", top_qtl$Marker, "** (LOD=", round(top_qtl$LOD, 2),
", PVE=", round(top_qtl$PVE_Percent, 1), "%)\n",
" \u2022 Test in independent population or F2 cross\n",
" \u2022 Use flanking markers for fine-mapping\n\n")
}
if (has_epi) {
n_epi <- nrow(rv$epistasis_sig)
response <- paste0(response,
"**2. Investigate Epistasis**\n",
" \u2022 ", n_epi, " significant interactions detected\n",
" \u2022 Test multi-locus models in breeding programs\n",
" \u2022 Check if interacting QTLs map to same pathways\n\n")
}
if (has_sel) {
n_sel <- sum(rv$selection_metrics$Significant, na.rm = TRUE)
response <- paste0(response,
"**3. Domestication Analysis**\n",
" \u2022 ", n_sel, " markers show selection signatures\n",
" \u2022 Cross-reference with QTL positions\n",
" \u2022 Candidate domestication genes\n\n")
}
response <- paste0(response,
"**4. Functional Analysis**\n",
" \u2022 Annotate QTL regions for candidate genes\n",
" \u2022 Check gene expression databases\n",
" \u2022 Design validation experiments\n\n",
"**5. Breeding Applications**\n",
" \u2022 Develop markers for MAS\n",
" \u2022 Design crossing schemes\n",
" \u2022 Predict breeding values\n")
return(response)
} else {
return("Run the QTL analysis first to get recommendations.")
}
}
# Default response
available <- c()
if (has_qtl) available <- c(available, paste(nrow(rv$qtl_effects_train), "QTLs"))
if (has_perf) {
val_r2 <- rv$performance_metrics$Value[rv$performance_metrics$Metric == "R\u00b2 (Validation)"]
available <- c(available, paste0("R\u00b2=", round(val_r2, 3)))
}
if (has_epi) available <- c(available, paste(nrow(rv$epistasis_sig), "interactions"))
if (has_sel) available <- c(available, paste(sum(rv$selection_metrics$Significant), "selection signatures"))
if (length(available) > 0) {
return(paste0(
"I can see you have: ", paste(available, collapse = ", "), ".\n\n",
"What would you like to know? Try asking about:\n",
"\u2022 **What is PVE?** - Understand variance explained\n",
"\u2022 **Top QTLs** - List most significant markers\n",
"\u2022 **Model performance** - Why is R\u00b2 negative?\n",
"\u2022 **Next steps** - Recommendations for your results"))
}
return(paste0(
"\U0001f44b Hello! I'm your QTL analysis assistant.\n\n",
"**I can help you with:**\n",
"\u2022 Understanding PVE (variance explained)\n",
"\u2022 Interpreting LOD scores and QTL significance\n",
"\u2022 Evaluating model performance (R\u00b2)\n",
"\u2022 Detecting epistatic interactions\n\n",
"**To get started:**\n",
"1. Upload your genotype and phenotype files\n",
"2. Click 'Run QTL Analysis'\n",
"3. Ask me specific questions!\n\n",
"Try: **'What is PVE?'** or **'Show me my top QTLs'**"))
}
# ============================================================
# AI RESPONSE GENERATION
# ============================================================
generate_ai_response <- function(user_message, rv) {
context <- build_system_prompt(rv)
if (use_hf_api) {
prompt <- paste(
"CONTEXT:", context,
"\n\nUSER QUESTION:", user_message,
"\n\nProvide a specific, helpful answer based ONLY on the context above. Be concise but informative.",
sep = "\n"
)
result <- query_hf_api(prompt)
if (result$success) {
return(result$text)
} else {
message("API Error: ", result$error)
return(enhanced_rule_response(user_message, rv))
}
}
return(enhanced_rule_response(user_message, rv))
}
# ============================================================
# UI
# ============================================================
ui <- fluidPage(
shinyjs::useShinyjs(),
tags$head(
tags$link(rel = "stylesheet", type = "text/css",
href = "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css"),
tags$link(rel = "stylesheet", type = "text/css",
href = "https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;600&family=IBM+Plex+Sans:wght@300;400;500;600&display=swap"),
tags$script(HTML("
function simulateQTLDiscovery() {
setTimeout(function() {
const markers = document.querySelectorAll('.chromosome-marker');
let delay = 0;
markers.forEach(marker => {
setTimeout(() => {
marker.classList.add('highlighted');
setTimeout(() => { marker.classList.add('pulse'); }, 300);
}, delay);
delay += 100;
});
}, 100);
}
function resetAnimation() {
const markers = document.querySelectorAll('.chromosome-marker');
markers.forEach(marker => {
marker.classList.remove('highlighted');
marker.classList.remove('pulse');
});
}
Shiny.addCustomMessageHandler('simulateQTLDiscovery', function(message) { simulateQTLDiscovery(); });
Shiny.addCustomMessageHandler('resetAnimation', function(message) { resetAnimation(); });
Shiny.addCustomMessageHandler('scrollChatBottom', function(message) {
setTimeout(function() {
var chatBox = document.getElementById('chat_messages');
if (chatBox) chatBox.scrollTop = chatBox.scrollHeight;
}, 100);
});
$(document).on('keydown', '#chat_input', function(e) {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
$('#send_chat').click();
}
});
")),
tags$style(HTML("
:root {
--bg-primary: #0d1117; --bg-secondary: #161b22; --bg-tertiary: #21262d;
--border: #30363d; --text-primary: #e6edf3; --text-secondary: #8b949e;
--text-muted: #6e7681; --accent: #58a6ff; --accent-hover: #79c0ff;
--success: #3fb950; --warning: #d29922; --danger: #f85149;
--purple: #bc8cff; --teal: #39d353;
--font-mono: 'IBM Plex Mono', monospace; --font-sans: 'IBM Plex Sans', sans-serif;
}
* { box-sizing: border-box; margin: 0; padding: 0; }
body { font-family: var(--font-sans); background-color: var(--bg-primary); color: var(--text-primary); font-size: 14px; }
.navbar { background-color: var(--bg-secondary) !important; border-bottom: 1px solid var(--border); }
.navbar-brand { color: var(--text-primary) !important; font-family: var(--font-mono); font-weight: 600; letter-spacing: -0.5px; }
.navbar-nav > li > a { color: var(--text-secondary) !important; font-family: var(--font-sans); font-size: 13px; }
.navbar-nav > li.active > a, .navbar-nav > li > a:hover { color: var(--accent) !important; background: transparent !important; }
.main-header { background: linear-gradient(135deg, #1c2b3a 0%, #0d1117 100%); border: 1px solid var(--border); border-left: 3px solid var(--accent); color: var(--text-primary); padding: 20px 24px; border-radius: 6px; margin-bottom: 20px; }
.main-header h2 { font-family: var(--font-mono); font-size: 1.3rem; font-weight: 600; color: var(--accent); }
.main-header p { color: var(--text-secondary); margin-top: 6px; font-size: 13px; }
.card { background-color: var(--bg-secondary); border: 1px solid var(--border); border-radius: 6px; margin-bottom: 20px; }
.card-header { background-color: var(--bg-tertiary); border-bottom: 1px solid var(--border); padding: 12px 16px; font-family: var(--font-mono); font-size: 12px; color: var(--text-secondary); letter-spacing: 0.5px; text-transform: uppercase; }
.card-body { padding: 16px; }
.form-control, .selectize-input { background-color: var(--bg-tertiary) !important; border: 1px solid var(--border) !important; color: var(--text-primary) !important; border-radius: 4px; font-family: var(--font-sans); font-size: 13px; }
.form-control:focus { border-color: var(--accent) !important; box-shadow: 0 0 0 2px rgba(88,166,255,0.2) !important; }
label { color: var(--text-secondary); font-size: 12px; margin-bottom: 4px; }
.btn { border-radius: 4px; font-family: var(--font-mono); font-size: 12px; font-weight: 600; letter-spacing: 0.3px; transition: all 0.15s; border: 1px solid; }
.btn-primary { background-color: var(--accent); border-color: var(--accent); color: #0d1117; }
.btn-primary:hover { background-color: var(--accent-hover); border-color: var(--accent-hover); color: #0d1117; }
.btn-info { background-color: transparent; border-color: var(--teal); color: var(--teal); }
.btn-info:hover { background-color: var(--teal); color: #0d1117; }
.btn-danger { background-color: transparent; border-color: var(--danger); color: var(--danger); }
.btn-danger:hover { background-color: var(--danger); color: white; }
.help-block, .shiny-input-container .help-block { color: var(--text-muted); font-size: 11px; margin-top: 4px; }
.btn-file { background-color: var(--bg-tertiary); border-color: var(--border); color: var(--text-secondary); }
.dataTables_wrapper { color: var(--text-secondary) !important; }
table.dataTable { background-color: var(--bg-secondary) !important; color: var(--text-primary) !important; border-color: var(--border) !important; }
table.dataTable thead th { background-color: var(--bg-tertiary) !important; color: var(--text-secondary) !important; border-bottom: 1px solid var(--border) !important; font-family: var(--font-mono); font-size: 11px; letter-spacing: 0.5px; }
table.dataTable tbody tr:hover { background-color: var(--bg-tertiary) !important; }
table.dataTable tbody td { border-bottom: 1px solid var(--border) !important; font-size: 12px; }
.dataTables_info, .dataTables_length, .dataTables_filter, .dataTables_paginate { color: var(--text-muted) !important; font-size: 12px; }
.dataTables_filter input, .dataTables_length select { background: var(--bg-tertiary) !important; border: 1px solid var(--border) !important; color: var(--text-primary) !important; border-radius: 3px; }
.paginate_button { color: var(--text-secondary) !important; }
.paginate_button.current { background: var(--accent) !important; color: #0d1117 !important; border-color: var(--accent) !important; }
.chromosome-container { margin: 12px 0; padding: 12px 16px; background: var(--bg-tertiary); border-radius: 4px; border: 1px solid var(--border); }
.chromosome { height: 24px; background: linear-gradient(to right, var(--bg-primary), var(--border)); border-radius: 12px; margin: 8px 0; position: relative; overflow: hidden; border: 1px solid var(--border); }
.chromosome-marker { position: absolute; height: 34px; width: 6px; background-color: var(--text-muted); border-radius: 3px; top: -5px; transform: translateX(-50%); transition: all 0.3s ease; }
.chromosome-marker.significant { background-color: var(--danger) !important; height: 40px !important; width: 8px !important; top: -8px !important; }
.chromosome-marker.flanking { background-color: var(--accent) !important; height: 30px !important; width: 5px !important; top: -3px !important; }
.chromosome-marker.selection { background-color: var(--success) !important; height: 34px !important; width: 6px !important; top: -5px !important; }
.chromosome-marker.highlighted { background-color: var(--warning) !important; box-shadow: 0 0 10px rgba(210,153,34,0.6); }
.chromosome-marker.pulse { animation: pulse 1.5s infinite; }
@keyframes pulse { 0% { transform: translateX(-50%) scale(1); } 50% { transform: translateX(-50%) scale(1.3); opacity: 0.7; } 100% { transform: translateX(-50%) scale(1); } }
.chromosome-legend { display: flex; justify-content: space-between; font-size: 10px; color: var(--text-muted); font-family: var(--font-mono); margin-top: 2px; }
.chromosome-title { font-family: var(--font-mono); font-size: 11px; color: var(--accent); margin-bottom: 4px; }
.simulation-controls { margin: 12px 0; display: flex; gap: 8px; }
.simulation-btn { background-color: transparent; color: var(--purple); border: 1px solid var(--purple); padding: 5px 12px; border-radius: 4px; cursor: pointer; font-family: var(--font-mono); font-size: 11px; transition: all 0.15s; }
.simulation-btn:hover { background-color: var(--purple); color: #0d1117; }
#chat-panel { position: fixed; bottom: 20px; right: 20px; z-index: 9999; width: 420px; display: flex; flex-direction: column; }
#chat-toggle-btn { align-self: flex-end; width: 56px; height: 56px; border-radius: 50%; background: linear-gradient(135deg, var(--accent), var(--purple)); border: none; cursor: pointer; display: flex; align-items: center; justify-content: center; box-shadow: 0 4px 20px rgba(88,166,255,0.4); transition: all 0.2s; color: #0d1117; font-size: 24px; }
#chat-toggle-btn:hover { transform: scale(1.05); box-shadow: 0 6px 24px rgba(88,166,255,0.6); }
#chat-window { display: none; flex-direction: column; background: var(--bg-secondary); border: 1px solid var(--accent); border-radius: 12px; overflow: hidden; box-shadow: 0 8px 40px rgba(0,0,0,0.5); margin-bottom: 10px; height: 600px; }
#chat-window.open { display: flex; }
#chat-header { background: linear-gradient(135deg, var(--bg-tertiary), #1c2b3a); border-bottom: 1px solid var(--border); padding: 12px 16px; display: flex; align-items: center; justify-content: space-between; }
.chat-title { display: flex; align-items: center; gap: 10px; }
.chat-avatar { width: 32px; height: 32px; background: linear-gradient(135deg, var(--accent), var(--purple)); border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 16px; color: #0d1117; font-weight: bold; }
#chat-header h4 { font-family: var(--font-mono); font-size: 13px; font-weight: 600; color: var(--text-primary); margin: 0; }
#chat-header p { font-size: 11px; color: var(--text-muted); margin: 0; font-weight: bold; }
#chat-header p.ai-mode { color: var(--success); }
#chat-header p.rule-mode { color: var(--warning); }
#chat-close-btn { background: none; border: none; color: var(--text-muted); cursor: pointer; font-size: 18px; padding: 4px; transition: color 0.15s; }
#chat-close-btn:hover { color: var(--text-primary); }
#chat_messages { flex: 1; overflow-y: auto; padding: 16px; display: flex; flex-direction: column; gap: 12px; background: var(--bg-primary); }
.chat-msg { max-width: 90%; animation: fadeIn 0.3s ease; }
@keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
.chat-msg.user { align-self: flex-end; }
.chat-msg.assistant { align-self: flex-start; }
.chat-bubble { padding: 12px 16px; border-radius: 16px; font-size: 13px; line-height: 1.6; word-wrap: break-word; white-space: pre-wrap; }
.chat-msg.user .chat-bubble { background: linear-gradient(135deg, var(--accent), #3a7bd5); color: #0d1117; border-bottom-right-radius: 4px; }
.chat-msg.assistant .chat-bubble { background: var(--bg-tertiary); color: var(--text-primary); border: 1px solid var(--border); border-bottom-left-radius: 4px; }
.chat-bubble strong { color: var(--accent); }
.chat-bubble em { color: var(--text-secondary); }
.chat-meta { font-size: 10px; color: var(--text-muted); margin-top: 4px; font-family: var(--font-mono); padding: 0 4px; }
.typing-indicator { display: flex; gap: 4px; padding: 12px 16px; background: var(--bg-tertiary); border: 1px solid var(--border); border-radius: 16px; border-bottom-left-radius: 4px; width: fit-content; }
.typing-dot { width: 8px; height: 8px; background: var(--text-muted); border-radius: 50%; animation: typingBounce 1.4s infinite; }
.typing-dot:nth-child(2) { animation-delay: 0.2s; }
.typing-dot:nth-child(3) { animation-delay: 0.4s; }
@keyframes typingBounce { 0%, 60%, 100% { transform: translateY(0); } 30% { transform: translateY(-8px); } }
#chat-footer { padding: 16px; border-top: 1px solid var(--border); background: var(--bg-tertiary); }
#chat_input { width: 100%; background: var(--bg-secondary) !important; border: 1px solid var(--border) !important; border-radius: 8px; color: var(--text-primary) !important; font-size: 13px; resize: none; padding: 10px 12px; font-family: var(--font-sans); margin-bottom: 8px; }
#chat_input:focus { border-color: var(--accent) !important; outline: none; }
.chat-actions { display: flex; gap: 8px; }
#send_chat { flex: 1; background: linear-gradient(135deg, var(--accent), #3a7bd5); color: #0d1117; border: none; border-radius: 6px; padding: 8px 16px; font-family: var(--font-mono); font-size: 12px; font-weight: 600; cursor: pointer; transition: all 0.15s; display: flex; align-items: center; justify-content: center; gap: 6px; }
#send_chat:hover:not(:disabled) { transform: translateY(-1px); box-shadow: 0 4px 12px rgba(88,166,255,0.4); }
#send_chat:disabled { opacity: 0.5; cursor: not-allowed; }
#clear_chat { background: transparent; color: var(--text-muted); border: 1px solid var(--border); border-radius: 6px; padding: 8px 12px; font-family: var(--font-mono); font-size: 12px; cursor: pointer; transition: all 0.15s; }
#clear_chat:hover { border-color: var(--danger); color: var(--danger); }
.model-badge { display: inline-block; background: var(--bg-secondary); border: 1px solid var(--border); border-radius: 12px; padding: 2px 8px; font-size: 10px; color: var(--text-muted); margin-left: 8px; }
.quick-questions { padding: 8px 16px; display: flex; flex-wrap: wrap; gap: 6px; border-bottom: 1px solid var(--border); }
.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; }
.quick-q-btn:hover { border-color: var(--accent); color: var(--accent); background: rgba(88,166,255,0.1); }
"))
),
navbarPage(
title = tags$span(tags$i(class = "fas fa-dna", style = "margin-right:8px; color:#58a6ff;"), "QTL-Mapper AI"),
id = "nav",
# ---- Data Upload tab ----
tabPanel("Data Upload", icon = icon("upload"),
div(class = "main-header",
h2(tags$i(class = "fas fa-upload", style = "margin-right:8px;"), "Data Upload"),
p("Upload genotype, phenotype, and population data for comprehensive QTL analysis with AI assistance")
),
fluidRow(
column(4,
div(class = "card",
div(class = "card-header", tags$i(class = "fas fa-table", style = "margin-right:6px;"), "Training Data"),
div(class = "card-body",
fileInput("genotype_file", "Training Genotype CSV", accept = ".csv", buttonLabel = "Browse"),
helpText("CSV: Row1=header(id,markers), Row2=chromosomes, Row3=positions, rows=samples. Genotype coded 0/1/2."),
fileInput("phenotype_file", "Training Phenotype CSV", accept = ".csv", buttonLabel = "Browse"),
helpText("CSV: id column + numeric trait columns."),
selectInput("phenotype_column", "Select Phenotype Column", choices = NULL)
)
)
),
column(4,
div(class = "card",
div(class = "card-header", tags$i(class = "fas fa-vial", style = "margin-right:6px; color:#3fb950;"), "Test Data (Optional)"),
div(class = "card-body",
fileInput("test_genotype_file", "Test Genotype CSV", accept = ".csv", buttonLabel = "Browse"),
helpText("Optional: Same format as training genotype data."),
tags$br(),
actionButton("predict_test_phenotype", "Predict Test Phenotypes", class = "btn-info btn-block", icon = icon("magic"))
)
)
),
column(4,
div(class = "card",
div(class = "card-header", tags$i(class = "fas fa-sliders-h", style = "margin-right:6px; color:#bc8cff;"), "Analysis Parameters"),
div(class = "card-body",
sliderInput("test_size", "Validation Set Proportion", min = 0.1, max = 0.5, value = 0.2, step = 0.05),
numericInput("lod_threshold", "LOD Threshold", value = 2.0, min = 1.0, max = 10.0, step = 0.1),
actionButton("run_analysis", "Run QTL Analysis", class = "btn-primary btn-block", icon = icon("play"))
)
)
)
),
fluidRow(
column(12,
div(class = "card",
div(class = "card-header", "Data Preview"),
div(class = "card-body",
tabsetPanel(
tabPanel("Training Genotype", DTOutput("geno_preview")),
tabPanel("Training Phenotype", DTOutput("pheno_preview")),
tabPanel("Test Genotype", DTOutput("test_geno_preview")),
tabPanel("Predicted Test Phenotype", DTOutput("predicted_test_pheno_preview"))
)
)
)
)
)
),
# ---- Domestication tab ----
tabPanel("Domestication", icon = icon("leaf"),
div(class = "main-header",
h2(tags$i(class = "fas fa-leaf", style = "margin-right:8px;"), "Domestication Analysis"),
p("Analyze selection signatures: Fst, Tajima's D, and nucleotide diversity")
),
fluidRow(
column(4,
div(class = "card",
div(class = "card-header", "Population Metadata"),
div(class = "card-body",
fileInput("pop_file", "Population Metadata CSV", accept = ".csv", buttonLabel = "Browse"),
helpText("CSV with 'id' and 'population' columns (e.g., Domesticated, Wild)."),
numericInput("fst_threshold", "Fst Threshold", value = 0.1, min = 0.05, max = 0.5, step = 0.01),
numericInput("tajima_threshold", "Tajima's D Threshold", value = -1, min = -5, max = 0, step = 0.1),
actionButton("run_domestication", "Run Domestication Analysis", class = "btn-primary btn-block", icon = icon("play"))
)
)
),
column(8,
div(class = "card",
div(class = "card-header", "Population Data Preview"),
div(class = "card-body", DTOutput("pop_preview"))
)
)
),
fluidRow(
column(6, div(class = "card", div(class = "card-header", "Fst Manhattan Plot"), div(class = "card-body", plotlyOutput("fst_plot", height = "400px")))),
column(6, div(class = "card", div(class = "card-header", "Tajima's D Manhattan Plot"), div(class = "card-body", plotlyOutput("tajima_plot", height = "400px"))))
),
fluidRow(
column(12,
div(class = "card",
div(class = "card-header", "Selection Signatures"),
div(class = "card-body",
DTOutput("selection_table"),
tags$br(),
downloadButton("download_selection", "Download Selection Results")
)
)
)
)
),
# ---- Results tab ----
tabPanel("Results", icon = icon("chart-line"),
div(class = "main-header",
h2(tags$i(class = "fas fa-chart-line", style = "margin-right:8px;"), "QTL Analysis Results"),
p("LOD scores, QTL effects, model performance, and epistasis analysis")
),
fluidRow(
column(6, div(class = "card", div(class = "card-header", "Manhattan Plot (LOD Scores)"), div(class = "card-body", plotlyOutput("lod_plot_2d", height = "500px")))),
column(6, div(class = "card",
div(class = "card-header", "Chromosome Visualization"),
div(class = "card-body",
uiOutput("chromosome_viz"),
div(class = "simulation-controls",
actionButton("simulate_btn", "Simulate Discovery", class = "simulation-btn"),
actionButton("reset_btn", "Reset", class = "simulation-btn")
)
)
))
),
fluidRow(
column(4, div(class = "card", div(class = "card-header", "Model Performance"), div(class = "card-body", plotlyOutput("performance_plot")))),
column(4, div(class = "card", div(class = "card-header", "Train: Predicted vs Observed"), div(class = "card-body", plotlyOutput("regression_plot_train", height = "300px")))),
column(4, div(class = "card", div(class = "card-header", "Validation: Predicted vs Observed"), div(class = "card-body", plotlyOutput("regression_plot_test", height = "300px"))))
),
fluidRow(
column(12, div(class = "card",
div(class = "card-header", "QTL Effects - Training Set"),
div(class = "card-body", DTOutput("qtl_effects_table_train"), tags$br(), downloadButton("download_train_results", "Download"))
))
),
fluidRow(
column(12, div(class = "card",
div(class = "card-header", "Epistasis Analysis"),
div(class = "card-body",
DTOutput("epistasis_table"),
plotlyOutput("epistasis_heatmap", height = "400px")
)
))
)
),
# ---- Interpretation tab ----
tabPanel("Interpretation", icon = icon("lightbulb"),
div(class = "main-header",
h2(tags$i(class = "fas fa-lightbulb", style = "margin-right:8px;"), "Results Interpretation"),
p("Comprehensive interpretation of QTL and domestication analysis")
),
fluidRow(column(12, div(class = "card", div(class = "card-header", "Analysis Summary"), div(class = "card-body", uiOutput("analysis_summary"))))),
fluidRow(
column(6, div(class = "card", div(class = "card-header", "QTL Significance"), div(class = "card-body", uiOutput("qtl_interpretation")))),
column(6, div(class = "card", div(class = "card-header", "Effect Sizes"), div(class = "card-body", uiOutput("effect_interpretation"))))
),
fluidRow(column(12, div(class = "card", div(class = "card-header", "Epistasis"), div(class = "card-body", uiOutput("epistasis_interpretation"))))),
fluidRow(column(12, div(class = "card", div(class = "card-header", "Recommendations"), div(class = "card-body", uiOutput("recommendations")))))
),
# ---- About tab ----
tabPanel("About", icon = icon("info-circle"),
div(class = "main-header",
h2(tags$i(class = "fas fa-info-circle", style = "margin-right:8px;"), "About QTL-Mapper AI"),
p("QTL Mapping with Transformer-based AI Assistant")
),
fluidRow(
column(8, offset = 2,
div(class = "card",
div(class = "card-body",
h4(style = "color:#58a6ff; font-family:'IBM Plex Mono'; margin-bottom:12px;", "Methodology"),
tags$ul(style = "color:#8b949e; line-height:2;",
tags$li("Random Forest for QTL mapping with variable importance scoring"),
tags$li("LOD scores derived from marker importance (-log10 scale)"),
tags$li("Additive and dominance effects estimated via linear regression"),
tags$li("Epistasis analysis: pairwise QTL x marker interactions"),
tags$li("Domestication: Fst, nucleotide diversity (Pi), Tajima's D"),
tags$li("AI Assistant powered by transformer models via Hugging Face Inference API")
),
h4(style = "color:#58a6ff; font-family:'IBM Plex Mono'; margin:12px 0;", "AI Assistant Status"),
p(style = "color:#8b949e; line-height:1.7;",
if (use_hf_api) paste("Connected to Hugging Face API using", hf_model)
else "AI Assistant is in rule-based mode. Set HF_API_TOKEN in Space secrets to enable transformer-based responses."
),
h4(style = "color:#58a6ff; font-family:'IBM Plex Mono'; margin:12px 0;", "Interpretation Thresholds"),
tags$ul(style = "color:#8b949e; line-height:2;",
tags$li("LOD > 3: Suggestive QTL | LOD > 5: Significant QTL"),
tags$li("Fst > 0.2: Strong population differentiation"),
tags$li("Tajima's D < -2: Potential selective sweep"),
tags$li("PVE > 10%: Major-effect QTL")
)
)
)
)
)
)
),
# ---- Floating Chat Panel ----
tags$div(id = "chat-panel",
tags$div(id = "chat-window",
tags$div(id = "chat-header",
tags$div(class = "chat-title",
tags$div(class = "chat-avatar", "AI"),
tags$div(
tags$h4("QTL Analysis AI Assistant",
tags$span(class = "model-badge",
if (use_hf_api) gsub(".*/", "", hf_model) else "rules")
),
tags$p(id = "model_status",
if (use_hf_api) paste("AI mode -", gsub(".*/", "", hf_model)) else "Rule-based mode",
class = if (use_hf_api) "ai-mode" else "rule-mode"
)
)
),
tags$button(id = "chat-close-btn",
onclick = "document.getElementById('chat-window').classList.remove('open');",
tags$i(class = "fas fa-times"))
),
tags$div(class = "quick-questions",
tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q','What is PVE?',{priority:'event'});", "PVE meaning"),
tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q','What are my top QTLs?',{priority:'event'});", "Top QTLs"),
tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q','Why is my R2 negative?',{priority:'event'});", "Negative R2"),
tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q','What should I do next?',{priority:'event'});", "Next steps")
),
tags$div(id = "chat_messages", uiOutput("chat_display")),
tags$div(id = "chat-footer",
tags$textarea(id = "chat_input", placeholder = "Ask about your results... (Enter to send)", rows = "2"),
tags$div(class = "chat-actions",
actionButton("send_chat", "Send", icon = icon("paper-plane"), class = "btn-primary"),
actionButton("clear_chat", "Clear", icon = icon("trash-alt"), class = "btn-danger")
)
)
),
tags$button(id = "chat-toggle-btn",
onclick = "document.getElementById('chat-window').classList.toggle('open');",
tags$i(class = "fas fa-robot"))
)
)
# ============================================================
# SERVER
# ============================================================
server <- function(input, output, session) {
values <- reactiveValues(
genotype_data = NULL,
phenotype_data = NULL,
test_genotype_data = NULL,
predicted_test_phenotype_data = NULL,
chromosome_info = NULL,
position_info = NULL,
all_markers = NULL,
importance_scores = NULL,
lod_scores_train = NULL,
model_fit = NULL,
phenotype_values = NULL,
qtl_effects_train = NULL,
qtl_effects_test = NULL,
performance_metrics = NULL,
train_predictions = NULL,
test_predictions = NULL,
epistasis_all = NULL,
epistasis_sig = NULL,
pop_data = NULL,
selection_metrics = NULL,
has_test_data = FALSE,
chat_messages = list(),
is_typing = FALSE,
lod_threshold = 2,
use_ai = use_hf_api
)
observe({
if (values$use_ai) {
shinyjs::html("model_status", paste("AI mode -", gsub(".*/", "", hf_model)))
} else {
shinyjs::html("model_status", "Rule-based mode")
}
})
# ---- Chat helpers ----
add_message <- function(role, content) {
timestamp <- format(Sys.time(), "%H:%M")
values$chat_messages <- c(values$chat_messages,
list(list(role = role, content = content, time = timestamp)))
if (length(values$chat_messages) > 50)
values$chat_messages <- tail(values$chat_messages, 50)
session$sendCustomMessage("scrollChatBottom", list())
}
process_message <- function(user_text) {
if (nchar(trimws(user_text)) == 0) return()
add_message("user", user_text)
values$is_typing <- TRUE
response <- generate_ai_response(user_text, values)
values$is_typing <- FALSE
add_message("assistant", response)
}
observeEvent(input$send_chat, {
req(input$chat_input)
user_text <- trimws(input$chat_input)
if (nchar(user_text) == 0) return()
updateTextAreaInput(session, "chat_input", value = "")
process_message(user_text)
})
observeEvent(input$quick_q, { req(input$quick_q); process_message(input$quick_q) })
observeEvent(input$clear_chat, {
values$chat_messages <- list()
add_message("assistant", "Chat cleared. How can I help?")
})
observe({
if (length(values$chat_messages) == 0) {
mode_msg <- if (values$use_ai) {
paste("I'm using the", gsub(".*/", "", hf_model), "model via Hugging Face API!")
} else {
"I'm using rule-based responses. To enable AI mode, set HF_API_TOKEN in Space secrets."
}
add_message("assistant", paste(
"\U0001f44b Hello! I'm your QTL analysis assistant.", mode_msg,
"\n\n**I can help you with:**",
"\u2022 **What is PVE?** - Understand variance explained",
"\u2022 **Show top QTLs** - List your most significant markers",
"\u2022 **Model performance** - Why is my R\u00b2 negative?",
"\u2022 **Next steps** - Recommendations",
"\nTry asking: **'What is PVE?'**"))
}
})
output$chat_display <- renderUI({
messages <- values$chat_messages
if (length(messages) == 0) return(NULL)
elems <- lapply(messages, function(msg) {
div(class = paste("chat-msg", msg$role),
div(class = "chat-bubble",
HTML(gsub("\n", "<br>", htmltools::htmlEscape(msg$content)))),
div(class = "chat-meta", msg$time))
})
if (values$is_typing) {
elems <- c(elems, list(
div(class = "chat-msg assistant",
div(class = "typing-indicator",
div(class = "typing-dot"), div(class = "typing-dot"), div(class = "typing-dot")))))
}
do.call(tagList, elems)
})
# ---- Data loading ----
observeEvent(input$genotype_file, {
req(input$genotype_file)
tryCatch({
all_data <- readLines(input$genotype_file$datapath)
if (length(all_data) < 4) { showNotification("Genotype file must have at least 4 rows", type = "error"); return() }
header <- strsplit(all_data[1], ",")[[1]]
chromosome_row <- strsplit(all_data[2], ",")[[1]]
position_row <- strsplit(all_data[3], ",")[[1]]
genotype_data <- read.csv(text = all_data[-(1:3)], header = FALSE)
colnames(genotype_data) <- header
rownames(genotype_data) <- genotype_data[, 1]
genotype_data <- genotype_data[, -1]
for (col in colnames(genotype_data))
genotype_data[[col]] <- as.numeric(as.character(genotype_data[[col]]))
values$all_markers <- data.frame(
Marker = colnames(genotype_data),
Chromosome = chromosome_row[-1],
Position = as.numeric(position_row[-1]),
stringsAsFactors = FALSE)
values$genotype_data <- genotype_data
values$chromosome_info <- chromosome_row[-1]
values$position_info <- as.numeric(position_row[-1])
showNotification("Genotype data loaded", type = "message")
add_message("assistant", paste0("\u2705 Loaded ", ncol(genotype_data), " markers, ", nrow(genotype_data), " samples"))
}, error = function(e) showNotification(paste("Error:", e$message), type = "error"))
})
observeEvent(input$phenotype_file, {
req(input$phenotype_file)
tryCatch({
phenotype_data <- read.csv(input$phenotype_file$datapath)
rownames(phenotype_data) <- phenotype_data[, 1]
phenotype_data <- phenotype_data[, -1]
for (col in colnames(phenotype_data))
phenotype_data[[col]] <- as.numeric(as.character(phenotype_data[[col]]))
values$phenotype_data <- phenotype_data
updateSelectInput(session, "phenotype_column",
choices = colnames(phenotype_data),
selected = colnames(phenotype_data)[1])
showNotification("Phenotype data loaded", type = "message")
add_message("assistant", paste0("\u2705 Loaded ", ncol(phenotype_data), " traits, ", nrow(phenotype_data), " samples"))
}, error = function(e) showNotification(paste("Error:", e$message), type = "error"))
})
observeEvent(input$pop_file, {
req(input$pop_file)
tryCatch({
pop_data <- read.csv(input$pop_file$datapath)
if (!all(c("id", "population") %in% colnames(pop_data))) {
showNotification("Population file must have 'id' and 'population' columns", type = "error"); return()
}
values$pop_data <- pop_data
showNotification("Population data loaded", type = "message")
add_message("assistant", paste0("\u2705 Loaded population data (", nrow(pop_data), " samples)"))
}, error = function(e) showNotification(paste("Error:", e$message), type = "error"))
})
observeEvent(input$test_genotype_file, {
req(input$test_genotype_file)
tryCatch({
all_data <- readLines(input$test_genotype_file$datapath)
header <- strsplit(all_data[1], ",")[[1]]
genotype_data <- read.csv(text = all_data[-(1:3)], header = FALSE)
colnames(genotype_data) <- header
rownames(genotype_data) <- genotype_data[, 1]
genotype_data <- genotype_data[, -1]
for (col in colnames(genotype_data))
genotype_data[[col]] <- as.numeric(as.character(genotype_data[[col]]))
values$test_genotype_data <- genotype_data
values$has_test_data <- TRUE
showNotification("Test genotype data loaded", type = "message")
}, error = function(e) showNotification(paste("Error:", e$message), type = "error"))
})
# ---- Data previews ----
output$geno_preview <- renderDT({ req(input$genotype_file); datatable(head(read.csv(input$genotype_file$datapath), 10), options = list(scrollX = TRUE, pageLength = 5)) })
output$pheno_preview <- renderDT({ req(input$phenotype_file); datatable(head(read.csv(input$phenotype_file$datapath), 10), options = list(scrollX = TRUE, pageLength = 5)) })
output$test_geno_preview <- renderDT({ req(input$test_genotype_file); datatable(head(read.csv(input$test_genotype_file$datapath), 10), options = list(scrollX = TRUE, pageLength = 5)) })
output$pop_preview <- renderDT({ req(input$pop_file); datatable(head(read.csv(input$pop_file$datapath), 10), options = list(scrollX = TRUE, pageLength = 5)) })
output$predicted_test_pheno_preview <- renderDT({ req(values$predicted_test_phenotype_data); datatable(values$predicted_test_phenotype_data, options = list(scrollX = TRUE, pageLength = 5)) })
# ---- QTL effect calculation ----
calculate_qtl_effects <- function(genotype_matrix, phenotype_vector, marker_names) {
effects_list <- list()
for (marker in marker_names) {
if (!marker %in% colnames(genotype_matrix)) next
geno <- genotype_matrix[, marker]
pheno <- phenotype_vector
valid_idx <- !is.na(geno) & !is.na(pheno)
geno <- geno[valid_idx]
pheno <- pheno[valid_idx]
if (length(unique(geno)) < 2) next
lm_fit <- lm(pheno ~ geno)
additive_effect <- coef(lm_fit)[2]
dominance_effect <- NA
if (length(unique(geno)) == 3) {
geno_means <- tapply(pheno, geno, mean, na.rm = TRUE)
het_mean <- geno_means[as.character(sort(unique(geno))[2])]
midparent <- (geno_means[as.character(sort(unique(geno))[1])] +
geno_means[as.character(sort(unique(geno))[3])]) / 2
dominance_effect <- het_mean - midparent
}
r_squared <- summary(lm_fit)$r.squared
se_additive <- tryCatch(summary(lm_fit)$coefficients[2, 2], error = function(e) NA)
effects_list[[marker]] <- data.frame(
Marker = marker,
Additive_Effect = additive_effect,
Dominance_Effect = dominance_effect,
PVE_Percent = r_squared * 100,
SE_Additive = se_additive,
CI_Lower = ifelse(is.na(se_additive), NA, additive_effect - 1.96 * se_additive),
CI_Upper = ifelse(is.na(se_additive), NA, additive_effect + 1.96 * se_additive),
N_Samples = length(pheno),
stringsAsFactors = FALSE)
}
if (length(effects_list) == 0) return(NULL)
do.call(rbind, effects_list)
}
# ---- Main QTL analysis ----
observeEvent(input$run_analysis, {
req(values$genotype_data, values$phenotype_data, input$phenotype_column)
showNotification("Starting QTL analysis...", type = "message")
values$lod_threshold <- input$lod_threshold
tryCatch({
common_samples <- intersect(rownames(values$genotype_data), rownames(values$phenotype_data))
if (length(common_samples) == 0) { showNotification("No common samples", type = "error"); return() }
X <- values$genotype_data[common_samples, , drop = FALSE]
y <- as.numeric(values$phenotype_data[common_samples, input$phenotype_column])
nzv <- nearZeroVar(X)
if (length(nzv) > 0) X <- X[, -nzv, drop = FALSE]
set.seed(123)
train_index <- createDataPartition(y, p = 1 - input$test_size, list = FALSE)
X_train <- X[train_index, , drop = FALSE]; X_val <- X[-train_index, , drop = FALSE]
y_train <- y[train_index]; y_val <- y[-train_index]
model <- train(x = X_train, y = y_train, method = "rf",
trControl = trainControl(method = "cv", number = 5),
importance = TRUE, tuneLength = 3)
values$model_fit <- model
imp <- varImp(model, scale = FALSE)$importance
importance_scores <- data.frame(
Marker = rownames(imp),
LOD = imp$Overall,
Chromosome = values$chromosome_info[match(rownames(imp), colnames(X))],
Position = as.numeric(values$position_info[match(rownames(imp), colnames(X))]),
stringsAsFactors = FALSE)
values$importance_scores <- importance_scores
lod_sig <- importance_scores[importance_scores$LOD > input$lod_threshold, , drop = FALSE]
if (nrow(lod_sig) > 0) {
lod_sig$Low_Flank <- NA
lod_sig$High_Flank <- NA
for (i in 1:nrow(lod_sig)) {
chr_m <- values$all_markers[values$all_markers$Chromosome == lod_sig$Chromosome[i], ]
chr_m <- chr_m[order(chr_m$Position), ]
idx <- which(chr_m$Marker == lod_sig$Marker[i])
if (length(idx) > 0) {
lod_sig$Low_Flank[i] <- if (idx > 1) chr_m$Marker[idx - 1] else lod_sig$Marker[i]
lod_sig$High_Flank[i] <- if (idx < nrow(chr_m)) chr_m$Marker[idx + 1] else lod_sig$Marker[i]
}
}
values$lod_scores_train <- lod_sig
qtl_fx <- calculate_qtl_effects(X_train, y_train, lod_sig$Marker)
if (!is.null(qtl_fx)) {
values$qtl_effects_train <- merge(lod_sig, qtl_fx, by = "Marker")
} else {
values$qtl_effects_train <- data.frame(Message = "Could not calculate QTL effects")
}
} else {
values$lod_scores_train <- data.frame(Message = paste("No QTLs above LOD", input$lod_threshold))
values$qtl_effects_train <- data.frame(Message = paste("No QTLs above LOD", input$lod_threshold))
}
y_train_pred <- predict(model, X_train)
y_val_pred <- predict(model, X_val)
train_r2 <- 1 - sum((y_train - y_train_pred)^2) / sum((y_train - mean(y_train))^2)
val_r2 <- 1 - sum((y_val - y_val_pred)^2) / sum((y_val - mean(y_val))^2)
values$performance_metrics <- data.frame(
Metric = c("R\u00b2 (Train)", "R (Train)", "R\u00b2 (Validation)", "R (Validation)"),
Value = c(train_r2, cor(y_train, y_train_pred), val_r2, cor(y_val, y_val_pred)),
stringsAsFactors = FALSE)
values$train_predictions <- data.frame(Observed = y_train, Predicted = y_train_pred)
values$test_predictions <- data.frame(Observed = y_val, Predicted = y_val_pred)
# Epistasis
if (nrow(lod_sig) > 0) {
sig_markers <- lod_sig$Marker[lod_sig$Marker %in% colnames(X_train)]
all_markers_v <- colnames(X_train)
epistasis_list <- list()
withProgress(message = "Calculating epistasis...", value = 0, {
total <- length(sig_markers) * length(all_markers_v)
for (m1 in sig_markers) {
for (m2 in all_markers_v) {
if (m1 == m2) next
incProgress(1 / total)
tryCatch({
data_epi <- data.frame(y = y_train, m1 = X_train[, m1], m2 = X_train[, m2])
data_epi <- na.omit(data_epi)
if (nrow(data_epi) < 10) next
fit <- lm(y ~ m1 * m2, data = data_epi)
coef_summary <- summary(fit)$coefficients
if ("m1:m2" %in% rownames(coef_summary)) {
epistasis_list[[length(epistasis_list) + 1]] <- data.frame(
QTL1 = m1, QTL2 = m2,
Interaction_p = coef_summary["m1:m2", "Pr(>|t|)"],
Effect_Size = coef(fit)["m1:m2"],
stringsAsFactors = FALSE)
}
}, error = function(e) {})
}
}
})
if (length(epistasis_list) > 0) {
epistasis_all <- do.call(rbind, epistasis_list)
values$epistasis_all <- epistasis_all
values$epistasis_sig <- epistasis_all[epistasis_all$Interaction_p < 0.05, ]
} else {
values$epistasis_all <- data.frame(Message = "No epistatic interactions")
values$epistasis_sig <- data.frame(Message = "No epistatic interactions")
}
}
showNotification("QTL analysis completed!", type = "message")
n_qtl <- if (!is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train)) nrow(values$qtl_effects_train) else 0
add_message("assistant", paste("\u2705 QTL analysis complete!", paste0("\u2022 Found ", n_qtl, " QTLs"), paste0("\u2022 Validation R\u00b2: ", round(val_r2, 3)), "Ask me about PVE or top QTLs!"))
updateTabsetPanel(session, "nav", selected = "Results")
}, error = function(e) showNotification(paste("Error:", e$message), type = "error"))
})
# ---- Domestication analysis ----
calculate_selection_metrics <- function(genotype_matrix, pop_data, marker_info) {
metrics_list <- list()
for (marker in colnames(genotype_matrix)) {
geno <- genotype_matrix[, marker]
pop <- pop_data$population[match(rownames(genotype_matrix), pop_data$id)]
valid_idx <- !is.na(geno) & !is.na(pop)
geno <- geno[valid_idx]; pop <- pop[valid_idx]
if (length(unique(pop)) < 2) next
geno_dom <- geno[pop == "Domesticated"]
geno_wild <- geno[pop == "Wild"]
if (length(geno_dom) < 3 || length(geno_wild) < 3) next
freq_dom <- mean(geno_dom, na.rm = TRUE) / 2
freq_wild <- mean(geno_wild, na.rm = TRUE) / 2
p_avg <- (freq_dom + freq_wild) / 2
fst <- if (p_avg > 0 && p_avg < 1) {
f <- (freq_dom - freq_wild)^2 / (p_avg * (1 - p_avg))
f / (1 + f)
} else 0
pi_dom <- 2 * freq_dom * (1 - freq_dom)
pi_wild <- 2 * freq_wild * (1 - freq_wild)
n_dom <- length(geno_dom)
n_wild <- length(geno_wild)
tajima_d_dom <- (pi_dom - 1/n_dom) / sqrt(var(geno_dom) /n_dom)
tajima_d_wild <- (pi_wild - 1/n_wild) / sqrt(var(geno_wild)/n_wild)
marker_row <- marker_info[marker_info$Marker == marker, ]
metrics_list[[marker]] <- data.frame(
Marker = marker,
Chromosome = ifelse(nrow(marker_row) > 0, marker_row$Chromosome[1], NA),
Position = ifelse(nrow(marker_row) > 0, marker_row$Position[1], NA),
Fst = fst, Pi_Dom = pi_dom, Pi_Wild = pi_wild,
Tajima_D_Dom = tajima_d_dom, Tajima_D_Wild = tajima_d_wild,
stringsAsFactors = FALSE)
}
if (length(metrics_list) == 0) return(NULL)
do.call(rbind, metrics_list)
}
observeEvent(input$run_domestication, {
req(values$genotype_data, values$pop_data, values$all_markers)
tryCatch({
common_samples <- intersect(rownames(values$genotype_data), values$pop_data$id)
if (length(common_samples) == 0) { showNotification("No common samples", type = "error"); return() }
X <- values$genotype_data[common_samples, , drop = FALSE]
pop_subset <- values$pop_data[values$pop_data$id %in% common_samples, ]
sel_metrics <- calculate_selection_metrics(X, pop_subset, values$all_markers)
if (is.null(sel_metrics)) { showNotification("Could not calculate selection metrics", type = "error"); return() }
sel_metrics$Significant <-
sel_metrics$Fst > input$fst_threshold |
sel_metrics$Tajima_D_Dom < input$tajima_threshold |
sel_metrics$Tajima_D_Wild < input$tajima_threshold
values$selection_metrics <- sel_metrics
showNotification("Domestication analysis completed!", type = "message")
n_sig <- sum(sel_metrics$Significant, na.rm = TRUE)
add_message("assistant", paste("\u2705 Domestication analysis complete!", paste0("\u2022 Found ", n_sig, " markers with selection signatures")))
}, error = function(e) showNotification(paste("Error:", e$message), type = "error"))
})
# ---- Predict test phenotypes ----
observeEvent(input$predict_test_phenotype, {
req(values$model_fit, values$test_genotype_data)
tryCatch({
common_markers <- intersect(colnames(values$test_genotype_data), colnames(values$genotype_data))
if (length(common_markers) == 0) { showNotification("No common markers", type = "error"); return() }
X_test <- values$test_genotype_data[, common_markers, drop = FALSE]
predictions <- predict(values$model_fit, newdata = X_test)
values$predicted_test_phenotype_data <- data.frame(
id = rownames(X_test),
Predicted_Phenotype = as.numeric(predictions),
stringsAsFactors = FALSE)
showNotification("Predictions completed!", type = "message")
}, error = function(e) showNotification(paste("Error:", e$message), type = "error"))
})
# ---- Manhattan plot helper ----
create_manhattan <- function(data, y_col, title, threshold, y_label = y_col) {
if (is.null(data) || nrow(data) == 0 || "Message" %in% colnames(data))
return(plot_ly() %>% layout(title = "No data available",
plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e")))
plot_data <- data[!is.na(data[[y_col]]), ]
if (nrow(plot_data) == 0)
return(plot_ly() %>% layout(title = "No valid data",
plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e")))
chroms <- unique(plot_data$Chromosome)
chrom_pos <- data.frame()
for (i in seq_along(chroms)) {
chr_data <- plot_data[plot_data$Chromosome == chroms[i], ]
if (nrow(chr_data) > 0) {
chr_data$ChromIndex <- i
chr_data$PosScaled <- chr_data$Position / max(chr_data$Position, na.rm = TRUE) + (i - 1)
chrom_pos <- rbind(chrom_pos, chr_data)
}
}
p <- plot_ly() %>%
add_trace(data = chrom_pos, x = ~PosScaled, y = as.formula(paste0("~", y_col)),
type = "scatter", mode = "markers", color = ~factor(Chromosome),
colors = viridis(length(chroms)), marker = list(size = 6, opacity = 0.7),
text = ~paste("Marker:", Marker, "<br>Chr:", Chromosome, "<br>Pos:", Position,
"<br>", y_label, ":", round(get(y_col), 3)),
hoverinfo = "text", showlegend = FALSE)
if (!is.null(threshold) && !is.na(threshold))
p <- p %>% add_segments(
x = min(chrom_pos$PosScaled, na.rm = TRUE), xend = max(chrom_pos$PosScaled, na.rm = TRUE),
y = threshold, yend = threshold,
line = list(color = "red", dash = "dash", width = 1), name = "Threshold")
p %>% layout(title = title,
xaxis = list(title = "Chromosome",
ticktext = chroms,
tickvals = tapply(chrom_pos$PosScaled, chrom_pos$Chromosome, median, na.rm = TRUE),
tickangle = 45),
yaxis = list(title = y_label),
plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))
}
# ---- Plots ----
output$lod_plot_2d <- renderPlotly({
req(values$importance_scores)
create_manhattan(values$importance_scores, "LOD", "QTL Manhattan Plot", input$lod_threshold, "LOD Score")
})
output$fst_plot <- renderPlotly({
req(values$selection_metrics)
create_manhattan(values$selection_metrics, "Fst", "Fst Manhattan Plot", input$fst_threshold, "Fst")
})
output$tajima_plot <- renderPlotly({
req(values$selection_metrics)
if ("Message" %in% colnames(values$selection_metrics))
return(plot_ly() %>% layout(title = "No data available", plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e")))
data <- values$selection_metrics
chroms <- unique(data$Chromosome)
chrom_pos <- data.frame()
for (i in seq_along(chroms)) {
chr_data <- data[data$Chromosome == chroms[i], ]
if (nrow(chr_data) > 0) {
chr_data$ChromIndex <- i
chr_data$PosScaled <- chr_data$Position / max(chr_data$Position, na.rm = TRUE) + (i - 1)
chrom_pos <- rbind(chrom_pos, chr_data)
}
}
plot_ly() %>%
add_trace(data = chrom_pos, x = ~PosScaled, y = ~Tajima_D_Dom, type = "scatter", mode = "markers",
name = "Domesticated", marker = list(size = 5, color = "#58a6ff", opacity = 0.7),
text = ~paste("Marker:", Marker, "<br>D(Dom):", round(Tajima_D_Dom, 3)), hoverinfo = "text") %>%
add_trace(data = chrom_pos, x = ~PosScaled, y = ~Tajima_D_Wild, type = "scatter", mode = "markers",
name = "Wild", marker = list(size = 5, color = "#f97316", opacity = 0.7),
text = ~paste("Marker:", Marker, "<br>D(Wild):", round(Tajima_D_Wild, 3)), hoverinfo = "text") %>%
add_segments(x = min(chrom_pos$PosScaled, na.rm = TRUE), xend = max(chrom_pos$PosScaled, na.rm = TRUE),
y = input$tajima_threshold, yend = input$tajima_threshold,
line = list(color = "red", dash = "dash", width = 1)) %>%
layout(title = "Tajima's D Manhattan Plot",
xaxis = list(title = "Chromosome",
ticktext = chroms,
tickvals = tapply(chrom_pos$PosScaled, chrom_pos$Chromosome, median, na.rm = TRUE),
tickangle = 45),
yaxis = list(title = "Tajima's D"),
plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))
})
output$performance_plot <- renderPlotly({
req(values$performance_metrics)
plot_ly(data = values$performance_metrics, x = ~Metric, y = ~Value, type = "bar",
marker = list(color = c("#58a6ff", "#58a6ff", "#3fb950", "#3fb950")),
text = ~round(Value, 3), textposition = "outside") %>%
layout(title = "Model Performance",
yaxis = list(title = "Value", range = c(0, 1.1)),
plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))
})
output$regression_plot_train <- renderPlotly({
req(values$train_predictions)
plot_ly(data = values$train_predictions, x = ~Observed, y = ~Predicted,
type = "scatter", mode = "markers", marker = list(size = 6, color = "#58a6ff", opacity = 0.7)) %>%
add_trace(x = range(values$train_predictions$Observed), y = range(values$train_predictions$Observed),
type = "scatter", mode = "lines", line = list(color = "#f85149", dash = "dash")) %>%
layout(title = "Training Set", xaxis = list(title = "Observed"), yaxis = list(title = "Predicted"),
plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))
})
output$regression_plot_test <- renderPlotly({
req(values$test_predictions)
plot_ly(data = values$test_predictions, x = ~Observed, y = ~Predicted,
type = "scatter", mode = "markers", marker = list(size = 6, color = "#3fb950", opacity = 0.7)) %>%
add_trace(x = range(values$test_predictions$Observed), y = range(values$test_predictions$Observed),
type = "scatter", mode = "lines", line = list(color = "#f85149", dash = "dash")) %>%
layout(title = "Validation Set", xaxis = list(title = "Observed"), yaxis = list(title = "Predicted"),
plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))
})
output$epistasis_heatmap <- renderPlotly({
req(values$epistasis_all)
if ("Message" %in% colnames(values$epistasis_all))
return(plot_ly() %>% layout(title = values$epistasis_all$Message[1],
plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e")))
qtls <- unique(values$epistasis_all$QTL1)
markers <- unique(values$epistasis_all$QTL2)
p_mat <- matrix(NA, nrow = length(qtls), ncol = length(markers),
dimnames = list(qtls, markers))
for (i in 1:nrow(values$epistasis_all))
p_mat[values$epistasis_all$QTL1[i], values$epistasis_all$QTL2[i]] <-
-log10(values$epistasis_all$Interaction_p[i])
plot_ly(x = colnames(p_mat), y = rownames(p_mat), z = p_mat,
type = "heatmap", colorscale = "Viridis",
hovertemplate = "QTL: %{y}<br>Marker: %{x}<br>-log10(p): %{z:.2f}") %>%
layout(title = "Epistatic Interactions",
xaxis = list(title = "Marker", tickangle = 45), yaxis = list(title = "QTL"),
plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))
})
# ---- Tables ----
output$qtl_effects_table_train <- renderDT({
req(values$qtl_effects_train)
if ("Message" %in% colnames(values$qtl_effects_train))
return(datatable(data.frame(Status = values$qtl_effects_train$Message[1]), options = list(dom = "t")))
display_cols <- intersect(
c("Marker", "Chromosome", "Position", "LOD", "Additive_Effect", "PVE_Percent", "Low_Flank", "High_Flank"),
colnames(values$qtl_effects_train))
df <- values$qtl_effects_train[order(-values$qtl_effects_train$LOD), display_cols]
datatable(df, options = list(pageLength = 10, scrollX = TRUE), rownames = FALSE) %>%
formatRound(intersect(c("LOD", "Additive_Effect", "PVE_Percent"), colnames(df)), 3)
})
output$epistasis_table <- renderDT({
req(values$epistasis_sig)
if ("Message" %in% colnames(values$epistasis_sig))
return(datatable(data.frame(Status = values$epistasis_sig$Message[1]), options = list(dom = "t")))
datatable(values$epistasis_sig[order(values$epistasis_sig$Interaction_p), ],
options = list(pageLength = 10, scrollX = TRUE), rownames = FALSE) %>%
formatSignif(columns = c("Interaction_p", "Effect_Size"), digits = 4)
})
output$selection_table <- renderDT({
req(values$selection_metrics)
if ("Message" %in% colnames(values$selection_metrics))
return(datatable(data.frame(Status = values$selection_metrics$Message[1]), options = list(dom = "t")))
df <- values$selection_metrics
if (!is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train))
df$QTL_Overlap <- df$Marker %in% values$qtl_effects_train$Marker
display_cols <- intersect(
c("Marker", "Chromosome", "Fst", "Pi_Dom", "Pi_Wild", "Tajima_D_Dom", "Significant", "QTL_Overlap"),
colnames(df))
datatable(df[order(-df$Fst), display_cols], options = list(pageLength = 10, scrollX = TRUE), rownames = FALSE) %>%
formatRound(c("Fst", "Pi_Dom", "Pi_Wild", "Tajima_D_Dom"), 3)
})
# ---- Chromosome visualization ----
output$chromosome_viz <- renderUI({
req(values$lod_scores_train, values$all_markers)
if ("Message" %in% colnames(values$lod_scores_train))
return(div(class = "alert alert-info", values$lod_scores_train$Message[1]))
chromosomes <- unique(values$lod_scores_train$Chromosome)
tagList(lapply(chromosomes, function(chr) {
chr_markers <- values$all_markers[values$all_markers$Chromosome == chr, ]
chr_markers <- chr_markers[order(chr_markers$Position), ]
chr_qtls <- values$lod_scores_train[values$lod_scores_train$Chromosome == chr, ]
sel_markers <- NULL
if (!is.null(values$selection_metrics) && !"Message" %in% colnames(values$selection_metrics))
sel_markers <- values$selection_metrics[
values$selection_metrics$Chromosome == chr & values$selection_metrics$Significant, ]
min_pos <- min(chr_markers$Position, na.rm = TRUE)
max_pos <- max(chr_markers$Position, na.rm = TRUE)
range_pos <- max_pos - min_pos
div(class = "chromosome-container",
div(class = "chromosome-title", paste("Chromosome", chr)),
div(class = "chromosome",
lapply(1:nrow(chr_markers), function(i) {
marker <- chr_markers[i, ]
left <- if (range_pos > 0) ((marker$Position - min_pos) / range_pos) * 100
else (i / nrow(chr_markers)) * 100
marker_class <- "chromosome-marker"
if (marker$Marker %in% chr_qtls$Marker) {
marker_class <- paste(marker_class, "significant")
} else if (!is.null(sel_markers) && marker$Marker %in% sel_markers$Marker) {
marker_class <- paste(marker_class, "selection")
} else if (marker$Marker %in% c(chr_qtls$Low_Flank, chr_qtls$High_Flank)) {
marker_class <- paste(marker_class, "flanking")
}
div(class = marker_class, style = paste0("left: ", left, "%;"))
})
),
div(class = "chromosome-legend",
span(paste(format(min_pos, big.mark = ","), "bp")),
span(paste(format(max_pos, big.mark = ","), "bp")))
)
}))
})
# ---- Simulation animations ----
observeEvent(input$simulate_btn, session$sendCustomMessage("simulateQTLDiscovery", list()))
observeEvent(input$reset_btn, session$sendCustomMessage("resetAnimation", list()))
# ---- Interpretation outputs ----
output$analysis_summary <- renderUI({
has_qtl <- !is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train)
has_perf <- !is.null(values$performance_metrics)
has_epi <- !is.null(values$epistasis_sig) && !"Message" %in% colnames(values$epistasis_sig) && nrow(values$epistasis_sig) > 0
has_sel <- !is.null(values$selection_metrics) && !"Message" %in% colnames(values$selection_metrics)
n_qtl <- if (has_qtl) nrow(values$qtl_effects_train) else 0
n_epi <- if (has_epi) nrow(values$epistasis_sig) else 0
n_sel <- if (has_sel) sum(values$selection_metrics$Significant, na.rm = TRUE) else 0
val_r2 <- if (has_perf) round(values$performance_metrics$Value[values$performance_metrics$Metric == "R\u00b2 (Validation)"], 3) else "N/A"
div(class = "interpretation-section",
tags$h5("Analysis Summary"),
tags$p(paste("Found", n_qtl, "QTLs above LOD", input$lod_threshold,
if (has_perf) paste0("(validation R\u00b2 = ", val_r2, ")"),
if (has_epi) paste0("with ", n_epi, " epistatic interactions"),
if (has_sel) paste0("and ", n_sel, " selection signatures."))))
})
output$qtl_interpretation <- renderUI({
if (is.null(values$qtl_effects_train) || "Message" %in% colnames(values$qtl_effects_train))
return(div(class = "interpretation-section", tags$h5("QTL Significance"), tags$p("No significant QTLs detected.")))
top_qtl <- values$qtl_effects_train[which.max(values$qtl_effects_train$LOD), ]
div(class = "interpretation-section",
tags$h5("QTL Significance"),
tags$p(paste("Top QTL:", top_qtl$Marker, "(Chr", top_qtl$Chromosome, ") with LOD =", round(top_qtl$LOD, 2))))
})
output$effect_interpretation <- renderUI({
if (is.null(values$qtl_effects_train) || "Message" %in% colnames(values$qtl_effects_train))
return(div(class = "interpretation-section", tags$h5("Effect Sizes"), tags$p("No QTL effects to interpret.")))
top_pve <- values$qtl_effects_train[which.max(values$qtl_effects_train$PVE_Percent), ]
div(class = "interpretation-section",
tags$h5("Effect Sizes"),
tags$p(paste("Largest effect:", top_pve$Marker, "explains", round(top_pve$PVE_Percent, 1), "% of variance")))
})
output$epistasis_interpretation <- renderUI({
if (is.null(values$epistasis_sig) || "Message" %in% colnames(values$epistasis_sig) || nrow(values$epistasis_sig) == 0)
return(div(class = "interpretation-section", tags$h5("Epistasis"), tags$p("No significant epistatic interactions detected.")))
top_epi <- values$epistasis_sig[which.min(values$epistasis_sig$Interaction_p), ]
div(class = "interpretation-section",
tags$h5("Epistasis"),
tags$p(paste("Detected", nrow(values$epistasis_sig), "interactions. Strongest:",
top_epi$QTL1, "x", top_epi$QTL2, "(p =", format.pval(top_epi$Interaction_p), ")")))
})
output$recommendations <- renderUI({
has_qtl <- !is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train)
recs <- if (has_qtl) {
c("Validate top QTLs in independent populations",
"Use flanking markers for fine-mapping",
"Check gene annotations in QTL regions")
} else {
c("Upload data and run QTL analysis",
"Consider lowering LOD threshold",
"Check data quality")
}
div(class = "interpretation-section",
tags$h5("Recommendations"),
tags$ul(lapply(recs, tags$li), style = "color:#8b949e;"))
})
# ---- Download handlers ----
output$download_train_results <- downloadHandler(
filename = function() paste0("qtl_results_", Sys.Date(), ".xlsx"),
content = function(file) {
sheets <- list()
if (!is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train))
sheets[["QTLs"]] <- values$qtl_effects_train
if (!is.null(values$performance_metrics))
sheets[["Performance"]] <- values$performance_metrics
write_xlsx(sheets, file)
}
)
output$download_selection <- downloadHandler(
filename = function() paste0("selection_", Sys.Date(), ".xlsx"),
content = function(file) {
if (!is.null(values$selection_metrics) && !"Message" %in% colnames(values$selection_metrics)) {
write_xlsx(list(Selection = values$selection_metrics), file)
} else {
write_xlsx(list(Message = data.frame(msg = "No results")), file)
}
}
)
}
# ============================================================
# RUN APP#
# ============================================================
shinyApp(ui = ui, server = server)
# ============================================================
# QTL-Mapper - Fixed API Connection
# ============================================================
options(repos = c(CRAN = "https://cloud.r-project.org"))
required_packages <- c(
"shiny", "randomForest", "caret", "DT", "ggplot2", "plotly",
"writexl", "viridis", "reshape2", "dplyr", "httr", "jsonlite",
"shinyjs", "markdown"
)
for (pkg in required_packages) {
if (!require(pkg, character.only = TRUE)) {
install.packages(pkg, dependencies = TRUE)
library(pkg, character.only = TRUE)
}
}
# ============================================================
# TOKEN DEBUG
# ============================================================
token <- Sys.getenv("HF_API_TOKEN")
token_exists <- token != ""
token_length <- if(token_exists) nchar(token) else 0
print("=== HUGGING FACE API TOKEN DEBUG ===")
print(paste("Token exists:", token_exists))
print(paste("Token length:", token_length))
if(token_exists) print(paste("Token starts with:", substr(token, 1, 10)))
print("===================================")
# ============================================================
# API CONFIGURATION (single, clean definition)
# ============================================================
HF_API_TOKEN <- token
HF_API_URL <- "https://router.huggingface.co/v1/chat/completions"
#hf_model <- "HuggingFaceTB/SmolLM3-3B:hf-inference"
hf_model <- "meta-llama/Llama-3.2-3B-Instruct:together"
# ============================================================
# TEST CONNECTION
# ============================================================
test_api_connection <- function() {
if (!token_exists) return(list(success = FALSE, error = "No token found"))
tryCatch({
response <- POST(
url = HF_API_URL,
add_headers(
Authorization = paste("Bearer", HF_API_TOKEN),
"Content-Type" = "application/json"
),
body = toJSON(list(
model = hf_model,
messages = list(list(role = "user", content = "Hi")),
max_tokens = 10L
), auto_unbox = TRUE),
encode = "json",
timeout(15)
)
status <- status_code(response)
if (status == 200) return(list(success = TRUE))
err <- tryCatch(content(response, "text", encoding = "UTF-8"),
error = function(e) paste("Status:", status))
return(list(success = FALSE,
error = paste("Status:", status, "-", substr(err, 1, 200))))
}, error = function(e) list(success = FALSE, error = e$message))
}
api_test <- test_api_connection()
use_hf_api <- token_exists && api_test$success
print(paste("API Test result:", if(api_test$success) "SUCCESS" else paste("FAILED -", api_test$error)))
if (use_hf_api) {
print(paste("✅ API working with model:", hf_model, "- AI mode enabled"))
} else {
print("⚠️ API not available - using rule-based mode")
}
# ============================================================
# QUERY FUNCTION (single, OpenAI-compatible version)
# ============================================================
query_hf_api <- function(prompt, max_length = 500, temperature = 0.7) {
if (!token_exists) return(list(success = FALSE, error = "HF_API_TOKEN not set"))
tryCatch({
response <- POST(
url = HF_API_URL,
add_headers(
Authorization = paste("Bearer", HF_API_TOKEN),
"Content-Type" = "application/json"
),
body = toJSON(list(