Skip to content

Advanced source access

These interfaces expose HFX records, relationships, traversal, native raster windows, metadata and diagnostics. Use the core operations for hydrological selection rather than rebuilding it from source primitives.

pourpoint.HydroFabric

Open one HFX publication for eager queries and reusable source access.

Parameters:

Name Type Description Default
source str | Path

Dataset root directory or HTTP(S)/S3 URL containing manifest.json.

required
cache bool | Literal['auto']

Persistent disk caching mode: "auto" (default) enables disk caching for remote sources (HTTP, HTTPS, S3) and disables it for local filesystem paths; True or False forces caching on or off. Disabling disk caching does not disable bounded in-memory reuse.

'auto'
cache_dir str | Path | None

Persistent cache location. When omitted, use ~/Library/Caches/pourpoint on macOS, %LOCALAPPDATA%/pourpoint on Windows (falling back to ~/AppData/Local/pourpoint), or $XDG_CACHE_HOME/pourpoint on other platforms (falling back to ~/.cache/pourpoint).

None
offline bool

Require the cached manifest snapshot and cached content without network access. Requires caching to be active (pass cache=True for local paths since "auto" disables local disk caching). Missing content raises rather than returning incomplete results.

False
storage_options Mapping[str, object] | None

Options passed to the remote object store, including S3 credentials or endpoint configuration. Local paths do not accept storage options.

None

Attributes:

Name Type Description
manifest

Parsed publication metadata, artifact identities and relationship declarations for this lifetime.

Notes

Opening reads only the manifest; vector and raster readers open as needed. Use a context manager and perform source-dependent work before it closes. Materialized vector results and raster arrays survive closure, but readers and raster requests cannot be used to acquire more data afterward. Instances belong to one thread; calls must not overlap.

The disk cache grows across queries against the same snapshot. Closing does not remove it and there is no automatic disk eviction. A partial cache is not necessarily an independently openable HFX publication.

rasters: RasterReader property

Native-grid raster access owned by this open fabric's lifecycle.

stats: TransferStats property

Cumulative transport calls, payload bytes and disk-cache hit bytes.

buffer_bytes: dict[str, int] property

Logical source/vector buffer bytes, not total process memory.

Excludes native-library caches, metadata and caller-owned results.

records(domain: str, ids: Sequence[int], *, columns: Sequence[str] | None = None) -> pa.Table

Read source rows in requested order, preserving duplicate IDs.

Parameters:

Name Type Description Default
domain str

Published feature family: catchments, rivers or river_nodes.

required
ids Sequence[int]

Positive int64 source IDs. Empty input returns an empty table with the selected schema; an unknown ID raises KeyError.

required
columns Sequence[str] | None

Unique source field names to read, or all fields when omitted. Geometry is original WKB, not decoded Shapely geometry.

None

Returns:

Type Description
Table

Materialized values with source types, nulls and applicable schema and field metadata. Remains usable after closure.

Raises:

Type Description
ValueError

Invalid IDs, unknown or duplicate columns, or corrupt source data.

KeyError

The domain or a requested ID is not supplied.

candidates(domain: str, bounds: BoundingBox, *, levels: Sequence[int] | None = None, columns: Sequence[str] | None = None) -> pa.Table

Read conservative bounding-box candidates, not exact intersections.

Parameters:

Name Type Description Default
domain str

Published catchments, rivers or river_nodes family.

required
bounds BoundingBox

Non-wrapping (west, south, east, north) envelope in EPSG:4326. Accepts a four-element sequence or 1D NumPy array of real numbers.

required
levels Sequence[int] | None

Nonnegative source levels to retain; omitted means all levels. Levels are independent between feature families.

None
columns Sequence[str] | None

Unique source field names, or all fields when omitted.

None

Returns:

Type Description
Table

Materialized source rows in publication order. False positives are possible; test decoded geometry for exact intersection. No matches returns an empty table with the selected schema.

relationships(domain: str, ids: Sequence[int], *, columns: Sequence[str] | None = None) -> pa.Table

Read immediate supplied relationships in requested ID order.

Parameters:

Name Type Description Default
domain str

Feature family whose relationship rows are requested.

required
ids Sequence[int]

Positive int64 source IDs; duplicates and order are preserved.

required
columns Sequence[str] | None

Unique relationship fields to read, or all fields when omitted.

None

Returns:

Type Description
Table

Selected source relationship columns, with supplied metadata. Neighbor IDs are retained as lists; id is included only when selected. Consult manifest.relationships for each field's target domain and meaning. Flow, hierarchy and node incidence are not interchangeable. References to unselected features remain present; they do not imply natural terminals. Empty input returns a schema-bearing empty table.

