Metadata-complete raster writing#

A writer stages a complete GeoTIFF, COG or JPEG 2000 dataset and publishes it once at successful close. Creation validates the immutable specification before private sample or output storage is opened. No requested metadata is silently dropped. GDAL and Rasterio are external reopen and conformance oracles in tests; they are never runtime writers or fallbacks.

Python image inputs use HW or CHW. Axis-presentation keywords are absent. Host and CUDA input support positive sample-aligned strides, including BIP, BSQ, BIL, padding, interior crops and spatial steps. Source storage changes addressing only; driver defaults and explicit creation options determine file storage. TIFF output remains pixel interleaved. Callers guarantee disjoint writable samples and forbidden buffer overlap; bounds, alignment, metadata validation and codec integrity checks remain enforced.

Surfaces#

Language

Creation and lifecycle

Rust

RasterWriteSession::create with a typed profile, or from_options with primitive RasterWriteOption values; write_full, write_device_full, write_mask, write_device_mask, close, abort, receipt

C

cugeo_raster_writer_session_create, completed write and write_mask, close, abort, release, and get_receipt; cugeo_raster_writer_option values or a typed native profile

C++20

Move-only raster_writer, with host and explicit cuda_stream_ref mutation overloads; destruction aborts

Python

open(path, "w", **profile) or profile=RasterWriteProfile(...); write() completes mutation, successful context exit or close() publishes, abort() discards unpublished work

Native mutation callers supply the whole retained backing allocation size in addition to the view’s checked forward extent. An interior pointer’s remaining extent is not its parent’s capacity. Python obtains those facts from the array owner. One-shot Rust, C and C++ plans use the same session and return its final receipt. In Python, read writer.receipt after successful close.

profile = cugeo.raster.RasterWriteProfile(
    driver="GTiff",              # "GTiff", "COG", or "nvJPEG2000"
    width=array.shape[2],
    height=array.shape[1],
    count=array.shape[0],
    dtype="uint16",
    transform=transform,
    crs=cugeo.raster.CRS.from_epsg(32631),
    pixel_interpretation="area",
    nodata=0,
    colorinterp=("red", "green", "blue"),
    compression="lzw",
    block_shape=(512, 512),
)
with cugeo.raster.open("out.tif", "w", profile=profile) as writer:
    writer.write(array)
receipt = writer.receipt

Creation opens an empty private sample file. The first host mutation or a no-pixel close allocates its bounded sample buffer and initializes the disk samples. CUDA preparation retains its unpublished codec output with zero sample-disk bytes. Admission refusal before sample initialization leaves the session open for retry; allocation or I/O failure after initialization poisons it.

Complete host replacements are repeatable and use private disk staging. The dataset writer contract also defines selected-band/window pixel mutation, repeated CUDA pixel mutation and metadata setters. Those capabilities remain explicit refusals. The API contract adds the C and C++ calling rules.

Profile#

The profile is immutable. overview_resampling is a canonical cugeo.raster.enums.Resampling member, or None for no overviews. COG requires an explicit Resampling.nearest; recognized unavailable methods raise UnsupportedError with code 2. Device COG writing remains unavailable.

Creation copies profile values, including nested band, RPC and overview sequences. Plain reader Profile values, dictionaries and typed arguments reach the same Rust normalization and admission owner. Keys use ASCII case folding; duplicate normalized keys, conflicting aliases and unknown keys are invalid. Combining a typed profile with creation keywords is invalid. Creation requires no input raster. Complete mutation then validates source schema, residency, strides and backing facts before changing staged samples. The one-shot plan additionally retains its original residency and strides.

Field

Values

driver

GTiff, COG, nvJPEG2000; canonical names compare ASCII-case-insensitively

size and sample type

nonzero width, height and band count; native sample type

transform

six finite coefficients, pixel-corner, with a nonsingular linear part; optional

CRS

full definition exactly representable as a geographic or projected 2D EPSG code fitting a nonzero, non-user-defined uint16; required with a transform

