name: saudi-pivot-irrigation
version: "0.2"
category: change-detection
themes: [agriculture]
family: irrigation-expansion-tracking
description: >
  Two-epoch extent of centre-pivot irrigation in the Wadi As-Sirhan basin,
  Saudi Arabia, from Landsat NDVI. Circular fields watered from a fossil aquifer
  expanded across bare desert through the 1990s and 2000s; groundwater policy
  and depletion have since retired many of them.

# WHAT THIS MEASURES, AND WHAT IT DOES NOT. READ BEFORE CITING A NUMBER.
#   NDVI > threshold is a GREEN-VEGETATION PROXY. In this desert it separates
#   irrigated fields from bare sand cleanly, but it cannot tell an active pivot
#   from any other irrigated block, it counts AREA and not circles, and a field
#   fallow in the composite window reads as retired. The answer below is a count
#   of proxy-vegetated pixels at 30 m (0.09 ha each).
#
#   The previous version of this recipe promised a COUNT OF ACTIVE CIRCLES via
#   `connected_components_timeseries`. No such op exists and none is planned;
#   counting circles needs a connected-component labeller the library does not
#   have. Area is what the primitives can honestly deliver today.
#
#   No per-year axis. Each epoch is ONE median composite over its window, so the
#   answer is a two-epoch comparison, not an annual series. A genuine annual
#   series needs a per-year grouping reduction, and no shipped op provides one
#   (recipe-library tracker, defect 63).
#
#   UPSTREAM BUG (recipe-library tracker, defects 61/62). Some Landsat 7 (LE07)
#   assets on the Planetary Computer answer an HTML error page where a COG
#   should be, and the read dies as "Unknown byte order marker: [3C, 21]" (`<!`).
#   Confirmed 2026-08-17 on LE07_L2SP_036035_20221027_02_T1. There is no
#   platform filter to exclude L7 with: the source params carry none, and the
#   `query.platform` block the previous version of this recipe declared was
#   silently ignored. The only lever an author has is the calendar. Windows that
#   overlap 1999-2023 can pull L7 and can therefore hit this.
#
#   No month filter. The engine's source params carry no month selector, so the
#   seasonal windows below are calendar spans and off-season scenes do enter the
#   median. A median over many scenes is robust to that; a mean would not be.

settings:
  ndvi_active_threshold: 0.3   # NDVI > this → green, irrigated field
  cloud_cover_max_pct: 20      # eo:cloud_cover upper bound — desert scenes are clear
  pixel_area_m2: 900           # 30 m Landsat pixel — multiply `count` by this for area


inputs:
  aoi:
    bbox: [37.2, 29.6, 38.6, 30.6]
    crs_target: EPSG:32637
    notes: >
      Wadi As-Sirhan basin, northern Saudi Arabia. Pivots are ~800 m across
      (~50 ha), so a single field is a few hundred 30 m pixels.


  baseline_epoch:
    start: "1987-11-01"
    end: "1991-04-01"
    notes: Landsat 5 TM, winter growing season early in the expansion.

  recent_epoch:
    start: "2021-11-01"
    end: "2025-04-01"
    notes: Landsat 8/9 OLI, winter growing season after the retrenchment.

  collection:
    uri: "@usgs/landsat/c2-l2"

