Skip to content

Core operations

pourpoint.select_upstream_subbasins(*, fabric: HydroFabric, target: BaseGeometry | Targets, level: int = 1, allow_incomplete: bool = False, n_jobs: int = 1) -> SelectionResult | BatchResult[SelectionResult]

select_upstream_subbasins(
    *,
    fabric: HydroFabric,
    target: BaseGeometry,
    level: int = 1,
    allow_incomplete: bool = False,
    n_jobs: int = 1,
) -> SelectionResult
select_upstream_subbasins(
    *,
    fabric: HydroFabric,
    target: Targets,
    level: int = 1,
    allow_incomplete: bool = False,
    n_jobs: int = 1,
) -> BatchResult[SelectionResult]

Select whole sub-basins approximating land draining to a target.

Parameters:

Name Type Description Default
fabric HydroFabric

Open HFX fabric supplying catchments and upstream connectivity.

required
target BaseGeometry | Targets

EPSG:4326 geometry, or a dictionary of named geometries or list for a batch. A multipart geometry is one target. Regions include boundary intersections. A point on a shared boundary belongs to the smallest supplied catchment ID; river associations do not determine ownership.

required
level int

Nonnegative catchment level, selected explicitly without fallback.

1
allow_incomplete bool

Accept selections whose upstream closure has known missing upstream connections, unverified (null) cut counts, or missing completeness assessment metadata. Returned UpstreamCoverage diagnostics retain all affected IDs and counts without promoting them to complete. Unavailable connectivity and corrupt source schemas or cut values still raise even when allow_incomplete=True.

False
n_jobs int

Batch worker limit: 1 is sequential, -1 uses available CPU capacity, and positive values bound worker-owned readers. Single calls are serial.

1

Returns:

Type Description
SelectionResult or BatchResult

Selected whole units and source-network UpstreamCoverage diagnostics. An empty geometry succeeds without opt-in with empty sub-basins and coverage.status == "not_assessed". Batch slots preserve input order; dictionary keys are names, while list entries get new UUID names on each call. Duplicate geometries remain independent targets.

Raises:

Type Description
OperationError

selection.invalid_target for invalid geometry or non-finite / out-of-range coordinates, selection.no_coverage for a nonempty target without coverage, selection.connectivity_unavailable for unsupplied connectivity, selection.incomplete_coverage when visited units have positive cuts, selection.unverified_coverage when visited units have null cuts, selection.incomplete_and_unverified_coverage when both occur, or selection.coverage_not_assessed when completeness metadata or a usable cut column is missing (unless allow_incomplete=True). Batches retain these failures as issues with None result slots.

ValueError

Invalid level or worker count, a flow relationship crossing levels, missing or non-integer declared cut columns, negative cut counts, or cuts/nulls contradicting a complete declaration.

TypeError

Invalid target type, nonboolean allow_incomplete, or invalid batch names.

Notes

This is whole-unit selection, not exact-point raster delineation. Returned vectors and coverage diagnostics survive fabric closure. Integrity, configuration and unexpected failures propagate even in batches; they are not empty selections.

pourpoint.delineate(*, fabric: HydroFabric, target: BaseGeometry | Targets, level: int = 1, snap_onto: SnapGeometry | None = None, radius: float = 100.0, refine: bool = False, merge: bool = True, window_size: int = 3, allow_incomplete: bool = False, n_jobs: int = 1) -> DelineationResult | BatchResult[DelineationResult]

delineate(
    *,
    fabric: HydroFabric,
    target: BaseGeometry,
    level: int = 1,
    snap_onto: SnapGeometry | None = None,
    radius: float = 100.0,
    refine: bool = False,
    merge: bool = True,
    window_size: int = 3,
    allow_incomplete: bool = False,
    n_jobs: int = 1,
) -> DelineationResult
delineate(
    *,
    fabric: HydroFabric,
    target: Targets,
    level: int = 1,
    snap_onto: SnapGeometry | None = None,
    radius: float = 100.0,
    refine: bool = False,
    merge: bool = True,
    window_size: int = 3,
    allow_incomplete: bool = False,
    n_jobs: int = 1,
) -> BatchResult[DelineationResult]