pixel interpretation

area or point; required with a transform

nodata

one finite value in the sample type’s range, including fractional integer declarations; NaN only for floating types; distinct from absence

bands

per band: source-order color interpretation, optional ExtraSamples value, optional finite scale and offset

RPC

RPC00B coefficients; optional

compression

none, LZW, Deflate (GeoTIFF, COG); lossless JPEG 2000 (JP2). Python "auto" selects none for TIFF and lossless JPEG 2000 for JP2

block layout

strips with rows per strip in 1..=height, or tiles whose width and height are positive multiples of 16

TIFF variant

automatic, classic or BigTIFF

overviews

COG only, and required there: at least one strictly increasing integer factor greater than one, nearest resampling

Integer nodata outside the sample type’s range, or integer NaN, is invalid (code 1). Infinite nodata is unsupported (code 2). Unwritten host samples use nodata rounded to the nearest integer, with half values rounded away from zero; floating samples preserve the declared value. Without nodata they use zero. The effective read mask compares against the native sample conversion of the declared nodata, which can differ from this initialization rounding.

Native validation derives CRS kind and verifies complete EPSG equivalence. Geographic comparison permits only geographic axis-order differences; it does not discard datum, dimension or component meaning. Unsupported definitions fail before publication and preserve an existing destination.

Pass descriptions and units as source-order sequences of text or None. Empty text reopens as absent (None). Pass explicit domains through metadata={scope: {domain: values}}: scope 0 selects the dataset and positive scopes select one-based bands. A key/value domain takes a string mapping; an xml: domain takes one well-formed XML document as a string. For example:

metadata = {
    0: {"": {"TITLE": "Survey λ"}, "xml:survey": "<survey>coast</survey>"},
    1: {"processing": {"METHOD": "raw=a=b"}},
}

Supply metadata=metadata, descriptions=("Elevation",), units=("m",) at creation for a single-band TIFF or COG. The native profile copies nested values before acceptance. writer.descriptions, writer.units, writer.tags() and writer.tag_namespaces() inspect accepted creation values; returned mappings are detached. These getters do not read staged pixels. Metadata setters and property assignment remain unsupported (code 2).

GTiff and COG embed dataset/band domains and band text in standard GDAL_METADATA XML on the base image. COG overviews omit these user fields. Empty key/value entries are omitted on reopening. JP2 admits dataset domains through a standard GDALMultiDomainMetadata XML box. Its emitted XML payload is limited to the native reader’s existing 4 MiB extent, checked before session acceptance. Its raw XML documents reopen with GDAL’s XML formatting, including a trailing newline. JP2 band text and band domains receive Unsupported (2) before session acceptance: the admitted standard metadata box supplies dataset domains. No added private UUID stores these fields.

IMAGE_STRUCTURE, SUBDATASETS, DERIVED_SUBDATASETS and GEOLOCATION are encoding or discovery facts and cannot be supplied as domain requests. RPC uses rpcs=RPC(...) or a GDAL-domain string mapping, also available as RasterWriteProfile.rpcs. The native owner writes tag 50844 and supplies the writer and reopened reader’s tags(ns="RPC"). Supplied zero error estimates persist as zero; absent estimates encode as unknown -1. Values are detached from executable sensor/DEM resources. Conflicting typed and generic RPC metadata is invalid; generic RPC-domain writes remain unsupported. Dataset default-domain NODATA_VALUES is an unsupported validity source and receives Unsupported (2) before acceptance. Explicit dataset AREA_OR_POINT values Area and Point use the native pixel-interpretation authority for a stored grid; a conflicting explicit pixel_interpretation is invalid. Without a stored grid, the supplied tag does not create one. A reader Profile contains none of these additional text/domain values; copy them explicitly.

Raw TIFF tags or GeoKeys, supplied overview arrays, per-band nodata and separate mask arrays have no creation fields. Copy an explicit validity mask with write_mask() after creating a GTiff writer.

Write a dataset mask#

