International Rice Research Institute commited on
Commit
1bfe887
·
verified ·
1 Parent(s): e31f4d2

Update app.R

Browse files
Files changed (1) hide show
  1. app.R +374 -70
app.R CHANGED
@@ -8,8 +8,10 @@ library(emmeans)
8
  library(plotly)
9
  library(shinyWidgets)
10
  library(ggplot2)
 
 
11
 
12
- # UI with updated styling, now including Heritability and Genotype Rankings
13
  ui <- fluidPage(
14
  useShinyjs(),
15
  tags$head(
@@ -29,20 +31,17 @@ ui <- fluidPage(
29
  --background: #FFFFFF; /* White background */
30
  --card-bg: #FFFFFF; /* White for cards */
31
  }
32
-
33
  body {
34
  font-family: 'Poppins', sans-serif;
35
  background: var(--background);
36
  color: var(--dark);
37
  overflow-x: hidden;
38
  }
39
-
40
  .container-fluid {
41
  max-width: 1600px;
42
  padding: 2.5rem;
43
  margin: 0 auto;
44
  }
45
-
46
  .section {
47
  margin-bottom: 30px;
48
  background: var(--card-bg);
@@ -51,7 +50,6 @@ ui <- fluidPage(
51
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
52
  border: 1px solid rgba(30, 58, 138, 0.2);
53
  }
54
-
55
  h1, h2, h3 {
56
  color: var(--primary);
57
  border-bottom: 2px solid var(--secondary);
@@ -59,7 +57,6 @@ ui <- fluidPage(
59
  margin-bottom: 20px;
60
  font-weight: 700;
61
  }
62
-
63
  .chart-container {
64
  position: relative;
65
  margin-bottom: 20px;
@@ -70,7 +67,6 @@ ui <- fluidPage(
70
  border: 1px solid rgba(30, 58, 138, 0.2);
71
  min-height: 400px;
72
  }
73
-
74
  .insights {
75
  margin-top: 20px;
76
  padding: 20px;
@@ -79,7 +75,6 @@ ui <- fluidPage(
79
  border-left: 4px solid var(--secondary);
80
  font-size: 14px;
81
  }
82
-
83
  .upload-container {
84
  padding: 20px;
85
  text-align: center;
@@ -88,13 +83,11 @@ ui <- fluidPage(
88
  margin-bottom: 25px;
89
  background: #F9F9F9;
90
  }
91
-
92
  .upload-icon {
93
  font-size: 48px;
94
  color: var(--primary);
95
  margin-bottom: 15px;
96
  }
97
-
98
  .btn-primary {
99
  background: linear-gradient(135deg, var(--primary), var(--info));
100
  border: none;
@@ -105,14 +98,12 @@ ui <- fluidPage(
105
  transition: all 0.3s;
106
  box-shadow: 0 4px 8px rgba(0,0,0,0.1);
107
  }
108
-
109
  .btn-primary:hover {
110
  background: linear-gradient(135deg, var(--info), var(--primary));
111
  transform: translateY(-2px);
112
  box-shadow: 0 6px 12px rgba(30, 58, 138, 0.3);
113
  color: white;
114
  }
115
-
116
  .sidebar {
117
  background: var(--card-bg);
118
  color: var(--dark);
@@ -123,7 +114,6 @@ ui <- fluidPage(
123
  box-shadow: 5px 0 15px rgba(0,0,0,0.1);
124
  border-right: 1px solid var(--primary);
125
  }
126
-
127
  .sidebar-header {
128
  padding: 20px;
129
  background: linear-gradient(135deg, var(--primary), var(--info));
@@ -133,11 +123,9 @@ ui <- fluidPage(
133
  margin-bottom: 20px;
134
  color: white;
135
  }
136
-
137
  .sidebar-content {
138
  padding: 15px;
139
  }
140
-
141
  .nav-link {
142
  color: var(--dark);
143
  padding: 12px 15px;
@@ -148,20 +136,17 @@ ui <- fluidPage(
148
  transition: all 0.3s;
149
  background: #F5F5F5;
150
  }
151
-
152
  .nav-link:hover, .nav-link.active {
153
  color: white;
154
  background: linear-gradient(90deg, var(--primary), var(--info));
155
  transform: translateX(5px);
156
  box-shadow: 0 4px 8px rgba(30, 58, 138, 0.3);
157
  }
158
-
159
  .nav-link i {
160
  margin-right: 10px;
161
  width: 20px;
162
  text-align: center;
163
  }
164
-
165
  .main-content {
166
  margin-left: 280px;
167
  padding: 20px;
@@ -169,7 +154,6 @@ ui <- fluidPage(
169
  min-height: 100vh;
170
  background: var(--background);
171
  }
172
-
173
  .loader {
174
  border: 5px solid #F5F5F5;
175
  border-top: 5px solid var(--primary);
@@ -179,16 +163,13 @@ ui <- fluidPage(
179
  animation: spin 1s linear infinite;
180
  margin: 20px auto;
181
  }
182
-
183
  @keyframes spin {
184
  0% { transform: rotate(0deg); }
185
  100% { transform: rotate(360deg); }
186
  }
187
-
188
  .hidden {
189
  display: none;
190
  }
191
-
192
  table.dataTable {
193
  border-collapse: collapse;
194
  width: 100%;
@@ -197,7 +178,6 @@ ui <- fluidPage(
197
  border-radius: 8px;
198
  overflow: hidden;
199
  }
200
-
201
  th {
202
  background: linear-gradient(45deg, var(--primary), var(--info));
203
  color: white;
@@ -205,22 +185,18 @@ ui <- fluidPage(
205
  font-weight: 700;
206
  text-transform: uppercase;
207
  }
208
-
209
  td {
210
  padding: 1.2rem;
211
  border-bottom: 1px solid #F0F0F0;
212
  transition: background 0.3s;
213
  color: var(--dark);
214
  }
215
-
216
  tr:hover {
217
  background: #F5F5F5;
218
  }
219
-
220
  .dataTables_wrapper {
221
  color: var(--dark);
222
  }
223
-
224
  .status-card {
225
  background: var(--card-bg);
226
  padding: 20px;
@@ -230,30 +206,25 @@ ui <- fluidPage(
230
  border: 1px solid rgba(30, 58, 138, 0.2);
231
  margin-bottom: 15px;
232
  }
233
-
234
  .status-card i {
235
  font-size: 2rem;
236
  color: var(--primary);
237
  margin-bottom: 10px;
238
  }
239
-
240
  .status-card h4 {
241
  color: var(--primary);
242
  font-size: 1.5rem;
243
  margin: 5px 0;
244
  }
245
-
246
  .status-card p {
247
  color: var(--dark);
248
  margin: 0;
249
  }
250
-
251
  .plotly-title {
252
  font-size: 18px;
253
  font-weight: bold;
254
  color: var(--primary);
255
  }
256
-
257
  .plotly-annotation {
258
  font-size: 14px;
259
  color: var(--dark);
@@ -285,12 +256,16 @@ ui <- fluidPage(
285
  tags$a(class = "nav-link", `data-toggle` = "pill", href = "#lme4-heritability", role = "tab",
286
  icon("calculator", class = "fas"), "🧬 Heritability"),
287
  tags$a(class = "nav-link", `data-toggle` = "pill", href = "#lme4-rankings", role = "tab",
288
- icon("trophy", class = "fas"), "🏆 Genotype Rankings")
 
 
 
 
289
  ),
290
  hr(style = "border-color: rgba(255,255,255,0.1);"),
291
  div(
292
  style = "padding: 15px; color: var(--light); font-size: 12px; text-align: center;",
293
- p("LME4 Analysis Dashboard v1.2"),
294
  p("© 2023 Statistical Genetics Lab")
295
  )
296
  )
@@ -356,8 +331,8 @@ ui <- fluidPage(
356
  div(
357
  class = "insights",
358
  h4("💡 Interpretation & Insights"),
359
- p("Descriptive statistics provide an overview of central tendency, variability, and range for each trait. Coefficient of Variation (CV) indicates relative variability; CV < 10% suggests low variability (high precision), 10-20% moderate, >20% high (potential environmental influence or measurement error). High CV traits may require more replicates."),
360
- p(HTML("<strong>Automated Insight:</strong> Traits with high SD relative to mean may benefit from genotype selection focusing on stability."))
361
  )
362
  ),
363
  div(
@@ -379,8 +354,8 @@ ui <- fluidPage(
379
  div(
380
  class = "insights",
381
  h4("💡 Interpretation & Insights"),
382
- p("The G×E interaction plot shows genotype performance across environments. Stable genotypes have consistent values (parallel lines), while environment-specific genotypes vary (crossing lines). Use for selecting broadly adapted (stable) or specific (high in target env) genotypes."),
383
- p(HTML("<strong>Automated Insight:</strong> Genotypes with low slope variation indicate stability; ideal for multi-environment breeding programs."))
384
  )
385
  ),
386
  div(
@@ -402,8 +377,8 @@ ui <- fluidPage(
402
  div(
403
  class = "insights",
404
  h4("💡 Interpretation & Insights"),
405
- p("Correlations reveal trait synergies or trade-offs. Positive correlations (r > 0.5) suggest traits improve together; negative (r < -0.5) indicate trade-offs (e.g., yield vs. disease resistance)."),
406
- p(HTML("<strong>Automated Insight:</strong> Strong positive correlations (|r| > 0.7) allow indirect selection; e.g., select for one trait to improve another."))
407
  )
408
  ),
409
  div(
@@ -424,8 +399,8 @@ ui <- fluidPage(
424
  div(
425
  class = "insights",
426
  h4("💡 Interpretation & Insights"),
427
- p("Broad-sense heritability (H²) indicates the proportion of phenotypic variance attributable to genotypic variance (including G×E). H² > 0.6 suggests high heritability (effective for selection), 0.3-0.6 moderate, <0.3 low (environment dominates)."),
428
- p(HTML("<strong>Automated Insight:</strong> Traits with high H² are prime targets for genetic improvement; low H² traits may need environmental optimization or more precise phenotyping."))
429
  )
430
  ),
431
  div(
@@ -448,7 +423,7 @@ ui <- fluidPage(
448
  class = "insights",
449
  h4("💡 Interpretation & Insights"),
450
  p("Rankings are based on average predicted performance across environments. Top-ranked genotypes are overall best performers."),
451
- p(HTML("<strong>Automated Insight:</strong> Consistent top ranks across traits indicate superior multi-trait genotypes; use for advancing to next breeding cycle."))
452
  )
453
  ),
454
  div(
@@ -457,6 +432,52 @@ ui <- fluidPage(
457
  h4("📤 Upload data to see genotype rankings", style = "color: var(--light);")
458
  )
459
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
460
  )
461
  )
462
  )
@@ -470,13 +491,16 @@ server <- function(input, output, session) {
470
  data = NULL,
471
  traits = NULL,
472
  trait = NULL,
473
- lme4_models = NULL,
 
474
  blues_all = NULL,
475
  cor_matrix = NULL,
476
  cor_table = NULL,
477
  descriptives = NULL,
478
  heritability = NULL,
479
  rankings = NULL,
 
 
480
  debug_log = NULL
481
  )
482
 
@@ -497,7 +521,7 @@ server <- function(input, output, session) {
497
  message("LME4: Reading Excel file: ", path)
498
  tryCatch({
499
  data <- read_excel(path)
500
- colnames(data) <- make.names(colnames(data), unique = TRUE) # Ensure unique column names
501
 
502
  required_cols <- c("Genotype", "Block", "Row", "Column", "Rep", "Environment")
503
  missing_cols <- setdiff(required_cols, names(data))
@@ -524,16 +548,20 @@ server <- function(input, output, session) {
524
  n_genotypes <- length(unique(data$Genotype))
525
  n_environments <- length(unique(data$Environment))
526
  if (n_genotypes < 3) {
527
- stop("Insufficient genotypes (", n_genotypes, ") for LME4 analysis; need at least 3")
528
  }
529
  if (n_environments < 2) {
530
- stop("Insufficient environments (", n_environments, ") for LME4 analysis; need at least 2")
531
  }
532
 
533
  combo_counts <- table(data$Environment, data$Genotype)
534
  zero_combinations <- sum(combo_counts == 0)
535
  if (zero_combinations > 0) {
536
  message("LME4: Warning: ", zero_combinations, " Environment:Genotype combinations have no data")
 
 
 
 
537
  }
538
  if (zero_combinations > (nrow(combo_counts) * ncol(combo_counts) * 0.5)) {
539
  showNotification("Warning: Over 50% of Environment:Genotype combinations are missing", type = "warning", duration = 10)
@@ -565,14 +593,22 @@ server <- function(input, output, session) {
565
  lme4_fit_fixed_model <- function(data, trait) {
566
  message("LME4: Fitting fixed model for ", trait)
567
  formula_str <- if (input$lme4_include_interaction) {
568
- paste(trait, "~ Environment + Genotype + Environment:Genotype + (1|Block) + (1|Row) + (1|Column) + (1|Rep)")
569
  } else {
570
- paste(trait, "~ Environment + Genotype + (1|Block) + (1|Row) + (1|Column) + (1|Rep)")
571
  }
572
  formula <- as.formula(formula_str)
573
  tryCatch({
574
  model <- lmer(formula, data = data, na.action = na.omit,
575
- control = lmerControl(check.rankX = "warn+drop.cols", optimizer = "bobyqa"))
 
 
 
 
 
 
 
 
576
  message("LME4: Successfully fitted fixed model for ", trait)
577
  return(model)
578
  }, error = function(e) {
@@ -586,14 +622,22 @@ server <- function(input, output, session) {
586
  lme4_fit_random_model <- function(data, trait) {
587
  message("LME4: Fitting random model for ", trait)
588
  formula_str <- if (input$lme4_include_interaction) {
589
- paste(trait, "~ Environment + (1|Genotype) + (1|Environment:Genotype) + (1|Block) + (1|Row) + (1|Column) + (1|Rep)")
590
  } else {
591
- paste(trait, "~ Environment + (1|Genotype) + (1|Block) + (1|Row) + (1|Column) + (1|Rep)")
592
  }
593
  formula <- as.formula(formula_str)
594
  tryCatch({
595
  model <- lmer(formula, data = data, na.action = na.omit,
596
- control = lmerControl(check.rankX = "warn+drop.cols", optimizer = "bobyqa"))
 
 
 
 
 
 
 
 
597
  message("LME4: Successfully fitted random model for ", trait)
598
  return(model)
599
  }, error = function(e) {
@@ -607,23 +651,23 @@ server <- function(input, output, session) {
607
  lme4_get_blue <- function(model, trait) {
608
  if (is.null(model)) {
609
  message("LME4: No fixed model for ", trait)
610
- return(data.frame(Trait = trait, Genotype = NA, Environment = NA, predicted.value = NA, SE = NA, Error = "No model fitted"))
611
  }
612
  tryCatch({
613
- emm_options(pbkrtest.limit = 5000, lmerTest.limit = 5000)
614
  blues <- emmeans(model, ~ Genotype:Environment)
615
  blues_df <- as.data.frame(blues) %>%
616
  rename(predicted.value = emmean) %>%
617
  mutate(Trait = trait) %>%
618
- select(Trait, Genotype, Environment, predicted.value, SE = SE) %>%
619
  filter(!is.na(predicted.value))
620
  if (nrow(blues_df) == 0) {
621
- return(data.frame(Trait = trait, Genotype = NA, Environment = NA, predicted.value = NA, SE = NA, Error = "No valid BLUEs"))
622
  }
623
  return(blues_df)
624
  }, error = function(e) {
625
  message("LME4: Error in BLUEs for ", trait, ": ", e$message)
626
- return(data.frame(Trait = trait, Genotype = NA, Environment = NA, predicted.value = NA, SE = NA, Error = e$message))
627
  })
628
  }
629
 
@@ -631,12 +675,12 @@ server <- function(input, output, session) {
631
  lme4_get_heritability <- function(model, trait) {
632
  if (is.null(model)) {
633
  message("LME4: No random model for ", trait)
634
- return(data.frame(Trait = trait, Heritability = NA, VarG = NA, VarGE = NA, VarRes = NA, Error = "No model fitted"))
635
  }
636
  tryCatch({
637
  vc <- VarCorr(model)
638
- sigma_g <- as.numeric(vc$Genotype)
639
- sigma_ge <- if (input$lme4_include_interaction && "Environment:Genotype" %in% names(vc)) as.numeric(vc$`Environment:Genotype`) else 0
640
  sigma_res <- sigma(model)^2
641
  var_g_total <- sigma_g + sigma_ge
642
  total_var <- var_g_total + sigma_res
@@ -645,7 +689,66 @@ server <- function(input, output, session) {
645
  VarGE = round(sigma_ge, 3), VarRes = round(sigma_res, 3))
646
  }, error = function(e) {
647
  message("LME4: Error in heritability for ", trait, ": ", e$message)
648
- return(data.frame(Trait = trait, Heritability = NA, VarG = NA, VarGE = NA, VarRes = NA, Error = e$message))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
649
  })
650
  }
651
 
@@ -684,9 +787,10 @@ server <- function(input, output, session) {
684
  random_models <- list()
685
  blues_list <- list()
686
  herit_list <- list()
 
687
 
688
  n_traits <- length(rv_lme4$traits)
689
- total_steps <- n_traits * 3 + 2 # fixed model, random model, blues per trait + correlations + descriptives
690
  step_increment <- 1 / total_steps
691
 
692
  for (trait in rv_lme4$traits) {
@@ -704,6 +808,9 @@ server <- function(input, output, session) {
704
  debug_log <- c(debug_log, paste("Trait:", trait, "- Random model:", ifelse(is.null(random_model), "Failed", "Success")))
705
 
706
  herit_list[[trait]] <- lme4_get_heritability(random_model, trait)
 
 
 
707
  }
708
 
709
  incProgress(step_increment, detail = "Calculating correlations")
@@ -746,7 +853,7 @@ server <- function(input, output, session) {
746
  debug_log <- c(debug_log, "Descriptives: Success")
747
 
748
  incProgress(step_increment, detail = "Calculating heritability")
749
- rv_lme4$heritability <- bind_rows(herit_list) %>% select(-Error)
750
  debug_log <- c(debug_log, "Heritability: Success")
751
 
752
  incProgress(step_increment, detail = "Calculating rankings")
@@ -760,16 +867,26 @@ server <- function(input, output, session) {
760
  rv_lme4$rankings <- rankings
761
  debug_log <- c(debug_log, "Rankings: Success")
762
 
763
- rv_lme4$lme4_models <- fixed_models # Keep fixed models for reference
 
 
 
 
 
 
 
 
 
764
  rv_lme4$debug_log <- debug_log
765
 
766
- # Show contents for all tabs
767
  shinyjs::hide(c("lme4_blues_placeholder", "lme4_correlations_placeholder",
768
  "lme4_descriptives_placeholder", "lme4_heritability_placeholder",
769
- "lme4_rankings_placeholder"))
 
770
  shinyjs::show(c("lme4_blues_content", "lme4_correlations_content",
771
  "lme4_descriptives_content", "lme4_heritability_content",
772
- "lme4_rankings_content"))
 
773
 
774
  output$lme4_debug_log <- renderPrint({
775
  cat(paste(rv_lme4$debug_log, collapse = "\n"))
@@ -796,6 +913,11 @@ server <- function(input, output, session) {
796
  rv_lme4$rankings %>% filter(Trait == rv_lme4$trait)
797
  })
798
 
 
 
 
 
 
799
  # LME4: Plot outputs
800
  output$lme4_blues_plot <- renderPlotly({
801
  req(lme4_filtered_blues())
@@ -891,7 +1013,7 @@ server <- function(input, output, session) {
891
 
892
  output$lme4_rankings_plot <- renderPlotly({
893
  req(lme4_filtered_rankings())
894
- data <- lme4_filtered_rankings() %>% head(10) # Top 10 for plot
895
  if (nrow(data) == 0) {
896
  return(plot_ly() %>%
897
  layout(
@@ -917,11 +1039,71 @@ server <- function(input, output, session) {
917
  )
918
  })
919
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
920
  # LME4: Table outputs
921
  output$lme4_blues_table <- renderDT({
922
  req(lme4_filtered_blues())
 
 
 
 
923
  datatable(
924
- lme4_filtered_blues() %>% select(-Error),
925
  extensions = 'Buttons',
926
  options = list(
927
  scrollX = TRUE,
@@ -997,6 +1179,128 @@ server <- function(input, output, session) {
997
  caption = paste("Genotype Rankings for", rv_lme4$trait)
998
  ) %>% formatRound(columns = "Mean", digits = 3)
999
  })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1000
  }
1001
 
1002
  # Run the Shiny app
 
8
  library(plotly)
9
  library(shinyWidgets)
10
  library(ggplot2)
11
+ library(pbkrtest)
12
+ library(lmerTest)
13
 
14
+ # UI with updated styling, including Stability and PCA tabs
15
  ui <- fluidPage(
16
  useShinyjs(),
17
  tags$head(
 
31
  --background: #FFFFFF; /* White background */
32
  --card-bg: #FFFFFF; /* White for cards */
33
  }
 
34
  body {
35
  font-family: 'Poppins', sans-serif;
36
  background: var(--background);
37
  color: var(--dark);
38
  overflow-x: hidden;
39
  }
 
40
  .container-fluid {
41
  max-width: 1600px;
42
  padding: 2.5rem;
43
  margin: 0 auto;
44
  }
 
45
  .section {
46
  margin-bottom: 30px;
47
  background: var(--card-bg);
 
50
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
51
  border: 1px solid rgba(30, 58, 138, 0.2);
52
  }
 
53
  h1, h2, h3 {
54
  color: var(--primary);
55
  border-bottom: 2px solid var(--secondary);
 
57
  margin-bottom: 20px;
58
  font-weight: 700;
59
  }
 
60
  .chart-container {
61
  position: relative;
62
  margin-bottom: 20px;
 
67
  border: 1px solid rgba(30, 58, 138, 0.2);
68
  min-height: 400px;
69
  }
 
70
  .insights {
71
  margin-top: 20px;
72
  padding: 20px;
 
75
  border-left: 4px solid var(--secondary);
76
  font-size: 14px;
77
  }
 
78
  .upload-container {
79
  padding: 20px;
80
  text-align: center;
 
83
  margin-bottom: 25px;
84
  background: #F9F9F9;
85
  }
 
86
  .upload-icon {
87
  font-size: 48px;
88
  color: var(--primary);
89
  margin-bottom: 15px;
90
  }
 
91
  .btn-primary {
92
  background: linear-gradient(135deg, var(--primary), var(--info));
93
  border: none;
 
98
  transition: all 0.3s;
99
  box-shadow: 0 4px 8px rgba(0,0,0,0.1);
100
  }
 
101
  .btn-primary:hover {
102
  background: linear-gradient(135deg, var(--info), var(--primary));
103
  transform: translateY(-2px);
104
  box-shadow: 0 6px 12px rgba(30, 58, 138, 0.3);
105
  color: white;
106
  }
 
107
  .sidebar {
108
  background: var(--card-bg);
109
  color: var(--dark);
 
114
  box-shadow: 5px 0 15px rgba(0,0,0,0.1);
115
  border-right: 1px solid var(--primary);
116
  }
 
117
  .sidebar-header {
118
  padding: 20px;
119
  background: linear-gradient(135deg, var(--primary), var(--info));
 
123
  margin-bottom: 20px;
124
  color: white;
125
  }
 
126
  .sidebar-content {
127
  padding: 15px;
128
  }
 
129
  .nav-link {
130
  color: var(--dark);
131
  padding: 12px 15px;
 
136
  transition: all 0.3s;
137
  background: #F5F5F5;
138
  }
 
139
  .nav-link:hover, .nav-link.active {
140
  color: white;
141
  background: linear-gradient(90deg, var(--primary), var(--info));
142
  transform: translateX(5px);
143
  box-shadow: 0 4px 8px rgba(30, 58, 138, 0.3);
144
  }
 
145
  .nav-link i {
146
  margin-right: 10px;
147
  width: 20px;
148
  text-align: center;
149
  }
 
150
  .main-content {
151
  margin-left: 280px;
152
  padding: 20px;
 
154
  min-height: 100vh;
155
  background: var(--background);
156
  }
 
157
  .loader {
158
  border: 5px solid #F5F5F5;
159
  border-top: 5px solid var(--primary);
 
163
  animation: spin 1s linear infinite;
164
  margin: 20px auto;
165
  }
 
166
  @keyframes spin {
167
  0% { transform: rotate(0deg); }
168
  100% { transform: rotate(360deg); }
169
  }
 
170
  .hidden {
171
  display: none;
172
  }
 
173
  table.dataTable {
174
  border-collapse: collapse;
175
  width: 100%;
 
178
  border-radius: 8px;
179
  overflow: hidden;
180
  }
 
181
  th {
182
  background: linear-gradient(45deg, var(--primary), var(--info));
183
  color: white;
 
185
  font-weight: 700;
186
  text-transform: uppercase;
187
  }
 
188
  td {
189
  padding: 1.2rem;
190
  border-bottom: 1px solid #F0F0F0;
191
  transition: background 0.3s;
192
  color: var(--dark);
193
  }
 
194
  tr:hover {
195
  background: #F5F5F5;
196
  }
 
197
  .dataTables_wrapper {
198
  color: var(--dark);
199
  }
 
200
  .status-card {
201
  background: var(--card-bg);
202
  padding: 20px;
 
206
  border: 1px solid rgba(30, 58, 138, 0.2);
207
  margin-bottom: 15px;
208
  }
 
209
  .status-card i {
210
  font-size: 2rem;
211
  color: var(--primary);
212
  margin-bottom: 10px;
213
  }
 
214
  .status-card h4 {
215
  color: var(--primary);
216
  font-size: 1.5rem;
217
  margin: 5px 0;
218
  }
 
219
  .status-card p {
220
  color: var(--dark);
221
  margin: 0;
222
  }
 
223
  .plotly-title {
224
  font-size: 18px;
225
  font-weight: bold;
226
  color: var(--primary);
227
  }
 
228
  .plotly-annotation {
229
  font-size: 14px;
230
  color: var(--dark);
 
256
  tags$a(class = "nav-link", `data-toggle` = "pill", href = "#lme4-heritability", role = "tab",
257
  icon("calculator", class = "fas"), "🧬 Heritability"),
258
  tags$a(class = "nav-link", `data-toggle` = "pill", href = "#lme4-rankings", role = "tab",
259
+ icon("trophy", class = "fas"), "🏆 Genotype Rankings"),
260
+ tags$a(class = "nav-link", `data-toggle` = "pill", href = "#lme4-stability", role = "tab",
261
+ icon("balance-scale", class = "fas"), "⚖️ Stability Analysis"),
262
+ tags$a(class = "nav-link", `data-toggle` = "pill", href = "#lme4-pca", role = "tab",
263
+ icon("chart-scatter", class = "fas"), "🔍 PCA Analysis")
264
  ),
265
  hr(style = "border-color: rgba(255,255,255,0.1);"),
266
  div(
267
  style = "padding: 15px; color: var(--light); font-size: 12px; text-align: center;",
268
+ p("LME4 Analysis Dashboard v1.3"),
269
  p("© 2023 Statistical Genetics Lab")
270
  )
271
  )
 
331
  div(
332
  class = "insights",
333
  h4("💡 Interpretation & Insights"),
334
+ p("Descriptive statistics summarize central tendency, variability, and range for each trait. Coefficient of Variation (CV) indicates relative variability; CV < 10% suggests low variability (high precision), 10-20% moderate, >20% high (potential environmental influence or measurement error)."),
335
+ uiOutput("lme4_descriptives_insights")
336
  )
337
  ),
338
  div(
 
354
  div(
355
  class = "insights",
356
  h4("💡 Interpretation & Insights"),
357
+ p("The G×E interaction plot shows genotype performance across environments. Stable genotypes have consistent values (parallel lines), while environment-specific genotypes vary (crossing lines)."),
358
+ uiOutput("lme4_blues_insights")
359
  )
360
  ),
361
  div(
 
377
  div(
378
  class = "insights",
379
  h4("💡 Interpretation & Insights"),
380
+ p("Correlations reveal trait synergies or trade-offs. Positive correlations (r > 0.5) suggest traits improve together; negative (r < -0.5) indicate trade-offs."),
381
+ uiOutput("lme4_correlations_insights")
382
  )
383
  ),
384
  div(
 
399
  div(
400
  class = "insights",
401
  h4("💡 Interpretation & Insights"),
402
+ p("Broad-sense heritability (H²) indicates the proportion of phenotypic variance attributable to genotypic variance. H² > 0.6 suggests high heritability (effective for selection), 0.3-0.6 moderate, <0.3 low (environment dominates)."),
403
+ uiOutput("lme4_heritability_insights")
404
  )
405
  ),
406
  div(
 
423
  class = "insights",
424
  h4("💡 Interpretation & Insights"),
425
  p("Rankings are based on average predicted performance across environments. Top-ranked genotypes are overall best performers."),
426
+ uiOutput("lme4_rankings_insights")
427
  )
428
  ),
429
  div(
 
432
  h4("📤 Upload data to see genotype rankings", style = "color: var(--light);")
433
  )
434
  )
435
+ ),
436
+ div(
437
+ class = "tab-pane fade", id = "lme4-stability", role = "tabpanel",
438
+ div(
439
+ class = "section",
440
+ h2("⚖️ Stability Analysis"),
441
+ div(
442
+ id = "lme4_stability_content",
443
+ div(class = "chart-container", plotlyOutput("lme4_stability_plot", height = "500px")),
444
+ div(class = "table-container", DTOutput("lme4_stability_table")),
445
+ div(
446
+ class = "insights",
447
+ h4("💡 Interpretation & Insights"),
448
+ p("Finlay-Wilkinson regression slopes measure genotype stability. Slopes ~1 indicate average stability, <1 high stability (less responsive to environment), >1 low stability (highly responsive)."),
449
+ uiOutput("lme4_stability_insights")
450
+ )
451
+ ),
452
+ div(
453
+ id = "lme4_stability_placeholder", class = "text-center",
454
+ icon("balance-scale", class = "fas", style = "font-size: 72px; color: var(--light); margin: 30px 0;"),
455
+ h4("📤 Upload data to see stability analysis", style = "color: var(--light);")
456
+ )
457
+ )
458
+ ),
459
+ div(
460
+ class = "tab-pane fade", id = "lme4-pca", role = "tabpanel",
461
+ div(
462
+ class = "section",
463
+ h2("🔍 PCA Analysis"),
464
+ div(
465
+ id = "lme4_pca_content",
466
+ div(class = "chart-container", plotlyOutput("lme4_pca_plot", height = "500px")),
467
+ div(class = "table-container", DTOutput("lme4_pca_table")),
468
+ div(
469
+ class = "insights",
470
+ h4("💡 Interpretation & Insights"),
471
+ p("PCA reduces multi-trait data to principal components. Genotypes close together are phenotypically similar. PC1 and PC2 explain the majority of variance; check loadings for trait contributions."),
472
+ uiOutput("lme4_pca_insights")
473
+ )
474
+ ),
475
+ div(
476
+ id = "lme4_pca_placeholder", class = "text-center",
477
+ icon("chart-scatter", class = "fas", style = "font-size: 72px; color: var(--light); margin: 30px 0;"),
478
+ h4("📤 Upload data to see PCA analysis", style = "color: var(--light);")
479
+ )
480
+ )
481
  )
482
  )
483
  )
 
491
  data = NULL,
492
  traits = NULL,
493
  trait = NULL,
494
+ fixed_models = NULL,
495
+ random_models = NULL,
496
  blues_all = NULL,
497
  cor_matrix = NULL,
498
  cor_table = NULL,
499
  descriptives = NULL,
500
  heritability = NULL,
501
  rankings = NULL,
502
+ stability = NULL,
503
+ pca = NULL,
504
  debug_log = NULL
505
  )
506
 
 
521
  message("LME4: Reading Excel file: ", path)
522
  tryCatch({
523
  data <- read_excel(path)
524
+ colnames(data) <- make.names(colnames(data), unique = TRUE)
525
 
526
  required_cols <- c("Genotype", "Block", "Row", "Column", "Rep", "Environment")
527
  missing_cols <- setdiff(required_cols, names(data))
 
548
  n_genotypes <- length(unique(data$Genotype))
549
  n_environments <- length(unique(data$Environment))
550
  if (n_genotypes < 3) {
551
+ stop("Insufficient genotypes (", n_genotypes, ") for analysis; need at least 3")
552
  }
553
  if (n_environments < 2) {
554
+ stop("Insufficient environments (", n_environments, ") for analysis; need at least 2")
555
  }
556
 
557
  combo_counts <- table(data$Environment, data$Genotype)
558
  zero_combinations <- sum(combo_counts == 0)
559
  if (zero_combinations > 0) {
560
  message("LME4: Warning: ", zero_combinations, " Environment:Genotype combinations have no data")
561
+ showNotification(
562
+ paste(zero_combinations, "Environment:Genotype combinations are missing. Consider checking data completeness or imputing missing values."),
563
+ type = "warning", duration = 10
564
+ )
565
  }
566
  if (zero_combinations > (nrow(combo_counts) * ncol(combo_counts) * 0.5)) {
567
  showNotification("Warning: Over 50% of Environment:Genotype combinations are missing", type = "warning", duration = 10)
 
593
  lme4_fit_fixed_model <- function(data, trait) {
594
  message("LME4: Fitting fixed model for ", trait)
595
  formula_str <- if (input$lme4_include_interaction) {
596
+ paste(trait, "~ Environment + Genotype + Environment:Genotype + (1|Block) + (1|Rep)")
597
  } else {
598
+ paste(trait, "~ Environment + Genotype + (1|Block) + (1|Rep)")
599
  }
600
  formula <- as.formula(formula_str)
601
  tryCatch({
602
  model <- lmer(formula, data = data, na.action = na.omit,
603
+ control = lmerControl(check.rankX = "warn+drop.cols", optimizer = "bobyqa", checkSingularity = TRUE))
604
+ if (isSingular(model)) {
605
+ message("LME4: Singular fit detected for ", trait, ". Simplifying model.")
606
+ showNotification(paste("Singular fit for", trait, ". Model simplified."), type = "warning", duration = 10)
607
+ formula_str <- paste(trait, "~ Environment + Genotype + (1|Rep)")
608
+ formula <- as.formula(formula_str)
609
+ model <- lmer(formula, data = data, na.action = na.omit,
610
+ control = lmerControl(check.rankX = "warn+drop.cols", optimizer = "bobyqa"))
611
+ }
612
  message("LME4: Successfully fitted fixed model for ", trait)
613
  return(model)
614
  }, error = function(e) {
 
622
  lme4_fit_random_model <- function(data, trait) {
623
  message("LME4: Fitting random model for ", trait)
624
  formula_str <- if (input$lme4_include_interaction) {
625
+ paste(trait, "~ Environment + (1|Genotype) + (1|Environment:Genotype) + (1|Block) + (1|Rep)")
626
  } else {
627
+ paste(trait, "~ Environment + (1|Genotype) + (1|Block) + (1|Rep)")
628
  }
629
  formula <- as.formula(formula_str)
630
  tryCatch({
631
  model <- lmer(formula, data = data, na.action = na.omit,
632
+ control = lmerControl(check.rankX = "warn+drop.cols", optimizer = "bobyqa", checkSingularity = TRUE))
633
+ if (isSingular(model)) {
634
+ message("LME4: Singular fit detected for ", trait, ". Simplifying model.")
635
+ showNotification(paste("Singular fit for", trait, ". Model simplified."), type = "warning", duration = 10)
636
+ formula_str <- paste(trait, "~ Environment + (1|Genotype) + (1|Rep)")
637
+ formula <- as.formula(formula_str)
638
+ model <- lmer(formula, data = data, na.action = na.omit,
639
+ control = lmerControl(check.rankX = "warn+drop.cols", optimizer = "bobyqa"))
640
+ }
641
  message("LME4: Successfully fitted random model for ", trait)
642
  return(model)
643
  }, error = function(e) {
 
651
  lme4_get_blue <- function(model, trait) {
652
  if (is.null(model)) {
653
  message("LME4: No fixed model for ", trait)
654
+ return(data.frame(Trait = trait, Genotype = NA, Environment = NA, predicted.value = NA, SE = NA))
655
  }
656
  tryCatch({
657
+ emm_options(pbkrtest.limit = 10000, lmerTest.limit = 10000)
658
  blues <- emmeans(model, ~ Genotype:Environment)
659
  blues_df <- as.data.frame(blues) %>%
660
  rename(predicted.value = emmean) %>%
661
  mutate(Trait = trait) %>%
662
+ select(Trait, Genotype, Environment, predicted.value, SE) %>%
663
  filter(!is.na(predicted.value))
664
  if (nrow(blues_df) == 0) {
665
+ return(data.frame(Trait = trait, Genotype = NA, Environment = NA, predicted.value = NA, SE = NA))
666
  }
667
  return(blues_df)
668
  }, error = function(e) {
669
  message("LME4: Error in BLUEs for ", trait, ": ", e$message)
670
+ return(data.frame(Trait = trait, Genotype = NA, Environment = NA, predicted.value = NA, SE = NA))
671
  })
672
  }
673
 
 
675
  lme4_get_heritability <- function(model, trait) {
676
  if (is.null(model)) {
677
  message("LME4: No random model for ", trait)
678
+ return(data.frame(Trait = trait, Heritability = NA, VarG = NA, VarGE = NA, VarRes = NA))
679
  }
680
  tryCatch({
681
  vc <- VarCorr(model)
682
+ sigma_g <- as.numeric(vc$Genotype[1])
683
+ sigma_ge <- if (input$lme4_include_interaction && "Environment:Genotype" %in% names(vc)) as.numeric(vc$`Environment:Genotype`[1]) else 0
684
  sigma_res <- sigma(model)^2
685
  var_g_total <- sigma_g + sigma_ge
686
  total_var <- var_g_total + sigma_res
 
689
  VarGE = round(sigma_ge, 3), VarRes = round(sigma_res, 3))
690
  }, error = function(e) {
691
  message("LME4: Error in heritability for ", trait, ": ", e$message)
692
+ return(data.frame(Trait = trait, Heritability = NA, VarG = NA, VarGE = NA, VarRes = NA))
693
+ })
694
+ }
695
+
696
+ # LME4: Finlay-Wilkinson stability analysis
697
+ lme4_get_stability <- function(blues, trait) {
698
+ tryCatch({
699
+ env_means <- blues %>%
700
+ group_by(Environment) %>%
701
+ summarise(Env_Mean = mean(predicted.value, na.rm = TRUE), .groups = "drop")
702
+
703
+ stability_data <- blues %>%
704
+ left_join(env_means, by = "Environment") %>%
705
+ group_by(Genotype) %>%
706
+ do({
707
+ model <- lm(predicted.value ~ Env_Mean, data = .)
708
+ slope <- coef(model)[2]
709
+ r_squared <- summary(model)$r.squared
710
+ data.frame(Slope = round(slope, 3), R_Squared = round(r_squared, 3))
711
+ }) %>%
712
+ mutate(Trait = trait) %>%
713
+ select(Trait, Genotype, Slope, R_Squared)
714
+
715
+ if (nrow(stability_data) == 0) {
716
+ return(data.frame(Trait = trait, Genotype = NA, Slope = NA, R_Squared = NA))
717
+ }
718
+ return(stability_data)
719
+ }, error = function(e) {
720
+ message("LME4: Error in stability analysis for ", trait, ": ", e$message)
721
+ return(data.frame(Trait = trait, Genotype = NA, Slope = NA, R_Squared = NA))
722
+ })
723
+ }
724
+
725
+ # LME4: PCA analysis
726
+ lme4_get_pca <- function(blues, traits) {
727
+ tryCatch({
728
+ wide_data <- blues %>%
729
+ select(Trait, Genotype, Environment, predicted.value) %>%
730
+ pivot_wider(names_from = Trait, values_from = predicted.value, values_fill = NA) %>%
731
+ na.omit()
732
+
733
+ if (nrow(wide_data) < 2 || ncol(wide_data) < length(traits) + 2) {
734
+ return(list(scores = data.frame(Genotype = NA, Environment = NA, PC1 = NA, PC2 = NA),
735
+ loadings = data.frame(Trait = NA, PC1 = NA, PC2 = NA)))
736
+ }
737
+
738
+ pca_data <- wide_data %>% select(all_of(traits))
739
+ pca_result <- prcomp(pca_data, scale. = TRUE)
740
+ scores <- as.data.frame(pca_result$x) %>%
741
+ mutate(Genotype = wide_data$Genotype, Environment = wide_data$Environment) %>%
742
+ select(Genotype, Environment, PC1, PC2)
743
+ loadings <- as.data.frame(pca_result$rotation) %>%
744
+ mutate(Trait = rownames(.)) %>%
745
+ select(Trait, PC1, PC2)
746
+ var_explained <- summary(pca_result)$importance[2, c("PC1", "PC2")] * 100
747
+ return(list(scores = scores, loadings = loadings, var_explained = var_explained))
748
+ }, error = function(e) {
749
+ message("LME4: Error in PCA analysis: ", e$message)
750
+ return(list(scores = data.frame(Genotype = NA, Environment = NA, PC1 = NA, PC2 = NA),
751
+ loadings = data.frame(Trait = NA, PC1 = NA, PC2 = NA)))
752
  })
753
  }
754
 
 
787
  random_models <- list()
788
  blues_list <- list()
789
  herit_list <- list()
790
+ stability_list <- list()
791
 
792
  n_traits <- length(rv_lme4$traits)
793
+ total_steps <- n_traits * 3 + 3 # fixed model, random model, stability, correlations, descriptives, pca
794
  step_increment <- 1 / total_steps
795
 
796
  for (trait in rv_lme4$traits) {
 
808
  debug_log <- c(debug_log, paste("Trait:", trait, "- Random model:", ifelse(is.null(random_model), "Failed", "Success")))
809
 
810
  herit_list[[trait]] <- lme4_get_heritability(random_model, trait)
811
+
812
+ incProgress(step_increment, detail = paste("Calculating stability for", trait))
813
+ stability_list[[trait]] <- lme4_get_stability(blues_list[[trait]], trait)
814
  }
815
 
816
  incProgress(step_increment, detail = "Calculating correlations")
 
853
  debug_log <- c(debug_log, "Descriptives: Success")
854
 
855
  incProgress(step_increment, detail = "Calculating heritability")
856
+ rv_lme4$heritability <- bind_rows(herit_list)
857
  debug_log <- c(debug_log, "Heritability: Success")
858
 
859
  incProgress(step_increment, detail = "Calculating rankings")
 
867
  rv_lme4$rankings <- rankings
868
  debug_log <- c(debug_log, "Rankings: Success")
869
 
870
+ incProgress(step_increment, detail = "Calculating stability")
871
+ rv_lme4$stability <- bind_rows(stability_list)
872
+ debug_log <- c(debug_log, "Stability: Success")
873
+
874
+ incProgress(step_increment, detail = "Calculating PCA")
875
+ rv_lme4$pca <- lme4_get_pca(rv_lme4$blues_all, rv_lme4$traits)
876
+ debug_log <- c(debug_log, "PCA: Success")
877
+
878
+ rv_lme4$fixed_models <- fixed_models
879
+ rv_lme4$random_models <- random_models
880
  rv_lme4$debug_log <- debug_log
881
 
 
882
  shinyjs::hide(c("lme4_blues_placeholder", "lme4_correlations_placeholder",
883
  "lme4_descriptives_placeholder", "lme4_heritability_placeholder",
884
+ "lme4_rankings_placeholder", "lme4_stability_placeholder",
885
+ "lme4_pca_placeholder"))
886
  shinyjs::show(c("lme4_blues_content", "lme4_correlations_content",
887
  "lme4_descriptives_content", "lme4_heritability_content",
888
+ "lme4_rankings_content", "lme4_stability_content",
889
+ "lme4_pca_content"))
890
 
891
  output$lme4_debug_log <- renderPrint({
892
  cat(paste(rv_lme4$debug_log, collapse = "\n"))
 
913
  rv_lme4$rankings %>% filter(Trait == rv_lme4$trait)
914
  })
915
 
916
+ lme4_filtered_stability <- reactive({
917
+ req(rv_lme4$stability, rv_lme4$trait)
918
+ rv_lme4$stability %>% filter(Trait == rv_lme4$trait)
919
+ })
920
+
921
  # LME4: Plot outputs
922
  output$lme4_blues_plot <- renderPlotly({
923
  req(lme4_filtered_blues())
 
1013
 
1014
  output$lme4_rankings_plot <- renderPlotly({
1015
  req(lme4_filtered_rankings())
1016
+ data <- lme4_filtered_rankings() %>% head(10)
1017
  if (nrow(data) == 0) {
1018
  return(plot_ly() %>%
1019
  layout(
 
1039
  )
1040
  })
1041
 
1042
+ output$lme4_stability_plot <- renderPlotly({
1043
+ req(lme4_filtered_stability())
1044
+ data <- lme4_filtered_stability()
1045
+ if (nrow(data) == 0 || all(is.na(data$Slope))) {
1046
+ return(plot_ly() %>%
1047
+ layout(
1048
+ title = list(text = paste("No Stability Data for", rv_lme4$trait), font = PLOT_FONT),
1049
+ annotations = list(
1050
+ text = "No valid data for plotting stability.",
1051
+ x = 0.5, y = 0.5, xref = "paper", yref = "paper",
1052
+ showarrow = FALSE, font = list(size = 12, color = "#2D3748")
1053
+ ),
1054
+ PLOT_LAYOUT
1055
+ ))
1056
+ }
1057
+ plot_ly(data, x = ~Slope, y = ~R_Squared, type = 'scatter', mode = 'markers',
1058
+ text = ~paste("Genotype:", Genotype, "<br>Slope:", round(Slope, 2), "<br>R²:", round(R_Squared, 2)),
1059
+ hoverinfo = "text", marker = list(size = 10, color = PLOT_COLORS[1])) %>%
1060
+ layout(
1061
+ title = list(text = paste("Stability Analysis for", rv_lme4$trait), font = list(size = 18, family = "Poppins", color = "#2D3748")),
1062
+ xaxis = list(title = "Stability Slope", titlefont = PLOT_FONT, tickfont = PLOT_FONT),
1063
+ yaxis = list(title = "R²", titlefont = PLOT_FONT, tickfont = PLOT_FONT),
1064
+ PLOT_LAYOUT,
1065
+ hoverlabel = list(bgcolor = "white", font = PLOT_FONT)
1066
+ )
1067
+ })
1068
+
1069
+ output$lme4_pca_plot <- renderPlotly({
1070
+ req(rv_lme4$pca)
1071
+ scores <- rv_lme4$pca$scores
1072
+ var_explained <- rv_lme4$pca$var_explained
1073
+ if (nrow(scores) == 0 || all(is.na(scores$PC1))) {
1074
+ return(plot_ly() %>%
1075
+ layout(
1076
+ title = list(text = "No PCA Data", font = PLOT_FONT),
1077
+ annotations = list(
1078
+ text = "No valid data for PCA plot.",
1079
+ x = 0.5, y = 0.5, xref = "paper", yref = "paper",
1080
+ showarrow = FALSE, font = list(size = 12, color = "#2D3748")
1081
+ ),
1082
+ PLOT_LAYOUT
1083
+ ))
1084
+ }
1085
+ plot_ly(scores, x = ~PC1, y = ~PC2, type = 'scatter', mode = 'markers',
1086
+ text = ~paste("Genotype:", Genotype, "<br>Environment:", Environment),
1087
+ hoverinfo = "text", marker = list(size = 10, color = PLOT_COLORS[1])) %>%
1088
+ layout(
1089
+ title = list(text = sprintf("PCA Biplot (PC1: %.1f%%, PC2: %.1f%%)", var_explained[1], var_explained[2]),
1090
+ font = list(size = 18, family = "Poppins", color = "#2D3748")),
1091
+ xaxis = list(title = "PC1", titlefont = PLOT_FONT, tickfont = PLOT_FONT),
1092
+ yaxis = list(title = "PC2", titlefont = PLOT_FONT, tickfont = PLOT_FONT),
1093
+ PLOT_LAYOUT,
1094
+ hoverlabel = list(bgcolor = "white", font = PLOT_FONT)
1095
+ )
1096
+ })
1097
+
1098
  # LME4: Table outputs
1099
  output$lme4_blues_table <- renderDT({
1100
  req(lme4_filtered_blues())
1101
+ data <- lme4_filtered_blues()
1102
+ if ("Error" %in% colnames(data)) {
1103
+ data <- data %>% select(-Error)
1104
+ }
1105
  datatable(
1106
+ data,
1107
  extensions = 'Buttons',
1108
  options = list(
1109
  scrollX = TRUE,
 
1179
  caption = paste("Genotype Rankings for", rv_lme4$trait)
1180
  ) %>% formatRound(columns = "Mean", digits = 3)
1181
  })
1182
+
1183
+ output$lme4_stability_table <- renderDT({
1184
+ req(lme4_filtered_stability())
1185
+ datatable(
1186
+ lme4_filtered_stability(),
1187
+ extensions = 'Buttons',
1188
+ options = list(
1189
+ scrollX = TRUE,
1190
+ dom = 'Bfrtip',
1191
+ buttons = c('copy', 'excel', 'pdf', 'print'),
1192
+ pageLength = 10,
1193
+ columnDefs = list(list(className = 'dt-center', targets = c(3,4)))
1194
+ ),
1195
+ caption = paste("Stability Analysis for", rv_lme4$trait)
1196
+ ) %>% formatRound(columns = c("Slope", "R_Squared"), digits = 3)
1197
+ })
1198
+
1199
+ output$lme4_pca_table <- renderDT({
1200
+ req(rv_lme4$pca)
1201
+ datatable(
1202
+ rv_lme4$pca$loadings,
1203
+ extensions = 'Buttons',
1204
+ options = list(
1205
+ scrollX = TRUE,
1206
+ dom = 'Bfrtip',
1207
+ buttons = c('copy', 'excel', 'pdf', 'print'),
1208
+ pageLength = 10,
1209
+ columnDefs = list(list(className = 'dt-center', targets = c(2,3)))
1210
+ ),
1211
+ caption = "PCA Loadings"
1212
+ ) %>% formatRound(columns = c("PC1", "PC2"), digits = 3)
1213
+ })
1214
+
1215
+ # LME4: Insights outputs
1216
+ output$lme4_descriptives_insights <- renderUI({
1217
+ req(rv_lme4$descriptives)
1218
+ desc <- rv_lme4$descriptives %>% filter(Trait == rv_lme4$trait)
1219
+ if (nrow(desc) == 0) return(NULL)
1220
+ cv <- desc$CV[1]
1221
+ insight <- if (cv > 20) {
1222
+ "High variability (CV > 20%) suggests environmental influence or measurement error. Consider increasing replicates or refining phenotyping."
1223
+ } else if (cv > 10) {
1224
+ "Moderate variability (CV 10-20%) indicates some environmental influence. Genotype selection for stability may be effective."
1225
+ } else {
1226
+ "Low variability (CV < 10%) indicates high precision. Suitable for reliable genetic selection."
1227
+ }
1228
+ HTML(sprintf("<strong>Insight for %s:</strong> %s", rv_lme4$trait, insight))
1229
+ })
1230
+
1231
+ output$lme4_blues_insights <- renderUI({
1232
+ req(lme4_filtered_blues())
1233
+ data <- lme4_filtered_blues()
1234
+ if (nrow(data) == 0) return(NULL)
1235
+ var_by_geno <- data %>%
1236
+ group_by(Genotype) %>%
1237
+ summarise(Var = var(predicted.value, na.rm = TRUE), .groups = "drop") %>%
1238
+ arrange(Var)
1239
+ stable_geno <- var_by_geno$Genotype[1]
1240
+ insight <- sprintf("Genotype %s shows the lowest variance across environments, indicating high stability.", stable_geno)
1241
+ HTML(sprintf("<strong>Insight for %s:</strong> %s", rv_lme4$trait, insight))
1242
+ })
1243
+
1244
+ output$lme4_correlations_insights <- renderUI({
1245
+ req(rv_lme4$cor_table)
1246
+ strong_cor <- rv_lme4$cor_table %>%
1247
+ filter(abs(Correlation) > 0.7, Trait1 != Trait2) %>%
1248
+ slice_head(n = 1)
1249
+ if (nrow(strong_cor) > 0) {
1250
+ insight <- sprintf("Strong correlation (r = %.3f) between %s and %s suggests potential for indirect selection.",
1251
+ strong_cor$Correlation, strong_cor$Trait1, strong_cor$Trait2)
1252
+ } else {
1253
+ insight <- "No strong correlations (|r| > 0.7) detected. Direct selection for each trait is recommended."
1254
+ }
1255
+ HTML(sprintf("<strong>Insight:</strong> %s", insight))
1256
+ })
1257
+
1258
+ output$lme4_heritability_insights <- renderUI({
1259
+ req(rv_lme4$heritability)
1260
+ h2 <- rv_lme4$heritability %>% filter(Trait == rv_lme4$trait)
1261
+ if (nrow(h2) == 0 || is.na(h2$Heritability)) return(NULL)
1262
+ insight <- if (h2$Heritability > 0.6) {
1263
+ sprintf("High heritability (H² = %.3f) for %s; effective for genetic selection.", h2$Heritability, rv_lme4$trait)
1264
+ } else if (h2$Heritability > 0.3) {
1265
+ sprintf("Moderate heritability (H² = %.3f) for %s; selection may be effective but consider environmental factors.", h2$Heritability, rv_lme4$trait)
1266
+ } else {
1267
+ sprintf("Low heritability (H² = %.3f) for %s; environmental optimization or more precise phenotyping needed.", h2$Heritability, rv_lme4$trait)
1268
+ }
1269
+ HTML(sprintf("<strong>Insight for %s:</strong> %s", rv_lme4$trait, insight))
1270
+ })
1271
+
1272
+ output$lme4_rankings_insights <- renderUI({
1273
+ req(lme4_filtered_rankings())
1274
+ top_geno <- lme4_filtered_rankings() %>% filter(Rank == 1) %>% slice_head(n = 1)
1275
+ if (nrow(top_geno) == 0) return(NULL)
1276
+ insight <- sprintf("Genotype %s ranks first for %s with mean value %.3f.",
1277
+ top_geno$Genotype, rv_lme4$trait, top_geno$Mean)
1278
+ HTML(sprintf("<strong>Insight for %s:</strong> %s", rv_lme4$trait, insight))
1279
+ })
1280
+
1281
+ output$lme4_stability_insights <- renderUI({
1282
+ req(lme4_filtered_stability())
1283
+ stab <- lme4_filtered_stability()
1284
+ stable_geno <- stab %>% filter(abs(Slope - 1) < 0.2, R_Squared > 0.8) %>% slice_head(n = 1)
1285
+ if (nrow(stable_geno) > 0) {
1286
+ insight <- sprintf("Genotype %s has high stability (slope = %.3f, R² = %.3f) for %s.",
1287
+ stable_geno$Genotype, stable_geno$Slope, stable_geno$R_Squared, rv_lme4$trait)
1288
+ } else {
1289
+ insight <- sprintf("No highly stable genotypes (slope ~ 1, R² > 0.8) for %s.", rv_lme4$trait)
1290
+ }
1291
+ HTML(sprintf("<strong>Insight for %s:</strong> %s", rv_lme4$trait, insight))
1292
+ })
1293
+
1294
+ output$lme4_pca_insights <- renderUI({
1295
+ req(rv_lme4$pca)
1296
+ loadings <- rv_lme4$pca$loadings
1297
+ var_explained <- rv_lme4$pca$var_explained
1298
+ if (nrow(loadings) == 0 || all(is.na(loadings$PC1))) return(NULL)
1299
+ top_trait_pc1 <- loadings %>% arrange(-abs(PC1)) %>% slice_head(n = 1)
1300
+ insight <- sprintf("PC1 (%.1f%% variance) is driven by %s (loading = %.3f).",
1301
+ var_explained[1], top_trait_pc1$Trait, top_trait_pc1$PC1)
1302
+ HTML(sprintf("<strong>Insight:</strong> %s", insight))
1303
+ })
1304
  }
1305
 
1306
  # Run the Shiny app