SmartCane/r_app/create_max_mosaic.R
2026-01-06 14:17:37 +01:00

129 lines
4.1 KiB
R

# CREATE_MAX_MOSAIC.R
# ===================
# Create maximum value mosaics (Chlorophyll Index) for current and previous weeks
# Uses pre-processed merged_final_tif files (already have 5 bands)
# Usage: Rscript create_max_mosaic.R [end_date] [project_dir]
# Example: Rscript r_app/create_max_mosaic.R 2025-12-24 angata
library(terra)
library(here)
library(lubridate)
main <- function() {
args <- commandArgs(trailingOnly = TRUE)
# Parse arguments
end_date <- if (length(args) >= 1 && !is.na(args[1])) {
as.Date(args[1])
} else {
Sys.Date()
}
project_dir <- if (length(args) >= 2) args[2] else "angata"
cat(sprintf("Creating MAX mosaics (Chlorophyll Index): end_date=%s, project=%s\n",
format(end_date, "%Y-%m-%d"), project_dir))
# Calculate date ranges
current_week_start <- end_date - 6 # Last 7 days
prev_week_start <- end_date - 13 # 7-14 days back
prev_week_end <- end_date - 7
cat(sprintf("Current week: %s to %s\n", format(current_week_start, "%Y-%m-%d"), format(end_date, "%Y-%m-%d")))
cat(sprintf("Previous week: %s to %s\n", format(prev_week_start, "%Y-%m-%d"), format(prev_week_end, "%Y-%m-%d")))
# Set up paths
tif_dir <- here("laravel_app/storage/app", project_dir, "merged_final_tif")
output_dir <- here("laravel_app/storage/app", project_dir, "weekly_mosaic")
dir.create(output_dir, showWarnings = FALSE, recursive = TRUE)
# Find all TIF files
tif_files <- list.files(tif_dir, pattern = "\\.tif$", full.names = TRUE)
if (length(tif_files) == 0) {
cat("✗ No TIF files found in:", tif_dir, "\n")
return(FALSE)
}
cat(sprintf("✓ Found %d total TIF files\n", length(tif_files)))
# Extract dates from filenames (assumes YYYY-MM-DD.tif format)
extract_date_from_filename <- function(filepath) {
basename <- basename(filepath)
# Extract date part before .tif
date_str <- sub("\\.tif$", "", basename)
tryCatch(as.Date(date_str), error = function(e) NA)
}
# Filter files by date range
filter_files_by_date <- function(files, start_date, end_date) {
dates <- sapply(files, extract_date_from_filename)
valid_idx <- !is.na(dates) & dates >= start_date & dates <= end_date
files[valid_idx]
}
# Create mosaic for date range
create_mosaic <- function(files, output_path, week_label) {
if (length(files) == 0) {
cat(sprintf("⚠ No files found for %s\n", week_label))
return(FALSE)
}
cat(sprintf("\n%s: Processing %d files\n", week_label, length(files)))
# Read all TIFs
cat(" Reading TIFs...\n")
rast_list <- lapply(files, function(f) {
tryCatch(rast(f), error = function(e) {
cat(sprintf(" ⚠ Failed to read: %s\n", basename(f)))
NULL
})
})
rast_list <- rast_list[!sapply(rast_list, is.null)]
if (length(rast_list) == 0) {
cat(sprintf(" ✗ Could not read any TIF files\n"))
return(FALSE)
}
cat(sprintf(" ✓ Successfully read %d TIFs\n", length(rast_list)))
# Stack them
cat(" Stacking rasters...\n")
stacked <- do.call(c, rast_list)
# Create max mosaic (pixel-wise maximum across all dates)
cat(" Computing maximum mosaic...\n")
max_mosaic <- max(stacked, na.rm = TRUE)
# Save
cat(sprintf(" Saving to: %s\n", basename(output_path)))
writeRaster(max_mosaic, output_path, overwrite = TRUE)
cat(sprintf(" ✓ MAX mosaic created\n"))
return(TRUE)
}
# Create both mosaics
current_files <- filter_files_by_date(tif_files, current_week_start, end_date)
prev_files <- filter_files_by_date(tif_files, prev_week_start, prev_week_end)
success <- TRUE
success <- create_mosaic(current_files,
file.path(output_dir, "max_mosaic_current_week.tif"),
"CURRENT WEEK") && success
success <- create_mosaic(prev_files,
file.path(output_dir, "max_mosaic_previous_week.tif"),
"PREVIOUS WEEK") && success
if (success) {
cat("\n✓ Both mosaics created successfully\n")
}
return(success)
}
if (sys.nframe() == 0) {
main()
}