Python facade#

The Python dataset API reads TIFF and JPEG2000. It follows Rasterio naming conventions for datasets, bands, and windows, with a subset of Rasterio’s format, masking, overview, and environment support. TIFF reads use the native host decoder or optional nvTIFF device decoder. JP2/raw-J2K metadata and device decoding use Jpeg2000Source. Metadata inspection needs no device codec; device reads require a build with the selected backend.

Host reads complete before returning. Device reads order writes before subsequent work on the selected stream; consumers on other streams must establish their own dependencies. Request return_receipt=True to wait for a completed read and its receipt. Some codec paths also wait for SDK safety and error reporting.

Readers expose independent uint8 validity through read_masks(), dataset_mask() and mask_flag_enums. Supply a NumPy out for TIFF host masks. CUDA mask kernels are built with the cuda native feature. JPEG2000/SAFE nodata masks also require nvjpeg2k. See JPEG2000 and SAFE masks and the CUDA boundary for supported profiles. read() accepts masked=False; masked=True and MaskedArray output raise code 2 before output mutation or device access. Pixels and masks remain separate arrays.

The reader’s xy() and index() use its stored affine by default. Select transform_method=TransformMethod.rpcs for native RPC point conversion. sample() accepts device points and returns a CuPy point array; see Point samples. The dataset metadata and helpers contract defines affine coordinates and device point arrays. Use cugeo.raster.transform to construct an affine, compute array bounds, or convert coordinates without opening a dataset. xy and rowcol accept scalars and one-dimensional host vectors. Default rowcol floors to signed 64-bit indexes. AffineTransformer captures the affine for repeated calls. See the affine coordinate contract for signatures, pixel offsets and errors.

cugeo.raster.errors exports cuGeo-owned handlers and warning categories. RasterIOError handles missing/corrupt admitted datasets and closed pixel reads; RasterioIOError is an alias to the identical class. Native failures retain .code; binding failures use None unless their operation assigns a code. Ordinary failures carry owned .context with the semantic operation name. errno remains separate. UnsupportedError handles valid unavailable requests; ResourceLimitError handles native allocation/budget limits with code 8. Caller-buffer failures retain code 3. Invalid Python arguments retain their built-in preflight types. A valid unavailable dtype conversion is unsupported.

WindowError remains directly under CugeoRasterError. Wrong-mode writer reads raise UnsupportedOperation, also caught by UnsupportedError and RasterioError. Established creation capability refusals use DriverCapabilityError, also caught by ValueError. Explicit native RPC and warp-option failures use RPCError and WarpOptionsError; warp execution failures use WarpOperationError without hiding capability/resource causes. Direct shared CRS calls retain cugeo-proj’s exceptions.

Body/construction failures stay primary when cleanup fails; the secondary exception is available as .cleanup_error. Successful body execution exposes cleanup failures directly. Partial receipts keep their existing types and meaning. Advanced fallible close retains live handles and backing owners on failure. These handlers add no execution capability, rollback or automatic retry. NodataShadowWarning is emitted by admitted RGBA mask reads when native nodata flags shadow alpha. Four nodata flags emit four warnings per call under warnings.simplefilter("always"), including scalar, repeated and alpha-only selections and dataset_mask(). Explicit masks take native precedence and suppress this warning. Standard Python filters apply at the caller’s location. With an error filter, supplied output bytes, shape, strides, dtype and pointer stay unchanged. Resources acquired during admission follow ordinary cleanup precedence; warning presentation adds no completion wait.

Opening, metadata access, unmasked pixel reads and the masked=True refusal do not emit nodata-shadow warnings. Other color arrangements have no warning rule. NotGeoreferencedWarning is importable; its native GCP-presence fact and reader initialization emission remain unavailable. The exception contract lists the finite hierarchy and classification boundaries.

import cugeo.raster

with cugeo.raster.open("image.tif") as src:
    image = src.metadata.images[0]
    print(image.width, image.height, image.bands, image.dtype)
    tile = src.read(window=cugeo.raster.windows.Window(0, 0, 512, 512))

For RPC imagery, cugeo.raster.plan_rpc_grid(image, height_range=(low, high)) returns a typed proposal containing CRS, transform, shape, resolution, height range, and a short explanation. It inverts nine source-boundary samples per edge at the declared heights on the host and uses cugeo-proj for projected coordinates. By default it chooses the UTM zone at the RPC center; callers may specify a complete CRS and resolution. It raises if an inverse sample fails. An unavailable boundary projection raises raster UnsupportedError; CRS normalization retains the shared authority’s typed failures. Pass the proposal’s geometry to cugeo.raster.orthorectify with caller-owned NumPy or CuPy output. The proposal is a fixed-height envelope, not a terrain-aware guarantee of valid edge pixels.

Sentinel-2 input layout#

Obtain an original Sentinel-2 L1C or L2A product through the Copernicus Browser. Choose a compact product with processing baseline 04.00 or later and unpack it locally. The Sentinel-2 product guide describes the SAFE format and naming convention. Check the product’s terms of use before downloading it. For a small synthetic L1C input, use cugeo-raster/tests/data/sentinel2_safe/S2A_MSIL1C_SYNTHETIC.SAFE from a source checkout. It includes B02 and deliberately omits a referenced B03 file.

Keep the product metadata, tile metadata and referenced images in their relative locations. A compact product has this layout (names are illustrative):

product.SAFE/
  MTD_MSIL1C.xml              # or MTD_MSIL2A.xml
  GRANULE/<granule>/
    MTD_TL.xml
    IMG_DATA/                 # product-referenced JP2 images; L2A uses resolution folders
    QI_DATA/                  # L2A cloud and snow probability JP2 masks

The product XML must reference JPEG 2000 images under that granule’s IMG_DATA directory and contain all 13 spectral information entries. For L2A, the tile XML can reference cloud and snow probability masks in QI_DATA. The tile metadata supplies the CRS and grids; a selected image’s size and any embedded georeference must agree with its grid. References and metadata used by the reader must resolve inside the product. The catalog reports referenced missing spectral files, but opening one fails. It does not discover unreferenced files by scanning the directory. ZIP and remote SAFE access and multi-granule products are unsupported. The separate L1B granule interface is described below.

Metadata discovery runs on the host. Pixel reads require a CUDA build with nvjpeg2k; see the installation guide and capability matrix for the supported JPEG 2000 profile.

Open a Sentinel-2 product#

cugeo.raster.open("product.SAFE") opens a cugeo.raster.io.sentinel2.Sentinel2Product catalog for supported unpacked, single-granule Sentinel-2 L1C or L2A products with processing baseline 04.00 or later. The parser requires a complete 13-band spectral information list. The directory’s MTD_MSIL1C.xml or MTD_MSIL2A.xml path works too. The catalog has no read(); select a band instead:

with cugeo.raster.open("product.SAFE") as product:
    with product.open_band("B02", resolution_metres=10) as band:
        band.read(indexes=1, out=caller_cupy, stream=stream)

open_band returns an ordinary DatasetReader that uses the JPEG 2000 route, and it stays valid after the catalog closes. resolution_metres may be omitted only when the product references the band at one resolution; L2A bands referenced at several resolutions need an explicit choice.

product.open_bands(names, resolution_metres=...) retains an ordered set of spectral bands on one projected grid. Its read_many method returns raw UInt16 NCHW windows, including repeated bands and windows. Omit out to allocate on CUDA or supply packed NCHW device storage with optional batch padding. Set return_receipt=True to receive one receipt for the read.

An L1C or L2A catalog’s subdatasets list gives canonical names for the available 10 m, 20 m and 60 m numeric groups and any referenced 10 m true-color image. L2A lists a numeric group when the product references every member, including the auxiliary layers defined for that grid. Each name contains the absolute XML path and remains usable after the catalog closes.

with cugeo.raster.open("product.SAFE") as product:
    group_name = product.subdatasets[0]

with cugeo.raster.open(group_name) as group:
    rgb = group.read(indexes=(1, 2, 3))

Group reads return raw pixels on the CUDA device as UInt16 for numeric groups and UInt8 for TCI. A scalar index returns HW, and a sequence returns CHW in the requested order, including repetitions. Use read_many for uniform windows. Point sampling and chip iteration raise UnsupportedError (2).

For L1C/L2A, the reader’s CRS, transform, and grid size come from tile metadata and must agree with any georeference embedded in the JP2. band.radiometry is an immutable Sentinel2Radiometry copied from native metadata. Its source_offset has a Sentinel2SourceOffsetState (NUMERIC, NOT_APPLICABLE or ABSENT) and a finite value for NUMERIC, otherwise None. Its conversion is either an immutable Sentinel2Conversion with finite scale and offset, or None. For numeric source offset A and positive quantification Q, the pair is (1/Q, A/Q) when both coefficients are finite. An absent offset, the literal Not applicable, or nonfinite derived arithmetic supplies no conversion.

Catalog crs and radiometry crs, transform and quantification use None for unavailable facts. The catalog requires all these values for admitted modern L1C/L2A products. An absent quantification omits the QUANTIFICATION_VALUE band tag and supplies no conversion. Ordinary reader geometry presents an absent transform as identity, including after refresh(). reader.metadata.georeference.transform preserves the raw None.

scales and offsets expose the established coefficients or the numeric defaults (1.0,) and (0.0,). Check radiometry.conversion to determine availability; the defaults do not establish reflectance. Lower-level band metadata keeps absent coefficients as None with ABSENT status. refresh() preserves the source state and conversion. Other datasets expose radiometry=None. Raw band opening does not require conversion, and stored samples are unchanged. tags() and tags(1) report source metadata. Numeric source-offset tags retain their binary64 values, Not applicable retains its literal, and absent offsets omit the tag. Special-value band tags use complete decimal integers, normalizing signs and leading zeroes. Quantification and numeric radiometric-offset tags use enough digits to retain the binary64 value and may use scientific notation.

Nodata and saturation records may be missing independently. Missing nodata returns None; stored nodata outside the sample dtype range also presents as None, while radiometry and raw band records retain its source value. Each missing special value omits its SPECIAL_VALUE_NODATA or SPECIAL_VALUE_SATURATED band tag. Raw band opening remains available; the reader invents no special code or mask. Supplied special indexes must follow XSD xs:int syntax and signed 32-bit bounds. Fractional, malformed, nonfinite and repeated recognized entries raise code 1. Allowing missing records is more permissive than the schema cardinality; rejecting fractions is stricter than GDAL 3.8.4’s source-metadata parsing.

product.bands lists every spectral JP2 the product references, with its resolution, path relative to product.path, and whether it is present. product.path is the native catalog’s canonical SAFE directory for both directory and named XML entry points, including contained metadata symlinks. missing_spectral_assets lists the absent spectral files. product.assets lists auxiliary images at supported stored resolutions and records each file’s presence. Use product.open_asset("TCI", resolution_metres=10) to read raw UInt8 RGB on its stored grid. L1C admits 10 m TCI. L2A admits 10 m, 20 m and 60 m TCI, and 20 m and 60 m scene classification (SCL), cloud probability (CLD), snow probability (SNW), aerosol optical thickness (AOT) and water vapour (WVP). Omit the resolution when the product references only one grid for the kind.

Read the stored values with an in-bounds integer window at native resolution. reader.sentinel2_asset carries the SAFE grid, scene classes and nodata for SCL, and declared units and quantification for AOT and WVP. The unit for CLD and SNW is percent. The reader retains the source after product close. Use product.subdatasets to discover canonical names for the complete numeric and true-color groups. The L2A numeric groups contain 4, 11 and 7 bands in 10 m, 20 m and 60 m order. Their arrays use UInt16, widening byte-valued auxiliary samples exactly. ZIP archives and multi-granule products are unsupported. The baseline 04.00 floor applies to L1C/L2A. The XML parser rejects DTDs, so no entity or external resource is resolved. The original Sentinel-2A T18TWL L2A baseline 05.12 product qualified on L40S for B02 at 10 m, B05 and B8A at 20 m, and B01 at 60 m. Tests compared raw full, windowed, clipped and reduced reads, Float32 windows, refresh and catalog-close lifetime against GDAL 3.8.4. This result applies to that product and the named reads; it does not qualify every SAFE product.

Standalone PSD15 L1B granules also open through their directory or original S2*_MTD_L1B_GR_*.xml granule metadata. The directory need not end in .SAFE. Their contained manifest.safe supplies spectral references in physical-band order, including B8A and B10; QA assets remain excluded. Each nominal resolution class uses its own XML dimensions. resolution_metres identifies that class; it supplies no metre-valued affine spacing for an unprojected image.

