terraproof 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -12,7 +12,7 @@ Terraproof helps AI coding agents do geospatial work they can prove. It gives an
12
12
 
13
13
  Everything runs locally and offline. No model API key is needed.
14
14
 
15
- **Status:** experimental (v0.9.0). See [Evaluation status](#evaluation-status) for what has and has not been measured.
15
+ **Status:** experimental (v0.10.0). See [Evaluation status](#evaluation-status) for what has and has not been measured.
16
16
 
17
17
  ---
18
18
 
@@ -73,7 +73,9 @@ The grade describes the data path and the checks that ran. It is not a certifica
73
73
  For explicit task requirements, add `--contract contract.json` (MCP: `contract`).
74
74
  The contract's outcome becomes the report's grade: it is decision-grade only when every
75
75
  required check on every required output ran and passed with its declared sources and
76
- parameters, and any other failure or warning still counts. See
76
+ parameters, and any other failure or warning still counts. `propose --profile NAME`
77
+ (MCP: `propose_contract`) drafts such a contract, filling bindings only from explicit
78
+ file or STAC metadata and listing what you still need to declare. See
77
79
  [verification contracts, diagnostics and unsigned evidence bundles](docs/VERIFICATION_CONTRACTS.md).
78
80
 
79
81
  ### Verify a spectral index against its source bands
@@ -137,7 +139,7 @@ band and pixel in bounded windows; see [scope, examples and measured controls](d
137
139
  python -m terraproof.mcp # stdio server; needs the `mcp` extra
138
140
  ```
139
141
 
140
- It is read-only and offline, with six tools: `preflight`, `inspect_dataset`, `run_checks`, `list_skills`, `load_section`, and `find_guidance`. CLI and MCP return the same reports.
142
+ It is read-only and offline, with seven tools: `preflight`, `inspect_dataset`, `run_checks`, `propose_contract`, `list_skills`, `load_section`, and `find_guidance`. CLI and MCP return the same reports.
141
143
 
142
144
  ### Install into a project
143
145
 
@@ -193,7 +195,8 @@ Each skill lives in `skills/<name>/` with a `SKILL.md`, references, and a `skill
193
195
  - **Routing:** an independent, frozen 160-item set (v5) passed once in both languages: English recall 0.97 with 3.75 wrong picks per 100, Arabic recall 0.96 with 2.5. Earlier independent sets (v3, v4) failed and stay on record. The v5 set was written by an AI agent, not reviewed by an expert.
194
196
  - **Agent lift:** in a 54-run Claude Code comparison on 9 tasks, runs with Terraproof passed 27/27 and runs without it 21/27. The pre-specified test is **not significant** (p = 0.125), and five tasks passed either way, so no lift is claimed. The clearest single result is Landsat QA masking (3/3 with, 0/3 without). See [`docs/plans/Terraproof_Phase5_PLAN.md`](docs/plans/Terraproof_Phase5_PLAN.md).
195
197
  - **Harder cohort:** a one-repeat Claude Code screen passed all six tasks both with and without Terraproof. That small screen shows no observed benefit and is separate from the original nine-task study. API pilots are exploratory and do not establish lift.
196
- - **Real hosts:** tool use through MCP has been verified with Codex, Claude Code and Antigravity (Gemini). OpenCode's install format passes a no-model check with the real CLI, but no real tool call has been recorded yet. Cursor and Copilot are unit-tested against their documented layouts only.
198
+ - **Real data (Phase 8):** on 34 sealed cases built from public Sentinel-2, Copernicus DEM, 3DEP and Natural Earth data, declared checks caught 7 of 7 covered wrong outputs with no false assurance and no false alarm. 20 of the 34 deliverables (validity masks, slope in percent, JSON reports) are forms no check covers yet. Contracts proposed from metadata alone did not meet acceptance. In a 10-run agent measurement, the agent rarely declared a goal, and the `s2-l2a` preset certified two wrong decodes; that preset now requires `--decode-offset`. See [`docs/plans/Terraproof_Phase8_PLAN.md`](docs/plans/Terraproof_Phase8_PLAN.md).
199
+ - **Real hosts:** tool use through MCP has been verified with Codex, Claude Code, Antigravity (Gemini) and OpenCode (Phase 8 P4, ten runs with real tool calls). Cursor and Copilot are unit-tested against their documented layouts only.
197
200
 
198
201
  ---
199
202
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "terraproof",
3
- "version": "0.9.0",
3
+ "version": "0.10.0",
4
4
  "description": "evidence-graded skills, tools, and checks for mapping and remote-sensing AI agents. By Geova.",
5
5
  "type": "module",
6
6
  "main": "./dist/router/index.js",
@@ -61,6 +61,16 @@
61
61
  "categorical"
62
62
  ]
63
63
  },
64
+ "raster.categorical_codes": {
65
+ "family": "raster",
66
+ "description": "Every valid output cell holds a class code found in the declared class source; blended codes from bilinear, cubic or average resampling fail.",
67
+ "applies_to": [
68
+ "raster"
69
+ ],
70
+ "enabled_by": [
71
+ "categorical_source"
72
+ ]
73
+ },
64
74
  "raster.grid_alignment": {
65
75
  "family": "raster",
66
76
  "description": "Rasters share CRS, pixel size, and pixel-grid origin so they can be combined."
@@ -155,6 +165,19 @@
155
165
  "sar_expect"
156
166
  ]
157
167
  },
168
+ "sar.filter_domain": {
169
+ "family": "sar",
170
+ "description": "A declared boxcar speckle filter, recomputed from its unfiltered source in linear power, matches the output; a filter averaged in dB fails.",
171
+ "applies_to": [
172
+ "raster"
173
+ ],
174
+ "enabled_by": [
175
+ "sar_filter",
176
+ "sar_filter_size",
177
+ "sar_filter_source",
178
+ "sar_expect"
179
+ ]
180
+ },
158
181
  "accuracy.sample_design": {
159
182
  "family": "accuracy",
160
183
  "description": "Every map class in the reference-sample CSV has at least min_per_class samples (default 50, a configurable rule of thumb); missing class areas when area estimates are requested are warned."
@@ -227,6 +250,18 @@
227
250
  "stack_reduction"
228
251
  ]
229
252
  },
