Raster Processing API¶
Build Cloud-Optimized GeoTIFFs and convert rasters to H3-indexed GeoParquet directly from Python. The cng-datasets raster-workflow jobs call these same functions.
Raster data processing utilities.
- class cng_datasets.raster.RasterProcessor(input_path: str | List[str], output_cog_path: str | None = None, output_parquet_path: str | None = None, h3_resolution: int | None = None, parent_resolutions: List[int] | None = None, h0_index: int | None = None, chunk_resolution: int = 0, chunk_index: int | None = None, window_reads: str = 'auto', h0_subset: List[int] | None = None, h0_grid_path: str = 's3://public-grids/hex/h0-valid.parquet', value_column: str = 'value', compression: str = 'deflate', blocksize: int = 512, resampling: str = 'nearest', hex_resampling: str = 'mean', method: str = 'exact-extract', nodata_value: float | str | List[float] | None = None, target_crs: str = 'EPSG:4326', target_extent: tuple | None = None, target_resolution: float | None = None, band: int | None = None, local_cache_dir: str | None = '/tmp/cng-raster-cache', cutline: str | None = None, cutline_where: str | None = None, value_units: str | None = None, read_credentials: Dict[str, str] | None = None, write_credentials: Dict[str, str] | None = None)[source]¶
Bases:
objectProcess raster datasets into cloud-native formats.
Converts raster data to COG format and H3-indexed parquet files partitioned by h0 cells, processing each h0 region separately for memory efficiency with global datasets.
- __init__(input_path: str | List[str], output_cog_path: str | None = None, output_parquet_path: str | None = None, h3_resolution: int | None = None, parent_resolutions: List[int] | None = None, h0_index: int | None = None, chunk_resolution: int = 0, chunk_index: int | None = None, window_reads: str = 'auto', h0_subset: List[int] | None = None, h0_grid_path: str = 's3://public-grids/hex/h0-valid.parquet', value_column: str = 'value', compression: str = 'deflate', blocksize: int = 512, resampling: str = 'nearest', hex_resampling: str = 'mean', method: str = 'exact-extract', nodata_value: float | str | List[float] | None = None, target_crs: str = 'EPSG:4326', target_extent: tuple | None = None, target_resolution: float | None = None, band: int | None = None, local_cache_dir: str | None = '/tmp/cng-raster-cache', cutline: str | None = None, cutline_where: str | None = None, value_units: str | None = None, read_credentials: Dict[str, str] | None = None, write_credentials: Dict[str, str] | None = None)[source]¶
Initialize the raster processor.
- Parameters:
input_path – Path(s) to input raster file(s). A single string or a list of tile URLs/paths (possibly in mixed CRS — they will be mosaicked and reprojected to target_crs before processing).
output_cog_path – Path for output COG file (optional)
output_parquet_path – Base path for output parquet (e.g., s3://bucket/dataset/hex/)
h3_resolution – Target H3 resolution (auto-detected if None)
parent_resolutions – List of parent resolutions to include (e.g., [9, 8, 0])
h0_index – Specific h0 cell index to process (0-121), or None for all
chunk_resolution – H3 resolution of the unit of work. 0 (default) is one h0 base cell per invocation, the historical behaviour. A higher value splits each h0 into its res-N descendants, so peak memory — which tracks the largest chunk’s cell count, not the raster’s size — falls by roughly 7x per level (issue #173).
chunk_index – Which chunk to process, indexing the ordered chunk list for chunk_resolution. At chunk_resolution 0 this is exactly h0_index; either may be given.
window_reads – Whether a chunk reads only its own window of the source COG instead of localizing the whole file. “auto” (default) windows whenever the source is remote, at any chunk resolution; “always” and “never” force it. Full localization costs one whole-file copy per pod, so transfer and ephemeral disk scale with the fan-out rather than with the data — already wasteful across 122 h0 pods (issue #209), ruinous across the thousands sub-h0 chunking creates (issue #173, lever C).
h0_subset – Restrict the chunk list to descendants of these h0 base cell indices, so a regional source never enumerates chunks it cannot overlap (issue #191, applied at chunk granularity).
h0_grid_path – Path to h0 grid parquet file
value_column – Name for the raster value column in parquet
compression – Compression method for COG (deflate, lzw, zstd, etc.)
blocksize – Block size for COG tiling
resampling – Resampling method for COG creation (default: “nearest”)
hex_resampling – Reducer for aggregating source pixels into each H3 cell. With method=”exact-extract” (default), one of: “sum” (counts/stocks like population), “mean” (intensities like NDVI), “mode” (categorical like land cover — single dominant class per cell), “fractions” (categorical area accounting — one LONG (value, frac) row per class present in each cell, with nodata kept as an explicit class so frac sums to <= 1 and area is SUM(frac * cell_area), issue #142), “max”/”min” (peak/extremum like species richness, where sum double-counts and mean averages away the hotspot). With method=”warp-centroid”, any GDAL resampleAlg is accepted (“average”, “sum”, “mode”, “near”, “bilinear”, “cubic”, …). Default: “mean”.
method – Which raster→hex algorithm to use. “exact-extract” (default) is area-weighted, mass-conserving, one row per cell — recommended for stock rasters (population, carbon). “warp-centroid” is the older gdal.Warp→XYZ→centroid path: fast, low-memory, but emits one row per warped pixel (consumers GROUP BY h<res>). Mass-conserving only when the hex pitch is finer than the source pixel pitch — see issue #84 for the regime analysis.
nodata_value – NoData value(s) to exclude from H3 conversion and to collapse in the COG warp. Accepts a single number, a list, or a comma-separated string (“-9999,-1111,32767”) for categorical products with multiple fill codes (issue #108).
target_crs – CRS for output (default: EPSG:4326); used when mosaicking
target_extent – Clip extent (xmin, ymin, xmax, ymax) in target_crs; used when mosaicking
target_resolution – Output pixel size in target_crs units; used when mosaicking
band – Extract a single band from multi-band sources (1-indexed); used when mosaicking
cutline – Polygon layer to clip to, as in create_mosaic_cog (#344).
cutline_where – Attribute filter on the cutline.
value_units – Units of the source values, e.g. “Mg/ha” (#105). Required by hex_resampling=”total”, whose per-area denominator sets the scale; refused with “sum” when per-area. Recorded as value_units in each partition’s metadata (for “total”, the units without the area: “Mg”).
read_credentials – Dict with AWS credentials for reading
write_credentials – Dict with AWS credentials for writing
- chunk_cells()[source]¶
Ordered [(chunk_cell, h0_cell, h0_index)] — this processor’s units of work.
Thin wrapper over enumerate_chunk_cells, which is shared with the workflow generator so the fan-out it emits and the list a pod indexes into cannot drift apart.
- create_cog(output_path: str | None = None, overviews: bool = True, overview_resampling: str | None = None) str[source]¶
Create a Cloud-Optimized GeoTIFF from input raster.
Optimized for cloud rendering in services like titiler with: - Internal tiling - Overview pyramids - Optimized compression - EPSG:4326 reprojection
- Parameters:
output_path – Path for output COG (uses self.output_cog_path if None)
overviews – Whether to create overview pyramids
overview_resampling – Resampling method for overviews. Defaults to “mode” when hex_resampling is categorical (“mode”/”fractions” — averaging class codes corrupts the zoomed-out COG, issue #108) and “average” otherwise.
- Returns:
Path to created COG file
- process_all_h0_regions() List[str][source]¶
Process every h0 region of the grid to H3-indexed parquet, or just the ones named by h0_subset.
h0_subset used to be ignored here: the loop ran the whole grid, so a flag that parsed, validated and printed its restriction quietly did nothing on this path, and the run reported Processing h0 grid position 0 … 121 regardless (issue #215). It applied only to enumerate_chunk_cells, which this method never called. A subset flag that appears to have been accepted is the same shape of defect as #213 and #218, in a different register.
The positions come from the grid via the same enumeration the workflow generator and process_chunk use, rather than range(122), so the list cannot drift from the grid it is indexing into.
- Returns:
List of output parquet file paths
- process_chunk(chunk_index: int | None = None) str | None[source]¶
Process one chunk (an h0 cell, or a sub-cell of one) to parquet.
Generalizes process_h0_region to any chunk_resolution. At chunk_resolution 0 it resolves to the same h0 cell, the same geometry from the stored grid and the same output path, so the default path is unchanged.
Returns the output parquet path, or None when the chunk has no data.
- process_h0_region(h0_index: int | None = None) str | None[source]¶
Process a single h0 region to H3-indexed parquet.
Polyfills the h0 cell to its native-resolution H3 children and area-weighted-aggregates source-raster values into each cell via exactextract. Parent resolutions are added as decoration columns.
- Parameters:
h0_index – h0 cell index (0-121), uses self.h0_index if None
- Returns:
Path to output parquet file, or None if region has no data
- cng_datasets.raster.create_cog(input_path: str, output_path: str, compression: str = 'deflate', blocksize: int = 512, overviews: bool = True, resampling: str = 'nearest', **kwargs) str[source]¶
Create a Cloud-Optimized GeoTIFF.
Convenience function that wraps RasterProcessor.create_cog().
- Parameters:
input_path – Path to input raster file
output_path – Path for output COG file
compression – Compression method (deflate, lzw, zstd, etc.)
blocksize – Internal tile size
overviews – Whether to create overview pyramids
resampling – Resampling method
**kwargs – Additional arguments passed to RasterProcessor
- Returns:
Path to created COG file
- cng_datasets.raster.create_mosaic_cog(source_urls: List[str], output_path: str, target_crs: str = 'EPSG:4326', target_extent: tuple | None = None, target_resolution: float | None = None, band: int | None = None, nodata: float | str | List[float] | None = None, resampling: str = 'bilinear', compression: str = 'deflate', overview_resampling: str = 'average', cutline: str | None = None, cutline_where: str | None = None) str[source]¶
Mosaic multiple raster tiles (potentially in different CRS) into a single COG.
Handles the common case where source data is distributed as per-UTM-zone tiles (e.g. RAP 10m products across zones 12 and 13 for Wyoming). Groups tiles by CRS, warps each group to the target CRS, merges, then writes a Cloud-Optimized GeoTIFF.
- Parameters:
source_urls – List of tile paths/URLs (local, /vsicurl/, s3://). Tiles may be in mixed CRS (e.g. multiple UTM zones).
output_path – Destination path for the COG (local path or s3://).
target_crs – Output CRS (default: EPSG:4326).
target_extent – Clip extent as (xmin, ymin, xmax, ymax) in target_crs. If None, uses the union of all tile extents.
target_resolution – Output pixel size in target_crs units (e.g. 0.0001 for ~10m in degrees). If None, derived from the finest source tile.
band – Extract a single band from multi-band sources (1-indexed). If None, all bands are preserved.
nodata – NoData value(s) for output. Accepts a single number, a list, or a comma-separated string (“-9999,-1111,32767”); all are applied as srcNodata and collapsed to the first as dstNodata so multi-fill categorical products end up with one nodata (issue #108). If None, inherited from source tiles.
resampling – Resampling algorithm for warping (default: bilinear).
compression – COG compression (deflate, lzw, zstd).
overview_resampling – Resampling for COG overviews. Use “mode”/”nearest” for categorical sources — “average” corrupts class codes.
cutline – A polygon layer (local path or URL; GeoParquet, GPKG, GeoJSON, a zipped shapefile, …) to clip to (#344). Pixels whose centre falls outside it become nodata. Tiles already on the target grid keep it: the extent is the polygon’s bounds snapped outward to the source pixels, cut to the source, and the warp is nearest, so values pass through unchanged.
cutline_where – An attribute filter on the cutline, e.g. “iso3 = ‘PER’”.
- Returns:
output_path (echoed back for chaining)
- cng_datasets.raster.detect_nodata_value(raster_path: str, verbose: bool = True) float | None[source]¶
Detect NoData value from raster metadata.
- Parameters:
raster_path – Path to raster file (can be /vsis3/ URL)
verbose – Whether to print detection message (default: True)
- Returns:
NoData value if found, None otherwise
- cng_datasets.raster.detect_optimal_h3_resolution(raster_path: str, verbose: bool = True) int[source]¶
Detect optimal H3 resolution based on raster resolution.
Uses the finest pixel dimension to recommend an H3 resolution. H3 average edge lengths (from https://h3geo.org/docs/core-library/restable): - h15: 0.58m, h14: 1.5m, h13: 4.1m, h12: 10.8m, h11: 28.7m - h10: 75.9m, h9: 200.8m, h8: 531.4m, h7: 1.4km, h6: 3.7km - h5: 9.9km, h4: 26.1km, h3: 69.0km, h2: 182.5km, h1: 483.1km, h0: 1281.3km
- Parameters:
raster_path – Path to raster file (can be /vsis3/ URL)
verbose – Whether to print detection message (default: True)
- Returns:
Recommended H3 resolution (0-15)
- cng_datasets.raster.h3_resolution_join_warning(resolution: int, user_specified: bool, parent_resolutions: List[int] | None = None) str | None[source]¶
Build the warning text when a build carries no path to the h8 join key.
Two ways to lose it, both silent today (issue #182):
Target too coarse. detect_optimal_h3_resolution targets ~3x the source pixel edge, which agrees with the catalog convention at fine pixels and diverges as pixels coarsen — a ~1 km global raster auto-detects h6, two levels below h8. Detection is only a suggestion, so a caller who omits
--h3-resolutiongets a non-joinable dataset with no error, only an informational log line.h8 not among the parents. A finer target only carries h8 if h8 is a requested parent resolution, and the default is
--parent-resolutions 0— so an h10 build emits h10 and h0 and nothing to join on.
- Parameters:
resolution – The H3 resolution the build will actually use
user_specified – Whether the caller passed the resolution explicitly
parent_resolutions – Parent resolutions the build will emit. None skips the parent check, for callers that do not know them yet.
- Returns:
Warning text, or None when the build can join on h8
- cng_datasets.raster.is_cog(url: str) bool[source]¶
Check if a raster is a Cloud-Optimized GeoTIFF.
Returns True if the raster has tiled blocks and internal overviews (COG structure). Returns True (fail-safe) if the file cannot be opened — avoids unnecessary preprocess steps when network access is unavailable at workflow-generation time. Returns False only when the file is confirmed to be non-COG.
- Parameters:
url – Path to raster file (s3://, https://, or local path).
- Returns:
True if COG (or unverifiable), False if confirmed non-COG.