Pass an HW Boolean or uint8 array to writer.write_mask(mask, window=None, stream=None). True and nonzero bytes mean valid. The full-resolution internal GTiff mask reopens as zero or 255 for every band, independently of nodata and alpha. Writing it preserves the stored pixels and creation metadata. CHW presentations, including a singleton band axis, and scalar Boolean fills are unsupported (code 2); supply an HW plane explicitly.

import numpy as np
import cugeo.raster as raster
from cugeo.raster.windows import Window

pixels = np.zeros((1, 19, 37), dtype=np.uint8)
with raster.open("masked.tif", "w", driver="GTiff", width=37, height=19,
                 count=1, dtype="uint8", nodata=0) as writer:
    writer.write(pixels)
    writer.write_mask(np.ones((13, 31), dtype=bool),
                      window=Window(3, 2, 31, 13))

with raster.open("masked.tif") as reader:
    valid = np.empty((19, 37), dtype=np.uint8)
    reader.read_masks(1, out=valid)
assert valid[2, 3] == 255
assert valid[0, 0] == 0

The first accepted partial mutation leaves untouched pixels invalid. Later full or window mutations replace only their addressed region, in call order. Windows must be integral and in bounds, with the same shape as the input; fractional windows and resizing are unsupported. Positive host strides are accepted. CUDA masks must be tight HW arrays. Python selects the current CuPy stream for stream=None; explicit streams, including defaults, override it. The writer joins declared producer streams with events. Mutation completes before returning, so the input can then be overwritten or released. Only packed one-bit bytes travel from the GPU to the host for TIFF assembly. Masks can be written before or after host or prepared CUDA pixels.

Without a write_mask() call, the file has no explicit mask storage. A refused first call leaves it absent. COG, JP2, per-band masks, external masks and mask overviews are unsupported. An existing destination .msk or .MSK sidecar causes a refusal before creation; neither sidecar nor destination is replaced.

receipt.mask_payload_bytes and mask_chunk_count report encoded mask storage; encoded_payload_bytes and chunk_count include pixels and mask together. logical_bytes continues to count pixel samples. mask_device_to_host_bytes counts packed validity transfers. mask_completion_host_waits and mask_resource_host_waits report actual shared completion and resource waits. Budget fields separate mask disk allocation, known resource-control reservations, the managed device limit and the original registered pinned extent. CUDA pool pages and foreign codec internals remain opaque.

TIFF bands must begin with Gray or Red/Green/Blue in source order. Primary color bands carry no ExtraSamples value; each further band declares Undefined (0) or Alpha (1 or 2). No band is reordered or color-converted.

Lifecycle#

Creation checks both <target>.msk and <target>.MSK. Either existing companion refuses with unsupported code 2 and preserves every file. Creation and completed mutations expose neither a new destination nor a replacement. Existing readers retain their own file lifetime.

DatasetWriter.write() returns None. After it completes, the caller may change or release its input; the native owner retains copied samples or completed unpublished encoded output. Full host replacements apply in call order. CUDA accepts one complete positive-stride mutation; a repeated CUDA mutation is an unsupported capability. An unsupported or invalid preflight preserves prior staged samples. An execution failure poisons the owner and drains work before releasing resources.

Successful close() or successful context exit encodes the staged samples, syncs private output, reopens and validates the semantic profile, prepares the native receipt and disposable storage cleanup, then atomically replaces the target once. Python close returns None; writer.receipt is absent until publication. Repeated successful close returns the retained outcome without publishing again. Repeated failed close raises the stored terminal failure without retrying publication. This is single-file atomic visibility, not crash durability or a transaction across companions.

abort() is idempotent and discards unpublished work. Close after abort is invalid state. Abort after publication preserves the receipt. Exceptional context exit preserves the original exception and aborts. Finalization and native release abort; they never publish and cannot report close failures. Use explicit close or successful context exit when finalization errors matter. Writer reads, publishing flush, update modes, append, masks and metadata setters are recognized unsupported operations.