Raises:

Type Description
KeyError

Relationship data for the domain or a requested ID is not supplied.

ValueError

Invalid IDs, columns or relationship data.

traverse(domain: str, ids: Sequence[int], *, relationship: str = 'upstream_ids') -> list[int]

Return inclusive closure over a supplied same-domain relationship.

Parameters:

Name Type Description Default
domain str

Feature family to traverse without crossing domains.

required
ids Sequence[int]

Positive int64 seed IDs. Duplicate seeds are visited only once.

required
relationship str

Declared relationship column targeting the same domain. Traversal follows only that relationship; it does not infer hydrological flow.

'upstream_ids'

Returns:

Type Description
list

Breadth-first IDs: seeds in input order, then each frontier sorted by ID. Cycles are deduplicated; empty seeds return an empty list.

Raises:

Type Description
ValueError

The relationship is absent or targets another domain, or data is invalid.

KeyError

Domain relationship data or a visited ID is unavailable.

subbasins(ids: Sequence[int]) -> list[Subbasin]

Materialize whole source sub-basins in ID order, including duplicates.

Uses records ID validation and missing-ID behavior. Geometry is decoded only when a feature's geometry property is accessed.

nodes(ids: Sequence[int]) -> list[SourceNode]

Materialize source nodes in ID order, with records ID semantics.

river_network(ids: Sequence[int]) -> RiverNetwork

Materialize selected rivers, their relationships and referenced nodes.

River order and duplicates follow ids; referenced nodes are unique and sorted by ID. Relationships retain references to unselected rivers. No clipping, traversal or inference of flow is performed.

Raises:

Type Description
KeyError

The river family or its relationship data are not supplied, even for empty IDs, or a requested river or referenced node is missing.

close() -> None

Release source readers and connections; retain the persistent cache.

Repeated closure is harmless. Materialized tables, features and raster arrays remain usable; subsequent source-dependent calls fail.

pourpoint.features.Attributes

Bases: Mapping[str, object]

Read-only mapping of source fields other than geometry.

Iteration exposes field names, including standard fields such as id. Indexing converts an Arrow scalar to its Python value; source nulls become None. Use scalar and schema for lossless typed inspection. Values are source quantities, not recomputed measurements of clipped pieces.

schema: pa.Schema property

Attribute fields with source field/schema metadata, excluding geometry.

scalar(name: str) -> pa.Scalar

Return a typed source value, including nulls; geometry raises KeyError.

pourpoint.rasters.RasterReader

Read native-grid raster pairs through an open fabric's rasters property.

Headers open lazily during prepare without acquiring vector data. Use the reader on its creating thread; calls must not overlap. Fabric closure closes this reader. GDAL owns native caches, so closure releases handles but does not necessarily release process-wide cache allocations.

prepare(envelope: BoundingBox, *, crs: str | CRS = 'EPSG:4326') -> RasterRequest

Resolve bounds into enclosing whole native cells, without pixel reads.

Parameters:

Name Type Description Default
envelope BoundingBox

Positive-area (xmin, ymin, xmax, ymax) bounds in crs, as a four-element sequence or 1D NumPy array of real numbers. Geographic bounds must not wrap the antimeridian.

required
crs str | CRS

Envelope CRS. Coordinates use x/y order. Projected bounds can avoid an unnecessarily large geographic bounding envelope.

'EPSG:4326'

Returns:

Type Description
RasterRequest

Enclosing cells from the first declared pair covering the entire envelope. No mosaic or partial-coverage fallback is performed.

Raises:

Type Description
MissingRastersError

The publication declares no D8 pair.

RasterCoverageError

No declared pair covers the whole request.

ValueError

Bounds, CRS, raster declarations or pair headers are invalid.

RuntimeError

The reader is closed, used from another thread or already in use.

Notes

Opens and validates pair headers, potentially acquiring source bytes. CRS conversion densifies all four edges with 101 interior samples per edge rather than transforming only opposite corners. Direction pointers remain on the native grid.

read(request: RasterRequest) -> RasterWindow

Read both bands and independent validity masks without resampling.

Parameters:

Name Type Description Default
request RasterRequest

Window prepared by this reader while it remains open.

required

Returns:

Type Description
RasterWindow

Caller-owned native-grid arrays. Direction codes declared as esri, merit, taudem or grass are normalized, while raw_direction retains original source values and dtype. Accumulation values retain their source dtype and units.

