International Rice Research Institute commited on
Commit
738442e
·
verified ·
1 Parent(s): 8843d2e

Update app.R

Browse files
Files changed (1) hide show
  1. app.R +280 -487
app.R CHANGED
@@ -33,115 +33,67 @@ print("===================================")
33
 
34
  # ============================================================
35
  # AVAILABLE MODELS CONFIGURATION
36
- # Valid providers for HF Router: sambanova, together, fireworks-ai,
37
- # nebius, hyperbolic, novita, groq, cerebras, featherless-ai, hf-inference
38
- # Format: "model-id:provider" — never use ":auto"
39
  # ============================================================
40
 
41
  available_models <- list(
42
-
43
- # ── SambaNova (fastest, free tier) ──────────────────────
44
  list(
45
  id = "meta-llama/Llama-3.1-8B-Instruct:sambanova",
46
- label = "Llama 3.1 8B",
47
- provider = "SambaNova",
48
  tier = "free"
49
  ),
50
  list(
51
  id = "meta-llama/Llama-3.3-70B-Instruct:sambanova",
52
- label = "Llama 3.3 70B",
53
- provider = "SambaNova",
54
  tier = "free"
55
  ),
56
  list(
57
  id = "Qwen/Qwen2.5-72B-Instruct:sambanova",
58
- label = "Qwen 2.5 72B",
59
- provider = "SambaNova",
60
  tier = "free"
61
  ),
62
- list(
63
- id = "deepseek-ai/DeepSeek-V3-0324:sambanova",
64
- label = "DeepSeek-V3-0324",
65
- provider = "SambaNova",
66
- tier = "free"
67
- ),
68
-
69
- # ── Together AI ─────────────────────────────────────────
70
  list(
71
  id = "meta-llama/Llama-3.2-3B-Instruct:together",
72
- label = "Llama 3.2 3B",
73
- provider = "Together",
74
  tier = "free"
75
  ),
76
  list(
77
  id = "Qwen/Qwen2.5-7B-Instruct:together",
78
- label = "Qwen 2.5 7B",
79
- provider = "Together",
80
  tier = "free"
81
  ),
 
82
  list(
83
- id = "deepseek-ai/DeepSeek-V3-0324:together",
84
- label = "DeepSeek-V3-0324",
85
- provider = "Together",
86
- tier = "paid"
87
- ),
88
-
89
- # ── Nebius AI Studio ────────────────────────────────────
90
- list(
91
- id = "deepseek-ai/DeepSeek-V3-0324:nebius",
92
- label = "DeepSeek-V3-0324",
93
- provider = "Nebius",
94
- tier = "paid"
95
- ),
96
- list(
97
- id = "meta-llama/Llama-3.3-70B-Instruct:nebius",
98
- label = "Llama 3.3 70B",
99
- provider = "Nebius",
100
- tier = "paid"
101
- ),
102
-
103
- # ── Fireworks AI ────────────────────────────────────────
104
- list(
105
- id = "deepseek-ai/DeepSeek-V3-0324:fireworks-ai",
106
- label = "DeepSeek-V3-0324",
107
- provider = "Fireworks",
108
- tier = "paid"
109
- ),
110
-
111
- # ── Groq (very fast) ────────────────────────────────────
112
- list(
113
- id = "meta-llama/Llama-3.3-70B-Instruct:groq",
114
- label = "Llama 3.3 70B",
115
- provider = "Groq",
116
  tier = "free"
117
  ),
118
  list(
119
- id = "meta-llama/Llama-3.1-8B-Instruct:groq",
120
- label = "Llama 3.1 8B",
121
- provider = "Groq",
122
- tier = "free"
123
- ),
124
-
125
- # ── Cerebras ────────────────────────────────────────────
126
- list(
127
- id = "meta-llama/Llama-3.1-8B-Instruct:cerebras",
128
- label = "Llama 3.1 8B",
129
- provider = "Cerebras",
130
  tier = "free"
131
  ),
132
-
133
- # ── HF Inference API ────────────────────────────────────
134
  list(
135
- id = "Qwen/Qwen2.5-7B-Instruct:hf-inference",
136
- label = "Qwen 2.5 7B",
137
- provider = "HF Inference",
138
  tier = "free"
139
  )
 
 
 
140
  )
141
 
142
  model_choices <- setNames(
143
  sapply(available_models, function(m) m$id),
144
- sapply(available_models, function(m) paste0("[", m$provider, "] ", m$label, " (", m$tier, ")"))
145
  )
146
 
147
  # ============================================================
@@ -160,7 +112,7 @@ default_model <- "meta-llama/Llama-3.2-3B-Instruct:together"
160
 