A no-pixel close publishes real initialized host output: uniform nodata-derived fill, or zero without nodata. Finite fractional integer nodata keeps its declared metadata while initialization rounds half away from zero. Effective read-mask comparison remains a separate rule. The reference can leave touched-block zero samples in wholly unwritten pixel-interleaved bands; this writer deliberately uses uniform fill across bands and layouts.

Mutation is synchronous. CUDA mutation completes the caller’s explicit stream before returning, including earlier producer work ordered there. JPEG 2000 retrieves the compressed host bitstream; nvTIFF completes its file encode. Close validates and publishes that same unpublished result. No second publisher or decoded device-to-host fallback is used.

Host input is any positive-stride NumPy BIP, BIL or BSQ array (Rust NativeRaster). CUDA Array Interface input (Rust NativeDeviceRaster) uses the shared stream contract. Native callers pass a resolved stream explicitly and establish producer readiness before execution. nvTIFF 0.9 requires tight BIP encoder input: that layout stays direct, and the native writer packs other source strides into one image-sized device buffer. nvJPEG2000 consumes pitched interleaved input directly, or planar component pointers with the source line pitch for BSQ and BIL. Sources requiring spatial steps within a line are packed on the GPU. Same-dtype packing preserves sample bits and band order. The native resource owner admits scratch before encoding and retains it through completion or failure draining. Allocation exhaustion is a resource-limit error.

GeoTIFF write dtype#

The creation profile sets the stored dtype. DatasetWriter.write() converts GeoTIFF inputs to that dtype. The native input types are uint8, uint16, int16, int32, float32, and float64. Host GeoTIFF accepts any pair of these types. nvTIFF accepts those input types with uint8, uint16, or float32 storage. Pass a Float64 CuPy array to a Float32 profile to store it as Float32.

The cast follows Rasterio 1.4.4 with GDAL 3.10.3 and NumPy 1.26.4 on x86-64.

  • Equal dtypes preserve sample bits.

  • Integer casts keep the low bits of the destination width. Floating inputs truncate toward zero before the integer cast. NaN, infinity, and values whose truncated integer is outside the signed 32-bit range use the signed 32-bit minimum before narrowing. This stores zero in the 8- and 16-bit types.

  • Floating results round to nearest with ties to even. Float32 overflow stores signed infinity. Floating casts preserve signed zero and infinity, and NaN remains NaN.

Host mutation casts into the bounded staging buffer. CUDA mutation casts and packs in one pass on the supplied stream into a single device allocation sized for the stored samples. The conversion keeps all input pixels on the GPU.

Backends#

Driver

Host input

CUDA input

GeoTIFF

portable host writer

nvTIFF (nvtiff feature)

COG

portable host COG writer

rejected (see below)

JP2

nvJPEG2000 after an H2D copy (nvjpeg2k feature)

nvJPEG2000 (nvjpeg2k feature)

A build without the feature a route needs rejects that route; no other backend is substituted.

Device COG encoding and CUDA overview generation are not implemented. CUDA GeoTIFF writing without an internal mask places its main image directory before the encoded pixels, but does not generate the overview pyramid described below.

GeoTIFF#

The portable host writer covers every native scalar type, none, LZW or Deflate with Predictor 1, strips or tiles, and classic or BigTIFF. It encodes one block at a time with bounded resident sample buffers. Host GeoTIFF and COG writes also copy the complete image into a private, unlinked sample file in the destination directory before encoding. Allow additional disk space for every uncompressed sample, the unpublished encoded output and, for COG, its encoded tile spool. Resident buffers and private disk usage are accounted separately. Blocks above the writer’s per-chunk limit reject.

