Pixel contract v1#

This document specifies behavior shared by affine sampling, CRS reprojection, RPC orthorectification, and temporal reduction. It is a public compatibility contract, not a roadmap.

Coordinates#

Raster transforms use pixel-corner coordinates. The center of destination pixel (row, column) is (column + 0.5, row + 0.5). For a tile, the declared destination origin is added before center evaluation. The six coefficients [c, a, b, f, d, e] map a destination coordinate to a source coordinate:

source_x = c + a * destination_x + b * destination_y
source_y = f + d * destination_x + e * destination_y

Native affine sampling, reprojection grids, terrain grids, writer validation and the required dataset/module xy and inverse coordinate helpers (including AffineTransformer construction) require nonsingular linear parts with a determinant distinguishable from binary64 cancellation, including forward-only sampling maps. Metadata exposure, array_bounds and reader bounds, composite output metadata, sample-minimum coefficients and orthorectification destination grids require finite coefficients without this determinant test. Bounds follow their shared owner and error contract. Their other operation-specific checks remain required. Define row scales r_x=max(abs(a),abs(b)) and r_y=max(abs(d),abs(e)), scaled products p=(a/r_x)*(e/r_y) and q=(b/r_x)*(d/r_y), determinant delta=p-q, and permanent P=abs(p)+abs(q). A zero row scale is singular. Otherwise the transform is rejected when abs(delta) <= gamma_8*P, where binary64 unit roundoff is u=2^-53 and gamma_8=8u/(1-8u). gamma_8*P is the standard forward absolute-error bound for the at-most-eight rounded divisions, products, subtraction, and bound arithmetic. The comparison is strict at the threshold.

This test detects cancellation between nearly parallel affine rows without imposing an isotropic minimum scale: valid anisotropic maps such as diag(1,1e-15), reflected maps, and representable extreme uniform scales are accepted. It is not a general condition-number or coordinate-unit guarantee. For forward-only evaluation, finite coefficients that pass this determinant test need not also have a finite representable inverse. A consumer that forms an inverse, including source-grid reprojection and terrain lookup, additionally rejects an inverse whose six coefficients are not finite and representable. Forward-only affine sampling retains this determinant requirement.

Nearest sampling selects floor(source_x), floor(source_y). Bilinear sampling subtracts 0.5 to obtain a continuous source-center index and interpolates the contributing neighbors.

Validity and boundaries#

This section defines the default shared sampling policy. Per-band valid-data masks and dataset-mask combination have separate semantics in the required dataset mask contract. Its host mask-reading interface leaves this sampler’s any-band nodata rule unchanged. Ordinary dataset nearest reads have a separate required per-band preservation rule in that contract. Host TIFF nearest reads preserve selected samples independently, including resized/fractional/boundless reads. Direct CUDA JPEG2000 ordinary nearest reads also preserve per-band samples; generic affine and reprojection nearest retain shared sampler validity.

The optional source validity bitmap is row-major and least-significant-bit first, matching Arrow bit ordering. A pixel is source nodata if its validity bit is clear or, under the default any-band policy, any of its bands exactly equals the declared nodata value. NaN nodata matches NaN values. WarpOptions::nodata_policy selects AnyBand (value 0, the default for existing consumers) or AllBands (value 1). Under AllBands, a pixel is nodata only if every band matches the scalar declaration; a partial match contributes every band. A clear explicit validity bit invalidates the pixel under either policy. The same policy governs the mapped-pixel gate and all nonzero bilinear contributors. Omitted nodata declares neither zero nor NaN invalid.

Imagery sampling requires a finite source coordinate inside the physical image: 0 <= source_x < width and 0 <= source_y < height. Nearest requires its selected pixel to be valid. Bilinear omits neighbors beyond the physical image and normalizes the remaining weights, matching GDAL 3.8.4 at image edges. Equivalently, it clips each source-center index to [0, extent - 1] before interpolation. It does not extrapolate beyond source coverage. If the whole source has only one row or one column, bilinear requests select nearest samples on both axes, matching GDAL 3.8.4. Cropped source windows retain the whole source’s interpolation choice.

Nearest and bilinear evaluate the mapped point. Destination scale does not widen the source filter footprint. GDAL’s coarse-grid warp can apply a wider downsampling filter; point-sampling comparisons use GDAL footprints with the same source-pixel scale at the independently determined destination centers.

Bilinear first requires the mapped source pixel at (floor(source_y), floor(source_x)) to be valid. If it is invalid, the output is source nodata even when other neighbors are valid. Otherwise, bilinear excludes masked or nodata neighbors and divides the weighted sum by the sum of surviving weights. A neighbor with exactly zero weight is not read and cannot invalidate or contaminate the result. The source bitmap and selected nodata policy define one shared validity mask for all imagery bands. GDAL comparisons of the default any-band policy encode that union as source alpha. An undeclared zero is a valid sample. Tile and decoded-window boundaries retain the source halo and do not create physical image edges.

