International Rice Research Institute commited on
Commit
6e738f3
·
verified ·
1 Parent(s): 4e0823d

Update app.R

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