SmartCane/r_app/old_scripts/09_calculate_kpis.R

163 lines
4.9 KiB
R

# 09_CALCULATE_KPIS.R
# ===================
# This script calculates 6 Key Performance Indicators (KPIs) for sugarcane monitoring:
# 1. Field Uniformity Summary
# 2. Farm-wide Area Change Summary
# 3. TCH Forecasted
# 4. Growth Decline Index
# 5. Weed Presence Score
# 6. Gap Filling Score (placeholder)
#
# Usage: Rscript 09_calculate_kpis.R [end_date] [offset] [project_dir]
# - end_date: End date for KPI calculation (YYYY-MM-DD format), default: today
# - offset: Number of days to look back (not currently used for KPIs, but for consistency)
# - project_dir: Project directory name (e.g., "aura", "esa")
# 1. Load required libraries
# -------------------------
suppressPackageStartupMessages({
library(here)
library(sf)
library(terra)
library(dplyr)
library(tidyr)
library(lubridate)
library(readr)
library(caret)
library(CAST)
library(randomForest)
})
# 2. Main function
# --------------
main <- function() {
# Process command line arguments
args <- commandArgs(trailingOnly = TRUE)
# Process end_date argument
if (length(args) >= 1 && !is.na(args[1])) {
end_date <- as.Date(args[1])
if (is.na(end_date)) {
warning("Invalid end_date provided. Using default (current date).")
end_date <- Sys.Date()
}
} else if (exists("end_date_str", envir = .GlobalEnv)) {
end_date <- as.Date(get("end_date_str", envir = .GlobalEnv))
} else {
end_date <- Sys.Date()
}
# Process offset argument (for consistency with other scripts, not currently used)
if (length(args) >= 2 && !is.na(args[2])) {
offset <- as.numeric(args[2])
if (is.na(offset) || offset <= 0) {
warning("Invalid offset provided. Using default (7 days).")
offset <- 7
}
} else if (exists("offset", envir = .GlobalEnv)) {
offset <- get("offset", envir = .GlobalEnv)
} else {
offset <- 7
}
# Process project_dir argument
if (length(args) >= 3 && !is.na(args[3])) {
project_dir <- as.character(args[3])
} else if (exists("project_dir", envir = .GlobalEnv)) {
project_dir <- get("project_dir", envir = .GlobalEnv)
} else {
project_dir <- "esa" # Default project
}
# Make project_dir available globally so parameters_project.R can use it
assign("project_dir", project_dir, envir = .GlobalEnv)
# 3. Load utility functions and project configuration
# --------------------------------------------------
tryCatch({
source(here("r_app", "crop_messaging_utils.R"))
}, error = function(e) {
stop("Error loading crop_messaging_utils.R: ", e$message)
})
tryCatch({
source(here("r_app", "kpi_utils.R"))
}, error = function(e) {
stop("Error loading kpi_utils.R: ", e$message)
})
# Load project parameters (this sets up all directory paths and field boundaries)
tryCatch({
source(here("r_app", "parameters_project.R"))
}, error = function(e) {
stop("Error loading parameters_project.R: ", e$message)
})
# Load growth model utils if available (for yield prediction)
tryCatch({
source(here("r_app", "30_growth_model_utils.R"))
}, error = function(e) {
warning("30_growth_model_utils.R not found, yield prediction KPI will use placeholder data")
})
# Check if required variables exist
if (!exists("project_dir")) {
stop("project_dir must be set before running this script")
}
if (!exists("field_boundaries_sf") || is.null(field_boundaries_sf)) {
stop("Field boundaries not loaded. Check parameters_project.R initialization.")
}
# 4. Calculate all KPIs
# -------------------
output_dir <- file.path(reports_dir, "kpis")
kpi_results <- calculate_all_kpis(
report_date = end_date,
output_dir = output_dir,
field_boundaries_sf = field_boundaries_sf,
harvesting_data = harvesting_data,
cumulative_CI_vals_dir = cumulative_CI_vals_dir,
weekly_CI_mosaic = weekly_CI_mosaic,
reports_dir = reports_dir,
project_dir = project_dir
)
# 5. Print summary
# --------------
cat("\n=== KPI CALCULATION SUMMARY ===\n")
cat("Report Date:", as.character(kpi_results$metadata$report_date), "\n")
cat("Current Week:", kpi_results$metadata$current_week, "\n")
cat("Previous Week:", kpi_results$metadata$previous_week, "\n")
cat("Total Fields Analyzed:", kpi_results$metadata$total_fields, "\n")
cat("Calculation Time:", as.character(kpi_results$metadata$calculation_time), "\n")
cat("\nField Uniformity Summary:\n")
print(kpi_results$field_uniformity_summary)
cat("\nArea Change Summary:\n")
print(kpi_results$area_change)
cat("\nTCH Forecasted:\n")
print(kpi_results$tch_forecasted)
cat("\nGrowth Decline Index:\n")
print(kpi_results$growth_decline)
cat("\nWeed Presence Score:\n")
print(kpi_results$weed_presence)
cat("\nGap Filling Score:\n")
print(kpi_results$gap_filling)
cat("\n=== KPI CALCULATION COMPLETED ===\n")
}
# 6. Script execution
# -----------------
if (sys.nframe() == 0) {
main()
}