From 2854891fca557a560856330fc8daece1d588b651 Mon Sep 17 00:00:00 2001 From: Al Handwerger <29788365+alhandwerger@users.noreply.github.com> Date: Sun, 22 Nov 2026 13:21:33 -0800 Subject: [PATCH 1/2] create_dem: make sure the DEM gets WGS84 ellipsoidal heights sardem converts Copernicus heights (EGM2008) to ellipsoidal heights with a GDAL warp. When PROJ cannot reach the geoid grid (the default with conda-forge proj), the DEM silently keeps geoid heights, which biases radar-geometry steps such as COMPASS geocoding by roughly dh / tan(look angle). Wrap the sardem call in a scoped context that enables PROJ network access, verifies the EGM2008 shift at the bbox centre and raises otherwise, then restores the previous setting. Co-Authored-By: Claude Opus 5.5 --- src/sweets/dem.py | 64 ++++++++++++++++++++++++++++++++++++++++------- tests/test_dem.py | 34 +++++++++++++++++++++++++ 2 files changed, 89 insertions(+), 9 deletions(-) create mode 100644 tests/test_dem.py diff --git a/src/sweets/dem.py b/src/sweets/dem.py index f6f8b0a..c27a1f2 100644 --- a/src/sweets/dem.py +++ b/src/sweets/dem.py @@ -1,5 +1,6 @@ from __future__ import annotations +import contextlib from os import fspath from pathlib import Path from typing import Tuple @@ -14,22 +15,67 @@ from sweets.utils import get_cache_dir +def _egm2008_shift(lon: float, lat: float) -> float: + """Return the height change PROJ applies at (lon, lat) from EGM2008 to WGS84 ellipsoidal heights.""" + from osgeo import osr + + src, dst = osr.SpatialReference(), osr.SpatialReference() + src.SetFromUserInput("EPSG:4326+3855") + dst.ImportFromEPSG(4979) + for srs in (src, dst): + srs.SetAxisMappingStrategy(osr.OAMS_TRADITIONAL_GIS_ORDER) + return osr.CoordinateTransformation(src, dst).TransformPoint(lon, lat, 0.0)[2] + + +@contextlib.contextmanager +def _geoid_grid_access(bbox: Tuple[float, float, float, float]): + """Let PROJ fetch the EGM2008 grid while the DEM is made, or raise if it cannot. + + sardem converts Copernicus heights (EGM2008) to WGS84 ellipsoidal heights with + a GDAL warp. PROJ needs the geoid grid for that; conda-forge `proj` ships no + geoid grids and PROJ network access is off by default. Without the grid, PROJ + applies a no-op vertical shift and the DEM silently keeps geoid heights (tens of + metres off), which then biases every radar-geometry step that uses it. + + Network access must be enabled before the first lookup because PROJ remembers a + grid it could not find. A locally installed grid is used as is. The previous + setting is restored afterwards. + """ + from osgeo import osr + + previous = osr.GetPROJEnableNetwork() + osr.SetPROJEnableNetwork(True) + try: + lon, lat = (bbox[0] + bbox[2]) / 2.0, (bbox[1] + bbox[3]) / 2.0 + if abs(_egm2008_shift(lon, lat)) < 1e-6: + raise RuntimeError( + "PROJ cannot apply the EGM2008 geoid, so the DEM would keep geoid heights " + "instead of WGS84 ellipsoidal heights. Allow network access, or install the " + "grid (`projsync --file us_nga_egm08_25.tif --user-writable-directory`, or " + "the conda-forge `proj-data` package), then retry." + ) + yield + finally: + osr.SetPROJEnableNetwork(previous) + + @log_runtime def create_dem(output_name: Filename, bbox: Tuple[float, float, float, float]) -> Path: - """Download a Copernicus Global DEM clipped to `bbox`.""" + """Download a Copernicus Global DEM clipped to `bbox`, in WGS84 ellipsoidal heights.""" output_name = Path(output_name).resolve() if output_name.exists(): logger.info(f"DEM already exists: {output_name}") return output_name - sardem.dem.main( - output_name=fspath(output_name), - bbox=bbox, - data_source="COP", - cache_dir=get_cache_dir(), - output_format="GTiff", - output_type="Float32", - ) + with _geoid_grid_access(bbox): + sardem.dem.main( + output_name=fspath(output_name), + bbox=bbox, + data_source="COP", + cache_dir=get_cache_dir(), + output_format="GTiff", + output_type="Float32", + ) return output_name diff --git a/tests/test_dem.py b/tests/test_dem.py new file mode 100644 index 0000000..96ecad2 --- /dev/null +++ b/tests/test_dem.py @@ -0,0 +1,34 @@ +from osgeo import osr +import pytest + +from sweets import dem + +BBOX = (-118.5, 33.6, -118.2, 33.9) + + +@pytest.fixture +def network_off(): + previous = osr.GetPROJEnableNetwork() + osr.SetPROJEnableNetwork(False) + yield + osr.SetPROJEnableNetwork(previous) + + +def test_create_dem_refuses_when_the_geoid_cannot_be_applied(monkeypatch, tmp_path, network_off): + # PROJ without a usable grid applies a no-op vertical shift + monkeypatch.setattr(dem, "_egm2008_shift", lambda lon, lat: 0.0) + called = [] + monkeypatch.setattr(dem.sardem.dem, "main", lambda **kwargs: called.append(kwargs)) + with pytest.raises(RuntimeError, match="EGM2008"): + dem.create_dem(tmp_path / "dem.tif", BBOX) + assert not called + assert osr.GetPROJEnableNetwork() is False + + +def test_network_is_enabled_while_sardem_runs_then_restored(monkeypatch, tmp_path, network_off): + monkeypatch.setattr(dem, "_egm2008_shift", lambda lon, lat: -36.0 if osr.GetPROJEnableNetwork() else 0.0) + seen = [] + monkeypatch.setattr(dem.sardem.dem, "main", lambda **kwargs: seen.append(osr.GetPROJEnableNetwork())) + dem.create_dem(tmp_path / "dem.tif", BBOX) + assert seen == [True] + assert osr.GetPROJEnableNetwork() is False From b8514dd0ee01c354be1aa3806058fc6957b9c341 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Sun, 22 Nov 2026 21:23:04 +0000 Subject: [PATCH 2/2] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- tests/test_dem.py | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/tests/test_dem.py b/tests/test_dem.py index 96ecad2..2e7915a 100644 --- a/tests/test_dem.py +++ b/tests/test_dem.py @@ -14,7 +14,9 @@ def network_off(): osr.SetPROJEnableNetwork(previous) -def test_create_dem_refuses_when_the_geoid_cannot_be_applied(monkeypatch, tmp_path, network_off): +def test_create_dem_refuses_when_the_geoid_cannot_be_applied( + monkeypatch, tmp_path, network_off +): # PROJ without a usable grid applies a no-op vertical shift monkeypatch.setattr(dem, "_egm2008_shift", lambda lon, lat: 0.0) called = [] @@ -25,10 +27,18 @@ def test_create_dem_refuses_when_the_geoid_cannot_be_applied(monkeypatch, tmp_pa assert osr.GetPROJEnableNetwork() is False -def test_network_is_enabled_while_sardem_runs_then_restored(monkeypatch, tmp_path, network_off): - monkeypatch.setattr(dem, "_egm2008_shift", lambda lon, lat: -36.0 if osr.GetPROJEnableNetwork() else 0.0) +def test_network_is_enabled_while_sardem_runs_then_restored( + monkeypatch, tmp_path, network_off +): + monkeypatch.setattr( + dem, + "_egm2008_shift", + lambda lon, lat: -36.0 if osr.GetPROJEnableNetwork() else 0.0, + ) seen = [] - monkeypatch.setattr(dem.sardem.dem, "main", lambda **kwargs: seen.append(osr.GetPROJEnableNetwork())) + monkeypatch.setattr( + dem.sardem.dem, "main", lambda **kwargs: seen.append(osr.GetPROJEnableNetwork()) + ) dem.create_dem(tmp_path / "dem.tif", BBOX) assert seen == [True] assert osr.GetPROJEnableNetwork() is False