L1B band readers retain raw unsigned 13-bit DN, including values through 8191. They have no affine, map CRS, Q, source offset or reflectance conversion. Convenience scales and offsets remain (1.0,) and (0.0,); these defaults are not physical calibration. Storage precision establishes no saturation code. Native pixel_interpretation retains POINT. These facts survive refresh() and closing the catalog. product.source_metadata and dataset tags() retain baseline, granule/datastrip/detector identity, sensing time, source footprint, incidence/solar angles in degrees, RASTER_CS_TYPE and PIXEL_ORIGIN. Footprint triples describe latitude, longitude and height over EGM96; they are source text, not map geometry or a public GCP surface. No parent product, datastrip, calibration, DEM, geoid or sensor resource is needed for raw reads.

The SAFE reader contract defines contributor requirements for metadata admission, radiometry and source ownership, with implementation gaps stated explicitly.

Dataset properties#

Ordinary properties describe image zero. Per-read image selection leaves them unchanged; use metadata.images[image] for another native image.

Property

Value

width, height, count, indexes

Dimensions, band count and one-based band indexes

shape

(height, width)

dtypes

One NumPy dtype string per band

crs, transform

Shared CRS or None, and a pixel-corner Affine

bounds

Immutable tuple-compatible BoundingBox(left, bottom, right, top)

res

Column and row vector lengths in CRS units

nodatavals, nodata

Per-band dtype-range-filtered values, and the first value

scales, offsets

Per-band coefficients, defaulting only absent facts to 1 and 0

descriptions, units

Per-band text, with empty or absent text represented by None

colorinterp

Per-band ColorInterp members

block_shapes

Detached list of source (block_height, block_width) pairs

Without a source affine, transform is identity. Check metadata.georeference.transform for source presence before an operation that requires a real grid, including DEM orthorectification. For axis-aligned transforms, bounds preserve flipped axis ordering; rotation and shear use all four outer pixel corners. Unknown or unavailable required native meanings raise UnsupportedError with code 2 instead of supplying a default.

meta returns a fresh dict containing exactly driver, dtype, nodata, width, height, count, crs and transform. profile returns a fresh mutable Profile with those values and source block/encoding facts. Its tiled predicate compares block widths with raster width; it does not expose the physical tiled flag. Mutating either mapping leaves the reader and later snapshots unchanged. Profile supports dict construction, copying, update and keyword expansion and rejects the obsolete affine key. The writer still accepts RasterWriteProfile; ordinary profile keyword expansion is not a writer input.

ColorInterp is an IntEnum with the Rasterio 1.4.4 member and alias set, including gray/grey, multispectral and SAR constants. Representing a constant does not admit a native decoding or writing capability. Native JP2 gray and sRGB declarations supply band color interpretation. Unknown declarations raise UnsupportedError with code 2 on ordinary color access. The native JP2 owner supplies ordinary block shapes independently of its physical codec tile facts.

DatasetReader.metadata exposes typed immutable native records. Use metadata.georeference.rpcs or dataset.rpcs for detached rpc.RPC values. Raw dtypes remain DType members and raw georeferencing remains optional. JSON from cugeo.raster.lowlevel.RasterSource.info is a diagnostic surface. ImageInfo.storage_layout maps contiguous TIFF samples to Layout.BIP and separate planes to Layout.BSQ; unknown source organizations remain None rather than being guessed.

cugeo.raster.rpc.RPC carries the Rasterio 1.4.4 constructor fields and from_gdal(), to_gdal() and to_dict() conversions. Its four coefficient lists retain RPC00B ordering. Construction and conversion do not admit an executable sensor model or initialize CUDA. Returned reader values and their coefficient lists remain usable after reader closure; changing one does not change the dataset. Proven absence returns None; malformed stored tags raise RasterIOError with native code 4.

The optional err_bias and err_rand estimates distinguish absent None, unknown -1.0, and known zero. to_dict() includes both fields; to_gdal() omits only None. Unlike Rasterio’s truthiness omission, supplied zero persists through ordinary creation rpcs=value. GeoTIFF encodes an absent estimate as -1, which reopens as -1.0. Native RPC tags use GDAL’s fifteen significant digit decimal view; the typed value retains the stored doubles.

Pass rpcs=src.rpcs explicitly when copying a dataset to a writer. Reader profiles do not include RPCs. RasterWriteProfile.rpcs accepts the same value or GDAL string mapping as ordinary creation. Writer tags derive from the native immutable profile; arbitrary RPC-domain updates remain unsupported.

TIFF RPC tags replace an embedded XML RPC domain. A TIFF with only embedded RPC XML exposes that domain through tags(ns="RPC") and converts rpcs on access, preserving optional errors and short coefficient lists. JP2 top-level RPC XML takes precedence over GeoJP2 RPC tags. Ordinary writer creation stores the sixteen tag-derived keys; bounds and additional mapping keys are not persisted. Frozen dataset metadata remains hashable, and each rpcs getter returns independently owned coefficient lists.

Per-band scale and offset remain convenient optional floats. scale_status/offset_status and the corresponding scale_metadata/ offset_metadata values preserve the three native states: PRESENT, ABSENT, and UNSUPPORTED. Unsupported representation is never reported as absent even though the compatibility float property is None in both cases. TIFF tag projections such as ifd_offset, raw compression/photometric/planar codes, tiff_sample_format, and tiff_extra_sample are typed optional. JP2/J2K metadata reports them as None rather than fabricating TIFF sentinel values.

Dataset coordinates#

Use dataset.xy(row, col, offset="center") to map pixel positions into the dataset’s X/Y coordinate units. The default returns pixel centers; "ul", "ur", "ll" and "lr" select corners. Rotation and shear apply to both the positions and their offsets. Scalars return two Python floats. One-dimensional host sequences or NumPy arrays return two detached float64 arrays; scalars and length-one vectors broadcast to the other vector’s length. An empty vector paired with another empty vector, a scalar or a length-one vector returns empty arrays.

dataset.index(x, y) accepts scalar coordinates and returns (row, col) Python integers. It applies exact floor to the computed native binary64 inverse coordinates, including negative values, without epsilon or snapping. The result can exceed int64 and is never clamped to the image. Pass a callable as op= to process the continuous row and column separately; each result is converted with int(). Callable and conversion exceptions propagate.

import cugeo.raster as raster

with raster.open("image.tif") as dataset:
    x, y = dataset.xy(2, 3)
    xs, ys = dataset.xy([0, 1, 2], 3, offset="ul")
    row, col = dataset.index(x, y)

Coordinates must be finite real host values. Higher-dimensional, string, complex and device inputs raise TypeError; nonfinite inputs, incompatible vector lengths and unknown offsets raise ValueError. index rejects vectors. The default affine selection requires a stored native affine; absence raises UnsupportedError with code 2, including for an RPC-only source. The metadata identity used for absent georeferencing does not satisfy this requirement; a stored identity does. A missing CRS alone is allowed.

Native map admission rejects nonfinite coefficients and singular or unresolved linear parts with CugeoRasterError, code 1. Inversion also requires finite representable inverse coefficients. Computed nonfinite results raise code 1 before floor or op. Closed readers raise ValueError. Returned vectors remain valid after later calls and reader closure.

Select transform_method=TransformMethod.rpcs with TransformMethod from cugeo.raster.enums to use the dataset’s full RPC domain, including runtime initialization bounds. z= supplies height in metres. RPC coordinates are WGS84 longitude/latitude; a stored affine is unnecessary for this selection. Missing RPCs raise code 2. Supply RPC options as keywords to either helper.

cugeo.raster.transform.RPCTransformer(rpcs, **rpc_options) snapshots a named RPC value or a GDAL string mapping. Use it as a context manager for repeated xy(rows, cols, zs=None, offset="center") and rowcol(xs, ys, zs=None, op=None) calls. The module xy and rowcol accept the same RPC inputs and options; get_transformer returns the corresponding constructor. Host shapes, broadcasting, offsets and rounding follow the coordinate rules above. Module rowcol defaults to checked NumPy int64; dataset index returns Python integers. Closing a transformer releases its resources; repeated close succeeds and later calls raise ValueError. Construction decodes a supplied DEM once and retains immutable nodes without a CUDA context; later file changes do not alter them. Module and dataset helpers, suggestions and ordinary reproject calls use bounded native DEM reads instead.

RPC_HEIGHT adds a constant and RPC_HEIGHT_SCALE multiplies the DEM sample: effective height is z + RPC_HEIGHT + RPC_HEIGHT_SCALE * DEM + vertical_shift. With no DEM it is z + RPC_HEIGHT. Polynomial height normalization is separate. RPC_DEM prepares a native raster DEM; interpolation, nodata substitution, SRS and vertical-resource options follow the RPC contract. To apply a compound DEM vertical correction, pass terrain_grid_directory explicitly; raster does not select grids from PROJ_DATA. Missing resources raise their native error, rather than producing successful fill values. Unknown options and unavailable capabilities fail explicitly. Failed or nonfinite computed points raise CugeoRasterError(code=None) with point positions and causes before floor or a user callable; call-level native codes are preserved. Nonconvergence is a point failure, not invalid metadata.

For explicit device forward evaluation, call transformer.transform(xs, ys, zs, out=(columns, rows), status=status, stream=stream). Inputs are contiguous one-dimensional Float64 CUDA buffers; outputs are Float64 and statuses uint8. Omitted outputs allocate with CuPy. The return tuple contains columns, rows and per-point statuses. None selects the current stream; declared producers are joined with events, and retained owners live through completion. The owner admits one in-flight execution. memory_budget_bytes covers admitted backing storage and operation resources. The call prepares and allocates execution resources before submitting work. Each DEM execution copies its immutable nodes into pinned host staging and uploads them on the selected stream. The budget includes retained nodes, pinned staging and device nodes; staging is retained until the execution drains. The execution’s context must remain live through close, while the host transformer can be reused in another context after that execution closes. Device inverse requests raise code 2 without host fallback. Host point inverse and plan_rpc_grid share a native owner, while the planner retains its distinct bounded Newton policy and sampled-envelope promise.

lowlevel.CorrectedRPCTransformer(rpcs, correction=(0,1,0,0,0,1), **rpc_options) adds a native image-plane correction to these host/device point methods. Parameters (a0,a1,a2,b0,b1,b2) map raw centers to (a0+a1*line+a2*sample, b0+b1*line+b2*sample) before the single +0.5 corner conversion. Nonfinite parameters raise RPCError (1). Finite singular corrections support forward calls; host inverse requires a representable inverse linear part (otherwise code 2). Its stopping tolerance uses corrected pixels and promises no global convergence or ground accuracy. Device inverse remains unsupported. Height, statuses, shapes, streams, budgets and retained completion follow RPCTransformer above.

For corrected warped pixels, construct lowlevel.RpcModel(values, correction=parameters) and pass it to the reusable lowlevel.Orthorectify with an explicit Terrain and destination grid. Its host and prepared CUDA paths share the native correction. CUDA geometry and sampling require borrowed arrays ready on the selected stream and reject foreign producer tags. Publish readiness as producer None or that stream; CAI producer stream 0 is invalid. RpcModel.geotiff_values requires an open owner and refuses code 2 for a nonidentity correction. Corrected executable objects cannot be used as plain rpcs= metadata; coefficients, error estimates and file domains remain ordinary detached RPC values.

RpcModel.uncertainty accepts packed host or CUDA ECEF points with explicit correction/mensuration/Up covariance blocks, an ENU anchor, observation epoch and finite-difference step. It returns sample/line derivatives, ENU covariance and Gaussian LE90/circular CE90 predictions with typed row statuses. Supplied output arrays retain their identity. CUDA producer dependencies and native completion retain arrays and owners; wait() and query() observe completion. Missing uncertainty inputs remain typed unknown, including when RPC error tags are zero. See the specialist uncertainty contract for array slices, parameter units, independence, height meaning and numerical admission. These predictions do not establish surveyed accuracy.

Embedded metadata catalogs#

dataset.metadata.images[image].catalog is an immutable native metadata snapshot for that image. It owns dataset and band domains, their listing visibility, ordered key/value or XML items, and band descriptions and units. Closing or refreshing the reader does not change an existing snapshot. Inspection uses host container metadata and requires no CUDA initialization or pixel decode.

import cugeo.raster

with cugeo.raster.open("tests/data/dataset_metadata/domains.tif") as dataset:
    catalog = dataset.metadata.images[0].catalog

description = catalog.descriptions[0]
domain = catalog.domain(bidx=0, name="science")
values = {item.key: item.value for item in domain.items}
assert description.value == "Bänd & 雪"
assert values == {"A": "one", "Z": "µ=3"}

