library(shiny) library(shinyjs) library(tidyverse) library(DT) library(readxl) library(lme4) library(emmeans) library(plotly) library(shinyWidgets) library(ggplot2) library(pbkrtest) library(lmerTest) # UI with updated styling, including Stability and PCA tabs ui <- fluidPage( useShinyjs(), tags$head( tags$meta(charset = "UTF-8"), tags$title("Phenotypic Analysis Dashboard"), tags$link(rel = "stylesheet", href = "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"), tags$style(HTML(" :root { --primary: #1E3A8A; /* Dark blue for tabs */ --secondary: #6B8E23; /* Olive green */ --success: #32CD32; /* Lime Green */ --info: #4169E1; /* Royal Blue */ --warning: #FF8C00; /* Dark Orange */ --danger: #DC143C; /* Crimson */ --light: #D1D5DB; /* Grey for tab text */ --dark: #2F4F4F; /* Dark Slate Gray */ --background: #FFFFFF; /* White background */ --card-bg: #FFFFFF; /* White for cards */ } body { font-family: 'Poppins', sans-serif; background: var(--background); color: var(--dark); overflow-x: hidden; } .container-fluid { max-width: 1600px; padding: 2.5rem; margin: 0 auto; } .section { margin-bottom: 30px; background: var(--card-bg); padding: 2.5rem; border-radius: 15px; box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1); border: 1px solid rgba(30, 58, 138, 0.2); } h1, h2, h3 { color: var(--primary); border-bottom: 2px solid var(--secondary); padding-bottom: 10px; margin-bottom: 20px; font-weight: 700; } .chart-container { position: relative; margin-bottom: 20px; border-radius: 12px; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); background: var(--card-bg); padding: 1.5rem; border: 1px solid rgba(30, 58, 138, 0.2); min-height: 400px; } .insights { margin-top: 20px; padding: 20px; background: #F5F5F5; border-radius: 8px; border-left: 4px solid var(--secondary); font-size: 14px; } .upload-container { padding: 20px; text-align: center; border: 2px dashed var(--primary); border-radius: 8px; margin-bottom: 25px; background: #F9F9F9; } .upload-icon { font-size: 48px; color: var(--primary); margin-bottom: 15px; } .btn-primary { background: linear-gradient(135deg, var(--primary), var(--info)); border: none; padding: 1rem 2.5rem; border-radius: 8px; font-weight: 600; color: white; transition: all 0.3s; box-shadow: 0 4px 8px rgba(0,0,0,0.1); } .btn-primary:hover { background: linear-gradient(135deg, var(--info), var(--primary)); transform: translateY(-2px); box-shadow: 0 6px 12px rgba(30, 58, 138, 0.3); color: white; } .sidebar { background: var(--card-bg); color: var(--dark); padding: 2rem; height: 100vh; position: fixed; width: 280px; box-shadow: 5px 0 15px rgba(0,0,0,0.1); border-right: 1px solid var(--primary); } .sidebar-header { padding: 20px; background: linear-gradient(135deg, var(--primary), var(--info)); text-align: center; border-bottom: 1px solid rgba(0,0,0,0.1); border-radius: 10px; margin-bottom: 20px; color: white; } .sidebar-content { padding: 15px; } .nav-link { color: var(--dark); padding: 12px 15px; border-radius: 8px; margin-bottom: 8px; display: flex; align-items: center; transition: all 0.3s; background: #F5F5F5; } .nav-link:hover, .nav-link.active { color: white; background: linear-gradient(90deg, var(--primary), var(--info)); transform: translateX(5px); box-shadow: 0 4px 8px rgba(30, 58, 138, 0.3); } .nav-link i { margin-right: 10px; width: 20px; text-align: center; } .main-content { margin-left: 280px; padding: 20px; width: calc(100% - 280px); min-height: 100vh; background: var(--background); } .loader { border: 5px solid #F5F5F5; border-top: 5px solid var(--primary); border-radius: 50%; width: 50px; height: 50px; animation: spin 1s linear infinite; margin: 20px auto; } @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } } .hidden { display: none; } table.dataTable { border-collapse: collapse; width: 100%; font-size: 16px; background: var(--card-bg); border-radius: 8px; overflow: hidden; } th { background: linear-gradient(45deg, var(--primary), var(--info)); color: white; padding: 1.2rem; font-weight: 700; text-transform: uppercase; } td { padding: 1.2rem; border-bottom: 1px solid #F0F0F0; transition: background 0.3s; color: var(--dark); } tr:hover { background: #F5F5F5; } .dataTables_wrapper { color: var(--dark); } .status-card { background: var(--card-bg); padding: 20px; border-radius: 10px; text-align: center; box-shadow: 0 4px 8px rgba(0,0,0,0.1); border: 1px solid rgba(30, 58, 138, 0.2); margin-bottom: 15px; } .status-card i { font-size: 2rem; color: var(--primary); margin-bottom: 10px; } .status-card h4 { color: var(--primary); font-size: 1.5rem; margin: 5px 0; } .status-card p { color: var(--dark); margin: 0; } .plotly-title { font-size: 18px; font-weight: bold; color: var(--primary); } .plotly-annotation { font-size: 14px; color: var(--dark); } ")) ), div( class = "app-wrapper", div( class = "sidebar", div( class = "sidebar-header", h3("📊 Phenotypic Data Analysis", style = "margin: 0; font-weight: 600; color: white;") ), selectInput("lme4_selected_trait", "Select Trait for Detailed Analysis", choices = c()), checkboxInput("lme4_include_interaction", "Include Environment:Genotype Interaction", value = FALSE), div( class = "sidebar-content", div( class = "nav flex-column", id = "lme4-v-pills-tab", role = "tablist", tags$a(class = "nav-link active", `data-toggle` = "pill", href = "#lme4-upload", role = "tab", icon("file-upload", class = "fas"), "📤 Upload Data"), tags$a(class = "nav-link", `data-toggle` = "pill", href = "#lme4-descriptives", role = "tab", icon("chart-line", class = "fas"), "📊 Descriptive Statistics"), tags$a(class = "nav-link", `data-toggle` = "pill", href = "#lme4-blues", role = "tab", icon("chart-bar", class = "fas"), "📈 Predicted Means"), tags$a(class = "nav-link", `data-toggle` = "pill", href = "#lme4-correlations", role = "tab", icon("link", class = "fas"), "🔗 Trait Correlations"), tags$a(class = "nav-link", `data-toggle` = "pill", href = "#lme4-heritability", role = "tab", icon("calculator", class = "fas"), "🧬 Heritability"), tags$a(class = "nav-link", `data-toggle` = "pill", href = "#lme4-rankings", role = "tab", icon("trophy", class = "fas"), "🏆 Genotype Rankings"), tags$a(class = "nav-link", `data-toggle` = "pill", href = "#lme4-stability", role = "tab", icon("balance-scale", class = "fas"), "⚖️ Stability Analysis"), tags$a(class = "nav-link", `data-toggle` = "pill", href = "#lme4-pca", role = "tab", icon("chart-scatter", class = "fas"), "🔍 PCA Analysis") ), hr(style = "border-color: rgba(255,255,255,0.1);"), div( style = "padding: 15px; color: var(--light); font-size: 12px; text-align: center;", p("LME4 Analysis Dashboard v1.3"), p("© 2023 Statistical Genetics Lab") ) ) ), div( class = "main-content", div( class = "tab-content", div( class = "tab-pane fade show active", id = "lme4-upload", role = "tabpanel", div( class = "section", h2("📤 Upload Your Data"), div( class = "upload-container", div(class = "upload-icon", icon("cloud-upload-alt", class = "fas")), h3("📁 Drag and drop your Excel file here", style = "color: var(--primary);"), p("or", style = "margin: 10px 0;"), fileInput("lme4_file", NULL, accept = c(".xlsx", ".xls"), buttonLabel = "Browse Files", placeholder = "No file selected"), p("📝 Supported formats: .xlsx, .xls", style = "color: var(--light); font-size: 14px;"), div(id = "lme4_loader", class = "loader hidden") ), verbatimTextOutput("lme4_data_preview"), verbatimTextOutput("lme4_debug_log"), div( id = "lme4_data_stats", class = "hidden", h3("📊 Data Overview"), fluidRow( column(3, div(class = "status-card card-1", icon("columns", class = "fas"), h4(textOutput("lme4_n_vars"), style = "font-weight: 600;"), p("Variables") )), column(3, div(class = "status-card card-2", icon("list", class = "fas"), h4(textOutput("lme4_n_obs"), style = "font-weight: 600;"), p("Observations") )), column(3, div(class = "status-card card-3", icon("dna", class = "fas"), h4(textOutput("lme4_n_geno"), style = "font-weight: 600;"), p("Genotypes") )), column(3, div(class = "status-card card-4", icon("globe", class = "fas"), h4(textOutput("lme4_n_env"), style = "font-weight: 600;"), p("Environments") )) ) ) ) ), div( class = "tab-pane fade", id = "lme4-descriptives", role = "tabpanel", div( class = "section", h2("📊 Descriptive Statistics"), div( id = "lme4_descriptives_content", div(class = "table-container", DTOutput("lme4_descriptives_table")), div(class = "chart-container", plotlyOutput("lme4_descriptives_plot", height = "500px")), div( class = "insights", h4("💡 Interpretation & Insights"), p("Descriptive statistics summarize central tendency, variability, and range for each trait. Coefficient of Variation (CV) indicates relative variability; CV < 10% suggests low variability (high precision), 10-20% moderate, >20% high (potential environmental influence or measurement error)."), uiOutput("lme4_descriptives_insights") ) ), div( id = "lme4_descriptives_placeholder", class = "text-center", icon("chart-line", class = "fas", style = "font-size: 72px; color: var(--light); margin: 30px 0;"), h4("📤 Upload data to see descriptive statistics", style = "color: var(--light);") ) ) ), div( class = "tab-pane fade", id = "lme4-blues", role = "tabpanel", div( class = "section", h2("📈 Predicted Means (BLUEs)"), div( id = "lme4_blues_content", div(class = "chart-container", plotlyOutput("lme4_blues_plot", height = "500px")), div(class = "table-container", DTOutput("lme4_blues_table")), div( class = "insights", h4("💡 Interpretation & Insights"), p("The G×E interaction plot shows genotype performance across environments. Stable genotypes have consistent values (parallel lines), while environment-specific genotypes vary (crossing lines)."), uiOutput("lme4_blues_insights") ) ), div( id = "lme4_blues_placeholder", class = "text-center", icon("chart-bar", class = "fas", style = "font-size: 72px; color: var(--light); margin: 30px 0;"), h4("📤 Upload data to see predicted means", style = "color: var(--light);") ) ) ), div( class = "tab-pane fade", id = "lme4-correlations", role = "tabpanel", div( class = "section", h2("🔗 Trait Correlations"), div( id = "lme4_correlations_content", div(class = "chart-container", plotlyOutput("lme4_correlation_plot", height = "500px")), div(class = "table-container", DTOutput("lme4_cor_table")), div( class = "insights", h4("💡 Interpretation & Insights"), p("Correlations reveal trait synergies or trade-offs. Positive correlations (r > 0.5) suggest traits improve together; negative (r < -0.5) indicate trade-offs."), uiOutput("lme4_correlations_insights") ) ), div( id = "lme4_correlations_placeholder", class = "text-center", icon("link", class = "fas", style = "font-size: 72px; color: var(--light); margin: 30px 0;"), h4("📤 Upload data to see trait correlations", style = "color: var(--light);") ) ) ), div( class = "tab-pane fade", id = "lme4-heritability", role = "tabpanel", div( class = "section", h2("🧬 Heritability Estimates"), div( id = "lme4_heritability_content", div(class = "table-container", DTOutput("lme4_heritability_table")), div( class = "insights", h4("💡 Interpretation & Insights"), p("Broad-sense heritability (H²) indicates the proportion of phenotypic variance attributable to genotypic variance. H² > 0.6 suggests high heritability (effective for selection), 0.3-0.6 moderate, <0.3 low (environment dominates)."), uiOutput("lme4_heritability_insights") ) ), div( id = "lme4_heritability_placeholder", class = "text-center", icon("calculator", class = "fas", style = "font-size: 72px; color: var(--light); margin: 30px 0;"), h4("📤 Upload data to see heritability estimates", style = "color: var(--light);") ) ) ), div( class = "tab-pane fade", id = "lme4-rankings", role = "tabpanel", div( class = "section", h2("🏆 Genotype Rankings"), div( id = "lme4_rankings_content", div(class = "table-container", DTOutput("lme4_rankings_table")), div(class = "chart-container", plotlyOutput("lme4_rankings_plot", height = "500px")), div( class = "insights", h4("💡 Interpretation & Insights"), p("Rankings are based on average predicted performance across environments. Top-ranked genotypes are overall best performers."), uiOutput("lme4_rankings_insights") ) ), div( id = "lme4_rankings_placeholder", class = "text-center", icon("trophy", class = "fas", style = "font-size: 72px; color: var(--light); margin: 30px 0;"), h4("📤 Upload data to see genotype rankings", style = "color: var(--light);") ) ) ), div( class = "tab-pane fade", id = "lme4-stability", role = "tabpanel", div( class = "section", h2("⚖️ Stability Analysis"), div( id = "lme4_stability_content", div(class = "chart-container", plotlyOutput("lme4_stability_plot", height = "500px")), div(class = "table-container", DTOutput("lme4_stability_table")), div( class = "insights", h4("💡 Interpretation & Insights"), p("Finlay-Wilkinson regression slopes measure genotype stability. Slopes ~1 indicate average stability, <1 high stability (less responsive to environment), >1 low stability (highly responsive)."), uiOutput("lme4_stability_insights") ) ), div( id = "lme4_stability_placeholder", class = "text-center", icon("balance-scale", class = "fas", style = "font-size: 72px; color: var(--light); margin: 30px 0;"), h4("📤 Upload data to see stability analysis", style = "color: var(--light);") ) ) ), div( class = "tab-pane fade", id = "lme4-pca", role = "tabpanel", div( class = "section", h2("🔍 PCA Analysis"), div( id = "lme4_pca_content", div(class = "chart-container", plotlyOutput("lme4_pca_plot", height = "500px")), div(class = "table-container", DTOutput("lme4_pca_table")), div( class = "insights", h4("💡 Interpretation & Insights"), p("PCA reduces multi-trait data to principal components. Genotypes close together are phenotypically similar. PC1 and PC2 explain the majority of variance; check loadings for trait contributions."), uiOutput("lme4_pca_insights") ) ), div( id = "lme4_pca_placeholder", class = "text-center", icon("chart-scatter", class = "fas", style = "font-size: 72px; color: var(--light); margin: 30px 0;"), h4("📤 Upload data to see PCA analysis", style = "color: var(--light);") ) ) ) ) ) ) ) # Server function server <- function(input, output, session) { # LME4 Analysis Reactive Values rv_lme4 <- reactiveValues( data = NULL, traits = NULL, trait = NULL, fixed_models = NULL, random_models = NULL, blues_all = NULL, cor_matrix = NULL, cor_table = NULL, descriptives = NULL, heritability = NULL, rankings = NULL, stability = NULL, pca = NULL, debug_log = NULL ) # Plot formatting constants PLOT_FONT <- list(family = "Poppins", size = 14, color = "#2D3748") PLOT_COLORS <- c("#FFB6C1", "#FFDAB9", "#B5EAD7", "#E6E6FA", "#FFFACD", "#FF9999") PLOT_LAYOUT <- list( plot_bgcolor = "transparent", paper_bgcolor = "transparent", margin = list(l = 80, r = 80, t = 100, b = 100), font = PLOT_FONT, showlegend = TRUE, legend = list(orientation = "h", y = -0.2, x = 0.5, xanchor = "center") ) # LME4: Process data lme4_process_data <- function(path) { message("LME4: Reading Excel file: ", path) tryCatch({ data <- read_excel(path) colnames(data) <- make.names(colnames(data), unique = TRUE) required_cols <- c("Genotype", "Block", "Row", "Column", "Rep", "Environment") missing_cols <- setdiff(required_cols, names(data)) if (length(missing_cols) > 0) { stop("Missing required columns: ", paste(missing_cols, collapse = ", ")) } data$Genotype <- as.factor(data$Genotype) data$Block <- as.factor(data$Block) data$Row <- as.factor(data$Row) data$Rep <- as.factor(data$Rep) data$Column <- as.factor(data$Column) data$Environment <- as.factor(data$Environment) data$Environment <- factor(data$Environment, levels = unique(data$Environment)) all_cols <- names(data) trait_cols <- all_cols[9:length(all_cols)] numeric_cols <- trait_cols[sapply(data[trait_cols], is.numeric)] if (length(numeric_cols) == 0) { stop("No numeric columns found for traits starting from column 9") } n_genotypes <- length(unique(data$Genotype)) n_environments <- length(unique(data$Environment)) if (n_genotypes < 3) { stop("Insufficient genotypes (", n_genotypes, ") for analysis; need at least 3") } if (n_environments < 2) { stop("Insufficient environments (", n_environments, ") for analysis; need at least 2") } combo_counts <- table(data$Environment, data$Genotype) zero_combinations <- sum(combo_counts == 0) if (zero_combinations > 0) { message("LME4: Warning: ", zero_combinations, " Environment:Genotype combinations have no data") showNotification( paste(zero_combinations, "Environment:Genotype combinations are missing. Consider checking data completeness or imputing missing values."), type = "warning", duration = 10 ) } if (zero_combinations > (nrow(combo_counts) * ncol(combo_counts) * 0.5)) { showNotification("Warning: Over 50% of Environment:Genotype combinations are missing", type = "warning", duration = 10) } missing_data <- data %>% group_by(Environment) %>% summarise(across(all_of(numeric_cols), ~ sum(is.na(.)) / length(.))) bad_envs <- missing_data %>% pivot_longer(cols = all_of(numeric_cols), names_to = "Trait", values_to = "Missing") %>% filter(Missing > 0.2) %>% pull(Environment) %>% unique() if (length(bad_envs) > 0) { message("LME4: Filtering out environments with >20% missing data: ", paste(bad_envs, collapse = ", ")) data <- data %>% filter(!Environment %in% bad_envs) %>% droplevels() } message("LME4: Data summary: Rows=", nrow(data), ", Genotypes=", n_genotypes, ", Environments=", n_environments, ", Traits=", paste(numeric_cols, collapse = ", ")) return(list(data = data, traits = numeric_cols)) }, error = function(e) { message("LME4: Error in data processing: ", e$message) showNotification(paste("Error processing file:", e$message), type = "error", duration = 10) return(NULL) }) } # LME4: Fit fixed model for BLUEs lme4_fit_fixed_model <- function(data, trait) { message("LME4: Fitting fixed model for ", trait) formula_str <- if (input$lme4_include_interaction) { paste(trait, "~ Environment + Genotype + Environment:Genotype + (1|Block) + (1|Rep)") } else { paste(trait, "~ Environment + Genotype + (1|Block) + (1|Rep)") } formula <- as.formula(formula_str) tryCatch({ model <- lmer(formula, data = data, na.action = na.omit, control = lmerControl(check.rankX = "warn+drop.cols", optimizer = "bobyqa", checkSingularity = TRUE)) if (isSingular(model)) { message("LME4: Singular fit detected for ", trait, ". Simplifying model.") showNotification(paste("Singular fit for", trait, ". Model simplified."), type = "warning", duration = 10) formula_str <- paste(trait, "~ Environment + Genotype + (1|Rep)") formula <- as.formula(formula_str) model <- lmer(formula, data = data, na.action = na.omit, control = lmerControl(check.rankX = "warn+drop.cols", optimizer = "bobyqa")) } message("LME4: Successfully fitted fixed model for ", trait) return(model) }, error = function(e) { message("LME4: Error fitting fixed model for ", trait, ": ", e$message) showNotification(paste("Fixed model fitting failed for", trait, ": ", e$message), type = "error", duration = 10) return(NULL) }) } # LME4: Fit random model for heritability lme4_fit_random_model <- function(data, trait) { message("LME4: Fitting random model for ", trait) formula_str <- if (input$lme4_include_interaction) { paste(trait, "~ Environment + (1|Genotype) + (1|Environment:Genotype) + (1|Block) + (1|Rep)") } else { paste(trait, "~ Environment + (1|Genotype) + (1|Block) + (1|Rep)") } formula <- as.formula(formula_str) tryCatch({ model <- lmer(formula, data = data, na.action = na.omit, control = lmerControl(check.rankX = "warn+drop.cols", optimizer = "bobyqa", checkSingularity = TRUE)) if (isSingular(model)) { message("LME4: Singular fit detected for ", trait, ". Simplifying model.") showNotification(paste("Singular fit for", trait, ". Model simplified."), type = "warning", duration = 10) formula_str <- paste(trait, "~ Environment + (1|Genotype) + (1|Rep)") formula <- as.formula(formula_str) model <- lmer(formula, data = data, na.action = na.omit, control = lmerControl(check.rankX = "warn+drop.cols", optimizer = "bobyqa")) } message("LME4: Successfully fitted random model for ", trait) return(model) }, error = function(e) { message("LME4: Error fitting random model for ", trait, ": ", e$message) showNotification(paste("Random model fitting failed for", trait, ": ", e$message), type = "error", duration = 10) return(NULL) }) } # LME4: Get BLUEs from fixed model lme4_get_blue <- function(model, trait) { if (is.null(model)) { message("LME4: No fixed model for ", trait) return(data.frame(Trait = trait, Genotype = NA, Environment = NA, predicted.value = NA, SE = NA)) } tryCatch({ emm_options(pbkrtest.limit = 10000, lmerTest.limit = 10000) blues <- emmeans(model, ~ Genotype:Environment) blues_df <- as.data.frame(blues) %>% rename(predicted.value = emmean) %>% mutate(Trait = trait) %>% select(Trait, Genotype, Environment, predicted.value, SE) %>% filter(!is.na(predicted.value)) if (nrow(blues_df) == 0) { return(data.frame(Trait = trait, Genotype = NA, Environment = NA, predicted.value = NA, SE = NA)) } return(blues_df) }, error = function(e) { message("LME4: Error in BLUEs for ", trait, ": ", e$message) return(data.frame(Trait = trait, Genotype = NA, Environment = NA, predicted.value = NA, SE = NA)) }) } # LME4: Get heritability from random model lme4_get_heritability <- function(model, trait) { if (is.null(model)) { message("LME4: No random model for ", trait) return(data.frame(Trait = trait, Heritability = NA, VarG = NA, VarGE = NA, VarRes = NA)) } tryCatch({ vc <- VarCorr(model) sigma_g <- as.numeric(vc$Genotype[1]) sigma_ge <- if (input$lme4_include_interaction && "Environment:Genotype" %in% names(vc)) as.numeric(vc$`Environment:Genotype`[1]) else 0 sigma_res <- sigma(model)^2 var_g_total <- sigma_g + sigma_ge total_var <- var_g_total + sigma_res h2 <- if (total_var > 0) var_g_total / total_var else NA data.frame(Trait = trait, Heritability = round(h2, 3), VarG = round(sigma_g, 3), VarGE = round(sigma_ge, 3), VarRes = round(sigma_res, 3)) }, error = function(e) { message("LME4: Error in heritability for ", trait, ": ", e$message) return(data.frame(Trait = trait, Heritability = NA, VarG = NA, VarGE = NA, VarRes = NA)) }) } # LME4: Finlay-Wilkinson stability analysis lme4_get_stability <- function(blues, trait) { tryCatch({ env_means <- blues %>% group_by(Environment) %>% summarise(Env_Mean = mean(predicted.value, na.rm = TRUE), .groups = "drop") stability_data <- blues %>% left_join(env_means, by = "Environment") %>% group_by(Genotype) %>% do({ model <- lm(predicted.value ~ Env_Mean, data = .) slope <- coef(model)[2] r_squared <- summary(model)$r.squared data.frame(Slope = round(slope, 3), R_Squared = round(r_squared, 3)) }) %>% mutate(Trait = trait) %>% select(Trait, Genotype, Slope, R_Squared) if (nrow(stability_data) == 0) { return(data.frame(Trait = trait, Genotype = NA, Slope = NA, R_Squared = NA)) } return(stability_data) }, error = function(e) { message("LME4: Error in stability analysis for ", trait, ": ", e$message) return(data.frame(Trait = trait, Genotype = NA, Slope = NA, R_Squared = NA)) }) } # LME4: PCA analysis lme4_get_pca <- function(blues, traits) { tryCatch({ wide_data <- blues %>% select(Trait, Genotype, Environment, predicted.value) %>% pivot_wider(names_from = Trait, values_from = predicted.value, values_fill = NA) %>% na.omit() if (nrow(wide_data) < 2 || ncol(wide_data) < length(traits) + 2) { return(list(scores = data.frame(Genotype = NA, Environment = NA, PC1 = NA, PC2 = NA), loadings = data.frame(Trait = NA, PC1 = NA, PC2 = NA))) } pca_data <- wide_data %>% select(all_of(traits)) pca_result <- prcomp(pca_data, scale. = TRUE) scores <- as.data.frame(pca_result$x) %>% mutate(Genotype = wide_data$Genotype, Environment = wide_data$Environment) %>% select(Genotype, Environment, PC1, PC2) loadings <- as.data.frame(pca_result$rotation) %>% mutate(Trait = rownames(.)) %>% select(Trait, PC1, PC2) var_explained <- summary(pca_result)$importance[2, c("PC1", "PC2")] * 100 return(list(scores = scores, loadings = loadings, var_explained = var_explained)) }, error = function(e) { message("LME4: Error in PCA analysis: ", e$message) return(list(scores = data.frame(Genotype = NA, Environment = NA, PC1 = NA, PC2 = NA), loadings = data.frame(Trait = NA, PC1 = NA, PC2 = NA))) }) } # LME4: File upload observer observeEvent(input$lme4_file, { req(input$lme4_file) message("LME4: File upload triggered: ", input$lme4_file$name) shinyjs::show("lme4_loader") on.exit(shinyjs::hide("lme4_loader")) result <- lme4_process_data(input$lme4_file$datapath) if (is.null(result)) { return() } rv_lme4$data <- result$data rv_lme4$traits <- result$traits rv_lme4$trait <- result$traits[1] updateSelectInput(session, "lme4_selected_trait", choices = rv_lme4$traits, selected = rv_lme4$traits[1]) shinyjs::show("lme4_data_stats") output$lme4_n_vars <- renderText({ ncol(rv_lme4$data) }) output$lme4_n_obs <- renderText({ nrow(rv_lme4$data) }) output$lme4_n_geno <- renderText({ length(unique(rv_lme4$data$Genotype)) }) output$lme4_n_env <- renderText({ length(unique(rv_lme4$data$Environment)) }) output$lme4_data_preview <- renderPrint({ str(rv_lme4$data) }) debug_log <- c() withProgress(message = 'LME4: Analyzing data', value = 0, { fixed_models <- list() random_models <- list() blues_list <- list() herit_list <- list() stability_list <- list() n_traits <- length(rv_lme4$traits) total_steps <- n_traits * 3 + 3 # fixed model, random model, stability, correlations, descriptives, pca step_increment <- 1 / total_steps for (trait in rv_lme4$traits) { incProgress(step_increment, detail = paste("Fitting fixed model for", trait)) fixed_model <- lme4_fit_fixed_model(rv_lme4$data, trait) fixed_models[[trait]] <- fixed_model debug_log <- c(debug_log, paste("Trait:", trait, "- Fixed model:", ifelse(is.null(fixed_model), "Failed", "Success"))) incProgress(step_increment, detail = paste("Calculating predicted means for", trait)) blues_list[[trait]] <- lme4_get_blue(fixed_model, trait) incProgress(step_increment, detail = paste("Fitting random model for", trait)) random_model <- lme4_fit_random_model(rv_lme4$data, trait) random_models[[trait]] <- random_model debug_log <- c(debug_log, paste("Trait:", trait, "- Random model:", ifelse(is.null(random_model), "Failed", "Success"))) herit_list[[trait]] <- lme4_get_heritability(random_model, trait) incProgress(step_increment, detail = paste("Calculating stability for", trait)) stability_list[[trait]] <- lme4_get_stability(blues_list[[trait]], trait) } incProgress(step_increment, detail = "Calculating correlations") if (n_traits > 1) { trait_data <- rv_lme4$data %>% select(all_of(rv_lme4$traits)) %>% na.omit() if (nrow(trait_data) > 0) { cor_matrix <- cor(trait_data, use = "pairwise.complete.obs") cor_table <- as.data.frame(as.table(cor_matrix)) %>% rename(Trait1 = Var1, Trait2 = Var2, Correlation = Freq) %>% mutate(Correlation = round(Correlation, 3)) rv_lme4$cor_matrix <- cor_matrix rv_lme4$cor_table <- cor_table debug_log <- c(debug_log, "Correlations: Success") } else { rv_lme4$cor_matrix <- matrix(NA, nrow = 1, ncol = 1, dimnames = list("NoData", "NoData")) rv_lme4$cor_table <- data.frame(Trait1 = "NoData", Trait2 = "NoData", Correlation = NA) debug_log <- c(debug_log, "Correlations: No valid data") } } else { rv_lme4$cor_matrix <- matrix(1, nrow = 1, ncol = 1, dimnames = list(rv_lme4$traits, rv_lme4$traits)) rv_lme4$cor_table <- data.frame(Trait1 = rv_lme4$traits, Trait2 = rv_lme4$traits, Correlation = 1) debug_log <- c(debug_log, "Correlations: Single trait") } incProgress(step_increment, detail = "Calculating descriptive statistics") descriptives <- rv_lme4$data %>% select(all_of(rv_lme4$traits)) %>% pivot_longer(cols = everything(), names_to = "Trait", values_to = "Value") %>% group_by(Trait) %>% summarise( Mean = mean(Value, na.rm = TRUE), SD = sd(Value, na.rm = TRUE), Min = min(Value, na.rm = TRUE), Max = max(Value, na.rm = TRUE), N = sum(!is.na(Value)), .groups = "drop" ) %>% mutate(CV = round((SD / Mean) * 100, 2)) rv_lme4$descriptives <- descriptives debug_log <- c(debug_log, "Descriptives: Success") incProgress(step_increment, detail = "Calculating heritability") rv_lme4$heritability <- bind_rows(herit_list) debug_log <- c(debug_log, "Heritability: Success") incProgress(step_increment, detail = "Calculating rankings") rv_lme4$blues_all <- bind_rows(blues_list) %>% filter(!is.na(predicted.value)) rankings <- rv_lme4$blues_all %>% group_by(Trait, Genotype) %>% summarise(Mean = mean(predicted.value, na.rm = TRUE), .groups = "drop") %>% group_by(Trait) %>% mutate(Rank = rank(-Mean, ties.method = "min")) %>% arrange(Trait, Rank) rv_lme4$rankings <- rankings debug_log <- c(debug_log, "Rankings: Success") incProgress(step_increment, detail = "Calculating stability") rv_lme4$stability <- bind_rows(stability_list) debug_log <- c(debug_log, "Stability: Success") incProgress(step_increment, detail = "Calculating PCA") rv_lme4$pca <- lme4_get_pca(rv_lme4$blues_all, rv_lme4$traits) debug_log <- c(debug_log, "PCA: Success") rv_lme4$fixed_models <- fixed_models rv_lme4$random_models <- random_models rv_lme4$debug_log <- debug_log shinyjs::hide(c("lme4_blues_placeholder", "lme4_correlations_placeholder", "lme4_descriptives_placeholder", "lme4_heritability_placeholder", "lme4_rankings_placeholder", "lme4_stability_placeholder", "lme4_pca_placeholder")) shinyjs::show(c("lme4_blues_content", "lme4_correlations_content", "lme4_descriptives_content", "lme4_heritability_content", "lme4_rankings_content", "lme4_stability_content", "lme4_pca_content")) output$lme4_debug_log <- renderPrint({ cat(paste(rv_lme4$debug_log, collapse = "\n")) }) showNotification("LME4: File uploaded and analyzed successfully", type = "message", duration = 5) }) }) # Update selected trait observe({ req(input$lme4_selected_trait) rv_lme4$trait <- input$lme4_selected_trait }) # LME4: Filtered reactives lme4_filtered_blues <- reactive({ req(rv_lme4$blues_all, rv_lme4$trait) rv_lme4$blues_all %>% filter(Trait == rv_lme4$trait, !is.na(predicted.value)) }) lme4_filtered_rankings <- reactive({ req(rv_lme4$rankings, rv_lme4$trait) rv_lme4$rankings %>% filter(Trait == rv_lme4$trait) }) lme4_filtered_stability <- reactive({ req(rv_lme4$stability, rv_lme4$trait) rv_lme4$stability %>% filter(Trait == rv_lme4$trait) }) # LME4: Plot outputs output$lme4_blues_plot <- renderPlotly({ req(lme4_filtered_blues()) data <- lme4_filtered_blues() if (nrow(data) == 0 || all(is.na(data$predicted.value))) { return(plot_ly() %>% layout( title = list(text = paste("No Valid Predicted Means for", rv_lme4$trait), font = PLOT_FONT), annotations = list( text = "No valid data for plotting predicted means.", x = 0.5, y = 0.5, xref = "paper", yref = "paper", showarrow = FALSE, font = list(size = 12, color = "#2D3748") ), PLOT_LAYOUT )) } plot_ly(data, x = ~Environment, y = ~predicted.value, color = ~Genotype, type = 'scatter', mode = 'lines+markers', marker = list(size = 8), line = list(width = 2), colors = PLOT_COLORS, text = ~paste("Genotype:", Genotype, "
Value:", round(predicted.value, 2)), hoverinfo = "text") %>% layout( title = list(text = paste("Predicted Means (BLUEs) for", rv_lme4$trait), font = list(size = 18, family = "Poppins", color = "#2D3748")), xaxis = list(title = "Environment", tickangle = 45, titlefont = PLOT_FONT, tickfont = PLOT_FONT), yaxis = list(title = "Predicted Value", titlefont = PLOT_FONT, tickfont = PLOT_FONT), PLOT_LAYOUT, hoverlabel = list(bgcolor = "white", font = PLOT_FONT) ) }) output$lme4_correlation_plot <- renderPlotly({ req(rv_lme4$cor_matrix) if (ncol(rv_lme4$cor_matrix) < 2 || all(is.na(rv_lme4$cor_matrix))) { return(plot_ly() %>% layout( title = list(text = "No Valid Correlation Data", font = PLOT_FONT), annotations = list( text = "Correlation plot requires at least two valid traits.", x = 0.5, y = 0.5, xref = "paper", yref = "paper", showarrow = FALSE, font = list(size = 12, color = "#2D3748") ), PLOT_LAYOUT )) } plot_ly( x = colnames(rv_lme4$cor_matrix), y = rownames(rv_lme4$cor_matrix), z = rv_lme4$cor_matrix, type = "heatmap", colorscale = list(c(-1, 0, 1), c("#FFB6C1", "white", "#B5EAD7")), showscale = TRUE, colorbar = list(title = "Correlation", titlefont = PLOT_FONT, tickfont = PLOT_FONT), text = round(rv_lme4$cor_matrix, 2), hoverinfo = "x+y+z" ) %>% layout( title = list(text = "Trait Correlation Matrix", font = list(size = 18, family = "Poppins", color = "#2D3748")), xaxis = list(title = "", tickangle = 45, titlefont = PLOT_FONT, tickfont = PLOT_FONT), yaxis = list(title = "", titlefont = PLOT_FONT, tickfont = PLOT_FONT), PLOT_LAYOUT, hoverlabel = list(bgcolor = "white", font = PLOT_FONT) ) }) output$lme4_descriptives_plot <- renderPlotly({ req(rv_lme4$data, rv_lme4$trait) trait_data <- rv_lme4$data[[rv_lme4$trait]] if (all(is.na(trait_data)) || length(unique(rv_lme4$data$Environment)) < 2) { return(plot_ly() %>% layout( title = list(text = paste("No Valid Data for", rv_lme4$trait), font = PLOT_FONT), annotations = list( text = "No valid data for boxplot.", x = 0.5, y = 0.5, xref = "paper", yref = "paper", showarrow = FALSE, font = list(size = 12, color = "#2D3748") ), PLOT_LAYOUT )) } plot_ly(rv_lme4$data, x = ~Environment, y = rv_lme4$data[[rv_lme4$trait]], type = 'box', color = ~Environment, colors = PLOT_COLORS, hoverinfo = "y+name") %>% layout( title = list(text = paste("Distribution of", rv_lme4$trait, "by Environment"), font = list(size = 18, family = "Poppins", color = "#2D3748")), xaxis = list(title = "Environment", titlefont = PLOT_FONT, tickfont = PLOT_FONT), yaxis = list(title = paste(rv_lme4$trait, "Value"), titlefont = PLOT_FONT, tickfont = PLOT_FONT), PLOT_LAYOUT, hoverlabel = list(bgcolor = "white", font = PLOT_FONT) ) }) output$lme4_rankings_plot <- renderPlotly({ req(lme4_filtered_rankings()) data <- lme4_filtered_rankings() %>% head(10) if (nrow(data) == 0) { return(plot_ly() %>% layout( title = list(text = paste("No Rankings for", rv_lme4$trait), font = PLOT_FONT), annotations = list( text = "No valid data for plotting rankings.", x = 0.5, y = 0.5, xref = "paper", yref = "paper", showarrow = FALSE, font = list(size = 12, color = "#2D3748") ), PLOT_LAYOUT )) } plot_ly(data, x = ~reorder(Genotype, -Mean), y = ~Mean, type = 'bar', marker = list(color = PLOT_COLORS[1:length(unique(data$Genotype))]), text = ~paste("Genotype:", Genotype, "
Mean:", round(Mean, 2), "
Rank:", Rank), hoverinfo = "text") %>% layout( title = list(text = paste("Top Genotypes for", rv_lme4$trait), font = list(size = 18, family = "Poppins", color = "#2D3748")), xaxis = list(title = "Genotype", tickangle = 45, titlefont = PLOT_FONT, tickfont = PLOT_FONT), yaxis = list(title = "Mean Predicted Value", titlefont = PLOT_FONT, tickfont = PLOT_FONT), PLOT_LAYOUT, hoverlabel = list(bgcolor = "white", font = PLOT_FONT) ) }) output$lme4_stability_plot <- renderPlotly({ req(lme4_filtered_stability()) data <- lme4_filtered_stability() if (nrow(data) == 0 || all(is.na(data$Slope))) { return(plot_ly() %>% layout( title = list(text = paste("No Stability Data for", rv_lme4$trait), font = PLOT_FONT), annotations = list( text = "No valid data for plotting stability.", x = 0.5, y = 0.5, xref = "paper", yref = "paper", showarrow = FALSE, font = list(size = 12, color = "#2D3748") ), PLOT_LAYOUT )) } plot_ly(data, x = ~Slope, y = ~R_Squared, type = 'scatter', mode = 'markers', text = ~paste("Genotype:", Genotype, "
Slope:", round(Slope, 2), "
R²:", round(R_Squared, 2)), hoverinfo = "text", marker = list(size = 10, color = PLOT_COLORS[1])) %>% layout( title = list(text = paste("Stability Analysis for", rv_lme4$trait), font = list(size = 18, family = "Poppins", color = "#2D3748")), xaxis = list(title = "Stability Slope", titlefont = PLOT_FONT, tickfont = PLOT_FONT), yaxis = list(title = "R²", titlefont = PLOT_FONT, tickfont = PLOT_FONT), PLOT_LAYOUT, hoverlabel = list(bgcolor = "white", font = PLOT_FONT) ) }) output$lme4_pca_plot <- renderPlotly({ req(rv_lme4$pca) scores <- rv_lme4$pca$scores var_explained <- rv_lme4$pca$var_explained if (nrow(scores) == 0 || all(is.na(scores$PC1))) { return(plot_ly() %>% layout( title = list(text = "No PCA Data", font = PLOT_FONT), annotations = list( text = "No valid data for PCA plot.", x = 0.5, y = 0.5, xref = "paper", yref = "paper", showarrow = FALSE, font = list(size = 12, color = "#2D3748") ), PLOT_LAYOUT )) } plot_ly(scores, x = ~PC1, y = ~PC2, type = 'scatter', mode = 'markers', text = ~paste("Genotype:", Genotype, "
Environment:", Environment), hoverinfo = "text", marker = list(size = 10, color = PLOT_COLORS[1])) %>% layout( title = list(text = sprintf("PCA Biplot (PC1: %.1f%%, PC2: %.1f%%)", var_explained[1], var_explained[2]), font = list(size = 18, family = "Poppins", color = "#2D3748")), xaxis = list(title = "PC1", titlefont = PLOT_FONT, tickfont = PLOT_FONT), yaxis = list(title = "PC2", titlefont = PLOT_FONT, tickfont = PLOT_FONT), PLOT_LAYOUT, hoverlabel = list(bgcolor = "white", font = PLOT_FONT) ) }) # LME4: Table outputs output$lme4_blues_table <- renderDT({ req(lme4_filtered_blues()) data <- lme4_filtered_blues() if ("Error" %in% colnames(data)) { data <- data %>% select(-Error) } datatable( data, extensions = 'Buttons', options = list( scrollX = TRUE, dom = 'Bfrtip', buttons = c('copy', 'excel', 'pdf', 'print'), pageLength = 10, columnDefs = list(list(className = 'dt-center', targets = '_all')) ), caption = paste("Predicted Means (BLUEs) for", rv_lme4$trait) ) %>% formatRound(columns = c("predicted.value", "SE"), digits = 3) }) output$lme4_cor_table <- renderDT({ req(rv_lme4$cor_table) datatable( rv_lme4$cor_table, extensions = 'Buttons', options = list( scrollX = TRUE, dom = 'Bfrtip', buttons = c('copy', 'excel', 'pdf', 'print'), pageLength = 10, columnDefs = list(list(className = 'dt-center', targets = '_all')) ), caption = "Correlation Between Traits" ) %>% formatRound(columns = "Correlation", digits = 3) }) output$lme4_descriptives_table <- renderDT({ req(rv_lme4$descriptives) datatable( rv_lme4$descriptives, extensions = 'Buttons', options = list( scrollX = TRUE, dom = 'Bfrtip', buttons = c('copy', 'excel', 'pdf', 'print'), pageLength = 10, columnDefs = list(list(className = 'dt-center', targets = c(2:6))) ), caption = "Descriptive Statistics for Traits" ) %>% formatRound(columns = c("Mean", "SD", "Min", "Max", "CV"), digits = 2) }) output$lme4_heritability_table <- renderDT({ req(rv_lme4$heritability) datatable( rv_lme4$heritability, extensions = 'Buttons', options = list( scrollX = TRUE, dom = 'Bfrtip', buttons = c('copy', 'excel', 'pdf', 'print'), pageLength = 10, columnDefs = list(list(className = 'dt-center', targets = c(2:5))) ), caption = "Broad-Sense Heritability Estimates" ) %>% formatRound(columns = c("Heritability", "VarG", "VarGE", "VarRes"), digits = 3) }) output$lme4_rankings_table <- renderDT({ req(lme4_filtered_rankings()) datatable( lme4_filtered_rankings(), extensions = 'Buttons', options = list( scrollX = TRUE, dom = 'Bfrtip', buttons = c('copy', 'excel', 'pdf', 'print'), pageLength = 10, columnDefs = list(list(className = 'dt-center', targets = c(3,4))) ), caption = paste("Genotype Rankings for", rv_lme4$trait) ) %>% formatRound(columns = "Mean", digits = 3) }) output$lme4_stability_table <- renderDT({ req(lme4_filtered_stability()) datatable( lme4_filtered_stability(), extensions = 'Buttons', options = list( scrollX = TRUE, dom = 'Bfrtip', buttons = c('copy', 'excel', 'pdf', 'print'), pageLength = 10, columnDefs = list(list(className = 'dt-center', targets = c(3,4))) ), caption = paste("Stability Analysis for", rv_lme4$trait) ) %>% formatRound(columns = c("Slope", "R_Squared"), digits = 3) }) output$lme4_pca_table <- renderDT({ req(rv_lme4$pca) datatable( rv_lme4$pca$loadings, extensions = 'Buttons', options = list( scrollX = TRUE, dom = 'Bfrtip', buttons = c('copy', 'excel', 'pdf', 'print'), pageLength = 10, columnDefs = list(list(className = 'dt-center', targets = c(2,3))) ), caption = "PCA Loadings" ) %>% formatRound(columns = c("PC1", "PC2"), digits = 3) }) # LME4: Insights outputs output$lme4_descriptives_insights <- renderUI({ req(rv_lme4$descriptives) desc <- rv_lme4$descriptives %>% filter(Trait == rv_lme4$trait) if (nrow(desc) == 0) return(NULL) cv <- desc$CV[1] insight <- if (cv > 20) { "High variability (CV > 20%) suggests environmental influence or measurement error. Consider increasing replicates or refining phenotyping." } else if (cv > 10) { "Moderate variability (CV 10-20%) indicates some environmental influence. Genotype selection for stability may be effective." } else { "Low variability (CV < 10%) indicates high precision. Suitable for reliable genetic selection." } HTML(sprintf("Insight for %s: %s", rv_lme4$trait, insight)) }) output$lme4_blues_insights <- renderUI({ req(lme4_filtered_blues()) data <- lme4_filtered_blues() if (nrow(data) == 0) return(NULL) var_by_geno <- data %>% group_by(Genotype) %>% summarise(Var = var(predicted.value, na.rm = TRUE), .groups = "drop") %>% arrange(Var) stable_geno <- var_by_geno$Genotype[1] insight <- sprintf("Genotype %s shows the lowest variance across environments, indicating high stability.", stable_geno) HTML(sprintf("Insight for %s: %s", rv_lme4$trait, insight)) }) output$lme4_correlations_insights <- renderUI({ req(rv_lme4$cor_table) strong_cor <- rv_lme4$cor_table %>% filter(abs(Correlation) > 0.7, Trait1 != Trait2) %>% slice_head(n = 1) if (nrow(strong_cor) > 0) { insight <- sprintf("Strong correlation (r = %.3f) between %s and %s suggests potential for indirect selection.", strong_cor$Correlation, strong_cor$Trait1, strong_cor$Trait2) } else { insight <- "No strong correlations (|r| > 0.7) detected. Direct selection for each trait is recommended." } HTML(sprintf("Insight: %s", insight)) }) output$lme4_heritability_insights <- renderUI({ req(rv_lme4$heritability) h2 <- rv_lme4$heritability %>% filter(Trait == rv_lme4$trait) if (nrow(h2) == 0 || is.na(h2$Heritability)) return(NULL) insight <- if (h2$Heritability > 0.6) { sprintf("High heritability (H² = %.3f) for %s; effective for genetic selection.", h2$Heritability, rv_lme4$trait) } else if (h2$Heritability > 0.3) { sprintf("Moderate heritability (H² = %.3f) for %s; selection may be effective but consider environmental factors.", h2$Heritability, rv_lme4$trait) } else { sprintf("Low heritability (H² = %.3f) for %s; environmental optimization or more precise phenotyping needed.", h2$Heritability, rv_lme4$trait) } HTML(sprintf("Insight for %s: %s", rv_lme4$trait, insight)) }) output$lme4_rankings_insights <- renderUI({ req(lme4_filtered_rankings()) top_geno <- lme4_filtered_rankings() %>% filter(Rank == 1) %>% slice_head(n = 1) if (nrow(top_geno) == 0) return(NULL) insight <- sprintf("Genotype %s ranks first for %s with mean value %.3f.", top_geno$Genotype, rv_lme4$trait, top_geno$Mean) HTML(sprintf("Insight for %s: %s", rv_lme4$trait, insight)) }) output$lme4_stability_insights <- renderUI({ req(lme4_filtered_stability()) stab <- lme4_filtered_stability() stable_geno <- stab %>% filter(abs(Slope - 1) < 0.2, R_Squared > 0.8) %>% slice_head(n = 1) if (nrow(stable_geno) > 0) { insight <- sprintf("Genotype %s has high stability (slope = %.3f, R² = %.3f) for %s.", stable_geno$Genotype, stable_geno$Slope, stable_geno$R_Squared, rv_lme4$trait) } else { insight <- sprintf("No highly stable genotypes (slope ~ 1, R² > 0.8) for %s.", rv_lme4$trait) } HTML(sprintf("Insight for %s: %s", rv_lme4$trait, insight)) }) output$lme4_pca_insights <- renderUI({ req(rv_lme4$pca) loadings <- rv_lme4$pca$loadings var_explained <- rv_lme4$pca$var_explained if (nrow(loadings) == 0 || all(is.na(loadings$PC1))) return(NULL) top_trait_pc1 <- loadings %>% arrange(-abs(PC1)) %>% slice_head(n = 1) insight <- sprintf("PC1 (%.1f%% variance) is driven by %s (loading = %.3f).", var_explained[1], top_trait_pc1$Trait, top_trait_pc1$PC1) HTML(sprintf("Insight: %s", insight)) }) } # Run the Shiny app shinyApp(ui, server)