SmartCane/r_app/30_interpolate_growth_model.R

123 lines
4.4 KiB
R

# filepath: c:\Users\timon\Resilience BV\4020 SCane ESA DEMO - Documenten\General\4020 SCDEMO Team\4020 TechnicalData\WP3\smartcane\r_app\interpolate_growth_model.R
#
# INTERPOLATE_GROWTH_MODEL.R
# =========================
# This script interpolates CI (Chlorophyll Index) values between measurement dates
# to create a continuous growth model. It generates daily values and cumulative
# CI statistics for each field.
#
# Usage: Rscript interpolate_growth_model.R [project_dir] [data_source]
# - project_dir: Project directory name (e.g., "chemba")
# - data_source: (Optional) Data source directory - "merged_tif" (default), "merged_tif_8b"
# & 'C:\Program Files\R\R-4.4.3\bin\x64\Rscript' r_app/30_interpolate_growth_model.R angata merged_tif
# 1. Load required packages
# -----------------------
suppressPackageStartupMessages({
library(tidyverse)
library(lubridate)
library(here)
})
# =============================================================================
# Load utility functions from 30_growth_model_utils.R
# =============================================================================
source("r_app/30_growth_model_utils.R")
# =============================================================================
# Main Processing
# =============================================================================
main <- function() {
# IMPORTANT: Set working directory to project root (smartcane/)
# This ensures here() functions resolve relative to /smartcane, not /smartcane/r_app
if (basename(getwd()) == "r_app") {
setwd("..")
}
# Parse command-line arguments
args <- commandArgs(trailingOnly = TRUE)
project_dir <- if (length(args) >= 1 && args[1] != "") args[1] else "angata"
# IMPORTANT: Make project_dir available globally for parameters_project.R
assign("project_dir", project_dir, envir = .GlobalEnv)
safe_log(sprintf("=== Script 30: Growth Model Interpolation ==="))
safe_log(sprintf("Project: %s", project_dir))
# 1. Load parameters (includes field boundaries setup)
# ---------------------------------------------------
tryCatch({
source("r_app/parameters_project.R")
safe_log("Loaded parameters_project.R")
}, error = function(e) {
safe_log(sprintf("Error loading parameters: %s", e$message), "ERROR")
stop(e)
})
# 2. Set up directory paths from parameters
# -----------------------------------------------
setup <- setup_project_directories(project_dir)
# For per-field architecture: read from daily_vals_per_field_dir (Script 20 per-field output)
daily_vals_dir <- setup$daily_vals_per_field_dir
safe_log(sprintf("Using per-field daily CI directory: %s", daily_vals_dir))
safe_log("Starting CI growth model interpolation")
# 3. Load and process the data
# ----------------------------
tryCatch({
# Load the combined CI data (created by Script 20 per-field)
# Script 20 per-field outputs: daily_vals/{FIELD_NAME}/{YYYY-MM-DD}.rds
CI_data <- load_combined_ci_data(daily_vals_dir)
# Validate harvesting data
if (is.null(harvesting_data) || nrow(harvesting_data) == 0) {
safe_log("No harvesting data available", "ERROR")
stop("No harvesting data available")
}
# Get the years from harvesting data
years <- harvesting_data %>%
filter(!is.na(season_start)) %>%
distinct(year) %>%
pull(year)
safe_log(paste("Processing data for years:", paste(years, collapse = ", ")))
# Generate interpolated CI data for each year and field
CI_all <- generate_interpolated_ci_data(years, harvesting_data, CI_data)
# CI_all <- CI_all %>%
# group_by(Date, field, season) %>%
# filter(!(field == "00F25" & season == 2023 & duplicated(DOY)))
# Calculate growth metrics and save the results
if (nrow(CI_all) > 0) {
# Add daily and cumulative metrics
CI_all_with_metrics <- calculate_growth_metrics(CI_all)
# Save the processed data to cumulative_vals directory
save_growth_model(
CI_all_with_metrics,
setup$cumulative_CI_vals_dir,
"All_pivots_Cumulative_CI_quadrant_year_v2.rds"
)
} else {
safe_log("No CI data was generated after interpolation", "WARNING")
}
safe_log("Growth model interpolation completed successfully")
}, error = function(e) {
safe_log(paste("Error in growth model interpolation:", e$message), "ERROR")
stop(e$message)
})
}
if (sys.nframe() == 0) {
main()
}