Vector Processing API¶
Convert vector sources to H3-indexed GeoParquet directly from Python, with no Kubernetes involved. The cng-datasets workflow jobs call these same functions.
Vector data processing utilities.
- class cng_datasets.vector.H3VectorProcessor(input_url: str, output_url: str, h3_resolution: int = 10, parent_resolutions: List[int] | None = None, chunk_size: int = 500, intermediate_chunk_size: int = 10, id_column: str | None = None, resolution_by_area: List[Tuple[float | None, int]] | None = None, read_credentials: Dict[str, str] | None = None, write_credentials: Dict[str, str] | None = None, plan_url: str | None = None, polyfill: str = 'centre')[source]¶
Bases:
objectProcess vector datasets into H3-indexed parquet files.
Handles chunked processing of large vector datasets, converting geometries to H3 cells and adding parent cell hierarchies.
- __init__(input_url: str, output_url: str, h3_resolution: int = 10, parent_resolutions: List[int] | None = None, chunk_size: int = 500, intermediate_chunk_size: int = 10, id_column: str | None = None, resolution_by_area: List[Tuple[float | None, int]] | None = None, read_credentials: Dict[str, str] | None = None, write_credentials: Dict[str, str] | None = None, plan_url: str | None = None, polyfill: str = 'centre')[source]¶
Initialize the H3 vector processor.
- Parameters:
input_url – S3 URL or local path to input parquet/geoparquet file
output_url – S3 URL or local path to output directory
h3_resolution – Target H3 resolution for tiling. Ignored when resolution_by_area is set (the finest bin resolution is used).
parent_resolutions – List of parent resolutions to include (e.g., [9, 8, 0])
chunk_size – Number of rows to process in pass 1 (geometry to H3 arrays)
intermediate_chunk_size – Number of rows to process in pass 2 (unnesting arrays)
id_column – Name of ID column to use (auto-detected if not specified)
resolution_by_area – Optional parsed bins from parse_resolution_by_area (issue #98). When set, each feature is hexed at the native resolution its planar ST_Area maps to, and the output carries a union schema (one column per resolution in the bins + parent_resolutions, finer columns NULL in coarser tiers) plus a native_res column.
read_credentials – Dict with AWS credentials for reading (key, secret, region, endpoint)
write_credentials – Dict with AWS credentials for writing (key, secret, region, endpoint)
plan_url – Optional chunk plan from cng-datasets vector-plan (issue #124). When set, chunk K is the plan’s row range K rather than rows [K * chunk_size, (K + 1) * chunk_size), and chunk_size is not used to select rows.
polyfill – ‘centre’ (default) keeps the cells whose centre a polygon contains. ‘overlap’ keeps every cell a polygon’s area touches and adds a
cover_fraccolumn, the share of the cell inside it (issue #363; see h3_overlap). With resolution_by_area, each feature is filled at its native resolution andcover_fracis the share of its native cell.
- process_all_chunks() List[str][source]¶
Process all chunks in the dataset.
- Returns:
List of output file paths
- process_chunk(chunk_id: int, keep_cols: List[str] | None = None) str | None[source]¶
Process a single chunk using two-pass approach to avoid OOM.
Pass 1: Convert geometries to H3 cell arrays (no unnesting) Pass 2: Read small batches, unnest arrays, write final output
- Parameters:
chunk_id – Zero-based chunk index to process
keep_cols – List of attribute columns to keep
- Returns:
Output file path if successful, None if chunk_id out of range
- cng_datasets.vector.geom_to_h3_cells(con: DuckDBPyConnection, table_name: str, zoom: int = 10, keep_cols: List[str] | None = None, geom_col: str = 'geom', resolution_by_area: List[Tuple[float | None, int]] | None = None) str[source]¶
Convert geometries to H3 cells at specified resolution.
- Parameters:
con – DuckDB connection
table_name – Name of the table or view with geometry column
zoom – H3 resolution level (0-15). Used when resolution_by_area is None.
keep_cols – List of columns to keep from input. If None, keeps all except geom.
geom_col – Name of the geometry column
resolution_by_area – Optional parsed bins from parse_resolution_by_area. When provided, each feature is hexed at the native resolution its planar ST_Area maps to (issue #98), and a per-feature
native_rescolumn is emitted alongsideh3id. Points/lines have ~0 planar area and so fall in the finest (first) bin. When None, every feature is hexed atzoom.
- Returns:
SQL query string that generates H3 cells
- cng_datasets.vector.process_vector_chunks(input_url: str, output_url: str, chunk_id: int | None = None, h3_resolution: int = 10, parent_resolutions: List[int] | None = None, chunk_size: int = 500, intermediate_chunk_size: int = 10, **kwargs) List[str] | None[source]¶
Convenience function to process vector data into H3-indexed chunks.
- Parameters:
input_url – S3 URL or local path to input file
output_url – S3 URL or local path to output directory
chunk_id – Specific chunk to process, or None to process all
h3_resolution – Target H3 resolution
parent_resolutions – List of parent resolutions to include
chunk_size – Number of rows per chunk in pass 1
intermediate_chunk_size – Number of rows per batch in pass 2 (unnesting)
**kwargs – Additional arguments passed to H3VectorProcessor
- Returns:
List of output file paths, or None if single chunk was out of range
- cng_datasets.vector.repartition_by_h0(chunks_dir: str, output_dir: str, source_parquet: str = None, cleanup: bool = True, memory_limit: str = None, sort_range_rows: int = None) None[source]¶
Repartition chunks by h0 for efficient spatial querying. Joins back attribute columns from source parquet (without geometry).
- Parameters:
chunks_dir – S3 URL or local path to chunks directory
output_dir – S3 URL or local path to output directory
source_parquet – S3 URL to original parquet (for joining attributes)
cleanup – Whether to remove chunks directory after repartitioning
memory_limit – DuckDB memory limit (e.g. ‘27GiB’). Falls back to DUCKDB_MEMORY_LIMIT env var. If neither is set, DuckDB auto-detects (which may ignore container cgroup limits).
sort_range_rows – Most rows sorted at once (default: the CNG_SORT_RANGE_ROWS env var, else default_sort_range_rows of the memory limit, 50M rows per 40GiB and at most 50M). A larger h0 partition is sorted in contiguous id ranges of about this many rows, which are then streamed in order into its one file, so scratch space tracks the range rather than the partition (#339).
Converting to GeoParquet¶
convert_to_parquet is the convert step. It lives in its own submodule:
from cng_datasets.vector.convert_to_parquet import convert_to_parquet.
- cng_datasets.vector.convert_to_parquet.convert_to_parquet(source_url: str | List[str], destination: str, compression: str = 'ZSTD', compression_level: int = 15, row_group_size: int = 100000, geometry_encoding: str = 'WKB', id_column: str | None = None, force_id: bool = True, progress: bool = True, target_crs: str = 'EPSG:4326', layer: str | None = None, verbose: bool = False, simplify_tolerance: float | None = None, lat_column: str | None = None, lon_column: str | None = None, trim_strings: bool = False, expect_features: int | None = None, csv_sample_size: int = -1, spatial_order: bool = True)[source]¶
Convert a vector dataset to optimized GeoParquet.
Workflow: 1. Detect source CRS using GDAL 2. Check if ID column exists or needs creation 3. Build DuckDB query to read, add ID, and reproject 4. Write GeoParquet with DuckDB COPY 5. Upload to S3 via rclone if destination is S3
- Parameters:
source_url – Source dataset URL or list of URLs (supports s3://, http://, file paths). Multiple URLs will be merged with UNION ALL.
destination – Output path (s3:// or local file path)
compression – Compression algorithm (ZSTD, GZIP, SNAPPY, NONE)
compression_level – Compression level (1-22 for ZSTD)
row_group_size – Number of rows per group
geometry_encoding – Geometry encoding (WKB, WKT)
id_column – Specific ID column to use (auto-detected if not specified)
force_id – Create _cng_fid if no suitable ID column exists
progress – Show progress during conversion
target_crs – Target CRS for output (default: EPSG:4326). The source is reprojected whenever its own CRS differs, including when that CRS carries no EPSG or authority code and is only available as a WKT definition (issue #187). A source that declares no CRS at all is assumed to be in target_crs already and written unchanged.
layer – Layer name for multi-layer datasets (e.g., GDB)
verbose – Print detailed debug information
simplify_tolerance – Optional geometry simplification tolerance in target-CRS units (e.g. degrees for EPSG:4326), applied after reprojection via ST_SimplifyPreserveTopology (issue #132)
lat_column – Latitude column name for CSV point input (auto-detected if not given, issue #78)
lon_column – Longitude column name for CSV point input (auto-detected if not given, issue #78)
trim_strings – Strip leading/trailing whitespace from every string (VARCHAR) attribute column. Off by default so outputs stay faithful to the source; opt in for sources whose categorical fields carry stray whitespace (e.g. WDPA NO_TAKE = ‘All ‘, issue #180).
expect_features – Row count this conversion is expected to produce, known independently by the caller (issue #186). The count is always logged; when this is given and the written count differs, the conversion raises FeatureCountMismatch so a pipeline can gate on it.
csv_sample_size – For CSV point sources, rows read_csv_auto samples for type inference; -1 (the default) scans the whole file (issue #188).
spatial_order – Write rows in Hilbert order of their geometry and number a synthetic _cng_fid in that order (issue #276). Turn off to keep source order, e.g. when the sort will not fit the pod.