Compose snapping, upstream selection, optional refinement and merging.

Parameters:

Name Type Description Default
fabric HydroFabric

Open fabric used for all source access.

required
target BaseGeometry | Targets

EPSG:4326 geometry, named dictionary or list of geometries. Batch naming and whole-unit selection follow select_upstream_subbasins.

required
level int

Explicit catchment level; no fallback or automatic finest-level choice.

1
snap_onto SnapGeometry | None

Optional supplied stream geometry accepted by snap. Snapping occurs before selection and requires a point; it is never inferred.

None
radius float

Maximum snap distance in WGS84 ground metres, finite and nonnegative. Validated even when snapping is disabled.

100.0
refine bool

Request raster refinement of the adjusted point under the equivalence assumption described by pourpoint.refinement.refine. Failure does not fall back to a coarse result.

False
merge bool

Populate the merged geometry as well as retaining individual sub-basins.

True
window_size int

Positive odd native-cell outlet search width. Validated even without refinement. This is a practical choice, not a universal scientific optimum.

3
allow_incomplete bool

Accept selections with incomplete, unverified or unassessed upstream source-network coverage, following select_upstream_subbasins. Coverage is assessed before raster refinement or merging.

False
n_jobs int

Batch worker limit: 1 is sequential, -1 uses available CPU capacity, and positive values bound worker-owned readers.

1

Returns:

Type Description
DelineationResult or BatchResult

Whole units or refined contributions, optional merged geometry, original and adjusted targets, source declarations, source-network coverage assessment, and any selected outlet and raster subsets. Batch identity and order are retained.

Raises:

Type Description
OperationError

Single-target failures use the codes of snap, select_upstream_subbasins and pourpoint.refinement.refine. Batches record them as issues and None slots, not coarse successes.

ValueError

Invalid level, worker count, radius or window size, invalid supplied stream geometry, or corrupt connectivity/cut metadata. Shared configuration and integrity failures propagate rather than becoming batch issues.

TypeError

Invalid target types or nonboolean refinement/merge/completeness controls.

Notes

No separate delineation algorithm is used. Vector outputs and coverage diagnostics are materialized and remain usable after fabric closure. Vector snapping and raster outlet adjustment are distinct: the latter is retained in outlet_cell. Source-network coverage on DelineationResult still describes the selected vector closure, not raster completeness.

pourpoint.refine(*, fabric: HydroFabric, target: BaseGeometry | None = None, subbasins: SelectionResult | DelineationResult | Sequence[Subbasin] | BatchResult[SelectionResult] | BatchResult[DelineationResult] | None = None, footprint: BaseGeometry | None = None, window_size: int = 3, n_jobs: int = 1) -> GranularRefinement | FootprintRefinement | BatchResult[GranularRefinement]

refine(
    *,
    fabric: HydroFabric,
    subbasins: BatchResult[SelectionResult]
    | BatchResult[DelineationResult],
    target: None = None,
    footprint: None = None,
    window_size: int = 3,
    n_jobs: int = 1,
) -> BatchResult[GranularRefinement]
refine(
    *,
    fabric: HydroFabric,
    subbasins: SelectionResult | DelineationResult,
    target: BaseGeometry | None = None,
    footprint: None = None,
    window_size: int = 3,
    n_jobs: int = 1,
) -> GranularRefinement
refine(
    *,
    fabric: HydroFabric,
    target: Point,
    subbasins: Sequence[Subbasin],
    footprint: None = None,
    window_size: int = 3,
    n_jobs: int = 1,
) -> GranularRefinement
refine(
    *,
    fabric: HydroFabric,
    target: Point,
    footprint: BaseGeometry,
    subbasins: None = None,
    window_size: int = 3,
    n_jobs: int = 1,
) -> FootprintRefinement

Trace incoming native D8 flow inside a complete vector mask.