catalog.domain(bidx, name) uses zero for dataset scope and one-based band indexes. Domain names match ASCII case-insensitively and retain their first source spelling. It returns None for an established absent embedded domain. A known domain carries its own status; PRESENT, UNSUPPORTED, and UNAVAILABLE must remain distinct. Incomplete discovery raises UnsupportedError with code 2 for an unknown domain. listed is separate from query availability: the one-band JPEG 2000 IMAGE_STRUCTURE domain can be queryable and unlisted. The empty default name is not listed. origin distinguishes embedded text, encoding facts, SAFE product source fields and RPC semantics.

MetadataItem.key, value and raw come from native extraction. XML items have no key. A key/value domain can have an xml-prefixed name without being an XML storage kind; its raw value retains the native KEY=VALUE spelling. Python performs no metadata XML parsing or numeric role interpretation.

BandInfo.description, unit, description_status, and unit_status expose each band’s text facts. Empty reference descriptions and units are absent. Numeric scale/offset roles and text roles remain local to each TIFF directory. The native georeference keeps a missing affine absent; metadata presentation supplies identity only for the ordinary transform. It does not admit an ungeoreferenced source to an operation requiring a real grid.

The catalog reads TIFF GDAL metadata, common TIFF text tags and XMP; JP2 GDAL multidomain XML, raw XML associations and XMP; and the existing SAFE source-text owner through product.metadata_catalog. An opened SAFE band retains a native associated catalog: product and selected-band default tags replace physical JP2 defaults, while named physical domains survive. Its source tags remain readable after product closure and reader refresh. IMAGE_STRUCTURE uses encoding facts. Uninterpreted TIFF source-color/sample encodings and JPEG 2000 component or tile coding overrides retain an unsupported structural domain. JPEG-compressed TIFF structural metadata and TIFF band structure at precisions outside 8, 16, 32 or 64 bits are also unsupported. Unknown JP2 UUID metadata, non-UTF-8 association labels and uninspected TIFF EXIF, ICC or Photoshop/IPTC metadata make discovery unavailable. SAFE discovery also remains unavailable outside the fields its semantic owner supplies. The native RPC owner supplies tags(ns="RPC") from the same tag or embedded text domain as dataset.rpcs. PAM sidecars and synthetic subdataset discovery are not supplied by this catalog. Raw XML/XMP payloads are copied without XML parsing, up to the first NUL byte. A raw payload or TIFF text tag that cannot be represented as UTF-8 marks its domain unsupported while preserving source inspection. Structured GDAL/GML metadata is parsed natively; malformed admitted XML raises an I/O error with native code 4. Structured XML exceeding 128 nested elements, 1,024 namespace declarations, one million nodes or 64 MiB of source/serialized text raises UnsupportedError with code 2 and a resource-limit diagnostic. A tag with more than 256 attribute names, namespace declarations included, raises CugeoRasterError with code 1. Container byte limits also apply. XML parsing resolves no external entities or sidecars.

TIFF/JP2 metadata compatibility targets ordinary, well-constructed producer metadata, including GDAL-produced forms. Unusual processing-instruction serialization/admission and Unicode XML attribute-name admission can differ from GDAL 3.8.4; Unicode text keys and values remain supported. Supported GMLJP2 xml:gml.root-instance metadata is exposed by both native and GDAL. Additional raw XML association domains that GDAL does not expose, such as xml:other, are a native extension. The metadata compatibility scope defines these differences and structured source authority.

tags(bidx=0, ns=None) returns a fresh dict from the native catalog. Dataset scope is zero; band indexes are one-based. None and "" select the default domain. tag_namespaces(bidx=0) returns a fresh list of listed nondefault domains in source order. A known absent domain returns an empty dict; unsupported or unavailable discovery raises UnsupportedError with code 2.

Domain lookup is ASCII case-insensitive, but XML presentation first checks the caller’s case-sensitive xml prefix. That prefix returns {ns: first_raw_item}; other queries return key/value entries split at their first equals sign. Keyless raw strings contribute no key/value entry. The upper-case XML query behavior uses this key/value model because the pinned reference crashes for that form. Python parses no XML to produce these values.

Reader driver and typed metadata.driver report GTiff or exactly nvJPEG2000. That JPEG 2000 name identifies a driver family; execution receipts establish which codec actually ran.

Affine transforms#

cugeo.raster.Affine and cugeo.raster.io.Affine are the upstream affine.Affine class. Public transform arguments, including reusable plans, require that class. Dataset and grid transforms map pixel corners to world coordinates and can be passed directly to write profiles, reprojection and orthorectification. warp_affine takes a destination-to-source pixel map. For grids in the same CRS, compose source pixel-to-world transform S and destination pixel-to-world transform D as (~S) @ D.

Construct Affine(a,b,c,d,e,f) in Python matrix order. For explicit GDAL coefficient sequences use Affine.from_gdal(c,a,b,f,d,e); to_gdal() returns that native order. A raw sequence is rejected with TypeError. Use @ for composition and coordinate application, and ~ for inversion. Upstream mathematical operations do not perform raster numerical admission; each operation retains its native finite, determinant and inverse requirements.

CRS metadata and write profiles use cugeo.proj.CRS, identically reexported as cugeo.raster.CRS. Type, axes, units and semantic equality come from linked PROJ. Writer inputs normalize with CRS.from_user_input; native validation admits only complete two-dimensional geographic or projected definitions representable by EPSG GeoKeys. CRS84 can serialize as EPSG:4326 under traditional raster X/Y mapping while public equality keeps their declared axes distinct. Unsupported stored CRS interpretation raises a typed capability error; None means absent CRS. Pixel reads and raw native metadata inspection remain available when interpretation is unsupported. Returned CRS values outlive the reader.

Layouts and caller output#

Allocating ordinary file reads return CuPy arrays on the calling thread’s current device. On host-only native builds, ordinary DatasetReader.read() allocates NumPy for supported reads when no CUDA context, stream or device codec backend is requested. Host selectors include "auto", "native", "native-tiff" and ReadBackendPolicy members. Explicit device requests retain typed missing-capability errors. Batch, iterator, mask and submission allocation keep their CuPy requirement. A scalar band index returns HW; sequences and all-band reads return CHW, retaining C=1. Stacks use NCHW. Physical packing is independent of axes: a CHW view may expose interleaved BIP storage. There are no axis-presentation keywords or HWC inference, including when axis lengths are equal.

For ordinary CUDA read(), read_masks() and dataset_mask(), the CuPy allocator governs a result that cugeo-raster allocates without memory_budget_bytes or a ReadPolicy. On routes with the default 64 MiB workspace budget, that budget covers intermediate backings and known host records and staging. Codec scratch uses its own resource limits. An explicit memory_budget_bytes or applicable ReadPolicy includes the complete result backing on routes that accept those controls. Supplied CUDA out arrays remain part of backing admission on those routes. Budget exhaustion raises ResourceLimitError. CuPy reports output allocation failures. Batch plans and chip iterators have their own budgets.

Supplied NumPy output selects a supported host route without importing CuPy or initializing CUDA. CUDA output selects a supported device route. The returned output is the supplied object. Its positive, sample-aligned strides and accessible forward extent are authoritative. Host paths accept admitted crops, steps and padding; packed-only codecs refuse unsupported valid packing with UnsupportedError. TIFF device decode requires all source bands in source order. JPEG2000 device decode preserves the requested band order and repetitions. Missing CuPy, CUDA or codec capability raises an explicit error.

import numpy as np
import cugeo.raster

window = cugeo.raster.windows.Window(10, 20, 64, 64)
out = np.empty((3, 64, 64), dtype=np.uint16)
with cugeo.raster.open("image.tif") as src:
    assert src.read(window=window, out=out) is out

Bands, windows, output shape, and resampling#

The resampling interface contract defines the enum, argument/property and admission-error contract. cugeo.raster.enums.Resampling is a cuGeo-owned IntEnum with Rasterio 1.4.4 IDs 0–14. Pass Resampling.nearest, Resampling.bilinear, or an integer scalar (including NumPy integers and external integer enums). Booleans, strings, floats, arrays and None raise TypeError; unknown IDs raise ValueError. Recognized methods unavailable to the selected operation raise UnsupportedError with code=2 before submission or output mutation, including direct decode. Only nearest and bilinear execute, within the route limits below.

Imagery plans and helpers use resampling, and readable plan properties return canonical cuGeo enum members. Reads, affine warp, reprojection and sample-minimum default to nearest. Orthorectification and raster terrain default to bilinear; the file helper selects terrain with terrain_resampling. Native JSON explanations retain their interpolation keys and lowercase method text. SurfaceGeometryPlan DEM preparation and angular/LUT/lattice interpolation retain their separate interpolation contracts.

indexes uses one-based Rasterio-style numbering and accepts an integer or a sequence. An integer produces a two-dimensional host result. An ordered sequence preserves selection, repetition, and ordering. The native TIFF leaf still decodes all stored bands, so subsets use an explicitly receipted host staging route rather than pretending the codec performed band selection. Device decoding uses all source bands internally. Native JPEG2000 nearest reads finish scalar HW and ordered/repeated CHW selections on device; other device decoding retains its source-order selection restrictions.

Window(col_off, row_off, width, height) is a frozen, hashable value with real scalar fields. Offsets may be negative or fractional; lengths may be zero or fractional but cannot be negative. Readers also accept external objects with these four named fields, without importing Rasterio. Ordinary reads accept row-first endpoint pairs or slices, such as window=((20, 24), (10, 16)). Open stops and dimension-relative negative endpoints use the selected image’s dimensions. Slice steps are ignored. Flat four-tuples raise TypeError; construct a Window explicitly.

cugeo.raster.windows exports Window, plus crop, transform and bounds. Window methods include from_slices, flatten, todict, toranges, toslices, crop, round_offsets and round_lengths. Ranges and slices are row-first; flatten() returns constructor order. Nonfinite fields can be stored but geometric evaluation raises ValueError. Malformed inner slice pairs and missing dimensions raise cugeo.raster.errors.WindowError, a cuGeo exception derived from CugeoRasterError. Native translations retain their .code.

src.window_transform(window) translates the dataset Affine by the requested column and row offsets, preserving rotation and shear. src.window_bounds transforms the bottom-left and top-right window corners; it does not return the four-corner envelope of a rotated grid. These helpers do not clip or scale the requested footprint and do not require pixel execution support. For pair forms, metadata helpers evaluate open stops and negative endpoints with zero height and width, following Rasterio. Module bounds(window, transform, height=0, width=0) accepts explicit dimensions for that evaluation.

Host TIFF reads into NumPy output and direct TIFF/JPEG2000 reads into CUDA output accept bounded fractional and clipped windows with nearest or bilinear source-typed sampling followed by native storage conversion. New fractional or clipped bilinear reads require source span divided by output size to be at most one on each actual selected-grid axis. Existing host TIFF and JPEG2000 in-bounds integer bilinear reductions keep their point-sampling behavior. Integer boundless nearest reads retain the requested footprint and fill uncovered output, including wholly outside requests. Fractional boundless and boundless bilinear execution raise UnsupportedError with code 2 before writes. Advanced batches, plans and chips retain their integer execution scope. CUDA TIFF retains its existing UInt16 C3 stripped and UInt16 C1 tiled Deflate profiles, base IFD and pitched BIP output. Bilinear reductions remain unsupported on CUDA TIFF. Allocated empty read() results follow the same residency rule without decode: NumPy for host-only allocation, otherwise CuPy. Explicit empty out or out_shape raises ValueError; empty-to-nonempty resampling raises UnsupportedError. No Python pixel fallback is used.

read(out=..., out_dtype=None) uses the supplied output’s dtype and returns that exact object. Native-endian UInt8, UInt16, Int16, Int32, Float32 and Float64 destinations admit every native conversion pair. Device codecs retain their source-profile admission. Strings, NumPy dtype objects and scalar types normalize through NumPy; malformed spellings raise TypeError even with supplied output. A recognized ignored out_dtype need not be executable. Other numeric destinations and non-native byte order raise code 2; nonnumeric and boolean destinations raise TypeError.

Allocating reads select out_dtype or the source type and retain the allocation residency described above. Admitted empty allocations retain the requested dtype and rank. Conversion applies no scale or offset, and leaves source metadata and masks unchanged. Integer destinations saturate; float-to-integer half ties round away from zero and NaN becomes zero. Bilinear first rounds to the source type using the sampler’s ties-to-even rule. See the numeric contract for floating overflow, subnormals and signed zero.

