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

Update app.R

Browse files
Files changed (1) hide show
  1. app.R +303 -33
app.R CHANGED
@@ -9,7 +9,7 @@ library(plotly)
9
  library(shinyWidgets)
10
  library(ggplot2)
11
 
12
- # UI with updated styling, only for Predicted Means and Trait Correlations
13
  ui <- fluidPage(
14
  useShinyjs(),
15
  tags$head(
@@ -276,15 +276,21 @@ ui <- fluidPage(
276
  class = "nav flex-column", id = "lme4-v-pills-tab", role = "tablist",
277
  tags$a(class = "nav-link active", `data-toggle` = "pill", href = "#lme4-upload", role = "tab",
278
  icon("file-upload", class = "fas"), "📤 Upload Data"),
 
 
279
  tags$a(class = "nav-link", `data-toggle` = "pill", href = "#lme4-blues", role = "tab",
280
  icon("chart-bar", class = "fas"), "📈 Predicted Means"),
281
  tags$a(class = "nav-link", `data-toggle` = "pill", href = "#lme4-correlations", role = "tab",
282
- icon("link", class = "fas"), "🔗 Trait Correlations")
 
 
 
 
283
  ),
284
  hr(style = "border-color: rgba(255,255,255,0.1);"),
285
  div(
286
  style = "padding: 15px; color: var(--light); font-size: 12px; text-align: center;",
287
- p("LME4 Analysis Dashboard v1.0"),
288
  p("© 2023 Statistical Genetics Lab")
289
  )
290
  )
@@ -338,6 +344,29 @@ ui <- fluidPage(
338
  )
339
  )
340
  ),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
341
  div(
342
  class = "tab-pane fade", id = "lme4-blues", role = "tabpanel",
343
  div(
@@ -349,8 +378,9 @@ ui <- fluidPage(
349
  div(class = "table-container", DTOutput("lme4_blues_table")),
350
  div(
351
  class = "insights",
352
- h4("💡 Interpretation"),
353
- p("The G×E interaction plot shows genotype performance across environments. Stable genotypes have consistent values, while environment-specific genotypes vary. Use for selecting broadly adapted or specific genotypes.")
 
354
  )
355
  ),
356
  div(
@@ -371,8 +401,9 @@ ui <- fluidPage(
371
  div(class = "table-container", DTOutput("lme4_cor_table")),
372
  div(
373
  class = "insights",
374
- h4("💡 Interpretation"),
375
- p("Correlations reveal trait synergies or trade-offs. Positive correlations (near 1) suggest traits improve together; negative correlations (near -1) indicate trade-offs.")
 
376
  )
377
  ),
378
  div(
@@ -381,6 +412,51 @@ ui <- fluidPage(
381
  h4("📤 Upload data to see trait correlations", style = "color: var(--light);")
382
  )
383
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
384
  )
385
  )
386
  )
@@ -398,6 +474,9 @@ server <- function(input, output, session) {
398
  blues_all = NULL,
399
  cor_matrix = NULL,
400
  cor_table = NULL,
 
 
 
401
  debug_log = NULL
402
  )
403
 
@@ -482,9 +561,9 @@ server <- function(input, output, session) {
482
  })
483
  }
484
 
