terraproof 0.5.1 → 0.6.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.
@@ -61,6 +61,7 @@
61
61
  "crs.consistent",
62
62
  "raster.nodata_declared",
63
63
  "raster.resampling",
64
- "raster.cog_layout"
64
+ "raster.cog_layout",
65
+ "terrain.slope_consistent"
65
66
  ]
66
67
  }
@@ -178,24 +178,53 @@ union = gpd.overlay(gdf1, gdf2, how='union')
178
178
  ### Terrain Analysis
179
179
 
180
180
  ```python
181
- def terrain_metrics(dem_path):
182
- """Calculate slope, aspect, hillshade from DEM."""
183
- with rasterio.open(dem_path) as src:
184
- dem = src.read(1)
181
+ # Vertical units to metres; extend for your data. None means "assume metres".
182
+ Z_TO_METRES = {None: 1.0, "": 1.0, "m": 1.0, "metre": 1.0, "meter": 1.0, "metres": 1.0, "meters": 1.0,
183
+ "ft": 0.3048, "foot": 0.3048, "feet": 0.3048, "us-ft": 1200 / 3937, "us survey foot": 1200 / 3937}
185
184
 
186
- dy, dx = np.gradient(dem)
187
- slope = np.arctan(np.sqrt(dx**2 + dy**2)) * 180 / np.pi
188
- aspect = (90 - np.arctan2(-dy, dx) * 180 / np.pi) % 360
185
+ def terrain_metrics(dem_path, z_factor=None, azimuth=315.0, altitude=45.0):
186
+ """Slope (degrees), aspect (compass degrees the slope faces) and hillshade from a projected DEM.
189
187
 
190
- # Hillshade
191
- az_rad, alt_rad = np.radians(315), np.radians(45)
192
- hillshade = (np.sin(alt_rad) * np.sin(np.radians(slope)) +
193
- np.cos(alt_rad) * np.cos(np.radians(slope)) *
194
- np.cos(np.radians(aspect) - az_rad))
188
+ Gradients use the real pixel size from the transform (pixels are often not square), and
189
+ elevations are converted to metres from the band unit unless z_factor is given.
190
+ Nodata becomes NaN, so cells next to nodata are NaN too; flat cells have no aspect.
191
+ """
192
+ with rasterio.open(dem_path) as src:
193
+ if src.crs is None or src.crs.is_geographic:
194
+ raise ValueError("reproject the DEM to a projected CRS in metres first")
195
+ if src.crs.linear_units_factor[1] != 1.0:
196
+ raise ValueError("the CRS units are not metres; reproject or rescale the horizontal units")
197
+ a, b, _, d, e, _ = tuple(src.transform)[:6]
198
+ if b or d:
199
+ raise ValueError("resample a rotated or sheared DEM to a north-up grid first")
200
+ dem = src.read(1, masked=True).astype("float64").filled(np.nan)
201
+ unit = (src.units[0] or "").strip().lower() if src.units else None
202
+ if z_factor is None:
203
+ if unit not in Z_TO_METRES:
204
+ raise ValueError(f"unknown elevation unit {unit!r}; pass z_factor")
205
+ z_factor = Z_TO_METRES[unit]
206
+
207
+ # Signed spacing: one row step moves e metres north (e < 0 on north-up grids), one column a metres east.
208
+ dz_dnorth, dz_deast = np.gradient(dem * z_factor, e, a)
209
+ slope = np.degrees(np.arctan(np.hypot(dz_deast, dz_dnorth)))
210
+ aspect = np.degrees(np.arctan2(-dz_deast, -dz_dnorth)) % 360 # downslope direction, clockwise from north
211
+ aspect[slope == 0] = np.nan
212
+ # A central difference skips the centre cell, so nodata cells themselves must be masked explicitly.
213
+ slope[np.isnan(dem)] = np.nan
214
+ aspect[np.isnan(dem)] = np.nan
215
+
216
+ # Hillshade (Burrough & McDonnell): zenith = 90 - altitude; 0 = shadow, 1 = facing the sun.
217
+ s, alt = np.radians(slope), np.radians(altitude)
218
+ facing = np.cos(np.radians(azimuth) - np.radians(np.nan_to_num(aspect)))
219
+ hillshade = np.clip(np.sin(alt) * np.cos(s) + np.cos(alt) * np.sin(s) * facing, 0, 1)
195
220
 
196
221
  return slope, aspect, hillshade
197
222
  ```
198
223
 
224
+ Check the DEM before trusting any terrain metric: projected CRS in metres, north-up grid, the
225
+ band's vertical unit, and the real pixel size (`src.res`). A geographic DEM (degrees) or a
226
+ feet-vs-metres mismatch gives slopes that look plausible but are wrong.
227
+
199
228
  ### Network Analysis
