Registered geolocation arrays#

Pass a cugeo.raster.geolocation.GeolocationGrid to cugeo.raster.warp.reproject(src_geoloc_array=grid, ...) to sample CUDA imagery through registered ground-coordinate fields. The operation uses the native complete inverse, cugeo-proj CRS operation and shared nearest/bilinear sampler. It accepts CUDA array imagery and native TIFF paths, readers and Band references. Physical sensor grid production is a separate operation. Native JPEG2000 readers and Bands also feed this controller with nvJPEG2000; their bounded CUDA file execution is unqualified. Registered geometry supplies the source georeferencing even when the image has no stored affine or CRS.

Construct a grid#

from cugeo.raster.geolocation import GeolocationGrid

grid = GeolocationGrid(x, y, source_shape=(height, width), crs=coordinate_crs,
                       offsets=(pixel_offset, line_offset),
                       steps=(pixel_step, line_step), convention="corner")

source_shape is the image’s HW shape, independent of node dimensions. Dense X/Y have equal HW shapes. With separable=True, each field is an N or 1×N axis; X and Y lengths may differ. Fields keep independent Float32/Float64 dtypes, positive aligned strides and host or CUDA residency. Constructor admission reads metadata only. Host fields upload explicitly during preparation; device fields are never scanned on the host or expanded to a dense lattice.

Node (column, row) registers at offset + step * (index + shift) independently per source axis. Steps may be signed and unequal, but must be finite and nonzero. The shift is zero for convention="corner" and 0.5 for "center": half a lattice step. x_nodata declares exact-equality geometry nodata on X only. A NaN declaration does not compare equal to a node. Unmarked nonfinite nodes remain unresolved unless independently excluded.

The complete CRS retains its native axes and units. Coordinates are literal traditional GIS X/Y: easting/longitude and northing/latitude. No sensor, frame, longitude-chart or CRS inference comes from coordinate magnitudes. Reprojection infers source CRS from the grid and rejects a conflicting explicit src_crs. Affine, GCP, RPC and geolocation source selections are mutually exclusive.

Reproject arrays#

The executable array example uses a 13×7 plane and automatic GDAL-shaped planning:

import json
import numpy as np
import cupy as cp
from cugeo.raster.geolocation import GeolocationGrid
from cugeo.raster.warp import reproject
from cugeo.raster.enums import Resampling

rows, columns = np.indices((7, 13), dtype=np.float64)
x = 500000 + 20 * columns
y = 70 - 10 * rows
source = cp.asarray((5 + 17 * rows + 3 * columns).astype(np.float32)[None])
with GeolocationGrid(x, y, source_shape=(7, 13), crs="EPSG:32631") as grid:
    result = reproject(source, src_geoloc_array=grid, dst_crs="EPSG:32631",
                       resampling=Resampling.bilinear, return_receipt=True)
    assert result.data.shape == (1, 4, 14)
    print(json.dumps({"shape": list(result.data.shape),
                      "transform": list(result.transform.to_gdal()),
                      "planning": result.receipt.geometry_planning}))

The example returns a (1, 4, 14) Float32 CuPy image. Planning is distinct from sampling: reference geometry can extrapolate closed source edges and choose a local planning branch. Its suggested grid grants no pixel coverage or global exterior uniqueness. Planning semantics and sampling semantics govern these separate decisions.

Supply a destination and dst_transform to select its grid, or omit both for planning and CHW allocation. Supplied output retains identity. The ordinary return is (destination, dst_transform); return_status or return_receipt returns WarpResult. Image dtype, positive strides, nodata, fill/preserve, validity and conversion follow the ordinary warp contract. UInt8, UInt16 and Float32 CUDA imagery are admitted. Host imagery has no fallback. Ordinary nodata uses all bands; advanced preparation defaults to any band.

The raw form src_geoloc_array=(x, y) requires an explicit src_crs and equal HW shapes. Native normalization sets zero offsets, corner convention and steps source_width / array_width, source_height / array_height. A one-row pair supplies separable axes. GeolocationGrid.from_pair(...) applies those same rules. Explicit one-row dense construction retains its paired-scanline meaning.

Only a proved unique source coordinate with stable physical coverage and sampling decisions reaches the sampler. Status 1 requires proved absence or coverage failure; ambiguity, continua and unestablished numerics use status 3. Only proved identical source points deduplicate. Geometry holes and imagery nodata have separate meanings; source-nodata output has status 2.

Reproject a file or Band#

Pass a native TIFF path, an open DatasetReader, or raster.band(reader, indexes) as the source with the same src_geoloc_array. Ordered one-based band sequences preserve repetitions. TIFF UInt8, UInt16 and Float32 sources use the existing native reader’s compression and layout admission. Alpha and internal/external mask sources return capability code 2; scalar nodata is admitted. File geolocation requires CUDA output. Omitted output allocates CHW CuPy storage; supplied output retains its shape, strides and identity.

Set memory_budget_bytes to cap known retained and working payload, and preferred_shape/minimum_shape to choose complete destination waves. Geometry maps stay on the device. Complete inverse traversal reduces each wave to its clipped source window, including nonzero nearest/bilinear contributors. The native TIFF reader decodes that window into host staging, transfers the region to CUDA and submits the existing sampler. No-sample waves retain geometry status and skip decoding. Resource exhaustion reduces complete waves; an insufficient minimum unit returns resource code 8. I/O, corruption, context and semantic errors propagate without a resource retry.

