International Rice Research Institute commited on
Commit
59c3308
·
verified ·
1 Parent(s): c3449d5

Update app.R

Browse files
Files changed (1) hide show
  1. app.R +312 -107
app.R CHANGED
@@ -20,6 +20,7 @@ library(RColorBrewer)
20
  library(moments)
21
  library(reshape2)
22
  library(gridExtra)
 
23
 
24
  # UI
25
  ui <- fluidPage(
@@ -42,8 +43,8 @@ ui <- fluidPage(
42
  --card-bg: #FFFFFF;
43
  }
44
 
45
- body {
46
- font-family: 'Poppins', sans-serif;
47
  background: var(--background);
48
  color: var(--dark);
49
  overflow-x: hidden;
@@ -55,17 +56,17 @@ ui <- fluidPage(
55
  margin: 0 auto;
56
  }
57
 
58
- .section {
59
- margin-bottom: 30px;
60
  background: var(--card-bg);
61
- padding: 2.5rem;
62
- border-radius: 15px;
63
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
64
  border: 1px solid rgba(30, 58, 138, 0.2);
65
  }
66
 
67
- h1, h2, h3 {
68
- color: var(--primary);
69
  border-bottom: 2px solid var(--secondary);
70
  padding-bottom: 10px;
71
  margin-bottom: 20px;
@@ -124,7 +125,35 @@ ui <- fluidPage(
124
  color: white;
125
  }
126
 
127
- .sidebar {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
128
  background: var(--card-bg);
129
  color: var(--dark);
130
  padding: 2rem;
@@ -163,7 +192,8 @@ ui <- fluidPage(
163
  cursor: pointer;
164
  }
165
 
166
- .nav-tabs .nav-link:hover, .nav-tabs .nav-link.active {
 
167
  color: white;
168
  background: linear-gradient(90deg, var(--primary), var(--info));
169
  transform: translateX(5px);
@@ -299,6 +329,7 @@ ui <- fluidPage(
299
  }
300
  "))
301
  ),
 
302
  div(
303
  class = "app-wrapper",
304
  div(
@@ -311,6 +342,16 @@ ui <- fluidPage(
311
  class = "sidebar-content",
312
  selectInput("selected_trait", "Select Trait for Analysis", choices = c(), width = "100%"),
313
  checkboxInput("include_interaction", "Include G×E Interaction", value = FALSE),
 
 
 
 
 
 
 
 
 
 
314
  hr(style = "border-color: rgba(255,255,255,0.1);"),
315
  div(
316
  style = "padding: 15px; color: var(--light); font-size: 12px; text-align: center;",
@@ -319,10 +360,12 @@ ui <- fluidPage(
319
  )
320
  )
321
  ),
 
322
  div(
323
  class = "main-content",
324
  tabsetPanel(
325
  id = "main_tabs",
 
326
  tabPanel("Data Upload", value = "upload",
327
  div(
328
  class = "section",
@@ -331,9 +374,9 @@ ui <- fluidPage(
331
  class = "upload-container",
332
  div(class = "upload-icon", icon("cloud-upload-alt", class = "fas")),
333
  h3("📁 Upload your Excel/CSV file", style = "color: var(--primary);"),
334
- fileInput("data_file", NULL,
335
  accept = c(".xlsx", ".xls", ".csv"),
336
- buttonLabel = "Browse Files",
337
  placeholder = "No file selected"),
338
  p("📝 Supported formats: .xlsx, .xls, .csv", style = "color: var(--light); font-size: 14px;")
339
  ),
@@ -341,27 +384,16 @@ ui <- fluidPage(
341
  div(id = "data_preview_section", class = "hidden",
342
  h3("📊 Data Overview"),
343
  fluidRow(
344
- column(3, div(class = "status-card",
345
- icon("columns", class = "fas"),
346
- h4(textOutput("n_vars")),
347
- p("Variables"))),
348
- column(3, div(class = "status-card",
349
- icon("list", class = "fas"),
350
- h4(textOutput("n_obs")),
351
- p("Observations"))),
352
- column(3, div(class = "status-card",
353
- icon("dna", class = "fas"),
354
- h4(textOutput("n_geno")),
355
- p("Genotypes"))),
356
- column(3, div(class = "status-card",
357
- icon("globe", class = "fas"),
358
- h4(textOutput("n_env")),
359
- p("Environments")))
360
  ),
361
  DTOutput("data_preview_table")
362
  )
363
  )
364
  ),
 
365
  tabPanel("Descriptive Statistics", value = "descriptives",
366
  div(
367
  class = "section",
@@ -373,25 +405,30 @@ ui <- fluidPage(
373
  DTOutput("descriptives_table"),
374
  div(class = "insights",
375
  h4("💡 Interpretation"),
376
- p("Descriptive statistics show central tendency and variability. CV > 20% indicates high variability. Check for outliers and data distribution normality."))
 
377
  )
378
  ),
 
379
  tabPanel("ANOVA", value = "anova",
380
  div(
381
  class = "section",
382
  h2("🧮 Analysis of Variance (ANOVA)"),
383
- div(class = "chart-container",
384
  h4("ANOVA Table"),
385
- DTOutput("anova_table")),
 
386
  fluidRow(
387
  column(6, div(class = "chart-container", plotlyOutput("residual_plot", height = "auto"))),
388
  column(6, div(class = "chart-container", plotlyOutput("qq_plot", height = "auto")))
389
  ),
390
  div(class = "insights",
391
  h4("💡 Interpretation"),
392
- p("ANOVA tests significance of effects. P < 0.05 indicates significant differences. Check residual plots for model assumptions."))
 
393
  )
394
  ),
 
395
  tabPanel("Mixed Models", value = "blues",
396
  div(
397
  class = "section",
@@ -400,27 +437,27 @@ ui <- fluidPage(
400
  DTOutput("blues_table"),
401
  div(class = "insights",
402
  h4("💡 Interpretation"),
403
- p("BLUEs (Best Linear Unbiased Estimators) account for experimental design. Parallel lines indicate no G×E interaction; crossing lines suggest interaction."))
 
404
  )
405
  ),
 
406
  tabPanel("Heritability", value = "heritability",
407
  div(
408
  class = "section",
409
  h2("🧬 Heritability Analysis"),
410
  fluidRow(
411
- column(6, div(class = "chart-container",
412
- h4("Variance Components"),
413
- DTOutput("variance_components"))),
414
- column(6, div(class = "chart-container",
415
- h4("Heritability Estimates"),
416
- DTOutput("heritability_table")))
417
  ),
418
  div(class = "chart-container", plotlyOutput("heritability_plot", height = "auto")),
419
  div(class = "insights",
420
  h4("💡 Interpretation"),
421
- p("Broad-sense heritability (H²) = genetic variance / total variance. Values > 0.6 indicate high heritability, suitable for selection."))
 
422
  )
423
  ),
 
424
  tabPanel("Correlations", value = "correlations",
425
  div(
426
  class = "section",
@@ -432,18 +469,21 @@ ui <- fluidPage(
432
  div(class = "chart-container", plotOutput("correlation_network", height = "auto")),
433
  div(class = "insights",
434
  h4("💡 Interpretation"),
435
- p("Correlation matrix shows relationships between traits. Values near ±1 indicate strong relationships. Use for indirect selection strategies."))
 
436
  )
437
  ),
 
438
  tabPanel("Clustering", value = "clustering",
439
  div(
440
  class = "section",
441
  h2("🌐 Genotype Clustering"),
442
  fluidRow(
443
- column(4,
444
  numericInput("n_clusters", "Number of Clusters:", value = 3, min = 2, max = 10),
445
- selectInput("clustering_method", "Clustering Method:",
446
- choices = c("K-means" = "kmeans", "Hierarchical" = "hierarchical"))),
 
447
  column(8, div(class = "chart-container", plotlyOutput("cluster_plot", height = "auto")))
448
  ),
449
  fluidRow(
@@ -452,9 +492,11 @@ ui <- fluidPage(
452
  ),
453
  div(class = "insights",
454
  h4("💡 Interpretation"),
455
- p("Clustering groups similar genotypes based on trait performance. Use for identifying genetic groups and breeding strategies."))
 
456
  )
457
  ),
 
458
  tabPanel("PCA", value = "pca",
459
  div(
460
  class = "section",
@@ -469,9 +511,11 @@ ui <- fluidPage(
469
  ),
470
  div(class = "insights",
471
  h4("💡 Interpretation"),
472
- p("PCA reduces dimensionality while preserving variance. First few PCs explain most variation. Loadings show trait contributions to each PC."))
 
473
  )
474
  ),
 
475
  tabPanel("Stability", value = "stability",
476
  div(
477
  class = "section",
@@ -483,9 +527,11 @@ ui <- fluidPage(
483
  DTOutput("stability_table"),
484
  div(class = "insights",
485
  h4("💡 Interpretation"),
486
- p("Stability parameters identify genotypes with consistent performance across environments. Low Ecovalence (Wi²) and high yield indicate stable, high-performing genotypes."))
 
487
  )
488
  ),
 
489
  tabPanel("Customization", value = "customization",
490
  div(
491
  class = "section",
@@ -494,10 +540,8 @@ ui <- fluidPage(
494
  class = "chart-container",
495
  h3("Adjust Plot Dimensions"),
496
  fluidRow(
497
- column(6,
498
- numericInput("plot_height", "Plot Height (px):", value = 600, min = 300, max = 1200, step = 50)),
499
- column(6,
500
- numericInput("plot_width", "Plot Width (px):", value = 800, min = 400, max = 1600, step = 50))
501
  ),
502
  h3("Select Color Scheme"),
503
  selectInput("color_scheme", "Color Scheme:",
@@ -511,7 +555,8 @@ ui <- fluidPage(
511
  ),
512
  div(class = "insights",
513
  h4("💡 Instructions"),
514
- p("Adjust the height and width of all plots using the sliders. Choose a color scheme to update the appearance of plots. Click 'Apply Customization' to update the visualizations."))
 
515
  )
516
  )
517
  )
@@ -571,9 +616,9 @@ server <- function(input, output, session) {
571
  # Check required columns
572
  required_cols <- c("Genotype", "Environment", "Rep", "Block")
573
  missing_cols <- setdiff(required_cols, names(data))
 
574
  if (length(missing_cols) > 0) {
575
- validation$errors <- c(validation$errors,
576
- paste("Missing required columns:", paste(missing_cols, collapse = ", ")))
577
  }
578
 
579
  # Check data types and convert if necessary
@@ -609,16 +654,14 @@ server <- function(input, output, session) {
609
  if ("Genotype" %in% names(data)) {
610
  n_geno <- length(unique(data$Genotype))
611
  if (n_geno < 3) {
612
- validation$errors <- c(validation$errors,
613
- paste("Insufficient genotypes (", n_geno, "); need at least 3"))
614
  }
615
  }
616
 
617
  if ("Environment" %in% names(data)) {
618
  n_env <- length(unique(data$Environment))
619
  if (n_env < 2) {
620
- validation$errors <- c(validation$errors,
621
- paste("Insufficient environments (", n_env, "); need at least 2"))
622
  }
623
  }
624
 
@@ -629,9 +672,7 @@ server <- function(input, output, session) {
629
  filter(Missing > 0)
630
 
631
  if (nrow(missing_summary) > 0) {
632
- validation$warnings <- c(validation$warnings,
633
- paste("Variables with missing data:",
634
- paste(missing_summary$Variable, collapse = ", ")))
635
  }
636
 
637
  # Check for balanced design
@@ -653,8 +694,7 @@ server <- function(input, output, session) {
653
  if (length(numeric_traits) == 0) {
654
  validation$errors <- c(validation$errors, "No numeric trait columns found starting from column 10")
655
  } else {
656
- validation$success <- c(validation$success,
657
- paste("Found", length(numeric_traits), "numeric trait columns starting from column 10"))
658
  }
659
  } else {
660
  validation$errors <- c(validation$errors, "Input data has fewer than 10 columns")
@@ -696,8 +736,8 @@ server <- function(input, output, session) {
696
  incProgress(0.6, detail = "Updating interface...")
697
 
698
  # Update trait selection
699
- updateSelectInput(session, "selected_trait",
700
- choices = rv$traits,
701
  selected = if(length(rv$traits) > 0) rv$traits[1] else NULL)
702
 
703
  # Show data preview
@@ -708,11 +748,11 @@ server <- function(input, output, session) {
708
  # Update summary statistics
709
  output$n_vars <- renderText({ ncol(rv$data) })
710
  output$n_obs <- renderText({ nrow(rv$data) })
711
- output$n_geno <- renderText({
712
- if("Genotype" %in% names(rv$data)) length(unique(rv$data$Genotype)) else "N/A"
713
  })
714
- output$n_env <- renderText({
715
- if("Environment" %in% names(rv$data)) length(unique(rv$data$Environment)) else "N/A"
716
  })
717
 
718
  incProgress(1, detail = "Complete!")
@@ -721,12 +761,14 @@ server <- function(input, output, session) {
721
  if (length(validation_results$errors) > 0) {
722
  showNotification(paste(validation_results$errors, collapse = "; "), type = "error")
723
  }
 
724
  if (length(validation_results$warnings) > 0) {
725
  showNotification(paste(validation_results$warnings, collapse = "; "), type = "warning")
726
  }
 
727
  output$upload_status <- renderUI({
728
- div(class = "success-message",
729
- icon("check-circle"),
730
  paste("Successfully loaded", nrow(rv$data), "observations with", length(rv$traits), "traits"))
731
  })
732
 
@@ -734,8 +776,8 @@ server <- function(input, output, session) {
734
 
735
  }, error = function(e) {
736
  output$upload_status <- renderUI({
737
- div(class = "error-message",
738
- icon("exclamation-triangle"),
739
  paste("Error:", e$message))
740
  })
741
  showNotification(paste("Error:", e$message), type = "error")
@@ -789,6 +831,7 @@ server <- function(input, output, session) {
789
 
790
  incProgress(1, detail = "Complete!")
791
  stats
 
792
  }, error = function(e) {
793
  showNotification(paste("Error in descriptive statistics:", e$message), type = "error")
794
  return(NULL)
@@ -799,7 +842,6 @@ server <- function(input, output, session) {
799
  # Descriptive statistics table
800
  output$descriptives_table <- renderDT({
801
  req(descriptive_stats())
802
-
803
  datatable(
804
  descriptive_stats(),
805
  extensions = 'Buttons',
@@ -818,7 +860,6 @@ server <- function(input, output, session) {
818
  # Descriptive statistics plot
819
  output$descriptives_plot <- renderPlotly({
820
  req(rv$data, input$selected_trait)
821
-
822
  if (!input$selected_trait %in% rv$traits) return(NULL)
823
 
824
  tryCatch({
@@ -843,6 +884,7 @@ server <- function(input, output, session) {
843
  scale_color_manual(values = get_color_palette(rv$color_scheme, length(unique(rv$data$Genotype))))
844
 
845
  ggplotly(p, tooltip = c("x", "y", "color"), height = rv$plot_height, width = rv$plot_width)
 
846
  }, error = function(e) {
847
  showNotification(paste("Error in descriptive plot:", e$message), type = "error")
848
  return(NULL)
@@ -852,7 +894,6 @@ server <- function(input, output, session) {
852
  # Distribution plot (histogram with density)
853
  output$distribution_plot <- renderPlotly({
854
  req(rv$data, input$selected_trait)
855
-
856
  if (!input$selected_trait %in% rv$traits) return(NULL)
857
 
858
  tryCatch({
@@ -878,6 +919,7 @@ server <- function(input, output, session) {
878
  )
879
 
880
  ggplotly(p, height = rv$plot_height, width = rv$plot_width)
 
881
  }, error = function(e) {
882
  showNotification(paste("Error in distribution plot:", e$message), type = "error")
883
  return(NULL)
@@ -915,8 +957,7 @@ server <- function(input, output, session) {
915
  incProgress(0.7, detail = "Computing residuals...")
916
 
917
  if (input$include_interaction) {
918
- model <- aov(Value ~ Environment + Genotype + Environment:Genotype +
919
- Error(Rep/Block), data = trait_data)
920
  } else {
921
  model <- aov(Value ~ Environment + Genotype + Error(Rep/Block), data = trait_data)
922
  }
@@ -962,8 +1003,8 @@ server <- function(input, output, session) {
962
  caption = paste("ANOVA Table for", input$selected_trait)
963
  ) %>%
964
  formatRound(columns = c("estimate", "std.error", "statistic", "p.value"), digits = 4) %>%
965
- formatStyle("p.value",
966
- backgroundColor = styleInterval(0.05, c("#ffebee", "#e8f5e8")))
967
  }, error = function(e) {
968
  showNotification(paste("Error in ANOVA table:", e$message), type = "error")
969
  return(NULL)
@@ -992,6 +1033,7 @@ server <- function(input, output, session) {
992
  scale_color_manual(values = get_color_palette(rv$color_scheme, length(unique(res_data$Genotype))))
993
 
994
  ggplotly(p, tooltip = c("color", "x", "y"), height = rv$plot_height, width = rv$plot_width)
 
995
  }, error = function(e) {
996
  showNotification(paste("Error in residual plot:", e$message), type = "error")
997
  return(NULL)
@@ -1019,6 +1061,7 @@ server <- function(input, output, session) {
1019
  scale_color_manual(values = get_color_palette(rv$color_scheme, length(unique(res_data$Genotype))))
1020
 
1021
  ggplotly(p, tooltip = c("color", "x", "y"), height = rv$plot_height, width = rv$plot_width)
 
1022
  }, error = function(e) {
1023
  showNotification(paste("Error in Q-Q plot:", e$message), type = "error")
1024
  return(NULL)
@@ -1056,11 +1099,9 @@ server <- function(input, output, session) {
1056
  incProgress(0.7, detail = "Calculating BLUEs...")
1057
 
1058
  if (input$include_interaction) {
1059
- model <- lmer(Value ~ Environment + Genotype + Environment:Genotype +
1060
- (1|Rep) + (1|Block), data = trait_data)
1061
  } else {
1062
- model <- lmer(Value ~ Environment + Genotype + (1|Rep) + (1|Block),
1063
- data = trait_data)
1064
  }
1065
 
1066
  blues <- emmeans(model, ~ Genotype | Environment)
@@ -1101,6 +1142,7 @@ server <- function(input, output, session) {
1101
  scale_color_manual(values = get_color_palette(rv$color_scheme, length(unique(blues_data$Genotype))))
1102
 
1103
  ggplotly(p, tooltip = c("color", "x", "y"), height = rv$plot_height, width = rv$plot_width)
 
1104
  }, error = function(e) {
1105
  showNotification(paste("Error in BLUEs plot:", e$message), type = "error")
1106
  return(NULL)
@@ -1125,6 +1167,7 @@ server <- function(input, output, session) {
1125
  caption = paste("BLUEs for", input$selected_trait)
1126
  ) %>%
1127
  formatRound(columns = c("BLUE", "SE"), digits = 3)
 
1128
  }, error = function(e) {
1129
  showNotification(paste("Error in BLUEs table:", e$message), type = "error")
1130
  return(NULL)
@@ -1167,8 +1210,7 @@ server <- function(input, output, session) {
1167
 
1168
  incProgress(0.6, detail = paste("Fitting model for", trait, "..."))
1169
 
1170
- model <- lmer(Value ~ (1|Genotype) + (1|Environment) + (1|Genotype:Environment) +
1171
- (1|Rep) + (1|Block), data = trait_data)
1172
 
1173
  var_comp <- as.data.frame(VarCorr(model))
1174
  var_comp$Trait <- trait
@@ -1202,7 +1244,9 @@ server <- function(input, output, session) {
1202
  }
1203
 
1204
  incProgress(1, detail = "Complete!")
 
1205
  if (length(herit_results) == 0) return(NULL)
 
1206
  herit_results
1207
  })
1208
  })
@@ -1227,6 +1271,7 @@ server <- function(input, output, session) {
1227
  caption = "Variance Components"
1228
  ) %>%
1229
  formatRound(columns = c("vcov", "sdcor"), digits = 4)
 
1230
  }, error = function(e) {
1231
  showNotification(paste("Error in variance components:", e$message), type = "error")
1232
  return(NULL)
@@ -1258,8 +1303,9 @@ server <- function(input, output, session) {
1258
  caption = "Heritability Estimates"
1259
  ) %>%
1260
  formatRound(columns = c("H2_Broad", "H2_Entry"), digits = 3) %>%
1261
- formatStyle(c("H2_Broad", "H2_Entry"),
1262
  backgroundColor = styleInterval(c(0.3, 0.6), c("#ffebee", "#fff3e0", "#e8f5e8")))
 
1263
  }, error = function(e) {
1264
  showNotification(paste("Error in heritability table:", e$message), type = "error")
1265
  return(NULL)
@@ -1293,6 +1339,7 @@ server <- function(input, output, session) {
1293
  geom_hline(yintercept = c(0.3, 0.6), linetype = "dashed", color = get_color_palette(rv$color_scheme, 1)[2])
1294
 
1295
  ggplotly(p, height = rv$plot_height, width = rv$plot_width)
 
1296
  }, error = function(e) {
1297
  showNotification(paste("Error in heritability plot:", e$message), type = "error")
1298
  return(NULL)
@@ -1339,6 +1386,7 @@ server <- function(input, output, session) {
1339
  incProgress(1, detail = "Complete!")
1340
 
1341
  list(matrix = cor_matrix, table = cor_table, data = trait_data)
 
1342
  }, error = function(e) {
1343
  showNotification(paste("Error in correlation analysis:", e$message), type = "error")
1344
  return(NULL)
@@ -1353,7 +1401,7 @@ server <- function(input, output, session) {
1353
  tryCatch({
1354
  cor_matrix <- correlation_analysis()$matrix
1355
 
1356
- corrplot::corrplot(cor_matrix,
1357
  method = "color",
1358
  type = "upper",
1359
  order = "hclust",
@@ -1365,6 +1413,7 @@ server <- function(input, output, session) {
1365
  title = "Trait Correlation Matrix",
1366
  mar = c(0, 0, 2, 0),
1367
  col = colorRampPalette(get_color_palette(rv$color_scheme, 3))(200))
 
1368
  }, error = function(e) {
1369
  showNotification(paste("Error in correlation heatmap:", e$message), type = "error")
1370
  return(NULL)
@@ -1389,9 +1438,9 @@ server <- function(input, output, session) {
1389
  caption = "Pairwise Trait Correlations"
1390
  ) %>%
1391
  formatRound(columns = c("Correlation", "Abs_Correlation"), digits = 3) %>%
1392
- formatStyle("Correlation",
1393
- backgroundColor = styleInterval(c(-0.7, -0.3, 0.3, 0.7),
1394
- get_color_palette(rv$color_scheme, 5)))
1395
  }, error = function(e) {
1396
  showNotification(paste("Error in correlation table:", e$message), type = "error")
1397
  return(NULL)
@@ -1405,7 +1454,7 @@ server <- function(input, output, session) {
1405
  tryCatch({
1406
  cor_matrix <- correlation_analysis()$matrix
1407
 
1408
- corrplot::corrplot(cor_matrix,
1409
  method = "circle",
1410
  type = "full",
1411
  order = "hclust",
@@ -1414,6 +1463,7 @@ server <- function(input, output, session) {
1414
  title = "Correlation Network",
1415
  mar = c(0, 0, 2, 0),
1416
  col = colorRampPalette(get_color_palette(rv$color_scheme, 3))(200))
 
1417
  }, error = function(e) {
1418
  showNotification(paste("Error in correlation network:", e$message), type = "error")
1419
  return(NULL)
@@ -1444,7 +1494,10 @@ server <- function(input, output, session) {
1444
  return(NULL)
1445
  }
1446
 
1447
- pca_data <- trait_data %>% select(-Genotype) %>% scale()
 
 
 
1448
  pca_result <- prcomp(pca_data, center = FALSE, scale. = FALSE)
1449
 
1450
  pca_scores <- as.data.frame(pca_result$x) %>%
@@ -1463,6 +1516,7 @@ server <- function(input, output, session) {
1463
  incProgress(1, detail = "Complete!")
1464
 
1465
  list(scores = pca_scores, variance = var_explained, loadings = loadings, result = pca_result)
 
1466
  }, error = function(e) {
1467
  showNotification(paste("Error in PCA analysis:", e$message), type = "error")
1468
  return(NULL)
@@ -1491,6 +1545,7 @@ server <- function(input, output, session) {
1491
  scale_color_manual(values = get_color_palette(rv$color_scheme, length(unique(pca_scores$Genotype))))
1492
 
1493
  ggplotly(p, tooltip = c("text", "x", "y"), height = rv$plot_height, width = rv$plot_width)
 
1494
  }, error = function(e) {
1495
  showNotification(paste("Error in PCA plot:", e$message), type = "error")
1496
  return(NULL)
@@ -1519,6 +1574,7 @@ server <- function(input, output, session) {
1519
  )
1520
 
1521
  ggplotly(p, height = rv$plot_height, width = rv$plot_width)
 
1522
  }, error = function(e) {
1523
  showNotification(paste("Error in PCA variance plot:", e$message), type = "error")
1524
  return(NULL)
@@ -1545,6 +1601,7 @@ server <- function(input, output, session) {
1545
  caption = "PCA Loadings"
1546
  ) %>%
1547
  formatRound(columns = -1, digits = 3)
 
1548
  }, error = function(e) {
1549
  showNotification(paste("Error in PCA loadings:", e$message), type = "error")
1550
  return(NULL)
@@ -1569,6 +1626,7 @@ server <- function(input, output, session) {
1569
  caption = "PCA Summary"
1570
  ) %>%
1571
  formatRound(columns = c("Variance", "Prop_Variance", "Cumulative"), digits = 4)
 
1572
  }, error = function(e) {
1573
  showNotification(paste("Error in PCA summary:", e$message), type = "error")
1574
  return(NULL)
@@ -1629,12 +1687,13 @@ server <- function(input, output, session) {
1629
  incProgress(1, detail = "Complete!")
1630
 
1631
  list(
1632
- clusters = cluster_df,
1633
  summary = cluster_summary,
1634
  data = cluster_data,
1635
  method = input$clustering_method,
1636
  hclust = hclust_result
1637
  )
 
1638
  }, error = function(e) {
1639
  showNotification(paste("Error in clustering analysis:", e$message), type = "error")
1640
  return(NULL)
@@ -1692,6 +1751,7 @@ server <- function(input, output, session) {
1692
  }
1693
 
1694
  ggplotly(p, tooltip = c("text", "color"), height = rv$plot_height, width = rv$plot_width)
 
1695
  }, error = function(e) {
1696
  showNotification(paste("Error in cluster plot:", e$message), type = "error")
1697
  return(NULL)
@@ -1705,7 +1765,7 @@ server <- function(input, output, session) {
1705
  tryCatch({
1706
  hclust_result <- clustering_analysis()$hclust
1707
 
1708
- plot(hclust_result,
1709
  main = "Hierarchical Clustering Dendrogram",
1710
  xlab = "Genotypes",
1711
  ylab = "Distance",
@@ -1713,6 +1773,7 @@ server <- function(input, output, session) {
1713
  col = "#000000")
1714
 
1715
  rect.hclust(hclust_result, k = input$n_clusters, border = get_color_palette(rv$color_scheme, 1)[2])
 
1716
  }, error = function(e) {
1717
  showNotification(paste("Error in dendrogram:", e$message), type = "error")
1718
  return(NULL)
@@ -1737,6 +1798,7 @@ server <- function(input, output, session) {
1737
  caption = "Cluster Summary Statistics"
1738
  ) %>%
1739
  formatRound(columns = rv$traits, digits = 3)
 
1740
  }, error = function(e) {
1741
  showNotification(paste("Error in cluster summary:", e$message), type = "error")
1742
  return(NULL)
@@ -1824,21 +1886,19 @@ server <- function(input, output, session) {
1824
  p <- ggplot(stability_params, aes(x = Overall_Mean, y = Ecovalence, color = Genotype, text = Genotype)) +
1825
  geom_point(size = 1, alpha = 0.7) +
1826
  labs(title = paste("Stability Analysis for", input$selected_trait),
1827
- x = "Mean Performance",
1828
- y = "Ecovalence (Wi²)") +
1829
  theme_minimal() +
1830
  theme(
1831
  axis.text = element_text(color = "#000000"),
1832
  axis.title = element_text(color = "#000000"),
1833
  plot.title = element_text(color = "#000000")
1834
  ) +
1835
- geom_hline(yintercept = median(stability_params$Ecovalence),
1836
- linetype = "dashed", color = get_color_palette(rv$color_scheme, 1)[2]) +
1837
- geom_vline(xintercept = median(stability_params$Overall_Mean),
1838
- linetype = "dashed", color = get_color_palette(rv$color_scheme, 1)[2]) +
1839
  scale_color_manual(values = get_color_palette(rv$color_scheme, length(unique(stability_params$Genotype))))
1840
 
1841
  ggplotly(p, tooltip = c("text", "x", "y"), height = rv$plot_height, width = rv$plot_width)
 
1842
  }, error = function(e) {
1843
  showNotification(paste("Error in stability plot:", e$message), type = "error")
1844
  return(NULL)
@@ -1856,8 +1916,7 @@ server <- function(input, output, session) {
1856
  geom_line(size = 1) +
1857
  geom_point(size = 1) +
1858
  labs(title = paste("Genotype × Environment Interaction for", input$selected_trait),
1859
- x = "Environment",
1860
- y = "Mean Value") +
1861
  theme_minimal() +
1862
  theme(
1863
  axis.text = element_text(color = "#000000"),
@@ -1868,6 +1927,7 @@ server <- function(input, output, session) {
1868
  scale_color_manual(values = get_color_palette(rv$color_scheme, length(unique(ammi_data$Genotype))))
1869
 
1870
  ggplotly(p, tooltip = c("color", "x", "y"), height = rv$plot_height, width = rv$plot_width)
 
1871
  }, error = function(e) {
1872
  showNotification(paste("Error in AMMI plot:", e$message), type = "error")
1873
  return(NULL)
@@ -1891,16 +1951,161 @@ server <- function(input, output, session) {
1891
  ),
1892
  caption = paste("Stability Parameters for", input$selected_trait)
1893
  ) %>%
1894
- formatRound(columns = c("Overall_Mean", "CV", "Ecovalence", "Min_Value", "Max_Value", "Range"),
1895
- digits = 3) %>%
1896
- formatStyle("Ecovalence",
1897
- backgroundColor = styleInterval(quantile(stability_analysis()$parameters$Ecovalence, c(0.33, 0.67), na.rm = TRUE),
1898
  get_color_palette(rv$color_scheme, 3)))
 
1899
  }, error = function(e) {
1900
  showNotification(paste("Error in stability table:", e$message), type = "error")
1901
  return(NULL)
1902
  })
1903
  })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1904
  }
1905
 
1906
  # Run the Shiny app
 
20
  library(moments)
21
  library(reshape2)
22
  library(gridExtra)
23
+ library(openxlsx) # Add this library for creating Excel files
24
 
25
  # UI
26
  ui <- fluidPage(
 
43
  --card-bg: #FFFFFF;
44
  }
45
 
46
+ body {
47
+ font-family: 'Poppins', sans-serif;
48
  background: var(--background);
49
  color: var(--dark);
50
  overflow-x: hidden;
 
56
  margin: 0 auto;
57
  }
58
 
59
+ .section {
60
+ margin-bottom: 30px;
61
  background: var(--card-bg);
62
+ padding: 2.5rem;
63
+ border-radius: 15px;
64
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
65
  border: 1px solid rgba(30, 58, 138, 0.2);
66
  }
67
 
68
+ h1, h2, h3 {
69
+ color: var(--primary);
70
  border-bottom: 2px solid var(--secondary);
71
  padding-bottom: 10px;
72
  margin-bottom: 20px;
 
125
  color: white;
126
  }
127
 
128
+ .btn-success {
129
+ background: linear-gradient(135deg, #32CD32, #228B22);
130
+ border: none;
131
+ padding: 1rem 2.5rem;
132
+ border-radius: 8px;
133
+ font-weight: 600;
134
+ color: white;
135
+ transition: all 0.3s;
136
+ box-shadow: 0 4px 8px rgba(0,0,0,0.1);
137
+ margin: 10px;
138
+ }
139
+
140
+ .btn-success:hover {
141
+ background: linear-gradient(135deg, #228B22, #32CD32);
142
+ transform: translateY(-2px);
143
+ box-shadow: 0 6px 12px rgba(50, 205, 50, 0.3);
144
+ color: white;
145
+ }
146
+
147
+ .download-section {
148
+ background: linear-gradient(135deg, #E8F5E8, #F0FFF0);
149
+ padding: 20px;
150
+ border-radius: 10px;
151
+ border: 2px solid var(--success);
152
+ margin: 20px 0;
153
+ text-align: center;
154
+ }
155
+
156
+ .sidebar {
157
  background: var(--card-bg);
158
  color: var(--dark);
159
  padding: 2rem;
 
192
  cursor: pointer;
193
  }
194
 
195
+ .nav-tabs .nav-link:hover,
196
+ .nav-tabs .nav-link.active {
197
  color: white;
198
  background: linear-gradient(90deg, var(--primary), var(--info));
199
  transform: translateX(5px);
 
329
  }
330
  "))
331
  ),
332
+
333
  div(
334
  class = "app-wrapper",
335
  div(
 
342
  class = "sidebar-content",
343
  selectInput("selected_trait", "Select Trait for Analysis", choices = c(), width = "100%"),
344
  checkboxInput("include_interaction", "Include G×E Interaction", value = FALSE),
345
+ hr(style = "border-color: rgba(255,255,255,0.1);"),
346
+
347
+ # Download Section
348
+ div(
349
+ class = "download-section",
350
+ h4("📥 Download All Results", style = "color: var(--success); margin-top: 0;"),
351
+ downloadButton("download_all_results", "Download Complete Analysis", class = "btn-success"),
352
+ p("Excel file with all analysis sheets", style = "margin-top: 10px; font-size: 12px; color: var(--dark);")
353
+ ),
354
+
355
  hr(style = "border-color: rgba(255,255,255,0.1);"),
356
  div(
357
  style = "padding: 15px; color: var(--light); font-size: 12px; text-align: center;",
 
360
  )
361
  )
362
  ),
363
+
364
  div(
365
  class = "main-content",
366
  tabsetPanel(
367
  id = "main_tabs",
368
+
369
  tabPanel("Data Upload", value = "upload",
370
  div(
371
  class = "section",
 
374
  class = "upload-container",
375
  div(class = "upload-icon", icon("cloud-upload-alt", class = "fas")),
376
  h3("📁 Upload your Excel/CSV file", style = "color: var(--primary);"),
377
+ fileInput("data_file", NULL,
378
  accept = c(".xlsx", ".xls", ".csv"),
379
+ buttonLabel = "Browse Files",
380
  placeholder = "No file selected"),
381
  p("📝 Supported formats: .xlsx, .xls, .csv", style = "color: var(--light); font-size: 14px;")
382
  ),
 
384
  div(id = "data_preview_section", class = "hidden",
385
  h3("📊 Data Overview"),
386
  fluidRow(
387
+ column(3, div(class = "status-card", icon("columns", class = "fas"), h4(textOutput("n_vars")), p("Variables"))),
388
+ column(3, div(class = "status-card", icon("list", class = "fas"), h4(textOutput("n_obs")), p("Observations"))),
389
+ column(3, div(class = "status-card", icon("dna", class = "fas"), h4(textOutput("n_geno")), p("Genotypes"))),
390
+ column(3, div(class = "status-card", icon("globe", class = "fas"), h4(textOutput("n_env")), p("Environments")))
 
 
 
 
 
 
 
 
 
 
 
 
391
  ),
392
  DTOutput("data_preview_table")
393
  )
394
  )
395
  ),
396
+
397
  tabPanel("Descriptive Statistics", value = "descriptives",
398
  div(
399
  class = "section",
 
405
  DTOutput("descriptives_table"),
406
  div(class = "insights",
407
  h4("💡 Interpretation"),
408
+ p("Descriptive statistics show central tendency and variability. CV > 20% indicates high variability. Check for outliers and data distribution normality.")
409
+ )
410
  )
411
  ),
412
+
413
  tabPanel("ANOVA", value = "anova",
414
  div(
415
  class = "section",
416
  h2("🧮 Analysis of Variance (ANOVA)"),
417
+ div(class = "chart-container",
418
  h4("ANOVA Table"),
419
+ DTOutput("anova_table")
420
+ ),
421
  fluidRow(
422
  column(6, div(class = "chart-container", plotlyOutput("residual_plot", height = "auto"))),
423
  column(6, div(class = "chart-container", plotlyOutput("qq_plot", height = "auto")))
424
  ),
425
  div(class = "insights",
426
  h4("💡 Interpretation"),
427
+ p("ANOVA tests significance of effects. P < 0.05 indicates significant differences. Check residual plots for model assumptions.")
428
+ )
429
  )
430
  ),
431
+
432
  tabPanel("Mixed Models", value = "blues",
433
  div(
434
  class = "section",
 
437
  DTOutput("blues_table"),
438
  div(class = "insights",
439
  h4("💡 Interpretation"),
440
+ p("BLUEs (Best Linear Unbiased Estimators) account for experimental design. Parallel lines indicate no G×E interaction; crossing lines suggest interaction.")
441
+ )
442
  )
443
  ),
444
+
445
  tabPanel("Heritability", value = "heritability",
446
  div(
447
  class = "section",
448
  h2("🧬 Heritability Analysis"),
449
  fluidRow(
450
+ column(6, div(class = "chart-container", h4("Variance Components"), DTOutput("variance_components"))),
451
+ column(6, div(class = "chart-container", h4("Heritability Estimates"), DTOutput("heritability_table")))
 
 
 
 
452
  ),
453
  div(class = "chart-container", plotlyOutput("heritability_plot", height = "auto")),
454
  div(class = "insights",
455
  h4("💡 Interpretation"),
456
+ p("Broad-sense heritability (H²) = genetic variance / total variance. Values > 0.6 indicate high heritability, suitable for selection.")
457
+ )
458
  )
459
  ),
460
+
461
  tabPanel("Correlations", value = "correlations",
462
  div(
463
  class = "section",
 
469
  div(class = "chart-container", plotOutput("correlation_network", height = "auto")),
470
  div(class = "insights",
471
  h4("💡 Interpretation"),
472
+ p("Correlation matrix shows relationships between traits. Values near ±1 indicate strong relationships. Use for indirect selection strategies.")
473
+ )
474
  )
475
  ),
476
+
477
  tabPanel("Clustering", value = "clustering",
478
  div(
479
  class = "section",
480
  h2("🌐 Genotype Clustering"),
481
  fluidRow(
482
+ column(4,
483
  numericInput("n_clusters", "Number of Clusters:", value = 3, min = 2, max = 10),
484
+ selectInput("clustering_method", "Clustering Method:",
485
+ choices = c("K-means" = "kmeans", "Hierarchical" = "hierarchical"))
486
+ ),
487
  column(8, div(class = "chart-container", plotlyOutput("cluster_plot", height = "auto")))
488
  ),
489
  fluidRow(
 
492
  ),
493
  div(class = "insights",
494
  h4("💡 Interpretation"),
495
+ p("Clustering groups similar genotypes based on trait performance. Use for identifying genetic groups and breeding strategies.")
496
+ )
497
  )
498
  ),
499
+
500
  tabPanel("PCA", value = "pca",
501
  div(
502
  class = "section",
 
511
  ),
512
  div(class = "insights",
513
  h4("💡 Interpretation"),
514
+ p("PCA reduces dimensionality while preserving variance. First few PCs explain most variation. Loadings show trait contributions to each PC.")
515
+ )
516
  )
517
  ),
518
+
519
  tabPanel("Stability", value = "stability",
520
  div(
521
  class = "section",
 
527
  DTOutput("stability_table"),
528
  div(class = "insights",
529
  h4("💡 Interpretation"),
530
+ p("Stability parameters identify genotypes with consistent performance across environments. Low Ecovalence (Wi²) and high yield indicate stable, high-performing genotypes.")
531
+ )
532
  )
533
  ),
534
+
535
  tabPanel("Customization", value = "customization",
536
  div(
537
  class = "section",
 
540
  class = "chart-container",
541
  h3("Adjust Plot Dimensions"),
542
  fluidRow(
543
+ column(6, numericInput("plot_height", "Plot Height (px):", value = 600, min = 300, max = 1200, step = 50)),
544
+ column(6, numericInput("plot_width", "Plot Width (px):", value = 800, min = 400, max = 1600, step = 50))
 
 
545
  ),
546
  h3("Select Color Scheme"),
547
  selectInput("color_scheme", "Color Scheme:",
 
555
  ),
556
  div(class = "insights",
557
  h4("💡 Instructions"),
558
+ p("Adjust the height and width of all plots using the sliders. Choose a color scheme to update the appearance of plots. Click 'Apply Customization' to update the visualizations.")
559
+ )
560
  )
561
  )
562
  )
 
616
  # Check required columns
617
  required_cols <- c("Genotype", "Environment", "Rep", "Block")
618
  missing_cols <- setdiff(required_cols, names(data))
619
+
620
  if (length(missing_cols) > 0) {
621
+ validation$errors <- c(validation$errors, paste("Missing required columns:", paste(missing_cols, collapse = ", ")))
 
622
  }
623
 
624
  # Check data types and convert if necessary
 
654
  if ("Genotype" %in% names(data)) {
655
  n_geno <- length(unique(data$Genotype))
656
  if (n_geno < 3) {
657
+ validation$errors <- c(validation$errors, paste("Insufficient genotypes (", n_geno, "); need at least 3"))
 
658
  }
659
  }
660
 
661
  if ("Environment" %in% names(data)) {
662
  n_env <- length(unique(data$Environment))
663
  if (n_env < 2) {
664
+ validation$errors <- c(validation$errors, paste("Insufficient environments (", n_env, "); need at least 2"))
 
665
  }
666
  }
667
 
 
672
  filter(Missing > 0)
673
 
674
  if (nrow(missing_summary) > 0) {
675
+ validation$warnings <- c(validation$warnings, paste("Variables with missing data:", paste(missing_summary$Variable, collapse = ", ")))
 
 
676
  }
677
 
678
  # Check for balanced design
 
694
  if (length(numeric_traits) == 0) {
695
  validation$errors <- c(validation$errors, "No numeric trait columns found starting from column 10")
696
  } else {
697
+ validation$success <- c(validation$success, paste("Found", length(numeric_traits), "numeric trait columns starting from column 10"))
 
698
  }
699
  } else {
700
  validation$errors <- c(validation$errors, "Input data has fewer than 10 columns")
 
736
  incProgress(0.6, detail = "Updating interface...")
737
 
738
  # Update trait selection
739
+ updateSelectInput(session, "selected_trait",
740
+ choices = rv$traits,
741
  selected = if(length(rv$traits) > 0) rv$traits[1] else NULL)
742
 
743
  # Show data preview
 
748
  # Update summary statistics
749
  output$n_vars <- renderText({ ncol(rv$data) })
750
  output$n_obs <- renderText({ nrow(rv$data) })
751
+ output$n_geno <- renderText({
752
+ if("Genotype" %in% names(rv$data)) length(unique(rv$data$Genotype)) else "N/A"
753
  })
754
+ output$n_env <- renderText({
755
+ if("Environment" %in% names(rv$data)) length(unique(rv$data$Environment)) else "N/A"
756
  })
757
 
758
  incProgress(1, detail = "Complete!")
 
761
  if (length(validation_results$errors) > 0) {
762
  showNotification(paste(validation_results$errors, collapse = "; "), type = "error")
763
  }
764
+
765
  if (length(validation_results$warnings) > 0) {
766
  showNotification(paste(validation_results$warnings, collapse = "; "), type = "warning")
767
  }
768
+
769
  output$upload_status <- renderUI({
770
+ div(class = "success-message",
771
+ icon("check-circle"),
772
  paste("Successfully loaded", nrow(rv$data), "observations with", length(rv$traits), "traits"))
773
  })
774
 
 
776
 
777
  }, error = function(e) {
778
  output$upload_status <- renderUI({
779
+ div(class = "error-message",
780
+ icon("exclamation-triangle"),
781
  paste("Error:", e$message))
782
  })
783
  showNotification(paste("Error:", e$message), type = "error")
 
831
 
832
  incProgress(1, detail = "Complete!")
833
  stats
834
+
835
  }, error = function(e) {
836
  showNotification(paste("Error in descriptive statistics:", e$message), type = "error")
837
  return(NULL)
 
842
  # Descriptive statistics table
843
  output$descriptives_table <- renderDT({
844
  req(descriptive_stats())
 
845
  datatable(
846
  descriptive_stats(),
847
  extensions = 'Buttons',
 
860
  # Descriptive statistics plot
861
  output$descriptives_plot <- renderPlotly({
862
  req(rv$data, input$selected_trait)
 
863
  if (!input$selected_trait %in% rv$traits) return(NULL)
864
 
865
  tryCatch({
 
884
  scale_color_manual(values = get_color_palette(rv$color_scheme, length(unique(rv$data$Genotype))))
885
 
886
  ggplotly(p, tooltip = c("x", "y", "color"), height = rv$plot_height, width = rv$plot_width)
887
+
888
  }, error = function(e) {
889
  showNotification(paste("Error in descriptive plot:", e$message), type = "error")
890
  return(NULL)
 
894
  # Distribution plot (histogram with density)
895
  output$distribution_plot <- renderPlotly({
896
  req(rv$data, input$selected_trait)
 
897
  if (!input$selected_trait %in% rv$traits) return(NULL)
898
 
899
  tryCatch({
 
919
  )
920
 
921
  ggplotly(p, height = rv$plot_height, width = rv$plot_width)
922
+
923
  }, error = function(e) {
924
  showNotification(paste("Error in distribution plot:", e$message), type = "error")
925
  return(NULL)
 
957
  incProgress(0.7, detail = "Computing residuals...")
958
 
959
  if (input$include_interaction) {
960
+ model <- aov(Value ~ Environment + Genotype + Environment:Genotype + Error(Rep/Block), data = trait_data)
 
961
  } else {
962
  model <- aov(Value ~ Environment + Genotype + Error(Rep/Block), data = trait_data)
963
  }
 
1003
  caption = paste("ANOVA Table for", input$selected_trait)
1004
  ) %>%
1005
  formatRound(columns = c("estimate", "std.error", "statistic", "p.value"), digits = 4) %>%
1006
+ formatStyle("p.value", backgroundColor = styleInterval(0.05, c("#ffebee", "#e8f5e8")))
1007
+
1008
  }, error = function(e) {
1009
  showNotification(paste("Error in ANOVA table:", e$message), type = "error")
1010
  return(NULL)
 
1033
  scale_color_manual(values = get_color_palette(rv$color_scheme, length(unique(res_data$Genotype))))
1034
 
1035
  ggplotly(p, tooltip = c("color", "x", "y"), height = rv$plot_height, width = rv$plot_width)
1036
+
1037
  }, error = function(e) {
1038
  showNotification(paste("Error in residual plot:", e$message), type = "error")
1039
  return(NULL)
 
1061
  scale_color_manual(values = get_color_palette(rv$color_scheme, length(unique(res_data$Genotype))))
1062
 
1063
  ggplotly(p, tooltip = c("color", "x", "y"), height = rv$plot_height, width = rv$plot_width)
1064
+
1065
  }, error = function(e) {
1066
  showNotification(paste("Error in Q-Q plot:", e$message), type = "error")
1067
  return(NULL)
 
1099
  incProgress(0.7, detail = "Calculating BLUEs...")
1100
 
1101
  if (input$include_interaction) {
1102
+ model <- lmer(Value ~ Environment + Genotype + Environment:Genotype + (1|Rep) + (1|Block), data = trait_data)
 
1103
  } else {
1104
+ model <- lmer(Value ~ Environment + Genotype + (1|Rep) + (1|Block), data = trait_data)
 
1105
  }
1106
 
1107
  blues <- emmeans(model, ~ Genotype | Environment)
 
1142
  scale_color_manual(values = get_color_palette(rv$color_scheme, length(unique(blues_data$Genotype))))
1143
 
1144
  ggplotly(p, tooltip = c("color", "x", "y"), height = rv$plot_height, width = rv$plot_width)
1145
+
1146
  }, error = function(e) {
1147
  showNotification(paste("Error in BLUEs plot:", e$message), type = "error")
1148
  return(NULL)
 
1167
  caption = paste("BLUEs for", input$selected_trait)
1168
  ) %>%
1169
  formatRound(columns = c("BLUE", "SE"), digits = 3)
1170
+
1171
  }, error = function(e) {
1172
  showNotification(paste("Error in BLUEs table:", e$message), type = "error")
1173
  return(NULL)
 
1210
 
1211
  incProgress(0.6, detail = paste("Fitting model for", trait, "..."))
1212
 
1213
+ model <- lmer(Value ~ (1|Genotype) + (1|Environment) + (1|Genotype:Environment) + (1|Rep) + (1|Block), data = trait_data)
 
1214
 
1215
  var_comp <- as.data.frame(VarCorr(model))
1216
  var_comp$Trait <- trait
 
1244
  }
1245
 
1246
  incProgress(1, detail = "Complete!")
1247
+
1248
  if (length(herit_results) == 0) return(NULL)
1249
+
1250
  herit_results
1251
  })
1252
  })
 
1271
  caption = "Variance Components"
1272
  ) %>%
1273
  formatRound(columns = c("vcov", "sdcor"), digits = 4)
1274
+
1275
  }, error = function(e) {
1276
  showNotification(paste("Error in variance components:", e$message), type = "error")
1277
  return(NULL)
 
1303
  caption = "Heritability Estimates"
1304
  ) %>%
1305
  formatRound(columns = c("H2_Broad", "H2_Entry"), digits = 3) %>%
1306
+ formatStyle(c("H2_Broad", "H2_Entry"),
1307
  backgroundColor = styleInterval(c(0.3, 0.6), c("#ffebee", "#fff3e0", "#e8f5e8")))
1308
+
1309
  }, error = function(e) {
1310
  showNotification(paste("Error in heritability table:", e$message), type = "error")
1311
  return(NULL)
 
1339
  geom_hline(yintercept = c(0.3, 0.6), linetype = "dashed", color = get_color_palette(rv$color_scheme, 1)[2])
1340
 
1341
  ggplotly(p, height = rv$plot_height, width = rv$plot_width)
1342
+
1343
  }, error = function(e) {
1344
  showNotification(paste("Error in heritability plot:", e$message), type = "error")
1345
  return(NULL)
 
1386
  incProgress(1, detail = "Complete!")
1387
 
1388
  list(matrix = cor_matrix, table = cor_table, data = trait_data)
1389
+
1390
  }, error = function(e) {
1391
  showNotification(paste("Error in correlation analysis:", e$message), type = "error")
1392
  return(NULL)
 
1401
  tryCatch({
1402
  cor_matrix <- correlation_analysis()$matrix
1403
 
1404
+ corrplot::corrplot(cor_matrix,
1405
  method = "color",
1406
  type = "upper",
1407
  order = "hclust",
 
1413
  title = "Trait Correlation Matrix",
1414
  mar = c(0, 0, 2, 0),
1415
  col = colorRampPalette(get_color_palette(rv$color_scheme, 3))(200))
1416
+
1417
  }, error = function(e) {
1418
  showNotification(paste("Error in correlation heatmap:", e$message), type = "error")
1419
  return(NULL)
 
1438
  caption = "Pairwise Trait Correlations"
1439
  ) %>%
1440
  formatRound(columns = c("Correlation", "Abs_Correlation"), digits = 3) %>%
1441
+ formatStyle("Correlation",
1442
+ backgroundColor = styleInterval(c(-0.7, -0.3, 0.3, 0.7), get_color_palette(rv$color_scheme, 5)))
1443
+
1444
  }, error = function(e) {
1445
  showNotification(paste("Error in correlation table:", e$message), type = "error")
1446
  return(NULL)
 
1454
  tryCatch({
1455
  cor_matrix <- correlation_analysis()$matrix
1456
 
1457
+ corrplot::corrplot(cor_matrix,
1458
  method = "circle",
1459
  type = "full",
1460
  order = "hclust",
 
1463
  title = "Correlation Network",
1464
  mar = c(0, 0, 2, 0),
1465
  col = colorRampPalette(get_color_palette(rv$color_scheme, 3))(200))
1466
+
1467
  }, error = function(e) {
1468
  showNotification(paste("Error in correlation network:", e$message), type = "error")
1469
  return(NULL)
 
1494
  return(NULL)
1495
  }
1496
 
1497
+ pca_data <- trait_data %>%
1498
+ select(-Genotype) %>%
1499
+ scale()
1500
+
1501
  pca_result <- prcomp(pca_data, center = FALSE, scale. = FALSE)
1502
 
1503
  pca_scores <- as.data.frame(pca_result$x) %>%
 
1516
  incProgress(1, detail = "Complete!")
1517
 
1518
  list(scores = pca_scores, variance = var_explained, loadings = loadings, result = pca_result)
1519
+
1520
  }, error = function(e) {
1521
  showNotification(paste("Error in PCA analysis:", e$message), type = "error")
1522
  return(NULL)
 
1545
  scale_color_manual(values = get_color_palette(rv$color_scheme, length(unique(pca_scores$Genotype))))
1546
 
1547
  ggplotly(p, tooltip = c("text", "x", "y"), height = rv$plot_height, width = rv$plot_width)
1548
+
1549
  }, error = function(e) {
1550
  showNotification(paste("Error in PCA plot:", e$message), type = "error")
1551
  return(NULL)
 
1574
  )
1575
 
1576
  ggplotly(p, height = rv$plot_height, width = rv$plot_width)
1577
+
1578
  }, error = function(e) {
1579
  showNotification(paste("Error in PCA variance plot:", e$message), type = "error")
1580
  return(NULL)
 
1601
  caption = "PCA Loadings"
1602
  ) %>%
1603
  formatRound(columns = -1, digits = 3)
1604
+
1605
  }, error = function(e) {
1606
  showNotification(paste("Error in PCA loadings:", e$message), type = "error")
1607
  return(NULL)
 
1626
  caption = "PCA Summary"
1627
  ) %>%
1628
  formatRound(columns = c("Variance", "Prop_Variance", "Cumulative"), digits = 4)
1629
+
1630
  }, error = function(e) {
1631
  showNotification(paste("Error in PCA summary:", e$message), type = "error")
1632
  return(NULL)
 
1687
  incProgress(1, detail = "Complete!")
1688
 
1689
  list(
1690
+ clusters = cluster_df,
1691
  summary = cluster_summary,
1692
  data = cluster_data,
1693
  method = input$clustering_method,
1694
  hclust = hclust_result
1695
  )
1696
+
1697
  }, error = function(e) {
1698
  showNotification(paste("Error in clustering analysis:", e$message), type = "error")
1699
  return(NULL)
 
1751
  }
1752
 
1753
  ggplotly(p, tooltip = c("text", "color"), height = rv$plot_height, width = rv$plot_width)
1754
+
1755
  }, error = function(e) {
1756
  showNotification(paste("Error in cluster plot:", e$message), type = "error")
1757
  return(NULL)
 
1765
  tryCatch({
1766
  hclust_result <- clustering_analysis()$hclust
1767
 
1768
+ plot(hclust_result,
1769
  main = "Hierarchical Clustering Dendrogram",
1770
  xlab = "Genotypes",
1771
  ylab = "Distance",
 
1773
  col = "#000000")
1774
 
1775
  rect.hclust(hclust_result, k = input$n_clusters, border = get_color_palette(rv$color_scheme, 1)[2])
1776
+
1777
  }, error = function(e) {
1778
  showNotification(paste("Error in dendrogram:", e$message), type = "error")
1779
  return(NULL)
 
1798
  caption = "Cluster Summary Statistics"
1799
  ) %>%
1800
  formatRound(columns = rv$traits, digits = 3)
1801
+
1802
  }, error = function(e) {
1803
  showNotification(paste("Error in cluster summary:", e$message), type = "error")
1804
  return(NULL)
 
1886
  p <- ggplot(stability_params, aes(x = Overall_Mean, y = Ecovalence, color = Genotype, text = Genotype)) +
1887
  geom_point(size = 1, alpha = 0.7) +
1888
  labs(title = paste("Stability Analysis for", input$selected_trait),
1889
+ x = "Mean Performance", y = "Ecovalence (Wi²)") +
 
1890
  theme_minimal() +
1891
  theme(
1892
  axis.text = element_text(color = "#000000"),
1893
  axis.title = element_text(color = "#000000"),
1894
  plot.title = element_text(color = "#000000")
1895
  ) +
1896
+ geom_hline(yintercept = median(stability_params$Ecovalence), linetype = "dashed", color = get_color_palette(rv$color_scheme, 1)[2]) +
1897
+ geom_vline(xintercept = median(stability_params$Overall_Mean), linetype = "dashed", color = get_color_palette(rv$color_scheme, 1)[2]) +
 
 
1898
  scale_color_manual(values = get_color_palette(rv$color_scheme, length(unique(stability_params$Genotype))))
1899
 
1900
  ggplotly(p, tooltip = c("text", "x", "y"), height = rv$plot_height, width = rv$plot_width)
1901
+
1902
  }, error = function(e) {
1903
  showNotification(paste("Error in stability plot:", e$message), type = "error")
1904
  return(NULL)
 
1916
  geom_line(size = 1) +
1917
  geom_point(size = 1) +
1918
  labs(title = paste("Genotype × Environment Interaction for", input$selected_trait),
1919
+ x = "Environment", y = "Mean Value") +
 
1920
  theme_minimal() +
1921
  theme(
1922
  axis.text = element_text(color = "#000000"),
 
1927
  scale_color_manual(values = get_color_palette(rv$color_scheme, length(unique(ammi_data$Genotype))))
1928
 
1929
  ggplotly(p, tooltip = c("color", "x", "y"), height = rv$plot_height, width = rv$plot_width)
1930
+
1931
  }, error = function(e) {
1932
  showNotification(paste("Error in AMMI plot:", e$message), type = "error")
1933
  return(NULL)
 
1951
  ),
1952
  caption = paste("Stability Parameters for", input$selected_trait)
1953
  ) %>%
1954
+ formatRound(columns = c("Overall_Mean", "CV", "Ecovalence", "Min_Value", "Max_Value", "Range"), digits = 3) %>%
1955
+ formatStyle("Ecovalence",
1956
+ backgroundColor = styleInterval(quantile(stability_analysis()$parameters$Ecovalence, c(0.33, 0.67), na.rm = TRUE),
 
1957
  get_color_palette(rv$color_scheme, 3)))
1958
+
1959
  }, error = function(e) {
1960
  showNotification(paste("Error in stability table:", e$message), type = "error")
1961
  return(NULL)
1962
  })
1963
  })
1964
+
1965
+ # Download all results as Excel file
1966
+ output$download_all_results <- downloadHandler(
1967
+ filename = function() {
1968
+ paste0("Phenotypic_Analysis_Results_", format(Sys.time(), "%Y%m%d_%H%M%S"), ".xlsx")
1969
+ },
1970
+ content = function(file) {
1971
+ withProgress(message = 'Preparing download...', value = 0, {
1972
+
1973
+ tryCatch({
1974
+ # Create a new workbook
1975
+ wb <- createWorkbook()
1976
+
1977
+ incProgress(0.1, detail = "Creating Data Summary sheet...")
1978
+
1979
+ # Sheet 1: Data Summary
1980
+ if (!is.null(rv$data)) {
1981
+ addWorksheet(wb, "Data_Summary")
1982
+ summary_info <- data.frame(
1983
+ Metric = c("Total Observations", "Total Variables", "Number of Genotypes", "Number of Environments", "Number of Traits", "Analysis Date"),
1984
+ Value = c(
1985
+ nrow(rv$data),
1986
+ ncol(rv$data),
1987
+ if("Genotype" %in% names(rv$data)) length(unique(rv$data$Genotype)) else "N/A",
1988
+ if("Environment" %in% names(rv$data)) length(unique(rv$data$Environment)) else "N/A",
1989
+ length(rv$traits),
1990
+ format(Sys.time(), "%Y-%m-%d %H:%M:%S")
1991
+ )
1992
+ )
1993
+ writeData(wb, "Data_Summary", summary_info)
1994
+ }
1995
+
1996
+ incProgress(0.2, detail = "Adding Descriptive Statistics...")
1997
+
1998
+ # Sheet 2: Descriptive Statistics
1999
+ if (!is.null(descriptive_stats())) {
2000
+ addWorksheet(wb, "Descriptive_Statistics")
2001
+ writeData(wb, "Descriptive_Statistics", descriptive_stats())
2002
+ }
2003
+
2004
+ incProgress(0.3, detail = "Adding ANOVA results...")
2005
+
2006
+ # Sheet 3: ANOVA Results
2007
+ if (!is.null(anova_analysis())) {
2008
+ addWorksheet(wb, "ANOVA_Results")
2009
+ anova_df <- broom::tidy(anova_analysis()$simple_model)
2010
+ writeData(wb, "ANOVA_Results", anova_df)
2011
+ }
2012
+
2013
+ incProgress(0.4, detail = "Adding BLUEs...")
2014
+
2015
+ # Sheet 4: BLUEs
2016
+ if (!is.null(mixed_model_analysis())) {
2017
+ addWorksheet(wb, "BLUEs")
2018
+ writeData(wb, "BLUEs", mixed_model_analysis()$blues)
2019
+ }
2020
+
2021
+ incProgress(0.5, detail = "Adding Heritability results...")
2022
+
2023
+ # Sheet 5: Heritability - Variance Components
2024
+ if (!is.null(heritability_analysis())) {
2025
+ addWorksheet(wb, "Variance_Components")
2026
+ all_var_comp <- do.call(rbind, lapply(heritability_analysis(), function(x) x$variance_components))
2027
+ writeData(wb, "Variance_Components", all_var_comp)
2028
+
2029
+ # Sheet 6: Heritability Estimates
2030
+ addWorksheet(wb, "Heritability_Estimates")
2031
+ herit_summary <- data.frame(
2032
+ Trait = names(heritability_analysis()),
2033
+ H2_Broad = sapply(heritability_analysis(), function(x) round(x$h2_broad, 3)),
2034
+ H2_Entry = sapply(heritability_analysis(), function(x) round(x$h2_entry, 3)),
2035
+ stringsAsFactors = FALSE
2036
+ )
2037
+ writeData(wb, "Heritability_Estimates", herit_summary)
2038
+ }
2039
+
2040
+ incProgress(0.6, detail = "Adding Correlation analysis...")
2041
+
2042
+ # Sheet 7: Correlation Matrix
2043
+ if (!is.null(correlation_analysis())) {
2044
+ addWorksheet(wb, "Correlation_Matrix")
2045
+ cor_matrix_df <- as.data.frame(correlation_analysis()$matrix)
2046
+ cor_matrix_df <- rownames_to_column(cor_matrix_df, "Trait")
2047
+ writeData(wb, "Correlation_Matrix", cor_matrix_df)
2048
+
2049
+ # Sheet 8: Pairwise Correlations
2050
+ addWorksheet(wb, "Pairwise_Correlations")
2051
+ writeData(wb, "Pairwise_Correlations", correlation_analysis()$table)
2052
+ }
2053
+
2054
+ incProgress(0.7, detail = "Adding PCA results...")
2055
+
2056
+ # Sheet 9: PCA Scores
2057
+ if (!is.null(pca_analysis())) {
2058
+ addWorksheet(wb, "PCA_Scores")
2059
+ writeData(wb, "PCA_Scores", pca_analysis()$scores)
2060
+
2061
+ # Sheet 10: PCA Variance Explained
2062
+ addWorksheet(wb, "PCA_Variance")
2063
+ writeData(wb, "PCA_Variance", pca_analysis()$variance)
2064
+
2065
+ # Sheet 11: PCA Loadings
2066
+ addWorksheet(wb, "PCA_Loadings")
2067
+ writeData(wb, "PCA_Loadings", pca_analysis()$loadings)
2068
+ }
2069
+
2070
+ incProgress(0.8, detail = "Adding Clustering results...")
2071
+
2072
+ # Sheet 12: Clustering Results
2073
+ if (!is.null(clustering_analysis())) {
2074
+ addWorksheet(wb, "Cluster_Assignments")
2075
+ writeData(wb, "Cluster_Assignments", clustering_analysis()$clusters)
2076
+
2077
+ # Sheet 13: Cluster Summary
2078
+ addWorksheet(wb, "Cluster_Summary")
2079
+ writeData(wb, "Cluster_Summary", clustering_analysis()$summary)
2080
+ }
2081
+
2082
+ incProgress(0.9, detail = "Adding Stability analysis...")
2083
+
2084
+ # Sheet 14: Stability Parameters
2085
+ if (!is.null(stability_analysis())) {
2086
+ addWorksheet(wb, "Stability_Parameters")
2087
+ writeData(wb, "Stability_Parameters", stability_analysis()$parameters)
2088
+
2089
+ # Sheet 15: GxE Interaction Data
2090
+ addWorksheet(wb, "GxE_Interaction")
2091
+ writeData(wb, "GxE_Interaction", stability_analysis()$ammi_data)
2092
+ }
2093
+
2094
+ incProgress(0.95, detail = "Finalizing workbook...")
2095
+
2096
+ # Save the workbook
2097
+ saveWorkbook(wb, file, overwrite = TRUE)
2098
+
2099
+ incProgress(1, detail = "Download ready!")
2100
+
2101
+ showNotification("All results downloaded successfully!", type = "message", duration = 5)
2102
+
2103
+ }, error = function(e) {
2104
+ showNotification(paste("Error creating download file:", e$message), type = "error", duration = 10)
2105
+ })
2106
+ })
2107
+ }
2108
+ )
2109
  }
2110
 
2111
  # Run the Shiny app