out_shape follows Rasterio’s (bands, height, width) spelling, or (height, width) for a scalar band index. A differently shaped NumPy out also requests resampling. Supplying both out and out_shape raises ValueError. Scalar read accepts keyword-only boundless=False and fill_value=None. With a window, boundless nearest uses the source nodata or zero as omitted fill. Explicit fills convert directly to the effective destination dtype, with saturation and half ties away from zero. Bounded nearest with explicit fill replaces only samples whose resolved per-band mask is zero. Without explicit fill it preserves stored samples, including invalid samples. An explicit boundless window preserves all in-image samples and fills padding only. With no window, boundless=True follows bounded behavior. This fill policy follows Rasterio 1.4.4; the nearest spatial center map retains the window contract’s conventions. Non-nearest bounded explicit fill and device bounded fill outside native JPEG2000 nearest raise code 2. Nearest preserves stored samples independently in each selected band; bilinear follows the shared any-band nodata and ties-to-even pixel contract. JPEG2000 reads default to OverviewPolicy.AUTO: cugeo-raster selects the coarsest codestream resolution that stays within GDAL’s strict 1.2 oversampling threshold. If that selected grid exactly matches the requested shape, the codec writes it directly and no affine kernel runs, even when the request says resampling=Resampling.bilinear. overview_policy="base" forces level zero and therefore the exact full-resolution affine semantics. An explicit discard_levels overrides automatic selection; a nonzero value conflicts with overview_policy="base". TIFF remains at its explicitly selected image/IFD. Device resampling is never silently staged through the host.

Set return_receipt=True to receive (array, DatasetReadReceipt). The receipt identifies the storage/parser/codec route, fallback, output residency, synchronization and wait count, transfers, known memory, hidden copy bytes, requested/effective JPEG2000 decoder partitions, and explicitly unknown foreign-codec facts. output_bytes is the logical result size. allocated_output_bytes records the addressed extent of an allocated result, and caller_output_bytes records the addressed extent of supplied output. Intermediate device capacity, retained host bytes and codec scratch have separate fields. Host calls are synchronous and report zero explicit waits. Completed scalar device receipts report their actual completion waits. Plain nvTIFF array reads establish selected-stream ordering and retain execution resources for background retirement; they do not return a completed receipt. Sampled TIFF reads queue the sampler on the selected stream after the decoder’s completion dependency, including default streams. A completed receipt waits for the retained execution. A partitioned JPEG2000 call reports one completion wait per decode job. Native tile jobs may outnumber decoder workers; reduced-resolution and affine calls wait per lane. overview_policy, source_resolution_level, source_resolution_shape, and resampling_executed distinguish codec-resolution selection from affine work. None means unknown, never zero.

Host TIFF and sampled CUDA TIFF/JPEG2000 receipts expose requested_window, effective_window, coverage_window, decode_window and destination_to_source in the selected image’s pixel frame. sampling_destination_to_source maps into the actual selected sampling grid, identified by source_resolution_level and source_resolution_shape. decode_window is the actual ROI in that grid, including contributing halo. executed_sampling records the sampler method; direct codec copies do not execute a sampler. Host sampling uses native scratch; TIFF and JPEG2000 sampling use device scratch ordered after decode. Wholly outside boundless requests fill without a nonempty decode.

Pixel qualification uses GDAL 3.8.4 Warp and independent analytic geometry; Rasterio 1.4.4 defines API and argument expectations. Ordinary RasterIO filters have separate conventions. For example, a three-row source [10,20,30], window Window(0,1,1,5), output (3,1) and fill 99 gives [20,99,99] under the approved center map; Rasterio boundless read gives [20,30,99]. The middle source center is y=3.5, outside height 3. Integer bilinear half ties and whole physical singleton sources also have documented read-filter differences. These reads do not promise unrestricted RasterIO pixel or mask equivalence. Computed bilinear values use natural binary64 arithmetic. At a non-dyadic integer half tie, a small arithmetic difference can select an adjacent integer rounding bin. Qualification derives allowed rounding bins from independent unconverted values and the declared small tolerance; stable bins stay exact. Exactly representable tie cases retain ties-to-even conversion.

A native nearest JPEG2000 read into caller-owned CUDA output needs no explicit stream, context handle, or codec-capacity arguments. This includes resizing, fractional/clipped bounded windows and integer boundless padding. Before calling read(), make a compatible CUDA context current on the calling thread; the managed decoder streams use that context. After a direct partitioned read, keep it live until the cached group retires or the dataset closes. All compatible JPEG2000 reads share the current CUDA context’s native pool. Device scratch grows on demand up to available CUDA memory, with at most 256 device records. Pool info reports the maximum native size for device capacity. Pinned limits are 64 MiB and 128 records. Two banks each schedule up to eight tile-aligned lanes; scalar and batch executions share sixteen native state slots. Byte backing and SDK states grow on demand. Preparation retains an immutable source binding without holding a slot.

Pass jpeg2000_pool to ordinary reads to use an explicit pool; low-level source preparation and reads accept pool. Omitted scratch limits inherit that pool’s policy. Explicit scratch limits must match it; they do not resize it. max_compressed_bytes is checked for every operation, including a cached snapshot. decoder_partitions selects the decoder stream count, independently of available native slots. The route determines the job decomposition. Explicit partition counts do not downshift; "auto" may downshift for the tile grid. Eligible full-image native reads schedule individual native tiles, largest area first. One submitting thread fills the streams and observes completion before reusing each slot. It retires its own work before waiting for shared native slot availability.

An open source retains one compatible group of managed streams, prepared handles and one host controller for direct partitioned reads. Context, stream count, compressed ceiling, scratch limits and explicit pool select compatibility. A change retires the group before replacement; a failed read drains submitted work and retires it. Concurrent direct partitioned reads and source close serialize. Closing the source releases the group. Completed reads retain neither caller output nor its views. Affine reads keep their per-call lanes.

For asynchronous full native-resolution, single-component UInt8/UInt16 JPEG2000 reads, use DatasetReader.submit(out=..., stream=...). SAFE band readers share one single-tile submission queue per context, pool and slot setting; standalone readers have independent queue groups. Outstanding output spans are reserved across every pool/slot setting in one group and context until safe completion or failure drain, before readiness is published. Cached configurations retain the supplied pool object and its native pool reference until the group closes. Closing a band reader retires its preparations; the catalog and pending owners can keep its queue’s streams and pool alive. A closed explicit pool is rejected on every submission; its idle cache is retired by a subsequent submission. A successfully drained failed queue is closed and replaced on retry; cleanup failure retains its owners and reports a coded error. DatasetReadPending.complete() returns the caller output and its DatasetReadReceipt. Pending owners retain bindings and output after reader/catalog closure. The SAFE submission example describes admission, producer ordering and completion lifetimes.

Cached preparations retain the selected native pool, its memory resources and any admission reservation until the group retires or the source closes. Closing an explicit public pool handle releases only that handle. Explicit resource close raises code 3 while the cache still retains it. Close the dataset or replace its cached group with a read using a different live pool, and release the remaining pool references before closing the resources. The context default also remains owned by its registry until Jpeg2000Pool.shutdown_default(); closing a dataset does not shut it down.

CUDA contexts are caller-owned borrows. Cached resources extend how long their context must remain live; retaining the pool does not retain the CUDA context. The ordinary reader does not call cuDevicePrimaryCtxRetain. Keep every cached group’s context alive through retirement or source close. To tear down a context, first close its readers and pending/prepared owners, then close explicit pools and resources and shut down its default pool while that context is current. Release caller CUDA buffers, streams and context references before resetting or destroying it. A caller’s primary-context retain is separate ownership and does not protect resources from an explicit primary-context reset. External reset or destruction while cuGeo owners remain live is outside the supported lifetime contract; subsequent reads, close and finalization cannot safely recover it.

Storage bytes count source loading during the call, so compatible repeated reads report zero. Retained compressed bytes count the shared snapshot once; scratch capacities and high-water observations describe the shared pool rather than a sum over jobs.

Affine lanes own conservative decode ROIs and disjoint destination views; interpolation halos may make decoded bytes exceed the source logical byte count. Device output capacity remains caller-owned. Execution uses the caller’s stream, including both decode and sampling; preparation’s stream is a convenience default for low-level prepared calls.

Persist a dataset mask#

DatasetWriter.write_mask(mask, window=None, *, stream=None) writes an internal full-resolution GTiff dataset mask from HW Boolean or uint8 input. True and nonzero bytes reopen as valid (255), independently of nodata and alpha. The first partial write leaves other pixels invalid; later calls replace the addressed region in order. Positive host strides and tight CUDA HW input are supported. CUDA input uses the selected current or explicit stream, ordered after its producer; mutation completes before return and transfers only encoded bits. See raster writing for an example, restrictions, ownership and receipt fields. CHW presentations, including a singleton band axis, and scalar Boolean fills are unsupported (code 2); supply an HW plane explicitly.

Independent TIFF masks#

Call read_masks(indexes=..., out=...) with uint8 output. Scalar indexes use HW; a sequence, including a singleton, uses CHW and preserves order and repeated bands. dataset_mask(out=...) takes HW output and combines all resolved band masks after nearest sampling. Both methods return the exact supplied object, including positive-stride slices. Zero is invalid; every nonzero byte is valid. Alpha masks retain coverage bytes between zero and 255.

mask_flag_enums returns one list per default-image band, containing MaskFlags.all_valid, per_dataset, alpha, or nodata in numeric order. An explicit per-band mask can have an empty list. Flags describe the selected source and remain independent of the pixels a window happens to cover.

Native discovery gives an associated internal one-bit TIFF mask precedence over an external byte .msk, effective nodata, eligible alpha, and all-valid. Host masks support none/LZW/Deflate on the portable TIFF profiles, including byte and UInt16 gray-alpha/RGBA. Composed host reads require FillOrder 1 for scalar imagery and byte sidecars; one-bit masks support both TIFF bit orders. UInt16 alpha scales to uint8 while retaining a nonzero value for every positive sample. Raw nodata metadata remains separate from comparison in the source dtype. Undeclared zeros and NaNs are valid.

Mask reads share pixel selection, normalized windows, output dimensions and nearest sampling. Fractional/clipped bounded windows, resized grids and integer boundless windows are admitted; padding is zero. Non-nearest masks raise code 2. TIFF uses the explicitly selected image/IFD. Its associated mask overview is used when present; otherwise the base mask supplies the requested grid. Requests that depend on PAM validity, NODATA_VALUES tuples, unqualified associations or unsupported mask profiles raise code 2. A required unreadable, corrupt or dimensionally mismatched sidecar raises I/O code 4. There is no lower-priority all-valid retry.

refresh() opens a replacement native source/sidecar snapshot using the path captured at open. It retains mask-discovery failures for a later mask request, as open does. Existing source owners retain their established descriptors; returned host arrays retain their values after reader close. Concurrent file modification between independent data and mask reads has no isolation guarantee. Mask receipts identify the host route and geometry; unmeasured storage, decoded-byte and workspace facts are None.

TIFF device masks and ordinary nearest pixels require cuda,nvtiff. Admitted little-endian classic TIFF profiles use contiguous UInt8/UInt16/Float32 imagery, up to four gray/RGB components, and none/LZW/Deflate compression. Byte-mask storage is admitted independently; external separate-plane NONE masks use native block assembly. Internal uncompressed one-bit masks unpack on the GPU; compressed one-bit masks refuse before writes. Eligible gray-alpha/RGBA UInt8 and UInt16 masks retain partial coverage. Device arrays support current/default or explicit streams, ordered/repeated selections and positive padding/strides. See the CUDA mask reference for resource accounting, ownership and codec limitations.

JPEG2000 and SAFE masks#

mask_flag_enums reads frozen native source facts without CUDA. It reports established native nodata or proven all-valid channels. SAFE sources preserve inherited nodata presence and absence after catalog closure; stored DN and saturation remain independent of validity. Alpha, external .msk/.MSK, PAM validity and required uninspected metadata refuse code 2. Inspected GeoJP2 metadata does not inherit the embedded TIFF’s pixel nodata, alpha or masks.

With these native features, read_masks() and dataset_mask() allocate CuPy or write supplied CUDA Array Interface output. Scalar indexes use HW, sequences use CHW, and order/repeats and positive strides are preserved. Nodata masks compare native decoded source samples before conversion or fill. All-valid and uncovered requests need no pixel decode. Native and selected codec resolutions share the existing nearest window planner; bounded resizing, fractional/clipped windows and integer boundless padding are supported. Mask padding is zero. NumPy JPEG2000 masks remain unsupported and do not initialize CUDA or copy decoded pixels to the host.

