International Rice Research Institute
Update app.R
4e0823d verified
Raw History Blame
44.3 kB
library(shiny) library(shinyjs) library(tidyverse) library(DT) library(readxl) library(jsonlite) library(lme4) library(emmeans) library(plotly) library(shinyWidgets) library(ggplot2) # UI with two tabs 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: #4A6FA5; /* Soft blue */ --secondary: #6B8E23; /* Olive green */ --success: #32CD32; /* Lime Green */ --info: #4169E1; /* Royal Blue */ --warning: #FF8C00; /* Dark Orange */ --danger: #DC143C; /* Crimson */ --light: #F5F5F5; /* Light gray */ --dark: #2F4F4F; /* Dark Slate Gray */ --background: #F0F8FF; /* AliceBlue - Light pastel blue */ --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(74, 111, 165, 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; height: 1000px; 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(74, 111, 165, 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(74, 111, 165, 0.3); color: white; } /* Tab styling */ .nav-tabs { border-bottom: 2px solid var(--primary); margin-bottom: 20px; } .nav-tabs .nav-item { margin-bottom: -2px; } .nav-tabs .nav-link { color: var(--dark); 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(--primary); background: #E8E8E8; border: 1px solid var(--primary); } .nav-tabs .nav-link.active { color: white; background: var(--primary); 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(74, 111, 165, 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(74, 111, 165, 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", height = "100%")), # h3("⚠️ High Missing Data Environments (>20%)", class = "text-xl font-semibold mt-8 mb-4"), # DTOutput("pheno_missingTable") ) ), 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", height = "100%")) ) ), 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: var(--darker);") ), 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-varcomp", role = "tab", icon("chart-pie", class = "fas"), "📊 Variance Components"), 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"), 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-varcomp", role = "tabpanel", div(class = "section", h2("📊 Variance Components"), div(id = "lme4_varcomp_content", div(class = "chart-container", plotlyOutput("lme4_varcomp_plot", height = "100%")), div(class = "table-container", DTOutput("lme4_varcomp_table")), div(class = "insights", h4("💡 Interpretation"), 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.") ) ), div(id = "lme4_varcomp_placeholder", class = "text-center", icon("chart-pie", class = "fas", style = "font-size: 72px; color: var(--light); margin: 30px 0;"), h4("📤 Upload data to see variance components", 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 = "100%")), 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", height = "100%")), 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", height = "100%")), 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", height = "100%")), 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 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, trait = NULL, lme4_models = NULL, varcomp_table = NULL, blues_all = NULL, heritability_table = NULL, cor_matrix = NULL, cor_table = NULL, stability_table = 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, height = 1000) %>% 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, height = 1000) %>% 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_missingTable <- renderDT({ req(rv_pheno$missing_20) datatable( rv_pheno$missing_20, 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 = "Environments with >20% Missing Data" ) }) 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 = ", ")) } numeric_cols <- names(data)[sapply(data, is.numeric)] if (length(numeric_cols) == 0) { stop("No numeric columns found for traits") } message("LME4: Found ", length(numeric_cols), " numeric columns: ", paste(numeric_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)) return(list(data = data, trait = numeric_cols[1])) } # LME4: Fit model lme4_fit_model <- function(data, trait) { message("LME4: Fitting lme4 model for trait: ", trait) formula <- as.formula(paste(trait, "~ Environment + Genotype + Environment:Genotype + (1|Block) + (1|Row) + (1|Column) + (1|Rep)")) tryCatch({ model <- lmer(formula, data = data, na.action = na.omit) return(model) }, error = function(e) { stop("LME4: Failed to fit lme4 model for ", trait, ": ", e$message) }) } # LME4: Summarize variance lme4_summarize_variance <- function(model, trait) { varcomp <- as.data.frame(VarCorr(model)) varcomp_df <- data.frame( Trait = trait, Component = varcomp$grp, Variance = varcomp$vcov, Std.Error = varcomp$sdcor ) residual <- data.frame( Trait = trait, Component = "Residual", Variance = sigma(model)^2, Std.Error = NA ) varcomp_df <- rbind(varcomp_df, residual) return(varcomp_df) } # LME4: Get BLUEs lme4_get_blue <- function(model, trait) { 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) } # LME4: Calculate heritability lme4_calculate_heritability <- function(model, trait) { varcomp <- as.data.frame(VarCorr(model)) vg <- varcomp$vcov[varcomp$grp == "Genotype"] ve <- sigma(model)^2 h2 <- vg / (vg + ve) return(data.frame(Trait = trait, Heritability = h2)) } # LME4: Finlay-Wilkinson stability lme4_finlay_wilkinson <- function(blues, trait) { blues_trait <- blues %>% filter(Trait == trait) env_means <- blues_trait %>% group_by(Environment) %>% summarize(mean_value = mean(predicted.value)) blues_trait <- blues_trait %>% left_join(env_means, by = "Environment") stability <- blues_trait %>% group_by(Genotype) %>% do(model = lm(predicted.value ~ mean_value, data = .)) %>% summarize( Slope = coef(model)[2], R2 = summary(model)$r.squared, 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$trait <- result$trait message("LME4: Data processed, rows: ", nrow(rv_lme4$data), ", selected trait: ", rv_lme4$trait) 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) }) withProgress(message = 'LME4: Analyzing data', value = 0, { incProgress(0.1, detail = "Fitting model") lme4_models <- list() trait <- rv_lme4$trait lme4_models[[trait]] <- lme4_fit_model(rv_lme4$data, trait) rv_lme4$lme4_models <- lme4_models incProgress(0.2, detail = "Calculating variance components") varcomp_table <- lme4_summarize_variance(lme4_models[[trait]], trait) rv_lme4$varcomp_table <- varcomp_table incProgress(0.3, detail = "Calculating predicted means") blues_all <- lme4_get_blue(lme4_models[[trait]], trait) rv_lme4$blues_all <- blues_all incProgress(0.4, detail = "Calculating heritability") heritability_table <- lme4_calculate_heritability(lme4_models[[trait]], trait) rv_lme4$heritability_table <- heritability_table incProgress(0.5, detail = "Calculating correlations") trait_data <- rv_lme4$data %>% select(all_of(trait)) 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 incProgress(0.6, detail = "Performing stability analysis") stability_table <- lme4_finlay_wilkinson(blues_all, trait) rv_lme4$stability_table <- stability_table shinyjs::hide("lme4_varcomp_placeholder") shinyjs::show("lme4_varcomp_content") 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") }) 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) }) }) # LME4: Filtered reactives lme4_filtered_varcomp <- reactive({ req(rv_lme4$varcomp_table, rv_lme4$trait) rv_lme4$varcomp_table %>% filter(Trait == rv_lme4$trait) }) 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_varcomp_plot <- renderPlotly({ req(lme4_filtered_varcomp()) data <- lme4_filtered_varcomp() p <- plot_ly(data, x = ~Component, y = ~Variance, type = 'bar', color = ~Component, colors = c('#FFB6C1', '#FFDAB9', '#B5EAD7', '#E6E6FA', '#FFFACD', '#FF9999')) %>% layout(title = paste("Variance Components for", rv_lme4$trait), xaxis = list(title = "Component"), yaxis = list(title = "Variance"), showlegend = FALSE, plot_bgcolor = "transparent", paper_bgcolor = "transparent", font = list(family = "Poppins", size = 12, color = "#2D3748")) p }) output$lme4_blues_plot <- renderPlotly({ req(lme4_filtered_blues()) data <- lme4_filtered_blues() p <- 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")) p }) output$lme4_heritability_plot <- renderPlotly({ req(rv_lme4$heritability_table) data <- rv_lme4$heritability_table p <- 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")) p }) output$lme4_correlation_plot <- renderPlotly({ req(rv_lme4$cor_matrix) p <- 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")) p }) output$lme4_stability_plot <- renderPlotly({ req(lme4_filtered_stability()) data <- lme4_filtered_stability() p <- 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")) p }) # LME4: Table outputs output$lme4_varcomp_table <- renderDT({ req(lme4_filtered_varcomp()) datatable( lme4_filtered_varcomp(), extensions = 'Buttons', options = list(scrollX = TRUE, dom = 'Bfrtip', buttons = c('copy', 'excel', 'pdf', 'print'), pageLength = 10), caption = paste("Variance Components for", rv_lme4$trait) ) }) 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(rv_lme4$heritability_table) datatable( rv_lme4$heritability_table, 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)
library(shiny)
library(shinyjs)
library(tidyverse)
library(DT)
library(readxl)
library(jsonlite)
library(lme4)
library(emmeans)
library(plotly)
library(shinyWidgets)
library(ggplot2)
# UI with two tabs
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: #4A6FA5; /* Soft blue */
--secondary: #6B8E23; /* Olive green */
--success: #32CD32; /* Lime Green */
--info: #4169E1; /* Royal Blue */
--warning: #FF8C00; /* Dark Orange */
--danger: #DC143C; /* Crimson */
--light: #F5F5F5; /* Light gray */
--dark: #2F4F4F; /* Dark Slate Gray */
--background: #F0F8FF; /* AliceBlue - Light pastel blue */
--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(74, 111, 165, 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;
height: 1000px;
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(74, 111, 165, 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 {