Parameters:

Name Type Description Default
fabric HydroFabric

Open fabric supplying the native direction/accumulation pair.

required
target BaseGeometry | None

Nonempty point in EPSG:4326 covered by the mask. Optional when subbasins is a SelectionResult or unrefined DelineationResult, defaulting to the result's post-snap .target. Omit for a batch, which carries per-target geometries.

None
subbasins SelectionResult | DelineationResult | Sequence[Subbasin] | BatchResult[SelectionResult] | BatchResult[DelineationResult] | None

A SelectionResult, an unrefined DelineationResult, whole source units forming one mask, or a batch of selection or unrefined delineation results. Mutually exclusive with footprint. Passing a SelectionResult, unrefined DelineationResult, or batch preserves its source-network UpstreamCoverage diagnostics on the refined output; manually supplied sub-basins receive status="not_assessed". Batch identity, order and prior issues are preserved; failed slots are not retried. Already-refined DelineationResult inputs are rejected.

None
footprint BaseGeometry | None

Nonempty Polygon or MultiPolygon in EPSG:4326, used as one mask (coverage.status == "not_assessed"). Supply exactly one mask form. Batch footprints come from subbasins.

None
window_size int

Positive odd search width in native cells around the cell containing the target. Size 1 permits no move beyond that cell. Selects the highest valid accumulation inside the mask, breaking ties by source row then column. Both bands must be valid for outlet selection.

3
n_jobs int

Batch worker limit: 1 is sequential, -1 uses available CPU capacity, and positive values bound worker-owned readers.

1

Returns:

Type Description
GranularRefinement or FootprintRefinement or BatchResult

Contributions for sub-basin input or one footprint for geometry input, the selected native outlet cell, materialized raster subsets, and retained or "not_assessed" source-network coverage diagnostics. Empty source pieces are omitted. Both forms trace the same combined mask; merging granular contributions yields the footprint result.

Raises:

Type Description
OperationError

refinement.point_required for a nonpoint, empty, or non-finite point geometry, refinement.empty_mask for an empty or nonpolygon mask, refinement.outside_mask when the point is not covered, refinement.missing_rasters for an absent raster pair, refinement.no_coverage for inadequate raster coverage or out-of-bounds geographic mask extents, or refinement.no_outlet when the local search has no valid masked cell. Batches retain these failures as issues with None slots.

ValueError

Invalid window/worker count, mutually incompatible mask arguments, or an already-refined DelineationResult. Integrity and unexpected errors also propagate, including in batches.

TypeError

A raw sub-basin/footprint call omits target, or a batch slot is not a SelectionResult or DelineationResult.

Notes

Assumes the whole vector mask equals the raster watershed at the terminal unit outlet, and that the requested point drains to that outlet. Execution does not verify this scientific equivalence. The default local search is a practical choice, not a universal optimum; larger windows can switch branches.

Mask cells use GDAL center-based rasterization. Reverse D8 tracing spans the entire mask and needs only valid direction, not valid accumulation; zero and signed negative directions are terminal. Paths cannot leave the mask. Native direction pointers are never warped. Selected cell polygons are transformed to EPSG:4326 and clipped to the vector mask, then partitioned at source boundaries for granular output. No hole filling is applied. Materialized vectors survive fabric closure; perform source-dependent operations and export within the fabric context.

pourpoint.merge(*, subbasins: MergeInput | Sequence[MergeInput]) -> Polygon | MultiPolygon | list[Polygon | MultiPolygon]

merge(*, subbasins: MergeInput) -> Polygon | MultiPolygon
merge(
    *, subbasins: Sequence[MergeInput]
) -> list[Polygon | MultiPolygon]

Merge sub-basin geometries without creating a new source feature.

Parameters:

Name Type Description Default
subbasins MergeInput | Sequence[MergeInput]

A SelectionResult, DelineationResult, GranularRefinement, FootprintRefinement, whole units or contributions forming one footprint, or a sequence of those groups representing independent footprints. Geometries use EPSG:4326. When a result already carries its merged .geometry, it is returned directly without recomputation.