The methods accept discard_levels, max_compressed_bytes, device_scratch_bytes, pinned_scratch_bytes and jpeg2000_pool. Omitted resolution selection uses overview_policy; base conflicts with a nonzero explicit level. Decoder-backed full-source native and exact selected-resolution masks use tile-aligned source partitions. Resizing and other admitted nearest windows use disjoint destination partitions with the original global geometry. Explicit counts retain native tile-grid and nonempty destination-size constraints. Non-nearest masks, nvImageCodec and host worker/policy/cancellation controls refuse code 2. A proven all-valid mask needs no decoder and reports zero effective decoder partitions. Source or codec capability failures never select a host fallback.

Work uses the selected caller/current stream. Plain output arrays retain their native source, decoded ROI, codec/pool resources and producer joins through the existing background retirement owner, including reader close. A completed receipt waits. An explicit memory_budget_bytes includes complete output and intermediate device backings. An allocating mask read with the implicit budget charges its workspace separately from its CuPy result. Codec scratch uses the supplied pool’s finite resource limits. Receipts distinguish mask output from decoded ROI storage, preserve cumulative codec scratch scope, and leave unexposed foreign costs unknown.

Ordinary nearest pixel reads preserve each band’s stored samples. Pixel band subsets/repeats and bounded explicit fill use the retained native decoder and common CUDA finishing stage. Supplied positive-stride HW/CHW outputs preserve identity and padding; read-time dtype conversion refuses code 2. Full-source native, exact selected-resolution and base-resolution resized reads preserve the existing partition planner’s count and geometry constraints. Other explicit window/partition combinations refuse code 2. Plain composed arrays retire asynchronously; completed receipts wait. An explicit boundless window fills padding only; window=None uses bounded semantics even with boundless=True. Masks remain separate from pixels and from the chosen fill value.

Composed pixel reads charge known native source, plan, preparation and execution payloads against the workspace budget, alongside intermediate device backings and common mask records. An explicit memory_budget_bytes also includes the complete result backing. Compressed snapshot capacity and shared plan payloads are counted once. Allocator bookkeeping, source metadata and foreign SDK/pool controls remain unexposed; the receipt’s memory_accounting states that scope. All-valid masks skip decode while still charging an existing retained native snapshot. Failed execution close keeps its owners for retry through reader or source close, or the next read; an unsuccessful retry retains them.

Native batching#

DatasetReader.read_many() accepts windows or existing ReadRequest values. TIFF collections retain typed ReadBatch structure; allocating collections contain CuPy images with the single-image rank rules. Explicit NumPy collections use native host batching. Native host plans require explicit host output when executed through the ordinary facade. JPEG2000 device batches and explicit TIFF nvCOMP batches retain stacked NCHW output, including C=1 for scalar indexes. Physical BIP/BSQ classes come from strides. Supplied output retains identity. Device routes retain their existing profile and band-selection restrictions. return_receipt=True is a completion boundary for device reads. Allocating TIFF collections always return a completed ReadBatch, including its completed receipt, regardless of return_receipt; each constituent read waits for completion before the next one.

read_many, plan_reads, submit_many and iter_chips accept one optional out_dtype for allocated results. Supplied outputs determine their own dtypes after the option is normalized; separate host outputs can differ in dtype. Omission preserves each source type, without promotion. A plan freezes its effective dtypes and strides; a conflicting execution out_dtype raises ValueError before output mutation. Queued submit uses its mandatory output’s dtype and accepts the same ignored, normalized option. Completion includes conversion, with source scratch and destination retained through failure draining.

import numpy as np
import cugeo.raster

windows = tuple(cugeo.raster.windows.Window(i * 8, 0, 8, 8) for i in range(64))
outputs = tuple(np.empty((3, 8, 8), dtype=np.uint16) for _ in windows)
with cugeo.raster.open("image.tif") as src:
    batch = src.read_many(windows, out=outputs)
    assert batch.outputs == outputs

TIFF NumPy batching selects the native host backend. Tiled UInt16 C1 Deflate device batches use backend="nvcomp" or a CUDA out= and return a stacked CUDA array; return_receipt=True adds a DeflateTiffReceipt. The Deflate TIFF reference defines the supported profile, integrity checks, asynchronous submission, and chip iteration. memory_budget_bytes sets the retained plan capacity for TIFF batches with explicit NumPy outputs. CUDA batches reject that argument with ValueError before output allocation or submission. For CUDA TIFF, set device_scratch_bytes to cap retained device scratch. For JPEG2000, set arena_capacity_bytes when creating the pool and pass it as jpeg2000_pool.

The JPEG2000 route is also one native call: Rust validates the complete batch, groups windows by native codec tile, and controls up to eight decoder lanes; CUDA gathers chips into the caller’s output. A tile is decoded once per batch when every window mapped to it stays within that tile. Tile-crossing windows remain valid and use independent nvJPEG2000 ROI decodes. The receipt reports route, request and decode counts, reused requests, lane and wave counts, blocking waits, the internal device arena, transfers, shared compressed snapshot bytes, and exposed codec scratch high-water marks. There is no GDAL, Rasterio, codec fallback, host pixel staging, or per-request Python worker pool. JPEG2000 read_many, submit_many, and iter_chips accept an ordered sequence of one-based indexes, including repetitions. Every result uses NCHW, including a single integer index. A supplied device batch keeps its identity and uses its strides to select physical BIP or BSQ.

requested_bytes and output_bytes count logical destination samples at the output dtype, excluding batch padding. decoded_bytes counts logical samples from each tile or ROI that the decoder produced, at the source dtype, including repeated decodes during capacity retries. A failed decoder invocation can leave the decoded total unknown. Optional facts with no reported value appear as None. Arena, mapping, and current native byte counters describe the shared pool at completion. Scratch peaks and allocation counts follow the lifetime of their provider.

A source caches an immutable compressed snapshot. Prepared bindings and retained operations keep that snapshot and its resources alive after source or dataset close; closing a handle releases its reference. The selected pool retains its native decoder until its final native users close. Decoded tiles remain batch-local; the API keeps no persistent decoded-pixel cache between calls.

import cupy as cp
import cugeo.raster

windows = tuple(cugeo.raster.windows.Window(x, y, 256, 256) for y in range(0, 1024, 256)
                for x in range(0, 1024, 256))
out = cp.empty((len(windows), 1, 256, 256), dtype=cp.uint16)
with cugeo.raster.open("B02.jp2") as src:
    out, receipt = src.read_many(
        windows,
        indexes=(1,),
        out=out,
        return_receipt=True,
    )
assert receipt.route == "tile-reuse"
assert receipt.decode_count == 1

All descriptors, windows, checked byte arithmetic, the complete output span, and CUDA context ownership are validated before decode or output mutation. Output pointers and strides must be aligned to the destination item size. read_many() completes synchronously. A source retains its compressed snapshot; the selected pool retains the decoder, reusable lanes, mapping buffers and two-bank arena. Different source bindings share that executor without replacing retained metadata. Parsed SDK streams and states are claimed only by executions. The SDK’s required host-observed synchronization precedes state reuse.

The selected JPEG2000 pool sets the decoder lane ceiling per bank, the aggregate arena capacity, and the device and pinned memory limits. Create a Jpeg2000Pool with decoder_lanes, arena_capacity_bytes, and finite device and pinned resources, then pass it as jpeg2000_pool. The default lane ceiling is eight, and the useful warmed count may grow for later requests.

The device provider’s hard cap N covers both arenas, device maps and SDK callback scratch, including replacement overlap. Pinned maps and SDK staging share the pinned provider’s separate finite cap. Caller output, compressed snapshots, affine scratch and physical driver/runtime overhead are outside N. Allocation calls may synchronize. Native scheduling uses useful decode units and may fit smaller candidates within the same policy. A proven capacity failure is code 8; shared bank or slot contention does not shrink the schedule.

Allocating batches and chip iterators initialize CuPy’s normal current-device stream before resolving an omitted pool. Caller-supplied output still requires a compatible current context. An explicit batch context is activated for pool resolution, output allocation and submission, then the previous context is restored. Keep that borrowed context and the operation stream alive through pending completion.

submit_many() returns None before work when shared admission would block. Synchronous reads wait for availability outside lifecycle locks. A caller holding pending work must drain it to permit progress. Closing a source or pool handle releases that reference; explicit pool shutdown stops new acquisitions while retained executions remain valid.

For low-level source batch methods, device_resource and pinned_resource, when supplied, must be the exact selected pool’s resource owners. They do not configure a source-private cache. All decoding routes resolve the native context default when the pool is omitted.

decoder_reused and lanes_reused identify reusable resources. Allocation counts, scratch high-water values, native_retained_bytes and native_peak_bytes are cumulative facts from the shared providers, including their other users. They are requested-byte accounting, not per-operation attribution or physical memory. native_capacity_bytes is effective N; effective_pinned_capacity_bytes is the pinned hard cap. mapping_bytes reports retained device mapping capacity across both banks. host_to_device_bytes measures gather mappings; SDK compressed staging transfer bytes remain unknown. duration_ns includes time the caller holds a pending batch.

Native UInt8/UInt16 values are preserved; normalization, band assembly, model metadata, tensor framework conversion, and inference remain outside cugeo-raster.

For the common fixed-chip case, iter_chips() owns the planning choices:

with cugeo.raster.open("B02.jp2") as src:
    for batch in src.iter_chips(256):
        consume(batch.data)  # NCHW CuPy view; may share a full backing allocation

batch_size is a hard delivery maximum, defaulting to 128. JPEG2000 fills deliveries when working-set admission permits; resource pressure and the final delivery can produce shorter batches. Physical decode groups can span several deliveries to reuse a codec tile. Native planning schedules physical units across decoder lanes, independently of the delivery maximum. Admission can split a group into submissions; up to two admitted submissions are prefetched. Chips stay within codec tiles when possible; edge windows overlap inward to cover the stored image without padding. Each ChipBatch carries its source windows and submission receipt. Views of a submission share its full output backing and receipt; the receipt’s request count and decode statistics describe the submitted windows. Use len(batch.windows) or batch.data.shape[0] to count delivered chips. Admission preserves window order. Use read_many() for custom windows, reusable output or explicit streams. Pass a matching jpeg2000_pool to select explicit lane, native or arena limits. Close a retained iterator when stopping early to drain prefetch.

iter_chips(indexes=None) yields NCHW CuPy imagery and retains the channel axis for scalar selection. JPEG2000 preserves the order and repetitions of the requested bands. The TIFF iterator requires all bands once in source order. Close an iterator when stopping early to retire its prefetched executions.

An omitted memory_budget_bytes defaults to 1 GiB. For JPEG2000, the limit applies to complete output backings retained by this iterator, including prefetched submissions and suspended deliveries. The context default or an explicit jpeg2000_pool governs decoder allocations through its own capacity and admissions. Each iterator owns its output admission independently, even when several iterators share a decoder pool.

The iterator reserves one output lease per backing across up to two live submission slots. Output pressure can reduce groups or prefetch. An output budget smaller than one chip raises resource code 8. A native capacity refusal can fit a smaller candidate under the existing pool capacity. Native Busy drains this iterator’s pending work or waits for availability.

Each admitted submission uses a separate cudaMalloc output allocation, released with cudaFree after its last array reference. Both calls may synchronize; their overhead is unmeasured. Smaller array views retain the whole allocation. Eligible idle pool storage can be retired without changing N or trimming a live bank. There is no CPU decode fallback.

Caller-only retained yielded outputs are excluded after the iterator releases all references; their pixels remain valid through advance, iterator close and source close. Compressed host bytes and pinned bytes are also excluded. The bound does not measure physical driver, runtime, allocator-cache or opaque foreign memory. Native codec arenas, maps, callback scratch, retained capacity and growth remain charged by the native owner across both banks.

Iterator receipts add iterator_budget_bytes (B), iterator_output_capacity_bytes (O), iterator_output_retained_bytes (the complete output requests retained at delivery), and iterator_output_peak_bytes (the iterator’s observed output-request high-water). JPEG2000 reports the same value for B and O. Direct batch receipts leave these fields unset. JPEG2000’s native_capacity_bytes is N; native_retained_bytes is a completion snapshot and native_peak_bytes covers the native pool’s lifetime. TIFF’s iterator_native_capacity_bytes is N. Its existing device_capacity_bytes remains the native aggregate completion snapshot across both banks; bank_index, bank_reused, and allocation counts describe the selected bank. TIFF exposes no native lifetime peak. Output high-water can come from an earlier partition. Separate peaks do not establish a simultaneous physical whole-iterator peak.

