- Consolidate 80_kpi_utils.R, 80_weekly_stats_utils.R, 80_report_building_utils.R into three client-aware files: - 80_utils_common.R (50+ functions): Shared utilities, constants, and helpers - 80_utils_agronomic_support.R: AURA-specific KPI calculations (6 KPIs) - 80_utils_cane_supply.R: ANGATA placeholder for future expansion - Move all internal helpers (calculate_cv, calculate_change_percentages, calculate_spatial_autocorrelation, extract_ci_values, etc.) to common - Add MORAN_THRESHOLD_* constants to common - Fix parameters_project.R field boundaries path (removed extra 'Data' directory) - Update 80_calculate_kpis.R with conditional client-type sourcing logic - Validate both ANGATA (cane_supply) and AURA (agronomic_support) workflows with comprehensive testing - All 96+ functions accounted for; ready for production use
211 lines
7.1 KiB
R
211 lines
7.1 KiB
R
# 80_UTILS_CANE_SUPPLY.R
|
|
# ============================================================================
|
|
# CANE SUPPLY CLIENT-SPECIFIC UTILITIES (SCRIPT 80 - CLIENT TYPE: cane_supply)
|
|
#
|
|
# Contains ANGATA and other cane supply-specific KPI and reporting functions.
|
|
#
|
|
# Currently, CANE_SUPPLY clients use the common utilities from 80_utils_common.R:
|
|
# - Weekly statistics (calculate_field_statistics, calculate_kpi_trends)
|
|
# - Field analysis reporting (generate_field_analysis_summary)
|
|
# - Excel export (export_field_analysis_excel)
|
|
#
|
|
# This file is structured to accommodate future ANGATA-specific functionality such as:
|
|
# - Custom yield models
|
|
# - Harvest readiness criteria
|
|
# - Supply chain integration hooks
|
|
# - ANGATA-specific alerting and messaging
|
|
#
|
|
# Orchestrator: (Placeholder - uses common functions)
|
|
# Dependencies: 00_common_utils.R, 80_utils_common.R
|
|
# Used by: 80_calculate_kpis.R (when client_type == "cane_supply")
|
|
# ============================================================================
|
|
|
|
library(terra)
|
|
library(sf)
|
|
library(dplyr)
|
|
library(tidyr)
|
|
library(readxl)
|
|
library(writexl)
|
|
|
|
# ============================================================================
|
|
# ANGATA-SPECIFIC HELPER FUNCTIONS (Placeholder Section)
|
|
# ============================================================================
|
|
|
|
#' Placeholder: ANGATA harvest readiness assessment
|
|
#'
|
|
#' Future implementation will integrate ANGATA-specific harvest readiness criteria:
|
|
#' - Maturation phase detection (CI threshold-based)
|
|
#' - Field age tracking (days since planting)
|
|
#' - Weather-based ripeness indicators (if available)
|
|
#' - Historical yield correlations
|
|
#'
|
|
#' @param field_ci CI values for the field
|
|
#' @param field_age_days Days since planting
|
|
#'
|
|
#' @return Character string with harvest readiness assessment
|
|
assess_harvest_readiness <- function(field_ci, field_age_days = NULL) {
|
|
# Placeholder implementation
|
|
# Real version would check:
|
|
# - Mean CI > 3.5 (maturation threshold)
|
|
# - Age > 350 days
|
|
# - Weekly growth rate < threshold (mature plateau)
|
|
|
|
if (is.null(field_ci) || all(is.na(field_ci))) {
|
|
return("No data available")
|
|
}
|
|
|
|
mean_ci <- mean(field_ci, na.rm = TRUE)
|
|
|
|
if (mean_ci > 3.5) {
|
|
return("Ready for harvest")
|
|
} else if (mean_ci > 2.5) {
|
|
return("Approaching harvest readiness")
|
|
} else {
|
|
return("Not ready - continue monitoring")
|
|
}
|
|
}
|
|
|
|
#' Placeholder: ANGATA supply chain status flags
|
|
#'
|
|
#' Future implementation will add supply chain-specific status indicators:
|
|
#' - Harvest scheduling readiness
|
|
#' - Equipment availability impact
|
|
#' - Transportation/logistics flags
|
|
#' - Quality parameter flags
|
|
#'
|
|
#' @param field_analysis Data frame with field analysis results
|
|
#'
|
|
#' @return Data frame with supply chain status columns
|
|
assess_supply_chain_status <- function(field_analysis) {
|
|
# Placeholder: return field analysis as-is
|
|
# Real version would add columns for:
|
|
# - schedule_ready (bool)
|
|
# - harvest_window_days (numeric)
|
|
# - transportation_priority (char)
|
|
# - quality_flags (char)
|
|
|
|
return(field_analysis)
|
|
}
|
|
|
|
# ============================================================================
|
|
# ORCHESTRATOR FOR CANE_SUPPLY WORKFLOWS
|
|
# ============================================================================
|
|
|
|
#' Orchestrate ANGATA weekly field analysis and reporting
|
|
#'
|
|
#' Main entry point for CANE_SUPPLY (ANGATA, etc.) workflows.
|
|
#' Currently uses common utilities; future versions will add client-specific logic.
|
|
#'
|
|
#' @param field_boundaries_sf SF object with field geometries
|
|
#' @param current_week ISO week number (1-53)
|
|
#' @param current_year ISO week year
|
|
#' @param mosaic_dir Directory containing weekly mosaics
|
|
#' @param field_boundaries_path Path to field GeoJSON
|
|
#' @param harvesting_data Data frame with harvest data (optional)
|
|
#' @param output_dir Directory for exports
|
|
#' @param data_dir Base data directory
|
|
#'
|
|
#' @return List with field analysis results
|
|
#'
|
|
#' @details
|
|
#' This function:
|
|
#' 1. Loads weekly mosaic and extracts field statistics
|
|
#' 2. Calculates field statistics (using common utilities)
|
|
#' 3. Prepares field analysis summary
|
|
#' 4. Exports to Excel/CSV/RDS
|
|
#' 5. (Future) Applies ANGATA-specific assessments
|
|
#'
|
|
calculate_field_analysis_cane_supply <- function(
|
|
field_boundaries_sf,
|
|
current_week,
|
|
current_year,
|
|
mosaic_dir,
|
|
field_boundaries_path = NULL,
|
|
harvesting_data = NULL,
|
|
output_dir = file.path(PROJECT_DIR, "output"),
|
|
data_dir = NULL
|
|
) {
|
|
|
|
message("\n============ CANE SUPPLY FIELD ANALYSIS (ANGATA, etc.) ============")
|
|
|
|
# Load current week mosaic
|
|
message("Loading current week mosaic...")
|
|
current_mosaic <- load_weekly_ci_mosaic(mosaic_dir, current_week, current_year)
|
|
|
|
if (is.null(current_mosaic)) {
|
|
warning(paste("Could not load current week mosaic for week", current_week, current_year))
|
|
return(NULL)
|
|
}
|
|
|
|
# Extract field statistics
|
|
message("Extracting field statistics from current mosaic...")
|
|
field_stats <- extract_field_statistics_from_ci(current_mosaic, field_boundaries_sf)
|
|
|
|
# Load previous week stats for comparison
|
|
message("Loading historical data for trends...")
|
|
target_prev <- calculate_target_week_and_year(current_week, current_year, offset_weeks = 1)
|
|
previous_stats <- NULL
|
|
|
|
previous_mosaic <- load_weekly_ci_mosaic(mosaic_dir, target_prev$week, target_prev$year)
|
|
if (!is.null(previous_mosaic)) {
|
|
previous_stats <- extract_field_statistics_from_ci(previous_mosaic, field_boundaries_sf)
|
|
}
|
|
|
|
# Calculate 4-week historical trend
|
|
message("Calculating field trends...")
|
|
ci_rds_path <- file.path(data_dir, "combined_CI", "combined_CI_data.rds")
|
|
|
|
field_analysis <- calculate_field_statistics(
|
|
field_stats = field_stats,
|
|
previous_stats = previous_stats,
|
|
week_num = current_week,
|
|
year = current_year,
|
|
ci_rds_path = ci_rds_path,
|
|
field_boundaries_sf = field_boundaries_sf,
|
|
harvesting_data = harvesting_data
|
|
)
|
|
|
|
if (is.null(field_analysis)) {
|
|
message("Could not generate field analysis")
|
|
return(NULL)
|
|
}
|
|
|
|
# Generate summary
|
|
message("Generating summary statistics...")
|
|
summary_df <- generate_field_analysis_summary(field_analysis)
|
|
|
|
# Export
|
|
message("Exporting field analysis...")
|
|
export_paths <- export_field_analysis_excel(
|
|
field_analysis,
|
|
summary_df,
|
|
PROJECT_DIR,
|
|
current_week,
|
|
current_year,
|
|
output_dir
|
|
)
|
|
|
|
message(paste("\n✓ CANE_SUPPLY field analysis complete. Week", current_week, current_year, "\n"))
|
|
|
|
result <- list(
|
|
field_analysis = field_analysis,
|
|
summary = summary_df,
|
|
exports = export_paths
|
|
)
|
|
|
|
return(result)
|
|
}
|
|
|
|
# ============================================================================
|
|
# FUTURE EXTENSION POINTS
|
|
# ============================================================================
|
|
|
|
# Placeholder for ANGATA-specific utilities that may be added in future:
|
|
# - Custom yield models based on ANGATA historical data
|
|
# - Field condition thresholds specific to ANGATA growing practices
|
|
# - Integration with ANGATA harvest scheduling system
|
|
# - WhatsApp messaging templates for ANGATA supply chain stakeholders
|
|
# - Cost/benefit analysis for ANGATA operational decisions
|
|
|
|
# These functions can be added here as ANGATA requirements evolve.
|