253
+ "rs.stack_window": {
254
+ "family": "rs",
255
+ "description": "The output's declared time window holds every stack layer's declared interval without overlap; an accumulation also covers it without gaps, weighted by layer hours.",
256
+ "applies_to": [
257
+ "raster"
258
+ ],
259
+ "enabled_by": [
260
+ "stack",
261
+ "stack_times",
262
+ "stack_window"
263
+ ]
264
+ },
230
265
  "terrain.slope_formula": {
231
266
  "family": "terrain",
232
267
  "description": "Opt-in calibrated central-difference slope comparison: every required value, complete center/four-neighbour support and nodata edges.",
@@ -1,209 +1,212 @@
1
- ---
2
- name: stac-and-cloud-access
3
- description: Search STAC APIs reproducibly and read cloud-hosted rasters lazily, covering collections/bbox/intersects/datetime/query/filter parameters, item and asset provenance, signed URLs and requester-pays buckets, COG and Zarr windowed reads through HTTP range requests and GDAL /vsicurl/, loader scale/offset behaviour, caching and pinning item ids in a run manifest; use when finding, loading or recording satellite data from STAC catalogs or object storage.
4
- license: MIT
5
- ---
6
-
7
- # STAC search and cloud-native access
8
-
9
- ## Search with explicit, reproducible parameters
10
-
11
- STAC API Item Search (`GET /search` required, `POST` recommended) returns an
12
- ItemCollection (GeoJSON FeatureCollection of Items). Core parameters [S1]:
13
-
14
- | Parameter | Meaning and pitfalls |
15
- |---|---|
16
- | `collections` | Collection ids; always set it so results are not cross-collection by accident. |
17
- | `bbox` | `[min lon, min lat, max lon, max lat]` in WGS 84 (CRS84); 2D or 3D. |
18
- | `intersects` | One GeoJSON geometry. **Only one of `bbox` or `intersects`**; both is a 400 error. |
19
- | `datetime` | RFC 3339 instant or interval with `/`; `..` for open ends. Item times are UTC [S2]. |
20
- | `ids` | Exact Item ids — the way to re-fetch a pinned set. |
21
- | `limit` | Page size suggestion only; servers may return fewer and paginate via `next` links. |
22
-
23
- Property filtering is an **extension**: the Query extension (`query`, operators
24
- `eq`, `neq`, `lt`, `lte`, `gt`, `gte`, `startsWith`, `endsWith`, `contains`, `in`)
25
- [S3] or the recommended Filter extension (`filter`, `filter-lang` = `cql2-text` or
26
- `cql2-json`) [S4]. Check conformance before relying on either; a server that does
27
- not implement one may ignore or reject it.
28
-
29
- ```python
30
- import pystac_client
31
-
32
- client = pystac_client.Client.open("https://earth-search.aws.element84.com/v1")
33
- if not client.conforms_to("QUERY"):
34
- raise RuntimeError("server does not advertise the Query extension")
35
- search = client.search(
36
- collections=["sentinel-2-l2a"],
37
- bbox=[13.30, 52.45, 13.50, 52.55],
38
- datetime="2024-06-01T00:00:00Z/2024-06-30T23:59:59Z",
39
- query={"eo:cloud_cover": {"lt": 20}},
40
- max_items=200, # client-side cap across pages
41
- )
42
- items = list(search.items())
43
- ```
44
-
45
- `Client.search` defaults to `POST`; `max_items` caps total items, `limit` is the
46
- per-page hint; `filter` defaults to `cql2-json` for dict input [S5]. When run in
47
- October 2026 this endpoint advertised Query but not Filter, so a `filter=` search
48
- only warned. An AOI can return items from several UTM zones/tiles; plan a common
49
- output CRS. Dataset discovery and licensing are covered by
50
- [geospatial data discovery](../geospatial-data-discovery/SKILL.md). Shared rules:
51
- [engineering](../../instructions/engineering.md),
52
- [simplicity](../../instructions/simplicity.md), [security](../../instructions/security.md).
53
-
54
- ## Record item and asset provenance
55
-
56
- An Item requires `id`, `geometry`, `bbox` (when geometry is not null),
57
- `properties.datetime` (or `null` with `start_datetime`/`end_datetime`), `links`
58
- and `assets`; ids are unique within a Collection, so record **collection + id**
59
- [S2]. For each input keep:
60
-
61
- - STAC API root URL, collection id, item id, `datetime`, self link;
62
- - asset key and **unsigned** `href`, media type and roles;
63
- - processing version: `processing:version` (e.g. a Sentinel processing
64
- baseline) [S6], or the deprecated `s2:processing_baseline` still used by some
65
- catalogs [S7];
66
- - encoding metadata: raster extension `scale`/`offset`/`nodata` (`raster:bands`
67
- in v1.x, `raster:scale`/`raster:offset` in v2.0) [S8];
68
- - the exact search parameters and the date the search ran.
69
-
70
- Catalogs change (reprocessing, new baselines, removed items). A search re-run
71
- later can return different items; the pinned ids cannot silently change.
72
- Re-fetch with `client.search(collections=[...], ids=[...])`. A manifest pattern
73
- is in [references/run-manifest.md](references/run-manifest.md).
74
-
75
- ## Signed URLs and requester-pays storage
76
-
77
- - **Signed URLs (SAS):** Microsoft Planetary Computer assets need signing,
78
- e.g. `Client.open(url, modifier=planetary_computer.sign_inplace)` or
79
- `planetary_computer.sign(item)`; tokens expire and signed items gain an
80
- `msft:expiry` property [S9]. Sign at read time; never store signed URLs or
81
- tokens in manifests, logs or reports ([security](../../instructions/security.md)).
82
- - **Requester pays:** the reader pays for access and transfer. Example:
83
- `s3://usgs-landsat/collection02/` is a requester-pays bucket [S10]. GDAL needs
84
- credentials plus `AWS_REQUEST_PAYER=requester`; `AWS_NO_SIGN_REQUEST=YES`
85
- disables signing for public buckets [S11]. Estimate transfer before bulk reads.
86
-
87
- ## Read COG windows with HTTP range requests
88
-
89
- `/vsicurl/` reads remote files piece-wise with HTTP range requests, chunked and
90
- cached in memory; `/vsicurl_streaming/` does not use range requests; a plain URL
91
- without `/vsi` uses the HTTP driver, which downloads the whole file [S11]. COGs
92
- are tiled with overviews and an internal tile index, which is what makes partial
93
- reads efficient [S11]. Rasterio opens `https://` hrefs through GDAL.
94
-
95
- ```python
96
- import rasterio
97
- from rasterio.warp import transform_bounds
98
- from rasterio.windows import Window, from_bounds
99
-
100
- aoi = (13.30, 52.45, 13.50, 52.55) # lon/lat
101
- href = items[0].assets["red"].href # unsigned public COG here
102
- with rasterio.Env(GDAL_DISABLE_READDIR_ON_OPEN="EMPTY_DIR",
103
- CPL_VSIL_CURL_ALLOWED_EXTENSIONS=".tif"):
104
- with rasterio.open(href) as src:
105
- bounds = transform_bounds("EPSG:4326", src.crs, *aoi)
106
- window = from_bounds(*bounds, transform=src.transform)
107
- window = window.round_offsets().round_lengths()
108
- window = window.intersection(Window(0, 0, src.width, src.height))
109
- dn = src.read(1, window=window, masked=True) # stored values
110
- transform = src.window_transform(window)
111
- ```
112
-
113
- `GDAL_DISABLE_READDIR_ON_OPEN=EMPTY_DIR` stops directory listing and side-car
114
- probing; `CPL_VSIL_CURL_ALLOWED_EXTENSIONS` limits which files GDAL assumes exist
115
- [S12]. CLI equivalents: `gdalinfo /vsicurl/https://.../B04.tif`, and
116
- `gdal_translate -projwin_srs EPSG:4326 -projwin ...` for a subset. Retries
117
- (`GDAL_HTTP_MAX_RETRY`, `GDAL_HTTP_RETRY_DELAY`) and cache sizes are in
118
- [references/run-manifest.md](references/run-manifest.md#gdal-network-options).
119
- Windows/blocks and COG creation: [raster processing](../raster-processing/SKILL.md).
120
-
121
- ## Know what your loader decodes
122
-
123
- In the example above (Earth Search Sentinel-2 L2A, October 2026) the STAC asset
124
- declared `scale 0.0001, offset -0.1, nodata 0`, while the GeoTIFF reported
125
- identity scale/offset: `rasterio.read()` returns raw DN [S8]. Loaders differ:
126
-
127
- - `odc.stac.load(...)` returned raw `uint16` DN with `nodata` 0 in the same test;
128
- decode afterwards, exactly once.
129
- - `stackstac.stack(...)` defaults to `rescale=True`, applying `raster:bands`
130
- scale/offset, with `dtype=float64` and NaN fill [S13]; do not decode again.
131
- - `xarray.open_zarr(...)` defaults to `mask_and_scale=True` (CF decoding) and
132
- lazy Dask chunks when Dask is installed [S14].
133
-
134
- Decoding rules and sensor offsets: [satellite preprocessing](../satellite-preprocessing/SKILL.md).
135
-
136
- ## Load many items as a lazy cube
137
-
138
- ```python
139
- import odc.stac
140
-
141
- ds = odc.stac.load(
142
- items, bands=["red", "nir", "scl"],
143
- crs="EPSG:32633", resolution=20, # explicit output grid
144
- bbox=[13.30, 52.45, 13.50, 52.55],
145
- groupby="solar_day", # merge same-pass tiles
146
- chunks={"x": 2048, "y": 2048}, # Dask-backed, nothing read yet
147
- )
148
- ```
149
-
150
- `groupby="solar_day"` places items from the same solar day in one time slice;
151
- by default overlapping pixels are filled from the first valid item in a
152
- deterministic time/id order; `patch_url` can sign hrefs (e.g. `planetary_computer.sign`)
153
- [S15]. Set `resampling` per band, e.g. nearest for categorical `scl` [S15]. In
154
- the test above, 4 tile-items became 2 dates. Record `crs`, `resolution`,
155
- `groupby`, `resampling` and library versions with the outputs.
156
-
157
- ## Cache and pin for reproducibility
158
-
159
- GDAL's `/vsicurl/` cache is in-process memory only [S11]; it is not a
160
- reproducibility mechanism. For results that must be re-verified:
161
-
162
- 1. Pin collection + item ids and asset keys; store unsigned hrefs.
163
- 2. Copy the exact bytes you analysed to a local or bucket cache and record
164
- SHA-256 and size; verify hashes before reuse.
165
- 3. Record processing versions, encoding metadata, loader parameters, library and
166
- GDAL versions, and the search parameters.
167
- 4. Keep timestamps and machine paths outside the hashed part of a manifest.
168
-
169
- ## Verify with Terraproof
170
-
171
- ```bash
172
- python -m terraproof check source-item.json
173
- python -m terraproof check subset_red.tif --expect reflectance
174
- ```
175
-
176
- `stac.provenance` checks Item time and a projection code, not full lineage,
177
- licences or calibration. Raster outputs get `crs.defined`, `crs.consistent`,
178
- `raster.nodata_declared`, `raster.grid_alignment`, `raster.cog_layout`, and
179
- `rs.reflectance_range` with `--expect reflectance` (only after decoding).
180
-
181
- Use `--manifest run.json --require-provenance` for `provenance.reproducible`
182
- (re-hashes manifest inputs/outputs; warns on tool-version drift, fails on content
183
- drift). Add `--time-range START END` for `rs.temporal_scope` on source Items.
184
- For `rs.scale_applied_once`, compare a decoded raster with its raw source using
185
- `--reference-input RAW.tif --encoding s2-l2a` or `landsat-c2-l2`; the sampled
186
- output is compared with DN × scale + offset under that declared encoding.
187
-
188
- **Not checked automatically:** whether the search returned the right items,
189
- whether pinned items still exist upstream, licence compliance and transfer
190
- costs. Manifest credential guards reject known secret-bearing paths/URLs, but
191
- do not audit every application log or prevent all signed-URL leakage.
192
-
193
- ## Sources
194
-
195
- - [S1 — STAC API Item Search](https://github.com/radiantearth/stac-api-spec/blob/main/item-search/README.md): parameters, bbox/intersects exclusivity, datetime syntax, limit and pagination.
196
- - [S2 — STAC Item specification](https://github.com/radiantearth/stac-spec/blob/master/item-spec/item-spec.md): required fields, id uniqueness, UTC datetime.
197
- - [S3 — STAC API Query extension](https://github.com/stac-api-extensions/query): `query` syntax and operators.
198
- - [S4 — STAC API Filter extension](https://github.com/stac-api-extensions/filter): `filter`, `filter-lang`, CQL2 text/JSON, queryables.
199
- - [S5 — pystac-client `Client`](https://github.com/stac-utils/pystac-client/blob/main/pystac_client/client.py): `open(modifier=...)`, `search()` parameters and defaults, `conforms_to`.
200
- - [S6 — STAC processing extension](https://github.com/stac-extensions/processing): `processing:version` (e.g. Sentinel processing baseline), `processing:software`, lineage links.
201
- - [S7 — STAC Sentinel-2 extension](https://github.com/stac-extensions/sentinel-2): `s2:processing_baseline` deprecated in favour of `processing:version`.
202
- - [S8 — STAC raster extension](https://github.com/stac-extensions/raster): scale/offset semantics; Earth Search behaviour observed by a live query and rasterio read (October 2026).
203
- - [S9 — Planetary Computer SDK](https://github.com/microsoft/planetary-computer-sdk-for-python): `sign`, `sign_inplace`, token expiry and `msft:expiry`.
204
- - [S10 — Registry of Open Data on AWS, USGS Landsat](https://registry.opendata.aws/usgs-landsat/): `usgs-landsat` bucket `RequesterPays: True`.
205
- - [S11 — GDAL virtual file systems](https://gdal.org/en/stable/user/virtual_file_systems.html): `/vsicurl/` range requests, chunking/cache, `/vsis3/`, `AWS_REQUEST_PAYER`, `AWS_NO_SIGN_REQUEST`, retries, cloud-friendly TIFF layout.
206
- - [S12 — GDAL configuration options](https://gdal.org/en/stable/user/configoptions.html): `GDAL_DISABLE_READDIR_ON_OPEN`, `CPL_VSIL_CURL_ALLOWED_EXTENSIONS`.
207
- - [S13 — stackstac `stack()`](https://github.com/gjoseph92/stackstac/blob/main/stackstac/stack.py): `rescale=True`, `dtype`, `fill_value`, `resampling` defaults.
208
- - [S14 — xarray `open_zarr`](https://github.com/pydata/xarray/blob/main/xarray/backends/zarr.py): `chunks` and `mask_and_scale` defaults.
209
- - [S15 — odc-stac `load`](https://odc-stac.readthedocs.io/en/latest/_api/odc.stac.load.html): `groupby`, `chunks`, `crs`, `resolution`, `bbox`, `resampling`, `patch_url`, fuse behaviour.
1
+ ---
2
+ name: stac-and-cloud-access
3
+ description: Search STAC APIs reproducibly and read cloud-hosted rasters lazily, covering collections/bbox/intersects/datetime/query/filter parameters, item and asset provenance, signed URLs and requester-pays buckets, COG and Zarr windowed reads through HTTP range requests and GDAL /vsicurl/, loader scale/offset behaviour, caching and pinning item ids in a run manifest; use when finding, loading or recording satellite data from STAC catalogs or object storage.
4
+ license: MIT
5
+ ---
6
+
7
+ # STAC search and cloud-native access
8
+
9
+ ## Search with explicit, reproducible parameters
10
+
11
+ STAC API Item Search (`GET /search` required, `POST` recommended) returns an
12
+ ItemCollection (GeoJSON FeatureCollection of Items). Core parameters [S1]:
13
+
14
+ | Parameter | Meaning and pitfalls |
15
+ |---|---|
16
+ | `collections` | Collection ids; always set it so results are not cross-collection by accident. |
17
+ | `bbox` | `[min lon, min lat, max lon, max lat]` in WGS 84 (CRS84); 2D or 3D. |
18
+ | `intersects` | One GeoJSON geometry. **Only one of `bbox` or `intersects`**; both is a 400 error. |
19
+ | `datetime` | RFC 3339 instant or interval with `/`; `..` for open ends. Item times are UTC [S2]. |
20
+ | `ids` | Exact Item ids — the way to re-fetch a pinned set. |
21
+ | `limit` | Page size suggestion only; servers may return fewer and paginate via `next` links. |
22
+
23
+ Property filtering is an **extension**: the Query extension (`query`, operators
24
+ `eq`, `neq`, `lt`, `lte`, `gt`, `gte`, `startsWith`, `endsWith`, `contains`, `in`)
25
+ [S3] or the recommended Filter extension (`filter`, `filter-lang` = `cql2-text` or
26
+ `cql2-json`) [S4]. Check conformance before relying on either; a server that does
27
+ not implement one may ignore or reject it.
28
+
29
+ ```python
30
+ import pystac_client
31
+
32
+ client = pystac_client.Client.open("https://earth-search.aws.element84.com/v1")
33
+ if not client.conforms_to("QUERY"):
34
+ raise RuntimeError("server does not advertise the Query extension")
35
+ search = client.search(
36
+ collections=["sentinel-2-l2a"],
37
+ bbox=[13.30, 52.45, 13.50, 52.55],
38
+ datetime="2024-06-01T00:00:00Z/2024-06-30T23:59:59Z",
39
+ query={"eo:cloud_cover": {"lt": 20}},
40
+ max_items=200, # client-side cap across pages
41
+ )
42
+ items = list(search.items())
43
+ ```
44
+
45
+ `Client.search` defaults to `POST`; `max_items` caps total items, `limit` is the
46
+ per-page hint; `filter` defaults to `cql2-json` for dict input [S5]. When run in
47
+ October 2026 this endpoint advertised Query but not Filter, so a `filter=` search
48
+ only warned. An AOI can return items from several UTM zones/tiles; plan a common
49
+ output CRS. Dataset discovery and licensing are covered by
50
+ [geospatial data discovery](../geospatial-data-discovery/SKILL.md). Shared rules:
51
+ [engineering](../../instructions/engineering.md),
52
+ [simplicity](../../instructions/simplicity.md), [security](../../instructions/security.md).
53
+
54
+ ## Record item and asset provenance
55
+
56
+ An Item requires `id`, `geometry`, `bbox` (when geometry is not null),
57
+ `properties.datetime` (or `null` with `start_datetime`/`end_datetime`), `links`
58
+ and `assets`; ids are unique within a Collection, so record **collection + id**
59
+ [S2]. For each input keep:
60
+
61
+ - STAC API root URL, collection id, item id, `datetime`, self link;
62
+ - asset key and **unsigned** `href`, media type and roles;
63
+ - processing version: `processing:version` (e.g. a Sentinel processing
64
+ baseline) [S6], or the deprecated `s2:processing_baseline` still used by some
65
+ catalogs [S7];
66
+ - encoding metadata: raster extension `scale`/`offset`/`nodata` (`raster:bands`
67
+ in v1.x, `raster:scale`/`raster:offset` in v2.0) [S8];
68
+ - the exact search parameters and the date the search ran.
69
+
70
+ Catalogs change (reprocessing, new baselines, removed items). A search re-run
71
+ later can return different items; the pinned ids cannot silently change.
72
+ Re-fetch with `client.search(collections=[...], ids=[...])`. A manifest pattern
73
+ is in [references/run-manifest.md](references/run-manifest.md).
74
+
75
+ ## Signed URLs and requester-pays storage
76
+
77
+ - **Signed URLs (SAS):** Microsoft Planetary Computer assets need signing,
78
+ e.g. `Client.open(url, modifier=planetary_computer.sign_inplace)` or
79
+ `planetary_computer.sign(item)`; tokens expire and signed items gain an
80
+ `msft:expiry` property [S9]. Sign at read time; never store signed URLs or
81
+ tokens in manifests, logs or reports ([security](../../instructions/security.md)).
82
+ - **Requester pays:** the reader pays for access and transfer. Example:
83
+ `s3://usgs-landsat/collection02/` is a requester-pays bucket [S10]. GDAL needs
84
+ credentials plus `AWS_REQUEST_PAYER=requester`; `AWS_NO_SIGN_REQUEST=YES`
85
+ disables signing for public buckets [S11]. Estimate transfer before bulk reads.
86
+
87
+ ## Read COG windows with HTTP range requests
88
+
89
+ `/vsicurl/` reads remote files piece-wise with HTTP range requests, chunked and
90
+ cached in memory; `/vsicurl_streaming/` does not use range requests; a plain URL
91
+ without `/vsi` uses the HTTP driver, which downloads the whole file [S11]. COGs
92
+ are tiled with overviews and an internal tile index, which is what makes partial
93
+ reads efficient [S11]. Rasterio opens `https://` hrefs through GDAL.
94
+
95
+ ```python
96
+ import rasterio
97
+ from rasterio.warp import transform_bounds
98
+ from rasterio.windows import Window, from_bounds
99
+
100
+ aoi = (13.30, 52.45, 13.50, 52.55) # lon/lat
101
+ href = items[0].assets["red"].href # unsigned public COG here
102
+ with rasterio.Env(GDAL_DISABLE_READDIR_ON_OPEN="EMPTY_DIR",
103
+ CPL_VSIL_CURL_ALLOWED_EXTENSIONS=".tif"):
104
+ with rasterio.open(href) as src:
105
+ bounds = transform_bounds("EPSG:4326", src.crs, *aoi)
106
+ window = from_bounds(*bounds, transform=src.transform)
107
+ window = window.round_offsets().round_lengths()
108
+ window = window.intersection(Window(0, 0, src.width, src.height))
109
+ dn = src.read(1, window=window, masked=True) # stored values
110
+ transform = src.window_transform(window)
111
+ ```
112
+
113
+ `GDAL_DISABLE_READDIR_ON_OPEN=EMPTY_DIR` stops directory listing and side-car
114
+ probing; `CPL_VSIL_CURL_ALLOWED_EXTENSIONS` limits which files GDAL assumes exist
115
+ [S12]. CLI equivalents: `gdalinfo /vsicurl/https://.../B04.tif`, and
116
+ `gdal_translate -projwin_srs EPSG:4326 -projwin ...` for a subset. Retries
117
+ (`GDAL_HTTP_MAX_RETRY`, `GDAL_HTTP_RETRY_DELAY`) and cache sizes are in
118
+ [references/run-manifest.md](references/run-manifest.md#gdal-network-options).
119
+ Windows/blocks and COG creation: [raster processing](../raster-processing/SKILL.md).
120
+
121
+ ## Know what your loader decodes
122
+
123
+ In the example above (Earth Search Sentinel-2 L2A, October 2026) the STAC asset
124
+ declared `scale 0.0001, offset -0.1, nodata 0`, while the GeoTIFF reported
125
+ identity scale/offset: `rasterio.read()` returns raw DN [S8]. Loaders differ:
126
+
127
+ - `odc.stac.load(...)` returned raw `uint16` DN with `nodata` 0 in the same test;
128
+ decode afterwards, exactly once.
129
+ - `stackstac.stack(...)` defaults to `rescale=True`, applying `raster:bands`
130
+ scale/offset, with `dtype=float64` and NaN fill [S13]; do not decode again.
131
+ - `xarray.open_zarr(...)` defaults to `mask_and_scale=True` (CF decoding) and
132
+ lazy Dask chunks when Dask is installed [S14].
133
+
134
+ Decoding rules and sensor offsets: [satellite preprocessing](../satellite-preprocessing/SKILL.md).
135
+
136
+ ## Load many items as a lazy cube
137
+
138
+ ```python
139
+ import odc.stac
140
+
141
+ ds = odc.stac.load(
142
+ items, bands=["red", "nir", "scl"],
143
+ crs="EPSG:32633", resolution=20, # explicit output grid
144
+ bbox=[13.30, 52.45, 13.50, 52.55],
145
+ groupby="solar_day", # merge same-pass tiles
146
+ chunks={"x": 2048, "y": 2048}, # Dask-backed, nothing read yet
147
+ )
148
+ ```
149
+
150
+ `groupby="solar_day"` places items from the same solar day in one time slice;
151
+ by default overlapping pixels are filled from the first valid item in a
152
+ deterministic time/id order; `patch_url` can sign hrefs (e.g. `planetary_computer.sign`)
153
+ [S15]. Set `resampling` per band, e.g. nearest for categorical `scl` [S15]. In
154
+ the test above, 4 tile-items became 2 dates. Record `crs`, `resolution`,
155
+ `groupby`, `resampling` and library versions with the outputs.
156
+
157
+ ## Cache and pin for reproducibility
158
+
159
+ GDAL's `/vsicurl/` cache is in-process memory only [S11]; it is not a
160
+ reproducibility mechanism. For results that must be re-verified:
161
+
162
+ 1. Pin collection + item ids and asset keys; store unsigned hrefs.
163
+ 2. Copy the exact bytes you analysed to a local or bucket cache and record
164
+ SHA-256 and size; verify hashes before reuse.
165
+ 3. Record processing versions, encoding metadata, loader parameters, library and
166
+ GDAL versions, and the search parameters.
167
+ 4. Keep timestamps and machine paths outside the hashed part of a manifest.
168
+
169
+ ## Verify with Terraproof
170
+
171
+ ```bash
172
+ python -m terraproof check source-item.json
173
+ python -m terraproof check subset_red.tif --expect reflectance
174
+ ```
175
+
176
+ `stac.provenance` checks Item time and a projection code, not full lineage,
177
+ licences or calibration. Raster outputs get `crs.defined`, `crs.consistent`,
178
+ `raster.nodata_declared`, `raster.grid_alignment`, `raster.cog_layout`, and
179
+ `rs.reflectance_range` with `--expect reflectance` (only after decoding).
180
+
181
+ Use `--manifest run.json --require-provenance` for `provenance.reproducible`
182
+ (re-hashes manifest inputs/outputs; warns on tool-version drift, fails on content
183
+ drift). Add `--time-range START END` for `rs.temporal_scope` on source Items.
184
+ For `rs.scale_applied_once`, compare a decoded raster with its raw source using
185
+ `--reference-input RAW.tif --encoding s2-l2a` or `landsat-c2-l2`; the sampled
186
+ output is compared with DN × scale + offset under that declared encoding. For
187
+ `s2-l2a` also pass `--decode-offset`: -0.1 for ESA DNs from processing baseline
188
+ 04.00, 0 for earlier baselines and for distributions that already applied it
189
+ (an Earth Search item says `earthsearch:boa_offset_applied: true`).
190
+
191
+ **Not checked automatically:** whether the search returned the right items,
192
+ whether pinned items still exist upstream, licence compliance and transfer
193
+ costs. Manifest credential guards reject known secret-bearing paths/URLs, but
194
+ do not audit every application log or prevent all signed-URL leakage.
195
+
196
+ ## Sources
197
+
198
+ - [S1 — STAC API Item Search](https://github.com/radiantearth/stac-api-spec/blob/main/item-search/README.md): parameters, bbox/intersects exclusivity, datetime syntax, limit and pagination.
199
+ - [S2 — STAC Item specification](https://github.com/radiantearth/stac-spec/blob/master/item-spec/item-spec.md): required fields, id uniqueness, UTC datetime.
200
+ - [S3 — STAC API Query extension](https://github.com/stac-api-extensions/query): `query` syntax and operators.
201
+ - [S4 — STAC API Filter extension](https://github.com/stac-api-extensions/filter): `filter`, `filter-lang`, CQL2 text/JSON, queryables.
202
+ - [S5 — pystac-client `Client`](https://github.com/stac-utils/pystac-client/blob/main/pystac_client/client.py): `open(modifier=...)`, `search()` parameters and defaults, `conforms_to`.
203
+ - [S6 — STAC processing extension](https://github.com/stac-extensions/processing): `processing:version` (e.g. Sentinel processing baseline), `processing:software`, lineage links.
204
+ - [S7 — STAC Sentinel-2 extension](https://github.com/stac-extensions/sentinel-2): `s2:processing_baseline` deprecated in favour of `processing:version`.
205
+ - [S8 — STAC raster extension](https://github.com/stac-extensions/raster): scale/offset semantics; Earth Search behaviour observed by a live query and rasterio read (October 2026).
206
+ - [S9 — Planetary Computer SDK](https://github.com/microsoft/planetary-computer-sdk-for-python): `sign`, `sign_inplace`, token expiry and `msft:expiry`.
207
+ - [S10 — Registry of Open Data on AWS, USGS Landsat](https://registry.opendata.aws/usgs-landsat/): `usgs-landsat` bucket `RequesterPays: True`.
208
+ - [S11 — GDAL virtual file systems](https://gdal.org/en/stable/user/virtual_file_systems.html): `/vsicurl/` range requests, chunking/cache, `/vsis3/`, `AWS_REQUEST_PAYER`, `AWS_NO_SIGN_REQUEST`, retries, cloud-friendly TIFF layout.
209
+ - [S12 — GDAL configuration options](https://gdal.org/en/stable/user/configoptions.html): `GDAL_DISABLE_READDIR_ON_OPEN`, `CPL_VSIL_CURL_ALLOWED_EXTENSIONS`.
210
+ - [S13 — stackstac `stack()`](https://github.com/gjoseph92/stackstac/blob/main/stackstac/stack.py): `rescale=True`, `dtype`, `fill_value`, `resampling` defaults.
211
+ - [S14 — xarray `open_zarr`](https://github.com/pydata/xarray/blob/main/xarray/backends/zarr.py): `chunks` and `mask_and_scale` defaults.
212
+ - [S15 — odc-stac `load`](https://odc-stac.readthedocs.io/en/latest/_api/odc.stac.load.html): `groupby`, `chunks`, `crs`, `resolution`, `bbox`, `resampling`, `patch_url`, fuse behaviour.
@@ -1,217 +1,218 @@
1
- ---
2
- name: time-series-and-change
3
- description: Build analysis-ready satellite time series and detect change defensibly, covering per-observation masking and decoding, compositing, gap handling, temporal alignment, per-date index versus index of a composite, seasonality and phenology confounds, thresholded differences, trend and breakpoint methods, post-classification comparison and validation of change with reference data; use for multi-date optical or SAR monitoring, composites and change maps.
4
- license: MIT
5
- ---
6
-
7
- # Time series and change detection
8
-
9
- ## Define the change question first
10
-
11
- State what change means (land-cover conversion, disturbance, flooding, gradual
12
- trend), the minimum detectable size and magnitude, the period and the
13
- observation frequency needed. Different change-detection procedures produce
14
- different change maps even in the same environment [S1]; the question decides the
15
- method, not the other way round. Reviews organise Landsat time-series change
16
- detection by temporal frequency, preprocessing, algorithm and application [S2].
17
-
18
- Related skills: [satellite preprocessing](../satellite-preprocessing/SKILL.md)
19
- (decoding, QA masks, single-period composites),
20
- [spectral indices](../spectral-indices/SKILL.md) (formulas, dNBR),
21
- [SAR basics](../sar-basics/SKILL.md) (backscatter scales, orbit consistency),
22
- [STAC and cloud access](../stac-and-cloud-access/SKILL.md) (search, loading,
23
- provenance), [raster processing](../raster-processing/SKILL.md) (grids,
24
- resampling), [accuracy assessment](../accuracy-assessment/SKILL.md) (validation).
25
- Shared rules: [engineering](../../instructions/engineering.md),
26
- [simplicity](../../instructions/simplicity.md), [security](../../instructions/security.md).
27
-
28
- ## Build an analysis-ready time series
29
-
30
- Process each observation **before** stacking or compositing:
31
-
32
- 1. Decode scale/offset exactly once and mask fill, cloud, shadow and other QA
33
- classes per sensor ([satellite preprocessing](../satellite-preprocessing/SKILL.md)).
34
- Check whether your loader already decoded the data
35
- ([STAC and cloud access](../stac-and-cloud-access/SKILL.md#know-what-your-loader-decodes)).
36
- 2. Put all dates on **one grid** (CRS, transform, shape); categorical QA layers
37
- with nearest neighbour.
38
- 3. Merge tiles of the same acquisition into one observation (e.g. odc-stac
39
- `groupby="solar_day"`) so overlaps are not counted as extra dates [S3].
40
- 4. Keep one consistent product definition: processing level and baseline,
41
- sensor, band (B08 vs B8A) and, for SAR, quantity/scale and relative orbit.
42
- 5. Keep per-observation provenance: item id, acquisition time (UTC), processing
43
- version and mask policy.
44
-
45
- Store a **valid-observation count** per pixel and period beside every composite
46
- or statistic. A median of two valid observations is not comparable with a median
47
- of twenty.
48
-
49
- ## Handle gaps without inventing data
50
-
51
- - Invalid pixels stay nodata (NaN or a declared nodata), never 0 — zero is a
52
- valid reflectance or index value.
53
- - Set a minimum valid count per period and mask results below it; report the
54
- masked fraction.
55
- - Interpolation or gap filling is a model: label filled values, keep the
56
- original count, and never treat filled values as observations in validation.
57
- - Irregular sampling (orbit changes, constellation gaps, seasonal cloud) biases
58
- composites towards the clearer part of a period; report the dates that
59
- actually contributed.
60
-
61
- ## Align observations in time
62
-
63
- STAC `datetime` is UTC [S4]. Define periods (calendar months, 16-day windows,
64
- seasons) explicitly, and whether an observation belongs to a period by its UTC
65
- timestamp or local solar day. For bi-temporal change use comparable dates
66
- (anniversary dates or the same phenological window), the same sensor geometry
67
- (SAR: same relative orbit) and the same processing baseline where possible.
68
-
69
- ## Composite of indices is not index of composite
70
-
71
- For a nonlinear index such as NDVI, the median (or mean) of per-date indices
72
- differs in general from the index of per-band composites, and per-band medians can
73
- come from **different dates**. Three valid dates (red, NIR):
74
- (0.05, 0.40), (0.10, 0.20), (0.04, 0.30):
75
-
76
- ```text
77
- per-date NDVI = 0.778, 0.333, 0.765 → median of NDVI = 0.765
78
- median red, median NIR = 0.05 (date 1), 0.30 (date 3) → NDVI of medians = 0.714
79
- ```
80
-
81
- Pick one, name it in metadata and outputs, and use it consistently across
82
- periods. A medoid or best-observation composite keeps real spectra from a single
83
- date ([satellite preprocessing](../satellite-preprocessing/SKILL.md)). The code below computes both, with counts:
84
-
85
- ```python
86
- import numpy as np
87
- import xarray as xr
88
-
89
- def ndvi(red, nir):
90
- den = nir + red
91
- return ((nir - red) / den).where(den != 0)
92
-
93
- def monthly_products(red, nir, min_obs=3):
94
- """red, nir: decoded, masked reflectance (NaN = invalid), dims (time, y, x)."""
95
- valid = np.isfinite(red) & np.isfinite(nir) & ((red + nir) != 0)
96
- red, nir = red.where(valid), nir.where(valid)
97
- count = valid.resample(time="1MS").sum()
98
- median_of_ndvi = ndvi(red, nir).resample(time="1MS").median()
99
- ndvi_of_median = ndvi(red.resample(time="1MS").median(),
100
- nir.resample(time="1MS").median())
101
- enough = count >= min_obs
102
- return xr.Dataset({
103
- "valid_count": count,
104
- "median_of_ndvi": median_of_ndvi.where(enough),
105
- "ndvi_of_median": ndvi_of_median.where(enough),
106
- })
107
- ```
108
-
109
- Both products use the same observations: finite red/NIR pairs with a nonzero
110
- NDVI denominator. Undefined per-date NDVI never increases `valid_count` or
111
- satisfies `min_obs`. On the three dates above this returns 0.765 and 0.714 with
112
- `valid_count` 3. For
113
- Dask-backed arrays, test chunking along `time` before relying on median
114
- reductions; write outputs with explicit nodata
115
- ([raster processing](../raster-processing/SKILL.md)).
116
-
117
- ## Separate seasonality and phenology from change
118
-
119
- Vegetation indices, soil moisture, snow and water levels vary within the year.
120
- A difference between a spring and a summer image is mostly phenology. Options:
121
-
122
- - compare the same season or phenological stage across years;
123
- - use a multi-year baseline per period (e.g. same month in prior years) and
124
- express change as a departure from it;
125
- - use models that represent seasonality explicitly (harmonic or seasonal terms),
126
- as BFAST and CCDC do [S5, S6].
127
-
128
- Also check for non-land-change causes: residual cloud/shadow, sensor or baseline
129
- changes, illumination and view geometry, and (SAR) moisture and incidence angle.
130
-
131
- ## Thresholded differences
132
-
133
- Bi-temporal differencing (e.g. ΔNDVI, dNBR) or SAR log ratios
134
- (`log10(date2/date1)` on linear power) is simple and transparent
135
- ([spectral indices](../spectral-indices/SKILL.md), [SAR basics](../sar-basics/SKILL.md)).
136
- The corresponding difference in dB is ten times that log ratio; declare the
137
- units before selecting a threshold.
138
-
139
- - Use the intersection of both dates' valid masks.
140
- - No universal threshold exists; derive and document it for the study area
141
- (reference data, histogram analysis) and report sensitivity to it.
142
- - A difference measures signal change, not cause; interpret with the change
143
- definition and validate.
144
-
145
- ## Trend and breakpoint methods
146
-
147
- Dense time-series methods model each pixel's trajectory and flag departures:
148
-
149
- - **BFAST** decomposes a series into trend, seasonal and remainder components and
150
- detects abrupt changes in the trend and seasonal components [S5].
151
- - **CCDC** uses all available observations, iteratively fitting harmonic
152
- functions and finding temporal breakpoints [S6, S7].
153
- - **LandTrendr** temporally segments yearly Landsat trajectories into linear
154
- segments to characterise disturbance and recovery [S8, S7].
155
-
156
- Their parameters, input requirements and outputs are compared in
157
- [references/change-methods.md](references/change-methods.md). Each needs a
158
- consistent, well-masked series; gaps, undetected clouds and baseline changes
159
- create false breaks. Treat their parameters as model choices to document and
160
- test, not universal defaults.
161
-
162
- ## Post-classification comparison
163
-
164
- Comparing two independently classified maps labels every classification error
165
- in either date as change, and the accuracies of the two single-date maps say
166
- nothing about the accuracy of the change classes [S9]. Prefer mapping change
167
- directly (time-series or multi-date classification). If maps must be compared,
168
- assess the resulting change map itself.
169
-
170
- ## Validate change with reference data
171
-
172
- Change is usually rare, so assessment needs a probability sample **stratified by
173
- the change map's classes** (e.g. loss, gain, stable) with enough units in the
174
- change strata, reference labels that cover both dates, and area-adjusted
175
- estimates with confidence intervals [S9, S10]. Follow
176
- [accuracy assessment](../accuracy-assessment/SKILL.md); do not report change area
177
- as a pixel count of the change map.
178
-
179
- ## Verify with Terraproof
180
-
181
- ```bash
182
- python -m terraproof check ndvi_2023-06.tif ndvi_2024-06.tif --expect index
183
- python -m terraproof check composite_count_2024-06.tif
184
- python -m terraproof check source-item.json
185
- ```
186
-
187
- `raster.grid_alignment` (dates on one grid), `raster.nodata_declared`,
188
- `crs.defined`/`crs.consistent`, `rs.index_range` (normalised indices, not dNBR or
189
- differences), `rs.reflectance_range` (decoded reflectance composites) and
190
- `stac.provenance` apply today.
191
-
192
- For source Items, add `--time-range START END` to run `rs.temporal_scope`.
193
- For individual decoded observations, `--qa QA.tif --qa-kind s2-scl` runs
194
- `rs.cloud_mask_applied`; use `landsat-qa-pixel` for Landsat. Compare a decoded
195
- observation to its raw source with `--reference-input RAW.tif --encoding s2-l2a`
196
- or `landsat-c2-l2` for `rs.scale_applied_once`. These sampled pixel comparisons
197
- do not validate a composite against a single acquisition's QA or raw DN.
198
- `--manifest run.json --require-provenance` runs `provenance.reproducible`.
199
- For change-map reference samples and estimates, follow the current CLI example
200
- in [accuracy assessment](../accuracy-assessment/SKILL.md#verify-with-terraproof).
201
-
202
- **Not checked automatically:** composite method and its consistency across
203
- periods, valid-count thresholds, phenological comparability, change thresholds,
204
- breakpoint-model parameters, and whether a detected change is real.
205
-
206
- ## Sources
207
-
208
- - [S1 — Singh, A. (1989). Digital change detection techniques using remotely-sensed data. International Journal of Remote Sensing 10(6):989–1003](https://doi.org/10.1080/01431168908903939): different procedures give different change maps.
209
- - [S2 — Zhu, Z. (2017). Change detection using Landsat time series: a review of frequencies, preprocessing, algorithms, and applications. ISPRS J. Photogramm. Remote Sens. 130:370–384](https://doi.org/10.1016/j.isprsjprs.2017.06.013).
210
- - [S3 — odc-stac `load`](https://odc-stac.readthedocs.io/en/latest/_api/odc.stac.load.html): `groupby="solar_day"` and fusing of overlapping items.
211
- - [S4 — STAC Item specification](https://github.com/radiantearth/stac-spec/blob/master/item-spec/item-spec.md): `datetime` in UTC.
212
- - [S5 — Verbesselt, J., Hyndman, R., Newnham, G., Culvenor, D. (2010). Detecting trend and seasonal changes in satellite image time series. Remote Sensing of Environment 114(1):106–115](https://doi.org/10.1016/j.rse.2009.08.014); [bfast package description](https://github.com/cran/bfast/blob/master/DESCRIPTION): trend/seasonal/remainder decomposition and break detection.
213
- - [S6 — Zhu, Z., Woodcock, C.E. (2014). Continuous change detection and classification of land cover using all available Landsat data. Remote Sensing of Environment 144:152–171](https://doi.org/10.1016/j.rse.2014.01.011).
214
- - [S7 — Google Earth Engine `ee.Algorithms.TemporalSegmentation.Ccdc`](https://developers.google.com/earth-engine/apidocs/ee-algorithms-temporalsegmentation-ccdc) and [`LandTrendr`](https://developers.google.com/earth-engine/apidocs/ee-algorithms-temporalsegmentation-landtrendr): harmonic-function breakpoints; temporal segmentation of spectral trajectories.
215
- - [S8 — Kennedy, R.E., Yang, Z., Cohen, W.B. (2010). Detecting trends in forest disturbance and recovery using yearly Landsat time series: 1. LandTrendr. Remote Sensing of Environment 114(12):2897–2910](https://doi.org/10.1016/j.rse.2010.07.008).
216
- - [S9 — FAO (2016). Map accuracy assessment and area estimation: a practical guide](https://www.fao.org/3/i5601e/i5601e.pdf): accuracy of change must be assessed on change, not on two single-date maps; stratification for change classes.
217
- - [S10 — Olofsson, P. et al. (2014). Good practices for estimating area and assessing accuracy of land change. Remote Sensing of Environment 148:42–57](https://doi.org/10.1016/j.rse.2014.02.015).
1
+ ---
2
+ name: time-series-and-change
3
+ description: Build analysis-ready satellite time series and detect change defensibly, covering per-observation masking and decoding, compositing, gap handling, temporal alignment, per-date index versus index of a composite, seasonality and phenology confounds, thresholded differences, trend and breakpoint methods, post-classification comparison and validation of change with reference data; use for multi-date optical or SAR monitoring, composites and change maps.
4
+ license: MIT
5
+ ---
6
+
7
+ # Time series and change detection
8
+
9
+ ## Define the change question first
10
+
11
+ State what change means (land-cover conversion, disturbance, flooding, gradual
12
+ trend), the minimum detectable size and magnitude, the period and the
13
+ observation frequency needed. Different change-detection procedures produce
14
+ different change maps even in the same environment [S1]; the question decides the
15
+ method, not the other way round. Reviews organise Landsat time-series change
16
+ detection by temporal frequency, preprocessing, algorithm and application [S2].
17
+
18
+ Related skills: [satellite preprocessing](../satellite-preprocessing/SKILL.md)
19
+ (decoding, QA masks, single-period composites),
20
+ [spectral indices](../spectral-indices/SKILL.md) (formulas, dNBR),
21
+ [SAR basics](../sar-basics/SKILL.md) (backscatter scales, orbit consistency),
22
+ [STAC and cloud access](../stac-and-cloud-access/SKILL.md) (search, loading,
23
+ provenance), [raster processing](../raster-processing/SKILL.md) (grids,
24
+ resampling), [accuracy assessment](../accuracy-assessment/SKILL.md) (validation).
25
+ Shared rules: [engineering](../../instructions/engineering.md),
26
+ [simplicity](../../instructions/simplicity.md), [security](../../instructions/security.md).
27
+
28
+ ## Build an analysis-ready time series
29
+
30
+ Process each observation **before** stacking or compositing:
31
+
32
+ 1. Decode scale/offset exactly once and mask fill, cloud, shadow and other QA
33
+ classes per sensor ([satellite preprocessing](../satellite-preprocessing/SKILL.md)).
34
+ Check whether your loader already decoded the data
35
+ ([STAC and cloud access](../stac-and-cloud-access/SKILL.md#know-what-your-loader-decodes)).
36
+ 2. Put all dates on **one grid** (CRS, transform, shape); categorical QA layers
37
+ with nearest neighbour.
38
+ 3. Merge tiles of the same acquisition into one observation (e.g. odc-stac
39
+ `groupby="solar_day"`) so overlaps are not counted as extra dates [S3].
40
+ 4. Keep one consistent product definition: processing level and baseline,
41
+ sensor, band (B08 vs B8A) and, for SAR, quantity/scale and relative orbit.
42
+ 5. Keep per-observation provenance: item id, acquisition time (UTC), processing
43
+ version and mask policy.
44
+
45
+ Store a **valid-observation count** per pixel and period beside every composite
46
+ or statistic. A median of two valid observations is not comparable with a median
47
+ of twenty.
48
+
49
+ ## Handle gaps without inventing data
50
+
51
+ - Invalid pixels stay nodata (NaN or a declared nodata), never 0 — zero is a
52
+ valid reflectance or index value.
53
+ - Set a minimum valid count per period and mask results below it; report the
54
+ masked fraction.
55
+ - Interpolation or gap filling is a model: label filled values, keep the
56
+ original count, and never treat filled values as observations in validation.
57
+ - Irregular sampling (orbit changes, constellation gaps, seasonal cloud) biases
58
+ composites towards the clearer part of a period; report the dates that
59
+ actually contributed.
60
+
61
+ ## Align observations in time
62
+
63
+ STAC `datetime` is UTC [S4]. Define periods (calendar months, 16-day windows,
64
+ seasons) explicitly, and whether an observation belongs to a period by its UTC
65
+ timestamp or local solar day. For bi-temporal change use comparable dates
66
+ (anniversary dates or the same phenological window), the same sensor geometry
67
+ (SAR: same relative orbit) and the same processing baseline where possible.
68
+
69
+ ## Composite of indices is not index of composite
70
+
71
+ For a nonlinear index such as NDVI, the median (or mean) of per-date indices
72
+ differs in general from the index of per-band composites, and per-band medians can
73
+ come from **different dates**. Three valid dates (red, NIR):
74
+ (0.05, 0.40), (0.10, 0.20), (0.04, 0.30):
75
+
76
+ ```text
77
+ per-date NDVI = 0.778, 0.333, 0.765 → median of NDVI = 0.765
78
+ median red, median NIR = 0.05 (date 1), 0.30 (date 3) → NDVI of medians = 0.714
79
+ ```
80
+
81
+ Pick one, name it in metadata and outputs, and use it consistently across
82
+ periods. A medoid or best-observation composite keeps real spectra from a single
83
+ date ([satellite preprocessing](../satellite-preprocessing/SKILL.md)). The code below computes both, with counts:
84
+
85
+ ```python
86
+ import numpy as np
87
+ import xarray as xr
88
+
89
+ def ndvi(red, nir):
90
+ den = nir + red
91
+ return ((nir - red) / den).where(den != 0)
92
+
93
+ def monthly_products(red, nir, min_obs=3):
94
+ """red, nir: decoded, masked reflectance (NaN = invalid), dims (time, y, x)."""
95
+ valid = np.isfinite(red) & np.isfinite(nir) & ((red + nir) != 0)
96
+ red, nir = red.where(valid), nir.where(valid)
97
+ count = valid.resample(time="1MS").sum()
98
+ median_of_ndvi = ndvi(red, nir).resample(time="1MS").median()
99
+ ndvi_of_median = ndvi(red.resample(time="1MS").median(),
100
+ nir.resample(time="1MS").median())
101
+ enough = count >= min_obs
102
+ return xr.Dataset({
103
+ "valid_count": count,
104
+ "median_of_ndvi": median_of_ndvi.where(enough),
105
+ "ndvi_of_median": ndvi_of_median.where(enough),
106
+ })
107
+ ```
108
+
109
+ Both products use the same observations: finite red/NIR pairs with a nonzero
110
+ NDVI denominator. Undefined per-date NDVI never increases `valid_count` or
111
+ satisfies `min_obs`. On the three dates above this returns 0.765 and 0.714 with
112
+ `valid_count` 3. For
113
+ Dask-backed arrays, test chunking along `time` before relying on median
114
+ reductions; write outputs with explicit nodata
115
+ ([raster processing](../raster-processing/SKILL.md)).
116
+
117
+ ## Separate seasonality and phenology from change
118
+
119
+ Vegetation indices, soil moisture, snow and water levels vary within the year.
120
+ A difference between a spring and a summer image is mostly phenology. Options:
121
+
122
+ - compare the same season or phenological stage across years;
123
+ - use a multi-year baseline per period (e.g. same month in prior years) and
124
+ express change as a departure from it;
125
+ - use models that represent seasonality explicitly (harmonic or seasonal terms),
126
+ as BFAST and CCDC do [S5, S6].
127
+
128
+ Also check for non-land-change causes: residual cloud/shadow, sensor or baseline
129
+ changes, illumination and view geometry, and (SAR) moisture and incidence angle.
130
+
131
+ ## Thresholded differences
132
+
133
+ Bi-temporal differencing (e.g. ΔNDVI, dNBR) or SAR log ratios
134
+ (`log10(date2/date1)` on linear power) is simple and transparent
135
+ ([spectral indices](../spectral-indices/SKILL.md), [SAR basics](../sar-basics/SKILL.md)).
136
+ The corresponding difference in dB is ten times that log ratio; declare the
137
+ units before selecting a threshold.
138
+
139
+ - Use the intersection of both dates' valid masks.
140
+ - No universal threshold exists; derive and document it for the study area
141
+ (reference data, histogram analysis) and report sensitivity to it.
142
+ - A difference measures signal change, not cause; interpret with the change
143
+ definition and validate.
144
+
145
+ ## Trend and breakpoint methods
146
+
147
+ Dense time-series methods model each pixel's trajectory and flag departures:
148
+
149
+ - **BFAST** decomposes a series into trend, seasonal and remainder components and
150
+ detects abrupt changes in the trend and seasonal components [S5].
151
+ - **CCDC** uses all available observations, iteratively fitting harmonic
152
+ functions and finding temporal breakpoints [S6, S7].
153
+ - **LandTrendr** temporally segments yearly Landsat trajectories into linear
154
+ segments to characterise disturbance and recovery [S8, S7].
155
+
156
+ Their parameters, input requirements and outputs are compared in
157
+ [references/change-methods.md](references/change-methods.md). Each needs a
158
+ consistent, well-masked series; gaps, undetected clouds and baseline changes
159
+ create false breaks. Treat their parameters as model choices to document and
160
+ test, not universal defaults.
161
+
162
+ ## Post-classification comparison
163
+
164
+ Comparing two independently classified maps labels every classification error
165
+ in either date as change, and the accuracies of the two single-date maps say
166
+ nothing about the accuracy of the change classes [S9]. Prefer mapping change
167
+ directly (time-series or multi-date classification). If maps must be compared,
168
+ assess the resulting change map itself.
169
+
170
+ ## Validate change with reference data
171
+
172
+ Change is usually rare, so assessment needs a probability sample **stratified by
173
+ the change map's classes** (e.g. loss, gain, stable) with enough units in the
174
+ change strata, reference labels that cover both dates, and area-adjusted
175
+ estimates with confidence intervals [S9, S10]. Follow
176
+ [accuracy assessment](../accuracy-assessment/SKILL.md); do not report change area
177
+ as a pixel count of the change map.
178
+
179
+ ## Verify with Terraproof
180
+
181
+ ```bash
182
+ python -m terraproof check ndvi_2023-06.tif ndvi_2024-06.tif --expect index
183
+ python -m terraproof check composite_count_2024-06.tif
184
+ python -m terraproof check source-item.json
185
+ ```
186
+
187
+ `raster.grid_alignment` (dates on one grid), `raster.nodata_declared`,
188
+ `crs.defined`/`crs.consistent`, `rs.index_range` (normalised indices, not dNBR or
189
+ differences), `rs.reflectance_range` (decoded reflectance composites) and
190
+ `stac.provenance` apply today.
191
+
192
+ For source Items, add `--time-range START END` to run `rs.temporal_scope`.
193
+ For individual decoded observations, `--qa QA.tif --qa-kind s2-scl` runs
194
+ `rs.cloud_mask_applied`; use `landsat-qa-pixel` for Landsat. Compare a decoded
195
+ observation to its raw source with `--reference-input RAW.tif --encoding s2-l2a`
196
+ (with `--decode-offset`, since the S2 offset depends on baseline and distributor)
197
+ or `landsat-c2-l2` for `rs.scale_applied_once`. These sampled pixel comparisons
198
+ do not validate a composite against a single acquisition's QA or raw DN.
199
+ `--manifest run.json --require-provenance` runs `provenance.reproducible`.
200
+ For change-map reference samples and estimates, follow the current CLI example
201
+ in [accuracy assessment](../accuracy-assessment/SKILL.md#verify-with-terraproof).
202
+
203
+ **Not checked automatically:** composite method and its consistency across
204
+ periods, valid-count thresholds, phenological comparability, change thresholds,
205
+ breakpoint-model parameters, and whether a detected change is real.
206
+
207
+ ## Sources
208
+
209
+ - [S1 — Singh, A. (1989). Digital change detection techniques using remotely-sensed data. International Journal of Remote Sensing 10(6):989–1003](https://doi.org/10.1080/01431168908903939): different procedures give different change maps.
210
+ - [S2 — Zhu, Z. (2017). Change detection using Landsat time series: a review of frequencies, preprocessing, algorithms, and applications. ISPRS J. Photogramm. Remote Sens. 130:370–384](https://doi.org/10.1016/j.isprsjprs.2017.06.013).
211
+ - [S3 — odc-stac `load`](https://odc-stac.readthedocs.io/en/latest/_api/odc.stac.load.html): `groupby="solar_day"` and fusing of overlapping items.
212
+ - [S4 — STAC Item specification](https://github.com/radiantearth/stac-spec/blob/master/item-spec/item-spec.md): `datetime` in UTC.
213
+ - [S5 — Verbesselt, J., Hyndman, R., Newnham, G., Culvenor, D. (2010). Detecting trend and seasonal changes in satellite image time series. Remote Sensing of Environment 114(1):106–115](https://doi.org/10.1016/j.rse.2009.08.014); [bfast package description](https://github.com/cran/bfast/blob/master/DESCRIPTION): trend/seasonal/remainder decomposition and break detection.
214
+ - [S6 — Zhu, Z., Woodcock, C.E. (2014). Continuous change detection and classification of land cover using all available Landsat data. Remote Sensing of Environment 144:152–171](https://doi.org/10.1016/j.rse.2014.01.011).
215
+ - [S7 — Google Earth Engine `ee.Algorithms.TemporalSegmentation.Ccdc`](https://developers.google.com/earth-engine/apidocs/ee-algorithms-temporalsegmentation-ccdc) and [`LandTrendr`](https://developers.google.com/earth-engine/apidocs/ee-algorithms-temporalsegmentation-landtrendr): harmonic-function breakpoints; temporal segmentation of spectral trajectories.
216
+ - [S8 — Kennedy, R.E., Yang, Z., Cohen, W.B. (2010). Detecting trends in forest disturbance and recovery using yearly Landsat time series: 1. LandTrendr. Remote Sensing of Environment 114(12):2897–2910](https://doi.org/10.1016/j.rse.2010.07.008).
217
+ - [S9 — FAO (2016). Map accuracy assessment and area estimation: a practical guide](https://www.fao.org/3/i5601e/i5601e.pdf): accuracy of change must be assessed on change, not on two single-date maps; stratification for change classes.
218
+ - [S10 — Olofsson, P. et al. (2014). Good practices for estimating area and assessing accuracy of land change. Remote Sensing of Environment 148:42–57](https://doi.org/10.1016/j.rse.2014.02.015).
@@ -399,3 +399,48 @@ repository's MIT license. No external implementation or data is vendored.
399
399
  Existing product skills, sources and third-party attribution remain included in
400
400
  candidate wheels. Evidence bundles are local integrity records, not signatures
401
401
  or scientific certification.
402
+
403
+ ---
404
+
405
+ ## Real-data held-out verification cases (Phase 8)
406
+
407
+ The bundle `evals/verification-heldout-real/` fetches the following public
408
+ sources with fixed URLs (no account, API key, requester-pays bucket or expiring
409
+ signed URL) into a local, git-ignored cache; binaries are never committed. The
410
+ SHA-256 of every fetched file is recorded in the bundle's cache manifest.
411
+
412
+ ### Sentinel-2 L2A (Copernicus, via Earth Search)
413
+
414
+ - **Data:** single scene `S2B_32TMS_20250831_0_L2A` (MGRS tile 32TMS, acquired
415
+ 2025-08-31, Bernese Oberland, Switzerland), served as stage-1 COGs by
416
+ element84's Earth Search STAC API v1
417
+ (`https://earth-search.aws.element84.com/v1`) with companion tileinfo JSON
418
+ and granule metadata XML.
419
+ - **Licence:** ESA Copernicus Sentinel data, free of charge under the ESA
420
+ Sentinel use conditions.
421
+ - **Required attribution:** *"Contains modified Copernicus Sentinel data
422
+ 2025."*
423
+
424
+ ### Copernicus DEM GLO-30
425
+
426
+ - **Data:** small windows of tiles `N28 E084` (Nepal) and `N78 E016`
427
+ (Svalbard), 30 m elevation rasters (EPSG:4326), from the public
428
+ Copernicus DEM S3 bucket on AWS Open Data
429
+ (`copernicus-dem-30m.s3.amazonaws.com`).
430
+ - **Licence:** Copernicus Digital Elevation Model — © DLR 2025, made available
431
+ by ESA/DLR for the Copernicus programme for free use with attribution.
432
+ - **Required attribution:** *"Contains Copernicus DEM data"*/*"© DLR"*.
433
+
434
+ ### USGS 3DEP 1/3 arc-second
435
+
436
+ - **Data:** windows of tiles `n31w091` (Mississippi delta) and `n22w159`
437
+ (Kauai) with their FGDC metadata sidecars, from the public USGS
438
+ (`prd-tnm.s3.amazonaws.com`) staged elevation products (resolution 13).
439
+ - **Licence:** public domain — the sidecar itself states *"All 3DEP products
440
+ are public domain."*
441
+
442
+ ### Natural Earth 110m admin-0 countries
443
+
444
+ - **Data:** `ne_110m_admin_0_countries.geojson` pinned at tag v5.1.2 of
445
+ `https://github.com/nvkelso/natural-earth-vector` (published via GitHub raw).
446
+ - **Licence:** public domain (no restrictions, no attribution required).