required

Returns:

Type Description
Polygon or MultiPolygon or list

Polygonal union for one group or result; an ordered list of unions for a sequence of groups. An empty outer sequence returns an empty Polygon, not a list. Empty inner groups produce empty Polygons. No source attributes are aggregated, and no source access or geometry repair is performed.

Notes

Large inputs exceeding 5,000 parts are unioned in bounded groups using retained HFX physical addresses when available, inside a process-wide serialized workspace with up to two group unions active at a time. Single valid parts and small groups up to 5,000 parts execute without workspace serialization. This bounds simultaneous large decoding and union work, not retained caller inputs, outputs or total process memory. Independent processes have independent bounds.

pourpoint.snap(*, target: BaseGeometry, onto: SnapGeometry, radius: float) -> Point

Find the nearest point on supplied streams within a search radius.

Parameters:

Name Type Description Default
target BaseGeometry

Nonempty finite Point in EPSG:4326 (longitude, latitude).

required
onto SnapGeometry

LineString, MultiLineString, River, RiverNetwork or sequence of rivers. Stream vertices must be finite and in EPSG:4326.

required
radius float

Maximum WGS84 ground distance in metres, finite and nonnegative.

required

Returns:

Type Description
Point

Snapped location in EPSG:4326. Equal-distance matches retain input order.

Raises:

Type Description
OperationError

snap.point_required for an invalid WGS84 point; snap.no_match when no supplied stream is in range.

ValueError

Invalid radius or stream geometry. Split segments spanning 180 degrees or more of longitude before calling.

Notes

Intended for local stream segments, not arbitrary globe-spanning lines. Segments interpolate straight in longitude/latitude, not along great-circle arcs; distances are measured on the WGS84 ellipsoid. This optional operation neither infers a network nor selects a raster outlet cell.

pourpoint.select_rivers(*, fabric: HydroFabric, target: RiverTarget, level: int = 1, include_downstream: bool = False) -> RiverNetwork

Select river portions inside one combined footprint.

Parameters:

Name Type Description Default
fabric HydroFabric

Open fabric supplying rivers and their relationships.

required
target RiverTarget

EPSG:4326 polygonal geometry, sub-basin/contribution, collection of parts forming one footprint, or a SelectionResult, DelineationResult, GranularRefinement, or FootprintRefinement. Reuses already materialized .geometry when present. Internal part boundaries do not limit flow; this collection is not a batch of independent targets.

required
level int

Nonnegative river level, independent of catchment levels. No fallback or inferred correspondence between catchment and river tiers is used.

1
include_downstream bool

Extend along every supplied outgoing continuation, including splits and reconvergence. Features are deduplicated by source ID. Partial boundary features require unambiguous orientation to retain downstream linework.

False

Returns:

Type Description
RiverNetwork

Selected portions with original identities, attributes, directed relationships and supplied nodes. Source quantities are not recomputed. Empty footprints or no intersecting rivers give an empty network when the river family and its relationship data are supplied. Materialized results survive closure.

Raises:

Type Description
OperationError

rivers.unavailable when the river family is absent; rivers.invalid_target when the target footprint is invalid or has non-finite or out-of-range coordinates; rivers.connectivity_unavailable when extension needs a missing downstream_ids column in supplied relationship data; rivers.ambiguous_direction when a partial feature cannot be oriented from supplied orientation or endpoint nodes.

KeyError

River relationship data are not declared, even for an empty footprint or no matching rivers. Missing referenced source IDs also raise.

ValueError

Invalid level, nonpolygonal nonempty footprint, or downstream flow crossing river levels. Integrity errors propagate rather than producing a partial network.

TypeError

Nonboolean include_downstream.

Notes

Clipping creates endpoints, not natural outlets. Retained relationship references outside the selection must not be interpreted as missing flow or source-described termination. No mainstem is inferred from node incidence.

pourpoint.QGISBundle