Raises:

Type Description
ValueError

The request belongs to another reader or has an invalid grid/window, consumed direction codes are invalid, or valid accumulation values are negative or nonfinite. Source integrity failures also raise.

RuntimeError

The reader is closed, used from another thread or already in use.

close() -> None

Release native raster handles; materialized arrays remain usable.

Repeated closure is harmless. Outstanding requests cannot be read after closure. The fabric normally manages this lifetime.

pourpoint.rasters.RasterRequest dataclass

Whole-cell window prepared by one live raster reader.

Attributes:

Name Type Description
col, row

Zero-based upper-left column and row in the full source grid.

width, height

Window dimensions in native cells.

grid RasterGrid

Full source grid descriptor, including CRS, affine and raster identities.

Notes

Pass this request to the reader that prepared it, before that reader closes. It retains no pixel arrays and cannot be transferred to another reader.

pourpoint.rasters.RasterWindow dataclass

Caller-owned arrays on the unwarped grid, with independent validity masks.

Direction: 1 E, 2 SE, 3 S, 4 SW, 5 W, 6 NW, 7 N, 8 NE; 0 terminal. Negative directions are exiting flow (terminal for upstream tracing). Mask-false direction payloads are zero, not valid terminal cells. Accumulation keeps native dtype and declared units, without area conversion.

Attributes:

Name Type Description
direction NDArray[int8]

Normalized D8 codes indexed by window-relative row and column.

accumulation NDArray[int32] | NDArray[float32]

Source accumulation values, without recomputation or unit conversion.

direction_valid, accumulation_valid

Independent boolean validity masks combining the source mask and header nodata. Use the corresponding mask rather than interpreting payloads alone.

transform Affine

Affine mapping window-relative pixel corners to native coordinates.

crs CRS

Native grid CRS; direction pointers have not been warped.

accumulation_units Literal['cells', 'km2']

Source units: contributing cell count or square kilometres.

request RasterRequest

Read extent and full source grid; its row/column offsets locate these arrays within that grid.

raw_direction NDArray[uint8] | NDArray[int8] | None

Original encoded direction values and source dtype (uint8 or int8) when retained, otherwise None. Preserves distinctions collapsed into normalized terminal 0 (such as MERIT river mouth 0 versus inland depression 255 or -1).

direction_nodata, accumulation_nodata

Source header nodata values when retained, otherwise None.

Notes

Arrays remain usable after reader/fabric closure. Array indices are relative to this window, unlike request.row and request.col.

pourpoint.rasters.RasterGrid dataclass

Native source grid shared by a direction/accumulation pair.

Attributes:

Name Type Description
crs CRS

Native coordinate reference system; not necessarily EPSG:4326.

transform Affine

Affine mapping from source-grid pixel corners to native coordinates.

width, height

Full source grid dimensions in cells, not read-window dimensions.

direction_sha256, accumulation_sha256

Published content identities of the two source rasters.

pourpoint.metadata.SpatialManifest dataclass

Final HFX publication declarations, including unchanged source metadata.

Attributes:

Name Type Description
families Mapping[str, DomainFamily]

Domain names mapped to their feature tables and addressing artifacts.

relationships Mapping[str, Mapping[str, object]]

Supplied immediate relationship declarations by domain. Columns retain their source meanings, target domains and artifact bindings; an absent declaration does not establish a natural outlet.

artifacts Mapping[str, Fingerprint]

Relative artifact paths mapped to immutable size and digest declarations.

declarations Mapping[str, object]

Complete source manifest, including provenance, raster declarations and otherwise unrecognized metadata. No source attributes are standardized.

catchment_connectivity Mapping[int, CatchmentConnectivity]

Per-level catchment connectivity and completeness declarations keyed by nonnegative catchment level. Absent levels remain unassessed.

pourpoint.metadata.CatchmentConnectivity dataclass

Published catchment connectivity and completeness declarations for one level.

Attributes:

Name Type Description
level int

Nonnegative catchment level to which this declaration applies.

status Literal['supplied', 'not_supplied']

Whether same-level catchment connectivity is "supplied" or "not_supplied".

completeness Literal['complete', 'partial'] | None

Declared source-network completeness when supplied: "complete", "partial", or None when completeness metadata was omitted.

upstream_cuts_column str | None

Top-level catchment integer column name reporting per-unit immediate upstream cut counts (where 0 means verified complete, > 0 means known missing upstream connections, and null means unverified), or None when absent.

derivation str | None

Optional source derivation note, or None when omitted.