Reproject locations and join them to service areas#
Library |
Source package version |
Documentation |
|---|---|---|
cugeo-proj |
0.1.0 |
|
cugeo-geometry |
0.1.0 |
Assign WGS 84 locations to service areas defined in UTM zone 31N. You will transform longitude and latitude on the GPU with cugeo-proj, materialize the projected points as WKB in a host Arrow table, then run a polygon spatial join with cugeo-geometry. Both packages come from the same repository checkout.
The example produces five matches, including overlapping areas and a location with a NULL label. It checks the coordinates against PROJ and the complete join result against an independent PostGIS reference.
Install both libraries#
Use Linux with glibc 2.38 or newer, Python 3.12 or newer, uv, rustup,
a C/C++ compiler and libclang. Both libraries select Rust 1.85.1 through their
toolchain files. The geometry native build needs micromamba, mamba or conda,
network access and about 4 GB of disk. It supplies its own CUDA 13 toolchain;
the proj source build also needs a CUDA 13 toolkit selected by CUDACXX,
PROJ 9.4 or newer and libtiff 4.5.1 or newer matching PROJ’s libtiff.
Execution requires an NVIDIA GPU and a compatible CUDA 13 driver.
Follow the build instructions for prerequisite installation and configuration:
geometry native build
and proj build.
Run the following commands from the repository root. The native build uses
stock libcudf. --jobs 1 limits concurrent compiler processes to reduce peak
RAM use. Increase it when available memory and your CPU allocation allow;
the native build instructions describe the resource options.
Removing the caller’s compiler and package-prefix overrides lets it use the
locked native toolchain. The proj installation below selects its CUDA compiler
separately.
NOTICE AND DISCLAIMER: This software automatically retrieves, accesses or interacts with external materials. Those retrieved materials are not distributed with this software and are governed solely by separate terms, conditions and licenses. You are solely responsible for finding, reviewing and complying with all applicable terms, conditions, and licenses, and for verifying the security, integrity and suitability of any retrieved materials for your specific use case. This software is provided “AS IS”, without warranty of any kind. The author makes no representations or warranties regarding any retrieved materials, and assumes no liability for any losses, damages, liabilities or legal consequences from your use or inability to use this software or any retrieved materials. Use this software and the retrieved materials at your own risk.
cugeo-geometry/tools/gpu_run -- \
env -u CUDACXX -u CUDAHOSTCXX -u CMAKE_PREFIX_PATH bash -c \
'cd cugeo-geometry && tools/build_native.sh --jobs 1'
export CUGEO_GEOMETRY_CUDF_LIBRARY="$PWD/cugeo-geometry/build/native/cugeo-geometry-cudf-build/libcugeo_geometry_cudf.so"
Create the named reproject-join environment and install both local packages
in one command. Keep this checkout at one revision throughout the build and
installation. The proj cu13 extra supplies CuPy, arrow supplies PyArrow,
and test supplies pyproj for the independent runtime check:
uv venv --python 3.12 build/reproject-join
CARGO_BUILD_JOBS=2 CUGEO_PROJ_BUILD_CUDA=1 CUGEO_PROJ_CUDA_MAJOR=13 \
CUDACXX=/usr/local/cuda/bin/nvcc \
uv pip install --python build/reproject-join/bin/python \
./cugeo-geometry './cugeo-proj[cu13,arrow,test]'
Change CUDACXX if your CUDA 13 toolkit is installed elsewhere. This installs
the Python extensions from source; pyproj’s wheel alone does not provide the
system PROJ library that cugeo-proj links. See the
proj packaging guide for native payload
selection.
Coordinates and service areas#
The program defines four synthetic locations at latitude 45° N and longitudes 3°, 3.001°, 3° and 3.01° E. IDs 1 and 3 share coordinates but retain their separate identities. ID 3 has a NULL label. ID 4 lies outside both areas. These inputs are original example data under the repository’s Apache-2.0 license and need no download.
always_xy=True takes EPSG:4326 coordinates as longitude, latitude in degrees.
The output EPSG:32631 coordinates are easting, northing in metres. Depot spans
eastings 499950–500050 m; Corridor spans 499990–500150 m. Both span northings
4982900–4983000 m. All points are far enough from the polygon edges that a
one-micrometre coordinate error cannot change membership.
The Arrow geom columns contain little-endian, two-dimensional ISO WKB:
Point for locations and Polygon with one closed exterior ring for each area.
WKB carries no CRS here. Both tables use the same EPSG:32631 XY metre
coordinates by construction. geometry="geom" declares the binary columns
as WKB input; it does not transform them or assign CRS metadata.
Transform and join#
Run the complete program with the environment you created:
cugeo-geometry/tools/gpu_run -- \
uv run --no-project --python build/reproject-join/bin/python \
python docs/site/integration-examples/reproject-then-join.py
The displayed source is included from reproject-then-join.py:
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
import hashlib
import json
from pathlib import Path
import struct
POINTS = [(1, "Library", 3.0, 45.0), (2, "Station", 3.001, 45.0),
(3, None, 3.0, 45.0), (4, "Outside", 3.01, 45.0)]
REGIONS = [(10, "Depot", 499950.0, 4982900.0, 500050.0, 4983000.0),
(20, "Corridor", 499990.0, 4982900.0, 500150.0, 4983000.0)]
QUERY = """
SELECT p.id, p.label, r.region_id, r.region_name
FROM points p JOIN regions r
ON ST_Intersects(ST_GeomFromWKB(p.geom), ST_GeomFromWKB(r.geom))
ORDER BY p.id, r.region_id
"""
def input_digest():
return hashlib.sha256(json.dumps([POINTS, REGIONS]).encode()).hexdigest()
def check_coordinates(x, y, status, expected):
import numpy as np
from cugeo.proj import RowStatus
n = len(POINTS)
if not n or np.shape(x) != (n,) or np.shape(y) != (n,):
raise AssertionError("Missing transformed coordinates")
np.testing.assert_array_equal(status, np.full(n, RowStatus.OK))
reference = np.asarray(expected, dtype=np.float64)
if reference.shape != (n, 2):
raise AssertionError("Missing reference coordinates")
error = np.hypot(x - reference[:, 0], y - reference[:, 1])
if not np.all(np.isfinite(error)) or not np.all(error <= 1e-6):
raise AssertionError(f"Coordinate error exceeds 1e-6 m: {error}")
def check_rows(actual, expected):
actual = tuple(tuple(row) for row in actual)
expected = tuple(tuple(row) for row in expected)
if not expected or not actual or actual != expected:
raise AssertionError(f"Join rows differ: {actual!r} != {expected!r}")
def polygon_wkb(region):
_, _, west, south, east, north = region
ring = [(west, south), (east, south), (east, north),
(west, north), (west, south)]
return struct.pack("<BIII", 1, 3, 1, len(ring)) + b"".join(
struct.pack("<dd", x, y) for x, y in ring
)
def main():
import cupy as cp
import numpy as np
import pyarrow as pa
import pyproj
import cugeo.geometry
from cugeo.proj import Transformer
evidence = json.loads(Path(__file__).with_suffix(".json").read_text())
if evidence["input_sha256"] != input_digest():
raise AssertionError("Stored independent evidence belongs to other inputs")
longitude = np.asarray([row[2] for row in POINTS], dtype=np.float64)
latitude = np.asarray([row[3] for row in POINTS], dtype=np.float64)
reference = pyproj.Transformer.from_crs(4326, 32631, always_xy=True)
reference_xy = np.column_stack(reference.transform(longitude, latitude, errcheck=True))
stream = cp.cuda.Stream(non_blocking=True)
with Transformer.from_crs(4326, 32631, always_xy=True) as transformer:
with stream:
device_lon, device_lat = cp.asarray(longitude), cp.asarray(latitude)
x, y, status = transformer.transform_device(
device_lon, device_lat, return_status=True, stream=stream
)
x, y, status = map(cp.asnumpy, (x, y, status))
check_coordinates(x, y, status, reference_xy)
check_coordinates(x, y, status, evidence["pyproj_xy"])
check_coordinates(x, y, status, evidence["postgis_xy"])
points = pa.table({
"id": pa.array([row[0] for row in POINTS], type=pa.int64()),
"label": pa.array([row[1] for row in POINTS], type=pa.string()),
"geom": pa.array([struct.pack("<BIdd", 1, 1, a, b) for a, b in zip(x, y)],
type=pa.binary()),
})
regions = pa.table({
"region_id": pa.array([row[0] for row in REGIONS], type=pa.int64()),
"region_name": pa.array([row[1] for row in REGIONS], type=pa.string()),
"geom": pa.array([polygon_wkb(row) for row in REGIONS], type=pa.binary()),
})
with cugeo.geometry.Session() as session:
tables = {"points": session.table_from_arrow(points, geometry="geom"),
"regions": session.table_from_arrow(regions, geometry="geom")}
result = session.sql(QUERY, tables=tables)
rows = result.rows
check_rows(rows, evidence["rows"])
for row in rows:
print(row)
print("Checked every coordinate (<= 1e-6 m) and every ordered join row")
if __name__ == "__main__":
main()
cp.asarray() copies the longitude and latitude arrays from host memory to
the GPU on stream. transform_device() uses that stream and waits for
completion before returning CuPy outputs. Closing the transformer releases
its plan and workspace; the coordinate arrays remain usable.
cp.asnumpy() then copies the two output arrays and statuses back to the host.
The program packs those host coordinates into WKB and constructs host Arrow
tables. Session.table_from_arrow() copies each table into GPU memory owned
by the session’s registered table. It does not borrow the proj arrays.
Keep the registered tables alive through session.sql(). The query decodes
WKB and computes point-polygon intersections on the GPU. Reading result.rows
materializes all result columns in host memory; those tuples remain usable
after the session closes. See the
Arrow input and lifetime contract.
Check the matches#
The program prints:
(1, 'Library', 10, 'Depot')
(1, 'Library', 20, 'Corridor')
(2, 'Station', 20, 'Corridor')
(3, None, 10, 'Depot')
(3, None, 20, 'Corridor')
Checked every coordinate (<= 1e-6 m) and every ordered join row
ST_Intersects includes polygon boundaries. This inner join emits every
matching pair, so an overlap produces two matches and an outside location
produces none. ORDER BY p.id, r.region_id uniquely orders these rows.
The comparison includes every ID and label, including the NULL payload.
The script checks every status against RowStatus.OK separately from the
coordinates. For each coordinate pair it requires a finite horizontal error
of at most 1e-6 metres against runtime pyproj/PROJ and both saved reference
arrays. It compares full precision values; no rounded display value is an
oracle. Empty coordinates, empty expected rows and empty actual rows fail.
The adjacent independent evidence records the runtime PROJ version and pipeline, the pinned PostgreSQL/PostGIS environment, reference SQL, every projected coordinate and every ordered row. PostGIS transforms the original longitude/latitude inputs and performs the join independently. Neither PostgreSQL nor PostGIS runs during the example.
For other CRS pairs, consult proj’s supported operations and inspect row statuses before packing coordinates. For more geometry queries, continue with supported SQL.