International Rice Research Institute commited on
Commit
5fdc881
·
verified ·
1 Parent(s): 98fbb77

Update app.R

Browse files
Files changed (1) hide show
  1. app.R +628 -370
app.R CHANGED
@@ -1,5 +1,5 @@
1
  # ============================================================
2
- # QTL-Mapper - Fixed API Connection
3
  # ============================================================
4
 
5
  options(repos = c(CRAN = "https://cloud.r-project.org"))
@@ -7,7 +7,7 @@ options(repos = c(CRAN = "https://cloud.r-project.org"))
7
  required_packages <- c(
8
  "shiny", "randomForest", "caret", "DT", "ggplot2", "plotly",
9
  "writexl", "viridis", "reshape2", "dplyr", "httr", "jsonlite",
10
- "shinyjs", "markdown"
11
  )
12
 
13
  for (pkg in required_packages) {
@@ -32,21 +32,64 @@ if(token_exists) print(paste("Token starts with:", substr(token, 1, 10)))
32
  print("===================================")
33
 
34
  # ============================================================
35
- # API CONFIGURATION (single, clean definition)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
  # ============================================================
37
 
38
  HF_API_TOKEN <- token
39
  HF_API_URL <- "https://router.huggingface.co/v1/chat/completions"
40
- #hf_model <- "HuggingFaceTB/SmolLM3-3B:hf-inference"
41
- hf_model <- "meta-llama/Llama-3.2-3B-Instruct:together"
 
42
 
43
  # ============================================================
44
  # TEST CONNECTION
45
  # ============================================================
46
 
47
- test_api_connection <- function() {
48
  if (!token_exists) return(list(success = FALSE, error = "No token found"))
49
-
50
  tryCatch({
51
  response <- POST(
52
  url = HF_API_URL,
@@ -55,17 +98,17 @@ test_api_connection <- function() {
55
  "Content-Type" = "application/json"
56
  ),
57
  body = toJSON(list(
58
- model = hf_model,
59
  messages = list(list(role = "user", content = "Hi")),
60
  max_tokens = 10L
61
  ), auto_unbox = TRUE),
62
  encode = "json",
63
  timeout(15)
64
  )
65
-
66
  status <- status_code(response)
67
  if (status == 200) return(list(success = TRUE))
68
-
69
  err <- tryCatch(content(response, "text", encoding = "UTF-8"),
70
  error = function(e) paste("Status:", status))
71
  return(list(success = FALSE,
@@ -73,23 +116,23 @@ test_api_connection <- function() {
73
  }, error = function(e) list(success = FALSE, error = e$message))
74
  }
75
 
76
- api_test <- test_api_connection()
77
  use_hf_api <- token_exists && api_test$success
78
 
79
  print(paste("API Test result:", if(api_test$success) "SUCCESS" else paste("FAILED -", api_test$error)))
80
  if (use_hf_api) {
81
- print(paste("✅ API working with model:", hf_model, "- AI mode enabled"))
82
  } else {
83
- print("⚠️ API not available - using rule-based mode")
84
  }
85
 
86
  # ============================================================
87
- # QUERY FUNCTION (single, OpenAI-compatible version)
88
  # ============================================================
89
 
90
- query_hf_api <- function(prompt, max_length = 500, temperature = 0.7) {
91
  if (!token_exists) return(list(success = FALSE, error = "HF_API_TOKEN not set"))
92
-
93
  tryCatch({
94
  response <- POST(
95
  url = HF_API_URL,
@@ -98,7 +141,7 @@ query_hf_api <- function(prompt, max_length = 500, temperature = 0.7) {
98
  "Content-Type" = "application/json"
99
  ),
100
  body = toJSON(list(
101
- model = hf_model,
102
  messages = list(
103
  list(role = "system",
104
  content = "You are an expert bioinformatics assistant specializing in QTL analysis. Be concise and helpful."),
@@ -110,15 +153,15 @@ query_hf_api <- function(prompt, max_length = 500, temperature = 0.7) {
110
  encode = "json",
111
  timeout(60)
112
  )
113
-
114
  status <- status_code(response)
115
-
116
  if (status == 200) {
117
  result <- content(response, as = "parsed", encoding = "UTF-8")
118
  text <- result$choices[[1]]$message$content
119
  return(list(success = TRUE, text = text))
120
  }
121
-
122
  err <- tryCatch(content(response, "text", encoding = "UTF-8"),
123
  error = function(e) paste("Status:", status))
124
  return(list(success = FALSE,
@@ -132,15 +175,15 @@ query_hf_api <- function(prompt, max_length = 500, temperature = 0.7) {
132
 
133
  build_system_prompt <- function(rv) {
134
  context_parts <- c("CURRENT ANALYSIS RESULTS:")
135
-
136
  if (!is.null(rv$qtl_effects_train) && !"Message" %in% colnames(rv$qtl_effects_train)) {
137
  n_qtl <- nrow(rv$qtl_effects_train)
138
  total_pve <- sum(rv$qtl_effects_train$PVE_Percent, na.rm = TRUE)
139
-
140
  context_parts <- c(context_parts,
141
  sprintf("\nQTL Results: %d significant QTLs detected above LOD %.1f.", n_qtl, rv$lod_threshold),
142
  sprintf("Total variance explained by QTLs: %.1f%%.", total_pve))
143
-
144
  top_qtls <- head(rv$qtl_effects_train[order(-rv$qtl_effects_train$LOD), ], 3)
145
  context_parts <- c(context_parts, "\nTop QTLs:")
146
  for (i in 1:nrow(top_qtls)) {
@@ -150,7 +193,7 @@ build_system_prompt <- function(rv) {
150
  i, row$Marker, row$Chromosome, row$LOD, row$PVE_Percent, row$Additive_Effect))
151
  }
152
  }
153
-
154
  if (!is.null(rv$performance_metrics)) {
155
  pm <- rv$performance_metrics
156
  train_r2 <- pm$Value[pm$Metric == "R\u00b2 (Train)"]
@@ -160,7 +203,7 @@ build_system_prompt <- function(rv) {
160
  sprintf(" Training R\u00b2: %.3f", train_r2),
161
  sprintf(" Validation R\u00b2: %.3f", val_r2))
162
  }
163
-
164
  if (!is.null(rv$epistasis_sig) && !"Message" %in% colnames(rv$epistasis_sig) && nrow(rv$epistasis_sig) > 0) {
165
  n_epi <- nrow(rv$epistasis_sig)
166
  top_epi <- rv$epistasis_sig[order(rv$epistasis_sig$Interaction_p), ][1, ]
@@ -168,13 +211,13 @@ build_system_prompt <- function(rv) {
168
  sprintf("\nEpistasis: %d significant pairwise interactions detected.", n_epi),
169
  sprintf(" Strongest: %s x %s (p=%.4f)", top_epi$QTL1, top_epi$QTL2, top_epi$Interaction_p))
170
  }
171
-
172
  if (!is.null(rv$selection_metrics) && !"Message" %in% colnames(rv$selection_metrics)) {
173
  n_sig <- sum(rv$selection_metrics$Significant, na.rm = TRUE)
174
  context_parts <- c(context_parts,
175
  sprintf("\nDomestication: %d markers with selection signatures.", n_sig))
176
  }
177
-
178
  paste(context_parts, collapse = "\n")
179
  }
180
 
@@ -184,19 +227,18 @@ build_system_prompt <- function(rv) {
184
 
185
  enhanced_rule_response <- function(user_message, rv) {
186
  q <- tolower(trimws(user_message))
187
-
188
  has_qtl <- !is.null(rv$qtl_effects_train) && !"Message" %in% colnames(rv$qtl_effects_train)
189
  has_perf <- !is.null(rv$performance_metrics)
190
  has_epi <- !is.null(rv$epistasis_sig) && !"Message" %in% colnames(rv$epistasis_sig) && nrow(rv$epistasis_sig) > 0
191
  has_sel <- !is.null(rv$selection_metrics) && !"Message" %in% colnames(rv$selection_metrics)
192
-
193
- # PVE questions
194
  if (grepl("pve|variance explained|how much variance|percent variance|what is pve", q)) {
195
  if (has_qtl) {
196
  df <- rv$qtl_effects_train
197
  total_pve <- sum(df$PVE_Percent, na.rm = TRUE)
198
  top_pve <- df[which.max(df$PVE_Percent), ]
199
-
200
  response <- paste0(
201
  "\U0001f4ca **PVE (Phenotypic Variance Explained) Analysis**\n\n",
202
  "**Your Results:**\n",
@@ -208,15 +250,15 @@ enhanced_rule_response <- function(user_message, rv) {
208
  "\u2022 PVE: **", round(top_pve$PVE_Percent, 1), "%**\n",
209
  "\u2022 LOD: ", round(top_pve$LOD, 2), "\n\n"
210
  )
211
-
212
  if (top_pve$PVE_Percent > 10) {
213
- response <- paste0(response, "\U0001f4a1 This is a **major-effect QTL** (>10% PVE) - excellent candidate for marker-assisted selection.\n\n")
214
  } else if (top_pve$PVE_Percent > 5) {
215
- response <- paste0(response, "\U0001f4a1 This is a **moderate-effect QTL** (5-10% PVE) - useful for polygenic breeding approaches.\n\n")
216
  } else {
217
- response <- paste0(response, "\U0001f4a1 This is a **minor-effect QTL** (<5% PVE) - typical for complex polygenic traits.\n\n")
218
  }
219
-
220
  response <- paste0(response, "**All QTLs by PVE:**\n")
221
  df_sorted <- df[order(-df$PVE_Percent), ]
222
  for (i in 1:min(5, nrow(df_sorted))) {
@@ -228,56 +270,48 @@ enhanced_rule_response <- function(user_message, rv) {
228
  return("No QTL results yet. Please run the QTL analysis first to see PVE values.")
229
  }
230
  }
231
-
232
- # Model performance questions
233
  if (grepl("model performance|r2|r squared|how good is my model|validation|negative r2", q)) {
234
  if (has_perf) {
235
  pm <- rv$performance_metrics
236
  train_r2 <- pm$Value[pm$Metric == "R\u00b2 (Train)"]
237
  val_r2 <- pm$Value[pm$Metric == "R\u00b2 (Validation)"]
238
-
239
  response <- paste0(
240
  "\U0001f4c8 **Model Performance Summary**\n\n",
241
  "\u2022 Training R\u00b2: **", round(train_r2, 3), "**\n",
242
  "\u2022 Validation R\u00b2: **", round(val_r2, 3), "**\n\n"
243
  )
244
-
245
  if (val_r2 < 0) {
246
  response <- paste0(response,
247
  "\u26a0\ufe0f **Your validation R\u00b2 is negative** (", round(val_r2, 3), ").\n\n",
248
- "This means the model performs worse than simply predicting the mean.\n\n",
249
  "**Common causes:**\n",
250
- "\u2022 **Small sample size** relative to number of markers\n",
251
- "\u2022 **Overfitting** - model learned noise instead of signal\n",
252
- "\u2022 **Population structure** in your data\n\n",
253
  "**Recommendations:**\n",
254
- "1. Increase sample size if possible\n",
255
- "2. Reduce marker number (use feature selection)\n",
256
- "3. Try simpler models or increase cross-validation folds\n",
257
- "4. Focus on individual QTL interpretation rather than prediction\n")
258
  } else if (val_r2 < 0.2) {
259
- response <- paste0(response,
260
- "\U0001f4c9 **Low validation R\u00b2** (<0.2) suggests modest predictive power.\n\n",
261
- "This is common for complex traits. Focus on individual QTL interpretation.\n")
262
  } else if (val_r2 < 0.5) {
263
- response <- paste0(response,
264
- "\U0001f4ca **Moderate validation R\u00b2** (0.2-0.5) - your model has decent predictive ability.\n\n")
265
  } else {
266
- response <- paste0(response,
267
- "\U0001f3af **Excellent validation R\u00b2** (>0.5) - your model has strong predictive power!\n\n")
268
  }
269
  return(response)
270
  } else {
271
  return("Run the QTL analysis first to see model performance metrics.")
272
  }
273
  }
274
-
275
- # Top QTLs question
276
  if (grepl("top qtl|best qtl|highest lod|significant qtl|list qtl|show qtl", q)) {
277
  if (has_qtl) {
278
  df <- rv$qtl_effects_train[order(-rv$qtl_effects_train$LOD), ]
279
  top5 <- head(df, 5)
280
-
281
  response <- "\U0001f3af **Top 5 QTLs by LOD Score**\n\n"
282
  for (i in 1:nrow(top5)) {
283
  row <- top5[i, ]
@@ -285,95 +319,71 @@ enhanced_rule_response <- function(user_message, rv) {
285
  i, ". **", row$Marker, "** (Chr ", row$Chromosome, ")\n",
286
  " \u2022 LOD: **", round(row$LOD, 2), "**\n",
287
  " \u2022 PVE: ", round(row$PVE_Percent, 1), "%\n",
288
- " \u2022 Additive effect: ", round(row$Additive_Effect, 3), "\n")
289
- if (!is.null(row$Low_Flank) && !is.na(row$Low_Flank) && row$Low_Flank != "NA") {
290
- response <- paste0(response, " \u2022 Interval: ", row$Low_Flank, " - ", row$High_Flank, "\n")
291
- }
292
- response <- paste0(response, "\n")
293
  }
294
  return(response)
295
  } else {
296
- return("No significant QTLs detected. Try lowering the LOD threshold or check your data.")
297
  }
298
  }
299
-
300
- # Next steps question
301
  if (grepl("next steps|what next|recommendations|suggest|advice|what should i do", q)) {
302
  if (has_qtl || has_perf || has_epi || has_sel) {
303
  response <- "\U0001f52c **Recommended Next Steps**\n\n"
304
-
305
  if (has_qtl) {
306
  top_qtl <- rv$qtl_effects_train[which.max(rv$qtl_effects_train$LOD), ]
307
  response <- paste0(response,
308
  "**1. Validate Top QTLs**\n",
309
- " \u2022 Prioritize **", top_qtl$Marker, "** (LOD=", round(top_qtl$LOD, 2),
310
- ", PVE=", round(top_qtl$PVE_Percent, 1), "%)\n",
311
- " \u2022 Test in independent population or F2 cross\n",
312
- " \u2022 Use flanking markers for fine-mapping\n\n")
313
  }
314
  if (has_epi) {
315
- n_epi <- nrow(rv$epistasis_sig)
316
- response <- paste0(response,
317
- "**2. Investigate Epistasis**\n",
318
- " \u2022 ", n_epi, " significant interactions detected\n",
319
- " \u2022 Test multi-locus models in breeding programs\n",
320
- " \u2022 Check if interacting QTLs map to same pathways\n\n")
321
  }
322
  if (has_sel) {
323
- n_sel <- sum(rv$selection_metrics$Significant, na.rm = TRUE)
324
- response <- paste0(response,
325
- "**3. Domestication Analysis**\n",
326
- " \u2022 ", n_sel, " markers show selection signatures\n",
327
- " \u2022 Cross-reference with QTL positions\n",
328
- " \u2022 Candidate domestication genes\n\n")
329
  }
330
-
331
  response <- paste0(response,
332
  "**4. Functional Analysis**\n",
333
- " \u2022 Annotate QTL regions for candidate genes\n",
334
- " \u2022 Check gene expression databases\n",
335
- " \u2022 Design validation experiments\n\n",
336
  "**5. Breeding Applications**\n",
337
- " \u2022 Develop markers for MAS\n",
338
- " \u2022 Design crossing schemes\n",
339
- " \u2022 Predict breeding values\n")
340
  return(response)
341
  } else {
342
  return("Run the QTL analysis first to get recommendations.")
343
  }
344
  }
345
-
346
- # Default response
347
  available <- c()
348
  if (has_qtl) available <- c(available, paste(nrow(rv$qtl_effects_train), "QTLs"))
349
  if (has_perf) {
350
- val_r2 <- rv$performance_metrics$Value[rv$performance_metrics$Metric == "R\u00b2 (Validation)"]
351
  available <- c(available, paste0("R\u00b2=", round(val_r2, 3)))
352
  }
353
  if (has_epi) available <- c(available, paste(nrow(rv$epistasis_sig), "interactions"))
354
  if (has_sel) available <- c(available, paste(sum(rv$selection_metrics$Significant), "selection signatures"))
355
-
356
  if (length(available) > 0) {
357
  return(paste0(
358
  "I can see you have: ", paste(available, collapse = ", "), ".\n\n",
359
  "What would you like to know? Try asking about:\n",
360
- "\u2022 **What is PVE?** - Understand variance explained\n",
361
- "\u2022 **Top QTLs** - List most significant markers\n",
362
- "\u2022 **Model performance** - Why is R\u00b2 negative?\n",
363
- "\u2022 **Next steps** - Recommendations for your results"))
364
  }
365
-
366
  return(paste0(
367
  "\U0001f44b Hello! I'm your QTL analysis assistant.\n\n",
368
  "**I can help you with:**\n",
369
- "\u2022 Understanding PVE (variance explained)\n",
370
- "\u2022 Interpreting LOD scores and QTL significance\n",
371
- "\u2022 Evaluating model performance (R\u00b2)\n",
372
  "\u2022 Detecting epistatic interactions\n\n",
373
- "**To get started:**\n",
374
- "1. Upload your genotype and phenotype files\n",
375
- "2. Click 'Run QTL Analysis'\n",
376
- "3. Ask me specific questions!\n\n",
377
  "Try: **'What is PVE?'** or **'Show me my top QTLs'**"))
378
  }
379
 
@@ -381,19 +391,21 @@ enhanced_rule_response <- function(user_message, rv) {
381
  # AI RESPONSE GENERATION
382
  # ============================================================
383
 
384
- generate_ai_response <- function(user_message, rv) {
385
  context <- build_system_prompt(rv)
386
-
387
- if (use_hf_api) {
 
 
388
  prompt <- paste(
389
  "CONTEXT:", context,
390
  "\n\nUSER QUESTION:", user_message,
391
  "\n\nProvide a specific, helpful answer based ONLY on the context above. Be concise but informative.",
392
  sep = "\n"
393
  )
394
-
395
- result <- query_hf_api(prompt)
396
-
397
  if (result$success) {
398
  return(result$text)
399
  } else {
@@ -401,7 +413,7 @@ generate_ai_response <- function(user_message, rv) {
401
  return(enhanced_rule_response(user_message, rv))
402
  }
403
  }
404
-
405
  return(enhanced_rule_response(user_message, rv))
406
  }
407
 
@@ -411,7 +423,7 @@ generate_ai_response <- function(user_message, rv) {
411
 
412
  ui <- fluidPage(
413
  shinyjs::useShinyjs(),
414
-
415
  tags$head(
416
  tags$link(rel = "stylesheet", type = "text/css",
417
  href = "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css"),
@@ -454,6 +466,15 @@ ui <- fluidPage(
454
  $('#send_chat').click();
455
  }
456
  });
 
 
 
 
 
 
 
 
 
457
  ")),
458
  tags$style(HTML("
459
  :root {
@@ -511,22 +532,37 @@ ui <- fluidPage(
511
  .simulation-controls { margin: 12px 0; display: flex; gap: 8px; }
512
  .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; }
513
  .simulation-btn:hover { background-color: var(--purple); color: #0d1117; }
514
- #chat-panel { position: fixed; bottom: 20px; right: 20px; z-index: 9999; width: 420px; display: flex; flex-direction: column; }
 
 
515
  #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; }
516
  #chat-toggle-btn:hover { transform: scale(1.05); box-shadow: 0 6px 24px rgba(88,166,255,0.6); }
517
- #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; }
518
  #chat-window.open { display: flex; }
519
- #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; }
 
520
  .chat-title { display: flex; align-items: center; gap: 10px; }
521
- .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; }
522
  #chat-header h4 { font-family: var(--font-mono); font-size: 13px; font-weight: 600; color: var(--text-primary); margin: 0; }
523
- #chat-header p { font-size: 11px; color: var(--text-muted); margin: 0; font-weight: bold; }
524
  #chat-header p.ai-mode { color: var(--success); }
525
  #chat-header p.rule-mode { color: var(--warning); }
526
- #chat-close-btn { background: none; border: none; color: var(--text-muted); cursor: pointer; font-size: 18px; padding: 4px; transition: color 0.15s; }
527
  #chat-close-btn:hover { color: var(--text-primary); }
 
 
 
 
 
 
 
 
 
 
 
 
528
  #chat_messages { flex: 1; overflow-y: auto; padding: 16px; display: flex; flex-direction: column; gap: 12px; background: var(--bg-primary); }
529
- .chat-msg { max-width: 90%; animation: fadeIn 0.3s ease; }
530
  @keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
531
  .chat-msg.user { align-self: flex-end; }
532
  .chat-msg.assistant { align-self: flex-start; }
@@ -534,33 +570,48 @@ ui <- fluidPage(
534
  .chat-msg.user .chat-bubble { background: linear-gradient(135deg, var(--accent), #3a7bd5); color: #0d1117; border-bottom-right-radius: 4px; }
535
  .chat-msg.assistant .chat-bubble { background: var(--bg-tertiary); color: var(--text-primary); border: 1px solid var(--border); border-bottom-left-radius: 4px; }
536
  .chat-bubble strong { color: var(--accent); }
537
- .chat-bubble em { color: var(--text-secondary); }
538
- .chat-meta { font-size: 10px; color: var(--text-muted); margin-top: 4px; font-family: var(--font-mono); padding: 0 4px; }
539
  .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; }
540
  .typing-dot { width: 8px; height: 8px; background: var(--text-muted); border-radius: 50%; animation: typingBounce 1.4s infinite; }
541
  .typing-dot:nth-child(2) { animation-delay: 0.2s; }
542
  .typing-dot:nth-child(3) { animation-delay: 0.4s; }
543
  @keyframes typingBounce { 0%, 60%, 100% { transform: translateY(0); } 30% { transform: translateY(-8px); } }
544
- #chat-footer { padding: 16px; border-top: 1px solid var(--border); background: var(--bg-tertiary); }
 
 
 
 
 
 
 
545
  #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; }
546
  #chat_input:focus { border-color: var(--accent) !important; outline: none; }
 
 
 
 
 
 
 
 
547
  .chat-actions { display: flex; gap: 8px; }
548
  #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; }
549
  #send_chat:hover:not(:disabled) { transform: translateY(-1px); box-shadow: 0 4px 12px rgba(88,166,255,0.4); }
550
  #send_chat:disabled { opacity: 0.5; cursor: not-allowed; }
551
  #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; }
552
  #clear_chat:hover { border-color: var(--danger); color: var(--danger); }
553
- .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; }
554
- .quick-questions { padding: 8px 16px; display: flex; flex-wrap: wrap; gap: 6px; border-bottom: 1px solid var(--border); }
555
- .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; }
556
- .quick-q-btn:hover { border-color: var(--accent); color: var(--accent); background: rgba(88,166,255,0.1); }
557
  "))
558
  ),
559
-
560
  navbarPage(
561
  title = tags$span(tags$i(class = "fas fa-dna", style = "margin-right:8px; color:#58a6ff;"), "QTL-Mapper AI"),
562
  id = "nav",
563
-
564
  # ---- Data Upload tab ----
565
  tabPanel("Data Upload", icon = icon("upload"),
566
  div(class = "main-header",
@@ -618,7 +669,7 @@ ui <- fluidPage(
618
  )
619
  )
620
  ),
621
-
622
  # ---- Domestication tab ----
623
  tabPanel("Domestication", icon = icon("leaf"),
624
  div(class = "main-header",
@@ -632,8 +683,8 @@ ui <- fluidPage(
632
  div(class = "card-body",
633
  fileInput("pop_file", "Population Metadata CSV", accept = ".csv", buttonLabel = "Browse"),
634
  helpText("CSV with 'id' and 'population' columns (e.g., Domesticated, Wild)."),
635
- numericInput("fst_threshold", "Fst Threshold", value = 0.1, min = 0.05, max = 0.5, step = 0.01),
636
- numericInput("tajima_threshold", "Tajima's D Threshold", value = -1, min = -5, max = 0, step = 0.1),
637
  actionButton("run_domestication", "Run Domestication Analysis", class = "btn-primary btn-block", icon = icon("play"))
638
  )
639
  )
@@ -646,7 +697,7 @@ ui <- fluidPage(
646
  )
647
  ),
648
  fluidRow(
649
- column(6, div(class = "card", div(class = "card-header", "Fst Manhattan Plot"), div(class = "card-body", plotlyOutput("fst_plot", height = "400px")))),
650
  column(6, div(class = "card", div(class = "card-header", "Tajima's D Manhattan Plot"), div(class = "card-body", plotlyOutput("tajima_plot", height = "400px"))))
651
  ),
652
  fluidRow(
@@ -662,7 +713,7 @@ ui <- fluidPage(
662
  )
663
  )
664
  ),
665
-
666
  # ---- Results tab ----
667
  tabPanel("Results", icon = icon("chart-line"),
668
  div(class = "main-header",
@@ -683,9 +734,9 @@ ui <- fluidPage(
683
  ))
684
  ),
685
  fluidRow(
686
- column(4, div(class = "card", div(class = "card-header", "Model Performance"), div(class = "card-body", plotlyOutput("performance_plot")))),
687
- column(4, div(class = "card", div(class = "card-header", "Train: Predicted vs Observed"), div(class = "card-body", plotlyOutput("regression_plot_train", height = "300px")))),
688
- column(4, div(class = "card", div(class = "card-header", "Validation: Predicted vs Observed"), div(class = "card-body", plotlyOutput("regression_plot_test", height = "300px"))))
689
  ),
690
  fluidRow(
691
  column(12, div(class = "card",
@@ -703,7 +754,7 @@ ui <- fluidPage(
703
  ))
704
  )
705
  ),
706
-
707
  # ---- Interpretation tab ----
708
  tabPanel("Interpretation", icon = icon("lightbulb"),
709
  div(class = "main-header",
@@ -715,15 +766,15 @@ ui <- fluidPage(
715
  column(6, div(class = "card", div(class = "card-header", "QTL Significance"), div(class = "card-body", uiOutput("qtl_interpretation")))),
716
  column(6, div(class = "card", div(class = "card-header", "Effect Sizes"), div(class = "card-body", uiOutput("effect_interpretation"))))
717
  ),
718
- fluidRow(column(12, div(class = "card", div(class = "card-header", "Epistasis"), div(class = "card-body", uiOutput("epistasis_interpretation"))))),
719
- fluidRow(column(12, div(class = "card", div(class = "card-header", "Recommendations"), div(class = "card-body", uiOutput("recommendations")))))
720
  ),
721
-
722
  # ---- About tab ----
723
  tabPanel("About", icon = icon("info-circle"),
724
  div(class = "main-header",
725
  h2(tags$i(class = "fas fa-info-circle", style = "margin-right:8px;"), "About QTL-Mapper AI"),
726
- p("QTL Mapping with Transformer-based AI Assistant")
727
  ),
728
  fluidRow(
729
  column(8, offset = 2,
@@ -736,12 +787,29 @@ ui <- fluidPage(
736
  tags$li("Additive and dominance effects estimated via linear regression"),
737
  tags$li("Epistasis analysis: pairwise QTL x marker interactions"),
738
  tags$li("Domestication: Fst, nucleotide diversity (Pi), Tajima's D"),
739
- tags$li("AI Assistant powered by transformer models via Hugging Face Inference API")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
740
  ),
741
  h4(style = "color:#58a6ff; font-family:'IBM Plex Mono'; margin:12px 0;", "AI Assistant Status"),
742
- p(style = "color:#8b949e; line-height:1.7;",
743
- if (use_hf_api) paste("Connected to Hugging Face API using", hf_model)
744
- else "AI Assistant is in rule-based mode. Set HF_API_TOKEN in Space secrets to enable transformer-based responses."
745
  ),
746
  h4(style = "color:#58a6ff; font-family:'IBM Plex Mono'; margin:12px 0;", "Interpretation Thresholds"),
747
  tags$ul(style = "color:#8b949e; line-height:2;",
@@ -756,47 +824,104 @@ ui <- fluidPage(
756
  )
757
  )
758
  ),
759
-
760
- # ---- Floating Chat Panel ----
 
 
761
  tags$div(id = "chat-panel",
762
  tags$div(id = "chat-window",
 
 
763
  tags$div(id = "chat-header",
764
- tags$div(class = "chat-title",
765
- tags$div(class = "chat-avatar", "AI"),
766
- tags$div(
767
- tags$h4("QTL Analysis AI Assistant",
768
- tags$span(class = "model-badge",
769
- if (use_hf_api) gsub(".*/", "", hf_model) else "rules")
770
- ),
771
- tags$p(id = "model_status",
772
- if (use_hf_api) paste("AI mode -", gsub(".*/", "", hf_model)) else "Rule-based mode",
773
- class = if (use_hf_api) "ai-mode" else "rule-mode"
774
- )
775
- )
 
776
  ),
777
- tags$button(id = "chat-close-btn",
778
- onclick = "document.getElementById('chat-window').classList.remove('open');",
779
- tags$i(class = "fas fa-times"))
 
 
 
 
 
 
 
 
780
  ),
 
 
781
  tags$div(class = "quick-questions",
782
- tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q','What is PVE?',{priority:'event'});", "PVE meaning"),
783
- tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q','What are my top QTLs?',{priority:'event'});", "Top QTLs"),
784
- tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q','Why is my R2 negative?',{priority:'event'});", "Negative R2"),
785
- tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q','What should I do next?',{priority:'event'});", "Next steps")
786
  ),
 
 
787
  tags$div(id = "chat_messages", uiOutput("chat_display")),
 
 
788
  tags$div(id = "chat-footer",
789
- tags$textarea(id = "chat_input", placeholder = "Ask about your results... (Enter to send)", rows = "2"),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
790
  tags$div(class = "chat-actions",
791
  actionButton("send_chat", "Send", icon = icon("paper-plane"), class = "btn-primary"),
792
  actionButton("clear_chat", "Clear", icon = icon("trash-alt"), class = "btn-danger")
793
  )
794
  )
795
  ),
 
 
796
  tags$button(id = "chat-toggle-btn",
797
  onclick = "document.getElementById('chat-window').classList.toggle('open');",
798
  tags$i(class = "fas fa-robot"))
799
- )
 
 
 
 
 
 
 
 
 
 
 
 
800
  )
801
 
802
  # ============================================================
@@ -804,106 +929,202 @@ ui <- fluidPage(
804
  # ============================================================
805
 
806
  server <- function(input, output, session) {
807
-
808
  values <- reactiveValues(
809
- genotype_data = NULL,
810
- phenotype_data = NULL,
811
- test_genotype_data = NULL,
812
- predicted_test_phenotype_data = NULL,
813
- chromosome_info = NULL,
814
- position_info = NULL,
815
- all_markers = NULL,
816
- importance_scores = NULL,
817
- lod_scores_train = NULL,
818
- model_fit = NULL,
819
- phenotype_values = NULL,
820
- qtl_effects_train = NULL,
821
- qtl_effects_test = NULL,
822
- performance_metrics = NULL,
823
- train_predictions = NULL,
824
- test_predictions = NULL,
825
- epistasis_all = NULL,
826
- epistasis_sig = NULL,
827
- pop_data = NULL,
828
- selection_metrics = NULL,
829
- has_test_data = FALSE,
830
- chat_messages = list(),
831
- is_typing = FALSE,
832
- lod_threshold = 2,
833
- use_ai = use_hf_api
 
 
 
834
  )
835
-
 
836
  observe({
837
- if (values$use_ai) {
838
- shinyjs::html("model_status", paste("AI mode -", gsub(".*/", "", hf_model)))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
839
  } else {
840
- shinyjs::html("model_status", "Rule-based mode")
 
 
841
  }
842
  })
843
-
844
  # ---- Chat helpers ----
845
- add_message <- function(role, content) {
846
  timestamp <- format(Sys.time(), "%H:%M")
847
  values$chat_messages <- c(values$chat_messages,
848
- list(list(role = role, content = content, time = timestamp)))
849
- if (length(values$chat_messages) > 50)
850
- values$chat_messages <- tail(values$chat_messages, 50)
 
851
  session$sendCustomMessage("scrollChatBottom", list())
852
  }
853
-
854
- process_message <- function(user_text) {
855
- if (nchar(trimws(user_text)) == 0) return()
856
- add_message("user", user_text)
 
 
 
 
 
 
 
 
 
 
 
857
  values$is_typing <- TRUE
858
- response <- generate_ai_response(user_text, values)
 
 
 
859
  values$is_typing <- FALSE
860
- add_message("assistant", response)
 
 
 
 
 
861
  }
862
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
863
  observeEvent(input$send_chat, {
864
- req(input$chat_input)
865
  user_text <- trimws(input$chat_input)
866
- if (nchar(user_text) == 0) return()
 
 
 
 
867
  updateTextAreaInput(session, "chat_input", value = "")
868
- process_message(user_text)
 
 
 
 
 
 
869
  })
870
-
871
  observeEvent(input$quick_q, { req(input$quick_q); process_message(input$quick_q) })
872
-
873
  observeEvent(input$clear_chat, {
874
  values$chat_messages <- list()
875
  add_message("assistant", "Chat cleared. How can I help?")
876
  })
877
-
 
878
  observe({
879
  if (length(values$chat_messages) == 0) {
880
- mode_msg <- if (values$use_ai) {
881
- paste("I'm using the", gsub(".*/", "", hf_model), "model via Hugging Face API!")
 
882
  } else {
883
- "I'm using rule-based responses. To enable AI mode, set HF_API_TOKEN in Space secrets."
884
  }
885
- add_message("assistant", paste(
886
- "\U0001f44b Hello! I'm your QTL analysis assistant.", mode_msg,
887
- "\n\n**I can help you with:**",
888
- "\u2022 **What is PVE?** - Understand variance explained",
889
- "\u2022 **Show top QTLs** - List your most significant markers",
890
- "\u2022 **Model performance** - Why is my R\u00b2 negative?",
891
- "\u2022 **Next steps** - Recommendations",
892
- "\nTry asking: **'What is PVE?'**"))
 
 
 
893
  }
894
  })
895
-
 
896
  output$chat_display <- renderUI({
897
  messages <- values$chat_messages
898
  if (length(messages) == 0) return(NULL)
899
-
900
  elems <- lapply(messages, function(msg) {
 
 
 
 
 
 
 
 
901
  div(class = paste("chat-msg", msg$role),
902
- div(class = "chat-bubble",
903
- HTML(gsub("\n", "<br>", htmltools::htmlEscape(msg$content)))),
904
- div(class = "chat-meta", msg$time))
905
  })
906
-
907
  if (values$is_typing) {
908
  elems <- c(elems, list(
909
  div(class = "chat-msg assistant",
@@ -912,61 +1133,64 @@ server <- function(input, output, session) {
912
  }
913
  do.call(tagList, elems)
914
  })
915
-
916
- # ---- Data loading ----
 
 
 
917
  observeEvent(input$genotype_file, {
918
  req(input$genotype_file)
919
  tryCatch({
920
  all_data <- readLines(input$genotype_file$datapath)
921
  if (length(all_data) < 4) { showNotification("Genotype file must have at least 4 rows", type = "error"); return() }
922
-
923
  header <- strsplit(all_data[1], ",")[[1]]
924
  chromosome_row <- strsplit(all_data[2], ",")[[1]]
925
  position_row <- strsplit(all_data[3], ",")[[1]]
926
-
927
  genotype_data <- read.csv(text = all_data[-(1:3)], header = FALSE)
928
  colnames(genotype_data) <- header
929
  rownames(genotype_data) <- genotype_data[, 1]
930
  genotype_data <- genotype_data[, -1]
931
-
932
  for (col in colnames(genotype_data))
933
  genotype_data[[col]] <- as.numeric(as.character(genotype_data[[col]]))
934
-
935
  values$all_markers <- data.frame(
936
  Marker = colnames(genotype_data),
937
  Chromosome = chromosome_row[-1],
938
  Position = as.numeric(position_row[-1]),
939
  stringsAsFactors = FALSE)
940
-
941
- values$genotype_data <- genotype_data
942
- values$chromosome_info <- chromosome_row[-1]
943
- values$position_info <- as.numeric(position_row[-1])
944
-
945
  showNotification("Genotype data loaded", type = "message")
946
- add_message("assistant", paste0("\u2705 Loaded ", ncol(genotype_data), " markers, ", nrow(genotype_data), " samples"))
947
  }, error = function(e) showNotification(paste("Error:", e$message), type = "error"))
948
  })
949
-
950
  observeEvent(input$phenotype_file, {
951
  req(input$phenotype_file)
952
  tryCatch({
953
  phenotype_data <- read.csv(input$phenotype_file$datapath)
954
  rownames(phenotype_data) <- phenotype_data[, 1]
955
  phenotype_data <- phenotype_data[, -1]
956
-
957
  for (col in colnames(phenotype_data))
958
  phenotype_data[[col]] <- as.numeric(as.character(phenotype_data[[col]]))
959
-
960
  values$phenotype_data <- phenotype_data
961
  updateSelectInput(session, "phenotype_column",
962
  choices = colnames(phenotype_data),
963
  selected = colnames(phenotype_data)[1])
964
-
965
  showNotification("Phenotype data loaded", type = "message")
966
- add_message("assistant", paste0("\u2705 Loaded ", ncol(phenotype_data), " traits, ", nrow(phenotype_data), " samples"))
967
  }, error = function(e) showNotification(paste("Error:", e$message), type = "error"))
968
  })
969
-
970
  observeEvent(input$pop_file, {
971
  req(input$pop_file)
972
  tryCatch({
@@ -979,52 +1203,55 @@ server <- function(input, output, session) {
979
  add_message("assistant", paste0("\u2705 Loaded population data (", nrow(pop_data), " samples)"))
980
  }, error = function(e) showNotification(paste("Error:", e$message), type = "error"))
981
  })
982
-
983
  observeEvent(input$test_genotype_file, {
984
  req(input$test_genotype_file)
985
  tryCatch({
986
- all_data <- readLines(input$test_genotype_file$datapath)
987
- header <- strsplit(all_data[1], ",")[[1]]
988
-
989
- genotype_data <- read.csv(text = all_data[-(1:3)], header = FALSE)
990
  colnames(genotype_data) <- header
991
  rownames(genotype_data) <- genotype_data[, 1]
992
  genotype_data <- genotype_data[, -1]
993
-
994
  for (col in colnames(genotype_data))
995
  genotype_data[[col]] <- as.numeric(as.character(genotype_data[[col]]))
996
-
997
  values$test_genotype_data <- genotype_data
998
  values$has_test_data <- TRUE
999
  showNotification("Test genotype data loaded", type = "message")
1000
  }, error = function(e) showNotification(paste("Error:", e$message), type = "error"))
1001
  })
1002
-
1003
  # ---- Data previews ----
1004
  output$geno_preview <- renderDT({ req(input$genotype_file); datatable(head(read.csv(input$genotype_file$datapath), 10), options = list(scrollX = TRUE, pageLength = 5)) })
1005
  output$pheno_preview <- renderDT({ req(input$phenotype_file); datatable(head(read.csv(input$phenotype_file$datapath), 10), options = list(scrollX = TRUE, pageLength = 5)) })
1006
  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)) })
1007
  output$pop_preview <- renderDT({ req(input$pop_file); datatable(head(read.csv(input$pop_file$datapath), 10), options = list(scrollX = TRUE, pageLength = 5)) })
1008
  output$predicted_test_pheno_preview <- renderDT({ req(values$predicted_test_phenotype_data); datatable(values$predicted_test_phenotype_data, options = list(scrollX = TRUE, pageLength = 5)) })
1009
-
1010
- # ---- QTL effect calculation ----
 
 
 
1011
  calculate_qtl_effects <- function(genotype_matrix, phenotype_vector, marker_names) {
1012
  effects_list <- list()
1013
-
1014
  for (marker in marker_names) {
1015
  if (!marker %in% colnames(genotype_matrix)) next
1016
-
1017
  geno <- genotype_matrix[, marker]
1018
  pheno <- phenotype_vector
1019
  valid_idx <- !is.na(geno) & !is.na(pheno)
1020
  geno <- geno[valid_idx]
1021
  pheno <- pheno[valid_idx]
1022
-
1023
  if (length(unique(geno)) < 2) next
1024
-
1025
  lm_fit <- lm(pheno ~ geno)
1026
  additive_effect <- coef(lm_fit)[2]
1027
-
1028
  dominance_effect <- NA
1029
  if (length(unique(geno)) == 3) {
1030
  geno_means <- tapply(pheno, geno, mean, na.rm = TRUE)
@@ -1033,10 +1260,10 @@ server <- function(input, output, session) {
1033
  geno_means[as.character(sort(unique(geno))[3])]) / 2
1034
  dominance_effect <- het_mean - midparent
1035
  }
1036
-
1037
  r_squared <- summary(lm_fit)$r.squared
1038
  se_additive <- tryCatch(summary(lm_fit)$coefficients[2, 2], error = function(e) NA)
1039
-
1040
  effects_list[[marker]] <- data.frame(
1041
  Marker = marker,
1042
  Additive_Effect = additive_effect,
@@ -1048,37 +1275,40 @@ server <- function(input, output, session) {
1048
  N_Samples = length(pheno),
1049
  stringsAsFactors = FALSE)
1050
  }
1051
-
1052
  if (length(effects_list) == 0) return(NULL)
1053
  do.call(rbind, effects_list)
1054
  }
1055
-
1056
- # ---- Main QTL analysis ----
 
 
 
1057
  observeEvent(input$run_analysis, {
1058
  req(values$genotype_data, values$phenotype_data, input$phenotype_column)
1059
  showNotification("Starting QTL analysis...", type = "message")
1060
  values$lod_threshold <- input$lod_threshold
1061
-
1062
  tryCatch({
1063
  common_samples <- intersect(rownames(values$genotype_data), rownames(values$phenotype_data))
1064
  if (length(common_samples) == 0) { showNotification("No common samples", type = "error"); return() }
1065
-
1066
  X <- values$genotype_data[common_samples, , drop = FALSE]
1067
  y <- as.numeric(values$phenotype_data[common_samples, input$phenotype_column])
1068
  nzv <- nearZeroVar(X)
1069
  if (length(nzv) > 0) X <- X[, -nzv, drop = FALSE]
1070
-
1071
  set.seed(123)
1072
  train_index <- createDataPartition(y, p = 1 - input$test_size, list = FALSE)
1073
  X_train <- X[train_index, , drop = FALSE]; X_val <- X[-train_index, , drop = FALSE]
1074
  y_train <- y[train_index]; y_val <- y[-train_index]
1075
-
1076
  model <- train(x = X_train, y = y_train, method = "rf",
1077
  trControl = trainControl(method = "cv", number = 5),
1078
  importance = TRUE, tuneLength = 3)
1079
-
1080
  values$model_fit <- model
1081
-
1082
  imp <- varImp(model, scale = FALSE)$importance
1083
  importance_scores <- data.frame(
1084
  Marker = rownames(imp),
@@ -1086,14 +1316,14 @@ server <- function(input, output, session) {
1086
  Chromosome = values$chromosome_info[match(rownames(imp), colnames(X))],
1087
  Position = as.numeric(values$position_info[match(rownames(imp), colnames(X))]),
1088
  stringsAsFactors = FALSE)
1089
-
1090
  values$importance_scores <- importance_scores
1091
  lod_sig <- importance_scores[importance_scores$LOD > input$lod_threshold, , drop = FALSE]
1092
-
1093
  if (nrow(lod_sig) > 0) {
1094
  lod_sig$Low_Flank <- NA
1095
  lod_sig$High_Flank <- NA
1096
-
1097
  for (i in 1:nrow(lod_sig)) {
1098
  chr_m <- values$all_markers[values$all_markers$Chromosome == lod_sig$Chromosome[i], ]
1099
  chr_m <- chr_m[order(chr_m$Position), ]
@@ -1103,10 +1333,10 @@ server <- function(input, output, session) {
1103
  lod_sig$High_Flank[i] <- if (idx < nrow(chr_m)) chr_m$Marker[idx + 1] else lod_sig$Marker[i]
1104
  }
1105
  }
1106
-
1107
  values$lod_scores_train <- lod_sig
1108
  qtl_fx <- calculate_qtl_effects(X_train, y_train, lod_sig$Marker)
1109
-
1110
  if (!is.null(qtl_fx)) {
1111
  values$qtl_effects_train <- merge(lod_sig, qtl_fx, by = "Marker")
1112
  } else {
@@ -1116,26 +1346,26 @@ server <- function(input, output, session) {
1116
  values$lod_scores_train <- data.frame(Message = paste("No QTLs above LOD", input$lod_threshold))
1117
  values$qtl_effects_train <- data.frame(Message = paste("No QTLs above LOD", input$lod_threshold))
1118
  }
1119
-
1120
  y_train_pred <- predict(model, X_train)
1121
  y_val_pred <- predict(model, X_val)
1122
  train_r2 <- 1 - sum((y_train - y_train_pred)^2) / sum((y_train - mean(y_train))^2)
1123
  val_r2 <- 1 - sum((y_val - y_val_pred)^2) / sum((y_val - mean(y_val))^2)
1124
-
1125
  values$performance_metrics <- data.frame(
1126
  Metric = c("R\u00b2 (Train)", "R (Train)", "R\u00b2 (Validation)", "R (Validation)"),
1127
  Value = c(train_r2, cor(y_train, y_train_pred), val_r2, cor(y_val, y_val_pred)),
1128
  stringsAsFactors = FALSE)
1129
-
1130
  values$train_predictions <- data.frame(Observed = y_train, Predicted = y_train_pred)
1131
  values$test_predictions <- data.frame(Observed = y_val, Predicted = y_val_pred)
1132
-
1133
  # Epistasis
1134
  if (nrow(lod_sig) > 0) {
1135
  sig_markers <- lod_sig$Marker[lod_sig$Marker %in% colnames(X_train)]
1136
  all_markers_v <- colnames(X_train)
1137
  epistasis_list <- list()
1138
-
1139
  withProgress(message = "Calculating epistasis...", value = 0, {
1140
  total <- length(sig_markers) * length(all_markers_v)
1141
  for (m1 in sig_markers) {
@@ -1159,57 +1389,64 @@ server <- function(input, output, session) {
1159
  }
1160
  }
1161
  })
1162
-
1163
  if (length(epistasis_list) > 0) {
1164
- epistasis_all <- do.call(rbind, epistasis_list)
1165
- values$epistasis_all <- epistasis_all
1166
- values$epistasis_sig <- epistasis_all[epistasis_all$Interaction_p < 0.05, ]
1167
  } else {
1168
  values$epistasis_all <- data.frame(Message = "No epistatic interactions")
1169
  values$epistasis_sig <- data.frame(Message = "No epistatic interactions")
1170
  }
1171
  }
1172
-
1173
  showNotification("QTL analysis completed!", type = "message")
1174
  n_qtl <- if (!is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train)) nrow(values$qtl_effects_train) else 0
1175
- 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!"))
 
 
 
 
1176
  updateTabsetPanel(session, "nav", selected = "Results")
1177
-
1178
  }, error = function(e) showNotification(paste("Error:", e$message), type = "error"))
1179
  })
1180
-
1181
- # ---- Domestication analysis ----
 
 
 
1182
  calculate_selection_metrics <- function(genotype_matrix, pop_data, marker_info) {
1183
  metrics_list <- list()
1184
-
1185
  for (marker in colnames(genotype_matrix)) {
1186
  geno <- genotype_matrix[, marker]
1187
  pop <- pop_data$population[match(rownames(genotype_matrix), pop_data$id)]
1188
  valid_idx <- !is.na(geno) & !is.na(pop)
1189
  geno <- geno[valid_idx]; pop <- pop[valid_idx]
1190
-
1191
  if (length(unique(pop)) < 2) next
1192
- geno_dom <- geno[pop == "Domesticated"]
1193
  geno_wild <- geno[pop == "Wild"]
1194
  if (length(geno_dom) < 3 || length(geno_wild) < 3) next
1195
-
1196
- freq_dom <- mean(geno_dom, na.rm = TRUE) / 2
1197
  freq_wild <- mean(geno_wild, na.rm = TRUE) / 2
1198
- p_avg <- (freq_dom + freq_wild) / 2
1199
-
1200
  fst <- if (p_avg > 0 && p_avg < 1) {
1201
  f <- (freq_dom - freq_wild)^2 / (p_avg * (1 - p_avg))
1202
  f / (1 + f)
1203
  } else 0
1204
-
1205
  pi_dom <- 2 * freq_dom * (1 - freq_dom)
1206
  pi_wild <- 2 * freq_wild * (1 - freq_wild)
1207
  n_dom <- length(geno_dom)
1208
  n_wild <- length(geno_wild)
1209
-
1210
  tajima_d_dom <- (pi_dom - 1/n_dom) / sqrt(var(geno_dom) /n_dom)
1211
  tajima_d_wild <- (pi_wild - 1/n_wild) / sqrt(var(geno_wild)/n_wild)
1212
-
1213
  marker_row <- marker_info[marker_info$Marker == marker, ]
1214
  metrics_list[[marker]] <- data.frame(
1215
  Marker = marker,
@@ -1219,65 +1456,71 @@ server <- function(input, output, session) {
1219
  Tajima_D_Dom = tajima_d_dom, Tajima_D_Wild = tajima_d_wild,
1220
  stringsAsFactors = FALSE)
1221
  }
1222
-
1223
  if (length(metrics_list) == 0) return(NULL)
1224
  do.call(rbind, metrics_list)
1225
  }
1226
-
1227
  observeEvent(input$run_domestication, {
1228
  req(values$genotype_data, values$pop_data, values$all_markers)
1229
  tryCatch({
1230
  common_samples <- intersect(rownames(values$genotype_data), values$pop_data$id)
1231
  if (length(common_samples) == 0) { showNotification("No common samples", type = "error"); return() }
1232
-
1233
  X <- values$genotype_data[common_samples, , drop = FALSE]
1234
  pop_subset <- values$pop_data[values$pop_data$id %in% common_samples, ]
1235
  sel_metrics <- calculate_selection_metrics(X, pop_subset, values$all_markers)
1236
-
1237
  if (is.null(sel_metrics)) { showNotification("Could not calculate selection metrics", type = "error"); return() }
1238
-
1239
  sel_metrics$Significant <-
1240
  sel_metrics$Fst > input$fst_threshold |
1241
  sel_metrics$Tajima_D_Dom < input$tajima_threshold |
1242
  sel_metrics$Tajima_D_Wild < input$tajima_threshold
1243
-
1244
  values$selection_metrics <- sel_metrics
1245
  showNotification("Domestication analysis completed!", type = "message")
1246
  n_sig <- sum(sel_metrics$Significant, na.rm = TRUE)
1247
- add_message("assistant", paste("\u2705 Domestication analysis complete!", paste0("\u2022 Found ", n_sig, " markers with selection signatures")))
1248
  }, error = function(e) showNotification(paste("Error:", e$message), type = "error"))
1249
  })
1250
-
1251
- # ---- Predict test phenotypes ----
 
 
 
1252
  observeEvent(input$predict_test_phenotype, {
1253
  req(values$model_fit, values$test_genotype_data)
1254
  tryCatch({
1255
  common_markers <- intersect(colnames(values$test_genotype_data), colnames(values$genotype_data))
1256
  if (length(common_markers) == 0) { showNotification("No common markers", type = "error"); return() }
1257
-
1258
  X_test <- values$test_genotype_data[, common_markers, drop = FALSE]
1259
  predictions <- predict(values$model_fit, newdata = X_test)
1260
-
1261
  values$predicted_test_phenotype_data <- data.frame(
1262
  id = rownames(X_test),
1263
  Predicted_Phenotype = as.numeric(predictions),
1264
  stringsAsFactors = FALSE)
1265
-
1266
  showNotification("Predictions completed!", type = "message")
1267
  }, error = function(e) showNotification(paste("Error:", e$message), type = "error"))
1268
  })
1269
-
1270
- # ---- Manhattan plot helper ----
 
 
 
1271
  create_manhattan <- function(data, y_col, title, threshold, y_label = y_col) {
1272
  if (is.null(data) || nrow(data) == 0 || "Message" %in% colnames(data))
1273
  return(plot_ly() %>% layout(title = "No data available",
1274
  plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e")))
1275
-
1276
  plot_data <- data[!is.na(data[[y_col]]), ]
1277
  if (nrow(plot_data) == 0)
1278
  return(plot_ly() %>% layout(title = "No valid data",
1279
  plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e")))
1280
-
1281
  chroms <- unique(plot_data$Chromosome)
1282
  chrom_pos <- data.frame()
1283
  for (i in seq_along(chroms)) {
@@ -1288,7 +1531,7 @@ server <- function(input, output, session) {
1288
  chrom_pos <- rbind(chrom_pos, chr_data)
1289
  }
1290
  }
1291
-
1292
  p <- plot_ly() %>%
1293
  add_trace(data = chrom_pos, x = ~PosScaled, y = as.formula(paste0("~", y_col)),
1294
  type = "scatter", mode = "markers", color = ~factor(Chromosome),
@@ -1296,13 +1539,13 @@ server <- function(input, output, session) {
1296
  text = ~paste("Marker:", Marker, "<br>Chr:", Chromosome, "<br>Pos:", Position,
1297
  "<br>", y_label, ":", round(get(y_col), 3)),
1298
  hoverinfo = "text", showlegend = FALSE)
1299
-
1300
  if (!is.null(threshold) && !is.na(threshold))
1301
  p <- p %>% add_segments(
1302
  x = min(chrom_pos$PosScaled, na.rm = TRUE), xend = max(chrom_pos$PosScaled, na.rm = TRUE),
1303
  y = threshold, yend = threshold,
1304
  line = list(color = "red", dash = "dash", width = 1), name = "Threshold")
1305
-
1306
  p %>% layout(title = title,
1307
  xaxis = list(title = "Chromosome",
1308
  ticktext = chroms,
@@ -1311,23 +1554,26 @@ server <- function(input, output, session) {
1311
  yaxis = list(title = y_label),
1312
  plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))
1313
  }
1314
-
1315
- # ---- Plots ----
 
 
 
1316
  output$lod_plot_2d <- renderPlotly({
1317
  req(values$importance_scores)
1318
  create_manhattan(values$importance_scores, "LOD", "QTL Manhattan Plot", input$lod_threshold, "LOD Score")
1319
  })
1320
-
1321
  output$fst_plot <- renderPlotly({
1322
  req(values$selection_metrics)
1323
  create_manhattan(values$selection_metrics, "Fst", "Fst Manhattan Plot", input$fst_threshold, "Fst")
1324
  })
1325
-
1326
  output$tajima_plot <- renderPlotly({
1327
  req(values$selection_metrics)
1328
  if ("Message" %in% colnames(values$selection_metrics))
1329
  return(plot_ly() %>% layout(title = "No data available", plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e")))
1330
-
1331
  data <- values$selection_metrics
1332
  chroms <- unique(data$Chromosome)
1333
  chrom_pos <- data.frame()
@@ -1339,7 +1585,7 @@ server <- function(input, output, session) {
1339
  chrom_pos <- rbind(chrom_pos, chr_data)
1340
  }
1341
  }
1342
-
1343
  plot_ly() %>%
1344
  add_trace(data = chrom_pos, x = ~PosScaled, y = ~Tajima_D_Dom, type = "scatter", mode = "markers",
1345
  name = "Domesticated", marker = list(size = 5, color = "#58a6ff", opacity = 0.7),
@@ -1358,7 +1604,7 @@ server <- function(input, output, session) {
1358
  yaxis = list(title = "Tajima's D"),
1359
  plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))
1360
  })
1361
-
1362
  output$performance_plot <- renderPlotly({
1363
  req(values$performance_metrics)
1364
  plot_ly(data = values$performance_metrics, x = ~Metric, y = ~Value, type = "bar",
@@ -1368,7 +1614,7 @@ server <- function(input, output, session) {
1368
  yaxis = list(title = "Value", range = c(0, 1.1)),
1369
  plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))
1370
  })
1371
-
1372
  output$regression_plot_train <- renderPlotly({
1373
  req(values$train_predictions)
1374
  plot_ly(data = values$train_predictions, x = ~Observed, y = ~Predicted,
@@ -1378,7 +1624,7 @@ server <- function(input, output, session) {
1378
  layout(title = "Training Set", xaxis = list(title = "Observed"), yaxis = list(title = "Predicted"),
1379
  plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))
1380
  })
1381
-
1382
  output$regression_plot_test <- renderPlotly({
1383
  req(values$test_predictions)
1384
  plot_ly(data = values$test_predictions, x = ~Observed, y = ~Predicted,
@@ -1388,13 +1634,13 @@ server <- function(input, output, session) {
1388
  layout(title = "Validation Set", xaxis = list(title = "Observed"), yaxis = list(title = "Predicted"),
1389
  plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))
1390
  })
1391
-
1392
  output$epistasis_heatmap <- renderPlotly({
1393
  req(values$epistasis_all)
1394
  if ("Message" %in% colnames(values$epistasis_all))
1395
  return(plot_ly() %>% layout(title = values$epistasis_all$Message[1],
1396
  plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e")))
1397
-
1398
  qtls <- unique(values$epistasis_all$QTL1)
1399
  markers <- unique(values$epistasis_all$QTL2)
1400
  p_mat <- matrix(NA, nrow = length(qtls), ncol = length(markers),
@@ -1402,7 +1648,7 @@ server <- function(input, output, session) {
1402
  for (i in 1:nrow(values$epistasis_all))
1403
  p_mat[values$epistasis_all$QTL1[i], values$epistasis_all$QTL2[i]] <-
1404
  -log10(values$epistasis_all$Interaction_p[i])
1405
-
1406
  plot_ly(x = colnames(p_mat), y = rownames(p_mat), z = p_mat,
1407
  type = "heatmap", colorscale = "Viridis",
1408
  hovertemplate = "QTL: %{y}<br>Marker: %{x}<br>-log10(p): %{z:.2f}") %>%
@@ -1410,13 +1656,16 @@ server <- function(input, output, session) {
1410
  xaxis = list(title = "Marker", tickangle = 45), yaxis = list(title = "QTL"),
1411
  plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))
1412
  })
1413
-
1414
- # ---- Tables ----
 
 
 
1415
  output$qtl_effects_table_train <- renderDT({
1416
  req(values$qtl_effects_train)
1417
  if ("Message" %in% colnames(values$qtl_effects_train))
1418
  return(datatable(data.frame(Status = values$qtl_effects_train$Message[1]), options = list(dom = "t")))
1419
-
1420
  display_cols <- intersect(
1421
  c("Marker", "Chromosome", "Position", "LOD", "Additive_Effect", "PVE_Percent", "Low_Flank", "High_Flank"),
1422
  colnames(values$qtl_effects_train))
@@ -1424,7 +1673,7 @@ server <- function(input, output, session) {
1424
  datatable(df, options = list(pageLength = 10, scrollX = TRUE), rownames = FALSE) %>%
1425
  formatRound(intersect(c("LOD", "Additive_Effect", "PVE_Percent"), colnames(df)), 3)
1426
  })
1427
-
1428
  output$epistasis_table <- renderDT({
1429
  req(values$epistasis_sig)
1430
  if ("Message" %in% colnames(values$epistasis_sig))
@@ -1433,44 +1682,47 @@ server <- function(input, output, session) {
1433
  options = list(pageLength = 10, scrollX = TRUE), rownames = FALSE) %>%
1434
  formatSignif(columns = c("Interaction_p", "Effect_Size"), digits = 4)
1435
  })
1436
-
1437
  output$selection_table <- renderDT({
1438
  req(values$selection_metrics)
1439
  if ("Message" %in% colnames(values$selection_metrics))
1440
  return(datatable(data.frame(Status = values$selection_metrics$Message[1]), options = list(dom = "t")))
1441
-
1442
  df <- values$selection_metrics
1443
  if (!is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train))
1444
  df$QTL_Overlap <- df$Marker %in% values$qtl_effects_train$Marker
1445
-
1446
  display_cols <- intersect(
1447
  c("Marker", "Chromosome", "Fst", "Pi_Dom", "Pi_Wild", "Tajima_D_Dom", "Significant", "QTL_Overlap"),
1448
  colnames(df))
1449
  datatable(df[order(-df$Fst), display_cols], options = list(pageLength = 10, scrollX = TRUE), rownames = FALSE) %>%
1450
  formatRound(c("Fst", "Pi_Dom", "Pi_Wild", "Tajima_D_Dom"), 3)
1451
  })
1452
-
1453
- # ---- Chromosome visualization ----
 
 
 
1454
  output$chromosome_viz <- renderUI({
1455
  req(values$lod_scores_train, values$all_markers)
1456
  if ("Message" %in% colnames(values$lod_scores_train))
1457
  return(div(class = "alert alert-info", values$lod_scores_train$Message[1]))
1458
-
1459
  chromosomes <- unique(values$lod_scores_train$Chromosome)
1460
  tagList(lapply(chromosomes, function(chr) {
1461
  chr_markers <- values$all_markers[values$all_markers$Chromosome == chr, ]
1462
  chr_markers <- chr_markers[order(chr_markers$Position), ]
1463
  chr_qtls <- values$lod_scores_train[values$lod_scores_train$Chromosome == chr, ]
1464
-
1465
  sel_markers <- NULL
1466
  if (!is.null(values$selection_metrics) && !"Message" %in% colnames(values$selection_metrics))
1467
  sel_markers <- values$selection_metrics[
1468
  values$selection_metrics$Chromosome == chr & values$selection_metrics$Significant, ]
1469
-
1470
  min_pos <- min(chr_markers$Position, na.rm = TRUE)
1471
  max_pos <- max(chr_markers$Position, na.rm = TRUE)
1472
  range_pos <- max_pos - min_pos
1473
-
1474
  div(class = "chromosome-container",
1475
  div(class = "chromosome-title", paste("Chromosome", chr)),
1476
  div(class = "chromosome",
@@ -1478,7 +1730,7 @@ server <- function(input, output, session) {
1478
  marker <- chr_markers[i, ]
1479
  left <- if (range_pos > 0) ((marker$Position - min_pos) / range_pos) * 100
1480
  else (i / nrow(chr_markers)) * 100
1481
-
1482
  marker_class <- "chromosome-marker"
1483
  if (marker$Marker %in% chr_qtls$Marker) {
1484
  marker_class <- paste(marker_class, "significant")
@@ -1496,23 +1748,26 @@ server <- function(input, output, session) {
1496
  )
1497
  }))
1498
  })
1499
-
1500
  # ---- Simulation animations ----
1501
  observeEvent(input$simulate_btn, session$sendCustomMessage("simulateQTLDiscovery", list()))
1502
  observeEvent(input$reset_btn, session$sendCustomMessage("resetAnimation", list()))
1503
-
1504
- # ---- Interpretation outputs ----
 
 
 
1505
  output$analysis_summary <- renderUI({
1506
  has_qtl <- !is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train)
1507
  has_perf <- !is.null(values$performance_metrics)
1508
- has_epi <- !is.null(values$epistasis_sig) && !"Message" %in% colnames(values$epistasis_sig) && nrow(values$epistasis_sig) > 0
1509
  has_sel <- !is.null(values$selection_metrics) && !"Message" %in% colnames(values$selection_metrics)
1510
-
1511
  n_qtl <- if (has_qtl) nrow(values$qtl_effects_train) else 0
1512
  n_epi <- if (has_epi) nrow(values$epistasis_sig) else 0
1513
  n_sel <- if (has_sel) sum(values$selection_metrics$Significant, na.rm = TRUE) else 0
1514
  val_r2 <- if (has_perf) round(values$performance_metrics$Value[values$performance_metrics$Metric == "R\u00b2 (Validation)"], 3) else "N/A"
1515
-
1516
  div(class = "interpretation-section",
1517
  tags$h5("Analysis Summary"),
1518
  tags$p(paste("Found", n_qtl, "QTLs above LOD", input$lod_threshold,
@@ -1520,38 +1775,38 @@ server <- function(input, output, session) {
1520
  if (has_epi) paste0("with ", n_epi, " epistatic interactions"),
1521
  if (has_sel) paste0("and ", n_sel, " selection signatures."))))
1522
  })
1523
-
1524
  output$qtl_interpretation <- renderUI({
1525
  if (is.null(values$qtl_effects_train) || "Message" %in% colnames(values$qtl_effects_train))
1526
  return(div(class = "interpretation-section", tags$h5("QTL Significance"), tags$p("No significant QTLs detected.")))
1527
-
1528
  top_qtl <- values$qtl_effects_train[which.max(values$qtl_effects_train$LOD), ]
1529
  div(class = "interpretation-section",
1530
  tags$h5("QTL Significance"),
1531
  tags$p(paste("Top QTL:", top_qtl$Marker, "(Chr", top_qtl$Chromosome, ") with LOD =", round(top_qtl$LOD, 2))))
1532
  })
1533
-
1534
  output$effect_interpretation <- renderUI({
1535
  if (is.null(values$qtl_effects_train) || "Message" %in% colnames(values$qtl_effects_train))
1536
  return(div(class = "interpretation-section", tags$h5("Effect Sizes"), tags$p("No QTL effects to interpret.")))
1537
-
1538
  top_pve <- values$qtl_effects_train[which.max(values$qtl_effects_train$PVE_Percent), ]
1539
  div(class = "interpretation-section",
1540
  tags$h5("Effect Sizes"),
1541
  tags$p(paste("Largest effect:", top_pve$Marker, "explains", round(top_pve$PVE_Percent, 1), "% of variance")))
1542
  })
1543
-
1544
  output$epistasis_interpretation <- renderUI({
1545
  if (is.null(values$epistasis_sig) || "Message" %in% colnames(values$epistasis_sig) || nrow(values$epistasis_sig) == 0)
1546
  return(div(class = "interpretation-section", tags$h5("Epistasis"), tags$p("No significant epistatic interactions detected.")))
1547
-
1548
  top_epi <- values$epistasis_sig[which.min(values$epistasis_sig$Interaction_p), ]
1549
  div(class = "interpretation-section",
1550
  tags$h5("Epistasis"),
1551
  tags$p(paste("Detected", nrow(values$epistasis_sig), "interactions. Strongest:",
1552
  top_epi$QTL1, "x", top_epi$QTL2, "(p =", format.pval(top_epi$Interaction_p), ")")))
1553
  })
1554
-
1555
  output$recommendations <- renderUI({
1556
  has_qtl <- !is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train)
1557
  recs <- if (has_qtl) {
@@ -1567,8 +1822,11 @@ server <- function(input, output, session) {
1567
  tags$h5("Recommendations"),
1568
  tags$ul(lapply(recs, tags$li), style = "color:#8b949e;"))
1569
  })
1570
-
1571
- # ---- Download handlers ----
 
 
 
1572
  output$download_train_results <- downloadHandler(
1573
  filename = function() paste0("qtl_results_", Sys.Date(), ".xlsx"),
1574
  content = function(file) {
@@ -1580,7 +1838,7 @@ server <- function(input, output, session) {
1580
  write_xlsx(sheets, file)
1581
  }
1582
  )
1583
-
1584
  output$download_selection <- downloadHandler(
1585
  filename = function() paste0("selection_", Sys.Date(), ".xlsx"),
1586
  content = function(file) {
@@ -1594,7 +1852,7 @@ server <- function(input, output, session) {
1594
  }
1595
 
1596
  # ============================================================
1597
- # RUN APP#
1598
  # ============================================================
1599
 
1600
  shinyApp(ui = ui, server = server)
 
1
  # ============================================================
2
+ # QTL-Mapper - With Model Selection & File Upload
3
  # ============================================================
4
 
5
  options(repos = c(CRAN = "https://cloud.r-project.org"))
 
7
  required_packages <- c(
8
  "shiny", "randomForest", "caret", "DT", "ggplot2", "plotly",
9
  "writexl", "viridis", "reshape2", "dplyr", "httr", "jsonlite",
10
+ "shinyjs", "markdown", "base64enc"
11
  )
12
 
13
  for (pkg in required_packages) {
 
32
  print("===================================")
33
 
34
  # ============================================================
35
+ # AVAILABLE MODELS CONFIGURATION
36
+ # ============================================================
37
+
38
+ available_models <- list(
39
+ list(
40
+ id = "meta-llama/Llama-3.1-8B-Instruct:sambanova",
41
+ label = "Llama 3.1 8B (SambaNova)",
42
+ provider = "sambanova",
43
+ tier = "free"
44
+ ),
45
+ list(
46
+ id = "meta-llama/Llama-3.3-70B-Instruct:sambanova",
47
+ label = "Llama 3.3 70B (SambaNova)",
48
+ provider = "sambanova",
49
+ tier = "free"
50
+ ),
51
+ list(
52
+ id = "Qwen/Qwen2.5-72B-Instruct:sambanova",
53
+ label = "Qwen 2.5 72B (SambaNova)",
54
+ provider = "sambanova",
55
+ tier = "free"
56
+ ),
57
+ list(
58
+ id = "meta-llama/Llama-3.2-3B-Instruct:together",
59
+ label = "Llama 3.2 3B (Together)",
60
+ provider = "together",
61
+ tier = "free"
62
+ ),
63
+ list(
64
+ id = "Qwen/Qwen2.5-7B-Instruct:together",
65
+ label = "Qwen 2.5 7B (Together)",
66
+ provider = "together",
67
+ tier = "free"
68
+ )
69
+ )
70
+
71
+ model_choices <- setNames(
72
+ sapply(available_models, function(m) m$id),
73
+ sapply(available_models, function(m) paste0(m$label, " [", m$tier, "]"))
74
+ )
75
+
76
+ # ============================================================
77
+ # API CONFIGURATION
78
  # ============================================================
79
 
80
  HF_API_TOKEN <- token
81
  HF_API_URL <- "https://router.huggingface.co/v1/chat/completions"
82
+
83
+ # Default model
84
+ default_model <- "meta-llama/Llama-3.2-3B-Instruct:together"
85
 
86
  # ============================================================
87
  # TEST CONNECTION
88
  # ============================================================
89
 
90
+ test_api_connection <- function(model_id = default_model) {
91
  if (!token_exists) return(list(success = FALSE, error = "No token found"))
92
+
93
  tryCatch({
94
  response <- POST(
95
  url = HF_API_URL,
 
98
  "Content-Type" = "application/json"
99
  ),
100
  body = toJSON(list(
101
+ model = model_id,
102
  messages = list(list(role = "user", content = "Hi")),
103
  max_tokens = 10L
104
  ), auto_unbox = TRUE),
105
  encode = "json",
106
  timeout(15)
107
  )
108
+
109
  status <- status_code(response)
110
  if (status == 200) return(list(success = TRUE))
111
+
112
  err <- tryCatch(content(response, "text", encoding = "UTF-8"),
113
  error = function(e) paste("Status:", status))
114
  return(list(success = FALSE,
 
116
  }, error = function(e) list(success = FALSE, error = e$message))
117
  }
118
 
119
+ api_test <- test_api_connection(default_model)
120
  use_hf_api <- token_exists && api_test$success
121
 
122
  print(paste("API Test result:", if(api_test$success) "SUCCESS" else paste("FAILED -", api_test$error)))
123
  if (use_hf_api) {
124
+ print(paste("\u2705 API working with model:", default_model, "- AI mode enabled"))
125
  } else {
126
+ print("\u26a0\ufe0f API not available - using rule-based mode")
127
  }
128
 
129
  # ============================================================
130
+ # QUERY FUNCTION
131
  # ============================================================
132
 
133
+ query_hf_api <- function(prompt, model_id = default_model, max_length = 500, temperature = 0.7) {
134
  if (!token_exists) return(list(success = FALSE, error = "HF_API_TOKEN not set"))
135
+
136
  tryCatch({
137
  response <- POST(
138
  url = HF_API_URL,
 
141
  "Content-Type" = "application/json"
142
  ),
143
  body = toJSON(list(
144
+ model = model_id,
145
  messages = list(
146
  list(role = "system",
147
  content = "You are an expert bioinformatics assistant specializing in QTL analysis. Be concise and helpful."),
 
153
  encode = "json",
154
  timeout(60)
155
  )
156
+
157
  status <- status_code(response)
158
+
159
  if (status == 200) {
160
  result <- content(response, as = "parsed", encoding = "UTF-8")
161
  text <- result$choices[[1]]$message$content
162
  return(list(success = TRUE, text = text))
163
  }
164
+
165
  err <- tryCatch(content(response, "text", encoding = "UTF-8"),
166
  error = function(e) paste("Status:", status))
167
  return(list(success = FALSE,
 
175
 
176
  build_system_prompt <- function(rv) {
177
  context_parts <- c("CURRENT ANALYSIS RESULTS:")
178
+
179
  if (!is.null(rv$qtl_effects_train) && !"Message" %in% colnames(rv$qtl_effects_train)) {
180
  n_qtl <- nrow(rv$qtl_effects_train)
181
  total_pve <- sum(rv$qtl_effects_train$PVE_Percent, na.rm = TRUE)
182
+
183
  context_parts <- c(context_parts,
184
  sprintf("\nQTL Results: %d significant QTLs detected above LOD %.1f.", n_qtl, rv$lod_threshold),
185
  sprintf("Total variance explained by QTLs: %.1f%%.", total_pve))
186
+
187
  top_qtls <- head(rv$qtl_effects_train[order(-rv$qtl_effects_train$LOD), ], 3)
188
  context_parts <- c(context_parts, "\nTop QTLs:")
189
  for (i in 1:nrow(top_qtls)) {
 
193
  i, row$Marker, row$Chromosome, row$LOD, row$PVE_Percent, row$Additive_Effect))
194
  }
195
  }
196
+
197
  if (!is.null(rv$performance_metrics)) {
198
  pm <- rv$performance_metrics
199
  train_r2 <- pm$Value[pm$Metric == "R\u00b2 (Train)"]
 
203
  sprintf(" Training R\u00b2: %.3f", train_r2),
204
  sprintf(" Validation R\u00b2: %.3f", val_r2))
205
  }
206
+
207
  if (!is.null(rv$epistasis_sig) && !"Message" %in% colnames(rv$epistasis_sig) && nrow(rv$epistasis_sig) > 0) {
208
  n_epi <- nrow(rv$epistasis_sig)
209
  top_epi <- rv$epistasis_sig[order(rv$epistasis_sig$Interaction_p), ][1, ]
 
211
  sprintf("\nEpistasis: %d significant pairwise interactions detected.", n_epi),
212
  sprintf(" Strongest: %s x %s (p=%.4f)", top_epi$QTL1, top_epi$QTL2, top_epi$Interaction_p))
213
  }
214
+
215
  if (!is.null(rv$selection_metrics) && !"Message" %in% colnames(rv$selection_metrics)) {
216
  n_sig <- sum(rv$selection_metrics$Significant, na.rm = TRUE)
217
  context_parts <- c(context_parts,
218
  sprintf("\nDomestication: %d markers with selection signatures.", n_sig))
219
  }
220
+
221
  paste(context_parts, collapse = "\n")
222
  }
223
 
 
227
 
228
  enhanced_rule_response <- function(user_message, rv) {
229
  q <- tolower(trimws(user_message))
230
+
231
  has_qtl <- !is.null(rv$qtl_effects_train) && !"Message" %in% colnames(rv$qtl_effects_train)
232
  has_perf <- !is.null(rv$performance_metrics)
233
  has_epi <- !is.null(rv$epistasis_sig) && !"Message" %in% colnames(rv$epistasis_sig) && nrow(rv$epistasis_sig) > 0
234
  has_sel <- !is.null(rv$selection_metrics) && !"Message" %in% colnames(rv$selection_metrics)
235
+
 
236
  if (grepl("pve|variance explained|how much variance|percent variance|what is pve", q)) {
237
  if (has_qtl) {
238
  df <- rv$qtl_effects_train
239
  total_pve <- sum(df$PVE_Percent, na.rm = TRUE)
240
  top_pve <- df[which.max(df$PVE_Percent), ]
241
+
242
  response <- paste0(
243
  "\U0001f4ca **PVE (Phenotypic Variance Explained) Analysis**\n\n",
244
  "**Your Results:**\n",
 
250
  "\u2022 PVE: **", round(top_pve$PVE_Percent, 1), "%**\n",
251
  "\u2022 LOD: ", round(top_pve$LOD, 2), "\n\n"
252
  )
253
+
254
  if (top_pve$PVE_Percent > 10) {
255
+ response <- paste0(response, "\U0001f4a1 This is a **major-effect QTL** (>10% PVE).\n\n")
256
  } else if (top_pve$PVE_Percent > 5) {
257
+ response <- paste0(response, "\U0001f4a1 This is a **moderate-effect QTL** (5-10% PVE).\n\n")
258
  } else {
259
+ response <- paste0(response, "\U0001f4a1 This is a **minor-effect QTL** (<5% PVE).\n\n")
260
  }
261
+
262
  response <- paste0(response, "**All QTLs by PVE:**\n")
263
  df_sorted <- df[order(-df$PVE_Percent), ]
264
  for (i in 1:min(5, nrow(df_sorted))) {
 
270
  return("No QTL results yet. Please run the QTL analysis first to see PVE values.")
271
  }
272
  }
273
+
 
274
  if (grepl("model performance|r2|r squared|how good is my model|validation|negative r2", q)) {
275
  if (has_perf) {
276
  pm <- rv$performance_metrics
277
  train_r2 <- pm$Value[pm$Metric == "R\u00b2 (Train)"]
278
  val_r2 <- pm$Value[pm$Metric == "R\u00b2 (Validation)"]
279
+
280
  response <- paste0(
281
  "\U0001f4c8 **Model Performance Summary**\n\n",
282
  "\u2022 Training R\u00b2: **", round(train_r2, 3), "**\n",
283
  "\u2022 Validation R\u00b2: **", round(val_r2, 3), "**\n\n"
284
  )
285
+
286
  if (val_r2 < 0) {
287
  response <- paste0(response,
288
  "\u26a0\ufe0f **Your validation R\u00b2 is negative** (", round(val_r2, 3), ").\n\n",
 
289
  "**Common causes:**\n",
290
+ "\u2022 Small sample size relative to number of markers\n",
291
+ "\u2022 Overfitting\n",
292
+ "\u2022 Population structure\n\n",
293
  "**Recommendations:**\n",
294
+ "1. Increase sample size\n",
295
+ "2. Reduce marker number\n",
296
+ "3. Try simpler models or increase CV folds\n")
 
297
  } else if (val_r2 < 0.2) {
298
+ response <- paste0(response, "\U0001f4c9 **Low validation R\u00b2** (<0.2). Focus on individual QTL interpretation.\n")
 
 
299
  } else if (val_r2 < 0.5) {
300
+ response <- paste0(response, "\U0001f4ca **Moderate validation R\u00b2** (0.2-0.5).\n")
 
301
  } else {
302
+ response <- paste0(response, "\U0001f3af **Excellent validation R\u00b2** (>0.5)!\n")
 
303
  }
304
  return(response)
305
  } else {
306
  return("Run the QTL analysis first to see model performance metrics.")
307
  }
308
  }
309
+
 
310
  if (grepl("top qtl|best qtl|highest lod|significant qtl|list qtl|show qtl", q)) {
311
  if (has_qtl) {
312
  df <- rv$qtl_effects_train[order(-rv$qtl_effects_train$LOD), ]
313
  top5 <- head(df, 5)
314
+
315
  response <- "\U0001f3af **Top 5 QTLs by LOD Score**\n\n"
316
  for (i in 1:nrow(top5)) {
317
  row <- top5[i, ]
 
319
  i, ". **", row$Marker, "** (Chr ", row$Chromosome, ")\n",
320
  " \u2022 LOD: **", round(row$LOD, 2), "**\n",
321
  " \u2022 PVE: ", round(row$PVE_Percent, 1), "%\n",
322
+ " \u2022 Additive effect: ", round(row$Additive_Effect, 3), "\n\n")
 
 
 
 
323
  }
324
  return(response)
325
  } else {
326
+ return("No significant QTLs detected. Try lowering the LOD threshold.")
327
  }
328
  }
329
+
 
330
  if (grepl("next steps|what next|recommendations|suggest|advice|what should i do", q)) {
331
  if (has_qtl || has_perf || has_epi || has_sel) {
332
  response <- "\U0001f52c **Recommended Next Steps**\n\n"
333
+
334
  if (has_qtl) {
335
  top_qtl <- rv$qtl_effects_train[which.max(rv$qtl_effects_train$LOD), ]
336
  response <- paste0(response,
337
  "**1. Validate Top QTLs**\n",
338
+ " \u2022 Prioritize **", top_qtl$Marker, "** (LOD=", round(top_qtl$LOD, 2), ")\n",
339
+ " \u2022 Test in independent population\n\n")
 
 
340
  }
341
  if (has_epi) {
342
+ response <- paste0(response, "**2. Investigate Epistasis**\n",
343
+ " \u2022 ", nrow(rv$epistasis_sig), " significant interactions\n\n")
 
 
 
 
344
  }
345
  if (has_sel) {
346
+ response <- paste0(response, "**3. Domestication Analysis**\n",
347
+ " \u2022 ", sum(rv$selection_metrics$Significant, na.rm = TRUE), " selection signatures\n\n")
 
 
 
 
348
  }
349
+
350
  response <- paste0(response,
351
  "**4. Functional Analysis**\n",
352
+ " \u2022 Annotate QTL regions for candidate genes\n\n",
 
 
353
  "**5. Breeding Applications**\n",
354
+ " \u2022 Develop markers for MAS\n")
 
 
355
  return(response)
356
  } else {
357
  return("Run the QTL analysis first to get recommendations.")
358
  }
359
  }
360
+
 
361
  available <- c()
362
  if (has_qtl) available <- c(available, paste(nrow(rv$qtl_effects_train), "QTLs"))
363
  if (has_perf) {
364
+ val_r2 <- rv$performance_metrics$Value[rv$performance_metrics$Metric == "R\u00b2 (Validation)"]
365
  available <- c(available, paste0("R\u00b2=", round(val_r2, 3)))
366
  }
367
  if (has_epi) available <- c(available, paste(nrow(rv$epistasis_sig), "interactions"))
368
  if (has_sel) available <- c(available, paste(sum(rv$selection_metrics$Significant), "selection signatures"))
369
+
370
  if (length(available) > 0) {
371
  return(paste0(
372
  "I can see you have: ", paste(available, collapse = ", "), ".\n\n",
373
  "What would you like to know? Try asking about:\n",
374
+ "\u2022 **What is PVE?**\n",
375
+ "\u2022 **Top QTLs**\n",
376
+ "\u2022 **Model performance**\n",
377
+ "\u2022 **Next steps**"))
378
  }
379
+
380
  return(paste0(
381
  "\U0001f44b Hello! I'm your QTL analysis assistant.\n\n",
382
  "**I can help you with:**\n",
383
+ "\u2022 Understanding PVE\n",
384
+ "\u2022 Interpreting LOD scores\n",
385
+ "\u2022 Evaluating model performance\n",
386
  "\u2022 Detecting epistatic interactions\n\n",
 
 
 
 
387
  "Try: **'What is PVE?'** or **'Show me my top QTLs'**"))
388
  }
389
 
 
391
  # AI RESPONSE GENERATION
392
  # ============================================================
393
 
394
+ generate_ai_response <- function(user_message, rv, model_id = default_model) {
395
  context <- build_system_prompt(rv)
396
+
397
+ current_use_api <- token_exists
398
+
399
+ if (current_use_api) {
400
  prompt <- paste(
401
  "CONTEXT:", context,
402
  "\n\nUSER QUESTION:", user_message,
403
  "\n\nProvide a specific, helpful answer based ONLY on the context above. Be concise but informative.",
404
  sep = "\n"
405
  )
406
+
407
+ result <- query_hf_api(prompt, model_id = model_id)
408
+
409
  if (result$success) {
410
  return(result$text)
411
  } else {
 
413
  return(enhanced_rule_response(user_message, rv))
414
  }
415
  }
416
+
417
  return(enhanced_rule_response(user_message, rv))
418
  }
419
 
 
423
 
424
  ui <- fluidPage(
425
  shinyjs::useShinyjs(),
426
+
427
  tags$head(
428
  tags$link(rel = "stylesheet", type = "text/css",
429
  href = "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css"),
 
466
  $('#send_chat').click();
467
  }
468
  });
469
+
470
+ // File preview in chat
471
+ function previewChatFile(input) {
472
+ const file = input.files[0];
473
+ if (!file) return;
474
+ const preview = document.getElementById('chat_file_preview');
475
+ preview.innerHTML = '<span style=\"color:#58a6ff\"><i class=\"fas fa-paperclip\"></i> ' + file.name + ' (' + (file.size/1024).toFixed(1) + ' KB)</span>';
476
+ preview.style.display = 'block';
477
+ }
478
  ")),
479
  tags$style(HTML("
480
  :root {
 
532
  .simulation-controls { margin: 12px 0; display: flex; gap: 8px; }
533
  .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; }
534
  .simulation-btn:hover { background-color: var(--purple); color: #0d1117; }
535
+
536
+ /* ---- Chat Panel ---- */
537
+ #chat-panel { position: fixed; bottom: 20px; right: 20px; z-index: 9999; width: 440px; display: flex; flex-direction: column; }
538
  #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; }
539
  #chat-toggle-btn:hover { transform: scale(1.05); box-shadow: 0 6px 24px rgba(88,166,255,0.6); }
540
+ #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: 640px; }
541
  #chat-window.open { display: flex; }
542
+ #chat-header { background: linear-gradient(135deg, var(--bg-tertiary), #1c2b3a); border-bottom: 1px solid var(--border); padding: 12px 16px; display: flex; flex-direction: column; gap: 8px; }
543
+ .chat-header-top { display: flex; align-items: center; justify-content: space-between; }
544
  .chat-title { display: flex; align-items: center; gap: 10px; }
545
+ .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; flex-shrink: 0; }
546
  #chat-header h4 { font-family: var(--font-mono); font-size: 13px; font-weight: 600; color: var(--text-primary); margin: 0; }
547
+ #chat-header p { font-size: 11px; color: var(--text-muted); margin: 0; }
548
  #chat-header p.ai-mode { color: var(--success); }
549
  #chat-header p.rule-mode { color: var(--warning); }
550
+ #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; }
551
  #chat-close-btn:hover { color: var(--text-primary); }
552
+
553
+ /* Model selector in chat */
554
+ .chat-model-selector { display: flex; align-items: center; gap: 8px; padding: 4px 0; }
555
+ .chat-model-selector label { color: var(--text-muted); font-size: 10px; font-family: var(--font-mono); white-space: nowrap; margin: 0; }
556
+ .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; }
557
+ .chat-model-selector select:focus { border-color: var(--accent) !important; outline: none; }
558
+ .model-status-dot { width: 7px; height: 7px; border-radius: 50%; flex-shrink: 0; }
559
+ .model-status-dot.online { background: var(--success); box-shadow: 0 0 6px var(--success); }
560
+ .model-status-dot.offline { background: var(--warning); box-shadow: 0 0 6px var(--warning); }
561
+ .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; }
562
+ .test-model-btn:hover { border-color: var(--accent); color: var(--accent); }
563
+
564
  #chat_messages { flex: 1; overflow-y: auto; padding: 16px; display: flex; flex-direction: column; gap: 12px; background: var(--bg-primary); }
565
+ .chat-msg { max-width: 92%; animation: fadeIn 0.3s ease; }
566
  @keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
567
  .chat-msg.user { align-self: flex-end; }
568
  .chat-msg.assistant { align-self: flex-start; }
 
570
  .chat-msg.user .chat-bubble { background: linear-gradient(135deg, var(--accent), #3a7bd5); color: #0d1117; border-bottom-right-radius: 4px; }
571
  .chat-msg.assistant .chat-bubble { background: var(--bg-tertiary); color: var(--text-primary); border: 1px solid var(--border); border-bottom-left-radius: 4px; }
572
  .chat-bubble strong { color: var(--accent); }
573
+ .chat-meta { font-size: 10px; color: var(--text-muted); margin-top: 4px; font-family: var(--font-mono); padding: 0 4px; display: flex; align-items: center; gap: 6px; }
574
+ .chat-meta .model-tag { color: var(--purple); font-size: 9px; }
575
  .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; }
576
  .typing-dot { width: 8px; height: 8px; background: var(--text-muted); border-radius: 50%; animation: typingBounce 1.4s infinite; }
577
  .typing-dot:nth-child(2) { animation-delay: 0.2s; }
578
  .typing-dot:nth-child(3) { animation-delay: 0.4s; }
579
  @keyframes typingBounce { 0%, 60%, 100% { transform: translateY(0); } 30% { transform: translateY(-8px); } }
580
+
581
+ /* Chat quick questions */
582
+ .quick-questions { padding: 8px 16px; display: flex; flex-wrap: wrap; gap: 6px; border-bottom: 1px solid var(--border); background: var(--bg-secondary); }
583
+ .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; }
584
+ .quick-q-btn:hover { border-color: var(--accent); color: var(--accent); background: rgba(88,166,255,0.1); }
585
+
586
+ /* Chat footer */
587
+ #chat-footer { padding: 12px 16px; border-top: 1px solid var(--border); background: var(--bg-tertiary); }
588
  #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; }
589
  #chat_input:focus { border-color: var(--accent) !important; outline: none; }
590
+
591
+ /* File upload in chat */
592
+ .chat-file-row { display: flex; align-items: center; gap: 8px; margin-bottom: 8px; }
593
+ #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; }
594
+ #chat_file_upload_btn:hover { border-color: var(--accent); color: var(--accent); }
595
+ #chat_file_preview { display: none; font-size: 11px; font-family: var(--font-mono); color: var(--text-muted); flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
596
+ #chat_file_clear_btn { background: transparent; border: none; color: var(--text-muted); cursor: pointer; font-size: 14px; padding: 2px 4px; transition: color 0.15s; }
597
+ #chat_file_clear_btn:hover { color: var(--danger); }
598
  .chat-actions { display: flex; gap: 8px; }
599
  #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; }
600
  #send_chat:hover:not(:disabled) { transform: translateY(-1px); box-shadow: 0 4px 12px rgba(88,166,255,0.4); }
601
  #send_chat:disabled { opacity: 0.5; cursor: not-allowed; }
602
  #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; }
603
  #clear_chat:hover { border-color: var(--danger); color: var(--danger); }
604
+
605
+ /* File message bubble in chat */
606
+ .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; }
607
+ .chat-file-bubble i { font-size: 14px; }
608
  "))
609
  ),
610
+
611
  navbarPage(
612
  title = tags$span(tags$i(class = "fas fa-dna", style = "margin-right:8px; color:#58a6ff;"), "QTL-Mapper AI"),
613
  id = "nav",
614
+
615
  # ---- Data Upload tab ----
616
  tabPanel("Data Upload", icon = icon("upload"),
617
  div(class = "main-header",
 
669
  )
670
  )
671
  ),
672
+
673
  # ---- Domestication tab ----
674
  tabPanel("Domestication", icon = icon("leaf"),
675
  div(class = "main-header",
 
683
  div(class = "card-body",
684
  fileInput("pop_file", "Population Metadata CSV", accept = ".csv", buttonLabel = "Browse"),
685
  helpText("CSV with 'id' and 'population' columns (e.g., Domesticated, Wild)."),
686
+ numericInput("fst_threshold", "Fst Threshold", value = 0.1, min = 0.05, max = 0.5, step = 0.01),
687
+ numericInput("tajima_threshold", "Tajima's D Threshold", value = -1, min = -5, max = 0, step = 0.1),
688
  actionButton("run_domestication", "Run Domestication Analysis", class = "btn-primary btn-block", icon = icon("play"))
689
  )
690
  )
 
697
  )
698
  ),
699
  fluidRow(
700
+ column(6, div(class = "card", div(class = "card-header", "Fst Manhattan Plot"), div(class = "card-body", plotlyOutput("fst_plot", height = "400px")))),
701
  column(6, div(class = "card", div(class = "card-header", "Tajima's D Manhattan Plot"), div(class = "card-body", plotlyOutput("tajima_plot", height = "400px"))))
702
  ),
703
  fluidRow(
 
713
  )
714
  )
715
  ),
716
+
717
  # ---- Results tab ----
718
  tabPanel("Results", icon = icon("chart-line"),
719
  div(class = "main-header",
 
734
  ))
735
  ),
736
  fluidRow(
737
+ column(4, div(class = "card", div(class = "card-header", "Model Performance"), div(class = "card-body", plotlyOutput("performance_plot")))),
738
+ column(4, div(class = "card", div(class = "card-header", "Train: Predicted vs Observed"), div(class = "card-body", plotlyOutput("regression_plot_train", height = "300px")))),
739
+ column(4, div(class = "card", div(class = "card-header", "Validation: Predicted vs Observed"), div(class = "card-body", plotlyOutput("regression_plot_test", height = "300px"))))
740
  ),
741
  fluidRow(
742
  column(12, div(class = "card",
 
754
  ))
755
  )
756
  ),
757
+
758
  # ---- Interpretation tab ----
759
  tabPanel("Interpretation", icon = icon("lightbulb"),
760
  div(class = "main-header",
 
766
  column(6, div(class = "card", div(class = "card-header", "QTL Significance"), div(class = "card-body", uiOutput("qtl_interpretation")))),
767
  column(6, div(class = "card", div(class = "card-header", "Effect Sizes"), div(class = "card-body", uiOutput("effect_interpretation"))))
768
  ),
769
+ fluidRow(column(12, div(class = "card", div(class = "card-header", "Epistasis"), div(class = "card-body", uiOutput("epistasis_interpretation"))))),
770
+ fluidRow(column(12, div(class = "card", div(class = "card-header", "Recommendations"), div(class = "card-body", uiOutput("recommendations")))))
771
  ),
772
+
773
  # ---- About tab ----
774
  tabPanel("About", icon = icon("info-circle"),
775
  div(class = "main-header",
776
  h2(tags$i(class = "fas fa-info-circle", style = "margin-right:8px;"), "About QTL-Mapper AI"),
777
+ p("QTL Mapping with Multi-Model AI Assistant")
778
  ),
779
  fluidRow(
780
  column(8, offset = 2,
 
787
  tags$li("Additive and dominance effects estimated via linear regression"),
788
  tags$li("Epistasis analysis: pairwise QTL x marker interactions"),
789
  tags$li("Domestication: Fst, nucleotide diversity (Pi), Tajima's D"),
790
+ tags$li("AI Assistant powered by multiple transformer models via Hugging Face Router API")
791
+ ),
792
+ h4(style = "color:#58a6ff; font-family:'IBM Plex Mono'; margin:12px 0;", "Available AI Models"),
793
+ tags$table(style = "width:100%; color:#8b949e; border-collapse: collapse;",
794
+ tags$thead(tags$tr(
795
+ tags$th(style = "text-align:left; padding:6px; border-bottom:1px solid #30363d; color:#58a6ff;", "Model"),
796
+ tags$th(style = "text-align:left; padding:6px; border-bottom:1px solid #30363d; color:#58a6ff;", "Provider"),
797
+ tags$th(style = "text-align:left; padding:6px; border-bottom:1px solid #30363d; color:#58a6ff;", "Tier")
798
+ )),
799
+ tags$tbody(
800
+ lapply(available_models, function(m) {
801
+ tags$tr(
802
+ tags$td(style = "padding:6px; border-bottom:1px solid #21262d;", m$label),
803
+ tags$td(style = "padding:6px; border-bottom:1px solid #21262d;", m$provider),
804
+ tags$td(style = "padding:6px; border-bottom:1px solid #21262d;", tags$span(style = "color:#3fb950;", m$tier))
805
+ )
806
+ })
807
+ )
808
  ),
809
  h4(style = "color:#58a6ff; font-family:'IBM Plex Mono'; margin:12px 0;", "AI Assistant Status"),
810
+ p(style = "color:#8b949e;",
811
+ if (token_exists) paste("\u2705 HF_API_TOKEN found. Select a model in the chat panel to get started.")
812
+ else "\u26a0\ufe0f No HF_API_TOKEN found. Set it in Space secrets to enable AI mode."
813
  ),
814
  h4(style = "color:#58a6ff; font-family:'IBM Plex Mono'; margin:12px 0;", "Interpretation Thresholds"),
815
  tags$ul(style = "color:#8b949e; line-height:2;",
 
824
  )
825
  )
826
  ),
827
+
828
+ # ============================================================
829
+ # FLOATING CHAT PANEL (with model selector + file upload)
830
+ # ============================================================
831
  tags$div(id = "chat-panel",
832
  tags$div(id = "chat-window",
833
+
834
+ # Chat header
835
  tags$div(id = "chat-header",
836
+ tags$div(class = "chat-header-top",
837
+ tags$div(class = "chat-title",
838
+ tags$div(class = "chat-avatar", "AI"),
839
+ tags$div(
840
+ tags$h4("QTL Analysis AI Assistant"),
841
+ tags$p(id = "model_status_text",
842
+ if (token_exists) "AI mode ready" else "Rule-based mode",
843
+ class = if (token_exists) "ai-mode" else "rule-mode")
844
+ )
845
+ ),
846
+ tags$button(id = "chat-close-btn",
847
+ onclick = "document.getElementById('chat-window').classList.remove('open');",
848
+ tags$i(class = "fas fa-times"))
849
  ),
850
+
851
+ # Model selector row
852
+ tags$div(class = "chat-model-selector",
853
+ tags$label(tags$i(class = "fas fa-robot"), " Model:"),
854
+ tags$div(id = "model_status_dot", class = paste0("model-status-dot ", if (token_exists) "online" else "offline")),
855
+ selectInput("selected_model", label = NULL,
856
+ choices = model_choices,
857
+ selected = default_model,
858
+ width = "100%"),
859
+ actionButton("test_model_btn", "Test", class = "test-model-btn")
860
+ )
861
  ),
862
+
863
+ # Quick question buttons
864
  tags$div(class = "quick-questions",
865
+ tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q','What is PVE?',{priority:'event'});", "PVE meaning"),
866
+ tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q','What are my top QTLs?',{priority:'event'});", "Top QTLs"),
867
+ tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q','Why is my R2 negative?',{priority:'event'});","Negative R2"),
868
+ tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q','What should I do next?',{priority:'event'});","Next steps")
869
  ),
870
+
871
+ # Messages area
872
  tags$div(id = "chat_messages", uiOutput("chat_display")),
873
+
874
+ # Footer
875
  tags$div(id = "chat-footer",
876
+
877
+ # File upload row
878
+ tags$div(class = "chat-file-row",
879
+ tags$label(
880
+ id = "chat_file_upload_btn",
881
+ tags$i(class = "fas fa-paperclip"),
882
+ " Attach file",
883
+ fileInput("chat_file_upload", label = NULL,
884
+ accept = c(".csv", ".txt", ".tsv", ".xlsx", ".pdf"),
885
+ buttonLabel = "",
886
+ placeholder = "",
887
+ width = "0px")
888
+ ),
889
+ tags$span(id = "chat_file_preview"),
890
+ tags$button(id = "chat_file_clear_btn",
891
+ onclick = "document.getElementById('chat_file_preview').style.display='none'; document.getElementById('chat_file_preview').innerHTML=''; Shiny.setInputValue('clear_chat_file', Math.random());",
892
+ tags$i(class = "fas fa-times"))
893
+ ),
894
+
895
+ # Text input
896
+ tags$textarea(id = "chat_input",
897
+ placeholder = "Ask about your results... (Enter to send)",
898
+ rows = "2"),
899
+
900
+ # Action buttons
901
  tags$div(class = "chat-actions",
902
  actionButton("send_chat", "Send", icon = icon("paper-plane"), class = "btn-primary"),
903
  actionButton("clear_chat", "Clear", icon = icon("trash-alt"), class = "btn-danger")
904
  )
905
  )
906
  ),
907
+
908
+ # Toggle button
909
  tags$button(id = "chat-toggle-btn",
910
  onclick = "document.getElementById('chat-window').classList.toggle('open');",
911
  tags$i(class = "fas fa-robot"))
912
+ ),
913
+
914
+ # JS to show filename on file selection
915
+ tags$script(HTML("
916
+ $(document).on('change', '#chat_file_upload', function() {
917
+ var file = this.files[0];
918
+ if (file) {
919
+ var preview = document.getElementById('chat_file_preview');
920
+ preview.innerHTML = '<i class=\"fas fa-paperclip\" style=\"color:#58a6ff;\"></i> ' + file.name + ' (' + (file.size/1024).toFixed(1) + ' KB)';
921
+ preview.style.display = 'inline';
922
+ }
923
+ });
924
+ "))
925
  )
926
 
927
  # ============================================================
 
929
  # ============================================================
930
 
931
  server <- function(input, output, session) {
932
+
933
  values <- reactiveValues(
934
+ genotype_data = NULL,
935
+ phenotype_data = NULL,
936
+ test_genotype_data = NULL,
937
+ predicted_test_phenotype_data = NULL,
938
+ chromosome_info = NULL,
939
+ position_info = NULL,
940
+ all_markers = NULL,
941
+ importance_scores = NULL,
942
+ lod_scores_train = NULL,
943
+ model_fit = NULL,
944
+ phenotype_values = NULL,
945
+ qtl_effects_train = NULL,
946
+ qtl_effects_test = NULL,
947
+ performance_metrics = NULL,
948
+ train_predictions = NULL,
949
+ test_predictions = NULL,
950
+ epistasis_all = NULL,
951
+ epistasis_sig = NULL,
952
+ pop_data = NULL,
953
+ selection_metrics = NULL,
954
+ has_test_data = FALSE,
955
+ chat_messages = list(),
956
+ is_typing = FALSE,
957
+ lod_threshold = 2,
958
+ current_model = default_model,
959
+ model_test_status = if (use_hf_api) "online" else "offline",
960
+ pending_file_content = NULL,
961
+ pending_file_name = NULL
962
  )
963
+
964
+ # ---- Current selected model ----
965
  observe({
966
+ req(input$selected_model)
967
+ values$current_model <- input$selected_model
968
+
969
+ # Update status display
970
+ model_label <- names(model_choices)[model_choices == input$selected_model]
971
+ if (is.null(model_label) || length(model_label) == 0)
972
+ model_label <- gsub(".*/([^:]+):.*", "\\1", input$selected_model)
973
+
974
+ shinyjs::html("model_status_text",
975
+ if (token_exists) paste("AI:", gsub(".*\\[(.*)\\]", "\\1", model_label), "- ready")
976
+ else "Rule-based mode (no token)")
977
+ })
978
+
979
+ # ---- Test model button ----
980
+ observeEvent(input$test_model_btn, {
981
+ req(input$selected_model)
982
+ add_message("assistant", paste0("\u23f3 Testing model: **", gsub(".*/", "", input$selected_model), "**..."))
983
+
984
+ result <- test_api_connection(input$selected_model)
985
+ if (result$success) {
986
+ add_message("assistant", paste0("\u2705 **", gsub(".*/", "", input$selected_model), "** is working! You can now chat with this model."))
987
+ shinyjs::runjs("document.getElementById('model_status_dot').className = 'model-status-dot online';")
988
  } else {
989
+ add_message("assistant", paste0("\u274c **", gsub(".*/", "", input$selected_model), "** test failed.\n\nError: ", result$error,
990
+ "\n\nTry another model or check your HF_API_TOKEN."))
991
+ shinyjs::runjs("document.getElementById('model_status_dot').className = 'model-status-dot offline';")
992
  }
993
  })
994
+
995
  # ---- Chat helpers ----
996
+ add_message <- function(role, content, model_used = NULL) {
997
  timestamp <- format(Sys.time(), "%H:%M")
998
  values$chat_messages <- c(values$chat_messages,
999
+ list(list(role = role, content = content,
1000
+ time = timestamp, model = model_used)))
1001
+ if (length(values$chat_messages) > 100)
1002
+ values$chat_messages <- tail(values$chat_messages, 100)
1003
  session$sendCustomMessage("scrollChatBottom", list())
1004
  }
1005
+
1006
+ process_message <- function(user_text, file_content = NULL, file_name = NULL) {
1007
+ if (nchar(trimws(user_text)) == 0 && is.null(file_content)) return()
1008
+
1009
+ # Build full message including file content if present
1010
+ full_message <- user_text
1011
+ if (!is.null(file_content) && nchar(trimws(file_content)) > 0) {
1012
+ full_message <- paste0(user_text,
1013
+ if (nchar(trimws(user_text)) > 0) "\n\n" else "",
1014
+ "--- Attached file: ", file_name, " ---\n",
1015
+ substr(file_content, 1, 3000),
1016
+ if (nchar(file_content) > 3000) "\n[... truncated ...]" else "")
1017
+ }
1018
+
1019
+ add_message("user", full_message)
1020
  values$is_typing <- TRUE
1021
+
1022
+ model_id <- isolate(values$current_model)
1023
+ response <- generate_ai_response(full_message, values, model_id = model_id)
1024
+
1025
  values$is_typing <- FALSE
1026
+ model_short <- gsub(".*/([^:]+):.*", "\\1", model_id)
1027
+ add_message("assistant", response, model_used = if (token_exists) model_short else NULL)
1028
+
1029
+ # Clear pending file
1030
+ values$pending_file_content <- NULL
1031
+ values$pending_file_name <- NULL
1032
  }
1033
+
1034
+ # ---- Handle chat file upload ----
1035
+ observeEvent(input$chat_file_upload, {
1036
+ req(input$chat_file_upload)
1037
+ file_path <- input$chat_file_upload$datapath
1038
+ file_name <- input$chat_file_upload$name
1039
+ ext <- tolower(tools::file_ext(file_name))
1040
+
1041
+ tryCatch({
1042
+ file_content <- if (ext %in% c("csv", "txt", "tsv")) {
1043
+ paste(readLines(file_path, n = 200), collapse = "\n")
1044
+ } else {
1045
+ paste0("[Binary file: ", file_name, " - ", round(file.info(file_path)$size / 1024, 1), " KB]")
1046
+ }
1047
+
1048
+ values$pending_file_content <- file_content
1049
+ values$pending_file_name <- file_name
1050
+ }, error = function(e) {
1051
+ showNotification(paste("Could not read file:", e$message), type = "warning")
1052
+ })
1053
+ })
1054
+
1055
+ # ---- Clear chat file ----
1056
+ observeEvent(input$clear_chat_file, {
1057
+ values$pending_file_content <- NULL
1058
+ values$pending_file_name <- NULL
1059
+ })
1060
+
1061
+ # ---- Send chat ----
1062
  observeEvent(input$send_chat, {
 
1063
  user_text <- trimws(input$chat_input)
1064
+ file_content <- isolate(values$pending_file_content)
1065
+ file_name <- isolate(values$pending_file_name)
1066
+
1067
+ if (nchar(user_text) == 0 && is.null(file_content)) return()
1068
+
1069
  updateTextAreaInput(session, "chat_input", value = "")
1070
+ # Clear file preview via JS
1071
+ shinyjs::runjs("
1072
+ document.getElementById('chat_file_preview').style.display = 'none';
1073
+ document.getElementById('chat_file_preview').innerHTML = '';
1074
+ ")
1075
+
1076
+ process_message(user_text, file_content, file_name)
1077
  })
1078
+
1079
  observeEvent(input$quick_q, { req(input$quick_q); process_message(input$quick_q) })
1080
+
1081
  observeEvent(input$clear_chat, {
1082
  values$chat_messages <- list()
1083
  add_message("assistant", "Chat cleared. How can I help?")
1084
  })
1085
+
1086
+ # ---- Initial greeting ----
1087
  observe({
1088
  if (length(values$chat_messages) == 0) {
1089
+ mode_msg <- if (token_exists) {
1090
+ paste0("I have access to **", length(available_models), " AI models** via Hugging Face.\n",
1091
+ "Select a model above and click **Test** to verify it's working!")
1092
  } else {
1093
+ "I'm using rule-based responses. Set **HF_API_TOKEN** in Space secrets to enable AI models."
1094
  }
1095
+ add_message("assistant", paste0(
1096
+ "\U0001f44b Vanakam! I'm TerraByte - An AI powered companion.\n\n",
1097
+ mode_msg,
1098
+ "\n\n**I can help you with:**\n",
1099
+ "\u2022 **What is PVE?** - Understand variance explained\n",
1100
+ "\u2022 **Show top QTLs** - List your most significant markers\n",
1101
+ "\u2022 **Model performance** - Why is my R\u00b2 negative?\n",
1102
+ "\u2022 **Next steps** - Recommendations\n",
1103
+ "\u2022 **Upload files** - Use the paperclip to attach CSV/TXT data\n\n",
1104
+ "Try asking: **'What is PVE?'**"
1105
+ ))
1106
  }
1107
  })
1108
+
1109
+ # ---- Chat display ----
1110
  output$chat_display <- renderUI({
1111
  messages <- values$chat_messages
1112
  if (length(messages) == 0) return(NULL)
1113
+
1114
  elems <- lapply(messages, function(msg) {
1115
+ content_html <- HTML(gsub("\n", "<br>", htmltools::htmlEscape(msg$content)))
1116
+
1117
+ meta_content <- tagList(
1118
+ span(msg$time),
1119
+ if (!is.null(msg$model) && msg$role == "assistant")
1120
+ span(class = "model-tag", paste0("[", msg$model, "]"))
1121
+ )
1122
+
1123
  div(class = paste("chat-msg", msg$role),
1124
+ div(class = "chat-bubble", content_html),
1125
+ div(class = "chat-meta", meta_content))
 
1126
  })
1127
+
1128
  if (values$is_typing) {
1129
  elems <- c(elems, list(
1130
  div(class = "chat-msg assistant",
 
1133
  }
1134
  do.call(tagList, elems)
1135
  })
1136
+
1137
+ # ============================================================
1138
+ # DATA LOADING
1139
+ # ============================================================
1140
+
1141
  observeEvent(input$genotype_file, {
1142
  req(input$genotype_file)
1143
  tryCatch({
1144
  all_data <- readLines(input$genotype_file$datapath)
1145
  if (length(all_data) < 4) { showNotification("Genotype file must have at least 4 rows", type = "error"); return() }
1146
+
1147
  header <- strsplit(all_data[1], ",")[[1]]
1148
  chromosome_row <- strsplit(all_data[2], ",")[[1]]
1149
  position_row <- strsplit(all_data[3], ",")[[1]]
1150
+
1151
  genotype_data <- read.csv(text = all_data[-(1:3)], header = FALSE)
1152
  colnames(genotype_data) <- header
1153
  rownames(genotype_data) <- genotype_data[, 1]
1154
  genotype_data <- genotype_data[, -1]
1155
+
1156
  for (col in colnames(genotype_data))
1157
  genotype_data[[col]] <- as.numeric(as.character(genotype_data[[col]]))
1158
+
1159
  values$all_markers <- data.frame(
1160
  Marker = colnames(genotype_data),
1161
  Chromosome = chromosome_row[-1],
1162
  Position = as.numeric(position_row[-1]),
1163
  stringsAsFactors = FALSE)
1164
+
1165
+ values$genotype_data <- genotype_data
1166
+ values$chromosome_info <- chromosome_row[-1]
1167
+ values$position_info <- as.numeric(position_row[-1])
1168
+
1169
  showNotification("Genotype data loaded", type = "message")
1170
+ add_message("assistant", paste0("\u2705 Loaded genotype data: **", ncol(genotype_data), " markers**, **", nrow(genotype_data), " samples**"))
1171
  }, error = function(e) showNotification(paste("Error:", e$message), type = "error"))
1172
  })
1173
+
1174
  observeEvent(input$phenotype_file, {
1175
  req(input$phenotype_file)
1176
  tryCatch({
1177
  phenotype_data <- read.csv(input$phenotype_file$datapath)
1178
  rownames(phenotype_data) <- phenotype_data[, 1]
1179
  phenotype_data <- phenotype_data[, -1]
1180
+
1181
  for (col in colnames(phenotype_data))
1182
  phenotype_data[[col]] <- as.numeric(as.character(phenotype_data[[col]]))
1183
+
1184
  values$phenotype_data <- phenotype_data
1185
  updateSelectInput(session, "phenotype_column",
1186
  choices = colnames(phenotype_data),
1187
  selected = colnames(phenotype_data)[1])
1188
+
1189
  showNotification("Phenotype data loaded", type = "message")
1190
+ add_message("assistant", paste0("\u2705 Loaded phenotype data: **", ncol(phenotype_data), " traits**, **", nrow(phenotype_data), " samples**"))
1191
  }, error = function(e) showNotification(paste("Error:", e$message), type = "error"))
1192
  })
1193
+
1194
  observeEvent(input$pop_file, {
1195
  req(input$pop_file)
1196
  tryCatch({
 
1203
  add_message("assistant", paste0("\u2705 Loaded population data (", nrow(pop_data), " samples)"))
1204
  }, error = function(e) showNotification(paste("Error:", e$message), type = "error"))
1205
  })
1206
+
1207
  observeEvent(input$test_genotype_file, {
1208
  req(input$test_genotype_file)
1209
  tryCatch({
1210
+ all_data <- readLines(input$test_genotype_file$datapath)
1211
+ header <- strsplit(all_data[1], ",")[[1]]
1212
+
1213
+ genotype_data <- read.csv(text = all_data[-(1:3)], header = FALSE)
1214
  colnames(genotype_data) <- header
1215
  rownames(genotype_data) <- genotype_data[, 1]
1216
  genotype_data <- genotype_data[, -1]
1217
+
1218
  for (col in colnames(genotype_data))
1219
  genotype_data[[col]] <- as.numeric(as.character(genotype_data[[col]]))
1220
+
1221
  values$test_genotype_data <- genotype_data
1222
  values$has_test_data <- TRUE
1223
  showNotification("Test genotype data loaded", type = "message")
1224
  }, error = function(e) showNotification(paste("Error:", e$message), type = "error"))
1225
  })
1226
+
1227
  # ---- Data previews ----
1228
  output$geno_preview <- renderDT({ req(input$genotype_file); datatable(head(read.csv(input$genotype_file$datapath), 10), options = list(scrollX = TRUE, pageLength = 5)) })
1229
  output$pheno_preview <- renderDT({ req(input$phenotype_file); datatable(head(read.csv(input$phenotype_file$datapath), 10), options = list(scrollX = TRUE, pageLength = 5)) })
1230
  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)) })
1231
  output$pop_preview <- renderDT({ req(input$pop_file); datatable(head(read.csv(input$pop_file$datapath), 10), options = list(scrollX = TRUE, pageLength = 5)) })
1232
  output$predicted_test_pheno_preview <- renderDT({ req(values$predicted_test_phenotype_data); datatable(values$predicted_test_phenotype_data, options = list(scrollX = TRUE, pageLength = 5)) })
1233
+
1234
+ # ============================================================
1235
+ # QTL EFFECT CALCULATION
1236
+ # ============================================================
1237
+
1238
  calculate_qtl_effects <- function(genotype_matrix, phenotype_vector, marker_names) {
1239
  effects_list <- list()
1240
+
1241
  for (marker in marker_names) {
1242
  if (!marker %in% colnames(genotype_matrix)) next
1243
+
1244
  geno <- genotype_matrix[, marker]
1245
  pheno <- phenotype_vector
1246
  valid_idx <- !is.na(geno) & !is.na(pheno)
1247
  geno <- geno[valid_idx]
1248
  pheno <- pheno[valid_idx]
1249
+
1250
  if (length(unique(geno)) < 2) next
1251
+
1252
  lm_fit <- lm(pheno ~ geno)
1253
  additive_effect <- coef(lm_fit)[2]
1254
+
1255
  dominance_effect <- NA
1256
  if (length(unique(geno)) == 3) {
1257
  geno_means <- tapply(pheno, geno, mean, na.rm = TRUE)
 
1260
  geno_means[as.character(sort(unique(geno))[3])]) / 2
1261
  dominance_effect <- het_mean - midparent
1262
  }
1263
+
1264
  r_squared <- summary(lm_fit)$r.squared
1265
  se_additive <- tryCatch(summary(lm_fit)$coefficients[2, 2], error = function(e) NA)
1266
+
1267
  effects_list[[marker]] <- data.frame(
1268
  Marker = marker,
1269
  Additive_Effect = additive_effect,
 
1275
  N_Samples = length(pheno),
1276
  stringsAsFactors = FALSE)
1277
  }
1278
+
1279
  if (length(effects_list) == 0) return(NULL)
1280
  do.call(rbind, effects_list)
1281
  }
1282
+
1283
+ # ============================================================
1284
+ # MAIN QTL ANALYSIS
1285
+ # ============================================================
1286
+
1287
  observeEvent(input$run_analysis, {
1288
  req(values$genotype_data, values$phenotype_data, input$phenotype_column)
1289
  showNotification("Starting QTL analysis...", type = "message")
1290
  values$lod_threshold <- input$lod_threshold
1291
+
1292
  tryCatch({
1293
  common_samples <- intersect(rownames(values$genotype_data), rownames(values$phenotype_data))
1294
  if (length(common_samples) == 0) { showNotification("No common samples", type = "error"); return() }
1295
+
1296
  X <- values$genotype_data[common_samples, , drop = FALSE]
1297
  y <- as.numeric(values$phenotype_data[common_samples, input$phenotype_column])
1298
  nzv <- nearZeroVar(X)
1299
  if (length(nzv) > 0) X <- X[, -nzv, drop = FALSE]
1300
+
1301
  set.seed(123)
1302
  train_index <- createDataPartition(y, p = 1 - input$test_size, list = FALSE)
1303
  X_train <- X[train_index, , drop = FALSE]; X_val <- X[-train_index, , drop = FALSE]
1304
  y_train <- y[train_index]; y_val <- y[-train_index]
1305
+
1306
  model <- train(x = X_train, y = y_train, method = "rf",
1307
  trControl = trainControl(method = "cv", number = 5),
1308
  importance = TRUE, tuneLength = 3)
1309
+
1310
  values$model_fit <- model
1311
+
1312
  imp <- varImp(model, scale = FALSE)$importance
1313
  importance_scores <- data.frame(
1314
  Marker = rownames(imp),
 
1316
  Chromosome = values$chromosome_info[match(rownames(imp), colnames(X))],
1317
  Position = as.numeric(values$position_info[match(rownames(imp), colnames(X))]),
1318
  stringsAsFactors = FALSE)
1319
+
1320
  values$importance_scores <- importance_scores
1321
  lod_sig <- importance_scores[importance_scores$LOD > input$lod_threshold, , drop = FALSE]
1322
+
1323
  if (nrow(lod_sig) > 0) {
1324
  lod_sig$Low_Flank <- NA
1325
  lod_sig$High_Flank <- NA
1326
+
1327
  for (i in 1:nrow(lod_sig)) {
1328
  chr_m <- values$all_markers[values$all_markers$Chromosome == lod_sig$Chromosome[i], ]
1329
  chr_m <- chr_m[order(chr_m$Position), ]
 
1333
  lod_sig$High_Flank[i] <- if (idx < nrow(chr_m)) chr_m$Marker[idx + 1] else lod_sig$Marker[i]
1334
  }
1335
  }
1336
+
1337
  values$lod_scores_train <- lod_sig
1338
  qtl_fx <- calculate_qtl_effects(X_train, y_train, lod_sig$Marker)
1339
+
1340
  if (!is.null(qtl_fx)) {
1341
  values$qtl_effects_train <- merge(lod_sig, qtl_fx, by = "Marker")
1342
  } else {
 
1346
  values$lod_scores_train <- data.frame(Message = paste("No QTLs above LOD", input$lod_threshold))
1347
  values$qtl_effects_train <- data.frame(Message = paste("No QTLs above LOD", input$lod_threshold))
1348
  }
1349
+
1350
  y_train_pred <- predict(model, X_train)
1351
  y_val_pred <- predict(model, X_val)
1352
  train_r2 <- 1 - sum((y_train - y_train_pred)^2) / sum((y_train - mean(y_train))^2)
1353
  val_r2 <- 1 - sum((y_val - y_val_pred)^2) / sum((y_val - mean(y_val))^2)
1354
+
1355
  values$performance_metrics <- data.frame(
1356
  Metric = c("R\u00b2 (Train)", "R (Train)", "R\u00b2 (Validation)", "R (Validation)"),
1357
  Value = c(train_r2, cor(y_train, y_train_pred), val_r2, cor(y_val, y_val_pred)),
1358
  stringsAsFactors = FALSE)
1359
+
1360
  values$train_predictions <- data.frame(Observed = y_train, Predicted = y_train_pred)
1361
  values$test_predictions <- data.frame(Observed = y_val, Predicted = y_val_pred)
1362
+
1363
  # Epistasis
1364
  if (nrow(lod_sig) > 0) {
1365
  sig_markers <- lod_sig$Marker[lod_sig$Marker %in% colnames(X_train)]
1366
  all_markers_v <- colnames(X_train)
1367
  epistasis_list <- list()
1368
+
1369
  withProgress(message = "Calculating epistasis...", value = 0, {
1370
  total <- length(sig_markers) * length(all_markers_v)
1371
  for (m1 in sig_markers) {
 
1389
  }
1390
  }
1391
  })
1392
+
1393
  if (length(epistasis_list) > 0) {
1394
+ epistasis_all <- do.call(rbind, epistasis_list)
1395
+ values$epistasis_all <- epistasis_all
1396
+ values$epistasis_sig <- epistasis_all[epistasis_all$Interaction_p < 0.05, ]
1397
  } else {
1398
  values$epistasis_all <- data.frame(Message = "No epistatic interactions")
1399
  values$epistasis_sig <- data.frame(Message = "No epistatic interactions")
1400
  }
1401
  }
1402
+
1403
  showNotification("QTL analysis completed!", type = "message")
1404
  n_qtl <- if (!is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train)) nrow(values$qtl_effects_train) else 0
1405
+ add_message("assistant", paste0(
1406
+ "\u2705 **QTL analysis complete!**\n\n",
1407
+ "\u2022 Found **", n_qtl, " QTLs** above LOD ", input$lod_threshold, "\n",
1408
+ "\u2022 Validation R\u00b2: **", round(val_r2, 3), "**\n\n",
1409
+ "Ask me about PVE, top QTLs, or next steps!"))
1410
  updateTabsetPanel(session, "nav", selected = "Results")
1411
+
1412
  }, error = function(e) showNotification(paste("Error:", e$message), type = "error"))
1413
  })
1414
+
1415
+ # ============================================================
1416
+ # DOMESTICATION ANALYSIS
1417
+ # ============================================================
1418
+
1419
  calculate_selection_metrics <- function(genotype_matrix, pop_data, marker_info) {
1420
  metrics_list <- list()
1421
+
1422
  for (marker in colnames(genotype_matrix)) {
1423
  geno <- genotype_matrix[, marker]
1424
  pop <- pop_data$population[match(rownames(genotype_matrix), pop_data$id)]
1425
  valid_idx <- !is.na(geno) & !is.na(pop)
1426
  geno <- geno[valid_idx]; pop <- pop[valid_idx]
1427
+
1428
  if (length(unique(pop)) < 2) next
1429
+ geno_dom <- geno[pop == "Domesticated"]
1430
  geno_wild <- geno[pop == "Wild"]
1431
  if (length(geno_dom) < 3 || length(geno_wild) < 3) next
1432
+
1433
+ freq_dom <- mean(geno_dom, na.rm = TRUE) / 2
1434
  freq_wild <- mean(geno_wild, na.rm = TRUE) / 2
1435
+ p_avg <- (freq_dom + freq_wild) / 2
1436
+
1437
  fst <- if (p_avg > 0 && p_avg < 1) {
1438
  f <- (freq_dom - freq_wild)^2 / (p_avg * (1 - p_avg))
1439
  f / (1 + f)
1440
  } else 0
1441
+
1442
  pi_dom <- 2 * freq_dom * (1 - freq_dom)
1443
  pi_wild <- 2 * freq_wild * (1 - freq_wild)
1444
  n_dom <- length(geno_dom)
1445
  n_wild <- length(geno_wild)
1446
+
1447
  tajima_d_dom <- (pi_dom - 1/n_dom) / sqrt(var(geno_dom) /n_dom)
1448
  tajima_d_wild <- (pi_wild - 1/n_wild) / sqrt(var(geno_wild)/n_wild)
1449
+
1450
  marker_row <- marker_info[marker_info$Marker == marker, ]
1451
  metrics_list[[marker]] <- data.frame(
1452
  Marker = marker,
 
1456
  Tajima_D_Dom = tajima_d_dom, Tajima_D_Wild = tajima_d_wild,
1457
  stringsAsFactors = FALSE)
1458
  }
1459
+
1460
  if (length(metrics_list) == 0) return(NULL)
1461
  do.call(rbind, metrics_list)
1462
  }
1463
+
1464
  observeEvent(input$run_domestication, {
1465
  req(values$genotype_data, values$pop_data, values$all_markers)
1466
  tryCatch({
1467
  common_samples <- intersect(rownames(values$genotype_data), values$pop_data$id)
1468
  if (length(common_samples) == 0) { showNotification("No common samples", type = "error"); return() }
1469
+
1470
  X <- values$genotype_data[common_samples, , drop = FALSE]
1471
  pop_subset <- values$pop_data[values$pop_data$id %in% common_samples, ]
1472
  sel_metrics <- calculate_selection_metrics(X, pop_subset, values$all_markers)
1473
+
1474
  if (is.null(sel_metrics)) { showNotification("Could not calculate selection metrics", type = "error"); return() }
1475
+
1476
  sel_metrics$Significant <-
1477
  sel_metrics$Fst > input$fst_threshold |
1478
  sel_metrics$Tajima_D_Dom < input$tajima_threshold |
1479
  sel_metrics$Tajima_D_Wild < input$tajima_threshold
1480
+
1481
  values$selection_metrics <- sel_metrics
1482
  showNotification("Domestication analysis completed!", type = "message")
1483
  n_sig <- sum(sel_metrics$Significant, na.rm = TRUE)
1484
+ add_message("assistant", paste0("\u2705 Domestication analysis complete!\n\n\u2022 Found **", n_sig, " markers** with selection signatures"))
1485
  }, error = function(e) showNotification(paste("Error:", e$message), type = "error"))
1486
  })
1487
+
1488
+ # ============================================================
1489
+ # PREDICT TEST PHENOTYPES
1490
+ # ============================================================
1491
+
1492
  observeEvent(input$predict_test_phenotype, {
1493
  req(values$model_fit, values$test_genotype_data)
1494
  tryCatch({
1495
  common_markers <- intersect(colnames(values$test_genotype_data), colnames(values$genotype_data))
1496
  if (length(common_markers) == 0) { showNotification("No common markers", type = "error"); return() }
1497
+
1498
  X_test <- values$test_genotype_data[, common_markers, drop = FALSE]
1499
  predictions <- predict(values$model_fit, newdata = X_test)
1500
+
1501
  values$predicted_test_phenotype_data <- data.frame(
1502
  id = rownames(X_test),
1503
  Predicted_Phenotype = as.numeric(predictions),
1504
  stringsAsFactors = FALSE)
1505
+
1506
  showNotification("Predictions completed!", type = "message")
1507
  }, error = function(e) showNotification(paste("Error:", e$message), type = "error"))
1508
  })
1509
+
1510
+ # ============================================================
1511
+ # MANHATTAN PLOT HELPER
1512
+ # ============================================================
1513
+
1514
  create_manhattan <- function(data, y_col, title, threshold, y_label = y_col) {
1515
  if (is.null(data) || nrow(data) == 0 || "Message" %in% colnames(data))
1516
  return(plot_ly() %>% layout(title = "No data available",
1517
  plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e")))
1518
+
1519
  plot_data <- data[!is.na(data[[y_col]]), ]
1520
  if (nrow(plot_data) == 0)
1521
  return(plot_ly() %>% layout(title = "No valid data",
1522
  plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e")))
1523
+
1524
  chroms <- unique(plot_data$Chromosome)
1525
  chrom_pos <- data.frame()
1526
  for (i in seq_along(chroms)) {
 
1531
  chrom_pos <- rbind(chrom_pos, chr_data)
1532
  }
1533
  }
1534
+
1535
  p <- plot_ly() %>%
1536
  add_trace(data = chrom_pos, x = ~PosScaled, y = as.formula(paste0("~", y_col)),
1537
  type = "scatter", mode = "markers", color = ~factor(Chromosome),
 
1539
  text = ~paste("Marker:", Marker, "<br>Chr:", Chromosome, "<br>Pos:", Position,
1540
  "<br>", y_label, ":", round(get(y_col), 3)),
1541
  hoverinfo = "text", showlegend = FALSE)
1542
+
1543
  if (!is.null(threshold) && !is.na(threshold))
1544
  p <- p %>% add_segments(
1545
  x = min(chrom_pos$PosScaled, na.rm = TRUE), xend = max(chrom_pos$PosScaled, na.rm = TRUE),
1546
  y = threshold, yend = threshold,
1547
  line = list(color = "red", dash = "dash", width = 1), name = "Threshold")
1548
+
1549
  p %>% layout(title = title,
1550
  xaxis = list(title = "Chromosome",
1551
  ticktext = chroms,
 
1554
  yaxis = list(title = y_label),
1555
  plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))
1556
  }
1557
+
1558
+ # ============================================================
1559
+ # PLOTS
1560
+ # ============================================================
1561
+
1562
  output$lod_plot_2d <- renderPlotly({
1563
  req(values$importance_scores)
1564
  create_manhattan(values$importance_scores, "LOD", "QTL Manhattan Plot", input$lod_threshold, "LOD Score")
1565
  })
1566
+
1567
  output$fst_plot <- renderPlotly({
1568
  req(values$selection_metrics)
1569
  create_manhattan(values$selection_metrics, "Fst", "Fst Manhattan Plot", input$fst_threshold, "Fst")
1570
  })
1571
+
1572
  output$tajima_plot <- renderPlotly({
1573
  req(values$selection_metrics)
1574
  if ("Message" %in% colnames(values$selection_metrics))
1575
  return(plot_ly() %>% layout(title = "No data available", plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e")))
1576
+
1577
  data <- values$selection_metrics
1578
  chroms <- unique(data$Chromosome)
1579
  chrom_pos <- data.frame()
 
1585
  chrom_pos <- rbind(chrom_pos, chr_data)
1586
  }
1587
  }
1588
+
1589
  plot_ly() %>%
1590
  add_trace(data = chrom_pos, x = ~PosScaled, y = ~Tajima_D_Dom, type = "scatter", mode = "markers",
1591
  name = "Domesticated", marker = list(size = 5, color = "#58a6ff", opacity = 0.7),
 
1604
  yaxis = list(title = "Tajima's D"),
1605
  plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))
1606
  })
1607
+
1608
  output$performance_plot <- renderPlotly({
1609
  req(values$performance_metrics)
1610
  plot_ly(data = values$performance_metrics, x = ~Metric, y = ~Value, type = "bar",
 
1614
  yaxis = list(title = "Value", range = c(0, 1.1)),
1615
  plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))
1616
  })
1617
+
1618
  output$regression_plot_train <- renderPlotly({
1619
  req(values$train_predictions)
1620
  plot_ly(data = values$train_predictions, x = ~Observed, y = ~Predicted,
 
1624
  layout(title = "Training Set", xaxis = list(title = "Observed"), yaxis = list(title = "Predicted"),
1625
  plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))
1626
  })
1627
+
1628
  output$regression_plot_test <- renderPlotly({
1629
  req(values$test_predictions)
1630
  plot_ly(data = values$test_predictions, x = ~Observed, y = ~Predicted,
 
1634
  layout(title = "Validation Set", xaxis = list(title = "Observed"), yaxis = list(title = "Predicted"),
1635
  plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))
1636
  })
1637
+
1638
  output$epistasis_heatmap <- renderPlotly({
1639
  req(values$epistasis_all)
1640
  if ("Message" %in% colnames(values$epistasis_all))
1641
  return(plot_ly() %>% layout(title = values$epistasis_all$Message[1],
1642
  plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e")))
1643
+
1644
  qtls <- unique(values$epistasis_all$QTL1)
1645
  markers <- unique(values$epistasis_all$QTL2)
1646
  p_mat <- matrix(NA, nrow = length(qtls), ncol = length(markers),
 
1648
  for (i in 1:nrow(values$epistasis_all))
1649
  p_mat[values$epistasis_all$QTL1[i], values$epistasis_all$QTL2[i]] <-
1650
  -log10(values$epistasis_all$Interaction_p[i])
1651
+
1652
  plot_ly(x = colnames(p_mat), y = rownames(p_mat), z = p_mat,
1653
  type = "heatmap", colorscale = "Viridis",
1654
  hovertemplate = "QTL: %{y}<br>Marker: %{x}<br>-log10(p): %{z:.2f}") %>%
 
1656
  xaxis = list(title = "Marker", tickangle = 45), yaxis = list(title = "QTL"),
1657
  plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))
1658
  })
1659
+
1660
+ # ============================================================
1661
+ # TABLES
1662
+ # ============================================================
1663
+
1664
  output$qtl_effects_table_train <- renderDT({
1665
  req(values$qtl_effects_train)
1666
  if ("Message" %in% colnames(values$qtl_effects_train))
1667
  return(datatable(data.frame(Status = values$qtl_effects_train$Message[1]), options = list(dom = "t")))
1668
+
1669
  display_cols <- intersect(
1670
  c("Marker", "Chromosome", "Position", "LOD", "Additive_Effect", "PVE_Percent", "Low_Flank", "High_Flank"),
1671
  colnames(values$qtl_effects_train))
 
1673
  datatable(df, options = list(pageLength = 10, scrollX = TRUE), rownames = FALSE) %>%
1674
  formatRound(intersect(c("LOD", "Additive_Effect", "PVE_Percent"), colnames(df)), 3)
1675
  })
1676
+
1677
  output$epistasis_table <- renderDT({
1678
  req(values$epistasis_sig)
1679
  if ("Message" %in% colnames(values$epistasis_sig))
 
1682
  options = list(pageLength = 10, scrollX = TRUE), rownames = FALSE) %>%
1683
  formatSignif(columns = c("Interaction_p", "Effect_Size"), digits = 4)
1684
  })
1685
+
1686
  output$selection_table <- renderDT({
1687
  req(values$selection_metrics)
1688
  if ("Message" %in% colnames(values$selection_metrics))
1689
  return(datatable(data.frame(Status = values$selection_metrics$Message[1]), options = list(dom = "t")))
1690
+
1691
  df <- values$selection_metrics
1692
  if (!is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train))
1693
  df$QTL_Overlap <- df$Marker %in% values$qtl_effects_train$Marker
1694
+
1695
  display_cols <- intersect(
1696
  c("Marker", "Chromosome", "Fst", "Pi_Dom", "Pi_Wild", "Tajima_D_Dom", "Significant", "QTL_Overlap"),
1697
  colnames(df))
1698
  datatable(df[order(-df$Fst), display_cols], options = list(pageLength = 10, scrollX = TRUE), rownames = FALSE) %>%
1699
  formatRound(c("Fst", "Pi_Dom", "Pi_Wild", "Tajima_D_Dom"), 3)
1700
  })
1701
+
1702
+ # ============================================================
1703
+ # CHROMOSOME VISUALIZATION
1704
+ # ============================================================
1705
+
1706
  output$chromosome_viz <- renderUI({
1707
  req(values$lod_scores_train, values$all_markers)
1708
  if ("Message" %in% colnames(values$lod_scores_train))
1709
  return(div(class = "alert alert-info", values$lod_scores_train$Message[1]))
1710
+
1711
  chromosomes <- unique(values$lod_scores_train$Chromosome)
1712
  tagList(lapply(chromosomes, function(chr) {
1713
  chr_markers <- values$all_markers[values$all_markers$Chromosome == chr, ]
1714
  chr_markers <- chr_markers[order(chr_markers$Position), ]
1715
  chr_qtls <- values$lod_scores_train[values$lod_scores_train$Chromosome == chr, ]
1716
+
1717
  sel_markers <- NULL
1718
  if (!is.null(values$selection_metrics) && !"Message" %in% colnames(values$selection_metrics))
1719
  sel_markers <- values$selection_metrics[
1720
  values$selection_metrics$Chromosome == chr & values$selection_metrics$Significant, ]
1721
+
1722
  min_pos <- min(chr_markers$Position, na.rm = TRUE)
1723
  max_pos <- max(chr_markers$Position, na.rm = TRUE)
1724
  range_pos <- max_pos - min_pos
1725
+
1726
  div(class = "chromosome-container",
1727
  div(class = "chromosome-title", paste("Chromosome", chr)),
1728
  div(class = "chromosome",
 
1730
  marker <- chr_markers[i, ]
1731
  left <- if (range_pos > 0) ((marker$Position - min_pos) / range_pos) * 100
1732
  else (i / nrow(chr_markers)) * 100
1733
+
1734
  marker_class <- "chromosome-marker"
1735
  if (marker$Marker %in% chr_qtls$Marker) {
1736
  marker_class <- paste(marker_class, "significant")
 
1748
  )
1749
  }))
1750
  })
1751
+
1752
  # ---- Simulation animations ----
1753
  observeEvent(input$simulate_btn, session$sendCustomMessage("simulateQTLDiscovery", list()))
1754
  observeEvent(input$reset_btn, session$sendCustomMessage("resetAnimation", list()))
1755
+
1756
+ # ============================================================
1757
+ # INTERPRETATION OUTPUTS
1758
+ # ============================================================
1759
+
1760
  output$analysis_summary <- renderUI({
1761
  has_qtl <- !is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train)
1762
  has_perf <- !is.null(values$performance_metrics)
1763
+ has_epi <- !is.null(values$epistasis_sig) && !"Message" %in% colnames(values$epistasis_sig) && nrow(values$epistasis_sig) > 0
1764
  has_sel <- !is.null(values$selection_metrics) && !"Message" %in% colnames(values$selection_metrics)
1765
+
1766
  n_qtl <- if (has_qtl) nrow(values$qtl_effects_train) else 0
1767
  n_epi <- if (has_epi) nrow(values$epistasis_sig) else 0
1768
  n_sel <- if (has_sel) sum(values$selection_metrics$Significant, na.rm = TRUE) else 0
1769
  val_r2 <- if (has_perf) round(values$performance_metrics$Value[values$performance_metrics$Metric == "R\u00b2 (Validation)"], 3) else "N/A"
1770
+
1771
  div(class = "interpretation-section",
1772
  tags$h5("Analysis Summary"),
1773
  tags$p(paste("Found", n_qtl, "QTLs above LOD", input$lod_threshold,
 
1775
  if (has_epi) paste0("with ", n_epi, " epistatic interactions"),
1776
  if (has_sel) paste0("and ", n_sel, " selection signatures."))))
1777
  })
1778
+
1779
  output$qtl_interpretation <- renderUI({
1780
  if (is.null(values$qtl_effects_train) || "Message" %in% colnames(values$qtl_effects_train))
1781
  return(div(class = "interpretation-section", tags$h5("QTL Significance"), tags$p("No significant QTLs detected.")))
1782
+
1783
  top_qtl <- values$qtl_effects_train[which.max(values$qtl_effects_train$LOD), ]
1784
  div(class = "interpretation-section",
1785
  tags$h5("QTL Significance"),
1786
  tags$p(paste("Top QTL:", top_qtl$Marker, "(Chr", top_qtl$Chromosome, ") with LOD =", round(top_qtl$LOD, 2))))
1787
  })
1788
+
1789
  output$effect_interpretation <- renderUI({
1790
  if (is.null(values$qtl_effects_train) || "Message" %in% colnames(values$qtl_effects_train))
1791
  return(div(class = "interpretation-section", tags$h5("Effect Sizes"), tags$p("No QTL effects to interpret.")))
1792
+
1793
  top_pve <- values$qtl_effects_train[which.max(values$qtl_effects_train$PVE_Percent), ]
1794
  div(class = "interpretation-section",
1795
  tags$h5("Effect Sizes"),
1796
  tags$p(paste("Largest effect:", top_pve$Marker, "explains", round(top_pve$PVE_Percent, 1), "% of variance")))
1797
  })
1798
+
1799
  output$epistasis_interpretation <- renderUI({
1800
  if (is.null(values$epistasis_sig) || "Message" %in% colnames(values$epistasis_sig) || nrow(values$epistasis_sig) == 0)
1801
  return(div(class = "interpretation-section", tags$h5("Epistasis"), tags$p("No significant epistatic interactions detected.")))
1802
+
1803
  top_epi <- values$epistasis_sig[which.min(values$epistasis_sig$Interaction_p), ]
1804
  div(class = "interpretation-section",
1805
  tags$h5("Epistasis"),
1806
  tags$p(paste("Detected", nrow(values$epistasis_sig), "interactions. Strongest:",
1807
  top_epi$QTL1, "x", top_epi$QTL2, "(p =", format.pval(top_epi$Interaction_p), ")")))
1808
  })
1809
+
1810
  output$recommendations <- renderUI({
1811
  has_qtl <- !is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train)
1812
  recs <- if (has_qtl) {
 
1822
  tags$h5("Recommendations"),
1823
  tags$ul(lapply(recs, tags$li), style = "color:#8b949e;"))
1824
  })
1825
+
1826
+ # ============================================================
1827
+ # DOWNLOAD HANDLERS
1828
+ # ============================================================
1829
+
1830
  output$download_train_results <- downloadHandler(
1831
  filename = function() paste0("qtl_results_", Sys.Date(), ".xlsx"),
1832
  content = function(file) {
 
1838
  write_xlsx(sheets, file)
1839
  }
1840
  )
1841
+
1842
  output$download_selection <- downloadHandler(
1843
  filename = function() paste0("selection_", Sys.Date(), ".xlsx"),
1844
  content = function(file) {
 
1852
  }
1853
 
1854
  # ============================================================
1855
+ # RUN APP
1856
  # ============================================================
1857
 
1858
  shinyApp(ui = ui, server = server)