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

Update app.R

Browse files
Files changed (1) hide show
  1. app.R +222 -199
app.R CHANGED
@@ -65,7 +65,30 @@ available_models <- list(
65
  label = "Qwen 2.5 7B (Together)",
66
  provider = "together",
67
  tier = "free"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
  )
 
 
 
69
  )
70
 
71
  model_choices <- setNames(
@@ -89,7 +112,7 @@ default_model <- "meta-llama/Llama-3.2-3B-Instruct:together"
89
 
90
  test_api_connection <- function(model_id = default_model) {
91
  if (!token_exists) return(list(success = FALSE, error = "No token found"))
92
-
93
  tryCatch({
94
  response <- POST(
95
  url = HF_API_URL,
@@ -105,10 +128,10 @@ test_api_connection <- function(model_id = default_model) {
105
  encode = "json",
106
  timeout(15)
107
  )
108
-
109
  status <- status_code(response)
110
  if (status == 200) return(list(success = TRUE))
111
-
112
  err <- tryCatch(content(response, "text", encoding = "UTF-8"),
113
  error = function(e) paste("Status:", status))
114
  return(list(success = FALSE,
@@ -132,7 +155,7 @@ if (use_hf_api) {
132
 
133
  query_hf_api <- function(prompt, model_id = default_model, max_length = 500, temperature = 0.7) {
134
  if (!token_exists) return(list(success = FALSE, error = "HF_API_TOKEN not set"))
135
-
136
  tryCatch({
137
  response <- POST(
138
  url = HF_API_URL,
@@ -153,15 +176,15 @@ query_hf_api <- function(prompt, model_id = default_model, max_length = 500, tem
153
  encode = "json",
154
  timeout(60)
155
  )
156
-
157
  status <- status_code(response)
158
-
159
  if (status == 200) {
160
  result <- content(response, as = "parsed", encoding = "UTF-8")
161
  text <- result$choices[[1]]$message$content
162
  return(list(success = TRUE, text = text))
163
  }
164
-
165
  err <- tryCatch(content(response, "text", encoding = "UTF-8"),
166
  error = function(e) paste("Status:", status))
167
  return(list(success = FALSE,
@@ -175,15 +198,15 @@ query_hf_api <- function(prompt, model_id = default_model, max_length = 500, tem
175
 
176
  build_system_prompt <- function(rv) {
177
  context_parts <- c("CURRENT ANALYSIS RESULTS:")
178
-
179
  if (!is.null(rv$qtl_effects_train) && !"Message" %in% colnames(rv$qtl_effects_train)) {
180
  n_qtl <- nrow(rv$qtl_effects_train)
181
  total_pve <- sum(rv$qtl_effects_train$PVE_Percent, na.rm = TRUE)
182
-
183
  context_parts <- c(context_parts,
184
  sprintf("\nQTL Results: %d significant QTLs detected above LOD %.1f.", n_qtl, rv$lod_threshold),
185
  sprintf("Total variance explained by QTLs: %.1f%%.", total_pve))
186
-
187
  top_qtls <- head(rv$qtl_effects_train[order(-rv$qtl_effects_train$LOD), ], 3)
188
  context_parts <- c(context_parts, "\nTop QTLs:")
189
  for (i in 1:nrow(top_qtls)) {
@@ -193,7 +216,7 @@ build_system_prompt <- function(rv) {
193
  i, row$Marker, row$Chromosome, row$LOD, row$PVE_Percent, row$Additive_Effect))
194
  }
195
  }
196
-
197
  if (!is.null(rv$performance_metrics)) {
198
  pm <- rv$performance_metrics
199
  train_r2 <- pm$Value[pm$Metric == "R\u00b2 (Train)"]
@@ -203,7 +226,7 @@ build_system_prompt <- function(rv) {
203
  sprintf(" Training R\u00b2: %.3f", train_r2),
204
  sprintf(" Validation R\u00b2: %.3f", val_r2))
205
  }
206
-
207
  if (!is.null(rv$epistasis_sig) && !"Message" %in% colnames(rv$epistasis_sig) && nrow(rv$epistasis_sig) > 0) {
208
  n_epi <- nrow(rv$epistasis_sig)
209
  top_epi <- rv$epistasis_sig[order(rv$epistasis_sig$Interaction_p), ][1, ]
@@ -211,13 +234,13 @@ build_system_prompt <- function(rv) {
211
  sprintf("\nEpistasis: %d significant pairwise interactions detected.", n_epi),
212
  sprintf(" Strongest: %s x %s (p=%.4f)", top_epi$QTL1, top_epi$QTL2, top_epi$Interaction_p))
213
  }
214
-
215
  if (!is.null(rv$selection_metrics) && !"Message" %in% colnames(rv$selection_metrics)) {
216
  n_sig <- sum(rv$selection_metrics$Significant, na.rm = TRUE)
217
  context_parts <- c(context_parts,
218
  sprintf("\nDomestication: %d markers with selection signatures.", n_sig))
219
  }
220
-
221
  paste(context_parts, collapse = "\n")
222
  }
223
 
@@ -227,18 +250,18 @@ build_system_prompt <- function(rv) {
227
 
228
  enhanced_rule_response <- function(user_message, rv) {
229
  q <- tolower(trimws(user_message))
230
-
231
  has_qtl <- !is.null(rv$qtl_effects_train) && !"Message" %in% colnames(rv$qtl_effects_train)
232
  has_perf <- !is.null(rv$performance_metrics)
233
  has_epi <- !is.null(rv$epistasis_sig) && !"Message" %in% colnames(rv$epistasis_sig) && nrow(rv$epistasis_sig) > 0
234
  has_sel <- !is.null(rv$selection_metrics) && !"Message" %in% colnames(rv$selection_metrics)
235
-
236
  if (grepl("pve|variance explained|how much variance|percent variance|what is pve", q)) {
237
  if (has_qtl) {
238
  df <- rv$qtl_effects_train
239
  total_pve <- sum(df$PVE_Percent, na.rm = TRUE)
240
  top_pve <- df[which.max(df$PVE_Percent), ]
241
-
242
  response <- paste0(
243
  "\U0001f4ca **PVE (Phenotypic Variance Explained) Analysis**\n\n",
244
  "**Your Results:**\n",
@@ -250,7 +273,7 @@ enhanced_rule_response <- function(user_message, rv) {
250
  "\u2022 PVE: **", round(top_pve$PVE_Percent, 1), "%**\n",
251
  "\u2022 LOD: ", round(top_pve$LOD, 2), "\n\n"
252
  )
253
-
254
  if (top_pve$PVE_Percent > 10) {
255
  response <- paste0(response, "\U0001f4a1 This is a **major-effect QTL** (>10% PVE).\n\n")
256
  } else if (top_pve$PVE_Percent > 5) {
@@ -258,7 +281,7 @@ enhanced_rule_response <- function(user_message, rv) {
258
  } else {
259
  response <- paste0(response, "\U0001f4a1 This is a **minor-effect QTL** (<5% PVE).\n\n")
260
  }
261
-
262
  response <- paste0(response, "**All QTLs by PVE:**\n")
263
  df_sorted <- df[order(-df$PVE_Percent), ]
264
  for (i in 1:min(5, nrow(df_sorted))) {
@@ -270,19 +293,19 @@ enhanced_rule_response <- function(user_message, rv) {
270
  return("No QTL results yet. Please run the QTL analysis first to see PVE values.")
271
  }
272
  }
273
-
274
  if (grepl("model performance|r2|r squared|how good is my model|validation|negative r2", q)) {
275
  if (has_perf) {
276
  pm <- rv$performance_metrics
277
  train_r2 <- pm$Value[pm$Metric == "R\u00b2 (Train)"]
278
  val_r2 <- pm$Value[pm$Metric == "R\u00b2 (Validation)"]
279
-
280
  response <- paste0(
281
  "\U0001f4c8 **Model Performance Summary**\n\n",
282
  "\u2022 Training R\u00b2: **", round(train_r2, 3), "**\n",
283
  "\u2022 Validation R\u00b2: **", round(val_r2, 3), "**\n\n"
284
  )
285
-
286
  if (val_r2 < 0) {
287
  response <- paste0(response,
288
  "\u26a0\ufe0f **Your validation R\u00b2 is negative** (", round(val_r2, 3), ").\n\n",
@@ -306,12 +329,12 @@ enhanced_rule_response <- function(user_message, rv) {
306
  return("Run the QTL analysis first to see model performance metrics.")
307
  }
308
  }
309
-
310
  if (grepl("top qtl|best qtl|highest lod|significant qtl|list qtl|show qtl", q)) {
311
  if (has_qtl) {
312
  df <- rv$qtl_effects_train[order(-rv$qtl_effects_train$LOD), ]
313
  top5 <- head(df, 5)
314
-
315
  response <- "\U0001f3af **Top 5 QTLs by LOD Score**\n\n"
316
  for (i in 1:nrow(top5)) {
317
  row <- top5[i, ]
@@ -326,11 +349,11 @@ enhanced_rule_response <- function(user_message, rv) {
326
  return("No significant QTLs detected. Try lowering the LOD threshold.")
327
  }
328
  }
329
-
330
  if (grepl("next steps|what next|recommendations|suggest|advice|what should i do", q)) {
331
  if (has_qtl || has_perf || has_epi || has_sel) {
332
  response <- "\U0001f52c **Recommended Next Steps**\n\n"
333
-
334
  if (has_qtl) {
335
  top_qtl <- rv$qtl_effects_train[which.max(rv$qtl_effects_train$LOD), ]
336
  response <- paste0(response,
@@ -346,7 +369,7 @@ enhanced_rule_response <- function(user_message, rv) {
346
  response <- paste0(response, "**3. Domestication Analysis**\n",
347
  " \u2022 ", sum(rv$selection_metrics$Significant, na.rm = TRUE), " selection signatures\n\n")
348
  }
349
-
350
  response <- paste0(response,
351
  "**4. Functional Analysis**\n",
352
  " \u2022 Annotate QTL regions for candidate genes\n\n",
@@ -357,7 +380,7 @@ enhanced_rule_response <- function(user_message, rv) {
357
  return("Run the QTL analysis first to get recommendations.")
358
  }
359
  }
360
-
361
  available <- c()
362
  if (has_qtl) available <- c(available, paste(nrow(rv$qtl_effects_train), "QTLs"))
363
  if (has_perf) {
@@ -366,7 +389,7 @@ enhanced_rule_response <- function(user_message, rv) {
366
  }
367
  if (has_epi) available <- c(available, paste(nrow(rv$epistasis_sig), "interactions"))
368
  if (has_sel) available <- c(available, paste(sum(rv$selection_metrics$Significant), "selection signatures"))
369
-
370
  if (length(available) > 0) {
371
  return(paste0(
372
  "I can see you have: ", paste(available, collapse = ", "), ".\n\n",
@@ -376,7 +399,7 @@ enhanced_rule_response <- function(user_message, rv) {
376
  "\u2022 **Model performance**\n",
377
  "\u2022 **Next steps**"))
378
  }
379
-
380
  return(paste0(
381
  "\U0001f44b Hello! I'm your QTL analysis assistant.\n\n",
382
  "**I can help you with:**\n",
@@ -393,9 +416,9 @@ enhanced_rule_response <- function(user_message, rv) {
393
 
394
  generate_ai_response <- function(user_message, rv, model_id = default_model) {
395
  context <- build_system_prompt(rv)
396
-
397
  current_use_api <- token_exists
398
-
399
  if (current_use_api) {
400
  prompt <- paste(
401
  "CONTEXT:", context,
@@ -403,9 +426,9 @@ generate_ai_response <- function(user_message, rv, model_id = default_model) {
403
  "\n\nProvide a specific, helpful answer based ONLY on the context above. Be concise but informative.",
404
  sep = "\n"
405
  )
406
-
407
  result <- query_hf_api(prompt, model_id = model_id)
408
-
409
  if (result$success) {
410
  return(result$text)
411
  } else {
@@ -413,7 +436,7 @@ generate_ai_response <- function(user_message, rv, model_id = default_model) {
413
  return(enhanced_rule_response(user_message, rv))
414
  }
415
  }
416
-
417
  return(enhanced_rule_response(user_message, rv))
418
  }
419
 
@@ -423,7 +446,7 @@ generate_ai_response <- function(user_message, rv, model_id = default_model) {
423
 
424
  ui <- fluidPage(
425
  shinyjs::useShinyjs(),
426
-
427
  tags$head(
428
  tags$link(rel = "stylesheet", type = "text/css",
429
  href = "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css"),
@@ -607,11 +630,11 @@ ui <- fluidPage(
607
  .chat-file-bubble i { font-size: 14px; }
608
  "))
609
  ),
610
-
611
  navbarPage(
612
  title = tags$span(tags$i(class = "fas fa-dna", style = "margin-right:8px; color:#58a6ff;"), "QTL-Mapper AI"),
613
  id = "nav",
614
-
615
  # ---- Data Upload tab ----
616
  tabPanel("Data Upload", icon = icon("upload"),
617
  div(class = "main-header",
@@ -669,7 +692,7 @@ ui <- fluidPage(
669
  )
670
  )
671
  ),
672
-
673
  # ---- Domestication tab ----
674
  tabPanel("Domestication", icon = icon("leaf"),
675
  div(class = "main-header",
@@ -713,7 +736,7 @@ ui <- fluidPage(
713
  )
714
  )
715
  ),
716
-
717
  # ---- Results tab ----
718
  tabPanel("Results", icon = icon("chart-line"),
719
  div(class = "main-header",
@@ -754,7 +777,7 @@ ui <- fluidPage(
754
  ))
755
  )
756
  ),
757
-
758
  # ---- Interpretation tab ----
759
  tabPanel("Interpretation", icon = icon("lightbulb"),
760
  div(class = "main-header",
@@ -769,7 +792,7 @@ ui <- fluidPage(
769
  fluidRow(column(12, div(class = "card", div(class = "card-header", "Epistasis"), div(class = "card-body", uiOutput("epistasis_interpretation"))))),
770
  fluidRow(column(12, div(class = "card", div(class = "card-header", "Recommendations"), div(class = "card-body", uiOutput("recommendations")))))
771
  ),
772
-
773
  # ---- About tab ----
774
  tabPanel("About", icon = icon("info-circle"),
775
  div(class = "main-header",
@@ -824,13 +847,13 @@ ui <- fluidPage(
824
  )
825
  )
826
  ),
827
-
828
  # ============================================================
829
  # FLOATING CHAT PANEL (with model selector + file upload)
830
  # ============================================================
831
  tags$div(id = "chat-panel",
832
  tags$div(id = "chat-window",
833
-
834
  # Chat header
835
  tags$div(id = "chat-header",
836
  tags$div(class = "chat-header-top",
@@ -847,7 +870,7 @@ ui <- fluidPage(
847
  onclick = "document.getElementById('chat-window').classList.remove('open');",
848
  tags$i(class = "fas fa-times"))
849
  ),
850
-
851
  # Model selector row
852
  tags$div(class = "chat-model-selector",
853
  tags$label(tags$i(class = "fas fa-robot"), " Model:"),
@@ -859,7 +882,7 @@ ui <- fluidPage(
859
  actionButton("test_model_btn", "Test", class = "test-model-btn")
860
  )
861
  ),
862
-
863
  # Quick question buttons
864
  tags$div(class = "quick-questions",
865
  tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q','What is PVE?',{priority:'event'});", "PVE meaning"),
@@ -867,13 +890,13 @@ ui <- fluidPage(
867
  tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q','Why is my R2 negative?',{priority:'event'});","Negative R2"),
868
  tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q','What should I do next?',{priority:'event'});","Next steps")
869
  ),
870
-
871
  # Messages area
872
  tags$div(id = "chat_messages", uiOutput("chat_display")),
873
-
874
  # Footer
875
  tags$div(id = "chat-footer",
876
-
877
  # File upload row
878
  tags$div(class = "chat-file-row",
879
  tags$label(
@@ -891,12 +914,12 @@ ui <- fluidPage(
891
  onclick = "document.getElementById('chat_file_preview').style.display='none'; document.getElementById('chat_file_preview').innerHTML=''; Shiny.setInputValue('clear_chat_file', Math.random());",
892
  tags$i(class = "fas fa-times"))
893
  ),
894
-
895
  # Text input
896
  tags$textarea(id = "chat_input",
897
  placeholder = "Ask about your results... (Enter to send)",
898
  rows = "2"),
899
-
900
  # Action buttons
901
  tags$div(class = "chat-actions",
902
  actionButton("send_chat", "Send", icon = icon("paper-plane"), class = "btn-primary"),
@@ -904,13 +927,13 @@ ui <- fluidPage(
904
  )
905
  )
906
  ),
907
-
908
  # Toggle button
909
  tags$button(id = "chat-toggle-btn",
910
  onclick = "document.getElementById('chat-window').classList.toggle('open');",
911
  tags$i(class = "fas fa-robot"))
912
  ),
913
-
914
  # JS to show filename on file selection
915
  tags$script(HTML("
916
  $(document).on('change', '#chat_file_upload', function() {
@@ -929,7 +952,7 @@ ui <- fluidPage(
929
  # ============================================================
930
 
931
  server <- function(input, output, session) {
932
-
933
  values <- reactiveValues(
934
  genotype_data = NULL,
935
  phenotype_data = NULL,
@@ -960,27 +983,27 @@ server <- function(input, output, session) {
960
  pending_file_content = NULL,
961
  pending_file_name = NULL
962
  )
963
-
964
  # ---- Current selected model ----
965
  observe({
966
  req(input$selected_model)
967
  values$current_model <- input$selected_model
968
-
969
  # Update status display
970
  model_label <- names(model_choices)[model_choices == input$selected_model]
971
  if (is.null(model_label) || length(model_label) == 0)
972
  model_label <- gsub(".*/([^:]+):.*", "\\1", input$selected_model)
973
-
974
  shinyjs::html("model_status_text",
975
  if (token_exists) paste("AI:", gsub(".*\\[(.*)\\]", "\\1", model_label), "- ready")
976
  else "Rule-based mode (no token)")
977
  })
978
-
979
  # ---- Test model button ----
980
  observeEvent(input$test_model_btn, {
981
  req(input$selected_model)
982
  add_message("assistant", paste0("\u23f3 Testing model: **", gsub(".*/", "", input$selected_model), "**..."))
983
-
984
  result <- test_api_connection(input$selected_model)
985
  if (result$success) {
986
  add_message("assistant", paste0("\u2705 **", gsub(".*/", "", input$selected_model), "** is working! You can now chat with this model."))
@@ -991,7 +1014,7 @@ server <- function(input, output, session) {
991
  shinyjs::runjs("document.getElementById('model_status_dot').className = 'model-status-dot offline';")
992
  }
993
  })
994
-
995
  # ---- Chat helpers ----
996
  add_message <- function(role, content, model_used = NULL) {
997
  timestamp <- format(Sys.time(), "%H:%M")
@@ -1002,10 +1025,10 @@ server <- function(input, output, session) {
1002
  values$chat_messages <- tail(values$chat_messages, 100)
1003
  session$sendCustomMessage("scrollChatBottom", list())
1004
  }
1005
-
1006
  process_message <- function(user_text, file_content = NULL, file_name = NULL) {
1007
  if (nchar(trimws(user_text)) == 0 && is.null(file_content)) return()
1008
-
1009
  # Build full message including file content if present
1010
  full_message <- user_text
1011
  if (!is.null(file_content) && nchar(trimws(file_content)) > 0) {
@@ -1015,74 +1038,74 @@ server <- function(input, output, session) {
1015
  substr(file_content, 1, 3000),
1016
  if (nchar(file_content) > 3000) "\n[... truncated ...]" else "")
1017
  }
1018
-
1019
  add_message("user", full_message)
1020
  values$is_typing <- TRUE
1021
-
1022
  model_id <- isolate(values$current_model)
1023
  response <- generate_ai_response(full_message, values, model_id = model_id)
1024
-
1025
  values$is_typing <- FALSE
1026
  model_short <- gsub(".*/([^:]+):.*", "\\1", model_id)
1027
  add_message("assistant", response, model_used = if (token_exists) model_short else NULL)
1028
-
1029
  # Clear pending file
1030
  values$pending_file_content <- NULL
1031
  values$pending_file_name <- NULL
1032
  }
1033
-
1034
  # ---- Handle chat file upload ----
1035
  observeEvent(input$chat_file_upload, {
1036
  req(input$chat_file_upload)
1037
  file_path <- input$chat_file_upload$datapath
1038
  file_name <- input$chat_file_upload$name
1039
  ext <- tolower(tools::file_ext(file_name))
1040
-
1041
  tryCatch({
1042
  file_content <- if (ext %in% c("csv", "txt", "tsv")) {
1043
  paste(readLines(file_path, n = 200), collapse = "\n")
1044
  } else {
1045
  paste0("[Binary file: ", file_name, " - ", round(file.info(file_path)$size / 1024, 1), " KB]")
1046
  }
1047
-
1048
  values$pending_file_content <- file_content
1049
  values$pending_file_name <- file_name
1050
  }, error = function(e) {
1051
  showNotification(paste("Could not read file:", e$message), type = "warning")
1052
  })
1053
  })
1054
-
1055
  # ---- Clear chat file ----
1056
  observeEvent(input$clear_chat_file, {
1057
  values$pending_file_content <- NULL
1058
  values$pending_file_name <- NULL
1059
  })
1060
-
1061
  # ---- Send chat ----
1062
  observeEvent(input$send_chat, {
1063
  user_text <- trimws(input$chat_input)
1064
  file_content <- isolate(values$pending_file_content)
1065
  file_name <- isolate(values$pending_file_name)
1066
-
1067
  if (nchar(user_text) == 0 && is.null(file_content)) return()
1068
-
1069
  updateTextAreaInput(session, "chat_input", value = "")
1070
  # Clear file preview via JS
1071
  shinyjs::runjs("
1072
  document.getElementById('chat_file_preview').style.display = 'none';
1073
  document.getElementById('chat_file_preview').innerHTML = '';
1074
  ")
1075
-
1076
  process_message(user_text, file_content, file_name)
1077
  })
1078
-
1079
  observeEvent(input$quick_q, { req(input$quick_q); process_message(input$quick_q) })
1080
-
1081
  observeEvent(input$clear_chat, {
1082
  values$chat_messages <- list()
1083
  add_message("assistant", "Chat cleared. How can I help?")
1084
  })
1085
-
1086
  # ---- Initial greeting ----
1087
  observe({
1088
  if (length(values$chat_messages) == 0) {
@@ -1105,26 +1128,26 @@ server <- function(input, output, session) {
1105
  ))
1106
  }
1107
  })
1108
-
1109
  # ---- Chat display ----
1110
  output$chat_display <- renderUI({
1111
  messages <- values$chat_messages
1112
  if (length(messages) == 0) return(NULL)
1113
-
1114
  elems <- lapply(messages, function(msg) {
1115
  content_html <- HTML(gsub("\n", "<br>", htmltools::htmlEscape(msg$content)))
1116
-
1117
  meta_content <- tagList(
1118
  span(msg$time),
1119
  if (!is.null(msg$model) && msg$role == "assistant")
1120
  span(class = "model-tag", paste0("[", msg$model, "]"))
1121
  )
1122
-
1123
  div(class = paste("chat-msg", msg$role),
1124
  div(class = "chat-bubble", content_html),
1125
  div(class = "chat-meta", meta_content))
1126
  })
1127
-
1128
  if (values$is_typing) {
1129
  elems <- c(elems, list(
1130
  div(class = "chat-msg assistant",
@@ -1133,64 +1156,64 @@ server <- function(input, output, session) {
1133
  }
1134
  do.call(tagList, elems)
1135
  })
1136
-
1137
  # ============================================================
1138
  # DATA LOADING
1139
  # ============================================================
1140
-
1141
  observeEvent(input$genotype_file, {
1142
  req(input$genotype_file)
1143
  tryCatch({
1144
  all_data <- readLines(input$genotype_file$datapath)
1145
  if (length(all_data) < 4) { showNotification("Genotype file must have at least 4 rows", type = "error"); return() }
1146
-
1147
  header <- strsplit(all_data[1], ",")[[1]]
1148
  chromosome_row <- strsplit(all_data[2], ",")[[1]]
1149
  position_row <- strsplit(all_data[3], ",")[[1]]
1150
-
1151
  genotype_data <- read.csv(text = all_data[-(1:3)], header = FALSE)
1152
  colnames(genotype_data) <- header
1153
  rownames(genotype_data) <- genotype_data[, 1]
1154
  genotype_data <- genotype_data[, -1]
1155
-
1156
  for (col in colnames(genotype_data))
1157
  genotype_data[[col]] <- as.numeric(as.character(genotype_data[[col]]))
1158
-
1159
  values$all_markers <- data.frame(
1160
  Marker = colnames(genotype_data),
1161
  Chromosome = chromosome_row[-1],
1162
  Position = as.numeric(position_row[-1]),
1163
  stringsAsFactors = FALSE)
1164
-
1165
  values$genotype_data <- genotype_data
1166
  values$chromosome_info <- chromosome_row[-1]
1167
  values$position_info <- as.numeric(position_row[-1])
1168
-
1169
  showNotification("Genotype data loaded", type = "message")
1170
  add_message("assistant", paste0("\u2705 Loaded genotype data: **", ncol(genotype_data), " markers**, **", nrow(genotype_data), " samples**"))
1171
  }, error = function(e) showNotification(paste("Error:", e$message), type = "error"))
1172
  })
1173
-
1174
  observeEvent(input$phenotype_file, {
1175
  req(input$phenotype_file)
1176
  tryCatch({
1177
  phenotype_data <- read.csv(input$phenotype_file$datapath)
1178
  rownames(phenotype_data) <- phenotype_data[, 1]
1179
  phenotype_data <- phenotype_data[, -1]
1180
-
1181
  for (col in colnames(phenotype_data))
1182
  phenotype_data[[col]] <- as.numeric(as.character(phenotype_data[[col]]))
1183
-
1184
  values$phenotype_data <- phenotype_data
1185
  updateSelectInput(session, "phenotype_column",
1186
  choices = colnames(phenotype_data),
1187
  selected = colnames(phenotype_data)[1])
1188
-
1189
  showNotification("Phenotype data loaded", type = "message")
1190
  add_message("assistant", paste0("\u2705 Loaded phenotype data: **", ncol(phenotype_data), " traits**, **", nrow(phenotype_data), " samples**"))
1191
  }, error = function(e) showNotification(paste("Error:", e$message), type = "error"))
1192
  })
1193
-
1194
  observeEvent(input$pop_file, {
1195
  req(input$pop_file)
1196
  tryCatch({
@@ -1203,55 +1226,55 @@ server <- function(input, output, session) {
1203
  add_message("assistant", paste0("\u2705 Loaded population data (", nrow(pop_data), " samples)"))
1204
  }, error = function(e) showNotification(paste("Error:", e$message), type = "error"))
1205
  })
1206
-
1207
  observeEvent(input$test_genotype_file, {
1208
  req(input$test_genotype_file)
1209
  tryCatch({
1210
  all_data <- readLines(input$test_genotype_file$datapath)
1211
  header <- strsplit(all_data[1], ",")[[1]]
1212
-
1213
  genotype_data <- read.csv(text = all_data[-(1:3)], header = FALSE)
1214
  colnames(genotype_data) <- header
1215
  rownames(genotype_data) <- genotype_data[, 1]
1216
  genotype_data <- genotype_data[, -1]
1217
-
1218
  for (col in colnames(genotype_data))
1219
  genotype_data[[col]] <- as.numeric(as.character(genotype_data[[col]]))
1220
-
1221
  values$test_genotype_data <- genotype_data
1222
  values$has_test_data <- TRUE
1223
  showNotification("Test genotype data loaded", type = "message")
1224
  }, error = function(e) showNotification(paste("Error:", e$message), type = "error"))
1225
  })
1226
-
1227
  # ---- Data previews ----
1228
  output$geno_preview <- renderDT({ req(input$genotype_file); datatable(head(read.csv(input$genotype_file$datapath), 10), options = list(scrollX = TRUE, pageLength = 5)) })
1229
  output$pheno_preview <- renderDT({ req(input$phenotype_file); datatable(head(read.csv(input$phenotype_file$datapath), 10), options = list(scrollX = TRUE, pageLength = 5)) })
1230
  output$test_geno_preview <- renderDT({ req(input$test_genotype_file); datatable(head(read.csv(input$test_genotype_file$datapath), 10), options = list(scrollX = TRUE, pageLength = 5)) })
1231
  output$pop_preview <- renderDT({ req(input$pop_file); datatable(head(read.csv(input$pop_file$datapath), 10), options = list(scrollX = TRUE, pageLength = 5)) })
1232
  output$predicted_test_pheno_preview <- renderDT({ req(values$predicted_test_phenotype_data); datatable(values$predicted_test_phenotype_data, options = list(scrollX = TRUE, pageLength = 5)) })
1233
-
1234
  # ============================================================
1235
  # QTL EFFECT CALCULATION
1236
  # ============================================================
1237
-
1238
  calculate_qtl_effects <- function(genotype_matrix, phenotype_vector, marker_names) {
1239
  effects_list <- list()
1240
-
1241
  for (marker in marker_names) {
1242
  if (!marker %in% colnames(genotype_matrix)) next
1243
-
1244
  geno <- genotype_matrix[, marker]
1245
  pheno <- phenotype_vector
1246
  valid_idx <- !is.na(geno) & !is.na(pheno)
1247
  geno <- geno[valid_idx]
1248
  pheno <- pheno[valid_idx]
1249
-
1250
  if (length(unique(geno)) < 2) next
1251
-
1252
  lm_fit <- lm(pheno ~ geno)
1253
  additive_effect <- coef(lm_fit)[2]
1254
-
1255
  dominance_effect <- NA
1256
  if (length(unique(geno)) == 3) {
1257
  geno_means <- tapply(pheno, geno, mean, na.rm = TRUE)
@@ -1260,10 +1283,10 @@ server <- function(input, output, session) {
1260
  geno_means[as.character(sort(unique(geno))[3])]) / 2
1261
  dominance_effect <- het_mean - midparent
1262
  }
1263
-
1264
  r_squared <- summary(lm_fit)$r.squared
1265
  se_additive <- tryCatch(summary(lm_fit)$coefficients[2, 2], error = function(e) NA)
1266
-
1267
  effects_list[[marker]] <- data.frame(
1268
  Marker = marker,
1269
  Additive_Effect = additive_effect,
@@ -1275,40 +1298,40 @@ server <- function(input, output, session) {
1275
  N_Samples = length(pheno),
1276
  stringsAsFactors = FALSE)
1277
  }
1278
-
1279
  if (length(effects_list) == 0) return(NULL)
1280
  do.call(rbind, effects_list)
1281
  }
1282
-
1283
  # ============================================================
1284
  # MAIN QTL ANALYSIS
1285
  # ============================================================
1286
-
1287
  observeEvent(input$run_analysis, {
1288
  req(values$genotype_data, values$phenotype_data, input$phenotype_column)
1289
  showNotification("Starting QTL analysis...", type = "message")
1290
  values$lod_threshold <- input$lod_threshold
1291
-
1292
  tryCatch({
1293
  common_samples <- intersect(rownames(values$genotype_data), rownames(values$phenotype_data))
1294
  if (length(common_samples) == 0) { showNotification("No common samples", type = "error"); return() }
1295
-
1296
  X <- values$genotype_data[common_samples, , drop = FALSE]
1297
  y <- as.numeric(values$phenotype_data[common_samples, input$phenotype_column])
1298
  nzv <- nearZeroVar(X)
1299
  if (length(nzv) > 0) X <- X[, -nzv, drop = FALSE]
1300
-
1301
  set.seed(123)
1302
  train_index <- createDataPartition(y, p = 1 - input$test_size, list = FALSE)
1303
  X_train <- X[train_index, , drop = FALSE]; X_val <- X[-train_index, , drop = FALSE]
1304
  y_train <- y[train_index]; y_val <- y[-train_index]
1305
-
1306
  model <- train(x = X_train, y = y_train, method = "rf",
1307
  trControl = trainControl(method = "cv", number = 5),
1308
  importance = TRUE, tuneLength = 3)
1309
-
1310
  values$model_fit <- model
1311
-
1312
  imp <- varImp(model, scale = FALSE)$importance
1313
  importance_scores <- data.frame(
1314
  Marker = rownames(imp),
@@ -1316,14 +1339,14 @@ server <- function(input, output, session) {
1316
  Chromosome = values$chromosome_info[match(rownames(imp), colnames(X))],
1317
  Position = as.numeric(values$position_info[match(rownames(imp), colnames(X))]),
1318
  stringsAsFactors = FALSE)
1319
-
1320
  values$importance_scores <- importance_scores
1321
  lod_sig <- importance_scores[importance_scores$LOD > input$lod_threshold, , drop = FALSE]
1322
-
1323
  if (nrow(lod_sig) > 0) {
1324
  lod_sig$Low_Flank <- NA
1325
  lod_sig$High_Flank <- NA
1326
-
1327
  for (i in 1:nrow(lod_sig)) {
1328
  chr_m <- values$all_markers[values$all_markers$Chromosome == lod_sig$Chromosome[i], ]
1329
  chr_m <- chr_m[order(chr_m$Position), ]
@@ -1333,10 +1356,10 @@ server <- function(input, output, session) {
1333
  lod_sig$High_Flank[i] <- if (idx < nrow(chr_m)) chr_m$Marker[idx + 1] else lod_sig$Marker[i]
1334
  }
1335
  }
1336
-
1337
  values$lod_scores_train <- lod_sig
1338
  qtl_fx <- calculate_qtl_effects(X_train, y_train, lod_sig$Marker)
1339
-
1340
  if (!is.null(qtl_fx)) {
1341
  values$qtl_effects_train <- merge(lod_sig, qtl_fx, by = "Marker")
1342
  } else {
@@ -1346,26 +1369,26 @@ server <- function(input, output, session) {
1346
  values$lod_scores_train <- data.frame(Message = paste("No QTLs above LOD", input$lod_threshold))
1347
  values$qtl_effects_train <- data.frame(Message = paste("No QTLs above LOD", input$lod_threshold))
1348
  }
1349
-
1350
  y_train_pred <- predict(model, X_train)
1351
  y_val_pred <- predict(model, X_val)
1352
  train_r2 <- 1 - sum((y_train - y_train_pred)^2) / sum((y_train - mean(y_train))^2)
1353
  val_r2 <- 1 - sum((y_val - y_val_pred)^2) / sum((y_val - mean(y_val))^2)
1354
-
1355
  values$performance_metrics <- data.frame(
1356
  Metric = c("R\u00b2 (Train)", "R (Train)", "R\u00b2 (Validation)", "R (Validation)"),
1357
  Value = c(train_r2, cor(y_train, y_train_pred), val_r2, cor(y_val, y_val_pred)),
1358
  stringsAsFactors = FALSE)
1359
-
1360
  values$train_predictions <- data.frame(Observed = y_train, Predicted = y_train_pred)
1361
  values$test_predictions <- data.frame(Observed = y_val, Predicted = y_val_pred)
1362
-
1363
  # Epistasis
1364
  if (nrow(lod_sig) > 0) {
1365
  sig_markers <- lod_sig$Marker[lod_sig$Marker %in% colnames(X_train)]
1366
  all_markers_v <- colnames(X_train)
1367
  epistasis_list <- list()
1368
-
1369
  withProgress(message = "Calculating epistasis...", value = 0, {
1370
  total <- length(sig_markers) * length(all_markers_v)
1371
  for (m1 in sig_markers) {
@@ -1389,7 +1412,7 @@ server <- function(input, output, session) {
1389
  }
1390
  }
1391
  })
1392
-
1393
  if (length(epistasis_list) > 0) {
1394
  epistasis_all <- do.call(rbind, epistasis_list)
1395
  values$epistasis_all <- epistasis_all
@@ -1399,7 +1422,7 @@ server <- function(input, output, session) {
1399
  values$epistasis_sig <- data.frame(Message = "No epistatic interactions")
1400
  }
1401
  }
1402
-
1403
  showNotification("QTL analysis completed!", type = "message")
1404
  n_qtl <- if (!is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train)) nrow(values$qtl_effects_train) else 0
1405
  add_message("assistant", paste0(
@@ -1408,45 +1431,45 @@ server <- function(input, output, session) {
1408
  "\u2022 Validation R\u00b2: **", round(val_r2, 3), "**\n\n",
1409
  "Ask me about PVE, top QTLs, or next steps!"))
1410
  updateTabsetPanel(session, "nav", selected = "Results")
1411
-
1412
  }, error = function(e) showNotification(paste("Error:", e$message), type = "error"))
1413
  })
1414
-
1415
  # ============================================================
1416
  # DOMESTICATION ANALYSIS
1417
  # ============================================================
1418
-
1419
  calculate_selection_metrics <- function(genotype_matrix, pop_data, marker_info) {
1420
  metrics_list <- list()
1421
-
1422
  for (marker in colnames(genotype_matrix)) {
1423
  geno <- genotype_matrix[, marker]
1424
  pop <- pop_data$population[match(rownames(genotype_matrix), pop_data$id)]
1425
  valid_idx <- !is.na(geno) & !is.na(pop)
1426
  geno <- geno[valid_idx]; pop <- pop[valid_idx]
1427
-
1428
  if (length(unique(pop)) < 2) next
1429
  geno_dom <- geno[pop == "Domesticated"]
1430
  geno_wild <- geno[pop == "Wild"]
1431
  if (length(geno_dom) < 3 || length(geno_wild) < 3) next
1432
-
1433
  freq_dom <- mean(geno_dom, na.rm = TRUE) / 2
1434
  freq_wild <- mean(geno_wild, na.rm = TRUE) / 2
1435
  p_avg <- (freq_dom + freq_wild) / 2
1436
-
1437
  fst <- if (p_avg > 0 && p_avg < 1) {
1438
  f <- (freq_dom - freq_wild)^2 / (p_avg * (1 - p_avg))
1439
  f / (1 + f)
1440
  } else 0
1441
-
1442
  pi_dom <- 2 * freq_dom * (1 - freq_dom)
1443
  pi_wild <- 2 * freq_wild * (1 - freq_wild)
1444
  n_dom <- length(geno_dom)
1445
  n_wild <- length(geno_wild)
1446
-
1447
  tajima_d_dom <- (pi_dom - 1/n_dom) / sqrt(var(geno_dom) /n_dom)
1448
  tajima_d_wild <- (pi_wild - 1/n_wild) / sqrt(var(geno_wild)/n_wild)
1449
-
1450
  marker_row <- marker_info[marker_info$Marker == marker, ]
1451
  metrics_list[[marker]] <- data.frame(
1452
  Marker = marker,
@@ -1456,71 +1479,71 @@ server <- function(input, output, session) {
1456
  Tajima_D_Dom = tajima_d_dom, Tajima_D_Wild = tajima_d_wild,
1457
  stringsAsFactors = FALSE)
1458
  }
1459
-
1460
  if (length(metrics_list) == 0) return(NULL)
1461
  do.call(rbind, metrics_list)
1462
  }
1463
-
1464
  observeEvent(input$run_domestication, {
1465
  req(values$genotype_data, values$pop_data, values$all_markers)
1466
  tryCatch({
1467
  common_samples <- intersect(rownames(values$genotype_data), values$pop_data$id)
1468
  if (length(common_samples) == 0) { showNotification("No common samples", type = "error"); return() }
1469
-
1470
  X <- values$genotype_data[common_samples, , drop = FALSE]
1471
  pop_subset <- values$pop_data[values$pop_data$id %in% common_samples, ]
1472
  sel_metrics <- calculate_selection_metrics(X, pop_subset, values$all_markers)
1473
-
1474
  if (is.null(sel_metrics)) { showNotification("Could not calculate selection metrics", type = "error"); return() }
1475
-
1476
  sel_metrics$Significant <-
1477
  sel_metrics$Fst > input$fst_threshold |
1478
  sel_metrics$Tajima_D_Dom < input$tajima_threshold |
1479
  sel_metrics$Tajima_D_Wild < input$tajima_threshold
1480
-
1481
  values$selection_metrics <- sel_metrics
1482
  showNotification("Domestication analysis completed!", type = "message")
1483
  n_sig <- sum(sel_metrics$Significant, na.rm = TRUE)
1484
  add_message("assistant", paste0("\u2705 Domestication analysis complete!\n\n\u2022 Found **", n_sig, " markers** with selection signatures"))
1485
  }, error = function(e) showNotification(paste("Error:", e$message), type = "error"))
1486
  })
1487
-
1488
  # ============================================================
1489
  # PREDICT TEST PHENOTYPES
1490
  # ============================================================
1491
-
1492
  observeEvent(input$predict_test_phenotype, {
1493
  req(values$model_fit, values$test_genotype_data)
1494
  tryCatch({
1495
  common_markers <- intersect(colnames(values$test_genotype_data), colnames(values$genotype_data))
1496
  if (length(common_markers) == 0) { showNotification("No common markers", type = "error"); return() }
1497
-
1498
  X_test <- values$test_genotype_data[, common_markers, drop = FALSE]
1499
  predictions <- predict(values$model_fit, newdata = X_test)
1500
-
1501
  values$predicted_test_phenotype_data <- data.frame(
1502
  id = rownames(X_test),
1503
  Predicted_Phenotype = as.numeric(predictions),
1504
  stringsAsFactors = FALSE)
1505
-
1506
  showNotification("Predictions completed!", type = "message")
1507
  }, error = function(e) showNotification(paste("Error:", e$message), type = "error"))
1508
  })
1509
-
1510
  # ============================================================
1511
  # MANHATTAN PLOT HELPER
1512
  # ============================================================
1513
-
1514
  create_manhattan <- function(data, y_col, title, threshold, y_label = y_col) {
1515
  if (is.null(data) || nrow(data) == 0 || "Message" %in% colnames(data))
1516
  return(plot_ly() %>% layout(title = "No data available",
1517
  plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e")))
1518
-
1519
  plot_data <- data[!is.na(data[[y_col]]), ]
1520
  if (nrow(plot_data) == 0)
1521
  return(plot_ly() %>% layout(title = "No valid data",
1522
  plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e")))
1523
-
1524
  chroms <- unique(plot_data$Chromosome)
1525
  chrom_pos <- data.frame()
1526
  for (i in seq_along(chroms)) {
@@ -1531,7 +1554,7 @@ server <- function(input, output, session) {
1531
  chrom_pos <- rbind(chrom_pos, chr_data)
1532
  }
1533
  }
1534
-
1535
  p <- plot_ly() %>%
1536
  add_trace(data = chrom_pos, x = ~PosScaled, y = as.formula(paste0("~", y_col)),
1537
  type = "scatter", mode = "markers", color = ~factor(Chromosome),
@@ -1539,13 +1562,13 @@ server <- function(input, output, session) {
1539
  text = ~paste("Marker:", Marker, "<br>Chr:", Chromosome, "<br>Pos:", Position,
1540
  "<br>", y_label, ":", round(get(y_col), 3)),
1541
  hoverinfo = "text", showlegend = FALSE)
1542
-
1543
  if (!is.null(threshold) && !is.na(threshold))
1544
  p <- p %>% add_segments(
1545
  x = min(chrom_pos$PosScaled, na.rm = TRUE), xend = max(chrom_pos$PosScaled, na.rm = TRUE),
1546
  y = threshold, yend = threshold,
1547
  line = list(color = "red", dash = "dash", width = 1), name = "Threshold")
1548
-
1549
  p %>% layout(title = title,
1550
  xaxis = list(title = "Chromosome",
1551
  ticktext = chroms,
@@ -1554,26 +1577,26 @@ server <- function(input, output, session) {
1554
  yaxis = list(title = y_label),
1555
  plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))
1556
  }
1557
-
1558
  # ============================================================
1559
  # PLOTS
1560
  # ============================================================
1561
-
1562
  output$lod_plot_2d <- renderPlotly({
1563
  req(values$importance_scores)
1564
  create_manhattan(values$importance_scores, "LOD", "QTL Manhattan Plot", input$lod_threshold, "LOD Score")
1565
  })
1566
-
1567
  output$fst_plot <- renderPlotly({
1568
  req(values$selection_metrics)
1569
  create_manhattan(values$selection_metrics, "Fst", "Fst Manhattan Plot", input$fst_threshold, "Fst")
1570
  })
1571
-
1572
  output$tajima_plot <- renderPlotly({
1573
  req(values$selection_metrics)
1574
  if ("Message" %in% colnames(values$selection_metrics))
1575
  return(plot_ly() %>% layout(title = "No data available", plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e")))
1576
-
1577
  data <- values$selection_metrics
1578
  chroms <- unique(data$Chromosome)
1579
  chrom_pos <- data.frame()
@@ -1585,7 +1608,7 @@ server <- function(input, output, session) {
1585
  chrom_pos <- rbind(chrom_pos, chr_data)
1586
  }
1587
  }
1588
-
1589
  plot_ly() %>%
1590
  add_trace(data = chrom_pos, x = ~PosScaled, y = ~Tajima_D_Dom, type = "scatter", mode = "markers",
1591
  name = "Domesticated", marker = list(size = 5, color = "#58a6ff", opacity = 0.7),
@@ -1604,7 +1627,7 @@ server <- function(input, output, session) {
1604
  yaxis = list(title = "Tajima's D"),
1605
  plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))
1606
  })
1607
-
1608
  output$performance_plot <- renderPlotly({
1609
  req(values$performance_metrics)
1610
  plot_ly(data = values$performance_metrics, x = ~Metric, y = ~Value, type = "bar",
@@ -1614,7 +1637,7 @@ server <- function(input, output, session) {
1614
  yaxis = list(title = "Value", range = c(0, 1.1)),
1615
  plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))
1616
  })
1617
-
1618
  output$regression_plot_train <- renderPlotly({
1619
  req(values$train_predictions)
1620
  plot_ly(data = values$train_predictions, x = ~Observed, y = ~Predicted,
@@ -1624,7 +1647,7 @@ server <- function(input, output, session) {
1624
  layout(title = "Training Set", xaxis = list(title = "Observed"), yaxis = list(title = "Predicted"),
1625
  plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))
1626
  })
1627
-
1628
  output$regression_plot_test <- renderPlotly({
1629
  req(values$test_predictions)
1630
  plot_ly(data = values$test_predictions, x = ~Observed, y = ~Predicted,
@@ -1634,13 +1657,13 @@ server <- function(input, output, session) {
1634
  layout(title = "Validation Set", xaxis = list(title = "Observed"), yaxis = list(title = "Predicted"),
1635
  plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))
1636
  })
1637
-
1638
  output$epistasis_heatmap <- renderPlotly({
1639
  req(values$epistasis_all)
1640
  if ("Message" %in% colnames(values$epistasis_all))
1641
  return(plot_ly() %>% layout(title = values$epistasis_all$Message[1],
1642
  plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e")))
1643
-
1644
  qtls <- unique(values$epistasis_all$QTL1)
1645
  markers <- unique(values$epistasis_all$QTL2)
1646
  p_mat <- matrix(NA, nrow = length(qtls), ncol = length(markers),
@@ -1648,7 +1671,7 @@ server <- function(input, output, session) {
1648
  for (i in 1:nrow(values$epistasis_all))
1649
  p_mat[values$epistasis_all$QTL1[i], values$epistasis_all$QTL2[i]] <-
1650
  -log10(values$epistasis_all$Interaction_p[i])
1651
-
1652
  plot_ly(x = colnames(p_mat), y = rownames(p_mat), z = p_mat,
1653
  type = "heatmap", colorscale = "Viridis",
1654
  hovertemplate = "QTL: %{y}<br>Marker: %{x}<br>-log10(p): %{z:.2f}") %>%
@@ -1656,16 +1679,16 @@ server <- function(input, output, session) {
1656
  xaxis = list(title = "Marker", tickangle = 45), yaxis = list(title = "QTL"),
1657
  plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))
1658
  })
1659
-
1660
  # ============================================================
1661
  # TABLES
1662
  # ============================================================
1663
-
1664
  output$qtl_effects_table_train <- renderDT({
1665
  req(values$qtl_effects_train)
1666
  if ("Message" %in% colnames(values$qtl_effects_train))
1667
  return(datatable(data.frame(Status = values$qtl_effects_train$Message[1]), options = list(dom = "t")))
1668
-
1669
  display_cols <- intersect(
1670
  c("Marker", "Chromosome", "Position", "LOD", "Additive_Effect", "PVE_Percent", "Low_Flank", "High_Flank"),
1671
  colnames(values$qtl_effects_train))
@@ -1673,7 +1696,7 @@ server <- function(input, output, session) {
1673
  datatable(df, options = list(pageLength = 10, scrollX = TRUE), rownames = FALSE) %>%
1674
  formatRound(intersect(c("LOD", "Additive_Effect", "PVE_Percent"), colnames(df)), 3)
1675
  })
1676
-
1677
  output$epistasis_table <- renderDT({
1678
  req(values$epistasis_sig)
1679
  if ("Message" %in% colnames(values$epistasis_sig))
@@ -1682,47 +1705,47 @@ server <- function(input, output, session) {
1682
  options = list(pageLength = 10, scrollX = TRUE), rownames = FALSE) %>%
1683
  formatSignif(columns = c("Interaction_p", "Effect_Size"), digits = 4)
1684
  })
1685
-
1686
  output$selection_table <- renderDT({
1687
  req(values$selection_metrics)
1688
  if ("Message" %in% colnames(values$selection_metrics))
1689
  return(datatable(data.frame(Status = values$selection_metrics$Message[1]), options = list(dom = "t")))
1690
-
1691
  df <- values$selection_metrics
1692
  if (!is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train))
1693
  df$QTL_Overlap <- df$Marker %in% values$qtl_effects_train$Marker
1694
-
1695
  display_cols <- intersect(
1696
  c("Marker", "Chromosome", "Fst", "Pi_Dom", "Pi_Wild", "Tajima_D_Dom", "Significant", "QTL_Overlap"),
1697
  colnames(df))
1698
  datatable(df[order(-df$Fst), display_cols], options = list(pageLength = 10, scrollX = TRUE), rownames = FALSE) %>%
1699
  formatRound(c("Fst", "Pi_Dom", "Pi_Wild", "Tajima_D_Dom"), 3)
1700
  })
1701
-
1702
  # ============================================================
1703
  # CHROMOSOME VISUALIZATION
1704
  # ============================================================
1705
-
1706
  output$chromosome_viz <- renderUI({
1707
  req(values$lod_scores_train, values$all_markers)
1708
  if ("Message" %in% colnames(values$lod_scores_train))
1709
  return(div(class = "alert alert-info", values$lod_scores_train$Message[1]))
1710
-
1711
  chromosomes <- unique(values$lod_scores_train$Chromosome)
1712
  tagList(lapply(chromosomes, function(chr) {
1713
  chr_markers <- values$all_markers[values$all_markers$Chromosome == chr, ]
1714
  chr_markers <- chr_markers[order(chr_markers$Position), ]
1715
  chr_qtls <- values$lod_scores_train[values$lod_scores_train$Chromosome == chr, ]
1716
-
1717
  sel_markers <- NULL
1718
  if (!is.null(values$selection_metrics) && !"Message" %in% colnames(values$selection_metrics))
1719
  sel_markers <- values$selection_metrics[
1720
  values$selection_metrics$Chromosome == chr & values$selection_metrics$Significant, ]
1721
-
1722
  min_pos <- min(chr_markers$Position, na.rm = TRUE)
1723
  max_pos <- max(chr_markers$Position, na.rm = TRUE)
1724
  range_pos <- max_pos - min_pos
1725
-
1726
  div(class = "chromosome-container",
1727
  div(class = "chromosome-title", paste("Chromosome", chr)),
1728
  div(class = "chromosome",
@@ -1730,7 +1753,7 @@ server <- function(input, output, session) {
1730
  marker <- chr_markers[i, ]
1731
  left <- if (range_pos > 0) ((marker$Position - min_pos) / range_pos) * 100
1732
  else (i / nrow(chr_markers)) * 100
1733
-
1734
  marker_class <- "chromosome-marker"
1735
  if (marker$Marker %in% chr_qtls$Marker) {
1736
  marker_class <- paste(marker_class, "significant")
@@ -1748,26 +1771,26 @@ server <- function(input, output, session) {
1748
  )
1749
  }))
1750
  })
1751
-
1752
  # ---- Simulation animations ----
1753
  observeEvent(input$simulate_btn, session$sendCustomMessage("simulateQTLDiscovery", list()))
1754
  observeEvent(input$reset_btn, session$sendCustomMessage("resetAnimation", list()))
1755
-
1756
  # ============================================================
1757
  # INTERPRETATION OUTPUTS
1758
  # ============================================================
1759
-
1760
  output$analysis_summary <- renderUI({
1761
  has_qtl <- !is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train)
1762
  has_perf <- !is.null(values$performance_metrics)
1763
  has_epi <- !is.null(values$epistasis_sig) && !"Message" %in% colnames(values$epistasis_sig) && nrow(values$epistasis_sig) > 0
1764
  has_sel <- !is.null(values$selection_metrics) && !"Message" %in% colnames(values$selection_metrics)
1765
-
1766
  n_qtl <- if (has_qtl) nrow(values$qtl_effects_train) else 0
1767
  n_epi <- if (has_epi) nrow(values$epistasis_sig) else 0
1768
  n_sel <- if (has_sel) sum(values$selection_metrics$Significant, na.rm = TRUE) else 0
1769
  val_r2 <- if (has_perf) round(values$performance_metrics$Value[values$performance_metrics$Metric == "R\u00b2 (Validation)"], 3) else "N/A"
1770
-
1771
  div(class = "interpretation-section",
1772
  tags$h5("Analysis Summary"),
1773
  tags$p(paste("Found", n_qtl, "QTLs above LOD", input$lod_threshold,
@@ -1775,38 +1798,38 @@ server <- function(input, output, session) {
1775
  if (has_epi) paste0("with ", n_epi, " epistatic interactions"),
1776
  if (has_sel) paste0("and ", n_sel, " selection signatures."))))
1777
  })
1778
-
1779
  output$qtl_interpretation <- renderUI({
1780
  if (is.null(values$qtl_effects_train) || "Message" %in% colnames(values$qtl_effects_train))
1781
  return(div(class = "interpretation-section", tags$h5("QTL Significance"), tags$p("No significant QTLs detected.")))
1782
-
1783
  top_qtl <- values$qtl_effects_train[which.max(values$qtl_effects_train$LOD), ]
1784
  div(class = "interpretation-section",
1785
  tags$h5("QTL Significance"),
1786
  tags$p(paste("Top QTL:", top_qtl$Marker, "(Chr", top_qtl$Chromosome, ") with LOD =", round(top_qtl$LOD, 2))))
1787
  })
1788
-
1789
  output$effect_interpretation <- renderUI({
1790
  if (is.null(values$qtl_effects_train) || "Message" %in% colnames(values$qtl_effects_train))
1791
  return(div(class = "interpretation-section", tags$h5("Effect Sizes"), tags$p("No QTL effects to interpret.")))
1792
-
1793
  top_pve <- values$qtl_effects_train[which.max(values$qtl_effects_train$PVE_Percent), ]
1794
  div(class = "interpretation-section",
1795
  tags$h5("Effect Sizes"),
1796
  tags$p(paste("Largest effect:", top_pve$Marker, "explains", round(top_pve$PVE_Percent, 1), "% of variance")))
1797
  })
1798
-
1799
  output$epistasis_interpretation <- renderUI({
1800
  if (is.null(values$epistasis_sig) || "Message" %in% colnames(values$epistasis_sig) || nrow(values$epistasis_sig) == 0)
1801
  return(div(class = "interpretation-section", tags$h5("Epistasis"), tags$p("No significant epistatic interactions detected.")))
1802
-
1803
  top_epi <- values$epistasis_sig[which.min(values$epistasis_sig$Interaction_p), ]
1804
  div(class = "interpretation-section",
1805
  tags$h5("Epistasis"),
1806
  tags$p(paste("Detected", nrow(values$epistasis_sig), "interactions. Strongest:",
1807
  top_epi$QTL1, "x", top_epi$QTL2, "(p =", format.pval(top_epi$Interaction_p), ")")))
1808
  })
1809
-
1810
  output$recommendations <- renderUI({
1811
  has_qtl <- !is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train)
1812
  recs <- if (has_qtl) {
@@ -1822,11 +1845,11 @@ server <- function(input, output, session) {
1822
  tags$h5("Recommendations"),
1823
  tags$ul(lapply(recs, tags$li), style = "color:#8b949e;"))
1824
  })
1825
-
1826
  # ============================================================
1827
  # DOWNLOAD HANDLERS
1828
  # ============================================================
1829
-
1830
  output$download_train_results <- downloadHandler(
1831
  filename = function() paste0("qtl_results_", Sys.Date(), ".xlsx"),
1832
  content = function(file) {
@@ -1838,7 +1861,7 @@ server <- function(input, output, session) {
1838
  write_xlsx(sheets, file)
1839
  }
1840
  )
1841
-
1842
  output$download_selection <- downloadHandler(
1843
  filename = function() paste0("selection_", Sys.Date(), ".xlsx"),
1844
  content = function(file) {
 
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:auto",
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(
 
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,
 
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,
 
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 Hello! I'm your QTL analysis assistant.\n\n",
405
  "**I can help you with:**\n",
 
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,
 
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 {
 
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",
 
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(
 
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,
 
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")
 
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) {
 
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) {
 
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) {