From 89e0d81801e5b8bced018bbce579cb3b97c73471 Mon Sep 17 00:00:00 2001 From: Kyle Barron Date: Mon, 26 Oct 2026 14:03:35 -0400 Subject: [PATCH 1/5] feat: Load the vendored GeoTIFF CT method table Co-Authored-By: Claude Fable 5.1 --- src/async_geotiff/_crs_table.py | 117 ++++++++++++++++++++++++++++++++ tests/test_crs_table.py | 47 +++++++++++++ 2 files changed, 164 insertions(+) create mode 100644 src/async_geotiff/_crs_table.py diff --git a/src/async_geotiff/_crs_table.py b/src/async_geotiff/_crs_table.py new file mode 100644 index 0000000..a5ed2d3 --- /dev/null +++ b/src/async_geotiff/_crs_table.py @@ -0,0 +1,117 @@ +"""The GeoTIFF coordinate-transformation method table. + +`data/geotiff-ct-methods.json` says, for every `ProjCoordTransGeoKey` code, +which PROJ/EPSG method it means and how each parameter is read from GeoKeys. +It is shared with other GeoTIFF readers through the geotiff-test-data +repository, which documents its schema in `crs/README.md`; this module only +loads it into typed records. +""" + +from __future__ import annotations + +import json +from dataclasses import dataclass +from functools import lru_cache +from importlib.resources import files +from typing import Literal + +ParameterKind = Literal["angular", "linear", "scale", "azimuth"] + +DEFAULT_AXES: tuple[str, str] = ("east", "north") + + +@dataclass(frozen=True) +class Parameter: + """One projection parameter and the GeoKeys it is read from.""" + + name: str + """PROJ/EPSG parameter name.""" + epsg: int | None + """EPSG parameter code, or None for PROJ-only methods.""" + proj: str + """PROJ string key.""" + kind: ParameterKind + """Unit class: angular and linear values are scaled by the file's units.""" + keys: tuple[str, ...] + """GeoKey names to try in order (spec names without the `GeoKey` suffix).""" + default: float + + +@dataclass(frozen=True) +class Variant: + """One way a CT code maps to a method, chosen by its `when` rule.""" + + when: dict | None + """Rule selecting this variant; None for the default variant.""" + method_name: str | None + method_epsg: int | None + proj: str | None + """PROJ projection name.""" + axes: tuple[str, str] + """Projected axis directions.""" + parameters: tuple[Parameter, ...] + unrepresentable: str | None + """Set when PROJ has no operation for this case.""" + note: str | None + + +@dataclass(frozen=True) +class Method: + """A `ProjCoordTransGeoKey` code and its variants.""" + + code: int + ct_name: str + unsupported: str | None + """Set when GDAL cannot read this code either.""" + variants: tuple[Variant, ...] + + @property + def all_parameters(self) -> tuple[Parameter, ...]: + """Every parameter any variant reads, first occurrence by name.""" + seen: dict[str, Parameter] = {} + for variant in self.variants: + for parameter in variant.parameters: + seen.setdefault(parameter.name, parameter) + return tuple(seen.values()) + + +def _parameter(raw: dict) -> Parameter: + return Parameter( + name=raw["name"], + epsg=raw["epsg"], + proj=raw["proj"], + kind=raw["kind"], + keys=tuple(raw["keys"]), + default=float(raw["default"]), + ) + + +def _variant(raw: dict) -> Variant: + method = raw.get("method") + return Variant( + when=raw.get("when"), + method_name=method["name"] if method else None, + method_epsg=method["epsg"] if method else None, + proj=method["proj"] if method else None, + axes=tuple(raw.get("axes", DEFAULT_AXES)), # type: ignore[arg-type] + parameters=tuple(_parameter(p) for p in raw.get("parameters", [])), + unrepresentable=raw.get("unrepresentable"), + note=raw.get("note"), + ) + + +def _method(code: str, raw: dict) -> Method: + return Method( + code=int(code), + ct_name=raw["ct_name"], + unsupported=raw.get("unsupported"), + variants=tuple(_variant(v) for v in raw.get("variants", [])), + ) + + +@lru_cache(maxsize=1) +def load_table() -> dict[int, Method]: + """Load the vendored table, keyed by CT code.""" + text = files("async_geotiff.data").joinpath("geotiff-ct-methods.json").read_text() + raw = json.loads(text) + return {int(code): _method(code, method) for code, method in raw["methods"].items()} diff --git a/tests/test_crs_table.py b/tests/test_crs_table.py index 1e1bd4f..2b705a8 100644 --- a/tests/test_crs_table.py +++ b/tests/test_crs_table.py @@ -5,6 +5,8 @@ import json from pathlib import Path +from async_geotiff._crs_table import load_table + REPO_ROOT = Path(__file__).parent.parent VENDORED = REPO_ROOT / "src/async_geotiff/data/geotiff-ct-methods.json" SUBMODULE = REPO_ROOT / "fixtures/geotiff-test-data/crs/geotiff-ct-methods.json" @@ -22,3 +24,48 @@ def test_table_methods_have_proj_names(): for variant in method["variants"]: if "method" in variant: assert variant["method"]["proj"] + + +def test_load_table_has_every_ct_code(): + assert set(load_table()) == set(range(1, 29)) | {9815} + + +def test_unsupported_method(): + method = load_table()[2] + assert method.unsupported + assert method.variants == () + + +def test_mercator_variants(): + variants = load_table()[7].variants + assert len(variants) == 2 + assert variants[0].when == {"present": "ProjStdParallel1"} + assert variants[0].method_epsg == 9805 + assert variants[1].when is None + assert variants[1].method_epsg == 9804 + + +def test_polar_unrepresentable(): + variants = load_table()[15].variants + assert variants[2].unrepresentable + assert variants[2].method_name is None + + +def test_all_parameters_union(): + names = {p.name for p in load_table()[15].all_parameters} + assert {"Scale factor at natural origin", "Latitude of standard parallel"} <= names + + +def test_axes(): + assert load_table()[27].variants[0].axes == ("west", "south") + assert load_table()[1].variants[0].axes == ("east", "north") + + +def test_parameter_fields(): + lat = load_table()[1].variants[0].parameters[0] + assert lat.name == "Latitude of natural origin" + assert lat.epsg == 8801 + assert lat.proj == "lat_0" + assert lat.kind == "angular" + assert lat.keys == ("ProjNatOriginLat", "ProjFalseOriginLat", "ProjCenterLat") + assert lat.default == 0.0 From 8713826226fd378759f2b018783d85bb5832efe5 Mon Sep 17 00:00:00 2001 From: Kyle Barron Date: Mon, 26 Oct 2026 14:05:32 -0400 Subject: [PATCH 2/5] feat: Build user-defined geographic CRSs with pyproj's typed classes Co-Authored-By: Claude Fable 5.1 --- src/async_geotiff/_crs_geographic.py | 275 +++++++++++++++++++++++++++ tests/test_crs_geographic.py | 198 +++++++++++++++++++ 2 files changed, 473 insertions(+) create mode 100644 src/async_geotiff/_crs_geographic.py create mode 100644 tests/test_crs_geographic.py diff --git a/src/async_geotiff/_crs_geographic.py b/src/async_geotiff/_crs_geographic.py new file mode 100644 index 0000000..351f6bf --- /dev/null +++ b/src/async_geotiff/_crs_geographic.py @@ -0,0 +1,275 @@ +"""Build the geographic side of a user-defined GeoTIFF CRS. + +Follows libgeotiff's `GTIFGetDefn` and the GeogCS block of GDAL's +`GTIFGetOGISDefn`: units come from the unit codes or sizes, the ellipsoid +from its code or explicit axes, the datum from its code or the citation, and +the prime meridian from its code or longitude. Every function takes the +GeoKeys as a plain mapping with async-tiff's attribute names (`dict(gkd)`). + +Names matter for CRS equality in PROJ and GDAL only for the datum and the +prime meridian, where a datum named exactly `unknown` matches any datum with +the same ellipsoid and prime meridian. GDAL names them from the citation it +wrote (`Datum = ...`, `Primem = ...`), so this module does the same. +""" + +from __future__ import annotations + +import math +from dataclasses import dataclass +from functools import lru_cache +from typing import TYPE_CHECKING, Any, TypeGuard + +from pyproj.crs import GeographicCRS +from pyproj.crs.coordinate_system import Cartesian2DCS, Ellipsoidal2DCS +from pyproj.crs.datum import ( + CustomDatum, + CustomEllipsoid, + CustomPrimeMeridian, + Datum, + Ellipsoid, + PrimeMeridian, +) +from pyproj.database import get_units_map + +from pyproj._crs import CoordinateSystem # noqa: PLC2701 + +if TYPE_CHECKING: + from collections.abc import Mapping + +USER_DEFINED = 32767 +"""GeoKey value meaning "defined by other keys".""" + +DEGREES_PER_RADIAN = 180.0 / math.pi +_SPHERE_TOLERANCE = 1e-10 + +_POLAR_PRESETS: dict[tuple[str, str], str] = { + ("west", "south"): "WESTING_SOUTHING", + ("south", "south"): "NORTH_POLE_EASTING_SOUTH_NORTHING_SOUTH", + ("north", "north"): "SOUTH_POLE_EASTING_NORTH_NORTHING_NORTH", +} +_FOOT_PRESETS: dict[str, str] = { + "foot": "EASTING_NORTHING_FT", + "US survey foot": "EASTING_NORTHING_US_FT", +} + + +@dataclass(frozen=True) +class AngularUnit: + """The geographic CRS's angular unit.""" + + name: str + to_degrees: float + """Multiply a value in this unit to get degrees (libgeotiff UOMAngleInDegrees).""" + conversion_factor: float + """Radians per unit.""" + + +@dataclass(frozen=True) +class LinearUnit: + """The projected CRS's linear unit.""" + + name: str + to_metres: float + """Multiply a value in this unit to get metres (libgeotiff UOMLengthInMeters).""" + + +DEGREE = AngularUnit(name="degree", to_degrees=1.0, conversion_factor=math.pi / 180) +METRE = LinearUnit(name="metre", to_metres=1.0) + + +def _is_code(value: object) -> TypeGuard[int]: + """Whether a GeoKey holds an EPSG code rather than "user-defined" or nothing.""" + return isinstance(value, int) and value != USER_DEFINED + + +@lru_cache(maxsize=2) +def _units(category: str) -> dict[str, Any]: + """EPSG units of one category, keyed by code (pyproj keys them by name).""" + units = get_units_map(auth_name="EPSG", category=category).values() + return {unit.code: unit for unit in units} + + +def angular_unit(keys: Mapping[str, Any]) -> AngularUnit: + """`GeogAngularUnits`, or `GeogAngularUnitSize` in radians, default degree.""" + code = keys.get("geog_angular_units") + if _is_code(code): + unit = _units("angular")[str(code)] + factor = float(unit.conv_factor) + return AngularUnit(unit.name, factor * DEGREES_PER_RADIAN, factor) + size = keys.get("geog_angular_unit_size") + if size is not None: + return AngularUnit("unknown", float(size) * DEGREES_PER_RADIAN, float(size)) + return DEGREE + + +def linear_unit(keys: Mapping[str, Any]) -> LinearUnit: + """`ProjLinearUnits`, or `ProjLinearUnitSize` in metres, default metre.""" + code = keys.get("proj_linear_units") + if _is_code(code): + unit = _units("linear")[str(code)] + return LinearUnit(unit.name, float(unit.conv_factor)) + size = keys.get("proj_linear_unit_size") + if size is not None: + return LinearUnit("unknown", float(size)) + return METRE + + +def parse_citation(citation: str | None) -> dict[str, str]: + """Parse GDAL's `GCS Name = ...|Datum = ...|Primem = ...|` citation.""" + result: dict[str, str] = {} + for part in (citation or "").split("|"): + if "=" in part: + key, value = part.split("=", 1) + result[key.strip()] = value.strip() + return result + + +def ellipsoid(keys: Mapping[str, Any], citation: Mapping[str, str]) -> Ellipsoid: + """The ellipsoid from its code, or from explicit axes.""" + code = keys.get("geog_ellipsoid") + semi_major = keys.get("geog_semi_major_axis") + semi_minor = keys.get("geog_semi_minor_axis") + inv_flattening = keys.get("geog_inv_flattening") + + if _is_code(code) and semi_major is None: + return Ellipsoid.from_epsg(code) + if semi_major is None: + raise ValueError( + "A user-defined ellipsoid needs a semi-major axis (GeogSemiMajorAxisGeoKey)", + ) + + name = citation.get("Ellipsoid") + if name is None: + name = Ellipsoid.from_epsg(code).name if _is_code(code) else "unknown" + + if inv_flattening: + return CustomEllipsoid( + name=name, + semi_major_axis=semi_major, + inverse_flattening=inv_flattening, + ) + if semi_minor is not None and not math.isclose( + semi_minor, + semi_major, + rel_tol=_SPHERE_TOLERANCE, + ): + return CustomEllipsoid( + name=name, + semi_major_axis=semi_major, + semi_minor_axis=semi_minor, + ) + return CustomEllipsoid(name=name, radius=semi_major) + + +def prime_meridian( + keys: Mapping[str, Any], + citation: Mapping[str, str], + unit: AngularUnit, +) -> PrimeMeridian: + """The prime meridian from its code, or from its longitude in the file's unit.""" + code = keys.get("geog_prime_meridian") + if _is_code(code): + return PrimeMeridian.from_epsg(code) + longitude = float(keys.get("geog_prime_meridian_long") or 0.0) * unit.to_degrees + name = citation.get("Primem") + if name is None: + name = "Greenwich" if longitude == 0.0 else "unknown" + return CustomPrimeMeridian(longitude=longitude, name=name) + + +def datum( + keys: Mapping[str, Any], + citation: Mapping[str, str], + ellipsoid: Ellipsoid, + prime_meridian: PrimeMeridian, +) -> Datum: + """The datum from its code (which brings its own ellipsoid), or user-defined.""" + code = keys.get("geog_geodetic_datum") + if _is_code(code): + return Datum.from_epsg(code) + return CustomDatum( + name=citation.get("Datum", "unknown"), + ellipsoid=ellipsoid, + prime_meridian=prime_meridian, + ) + + +def ellipsoidal_cs(unit: AngularUnit) -> CoordinateSystem: + """A lon/lat coordinate system in the given angular unit.""" + if unit == DEGREE: + return Ellipsoidal2DCS() + json_unit = { + "type": "AngularUnit", + "name": unit.name, + "conversion_factor": unit.conversion_factor, + } + return CoordinateSystem.from_json_dict( + { + "type": "CoordinateSystem", + "subtype": "ellipsoidal", + "axis": [ + { + "name": "Longitude", + "abbreviation": "lon", + "direction": "east", + "unit": json_unit, + }, + { + "name": "Latitude", + "abbreviation": "lat", + "direction": "north", + "unit": json_unit, + }, + ], + }, + ) + + +def cartesian_cs(unit: LinearUnit, axes: tuple[str, str]) -> CoordinateSystem: + """A projected coordinate system in the given unit with the given axis directions.""" + if axes == ("east", "north"): + if unit == METRE: + return Cartesian2DCS() + if unit.name in _FOOT_PRESETS: + return Cartesian2DCS(axis=_FOOT_PRESETS[unit.name]) + elif unit == METRE and axes in _POLAR_PRESETS: + return Cartesian2DCS(axis=_POLAR_PRESETS[axes]) + json_unit = { + "type": "LinearUnit", + "name": unit.name, + "conversion_factor": unit.to_metres, + } + return CoordinateSystem.from_json_dict( + { + "type": "CoordinateSystem", + "subtype": "Cartesian", + "axis": [ + { + "name": "Easting", + "abbreviation": "E", + "direction": axes[0], + "unit": json_unit, + }, + { + "name": "Northing", + "abbreviation": "N", + "direction": axes[1], + "unit": json_unit, + }, + ], + }, + ) + + +def geographic_crs(keys: Mapping[str, Any]) -> tuple[GeographicCRS, AngularUnit]: + """A user-defined geographic CRS and its angular unit.""" + citation = parse_citation(keys.get("geog_citation")) + unit = angular_unit(keys) + pm = prime_meridian(keys, citation, unit) + datum_ = datum(keys, citation, ellipsoid(keys, citation), pm) + crs = GeographicCRS( + name=citation.get("GCS Name", "unknown"), + datum=datum_, + ellipsoidal_cs=ellipsoidal_cs(unit), + ) + return crs, unit diff --git a/tests/test_crs_geographic.py b/tests/test_crs_geographic.py new file mode 100644 index 0000000..d78acd3 --- /dev/null +++ b/tests/test_crs_geographic.py @@ -0,0 +1,198 @@ +"""Unit tests for the user-defined geographic CRS builder. + +Inputs are plain dicts with async-tiff's GeoKeyDirectory attribute names. +""" + +from __future__ import annotations + +import json +import math +from pathlib import Path + +import pytest +from pyproj import CRS + +from async_geotiff._crs_geographic import ( + AngularUnit, + LinearUnit, + angular_unit, + cartesian_cs, + datum, + ellipsoid, + ellipsoidal_cs, + geographic_crs, + linear_unit, + parse_citation, + prime_meridian, +) + +MANIFEST = json.loads( + ( + Path(__file__).parent.parent / "fixtures/geotiff-test-data/crs/manifest.json" + ).read_text(), +) +ROWS = {row["name"]: row for row in MANIFEST["cases"]} +GRAD = AngularUnit(name="grad", to_degrees=0.9, conversion_factor=math.pi / 200) +DEGREE = AngularUnit(name="degree", to_degrees=1.0, conversion_factor=math.pi / 180) + + +def test_angular_unit_grad(): + unit = angular_unit({"geog_angular_units": 9105}) + assert unit.name == "grad" + assert unit.to_degrees == pytest.approx(0.9) + + +def test_angular_unit_default_degree(): + assert angular_unit({}).to_degrees == 1.0 + + +def test_angular_unit_size(): + unit = angular_unit( + {"geog_angular_units": 32767, "geog_angular_unit_size": 0.015707963267949}, + ) + assert unit.name == "unknown" + assert unit.to_degrees == pytest.approx(0.9) + + +def test_linear_unit_us_ft(): + unit = linear_unit({"proj_linear_units": 9003}) + assert unit.name == "US survey foot" + assert unit.to_metres == pytest.approx(0.3048006096012192) + + +def test_linear_unit_size(): + unit = linear_unit({"proj_linear_units": 32767, "proj_linear_unit_size": 0.5}) + assert unit.to_metres == 0.5 + + +def test_linear_unit_default_metre(): + assert linear_unit({}) == LinearUnit(name="metre", to_metres=1.0) + + +def test_parse_citation(): + assert parse_citation("GCS Name = unknown|Datum = D|Primem = Paris|") == { + "GCS Name": "unknown", + "Datum": "D", + "Primem": "Paris", + } + assert parse_citation(None) == {} + + +def test_ellipsoid_from_code(): + e = ellipsoid({"geog_ellipsoid": 7030}, {}) + assert e.name == "WGS 84" + assert e.semi_major_metre == 6378137.0 + + +def test_ellipsoid_from_axes(): + e = ellipsoid( + { + "geog_ellipsoid": 32767, + "geog_semi_major_axis": 6377397.155, + "geog_inv_flattening": 299.1528128, + }, + {"Ellipsoid": "Bessel 1841"}, + ) + assert e.name == "Bessel 1841" + assert e.inverse_flattening == pytest.approx(299.1528128) + + +def test_ellipsoid_sphere(): + e = ellipsoid( + {"geog_semi_major_axis": 6371007.181, "geog_semi_minor_axis": 6371007.181}, + {}, + ) + assert e.to_json_dict()["radius"] == 6371007.181 + + +def test_ellipsoid_requires_semi_major(): + with pytest.raises(ValueError, match="semi-major"): + ellipsoid({"geog_ellipsoid": 32767}, {}) + + +def test_prime_meridian_from_code(): + pm = prime_meridian({"geog_prime_meridian": 8903}, {}, DEGREE) + assert pm.name == "Paris" + assert pm.longitude * pm.unit_conversion_factor * 180 / math.pi == pytest.approx( + 2.33722917, + ) + + +def test_prime_meridian_in_grads(): + pm = prime_meridian({"geog_prime_meridian_long": 2.0}, {"Primem": "x"}, GRAD) + assert pm.name == "x" + assert pm.longitude == pytest.approx(1.8) + + +def test_prime_meridian_default_greenwich(): + pm = prime_meridian({}, {}, DEGREE) + assert pm.name == "Greenwich" + assert pm.longitude == 0.0 + + +def test_datum_from_code_ignores_axes(): + e = ellipsoid({"geog_semi_major_axis": 1.0, "geog_inv_flattening": 300.0}, {}) + d = datum({"geog_geodetic_datum": 6267}, {}, e, prime_meridian({}, {}, DEGREE)) + assert d.name == "North American Datum 1927" + + +def test_datum_name_from_citation(): + e = ellipsoid({"geog_ellipsoid": 7030}, {}) + d = datum({}, {"Datum": "My datum"}, e, prime_meridian({}, {}, DEGREE)) + assert d.name == "My datum" + assert d.ellipsoid.name == "WGS 84" + + +def test_datum_name_unknown(): + e = ellipsoid({"geog_ellipsoid": 7030}, {}) + assert datum({}, {}, e, prime_meridian({}, {}, DEGREE)).name == "unknown" + + +def test_ellipsoidal_cs_units(): + assert ellipsoidal_cs(DEGREE).to_json_dict()["axis"][0]["unit"] == "degree" + unit = ellipsoidal_cs(GRAD).to_json_dict()["axis"][0]["unit"] + assert unit["name"] == "grad" + assert unit["conversion_factor"] == pytest.approx(math.pi / 200) + + +def test_cartesian_cs_polar(): + cs = cartesian_cs(LinearUnit(name="metre", to_metres=1.0), ("south", "south")) + assert [a["direction"] for a in cs.to_json_dict()["axis"]] == ["south", "south"] + + +def test_cartesian_cs_feet(): + cs = cartesian_cs(linear_unit({"proj_linear_units": 9003}), ("east", "north")) + assert cs.to_json_dict()["axis"][0]["unit"]["name"] == "US survey foot" + + +def test_cartesian_cs_user_defined_unit(): + cs = cartesian_cs(LinearUnit(name="unknown", to_metres=0.5), ("east", "north")) + assert cs.to_json_dict()["axis"][0]["unit"]["conversion_factor"] == 0.5 + + +@pytest.mark.parametrize("name", ["geog_grad_wkt", "longlat_grs80", "geog_sphere"]) +def test_geographic_crs_equals_gdal(name: str): + row = ROWS[name] + keys = _async_tiff_keys(row["geokeys"]) + crs, unit = geographic_crs(keys) + expected = CRS.from_json_dict(row["gdal"]["projjson"]) + assert expected.equals(crs, ignore_axis_order=True), crs.to_wkt(pretty=True) + assert unit.to_degrees == pytest.approx(0.9 if name == "geog_grad_wkt" else 1.0) + + +def _async_tiff_keys(geokeys: dict) -> dict: + """Spec key names (manifest) to async-tiff attribute names.""" + names = { + "GeographicType": "geographic_type", + "GeogCitation": "geog_citation", + "GeogGeodeticDatum": "geog_geodetic_datum", + "GeogPrimeMeridian": "geog_prime_meridian", + "GeogAngularUnits": "geog_angular_units", + "GeogAngularUnitSize": "geog_angular_unit_size", + "GeogEllipsoid": "geog_ellipsoid", + "GeogSemiMajorAxis": "geog_semi_major_axis", + "GeogSemiMinorAxis": "geog_semi_minor_axis", + "GeogInvFlattening": "geog_inv_flattening", + "GeogPrimeMeridianLong": "geog_prime_meridian_long", + } + return {names[k]: v for k, v in geokeys.items() if k in names} From 67ef07b496f6ee0111a3240e1a53a1b3b133fad9 Mon Sep 17 00:00:00 2001 From: Kyle Barron Date: Mon, 26 Oct 2026 14:10:17 -0400 Subject: [PATCH 3/5] feat: Build user-defined CRSs from the GeoTIFF CT method table The user-defined path of _crs.py no longer hand-writes PROJJSON. The geographic CRS comes from _crs_geographic (units, ellipsoid, datum and prime meridian by code or key, GDAL's citation names) and the projection from _crs_conversion, which interprets the vendored CT table: libgeotiff's key fallback order, unit scaling of angular and linear parameters, the Mercator and Polar Stereographic variant rules, pyproj's typed conversion classes where they exist and a PROJ string otherwise, and a check that every table parameter reached the conversion. Known conformance failures drop from 34 to 7: four rows need GeoKeys async-tiff does not expose yet, one is GDAL's own prime-meridian-in-grads inconsistency, and two are ESRI PE String rows where GDAL's ESRI name morphing differs from PROJ's parser. Co-Authored-By: Claude Fable 5.1 --- .gitignore | 3 + src/async_geotiff/_crs.py | 666 +++------------------------ src/async_geotiff/_crs_conversion.py | 352 ++++++++++++++ src/async_geotiff/_crs_geographic.py | 3 +- tests/test_crs_conformance.py | 61 +-- tests/test_crs_conversion.py | 182 ++++++++ 6 files changed, 605 insertions(+), 662 deletions(-) create mode 100644 src/async_geotiff/_crs_conversion.py create mode 100644 tests/test_crs_conversion.py diff --git a/.gitignore b/.gitignore index b7faf40..5217d5c 100644 --- a/.gitignore +++ b/.gitignore @@ -205,3 +205,6 @@ cython_debug/ marimo/_static/ marimo/_lsp/ __marimo__/ + +# Internal implementation plans stay local; specs are committed. +dev-docs/plans/ diff --git a/src/async_geotiff/_crs.py b/src/async_geotiff/_crs.py index e25d3cb..5ab2cc5 100644 --- a/src/async_geotiff/_crs.py +++ b/src/async_geotiff/_crs.py @@ -1,14 +1,17 @@ """Parse a pyproj CRS from a GeoKeyDirectory. -In the simple case, a GeoTIFF is defined by an EPSG code, which we can pass to -`pyproj.CRS.from_epsg`. - -In the complex case, a GeoTIFF is defined by a set of geo keys that specify all -the parameters of a user-defined CRS. In this case, we need to build a PROJJSON -dictionary representing the CRS, which we can then pass to `pyproj.CRS.from_json_dict`. - -Most of the code to construct a custom PROJJSON is generated by Claude. For any files -where CRS generation fails, we should add a new test case in `test_crs.py`. +In the simple case, a GeoTIFF names its CRS by EPSG code, which goes straight +to `pyproj.CRS.from_epsg`. + +In the general case the GeoKeys describe a user-defined CRS. The geographic +side (units, ellipsoid, datum, prime meridian) is built by `_crs_geographic` +and the projection by `_crs_conversion`, which interprets the GeoTIFF +coordinate-transformation table shared through geotiff-test-data. Both follow +libgeotiff and GDAL, and the result is tested against GDAL's own reading of +every fixture in that corpus (`tests/test_crs_conformance.py`). + +GDAL also writes an `ESRI PE String = ` citation for projections GeoTIFF +has no code for; that WKT is parsed directly. """ from __future__ import annotations @@ -16,7 +19,16 @@ from typing import TYPE_CHECKING from pyproj import CRS -from pyproj.crs import CoordinateOperation # type: ignore[import] +from pyproj.crs import ProjectedCRS + +from async_geotiff._crs_conversion import conversion_from_geo_keys +from async_geotiff._crs_geographic import ( + USER_DEFINED, + angular_unit, + cartesian_cs, + geographic_crs, + linear_unit, +) if TYPE_CHECKING: from async_tiff import GeoKeyDirectory @@ -27,7 +39,7 @@ MODEL_TYPE_GEOGRAPHIC = 2 """GeoTIFF model type constant for geographic coordinate systems.""" -USER_DEFINED_CRS = 32767 +USER_DEFINED_CRS = USER_DEFINED """Sentinel value for user-defined CRS.""" # The two "public" functions of this module @@ -42,18 +54,10 @@ def crs_from_geo_keys(gkd: GeoKeyDirectory) -> CRS: model_type = gkd.model_type if model_type == MODEL_TYPE_PROJECTED: - crs = _projected_projection(gkd) - if isinstance(crs, int): - return CRS.from_epsg(crs) - - return CRS.from_json_dict(crs) + return _projected_crs(gkd) if model_type == MODEL_TYPE_GEOGRAPHIC: - crs = _geographic_projection(gkd) - if isinstance(crs, int): - return CRS.from_epsg(crs) - - return CRS.from_json_dict(crs) + return _geographic_crs(gkd) if model_type == USER_DEFINED_CRS: wkt = _esri_pe_string(gkd) @@ -66,34 +70,11 @@ def crs_from_geo_keys(gkd: GeoKeyDirectory) -> CRS: def projjson_from_geo_keys(gkd: GeoKeyDirectory) -> dict: """Build a PROJJSON dict from a GeoKeyDirectory. - For EPSG-coded CRSes, resolves via pyproj and returns the canonical - PROJJSON. - - For user-defined CRSes, constructs the PROJJSON from individual - geo key parameters. + For EPSG-coded CRSes this is the canonical PROJJSON of that code; for + user-defined CRSes it is PROJ's own serialization of the CRS built from + the GeoKeys. """ - model_type = gkd.model_type - - if model_type == MODEL_TYPE_PROJECTED: - crs = _projected_projection(gkd) - if isinstance(crs, int): - return CRS.from_epsg(crs).to_json_dict() - - return crs - - if model_type == MODEL_TYPE_GEOGRAPHIC: - crs = _geographic_projection(gkd) - if isinstance(crs, int): - return CRS.from_epsg(crs).to_json_dict() - - return crs - - if model_type == USER_DEFINED_CRS: - wkt = _esri_pe_string(gkd) - if wkt is not None: - return CRS.from_wkt(wkt).to_json_dict() - - raise ValueError(f"Unsupported GeoTIFF model type: {model_type}") + return crs_from_geo_keys(gkd).to_json_dict() _ESRI_PE_STRING_PREFIX = "ESRI PE String =" @@ -113,570 +94,37 @@ def _esri_pe_string(gkd: GeoKeyDirectory) -> str | None: return citation.split(_ESRI_PE_STRING_PREFIX, 1)[1].strip() or None -def _geographic_projection(gkd: GeoKeyDirectory) -> int | dict: - """Infer the geographic CRS from geo keys. - - If an EPSG code is present, returns that integer. Otherwise, constructs - a user-defined geographic CRS PROJJSON dict. - """ - epsg = gkd.geographic_type - if epsg is not None and epsg != USER_DEFINED_CRS: - return epsg - - return _build_user_defined_geographic_projjson(gkd) - - -def _projected_projection(gkd: GeoKeyDirectory) -> int | dict: - """Infer the projected CRS from geo keys. +def _geographic_crs(gkd: GeoKeyDirectory) -> CRS: + """The geographic CRS, by EPSG code or from the Geog* keys.""" + code = gkd.geographic_type + if code is not None and code != USER_DEFINED_CRS: + return CRS.from_epsg(code) + crs, _ = geographic_crs(dict(gkd)) + return crs - If an EPSG code is present, returns that integer. Otherwise, constructs - a user-defined projected CRS PROJJSON dict. - """ - epsg = gkd.projected_type - if epsg is not None and epsg != USER_DEFINED_CRS: - return epsg - - return _build_user_defined_projected_projjson(gkd) - - -def _parse_geog_citation(citation: str) -> dict[str, str]: - """Parse a GDAL-style geog_citation string into a dict of key/value pairs. - - Example input: - "GCS Name = My CRS|Datum = My Datum|Primem = Greenwich|" - """ - result: dict[str, str] = {} - for part in citation.split("|"): - stripped = part.strip() - if "=" in stripped: - k, v = stripped.split("=", 1) - result[k.strip()] = v.strip() - return result +def _projected_crs(gkd: GeoKeyDirectory) -> CRS: + """The projected CRS, by EPSG code or from the Geog* and Proj* keys.""" + code = gkd.projected_type + if code is not None and code != USER_DEFINED_CRS: + return CRS.from_epsg(code) -def _build_user_defined_geographic_projjson(gkd: GeoKeyDirectory) -> dict: - """Build a user-defined geographic CRS PROJJSON dict. - - Constructs PROJJSON from the ellipsoid, datum, prime meridian, and angular - unit parameters stored in the GeoKeyDirectory. - """ - # Build ellipsoid parameters - ellipsoid = _build_ellipsoid_params(gkd) - - # Build prime meridian - pm_name = "Greenwich" - pm_longitude = 0.0 - if ( - gkd.geog_prime_meridian is not None - and gkd.geog_prime_meridian != USER_DEFINED_CRS - ): - # Known prime meridian by EPSG code - pm_name = f"EPSG:{gkd.geog_prime_meridian}" - elif gkd.geog_prime_meridian_long is not None: - pm_longitude = gkd.geog_prime_meridian_long - pm_name = "User-defined" - - # Try to extract structured names from GDAL-style geog_citation - citation_parts = ( - _parse_geog_citation(gkd.geog_citation) if gkd.geog_citation else {} - ) - gcs_name = citation_parts.get("GCS Name") or gkd.geog_citation or "User-defined" - datum_name = citation_parts.get("Datum") or gkd.geog_citation or "User-defined" - if citation_parts.get("Primem"): - pm_name = citation_parts["Primem"] - - # Build datum - datum_json: dict - if ( - gkd.geog_geodetic_datum is not None - and gkd.geog_geodetic_datum != USER_DEFINED_CRS - ): - datum_json = { - "type": "GeodeticReferenceFrame", - "name": f"Unknown datum based upon EPSG {gkd.geog_geodetic_datum} ellipsoid", # noqa: E501 - } - else: - datum_json = { - "type": "GeodeticReferenceFrame", - "name": datum_name, - "ellipsoid": ellipsoid, - "prime_meridian": { - "name": pm_name, - "longitude": pm_longitude, - }, - } - - return { - "type": "GeographicCRS", - "$schema": "https://proj.org/schemas/v0.7/projjson.schema.json", - "name": gcs_name, - "datum": datum_json, - "coordinate_system": _geographic_cs(gkd), - } - - -def _build_user_defined_projected_projjson(gkd: GeoKeyDirectory) -> dict: - """Build a user-defined projected CRS PROJJSON dict. - - Constructs PROJJSON from the geographic base CRS and projection parameters - stored in the GeoKeyDirectory. - """ - # Build the base geographic CRS as PROJJSON - base_crs = _geographic_projection(gkd) - if isinstance(base_crs, int): - base_crs_json = CRS.from_epsg(base_crs).to_json_dict() - else: - base_crs_json = base_crs - - # Build the coordinate operation (projection) - conversion = _build_conversion(gkd) - - # Build the coordinate system for the projected CRS - cs = _projected_cs(gkd) - - return { - "type": "ProjectedCRS", - "$schema": "https://proj.org/schemas/v0.7/projjson.schema.json", - "name": gkd.proj_citation or gkd.citation or "User-defined", - "base_crs": base_crs_json, - "conversion": conversion, - "coordinate_system": cs, - } - - -def _build_ellipsoid_params(gkd: GeoKeyDirectory) -> dict: - """Build ellipsoid JSON parameters from geo keys.""" - if gkd.geog_ellipsoid is not None and gkd.geog_ellipsoid != USER_DEFINED_CRS: - # Known ellipsoid by EPSG code — use parameters from geo keys if present, - # and include the EPSG id so pyproj resolves the canonical name. - ellipsoid: dict = { - "name": f"EPSG ellipsoid {gkd.geog_ellipsoid}", - "id": {"authority": "EPSG", "code": gkd.geog_ellipsoid}, - } - - if gkd.geog_semi_major_axis is not None: - ellipsoid["semi_major_axis"] = gkd.geog_semi_major_axis - if gkd.geog_inv_flattening is not None: - ellipsoid["inverse_flattening"] = gkd.geog_inv_flattening - elif gkd.geog_semi_minor_axis is not None: - ellipsoid["semi_minor_axis"] = gkd.geog_semi_minor_axis - - return ellipsoid - - # Fully user-defined ellipsoid - semi_major = gkd.geog_semi_major_axis - if semi_major is None: - raise ValueError("User-defined ellipsoid requires geog_semi_major_axis") - - user_ellipsoid: dict = { - "name": "User-defined", - "semi_major_axis": semi_major, - } - - if gkd.geog_inv_flattening is not None: - user_ellipsoid["inverse_flattening"] = gkd.geog_inv_flattening - elif gkd.geog_semi_minor_axis is not None: - user_ellipsoid["semi_minor_axis"] = gkd.geog_semi_minor_axis - else: - raise ValueError( - "User-defined ellipsoid requires geog_inv_flattening or geog_semi_minor_axis", # noqa: E501 - ) - - return user_ellipsoid - - -# GeoTIFF coordinate transformation type codes (GeoKey 3075) -# Ref: http://geotiff.maptools.org/spec/geotiff6.html#6.3.3.3 -CT_TRANSVERSE_MERCATOR = 1 -CT_TRANSVERSE_MERCATOR_SOUTH = 2 -CT_OBLIQUE_MERCATOR = 3 -CT_OBLIQUE_MERCATOR_LABORDE = 4 -CT_OBLIQUE_MERCATOR_ROSENMUND = 5 -CT_OBLIQUE_MERCATOR_SPHERICAL = 6 -CT_MERCATOR = 7 -CT_LAMBERT_CONFORMAL_CONIC_2SP = 8 -CT_LAMBERT_CONFORMAL_CONIC_1SP = 9 -CT_LAMBERT_AZIMUTHAL_EQUAL_AREA = 10 -CT_ALBERS_EQUAL_AREA = 11 -CT_AZIMUTHAL_EQUIDISTANT = 12 -CT_STEREOGRAPHIC = 14 -CT_POLAR_STEREOGRAPHIC = 15 -CT_OBLIQUE_STEREOGRAPHIC = 16 -CT_EQUIRECTANGULAR = 17 -CT_CASSINI_SOLDNER = 18 -CT_ORTHOGRAPHIC = 21 -CT_POLYCONIC = 22 -CT_SINUSOIDAL = 24 -CT_NEW_ZEALAND_MAP_GRID = 26 -CT_TRANSVERSE_MERCATOR_SOUTH_ORIENTED = 27 - - -def _build_conversion(gkd: GeoKeyDirectory) -> dict: # noqa: C901, PLR0912, PLR0915 - """Build a PROJ JSON conversion (coordinate operation) from geo keys.""" - ct = gkd.proj_coord_trans - if ct is None: - # Fall back to the named projection code (GeoKey 3074) if available - if gkd.projection is not None and gkd.projection != USER_DEFINED_CRS: - conv = CoordinateOperation.from_epsg(gkd.projection).to_json_dict() - conv.pop("$schema", None) - return conv - raise ValueError("User-defined projected CRS requires proj_coord_trans") - - # Helper to build a projection parameter with unit - def _angular(name: str, value: float | None, default: float = 0.0) -> dict: - return { - "name": name, - "value": value if value is not None else default, - "unit": "degree", - } - - def _linear(name: str, value: float | None, default: float = 0.0) -> dict: - return { - "name": name, - "value": value if value is not None else default, - "unit": "metre", - } - - def _scale(name: str, value: float | None, default: float = 1.0) -> dict: - return { - "name": name, - "value": value if value is not None else default, - "unit": "unity", - } - - name = "User-defined" - method: dict - parameters: list[dict] - - if ct == CT_TRANSVERSE_MERCATOR: - name = "Transverse Mercator" - method = {"name": "Transverse Mercator"} - parameters = [ - _angular("Latitude of natural origin", gkd.proj_nat_origin_lat), - _angular("Longitude of natural origin", gkd.proj_nat_origin_long), - _scale("Scale factor at natural origin", gkd.proj_scale_at_nat_origin), - _linear("False easting", gkd.proj_false_easting), - _linear("False northing", gkd.proj_false_northing), - ] - - elif ct == CT_TRANSVERSE_MERCATOR_SOUTH: - name = "Transverse Mercator (South Orientated)" - method = {"name": "Transverse Mercator (South Orientated)"} - parameters = [ - _angular("Latitude of natural origin", gkd.proj_nat_origin_lat), - _angular("Longitude of natural origin", gkd.proj_nat_origin_long), - _scale("Scale factor at natural origin", gkd.proj_scale_at_nat_origin), - _linear("False easting", gkd.proj_false_easting), - _linear("False northing", gkd.proj_false_northing), - ] - - elif ct in ( - CT_OBLIQUE_MERCATOR, - CT_OBLIQUE_MERCATOR_LABORDE, - CT_OBLIQUE_MERCATOR_ROSENMUND, - CT_OBLIQUE_MERCATOR_SPHERICAL, - ): - name = "Hotine Oblique Mercator (variant B)" - method = {"name": "Hotine Oblique Mercator (variant B)"} - parameters = [ - _angular("Latitude of projection centre", gkd.proj_center_lat), - _angular("Longitude of projection centre", gkd.proj_center_long), - _angular("Azimuth of initial line", gkd.proj_azimuth_angle), - _angular("Angle from Rectified to Skew Grid", gkd.proj_azimuth_angle), - _scale("Scale factor on initial line", gkd.proj_scale_at_center), - _linear("Easting at projection centre", gkd.proj_center_easting), - _linear("Northing at projection centre", gkd.proj_center_northing), - ] - - elif ct == CT_MERCATOR: - name = "Mercator (variant A)" - method = {"name": "Mercator (variant A)"} - parameters = [ - _angular("Latitude of natural origin", gkd.proj_nat_origin_lat), - _angular("Longitude of natural origin", gkd.proj_nat_origin_long), - _scale("Scale factor at natural origin", gkd.proj_scale_at_nat_origin), - _linear("False easting", gkd.proj_false_easting), - _linear("False northing", gkd.proj_false_northing), - ] - - elif ct == CT_LAMBERT_CONFORMAL_CONIC_2SP: - name = "Lambert Conic Conformal (2SP)" - method = {"name": "Lambert Conic Conformal (2SP)"} - parameters = [ - _angular( - "Latitude of false origin", - gkd.proj_false_origin_lat or gkd.proj_nat_origin_lat, - ), - _angular( - "Longitude of false origin", - gkd.proj_false_origin_long or gkd.proj_nat_origin_long, - ), - _angular("Latitude of 1st standard parallel", gkd.proj_std_parallel1), - _angular("Latitude of 2nd standard parallel", gkd.proj_std_parallel2), - _linear( - "Easting at false origin", - gkd.proj_false_origin_easting or gkd.proj_false_easting, - ), - _linear( - "Northing at false origin", - gkd.proj_false_origin_northing or gkd.proj_false_northing, - ), - ] - - elif ct == CT_LAMBERT_CONFORMAL_CONIC_1SP: - name = "Lambert Conic Conformal (1SP)" - method = {"name": "Lambert Conic Conformal (1SP)"} - parameters = [ - _angular("Latitude of natural origin", gkd.proj_nat_origin_lat), - _angular("Longitude of natural origin", gkd.proj_nat_origin_long), - _scale("Scale factor at natural origin", gkd.proj_scale_at_nat_origin), - _linear("False easting", gkd.proj_false_easting), - _linear("False northing", gkd.proj_false_northing), - ] - - elif ct == CT_LAMBERT_AZIMUTHAL_EQUAL_AREA: - name = "Lambert Azimuthal Equal Area" - method = {"name": "Lambert Azimuthal Equal Area"} - parameters = [ - _angular("Latitude of natural origin", gkd.proj_center_lat), - _angular("Longitude of natural origin", gkd.proj_center_long), - _linear("False easting", gkd.proj_false_easting), - _linear("False northing", gkd.proj_false_northing), - ] - - elif ct == CT_ALBERS_EQUAL_AREA: - name = "Albers Equal Area" - method = {"name": "Albers Equal Area"} - parameters = [ - _angular( - "Latitude of false origin", - gkd.proj_false_origin_lat or gkd.proj_nat_origin_lat, - ), - _angular( - "Longitude of false origin", - gkd.proj_false_origin_long or gkd.proj_nat_origin_long, - ), - _angular("Latitude of 1st standard parallel", gkd.proj_std_parallel1), - _angular("Latitude of 2nd standard parallel", gkd.proj_std_parallel2), - _linear( - "Easting at false origin", - gkd.proj_false_origin_easting or gkd.proj_false_easting, - ), - _linear( - "Northing at false origin", - gkd.proj_false_origin_northing or gkd.proj_false_northing, - ), - ] - - elif ct == CT_AZIMUTHAL_EQUIDISTANT: - name = "Modified Azimuthal Equidistant" - method = {"name": "Modified Azimuthal Equidistant"} - parameters = [ - _angular("Latitude of natural origin", gkd.proj_center_lat), - _angular("Longitude of natural origin", gkd.proj_center_long), - _linear("False easting", gkd.proj_false_easting), - _linear("False northing", gkd.proj_false_northing), - ] - - elif ct == CT_STEREOGRAPHIC: - name = "Stereographic" - method = {"name": "Stereographic"} - parameters = [ - _angular("Latitude of natural origin", gkd.proj_center_lat), - _angular("Longitude of natural origin", gkd.proj_center_long), - _scale("Scale factor at natural origin", gkd.proj_scale_at_center), - _linear("False easting", gkd.proj_false_easting), - _linear("False northing", gkd.proj_false_northing), - ] - - elif ct == CT_POLAR_STEREOGRAPHIC: - name = "Polar Stereographic (variant B)" - method = {"name": "Polar Stereographic (variant B)"} - parameters = [ - _angular( - "Latitude of standard parallel", - gkd.proj_nat_origin_lat or gkd.proj_std_parallel1, - ), - _angular( - "Longitude of origin", - gkd.proj_straight_vert_pole_long or gkd.proj_nat_origin_long, - ), - _linear("False easting", gkd.proj_false_easting), - _linear("False northing", gkd.proj_false_northing), - ] - - elif ct == CT_OBLIQUE_STEREOGRAPHIC: - name = "Oblique Stereographic" - method = {"name": "Oblique Stereographic"} - parameters = [ - _angular("Latitude of natural origin", gkd.proj_center_lat), - _angular("Longitude of natural origin", gkd.proj_center_long), - _scale("Scale factor at natural origin", gkd.proj_scale_at_center), - _linear("False easting", gkd.proj_false_easting), - _linear("False northing", gkd.proj_false_northing), - ] - - elif ct == CT_EQUIRECTANGULAR: - name = "Equidistant Cylindrical" - method = {"name": "Equidistant Cylindrical"} - parameters = [ - _angular( - "Latitude of 1st standard parallel", - gkd.proj_std_parallel1 or gkd.proj_center_lat, - ), - _angular("Longitude of natural origin", gkd.proj_center_long), - _linear("False easting", gkd.proj_false_easting), - _linear("False northing", gkd.proj_false_northing), - ] - - elif ct == CT_CASSINI_SOLDNER: - name = "Cassini-Soldner" - method = {"name": "Cassini-Soldner"} - parameters = [ - _angular("Latitude of natural origin", gkd.proj_nat_origin_lat), - _angular("Longitude of natural origin", gkd.proj_nat_origin_long), - _linear("False easting", gkd.proj_false_easting), - _linear("False northing", gkd.proj_false_northing), - ] - - elif ct == CT_POLYCONIC: - name = "American Polyconic" - method = {"name": "American Polyconic"} - parameters = [ - _angular("Latitude of natural origin", gkd.proj_nat_origin_lat), - _angular("Longitude of natural origin", gkd.proj_nat_origin_long), - _linear("False easting", gkd.proj_false_easting), - _linear("False northing", gkd.proj_false_northing), - ] - - elif ct == CT_SINUSOIDAL: - name = "Sinusoidal" - method = {"name": "Sinusoidal"} - parameters = [ - _angular("Longitude of natural origin", gkd.proj_center_long), - _linear("False easting", gkd.proj_false_easting), - _linear("False northing", gkd.proj_false_northing), - ] - - elif ct == CT_ORTHOGRAPHIC: - name = "Orthographic" - method = {"name": "Orthographic"} - parameters = [ - _angular("Latitude of natural origin", gkd.proj_center_lat), - _angular("Longitude of natural origin", gkd.proj_center_long), - _linear("False easting", gkd.proj_false_easting), - _linear("False northing", gkd.proj_false_northing), - ] - - elif ct == CT_NEW_ZEALAND_MAP_GRID: - name = "New Zealand Map Grid" - method = {"name": "New Zealand Map Grid"} - parameters = [ - _angular("Latitude of natural origin", gkd.proj_nat_origin_lat), - _angular("Longitude of natural origin", gkd.proj_nat_origin_long), - _linear("False easting", gkd.proj_false_easting), - _linear("False northing", gkd.proj_false_northing), - ] - - elif ct == CT_TRANSVERSE_MERCATOR_SOUTH_ORIENTED: - name = "Transverse Mercator (South Orientated)" - method = {"name": "Transverse Mercator (South Orientated)"} - parameters = [ - _angular("Latitude of natural origin", gkd.proj_nat_origin_lat), - _angular("Longitude of natural origin", gkd.proj_nat_origin_long), - _scale("Scale factor at natural origin", gkd.proj_scale_at_nat_origin), - _linear("False easting", gkd.proj_false_easting), - _linear("False northing", gkd.proj_false_northing), - ] - + keys = dict(gkd) + geographic_type = gkd.geographic_type + if geographic_type is not None and geographic_type != USER_DEFINED_CRS: + base: CRS = CRS.from_epsg(geographic_type) + unit = angular_unit(keys) else: - raise ValueError(f"Unsupported coordinate transformation type: {ct}") - - return { - "name": name, - "method": method, - "parameters": parameters, - } - - -ANGULAR_UNIT_RADIAN = 9101 -"""EPSG code for radian angular unit.""" - -ANGULAR_UNIT_DEGREE = 9102 -"""EPSG code for degree angular unit.""" - -ANGULAR_UNIT_GRAD = 9105 -"""EPSG code for grad angular unit.""" - -ANGULAR_UNIT: dict[int | None, str] = { - ANGULAR_UNIT_DEGREE: "degree", - ANGULAR_UNIT_RADIAN: "radian", - ANGULAR_UNIT_GRAD: "grad", -} - - -def _geographic_cs(gkd: GeoKeyDirectory) -> dict: - """Build a geographic coordinate system JSON dict from geo keys.""" - angular_unit = ANGULAR_UNIT.get( - gkd.geog_angular_units, - "degree", + base, unit = geographic_crs(keys) + linear = linear_unit(keys) + conversion, axes = conversion_from_geo_keys( + keys, + to_degrees=unit.to_degrees, + to_metres=linear.to_metres, ) - - return { - "subtype": "ellipsoidal", - "axis": [ - { - "name": "Latitude", - "abbreviation": "lat", - "direction": "north", - "unit": angular_unit, - }, - { - "name": "Longitude", - "abbreviation": "lon", - "direction": "east", - "unit": angular_unit, - }, - ], - } - - -LINEAR_UNIT_METRE = 9001 -LINEAR_UNIT_FOOT = 9002 -LINEAR_UNIT_US_SURVEY_FOOT = 9003 - -LINEAR_UNIT: dict[int | None, str | dict[str, str | float]] = { - LINEAR_UNIT_METRE: "metre", - LINEAR_UNIT_FOOT: "foot", - LINEAR_UNIT_US_SURVEY_FOOT: { - "type": "LinearUnit", - "name": "US survey foot", - "conversion_factor": 0.30480060960121924, - }, -} - - -def _projected_cs(gkd: GeoKeyDirectory) -> dict: - """Build a projected coordinate system JSON dict from geo keys.""" - linear_unit: str | dict[str, str | float] = LINEAR_UNIT.get( - gkd.proj_linear_units, - "metre", + return ProjectedCRS( + name=gkd.proj_citation or gkd.citation or "unknown", + conversion=conversion, + geodetic_crs=base, + cartesian_cs=cartesian_cs(linear, axes), ) - - return { - "subtype": "Cartesian", - "axis": [ - { - "name": "Easting", - "abbreviation": "E", - "direction": "east", - "unit": linear_unit, - }, - { - "name": "Northing", - "abbreviation": "N", - "direction": "north", - "unit": linear_unit, - }, - ], - } diff --git a/src/async_geotiff/_crs_conversion.py b/src/async_geotiff/_crs_conversion.py new file mode 100644 index 0000000..340992f --- /dev/null +++ b/src/async_geotiff/_crs_conversion.py @@ -0,0 +1,352 @@ +"""Build a projection (conversion) from GeoKeys by interpreting the CT table. + +For a `ProjCoordTransGeoKey` code the table (`_crs_table`) says which PROJ +method applies and which GeoKeys hold each parameter, in libgeotiff's fallback +order. This module resolves the parameters, scales angular and linear values +to degrees and metres with the file's units, picks the method variant, and +builds the conversion with one of pyproj's typed classes, or, for methods +without one, from a PROJ string. Either way the result is checked against the +table so a silently dropped parameter is an error rather than a zero. +""" + +from __future__ import annotations + +import math +from typing import TYPE_CHECKING, Any + +from pyproj import CRS +from pyproj.crs.coordinate_operation import ( + AlbersEqualAreaConversion, + CoordinateOperation, + EquidistantCylindricalConversion, + HotineObliqueMercatorBConversion, + LambertAzimuthalEqualAreaConversion, + LambertConformalConic1SPConversion, + LambertConformalConic2SPConversion, + LambertCylindricalEqualAreaConversion, + MercatorAConversion, + MercatorBConversion, + OrthographicConversion, + PolarStereographicAConversion, + PolarStereographicBConversion, + SinusoidalConversion, + StereographicConversion, + TransverseMercatorConversion, +) + +from async_geotiff._crs_geographic import DEGREES_PER_RADIAN, USER_DEFINED +from async_geotiff._crs_table import DEFAULT_AXES, Method, Variant, load_table + +if TYPE_CHECKING: + from collections.abc import Mapping + +KEY_ACCESSORS: dict[str, str] = { + "ProjStdParallel1": "proj_std_parallel1", + "ProjStdParallel2": "proj_std_parallel2", + "ProjNatOriginLong": "proj_nat_origin_long", + "ProjNatOriginLat": "proj_nat_origin_lat", + "ProjFalseEasting": "proj_false_easting", + "ProjFalseNorthing": "proj_false_northing", + "ProjFalseOriginLong": "proj_false_origin_long", + "ProjFalseOriginLat": "proj_false_origin_lat", + "ProjFalseOriginEasting": "proj_false_origin_easting", + "ProjFalseOriginNorthing": "proj_false_origin_northing", + "ProjCenterLong": "proj_center_long", + "ProjCenterLat": "proj_center_lat", + "ProjCenterEasting": "proj_center_easting", + "ProjCenterNorthing": "proj_center_northing", + "ProjScaleAtNatOrigin": "proj_scale_at_nat_origin", + "ProjScaleAtCenter": "proj_scale_at_center", + "ProjAzimuthAngle": "proj_azimuth_angle", + "ProjStraightVertPoleLong": "proj_straight_vert_pole_long", +} +"""Table key names to async-tiff `GeoKeyDirectory` attributes. + +`ProjRectifiedGridAngle` is deliberately absent: async-tiff 0.7 does not read +key 3096, and defaulting it silently would build a wrong Hotine Oblique +Mercator. +""" + +_NATURAL_ORIGIN = { + 8801: "latitude_natural_origin", + 8802: "longitude_natural_origin", + 8805: "scale_factor_natural_origin", + 8806: "false_easting", + 8807: "false_northing", +} +_FALSE_ORIGIN_2SP = { + 8821: "latitude_false_origin", + 8822: "longitude_false_origin", + 8823: "latitude_first_parallel", + 8824: "latitude_second_parallel", + 8826: "easting_false_origin", + 8827: "northing_false_origin", +} +_ORIGIN_NO_SCALE = { + code: keyword + for code, keyword in _NATURAL_ORIGIN.items() + if keyword != "scale_factor_natural_origin" +} + +TYPED: dict[int | str, tuple[type[CoordinateOperation], dict[int, str]]] = { + 9807: (TransverseMercatorConversion, _NATURAL_ORIGIN), + 9804: (MercatorAConversion, _NATURAL_ORIGIN), + 9805: ( + MercatorBConversion, + { + 8823: "latitude_first_parallel", + 8802: "longitude_natural_origin", + 8806: "false_easting", + 8807: "false_northing", + }, + ), + 9801: (LambertConformalConic1SPConversion, _NATURAL_ORIGIN), + 9802: (LambertConformalConic2SPConversion, _FALSE_ORIGIN_2SP), + 9822: (AlbersEqualAreaConversion, _FALSE_ORIGIN_2SP), + 9820: (LambertAzimuthalEqualAreaConversion, _ORIGIN_NO_SCALE), + 9810: (PolarStereographicAConversion, _NATURAL_ORIGIN), + 9829: ( + PolarStereographicBConversion, + { + 8832: "latitude_standard_parallel", + 8833: "longitude_origin", + 8806: "false_easting", + 8807: "false_northing", + }, + ), + "Stereographic": (StereographicConversion, _NATURAL_ORIGIN), + 9840: (OrthographicConversion, _ORIGIN_NO_SCALE), + 1028: ( + EquidistantCylindricalConversion, + {8823: "latitude_first_parallel", **_ORIGIN_NO_SCALE}, + ), + "Sinusoidal": ( + SinusoidalConversion, + { + 8802: "longitude_natural_origin", + 8806: "false_easting", + 8807: "false_northing", + }, + ), + 9835: ( + LambertCylindricalEqualAreaConversion, + { + 8823: "latitude_first_parallel", + 8802: "longitude_natural_origin", + 8806: "false_easting", + 8807: "false_northing", + }, + ), + 9815: ( + HotineObliqueMercatorBConversion, + { + 8811: "latitude_projection_centre", + 8812: "longitude_projection_centre", + 8813: "azimuth_projection_centre", + 8814: "angle_from_rectified_to_skew_grid", + 8815: "scale_factor_projection_centre", + 8816: "easting_projection_centre", + 8817: "northing_projection_centre", + }, + ), +} +"""Methods with a typed pyproj class, by EPSG code (or PROJ name when there is none). + +A typo in a keyword here is a `TypeError`; units are implied; EPSG ids attached. +Every other method goes through a PROJ string (PROJ maps it to the EPSG method). +""" + +PROJ_STRING_EXTRAS: dict[int | None, str] = { + 9812: "+no_uoff", # Hotine Oblique Mercator (variant A) + 9808: "+axis=wsu", # Transverse Mercator (South Orientated) +} +PROJ_KEY_OVERRIDES: dict[int | None, dict[int | None, str]] = { + # Laborde spells its centre longitude +lon_0 and its azimuth +azi, unlike + # the Hotine Oblique Mercator keys (+lonc, +alpha) the table shares with it. + 9813: {8812: "lon_0", 8813: "azi"}, +} +_PLACEHOLDER_ELLIPSOID = "+ellps=WGS84" +_POLAR_STEREOGRAPHIC = 15 +_TOLERANCE = 1e-9 + + +def resolve_parameters( + method: Method, + keys: Mapping[str, Any], + *, + to_degrees: float, + to_metres: float, +) -> dict[str, float]: + """Read every parameter any variant of `method` uses, in degrees and metres. + + The first key present in a parameter's list wins (a stored `0.0` is + present); a parameter with no key present takes its default. + """ + values: dict[str, float] = {} + for parameter in method.all_parameters: + value = parameter.default + for key in parameter.keys: + attribute = KEY_ACCESSORS.get(key) + if attribute is None: + raise ValueError( + f"GeoKey {key} is not readable by async-tiff, so " + f"{method.ct_name} ({method.code}) cannot be built", + ) + raw = keys.get(attribute) + if raw is not None: + value = float(raw) + break + if parameter.kind == "angular": + value *= to_degrees + elif parameter.kind == "linear": + value *= to_metres + values[parameter.name] = value + return values + + +def _rule_matches( + rule: dict, + values: Mapping[str, float], + keys: Mapping[str, Any], +) -> bool: + ((kind, body),) = rule.items() + if kind == "any": + return any(_rule_matches(r, values, keys) for r in body) + if kind == "all": + return all(_rule_matches(r, values, keys) for r in body) + if kind == "present": + return keys.get(KEY_ACCESSORS[body]) is not None + value = values[body["param"]] + if kind == "abs_value": + value = abs(value) + elif kind != "value": + raise ValueError(f"Unknown rule in the CT table: {kind}") + return math.isclose(value, body["equals"], abs_tol=_TOLERANCE) + + +def select_variant( + method: Method, + values: Mapping[str, float], + keys: Mapping[str, Any], +) -> Variant: + """Pick the first variant whose rule matches; the last variant has no rule.""" + for variant in method.variants: + if variant.when is None or _rule_matches(variant.when, values, keys): + if variant.unrepresentable: + raise ValueError( + f"{method.ct_name} ({method.code}) with these parameters: " + f"{variant.unrepresentable}", + ) + return variant + raise ValueError(f"No variant of {method.ct_name} ({method.code}) matched") + + +def _proj_string(variant: Variant, values: Mapping[str, float]) -> str: + overrides = PROJ_KEY_OVERRIDES.get(variant.method_epsg, {}) + parts = [f"+proj={variant.proj}"] + for parameter in variant.parameters: + key = overrides.get(parameter.epsg, parameter.proj) + parts.append(f"+{key}={values[parameter.name]!r}") + extra = PROJ_STRING_EXTRAS.get(variant.method_epsg) + if extra: + parts.append(extra) + parts.append(_PLACEHOLDER_ELLIPSOID) + return " ".join(parts) + + +def build_conversion( + variant: Variant, + values: Mapping[str, float], +) -> CoordinateOperation: + """Build the conversion for a variant from resolved parameter values.""" + typed = TYPED.get(variant.method_epsg or variant.method_name or "") + if typed is None: + # The ellipsoid is a placeholder: the conversion is re-attached to the + # real geographic CRS by the caller and carries no ellipsoid of its own. + conversion = CRS.from_proj4(_proj_string(variant, values)).coordinate_operation + if conversion is None: + raise ValueError(f"PROJ built no conversion for {variant.method_name}") + return conversion + cls, keywords = typed + kwargs = {} + for parameter in variant.parameters: + if parameter.epsg not in keywords: + raise ValueError( + f"{variant.method_name}: no keyword for parameter {parameter.name}", + ) + kwargs[keywords[parameter.epsg]] = values[parameter.name] + return cls(**kwargs) + + +def validate_conversion( + conversion: CoordinateOperation, + variant: Variant, + values: Mapping[str, float], +) -> None: + """Check every table parameter made it into the conversion with its value.""" + by_code = {p.code: p for p in conversion.params if p.code} + by_name = {p.name: p for p in conversion.params} + for parameter in variant.parameters: + found = ( + by_code.get(str(parameter.epsg)) + if parameter.epsg + else by_name.get(parameter.name) + ) + if found is None: + raise ValueError( + f"{variant.method_name}: parameter {parameter.name} was dropped", + ) + actual = float(found.value) + if parameter.kind in ("angular", "azimuth"): + actual *= found.unit_conversion_factor * DEGREES_PER_RADIAN + elif parameter.kind == "linear": + actual *= found.unit_conversion_factor + expected = values[parameter.name] + if not math.isclose(actual, expected, rel_tol=_TOLERANCE, abs_tol=_TOLERANCE): + raise ValueError( + f"{variant.method_name}: parameter {parameter.name} is {actual}, " + f"expected {expected}", + ) + + +def conversion_from_geo_keys( + keys: Mapping[str, Any], + *, + to_degrees: float, + to_metres: float, +) -> tuple[CoordinateOperation, tuple[str, str]]: + """Build the conversion and the projected axis directions for a user-defined CRS.""" + ct = keys.get("proj_coord_trans") + if ct is None: + projection = keys.get("projection") + if projection is not None and projection != USER_DEFINED: + return CoordinateOperation.from_epsg(projection), DEFAULT_AXES + raise ValueError( + "A user-defined projected CRS needs ProjCoordTrans or Projection", + ) + + method = load_table().get(int(ct)) + if method is None: + raise ValueError(f"Unknown coordinate transformation code: {ct}") + if method.unsupported: + raise ValueError( + f"{method.ct_name} ({ct}) is not supported: {method.unsupported}", + ) + + values = resolve_parameters( + method, + keys, + to_degrees=to_degrees, + to_metres=to_metres, + ) + variant = select_variant(method, values, keys) + conversion = build_conversion(variant, values) + validate_conversion(conversion, variant, values) + + axes = variant.axes + if method.code == _POLAR_STEREOGRAPHIC: + # PROJ's WKT1 Polar_Stereographic import sets both axes by the sign of + # the latitude; GDAL's reading carries it (geotiff-test-data crs/README.md). + latitude = values["Latitude of natural origin"] + axes = ("south", "south") if latitude > 0 else ("north", "north") + return conversion, axes diff --git a/src/async_geotiff/_crs_geographic.py b/src/async_geotiff/_crs_geographic.py index 351f6bf..3be313b 100644 --- a/src/async_geotiff/_crs_geographic.py +++ b/src/async_geotiff/_crs_geographic.py @@ -19,6 +19,7 @@ from functools import lru_cache from typing import TYPE_CHECKING, Any, TypeGuard +from pyproj._crs import CoordinateSystem from pyproj.crs import GeographicCRS from pyproj.crs.coordinate_system import Cartesian2DCS, Ellipsoidal2DCS from pyproj.crs.datum import ( @@ -31,8 +32,6 @@ ) from pyproj.database import get_units_map -from pyproj._crs import CoordinateSystem # noqa: PLC2701 - if TYPE_CHECKING: from collections.abc import Mapping diff --git a/tests/test_crs_conformance.py b/tests/test_crs_conformance.py index 34d6634..48b161d 100644 --- a/tests/test_crs_conformance.py +++ b/tests/test_crs_conformance.py @@ -28,61 +28,20 @@ MANIFEST = json.loads((CRS_DIR / "manifest.json").read_text()) ROWS = {row["name"]: row for row in MANIFEST["cases"]} -_REJECTED_CT = "CT code rejected by _build_conversion" -_INVALID_PROJJSON = "builder emits PROJJSON that PROJ rejects" -_WRONG_VARIANT = "wrong method variant" -_ORIGIN_KEYS = ( - "origin or scale read from the wrong GeoKey, libgeotiff fallback order not applied" -) -_UNITS = "linear parameters labelled metres instead of the projected unit" -_AXES = "projected axis directions not set (south/south, north/north, or west/south)" _ASYNC_TIFF = "needs an async-tiff release with keys 2062/3096 (async-tiff#368)" _PE_STRING = "ESRI PE String read by pyproj differs from GDAL's ESRI morphing" KNOWN_FAILURES: dict[str, str] = { - # Rejected CT codes (spec section 1). - "cea": _REJECTED_CT + " (28 Cylindrical Equal Area)", - "eqdc": _REJECTED_CT + " (13 Equidistant Conic)", - "gnom": _REJECTED_CT + " (19 Gnomonic)", - "mill": _REJECTED_CT + " (20 Miller)", - "robin": _REJECTED_CT + " (23 Robinson)", - "vandg": _REJECTED_CT + " (25 Van der Grinten)", - "omerc_variant_b": _REJECTED_CT + " (9815 Hotine Oblique Mercator azimuth centre)", - "somerc": _REJECTED_CT + " (9815 Hotine Oblique Mercator azimuth centre)", - # PROJJSON PROJ rejects outright. - "aea_nad27": _INVALID_PROJJSON + ": EPSG-coded datum without an ellipsoid", - "tmerc_datum_wgs84": _INVALID_PROJJSON + ": EPSG-coded datum without an ellipsoid", - "geog_grad_wkt": _INVALID_PROJJSON + ": angular unit grads", - "lcc_1sp_grad_wkt": _INVALID_PROJJSON + ": angular unit grads", - "lcc_1sp_paris_grad": _INVALID_PROJJSON - + ": angular unit grads (also GDAL PM bug, spec Q3)", - "tmerc_ft": _INVALID_PROJJSON + ": linear unit international foot", - # Wrong variant. - "merc_2sp": _WRONG_VARIANT + ": Mercator with ProjStdParallel1 is variant B", - "stere_polar_a": _WRONG_VARIANT - + ": polar stereographic at the pole with scale is variant A", - "stere_south_a": _WRONG_VARIANT - + ": polar stereographic at the pole with scale is variant A", - "omerc_variant_a": _WRONG_VARIANT - + ": CT 3 is variant A; grid angle read from the azimuth key", - "labrd": _WRONG_VARIANT - + ": CT 4 is Laborde Oblique Mercator, not Hotine variant B", - # Origin and scale keys. - "aeqd": _ORIGIN_KEYS + "; method name maps to Modified Azimuthal Equidistant", - "sterea": _ORIGIN_KEYS, - "stere_oblique": _ORIGIN_KEYS, - "eqc_lat0": _ORIGIN_KEYS + "; latitude of natural origin dropped", - # Units. - "lcc_2sp_usft": _UNITS, - # Axes. - "stere_polar_b": _AXES, - "stere_south_b": _AXES, - "stere_polar_k1_wkt": _AXES, - "tmso": _AXES, - # Datum, prime meridian, TOWGS84. - "lcc_1sp_pm_epsg_tifffile": "EPSG-coded prime meridian read as longitude 0", - "tmerc_towgs84": _ASYNC_TIFF + "; no BoundCRS", - # ESRI PE String citations. + # GeoKeys async-tiff 0.7 does not expose. + "tmerc_towgs84": _ASYNC_TIFF + "; GeogTOWGS84GeoKey, no BoundCRS", + "omerc_variant_a": _ASYNC_TIFF + "; ProjRectifiedGridAngleGeoKey", + "omerc_variant_b": _ASYNC_TIFF + "; ProjRectifiedGridAngleGeoKey", + "somerc": _ASYNC_TIFF + "; ProjRectifiedGridAngleGeoKey", + # GDAL's own writer and reader disagree on a prime meridian in grads + # (spec Q3); we follow libgeotiff's single unit conversion. + "lcc_1sp_paris_grad": "GDAL converts a grads prime meridian three times on read", + # ESRI PE String citations: GDAL also applies the Geog* keys and its ESRI + # name morphing on top of the WKT; pyproj parses the WKT alone. "krovak": _PE_STRING + ": Krovak read as North Orientated", "moll": _PE_STRING + ": datum keeps its ESRI name", } diff --git a/tests/test_crs_conversion.py b/tests/test_crs_conversion.py new file mode 100644 index 0000000..a9c5778 --- /dev/null +++ b/tests/test_crs_conversion.py @@ -0,0 +1,182 @@ +"""Unit tests for the CT table interpreter. + +Inputs are plain dicts with async-tiff's GeoKeyDirectory attribute names. +""" + +from __future__ import annotations + +import pytest + +from async_geotiff._crs_conversion import ( + build_conversion, + conversion_from_geo_keys, + resolve_parameters, + select_variant, + validate_conversion, +) +from async_geotiff._crs_table import load_table + +TABLE = load_table() +TM = TABLE[1] +POLAR = TABLE[15] + + +def test_resolve_fallback_order(): + values = resolve_parameters( + TM, + {"proj_center_lat": 5.0, "proj_center_long": 6.0}, + to_degrees=1.0, + to_metres=1.0, + ) + assert values["Latitude of natural origin"] == 5.0 + assert values["Longitude of natural origin"] == 6.0 + assert values["Scale factor at natural origin"] == 1.0 + assert values["False easting"] == 0.0 + + +def test_resolve_zero_is_present(): + values = resolve_parameters( + TM, + {"proj_nat_origin_lat": 0.0, "proj_center_lat": 5.0}, + to_degrees=1.0, + to_metres=1.0, + ) + assert values["Latitude of natural origin"] == 0.0 + + +def test_resolve_scales_units(): + values = resolve_parameters( + TM, + { + "proj_nat_origin_lat": 52.0, + "proj_false_easting": 984250.0, + "proj_scale_at_nat_origin": 0.5, + }, + to_degrees=0.9, + to_metres=0.3048006096012192, + ) + assert values["Latitude of natural origin"] == pytest.approx(46.8) + assert values["False easting"] == pytest.approx(300000.0) + assert values["Scale factor at natural origin"] == 0.5 + + +def test_resolve_missing_accessor_raises(): + with pytest.raises(ValueError, match="ProjRectifiedGridAngle"): + resolve_parameters(TABLE[3], {}, to_degrees=1.0, to_metres=1.0) + + +def test_mercator_variant_b_when_parallel_present(): + mercator = TABLE[7] + keys = {"proj_std_parallel1": 30.0, "proj_nat_origin_long": 10.0} + values = resolve_parameters(mercator, keys, to_degrees=1.0, to_metres=1.0) + assert select_variant(mercator, values, keys).method_epsg == 9805 + keys = {"proj_scale_at_nat_origin": 0.98} + values = resolve_parameters(mercator, keys, to_degrees=1.0, to_metres=1.0) + assert select_variant(mercator, values, keys).method_epsg == 9804 + + +def test_polar_rule_after_unit_scaling(): + def pick(lat: float, scale: float) -> int | None: + keys = {"proj_nat_origin_lat": lat, "proj_scale_at_nat_origin": scale} + values = resolve_parameters(POLAR, keys, to_degrees=0.9, to_metres=1.0) + return select_variant(POLAR, values, keys).method_epsg + + assert pick(100.0, 1.0) == 9829 # 100 grad = 90 degrees, scale 1: variant B + assert pick(100.0, 0.9) == 9810 # at the pole with a scale: variant A + keys = {"proj_nat_origin_lat": 71.0, "proj_scale_at_nat_origin": 0.9} + values = resolve_parameters(POLAR, keys, to_degrees=1.0, to_metres=1.0) + with pytest.raises(ValueError, match="Polar_Stereographic"): + select_variant(POLAR, values, keys) + + +def test_unsupported_ct_raises(): + with pytest.raises(ValueError, match="CT_TransvMercator_Modified_Alaska"): + conversion_from_geo_keys({"proj_coord_trans": 2}, to_degrees=1.0, to_metres=1.0) + + +def test_typed_build_equals_proj_string(): + keys = { + "proj_nat_origin_lat": 0.0, + "proj_nat_origin_long": -3.5, + "proj_scale_at_nat_origin": 0.9996, + "proj_false_easting": 500000.0, + } + values = resolve_parameters(TM, keys, to_degrees=1.0, to_metres=1.0) + typed = build_conversion(TM.variants[0], values) + assert typed.method_code == "9807" + assert {p.name: p.value for p in typed.params}[ + "Longitude of natural origin" + ] == -3.5 + + +def test_proj_string_build_laborde(): + laborde = TABLE[4] + keys = { + "proj_center_lat": -18.9, + "proj_center_long": 46.43722917, + "proj_azimuth_angle": 18.9, + "proj_scale_at_center": 0.9995, + "proj_false_easting": 400000.0, + "proj_false_northing": 800000.0, + } + values = resolve_parameters(laborde, keys, to_degrees=1.0, to_metres=1.0) + conversion = build_conversion(laborde.variants[0], values) + assert conversion.method_code == "9813" + assert {p.name: p.value for p in conversion.params}[ + "Azimuth at projection centre" + ] == 18.9 + + +def test_validate_catches_dropped_parameter(): + keys = {"proj_nat_origin_lat": 5.0, "proj_nat_origin_long": -3.5} + values = resolve_parameters(TM, keys, to_degrees=1.0, to_metres=1.0) + conversion = build_conversion(TM.variants[0], values) + validate_conversion(conversion, TM.variants[0], values) + values["Latitude of natural origin"] = 6.0 + with pytest.raises(ValueError, match="Latitude of natural origin"): + validate_conversion(conversion, TM.variants[0], values) + + +def test_projection_code_path(): + conversion, axes = conversion_from_geo_keys( + {"projection": 16033}, + to_degrees=1.0, + to_metres=1.0, + ) + assert conversion.method_code == "9807" + assert {p.name: p.value for p in conversion.params}[ + "Longitude of natural origin" + ] == 15.0 + assert axes == ("east", "north") + + +def test_polar_axes(): + north = { + "proj_coord_trans": 15, + "proj_nat_origin_lat": 90.0, + "proj_scale_at_nat_origin": 0.994, + } + south = { + "proj_coord_trans": 15, + "proj_nat_origin_lat": -71.0, + "proj_scale_at_nat_origin": 1.0, + } + assert conversion_from_geo_keys(north, to_degrees=1.0, to_metres=1.0)[1] == ( + "south", + "south", + ) + assert conversion_from_geo_keys(south, to_degrees=1.0, to_metres=1.0)[1] == ( + "north", + "north", + ) + + +def test_south_orientated_axes(): + keys = { + "proj_coord_trans": 27, + "proj_nat_origin_long": 19.0, + "proj_scale_at_nat_origin": 1.0, + } + conversion, axes = conversion_from_geo_keys(keys, to_degrees=1.0, to_metres=1.0) + assert conversion.method_code == "9808" + assert axes == ("west", "south") From e0ab3e6acadf14a00d2caa773eafad3a3ebe2644 Mon Sep 17 00:00:00 2001 From: Kyle Barron Date: Mon, 26 Oct 2026 14:11:29 -0400 Subject: [PATCH 4/5] style: Imperative docstrings in the CRS builders; note Laborde PROJ keys in the spec Co-Authored-By: Claude Fable 5.1 --- .../2026-10-26-geokey-crs-conformance-design.md | 2 +- src/async_geotiff/_crs.py | 4 ++-- src/async_geotiff/_crs_geographic.py | 14 +++++++------- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/dev-docs/specs/2026-10-26-geokey-crs-conformance-design.md b/dev-docs/specs/2026-10-26-geokey-crs-conformance-design.md index 757309f..a1b0bf3 100644 --- a/dev-docs/specs/2026-10-26-geokey-crs-conformance-design.md +++ b/dev-docs/specs/2026-10-26-geokey-crs-conformance-design.md @@ -437,7 +437,7 @@ Every row's `keys` order comes from `GTIFFetchProjParms`; every method from the | 1 | Transverse Mercator (9807), `tmerc` | lat_0, lon_0, k, FE, FN | L1774-L1816 | L1440 | | 2 | unsupported: no GDAL read case (falls to `SetLocalCS`) | | | L1587 | | 3 | Hotine Oblique Mercator (variant A) (9812), `omerc +no_uoff` | lat_c, lon_c, azimuth, rectified grid angle, k_c, FE, FN | L1819-L1870 | L1489 | -| 4 | Laborde Oblique Mercator (9813), `labrd` | lat_c, lon_c, azimuth, k_c, FE, FN | L1873-L1917 | L1500 | +| 4 | Laborde Oblique Mercator (9813), `labrd` (PROJ keys `+lon_0` and `+azi`, not the HOM `+lonc`/`+alpha` the table's shared parameters name; the builder overrides them, the table should be corrected) | lat_c, lon_c, azimuth, k_c, FE, FN | L1873-L1917 | L1500 | | 5 | unsupported (no GDAL read case) | | | L1587 | | 6 | unsupported (no GDAL read case) | | | L1587 | | 7 | Mercator A (9804) / B (9805), `merc` | see 5.2 | L1717-L1771 | L1450 | diff --git a/src/async_geotiff/_crs.py b/src/async_geotiff/_crs.py index 5ab2cc5..13559cd 100644 --- a/src/async_geotiff/_crs.py +++ b/src/async_geotiff/_crs.py @@ -95,7 +95,7 @@ def _esri_pe_string(gkd: GeoKeyDirectory) -> str | None: def _geographic_crs(gkd: GeoKeyDirectory) -> CRS: - """The geographic CRS, by EPSG code or from the Geog* keys.""" + """Build the geographic CRS, by EPSG code or from the Geog* keys.""" code = gkd.geographic_type if code is not None and code != USER_DEFINED_CRS: return CRS.from_epsg(code) @@ -104,7 +104,7 @@ def _geographic_crs(gkd: GeoKeyDirectory) -> CRS: def _projected_crs(gkd: GeoKeyDirectory) -> CRS: - """The projected CRS, by EPSG code or from the Geog* and Proj* keys.""" + """Build the projected CRS, by EPSG code or from the Geog* and Proj* keys.""" code = gkd.projected_type if code is not None and code != USER_DEFINED_CRS: return CRS.from_epsg(code) diff --git a/src/async_geotiff/_crs_geographic.py b/src/async_geotiff/_crs_geographic.py index 3be313b..84369b4 100644 --- a/src/async_geotiff/_crs_geographic.py +++ b/src/async_geotiff/_crs_geographic.py @@ -124,7 +124,7 @@ def parse_citation(citation: str | None) -> dict[str, str]: def ellipsoid(keys: Mapping[str, Any], citation: Mapping[str, str]) -> Ellipsoid: - """The ellipsoid from its code, or from explicit axes.""" + """Build the ellipsoid from its code, or from explicit axes.""" code = keys.get("geog_ellipsoid") semi_major = keys.get("geog_semi_major_axis") semi_minor = keys.get("geog_semi_minor_axis") @@ -134,7 +134,7 @@ def ellipsoid(keys: Mapping[str, Any], citation: Mapping[str, str]) -> Ellipsoid return Ellipsoid.from_epsg(code) if semi_major is None: raise ValueError( - "A user-defined ellipsoid needs a semi-major axis (GeogSemiMajorAxisGeoKey)", + "A user-defined ellipsoid needs a semi-major axis (GeogSemiMajorAxis)", ) name = citation.get("Ellipsoid") @@ -165,7 +165,7 @@ def prime_meridian( citation: Mapping[str, str], unit: AngularUnit, ) -> PrimeMeridian: - """The prime meridian from its code, or from its longitude in the file's unit.""" + """Build the prime meridian from its code, or from its longitude and unit.""" code = keys.get("geog_prime_meridian") if _is_code(code): return PrimeMeridian.from_epsg(code) @@ -182,7 +182,7 @@ def datum( ellipsoid: Ellipsoid, prime_meridian: PrimeMeridian, ) -> Datum: - """The datum from its code (which brings its own ellipsoid), or user-defined.""" + """Build the datum from its code (which brings its ellipsoid), or user-defined.""" code = keys.get("geog_geodetic_datum") if _is_code(code): return Datum.from_epsg(code) @@ -194,7 +194,7 @@ def datum( def ellipsoidal_cs(unit: AngularUnit) -> CoordinateSystem: - """A lon/lat coordinate system in the given angular unit.""" + """Build a lon/lat coordinate system in the given angular unit.""" if unit == DEGREE: return Ellipsoidal2DCS() json_unit = { @@ -225,7 +225,7 @@ def ellipsoidal_cs(unit: AngularUnit) -> CoordinateSystem: def cartesian_cs(unit: LinearUnit, axes: tuple[str, str]) -> CoordinateSystem: - """A projected coordinate system in the given unit with the given axis directions.""" + """Build a projected coordinate system in the given unit and axis directions.""" if axes == ("east", "north"): if unit == METRE: return Cartesian2DCS() @@ -261,7 +261,7 @@ def cartesian_cs(unit: LinearUnit, axes: tuple[str, str]) -> CoordinateSystem: def geographic_crs(keys: Mapping[str, Any]) -> tuple[GeographicCRS, AngularUnit]: - """A user-defined geographic CRS and its angular unit.""" + """Build a user-defined geographic CRS and return it with its angular unit.""" citation = parse_citation(keys.get("geog_citation")) unit = angular_unit(keys) pm = prime_meridian(keys, citation, unit) From a7bf8a0499581f25e12ba604ade1c3412364fc6c Mon Sep 17 00:00:00 2001 From: Kyle Barron Date: Mon, 26 Oct 2026 14:22:04 -0400 Subject: [PATCH 5/5] fix: Handle coded datums without axes, coded ellipsoids with one axis, and exact degree units Review findings on GeoKey arrangements GDAL never writes but the spec allows: a coded datum no longer requires ellipsoid keys, an ellipsoid code with only a semi-major axis keeps the coded flattening (and a user-defined ellipsoid with no shape raises instead of becoming a sphere), the degree code 9102 is exactly 1.0 as in libgeotiff, and a unit with a zero conversion factor raises instead of zeroing angles. Co-Authored-By: Claude Fable 5.1 --- src/async_geotiff/_crs_geographic.py | 49 ++++++++++++++++++++++------ tests/test_crs_geographic.py | 33 +++++++++++++++++++ 2 files changed, 72 insertions(+), 10 deletions(-) diff --git a/src/async_geotiff/_crs_geographic.py b/src/async_geotiff/_crs_geographic.py index 84369b4..163e860 100644 --- a/src/async_geotiff/_crs_geographic.py +++ b/src/async_geotiff/_crs_geographic.py @@ -88,16 +88,26 @@ def _units(category: str) -> dict[str, Any]: return {unit.code: unit for unit in units} +def _angular(name: str, factor: float, source: str) -> AngularUnit: + """Build an angular unit from its size in radians; degrees snap to exactly 1.""" + if not factor: + raise ValueError(f"{source} gives an angular unit of size 0") + if math.isclose(factor, DEGREE.conversion_factor): + # libgeotiff's UOMAngleInDegrees is exactly 1.0 for the degree codes + # and skips the multiplication; pyproj's factor is a hair off. + return DEGREE + return AngularUnit(name, factor * DEGREES_PER_RADIAN, factor) + + def angular_unit(keys: Mapping[str, Any]) -> AngularUnit: """`GeogAngularUnits`, or `GeogAngularUnitSize` in radians, default degree.""" code = keys.get("geog_angular_units") if _is_code(code): unit = _units("angular")[str(code)] - factor = float(unit.conv_factor) - return AngularUnit(unit.name, factor * DEGREES_PER_RADIAN, factor) + return _angular(unit.name, float(unit.conv_factor), f"GeogAngularUnits {code}") size = keys.get("geog_angular_unit_size") if size is not None: - return AngularUnit("unknown", float(size) * DEGREES_PER_RADIAN, float(size)) + return _angular("unknown", float(size), "GeogAngularUnitSize") return DEGREE @@ -130,16 +140,27 @@ def ellipsoid(keys: Mapping[str, Any], citation: Mapping[str, str]) -> Ellipsoid semi_minor = keys.get("geog_semi_minor_axis") inv_flattening = keys.get("geog_inv_flattening") - if _is_code(code) and semi_major is None: - return Ellipsoid.from_epsg(code) if semi_major is None: + if _is_code(code): + return Ellipsoid.from_epsg(code) raise ValueError( "A user-defined ellipsoid needs a semi-major axis (GeogSemiMajorAxis)", ) name = citation.get("Ellipsoid") - if name is None: - name = Ellipsoid.from_epsg(code).name if _is_code(code) else "unknown" + if _is_code(code): + # libgeotiff loads the coded ellipsoid, then overrides only the axes + # the keys supply (GTIFGetDefn, geo_normalize.c L2580-L2600). + coded = Ellipsoid.from_epsg(code) + name = name or coded.name + if inv_flattening is None and semi_minor is None: + inv_flattening = coded.inverse_flattening or None + semi_minor = None if inv_flattening else coded.semi_minor_metre + elif inv_flattening is None and semi_minor is None: + raise ValueError( + "A user-defined ellipsoid needs GeogInvFlattening or GeogSemiMinorAxis", + ) + name = name or "unknown" if inv_flattening: return CustomEllipsoid( @@ -179,13 +200,18 @@ def prime_meridian( def datum( keys: Mapping[str, Any], citation: Mapping[str, str], - ellipsoid: Ellipsoid, + ellipsoid: Ellipsoid | None, prime_meridian: PrimeMeridian, ) -> Datum: - """Build the datum from its code (which brings its ellipsoid), or user-defined.""" + """Build the datum from its code (which brings its ellipsoid), or user-defined. + + `ellipsoid` is only needed, and only read, for a user-defined datum. + """ code = keys.get("geog_geodetic_datum") if _is_code(code): return Datum.from_epsg(code) + if ellipsoid is None: + raise ValueError("A user-defined datum needs an ellipsoid") return CustomDatum( name=citation.get("Datum", "unknown"), ellipsoid=ellipsoid, @@ -265,7 +291,10 @@ def geographic_crs(keys: Mapping[str, Any]) -> tuple[GeographicCRS, AngularUnit] citation = parse_citation(keys.get("geog_citation")) unit = angular_unit(keys) pm = prime_meridian(keys, citation, unit) - datum_ = datum(keys, citation, ellipsoid(keys, citation), pm) + # A coded datum implies its ellipsoid; the file need not carry axes at all. + coded_datum = _is_code(keys.get("geog_geodetic_datum")) + ellipsoid_ = None if coded_datum else ellipsoid(keys, citation) + datum_ = datum(keys, citation, ellipsoid_, pm) crs = GeographicCRS( name=citation.get("GCS Name", "unknown"), datum=datum_, diff --git a/tests/test_crs_geographic.py b/tests/test_crs_geographic.py index d78acd3..668ad82 100644 --- a/tests/test_crs_geographic.py +++ b/tests/test_crs_geographic.py @@ -46,6 +46,19 @@ def test_angular_unit_default_degree(): assert angular_unit({}).to_degrees == 1.0 +def test_angular_unit_degree_code_is_exact(): + """libgeotiff treats 9102 as exactly 1.0; pyproj's factor is a hair off.""" + assert angular_unit({"geog_angular_units": 9102}) == DEGREE + + +def test_angular_unit_zero_factor_raises(): + with pytest.raises(ValueError, match="GeogAngularUnitSize"): + angular_unit({"geog_angular_units": 32767, "geog_angular_unit_size": 0.0}) + # pyproj reports no conversion factor for some sexagesimal EPSG codes. + with pytest.raises(ValueError, match="9107"): + angular_unit({"geog_angular_units": 9107}) + + def test_angular_unit_size(): unit = angular_unit( {"geog_angular_units": 32767, "geog_angular_unit_size": 0.015707963267949}, @@ -105,6 +118,26 @@ def test_ellipsoid_sphere(): assert e.to_json_dict()["radius"] == 6371007.181 +def test_ellipsoid_code_with_only_semi_major_keeps_flattening(): + """libgeotiff seeds the axes from the code and overrides only what keys give.""" + e = ellipsoid({"geog_ellipsoid": 7030, "geog_semi_major_axis": 6378137.0}, {}) + assert e.name == "WGS 84" + assert e.inverse_flattening == pytest.approx(298.257223563) + + +def test_ellipsoid_without_shape_raises(): + with pytest.raises(ValueError, match="GeogInvFlattening or GeogSemiMinorAxis"): + ellipsoid({"geog_semi_major_axis": 6378137.0}, {}) + + +def test_datum_from_code_without_ellipsoid_keys(): + """A coded datum implies its ellipsoid; GDAL just happens to write the axes too.""" + crs, _ = geographic_crs({"geographic_type": 32767, "geog_geodetic_datum": 6326}) + assert crs.ellipsoid is not None + assert crs.ellipsoid.name == "WGS 84" + assert "World Geodetic System 1984" in crs.datum.name + + def test_ellipsoid_requires_semi_major(): with pytest.raises(ValueError, match="semi-major"): ellipsoid({"geog_ellipsoid": 32767}, {})