pourpoint 0.5.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pourpoint/__init__.py ADDED
@@ -0,0 +1,54 @@
1
+ """Eager hydrological operations and HFX source access."""
2
+
3
+ from pourpoint.fabric import HydroFabric
4
+ from pourpoint.features import River, RiverNetwork, SourceNode, Subbasin
5
+ from pourpoint.operations import delineate, select_upstream_subbasins
6
+ from pourpoint.qgis import QGISBundle
7
+ from pourpoint.refinement import (
8
+ FootprintRefinement,
9
+ GranularRefinement,
10
+ OutletCell,
11
+ RasterSubset,
12
+ RefinementRasters,
13
+ SubbasinContribution,
14
+ merge,
15
+ refine,
16
+ )
17
+ from pourpoint.results import (
18
+ BatchIssue,
19
+ BatchResult,
20
+ DelineationResult,
21
+ OperationError,
22
+ SelectionResult,
23
+ Target,
24
+ UpstreamCoverage,
25
+ )
26
+ from pourpoint.rivers import select_rivers, snap
27
+
28
+ __all__ = [
29
+ "QGISBundle",
30
+ "select_upstream_subbasins",
31
+ "delineate",
32
+ "refine",
33
+ "merge",
34
+ "snap",
35
+ "select_rivers",
36
+ "SubbasinContribution",
37
+ "OutletCell",
38
+ "RasterSubset",
39
+ "RefinementRasters",
40
+ "GranularRefinement",
41
+ "FootprintRefinement",
42
+ "BatchIssue",
43
+ "BatchResult",
44
+ "SelectionResult",
45
+ "UpstreamCoverage",
46
+ "DelineationResult",
47
+ "OperationError",
48
+ "Target",
49
+ "HydroFabric",
50
+ "Subbasin",
51
+ "River",
52
+ "SourceNode",
53
+ "RiverNetwork",
54
+ ]
pourpoint/_batch.py ADDED
@@ -0,0 +1,67 @@
1
+ """Ordered target identities and bounded worker-owned execution."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from collections.abc import Callable
7
+ from concurrent.futures import ThreadPoolExecutor
8
+ from uuid import uuid4
9
+
10
+ from shapely.geometry.base import BaseGeometry
11
+
12
+ from pourpoint.fabric import HydroFabric
13
+ from pourpoint.results import BatchIssue, BatchResult, OperationError, Target
14
+ from pourpoint.storage import TransferStats
15
+
16
+ type Targets = dict[str, BaseGeometry] | list[BaseGeometry]
17
+
18
+
19
+ def workers(n_jobs: int) -> int:
20
+ if type(n_jobs) is not int or n_jobs == 0 or n_jobs < -1:
21
+ raise ValueError("n_jobs must be -1 or a positive integer")
22
+ return (os.cpu_count() or 1) if n_jobs == -1 else n_jobs
23
+
24
+
25
+ def identify(targets: Targets) -> list[Target]:
26
+ items = targets.items() if isinstance(targets, dict) else ((str(uuid4()), geometry) for geometry in targets)
27
+ result = []
28
+ for index, (name, geometry) in enumerate(items):
29
+ if not isinstance(name, str) or not isinstance(geometry, BaseGeometry):
30
+ raise TypeError("batch targets require string names and Shapely geometries")
31
+ result.append(Target(index, name, geometry))
32
+ return result
33
+
34
+
35
+ def execute[T](
36
+ fabric: HydroFabric, targets: list[Target], operation: Callable[[HydroFabric, Target], T], n_jobs: int
37
+ ) -> BatchResult[T]:
38
+ count = min(workers(n_jobs), len(targets))
39
+ fabric._ensure_open()
40
+
41
+ def evaluate(reader: HydroFabric, target: Target) -> tuple[T | None, BatchIssue | None]:
42
+ try:
43
+ return operation(reader, target), None
44
+ except OperationError as error:
45
+ return None, BatchIssue(target.index, target.name, error.code, error.reason)
46
+
47
+ if count <= 1:
48
+ slots = [evaluate(fabric, target) for target in targets]
49
+ else:
50
+
51
+ def chunk(indices: list[int]) -> tuple[list[tuple[int, T | None, BatchIssue | None]], TransferStats]:
52
+ with fabric._fork() as reader:
53
+ values = [(index, *evaluate(reader, targets[index])) for index in indices]
54
+ return values, reader.stats
55
+
56
+ slots: list[tuple[T | None, BatchIssue | None]] = [(None, None)] * len(targets)
57
+ with ThreadPoolExecutor(max_workers=count) as pool:
58
+ # One context per worker chunk, reused for its targets, never shared.
59
+ futures = [pool.submit(chunk, list(range(worker, len(targets), count))) for worker in range(count)]
60
+ for future in futures:
61
+ values, stats = future.result()
62
+ fabric.stats.requests += stats.requests
63
+ fabric.stats.transferred_bytes += stats.transferred_bytes
64
+ fabric.stats.cache_hit_bytes += stats.cache_hit_bytes
65
+ for index, value, issue in values:
66
+ slots[index] = value, issue
67
+ return BatchResult([value for value, _ in slots], targets, [issue for _, issue in slots if issue is not None])
@@ -0,0 +1,130 @@
1
+ """Chunk-preserving Arrow selection and release of unused dictionary values."""
2
+
3
+ import numpy as np
4
+ import pyarrow as pa
5
+ import pyarrow.compute as pc
6
+
7
+
8
+ def _compact_dictionary_values(array: pa.Array) -> pa.Array:
9
+ if isinstance(array, pa.DictionaryArray):
10
+ # Sorted original indices preserve the meaning of ordered dictionaries.
11
+ used = pc.call_function("unique", [pc.call_function("drop_null", [array.indices])])
12
+ used = pc.take(used, pc.call_function("array_sort_indices", [used]))
13
+ indices = pc.cast(
14
+ pc.call_function("index_in", [array.indices], options=pc.SetLookupOptions(used)), array.type.index_type
15
+ )
16
+ values = _compact_dictionary_values(pc.take(array.dictionary, used))
17
+ return pa.DictionaryArray.from_arrays(indices, values, ordered=array.type.ordered)
18
+ if isinstance(array, pa.ExtensionArray):
19
+ return pa.ExtensionArray.from_storage(array.type, _compact_dictionary_values(array.storage))
20
+ children: list[pa.Array]
21
+ if pa.types.is_struct(array.type) or pa.types.is_union(array.type):
22
+ children = [array.field(i) for i in range(array.type.num_fields)]
23
+ elif (
24
+ pa.types.is_list(array.type)
25
+ or pa.types.is_large_list(array.type)
26
+ or pa.types.is_fixed_size_list(array.type)
27
+ or pa.types.is_map(array.type)
28
+ or pa.types.is_list_view(array.type)
29
+ or pa.types.is_large_list_view(array.type)
30
+ ):
31
+ children = [array.values]
32
+ elif pa.types.is_run_end_encoded(array.type):
33
+ children = [array.run_ends, array.values]
34
+ else:
35
+ return array
36
+ return pa.Array.from_buffers(
37
+ array.type,
38
+ len(array),
39
+ array.buffers()[: array.type.num_buffers],
40
+ null_count=array.null_count,
41
+ offset=array.offset,
42
+ children=[_compact_dictionary_values(child) for child in children],
43
+ )
44
+
45
+
46
+ def compact_dictionaries(table: pa.Table) -> pa.Table:
47
+ """Keep exact schema and selected values without unreferenced dictionary data.
48
+
49
+ Call after Arrow take/filter has gathered ordinary value buffers. Arrow's
50
+ gather kernels retain dictionaries even when only one entry is selected.
51
+ """
52
+ if not table.num_columns:
53
+ return table
54
+ return pa.Table.from_arrays(
55
+ [
56
+ pa.chunked_array([_compact_dictionary_values(chunk) for chunk in column.chunks], type=column.type)
57
+ for column in table.columns
58
+ ],
59
+ schema=table.schema,
60
+ )
61
+
62
+
63
+ # Keep even bit-packed list children below signed 32-bit element offsets.
64
+ _GATHER_BYTE_LIMIT = 128 * 1024 * 1024
65
+
66
+
67
+ def _bounded_gather_type(dtype: pa.DataType) -> bool:
68
+ if pa.types.is_struct(dtype):
69
+ return dtype.num_fields > 0 and all(_bounded_gather_type(field.type) for field in dtype)
70
+ if pa.types.is_list(dtype) or pa.types.is_large_list(dtype):
71
+ return _bounded_gather_type(dtype.value_type)
72
+ return (
73
+ pa.types.is_integer(dtype)
74
+ or pa.types.is_floating(dtype)
75
+ or pa.types.is_boolean(dtype)
76
+ or pa.types.is_binary(dtype)
77
+ or pa.types.is_string(dtype)
78
+ or pa.types.is_large_binary(dtype)
79
+ or pa.types.is_large_string(dtype)
80
+ )
81
+
82
+
83
+ def take_rows(table: pa.Table, indices: list[int]) -> pa.Table:
84
+ """Gather requested rows while bounding variable-width output arrays.
85
+
86
+ Bounded interleaved gathers avoid excessive small chunks. Other requests use
87
+ distinct-row runs within aligned source batches, preserving representable
88
+ source payloads. Values, duplicates and schema survive either path.
89
+ """
90
+ if not indices:
91
+ return table.slice(0, 0)
92
+ if not table.num_columns:
93
+ return pa.table({"_row": pa.nulls(len(indices))}).replace_schema_metadata(table.schema.metadata).select([])
94
+ # ID lookups contain only fixed-width numeric addresses, with no offset ceiling.
95
+ if all(
96
+ pa.types.is_integer(field.type) or pa.types.is_floating(field.type) or pa.types.is_boolean(field.type)
97
+ for field in table.schema
98
+ ):
99
+ return table.take(pa.array(indices, type=pa.int64()))
100
+ batches = table.to_batches()
101
+ ends = np.cumsum([batch.num_rows for batch in batches])
102
+ groups = np.searchsorted(ends, indices, side="right")
103
+ # Ordinary monotone requests already produce few chunks. For interleaving,
104
+ # logical bytes count shared source chunks repeatedly, unlike retained bytes.
105
+ # Maximum row multiplicity bounds duplicate expansion; ordinary list/struct
106
+ # children cannot overlap within a source chunk. Other nesting stays below.
107
+ if (
108
+ len(batches) > 1
109
+ and np.count_nonzero(groups[1:] != groups[:-1]) >= len(batches)
110
+ and all(_bounded_gather_type(field.type) for field in table.schema)
111
+ and table.nbytes <= _GATHER_BYTE_LIMIT
112
+ and table.get_total_buffer_size() <= _GATHER_BYTE_LIMIT
113
+ and table.nbytes * int(np.bincount(indices, minlength=table.num_rows).max()) <= _GATHER_BYTE_LIMIT
114
+ ):
115
+ return table.take(pa.array(indices, type=pa.int64()))
116
+ pieces: list[pa.RecordBatch] = []
117
+ start = 0
118
+ while start < len(indices):
119
+ group = int(groups[start])
120
+ stop = start + 1
121
+ seen = {indices[start]}
122
+ while stop < len(indices) and groups[stop] == group and indices[stop] not in seen:
123
+ seen.add(indices[stop])
124
+ stop += 1
125
+ offset = 0 if group == 0 else int(ends[group - 1])
126
+ # Take gathers nested buffers as well as outer values; slices alone retain
127
+ # unrelated list children and their dictionaries during IPC serialization.
128
+ pieces.append(batches[group].take(pa.array([index - offset for index in indices[start:stop]], type=pa.int64())))
129
+ start = stop
130
+ return pa.Table.from_batches(pieces, schema=table.schema)
pourpoint/_union.py ADDED
@@ -0,0 +1,53 @@
1
+ """Bounded union of materialized catchments and contributions."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections import deque
6
+ from collections.abc import Sequence
7
+ from concurrent.futures import ThreadPoolExecutor
8
+ from threading import Lock
9
+ from typing import TYPE_CHECKING
10
+
11
+ import shapely
12
+ from shapely.geometry.base import BaseGeometry
13
+
14
+ from pourpoint.features import Subbasin
15
+
16
+ if TYPE_CHECKING:
17
+ from pourpoint.refinement import BasinPart
18
+
19
+
20
+ _GROUP_SIZE = 5000
21
+ _WORKERS = 2
22
+ # Admit an entire workspace, not individual tasks: waiting delineations must not
23
+ # accumulate partial unions while another call combines its final geometry.
24
+ _WORKSPACE = Lock()
25
+
26
+
27
+ def _union_group(parts: Sequence[BasinPart]) -> BaseGeometry:
28
+ return shapely.union_all([part.geometry for part in parts])
29
+
30
+
31
+ def union_subbasins(parts: Sequence[BasinPart]) -> BaseGeometry:
32
+ with _WORKSPACE:
33
+ if len(parts) <= _GROUP_SIZE:
34
+ return _union_group(parts)
35
+ addresses = [(part if isinstance(part, Subbasin) else part.source)._source_address for part in parts]
36
+ # No source lookup or invented spatial order for manually supplied parts.
37
+ ordered = (
38
+ [parts[index] for index in sorted(range(len(parts)), key=lambda index: addresses[index])]
39
+ if all(address is not None for address in addresses)
40
+ else parts
41
+ )
42
+ groups = (ordered[start : start + _GROUP_SIZE] for start in range(0, len(ordered), _GROUP_SIZE))
43
+ partials: list[BaseGeometry] = []
44
+ with ThreadPoolExecutor(max_workers=_WORKERS) as pool:
45
+ pending = deque()
46
+ for _ in range(_WORKERS):
47
+ if (group := next(groups, None)) is not None:
48
+ pending.append(pool.submit(_union_group, group))
49
+ while pending:
50
+ partials.append(pending.popleft().result())
51
+ if (group := next(groups, None)) is not None:
52
+ pending.append(pool.submit(_union_group, group))
53
+ return shapely.union_all(partials)
pourpoint/cache.py ADDED
@@ -0,0 +1,58 @@
1
+ """Persistent original byte ranges, scoped to one source and immutable identity."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import sqlite3
7
+ from pathlib import Path
8
+ from threading import RLock
9
+
10
+
11
+ class RangeCache:
12
+ def __init__(self, directory: Path, source: str) -> None:
13
+ directory = directory / source
14
+ directory.mkdir(parents=True, exist_ok=True)
15
+ self._lock = RLock()
16
+ self._db = sqlite3.connect(directory / "ranges.sqlite3", check_same_thread=False)
17
+ self._db.executescript("""
18
+ CREATE TABLE IF NOT EXISTS metadata (key TEXT PRIMARY KEY, value BLOB NOT NULL);
19
+ CREATE TABLE IF NOT EXISTS ranges (
20
+ key TEXT NOT NULL, start INTEGER NOT NULL, end INTEGER NOT NULL,
21
+ data BLOB NOT NULL, digest TEXT NOT NULL, PRIMARY KEY (key, start, end));
22
+ """)
23
+
24
+ def metadata(self, key: str) -> bytes | None:
25
+ with self._lock:
26
+ row = self._db.execute("SELECT value FROM metadata WHERE key = ?", (key,)).fetchone()
27
+ return bytes(row[0]) if row else None
28
+
29
+ def pin(self, key: str, value: bytes) -> bytes:
30
+ with self._lock, self._db:
31
+ self._db.execute("INSERT OR IGNORE INTO metadata VALUES (?, ?)", (key, value))
32
+ result = self.metadata(key)
33
+ assert result is not None
34
+ return result
35
+
36
+ def pieces(self, key: str, start: int, end: int) -> list[tuple[int, bytes]]:
37
+ with self._lock:
38
+ rows = self._db.execute(
39
+ "SELECT start, data, digest FROM ranges WHERE key = ? AND start < ? AND end > ? ORDER BY start",
40
+ (key, end, start),
41
+ ).fetchall()
42
+ result: list[tuple[int, bytes]] = []
43
+ for offset, data, digest in rows:
44
+ if hashlib.sha256(data).hexdigest() != digest:
45
+ raise ValueError("cached range SHA-256 mismatch")
46
+ result.append((offset, bytes(data)))
47
+ return result
48
+
49
+ def put(self, key: str, start: int, data: bytes) -> None:
50
+ with self._lock, self._db:
51
+ self._db.execute(
52
+ "INSERT OR IGNORE INTO ranges VALUES (?, ?, ?, ?, ?)",
53
+ (key, start, start + len(data), data, hashlib.sha256(data).hexdigest()),
54
+ )
55
+
56
+ def close(self) -> None:
57
+ with self._lock:
58
+ self._db.close()
pourpoint/fabric.py ADDED
@@ -0,0 +1,329 @@
1
+ """Context-managed selective access to one final HFX publication snapshot."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Mapping, Sequence
6
+ from pathlib import Path
7
+ from types import TracebackType
8
+ from typing import Self
9
+
10
+ import pyarrow as pa
11
+
12
+ from pourpoint.features import River, RiverNetwork, SourceNode, Subbasin
13
+ from pourpoint.metadata import BoundingBox, SpatialManifest
14
+ from pourpoint.rasters import RasterReader
15
+ from pourpoint.storage import Source, TransferStats
16
+ from pourpoint.vectors import VectorReader
17
+
18
+
19
+ class HydroFabric:
20
+ """Open one HFX publication for eager queries and reusable source access.
21
+
22
+ Parameters
23
+ ----------
24
+ source
25
+ Dataset root directory or HTTP(S)/S3 URL containing ``manifest.json``.
26
+ cache
27
+ Retain acquired original bytes and metadata on disk across lifetimes.
28
+ Disabling this does not disable bounded in-memory reuse.
29
+ cache_dir
30
+ Persistent cache location. When omitted, use ``~/Library/Caches/pourpoint``
31
+ on macOS, ``%LOCALAPPDATA%/pourpoint`` on Windows (falling back to
32
+ ``~/AppData/Local/pourpoint``), or ``$XDG_CACHE_HOME/pourpoint`` on other
33
+ platforms (falling back to ``~/.cache/pourpoint``).
34
+ offline
35
+ Require the cached manifest snapshot and cached content without network
36
+ access. Requires caching; missing content raises rather than returning
37
+ incomplete results.
38
+ storage_options
39
+ Options passed to the remote object store, including S3 credentials or
40
+ endpoint configuration. Local paths do not accept storage options.
41
+
42
+ Attributes
43
+ ----------
44
+ manifest
45
+ Parsed publication metadata, artifact identities and relationship
46
+ declarations for this lifetime.
47
+
48
+ Notes
49
+ -----
50
+ Opening reads only the manifest; vector and raster readers open as needed.
51
+ Use a context manager and perform source-dependent work before it closes.
52
+ Materialized vector results and raster arrays survive closure, but readers
53
+ and raster requests cannot be used to acquire more data afterward.
54
+ Instances belong to one thread; calls must not overlap.
55
+
56
+ The disk cache grows across queries against the same snapshot. Closing does
57
+ not remove it and there is no automatic disk eviction. A partial cache is
58
+ not necessarily an independently openable HFX publication.
59
+ """
60
+
61
+ def __init__(
62
+ self,
63
+ source: str | Path,
64
+ *,
65
+ cache: bool = True,
66
+ cache_dir: str | Path | None = None,
67
+ offline: bool = False,
68
+ storage_options: Mapping[str, object] | None = None,
69
+ ) -> None:
70
+ self._location = source
71
+ self._cache = cache
72
+ self._cache_dir = cache_dir
73
+ self._offline = offline
74
+ self._storage_options = storage_options
75
+ self._source = Source(
76
+ source, cache=cache, cache_dir=cache_dir, offline=offline, storage_options=storage_options
77
+ )
78
+ self._closed = False
79
+ self._vectors: dict[str, VectorReader] = {}
80
+ self._rasters: RasterReader | None = None
81
+ try:
82
+ self.manifest = SpatialManifest.parse(self._source.read_json("manifest.json"))
83
+ except BaseException:
84
+ self.close()
85
+ raise
86
+
87
+ def _fork(self) -> HydroFabric:
88
+ """Open independent worker-owned readers against the same pinned snapshot."""
89
+ self._ensure_open()
90
+ worker = HydroFabric(
91
+ self._location,
92
+ cache=self._cache,
93
+ cache_dir=self._cache_dir,
94
+ offline=self._offline,
95
+ storage_options=self._storage_options,
96
+ )
97
+ if worker.manifest.declarations != self.manifest.declarations:
98
+ worker.close()
99
+ raise ValueError("publication changed while starting batch workers")
100
+ return worker
101
+
102
+ def _ensure_open(self) -> None:
103
+ if self._closed:
104
+ raise RuntimeError("fabric is closed")
105
+
106
+ def _reader(self, domain: str) -> VectorReader:
107
+ self._ensure_open()
108
+ if domain not in self._vectors:
109
+ self._vectors[domain] = VectorReader(self._source, self.manifest, domain)
110
+ return self._vectors[domain]
111
+
112
+ def records(self, domain: str, ids: Sequence[int], *, columns: Sequence[str] | None = None) -> pa.Table:
113
+ """Read source rows in requested order, preserving duplicate IDs.
114
+
115
+ Parameters
116
+ ----------
117
+ domain
118
+ Published feature family: ``catchments``, ``rivers`` or ``river_nodes``.
119
+ ids
120
+ Positive int64 source IDs. Empty input returns an empty table with
121
+ the selected schema; an unknown ID raises ``KeyError``.
122
+ columns
123
+ Unique source field names to read, or all fields when omitted.
124
+ Geometry is original WKB, not decoded Shapely geometry.
125
+
126
+ Returns
127
+ -------
128
+ pyarrow.Table
129
+ Materialized values with source types, nulls and applicable schema
130
+ and field metadata. Remains usable after closure.
131
+
132
+ Raises
133
+ ------
134
+ ValueError
135
+ Invalid IDs, unknown or duplicate columns, or corrupt source data.
136
+ KeyError
137
+ The domain or a requested ID is not supplied.
138
+ """
139
+ return self._reader(domain).records(ids, columns=columns)
140
+
141
+ def candidates(
142
+ self,
143
+ domain: str,
144
+ bounds: BoundingBox,
145
+ *,
146
+ levels: Sequence[int] | None = None,
147
+ columns: Sequence[str] | None = None,
148
+ ) -> pa.Table:
149
+ """Read conservative bounding-box candidates, not exact intersections.
150
+
151
+ Parameters
152
+ ----------
153
+ domain
154
+ Published ``catchments``, ``rivers`` or ``river_nodes`` family.
155
+ bounds
156
+ Non-wrapping ``(west, south, east, north)`` envelope in EPSG:4326.
157
+ Accepts a four-element sequence or 1D NumPy array of real numbers.
158
+ levels
159
+ Nonnegative source levels to retain; omitted means all levels.
160
+ Levels are independent between feature families.
161
+ columns
162
+ Unique source field names, or all fields when omitted.
163
+
164
+ Returns
165
+ -------
166
+ pyarrow.Table
167
+ Materialized source rows in publication order. False positives are
168
+ possible; test decoded geometry for exact intersection. No matches
169
+ returns an empty table with the selected schema.
170
+ """
171
+ return self._reader(domain).candidates(bounds, levels=levels, columns=columns)
172
+
173
+ def relationships(self, domain: str, ids: Sequence[int], *, columns: Sequence[str] | None = None) -> pa.Table:
174
+ """Read immediate supplied relationships in requested ID order.
175
+
176
+ Parameters
177
+ ----------
178
+ domain
179
+ Feature family whose relationship rows are requested.
180
+ ids
181
+ Positive int64 source IDs; duplicates and order are preserved.
182
+ columns
183
+ Unique relationship fields to read, or all fields when omitted.
184
+
185
+ Returns
186
+ -------
187
+ pyarrow.Table
188
+ Selected source relationship columns, with supplied metadata.
189
+ Neighbor IDs are retained as lists; ``id`` is included only when selected.
190
+ Consult ``manifest.relationships`` for each field's target domain
191
+ and meaning. Flow, hierarchy and node incidence are not interchangeable.
192
+ References to unselected features remain present; they do not imply
193
+ natural terminals. Empty input returns a schema-bearing empty table.
194
+
195
+ Raises
196
+ ------
197
+ KeyError
198
+ Relationship data for the domain or a requested ID is not supplied.
199
+ ValueError
200
+ Invalid IDs, columns or relationship data.
201
+ """
202
+ return self._reader(domain).relationships(ids, columns=columns)
203
+
204
+ def traverse(self, domain: str, ids: Sequence[int], *, relationship: str = "upstream_ids") -> list[int]:
205
+ """Return inclusive closure over a supplied same-domain relationship.
206
+
207
+ Parameters
208
+ ----------
209
+ domain
210
+ Feature family to traverse without crossing domains.
211
+ ids
212
+ Positive int64 seed IDs. Duplicate seeds are visited only once.
213
+ relationship
214
+ Declared relationship column targeting the same domain. Traversal
215
+ follows only that relationship; it does not infer hydrological flow.
216
+
217
+ Returns
218
+ -------
219
+ list
220
+ Breadth-first IDs: seeds in input order, then each frontier sorted
221
+ by ID. Cycles are deduplicated; empty seeds return an empty list.
222
+
223
+ Raises
224
+ ------
225
+ ValueError
226
+ The relationship is absent or targets another domain, or data is invalid.
227
+ KeyError
228
+ Domain relationship data or a visited ID is unavailable.
229
+ """
230
+ return self._reader(domain).traverse(ids, relationship=relationship)
231
+
232
+ def subbasins(self, ids: Sequence[int]) -> list[Subbasin]:
233
+ """Materialize whole source sub-basins in ID order, including duplicates.
234
+
235
+ Uses ``records`` ID validation and missing-ID behavior. Geometry is
236
+ decoded only when a feature's ``geometry`` property is accessed.
237
+ """
238
+ table, rows, addresses = self._reader("catchments")._addressed_records(ids)
239
+ parts = [Subbasin(table, row) for row in rows]
240
+ for part, address in zip(parts, addresses, strict=True):
241
+ object.__setattr__(part, "_source_address", address)
242
+ return parts
243
+
244
+ def nodes(self, ids: Sequence[int]) -> list[SourceNode]:
245
+ """Materialize source nodes in ID order, with ``records`` ID semantics."""
246
+ table = self.records("river_nodes", ids)
247
+ return [SourceNode(table, row) for row in range(table.num_rows)]
248
+
249
+ def river_network(self, ids: Sequence[int]) -> RiverNetwork:
250
+ """Materialize selected rivers, their relationships and referenced nodes.
251
+
252
+ River order and duplicates follow ``ids``; referenced nodes are unique
253
+ and sorted by ID. Relationships retain references to unselected rivers.
254
+ No clipping, traversal or inference of flow is performed.
255
+
256
+ Raises
257
+ ------
258
+ KeyError
259
+ The river family or its relationship data are not supplied, even
260
+ for empty IDs, or a requested river or referenced node is missing.
261
+ """
262
+ table = self.records("rivers", ids)
263
+ relations = self.relationships("rivers", ids)
264
+ node_ids: set[int] = set()
265
+ for name in ("upstream_node_ids", "downstream_node_ids"):
266
+ if name in relations.column_names:
267
+ for values in relations[name].to_pylist():
268
+ node_ids.update(values)
269
+ nodes = self.nodes(sorted(node_ids)) if node_ids else []
270
+ node_relations = (
271
+ self.relationships("river_nodes", sorted(node_ids))
272
+ if node_ids and "river_nodes" in self.manifest.relationships
273
+ else None
274
+ )
275
+ return RiverNetwork(
276
+ [River(table, row) for row in range(table.num_rows)],
277
+ relations,
278
+ nodes,
279
+ node_relations,
280
+ self.manifest.declarations,
281
+ )
282
+
283
+ @property
284
+ def rasters(self) -> RasterReader:
285
+ """Native-grid raster access owned by this open fabric's lifecycle."""
286
+ self._ensure_open()
287
+ if self._rasters is None:
288
+ self._rasters = RasterReader(self._source, self.manifest)
289
+ return self._rasters
290
+
291
+ @property
292
+ def stats(self) -> TransferStats:
293
+ """Cumulative transport calls, payload bytes and disk-cache hit bytes."""
294
+ return self._source.stats
295
+
296
+ @property
297
+ def buffer_bytes(self) -> dict[str, int]:
298
+ """Logical source/vector buffer bytes, not total process memory.
299
+
300
+ Excludes native-library caches, metadata and caller-owned results.
301
+ """
302
+ self._ensure_open()
303
+ return {
304
+ "source": self._source.buffer_bytes,
305
+ "vectors": sum(reader.buffer_bytes for reader in self._vectors.values()),
306
+ }
307
+
308
+ def close(self) -> None:
309
+ """Release source readers and connections; retain the persistent cache.
310
+
311
+ Repeated closure is harmless. Materialized tables, features and raster
312
+ arrays remain usable; subsequent source-dependent calls fail.
313
+ """
314
+ if self._closed:
315
+ return
316
+ self._closed = True
317
+ if self._rasters is not None:
318
+ self._rasters.close()
319
+ self._vectors.clear()
320
+ self._source.close()
321
+
322
+ def __enter__(self) -> Self:
323
+ self._ensure_open()
324
+ return self
325
+
326
+ def __exit__(
327
+ self, exc_type: type[BaseException] | None, exc: BaseException | None, traceback: TracebackType | None
328
+ ) -> None:
329
+ self.close()