|
| 1 | +#' Detect per-pixel index-trajectory breakpoints |
| 2 | +#' |
| 3 | +#' Reduce a monthly index stack (from [dft_stac_cube()]) over time with |
| 4 | +#' [bfast::bfastmonitor()], returning a two-band `SpatRaster` of the break date |
| 5 | +#' and magnitude for every pixel. Where categorical differencing compares two |
| 6 | +#' land-cover labels, this asks a stronger question of a continuous index |
| 7 | +#' trajectory: *when* did the pixel's spectral history break, and by how much? |
| 8 | +#' |
| 9 | +#' `bfastmonitor` fits a season-trend model to a stable *history* period, then |
| 10 | +#' watches the *monitoring* period (from `start` onward) for a structural break. |
| 11 | +#' The returned `break_mag` is the median monitoring-period residual: **negative |
| 12 | +#' means the index dropped** (e.g. vegetation loss / channel scour), positive |
| 13 | +#' means it rose (establishment). `break_date` is a decimal year (e.g. |
| 14 | +#' `2022.42`) or `NA` where no break was detected. |
| 15 | +#' |
| 16 | +#' Pixels are reduced in parallel with `parallel::mclapply()` (forked workers, so |
| 17 | +#' the per-pixel logic and its parameters are inherited directly). Pixels with |
| 18 | +#' fewer than `min_obs` valid observations short-circuit to `NA`. |
| 19 | +#' |
| 20 | +#' @param cube A monthly index `SpatRaster` (the return value of |
| 21 | +#' [dft_stac_cube()]): one layer per time step, with a time value per layer. |
| 22 | +#' @param history Character. `bfastmonitor` history-selection method: `"all"` |
| 23 | +#' (default), `"ROC"`, or `"BP"`. |
| 24 | +#' @param start Numeric `c(year, period)`. Start of the monitoring period, in the |
| 25 | +#' stack's temporal frequency (e.g. `c(2022, 1)` = Jan 2022 for a monthly |
| 26 | +#' stack). Everything before it is the stable history. |
| 27 | +#' @param frequency Numeric or `NULL`. Seasonal frequency of the time series |
| 28 | +#' (12 for monthly, 1 for annual). When `NULL`, derived from the layer time |
| 29 | +#' spacing; when supplied, it must agree with that spacing or the call errors. |
| 30 | +#' @param order Integer. Harmonic order of the season-trend model passed to |
| 31 | +#' [bfast::bfastmonitor()] (default 3). Lower it (1-2) when the series samples |
| 32 | +#' only part of the year (e.g. a growing-season-only cube from |
| 33 | +#' [dft_stac_cube()] `months`), where a high order overfits sparse seasonal |
| 34 | +#' coverage. |
| 35 | +#' @param level Numeric. Significance level passed to [bfast::bfastmonitor()] |
| 36 | +#' (default 0.01). |
| 37 | +#' @param min_obs Integer. Minimum non-`NA` observations required to attempt a |
| 38 | +#' fit; pixels with fewer return `NA` (default 6). |
| 39 | +#' @param cores Integer or `NULL`. Forked workers for the per-pixel reduction. |
| 40 | +#' When `NULL`, uses one fewer than the detected cores. |
| 41 | +#' |
| 42 | +#' @return A two-band [terra::SpatRaster] with layers `break_date` (decimal year |
| 43 | +#' or `NA`) and `break_mag` (signed index change; negative = index drop). |
| 44 | +#' |
| 45 | +#' @seealso [dft_stac_cube()] (builds the input stack), [dft_index_expr()]. |
| 46 | +#' |
| 47 | +#' @examples |
| 48 | +#' \dontrun{ |
| 49 | +#' # Requires network + gdalcubes + bfast |
| 50 | +#' aoi <- sf::st_read(system.file("extdata", "example_aoi.gpkg", package = "drift")) |
| 51 | +#' cube <- dft_stac_cube(aoi, index = "kndvi", datetime = "2019-01-01/2023-12-31") |
| 52 | +#' breaks <- dft_rast_break(cube, start = c(2022, 1)) |
| 53 | +#' terra::plot(breaks[["break_mag"]]) # negative (blue) = scour / veg loss |
| 54 | +#' } |
| 55 | +#' |
| 56 | +#' @export |
| 57 | +dft_rast_break <- function(cube, |
| 58 | + history = "all", |
| 59 | + start = c(2022, 1), |
| 60 | + frequency = NULL, |
| 61 | + order = 3, |
| 62 | + level = 0.01, |
| 63 | + min_obs = 6, |
| 64 | + cores = NULL) { |
| 65 | + rlang::check_installed("bfast", reason = "for trajectory breakpoint detection") |
| 66 | + if (!inherits(cube, "SpatRaster")) { |
| 67 | + cli::cli_abort("`cube` must be a SpatRaster time stack from {.fn dft_stac_cube}.") |
| 68 | + } |
| 69 | + tm <- terra::time(cube) |
| 70 | + if (length(tm) != terra::nlyr(cube) || anyNA(tm)) { |
| 71 | + cli::cli_abort(c( |
| 72 | + "`cube` must carry a time value for every layer.", |
| 73 | + "i" = "Pass the stack returned by {.fn dft_stac_cube}." |
| 74 | + )) |
| 75 | + } |
| 76 | + |
| 77 | + # derive the ts() start and seasonal frequency from the layer times |
| 78 | + cadence_freq <- cadence_frequency(tm) |
| 79 | + if (is.na(cadence_freq)) { |
| 80 | + cli::cli_abort("Unsupported layer cadence; use a monthly or annual stack.") |
| 81 | + } |
| 82 | + if (is.null(frequency)) { |
| 83 | + frequency <- cadence_freq |
| 84 | + } else if (!isTRUE(all.equal(as.numeric(frequency), as.numeric(cadence_freq)))) { |
| 85 | + cli::cli_abort(c( |
| 86 | + "`frequency` ({frequency}) disagrees with the layer cadence (= {cadence_freq}).", |
| 87 | + "i" = "Leave `frequency = NULL` to derive it from the stack." |
| 88 | + )) |
| 89 | + } |
| 90 | + t0 <- as.Date(tm[1]) |
| 91 | + yr <- as.integer(format(t0, "%Y")) |
| 92 | + mo <- as.integer(format(t0, "%m")) |
| 93 | + ts_start <- c(yr, floor((mo - 1) / (12 / frequency)) + 1) |
| 94 | + |
| 95 | + if (is.null(cores)) { |
| 96 | + dc <- parallel::detectCores() |
| 97 | + cores <- if (is.na(dc)) 2L else max(1L, dc - 1L) |
| 98 | + } |
| 99 | + |
| 100 | + # reduce only pixels with a usable series; the rest stay NA |
| 101 | + vals <- terra::values(cube) |
| 102 | + usable <- which(rowSums(!is.na(vals)) >= min_obs) |
| 103 | + res <- matrix(NA_real_, nrow(vals), 2) |
| 104 | + if (length(usable)) { |
| 105 | + chunks <- split(usable, (seq_along(usable) - 1) %% cores) |
| 106 | + parts <- parallel::mclapply(chunks, function(ii) { |
| 107 | + t(vapply(ii, function(i) { |
| 108 | + .dft_break_pixel(vals[i, ], ts_start, frequency, start, history, order, |
| 109 | + level, min_obs) |
| 110 | + }, numeric(2))) |
| 111 | + }, mc.cores = cores) |
| 112 | + for (k in seq_along(chunks)) res[chunks[[k]], ] <- parts[[k]] |
| 113 | + } |
| 114 | + |
| 115 | + out <- cube[[1:2]] |
| 116 | + terra::values(out) <- res |
| 117 | + names(out) <- c("break_date", "break_mag") |
| 118 | + out |
| 119 | +} |
| 120 | + |
| 121 | + |
| 122 | +#' Per-pixel breakpoint reducer logic (internal, unit-testable) |
| 123 | +#' |
| 124 | +#' The degenerate branches (all-`NA` or fewer than `min_obs` observations) return |
| 125 | +#' `c(NA, NA)` before any `bfast` symbol is touched, so they are testable without |
| 126 | +#' bfast installed. |
| 127 | +#' @noRd |
| 128 | +.dft_break_pixel <- function(v, ts_start, frequency, start, history, order, |
| 129 | + level, min_obs) { |
| 130 | + if (all(is.na(v)) || sum(!is.na(v)) < min_obs) return(c(NA_real_, NA_real_)) |
| 131 | + ts_v <- stats::ts(v, start = ts_start, frequency = frequency) |
| 132 | + tryCatch({ |
| 133 | + m <- bfast::bfastmonitor(ts_v, start = start, history = history, |
| 134 | + order = order, level = level) |
| 135 | + c(m$breakpoint, m$magnitude) |
| 136 | + }, error = function(e) c(NA_real_, NA_real_)) |
| 137 | +} |
| 138 | + |
| 139 | + |
| 140 | +#' Seasonal frequency implied by a stack's layer times (internal) |
| 141 | +#' |
| 142 | +#' Monthly spacing -> 12, quarterly -> 4, annual -> 1. Returns `NA` for |
| 143 | +#' unsupported cadences. |
| 144 | +#' @noRd |
| 145 | +cadence_frequency <- function(tm) { |
| 146 | + if (length(tm) < 2) return(NA_real_) |
| 147 | + d <- stats::median(as.numeric(diff(as.Date(tm)))) |
| 148 | + if (is.na(d)) return(NA_real_) |
| 149 | + if (d >= 26 && d <= 32) return(12) |
| 150 | + if (d >= 85 && d <= 95) return(4) |
| 151 | + if (d >= 360 && d <= 370) return(1) |
| 152 | + NA_real_ |
| 153 | +} |
0 commit comments