Build a portable QGIS folder incrementally without hydrological computation.

Notes

Add methods retain data and return this builder for chaining. write creates a new folder with a relative-reference project, GeoPackage and native-grid GeoTIFFs; it never replaces an existing path. No merging, delineation or river tracing is performed implicitly. Perform source-dependent export inside the fabric context; current raster subsets already contain materialized arrays.

Scalar source fields become ordinary vector columns. Reserved-name collisions gain source_ prefixes; source_metadata.attribute_columns records names. Rich values, original WKB and Arrow schemas/metadata are losslessly retained as collective IPC streams in source_arrow (kind="features" for vector layers and kind="nodes" for supplied river nodes). Each stream_id identifies one table aligned with layer row order when one schema backs the layer, or recorded per-fid in source_metadata (feature_streams / node_streams) when mixed backing schemas occur. Concatenate its payload values in ascending part order before opening the IPC stream. Small streams occupy one row. Parts are byte segments, not independent IPC streams. Individual geometry and ordinary attribute values must still fit SQLite's value/row limits; segmentation removes the aggregate source-IPC limit only. Result locations are WGS84 WKB in result_metadata, alongside provenance and JSON-encoded UpstreamCoverage diagnostics; these are not extra map layers.

add_vector(name: str, data: BaseGeometry | VectorFeature | Sequence[VectorFeature] | RiverNetwork, *, crs: str | CRS | None = None) -> Self

Add one vector layer, retaining supplied source records.

Parameters:

Name Type Description Default
name str

Display layer name. Storage table names are generated separately.

required
data BaseGeometry | VectorFeature | Sequence[VectorFeature] | RiverNetwork

Raw geometry, feature, collection of features, or river network. Networks also retain relationships, source nodes and declarations in companion tables; individual feature identities are preserved.

required
crs str | CRS | None

Required for raw geometry. Feature inputs default to EPSG:4326. This assigns the CRS; it does not transform coordinates. Native outlet-cell geometry must use its grid CRS explicitly.

None

Raises:

Type Description
ValueError

Raw geometry has no explicit CRS.

add_raster(name: str, data: RasterSubset) -> Self

Add a retained raster subset without reading or warping source data.

Parameters:

Name Type Description Default
name str

Display layer name; a safe storage filename is generated on write.

required
data RasterSubset

Native-grid band and whole-vector mask. Write preserves valid source values inside the mask and uses source nodata elsewhere, including unrelated corners of the rectangular window.

required

add_result(result: ExportResult | ExportBatch | BatchResult[ExportResult]) -> Self

Add available selection, delineation or refinement outputs without computing more.

Parameters:

Name Type Description Default
result ExportResult | ExportBatch | BatchResult[ExportResult]

A single result (SelectionResult, DelineationResult, GranularRefinement or FootprintRefinement) or its batch container. Each batch target gets its named group and retained identity; failures go into target_issues without fabricated features. Available outputs include sub-basins, merged footprint (including retained watershed geometry for GranularRefinement), outlined native-CRS outlet cell and one raster pair per refined target. Overlapping targets may duplicate pixels. Granular refinement is exported with both subbasins and its retained watershed boundary with no implicit merging during export.

required
Notes

Original and vector-adjusted targets, provenance and source-network coverage diagnostics are retained in result_metadata when available, not added as extra map layers.

write(path: str | Path) -> Path

Write the accumulated layers to a new portable folder.

Parameters:

Name Type Description Default
path str | Path

New output directory. Missing parents are created.

required

Returns:

Type Description
Path

Output folder containing watershed.qgz, vectors.gpkg and any raster_*.tif files. Project references are relative so the entire folder can be moved together.

Raises:

Type Description
FileExistsError

The destination already exists; it is never overwritten.

ValueError

A raster subset lacks retained source values or source nodata.

Notes

Serializes retained arrays and vector records, with no hidden hydrological operations. Cost scales with exported features and pixels, including duplicated pixels across targets. Writes are not transactional across the folder: a failure may leave partial files for the caller to remove.