Source code for geodetic_engine.geodesy.transformation

"""Resolving and applying a coordinate transformation, with the rules enforced.

Four things are checked here that PROJ will not check for you, because PROJ's
job is to compute and this package's job is to refuse to compute something
untrustworthy:

1. If an operation was requested, the transformer that gets built is inspected
   to confirm it really contains that operation. PROJ will otherwise build a
   perfectly functional transformer using a different one.
2. A ballpark path is refused outright rather than returned as an approximate
   number with no usable accuracy statement.
3. A grid the operation depends on but that is not installed is an error, named
   specifically, rather than a quiet fall back to a grid-free operation.
4. A time-dependent operation without a coordinate epoch is an error. A dynamic
    reference frame alone does not require an epoch if the operation ignores time.

Coordinate **values** are in ``xy`` order, in and out: easting or longitude
first wherever a CRS has an easting and a northing, whatever order it declares
them in. A CRS with no such pair (Krovak's southing and westing, a geocentric
X/Y/Z, a plant grid declaring north and west) keeps its declared order, as
PROJ's ``always_xy`` keeps it; ``value_axis_order`` states the order axis by
axis. The CRSs' declared axis order is reported separately and is not changed
by this; see :mod:`geodetic_engine.geodesy.crs`. PROJ does not honour this
contract at an engineering CRS on its own; see the workaround block above
``_correct_engineering_axes``.
"""

from __future__ import annotations

import json
import math
import os
import warnings
from collections.abc import Generator, Iterable, Iterator, Sequence
from contextlib import contextmanager
from dataclasses import dataclass, replace
from functools import lru_cache
from pathlib import Path
from typing import TYPE_CHECKING, Any, cast

import numpy as np
from numpy.typing import ArrayLike, NDArray
from pyproj import CRS, Transformer, datadir
from pyproj.crs import CoordinateOperation
from pyproj.enums import TransformDirection
from pyproj.exceptions import CRSError, ProjError
from pyproj.network import is_network_enabled
from pyproj.transformer import TransformerGroup

from geodetic_engine._referencing.database import (
    DatabaseIdentity,
    database_fingerprints,
    database_identity,
)
from geodetic_engine._referencing.projjson import operation_nodes
from geodetic_engine.geodesy import _compose, _datum, _pipeline_opt
from geodetic_engine.geodesy.crs import AxisSpec, CoordinateReferenceSystem
from geodetic_engine.geodesy.errors import (
    AmbiguousOperationError,
    BallparkTransformationError,
    CoordinateOutOfRangeError,
    MissingCoordinateEpochError,
    MissingGridError,
    OperationNotAvailableError,
    TransformationFailedError,
)
from geodetic_engine.geodesy.operation import (
    _VISUALIZATION_SUFFIX,
    AppliedOperation,
    AreaOfUse,
    GridUsage,
    OperationCandidate,
    OperationReference,
    OperationRequest,
    OperationRoute,
    OperationStep,
    StatedOperation,
    base_authority,
    datum_operation_count,
    distinct_requests,
    fully_requested,
    grid_usages,
    has_inverted_step,
    is_ballpark,
    matched_request_directions,
    operation_names,
    operation_references,
    parse_operations,
    requires_epoch,
)
from geodetic_engine.geodesy.result import (
    ArrayTransformationResult,
    FloatArray,
    TransformationResult,
)

if TYPE_CHECKING:
    from geodetic_engine.geodesy._antimeridian import Antimeridian
    from geodetic_engine.geodesy._segments import Segments
    from geodetic_engine.geodesy.geometry import (
        AxisOrder,
        GeometryResult,
        GeometryResults,
        Orientation,
    )

_VERTICAL_DIRECTIONS = frozenset({"up", "down"})

# Axis directions that carry latitude and longitude in a geographic CRS.
_NORTHINGS = frozenset({"north", "south"})
_EASTINGS = frozenset({"east", "west"})

# PROJ transforms at most x, y, z: a fourth spatial component has no meaning to
# it, so one extra value beyond what a CRS declares is tolerated (a height
# alongside a 2D horizontal CRS, carried through unchanged) but no more than
# that.
_MAX_COORDINATE_VALUES = 3

# PROJ's flag for running a step backwards. A bare token, never a parameter
# with a value, so it can be added or removed by name.
_INVERSE_FLAG = "inv"

# How PROJ words a grid it cannot open while building a pipeline step. The
# message names the step, never the file.
_MISSING_FILE_MARKER = "File not found or invalid"

# Methods that restate axes rather than move coordinates. PROJ inserts these
# when it normalises axis order, and they are not the method a caller means.
_BOOKKEEPING_METHODS = frozenset(
    {
        "axis order reversal (2d)",
        "axis order reversal (geographic3d horizontal)",
        "change of vertical unit",
        "geographic3d to geographic2d conversion",
    }
)

# Vertical operation methods whose shift is the same everywhere. Their result
# does not read the horizontal position, unlike a grid interpolation or
# "Vertical Offset and Slope", so a position supplied alongside the height is
# carried rather than interpreted as a latitude and longitude.
_POSITION_FREE_VERTICAL_METHODS = frozenset(
    {
        "vertical offset",
        "change of vertical unit",
        "height depth reversal",
    }
)


@dataclass(frozen=True, slots=True)
class _Pipeline:
    """One or more PROJ transformers applied in sequence.

    A single operation is a pipeline of one. Chaining exists for the case where
    the requested operation is defined between different CRSs than the caller's
    pair, for example a datum shift published between geographic CRSs that a
    caller wants applied between two projected ones.
    """

    steps: tuple[tuple[Transformer, TransformDirection], ...]
    core: Transformer
    route: OperationRoute
    identified_by: tuple[OperationRequest, ...] = ()
    """Operations that name this pipeline when the caller did not name one.

    Set for a bound CRS, whose definition states the operation itself: one
    entry per bound end. Kept apart from the caller's request so that a result
    reports what was applied without claiming it was asked for.
    """
    corrected: tuple[tuple[Transformer, TransformDirection], ...] | None = None
    """The steps actually run, when a PROJ workaround had to rewrite one.

    ``steps`` keeps the transformers PROJ built, which carry the provenance
    (definition, accuracy, grids). This holds the same sequence with the
    rewritten core in place of the original, and is what executes and what is
    reported as the pipeline. None when nothing was rewritten. See
    ``_correct_engineering_axes``.
    """
    compiled: Transformer | None = None
    """Single compiled PROJ pipeline executing the whole chain in one C call."""
    pipeline_text: str | None = None
    """Optimized pipeline text matching ``compiled`` when built from flat steps."""
    parts: tuple[_Part, ...] = ()
    """Individual requested operations in execution order for a composed chain."""

    @property
    def executed(self) -> tuple[tuple[Transformer, TransformDirection], ...]:
        """The steps that run, corrected where a PROJ workaround applies."""
        return self.steps if self.corrected is None else self.corrected

    def run(
        self,
        columns: tuple[FloatArray, ...],
        epoch: float | None,
        *,
        errcheck: bool = True,
    ) -> tuple[FloatArray, ...]:
        """Apply every step in place to privately owned coordinate buffers.

        With ``errcheck`` false, PROJ does not raise for a point it cannot
        transform, and leaves it infinite instead.
        """
        count = len(columns[0]) if columns else 0
        times = None if epoch is None else np.full(count, epoch)
        if self.compiled is not None:
            return _apply(
                self.compiled,
                columns,
                times,
                TransformDirection.FORWARD,
                errcheck=errcheck,
            )
        # A 2D position leaves a geocentric leg with a Z the next leg needs to
        # recover latitude, as one PROJ pipeline would keep it.
        values = (
            columns
            if len(self.executed) <= 1 or len(columns) >= _MAX_COORDINATE_VALUES
            else (
                *columns,
                *(
                    np.zeros(count, dtype=np.float64)
                    for _ in range(_MAX_COORDINATE_VALUES - len(columns))
                ),
            )
        )
        for transformer, direction in self.executed:
            if times is not None and epoch is not None:
                # Every leg reads the observation year, not the previous output time.
                times.fill(epoch)
            values = _apply(transformer, values, times, direction, errcheck=errcheck)
        return values[: len(columns)]

    @property
    def core_direction(self) -> TransformDirection:
        """Direction in which the raw core definition is executed."""
        return next(
            direction
            for transformer, direction in self.steps
            if transformer is self.core
        )

    @property
    def definition(self) -> dict[str, Any]:
        """PROJJSON of the resolved operation."""
        try:
            return dict(self.core.to_json_dict())
        except (TypeError, ProjError):
            return {}

    @property
    def accuracy(self) -> float | None:
        """Stated accuracy in metres, or None when PROJ reports none."""
        value = self.core.accuracy
        return None if value is None or value < 0 else float(value)

    @property
    def text(self) -> str | None:
        """The whole chain as one PROJ pipeline definition, ready to be rebuilt."""
        if self.pipeline_text is not None:
            return self.pipeline_text
        return _compose_pipeline(self.executed)

    @property
    def reads_declared_horizontal(self) -> bool:
        """Whether the pipeline consumes its horizontal pair northing-first."""
        steps = (
            _pipeline_opt.parse_steps(self.pipeline_text)
            if self.pipeline_text is not None
            else _composed_steps(self.executed)
        )
        if steps is None:
            if not self.executed:
                return False
            transformer, direction = self.executed[0]
            return _swaps_horizontal(_entry_step(transformer.definition, direction))
        entry = next((step for step in steps if not _passes_horizontal(step)), None)
        return entry is not None and _swaps_horizontal(entry)


@dataclass(frozen=True, slots=True)
class _Part:
    """One resolved operation within a composed multi-operation chain."""

    requests: tuple[OperationRequest, ...]
    pipeline: _Pipeline


