Download app.R from softwareDevelopment/Phenotypic_data_analysis: direct link, hf CLI and curl.
- Browser
- Download file 88.1 kB
-
https://huggingface.co/spaces/softwareDevelopment/Phenotypic_data_analysis/resolve/main/app.R
- Command line
-
hf download hf://spaces/softwareDevelopment/Phenotypic_data_analysis/app.R
-
curl -L -o app.R https://huggingface.co/spaces/softwareDevelopment/Phenotypic_data_analysis/resolve/main/app.R
88.1 kB
library(shiny)
library(shinyjs)
library(tidyverse)
library(DT)
library(readxl)
library(lme4)
library(emmeans)
library(plotly)
library(shinyWidgets)
library(ggplot2)
library(GGally)
library(corrplot)
library(agricolae)
library(car)
library(broom)
library(cluster)
library(factoextra)
library(pheatmap)
library(RColorBrewer)
library(moments)
library(reshape2)
library(gridExtra)
library(openxlsx)
library(stringr)
library(scales)
# ─────────────────────────────────────────────────────────────────
# UI
# ─────────────────────────────────────────────────────────────────
ui <- fluidPage(
useShinyjs(),
tags$head(
tags$meta(charset = "UTF-8"),
tags$title("Advanced 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;
--secondary: #6B8E23;
--success: #32CD32;
--info: #4169E1;
--warning: #FF8C00;
--danger: #DC143C;
--light: #D1D5DB;
--dark: #2F4F4F;
--background: #FFFFFF;
--card-bg: #FFFFFF;
}
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,.1); border:1px solid rgba(30,58,138,.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,.1); background:var(--card-bg);
padding:1.5rem; border:1px solid rgba(30,58,138,.2); }
.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 .3s; box-shadow:0 4px 8px rgba(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,.3); color:white; }
.btn-success { background:linear-gradient(135deg,#32CD32,#228B22); border:none;
padding:1rem 2.5rem; border-radius:8px; font-weight:600; color:white;
transition:all .3s; box-shadow:0 4px 8px rgba(0,0,0,.1); margin:10px; }
.btn-success:hover { background:linear-gradient(135deg,#228B22,#32CD32);
transform:translateY(-2px); box-shadow:0 6px 12px rgba(50,205,50,.3); color:white; }
.btn-warning { background:linear-gradient(135deg,#FF8C00,#FF6347); border:none;
padding:1rem 2.5rem; border-radius:8px; font-weight:600; color:white;
transition:all .3s; box-shadow:0 4px 8px rgba(0,0,0,.1); margin:10px; }
.btn-warning:hover { background:linear-gradient(135deg,#FF6347,#FF8C00);
transform:translateY(-2px); color:white; }
.download-section { background:linear-gradient(135deg,#E8F5E8,#F0FFF0); padding:20px;
border-radius:10px; border:2px solid var(--success); margin:20px 0; text-align:center; }
.env-filter-box { background:linear-gradient(135deg,#E8F0FF,#F0F4FF); padding:20px;
border-radius:10px; border:2px solid var(--primary); margin:10px 0; }
.sidebar { background:var(--card-bg); color:var(--dark); padding:2rem; height:100vh;
position:fixed; width:300px; box-shadow:5px 0 15px rgba(0,0,0,.1);
border-right:1px solid var(--primary); overflow-y:auto; }
.sidebar-header { padding:20px; background:linear-gradient(135deg,var(--primary),var(--info));
text-align:center; border-bottom:1px solid rgba(0,0,0,.1); border-radius:10px;
margin-bottom:20px; color:white; }
.sidebar-content { padding:15px; }
.main-content { margin-left:300px; padding:20px; width:calc(100% - 300px);
min-height:100vh; background:var(--background); }
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 .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,.1); border:1px solid rgba(30,58,138,.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; }
.error-message { background:#ffebee; border:1px solid #e57373; color:#c62828;
padding:15px; border-radius:5px; margin:10px 0; }
.warning-message { background:#fff3e0; border:1px solid #ffb74d; color:#ef6c00;
padding:15px; border-radius:5px; margin:10px 0; }
.success-message { background:#e8f5e8; border:1px solid #81c784; color:#2e7d32;
padding:15px; border-radius:5px; margin:10px 0; }
.env-badge { display:inline-block; background:linear-gradient(135deg,var(--primary),var(--info));
color:white; padding:4px 12px; border-radius:20px; font-size:12px;
font-weight:600; margin:2px; }
.analysis-mode-indicator { background:linear-gradient(135deg,#E8F0FF,#F8F0FF);
border:2px solid var(--primary); border-radius:8px;
padding:12px 20px; margin:10px 0; font-weight:600;
color:var(--primary); text-align:center; font-size:14px; }
"))
),
div(class = "app-wrapper",
# ── SIDEBAR ──────────────────────────────────────────────────
div(class = "sidebar",
div(class = "sidebar-header",
h3("📊 Advanced Phenotypic Analysis",
style = "margin:0; font-weight:600; color:white;")),
div(class = "sidebar-content",
# ── Environment Filter ────────────────────────────────
div(class = "env-filter-box",
h4("🌍 Environment Selection", style = "color:var(--primary); margin-top:0;"),
radioButtons("analysis_mode", "Analysis Mode:",
choices = c("All Environments" = "all",
"Specific Environment(s)" = "specific"),
selected = "all"),
conditionalPanel(
condition = "input.analysis_mode == 'specific'",
selectInput("selected_environments", "Select Environment(s):",
choices = c(), multiple = TRUE, width = "100%"),
actionButton("apply_env_filter", "Apply Filter",
class = "btn-primary",
style = "width:100%; margin-top:8px; padding:8px;")
),
uiOutput("active_env_display")
),
hr(),
selectInput("selected_trait", "Select Trait for Analysis",
choices = c(), width = "100%"),
checkboxInput("include_interaction", "Include G×E Interaction", value = FALSE),
hr(),
# ── Download ─────────────────────────────────────────
div(class = "download-section",
h4("📥 Download All Results", style = "color:var(--success); margin-top:0;"),
downloadButton("download_all_results", "Download Complete Analysis",
class = "btn-success"),
downloadButton("download_env_results", "Download Env Analysis",
class = "btn-warning"),
p("Excel files with all analysis sheets",
style = "margin-top:10px; font-size:12px; color:var(--dark);")
),
hr(),
div(style = "padding:15px; color:var(--light); font-size:12px; text-align:center;",
p("Advanced Phenotypic Analysis v3.0"),
p("© 2024 Statistical Genetics Lab"))
)
),
# ── MAIN CONTENT ─────────────────────────────────────────────
div(class = "main-content",
tabsetPanel(id = "main_tabs",
# ── 1. Data Upload ──────────────────────────────────────
tabPanel("Data Upload", value = "upload",
div(class = "section",
h2("📤 Data Upload & Preview"),
div(class = "upload-container",
div(class = "upload-icon", icon("cloud-upload-alt", class = "fas")),
h3("📁 Upload your Excel/CSV file",
style = "color:var(--primary);"),
fileInput("data_file", NULL,
accept = c(".xlsx", ".xls", ".csv"),
buttonLabel = "Browse Files",
placeholder = "No file selected"),
p("📝 Supported: .xlsx, .xls, .csv",
style = "color:var(--light); font-size:14px;")
),
div(id = "upload_status"),
div(id = "data_preview_section", class = "hidden",
h3("📊 Data Overview"),
fluidRow(
column(3, div(class = "status-card", icon("columns", class = "fas"),
h4(textOutput("n_vars")), p("Variables"))),
column(3, div(class = "status-card", icon("list", class = "fas"),
h4(textOutput("n_obs")), p("Observations"))),
column(3, div(class = "status-card", icon("dna", class = "fas"),
h4(textOutput("n_geno")), p("Genotypes"))),
column(3, div(class = "status-card", icon("globe", class = "fas"),
h4(textOutput("n_env")), p("Environments")))
),
DTOutput("data_preview_table")
)
)
),
# ── 2. Environment Selection Tab ────────────────────────
tabPanel("Environment Analysis", value = "env_analysis",
div(class = "section",
h2("🌍 Per-Environment Analysis"),
uiOutput("env_analysis_mode_banner"),
tabsetPanel(id = "env_sub_tabs",
tabPanel("Summary Statistics",
div(class = "chart-container",
h4("Environment-wise Descriptive Statistics"),
DTOutput("env_desc_table"),
div(class = "insights", h4("💡 Interpretation"),
p("Per-environment descriptive statistics reveal how trait expression varies across locations/seasons. Large CV differences between environments signal strong environmental effects."))
)
),
tabPanel("Trait Distribution",
div(class = "chart-container",
h4("Trait Distribution per Environment"),
plotlyOutput("env_boxplot", height = "auto"),
plotlyOutput("env_violin_plot", height = "auto"),
div(class = "insights", h4("💡 Interpretation"),
p("Boxplots and violin plots show the spread of trait values within each environment. Outlier genotypes can be spotted as individual points beyond the whiskers."))
)
),
tabPanel("Environment ANOVA",
div(class = "chart-container",
h4("ANOVA Results by Environment"),
DTOutput("env_anova_table"),
div(class = "insights", h4("💡 Interpretation"),
p("Within-environment ANOVA tests whether genotypic differences are significant in each location. Significant p-values (< 0.05) justify genotype comparisons within that environment."))
)
),
tabPanel("Mean Comparison",
div(class = "chart-container",
h4("Genotype Means per Environment"),
plotlyOutput("env_means_plot", height = "auto"),
DTOutput("env_means_table"),
div(class = "insights", h4("💡 Interpretation"),
p("Genotype mean performance in each environment. Use for identifying top performers in specific target environments."))
)
),
tabPanel("Rank Changes",
div(class = "chart-container",
h4("Genotype Rank Across Environments"),
plotlyOutput("env_rank_plot", height = "auto"),
DTOutput("env_rank_table"),
div(class = "insights", h4("💡 Interpretation"),
p("Rank changes across environments reveal G×E interaction. Consistent ranks indicate stable genotypes; large rank changes indicate strong G×E."))
)
),
tabPanel("Environment Correlation",
div(class = "chart-container",
h4("Environment-to-Environment Correlation"),
plotOutput("env_cor_heatmap", height = "auto"),
DTOutput("env_cor_table"),
div(class = "insights", h4("💡 Interpretation"),
p("High correlation between environments means they discriminate genotypes similarly. Low or negative correlation suggests mega-environment differentiation."))
)
),
tabPanel("BLUEs per Environment",
div(class = "chart-container",
h4("BLUEs within Each Environment"),
plotlyOutput("env_blues_plot", height = "auto"),
DTOutput("env_blues_table"),
div(class = "insights", h4("💡 Interpretation"),
p("Within-environment BLUEs remove block/rep noise. Use these adjusted means for environment-specific selection decisions."))
)
)
)
)
),
# ── 3. Descriptive Statistics ───────────────────────────
tabPanel("Descriptive Statistics", value = "descriptives",
div(class = "section",
h2("📊 Descriptive Statistics"),
uiOutput("desc_mode_banner"),
fluidRow(
column(6, div(class = "chart-container",
plotlyOutput("descriptives_plot", height = "auto"))),
column(6, div(class = "chart-container",
plotlyOutput("distribution_plot", height = "auto")))
),
DTOutput("descriptives_table"),
div(class = "insights", h4("💡 Interpretation"),
p("CV > 20% indicates high variability. Check skewness and kurtosis for normality."))
)
),
# ── 4. ANOVA ────────────────────────────────────────────
tabPanel("ANOVA", value = "anova",
div(class = "section",
h2("🧮 Analysis of Variance (ANOVA)"),
uiOutput("anova_mode_banner"),
div(class = "chart-container", h4("ANOVA Table"), DTOutput("anova_table")),
fluidRow(
column(6, div(class = "chart-container",
plotlyOutput("residual_plot", height = "auto"))),
column(6, div(class = "chart-container",
plotlyOutput("qq_plot", height = "auto")))
),
div(class = "insights", h4("💡 Interpretation"),
p("P < 0.05 indicates significant differences. Check residual plots for model assumptions."))
)
),
# ── 5. Mixed Models / BLUEs ─────────────────────────────
tabPanel("Mixed Models", value = "blues",
div(class = "section",
h2("📈 Mixed Models & BLUEs"),
uiOutput("blues_mode_banner"),
div(class = "chart-container", plotlyOutput("blues_plot", height = "auto")),
DTOutput("blues_table"),
div(class = "insights", h4("💡 Interpretation"),
p("Parallel lines = no G×E; crossing lines = interaction present."))
)
),
# ── 6. Heritability ─────────────────────────────────────
tabPanel("Heritability", value = "heritability",
div(class = "section",
h2("🧬 Heritability Analysis"),
uiOutput("herit_mode_banner"),
fluidRow(
column(6, div(class = "chart-container", h4("Variance Components"),
DTOutput("variance_components"))),
column(6, div(class = "chart-container", h4("Heritability Estimates"),
DTOutput("heritability_table")))
),
div(class = "chart-container", plotlyOutput("heritability_plot", height = "auto")),
div(class = "insights", h4("💡 Interpretation"),
p("H² > 0.6 = high heritability, suitable for direct selection."))
)
),
# ── 7. Correlations ─────────────────────────────────────
tabPanel("Correlations", value = "correlations",
div(class = "section",
h2("🔗 Trait Correlations"),
uiOutput("corr_mode_banner"),
fluidRow(
column(8, div(class = "chart-container",
plotOutput("correlation_heatmap", height = "auto"))),
column(4, div(class = "chart-container",
DTOutput("correlation_table")))
),
div(class = "chart-container",
plotOutput("correlation_network", height = "auto")),
div(class = "insights", h4("💡 Interpretation"),
p("Values near ±1 = strong relationships. Use for indirect selection strategies."))
)
),
# ── 8. Clustering ───────────────────────────────────────
tabPanel("Clustering", value = "clustering",
div(class = "section",
h2("🌐 Genotype Clustering"),
uiOutput("clust_mode_banner"),
fluidRow(
column(4,
numericInput("n_clusters", "Number of Clusters:", value = 3, min = 2, max = 10),
selectInput("clustering_method", "Clustering Method:",
choices = c("K-means" = "kmeans",
"Hierarchical" = "hierarchical"))),
column(8, div(class = "chart-container",
plotlyOutput("cluster_plot", height = "auto")))
),
fluidRow(
column(6, div(class = "chart-container",
plotOutput("dendrogram", height = "auto"))),
column(6, div(class = "chart-container",
DTOutput("cluster_summary")))
),
div(class = "insights", h4("💡 Interpretation"),
p("Groups similar genotypes. Use for identifying genetic groups and breeding strategies."))
)
),
# ── 9. PCA ──────────────────────────────────────────────
tabPanel("PCA", value = "pca",
div(class = "section",
h2("📐 Principal Component Analysis"),
uiOutput("pca_mode_banner"),
fluidRow(
column(6, div(class = "chart-container",
plotlyOutput("pca_plot", height = "auto"))),
column(6, div(class = "chart-container",
plotlyOutput("pca_variance_plot", height = "auto")))
),
fluidRow(
column(6, div(class = "chart-container", DTOutput("pca_loadings"))),
column(6, div(class = "chart-container", DTOutput("pca_summary")))
),
div(class = "insights", h4("💡 Interpretation"),
p("First PCs explain most variation. Loadings show trait contributions."))
)
),
# ── 10. Stability ────────────────────────────────────────
tabPanel("Stability", value = "stability",
div(class = "section",
h2("⚖️ Genotype Stability Analysis"),
fluidRow(
column(6, div(class = "chart-container",
plotlyOutput("stability_plot", height = "auto"))),
column(6, div(class = "chart-container",
plotlyOutput("ammi_plot", height = "auto")))
),
DTOutput("stability_table"),
div(class = "insights", h4("💡 Interpretation"),
p("Low Ecovalence (Wi²) + high yield = stable high-performer."))
)
),
# ── 11. Customization ────────────────────────────────────
tabPanel("Customization", value = "customization",
div(class = "section",
h2("🎨 Plot Customization"),
div(class = "chart-container",
h3("Adjust Plot Dimensions"),
fluidRow(
column(6, numericInput("plot_height", "Plot Height (px):", value = 600, min = 300, max = 1200, step = 50)),
column(6, numericInput("plot_width", "Plot Width (px):", value = 800, min = 400, max = 1600, step = 50))
),
h3("Select Color Scheme"),
selectInput("color_scheme", "Color Scheme:",
choices = c("Default (Green/Red)" = "default",
"Blue Gradient" = "blue",
"Viridis" = "viridis",
"Plasma" = "plasma",
"Magma" = "magma"),
selected = "default"),
actionButton("apply_customization", "Apply Customization",
class = "btn-primary")
),
div(class = "insights", h4("💡 Instructions"),
p("Adjust height/width and color scheme, then click Apply."))
)
)
) # end tabsetPanel
)
)
)
# ─────────────────────────────────────────────────────────────────
# SERVER
# ─────────────────────────────────────────────────────────────────
server <- function(input, output, session) {
rv <- reactiveValues(
data = NULL,
filtered_data = NULL, # data after env filter
traits = NULL,
active_envs = NULL, # currently active environments
plot_height = 600,
plot_width = 800,
color_scheme = "default"
)
# ── Helpers ──────────────────────────────────────────────────
get_color_palette <- function(scheme, n) {
n <- max(n, 1)
if (scheme == "default") {
return(colorRampPalette(c("#1E3A8A","#6B8E23","#FF8C00","#DC143C","#4169E1"))(n))
} else if (scheme == "blue") {
return(colorRampPalette(c("#E6F0FA","#1E3A8A"))(n))
} else if (scheme == "viridis") {
return(viridisLite::viridis(n))
} else if (scheme == "plasma") {
return(viridisLite::plasma(n))
} else if (scheme == "magma") {
return(viridisLite::magma(n))
}
colorRampPalette(c("#1E3A8A","#6B8E23","#FF8C00"))(n)
}
# Helper: return working dataset (filtered or full)
working_data <- reactive({
req(rv$data)
if (!is.null(rv$filtered_data)) rv$filtered_data else rv$data
})
# Mode label
mode_label <- reactive({
if (input$analysis_mode == "all" || is.null(rv$active_envs)) {
"All Environments"
} else {
paste("Environments:", paste(rv$active_envs, collapse = ", "))
}
})
banner_ui <- function(icon_char = "🌍") {
renderUI({
div(class = "analysis-mode-indicator",
paste(icon_char, "Currently analysing:", mode_label()))
})
}
output$env_analysis_mode_banner <- banner_ui("🌍")
output$desc_mode_banner <- banner_ui("📊")
output$anova_mode_banner <- banner_ui("🧮")
output$blues_mode_banner <- banner_ui("📈")
output$herit_mode_banner <- banner_ui("🧬")
output$corr_mode_banner <- banner_ui("🔗")
output$clust_mode_banner <- banner_ui("🌐")
output$pca_mode_banner <- banner_ui("📐")
# Customization
observeEvent(input$apply_customization, {
rv$plot_height <- input$plot_height
rv$plot_width <- input$plot_width
rv$color_scheme <- input$color_scheme
showNotification("Customization applied!", type = "message")
})
# ── Data Validation ──────────────────────────────────────────
validate_data <- function(data) {
validation <- list()
required_cols <- c("Genotype","Environment","Rep","Block")
missing_cols <- setdiff(required_cols, names(data))
if (length(missing_cols) > 0)
validation$errors <- c(validation$errors,
paste("Missing columns:", paste(missing_cols, collapse=", ")))
for (col in c("Genotype","Environment","Rep","Block")) {
if (col %in% names(data) && !is.factor(data[[col]])) {
data[[col]] <- as.factor(data[[col]])
validation$warnings <- c(validation$warnings, paste(col, "converted to factor"))
}
}
if ("Genotype" %in% names(data) && length(unique(data$Genotype)) < 3)
validation$errors <- c(validation$errors, "Need at least 3 genotypes")
if ("Environment" %in% names(data) && length(unique(data$Environment)) < 2)
validation$errors <- c(validation$errors, "Need at least 2 environments")
if (ncol(data) >= 10) {
tc <- names(data)[10:ncol(data)]
nt <- tc[sapply(data[tc], is.numeric)]
if (length(nt) == 0)
validation$errors <- c(validation$errors, "No numeric trait columns from col 10 onward")
} else {
validation$errors <- c(validation$errors, "Data has fewer than 10 columns")
}
list(data=data, validation=validation)
}
# ── File Upload ──────────────────────────────────────────────
observeEvent(input$data_file, {
req(input$data_file)
withProgress(message='Processing data…', value=0, {
tryCatch({
incProgress(0.2, detail="Reading file…")
if (tools::file_ext(input$data_file$name) == "csv") {
data <- read.csv(input$data_file$datapath, stringsAsFactors=FALSE)
} else {
data <- as.data.frame(read_excel(input$data_file$datapath))
}
incProgress(0.4, detail="Validating…")
result <- validate_data(data)
rv$data <- result$data
rv$filtered_data <- NULL
rv$active_envs <- NULL
val <- result$validation
trait_cols <- if (ncol(data) >= 10) names(data)[10:ncol(data)] else character(0)
rv$traits <- trait_cols[sapply(data[trait_cols], is.numeric)]
incProgress(0.6, detail="Updating UI…")
envs <- as.character(unique(rv$data$Environment))
updateSelectInput(session, "selected_environments",
choices = envs, selected = envs)
updateSelectInput(session, "selected_trait",
choices = rv$traits,
selected = if (length(rv$traits)>0) rv$traits[1] else NULL)
shinyjs::show("data_preview_section")
incProgress(0.8, detail="Summary…")
output$n_vars <- renderText(ncol(rv$data))
output$n_obs <- renderText(nrow(rv$data))
output$n_geno <- renderText(if("Genotype" %in% names(rv$data))
length(unique(rv$data$Genotype)) else "N/A")
output$n_env <- renderText(if("Environment" %in% names(rv$data))
length(unique(rv$data$Environment)) else "N/A")
if (length(val$errors)>0)
showNotification(paste(val$errors, collapse="; "), type="error")
if (length(val$warnings)>0)
showNotification(paste(val$warnings, collapse="; "), type="warning")
output$upload_status <- renderUI(
div(class="success-message", icon("check-circle"),
paste("Loaded", nrow(rv$data), "observations with",
length(rv$traits), "traits")))
showNotification("Data uploaded!", type="message")
incProgress(1)
}, error=function(e) {
output$upload_status <- renderUI(
div(class="error-message", icon("exclamation-triangle"),
paste("Error:", e$message)))
showNotification(paste("Error:", e$message), type="error")
})
})
})
# ── Environment Filter Apply ──────────────────────────────────
observeEvent(input$apply_env_filter, {
req(rv$data, input$selected_environments)
if (input$analysis_mode == "specific" && length(input$selected_environments) > 0) {
rv$filtered_data <- rv$data %>%
filter(as.character(Environment) %in% input$selected_environments)
rv$active_envs <- input$selected_environments
showNotification(
paste("Filter applied:", paste(input$selected_environments, collapse=", ")),
type="message")
}
})
observeEvent(input$analysis_mode, {
if (input$analysis_mode == "all") {
rv$filtered_data <- NULL
rv$active_envs <- NULL
}
})
output$active_env_display <- renderUI({
if (!is.null(rv$active_envs) && input$analysis_mode == "specific") {
div(style="margin-top:8px;",
p("Active:", style="margin:0; font-size:12px; font-weight:600; color:var(--primary);"),
div(lapply(rv$active_envs, function(e)
span(class="env-badge", e))))
}
})
# ── Data Preview ─────────────────────────────────────────────
output$data_preview_table <- renderDT({
req(rv$data)
datatable(rv$data[1:min(100,nrow(rv$data)),],
options=list(scrollX=TRUE, pageLength=10, dom='frtip'),
caption="Data Preview (First 100 rows)")
})
# ═══════════════════════════════════════════════════════════════
# ENVIRONMENT-LEVEL ANALYSIS HELPERS
# ═══════════════════════════════════════════════════════════════
# Per-env descriptive stats
env_desc_stats <- reactive({
req(working_data(), rv$traits, input$selected_trait)
trait <- input$selected_trait
if (!trait %in% rv$traits) return(NULL)
tryCatch({
working_data() %>%
select(Environment, Genotype, all_of(trait)) %>%
rename(Value = !!trait) %>%
filter(!is.na(Value)) %>%
group_by(Environment) %>%
summarise(
N = n(),
Mean = round(mean(Value, na.rm=TRUE), 3),
Median = round(median(Value, na.rm=TRUE), 3),
SD = round(sd(Value, na.rm=TRUE), 3),
CV = round(sd(Value,na.rm=TRUE)/mean(Value,na.rm=TRUE)*100, 2),
Min = round(min(Value, na.rm=TRUE), 3),
Max = round(max(Value, na.rm=TRUE), 3),
Skewness= round(moments::skewness(Value, na.rm=TRUE), 3),
Kurtosis= round(moments::kurtosis(Value, na.rm=TRUE), 3),
Missing = sum(is.na(Value)),
.groups="drop"
)
}, error=function(e) { showNotification(e$message, type="error"); NULL })
})
output$env_desc_table <- renderDT({
req(env_desc_stats())
datatable(env_desc_stats(),
extensions='Buttons',
options=list(scrollX=TRUE, dom='Bfrtip',
buttons=c('copy','excel','csv'), pageLength=15),
caption=paste("Environment-wise Stats for", input$selected_trait)) %>%
formatRound(columns=c("Mean","Median","SD","CV","Min","Max","Skewness","Kurtosis"), digits=3)
})
# Env boxplot
output$env_boxplot <- renderPlotly({
req(working_data(), input$selected_trait)
trait <- input$selected_trait
if (!trait %in% rv$traits) return(NULL)
tryCatch({
df <- working_data() %>%
select(Environment, Genotype, all_of(trait)) %>%
rename(Value=!!trait) %>% filter(!is.na(Value)) %>%
mutate(Environment = factor(Environment))
n_env <- length(unique(df$Environment))
lbl_angle <- if (n_env > 6) 90 else if (n_env > 3) 45 else 0
lbl_hjust <- if (lbl_angle == 90) 1 else if (lbl_angle == 45) 1 else 0.5
lbl_vjust <- if (lbl_angle == 90) 0.5 else 1
bot_margin <- if (lbl_angle >= 45) 60 else 20
p <- ggplot(df, aes(x=Environment, y=Value, fill=Environment)) +
geom_boxplot(alpha=0.7, outlier.colour="red", outlier.size=2) +
geom_jitter(width=0.2, alpha=0.35, size=0.8, color="#444444") +
labs(title=paste("Boxplot of", trait, "per Environment"),
x=NULL, y=trait) +
theme_minimal() +
theme(
axis.text.x = element_text(angle=lbl_angle, hjust=lbl_hjust,
vjust=lbl_vjust, size=11, color="#000"),
axis.text.y = element_text(size=11, color="#000"),
axis.title = element_text(size=12, color="#000"),
plot.title = element_text(size=13, color="#000", face="bold"),
plot.margin = margin(t=10, r=10, b=bot_margin, l=10),
legend.position = "none"
) +
scale_fill_manual(values=get_color_palette(rv$color_scheme, n_env)) +
scale_x_discrete(labels = function(x) stringr::str_wrap(x, width=12))
ggplotly(p, height=rv$plot_height, width=rv$plot_width) %>%
layout(margin=list(b=bot_margin+20))
}, error=function(e) { showNotification(e$message, type="error"); NULL })
})
# Env violin plot
output$env_violin_plot <- renderPlotly({
req(working_data(), input$selected_trait)
trait <- input$selected_trait
if (!trait %in% rv$traits) return(NULL)
tryCatch({
df <- working_data() %>%
select(Environment, all_of(trait)) %>%
rename(Value=!!trait) %>% filter(!is.na(Value)) %>%
mutate(Environment = factor(Environment))
n_env <- length(unique(df$Environment))
lbl_angle <- if (n_env > 6) 90 else if (n_env > 3) 45 else 0
lbl_hjust <- if (lbl_angle == 90) 1 else if (lbl_angle == 45) 1 else 0.5
lbl_vjust <- if (lbl_angle == 90) 0.5 else 1
bot_margin <- if (lbl_angle >= 45) 60 else 20
p <- ggplot(df, aes(x=Environment, y=Value, fill=Environment)) +
geom_violin(alpha=0.7, trim=FALSE) +
geom_boxplot(width=0.08, fill="white", alpha=0.85, outlier.size=1.5) +
stat_summary(fun=mean, geom="point", shape=18, size=4, color="#1E3A8A") +
labs(title=paste("Violin Plot of", trait, "per Environment"),
x=NULL, y=trait) +
theme_minimal() +
theme(
axis.text.x = element_text(angle=lbl_angle, hjust=lbl_hjust,
vjust=lbl_vjust, size=11, color="#000"),
axis.text.y = element_text(size=11, color="#000"),
axis.title = element_text(size=12, color="#000"),
plot.title = element_text(size=13, color="#000", face="bold"),
plot.margin = margin(t=10, r=10, b=bot_margin, l=10),
legend.position = "none"
) +
scale_fill_manual(values=get_color_palette(rv$color_scheme, n_env)) +
scale_x_discrete(labels = function(x) stringr::str_wrap(x, width=12))
ggplotly(p, height=rv$plot_height, width=rv$plot_width) %>%
layout(margin=list(b=bot_margin+20))
}, error=function(e) { showNotification(e$message, type="error"); NULL })
})
# Per-env ANOVA
env_anova_results <- reactive({
req(working_data(), input$selected_trait)
trait <- input$selected_trait
if (!trait %in% rv$traits) return(NULL)
tryCatch({
envs <- unique(as.character(working_data()$Environment))
results <- lapply(envs, function(env) {
df <- working_data() %>%
filter(as.character(Environment)==env) %>%
select(Genotype, Rep, Block, all_of(trait)) %>%
rename(Value=!!trait) %>% filter(!is.na(Value)) %>%
mutate(Genotype=as.factor(Genotype), Rep=as.factor(Rep), Block=as.factor(Block))
if (nrow(df) < 6 || length(unique(df$Genotype)) < 2) return(NULL)
tryCatch({
m <- aov(Value ~ Genotype + Rep + Block, data=df)
sm <- broom::tidy(m)
sm$Environment <- env
sm
}, error=function(e) NULL)
})
do.call(rbind, Filter(Negate(is.null), results))
}, error=function(e) { showNotification(e$message, type="error"); NULL })
})
output$env_anova_table <- renderDT({
req(env_anova_results())
datatable(env_anova_results(),
extensions='Buttons',
options=list(scrollX=TRUE, dom='Bfrtip',
buttons=c('copy','excel','csv'), pageLength=20),
caption=paste("ANOVA by Environment for", input$selected_trait)) %>%
formatRound(columns=c("sumsq","meansq","statistic","p.value"), digits=4) %>%
formatStyle("p.value",
backgroundColor=styleInterval(0.05, c("#e8f5e8","#ffebee")))
})
# Genotype means per env
env_means_data <- reactive({
req(working_data(), input$selected_trait)
trait <- input$selected_trait
if (!trait %in% rv$traits) return(NULL)
tryCatch({
working_data() %>%
select(Genotype, Environment, all_of(trait)) %>%
rename(Value=!!trait) %>% filter(!is.na(Value)) %>%
group_by(Genotype, Environment) %>%
summarise(Mean=round(mean(Value, na.rm=TRUE), 3),
SD=round(sd(Value, na.rm=TRUE), 3),
N=n(), .groups="drop")
}, error=function(e) { showNotification(e$message, type="error"); NULL })
})
output$env_means_plot <- renderPlotly({
req(env_means_data())
df <- env_means_data()
tryCatch({
n_geno <- length(unique(df$Genotype))
txt_size <- if (n_geno > 40) 6 else if (n_geno > 20) 8 else 10
# dynamic height: give each genotype at least 18px
dyn_h <- max(rv$plot_height, n_geno * 18 + 100)
p <- ggplot(df, aes(x=reorder(Genotype, Mean), y=Mean, fill=Environment)) +
geom_col(position="dodge", alpha=0.85) +
coord_flip() +
labs(title=paste("Genotype Means per Environment —", input$selected_trait),
x=NULL, y="Mean Value") +
theme_minimal() +
theme(
axis.text.y = element_text(size=txt_size, color="#000", lineheight=0.9),
axis.text.x = element_text(size=10, color="#000"),
axis.title = element_text(size=12, color="#000"),
plot.title = element_text(size=13, color="#000", face="bold"),
legend.text = element_text(size=10),
legend.title = element_text(size=11)
) +
scale_fill_manual(values=get_color_palette(rv$color_scheme,
length(unique(df$Environment)))) +
scale_x_discrete(labels=function(x) stringr::str_trunc(x, 20))
ggplotly(p, height=dyn_h, width=rv$plot_width) %>%
layout(margin=list(l=10))
}, error=function(e) { showNotification(e$message, type="error"); NULL })
})
output$env_means_table <- renderDT({
req(env_means_data())
datatable(env_means_data(),
extensions='Buttons',
options=list(scrollX=TRUE, dom='Bfrtip',
buttons=c('copy','excel','csv'), pageLength=20),
caption=paste("Genotype Means per Environment —", input$selected_trait)) %>%
formatRound(columns=c("Mean","SD"), digits=3)
})
# Rank table
env_rank_data <- reactive({
req(env_means_data())
df <- env_means_data()
tryCatch({
ranks <- df %>%
group_by(Environment) %>%
mutate(Rank=rank(-Mean, ties.method="average")) %>%
ungroup() %>%
select(Genotype, Environment, Mean, Rank)
wide_rank <- ranks %>%
select(Genotype, Environment, Rank) %>%
pivot_wider(names_from=Environment, values_from=Rank,
names_prefix="Rank_")
wide_mean <- df %>%
select(Genotype, Environment, Mean) %>%
pivot_wider(names_from=Environment, values_from=Mean,
names_prefix="Mean_")
list(long=ranks, wide_rank=wide_rank, wide_mean=wide_mean)
}, error=function(e) { showNotification(e$message, type="error"); NULL })
})
output$env_rank_plot <- renderPlotly({
req(env_rank_data())
df <- env_rank_data()$long
tryCatch({
n_env <- length(unique(df$Environment))
n_geno <- length(unique(df$Genotype))
lbl_angle <- if (n_env > 6) 90 else if (n_env > 3) 45 else 0
lbl_hjust <- if (lbl_angle == 90) 1 else if (lbl_angle == 45) 1 else 0.5
lbl_vjust <- if (lbl_angle == 90) 0.5 else 1
bot_margin <- if (lbl_angle >= 45) 60 else 20
dyn_h <- max(rv$plot_height, n_geno * 14 + 120)
p <- ggplot(df, aes(x=Environment, y=Rank,
color=Genotype, group=Genotype,
text=paste0("Genotype: ", Genotype,
"<br>Rank: ", round(Rank,1),
"<br>Mean: ", round(Mean,3)))) +
geom_line(linewidth=0.9, alpha=0.75) +
geom_point(size=2.5, alpha=0.9) +
scale_y_reverse(breaks=seq(1, n_geno, by=max(1, floor(n_geno/10)))) +
labs(title=paste("Genotype Rank Across Environments —", input$selected_trait),
x=NULL, y="Rank (1 = Best)") +
theme_minimal() +
theme(
axis.text.x = element_text(angle=lbl_angle, hjust=lbl_hjust,
vjust=lbl_vjust, size=11, color="#000"),
axis.text.y = element_text(size=10, color="#000"),
axis.title.y = element_text(size=12, color="#000"),
plot.title = element_text(size=13, color="#000", face="bold"),
plot.margin = margin(t=10, r=10, b=bot_margin, l=10),
legend.position = if (n_geno > 25) "none" else "right",
legend.text = element_text(size=8)
) +
scale_color_manual(values=get_color_palette(rv$color_scheme, n_geno)) +
scale_x_discrete(labels=function(x) stringr::str_wrap(x, width=10))
ggplotly(p, tooltip="text", height=dyn_h, width=rv$plot_width) %>%
layout(margin=list(b=bot_margin+20))
}, error=function(e) { showNotification(e$message, type="error"); NULL })
})
output$env_rank_table <- renderDT({
req(env_rank_data())
datatable(env_rank_data()$wide_rank,
extensions='Buttons',
options=list(scrollX=TRUE, dom='Bfrtip',
buttons=c('copy','excel','csv'), pageLength=20),
caption=paste("Rank Table —", input$selected_trait))
})
# Env-env correlation
env_cor_data <- reactive({
req(working_data(), input$selected_trait)
trait <- input$selected_trait
if (!trait %in% rv$traits) return(NULL)
tryCatch({
wide <- working_data() %>%
select(Genotype, Environment, all_of(trait)) %>%
rename(Value=!!trait) %>% filter(!is.na(Value)) %>%
group_by(Genotype, Environment) %>%
summarise(Mean=mean(Value, na.rm=TRUE), .groups="drop") %>%
pivot_wider(names_from=Environment, values_from=Mean) %>%
column_to_rownames("Genotype")
if (ncol(wide) < 2) return(NULL)
cor_mat <- cor(wide, use="pairwise.complete.obs")
cor_long <- cor_mat %>% as.data.frame() %>%
rownames_to_column("Env1") %>%
pivot_longer(-Env1, names_to="Env2", values_to="Correlation") %>%
filter(Env1 != Env2) %>%
mutate(Correlation=round(Correlation,3))
list(matrix=cor_mat, table=cor_long)
}, error=function(e) { showNotification(e$message, type="error"); NULL })
})
output$env_cor_heatmap <- renderPlot({
req(env_cor_data())
tryCatch({
m <- env_cor_data()$matrix
corrplot::corrplot(m, method="color", type="upper", order="hclust",
tl.cex=0.9, tl.col="#000000", tl.srt=45,
addCoef.col="#000000", number.cex=0.8,
title="Environment Correlation Matrix",
mar=c(0,0,2,0),
col=colorRampPalette(
get_color_palette(rv$color_scheme, 3))(200))
}, error=function(e) { showNotification(e$message, type="error") })
}, height=function() rv$plot_height, width=function() rv$plot_width)
output$env_cor_table <- renderDT({
req(env_cor_data())
datatable(env_cor_data()$table,
extensions='Buttons',
options=list(scrollX=TRUE, dom='Bfrtip',
buttons=c('copy','excel','csv'), pageLength=15),
caption="Environment-to-Environment Correlations") %>%
formatRound("Correlation", 3)
})
# Per-env BLUEs
env_blues_data <- reactive({
req(working_data(), input$selected_trait)
trait <- input$selected_trait
if (!trait %in% rv$traits) return(NULL)
tryCatch({
envs <- unique(as.character(working_data()$Environment))
results <- lapply(envs, function(env) {
df <- working_data() %>%
filter(as.character(Environment)==env) %>%
select(Genotype, Rep, Block, all_of(trait)) %>%
rename(Value=!!trait) %>% filter(!is.na(Value)) %>%
mutate(Genotype=as.factor(Genotype),
Rep=as.factor(Rep), Block=as.factor(Block))
if (nrow(df)<6 || length(unique(df$Genotype))<2) return(NULL)
tryCatch({
m <- lmer(Value ~ Genotype + (1|Rep) + (1|Block), data=df)
em <- as.data.frame(emmeans(m, ~Genotype))
em$Environment <- env
em %>% select(Environment, Genotype, emmean, SE) %>%
rename(BLUE=emmean)
}, error=function(e) NULL)
})
do.call(rbind, Filter(Negate(is.null), results))
}, error=function(e) { showNotification(e$message, type="error"); NULL })
})
output$env_blues_plot <- renderPlotly({
req(env_blues_data())
df <- env_blues_data()
tryCatch({
n_geno <- length(unique(df$Genotype))
n_env <- length(unique(df$Environment))
txt_size <- if (n_geno > 40) 6 else if (n_geno > 20) 8 else 10
# height grows with genotypes × environments
dyn_h <- max(rv$plot_height, n_geno * 16 * max(1, ceiling(n_env/3)) + 120)
p <- ggplot(df, aes(x=reorder(Genotype, BLUE), y=BLUE, color=Environment)) +
geom_point(size=2, alpha=0.85) +
geom_errorbar(aes(ymin=BLUE-SE, ymax=BLUE+SE), width=0.4, alpha=0.65) +
facet_wrap(~Environment, scales="free_x", ncol=min(n_env, 3)) +
coord_flip() +
labs(title=paste("Within-Environment BLUEs —", input$selected_trait),
x=NULL, y="BLUE") +
theme_minimal() +
theme(
axis.text.y = element_text(size=txt_size, color="#000", lineheight=0.9),
axis.text.x = element_text(size=9, color="#000"),
axis.title = element_text(size=11, color="#000"),
strip.text = element_text(size=11, face="bold", color="#1E3A8A"),
plot.title = element_text(size=13, color="#000", face="bold"),
legend.position = "none"
) +
scale_color_manual(values=get_color_palette(rv$color_scheme, n_env)) +
scale_y_continuous(labels=scales::number_format(accuracy=0.01))
ggplotly(p, height=dyn_h, width=rv$plot_width) %>%
layout(margin=list(l=10))
}, error=function(e) { showNotification(e$message, type="error"); NULL })
})
output$env_blues_table <- renderDT({
req(env_blues_data())
datatable(env_blues_data(),
extensions='Buttons',
options=list(scrollX=TRUE, dom='Bfrtip',
buttons=c('copy','excel','csv'), pageLength=20),
caption=paste("Within-Environment BLUEs —", input$selected_trait)) %>%
formatRound(columns=c("BLUE","SE"), digits=3)
})
# ═══════════════════════════════════════════════════════════════
# ACROSS-ENVIRONMENT (GLOBAL) ANALYSES — use working_data()
# ═══════════════════════════════════════════════════════════════
# Descriptive stats
descriptive_stats <- reactive({
req(working_data(), rv$traits)
tryCatch({
working_data() %>%
select(all_of(rv$traits)) %>%
pivot_longer(everything(), names_to="Trait", values_to="Value") %>%
group_by(Trait) %>%
summarise(
N = sum(!is.na(Value)),
Mean = round(mean(Value, na.rm=TRUE), 3),
Median = round(median(Value, na.rm=TRUE), 3),
SD = round(sd(Value, na.rm=TRUE), 3),
CV = round(sd(Value,na.rm=TRUE)/mean(Value,na.rm=TRUE)*100, 2),
Min = round(min(Value, na.rm=TRUE), 3),
Max = round(max(Value, na.rm=TRUE), 3),
Q1 = round(quantile(Value,.25, na.rm=TRUE), 3),
Q3 = round(quantile(Value,.75, na.rm=TRUE), 3),
Skewness = round(moments::skewness(Value, na.rm=TRUE), 3),
Kurtosis = round(moments::kurtosis(Value, na.rm=TRUE), 3),
Missing = sum(is.na(Value)),
.groups="drop")
}, error=function(e) { showNotification(e$message, type="error"); NULL })
})
output$descriptives_table <- renderDT({
req(descriptive_stats())
datatable(descriptive_stats(), extensions='Buttons',
options=list(scrollX=TRUE, dom='Bfrtip',
buttons=c('copy','excel','csv'),
pageLength=15),
caption="Descriptive Statistics — All Traits") %>%
formatRound(columns=c("Mean","Median","SD","CV","Min","Max","Q1","Q3","Skewness","Kurtosis"),
digits=3)
})
output$descriptives_plot <- renderPlotly({
req(working_data(), input$selected_trait)
if (!input$selected_trait %in% rv$traits) return(NULL)
tryCatch({
df <- working_data() %>%
select(Genotype, Environment, all_of(input$selected_trait)) %>%
rename(Value=!!input$selected_trait) %>% filter(!is.na(Value)) %>%
mutate(Environment=factor(Environment))
n_env <- length(unique(df$Environment))
lbl_angle <- if (n_env > 6) 90 else if (n_env > 3) 45 else 0
lbl_hjust <- if (lbl_angle == 90) 1 else if (lbl_angle == 45) 1 else 0.5
lbl_vjust <- if (lbl_angle == 90) 0.5 else 1
bot_margin <- if (lbl_angle >= 45) 60 else 20
p <- df %>%
ggplot(aes(x=Environment, y=Value, fill=Environment)) +
geom_boxplot(alpha=0.7) +
geom_jitter(width=0.2, alpha=0.35, size=0.8, color="#444444") +
labs(title=paste("Distribution of", input$selected_trait, "by Environment"),
x=NULL, y=input$selected_trait) +
theme_minimal() +
theme(
axis.text.x = element_text(angle=lbl_angle, hjust=lbl_hjust,
vjust=lbl_vjust, size=11, color="#000"),
axis.text.y = element_text(size=11, color="#000"),
axis.title = element_text(size=12, color="#000"),
plot.title = element_text(size=13, color="#000", face="bold"),
plot.margin = margin(t=10, r=10, b=bot_margin, l=10),
legend.position = "none"
) +
scale_fill_manual(values=get_color_palette(rv$color_scheme, n_env)) +
scale_x_discrete(labels=function(x) stringr::str_wrap(x, width=12))
ggplotly(p, height=rv$plot_height, width=rv$plot_width) %>%
layout(margin=list(b=bot_margin+20))
}, error=function(e) { showNotification(e$message, type="error"); NULL })
})
output$distribution_plot <- renderPlotly({
req(working_data(), input$selected_trait)
if (!input$selected_trait %in% rv$traits) return(NULL)
tryCatch({
td <- working_data()[[input$selected_trait]]
td <- td[!is.na(td)]
if (length(td)<2) return(NULL)
p <- data.frame(Value=td) %>%
ggplot(aes(x=Value)) +
geom_histogram(aes(y=after_stat(density)), bins=30,
fill=get_color_palette(rv$color_scheme,2)[1], alpha=0.7) +
geom_density(color=get_color_palette(rv$color_scheme,2)[2], linewidth=1) +
labs(title=paste("Distribution of", input$selected_trait),
x=input$selected_trait, y="Density") +
theme_minimal() +
theme(axis.text=element_text(color="#000"),
axis.title=element_text(color="#000"),
plot.title=element_text(color="#000"))
ggplotly(p, height=rv$plot_height, width=rv$plot_width)
}, error=function(e) { showNotification(e$message, type="error"); NULL })
})
# ANOVA
anova_analysis <- reactive({
req(working_data(), input$selected_trait)
if (!input$selected_trait %in% rv$traits) return(NULL)
tryCatch({
td <- working_data() %>%
select(Genotype, Environment, Rep, Block, all_of(input$selected_trait)) %>%
rename(Value=!!input$selected_trait) %>% filter(!is.na(Value)) %>%
mutate(across(c(Genotype,Environment,Rep,Block), as.factor))
if (nrow(td)<10) { showNotification("Insufficient data for ANOVA", type="error"); return(NULL) }
model <- if (input$include_interaction)
aov(Value ~ Environment + Genotype + Environment:Genotype + Error(Rep/Block), data=td)
else
aov(Value ~ Environment + Genotype + Error(Rep/Block), data=td)
sm <- lm(Value ~ Environment + Genotype, data=td)
rd <- data.frame(Fitted=fitted(sm), Residuals=residuals(sm),
Standardized_Residuals=rstandard(sm), Genotype=td$Genotype)
list(model=model, summary=summary(model), residuals=rd, simple_model=sm)
}, error=function(e) { showNotification(paste("ANOVA:", e$message), type="error"); NULL })
})
output$anova_table <- renderDT({
req(anova_analysis())
tryCatch({
df <- broom::tidy(anova_analysis()$simple_model)
datatable(df, extensions='Buttons',
options=list(scrollX=TRUE, dom='Bfrtip',
buttons=c('copy','excel','csv'), pageLength=10),
caption=paste("ANOVA —", input$selected_trait)) %>%
formatRound(columns=c("estimate","std.error","statistic","p.value"), digits=4) %>%
formatStyle("p.value",
backgroundColor=styleInterval(0.05, c("#ffebee","#e8f5e8")))
}, error=function(e) { showNotification(e$message, type="error"); NULL })
})
output$residual_plot <- renderPlotly({
req(anova_analysis())
tryCatch({
rd <- anova_analysis()$residuals
p <- ggplot(rd, aes(x=Fitted, y=Residuals, color=Genotype)) +
geom_point(size=1, alpha=0.6) +
geom_smooth(method="loess", se=FALSE,
color=get_color_palette(rv$color_scheme,2)[2]) +
geom_hline(yintercept=0, linetype="dashed",
color=get_color_palette(rv$color_scheme,2)[2]) +
labs(title="Residuals vs Fitted", x="Fitted", y="Residuals") +
theme_minimal() +
theme(axis.text=element_text(color="#000"),
axis.title=element_text(color="#000"),
plot.title=element_text(color="#000")) +
scale_color_manual(values=get_color_palette(rv$color_scheme,
length(unique(rd$Genotype))))
ggplotly(p, tooltip=c("color","x","y"), height=rv$plot_height, width=rv$plot_width)
}, error=function(e) { showNotification(e$message, type="error"); NULL })
})
output$qq_plot <- renderPlotly({
req(anova_analysis())
tryCatch({
rd <- anova_analysis()$residuals
p <- ggplot(rd, aes(sample=Standardized_Residuals, color=Genotype)) +
stat_qq(size=1) +
stat_qq_line(color=get_color_palette(rv$color_scheme,2)[2]) +
labs(title="Normal Q-Q Plot",
x="Theoretical Quantiles", y="Sample Quantiles") +
theme_minimal() +
theme(axis.text=element_text(color="#000"),
axis.title=element_text(color="#000"),
plot.title=element_text(color="#000")) +
scale_color_manual(values=get_color_palette(rv$color_scheme,
length(unique(rd$Genotype))))
ggplotly(p, tooltip=c("color","x","y"), height=rv$plot_height, width=rv$plot_width)
}, error=function(e) { showNotification(e$message, type="error"); NULL })
})
# Mixed Models / BLUEs
mixed_model_analysis <- reactive({
req(working_data(), input$selected_trait)
if (!input$selected_trait %in% rv$traits) return(NULL)
tryCatch({
td <- working_data() %>%
select(Genotype, Environment, Rep, Block, all_of(input$selected_trait)) %>%
rename(Value=!!input$selected_trait) %>% filter(!is.na(Value)) %>%
mutate(across(c(Genotype,Environment,Rep,Block), as.factor))
if (nrow(td)<10) { showNotification("Insufficient data for mixed model", type="error"); return(NULL) }
model <- if (input$include_interaction)
lmer(Value ~ Environment + Genotype + Environment:Genotype + (1|Rep) + (1|Block), data=td)
else
lmer(Value ~ Environment + Genotype + (1|Rep) + (1|Block), data=td)
blues_df <- as.data.frame(emmeans(model, ~Genotype|Environment)) %>%
select(Genotype, Environment, emmean, SE) %>%
rename(BLUE=emmean)
list(model=model, blues=blues_df)
}, error=function(e) { showNotification(paste("Mixed Model:", e$message), type="error"); NULL })
})
output$blues_plot <- renderPlotly({
req(mixed_model_analysis())
tryCatch({
df <- mixed_model_analysis()$blues
n_env <- length(unique(df$Environment))
n_gen <- length(unique(df$Genotype))
lbl_angle <- if (n_env > 6) 90 else if (n_env > 3) 45 else 0
lbl_hjust <- if (lbl_angle == 90) 1 else if (lbl_angle == 45) 1 else 0.5
lbl_vjust <- if (lbl_angle == 90) 0.5 else 1
bot_margin <- if (lbl_angle >= 45) 60 else 20
p <- ggplot(df, aes(x=Environment, y=BLUE, color=Genotype, group=Genotype)) +
geom_line(linewidth=1) + geom_point(size=2) +
labs(title=paste("BLUEs for", input$selected_trait),
x=NULL, y="BLUE") +
theme_minimal() +
theme(
axis.text.x = element_text(angle=lbl_angle, hjust=lbl_hjust,
vjust=lbl_vjust, size=11, color="#000"),
axis.text.y = element_text(size=11, color="#000"),
axis.title = element_text(size=12, color="#000"),
plot.title = element_text(size=13, color="#000", face="bold"),
plot.margin = margin(t=10, r=10, b=bot_margin, l=10),
legend.position = if (n_gen > 25) "none" else "right",
legend.text = element_text(size=8)
) +
scale_color_manual(values=get_color_palette(rv$color_scheme, n_gen)) +
scale_x_discrete(labels=function(x) stringr::str_wrap(x, width=10))
ggplotly(p, tooltip=c("color","x","y"), height=rv$plot_height, width=rv$plot_width) %>%
layout(margin=list(b=bot_margin+20))
}, error=function(e) { showNotification(e$message, type="error"); NULL })
})
output$blues_table <- renderDT({
req(mixed_model_analysis())
datatable(mixed_model_analysis()$blues, extensions='Buttons',
options=list(scrollX=TRUE, dom='Bfrtip',
buttons=c('copy','excel','csv'), pageLength=15),
caption=paste("BLUEs —", input$selected_trait)) %>%
formatRound(columns=c("BLUE","SE"), digits=3)
})
# Heritability
heritability_analysis <- reactive({
req(working_data(), rv$traits)
if (length(rv$traits)<1) return(NULL)
results <- list()
for (trait in rv$traits) {
tryCatch({
td <- working_data() %>%
select(Genotype, Environment, Rep, Block, all_of(trait)) %>%
rename(Value=!!trait) %>% filter(!is.na(Value)) %>%
mutate(across(c(Genotype,Environment,Rep,Block), as.factor))
if (nrow(td)<10 || length(unique(td$Environment))<2) next
m <- lmer(Value ~ (1|Genotype) + (1|Environment) + (1|Genotype:Environment) +
(1|Rep) + (1|Block), data=td)
vc <- as.data.frame(VarCorr(m)); vc$Trait <- trait
vg <- vc$vcov[vc$grp=="Genotype"]; vg <- if(length(vg)==0) 0 else vg
vge <- vc$vcov[vc$grp=="Genotype:Environment"]; vge <- if(length(vge)==0) 0 else vge
ve <- vc$vcov[vc$grp=="Residual"]; ve <- if(length(ve)==0) 1 else ve
ne <- length(unique(td$Environment))
nr <- length(unique(td$Rep))
h2b <- vg/(vg+vge+ve)
h2e <- vg/(vg+(vge/ne)+(ve/(ne*nr)))
results[[trait]] <- list(trait=trait, variance_components=vc,
h2_broad=h2b, h2_entry=h2e)
}, error=function(e) NULL)
}
if (length(results)==0) return(NULL)
results
})
output$variance_components <- renderDT({
req(heritability_analysis())
tryCatch({
df <- do.call(rbind, lapply(heritability_analysis(), `[[`, "variance_components"))
datatable(df, extensions='Buttons',
options=list(scrollX=TRUE, dom='Bfrtip',
buttons=c('copy','excel','csv'), pageLength=10),
caption="Variance Components") %>%
formatRound(columns=c("vcov","sdcor"), digits=4)
}, error=function(e) { showNotification(e$message, type="error"); NULL })
})
output$heritability_table <- renderDT({
req(heritability_analysis())
tryCatch({
df <- data.frame(
Trait = names(heritability_analysis()),
H2_Broad = sapply(heritability_analysis(), function(x) round(x$h2_broad,3)),
H2_Entry = sapply(heritability_analysis(), function(x) round(x$h2_entry,3)),
stringsAsFactors=FALSE)
datatable(df, extensions='Buttons',
options=list(scrollX=TRUE, dom='Bfrtip',
buttons=c('copy','excel','csv'), pageLength=10),
caption="Heritability Estimates") %>%
formatRound(columns=c("H2_Broad","H2_Entry"), digits=3) %>%
formatStyle(c("H2_Broad","H2_Entry"),
backgroundColor=styleInterval(c(.3,.6), c("#ffebee","#fff3e0","#e8f5e8")))
}, error=function(e) { showNotification(e$message, type="error"); NULL })
})
output$heritability_plot <- renderPlotly({
req(heritability_analysis())
tryCatch({
df <- data.frame(
Trait = names(heritability_analysis()),
H2_Broad = sapply(heritability_analysis(), function(x) x$h2_broad),
H2_Entry = sapply(heritability_analysis(), function(x) x$h2_entry)) %>%
pivot_longer(cols=c(H2_Broad,H2_Entry), names_to="Type", values_to="Heritability")
p <- ggplot(df, aes(x=Trait, y=Heritability, fill=Type)) +
geom_col(position="dodge", alpha=0.8) +
geom_hline(yintercept=c(.3,.6), linetype="dashed",
color=get_color_palette(rv$color_scheme,2)[2]) +
labs(title="Heritability by Trait", x="Trait", y="Heritability") +
theme_minimal() +
theme(axis.text.x=element_text(angle=45, hjust=1),
axis.text=element_text(color="#000"),
axis.title=element_text(color="#000"),
plot.title=element_text(color="#000")) +
scale_fill_manual(values=get_color_palette(rv$color_scheme,2))
ggplotly(p, height=rv$plot_height, width=rv$plot_width)
}, error=function(e) { showNotification(e$message, type="error"); NULL })
})
# Correlations
correlation_analysis <- reactive({
req(working_data(), rv$traits)
if (length(rv$traits)<2) return(NULL)
tryCatch({
td <- working_data() %>% select(all_of(rv$traits)) %>% na.omit()
if (nrow(td)<10) return(NULL)
cm <- cor(td, use="complete.obs")
ct <- cm %>% as.data.frame() %>% rownames_to_column("Trait1") %>%
pivot_longer(-Trait1, names_to="Trait2", values_to="Correlation") %>%
filter(Trait1!=Trait2) %>%
mutate(Correlation=round(Correlation,3), Abs_Correlation=abs(Correlation)) %>%
arrange(desc(Abs_Correlation))
list(matrix=cm, table=ct, data=td)
}, error=function(e) { showNotification(e$message, type="error"); NULL })
})
output$correlation_heatmap <- renderPlot({
req(correlation_analysis())
tryCatch({
corrplot::corrplot(correlation_analysis()$matrix, method="color",
type="upper", order="hclust", tl.cex=0.8, tl.col="#000000",
tl.srt=45, addCoef.col="#000000", number.cex=0.7,
title="Trait Correlation Matrix", mar=c(0,0,2,0),
col=colorRampPalette(get_color_palette(rv$color_scheme,3))(200))
}, error=function(e) showNotification(e$message, type="error"))
}, height=function() rv$plot_height, width=function() rv$plot_width)
output$correlation_table <- renderDT({
req(correlation_analysis())
datatable(correlation_analysis()$table, extensions='Buttons',
options=list(scrollX=TRUE, dom='Bfrtip',
buttons=c('copy','excel','csv'), pageLength=15),
caption="Pairwise Correlations") %>%
formatRound(columns=c("Correlation","Abs_Correlation"), digits=3)
})
output$correlation_network <- renderPlot({
req(correlation_analysis())
tryCatch({
corrplot::corrplot(correlation_analysis()$matrix, method="circle",
type="full", order="hclust", tl.cex=0.8, tl.col="#000000",
title="Correlation Network", mar=c(0,0,2,0),
col=colorRampPalette(get_color_palette(rv$color_scheme,3))(200))
}, error=function(e) showNotification(e$message, type="error"))
}, height=function() rv$plot_height, width=function() rv$plot_width)
# PCA
pca_analysis <- reactive({
req(working_data(), rv$traits)
if (length(rv$traits)<2) return(NULL)
tryCatch({
td <- working_data() %>% select(Genotype, all_of(rv$traits)) %>% na.omit()
if (nrow(td)<10) return(NULL)
pd <- scale(td %>% select(-Genotype))
pr <- prcomp(pd, center=FALSE, scale.=FALSE)
scores <- as.data.frame(pr$x) %>% mutate(Genotype=td$Genotype)
vexp <- data.frame(PC=paste0("PC",1:length(pr$sdev)),
Variance=pr$sdev^2,
Prop_Variance=pr$sdev^2/sum(pr$sdev^2),
Cumulative=cumsum(pr$sdev^2/sum(pr$sdev^2)))
loadings <- as.data.frame(pr$rotation) %>% rownames_to_column("Trait")
list(scores=scores, variance=vexp, loadings=loadings, result=pr)
}, error=function(e) { showNotification(e$message, type="error"); NULL })
})
output$pca_plot <- renderPlotly({
req(pca_analysis())
tryCatch({
sc <- pca_analysis()$scores
p <- ggplot(sc, aes(x=PC1, y=PC2, color=Genotype, text=Genotype)) +
geom_point(size=2, alpha=0.8) +
labs(title="PCA Biplot",
x=paste0("PC1 (",round(pca_analysis()$variance$Prop_Variance[1]*100,1),"%)"),
y=paste0("PC2 (",round(pca_analysis()$variance$Prop_Variance[2]*100,1),"%)")) +
theme_minimal() +
theme(axis.text=element_text(color="#000"),
axis.title=element_text(color="#000"),
plot.title=element_text(color="#000")) +
scale_color_manual(values=get_color_palette(rv$color_scheme,
length(unique(sc$Genotype))))
ggplotly(p, tooltip=c("text","x","y"), height=rv$plot_height, width=rv$plot_width)
}, error=function(e) { showNotification(e$message, type="error"); NULL })
})
output$pca_variance_plot <- renderPlotly({
req(pca_analysis())
tryCatch({
vd <- pca_analysis()$variance[1:min(10, nrow(pca_analysis()$variance)),]
p <- ggplot(vd, aes(x=PC, y=Prop_Variance)) +
geom_col(fill=get_color_palette(rv$color_scheme,2)[1], alpha=0.8) +
geom_line(aes(y=Cumulative, group=1),
color=get_color_palette(rv$color_scheme,2)[2], linewidth=1) +
geom_point(aes(y=Cumulative),
color=get_color_palette(rv$color_scheme,2)[2], size=2) +
labs(title="PCA Variance Explained", x="PC", y="Proportion of Variance") +
theme_minimal() +
theme(axis.text.x=element_text(angle=45, hjust=1),
axis.text=element_text(color="#000"),
axis.title=element_text(color="#000"),
plot.title=element_text(color="#000"))
ggplotly(p, height=rv$plot_height, width=rv$plot_width)
}, error=function(e) { showNotification(e$message, type="error"); NULL })
})
output$pca_loadings <- renderDT({
req(pca_analysis())
ld <- pca_analysis()$loadings[,1:min(6, ncol(pca_analysis()$loadings))]
datatable(ld, extensions='Buttons',
options=list(scrollX=TRUE, dom='Bfrtip',
buttons=c('copy','excel','csv'), pageLength=10),
caption="PCA Loadings") %>%
formatRound(columns=-1, digits=3)
})
output$pca_summary <- renderDT({
req(pca_analysis())
datatable(pca_analysis()$variance, extensions='Buttons',
options=list(scrollX=TRUE, dom='Bfrtip',
buttons=c('copy','excel','csv'), pageLength=10),
caption="PCA Summary") %>%
formatRound(columns=c("Variance","Prop_Variance","Cumulative"), digits=4)
})
# Clustering
clustering_analysis <- reactive({
req(working_data(), rv$traits, input$n_clusters)
if (length(rv$traits)<2) return(NULL)
tryCatch({
td <- working_data() %>% select(Genotype, all_of(rv$traits)) %>% na.omit()
if (nrow(td) < input$n_clusters+2) return(NULL)
cd <- scale(td %>% select(-Genotype))
rownames(cd) <- td$Genotype
if (input$clustering_method=="kmeans") {
kr <- kmeans(cd, centers=input$n_clusters, nstart=25)
clusters <- kr$cluster; hclust_res <- NULL
} else {
hr <- hclust(dist(cd), method="ward.D2")
clusters <- cutree(hr, k=input$n_clusters); hclust_res <- hr
}
cdf <- data.frame(Genotype=td$Genotype, Cluster=as.factor(clusters))
cs <- td %>% mutate(Cluster=as.factor(clusters)) %>%
group_by(Cluster) %>%
summarise_at(vars(all_of(rv$traits)), mean, na.rm=TRUE) %>%
mutate(Count=as.numeric(table(clusters)))
list(clusters=cdf, summary=cs, data=cd,
method=input$clustering_method, hclust=hclust_res)
}, error=function(e) { showNotification(e$message, type="error"); NULL })
})
output$cluster_plot <- renderPlotly({
req(clustering_analysis())
tryCatch({
cd <- clustering_analysis()$data
clu <- clustering_analysis()$clusters
if (ncol(cd)>2) {
pf <- prcomp(cd)
pd <- data.frame(PC1=pf$x[,1], PC2=pf$x[,2],
Genotype=clu$Genotype, Cluster=clu$Cluster)
p <- ggplot(pd, aes(x=PC1, y=PC2, color=Cluster, text=Genotype)) +
geom_point(size=3, alpha=0.8) +
labs(title="Clustering (PCA Space)", x="PC1", y="PC2")
} else {
pd <- data.frame(X=cd[,1], Y=cd[,2],
Genotype=clu$Genotype, Cluster=clu$Cluster)
p <- ggplot(pd, aes(x=X, y=Y, color=Cluster, text=Genotype)) +
geom_point(size=3, alpha=0.8) +
labs(title="Genotype Clustering", x=rv$traits[1], y=rv$traits[2])
}
p <- p + theme_minimal() +
theme(axis.text=element_text(color="#000"),
axis.title=element_text(color="#000"),
plot.title=element_text(color="#000")) +
scale_color_manual(values=get_color_palette(rv$color_scheme, input$n_clusters))
ggplotly(p, tooltip=c("text","color"), height=rv$plot_height, width=rv$plot_width)
}, error=function(e) { showNotification(e$message, type="error"); NULL })
})
output$dendrogram <- renderPlot({
req(clustering_analysis(), clustering_analysis()$method=="hierarchical")
tryCatch({
hr <- clustering_analysis()$hclust
plot(hr, main="Hierarchical Clustering Dendrogram",
xlab="Genotypes", ylab="Distance", cex=0.8, col="#000000")
rect.hclust(hr, k=input$n_clusters,
border=get_color_palette(rv$color_scheme,2)[2])
}, error=function(e) showNotification(e$message, type="error"))
}, height=function() rv$plot_height, width=function() rv$plot_width)
output$cluster_summary <- renderDT({
req(clustering_analysis())
datatable(clustering_analysis()$summary, extensions='Buttons',
options=list(scrollX=TRUE, dom='Bfrtip',
buttons=c('copy','excel','csv'), pageLength=10),
caption="Cluster Summary Statistics") %>%
formatRound(columns=rv$traits, digits=3)
})
# Stability
stability_analysis <- reactive({
req(rv$data, input$selected_trait) # always use full data for stability
if (!input$selected_trait %in% rv$traits) return(NULL)
tryCatch({
sd2 <- rv$data %>%
select(Genotype, Environment, all_of(input$selected_trait)) %>%
rename(Value=!!input$selected_trait) %>% filter(!is.na(Value)) %>%
group_by(Genotype, Environment) %>%
summarise(Mean_Value=mean(Value, na.rm=TRUE), .groups="drop")
if (nrow(sd2)<10) return(NULL)
om <- mean(sd2$Mean_Value, na.rm=TRUE)
sp <- sd2 %>% group_by(Genotype) %>%
summarise(
Overall_Mean = mean(Mean_Value, na.rm=TRUE),
CV = sd(Mean_Value,na.rm=TRUE)/mean(Mean_Value,na.rm=TRUE)*100,
Ecovalence = sum((Mean_Value-om)^2, na.rm=TRUE),
Min_Value = min(Mean_Value, na.rm=TRUE),
Max_Value = max(Mean_Value, na.rm=TRUE),
Range = Max_Value - Min_Value, .groups="drop") %>%
mutate(CV=round(CV,2), Ecovalence=round(Ecovalence,3),
Stability_Rank=rank(Ecovalence))
em <- sd2 %>% group_by(Environment) %>%
summarise(Env_Mean=mean(Mean_Value, na.rm=TRUE), .groups="drop")
ad <- sd2 %>% left_join(em, by="Environment") %>%
mutate(Env_Index=Env_Mean-om,
GE_Interaction=Mean_Value-om-Env_Index) %>%
left_join(sp %>% select(Genotype, Overall_Mean), by="Genotype")
list(parameters=sp, data=sd2, ammi_data=ad, env_means=em)
}, error=function(e) { showNotification(e$message, type="error"); NULL })
})
output$stability_plot <- renderPlotly({
req(stability_analysis())
tryCatch({
sp <- stability_analysis()$parameters
p <- ggplot(sp, aes(x=Overall_Mean, y=Ecovalence, color=Genotype, text=Genotype)) +
geom_point(size=3, alpha=0.8) +
geom_hline(yintercept=median(sp$Ecovalence), linetype="dashed",
color=get_color_palette(rv$color_scheme,2)[2]) +
geom_vline(xintercept=median(sp$Overall_Mean), linetype="dashed",
color=get_color_palette(rv$color_scheme,2)[2]) +
labs(title=paste("Stability —", input$selected_trait),
x="Mean Performance", y="Ecovalence (Wi²)") +
theme_minimal() +
theme(axis.text=element_text(color="#000"),
axis.title=element_text(color="#000"),
plot.title=element_text(color="#000")) +
scale_color_manual(values=get_color_palette(rv$color_scheme,
length(unique(sp$Genotype))))
ggplotly(p, tooltip=c("text","x","y"), height=rv$plot_height, width=rv$plot_width)
}, error=function(e) { showNotification(e$message, type="error"); NULL })
})
output$ammi_plot <- renderPlotly({
req(stability_analysis())
tryCatch({
ad <- stability_analysis()$ammi_data
n_env <- length(unique(ad$Environment))
n_gen <- length(unique(ad$Genotype))
lbl_angle <- if (n_env > 6) 90 else if (n_env > 3) 45 else 0
lbl_hjust <- if (lbl_angle == 90) 1 else if (lbl_angle == 45) 1 else 0.5
lbl_vjust <- if (lbl_angle == 90) 0.5 else 1
bot_margin <- if (lbl_angle >= 45) 60 else 20
p <- ggplot(ad, aes(x=Environment, y=Mean_Value,
color=Genotype, group=Genotype)) +
geom_line(linewidth=1) + geom_point(size=2) +
labs(title=paste("G×E Interaction —", input$selected_trait),
x=NULL, y="Mean Value") +
theme_minimal() +
theme(
axis.text.x = element_text(angle=lbl_angle, hjust=lbl_hjust,
vjust=lbl_vjust, size=11, color="#000"),
axis.text.y = element_text(size=11, color="#000"),
axis.title = element_text(size=12, color="#000"),
plot.title = element_text(size=13, color="#000", face="bold"),
plot.margin = margin(t=10, r=10, b=bot_margin, l=10),
legend.position = if (n_gen > 25) "none" else "right",
legend.text = element_text(size=8)
) +
scale_color_manual(values=get_color_palette(rv$color_scheme, n_gen)) +
scale_x_discrete(labels=function(x) stringr::str_wrap(x, width=10))
ggplotly(p, tooltip=c("color","x","y"), height=rv$plot_height, width=rv$plot_width) %>%
layout(margin=list(b=bot_margin+20))
}, error=function(e) { showNotification(e$message, type="error"); NULL })
})
output$stability_table <- renderDT({
req(stability_analysis())
sp <- stability_analysis()$parameters
datatable(sp, extensions='Buttons',
options=list(scrollX=TRUE, dom='Bfrtip',
buttons=c('copy','excel','csv'), pageLength=15),
caption=paste("Stability Parameters —", input$selected_trait)) %>%
formatRound(columns=c("Overall_Mean","CV","Ecovalence","Min_Value","Max_Value","Range"), digits=3) %>%
formatStyle("Ecovalence",
backgroundColor=styleInterval(
quantile(sp$Ecovalence, c(.33,.67), na.rm=TRUE),
get_color_palette(rv$color_scheme, 3)))
})
# ═══════════════════════════════════════════════════════════════
# DOWNLOADS
# ═══════════════════════════════════════════════════════════════
# Full / filtered analysis download
output$download_all_results <- downloadHandler(
filename = function() {
paste0("Phenotypic_Analysis_", format(Sys.time(),"%Y%m%d_%H%M%S"), ".xlsx")
},
content = function(file) {
withProgress(message='Preparing download…', value=0, {
tryCatch({
wb <- createWorkbook()
# 1. Data Summary
if (!is.null(rv$data)) {
addWorksheet(wb, "Data_Summary")
writeData(wb, "Data_Summary", data.frame(
Metric=c("Observations","Variables","Genotypes","Environments",
"Traits","Active Environments","Date"),
Value=c(nrow(working_data()), ncol(working_data()),
length(unique(working_data()$Genotype)),
length(unique(working_data()$Environment)),
length(rv$traits),
if(!is.null(rv$active_envs)) paste(rv$active_envs,collapse=", ") else "All",
format(Sys.time(),"%Y-%m-%d %H:%M:%S"))))
}
incProgress(0.1)
if (!is.null(descriptive_stats())) {
addWorksheet(wb,"Descriptive_Statistics")
writeData(wb,"Descriptive_Statistics", descriptive_stats())
}
incProgress(0.2)
if (!is.null(anova_analysis())) {
addWorksheet(wb,"ANOVA_Results")
writeData(wb,"ANOVA_Results", broom::tidy(anova_analysis()$simple_model))
}
incProgress(0.3)
if (!is.null(mixed_model_analysis())) {
addWorksheet(wb,"BLUEs")
writeData(wb,"BLUEs", mixed_model_analysis()$blues)
}
incProgress(0.4)
if (!is.null(heritability_analysis())) {
addWorksheet(wb,"Variance_Components")
writeData(wb,"Variance_Components",
do.call(rbind, lapply(heritability_analysis(), `[[`, "variance_components")))
addWorksheet(wb,"Heritability_Estimates")
writeData(wb,"Heritability_Estimates", data.frame(
Trait = names(heritability_analysis()),
H2_Broad = sapply(heritability_analysis(), function(x) round(x$h2_broad,3)),
H2_Entry = sapply(heritability_analysis(), function(x) round(x$h2_entry,3))))
}
incProgress(0.5)
if (!is.null(correlation_analysis())) {
addWorksheet(wb,"Correlation_Matrix")
writeData(wb,"Correlation_Matrix",
rownames_to_column(as.data.frame(correlation_analysis()$matrix),"Trait"))
addWorksheet(wb,"Pairwise_Correlations")
writeData(wb,"Pairwise_Correlations", correlation_analysis()$table)
}
incProgress(0.6)
if (!is.null(pca_analysis())) {
addWorksheet(wb,"PCA_Scores"); writeData(wb,"PCA_Scores", pca_analysis()$scores)
addWorksheet(wb,"PCA_Variance"); writeData(wb,"PCA_Variance", pca_analysis()$variance)
addWorksheet(wb,"PCA_Loadings"); writeData(wb,"PCA_Loadings", pca_analysis()$loadings)
}
incProgress(0.7)
if (!is.null(clustering_analysis())) {
addWorksheet(wb,"Cluster_Assignments")
writeData(wb,"Cluster_Assignments", clustering_analysis()$clusters)
addWorksheet(wb,"Cluster_Summary")
writeData(wb,"Cluster_Summary", clustering_analysis()$summary)
}
incProgress(0.8)
if (!is.null(stability_analysis())) {
addWorksheet(wb,"Stability_Parameters")
writeData(wb,"Stability_Parameters", stability_analysis()$parameters)
addWorksheet(wb,"GxE_Interaction")
writeData(wb,"GxE_Interaction", stability_analysis()$ammi_data)
}
incProgress(0.9)
saveWorkbook(wb, file, overwrite=TRUE)
incProgress(1)
showNotification("Download ready!", type="message", duration=5)
}, error=function(e) showNotification(paste("Error:", e$message), type="error", duration=10))
})
}
)
# Environment-specific analysis download
output$download_env_results <- downloadHandler(
filename = function() {
paste0("Environment_Analysis_", format(Sys.time(),"%Y%m%d_%H%M%S"), ".xlsx")
},
content = function(file) {
withProgress(message='Preparing env download…', value=0, {
tryCatch({
wb <- createWorkbook()
if (!is.null(env_desc_stats())) {
addWorksheet(wb,"Env_Descriptive_Stats")
writeData(wb,"Env_Descriptive_Stats", env_desc_stats())
}
incProgress(0.2)
if (!is.null(env_means_data())) {
addWorksheet(wb,"Env_Genotype_Means")
writeData(wb,"Env_Genotype_Means", env_means_data())
}
incProgress(0.4)
if (!is.null(env_rank_data())) {
addWorksheet(wb,"Env_Rank_Table")
writeData(wb,"Env_Rank_Table", env_rank_data()$wide_rank)
}
incProgress(0.5)
if (!is.null(env_anova_results())) {
addWorksheet(wb,"Env_ANOVA_Results")
writeData(wb,"Env_ANOVA_Results", env_anova_results())
}
incProgress(0.6)
if (!is.null(env_cor_data())) {
addWorksheet(wb,"Env_Correlations")
writeData(wb,"Env_Correlations", env_cor_data()$table)
}
incProgress(0.8)
if (!is.null(env_blues_data())) {
addWorksheet(wb,"Env_BLUEs")
writeData(wb,"Env_BLUEs", env_blues_data())
}
incProgress(1)
saveWorkbook(wb, file, overwrite=TRUE)
showNotification("Env download ready!", type="message", duration=5)
}, error=function(e) showNotification(paste("Error:", e$message), type="error", duration=10))
})
}
)
} # end server
shinyApp(ui=ui, server=server)
library(shiny)
library(shinyjs)
library(tidyverse)
library(DT)
library(readxl)
library(lme4)
library(emmeans)
library(plotly)
library(shinyWidgets)
library(ggplot2)
library(GGally)
library(corrplot)
library(agricolae)
library(car)
library(broom)
library(cluster)
library(factoextra)
library(pheatmap)
library(RColorBrewer)
library(moments)
library(reshape2)
library(gridExtra)
library(openxlsx)
library(stringr)
library(scales)
# ─────────────────────────────────────────────────────────────────
# UI
# ─────────────────────────────────────────────────────────────────
ui <- fluidPage(
useShinyjs(),
tags$head(
tags$meta(charset = "UTF-8"),
tags$title("Advanced 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;
--secondary: #6B8E23;
--success: #32CD32;
--info: #4169E1;
--warning: #FF8C00;
--danger: #DC143C;
--light: #D1D5DB;
--dark: #2F4F4F;
--background: #FFFFFF;
--card-bg: #FFFFFF;
}
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,.1); border:1px solid rgba(30,58,138,.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,.1); background:var(--card-bg);
padding:1.5rem; border:1px solid rgba(30,58,138,.2); }
.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 .3s; box-shadow:0 4px 8px rgba(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,.3); color:white; }
.btn-success { background:linear-gradient(135deg,#32CD32,#228B22); border:none;
padding:1rem 2.5rem; border-radius:8px; font-weight:600; color:white;
transition:all .3s; box-shadow:0 4px 8px rgba(0,0,0,.1); margin:10px; }
.btn-success:hover { background:linear-gradient(135deg,#228B22,#32CD32);
transform:translateY(-2px); box-shadow:0 6px 12px rgba(50,205,50,.3); color:white; }
.btn-warning { background:linear-gradient(135deg,#FF8C00,#FF6347); border:none;
padding:1rem 2.5rem; border-radius:8px; font-weight:600; color:white;
transition:all .3s; box-shadow:0 4px 8px rgba(0,0,0,.1); margin:10px; }
.btn-warning:hover { background:linear-gradient(135deg,#FF6347,#FF8C00);
transform:translateY(-2px); color:white; }
.download-section { background:linear-gradient(135deg,#E8F5E8,#F0FFF0); padding:20px;
border-radius:10px; border:2px solid var(--success); margin:20px 0; text-align:center; }
.env-filter-box { background:linear-gradient(135deg,#E8F0FF,#F0F4FF); padding:20px;
border-radius:10px; border:2px solid var(--primary); margin:10px 0; }
.sidebar { background:var(--card-bg); color:var(--dark); padding:2rem; height:100vh;
position:fixed; width:300px; box-shadow:5px 0 15px rgba(0,0,0,.1);
border-right:1px solid var(--primary); overflow-y:auto; }
.sidebar-header { padding:20px; background:linear-gradient(135deg,var(--primary),var(--info));
text-align:center; border-bottom:1px solid rgba(0,0,0,.1); border-radius:10px;
margin-bottom:20px; color:white; }
.sidebar-content { padding:15px; }
.main-content { margin-left:300px; padding:20px; width:calc(100% - 300px);
min-height:100vh; background:var(--background); }
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 .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,.1); border:1px solid rgba(30,58,138,.2); margin-bottom:15px; }