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

Update app.R

Browse files
Files changed (1) hide show
  1. app.R +97 -721
app.R CHANGED
@@ -8,14 +8,13 @@ library(emmeans)
8
  library(plotly)
9
  library(shinyWidgets)
10
  library(ggplot2)
11
- library(blme) # For Bayesian modeling to handle singular fits
12
 
13
- # UI with updated styling and improved plot containers
14
  ui <- fluidPage(
15
  useShinyjs(),
16
  tags$head(
17
  tags$meta(charset = "UTF-8"),
18
- tags$title("Combined Analysis Dashboard"),
19
  tags$link(rel = "stylesheet", href = "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"),
20
  tags$style(HTML("
21
  :root {
@@ -114,42 +113,6 @@ ui <- fluidPage(
114
  color: white;
115
  }
116
 
117
- .nav-tabs {
118
- border-bottom: 2px solid var(--primary);
119
- margin-bottom: 20px;
120
- }
121
-
122
- .nav-tabs .nav-item {
123
- margin-bottom: -2px;
124
- }
125
-
126
- .nav-tabs .nav-link {
127
- color: var(--light);
128
- background: #F5F5F5;
129
- border: 1px solid transparent;
130
- border-radius: 8px 8px 0 0;
131
- margin-right: 5px;
132
- padding: 12px 20px;
133
- transition: all 0.3s;
134
- }
135
-
136
- .nav-tabs .nav-link:hover {
137
- color: var(--light);
138
- background: var(--primary);
139
- border: 1px solid var(--primary);
140
- }
141
-
142
- .nav-tabs .nav-link.active {
143
- color: var(--light);
144
- background: var(--primary);
145
- border: 1px solid var(--primary);
146
- font-weight: bold;
147
- }
148
-
149
- .nav-tabs .nav-link i {
150
- margin-right: 8px;
151
- }
152
-
153
  .sidebar {
154
  background: var(--card-bg);
155
  color: var(--dark);
@@ -297,229 +260,125 @@ ui <- fluidPage(
297
  }
298
  "))
299
  ),
300
- tabsetPanel(
301
- id = "main_tabs",
302
- type = "tabs",
303
- tabPanel(
304
- icon("seedling"), "Preprocessing data",
305
  div(
306
- class = "section",
307
- h1("🌱 Preprocessing", class = "text-4xl font-extrabold tracking-tight"),
 
 
 
 
 
308
  div(
309
- class = "upload-container",
310
- div(class = "upload-icon", icon("cloud-upload-alt", class = "fas")),
311
- h3("📤 Upload Dataset (Excel)", style = "color: var(--primary);"),
312
- p("or", style = "margin: 10px 0;"),
313
- fileInput("pheno_file", NULL, accept = ".xlsx",
314
- buttonLabel = "Browse Files", placeholder = "No file selected"),
315
- p("📝 Supported format: .xlsx", style = "color: var(--light); font-size: 14px;"),
316
- div(id = "pheno_loader", class = "loader hidden")
317
  ),
318
- radioButtons("pheno_plotType", "📊 Select Plot Type",
319
- choices = c("2D Bar" = "2d", "3D Heatmap" = "3d"),
320
- selected = "2d", width = "100%"),
321
- actionButton("pheno_process", "🔍 Analyze Data", class = "btn-primary w-full"),
322
- tabsetPanel(
323
- tabPanel(
324
- icon("search"), "Missing Data Analysis",
325
- div(
326
- class = "section",
327
- h3("🔍 Missing Data Patterns by Environment & Trait", class = "text-2xl font-bold mb-6"),
328
- div(class = "chart-container", plotlyOutput("pheno_missingPlot", height = "500px"))
329
- )
330
- ),
331
- tabPanel(
332
- icon("filter"), "Filtered Data Insights",
333
- div(
334
- class = "section",
335
- h3("✅ Post-Filtering Missing Data Patterns", class = "text-2xl font-bold mb-6"),
336
- div(class = "chart-container", plotlyOutput("pheno_filteredMissingPlot", height = "500px"))
337
- )
338
- ),
339
- tabPanel(
340
- icon("table"), "Statistical Summary",
341
- div(
342
- class = "section",
343
- h3("📈 Environment-Wise Descriptive Statistics", class = "text-2xl font-bold mb-6"),
344
- DTOutput("pheno_statsTable"),
345
- downloadButton("pheno_downloadStats", "📥 Export Stats as CSV", class = "btn-primary mt-6")
346
- )
347
- )
348
  )
349
  )
350
  ),
351
- tabPanel(
352
- icon("calculator"), "Phenotypic data analysis",
353
  div(
354
- class = "app-wrapper",
355
  div(
356
- class = "sidebar",
357
  div(
358
- class = "sidebar-header",
359
- h3("📊 Phenotypic data analysis", style = "margin: 0; font-weight: 600; color: white;")
360
- ),
361
- selectInput("lme4_selected_trait", "Select Trait for Detailed Analysis", choices = c()),
362
- checkboxInput("lme4_include_interaction", "Include Environment:Genotype Interaction", value = FALSE),
363
- checkboxInput("use_blme", "Use Bayesian Model for Singular Fit", value = FALSE),
364
- div(
365
- class = "sidebar-content",
366
  div(
367
- class = "nav flex-column", id = "lme4-v-pills-tab", role = "tablist",
368
- tags$a(class = "nav-link active", `data-toggle` = "pill", href = "#lme4-upload", role = "tab",
369
- icon("file-upload", class = "fas"), "📤 Upload Data"),
370
- tags$a(class = "nav-link", `data-toggle` = "pill", href = "#lme4-blues", role = "tab",
371
- icon("chart-bar", class = "fas"), "📈 Predicted Means"),
372
- tags$a(class = "nav-link", `data-toggle` = "pill", href = "#lme4-heritability", role = "tab",
373
- icon("dna", class = "fas"), "🧬 Heritability"),
374
- tags$a(class = "nav-link", `data-toggle` = "pill", href = "#lme4-correlations", role = "tab",
375
- icon("link", class = "fas"), "🔗 Trait Correlations"),
376
- tags$a(class = "nav-link", `data-toggle` = "pill", href = "#lme4-stability", role = "tab",
377
- icon("balance-scale", class = "fas"), "⚖️ Stability Analysis")
378
  ),
379
- hr(style = "border-color: rgba(255,255,255,0.1);"),
 
380
  div(
381
- style = "padding: 15px; color: var(--light); font-size: 12px; text-align: center;",
382
- p("LME4 Analysis Dashboard v1.0"),
383
- p("© 2023 Statistical Genetics Lab")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
384
  )
385
  )
386
  ),
387
  div(
388
- class = "main-content",
389
  div(
390
- class = "tab-content",
 
391
  div(
392
- class = "tab-pane fade show active", id = "lme4-upload", role = "tabpanel",
 
 
393
  div(
394
- class = "section",
395
- h2("📤 Upload Your Data"),
396
- div(
397
- class = "upload-container",
398
- div(class = "upload-icon", icon("cloud-upload-alt", class = "fas")),
399
- h3("📁 Drag and drop your Excel file here", style = "color: var(--primary);"),
400
- p("or", style = "margin: 10px 0;"),
401
- fileInput("lme4_file", NULL, accept = c(".xlsx", ".xls"),
402
- buttonLabel = "Browse Files", placeholder = "No file selected"),
403
- p("📝 Supported formats: .xlsx, .xls", style = "color: var(--light); font-size: 14px;"),
404
- div(id = "lme4_loader", class = "loader hidden")
405
- ),
406
- verbatimTextOutput("lme4_data_preview"),
407
- verbatimTextOutput("lme4_debug_log"),
408
- div(
409
- id = "lme4_data_stats", class = "hidden",
410
- h3("📊 Data Overview"),
411
- fluidRow(
412
- column(3, div(class = "status-card card-1",
413
- icon("columns", class = "fas"),
414
- h4(textOutput("lme4_n_vars"), style = "font-weight: 600;"),
415
- p("Variables")
416
- )),
417
- column(3, div(class = "status-card card-2",
418
- icon("list", class = "fas"),
419
- h4(textOutput("lme4_n_obs"), style = "font-weight: 600;"),
420
- p("Observations")
421
- )),
422
- column(3, div(class = "status-card card-3",
423
- icon("dna", class = "fas"),
424
- h4(textOutput("lme4_n_geno"), style = "font-weight: 600;"),
425
- p("Genotypes")
426
- )),
427
- column(3, div(class = "status-card card-4",
428
- icon("globe", class = "fas"),
429
- h4(textOutput("lme4_n_env"), style = "font-weight: 600;"),
430
- p("Environments")
431
- ))
432
- )
433
- )
434
  )
435
  ),
436
  div(
437
- class = "tab-pane fade", id = "lme4-blues", role = "tabpanel",
438
- div(
439
- class = "section",
440
- h2("📈 Predicted Means (BLUEs)"),
441
- div(
442
- id = "lme4_blues_content",
443
- div(class = "chart-container", plotlyOutput("lme4_blues_plot", height = "500px")),
444
- div(class = "table-container", DTOutput("lme4_blues_table")),
445
- div(
446
- class = "insights",
447
- h4("💡 Interpretation"),
448
- p("The G×E interaction heatmap shows genotype performance across environments. Stable genotypes have consistent values, while environment-specific genotypes vary. Use for selecting broadly adapted or specific genotypes.")
449
- )
450
- ),
451
- div(
452
- id = "lme4_blues_placeholder", class = "text-center",
453
- icon("chart-bar", class = "fas", style = "font-size: 72px; color: var(--light); margin: 30px 0;"),
454
- h4("📤 Upload data to see predicted means", style = "color: var(--light);")
455
- )
456
- )
457
- ),
458
- div(
459
- class = "tab-pane fade", id = "lme4-heritability", role = "tabpanel",
460
- div(
461
- class = "section",
462
- h2("🧬 Heritability Across All Traits"),
463
- div(
464
- id = "lme4_heritability_content",
465
- div(class = "chart-container", plotlyOutput("lme4_heritability_plot", height = "500px")),
466
- div(class = "table-container", DTOutput("lme4_heritability_table")),
467
- div(
468
- class = "insights",
469
- h4("💡 Interpretation"),
470
- p("Heritability (H²) measures the proportion of phenotypic variance due to genetics. High H² (>0.7) traits are easier to improve via breeding; low H² traits are more environment-driven.")
471
- )
472
- ),
473
- div(
474
- id = "lme4_heritability_placeholder", class = "text-center",
475
- icon("dna", class = "fas", style = "font-size: 72px; color: var(--light); margin: 30px 0;"),
476
- h4("📤 Upload data to see heritability analysis", style = "color: var(--light);")
477
- )
478
- )
479
- ),
480
  div(
481
- class = "tab-pane fade", id = "lme4-correlations", role = "tabpanel",
 
 
482
  div(
483
- class = "section",
484
- h2("🔗 Trait Correlations"),
485
- div(
486
- id = "lme4_correlations_content",
487
- div(class = "chart-container", plotlyOutput("lme4_correlation_plot", height = "500px")),
488
- div(class = "table-container", DTOutput("lme4_cor_table")),
489
- div(
490
- class = "insights",
491
- h4("💡 Interpretation"),
492
- p("Correlations reveal trait synergies or trade-offs. Positive correlations (near 1) suggest traits improve together; negative correlations (near -1) indicate trade-offs.")
493
- )
494
- ),
495
- div(
496
- id = "lme4_correlations_placeholder", class = "text-center",
497
- icon("link", class = "fas", style = "font-size: 72px; color: var(--light); margin: 30px 0;"),
498
- h4("📤 Upload data to see trait correlations", style = "color: var(--light);")
499
- )
500
  )
501
  ),
502
  div(
503
- class = "tab-pane fade", id = "lme4-stability", role = "tabpanel",
504
- div(
505
- class = "section",
506
- h2("⚖️ Stability Analysis"),
507
- div(
508
- id = "lme4_stability_content",
509
- div(class = "chart-container", plotlyOutput("lme4_stability_plot", height = "500px")),
510
- div(class = "table-container", DTOutput("lme4_stability_table")),
511
- div(
512
- class = "insights",
513
- h4("💡 Interpretation"),
514
- p("Finlay-Wilkinson stability identifies genotypes with slopes near 1 (stable) and high R² (consistent). Stable genotypes suit broad adaptation; extreme slopes suit specific environments.")
515
- )
516
- ),
517
- div(
518
- id = "lme4_stability_placeholder", class = "text-center",
519
- icon("balance-scale", class = "fas", style = "font-size: 72px; color: var(--light); margin: 30px 0;"),
520
- h4("📤 Upload data to see stability analysis", style = "color: var(--light);")
521
- )
522
- )
523
  )
524
  )
525
  )
@@ -530,16 +389,6 @@ ui <- fluidPage(
530
 
531
  # Server function
532
  server <- function(input, output, session) {
533
- # Phenotypic Analysis Reactive Values
534
- rv_pheno <- reactiveValues(
535
- data = NULL,
536
- processed_data = NULL,
537
- missing_data = NULL,
538
- missing_20 = NULL,
539
- filtered_missing_data = NULL,
540
- summary_traits = NULL
541
- )
542
-
543
  # LME4 Analysis Reactive Values
544
  rv_lme4 <- reactiveValues(
545
  data = NULL,
@@ -547,10 +396,8 @@ server <- function(input, output, session) {
547
  trait = NULL,
548
  lme4_models = NULL,
549
  blues_all = NULL,
550
- heritability_table = NULL,
551
  cor_matrix = NULL,
552
  cor_table = NULL,
553
- stability_table = NULL,
554
  debug_log = NULL
555
  )
556
 
@@ -566,280 +413,6 @@ server <- function(input, output, session) {
566
  legend = list(orientation = "h", y = -0.2, x = 0.5, xanchor = "center")
567
  )
568
 
569
- # Phenotypic: Process data
570
- pheno_process_data <- function(path) {
571
- message("Pheno: Reading Excel file: ", path)
572
- tryCatch({
573
- input_data <- read_excel(path)
574
- colnames(input_data) <- make.names(colnames(input_data), unique = TRUE) # Ensure unique column names
575
-
576
- # Validate required columns
577
- required_cols <- c("Genotype", "Block", "Row", "Column", "Rep", "Environment")
578
- missing_cols <- setdiff(required_cols, colnames(input_data))
579
- if (length(missing_cols) > 0) {
580
- stop("Missing required columns: ", paste(missing_cols, collapse = ", "))
581
- }
582
-
583
- # Convert to factors
584
- input_data$Genotype <- as.factor(input_data$Genotype)
585
- input_data$Block <- as.factor(input_data$Block)
586
- input_data$Row <- as.factor(input_data$Row)
587
- input_data$Rep <- as.factor(input_data$Rep)
588
- input_data$Column <- as.factor(input_data$Column)
589
- input_data$Environment <- as.factor(input_data$Environment)
590
- input_data$Environment <- factor(input_data$Environment, levels = unique(input_data$Environment))
591
-
592
- # Identify trait columns (from column 10 onward)
593
- trait_cols <- colnames(input_data)[10:ncol(input_data)]
594
- if (length(trait_cols) == 0) {
595
- stop("No trait columns found (expected from column 10 onward)")
596
- }
597
-
598
- # Check if trait columns are numeric
599
- non_numeric_cols <- trait_cols[!sapply(input_data[trait_cols], is.numeric)]
600
- if (length(non_numeric_cols) > 0) {
601
- stop("Non-numeric trait columns detected: ", paste(non_numeric_cols, collapse = ", "))
602
- }
603
-
604
- # Calculate missing data
605
- data_missing <- input_data %>%
606
- group_by(Environment) %>%
607
- summarise(across(all_of(trait_cols), ~ sum(is.na(.)) / length(.)))
608
-
609
- data_missing_long <- data_missing %>%
610
- pivot_longer(cols = all_of(trait_cols), names_to = "Trait", values_to = "value") %>%
611
- filter(!is.na(value))
612
-
613
- missing_20_df <- data_missing_long %>% filter(value > 0.20)
614
- bad_env <- unique(missing_20_df$Environment)
615
-
616
- filtered_data <- input_data %>% filter(!(Environment %in% bad_env)) %>% droplevels()
617
-
618
- filtered_missing <- filtered_data %>%
619
- group_by(Environment) %>%
620
- summarise(across(all_of(trait_cols), ~ sum(is.na(.)) / length(.)))
621
-
622
- filtered_missing_long <- filtered_missing %>%
623
- pivot_longer(cols = all_of(trait_cols), names_to = "Trait", values_to = "value") %>%
624
- filter(!is.na(value))
625
-
626
- summary_traits_df <- filtered_data %>%
627
- group_by(Environment) %>%
628
- summarise(across(
629
- all_of(trait_cols),
630
- list(
631
- mean = ~ mean(.x, na.rm = TRUE),
632
- median = ~ median(.x, na.rm = TRUE),
633
- sd = ~ sd(.x, na.rm = TRUE),
634
- min = ~ min(.x, na.rm = TRUE),
635
- max = ~ max(.x, na.rm = TRUE),
636
- cv = ~ if (mean(.x, na.rm = TRUE) != 0) (sd(.x, na.rm = TRUE) / mean(.x, na.rm = TRUE)) * 100 else NA
637
- ),
638
- .names = "{.col}_{.fn}"
639
- )) %>%
640
- mutate(across(where(is.numeric), ~ round(.x, 2)))
641
-
642
- summary_long <- summary_traits_df %>%
643
- pivot_longer(cols = -Environment, names_to = c("Trait", "Stat"), names_sep = "_", values_to = "value") %>%
644
- pivot_wider(names_from = "Stat", values_from = "value") %>%
645
- filter(!is.na(mean))
646
-
647
- return(list(
648
- data = input_data,
649
- processed_data = filtered_data,
650
- missing_data = data_missing_long,
651
- missing_20 = missing_20_df,
652
- filtered_missing_data = filtered_missing_long,
653
- summary_traits = summary_long
654
- ))
655
- }, error = function(e) {
656
- message("Pheno: Error in data processing: ", e$message)
657
- showNotification(paste("Error processing file:", e$message), type = "error", duration = 10)
658
- return(NULL)
659
- })
660
- }
661
-
662
- # Phenotypic: File upload and process observer
663
- observeEvent(input$pheno_process, {
664
- req(input$pheno_file)
665
- message("Pheno: File upload triggered: ", input$pheno_file$name)
666
- shinyjs::show("pheno_loader")
667
- on.exit(shinyjs::hide("pheno_loader"))
668
-
669
- result <- pheno_process_data(input$pheno_file$datapath)
670
- if (!is.null(result)) {
671
- rv_pheno$data <- result$data
672
- rv_pheno$processed_data <- result$processed_data
673
- rv_pheno$missing_data <- result$missing_data
674
- rv_pheno$missing_20 <- result$missing_20
675
- rv_pheno$filtered_missing_data <- result$filtered_missing_data
676
- rv_pheno$summary_traits <- result$summary_traits
677
- showNotification("File uploaded and analyzed successfully", type = "message", duration = 5)
678
- }
679
- })
680
-
681
- # Phenotypic: Plot outputs
682
- output$pheno_missingPlot <- renderPlotly({
683
- req(rv_pheno$missing_data)
684
- data <- rv_pheno$missing_data %>% filter(!is.na(value))
685
- if (nrow(data) == 0) {
686
- return(plot_ly() %>%
687
- layout(
688
- title = list(text = "No Valid Data for Missing Data Plot", font = PLOT_FONT),
689
- annotations = list(
690
- text = "Upload valid data to visualize missing patterns.",
691
- x = 0.5, y = 0.5, xref = "paper", yref = "paper",
692
- showarrow = FALSE, font = list(size = 12, color = "#2D3748")
693
- ),
694
- PLOT_LAYOUT
695
- ))
696
- }
697
- if (input$pheno_plotType == "2d") {
698
- p <- ggplot(data, aes(x = Environment, y = value, fill = Trait)) +
699
- geom_bar(stat = "identity", position = "dodge", alpha = 0.85) +
700
- labs(
701
- title = "Missing Data by Environment and Trait",
702
- y = "Proportion of Missing Data",
703
- x = "Environment"
704
- ) +
705
- theme_minimal() +
706
- scale_fill_manual(values = PLOT_COLORS) +
707
- theme(
708
- plot.title = element_text(size = 18, face = "bold", color = "#2D3748", hjust = 0.5),
709
- axis.text.x = element_text(angle = 45, hjust = 1, size = 12, color = "#2D3748"),
710
- axis.text.y = element_text(size = 12, color = "#2D3748"),
711
- axis.title.x = element_text(size = 14, color = "#2D3748", face = "bold", margin = margin(t = 12)),
712
- axis.title.y = element_text(size = 14, color = "#2D3748", face = "bold", margin = margin(r = 12)),
713
- legend.position = "top",
714
- legend.title = element_text(size = 12, face = "bold", color = "#2D3748"),
715
- legend.text = element_text(size = 10, color = "#2D3748"),
716
- panel.grid.major = element_line(color = "#e5e7eb", size = 0.4),
717
- panel.grid.minor = element_blank(),
718
- panel.background = element_rect(fill = "#F9FAFB"),
719
- plot.background = element_rect(fill = "transparent")
720
- ) +
721
- facet_wrap(~Trait, ncol = 2, scales = "free_y")
722
-
723
- ggplotly(p, tooltip = c("Environment", "Trait", "value")) %>%
724
- layout(
725
- PLOT_LAYOUT,
726
- title = list(text = "Missing Data by Environment and Trait", font = list(size = 18, family = "Poppins", color = "#2D3748")),
727
- hoverlabel = list(bgcolor = "white", font = PLOT_FONT)
728
- )
729
- } else {
730
- plot_ly(
731
- data = data,
732
- x = ~Environment,
733
- y = ~Trait,
734
- z = ~value,
735
- type = "heatmap",
736
- colorscale = list(c(0, 0.5, 1), c("#FFB6C1", "#FFDAB9", "#B5EAD7")),
737
- showscale = TRUE,
738
- colorbar = list(title = "Missing Proportion", titlefont = PLOT_FONT, tickfont = PLOT_FONT)
739
- ) %>%
740
- layout(
741
- title = list(text = "Missing Data Heatmap", font = list(size = 18, family = "Poppins", color = "#2D3748")),
742
- xaxis = list(title = "Environment", tickangle = 45, titlefont = PLOT_FONT, tickfont = PLOT_FONT),
743
- yaxis = list(title = "Trait", titlefont = PLOT_FONT, tickfont = PLOT_FONT),
744
- PLOT_LAYOUT
745
- )
746
- }
747
- })
748
-
749
- output$pheno_filteredMissingPlot <- renderPlotly({
750
- req(rv_pheno$filtered_missing_data)
751
- data <- rv_pheno$filtered_missing_data %>% filter(!is.na(value))
752
- if (nrow(data) == 0) {
753
- return(plot_ly() %>%
754
- layout(
755
- title = list(text = "No Valid Filtered Data for Plot", font = PLOT_FONT),
756
- annotations = list(
757
- text = "No valid data after filtering environments with >20% missing data.",
758
- x = 0.5, y = 0.5, xref = "paper", yref = "paper",
759
- showarrow = FALSE, font = list(size = 12, color = "#2D3748")
760
- ),
761
- PLOT_LAYOUT
762
- ))
763
- }
764
- if (input$pheno_plotType == "2d") {
765
- p <- ggplot(data, aes(x = Environment, y = value, fill = Trait)) +
766
- geom_bar(stat = "identity", position = "dodge", alpha = 0.85) +
767
- labs(
768
- title = "Filtered Missing Data by Environment and Trait",
769
- y = "Proportion of Missing Data (Filtered)",
770
- x = "Environment"
771
- ) +
772
- theme_minimal() +
773
- scale_fill_manual(values = PLOT_COLORS) +
774
- theme(
775
- plot.title = element_text(size = 18, face = "bold", color = "#2D3748", hjust = 0.5),
776
- axis.text.x = element_text(angle = 45, hjust = 1, size = 12, color = "#2D3748"),
777
- axis.text.y = element_text(size = 12, color = "#2D3748"),
778
- axis.title.x = element_text(size = 14, color = "#2D3748", face = "bold", margin = margin(t = 12)),
779
- axis.title.y = element_text(size = 14, color = "#2D3748", face = "bold", margin = margin(r = 12)),
780
- legend.position = "top",
781
- legend.title = element_text(size = 12, face = "bold", color = "#2D3748"),
782
- legend.text = element_text(size = 10, color = "#2D3748"),
783
- panel.grid.major = element_line(color = "#e5e7eb", size = 0.4),
784
- panel.grid.minor = element_blank(),
785
- panel.background = element_rect(fill = "#F9FAFB"),
786
- plot.background = element_rect(fill = "transparent")
787
- ) +
788
- facet_wrap(~Trait, ncol = 2, scales = "free_y")
789
-
790
- ggplotly(p, tooltip = c("Environment", "Trait", "value")) %>%
791
- layout(
792
- PLOT_LAYOUT,
793
- title = list(text = "Filtered Missing Data by Environment and Trait", font = list(size = 18, family = "Poppins", color = "#2D3748")),
794
- hoverlabel = list(bgcolor = "white", font = PLOT_FONT)
795
- )
796
- } else {
797
- plot_ly(
798
- data = data,
799
- x = ~Environment,
800
- y = ~Trait,
801
- z = ~value,
802
- type = "heatmap",
803
- colorscale = list(c(0, 0.5, 1), c("#FFB6C1", "#FFDAB9", "#B5EAD7")),
804
- showscale = TRUE,
805
- colorbar = list(title = "Missing Proportion", titlefont = PLOT_FONT, tickfont = PLOT_FONT)
806
- ) %>%
807
- layout(
808
- title = list(text = "Filtered Missing Data Heatmap", font = list(size = 18, family = "Poppins", color = "#2D3748")),
809
- xaxis = list(title = "Environment", tickangle = 45, titlefont = PLOT_FONT, tickfont = PLOT_FONT),
810
- yaxis = list(title = "Trait", titlefont = PLOT_FONT, tickfont = PLOT_FONT),
811
- PLOT_LAYOUT
812
- )
813
- }
814
- })
815
-
816
- # Phenotypic: Table outputs
817
- output$pheno_statsTable <- renderDT({
818
- req(rv_pheno$summary_traits)
819
- datatable(
820
- rv_pheno$summary_traits,
821
- options = list(
822
- pageLength = 10,
823
- scrollX = TRUE,
824
- dom = 'Bfrtip',
825
- buttons = c('copy', 'csv', 'excel', 'pdf', 'print'),
826
- columnDefs = list(list(className = 'dt-center', targets = '_all'))
827
- ),
828
- extensions = 'Buttons',
829
- class = 'cell-border stripe',
830
- caption = "Environment-Wise Descriptive Statistics"
831
- ) %>% formatRound(columns = c("mean", "median", "sd", "min", "max", "cv"), digits = 2)
832
- })
833
-
834
- output$pheno_downloadStats <- downloadHandler(
835
- filename = function() {
836
- "descriptive_stats.csv"
837
- },
838
- content = function(file) {
839
- write.csv(rv_pheno$summary_traits, file, row.names = FALSE)
840
- }
841
- )
842
-
843
  # LME4: Process data
844
  lme4_process_data <- function(path) {
845
  message("LME4: Reading Excel file: ", path)
@@ -919,18 +492,8 @@ server <- function(input, output, session) {
919
  }
920
  formula <- as.formula(formula_str)
921
  tryCatch({
922
- if (input$use_blme) {
923
- model <- blmer(formula, data = data, na.action = na.omit,
924
- control = lmerControl(check.rankX = "warn+drop.cols", optimizer = "bobyqa"))
925
- message("LME4: Bayesian model fitted for ", trait)
926
- } else {
927
- model <- lmer(formula, data = data, na.action = na.omit,
928
- control = lmerControl(check.rankX = "warn+drop.cols", optimizer = "bobyqa"))
929
- if (isSingular(model)) {
930
- message("LME4: Singular fit for ", trait)
931
- showNotification(paste("Singular fit for", trait, "- consider using Bayesian model"), type = "warning", duration = 10)
932
- }
933
- }
934
  message("LME4: Successfully fitted model for ", trait)
935
  return(model)
936
  }, error = function(e) {
@@ -968,83 +531,6 @@ server <- function(input, output, session) {
968
  })
969
  }
970
 
971
- # LME4: Calculate heritability (modified to use only environmental variance)
972
- lme4_calculate_heritability <- function(model, trait) {
973
- message("LME4: Calculating heritability for ", trait)
974
- if (is.null(model)) {
975
- return(data.frame(Trait = trait, Heritability = NA, Error = "No model fitted"))
976
- }
977
- tryCatch({
978
- varcomp <- as.data.frame(VarCorr(model))
979
- vg <- varcomp$vcov[varcomp$grp == "Genotype"]
980
- vge <- varcomp$vcov[varcomp$grp == "Environment:Genotype"]
981
- ve <- sigma(model)^2 # Residual variance (used as environmental variance)
982
-
983
- # Check for valid variance components
984
- if (length(vg) == 0 || is.na(vg) || vg <= 0) {
985
- return(data.frame(Trait = trait, Heritability = NA, Error = "Invalid or zero genetic variance"))
986
- }
987
- if (is.na(ve) || ve <= 0) {
988
- return(data.frame(Trait = trait, Heritability = NA, Error = "Invalid or zero environmental variance"))
989
- }
990
-
991
- # Calculate heritability using only environmental variance
992
- if (input$lme4_include_interaction && !is.na(vge) && vge > 0) {
993
- h2 <- (vg + vge) / (vg + vge + ve)
994
- } else {
995
- h2 <- vg / (vg + ve)
996
- }
997
-
998
- if (is.na(h2) || h2 < 0 || h2 > 1) {
999
- return(data.frame(Trait = trait, Heritability = NA, Error = "Heritability out of bounds"))
1000
- }
1001
-
1002
- return(data.frame(Trait = trait, Heritability = round(h2, 3), Error = NA))
1003
- }, error = function(e) {
1004
- message("LME4: Error in heritability for ", trait, ": ", e$message)
1005
- return(data.frame(Trait = trait, Heritability = NA, Error = e$message))
1006
- })
1007
- }
1008
-
1009
- # LME4: Finlay-Wilkinson stability
1010
- lme4_finlay_wilkinson <- function(blues, trait) {
1011
- blues_trait <- blues %>% filter(Trait == trait, !is.na(predicted.value))
1012
- if (nrow(blues_trait) < 4) {
1013
- return(data.frame(Genotype = NA, Slope = NA, R2 = NA, Trait = trait, Error = "Insufficient data"))
1014
- }
1015
- env_means <- blues_trait %>%
1016
- group_by(Environment) %>%
1017
- summarize(mean_value = mean(predicted.value, na.rm = TRUE))
1018
- blues_trait <- blues_trait %>% left_join(env_means, by = "Environment")
1019
-
1020
- if (nrow(blues_trait) == 0 || all(is.na(blues_trait$mean_value))) {
1021
- return(data.frame(Genotype = NA, Slope = NA, R2 = NA, Trait = trait, Error = "No valid environment means"))
1022
- }
1023
-
1024
- stability <- blues_trait %>%
1025
- group_by(Genotype) %>%
1026
- do({
1027
- data_subset <- .
1028
- model <- tryCatch({
1029
- lm(predicted.value ~ mean_value, data = data_subset)
1030
- }, error = function(e) {
1031
- NULL
1032
- })
1033
- if (is.null(model) || nrow(data_subset) < 2) {
1034
- data.frame(Slope = NA, R2 = NA, Error = "Model fitting failed")
1035
- } else {
1036
- data.frame(
1037
- Slope = round(coef(model)[2], 3),
1038
- R2 = round(summary(model)$r.squared, 3),
1039
- Error = NA
1040
- )
1041
- }
1042
- }) %>%
1043
- mutate(Trait = trait)
1044
-
1045
- return(stability)
1046
- }
1047
-
1048
  # LME4: File upload observer
1049
  observeEvent(input$lme4_file, {
1050
  req(input$lme4_file)
@@ -1078,10 +564,8 @@ server <- function(input, output, session) {
1078
  withProgress(message = 'LME4: Analyzing data', value = 0, {
1079
  lme4_models <- list()
1080
  blues_list <- list()
1081
- herit_list <- list()
1082
- stability_list <- list()
1083
 
1084
- total_steps <- length(rv_lme4$traits) * 3 + 1
1085
  step_increment <- 1 / total_steps
1086
 
1087
  for (trait in rv_lme4$traits) {
@@ -1092,12 +576,6 @@ server <- function(input, output, session) {
1092
 
1093
  incProgress(step_increment, detail = paste("Calculating predicted means for", trait))
1094
  blues_list[[trait]] <- lme4_get_blue(model, trait)
1095
-
1096
- incProgress(step_increment, detail = paste("Calculating heritability for", trait))
1097
- herit_list[[trait]] <- lme4_calculate_heritability(model, trait)
1098
-
1099
- incProgress(step_increment, detail = paste("Performing stability analysis for", trait))
1100
- stability_list[[trait]] <- lme4_finlay_wilkinson(blues_list[[trait]], trait)
1101
  }
1102
 
1103
  incProgress(step_increment, detail = "Calculating correlations")
@@ -1124,18 +602,12 @@ server <- function(input, output, session) {
1124
 
1125
  rv_lme4$lme4_models <- lme4_models
1126
  rv_lme4$blues_all <- bind_rows(blues_list) %>% filter(!is.na(predicted.value))
1127
- rv_lme4$heritability_table <- bind_rows(herit_list) %>% filter(!is.na(Heritability) | !is.na(Error))
1128
- rv_lme4$stability_table <- bind_rows(stability_list)
1129
  rv_lme4$debug_log <- debug_log
1130
 
1131
  shinyjs::hide("lme4_blues_placeholder")
1132
  shinyjs::show("lme4_blues_content")
1133
- shinyjs::hide("lme4_heritability_placeholder")
1134
- shinyjs::show("lme4_heritability_content")
1135
  shinyjs::hide("lme4_correlations_placeholder")
1136
  shinyjs::show("lme4_correlations_content")
1137
- shinyjs::hide("lme4_stability_placeholder")
1138
- shinyjs::show("lme4_stability_content")
1139
 
1140
  output$lme4_debug_log <- renderPrint({
1141
  cat(paste(rv_lme4$debug_log, collapse = "\n"))
@@ -1157,11 +629,6 @@ server <- function(input, output, session) {
1157
  rv_lme4$blues_all %>% filter(Trait == rv_lme4$trait, !is.na(predicted.value))
1158
  })
1159
 
1160
- lme4_filtered_stability <- reactive({
1161
- req(rv_lme4$stability_table, rv_lme4$trait)
1162
- rv_lme4$stability_table %>% filter(Trait == rv_lme4$trait, !is.na(Slope))
1163
- })
1164
-
1165
  # LME4: Plot outputs
1166
  output$lme4_blues_plot <- renderPlotly({
1167
  req(lme4_filtered_blues())
@@ -1194,35 +661,6 @@ server <- function(input, output, session) {
1194
  )
1195
  })
1196
 
1197
- output$lme4_heritability_plot <- renderPlotly({
1198
- req(rv_lme4$heritability_table)
1199
- data <- rv_lme4$heritability_table %>% filter(!is.na(Heritability))
1200
- if (nrow(data) == 0) {
1201
- return(plot_ly() %>%
1202
- layout(
1203
- title = list(text = "No Valid Heritability Data", font = PLOT_FONT),
1204
- annotations = list(
1205
- text = paste("Heritability calculation failed for all traits.<br>Check debug log for details."),
1206
- x = 0.5, y = 0.5, xref = "paper", yref = "paper",
1207
- showarrow = FALSE, font = list(size = 12, color = "#2D3748")
1208
- ),
1209
- PLOT_LAYOUT
1210
- ))
1211
- }
1212
- plot_ly(data, x = ~Trait, y = ~Heritability, type = 'bar',
1213
- marker = list(color = PLOT_COLORS),
1214
- text = ~paste("H²:", round(Heritability, 3)),
1215
- hoverinfo = "text") %>%
1216
- layout(
1217
- title = list(text = "Broad-Sense Heritability Across All Traits", font = list(size = 18, family = "Poppins", color = "#2D3748")),
1218
- xaxis = list(title = "Trait", tickangle = 45, titlefont = PLOT_FONT, tickfont = PLOT_FONT),
1219
- yaxis = list(title = "Heritability (H²)", range = c(0, 1), titlefont = PLOT_FONT, tickfont = PLOT_FONT),
1220
- PLOT_LAYOUT,
1221
- showlegend = FALSE,
1222
- hoverlabel = list(bgcolor = "white", font = PLOT_FONT)
1223
- )
1224
- })
1225
-
1226
  output$lme4_correlation_plot <- renderPlotly({
1227
  req(rv_lme4$cor_matrix)
1228
  if (ncol(rv_lme4$cor_matrix) < 2 || all(is.na(rv_lme4$cor_matrix))) {
@@ -1257,36 +695,6 @@ server <- function(input, output, session) {
1257
  )
1258
  })
1259
 
1260
- output$lme4_stability_plot <- renderPlotly({
1261
- req(lme4_filtered_stability())
1262
- data <- lme4_filtered_stability()
1263
- if (nrow(data) == 0 || all(is.na(data$Slope))) {
1264
- return(plot_ly() %>%
1265
- layout(
1266
- title = list(text = paste("No Valid Stability Analysis for", rv_lme4$trait), font = PLOT_FONT),
1267
- annotations = list(
1268
- text = paste("Stability analysis failed for", rv_lme4$trait, ".<br>Check debug log for details."),
1269
- x = 0.5, y = 0.5, xref = "paper", yref = "paper",
1270
- showarrow = FALSE, font = list(size = 12, color = "#2D3748")
1271
- ),
1272
- PLOT_LAYOUT
1273
- ))
1274
- }
1275
- plot_ly(data, x = ~Slope, y = ~R2, text = ~Genotype, type = 'scatter', mode = 'markers+text',
1276
- marker = list(size = 12, color = PLOT_COLORS[1]),
1277
- textposition = 'top',
1278
- hoverinfo = "text",
1279
- text = ~paste("Genotype:", Genotype, "<br>Slope:", round(Slope, 3), "<br>R²:", round(R2, 3))) %>%
1280
- layout(
1281
- title = list(text = paste("Finlay-Wilkinson Stability Analysis for", rv_lme4$trait), font = list(size = 18, family = "Poppins", color = "#2D3748")),
1282
- xaxis = list(title = "Slope", titlefont = PLOT_FONT, tickfont = PLOT_FONT),
1283
- yaxis = list(title = "R²", titlefont = PLOT_FONT, tickfont = PLOT_FONT, range = c(0, 1)),
1284
- PLOT_LAYOUT,
1285
- showlegend = FALSE,
1286
- hoverlabel = list(bgcolor = "white", font = PLOT_FONT)
1287
- )
1288
- })
1289
-
1290
  # LME4: Table outputs
1291
  output$lme4_blues_table <- renderDT({
1292
  req(lme4_filtered_blues())
@@ -1304,22 +712,6 @@ server <- function(input, output, session) {
1304
  ) %>% formatRound(columns = c("predicted.value", "SE"), digits = 3)
1305
  })
1306
 
1307
- output$lme4_heritability_table <- renderDT({
1308
- req(rv_lme4$heritability_table)
1309
- datatable(
1310
- rv_lme4$heritability_table,
1311
- extensions = 'Buttons',
1312
- options = list(
1313
- scrollX = TRUE,
1314
- dom = 'Bfrtip',
1315
- buttons = c('copy', 'excel', 'pdf', 'print'),
1316
- pageLength = 10,
1317
- columnDefs = list(list(className = 'dt-center', targets = '_all'))
1318
- ),
1319
- caption = "Broad-Sense Heritability for All Traits"
1320
- ) %>% formatRound(columns = "Heritability", digits = 3)
1321
- })
1322
-
1323
  output$lme4_cor_table <- renderDT({
1324
  req(rv_lme4$cor_table)
1325
  datatable(
@@ -1335,22 +727,6 @@ server <- function(input, output, session) {
1335
  caption = "Correlation Between Traits"
1336
  ) %>% formatRound(columns = "Correlation", digits = 3)
1337
  })
1338
-
1339
- output$lme4_stability_table <- renderDT({
1340
- req(lme4_filtered_stability())
1341
- datatable(
1342
- lme4_filtered_stability() %>% select(-Error),
1343
- extensions = 'Buttons',
1344
- options = list(
1345
- scrollX = TRUE,
1346
- dom = 'Bfrtip',
1347
- buttons = c('copy', 'excel', 'pdf', 'print'),
1348
- pageLength = 10,
1349
- columnDefs = list(list(className = 'dt-center', targets = '_all'))
1350
- ),
1351
- caption = paste("Stability Analysis for", rv_lme4$trait)
1352
- ) %>% formatRound(columns = c("Slope", "R2"), digits = 3)
1353
- })
1354
  }
1355
 
1356
  # Run the Shiny app
 
8
  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(
16
  tags$meta(charset = "UTF-8"),
17
+ tags$title("Phenotypic Analysis Dashboard"),
18
  tags$link(rel = "stylesheet", href = "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"),
19
  tags$style(HTML("
20
  :root {
 
113
  color: white;
114
  }
115
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
116
  .sidebar {
117
  background: var(--card-bg);
118
  color: var(--dark);
 
260
  }
261
  "))
262
  ),
263
+ div(
264
+ class = "app-wrapper",
265
+ div(
266
+ class = "sidebar",
 
267
  div(
268
+ class = "sidebar-header",
269
+ h3("📊 Phenotypic Data Analysis", style = "margin: 0; font-weight: 600; color: white;")
270
+ ),
271
+ selectInput("lme4_selected_trait", "Select Trait for Detailed Analysis", choices = c()),
272
+ checkboxInput("lme4_include_interaction", "Include Environment:Genotype Interaction", value = FALSE),
273
+ div(
274
+ class = "sidebar-content",
275
  div(
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
  )
291
  ),
292
+ div(
293
+ class = "main-content",
294
  div(
295
+ class = "tab-content",
296
  div(
297
+ class = "tab-pane fade show active", id = "lme4-upload", role = "tabpanel",
298
  div(
299
+ class = "section",
300
+ h2("📤 Upload Your Data"),
 
 
 
 
 
 
301
  div(
302
+ class = "upload-container",
303
+ div(class = "upload-icon", icon("cloud-upload-alt", class = "fas")),
304
+ h3("📁 Drag and drop your Excel file here", style = "color: var(--primary);"),
305
+ p("or", style = "margin: 10px 0;"),
306
+ fileInput("lme4_file", NULL, accept = c(".xlsx", ".xls"),
307
+ buttonLabel = "Browse Files", placeholder = "No file selected"),
308
+ p("📝 Supported formats: .xlsx, .xls", style = "color: var(--light); font-size: 14px;"),
309
+ div(id = "lme4_loader", class = "loader hidden")
 
 
 
310
  ),
311
+ verbatimTextOutput("lme4_data_preview"),
312
+ verbatimTextOutput("lme4_debug_log"),
313
  div(
314
+ id = "lme4_data_stats", class = "hidden",
315
+ h3("📊 Data Overview"),
316
+ fluidRow(
317
+ column(3, div(class = "status-card card-1",
318
+ icon("columns", class = "fas"),
319
+ h4(textOutput("lme4_n_vars"), style = "font-weight: 600;"),
320
+ p("Variables")
321
+ )),
322
+ column(3, div(class = "status-card card-2",
323
+ icon("list", class = "fas"),
324
+ h4(textOutput("lme4_n_obs"), style = "font-weight: 600;"),
325
+ p("Observations")
326
+ )),
327
+ column(3, div(class = "status-card card-3",
328
+ icon("dna", class = "fas"),
329
+ h4(textOutput("lme4_n_geno"), style = "font-weight: 600;"),
330
+ p("Genotypes")
331
+ )),
332
+ column(3, div(class = "status-card card-4",
333
+ icon("globe", class = "fas"),
334
+ h4(textOutput("lme4_n_env"), style = "font-weight: 600;"),
335
+ p("Environments")
336
+ ))
337
+ )
338
  )
339
  )
340
  ),
341
  div(
342
+ class = "tab-pane fade", id = "lme4-blues", role = "tabpanel",
343
  div(
344
+ class = "section",
345
+ h2("📈 Predicted Means (BLUEs)"),
346
  div(
347
+ id = "lme4_blues_content",
348
+ div(class = "chart-container", plotlyOutput("lme4_blues_plot", height = "500px")),
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(
357
+ id = "lme4_blues_placeholder", class = "text-center",
358
+ icon("chart-bar", class = "fas", style = "font-size: 72px; color: var(--light); margin: 30px 0;"),
359
+ h4("📤 Upload data to see predicted means", style = "color: var(--light);")
360
+ )
361
+ )
362
+ ),
363
+ div(
364
+ class = "tab-pane fade", id = "lme4-correlations", role = "tabpanel",
365
+ div(
366
+ class = "section",
367
+ h2("🔗 Trait Correlations"),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
368
  div(
369
+ id = "lme4_correlations_content",
370
+ div(class = "chart-container", plotlyOutput("lme4_correlation_plot", height = "500px")),
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(
379
+ id = "lme4_correlations_placeholder", class = "text-center",
380
+ icon("link", class = "fas", style = "font-size: 72px; color: var(--light); margin: 30px 0;"),
381
+ h4("📤 Upload data to see trait correlations", style = "color: var(--light);")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
382
  )
383
  )
384
  )
 
389
 
390
  # Server function
391
  server <- function(input, output, session) {
 
 
 
 
 
 
 
 
 
 
392
  # LME4 Analysis Reactive Values
393
  rv_lme4 <- reactiveValues(
394
  data = NULL,
 
396
  trait = NULL,
397
  lme4_models = NULL,
398
  blues_all = NULL,
 
399
  cor_matrix = NULL,
400
  cor_table = NULL,
 
401
  debug_log = NULL
402
  )
403
 
 
413
  legend = list(orientation = "h", y = -0.2, x = 0.5, xanchor = "center")
414
  )
415
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
416
  # LME4: Process data
417
  lme4_process_data <- function(path) {
418
  message("LME4: Reading Excel file: ", path)
 
492
  }
493
  formula <- as.formula(formula_str)
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) {
 
531
  })
532
  }
533
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
534
  # LME4: File upload observer
535
  observeEvent(input$lme4_file, {
536
  req(input$lme4_file)
 
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) {
 
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")
 
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
  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())
 
661
  )
662
  })
663
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
664
  output$lme4_correlation_plot <- renderPlotly({
665
  req(rv_lme4$cor_matrix)
666
  if (ncol(rv_lme4$cor_matrix) < 2 || all(is.na(rv_lme4$cor_matrix))) {
 
695
  )
696
  })
697
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
698
  # LME4: Table outputs
699
  output$lme4_blues_table <- renderDT({
700
  req(lme4_filtered_blues())
 
712
  ) %>% formatRound(columns = c("predicted.value", "SE"), digits = 3)
713
  })
714
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
715
  output$lme4_cor_table <- renderDT({
716
  req(rv_lme4$cor_table)
717
  datatable(
 
727
  caption = "Correlation Between Traits"
728
  ) %>% formatRound(columns = "Correlation", digits = 3)
729
  })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
730
  }
731
 
732
  # Run the Shiny app