[docs] class Transformation: """A resolved, reusable transformation between two CRSs. Resolution happens once, on construction, so every failure that can be detected without coordinates is raised before any coordinate is handed over. The built PROJ transformer is kept, so transforming many batches costs one resolution rather than one per batch. Coordinate values are in ``xy`` order in both directions: longitude then latitude for geographic CRSs, easting then northing for projected and engineering ones that have both, then height. A CRS with no easting and northing to order (Krovak's southing and westing, a geocentric X/Y/Z, a plant grid declaring north and west) keeps its declared order, as PROJ's ``always_xy`` keeps it. The CRSs' EPSG-declared axis order is reported by :attr:`source_crs` and :attr:`target_crs` and is frequently different; their ``value_axis_order`` states the order the values are in, axis by axis. Example: Reusing one transformation for several batches, naming the operation so that PROJ cannot substitute another: >>> tfm = Transformation("EPSG:4258", "EPSG:25832", operation="EPSG:16032") >>> tfm.operation.authority_code 'EPSG:16032' >>> first = tfm.transform([(10.75, 59.91)]) >>> second = tfm.transform([(5.32, 60.39), (7.99, 58.15)]) A time-dependent operation needs an epoch, in decimal years: >>> tfm = Transformation("EPSG:4896", "EPSG:4938", operation="EPSG:6277") >>> result = tfm.transform([(1137080.2487, -214618.1963, 6252133.9585)], ... coordinate_epoch=1993.0) A compound target CRS can need a horizontal and a vertical operation both named: PROJ fuses the two into one unidentified step whenever each touches only part of the compound, so naming just one would leave the other chosen silently. >>> tfm = Transformation("EPSG:4979", "EPSG:6172", ... operation=["EPSG:11028", "EPSG:11559"]) A datum change requires an explicit operation or bound CRS. Automatic datum selection and ballpark results are not supported: >>> tfm = Transformation("EPSG:4230", "EPSG:4326", operation="EPSG:1133") """ __slots__ = ( "_applied", "_database_fingerprints", "_grids", "_pipeline", "_pipeline_text", "_requests", "_requires_epoch", "_source", "_target", )
[docs] def __init__( self, source_crs: Any, target_crs: Any, operation: ( str | int | OperationReference | StatedOperation | CoordinateOperation | Sequence[ str | int | OperationReference | StatedOperation | CoordinateOperation ] | None ) = None, *, allow_any_operation: bool = False, ) -> None: """Resolve a transformation. Args: source_crs: CRS the input coordinates are in; an authority code, WKT, a PROJ string or a :class:`pyproj.CRS`. target_crs: CRS to produce coordinates in. operation: EPSG coordinate operation to apply, as ``"EPSG:15670"``, a bare code, an OGC URN, an operation name, or an :class:`~geodetic_engine.geodesy.operation.OperationCandidate` from :func:`available_operations` -- the latter is the only way to pin down a candidate PROJ built with no EPSG id of its own. Or several, when a compound target CRS needs more than one to be pinned down (a horizontal and a vertical operation, most commonly). Several are a set, not a sequence: each is checked for independently against whatever pipeline PROJ built, so the order they are given in does not matter and does not change the result. When omitted, only same-datum conversions or explicitly bound operations are permitted. An operation may also be stated outright rather than named: an OSDU persistableReference payload, an ESRI ``GEOGTRAN``, a :class:`pyproj.crs.CoordinateOperation`, or a parsed reference. What is stated is then applied exactly as given, parameters and all, instead of being resolved against PROJ's database -- which is the point, since a payload's parameters need not agree with whatever a register publishes under the same code. A stated operation is applied on its own and cannot be combined with other references. allow_any_operation: Retained for call compatibility. No longer enables automatic datum selection or ballpark transformations. Raises: UnresolvableCRSError: If either CRS cannot be constructed. OperationNotAvailableError: If the requested operation(s) cannot be applied to this CRS pair, or if the operation is a Similarity or Affine parametric transformation into a northing-first projected CRS whose evaluation point cannot be placed inside the area of use under either reading of its ordinates; see ``_correct_engineering_axes``. AmbiguousOperationError: If no operation was requested, the transformation involves an unbound datum change. BallparkTransformationError: If the path includes a ballpark. MissingGridError: If a grid the operation needs is not installed. """ self._source = CoordinateReferenceSystem.from_user_input(source_crs) self._database_fingerprints = database_fingerprints(database_identity()) self._target = CoordinateReferenceSystem.from_user_input(target_crs) self._requests = ( () if operation is None else distinct_requests(parse_operations(operation)) ) pipeline = _resolve( self._source, self._target, self._requests, allow_any_operation=allow_any_operation, ) if pipeline.parts: examined = [ _examine(part.requests, part.pipeline, self._source, self._target) for part in pipeline.parts ] applied = _describe_chain( self._requests, pipeline, [found for found, _ in examined], ) operations = tuple(op for _, ops in examined for op in ops) else: pipeline = _compile_pipeline(_correct_engineering_axes(pipeline)) applied, operations = _examine( self._requests, pipeline, self._source, self._target ) if ( pipeline.route is OperationRoute.TRANSFORMER_GROUP and len(self._requests) > 1 ): tg_parts = _transformer_group_parts( pipeline.definition, self._requests, self._source, self._target ) if tg_parts: applied = replace(applied, parts=tg_parts) self._grids = _confirm_installed(grid_usages(operations), pipeline) _require_grids(self._grids, self._source, self._target) self._requires_epoch = applied.requires_epoch self._applied = applied self._pipeline = pipeline self._pipeline_text = pipeline.text
@property def source_crs(self) -> CoordinateReferenceSystem: """CRS the input coordinates are expressed in.""" return self._source @property def target_crs(self) -> CoordinateReferenceSystem: """CRS the output coordinates are expressed in.""" return self._target @property def operation(self) -> AppliedOperation: """Which operation is applied, and how it was arrived at.""" return self._applied @property def grids(self) -> tuple[GridUsage, ...]: """Grid files this transformation depends on. All are installed.""" return self._grids @property def requires_epoch(self) -> bool: """Whether a coordinate epoch must be supplied to transform. True when the operation actually reads the epoch, not merely when a datum involved is a dynamic reference frame: a static Helmert out of a dynamic frame gives the same answer at every epoch. """ return self._requires_epoch
[docs] def transform( self, x: Iterable[Iterable[float]] | Iterable[float] | float, y: Iterable[float] | float | None = None, z: Iterable[float] | float | None = None, *, coordinate_epoch: float | None = None, ) -> TransformationResult: """Transform one point or a batch of points. Args: x: Either every point's values in one go -- a single point given flat such as ``(lon, lat)``, a list of tuples, or a 2D numpy array of shape ``(n_points, n_axes)`` -- when ``y`` is omitted; or just the first axis's values, matching :meth:`pyproj.Transformer.transform`'s ``xx, yy, zz`` convention, when ``y`` is given. y: Second axis's values: a scalar for one point, or a sequence for a batch. Omit to pass ``x`` as the whole set of points instead. z: Third axis's values (for example a height), in the same shape as ``x`` and ``y``. A lone scalar is broadcast against the other axes, so one height can be given once for many horizontal points rather than repeated. coordinate_epoch: Decimal year the coordinates were observed at, for example ``2010.0``. Required when the operation reads it, which is not the same as either CRS being dynamic. Returns: The transformed coordinates and their provenance. Output values are in ``xy`` order in the target CRS's axis units, with one value per axis the target CRS declares. Raises: TypeError: If ``z`` was given without ``y``, or ``x`` is a lone number while ``y`` is omitted, which names no point. ValueError: If points disagree on how many values they carry, or that count is not the source CRS's declared dimension, or one more (a height alongside a 2D horizontal CRS, carried through unchanged). MissingCoordinateEpochError: If the operation reads a coordinate epoch and none was given. CoordinateOutOfRangeError: If a latitude or longitude is outside the range the source CRS's own axis unit can represent, which most often means projected coordinates were passed to a geographic CRS. TransformationFailedError: If PROJ could not produce a finite result, or cannot produce every axis the target CRS declares. Example: A single point can be given flat, without wrapping it in a list: >>> tfm = Transformation("EPSG:4979", "EPSG:3855", operation="EPSG:3858") >>> tfm.transform((-144.0, 72.0, 548.4082)).coordinates ((556.38...,),) Or as separate per-axis values, matching pyproj's own convention: >>> tfm.transform(-144.0, 72.0, 548.4082).coordinates ((556.38...,),) """ # Object arrays keep the value-by-value normalisation below, as lists # do: it reads a 1D array of (lon, lat) tuples, such as a pandas # Series of them after to_numpy(), as one point per tuple. if ( isinstance(x, np.ndarray) and (y is None or isinstance(y, np.ndarray | int | float)) and (z is None or isinstance(z, np.ndarray | int | float)) and not any( isinstance(value, np.ndarray) and value.dtype.hasobject for value in (x, y, z) ) ): return self.transform_arrays( x, y, z, coordinate_epoch=coordinate_epoch ).to_result() if y is None: if z is not None: raise TypeError( "z was given without y; pass x, y and z as separate " "per-axis values, or x alone as the whole set of points" ) if isinstance(x, int | float): raise TypeError( "a single number is not a point; give every value of the " "point, for example (lon, lat), or pass x, y and z as " "separate per-axis values" ) columns = _columns(self._source, x) else: # Giving y selects pyproj's per-axis convention, under which x is # one axis's values and never the whole batch of points. columns = _columns_from_axes( self._source, cast("Iterable[float] | float", x), y, z ) return self._transform_columns( tuple(np.array(column, dtype=np.float64) for column in columns), coordinate_epoch, ).to_result()
[docs] def transform_arrays( self, x: ArrayLike, y: ArrayLike | None = None, z: ArrayLike | None = None, *, coordinate_epoch: float | None = None, ) -> ArrayTransformationResult: """Transform a numeric batch without materialising Python point objects. Accept a row array of shape ``(n_points, n_values)`` (or one flat point), or separate one-dimensional axes. Scalar axes broadcast. Each input axis is copied once into a private contiguous float64 working buffer, then transformed in place through every pipeline step. Strided, read-only and non-float64 inputs are accepted; caller buffers are never modified, including when execution fails. Output columns are independent of the inputs and of later calls. Geodetic rules, output dimensions and errors match :meth:`transform`. Use :meth:`transform_batches` for a lazy stream of bounded row batches. """ return self._transform_columns( _array_columns(self._source, x, y, z), coordinate_epoch )
[docs] def transform_batches( self, batches: Iterable[ArrayLike], *, coordinate_epoch: float | None = None, ) -> Generator[ArrayTransformationResult]: """Lazily transform row batches, with no prefetch or retained history. The producer controls each batch's size and when it is available. Only the next batch is read when the consumer advances the iterator. Results own their arrays and remain valid after subsequent batches. Range and non-finite-result errors report stream-global point indexes. Errors stop iteration; batches already yielded are not rolled back. No network I/O, threads or asynchronous scheduling are performed here. """ offset = 0 for batch in batches: result = self._transform_columns( _array_columns(self._source, batch, None, None), coordinate_epoch, point_offset=offset, ) offset += result.count yield result
[docs] def transform_geometry( self, value: object, *, coordinate_epoch: float | None = None, axis_order: AxisOrder = "xy", densify: float | None = None, segments: Segments = "straight", antimeridian: Antimeridian | None = "split", orient: Orientation | None = None, srid_authority: str = "EPSG", ) -> GeometryResult: """Transform a geometry, read from any encoding geometry WKT to Esri JSON. Every position goes through :meth:`transform_arrays` in one call, so the operation, grids, epoch and range checks are those of points. A position that fails fails the whole geometry, naming its part and vertex. Z is transformed where the CRSs have a height, and carried through otherwise; M is carried through. None and empty geometries come back as they are. In a geographic target CRS, a part whose true path crosses the antimeridian is cut there, into parts of a multipart geometry, as RFC 7946 has it; a ring round a pole is closed through it. Args: value: The geometry: WKT, EWKT, WKB or EWKB as bytes or hex, a GeoJSON or Esri JSON geometry, or a Shapely geometry; see :func:`~geodetic_engine.geodesy.geometry.read_geometry`. coordinate_epoch: As for :meth:`transform`. axis_order: ``"xy"``, or ``"crs"`` when the geometry is in the source CRS's declared order, and is to be written in the target's. densify: Insert vertices first so that no segment is longer than this: a straight edge in one CRS is not straight in another. In source CRS units for straight segments, and in metres along the ellipsoid for geodesics. segments: What a segment is in the source CRS: ``"straight"``, as WKT, WKB, GeoJSON and Esri JSON have it, or ``"geodesic"``, the shortest line on the source CRS's ellipsoid, as boundaries are commonly defined. Geodesics need ``densify``. antimeridian: In a geographic target CRS, ``"split"`` cuts a part that crosses the antimeridian into parts there, ``"unwrap"`` carries its longitudes on past it instead, and None keeps it as transformed, a segment going the long way round. orient: None keeps the vertex order as transformed; ``"ccw"`` winds exterior rings counterclockwise (the RFC 7946 rule) and ``"cw"`` clockwise (Esri's). srid_authority: The authority an EWKT or EWKB SRID is a code of. Returns: The geometry in the target CRS with its provenance, written in any encoding by its ``wkt()``, ``wkb()``, ``ewkb_hex()``, ``geojson()`` and like methods, each rounding to ``decimals`` if asked. Raises: GeometryError: If the geometry cannot be read, or states a CRS other than :attr:`source_crs`; if geodesics are asked of a source CRS on no ellipsoid; or if a geometry with M values crosses the antimeridian, cutting which would lose them. ValueError: If its positions have a number of values the source CRS does not allow. TransformationFailedError: If a position cannot be transformed. Example: >>> tfm = Transformation("EPSG:4230", "EPSG:32631", operation="EPSG:1612") >>> tfm.transform_geometry("LINESTRING (2.5 63.5, 3 64)").wkt(decimals=1) 'LINESTRING (475017.6 7041354.6, 499910.8 7096974.1)' """ from geodetic_engine.geodesy import geometry return cast( "GeometryResult", geometry._transform( self, value, single=True, coordinate_epoch=coordinate_epoch, axis_order=axis_order, densify=densify, segments=segments, antimeridian=antimeridian, orient=orient, srid_authority=srid_authority, ), )
[docs] def transform_geometries( self, values: object, *, coordinate_epoch: float | None = None, axis_order: AxisOrder = "xy", densify: float | None = None, segments: Segments = "straight", antimeridian: Antimeridian | None = "split", orient: Orientation | None = None, srid_authority: str = "EPSG", ) -> GeometryResults: """Transform many geometries, with one call per number of values per position. As :meth:`transform_geometry`, for a sequence, a numpy array, a pandas Series or a GeoPandas GeoSeries, whose CRS must be :attr:`source_crs`. One failing position fails the batch, naming its geometry. Returns: The geometries in the target CRS, in the container they came in, with their provenance and encodings. Example: >>> tfm = Transformation("EPSG:4230", "EPSG:32631", operation="EPSG:1612") >>> tfm.transform_geometries(["POINT (2.5 63.5)", None]).wkt(decimals=0) ['POINT (475018 7041355)', None] """ from geodetic_engine.geodesy import geometry return cast( "GeometryResults", geometry._transform( self, values, single=False, coordinate_epoch=coordinate_epoch, axis_order=axis_order, densify=densify, segments=segments, antimeridian=antimeridian, orient=orient, srid_authority=srid_authority, ), )
def _transform_columns( self, columns: tuple[FloatArray, ...], coordinate_epoch: float | None, *, point_offset: int = 0, ) -> ArrayTransformationResult: if coordinate_epoch is not None and not math.isfinite(coordinate_epoch): raise MissingCoordinateEpochError("coordinate epoch must be finite") _require_in_range(self._source, columns, point_offset=point_offset) output, swapped = self._execute(columns, coordinate_epoch, errcheck=True) _require_finite(output, self._source, self._target, point_offset=point_offset) applied, grids = self._applied, self._grids pipeline_text = self._pipeline_text if swapped: pipeline_text = _report_horizontal_swap(pipeline_text) return ArrayTransformationResult( columns=output, source_crs=self._source, target_crs=self._target, operation=applied, grids=grids, coordinate_epoch=coordinate_epoch, pipeline=pipeline_text, database_fingerprints=self._database_fingerprints, ) def _transform_marking_failures( self, rows: ArrayLike, coordinate_epoch: float | None ) -> tuple[tuple[FloatArray, ...], NDArray[np.bool_]]: """Transform a row batch, marking the rows that fail instead of raising. For :mod:`geodetic_engine.geodesy._failures`, which finds every failing row in a pass over the batch rather than by transforming parts of it. A row that :meth:`transform_arrays` would refuse as out of range, or that PROJ gives no finite value for, is NaN in every column and True in the mask. The other rows have the values :meth:`transform_arrays` gives them. A failure that is no row's raises as it does there. Returns: One array per output axis, and True for each row that failed. """ if coordinate_epoch is not None and not math.isfinite(coordinate_epoch): raise MissingCoordinateEpochError("coordinate epoch must be finite") columns = _array_columns(self._source, rows, None, None) failed = _out_of_range(self._source, columns) output, _ = self._execute(columns, coordinate_epoch, errcheck=False) for column in output: failed |= ~np.isfinite(column) for column in output: column[failed] = np.nan return output, failed def _execute( self, columns: tuple[FloatArray, ...], coordinate_epoch: float | None, *, errcheck: bool, ) -> tuple[tuple[FloatArray, ...], bool]: """Run the pipeline over owned columns whose range has been seen to. Returns: The target CRS's columns, and whether the horizontal pair was transposed for the pipeline. """ # PROJ workaround, see the note above _entry_step: remove this call # once PROJ no longer leaves a residual axisswap at a vertical end. ordered, swapped = _order_horizontal_for_pipeline( self._source, self._pipeline, columns ) columns = _carry_unread_horizontal( self._source, self._target, self._applied, self._grids, ordered ) if self._requires_epoch and coordinate_epoch is None: raise MissingCoordinateEpochError( "a dynamic CRS or time-dependent operation requires a coordinate " "epoch; supply a finite observation year explicitly" ) try: produced = self._pipeline.run(columns, coordinate_epoch, errcheck=errcheck) except ProjError as error: raise TransformationFailedError( f"PROJ could not transform from {_label(self._source)} to " f"{_label(self._target)}: {error}" ) from error indices = _output_indices(self._target, len(produced)) return tuple(produced[index] for index in indices), swapped def __repr__(self) -> str: return ( f"Transformation({_label(self._source)} -> {_label(self._target)}, " f"operation={self._applied.authority_code or self._applied.name!r})" )
def _require_unmasked(values: object) -> None: pending = [values] visited: set[int] = set() while pending: value = pending.pop() if np.ma.isMaskedArray(value): raise TypeError("masked coordinates must be resolved before transformation") children: Iterable[object] if isinstance(value, np.ndarray): if not value.dtype.hasobject: continue children = value.flat elif isinstance(value, Sequence) and not isinstance(value, str | bytes): children = iter(value) else: continue if id(value) not in visited: visited.add(id(value)) pending.extend(children) def _numeric_array(values: ArrayLike) -> NDArray[np.generic]: # Coercion discards masks on nested arrays as well as top-level arrays. _require_unmasked(values) array = np.asarray(values) if np.iscomplexobj(array): raise TypeError("coordinate values must be real numbers") return array def _array_columns( crs: CoordinateReferenceSystem, x: ArrayLike, y: ArrayLike | None, z: ArrayLike | None, ) -> tuple[FloatArray, ...]: """Normalise a numeric batch into independent owned axis buffers.""" if y is None: if z is not None: raise TypeError( "z was given without y; pass x, y and z as separate " "per-axis values, or x alone as the whole set of points" ) rows = _numeric_array(x) if rows.ndim == 0: raise TypeError( "a single number is not a point; give every value of the " "point, for example (lon, lat), or pass x, y and z as " "separate per-axis values" ) if rows.ndim == 1: rows = rows.reshape(1, -1) if rows.size else rows.reshape(0, crs.dimension) if rows.ndim != 2: raise ValueError("points must be a flat point or a two-dimensional array") _require_width(crs, rows.shape[1]) return tuple( np.array(rows[:, axis], dtype=np.float64, order="C", copy=True) for axis in range(rows.shape[1]) ) axes = (x, y) if z is None else (x, y, z) _require_width(crs, len(axes)) arrays = tuple(_numeric_array(axis) for axis in axes) if any(axis.ndim > 1 for axis in arrays): raise ValueError("separate axes must be scalars or one-dimensional arrays") lengths = {len(axis) for axis in arrays if axis.ndim == 1} if len(lengths) > 1: raise ValueError(f"axes have differing batch sizes: {sorted(lengths)}") count = lengths.pop() if lengths else 1 return tuple( np.full(count, axis.item(), dtype=np.float64) if axis.ndim == 0 else np.array(axis, dtype=np.float64, order="C", copy=True) for axis in arrays ) def _columns( crs: CoordinateReferenceSystem, points: Iterable[Iterable[float]] | Iterable[float] ) -> tuple[tuple[float, ...], ...]: """Reshape points into one tuple of values per axis, the shape PROJ wants. Args: crs: The CRS the points are expressed in, whose declared axis count bounds how many values each point may carry. points: A single point's values, given flat -- ``(lon, lat)`` -- or a batch: an iterable of coordinate iterables, each holding one point's values in ``xy`` order. A 2D numpy array of shape ``(n_points, n_axes)`` works, one row per point. A row may carry one value more than ``crs`` declares -- a height alongside a 2D horizontal CRS -- which is carried through unchanged rather than consumed, matching how :meth:`pyproj.Transformer.transform` accepts an optional ``zz`` regardless of what the CRS pair declares. Returns: One tuple of values per axis, so a whole batch crosses into PROJ in a single call instead of once per point. Raises: ValueError: If points disagree on how many values they carry, or that count is not ``crs``'s declared dimension, or one more. """ # Materialised up front: points may be a one-shot iterable or a numpy array # (not a Sequence), and each axis is read once below. Whether an element is # a point or one value of a single flat point is only known at runtime. materialized: list[Any] = list(points) if materialized and not isinstance(materialized[0], Iterable): # A lone point given flat, e.g. (lon, lat), rather than [(lon, lat)]. # Unambiguous whenever a point has more than one value: only a single # flat point looks like a list of bare numbers rather than of rows. materialized = [materialized] rows = [tuple(float(value) for value in point) for point in materialized] widths = {len(row) for row in rows} if len(widths) > 1: raise ValueError(f"points have differing numbers of values: {sorted(widths)}") width = widths.pop() if widths else crs.dimension _require_width(crs, width) return tuple(tuple(row[axis] for row in rows) for axis in range(width)) def _columns_from_axes( crs: CoordinateReferenceSystem, x: Iterable[float] | float, y: Iterable[float] | float, z: Iterable[float] | float | None, ) -> tuple[tuple[float, ...], ...]: """Reshape separate per-axis values into columns, broadcasting a lone scalar. Mirrors :meth:`pyproj.Transformer.transform`'s ``xx, yy, zz`` convention: each axis is either the whole batch's values, or a lone scalar applied to every point -- a fixed height for many horizontal points, for example, given once rather than repeated per point. Args: crs: The CRS the points are expressed in, whose declared axis count bounds how many axes may be given. x: First axis's values: a scalar for one point, or a sequence (a list or a 1D numpy array) for a batch. y: Second axis's values, in the same shape as ``x``. z: Third axis's values, if any, in the same shape as ``x`` and ``y``. Returns: One tuple of values per axis, so a whole batch crosses into PROJ in a single call instead of once per point. Raises: ValueError: If the sequence axes disagree on how many points they hold, or the number of axes given is not ``crs``'s declared dimension, or one more. """ axes = (x, y) if z is None else (x, y, z) _require_width(crs, len(axes)) values: list[tuple[float, ...] | float] = [ tuple(float(value) for value in axis) if isinstance(axis, Iterable) else float(axis) for axis in axes ] lengths = {len(column) for column in values if isinstance(column, tuple)} if len(lengths) > 1: raise ValueError(f"axes have differing batch sizes: {sorted(lengths)}") count = lengths.pop() if lengths else 1 return tuple( column if isinstance(column, tuple) else (column,) * count for column in values ) def _require_width(crs: CoordinateReferenceSystem, width: int) -> None: """Check how many values a point carries against what ``crs`` allows. Raises: ValueError: If ``width`` is not ``crs``'s declared dimension or one more (a height alongside a 2D horizontal CRS, carried through unchanged); or, for a vertical CRS, anything other than a full ``(lon, lat, h)`` triple. """ if crs.dimension == 1 and _is_vertical(crs): # A height shifted by a geoid or vertical datum grid is only defined # where the grid is read, so the horizontal position that locates it # has to be given even though the CRS declares no axis for it. The # values go to PROJ in x, y, z order, so a lone height would be read # as a longitude rather than as a height. if width != _MAX_COORDINATE_VALUES: raise ValueError( f"{width} values were given per point but {crs!r} is a vertical " f"CRS; exactly {_MAX_COORDINATE_VALUES} are accepted, " "(lon, lat, h), because the height is only defined at the " "horizontal position its grid is read at" ) return allowed = {crs.dimension} if crs.dimension < _MAX_COORDINATE_VALUES: allowed.add(crs.dimension + 1) if width not in allowed: raise ValueError( f"{width} values were given per point but {crs!r} declares " f"{crs.dimension} axes; {sorted(allowed)} values are accepted " "(the extra being a height PROJ carries through unchanged)" )
[docs] def transform( source_crs: Any, target_crs: Any, x: Iterable[Iterable[float]] | Iterable[float] | float, y: Iterable[float] | float | None = None, z: Iterable[float] | float | None = None, *, operation: ( str | int | OperationReference | StatedOperation | CoordinateOperation | Sequence[ str | int | OperationReference | StatedOperation | CoordinateOperation ] | None ) = None, allow_any_operation: bool = False, coordinate_epoch: float | None = None, ) -> TransformationResult: """Transform points between two CRSs in one call. A thin front for :class:`Transformation` for the case where the transformation is used once. Resolved transformations are cached, so repeating the same call does not repeat the resolution. Prefer building a :class:`Transformation` directly when transforming many separate batches. Args: source_crs: CRS the input coordinates are in. target_crs: CRS to produce coordinates in. x: Either every point's values in one go -- a single point given flat such as ``(lon, lat)``, a list of tuples, or a 2D numpy array of shape ``(n_points, n_axes)`` -- when ``y`` is omitted; or just the first axis's values, matching :meth:`pyproj.Transformer.transform`'s ``xx, yy, zz`` convention, when ``y`` is given. y: Second axis's values: a scalar for one point, or a sequence for a batch. Omit to pass ``x`` as the whole set of points instead. z: Third axis's values (for example a height), in the same shape as ``x`` and ``y``. A lone scalar is broadcast against the other axes, so one height can be given once for many horizontal points rather than repeated. operation: EPSG coordinate operation to apply, for example ``"EPSG:15670"``, or an :class:`~geodetic_engine.geodesy.operation.OperationCandidate` from :func:`available_operations`. Or several, when a compound target CRS needs more than one pinned down -- order does not matter, see :class:`Transformation`. Or the operation itself, stated as an OSDU persistableReference payload, an ESRI ``GEOGTRAN``, a :class:`pyproj.crs.CoordinateOperation` or a parsed reference, which is then applied as given rather than looked up. Required whenever a datum change is involved, except where a bound CRS already names it. allow_any_operation: Compatibility keyword with no effect on strict datum-operation selection or ballpark refusal. coordinate_epoch: Decimal year the coordinates were observed at, required when the selected operation reads time. A dynamic CRS alone does not require an epoch. Returns: The transformed coordinates and their provenance. Raises: AmbiguousOperationError: If no operation was given, the transformation involves an unbound datum change. Example: >>> result = transform( ... "EPSG:4258", "EPSG:25832", (10.75, 59.91), ... operation="EPSG:16032", ... ) >>> result.operation.authority_code 'EPSG:16032' >>> result.target_axes ('E', 'N') Or as separate per-axis values: >>> result = transform( ... "EPSG:4258", "EPSG:25832", 10.75, 59.91, operation="EPSG:16032" ... ) >>> result.coordinates ((597868.38..., 6642681.51...),) """ references = () if operation is None else operation_references(operation) if any( isinstance(reference, (StatedOperation, CoordinateOperation)) for reference in references ): resolved = Transformation( source_crs, target_crs, references, allow_any_operation=allow_any_operation ) else: cacheable = tuple( reference for reference in references if not isinstance(reference, (StatedOperation, CoordinateOperation)) ) resolved = _cached_transformation( _cache_key(source_crs), _cache_key(target_crs), cacheable or None, allow_any_operation, database_identity(), ) return resolved.transform(x, y, z, coordinate_epoch=coordinate_epoch)
[docs] def available_operations( source_crs: Any, target_crs: Any, *, authority: str | None = "any", accuracy: float | None = None, allow_superseded: bool = True, allow_ballpark: bool = True, ) -> tuple[OperationCandidate, ...]: """List every coordinate operation PROJ offers between two CRSs. This package's equivalent of inspecting a :class:`pyproj.transformer.TransformerGroup` directly: every candidate is described, including a ballpark fallback or one whose grid is not installed, so an ``operation=`` argument for :class:`Transformation` can be chosen with full information instead of by trial and error. Nothing here is applied to coordinates or checked against a request. A deprecated EPSG operation is never among the candidates: PROJ's own operation search excludes deprecated operations unconditionally, with no option to include them, so there is no ``allow_deprecated`` filter here to match -- one would silently do nothing. Args: source_crs: CRS the input coordinates would be in. target_crs: CRS to produce coordinates in. authority: Restrict candidates to those published by this authority, for example ``"EPSG"``. ``"any"`` searches every authority without the preference PROJ otherwise gives the source/target CRS's own authority. Defaults to "any"; pass None to use PROJ's preference. accuracy: Discard candidates stated as less accurate than this, in metres. Omitted by default, so every accuracy is considered. allow_superseded: Whether to include an operation EPSG has marked as superseded by a newer one. True by default, since a superseded operation is still valid, just no longer preferred. allow_ballpark: Whether to include a ballpark approximation among the candidates. True by default, so its presence and its lack of a usable accuracy are visible here rather than only discovered when :class:`Transformation` refuses it. Returns: One candidate per operation PROJ offers, in the order PROJ ranks them, which weighs area of use and other criteria alongside accuracy: for ED50 to WGS 84 the first candidate is EPSG:1133 (10 m) ahead of EPSG:1612 (1 m). Filter on :attr:`~geodetic_engine.geodesy.operation.OperationCandidate.accuracy` or pass ``accuracy=`` rather than taking the first entry as the best. Pass any entry's :attr:`~geodetic_engine.geodesy.operation.OperationCandidate.authority_code` as ``Transformation``'s ``operation=`` argument. Example: >>> candidates = available_operations("EPSG:4230", "EPSG:4326") >>> candidates[0].authority_code 'EPSG:1133' >>> most_accurate = available_operations( ... "EPSG:4230", "EPSG:4326", accuracy=1.0, allow_ballpark=False ... ) >>> all(c.accuracy is not None and c.accuracy <= 1.0 for c in most_accurate) True """ source = CoordinateReferenceSystem.from_user_input(source_crs) target = CoordinateReferenceSystem.from_user_input(target_crs) with _proj_construction(source, target): group = TransformerGroup( source.crs, target.crs, always_xy=True, authority=authority, accuracy=accuracy, allow_ballpark=allow_ballpark, allow_superseded=allow_superseded, crs_extent_use="none", grid_check="none", ) return tuple(_describe_candidate(transformer) for transformer in group.transformers)
def _describe_candidate(transformer: Transformer) -> OperationCandidate: """Describe one candidate transformer without applying or requesting it.""" definition = transformer.to_json_dict() operations = tuple(transformer.operations or ()) if not operations: try: operations = (CoordinateOperation.from_json_dict(definition),) except CRSError: operations = () steps = _substantive_steps(operations) # The whole candidate's own id, which a registered concatenated operation # such as EPSG:8047 carries even though it applies two Helmerts. Absent # only when PROJ assembled the chain itself, and then no code may be # reported: borrowing a step's would understate the rest of the pipeline. identifier = _identifier(definition) or ( (steps[0].auth_name, steps[0].code) if len(steps) == 1 and steps[0].auth_name and steps[0].code else None ) area = transformer.area_of_use ballpark = is_ballpark(definition) grids = grid_usages(operations) return OperationCandidate( auth_name=None if identifier is None else identifier[0], code=None if identifier is None else identifier[1], name=_candidate_name(definition, steps, transformer), method_name=steps[0].method_name if len(steps) == 1 else None, accuracy=transformer.accuracy if transformer.accuracy >= 0 else None, area_of_use=( None if area is None else AreaOfUse( west=area.west, south=area.south, east=area.east, north=area.north, name=area.name, ) ), ballpark=ballpark, requires_epoch=requires_epoch(definition, operations), grids=grids, steps=steps, projjson=json.dumps(definition), usable=not ballpark and all(grid.available for grid in grids), ) def _candidate_name( definition: dict[str, Any], steps: tuple[OperationStep, ...], transformer: Transformer, ) -> str: """The candidate's name, without PROJ's axis-normalisation annotation. Normalising axis order makes PROJ append "(with axis order normalized for visualization)" to the name of the operation it wraps, which is wording the caller never asked to have on a result. A single step's own name is already clean; otherwise the annotation is stripped from the whole. """ if len(steps) == 1: return steps[0].name name = str(definition.get("name") or transformer.description) return name.removesuffix(_VISUALIZATION_SUFFIX) or " + ".join( step.name for step in steps ) def _substantive_steps( operations: tuple[CoordinateOperation, ...], ) -> tuple[OperationStep, ...]: """Every operation that does geodetic work, not the axis bookkeeping.""" return tuple( OperationStep( auth_name=None if identifier is None else identifier[0], code=None if identifier is None else identifier[1], name=str(node.get("name") or operation.name), method_name=(str(operation.method_name) if operation.method_name else None), ) for operation in operations if not _is_bookkeeping(operation) for node in (operation.to_json_dict(),) for identifier in (_identifier(node),) ) def _is_bookkeeping(operation: CoordinateOperation) -> bool: """Whether a step restates axes or units rather than moving coordinates.""" name = operation.method_name return bool(name) and name.strip().lower() in _BOOKKEEPING_METHODS def _cache_key(crs: Any) -> str: """Render a CRS input as a hashable definition string.""" return CoordinateReferenceSystem.from_user_input(crs).definition @lru_cache(maxsize=128) def _cached_transformation( source: str, target: str, operation: ( str | int | OperationReference | tuple[str | int | OperationReference, ...] | None ), allow_any_operation: bool, identity: DatabaseIdentity, ) -> Transformation: """Resolve and cache a transformation by its textual inputs.""" return Transformation( source, target, operation, allow_any_operation=allow_any_operation ) @contextmanager def _proj_construction( source: CoordinateReferenceSystem, target: CoordinateReferenceSystem ) -> Iterator[None]: """Report PROJ's refusal to build anything for a CRS pair as a package error. PROJ raises for pairs it has no notion of a path between at all, such as a vertical CRS to a geographic one. That is a real failure and is not hidden, but it reaches the caller as :class:`OperationNotAvailableError` naming both CRSs rather than as a bare ``ProjError`` from inside pyproj. pyproj's warning about the best ranked candidate is dropped here. Candidates are only being enumerated, most are discarded, and this package never takes PROJ's ranking silently: it applies the operation the caller named, or refuses the pair as ambiguous. What the chosen operation needs is reported by :attr:`Transformation.grids`, and a grid that is genuinely missing raises :class:`MissingGridError` naming it. """ try: with warnings.catch_warnings(): warnings.filterwarnings( "ignore", message="Best transformation is not available", category=UserWarning, ) yield except (ProjError, CRSError, IndexError) as error: raise OperationNotAvailableError( f"PROJ cannot build a transformation from {_label(source)} to " f"{_label(target)}: {error}" ) from error def _resolve( source: CoordinateReferenceSystem, target: CoordinateReferenceSystem, requests: tuple[OperationRequest, ...], *, allow_any_operation: bool, ) -> _Pipeline: """Build the pipeline that will be applied, recording how it was found.""" halves = _halves(source, target, multiple=len(requests) > 1) if not requests: if halves is not None and any(h.bound_op is not None for h in halves): composed = _from_parts( source, target, halves, (), route=OperationRoute.BOUND ) if composed is not None: return composed return _resolve_without_request( source, target, allow_any_operation=allow_any_operation ) stated = any(request.definition is not None for request in requests) compose_first = halves is not None and ( stated or not _heights_in_metres(halves) or any(h.bound_op is not None for h in halves) ) refusal: OperationNotAvailableError | None = None if halves is not None and compose_first: try: composed = _from_parts(source, target, halves, requests) except OperationNotAvailableError as error: composed, refusal = None, error if composed is not None: return composed if not stated: # Stated operations are never matched against PROJ's registry candidates. found = _from_transformer_group(source, target, requests) if found is not None: return _Pipeline( steps=((found, TransformDirection.FORWARD),), core=found, route=OperationRoute.TRANSFORMER_GROUP, ) if refusal is not None: raise refusal if halves is not None and not compose_first: composed = _from_parts(source, target, halves, requests) if composed is not None: return composed if len(requests) == 1: return _from_operation(source, target, requests[0]) if stated: raise OperationNotAvailableError( f"{_asked(requests)} for {_label(source)} to {_label(target)}, but " "an operation stated outright is applied on its own; it is " "combined with another only between CRSs that decompose into a " "horizontal part and a height" ) raise OperationNotAvailableError( f"{_asked(requests)} for {_label(source)} to {_label(target)}, but no " "candidate PROJ offers for this CRS pair applies all of them together, " "and they do not form a valid horizontal/vertical chain for the CRSs" ) def _asked(requests: Sequence[OperationRequest]) -> str: named = ", ".join(str(request) for request in requests) return f"{named} {'was' if len(requests) == 1 else 'were'} requested" def _halves( source: CoordinateReferenceSystem, target: CoordinateReferenceSystem, *, multiple: bool = False, ) -> tuple[_compose.CrsParts, _compose.CrsParts] | None: """Decompose ``source`` and ``target`` when H+V rad-frame composition applies.""" has_compound = source.crs.is_compound or target.crs.is_compound has_geocentric = "Geocentric CRS" in (source.crs.type_name, target.crs.type_name) if not (has_compound or (multiple and has_geocentric) or multiple): return None start, end = _compose.split(source), _compose.split(target) if start is None or end is None: return None # Plain 3D Geographic/Projected pairs with one op stay on PROJ/single path. if not has_compound and not has_geocentric and not multiple: return None return start, end def _heights_in_metres(halves: tuple[_compose.CrsParts, _compose.CrsParts]) -> bool: return all(half.height.metres == 1.0 and half.height.up for half in halves) def _from_parts( source: CoordinateReferenceSystem, target: CoordinateReferenceSystem, halves: tuple[_compose.CrsParts, _compose.CrsParts], requests: tuple[OperationRequest, ...], *, route: OperationRoute = OperationRoute.CHAINED, ) -> _Pipeline | None: """Plan and compile a single optimized rad-frame PROJ pipeline across H+V ops.""" # Caller requests are bidirectional and mandatory; source/target bindings are # optional and direction-constrained (source -> hub forward, hub -> target inverse) # so hub round trips through the same binding stay unambiguous. entries: list[tuple[OperationRequest, bool, bool | None]] = [ *((req, True, None) for req in requests), *( (half.bound_op, False, is_target) for is_target, half in ((False, halves[0]), (True, halves[1])) if half.bound_op is not None ), ] if not entries: return None bound_ops = tuple(req for req, required, _ in entries if not required) h_ops: list[_compose.HorizontalOp] = [] v_ops: list[_compose.VerticalOp] = [] cores: dict[int, Transformer] = {} for key, (request, required, allowed_direction) in enumerate(entries): if not required and request.definition is not None: # Defer compiling optional bindings (and their grid checks) until selected. ends = _definition_ends(request.definition) if ends is None: continue h_op = _compose.horizontal_operation( key, str(request), *ends, required=False, allowed_direction=allowed_direction, ) if h_op is not None: h_ops.append(h_op) continue try: core = _operation_transformer(request, source, target) except OperationNotAvailableError: if request.definition is not None and required: raise return None ends = _operation_ends(core) steps = _pipeline_steps(core.definition) if ends is None or steps is None: return None cores[key] = core h_op = _compose.horizontal_operation( key, str(request), *ends, required=required, allowed_direction=allowed_direction, ) if h_op is not None: h_ops.append(h_op) continue if not required: continue v_op = _compose.vertical_operation( key, str(request), *ends, core.to_json_dict(), steps ) if v_op is None: return None v_ops.append(v_op) error_requests = requests or tuple(bound_ops) try: plan = _compose.plan_chain(*halves, h_ops, v_ops) except _compose.AmbiguousOrder as error: raise OperationNotAvailableError( f"{_asked(error_requests)} for {_label(source)} to {_label(target)}, " f"but {error}" ) from error if plan is None: if not requests: return None raise OperationNotAvailableError( f"{_asked(requests)} for {_label(source)} to {_label(target)}, but " f"{_compose.gap(*halves, h_ops, v_ops)}" ) # Materialize selected optional bindings and promote 3D horizontal steps once so # emit_steps and AppliedOperation.parts share the exact same transformers. step_cores: dict[int, Transformer] = {} for planned in plan: key = planned.op.key step_core = cores.get(key) if step_core is None: step_core = _operation_transformer(entries[key][0], source, target) cores[key] = step_core if ( isinstance(planned, _compose.PlannedHorizontal) and planned.three_dimensional ): step_core = _in_three_dimensions(step_core) step_cores[key] = step_core try: steps = _compose.emit_steps( *halves, plan, core_of=step_cores.__getitem__, can_change_height=_changes_height_transformer, ) except (ProjError, ValueError) as error: raise OperationNotAvailableError( f"{_asked(error_requests)} for {_label(source)} to {_label(target)}, " f"but {error}" ) from error text = _pipeline_opt.format_pipeline(steps) try: compiled = Transformer.from_pipeline(text) except ProjError as error: raise OperationNotAvailableError( f"PROJ cannot run the composed pipeline for {_label(source)} to " f"{_label(target)}: {error}" ) from error if not plan: return _Pipeline( steps=((compiled, TransformDirection.FORWARD),), core=compiled, route=OperationRoute.PROJ_DEFAULT, compiled=compiled, pipeline_text=text, ) parts: list[_Part] = [] applied_bounds: list[OperationRequest] = [] seen_bound_texts: set[str] = set() for planned in plan: key = planned.op.key request, required, _ = entries[key] core = step_cores[key] direction = ( TransformDirection.INVERSE if planned.inverse else TransformDirection.FORWARD ) if required: part_requests: tuple[OperationRequest, ...] = (request,) part_route = route part_bounds: tuple[OperationRequest, ...] = () else: part_requests = () part_route = OperationRoute.BOUND part_bounds = (request,) if request.text not in seen_bound_texts: seen_bound_texts.add(request.text) applied_bounds.append(request) parts.append( _Part( part_requests, _Pipeline( steps=((core, direction),), core=core, route=part_route, identified_by=part_bounds, ), ) ) return _Pipeline( steps=((compiled, TransformDirection.FORWARD),), core=parts[0].pipeline.core, route=route, identified_by=tuple(applied_bounds), compiled=compiled, pipeline_text=text, parts=tuple(parts), ) def _definition_ends(operation: CoordinateOperation) -> tuple[CRS, CRS] | None: """The source and target CRSs declared in a stated operation's PROJJSON.""" node = operation.to_json_dict() src, tgt = _node_crs(node, "source_crs"), _node_crs(node, "target_crs") return None if src is None or tgt is None else (src, tgt) def _resolve_without_request( source: CoordinateReferenceSystem, target: CoordinateReferenceSystem, *, allow_any_operation: bool, ) -> _Pipeline: """Resolve conversions or bound operations, refusing unrequested datum shifts.""" mine, theirs = _datum.datums(source.crs), _datum.datums(target.crs) shared = _two_datums(mine, theirs) if shared or {one.name for one in mine} != {one.name for one in theirs}: bound = _from_bound_crs(source, target) if bound is not None: return bound conversion = _from_transformer_group(source, target, ()) if conversion is not None: return _Pipeline( steps=((conversion, TransformDirection.FORWARD),), core=conversion, route=OperationRoute.TRANSFORMER_GROUP, ) raise AmbiguousOperationError( f"{_label(source)} to {_label(target)} involves a datum change" f"{shared}; every datum operation must be named explicitly. " "allow_any_operation no longer " "permits automatic selection or ballpark results" ) with _proj_construction(source, target): transformer = Transformer.from_crs( source.crs, target.crs, always_xy=True, allow_ballpark=False ) return _Pipeline( steps=((transformer, TransformDirection.FORWARD),), core=transformer, route=OperationRoute.PROJ_DEFAULT, ) def _from_bound_crs( source: CoordinateReferenceSystem, target: CoordinateReferenceSystem ) -> _Pipeline | None: """Use the transformation a bound CRS states as its own definition. A bound CRS names exactly one transformation to its hub, so there is no choice left for PROJ to make and nothing for the caller to disambiguate. That is early binding, and it is the one datum change this package will apply without being told which operation to use: the operation was declared by whoever defined the CRS, not guessed here. The operation is read out of the bound CRS and then resolved through the same transformer group as a named one, rather than letting the bound CRS build the transformer by itself. A bound CRS with a projected base needs the map projection applied around the datum shift, and going through the group is what supplies those steps and keeps the applied operation identifiable. Returns: The pipeline, or None if neither CRS is bound, in which case the datum change really is ambiguous. """ requests = (*_bound_operations(source), *_bound_operations(target)) if not requests: return None found = _from_transformer_group(source, target, requests) if found is None: found = _bound_transformer(source, target, requests) if found is None: return None return _Pipeline( steps=((found, TransformDirection.FORWARD),), core=found, route=OperationRoute.BOUND, identified_by=requests, ) def _bound_transformer( source: CoordinateReferenceSystem, target: CoordinateReferenceSystem, requests: tuple[OperationRequest, ...], ) -> Transformer | None: """Chain the bound CRSs' own transformations without the candidate search. ``TransformerGroup`` withholds a candidate PROJ reports as not instantiable, and it judges that on the grid name the authority published rather than on the one it would actually read: the NADCON pair binding EPSG:1188 to EPSG:15851 is withheld over ``conus.las`` while PROJ builds it perfectly well from the installed ``us_noaa_conus.tif``. Early binding is then left with nothing to apply and the caller is told the datum change is ambiguous, when both CRSs had in fact declared their operation. Building the pair outright goes through the same early binding without that filter. Ballpark remains refused, and the result is accepted only once every declared operation is confirmed present in what PROJ built, so this cannot quietly substitute a different one. """ with _proj_construction(source, target): transformer = Transformer.from_crs( source.crs, target.crs, always_xy=True, allow_ballpark=False ) definition = transformer.to_json_dict() if all( request.is_satisfied_by(definition) for request in requests ) and fully_requested(definition, requests): return transformer return None def _bound_operations( crs: CoordinateReferenceSystem, ) -> tuple[OperationRequest, ...]: """The operation(s) a bound CRS or bound compound component embeds. A collapsed concatenated operation carries no identifier of its own, having been synthesised rather than published, so the name is the only handle on it. See :func:`~geodetic_engine.geodesy.utils.collapse_concatenated`. """ parts = crs.crs.sub_crs_list if crs.crs.is_compound else [crs.crs] found: list[OperationRequest] = [] for part in parts: if not part.is_bound: continue node = part.to_json_dict().get("transformation") if not isinstance(node, dict): continue identifier = node.get("id") if isinstance(identifier, dict): authority, code = identifier.get("authority"), identifier.get("code") if authority is not None and code is not None: found.append( OperationRequest.parse(f"{base_authority(str(authority))}:{code}") ) continue name = node.get("name") if name: found.append(OperationRequest.parse(str(name))) return tuple(found) def _from_transformer_group( source: CoordinateReferenceSystem, target: CoordinateReferenceSystem, requests: tuple[OperationRequest, ...], ) -> Transformer | None: """Find a candidate PROJ offers that satisfies every one of the requests. Extent filtering and grid filtering are both turned off, so that an operation is not hidden merely because its grid is missing. A missing grid is then reported as a missing grid rather than as a missing operation. """ with _proj_construction(source, target): group = TransformerGroup( source.crs, target.crs, always_xy=True, allow_ballpark=False, allow_superseded=True, crs_extent_use="none", grid_check="none", ) for transformer in group.transformers: definition = transformer.to_json_dict() authorized = ( *requests, *_bound_operations(source), *_bound_operations(target), ) if ( all(request.is_satisfied_by(definition) for request in requests) and fully_requested(definition, authorized) and _reads_positions_on_their_datum(definition, source.crs, target.crs) ): return transformer return None def _reads_positions_on_their_datum( definition: dict[str, Any], source: CRS, target: CRS ) -> bool: """Ensure every vertical step in a PROJ candidate reads positions on its datum.""" steps: list[tuple[dict[str, Any], CRS, CRS]] = [] for node in operation_nodes(definition): if node.get("type") not in ("Transformation", "PointMotionOperation"): continue start, end = _node_crs(node, "source_crs"), _node_crs(node, "target_crs") if start is not None and end is not None: steps.append((node, start, end)) if not any(_datum.has_vertical(crs) for _, *ends in steps for crs in ends): return True position = _datum.position_datum(source) for node, start, end in steps: entry, exit_ = _datum.position_datum(start), _datum.position_datum(end) if _datum.has_vertical(start) or _datum.has_vertical(end): stated = _node_crs(node, "interpolation_crs") reads = ( (None if stated is None else _datum.position_datum(stated)) or entry or exit_ ) if reads is not None: if position is None: position = reads elif not position.same_as(reads): return False if entry is not None and exit_ is not None and not entry.same_as(exit_): position = exit_ wanted = _datum.position_datum(target) return position is None or wanted is None or position.same_as(wanted) def _grids_of(request: OperationRequest) -> tuple[GridUsage, ...]: """Grids the requested operation declares, read from the registry. The registry answers even when the operation cannot be built, which is what makes it usable for explaining that failure. Args: request: The operation the caller asked for. Returns: Its grids, or empty when the request names no authority code or the registry does not know it. """ if request.auth_name is None or request.code is None: return () try: operation = CoordinateOperation.from_authority(request.auth_name, request.code) except (CRSError, ProjError): return () return grid_usages((operation,)) def _from_operation( source: CoordinateReferenceSystem, target: CoordinateReferenceSystem, request: OperationRequest, ) -> _Pipeline: """Build the named operation itself, wrapping it in same-datum conversions.""" core = _operation_transformer(request, source, target) ends = _operation_ends(core) if ends is None: raise OperationNotAvailableError( f"{request} does not declare the CRSs it operates between, so it " f"cannot be chained into {_label(source)} to {_label(target)}" ) if all(_above_ellipsoid(crs.crs) for crs in (source, target)) and all( end.type_name == "Geographic 2D CRS" for end in ends ): core = _in_three_dimensions(core) ends = _operation_ends(core) or ends op_source, op_target = ends direction = _direction_from(source.crs, op_source, op_target) if direction is None: raise OperationNotAvailableError( f"{request} operates between {op_source.name!r} and " f"{op_target.name!r}, neither of which shares a datum with " f"{_label(source)}; it cannot be applied here" ) entry, exit_ = ( (op_source, op_target) if direction is TransformDirection.FORWARD else (op_target, op_source) ) steps: list[tuple[Transformer, TransformDirection]] = [] if _datum_names(source.crs) != _datum_names(entry) or source.crs != entry: steps.append( ( _conversion(source.crs, entry, request, published=entry), TransformDirection.FORWARD, ) ) steps.append((core, direction)) if _datum_names(target.crs) != _datum_names(exit_) or target.crs != exit_: steps.append( ( _conversion(exit_, target.crs, request, published=exit_), TransformDirection.FORWARD, ) ) return _Pipeline(steps=tuple(steps), core=core, route=OperationRoute.CHAINED) def _operation_transformer( request: OperationRequest, source: CoordinateReferenceSystem, target: CoordinateReferenceSystem, ) -> Transformer: """Build the requested operation by itself between its published CRSs.""" if request.definition is not None: return _stated_transformer(request, source, target) try: return Transformer.from_pipeline(request.urn or request.text, always_xy=True) except (ProjError, CRSError) as error: _require_grids(_grids_of(request), source, target) raise OperationNotAvailableError( f"{request} could not be built as a coordinate operation, and is " f"not among the operations PROJ offers for {_label(source)} to " f"{_label(target)}: {error}" ) from error def _above_ellipsoid(crs: CRS) -> bool: return ( crs.type_name in ("Geographic 3D CRS", "Projected CRS", "Geocentric CRS") and len(crs.axis_info) == _MAX_COORDINATE_VALUES ) def _in_three_dimensions(core: Transformer) -> Transformer: """Promote an operation between geographic 2D CRSs to their 3D forms.""" definition = core.to_json_dict() if has_inverted_step(definition): return core restated = False for node in operation_nodes(definition): for end in ("source_crs", "target_crs"): stated = node.get(end) if not isinstance(stated, dict): continue try: crs = CRS.from_json_dict(stated) except CRSError: return core if crs.type_name == "Geographic 2D CRS": node[end] = crs.to_3d().to_json_dict() restated = True if not restated: return core try: return Transformer.from_pipeline(json.dumps(definition), always_xy=True) except (ProjError, CRSError): return core def _changes_height_transformer(core: Transformer) -> bool: ends = _operation_ends(core) return ends is not None and all( len(end.axis_info) == _MAX_COORDINATE_VALUES for end in ends ) def _direction_from( crs: CRS, op_source: CRS, op_target: CRS ) -> TransformDirection | None: """Direction an operation runs from ``crs``, preferring exact datum match.""" mine = _datum.datums(crs, vertical_ensembles=True) ends = ( (TransformDirection.FORWARD, _datum.datums(op_source, vertical_ensembles=True)), (TransformDirection.INVERSE, _datum.datums(op_target, vertical_ensembles=True)), ) for direction, theirs in ends: if any(other.equals(one) for one in mine for other in theirs): return direction for direction, theirs in ends: if any(other.within(one) for one in mine for other in theirs): return direction return None def _stated_transformer( request: OperationRequest, source: CoordinateReferenceSystem, target: CoordinateReferenceSystem, ) -> Transformer: """Run the operation a caller stated, rather than one PROJ looked up. The definition is handed over whole, so a chain stays a chain: nothing has to be collapsed into a single step the way a bound CRS would require. Raises: MissingGridError: If PROJ cannot build the operation because a grid it reads is not installed. PROJ reports that as a malformed pipeline step, which would otherwise send the caller looking for another operation instead of for the grid. OperationNotAvailableError: If PROJ cannot build it for any other reason. """ definition = request.definition if definition is None: raise ValueError(f"{request} states no operation to run") if has_inverted_step(definition.to_json_dict()): # PROJJSON writes an inverted step with its forward parameters. raise OperationNotAvailableError( f"{request} states an operation with a step applied inverted, which " "PROJ would run forwards once handed over; state that step in the " "direction it is applied" ) try: return Transformer.from_pipeline(definition.to_json(), always_xy=True) except (ProjError, CRSError) as error: if _MISSING_FILE_MARKER in str(error): _require_grids(grid_usages((definition,)), source, target) raise OperationNotAvailableError( f"{request} states an operation PROJ cannot run: {error}" ) from error def _conversion( source: CRS, target: CRS, request: OperationRequest, *, published: CRS ) -> Transformer: """Build a step that changes representation without changing datum. Allows an operation published on a realisation to attach to a CRS on its datum ensemble by restating the operation end on the ensemble. """ if _datum_names(source) != _datum_names(target): callers = target if published is source else source restated = _datum.on_datum_of(published, callers) if restated is None: raise OperationNotAvailableError( f"applying {request} between {source.name!r} and " f"{target.name!r} would require an additional, unrequested " "datum change; name the full operation instead" ) source, target = ( (restated, target) if published is source else (source, restated) ) elif shared := _two_datums(_datum.datums(source), _datum.datums(target)): raise OperationNotAvailableError( f"applying {request} between {source.name!r} and {target.name!r} " f"would require an additional, unrequested datum change{shared}" ) return Transformer.from_crs(source, target, always_xy=True, allow_ballpark=False) def _two_datums(first: Sequence[_datum.Datum], second: Sequence[_datum.Datum]) -> str: shared = _datum.namesakes(first, second) if not shared: return "" return ( f": they state {' and '.join(map(repr, shared))} on two ellipsoids, or " "with two prime meridians, which makes it two datums" ) def _operation_ends(transformer: Transformer) -> tuple[CRS, CRS] | None: """The CRSs an operation is defined between, as full CRS objects.""" source = transformer.source_crs target = transformer.target_crs if source is None or target is None: return None return CRS.from_wkt(source.to_wkt()), CRS.from_wkt(target.to_wkt()) def _datum_names(crs: CRS) -> frozenset[str]: """Names of every datum the CRS is built on, including compound components.""" return frozenset(datum.name for datum in _datum.datums(crs)) def _mandatory_pipeline_grids(pipeline: _Pipeline) -> set[str]: """Grid files the compiled pipeline must read, under PROJ's own filenames. A name prefixed with ``@`` is one PROJ will run without, so it proves nothing about what is installed and is not returned here. """ found: set[str] = set() for token in (pipeline.text or "").split(): if not token.startswith("grids="): continue found.update( name for name in token.removeprefix("grids=").split(",") if name and not name.startswith("@") ) return found def _confirm_installed( grids: tuple[GridUsage, ...], pipeline: _Pipeline ) -> tuple[GridUsage, ...]: """Correct the registry's account of what is installed with the pipeline's. The registry names the grid the authority published; PROJ substitutes its own distribution of it through proj.db's ``grid_alternatives``. EPSG:15851 cites ``conus.las`` and ``conus.los``, neither of which PROJ ships any more: it reads the installed ``us_noaa_conus.tif`` instead, while the registry still reports the published names as missing. Believing the registry there refuses a transformation that demonstrably runs, which is the same failure in the opposite direction to the one :func:`_require_grids` exists to prevent. The compiled pipeline is the complete statement of what will be read, so it is the pipeline's files that are checked, and checked on disk: PROJ keeps opened grids in memory, and a pipeline compiled while a file was present still compiles once the file is gone, only to fail at the first coordinate. A registry grid reported missing is taken as satisfied only when every file the pipeline must read is installed; a file the pipeline must read and that is not installed is reported missing under PROJ's own name, whatever the registry said. With PROJ's network access enabled a file can be fetched on demand, so its absence proves nothing and the pipeline is trusted as compiled. Args: grids: What the registry says the applied operations depend on. pipeline: The pipeline that was compiled from them. Returns: The same grids, with availability corrected from the pipeline and the disk, plus one entry per file the pipeline reads that the registry did not name and that is not installed. """ reads = _mandatory_pipeline_grids(pipeline) if not reads: return grids if is_network_enabled(): # A grid PROJ substituted may be fetched on demand, so its absence # proves nothing; a name the registry calls missing and the pipeline # reads unchanged still says nothing new. return tuple( grid if grid.available or grid.name in reads else replace(grid, available=True) for grid in grids ) absent = sorted(name for name in reads if not _installed_grid(name)) if not absent: return tuple(replace(grid, available=True) for grid in grids) # The pipeline is the complete list of what will be read: a registry name # it does not read is satisfied, and only its own absent files are missing. named = {grid.name for grid in grids} return ( *(replace(grid, available=grid.name not in absent) for grid in grids), *( GridUsage( name=name, full_name="", package_name="", url="", available=False, open_license=False, direct_download=False, ) for name in absent if name not in named ), ) def _installed_grid(name: str) -> bool: """Whether PROJ will find a grid file on disk under the name it uses. Searched where PROJ searches: the data directories on its search path, in order, and the user-writable directory that ``projsync`` and PROJ's own network cache write to. """ path = Path(name) if path.is_absolute(): return path.is_file() return any((Path(directory) / name).is_file() for directory in _grid_directories()) def _grid_directories() -> tuple[str, ...]: """PROJ's grid search path, first match winning, without duplicates.""" found: list[str] = [] for entry in ( *datadir.get_data_dir().split(os.pathsep), *os.environ.get("PROJ_DATA", "").split(os.pathsep), *os.environ.get("PROJ_LIB", "").split(os.pathsep), datadir.get_user_data_dir(), ): if entry and entry not in found: found.append(entry) return tuple(found) def _constituent_operations( pipeline: _Pipeline, definition: dict[str, Any] ) -> tuple[CoordinateOperation, ...]: """Every operation being applied, so their grids can be inspected. Read from what PROJ built, never from the EPSG registry. The registry names the grid the authority published, while PROJ substitutes its own distribution of it: EPSG:3858 cites ``Und_min2.5x2.5_egm2008_isw=82_WGS84_TideFree``, which is not installed, where PROJ actually reads ``us_nga_egm08_25.tif``, which is. Asking the registry would report a missing grid for a transformation that works. """ found: list[CoordinateOperation] = [] for transformer, _ in pipeline.steps: found.extend(transformer.operations or ()) try: found.append(CoordinateOperation.from_json_dict(transformer.to_json_dict())) except (CRSError, TypeError, ProjError): continue return tuple(found) def _require_grids( grids: tuple[GridUsage, ...], source: CoordinateReferenceSystem, target: CoordinateReferenceSystem, ) -> None: """Refuse to transform when a grid the operation depends on is absent.""" missing = [grid for grid in grids if not grid.available] if not missing: return described = ", ".join( f"{grid.name}" + (f" (from {grid.package_name})" if grid.package_name else "") + (f" at {grid.url}" if grid.url else "") for grid in missing ) raise MissingGridError( f"transforming {_label(source)} to {_label(target)} needs " f"{len(missing)} grid file(s) that are not installed: {described}" ) def _examine( requests: tuple[OperationRequest, ...], pipeline: _Pipeline, source: CoordinateReferenceSystem, target: CoordinateReferenceSystem, ) -> tuple[AppliedOperation, tuple[CoordinateOperation, ...]]: """Validate a resolved pipeline against the rules and describe what it applies.""" definition = pipeline.definition unsatisfied = [r for r in requests if not r.is_satisfied_by(definition)] if unsatisfied: raise OperationNotAvailableError( f"{_asked(unsatisfied)} for {_label(source)} to {_label(target)}, " f"but PROJ built {_applied_label(definition)} instead; " "refusing to substitute a different operation" ) if is_ballpark(definition) or ( pipeline.core.description.lower().startswith("ballpark") ): raise BallparkTransformationError( f"the only path from {_label(source)} to " f"{_label(target)} is a ballpark approximation " f"({pipeline.core.description!r}), which carries no usable " "accuracy; no result can be given" ) operations = _constituent_operations(pipeline, definition) applied = _describe( requests, pipeline, definition, operations, ballpark=False, requires_epoch=requires_epoch(definition, operations, pipeline.text), ) return applied, operations def _describe_chain( requests: tuple[OperationRequest, ...], pipeline: _Pipeline, parts: Sequence[AppliedOperation], ) -> AppliedOperation: """Summarize a multi-operation composed chain and its individual parts.""" requested = " + ".join(r.text for r in requests) if requests else None bound_ops = tuple(r.text for r in pipeline.identified_by) if len(parts) == 1: return replace( parts[0], requested=requested, route=pipeline.route, bound_operations=bound_ops, ) accuracies = [part.accuracy for part in parts] known = [a for a in accuracies if a is not None] return AppliedOperation( requested=requested, auth_name=None, code=None, name=" + ".join(part.name for part in parts), method_name=None, accuracy=round(sum(known), 9) if len(known) == len(accuracies) else None, route=pipeline.route, requires_epoch=any(part.requires_epoch for part in parts), steps=tuple(part.name for part in parts), bound_operations=bound_ops, axis_order_corrected=any(part.axis_order_corrected for part in parts), parts=tuple(parts), ) def _transformer_group_parts( definition: dict[str, Any], requests: tuple[OperationRequest, ...], source: CoordinateReferenceSystem, target: CoordinateReferenceSystem, ) -> tuple[AppliedOperation, ...]: """Populate per-operation metadata for a multi-op TransformerGroup candidate.""" matched = matched_request_directions(definition, requests) if len(matched) < 2: return () described: list[AppliedOperation] = [] for req, direction in matched: try: core = _operation_transformer(req, source, target) part_pipe = _Pipeline( steps=((core, direction),), core=core, route=OperationRoute.TRANSFORMER_GROUP, ) part_applied, _ = _examine((req,), part_pipe, source, target) except OperationNotAvailableError: return () described.append(part_applied) return tuple(described) def _describe( requests: tuple[OperationRequest, ...], pipeline: _Pipeline, definition: dict[str, Any], operations: tuple[CoordinateOperation, ...], *, ballpark: bool, requires_epoch: bool = False, ) -> AppliedOperation: """Record which operation was applied, against what was asked for. Provenance comes from the requested operation's own node in the tree when exactly one was named, or from the operation a bound CRS names for itself. When more than one was named, no single node represents "the" operation -- the whole applied step does, since that is what actually fused them -- so the top-level definition is reported as-is. Otherwise it comes from the substantive step: normalising axis order renames the top-level operation, appending "(with axis order normalized for visualization)" to its name, so using it directly would leak that wording into a result the caller never asked to have annotated. Narrowing to one node is refused outright when the caller named nothing, the pipeline applies more than one datum transformation, and no authority publishes the whole of it. That is what a bound CRS on each side of the pair produces: each names its own shift to the hub, so the identification one of them supplies would understate the result by the other. Both are then reported as :attr:`AppliedOperation.bound_operations` instead, since a chain of two identified operations has no single code but is not unidentified either. A registered concatenated operation such as EPSG:8047 is unaffected, since the identifier is then on the top-level node, and so is an operation the caller named, which is reported as asked for. """ node = definition unnamed_chain = ( not requests and datum_operation_count(definition) > 1 and _identifier(definition) is None ) identifier_of = ( requests[0] if len(requests) == 1 else pipeline.identified_by[0] if len(pipeline.identified_by) == 1 else None ) if not unnamed_chain: if identifier_of is not None: matched = identifier_of.find_in(definition) if matched is not None: node = matched elif not requests: substantive = _substantive_operation(operations) if substantive is not None: node = substantive.to_json_dict() identifier = _identifier(node) steps = tuple( name for name in operation_names(definition) if name != definition.get("name") ) method = node.get("method") name = str(node.get("name") or pipeline.core.description).removesuffix( _VISUALIZATION_SUFFIX ) if pipeline.core_direction is TransformDirection.INVERSE: name = f"Inverse of {name}" return AppliedOperation( requested=None if not requests else " + ".join(r.text for r in requests), auth_name=None if identifier is None else identifier[0], code=None if identifier is None else identifier[1], name=name, method_name=( None if unnamed_chain else str(method["name"]) if isinstance(method, dict) and "name" in method else _substantive_method(operations) ), accuracy=pipeline.accuracy, route=pipeline.route, ballpark=ballpark, requires_epoch=requires_epoch, steps=tuple(sorted(steps)), projjson=json.dumps(node), execution_direction=pipeline.core_direction, bound_operations=tuple(r.text for r in pipeline.identified_by), axis_order_corrected=pipeline.corrected is not None, ) def _substantive_operation( operations: tuple[CoordinateOperation, ...], ) -> CoordinateOperation | None: """The operation that does the geodetic work, not the axis bookkeeping. Normalising axis order makes PROJ prepend an axis-reversal conversion, so the first step of a concatenated operation is often bookkeeping rather than the transformation the caller cares about. """ for operation in operations: if not _is_bookkeeping(operation): return operation return None def _substantive_method(operations: tuple[CoordinateOperation, ...]) -> str | None: """Name of the method applied, or None when more than one operation is chained. A chain has no single method, and naming the first one would understate what the other steps do. """ substantive = [ operation for operation in operations if not _is_bookkeeping(operation) ] if len(substantive) != 1 or not substantive[0].method_name: return None return str(substantive[0].method_name) def _identifier(definition: dict[str, Any]) -> tuple[str, str] | None: """The authority code of the operation as a whole, if it has one.""" identity = definition.get("id") if isinstance(identity, dict): authority = identity.get("authority") code = identity.get("code") if authority is not None and code is not None: return base_authority(str(authority)), str(code) return None def _apply( transformer: Transformer, values: tuple[FloatArray, ...], times: FloatArray | None, direction: TransformDirection, *, errcheck: bool = True, ) -> tuple[FloatArray, ...]: """Run one transformer over every coordinate component at once.""" count = len(values[0]) if values else 0 arguments: dict[str, Any] = { "xx": values[0], "yy": values[1] if len(values) > 1 else np.zeros(count), } if len(values) > 2: arguments["zz"] = values[2] if times is not None: arguments["tt"] = times produced = transformer.transform( **arguments, direction=direction, errcheck=errcheck, inplace=True ) return tuple(produced[: len(values)]) def _compile_pipeline(pipeline: _Pipeline) -> _Pipeline: """Compile a multi-step chain into a single peephole-optimized PROJ Transformer.""" if pipeline.compiled is not None or len(pipeline.executed) <= 1: return pipeline steps = _composed_steps(pipeline.executed) if steps is None: return pipeline optimized = _pipeline_opt.optimize_steps(steps) text = _pipeline_opt.format_pipeline(optimized) try: compiled = Transformer.from_pipeline(text) except (ProjError, CRSError): return pipeline return replace(pipeline, compiled=compiled, pipeline_text=text) def _compose_pipeline( steps: Sequence[tuple[Transformer, TransformDirection]], ) -> str | None: """Write a sequence of transformers out as one runnable PROJ pipeline.""" composed = _composed_steps(steps) if composed is None: return None return _pipeline_opt.format_pipeline(composed) def _composed_steps( steps: Sequence[tuple[Transformer, TransformDirection]], ) -> list[str] | None: """Flatten a sequence of transformers into PROJ step strings in execution order.""" composed: list[str] = [] for transformer, direction in steps: flattened = _pipeline_steps(transformer.definition) if flattened is None: return None if direction is TransformDirection.INVERSE: flattened = [_inverted_step(step) for step in reversed(flattened)] composed.extend(flattened) return composed def _pipeline_steps(definition: str) -> list[str] | None: """Split one PROJ definition into its steps, without the ``step`` keywords.""" return _pipeline_opt.parse_steps(definition) def _inverted_step(step: str) -> str: """The same PROJ step run backwards.""" return _pipeline_opt.invert_step(step) def _output_indices( target: CoordinateReferenceSystem, produced: int ) -> tuple[int, ...]: """Map PROJ's output components onto the axes the target CRS declares. PROJ returns as many components as it was given. The target CRS decides how many of them are coordinates in that CRS: a vertical CRS declares one axis and its value is the height component, not the first one. A source height supplied alongside a horizontal-only pair is one component more than the target declares; it is passed through rather than dropped, since the caller gave it deliberately and PROJ already carried it through unchanged. """ if target.dimension == 1 and _is_vertical(target): if produced < 3: raise TransformationFailedError( f"{_label(target)} declares a height axis, but only {produced} " "coordinate components were supplied; give the source height too" ) return (2,) if target.dimension > produced: raise TransformationFailedError( f"{_label(target)} declares {target.dimension} axes but only " f"{produced} coordinate components were produced; supply " f"{target.dimension} values per point" ) if produced - target.dimension > 1: raise TransformationFailedError( f"{_label(target)} declares {target.dimension} axes but {produced} " "coordinate components were produced; at most one extra " "(a pass-through height) is carried through" ) return tuple(range(produced)) def _is_vertical(crs: CoordinateReferenceSystem) -> bool: """Whether the CRS's single axis is a height or a depth.""" return crs.axes[0].direction.lower() in _VERTICAL_DIRECTIONS # --------------------------------------------------------------------------- # PROJ workaround, not permanent design. ``always_xy`` is supposed to # guarantee lon/lat, E/N in and out; it does not for a pipeline with a vertical # (or otherwise horizontal-axis-less) end, because there is no declared order # there for PROJ to normalise against, and the operation's own residual # ``axisswap`` survives. ``_entry_step``, ``_swaps_horizontal``, # ``reads_declared_horizontal`` and ``_order_horizontal_for_pipeline`` exist # only to detect and undo that residual swap on the way in. # # Once PROJ strips the residual axisswap itself, # ``Transformation.transform`` no longer needs to call # ``_order_horizontal_for_pipeline`` at all, and this whole block -- # including ``reads_declared_horizontal`` and its call site -- can be deleted # outright rather than adapted: nothing else in this module depends on it. # --------------------------------------------------------------------------- def _entry_step(definition: str, direction: TransformDirection) -> str: """The step a PROJ pipeline applies first when run in ``direction``. An inverted pipeline runs its steps back to front, so its entry step is the last one written. ``axisswap`` is its own inverse, so the step reads the same either way. """ steps = definition.split(" step ") if len(steps) == 1: return definition return steps[1] if direction is TransformDirection.FORWARD else steps[-1] def _swaps_horizontal(step: str) -> bool: """Whether a PROJ step exchanges the first two coordinate components.""" return _horizontal_order(step) == ["2", "1"] def _passes_horizontal(step: str) -> bool: """Whether a PROJ step hands the first two components on unchanged.""" tokens = step.split() if "proj=noop" in tokens: return True if "proj=unitconvert" in tokens: return not any(token.startswith(("xy_in=", "xy_out=")) for token in tokens) return _horizontal_order(step) == ["1", "2"] def _horizontal_order(step: str) -> list[str] | None: if "proj=axisswap" not in step: return None for token in step.split(): if token.startswith("order="): return token.removeprefix("order=").split(",")[:2] return None def _order_horizontal_for_pipeline( source: CoordinateReferenceSystem, pipeline: _Pipeline, columns: tuple[FloatArray, ...], ) -> tuple[tuple[FloatArray, ...], bool]: """Hand a vertical CRS's position to PROJ in the order the pipeline reads it. Coordinate values reach this package in ``xy`` order, and PROJ's ``always_xy`` normally guarantees PROJ reads them that way. It cannot for a vertical source: with no horizontal axes to normalise, the pipeline keeps the ``axisswap`` belonging to the operation's own geographic end and reads the accompanying position latitude-first. Left uncorrected the grid is interpolated at the transposed point, which is a wrong height wherever the transposed point is still inside the grid. Args: source: Source CRS. pipeline: The pipeline the values are about to be run through. columns: One owned array per axis, in ``xy`` order. Returns: The columns with the horizontal pair transposed when the pipeline reads it northing-first, and unchanged otherwise, and whether it transposed them. The caller reports the transposition as a step of the pipeline, so it needs to be told rather than left to compare tuples. """ if len(columns) != _MAX_COORDINATE_VALUES: return columns, False if not (source.dimension == 1 and _is_vertical(source)): return columns, False if not pipeline.reads_declared_horizontal: return columns, False return (columns[1], columns[0], columns[2]), True def _report_horizontal_swap(pipeline: str | None) -> str | None: """Write the transposition above into the pipeline that gets reported. The reordering happens in Python, before PROJ is handed the values, so a pipeline rebuilt from the reported text alone would read the caller's ``xy`` values transposed and interpolate the grid at the wrong point. Stating it as the ``axisswap`` step it is keeps the reported pipeline reproducing the result from the values the caller actually gave. """ if pipeline is None: return None body = pipeline.removeprefix("proj=pipeline ") if body == pipeline: body = f"step {pipeline}" return f"proj=pipeline step proj=axisswap order=2,1 {body}" # --------------------------------------------------------------------------- # PROJ/EPSG workaround, not permanent design. Two things go wrong at an # engineering CRS, and both transpose coordinates without any error: # # 1. ``always_xy`` never normalises an engineering CRS. PROJ's # ``mustAxisOrderBeSwitchedForVisualization`` considers geographic, # projected and derived projected CRSs only, so a plant grid declared # (northing, easting) is read and written in that order while every other # end of the pipeline is east-first. This package promises ``xy`` wherever # a CRS has an easting and a northing, so the ``axisswap`` PROJ omits is # added here. Cartesian Grid Offsets (EPSG:9656) is the exception: PROJ # renders it as an east-first ``affine`` and adapts projected ends around # it but leaves engineering ends alone, so at such an end the values PROJ # consumes already are ``xy``. A grid with no east/north pair at all # (EPSG:5800 declares north and west) is left in declared order, which is # what ``value_axis_order`` reports for it and what PROJ does with the # corresponding projected case (Krovak's south and west). # # 2. PROJ reads the "Ordinate 1/2 of evaluation point in target CRS" of a # Similarity transformation (EPSG:9621), and A0/B0 of an Affine parametric # transformation (EPSG:9624), as the target CRS's first and second declared # axes, then appends an ``axisswap`` to normalise a northing-first target. # EPSG's own data does not follow that reading: EPSG:1035 states the Astra # Minas grid origin as (2610200.48, 4905282.73) in EPSG:22192, which is # declared (northing, easting) -- read that way the origin lies in # Antarctica, read as (easting, northing) it lies at Comodoro Rivadavia, # the operation's area of use. Registers of plant grids are authored both # ways. So the convention is established from the data: the evaluation # point is unprojected under both readings and the one that falls inside # the area of use wins. When the ordinates turn out east-first, PROJ's # appended ``axisswap`` transposes a result that was already ``xy`` and is # removed. When neither or both readings are plausible the operation is # refused rather than guessed at. An evaluation point stated in an # engineering CRS cannot be unprojected, so PROJ's declared-order reading # is kept there. # # Retire part 1 when PROJ normalises engineering CRSs under always_xy; the # canary is tests/geodesy/test_engineering_axes.py:: # test_proj_still_leaves_engineering_axes_alone, which fails the day it does. # Retire part 2 when EPSG and PROJ agree on which axis each ordinate of # methods 9621/9624 refers to. The corrected core is rebuilt from its text # and reported as TransformationResult.pipeline, so replaying that pipeline # reproduces the result from the caller's own ``xy`` values. # --------------------------------------------------------------------------- _AXIS_SWAP_STEP = "proj=axisswap order=2,1" _AFFINE_STEP = "proj=affine" _INVERSE_METHOD_PREFIX = "inverse of " _EVALUATION_POINT_METHODS = frozenset( {"similarity transformation", "affine parametric transformation"} ) _GRID_OFFSETS_METHOD = "cartesian grid offsets" # Slack around an area of use when placing an evaluation point, in degrees. # Extents are quoted coarsely; the two readings differ by thousands of # kilometres, so this only has to absorb a sloppy bounding box. _AREA_MARGIN_DEGREES = 1.0 def _correct_engineering_axes(pipeline: _Pipeline) -> _Pipeline: """Rewrite the core so that its engineering ends honour the ``xy`` contract. See the block comment above for what is corrected and why. Returns: The pipeline unchanged when no engineering CRS and no northing-first evaluation point is involved, otherwise with ``corrected`` set to the steps to execute. Raises: OperationNotAvailableError: If the operation is a Similarity or Affine parametric transformation whose evaluation point is stated in a northing-first projected CRS and cannot be placed inside the area of use under exactly one reading of its ordinates, or if PROJ built it in a shape this correction does not recognise. """ nodes = _substantive_nodes(pipeline.definition) steps = _pipeline_steps(pipeline.core.definition) if not nodes or steps is None: return pipeline rewritten = list(steps) changed = _drop_spurious_ordinate_swap(rewritten, nodes, pipeline.core) changed = _add_engineering_swaps(rewritten, nodes) or changed if not changed: return pipeline corrected = Transformer.from_pipeline( " ".join(["proj=pipeline", *(f"step {step}" for step in rewritten)]) ) return replace( pipeline, corrected=tuple( (corrected if transformer is pipeline.core else transformer, direction) for transformer, direction in pipeline.steps ), ) def _substantive_nodes(definition: dict[str, Any]) -> list[dict[str, Any]]: """The operations in a PROJJSON tree that move coordinates, in order. ``always_xy`` wraps the operation in a concatenated operation together with the axis-order bookkeeping it inserts; that bookkeeping is skipped. """ if definition.get("type") == "ConcatenatedOperation": return [ node for node in definition.get("steps", ()) if isinstance(node, dict) and _method_of(node)[0] not in _BOOKKEEPING_METHODS ] return [definition] if isinstance(definition.get("method"), dict) else [] def _method_of(node: dict[str, Any]) -> tuple[str, bool]: """A node's method name, lower-cased, and whether PROJ inverted the node. PROJ exports an inverted step with its forward parameters, the ends swapped, and ``Inverse of`` prefixed to the method name. """ method = node.get("method") name = str(method.get("name", "")).lower() if isinstance(method, dict) else "" if name.startswith(_INVERSE_METHOD_PREFIX): return name[len(_INVERSE_METHOD_PREFIX) :], True return name, False def _node_crs(node: dict[str, Any], end: str) -> CRS | None: """The CRS a PROJJSON operation node names at ``end``, as declared.""" value = node.get(end) if not isinstance(value, dict): return None try: return CRS.from_json_dict(value) except CRSError: return None def _north_first(crs: CRS) -> bool: """Whether the CRS declares a northing before an easting. Read through :attr:`CoordinateReferenceSystem.value_axis_order` so that the correction and the order this package reports cannot disagree. """ order = CoordinateReferenceSystem(crs, crs.name).value_axis_order return order[:2] == (1, 0) def _add_engineering_swaps(steps: list[str], nodes: list[dict[str, Any]]) -> bool: """Part 1: swap the values at a northing-first engineering end. Returns: Whether ``steps`` was changed. """ changed = False entry = _node_crs(nodes[0], "source_crs") if ( entry is not None and entry.is_engineering and _north_first(entry) and _method_of(nodes[0])[0] != _GRID_OFFSETS_METHOD ): steps.insert(0, _AXIS_SWAP_STEP) changed = True exit_ = _node_crs(nodes[-1], "target_crs") if ( exit_ is not None and exit_.is_engineering and _north_first(exit_) and _method_of(nodes[-1])[0] != _GRID_OFFSETS_METHOD ): steps.append(_AXIS_SWAP_STEP) changed = True return changed def _drop_spurious_ordinate_swap( steps: list[str], nodes: list[dict[str, Any]], core: Transformer ) -> bool: """Part 2: remove PROJ's normalising swap when the ordinates are east-first. Returns: Whether ``steps`` was changed. Raises: OperationNotAvailableError: See :func:`_correct_engineering_axes`. """ evaluated = [] for node in nodes: method, inverted = _method_of(node) if method not in _EVALUATION_POINT_METHODS: continue # The evaluation point is stated in the operation's own target CRS, # which is the node's source once PROJ has inverted it. crs = _node_crs(node, "source_crs" if inverted else "target_crs") if crs is not None and crs.is_projected and _north_first(crs): evaluated.append((node, crs)) if not evaluated: return False if len(nodes) > 1: raise OperationNotAvailableError( f"{_node_label(evaluated[0][0])} states its evaluation point in " f"{evaluated[0][1].name!r}, which declares its northing first, and " "PROJ chained it with other steps; whether the ordinates follow " "that declared order or are east-first cannot be established for " "a step inside a chain, so the operation is refused rather than " "risk a transposed result. Apply the operation between its own " "CRSs instead" ) node, crs = evaluated[0] affine = [index for index, step in enumerate(steps) if _AFFINE_STEP in step.split()] if len(affine) != 1: raise OperationNotAvailableError( f"PROJ built {_node_label(node)} as {len(affine)} affine steps " "rather than one, a shape this package does not recognise; " "refusing rather than risk a transposed result" ) index = affine[0] inverted = _INVERSE_FLAG in steps[index].split() first, second = _affine_offsets(steps[index]) convention = _ordinate_convention( crs, first, second, _area_bounds(core.area_of_use, crs, node) ) if convention is None: raise OperationNotAvailableError( f"{_node_label(node)} states its evaluation point as ({first:g}, " f"{second:g}) in {crs.name!r}, which declares its northing first, " "and the point does not fall inside the area of use under exactly " "one reading of those ordinates (declared order, or easting " "first); which axis each ordinate refers to cannot be established, " "so the operation is refused rather than risk a transposed result" ) if convention == "declared": return False swap = index - 1 if inverted else index + 1 if not (0 <= swap < len(steps) and _swaps_horizontal(steps[swap])): raise OperationNotAvailableError( f"PROJ built {_node_label(node)} without the axis swap this " "package expects beside its affine step; refusing rather than " "risk a transposed result" ) del steps[swap] return True def _affine_offsets(step: str) -> tuple[float, float]: """The translation of a PROJ ``affine`` step, in the CRS's own units.""" offsets = {"xoff": 0.0, "yoff": 0.0} for token in step.split(): key, separator, value = token.partition("=") if separator and key in offsets: offsets[key] = float(value) return offsets["xoff"], offsets["yoff"] def _area_bounds( area: Any, crs: CRS, node: dict[str, Any] ) -> tuple[float, float, float, float] | None: """The bounding box to place an evaluation point against. The operation's own area of use is the most specific. Failing that, the CRS's -- read from the registry by the authority code the operation names for it when the embedded definition dropped its usage, as PROJ's export of an operation's ends does. """ bounds = getattr(area, "bounds", None) if bounds is not None: return cast("tuple[float, float, float, float]", bounds) if crs.area_of_use is not None: return crs.area_of_use.bounds for end in ("target_crs", "source_crs"): value = node.get(end) if not isinstance(value, dict) or value.get("name") != crs.name: continue identifier = _identifier(value) if identifier is None: return None try: registered = CRS.from_authority(*identifier) except CRSError: return None if registered.area_of_use is not None and registered.equals( crs, ignore_axis_order=False ): return registered.area_of_use.bounds return None def _ordinate_convention( crs: CRS, first: float, second: float, bounds: tuple[float, float, float, float] | None, ) -> str | None: """Which axes an evaluation point's ordinates refer to, from where it lands. Args: crs: The northing-first projected CRS the point is stated in. first: The first ordinate as stated. second: The second ordinate as stated. bounds: The area of use to place the point against, or None when nothing states one. Returns: ``"declared"`` when only the declared reading (first ordinate a northing) lands inside the area of use, ``"east-first"`` when only the other does, None when neither or both do or there is no area. """ geodetic = crs.geodetic_crs if bounds is None or geodetic is None: return None to_geographic = Transformer.from_crs(crs, geodetic, always_xy=True) # An area of use is stated from Greenwich; a base CRS on another prime # meridian (NGO 1948 counts from Oslo) reports longitudes from there. meridian = geodetic.prime_meridian offset = ( 0.0 if meridian is None else math.degrees( float(meridian.longitude) * float(meridian.unit_conversion_factor) ) ) def lands(easting: float, northing: float) -> bool: longitude, latitude = to_geographic.transform(easting, northing) return _inside(bounds, longitude + offset, latitude) declared = lands(second, first) east_first = lands(first, second) if declared and not east_first: return "declared" if east_first and not declared: return "east-first" return None def _inside( bounds: tuple[float, float, float, float], longitude: float, latitude: float ) -> bool: """Whether a position lies within a bounding box, allowing for slack.""" if not (math.isfinite(longitude) and math.isfinite(latitude)): return False longitude = (longitude + 180.0) % 360.0 - 180.0 west, south, east, north = bounds margin = _AREA_MARGIN_DEGREES if not south - margin <= latitude <= north + margin: return False if west <= east: return west - margin <= longitude <= east + margin # A box across the antimeridian. return longitude >= west - margin or longitude <= east + margin def _node_label(node: dict[str, Any]) -> str: """Short identification of an operation node for error messages.""" identifier = _identifier(node) name = node.get("name") or "the operation" return f"{name!r}" if identifier is None else f"{identifier[0]}:{identifier[1]}" def _carry_unread_horizontal( source: CoordinateReferenceSystem, target: CoordinateReferenceSystem, applied: AppliedOperation, grids: tuple[GridUsage, ...], columns: tuple[FloatArray, ...], ) -> tuple[FloatArray, ...]: """Withhold a horizontal position that the applied shift never reads. A height travelling between two vertical CRSs is usually accompanied by the horizontal position its grid is read at. Where the shift is instead the same everywhere -- a plain vertical offset, a unit change, a height/depth reversal -- that position is not part of the calculation, and it need not even be geographic: it is commonly an engineering or projected coordinate, which PROJ's ``geogoffset`` step would reject as an impossible latitude. Both CRSs being vertical, the position cannot reach the result either way, so it is held back rather than offered to PROJ as something it is not. Args: source: Source CRS. target: Target CRS. applied: The operation being applied. grids: Grids that operation depends on. columns: One owned array per axis. Returns: The columns, with the horizontal pair blanked when it cannot be read, and unchanged otherwise. """ if len(columns) != _MAX_COORDINATE_VALUES or grids: return columns if not (source.dimension == 1 and _is_vertical(source)): return columns if not (target.dimension == 1 and _is_vertical(target)): return columns if (applied.method_name or "").strip().lower() not in ( _POSITION_FREE_VERTICAL_METHODS ): return columns columns[0].fill(0.0) columns[1].fill(0.0) return columns def _require_in_range( source: CoordinateReferenceSystem, columns: Sequence[Sequence[float] | FloatArray], *, point_offset: int = 0, ) -> None: """Refuse a latitude or longitude a geographic CRS's axis unit cannot represent. PROJ rejects an impossible latitude too, but only as "Invalid latitude", naming neither the CRS nor the units nor which value it read as latitude. Since the usual cause is projected coordinates in metres handed to a geographic CRS, or latitude passed first, the message has to name all three to be actionable. An impossible longitude PROJ does not reject at all: it wraps it, so a longitude of 400 degrees quietly becomes 40. The limits are derived from each axis's own unit rather than assumed to be 90 and 180, so a CRS declaring grads (``EPSG:4807``) is held to 100 rather than wrongly refused. Longitude is allowed a full turn either way, since a dataset counted from 0 to 360 is a convention, not a mistake. """ for value_index, axis, limit in _range_checks(source, len(columns)): values = np.asarray(columns[value_index]) invalid = np.isfinite(values) & (np.abs(values) > limit) if np.any(invalid): point = int(np.argmax(invalid)) value = float(values[point]) raise CoordinateOutOfRangeError( f"has {axis.name.lower()} {value} " f"{axis.unit_name}, outside the valid range " f"[-{limit:g}, {limit:g}] for {_label(source)}; values are " f"given in {source.value_axis_abbreviations} order and in " f"{source.axis_units} -- projected coordinates in metres " "need a projected CRS", point=point + point_offset, ) def _out_of_range( source: CoordinateReferenceSystem, columns: Sequence[FloatArray] ) -> NDArray[np.bool_]: """True for each point :func:`_require_in_range` would refuse.""" invalid = np.zeros(len(columns[0]) if columns else 0, dtype=np.bool_) for value_index, _, limit in _range_checks(source, len(columns)): values = columns[value_index] invalid |= np.isfinite(values) & (np.abs(values) > limit) return invalid def _range_checks( source: CoordinateReferenceSystem, width: int ) -> list[tuple[int, AxisSpec, float]]: """Each latitude and longitude among ``width`` values, with its limit. Latitude first: when both values are metres, the one read as latitude is the diagnostic the caller can act on. """ if not source.is_geographic: return [] checks: list[tuple[int, AxisSpec, float]] = [] for value_index, declared_index in enumerate(source.value_axis_order[:width]): axis = source.axes[declared_index] direction = axis.direction.lower() if direction in _NORTHINGS: limit = (math.pi / 2) / axis.unit_conversion_factor checks.insert(0, (value_index, axis, limit)) elif direction in _EASTINGS: limit = (2 * math.pi) / axis.unit_conversion_factor checks.append((value_index, axis, limit)) return checks def _require_finite( columns: tuple[FloatArray, ...], source: CoordinateReferenceSystem, target: CoordinateReferenceSystem, *, point_offset: int = 0, ) -> None: """Refuse to return an infinite or undefined coordinate. PROJ signals an unrepresentable result with infinity. Returned as-is it would propagate silently into whatever consumes it. """ finite = np.ones(len(columns[0]), dtype=np.bool_) for column in columns: finite &= np.isfinite(column) if not np.all(finite): index = int(np.argmin(finite)) row = tuple(float(column[index]) for column in columns) raise TransformationFailedError( "has no finite representation transforming " f"{_label(source)} to {_label(target)}; PROJ produced {row}", point=index + point_offset, ) def _label(crs: CoordinateReferenceSystem) -> str: """Short identification of a CRS for error messages.""" return crs.authority_code or crs.name def _applied_label(definition: dict[str, Any]) -> str: """Short identification of the operation PROJ actually built.""" identifier = _identifier(definition) name = definition.get("name") or "an unnamed operation" if identifier is None: return f"{name!r}" return f"{identifier[0]}:{identifier[1]} ({name!r})"