485
- # LME4: Fit model
486
- lme4_fit_model <- function(data, trait) {
487
- message("LME4: Fitting model for ", trait)
488
  formula_str <- if (input$lme4_include_interaction) {
489
  paste(trait, "~ Environment + Genotype + Environment:Genotype + (1|Block) + (1|Row) + (1|Column) + (1|Rep)")
490
  } else {
@@ -494,24 +573,41 @@ server <- function(input, output, session) {
494
  tryCatch({
495
  model <- lmer(formula, data = data, na.action = na.omit,
496
  control = lmerControl(check.rankX = "warn+drop.cols", optimizer = "bobyqa"))
497
- message("LME4: Successfully fitted model for ", trait)
498
  return(model)
499
  }, error = function(e) {
500
- message("LME4: Error fitting model for ", trait, ": ", e$message)
501
- showNotification(paste("Model fitting failed for", trait, ": ", e$message), type = "error", duration = 10)
502
  return(NULL)
503
- }, warning = function(w) {
504
- message("LME4: Warning in model fitting for ", trait, ": ", w$message)
505
- showNotification(paste("Warning for", trait, ": ", w$message), type = "warning", duration = 10)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
506
  return(NULL)
507
  })
508
  }
509
 
510
- # LME4: Get BLUEs
511
  lme4_get_blue <- function(model, trait) {
512
  if (is.null(model)) {
513
- message("LME4: No model for ", trait)
514
- return(data.frame(Trait = trait, Genotype = NA, Environment = NA, predicted.value = NA, Error = "No model fitted"))
515
  }
516
  tryCatch({
517
  emm_options(pbkrtest.limit = 5000, lmerTest.limit = 5000)
@@ -531,6 +627,28 @@ server <- function(input, output, session) {
531
  })
532
  }
533
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
534
  # LME4: File upload observer
535
  observeEvent(input$lme4_file, {
536
  req(input$lme4_file)
@@ -562,24 +680,34 @@ server <- function(input, output, session) {
562
  debug_log <- c()
563
 
564
  withProgress(message = 'LME4: Analyzing data', value = 0, {
565
- lme4_models <- list()
 
566
  blues_list <- list()
 
567
 
568
- total_steps <- length(rv_lme4$traits) + 1
 
569
  step_increment <- 1 / total_steps
570
 
571
  for (trait in rv_lme4$traits) {
572
- incProgress(step_increment, detail = paste("Fitting model for", trait))
573
- model <- lme4_fit_model(rv_lme4$data, trait)
574
- lme4_models[[trait]] <- model
575
- debug_log <- c(debug_log, paste("Trait:", trait, "- Model fitted:", ifelse(is.null(model), "Failed", "Success")))
576
 
577
  incProgress(step_increment, detail = paste("Calculating predicted means for", trait))
578
- blues_list[[trait]] <- lme4_get_blue(model, trait)
 
 
 
 
 
 
 
579
  }
580
 
581
  incProgress(step_increment, detail = "Calculating correlations")
582
- if (length(rv_lme4$traits) > 1) {
583
  trait_data <- rv_lme4$data %>% select(all_of(rv_lme4$traits)) %>% na.omit()
584
  if (nrow(trait_data) > 0) {
585
  cor_matrix <- cor(trait_data, use = "pairwise.complete.obs")
@@ -600,14 +728,48 @@ server <- function(input, output, session) {
600
  debug_log <- c(debug_log, "Correlations: Single trait")
601
  }
602
 
603
- rv_lme4$lme4_models <- lme4_models
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
604
  rv_lme4$blues_all <- bind_rows(blues_list) %>% filter(!is.na(predicted.value))
 
 
 
 
 
 
 
 
 
 
605
  rv_lme4$debug_log <- debug_log
606
 
607
- shinyjs::hide("lme4_blues_placeholder")
608
- shinyjs::show("lme4_blues_content")
609
- shinyjs::hide("lme4_correlations_placeholder")
610
- shinyjs::show("lme4_correlations_content")
 
 
 
611
 
612
  output$lme4_debug_log <- renderPrint({
613
  cat(paste(rv_lme4$debug_log, collapse = "\n"))
@@ -629,6 +791,11 @@ server <- function(input, output, session) {
629
  rv_lme4$blues_all %>% filter(Trait == rv_lme4$trait, !is.na(predicted.value))
630
  })
631
 
 
 
 
 
 
632
  # LME4: Plot outputs
633
  output$lme4_blues_plot <- renderPlotly({
634
  req(lme4_filtered_blues())
@@ -683,7 +850,7 @@ server <- function(input, output, session) {
683
  colorscale = list(c(-1, 0, 1), c("#FFB6C1", "white", "#B5EAD7")),
684
  showscale = TRUE,
685
  colorbar = list(title = "Correlation", titlefont = PLOT_FONT, tickfont = PLOT_FONT),
686
- text = ~round(rv_lme4$cor_matrix, 2),
687
  hoverinfo = "x+y+z"
688
  ) %>%
689
  layout(
@@ -695,6 +862,61 @@ server <- function(input, output, session) {
695
  )
696
  })
697
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
698
  # LME4: Table outputs
699
  output$lme4_blues_table <- renderDT({
700
  req(lme4_filtered_blues())
@@ -727,6 +949,54 @@ server <- function(input, output, session) {
727
  caption = "Correlation Between Traits"
728
  ) %>% formatRound(columns = "Correlation", digits = 3)
729
  })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
730
  }
731
 
732
  # Run the Shiny app
 
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(
 
276
  class = "nav flex-column", id = "lme4-v-pills-tab", role = "tablist",
277
  tags$a(class = "nav-link active", `data-toggle` = "pill", href = "#lme4-upload", role = "tab",
278
  icon("file-upload", class = "fas"), "📤 Upload Data"),
279
+ tags$a(class = "nav-link", `data-toggle` = "pill", href = "#lme4-descriptives", role = "tab",
280
+ icon("chart-line", class = "fas"), "📊 Descriptive Statistics"),
281
  tags$a(class = "nav-link", `data-toggle` = "pill", href = "#lme4-blues", role = "tab",
282
  icon("chart-bar", class = "fas"), "📈 Predicted Means"),
283
  tags$a(class = "nav-link", `data-toggle` = "pill", href = "#lme4-correlations", role = "tab",
284
+ icon("link", class = "fas"), "🔗 Trait Correlations"),
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
  )
 
344
  )
345
  )
346
  ),
347
+ div(
348
+ class = "tab-pane fade", id = "lme4-descriptives", role = "tabpanel",
349
+ div(
350
+ class = "section",
351
+ h2("📊 Descriptive Statistics"),
352
+ div(
353
+ id = "lme4_descriptives_content",
354
+ div(class = "table-container", DTOutput("lme4_descriptives_table")),
355
+ div(class = "chart-container", plotlyOutput("lme4_descriptives_plot", height = "500px")),
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(
364
+ id = "lme4_descriptives_placeholder", class = "text-center",
365
+ icon("chart-line", class = "fas", style = "font-size: 72px; color: var(--light); margin: 30px 0;"),
366
+ h4("📤 Upload data to see descriptive statistics", style = "color: var(--light);")
367
+ )
368
+ )
369
+ ),
370
  div(
371
  class = "tab-pane fade", id = "lme4-blues", role = "tabpanel",
372
  div(
 
378
  div(class = "table-container", DTOutput("lme4_blues_table")),
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(
 
401
  div(class = "table-container", DTOutput("lme4_cor_table")),
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(
 
412
  h4("📤 Upload data to see trait correlations", style = "color: var(--light);")
413
  )
414
  )
415
+ ),
416
+ div(
417
+ class = "tab-pane fade", id = "lme4-heritability", role = "tabpanel",
418
+ div(
419
+ class = "section",
420
+ h2("🧬 Heritability Estimates"),
421
+ div(
422
+ id = "lme4_heritability_content",
423
+ div(class = "table-container", DTOutput("lme4_heritability_table")),
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(
432
+ id = "lme4_heritability_placeholder", class = "text-center",
433
+ icon("calculator", class = "fas", style = "font-size: 72px; color: var(--light); margin: 30px 0;"),
434
+ h4("📤 Upload data to see heritability estimates", style = "color: var(--light);")
435
+ )
436
+ )
437
+ ),
438
+ div(
439
+ class = "tab-pane fade", id = "lme4-rankings", role = "tabpanel",
440
+ div(
441
+ class = "section",
442
+ h2("🏆 Genotype Rankings"),
443
+ div(
444
+ id = "lme4_rankings_content",
445
+ div(class = "table-container", DTOutput("lme4_rankings_table")),
446
+ div(class = "chart-container", plotlyOutput("lme4_rankings_plot", height = "500px")),
447
+ div(
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(
455
+ id = "lme4_rankings_placeholder", class = "text-center",
456
+ icon("trophy", class = "fas", style = "font-size: 72px; color: var(--light); margin: 30px 0;"),
457
+ h4("📤 Upload data to see genotype rankings", style = "color: var(--light);")
458
+ )
459
+ )
460
  )
461
  )
462
  )
 
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
 
 
561
  })
562
  }
563
 
564
+ # LME4: Fit fixed model for BLUEs
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 {
 
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) {
579
+ message("LME4: Error fitting fixed model for ", trait, ": ", e$message)
580
+ showNotification(paste("Fixed model fitting failed for", trait, ": ", e$message), type = "error", duration = 10)
581
  return(NULL)
582
+ })
583
+ }
584
+
585
+ # LME4: Fit random model for heritability
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) {
600
+ message("LME4: Error fitting random model for ", trait, ": ", e$message)
601
+ showNotification(paste("Random model fitting failed for", trait, ": ", e$message), type = "error", duration = 10)
602
  return(NULL)
603
  })
604
  }
605
 
606
+ # LME4: Get BLUEs from fixed model
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)
 
627
  })
