International Rice Research Institute commited on
Commit
1d748d8
·
verified ·
1 Parent(s): 66842e9

Update app.R

Browse files
Files changed (1) hide show
  1. app.R +1237 -44
app.R CHANGED
@@ -1,58 +1,1251 @@
1
  library(shiny)
2
- library(bslib)
3
- library(dplyr)
 
 
 
 
 
 
4
  library(ggplot2)
5
 
6
- df <- readr::read_csv("penguins.csv")
7
- # Find subset of columns that are suitable for scatter plot
8
- df_num <- df |> select(where(is.numeric), -Year)
9
-
10
- ui <- page_sidebar(
11
- theme = bs_theme(bootswatch = "minty"),
12
- title = "Penguins explorer",
13
- sidebar = sidebar(
14
- varSelectInput("xvar", "X variable", df_num, selected = "Bill Length (mm)"),
15
- varSelectInput("yvar", "Y variable", df_num, selected = "Bill Depth (mm)"),
16
- checkboxGroupInput("species", "Filter by species",
17
- choices = unique(df$Species), selected = unique(df$Species)
18
- ),
19
- hr(), # Add a horizontal rule
20
- checkboxInput("by_species", "Show species", TRUE),
21
- checkboxInput("show_margins", "Show marginal plots", TRUE),
22
- checkboxInput("smooth", "Add smoother"),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  ),
24
- plotOutput("scatter")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  )
26
 
 
27
  server <- function(input, output, session) {
28
- subsetted <- reactive({
29
- req(input$species)
30
- df |> filter(Species %in% input$species)
31
- })
32
-
33
- output$scatter <- renderPlot(
34
- {
35
- p <- ggplot(subsetted(), aes(!!input$xvar, !!input$yvar)) +
36
- theme_light() +
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  list(
38
- theme(legend.position = "bottom"),
39
- if (input$by_species) aes(color = Species),
40
- geom_point(),
41
- if (input$smooth) geom_smooth()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  )
43
-
44
- if (input$show_margins) {
45
- margin_type <- if (input$by_species) "density" else "histogram"
46
- p <- p |> ggExtra::ggMarginal(
47
- type = margin_type, margins = "both",
48
- size = 8, groupColour = input$by_species, groupFill = input$by_species
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
  )
50
- }
51
-
52
- p
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
  },
54
- res = 100
 
 
55
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
  }
57
 
58
- shinyApp(ui, server)
 
 
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
 
12
+ # UI with updated styling
13
+ ui <- fluidPage(
14
+ useShinyjs(),
15
+ tags$head(
16
+ tags$meta(charset = "UTF-8"),
17
+ tags$title("Combined Analysis Dashboard"),
18
+ tags$link(rel = "stylesheet", href = "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"),
19
+ tags$style(HTML("
20
+ :root {
21
+ --primary: #1E3A8A; /* Dark blue for tabs */
22
+ --secondary: #6B8E23; /* Olive green */
23
+ --success: #32CD32; /* Lime Green */
24
+ --info: #4169E1; /* Royal Blue */
25
+ --warning: #FF8C00; /* Dark Orange */
26
+ --danger: #DC143C; /* Crimson */
27
+ --light: #D1D5DB; /* Grey for tab text */
28
+ --dark: #2F4F4F; /* Dark Slate Gray */
29
+ --background: #FFFFFF; /* White background */
30
+ --card-bg: #FFFFFF; /* White for cards */
31
+ }
32
+
33
+ body {
34
+ font-family: 'Poppins', sans-serif;
35
+ background: var(--background);
36
+ color: var(--dark);
37
+ overflow-x: hidden;
38
+ }
39
+
40
+ .container-fluid {
41
+ max-width: 1600px;
42
+ padding: 2.5rem;
43
+ margin: 0 auto;
44
+ }
45
+
46
+ .section {
47
+ margin-bottom: 30px;
48
+ background: var(--card-bg);
49
+ padding: 2.5rem;
50
+ border-radius: 15px;
51
+ box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
52
+ border: 1px solid rgba(30, 58, 138, 0.2);
53
+ }
54
+
55
+ h1, h2, h3 {
56
+ color: var(--primary);
57
+ border-bottom: 2px solid var(--secondary);
58
+ padding-bottom: 10px;
59
+ margin-bottom: 20px;
60
+ font-weight: 700;
61
+ }
62
+
63
+ .chart-container {
64
+ position: relative;
65
+ margin-bottom: 20px;
66
+ border-radius: 12px;
67
+ box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
68
+ background: var(--card-bg);
69
+ padding: 1.5rem;
70
+ border: 1px solid rgba(30, 58, 138, 0.2);
71
+ }
72
+
73
+ .insights {
74
+ margin-top: 20px;
75
+ padding: 20px;
76
+ background: #F5F5F5;
77
+ border-radius: 8px;
78
+ border-left: 4px solid var(--secondary);
79
+ }
80
+
81
+ .upload-container {
82
+ padding: 20px;
83
+ text-align: center;
84
+ border: 2px dashed var(--primary);
85
+ border-radius: 8px;
86
+ margin-bottom: 25px;
87
+ background: #F9F9F9;
88
+ }
89
+
90
+ .upload-icon {
91
+ font-size: 48px;
92
+ color: var(--primary);
93
+ margin-bottom: 15px;
94
+ }
95
+
96
+ .btn-primary {
97
+ background: linear-gradient(135deg, var(--primary), var(--info));
98
+ border: none;
99
+ padding: 1rem 2.5rem;
100
+ border-radius: 8px;
101
+ font-weight: 600;
102
+ color: white;
103
+ transition: all 0.3s;
104
+ box-shadow: 0 4px 8px rgba(0,0,0,0.1);
105
+ }
106
+
107
+ .btn-primary:hover {
108
+ background: linear-gradient(135deg, var(--info), var(--primary));
109
+ transform: translateY(-2px);
110
+ box-shadow: 0 6px 12px rgba(30, 58, 138, 0.3);
111
+ color: white;
112
+ }
113
+
114
+ .nav-tabs {
115
+ border-bottom: 2px solid var(--primary);
116
+ margin-bottom: 20px;
117
+ }
118
+
119
+ .nav-tabs .nav-item {
120
+ margin-bottom: -2px;
121
+ }
122
+
123
+ .nav-tabs .nav-link {
124
+ color: var(--light); /* Grey text for tabs */
125
+ background: #F5F5F5;
126
+ border: 1px solid transparent;
127
+ border-radius: 8px 8px 0 0;
128
+ margin-right: 5px;
129
+ padding: 12px 20px;
130
+ transition: all 0.3s;
131
+ }
132
+
133
+ .nav-tabs .nav-link:hover {
134
+ color: var(--light);
135
+ background: var(--primary); /* Dark blue on hover */
136
+ border: 1px solid var(--primary);
137
+ }
138
+
139
+ .nav-tabs .nav-link.active {
140
+ color: var(--light); /* Grey text for active tab */
141
+ background: var(--primary); /* Dark blue for active tab */
142
+ border: 1px solid var(--primary);
143
+ font-weight: bold;
144
+ }
145
+
146
+ .nav-tabs .nav-link i {
147
+ margin-right: 8px;
148
+ }
149
+
150
+ .sidebar {
151
+ background: var(--card-bg);
152
+ color: var(--dark);
153
+ padding: 2rem;
154
+ height: 100vh;
155
+ position: fixed;
156
+ width: 280px;
157
+ box-shadow: 5px 0 15px rgba(0,0,0,0.1);
158
+ border-right: 1px solid var(--primary);
159
+ }
160
+
161
+ .sidebar-header {
162
+ padding: 20px;
163
+ background: linear-gradient(135deg, var(--primary), var(--info));
164
+ text-align: center;
165
+ border-bottom: 1px solid rgba(0,0,0,0.1);
166
+ border-radius: 10px;
167
+ margin-bottom: 20px;
168
+ color: white;
169
+ }
170
+
171
+ .sidebar-content {
172
+ padding: 15px;
173
+ }
174
+
175
+ .nav-link {
176
+ color: var(--dark);
177
+ padding: 12px 15px;
178
+ border-radius: 8px;
179
+ margin-bottom: 8px;
180
+ display: flex;
181
+ align-items: center;
182
+ transition: all 0.3s;
183
+ background: #F5F5F5;
184
+ }
185
+
186
+ .nav-link:hover, .nav-link.active {
187
+ color: white;
188
+ background: linear-gradient(90deg, var(--primary), var(--info));
189
+ transform: translateX(5px);
190
+ box-shadow: 0 4px 8px rgba(30, 58, 138, 0.3);
191
+ }
192
+
193
+ .nav-link i {
194
+ margin-right: 10px;
195
+ width: 20px;
196
+ text-align: center;
197
+ }
198
+
199
+ .main-content {
200
+ margin-left: 280px;
201
+ padding: 20px;
202
+ width: calc(100% - 280px);
203
+ min-height: 100vh;
204
+ background: var(--background);
205
+ }
206
+
207
+ .loader {
208
+ border: 5px solid #F5F5F5;
209
+ border-top: 5px solid var(--primary);
210
+ border-radius: 50%;
211
+ width: 50px;
212
+ height: 50px;
213
+ animation: spin 1s linear infinite;
214
+ margin: 20px auto;
215
+ }
216
+
217
+ @keyframes spin {
218
+ 0% { transform: rotate(0deg); }
219
+ 100% { transform: rotate(360deg); }
220
+ }
221
+
222
+ .hidden {
223
+ display: none;
224
+ }
225
+
226
+ table.dataTable {
227
+ border-collapse: collapse;
228
+ width: 100%;
229
+ font-size: 16px;
230
+ background: var(--card-bg);
231
+ border-radius: 8px;
232
+ overflow: hidden;
233
+ }
234
+
235
+ th {
236
+ background: linear-gradient(45deg, var(--primary), var(--info));
237
+ color: white;
238
+ padding: 1.2rem;
239
+ font-weight: 700;
240
+ text-transform: uppercase;
241
+ }
242
+
243
+ td {
244
+ padding: 1.2rem;
245
+ border-bottom: 1px solid #F0F0F0;
246
+ transition: background 0.3s;
247
+ color: var(--dark);
248
+ }
249
+
250
+ tr:hover {
251
+ background: #F5F5F5;
252
+ }
253
+
254
+ .dataTables_wrapper {
255
+ color: var(--dark);
256
+ }
257
+
258
+ .status-card {
259
+ background: var(--card-bg);
260
+ padding: 20px;
261
+ border-radius: 10px;
262
+ text-align: center;
263
+ box-shadow: 0 4px 8px rgba(0,0,0,0.1);
264
+ border: 1px solid rgba(30, 58, 138, 0.2);
265
+ margin-bottom: 15px;
266
+ }
267
+
268
+ .status-card i {
269
+ font-size: 2rem;
270
+ color: var(--primary);
271
+ margin-bottom: 10px;
272
+ }
273
+
274
+ .status-card h4 {
275
+ color: var(--primary);
276
+ font-size: 1.5rem;
277
+ margin: 5px 0;
278
+ }
279
+
280
+ .status-card p {
281
+ color: var(--dark);
282
+ margin: 0;
283
+ }
284
+ "))
285
  ),
286
+ tabsetPanel(
287
+ id = "main_tabs",
288
+ type = "tabs",
289
+ tabPanel(
290
+ icon("seedling"), "Preprocessing data",
291
+ div(
292
+ class = "section",
293
+ h1("🌱 Preprocessing", class = "text-4xl font-extrabold tracking-tight"),
294
+ div(
295
+ class = "upload-container",
296
+ div(class = "upload-icon", icon("cloud-upload-alt", class = "fas")),
297
+ h3("📤 Upload Dataset (Excel)", style = "color: var(--primary);"),
298
+ p("or", style = "margin: 10px 0;"),
299
+ fileInput("pheno_file", NULL, accept = ".xlsx",
300
+ buttonLabel = "Browse Files", placeholder = "No file selected"),
301
+ p("📝 Supported format: .xlsx", style = "color: var(--light); font-size: 14px;"),
302
+ div(id = "pheno_loader", class = "loader hidden")
303
+ ),
304
+ radioButtons("pheno_plotType", "📊 Select Plot Type",
305
+ choices = c("2D Bar" = "2d", "3D Bar" = "3d"),
306
+ selected = "2d", width = "100%"),
307
+ actionButton("pheno_process", "🔍 Analyze Data", class = "btn-primary w-full"),
308
+ tabsetPanel(
309
+ tabPanel(
310
+ icon("search"), "Missing Data Analysis",
311
+ div(
312
+ class = "section",
313
+ h3("🔍 Missing Data Patterns by Environment & Trait", class = "text-2xl font-bold mb-6"),
314
+ div(class = "chart-container", plotlyOutput("pheno_missingPlot"))
315
+ )
316
+ ),
317
+ tabPanel(
318
+ icon("filter"), "Filtered Data Insights",
319
+ div(
320
+ class = "section",
321
+ h3("✅ Post-Filtering Missing Data Patterns", class = "text-2xl font-bold mb-6"),
322
+ div(class = "chart-container", plotlyOutput("pheno_filteredMissingPlot"))
323
+ )
324
+ ),
325
+ tabPanel(
326
+ icon("table"), "Statistical Summary",
327
+ div(
328
+ class = "section",
329
+ h3("📈 Environment-Wise Descriptive Statistics", class = "text-2xl font-bold mb-6"),
330
+ DTOutput("pheno_statsTable"),
331
+ downloadButton("pheno_downloadStats", "📥 Export Stats as CSV", class = "btn-primary mt-6")
332
+ )
333
+ )
334
+ )
335
+ )
336
+ ),
337
+ tabPanel(
338
+ icon("calculator"), "Phenotypic data analysis",
339
+ div(
340
+ class = "app-wrapper",
341
+ div(
342
+ class = "sidebar",
343
+ div(
344
+ class = "sidebar-header",
345
+ h3("📊 Phenotypic data analysis", style = "margin: 0; font-weight: 600; color: white;")
346
+ ),
347
+ selectInput("lme4_selected_trait", "Select Trait", choices = c()),
348
+ checkboxInput("lme4_include_interaction", "Include Environment:Genotype Interaction", value = FALSE),
349
+ div(
350
+ class = "sidebar-content",
351
+ div(
352
+ class = "nav flex-column", id = "lme4-v-pills-tab", role = "tablist",
353
+ tags$a(class = "nav-link active", `data-toggle` = "pill", href = "#lme4-upload", role = "tab",
354
+ icon("file-upload", class = "fas"), "📤 Upload Data"),
355
+ tags$a(class = "nav-link", `data-toggle` = "pill", href = "#lme4-blues", role = "tab",
356
+ icon("chart-bar", class = "fas"), "📈 Predicted Means"),
357
+ tags$a(class = "nav-link", `data-toggle` = "pill", href = "#lme4-heritability", role = "tab",
358
+ icon("dna", class = "fas"), "🧬 Heritability"),
359
+ tags$a(class = "nav-link", `data-toggle` = "pill", href = "#lme4-correlations", role = "tab",
360
+ icon("link", class = "fas"), "🔗 Trait Correlations"),
361
+ tags$a(class = "nav-link", `data-toggle` = "pill", href = "#lme4-stability", role = "tab",
362
+ icon("balance-scale", class = "fas"), "⚖️ Stability Analysis")
363
+ ),
364
+ hr(style = "border-color: rgba(255,255,255,0.1);"),
365
+ div(
366
+ style = "padding: 15px; color: var(--light); font-size: 12px; text-align: center;",
367
+ p("LME4 Analysis Dashboard v1.0"),
368
+ p("© 2023 Statistical Genetics Lab")
369
+ )
370
+ )
371
+ ),
372
+ div(
373
+ class = "main-content",
374
+ div(
375
+ class = "tab-content",
376
+ div(
377
+ class = "tab-pane fade show active", id = "lme4-upload", role = "tabpanel",
378
+ div(
379
+ class = "section",
380
+ h2("📤 Upload Your Data"),
381
+ div(
382
+ class = "upload-container",
383
+ div(class = "upload-icon", icon("cloud-upload-alt", class = "fas")),
384
+ h3("📁 Drag and drop your Excel file here", style = "color: var(--primary);"),
385
+ p("or", style = "margin: 10px 0;"),
386
+ fileInput("lme4_file", NULL, accept = c(".xlsx", ".xls"),
387
+ buttonLabel = "Browse Files", placeholder = "No file selected"),
388
+ p("📝 Supported formats: .xlsx, .xls", style = "color: var(--light); font-size: 14px;"),
389
+ div(id = "lme4_loader", class = "loader hidden")
390
+ ),
391
+ verbatimTextOutput("lme4_data_preview"),
392
+ verbatimTextOutput("lme4_debug_log"),
393
+ div(
394
+ id = "lme4_data_stats", class = "hidden",
395
+ h3("📊 Data Overview"),
396
+ fluidRow(
397
+ column(3, div(class = "status-card card-1",
398
+ icon("columns", class = "fas"),
399
+ h4(textOutput("lme4_n_vars"), style = "font-weight: 600;"),
400
+ p("Variables")
401
+ )),
402
+ column(3, div(class = "status-card card-2",
403
+ icon("list", class = "fas"),
404
+ h4(textOutput("lme4_n_obs"), style = "font-weight: 600;"),
405
+ p("Observations")
406
+ )),
407
+ column(3, div(class = "status-card card-3",
408
+ icon("dna", class = "fas"),
409
+ h4(textOutput("lme4_n_geno"), style = "font-weight: 600;"),
410
+ p("Genotypes")
411
+ )),
412
+ column(3, div(class = "status-card card-4",
413
+ icon("globe", class = "fas"),
414
+ h4(textOutput("lme4_n_env"), style = "font-weight: 600;"),
415
+ p("Environments")
416
+ ))
417
+ )
418
+ )
419
+ )
420
+ ),
421
+ div(
422
+ class = "tab-pane fade", id = "lme4-blues", role = "tabpanel",
423
+ div(
424
+ class = "section",
425
+ h2("📈 Predicted Means (BLUEs)"),
426
+ div(
427
+ id = "lme4_blues_content",
428
+ div(class = "chart-container", plotlyOutput("lme4_blues_plot")),
429
+ div(class = "table-container", DTOutput("lme4_blues_table")),
430
+ div(
431
+ class = "insights",
432
+ h4("💡 Interpretation"),
433
+ p("The G×E interaction heatmap shows genotype performance across environments. Stable genotypes have consistent values, while environment-specific genotypes vary. Use for selecting broadly adapted or specific genotypes.")
434
+ )
435
+ ),
436
+ div(
437
+ id = "lme4_blues_placeholder", class = "text-center",
438
+ icon("chart-bar", class = "fas", style = "font-size: 72px; color: var(--light); margin: 30px 0;"),
439
+ h4("📤 Upload data to see predicted means", style = "color: var(--light);")
440
+ )
441
+ )
442
+ ),
443
+ div(
444
+ class = "tab-pane fade", id = "lme4-heritability", role = "tabpanel",
445
+ div(
446
+ class = "section",
447
+ h2("🧬 Heritability"),
448
+ div(
449
+ id = "lme4_heritability_content",
450
+ div(class = "chart-container", plotlyOutput("lme4_heritability_plot")),
451
+ div(class = "table-container", DTOutput("lme4_heritability_table")),
452
+ div(
453
+ class = "insights",
454
+ h4("💡 Interpretation"),
455
+ p("Heritability (H²) measures genetic variance proportion. High H² (>0.7) traits are easier to improve via breeding, while low H² traits are environment-driven, requiring careful management.")
456
+ )
457
+ ),
458
+ div(
459
+ id = "lme4_heritability_placeholder", class = "text-center",
460
+ icon("dna", class = "fas", style = "font-size: 72px; color: var(--light); margin: 30px 0;"),
461
+ h4("📤 Upload data to see heritability analysis", style = "color: var(--light);")
462
+ )
463
+ )
464
+ ),
465
+ div(
466
+ class = "tab-pane fade", id = "lme4-correlations", role = "tabpanel",
467
+ div(
468
+ class = "section",
469
+ h2("🔗 Trait Correlations"),
470
+ div(
471
+ id = "lme4_correlations_content",
472
+ div(class = "chart-container", plotlyOutput("lme4_correlation_plot")),
473
+ div(class = "table-container", DTOutput("lme4_cor_table")),
474
+ div(
475
+ class = "insights",
476
+ h4("💡 Interpretation"),
477
+ p("Correlations reveal trait synergies or trade-offs. Positive correlations (near 1) suggest traits improve together; negative correlations (near -1) indicate trade-offs. Prioritize traits accordingly.")
478
+ )
479
+ ),
480
+ div(
481
+ id = "lme4_correlations_placeholder", class = "text-center",
482
+ icon("link", class = "fas", style = "font-size: 72px; color: var(--light); margin: 30px 0;"),
483
+ h4("📤 Upload data to see trait correlations", style = "color: var(--light);")
484
+ )
485
+ )
486
+ ),
487
+ div(
488
+ class = "tab-pane fade", id = "lme4-stability", role = "tabpanel",
489
+ div(
490
+ class = "section",
491
+ h2("⚖️ Stability Analysis"),
492
+ div(
493
+ id = "lme4_stability_content",
494
+ div(class = "chart-container", plotlyOutput("lme4_stability_plot")),
495
+ div(class = "table-container", DTOutput("lme4_stability_table")),
496
+ div(
497
+ class = "insights",
498
+ h4("💡 Interpretation"),
499
+ p("Finlay-Wilkinson stability identifies genotypes with slopes near 1 (stable) and high R² (consistent). Stable genotypes suit broad adaptation; extreme slopes suit specific environments.")
500
+ )
501
+ ),
502
+ div(
503
+ id = "lme4_stability_placeholder", class = "text-center",
504
+ icon("balance-scale", class = "fas", style = "font-size: 72px; color: var(--light); margin: 30px 0;"),
505
+ h4("📤 Upload data to see stability analysis", style = "color: var(--light);")
506
+ )
507
+ )
508
+ )
509
+ )
510
+ )
511
+ )
512
+ )
513
+ )
514
  )
515
 
516
+ # Server function (unchanged from previous)
517
  server <- function(input, output, session) {
518
+ # Phenotypic Analysis Reactive Values
519
+ rv_pheno <- reactiveValues(
520
+ data = NULL,
521
+ processed_data = NULL,
522
+ missing_data = NULL,
523
+ missing_20 = NULL,
524
+ filtered_missing_data = NULL,
525
+ summary_traits = NULL
526
+ )
527
+
528
+ # LME4 Analysis Reactive Values
529
+ rv_lme4 <- reactiveValues(
530
+ data = NULL,
531
+ traits = NULL,
532
+ trait = NULL,
533
+ lme4_models = NULL,
534
+ blues_all = NULL,
535
+ heritability_table = NULL,
536
+ cor_matrix = NULL,
537
+ cor_table = NULL,
538
+ stability_table = NULL,
539
+ debug_log = NULL
540
+ )
541
+
542
+ # Phenotypic: Process data
543
+ pheno_process_data <- function(path) {
544
+ message("Pheno: Reading Excel file: ", path)
545
+ input_data <- read_excel(path)
546
+ input_data$Genotype <- as.factor(input_data$Genotype)
547
+ input_data$Block <- as.factor(input_data$Block)
548
+ input_data$Row <- as.factor(input_data$Row)
549
+ input_data$Rep <- as.factor(input_data$Rep)
550
+ input_data$Column <- as.factor(input_data$Column)
551
+ input_data$Environment <- as.factor(input_data$Environment)
552
+ input_data$Environment <- factor(input_data$Environment, levels = unique(input_data$Environment))
553
+
554
+ trait_cols <- colnames(input_data)[10:ncol(input_data)]
555
+
556
+ data_missing <- input_data %>%
557
+ group_by(Environment) %>%
558
+ summarise(across(all_of(trait_cols), ~ sum(is.na(.)) / length(.)))
559
+
560
+ data_missing_long <- data_missing %>%
561
+ pivot_longer(cols = all_of(trait_cols), names_to = "Trait", values_to = "value")
562
+
563
+ missing_20_df <- data_missing_long %>% filter(value > 0.20)
564
+ bad_env <- unique(missing_20_df$Environment)
565
+
566
+ filtered_data <- input_data %>% filter(!(Environment %in% bad_env)) %>% droplevels()
567
+
568
+ filtered_missing <- filtered_data %>%
569
+ group_by(Environment) %>%
570
+ summarise(across(all_of(trait_cols), ~ sum(is.na(.)) / length(.)))
571
+
572
+ filtered_missing_long <- filtered_missing %>%
573
+ pivot_longer(cols = all_of(trait_cols), names_to = "Trait", values_to = "value")
574
+
575
+ summary_traits_df <- filtered_data %>%
576
+ group_by(Environment) %>%
577
+ summarise(across(
578
+ all_of(trait_cols),
579
  list(
580
+ mean = ~ mean(.x, na.rm = TRUE),
581
+ median = ~ median(.x, na.rm = TRUE),
582
+ sd = ~ sd(.x, na.rm = TRUE),
583
+ min = ~ min(.x, na.rm = TRUE),
584
+ max = ~ max(.x, na.rm = TRUE),
585
+ cv = ~ (sd(.x, na.rm = TRUE) / mean(.x, na.rm = TRUE)) * 100
586
+ ),
587
+ .names = "{.col}_{.fn}"
588
+ )) %>%
589
+ mutate(across(where(is.numeric), ~ round(.x, 2)))
590
+
591
+ summary_long <- summary_traits_df %>%
592
+ pivot_longer(cols = -Environment, names_to = c("Trait", "Stat"), names_sep = "_", values_to = "value") %>%
593
+ pivot_wider(names_from = "Stat", values_from = "value")
594
+
595
+ return(list(
596
+ data = input_data,
597
+ processed_data = filtered_data,
598
+ missing_data = data_missing_long,
599
+ missing_20 = missing_20_df,
600
+ filtered_missing_data = filtered_missing_long,
601
+ summary_traits = summary_long
602
+ ))
603
+ }
604
+
605
+ # Phenotypic: File upload and process observer
606
+ observeEvent(input$pheno_process, {
607
+ req(input$pheno_file)
608
+ message("Pheno: File upload triggered: ", input$pheno_file$name)
609
+ shinyjs::show("pheno_loader")
610
+ on.exit(shinyjs::hide("pheno_loader"))
611
+
612
+ tryCatch({
613
+ result <- pheno_process_data(input$pheno_file$datapath)
614
+ rv_pheno$data <- result$data
615
+ rv_pheno$processed_data <- result$processed_data
616
+ rv_pheno$missing_data <- result$missing_data
617
+ rv_pheno$missing_20 <- result$missing_20
618
+ rv_pheno$filtered_missing_data <- result$filtered_missing_data
619
+ rv_pheno$summary_traits <- result$summary_traits
620
+
621
+ showNotification("Pheno: File uploaded and analyzed successfully", type = "message", duration = 5)
622
+ }, error = function(e) {
623
+ message("Pheno: Error in file processing: ", e$message)
624
+ showNotification(paste("Pheno Error:", e$message), type = "error", duration = 10)
625
+ })
626
+ })
627
+
628
+ # Phenotypic: Plot outputs
629
+ output$pheno_missingPlot <- renderPlotly({
630
+ req(rv_pheno$missing_data)
631
+ if (input$pheno_plotType == "2d") {
632
+ p <- ggplot(rv_pheno$missing_data, aes(x = Environment, y = value, fill = Trait)) +
633
+ geom_bar(stat = "identity", position = "dodge", alpha = 0.85) +
634
+ labs(y = "Proportion of Missing Data", x = "Environment") +
635
+ theme_minimal() +
636
+ scale_fill_manual(values = c("#FFB6C1", "#FFDAB9", "#B5EAD7", "#E6E6FA", "#FFFACD", "#FF9999")) +
637
+ theme(
638
+ axis.text.x = element_text(angle = 30, hjust = 1, size = 12, color = "#2D3748"),
639
+ axis.text.y = element_text(size = 12, color = "#2D3748"),
640
+ axis.title.x = element_text(size = 14, color = "#2D3748", face = "bold", margin = margin(t = 12)),
641
+ axis.title.y = element_text(size = 14, color = "#2D3748", face = "bold", margin = margin(r = 12)),
642
+ legend.position = "top",
643
+ legend.title = element_text(size = 12, face = "bold", color = "#2D3748"),
644
+ legend.text = element_text(size = 10, color = "#2D3748"),
645
+ panel.grid.major = element_line(color = "#e5e7eb", size = 0.4),
646
+ panel.grid.minor = element_blank(),
647
+ panel.background = element_rect(fill = "#F9FAFB"),
648
+ plot.background = element_rect(fill = "transparent")
649
+ ) +
650
+ facet_wrap(~Trait, ncol = 2, scales = "free_y")
651
+
652
+ ggplotly(p) %>%
653
+ layout(
654
+ plot_bgcolor = "transparent",
655
+ paper_bgcolor = "transparent",
656
+ margin = list(l = 70, r = 70, t = 70, b = 140),
657
+ font = list(family = "Poppins", size = 12, color = "#2D3748"),
658
+ showlegend = TRUE
659
  )
660
+ } else {
661
+ plot_ly(
662
+ data = rv_pheno$missing_data,
663
+ x = ~Environment,
664
+ y = ~Trait,
665
+ z = ~value,
666
+ type = "histogram2dcontour",
667
+ histfunc = "sum",
668
+ colorscale = list(
669
+ c(0, 0.5, 1),
670
+ c("#FFB6C1", "#FFDAB9", "#B5EAD7")
671
+ ),
672
+ showscale = TRUE,
673
+ colorbar = list(title = "Missing Proportion")
674
+ ) %>%
675
+ layout(
676
+ scene = list(
677
+ xaxis = list(title = "Environment", tickangle = 45),
678
+ yaxis = list(title = "Trait"),
679
+ zaxis = list(title = "Proportion"),
680
+ camera = list(
681
+ eye = list(x = 2, y = 2, z = 0.5),
682
+ up = list(x = 0, y = 0, z = 1)
683
+ )
684
+ ),
685
+ plot_bgcolor = "transparent",
686
+ paper_bgcolor = "transparent",
687
+ margin = list(l = 70, r = 70, t = 70, b = 140),
688
+ font = list(family = "Poppins", size = 12, color = "#2D3748"),
689
+ showlegend = FALSE
690
  )
691
+ }
692
+ })
693
+
694
+ output$pheno_filteredMissingPlot <- renderPlotly({
695
+ req(rv_pheno$filtered_missing_data)
696
+ if (input$pheno_plotType == "2d") {
697
+ p <- ggplot(rv_pheno$filtered_missing_data, aes(x = Environment, y = value, fill = Trait)) +
698
+ geom_bar(stat = "identity", position = "dodge", alpha = 0.85) +
699
+ labs(y = "Proportion of Missing Data (Filtered)", x = "Environment") +
700
+ theme_minimal() +
701
+ scale_fill_manual(values = c("#FFB6C1", "#FFDAB9", "#B5EAD7", "#E6E6FA", "#FFFACD", "#FF9999")) +
702
+ theme(
703
+ axis.text.x = element_text(angle = 30, hjust = 1, size = 12, color = "#2D3748"),
704
+ axis.text.y = element_text(size = 12, color = "#2D3748"),
705
+ axis.title.x = element_text(size = 14, color = "#2D3748", face = "bold", margin = margin(t = 12)),
706
+ axis.title.y = element_text(size = 14, color = "#2D3748", face = "bold", margin = margin(r = 12)),
707
+ legend.position = "top",
708
+ legend.title = element_text(size = 12, face = "bold", color = "#2D3748"),
709
+ legend.text = element_text(size = 10, color = "#2D3748"),
710
+ panel.grid.major = element_line(color = "#e5e7eb", size = 0.4),
711
+ panel.grid.minor = element_blank(),
712
+ panel.background = element_rect(fill = "#F9FAFB"),
713
+ plot.background = element_rect(fill = "transparent")
714
+ ) +
715
+ facet_wrap(~Trait, ncol = 2, scales = "free_y")
716
+
717
+ ggplotly(p) %>%
718
+ layout(
719
+ plot_bgcolor = "transparent",
720
+ paper_bgcolor = "transparent",
721
+ margin = list(l = 70, r = 70, t = 70, b = 140),
722
+ font = list(family = "Poppins", size = 12, color = "#2D3748"),
723
+ showlegend = TRUE
724
+ )
725
+ } else {
726
+ plot_ly(
727
+ data = rv_pheno$filtered_missing_data,
728
+ x = ~Environment,
729
+ y = ~Trait,
730
+ z = ~value,
731
+ type = "histogram2dcontour",
732
+ histfunc = "sum",
733
+ colorscale = list(
734
+ c(0, 0.5, 1),
735
+ c("#FFB6C1", "#FFDAB9", "#B5EAD7")
736
+ ),
737
+ showscale = TRUE,
738
+ colorbar = list(title = "Missing Proportion")
739
+ ) %>%
740
+ layout(
741
+ scene = list(
742
+ xaxis = list(title = "Environment", tickangle = 45),
743
+ yaxis = list(title = "Trait"),
744
+ zaxis = list(title = "Proportion"),
745
+ camera = list(
746
+ eye = list(x = 2, y = 2, z = 0.5),
747
+ up = list(x = 0, y = 0, z = 1)
748
+ )
749
+ ),
750
+ plot_bgcolor = "transparent",
751
+ paper_bgcolor = "transparent",
752
+ margin = list(l = 70, r = 70, t = 70, b = 140),
753
+ font = list(family = "Poppins", size = 12, color = "#2D3748"),
754
+ showlegend = FALSE
755
+ )
756
+ }
757
+ })
758
+
759
+ # Phenotypic: Table outputs
760
+ output$pheno_statsTable <- renderDT({
761
+ req(rv_pheno$summary_traits)
762
+ datatable(
763
+ rv_pheno$summary_traits,
764
+ options = list(
765
+ pageLength = 10,
766
+ scrollX = TRUE,
767
+ dom = 'Bfrtip',
768
+ buttons = c('copy', 'csv', 'excel', 'pdf', 'print'),
769
+ columnDefs = list(list(className = 'dt-center', targets = '_all'))
770
+ ),
771
+ extensions = 'Buttons',
772
+ class = 'cell-border stripe',
773
+ caption = "Environment-Wise Descriptive Statistics"
774
+ )
775
+ })
776
+
777
+ output$pheno_downloadStats <- downloadHandler(
778
+ filename = function() {
779
+ "descriptive_stats.csv"
780
  },
781
+ content = function(file) {
782
+ write.csv(rv_pheno$summary_traits, file, row.names = FALSE)
783
+ }
784
  )
785
+
786
+ # LME4: Process data
787
+ lme4_process_data <- function(path) {
788
+ message("LME4: Reading Excel file: ", path)
789
+ data <- read_excel(path)
790
+
791
+ required_cols <- c("Genotype", "Block", "Row", "Column", "Rep", "Environment")
792
+ missing_cols <- setdiff(required_cols, names(data))
793
+ if (length(missing_cols) > 0) {
794
+ stop("Missing required columns: ", paste(missing_cols, collapse = ", "))
795
+ }
796
+
797
+ data$Genotype <- as.factor(data$Genotype)
798
+ data$Block <- as.factor(data$Block)
799
+ data$Row <- as.factor(data$Row)
800
+ data$Rep <- as.factor(data$Rep)
801
+ data$Column <- as.factor(data$Column)
802
+ data$Environment <- as.factor(data$Environment)
803
+ data$Environment <- factor(data$Environment, levels = unique(data$Environment))
804
+
805
+ all_cols <- names(data)
806
+ trait_cols <- all_cols[9:length(all_cols)]
807
+ numeric_cols <- trait_cols[sapply(data[trait_cols], is.numeric)]
808
+
809
+ if (length(numeric_cols) == 0) {
810
+ stop("No numeric columns found for traits starting from column 9")
811
+ }
812
+
813
+ combo_counts <- table(data$Environment, data$Genotype)
814
+ zero_combinations <- sum(combo_counts == 0)
815
+ if (zero_combinations > 0) {
816
+ message("LME4: Warning: ", zero_combinations, " Environment:Genotype combinations have no data")
817
+ }
818
+ if (zero_combinations > (nrow(combo_counts) * ncol(combo_counts) * 0.5)) {
819
+ message("LME4: Warning: Over 50% of Environment:Genotype combinations are missing, model fitting may fail")
820
+ }
821
+
822
+ missing_data <- data %>%
823
+ group_by(Environment) %>%
824
+ summarise(across(all_of(numeric_cols), ~ sum(is.na(.)) / length(.)))
825
+ bad_envs <- missing_data %>%
826
+ pivot_longer(cols = all_of(numeric_cols), names_to = "Trait", values_to = "Missing") %>%
827
+ filter(Missing > 0.2) %>%
828
+ pull(Environment) %>%
829
+ unique()
830
+ if (length(bad_envs) > 0) {
831
+ message("LME4: Filtering out environments with >20% missing data: ", paste(bad_envs, collapse = ", "))
832
+ data <- data %>% filter(!Environment %in% bad_envs) %>% droplevels()
833
+ }
834
+
835
+ n_genotypes <- length(unique(data$Genotype))
836
+ n_environments <- length(unique(data$Environment))
837
+ n_reps <- length(unique(data$Rep))
838
+ n_blocks <- length(unique(data$Block))
839
+ message("LME4: Data summary: ",
840
+ "Rows: ", nrow(data), ", ",
841
+ "Genotypes: ", n_genotypes, ", ",
842
+ "Environments: ", n_environments, ", ",
843
+ "Reps: ", n_reps, ", ",
844
+ "Blocks: ", n_blocks, ", ",
845
+ "Numeric traits: ", length(numeric_cols), " (", paste(numeric_cols, collapse = ", "), ")")
846
+
847
+ if (n_genotypes < 2 || n_environments < 2) {
848
+ stop("Insufficient genotypes (", n_genotypes, ") or environments (", n_environments, ") for LME4 analysis")
849
+ }
850
+
851
+ return(list(data = data, traits = numeric_cols))
852
+ }
853
+
854
+ # LME4: Fit model
855
+ lme4_fit_model <- function(data, trait) {
856
+ message("LME4: Fitting lme4 model for trait: ", trait)
857
+ formula_str <- if (input$lme4_include_interaction) {
858
+ paste(trait, "~ Environment + Genotype + Environment:Genotype + (1|Block) + (1|Row) + (1|Column) + (1|Rep)")
859
+ } else {
860
+ paste(trait, "~ Environment + Genotype + (1|Block) + (1|Row) + (1|Column) + (1|Rep)")
861
+ }
862
+ formula <- as.formula(formula_str)
863
+ model <- NULL
864
+ tryCatch({
865
+ model <- lmer(formula, data = data, na.action = na.omit, control = lmerControl(check.rankX = "warn+drop.cols"))
866
+ message("LME4: Successfully fitted model for ", trait)
867
+ return(model)
868
+ }, error = function(e) {
869
+ message("LME4: Failed to fit model for ", trait, ": ", e$message)
870
+ showNotification(paste("LME4: Failed to fit model for ", trait, ": ", e$message), type = "error", duration = 10)
871
+ return(NULL)
872
+ }, warning = function(w) {
873
+ message("LME4: Warning in model fitting for ", trait, ": ", w$message)
874
+ showNotification(paste("LME4: Warning for ", trait, ": ", w$message), type = "warning", duration = 10)
875
+ return(model)
876
+ })
877
+ }
878
+
879
+ # LME4: Get BLUEs
880
+ lme4_get_blue <- function(model, trait) {
881
+ if (is.null(model)) {
882
+ message("LME4: No model for ", trait, ", returning dummy BLUEs")
883
+ return(data.frame(Trait = trait, Genotype = NA, Environment = NA, predicted.value = NA))
884
+ }
885
+ tryCatch({
886
+ emm_options(pbkrtest.limit = 5000, lmerTest.limit = 5000)
887
+ blues <- emmeans(model, ~ Genotype:Environment)
888
+ blues_df <- as.data.frame(blues) %>%
889
+ rename(predicted.value = emmean) %>%
890
+ mutate(Trait = trait) %>%
891
+ select(Trait, Genotype, Environment, predicted.value)
892
+ return(blues_df)
893
+ }, error = function(e) {
894
+ message("LME4: Error in BLUEs for ", trait, ": ", e$message)
895
+ return(data.frame(Trait = trait, Genotype = NA, Environment = NA, predicted.value = NA))
896
+ })
897
+ }
898
+
899
+ # LME4: Calculate heritability
900
+ lme4_calculate_heritability <- function(model, trait) {
901
+ message("LME4: Calculating heritability for trait: ", trait)
902
+ if (is.null(model)) {
903
+ message("LME4: No model for ", trait, ", returning dummy heritability")
904
+ return(data.frame(Trait = trait, Heritability = NA, Error = "No model fitted"))
905
+ }
906
+ tryCatch({
907
+ varcomp <- as.data.frame(VarCorr(model))
908
+ vg <- varcomp$vcov[varcomp$grp == "Genotype"]
909
+ if (length(vg) == 0 || is.na(vg) || vg <= 0) {
910
+ message("LME4: Invalid or zero genetic variance for ", trait)
911
+ return(data.frame(Trait = trait, Heritability = NA, Error = "Invalid genetic variance"))
912
+ }
913
+ ve <- sigma(model)^2
914
+ if (is.na(ve) || ve <= 0) {
915
+ message("LME4: Invalid or zero residual variance for ", trait)
916
+ return(data.frame(Trait = trait, Heritability = NA, Error = "Invalid residual variance"))
917
+ }
918
+ h2 <- vg / (vg + ve)
919
+ if (h2 < 0 || h2 > 1) {
920
+ message("LME4: Heritability out of bounds for ", trait, ": ", h2)
921
+ return(data.frame(Trait = trait, Heritability = NA, Error = "Heritability out of bounds"))
922
+ }
923
+ return(data.frame(Trait = trait, Heritability = round(h2, 3), Error = NA))
924
+ }, error = function(e) {
925
+ message("LME4: Failed to calculate heritability for ", trait, ": ", e$message)
926
+ return(data.frame(Trait = trait, Heritability = NA, Error = e$message))
927
+ }, warning = function(w) {
928
+ message("LME4: Warning in heritability calculation for ", trait, ": ", w$message)
929
+ return(data.frame(Trait = trait, Heritability = NA, Error = w$message))
930
+ })
931
+ }
932
+
933
+ # LME4: Finlay-Wilkinson stability
934
+ lme4_finlay_wilkinson <- function(blues, trait) {
935
+ blues_trait <- blues %>% filter(Trait == trait, !is.na(predicted.value))
936
+ if (nrow(blues_trait) < 4) {
937
+ message("LME4: Insufficient valid BLUEs for ", trait, " (", nrow(blues_trait), " rows)")
938
+ return(data.frame(Genotype = NA, Slope = NA, R2 = NA, Trait = trait, Error = "Insufficient data"))
939
+ }
940
+ env_means <- blues_trait %>%
941
+ group_by(Environment) %>%
942
+ summarize(mean_value = mean(predicted.value, na.rm = TRUE))
943
+ blues_trait <- blues_trait %>% left_join(env_means, by = "Environment")
944
+
945
+ if (nrow(blues_trait) == 0 || all(is.na(blues_trait$mean_value))) {
946
+ message("LME4: No valid environment means for ", trait)
947
+ return(data.frame(Genotype = NA, Slope = NA, R2 = NA, Trait = trait, Error = "No valid environment means"))
948
+ }
949
+
950
+ stability <- blues_trait %>%
951
+ group_by(Genotype) %>%
952
+ do({
953
+ data_subset <- .
954
+ model <- tryCatch({
955
+ lm(predicted.value ~ mean_value, data = data_subset)
956
+ }, error = function(e) {
957
+ NULL
958
+ })
959
+ if (is.null(model) || nrow(data_subset) < 2) {
960
+ data.frame(Slope = NA, R2 = NA, Error = "Model fitting failed or insufficient data")
961
+ } else {
962
+ data.frame(
963
+ Slope = coef(model)[2],
964
+ R2 = summary(model)$r.squared,
965
+ Error = NA
966
+ )
967
+ }
968
+ }) %>%
969
+ mutate(Trait = trait)
970
+
971
+ return(stability)
972
+ }
973
+
974
+ # LME4: File upload observer
975
+ observeEvent(input$lme4_file, {
976
+ req(input$lme4_file)
977
+ message("LME4: File upload triggered: ", input$lme4_file$name)
978
+ shinyjs::show("lme4_loader")
979
+ on.exit(shinyjs::hide("lme4_loader"))
980
+
981
+ tryCatch({
982
+ result <- lme4_process_data(input$lme4_file$datapath)
983
+ rv_lme4$data <- result$data
984
+ rv_lme4$traits <- result$traits
985
+ rv_lme4$trait <- result$traits[1]
986
+ message("LME4: Data processed, rows: ", nrow(rv_lme4$data), ", traits: ", paste(rv_lme4$traits, collapse = ", "))
987
+
988
+ updateSelectInput(session, "lme4_selected_trait", choices = rv_lme4$traits, selected = rv_lme4$traits[1])
989
+
990
+ shinyjs::show("lme4_data_stats")
991
+ output$lme4_n_vars <- renderText({ ncol(rv_lme4$data) })
992
+ output$lme4_n_obs <- renderText({ nrow(rv_lme4$data) })
993
+ output$lme4_n_geno <- renderText({ length(unique(rv_lme4$data$Genotype)) })
994
+ output$lme4_n_env <- renderText({ length(unique(rv_lme4$data$Environment)) })
995
+
996
+ output$lme4_data_preview <- renderPrint({
997
+ str(rv_lme4$data)
998
+ message("LME4: Trait columns selected: ", paste(names(rv_lme4$data)[9:ncol(rv_lme4$data)], collapse = ", "))
999
+ })
1000
+
1001
+ debug_log <- c()
1002
+
1003
+ withProgress(message = 'LME4: Analyzing data', value = 0, {
1004
+ lme4_models <- list()
1005
+ blues_list <- list()
1006
+ herit_list <- list()
1007
+ stability_list <- list()
1008
+
1009
+ total_steps <- length(rv_lme4$traits) * 3 + 1
1010
+ step_increment <- 1 / total_steps
1011
+
1012
+ for (trait in rv_lme4$traits) {
1013
+ incProgress(step_increment, detail = paste("Fitting model for", trait))
1014
+ model <- lme4_fit_model(rv_lme4$data, trait)
1015
+ lme4_models[[trait]] <- model
1016
+ debug_log <- c(debug_log, paste("Trait:", trait, "- Model fitted:", ifelse(is.null(model), "Failed", "Success")))
1017
+
1018
+ incProgress(step_increment, detail = paste("Calculating predicted means for", trait))
1019
+ blues_list[[trait]] <- lme4_get_blue(model, trait)
1020
+
1021
+ incProgress(step_increment, detail = paste("Calculating heritability for", trait))
1022
+ herit_list[[trait]] <- lme4_calculate_heritability(model, trait)
1023
+
1024
+ incProgress(step_increment, detail = paste("Performing stability analysis for", trait))
1025
+ stability_list[[trait]] <- lme4_finlay_wilkinson(blues_list[[trait]], trait)
1026
+ }
1027
+
1028
+ incProgress(step_increment, detail = "Calculating correlations")
1029
+ if (length(rv_lme4$traits) > 1) {
1030
+ trait_data <- rv_lme4$data %>% select(all_of(rv_lme4$traits))
1031
+ cor_matrix <- cor(trait_data, use = "pairwise.complete.obs")
1032
+ cor_table <- as.data.frame(as.table(cor_matrix)) %>%
1033
+ rename(Trait1 = Var1, Trait2 = Var2, Correlation = Freq)
1034
+ rv_lme4$cor_matrix <- cor_matrix
1035
+ rv_lme4$cor_table <- cor_table
1036
+ debug_log <- c(debug_log, "Correlations: Success")
1037
+ } else {
1038
+ rv_lme4$cor_matrix <- matrix(1, nrow = 1, ncol = 1, dimnames = list(rv_lme4$traits, rv_lme4$traits))
1039
+ rv_lme4$cor_table <- data.frame(Trait1 = rv_lme4$traits, Trait2 = rv_lme4$traits, Correlation = 1)
1040
+ debug_log <- c(debug_log, "Correlations: Single trait, set to 1")
1041
+ }
1042
+
1043
+ rv_lme4$lme4_models <- lme4_models
1044
+ rv_lme4$blues_all <- bind_rows(blues_list)
1045
+ rv_lme4$heritability_table <- bind_rows(herit_list)
1046
+ rv_lme4$stability_table <- bind_rows(stability_list)
1047
+ rv_lme4$debug_log <- debug_log
1048
+
1049
+ shinyjs::hide("lme4_blues_placeholder")
1050
+ shinyjs::show("lme4_blues_content")
1051
+ shinyjs::hide("lme4_heritability_placeholder")
1052
+ shinyjs::show("lme4_heritability_content")
1053
+ shinyjs::hide("lme4_correlations_placeholder")
1054
+ shinyjs::show("lme4_correlations_content")
1055
+ shinyjs::hide("lme4_stability_placeholder")
1056
+ shinyjs::show("lme4_stability_content")
1057
+ })
1058
+
1059
+ output$lme4_debug_log <- renderPrint({
1060
+ cat(paste(rv_lme4$debug_log, collapse = "\n"))
1061
+ })
1062
+
1063
+ showNotification("LME4: File uploaded and analyzed successfully", type = "message", duration = 5)
1064
+ }, error = function(e) {
1065
+ message("LME4: Error in file processing: ", e$message)
1066
+ showNotification(paste("LME4 Error:", e$message), type = "error", duration = 10)
1067
+ })
1068
+ })
1069
+
1070
+ # Update selected trait
1071
+ observe({
1072
+ req(input$lme4_selected_trait)
1073
+ rv_lme4$trait <- input$lme4_selected_trait
1074
+ })
1075
+
1076
+ # LME4: Filtered reactives
1077
+ lme4_filtered_blues <- reactive({
1078
+ req(rv_lme4$blues_all, rv_lme4$trait)
1079
+ rv_lme4$blues_all %>% filter(Trait = rv_lme4$trait)
1080
+ })
1081
+
1082
+ lme4_filtered_heritability <- reactive({
1083
+ req(rv_lme4$heritability_table, rv_lme4$trait)
1084
+ rv_lme4$heritability_table %>% filter(Trait = rv_lme4$trait)
1085
+ })
1086
+
1087
+ lme4_filtered_stability <- reactive({
1088
+ req(rv_lme4$stability_table, rv_lme4$trait)
1089
+ rv_lme4$stability_table %>% filter(Trait = rv_lme4$trait)
1090
+ })
1091
+
1092
+ # LME4: Plot outputs
1093
+ output$lme4_blues_plot <- renderPlotly({
1094
+ req(lme4_filtered_blues())
1095
+ data <- lme4_filtered_blues()
1096
+ if (all(is.na(data$predicted.value))) {
1097
+ plot_ly() %>%
1098
+ layout(
1099
+ title = paste("No valid predicted means for", rv_lme4$trait),
1100
+ plot_bgcolor = "transparent",
1101
+ paper_bgcolor = "transparent",
1102
+ font = list(family = "Poppins", size = 12, color = "#2D3748")
1103
+ )
1104
+ } else {
1105
+ plot_ly(data, x = ~Environment, y = ~predicted.value, color = ~Genotype,
1106
+ type = 'scatter', mode = 'lines+markers',
1107
+ colors = c('#FFB6C1', '#FFDAB9', '#B5EAD7', '#E6E6FA', '#FFFACD', '#FF9999')) %>%
1108
+ layout(
1109
+ title = paste("Predicted Means for", rv_lme4$trait),
1110
+ xaxis = list(title = "Environment"),
1111
+ yaxis = list(title = "Predicted Value"),
1112
+ plot_bgcolor = "transparent",
1113
+ paper_bgcolor = "transparent",
1114
+ font = list(family = "Poppins", size = 12, color = "#2D3748")
1115
+ )
1116
+ }
1117
+ })
1118
+
1119
+ output$lme4_heritability_plot <- renderPlotly({
1120
+ req(lme4_filtered_heritability())
1121
+ data <- lme4_filtered_heritability()
1122
+ if (all(is.na(data$Heritability))) {
1123
+ plot_ly() %>%
1124
+ layout(
1125
+ title = paste("No valid heritability for", rv_lme4$trait, ":", unique(data$Error)),
1126
+ plot_bgcolor = "transparent",
1127
+ paper_bgcolor = "transparent",
1128
+ font = list(family = "Poppins", size = 12, color = "#2D3748")
1129
+ )
1130
+ } else {
1131
+ plot_ly(data, x = ~Trait, y = ~Heritability, type = 'bar',
1132
+ color = ~Trait, colors = c('#FFB6C1', '#FFDAB9', '#B5EAD7', '#E6E6FA', '#FFFACD', '#FF9999')) %>%
1133
+ layout(
1134
+ title = "Heritability",
1135
+ xaxis = list(title = "Trait"),
1136
+ yaxis = list(title = "Heritability", range = c(0, 1)),
1137
+ showlegend = FALSE,
1138
+ plot_bgcolor = "transparent",
1139
+ paper_bgcolor = "transparent",
1140
+ font = list(family = "Poppins", size = 12, color = "#2D3748")
1141
+ )
1142
+ }
1143
+ })
1144
+
1145
+ output$lme4_correlation_plot <- renderPlotly({
1146
+ req(rv_lme4$cor_matrix)
1147
+ if (ncol(rv_lme4$cor_matrix) < 2) {
1148
+ plot_ly() %>%
1149
+ layout(
1150
+ title = "Correlation plot requires at least two traits",
1151
+ plot_bgcolor = "transparent",
1152
+ paper_bgcolor = "transparent",
1153
+ font = list(family = "Poppins", size = 12, color = "#2D3748")
1154
+ )
1155
+ } else {
1156
+ plot_ly(
1157
+ x = colnames(rv_lme4$cor_matrix),
1158
+ y = rownames(rv_lme4$cor_matrix),
1159
+ z = rv_lme4$cor_matrix,
1160
+ type = "heatmap",
1161
+ colors = colorRamp(c('#E6E6FA', 'white', '#FFB6C1'))
1162
+ ) %>%
1163
+ layout(
1164
+ title = "Trait Correlation Matrix",
1165
+ xaxis = list(title = ""),
1166
+ yaxis = list(title = ""),
1167
+ plot_bgcolor = "transparent",
1168
+ paper_bgcolor = "transparent",
1169
+ font = list(family = "Poppins", size = 12, color = "#2D3748")
1170
+ )
1171
+ }
1172
+ })
1173
+
1174
+ output$lme4_stability_plot <- renderPlotly({
1175
+ req(lme4_filtered_stability())
1176
+ data <- lme4_filtered_stability()
1177
+ if (all(is.na(data$Slope))) {
1178
+ plot_ly() %>%
1179
+ layout(
1180
+ title = paste("No valid stability analysis for", rv_lme4$trait, ":", unique(data$Error)),
1181
+ plot_bgcolor = "transparent",
1182
+ paper_bgcolor = "transparent",
1183
+ font = list(family = "Poppins", size = 12, color = "#2D3748")
1184
+ )
1185
+ } else {
1186
+ plot_ly(data, x = ~Slope, y = ~R2, text = ~Genotype, type = 'scatter', mode = 'markers+text',
1187
+ marker = list(size = 12, color = '#FFB6C1'),
1188
+ textposition = 'top') %>%
1189
+ layout(
1190
+ title = paste("Stability Analysis for", rv_lme4$trait),
1191
+ xaxis = list(title = "Slope"),
1192
+ yaxis = list(title = "R²"),
1193
+ plot_bgcolor = "transparent",
1194
+ paper_bgcolor = "transparent",
1195
+ font = list(family = "Poppins", size = 12, color = "#2D3748")
1196
+ )
1197
+ }
1198
+ })
1199
+
1200
+ # LME4: Table outputs
1201
+ output$lme4_blues_table <- renderDT({
1202
+ req(lme4_filtered_blues())
1203
+ datatable(
1204
+ lme4_filtered_blues(),
1205
+ extensions = 'Buttons',
1206
+ options = list(scrollX = TRUE, dom = 'Bfrtip',
1207
+ buttons = c('copy', 'excel', 'pdf', 'print'),
1208
+ pageLength = 10),
1209
+ caption = paste("Predicted Means for", rv_lme4$trait)
1210
+ )
1211
+ })
1212
+
1213
+ output$lme4_heritability_table <- renderDT({
1214
+ req(lme4_filtered_heritability())
1215
+ datatable(
1216
+ lme4_filtered_heritability(),
1217
+ extensions = 'Buttons',
1218
+ options = list(scrollX = TRUE, dom = 'Bfrtip',
1219
+ buttons = c('copy', 'excel', 'pdf', 'print'),
1220
+ pageLength = 10),
1221
+ caption = "Broad-Sense Heritability"
1222
+ )
1223
+ })
1224
+
1225
+ output$lme4_cor_table <- renderDT({
1226
+ req(rv_lme4$cor_table)
1227
+ datatable(
1228
+ rv_lme4$cor_table,
1229
+ extensions = 'Buttons',
1230
+ options = list(scrollX = TRUE, dom = 'Bfrtip',
1231
+ buttons = c('copy', 'excel', 'pdf', 'print'),
1232
+ pageLength = 10),
1233
+ caption = "Correlation Between Traits"
1234
+ )
1235
+ })
1236
+
1237
+ output$lme4_stability_table <- renderDT({
1238
+ req(lme4_filtered_stability())
1239
+ datatable(
1240
+ lme4_filtered_stability(),
1241
+ extensions = 'Buttons',
1242
+ options = list(scrollX = TRUE, dom = 'Bfrtip',
1243
+ buttons = c('copy', 'excel', 'pdf', 'print'),
1244
+ pageLength = 10),
1245
+ caption = paste("Stability Analysis for", rv_lme4$trait)
1246
+ )
1247
+ })
1248
  }
1249
 
1250
+ # Run the Shiny app
1251
+ shinyApp(ui, server)