International Rice Research Institute commited on
Commit
69c1b17
·
verified ·
1 Parent(s): 975d741

Update app.R

Browse files
Files changed (1) hide show
  1. app.R +1589 -617
app.R CHANGED
@@ -1,7 +1,3 @@
1
- # UI with updated styling, including separate Color Selection Dashboard
2
- # UI with updated styling to enable scrolling
3
-
4
-
5
  library(shiny)
6
  library(shinyjs)
7
  library(tidyverse)
@@ -12,25 +8,38 @@ library(emmeans)
12
  library(plotly)
13
  library(shinyWidgets)
14
  library(ggplot2)
15
- library(colourpicker)
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  ui <- fluidPage(
17
  useShinyjs(),
18
  tags$head(
19
  tags$meta(charset = "UTF-8"),
20
- tags$title("Phenotypic Analysis Dashboard"),
21
  tags$link(rel = "stylesheet", href = "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"),
22
  tags$style(HTML("
23
  :root {
24
- --primary: #1E3A8A; /* Dark blue for tabs */
25
- --secondary: #6B8E23; /* Olive green */
26
- --success: #32CD32; /* Lime Green */
27
- --info: #4169E1; /* Royal Blue */
28
- --warning: #FF8C00; /* Dark Orange */
29
- --danger: #DC143C; /* Crimson */
30
- --light: #D1D5DB; /* Grey for tab text */
31
- --dark: #2F4F4F; /* Dark Slate Gray */
32
- --background: #FFFFFF; /* White background */
33
- --card-bg: #FFFFFF; /* White for cards */
34
  }
35
 
36
  body {
@@ -38,8 +47,6 @@ ui <- fluidPage(
38
  background: var(--background);
39
  color: var(--dark);
40
  overflow-x: hidden;
41
- overflow-y: auto; /* Enable vertical scrolling */
42
- margin: 0;
43
  }
44
 
45
  .container-fluid {
@@ -48,12 +55,6 @@ ui <- fluidPage(
48
  margin: 0 auto;
49
  }
50
 
51
- .app-wrapper {
52
- display: flex;
53
- flex-direction: column;
54
- min-height: 100vh; /* Ensure wrapper takes at least full viewport height */
55
- }
56
-
57
  .section {
58
  margin-bottom: 30px;
59
  background: var(--card-bg);
@@ -63,6 +64,14 @@ ui <- fluidPage(
63
  border: 1px solid rgba(30, 58, 138, 0.2);
64
  }
65
 
 
 
 
 
 
 
 
 
66
  .chart-container {
67
  position: relative;
68
  margin-bottom: 20px;
@@ -71,7 +80,6 @@ ui <- fluidPage(
71
  background: var(--card-bg);
72
  padding: 1.5rem;
73
  border: 1px solid rgba(30, 58, 138, 0.2);
74
- min-height: 400px;
75
  }
76
 
77
  .insights {
@@ -120,9 +128,12 @@ ui <- fluidPage(
120
  background: var(--card-bg);
121
  color: var(--dark);
122
  padding: 2rem;
123
- width: 280px; /* Fixed width for sidebar */
 
 
124
  box-shadow: 5px 0 15px rgba(0,0,0,0.1);
125
  border-right: 1px solid var(--primary);
 
126
  }
127
 
128
  .sidebar-header {
@@ -139,7 +150,7 @@ ui <- fluidPage(
139
  padding: 15px;
140
  }
141
 
142
- .nav-link {
143
  color: var(--dark);
144
  padding: 12px 15px;
145
  border-radius: 8px;
@@ -148,26 +159,30 @@ ui <- fluidPage(
148
  align-items: center;
149
  transition: all 0.3s;
150
  background: #F5F5F5;
 
 
151
  }
152
 
153
- .nav-link:hover, .nav-link.active {
154
  color: white;
155
  background: linear-gradient(90deg, var(--primary), var(--info));
156
  transform: translateX(5px);
157
  box-shadow: 0 4px 8px rgba(30, 58, 138, 0.3);
 
158
  }
159
 
160
- .nav-link i {
161
  margin-right: 10px;
162
  width: 20px;
163
  text-align: center;
164
  }
165
 
166
  .main-content {
167
- flex: 1; /* Allow main content to take remaining space */
168
  padding: 20px;
169
- width: calc(100% - 280px);
170
- margin-left: 280px; /* Offset for sidebar */
 
171
  }
172
 
173
  .loader {
@@ -186,7 +201,7 @@ ui <- fluidPage(
186
  }
187
 
188
  .hidden {
189
- display: none;
190
  }
191
 
192
  table.dataTable {
@@ -248,688 +263,1645 @@ ui <- fluidPage(
248
  margin: 0;
249
  }
250
 
251
- .plotly-title {
252
- font-size: 18px;
253
- font-weight: bold;
254
- color: var(--primary);
255
- }
256
-
257
- .plotly-annotation {
258
- font-size: 14px;
259
- color: var(--dark);
260
- }
261
-
262
- .color-picker-container {
263
- background: #F9F9F9;
264
  padding: 15px;
265
- border-radius: 8px;
266
- margin-bottom: 15px;
267
- border: 1px solid #E0E0E0;
268
  }
269
 
270
- .color-picker-title {
271
- font-weight: 600;
272
- margin-bottom: 10px;
273
- color: var(--primary);
274
- }
275
-
276
- .color-dashboard {
277
- background: var(--card-bg);
278
- padding: 2rem;
279
- margin-bottom: 20px;
280
- border-radius: 15px;
281
- box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
282
- border: 1px solid rgba(30, 58, 138, 0.2);
283
- width: 100%;
284
  }
285
 
286
- .color-dashboard-header {
 
 
 
287
  padding: 15px;
288
- background: linear-gradient(135deg, var(--primary), var(--info));
289
- text-align: center;
290
- border-radius: 10px;
291
- margin-bottom: 20px;
292
- color: white;
293
  }
294
 
295
- .color-picker-row {
296
- display: flex;
297
- flex-wrap: wrap;
298
- gap: 15px;
299
- justify-content: space-between;
300
  }
301
 
302
- .color-picker-item {
303
- flex: 1;
304
- min-width: 150px;
305
  }
306
  "))
307
  ),
308
  div(
309
  class = "app-wrapper",
310
- # Color Selection Dashboard
311
  div(
312
- class = "color-dashboard",
313
  div(
314
- class = "color-dashboard-header",
315
- h3("🎨 Plot Color Customization", style = "margin: 0; font-weight: 600; color: white;")
316
  ),
317
  div(
318
- class = "color-picker-container",
319
- div(class = "color-picker-title", "Select Plot Colors"),
 
 
320
  div(
321
- class = "color-picker-row",
322
- div(class = "color-picker-item", colourpicker::colourInput("color_primary", "Primary Color", value = "#1E3A8A")),
323
- div(class = "color-picker-item", colourpicker::colourInput("color_secondary", "Secondary Color", value = "#6B8E23")),
324
- div(class = "color-picker-item", colourpicker::colourInput("color_accent", "Accent Color", value = "#4169E1")),
325
- div(class = "color-picker-item", colourpicker::colourInput("color_highlight", "Highlight Color", value = "#FF8C00"))
326
- ),
327
- actionButton("apply_colors", "Apply Colors", class = "btn-primary", style = "width: 100%; margin-top: 15px;")
328
  )
329
  ),
330
- # Main layout with sidebar and content
331
  div(
332
- style = "display: flex; flex-direction: row;",
333
- # Sidebar
334
- div(
335
- class = "sidebar",
336
- div(
337
- class = "sidebar-header",
338
- h3("📊 Phenotypic Data Analysis", style = "margin: 0; font-weight: 600; color: white;")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
339
  ),
340
- selectInput("lme4_selected_trait", "Select Trait for Detailed Analysis", choices = c()),
341
- checkboxInput("lme4_include_interaction", "Include Environment:Genotype Interaction", value = FALSE),
342
- div(
343
- class = "sidebar-content",
344
- div(
345
- class = "nav flex-column", id = "lme4-v-pills-tab", role = "tablist",
346
- tags$a(class = "nav-link active", `data-toggle` = "pill", href = "#lme4-upload", role = "tab",
347
- icon("file-upload", class = "fas"), "📤 Upload Data"),
348
- tags$a(class = "nav-link", `data-toggle` = "pill", href = "#lme4-descriptives", role = "tab",
349
- icon("chart-line", class = "fas"), "📊 Descriptive Statistics"),
350
- tags$a(class = "nav-link", `data-toggle` = "pill", href = "#lme4-blues", role = "tab",
351
- icon("chart-bar", class = "fas"), "📈 Predicted Means"),
352
- tags$a(class = "nav-link", `data-toggle` = "pill", href = "#lme4-correlations", role = "tab",
353
- icon("link", class = "fas"), "🔗 Trait Correlations")
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;",
358
- p("LME4 Analysis Dashboard v1.1"),
359
- p("© 2023 Statistical Genetics Lab")
360
- )
361
- )
362
- ),
363
- # Main content
364
- div(
365
- class = "main-content",
366
- div(
367
- class = "tab-content",
368
- div(
369
- class = "tab-pane fade show active", id = "lme4-upload", role = "tabpanel",
370
- div(
371
- class = "section",
372
- h2("📤 Upload Your Data"),
373
- div(
374
- class = "upload-container",
375
- div(class = "upload-icon", icon("cloud-upload-alt", class = "fas")),
376
- h3("📁 Drag and drop your Excel file here", style = "color: var(--primary);"),
377
- p("or", style = "margin: 10px 0;"),
378
- fileInput("lme4_file", NULL, accept = c(".xlsx", ".xls"),
379
- buttonLabel = "Browse Files", placeholder = "No file selected"),
380
- p("📝 Supported formats: .xlsx, .xls", style = "color: var(--light); font-size: 14px;"),
381
- div(id = "lme4_loader", class = "loader hidden")
382
- ),
383
- verbatimTextOutput("lme4_data_preview"),
384
- verbatimTextOutput("lme4_debug_log"),
385
- div(
386
- id = "lme4_data_stats", class = "hidden",
387
- h3("📊 Data Overview"),
388
- fluidRow(
389
- column(3, div(class = "status-card card-1",
390
- icon("columns", class = "fas"),
391
- h4(textOutput("lme4_n_vars"), style = "font-weight: 600;"),
392
- p("Variables")
393
- )),
394
- column(3, div(class = "status-card card-2",
395
- icon("list", class = "fas"),
396
- h4(textOutput("lme4_n_obs"), style = "font-weight: 600;"),
397
- p("Observations")
398
- )),
399
- column(3, div(class = "status-card card-3",
400
- icon("dna", class = "fas"),
401
- h4(textOutput("lme4_n_geno"), style = "font-weight: 600;"),
402
- p("Genotypes")
403
- )),
404
- column(3, div(class = "status-card card-4",
405
- icon("globe", class = "fas"),
406
- h4(textOutput("lme4_n_env"), style = "font-weight: 600;"),
407
- p("Environments")
408
- ))
409
- )
410
- )
411
- )
412
- ),
413
- div(
414
- class = "tab-pane fade", id = "lme4-descriptives", role = "tabpanel",
415
- div(
416
- class = "section",
417
- h2("📊 Descriptive Statistics"),
418
- div(
419
- id = "lme4_descriptives_content",
420
- div(class = "table-container", DTOutput("lme4_descriptives_table")),
421
- div(class = "chart-container", plotlyOutput("lme4_descriptives_plot", height = "500px")),
422
- div(
423
- class = "insights",
424
- h4("💡 Interpretation"),
425
- p("Descriptive statistics provide an overview of central tendency, variability, and range for each trait. Coefficient of Variation (CV) indicates relative variability; lower CV suggests more consistent data across observations.")
426
- )
427
- ),
428
- div(
429
- id = "lme4_descriptives_placeholder", class = "text-center",
430
- icon("chart-line", class = "fas", style = "font-size: 72px; color: var(--light); margin: 30px 0;"),
431
- h4("📤 Upload data to see descriptive statistics", style = "color: var(--light);")
432
- )
433
- )
434
- ),
435
- div(
436
- class = "tab-pane fade", id = "lme4-blues", role = "tabpanel",
437
- div(
438
- class = "section",
439
- h2("📈 Predicted Means (BLUEs)"),
440
- div(
441
- id = "lme4_blues_content",
442
- div(class = "chart-container", plotlyOutput("lme4_blues_plot", height = "500px")),
443
- div(class = "table-container", DTOutput("lme4_blues_table")),
444
- div(
445
- class = "insights",
446
- h4("💡 Interpretation"),
447
- 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.")
448
- )
449
- ),
450
- div(
451
- id = "lme4_blues_placeholder", class = "text-center",
452
- icon("chart-bar", class = "fas", style = "font-size: 72px; color: var(--light); margin: 30px 0;"),
453
- h4("📤 Upload data to see predicted means", style = "color: var(--light);")
454
- )
455
- )
456
- ),
457
- div(
458
- class = "tab-pane fade", id = "lme4-correlations", role = "tabpanel",
459
- div(
460
- class = "section",
461
- h2("🔗 Trait Correlations"),
462
- div(
463
- id = "lme4_correlations_content",
464
- div(class = "chart-container", plotlyOutput("lme4_correlation_plot", height = "600px")),
465
- div(class = "table-container", DTOutput("lme4_cor_table")),
466
- div(
467
- class = "insights",
468
- h4("💡 Interpretation"),
469
- p("Correlations reveal trait synergies or trade-offs. Positive correlations (near 1) suggest traits improve together; negative correlations (near -1) indicate trade-offs.")
470
- )
471
- ),
472
- div(
473
- id = "lme4_correlations_placeholder", class = "text-center",
474
- icon("link", class = "fas", style = "font-size: 72px; color: var(--light); margin: 30px 0;"),
475
- h4("📤 Upload data to see trait correlations", style = "color: var(--light);")
476
- )
477
- )
478
- )
 
 
 
 
 
 
 
 
 
 
 
 
479
  )
480
  )
481
  )
482
  )
483
  )
484
- # Server function
 
485
  server <- function(input, output, session) {
486
- # LME4 Analysis Reactive Values
487
- rv_lme4 <- reactiveValues(
 
488
  data = NULL,
489
  traits = NULL,
490
- trait = NULL,
491
- lme4_models = NULL,
492
- blues_all = NULL,
493
- cor_matrix = NULL,
494
- cor_table = NULL,
495
- descriptives = NULL,
496
- debug_log = NULL,
497
- plot_colors = list(
498
- primary = "#1E3A8A",
499
- secondary = "#6B8E23",
500
- accent = "#4169E1",
501
- highlight = "#FF8C00"
502
- )
503
  )
504
 
505
- # Update colors when apply button is clicked
506
- observeEvent(input$apply_colors, {
507
- rv_lme4$plot_colors$primary <- input$color_primary
508
- rv_lme4$plot_colors$secondary <- input$color_secondary
509
- rv_lme4$plot_colors$accent <- input$color_accent
510
- rv_lme4$plot_colors$highlight <- input$color_highlight
511
-
512
- showNotification("Colors updated! Refresh plots to see changes.", type = "message")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
513
  })
514
 
515
- # Generate color palette based on selected colors
516
- get_color_palette <- function() {
517
- c(
518
- rv_lme4$plot_colors$primary,
519
- rv_lme4$plot_colors$secondary,
520
- rv_lme4$plot_colors$accent,
521
- rv_lme4$plot_colors$highlight,
522
- "#B5EAD7", "#E6E6FA", "#FFFACD", "#FF9999"
523
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
524
  }
525
 
526
- # Plot formatting with dynamic colors
527
- get_plot_layout <- function() {
528
- list(
529
- plot_bgcolor = "transparent",
530
- paper_bgcolor = "transparent",
531
- margin = list(l = 80, r = 80, t = 100, b = 100),
532
- font = list(family = "Poppins", size = 14, color = "#2D3748"),
533
- showlegend = TRUE,
534
- legend = list(orientation = "h", y = -0.2, x = 0.5, xanchor = "center")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
535
  )
536
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
537
 
538
- # LME4: Process data
539
- lme4_process_data <- function(path) {
540
- message("LME4: Reading Excel file: ", path)
 
 
 
541
  tryCatch({
542
- data <- read_excel(path)
543
- colnames(data) <- make.names(colnames(data), unique = TRUE)
544
 
545
- required_cols <- c("Genotype", "Block", "Row", "Column", "Rep", "Environment")
546
- missing_cols <- setdiff(required_cols, names(data))
547
- if (length(missing_cols) > 0) {
548
- stop("Missing required columns: ", paste(missing_cols, collapse = ", "))
549
  }
550
 
551
- data$Genotype <- as.factor(data$Genotype)
552
- data$Block <- as.factor(data$Block)
553
- data$Row <- as.factor(data$Row)
554
- data$Rep <- as.factor(data$Rep)
555
- data$Column <- as.factor(data$Column)
556
- data$Environment <- as.factor(data$Environment)
557
- data$Environment <- factor(data$Environment, levels = unique(data$Environment))
 
 
 
 
 
558
 
559
- all_cols <- names(data)
560
- trait_cols <- all_cols[9:length(all_cols)]
561
- numeric_cols <- trait_cols[sapply(data[trait_cols], is.numeric)]
 
 
 
 
 
 
 
 
 
 
562
 
563
- if (length(numeric_cols) == 0) {
564
- stop("No numeric columns found for traits starting from column 9")
565
- }
566
 
567
- n_genotypes <- length(unique(data$Genotype))
568
- n_environments <- length(unique(data$Environment))
569
- if (n_genotypes < 3) {
570
- stop("Insufficient genotypes (", n_genotypes, ") for LME4 analysis; need at least 3")
571
- }
572
- if (n_environments < 2) {
573
- stop("Insufficient environments (", n_environments, ") for LME4 analysis; need at least 2")
574
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
575
 
576
- combo_counts <- table(data$Environment, data$Genotype)
577
- zero_combinations <- sum(combo_counts == 0)
578
- if (zero_combinations > 0) {
579
- message("LME4: Warning: ", zero_combinations, " Environment:Genotype combinations have no data")
580
- }
581
- if (zero_combinations > (nrow(combo_counts) * ncol(combo_counts) * 0.5)) {
582
- showNotification("Warning: Over 50% of Environment:Genotype combinations are missing", type = "warning", duration = 10)
583
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
584
 
585
- missing_data <- data %>%
586
- group_by(Environment) %>%
587
- summarise(across(all_of(numeric_cols), ~ sum(is.na(.)) / length(.)))
588
- bad_envs <- missing_data %>%
589
- pivot_longer(cols = all_of(numeric_cols), names_to = "Trait", values_to = "Missing") %>%
590
- filter(Missing > 0.2) %>%
591
- pull(Environment) %>%
592
- unique()
593
- if (length(bad_envs) > 0) {
594
- message("LME4: Filtering out environments with >20% missing data: ", paste(bad_envs, collapse = ", "))
595
- data <- data %>% filter(!Environment %in% bad_envs) %>% droplevels()
596
- }
 
597
 
598
- message("LME4: Data summary: Rows=", nrow(data), ", Genotypes=", n_genotypes, ", Environments=", n_environments, ", Traits=", paste(numeric_cols, collapse = ", "))
599
- return(list(data = data, traits = numeric_cols))
600
  }, error = function(e) {
601
- message("LME4: Error in data processing: ", e$message)
602
- showNotification(paste("Error processing file:", e$message), type = "error", duration = 10)
603
  return(NULL)
604
  })
605
- }
606
 
607
- # LME4: Fit model
608
- lme4_fit_model <- function(data, trait) {
609
- message("LME4: Fitting model for ", trait)
610
- formula_str <- if (input$lme4_include_interaction) {
611
- paste(trait, "~ Environment + Genotype + Environment:Genotype + (1|Block) + (1|Row) + (1|Column) + (1|Rep)")
612
- } else {
613
- paste(trait, "~ Environment + Genotype + (1|Block) + (1|Row) + (1|Column) + (1|Rep)")
614
- }
615
- formula <- as.formula(formula_str)
616
  tryCatch({
617
- model <- lmer(formula, data = data, na.action = na.omit,
618
- control = lmerControl(check.rankX = "warn+drop.cols", optimizer = "bobyqa"))
619
- message("LME4: Successfully fitted model for ", trait)
620
- return(model)
 
 
 
 
 
 
 
 
 
 
 
 
621
  }, error = function(e) {
622
- message("LME4: Error fitting model for ", trait, ": ", e$message)
623
- showNotification(paste("Model fitting failed for", trait, ": ", e$message), type = "error", duration = 10)
624
  return(NULL)
625
- }, warning = function(w) {
626
- message("LME4: Warning in model fitting for ", trait, ": ", w$message)
627
- showNotification(paste("Warning for", trait, ": ", w$message), type = "warning", duration = 10)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
628
  return(NULL)
629
  })
630
- }
631
 
632
- # LME4: Get BLUEs
633
- lme4_get_blue <- function(model, trait) {
634
- if (is.null(model)) {
635
- message("LME4: No model for ", trait)
636
- return(data.frame(Trait = trait, Genotype = NA, Environment = NA, predicted.value = NA, Error = "No model fitted"))
637
- }
638
  tryCatch({
639
- emm_options(pbkrtest.limit = 5000, lmerTest.limit = 5000)
640
- blues <- emmeans(model, ~ Genotype:Environment)
641
- blues_df <- as.data.frame(blues) %>%
642
- rename(predicted.value = emmean) %>%
643
- mutate(Trait = trait) %>%
644
- select(Trait, Genotype, Environment, predicted.value, SE = SE) %>%
645
- filter(!is.na(predicted.value))
646
- if (nrow(blues_df) == 0) {
647
- return(data.frame(Trait = trait, Genotype = NA, Environment = NA, predicted.value = NA, SE = NA, Error = "No valid BLUEs"))
648
- }
649
- return(blues_df)
 
 
650
  }, error = function(e) {
651
- message("LME4: Error in BLUEs for ", trait, ": ", e$message)
652
- return(data.frame(Trait = trait, Genotype = NA, Environment = NA, predicted.value = NA, SE = NA, Error = e$message))
653
  })
654
- }
655
 
656
- # LME4: File upload observer
657
- observeEvent(input$lme4_file, {
658
- req(input$lme4_file)
659
- message("LME4: File upload triggered: ", input$lme4_file$name)
660
- shinyjs::show("lme4_loader")
661
- on.exit(shinyjs::hide("lme4_loader"))
662
 
663
- result <- lme4_process_data(input$lme4_file$datapath)
664
- if (is.null(result)) {
665
- return()
666
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
667
 
668
- rv_lme4$data <- result$data
669
- rv_lme4$traits <- result$traits
670
- rv_lme4$trait <- result$traits[1]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
671
 
672
- updateSelectInput(session, "lme4_selected_trait", choices = rv_lme4$traits, selected = rv_lme4$traits[1])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
673
 
674
- shinyjs::show("lme4_data_stats")
675
- output$lme4_n_vars <- renderText({ ncol(rv_lme4$data) })
676
- output$lme4_n_obs <- renderText({ nrow(rv_lme4$data) })
677
- output$lme4_n_geno <- renderText({ length(unique(rv_lme4$data$Genotype)) })
678
- output$lme4_n_env <- renderText({ length(unique(rv_lme4$data$Environment)) })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
679
 
680
- output$lme4_data_preview <- renderPrint({
681
- str(rv_lme4$data)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
682
  })
 
 
 
 
 
683
 
684
- debug_log <- c()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
685
 
686
- withProgress(message = 'LME4: Analyzing data', value = 0, {
687
- lme4_models <- list()
688
- blues_list <- list()
689
 
690
- total_steps <- length(rv_lme4$traits) * 2 + 2
691
- step_increment <- 1 / total_steps
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
692
 
693
- for (trait in rv_lme4$traits) {
694
- incProgress(step_increment, detail = paste("Fitting model for", trait))
695
- model <- lme4_fit_model(rv_lme4$data, trait)
696
- lme4_models[[trait]] <- model
697
- debug_log <- c(debug_log, paste("Trait:", trait, "- Model fitted:", ifelse(is.null(model), "Failed", "Success")))
698
-
699
- incProgress(step_increment, detail = paste("Calculating predicted means for", trait))
700
- blues_list[[trait]] <- lme4_get_blue(model, trait)
701
  }
702
 
703
- incProgress(step_increment, detail = "Calculating correlations")
704
- if (length(rv_lme4$traits) > 1) {
705
- trait_data <- rv_lme4$data %>% select(all_of(rv_lme4$traits)) %>% na.omit()
706
- if (nrow(trait_data) > 0) {
707
- cor_matrix <- cor(trait_data, use = "pairwise.complete.obs")
708
- cor_table <- as.data.frame(as.table(cor_matrix)) %>%
709
- rename(Trait1 = Var1, Trait2 = Var2, Correlation = Freq) %>%
710
- mutate(Correlation = round(Correlation, 3))
711
- rv_lme4$cor_matrix <- cor_matrix
712
- rv_lme4$cor_table <- cor_table
713
- debug_log <- c(debug_log, "Correlations: Success")
714
- } else {
715
- rv_lme4$cor_matrix <- matrix(NA, nrow = 1, ncol = 1, dimnames = list("NoData", "NoData"))
716
- rv_lme4$cor_table <- data.frame(Trait1 = "NoData", Trait2 = "NoData", Correlation = NA)
717
- debug_log <- c(debug_log, "Correlations: No valid data")
718
  }
719
- } else {
720
- rv_lme4$cor_matrix <- matrix(1, nrow = 1, ncol = 1, dimnames = list(rv_lme4$traits, rv_lme4$traits))
721
- rv_lme4$cor_table <- data.frame(Trait1 = rv_lme4$traits, Trait2 = rv_lme4$traits, Correlation = 1)
722
- debug_log <- c(debug_log, "Correlations: Single trait")
723
- }
724
-
725
- incProgress(step_increment, detail = "Calculating descriptive statistics")
726
- descriptives <- rv_lme4$data %>%
727
- select(all_of(rv_lme4$traits)) %>%
728
- pivot_longer(cols = everything(), names_to = "Trait", values_to = "Value") %>%
729
- group_by(Trait) %>%
730
- summarise(
731
- Mean = mean(Value, na.rm = TRUE),
732
- SD = sd(Value, na.rm = TRUE),
733
- Min = min(Value, na.rm = TRUE),
734
- Max = max(Value, na.rm = TRUE),
735
- N = sum(!is.na(Value)),
736
- .groups = "drop"
737
- ) %>%
738
- mutate(CV = round((SD / Mean) * 100, 2))
739
- rv_lme4$descriptives <- descriptives
740
- debug_log <- c(debug_log, "Descriptives: Success")
741
-
742
- rv_lme4$lme4_models <- lme4_models
743
- rv_lme4$blues_all <- bind_rows(blues_list) %>% filter(!is.na(predicted.value))
744
- rv_lme4$debug_log <- debug_log
745
-
746
- shinyjs::hide("lme4_blues_placeholder")
747
- shinyjs::show("lme4_blues_content")
748
- shinyjs::hide("lme4_correlations_placeholder")
749
- shinyjs::show("lme4_correlations_content")
750
- shinyjs::hide("lme4_descriptives_placeholder")
751
- shinyjs::show("lme4_descriptives_content")
752
-
753
- output$lme4_debug_log <- renderPrint({
754
- cat(paste(rv_lme4$debug_log, collapse = "\n"))
755
  })
 
 
 
 
 
 
 
 
 
756
 
757
- showNotification("LME4: File uploaded and analyzed successfully", type = "message", duration = 5)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
758
  })
759
  })
760
 
761
- # Update selected trait
762
- observe({
763
- req(input$lme4_selected_trait)
764
- rv_lme4$trait <- input$lme4_selected_trait
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
765
  })
766
 
767
- # LME4: Filtered reactives
768
- lme4_filtered_blues <- reactive({
769
- req(rv_lme4$blues_all, rv_lme4$trait)
770
- rv_lme4$blues_all %>% filter(Trait == rv_lme4$trait, !is.na(predicted.value))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
771
  })
772
 
773
- # LME4: Plot outputs
774
- output$lme4_blues_plot <- renderPlotly({
775
- req(lme4_filtered_blues())
776
- data <- lme4_filtered_blues()
777
- if (nrow(data) == 0 || all(is.na(data$predicted.value))) {
778
- return(plot_ly() %>%
779
- layout(
780
- title = list(text = paste("No Valid Predicted Means for", rv_lme4$trait), font = list(family = "Poppins")),
781
- annotations = list(
782
- text = "No valid data for plotting predicted means.",
783
- x = 0.5, y = 0.5, xref = "paper", yref = "paper",
784
- showarrow = FALSE, font = list(size = 12, color = "#2D3748")
785
- ),
786
- get_plot_layout()
787
- ))
788
- }
789
- plot_ly(data, x = ~Environment, y = ~predicted.value, color = ~Genotype,
790
- type = 'scatter', mode = 'lines+markers',
791
- marker = list(size = 8),
792
- line = list(width = 2),
793
- colors = get_color_palette(),
794
- text = ~paste("Genotype:", Genotype, "<br>Value:", round(predicted.value, 2)),
795
- hoverinfo = "text") %>%
796
- layout(
797
- title = list(text = paste("Predicted Means (BLUEs) for", rv_lme4$trait), font = list(size = 18, family = "Poppins", color = "#2D3748")),
798
- xaxis = list(title = "Environment", tickangle = 45, titlefont = list(family = "Poppins"), tickfont = list(family = "Poppins")),
799
- yaxis = list(title = "Predicted Value", titlefont = list(family = "Poppins"), tickfont = list(family = "Poppins")),
800
- get_plot_layout(),
801
- hoverlabel = list(bgcolor = "white", font = list(family = "Poppins"))
802
- )
803
  })
804
 
805
- # Scatter plot matrix for correlations
806
- output$lme4_correlation_plot <- renderPlotly({
807
- req(rv_lme4$data, rv_lme4$traits)
808
- if (length(rv_lme4$traits) < 2) {
809
- return(plot_ly() %>%
810
- layout(
811
- title = list(text = "Need at least 2 traits for correlation plot", font = list(family = "Poppins")),
812
- annotations = list(
813
- text = "Upload data with at least 2 numeric traits.",
814
- x = 0.5, y = 0.5, xref = "paper", yref = "paper",
815
- showarrow = FALSE, font = list(size = 12, color = "#2D3748")
816
- ),
817
- get_plot_layout()
818
- ))
819
- }
820
 
821
- # Prepare data for scatter plot matrix
822
- plot_data <- rv_lme4$data %>%
823
- select(all_of(rv_lme4$traits)) %>%
824
- na.omit()
825
-
826
- if (nrow(plot_data) == 0) {
827
- return(plot_ly() %>%
828
- layout(
829
- title = list(text = "No valid data for correlation plot", font = list(family = "Poppins")),
830
- annotations = list(
831
- text = "No complete cases found for the selected traits.",
832
- x = 0.5, y = 0.5, xref = "paper", yref = "paper",
833
- showarrow = FALSE, font = list(size = 12, color = "#2D3748")
834
- ),
835
- get_plot_layout()
836
- ))
837
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
838
 
839
- # Create scatter plot matrix
840
- fig <- plot_ly(type = 'splom', dimensions = lapply(names(plot_data), function(col) {
841
- list(label = col, values = plot_data[[col]])
842
- }))
843
-
844
- fig <- fig %>% layout(
845
- title = list(text = "Trait Correlation Scatter Plot Matrix", font = list(size = 18, family = "Poppins", color = "#2D3748")),
846
- dragmode = 'select',
847
- hovermode = 'closest',
848
- plot_bgcolor = 'transparent',
849
- paper_bgcolor = 'transparent',
850
- font = list(family = "Poppins", size = 12)
851
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
852
 
853
- fig
854
- })
855
-
856
- # LME4: Descriptive Statistics Plot (Boxplot by Environment for selected trait)
857
- output$lme4_descriptives_plot <- renderPlotly({
858
- req(rv_lme4$data, rv_lme4$trait)
859
- trait_data <- rv_lme4$data[[rv_lme4$trait]]
860
- if (all(is.na(trait_data)) || length(unique(rv_lme4$data$Environment)) < 2) {
861
- return(plot_ly() %>%
862
- layout(
863
- title = list(text = paste("No Valid Data for", rv_lme4$trait), font = list(family = "Poppins")),
864
- annotations = list(
865
- text = "No valid data for boxplot.",
866
- x = 0.5, y = 0.5, xref = "paper", yref = "paper",
867
- showarrow = FALSE, font = list(size = 12, color = "#2D3748")
868
- ),
869
- get_plot_layout()
870
- ))
871
- }
872
- plot_ly(rv_lme4$data, x = ~Environment, y = rv_lme4$data[[rv_lme4$trait]], type = 'box',
873
- color = ~Environment, colors = get_color_palette(),
874
- hoverinfo = "y+name") %>%
875
- layout(
876
- title = list(text = paste("Distribution of", rv_lme4$trait, "by Environment"), font = list(size = 18, family = "Poppins", color = "#2D3748")),
877
- xaxis = list(title = "Environment", titlefont = list(family = "Poppins"), tickfont = list(family = "Poppins")),
878
- yaxis = list(title = paste(rv_lme4$trait, "Value"), titlefont = list(family = "Poppins"), tickfont = list(family = "Poppins")),
879
- get_plot_layout(),
880
- hoverlabel = list(bgcolor = "white", font = list(family = "Poppins"))
881
- )
 
 
 
 
 
 
 
 
 
 
882
  })
883
 
884
- # LME4: Table outputs
885
- output$lme4_blues_table <- renderDT({
886
- req(lme4_filtered_blues())
887
- datatable(
888
- lme4_filtered_blues() %>% select(-Error),
889
- extensions = 'Buttons',
890
- options = list(
891
- scrollX = TRUE,
892
- dom = 'Bfrtip',
893
- buttons = c('copy', 'excel', 'pdf', 'print'),
894
- pageLength = 10,
895
- columnDefs = list(list(className = 'dt-center', targets = '_all'))
896
- ),
897
- caption = paste("Predicted Means (BLUEs) for", rv_lme4$trait)
898
- ) %>% formatRound(columns = c("predicted.value", "SE"), digits = 3)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
899
  })
900
 
901
- output$lme4_cor_table <- renderDT({
902
- req(rv_lme4$cor_table)
903
- datatable(
904
- rv_lme4$cor_table,
905
- extensions = 'Buttons',
906
- options = list(
907
- scrollX = TRUE,
908
- dom = 'Bfrtip',
909
- buttons = c('copy', 'excel', 'pdf', 'print'),
910
- pageLength = 10,
911
- columnDefs = list(list(className = 'dt-center', targets = '_all'))
912
- ),
913
- caption = "Correlation Between Traits"
914
- ) %>% formatRound(columns = "Correlation", digits = 3)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
915
  })
916
 
917
- output$lme4_descriptives_table <- renderDT({
918
- req(rv_lme4$descriptives)
919
- datatable(
920
- rv_lme4$descriptives,
921
- extensions = 'Buttons',
922
- options = list(
923
- scrollX = TRUE,
924
- dom = 'Bfrtip',
925
- buttons = c('copy', 'excel', 'pdf', 'print'),
926
- pageLength = 10,
927
- columnDefs = list(list(className = 'dt-center', targets = c(2:6)))
928
- ),
929
- caption = "Descriptive Statistics for Traits"
930
- ) %>% formatRound(columns = c("Mean", "SD", "Min", "Max", "CV"), digits = 2)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
931
  })
932
  }
933
 
934
  # Run the Shiny app
935
- shinyApp(ui, server)
 
 
 
 
 
1
  library(shiny)
2
  library(shinyjs)
3
  library(tidyverse)
 
8
  library(plotly)
9
  library(shinyWidgets)
10
  library(ggplot2)
11
+ library(GGally)
12
+ library(corrplot)
13
+ library(agricolae)
14
+ library(car)
15
+ library(broom)
16
+ library(cluster)
17
+ library(factoextra)
18
+ library(pheatmap)
19
+ library(RColorBrewer)
20
+ library(moments)
21
+ library(reshape2)
22
+ library(gridExtra)
23
+
24
+ # UI
25
  ui <- fluidPage(
26
  useShinyjs(),
27
  tags$head(
28
  tags$meta(charset = "UTF-8"),
29
+ tags$title("Advanced Phenotypic Analysis Dashboard"),
30
  tags$link(rel = "stylesheet", href = "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"),
31
  tags$style(HTML("
32
  :root {
33
+ --primary: #1E3A8A;
34
+ --secondary: #6B8E23;
35
+ --success: #32CD32;
36
+ --info: #4169E1;
37
+ --warning: #FF8C00;
38
+ --danger: #DC143C;
39
+ --light: #D1D5DB;
40
+ --dark: #2F4F4F;
41
+ --background: #FFFFFF;
42
+ --card-bg: #FFFFFF;
43
  }
44
 
45
  body {
 
47
  background: var(--background);
48
  color: var(--dark);
49
  overflow-x: hidden;
 
 
50
  }
51
 
52
  .container-fluid {
 
55
  margin: 0 auto;
56
  }
57
 
 
 
 
 
 
 
58
  .section {
59
  margin-bottom: 30px;
60
  background: var(--card-bg);
 
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;
72
+ font-weight: 700;
73
+ }
74
+
75
  .chart-container {
76
  position: relative;
77
  margin-bottom: 20px;
 
80
  background: var(--card-bg);
81
  padding: 1.5rem;
82
  border: 1px solid rgba(30, 58, 138, 0.2);
 
83
  }
84
 
85
  .insights {
 
128
  background: var(--card-bg);
129
  color: var(--dark);
130
  padding: 2rem;
131
+ height: 100vh;
132
+ position: fixed;
133
+ width: 300px;
134
  box-shadow: 5px 0 15px rgba(0,0,0,0.1);
135
  border-right: 1px solid var(--primary);
136
+ overflow-y: auto;
137
  }
138
 
139
  .sidebar-header {
 
150
  padding: 15px;
151
  }
152
 
153
+ .nav-tabs .nav-link {
154
  color: var(--dark);
155
  padding: 12px 15px;
156
  border-radius: 8px;
 
159
  align-items: center;
160
  transition: all 0.3s;
161
  background: #F5F5F5;
162
+ text-decoration: none;
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);
170
  box-shadow: 0 4px 8px rgba(30, 58, 138, 0.3);
171
+ text-decoration: none;
172
  }
173
 
174
+ .nav-tabs .nav-link i {
175
  margin-right: 10px;
176
  width: 20px;
177
  text-align: center;
178
  }
179
 
180
  .main-content {
181
+ margin-left: 300px;
182
  padding: 20px;
183
+ width: calc(100% - 300px);
184
+ min-height: 100vh;
185
+ background: var(--background);
186
  }
187
 
188
  .loader {
 
201
  }
202
 
203
  .hidden {
204
+ display: none !important;
205
  }
206
 
207
  table.dataTable {
 
263
  margin: 0;
264
  }
265
 
266
+ .error-message {
267
+ background: #ffebee;
268
+ border: 1px solid #e57373;
269
+ color: #c62828;
 
 
 
 
 
 
 
 
 
270
  padding: 15px;
271
+ border-radius: 5px;
272
+ margin: 10px 0;
 
273
  }
274
 
275
+ .warning-message {
276
+ background: #fff3e0;
277
+ border: 1px solid #ffb74d;
278
+ color: #ef6c00;
279
+ padding: 15px;
280
+ border-radius: 5px;
281
+ margin: 10px 0;
 
 
 
 
 
 
 
282
  }
283
 
284
+ .success-message {
285
+ background: #e8f5e8;
286
+ border: 1px solid #81c784;
287
+ color: #2e7d32;
288
  padding: 15px;
289
+ border-radius: 5px;
290
+ margin: 10px 0;
 
 
 
291
  }
292
 
293
+ .tab-pane {
294
+ padding: 20px;
 
 
 
295
  }
296
 
297
+ .nav-tabs {
298
+ border-bottom: none;
 
299
  }
300
  "))
301
  ),
302
  div(
303
  class = "app-wrapper",
 
304
  div(
305
+ class = "sidebar",
306
  div(
307
+ class = "sidebar-header",
308
+ h3("📊 Advanced Phenotypic Analysis", style = "margin: 0; font-weight: 600; color: white;")
309
  ),
310
  div(
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;",
317
+ p("Advanced Phenotypic Analysis v2.0"),
318
+ p("© 2024 Statistical Genetics Lab")
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",
329
+ h2("📤 Data Upload & Preview"),
330
+ div(
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
+ ),
340
+ div(id = "upload_status"),
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",
368
+ h2("📊 Descriptive Statistics"),
369
+ fluidRow(
370
+ column(6, div(class = "chart-container", plotlyOutput("descriptives_plot", height = "auto"))),
371
+ column(6, div(class = "chart-container", plotlyOutput("distribution_plot", height = "auto")))
372
+ ),
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",
398
+ h2("📈 Mixed Models & BLUEs"),
399
+ div(class = "chart-container", plotlyOutput("blues_plot", height = "auto")),
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",
427
+ h2("🔗 Trait Correlations"),
428
+ fluidRow(
429
+ column(8, div(class = "chart-container", plotOutput("correlation_heatmap", height = "auto"))),
430
+ column(4, div(class = "chart-container", DTOutput("correlation_table")))
431
+ ),
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(
450
+ column(6, div(class = "chart-container", plotOutput("dendrogram", height = "auto"))),
451
+ column(6, div(class = "chart-container", DTOutput("cluster_summary")))
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",
461
+ h2("📐 Principal Component Analysis"),
462
+ fluidRow(
463
+ column(6, div(class = "chart-container", plotlyOutput("pca_plot", height = "auto"))),
464
+ column(6, div(class = "chart-container", plotlyOutput("pca_variance_plot", height = "auto")))
465
+ ),
466
+ fluidRow(
467
+ column(6, div(class = "chart-container", DTOutput("pca_loadings"))),
468
+ column(6, div(class = "chart-container", DTOutput("pca_summary")))
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",
478
+ h2("⚖️ Genotype Stability Analysis"),
479
+ fluidRow(
480
+ column(6, div(class = "chart-container", plotlyOutput("stability_plot", height = "auto"))),
481
+ column(6, div(class = "chart-container", plotlyOutput("ammi_plot", height = "auto")))
482
+ ),
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",
492
+ h2("🎨 Plot Customization"),
493
+ div(
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:",
504
+ choices = c("Default (Green/Red)" = "default",
505
+ "Blue Gradient" = "blue",
506
+ "Viridis" = "viridis",
507
+ "Plasma" = "plasma",
508
+ "Magma" = "magma"),
509
+ selected = "default"),
510
+ actionButton("apply_customization", "Apply Customization", class = "btn-primary")
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
  )
518
  )
519
  )
520
  )
521
+
522
+ # Server Function
523
  server <- function(input, output, session) {
524
+
525
+ # Reactive values to store data, results, and customization settings
526
+ rv <- reactiveValues(
527
  data = NULL,
528
  traits = NULL,
529
+ anova_results = NULL,
530
+ blues = NULL,
531
+ variance_components = NULL,
532
+ heritability = NULL,
533
+ correlations = NULL,
534
+ pca_results = NULL,
535
+ cluster_results = NULL,
536
+ stability_results = NULL,
537
+ plot_height = 600,
538
+ plot_width = 800,
539
+ color_scheme = "default"
 
 
540
  )
541
 
542
+ # Function to get color palette based on selected scheme
543
+ get_color_palette <- function(scheme, n) {
544
+ if (scheme == "default") {
545
+ return(rep(c("#00FF00", "#FF0000", "#FFFF00"), length.out = n))
546
+ } else if (scheme == "blue") {
547
+ return(colorRampPalette(c("#E6F0FA", "#1E3A8A"))(n))
548
+ } else if (scheme == "viridis") {
549
+ return(viridis::viridis(n))
550
+ } else if (scheme == "plasma") {
551
+ return(viridis::plasma(n))
552
+ } else if (scheme == "magma") {
553
+ return(viridis::magma(n))
554
+ } else {
555
+ return(rep(c("#00FF00", "#FF0000", "#FFFF00"), length.out = n))
556
+ }
557
+ }
558
+
559
+ # Observe customization inputs
560
+ observeEvent(input$apply_customization, {
561
+ rv$plot_height <- input$plot_height
562
+ rv$plot_width <- input$plot_width
563
+ rv$color_scheme <- input$color_scheme
564
+ showNotification("Customization applied successfully!", type = "message")
565
  })
566
 
567
+ # Data validation function
568
+ validate_data <- function(data) {
569
+ validation <- list()
570
+
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
580
+ if ("Genotype" %in% names(data)) {
581
+ if (!is.factor(data$Genotype)) {
582
+ data$Genotype <- as.factor(data$Genotype)
583
+ validation$warnings <- c(validation$warnings, "Genotype converted to factor")
584
+ }
585
+ }
586
+
587
+ if ("Environment" %in% names(data)) {
588
+ if (!is.factor(data$Environment)) {
589
+ data$Environment <- as.factor(data$Environment)
590
+ validation$warnings <- c(validation$warnings, "Environment converted to factor")
591
+ }
592
+ }
593
+
594
+ if ("Rep" %in% names(data)) {
595
+ if (!is.factor(data$Rep)) {
596
+ data$Rep <- as.factor(data$Rep)
597
+ validation$warnings <- c(validation$warnings, "Rep converted to factor")
598
+ }
599
+ }
600
+
601
+ if ("Block" %in% names(data)) {
602
+ if (!is.factor(data$Block)) {
603
+ data$Block <- as.factor(data$Block)
604
+ validation$warnings <- c(validation$warnings, "Block converted to factor")
605
+ }
606
+ }
607
+
608
+ # Check for sufficient levels
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
+
625
+ # Check for missing data
626
+ missing_summary <- data %>%
627
+ summarise_all(~sum(is.na(.))) %>%
628
+ pivot_longer(everything(), names_to = "Variable", values_to = "Missing") %>%
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
638
+ if (all(required_cols %in% names(data))) {
639
+ design_check <- data %>%
640
+ group_by(Genotype, Environment) %>%
641
+ summarise(n = n(), .groups = "drop")
642
+
643
+ if (length(unique(design_check$n)) > 1) {
644
+ validation$warnings <- c(validation$warnings, "Unbalanced design detected")
645
+ }
646
+ }
647
+
648
+ # Identify numeric trait columns starting from column 10
649
+ if (ncol(data) >= 10) {
650
+ trait_cols <- names(data)[10:ncol(data)]
651
+ numeric_traits <- trait_cols[sapply(data[trait_cols], is.numeric)]
652
+
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")
661
+ }
662
+
663
+ list(data = data, validation = validation)
664
  }
665
 
666
+ # File upload observer
667
+ observeEvent(input$data_file, {
668
+ req(input$data_file)
669
+
670
+ withProgress(message = 'Processing data...', value = 0, {
671
+ incProgress(0.2, detail = "Reading file...")
672
+
673
+ tryCatch({
674
+ if (tools::file_ext(input$data_file$name) == "csv") {
675
+ data <- read.csv(input$data_file$datapath, stringsAsFactors = FALSE)
676
+ } else {
677
+ data <- read_excel(input$data_file$datapath)
678
+ data <- as.data.frame(data)
679
+ }
680
+
681
+ incProgress(0.4, detail = "Validating data...")
682
+
683
+ # Validate data
684
+ result <- validate_data(data)
685
+ rv$data <- result$data
686
+ validation_results <- result$validation
687
+
688
+ # Identify trait columns starting from column 10
689
+ if (ncol(data) >= 10) {
690
+ trait_cols <- names(data)[10:ncol(data)]
691
+ rv$traits <- trait_cols[sapply(data[trait_cols], is.numeric)]
692
+ } else {
693
+ rv$traits <- character(0)
694
+ }
695
+
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
704
+ shinyjs::show("data_preview_section")
705
+
706
+ incProgress(0.8, detail = "Generating summary...")
707
+
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!")
719
+
720
+ # Show validation messages as notifications
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
+
733
+ showNotification("Data uploaded successfully!", type = "message")
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")
742
+ })
743
+ })
744
+ })
745
+
746
+ # Data preview table
747
+ output$data_preview_table <- renderDT({
748
+ req(rv$data)
749
+ datatable(
750
+ rv$data[1:min(100, nrow(rv$data)), ],
751
+ options = list(
752
+ scrollX = TRUE,
753
+ pageLength = 10,
754
+ dom = 'frtip'
755
+ ),
756
+ caption = "Data Preview (First 100 rows)"
757
  )
758
+ })
759
+
760
+ # Descriptive statistics
761
+ descriptive_stats <- reactive({
762
+ req(rv$data, rv$traits)
763
+
764
+ withProgress(message = 'Computing Descriptive Statistics...', value = 0, {
765
+ incProgress(0.3, detail = "Preparing data...")
766
+
767
+ tryCatch({
768
+ incProgress(0.6, detail = "Calculating statistics...")
769
+
770
+ stats <- rv$data %>%
771
+ select(all_of(rv$traits)) %>%
772
+ pivot_longer(everything(), names_to = "Trait", values_to = "Value") %>%
773
+ group_by(Trait) %>%
774
+ summarise(
775
+ N = sum(!is.na(Value)),
776
+ Mean = round(mean(Value, na.rm = TRUE), 3),
777
+ Median = round(median(Value, na.rm = TRUE), 3),
778
+ SD = round(sd(Value, na.rm = TRUE), 3),
779
+ CV = round((sd(Value, na.rm = TRUE) / mean(Value, na.rm = TRUE)) * 100, 2),
780
+ Min = round(min(Value, na.rm = TRUE), 3),
781
+ Max = round(max(Value, na.rm = TRUE), 3),
782
+ Q1 = round(quantile(Value, 0.25, na.rm = TRUE), 3),
783
+ Q3 = round(quantile(Value, 0.75, na.rm = TRUE), 3),
784
+ Skewness = round(moments::skewness(Value, na.rm = TRUE), 3),
785
+ Kurtosis = round(moments::kurtosis(Value, na.rm = TRUE), 3),
786
+ Missing = sum(is.na(Value)),
787
+ .groups = "drop"
788
+ )
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)
795
+ })
796
+ })
797
+ })
798
+
799
+ # Descriptive statistics table
800
+ output$descriptives_table <- renderDT({
801
+ req(descriptive_stats())
802
+
803
+ datatable(
804
+ descriptive_stats(),
805
+ extensions = 'Buttons',
806
+ options = list(
807
+ scrollX = TRUE,
808
+ dom = 'Bfrtip',
809
+ buttons = c('copy', 'excel', 'csv', 'pdf'),
810
+ pageLength = 15,
811
+ columnDefs = list(list(className = 'dt-center', targets = '_all'))
812
+ ),
813
+ caption = "Descriptive Statistics for All Traits"
814
+ ) %>%
815
+ formatRound(columns = c("Mean", "Median", "SD", "CV", "Min", "Max", "Q1", "Q3", "Skewness", "Kurtosis"), digits = 3)
816
+ })
817
+
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({
825
+ p <- rv$data %>%
826
+ select(Genotype, Environment, all_of(input$selected_trait)) %>%
827
+ rename(Value = !!input$selected_trait) %>%
828
+ filter(!is.na(Value)) %>%
829
+ ggplot(aes(x = Environment, y = Value, fill = Environment)) +
830
+ geom_boxplot(alpha = 0.7) +
831
+ geom_jitter(aes(color = Genotype), width = 0.2, alpha = 0.5, size = 1) +
832
+ labs(title = paste("Distribution of", input$selected_trait, "by Environment"),
833
+ x = "Environment", y = input$selected_trait) +
834
+ theme_minimal() +
835
+ theme(
836
+ axis.text = element_text(color = "#000000"),
837
+ axis.title = element_text(color = "#000000"),
838
+ plot.title = element_text(color = "#000000"),
839
+ axis.text.x = element_text(angle = 45, hjust = 1),
840
+ legend.position = "none"
841
+ ) +
842
+ scale_fill_manual(values = get_color_palette(rv$color_scheme, length(unique(rv$data$Environment)))) +
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)
849
+ })
850
+ })
851
 
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({
859
+ trait_data <- rv$data[[input$selected_trait]]
860
+ trait_data <- trait_data[!is.na(trait_data)]
861
 
862
+ if (length(trait_data) < 2) {
863
+ showNotification("Insufficient data for distribution plot", type = "error")
864
+ return(NULL)
 
865
  }
866
 
867
+ p <- data.frame(Value = trait_data) %>%
868
+ ggplot(aes(x = Value)) +
869
+ geom_histogram(aes(y = after_stat(density)), bins = 30, fill = get_color_palette(rv$color_scheme, 1)[1], alpha = 0.7) +
870
+ geom_density(color = get_color_palette(rv$color_scheme, 1)[2], size = 1) +
871
+ labs(title = paste("Distribution of", input$selected_trait),
872
+ x = input$selected_trait, y = "Density") +
873
+ theme_minimal() +
874
+ theme(
875
+ axis.text = element_text(color = "#000000"),
876
+ axis.title = element_text(color = "#000000"),
877
+ plot.title = element_text(color = "#000000")
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)
884
+ })
885
+ })
886
+
887
+ # ANOVA analysis
888
+ anova_analysis <- reactive({
889
+ req(rv$data, input$selected_trait)
890
+
891
+ withProgress(message = 'Running ANOVA...', value = 0, {
892
+ incProgress(0.3, detail = "Preparing data...")
893
 
894
+ if (!input$selected_trait %in% rv$traits) return(NULL)
 
 
895
 
896
+ tryCatch({
897
+ incProgress(0.5, detail = "Fitting model...")
898
+
899
+ trait_data <- rv$data %>%
900
+ select(Genotype, Environment, Rep, Block, all_of(input$selected_trait)) %>%
901
+ rename(Value = !!input$selected_trait) %>%
902
+ filter(!is.na(Value)) %>%
903
+ mutate(
904
+ Genotype = as.factor(Genotype),
905
+ Environment = as.factor(Environment),
906
+ Rep = as.factor(Rep),
907
+ Block = as.factor(Block)
908
+ )
909
+
910
+ if (nrow(trait_data) < 10) {
911
+ showNotification("Insufficient data for ANOVA (need at least 10 observations)", type = "error")
912
+ return(NULL)
913
+ }
914
+
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
+ }
923
+
924
+ anova_summary <- summary(model)
925
+
926
+ simple_model <- lm(Value ~ Environment + Genotype, data = trait_data)
927
+ residuals_data <- data.frame(
928
+ Fitted = fitted(simple_model),
929
+ Residuals = residuals(simple_model),
930
+ Standardized_Residuals = rstandard(simple_model),
931
+ Genotype = trait_data$Genotype
932
+ )
933
+
934
+ incProgress(1, detail = "Complete!")
935
+
936
+ list(model = model, summary = anova_summary, residuals = residuals_data, simple_model = simple_model)
937
+
938
+ }, error = function(e) {
939
+ showNotification(paste("ANOVA Error:", e$message), type = "error")
940
+ return(NULL)
941
+ })
942
+ })
943
+ })
944
+
945
+ # ANOVA table
946
+ output$anova_table <- renderDT({
947
+ req(anova_analysis())
948
+
949
+ tryCatch({
950
+ anova_df <- broom::tidy(anova_analysis()$simple_model)
951
 
952
+ datatable(
953
+ anova_df,
954
+ extensions = 'Buttons',
955
+ options = list(
956
+ scrollX = TRUE,
957
+ dom = 'Bfrtip',
958
+ buttons = c('copy', 'excel', 'csv'),
959
+ pageLength = 10,
960
+ columnDefs = list(list(className = 'dt-center', targets = '_all'))
961
+ ),
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)
970
+ })
971
+ })
972
+
973
+ # Residual plot
974
+ output$residual_plot <- renderPlotly({
975
+ req(anova_analysis())
976
+
977
+ tryCatch({
978
+ res_data <- anova_analysis()$residuals
979
 
980
+ p <- ggplot(res_data, aes(x = Fitted, y = Residuals, color = Genotype)) +
981
+ geom_point(size = 1, alpha = 0.6) +
982
+ geom_smooth(method = "loess", se = FALSE, color = get_color_palette(rv$color_scheme, 1)[2]) +
983
+ geom_hline(yintercept = 0, linetype = "dashed", color = get_color_palette(rv$color_scheme, 1)[2]) +
984
+ labs(title = "Residuals vs Fitted Values",
985
+ x = "Fitted Values", y = "Residuals") +
986
+ theme_minimal() +
987
+ theme(
988
+ axis.text = element_text(color = "#000000"),
989
+ axis.title = element_text(color = "#000000"),
990
+ plot.title = element_text(color = "#000000")
991
+ ) +
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)
998
  })
999
+ })
1000
 
1001
+ # Q-Q plot
1002
+ output$qq_plot <- renderPlotly({
1003
+ req(anova_analysis())
1004
+
 
 
 
 
 
1005
  tryCatch({
1006
+ res_data <- anova_analysis()$residuals
1007
+
1008
+ p <- ggplot(res_data, aes(sample = Standardized_Residuals, color = Genotype)) +
1009
+ stat_qq(size = 1) +
1010
+ stat_qq_line(color = get_color_palette(rv$color_scheme, 1)[2]) +
1011
+ labs(title = "Normal Q-Q Plot",
1012
+ x = "Theoretical Quantiles", y = "Sample Quantiles") +
1013
+ theme_minimal() +
1014
+ theme(
1015
+ axis.text = element_text(color = "#000000"),
1016
+ axis.title = element_text(color = "#000000"),
1017
+ plot.title = element_text(color = "#000000")
1018
+ ) +
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)
1025
+ })
1026
+ })
1027
+
1028
+ # Mixed model analysis and BLUEs
1029
+ mixed_model_analysis <- reactive({
1030
+ req(rv$data, input$selected_trait)
1031
+
1032
+ withProgress(message = 'Running Mixed Model Analysis...', value = 0, {
1033
+ incProgress(0.3, detail = "Preparing data...")
1034
+
1035
+ if (!input$selected_trait %in% rv$traits) return(NULL)
1036
+
1037
+ tryCatch({
1038
+ incProgress(0.5, detail = "Fitting mixed model...")
1039
+
1040
+ trait_data <- rv$data %>%
1041
+ select(Genotype, Environment, Rep, Block, all_of(input$selected_trait)) %>%
1042
+ rename(Value = !!input$selected_trait) %>%
1043
+ filter(!is.na(Value)) %>%
1044
+ mutate(
1045
+ Genotype = as.factor(Genotype),
1046
+ Environment = as.factor(Environment),
1047
+ Rep = as.factor(Rep),
1048
+ Block = as.factor(Block)
1049
+ )
1050
+
1051
+ if (nrow(trait_data) < 10) {
1052
+ showNotification("Insufficient data for mixed model (need at least 10 observations)", type = "error")
1053
+ return(NULL)
1054
+ }
1055
+
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)
1067
+ blues_df <- as.data.frame(blues) %>%
1068
+ select(Genotype, Environment, emmean, SE) %>%
1069
+ rename(BLUE = emmean)
1070
+
1071
+ incProgress(1, detail = "Complete!")
1072
+
1073
+ list(model = model, blues = blues_df)
1074
+
1075
+ }, error = function(e) {
1076
+ showNotification(paste("Mixed Model Error:", e$message), type = "error")
1077
+ return(NULL)
1078
+ })
1079
+ })
1080
+ })
1081
+
1082
+ # BLUEs plot
1083
+ output$blues_plot <- renderPlotly({
1084
+ req(mixed_model_analysis())
1085
+
1086
+ tryCatch({
1087
+ blues_data <- mixed_model_analysis()$blues
1088
+
1089
+ p <- ggplot(blues_data, aes(x = Environment, y = BLUE, color = Genotype, group = Genotype)) +
1090
+ geom_line(size = 1) +
1091
+ geom_point(size = 1) +
1092
+ labs(title = paste("BLUEs for", input$selected_trait),
1093
+ x = "Environment", y = "BLUE Value") +
1094
+ theme_minimal() +
1095
+ theme(
1096
+ axis.text = element_text(color = "#000000"),
1097
+ axis.title = element_text(color = "#000000"),
1098
+ plot.title = element_text(color = "#000000"),
1099
+ axis.text.x = element_text(angle = 45, hjust = 1)
1100
+ ) +
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)
1107
  })
1108
+ })
1109
 
1110
+ # BLUEs table
1111
+ output$blues_table <- renderDT({
1112
+ req(mixed_model_analysis())
1113
+
 
 
1114
  tryCatch({
1115
+ datatable(
1116
+ mixed_model_analysis()$blues,
1117
+ extensions = 'Buttons',
1118
+ options = list(
1119
+ scrollX = TRUE,
1120
+ dom = 'Bfrtip',
1121
+ buttons = c('copy', 'excel', 'csv'),
1122
+ pageLength = 15,
1123
+ columnDefs = list(list(className = 'dt-center', targets = '_all'))
1124
+ ),
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)
1131
  })
1132
+ })
1133
 
1134
+ # Heritability analysis
1135
+ heritability_analysis <- reactive({
1136
+ req(rv$data, rv$traits)
 
 
 
1137
 
1138
+ withProgress(message = 'Running Heritability Analysis...', value = 0, {
1139
+ incProgress(0.2, detail = "Preparing traits...")
1140
+
1141
+ if (length(rv$traits) < 1) {
1142
+ showNotification("No numeric traits available for heritability analysis", type = "error")
1143
+ return(NULL)
1144
+ }
1145
+
1146
+ herit_results <- list()
1147
+
1148
+ for (trait in rv$traits) {
1149
+ tryCatch({
1150
+ incProgress(0.4, detail = paste("Processing", trait, "..."))
1151
+
1152
+ trait_data <- rv$data %>%
1153
+ select(Genotype, Environment, Rep, Block, all_of(trait)) %>%
1154
+ rename(Value = !!trait) %>%
1155
+ filter(!is.na(Value)) %>%
1156
+ mutate(
1157
+ Genotype = as.factor(Genotype),
1158
+ Environment = as.factor(Environment),
1159
+ Rep = as.factor(Rep),
1160
+ Block = as.factor(Block)
1161
+ )
1162
+
1163
+ if (nrow(trait_data) < 10) {
1164
+ showNotification(paste("Insufficient data for", trait, "(need at least 10 observations)"), type = "error")
1165
+ next
1166
+ }
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
1175
+
1176
+ var_g <- var_comp$vcov[var_comp$grp == "Genotype"]
1177
+ var_ge <- var_comp$vcov[var_comp$grp == "Genotype:Environment"]
1178
+ var_e <- var_comp$vcov[var_comp$grp == "Residual"]
1179
+
1180
+ var_g <- ifelse(length(var_g) == 0, 0, var_g)
1181
+ var_ge <- ifelse(length(var_ge) == 0, 0, var_ge)
1182
+ var_e <- ifelse(length(var_e) == 0, 1, var_e)
1183
+
1184
+ h2_broad <- var_g / (var_g + var_ge + var_e)
1185
+
1186
+ n_env <- length(unique(trait_data$Environment))
1187
+ n_rep <- length(unique(trait_data$Rep))
1188
+ h2_entry <- var_g / (var_g + (var_ge / n_env) + (var_e / (n_env * n_rep)))
1189
+
1190
+ herit_results[[trait]] <- list(
1191
+ trait = trait,
1192
+ variance_components = var_comp,
1193
+ h2_broad = h2_broad,
1194
+ h2_entry = h2_entry
1195
+ )
1196
+
1197
+ incProgress(0.9, detail = paste("Completed", trait))
1198
+
1199
+ }, error = function(e) {
1200
+ showNotification(paste("Heritability error for", trait, ":", e$message), type = "error")
1201
+ })
1202
+ }
1203
+
1204
+ incProgress(1, detail = "Complete!")
1205
+ if (length(herit_results) == 0) return(NULL)
1206
+ herit_results
1207
+ })
1208
+ })
1209
+
1210
+ # Variance components table
1211
+ output$variance_components <- renderDT({
1212
+ req(heritability_analysis())
1213
+
1214
+ tryCatch({
1215
+ all_var_comp <- do.call(rbind, lapply(heritability_analysis(), function(x) x$variance_components))
1216
+
1217
+ datatable(
1218
+ all_var_comp,
1219
+ extensions = 'Buttons',
1220
+ options = list(
1221
+ scrollX = TRUE,
1222
+ dom = 'Bfrtip',
1223
+ buttons = c('copy', 'excel', 'csv'),
1224
+ pageLength = 10,
1225
+ columnDefs = list(list(className = 'dt-center', targets = '_all'))
1226
+ ),
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)
1233
+ })
1234
+ })
1235
+
1236
+ # Heritability table
1237
+ output$heritability_table <- renderDT({
1238
+ req(heritability_analysis())
1239
 
1240
+ tryCatch({
1241
+ herit_summary <- data.frame(
1242
+ Trait = names(heritability_analysis()),
1243
+ H2_Broad = sapply(heritability_analysis(), function(x) round(x$h2_broad, 3)),
1244
+ H2_Entry = sapply(heritability_analysis(), function(x) round(x$h2_entry, 3)),
1245
+ stringsAsFactors = FALSE
1246
+ )
1247
+
1248
+ datatable(
1249
+ herit_summary,
1250
+ extensions = 'Buttons',
1251
+ options = list(
1252
+ scrollX = TRUE,
1253
+ dom = 'Bfrtip',
1254
+ buttons = c('copy', 'excel', 'csv'),
1255
+ pageLength = 10,
1256
+ columnDefs = list(list(className = 'dt-center', targets = '_all'))
1257
+ ),
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)
1266
+ })
1267
+ })
1268
+
1269
+ # Heritability plot
1270
+ output$heritability_plot <- renderPlotly({
1271
+ req(heritability_analysis())
1272
 
1273
+ tryCatch({
1274
+ herit_summary <- data.frame(
1275
+ Trait = names(heritability_analysis()),
1276
+ H2_Broad = sapply(heritability_analysis(), function(x) x$h2_broad),
1277
+ H2_Entry = sapply(heritability_analysis(), function(x) x$h2_entry)
1278
+ ) %>%
1279
+ pivot_longer(cols = c(H2_Broad, H2_Entry), names_to = "Type", values_to = "Heritability")
1280
+
1281
+ p <- ggplot(herit_summary, aes(x = Trait, y = Heritability, fill = Type)) +
1282
+ geom_col(position = "dodge", alpha = 0.8) +
1283
+ labs(title = "Heritability Estimates by Trait",
1284
+ x = "Trait", y = "Heritability") +
1285
+ theme_minimal() +
1286
+ theme(
1287
+ axis.text = element_text(color = "#000000"),
1288
+ axis.title = element_text(color = "#000000"),
1289
+ plot.title = element_text(color = "#000000"),
1290
+ axis.text.x = element_text(angle = 45, hjust = 1)
1291
+ ) +
1292
+ scale_fill_manual(values = get_color_palette(rv$color_scheme, 2)) +
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)
1299
+ })
1300
+ })
1301
+
1302
+ # Correlation analysis
1303
+ correlation_analysis <- reactive({
1304
+ req(rv$data, rv$traits)
1305
 
1306
+ withProgress(message = 'Computing Correlations...', value = 0, {
1307
+ incProgress(0.3, detail = "Preparing data...")
1308
+
1309
+ if (length(rv$traits) < 2) {
1310
+ showNotification("Need at least 2 numeric traits for correlation analysis", type = "error")
1311
+ return(NULL)
1312
+ }
1313
+
1314
+ tryCatch({
1315
+ incProgress(0.6, detail = "Calculating correlations...")
1316
+
1317
+ trait_data <- rv$data %>%
1318
+ select(all_of(rv$traits)) %>%
1319
+ na.omit()
1320
+
1321
+ if (nrow(trait_data) < 10) {
1322
+ showNotification("Insufficient data for correlation analysis (need at least 10 observations)", type = "error")
1323
+ return(NULL)
1324
+ }
1325
+
1326
+ cor_matrix <- cor(trait_data, use = "complete.obs")
1327
+
1328
+ cor_table <- cor_matrix %>%
1329
+ as.data.frame() %>%
1330
+ rownames_to_column("Trait1") %>%
1331
+ pivot_longer(-Trait1, names_to = "Trait2", values_to = "Correlation") %>%
1332
+ filter(Trait1 != Trait2) %>%
1333
+ mutate(
1334
+ Correlation = round(Correlation, 3),
1335
+ Abs_Correlation = abs(Correlation)
1336
+ ) %>%
1337
+ arrange(desc(Abs_Correlation))
1338
+
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)
1345
+ })
1346
+ })
1347
+ })
1348
+
1349
+ # Correlation heatmap
1350
+ output$correlation_heatmap <- renderPlot({
1351
+ req(correlation_analysis())
1352
 
1353
+ tryCatch({
1354
+ cor_matrix <- correlation_analysis()$matrix
1355
+
1356
+ corrplot::corrplot(cor_matrix,
1357
+ method = "color",
1358
+ type = "upper",
1359
+ order = "hclust",
1360
+ tl.cex = 0.8,
1361
+ tl.col = "#000000",
1362
+ tl.srt = 45,
1363
+ addCoef.col = "#000000",
1364
+ number.cex = 0.7,
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)
1371
  })
1372
+ }, height = function() rv$plot_height, width = function() rv$plot_width)
1373
+
1374
+ # Correlation table
1375
+ output$correlation_table <- renderDT({
1376
+ req(correlation_analysis())
1377
 
1378
+ tryCatch({
1379
+ datatable(
1380
+ correlation_analysis()$table,
1381
+ extensions = 'Buttons',
1382
+ options = list(
1383
+ scrollX = TRUE,
1384
+ dom = 'Bfrtip',
1385
+ buttons = c('copy', 'excel', 'csv'),
1386
+ pageLength = 15,
1387
+ columnDefs = list(list(className = 'dt-center', targets = '_all'))
1388
+ ),
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)
1398
+ })
1399
+ })
1400
+
1401
+ # Correlation network plot
1402
+ output$correlation_network <- renderPlot({
1403
+ req(correlation_analysis())
1404
 
1405
+ tryCatch({
1406
+ cor_matrix <- correlation_analysis()$matrix
 
1407
 
1408
+ corrplot::corrplot(cor_matrix,
1409
+ method = "circle",
1410
+ type = "full",
1411
+ order = "hclust",
1412
+ tl.cex = 0.8,
1413
+ tl.col = "#000000",
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)
1420
+ })
1421
+ }, height = function() rv$plot_height, width = function() rv$plot_width)
1422
+
1423
+ # PCA analysis
1424
+ pca_analysis <- reactive({
1425
+ req(rv$data, rv$traits)
1426
+
1427
+ withProgress(message = 'Running PCA Analysis...', value = 0, {
1428
+ incProgress(0.3, detail = "Preparing data...")
1429
 
1430
+ if (length(rv$traits) < 2) {
1431
+ showNotification("Need at least 2 numeric traits for PCA", type = "error")
1432
+ return(NULL)
 
 
 
 
 
1433
  }
1434
 
1435
+ tryCatch({
1436
+ incProgress(0.6, detail = "Computing PCA...")
1437
+
1438
+ trait_data <- rv$data %>%
1439
+ select(Genotype, all_of(rv$traits)) %>%
1440
+ na.omit()
1441
+
1442
+ if (nrow(trait_data) < 10) {
1443
+ showNotification("Insufficient data for PCA (need at least 10 observations)", type = "error")
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) %>%
1451
+ mutate(Genotype = trait_data$Genotype)
1452
+
1453
+ var_explained <- data.frame(
1454
+ PC = paste0("PC", 1:length(pca_result$sdev)),
1455
+ Variance = pca_result$sdev^2,
1456
+ Prop_Variance = pca_result$sdev^2 / sum(pca_result$sdev^2),
1457
+ Cumulative = cumsum(pca_result$sdev^2 / sum(pca_result$sdev^2))
1458
+ )
1459
+
1460
+ loadings <- as.data.frame(pca_result$rotation) %>%
1461
+ rownames_to_column("Trait")
1462
+
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)
 
 
 
 
 
 
 
 
 
 
 
 
 
1469
  })
1470
+ })
1471
+ })
1472
+
1473
+ # PCA plot
1474
+ output$pca_plot <- renderPlotly({
1475
+ req(pca_analysis())
1476
+
1477
+ tryCatch({
1478
+ pca_scores <- pca_analysis()$scores
1479
 
1480
+ p <- ggplot(pca_scores, aes(x = PC1, y = PC2, color = Genotype, text = Genotype)) +
1481
+ geom_point(size = 1, alpha = 0.7) +
1482
+ labs(title = "PCA Biplot",
1483
+ x = paste0("PC1 (", round(pca_analysis()$variance$Prop_Variance[1] * 100, 1), "%)"),
1484
+ y = paste0("PC2 (", round(pca_analysis()$variance$Prop_Variance[2] * 100, 1), "%)")) +
1485
+ theme_minimal() +
1486
+ theme(
1487
+ axis.text = element_text(color = "#000000"),
1488
+ axis.title = element_text(color = "#000000"),
1489
+ plot.title = element_text(color = "#000000")
1490
+ ) +
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)
1497
  })
1498
  })
1499
 
1500
+ # PCA variance plot
1501
+ output$pca_variance_plot <- renderPlotly({
1502
+ req(pca_analysis())
1503
+
1504
+ tryCatch({
1505
+ var_data <- pca_analysis()$variance
1506
+
1507
+ p <- ggplot(var_data[1:min(10, nrow(var_data)), ], aes(x = PC, y = Prop_Variance)) +
1508
+ geom_col(fill = get_color_palette(rv$color_scheme, 1)[1], alpha = 0.8) +
1509
+ geom_line(aes(y = Cumulative, group = 1), color = get_color_palette(rv$color_scheme, 1)[2], size = 1) +
1510
+ geom_point(aes(y = Cumulative), color = get_color_palette(rv$color_scheme, 1)[2], size = 1) +
1511
+ labs(title = "PCA Variance Explained",
1512
+ x = "Principal Component", y = "Proportion of Variance") +
1513
+ theme_minimal() +
1514
+ theme(
1515
+ axis.text = element_text(color = "#000000"),
1516
+ axis.title = element_text(color = "#000000"),
1517
+ plot.title = element_text(color = "#000000"),
1518
+ axis.text.x = element_text(angle = 45, hjust = 1)
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)
1525
+ })
1526
  })
1527
 
1528
+ # PCA loadings table
1529
+ output$pca_loadings <- renderDT({
1530
+ req(pca_analysis())
1531
+
1532
+ tryCatch({
1533
+ loadings_data <- pca_analysis()$loadings[, 1:min(5, ncol(pca_analysis()$loadings))]
1534
+
1535
+ datatable(
1536
+ loadings_data,
1537
+ extensions = 'Buttons',
1538
+ options = list(
1539
+ scrollX = TRUE,
1540
+ dom = 'Bfrtip',
1541
+ buttons = c('copy', 'excel', 'csv'),
1542
+ pageLength = 10,
1543
+ columnDefs = list(list(className = 'dt-center', targets = '_all'))
1544
+ ),
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)
1551
+ })
1552
  })
1553
 
1554
+ # PCA summary table
1555
+ output$pca_summary <- renderDT({
1556
+ req(pca_analysis())
1557
+
1558
+ tryCatch({
1559
+ datatable(
1560
+ pca_analysis()$variance,
1561
+ extensions = 'Buttons',
1562
+ options = list(
1563
+ scrollX = TRUE,
1564
+ dom = 'Bfrtip',
1565
+ buttons = c('copy', 'excel', 'csv'),
1566
+ pageLength = 10,
1567
+ columnDefs = list(list(className = 'dt-center', targets = '_all'))
1568
+ ),
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)
1575
+ })
 
 
 
 
 
 
 
 
1576
  })
1577
 
1578
+ # Clustering analysis
1579
+ clustering_analysis <- reactive({
1580
+ req(rv$data, rv$traits, input$n_clusters)
 
 
 
 
 
 
 
 
 
 
 
 
1581
 
1582
+ withProgress(message = 'Running Clustering Analysis...', value = 0, {
1583
+ incProgress(0.3, detail = "Preparing data...")
1584
+
1585
+ if (length(rv$traits) < 2) {
1586
+ showNotification("Need at least 2 numeric traits for clustering", type = "error")
1587
+ return(NULL)
1588
+ }
1589
+
1590
+ tryCatch({
1591
+ incProgress(0.6, detail = "Performing clustering...")
1592
+
1593
+ trait_data <- rv$data %>%
1594
+ select(Genotype, all_of(rv$traits)) %>%
1595
+ na.omit()
1596
+
1597
+ if (nrow(trait_data) < input$n_clusters + 2) {
1598
+ showNotification("Insufficient data for clustering (need more observations than clusters)", type = "error")
1599
+ return(NULL)
1600
+ }
1601
+
1602
+ cluster_data <- trait_data %>%
1603
+ select(-Genotype) %>%
1604
+ scale()
1605
+
1606
+ rownames(cluster_data) <- trait_data$Genotype
1607
+
1608
+ if (input$clustering_method == "kmeans") {
1609
+ cluster_result <- kmeans(cluster_data, centers = input$n_clusters, nstart = 25)
1610
+ clusters <- cluster_result$cluster
1611
+ hclust_result <- NULL
1612
+ } else {
1613
+ dist_matrix <- dist(cluster_data)
1614
+ hclust_result <- hclust(dist_matrix, method = "ward.D2")
1615
+ clusters <- cutree(hclust_result, k = input$n_clusters)
1616
+ }
1617
+
1618
+ cluster_df <- data.frame(
1619
+ Genotype = trait_data$Genotype,
1620
+ Cluster = as.factor(clusters)
1621
+ )
1622
+
1623
+ cluster_summary <- trait_data %>%
1624
+ mutate(Cluster = as.factor(clusters)) %>%
1625
+ group_by(Cluster) %>%
1626
+ summarise_at(vars(all_of(rv$traits)), mean, na.rm = TRUE) %>%
1627
+ mutate(Count = as.numeric(table(clusters)))
1628
+
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)
1641
+ })
1642
+ })
1643
+ })
1644
+
1645
+ # Cluster plot
1646
+ output$cluster_plot <- renderPlotly({
1647
+ req(clustering_analysis())
1648
 
1649
+ tryCatch({
1650
+ cluster_data <- clustering_analysis()$data
1651
+ clusters <- clustering_analysis()$clusters
1652
+
1653
+ if (ncol(cluster_data) > 2) {
1654
+ pca_for_plot <- prcomp(cluster_data)
1655
+ plot_data <- data.frame(
1656
+ PC1 = pca_for_plot$x[, 1],
1657
+ PC2 = pca_for_plot$x[, 2],
1658
+ Genotype = clusters$Genotype,
1659
+ Cluster = clusters$Cluster
1660
+ )
1661
+
1662
+ p <- ggplot(plot_data, aes(x = PC1, y = PC2, color = Genotype, text = Genotype)) +
1663
+ geom_point(size = 1, alpha = 0.8) +
1664
+ labs(title = "Genotype Clustering (PCA Space)",
1665
+ x = "PC1", y = "PC2") +
1666
+ theme_minimal() +
1667
+ theme(
1668
+ axis.text = element_text(color = "#000000"),
1669
+ axis.title = element_text(color = "#000000"),
1670
+ plot.title = element_text(color = "#000000")
1671
+ ) +
1672
+ scale_color_manual(values = get_color_palette(rv$color_scheme, length(unique(plot_data$Genotype))))
1673
+ } else {
1674
+ plot_data <- data.frame(
1675
+ X = cluster_data[, 1],
1676
+ Y = cluster_data[, 2],
1677
+ Genotype = clusters$Genotype,
1678
+ Cluster = clusters$Cluster
1679
+ )
1680
+
1681
+ p <- ggplot(plot_data, aes(x = X, y = Y, color = Genotype, text = Genotype)) +
1682
+ geom_point(size = 1, alpha = 0.8) +
1683
+ labs(title = "Genotype Clustering",
1684
+ x = rv$traits[1], y = rv$traits[2]) +
1685
+ theme_minimal() +
1686
+ theme(
1687
+ axis.text = element_text(color = "#000000"),
1688
+ axis.title = element_text(color = "#000000"),
1689
+ plot.title = element_text(color = "#000000")
1690
+ ) +
1691
+ scale_color_manual(values = get_color_palette(rv$color_scheme, length(unique(plot_data$Genotype))))
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)
1698
+ })
1699
+ })
1700
+
1701
+ # Dendrogram
1702
+ output$dendrogram <- renderPlot({
1703
+ req(clustering_analysis(), clustering_analysis()$method == "hierarchical")
1704
 
1705
+ tryCatch({
1706
+ hclust_result <- clustering_analysis()$hclust
1707
+
1708
+ plot(hclust_result,
1709
+ main = "Hierarchical Clustering Dendrogram",
1710
+ xlab = "Genotypes",
1711
+ ylab = "Distance",
1712
+ cex = 0.8,
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)
1719
+ })
1720
+ }, height = function() rv$plot_height, width = function() rv$plot_width)
1721
+
1722
+ # Cluster summary table
1723
+ output$cluster_summary <- renderDT({
1724
+ req(clustering_analysis())
1725
+
1726
+ tryCatch({
1727
+ datatable(
1728
+ clustering_analysis()$summary,
1729
+ extensions = 'Buttons',
1730
+ options = list(
1731
+ scrollX = TRUE,
1732
+ dom = 'Bfrtip',
1733
+ buttons = c('copy', 'excel', 'csv'),
1734
+ pageLength = 10,
1735
+ columnDefs = list(list(className = 'dt-center', targets = '_all'))
1736
+ ),
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)
1743
+ })
1744
  })
1745
 
1746
+ # Stability analysis
1747
+ stability_analysis <- reactive({
1748
+ req(rv$data, input$selected_trait)
1749
+
1750
+ withProgress(message = 'Running Stability Analysis...', value = 0, {
1751
+ incProgress(0.3, detail = "Preparing data...")
1752
+
1753
+ if (!input$selected_trait %in% rv$traits) return(NULL)
1754
+
1755
+ tryCatch({
1756
+ incProgress(0.6, detail = "Computing stability parameters...")
1757
+
1758
+ stability_data <- rv$data %>%
1759
+ select(Genotype, Environment, all_of(input$selected_trait)) %>%
1760
+ rename(Value = !!input$selected_trait) %>%
1761
+ filter(!is.na(Value)) %>%
1762
+ group_by(Genotype, Environment) %>%
1763
+ summarise(Mean_Value = mean(Value, na.rm = TRUE), .groups = "drop")
1764
+
1765
+ if (nrow(stability_data) < 10) {
1766
+ showNotification("Insufficient data for stability analysis (need at least 10 observations)", type = "error")
1767
+ return(NULL)
1768
+ }
1769
+
1770
+ overall_mean <- mean(stability_data$Mean_Value, na.rm = TRUE)
1771
+
1772
+ stability_params <- stability_data %>%
1773
+ group_by(Genotype) %>%
1774
+ summarise(
1775
+ Overall_Mean = mean(Mean_Value, na.rm = TRUE),
1776
+ CV = (sd(Mean_Value, na.rm = TRUE) / mean(Mean_Value, na.rm = TRUE)) * 100,
1777
+ Ecovalence = sum((Mean_Value - overall_mean)^2, na.rm = TRUE),
1778
+ Min_Value = min(Mean_Value, na.rm = TRUE),
1779
+ Max_Value = max(Mean_Value, na.rm = TRUE),
1780
+ Range = Max_Value - Min_Value,
1781
+ .groups = "drop"
1782
+ ) %>%
1783
+ mutate(
1784
+ CV = round(CV, 2),
1785
+ Ecovalence = round(Ecovalence, 3),
1786
+ Stability_Rank = rank(Ecovalence)
1787
+ )
1788
+
1789
+ env_means <- stability_data %>%
1790
+ group_by(Environment) %>%
1791
+ summarise(Env_Mean = mean(Mean_Value, na.rm = TRUE), .groups = "drop")
1792
+
1793
+ ammi_data <- stability_data %>%
1794
+ left_join(env_means, by = "Environment") %>%
1795
+ mutate(
1796
+ Env_Index = Env_Mean - overall_mean,
1797
+ GE_Interaction = Mean_Value - overall_mean - Env_Index
1798
+ ) %>%
1799
+ left_join(stability_params %>% select(Genotype, Overall_Mean), by = "Genotype")
1800
+
1801
+ incProgress(1, detail = "Complete!")
1802
+
1803
+ list(
1804
+ parameters = stability_params,
1805
+ data = stability_data,
1806
+ ammi_data = ammi_data,
1807
+ env_means = env_means
1808
+ )
1809
+
1810
+ }, error = function(e) {
1811
+ showNotification(paste("Stability Analysis Error:", e$message), type = "error")
1812
+ return(NULL)
1813
+ })
1814
+ })
1815
  })
1816
 
1817
+ # Stability plot
1818
+ output$stability_plot <- renderPlotly({
1819
+ req(stability_analysis())
1820
+
1821
+ tryCatch({
1822
+ stability_params <- stability_analysis()$parameters
1823
+
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)
1845
+ })
1846
  })
1847
 
1848
+ # AMMI-like plot
1849
+ output$ammi_plot <- renderPlotly({
1850
+ req(stability_analysis())
1851
+
1852
+ tryCatch({
1853
+ ammi_data <- stability_analysis()$ammi_data
1854
+
1855
+ p <- ggplot(ammi_data, aes(x = Environment, y = Mean_Value, color = Genotype, group = Genotype)) +
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"),
1864
+ axis.title = element_text(color = "#000000"),
1865
+ plot.title = element_text(color = "#000000"),
1866
+ axis.text.x = element_text(angle = 45, hjust = 1)
1867
+ ) +
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)
1874
+ })
1875
+ })
1876
+
1877
+ # Stability table
1878
+ output$stability_table <- renderDT({
1879
+ req(stability_analysis())
1880
+
1881
+ tryCatch({
1882
+ datatable(
1883
+ stability_analysis()$parameters,
1884
+ extensions = 'Buttons',
1885
+ options = list(
1886
+ scrollX = TRUE,
1887
+ dom = 'Bfrtip',
1888
+ buttons = c('copy', 'excel', 'csv'),
1889
+ pageLength = 15,
1890
+ columnDefs = list(list(className = 'dt-center', targets = '_all'))
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
1907
+ shinyApp(ui = ui, server = server)