WarpOptions::invalid_output_policy selects Fill (value 0) or Preserve (value 1). Fill writes output_fill to every band of an invalid pixel. Preserve leaves every destination sample of that pixel untouched. Both update status and validity for this execution, including coordinate failures. Affine sampling and reprojection accept either write policy. Orthorectification accepts only Fill: OrthorectifyOptions::new rejects Preserve as Unsupported before host or CUDA planning. Existing consumers select fill by default. Status is classified separately:

Code

Meaning

0

valid sampled pixel

1

sampled coordinate outside physical source coverage

2

mapped source pixel is masked or nodata, or no valid weight survives

3

destination-to-source coordinate operation failed

4

terrain coordinate, coverage, mask/nodata, units, or vertical-reference failure

5

sensor footprint or numerical evaluation failure

cuGeo selects the mapped pixel by exact floor. GDAL 3.8.4 adds 1e-10 before converting that coordinate to an integer in its warp sampler. A point just below an integer can therefore select a different mapped pixel in GDAL, affecting nearest values and bilinear nodata rejection. The source-only boundary probe records this convention difference separately from ordinary pixel comparisons.

The required ordinary reprojection contract selects an explicit all-bands-nodata policy for Rasterio-style calls and defines destination preservation when initialization is disabled. The native host and CUDA samplers implement both policies through affine and reprojection options. The ordinary Python reprojection facade selects all-bands nodata and its initialization argument selects fill or preserve. These selections do not change the default any-band/fill policy or the exact-floor boundary convention.

The optional destination bitmap uses the same bit order. Unused high bits in its final byte are preserved.

Geolocation inverse contract#

The advanced Rust geolocation::InversePlan maps host queries to source coordinates under this contract. It establishes sampling decisions without reading imagery. The native Rust CUDA plan composes this inverse with cugeo-proj coordinate operations and the shared image sampler. Registered array bindings expose this owner through Rust, C, C++ and Python. Geolocation execution from files and physical sensor grid producers are unavailable. Singular or numerically unestablished cases return status 3. Automatic output planning uses the distinct geometry-only planning mapping. Its extrapolated coordinates and branch selection establish a suggested grid, not eligible image samples. They never widen this inverse’s physical domain, change its literal chart, admit multiple image roots, or change half-open coverage and unresolved statuses. The source-only orthorectification experiment has a separate private callable contract and finite CUDA qualification. The API contract owns descriptor admission and borrowing. The architecture contract owns discovery, arithmetic and work limits.

Coordinate model#

X is easting or longitude and Y is northing or latitude, in traditional GIS X/Y order regardless of the CRS’s native axis order. Values use the declared CRS units and literal chart. Longitude is not normalized, unwrapped or replaced by a shortest path across a chart seam. Coordinate operations belong to cugeo-proj.

Let the lattice have Nx columns and Ny rows, and the physical source image have width W and height H. Cell (i, j) starts at node column i, row j, with 0 <= i < Nx - 1 and 0 <= j < Ny - 1. Its local parameters (u, v) map to physical source pixel-corner coordinates (s, t) in source-pixel units:

s = O_s + S_s * (i + c + u)
t = O_t + S_t * (j + c + v)

Offsets O_s, O_t are finite. Steps S_s, S_t are independently finite, nonzero and signed; negative steps reverse the corresponding axis. c is zero for PixelCorner (GDAL TOP_LEFT_CORNER) and 0.5 for PixelCenter (GDAL PIXEL_CENTER). The center shift is half a lattice step on each axis, not an additional fixed half source pixel.

A complete cell’s finite bilinear map requires four geometrically valid, finite X/Y node pairs. Only explicit geometry validity or X-nodata rules establish a hole. A node whose X value exactly equals the declared X nodata is missing; a finite Y value equal to a Y-band nodata declaration does not independently remove it. Geometry nodata uses ordinary equality, so a NaN declaration does not compare equal. This geometry rule is separate from imagery’s any-band nodata rule and NaN matching above.

A cell with any explicitly invalid node is a hole. Otherwise, an unmarked NaN or infinity supplies no finite bilinear map and cannot prove absence or uniqueness. Unless the cell can independently be excluded, for example because its clipped physical parameter domain is empty, classification remains unresolved and gives pixel status 3. Metadata admission does not scan or reject these coordinate values.

For encoded node vectors P00, P10, P01, P11, the cell’s mathematical map is below. An inverse of query Q solves F(u, v) = Q in the cell’s domain.

A = P00
B = P10 - P00
C = P01 - P00
D = (P11 - P10) - (P01 - P00)
F(u, v) = A + B*u + C*v + D*u*v

