International Rice Research Institute commited on
Commit
27ec731
·
verified ·
1 Parent(s): 4334e4b

Update app.R

Browse files
Files changed (1) hide show
  1. app.R +432 -332
app.R CHANGED
@@ -20,117 +20,97 @@ for (pkg in required_packages) {
20
  }
21
 
22
  # Initialize reticulate for Python-based transformers
23
- use_python("/usr/local/bin/python3", required = FALSE)
 
 
 
 
24
 
25
  # ============================================================
26
  # TRANSFORMER-BASED LLM SYSTEM
27
  # ============================================================
28
 
29
- # Check if we should use Hugging Face API or local model
30
- use_hf_api <- Sys.getenv("HF_API_TOKEN") != "" # Set this in Spaces secrets
 
31
 
32
- # Configuration
33
- hf_model <- "microsoft/phi-2" # Smaller model suitable for Q&A
34
- # Alternative models: "google/flan-t5-large", "microsoft/phi-2", "mistralai/Mistral-7B-Instruct-v0.1"
 
 
 
35
 
36
- # Hugging Face API configuration
37
- HF_API_TOKEN <- Sys.getenv("HF_API_TOKEN") # Set in Spaces secrets
38
  HF_API_URL <- paste0("https://api-inference.huggingface.co/models/", hf_model)
39
 
