Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/korp-map

python/src/korp_map_client/_geo.py

"""GeoParquet 1.1 separated geometry (struct<x, y> in lists) to shapely, vectorised."""

from __future__ import annotations

import json
from typing import TYPE_CHECKING, Any

import pyarrow as pa
import pyarrow.types as pat

if TYPE_CHECKING:  # pragma: no cover
    import geopandas

GEO_HINT = "korp_map_client geometry needs the [geo] extra: pip install 'korp-map-client[geo]'"
try:
    import numpy as np
except ImportError as e:  # numpy comes with shapely / geopandas
    raise ImportError(GEO_HINT) from e

CRS = "EPSG:4326"


def _need_geo() -> tuple[Any, Any]:
    try:
        import geopandas
        import shapely
    except ImportError as e:  # pragma: no cover - exercised only without the extra
        raise ImportError(GEO_HINT) from e
    return geopandas, shapely


def _is_list(t: pa.DataType) -> bool:
    return pat.is_list(t) or pat.is_large_list(t)


def _list_levels(arr: pa.Array) -> tuple[pa.Array, list[np.ndarray]]:
    """Peel list levels off ``arr``; return the innermost (struct) values and the
    offsets of each level, outermost first, rebased to start at 0 and sliced to fit."""
    offsets: list[np.ndarray] = []
    while _is_list(arr.type):
        offs = np.asarray(arr.offsets.to_numpy(zero_copy_only=False), dtype=np.int64)
        start, stop = int(offs[0]), int(offs[-1])
        offsets.append(offs - start)
        arr = arr.values.slice(start, stop - start)
    return arr, offsets


_ENCODINGS = {
    "point": (0, "POINT"),
    "linestring": (1, "LINESTRING"),
    "multipoint": (1, "MULTIPOINT"),
    "polygon": (2, "POLYGON"),
    "multilinestring": (2, "MULTILINESTRING"),
    "multipolygon": (3, "MULTIPOLYGON"),
}
_BY_DEPTH = {0: "POINT", 1: "LINESTRING", 2: "MULTILINESTRING", 3: "MULTIPOLYGON"}


def geo_encoding(table: pa.Table, column: str = "geometry") -> str | None:
    """The column's GeoParquet ``encoding`` from the ``geo`` schema metadata, if any."""
    raw = (table.schema.metadata or {}).get(b"geo")
    if not raw:
        return None
    try:
        enc = json.loads(raw)["columns"][column]["encoding"]
    except (ValueError, KeyError, TypeError):
        return None
    return str(enc).lower()


def geometry_to_shapely(col: pa.Array | pa.ChunkedArray, encoding: str | None = None) -> np.ndarray:
    """A separated-layout geometry column as a numpy array of shapely geometries.

    point = ``struct<x, y>``; multilinestring = ``list<list<struct>>``;
    multipolygon = ``list<list<list<struct>>>``. ``encoding`` (the GeoParquet ``geo``
    metadata value) picks the type when the list depth is ambiguous (polygon vs
    multilinestring); without it the depth decides. Null rows come back as ``None``.
    No per-row Python loop.
    """
    _, shapely = _need_geo()
    from shapely import GeometryType

    if isinstance(col, pa.ChunkedArray):
        col = col.combine_chunks() if col.num_chunks != 1 else col.chunk(0)
    n = len(col)
    nulls = col.is_null().to_numpy(zero_copy_only=False) if col.null_count else None

    coords_arr, offsets = _list_levels(col)
    if not pat.is_struct(coords_arr.type):
        raise TypeError(f"geometry is not the separated layout: {col.type}")
    x, y = (c.to_numpy(zero_copy_only=False) for c in coords_arr.flatten()[:2])
    coords = np.column_stack([np.asarray(x, dtype=np.float64), np.asarray(y, dtype=np.float64)])

    depth = len(offsets)
    name = _BY_DEPTH.get(depth)
    if encoding is not None and encoding in _ENCODINGS:
        want_depth, want_name = _ENCODINGS[encoding]
        if want_depth != depth:
            raise TypeError(f"geometry encoding {encoding!r} does not fit {col.type}")
        name = want_name
    if name is None:
        raise TypeError(f"unexpected list depth {depth} in geometry {col.type}")
    if depth == 0:
        geoms = shapely.points(coords)
    else:
        # from_ragged_array wants the innermost offsets first.
        geoms = shapely.from_ragged_array(getattr(GeometryType, name), coords, tuple(reversed(offsets)))
    geoms = np.asarray(geoms, dtype=object)
    assert len(geoms) == n
    if nulls is not None:
        geoms[nulls] = None
    return geoms


def _is_wkb(t: pa.DataType) -> bool:
    if isinstance(t, pa.ExtensionType):
        t = t.storage_type
    return pat.is_binary(t) or pat.is_large_binary(t) or pat.is_binary_view(t)


def wkb_to_shapely(col: pa.Array | pa.ChunkedArray) -> np.ndarray:
    """A WKB column (GeoParquet 2.0 / Parquet GEOMETRY, geoarrow.wkb) as shapely
    geometries; nulls come back as ``None``. One vectorised shapely call."""
    _, shapely = _need_geo()
    if isinstance(col, pa.ChunkedArray):
        col = col.combine_chunks() if col.num_chunks != 1 else col.chunk(0)
    if isinstance(col, pa.ExtensionArray):
        col = col.storage
    return np.asarray(shapely.from_wkb(np.asarray(col.to_numpy(zero_copy_only=False), dtype=object)), dtype=object)


def _crs(table: pa.Table, geometry: str) -> Any:
    """The column's CRS from the geo metadata or the geoarrow field metadata;
    lon/lat (OGC:CRS84 or none given) is EPSG:4326."""
    crs: Any = None
    raw = (table.schema.metadata or {}).get(b"geo")
    if raw:
        try:
            crs = (json.loads(raw).get("columns", {}).get(geometry) or {}).get("crs")
        except (ValueError, AttributeError):
            crs = None
    if crs is None:
        f = table.schema.field(geometry)
        ext = (f.metadata or {}).get(b"ARROW:extension:metadata")
        if ext is None and isinstance(f.type, pa.ExtensionType):
            ext = f.type.__arrow_ext_serialize__()
        if ext:
            try:
                crs = json.loads(ext).get("crs")
            except (ValueError, AttributeError):
                crs = None
    if crs is None or (isinstance(crs, str) and crs.upper() in ("OGC:CRS84", "EPSG:4326", "")):
        return CRS
    if isinstance(crs, dict):
        ident = crs.get("id") or {}
        if ident.get("authority") in ("OGC",) and str(ident.get("code")) == "CRS84":
            return CRS
        if ident.get("authority") == "EPSG" and str(ident.get("code")) == "4326":
            return CRS
    return crs


def table_to_geodataframe(table: pa.Table, geometry: str = "geometry") -> "geopandas.GeoDataFrame":
    """``table`` as a GeoDataFrame; the geometry column (separated layout or WKB)
    becomes shapely. CRS from the file (EPSG:4326 for lon/lat)."""
    geopandas, _ = _need_geo()
    col = table.column(geometry)
    if _is_wkb(table.schema.field(geometry).type):
        geoms = wkb_to_shapely(col)
    else:
        geoms = geometry_to_shapely(col, geo_encoding(table, geometry))
    crs = _crs(table, geometry)
    df = table.drop_columns([geometry]).to_pandas()
    return geopandas.GeoDataFrame(df, geometry=geopandas.GeoSeries(geoms, crs=crs, index=df.index), crs=crs)