628
  }
629
 
630
+ # LME4: Get heritability from random model
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
643
+ h2 <- if (total_var > 0) var_g_total / total_var else NA
644
+ data.frame(Trait = trait, Heritability = round(h2, 3), VarG = round(sigma_g, 3),
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
+
652
  # LME4: File upload observer
653
  observeEvent(input$lme4_file, {
654
  req(input$lme4_file)
 
680
  debug_log <- c()
681
 
682
  withProgress(message = 'LME4: Analyzing data', value = 0, {
683
+ fixed_models <- list()
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) {
693
+ incProgress(step_increment, detail = paste("Fitting fixed model for", trait))
694
+ fixed_model <- lme4_fit_fixed_model(rv_lme4$data, trait)
695
+ fixed_models[[trait]] <- fixed_model
696
+ debug_log <- c(debug_log, paste("Trait:", trait, "- Fixed model:", ifelse(is.null(fixed_model), "Failed", "Success")))
697
 
698
  incProgress(step_increment, detail = paste("Calculating predicted means for", trait))
699
+ blues_list[[trait]] <- lme4_get_blue(fixed_model, trait)
700
+
701
+ incProgress(step_increment, detail = paste("Fitting random model for", trait))
702
+ random_model <- lme4_fit_random_model(rv_lme4$data, trait)
703
+ random_models[[trait]] <- random_model
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")
710
+ if (n_traits > 1) {
711
  trait_data <- rv_lme4$data %>% select(all_of(rv_lme4$traits)) %>% na.omit()
712
  if (nrow(trait_data) > 0) {
713
  cor_matrix <- cor(trait_data, use = "pairwise.complete.obs")
 
728
  debug_log <- c(debug_log, "Correlations: Single trait")
729
  }
730
 
731
+ incProgress(step_increment, detail = "Calculating descriptive statistics")
732
+ descriptives <- rv_lme4$data %>%
733
+ select(all_of(rv_lme4$traits)) %>%
734
+ pivot_longer(cols = everything(), names_to = "Trait", values_to = "Value") %>%
735
+ group_by(Trait) %>%
736
+ summarise(
737
+ Mean = mean(Value, na.rm = TRUE),
738
+ SD = sd(Value, na.rm = TRUE),
739
+ Min = min(Value, na.rm = TRUE),
740
+ Max = max(Value, na.rm = TRUE),
741
+ N = sum(!is.na(Value)),
742
+ .groups = "drop"
743
+ ) %>%
744
+ mutate(CV = round((SD / Mean) * 100, 2))
745
+ rv_lme4$descriptives <- descriptives
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")
753
  rv_lme4$blues_all <- bind_rows(blues_list) %>% filter(!is.na(predicted.value))
754
+ rankings <- rv_lme4$blues_all %>%
755
+ group_by(Trait, Genotype) %>%
756
+ summarise(Mean = mean(predicted.value, na.rm = TRUE), .groups = "drop") %>%
757
+ group_by(Trait) %>%
758
+ mutate(Rank = rank(-Mean, ties.method = "min")) %>%
759
+ arrange(Trait, Rank)
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"))
 
791
  rv_lme4$blues_all %>% filter(Trait == rv_lme4$trait, !is.na(predicted.value))
792
  })
793
 
794
+ lme4_filtered_rankings <- reactive({
795
+ req(rv_lme4$rankings, rv_lme4$trait)
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())
 
850
  colorscale = list(c(-1, 0, 1), c("#FFB6C1", "white", "#B5EAD7")),
851
  showscale = TRUE,
852
  colorbar = list(title = "Correlation", titlefont = PLOT_FONT, tickfont = PLOT_FONT),
853
+ text = round(rv_lme4$cor_matrix, 2),
854
  hoverinfo = "x+y+z"
855
  ) %>%
856
  layout(
 
862
  )
863
  })
864
 
865
+ output$lme4_descriptives_plot <- renderPlotly({
866
+ req(rv_lme4$data, rv_lme4$trait)
867
+ trait_data <- rv_lme4$data[[rv_lme4$trait]]
868
+ if (all(is.na(trait_data)) || length(unique(rv_lme4$data$Environment)) < 2) {
869
+ return(plot_ly() %>%
870
+ layout(
871
+ title = list(text = paste("No Valid Data for", rv_lme4$trait), font = PLOT_FONT),
872
+ annotations = list(
873
+ text = "No valid data for boxplot.",
874
+ x = 0.5, y = 0.5, xref = "paper", yref = "paper",
875
+ showarrow = FALSE, font = list(size = 12, color = "#2D3748")
876
+ ),
877
+ PLOT_LAYOUT
878
+ ))
879
+ }
880
+ plot_ly(rv_lme4$data, x = ~Environment, y = rv_lme4$data[[rv_lme4$trait]], type = 'box',
881
+ color = ~Environment, colors = PLOT_COLORS,
882
+ hoverinfo = "y+name") %>%
883
+ layout(
884
+ title = list(text = paste("Distribution of", rv_lme4$trait, "by Environment"), font = list(size = 18, family = "Poppins", color = "#2D3748")),
885
+ xaxis = list(title = "Environment", titlefont = PLOT_FONT, tickfont = PLOT_FONT),
886
+ yaxis = list(title = paste(rv_lme4$trait, "Value"), titlefont = PLOT_FONT, tickfont = PLOT_FONT),
887
+ PLOT_LAYOUT,
888
+ hoverlabel = list(bgcolor = "white", font = PLOT_FONT)
889
+ )
890
+ })
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(
898
+ title = list(text = paste("No Rankings for", rv_lme4$trait), font = PLOT_FONT),
899
+ annotations = list(
900
+ text = "No valid data for plotting rankings.",
901
+ x = 0.5, y = 0.5, xref = "paper", yref = "paper",
902
+ showarrow = FALSE, font = list(size = 12, color = "#2D3748")
903
+ ),
904
+ PLOT_LAYOUT
905
+ ))
906
+ }
907
+ plot_ly(data, x = ~reorder(Genotype, -Mean), y = ~Mean, type = 'bar',
908
+ marker = list(color = PLOT_COLORS[1:length(unique(data$Genotype))]),
909
+ text = ~paste("Genotype:", Genotype, "<br>Mean:", round(Mean, 2), "<br>Rank:", Rank),
910
+ hoverinfo = "text") %>%
911
+ layout(
912
+ title = list(text = paste("Top Genotypes for", rv_lme4$trait), font = list(size = 18, family = "Poppins", color = "#2D3748")),
913
+ xaxis = list(title = "Genotype", tickangle = 45, titlefont = PLOT_FONT, tickfont = PLOT_FONT),
914
+ yaxis = list(title = "Mean Predicted Value", titlefont = PLOT_FONT, tickfont = PLOT_FONT),
915
+ PLOT_LAYOUT,
916
+ hoverlabel = list(bgcolor = "white", font = PLOT_FONT)
917
+ )
918
+ })
919
+
920
  # LME4: Table outputs