200
229
 
201
230
  ```python
@@ -1,21 +1,34 @@
1
- # Upstream Attribution
2
-
3
- This skill is derived from the `geomaster` skill in `K-Dense-AI/scientific-agent-skills`.
4
-
5
- - **Upstream repository:** https://github.com/K-Dense-AI/scientific-agent-skills
6
- - **Upstream path:** `skills/geomaster/`
7
- - **License:** MIT (see [third_party/kdense-scientific-agent-skills/LICENSE](../../third_party/kdense-scientific-agent-skills/LICENSE))
8
- - **Imported commit:** `390f5146bf3c1877cf15636a3dd7b775e4f0f185`
9
- - **Import date:** 2026-08-25
10
- - **Local path:** `skills/geomaster/`
11
-
12
- ## Imported Files
13
-
14
- - `SKILL.md`
15
-
16
- ## Local modifications
17
-
18
- Initial import:
19
- - Local behavioral modifications: none (faithful vendoring, byte-for-byte identical to upstream).
20
-
21
- Any future AgentLayer modifications must be documented here.
1
+ # Upstream Attribution
2
+
3
+ This skill is derived from the `geomaster` skill in `K-Dense-AI/scientific-agent-skills`.
4
+
5
+ - **Upstream repository:** https://github.com/K-Dense-AI/scientific-agent-skills
6
+ - **Upstream path:** `skills/geomaster/`
7
+ - **License:** MIT (see [third_party/kdense-scientific-agent-skills/LICENSE](../../third_party/kdense-scientific-agent-skills/LICENSE))
8
+ - **Imported commit:** `390f5146bf3c1877cf15636a3dd7b775e4f0f185`
9
+ - **Import date:** 2026-08-25
10
+ - **Local path:** `skills/geomaster/`
11
+
12
+ ## Imported Files
13
+
14
+ - `SKILL.md`
15
+
16
+ ## Local modifications
17
+
18
+ Initial import:
19
+ - Local behavioral modifications: none (faithful vendoring, byte-for-byte identical to upstream).
20
+
21
+ 2026-10-24, terrain slope correctness fix (Terraproof):
22
+ - `SKILL.md`, section "Terrain Analysis": `terrain_metrics()` is rewritten. The upstream version called
23
+ `np.gradient(dem)` with no spacing, so it assumed 1-unit square pixels and equal vertical and horizontal
24
+ units, and its hillshade swapped the sine and cosine of the slope. The local version uses the signed pixel
25
+ size from the transform, converts the band's vertical unit to metres (or a given `z_factor`), refuses
26
+ geographic, non-metre, rotated or sheared grids, masks nodata as NaN, leaves flat cells without aspect, and
27
+ uses the standard hillshade formula. A short checklist follows the code.
28
+ - `references/code-examples.md`, example 68: the same `np.gradient(dem)` example is replaced by a pointer to
29
+ `terrain_metrics()` and the reason.
30
+ - Found by an independent review (Codex, 2026-10-24) while authoring the `terrain-slope-map` eval task.
31
+ Covered by `tests/python/test_skill_snippets.py`, which runs the snippet on synthetic DEMs.
32
+ - All other content is unchanged from upstream.
33
+
34
+ Any future modifications must be documented here.
@@ -358,24 +358,11 @@ def map_flood(dem_path, flood_level, output_path):
358
358
 
359
359
  ```python
360
360
  # 68. Slope and aspect from DEM
361
- def terrain_analysis(dem_path):
362
- import numpy as np
363
- from scipy import ndimage
364
-
365
- with rasterio.open(dem_path) as src:
366
- dem = src.read(1)
367
-
368
- # Calculate gradients
369
- dy, dx = np.gradient(dem)
370
-
371
- # Slope in degrees
372
- slope = np.arctan(np.sqrt(dx**2 + dy**2)) * 180 / np.pi
373
-
374
- # Aspect
375
- aspect = np.arctan2(-dy, dx) * 180 / np.pi
376
- aspect = (90 - aspect) % 360
377
-
378
- return slope, aspect
361
+ # Use terrain_metrics() in ../SKILL.md (section "Terrain Analysis"). It takes the real pixel size
362
+ # from the transform, converts vertical units to metres, refuses geographic or rotated grids and
363
+ # masks nodata. np.gradient(dem) without spacing assumes 1-unit square pixels and equal vertical
364
+ # and horizontal units, which gives wrong slopes for almost every real DEM.
365
+ slope, aspect, hillshade = terrain_metrics("dem.tif")
379
366
  ```
380
367
 
381
368
  ## Additional Examples (70-100)