pourpoint 0.5.0rc1__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,44 @@
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 BatchIssue, BatchResult, DelineationResult, OperationError, Target
18
+ from pourpoint.rivers import select_rivers, snap
19
+
20
+ __all__ = [
21
+ "QGISBundle",
22
+ "select_upstream_subbasins",
23
+ "delineate",
24
+ "refine",
25
+ "merge",
26
+ "snap",
27
+ "select_rivers",
28
+ "SubbasinContribution",
29
+ "OutletCell",
30
+ "RasterSubset",
31
+ "RefinementRasters",
32
+ "GranularRefinement",
33
+ "FootprintRefinement",
34
+ "BatchIssue",
35
+ "BatchResult",
36
+ "DelineationResult",
37
+ "OperationError",
38
+ "Target",
39
+ "HydroFabric",
40
+ "Subbasin",
41
+ "River",
42
+ "SourceNode",
43
+ "RiverNetwork",
44
+ ]
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,57 @@
1
+ """Release unused dictionary values in already-gathered Arrow selections."""
2
+
3
+ import pyarrow as pa
4
+ import pyarrow.compute as pc
5
+
6
+
7
+ def _compact_dictionary_values(array: pa.Array) -> pa.Array:
8
+ if isinstance(array, pa.DictionaryArray):
9
+ # Sorted original indices preserve the meaning of ordered dictionaries.
10
+ used = pc.call_function("unique", [pc.call_function("drop_null", [array.indices])])
11
+ used = pc.take(used, pc.call_function("array_sort_indices", [used]))
12
+ indices = pc.cast(
13
+ pc.call_function("index_in", [array.indices], options=pc.SetLookupOptions(used)), array.type.index_type
14
+ )
15
+ values = _compact_dictionary_values(pc.take(array.dictionary, used))
16
+ return pa.DictionaryArray.from_arrays(indices, values, ordered=array.type.ordered)
17
+ if isinstance(array, pa.ExtensionArray):
18
+ return pa.ExtensionArray.from_storage(array.type, _compact_dictionary_values(array.storage))
19
+ children: list[pa.Array]
20
+ if pa.types.is_struct(array.type) or pa.types.is_union(array.type):
21
+ children = [array.field(i) for i in range(array.type.num_fields)]
22
+ elif (
23
+ pa.types.is_list(array.type)
24
+ or pa.types.is_large_list(array.type)
25
+ or pa.types.is_fixed_size_list(array.type)
26
+ or pa.types.is_map(array.type)
27
+ or pa.types.is_list_view(array.type)
28
+ or pa.types.is_large_list_view(array.type)
29
+ ):
30
+ children = [array.values]
31
+ elif pa.types.is_run_end_encoded(array.type):
32
+ children = [array.run_ends, array.values]
33
+ else:
34
+ return array
35
+ return pa.Array.from_buffers(
36
+ array.type,
37
+ len(array),
38
+ array.buffers()[: array.type.num_buffers],
39
+ null_count=array.null_count,
40
+ offset=array.offset,
41
+ children=[_compact_dictionary_values(child) for child in children],
42
+ )
43
+
44
+
45
+ def compact_dictionaries(table: pa.Table) -> pa.Table:
46
+ """Keep exact schema and selected values without unreferenced dictionary data.
47
+
48
+ Call after Arrow take/filter has gathered ordinary value buffers. Arrow's
49
+ gather kernels retain dictionaries even when only one entry is selected.
50
+ """
51
+ return pa.Table.from_arrays(
52
+ [
53
+ pa.chunked_array([_compact_dictionary_values(chunk) for chunk in column.chunks], type=column.type)
54
+ for column in table.columns
55
+ ],
56
+ schema=table.schema,
57
+ )
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,320 @@
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 Bounds, 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, domain: str, bounds: Bounds, *, levels: Sequence[int] | None = None, columns: Sequence[str] | None = None
143
+ ) -> pa.Table:
144
+ """Read conservative bounding-box candidates, not exact intersections.
145
+
146
+ Parameters
147
+ ----------
148
+ domain
149
+ Published ``catchments``, ``rivers`` or ``river_nodes`` family.
150
+ bounds
151
+ Non-wrapping ``(west, south, east, north)`` envelope in EPSG:4326.
152
+ levels
153
+ Nonnegative source levels to retain; omitted means all levels.
154
+ Levels are independent between feature families.
155
+ columns
156
+ Unique source field names, or all fields when omitted.
157
+
158
+ Returns
159
+ -------
160
+ pyarrow.Table
161
+ Materialized source rows in publication order. False positives are
162
+ possible; test decoded geometry for exact intersection. No matches
163
+ returns an empty table with the selected schema.
164
+ """
165
+ return self._reader(domain).candidates(bounds, levels=levels, columns=columns)
166
+
167
+ def relationships(self, domain: str, ids: Sequence[int], *, columns: Sequence[str] | None = None) -> pa.Table:
168
+ """Read immediate supplied relationships in requested ID order.
169
+
170
+ Parameters
171
+ ----------
172
+ domain
173
+ Feature family whose relationship rows are requested.
174
+ ids
175
+ Positive int64 source IDs; duplicates and order are preserved.
176
+ columns
177
+ Unique relationship fields to read, or all fields when omitted.
178
+
179
+ Returns
180
+ -------
181
+ pyarrow.Table
182
+ Selected source relationship columns, with supplied metadata.
183
+ Neighbor IDs are retained as lists; ``id`` is included only when selected.
184
+ Consult ``manifest.relationships`` for each field's target domain
185
+ and meaning. Flow, hierarchy and node incidence are not interchangeable.
186
+ References to unselected features remain present; they do not imply
187
+ natural terminals. Empty input returns a schema-bearing empty table.
188
+
189
+ Raises
190
+ ------
191
+ KeyError
192
+ Relationship data for the domain or a requested ID is not supplied.
193
+ ValueError
194
+ Invalid IDs, columns or relationship data.
195
+ """
196
+ return self._reader(domain).relationships(ids, columns=columns)
197
+
198
+ def traverse(self, domain: str, ids: Sequence[int], *, relationship: str = "upstream_ids") -> list[int]:
199
+ """Return inclusive closure over a supplied same-domain relationship.
200
+
201
+ Parameters
202
+ ----------
203
+ domain
204
+ Feature family to traverse without crossing domains.
205
+ ids
206
+ Positive int64 seed IDs. Duplicate seeds are visited only once.
207
+ relationship
208
+ Declared relationship column targeting the same domain. Traversal
209
+ follows only that relationship; it does not infer hydrological flow.
210
+
211
+ Returns
212
+ -------
213
+ list
214
+ Breadth-first IDs: seeds in input order, then each frontier sorted
215
+ by ID. Cycles are deduplicated; empty seeds return an empty list.
216
+
217
+ Raises
218
+ ------
219
+ ValueError
220
+ The relationship is absent or targets another domain, or data is invalid.
221
+ KeyError
222
+ Domain relationship data or a visited ID is unavailable.
223
+ """
224
+ return self._reader(domain).traverse(ids, relationship=relationship)
225
+
226
+ def subbasins(self, ids: Sequence[int]) -> list[Subbasin]:
227
+ """Materialize whole source sub-basins in ID order, including duplicates.
228
+
229
+ Uses ``records`` ID validation and missing-ID behavior. Geometry is
230
+ decoded only when a feature's ``geometry`` property is accessed.
231
+ """
232
+ table = self.records("catchments", ids)
233
+ return [Subbasin(table, row) for row in range(table.num_rows)]
234
+
235
+ def nodes(self, ids: Sequence[int]) -> list[SourceNode]:
236
+ """Materialize source nodes in ID order, with ``records`` ID semantics."""
237
+ table = self.records("river_nodes", ids)
238
+ return [SourceNode(table, row) for row in range(table.num_rows)]
239
+
240
+ def river_network(self, ids: Sequence[int]) -> RiverNetwork:
241
+ """Materialize selected rivers, their relationships and referenced nodes.
242
+
243
+ River order and duplicates follow ``ids``; referenced nodes are unique
244
+ and sorted by ID. Relationships retain references to unselected rivers.
245
+ No clipping, traversal or inference of flow is performed.
246
+
247
+ Raises
248
+ ------
249
+ KeyError
250
+ The river family or its relationship data are not supplied, even
251
+ for empty IDs, or a requested river or referenced node is missing.
252
+ """
253
+ table = self.records("rivers", ids)
254
+ relations = self.relationships("rivers", ids)
255
+ node_ids: set[int] = set()
256
+ for name in ("upstream_node_ids", "downstream_node_ids"):
257
+ if name in relations.column_names:
258
+ for values in relations[name].to_pylist():
259
+ node_ids.update(values)
260
+ nodes = self.nodes(sorted(node_ids)) if node_ids else []
261
+ node_relations = (
262
+ self.relationships("river_nodes", sorted(node_ids))
263
+ if node_ids and "river_nodes" in self.manifest.relationships
264
+ else None
265
+ )
266
+ return RiverNetwork(
267
+ [River(table, row) for row in range(table.num_rows)],
268
+ relations,
269
+ nodes,
270
+ node_relations,
271
+ self.manifest.declarations,
272
+ )
273
+
274
+ @property
275
+ def rasters(self) -> RasterReader:
276
+ """Native-grid raster access owned by this open fabric's lifecycle."""
277
+ self._ensure_open()
278
+ if self._rasters is None:
279
+ self._rasters = RasterReader(self._source, self.manifest)
280
+ return self._rasters
281
+
282
+ @property
283
+ def stats(self) -> TransferStats:
284
+ """Cumulative transport calls, payload bytes and disk-cache hit bytes."""
285
+ return self._source.stats
286
+
287
+ @property
288
+ def buffer_bytes(self) -> dict[str, int]:
289
+ """Logical source/vector buffer bytes, not total process memory.
290
+
291
+ Excludes native-library caches, metadata and caller-owned results.
292
+ """
293
+ self._ensure_open()
294
+ return {
295
+ "source": self._source.buffer_bytes,
296
+ "vectors": sum(reader.buffer_bytes for reader in self._vectors.values()),
297
+ }
298
+
299
+ def close(self) -> None:
300
+ """Release source readers and connections; retain the persistent cache.
301
+
302
+ Repeated closure is harmless. Materialized tables, features and raster
303
+ arrays remain usable; subsequent source-dependent calls fail.
304
+ """
305
+ if self._closed:
306
+ return
307
+ self._closed = True
308
+ if self._rasters is not None:
309
+ self._rasters.close()
310
+ self._vectors.clear()
311
+ self._source.close()
312
+
313
+ def __enter__(self) -> Self:
314
+ self._ensure_open()
315
+ return self
316
+
317
+ def __exit__(
318
+ self, exc_type: type[BaseException] | None, exc: BaseException | None, traceback: TracebackType | None
319
+ ) -> None:
320
+ self.close()