The nvTIFF route stores UInt8, UInt16 and Float32 with one or three to five bands and none, LZW or Deflate. nvTIFF writes the encoded strips or tiles straight into the temporary file through nvtiffWriteTiffFile, with cugeo-raster’s georeferencing and creation metadata supplied through nvtiffEncodeParamsSetTag. For writes without an internal mask, the main image directory precedes the encoded pixels. cugeo-raster sets alpha association in that directory in place. For grayscale images with extra bands, it rebuilds the directory before the pixels and moves compressed blocks within the temporary file if more metadata space is needed, using at most 64 KiB of accounted host staging. The selected predictor is preserved (1 for none; 2 for LZW and Deflate). This route is not GPUDirect Storage: nvTIFF finalizes the file through host-visible file I/O.

An axis-aligned north-up transform is written as ModelPixelScaleTag plus ModelTiepointTag; any other transform as ModelTransformationTag. COG output uses the same rule, so a rotated or sheared COG base image carries ModelTransformationTag; whether that conforms to OGC COG 1.0 is not established. PixelIsPoint serialization is the inverse of the reader’s half-pixel normalization. CRS and area or point are GeoKeys; nodata is GDAL_NODATA, scale and offset are GDAL_METADATA XML, and RPC00B, photometric interpretation and ExtraSamples are their TIFF tags.

COG#

The host COG writer requires tiles and nearest overviews whose last level fits in one tile along at least one dimension. It writes the header, every IFD and its tag values, and every tile offset and byte-count array before any image data, then image data from the smallest overview to the base, row-major within each level. Encoded tiles pass through a bounded spool, and the classic or BigTIFF choice follows from the complete size calculation. Reduced-resolution IFDs set NewSubfileType bit 0 and carry no georeference tags; the base carries the georeference once. Explicit alpha bands are downsampled with the imagery. Reopen checks the overview count and every factor. Overview samples use source[min(y * factor, height - 1), min(x * factor, width - 1)] on ceil-divided level dimensions. On odd dimensions this can differ from GDAL’s own nearest overview builder; parity with that builder is not established.

GeoTIFF output rejects overview factors; overviews are written only through the COG driver.

JP2#

The ordinary Python creation name and write-receipt driver are exactly nvJPEG2000. JP2, JP2OpenJPEG, GEOTIFF and GTIF are unsupported creation aliases and raise UnsupportedError with native code 2. Native container enums keep their TIFF/JP2 format meanings.

JP2 output is lossless reversible JPEG 2000 of UInt8 or UInt16 Gray or RGB source-order bands. An admitted grid has a transform, an EPSG CRS and area or point interpretation. Without a grid, the container omits georeferencing boxes; no CRS is invented. Width and height must each be at least two pixels for the nvJPEG2000 writer. For both host and CUDA input, Rust write-plan validation rejects a one-pixel width or height before encoding with Error::Unsupported: an unsupported-capability refusal, exposed as CUGEO_RASTER_UNSUPPORTED (2) in C and UnsupportedError with code == 2 in Python. These raster extents are valid but outside this backend’s supported output profile; zero dimensions are invalid input.

JP2 output rejects overview factors, tiles and a TIFF variant other than automatic; codestream resolution levels are derived by the codec. Alpha and other extra bands are rejected. Host input is first packed into one whole-image tight BIP host buffer and copied to the device; the receipt reports both. nvJPEG2000 encodes a raw codestream; cugeo-raster assembles the JP2 header with its image header (ihdr) and colour specification (colr, greyscale or sRGB) boxes, then an optional GeoJP2 UUID box generated by the same GeoTIFF serializer as TIFF output. The writer emits neither channel definitions (cdef) nor component mappings (cmap). Reader capability admission remains separate. A versioned cugeo-raster UUID box preserves sample type, source-order color meaning, ExtraSamples status, nodata including NaN, per-band scale and offset, and RPC00B. Jpeg2000Source.write_metadata, the JP2 C band and RPC queries, and ordinary Python dataset metadata recover these values without a sidecar. The codestream returns to host memory and the receipt reports its D2H bytes.

Metadata by format#

Metadata

GeoTIFF

COG

JP2

affine grid

GeoTIFF tags

base IFD GeoTIFF tags

GeoJP2 UUID

EPSG CRS

GeoKeys

base IFD GeoKeys