921
  output$lme4_blues_table <- renderDT({
922
  req(lme4_filtered_blues())
 
949
  caption = "Correlation Between Traits"
950
  ) %>% formatRound(columns = "Correlation", digits = 3)
951
  })
952
+
953
+ output$lme4_descriptives_table <- renderDT({
954
+ req(rv_lme4$descriptives)
955
+ datatable(
956
+ rv_lme4$descriptives,
957
+ extensions = 'Buttons',
958
+ options = list(
959
+ scrollX = TRUE,
960
+ dom = 'Bfrtip',
961
+ buttons = c('copy', 'excel', 'pdf', 'print'),
962
+ pageLength = 10,
963
+ columnDefs = list(list(className = 'dt-center', targets = c(2:6)))
964
+ ),
965
+ caption = "Descriptive Statistics for Traits"
966
+ ) %>% formatRound(columns = c("Mean", "SD", "Min", "Max", "CV"), digits = 2)
967
+ })
968
+
969
+ output$lme4_heritability_table <- renderDT({
970
+ req(rv_lme4$heritability)
971
+ datatable(
972
+ rv_lme4$heritability,
973
+ extensions = 'Buttons',
974
+ options = list(
975
+ scrollX = TRUE,
976
+ dom = 'Bfrtip',
977
+ buttons = c('copy', 'excel', 'pdf', 'print'),
978
+ pageLength = 10,
979
+ columnDefs = list(list(className = 'dt-center', targets = c(2:5)))
980
+ ),
981
+ caption = "Broad-Sense Heritability Estimates"
982
+ ) %>% formatRound(columns = c("Heritability", "VarG", "VarGE", "VarRes"), digits = 3)
983
+ })
984
+
985
+ output$lme4_rankings_table <- renderDT({
986
+ req(lme4_filtered_rankings())
987
+ datatable(
988
+ lme4_filtered_rankings(),
989
+ extensions = 'Buttons',
990
+ options = list(
991
+ scrollX = TRUE,
992
+ dom = 'Bfrtip',
993
+ buttons = c('copy', 'excel', 'pdf', 'print'),
994
+ pageLength = 10,
995
+ columnDefs = list(list(className = 'dt-center', targets = c(3,4)))
996
+ ),
997
+ caption = paste("Genotype Rankings for", rv_lme4$trait)
998
+ ) %>% formatRound(columns = "Mean", digits = 3)
999
+ })
1000
  }
1001
 
1002
  # Run the Shiny app