40
- # Function to query Hugging Face API
41
  query_hf_api <- function(prompt, max_length = 500, temperature = 0.7) {
42
  if (HF_API_TOKEN == "") {
43
  return(list(success = FALSE, error = "HF_API_TOKEN not set"))
44
  }
45
 
 
 
 
 
 
 
 
46
  tryCatch({
47
  response <- POST(
48
  url = HF_API_URL,
49
- add_headers(Authorization = paste("Bearer", HF_API_TOKEN)),
 
 
 
50
  body = toJSON(list(
51
- inputs = prompt,
52
  parameters = list(
53
  max_new_tokens = max_length,
54
  temperature = temperature,
55
  do_sample = TRUE,
56
- top_p = 0.95
 
 
 
57
  )
58
  ), auto_unbox = TRUE),
59
- content_type_json(),
60
  timeout(60)
61
  )
62
 
 
63
  if (status_code(response) == 200) {
64
- result <- content(response, as = "parsed")
65
- if (is.list(result) && !is.null(result$generated_text)) {
66
- return(list(success = TRUE, text = result$generated_text))
67
- } else if (is.list(result) && length(result) > 0 && !is.null(result[[1]]$generated_text)) {
68
- return(list(success = TRUE, text = result[[1]]$generated_text))
 
 
 
 
 
 
 
69
  } else {
70
- return(list(success = FALSE, error = "Unexpected API response format"))
71
  }
 
 
 
72
  } else {
73
- return(list(success = FALSE, error = paste("API returned status:", status_code(response))))
74
- }
75
- }, error = function(e) {
76
- return(list(success = FALSE, error = e$message))
77
- })
78
- }
79
-
80
- # Function to query local transformer model (if resources allow)
81
- # This will work if the model can fit in Spaces memory
82
- setup_local_model <- function() {
83
- tryCatch({
84
- # Import transformers via reticulate
85
- transformers <- import("transformers")
86
- torch <- import("torch")
87
-
88
- # Load a small model suitable for CPU
89
- model_name <- "microsoft/phi-2"
90
-
91
- tokenizer <- transformers$AutoTokenizer$from_pretrained(model_name)
92
- model <- transformers$AutoModelForCausalLM$from_pretrained(
93
- model_name,
94
- torch_dtype = "auto",
95
- device_map = "auto",
96
- low_cpu_mem_usage = TRUE
97
- )
98
-
99
- return(list(
100
- success = TRUE,
101
- tokenizer = tokenizer,
102
- model = model
103
- ))
104
- }, error = function(e) {
105
- return(list(success = FALSE, error = e$message))
106
- })
107
- }
108
-
109
- query_local_model <- function(prompt, model_objects, max_length = 500) {
110
- tryCatch({
111
- tokenizer <- model_objects$tokenizer
112
- model <- model_objects$model
113
-
114
- inputs <- tokenizer$encode(prompt, return_tensors = "pt")
115
-
116
- with(torch$no_grad(), {
117
- outputs <- model$generate(
118
- inputs,
119
- max_length = max_length,
120
- temperature = 0.7,
121
- do_sample = TRUE,
122
- pad_token_id = tokenizer$eos_token_id
123
- )
124
- })
125
-
126
- response <- tokenizer$decode(outputs[1], skip_special_tokens = TRUE)
127
-
128
- # Remove the prompt from response
129
- if (startsWith(response, prompt)) {
130
- response <- substring(response, nchar(prompt) + 1)
131
  }
132
-
133
- return(list(success = TRUE, text = trimws(response)))
134
  }, error = function(e) {
135
  return(list(success = FALSE, error = e$message))
136
  })
@@ -143,19 +123,34 @@ query_local_model <- function(prompt, model_objects, max_length = 500) {
143
  build_system_prompt <- function(rv) {
144
  # Build context from current analysis results
145
  context_parts <- c(
146
- "You are a specialized bioinformatics assistant for QTL (Quantitative Trait Loci) mapping and domestication analysis. You help researchers understand their genomic analysis results.",
147
- "\nCURRENT ANALYSIS RESULTS:"
148
  )
149
 
150
  # Add QTL results
151
  if (!is.null(rv$qtl_effects_train) && !"Message" %in% colnames(rv$qtl_effects_train)) {
152
  n_qtl <- nrow(rv$qtl_effects_train)
153
  top_qtl <- rv$qtl_effects_train[order(-rv$qtl_effects_train$LOD), ][1,]
 
 
 
 
 
 
 
154
  context_parts <- c(context_parts, sprintf(
155
- "\n- QTL Results: %d significant QTLs detected. Top QTL: %s (Chr %s, Pos %s) with LOD=%.2f, PVE=%.1f%%, Additive Effect=%.3f",
156
- n_qtl, top_qtl$Marker, top_qtl$Chromosome, top_qtl$Position,
157
  top_qtl$LOD, top_qtl$PVE_Percent, top_qtl$Additive_Effect
158
  ))
 
 
 
 
 
 
 
 
 
159
  }
160
 
161
  # Add performance metrics
@@ -163,36 +158,260 @@ build_system_prompt <- function(rv) {
163
  pm <- rv$performance_metrics
164
  train_r2 <- round(pm$Value[pm$Metric == "R² (Train)"], 3)
165
  val_r2 <- round(pm$Value[pm$Metric == "R² (Validation)"], 3)
 
 
 
166
  context_parts <- c(context_parts, sprintf(
167
- "\n- Model Performance: Training R²=%.3f, Validation R²=%.3f",
168
- train_r2, val_r2
169
  ))
 
 
 
 
 
 
 
 
 
 
 
 
 
170
  }
171
 
172
  # Add epistasis results
173
- if (!is.null(rv$epistasis_sig) && !"Message" %in% colnames(rv$epistasis_sig)) {
174
  n_epi <- nrow(rv$epistasis_sig)
 
 
175
  context_parts <- c(context_parts, sprintf(
176
- "\n- Epistasis: %d significant pairwise interactions detected",
177
  n_epi
178
  ))
 
 
 
 
 
179
  }
180
 
181
  # Add domestication results
182
  if (!is.null(rv$selection_metrics) && !"Message" %in% colnames(rv$selection_metrics)) {
183
- n_sel <- sum(rv$selection_metrics$Significant, na.rm = TRUE)
 
 
 
 
 
 
 
184
  context_parts <- c(context_parts, sprintf(
185
- "\n- Domestication: %d markers with significant selection signatures",
186
- n_sel
 
187
  ))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
188
  }
189
 
190
- context_parts <- c(context_parts,
191
- "\n\nAnswer questions clearly and concisely. When referring to specific results, use the data provided above. If asked about methodology, explain it in accessible terms. Always relate your answers back to what the analysis results mean biologically.",
192
- "\nKeep responses focused on QTL analysis, genetics, and domestication. If you're not sure about something, admit it and suggest what the user could check."
193
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
194
 
195
- paste(context_parts, collapse = "")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196
  }
197
 
198
  # ============================================================
@@ -378,7 +597,7 @@ ui <- fluidPage(
378
  bottom: 20px;
379
  right: 20px;
380
  z-index: 9999;
381
- width: 400px;
382
  display: flex;
383
  flex-direction: column;
384
  }
@@ -447,7 +666,7 @@ ui <- fluidPage(
447
  }
448
 
449
  .chat-msg {
450
- max-width: 85%;
451
  animation: fadeIn 0.3s ease;
452
  }
453
  @keyframes fadeIn {
@@ -461,7 +680,7 @@ ui <- fluidPage(
461
  padding: 12px 16px;
462
  border-radius: 16px;
463
  font-size: 13px;
464
- line-height: 1.5;
465
  word-wrap: break-word;
466
  white-space: pre-wrap;
467
  }
@@ -476,6 +695,8 @@ ui <- fluidPage(
476
  border: 1px solid var(--border);
477
  border-bottom-left-radius: 4px;
478
  }
 
 
479
  .chat-meta { font-size: 10px; color: var(--text-muted); margin-top: 4px; font-family: var(--font-mono); padding: 0 4px; }
480
 
481
  .typing-indicator {
@@ -779,10 +1000,13 @@ ui <- fluidPage(
779
  tags$li("Domestication: Fst, nucleotide diversity (Pi), Tajima's D"),
780
  tags$li("AI Assistant powered by ", tags$code("microsoft/phi-2"), " transformer model via Hugging Face Inference API")
781
  ),
782
- h4(style = "color:#58a6ff; font-family: 'IBM Plex Mono'; margin: 12px 0;", "AI Assistant Features"),
783
  p(style = "color: #8b949e; line-height: 1.7;",
784
- "The AI assistant uses a transformer-based language model to provide intelligent, context-aware responses about your QTL analysis results. ",
785
- "It understands questions about LOD scores, QTL effects, epistasis, domestication signatures, and can provide tailored recommendations based on your specific results."
 
 
 
786
  ),
787
  h4(style = "color:#58a6ff; font-family: 'IBM Plex Mono'; margin: 12px 0;", "Interpretation Thresholds"),
788
  tags$ul(style = "color: #8b949e; line-height: 2;",
@@ -809,7 +1033,9 @@ ui <- fluidPage(
809
  tags$h4("QTL Analysis AI Assistant",
810
  tags$span(class = "model-badge", "phi-2")
811
  ),
812
- tags$p(id = "model_status", "Transformer model ready")
 
 
813
  )
814
  ),
815
  tags$button(id = "chat-close-btn", onclick = "document.getElementById('chat-window').classList.remove('open');",
@@ -819,9 +1045,10 @@ ui <- fluidPage(
819
 
820
  # Quick questions
821
  tags$div(class = "quick-questions",
 
822
  tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q', 'What are my top QTLs?', {priority: 'event'});", "Top QTLs"),
823
  tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q', 'How is my model performing?', {priority: 'event'});", "Model performance"),
824
- tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q', 'Explain epistasis results', {priority: 'event'});", "Epistasis"),
825
  tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q', 'What does Fst mean?', {priority: 'event'});", "Fst meaning"),
826
  tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q', 'Any selection signatures?', {priority: 'event'});", "Selection"),
827
  tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q', 'Next steps?', {priority: 'event'});", "Next steps")
@@ -887,194 +1114,21 @@ server <- function(input, output, session) {
887
  chat_messages = list(),
888
  is_typing = FALSE,
889
  # Model objects
890
- hf_model_loaded = FALSE,
891
- local_model = NULL,
892
- using_api = use_hf_api
893
  )
894
 
895
  # Initialize model status
896
  observe({
897
- if (values$using_api) {
898
- if (HF_API_TOKEN != "") {
899
- values$hf_model_loaded <- TRUE
900
- shinyjs::html("model_status", "Hugging Face API connected")
901
- } else {
902
- values$using_api <- FALSE
903
- shinyjs::html("model_status", "Using rule-based fallback (set HF_API_TOKEN for AI)")
904
- }
905
  } else {
906
- # Try to load local model (will likely fail in Spaces due to memory)
907
- # This is optional and commented out for Spaces deployment
908
- # model_objects <- setup_local_model()
909
- # if (model_objects$success) {
910
- # values$local_model <- model_objects
911
- # values$hf_model_loaded <- TRUE
912
- # shinyjs::html("model_status", "Local transformer model loaded")
913
- # } else {
914
- # shinyjs::html("model_status", "Using rule-based responses")
915
- # }
916
- shinyjs::html("model_status", "Using enhanced rule-based AI")
917
  }
918
  })
919
 
920
- # ============================================================
921
- # ENHANCED RULE-BASED RESPONSES (Fallback when transformer not available)
922
- # ============================================================
923
-
924
- enhanced_rule_response <- function(user_message, rv) {
925
- q <- tolower(trimws(user_message))
926
-
927
- # Check for results availability
928
- has_qtl <- !is.null(rv$qtl_effects_train) && !"Message" %in% colnames(rv$qtl_effects_train)
929
- has_perf <- !is.null(rv$performance_metrics)
930
- has_epi <- !is.null(rv$epistasis_sig) && !"Message" %in% colnames(rv$epistasis_sig)
931
- has_sel <- !is.null(rv$selection_metrics) && !"Message" %in% colnames(rv$selection_metrics)
932
-
933
- # Comprehensive response patterns
934
- responses <- list()
935
-
936
- # QTL-related queries
937
- if (grepl("qtl|quantitative trait|marker", q)) {
938
- if (has_qtl) {
939
- df <- rv$qtl_effects_train
940
- top <- df[which.max(df$LOD), ]
941
- responses <- c(responses, paste(
942
- "Based on your QTL analysis:",
943
- paste0("- You have ", nrow(df), " significant QTLs above LOD ", input$lod_threshold),
944
- paste0("- Top QTL: ", top$Marker, " on chromosome ", top$Chromosome),
945
- paste0(" • LOD score: ", round(top$LOD, 2)),
946
- paste0(" • PVE: ", round(top$PVE_Percent, 1), "%"),
947
- paste0(" • Additive effect: ", round(top$Additive_Effect, 3)),
948
- "",
949
- "This QTL explains the most variance in your trait. The flanking markers ",
950
- top$Low_Flank, " and ", top$High_Flank, " define the confidence interval.",
951
- sep = "\n"
952
- ))
953
- } else {
954
- responses <- c(responses, "No QTL results yet. Please upload your data and run the analysis first.")
955
- }
956
- }
957
-
958
- # Performance queries
959
- if (grepl("performance|model|r2|accuracy|predict", q)) {
960
- if (has_perf) {
961
- pm <- rv$performance_metrics
962
- train_r2 <- pm$Value[pm$Metric == "R² (Train)"]
963
- val_r2 <- pm$Value[pm$Metric == "R² (Validation)"]
964
- train_r <- pm$Value[pm$Metric == "R (Train)"]
965
- val_r <- pm$Value[pm$Metric == "R (Validation)"]
966
-
967
- quality <- if (val_r2 > 0.7) "excellent"
968
- else if (val_r2 > 0.5) "good"
969
- else if (val_r2 > 0.3) "moderate"
970
- else "modest"
971
-
972
- responses <- c(responses, paste(
973
- "Model Performance Summary:",
974
- paste0("- Training R²: ", round(train_r2, 3), " (", round(train_r2*100, 1), "% variance explained)"),
975
- paste0("- Validation R²: ", round(val_r2, 3), " (", round(val_r2*100, 1), "% variance explained)"),
976
- paste0("- Training R: ", round(train_r, 3)),
977
- paste0("- Validation R: ", round(val_r, 3)),
978
- "",
979
- paste0("Overall predictive power is ", quality, "."),
980
- if (train_r2 - val_r2 > 0.2) "⚠️ There may be some overfitting - consider simplifying the model or increasing sample size." else "✅ The model generalizes well to validation data.",
981
- sep = "\n"
982
- ))
983
- } else {
984
- responses <- c(responses, "Run the QTL analysis first to see model performance metrics.")
985
- }
986
- }
987
-
988
- # Domestication queries
989
- if (grepl("domestication|selection|fst|tajima|wild|domesticated", q)) {
990
- if (has_sel) {
991
- sel <- rv$selection_metrics
992
- n_sig <- sum(sel$Significant, na.rm = TRUE)
993
- top_fst <- sel[which.max(sel$Fst), ]
994
-
995
- responses <- c(responses, paste(
996
- "Domestication Analysis Results:",
997
- paste0("- ", n_sig, " markers show significant selection signatures"),
998
- paste0("- Strongest differentiation: ", top_fst$Marker, " (Fst = ", round(top_fst$Fst, 3), ")"),
999
- paste0(" • Pi (Domesticated): ", round(top_fst$Pi_Dom, 4)),
1000
- paste0(" • Pi (Wild): ", round(top_fst$Pi_Wild, 4)),
1001
- paste0(" • Tajima's D (Dom): ", round(top_fst$Tajima_D_Dom, 3)),
1002
- "",
1003
- if (has_qtl) {
1004
- overlap <- sel$Marker[sel$Marker %in% rv$qtl_effects_train$Marker & sel$Significant]
1005
- if (length(overlap) > 0) {
1006
- paste("🔬 QTLs under selection:", paste(overlap, collapse = ", "),
1007
- "- these are strong domestication candidates!")
1008
- } else {
1009
- "No overlap between QTLs and selection signatures detected."
1010
- }
1011
- } else {
1012
- "Run QTL analysis to check if these selection signatures overlap with trait-associated loci."
1013
- },
1014
- sep = "\n"
1015
- ))
1016
- } else {
1017
- responses <- c(responses, "No domestication results yet. Upload population data and run the analysis.")
1018
- }
1019
- }
1020
-
1021
- # Epistasis queries
1022
- if (grepl("epistasis|interaction|epistatic", q)) {
1023
- if (has_epi) {
1024
- epi <- rv$epistasis_sig
1025
- top_epi <- epi[which.min(epi$Interaction_p), ]
1026
-
1027
- responses <- c(responses, paste(
1028
- "Epistasis Analysis:",
1029
- paste0("- Found ", nrow(epi), " significant pairwise interactions (p < 0.05)"),
1030
- paste0("- Strongest interaction: ", top_epi$QTL1, " × ", top_epi$QTL2),
1031
- paste0(" • p-value: ", format.pval(top_epi$Interaction_p)),
1032
- paste0(" • Effect size: ", round(top_epi$Effect_Size, 3)),
1033
- "",
1034
- "This suggests the effect of one QTL depends on the genotype at the other locus.",
1035
- "Consider these interactions in breeding programs or functional studies.",
1036
- sep = "\n"
1037
- ))
1038
- } else {
1039
- responses <- c(responses, "No significant epistatic interactions detected in your analysis.")
1040
- }
1041
- }
1042
-
1043
- # Return appropriate response or default
1044
- if (length(responses) > 0) {
1045
- return(paste(responses[[1]], collapse = "\n"))
1046
- } else {
1047
- # Default response with available information
1048
- available <- c()
1049
- if (has_qtl) available <- c(available, paste(nrow(rv$qtl_effects_train), "QTLs"))
1050
- if (has_perf) available <- c(available, "performance metrics")
1051
- if (has_epi) available <- c(available, paste(nrow(rv$epistasis_sig), "epistatic interactions"))
1052
- if (has_sel) available <- c(available, paste(sum(rv$selection_metrics$Significant), "selection signatures"))
1053
-
1054
- if (length(available) > 0) {
1055
- return(paste0(
1056
- "I can see you have: ", paste(available, collapse = ", "), ".\n\n",
1057
- "What would you like to know? Try asking about:\n",
1058
- "- Top QTLs and their effects\n",
1059
- "- Model performance and reliability\n",
1060
- "- Domestication signatures and selection\n",
1061
- "- Epistatic interactions\n",
1062
- "- Next steps for your analysis"
1063
- ))
1064
- } else {
1065
- return(paste0(
1066
- "Hello! I'm your QTL analysis assistant. I can help you with:\n\n",
1067
- "• Uploading and analyzing your data\n",
1068
- "• Understanding LOD scores and QTL effects\n",
1069
- "• Interpreting model performance\n",
1070
- "• Detecting selection signatures (Fst, Tajima's D)\n",
1071
- "• Identifying epistatic interactions\n\n",
1072
- "To get started, upload your genotype and phenotype files and click 'Run QTL Analysis'."
1073
- ))
1074
- }
1075
- }
1076
- }
1077
-
1078
  # ============================================================
1079
  # AI RESPONSE GENERATION
1080
  # ============================================================
@@ -1085,17 +1139,29 @@ server <- function(input, output, session) {
1085
 
1086
  # Construct prompt
1087
  prompt <- paste(
 
1088
  context,
1089
- "\n\nUser Question: ", user_message,
1090
- "\n\nProvide a helpful, concise response based on the analysis results above. Focus on biological interpretation and practical recommendations.",
1091
- sep = ""
1092
  )
1093
 
1094
  # Try transformer if available
1095
- if (values$using_api && values$hf_model_loaded) {
 
 
 
1096
  result <- query_hf_api(prompt)
 
 
 
1097
  if (result$success) {
1098
  return(result$text)
 
 
 
 
 
1099
  }
1100
  }
1101
 
@@ -1108,12 +1174,22 @@ server <- function(input, output, session) {
1108
  # ============================================================
1109
 
1110
  # Add message to chat history
1111
- add_message <- function(role, content) {
1112
  timestamp <- format(Sys.time(), "%H:%M")
 
 
 
 
 
 
 
 
 
1113
  values$chat_messages <- c(values$chat_messages, list(list(
1114
  role = role,
1115
  content = content,
1116
- time = timestamp
 
1117
  )))
1118
 
1119
  # Keep only last 50 messages
@@ -1121,7 +1197,6 @@ server <- function(input, output, session) {
1121
  values$chat_messages <- tail(values$chat_messages, 50)
1122
  }
1123
 
1124
- # Scroll to bottom
1125
  session$sendCustomMessage("scrollChatBottom", list())
1126
  }
1127
 
@@ -1132,15 +1207,9 @@ server <- function(input, output, session) {
1132
  # Add user message
1133
  add_message("user", user_text)
1134
 
1135
- # Show typing indicator
1136
- values$is_typing <- TRUE
1137
-
1138
  # Generate response
1139
  response <- generate_ai_response(user_text)
1140
 
1141
- # Hide typing indicator
1142
- values$is_typing <- FALSE
1143
-
1144
  # Add assistant response
1145
  add_message("assistant", response)
1146
  }
@@ -1173,19 +1242,35 @@ server <- function(input, output, session) {
1173
  # Initialize chat
1174
  observe({
1175
  if (length(values$chat_messages) == 0) {
1176
- add_message("assistant", paste(
1177
- "👋 Hello! I'm your AI-powered QTL analysis assistant.",
1178
- "",
1179
- "I can help you interpret your results and answer questions about:",
1180
- "• QTL detection and LOD scores",
1181
- "• Model performance (R², predictions)",
1182
- "• Epistatic interactions",
1183
- "• Domestication signatures (Fst, Tajima's D)",
1184
- "• Next steps and recommendations",
1185
- "",
1186
- "Upload your data, run the analysis, and ask me anything!",
1187
- sep = "\n"
1188
- ))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1189
  }
1190
  })
1191
 
@@ -1442,16 +1527,18 @@ server <- function(input, output, session) {
1442
  r_squared <- summary(lm_fit)$r.squared
1443
 
1444
  # Standard error and CI
1445
- se_additive <- summary(lm_fit)$coefficients[2, 2]
 
 
1446
 
1447
  effects_list[[marker]] <- data.frame(
1448
  Marker = marker,
1449
  Additive_Effect = additive_effect,
1450
  Dominance_Effect = dominance_effect,
1451
  PVE_Percent = r_squared * 100,
1452
- SE_Additive = se_additive,
1453
- CI_Lower = additive_effect - 1.96 * se_additive,
1454
- CI_Upper = additive_effect + 1.96 * se_additive,
1455
  N_Samples = length(pheno),
1456
  stringsAsFactors = FALSE
1457
  )
@@ -1468,6 +1555,9 @@ server <- function(input, output, session) {
1468
  showNotification("Starting QTL analysis...", type = "message")
1469
 
1470
  tryCatch({
 
 
 
1471
  # Get common samples
1472
  common_samples <- intersect(rownames(values$genotype_data),
1473
  rownames(values$phenotype_data))
@@ -1639,14 +1729,16 @@ server <- function(input, output, session) {
1639
  showNotification("QTL analysis completed successfully!", type = "message")
1640
 
1641
  # Add to chat
1642
- n_qtl <- if ("Message" %in% colnames(values$qtl_effects_train)) 0 else nrow(values$qtl_effects_train)
 
 
1643
  add_message("assistant", paste(
1644
  "✅ QTL analysis complete!",
1645
  paste0("• Found ", n_qtl, " significant QTLs"),
1646
- paste0("• Model validation R²: ", round(val_r2, 3)),
1647
  paste0("• Check the Results tab for details"),
1648
  "",
1649
- "What would you like to know about your results?",
1650
  sep = "\n"
1651
  ))
1652
 
@@ -1883,7 +1975,7 @@ server <- function(input, output, session) {
1883
  )
1884
 
1885
  # Add threshold line
1886
- if (!is.null(threshold)) {
1887
  p <- p %>% add_segments(
1888
  x = min(chrom_pos$PosScaled, na.rm = TRUE),
1889
  xend = max(chrom_pos$PosScaled, na.rm = TRUE),
@@ -2298,7 +2390,7 @@ server <- function(input, output, session) {
2298
  output$analysis_summary <- renderUI({
2299
  has_qtl <- !is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train)
2300
  has_perf <- !is.null(values$performance_metrics)
2301
- has_epi <- !is.null(values$epistasis_sig) && !"Message" %in% colnames(values$epistasis_sig)
2302
  has_sel <- !is.null(values$selection_metrics) && !"Message" %in% colnames(values$selection_metrics)
2303
 
2304
  n_qtl <- if (has_qtl) nrow(values$qtl_effects_train) else 0
@@ -2371,7 +2463,7 @@ server <- function(input, output, session) {
2371
  })
2372
 
2373
  output$epistasis_interpretation <- renderUI({
2374
- if (is.null(values$epistasis_sig) || "Message" %in% colnames(values$epistasis_sig)) {
2375
  return(div(class = "interpretation-section",
2376
  tags$h5("Epistasis"),
2377
  tags$p("No significant epistatic interactions detected.")
@@ -2394,17 +2486,18 @@ server <- function(input, output, session) {
2394
 
2395
  output$recommendations <- renderUI({
2396
  has_qtl <- !is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train)
2397
- has_epi <- !is.null(values$epistasis_sig) && !"Message" %in% colnames(values$epistasis_sig)
2398
  has_sel <- !is.null(values$selection_metrics) && !"Message" %in% colnames(values$selection_metrics)
 
2399
 
2400
  recs <- character()
2401
 
2402
  if (has_qtl) {
2403
  top_qtl <- values$qtl_effects_train[which.max(values$qtl_effects_train$LOD), ]
2404
- recs <- c(recs, paste("• Prioritize", top_qtl$Marker, "for validation and fine-mapping"))
2405
 
2406
- if (has_epi && nrow(values$epistasis_sig) > 0) {
2407
- recs <- c(recs, paste("• Investigate epistatic interactions in breeding programs"))
2408
  }
2409
 
2410
  if (has_sel) {
@@ -2413,29 +2506,36 @@ server <- function(input, output, session) {
2413
  values$selection_metrics$Significant
2414
  ]
2415
  if (length(overlap) > 0) {
2416
- recs <- c(recs, paste("• QTLs under selection:", paste(overlap, collapse = ", ")))
 
 
 
 
 
 
 
2417
  }
2418
  }
2419
 
2420
  # Add general recommendations
2421
  recs <- c(recs,
2422
- "• Validate QTLs in independent populations",
2423
- "• Use flanking markers for marker-assisted selection",
2424
- "• Consider multi-locus models for prediction"
2425
  )
2426
  } else {
2427
  recs <- c(
2428
- "• Upload genotype and phenotype data",
2429
- "• Run QTL analysis with appropriate LOD threshold",
2430
- "• Consider increasing sample size for more power",
2431
- "• Check data quality and format"
2432
  )
2433
  }
2434
 
2435
  div(class = "interpretation-section",
2436
  tags$h5("Recommendations"),
2437
  tags$ul(
2438
- lapply(recs, function(r) tags$li(r)),
2439
  style = "color: #8b949e; line-height: 1.8;"
2440
  )
2441
  )
 
20
  }
21
 
22
  # Initialize reticulate for Python-based transformers
23
+ tryCatch({
24
+ use_python("/usr/local/bin/python3", required = FALSE)
25
+ }, error = function(e) {
26
+ message("Python not available, using API mode only")
27
+ })
28
 
29
  # ============================================================
30
  # TRANSFORMER-BASED LLM SYSTEM
31
  # ============================================================
32
 
33
+ # Configuration - Load token from environment variable (set in Spaces secrets)
34
+ HF_API_TOKEN <- Sys.getenv("HF_API_TOKEN")
35
+ use_hf_api <- HF_API_TOKEN != ""
36
 
37
+ # Model selection - using a reliable model for Q&A
38
+ hf_model <- "microsoft/phi-2" # Good balance of size and capability
39
+ # Alternative models if phi-2 doesn't work well:
40
+ # hf_model <- "google/flan-t5-large"
41
+ # hf_model <- "mistralai/Mistral-7B-Instruct-v0.2"
42
+ # hf_model <- "HuggingFaceH4/zephyr-7b-beta"
43
 
 
 
44
  HF_API_URL <- paste0("https://api-inference.huggingface.co/models/", hf_model)
45
 
46
+ # Function to query Hugging Face API with improved error handling
47
  query_hf_api <- function(prompt, max_length = 500, temperature = 0.7) {
48
  if (HF_API_TOKEN == "") {
49
  return(list(success = FALSE, error = "HF_API_TOKEN not set"))
50
  }
51
 
52
+ # Format prompt for better responses
53
+ formatted_prompt <- paste0(
54
+ "You are an expert bioinformatics assistant specializing in QTL (Quantitative Trait Loci) mapping and domestication analysis.\n\n",
55
+ "CONTEXT:\n", prompt, "\n\n",
56
+ "Provide a detailed, helpful response based on the analysis results. Focus on biological interpretation and practical recommendations. "
57
+ )
58
+
59
  tryCatch({
60
  response <- POST(
61
  url = HF_API_URL,
62
+ add_headers(
63
+ Authorization = paste("Bearer", HF_API_TOKEN),
64
+ "Content-Type" = "application/json"
65
+ ),
66
  body = toJSON(list(
67
+ inputs = formatted_prompt,
68
  parameters = list(
69
  max_new_tokens = max_length,
70
  temperature = temperature,
71
  do_sample = TRUE,
72
+ top_p = 0.95,
73
+ top_k = 50,
74
+ repetition_penalty = 1.1,
75
+ return_full_text = FALSE
76
  )
77
  ), auto_unbox = TRUE),
78
+ encode = "json",
79
  timeout(60)
80
  )
81
 
82
+ # Check response status
83
  if (status_code(response) == 200) {
84
+ result <- content(response, as = "parsed", encoding = "UTF-8")
85
+
86
+ # Handle different response formats
87
+ if (is.list(result)) {
88
+ if (!is.null(result$generated_text)) {
89
+ return(list(success = TRUE, text = result$generated_text))
90
+ } else if (length(result) > 0 && !is.null(result[[1]]$generated_text)) {
91
+ return(list(success = TRUE, text = result[[1]]$generated_text))
92
+ } else {
93
+ # Try to extract text from response
94
+ return(list(success = TRUE, text = as.character(result)))
95
+ }
96
  } else {
97
+ return(list(success = TRUE, text = as.character(result)))
98
  }
99
+ } else if (status_code(response) == 503) {
100
+ # Model is loading
101
+ return(list(success = FALSE, error = "Model is loading, please try again in a few seconds", loading = TRUE))
102
  } else {
103
+ error_content <- tryCatch({
104
+ content(response, "text", encoding = "UTF-8")
105
+ }, error = function(e) {
106
+ paste("Status:", status_code(response))
107
+ })
108
+
109
+ return(list(
110
+ success = FALSE,
111
+ error = paste("API returned status:", status_code(response), "-", error_content)
112
+ ))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
113
  }
 
 
114
  }, error = function(e) {
115
  return(list(success = FALSE, error = e$message))
116
  })
 
123
  build_system_prompt <- function(rv) {
124
  # Build context from current analysis results
125
  context_parts <- c(
126
+ "CURRENT ANALYSIS RESULTS:"
 
127
  )
128
 
129
  # Add QTL results
130
  if (!is.null(rv$qtl_effects_train) && !"Message" %in% colnames(rv$qtl_effects_train)) {
131
  n_qtl <- nrow(rv$qtl_effects_train)
132
  top_qtl <- rv$qtl_effects_train[order(-rv$qtl_effects_train$LOD), ][1,]
133
+ total_pve <- sum(rv$qtl_effects_train$PVE_Percent, na.rm = TRUE)
134
+
135
+ context_parts <- c(context_parts, sprintf(
136
+ "\nQTL Results: %d significant QTLs detected (LOD > %.1f). Total PVE: %.1f%%.",
137
+ n_qtl, rv$lod_threshold, total_pve
138
+ ))
139
+
140
  context_parts <- c(context_parts, sprintf(
141
+ "Top QTL: %s on Chr %s at position %s with LOD=%.2f, PVE=%.1f%%, Additive Effect=%.3f.",
142
+ top_qtl$Marker, top_qtl$Chromosome, top_qtl$Position,
143
  top_qtl$LOD, top_qtl$PVE_Percent, top_qtl$Additive_Effect
144
  ))
145
+
146
+ # Add flanking markers if available
147
+ if (!is.null(top_qtl$Low_Flank) && !is.null(top_qtl$High_Flank) &&
148
+ !is.na(top_qtl$Low_Flank) && !is.na(top_qtl$High_Flank)) {
149
+ context_parts <- c(context_parts, sprintf(
150
+ "Confidence interval: from %s to %s.",
151
+ top_qtl$Low_Flank, top_qtl$High_Flank
152
+ ))
153
+ }
154
  }
155
 
156
  # Add performance metrics
 
158
  pm <- rv$performance_metrics
159
  train_r2 <- round(pm$Value[pm$Metric == "R² (Train)"], 3)
160
  val_r2 <- round(pm$Value[pm$Metric == "R² (Validation)"], 3)
161
+ train_r <- round(pm$Value[pm$Metric == "R (Train)"], 3)
162
+ val_r <- round(pm$Value[pm$Metric == "R (Validation)"], 3)
163
+
164
  context_parts <- c(context_parts, sprintf(
165
+ "\nModel Performance: Training R²=%.3f, Validation R²=%.3f, Training R=%.3f, Validation R=%.3f.",
166
+ train_r2, val_r2, train_r, val_r
167
  ))
168
+
169
+ # Add interpretation
170
+ if (val_r2 < 0) {
171
+ context_parts <- c(context_parts, "Note: Negative validation R² indicates poor model generalization.")
172
+ } else if (val_r2 < 0.2) {
173
+ context_parts <- c(context_parts, "Note: Low validation R² suggests weak predictive power.")
174
+ } else if (val_r2 > 0.5) {
175
+ context_parts <- c(context_parts, "Note: Good validation R² indicates strong predictive power.")
176
+ }
177
+
178
+ if (train_r2 - val_r2 > 0.2) {
179
+ context_parts <- c(context_parts, "Warning: Large gap between training and validation R² suggests overfitting.")
180
+ }
181
  }
182
 
183
  # Add epistasis results
184
+ if (!is.null(rv$epistasis_sig) && !"Message" %in% colnames(rv$epistasis_sig) && nrow(rv$epistasis_sig) > 0) {
185
  n_epi <- nrow(rv$epistasis_sig)
186
+ top_epi <- rv$epistasis_sig[order(rv$epistasis_sig$Interaction_p), ][1, ]
187
+
188
  context_parts <- c(context_parts, sprintf(
189
+ "\nEpistasis: %d significant pairwise interactions detected (p<0.05).",
190
  n_epi
191
  ))
192
+
193
+ context_parts <- c(context_parts, sprintf(
194
+ "Strongest interaction: %s × %s (p=%.4f, effect=%.3f).",
195
+ top_epi$QTL1, top_epi$QTL2, top_epi$Interaction_p, top_epi$Effect_Size
196
+ ))
197
  }
198
 
199
  # Add domestication results
200
  if (!is.null(rv$selection_metrics) && !"Message" %in% colnames(rv$selection_metrics)) {
201
+ n_sig <- sum(rv$selection_metrics$Significant, na.rm = TRUE)
202
+ top_fst <- rv$selection_metrics[which.max(rv$selection_metrics$Fst), ]
203
+
204
+ context_parts <- c(context_parts, sprintf(
205
+ "\nDomestication: %d markers with significant selection signatures.",
206
+ n_sig
207
+ ))
208
+
209
  context_parts <- c(context_parts, sprintf(
210
+ "Highest Fst: %s on Chr %s (Fst=%.3f, Pi_Dom=%.4f, Pi_Wild=%.4f, Tajima_D_Dom=%.3f).",
211
+ top_fst$Marker, top_fst$Chromosome, top_fst$Fst,
212
+ top_fst$Pi_Dom, top_fst$Pi_Wild, top_fst$Tajima_D_Dom
213
  ))
214
+
215
+ # Check QTL overlap
216
+ if (!is.null(rv$qtl_effects_train) && !"Message" %in% colnames(rv$qtl_effects_train)) {
217
+ overlap <- rv$selection_metrics$Marker[
218
+ rv$selection_metrics$Marker %in% rv$qtl_effects_train$Marker &
219
+ rv$selection_metrics$Significant
220
+ ]
221
+ if (length(overlap) > 0) {
222
+ context_parts <- c(context_parts, sprintf(
223
+ "QTLs under selection: %s.",
224
+ paste(overlap, collapse = ", ")
225
+ ))
226
+ }
227
+ }
228
  }
229
 
230
+ # Add data summary
231
+ if (!is.null(rv$genotype_data)) {
232
+ context_parts <- c(context_parts, sprintf(
233
+ "\nData Summary: %d samples, %d markers.",
234
+ nrow(rv$genotype_data), ncol(rv$genotype_data)
235
+ ))
236
+ }
237
+
238
+ paste(context_parts, collapse = " ")
239
+ }
240
+
241
+ # ============================================================
242
+ # ENHANCED RULE-BASED RESPONSES (Fallback)
243
+ # ============================================================
244
+
245
+ enhanced_rule_response <- function(user_message, rv) {
246
+ q <- tolower(trimws(user_message))
247
+
248
+ # Check for results availability
249
+ has_qtl <- !is.null(rv$qtl_effects_train) && !"Message" %in% colnames(rv$qtl_effects_train)
250
+ has_perf <- !is.null(rv$performance_metrics)
251
+ has_epi <- !is.null(rv$epistasis_sig) && !"Message" %in% colnames(rv$epistasis_sig) && nrow(rv$epistasis_sig) > 0
252
+ has_sel <- !is.null(rv$selection_metrics) && !"Message" %in% colnames(rv$selection_metrics)
253
+
254
+ # PVE-specific questions
255
+ if (grepl("pve|variance explained|how much variance|percent variance", q)) {
256
+ if (has_qtl) {
257
+ df <- rv$qtl_effects_train
258
+ total_pve <- sum(df$PVE_Percent, na.rm = TRUE)
259
+ top_pve <- df[which.max(df$PVE_Percent), ]
260
+
261
+ response <- paste0(
262
+ "📊 **PVE (Phenotypic Variance Explained) Analysis**\n\n",
263
+ "Your QTLs explain a total of ", round(total_pve, 1), "% of the phenotypic variance.\n\n",
264
+ "**Top QTL by PVE:**\n",
265
+ "• Marker: ", top_pve$Marker, "\n",
266
+ "• Chromosome: ", top_pve$Chromosome, "\n",
267
+ "• PVE: ", round(top_pve$PVE_Percent, 1), "%\n",
268
+ "• LOD: ", round(top_pve$LOD, 2), "\n\n"
269
+ )
270
+
271
+ if (top_pve$PVE_Percent > 10) {
272
+ response <- paste0(response, "This is a **major-effect QTL** (>10% PVE) - excellent candidate for marker-assisted selection.\n\n")
273
+ } else if (top_pve$PVE_Percent > 5) {
274
+ response <- paste0(response, "This is a **moderate-effect QTL** (5-10% PVE) - useful for polygenic breeding approaches.\n\n")
275
+ } else {
276
+ response <- paste0(response, "This is a **minor-effect QTL** (<5% PVE) - typical for complex polygenic traits.\n\n")
277
+ }
278
+
279
+ # Add context about total variance
280
+ if (has_perf) {
281
+ val_r2 <- rv$performance_metrics$Value[rv$performance_metrics$Metric == "R² (Validation)"]
282
+ response <- paste0(response,
283
+ "The Random Forest model validation R² is ", round(val_r2, 3),
284
+ ", which represents the total predictive power of all markers combined.\n\n"
285
+ )
286
+ }
287
+
288
+ # Add recommendations
289
+ response <- paste0(response,
290
+ "**Recommendations:**\n",
291
+ "• Focus on QTLs with PVE >5% for validation\n",
292
+ "• Consider that QTLs may share overlapping variance\n",
293
+ "• Use flanking markers for fine-mapping\n"
294
+ )
295
+
296
+ return(response)
297
+ } else {
298
+ return("No QTL results yet. Please run the QTL analysis first to see PVE values.")
299
+ }
300
+ }
301
+
302
+ # Model performance questions
303
+ if (grepl("model performance|r2|r squared|how good is my model|validation", q)) {
304
+ if (has_perf) {
305
+ pm <- rv$performance_metrics
306
+ train_r2 <- pm$Value[pm$Metric == "R² (Train)"]
307
+ val_r2 <- pm$Value[pm$Metric == "R² (Validation)"]
308
+
309
+ response <- paste0(
310
+ "📈 **Model Performance Summary**\n\n",
311
+ "• Training R²: ", round(train_r2, 3), "\n",
312
+ "• Validation R²: ", round(val_r2, 3), "\n\n"
313
+ )
314
+
315
+ if (val_r2 < 0) {
316
+ response <- paste0(response,
317
+ "⚠️ **Negative validation R²** indicates the model performs worse than simply predicting the mean.\n\n",
318
+ "**Possible reasons:**\n",
319
+ "• Small sample size relative to number of markers\n",
320
+ "• Overfitting - the model learned noise instead of signal\n",
321
+ "• Population structure in your data\n\n",
322
+ "**Suggestions:**\n",
323
+ "• Increase sample size if possible\n",
324
+ "• Reduce marker number (use feature selection)\n",
325
+ "• Try simpler models or increase cross-validation folds\n"
326
+ )
327
+ } else if (val_r2 < 0.2) {
328
+ response <- paste0(response,
329
+ "📉 **Low validation R²** (<0.2) suggests modest predictive power.\n\n",
330
+ "This is common for complex traits. Focus on individual QTL interpretation rather than overall prediction.\n"
331
+ )
332
+ } else if (val_r2 < 0.5) {
333
+ response <- paste0(response,
334
+ "📊 **Moderate validation R²** (0.2-0.5) - your model has decent predictive ability.\n\n",
335
+ "The identified QTLs explain a meaningful portion of trait variation.\n"
336
+ )
337
+ } else {
338
+ response <- paste0(response,
339
+ "🎯 **Excellent validation R²** (>0.5) - your model has strong predictive power!\n\n",
340
+ "The identified QTLs capture most of the genetic architecture.\n"
341
+ )
342
+ }
343
+
344
+ return(response)
345
+ } else {
346
+ return("Run the QTL analysis first to see model performance metrics.")
347
+ }
348
+ }
349
+
350
+ # Top QTLs question
351
+ if (grepl("top qtl|best qtl|highest lod|significant qtl", q)) {
352
+ if (has_qtl) {
353
+ df <- rv$qtl_effects_train[order(-rv$qtl_effects_train$LOD), ]
354
+ top5 <- head(df, 5)
355
+
356
+ response <- "🎯 **Top 5 QTLs by LOD Score**\n\n"
357
+
358
+ for (i in 1:nrow(top5)) {
359
+ row <- top5[i, ]
360
+ response <- paste0(response,
361
+ i, ". **", row$Marker, "** (Chr ", row$Chromosome, ")\n",
362
+ " • LOD: ", round(row$LOD, 2), "\n",
363
+ " • PVE: ", round(row$PVE_Percent, 1), "%\n",
364
+ " • Additive effect: ", round(row$Additive_Effect, 3), "\n"
365
+ )
366
+ if (!is.null(row$Low_Flank) && !is.na(row$Low_Flank) && row$Low_Flank != "NA") {
367
+ response <- paste0(response, " • Interval: ", row$Low_Flank, " - ", row$High_Flank, "\n")
368
+ }
369
+ response <- paste0(response, "\n")
370
+ }
371
+
372
+ return(response)
373
+ } else {
374
+ return("No significant QTLs detected. Try lowering the LOD threshold or check your data.")
375
+ }
376
+ }
377
 
378
+ # Default response with available information
379
+ available <- c()
380
+ if (has_qtl) available <- c(available, paste(nrow(rv$qtl_effects_train), "QTLs"))
381
+ if (has_perf) {
382
+ val_r2 <- rv$performance_metrics$Value[rv$performance_metrics$Metric == "R² (Validation)"]
383
+ available <- c(available, paste0("R²=", round(val_r2, 3)))
384
+ }
385
+ if (has_epi) available <- c(available, paste(nrow(rv$epistasis_sig), "interactions"))
386
+ if (has_sel) available <- c(available, paste(sum(rv$selection_metrics$Significant), "selection signatures"))
387
+
388
+ if (length(available) > 0) {
389
+ return(paste0(
390
+ "I can see you have: ", paste(available, collapse = ", "), ".\n\n",
391
+ "What would you like to know? Try asking about:\n",
392
+ "• **PVE** - How much variance each QTL explains\n",
393
+ "• **Top QTLs** - List of most significant markers\n",
394
+ "• **Model performance** - R² and predictions\n",
395
+ "• **Epistasis** - Interactions between QTLs\n",
396
+ "• **Selection signatures** - Domestication analysis\n",
397
+ "• **Next steps** - Recommendations for your results"
398
+ ))
399
+ }
400
+
401
+ return(paste0(
402
+ "👋 Hello! I'm your QTL analysis assistant.\n\n",
403
+ "**I can help you with:**\n",
404
+ "• Understanding LOD scores and QTL significance\n",
405
+ "• Interpreting PVE (variance explained)\n",
406
+ "• Evaluating model performance (R²)\n",
407
+ "• Detecting epistatic interactions\n",
408
+ "• Analyzing selection signatures (Fst, Tajima's D)\n\n",
409
+ "**To get started:**\n",
410
+ "1. Upload your genotype and phenotype files\n",
411
+ "2. Click 'Run QTL Analysis'\n",
412
+ "3. Ask me specific questions about your results!\n\n",
413
+ "Try: 'What is PVE?' or 'Show me my top QTLs'"
414
+ ))
415
  }
416
 
417
  # ============================================================
 
597
  bottom: 20px;
598
  right: 20px;
599
  z-index: 9999;
600
+ width: 420px;
601
  display: flex;
602
  flex-direction: column;
603
  }
 
666
  }
667
 
668
  .chat-msg {
669
+ max-width: 90%;
670
  animation: fadeIn 0.3s ease;
671
  }
672
  @keyframes fadeIn {
 
680
  padding: 12px 16px;
681
  border-radius: 16px;
682
  font-size: 13px;
683
+ line-height: 1.6;
684
  word-wrap: break-word;
685
  white-space: pre-wrap;
686
  }
 
695
  border: 1px solid var(--border);
696
  border-bottom-left-radius: 4px;
697
  }
698
+ .chat-bubble strong { color: var(--accent); }
699
+ .chat-bubble em { color: var(--text-secondary); }
700
  .chat-meta { font-size: 10px; color: var(--text-muted); margin-top: 4px; font-family: var(--font-mono); padding: 0 4px; }
701
 
702
  .typing-indicator {
 
1000
  tags$li("Domestication: Fst, nucleotide diversity (Pi), Tajima's D"),
1001
  tags$li("AI Assistant powered by ", tags$code("microsoft/phi-2"), " transformer model via Hugging Face Inference API")
1002
  ),
1003
+ h4(style = "color:#58a6ff; font-family: 'IBM Plex Mono'; margin: 12px 0;", "AI Assistant Status"),
1004
  p(style = "color: #8b949e; line-height: 1.7;",
1005
+ if (use_hf_api) {
1006
+ "✅ AI Assistant is connected to Hugging Face API and ready to answer questions intelligently."
1007
+ } else {
1008
+ "⚠️ AI Assistant is in rule-based mode. Set HF_API_TOKEN in Space secrets to enable transformer-based responses."
1009
+ }
1010
  ),
1011
  h4(style = "color:#58a6ff; font-family: 'IBM Plex Mono'; margin: 12px 0;", "Interpretation Thresholds"),
1012
  tags$ul(style = "color: #8b949e; line-height: 2;",
 
1033
  tags$h4("QTL Analysis AI Assistant",
1034
  tags$span(class = "model-badge", "phi-2")
1035
  ),
1036
+ tags$p(id = "model_status",
1037
+ if (use_hf_api) "Hugging Face API connected" else "Rule-based mode"
1038
+ )
1039
  )
1040
  ),
1041
  tags$button(id = "chat-close-btn", onclick = "document.getElementById('chat-window').classList.remove('open');",
 
1045
 
1046
  # Quick questions
1047
  tags$div(class = "quick-questions",
1048
+ tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q', 'What is PVE?', {priority: 'event'});", "PVE meaning"),
1049
  tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q', 'What are my top QTLs?', {priority: 'event'});", "Top QTLs"),
1050
  tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q', 'How is my model performing?', {priority: 'event'});", "Model performance"),
1051
+ tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q', 'Explain epistasis', {priority: 'event'});", "Epistasis"),
1052
  tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q', 'What does Fst mean?', {priority: 'event'});", "Fst meaning"),
1053
  tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q', 'Any selection signatures?', {priority: 'event'});", "Selection"),
1054
  tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q', 'Next steps?', {priority: 'event'});", "Next steps")
 
1114
  chat_messages = list(),
1115
  is_typing = FALSE,
1116
  # Model objects
1117
+ hf_model_loaded = use_hf_api,
1118
+ lod_threshold = 2 # Default threshold
 
1119
  )
1120
 
1121
  # Initialize model status
1122
  observe({
1123
+ if (use_hf_api) {
1124
+ values$hf_model_loaded <- TRUE
1125
+ shinyjs::html("model_status", "Hugging Face API connected ✓")
 
 
 
 
 
1126
  } else {
1127
+ values$hf_model_loaded <- FALSE
1128
+ shinyjs::html("model_status", "Rule-based mode (set HF_API_TOKEN for AI)")
 
 
 
 
 
 
 
 
 
1129
  }
1130
  })
1131
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1132
  # ============================================================
1133
  # AI RESPONSE GENERATION
1134
  # ============================================================
 
1139
 
1140
  # Construct prompt
1141
  prompt <- paste(
1142
+ "CONTEXT:",
1143
  context,
1144
+ "\n\nUSER QUESTION:", user_message,
1145
+ "\n\nProvide a detailed, helpful response based on the analysis results above. Be specific about marker names, LOD scores, and PVE values when relevant.",
1146
+ sep = "\n"
1147
  )
1148
 
1149
  # Try transformer if available
1150
+ if (use_hf_api && values$hf_model_loaded) {
1151
+ # Show thinking indicator
1152
+ values$is_typing <- TRUE
1153
+
1154
  result <- query_hf_api(prompt)
1155
+
1156
+ values$is_typing <- FALSE
1157
+
1158
  if (result$success) {
1159
  return(result$text)
1160
+ } else {
1161
+ # Log error
1162
+ print(paste("API Error:", result$error))
1163
+ # Fallback to rule-based
1164
+ return(enhanced_rule_response(user_message, values))
1165
  }
1166
  }
1167
 
 
1174
  # ============================================================
1175
 
1176
  # Add message to chat history
1177
+ add_message <- function(role, content, temporary = FALSE) {
1178
  timestamp <- format(Sys.time(), "%H:%M")
1179
+
1180
+ # If temporary, replace last message if it's also temporary
1181
+ if (temporary && length(values$chat_messages) > 0) {
1182
+ last_msg <- values$chat_messages[[length(values$chat_messages)]]
1183
+ if (!is.null(last_msg$temporary) && last_msg$temporary) {
1184
+ values$chat_messages <- values$chat_messages[-length(values$chat_messages)]
1185
+ }
1186
+ }
1187
+
1188
  values$chat_messages <- c(values$chat_messages, list(list(
1189
  role = role,
1190
  content = content,
1191
+ time = timestamp,
1192
+ temporary = temporary
1193
  )))
1194
 
1195
  # Keep only last 50 messages
 
1197
  values$chat_messages <- tail(values$chat_messages, 50)
1198
  }
1199
 
 
1200
  session$sendCustomMessage("scrollChatBottom", list())
1201
  }
1202
 
 
1207
  # Add user message
1208
  add_message("user", user_text)
1209
 
 
 
 
1210
  # Generate response
1211
  response <- generate_ai_response(user_text)
1212
 
 
 
 
1213
  # Add assistant response
1214
  add_message("assistant", response)
1215
  }
 
1242
  # Initialize chat
1243
  observe({
1244
  if (length(values$chat_messages) == 0) {
1245
+ welcome_msg <- if (use_hf_api) {
1246
+ paste(
1247
+ "👋 Hello! I'm your AI-powered QTL analysis assistant powered by the phi-2 transformer model.\n\n",
1248
+ "I can help you interpret your results and answer questions about:\n",
1249
+ "• **PVE** - How much variance each QTL explains\n",
1250
+ "• **QTL detection** - LOD scores and significance\n",
1251
+ "• **Model performance** - R² and predictions\n",
1252
+ "• **Epistatic interactions** - QTL × QTL effects\n",
1253
+ "• **Domestication signatures** - Fst and Tajima's D\n",
1254
+ "• **Next steps** - Recommendations for your results\n\n",
1255
+ "Upload your data, run the analysis, and ask me anything!"
1256
+ )
1257
+ } else {
1258
+ paste(
1259
+ "👋 Hello! I'm your QTL analysis assistant.\n\n",
1260
+ "I can help you with:\n",
1261
+ "• Understanding LOD scores and QTL significance\n",
1262
+ "• Interpreting PVE (variance explained)\n",
1263
+ "• Evaluating model performance (R²)\n",
1264
+ "• Detecting epistatic interactions\n",
1265
+ "• Analyzing selection signatures (Fst, Tajima's D)\n\n",
1266
+ "**To get started:**\n",
1267
+ "1. Upload your genotype and phenotype files\n",
1268
+ "2. Click 'Run QTL Analysis'\n",
1269
+ "3. Ask me specific questions about your results!\n\n",
1270
+ "Try: 'What is PVE?' or 'Show me my top QTLs'"
1271
+ )
1272
+ }
1273
+ add_message("assistant", welcome_msg)
1274
  }
1275
  })
1276
 
 
1527
  r_squared <- summary(lm_fit)$r.squared
1528
 
1529
  # Standard error and CI
1530
+ se_additive <- tryCatch({
1531
+ summary(lm_fit)$coefficients[2, 2]
1532
+ }, error = function(e) NA)
1533
 
1534
  effects_list[[marker]] <- data.frame(
1535
  Marker = marker,
1536
  Additive_Effect = additive_effect,
1537
  Dominance_Effect = dominance_effect,
1538
  PVE_Percent = r_squared * 100,
1539
+ SE_Additive = ifelse(is.na(se_additive), NA, se_additive),
1540
+ CI_Lower = ifelse(is.na(se_additive), NA, additive_effect - 1.96 * se_additive),
1541
+ CI_Upper = ifelse(is.na(se_additive), NA, additive_effect + 1.96 * se_additive),
1542
  N_Samples = length(pheno),
1543
  stringsAsFactors = FALSE
1544
  )
 
1555
  showNotification("Starting QTL analysis...", type = "message")
1556
 
1557
  tryCatch({
1558
+ # Update threshold
1559
+ values$lod_threshold <- input$lod_threshold
1560
+
1561
  # Get common samples
1562
  common_samples <- intersect(rownames(values$genotype_data),
1563
  rownames(values$phenotype_data))
 
1729
  showNotification("QTL analysis completed successfully!", type = "message")
1730
 
1731
  # Add to chat
1732
+ n_qtl <- if (!is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train)) nrow(values$qtl_effects_train) else 0
1733
+ val_r2 <- if (!is.null(values$performance_metrics)) round(values$performance_metrics$Value[values$performance_metrics$Metric == "R² (Validation)"], 3) else "N/A"
1734
+
1735
  add_message("assistant", paste(
1736
  "✅ QTL analysis complete!",
1737
  paste0("• Found ", n_qtl, " significant QTLs"),
1738
+ paste0("• Model validation R²: ", val_r2),
1739
  paste0("• Check the Results tab for details"),
1740
  "",
1741
+ "What would you like to know about your results? Try asking about PVE or top QTLs!",
1742
  sep = "\n"
1743
  ))
1744
 
 
1975
  )
1976
 
1977
  # Add threshold line
1978
+ if (!is.null(threshold) && !is.na(threshold)) {
1979
  p <- p %>% add_segments(
1980
  x = min(chrom_pos$PosScaled, na.rm = TRUE),
1981
  xend = max(chrom_pos$PosScaled, na.rm = TRUE),
 
2390
  output$analysis_summary <- renderUI({
2391
  has_qtl <- !is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train)
2392
  has_perf <- !is.null(values$performance_metrics)
2393
+ has_epi <- !is.null(values$epistasis_sig) && !"Message" %in% colnames(values$epistasis_sig) && nrow(values$epistasis_sig) > 0
2394
  has_sel <- !is.null(values$selection_metrics) && !"Message" %in% colnames(values$selection_metrics)
2395
 
2396
  n_qtl <- if (has_qtl) nrow(values$qtl_effects_train) else 0
 
2463
  })
2464
 
2465
  output$epistasis_interpretation <- renderUI({
2466
+ if (is.null(values$epistasis_sig) || "Message" %in% colnames(values$epistasis_sig) || nrow(values$epistasis_sig) == 0) {
2467
  return(div(class = "interpretation-section",
2468
  tags$h5("Epistasis"),
2469
  tags$p("No significant epistatic interactions detected.")
 
2486
 
2487
  output$recommendations <- renderUI({
2488
  has_qtl <- !is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train)
2489
+ has_epi <- !is.null(values$epistasis_sig) && !"Message" %in% colnames(values$epistasis_sig) && nrow(values$epistasis_sig) > 0
2490
  has_sel <- !is.null(values$selection_metrics) && !"Message" %in% colnames(values$selection_metrics)
2491
+ has_perf <- !is.null(values$performance_metrics)
2492
 
2493
  recs <- character()
2494
 
2495
  if (has_qtl) {
2496
  top_qtl <- values$qtl_effects_train[which.max(values$qtl_effects_train$LOD), ]
2497
+ recs <- c(recs, paste("• **Prioritize**", top_qtl$Marker, "for validation and fine-mapping"))
2498
 
2499
+ if (has_epi) {
2500
+ recs <- c(recs, paste("• **Investigate** epistatic interactions in breeding programs"))
2501
  }
2502
 
2503
  if (has_sel) {
 
2506
  values$selection_metrics$Significant
2507
  ]
2508
  if (length(overlap) > 0) {
2509
+ recs <- c(recs, paste("• **QTLs under selection**:", paste(overlap, collapse = ", ")))
2510
+ }
2511
+ }
2512
+
2513
+ if (has_perf) {
2514
+ val_r2 <- values$performance_metrics$Value[values$performance_metrics$Metric == "R² (Validation)"]
2515
+ if (val_r2 < 0.2) {
2516
+ recs <- c(recs, "• **Consider** increasing sample size or reducing marker number")
2517
  }
2518
  }
2519
 
2520
  # Add general recommendations
2521
  recs <- c(recs,
2522
+ "• **Validate** QTLs in independent populations",
2523
+ "• **Use** flanking markers for marker-assisted selection",
2524
+ "• **Consider** multi-locus models for prediction"
2525
  )
2526
  } else {
2527
  recs <- c(
2528
+ "• **Upload** genotype and phenotype data",
2529
+ "• **Run** QTL analysis with appropriate LOD threshold",
2530
+ "• **Consider** increasing sample size for more power",
2531
+ "• **Check** data quality and format"
2532
  )
2533
  }
2534
 
2535
  div(class = "interpretation-section",
2536
  tags$h5("Recommendations"),
2537
  tags$ul(
2538
+ lapply(recs, function(r) tags$li(HTML(r))),
2539
  style = "color: #8b949e; line-height: 1.8;"
2540
  )
2541
  )