GeoJP2 UUID

non-EPSG CRS

rejected

rejected

rejected

area or point

GTRasterTypeGeoKey

base IFD GeoKey

GeoJP2 UUID

nodata

GDAL_NODATA

GDAL_NODATA on every level

owned UUID box

scale and offset

GDAL_METADATA XML

GDAL_METADATA XML

owned UUID box

color and alpha

photometric and ExtraSamples

same at every level

colr greyscale or sRGB box plus owned UUID box; alpha bands rejected

separate mask arrays

not a profile field

not a profile field

not a profile field

RPC00B

TIFF RPC tag

base IFD RPC tag

owned UUID box

overviews

rejected

reduced-resolution IFDs in the next-IFD chain

rejected

descriptions and units

GDAL_METADATA band roles

GDAL_METADATA band roles

Unsupported (2)

explicit key/value and XML domains

dataset and band GDAL_METADATA items

dataset and band GDAL_METADATA items

dataset XML box; band scopes Unsupported (2)

Receipt#

The final receipt, available after successful close, records:

  • path, driver, concrete backend (portable-host, nvtiff or nvjpeg2000), TIFF variant, compression and block layout;

  • logical bytes at the stored dtype, encoded payload bytes, metadata bytes and file bytes;

  • chunk count, overview count and overview resampling;

  • chunk-staging and layout-conversion bytes, plus a separate admission budget;

  • H2D, D2H and D2D transfer bytes;

  • whether the output was reopened and atomically published; and

  • host-monotonic timings for codec setup, encode, finalize, encoded write, codec cleanup, staging parse, container assembly, file sync, verification and publication.

Transfers cugeo-raster owns are counted exactly. For nvTIFF file output the encoded payload bytes are attributed to the codec’s device-to-host and file-finalization boundary; nvTIFF does not expose its private copies. writer.budget reports the shared admission capacity, record capacity and requested-byte high water separately from the chunk-staging receipt. admission_control_known_bytes reports the shared gate’s fixed record table and control object outside that working-byte capacity; it excludes the standard library’s private Arc allocation header. The working-byte high water includes observable buffer/table/metadata lifetimes, borrowed whole host backing and codec workspace reservations. Diagnostic error-message storage is outside the managed working-byte capacity; exhausted sessions retain full text and structured error codes. The pinned LZW dictionary reservation is a structural bound; it is not a measurement of the allocator’s actual use. Host JPEG 2000 encoding allocates its H2D input, and CUDA writers allocate packing scratch when needed, through the native CUDA memory resource. CUDA packing and dtype conversion use one device allocation sized for the stored samples and report that size in device_to_device_bytes. If packing changes the source layout, the same size appears in layout_conversion_bytes. Direct encoder input reports zero for both. backend_resource_control_peak_bytes reports known native record table and Rust control payload, admitted before construction. Packing preparation’s known Rust payload is included; private Arc headers and CUDA event storage are excluded opaque costs. backend_device_capacity_bytes and backend_device_peak_bytes report the managed device limit and allocation high water separately from host admission. CUDA pool backing, event internals and private allocation headers are opaque. Private sample, encoded-output and COG spool facts report filesystem logical bytes and allocated bytes separately. Missing disk evidence is unavailable or an error, not a fictitious capacity. These counters are not process RSS, allocator bookkeeping, isolation or a bound on opaque codec-private allocation. PROJ internals, serde_json’s temporary parsing/DOM workspace and roxmltree’s private XML workspace are also opaque; known retained strings and query buffers remain admitted. Host backing facts follow NumPy and buffer-protocol owners, including mapped files. CUDA backing facts come from the native allocation owner in the current context. Missing ownership evidence is a missing-capability refusal rather than a resource-exhaustion report. Timings are host-observed, not CUDA event times.

Performance against GDAL and Rasterio is not established. benchmarks/benchmark_raster_write.py, its GDAL and Rasterio helpers, and benchmarks/benchmark_raster_pipeline.py are the runners.

References#