The cap includes executor-owned map/index state, coordinate uploads, decoded regions, staging, codec workspace, retained output and status backings, native output-owner control reservations and overlapping growth. Implicit output-grid planning uses the same cap in a separate completed phase. Caller coordinate spans are immutable inputs reported separately. Opening a path charges parser buffers, growth overlap, retained tables, strings and sidecars to the cap. Executor-owned paths retain the bounded native source and request only primary image dimensions/type, demanded nodata/affine facts and a demanded full CRS. They create no ordinary reader, complete catalog or diagnostic JSON. Requested CRS text and presentation overlap use native host admission. A registered pair still requires its explicit source chart; imagery metadata does not infer it. Retained metadata and binding controls stay charged during planning, output allocation and execution. CRS transport queries CRS.to_wkt_into() before allocating one NUL-terminated buffer. Grid creation, implicit-grid planning and imagery-plan creation admit that buffer and its query/view controls before growth. The native coordinate export borrows PROJ text during its serialized call; opaque PROJ export and semantic-validation storage remains unknown. Unadmitted Reader and Band metadata remains external. Explicit source admission retains its metadata charge when that source is passed to file execution. Opaque provider, XML-parser, transport, allocator and driver storage remains unknown; the cap does not measure physical memory or isolate a process.

Opening, plan/controller construction, implicit-grid preparation, output allocation and wave execution admit their requested payload. Constructor admission includes simultaneously live outputs and source/plan metadata. A raw X/Y pair creates its grid metadata under the same admission; a supplied registered grid remains an external immutable owner unless explicitly admitted.

Explicit Rust/C/C++ file calls and GeolocationGrid.enqueue_file accept the existing ReadCancellation token. Cancellation stops new atomic waves and drains submitted work. It leaves unsubmitted pixels, statuses and validity bits untouched; enqueue_file initializes no destination outside those waves. complete means submitted work completed; cancelled, requested_pixels, submitted_pixels and completed_pixels distinguish partial coverage from a completed request. A cancelled token stays cancelled until Rust reset or replacement; closing its public handle after enqueue does not end execution’s retained owners. Ordinary reproject keeps its complete-image return contract and accepts no cancellation argument.

receipt.file reports completed pixels, actual windows, waves, resource retries, rejected windows, transfers, waits and known peaks. Its geometry_planning entry holds separate preparation counters and admission facts. source_metadata, grid_creation, geometry_creation and controller_creation record separate constructor admissions and retained bytes. For an ordinary file call, the combined known peak includes constructors it owns, planning and execution with their retained overlap. Historical opening peaks of supplied readers remain separate from the current call. A failed preparation can report incomplete work counters; an early source-presentation refusal reports source_admission with its budget, required payload, controls and known output backing or unknown backing’s addressed span, without claiming geometry work. Missing opaque counters are not zero. File execution completes before an ordinary call returns, including when no receipt was requested. Earlier complete waves can remain written after a later failure; outputs have no transactional rollback guarantee.

Streams, lifetime and resources#

Ordinary calls select the current CuPy stream or an explicit stream through the shared stream adapter. Native execution accepts resolved stream 0, 1, 2 and context-owned caller streams. CAI metadata stream 0 remains invalid. Foreign producer declarations are ordered with retained events; undeclared producers establish readiness themselves. Borrowed fields remain unchanged after declared production and alive while consumers retain them.

Grid, preparation and execution handles stay on their creating OS thread and process. Native prepared operations also require their captured CUDA context. Do not transfer these owners to another thread. Complete and close them on the creator thread; finalization that cannot safely close fails closed. Grid and prepared aliases may close before execution completion: retained native and Python owners keep the needed storage alive.

Ordinary geolocation waits before returning to observe native resource reports, including when no receipt was requested. Advanced grid.prepare(...) returns a reusable preparation with enqueue, query, wait and close; one execution may retain a preparation at a time. Close an execution before reusing it.

A positive array workspace_budget_bytes limits native map/report/arithmetic payload. Zero selects a wave using available memory, work size and compiled occupancy. Planning warms its seed and inverse kernels before sizing arithmetic storage; the wave uses queried hardware properties and backs off on resource failure. Coordinate uploads, coordinate-operation resources, host bookkeeping and opaque driver local-memory backing are separate. Smaller waves and device seed reconstruction preserve the full candidate set. Planning additionally accounts for its metadata, query, seed-weight and CCCL sort buffers within the requested budget. It replays ordered sample waves or reconstructs bounded seed tiles when a full table is unavailable. Actual insufficient minimum storage fails with a resource error; numerical uncertainty remains status 3. Isolated branches retain the 128-update refinement limit.

For retained seed construction, planning reserves arithmetic workers against the minimum ordered sample wave before assigning remaining storage to wave scratch. The worker count is bounded by work size, compiled occupancy and the actual fit. A multi-wave lattice therefore retains parallel arithmetic when multiple worker arenas fit alongside its minimum construction storage.

Completed receipts report actual uploads, transfers, waits and requested allocation payloads. Automatic ordinary calls include geometry_planning facts. Planning allocated_bytes describes live requested raster storage; peak_allocated_bytes includes overlapping transient seed construction storage. seed_sort_calls counts CCCL calls; kernel_launches counts direct raster launches and excludes opaque CCCL launches. seed_resource_failures records resource failures recovered through device reconstruction. Array workspace facts exclude coordinate-owner and driver allocations. File planning instead reports budget_scope=1, including its owned uploads and host preparation storage; admission_requests/admission_acquired count reservations, while allocation_count describes live requested device allocations. Compiled local-byte products estimate kernel backing demand, not measured device traffic or allocator peaks. Native sampling timing fields retain their sampling submission boundary.

The native API reference specifies Rust and C admission, budgets and ownership. The installed C++20 facade is <cugeo/raster/geolocation.hpp>; C records and entry points are in raster.h.