Supported Deflate TIFF datasets also accept iter_chips(). TIFF uses decode_tiles to bound each decode wave and emits at most batch_size chips per yielded view. Shared edge tiles stay together when budget admission permits. Each view retains the full wave output and shares its wave receipt. The first, middle and last views all charge that full backing while suspended. Native code-8 resource refusals can split waves or reduce prefetch; drained cached native capacities can be retired before retrying. See GeoTIFF chip iteration. Run examples/geotiff_chip_batches.py for a complete example with optional PyTorch handoff:

python examples/geotiff_chip_batches.py B02.tif --max-batches 1

For caller-managed pipelining, submit up to two batches with disjoint outputs:

with cugeo.raster.open("B02.jp2") as src:
    with src.submit_many([(0, 0, 256, 256)]) as first:
        with src.submit_many([(1024, 0, 256, 256)]) as second:
            first_data, first_receipt = first.complete()
            second_data, second_receipt = second.complete()

submit_many() accepts the JPEG2000 output, stream, context, compressed-byte limit, and pool options from read_many(). Its PendingBatch retains the output and stream until successful completion or close. A third pending batch returns busy. Keep the bytes written by each batch disjoint from other in-flight operations. Two batches can write disjoint views of one allocation. Allocating submissions retain their output and use the selected caller stream, including the default stream. Event dependencies keep decode concurrency within the lane limit while host submission overlaps the preceding batch.

examples/jpeg2000_chip_batches.py is a shareable runnable version. Model normalization, framework conversion, metadata, and inference begin where its consume() function receives the raw GPU batch. Sentinel-2 stores spectral bands in separate JP2 files, so a downstream adapter must align and assemble its requested bands rather than treating one B02 file as a complete multispectral input.

For a PyTorch model, the optional --torch mode demonstrates the framework handoff without choosing a model or its preprocessing:

python examples/jpeg2000_chip_batches.py image.jp2 --torch --max-batches 1

Both chip examples use chips.astype("float32") to allocate converted pixels on the GPU, then torch.from_dlpack shares that allocation with PyTorch without a host pixel copy. The resulting tensor has NCHW shape and stays on the GPU. Replace consume() with your model’s normalization, metadata, and inference; for Clay, first align and assemble its requested sensor bands. See PyTorch’s DLPack documentation.

CUDA streams#

Pass stream=None to use the current CuPy stream on the submitting thread, including its current default stream. An explicit stream overrides that lookup. The shared adapter accepts __cuda_stream__() returning (0, integer_handle), integer handles, objects with .ptr, and legacy ctypes.c_void_p handles directly or in .ptr. Protocol values take precedence. Booleans, unsupported protocol versions, malformed tuples and values outside uintptr_t fail before submission. Handles 0 and 1 select legacy default; 2 selects the submitting thread’s default.

Explicit stream normalization requires no CuPy; caller-buffer APIs retain their existing CuPy-independent paths. Selecting a current stream without CuPy raises UnsupportedError with code 2. APIs allocating CuPy output or scratch retain that requirement. Host calls neither look up a CUDA stream nor initialize CUDA.

Python API

Selection and completion

DatasetReader.read (including out=), read_masks, dataset_mask, sample; SAFE band readers

Per call; None selects current. Ordinary arrays establish selected-stream output ordering before return; completed receipts observe completion. Point inputs must already be ready on that stream.

read_many, submit_many, submit, iter_chips

Select on the submitting thread; iterators bind when iteration starts. Submitted handles require their documented completion method before consumption. Background controllers receive recorded producer events and use owned streams.

warp_affine, warp.reproject

Per call; None selects current. Join declared producers with events; retain work through asynchronous completion.

orthorectify, OrthorectifyFilePlan.execute_cuda

Per call; select current or explicit. Ordinary orthorectify allocates scratch through CuPy; execute_cuda accepts a caller-owned arena. Synchronous file execution drains selected work before return; publication and receipts retain their existing boundaries.

DatasetWriter.write, write_mask

Per mutation; select current or explicit and join declared producers. Input may be released or overwritten after successful return. Successful writer close publishes the file.

RasterSource.read_device_into, read_device_into_nvtiff; Jpeg2000Source.read_device_into, read_device_into_nvimagecodec, read_many_device_into

Per call; None selects current. Retained execution/pending handles own completion and failure observation.

RasterSource.prepare_nvtiff, Jpeg2000Source.prepare_device, prepare_affine_device

Select at preparation. NvTiffPrepared.decode_into, Jpeg2000Prepared.read_device_into, and Jpeg2000AffinePrepared.enqueue inherit for None; explicit operation streams override preparation. Both owners remain retained through completion.

CudaWarp.enqueue, CudaReproject.enqueue, CudaLayoutCopy.enqueue, SampleMinimumPrepared.enqueue

Context-only preparation; select per enqueue. Borrowed arrays must be ready on the selected stream. Warp/reprojection also expose producer_handoff=True.

CudaOrthorectify.plan_geometry, CudaOrthorectifyGeometry.sample

Select per call. Borrowed arrays require producer None or the selected stream (CAI 1 also matches execution 0); foreign tags are rejected. Geometry/result and execution owners retain their existing query, result, wait and close boundaries.

CompositeCudaPrepared.begin and CompositeCudaSession

Select at begin; accumulation, pass advance and finalization inherit. No execution override: state and candidates share one ordered session. Defaults use a managed stream with event dependencies in both directions.

io.nvtiff.DeviceReadPlan.prepare, prepare_pool

Bind at preparation or to each pool member. Enqueue inherits the selected binding and exposes no override. A pool destination must be ready for every eligible member.

io.nvcomp.DeflateTiffReader

Select at reader creation; its banks inherit and expose no override. Default bindings use a managed stream; receipts identify the actual execution stream.

surface_reflectance.toa_to_surface, l1b_to_reflectance, quality_validity, encode_l2a, retrieve_visibility, terrain_illumination, terrain_coefficients, correct_surface; RadiativeTerms.coefficients; Sen2CorLUT construction and sample

Select per call, including LUT upload. Calls complete on their selected stream before returning; later calls do not inherit an upload stream.

SurfaceGeometryPlan.prepare, SurfaceGeometryPrepared construction, execute, sample_solar, sample_registered_solar, sample_registered_illumination, relative_azimuth, viewing; compose_surface_geometry, source_illumination; SurfaceFieldSampler.sample

Select per call, including staging during preparation. Calls complete before returning; later calls do not inherit a staging stream. Convergence uses an ordered managed bridge for defaults.

AtmosphericLUT construction, from_host, from_device, sample

Select per call. Construction uploads host nodes or copies device coefficients and completes staging before return. Sampling selects independently and completes before return.

Context-only prepare_cuda, pool/resource configuration, scratch/layout queries, CudaLayoutCopy.allocate_bip, memory-resource/admission creation

Preparation, allocation or host metadata boundaries; no execution-stream parameter. Allocations do not imply producer work. Their resource owners control teardown.

io.gds.read_tile_into, GDS source preparation

Synchronous storage boundary, no stream parameter. Destination must be quiescent; CAI producer tag must be absent or None.

Execution/pending query, wait, result, complete, close; reader, prepared and allocation close

Observe or drain the retained operation. No new stream selection or override; CUDA cleanup uses the bound context and completion dependency.

Keep the stream and context live through completion and failure draining. Raw integers and ctypes pointers carry no ownership; retain their external owners yourself. PTDS dependencies are captured on the submitting thread; another host thread cannot identify that stream merely by using token 2. Retained close uses the recorded execution dependency. Ordinary calls make no graph-capture promise.

Caller-owned CUDA output#

Before passing caller-owned CUDA output to a JP2/raw-J2K read(), make a compatible CUDA context current on the calling thread. An array allocated on another thread does not make its context current here. The managed JPEG2000 route queries the calling thread before it creates streams or submits decode; without a current context, read() raises CugeoRasterError and leaves out untouched.

Every CUDA Array Interface input and output follows the version 3 stream rule. An absent or None stream needs no ordering, 1 names the legacy default stream, 2 the per-thread default stream, and a larger integer a stream handle. A stream of 0 raises ValueError, because version 3 forbids it as ambiguous between the two default streams. A call that takes an explicit stream uses the producer policy of its row in the stream inventory. Advanced borrowed-array enqueues generally require producer None or the selected stream (CAI 1 also matches execution 0). Ordinary writes and warps join declared producers through events. Read composition performs its documented joins; other read paths reject unresolved producer tags. Callers establish readiness before those calls and publish that fact in their array interface.

GPU reads capture the current CuPy device and stream on the calling thread; an existing explicit stream overrides the current stream. Default streams are accepted. Producer readiness and current-context requirements remain enforced. All writes are ordered before subsequent work on the selected stream before an ordinary array returns. Consumers on other streams establish their own events.

Plain nvTIFF array reads retire retained executions in the background after return. Outputs, backing allocations, streams and decoder state remain retained through completion and failure draining. Reader close drains its retirement jobs before batch-session and source teardown; keep its borrowed CUDA context alive through close, and shut down shared context pools before destroying the context. JPEG2000 and other paths retain waits needed for SDK safety or host-observed codec errors. Completed receipts wait, observe errors and close execution resources. Early reader or array destruction does not permit premature pool reuse. There is no pending-array wrapper.

TIFF delegates to direct nvTIFF. JP2/raw-J2K explicitly selects the Jpeg2000Source direct-nvJPEG2000 product method and forwards context, max_compressed_bytes, optional device/pinned scratch capacities, overview_policy, an optional explicit discard_levels, and the window. A build without the optional direct codec returns its typed rejection rather than substituting nvImageCodec. The explicit comparator remains available only with backend="nvimagecodec". CUDA TIFF uses the native base-image frame. Direct JPEG2000 scalar reads retain their fractional footprint through resolution mapping and integer ROI decode. JPEG2000 forwards the requested band order and repetitions through the native device routes. Transfer and foreign scratch counts not exposed by a codec remain typed unknown in the receipt. cugeo-raster-managed device and pinned scratch capacities are distinct from foreign codec memory, and device residency is never relabeled as GDS.

Jpeg2000Source.prepare_device, prepare_affine_device and one-shot read_device_into accept pool=None. Omission resolves the native context default; an explicit cugeo.raster.cuda.Jpeg2000Pool uses the same executor. Preparation retains the Pool and immutable source snapshot without reserving a native Slot. Scalar execution claims one Slot; batches claim one of two banks and distinct Slots for their useful lanes. Automatic policy permits eight lanes per bank and sixteen native Slots, within the same aggregate byte/record limits.

Construct explicit pools with finite device/pinned MemoryResource owners. Optional scalar device_resource and pinned_resource arguments must be that pool’s actual pair. Omitted scratch capacities inherit immutable pool policy; explicit conflicts raise native code 1. Resource counters describe aggregate provider use. Unspecified allocator kinds are reported as shared-pool-resource; known explicit provider facts name the resource kind. No standalone allocation fallback or Python pool registry runs.

Prepared read_device_into and affine enqueue accept stream=None and wait_for_slot=False. An explicit operation stream overrides the preparation’s convenience stream for decode, sampling and error drain. Shared pressure returns None before work; wait_for_slot=True waits for admission outside lifecycle locks, then returns an execution. A preparation’s own live execution raises code 1. Query and wait retain native claims until execution close. Prepared, source and pool close release references; explicit shared shutdown stops acquisitions and preserves retained completion.

Pass one-based indexes to prepare_affine_device to select destination channels after all source bands have been sampled. Nonidentity selection writes ordered channels to a BIP or BSQ CUDA destination. Give enqueue a contiguous CUDA UInt8 sampled_scratch buffer of at least the byte count in the preparation’s explain()["sampled_scratch_required_bytes"]. The execution retains this buffer until close. The composed read’s status and nodata rules use all source bands.

Explicit JPEG2000 source#

cugeo.raster.io.jpeg2000.Jpeg2000Source remains the advanced JPEG2000 lifecycle owner used by cugeo.raster.open(). Construction performs bounded JP2/raw-J2K inspection and returns typed pixel metadata plus optional GeoJP2 georeferencing without loading a codec. prepare_device() retains a bounded immutable compressed snapshot and a direct nvJPEG2000 decoder. Both prepared and one-shot read_device_into() require a caller-owned CUDA Array Interface destination and a compatible CUDA context current on the calling thread. Pass that context’s handle, a stream (including the default stream), and compressed/scratch capacity bounds. Set indexes at preparation or on the one-shot call to read an ordered, one-based band selection. The destination needs the selected band count, matching dtype and packed or pitched BIP or BSQ strides. Repeated indexes write distinct output channels. The receipt reports the bytes in the native decode intermediate and the band-map upload, when used. Selection uses a discard level and an optional selected-resolution (x, y, width, height) window. They return owned execution objects with explicit query/wait/retryable-close and route facts. There is no fallback. The explicit nvImageCodec comparator remains available only as read_device_into_nvimagecodec().

