Transformation

class geodetic_engine.geodesy.Transformation[source]

Bases: object

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 source_crs and 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")

Resolve a transformation.

Parameters:
  • source_crs (Any) – CRS the input coordinates are in; an authority code, WKT, a PROJ string or a pyproj.CRS.

  • target_crs (Any) – CRS to produce coordinates in.

  • operation (str | int | OperationCandidate | StatedOperation | CoordinateOperation | Sequence[str | int | OperationCandidate | StatedOperation | CoordinateOperation] | None, default: None) –

    EPSG coordinate operation to apply, as "EPSG:15670", a bare code, an OGC URN, an operation name, or an OperationCandidate from 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 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 (bool, default: False) – 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.

__init__(source_crs, target_crs, operation=None, *, allow_any_operation=False)[source]

Resolve a transformation.

Parameters:
  • source_crs (Any) – CRS the input coordinates are in; an authority code, WKT, a PROJ string or a pyproj.CRS.

  • target_crs (Any) – CRS to produce coordinates in.

  • operation (str | int | OperationCandidate | StatedOperation | CoordinateOperation | Sequence[str | int | OperationCandidate | StatedOperation | CoordinateOperation] | None, default: None) –

    EPSG coordinate operation to apply, as "EPSG:15670", a bare code, an OGC URN, an operation name, or an OperationCandidate from 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 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 (bool, default: False) – 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.

property source_crs: CoordinateReferenceSystem

CRS the input coordinates are expressed in.

property target_crs: CoordinateReferenceSystem

CRS the output coordinates are expressed in.

property operation: AppliedOperation

Which operation is applied, and how it was arrived at.

property grids: tuple[GridUsage, ...]

Grid files this transformation depends on. All are installed.

property requires_epoch: 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.

transform(x, y=None, z=None, *, coordinate_epoch=None)[source]

Transform one point or a batch of points.

Parameters:
  • x (Iterable[Iterable[float]] | Iterable[float] | float) – 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 pyproj.Transformer.transform()’s xx, yy, zz convention, when y is given.

  • y (Iterable[float] | float | None, default: None) – 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 (Iterable[float] | float | None, default: None) – 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 (float | None, default: None) – 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.

Return type:

TransformationResult

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...,),)
transform_arrays(x, y=None, z=None, *, coordinate_epoch=None)[source]

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 transform(). Use transform_batches() for a lazy stream of bounded row batches.

Return type:

ArrayTransformationResult

transform_batches(batches, *, coordinate_epoch=None)[source]

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.

Return type:

Generator[ArrayTransformationResult]

transform_geometry(value, *, coordinate_epoch=None, axis_order='xy', densify=None, segments='straight', antimeridian='split', orient=None, srid_authority='EPSG')[source]

Transform a geometry, read from any encoding geometry WKT to Esri JSON.

Every position goes through 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.

Parameters:
  • value (object) – The geometry: WKT, EWKT, WKB or EWKB as bytes or hex, a GeoJSON or Esri JSON geometry, or a Shapely geometry; see read_geometry().

  • coordinate_epoch (float | None, default: None) – As for transform().

  • axis_order (Literal['xy', 'crs'], default: "xy") – "xy", or "crs" when the geometry is in the source CRS’s declared order, and is to be written in the target’s.

  • densify (float | None, default: None) – 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 (Literal['straight', 'geodesic'], default: "straight") – 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 (Literal['split', 'unwrap'] | None, default: "split") – 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 (Literal['ccw', 'cw'] | None, default: None) – None keeps the vertex order as transformed; "ccw" winds exterior rings counterclockwise (the RFC 7946 rule) and "cw" clockwise (Esri’s).

  • srid_authority (str, default: "EPSG") – The authority an EWKT or EWKB SRID is a code of.

Return type:

GeometryResult

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 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)'
transform_geometries(values, *, coordinate_epoch=None, axis_order='xy', densify=None, segments='straight', antimeridian='split', orient=None, srid_authority='EPSG')[source]

Transform many geometries, with one call per number of values per position.

As transform_geometry(), for a sequence, a numpy array, a pandas Series or a GeoPandas GeoSeries, whose CRS must be source_crs. One failing position fails the batch, naming its geometry.

Return type:

GeometryResults

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]