The encoded Float32 or Float64 nodes define this map; Float32 promotion to binary64 is exact. Input quantization and upstream coordinate accuracy are separate from inverse arithmetic error. Separable axes define the same logical cells without expanding their coordinate vectors.

Complete cells and the outer band#

Each complete cell starts with the closed parameter rectangle [0,1]^2. Only the first and last cells in node-index order may change the outer limits, independently on each axis, as the table shows:

Registration

First cell’s lower limit

Last cell’s upper limit

PixelCorner

0

2

PixelCenter

-0.5

1.5

All other limits stay at zero or one. A single cell receives both applicable limits; a corner cell extends on both axes. The polynomial stays unchanged. A boundary cell with an explicitly invalid node supplies no band, and an interior complete cell does not replace it. Interior holes receive no extension or filling. A lattice with fewer than two nodes on either axis has no complete bilinear cells. A missing neighboring cell does not remove a boundary point supplied by a complete cell.

Intersect every complete cell’s rectangle, extended or not, with the preimage of the closed physical image rectangle [0,W] x [0,H]. Apply the same parameter limits and clipping when checking whether a cell with an unmarked nonfinite node can be excluded. For each signed step, compute both physical edge preimages and sort them before intersecting the parameter interval. Node-index order need not be physical source-coordinate order. No tolerance expands an edge or fills a hole.

Multiplicity before sampling#

Classify the inverse set over the union of all these closed rectangles before applying half-open imagery coverage. Only a unique physical source point can be sampled. Reports from adjoining cells count once only when their source points are proved equal; overlapping enclosures or close coordinates do not prove equality. Distinct roots remain distinct however close they are.

Two distinct roots or any continuum of roots mean ambiguity and pixel status 3. One isolated root with another relevant cell unresolved also gives status 3. Absence gives status 1 only after every relevant cell is excluded or proved empty. Whole-grid injectivity is not a precondition: a folded cell can still have a unique inverse for a particular query.

After unique classification, apply the existing sampler’s half-open coverage 0 <= s < W, 0 <= t < H. A unique root on s = W or t = H therefore gives status 1. That same boundary root together with a distinct interior root gives ambiguity status 3, even though only one is sampleable. Imagery mask or nodata failure after a unique, in-bounds inverse remains status 2. Every invalid result receives all-band fill and clear output validity.

Numerical completion and comparison#

Successful inversion requires complete root classification and an enclosure of the unique root in physical source coordinates. The enclosure includes inverse arithmetic and lattice reconstruction error, including signed steps and center/offset cancellation. Coverage, nearest pixel selection and the applicable bilinear nonzero-contributor decisions must be stable throughout that enclosure, or established separately by an exact boundary identity. An interval crossing a coverage edge, nearest floor boundary or contributor boundary cannot silently select one side. Unresolved decisions give status 3.

Nearest preserves the selected native value. Bilinear comparisons use bounds derived from the source-coordinate enclosure, interpolation arithmetic and dtype conversion. Each successful qualification case declares and independently checks its comparison bound; a finite but arbitrarily wide interval is insufficient. Exact integer equality is claimed only when its rounding bin is stable. An otherwise established bilinear result spanning two rounding bins is not by itself a coordinate failure.

These conditions promise neither a universal world-coordinate tolerance nor universal exact output rounding. They do not require adjacent binary64 parameter or reconstructed-coordinate endpoints. Tolerance snapping and a small residual alone cannot establish domain membership, multiplicity or sampling stability.

Dtypes and layouts#

ABI v1 supports native-endian uint8, uint16, and float32. Input and output dtypes and band counts must match the plan. Positive, element-aligned row, pixel, and band byte strides permit interleaved and planar caller-owned storage; negative, zero, or element-misaligned strides are rejected. Source and destination allocations may not overlap.

This three-dtype raster ABI applies to imagery and reducer candidates. Raster terrain has a distinct descriptor and accepts native Int16, Int32, Float32, or Float64 samples. Terrain scale and offset are applied explicitly in binary64; they are not general imagery conversions.

The native TIFF descriptor separately supports UInt8, UInt16, Int16, Int32, Float32 and Float64. Scalar host TIFF reads sample all six at source dtype with the shared bilinear evaluator, then convert into any of the six native destination types; this does not widen CUDA codec profiles or the three-dtype imagery descriptor. In-range Int16/Int32 nodata declarations truncate toward zero for source comparison. Their omitted fill rounds to nearest with half ties away from zero, matching the pinned GDAL stored-nodata interpretation. Ordinary read explicit fills convert directly into the destination under the array contract. These declaration rules do not alter bilinear conversion.

Nearest preserves native values. Bilinear arithmetic uses binary64 and converts integer output with clamping and IEEE ties-to-even rounding. Float32 output uses normal float conversion. cugeo-raster does not apply scale, offset, color conversion, or radiometric normalization implicitly.