layers:

  # ── SOURCE ──────────────────────────────────────────────────────────────────
  #
  # Bands are CANONICAL concept codes from registry/datasets/usgs/landsat/c2-l2/
  # _dataset.yaml (N = nir, R = red, QA = qa-pixel). Each distribution maps them onto its own
  # producer asset keys, so ONE band list is correct across TM, ETM+ and OLI —
  # which the previous SR_Bx spelling was not (SR_B5 is SWIR-1 on TM/ETM+ and
  # NIR on OLI, so the old files asked for a different physical band per sensor).
  #
  # The FUSED per-scene form (`scenes: true` + `expression:` + `mask_band:`) is
  # what makes the index correct: the distribution's declared scale/offset is
  # applied per band before the expression, fill DNs become NaN, and QA_PIXEL is
  # the platform mask band, excluded from the b1..bN binding. `temporal_reduce`
  # then takes the median across the surviving scenes.
  #
  # Do NOT collapse this to a bare `bands: [A, B, QA]` source and difference the
  # result. A source read emits the DECLARED BANDS (measured 2026-08-17: three
  # bands out for a three-band request), so `b2 - b1` there is raw band math,
  # not a normalized-difference change. It plans green and answers plausibly.

  source/ndvi-baseline-scenes:
    type: raster
    description: Per-scene NDVI, QA-masked, baseline epoch.
    uri: "@usgs/landsat/c2-l2"
    params:
      scenes: true
      bands: [N, R, QA]
      mask_band: QA
      expression: "(b1 - b2) / (b1 + b2)"
      bbox: [37.2, 29.6, 38.6, 30.6]
      temporal: ["1987-11-01", "1991-04-01"]
      cloud_lt: 20
      resolution: 30
      limit: 60

  source/ndvi-recent-scenes:
    type: raster
    description: Per-scene NDVI, QA-masked, recent epoch.
    uri: "@usgs/landsat/c2-l2"
    params:
      scenes: true
      bands: [N, R, QA]
      mask_band: QA
      expression: "(b1 - b2) / (b1 + b2)"
      bbox: [37.2, 29.6, 38.6, 30.6]
      temporal: ["2021-11-01", "2025-04-01"]
      cloud_lt: 20
      resolution: 30
      limit: 60

  # ── COMPUTE ─────────────────────────────────────────────────────────────────

  compute/ndvi-baseline:
    type: raster
    description: Median NDVI over the baseline epoch's scenes.
    compute:
      op: temporal_reduce
      inputs:
        time_series: { layer: source/ndvi-baseline-scenes }
      params:
        method: median

  compute/ndvi-recent:
    type: raster
    description: Median NDVI over the recent epoch's scenes.
    compute:
      op: temporal_reduce
      inputs:
        time_series: { layer: source/ndvi-recent-scenes }
      params:
        method: median

  compute/ndvi-pair:
    type: raster
    description: The two NDVI composites stacked into one 2-band raster (b1 = baseline, b2 = recent).
    compute:
      op: stack_concat
      inputs:
        layers:
          - { layer: compute/ndvi-baseline }
          - { layer: compute/ndvi-recent }

  compute/ndvi-change:
    type: raster
    description: >
      dNDVI = recent - baseline. Positive where desert became irrigated field;
      negative where a field was retired.
    compute:
      op: raster_calc
      inputs:
        raster: { layer: compute/ndvi-pair }
      params:
        expression: "b2 - b1"
        output_band: dndvi

  compute/active-baseline:
    type: raster
    description: >
      Proxy irrigated-field footprint. Green pixels keep the value 1; bare
      desert becomes NaN (`b1 / 0.0`), which the stats kernel skips — so the
      answer layer's `count` is the irrigated-pixel count.
    compute:
      op: raster_calc
      inputs:
        raster: { layer: compute/ndvi-baseline }
      params:
        expression: "where(b1 > ${settings.ndvi_active_threshold}, 1.0, b1 / 0.0)"
        output_band: active

  compute/active-recent:
    type: raster
    description: >
      Proxy irrigated-field footprint. Green pixels keep the value 1; bare
      desert becomes NaN (`b1 / 0.0`), which the stats kernel skips — so the
      answer layer's `count` is the irrigated-pixel count.
    compute:
      op: raster_calc
      inputs:
        raster: { layer: compute/ndvi-recent }
      params:
        expression: "where(b1 > ${settings.ndvi_active_threshold}, 1.0, b1 / 0.0)"
        output_band: active

  # ── ANSWERS ─────────────────────────────────────────────────────────────────

  answer/active-baseline:
    type: answer
    description: >
      Proxy irrigated-field pixel count, baseline epoch. Area = count x 900 m².
    compute:
      op: summary
      inputs:
        raster: { layer: compute/active-baseline }
      params:
        stats: [count]

  answer/active-recent:
    type: answer
    description: >
      Proxy irrigated-field pixel count, recent epoch. Area = count x 900 m².
    compute:
      op: summary
      inputs:
        raster: { layer: compute/active-recent }
      params:
        stats: [count]

outputs:
  active_baseline:
    layer: answer/active-baseline
    value_kind: answer
    description: Early-expansion proxy irrigated pixel count.
  active_recent:
    layer: answer/active-recent
    value_kind: answer
    description: Recent proxy irrigated pixel count. THE answer, read against the baseline.
  ndvi_change:
    layer: compute/ndvi-change
    value_kind: raster
    description: dNDVI raster, recent minus baseline (show-your-work).


license:
  recipe: Apache-2.0
  output_dataset: CC-BY-4.0
  upstream_data:
    - { source: "@usgs/landsat/c2-l2", license: usgs-public-domain }
