library(shiny) library(shinyjs) library(tidyverse) library(DT) library(readxl) library(lme4) library(emmeans) library(plotly) library(shinyWidgets) library(ggplot2) # UI with updated styling ui <- fluidPage( useShinyjs(), tags$head( tags$meta(charset = "UTF-8"), tags$title("Combined 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); } .insights { margin-top: 20px; padding: 20px; background: #F5F5F5; border-radius: 8px; border-left: 4px solid var(--secondary); } .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; } .nav-tabs { border-bottom: 2px solid var(--primary); margin-bottom: 20px; } .nav-tabs .nav-item { margin-bottom: -2px; } .nav-tabs .nav-link { color: var(--light); /* Grey text for tabs */ background: #F5F5F5; border: 1px solid transparent; border-radius: 8px 8px 0 0; margin-right: 5px; padding: 12px 20px; transition: all 0.3s; } .nav-tabs .nav-link:hover { color: var(--light); background: var(--primary); /* Dark blue on hover */ border: 1px solid var(--primary); } .nav-tabs .nav-link.active { color: var(--light); /* Grey text for active tab */ background: var(--primary); /* Dark blue for active tab */ border: 1px solid var(--primary); font-weight: bold; } .nav-tabs .nav-link i { margin-right: 8px; } .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; } ")) ), tabsetPanel( id = "main_tabs", type = "tabs", tabPanel( icon("seedling"), "Preprocessing data", div( class = "section", h1("🌱 Preprocessing", class = "text-4xl font-extrabold tracking-tight"), div( class = "upload-container", div(class = "upload-icon", icon("cloud-upload-alt", class = "fas")), h3("📤 Upload Dataset (Excel)", style = "color: var(--primary);"), p("or", style = "margin: 10px 0;"), fileInput("pheno_file", NULL, accept = ".xlsx", buttonLabel = "Browse Files", placeholder = "No file selected"), p("📝 Supported format: .xlsx", style = "color: var(--light); font-size: 14px;"), div(id = "pheno_loader", class = "loader hidden") ), radioButtons("pheno_plotType", "📊 Select Plot Type", choices = c("2D Bar" = "2d", "3D Bar" = "3d"), selected = "2d", width = "100%"), actionButton("pheno_process", "🔍 Analyze Data", class = "btn-primary w-full"), tabsetPanel( tabPanel( icon("search"), "Missing Data Analysis", div( class = "section", h3("🔍 Missing Data Patterns by Environment & Trait", class = "text-2xl font-bold mb-6"), div(class = "chart-container", plotlyOutput("pheno_missingPlot")) ) ), tabPanel( icon("filter"), "Filtered Data Insights", div( class = "section", h3("✅ Post-Filtering Missing Data Patterns", class = "text-2xl font-bold mb-6"), div(class = "chart-container", plotlyOutput("pheno_filteredMissingPlot")) ) ), tabPanel( icon("table"), "Statistical Summary", div( class = "section", h3("📈 Environment-Wise Descriptive Statistics", class = "text-2xl font-bold mb-6"), DTOutput("pheno_statsTable"), downloadButton("pheno_downloadStats", "📥 Export Stats as CSV", class = "btn-primary mt-6") ) ) ) ) ), tabPanel( icon("calculator"), "Phenotypic data analysis", 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", 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-blues", role = "tab", icon("chart-bar", class = "fas"), "📈 Predicted Means"), tags$a(class = "nav-link", `data-toggle` = "pill", href = "#lme4-heritability", role = "tab", icon("dna", class = "fas"), "🧬 Heritability"), 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-stability", role = "tab", icon("balance-scale", class = "fas"), "⚖️ Stability 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.0"), 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-blues", role = "tabpanel", div( class = "section", h2("📈 Predicted Means (BLUEs)"), div( id = "lme4_blues_content", div(class = "chart-container", plotlyOutput("lme4_blues_plot")), div(class = "table-container", DTOutput("lme4_blues_table")), div( class = "insights", h4("💡 Interpretation"), 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.") ) ), 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-heritability", role = "tabpanel", div( class = "section", h2("🧬 Heritability"), div( id = "lme4_heritability_content", div(class = "chart-container", plotlyOutput("lme4_heritability_plot")), div(class = "table-container", DTOutput("lme4_heritability_table")), div( class = "insights", h4("💡 Interpretation"), 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.") ) ), div( id = "lme4_heritability_placeholder", class = "text-center", icon("dna", class = "fas", style = "font-size: 72px; color: var(--light); margin: 30px 0;"), h4("📤 Upload data to see heritability analysis", 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")), div(class = "table-container", DTOutput("lme4_cor_table")), div( class = "insights", h4("💡 Interpretation"), 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.") ) ), 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-stability", role = "tabpanel", div( class = "section", h2("⚖️ Stability Analysis"), div( id = "lme4_stability_content", div(class = "chart-container", plotlyOutput("lme4_stability_plot")), div(class = "table-container", DTOutput("lme4_stability_table")), div( class = "insights", h4("💡 Interpretation"), 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.") ) ), 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);") ) ) ) ) ) ) ) ) ) # Server function (unchanged from previous) server <- function(input, output, session) { # Phenotypic Analysis Reactive Values rv_pheno <- reactiveValues( data = NULL, processed_data = NULL, missing_data = NULL, missing_20 = NULL, filtered_missing_data = NULL, summary_traits = NULL ) # LME4 Analysis Reactive Values rv_lme4 <- reactiveValues( data = NULL, traits = NULL, trait = NULL, lme4_models = NULL, blues_all = NULL, heritability_table = NULL, cor_matrix = NULL, cor_table = NULL, stability_table = NULL, debug_log = NULL ) # Phenotypic: Process data pheno_process_data <- function(path) { message("Pheno: Reading Excel file: ", path) input_data <- read_excel(path) input_data$Genotype <- as.factor(input_data$Genotype) input_data$Block <- as.factor(input_data$Block) input_data$Row <- as.factor(input_data$Row) input_data$Rep <- as.factor(input_data$Rep) input_data$Column <- as.factor(input_data$Column) input_data$Environment <- as.factor(input_data$Environment) input_data$Environment <- factor(input_data$Environment, levels = unique(input_data$Environment)) trait_cols <- colnames(input_data)[10:ncol(input_data)] data_missing <- input_data %>% group_by(Environment) %>% summarise(across(all_of(trait_cols), ~ sum(is.na(.)) / length(.))) data_missing_long <- data_missing %>% pivot_longer(cols = all_of(trait_cols), names_to = "Trait", values_to = "value") missing_20_df <- data_missing_long %>% filter(value > 0.20) bad_env <- unique(missing_20_df$Environment) filtered_data <- input_data %>% filter(!(Environment %in% bad_env)) %>% droplevels() filtered_missing <- filtered_data %>% group_by(Environment) %>% summarise(across(all_of(trait_cols), ~ sum(is.na(.)) / length(.))) filtered_missing_long <- filtered_missing %>% pivot_longer(cols = all_of(trait_cols), names_to = "Trait", values_to = "value") summary_traits_df <- filtered_data %>% group_by(Environment) %>% summarise(across( all_of(trait_cols), list( mean = ~ mean(.x, na.rm = TRUE), median = ~ median(.x, na.rm = TRUE), sd = ~ sd(.x, na.rm = TRUE), min = ~ min(.x, na.rm = TRUE), max = ~ max(.x, na.rm = TRUE), cv = ~ (sd(.x, na.rm = TRUE) / mean(.x, na.rm = TRUE)) * 100 ), .names = "{.col}_{.fn}" )) %>% mutate(across(where(is.numeric), ~ round(.x, 2))) summary_long <- summary_traits_df %>% pivot_longer(cols = -Environment, names_to = c("Trait", "Stat"), names_sep = "_", values_to = "value") %>% pivot_wider(names_from = "Stat", values_from = "value") return(list( data = input_data, processed_data = filtered_data, missing_data = data_missing_long, missing_20 = missing_20_df, filtered_missing_data = filtered_missing_long, summary_traits = summary_long )) } # Phenotypic: File upload and process observer observeEvent(input$pheno_process, { req(input$pheno_file) message("Pheno: File upload triggered: ", input$pheno_file$name) shinyjs::show("pheno_loader") on.exit(shinyjs::hide("pheno_loader")) tryCatch({ result <- pheno_process_data(input$pheno_file$datapath) rv_pheno$data <- result$data rv_pheno$processed_data <- result$processed_data rv_pheno$missing_data <- result$missing_data rv_pheno$missing_20 <- result$missing_20 rv_pheno$filtered_missing_data <- result$filtered_missing_data rv_pheno$summary_traits <- result$summary_traits showNotification("Pheno: File uploaded and analyzed successfully", type = "message", duration = 5) }, error = function(e) { message("Pheno: Error in file processing: ", e$message) showNotification(paste("Pheno Error:", e$message), type = "error", duration = 10) }) }) # Phenotypic: Plot outputs output$pheno_missingPlot <- renderPlotly({ req(rv_pheno$missing_data) if (input$pheno_plotType == "2d") { p <- ggplot(rv_pheno$missing_data, aes(x = Environment, y = value, fill = Trait)) + geom_bar(stat = "identity", position = "dodge", alpha = 0.85) + labs(y = "Proportion of Missing Data", x = "Environment") + theme_minimal() + scale_fill_manual(values = c("#FFB6C1", "#FFDAB9", "#B5EAD7", "#E6E6FA", "#FFFACD", "#FF9999")) + theme( axis.text.x = element_text(angle = 30, hjust = 1, size = 12, color = "#2D3748"), axis.text.y = element_text(size = 12, color = "#2D3748"), axis.title.x = element_text(size = 14, color = "#2D3748", face = "bold", margin = margin(t = 12)), axis.title.y = element_text(size = 14, color = "#2D3748", face = "bold", margin = margin(r = 12)), legend.position = "top", legend.title = element_text(size = 12, face = "bold", color = "#2D3748"), legend.text = element_text(size = 10, color = "#2D3748"), panel.grid.major = element_line(color = "#e5e7eb", size = 0.4), panel.grid.minor = element_blank(), panel.background = element_rect(fill = "#F9FAFB"), plot.background = element_rect(fill = "transparent") ) + facet_wrap(~Trait, ncol = 2, scales = "free_y") ggplotly(p) %>% layout( plot_bgcolor = "transparent", paper_bgcolor = "transparent", margin = list(l = 70, r = 70, t = 70, b = 140), font = list(family = "Poppins", size = 12, color = "#2D3748"), showlegend = TRUE ) } else { plot_ly( data = rv_pheno$missing_data, x = ~Environment, y = ~Trait, z = ~value, type = "histogram2dcontour", histfunc = "sum", colorscale = list( c(0, 0.5, 1), c("#FFB6C1", "#FFDAB9", "#B5EAD7") ), showscale = TRUE, colorbar = list(title = "Missing Proportion") ) %>% layout( scene = list( xaxis = list(title = "Environment", tickangle = 45), yaxis = list(title = "Trait"), zaxis = list(title = "Proportion"), camera = list( eye = list(x = 2, y = 2, z = 0.5), up = list(x = 0, y = 0, z = 1) ) ), plot_bgcolor = "transparent", paper_bgcolor = "transparent", margin = list(l = 70, r = 70, t = 70, b = 140), font = list(family = "Poppins", size = 12, color = "#2D3748"), showlegend = FALSE ) } }) output$pheno_filteredMissingPlot <- renderPlotly({ req(rv_pheno$filtered_missing_data) if (input$pheno_plotType == "2d") { p <- ggplot(rv_pheno$filtered_missing_data, aes(x = Environment, y = value, fill = Trait)) + geom_bar(stat = "identity", position = "dodge", alpha = 0.85) + labs(y = "Proportion of Missing Data (Filtered)", x = "Environment") + theme_minimal() + scale_fill_manual(values = c("#FFB6C1", "#FFDAB9", "#B5EAD7", "#E6E6FA", "#FFFACD", "#FF9999")) + theme( axis.text.x = element_text(angle = 30, hjust = 1, size = 12, color = "#2D3748"), axis.text.y = element_text(size = 12, color = "#2D3748"), axis.title.x = element_text(size = 14, color = "#2D3748", face = "bold", margin = margin(t = 12)), axis.title.y = element_text(size = 14, color = "#2D3748", face = "bold", margin = margin(r = 12)), legend.position = "top", legend.title = element_text(size = 12, face = "bold", color = "#2D3748"), legend.text = element_text(size = 10, color = "#2D3748"), panel.grid.major = element_line(color = "#e5e7eb", size = 0.4), panel.grid.minor = element_blank(), panel.background = element_rect(fill = "#F9FAFB"), plot.background = element_rect(fill = "transparent") ) + facet_wrap(~Trait, ncol = 2, scales = "free_y") ggplotly(p) %>% layout( plot_bgcolor = "transparent", paper_bgcolor = "transparent", margin = list(l = 70, r = 70, t = 70, b = 140), font = list(family = "Poppins", size = 12, color = "#2D3748"), showlegend = TRUE ) } else { plot_ly( data = rv_pheno$filtered_missing_data, x = ~Environment, y = ~Trait, z = ~value, type = "histogram2dcontour", histfunc = "sum", colorscale = list( c(0, 0.5, 1), c("#FFB6C1", "#FFDAB9", "#B5EAD7") ), showscale = TRUE, colorbar = list(title = "Missing Proportion") ) %>% layout( scene = list( xaxis = list(title = "Environment", tickangle = 45), yaxis = list(title = "Trait"), zaxis = list(title = "Proportion"), camera = list( eye = list(x = 2, y = 2, z = 0.5), up = list(x = 0, y = 0, z = 1) ) ), plot_bgcolor = "transparent", paper_bgcolor = "transparent", margin = list(l = 70, r = 70, t = 70, b = 140), font = list(family = "Poppins", size = 12, color = "#2D3748"), showlegend = FALSE ) } }) # Phenotypic: Table outputs output$pheno_statsTable <- renderDT({ req(rv_pheno$summary_traits) datatable( rv_pheno$summary_traits, options = list( pageLength = 10, scrollX = TRUE, dom = 'Bfrtip', buttons = c('copy', 'csv', 'excel', 'pdf', 'print'), columnDefs = list(list(className = 'dt-center', targets = '_all')) ), extensions = 'Buttons', class = 'cell-border stripe', caption = "Environment-Wise Descriptive Statistics" ) }) output$pheno_downloadStats <- downloadHandler( filename = function() { "descriptive_stats.csv" }, content = function(file) { write.csv(rv_pheno$summary_traits, file, row.names = FALSE) } ) # LME4: Process data lme4_process_data <- function(path) { message("LME4: Reading Excel file: ", path) data <- read_excel(path) 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") } 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") } if (zero_combinations > (nrow(combo_counts) * ncol(combo_counts) * 0.5)) { message("LME4: Warning: Over 50% of Environment:Genotype combinations are missing, model fitting may fail") } 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() } n_genotypes <- length(unique(data$Genotype)) n_environments <- length(unique(data$Environment)) n_reps <- length(unique(data$Rep)) n_blocks <- length(unique(data$Block)) message("LME4: Data summary: ", "Rows: ", nrow(data), ", ", "Genotypes: ", n_genotypes, ", ", "Environments: ", n_environments, ", ", "Reps: ", n_reps, ", ", "Blocks: ", n_blocks, ", ", "Numeric traits: ", length(numeric_cols), " (", paste(numeric_cols, collapse = ", "), ")") if (n_genotypes < 2 || n_environments < 2) { stop("Insufficient genotypes (", n_genotypes, ") or environments (", n_environments, ") for LME4 analysis") } return(list(data = data, traits = numeric_cols)) } # LME4: Fit model lme4_fit_model <- function(data, trait) { message("LME4: Fitting lme4 model for trait: ", trait) formula_str <- if (input$lme4_include_interaction) { paste(trait, "~ Environment + Genotype + Environment:Genotype + (1|Block) + (1|Row) + (1|Column) + (1|Rep)") } else { paste(trait, "~ Environment + Genotype + (1|Block) + (1|Row) + (1|Column) + (1|Rep)") } formula <- as.formula(formula_str) model <- NULL tryCatch({ model <- lmer(formula, data = data, na.action = na.omit, control = lmerControl(check.rankX = "warn+drop.cols")) message("LME4: Successfully fitted model for ", trait) return(model) }, error = function(e) { message("LME4: Failed to fit model for ", trait, ": ", e$message) showNotification(paste("LME4: Failed to fit model for ", trait, ": ", e$message), type = "error", duration = 10) return(NULL) }, warning = function(w) { message("LME4: Warning in model fitting for ", trait, ": ", w$message) showNotification(paste("LME4: Warning for ", trait, ": ", w$message), type = "warning", duration = 10) return(model) }) } # LME4: Get BLUEs lme4_get_blue <- function(model, trait) { if (is.null(model)) { message("LME4: No model for ", trait, ", returning dummy BLUEs") return(data.frame(Trait = trait, Genotype = NA, Environment = NA, predicted.value = NA)) } tryCatch({ emm_options(pbkrtest.limit = 5000, lmerTest.limit = 5000) blues <- emmeans(model, ~ Genotype:Environment) blues_df <- as.data.frame(blues) %>% rename(predicted.value = emmean) %>% mutate(Trait = trait) %>% select(Trait, Genotype, Environment, predicted.value) 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)) }) } # LME4: Calculate heritability lme4_calculate_heritability <- function(model, trait) { message("LME4: Calculating heritability for trait: ", trait) if (is.null(model)) { message("LME4: No model for ", trait, ", returning dummy heritability") return(data.frame(Trait = trait, Heritability = NA, Error = "No model fitted")) } tryCatch({ varcomp <- as.data.frame(VarCorr(model)) vg <- varcomp$vcov[varcomp$grp == "Genotype"] if (length(vg) == 0 || is.na(vg) || vg <= 0) { message("LME4: Invalid or zero genetic variance for ", trait) return(data.frame(Trait = trait, Heritability = NA, Error = "Invalid genetic variance")) } ve <- sigma(model)^2 if (is.na(ve) || ve <= 0) { message("LME4: Invalid or zero residual variance for ", trait) return(data.frame(Trait = trait, Heritability = NA, Error = "Invalid residual variance")) } h2 <- vg / (vg + ve) if (h2 < 0 || h2 > 1) { message("LME4: Heritability out of bounds for ", trait, ": ", h2) return(data.frame(Trait = trait, Heritability = NA, Error = "Heritability out of bounds")) } return(data.frame(Trait = trait, Heritability = round(h2, 3), Error = NA)) }, error = function(e) { message("LME4: Failed to calculate heritability for ", trait, ": ", e$message) return(data.frame(Trait = trait, Heritability = NA, Error = e$message)) }, warning = function(w) { message("LME4: Warning in heritability calculation for ", trait, ": ", w$message) return(data.frame(Trait = trait, Heritability = NA, Error = w$message)) }) } # LME4: Finlay-Wilkinson stability lme4_finlay_wilkinson <- function(blues, trait) { blues_trait <- blues %>% filter(Trait == trait, !is.na(predicted.value)) if (nrow(blues_trait) < 4) { message("LME4: Insufficient valid BLUEs for ", trait, " (", nrow(blues_trait), " rows)") return(data.frame(Genotype = NA, Slope = NA, R2 = NA, Trait = trait, Error = "Insufficient data")) } env_means <- blues_trait %>% group_by(Environment) %>% summarize(mean_value = mean(predicted.value, na.rm = TRUE)) blues_trait <- blues_trait %>% left_join(env_means, by = "Environment") if (nrow(blues_trait) == 0 || all(is.na(blues_trait$mean_value))) { message("LME4: No valid environment means for ", trait) return(data.frame(Genotype = NA, Slope = NA, R2 = NA, Trait = trait, Error = "No valid environment means")) } stability <- blues_trait %>% group_by(Genotype) %>% do({ data_subset <- . model <- tryCatch({ lm(predicted.value ~ mean_value, data = data_subset) }, error = function(e) { NULL }) if (is.null(model) || nrow(data_subset) < 2) { data.frame(Slope = NA, R2 = NA, Error = "Model fitting failed or insufficient data") } else { data.frame( Slope = coef(model)[2], R2 = summary(model)$r.squared, Error = NA ) } }) %>% mutate(Trait = trait) return(stability) } # 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")) tryCatch({ result <- lme4_process_data(input$lme4_file$datapath) rv_lme4$data <- result$data rv_lme4$traits <- result$traits rv_lme4$trait <- result$traits[1] message("LME4: Data processed, rows: ", nrow(rv_lme4$data), ", traits: ", paste(rv_lme4$traits, collapse = ", ")) 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) message("LME4: Trait columns selected: ", paste(names(rv_lme4$data)[9:ncol(rv_lme4$data)], collapse = ", ")) }) debug_log <- c() withProgress(message = 'LME4: Analyzing data', value = 0, { lme4_models <- list() blues_list <- list() herit_list <- list() stability_list <- list() total_steps <- length(rv_lme4$traits) * 3 + 1 step_increment <- 1 / total_steps for (trait in rv_lme4$traits) { incProgress(step_increment, detail = paste("Fitting model for", trait)) model <- lme4_fit_model(rv_lme4$data, trait) lme4_models[[trait]] <- model debug_log <- c(debug_log, paste("Trait:", trait, "- Model fitted:", ifelse(is.null(model), "Failed", "Success"))) incProgress(step_increment, detail = paste("Calculating predicted means for", trait)) blues_list[[trait]] <- lme4_get_blue(model, trait) incProgress(step_increment, detail = paste("Calculating heritability for", trait)) herit_list[[trait]] <- lme4_calculate_heritability(model, trait) incProgress(step_increment, detail = paste("Performing stability analysis for", trait)) stability_list[[trait]] <- lme4_finlay_wilkinson(blues_list[[trait]], trait) } incProgress(step_increment, detail = "Calculating correlations") if (length(rv_lme4$traits) > 1) { trait_data <- rv_lme4$data %>% select(all_of(rv_lme4$traits)) 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) 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(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, set to 1") } rv_lme4$lme4_models <- lme4_models rv_lme4$blues_all <- bind_rows(blues_list) rv_lme4$heritability_table <- bind_rows(herit_list) rv_lme4$stability_table <- bind_rows(stability_list) rv_lme4$debug_log <- debug_log shinyjs::hide("lme4_blues_placeholder") shinyjs::show("lme4_blues_content") shinyjs::hide("lme4_heritability_placeholder") shinyjs::show("lme4_heritability_content") shinyjs::hide("lme4_correlations_placeholder") shinyjs::show("lme4_correlations_content") shinyjs::hide("lme4_stability_placeholder") shinyjs::show("lme4_stability_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) }, error = function(e) { message("LME4: Error in file processing: ", e$message) showNotification(paste("LME4 Error:", e$message), type = "error", duration = 10) }) }) # 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) }) lme4_filtered_heritability <- reactive({ req(rv_lme4$heritability_table, rv_lme4$trait) rv_lme4$heritability_table %>% filter(Trait = rv_lme4$trait) }) lme4_filtered_stability <- reactive({ req(rv_lme4$stability_table, rv_lme4$trait) rv_lme4$stability_table %>% filter(Trait = rv_lme4$trait) }) # LME4: Plot outputs output$lme4_blues_plot <- renderPlotly({ req(lme4_filtered_blues()) data <- lme4_filtered_blues() if (all(is.na(data$predicted.value))) { plot_ly() %>% layout( title = paste("No valid predicted means for", rv_lme4$trait), plot_bgcolor = "transparent", paper_bgcolor = "transparent", font = list(family = "Poppins", size = 12, color = "#2D3748") ) } else { plot_ly(data, x = ~Environment, y = ~predicted.value, color = ~Genotype, type = 'scatter', mode = 'lines+markers', colors = c('#FFB6C1', '#FFDAB9', '#B5EAD7', '#E6E6FA', '#FFFACD', '#FF9999')) %>% layout( title = paste("Predicted Means for", rv_lme4$trait), xaxis = list(title = "Environment"), yaxis = list(title = "Predicted Value"), plot_bgcolor = "transparent", paper_bgcolor = "transparent", font = list(family = "Poppins", size = 12, color = "#2D3748") ) } }) output$lme4_heritability_plot <- renderPlotly({ req(lme4_filtered_heritability()) data <- lme4_filtered_heritability() if (all(is.na(data$Heritability))) { plot_ly() %>% layout( title = paste("No valid heritability for", rv_lme4$trait, ":", unique(data$Error)), plot_bgcolor = "transparent", paper_bgcolor = "transparent", font = list(family = "Poppins", size = 12, color = "#2D3748") ) } else { plot_ly(data, x = ~Trait, y = ~Heritability, type = 'bar', color = ~Trait, colors = c('#FFB6C1', '#FFDAB9', '#B5EAD7', '#E6E6FA', '#FFFACD', '#FF9999')) %>% layout( title = "Heritability", xaxis = list(title = "Trait"), yaxis = list(title = "Heritability", range = c(0, 1)), showlegend = FALSE, plot_bgcolor = "transparent", paper_bgcolor = "transparent", font = list(family = "Poppins", size = 12, color = "#2D3748") ) } }) output$lme4_correlation_plot <- renderPlotly({ req(rv_lme4$cor_matrix) if (ncol(rv_lme4$cor_matrix) < 2) { plot_ly() %>% layout( title = "Correlation plot requires at least two traits", plot_bgcolor = "transparent", paper_bgcolor = "transparent", font = list(family = "Poppins", size = 12, color = "#2D3748") ) } else { plot_ly( x = colnames(rv_lme4$cor_matrix), y = rownames(rv_lme4$cor_matrix), z = rv_lme4$cor_matrix, type = "heatmap", colors = colorRamp(c('#E6E6FA', 'white', '#FFB6C1')) ) %>% layout( title = "Trait Correlation Matrix", xaxis = list(title = ""), yaxis = list(title = ""), plot_bgcolor = "transparent", paper_bgcolor = "transparent", font = list(family = "Poppins", size = 12, color = "#2D3748") ) } }) output$lme4_stability_plot <- renderPlotly({ req(lme4_filtered_stability()) data <- lme4_filtered_stability() if (all(is.na(data$Slope))) { plot_ly() %>% layout( title = paste("No valid stability analysis for", rv_lme4$trait, ":", unique(data$Error)), plot_bgcolor = "transparent", paper_bgcolor = "transparent", font = list(family = "Poppins", size = 12, color = "#2D3748") ) } else { plot_ly(data, x = ~Slope, y = ~R2, text = ~Genotype, type = 'scatter', mode = 'markers+text', marker = list(size = 12, color = '#FFB6C1'), textposition = 'top') %>% layout( title = paste("Stability Analysis for", rv_lme4$trait), xaxis = list(title = "Slope"), yaxis = list(title = "R²"), plot_bgcolor = "transparent", paper_bgcolor = "transparent", font = list(family = "Poppins", size = 12, color = "#2D3748") ) } }) # LME4: Table outputs output$lme4_blues_table <- renderDT({ req(lme4_filtered_blues()) datatable( lme4_filtered_blues(), extensions = 'Buttons', options = list(scrollX = TRUE, dom = 'Bfrtip', buttons = c('copy', 'excel', 'pdf', 'print'), pageLength = 10), caption = paste("Predicted Means for", rv_lme4$trait) ) }) output$lme4_heritability_table <- renderDT({ req(lme4_filtered_heritability()) datatable( lme4_filtered_heritability(), extensions = 'Buttons', options = list(scrollX = TRUE, dom = 'Bfrtip', buttons = c('copy', 'excel', 'pdf', 'print'), pageLength = 10), caption = "Broad-Sense Heritability" ) }) 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), caption = "Correlation Between Traits" ) }) 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), caption = paste("Stability Analysis for", rv_lme4$trait) ) }) } # Run the Shiny app shinyApp(ui, server) # Add health check middleware app$staticPaths <- list("/health" = httpuv::staticPath(system.file("health", package = "shiny"))) app