Execution#

Host calls are synchronous. CUDA calls are enqueued on the caller’s explicit stream and return a completion handle. The CUDA context used for preparation must be current during preparation and enqueue; query and wait also require that context. Foreign allocations, masks, status buffers, their owners, and the stream must remain valid until a fallible close succeeds. The affine, reproject, orthorect geometry, nvTIFF decode, and nvImageCodec decode *_close_v1 calls activate the stored context, drain only the owned chain, destroy it, and explicitly restore the caller context. Any failure preserves the exact handle for retry, except that caller-context restoration failure is terminal: the process aborts before control can return under the owner context. Legacy void releases and language finalizers are ABI fallbacks that abort if completion, cleanup, or restoration cannot be proven; they never leak and return. Python retains every foreign owner until explicit close succeeds.

CUDA CRS reprojection additionally requires caller-owned, float64-aligned scratch containing four coordinate arrays and coordinate status. Preparation reserves one cugeo-proj workspace for an explicit maximum active destination-pixel count, and enqueue rejects a larger tile before submitting grid work. Destination grid generation, one- or two-stage cugeo-proj transformation, inverse source-grid mapping, and sampling preserve stream order. A nonzero cugeo-proj row status produces pixel status 3 and applies the invalid-output policy without attempting source sampling.

RPC orthorectification CUDA geometry similarly uses caller-owned scratch, status, and a prepared per-context coordinate workspace. Geometry completes before its exact source window can be read. That geometry and its scratch stay live through sampling. The source ROI origin supplied to sampling must match the geometry result.

Terrain and sensor behavior#

RPC offsets denote source pixel centers. A successful ground-to-image result therefore receives +0.5 before entering the pixel-corner sampler. RPC denominator, non-finite, and explicit-footprint failures produce sensor status 5; no source read is attempted for those pixels.

Terrain lookup first maps the destination pixel center into the DEM CRS. Nearest requires its selected DEM pixel to be in bounds and valid. Terrain bilinear sampling requires every nonzero-weight DEM contributor to be in bounds and valid; it retains strict footprint coverage. DEM nodata, coverage, coordinate, unit, or vertical-reference failure produces public status 4. Heights are metres, declared as WGS84 ellipsoidal or orthometric; unknown units, unknown references, and implicit zero height are rejected. Orthometric heights require a declared compound CRS. Each sampled point’s X/Y/height is then converted together to WGS84(G2139) before RPC evaluation, and a point the conversion cannot transform gets public status 3.

Temporal reduction#

Temporal candidates are consumed in strictly increasing scene ordinal with unique stable scene IDs. An invalid candidate does not update reducer state. Selection reducers copy every imagery band from one observation; per-band minimum and maximum are the intentionally per-band exceptions.

Selection ties apply the reducer’s declared time policy, then ordinal policy, then the lowest stable scene ID. Positive and negative zero compare equal and therefore retain the stable tie winner. A non-finite valid imagery value or a non-finite required key, score, or metric is a terminal numerical failure for that pixel.

Exact scalar quantile returns the observed value at lower rank floor(q * (count - 1)). It does not interpolate. Float32 radix ordering treats the two signed zeros as numerically equal and preserves the first observed sign for a stable tie. Host multipass sessions require an identical replay of scene identity, order, schema, and content. CUDA multipass submissions additionally require a caller-recomputed 256-bit digest that attests the exact logical content and layout. The library compares replay tokens but does not independently hash device memory; a stale or forged caller token violates the contract and is not detectable without adding a synchronization boundary.

UInt8/UInt16 checked accumulation uses UInt64 sums and UInt32 internal counts. Overflow never wraps: the output is fill, invalid, numerical-failure status, and no provenance. Float32 accumulation and Welford moments use binary64. Population variance is M2 / count; one observation produces zero variance. Sample variance requires at least two observations. Native integer output is clamped and rounded ties to even.

Composite status has a namespace disjoint from input candidate status:

Code

Input candidate meaning

0

valid candidate

1

masked candidate

2

outside source

3

source nodata

4

coordinate failure

5

terrain failure

6

sensor failure

7

source/read failure

The final output uses a separate encoding:

Code

Final composite meaning

0

valid result

1

no valid observations

2

reducer numerical failure

16

retained upstream masked-candidate reason

17

retained upstream source-coverage reason

18

retained upstream source-nodata reason

19

retained upstream coordinate-failure reason

20

retained upstream terrain-failure reason

21

retained upstream sensor-failure reason

22

retained upstream source/read-failure reason

Plans declare whether upstream reasons are collapsed into candidate-invalid or retained for final status and receipts. Output validity is clear for status 1 or 2, all output bands receive the declared fill, and missing provenance uses the public no-provenance sentinels: UInt64 maximum for scene ID and ordinal, and Int64 minimum for timestamp.