International Rice Research Institute commited on
Commit
6b1913b
·
verified ·
1 Parent(s): 932b4db

Update app.R

Browse files
Files changed (1) hide show
  1. app.R +1259 -144
app.R CHANGED
@@ -1,192 +1,1307 @@
1
- # LME4: File upload observer (modified correlation section)
2
- observeEvent(input$lme4_file, {
3
- req(input$lme4_file)
4
- message("LME4: File upload triggered: ", input$lme4_file$name)
5
- shinyjs::show("lme4_loader")
6
- on.exit(shinyjs::hide("lme4_loader"))
7
-
8
- result <- lme4_process_data(input$lme4_file$datapath)
9
- if (is.null(result)) {
10
- return()
11
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
 
13
- rv_lme4$data <- result$data
14
- rv_lme4$traits <- result$traits
15
- rv_lme4$trait <- result$traits[1]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
 
17
- updateSelectInput(session, "lme4_selected_trait", choices = rv_lme4$traits, selected = rv_lme4$traits[1])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
 
19
- shinyjs::show("lme4_data_stats")
20
- output$lme4_n_vars <- renderText({ ncol(rv_lme4$data) })
21
- output$lme4_n_obs <- renderText({ nrow(rv_lme4$data) })
22
- output$lme4_n_geno <- renderText({ length(unique(rv_lme4$data$Genotype)) })
23
- output$lme4_n_env <- renderText({ length(unique(rv_lme4$data$Environment)) })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
 
25
- output$lme4_data_preview <- renderPrint({
26
- str(rv_lme4$data)
27
- })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
 
29
- debug_log <- c()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
 
31
- withProgress(message = 'LME4: Analyzing data', value = 0, {
32
- fixed_models <- list()
33
- random_models <- list()
34
- blues_list <- list()
35
- herit_list <- list()
36
- stability_list <- list()
37
-
38
- n_traits <- length(rv_lme4$traits)
39
- total_steps <- n_traits * 3 + 3 # fixed model, random model, stability, correlations, descriptives, pca
40
- step_increment <- 1 / total_steps
41
-
42
- for (trait in rv_lme4$traits) {
43
- incProgress(step_increment, detail = paste("Fitting fixed model for", trait))
44
- fixed_model <- lme4_fit_fixed_model(rv_lme4$data, trait)
45
- fixed_models[[trait]] <- fixed_model
46
- debug_log <- c(debug_log, paste("Trait:", trait, "- Fixed model:", ifelse(is.null(fixed_model), "Failed", "Success")))
47
 
48
- incProgress(step_increment, detail = paste("Calculating predicted means for", trait))
49
- blues_list[[trait]] <- lme4_get_blue(fixed_model, trait)
 
 
 
 
 
 
 
 
 
50
 
51
- incProgress(step_increment, detail = paste("Fitting random model for", trait))
52
- random_model <- lme4_fit_random_model(rv_lme4$data, trait)
53
- random_models[[trait]] <- random_model
54
- debug_log <- c(debug_log, paste("Trait:", trait, "- Random model:", ifelse(is.null(random_model), "Failed", "Success")))
 
 
 
 
 
 
 
 
 
 
 
 
 
55
 
56
- herit_list[[trait]] <- lme4_get_heritability(random_model, trait)
 
 
 
57
 
58
- incProgress(step_increment, detail = paste("Calculating stability for", trait))
59
- stability_list[[trait]] <- lme4_get_stability(blues_list[[trait]], trait)
60
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
 
62
- incProgress(step_increment, detail = "Calculating correlations")
63
- if (n_traits > 1) {
64
- trait_data <- rv_lme4$data %>% select(all_of(rv_lme4$traits)) %>% na.omit()
65
- if (nrow(trait_data) > 0) {
66
- cor_matrix <- cor(trait_data, use = "pairwise.complete.obs")
67
- # Convert correlation matrix to scatter plot format
68
- cor_table <- as.data.frame(as.table(cor_matrix)) %>%
69
- rename(Trait1 = Var1, Trait2 = Var2, Correlation = Freq) %>%
70
- mutate(Correlation = round(Correlation, 3)) %>%
71
- filter(Trait1 != Trait2) %>% # Exclude self-correlations
72
- mutate(Abs_Correlation = abs(Correlation)) # For point size
73
- rv_lme4$cor_matrix <- cor_matrix
74
- rv_lme4$cor_table <- cor_table
75
- debug_log <- c(debug_log, "Correlations: Success")
76
- } else {
77
- rv_lme4$cor_matrix <- matrix(NA, nrow = 1, ncol = 1, dimnames = list("NoData", "NoData"))
78
- rv_lme4$cor_table <- data.frame(Trait1 = "NoData", Trait2 = "NoData", Correlation = NA, Abs_Correlation = NA)
79
- debug_log <- c(debug_log, "Correlations: No valid data")
80
- }
81
- } else {
82
- rv_lme4$cor_matrix <- matrix(1, nrow = 1, ncol = 1, dimnames = list(rv_lme4$traits, rv_lme4$traits))
83
- rv_lme4$cor_table <- data.frame(Trait1 = rv_lme4$traits, Trait2 = rv_lme4$traits, Correlation = 1, Abs_Correlation = 1)
84
- debug_log <- c(debug_log, "Correlations: Single trait")
85
  }
86
 
87
- incProgress(step_increment, detail = "Calculating descriptive statistics")
88
- descriptives <- rv_lme4$data %>%
89
- select(all_of(rv_lme4$traits)) %>%
90
- pivot_longer(cols = everything(), names_to = "Trait", values_to = "Value") %>%
91
- group_by(Trait) %>%
92
- summarise(
93
- Mean = mean(Value, na.rm = TRUE),
94
- SD = sd(Value, na.rm = TRUE),
95
- Min = min(Value, na.rm = TRUE),
96
- Max = max(Value, na.rm = TRUE),
97
- N = sum(!is.na(Value)),
98
- .groups = "drop"
99
- ) %>%
100
- mutate(CV = round((SD / Mean) * 100, 2))
101
- rv_lme4$descriptives <- descriptives
102
- debug_log <- c(debug_log, "Descriptives: Success")
103
-
104
- incProgress(step_increment, detail = "Calculating heritability")
105
- rv_lme4$heritability <- bind_rows(herit_list)
106
- debug_log <- c(debug_log, "Heritability: Success")
107
 
108
- incProgress(step_increment, detail = "Calculating rankings")
109
- rv_lme4$blues_all <- bind_rows(blues_list) %>% filter(!is.na(predicted.value))
110
- rankings <- rv_lme4$blues_all %>%
111
- group_by(Trait, Genotype) %>%
112
- summarise(Mean = mean(predicted.value, na.rm = TRUE), .groups = "drop") %>%
113
- group_by(Trait) %>%
114
- mutate(Rank = rank(-Mean, ties.method = "min")) %>%
115
- arrange(Trait, Rank)
116
- rv_lme4$rankings <- rankings
117
- debug_log <- c(debug_log, "Rankings: Success")
118
 
119
- incProgress(step_increment, detail = "Calculating stability")
120
- rv_lme4$stability <- bind_rows(stability_list)
121
- debug_log <- c(debug_log, "Stability: Success")
 
 
122
 
123
- incProgress(step_increment, detail = "Calculating PCA")
124
- rv_lme4$pca <- lme4_get_pca(rv_lme4$blues_all, rv_lme4$traits)
125
- debug_log <- c(debug_log, "PCA: Success")
126
-
127
- rv_lme4$fixed_models <- fixed_models
128
- rv_lme4$random_models <- random_models
129
- rv_lme4$debug_log <- debug_log
130
 
131
- shinyjs::hide(c("lme4_blues_placeholder", "lme4_correlations_placeholder",
132
- "lme4_descriptives_placeholder", "lme4_heritability_placeholder",
133
- "lme4_rankings_placeholder", "lme4_stability_placeholder",
134
- "lme4_pca_placeholder"))
135
- shinyjs::show(c("lme4_blues_content", "lme4_correlations_content",
136
- "lme4_descriptives_content", "lme4_heritability_content",
137
- "lme4_rankings_content", "lme4_stability_content",
138
- "lme4_pca_content"))
139
 
140
- output$lme4_debug_log <- renderPrint({
141
- cat(paste(rv_lme4$debug_log, collapse = "\n"))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
142
  })
143
-
144
- showNotification("LME4: File uploaded and analyzed successfully", type = "message", duration = 5)
145
  })
146
 
147
- # LME4: Correlation scatter plot
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
148
  output$lme4_correlation_plot <- renderPlotly({
149
- req(rv_lme4$cor_table)
150
- data <- rv_lme4$cor_table
151
- if (nrow(data) == 0 || all(is.na(data$Correlation)) || all(data$Trait1 == data$Trait2)) {
152
  return(plot_ly() %>%
153
  layout(
154
  title = list(text = "No Valid Correlation Data", font = PLOT_FONT),
155
  annotations = list(
156
- text = "Correlation scatter plot requires at least two valid traits with non-self correlations.",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
157
  x = 0.5, y = 0.5, xref = "paper", yref = "paper",
158
  showarrow = FALSE, font = list(size = 12, color = "#2D3748")
159
  ),
160
  PLOT_LAYOUT
161
  ))
162
  }
163
- plot_ly(data, x = ~Trait1, y = ~Trait2, size = ~Abs_Correlation, color = ~Correlation,
164
- type = 'scatter', mode = 'markers',
165
- sizes = c(5, 20), # Scale point sizes
166
- colors = c("#FFB6C1", "white", "#B5EAD7"), # Red to white to green
167
- text = ~paste("Trait1:", Trait1, "<br>Trait2:", Trait2, "<br>Correlation:", round(Correlation, 3)),
168
- hoverinfo = "text",
169
- marker = list(sizemode = 'diameter', opacity = 0.8)) %>%
170
  layout(
171
- title = list(text = "Trait Correlation Scatter Plot", font = list(size = 18, family = "Poppins", color = "#2D3748")),
172
- xaxis = list(title = "Trait 1", tickangle = 45, titlefont = PLOT_FONT, tickfont = PLOT_FONT),
173
- yaxis = list(title = "Trait 2", titlefont = PLOT_FONT, tickfont = PLOT_FONT),
 
174
  PLOT_LAYOUT,
175
  hoverlabel = list(bgcolor = "white", font = PLOT_FONT)
176
  )
177
  })
178
 
179
- # LME4: Correlation insights
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
180
  output$lme4_correlations_insights <- renderUI({
181
  req(rv_lme4$cor_table)
182
  strong_cor <- rv_lme4$cor_table %>%
183
  filter(abs(Correlation) > 0.7, Trait1 != Trait2) %>%
184
  slice_head(n = 1)
185
  if (nrow(strong_cor) > 0) {
186
- insight <- sprintf("Strong correlation (r = %.3f) between %s and %s suggests potential for indirect selection. Points with larger sizes indicate stronger correlations.",
187
  strong_cor$Correlation, strong_cor$Trait1, strong_cor$Trait2)
188
  } else {
189
- insight <- "No strong correlations (|r| > 0.7) detected. Direct selection for each trait is recommended. Point sizes reflect correlation strength."
190
  }
191
  HTML(sprintf("<strong>Insight:</strong> %s", insight))
192
- })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ library(shiny)
2
+ library(shinyjs)
3
+ library(tidyverse)
4
+ library(DT)
5
+ library(readxl)
6
+ library(lme4)
7
+ library(emmeans)
8
+ library(plotly)
9
+ library(shinyWidgets)
10
+ library(ggplot2)
11
+ library(pbkrtest)
12
+ library(lmerTest)
13
+
14
+ # UI with updated styling, including Stability and PCA tabs
15
+ ui <- fluidPage(
16
+ useShinyjs(),
17
+ tags$head(
18
+ tags$meta(charset = "UTF-8"),
19
+ tags$title("Phenotypic Analysis Dashboard"),
20
+ tags$link(rel = "stylesheet", href = "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"),
21
+ tags$style(HTML("
22
+ :root {
23
+ --primary: #1E3A8A; /* Dark blue for tabs */
24
+ --secondary: #6B8E23; /* Olive green */
25
+ --success: #32CD32; /* Lime Green */
26
+ --info: #4169E1; /* Royal Blue */
27
+ --warning: #FF8C00; /* Dark Orange */
28
+ --danger: #DC143C; /* Crimson */
29
+ --light: #D1D5DB; /* Grey for tab text */
30
+ --dark: #2F4F4F; /* Dark Slate Gray */
31
+ --background: #FFFFFF; /* White background */
32
+ --card-bg: #FFFFFF; /* White for cards */
33
+ }
34
+ body {
35
+ font-family: 'Poppins', sans-serif;
36
+ background: var(--background);
37
+ color: var(--dark);
38
+ overflow-x: hidden;
39
+ }
40
+ .container-fluid {
41
+ max-width: 1600px;
42
+ padding: 2.5rem;
43
+ margin: 0 auto;
44
+ }
45
+ .section {
46
+ margin-bottom: 30px;
47
+ background: var(--card-bg);
48
+ padding: 2.5rem;
49
+ border-radius: 15px;
50
+ box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
51
+ border: 1px solid rgba(30, 58, 138, 0.2);
52
+ }
53
+ h1, h2, h3 {
54
+ color: var(--primary);
55
+ border-bottom: 2px solid var(--secondary);
56
+ padding-bottom: 10px;
57
+ margin-bottom: 20px;
58
+ font-weight: 700;
59
+ }
60
+ .chart-container {
61
+ position: relative;
62
+ margin-bottom: 20px;
63
+ border-radius: 12px;
64
+ box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
65
+ background: var(--card-bg);
66
+ padding: 1.5rem;
67
+ border: 1px solid rgba(30, 58, 138, 0.2);
68
+ min-height: 400px;
69
+ }
70
+ .insights {
71
+ margin-top: 20px;
72
+ padding: 20px;
73
+ background: #F5F5F5;
74
+ border-radius: 8px;
75
+ border-left: 4px solid var(--secondary);
76
+ font-size: 14px;
77
+ }
78
+ .upload-container {
79
+ padding: 20px;
80
+ text-align: center;
81
+ border: 2px dashed var(--primary);
82
+ border-radius: 8px;
83
+ margin-bottom: 25px;
84
+ background: #F9F9F9;
85
+ }
86
+ .upload-icon {
87
+ font-size: 48px;
88
+ color: var(--primary);
89
+ margin-bottom: 15px;
90
+ }
91
+ .btn-primary {
92
+ background: linear-gradient(135deg, var(--primary), var(--info));
93
+ border: none;
94
+ padding: 1rem 2.5rem;
95
+ border-radius: 8px;
96
+ font-weight: 600;
97
+ color: white;
98
+ transition: all 0.3s;
99
+ box-shadow: 0 4px 8px rgba(0,0,0,0.1);
100
+ }
101
+ .btn-primary:hover {
102
+ background: linear-gradient(135deg, var(--info), var(--primary));
103
+ transform: translateY(-2px);
104
+ box-shadow: 0 6px 12px rgba(30, 58, 138, 0.3);
105
+ color: white;
106
+ }
107
+ .sidebar {
108
+ background: var(--card-bg);
109
+ color: var(--dark);
110
+ padding: 2rem;
111
+ height: 100vh;
112
+ position: fixed;
113
+ width: 280px;
114
+ box-shadow: 5px 0 15px rgba(0,0,0,0.1);
115
+ border-right: 1px solid var(--primary);
116
+ }
117
+ .sidebar-header {
118
+ padding: 20px;
119
+ background: linear-gradient(135deg, var(--primary), var(--info));
120
+ text-align: center;
121
+ border-bottom: 1px solid rgba(0,0,0,0.1);
122
+ border-radius: 10px;
123
+ margin-bottom: 20px;
124
+ color: white;
125
+ }
126
+ .sidebar-content {
127
+ padding: 15px;
128
+ }
129
+ .nav-link {
130
+ color: var(--dark);
131
+ padding: 12px 15px;
132
+ border-radius: 8px;
133
+ margin-bottom: 8px;
134
+ display: flex;
135
+ align-items: center;
136
+ transition: all 0.3s;
137
+ background: #F5F5F5;
138
+ }
139
+ .nav-link:hover, .nav-link.active {
140
+ color: white;
141
+ background: linear-gradient(90deg, var(--primary), var(--info));
142
+ transform: translateX(5px);
143
+ box-shadow: 0 4px 8px rgba(30, 58, 138, 0.3);
144
+ }
145
+ .nav-link i {
146
+ margin-right: 10px;
147
+ width: 20px;
148
+ text-align: center;
149
+ }
150
+ .main-content {
151
+ margin-left: 280px;
152
+ padding: 20px;
153
+ width: calc(100% - 280px);
154
+ min-height: 100vh;
155
+ background: var(--background);
156
+ }
157
+ .loader {
158
+ border: 5px solid #F5F5F5;
159
+ border-top: 5px solid var(--primary);
160
+ border-radius: 50%;
161
+ width: 50px;
162
+ height: 50px;
163
+ animation: spin 1s linear infinite;
164
+ margin: 20px auto;
165
+ }
166
+ @keyframes spin {
167
+ 0% { transform: rotate(0deg); }
168
+ 100% { transform: rotate(360deg); }
169
+ }
170
+ .hidden {
171
+ display: none;
172
+ }
173
+ table.dataTable {
174
+ border-collapse: collapse;
175
+ width: 100%;
176
+ font-size: 16px;
177
+ background: var(--card-bg);
178
+ border-radius: 8px;
179
+ overflow: hidden;
180
+ }
181
+ th {
182
+ background: linear-gradient(45deg, var(--primary), var(--info));
183
+ color: white;
184
+ padding: 1.2rem;
185
+ font-weight: 700;
186
+ text-transform: uppercase;
187
+ }
188
+ td {
189
+ padding: 1.2rem;
190
+ border-bottom: 1px solid #F0F0F0;
191
+ transition: background 0.3s;
192
+ color: var(--dark);
193
+ }
194
+ tr:hover {
195
+ background: #F5F5F5;
196
+ }
197
+ .dataTables_wrapper {
198
+ color: var(--dark);
199
+ }
200
+ .status-card {
201
+ background: var(--card-bg);
202
+ padding: 20px;
203
+ border-radius: 10px;
204
+ text-align: center;
205
+ box-shadow: 0 4px 8px rgba(0,0,0,0.1);
206
+ border: 1px solid rgba(30, 58, 138, 0.2);
207
+ margin-bottom: 15px;
208
+ }
209
+ .status-card i {
210
+ font-size: 2rem;
211
+ color: var(--primary);
212
+ margin-bottom: 10px;
213
+ }
214
+ .status-card h4 {
215
+ color: var(--primary);
216
+ font-size: 1.5rem;
217
+ margin: 5px 0;
218
+ }
219
+ .status-card p {
220
+ color: var(--dark);
221
+ margin: 0;
222
+ }
223
+ .plotly-title {
224
+ font-size: 18px;
225
+ font-weight: bold;
226
+ color: var(--primary);
227
+ }
228
+ .plotly-annotation {
229
+ font-size: 14px;
230
+ color: var(--dark);
231
+ }
232
+ "))
233
+ ),
234
+ div(
235
+ class = "app-wrapper",
236
+ div(
237
+ class = "sidebar",
238
+ div(
239
+ class = "sidebar-header",
240
+ h3("📊 Phenotypic Data Analysis", style = "margin: 0; font-weight: 600; color: white;")
241
+ ),
242
+ selectInput("lme4_selected_trait", "Select Trait for Detailed Analysis", choices = c()),
243
+ checkboxInput("lme4_include_interaction", "Include Environment:Genotype Interaction", value = FALSE),
244
+ div(
245
+ class = "sidebar-content",
246
+ div(
247
+ class = "nav flex-column", id = "lme4-v-pills-tab", role = "tablist",
248
+ tags$a(class = "nav-link active", `data-toggle` = "pill", href = "#lme4-upload", role = "tab",
249
+ icon("file-upload", class = "fas"), "📤 Upload Data"),
250
+ tags$a(class = "nav-link", `data-toggle` = "pill", href = "#lme4-descriptives", role = "tab",
251
+ icon("chart-line", class = "fas"), "📊 Descriptive Statistics"),
252
+ tags$a(class = "nav-link", `data-toggle` = "pill", href = "#lme4-blues", role = "tab",
253
+ icon("chart-bar", class = "fas"), "📈 Predicted Means"),
254
+ tags$a(class = "nav-link", `data-toggle` = "pill", href = "#lme4-correlations", role = "tab",
255
+ icon("link", class = "fas"), "🔗 Trait Correlations"),
256
+ tags$a(class = "nav-link", `data-toggle` = "pill", href = "#lme4-heritability", role = "tab",
257
+ icon("calculator", class = "fas"), "🧬 Heritability"),
258
+ tags$a(class = "nav-link", `data-toggle` = "pill", href = "#lme4-rankings", role = "tab",
259
+ icon("trophy", class = "fas"), "🏆 Genotype Rankings"),
260
+ tags$a(class = "nav-link", `data-toggle` = "pill", href = "#lme4-stability", role = "tab",
261
+ icon("balance-scale", class = "fas"), "⚖️ Stability Analysis"),
262
+ tags$a(class = "nav-link", `data-toggle` = "pill", href = "#lme4-pca", role = "tab",
263
+ icon("chart-scatter", class = "fas"), "🔍 PCA Analysis")
264
+ ),
265
+ hr(style = "border-color: rgba(255,255,255,0.1);"),
266
+ div(
267
+ style = "padding: 15px; color: var(--light); font-size: 12px; text-align: center;",
268
+ p("LME4 Analysis Dashboard v1.3"),
269
+ p("© 2023 Statistical Genetics Lab")
270
+ )
271
+ )
272
+ ),
273
+ div(
274
+ class = "main-content",
275
+ div(
276
+ class = "tab-content",
277
+ div(
278
+ class = "tab-pane fade show active", id = "lme4-upload", role = "tabpanel",
279
+ div(
280
+ class = "section",
281
+ h2("📤 Upload Your Data"),
282
+ div(
283
+ class = "upload-container",
284
+ div(class = "upload-icon", icon("cloud-upload-alt", class = "fas")),
285
+ h3("📁 Drag and drop your Excel file here", style = "color: var(--primary);"),
286
+ p("or", style = "margin: 10px 0;"),
287
+ fileInput("lme4_file", NULL, accept = c(".xlsx", ".xls"),
288
+ buttonLabel = "Browse Files", placeholder = "No file selected"),
289
+ p("📝 Supported formats: .xlsx, .xls", style = "color: var(--light); font-size: 14px;"),
290
+ div(id = "lme4_loader", class = "loader hidden")
291
+ ),
292
+ verbatimTextOutput("lme4_data_preview"),
293
+ verbatimTextOutput("lme4_debug_log"),
294
+ div(
295
+ id = "lme4_data_stats", class = "hidden",
296
+ h3("📊 Data Overview"),
297
+ fluidRow(
298
+ column(3, div(class = "status-card card-1",
299
+ icon("columns", class = "fas"),
300
+ h4(textOutput("lme4_n_vars"), style = "font-weight: 600;"),
301
+ p("Variables")
302
+ )),
303
+ column(3, div(class = "status-card card-2",
304
+ icon("list", class = "fas"),
305
+ h4(textOutput("lme4_n_obs"), style = "font-weight: 600;"),
306
+ p("Observations")
307
+ )),
308
+ column(3, div(class = "status-card card-3",
309
+ icon("dna", class = "fas"),
310
+ h4(textOutput("lme4_n_geno"), style = "font-weight: 600;"),
311
+ p("Genotypes")
312
+ )),
313
+ column(3, div(class = "status-card card-4",
314
+ icon("globe", class = "fas"),
315
+ h4(textOutput("lme4_n_env"), style = "font-weight: 600;"),
316
+ p("Environments")
317
+ ))
318
+ )
319
+ )
320
+ )
321
+ ),
322
+ div(
323
+ class = "tab-pane fade", id = "lme4-descriptives", role = "tabpanel",
324
+ div(
325
+ class = "section",
326
+ h2("📊 Descriptive Statistics"),
327
+ div(
328
+ id = "lme4_descriptives_content",
329
+ div(class = "table-container", DTOutput("lme4_descriptives_table")),
330
+ div(class = "chart-container", plotlyOutput("lme4_descriptives_plot", height = "500px")),
331
+ div(
332
+ class = "insights",
333
+ h4("💡 Interpretation & Insights"),
334
+ p("Descriptive statistics summarize central tendency, variability, and range for each trait. Coefficient of Variation (CV) indicates relative variability; CV < 10% suggests low variability (high precision), 10-20% moderate, >20% high (potential environmental influence or measurement error)."),
335
+ uiOutput("lme4_descriptives_insights")
336
+ )
337
+ ),
338
+ div(
339
+ id = "lme4_descriptives_placeholder", class = "text-center",
340
+ icon("chart-line", class = "fas", style = "font-size: 72px; color: var(--light); margin: 30px 0;"),
341
+ h4("📤 Upload data to see descriptive statistics", style = "color: var(--light);")
342
+ )
343
+ )
344
+ ),
345
+ div(
346
+ class = "tab-pane fade", id = "lme4-blues", role = "tabpanel",
347
+ div(
348
+ class = "section",
349
+ h2("📈 Predicted Means (BLUEs)"),
350
+ div(
351
+ id = "lme4_blues_content",
352
+ div(class = "chart-container", plotlyOutput("lme4_blues_plot", height = "500px")),
353
+ div(class = "table-container", DTOutput("lme4_blues_table")),
354
+ div(
355
+ class = "insights",
356
+ h4("💡 Interpretation & Insights"),
357
+ p("The G×E interaction plot shows genotype performance across environments. Stable genotypes have consistent values (parallel lines), while environment-specific genotypes vary (crossing lines)."),
358
+ uiOutput("lme4_blues_insights")
359
+ )
360
+ ),
361
+ div(
362
+ id = "lme4_blues_placeholder", class = "text-center",
363
+ icon("chart-bar", class = "fas", style = "font-size: 72px; color: var(--light); margin: 30px 0;"),
364
+ h4("📤 Upload data to see predicted means", style = "color: var(--light);")
365
+ )
366
+ )
367
+ ),
368
+ div(
369
+ class = "tab-pane fade", id = "lme4-correlations", role = "tabpanel",
370
+ div(
371
+ class = "section",
372
+ h2("🔗 Trait Correlations"),
373
+ div(
374
+ id = "lme4_correlations_content",
375
+ div(class = "chart-container", plotlyOutput("lme4_correlation_plot", height = "500px")),
376
+ div(class = "table-container", DTOutput("lme4_cor_table")),
377
+ div(
378
+ class = "insights",
379
+ h4("💡 Interpretation & Insights"),
380
+ p("Correlations reveal trait synergies or trade-offs. Positive correlations (r > 0.5) suggest traits improve together; negative (r < -0.5) indicate trade-offs."),
381
+ uiOutput("lme4_correlations_insights")
382
+ )
383
+ ),
384
+ div(
385
+ id = "lme4_correlations_placeholder", class = "text-center",
386
+ icon("link", class = "fas", style = "font-size: 72px; color: var(--light); margin: 30px 0;"),
387
+ h4("📤 Upload data to see trait correlations", style = "color: var(--light);")
388
+ )
389
+ )
390
+ ),
391
+ div(
392
+ class = "tab-pane fade", id = "lme4-heritability", role = "tabpanel",
393
+ div(
394
+ class = "section",
395
+ h2("🧬 Heritability Estimates"),
396
+ div(
397
+ id = "lme4_heritability_content",
398
+ div(class = "table-container", DTOutput("lme4_heritability_table")),
399
+ div(
400
+ class = "insights",
401
+ h4("💡 Interpretation & Insights"),
402
+ p("Broad-sense heritability (H²) indicates the proportion of phenotypic variance attributable to genotypic variance. H² > 0.6 suggests high heritability (effective for selection), 0.3-0.6 moderate, <0.3 low (environment dominates)."),
403
+ uiOutput("lme4_heritability_insights")
404
+ )
405
+ ),
406
+ div(
407
+ id = "lme4_heritability_placeholder", class = "text-center",
408
+ icon("calculator", class = "fas", style = "font-size: 72px; color: var(--light); margin: 30px 0;"),
409
+ h4("📤 Upload data to see heritability estimates", style = "color: var(--light);")
410
+ )
411
+ )
412
+ ),
413
+ div(
414
+ class = "tab-pane fade", id = "lme4-rankings", role = "tabpanel",
415
+ div(
416
+ class = "section",
417
+ h2("🏆 Genotype Rankings"),
418
+ div(
419
+ id = "lme4_rankings_content",
420
+ div(class = "table-container", DTOutput("lme4_rankings_table")),
421
+ div(class = "chart-container", plotlyOutput("lme4_rankings_plot", height = "500px")),
422
+ div(
423
+ class = "insights",
424
+ h4("💡 Interpretation & Insights"),
425
+ p("Rankings are based on average predicted performance across environments. Top-ranked genotypes are overall best performers."),
426
+ uiOutput("lme4_rankings_insights")
427
+ )
428
+ ),
429
+ div(
430
+ id = "lme4_rankings_placeholder", class = "text-center",
431
+ icon("trophy", class = "fas", style = "font-size: 72px; color: var(--light); margin: 30px 0;"),
432
+ h4("📤 Upload data to see genotype rankings", style = "color: var(--light);")
433
+ )
434
+ )
435
+ ),
436
+ div(
437
+ class = "tab-pane fade", id = "lme4-stability", role = "tabpanel",
438
+ div(
439
+ class = "section",
440
+ h2("⚖️ Stability Analysis"),
441
+ div(
442
+ id = "lme4_stability_content",
443
+ div(class = "chart-container", plotlyOutput("lme4_stability_plot", height = "500px")),
444
+ div(class = "table-container", DTOutput("lme4_stability_table")),
445
+ div(
446
+ class = "insights",
447
+ h4("💡 Interpretation & Insights"),
448
+ p("Finlay-Wilkinson regression slopes measure genotype stability. Slopes ~1 indicate average stability, <1 high stability (less responsive to environment), >1 low stability (highly responsive)."),
449
+ uiOutput("lme4_stability_insights")
450
+ )
451
+ ),
452
+ div(
453
+ id = "lme4_stability_placeholder", class = "text-center",
454
+ icon("balance-scale", class = "fas", style = "font-size: 72px; color: var(--light); margin: 30px 0;"),
455
+ h4("📤 Upload data to see stability analysis", style = "color: var(--light);")
456
+ )
457
+ )
458
+ ),
459
+ div(
460
+ class = "tab-pane fade", id = "lme4-pca", role = "tabpanel",
461
+ div(
462
+ class = "section",
463
+ h2("🔍 PCA Analysis"),
464
+ div(
465
+ id = "lme4_pca_content",
466
+ div(class = "chart-container", plotlyOutput("lme4_pca_plot", height = "500px")),
467
+ div(class = "table-container", DTOutput("lme4_pca_table")),
468
+ div(
469
+ class = "insights",
470
+ h4("💡 Interpretation & Insights"),
471
+ p("PCA reduces multi-trait data to principal components. Genotypes close together are phenotypically similar. PC1 and PC2 explain the majority of variance; check loadings for trait contributions."),
472
+ uiOutput("lme4_pca_insights")
473
+ )
474
+ ),
475
+ div(
476
+ id = "lme4_pca_placeholder", class = "text-center",
477
+ icon("chart-scatter", class = "fas", style = "font-size: 72px; color: var(--light); margin: 30px 0;"),
478
+ h4("📤 Upload data to see PCA analysis", style = "color: var(--light);")
479
+ )
480
+ )
481
+ )
482
+ )
483
+ )
484
+ )
485
+ )
486
+
487
+ # Server function
488
+ server <- function(input, output, session) {
489
+ # LME4 Analysis Reactive Values
490
+ rv_lme4 <- reactiveValues(
491
+ data = NULL,
492
+ traits = NULL,
493
+ trait = NULL,
494
+ fixed_models = NULL,
495
+ random_models = NULL,
496
+ blues_all = NULL,
497
+ cor_matrix = NULL,
498
+ cor_table = NULL,
499
+ descriptives = NULL,
500
+ heritability = NULL,
501
+ rankings = NULL,
502
+ stability = NULL,
503
+ pca = NULL,
504
+ debug_log = NULL
505
+ )
506
 
507
+ # Plot formatting constants
508
+ PLOT_FONT <- list(family = "Poppins", size = 14, color = "#2D3748")
509
+ PLOT_COLORS <- c("#FFB6C1", "#FFDAB9", "#B5EAD7", "#E6E6FA", "#FFFACD", "#FF9999")
510
+ PLOT_LAYOUT <- list(
511
+ plot_bgcolor = "transparent",
512
+ paper_bgcolor = "transparent",
513
+ margin = list(l = 80, r = 80, t = 100, b = 100),
514
+ font = PLOT_FONT,
515
+ showlegend = TRUE,
516
+ legend = list(orientation = "h", y = -0.2, x = 0.5, xanchor = "center")
517
+ )
518
+
519
+ # LME4: Process data
520
+ lme4_process_data <- function(path) {
521
+ message("LME4: Reading Excel file: ", path)
522
+ tryCatch({
523
+ data <- read_excel(path)
524
+ colnames(data) <- make.names(colnames(data), unique = TRUE)
525
+
526
+ required_cols <- c("Genotype", "Block", "Row", "Column", "Rep", "Environment")
527
+ missing_cols <- setdiff(required_cols, names(data))
528
+ if (length(missing_cols) > 0) {
529
+ stop("Missing required columns: ", paste(missing_cols, collapse = ", "))
530
+ }
531
+
532
+ data$Genotype <- as.factor(data$Genotype)
533
+ data$Block <- as.factor(data$Block)
534
+ data$Row <- as.factor(data$Row)
535
+ data$Rep <- as.factor(data$Rep)
536
+ data$Column <- as.factor(data$Column)
537
+ data$Environment <- as.factor(data$Environment)
538
+ data$Environment <- factor(data$Environment, levels = unique(data$Environment))
539
+
540
+ all_cols <- names(data)
541
+ trait_cols <- all_cols[9:length(all_cols)]
542
+ numeric_cols <- trait_cols[sapply(data[trait_cols], is.numeric)]
543
+
544
+ if (length(numeric_cols) == 0) {
545
+ stop("No numeric columns found for traits starting from column 9")
546
+ }
547
+
548
+ n_genotypes <- length(unique(data$Genotype))
549
+ n_environments <- length(unique(data$Environment))
550
+ if (n_genotypes < 3) {
551
+ stop("Insufficient genotypes (", n_genotypes, ") for analysis; need at least 3")
552
+ }
553
+ if (n_environments < 2) {
554
+ stop("Insufficient environments (", n_environments, ") for analysis; need at least 2")
555
+ }
556
+
557
+ combo_counts <- table(data$Environment, data$Genotype)
558
+ zero_combinations <- sum(combo_counts == 0)
559
+ if (zero_combinations > 0) {
560
+ message("LME4: Warning: ", zero_combinations, " Environment:Genotype combinations have no data")
561
+ showNotification(
562
+ paste(zero_combinations, "Environment:Genotype combinations are missing. Consider checking data completeness or imputing missing values."),
563
+ type = "warning", duration = 10
564
+ )
565
+ }
566
+ if (zero_combinations > (nrow(combo_counts) * ncol(combo_counts) * 0.5)) {
567
+ showNotification("Warning: Over 50% of Environment:Genotype combinations are missing", type = "warning", duration = 10)
568
+ }
569
+
570
+ missing_data <- data %>%
571
+ group_by(Environment) %>%
572
+ summarise(across(all_of(numeric_cols), ~ sum(is.na(.)) / length(.)))
573
+ bad_envs <- missing_data %>%
574
+ pivot_longer(cols = all_of(numeric_cols), names_to = "Trait", values_to = "Missing") %>%
575
+ filter(Missing > 0.2) %>%
576
+ pull(Environment) %>%
577
+ unique()
578
+ if (length(bad_envs) > 0) {
579
+ message("LME4: Filtering out environments with >20% missing data: ", paste(bad_envs, collapse = ", "))
580
+ data <- data %>% filter(!Environment %in% bad_envs) %>% droplevels()
581
+ }
582
+
583
+ message("LME4: Data summary: Rows=", nrow(data), ", Genotypes=", n_genotypes, ", Environments=", n_environments, ", Traits=", paste(numeric_cols, collapse = ", "))
584
+ return(list(data = data, traits = numeric_cols))
585
+ }, error = function(e) {
586
+ message("LME4: Error in data processing: ", e$message)
587
+ showNotification(paste("Error processing file:", e$message), type = "error", duration = 10)
588
+ return(NULL)
589
+ })
590
+ }
591
 
592
+ # LME4: Fit fixed model for BLUEs
593
+ lme4_fit_fixed_model <- function(data, trait) {
594
+ message("LME4: Fitting fixed model for ", trait)
595
+ formula_str <- if (input$lme4_include_interaction) {
596
+ paste(trait, "~ Environment + Genotype + Environment:Genotype + (1|Block) + (1|Rep)")
597
+ } else {
598
+ paste(trait, "~ Environment + Genotype + (1|Block) + (1|Rep)")
599
+ }
600
+ formula <- as.formula(formula_str)
601
+ tryCatch({
602
+ model <- lmer(formula, data = data, na.action = na.omit,
603
+ control = lmerControl(check.rankX = "warn+drop.cols", optimizer = "bobyqa", checkSingularity = TRUE))
604
+ if (isSingular(model)) {
605
+ message("LME4: Singular fit detected for ", trait, ". Simplifying model.")
606
+ showNotification(paste("Singular fit for", trait, ". Model simplified."), type = "warning", duration = 10)
607
+ formula_str <- paste(trait, "~ Environment + Genotype + (1|Rep)")
608
+ formula <- as.formula(formula_str)
609
+ model <- lmer(formula, data = data, na.action = na.omit,
610
+ control = lmerControl(check.rankX = "warn+drop.cols", optimizer = "bobyqa"))
611
+ }
612
+ message("LME4: Successfully fitted fixed model for ", trait)
613
+ return(model)
614
+ }, error = function(e) {
615
+ message("LME4: Error fitting fixed model for ", trait, ": ", e$message)
616
+ showNotification(paste("Fixed model fitting failed for", trait, ": ", e$message), type = "error", duration = 10)
617
+ return(NULL)
618
+ })
619
+ }
620
 
621
+ # LME4: Fit random model for heritability
622
+ lme4_fit_random_model <- function(data, trait) {
623
+ message("LME4: Fitting random model for ", trait)
624
+ formula_str <- if (input$lme4_include_interaction) {
625
+ paste(trait, "~ Environment + (1|Genotype) + (1|Environment:Genotype) + (1|Block) + (1|Rep)")
626
+ } else {
627
+ paste(trait, "~ Environment + (1|Genotype) + (1|Block) + (1|Rep)")
628
+ }
629
+ formula <- as.formula(formula_str)
630
+ tryCatch({
631
+ model <- lmer(formula, data = data, na.action = na.omit,
632
+ control = lmerControl(check.rankX = "warn+drop.cols", optimizer = "bobyqa", checkSingularity = TRUE))
633
+ if (isSingular(model)) {
634
+ message("LME4: Singular fit detected for ", trait, ". Simplifying model.")
635
+ showNotification(paste("Singular fit for", trait, ". Model simplified."), type = "warning", duration = 10)
636
+ formula_str <- paste(trait, "~ Environment + (1|Genotype) + (1|Rep)")
637
+ formula <- as.formula(formula_str)
638
+ model <- lmer(formula, data = data, na.action = na.omit,
639
+ control = lmerControl(check.rankX = "warn+drop.cols", optimizer = "bobyqa"))
640
+ }
641
+ message("LME4: Successfully fitted random model for ", trait)
642
+ return(model)
643
+ }, error = function(e) {
644
+ message("LME4: Error fitting random model for ", trait, ": ", e$message)
645
+ showNotification(paste("Random model fitting failed for", trait, ": ", e$message), type = "error", duration = 10)
646
+ return(NULL)
647
+ })
648
+ }
649
 
650
+ # LME4: Get BLUEs from fixed model
651
+ lme4_get_blue <- function(model, trait) {
652
+ if (is.null(model)) {
653
+ message("LME4: No fixed model for ", trait)
654
+ return(data.frame(Trait = trait, Genotype = NA, Environment = NA, predicted.value = NA, SE = NA))
655
+ }
656
+ tryCatch({
657
+ emm_options(pbkrtest.limit = 10000, lmerTest.limit = 10000)
658
+ blues <- emmeans(model, ~ Genotype:Environment)
659
+ blues_df <- as.data.frame(blues) %>%
660
+ rename(predicted.value = emmean) %>%
661
+ mutate(Trait = trait) %>%
662
+ select(Trait, Genotype, Environment, predicted.value, SE) %>%
663
+ filter(!is.na(predicted.value))
664
+ if (nrow(blues_df) == 0) {
665
+ return(data.frame(Trait = trait, Genotype = NA, Environment = NA, predicted.value = NA, SE = NA))
666
+ }
667
+ return(blues_df)
668
+ }, error = function(e) {
669
+ message("LME4: Error in BLUEs for ", trait, ": ", e$message)
670
+ return(data.frame(Trait = trait, Genotype = NA, Environment = NA, predicted.value = NA, SE = NA))
671
+ })
672
+ }
673
 
674
+ # LME4: Get heritability from random model
675
+ lme4_get_heritability <- function(model, trait) {
676
+ if (is.null(model)) {
677
+ message("LME4: No random model for ", trait)
678
+ return(data.frame(Trait = trait, Heritability = NA, VarG = NA, VarGE = NA, VarRes = NA))
679
+ }
680
+ tryCatch({
681
+ vc <- VarCorr(model)
682
+ sigma_g <- as.numeric(vc$Genotype[1])
683
+ sigma_ge <- if (input$lme4_include_interaction && "Environment:Genotype" %in% names(vc)) as.numeric(vc$`Environment:Genotype`[1]) else 0
684
+ sigma_res <- sigma(model)^2
685
+ var_g_total <- sigma_g + sigma_ge
686
+ total_var <- var_g_total + sigma_res
687
+ h2 <- if (total_var > 0) var_g_total / total_var else NA
688
+ data.frame(Trait = trait, Heritability = round(h2, 3), VarG = round(sigma_g, 3),
689
+ VarGE = round(sigma_ge, 3), VarRes = round(sigma_res, 3))
690
+ }, error = function(e) {
691
+ message("LME4: Error in heritability for ", trait, ": ", e$message)
692
+ return(data.frame(Trait = trait, Heritability = NA, VarG = NA, VarGE = NA, VarRes = NA))
693
+ })
694
+ }
695
 
696
+ # LME4: Finlay-Wilkinson stability analysis
697
+ lme4_get_stability <- function(blues, trait) {
698
+ tryCatch({
699
+ env_means <- blues %>%
700
+ group_by(Environment) %>%
701
+ summarise(Env_Mean = mean(predicted.value, na.rm = TRUE), .groups = "drop")
 
 
 
 
 
 
 
 
 
 
702
 
703
+ stability_data <- blues %>%
704
+ left_join(env_means, by = "Environment") %>%
705
+ group_by(Genotype) %>%
706
+ do({
707
+ model <- lm(predicted.value ~ Env_Mean, data = .)
708
+ slope <- coef(model)[2]
709
+ r_squared <- summary(model)$r.squared
710
+ data.frame(Slope = round(slope, 3), R_Squared = round(r_squared, 3))
711
+ }) %>%
712
+ mutate(Trait = trait) %>%
713
+ select(Trait, Genotype, Slope, R_Squared)
714
 
715
+ if (nrow(stability_data) == 0) {
716
+ return(data.frame(Trait = trait, Genotype = NA, Slope = NA, R_Squared = NA))
717
+ }
718
+ return(stability_data)
719
+ }, error = function(e) {
720
+ message("LME4: Error in stability analysis for ", trait, ": ", e$message)
721
+ return(data.frame(Trait = trait, Genotype = NA, Slope = NA, R_Squared = NA))
722
+ })
723
+ }
724
+
725
+ # LME4: PCA analysis
726
+ lme4_get_pca <- function(blues, traits) {
727
+ tryCatch({
728
+ wide_data <- blues %>%
729
+ select(Trait, Genotype, Environment, predicted.value) %>%
730
+ pivot_wider(names_from = Trait, values_from = predicted.value, values_fill = NA) %>%
731
+ na.omit()
732
 
733
+ if (nrow(wide_data) < 2 || ncol(wide_data) < length(traits) + 2) {
734
+ return(list(scores = data.frame(Genotype = NA, Environment = NA, PC1 = NA, PC2 = NA),
735
+ loadings = data.frame(Trait = NA, PC1 = NA, PC2 = NA)))
736
+ }
737
 
738
+ pca_data <- wide_data %>% select(all_of(traits))
739
+ pca_result <- prcomp(pca_data, scale. = TRUE)
740
+ scores <- as.data.frame(pca_result$x) %>%
741
+ mutate(Genotype = wide_data$Genotype, Environment = wide_data$Environment) %>%
742
+ select(Genotype, Environment, PC1, PC2)
743
+ loadings <- as.data.frame(pca_result$rotation) %>%
744
+ mutate(Trait = rownames(.)) %>%
745
+ select(Trait, PC1, PC2)
746
+ var_explained <- summary(pca_result)$importance[2, c("PC1", "PC2")] * 100
747
+ return(list(scores = scores, loadings = loadings, var_explained = var_explained))
748
+ }, error = function(e) {
749
+ message("LME4: Error in PCA analysis: ", e$message)
750
+ return(list(scores = data.frame(Genotype = NA, Environment = NA, PC1 = NA, PC2 = NA),
751
+ loadings = data.frame(Trait = NA, PC1 = NA, PC2 = NA)))
752
+ })
753
+ }
754
+
755
+ # LME4: File upload observer
756
+ observeEvent(input$lme4_file, {
757
+ req(input$lme4_file)
758
+ message("LME4: File upload triggered: ", input$lme4_file$name)
759
+ shinyjs::show("lme4_loader")
760
+ on.exit(shinyjs::hide("lme4_loader"))
761
 
762
+ result <- lme4_process_data(input$lme4_file$datapath)
763
+ if (is.null(result)) {
764
+ return()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
765
  }
766
 
767
+ rv_lme4$data <- result$data
768
+ rv_lme4$traits <- result$traits
769
+ rv_lme4$trait <- result$traits[1]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
770
 
771
+ updateSelectInput(session, "lme4_selected_trait", choices = rv_lme4$traits, selected = rv_lme4$traits[1])
 
 
 
 
 
 
 
 
 
772
 
773
+ shinyjs::show("lme4_data_stats")
774
+ output$lme4_n_vars <- renderText({ ncol(rv_lme4$data) })
775
+ output$lme4_n_obs <- renderText({ nrow(rv_lme4$data) })
776
+ output$lme4_n_geno <- renderText({ length(unique(rv_lme4$data$Genotype)) })
777
+ output$lme4_n_env <- renderText({ length(unique(rv_lme4$data$Environment)) })
778
 
779
+ output$lme4_data_preview <- renderPrint({
780
+ str(rv_lme4$data)
781
+ })
 
 
 
 
782
 
783
+ debug_log <- c()
 
 
 
 
 
 
 
784
 
785
+ withProgress(message = 'LME4: Analyzing data', value = 0, {
786
+ fixed_models <- list()
787
+ random_models <- list()
788
+ blues_list <- list()
789
+ herit_list <- list()
790
+ stability_list <- list()
791
+
792
+ n_traits <- length(rv_lme4$traits)
793
+ total_steps <- n_traits * 3 + 3 # fixed model, random model, stability, correlations, descriptives, pca
794
+ step_increment <- 1 / total_steps
795
+
796
+ for (trait in rv_lme4$traits) {
797
+ incProgress(step_increment, detail = paste("Fitting fixed model for", trait))
798
+ fixed_model <- lme4_fit_fixed_model(rv_lme4$data, trait)
799
+ fixed_models[[trait]] <- fixed_model
800
+ debug_log <- c(debug_log, paste("Trait:", trait, "- Fixed model:", ifelse(is.null(fixed_model), "Failed", "Success")))
801
+
802
+ incProgress(step_increment, detail = paste("Calculating predicted means for", trait))
803
+ blues_list[[trait]] <- lme4_get_blue(fixed_model, trait)
804
+
805
+ incProgress(step_increment, detail = paste("Fitting random model for", trait))
806
+ random_model <- lme4_fit_random_model(rv_lme4$data, trait)
807
+ random_models[[trait]] <- random_model
808
+ debug_log <- c(debug_log, paste("Trait:", trait, "- Random model:", ifelse(is.null(random_model), "Failed", "Success")))
809
+
810
+ herit_list[[trait]] <- lme4_get_heritability(random_model, trait)
811
+
812
+ incProgress(step_increment, detail = paste("Calculating stability for", trait))
813
+ stability_list[[trait]] <- lme4_get_stability(blues_list[[trait]], trait)
814
+ }
815
+
816
+ incProgress(step_increment, detail = "Calculating correlations")
817
+ if (n_traits > 1) {
818
+ trait_data <- rv_lme4$data %>% select(all_of(rv_lme4$traits)) %>% na.omit()
819
+ if (nrow(trait_data) > 0) {
820
+ cor_matrix <- cor(trait_data, use = "pairwise.complete.obs")
821
+ cor_table <- as.data.frame(as.table(cor_matrix)) %>%
822
+ rename(Trait1 = Var1, Trait2 = Var2, Correlation = Freq) %>%
823
+ mutate(Correlation = round(Correlation, 3))
824
+ rv_lme4$cor_matrix <- cor_matrix
825
+ rv_lme4$cor_table <- cor_table
826
+ debug_log <- c(debug_log, "Correlations: Success")
827
+ } else {
828
+ rv_lme4$cor_matrix <- matrix(NA, nrow = 1, ncol = 1, dimnames = list("NoData", "NoData"))
829
+ rv_lme4$cor_table <- data.frame(Trait1 = "NoData", Trait2 = "NoData", Correlation = NA)
830
+ debug_log <- c(debug_log, "Correlations: No valid data")
831
+ }
832
+ } else {
833
+ rv_lme4$cor_matrix <- matrix(1, nrow = 1, ncol = 1, dimnames = list(rv_lme4$traits, rv_lme4$traits))
834
+ rv_lme4$cor_table <- data.frame(Trait1 = rv_lme4$traits, Trait2 = rv_lme4$traits, Correlation = 1)
835
+ debug_log <- c(debug_log, "Correlations: Single trait")
836
+ }
837
+
838
+ incProgress(step_increment, detail = "Calculating descriptive statistics")
839
+ descriptives <- rv_lme4$data %>%
840
+ select(all_of(rv_lme4$traits)) %>%
841
+ pivot_longer(cols = everything(), names_to = "Trait", values_to = "Value") %>%
842
+ group_by(Trait) %>%
843
+ summarise(
844
+ Mean = mean(Value, na.rm = TRUE),
845
+ SD = sd(Value, na.rm = TRUE),
846
+ Min = min(Value, na.rm = TRUE),
847
+ Max = max(Value, na.rm = TRUE),
848
+ N = sum(!is.na(Value)),
849
+ .groups = "drop"
850
+ ) %>%
851
+ mutate(CV = round((SD / Mean) * 100, 2))
852
+ rv_lme4$descriptives <- descriptives
853
+ debug_log <- c(debug_log, "Descriptives: Success")
854
+
855
+ incProgress(step_increment, detail = "Calculating heritability")
856
+ rv_lme4$heritability <- bind_rows(herit_list)
857
+ debug_log <- c(debug_log, "Heritability: Success")
858
+
859
+ incProgress(step_increment, detail = "Calculating rankings")
860
+ rv_lme4$blues_all <- bind_rows(blues_list) %>% filter(!is.na(predicted.value))
861
+ rankings <- rv_lme4$blues_all %>%
862
+ group_by(Trait, Genotype) %>%
863
+ summarise(Mean = mean(predicted.value, na.rm = TRUE), .groups = "drop") %>%
864
+ group_by(Trait) %>%
865
+ mutate(Rank = rank(-Mean, ties.method = "min")) %>%
866
+ arrange(Trait, Rank)
867
+ rv_lme4$rankings <- rankings
868
+ debug_log <- c(debug_log, "Rankings: Success")
869
+
870
+ incProgress(step_increment, detail = "Calculating stability")
871
+ rv_lme4$stability <- bind_rows(stability_list)
872
+ debug_log <- c(debug_log, "Stability: Success")
873
+
874
+ incProgress(step_increment, detail = "Calculating PCA")
875
+ rv_lme4$pca <- lme4_get_pca(rv_lme4$blues_all, rv_lme4$traits)
876
+ debug_log <- c(debug_log, "PCA: Success")
877
+
878
+ rv_lme4$fixed_models <- fixed_models
879
+ rv_lme4$random_models <- random_models
880
+ rv_lme4$debug_log <- debug_log
881
+
882
+ shinyjs::hide(c("lme4_blues_placeholder", "lme4_correlations_placeholder",
883
+ "lme4_descriptives_placeholder", "lme4_heritability_placeholder",
884
+ "lme4_rankings_placeholder", "lme4_stability_placeholder",
885
+ "lme4_pca_placeholder"))
886
+ shinyjs::show(c("lme4_blues_content", "lme4_correlations_content",
887
+ "lme4_descriptives_content", "lme4_heritability_content",
888
+ "lme4_rankings_content", "lme4_stability_content",
889
+ "lme4_pca_content"))
890
+
891
+ output$lme4_debug_log <- renderPrint({
892
+ cat(paste(rv_lme4$debug_log, collapse = "\n"))
893
+ })
894
+
895
+ showNotification("LME4: File uploaded and analyzed successfully", type = "message", duration = 5)
896
  })
 
 
897
  })
898
 
899
+ # Update selected trait
900
+ observe({
901
+ req(input$lme4_selected_trait)
902
+ rv_lme4$trait <- input$lme4_selected_trait
903
+ })
904
+
905
+ # LME4: Filtered reactives
906
+ lme4_filtered_blues <- reactive({
907
+ req(rv_lme4$blues_all, rv_lme4$trait)
908
+ rv_lme4$blues_all %>% filter(Trait == rv_lme4$trait, !is.na(predicted.value))
909
+ })
910
+
911
+ lme4_filtered_rankings <- reactive({
912
+ req(rv_lme4$rankings, rv_lme4$trait)
913
+ rv_lme4$rankings %>% filter(Trait == rv_lme4$trait)
914
+ })
915
+
916
+ lme4_filtered_stability <- reactive({
917
+ req(rv_lme4$stability, rv_lme4$trait)
918
+ rv_lme4$stability %>% filter(Trait == rv_lme4$trait)
919
+ })
920
+
921
+ # LME4: Plot outputs
922
+ output$lme4_blues_plot <- renderPlotly({
923
+ req(lme4_filtered_blues())
924
+ data <- lme4_filtered_blues()
925
+ if (nrow(data) == 0 || all(is.na(data$predicted.value))) {
926
+ return(plot_ly() %>%
927
+ layout(
928
+ title = list(text = paste("No Valid Predicted Means for", rv_lme4$trait), font = PLOT_FONT),
929
+ annotations = list(
930
+ text = "No valid data for plotting predicted means.",
931
+ x = 0.5, y = 0.5, xref = "paper", yref = "paper",
932
+ showarrow = FALSE, font = list(size = 12, color = "#2D3748")
933
+ ),
934
+ PLOT_LAYOUT
935
+ ))
936
+ }
937
+ plot_ly(data, x = ~Environment, y = ~predicted.value, color = ~Genotype,
938
+ type = 'scatter', mode = 'lines+markers',
939
+ marker = list(size = 8),
940
+ line = list(width = 2),
941
+ colors = PLOT_COLORS,
942
+ text = ~paste("Genotype:", Genotype, "<br>Value:", round(predicted.value, 2)),
943
+ hoverinfo = "text") %>%
944
+ layout(
945
+ title = list(text = paste("Predicted Means (BLUEs) for", rv_lme4$trait), font = list(size = 18, family = "Poppins", color = "#2D3748")),
946
+ xaxis = list(title = "Environment", tickangle = 45, titlefont = PLOT_FONT, tickfont = PLOT_FONT),
947
+ yaxis = list(title = "Predicted Value", titlefont = PLOT_FONT, tickfont = PLOT_FONT),
948
+ PLOT_LAYOUT,
949
+ hoverlabel = list(bgcolor = "white", font = PLOT_FONT)
950
+ )
951
+ })
952
+
953
  output$lme4_correlation_plot <- renderPlotly({
954
+ req(rv_lme4$cor_matrix)
955
+ if (ncol(rv_lme4$cor_matrix) < 2 || all(is.na(rv_lme4$cor_matrix))) {
 
956
  return(plot_ly() %>%
957
  layout(
958
  title = list(text = "No Valid Correlation Data", font = PLOT_FONT),
959
  annotations = list(
960
+ text = "Correlation plot requires at least two valid traits.",
961
+ x = 0.5, y = 0.5, xref = "paper", yref = "paper",
962
+ showarrow = FALSE, font = list(size = 12, color = "#2D3748")
963
+ ),
964
+ PLOT_LAYOUT
965
+ ))
966
+ }
967
+ plot_ly(
968
+ x = colnames(rv_lme4$cor_matrix),
969
+ y = rownames(rv_lme4$cor_matrix),
970
+ z = rv_lme4$cor_matrix,
971
+ type = "heatmap",
972
+ colorscale = list(c(-1, 0, 1), c("#FFB6C1", "white", "#B5EAD7")),
973
+ showscale = TRUE,
974
+ colorbar = list(title = "Correlation", titlefont = PLOT_FONT, tickfont = PLOT_FONT),
975
+ text = round(rv_lme4$cor_matrix, 2),
976
+ hoverinfo = "x+y+z"
977
+ ) %>%
978
+ layout(
979
+ title = list(text = "Trait Correlation Matrix", font = list(size = 18, family = "Poppins", color = "#2D3748")),
980
+ xaxis = list(title = "", tickangle = 45, titlefont = PLOT_FONT, tickfont = PLOT_FONT),
981
+ yaxis = list(title = "", titlefont = PLOT_FONT, tickfont = PLOT_FONT),
982
+ PLOT_LAYOUT,
983
+ hoverlabel = list(bgcolor = "white", font = PLOT_FONT)
984
+ )
985
+ })
986
+
987
+ output$lme4_descriptives_plot <- renderPlotly({
988
+ req(rv_lme4$data, rv_lme4$trait)
989
+ trait_data <- rv_lme4$data[[rv_lme4$trait]]
990
+ if (all(is.na(trait_data)) || length(unique(rv_lme4$data$Environment)) < 2) {
991
+ return(plot_ly() %>%
992
+ layout(
993
+ title = list(text = paste("No Valid Data for", rv_lme4$trait), font = PLOT_FONT),
994
+ annotations = list(
995
+ text = "No valid data for boxplot.",
996
+ x = 0.5, y = 0.5, xref = "paper", yref = "paper",
997
+ showarrow = FALSE, font = list(size = 12, color = "#2D3748")
998
+ ),
999
+ PLOT_LAYOUT
1000
+ ))
1001
+ }
1002
+ plot_ly(rv_lme4$data, x = ~Environment, y = rv_lme4$data[[rv_lme4$trait]], type = 'box',
1003
+ color = ~Environment, colors = PLOT_COLORS,
1004
+ hoverinfo = "y+name") %>%
1005
+ layout(
1006
+ title = list(text = paste("Distribution of", rv_lme4$trait, "by Environment"), font = list(size = 18, family = "Poppins", color = "#2D3748")),
1007
+ xaxis = list(title = "Environment", titlefont = PLOT_FONT, tickfont = PLOT_FONT),
1008
+ yaxis = list(title = paste(rv_lme4$trait, "Value"), titlefont = PLOT_FONT, tickfont = PLOT_FONT),
1009
+ PLOT_LAYOUT,
1010
+ hoverlabel = list(bgcolor = "white", font = PLOT_FONT)
1011
+ )
1012
+ })
1013
+
1014
+ output$lme4_rankings_plot <- renderPlotly({
1015
+ req(lme4_filtered_rankings())
1016
+ data <- lme4_filtered_rankings() %>% head(10)
1017
+ if (nrow(data) == 0) {
1018
+ return(plot_ly() %>%
1019
+ layout(
1020
+ title = list(text = paste("No Rankings for", rv_lme4$trait), font = PLOT_FONT),
1021
+ annotations = list(
1022
+ text = "No valid data for plotting rankings.",
1023
+ x = 0.5, y = 0.5, xref = "paper", yref = "paper",
1024
+ showarrow = FALSE, font = list(size = 12, color = "#2D3748")
1025
+ ),
1026
+ PLOT_LAYOUT
1027
+ ))
1028
+ }
1029
+ plot_ly(data, x = ~reorder(Genotype, -Mean), y = ~Mean, type = 'bar',
1030
+ marker = list(color = PLOT_COLORS[1:length(unique(data$Genotype))]),
1031
+ text = ~paste("Genotype:", Genotype, "<br>Mean:", round(Mean, 2), "<br>Rank:", Rank),
1032
+ hoverinfo = "text") %>%
1033
+ layout(
1034
+ title = list(text = paste("Top Genotypes for", rv_lme4$trait), font = list(size = 18, family = "Poppins", color = "#2D3748")),
1035
+ xaxis = list(title = "Genotype", tickangle = 45, titlefont = PLOT_FONT, tickfont = PLOT_FONT),
1036
+ yaxis = list(title = "Mean Predicted Value", titlefont = PLOT_FONT, tickfont = PLOT_FONT),
1037
+ PLOT_LAYOUT,
1038
+ hoverlabel = list(bgcolor = "white", font = PLOT_FONT)
1039
+ )
1040
+ })
1041
+
1042
+ output$lme4_stability_plot <- renderPlotly({
1043
+ req(lme4_filtered_stability())
1044
+ data <- lme4_filtered_stability()
1045
+ if (nrow(data) == 0 || all(is.na(data$Slope))) {
1046
+ return(plot_ly() %>%
1047
+ layout(
1048
+ title = list(text = paste("No Stability Data for", rv_lme4$trait), font = PLOT_FONT),
1049
+ annotations = list(
1050
+ text = "No valid data for plotting stability.",
1051
+ x = 0.5, y = 0.5, xref = "paper", yref = "paper",
1052
+ showarrow = FALSE, font = list(size = 12, color = "#2D3748")
1053
+ ),
1054
+ PLOT_LAYOUT
1055
+ ))
1056
+ }
1057
+ plot_ly(data, x = ~Slope, y = ~R_Squared, type = 'scatter', mode = 'markers',
1058
+ text = ~paste("Genotype:", Genotype, "<br>Slope:", round(Slope, 2), "<br>R²:", round(R_Squared, 2)),
1059
+ hoverinfo = "text", marker = list(size = 10, color = PLOT_COLORS[1])) %>%
1060
+ layout(
1061
+ title = list(text = paste("Stability Analysis for", rv_lme4$trait), font = list(size = 18, family = "Poppins", color = "#2D3748")),
1062
+ xaxis = list(title = "Stability Slope", titlefont = PLOT_FONT, tickfont = PLOT_FONT),
1063
+ yaxis = list(title = "R²", titlefont = PLOT_FONT, tickfont = PLOT_FONT),
1064
+ PLOT_LAYOUT,
1065
+ hoverlabel = list(bgcolor = "white", font = PLOT_FONT)
1066
+ )
1067
+ })
1068
+
1069
+ output$lme4_pca_plot <- renderPlotly({
1070
+ req(rv_lme4$pca)
1071
+ scores <- rv_lme4$pca$scores
1072
+ var_explained <- rv_lme4$pca$var_explained
1073
+ if (nrow(scores) == 0 || all(is.na(scores$PC1))) {
1074
+ return(plot_ly() %>%
1075
+ layout(
1076
+ title = list(text = "No PCA Data", font = PLOT_FONT),
1077
+ annotations = list(
1078
+ text = "No valid data for PCA plot.",
1079
  x = 0.5, y = 0.5, xref = "paper", yref = "paper",
1080
  showarrow = FALSE, font = list(size = 12, color = "#2D3748")
1081
  ),
1082
  PLOT_LAYOUT
1083
  ))
1084
  }
1085
+ plot_ly(scores, x = ~PC1, y = ~PC2, type = 'scatter', mode = 'markers',
1086
+ text = ~paste("Genotype:", Genotype, "<br>Environment:", Environment),
1087
+ hoverinfo = "text", marker = list(size = 10, color = PLOT_COLORS[1])) %>%
 
 
 
 
1088
  layout(
1089
+ title = list(text = sprintf("PCA Biplot (PC1: %.1f%%, PC2: %.1f%%)", var_explained[1], var_explained[2]),
1090
+ font = list(size = 18, family = "Poppins", color = "#2D3748")),
1091
+ xaxis = list(title = "PC1", titlefont = PLOT_FONT, tickfont = PLOT_FONT),
1092
+ yaxis = list(title = "PC2", titlefont = PLOT_FONT, tickfont = PLOT_FONT),
1093
  PLOT_LAYOUT,
1094
  hoverlabel = list(bgcolor = "white", font = PLOT_FONT)
1095
  )
1096
  })
1097
 
1098
+ # LME4: Table outputs
1099
+ output$lme4_blues_table <- renderDT({
1100
+ req(lme4_filtered_blues())
1101
+ data <- lme4_filtered_blues()
1102
+ if ("Error" %in% colnames(data)) {
1103
+ data <- data %>% select(-Error)
1104
+ }
1105
+ datatable(
1106
+ data,
1107
+ extensions = 'Buttons',
1108
+ options = list(
1109
+ scrollX = TRUE,
1110
+ dom = 'Bfrtip',
1111
+ buttons = c('copy', 'excel', 'pdf', 'print'),
1112
+ pageLength = 10,
1113
+ columnDefs = list(list(className = 'dt-center', targets = '_all'))
1114
+ ),
1115
+ caption = paste("Predicted Means (BLUEs) for", rv_lme4$trait)
1116
+ ) %>% formatRound(columns = c("predicted.value", "SE"), digits = 3)
1117
+ })
1118
+
1119
+ output$lme4_cor_table <- renderDT({
1120
+ req(rv_lme4$cor_table)
1121
+ datatable(
1122
+ rv_lme4$cor_table,
1123
+ extensions = 'Buttons',
1124
+ options = list(
1125
+ scrollX = TRUE,
1126
+ dom = 'Bfrtip',
1127
+ buttons = c('copy', 'excel', 'pdf', 'print'),
1128
+ pageLength = 10,
1129
+ columnDefs = list(list(className = 'dt-center', targets = '_all'))
1130
+ ),
1131
+ caption = "Correlation Between Traits"
1132
+ ) %>% formatRound(columns = "Correlation", digits = 3)
1133
+ })
1134
+
1135
+ output$lme4_descriptives_table <- renderDT({
1136
+ req(rv_lme4$descriptives)
1137
+ datatable(
1138
+ rv_lme4$descriptives,
1139
+ extensions = 'Buttons',
1140
+ options = list(
1141
+ scrollX = TRUE,
1142
+ dom = 'Bfrtip',
1143
+ buttons = c('copy', 'excel', 'pdf', 'print'),
1144
+ pageLength = 10,
1145
+ columnDefs = list(list(className = 'dt-center', targets = c(2:6)))
1146
+ ),
1147
+ caption = "Descriptive Statistics for Traits"
1148
+ ) %>% formatRound(columns = c("Mean", "SD", "Min", "Max", "CV"), digits = 2)
1149
+ })
1150
+
1151
+ output$lme4_heritability_table <- renderDT({
1152
+ req(rv_lme4$heritability)
1153
+ datatable(
1154
+ rv_lme4$heritability,
1155
+ extensions = 'Buttons',
1156
+ options = list(
1157
+ scrollX = TRUE,
1158
+ dom = 'Bfrtip',
1159
+ buttons = c('copy', 'excel', 'pdf', 'print'),
1160
+ pageLength = 10,
1161
+ columnDefs = list(list(className = 'dt-center', targets = c(2:5)))
1162
+ ),
1163
+ caption = "Broad-Sense Heritability Estimates"
1164
+ ) %>% formatRound(columns = c("Heritability", "VarG", "VarGE", "VarRes"), digits = 3)
1165
+ })
1166
+
1167
+ output$lme4_rankings_table <- renderDT({
1168
+ req(lme4_filtered_rankings())
1169
+ datatable(
1170
+ lme4_filtered_rankings(),
1171
+ extensions = 'Buttons',
1172
+ options = list(
1173
+ scrollX = TRUE,
1174
+ dom = 'Bfrtip',
1175
+ buttons = c('copy', 'excel', 'pdf', 'print'),
1176
+ pageLength = 10,
1177
+ columnDefs = list(list(className = 'dt-center', targets = c(3,4)))
1178
+ ),
1179
+ caption = paste("Genotype Rankings for", rv_lme4$trait)
1180
+ ) %>% formatRound(columns = "Mean", digits = 3)
1181
+ })
1182
+
1183
+ output$lme4_stability_table <- renderDT({
1184
+ req(lme4_filtered_stability())
1185
+ datatable(
1186
+ lme4_filtered_stability(),
1187
+ extensions = 'Buttons',
1188
+ options = list(
1189
+ scrollX = TRUE,
1190
+ dom = 'Bfrtip',
1191
+ buttons = c('copy', 'excel', 'pdf', 'print'),
1192
+ pageLength = 10,
1193
+ columnDefs = list(list(className = 'dt-center', targets = c(3,4)))
1194
+ ),
1195
+ caption = paste("Stability Analysis for", rv_lme4$trait)
1196
+ ) %>% formatRound(columns = c("Slope", "R_Squared"), digits = 3)
1197
+ })
1198
+
1199
+ output$lme4_pca_table <- renderDT({
1200
+ req(rv_lme4$pca)
1201
+ datatable(
1202
+ rv_lme4$pca$loadings,
1203
+ extensions = 'Buttons',
1204
+ options = list(
1205
+ scrollX = TRUE,
1206
+ dom = 'Bfrtip',
1207
+ buttons = c('copy', 'excel', 'pdf', 'print'),
1208
+ pageLength = 10,
1209
+ columnDefs = list(list(className = 'dt-center', targets = c(2,3)))
1210
+ ),
1211
+ caption = "PCA Loadings"
1212
+ ) %>% formatRound(columns = c("PC1", "PC2"), digits = 3)
1213
+ })
1214
+
1215
+ # LME4: Insights outputs
1216
+ output$lme4_descriptives_insights <- renderUI({
1217
+ req(rv_lme4$descriptives)
1218
+ desc <- rv_lme4$descriptives %>% filter(Trait == rv_lme4$trait)
1219
+ if (nrow(desc) == 0) return(NULL)
1220
+ cv <- desc$CV[1]
1221
+ insight <- if (cv > 20) {
1222
+ "High variability (CV > 20%) suggests environmental influence or measurement error. Consider increasing replicates or refining phenotyping."
1223
+ } else if (cv > 10) {
1224
+ "Moderate variability (CV 10-20%) indicates some environmental influence. Genotype selection for stability may be effective."
1225
+ } else {
1226
+ "Low variability (CV < 10%) indicates high precision. Suitable for reliable genetic selection."
1227
+ }
1228
+ HTML(sprintf("<strong>Insight for %s:</strong> %s", rv_lme4$trait, insight))
1229
+ })
1230
+
1231
+ output$lme4_blues_insights <- renderUI({
1232
+ req(lme4_filtered_blues())
1233
+ data <- lme4_filtered_blues()
1234
+ if (nrow(data) == 0) return(NULL)
1235
+ var_by_geno <- data %>%
1236
+ group_by(Genotype) %>%
1237
+ summarise(Var = var(predicted.value, na.rm = TRUE), .groups = "drop") %>%
1238
+ arrange(Var)
1239
+ stable_geno <- var_by_geno$Genotype[1]
1240
+ insight <- sprintf("Genotype %s shows the lowest variance across environments, indicating high stability.", stable_geno)
1241
+ HTML(sprintf("<strong>Insight for %s:</strong> %s", rv_lme4$trait, insight))
1242
+ })
1243
+
1244
  output$lme4_correlations_insights <- renderUI({
1245
  req(rv_lme4$cor_table)
1246
  strong_cor <- rv_lme4$cor_table %>%
1247
  filter(abs(Correlation) > 0.7, Trait1 != Trait2) %>%
1248
  slice_head(n = 1)
1249
  if (nrow(strong_cor) > 0) {
1250
+ insight <- sprintf("Strong correlation (r = %.3f) between %s and %s suggests potential for indirect selection.",
1251
  strong_cor$Correlation, strong_cor$Trait1, strong_cor$Trait2)
1252
  } else {
1253
+ insight <- "No strong correlations (|r| > 0.7) detected. Direct selection for each trait is recommended."
1254
  }
1255
  HTML(sprintf("<strong>Insight:</strong> %s", insight))
1256
+ })
1257
+
1258
+ output$lme4_heritability_insights <- renderUI({
1259
+ req(rv_lme4$heritability)
1260
+ h2 <- rv_lme4$heritability %>% filter(Trait == rv_lme4$trait)
1261
+ if (nrow(h2) == 0 || is.na(h2$Heritability)) return(NULL)
1262
+ insight <- if (h2$Heritability > 0.6) {
1263
+ sprintf("High heritability (H² = %.3f) for %s; effective for genetic selection.", h2$Heritability, rv_lme4$trait)
1264
+ } else if (h2$Heritability > 0.3) {
1265
+ sprintf("Moderate heritability (H² = %.3f) for %s; selection may be effective but consider environmental factors.", h2$Heritability, rv_lme4$trait)
1266
+ } else {
1267
+ sprintf("Low heritability (H² = %.3f) for %s; environmental optimization or more precise phenotyping needed.", h2$Heritability, rv_lme4$trait)
1268
+ }
1269
+ HTML(sprintf("<strong>Insight for %s:</strong> %s", rv_lme4$trait, insight))
1270
+ })
1271
+
1272
+ output$lme4_rankings_insights <- renderUI({
1273
+ req(lme4_filtered_rankings())
1274
+ top_geno <- lme4_filtered_rankings() %>% filter(Rank == 1) %>% slice_head(n = 1)
1275
+ if (nrow(top_geno) == 0) return(NULL)
1276
+ insight <- sprintf("Genotype %s ranks first for %s with mean value %.3f.",
1277
+ top_geno$Genotype, rv_lme4$trait, top_geno$Mean)
1278
+ HTML(sprintf("<strong>Insight for %s:</strong> %s", rv_lme4$trait, insight))
1279
+ })
1280
+
1281
+ output$lme4_stability_insights <- renderUI({
1282
+ req(lme4_filtered_stability())
1283
+ stab <- lme4_filtered_stability()
1284
+ stable_geno <- stab %>% filter(abs(Slope - 1) < 0.2, R_Squared > 0.8) %>% slice_head(n = 1)
1285
+ if (nrow(stable_geno) > 0) {
1286
+ insight <- sprintf("Genotype %s has high stability (slope = %.3f, R² = %.3f) for %s.",
1287
+ stable_geno$Genotype, stable_geno$Slope, stable_geno$R_Squared, rv_lme4$trait)
1288
+ } else {
1289
+ insight <- sprintf("No highly stable genotypes (slope ~ 1, R² > 0.8) for %s.", rv_lme4$trait)
1290
+ }
1291
+ HTML(sprintf("<strong>Insight for %s:</strong> %s", rv_lme4$trait, insight))
1292
+ })
1293
+
1294
+ output$lme4_pca_insights <- renderUI({
1295
+ req(rv_lme4$pca)
1296
+ loadings <- rv_lme4$pca$loadings
1297
+ var_explained <- rv_lme4$pca$var_explained
1298
+ if (nrow(loadings) == 0 || all(is.na(loadings$PC1))) return(NULL)
1299
+ top_trait_pc1 <- loadings %>% arrange(-abs(PC1)) %>% slice_head(n = 1)
1300
+ insight <- sprintf("PC1 (%.1f%% variance) is driven by %s (loading = %.3f).",
1301
+ var_explained[1], top_trait_pc1$Trait, top_trait_pc1$PC1)
1302
+ HTML(sprintf("<strong>Insight:</strong> %s", insight))
1303
+ })
1304
+ }
1305
+
1306
+ # Run the Shiny app
1307
+ shinyApp(ui, server)