submit_many_device_into() and read_many_device_into() accept a one-based index or a nonempty sequence of indexes. Omit it to read all components in source order. Each output channel has independent storage, including repeated indexes. Pass a caller-owned CUDA array of shape (requests, bands, height, width) with the selected band count and packed or pitched BSQ or BIP strides. The batch receipt counts selected samples in requested_bytes and all source components in the scheduled decode units in decoded_bytes.

from cugeo.raster.io.jpeg2000 import Jpeg2000Source

with Jpeg2000Source("image.jp2") as source:
    execution = source.read_device_into(
        output,
        context=context.ptr,
        stream=stream,
        max_compressed_bytes=128 * 1024 * 1024,
        window=cugeo.raster.windows.Window(16, 24, 512, 512),
        wait_for_slot=True,
    )
    execution.wait()
    assert execution.explain()["backend"] == "direct-nvjpeg2000"
    assert not execution.explain()["fallback"]
    execution.close()

pool.trim() retires eligible idle storage while preserving immutable policy, configured resources, native admission, live scalar Slots and caller outputs. Pending batch banks raise code 1. The pool’s CUDA context must be current. Useful lanes may grow up to the configured per-bank ceiling; a small first batch does not freeze their warmed population.

Synchronous batch reads wait for shared availability. Callers must drain their held pending work to make progress. Asynchronous submission returns None when busy. Python releases lifecycle locks while waiting, then revalidates live handles. Pending outputs remain valid after source closure. Native callers keep borrowed contexts, streams and outputs alive through successful completion.

The implemented lane is GPU-only and lossless, with a nonzero number of unsigned, equally sized components. It writes pitched BIP or BSQ output with optional ordered one-based band indexes. Repeated indexes write distinct output channels. Component counts are bounded by the source format, checked byte extents, and selected backend. Precision 1–8 produces UInt8; precision 9–16 produces UInt16. Native-resolution ROI, full reduced resolution, and reduced-resolution ROI that begins and ends on reduced tile boundaries are supported. GeoJP2 and the bounded two-dimensional UTM GMLJP2 RectifiedGrid profile used by the qualified Sentinel-2 product are supported; other GMLJP2 profiles, nonzero codestream reference origins, misaligned reduced-resolution ROI, palette/alpha/color conversion, signed/subsampled/mixed components, host output, encoding, output allocation, automatic routing, and fallback are not. Checked-in synthetic fixtures are contract evidence. The pinned real Sentinel-2 B02 passed exact native and discard-level 1–4 runtime comparison; see the prepared-lifecycle document for its reproducible evidence.

One-shot native operations#

cugeo.raster.warp.calculate_default_transform(src_crs, dst_crs, width, height, rpcs=metadata, **rpc_options) proposes an Affine and exact integer dimensions through native suggested output. Supply a detached rpc.RPC or full GDAL-domain mapping. RPC ground coordinates default to WGS84 even with an unrelated src_crs; None is allowed for that argument. Destination CRS and positive source dimensions are required. Bounds, GCPs, RPCs and geolocation arrays are mutually exclusive, including empty supplied forms. Shared RPC height/DEM options apply at user Z zero. Resolution or paired destination dimensions override the completed suggestion while retaining its upper-left anchor. The call completes on the host, reads no source imagery and launches no CUDA. Missing terrain or failed required inversion refuses the whole suggestion; samples do not establish complete source coverage. See the suggested-output contract for finite coordinate charts and typed failures. plan_rpc_grid retains its distinct sampled-envelope promise.

Pass rpcs=metadata, **rpc_options to warp.reproject to execute the same RPC model and height options on NumPy or CUDA imagery. Supply exactly one source georeferencing form, including when a supplied form is empty. Arrays require src_crs; RPC ground coordinates remain WGS84 despite unrelated source CRS metadata. Explicit grids, supplied output dimensions and omitted-grid allocation use the same rules as affine reprojection. The shared native height owner uses user Z zero, so constant-height calls use RPC_HEIGHT and terrain calls use RPC_DEM. No Python transformer instance is required.

Native TIFF paths, open readers and raster.band(reader, indexes) select file-backed source windows. Integer selection is HW; sequences preserve CHW, order and repetitions. Supplied NumPy output executes on the host; supplied CUDA output executes on its selected stream. Omitted file output allocates CHW CuPy. Explicit rpcs= suppresses the dataset affine. Other formats and alpha/internal/external mask sources receive code 2; scalar nodata is supported. Image dtypes remain UInt8, UInt16 and Float32 with matching output types.

File calls accept memory_budget_bytes (default 64 MiB), preferred_shape (default (256, 256)) and minimum_shape (default (1, 1)), in HW order. The native controller splits complete destination waves until their maps, source/DEM windows, decode staging and retained output storage fit the cap. Nearest/bilinear source halos remain in full source coordinates. CUDA maps stay on device; native TIFF decode uses bounded host storage and explicit H2D copies. return_receipt=True waits and adds receipt.file: completed pixels, waves, splits, source windows, known storage peaks, transfers and host waits. Unknown foreign device/pinned allocations remain None. The cap covers known owned payload and known complete output backings; it is not a whole-process memory limit. Minimum-wave exhaustion is code 8. A runtime failure can leave completed waves in output; its receipt records partial work.

cugeo.raster.warp.reproject returns (destination, dst_transform). Supply the source array, its Affine transform and both CRSs. Supply destination and transform for an explicit grid, omit the transform to derive it for a supplied output shape, or omit both to suggest and allocate CHW output. A NumPy source allocates NumPy; a CUDA source requires CuPy for allocation in the compatible current context and selected stream. Supplied output keeps its exact identity, rank and strides. Inputs normalize through CRS.from_user_input, including canonical values, EPSG integers, WKT/authority strings, mappings and foreign to_wkt() objects. Complete WKT2 definitions reach native planning; foreign conversion is called once. Existing supported 2D horizontal operations execute in traditional X/Y order, with their declared units. Valid unsupported operations or dimensions raise explicitly; parsing alone does not grant execution. GDAL and Rasterio are external references, never runtime fallbacks.

NumPy calls finish synchronously without importing CuPy or initializing CUDA. CuPy calls queue on the current stream, including the default stream, or an explicit stream. The call retains inputs, complete output backing, scratch and prepared execution through completion. Declared producer streams are ordered with events. Cross-stream consumers establish their own dependency. Graph capture is unsupported for ordinary calls.

import numpy as np
import cugeo.raster as raster

source = np.arange(12, dtype=np.uint16).reshape(3, 4)
out = np.empty_like(source)
grid = raster.Affine(10, 0, 500000, 0, -10, 30)
result, transform = raster.warp.reproject(
    source, out, src_transform=grid, dst_transform=grid,
    src_crs=32631, dst_crs="EPSG:32631",
)
assert result is out and transform == grid
np.testing.assert_array_equal(out, source)
assert raster.warp_affine(source, raster.Affine.identity(), out=out) is out

Both calls accept HW/CHW UInt8, UInt16 or Float32 arrays with admitted positive strides and matching source/output types and band counts. No pixel staging, repacking or conversion is performed. Reprojection uses all-bands scalar nodata and fills invalid output by default; init_dest_nodata=False preserves invalid destination samples. In a new allocation those samples are unspecified; status and validity remain defined. dst_resolution accepts a positive scalar, one-element sequence or (xres,yres) when both destination and transform are omitted. None, scalar zero and empty lists/tuples mean omission. A consumed resolution conflicts with supplied dimensions; with a supplied transform it has no grid effect. Planning uses native bounds proxies for rotated/sheared sources; sampling uses the original affine. warp_affine maps destination pixel corners to source pixel corners, retains any-band nodata/fill, and accepts same-residency HW boolean source_validity. Omitted out allocates NumPy for host input or CuPy for CUDA input, using the source dtype and HW/CHW shape unless destination_shape is supplied. An HW destination shape preserves source bands for CHW input. Supplied out retains its exact identity. See the ordinary warp contract for the complete signature, numerical reference differences and refusal matrix.

Either return_status or return_receipt selects an immutable raster.warp.WarpResult. Its data is the supplied or allocated destination; transform is the destination grid (None for warp_affine). Status requests return HW UInt8 status and HW boolean validity on the imagery’s residency. Receipt requests wait for completion and report native and convenience allocation, scratch, preparation and transfer facts. Other fields are None. Fatal CUDA context faults can terminate the process during background retirement or receipt completion when cleanup cannot be proved. That fail-stop can race stream synchronization; a catchable Python exception is not guaranteed. Use lowlevel.AffineWarp or lowlevel.Reproject to reuse prepared plans and caller-owned ancillary storage.

Reusable Reproject takes source_crs and destination_crs with the same input protocol. Its attributes retain canonical CRS values. Terrain takes crs; orthorectification takes destination_crs and, for orthometric heights, a complete compound terrain_vertical_crs. Native creation owns these definitions independently of caller buffers and closed source readers.

Reproject.prepare_cuda(maximum_pixels=...) binds one reusable cugeo-proj workspace to the current CUDA context. The capacity bounds each submitted destination tile and enables both direct and composed two-stage coordinate plans without allocating during enqueue. Omitting it reserves the full destination grid. Source, destination, scratch, validity, and status remain caller-owned CUDA Array Interface buffers through completion.

orthorectify(image, dem, *, out, destination_transform, destination_crs, terrain_vertical_reference, ...) is the synchronous file workflow. image and dem are TIFF paths or open DatasetReader objects; the imagery must carry RPC00B metadata and the DEM must carry an affine transform and interpretable CRS. cugeo-raster does not establish a vertical datum from the file, so terrain_vertical_reference is required. Pass "wgs84_ellipsoid" for WGS84 ellipsoidal heights, or the DEM’s compound CRS such as "EPSG:6318+5703" for orthometric heights. A compound declaration also needs terrain_grid_directory (the only directory searched for PROJ grids, such as us_noaa_g2018u0.tif). Supply terrain_coordinate_epoch as a decimal year when the selected operation is time-dependent. The compound CRS’s horizontal part replaces the DEM file’s CRS for terrain lookup. A destination may use a supported projected CRS. Each sampled point’s X/Y/height is converted together to WGS84(G2139) through cugeo-proj before RPC evaluation; the receipt’s native_details["vertical_datum"] records the resolved operation. Omitting the argument or passing None raises TypeError. Malformed definitions raise a cugeo-proj ValueError-family error; valid unsupported declarations raise UnsupportedError.

examples/orthorectify_navd88.py is a shareable runnable version for a 3DEP NAVD88 DEM:

python examples/orthorectify_navd88.py image_rpc.tif navd88_dem.tif \
  --grid-directory proj-data --bounds -80.2985 26.2565 -80.2485 26.3045 \
  --resolution 4e-5 --acquired 2006-01-16T16:01:07.9044Z --cuda

out is caller-owned NumPy or CuPy. NumPy reuses the bounded native host file pipeline. CuPy uses the current or explicit stream and selects only uncompressed UInt16 C1 native TIFF ROI decode on host, explicit H2D staging, and the existing CUDA geometry/sampler. The call drains that stream before returning and reports storage reads, transfers, device work, waits, allocations, route, and fallback=False in OrthorectificationReceipt. It never imports GDAL or Rasterio. Reusable geometry/sample and asynchronous completion ownership stay available through OrthorectificationPlan, OrthorectifyFilePlan, OrthorectifyGeometry, and cugeo.raster.cuda.

memory_budget_bytes also bounds the ordinary CUDA facade’s caller arena: it reserves scratch, status, validity, active output, and the conservative cugeo-proj workspace ceiling before splitting the remaining capacity between terrain and image ROIs. Large source rasters are not allocated in full. Receipt fields keep exact caller capacity separate from unknown foreign capacity and from the cugeo-proj upper bound.

TemporalComposite is the ordinary name for the native plan and is identical to cugeo.raster.lowlevel.Composite. It does not mean the Rust-only temporal file pipeline is available from Python.

Advanced namespaces#

cugeo.raster.cuda owns the public CUDA plan, prepared, session, execution, layout-copy, and BIP-allocation paths without changing their explicit context, stream, query/wait, or close semantics.

