International Rice Research Institute commited on
Commit
d38726d
·
verified ·
1 Parent(s): 03effb3

Update app.R

Browse files
Files changed (1) hide show
  1. app.R +360 -363
app.R CHANGED
@@ -54,7 +54,7 @@ HF_API_TOKEN <- token
54
  # hf_model <- "google/gemma-2b-it"
55
 
56
  # Option 4: HuggingFaceH4/zephyr-7b-beta (very reliable)
57
- hf_model <- "mistralai/Mistral-7B-Instruct-v0.2"
58
  #"HuggingFaceH4/zephyr-7b-beta", # Most reliable
59
  # "mistralai/Mistral-7B-Instruct-v0.2", # Also good
60
  # "microsoft/phi-2", # Small but works
@@ -114,14 +114,10 @@ if (token_exists && api_test$success) {
114
 
115
  # Try alternative models if first one fails
116
  alt_models <- c(
117
- "mistralai/Mistral-7B-Instruct-v0.2",
118
  "microsoft/phi-2",
119
  "google/gemma-2b-it",
120
- "HuggingFaceH4/zephyr-7b-beta",
121
- "HuggingFaceH4/zephyr-7b-beta", # Most reliable
122
- "mistralai/Mistral-7B-Instruct-v0.2", # Also good
123
- "microsoft/phi-2", # Small but works
124
- "google/flan-t5-large"
125
  )
126
  ############################
127
  for (alt_model in alt_models) {
@@ -129,9 +125,10 @@ if (token_exists && api_test$success) {
129
 
130
  print(paste("Trying alternative model:", alt_model))
131
  test_url <- paste0("https://router.huggingface.co/hf-inference/models/", alt_model)
132
- # url <- paste0("https://router.huggingface.co/hf-inference/models/", model)
133
- url <- paste0("https://router.huggingface.co/hf-inference/models/", model)
134
-
 
135
  tryCatch({
136
  response <- POST(
137
  url = test_url,
@@ -253,10 +250,10 @@ build_system_prompt <- function(rv) {
253
  total_pve <- sum(rv$qtl_effects_train$PVE_Percent, na.rm = TRUE)
254
 
255
  context_parts <- c(context_parts,
256
- sprintf("\nQTL Results: %d significant QTLs detected above LOD %.1f.",
257
- n_qtl, rv$lod_threshold))
258
  context_parts <- c(context_parts,
259
- sprintf("Total variance explained by QTLs: %.1f%%.", total_pve))
260
 
261
  # Add top 3 QTLs
262
  top_qtls <- head(rv$qtl_effects_train[order(-rv$qtl_effects_train$LOD), ], 3)
@@ -264,8 +261,8 @@ build_system_prompt <- function(rv) {
264
  for (i in 1:nrow(top_qtls)) {
265
  row <- top_qtls[i, ]
266
  context_parts <- c(context_parts,
267
- sprintf(" %d. %s (Chr %s): LOD=%.2f, PVE=%.1f%%, Additive=%.3f",
268
- i, row$Marker, row$Chromosome, row$LOD, row$PVE_Percent, row$Additive_Effect))
269
  }
270
  }
271
 
@@ -276,27 +273,27 @@ build_system_prompt <- function(rv) {
276
  val_r2 <- pm$Value[pm$Metric == "R² (Validation)"]
277
 
278
  context_parts <- c(context_parts,
279
- sprintf("\nModel Performance:"),
280
- sprintf(" Training R²: %.3f", train_r2),
281
- sprintf(" Validation R²: %.3f", val_r2))
282
  }
283
 
284
  # Add epistasis results
285
  if (!is.null(rv$epistasis_sig) && !"Message" %in% colnames(rv$epistasis_sig) && nrow(rv$epistasis_sig) > 0) {
286
  n_epi <- nrow(rv$epistasis_sig)
287
  context_parts <- c(context_parts,
288
- sprintf("\nEpistasis: %d significant pairwise interactions detected.", n_epi))
289
 
290
  top_epi <- rv$epistasis_sig[order(rv$epistasis_sig$Interaction_p), ][1, ]
291
  context_parts <- c(context_parts,
292
- sprintf(" Strongest: %s × %s (p=%.4f)", top_epi$QTL1, top_epi$QTL2, top_epi$Interaction_p))
293
  }
294
 
295
  # Add domestication results
296
  if (!is.null(rv$selection_metrics) && !"Message" %in% colnames(rv$selection_metrics)) {
297
  n_sig <- sum(rv$selection_metrics$Significant, na.rm = TRUE)
298
  context_parts <- c(context_parts,
299
- sprintf("\nDomestication: %d markers with selection signatures.", n_sig))
300
  }
301
 
302
  paste(context_parts, collapse = "\n")
@@ -371,30 +368,30 @@ enhanced_rule_response <- function(user_message, rv) {
371
 
372
  if (val_r2 < 0) {
373
  response <- paste0(response,
374
- "⚠️ **Your validation R² is negative** (", round(val_r2, 3), ").\n\n",
375
- "This means the model performs worse than simply predicting the mean.\n\n",
376
- "**Common causes:**\n",
377
- "• **Small sample size** relative to number of markers\n",
378
- "• **Overfitting** - model learned noise instead of signal\n",
379
- "• **Population structure** in your data\n\n",
380
- "**Recommendations:**\n",
381
- "1. Increase sample size if possible\n",
382
- "2. Reduce marker number (use feature selection)\n",
383
- "3. Try simpler models or increase cross-validation folds\n",
384
- "4. Focus on individual QTL interpretation rather than prediction\n"
385
  )
386
  } else if (val_r2 < 0.2) {
387
  response <- paste0(response,
388
- "📉 **Low validation R²** (<0.2) suggests modest predictive power.\n\n",
389
- "This is common for complex traits. Focus on individual QTL interpretation.\n"
390
  )
391
  } else if (val_r2 < 0.5) {
392
  response <- paste0(response,
393
- "📊 **Moderate validation R²** (0.2-0.5) - your model has decent predictive ability.\n\n"
394
  )
395
  } else {
396
  response <- paste0(response,
397
- "🎯 **Excellent validation R²** (>0.5) - your model has strong predictive power!\n\n"
398
  )
399
  }
400
 
@@ -415,10 +412,10 @@ enhanced_rule_response <- function(user_message, rv) {
415
  for (i in 1:nrow(top5)) {
416
  row <- top5[i, ]
417
  response <- paste0(response,
418
- i, ". **", row$Marker, "** (Chr ", row$Chromosome, ")\n",
419
- " • LOD: **", round(row$LOD, 2), "**\n",
420
- " • PVE: ", round(row$PVE_Percent, 1), "%\n",
421
- " • Additive effect: ", round(row$Additive_Effect, 3), "\n"
422
  )
423
  if (!is.null(row$Low_Flank) && !is.na(row$Low_Flank) && row$Low_Flank != "NA") {
424
  response <- paste0(response, " • Interval: ", row$Low_Flank, " - ", row$High_Flank, "\n")
@@ -440,44 +437,44 @@ enhanced_rule_response <- function(user_message, rv) {
440
  if (has_qtl) {
441
  top_qtl <- rv$qtl_effects_train[which.max(rv$qtl_effects_train$LOD), ]
442
  response <- paste0(response,
443
- "**1. Validate Top QTLs**\n",
444
- " • Prioritize **", top_qtl$Marker, "** (LOD=", round(top_qtl$LOD, 2),
445
- ", PVE=", round(top_qtl$PVE_Percent, 1), "%)\n",
446
- " • Test in independent population or F2 cross\n",
447
- " • Use flanking markers for fine-mapping\n\n"
448
  )
449
  }
450
 
451
  if (has_epi) {
452
  n_epi <- nrow(rv$epistasis_sig)
453
  response <- paste0(response,
454
- "**2. Investigate Epistasis**\n",
455
- " • ", n_epi, " significant interactions detected\n",
456
- " • Test multi-locus models in breeding programs\n",
457
- " • Check if interacting QTLs map to same pathways\n\n"
458
  )
459
  }
460
 
461
  if (has_sel) {
462
  n_sel <- sum(rv$selection_metrics$Significant, na.rm = TRUE)
463
  response <- paste0(response,
464
- "**3. Domestication Analysis**\n",
465
- " • ", n_sel, " markers show selection signatures\n",
466
- " • Cross-reference with QTL positions\n",
467
- " • Candidate domestication genes\n\n"
468
  )
469
  }
470
 
471
  response <- paste0(response,
472
- "**4. Functional Analysis**\n",
473
- " • Annotate QTL regions for candidate genes\n",
474
- " • Check gene expression databases\n",
475
- " • Design validation experiments\n\n",
476
-
477
- "**5. Breeding Applications**\n",
478
- " • Develop markers for MAS\n",
479
- " • Design crossing schemes\n",
480
- " • Predict breeding values\n"
481
  )
482
 
483
  return(response)
@@ -967,254 +964,254 @@ ui <- fluidPage(
967
  id = "nav",
968
 
969
  tabPanel("Data Upload", icon = icon("upload"),
970
- div(class = "main-header",
971
- h2(tags$i(class = "fas fa-upload", style = "margin-right:8px;"), "Data Upload"),
972
- p("Upload genotype, phenotype, and population data for comprehensive QTL analysis with AI assistance")
973
- ),
974
- fluidRow(
975
- column(4,
976
- div(class = "card",
977
- div(class = "card-header", tags$i(class = "fas fa-table", style = "margin-right:6px;"), "Training Data"),
978
- div(class = "card-body",
979
- fileInput("genotype_file", "Training Genotype CSV", accept = c(".csv"), buttonLabel = "Browse"),
980
- helpText("CSV: Row1=header(id,markers), Row2=chromosomes, Row3=positions, rows=samples. Genotype coded 0/1/2."),
981
- fileInput("phenotype_file", "Training Phenotype CSV", accept = c(".csv"), buttonLabel = "Browse"),
982
- helpText("CSV: id column + numeric trait columns."),
983
- selectInput("phenotype_column", "Select Phenotype Column", choices = NULL)
984
- )
985
- )
986
- ),
987
- column(4,
988
- div(class = "card",
989
- div(class = "card-header", tags$i(class = "fas fa-vial", style = "margin-right:6px; color:#3fb950;"), "Test Data (Optional)"),
990
- div(class = "card-body",
991
- fileInput("test_genotype_file", "Test Genotype CSV", accept = c(".csv"), buttonLabel = "Browse"),
992
- helpText("Optional: Same format as training genotype data."),
993
- tags$br(),
994
- actionButton("predict_test_phenotype", "Predict Test Phenotypes", class = "btn-info btn-block", icon = icon("magic"))
995
- )
996
- )
997
- ),
998
- column(4,
999
- div(class = "card",
1000
- div(class = "card-header", tags$i(class = "fas fa-sliders-h", style = "margin-right:6px; color:#bc8cff;"), "Analysis Parameters"),
1001
- div(class = "card-body",
1002
- sliderInput("test_size", "Validation Set Proportion", min = 0.1, max = 0.5, value = 0.2, step = 0.05),
1003
- numericInput("lod_threshold", "LOD Threshold", value = 2.0, min = 1.0, max = 10.0, step = 0.1),
1004
- actionButton("run_analysis", "Run QTL Analysis", class = "btn-primary btn-block", icon = icon("play"))
1005
- )
1006
- )
1007
- )
1008
- ),
1009
- fluidRow(
1010
- column(12,
1011
- div(class = "card",
1012
- div(class = "card-header", "Data Preview"),
1013
- div(class = "card-body",
1014
- tabsetPanel(
1015
- tabPanel("Training Genotype", DTOutput("geno_preview")),
1016
- tabPanel("Training Phenotype", DTOutput("pheno_preview")),
1017
- tabPanel("Test Genotype", DTOutput("test_geno_preview")),
1018
- tabPanel("Predicted Test Phenotype", DTOutput("predicted_test_pheno_preview"))
1019
- )
1020
- )
1021
- )
1022
- )
1023
- )
1024
  ),
1025
 
1026
  tabPanel("Domestication", icon = icon("leaf"),
1027
- div(class = "main-header",
1028
- h2(tags$i(class = "fas fa-leaf", style = "margin-right:8px;"), "Domestication Analysis"),
1029
- p("Analyze selection signatures: Fst, Tajima's D, and nucleotide diversity")
1030
- ),
1031
- fluidRow(
1032
- column(4,
1033
- div(class = "card",
1034
- div(class = "card-header", "Population Metadata"),
1035
- div(class = "card-body",
1036
- fileInput("pop_file", "Population Metadata CSV", accept = c(".csv"), buttonLabel = "Browse"),
1037
- helpText("CSV with 'id' and 'population' columns (e.g., Domesticated, Wild)."),
1038
- numericInput("fst_threshold", "Fst Threshold", value = 0.1, min = 0.05, max = 0.5, step = 0.01),
1039
- numericInput("tajima_threshold", "Tajima's D Threshold", value = -1, min = -5, max = 0, step = 0.1),
1040
- actionButton("run_domestication", "Run Domestication Analysis", class = "btn-primary btn-block", icon = icon("play"))
1041
- )
1042
- )
1043
- ),
1044
- column(8,
1045
- div(class = "card",
1046
- div(class = "card-header", "Population Data Preview"),
1047
- div(class = "card-body", DTOutput("pop_preview"))
1048
- )
1049
- )
1050
- ),
1051
- fluidRow(
1052
- column(6, div(class = "card", div(class = "card-header", "Fst Manhattan Plot"), div(class = "card-body", plotlyOutput("fst_plot", height = "400px")))),
1053
- column(6, div(class = "card", div(class = "card-header", "Tajima's D Manhattan Plot"), div(class = "card-body", plotlyOutput("tajima_plot", height = "400px"))))
1054
- ),
1055
- fluidRow(
1056
- column(12,
1057
- div(class = "card",
1058
- div(class = "card-header", "Selection Signatures"),
1059
- div(class = "card-body",
1060
- DTOutput("selection_table"),
1061
- tags$br(),
1062
- downloadButton("download_selection", "Download Selection Results")
1063
- )
1064
- )
1065
- )
1066
- )
1067
  ),
1068
 
1069
  tabPanel("Results", icon = icon("chart-line"),
1070
- div(class = "main-header",
1071
- h2(tags$i(class = "fas fa-chart-line", style = "margin-right:8px;"), "QTL Analysis Results"),
1072
- p("LOD scores, QTL effects, model performance, and epistasis analysis")
1073
- ),
1074
- fluidRow(
1075
- column(6, div(class = "card", div(class = "card-header", "Manhattan Plot (LOD Scores)"), div(class = "card-body", plotlyOutput("lod_plot_2d", height = "500px")))),
1076
- column(6, div(class = "card",
1077
- div(class = "card-header", "Chromosome Visualization"),
1078
- div(class = "card-body",
1079
- uiOutput("chromosome_viz"),
1080
- div(class = "simulation-controls",
1081
- actionButton("simulate_btn", "Simulate Discovery", class = "simulation-btn"),
1082
- actionButton("reset_btn", "Reset", class = "simulation-btn")
1083
- )
1084
- )
1085
- ))
1086
- ),
1087
- fluidRow(
1088
- column(4, div(class = "card", div(class = "card-header", "Model Performance"), div(class = "card-body", plotlyOutput("performance_plot")))),
1089
- column(4, div(class = "card", div(class = "card-header", "Train: Predicted vs Observed"), div(class = "card-body", plotlyOutput("regression_plot_train", height = "300px")))),
1090
- column(4, div(class = "card", div(class = "card-header", "Validation: Predicted vs Observed"), div(class = "card-body", plotlyOutput("regression_plot_test", height = "300px"))))
1091
- ),
1092
- fluidRow(
1093
- column(12, div(class = "card",
1094
- div(class = "card-header", "QTL Effects — Training Set"),
1095
- div(class = "card-body", DTOutput("qtl_effects_table_train"), tags$br(), downloadButton("download_train_results", "Download"))
1096
- ))
1097
- ),
1098
- fluidRow(
1099
- column(12, div(class = "card",
1100
- div(class = "card-header", "Epistasis Analysis"),
1101
- div(class = "card-body",
1102
- DTOutput("epistasis_table"),
1103
- plotlyOutput("epistasis_heatmap", height = "400px")
1104
- )
1105
- ))
1106
- )
1107
  ),
1108
 
1109
  tabPanel("Interpretation", icon = icon("lightbulb"),
1110
- div(class = "main-header",
1111
- h2(tags$i(class = "fas fa-lightbulb", style = "margin-right:8px;"), "Results Interpretation"),
1112
- p("Comprehensive interpretation of QTL and domestication analysis")
1113
- ),
1114
- fluidRow(
1115
- column(12, div(class = "card", div(class = "card-header", "Analysis Summary"), div(class = "card-body", uiOutput("analysis_summary"))))
1116
- ),
1117
- fluidRow(
1118
- column(6, div(class = "card", div(class = "card-header", "QTL Significance"), div(class = "card-body", uiOutput("qtl_interpretation")))),
1119
- column(6, div(class = "card", div(class = "card-header", "Effect Sizes"), div(class = "card-body", uiOutput("effect_interpretation"))))
1120
- ),
1121
- fluidRow(
1122
- column(12, div(class = "card", div(class = "card-header", "Epistasis"), div(class = "card-body", uiOutput("epistasis_interpretation"))))
1123
- ),
1124
- fluidRow(
1125
- column(12, div(class = "card", div(class = "card-header", "Recommendations"), div(class = "card-body", uiOutput("recommendations"))))
1126
- )
1127
  ),
1128
 
1129
  tabPanel("About", icon = icon("info-circle"),
1130
- div(class = "main-header",
1131
- h2(tags$i(class = "fas fa-info-circle", style = "margin-right:8px;"), "About QTL-Mapper AI"),
1132
- p("QTL Mapping with Transformer-based AI Assistant")
1133
- ),
1134
- fluidRow(
1135
- column(8, offset = 2,
1136
- div(class = "card",
1137
- div(class = "card-body",
1138
- h4(style = "color:#58a6ff; font-family: 'IBM Plex Mono'; margin-bottom:12px;", "Methodology"),
1139
- tags$ul(style = "color: #8b949e; line-height: 2;",
1140
- tags$li("Random Forest for QTL mapping with variable importance scoring"),
1141
- tags$li("LOD scores derived from marker importance (-log10 scale)"),
1142
- tags$li("Additive and dominance effects estimated via linear regression"),
1143
- tags$li("Epistasis analysis: pairwise QTL x marker interactions"),
1144
- tags$li("Domestication: Fst, nucleotide diversity (Pi), Tajima's D"),
1145
- tags$li("AI Assistant powered by transformer models via Hugging Face Inference API")
1146
- ),
1147
- h4(style = "color:#58a6ff; font-family: 'IBM Plex Mono'; margin: 12px 0;", "AI Assistant Status"),
1148
- p(style = "color: #8b949e; line-height: 1.7;",
1149
- if (use_hf_api) {
1150
- paste("✅ AI Assistant is connected to Hugging Face API using", hf_model)
1151
- } else {
1152
- "⚠️ AI Assistant is in rule-based mode. Set HF_API_TOKEN in Space secrets to enable transformer-based responses."
1153
- }
1154
- ),
1155
- h4(style = "color:#58a6ff; font-family: 'IBM Plex Mono'; margin: 12px 0;", "Interpretation Thresholds"),
1156
- tags$ul(style = "color: #8b949e; line-height: 2;",
1157
- tags$li("LOD > 3: Suggestive QTL | LOD > 5: Significant QTL"),
1158
- tags$li("Fst > 0.2: Strong population differentiation"),
1159
- tags$li("Tajima's D < -2: Potential selective sweep"),
1160
- tags$li("PVE > 10%: Major-effect QTL")
1161
- )
1162
- )
1163
- )
1164
- )
1165
- )
1166
  )
1167
  ),
1168
 
1169
  tags$div(id = "chat-panel",
1170
- tags$div(id = "chat-window",
1171
- tags$div(id = "chat-header",
1172
- tags$div(class = "chat-title",
1173
- tags$div(class = "chat-avatar", "AI"),
1174
- tags$div(
1175
- tags$h4("QTL Analysis AI Assistant",
1176
- tags$span(class = "model-badge",
1177
- if(use_hf_api) gsub(".*/", "", hf_model) else "rules")
1178
- ),
1179
- tags$p(id = "model_status",
1180
- if(use_hf_api) paste("🤖 AI mode -", gsub(".*/", "", hf_model)) else "📝 Rule-based mode",
1181
- class = if(use_hf_api) "ai-mode" else "rule-mode"
1182
- )
1183
- )
1184
- ),
1185
- tags$button(id = "chat-close-btn", onclick = "document.getElementById('chat-window').classList.remove('open');",
1186
- tags$i(class = "fas fa-times")
1187
- )
1188
- ),
1189
-
1190
- tags$div(class = "quick-questions",
1191
- tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q', 'What is PVE?', {priority: 'event'});", "PVE meaning"),
1192
- tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q', 'What are my top QTLs?', {priority: 'event'});", "Top QTLs"),
1193
- tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q', 'Why is my R² negative?', {priority: 'event'});", "Negative R²"),
1194
- tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q', 'What should I do next?', {priority: 'event'});", "Next steps")
1195
- ),
1196
-
1197
- tags$div(id = "chat_messages",
1198
- uiOutput("chat_display")
1199
- ),
1200
-
1201
- tags$div(id = "chat-footer",
1202
- tags$textarea(
1203
- id = "chat_input",
1204
- placeholder = "Ask about your results... (Enter to send)",
1205
- rows = "2"
1206
- ),
1207
- tags$div(class = "chat-actions",
1208
- actionButton("send_chat", "Send", icon = icon("paper-plane"), class = "btn-primary"),
1209
- actionButton("clear_chat", "Clear", icon = icon("trash-alt"), class = "btn-danger")
1210
- )
1211
- )
1212
- ),
1213
-
1214
- tags$button(id = "chat-toggle-btn",
1215
- onclick = "document.getElementById('chat-window').classList.toggle('open');",
1216
- tags$i(class = "fas fa-robot")
1217
- )
1218
  )
1219
  )
1220
 
@@ -1333,19 +1330,19 @@ server <- function(input, output, session) {
1333
 
1334
  message_elements <- lapply(messages, function(msg) {
1335
  div(class = paste("chat-msg", msg$role),
1336
- div(class = "chat-bubble",
1337
- HTML(gsub("\n", "<br>", htmltools::htmlEscape(msg$content)))
1338
- ),
1339
- div(class = "chat-meta", msg$time)
1340
  )
1341
  })
1342
 
1343
  if (values$is_typing) {
1344
  message_elements <- c(message_elements, list(
1345
  div(class = "chat-msg assistant",
1346
- div(class = "typing-indicator",
1347
- div(class = "typing-dot"), div(class = "typing-dot"), div(class = "typing-dot")
1348
- )
1349
  )
1350
  ))
1351
  }
@@ -1411,8 +1408,8 @@ server <- function(input, output, session) {
1411
 
1412
  values$phenotype_data <- phenotype_data
1413
  updateSelectInput(session, "phenotype_column",
1414
- choices = colnames(phenotype_data),
1415
- selected = colnames(phenotype_data)[1])
1416
 
1417
  showNotification("Phenotype data loaded", type = "message")
1418
  add_message("assistant", paste0("✅ Loaded ", ncol(phenotype_data), " traits, ", nrow(phenotype_data), " samples"))
@@ -1524,7 +1521,7 @@ server <- function(input, output, session) {
1524
  geno_means <- tapply(pheno, geno, mean, na.rm = TRUE)
1525
  het_mean <- geno_means[as.character(sort(unique(geno))[2])]
1526
  midparent <- (geno_means[as.character(sort(unique(geno))[1])] +
1527
- geno_means[as.character(sort(unique(geno))[3])]) / 2
1528
  dominance_effect <- het_mean - midparent
1529
  }
1530
 
@@ -1817,7 +1814,7 @@ server <- function(input, output, session) {
1817
 
1818
  tryCatch({
1819
  common_markers <- intersect(colnames(values$test_genotype_data),
1820
- colnames(values$genotype_data))
1821
 
1822
  if (length(common_markers) == 0) {
1823
  showNotification("No common markers", type = "error")
@@ -2089,7 +2086,7 @@ server <- function(input, output, session) {
2089
 
2090
  if ("Message" %in% colnames(values$qtl_effects_train)) {
2091
  return(datatable(data.frame(Status = values$qtl_effects_train$Message[1]),
2092
- options = list(dom = 't')))
2093
  }
2094
 
2095
  display_cols <- intersect(
@@ -2109,7 +2106,7 @@ server <- function(input, output, session) {
2109
 
2110
  if ("Message" %in% colnames(values$epistasis_sig)) {
2111
  return(datatable(data.frame(Status = values$epistasis_sig$Message[1]),
2112
- options = list(dom = 't')))
2113
  }
2114
 
2115
  datatable(
@@ -2125,7 +2122,7 @@ server <- function(input, output, session) {
2125
 
2126
  if ("Message" %in% colnames(values$selection_metrics)) {
2127
  return(datatable(data.frame(Status = values$selection_metrics$Message[1]),
2128
- options = list(dom = 't')))
2129
  }
2130
 
2131
  df <- values$selection_metrics
@@ -2175,29 +2172,29 @@ server <- function(input, output, session) {
2175
  range_pos <- max_pos - min_pos
2176
 
2177
  div(class = "chromosome-container",
2178
- div(class = "chromosome-title", paste("Chromosome", chr)),
2179
- div(class = "chromosome",
2180
- lapply(1:nrow(chr_markers), function(i) {
2181
- marker <- chr_markers[i, ]
2182
- left <- if (range_pos > 0) ((marker$Position - min_pos) / range_pos) * 100
2183
- else (i / nrow(chr_markers)) * 100
2184
-
2185
- marker_class <- "chromosome-marker"
2186
- if (marker$Marker %in% chr_qtls$Marker) {
2187
- marker_class <- paste(marker_class, "significant")
2188
- } else if (!is.null(sel_markers) && marker$Marker %in% sel_markers$Marker) {
2189
- marker_class <- paste(marker_class, "selection")
2190
- } else if (marker$Marker %in% c(chr_qtls$Low_Flank, chr_qtls$High_Flank)) {
2191
- marker_class <- paste(marker_class, "flanking")
2192
- }
2193
-
2194
- div(class = marker_class, style = paste0("left: ", left, "%;"))
2195
- })
2196
- ),
2197
- div(class = "chromosome-legend",
2198
- span(paste(format(min_pos, big.mark = ","), "bp")),
2199
- span(paste(format(max_pos, big.mark = ","), "bp"))
2200
- )
2201
  )
2202
  })
2203
  )
@@ -2232,59 +2229,59 @@ server <- function(input, output, session) {
2232
  val_r2 <- if (has_perf) round(values$performance_metrics$Value[values$performance_metrics$Metric == "R² (Validation)"], 3) else "N/A"
2233
 
2234
  div(class = "interpretation-section",
2235
- tags$h5("Analysis Summary"),
2236
- tags$p(paste(
2237
- "Found", n_qtl, "QTLs above LOD", input$lod_threshold,
2238
- if (has_perf) paste0("(validation R² = ", val_r2, ")"),
2239
- if (has_epi) paste0("with", n_epi, "epistatic interactions"),
2240
- if (has_sel) paste0("and", n_sel, "selection signatures.")
2241
- ))
2242
  )
2243
  })
2244
 
2245
  output$qtl_interpretation <- renderUI({
2246
  if (is.null(values$qtl_effects_train) || "Message" %in% colnames(values$qtl_effects_train)) {
2247
  return(div(class = "interpretation-section",
2248
- tags$h5("QTL Significance"),
2249
- tags$p("No significant QTLs detected.")
2250
  ))
2251
  }
2252
 
2253
  top_qtl <- values$qtl_effects_train[which.max(values$qtl_effects_train$LOD), ]
2254
 
2255
  div(class = "interpretation-section",
2256
- tags$h5("QTL Significance"),
2257
- tags$p(paste(
2258
- "Top QTL:", top_qtl$Marker, "(Chr", top_qtl$Chromosome,
2259
- ") with LOD =", round(top_qtl$LOD, 2)
2260
- ))
2261
  )
2262
  })
2263
 
2264
  output$effect_interpretation <- renderUI({
2265
  if (is.null(values$qtl_effects_train) || "Message" %in% colnames(values$qtl_effects_train)) {
2266
  return(div(class = "interpretation-section",
2267
- tags$h5("Effect Sizes"),
2268
- tags$p("No QTL effects to interpret.")
2269
  ))
2270
  }
2271
 
2272
  top_pve <- values$qtl_effects_train[which.max(values$qtl_effects_train$PVE_Percent), ]
2273
 
2274
  div(class = "interpretation-section",
2275
- tags$h5("Effect Sizes"),
2276
- tags$p(paste(
2277
- "Largest effect:", top_pve$Marker, "explains",
2278
- round(top_pve$PVE_Percent, 1), "% of variance"
2279
- ))
2280
  )
2281
  })
2282
 
2283
  output$epistasis_interpretation <- renderUI({
2284
  if (is.null(values$epistasis_sig) || "Message" %in% colnames(values$epistasis_sig) || nrow(values$epistasis_sig) == 0) {
2285
  return(div(class = "interpretation-section",
2286
- tags$h5("Epistasis"),
2287
- tags$p("No significant epistatic interactions detected.")
2288
  ))
2289
  }
2290
 
@@ -2292,12 +2289,12 @@ server <- function(input, output, session) {
2292
  top_epi <- values$epistasis_sig[which.min(values$epistasis_sig$Interaction_p), ]
2293
 
2294
  div(class = "interpretation-section",
2295
- tags$h5("Epistasis"),
2296
- tags$p(paste(
2297
- "Detected", n_epi, "interactions. Strongest:",
2298
- top_epi$QTL1, "×", top_epi$QTL2,
2299
- "(p =", format.pval(top_epi$Interaction_p), ")"
2300
- ))
2301
  )
2302
  })
2303
 
@@ -2319,8 +2316,8 @@ server <- function(input, output, session) {
2319
  }
2320
 
2321
  div(class = "interpretation-section",
2322
- tags$h5("Recommendations"),
2323
- tags$ul(lapply(recs, tags$li), style = "color: #8b949e;")
2324
  )
2325
  })
2326
 
@@ -2355,7 +2352,7 @@ server <- function(input, output, session) {
2355
  }
2356
 
2357
  # ============================================================
2358
- # RUN APPa
2359
  # ============================================================
2360
 
2361
  shinyApp(ui = ui, server = server)
 
54
  # hf_model <- "google/gemma-2b-it"
55
 
56
  # Option 4: HuggingFaceH4/zephyr-7b-beta (very reliable)
57
+ hf_model <- "HuggingFaceH4/zephyr-7b-beta"
58
  #"HuggingFaceH4/zephyr-7b-beta", # Most reliable
59
  # "mistralai/Mistral-7B-Instruct-v0.2", # Also good
60
  # "microsoft/phi-2", # Small but works
 
114
 
115
  # Try alternative models if first one fails
116
  alt_models <- c(
117
+ "HuggingFaceH4/zephyr-7b-beta",
118
  "microsoft/phi-2",
119
  "google/gemma-2b-it",
120
+ "google/flan-t5-large"
 
 
 
 
121
  )
122
  ############################
123
  for (alt_model in alt_models) {
 
125
 
126
  print(paste("Trying alternative model:", alt_model))
127
  test_url <- paste0("https://router.huggingface.co/hf-inference/models/", alt_model)
128
+ # url <- paste0("https://router.huggingface.co/hf-inference/models/", model)
129
+ #url <- paste0("https://router.huggingface.co/hf-inference/models/", model)
130
+ url <- paste0("https://router.huggingface.co/hf-inference/models/", alt_model)
131
+
132
  tryCatch({
133
  response <- POST(
134
  url = test_url,
 
250
  total_pve <- sum(rv$qtl_effects_train$PVE_Percent, na.rm = TRUE)
251
 
252
  context_parts <- c(context_parts,
253
+ sprintf("\nQTL Results: %d significant QTLs detected above LOD %.1f.",
254
+ n_qtl, rv$lod_threshold))
255
  context_parts <- c(context_parts,
256
+ sprintf("Total variance explained by QTLs: %.1f%%.", total_pve))
257
 
258
  # Add top 3 QTLs
259
  top_qtls <- head(rv$qtl_effects_train[order(-rv$qtl_effects_train$LOD), ], 3)
 
261
  for (i in 1:nrow(top_qtls)) {
262
  row <- top_qtls[i, ]
263
  context_parts <- c(context_parts,
264
+ sprintf(" %d. %s (Chr %s): LOD=%.2f, PVE=%.1f%%, Additive=%.3f",
265
+ i, row$Marker, row$Chromosome, row$LOD, row$PVE_Percent, row$Additive_Effect))
266
  }
267
  }
268
 
 
273
  val_r2 <- pm$Value[pm$Metric == "R² (Validation)"]
274
 
275
  context_parts <- c(context_parts,
276
+ sprintf("\nModel Performance:"),
277
+ sprintf(" Training R²: %.3f", train_r2),
278
+ sprintf(" Validation R²: %.3f", val_r2))
279
  }
280
 
281
  # Add epistasis results
282
  if (!is.null(rv$epistasis_sig) && !"Message" %in% colnames(rv$epistasis_sig) && nrow(rv$epistasis_sig) > 0) {
283
  n_epi <- nrow(rv$epistasis_sig)
284
  context_parts <- c(context_parts,
285
+ sprintf("\nEpistasis: %d significant pairwise interactions detected.", n_epi))
286
 
287
  top_epi <- rv$epistasis_sig[order(rv$epistasis_sig$Interaction_p), ][1, ]
288
  context_parts <- c(context_parts,
289
+ sprintf(" Strongest: %s × %s (p=%.4f)", top_epi$QTL1, top_epi$QTL2, top_epi$Interaction_p))
290
  }
291
 
292
  # Add domestication results
293
  if (!is.null(rv$selection_metrics) && !"Message" %in% colnames(rv$selection_metrics)) {
294
  n_sig <- sum(rv$selection_metrics$Significant, na.rm = TRUE)
295
  context_parts <- c(context_parts,
296
+ sprintf("\nDomestication: %d markers with selection signatures.", n_sig))
297
  }
298
 
299
  paste(context_parts, collapse = "\n")
 
368
 
369
  if (val_r2 < 0) {
370
  response <- paste0(response,
371
+ "⚠️ **Your validation R² is negative** (", round(val_r2, 3), ").\n\n",
372
+ "This means the model performs worse than simply predicting the mean.\n\n",
373
+ "**Common causes:**\n",
374
+ "• **Small sample size** relative to number of markers\n",
375
+ "• **Overfitting** - model learned noise instead of signal\n",
376
+ "• **Population structure** in your data\n\n",
377
+ "**Recommendations:**\n",
378
+ "1. Increase sample size if possible\n",
379
+ "2. Reduce marker number (use feature selection)\n",
380
+ "3. Try simpler models or increase cross-validation folds\n",
381
+ "4. Focus on individual QTL interpretation rather than prediction\n"
382
  )
383
  } else if (val_r2 < 0.2) {
384
  response <- paste0(response,
385
+ "📉 **Low validation R²** (<0.2) suggests modest predictive power.\n\n",
386
+ "This is common for complex traits. Focus on individual QTL interpretation.\n"
387
  )
388
  } else if (val_r2 < 0.5) {
389
  response <- paste0(response,
390
+ "📊 **Moderate validation R²** (0.2-0.5) - your model has decent predictive ability.\n\n"
391
  )
392
  } else {
393
  response <- paste0(response,
394
+ "🎯 **Excellent validation R²** (>0.5) - your model has strong predictive power!\n\n"
395
  )
396
  }
397
 
 
412
  for (i in 1:nrow(top5)) {
413
  row <- top5[i, ]
414
  response <- paste0(response,
415
+ i, ". **", row$Marker, "** (Chr ", row$Chromosome, ")\n",
416
+ " • LOD: **", round(row$LOD, 2), "**\n",
417
+ " • PVE: ", round(row$PVE_Percent, 1), "%\n",
418
+ " • Additive effect: ", round(row$Additive_Effect, 3), "\n"
419
  )
420
  if (!is.null(row$Low_Flank) && !is.na(row$Low_Flank) && row$Low_Flank != "NA") {
421
  response <- paste0(response, " • Interval: ", row$Low_Flank, " - ", row$High_Flank, "\n")
 
437
  if (has_qtl) {
438
  top_qtl <- rv$qtl_effects_train[which.max(rv$qtl_effects_train$LOD), ]
439
  response <- paste0(response,
440
+ "**1. Validate Top QTLs**\n",
441
+ " • Prioritize **", top_qtl$Marker, "** (LOD=", round(top_qtl$LOD, 2),
442
+ ", PVE=", round(top_qtl$PVE_Percent, 1), "%)\n",
443
+ " • Test in independent population or F2 cross\n",
444
+ " • Use flanking markers for fine-mapping\n\n"
445
  )
446
  }
447
 
448
  if (has_epi) {
449
  n_epi <- nrow(rv$epistasis_sig)
450
  response <- paste0(response,
451
+ "**2. Investigate Epistasis**\n",
452
+ " • ", n_epi, " significant interactions detected\n",
453
+ " • Test multi-locus models in breeding programs\n",
454
+ " • Check if interacting QTLs map to same pathways\n\n"
455
  )
456
  }
457
 
458
  if (has_sel) {
459
  n_sel <- sum(rv$selection_metrics$Significant, na.rm = TRUE)
460
  response <- paste0(response,
461
+ "**3. Domestication Analysis**\n",
462
+ " • ", n_sel, " markers show selection signatures\n",
463
+ " • Cross-reference with QTL positions\n",
464
+ " • Candidate domestication genes\n\n"
465
  )
466
  }
467
 
468
  response <- paste0(response,
469
+ "**4. Functional Analysis**\n",
470
+ " • Annotate QTL regions for candidate genes\n",
471
+ " • Check gene expression databases\n",
472
+ " • Design validation experiments\n\n",
473
+
474
+ "**5. Breeding Applications**\n",
475
+ " • Develop markers for MAS\n",
476
+ " • Design crossing schemes\n",
477
+ " • Predict breeding values\n"
478
  )
479
 
480
  return(response)
 
964
  id = "nav",
965
 
966
  tabPanel("Data Upload", icon = icon("upload"),
967
+ div(class = "main-header",
968
+ h2(tags$i(class = "fas fa-upload", style = "margin-right:8px;"), "Data Upload"),
969
+ p("Upload genotype, phenotype, and population data for comprehensive QTL analysis with AI assistance")
970
+ ),
971
+ fluidRow(
972
+ column(4,
973
+ div(class = "card",
974
+ div(class = "card-header", tags$i(class = "fas fa-table", style = "margin-right:6px;"), "Training Data"),
975
+ div(class = "card-body",
976
+ fileInput("genotype_file", "Training Genotype CSV", accept = c(".csv"), buttonLabel = "Browse"),
977
+ helpText("CSV: Row1=header(id,markers), Row2=chromosomes, Row3=positions, rows=samples. Genotype coded 0/1/2."),
978
+ fileInput("phenotype_file", "Training Phenotype CSV", accept = c(".csv"), buttonLabel = "Browse"),
979
+ helpText("CSV: id column + numeric trait columns."),
980
+ selectInput("phenotype_column", "Select Phenotype Column", choices = NULL)
981
+ )
982
+ )
983
+ ),
984
+ column(4,
985
+ div(class = "card",
986
+ div(class = "card-header", tags$i(class = "fas fa-vial", style = "margin-right:6px; color:#3fb950;"), "Test Data (Optional)"),
987
+ div(class = "card-body",
988
+ fileInput("test_genotype_file", "Test Genotype CSV", accept = c(".csv"), buttonLabel = "Browse"),
989
+ helpText("Optional: Same format as training genotype data."),
990
+ tags$br(),
991
+ actionButton("predict_test_phenotype", "Predict Test Phenotypes", class = "btn-info btn-block", icon = icon("magic"))
992
+ )
993
+ )
994
+ ),
995
+ column(4,
996
+ div(class = "card",
997
+ div(class = "card-header", tags$i(class = "fas fa-sliders-h", style = "margin-right:6px; color:#bc8cff;"), "Analysis Parameters"),
998
+ div(class = "card-body",
999
+ sliderInput("test_size", "Validation Set Proportion", min = 0.1, max = 0.5, value = 0.2, step = 0.05),
1000
+ numericInput("lod_threshold", "LOD Threshold", value = 2.0, min = 1.0, max = 10.0, step = 0.1),
1001
+ actionButton("run_analysis", "Run QTL Analysis", class = "btn-primary btn-block", icon = icon("play"))
1002
+ )
1003
+ )
1004
+ )
1005
+ ),
1006
+ fluidRow(
1007
+ column(12,
1008
+ div(class = "card",
1009
+ div(class = "card-header", "Data Preview"),
1010
+ div(class = "card-body",
1011
+ tabsetPanel(
1012
+ tabPanel("Training Genotype", DTOutput("geno_preview")),
1013
+ tabPanel("Training Phenotype", DTOutput("pheno_preview")),
1014
+ tabPanel("Test Genotype", DTOutput("test_geno_preview")),
1015
+ tabPanel("Predicted Test Phenotype", DTOutput("predicted_test_pheno_preview"))
1016
+ )
1017
+ )
1018
+ )
1019
+ )
1020
+ )
1021
  ),
1022
 
1023
  tabPanel("Domestication", icon = icon("leaf"),
1024
+ div(class = "main-header",
1025
+ h2(tags$i(class = "fas fa-leaf", style = "margin-right:8px;"), "Domestication Analysis"),
1026
+ p("Analyze selection signatures: Fst, Tajima's D, and nucleotide diversity")
1027
+ ),
1028
+ fluidRow(
1029
+ column(4,
1030
+ div(class = "card",
1031
+ div(class = "card-header", "Population Metadata"),
1032
+ div(class = "card-body",
1033
+ fileInput("pop_file", "Population Metadata CSV", accept = c(".csv"), buttonLabel = "Browse"),
1034
+ helpText("CSV with 'id' and 'population' columns (e.g., Domesticated, Wild)."),
1035
+ numericInput("fst_threshold", "Fst Threshold", value = 0.1, min = 0.05, max = 0.5, step = 0.01),
1036
+ numericInput("tajima_threshold", "Tajima's D Threshold", value = -1, min = -5, max = 0, step = 0.1),
1037
+ actionButton("run_domestication", "Run Domestication Analysis", class = "btn-primary btn-block", icon = icon("play"))
1038
+ )
1039
+ )
1040
+ ),
1041
+ column(8,
1042
+ div(class = "card",
1043
+ div(class = "card-header", "Population Data Preview"),
1044
+ div(class = "card-body", DTOutput("pop_preview"))
1045
+ )
1046
+ )
1047
+ ),
1048
+ fluidRow(
1049
+ column(6, div(class = "card", div(class = "card-header", "Fst Manhattan Plot"), div(class = "card-body", plotlyOutput("fst_plot", height = "400px")))),
1050
+ column(6, div(class = "card", div(class = "card-header", "Tajima's D Manhattan Plot"), div(class = "card-body", plotlyOutput("tajima_plot", height = "400px"))))
1051
+ ),
1052
+ fluidRow(
1053
+ column(12,
1054
+ div(class = "card",
1055
+ div(class = "card-header", "Selection Signatures"),
1056
+ div(class = "card-body",
1057
+ DTOutput("selection_table"),
1058
+ tags$br(),
1059
+ downloadButton("download_selection", "Download Selection Results")
1060
+ )
1061
+ )
1062
+ )
1063
+ )
1064
  ),
1065
 
1066
  tabPanel("Results", icon = icon("chart-line"),
1067
+ div(class = "main-header",
1068
+ h2(tags$i(class = "fas fa-chart-line", style = "margin-right:8px;"), "QTL Analysis Results"),
1069
+ p("LOD scores, QTL effects, model performance, and epistasis analysis")
1070
+ ),
1071
+ fluidRow(
1072
+ column(6, div(class = "card", div(class = "card-header", "Manhattan Plot (LOD Scores)"), div(class = "card-body", plotlyOutput("lod_plot_2d", height = "500px")))),
1073
+ column(6, div(class = "card",
1074
+ div(class = "card-header", "Chromosome Visualization"),
1075
+ div(class = "card-body",
1076
+ uiOutput("chromosome_viz"),
1077
+ div(class = "simulation-controls",
1078
+ actionButton("simulate_btn", "Simulate Discovery", class = "simulation-btn"),
1079
+ actionButton("reset_btn", "Reset", class = "simulation-btn")
1080
+ )
1081
+ )
1082
+ ))
1083
+ ),
1084
+ fluidRow(
1085
+ column(4, div(class = "card", div(class = "card-header", "Model Performance"), div(class = "card-body", plotlyOutput("performance_plot")))),
1086
+ column(4, div(class = "card", div(class = "card-header", "Train: Predicted vs Observed"), div(class = "card-body", plotlyOutput("regression_plot_train", height = "300px")))),
1087
+ column(4, div(class = "card", div(class = "card-header", "Validation: Predicted vs Observed"), div(class = "card-body", plotlyOutput("regression_plot_test", height = "300px"))))
1088
+ ),
1089
+ fluidRow(
1090
+ column(12, div(class = "card",
1091
+ div(class = "card-header", "QTL Effects — Training Set"),
1092
+ div(class = "card-body", DTOutput("qtl_effects_table_train"), tags$br(), downloadButton("download_train_results", "Download"))
1093
+ ))
1094
+ ),
1095
+ fluidRow(
1096
+ column(12, div(class = "card",
1097
+ div(class = "card-header", "Epistasis Analysis"),
1098
+ div(class = "card-body",
1099
+ DTOutput("epistasis_table"),
1100
+ plotlyOutput("epistasis_heatmap", height = "400px")
1101
+ )
1102
+ ))
1103
+ )
1104
  ),
1105
 
1106
  tabPanel("Interpretation", icon = icon("lightbulb"),
1107
+ div(class = "main-header",
1108
+ h2(tags$i(class = "fas fa-lightbulb", style = "margin-right:8px;"), "Results Interpretation"),
1109
+ p("Comprehensive interpretation of QTL and domestication analysis")
1110
+ ),
1111
+ fluidRow(
1112
+ column(12, div(class = "card", div(class = "card-header", "Analysis Summary"), div(class = "card-body", uiOutput("analysis_summary"))))
1113
+ ),
1114
+ fluidRow(
1115
+ column(6, div(class = "card", div(class = "card-header", "QTL Significance"), div(class = "card-body", uiOutput("qtl_interpretation")))),
1116
+ column(6, div(class = "card", div(class = "card-header", "Effect Sizes"), div(class = "card-body", uiOutput("effect_interpretation"))))
1117
+ ),
1118
+ fluidRow(
1119
+ column(12, div(class = "card", div(class = "card-header", "Epistasis"), div(class = "card-body", uiOutput("epistasis_interpretation"))))
1120
+ ),
1121
+ fluidRow(
1122
+ column(12, div(class = "card", div(class = "card-header", "Recommendations"), div(class = "card-body", uiOutput("recommendations"))))
1123
+ )
1124
  ),
1125
 
1126
  tabPanel("About", icon = icon("info-circle"),
1127
+ div(class = "main-header",
1128
+ h2(tags$i(class = "fas fa-info-circle", style = "margin-right:8px;"), "About QTL-Mapper AI"),
1129
+ p("QTL Mapping with Transformer-based AI Assistant")
1130
+ ),
1131
+ fluidRow(
1132
+ column(8, offset = 2,
1133
+ div(class = "card",
1134
+ div(class = "card-body",
1135
+ h4(style = "color:#58a6ff; font-family: 'IBM Plex Mono'; margin-bottom:12px;", "Methodology"),
1136
+ tags$ul(style = "color: #8b949e; line-height: 2;",
1137
+ tags$li("Random Forest for QTL mapping with variable importance scoring"),
1138
+ tags$li("LOD scores derived from marker importance (-log10 scale)"),
1139
+ tags$li("Additive and dominance effects estimated via linear regression"),
1140
+ tags$li("Epistasis analysis: pairwise QTL x marker interactions"),
1141
+ tags$li("Domestication: Fst, nucleotide diversity (Pi), Tajima's D"),
1142
+ tags$li("AI Assistant powered by transformer models via Hugging Face Inference API")
1143
+ ),
1144
+ h4(style = "color:#58a6ff; font-family: 'IBM Plex Mono'; margin: 12px 0;", "AI Assistant Status"),
1145
+ p(style = "color: #8b949e; line-height: 1.7;",
1146
+ if (use_hf_api) {
1147
+ paste("✅ AI Assistant is connected to Hugging Face API using", hf_model)
1148
+ } else {
1149
+ "⚠️ AI Assistant is in rule-based mode. Set HF_API_TOKEN in Space secrets to enable transformer-based responses."
1150
+ }
1151
+ ),
1152
+ h4(style = "color:#58a6ff; font-family: 'IBM Plex Mono'; margin: 12px 0;", "Interpretation Thresholds"),
1153
+ tags$ul(style = "color: #8b949e; line-height: 2;",
1154
+ tags$li("LOD > 3: Suggestive QTL | LOD > 5: Significant QTL"),
1155
+ tags$li("Fst > 0.2: Strong population differentiation"),
1156
+ tags$li("Tajima's D < -2: Potential selective sweep"),
1157
+ tags$li("PVE > 10%: Major-effect QTL")
1158
+ )
1159
+ )
1160
+ )
1161
+ )
1162
+ )
1163
  )
1164
  ),
1165
 
1166
  tags$div(id = "chat-panel",
1167
+ tags$div(id = "chat-window",
1168
+ tags$div(id = "chat-header",
1169
+ tags$div(class = "chat-title",
1170
+ tags$div(class = "chat-avatar", "AI"),
1171
+ tags$div(
1172
+ tags$h4("QTL Analysis AI Assistant",
1173
+ tags$span(class = "model-badge",
1174
+ if(use_hf_api) gsub(".*/", "", hf_model) else "rules")
1175
+ ),
1176
+ tags$p(id = "model_status",
1177
+ if(use_hf_api) paste("🤖 AI mode -", gsub(".*/", "", hf_model)) else "📝 Rule-based mode",
1178
+ class = if(use_hf_api) "ai-mode" else "rule-mode"
1179
+ )
1180
+ )
1181
+ ),
1182
+ tags$button(id = "chat-close-btn", onclick = "document.getElementById('chat-window').classList.remove('open');",
1183
+ tags$i(class = "fas fa-times")
1184
+ )
1185
+ ),
1186
+
1187
+ tags$div(class = "quick-questions",
1188
+ tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q', 'What is PVE?', {priority: 'event'});", "PVE meaning"),
1189
+ tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q', 'What are my top QTLs?', {priority: 'event'});", "Top QTLs"),
1190
+ tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q', 'Why is my R² negative?', {priority: 'event'});", "Negative R²"),
1191
+ tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q', 'What should I do next?', {priority: 'event'});", "Next steps")
1192
+ ),
1193
+
1194
+ tags$div(id = "chat_messages",
1195
+ uiOutput("chat_display")
1196
+ ),
1197
+
1198
+ tags$div(id = "chat-footer",
1199
+ tags$textarea(
1200
+ id = "chat_input",
1201
+ placeholder = "Ask about your results... (Enter to send)",
1202
+ rows = "2"
1203
+ ),
1204
+ tags$div(class = "chat-actions",
1205
+ actionButton("send_chat", "Send", icon = icon("paper-plane"), class = "btn-primary"),
1206
+ actionButton("clear_chat", "Clear", icon = icon("trash-alt"), class = "btn-danger")
1207
+ )
1208
+ )
1209
+ ),
1210
+
1211
+ tags$button(id = "chat-toggle-btn",
1212
+ onclick = "document.getElementById('chat-window').classList.toggle('open');",
1213
+ tags$i(class = "fas fa-robot")
1214
+ )
1215
  )
1216
  )
1217
 
 
1330
 
1331
  message_elements <- lapply(messages, function(msg) {
1332
  div(class = paste("chat-msg", msg$role),
1333
+ div(class = "chat-bubble",
1334
+ HTML(gsub("\n", "<br>", htmltools::htmlEscape(msg$content)))
1335
+ ),
1336
+ div(class = "chat-meta", msg$time)
1337
  )
1338
  })
1339
 
1340
  if (values$is_typing) {
1341
  message_elements <- c(message_elements, list(
1342
  div(class = "chat-msg assistant",
1343
+ div(class = "typing-indicator",
1344
+ div(class = "typing-dot"), div(class = "typing-dot"), div(class = "typing-dot")
1345
+ )
1346
  )
1347
  ))
1348
  }
 
1408
 
1409
  values$phenotype_data <- phenotype_data
1410
  updateSelectInput(session, "phenotype_column",
1411
+ choices = colnames(phenotype_data),
1412
+ selected = colnames(phenotype_data)[1])
1413
 
1414
  showNotification("Phenotype data loaded", type = "message")
1415
  add_message("assistant", paste0("✅ Loaded ", ncol(phenotype_data), " traits, ", nrow(phenotype_data), " samples"))
 
1521
  geno_means <- tapply(pheno, geno, mean, na.rm = TRUE)
1522
  het_mean <- geno_means[as.character(sort(unique(geno))[2])]
1523
  midparent <- (geno_means[as.character(sort(unique(geno))[1])] +
1524
+ geno_means[as.character(sort(unique(geno))[3])]) / 2
1525
  dominance_effect <- het_mean - midparent
1526
  }
1527
 
 
1814
 
1815
  tryCatch({
1816
  common_markers <- intersect(colnames(values$test_genotype_data),
1817
+ colnames(values$genotype_data))
1818
 
1819
  if (length(common_markers) == 0) {
1820
  showNotification("No common markers", type = "error")
 
2086
 
2087
  if ("Message" %in% colnames(values$qtl_effects_train)) {
2088
  return(datatable(data.frame(Status = values$qtl_effects_train$Message[1]),
2089
+ options = list(dom = 't')))
2090
  }
2091
 
2092
  display_cols <- intersect(
 
2106
 
2107
  if ("Message" %in% colnames(values$epistasis_sig)) {
2108
  return(datatable(data.frame(Status = values$epistasis_sig$Message[1]),
2109
+ options = list(dom = 't')))
2110
  }
2111
 
2112
  datatable(
 
2122
 
2123
  if ("Message" %in% colnames(values$selection_metrics)) {
2124
  return(datatable(data.frame(Status = values$selection_metrics$Message[1]),
2125
+ options = list(dom = 't')))
2126
  }
2127
 
2128
  df <- values$selection_metrics
 
2172
  range_pos <- max_pos - min_pos
2173
 
2174
  div(class = "chromosome-container",
2175
+ div(class = "chromosome-title", paste("Chromosome", chr)),
2176
+ div(class = "chromosome",
2177
+ lapply(1:nrow(chr_markers), function(i) {
2178
+ marker <- chr_markers[i, ]
2179
+ left <- if (range_pos > 0) ((marker$Position - min_pos) / range_pos) * 100
2180
+ else (i / nrow(chr_markers)) * 100
2181
+
2182
+ marker_class <- "chromosome-marker"
2183
+ if (marker$Marker %in% chr_qtls$Marker) {
2184
+ marker_class <- paste(marker_class, "significant")
2185
+ } else if (!is.null(sel_markers) && marker$Marker %in% sel_markers$Marker) {
2186
+ marker_class <- paste(marker_class, "selection")
2187
+ } else if (marker$Marker %in% c(chr_qtls$Low_Flank, chr_qtls$High_Flank)) {
2188
+ marker_class <- paste(marker_class, "flanking")
2189
+ }
2190
+
2191
+ div(class = marker_class, style = paste0("left: ", left, "%;"))
2192
+ })
2193
+ ),
2194
+ div(class = "chromosome-legend",
2195
+ span(paste(format(min_pos, big.mark = ","), "bp")),
2196
+ span(paste(format(max_pos, big.mark = ","), "bp"))
2197
+ )
2198
  )
2199
  })
2200
  )
 
2229
  val_r2 <- if (has_perf) round(values$performance_metrics$Value[values$performance_metrics$Metric == "R² (Validation)"], 3) else "N/A"
2230
 
2231
  div(class = "interpretation-section",
2232
+ tags$h5("Analysis Summary"),
2233
+ tags$p(paste(
2234
+ "Found", n_qtl, "QTLs above LOD", input$lod_threshold,
2235
+ if (has_perf) paste0("(validation R² = ", val_r2, ")"),
2236
+ if (has_epi) paste0("with", n_epi, "epistatic interactions"),
2237
+ if (has_sel) paste0("and", n_sel, "selection signatures.")
2238
+ ))
2239
  )
2240
  })
2241
 
2242
  output$qtl_interpretation <- renderUI({
2243
  if (is.null(values$qtl_effects_train) || "Message" %in% colnames(values$qtl_effects_train)) {
2244
  return(div(class = "interpretation-section",
2245
+ tags$h5("QTL Significance"),
2246
+ tags$p("No significant QTLs detected.")
2247
  ))
2248
  }
2249
 
2250
  top_qtl <- values$qtl_effects_train[which.max(values$qtl_effects_train$LOD), ]
2251
 
2252
  div(class = "interpretation-section",
2253
+ tags$h5("QTL Significance"),
2254
+ tags$p(paste(
2255
+ "Top QTL:", top_qtl$Marker, "(Chr", top_qtl$Chromosome,
2256
+ ") with LOD =", round(top_qtl$LOD, 2)
2257
+ ))
2258
  )
2259
  })
2260
 
2261
  output$effect_interpretation <- renderUI({
2262
  if (is.null(values$qtl_effects_train) || "Message" %in% colnames(values$qtl_effects_train)) {
2263
  return(div(class = "interpretation-section",
2264
+ tags$h5("Effect Sizes"),
2265
+ tags$p("No QTL effects to interpret.")
2266
  ))
2267
  }
2268
 
2269
  top_pve <- values$qtl_effects_train[which.max(values$qtl_effects_train$PVE_Percent), ]
2270
 
2271
  div(class = "interpretation-section",
2272
+ tags$h5("Effect Sizes"),
2273
+ tags$p(paste(
2274
+ "Largest effect:", top_pve$Marker, "explains",
2275
+ round(top_pve$PVE_Percent, 1), "% of variance"
2276
+ ))
2277
  )
2278
  })
2279
 
2280
  output$epistasis_interpretation <- renderUI({
2281
  if (is.null(values$epistasis_sig) || "Message" %in% colnames(values$epistasis_sig) || nrow(values$epistasis_sig) == 0) {
2282
  return(div(class = "interpretation-section",
2283
+ tags$h5("Epistasis"),
2284
+ tags$p("No significant epistatic interactions detected.")
2285
  ))
2286
  }
2287
 
 
2289
  top_epi <- values$epistasis_sig[which.min(values$epistasis_sig$Interaction_p), ]
2290
 
2291
  div(class = "interpretation-section",
2292
+ tags$h5("Epistasis"),
2293
+ tags$p(paste(
2294
+ "Detected", n_epi, "interactions. Strongest:",
2295
+ top_epi$QTL1, "×", top_epi$QTL2,
2296
+ "(p =", format.pval(top_epi$Interaction_p), ")"
2297
+ ))
2298
  )
2299
  })
2300
 
 
2316
  }
2317
 
2318
  div(class = "interpretation-section",
2319
+ tags$h5("Recommendations"),
2320
+ tags$ul(lapply(recs, tags$li), style = "color: #8b949e;")
2321
  )
2322
  })
2323
 
 
2352
  }
2353
 
2354
  # ============================================================
2355
+ # RUN APP
2356
  # ============================================================
2357
 
2358
  shinyApp(ui = ui, server = server)