diff --git "a/app.R" "b/app.R" --- "a/app.R" +++ "b/app.R" @@ -20,15 +20,18 @@ library(RColorBrewer) library(moments) library(reshape2) library(gridExtra) -library(openxlsx) # Add this library for creating Excel files +library(openxlsx) +# ───────────────────────────────────────────────────────────────── # 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$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; @@ -42,2071 +45,1669 @@ ui <- fluidPage( --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, 0.1); - border: 1px solid rgba(30, 58, 138, 0.2); - } - - h1, h2, h3 { - color: var(--primary); - border-bottom: 2px solid var(--secondary); - padding-bottom: 10px; - margin-bottom: 20px; - font-weight: 700; - } - - .chart-container { - position: relative; - margin-bottom: 20px; - border-radius: 12px; - box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); - background: var(--card-bg); - padding: 1.5rem; - border: 1px solid rgba(30, 58, 138, 0.2); - } - - .insights { - margin-top: 20px; - padding: 20px; - background: #F5F5F5; - border-radius: 8px; - border-left: 4px solid var(--secondary); - font-size: 14px; - } - - .upload-container { - padding: 20px; - text-align: center; - border: 2px dashed var(--primary); - border-radius: 8px; - margin-bottom: 25px; - background: #F9F9F9; - } - - .upload-icon { - font-size: 48px; - color: var(--primary); - margin-bottom: 15px; - } - - .btn-primary { - background: linear-gradient(135deg, var(--primary), var(--info)); - border: none; - padding: 1rem 2.5rem; - border-radius: 8px; - font-weight: 600; - color: white; - transition: all 0.3s; - box-shadow: 0 4px 8px rgba(0,0,0,0.1); - } - - .btn-primary:hover { - background: linear-gradient(135deg, var(--info), var(--primary)); - transform: translateY(-2px); - box-shadow: 0 6px 12px rgba(30, 58, 138, 0.3); - color: white; - } - - .btn-success { - background: linear-gradient(135deg, #32CD32, #228B22); - 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); - margin: 10px; - } - - .btn-success:hover { - background: linear-gradient(135deg, #228B22, #32CD32); - transform: translateY(-2px); - box-shadow: 0 6px 12px rgba(50, 205, 50, 0.3); - 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; - } - - .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,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,0.1); - border-radius: 10px; - margin-bottom: 20px; - color: white; - } - - .sidebar-content { - padding: 15px; - } - - .nav-tabs .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; - text-decoration: none; - cursor: pointer; - } - - .nav-tabs .nav-link:hover, - .nav-tabs .nav-link.active { - color: white; - background: linear-gradient(90deg, var(--primary), var(--info)); - transform: translateX(5px); - box-shadow: 0 4px 8px rgba(30, 58, 138, 0.3); - text-decoration: none; - } - - .nav-tabs .nav-link i { - margin-right: 10px; - width: 20px; - text-align: center; - } - - .main-content { - margin-left: 300px; - padding: 20px; - width: calc(100% - 300px); - 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 !important; - } - - table.dataTable { - border-collapse: collapse; - width: 100%; - font-size: 16px; - background: var(--card-bg); - border-radius: 8px; - overflow: hidden; - } - - th { - background: linear-gradient(45deg, var(--primary), var(--info)); - color: white; - padding: 1.2rem; - font-weight: 700; - text-transform: uppercase; - } - - td { - padding: 1.2rem; - border-bottom: 1px solid #F0F0F0; - transition: background 0.3s; - color: var(--dark); - } - - tr:hover { - background: #F5F5F5; - } - - .dataTables_wrapper { - color: var(--dark); - } - - .status-card { - background: var(--card-bg); - padding: 20px; - border-radius: 10px; - text-align: center; - box-shadow: 0 4px 8px rgba(0,0,0,0.1); - border: 1px solid rgba(30, 58, 138, 0.2); - margin-bottom: 15px; - } - - .status-card i { - font-size: 2rem; - color: var(--primary); - margin-bottom: 10px; - } - - .status-card h4 { - color: var(--primary); - font-size: 1.5rem; - margin: 5px 0; - } - - .status-card p { - color: var(--dark); - margin: 0; - } - - .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; - } - - .tab-pane { - padding: 20px; - } - - .nav-tabs { - border-bottom: none; - } + 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", - div( - class = "sidebar", - div( - class = "sidebar-header", - h3("📊 Advanced Phenotypic Analysis", style = "margin: 0; font-weight: 600; color: white;") - ), - div( - class = "sidebar-content", - selectInput("selected_trait", "Select Trait for Analysis", choices = c(), width = "100%"), - checkboxInput("include_interaction", "Include G×E Interaction", value = FALSE), - hr(style = "border-color: rgba(255,255,255,0.1);"), - - # Download Section - 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"), - p("Excel file with all analysis sheets", style = "margin-top: 10px; font-size: 12px; color: var(--dark);") - ), - - hr(style = "border-color: rgba(255,255,255,0.1);"), - div( - style = "padding: 15px; color: var(--light); font-size: 12px; text-align: center;", - p("Advanced Phenotypic Analysis v2.0"), - p("© 2024 Statistical Genetics Lab") - ) + + 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")) ) ), - - div( - class = "main-content", - tabsetPanel( - id = "main_tabs", - + + # ── 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 formats: .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") - ) - ) + 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"), - 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("Descriptive statistics show central tendency and variability. CV > 20% indicates high variability. Check for outliers and data distribution normality.") - ) - ) + 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)"), - 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("ANOVA tests significance of effects. P < 0.05 indicates significant differences. Check residual plots for model assumptions.") - ) - ) + 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"), - div(class = "chart-container", plotlyOutput("blues_plot", height = "auto")), - DTOutput("blues_table"), - div(class = "insights", - h4("💡 Interpretation"), - p("BLUEs (Best Linear Unbiased Estimators) account for experimental design. Parallel lines indicate no G×E interaction; crossing lines suggest interaction.") - ) - ) + 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"), - 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("Broad-sense heritability (H²) = genetic variance / total variance. Values > 0.6 indicate high heritability, suitable for selection.") - ) - ) + 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"), - 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("Correlation matrix shows relationships between traits. Values near ±1 indicate strong relationships. Use for indirect selection strategies.") - ) - ) + 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"), - 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("Clustering groups similar genotypes based on trait performance. Use for identifying genetic groups and breeding strategies.") - ) - ) + 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"), - 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("PCA reduces dimensionality while preserving variance. First few PCs explain most variation. Loadings show trait contributions to each PC.") - ) - ) + 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("Stability parameters identify genotypes with consistent performance across environments. Low Ecovalence (Wi²) and high yield indicate stable, high-performing genotypes.") - ) - ) + 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 the height and width of all plots using the sliders. Choose a color scheme to update the appearance of plots. Click 'Apply Customization' to update the visualizations.") - ) - ) + 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 Function +# ───────────────────────────────────────────────────────────────── +# SERVER +# ───────────────────────────────────────────────────────────────── server <- function(input, output, session) { - - # Reactive values to store data, results, and customization settings + rv <- reactiveValues( - data = NULL, - traits = NULL, - anova_results = NULL, - blues = NULL, - variance_components = NULL, - heritability = NULL, - correlations = NULL, - pca_results = NULL, - cluster_results = NULL, - stability_results = NULL, - plot_height = 600, - plot_width = 800, - color_scheme = "default" + 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" ) - - # Function to get color palette based on selected scheme + + # ── Helpers ────────────────────────────────────────────────── get_color_palette <- function(scheme, n) { + n <- max(n, 1) if (scheme == "default") { - return(rep(c("#00FF00", "#FF0000", "#FFFF00"), length.out = n)) + return(colorRampPalette(c("#1E3A8A","#6B8E23","#FF8C00","#DC143C","#4169E1"))(n)) } else if (scheme == "blue") { - return(colorRampPalette(c("#E6F0FA", "#1E3A8A"))(n)) + return(colorRampPalette(c("#E6F0FA","#1E3A8A"))(n)) } else if (scheme == "viridis") { - return(viridis::viridis(n)) + return(viridisLite::viridis(n)) } else if (scheme == "plasma") { - return(viridis::plasma(n)) + return(viridisLite::plasma(n)) } else if (scheme == "magma") { - return(viridis::magma(n)) + 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 { - return(rep(c("#00FF00", "#FF0000", "#FFFF00"), length.out = n)) + 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())) + }) } - - # Observe customization inputs + + 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$plot_width <- input$plot_width rv$color_scheme <- input$color_scheme - showNotification("Customization applied successfully!", type = "message") + showNotification("Customization applied!", type = "message") }) - - # Data validation function + + # ── Data Validation ────────────────────────────────────────── validate_data <- function(data) { validation <- list() - - # Check required columns - 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 required columns:", paste(missing_cols, collapse = ", "))) - } - - # Check data types and convert if necessary - if ("Genotype" %in% names(data)) { - if (!is.factor(data$Genotype)) { - data$Genotype <- as.factor(data$Genotype) - validation$warnings <- c(validation$warnings, "Genotype converted to factor") - } - } - - if ("Environment" %in% names(data)) { - if (!is.factor(data$Environment)) { - data$Environment <- as.factor(data$Environment) - validation$warnings <- c(validation$warnings, "Environment converted to factor") - } - } - - if ("Rep" %in% names(data)) { - if (!is.factor(data$Rep)) { - data$Rep <- as.factor(data$Rep) - validation$warnings <- c(validation$warnings, "Rep converted to factor") - } - } - - if ("Block" %in% names(data)) { - if (!is.factor(data$Block)) { - data$Block <- as.factor(data$Block) - validation$warnings <- c(validation$warnings, "Block converted to factor") - } - } - - # Check for sufficient levels - if ("Genotype" %in% names(data)) { - n_geno <- length(unique(data$Genotype)) - if (n_geno < 3) { - validation$errors <- c(validation$errors, paste("Insufficient genotypes (", n_geno, "); need at least 3")) + 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 ("Environment" %in% names(data)) { - n_env <- length(unique(data$Environment)) - if (n_env < 2) { - validation$errors <- c(validation$errors, paste("Insufficient environments (", n_env, "); need at least 2")) - } - } - - # Check for missing data - missing_summary <- data %>% - summarise_all(~sum(is.na(.))) %>% - pivot_longer(everything(), names_to = "Variable", values_to = "Missing") %>% - filter(Missing > 0) - - if (nrow(missing_summary) > 0) { - validation$warnings <- c(validation$warnings, paste("Variables with missing data:", paste(missing_summary$Variable, collapse = ", "))) - } - - # Check for balanced design - if (all(required_cols %in% names(data))) { - design_check <- data %>% - group_by(Genotype, Environment) %>% - summarise(n = n(), .groups = "drop") - - if (length(unique(design_check$n)) > 1) { - validation$warnings <- c(validation$warnings, "Unbalanced design detected") - } - } - - # Identify numeric trait columns starting from column 10 + 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) { - trait_cols <- names(data)[10:ncol(data)] - numeric_traits <- trait_cols[sapply(data[trait_cols], is.numeric)] - - if (length(numeric_traits) == 0) { - validation$errors <- c(validation$errors, "No numeric trait columns found starting from column 10") - } else { - validation$success <- c(validation$success, paste("Found", length(numeric_traits), "numeric trait columns starting from column 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, "Input data has fewer than 10 columns") + validation$errors <- c(validation$errors, "Data has fewer than 10 columns") } - - list(data = data, validation = validation) + list(data=data, validation=validation) } - - # File upload observer + + # ── File Upload ────────────────────────────────────────────── observeEvent(input$data_file, { req(input$data_file) - - withProgress(message = 'Processing data...', value = 0, { - incProgress(0.2, detail = "Reading 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) + data <- read.csv(input$data_file$datapath, stringsAsFactors=FALSE) } else { - data <- read_excel(input$data_file$datapath) - data <- as.data.frame(data) + data <- as.data.frame(read_excel(input$data_file$datapath)) } - - incProgress(0.4, detail = "Validating data...") - - # Validate data - result <- validate_data(data) - rv$data <- result$data - validation_results <- result$validation - - # Identify trait columns starting from column 10 - if (ncol(data) >= 10) { - trait_cols <- names(data)[10:ncol(data)] - rv$traits <- trait_cols[sapply(data[trait_cols], is.numeric)] - } else { - rv$traits <- character(0) - } - - incProgress(0.6, detail = "Updating interface...") - - # Update trait selection + 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) - - # Show data preview + selected = if (length(rv$traits)>0) rv$traits[1] else NULL) shinyjs::show("data_preview_section") - - incProgress(0.8, detail = "Generating summary...") - - # Update summary statistics - 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" - }) - - incProgress(1, detail = "Complete!") - - # Show validation messages as notifications - if (length(validation_results$errors) > 0) { - showNotification(paste(validation_results$errors, collapse = "; "), type = "error") - } - - if (length(validation_results$warnings) > 0) { - showNotification(paste(validation_results$warnings, collapse = "; "), type = "warning") - } - - output$upload_status <- renderUI({ - div(class = "success-message", - icon("check-circle"), - paste("Successfully loaded", nrow(rv$data), "observations with", length(rv$traits), "traits")) - }) - - showNotification("Data uploaded successfully!", type = "message") - - }, 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") + 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") }) }) }) - - # Data preview table + + # ── 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)" - ) + datatable(rv$data[1:min(100,nrow(rv$data)),], + options=list(scrollX=TRUE, pageLength=10, dom='frtip'), + caption="Data Preview (First 100 rows)") }) - - # Descriptive statistics - descriptive_stats <- reactive({ - req(rv$data, rv$traits) - - withProgress(message = 'Computing Descriptive Statistics...', value = 0, { - incProgress(0.3, detail = "Preparing data...") - - tryCatch({ - incProgress(0.6, detail = "Calculating statistics...") - - stats <- rv$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, 0.25, na.rm = TRUE), 3), - Q3 = round(quantile(Value, 0.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" - ) - - incProgress(1, detail = "Complete!") - stats - - }, error = function(e) { - showNotification(paste("Error in descriptive statistics:", e$message), type = "error") - return(NULL) + + # ═══════════════════════════════════════════════════════════════ + # 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)) + p <- ggplot(df, aes(x=Environment, y=Value, fill=Environment)) + + geom_boxplot(alpha=0.7, outlier.colour="red", outlier.size=2) + + geom_jitter(aes(color=Genotype), width=0.2, alpha=0.4, size=1) + + labs(title=paste("Boxplot of", trait, "per Environment"), + x="Environment", y=trait) + + 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"), + legend.position="none") + + scale_fill_manual(values=get_color_palette(rv$color_scheme, + length(unique(df$Environment)))) + ggplotly(p, height=rv$plot_height, width=rv$plot_width) + }, 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)) + p <- ggplot(df, aes(x=Environment, y=Value, fill=Environment)) + + geom_violin(alpha=0.7, trim=FALSE) + + geom_boxplot(width=0.1, fill="white", alpha=0.8) + + stat_summary(fun=mean, geom="point", shape=18, size=3, color="#1E3A8A") + + labs(title=paste("Violin Plot of", trait, "per Environment"), + x="Environment", y=trait) + + 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"), + legend.position="none") + + scale_fill_manual(values=get_color_palette(rv$color_scheme, + length(unique(df$Environment)))) + ggplotly(p, height=rv$plot_height, width=rv$plot_width) + }, 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({ + 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="Genotype", y="Mean Value") + + theme_minimal() + + theme(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, + length(unique(df$Environment)))) + ggplotly(p, height=rv$plot_height, width=rv$plot_width) + }, 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({ + p <- ggplot(df, aes(x=Environment, y=Rank, color=Genotype, group=Genotype)) + + geom_line(size=1, alpha=0.8) + + geom_point(size=3, alpha=0.9) + + scale_y_reverse(breaks=1:length(unique(df$Genotype))) + + labs(title=paste("Genotype Rank Across Environments —", input$selected_trait), + x="Environment", y="Rank (1 = Best)") + + 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_color_manual(values=get_color_palette(rv$color_scheme, + length(unique(df$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$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 }) }) - - # Descriptive statistics table + + 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({ + p <- ggplot(df, aes(x=reorder(Genotype, BLUE), y=BLUE, color=Environment)) + + geom_point(size=3, alpha=0.8) + + geom_errorbar(aes(ymin=BLUE-SE, ymax=BLUE+SE), width=0.3, alpha=0.7) + + facet_wrap(~Environment, scales="free_x") + + coord_flip() + + labs(title=paste("Within-Environment BLUEs —", input$selected_trait), + x="Genotype", y="BLUE") + + theme_minimal() + + theme(axis.text=element_text(color="#000"), + axis.title=element_text(color="#000"), + plot.title=element_text(color="#000"), + legend.position="none") + + scale_color_manual(values=get_color_palette(rv$color_scheme, + length(unique(df$Environment)))) + ggplotly(p, height=rv$plot_height, width=rv$plot_width) + }, 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', 'pdf'), - pageLength = 15, - columnDefs = list(list(className = 'dt-center', targets = '_all')) - ), - caption = "Descriptive Statistics for All Traits" - ) %>% - formatRound(columns = c("Mean", "Median", "SD", "CV", "Min", "Max", "Q1", "Q3", "Skewness", "Kurtosis"), digits = 3) + 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) }) - - # Descriptive statistics plot + output$descriptives_plot <- renderPlotly({ - req(rv$data, input$selected_trait) + req(working_data(), input$selected_trait) if (!input$selected_trait %in% rv$traits) return(NULL) - tryCatch({ - p <- rv$data %>% + p <- working_data() %>% select(Genotype, Environment, all_of(input$selected_trait)) %>% - rename(Value = !!input$selected_trait) %>% - filter(!is.na(Value)) %>% - ggplot(aes(x = Environment, y = Value, fill = Environment)) + - geom_boxplot(alpha = 0.7) + - geom_jitter(aes(color = Genotype), width = 0.2, alpha = 0.5, size = 1) + - labs(title = paste("Distribution of", input$selected_trait, "by Environment"), - x = "Environment", y = input$selected_trait) + + rename(Value=!!input$selected_trait) %>% filter(!is.na(Value)) %>% + ggplot(aes(x=Environment, y=Value, fill=Environment)) + + geom_boxplot(alpha=0.7) + + geom_jitter(aes(color=Genotype), width=0.2, alpha=0.5, size=1) + + labs(title=paste("Distribution of", input$selected_trait, "by Environment"), + x="Environment", y=input$selected_trait) + theme_minimal() + - theme( - axis.text = element_text(color = "#000000"), - axis.title = element_text(color = "#000000"), - plot.title = element_text(color = "#000000"), - axis.text.x = element_text(angle = 45, hjust = 1), - legend.position = "none" - ) + - scale_fill_manual(values = get_color_palette(rv$color_scheme, length(unique(rv$data$Environment)))) + - scale_color_manual(values = get_color_palette(rv$color_scheme, length(unique(rv$data$Genotype)))) - - ggplotly(p, tooltip = c("x", "y", "color"), height = rv$plot_height, width = rv$plot_width) - - }, error = function(e) { - showNotification(paste("Error in descriptive plot:", e$message), type = "error") - return(NULL) - }) + 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"), + legend.position="none") + + scale_fill_manual(values=get_color_palette(rv$color_scheme, + length(unique(working_data()$Environment)))) + ggplotly(p, height=rv$plot_height, width=rv$plot_width) + }, error=function(e) { showNotification(e$message, type="error"); NULL }) }) - - # Distribution plot (histogram with density) + output$distribution_plot <- renderPlotly({ - req(rv$data, input$selected_trait) + req(working_data(), input$selected_trait) if (!input$selected_trait %in% rv$traits) return(NULL) - tryCatch({ - trait_data <- rv$data[[input$selected_trait]] - trait_data <- trait_data[!is.na(trait_data)] - - if (length(trait_data) < 2) { - showNotification("Insufficient data for distribution plot", type = "error") - return(NULL) - } - - p <- data.frame(Value = trait_data) %>% - ggplot(aes(x = Value)) + - geom_histogram(aes(y = after_stat(density)), bins = 30, fill = get_color_palette(rv$color_scheme, 1)[1], alpha = 0.7) + - geom_density(color = get_color_palette(rv$color_scheme, 1)[2], size = 1) + - labs(title = paste("Distribution of", input$selected_trait), - x = input$selected_trait, y = "Density") + + 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 = "#000000"), - axis.title = element_text(color = "#000000"), - plot.title = element_text(color = "#000000") - ) - - ggplotly(p, height = rv$plot_height, width = rv$plot_width) - - }, error = function(e) { - showNotification(paste("Error in distribution plot:", e$message), type = "error") - return(NULL) - }) + 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 analysis + + # ANOVA anova_analysis <- reactive({ - req(rv$data, input$selected_trait) - - withProgress(message = 'Running ANOVA...', value = 0, { - incProgress(0.3, detail = "Preparing data...") - - if (!input$selected_trait %in% rv$traits) return(NULL) - - tryCatch({ - incProgress(0.5, detail = "Fitting model...") - - trait_data <- rv$data %>% - select(Genotype, Environment, Rep, Block, all_of(input$selected_trait)) %>% - rename(Value = !!input$selected_trait) %>% - filter(!is.na(Value)) %>% - mutate( - Genotype = as.factor(Genotype), - Environment = as.factor(Environment), - Rep = as.factor(Rep), - Block = as.factor(Block) - ) - - if (nrow(trait_data) < 10) { - showNotification("Insufficient data for ANOVA (need at least 10 observations)", type = "error") - return(NULL) - } - - incProgress(0.7, detail = "Computing residuals...") - - if (input$include_interaction) { - model <- aov(Value ~ Environment + Genotype + Environment:Genotype + Error(Rep/Block), data = trait_data) - } else { - model <- aov(Value ~ Environment + Genotype + Error(Rep/Block), data = trait_data) - } - - anova_summary <- summary(model) - - simple_model <- lm(Value ~ Environment + Genotype, data = trait_data) - residuals_data <- data.frame( - Fitted = fitted(simple_model), - Residuals = residuals(simple_model), - Standardized_Residuals = rstandard(simple_model), - Genotype = trait_data$Genotype - ) - - incProgress(1, detail = "Complete!") - - list(model = model, summary = anova_summary, residuals = residuals_data, simple_model = simple_model) - - }, error = function(e) { - showNotification(paste("ANOVA Error:", e$message), type = "error") - return(NULL) - }) - }) + 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 }) }) - - # ANOVA table + output$anova_table <- renderDT({ req(anova_analysis()) - tryCatch({ - anova_df <- broom::tidy(anova_analysis()$simple_model) - - datatable( - anova_df, - extensions = 'Buttons', - options = list( - scrollX = TRUE, - dom = 'Bfrtip', - buttons = c('copy', 'excel', 'csv'), - pageLength = 10, - columnDefs = list(list(className = 'dt-center', targets = '_all')) - ), - caption = paste("ANOVA Table for", 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(paste("Error in ANOVA table:", e$message), type = "error") - return(NULL) - }) + 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 }) }) - - # Residual plot + output$residual_plot <- renderPlotly({ req(anova_analysis()) - tryCatch({ - res_data <- anova_analysis()$residuals - - p <- ggplot(res_data, 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, 1)[2]) + - geom_hline(yintercept = 0, linetype = "dashed", color = get_color_palette(rv$color_scheme, 1)[2]) + - labs(title = "Residuals vs Fitted Values", - x = "Fitted Values", y = "Residuals") + + 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 = "#000000"), - axis.title = element_text(color = "#000000"), - plot.title = element_text(color = "#000000") - ) + - scale_color_manual(values = get_color_palette(rv$color_scheme, length(unique(res_data$Genotype)))) - - ggplotly(p, tooltip = c("color", "x", "y"), height = rv$plot_height, width = rv$plot_width) - - }, error = function(e) { - showNotification(paste("Error in residual plot:", e$message), type = "error") - return(NULL) - }) + 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 }) }) - - # Q-Q plot + output$qq_plot <- renderPlotly({ req(anova_analysis()) - tryCatch({ - res_data <- anova_analysis()$residuals - - p <- ggplot(res_data, aes(sample = Standardized_Residuals, color = Genotype)) + - stat_qq(size = 1) + - stat_qq_line(color = get_color_palette(rv$color_scheme, 1)[2]) + - labs(title = "Normal Q-Q Plot", - x = "Theoretical Quantiles", y = "Sample Quantiles") + + 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 = "#000000"), - axis.title = element_text(color = "#000000"), - plot.title = element_text(color = "#000000") - ) + - scale_color_manual(values = get_color_palette(rv$color_scheme, length(unique(res_data$Genotype)))) - - ggplotly(p, tooltip = c("color", "x", "y"), height = rv$plot_height, width = rv$plot_width) - - }, error = function(e) { - showNotification(paste("Error in Q-Q plot:", e$message), type = "error") - return(NULL) - }) + 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 model analysis and BLUEs + + # Mixed Models / BLUEs mixed_model_analysis <- reactive({ - req(rv$data, input$selected_trait) - - withProgress(message = 'Running Mixed Model Analysis...', value = 0, { - incProgress(0.3, detail = "Preparing data...") - - if (!input$selected_trait %in% rv$traits) return(NULL) - - tryCatch({ - incProgress(0.5, detail = "Fitting mixed model...") - - trait_data <- rv$data %>% - select(Genotype, Environment, Rep, Block, all_of(input$selected_trait)) %>% - rename(Value = !!input$selected_trait) %>% - filter(!is.na(Value)) %>% - mutate( - Genotype = as.factor(Genotype), - Environment = as.factor(Environment), - Rep = as.factor(Rep), - Block = as.factor(Block) - ) - - if (nrow(trait_data) < 10) { - showNotification("Insufficient data for mixed model (need at least 10 observations)", type = "error") - return(NULL) - } - - incProgress(0.7, detail = "Calculating BLUEs...") - - if (input$include_interaction) { - model <- lmer(Value ~ Environment + Genotype + Environment:Genotype + (1|Rep) + (1|Block), data = trait_data) - } else { - model <- lmer(Value ~ Environment + Genotype + (1|Rep) + (1|Block), data = trait_data) - } - - blues <- emmeans(model, ~ Genotype | Environment) - blues_df <- as.data.frame(blues) %>% - select(Genotype, Environment, emmean, SE) %>% - rename(BLUE = emmean) - - incProgress(1, detail = "Complete!") - - list(model = model, blues = blues_df) - - }, error = function(e) { - showNotification(paste("Mixed Model Error:", e$message), type = "error") - return(NULL) - }) - }) + 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 }) }) - - # BLUEs plot + output$blues_plot <- renderPlotly({ req(mixed_model_analysis()) - tryCatch({ - blues_data <- mixed_model_analysis()$blues - - p <- ggplot(blues_data, aes(x = Environment, y = BLUE, color = Genotype, group = Genotype)) + - geom_line(size = 1) + - geom_point(size = 1) + - labs(title = paste("BLUEs for", input$selected_trait), - x = "Environment", y = "BLUE Value") + + df <- mixed_model_analysis()$blues + 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="Environment", y="BLUE") + theme_minimal() + - theme( - axis.text = element_text(color = "#000000"), - axis.title = element_text(color = "#000000"), - plot.title = element_text(color = "#000000"), - axis.text.x = element_text(angle = 45, hjust = 1) - ) + - scale_color_manual(values = get_color_palette(rv$color_scheme, length(unique(blues_data$Genotype)))) - - ggplotly(p, tooltip = c("color", "x", "y"), height = rv$plot_height, width = rv$plot_width) - - }, error = function(e) { - showNotification(paste("Error in BLUEs plot:", e$message), type = "error") - return(NULL) - }) + 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_color_manual(values=get_color_palette(rv$color_scheme, + length(unique(df$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 }) }) - - # BLUEs table + output$blues_table <- renderDT({ req(mixed_model_analysis()) - - tryCatch({ - datatable( - mixed_model_analysis()$blues, - extensions = 'Buttons', - options = list( - scrollX = TRUE, - dom = 'Bfrtip', - buttons = c('copy', 'excel', 'csv'), - pageLength = 15, - columnDefs = list(list(className = 'dt-center', targets = '_all')) - ), - caption = paste("BLUEs for", input$selected_trait) - ) %>% - formatRound(columns = c("BLUE", "SE"), digits = 3) - - }, error = function(e) { - showNotification(paste("Error in BLUEs table:", e$message), type = "error") - return(NULL) - }) + 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 analysis + + # Heritability heritability_analysis <- reactive({ - req(rv$data, rv$traits) - - withProgress(message = 'Running Heritability Analysis...', value = 0, { - incProgress(0.2, detail = "Preparing traits...") - - if (length(rv$traits) < 1) { - showNotification("No numeric traits available for heritability analysis", type = "error") - return(NULL) - } - - herit_results <- list() - - for (trait in rv$traits) { - tryCatch({ - incProgress(0.4, detail = paste("Processing", trait, "...")) - - trait_data <- rv$data %>% - select(Genotype, Environment, Rep, Block, all_of(trait)) %>% - rename(Value = !!trait) %>% - filter(!is.na(Value)) %>% - mutate( - Genotype = as.factor(Genotype), - Environment = as.factor(Environment), - Rep = as.factor(Rep), - Block = as.factor(Block) - ) - - if (nrow(trait_data) < 10) { - showNotification(paste("Insufficient data for", trait, "(need at least 10 observations)"), type = "error") - next - } - - incProgress(0.6, detail = paste("Fitting model for", trait, "...")) - - model <- lmer(Value ~ (1|Genotype) + (1|Environment) + (1|Genotype:Environment) + (1|Rep) + (1|Block), data = trait_data) - - var_comp <- as.data.frame(VarCorr(model)) - var_comp$Trait <- trait - - var_g <- var_comp$vcov[var_comp$grp == "Genotype"] - var_ge <- var_comp$vcov[var_comp$grp == "Genotype:Environment"] - var_e <- var_comp$vcov[var_comp$grp == "Residual"] - - var_g <- ifelse(length(var_g) == 0, 0, var_g) - var_ge <- ifelse(length(var_ge) == 0, 0, var_ge) - var_e <- ifelse(length(var_e) == 0, 1, var_e) - - h2_broad <- var_g / (var_g + var_ge + var_e) - - n_env <- length(unique(trait_data$Environment)) - n_rep <- length(unique(trait_data$Rep)) - h2_entry <- var_g / (var_g + (var_ge / n_env) + (var_e / (n_env * n_rep))) - - herit_results[[trait]] <- list( - trait = trait, - variance_components = var_comp, - h2_broad = h2_broad, - h2_entry = h2_entry - ) - - incProgress(0.9, detail = paste("Completed", trait)) - - }, error = function(e) { - showNotification(paste("Heritability error for", trait, ":", e$message), type = "error") - }) - } - - incProgress(1, detail = "Complete!") - - if (length(herit_results) == 0) return(NULL) - - herit_results - }) + 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 }) - - # Variance components table + output$variance_components <- renderDT({ req(heritability_analysis()) - tryCatch({ - all_var_comp <- do.call(rbind, lapply(heritability_analysis(), function(x) x$variance_components)) - - datatable( - all_var_comp, - extensions = 'Buttons', - options = list( - scrollX = TRUE, - dom = 'Bfrtip', - buttons = c('copy', 'excel', 'csv'), - pageLength = 10, - columnDefs = list(list(className = 'dt-center', targets = '_all')) - ), - caption = "Variance Components" - ) %>% - formatRound(columns = c("vcov", "sdcor"), digits = 4) - - }, error = function(e) { - showNotification(paste("Error in variance components:", e$message), type = "error") - return(NULL) - }) + 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 }) }) - - # Heritability table + output$heritability_table <- renderDT({ req(heritability_analysis()) - tryCatch({ - herit_summary <- 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( - herit_summary, - extensions = 'Buttons', - options = list( - scrollX = TRUE, - dom = 'Bfrtip', - buttons = c('copy', 'excel', 'csv'), - pageLength = 10, - columnDefs = list(list(className = 'dt-center', targets = '_all')) - ), - caption = "Heritability Estimates" - ) %>% - formatRound(columns = c("H2_Broad", "H2_Entry"), digits = 3) %>% - formatStyle(c("H2_Broad", "H2_Entry"), - backgroundColor = styleInterval(c(0.3, 0.6), c("#ffebee", "#fff3e0", "#e8f5e8"))) - - }, error = function(e) { - showNotification(paste("Error in heritability table:", e$message), type = "error") - return(NULL) - }) + 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 }) }) - - # Heritability plot + output$heritability_plot <- renderPlotly({ req(heritability_analysis()) - tryCatch({ - herit_summary <- data.frame( - Trait = names(heritability_analysis()), + 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(herit_summary, aes(x = Trait, y = Heritability, fill = Type)) + - geom_col(position = "dodge", alpha = 0.8) + - labs(title = "Heritability Estimates by Trait", - x = "Trait", y = "Heritability") + + 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 = element_text(color = "#000000"), - axis.title = element_text(color = "#000000"), - plot.title = element_text(color = "#000000"), - axis.text.x = element_text(angle = 45, hjust = 1) - ) + - scale_fill_manual(values = get_color_palette(rv$color_scheme, 2)) + - geom_hline(yintercept = c(0.3, 0.6), linetype = "dashed", color = get_color_palette(rv$color_scheme, 1)[2]) - - ggplotly(p, height = rv$plot_height, width = rv$plot_width) - - }, error = function(e) { - showNotification(paste("Error in heritability plot:", e$message), type = "error") - return(NULL) - }) + 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 }) }) - - # Correlation analysis + + # Correlations correlation_analysis <- reactive({ - req(rv$data, rv$traits) - - withProgress(message = 'Computing Correlations...', value = 0, { - incProgress(0.3, detail = "Preparing data...") - - if (length(rv$traits) < 2) { - showNotification("Need at least 2 numeric traits for correlation analysis", type = "error") - return(NULL) - } - - tryCatch({ - incProgress(0.6, detail = "Calculating correlations...") - - trait_data <- rv$data %>% - select(all_of(rv$traits)) %>% - na.omit() - - if (nrow(trait_data) < 10) { - showNotification("Insufficient data for correlation analysis (need at least 10 observations)", type = "error") - return(NULL) - } - - cor_matrix <- cor(trait_data, use = "complete.obs") - - cor_table <- cor_matrix %>% - 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)) - - incProgress(1, detail = "Complete!") - - list(matrix = cor_matrix, table = cor_table, data = trait_data) - - }, error = function(e) { - showNotification(paste("Error in correlation analysis:", e$message), type = "error") - return(NULL) - }) - }) + 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 }) }) - - # Correlation heatmap + output$correlation_heatmap <- renderPlot({ req(correlation_analysis()) - tryCatch({ - cor_matrix <- correlation_analysis()$matrix - - corrplot::corrplot(cor_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(paste("Error in correlation heatmap:", e$message), type = "error") - return(NULL) - }) - }, height = function() rv$plot_height, width = function() rv$plot_width) - - # Correlation table + 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()) - - tryCatch({ - datatable( - correlation_analysis()$table, - extensions = 'Buttons', - options = list( - scrollX = TRUE, - dom = 'Bfrtip', - buttons = c('copy', 'excel', 'csv'), - pageLength = 15, - columnDefs = list(list(className = 'dt-center', targets = '_all')) - ), - caption = "Pairwise Trait Correlations" - ) %>% - formatRound(columns = c("Correlation", "Abs_Correlation"), digits = 3) %>% - formatStyle("Correlation", - backgroundColor = styleInterval(c(-0.7, -0.3, 0.3, 0.7), get_color_palette(rv$color_scheme, 5))) - - }, error = function(e) { - showNotification(paste("Error in correlation table:", e$message), type = "error") - return(NULL) - }) + 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) }) - - # Correlation network plot + output$correlation_network <- renderPlot({ req(correlation_analysis()) - tryCatch({ - cor_matrix <- correlation_analysis()$matrix - - corrplot::corrplot(cor_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(paste("Error in correlation network:", e$message), type = "error") - return(NULL) - }) - }, height = function() rv$plot_height, width = function() rv$plot_width) - - # PCA analysis + 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(rv$data, rv$traits) - - withProgress(message = 'Running PCA Analysis...', value = 0, { - incProgress(0.3, detail = "Preparing data...") - - if (length(rv$traits) < 2) { - showNotification("Need at least 2 numeric traits for PCA", type = "error") - return(NULL) - } - - tryCatch({ - incProgress(0.6, detail = "Computing PCA...") - - trait_data <- rv$data %>% - select(Genotype, all_of(rv$traits)) %>% - na.omit() - - if (nrow(trait_data) < 10) { - showNotification("Insufficient data for PCA (need at least 10 observations)", type = "error") - return(NULL) - } - - pca_data <- trait_data %>% - select(-Genotype) %>% - scale() - - pca_result <- prcomp(pca_data, center = FALSE, scale. = FALSE) - - pca_scores <- as.data.frame(pca_result$x) %>% - mutate(Genotype = trait_data$Genotype) - - var_explained <- data.frame( - PC = paste0("PC", 1:length(pca_result$sdev)), - Variance = pca_result$sdev^2, - Prop_Variance = pca_result$sdev^2 / sum(pca_result$sdev^2), - Cumulative = cumsum(pca_result$sdev^2 / sum(pca_result$sdev^2)) - ) - - loadings <- as.data.frame(pca_result$rotation) %>% - rownames_to_column("Trait") - - incProgress(1, detail = "Complete!") - - list(scores = pca_scores, variance = var_explained, loadings = loadings, result = pca_result) - - }, error = function(e) { - showNotification(paste("Error in PCA analysis:", e$message), type = "error") - return(NULL) - }) - }) + 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 }) }) - - # PCA plot + output$pca_plot <- renderPlotly({ req(pca_analysis()) - tryCatch({ - pca_scores <- pca_analysis()$scores - - p <- ggplot(pca_scores, aes(x = PC1, y = PC2, color = Genotype, text = Genotype)) + - geom_point(size = 1, alpha = 0.7) + - 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), "%)")) + + 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 = "#000000"), - axis.title = element_text(color = "#000000"), - plot.title = element_text(color = "#000000") - ) + - scale_color_manual(values = get_color_palette(rv$color_scheme, length(unique(pca_scores$Genotype)))) - - ggplotly(p, tooltip = c("text", "x", "y"), height = rv$plot_height, width = rv$plot_width) - - }, error = function(e) { - showNotification(paste("Error in PCA plot:", e$message), type = "error") - return(NULL) - }) + 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 }) }) - - # PCA variance plot + output$pca_variance_plot <- renderPlotly({ req(pca_analysis()) - tryCatch({ - var_data <- pca_analysis()$variance - - p <- ggplot(var_data[1:min(10, nrow(var_data)), ], aes(x = PC, y = Prop_Variance)) + - geom_col(fill = get_color_palette(rv$color_scheme, 1)[1], alpha = 0.8) + - geom_line(aes(y = Cumulative, group = 1), color = get_color_palette(rv$color_scheme, 1)[2], size = 1) + - geom_point(aes(y = Cumulative), color = get_color_palette(rv$color_scheme, 1)[2], size = 1) + - labs(title = "PCA Variance Explained", - x = "Principal Component", y = "Proportion of Variance") + + 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 = element_text(color = "#000000"), - axis.title = element_text(color = "#000000"), - plot.title = element_text(color = "#000000"), - axis.text.x = element_text(angle = 45, hjust = 1) - ) - - ggplotly(p, height = rv$plot_height, width = rv$plot_width) - - }, error = function(e) { - showNotification(paste("Error in PCA variance plot:", e$message), type = "error") - return(NULL) - }) + 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 }) }) - - # PCA loadings table + output$pca_loadings <- renderDT({ req(pca_analysis()) - - tryCatch({ - loadings_data <- pca_analysis()$loadings[, 1:min(5, ncol(pca_analysis()$loadings))] - - datatable( - loadings_data, - extensions = 'Buttons', - options = list( - scrollX = TRUE, - dom = 'Bfrtip', - buttons = c('copy', 'excel', 'csv'), - pageLength = 10, - columnDefs = list(list(className = 'dt-center', targets = '_all')) - ), - caption = "PCA Loadings" - ) %>% - formatRound(columns = -1, digits = 3) - - }, error = function(e) { - showNotification(paste("Error in PCA loadings:", e$message), type = "error") - return(NULL) - }) + 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) }) - - # PCA summary table + output$pca_summary <- renderDT({ req(pca_analysis()) - - tryCatch({ - datatable( - pca_analysis()$variance, - extensions = 'Buttons', - options = list( - scrollX = TRUE, - dom = 'Bfrtip', - buttons = c('copy', 'excel', 'csv'), - pageLength = 10, - columnDefs = list(list(className = 'dt-center', targets = '_all')) - ), - caption = "PCA Summary" - ) %>% - formatRound(columns = c("Variance", "Prop_Variance", "Cumulative"), digits = 4) - - }, error = function(e) { - showNotification(paste("Error in PCA summary:", e$message), type = "error") - return(NULL) - }) + 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 analysis + + # Clustering clustering_analysis <- reactive({ - req(rv$data, rv$traits, input$n_clusters) - - withProgress(message = 'Running Clustering Analysis...', value = 0, { - incProgress(0.3, detail = "Preparing data...") - - if (length(rv$traits) < 2) { - showNotification("Need at least 2 numeric traits for clustering", type = "error") - return(NULL) + 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 } - - tryCatch({ - incProgress(0.6, detail = "Performing clustering...") - - trait_data <- rv$data %>% - select(Genotype, all_of(rv$traits)) %>% - na.omit() - - if (nrow(trait_data) < input$n_clusters + 2) { - showNotification("Insufficient data for clustering (need more observations than clusters)", type = "error") - return(NULL) - } - - cluster_data <- trait_data %>% - select(-Genotype) %>% - scale() - - rownames(cluster_data) <- trait_data$Genotype - - if (input$clustering_method == "kmeans") { - cluster_result <- kmeans(cluster_data, centers = input$n_clusters, nstart = 25) - clusters <- cluster_result$cluster - hclust_result <- NULL - } else { - dist_matrix <- dist(cluster_data) - hclust_result <- hclust(dist_matrix, method = "ward.D2") - clusters <- cutree(hclust_result, k = input$n_clusters) - } - - cluster_df <- data.frame( - Genotype = trait_data$Genotype, - Cluster = as.factor(clusters) - ) - - cluster_summary <- trait_data %>% - 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))) - - incProgress(1, detail = "Complete!") - - list( - clusters = cluster_df, - summary = cluster_summary, - data = cluster_data, - method = input$clustering_method, - hclust = hclust_result - ) - - }, error = function(e) { - showNotification(paste("Error in clustering analysis:", e$message), type = "error") - return(NULL) - }) - }) + 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 }) }) - - # Cluster plot + output$cluster_plot <- renderPlotly({ req(clustering_analysis()) - tryCatch({ - cluster_data <- clustering_analysis()$data - clusters <- clustering_analysis()$clusters - - if (ncol(cluster_data) > 2) { - pca_for_plot <- prcomp(cluster_data) - plot_data <- data.frame( - PC1 = pca_for_plot$x[, 1], - PC2 = pca_for_plot$x[, 2], - Genotype = clusters$Genotype, - Cluster = clusters$Cluster - ) - - p <- ggplot(plot_data, aes(x = PC1, y = PC2, color = Genotype, text = Genotype)) + - geom_point(size = 1, alpha = 0.8) + - labs(title = "Genotype Clustering (PCA Space)", - x = "PC1", y = "PC2") + - theme_minimal() + - theme( - axis.text = element_text(color = "#000000"), - axis.title = element_text(color = "#000000"), - plot.title = element_text(color = "#000000") - ) + - scale_color_manual(values = get_color_palette(rv$color_scheme, length(unique(plot_data$Genotype)))) + 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 { - plot_data <- data.frame( - X = cluster_data[, 1], - Y = cluster_data[, 2], - Genotype = clusters$Genotype, - Cluster = clusters$Cluster - ) - - p <- ggplot(plot_data, aes(x = X, y = Y, color = Genotype, text = Genotype)) + - geom_point(size = 1, alpha = 0.8) + - labs(title = "Genotype Clustering", - x = rv$traits[1], y = rv$traits[2]) + - theme_minimal() + - theme( - axis.text = element_text(color = "#000000"), - axis.title = element_text(color = "#000000"), - plot.title = element_text(color = "#000000") - ) + - scale_color_manual(values = get_color_palette(rv$color_scheme, length(unique(plot_data$Genotype)))) + 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]) } - - ggplotly(p, tooltip = c("text", "color"), height = rv$plot_height, width = rv$plot_width) - - }, error = function(e) { - showNotification(paste("Error in cluster plot:", e$message), type = "error") - return(NULL) - }) + 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 }) }) - - # Dendrogram + output$dendrogram <- renderPlot({ - req(clustering_analysis(), clustering_analysis()$method == "hierarchical") - + req(clustering_analysis(), clustering_analysis()$method=="hierarchical") tryCatch({ - hclust_result <- clustering_analysis()$hclust - - plot(hclust_result, - main = "Hierarchical Clustering Dendrogram", - xlab = "Genotypes", - ylab = "Distance", - cex = 0.8, - col = "#000000") - - rect.hclust(hclust_result, k = input$n_clusters, border = get_color_palette(rv$color_scheme, 1)[2]) - - }, error = function(e) { - showNotification(paste("Error in dendrogram:", e$message), type = "error") - return(NULL) - }) - }, height = function() rv$plot_height, width = function() rv$plot_width) - - # Cluster summary table + 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()) - - tryCatch({ - datatable( - clustering_analysis()$summary, - extensions = 'Buttons', - options = list( - scrollX = TRUE, - dom = 'Bfrtip', - buttons = c('copy', 'excel', 'csv'), - pageLength = 10, - columnDefs = list(list(className = 'dt-center', targets = '_all')) - ), - caption = "Cluster Summary Statistics" - ) %>% - formatRound(columns = rv$traits, digits = 3) - - }, error = function(e) { - showNotification(paste("Error in cluster summary:", e$message), type = "error") - return(NULL) - }) + 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 analysis + + # Stability stability_analysis <- reactive({ - req(rv$data, input$selected_trait) - - withProgress(message = 'Running Stability Analysis...', value = 0, { - incProgress(0.3, detail = "Preparing data...") - - if (!input$selected_trait %in% rv$traits) return(NULL) - - tryCatch({ - incProgress(0.6, detail = "Computing stability parameters...") - - stability_data <- 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(stability_data) < 10) { - showNotification("Insufficient data for stability analysis (need at least 10 observations)", type = "error") - return(NULL) - } - - overall_mean <- mean(stability_data$Mean_Value, na.rm = TRUE) - - stability_params <- stability_data %>% - 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 - overall_mean)^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) - ) - - env_means <- stability_data %>% - group_by(Environment) %>% - summarise(Env_Mean = mean(Mean_Value, na.rm = TRUE), .groups = "drop") - - ammi_data <- stability_data %>% - left_join(env_means, by = "Environment") %>% - mutate( - Env_Index = Env_Mean - overall_mean, - GE_Interaction = Mean_Value - overall_mean - Env_Index - ) %>% - left_join(stability_params %>% select(Genotype, Overall_Mean), by = "Genotype") - - incProgress(1, detail = "Complete!") - - list( - parameters = stability_params, - data = stability_data, - ammi_data = ammi_data, - env_means = env_means - ) - - }, error = function(e) { - showNotification(paste("Stability Analysis Error:", e$message), type = "error") - return(NULL) - }) - }) + 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 }) }) - - # Stability plot + output$stability_plot <- renderPlotly({ req(stability_analysis()) - tryCatch({ - stability_params <- stability_analysis()$parameters - - p <- ggplot(stability_params, aes(x = Overall_Mean, y = Ecovalence, color = Genotype, text = Genotype)) + - geom_point(size = 1, alpha = 0.7) + - labs(title = paste("Stability Analysis for", input$selected_trait), - x = "Mean Performance", y = "Ecovalence (Wi²)") + + 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 = "#000000"), - axis.title = element_text(color = "#000000"), - plot.title = element_text(color = "#000000") - ) + - geom_hline(yintercept = median(stability_params$Ecovalence), linetype = "dashed", color = get_color_palette(rv$color_scheme, 1)[2]) + - geom_vline(xintercept = median(stability_params$Overall_Mean), linetype = "dashed", color = get_color_palette(rv$color_scheme, 1)[2]) + - scale_color_manual(values = get_color_palette(rv$color_scheme, length(unique(stability_params$Genotype)))) - - ggplotly(p, tooltip = c("text", "x", "y"), height = rv$plot_height, width = rv$plot_width) - - }, error = function(e) { - showNotification(paste("Error in stability plot:", e$message), type = "error") - return(NULL) - }) + 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 }) }) - - # AMMI-like plot + output$ammi_plot <- renderPlotly({ req(stability_analysis()) - tryCatch({ - ammi_data <- stability_analysis()$ammi_data - - p <- ggplot(ammi_data, aes(x = Environment, y = Mean_Value, color = Genotype, group = Genotype)) + - geom_line(size = 1) + - geom_point(size = 1) + - labs(title = paste("Genotype × Environment Interaction for", input$selected_trait), - x = "Environment", y = "Mean Value") + + ad <- stability_analysis()$ammi_data + 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="Environment", y="Mean Value") + theme_minimal() + - theme( - axis.text = element_text(color = "#000000"), - axis.title = element_text(color = "#000000"), - plot.title = element_text(color = "#000000"), - axis.text.x = element_text(angle = 45, hjust = 1) - ) + - scale_color_manual(values = get_color_palette(rv$color_scheme, length(unique(ammi_data$Genotype)))) - - ggplotly(p, tooltip = c("color", "x", "y"), height = rv$plot_height, width = rv$plot_width) - - }, error = function(e) { - showNotification(paste("Error in AMMI plot:", e$message), type = "error") - return(NULL) - }) + 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_color_manual(values=get_color_palette(rv$color_scheme, + length(unique(ad$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 }) }) - - # Stability table + output$stability_table <- renderDT({ req(stability_analysis()) - - tryCatch({ - datatable( - stability_analysis()$parameters, - extensions = 'Buttons', - options = list( - scrollX = TRUE, - dom = 'Bfrtip', - buttons = c('copy', 'excel', 'csv'), - pageLength = 15, - columnDefs = list(list(className = 'dt-center', targets = '_all')) - ), - caption = paste("Stability Parameters for", input$selected_trait) - ) %>% - formatRound(columns = c("Overall_Mean", "CV", "Ecovalence", "Min_Value", "Max_Value", "Range"), digits = 3) %>% - formatStyle("Ecovalence", - backgroundColor = styleInterval(quantile(stability_analysis()$parameters$Ecovalence, c(0.33, 0.67), na.rm = TRUE), - get_color_palette(rv$color_scheme, 3))) - - }, error = function(e) { - showNotification(paste("Error in stability table:", e$message), type = "error") - return(NULL) - }) + 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))) }) - - # Download all results as Excel file + + # ═══════════════════════════���═══════════════════════════════════ + # DOWNLOADS + # ═══════════════════════════════════════════════════════════════ + + # Full / filtered analysis download output$download_all_results <- downloadHandler( filename = function() { - paste0("Phenotypic_Analysis_Results_", format(Sys.time(), "%Y%m%d_%H%M%S"), ".xlsx") + paste0("Phenotypic_Analysis_", format(Sys.time(),"%Y%m%d_%H%M%S"), ".xlsx") }, content = function(file) { - withProgress(message = 'Preparing download...', value = 0, { - + withProgress(message='Preparing download…', value=0, { tryCatch({ - # Create a new workbook wb <- createWorkbook() - - incProgress(0.1, detail = "Creating Data Summary sheet...") - - # Sheet 1: Data Summary + + # 1. Data Summary if (!is.null(rv$data)) { addWorksheet(wb, "Data_Summary") - summary_info <- data.frame( - Metric = c("Total Observations", "Total Variables", "Number of Genotypes", "Number of Environments", "Number of Traits", "Analysis Date"), - Value = c( - nrow(rv$data), - ncol(rv$data), - if("Genotype" %in% names(rv$data)) length(unique(rv$data$Genotype)) else "N/A", - if("Environment" %in% names(rv$data)) length(unique(rv$data$Environment)) else "N/A", - length(rv$traits), - format(Sys.time(), "%Y-%m-%d %H:%M:%S") - ) - ) - writeData(wb, "Data_Summary", summary_info) + 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.2, detail = "Adding Descriptive Statistics...") - - # Sheet 2: Descriptive Statistics + incProgress(0.1) + if (!is.null(descriptive_stats())) { - addWorksheet(wb, "Descriptive_Statistics") - writeData(wb, "Descriptive_Statistics", descriptive_stats()) + addWorksheet(wb,"Descriptive_Statistics") + writeData(wb,"Descriptive_Statistics", descriptive_stats()) } - - incProgress(0.3, detail = "Adding ANOVA results...") - - # Sheet 3: ANOVA Results + incProgress(0.2) + if (!is.null(anova_analysis())) { - addWorksheet(wb, "ANOVA_Results") - anova_df <- broom::tidy(anova_analysis()$simple_model) - writeData(wb, "ANOVA_Results", anova_df) + addWorksheet(wb,"ANOVA_Results") + writeData(wb,"ANOVA_Results", broom::tidy(anova_analysis()$simple_model)) } - - incProgress(0.4, detail = "Adding BLUEs...") - - # Sheet 4: BLUEs + incProgress(0.3) + if (!is.null(mixed_model_analysis())) { - addWorksheet(wb, "BLUEs") - writeData(wb, "BLUEs", mixed_model_analysis()$blues) + addWorksheet(wb,"BLUEs") + writeData(wb,"BLUEs", mixed_model_analysis()$blues) } - - incProgress(0.5, detail = "Adding Heritability results...") - - # Sheet 5: Heritability - Variance Components + incProgress(0.4) + if (!is.null(heritability_analysis())) { - addWorksheet(wb, "Variance_Components") - all_var_comp <- do.call(rbind, lapply(heritability_analysis(), function(x) x$variance_components)) - writeData(wb, "Variance_Components", all_var_comp) - - # Sheet 6: Heritability Estimates - addWorksheet(wb, "Heritability_Estimates") - herit_summary <- 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 - ) - writeData(wb, "Heritability_Estimates", herit_summary) + 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.6, detail = "Adding Correlation analysis...") - - # Sheet 7: Correlation Matrix + incProgress(0.5) + if (!is.null(correlation_analysis())) { - addWorksheet(wb, "Correlation_Matrix") - cor_matrix_df <- as.data.frame(correlation_analysis()$matrix) - cor_matrix_df <- rownames_to_column(cor_matrix_df, "Trait") - writeData(wb, "Correlation_Matrix", cor_matrix_df) - - # Sheet 8: Pairwise Correlations - addWorksheet(wb, "Pairwise_Correlations") - writeData(wb, "Pairwise_Correlations", correlation_analysis()$table) + 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.7, detail = "Adding PCA results...") - - # Sheet 9: PCA Scores + incProgress(0.6) + if (!is.null(pca_analysis())) { - addWorksheet(wb, "PCA_Scores") - writeData(wb, "PCA_Scores", pca_analysis()$scores) - - # Sheet 10: PCA Variance Explained - addWorksheet(wb, "PCA_Variance") - writeData(wb, "PCA_Variance", pca_analysis()$variance) - - # Sheet 11: PCA Loadings - addWorksheet(wb, "PCA_Loadings") - writeData(wb, "PCA_Loadings", pca_analysis()$loadings) + 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.8, detail = "Adding Clustering results...") - - # Sheet 12: Clustering Results + incProgress(0.7) + if (!is.null(clustering_analysis())) { - addWorksheet(wb, "Cluster_Assignments") - writeData(wb, "Cluster_Assignments", clustering_analysis()$clusters) - - # Sheet 13: Cluster Summary - addWorksheet(wb, "Cluster_Summary") - writeData(wb, "Cluster_Summary", clustering_analysis()$summary) + addWorksheet(wb,"Cluster_Assignments") + writeData(wb,"Cluster_Assignments", clustering_analysis()$clusters) + addWorksheet(wb,"Cluster_Summary") + writeData(wb,"Cluster_Summary", clustering_analysis()$summary) } - - incProgress(0.9, detail = "Adding Stability analysis...") - - # Sheet 14: Stability Parameters + incProgress(0.8) + if (!is.null(stability_analysis())) { - addWorksheet(wb, "Stability_Parameters") - writeData(wb, "Stability_Parameters", stability_analysis()$parameters) - - # Sheet 15: GxE Interaction Data - addWorksheet(wb, "GxE_Interaction") - writeData(wb, "GxE_Interaction", stability_analysis()$ammi_data) + 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.95, detail = "Finalizing workbook...") - - # Save the workbook - saveWorkbook(wb, file, overwrite = TRUE) - - incProgress(1, detail = "Download ready!") - - showNotification("All results downloaded successfully!", type = "message", duration = 5) - - }, error = function(e) { - showNotification(paste("Error creating download file:", e$message), type = "error", duration = 10) - }) + 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)) }) } ) -} -# Run the Shiny app -shinyApp(ui = ui, server = server) \ No newline at end of file +} # end server + +shinyApp(ui=ui, server=server) \ No newline at end of file