cugeo.raster.cuda.SampleMinimumSpec is the sole named compound CUDA operation. It accepts exactly four UInt16/C3 BIP CUDA Array Interface sources, one caller-owned destination and status array, and a selected CUDA stream. prepare_cuda() freezes transforms/shape/resampling; enqueue() crosses the ABI once and retains every Python owner until SampleMinimumExecution.close(). Its typed receipt reports four fused sample/reduce launches, active addressed bytes, zero intermediate/scratch and transfer bytes, completion, and fallback=false. Other scene counts, layouts, types, masks, nodata, fill, and reducers are rejected rather than routed to a Python loop or modular fallback. See the exact contract.

cugeo.raster.io.nvtiff contains NvTiffPrepared, NvTiffExecution, and the additive generic DeviceReadPlan/DeviceReadPrepared/DeviceReadPool/ DeviceReadExecution public experimental advanced surface. plan_device_reads() freezes pointer-free request specifications; preparation requires named device/pinned MemoryResource owners, MemoryAdmission, and a selected CUDA stream; the Python surface accepts the shared stream representations and retains the supplied owner. Raw handles remain borrowed. Enqueue requires matching caller-owned CUDA arrays. The surface performs no allocation, split, conversion, automatic backend choice, or fallback and is covered by the exact 64-region and two-stream correctness/capacity/ backpressure/lifetime rails. Those rails do not choose a pool size, concurrency, or performance default and do not attribute total foreign memory. A rejected native submission raises DeviceReadSubmissionError, whose results tuple preserves one normalized status and any raw backend status for every request in caller order. Scalar decode submission remains on cugeo.raster.lowlevel.RasterSource.read_device_into_nvtiff() and prepare_nvtiff(). cugeo.raster.io.nvimagecodec contains only NvImageCodecExecution; the former metadata-free pixel-TIFF writer was removed. Scalar decode submission remains on RasterSource.read_device_into(). nvImageCodec multi-ROI remains crate-private, and neither namespace exposes Python allocator callbacks.

DeviceReadPlan.prepare_pool() requires a nonempty sequence of DeviceReadPoolMember values, an explicit DeviceReadPoolPolicy, a shared native MemoryAdmission, and a retained-capacity limit. Each member’s stream uses the shared protocol/integer/.ptr/ctypes adapter; the pool and its executions retain supplied stream and resource owners. Raw handles still borrow their external stream lifetime. Python installs no asynchronous allocation callbacks. Because the native pool may select any member, a destination with an unresolved explicit producer-stream tag is rejected until the caller establishes readiness for every member.

examples/native.py is the executable golden workflow. The wheel test copies it to the installed location and runs typed inspection, one native reusable read_many plan, identity affine warp, exact fixture pixels/status, and explicit close without importing the source-tree package.

Complete raster writes#

Dictionary profiles and RasterWriteProfile use the same native creation and validation. Full pixel replacements and HW write_mask() mutations remain private until successful close(). Exceptional context exit and finalization abort without publishing. Partial pixel mutation and metadata setters remain unsupported. The ordinary JPEG 2000 driver name is nvJPEG2000.

RasterWriteProfile declares the complete output contract. The ordinary writer accepts one complete array and publishes only after native reopen:

profile = cugeo.raster.RasterWriteProfile(
    driver="GTiff",
    width=width, height=height, count=3, dtype="uint16",
    transform=transform,
    crs=cugeo.raster.CRS.from_epsg(32631),
    pixel_interpretation="area",
    nodata=0,
    colorinterp=("red", "green", "blue"),
    scales=(0.01, 0.01, 0.01),
    offsets=(0.0, 0.0, 0.0),
    compression="lzw",
    block_shape=(256, 256),
)
with cugeo.raster.open("output.tif", "w", profile=profile) as writer:
    writer.write(array)
receipt = writer.receipt

Use driver="COG" with tiled block_shape, strictly increasing overview_factors, and overview_resampling=Resampling.nearest. Use driver="nvJPEG2000" for georeferenced UInt8/UInt16 gray or source-order RGB; compression resolves to jpeg2000-lossless. JP2 requires a build with direct nvJPEG2000.

NumPy is portable and may use positive-stride BIP, BIL, or BSQ. CUDA Array Interface input accepts positive sample-aligned strides, including padded and stepped CHW views, with a selected current or explicit stream and an eligible codec feature. Native encoder descriptors serve compatible layouts; other layouts use an admitted image-sized GPU packing buffer. File storage follows creation options independently of source strides. No host fallback occurs. After successful close, writer.receipt names backend, container/codec, logical/encoded/ metadata/file bytes, chunk and overview counts, cugeo-raster-owned staging and layout-copy bytes, transfers, native reopen, and atomic publication.

The current strict profile owns transform/CRS/area-point, one dataset nodata, source-order color/alpha and ExtraSamples, per-band scale/offset, RPC00B, and generated nearest COG overviews. It does not accept separate mask arrays or supplied overview pixels; explicit descriptions, units and metadata creation fields follow the writing reference. No option exists to drop those fields silently.

Lifecycle and namespaces#

DatasetReader is a context manager over either owned format source. Its read-only mode property returns "r" before and after close, including for SAFE band readers. DatasetWriter.mode returns "w". close() is idempotent. Pixel and mask reads after close raise RasterIOError. Metadata access and refresh() after close raise ValueError.

No Python API preceded this first-release surface, so there is no legacy-root compatibility layer or deprecation schedule. Advanced ownership and backend objects are under cugeo.raster.lowlevel; typed receipts, status/results, and capability inspection are under cugeo.raster.diagnostics; ordinary I/O values are under cugeo.raster.io. The underscore implementation modules remain internal.

Advanced spelling

Ordinary spelling

cugeo.raster.lowlevel.RasterSource(path)

cugeo.raster.open(path)

source.info["images"][0]

dataset.metadata.images[0]

source.read_into(out, window)

dataset.read(window=Window(...), out=out)

root low-level lifecycle imports

cugeo.raster.lowlevel

root receipt/capability imports

cugeo.raster.diagnostics

root CUDA lifecycle imports

cugeo.raster.cuda

root scalar nvTIFF owners

cugeo.raster.io.nvtiff; the public experimental generic multi-region surface also lives here

root scalar nvImageCodec owner/encoder

cugeo.raster.io.nvimagecodec

explicit JP2/J2K source

cugeo.raster.io.jpeg2000

AffineWarp(...) one-shot use

cugeo.raster.warp_affine(...)

Composite(...)

TemporalComposite(...)

See the API namespace guide for the complete ownership map. Removed advanced root spellings are absent rather than warning aliases.

Grid utilities#

cugeo.raster.warp.calculate_default_transform(src_crs, dst_crs, width, height, left=None, bottom=None, right=None, top=None, gcps=None, rpcs=None, resolution=None, dst_width=None, dst_height=None, src_geoloc_array=None, **kwargs) returns (Affine, width, height) from positive source dimensions and ordered outer bounds. Native raster geometry constructs the planning proxy and suggests a north-up grid. Complete source and target CRS values use traditional X/Y units. The finite families are WGS84 degree geographic, Web Mercator and WGS84 UTM. Complete same-CRS identities and WGS84 degree geographic to/from those projected families are supported, including their native projected units and axis variants (international foot, US survey foot and north/east declarations). Values remain traditional X/Y; complete CRS meaning and execution restrictions are retained. World Mercator and equidistant cylindrical remain unsupported. See the suggested-output contract.

For example, a 13 by 7 EPSG:32631 source with bounds (500000, 0, 500260, 70) suggests 14 by 4 square pixels, rather than copying the source dimensions. A positive scalar, one-component or two-component resolution overrides the completed suggestion while retaining its upper-left anchor. Alternatively supply both dst_width and dst_height. None, scalar zero and an empty list or tuple resolution omit that override. Nonpositive sequence components and nonfinite values are invalid. Extra positive components, non-RPC transformer kwargs and GCP forms are unsupported; registered geolocation arrays use native CUDA planning/execution; even empty supplied forms participate in source exclusivity. A valid target with src_crs=None is unsupported; dst_crs=None is invalid.

The utility certifies the complete forward and inverse-check domains through the selected coordinate owner and checks every required numerical row. It returns no partial or empty successful grid. Malformed source values and unrepresentable source inverses are invalid. Failed numerical mappings, unsupported charts and unavailable operations use native code 2; size or dimension overflow uses code 8. The utility allocates no image; ordinary reproject consumes the same planner before allocating pixels.

Use cugeo.raster.warp.aligned_target(transform, width, height, resolution) to align a north-up corner grid outward. It returns (Affine, width, height) in the grid’s world units. Resolution is a positive scalar or (xres, yres) pair. Rotated, sheared, reflected and south-up grids raise UnsupportedError.

cugeo.raster.warp.transform_bounds(src_crs, dst_crs, left, bottom, right, top, densify_pts=21) returns four floats in target traditional X/Y units. Each edge includes endpoints and the requested equally spaced interior points. Point and line bounds are valid. Geographic targets need at least two interior points. The selected coordinate operation must certify the complete rectangle in one continuous chart; crossings, poles, unprovable domains and failed numerical samples raise UnsupportedError with native code 2. No partial envelope is returned. These host metadata utilities access no pixels and initialize no CUDA runtime. GDAL and Rasterio are development references, not dependencies.

Point samples#

Call dataset.sample(xy, indexes=None, masked=False, *, stream=None) with float32 or float64 CUDA Array Interface coordinates of shape (N,2) in the dataset’s X/Y units. The result is a CuPy array of native stored samples with shape (N,selected_bands). An integer index keeps its band axis, (N,1); empty input returns (0,selected_bands) after normal admission. Points and bands retain order and repetitions. Positive aligned coordinate strides are accepted. Host arrays/iterables and coordinate dtypes other than native float32/float64 are rejected. Unlike Rasterio, this interface returns a device array and accepts device coordinates; it has no host iterator.

import cupy as cp
import cugeo.raster

with cugeo.raster.open("image.tif") as dataset:
    xy = cp.asarray([[500005, 4199995], [500015, 4199985]], dtype=cp.float64)
    values = dataset.sample(xy, indexes=[3, 1, 3])
    assert values.shape == (2, 3)

A stored default-image affine is required, including when no CRS is declared. Inverse evaluation uses binary64 and exact floor without snapping. A float32 input retains its original precision. Nonfinite/outside points receive effective first-band nodata or zero; in-image samples retain source nodata and mask-invalid stored values. No calibration, dtype conversion, interpolation or reprojection is applied. masked=True is unsupported (code 2), including empty inputs; non-bools raise TypeError. Missing affine/codec/profile is unsupported (code 2). There is no out, public budget, context or receipt option.

Source profile

Native decode owner

Classic little-endian TIFF, stripped contiguous UInt8 RGB C3 or UInt16 C3, uncompressed, predictor 1, orientation 1

nvTIFF shared pool; native batch with bounded allocator policy, scalar slots otherwise

Classic little-endian TIFF, tiled contiguous BlackIsZero UInt16 C1, Deflate/predictor 2, no extra samples, orientation 1, tile dimensions divisible by 16

nvTIFF shared scalar pool

Admitted unsigned homogeneous JP2 with stored affine, 1–16-bit components, native resolution and matching component grids

nvJPEG2000 native batch; codec tile reuse where supported

The TIFF routes require nvtiff; JPEG2000 requires nvjpeg2k. Other profiles are explicitly refused. These implementation profiles are not a GPU runtime qualification claim. Point-specific runtime and sanitizer checks are in tools/test-point-sampling.sh.

Work joins the current CuPy stream or the supplied stream. Producer inputs must be ready on that stream; other consumer streams need caller dependencies. Native planning copies at most 4096 derived integer point positions per batch to the host. TIFF scratch holds at most eight physical units within a 64 MiB working target, or one larger required physical unit. JPEG2000 inherits its existing pool/arena policies. Coordinates and decoded imagery are not copied to the host. Repeated points share physical decode work within a batch; reuse across batches is not promised. Input and final output scale with N.

Planning and scratch reuse can block, as can SDK requirements and error observation. Returning the array adds no unconditional final completion wait. Native Rust/C/C++ submissions return WOULD_BLOCK (code 7) when another pending owner holds decoder capacity; complete or close that owner before retrying. Python coordinates managed admissions and retirements across readers and threads in the same CUDA context and decoder scope. A busy call retries only after matching managed completion advances; it waits for progress rather than joining every pending job. Admission is registered before submission to cover the retirement-publication window. Caller-held advanced owners still return code 7 when no managed operation can release capacity. Real allocation exhaustion remains RESOURCE_LIMIT (code 8) and is not retried. Coordinate storage, scratch, output and decode owners remain retained through completion, even if Python references are dropped. Reader close drains its pending work; the result remains usable. Keep the borrowed CUDA context alive through reader close.