161
  test_api_connection <- function(model_id = default_model) {
162
  if (!token_exists) return(list(success = FALSE, error = "No token found"))
163
-
164
  tryCatch({
165
  response <- POST(
166
  url = HF_API_URL,
@@ -176,10 +128,10 @@ test_api_connection <- function(model_id = default_model) {
176
  encode = "json",
177
  timeout(15)
178
  )
179
-
180
  status <- status_code(response)
181
  if (status == 200) return(list(success = TRUE))
182
-
183
  err <- tryCatch(content(response, "text", encoding = "UTF-8"),
184
  error = function(e) paste("Status:", status))
185
  return(list(success = FALSE,
@@ -201,56 +153,38 @@ if (use_hf_api) {
201
  # QUERY FUNCTION
202
  # ============================================================
203
 
204
- query_hf_api <- function(prompt, model_id = default_model, max_length = 500,
205
- temperature = 0.7, image_b64 = NULL, image_mime = "image/png") {
206
  if (!token_exists) return(list(success = FALSE, error = "HF_API_TOKEN not set"))
207
-
208
  tryCatch({
209
-
210
- # Build user content: plain text OR vision (image_url + text parts)
211
- user_content <- if (!is.null(image_b64)) {
212
- list(
213
- list(type = "image_url",
214
- image_url = list(url = paste0("data:", image_mime, ";base64,", image_b64))),
215
- list(type = "text", text = prompt)
216
- )
217
- } else {
218
- prompt # plain scalar string; auto_unbox keeps it as-is
219
- }
220
-
221
- body_list <- list(
222
- model = model_id,
223
- messages = list(
224
- list(role = "system",
225
- content = paste("You are an expert bioinformatics assistant specializing in QTL analysis.",
226
- "When an image is provided, describe and interpret it in a QTL/genomics context.",
227
- "Be concise and helpful.")),
228
- list(role = "user",
229
- content = user_content)
230
- ),
231
- max_tokens = as.integer(max_length),
232
- temperature = temperature
233
- )
234
-
235
  response <- POST(
236
  url = HF_API_URL,
237
  add_headers(
238
  Authorization = paste("Bearer", HF_API_TOKEN),
239
  "Content-Type" = "application/json"
240
  ),
241
- body = toJSON(body_list, auto_unbox = TRUE),
242
- encode = "json",
 
 
 
 
 
 
 
 
 
243
  timeout(60)
244
  )
245
-
246
  status <- status_code(response)
247
-
248
  if (status == 200) {
249
  result <- content(response, as = "parsed", encoding = "UTF-8")
250
  text <- result$choices[[1]]$message$content
251
  return(list(success = TRUE, text = text))
252
  }
253
-
254
  err <- tryCatch(content(response, "text", encoding = "UTF-8"),
255
  error = function(e) paste("Status:", status))
256
  return(list(success = FALSE,
@@ -264,15 +198,15 @@ query_hf_api <- function(prompt, model_id = default_model, max_length = 500,
264
 
265
  build_system_prompt <- function(rv) {
266
  context_parts <- c("CURRENT ANALYSIS RESULTS:")
267
-
268
  if (!is.null(rv$qtl_effects_train) && !"Message" %in% colnames(rv$qtl_effects_train)) {
269
  n_qtl <- nrow(rv$qtl_effects_train)
270
  total_pve <- sum(rv$qtl_effects_train$PVE_Percent, na.rm = TRUE)
271
-
272
  context_parts <- c(context_parts,
273
  sprintf("\nQTL Results: %d significant QTLs detected above LOD %.1f.", n_qtl, rv$lod_threshold),
274
  sprintf("Total variance explained by QTLs: %.1f%%.", total_pve))
275
-
276
  top_qtls <- head(rv$qtl_effects_train[order(-rv$qtl_effects_train$LOD), ], 3)
277
  context_parts <- c(context_parts, "\nTop QTLs:")
278
  for (i in 1:nrow(top_qtls)) {
@@ -282,7 +216,7 @@ build_system_prompt <- function(rv) {
282
  i, row$Marker, row$Chromosome, row$LOD, row$PVE_Percent, row$Additive_Effect))
283
  }
284
  }
285
-
286
  if (!is.null(rv$performance_metrics)) {
287
  pm <- rv$performance_metrics
288
  train_r2 <- pm$Value[pm$Metric == "R\u00b2 (Train)"]
@@ -292,7 +226,7 @@ build_system_prompt <- function(rv) {
292
  sprintf(" Training R\u00b2: %.3f", train_r2),
293
  sprintf(" Validation R\u00b2: %.3f", val_r2))
294
  }
295
-
296
  if (!is.null(rv$epistasis_sig) && !"Message" %in% colnames(rv$epistasis_sig) && nrow(rv$epistasis_sig) > 0) {
297
  n_epi <- nrow(rv$epistasis_sig)
298
  top_epi <- rv$epistasis_sig[order(rv$epistasis_sig$Interaction_p), ][1, ]
@@ -300,13 +234,13 @@ build_system_prompt <- function(rv) {
300
  sprintf("\nEpistasis: %d significant pairwise interactions detected.", n_epi),
301
  sprintf(" Strongest: %s x %s (p=%.4f)", top_epi$QTL1, top_epi$QTL2, top_epi$Interaction_p))
302
  }
303
-
304
  if (!is.null(rv$selection_metrics) && !"Message" %in% colnames(rv$selection_metrics)) {
305
  n_sig <- sum(rv$selection_metrics$Significant, na.rm = TRUE)
306
  context_parts <- c(context_parts,
307
  sprintf("\nDomestication: %d markers with selection signatures.", n_sig))
308
  }
309
-
310
  paste(context_parts, collapse = "\n")
311
  }
312
 
@@ -316,18 +250,18 @@ build_system_prompt <- function(rv) {
316
 
317
  enhanced_rule_response <- function(user_message, rv) {
318
  q <- tolower(trimws(user_message))
319
-
320
  has_qtl <- !is.null(rv$qtl_effects_train) && !"Message" %in% colnames(rv$qtl_effects_train)
321
  has_perf <- !is.null(rv$performance_metrics)
322
  has_epi <- !is.null(rv$epistasis_sig) && !"Message" %in% colnames(rv$epistasis_sig) && nrow(rv$epistasis_sig) > 0
323
  has_sel <- !is.null(rv$selection_metrics) && !"Message" %in% colnames(rv$selection_metrics)
324
-
325
  if (grepl("pve|variance explained|how much variance|percent variance|what is pve", q)) {
326
  if (has_qtl) {
327
  df <- rv$qtl_effects_train
328
  total_pve <- sum(df$PVE_Percent, na.rm = TRUE)
329
  top_pve <- df[which.max(df$PVE_Percent), ]
330
-
331
  response <- paste0(
332
  "\U0001f4ca **PVE (Phenotypic Variance Explained) Analysis**\n\n",
333
  "**Your Results:**\n",
@@ -339,7 +273,7 @@ enhanced_rule_response <- function(user_message, rv) {
339
  "\u2022 PVE: **", round(top_pve$PVE_Percent, 1), "%**\n",
340
  "\u2022 LOD: ", round(top_pve$LOD, 2), "\n\n"
341
  )
342
-
343
  if (top_pve$PVE_Percent > 10) {
344
  response <- paste0(response, "\U0001f4a1 This is a **major-effect QTL** (>10% PVE).\n\n")
345
  } else if (top_pve$PVE_Percent > 5) {
@@ -347,7 +281,7 @@ enhanced_rule_response <- function(user_message, rv) {
347
  } else {
348
  response <- paste0(response, "\U0001f4a1 This is a **minor-effect QTL** (<5% PVE).\n\n")
349
  }
350
-
351
  response <- paste0(response, "**All QTLs by PVE:**\n")
352
  df_sorted <- df[order(-df$PVE_Percent), ]
353
  for (i in 1:min(5, nrow(df_sorted))) {
@@ -359,19 +293,19 @@ enhanced_rule_response <- function(user_message, rv) {
359
  return("No QTL results yet. Please run the QTL analysis first to see PVE values.")
360
  }
361
  }
362
-
363
  if (grepl("model performance|r2|r squared|how good is my model|validation|negative r2", q)) {
364
  if (has_perf) {
365
  pm <- rv$performance_metrics
366
  train_r2 <- pm$Value[pm$Metric == "R\u00b2 (Train)"]
367
  val_r2 <- pm$Value[pm$Metric == "R\u00b2 (Validation)"]
368
-
369
  response <- paste0(
370
  "\U0001f4c8 **Model Performance Summary**\n\n",
371
  "\u2022 Training R\u00b2: **", round(train_r2, 3), "**\n",
372
  "\u2022 Validation R\u00b2: **", round(val_r2, 3), "**\n\n"
373
  )
374
-
375
  if (val_r2 < 0) {
376
  response <- paste0(response,
377
  "\u26a0\ufe0f **Your validation R\u00b2 is negative** (", round(val_r2, 3), ").\n\n",
@@ -395,12 +329,12 @@ enhanced_rule_response <- function(user_message, rv) {
395
  return("Run the QTL analysis first to see model performance metrics.")
396
  }
397
  }
398
-
399
  if (grepl("top qtl|best qtl|highest lod|significant qtl|list qtl|show qtl", q)) {
400
  if (has_qtl) {
401
  df <- rv$qtl_effects_train[order(-rv$qtl_effects_train$LOD), ]
402
  top5 <- head(df, 5)
403
-
404
  response <- "\U0001f3af **Top 5 QTLs by LOD Score**\n\n"
405
  for (i in 1:nrow(top5)) {
406
  row <- top5[i, ]
@@ -415,11 +349,11 @@ enhanced_rule_response <- function(user_message, rv) {
415
  return("No significant QTLs detected. Try lowering the LOD threshold.")
416
  }
417
  }
418
-
419
  if (grepl("next steps|what next|recommendations|suggest|advice|what should i do", q)) {
420
  if (has_qtl || has_perf || has_epi || has_sel) {
421
  response <- "\U0001f52c **Recommended Next Steps**\n\n"
422
-
423
  if (has_qtl) {
424
  top_qtl <- rv$qtl_effects_train[which.max(rv$qtl_effects_train$LOD), ]
425
  response <- paste0(response,
@@ -435,7 +369,7 @@ enhanced_rule_response <- function(user_message, rv) {
435
  response <- paste0(response, "**3. Domestication Analysis**\n",
436
  " \u2022 ", sum(rv$selection_metrics$Significant, na.rm = TRUE), " selection signatures\n\n")
437
  }
438
-
439
  response <- paste0(response,
440
  "**4. Functional Analysis**\n",
441
  " \u2022 Annotate QTL regions for candidate genes\n\n",
@@ -446,7 +380,7 @@ enhanced_rule_response <- function(user_message, rv) {
446
  return("Run the QTL analysis first to get recommendations.")
447
  }
448
  }
449
-
450
  available <- c()
451
  if (has_qtl) available <- c(available, paste(nrow(rv$qtl_effects_train), "QTLs"))
452
  if (has_perf) {
@@ -455,7 +389,7 @@ enhanced_rule_response <- function(user_message, rv) {
455
  }
456
  if (has_epi) available <- c(available, paste(nrow(rv$epistasis_sig), "interactions"))
457
  if (has_sel) available <- c(available, paste(sum(rv$selection_metrics$Significant), "selection signatures"))
458
-
459
  if (length(available) > 0) {
460
  return(paste0(
461
  "I can see you have: ", paste(available, collapse = ", "), ".\n\n",
@@ -465,9 +399,9 @@ enhanced_rule_response <- function(user_message, rv) {
465
  "\u2022 **Model performance**\n",
466
  "\u2022 **Next steps**"))
467
  }
468
-
469
  return(paste0(
470
- "\U0001f44b Hello! I'm your QTL analysis assistant.\n\n",
471
  "**I can help you with:**\n",
472
  "\u2022 Understanding PVE\n",
473
  "\u2022 Interpreting LOD scores\n",
@@ -480,43 +414,29 @@ enhanced_rule_response <- function(user_message, rv) {
480
  # AI RESPONSE GENERATION
481
  # ============================================================
482
 
483
- generate_ai_response <- function(user_message, rv, model_id = default_model,
484
- image_b64 = NULL, image_mime = "image/png") {
485
  context <- build_system_prompt(rv)
486
-
487
- if (token_exists) {
488
- # For image-only messages use a short prompt; otherwise include QTL context
489
- if (!is.null(image_b64) && nchar(trimws(user_message)) == 0) {
490
- prompt <- paste("Please analyse this image in the context of QTL / genomics research.",
491
- "Describe what you see and provide any relevant bioinformatics interpretation.")
492
- } else {
493
- prompt <- paste(
494
- "CONTEXT:", context,
495
- "\n\nUSER QUESTION:", user_message,
496
- "\n\nProvide a specific, helpful answer. Be concise but informative.",
497
- sep = "\n"
498
- )
499
- }
500
-
501
- result <- query_hf_api(prompt, model_id = model_id,
502
- image_b64 = image_b64, image_mime = image_mime)
503
-
504
  if (result$success) {
505
  return(result$text)
506
  } else {
507
- # If vision failed (model may not support it), tell the user clearly
508
- if (!is.null(image_b64)) {
509
- return(paste0("\u26a0\ufe0f This model does not support image input.\n\n",
510
- "Try a vision-capable model such as:\n",
511
- "\u2022 [SambaNova] Llama 3.3 70B\n",
512
- "\u2022 [Together] Llama 3.2 3B\n\n",
513
- "API error: ", result$error))
514
- }
515
  message("API Error: ", result$error)
516
  return(enhanced_rule_response(user_message, rv))
517
  }
518
  }
519
-
520
  return(enhanced_rule_response(user_message, rv))
521
  }
522
 
@@ -526,7 +446,7 @@ generate_ai_response <- function(user_message, rv, model_id = default_model,
526
 
527
  ui <- fluidPage(
528
  shinyjs::useShinyjs(),
529
-
530
  tags$head(
531
  tags$link(rel = "stylesheet", type = "text/css",
532
  href = "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css"),
@@ -710,11 +630,11 @@ ui <- fluidPage(
710
  .chat-file-bubble i { font-size: 14px; }
711
  "))
712
  ),
713
-
714
  navbarPage(
715
  title = tags$span(tags$i(class = "fas fa-dna", style = "margin-right:8px; color:#58a6ff;"), "QTL-Mapper AI"),
716
  id = "nav",
717
-
718
  # ---- Data Upload tab ----
719
  tabPanel("Data Upload", icon = icon("upload"),
720
  div(class = "main-header",
@@ -772,7 +692,7 @@ ui <- fluidPage(
772
  )
773
  )
774
  ),
775
-
776
  # ---- Domestication tab ----
777
  tabPanel("Domestication", icon = icon("leaf"),
778
  div(class = "main-header",
@@ -816,7 +736,7 @@ ui <- fluidPage(
816
  )
817
  )
818
  ),
819
-
820
  # ---- Results tab ----
821
  tabPanel("Results", icon = icon("chart-line"),
822
  div(class = "main-header",
@@ -857,7 +777,7 @@ ui <- fluidPage(
857
  ))
858
  )
859
  ),
860
-
861
  # ---- Interpretation tab ----
862
  tabPanel("Interpretation", icon = icon("lightbulb"),
863
  div(class = "main-header",
@@ -872,7 +792,7 @@ ui <- fluidPage(
872
  fluidRow(column(12, div(class = "card", div(class = "card-header", "Epistasis"), div(class = "card-body", uiOutput("epistasis_interpretation"))))),
873
  fluidRow(column(12, div(class = "card", div(class = "card-header", "Recommendations"), div(class = "card-body", uiOutput("recommendations")))))
874
  ),
875
-
876
  # ---- About tab ----
877
  tabPanel("About", icon = icon("info-circle"),
878
  div(class = "main-header",
@@ -897,18 +817,14 @@ ui <- fluidPage(
897
  tags$thead(tags$tr(
898
  tags$th(style = "text-align:left; padding:6px; border-bottom:1px solid #30363d; color:#58a6ff;", "Model"),
899
  tags$th(style = "text-align:left; padding:6px; border-bottom:1px solid #30363d; color:#58a6ff;", "Provider"),
900
- tags$th(style = "text-align:left; padding:6px; border-bottom:1px solid #30363d; color:#58a6ff;", "Model ID"),
901
  tags$th(style = "text-align:left; padding:6px; border-bottom:1px solid #30363d; color:#58a6ff;", "Tier")
902
  )),
903
  tags$tbody(
904
  lapply(available_models, function(m) {
905
- tier_color <- if (m$tier == "free") "#3fb950" else "#d29922"
906
  tags$tr(
907
  tags$td(style = "padding:6px; border-bottom:1px solid #21262d;", m$label),
908
  tags$td(style = "padding:6px; border-bottom:1px solid #21262d;", m$provider),
909
- tags$td(style = "padding:6px; border-bottom:1px solid #21262d; font-family:'IBM Plex Mono'; font-size:11px; color:#6e7681;",
910
- gsub(":.*$", "", m$id)),
911
- tags$td(style = paste0("padding:6px; border-bottom:1px solid #21262d; color:", tier_color, ";"), m$tier)
912
  )
913
  })
914
  )
@@ -931,13 +847,13 @@ ui <- fluidPage(
931
  )
932
  )
933
  ),
934
-
935
  # ============================================================
936
  # FLOATING CHAT PANEL (with model selector + file upload)
937
  # ============================================================
938
  tags$div(id = "chat-panel",
939
  tags$div(id = "chat-window",
940
-
941
  # Chat header
942
  tags$div(id = "chat-header",
943
  tags$div(class = "chat-header-top",
@@ -954,7 +870,7 @@ ui <- fluidPage(
954
  onclick = "document.getElementById('chat-window').classList.remove('open');",
955
  tags$i(class = "fas fa-times"))
956
  ),
957
-
958
  # Model selector row
959
  tags$div(class = "chat-model-selector",
960
  tags$label(tags$i(class = "fas fa-robot"), " Model:"),
@@ -966,7 +882,7 @@ ui <- fluidPage(
966
  actionButton("test_model_btn", "Test", class = "test-model-btn")
967
  )
968
  ),
969
-
970
  # Quick question buttons
971
  tags$div(class = "quick-questions",
972
  tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q','What is PVE?',{priority:'event'});", "PVE meaning"),
@@ -974,13 +890,13 @@ ui <- fluidPage(
974
  tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q','Why is my R2 negative?',{priority:'event'});","Negative R2"),
975
  tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q','What should I do next?',{priority:'event'});","Next steps")
976
  ),
977
-
978
  # Messages area
979
  tags$div(id = "chat_messages", uiOutput("chat_display")),
980
-
981
  # Footer
982
  tags$div(id = "chat-footer",
983
-
984
  # File upload row
985
  tags$div(class = "chat-file-row",
986
  tags$label(
@@ -988,7 +904,7 @@ ui <- fluidPage(
988
  tags$i(class = "fas fa-paperclip"),
989
  " Attach file",
990
  fileInput("chat_file_upload", label = NULL,
991
- accept = c(".csv", ".txt", ".tsv", ".xlsx", ".pdf", ".png", ".jpg", ".jpeg", ".gif", ".webp"),
992
  buttonLabel = "",
993
  placeholder = "",
994
  width = "0px")
@@ -998,12 +914,12 @@ ui <- fluidPage(
998
  onclick = "document.getElementById('chat_file_preview').style.display='none'; document.getElementById('chat_file_preview').innerHTML=''; Shiny.setInputValue('clear_chat_file', Math.random());",
999
  tags$i(class = "fas fa-times"))
1000
  ),
1001
-
1002
  # Text input
1003
  tags$textarea(id = "chat_input",
1004
  placeholder = "Ask about your results... (Enter to send)",
1005
  rows = "2"),
1006
-
1007
  # Action buttons
1008
  tags$div(class = "chat-actions",
1009
  actionButton("send_chat", "Send", icon = icon("paper-plane"), class = "btn-primary"),
@@ -1011,13 +927,13 @@ ui <- fluidPage(
1011
  )
1012
  )
1013
  ),
1014
-
1015
  # Toggle button
1016
  tags$button(id = "chat-toggle-btn",
1017
  onclick = "document.getElementById('chat-window').classList.toggle('open');",
1018
  tags$i(class = "fas fa-robot"))
1019
  ),
1020
-
1021
  # JS to show filename on file selection
1022
  tags$script(HTML("
1023
  $(document).on('change', '#chat_file_upload', function() {
@@ -1036,7 +952,7 @@ ui <- fluidPage(
1036
  # ============================================================
1037
 
1038
  server <- function(input, output, session) {
1039
-
1040
  values <- reactiveValues(
1041
  genotype_data = NULL,
1042
  phenotype_data = NULL,
@@ -1065,32 +981,29 @@ server <- function(input, output, session) {
1065
  current_model = default_model,
1066
  model_test_status = if (use_hf_api) "online" else "offline",
1067
  pending_file_content = NULL,
1068
- pending_file_name = NULL,
1069
- pending_image_b64 = NULL,
1070
- pending_image_mime = NULL,
1071
- pending_image_thumb = NULL # data URI for thumbnail preview
1072
  )
1073
-
1074
  # ---- Current selected model ----
1075
  observe({
1076
  req(input$selected_model)
1077
  values$current_model <- input$selected_model
1078
-
1079
  # Update status display
1080
  model_label <- names(model_choices)[model_choices == input$selected_model]
1081
  if (is.null(model_label) || length(model_label) == 0)
1082
  model_label <- gsub(".*/([^:]+):.*", "\\1", input$selected_model)
1083
-
1084
  shinyjs::html("model_status_text",
1085
  if (token_exists) paste("AI:", gsub(".*\\[(.*)\\]", "\\1", model_label), "- ready")
1086
  else "Rule-based mode (no token)")
1087
  })
1088
-
1089
  # ---- Test model button ----
1090
  observeEvent(input$test_model_btn, {
1091
  req(input$selected_model)
1092
  add_message("assistant", paste0("\u23f3 Testing model: **", gsub(".*/", "", input$selected_model), "**..."))
1093
-
1094
  result <- test_api_connection(input$selected_model)
1095
  if (result$success) {
1096
  add_message("assistant", paste0("\u2705 **", gsub(".*/", "", input$selected_model), "** is working! You can now chat with this model."))
@@ -1101,201 +1014,98 @@ server <- function(input, output, session) {
1101
  shinyjs::runjs("document.getElementById('model_status_dot').className = 'model-status-dot offline';")
1102
  }
1103
  })
1104
-
1105
  # ---- Chat helpers ----
1106
- add_message <- function(role, content, model_used = NULL,
1107
- image_thumb = NULL, image_name = NULL) {
1108
  timestamp <- format(Sys.time(), "%H:%M")
1109
  values$chat_messages <- c(values$chat_messages,
1110
- list(list(role = role,
1111
- content = content,
1112
- time = timestamp,
1113
- model = model_used,
1114
- image_thumb = image_thumb,
1115
- image_name = image_name)))
1116
  if (length(values$chat_messages) > 100)
1117
  values$chat_messages <- tail(values$chat_messages, 100)
1118
  session$sendCustomMessage("scrollChatBottom", list())
1119
  }
1120
-
1121
- process_message <- function(user_text,
1122
- file_content = NULL, file_name = NULL,
1123
- image_b64 = NULL, image_mime = NULL,
1124
- image_thumb = NULL) {
1125
- has_text <- nchar(trimws(user_text)) > 0
1126
- has_file <- !is.null(file_content)
1127
- has_image <- !is.null(image_b64)
1128
-
1129
- if (!has_text && !has_file && !has_image) return()
1130
-
1131
- # ── Build display message for user bubble ──
1132
- display_text <- user_text
1133
- if (has_file && nchar(trimws(file_content)) > 0) {
1134
- display_text <- paste0(user_text,
1135
- if (has_text) "\n\n" else "",
1136
- "\U0001f4ce ", file_name)
1137
- }
1138
- if (has_image) {
1139
- # We pass thumbnail separately so the bubble can render it
1140
- display_text <- paste0(if (has_text) user_text else "",
1141
- if (has_text) "\n" else "",
1142
- "\U0001f5bc\ufe0f ", file_name)
1143
  }
1144
-
1145
- add_message("user", display_text,
1146
- image_thumb = image_thumb, image_name = if (has_image) file_name else NULL)
1147
-
1148
  values$is_typing <- TRUE
1149
-
1150
  model_id <- isolate(values$current_model)
1151
-
1152
- # ── Build prompt (text + file context) ──
1153
- prompt_text <- user_text
1154
- if (has_file) {
1155
- prompt_text <- paste0(user_text,
1156
- if (has_text) "\n\n" else "",
1157
- "--- Attached file: ", file_name, " ---\n",
1158
- substr(file_content, 1, 3000),
1159
- if (nchar(file_content) > 3000) "\n[... truncated ...]" else "")
1160
- }
1161
- if (has_image && !has_text && !has_file) {
1162
- prompt_text <- "Please analyse this image in the context of QTL/genomics research."
1163
- }
1164
-
1165
- response <- generate_ai_response(prompt_text, values,
1166
- model_id = model_id,
1167
- image_b64 = image_b64,
1168
- image_mime = if (!is.null(image_mime)) image_mime else "image/png")
1169
-
1170
  values$is_typing <- FALSE
1171
  model_short <- gsub(".*/([^:]+):.*", "\\1", model_id)
1172
  add_message("assistant", response, model_used = if (token_exists) model_short else NULL)
1173
-
1174
- # Clear all pending attachments
1175
  values$pending_file_content <- NULL
1176
  values$pending_file_name <- NULL
1177
- values$pending_image_b64 <- NULL
1178
- values$pending_image_mime <- NULL
1179
- values$pending_image_thumb <- NULL
1180
  }
1181
-
1182
  # ---- Handle chat file upload ----
1183
  observeEvent(input$chat_file_upload, {
1184
  req(input$chat_file_upload)
1185
  file_path <- input$chat_file_upload$datapath
1186
  file_name <- input$chat_file_upload$name
1187
  ext <- tolower(tools::file_ext(file_name))
1188
-
1189
- # Reset previous pending files
1190
- values$pending_file_content <- NULL
1191
- values$pending_file_name <- NULL
1192
- values$pending_image_b64 <- NULL
1193
- values$pending_image_mime <- NULL
1194
- values$pending_image_thumb <- NULL
1195
-
1196
  tryCatch({
1197
- if (ext %in% c("png", "jpg", "jpeg", "gif", "webp", "bmp")) {
1198
- # ── IMAGE: read as base64, build data URI thumbnail ──
1199
- mime_map <- c(png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg",
1200
- gif = "image/gif", webp = "image/webp", bmp = "image/bmp")
1201
- mime_type <- unname(mime_map[ext])
1202
- if (is.na(mime_type)) mime_type <- "image/png"
1203
-
1204
- raw_bytes <- readBin(file_path, "raw", file.info(file_path)$size)
1205
- b64_string <- base64enc::base64encode(raw_bytes)
1206
- data_uri <- paste0("data:", mime_type, ";base64,", b64_string)
1207
-
1208
- values$pending_image_b64 <- b64_string
1209
- values$pending_image_mime <- mime_type
1210
- values$pending_image_thumb <- data_uri
1211
- values$pending_file_name <- file_name
1212
-
1213
- showNotification(paste0("Image ready: ", file_name), type = "message")
1214
-
1215
- } else if (ext %in% c("csv", "txt", "tsv")) {
1216
- # ── TEXT files: read lines ──
1217
- file_content <- paste(readLines(file_path, n = 200), collapse = "\n")
1218
- values$pending_file_content <- file_content
1219
- values$pending_file_name <- file_name
1220
-
1221
- } else if (ext == "xlsx") {
1222
- # ── EXCEL: read with readxl if available ──
1223
- if (requireNamespace("readxl", quietly = TRUE)) {
1224
- df <- readxl::read_excel(file_path)
1225
- file_content <- paste(capture.output(print(head(df, 20))), collapse = "\n")
1226
- values$pending_file_content <- paste0("[Excel: ", file_name, "]\n", file_content)
1227
- } else {
1228
- values$pending_file_content <- paste0("[Excel file: ", file_name,
1229
- " - install readxl to parse content]")
1230
- }
1231
- values$pending_file_name <- file_name
1232
-
1233
- } else if (ext == "pdf") {
1234
- # ── PDF: extract text with pdftools if available ──
1235
- if (requireNamespace("pdftools", quietly = TRUE)) {
1236
- txt <- pdftools::pdf_text(file_path)
1237
- file_content <- substr(paste(txt, collapse = "\n"), 1, 3000)
1238
- values$pending_file_content <- paste0("[PDF: ", file_name, "]\n", file_content)
1239
- } else {
1240
- values$pending_file_content <- paste0("[PDF file: ", file_name,
1241
- " - install pdftools to parse content]")
1242
- }
1243
- values$pending_file_name <- file_name
1244
-
1245
  } else {
1246
- values$pending_file_content <- paste0("[File: ", file_name, " (",
1247
- round(file.info(file_path)$size / 1024, 1), " KB)]")
1248
- values$pending_file_name <- file_name
1249
  }
1250
-
 
 
1251
  }, error = function(e) {
1252
  showNotification(paste("Could not read file:", e$message), type = "warning")
1253
  })
1254
  })
1255
-
1256
- # ---- Clear chat file / image ----
1257
  observeEvent(input$clear_chat_file, {
1258
  values$pending_file_content <- NULL
1259
  values$pending_file_name <- NULL
1260
- values$pending_image_b64 <- NULL
1261
- values$pending_image_mime <- NULL
1262
- values$pending_image_thumb <- NULL
1263
  })
1264
-
1265
  # ---- Send chat ----
1266
  observeEvent(input$send_chat, {
1267
- user_text <- trimws(input$chat_input)
1268
  file_content <- isolate(values$pending_file_content)
1269
  file_name <- isolate(values$pending_file_name)
1270
- image_b64 <- isolate(values$pending_image_b64)
1271
- image_mime <- isolate(values$pending_image_mime)
1272
- image_thumb <- isolate(values$pending_image_thumb)
1273
- img_name <- isolate(values$pending_file_name) # same field used for images
1274
-
1275
- has_anything <- nchar(user_text) > 0 || !is.null(file_content) || !is.null(image_b64)
1276
- if (!has_anything) return()
1277
-
1278
  updateTextAreaInput(session, "chat_input", value = "")
 
1279
  shinyjs::runjs("
1280
  document.getElementById('chat_file_preview').style.display = 'none';
1281
  document.getElementById('chat_file_preview').innerHTML = '';
1282
  ")
1283
-
1284
- process_message(user_text,
1285
- file_content = file_content,
1286
- file_name = file_name,
1287
- image_b64 = image_b64,
1288
- image_mime = image_mime,
1289
- image_thumb = image_thumb)
1290
  })
1291
-
1292
  observeEvent(input$quick_q, { req(input$quick_q); process_message(input$quick_q) })
1293
-
1294
  observeEvent(input$clear_chat, {
1295
  values$chat_messages <- list()
1296
  add_message("assistant", "Chat cleared. How can I help?")
1297
  })
1298
-
1299
  # ---- Initial greeting ----
1300
  observe({
1301
  if (length(values$chat_messages) == 0) {
@@ -1306,7 +1116,7 @@ server <- function(input, output, session) {
1306
  "I'm using rule-based responses. Set **HF_API_TOKEN** in Space secrets to enable AI models."
1307
  }
1308
  add_message("assistant", paste0(
1309
- "\U0001f44b Vanakam! I'm TerraByte- Your AI powered companion.\n\n",
1310
  mode_msg,
1311
  "\n\n**I can help you with:**\n",
1312
  "\u2022 **What is PVE?** - Understand variance explained\n",
@@ -1318,43 +1128,26 @@ server <- function(input, output, session) {
1318
  ))
1319
  }
1320
  })
1321
-
1322
  # ---- Chat display ----
1323
  output$chat_display <- renderUI({
1324
  messages <- values$chat_messages
1325
  if (length(messages) == 0) return(NULL)
1326
-
1327
  elems <- lapply(messages, function(msg) {
1328
  content_html <- HTML(gsub("\n", "<br>", htmltools::htmlEscape(msg$content)))
1329
-
1330
- # Render image thumbnail inside user bubble if present
1331
- image_tag <- if (!is.null(msg$image_thumb)) {
1332
- tags$div(
1333
- style = "margin-top:8px;",
1334
- tags$img(
1335
- src = msg$image_thumb,
1336
- alt = if (!is.null(msg$image_name)) msg$image_name else "uploaded image",
1337
- style = paste0("max-width:100%; max-height:200px; border-radius:8px;",
1338
- "border:1px solid rgba(255,255,255,0.2); display:block;")
1339
- ),
1340
- if (!is.null(msg$image_name))
1341
- tags$div(style = "font-size:10px; opacity:0.7; margin-top:3px;", msg$image_name)
1342
- )
1343
- } else NULL
1344
-
1345
  meta_content <- tagList(
1346
  span(msg$time),
1347
  if (!is.null(msg$model) && msg$role == "assistant")
1348
  span(class = "model-tag", paste0("[", msg$model, "]"))
1349
  )
1350
-
1351
  div(class = paste("chat-msg", msg$role),
1352
- div(class = "chat-bubble",
1353
- content_html,
1354
- image_tag),
1355
  div(class = "chat-meta", meta_content))
1356
  })
1357
-
1358
  if (values$is_typing) {
1359
  elems <- c(elems, list(
1360
  div(class = "chat-msg assistant",
@@ -1363,64 +1156,64 @@ server <- function(input, output, session) {
1363
  }
1364
  do.call(tagList, elems)
1365
  })
1366
-
1367
  # ============================================================
1368
  # DATA LOADING
1369
  # ============================================================
1370
-
1371
  observeEvent(input$genotype_file, {
1372
  req(input$genotype_file)
1373
  tryCatch({
1374
  all_data <- readLines(input$genotype_file$datapath)
1375
  if (length(all_data) < 4) { showNotification("Genotype file must have at least 4 rows", type = "error"); return() }
1376
-
1377
  header <- strsplit(all_data[1], ",")[[1]]
1378
  chromosome_row <- strsplit(all_data[2], ",")[[1]]
1379
  position_row <- strsplit(all_data[3], ",")[[1]]
1380
-
1381
  genotype_data <- read.csv(text = all_data[-(1:3)], header = FALSE)
1382
  colnames(genotype_data) <- header
1383
  rownames(genotype_data) <- genotype_data[, 1]
1384
  genotype_data <- genotype_data[, -1]
1385
-
1386
  for (col in colnames(genotype_data))
1387
  genotype_data[[col]] <- as.numeric(as.character(genotype_data[[col]]))
1388
-
1389
  values$all_markers <- data.frame(
1390
  Marker = colnames(genotype_data),
1391
  Chromosome = chromosome_row[-1],
1392
  Position = as.numeric(position_row[-1]),
1393
  stringsAsFactors = FALSE)
1394
-
1395
  values$genotype_data <- genotype_data
1396
  values$chromosome_info <- chromosome_row[-1]
1397
  values$position_info <- as.numeric(position_row[-1])
1398
-
1399
  showNotification("Genotype data loaded", type = "message")
1400
  add_message("assistant", paste0("\u2705 Loaded genotype data: **", ncol(genotype_data), " markers**, **", nrow(genotype_data), " samples**"))
1401
  }, error = function(e) showNotification(paste("Error:", e$message), type = "error"))
1402
  })
1403
-
1404
  observeEvent(input$phenotype_file, {
1405
  req(input$phenotype_file)
1406
  tryCatch({
1407
  phenotype_data <- read.csv(input$phenotype_file$datapath)
1408
  rownames(phenotype_data) <- phenotype_data[, 1]
1409
  phenotype_data <- phenotype_data[, -1]
1410
-
1411
  for (col in colnames(phenotype_data))
1412
  phenotype_data[[col]] <- as.numeric(as.character(phenotype_data[[col]]))
1413
-
1414
  values$phenotype_data <- phenotype_data
1415
  updateSelectInput(session, "phenotype_column",
1416
  choices = colnames(phenotype_data),
1417
  selected = colnames(phenotype_data)[1])
1418
-
1419
  showNotification("Phenotype data loaded", type = "message")
1420
  add_message("assistant", paste0("\u2705 Loaded phenotype data: **", ncol(phenotype_data), " traits**, **", nrow(phenotype_data), " samples**"))
1421
  }, error = function(e) showNotification(paste("Error:", e$message), type = "error"))
1422
  })
1423
-
1424
  observeEvent(input$pop_file, {
1425
  req(input$pop_file)
1426
  tryCatch({
@@ -1433,55 +1226,55 @@ server <- function(input, output, session) {
1433
  add_message("assistant", paste0("\u2705 Loaded population data (", nrow(pop_data), " samples)"))
1434
  }, error = function(e) showNotification(paste("Error:", e$message), type = "error"))
1435
  })
1436
-
1437
  observeEvent(input$test_genotype_file, {
1438
  req(input$test_genotype_file)
1439
  tryCatch({
1440
  all_data <- readLines(input$test_genotype_file$datapath)
1441
  header <- strsplit(all_data[1], ",")[[1]]
1442
-
1443
  genotype_data <- read.csv(text = all_data[-(1:3)], header = FALSE)
1444
  colnames(genotype_data) <- header
1445
  rownames(genotype_data) <- genotype_data[, 1]
1446
  genotype_data <- genotype_data[, -1]
1447
-
1448
  for (col in colnames(genotype_data))
1449
  genotype_data[[col]] <- as.numeric(as.character(genotype_data[[col]]))
1450
-
1451
  values$test_genotype_data <- genotype_data
1452
  values$has_test_data <- TRUE
1453
  showNotification("Test genotype data loaded", type = "message")
1454
  }, error = function(e) showNotification(paste("Error:", e$message), type = "error"))
1455
  })
1456
-
1457
  # ---- Data previews ----
1458
  output$geno_preview <- renderDT({ req(input$genotype_file); datatable(head(read.csv(input$genotype_file$datapath), 10), options = list(scrollX = TRUE, pageLength = 5)) })
1459
  output$pheno_preview <- renderDT({ req(input$phenotype_file); datatable(head(read.csv(input$phenotype_file$datapath), 10), options = list(scrollX = TRUE, pageLength = 5)) })
1460
  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)) })
1461
  output$pop_preview <- renderDT({ req(input$pop_file); datatable(head(read.csv(input$pop_file$datapath), 10), options = list(scrollX = TRUE, pageLength = 5)) })
1462
  output$predicted_test_pheno_preview <- renderDT({ req(values$predicted_test_phenotype_data); datatable(values$predicted_test_phenotype_data, options = list(scrollX = TRUE, pageLength = 5)) })
1463
-
1464
  # ============================================================
1465
  # QTL EFFECT CALCULATION
1466
  # ============================================================
1467
-
1468
  calculate_qtl_effects <- function(genotype_matrix, phenotype_vector, marker_names) {
1469
  effects_list <- list()
1470
-
1471
  for (marker in marker_names) {
1472
  if (!marker %in% colnames(genotype_matrix)) next
1473
-
1474
  geno <- genotype_matrix[, marker]
1475
  pheno <- phenotype_vector
1476
  valid_idx <- !is.na(geno) & !is.na(pheno)
1477
  geno <- geno[valid_idx]
1478
  pheno <- pheno[valid_idx]
1479
-
1480
  if (length(unique(geno)) < 2) next
1481
-
1482
  lm_fit <- lm(pheno ~ geno)
1483
  additive_effect <- coef(lm_fit)[2]
1484
-
1485
  dominance_effect <- NA
1486
  if (length(unique(geno)) == 3) {
1487
  geno_means <- tapply(pheno, geno, mean, na.rm = TRUE)
@@ -1490,10 +1283,10 @@ server <- function(input, output, session) {
1490
  geno_means[as.character(sort(unique(geno))[3])]) / 2
1491
  dominance_effect <- het_mean - midparent
1492
  }
1493
-
1494
  r_squared <- summary(lm_fit)$r.squared
1495
  se_additive <- tryCatch(summary(lm_fit)$coefficients[2, 2], error = function(e) NA)
1496
-
1497
  effects_list[[marker]] <- data.frame(
1498
  Marker = marker,
1499
  Additive_Effect = additive_effect,
@@ -1505,40 +1298,40 @@ server <- function(input, output, session) {
1505
  N_Samples = length(pheno),
1506
  stringsAsFactors = FALSE)
1507
  }
1508
-
1509
  if (length(effects_list) == 0) return(NULL)
1510
  do.call(rbind, effects_list)
1511
  }
1512
-
1513
  # ============================================================
1514
  # MAIN QTL ANALYSIS
1515
  # ============================================================
1516
-
1517
  observeEvent(input$run_analysis, {
1518
  req(values$genotype_data, values$phenotype_data, input$phenotype_column)
1519
  showNotification("Starting QTL analysis...", type = "message")
1520
  values$lod_threshold <- input$lod_threshold
1521
-
1522
  tryCatch({
1523
  common_samples <- intersect(rownames(values$genotype_data), rownames(values$phenotype_data))
1524
  if (length(common_samples) == 0) { showNotification("No common samples", type = "error"); return() }
1525
-
1526
  X <- values$genotype_data[common_samples, , drop = FALSE]
1527
  y <- as.numeric(values$phenotype_data[common_samples, input$phenotype_column])
1528
  nzv <- nearZeroVar(X)
1529
  if (length(nzv) > 0) X <- X[, -nzv, drop = FALSE]
1530
-
1531
  set.seed(123)
1532
  train_index <- createDataPartition(y, p = 1 - input$test_size, list = FALSE)
1533
  X_train <- X[train_index, , drop = FALSE]; X_val <- X[-train_index, , drop = FALSE]
1534
  y_train <- y[train_index]; y_val <- y[-train_index]
1535
-
1536
  model <- train(x = X_train, y = y_train, method = "rf",
1537
  trControl = trainControl(method = "cv", number = 5),
1538
  importance = TRUE, tuneLength = 3)
1539
-
1540
  values$model_fit <- model
1541
-
1542
  imp <- varImp(model, scale = FALSE)$importance
1543
  importance_scores <- data.frame(
1544
  Marker = rownames(imp),
@@ -1546,14 +1339,14 @@ server <- function(input, output, session) {
1546
  Chromosome = values$chromosome_info[match(rownames(imp), colnames(X))],
1547
  Position = as.numeric(values$position_info[match(rownames(imp), colnames(X))]),
1548
  stringsAsFactors = FALSE)
1549
-
1550
  values$importance_scores <- importance_scores
1551
  lod_sig <- importance_scores[importance_scores$LOD > input$lod_threshold, , drop = FALSE]
1552
-
1553
  if (nrow(lod_sig) > 0) {
1554
  lod_sig$Low_Flank <- NA
1555
  lod_sig$High_Flank <- NA
1556
-
1557
  for (i in 1:nrow(lod_sig)) {
1558
  chr_m <- values$all_markers[values$all_markers$Chromosome == lod_sig$Chromosome[i], ]
1559
  chr_m <- chr_m[order(chr_m$Position), ]
@@ -1563,10 +1356,10 @@ server <- function(input, output, session) {
1563
  lod_sig$High_Flank[i] <- if (idx < nrow(chr_m)) chr_m$Marker[idx + 1] else lod_sig$Marker[i]
1564
  }
1565
  }
1566
-
1567
  values$lod_scores_train <- lod_sig
1568
  qtl_fx <- calculate_qtl_effects(X_train, y_train, lod_sig$Marker)
1569
-
1570
  if (!is.null(qtl_fx)) {
1571
  values$qtl_effects_train <- merge(lod_sig, qtl_fx, by = "Marker")
1572
  } else {
@@ -1576,26 +1369,26 @@ server <- function(input, output, session) {
1576
  values$lod_scores_train <- data.frame(Message = paste("No QTLs above LOD", input$lod_threshold))
1577
  values$qtl_effects_train <- data.frame(Message = paste("No QTLs above LOD", input$lod_threshold))
1578
  }
1579
-
1580
  y_train_pred <- predict(model, X_train)
1581
  y_val_pred <- predict(model, X_val)
1582
  train_r2 <- 1 - sum((y_train - y_train_pred)^2) / sum((y_train - mean(y_train))^2)
1583
  val_r2 <- 1 - sum((y_val - y_val_pred)^2) / sum((y_val - mean(y_val))^2)
1584
-
1585
  values$performance_metrics <- data.frame(
1586
  Metric = c("R\u00b2 (Train)", "R (Train)", "R\u00b2 (Validation)", "R (Validation)"),
1587
  Value = c(train_r2, cor(y_train, y_train_pred), val_r2, cor(y_val, y_val_pred)),
1588
  stringsAsFactors = FALSE)
1589
-
1590
  values$train_predictions <- data.frame(Observed = y_train, Predicted = y_train_pred)
1591
  values$test_predictions <- data.frame(Observed = y_val, Predicted = y_val_pred)
1592
-
1593
  # Epistasis
1594
  if (nrow(lod_sig) > 0) {
1595
  sig_markers <- lod_sig$Marker[lod_sig$Marker %in% colnames(X_train)]
1596
  all_markers_v <- colnames(X_train)
1597
  epistasis_list <- list()
1598
-
1599
  withProgress(message = "Calculating epistasis...", value = 0, {
1600
  total <- length(sig_markers) * length(all_markers_v)
1601
  for (m1 in sig_markers) {
@@ -1619,7 +1412,7 @@ server <- function(input, output, session) {
1619
  }
1620
  }
1621
  })
1622
-
1623
  if (length(epistasis_list) > 0) {
1624
  epistasis_all <- do.call(rbind, epistasis_list)
1625
  values$epistasis_all <- epistasis_all
@@ -1629,7 +1422,7 @@ server <- function(input, output, session) {
1629
  values$epistasis_sig <- data.frame(Message = "No epistatic interactions")
1630
  }
1631
  }
1632
-
1633
  showNotification("QTL analysis completed!", type = "message")
1634
  n_qtl <- if (!is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train)) nrow(values$qtl_effects_train) else 0
1635
  add_message("assistant", paste0(
@@ -1638,45 +1431,45 @@ server <- function(input, output, session) {
1638
  "\u2022 Validation R\u00b2: **", round(val_r2, 3), "**\n\n",
1639
  "Ask me about PVE, top QTLs, or next steps!"))
1640
  updateTabsetPanel(session, "nav", selected = "Results")
1641
-
1642
  }, error = function(e) showNotification(paste("Error:", e$message), type = "error"))
1643
  })
1644
-
1645
  # ============================================================
1646
  # DOMESTICATION ANALYSIS
1647
  # ============================================================
1648
-
1649
  calculate_selection_metrics <- function(genotype_matrix, pop_data, marker_info) {
1650
  metrics_list <- list()
1651
-
1652
  for (marker in colnames(genotype_matrix)) {
1653
  geno <- genotype_matrix[, marker]
1654
  pop <- pop_data$population[match(rownames(genotype_matrix), pop_data$id)]
1655
  valid_idx <- !is.na(geno) & !is.na(pop)
1656
  geno <- geno[valid_idx]; pop <- pop[valid_idx]
1657
-
1658
  if (length(unique(pop)) < 2) next
1659
  geno_dom <- geno[pop == "Domesticated"]
1660
  geno_wild <- geno[pop == "Wild"]
1661
  if (length(geno_dom) < 3 || length(geno_wild) < 3) next
1662
-
1663
  freq_dom <- mean(geno_dom, na.rm = TRUE) / 2
1664
  freq_wild <- mean(geno_wild, na.rm = TRUE) / 2
1665
  p_avg <- (freq_dom + freq_wild) / 2
1666
-
1667
  fst <- if (p_avg > 0 && p_avg < 1) {
1668
  f <- (freq_dom - freq_wild)^2 / (p_avg * (1 - p_avg))
1669
  f / (1 + f)
1670
  } else 0
1671
-
1672
  pi_dom <- 2 * freq_dom * (1 - freq_dom)
1673
  pi_wild <- 2 * freq_wild * (1 - freq_wild)
1674
  n_dom <- length(geno_dom)
1675
  n_wild <- length(geno_wild)
1676
-
1677
  tajima_d_dom <- (pi_dom - 1/n_dom) / sqrt(var(geno_dom) /n_dom)
1678
  tajima_d_wild <- (pi_wild - 1/n_wild) / sqrt(var(geno_wild)/n_wild)
1679
-
1680
  marker_row <- marker_info[marker_info$Marker == marker, ]
1681
  metrics_list[[marker]] <- data.frame(
1682
  Marker = marker,
@@ -1686,71 +1479,71 @@ server <- function(input, output, session) {
1686
  Tajima_D_Dom = tajima_d_dom, Tajima_D_Wild = tajima_d_wild,
1687
  stringsAsFactors = FALSE)
1688
  }
1689
-
1690
  if (length(metrics_list) == 0) return(NULL)
1691
  do.call(rbind, metrics_list)
1692
  }
1693
-
1694
  observeEvent(input$run_domestication, {
1695
  req(values$genotype_data, values$pop_data, values$all_markers)
1696
  tryCatch({
1697
  common_samples <- intersect(rownames(values$genotype_data), values$pop_data$id)
1698
  if (length(common_samples) == 0) { showNotification("No common samples", type = "error"); return() }
1699
-
1700
  X <- values$genotype_data[common_samples, , drop = FALSE]
1701
  pop_subset <- values$pop_data[values$pop_data$id %in% common_samples, ]
1702
  sel_metrics <- calculate_selection_metrics(X, pop_subset, values$all_markers)
1703
-
1704
  if (is.null(sel_metrics)) { showNotification("Could not calculate selection metrics", type = "error"); return() }
1705
-
1706
  sel_metrics$Significant <-
1707
  sel_metrics$Fst > input$fst_threshold |
1708
  sel_metrics$Tajima_D_Dom < input$tajima_threshold |
1709
  sel_metrics$Tajima_D_Wild < input$tajima_threshold
1710
-
1711
  values$selection_metrics <- sel_metrics
1712
  showNotification("Domestication analysis completed!", type = "message")
1713
  n_sig <- sum(sel_metrics$Significant, na.rm = TRUE)
1714
  add_message("assistant", paste0("\u2705 Domestication analysis complete!\n\n\u2022 Found **", n_sig, " markers** with selection signatures"))
1715
  }, error = function(e) showNotification(paste("Error:", e$message), type = "error"))
1716
  })
1717
-
1718
  # ============================================================
1719
  # PREDICT TEST PHENOTYPES
1720
  # ============================================================
1721
-
1722
  observeEvent(input$predict_test_phenotype, {
1723
  req(values$model_fit, values$test_genotype_data)
1724
  tryCatch({
1725
  common_markers <- intersect(colnames(values$test_genotype_data), colnames(values$genotype_data))
1726
  if (length(common_markers) == 0) { showNotification("No common markers", type = "error"); return() }
1727
-
1728
  X_test <- values$test_genotype_data[, common_markers, drop = FALSE]
1729
  predictions <- predict(values$model_fit, newdata = X_test)
1730
-
1731
  values$predicted_test_phenotype_data <- data.frame(
1732
  id = rownames(X_test),
1733
  Predicted_Phenotype = as.numeric(predictions),
1734
  stringsAsFactors = FALSE)
1735
-
1736
  showNotification("Predictions completed!", type = "message")
1737
  }, error = function(e) showNotification(paste("Error:", e$message), type = "error"))
1738
  })
1739
-
1740
  # ============================================================
1741
  # MANHATTAN PLOT HELPER
1742
  # ============================================================
1743
-
1744
  create_manhattan <- function(data, y_col, title, threshold, y_label = y_col) {
1745
  if (is.null(data) || nrow(data) == 0 || "Message" %in% colnames(data))
1746
  return(plot_ly() %>% layout(title = "No data available",
1747
  plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e")))
1748
-
1749
  plot_data <- data[!is.na(data[[y_col]]), ]
1750
  if (nrow(plot_data) == 0)
1751
  return(plot_ly() %>% layout(title = "No valid data",
1752
  plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e")))
1753
-
1754
  chroms <- unique(plot_data$Chromosome)
1755
  chrom_pos <- data.frame()
1756
  for (i in seq_along(chroms)) {
@@ -1761,7 +1554,7 @@ server <- function(input, output, session) {
1761
  chrom_pos <- rbind(chrom_pos, chr_data)
1762
  }
1763
  }
1764
-
1765
  p <- plot_ly() %>%
1766
  add_trace(data = chrom_pos, x = ~PosScaled, y = as.formula(paste0("~", y_col)),
1767
  type = "scatter", mode = "markers", color = ~factor(Chromosome),
@@ -1769,13 +1562,13 @@ server <- function(input, output, session) {
1769
  text = ~paste("Marker:", Marker, "<br>Chr:", Chromosome, "<br>Pos:", Position,
1770
  "<br>", y_label, ":", round(get(y_col), 3)),
1771
  hoverinfo = "text", showlegend = FALSE)
1772
-
1773
  if (!is.null(threshold) && !is.na(threshold))
1774
  p <- p %>% add_segments(
1775
  x = min(chrom_pos$PosScaled, na.rm = TRUE), xend = max(chrom_pos$PosScaled, na.rm = TRUE),
1776
  y = threshold, yend = threshold,
1777
  line = list(color = "red", dash = "dash", width = 1), name = "Threshold")
1778
-
1779
  p %>% layout(title = title,
1780
  xaxis = list(title = "Chromosome",
1781
  ticktext = chroms,
@@ -1784,26 +1577,26 @@ server <- function(input, output, session) {
1784
  yaxis = list(title = y_label),
1785
  plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))
1786
  }
1787
-
1788
  # ============================================================
1789
  # PLOTS
1790
  # ============================================================
1791
-
1792
  output$lod_plot_2d <- renderPlotly({
1793
  req(values$importance_scores)
1794
  create_manhattan(values$importance_scores, "LOD", "QTL Manhattan Plot", input$lod_threshold, "LOD Score")
1795
  })
1796
-
1797
  output$fst_plot <- renderPlotly({
1798
  req(values$selection_metrics)
1799
  create_manhattan(values$selection_metrics, "Fst", "Fst Manhattan Plot", input$fst_threshold, "Fst")
1800
  })
1801
-
1802
  output$tajima_plot <- renderPlotly({
1803
  req(values$selection_metrics)
1804
  if ("Message" %in% colnames(values$selection_metrics))
1805
  return(plot_ly() %>% layout(title = "No data available", plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e")))
1806
-
1807
  data <- values$selection_metrics
1808
  chroms <- unique(data$Chromosome)
1809
  chrom_pos <- data.frame()
@@ -1815,7 +1608,7 @@ server <- function(input, output, session) {
1815
  chrom_pos <- rbind(chrom_pos, chr_data)
1816
  }
1817
  }
1818
-
1819
  plot_ly() %>%
1820
  add_trace(data = chrom_pos, x = ~PosScaled, y = ~Tajima_D_Dom, type = "scatter", mode = "markers",
1821
  name = "Domesticated", marker = list(size = 5, color = "#58a6ff", opacity = 0.7),
@@ -1834,7 +1627,7 @@ server <- function(input, output, session) {
1834
  yaxis = list(title = "Tajima's D"),
1835
  plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))
1836
  })
1837
-
1838
  output$performance_plot <- renderPlotly({
1839
  req(values$performance_metrics)
1840
  plot_ly(data = values$performance_metrics, x = ~Metric, y = ~Value, type = "bar",
@@ -1844,7 +1637,7 @@ server <- function(input, output, session) {
1844
  yaxis = list(title = "Value", range = c(0, 1.1)),
1845
  plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))
1846
  })
1847
-
1848
  output$regression_plot_train <- renderPlotly({
1849
  req(values$train_predictions)
1850
  plot_ly(data = values$train_predictions, x = ~Observed, y = ~Predicted,
@@ -1854,7 +1647,7 @@ server <- function(input, output, session) {
1854
  layout(title = "Training Set", xaxis = list(title = "Observed"), yaxis = list(title = "Predicted"),
1855
  plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))
1856
  })
1857
-
1858
  output$regression_plot_test <- renderPlotly({
1859
  req(values$test_predictions)
1860
  plot_ly(data = values$test_predictions, x = ~Observed, y = ~Predicted,
@@ -1864,13 +1657,13 @@ server <- function(input, output, session) {
1864
  layout(title = "Validation Set", xaxis = list(title = "Observed"), yaxis = list(title = "Predicted"),
1865
  plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))
1866
  })
1867
-
1868
  output$epistasis_heatmap <- renderPlotly({
1869
  req(values$epistasis_all)
1870
  if ("Message" %in% colnames(values$epistasis_all))
1871
  return(plot_ly() %>% layout(title = values$epistasis_all$Message[1],
1872
  plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e")))
1873
-
1874
  qtls <- unique(values$epistasis_all$QTL1)
1875
  markers <- unique(values$epistasis_all$QTL2)
1876
  p_mat <- matrix(NA, nrow = length(qtls), ncol = length(markers),
@@ -1878,7 +1671,7 @@ server <- function(input, output, session) {
1878
  for (i in 1:nrow(values$epistasis_all))
1879
  p_mat[values$epistasis_all$QTL1[i], values$epistasis_all$QTL2[i]] <-
1880
  -log10(values$epistasis_all$Interaction_p[i])
1881
-
1882
  plot_ly(x = colnames(p_mat), y = rownames(p_mat), z = p_mat,
1883
  type = "heatmap", colorscale = "Viridis",
1884
  hovertemplate = "QTL: %{y}<br>Marker: %{x}<br>-log10(p): %{z:.2f}") %>%
@@ -1886,16 +1679,16 @@ server <- function(input, output, session) {
1886
  xaxis = list(title = "Marker", tickangle = 45), yaxis = list(title = "QTL"),
1887
  plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))
1888
  })
1889
-
1890
  # ============================================================
1891
  # TABLES
1892
  # ============================================================
1893
-
1894
  output$qtl_effects_table_train <- renderDT({
1895
  req(values$qtl_effects_train)
1896
  if ("Message" %in% colnames(values$qtl_effects_train))
1897
  return(datatable(data.frame(Status = values$qtl_effects_train$Message[1]), options = list(dom = "t")))
1898
-
1899
  display_cols <- intersect(
1900
  c("Marker", "Chromosome", "Position", "LOD", "Additive_Effect", "PVE_Percent", "Low_Flank", "High_Flank"),
1901
  colnames(values$qtl_effects_train))
@@ -1903,7 +1696,7 @@ server <- function(input, output, session) {
1903
  datatable(df, options = list(pageLength = 10, scrollX = TRUE), rownames = FALSE) %>%
1904
  formatRound(intersect(c("LOD", "Additive_Effect", "PVE_Percent"), colnames(df)), 3)
1905
  })
1906
-
1907
  output$epistasis_table <- renderDT({
1908
  req(values$epistasis_sig)
1909
  if ("Message" %in% colnames(values$epistasis_sig))
@@ -1912,47 +1705,47 @@ server <- function(input, output, session) {
1912
  options = list(pageLength = 10, scrollX = TRUE), rownames = FALSE) %>%
1913
  formatSignif(columns = c("Interaction_p", "Effect_Size"), digits = 4)
1914
  })
1915
-
1916
  output$selection_table <- renderDT({
1917
  req(values$selection_metrics)
1918
  if ("Message" %in% colnames(values$selection_metrics))
1919
  return(datatable(data.frame(Status = values$selection_metrics$Message[1]), options = list(dom = "t")))
1920
-
1921
  df <- values$selection_metrics
1922
  if (!is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train))
1923
  df$QTL_Overlap <- df$Marker %in% values$qtl_effects_train$Marker
1924
-
1925
  display_cols <- intersect(
1926
  c("Marker", "Chromosome", "Fst", "Pi_Dom", "Pi_Wild", "Tajima_D_Dom", "Significant", "QTL_Overlap"),
1927
  colnames(df))
1928
  datatable(df[order(-df$Fst), display_cols], options = list(pageLength = 10, scrollX = TRUE), rownames = FALSE) %>%
1929
  formatRound(c("Fst", "Pi_Dom", "Pi_Wild", "Tajima_D_Dom"), 3)
1930
  })
1931
-
1932
  # ============================================================
1933
  # CHROMOSOME VISUALIZATION
1934
  # ============================================================
1935
-
1936
  output$chromosome_viz <- renderUI({
1937
  req(values$lod_scores_train, values$all_markers)
1938
  if ("Message" %in% colnames(values$lod_scores_train))
1939
  return(div(class = "alert alert-info", values$lod_scores_train$Message[1]))
1940
-
1941
  chromosomes <- unique(values$lod_scores_train$Chromosome)
1942
  tagList(lapply(chromosomes, function(chr) {
1943
  chr_markers <- values$all_markers[values$all_markers$Chromosome == chr, ]
1944
  chr_markers <- chr_markers[order(chr_markers$Position), ]
1945
  chr_qtls <- values$lod_scores_train[values$lod_scores_train$Chromosome == chr, ]
1946
-
1947
  sel_markers <- NULL
1948
  if (!is.null(values$selection_metrics) && !"Message" %in% colnames(values$selection_metrics))
1949
  sel_markers <- values$selection_metrics[
1950
  values$selection_metrics$Chromosome == chr & values$selection_metrics$Significant, ]
1951
-
1952
  min_pos <- min(chr_markers$Position, na.rm = TRUE)
1953
  max_pos <- max(chr_markers$Position, na.rm = TRUE)
1954
  range_pos <- max_pos - min_pos
1955
-
1956
  div(class = "chromosome-container",
1957
  div(class = "chromosome-title", paste("Chromosome", chr)),
1958
  div(class = "chromosome",
@@ -1960,7 +1753,7 @@ server <- function(input, output, session) {
1960
  marker <- chr_markers[i, ]
1961
  left <- if (range_pos > 0) ((marker$Position - min_pos) / range_pos) * 100
1962
  else (i / nrow(chr_markers)) * 100
1963
-
1964
  marker_class <- "chromosome-marker"
1965
  if (marker$Marker %in% chr_qtls$Marker) {
1966
  marker_class <- paste(marker_class, "significant")
@@ -1978,26 +1771,26 @@ server <- function(input, output, session) {
1978
  )
1979
  }))
1980
  })
1981
-
1982
  # ---- Simulation animations ----
1983
  observeEvent(input$simulate_btn, session$sendCustomMessage("simulateQTLDiscovery", list()))
1984
  observeEvent(input$reset_btn, session$sendCustomMessage("resetAnimation", list()))
1985
-
1986
  # ============================================================
1987
  # INTERPRETATION OUTPUTS
1988
  # ============================================================
1989
-
1990
  output$analysis_summary <- renderUI({
1991
  has_qtl <- !is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train)
1992
  has_perf <- !is.null(values$performance_metrics)
1993
  has_epi <- !is.null(values$epistasis_sig) && !"Message" %in% colnames(values$epistasis_sig) && nrow(values$epistasis_sig) > 0
1994
  has_sel <- !is.null(values$selection_metrics) && !"Message" %in% colnames(values$selection_metrics)
1995
-
1996
  n_qtl <- if (has_qtl) nrow(values$qtl_effects_train) else 0
1997
  n_epi <- if (has_epi) nrow(values$epistasis_sig) else 0
1998
  n_sel <- if (has_sel) sum(values$selection_metrics$Significant, na.rm = TRUE) else 0
1999
  val_r2 <- if (has_perf) round(values$performance_metrics$Value[values$performance_metrics$Metric == "R\u00b2 (Validation)"], 3) else "N/A"
2000
-
2001
  div(class = "interpretation-section",
2002
  tags$h5("Analysis Summary"),
2003
  tags$p(paste("Found", n_qtl, "QTLs above LOD", input$lod_threshold,
@@ -2005,38 +1798,38 @@ server <- function(input, output, session) {
2005
  if (has_epi) paste0("with ", n_epi, " epistatic interactions"),
2006
  if (has_sel) paste0("and ", n_sel, " selection signatures."))))
2007
  })
2008
-
2009
  output$qtl_interpretation <- renderUI({
2010
  if (is.null(values$qtl_effects_train) || "Message" %in% colnames(values$qtl_effects_train))
2011
  return(div(class = "interpretation-section", tags$h5("QTL Significance"), tags$p("No significant QTLs detected.")))
2012
-
2013
  top_qtl <- values$qtl_effects_train[which.max(values$qtl_effects_train$LOD), ]
2014
  div(class = "interpretation-section",
2015
  tags$h5("QTL Significance"),
2016
  tags$p(paste("Top QTL:", top_qtl$Marker, "(Chr", top_qtl$Chromosome, ") with LOD =", round(top_qtl$LOD, 2))))
2017
  })
2018
-
2019
  output$effect_interpretation <- renderUI({
2020
  if (is.null(values$qtl_effects_train) || "Message" %in% colnames(values$qtl_effects_train))
2021
  return(div(class = "interpretation-section", tags$h5("Effect Sizes"), tags$p("No QTL effects to interpret.")))
2022
-
2023
  top_pve <- values$qtl_effects_train[which.max(values$qtl_effects_train$PVE_Percent), ]
2024
  div(class = "interpretation-section",
2025
  tags$h5("Effect Sizes"),
2026
  tags$p(paste("Largest effect:", top_pve$Marker, "explains", round(top_pve$PVE_Percent, 1), "% of variance")))
2027
  })
2028
-
2029
  output$epistasis_interpretation <- renderUI({
2030
  if (is.null(values$epistasis_sig) || "Message" %in% colnames(values$epistasis_sig) || nrow(values$epistasis_sig) == 0)
2031
  return(div(class = "interpretation-section", tags$h5("Epistasis"), tags$p("No significant epistatic interactions detected.")))
2032
-
2033
  top_epi <- values$epistasis_sig[which.min(values$epistasis_sig$Interaction_p), ]
2034
  div(class = "interpretation-section",
2035
  tags$h5("Epistasis"),
2036
  tags$p(paste("Detected", nrow(values$epistasis_sig), "interactions. Strongest:",
2037
  top_epi$QTL1, "x", top_epi$QTL2, "(p =", format.pval(top_epi$Interaction_p), ")")))
2038
  })
2039
-
2040
  output$recommendations <- renderUI({
2041
  has_qtl <- !is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train)
2042
  recs <- if (has_qtl) {
@@ -2052,11 +1845,11 @@ server <- function(input, output, session) {
2052
  tags$h5("Recommendations"),
2053
  tags$ul(lapply(recs, tags$li), style = "color:#8b949e;"))
2054
  })
2055
-
2056
  # ============================================================
2057
  # DOWNLOAD HANDLERS
2058
  # ============================================================
2059
-
2060
  output$download_train_results <- downloadHandler(
2061
  filename = function() paste0("qtl_results_", Sys.Date(), ".xlsx"),
2062
  content = function(file) {
@@ -2068,7 +1861,7 @@ server <- function(input, output, session) {
2068
  write_xlsx(sheets, file)
2069
  }
2070
  )
2071
-
2072
  output$download_selection <- downloadHandler(
2073
  filename = function() paste0("selection_", Sys.Date(), ".xlsx"),
2074
  content = function(file) {
@@ -2082,7 +1875,7 @@ server <- function(input, output, session) {
2082
  }
2083
 
2084
  # ============================================================
2085
- # RUN APP
2086
  # ============================================================
2087
 
2088
- shinyApp(ui = ui, server = server)
 
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
  list(
71
+ id = "HuggingFaceTB/SmolLM3-3B:hf-inference",
72
+ label = "SmolLM3",
73
+ provider = "together",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
  tier = "free"
75
  ),
76
  list(
77
+ id = "deepseek-ai/DeepSeek-V3-0324:sambanova",
78
+ label = "Deepseek",
79
+ provider = "together",
 
 
 
 
 
 
 
 
80
  tier = "free"
81
  ),
82
+
 
83
  list(
84
+ id = "meta-llama/Llama-3.2-3B-Instruct:together",
85
+ label = "meta-llma",
86
+ provider = "together",
87
  tier = "free"
88
  )
89
+
90
+
91
+
92
  )
93
 
94
  model_choices <- setNames(
95
  sapply(available_models, function(m) m$id),
96
+ sapply(available_models, function(m) paste0(m$label, " [", m$tier, "]"))
97
  )
98
 
99
  # ============================================================
 
112
 
113
  test_api_connection <- function(model_id = default_model) {
114
  if (!token_exists) return(list(success = FALSE, error = "No token found"))
115
+
116
  tryCatch({
117
  response <- POST(
118
  url = HF_API_URL,
 
128
  encode = "json",
129
  timeout(15)
130
  )
131
+
132
  status <- status_code(response)
133
  if (status == 200) return(list(success = TRUE))
134
+
135
  err <- tryCatch(content(response, "text", encoding = "UTF-8"),
136
  error = function(e) paste("Status:", status))
137
  return(list(success = FALSE,
 
153
  # QUERY FUNCTION
154
  # ============================================================
155
 
156
+ query_hf_api <- function(prompt, model_id = default_model, max_length = 500, temperature = 0.7) {
 
157
  if (!token_exists) return(list(success = FALSE, error = "HF_API_TOKEN not set"))
158
+
159
  tryCatch({
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
160
  response <- POST(
161
  url = HF_API_URL,
162
  add_headers(
163
  Authorization = paste("Bearer", HF_API_TOKEN),
164
  "Content-Type" = "application/json"
165
  ),
166
+ body = toJSON(list(
167
+ model = model_id,
168
+ messages = list(
169
+ list(role = "system",
170
+ content = "You are an expert bioinformatics assistant specializing in QTL analysis. Be concise and helpful."),
171
+ list(role = "user", content = prompt)
172
+ ),
173
+ max_tokens = as.integer(max_length),
174
+ temperature = temperature
175
+ ), auto_unbox = TRUE),
176
+ encode = "json",
177
  timeout(60)
178
  )
179
+
180
  status <- status_code(response)
181
+
182
  if (status == 200) {
183
  result <- content(response, as = "parsed", encoding = "UTF-8")
184
  text <- result$choices[[1]]$message$content
185
  return(list(success = TRUE, text = text))
186
  }
187
+
188
  err <- tryCatch(content(response, "text", encoding = "UTF-8"),
189
  error = function(e) paste("Status:", status))
190
  return(list(success = FALSE,
 
198
 
199
  build_system_prompt <- function(rv) {
200
  context_parts <- c("CURRENT ANALYSIS RESULTS:")
201
+
202
  if (!is.null(rv$qtl_effects_train) && !"Message" %in% colnames(rv$qtl_effects_train)) {
203
  n_qtl <- nrow(rv$qtl_effects_train)
204
  total_pve <- sum(rv$qtl_effects_train$PVE_Percent, na.rm = TRUE)
205
+
206
  context_parts <- c(context_parts,
207
  sprintf("\nQTL Results: %d significant QTLs detected above LOD %.1f.", n_qtl, rv$lod_threshold),
208
  sprintf("Total variance explained by QTLs: %.1f%%.", total_pve))
209
+
210
  top_qtls <- head(rv$qtl_effects_train[order(-rv$qtl_effects_train$LOD), ], 3)
211
  context_parts <- c(context_parts, "\nTop QTLs:")
212
  for (i in 1:nrow(top_qtls)) {
 
216
  i, row$Marker, row$Chromosome, row$LOD, row$PVE_Percent, row$Additive_Effect))
217
  }
218
  }
219
+
220
  if (!is.null(rv$performance_metrics)) {
221
  pm <- rv$performance_metrics
222
  train_r2 <- pm$Value[pm$Metric == "R\u00b2 (Train)"]
 
226
  sprintf(" Training R\u00b2: %.3f", train_r2),
227
  sprintf(" Validation R\u00b2: %.3f", val_r2))
228
  }
229
+
230
  if (!is.null(rv$epistasis_sig) && !"Message" %in% colnames(rv$epistasis_sig) && nrow(rv$epistasis_sig) > 0) {
231
  n_epi <- nrow(rv$epistasis_sig)
232
  top_epi <- rv$epistasis_sig[order(rv$epistasis_sig$Interaction_p), ][1, ]
 
234
  sprintf("\nEpistasis: %d significant pairwise interactions detected.", n_epi),
235
  sprintf(" Strongest: %s x %s (p=%.4f)", top_epi$QTL1, top_epi$QTL2, top_epi$Interaction_p))
236
  }
237
+
238
  if (!is.null(rv$selection_metrics) && !"Message" %in% colnames(rv$selection_metrics)) {
239
  n_sig <- sum(rv$selection_metrics$Significant, na.rm = TRUE)
240
  context_parts <- c(context_parts,
241
  sprintf("\nDomestication: %d markers with selection signatures.", n_sig))
242
  }
243
+
244
  paste(context_parts, collapse = "\n")
245
  }
246
 
 
250
 
251
  enhanced_rule_response <- function(user_message, rv) {
252
  q <- tolower(trimws(user_message))
253
+
254
  has_qtl <- !is.null(rv$qtl_effects_train) && !"Message" %in% colnames(rv$qtl_effects_train)
255
  has_perf <- !is.null(rv$performance_metrics)
256
  has_epi <- !is.null(rv$epistasis_sig) && !"Message" %in% colnames(rv$epistasis_sig) && nrow(rv$epistasis_sig) > 0
257
  has_sel <- !is.null(rv$selection_metrics) && !"Message" %in% colnames(rv$selection_metrics)
258
+
259
  if (grepl("pve|variance explained|how much variance|percent variance|what is pve", q)) {
260
  if (has_qtl) {
261
  df <- rv$qtl_effects_train
262
  total_pve <- sum(df$PVE_Percent, na.rm = TRUE)
263
  top_pve <- df[which.max(df$PVE_Percent), ]
264
+
265
  response <- paste0(
266
  "\U0001f4ca **PVE (Phenotypic Variance Explained) Analysis**\n\n",
267
  "**Your Results:**\n",
 
273
  "\u2022 PVE: **", round(top_pve$PVE_Percent, 1), "%**\n",
274
  "\u2022 LOD: ", round(top_pve$LOD, 2), "\n\n"
275
  )
276
+
277
  if (top_pve$PVE_Percent > 10) {
278
  response <- paste0(response, "\U0001f4a1 This is a **major-effect QTL** (>10% PVE).\n\n")
279
  } else if (top_pve$PVE_Percent > 5) {
 
281
  } else {
282
  response <- paste0(response, "\U0001f4a1 This is a **minor-effect QTL** (<5% PVE).\n\n")
283
  }
284
+
285
  response <- paste0(response, "**All QTLs by PVE:**\n")
286
  df_sorted <- df[order(-df$PVE_Percent), ]
287
  for (i in 1:min(5, nrow(df_sorted))) {
 
293
  return("No QTL results yet. Please run the QTL analysis first to see PVE values.")
294
  }
295
  }
296
+
297
  if (grepl("model performance|r2|r squared|how good is my model|validation|negative r2", q)) {
298
  if (has_perf) {
299
  pm <- rv$performance_metrics
300
  train_r2 <- pm$Value[pm$Metric == "R\u00b2 (Train)"]
301
  val_r2 <- pm$Value[pm$Metric == "R\u00b2 (Validation)"]
302
+
303
  response <- paste0(
304
  "\U0001f4c8 **Model Performance Summary**\n\n",
305
  "\u2022 Training R\u00b2: **", round(train_r2, 3), "**\n",
306
  "\u2022 Validation R\u00b2: **", round(val_r2, 3), "**\n\n"
307
  )
308
+
309
  if (val_r2 < 0) {
310
  response <- paste0(response,
311
  "\u26a0\ufe0f **Your validation R\u00b2 is negative** (", round(val_r2, 3), ").\n\n",
 
329
  return("Run the QTL analysis first to see model performance metrics.")
330
  }
331
  }
332
+
333
  if (grepl("top qtl|best qtl|highest lod|significant qtl|list qtl|show qtl", q)) {
334
  if (has_qtl) {
335
  df <- rv$qtl_effects_train[order(-rv$qtl_effects_train$LOD), ]
336
  top5 <- head(df, 5)
337
+
338
  response <- "\U0001f3af **Top 5 QTLs by LOD Score**\n\n"
339
  for (i in 1:nrow(top5)) {
340
  row <- top5[i, ]
 
349
  return("No significant QTLs detected. Try lowering the LOD threshold.")
350
  }
351
  }
352
+
353
  if (grepl("next steps|what next|recommendations|suggest|advice|what should i do", q)) {
354
  if (has_qtl || has_perf || has_epi || has_sel) {
355
  response <- "\U0001f52c **Recommended Next Steps**\n\n"
356
+
357
  if (has_qtl) {
358
  top_qtl <- rv$qtl_effects_train[which.max(rv$qtl_effects_train$LOD), ]
359
  response <- paste0(response,
 
369
  response <- paste0(response, "**3. Domestication Analysis**\n",
370
  " \u2022 ", sum(rv$selection_metrics$Significant, na.rm = TRUE), " selection signatures\n\n")
371
  }
372
+
373
  response <- paste0(response,
374
  "**4. Functional Analysis**\n",
375
  " \u2022 Annotate QTL regions for candidate genes\n\n",
 
380
  return("Run the QTL analysis first to get recommendations.")
381
  }
382
  }
383
+
384
  available <- c()
385
  if (has_qtl) available <- c(available, paste(nrow(rv$qtl_effects_train), "QTLs"))
386
  if (has_perf) {
 
389
  }
390
  if (has_epi) available <- c(available, paste(nrow(rv$epistasis_sig), "interactions"))
391
  if (has_sel) available <- c(available, paste(sum(rv$selection_metrics$Significant), "selection signatures"))
392
+
393
  if (length(available) > 0) {
394
  return(paste0(
395
  "I can see you have: ", paste(available, collapse = ", "), ".\n\n",
 
399
  "\u2022 **Model performance**\n",
400
  "\u2022 **Next steps**"))
401
  }
402
+
403
  return(paste0(
404
+ "\U0001f44b Vanakam! I'm TerraByte-AI powered Companion.\n\n",
405
  "**I can help you with:**\n",
406
  "\u2022 Understanding PVE\n",
407
  "\u2022 Interpreting LOD scores\n",
 
414
  # AI RESPONSE GENERATION
415
  # ============================================================
416
 
417
+ generate_ai_response <- function(user_message, rv, model_id = default_model) {
 
418
  context <- build_system_prompt(rv)
419
+
420
+ current_use_api <- token_exists
421
+
422
+ if (current_use_api) {
423
+ prompt <- paste(
424
+ "CONTEXT:", context,
425
+ "\n\nUSER QUESTION:", user_message,
426
+ "\n\nProvide a specific, helpful answer based ONLY on the context above. Be concise but informative.",
427
+ sep = "\n"
428
+ )
429
+
430
+ result <- query_hf_api(prompt, model_id = model_id)
431
+
 
 
 
 
 
432
  if (result$success) {
433
  return(result$text)
434
  } else {
 
 
 
 
 
 
 
 
435
  message("API Error: ", result$error)
436
  return(enhanced_rule_response(user_message, rv))
437
  }
438
  }
439
+
440
  return(enhanced_rule_response(user_message, rv))
441
  }
442
 
 
446
 
447
  ui <- fluidPage(
448
  shinyjs::useShinyjs(),
449
+
450
  tags$head(
451
  tags$link(rel = "stylesheet", type = "text/css",
452
  href = "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css"),
 
630
  .chat-file-bubble i { font-size: 14px; }
631
  "))
632
  ),
633
+
634
  navbarPage(
635
  title = tags$span(tags$i(class = "fas fa-dna", style = "margin-right:8px; color:#58a6ff;"), "QTL-Mapper AI"),
636
  id = "nav",
637
+
638
  # ---- Data Upload tab ----
639
  tabPanel("Data Upload", icon = icon("upload"),
640
  div(class = "main-header",
 
692
  )
693
  )
694
  ),
695
+
696
  # ---- Domestication tab ----
697
  tabPanel("Domestication", icon = icon("leaf"),
698
  div(class = "main-header",
 
736
  )
737
  )
738
  ),
739
+
740
  # ---- Results tab ----
741
  tabPanel("Results", icon = icon("chart-line"),
742
  div(class = "main-header",
 
777
  ))
778
  )
779
  ),
780
+
781
  # ---- Interpretation tab ----
782
  tabPanel("Interpretation", icon = icon("lightbulb"),
783
  div(class = "main-header",
 
792
  fluidRow(column(12, div(class = "card", div(class = "card-header", "Epistasis"), div(class = "card-body", uiOutput("epistasis_interpretation"))))),
793
  fluidRow(column(12, div(class = "card", div(class = "card-header", "Recommendations"), div(class = "card-body", uiOutput("recommendations")))))
794
  ),
795
+
796
  # ---- About tab ----
797
  tabPanel("About", icon = icon("info-circle"),
798
  div(class = "main-header",
 
817
  tags$thead(tags$tr(
818
  tags$th(style = "text-align:left; padding:6px; border-bottom:1px solid #30363d; color:#58a6ff;", "Model"),
819
  tags$th(style = "text-align:left; padding:6px; border-bottom:1px solid #30363d; color:#58a6ff;", "Provider"),
 
820
  tags$th(style = "text-align:left; padding:6px; border-bottom:1px solid #30363d; color:#58a6ff;", "Tier")
821
  )),
822
  tags$tbody(
823
  lapply(available_models, function(m) {
 
824
  tags$tr(
825
  tags$td(style = "padding:6px; border-bottom:1px solid #21262d;", m$label),
826
  tags$td(style = "padding:6px; border-bottom:1px solid #21262d;", m$provider),
827
+ tags$td(style = "padding:6px; border-bottom:1px solid #21262d;", tags$span(style = "color:#3fb950;", m$tier))
 
 
828
  )
829
  })
830
  )
 
847
  )
848
  )
849
  ),
850
+
851
  # ============================================================
852
  # FLOATING CHAT PANEL (with model selector + file upload)
853
  # ============================================================
854
  tags$div(id = "chat-panel",
855
  tags$div(id = "chat-window",
856
+
857
  # Chat header
858
  tags$div(id = "chat-header",
859
  tags$div(class = "chat-header-top",
 
870
  onclick = "document.getElementById('chat-window').classList.remove('open');",
871
  tags$i(class = "fas fa-times"))
872
  ),
873
+
874
  # Model selector row
875
  tags$div(class = "chat-model-selector",
876
  tags$label(tags$i(class = "fas fa-robot"), " Model:"),
 
882
  actionButton("test_model_btn", "Test", class = "test-model-btn")
883
  )
884
  ),
885
+
886
  # Quick question buttons
887
  tags$div(class = "quick-questions",
888
  tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q','What is PVE?',{priority:'event'});", "PVE meaning"),
 
890
  tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q','Why is my R2 negative?',{priority:'event'});","Negative R2"),
891
  tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q','What should I do next?',{priority:'event'});","Next steps")
892
  ),
893
+
894
  # Messages area
895
  tags$div(id = "chat_messages", uiOutput("chat_display")),
896
+
897
  # Footer
898
  tags$div(id = "chat-footer",
899
+
900
  # File upload row
901
  tags$div(class = "chat-file-row",
902
  tags$label(
 
904
  tags$i(class = "fas fa-paperclip"),
905
  " Attach file",
906
  fileInput("chat_file_upload", label = NULL,
907
+ accept = c(".csv", ".txt", ".tsv", ".xlsx", ".pdf"),
908
  buttonLabel = "",
909
  placeholder = "",
910
  width = "0px")
 
914
  onclick = "document.getElementById('chat_file_preview').style.display='none'; document.getElementById('chat_file_preview').innerHTML=''; Shiny.setInputValue('clear_chat_file', Math.random());",
915
  tags$i(class = "fas fa-times"))
916
  ),
917
+
918
  # Text input
919
  tags$textarea(id = "chat_input",
920
  placeholder = "Ask about your results... (Enter to send)",
921
  rows = "2"),
922
+
923
  # Action buttons
924
  tags$div(class = "chat-actions",
925
  actionButton("send_chat", "Send", icon = icon("paper-plane"), class = "btn-primary"),
 
927
  )
928
  )
929
  ),
930
+
931
  # Toggle button
932
  tags$button(id = "chat-toggle-btn",
933
  onclick = "document.getElementById('chat-window').classList.toggle('open');",
934
  tags$i(class = "fas fa-robot"))
935
  ),
936
+
937
  # JS to show filename on file selection
938
  tags$script(HTML("
939
  $(document).on('change', '#chat_file_upload', function() {
 
952
  # ============================================================
953
 
954
  server <- function(input, output, session) {
955
+
956
  values <- reactiveValues(
957
  genotype_data = NULL,
958
  phenotype_data = NULL,
 
981
  current_model = default_model,
982
  model_test_status = if (use_hf_api) "online" else "offline",
983
  pending_file_content = NULL,
984
+ pending_file_name = NULL
 
 
 
985
  )
986
+
987
  # ---- Current selected model ----
988
  observe({
989
  req(input$selected_model)
990
  values$current_model <- input$selected_model
991
+
992
  # Update status display
993
  model_label <- names(model_choices)[model_choices == input$selected_model]
994
  if (is.null(model_label) || length(model_label) == 0)
995
  model_label <- gsub(".*/([^:]+):.*", "\\1", input$selected_model)
996
+
997
  shinyjs::html("model_status_text",
998
  if (token_exists) paste("AI:", gsub(".*\\[(.*)\\]", "\\1", model_label), "- ready")
999
  else "Rule-based mode (no token)")
1000
  })
1001
+
1002
  # ---- Test model button ----
1003
  observeEvent(input$test_model_btn, {
1004
  req(input$selected_model)
1005
  add_message("assistant", paste0("\u23f3 Testing model: **", gsub(".*/", "", input$selected_model), "**..."))
1006
+
1007
  result <- test_api_connection(input$selected_model)
1008
  if (result$success) {
1009
  add_message("assistant", paste0("\u2705 **", gsub(".*/", "", input$selected_model), "** is working! You can now chat with this model."))
 
1014
  shinyjs::runjs("document.getElementById('model_status_dot').className = 'model-status-dot offline';")
1015
  }
1016
  })
1017
+
1018
  # ---- Chat helpers ----
1019
+ add_message <- function(role, content, model_used = NULL) {
 
1020
  timestamp <- format(Sys.time(), "%H:%M")
1021
  values$chat_messages <- c(values$chat_messages,
1022
+ list(list(role = role, content = content,
1023
+ time = timestamp, model = model_used)))
 
 
 
 
1024
  if (length(values$chat_messages) > 100)
1025
  values$chat_messages <- tail(values$chat_messages, 100)
1026
  session$sendCustomMessage("scrollChatBottom", list())
1027
  }
1028
+
1029
+ process_message <- function(user_text, file_content = NULL, file_name = NULL) {
1030
+ if (nchar(trimws(user_text)) == 0 && is.null(file_content)) return()
1031
+
1032
+ # Build full message including file content if present
1033
+ full_message <- user_text
1034
+ if (!is.null(file_content) && nchar(trimws(file_content)) > 0) {
1035
+ full_message <- paste0(user_text,
1036
+ if (nchar(trimws(user_text)) > 0) "\n\n" else "",
1037
+ "--- Attached file: ", file_name, " ---\n",
1038
+ substr(file_content, 1, 3000),
1039
+ if (nchar(file_content) > 3000) "\n[... truncated ...]" else "")
 
 
 
 
 
 
 
 
 
 
 
1040
  }
1041
+
1042
+ add_message("user", full_message)
 
 
1043
  values$is_typing <- TRUE
1044
+
1045
  model_id <- isolate(values$current_model)
1046
+ response <- generate_ai_response(full_message, values, model_id = model_id)
1047
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1048
  values$is_typing <- FALSE
1049
  model_short <- gsub(".*/([^:]+):.*", "\\1", model_id)
1050
  add_message("assistant", response, model_used = if (token_exists) model_short else NULL)
1051
+
1052
+ # Clear pending file
1053
  values$pending_file_content <- NULL
1054
  values$pending_file_name <- NULL
 
 
 
1055
  }
1056
+
1057
  # ---- Handle chat file upload ----
1058
  observeEvent(input$chat_file_upload, {
1059
  req(input$chat_file_upload)
1060
  file_path <- input$chat_file_upload$datapath
1061
  file_name <- input$chat_file_upload$name
1062
  ext <- tolower(tools::file_ext(file_name))
1063
+
 
 
 
 
 
 
 
1064
  tryCatch({
1065
+ file_content <- if (ext %in% c("csv", "txt", "tsv")) {
1066
+ paste(readLines(file_path, n = 200), collapse = "\n")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1067
  } else {
1068
+ paste0("[Binary file: ", file_name, " - ", round(file.info(file_path)$size / 1024, 1), " KB]")
 
 
1069
  }
1070
+
1071
+ values$pending_file_content <- file_content
1072
+ values$pending_file_name <- file_name
1073
  }, error = function(e) {
1074
  showNotification(paste("Could not read file:", e$message), type = "warning")
1075
  })
1076
  })
1077
+
1078
+ # ---- Clear chat file ----
1079
  observeEvent(input$clear_chat_file, {
1080
  values$pending_file_content <- NULL
1081
  values$pending_file_name <- NULL
 
 
 
1082
  })
1083
+
1084
  # ---- Send chat ----
1085
  observeEvent(input$send_chat, {
1086
+ user_text <- trimws(input$chat_input)
1087
  file_content <- isolate(values$pending_file_content)
1088
  file_name <- isolate(values$pending_file_name)
1089
+
1090
+ if (nchar(user_text) == 0 && is.null(file_content)) return()
1091
+
 
 
 
 
 
1092
  updateTextAreaInput(session, "chat_input", value = "")
1093
+ # Clear file preview via JS
1094
  shinyjs::runjs("
1095
  document.getElementById('chat_file_preview').style.display = 'none';
1096
  document.getElementById('chat_file_preview').innerHTML = '';
1097
  ")
1098
+
1099
+ process_message(user_text, file_content, file_name)
 
 
 
 
 
1100
  })
1101
+
1102
  observeEvent(input$quick_q, { req(input$quick_q); process_message(input$quick_q) })
1103
+
1104
  observeEvent(input$clear_chat, {
1105
  values$chat_messages <- list()
1106
  add_message("assistant", "Chat cleared. How can I help?")
1107
  })
1108
+
1109
  # ---- Initial greeting ----
1110
  observe({
1111
  if (length(values$chat_messages) == 0) {
 
1116
  "I'm using rule-based responses. Set **HF_API_TOKEN** in Space secrets to enable AI models."
1117
  }
1118
  add_message("assistant", paste0(
1119
+ "\U0001f44b Vanakam! I'm TerraByte - An AI powered companion.\n\n",
1120
  mode_msg,
1121
  "\n\n**I can help you with:**\n",
1122
  "\u2022 **What is PVE?** - Understand variance explained\n",
 
1128
  ))
1129
  }
1130
  })
1131
+
1132
  # ---- Chat display ----
1133
  output$chat_display <- renderUI({
1134
  messages <- values$chat_messages
1135
  if (length(messages) == 0) return(NULL)
1136
+
1137
  elems <- lapply(messages, function(msg) {
1138
  content_html <- HTML(gsub("\n", "<br>", htmltools::htmlEscape(msg$content)))
1139
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1140
  meta_content <- tagList(
1141
  span(msg$time),
1142
  if (!is.null(msg$model) && msg$role == "assistant")
1143
  span(class = "model-tag", paste0("[", msg$model, "]"))
1144
  )
1145
+
1146
  div(class = paste("chat-msg", msg$role),
1147
+ div(class = "chat-bubble", content_html),
 
 
1148
  div(class = "chat-meta", meta_content))
1149
  })
1150
+
1151
  if (values$is_typing) {
1152
  elems <- c(elems, list(
1153
  div(class = "chat-msg assistant",
 
1156
  }
1157
  do.call(tagList, elems)
1158
  })
1159
+
1160
  # ============================================================
1161
  # DATA LOADING
1162
  # ============================================================
1163
+
1164
  observeEvent(input$genotype_file, {
1165
  req(input$genotype_file)
1166
  tryCatch({
1167
  all_data <- readLines(input$genotype_file$datapath)
1168
  if (length(all_data) < 4) { showNotification("Genotype file must have at least 4 rows", type = "error"); return() }
1169
+
1170
  header <- strsplit(all_data[1], ",")[[1]]
1171
  chromosome_row <- strsplit(all_data[2], ",")[[1]]
1172
  position_row <- strsplit(all_data[3], ",")[[1]]
1173
+
1174
  genotype_data <- read.csv(text = all_data[-(1:3)], header = FALSE)
1175
  colnames(genotype_data) <- header
1176
  rownames(genotype_data) <- genotype_data[, 1]
1177
  genotype_data <- genotype_data[, -1]
1178
+
1179
  for (col in colnames(genotype_data))
1180
  genotype_data[[col]] <- as.numeric(as.character(genotype_data[[col]]))
1181
+
1182
  values$all_markers <- data.frame(
1183
  Marker = colnames(genotype_data),
1184
  Chromosome = chromosome_row[-1],
1185
  Position = as.numeric(position_row[-1]),
1186
  stringsAsFactors = FALSE)
1187
+
1188
  values$genotype_data <- genotype_data
1189
  values$chromosome_info <- chromosome_row[-1]
1190
  values$position_info <- as.numeric(position_row[-1])
1191
+
1192
  showNotification("Genotype data loaded", type = "message")
1193
  add_message("assistant", paste0("\u2705 Loaded genotype data: **", ncol(genotype_data), " markers**, **", nrow(genotype_data), " samples**"))
1194
  }, error = function(e) showNotification(paste("Error:", e$message), type = "error"))
1195
  })
1196
+
1197
  observeEvent(input$phenotype_file, {
1198
  req(input$phenotype_file)
1199
  tryCatch({
1200
  phenotype_data <- read.csv(input$phenotype_file$datapath)
1201
  rownames(phenotype_data) <- phenotype_data[, 1]
1202
  phenotype_data <- phenotype_data[, -1]
1203
+
1204
  for (col in colnames(phenotype_data))
1205
  phenotype_data[[col]] <- as.numeric(as.character(phenotype_data[[col]]))
1206
+
1207
  values$phenotype_data <- phenotype_data
1208
  updateSelectInput(session, "phenotype_column",
1209
  choices = colnames(phenotype_data),
1210
  selected = colnames(phenotype_data)[1])
1211
+
1212
  showNotification("Phenotype data loaded", type = "message")
1213
  add_message("assistant", paste0("\u2705 Loaded phenotype data: **", ncol(phenotype_data), " traits**, **", nrow(phenotype_data), " samples**"))
1214
  }, error = function(e) showNotification(paste("Error:", e$message), type = "error"))
1215
  })
1216
+
1217
  observeEvent(input$pop_file, {
1218
  req(input$pop_file)
1219
  tryCatch({
 
1226
  add_message("assistant", paste0("\u2705 Loaded population data (", nrow(pop_data), " samples)"))
1227
  }, error = function(e) showNotification(paste("Error:", e$message), type = "error"))
1228
  })
1229
+
1230
  observeEvent(input$test_genotype_file, {
1231
  req(input$test_genotype_file)
1232
  tryCatch({
1233
  all_data <- readLines(input$test_genotype_file$datapath)
1234
  header <- strsplit(all_data[1], ",")[[1]]
1235
+
1236
  genotype_data <- read.csv(text = all_data[-(1:3)], header = FALSE)
1237
  colnames(genotype_data) <- header
1238
  rownames(genotype_data) <- genotype_data[, 1]
1239
  genotype_data <- genotype_data[, -1]
1240
+
1241
  for (col in colnames(genotype_data))
1242
  genotype_data[[col]] <- as.numeric(as.character(genotype_data[[col]]))
1243
+
1244
  values$test_genotype_data <- genotype_data
1245
  values$has_test_data <- TRUE
1246
  showNotification("Test genotype data loaded", type = "message")
1247
  }, error = function(e) showNotification(paste("Error:", e$message), type = "error"))
1248
  })
1249
+
1250
  # ---- Data previews ----
1251
  output$geno_preview <- renderDT({ req(input$genotype_file); datatable(head(read.csv(input$genotype_file$datapath), 10), options = list(scrollX = TRUE, pageLength = 5)) })
1252
  output$pheno_preview <- renderDT({ req(input$phenotype_file); datatable(head(read.csv(input$phenotype_file$datapath), 10), options = list(scrollX = TRUE, pageLength = 5)) })
1253
  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)) })
1254
  output$pop_preview <- renderDT({ req(input$pop_file); datatable(head(read.csv(input$pop_file$datapath), 10), options = list(scrollX = TRUE, pageLength = 5)) })
1255
  output$predicted_test_pheno_preview <- renderDT({ req(values$predicted_test_phenotype_data); datatable(values$predicted_test_phenotype_data, options = list(scrollX = TRUE, pageLength = 5)) })
1256
+
1257
  # ============================================================
1258
  # QTL EFFECT CALCULATION
1259
  # ============================================================
1260
+
1261
  calculate_qtl_effects <- function(genotype_matrix, phenotype_vector, marker_names) {
1262
  effects_list <- list()
1263
+
1264
  for (marker in marker_names) {
1265
  if (!marker %in% colnames(genotype_matrix)) next
1266
+
1267
  geno <- genotype_matrix[, marker]
1268
  pheno <- phenotype_vector
1269
  valid_idx <- !is.na(geno) & !is.na(pheno)
1270
  geno <- geno[valid_idx]
1271
  pheno <- pheno[valid_idx]
1272
+
1273
  if (length(unique(geno)) < 2) next
1274
+
1275
  lm_fit <- lm(pheno ~ geno)
1276
  additive_effect <- coef(lm_fit)[2]
1277
+
1278
  dominance_effect <- NA
1279
  if (length(unique(geno)) == 3) {
1280
  geno_means <- tapply(pheno, geno, mean, na.rm = TRUE)
 
1283
  geno_means[as.character(sort(unique(geno))[3])]) / 2
1284
  dominance_effect <- het_mean - midparent
1285
  }
1286
+
1287
  r_squared <- summary(lm_fit)$r.squared
1288
  se_additive <- tryCatch(summary(lm_fit)$coefficients[2, 2], error = function(e) NA)
1289
+
1290
  effects_list[[marker]] <- data.frame(
1291
  Marker = marker,
1292
  Additive_Effect = additive_effect,
 
1298
  N_Samples = length(pheno),
1299
  stringsAsFactors = FALSE)
1300
  }
1301
+
1302
  if (length(effects_list) == 0) return(NULL)
1303
  do.call(rbind, effects_list)
1304
  }
1305
+
1306
  # ============================================================
1307
  # MAIN QTL ANALYSIS
1308
  # ============================================================
1309
+
1310
  observeEvent(input$run_analysis, {
1311
  req(values$genotype_data, values$phenotype_data, input$phenotype_column)
1312
  showNotification("Starting QTL analysis...", type = "message")
1313
  values$lod_threshold <- input$lod_threshold
1314
+
1315
  tryCatch({
1316
  common_samples <- intersect(rownames(values$genotype_data), rownames(values$phenotype_data))
1317
  if (length(common_samples) == 0) { showNotification("No common samples", type = "error"); return() }
1318
+
1319
  X <- values$genotype_data[common_samples, , drop = FALSE]
1320
  y <- as.numeric(values$phenotype_data[common_samples, input$phenotype_column])
1321
  nzv <- nearZeroVar(X)
1322
  if (length(nzv) > 0) X <- X[, -nzv, drop = FALSE]
1323
+
1324
  set.seed(123)
1325
  train_index <- createDataPartition(y, p = 1 - input$test_size, list = FALSE)
1326
  X_train <- X[train_index, , drop = FALSE]; X_val <- X[-train_index, , drop = FALSE]
1327
  y_train <- y[train_index]; y_val <- y[-train_index]
1328
+
1329
  model <- train(x = X_train, y = y_train, method = "rf",
1330
  trControl = trainControl(method = "cv", number = 5),
1331
  importance = TRUE, tuneLength = 3)
1332
+
1333
  values$model_fit <- model
1334
+
1335
  imp <- varImp(model, scale = FALSE)$importance
1336
  importance_scores <- data.frame(
1337
  Marker = rownames(imp),
 
1339
  Chromosome = values$chromosome_info[match(rownames(imp), colnames(X))],
1340
  Position = as.numeric(values$position_info[match(rownames(imp), colnames(X))]),
1341
  stringsAsFactors = FALSE)
1342
+
1343
  values$importance_scores <- importance_scores
1344
  lod_sig <- importance_scores[importance_scores$LOD > input$lod_threshold, , drop = FALSE]
1345
+
1346
  if (nrow(lod_sig) > 0) {
1347
  lod_sig$Low_Flank <- NA
1348
  lod_sig$High_Flank <- NA
1349
+
1350
  for (i in 1:nrow(lod_sig)) {
1351
  chr_m <- values$all_markers[values$all_markers$Chromosome == lod_sig$Chromosome[i], ]
1352
  chr_m <- chr_m[order(chr_m$Position), ]
 
1356
  lod_sig$High_Flank[i] <- if (idx < nrow(chr_m)) chr_m$Marker[idx + 1] else lod_sig$Marker[i]
1357
  }
1358
  }
1359
+
1360
  values$lod_scores_train <- lod_sig
1361
  qtl_fx <- calculate_qtl_effects(X_train, y_train, lod_sig$Marker)
1362
+
1363
  if (!is.null(qtl_fx)) {
1364
  values$qtl_effects_train <- merge(lod_sig, qtl_fx, by = "Marker")
1365
  } else {
 
1369
  values$lod_scores_train <- data.frame(Message = paste("No QTLs above LOD", input$lod_threshold))
1370
  values$qtl_effects_train <- data.frame(Message = paste("No QTLs above LOD", input$lod_threshold))
1371
  }
1372
+
1373
  y_train_pred <- predict(model, X_train)
1374
  y_val_pred <- predict(model, X_val)
1375
  train_r2 <- 1 - sum((y_train - y_train_pred)^2) / sum((y_train - mean(y_train))^2)
1376
  val_r2 <- 1 - sum((y_val - y_val_pred)^2) / sum((y_val - mean(y_val))^2)
1377
+
1378
  values$performance_metrics <- data.frame(
1379
  Metric = c("R\u00b2 (Train)", "R (Train)", "R\u00b2 (Validation)", "R (Validation)"),
1380
  Value = c(train_r2, cor(y_train, y_train_pred), val_r2, cor(y_val, y_val_pred)),
1381
  stringsAsFactors = FALSE)
1382
+
1383
  values$train_predictions <- data.frame(Observed = y_train, Predicted = y_train_pred)
1384
  values$test_predictions <- data.frame(Observed = y_val, Predicted = y_val_pred)
1385
+
1386
  # Epistasis
1387
  if (nrow(lod_sig) > 0) {
1388
  sig_markers <- lod_sig$Marker[lod_sig$Marker %in% colnames(X_train)]
1389
  all_markers_v <- colnames(X_train)
1390
  epistasis_list <- list()
1391
+
1392
  withProgress(message = "Calculating epistasis...", value = 0, {
1393
  total <- length(sig_markers) * length(all_markers_v)
1394
  for (m1 in sig_markers) {
 
1412
  }
1413
  }
1414
  })
1415
+
1416
  if (length(epistasis_list) > 0) {
1417
  epistasis_all <- do.call(rbind, epistasis_list)
1418
  values$epistasis_all <- epistasis_all
 
1422
  values$epistasis_sig <- data.frame(Message = "No epistatic interactions")
1423
  }
1424
  }
1425
+
1426
  showNotification("QTL analysis completed!", type = "message")
1427
  n_qtl <- if (!is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train)) nrow(values$qtl_effects_train) else 0
1428
  add_message("assistant", paste0(
 
1431
  "\u2022 Validation R\u00b2: **", round(val_r2, 3), "**\n\n",
1432
  "Ask me about PVE, top QTLs, or next steps!"))
1433
  updateTabsetPanel(session, "nav", selected = "Results")
1434
+
1435
  }, error = function(e) showNotification(paste("Error:", e$message), type = "error"))
1436
  })
1437
+
1438
  # ============================================================
1439
  # DOMESTICATION ANALYSIS
1440
  # ============================================================
1441
+
1442
  calculate_selection_metrics <- function(genotype_matrix, pop_data, marker_info) {
1443
  metrics_list <- list()
1444
+
1445
  for (marker in colnames(genotype_matrix)) {
1446
  geno <- genotype_matrix[, marker]
1447
  pop <- pop_data$population[match(rownames(genotype_matrix), pop_data$id)]
1448
  valid_idx <- !is.na(geno) & !is.na(pop)
1449
  geno <- geno[valid_idx]; pop <- pop[valid_idx]
1450
+
1451
  if (length(unique(pop)) < 2) next
1452
  geno_dom <- geno[pop == "Domesticated"]
1453
  geno_wild <- geno[pop == "Wild"]
1454
  if (length(geno_dom) < 3 || length(geno_wild) < 3) next
1455
+
1456
  freq_dom <- mean(geno_dom, na.rm = TRUE) / 2
1457
  freq_wild <- mean(geno_wild, na.rm = TRUE) / 2
1458
  p_avg <- (freq_dom + freq_wild) / 2
1459
+
1460
  fst <- if (p_avg > 0 && p_avg < 1) {
1461
  f <- (freq_dom - freq_wild)^2 / (p_avg * (1 - p_avg))
1462
  f / (1 + f)
1463
  } else 0
1464
+
1465
  pi_dom <- 2 * freq_dom * (1 - freq_dom)
1466
  pi_wild <- 2 * freq_wild * (1 - freq_wild)
1467
  n_dom <- length(geno_dom)
1468
  n_wild <- length(geno_wild)
1469
+
1470
  tajima_d_dom <- (pi_dom - 1/n_dom) / sqrt(var(geno_dom) /n_dom)
1471
  tajima_d_wild <- (pi_wild - 1/n_wild) / sqrt(var(geno_wild)/n_wild)
1472
+
1473
  marker_row <- marker_info[marker_info$Marker == marker, ]
1474
  metrics_list[[marker]] <- data.frame(
1475
  Marker = marker,
 
1479
  Tajima_D_Dom = tajima_d_dom, Tajima_D_Wild = tajima_d_wild,
1480
  stringsAsFactors = FALSE)
1481
  }
1482
+
1483
  if (length(metrics_list) == 0) return(NULL)
1484
  do.call(rbind, metrics_list)
1485
  }
1486
+
1487
  observeEvent(input$run_domestication, {
1488
  req(values$genotype_data, values$pop_data, values$all_markers)
1489
  tryCatch({
1490
  common_samples <- intersect(rownames(values$genotype_data), values$pop_data$id)
1491
  if (length(common_samples) == 0) { showNotification("No common samples", type = "error"); return() }
1492
+
1493
  X <- values$genotype_data[common_samples, , drop = FALSE]
1494
  pop_subset <- values$pop_data[values$pop_data$id %in% common_samples, ]
1495
  sel_metrics <- calculate_selection_metrics(X, pop_subset, values$all_markers)
1496
+
1497
  if (is.null(sel_metrics)) { showNotification("Could not calculate selection metrics", type = "error"); return() }
1498
+
1499
  sel_metrics$Significant <-
1500
  sel_metrics$Fst > input$fst_threshold |
1501
  sel_metrics$Tajima_D_Dom < input$tajima_threshold |
1502
  sel_metrics$Tajima_D_Wild < input$tajima_threshold
1503
+
1504
  values$selection_metrics <- sel_metrics
1505
  showNotification("Domestication analysis completed!", type = "message")
1506
  n_sig <- sum(sel_metrics$Significant, na.rm = TRUE)
1507
  add_message("assistant", paste0("\u2705 Domestication analysis complete!\n\n\u2022 Found **", n_sig, " markers** with selection signatures"))
1508
  }, error = function(e) showNotification(paste("Error:", e$message), type = "error"))
1509
  })
1510
+
1511
  # ============================================================
1512
  # PREDICT TEST PHENOTYPES
1513
  # ============================================================
1514
+
1515
  observeEvent(input$predict_test_phenotype, {
1516
  req(values$model_fit, values$test_genotype_data)
1517
  tryCatch({
1518
  common_markers <- intersect(colnames(values$test_genotype_data), colnames(values$genotype_data))
1519
  if (length(common_markers) == 0) { showNotification("No common markers", type = "error"); return() }
1520
+
1521
  X_test <- values$test_genotype_data[, common_markers, drop = FALSE]
1522
  predictions <- predict(values$model_fit, newdata = X_test)
1523
+
1524
  values$predicted_test_phenotype_data <- data.frame(
1525
  id = rownames(X_test),
1526
  Predicted_Phenotype = as.numeric(predictions),
1527
  stringsAsFactors = FALSE)
1528
+
1529
  showNotification("Predictions completed!", type = "message")
1530
  }, error = function(e) showNotification(paste("Error:", e$message), type = "error"))
1531
  })
1532
+
1533
  # ============================================================
1534
  # MANHATTAN PLOT HELPER
1535
  # ============================================================
1536
+
1537
  create_manhattan <- function(data, y_col, title, threshold, y_label = y_col) {
1538
  if (is.null(data) || nrow(data) == 0 || "Message" %in% colnames(data))
1539
  return(plot_ly() %>% layout(title = "No data available",
1540
  plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e")))
1541
+
1542
  plot_data <- data[!is.na(data[[y_col]]), ]
1543
  if (nrow(plot_data) == 0)
1544
  return(plot_ly() %>% layout(title = "No valid data",
1545
  plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e")))
1546
+
1547
  chroms <- unique(plot_data$Chromosome)
1548
  chrom_pos <- data.frame()
1549
  for (i in seq_along(chroms)) {
 
1554
  chrom_pos <- rbind(chrom_pos, chr_data)
1555
  }
1556
  }
1557
+
1558
  p <- plot_ly() %>%
1559
  add_trace(data = chrom_pos, x = ~PosScaled, y = as.formula(paste0("~", y_col)),
1560
  type = "scatter", mode = "markers", color = ~factor(Chromosome),
 
1562
  text = ~paste("Marker:", Marker, "<br>Chr:", Chromosome, "<br>Pos:", Position,
1563
  "<br>", y_label, ":", round(get(y_col), 3)),
1564
  hoverinfo = "text", showlegend = FALSE)
1565
+
1566
  if (!is.null(threshold) && !is.na(threshold))
1567
  p <- p %>% add_segments(
1568
  x = min(chrom_pos$PosScaled, na.rm = TRUE), xend = max(chrom_pos$PosScaled, na.rm = TRUE),
1569
  y = threshold, yend = threshold,
1570
  line = list(color = "red", dash = "dash", width = 1), name = "Threshold")
1571
+
1572
  p %>% layout(title = title,
1573
  xaxis = list(title = "Chromosome",
1574
  ticktext = chroms,
 
1577
  yaxis = list(title = y_label),
1578
  plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))
1579
  }
1580
+
1581
  # ============================================================
1582
  # PLOTS
1583
  # ============================================================
1584
+
1585
  output$lod_plot_2d <- renderPlotly({
1586
  req(values$importance_scores)
1587
  create_manhattan(values$importance_scores, "LOD", "QTL Manhattan Plot", input$lod_threshold, "LOD Score")
1588
  })
1589
+
1590
  output$fst_plot <- renderPlotly({
1591
  req(values$selection_metrics)
1592
  create_manhattan(values$selection_metrics, "Fst", "Fst Manhattan Plot", input$fst_threshold, "Fst")
1593
  })
1594
+
1595
  output$tajima_plot <- renderPlotly({
1596
  req(values$selection_metrics)
1597
  if ("Message" %in% colnames(values$selection_metrics))
1598
  return(plot_ly() %>% layout(title = "No data available", plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e")))
1599
+
1600
  data <- values$selection_metrics
1601
  chroms <- unique(data$Chromosome)
1602
  chrom_pos <- data.frame()
 
1608
  chrom_pos <- rbind(chrom_pos, chr_data)
1609
  }
1610
  }
1611
+
1612
  plot_ly() %>%
1613
  add_trace(data = chrom_pos, x = ~PosScaled, y = ~Tajima_D_Dom, type = "scatter", mode = "markers",
1614
  name = "Domesticated", marker = list(size = 5, color = "#58a6ff", opacity = 0.7),
 
1627
  yaxis = list(title = "Tajima's D"),
1628
  plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))
1629
  })
1630
+
1631
  output$performance_plot <- renderPlotly({
1632
  req(values$performance_metrics)
1633
  plot_ly(data = values$performance_metrics, x = ~Metric, y = ~Value, type = "bar",
 
1637
  yaxis = list(title = "Value", range = c(0, 1.1)),
1638
  plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))
1639
  })
1640
+
1641
  output$regression_plot_train <- renderPlotly({
1642
  req(values$train_predictions)
1643
  plot_ly(data = values$train_predictions, x = ~Observed, y = ~Predicted,
 
1647
  layout(title = "Training Set", xaxis = list(title = "Observed"), yaxis = list(title = "Predicted"),
1648
  plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))
1649
  })
1650
+
1651
  output$regression_plot_test <- renderPlotly({
1652
  req(values$test_predictions)
1653
  plot_ly(data = values$test_predictions, x = ~Observed, y = ~Predicted,
 
1657
  layout(title = "Validation Set", xaxis = list(title = "Observed"), yaxis = list(title = "Predicted"),
1658
  plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))
1659
  })
1660
+
1661
  output$epistasis_heatmap <- renderPlotly({
1662
  req(values$epistasis_all)
1663
  if ("Message" %in% colnames(values$epistasis_all))
1664
  return(plot_ly() %>% layout(title = values$epistasis_all$Message[1],
1665
  plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e")))
1666
+
1667
  qtls <- unique(values$epistasis_all$QTL1)
1668
  markers <- unique(values$epistasis_all$QTL2)
1669
  p_mat <- matrix(NA, nrow = length(qtls), ncol = length(markers),
 
1671
  for (i in 1:nrow(values$epistasis_all))
1672
  p_mat[values$epistasis_all$QTL1[i], values$epistasis_all$QTL2[i]] <-
1673
  -log10(values$epistasis_all$Interaction_p[i])
1674
+
1675
  plot_ly(x = colnames(p_mat), y = rownames(p_mat), z = p_mat,
1676
  type = "heatmap", colorscale = "Viridis",
1677
  hovertemplate = "QTL: %{y}<br>Marker: %{x}<br>-log10(p): %{z:.2f}") %>%
 
1679
  xaxis = list(title = "Marker", tickangle = 45), yaxis = list(title = "QTL"),
1680
  plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))
1681
  })
1682
+
1683
  # ============================================================
1684
  # TABLES
1685
  # ============================================================
1686
+
1687
  output$qtl_effects_table_train <- renderDT({
1688
  req(values$qtl_effects_train)
1689
  if ("Message" %in% colnames(values$qtl_effects_train))
1690
  return(datatable(data.frame(Status = values$qtl_effects_train$Message[1]), options = list(dom = "t")))
1691
+
1692
  display_cols <- intersect(
1693
  c("Marker", "Chromosome", "Position", "LOD", "Additive_Effect", "PVE_Percent", "Low_Flank", "High_Flank"),
1694
  colnames(values$qtl_effects_train))
 
1696
  datatable(df, options = list(pageLength = 10, scrollX = TRUE), rownames = FALSE) %>%
1697
  formatRound(intersect(c("LOD", "Additive_Effect", "PVE_Percent"), colnames(df)), 3)
1698
  })
1699
+
1700
  output$epistasis_table <- renderDT({
1701
  req(values$epistasis_sig)
1702
  if ("Message" %in% colnames(values$epistasis_sig))
 
1705
  options = list(pageLength = 10, scrollX = TRUE), rownames = FALSE) %>%
1706
  formatSignif(columns = c("Interaction_p", "Effect_Size"), digits = 4)
1707
  })
1708
+
1709
  output$selection_table <- renderDT({
1710
  req(values$selection_metrics)
1711
  if ("Message" %in% colnames(values$selection_metrics))
1712
  return(datatable(data.frame(Status = values$selection_metrics$Message[1]), options = list(dom = "t")))
1713
+
1714
  df <- values$selection_metrics
1715
  if (!is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train))
1716
  df$QTL_Overlap <- df$Marker %in% values$qtl_effects_train$Marker
1717
+
1718
  display_cols <- intersect(
1719
  c("Marker", "Chromosome", "Fst", "Pi_Dom", "Pi_Wild", "Tajima_D_Dom", "Significant", "QTL_Overlap"),
1720
  colnames(df))
1721
  datatable(df[order(-df$Fst), display_cols], options = list(pageLength = 10, scrollX = TRUE), rownames = FALSE) %>%
1722
  formatRound(c("Fst", "Pi_Dom", "Pi_Wild", "Tajima_D_Dom"), 3)
1723
  })
1724
+
1725
  # ============================================================
1726
  # CHROMOSOME VISUALIZATION
1727
  # ============================================================
1728
+
1729
  output$chromosome_viz <- renderUI({
1730
  req(values$lod_scores_train, values$all_markers)
1731
  if ("Message" %in% colnames(values$lod_scores_train))
1732
  return(div(class = "alert alert-info", values$lod_scores_train$Message[1]))
1733
+
1734
  chromosomes <- unique(values$lod_scores_train$Chromosome)
1735
  tagList(lapply(chromosomes, function(chr) {
1736
  chr_markers <- values$all_markers[values$all_markers$Chromosome == chr, ]
1737
  chr_markers <- chr_markers[order(chr_markers$Position), ]
1738
  chr_qtls <- values$lod_scores_train[values$lod_scores_train$Chromosome == chr, ]
1739
+
1740
  sel_markers <- NULL
1741
  if (!is.null(values$selection_metrics) && !"Message" %in% colnames(values$selection_metrics))
1742
  sel_markers <- values$selection_metrics[
1743
  values$selection_metrics$Chromosome == chr & values$selection_metrics$Significant, ]
1744
+
1745
  min_pos <- min(chr_markers$Position, na.rm = TRUE)
1746
  max_pos <- max(chr_markers$Position, na.rm = TRUE)
1747
  range_pos <- max_pos - min_pos
1748
+
1749
  div(class = "chromosome-container",
1750
  div(class = "chromosome-title", paste("Chromosome", chr)),
1751
  div(class = "chromosome",
 
1753
  marker <- chr_markers[i, ]
1754
  left <- if (range_pos > 0) ((marker$Position - min_pos) / range_pos) * 100
1755
  else (i / nrow(chr_markers)) * 100
1756
+
1757
  marker_class <- "chromosome-marker"
1758
  if (marker$Marker %in% chr_qtls$Marker) {
1759
  marker_class <- paste(marker_class, "significant")
 
1771
  )
1772
  }))
1773
  })
1774
+
1775
  # ---- Simulation animations ----
1776
  observeEvent(input$simulate_btn, session$sendCustomMessage("simulateQTLDiscovery", list()))
1777
  observeEvent(input$reset_btn, session$sendCustomMessage("resetAnimation", list()))
1778
+
1779
  # ============================================================
1780
  # INTERPRETATION OUTPUTS
1781
  # ============================================================
1782
+
1783
  output$analysis_summary <- renderUI({
1784
  has_qtl <- !is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train)
1785
  has_perf <- !is.null(values$performance_metrics)
1786
  has_epi <- !is.null(values$epistasis_sig) && !"Message" %in% colnames(values$epistasis_sig) && nrow(values$epistasis_sig) > 0
1787
  has_sel <- !is.null(values$selection_metrics) && !"Message" %in% colnames(values$selection_metrics)
1788
+
1789
  n_qtl <- if (has_qtl) nrow(values$qtl_effects_train) else 0
1790
  n_epi <- if (has_epi) nrow(values$epistasis_sig) else 0
1791
  n_sel <- if (has_sel) sum(values$selection_metrics$Significant, na.rm = TRUE) else 0
1792
  val_r2 <- if (has_perf) round(values$performance_metrics$Value[values$performance_metrics$Metric == "R\u00b2 (Validation)"], 3) else "N/A"
1793
+
1794
  div(class = "interpretation-section",
1795
  tags$h5("Analysis Summary"),
1796
  tags$p(paste("Found", n_qtl, "QTLs above LOD", input$lod_threshold,
 
1798
  if (has_epi) paste0("with ", n_epi, " epistatic interactions"),
1799
  if (has_sel) paste0("and ", n_sel, " selection signatures."))))
1800
  })
1801
+
1802
  output$qtl_interpretation <- renderUI({
1803
  if (is.null(values$qtl_effects_train) || "Message" %in% colnames(values$qtl_effects_train))
1804
  return(div(class = "interpretation-section", tags$h5("QTL Significance"), tags$p("No significant QTLs detected.")))
1805
+
1806
  top_qtl <- values$qtl_effects_train[which.max(values$qtl_effects_train$LOD), ]
1807
  div(class = "interpretation-section",
1808
  tags$h5("QTL Significance"),
1809
  tags$p(paste("Top QTL:", top_qtl$Marker, "(Chr", top_qtl$Chromosome, ") with LOD =", round(top_qtl$LOD, 2))))
1810
  })
1811
+
1812
  output$effect_interpretation <- renderUI({
1813
  if (is.null(values$qtl_effects_train) || "Message" %in% colnames(values$qtl_effects_train))
1814
  return(div(class = "interpretation-section", tags$h5("Effect Sizes"), tags$p("No QTL effects to interpret.")))
1815
+
1816
  top_pve <- values$qtl_effects_train[which.max(values$qtl_effects_train$PVE_Percent), ]
1817
  div(class = "interpretation-section",
1818
  tags$h5("Effect Sizes"),
1819
  tags$p(paste("Largest effect:", top_pve$Marker, "explains", round(top_pve$PVE_Percent, 1), "% of variance")))
1820
  })
1821
+
1822
  output$epistasis_interpretation <- renderUI({
1823
  if (is.null(values$epistasis_sig) || "Message" %in% colnames(values$epistasis_sig) || nrow(values$epistasis_sig) == 0)
1824
  return(div(class = "interpretation-section", tags$h5("Epistasis"), tags$p("No significant epistatic interactions detected.")))
1825
+
1826
  top_epi <- values$epistasis_sig[which.min(values$epistasis_sig$Interaction_p), ]
1827
  div(class = "interpretation-section",
1828
  tags$h5("Epistasis"),
1829
  tags$p(paste("Detected", nrow(values$epistasis_sig), "interactions. Strongest:",
1830
  top_epi$QTL1, "x", top_epi$QTL2, "(p =", format.pval(top_epi$Interaction_p), ")")))
1831
  })
1832
+
1833
  output$recommendations <- renderUI({
1834
  has_qtl <- !is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train)
1835
  recs <- if (has_qtl) {
 
1845
  tags$h5("Recommendations"),
1846
  tags$ul(lapply(recs, tags$li), style = "color:#8b949e;"))
1847
  })
1848
+
1849
  # ============================================================
1850
  # DOWNLOAD HANDLERS
1851
  # ============================================================
1852
+
1853
  output$download_train_results <- downloadHandler(
1854
  filename = function() paste0("qtl_results_", Sys.Date(), ".xlsx"),
1855
  content = function(file) {
 
1861
  write_xlsx(sheets, file)
1862
  }
1863
  )
1864
+
1865
  output$download_selection <- downloadHandler(
1866
  filename = function() paste0("selection_", Sys.Date(), ".xlsx"),
1867
  content = function(file) {
 
1875
  }
1876
 
1877
  # ============================================================
1878
+ # RUN APP#
1879
  # ============================================================
1880
 
1881
+ shinyApp(ui = ui, server = server)