Skip to content

FlowDirection#

Typed flow-direction raster — produced by DEM.flow_direction(method=...) for any of the five routing schemes (d8 / dinf / mfd_quinn / mfd_holmgren / rho8). Carries a routing tag persisted into the raster's metadata (DR_ROUTING) so downstream consumers stay aware of which scheme produced the grid.

Top-level surface:

  • accumulate(weights=...) — Kahn topological-sort flow accumulation (single kernel for all five routings).
  • watershed(points, ...) — pour-point watershed delineation under D8 / Rho8.
  • basins(...) — partition the DEM into one basin per terminal outlet.
  • subbasins_pfafstetter(accumulation, streams, level=N) — hierarchical Pfafstetter coding to the requested level (1 or 2).
  • isobasins(streams, accumulation, target_area_km2) — equal-area sub-basin partition (W-7).
  • upslope_flowpath_length() — per-cell longest upslope flow path (W-9).
  • upscale(method=...) / upscale_ihu(...) — COTAT / EAM / DMM / IHU (Eilander 2021) upscalers.

digitalrivers.flow.direction.FlowDirection #

Bases: UpscaleMixin, PfafstetterMixin, Dataset

Flow-direction raster with routing-scheme metadata.

Parameters:

Name Type Description Default
src Dataset

GDAL dataset wrapping a flow-direction raster.

required
access str

"read_only" (default) or "write".

'read_only'
routing str

Routing scheme used to produce this raster. One of "d8", "dinf", "mfd_quinn", "mfd_holmgren", "rho8". Required keyword-only argument — no default.

required
encoding str

Cell-value encoding convention. One of "digitalrivers", "taudem", "esri", "whitebox". Defaults to "digitalrivers" (the convention defined by DIR_OFFSETS in core.directions).

'digitalrivers'
gdal_env dict[str, str] | None

GDAL config (cloud credentials, HTTP knobs) captured on the dataset and re-installed around its reads, so the paths that reopen the file authenticate the same way. Default None.

None
open_options tuple[str, ...] | list[str] | None

GDAL open options captured on the dataset and reapplied when it is reopened. Default None.

None

Raises:

Type Description
ValueError

If routing or encoding is not a recognised value.

Source code in src/digitalrivers/flow/direction.py
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
class FlowDirection(UpscaleMixin, PfafstetterMixin, Dataset):
    """Flow-direction raster with routing-scheme metadata.

    Args:
        src: GDAL dataset wrapping a flow-direction raster.
        access: `"read_only"` (default) or `"write"`.
        routing: Routing scheme used to produce this raster. One of
            `"d8"`, `"dinf"`, `"mfd_quinn"`, `"mfd_holmgren"`,
            `"rho8"`. Required keyword-only argument — no default.
        encoding: Cell-value encoding convention. One of `"digitalrivers"`,
            `"taudem"`, `"esri"`, `"whitebox"`. Defaults to
            `"digitalrivers"` (the convention defined by `DIR_OFFSETS` in
            `core.directions`).
        gdal_env: GDAL config (cloud credentials, HTTP knobs) captured on
            the dataset and re-installed around its reads, so the paths that
            reopen the file authenticate the same way. Default `None`.
        open_options: GDAL open options captured on the dataset and reapplied
            when it is reopened. Default `None`.

    Raises:
        ValueError: If `routing` or `encoding` is not a recognised value.
    """

    routing: str
    encoding: str

    def __init__(
        self,
        src: gdal.Dataset,
        access: str = "read_only",
        *,
        routing: str,
        encoding: str = "digitalrivers",
        gdal_env: dict[str, str] | None = None,
        open_options: tuple[str, ...] | list[str] | None = None,
    ):
        """Wrap a GDAL dataset as a flow-direction raster.

        Args:
            src: Open GDAL dataset to wrap. The handle is adopted, not copied.
            access: `"read_only"` (default) or `"write"`.
            gdal_env: GDAL config (cloud credentials, HTTP knobs) captured on the
                dataset and re-installed around its reads. Default `None`.
            open_options: GDAL open options captured on the dataset and reapplied
                when it is reopened. Default `None`.
            routing: Routing scheme the raster encodes. Required keyword-only —
                there is no default, because reading a D-infinity raster as D8
                silently corrupts every derivative.
            encoding: Cell-value convention. Defaults to `"digitalrivers"`.

        Raises:
            ValueError: If `routing` or `encoding` is not a recognised value.
        """
        super().__init__(src, access, gdal_env=gdal_env, open_options=open_options)
        if routing not in VALID_ROUTING:
            raise ValueError(
                f"routing must be one of {sorted(VALID_ROUTING)}; got {routing!r}"
            )
        if encoding not in VALID_ENCODING:
            raise ValueError(
                f"encoding must be one of {sorted(VALID_ENCODING)}; got {encoding!r}"
            )
        self.routing = routing
        self.encoding = encoding

    @classmethod
    def from_dataset(
        cls,
        ds: Dataset,
        *,
        routing: str,
        encoding: str = "digitalrivers",
    ) -> FlowDirection:
        """Promote a plain `Dataset` into a `FlowDirection`.

        The source's access mode, `gdal_env` and `open_options` are carried onto
        the wrapper. Dropping them left a promoted file-backed raster unable to
        write its own metadata tags, and stripped the credentials a signed remote
        raster needs when pyramids reopens it.

        Args:
            ds: Dataset wrapping the flow-direction raster. Its raster handle is
                reused, not copied.
            routing: Routing scheme. Required keyword-only.
            encoding: Cell-value encoding convention.

        Returns:
            A `FlowDirection` over the same raster, with `ds`'s handle
            configuration.

        Examples:
            - Promote an in-memory raster and read the provenance back, and confirm the handle carries through:
                ```python
                >>> import numpy as np
                >>> from pyramids.dataset import Dataset, GeoReference
                >>> from digitalrivers import FlowDirection
                >>> plain = Dataset.from_array(
                ...     np.array([[0, 1], [2, 3]], dtype=np.int32),
                ...     geo_ref=GeoReference(
                ...         top_left_corner=(0.0, 0.0), cell_size=1.0, epsg=4326
                ...     ),
                ... )
                >>> wrapped = FlowDirection.from_dataset(plain, routing="d8")
                >>> wrapped.routing, wrapped.encoding
                ('d8', 'digitalrivers')
                >>> FlowDirection.from_dataset(
                ...     plain, routing="d8"
                ... ).access == plain.access
                True

                ```
        """
        return cls(
            ds.raster,
            ds.access,
            routing=routing,
            encoding=encoding,
            gdal_env=ds.gdal_env or None,
            open_options=ds.open_options or None,
        )

    def to_dataset(self) -> Dataset:
        """Drop the typed wrapper and return the underlying `Dataset`.

        Symmetric with `from_dataset`: the access mode, `gdal_env` and
        `open_options` come back out with the raster, so a round trip does not
        silently downgrade a writable handle to a read-only one.

        Returns:
            A plain `Dataset` over the same raster and handle configuration.

        Examples:
            - Unwrap and read the grid straight off the plain `Dataset`, and confirm the handle carries through:
                ```python
                >>> import numpy as np
                >>> from pyramids.dataset import Dataset, GeoReference
                >>> from digitalrivers import FlowDirection
                >>> plain = Dataset.from_array(
                ...     np.array([[1, 2], [3, 4]], dtype=np.float32),
                ...     geo_ref=GeoReference(
                ...         top_left_corner=(0.0, 0.0), cell_size=1.0, epsg=4326
                ...     ),
                ... )
                >>> wrapped = FlowDirection.from_dataset(plain, routing="d8")
                >>> plain_again = wrapped.to_dataset()
                >>> plain_again.read_array().tolist()
                [[1.0, 2.0], [3.0, 4.0]]
                >>> wrapped.to_dataset().access == wrapped.access
                True

                ```
        """
        return Dataset(
            self.raster,
            self.access,
            gdal_env=self.gdal_env or None,
            open_options=self.open_options or None,
        )

    def persist_metadata(self) -> None:
        """Write `routing` and `encoding` to the underlying raster tags.

        Stored under `DR_CLASS` / `DR_ROUTING` / `DR_ENCODING` GeoTIFF
        metadata keys so `FlowDirection.open(path)` can recover them.
        """
        self.metadata = {
            META_CLASS: type(self).__name__,
            META_ROUTING: self.routing,
            META_ENCODING: self.encoding,
        }

    @classmethod
    def open(
        cls,
        path: str,
        *,
        routing: str | None = None,
        encoding: str | None = None,
        read_only: bool = True,
        gdal_env: dict[str, str] | None = None,
        open_options: tuple[str, ...] | list[str] | None = None,
    ) -> FlowDirection:
        """Open a `FlowDirection` GeoTIFF.

        Resolution order for the routing/encoding tags:

        1. Explicit `routing=` / `encoding=` kwargs win unconditionally
           (caller knows what the file is).
        2. Otherwise, `DR_ROUTING` / `DR_ENCODING` metadata tags are used
           if present.
        3. Otherwise, raise `ValueError`. There is no silent fallback to
           `"d8"` — a D∞ raster on disk is float32 in `[0, 2π]` and
           reinterpreting it as int D8 codes silently corrupts every
           downstream computation.

        Args:
            path: Path to the GeoTIFF.
            routing: Explicit routing override. If `None`, falls back to
                the `DR_ROUTING` tag.
            encoding: Explicit encoding override. If `None`, falls back to
                the `DR_ENCODING` tag, then to `"digitalrivers"`.
            read_only: Open the file read-only (default). Pass `False` to
                get a writable handle — required before `persist_metadata()`
                can stamp the `DR_*` tags onto an existing file.
            gdal_env: GDAL config (cloud credentials, HTTP knobs) installed
                for the open and captured on the result, so pyramids' reopen
                paths re-authenticate. Default `None`.
            open_options: GDAL open options forwarded to the driver and
                captured on the result. Default `None`.

        Returns:
            A `FlowDirection` wrapping the opened raster.

        Raises:
            ValueError: If neither `routing=` nor a `DR_ROUTING` tag is
                available.
        """
        ds = Dataset.read_file(
            path, read_only, gdal_env=gdal_env, open_options=open_options
        )
        md = ds.metadata or {}
        resolved_routing = routing or md.get(META_ROUTING)
        resolved_encoding = encoding or md.get(META_ENCODING) or "digitalrivers"
        if resolved_routing is None:
            raise ValueError(
                f"{path!r} carries no DR_ROUTING tag and no routing= was passed. "
                f"Pass routing= explicitly (one of {sorted(VALID_ROUTING)}) to "
                f"avoid silent misinterpretation of cell values."
            )
        return cls(
            ds.raster,
            ds.access,
            routing=resolved_routing,
            encoding=resolved_encoding,
            gdal_env=ds.gdal_env or None,
            open_options=ds.open_options or None,
        )

    def accumulate(
        self,
        weights: Dataset | None = None,
        *,
        engine: str = "auto",
        out_path: str | None = None,
        tile_size: int | tuple[int, int] = 2048,
        cache: str = "evict",
        workers: int = 1,
        scratch_dir: str | None = None,
        scheduler: str = "threads",
        client=None,
    ) -> Accumulation:
        """Run flow accumulation over this raster's routing scheme.

        Implements a Kahn topological-sort sweep that handles all five routing
        schemes (D8, Rho8, D∞, MFD-Quinn, MFD-Holmgren) via a single algorithm,
        dispatched by `self.routing`.

        Output semantics: `out[cell] = sum of weights over strictly-upstream
        cells` — the cell's own weight does not contribute to its own count.
        This matches the legacy `DEM.flow_accumulation` convention.

        Args:
            weights: Per-cell weight raster (rainfall, runoff coefficient,
                whatever). Must align with this FlowDirection's shape. `None`
                means unit weights (cell-count accumulation).

        Returns:
            Accumulation carrying this object's `routing` for provenance.

        Out-of-core:
            `engine="tiled"` streams a Barnes-2017 tiled accumulation to `out_path` (D8/Rho8 only). `engine="auto"`
            (default) only switches to it when the raster is large enough to risk exhausting RAM.
        """
        from digitalrivers._outofcore.engine import (  # lazy
            require_out_path,
            resolve_engine,
        )

        resolved = resolve_engine(engine, self.rows, self.columns, k=6)
        if resolved == "tiled":
            require_out_path(engine, out_path)
            # lazy import: pulls the numba kernels only when the tiled path is actually used
            from digitalrivers._outofcore.accumulate import flow_accumulation_tiled

            tile_rows, tile_cols = (
                (tile_size, tile_size) if isinstance(tile_size, int) else tile_size
            )
            out = flow_accumulation_tiled(
                self,
                out_path,
                weights=weights,
                tile_rows=tile_rows,
                tile_cols=tile_cols,
                cache=cache,
                workers=workers,
                scratch_dir=scratch_dir,
                scheduler=scheduler,
                client=client,
            )
            from digitalrivers.flow.accumulation import Accumulation

            return Accumulation.from_dataset(out, routing=self.routing)

        from digitalrivers.flow.accumulation import Accumulation

        fd_arr = self.read_array()
        valid_mask = self._valid_mask_from_array(fd_arr)
        if weights is not None:
            w_arr = weights.read_array()
            if w_arr.shape != valid_mask.shape:
                raise ValueError(
                    f"weights shape {w_arr.shape} does not match flow_direction "
                    f"shape {valid_mask.shape}"
                )
        else:
            w_arr = None
        acc = _accumulate_array(fd_arr, self.routing, valid_mask, weights=w_arr)
        acc_f32 = acc.astype(np.float32, copy=False)
        plain = Dataset.from_array(
            acc_f32,
            geo_ref=GeoReference(geo=self.geotransform, epsg=self.epsg),
            no_data_value=self.default_no_data_value,
        )
        return Accumulation.from_dataset(plain, routing=self.routing)

    def _valid_mask_from_array(self, arr) -> np.ndarray:
        """Compute the (rows, cols) bool mask of valid-data cells from the raster.

        For accumulation purposes `valid` means "this cell can hold and receive a
        contribution". For D8/Rho8 we cannot distinguish a sink (cell with no
        outgoing direction but still in the data envelope) from a truly-outside
        cell at the flow-direction level — both share the no-data sentinel. We
        treat all in-bounds cells as valid; truly-outside cells naturally end up
        with accumulation 0 because no valid direction points at them, and
        callers that want to mask them in the output do so against the original
        DEM (this is what `DEM.flow_accumulation` does).

        Multi-band MFD/D∞ rasters use band 0 as the routing-specific validity
        indicator (angle `>= 0` for D∞, any non-zero fraction for MFD).
        """
        if arr.ndim == 2:
            # D8 / Rho8: treat every in-bounds cell as a valid receiver. Sinks
            # (direction == no_data) are kept in the graph so they accumulate.
            return np.ones(arr.shape, dtype=bool)
        # Multi-band routings.
        band0 = arr[0]
        if self.routing == "dinf":
            return band0 >= 0
        no_val = self.no_data_value[0] if self.no_data_value else None
        if no_val is None:
            return np.ones(band0.shape, dtype=bool)
        return band0 != no_val

    def upslope_flowpath_length(self) -> Dataset:
        """Return a per-cell raster of the longest upslope flow path.

        For every cell in the raster, the returned value is the longest
        planimetric flow path from any upstream source to that cell —
        following D8 / Rho8 receivers, with cardinal steps contributing
        `cell_size` and diagonal steps contributing `cell_size * sqrt(2)`.
        Source cells (no upstream neighbour pointing at them) hold `0.0`.

        Only single-direction routings (`d8` / `rho8`) are supported.

        Returns:
            `Dataset` of float32 lengths in map units, aligned to this
            `FlowDirection` raster. Uses `-9999.0` as the on-disk no-data
            sentinel.

        Raises:
            ValueError: If `self.routing` is not single-direction.
        """
        if self.routing not in ("d8", "rho8"):
            raise ValueError(
                f"upslope_flowpath_length supports single-direction routing "
                f"only; got {self.routing!r}"
            )
        fdir = self.read_array().astype(np.int32, copy=False)
        lengths = kahn_max_upslope_length(fdir, float(abs(self.geotransform[1])))
        return Dataset.from_array(
            lengths.astype(np.float32),
            geo_ref=GeoReference(geo=self.geotransform, epsg=self.epsg),
            no_data_value=-9999.0,
        )

    def isobasins(
        self,
        streams,
        accumulation,
        target_area_km2: float,
    ) -> WatershedRaster:
        """Partition the catchment into sub-basins of approximately equal area.

        Walks the stream network from heads to outlet via the accumulation
        raster. At every stream cell whose floor-divided accumulation quantile
        (`accumulation // target_cells`) is strictly greater than the maximum
        quantile of its stream-upstream neighbours, a virtual sub-basin
        outlet is placed. The final sub-basin labels are produced by
        first-claim-wins reverse-BFS watershed delineation on those seeds.

        Args:
            streams: `StreamRaster` aligned to this flow-direction raster.
            accumulation: `Accumulation` raster aligned to this flow-direction
                raster (units: cells).
            target_area_km2: Target sub-basin area in km². Converted to
                target cell count via the dataset's cell size; must be
                positive.

        Returns:
            `WatershedRaster` whose cells carry a `1..N` sub-basin label
            (or 0 for cells outside any sub-basin) and whose `outlets`
            mapping carries `{basin_id: (row, col)}`.

        Raises:
            ValueError: If routing is multi-direction, shapes mismatch, or
                `target_area_km2` is not positive.
        """
        from digitalrivers.watershed.raster import WatershedRaster

        if self.routing not in ("d8", "rho8"):
            raise ValueError(
                f"isobasins supports single-direction routing only; got "
                f"{self.routing!r}"
            )
        if target_area_km2 <= 0:
            raise ValueError(
                f"target_area_km2 must be positive; got {target_area_km2!r}"
            )

        sm = streams.read_array().astype(bool, copy=False)
        acc_arr = accumulation.read_array().astype(np.int64, copy=False)
        fdir = self.read_array().astype(np.int32, copy=False)
        if sm.shape != fdir.shape or acc_arr.shape != fdir.shape:
            raise ValueError(
                f"shape mismatch: fdir={fdir.shape}, streams={sm.shape}, "
                f"accumulation={acc_arr.shape}"
            )

        gt = self.geotransform
        cell_area_km2 = abs(gt[1] * gt[5]) / 1.0e6
        target_cells = max(1, int(round(target_area_km2 / cell_area_km2)))

        # Quantile bucket of each stream cell, -1 elsewhere.
        quantile = np.where(sm, acc_arr // target_cells, -1).astype(np.int64)

        # For each stream cell, find the max quantile across its stream-upstream
        # neighbours. A cell with strictly larger quantile than that max marks a
        # bucket-boundary — place a seed there.
        rows, cols = sm.shape
        up_max = np.full((rows, cols), -1, dtype=np.int64)
        for k in range(8):
            dr = int(_DIR_DR[k])
            dc = int(_DIR_DC[k])
            src_r = slice(max(0, dr), min(rows, rows + dr))
            src_c = slice(max(0, dc), min(cols, cols + dc))
            dst_r = slice(max(0, -dr), min(rows, rows - dr))
            dst_c = slice(max(0, -dc), min(cols, cols - dc))
            sm_src = sm[src_r, src_c]
            fd_src = fdir[src_r, src_c]
            inflow = sm_src & (fd_src == int(_INV_DIR[k])) & sm[dst_r, dst_c]
            cand = np.where(inflow, quantile[src_r, src_c], -1).astype(np.int64)
            block = up_max[dst_r, dst_c]
            np.maximum(block, cand, out=block)
            up_max[dst_r, dst_c] = block

        seed_mask = sm & (quantile > up_max)
        seed_rcs: list[tuple[int, int]] = [
            (int(r), int(c)) for r, c in zip(*np.nonzero(seed_mask))
        ]
        if not seed_rcs:
            # Catchment smaller than target → fall back to a single basin at
            # the outlet (consistent with WBT's behaviour at extreme inputs).
            outlets = _stream_outlets(sm, fdir)
            if not outlets:
                # No stream cells at all — emit an all-zero basin raster.
                labels = np.zeros((rows, cols), dtype=np.int32)
                plain = Dataset.from_array(
                    labels,
                    geo_ref=GeoReference(geo=self.geotransform, epsg=self.epsg),
                    no_data_value=0,
                )
                return WatershedRaster.from_dataset(
                    plain,
                    routing=self.routing,
                    outlets={},
                )
            seed_rcs = [outlets[0]]

        basin_ids = list(range(1, len(seed_rcs) + 1))
        labels = watershed_d8(
            fdir,
            seed_rcs,
            basin_ids,
            require_unique_basins=True,
        )
        plain = Dataset.from_array(
            labels.astype(np.int32),
            geo_ref=GeoReference(geo=self.geotransform, epsg=self.epsg),
            no_data_value=0,
        )
        outlets_dict = dict(zip(basin_ids, seed_rcs))
        return WatershedRaster.from_dataset(
            plain,
            routing=self.routing,
            outlets=outlets_dict,
        )

    def basins(
        self,
        *,
        min_area_cells: int | None = None,
        min_area_km2: float | None = None,
        merge_small: str = "drop",
    ) -> WatershedRaster:
        """Partition the entire DEM into basins, one label per terminal outlet.

        Detects every cell whose flow direction is the no-data sentinel
        (cells with no defined downstream — either at the data envelope or
        at internal sinks that survived the fill phase) and seeds a reverse
        BFS from each. The result labels every valid cell with the ID of
        the outlet it drains to.

        Args:
            min_area_cells: Optional minimum basin area in cells; basins
                smaller than this are post-processed via `merge_small`.
            min_area_km2: Same threshold expressed in map km². Mutually
                exclusive with `min_area_cells`.
            merge_small: `"drop"` (default) sets undersized basins to 0;
                `"merge_to_neighbour"` dilates the small basin's mask by
                one cell, collects the labels of every basin it touches,
                and relabels the small basin with the largest of those
                8-neighbour labels. Returns `0` for basins whose entire
                8-neighbourhood is either background or other small
                basins (no qualifying survivor).

        Returns:
            :class:`WatershedRaster` tagged with this FlowDirection's
            routing. The `outlets` GeoDataFrame has one row per surviving
            basin with the outlet `row`/`col`/`x`/`y` and
            `cell_count`.

        Raises:
            ValueError: If both area kwargs are supplied or
                `merge_small` is unknown.
        """
        from digitalrivers.watershed.raster import WatershedRaster

        if self.routing not in ("d8", "rho8"):
            raise ValueError(
                f"basins currently supports single-direction routing only; "
                f"got {self.routing!r}"
            )
        if min_area_cells is not None and min_area_km2 is not None:
            raise ValueError("Pass at most one of min_area_cells / min_area_km2")
        if merge_small not in ("drop", "merge_to_neighbour"):
            raise ValueError(
                f"merge_small must be 'drop' or 'merge_to_neighbour'; "
                f"got {merge_small!r}"
            )

        fdir = self.read_array().astype(np.int32, copy=False)
        rows, cols = fdir.shape
        gt = self.geotransform
        x0, dx, _, y0, _, dy = gt

        no_val = self.no_data_value[0] if self.no_data_value else None
        # Outlet = cell whose direction code is not in [0, 7] (sink) but the
        # cell itself is in the data envelope.
        if no_val is None:
            no_val = -9999
        is_outlet = (fdir < 0) | (fdir > 7)

        if min_area_km2 is not None:
            cell_area_m2 = abs(dx * dy)
            min_area_cells = int(round(min_area_km2 * 1.0e6 / cell_area_m2))

        seeds: list[tuple[int, int]] = []
        basin_ids: list[int] = []
        outlet_records: list[dict] = []
        bid = 1
        for r, c in zip(*np.nonzero(is_outlet)):
            r = int(r)
            c = int(c)
            seeds.append((r, c))
            basin_ids.append(bid)
            outlet_records.append(
                {
                    "basin_id": bid,
                    "row": r,
                    "col": c,
                    "x": x0 + (c + 0.5) * dx,
                    "y": y0 + (r + 0.5) * dy,
                }
            )
            bid += 1

        basins = watershed_d8(fdir, seeds, basin_ids, require_unique_basins=True)

        # Area filter.
        if min_area_cells is not None and min_area_cells > 1:
            unique, counts = np.unique(basins, return_counts=True)
            sizes = dict(zip(unique.tolist(), counts.tolist()))
            small_ids = {b for b, n in sizes.items() if b != 0 and n < min_area_cells}
            if merge_small == "drop":
                for b in small_ids:
                    basins[basins == b] = 0
            else:  # merge_to_neighbour
                # 8-connected adjacency: shift the small-basin mask in each of
                # the 8 directions and collect any non-self, non-small basin
                # labels that touch its boundary. Pick the largest of those.
                rows, cols = basins.shape
                for b in small_ids:
                    mask = basins == b
                    if not mask.any():
                        continue
                    # Build the 1-cell-dilated border of the small basin.
                    border_labels: set[int] = set()
                    for dr in (-1, 0, 1):
                        for dc in (-1, 0, 1):
                            if dr == 0 and dc == 0:
                                continue
                            r0, r1 = max(0, dr), rows + min(0, dr)
                            c0, c1 = max(0, dc), cols + min(0, dc)
                            src_r0, src_r1 = max(0, -dr), rows + min(0, -dr)
                            src_c0, src_c1 = max(0, -dc), cols + min(0, -dc)
                            mask_dst = mask[r0:r1, c0:c1]
                            labels_src = basins[src_r0:src_r1, src_c0:src_c1]
                            touched = labels_src[mask_dst]
                            border_labels.update(int(v) for v in np.unique(touched))
                    # Drop self, background, and other small basins.
                    candidates = [
                        lbl
                        for lbl in border_labels
                        if lbl != 0 and lbl != b and lbl not in small_ids
                    ]
                    if not candidates:
                        neighbour_id = 0
                    else:
                        neighbour_id = max(candidates, key=lambda lbl: sizes[lbl])
                    basins[mask] = neighbour_id
            # Trim outlet records.
            outlet_records = [
                rec for rec in outlet_records if rec["basin_id"] not in small_ids
            ]
            for rec in outlet_records:
                rec["cell_count"] = int(sizes.get(rec["basin_id"], 0))
        else:
            unique, counts = np.unique(basins, return_counts=True)
            sizes = dict(zip(unique.tolist(), counts.tolist()))
            for rec in outlet_records:
                rec["cell_count"] = int(sizes.get(rec["basin_id"], 0))

        plain = Dataset.from_array(
            basins,
            geo_ref=GeoReference(geo=self.geotransform, epsg=self.epsg),
            no_data_value=0,
        )

        outlets_gdf = gpd.GeoDataFrame(
            outlet_records,
            geometry=[Point(rec["x"], rec["y"]) for rec in outlet_records],
            crs=self.epsg,
        )
        return WatershedRaster.from_dataset(
            plain,
            routing=self.routing,
            outlets=outlets_gdf,
        )

    def watershed(
        self,
        pour_points,
        require_unique_basins: bool = False,
    ) -> WatershedRaster:
        """Delineate the upstream watershed of each pour point.

        Reverse-BFS from every pour-point cell, labelling every contributing
        cell with the pour point's 1-based basin ID. Multi-point inputs
        produce a labelled raster (one ID per pour point).

        Args:
            pour_points: `GeoDataFrame` of Point geometries — one row per
                desired basin. Points outside the raster envelope are skipped
                with a NaN entry in the returned `outlets` GeoDataFrame.
            require_unique_basins: If False (default), inner pour points
                overwrite the outer basin's cells along shared upstream
                paths — the outer basin contains a hole around the inner
                basin. If True, the first seed to claim a cell keeps it; the
                outer basin contains no inner-basin cells.

        Returns:
            :class:`WatershedRaster` tagged with this FlowDirection's routing.
            The `outlets` attribute is a GeoDataFrame parallel to the input
            `pour_points`.
        """
        from digitalrivers.watershed.raster import WatershedRaster

        if self.routing not in ("d8", "rho8"):
            raise ValueError(
                f"watershed currently supports single-direction routing only; "
                f"got {self.routing!r}"
            )

        target_epsg = self.epsg
        if (
            getattr(pour_points, "crs", None) is not None
            and target_epsg is not None
            and pour_points.crs.to_epsg() != target_epsg
        ):
            pour_points = pour_points.to_crs(target_epsg)

        fdir = self.read_array().astype(np.int32, copy=False)
        rows, cols = fdir.shape
        gt = self.geotransform
        x0, dx, _, y0, _, dy = gt

        seeds: list[tuple[int, int]] = []
        basin_ids: list[int] = []
        outlet_records: list[dict] = []
        for i, pt in enumerate(pour_points.geometry):
            px, py = float(pt.x), float(pt.y)
            col = int((px - x0) / dx)
            row = int((py - y0) / dy)
            bid = i + 1
            if 0 <= row < rows and 0 <= col < cols:
                seeds.append((row, col))
                basin_ids.append(bid)
                outlet_records.append(
                    {
                        "basin_id": bid,
                        "row": row,
                        "col": col,
                        "x": x0 + (col + 0.5) * dx,
                        "y": y0 + (row + 0.5) * dy,
                    }
                )
            else:
                outlet_records.append(
                    {
                        "basin_id": bid,
                        "row": -1,
                        "col": -1,
                        "x": float("nan"),
                        "y": float("nan"),
                    }
                )

        basins = watershed_d8(
            fdir, seeds, basin_ids, require_unique_basins=require_unique_basins
        )
        plain = Dataset.from_array(
            basins,
            geo_ref=GeoReference(geo=self.geotransform, epsg=self.epsg),
            no_data_value=0,
        )

        outlets_gdf = gpd.GeoDataFrame(
            outlet_records,
            geometry=[
                Point(rec["x"], rec["y"]) if not (rec["row"] < 0) else None
                for rec in outlet_records
            ],
            crs=target_epsg,
        )
        return WatershedRaster.from_dataset(
            plain,
            routing=self.routing,
            outlets=outlets_gdf,
        )

    def __repr__(self) -> str:
        """Return a one-line summary of the raster.

        Names its shape, routing scheme and cell-value encoding.

        Both tags are shown, because a direction grid is only interpretable given the
        pair: the same cell value means different neighbours under different
        encodings.

        Returns:
            A string of the form `<FlowDirection rows=R cols=C routing='...' encoding='...'>`.
        """
        return (
            f"<FlowDirection rows={self.rows} cols={self.columns} "
            f"routing={self.routing!r} encoding={self.encoding!r}>"
        )

__init__(src, access='read_only', *, routing, encoding='digitalrivers', gdal_env=None, open_options=None) #

Wrap a GDAL dataset as a flow-direction raster.

Parameters:

Name Type Description Default
src Dataset

Open GDAL dataset to wrap. The handle is adopted, not copied.

required
access str

"read_only" (default) or "write".

'read_only'
gdal_env dict[str, str] | None

GDAL config (cloud credentials, HTTP knobs) captured on the dataset and re-installed around its reads. Default None.

None
open_options tuple[str, ...] | list[str] | None

GDAL open options captured on the dataset and reapplied when it is reopened. Default None.

None
routing str

Routing scheme the raster encodes. Required keyword-only — there is no default, because reading a D-infinity raster as D8 silently corrupts every derivative.

required
encoding str

Cell-value convention. Defaults to "digitalrivers".

'digitalrivers'

Raises:

Type Description
ValueError

If routing or encoding is not a recognised value.

Source code in src/digitalrivers/flow/direction.py
def __init__(
    self,
    src: gdal.Dataset,
    access: str = "read_only",
    *,
    routing: str,
    encoding: str = "digitalrivers",
    gdal_env: dict[str, str] | None = None,
    open_options: tuple[str, ...] | list[str] | None = None,
):
    """Wrap a GDAL dataset as a flow-direction raster.

    Args:
        src: Open GDAL dataset to wrap. The handle is adopted, not copied.
        access: `"read_only"` (default) or `"write"`.
        gdal_env: GDAL config (cloud credentials, HTTP knobs) captured on the
            dataset and re-installed around its reads. Default `None`.
        open_options: GDAL open options captured on the dataset and reapplied
            when it is reopened. Default `None`.
        routing: Routing scheme the raster encodes. Required keyword-only —
            there is no default, because reading a D-infinity raster as D8
            silently corrupts every derivative.
        encoding: Cell-value convention. Defaults to `"digitalrivers"`.

    Raises:
        ValueError: If `routing` or `encoding` is not a recognised value.
    """
    super().__init__(src, access, gdal_env=gdal_env, open_options=open_options)
    if routing not in VALID_ROUTING:
        raise ValueError(
            f"routing must be one of {sorted(VALID_ROUTING)}; got {routing!r}"
        )
    if encoding not in VALID_ENCODING:
        raise ValueError(
            f"encoding must be one of {sorted(VALID_ENCODING)}; got {encoding!r}"
        )
    self.routing = routing
    self.encoding = encoding

from_dataset(ds, *, routing, encoding='digitalrivers') classmethod #

Promote a plain Dataset into a FlowDirection.

The source's access mode, gdal_env and open_options are carried onto the wrapper. Dropping them left a promoted file-backed raster unable to write its own metadata tags, and stripped the credentials a signed remote raster needs when pyramids reopens it.

Parameters:

Name Type Description Default
ds Dataset

Dataset wrapping the flow-direction raster. Its raster handle is reused, not copied.

required
routing str

Routing scheme. Required keyword-only.

required
encoding str

Cell-value encoding convention.

'digitalrivers'

Returns:

Type Description
FlowDirection

A FlowDirection over the same raster, with ds's handle

FlowDirection

configuration.

Examples:

  • Promote an in-memory raster and read the provenance back, and confirm the handle carries through:
    >>> import numpy as np
    >>> from pyramids.dataset import Dataset, GeoReference
    >>> from digitalrivers import FlowDirection
    >>> plain = Dataset.from_array(
    ...     np.array([[0, 1], [2, 3]], dtype=np.int32),
    ...     geo_ref=GeoReference(
    ...         top_left_corner=(0.0, 0.0), cell_size=1.0, epsg=4326
    ...     ),
    ... )
    >>> wrapped = FlowDirection.from_dataset(plain, routing="d8")
    >>> wrapped.routing, wrapped.encoding
    ('d8', 'digitalrivers')
    >>> FlowDirection.from_dataset(
    ...     plain, routing="d8"
    ... ).access == plain.access
    True
    
Source code in src/digitalrivers/flow/direction.py
@classmethod
def from_dataset(
    cls,
    ds: Dataset,
    *,
    routing: str,
    encoding: str = "digitalrivers",
) -> FlowDirection:
    """Promote a plain `Dataset` into a `FlowDirection`.

    The source's access mode, `gdal_env` and `open_options` are carried onto
    the wrapper. Dropping them left a promoted file-backed raster unable to
    write its own metadata tags, and stripped the credentials a signed remote
    raster needs when pyramids reopens it.

    Args:
        ds: Dataset wrapping the flow-direction raster. Its raster handle is
            reused, not copied.
        routing: Routing scheme. Required keyword-only.
        encoding: Cell-value encoding convention.

    Returns:
        A `FlowDirection` over the same raster, with `ds`'s handle
        configuration.

    Examples:
        - Promote an in-memory raster and read the provenance back, and confirm the handle carries through:
            ```python
            >>> import numpy as np
            >>> from pyramids.dataset import Dataset, GeoReference
            >>> from digitalrivers import FlowDirection
            >>> plain = Dataset.from_array(
            ...     np.array([[0, 1], [2, 3]], dtype=np.int32),
            ...     geo_ref=GeoReference(
            ...         top_left_corner=(0.0, 0.0), cell_size=1.0, epsg=4326
            ...     ),
            ... )
            >>> wrapped = FlowDirection.from_dataset(plain, routing="d8")
            >>> wrapped.routing, wrapped.encoding
            ('d8', 'digitalrivers')
            >>> FlowDirection.from_dataset(
            ...     plain, routing="d8"
            ... ).access == plain.access
            True

            ```
    """
    return cls(
        ds.raster,
        ds.access,
        routing=routing,
        encoding=encoding,
        gdal_env=ds.gdal_env or None,
        open_options=ds.open_options or None,
    )

to_dataset() #

Drop the typed wrapper and return the underlying Dataset.

Symmetric with from_dataset: the access mode, gdal_env and open_options come back out with the raster, so a round trip does not silently downgrade a writable handle to a read-only one.

Returns:

Type Description
Dataset

A plain Dataset over the same raster and handle configuration.

Examples:

  • Unwrap and read the grid straight off the plain Dataset, and confirm the handle carries through:
    >>> import numpy as np
    >>> from pyramids.dataset import Dataset, GeoReference
    >>> from digitalrivers import FlowDirection
    >>> plain = Dataset.from_array(
    ...     np.array([[1, 2], [3, 4]], dtype=np.float32),
    ...     geo_ref=GeoReference(
    ...         top_left_corner=(0.0, 0.0), cell_size=1.0, epsg=4326
    ...     ),
    ... )
    >>> wrapped = FlowDirection.from_dataset(plain, routing="d8")
    >>> plain_again = wrapped.to_dataset()
    >>> plain_again.read_array().tolist()
    [[1.0, 2.0], [3.0, 4.0]]
    >>> wrapped.to_dataset().access == wrapped.access
    True
    
Source code in src/digitalrivers/flow/direction.py
def to_dataset(self) -> Dataset:
    """Drop the typed wrapper and return the underlying `Dataset`.

    Symmetric with `from_dataset`: the access mode, `gdal_env` and
    `open_options` come back out with the raster, so a round trip does not
    silently downgrade a writable handle to a read-only one.

    Returns:
        A plain `Dataset` over the same raster and handle configuration.

    Examples:
        - Unwrap and read the grid straight off the plain `Dataset`, and confirm the handle carries through:
            ```python
            >>> import numpy as np
            >>> from pyramids.dataset import Dataset, GeoReference
            >>> from digitalrivers import FlowDirection
            >>> plain = Dataset.from_array(
            ...     np.array([[1, 2], [3, 4]], dtype=np.float32),
            ...     geo_ref=GeoReference(
            ...         top_left_corner=(0.0, 0.0), cell_size=1.0, epsg=4326
            ...     ),
            ... )
            >>> wrapped = FlowDirection.from_dataset(plain, routing="d8")
            >>> plain_again = wrapped.to_dataset()
            >>> plain_again.read_array().tolist()
            [[1.0, 2.0], [3.0, 4.0]]
            >>> wrapped.to_dataset().access == wrapped.access
            True

            ```
    """
    return Dataset(
        self.raster,
        self.access,
        gdal_env=self.gdal_env or None,
        open_options=self.open_options or None,
    )

persist_metadata() #

Write routing and encoding to the underlying raster tags.

Stored under DR_CLASS / DR_ROUTING / DR_ENCODING GeoTIFF metadata keys so FlowDirection.open(path) can recover them.

Source code in src/digitalrivers/flow/direction.py
def persist_metadata(self) -> None:
    """Write `routing` and `encoding` to the underlying raster tags.

    Stored under `DR_CLASS` / `DR_ROUTING` / `DR_ENCODING` GeoTIFF
    metadata keys so `FlowDirection.open(path)` can recover them.
    """
    self.metadata = {
        META_CLASS: type(self).__name__,
        META_ROUTING: self.routing,
        META_ENCODING: self.encoding,
    }

open(path, *, routing=None, encoding=None, read_only=True, gdal_env=None, open_options=None) classmethod #

Open a FlowDirection GeoTIFF.

Resolution order for the routing/encoding tags:

  1. Explicit routing= / encoding= kwargs win unconditionally (caller knows what the file is).
  2. Otherwise, DR_ROUTING / DR_ENCODING metadata tags are used if present.
  3. Otherwise, raise ValueError. There is no silent fallback to "d8" — a D∞ raster on disk is float32 in [0, 2π] and reinterpreting it as int D8 codes silently corrupts every downstream computation.

Parameters:

Name Type Description Default
path str

Path to the GeoTIFF.

required
routing str | None

Explicit routing override. If None, falls back to the DR_ROUTING tag.

None
encoding str | None

Explicit encoding override. If None, falls back to the DR_ENCODING tag, then to "digitalrivers".

None
read_only bool

Open the file read-only (default). Pass False to get a writable handle — required before persist_metadata() can stamp the DR_* tags onto an existing file.

True
gdal_env dict[str, str] | None

GDAL config (cloud credentials, HTTP knobs) installed for the open and captured on the result, so pyramids' reopen paths re-authenticate. Default None.

None
open_options tuple[str, ...] | list[str] | None

GDAL open options forwarded to the driver and captured on the result. Default None.

None

Returns:

Type Description
FlowDirection

A FlowDirection wrapping the opened raster.

Raises:

Type Description
ValueError

If neither routing= nor a DR_ROUTING tag is available.

Source code in src/digitalrivers/flow/direction.py
@classmethod
def open(
    cls,
    path: str,
    *,
    routing: str | None = None,
    encoding: str | None = None,
    read_only: bool = True,
    gdal_env: dict[str, str] | None = None,
    open_options: tuple[str, ...] | list[str] | None = None,
) -> FlowDirection:
    """Open a `FlowDirection` GeoTIFF.

    Resolution order for the routing/encoding tags:

    1. Explicit `routing=` / `encoding=` kwargs win unconditionally
       (caller knows what the file is).
    2. Otherwise, `DR_ROUTING` / `DR_ENCODING` metadata tags are used
       if present.
    3. Otherwise, raise `ValueError`. There is no silent fallback to
       `"d8"` — a D∞ raster on disk is float32 in `[0, 2π]` and
       reinterpreting it as int D8 codes silently corrupts every
       downstream computation.

    Args:
        path: Path to the GeoTIFF.
        routing: Explicit routing override. If `None`, falls back to
            the `DR_ROUTING` tag.
        encoding: Explicit encoding override. If `None`, falls back to
            the `DR_ENCODING` tag, then to `"digitalrivers"`.
        read_only: Open the file read-only (default). Pass `False` to
            get a writable handle — required before `persist_metadata()`
            can stamp the `DR_*` tags onto an existing file.
        gdal_env: GDAL config (cloud credentials, HTTP knobs) installed
            for the open and captured on the result, so pyramids' reopen
            paths re-authenticate. Default `None`.
        open_options: GDAL open options forwarded to the driver and
            captured on the result. Default `None`.

    Returns:
        A `FlowDirection` wrapping the opened raster.

    Raises:
        ValueError: If neither `routing=` nor a `DR_ROUTING` tag is
            available.
    """
    ds = Dataset.read_file(
        path, read_only, gdal_env=gdal_env, open_options=open_options
    )
    md = ds.metadata or {}
    resolved_routing = routing or md.get(META_ROUTING)
    resolved_encoding = encoding or md.get(META_ENCODING) or "digitalrivers"
    if resolved_routing is None:
        raise ValueError(
            f"{path!r} carries no DR_ROUTING tag and no routing= was passed. "
            f"Pass routing= explicitly (one of {sorted(VALID_ROUTING)}) to "
            f"avoid silent misinterpretation of cell values."
        )
    return cls(
        ds.raster,
        ds.access,
        routing=resolved_routing,
        encoding=resolved_encoding,
        gdal_env=ds.gdal_env or None,
        open_options=ds.open_options or None,
    )

accumulate(weights=None, *, engine='auto', out_path=None, tile_size=2048, cache='evict', workers=1, scratch_dir=None, scheduler='threads', client=None) #

Run flow accumulation over this raster's routing scheme.

Implements a Kahn topological-sort sweep that handles all five routing schemes (D8, Rho8, D∞, MFD-Quinn, MFD-Holmgren) via a single algorithm, dispatched by self.routing.

Output semantics: out[cell] = sum of weights over strictly-upstream cells — the cell's own weight does not contribute to its own count. This matches the legacy DEM.flow_accumulation convention.

Parameters:

Name Type Description Default
weights Dataset | None

Per-cell weight raster (rainfall, runoff coefficient, whatever). Must align with this FlowDirection's shape. None means unit weights (cell-count accumulation).

None

Returns:

Type Description
Accumulation

Accumulation carrying this object's routing for provenance.

Out-of-core

engine="tiled" streams a Barnes-2017 tiled accumulation to out_path (D8/Rho8 only). engine="auto" (default) only switches to it when the raster is large enough to risk exhausting RAM.

Source code in src/digitalrivers/flow/direction.py
def accumulate(
    self,
    weights: Dataset | None = None,
    *,
    engine: str = "auto",
    out_path: str | None = None,
    tile_size: int | tuple[int, int] = 2048,
    cache: str = "evict",
    workers: int = 1,
    scratch_dir: str | None = None,
    scheduler: str = "threads",
    client=None,
) -> Accumulation:
    """Run flow accumulation over this raster's routing scheme.

    Implements a Kahn topological-sort sweep that handles all five routing
    schemes (D8, Rho8, D∞, MFD-Quinn, MFD-Holmgren) via a single algorithm,
    dispatched by `self.routing`.

    Output semantics: `out[cell] = sum of weights over strictly-upstream
    cells` — the cell's own weight does not contribute to its own count.
    This matches the legacy `DEM.flow_accumulation` convention.

    Args:
        weights: Per-cell weight raster (rainfall, runoff coefficient,
            whatever). Must align with this FlowDirection's shape. `None`
            means unit weights (cell-count accumulation).

    Returns:
        Accumulation carrying this object's `routing` for provenance.

    Out-of-core:
        `engine="tiled"` streams a Barnes-2017 tiled accumulation to `out_path` (D8/Rho8 only). `engine="auto"`
        (default) only switches to it when the raster is large enough to risk exhausting RAM.
    """
    from digitalrivers._outofcore.engine import (  # lazy
        require_out_path,
        resolve_engine,
    )

    resolved = resolve_engine(engine, self.rows, self.columns, k=6)
    if resolved == "tiled":
        require_out_path(engine, out_path)
        # lazy import: pulls the numba kernels only when the tiled path is actually used
        from digitalrivers._outofcore.accumulate import flow_accumulation_tiled

        tile_rows, tile_cols = (
            (tile_size, tile_size) if isinstance(tile_size, int) else tile_size
        )
        out = flow_accumulation_tiled(
            self,
            out_path,
            weights=weights,
            tile_rows=tile_rows,
            tile_cols=tile_cols,
            cache=cache,
            workers=workers,
            scratch_dir=scratch_dir,
            scheduler=scheduler,
            client=client,
        )
        from digitalrivers.flow.accumulation import Accumulation

        return Accumulation.from_dataset(out, routing=self.routing)

    from digitalrivers.flow.accumulation import Accumulation

    fd_arr = self.read_array()
    valid_mask = self._valid_mask_from_array(fd_arr)
    if weights is not None:
        w_arr = weights.read_array()
        if w_arr.shape != valid_mask.shape:
            raise ValueError(
                f"weights shape {w_arr.shape} does not match flow_direction "
                f"shape {valid_mask.shape}"
            )
    else:
        w_arr = None
    acc = _accumulate_array(fd_arr, self.routing, valid_mask, weights=w_arr)
    acc_f32 = acc.astype(np.float32, copy=False)
    plain = Dataset.from_array(
        acc_f32,
        geo_ref=GeoReference(geo=self.geotransform, epsg=self.epsg),
        no_data_value=self.default_no_data_value,
    )
    return Accumulation.from_dataset(plain, routing=self.routing)

upslope_flowpath_length() #

Return a per-cell raster of the longest upslope flow path.

For every cell in the raster, the returned value is the longest planimetric flow path from any upstream source to that cell — following D8 / Rho8 receivers, with cardinal steps contributing cell_size and diagonal steps contributing cell_size * sqrt(2). Source cells (no upstream neighbour pointing at them) hold 0.0.

Only single-direction routings (d8 / rho8) are supported.

Returns:

Type Description
Dataset

Dataset of float32 lengths in map units, aligned to this

Dataset

FlowDirection raster. Uses -9999.0 as the on-disk no-data

Dataset

sentinel.

Raises:

Type Description
ValueError

If self.routing is not single-direction.

Source code in src/digitalrivers/flow/direction.py
def upslope_flowpath_length(self) -> Dataset:
    """Return a per-cell raster of the longest upslope flow path.

    For every cell in the raster, the returned value is the longest
    planimetric flow path from any upstream source to that cell —
    following D8 / Rho8 receivers, with cardinal steps contributing
    `cell_size` and diagonal steps contributing `cell_size * sqrt(2)`.
    Source cells (no upstream neighbour pointing at them) hold `0.0`.

    Only single-direction routings (`d8` / `rho8`) are supported.

    Returns:
        `Dataset` of float32 lengths in map units, aligned to this
        `FlowDirection` raster. Uses `-9999.0` as the on-disk no-data
        sentinel.

    Raises:
        ValueError: If `self.routing` is not single-direction.
    """
    if self.routing not in ("d8", "rho8"):
        raise ValueError(
            f"upslope_flowpath_length supports single-direction routing "
            f"only; got {self.routing!r}"
        )
    fdir = self.read_array().astype(np.int32, copy=False)
    lengths = kahn_max_upslope_length(fdir, float(abs(self.geotransform[1])))
    return Dataset.from_array(
        lengths.astype(np.float32),
        geo_ref=GeoReference(geo=self.geotransform, epsg=self.epsg),
        no_data_value=-9999.0,
    )

isobasins(streams, accumulation, target_area_km2) #

Partition the catchment into sub-basins of approximately equal area.

Walks the stream network from heads to outlet via the accumulation raster. At every stream cell whose floor-divided accumulation quantile (accumulation // target_cells) is strictly greater than the maximum quantile of its stream-upstream neighbours, a virtual sub-basin outlet is placed. The final sub-basin labels are produced by first-claim-wins reverse-BFS watershed delineation on those seeds.

Parameters:

Name Type Description Default
streams

StreamRaster aligned to this flow-direction raster.

required
accumulation

Accumulation raster aligned to this flow-direction raster (units: cells).

required
target_area_km2 float

Target sub-basin area in km². Converted to target cell count via the dataset's cell size; must be positive.

required

Returns:

Type Description
WatershedRaster

WatershedRaster whose cells carry a 1..N sub-basin label

WatershedRaster

(or 0 for cells outside any sub-basin) and whose outlets

WatershedRaster

mapping carries {basin_id: (row, col)}.

Raises:

Type Description
ValueError

If routing is multi-direction, shapes mismatch, or target_area_km2 is not positive.

Source code in src/digitalrivers/flow/direction.py
def isobasins(
    self,
    streams,
    accumulation,
    target_area_km2: float,
) -> WatershedRaster:
    """Partition the catchment into sub-basins of approximately equal area.

    Walks the stream network from heads to outlet via the accumulation
    raster. At every stream cell whose floor-divided accumulation quantile
    (`accumulation // target_cells`) is strictly greater than the maximum
    quantile of its stream-upstream neighbours, a virtual sub-basin
    outlet is placed. The final sub-basin labels are produced by
    first-claim-wins reverse-BFS watershed delineation on those seeds.

    Args:
        streams: `StreamRaster` aligned to this flow-direction raster.
        accumulation: `Accumulation` raster aligned to this flow-direction
            raster (units: cells).
        target_area_km2: Target sub-basin area in km². Converted to
            target cell count via the dataset's cell size; must be
            positive.

    Returns:
        `WatershedRaster` whose cells carry a `1..N` sub-basin label
        (or 0 for cells outside any sub-basin) and whose `outlets`
        mapping carries `{basin_id: (row, col)}`.

    Raises:
        ValueError: If routing is multi-direction, shapes mismatch, or
            `target_area_km2` is not positive.
    """
    from digitalrivers.watershed.raster import WatershedRaster

    if self.routing not in ("d8", "rho8"):
        raise ValueError(
            f"isobasins supports single-direction routing only; got "
            f"{self.routing!r}"
        )
    if target_area_km2 <= 0:
        raise ValueError(
            f"target_area_km2 must be positive; got {target_area_km2!r}"
        )

    sm = streams.read_array().astype(bool, copy=False)
    acc_arr = accumulation.read_array().astype(np.int64, copy=False)
    fdir = self.read_array().astype(np.int32, copy=False)
    if sm.shape != fdir.shape or acc_arr.shape != fdir.shape:
        raise ValueError(
            f"shape mismatch: fdir={fdir.shape}, streams={sm.shape}, "
            f"accumulation={acc_arr.shape}"
        )

    gt = self.geotransform
    cell_area_km2 = abs(gt[1] * gt[5]) / 1.0e6
    target_cells = max(1, int(round(target_area_km2 / cell_area_km2)))

    # Quantile bucket of each stream cell, -1 elsewhere.
    quantile = np.where(sm, acc_arr // target_cells, -1).astype(np.int64)

    # For each stream cell, find the max quantile across its stream-upstream
    # neighbours. A cell with strictly larger quantile than that max marks a
    # bucket-boundary — place a seed there.
    rows, cols = sm.shape
    up_max = np.full((rows, cols), -1, dtype=np.int64)
    for k in range(8):
        dr = int(_DIR_DR[k])
        dc = int(_DIR_DC[k])
        src_r = slice(max(0, dr), min(rows, rows + dr))
        src_c = slice(max(0, dc), min(cols, cols + dc))
        dst_r = slice(max(0, -dr), min(rows, rows - dr))
        dst_c = slice(max(0, -dc), min(cols, cols - dc))
        sm_src = sm[src_r, src_c]
        fd_src = fdir[src_r, src_c]
        inflow = sm_src & (fd_src == int(_INV_DIR[k])) & sm[dst_r, dst_c]
        cand = np.where(inflow, quantile[src_r, src_c], -1).astype(np.int64)
        block = up_max[dst_r, dst_c]
        np.maximum(block, cand, out=block)
        up_max[dst_r, dst_c] = block

    seed_mask = sm & (quantile > up_max)
    seed_rcs: list[tuple[int, int]] = [
        (int(r), int(c)) for r, c in zip(*np.nonzero(seed_mask))
    ]
    if not seed_rcs:
        # Catchment smaller than target → fall back to a single basin at
        # the outlet (consistent with WBT's behaviour at extreme inputs).
        outlets = _stream_outlets(sm, fdir)
        if not outlets:
            # No stream cells at all — emit an all-zero basin raster.
            labels = np.zeros((rows, cols), dtype=np.int32)
            plain = Dataset.from_array(
                labels,
                geo_ref=GeoReference(geo=self.geotransform, epsg=self.epsg),
                no_data_value=0,
            )
            return WatershedRaster.from_dataset(
                plain,
                routing=self.routing,
                outlets={},
            )
        seed_rcs = [outlets[0]]

    basin_ids = list(range(1, len(seed_rcs) + 1))
    labels = watershed_d8(
        fdir,
        seed_rcs,
        basin_ids,
        require_unique_basins=True,
    )
    plain = Dataset.from_array(
        labels.astype(np.int32),
        geo_ref=GeoReference(geo=self.geotransform, epsg=self.epsg),
        no_data_value=0,
    )
    outlets_dict = dict(zip(basin_ids, seed_rcs))
    return WatershedRaster.from_dataset(
        plain,
        routing=self.routing,
        outlets=outlets_dict,
    )

basins(*, min_area_cells=None, min_area_km2=None, merge_small='drop') #

Partition the entire DEM into basins, one label per terminal outlet.

Detects every cell whose flow direction is the no-data sentinel (cells with no defined downstream — either at the data envelope or at internal sinks that survived the fill phase) and seeds a reverse BFS from each. The result labels every valid cell with the ID of the outlet it drains to.

Parameters:

Name Type Description Default
min_area_cells int | None

Optional minimum basin area in cells; basins smaller than this are post-processed via merge_small.

None
min_area_km2 float | None

Same threshold expressed in map km². Mutually exclusive with min_area_cells.

None
merge_small str

"drop" (default) sets undersized basins to 0; "merge_to_neighbour" dilates the small basin's mask by one cell, collects the labels of every basin it touches, and relabels the small basin with the largest of those 8-neighbour labels. Returns 0 for basins whose entire 8-neighbourhood is either background or other small basins (no qualifying survivor).

'drop'

Returns:

Type Description
WatershedRaster

class:WatershedRaster tagged with this FlowDirection's

WatershedRaster

routing. The outlets GeoDataFrame has one row per surviving

WatershedRaster

basin with the outlet row/col/x/y and

WatershedRaster

cell_count.

Raises:

Type Description
ValueError

If both area kwargs are supplied or merge_small is unknown.

Source code in src/digitalrivers/flow/direction.py
def basins(
    self,
    *,
    min_area_cells: int | None = None,
    min_area_km2: float | None = None,
    merge_small: str = "drop",
) -> WatershedRaster:
    """Partition the entire DEM into basins, one label per terminal outlet.

    Detects every cell whose flow direction is the no-data sentinel
    (cells with no defined downstream — either at the data envelope or
    at internal sinks that survived the fill phase) and seeds a reverse
    BFS from each. The result labels every valid cell with the ID of
    the outlet it drains to.

    Args:
        min_area_cells: Optional minimum basin area in cells; basins
            smaller than this are post-processed via `merge_small`.
        min_area_km2: Same threshold expressed in map km². Mutually
            exclusive with `min_area_cells`.
        merge_small: `"drop"` (default) sets undersized basins to 0;
            `"merge_to_neighbour"` dilates the small basin's mask by
            one cell, collects the labels of every basin it touches,
            and relabels the small basin with the largest of those
            8-neighbour labels. Returns `0` for basins whose entire
            8-neighbourhood is either background or other small
            basins (no qualifying survivor).

    Returns:
        :class:`WatershedRaster` tagged with this FlowDirection's
        routing. The `outlets` GeoDataFrame has one row per surviving
        basin with the outlet `row`/`col`/`x`/`y` and
        `cell_count`.

    Raises:
        ValueError: If both area kwargs are supplied or
            `merge_small` is unknown.
    """
    from digitalrivers.watershed.raster import WatershedRaster

    if self.routing not in ("d8", "rho8"):
        raise ValueError(
            f"basins currently supports single-direction routing only; "
            f"got {self.routing!r}"
        )
    if min_area_cells is not None and min_area_km2 is not None:
        raise ValueError("Pass at most one of min_area_cells / min_area_km2")
    if merge_small not in ("drop", "merge_to_neighbour"):
        raise ValueError(
            f"merge_small must be 'drop' or 'merge_to_neighbour'; "
            f"got {merge_small!r}"
        )

    fdir = self.read_array().astype(np.int32, copy=False)
    rows, cols = fdir.shape
    gt = self.geotransform
    x0, dx, _, y0, _, dy = gt

    no_val = self.no_data_value[0] if self.no_data_value else None
    # Outlet = cell whose direction code is not in [0, 7] (sink) but the
    # cell itself is in the data envelope.
    if no_val is None:
        no_val = -9999
    is_outlet = (fdir < 0) | (fdir > 7)

    if min_area_km2 is not None:
        cell_area_m2 = abs(dx * dy)
        min_area_cells = int(round(min_area_km2 * 1.0e6 / cell_area_m2))

    seeds: list[tuple[int, int]] = []
    basin_ids: list[int] = []
    outlet_records: list[dict] = []
    bid = 1
    for r, c in zip(*np.nonzero(is_outlet)):
        r = int(r)
        c = int(c)
        seeds.append((r, c))
        basin_ids.append(bid)
        outlet_records.append(
            {
                "basin_id": bid,
                "row": r,
                "col": c,
                "x": x0 + (c + 0.5) * dx,
                "y": y0 + (r + 0.5) * dy,
            }
        )
        bid += 1

    basins = watershed_d8(fdir, seeds, basin_ids, require_unique_basins=True)

    # Area filter.
    if min_area_cells is not None and min_area_cells > 1:
        unique, counts = np.unique(basins, return_counts=True)
        sizes = dict(zip(unique.tolist(), counts.tolist()))
        small_ids = {b for b, n in sizes.items() if b != 0 and n < min_area_cells}
        if merge_small == "drop":
            for b in small_ids:
                basins[basins == b] = 0
        else:  # merge_to_neighbour
            # 8-connected adjacency: shift the small-basin mask in each of
            # the 8 directions and collect any non-self, non-small basin
            # labels that touch its boundary. Pick the largest of those.
            rows, cols = basins.shape
            for b in small_ids:
                mask = basins == b
                if not mask.any():
                    continue
                # Build the 1-cell-dilated border of the small basin.
                border_labels: set[int] = set()
                for dr in (-1, 0, 1):
                    for dc in (-1, 0, 1):
                        if dr == 0 and dc == 0:
                            continue
                        r0, r1 = max(0, dr), rows + min(0, dr)
                        c0, c1 = max(0, dc), cols + min(0, dc)
                        src_r0, src_r1 = max(0, -dr), rows + min(0, -dr)
                        src_c0, src_c1 = max(0, -dc), cols + min(0, -dc)
                        mask_dst = mask[r0:r1, c0:c1]
                        labels_src = basins[src_r0:src_r1, src_c0:src_c1]
                        touched = labels_src[mask_dst]
                        border_labels.update(int(v) for v in np.unique(touched))
                # Drop self, background, and other small basins.
                candidates = [
                    lbl
                    for lbl in border_labels
                    if lbl != 0 and lbl != b and lbl not in small_ids
                ]
                if not candidates:
                    neighbour_id = 0
                else:
                    neighbour_id = max(candidates, key=lambda lbl: sizes[lbl])
                basins[mask] = neighbour_id
        # Trim outlet records.
        outlet_records = [
            rec for rec in outlet_records if rec["basin_id"] not in small_ids
        ]
        for rec in outlet_records:
            rec["cell_count"] = int(sizes.get(rec["basin_id"], 0))
    else:
        unique, counts = np.unique(basins, return_counts=True)
        sizes = dict(zip(unique.tolist(), counts.tolist()))
        for rec in outlet_records:
            rec["cell_count"] = int(sizes.get(rec["basin_id"], 0))

    plain = Dataset.from_array(
        basins,
        geo_ref=GeoReference(geo=self.geotransform, epsg=self.epsg),
        no_data_value=0,
    )

    outlets_gdf = gpd.GeoDataFrame(
        outlet_records,
        geometry=[Point(rec["x"], rec["y"]) for rec in outlet_records],
        crs=self.epsg,
    )
    return WatershedRaster.from_dataset(
        plain,
        routing=self.routing,
        outlets=outlets_gdf,
    )

watershed(pour_points, require_unique_basins=False) #

Delineate the upstream watershed of each pour point.

Reverse-BFS from every pour-point cell, labelling every contributing cell with the pour point's 1-based basin ID. Multi-point inputs produce a labelled raster (one ID per pour point).

Parameters:

Name Type Description Default
pour_points

GeoDataFrame of Point geometries — one row per desired basin. Points outside the raster envelope are skipped with a NaN entry in the returned outlets GeoDataFrame.

required
require_unique_basins bool

If False (default), inner pour points overwrite the outer basin's cells along shared upstream paths — the outer basin contains a hole around the inner basin. If True, the first seed to claim a cell keeps it; the outer basin contains no inner-basin cells.

False

Returns:

Type Description
WatershedRaster

class:WatershedRaster tagged with this FlowDirection's routing.

WatershedRaster

The outlets attribute is a GeoDataFrame parallel to the input

WatershedRaster

pour_points.

Source code in src/digitalrivers/flow/direction.py
def watershed(
    self,
    pour_points,
    require_unique_basins: bool = False,
) -> WatershedRaster:
    """Delineate the upstream watershed of each pour point.

    Reverse-BFS from every pour-point cell, labelling every contributing
    cell with the pour point's 1-based basin ID. Multi-point inputs
    produce a labelled raster (one ID per pour point).

    Args:
        pour_points: `GeoDataFrame` of Point geometries — one row per
            desired basin. Points outside the raster envelope are skipped
            with a NaN entry in the returned `outlets` GeoDataFrame.
        require_unique_basins: If False (default), inner pour points
            overwrite the outer basin's cells along shared upstream
            paths — the outer basin contains a hole around the inner
            basin. If True, the first seed to claim a cell keeps it; the
            outer basin contains no inner-basin cells.

    Returns:
        :class:`WatershedRaster` tagged with this FlowDirection's routing.
        The `outlets` attribute is a GeoDataFrame parallel to the input
        `pour_points`.
    """
    from digitalrivers.watershed.raster import WatershedRaster

    if self.routing not in ("d8", "rho8"):
        raise ValueError(
            f"watershed currently supports single-direction routing only; "
            f"got {self.routing!r}"
        )

    target_epsg = self.epsg
    if (
        getattr(pour_points, "crs", None) is not None
        and target_epsg is not None
        and pour_points.crs.to_epsg() != target_epsg
    ):
        pour_points = pour_points.to_crs(target_epsg)

    fdir = self.read_array().astype(np.int32, copy=False)
    rows, cols = fdir.shape
    gt = self.geotransform
    x0, dx, _, y0, _, dy = gt

    seeds: list[tuple[int, int]] = []
    basin_ids: list[int] = []
    outlet_records: list[dict] = []
    for i, pt in enumerate(pour_points.geometry):
        px, py = float(pt.x), float(pt.y)
        col = int((px - x0) / dx)
        row = int((py - y0) / dy)
        bid = i + 1
        if 0 <= row < rows and 0 <= col < cols:
            seeds.append((row, col))
            basin_ids.append(bid)
            outlet_records.append(
                {
                    "basin_id": bid,
                    "row": row,
                    "col": col,
                    "x": x0 + (col + 0.5) * dx,
                    "y": y0 + (row + 0.5) * dy,
                }
            )
        else:
            outlet_records.append(
                {
                    "basin_id": bid,
                    "row": -1,
                    "col": -1,
                    "x": float("nan"),
                    "y": float("nan"),
                }
            )

    basins = watershed_d8(
        fdir, seeds, basin_ids, require_unique_basins=require_unique_basins
    )
    plain = Dataset.from_array(
        basins,
        geo_ref=GeoReference(geo=self.geotransform, epsg=self.epsg),
        no_data_value=0,
    )

    outlets_gdf = gpd.GeoDataFrame(
        outlet_records,
        geometry=[
            Point(rec["x"], rec["y"]) if not (rec["row"] < 0) else None
            for rec in outlet_records
        ],
        crs=target_epsg,
    )
    return WatershedRaster.from_dataset(
        plain,
        routing=self.routing,
        outlets=outlets_gdf,
    )

__repr__() #

Return a one-line summary of the raster.

Names its shape, routing scheme and cell-value encoding.

Both tags are shown, because a direction grid is only interpretable given the pair: the same cell value means different neighbours under different encodings.

Returns:

Type Description
str

A string of the form <FlowDirection rows=R cols=C routing='...' encoding='...'>.

Source code in src/digitalrivers/flow/direction.py
def __repr__(self) -> str:
    """Return a one-line summary of the raster.

    Names its shape, routing scheme and cell-value encoding.

    Both tags are shown, because a direction grid is only interpretable given the
    pair: the same cell value means different neighbours under different
    encodings.

    Returns:
        A string of the form `<FlowDirection rows=R cols=C routing='...' encoding='...'>`.
    """
    return (
        f"<FlowDirection rows={self.rows} cols={self.columns} "
        f"routing={self.routing!r} encoding={self.encoding!r}>"
    )

subbasins_pfafstetter(accumulation, streams, level=1, encoding='packed_int') #

Compute Pfafstetter (Verdin & Verdin 1999) hierarchical codes.

Single-basin level-1 implementation: identifies the main stem (the path with the largest downstream-accumulation), finds the four tributaries with the largest accumulation at confluence with the main stem, and labels every cell with one of the nine Pfafstetter codes: 2/4/6/8 for the four main tributaries (downstream order) and 1/3/5/7/9 for the inter-basin segments between them.

The multi-level recursive descent (level > 1) and the HydroBASINS iso-basin pre-split are out of scope for this initial implementation.

Parameters:

Name Type Description Default
accumulation

Accumulation raster aligned to this FlowDirection. Used for ranking tributaries by area.

required
streams

StreamRaster aligned to this FlowDirection. Defines the channel network the Pfafstetter scheme walks.

required
level int

Hierarchy depth. Only level=1 is implemented; higher levels raise NotImplementedError.

1
encoding str

"packed_int" (default) writes codes as int32 cell values. "string" is not yet implemented.

'packed_int'

Returns:

Type Description
WatershedRaster

class:WatershedRaster with int32 Pfafstetter codes. Level-1

WatershedRaster

codes are in [1, 9]; level-N codes are N-digit concatenations

WatershedRaster

parent * 10 + child (e.g. level-2 ⇒ [11, 99], level-3 ⇒

WatershedRaster

[111, 999]). Cells outside the basin envelope are 0.

Raises:

Type Description
ValueError

If level < 1 or non-D8 routing is used or an argument has the wrong type.

NotImplementedError

If encoding != "packed_int".

Examples:

  • Level-1 coding on a small east-flowing DEM yields codes within the canonical [1, 9] Pfafstetter range:

    import numpy as np from pyramids.dataset import Dataset, GeoReference from digitalrivers import DEM z = np.array( ... [ ... [9, 9, 9, 9, 9, 9], ... [9, 5, 4, 3, 2, 1], ... [9, 9, 9, 9, 9, 9], ... ], ... dtype=np.float32, ... ) ds = Dataset.from_array( ... z, ... geo_ref=GeoReference( ... top_left_corner=(0.0, 0.0), ... cell_size=1.0, ... epsg=4326, ... ), ... no_data_value=-9999.0, ... ) dem = DEM(ds.raster) fd = dem.flow_direction(method="d8") acc = fd.accumulate() sr = acc.streams(threshold=1) ws = fd.subbasins_pfafstetter(acc, sr, level=1) arr = ws.read_array() codes = sorted({int(v) for v in np.unique(arr) if v != 0}) bool(set(codes).issubset(set(range(1, 10)))) True

  • Level-2 coding produces two-digit parent*10 + child codes (P16 multi-level backfill):

    import numpy as np from pyramids.dataset import Dataset, GeoReference from digitalrivers import DEM z = np.array( ... [ ... [9, 9, 9, 9, 9, 9], ... [9, 5, 4, 3, 2, 1], ... [9, 9, 9, 9, 9, 9], ... ], ... dtype=np.float32, ... ) ds = Dataset.from_array( ... z, ... geo_ref=GeoReference( ... top_left_corner=(0.0, 0.0), ... cell_size=1.0, ... epsg=4326, ... ), ... no_data_value=-9999.0, ... ) dem = DEM(ds.raster) fd = dem.flow_direction(method="d8") acc = fd.accumulate() sr = acc.streams(threshold=1) ws = fd.subbasins_pfafstetter(acc, sr, level=2) arr = ws.read_array() codes = sorted({int(v) for v in np.unique(arr) if v != 0}) bool(all(11 <= c <= 99 for c in codes)) True

  • level < 1 is rejected:

    import numpy as np from pyramids.dataset import Dataset, GeoReference from digitalrivers import DEM z = np.array( ... [[9, 9, 9], [9, 5, 9], [9, 9, 9]], dtype=np.float32 ... ) ds = Dataset.from_array( ... z, ... geo_ref=GeoReference( ... top_left_corner=(0.0, 0.0), ... cell_size=1.0, ... epsg=4326, ... ), ... no_data_value=-9999.0, ... ) dem = DEM(ds.raster) fd = dem.flow_direction(method="d8") acc = fd.accumulate() sr = acc.streams(threshold=1) fd.subbasins_pfafstetter(acc, sr, level=0) Traceback (most recent call last): ... ValueError: level must be >= 1; got 0

See Also

FlowDirection.basins: terminal-outlet partitioning of the DEM. FlowDirection.accumulate: upstream-area accumulation needed for tributary ranking.

Source code in src/digitalrivers/flow/pfafstetter.py
def subbasins_pfafstetter(
    self,
    accumulation,
    streams,
    level: int = 1,
    encoding: str = "packed_int",
) -> WatershedRaster:
    """Compute Pfafstetter (Verdin & Verdin 1999) hierarchical codes.

    Single-basin level-1 implementation: identifies the main stem (the
    path with the largest downstream-accumulation), finds the four
    tributaries with the largest accumulation at confluence with the main
    stem, and labels every cell with one of the nine Pfafstetter codes:
    `2/4/6/8` for the four main tributaries (downstream order) and
    `1/3/5/7/9` for the inter-basin segments between them.

    The multi-level recursive descent (`level > 1`) and the HydroBASINS
    iso-basin pre-split are out of scope for this initial implementation.

    Args:
        accumulation: `Accumulation` raster aligned to this
            FlowDirection. Used for ranking tributaries by area.
        streams: `StreamRaster` aligned to this FlowDirection. Defines
            the channel network the Pfafstetter scheme walks.
        level: Hierarchy depth. Only `level=1` is implemented; higher
            levels raise `NotImplementedError`.
        encoding: `"packed_int"` (default) writes codes as int32 cell
            values. `"string"` is not yet implemented.

    Returns:
        :class:`WatershedRaster` with int32 Pfafstetter codes. Level-1
        codes are in `[1, 9]`; level-N codes are N-digit concatenations
        `parent * 10 + child` (e.g. level-2 ⇒ `[11, 99]`, level-3 ⇒
        `[111, 999]`). Cells outside the basin envelope are 0.

    Raises:
        ValueError: If `level < 1` or non-D8 routing is used or an
            argument has the wrong type.
        NotImplementedError: If `encoding != "packed_int"`.

    Examples:
        - Level-1 coding on a small east-flowing DEM yields codes within
          the canonical `[1, 9]` Pfafstetter range:

            >>> import numpy as np
            >>> from pyramids.dataset import Dataset, GeoReference
            >>> from digitalrivers import DEM
            >>> z = np.array(
            ...     [
            ...         [9, 9, 9, 9, 9, 9],
            ...         [9, 5, 4, 3, 2, 1],
            ...         [9, 9, 9, 9, 9, 9],
            ...     ],
            ...     dtype=np.float32,
            ... )
            >>> ds = Dataset.from_array(
            ...     z,
            ...     geo_ref=GeoReference(
            ...         top_left_corner=(0.0, 0.0),
            ...         cell_size=1.0,
            ...         epsg=4326,
            ...     ),
            ...     no_data_value=-9999.0,
            ... )
            >>> dem = DEM(ds.raster)
            >>> fd = dem.flow_direction(method="d8")
            >>> acc = fd.accumulate()
            >>> sr = acc.streams(threshold=1)
            >>> ws = fd.subbasins_pfafstetter(acc, sr, level=1)
            >>> arr = ws.read_array()
            >>> codes = sorted({int(v) for v in np.unique(arr) if v != 0})
            >>> bool(set(codes).issubset(set(range(1, 10))))
            True

        - Level-2 coding produces two-digit `parent*10 + child` codes
          (P16 multi-level backfill):

            >>> import numpy as np
            >>> from pyramids.dataset import Dataset, GeoReference
            >>> from digitalrivers import DEM
            >>> z = np.array(
            ...     [
            ...         [9, 9, 9, 9, 9, 9],
            ...         [9, 5, 4, 3, 2, 1],
            ...         [9, 9, 9, 9, 9, 9],
            ...     ],
            ...     dtype=np.float32,
            ... )
            >>> ds = Dataset.from_array(
            ...     z,
            ...     geo_ref=GeoReference(
            ...         top_left_corner=(0.0, 0.0),
            ...         cell_size=1.0,
            ...         epsg=4326,
            ...     ),
            ...     no_data_value=-9999.0,
            ... )
            >>> dem = DEM(ds.raster)
            >>> fd = dem.flow_direction(method="d8")
            >>> acc = fd.accumulate()
            >>> sr = acc.streams(threshold=1)
            >>> ws = fd.subbasins_pfafstetter(acc, sr, level=2)
            >>> arr = ws.read_array()
            >>> codes = sorted({int(v) for v in np.unique(arr) if v != 0})
            >>> bool(all(11 <= c <= 99 for c in codes))
            True

        - `level < 1` is rejected:

            >>> import numpy as np
            >>> from pyramids.dataset import Dataset, GeoReference
            >>> from digitalrivers import DEM
            >>> z = np.array(
            ...     [[9, 9, 9], [9, 5, 9], [9, 9, 9]], dtype=np.float32
            ... )
            >>> ds = Dataset.from_array(
            ...     z,
            ...     geo_ref=GeoReference(
            ...         top_left_corner=(0.0, 0.0),
            ...         cell_size=1.0,
            ...         epsg=4326,
            ...     ),
            ...     no_data_value=-9999.0,
            ... )
            >>> dem = DEM(ds.raster)
            >>> fd = dem.flow_direction(method="d8")
            >>> acc = fd.accumulate()
            >>> sr = acc.streams(threshold=1)
            >>> fd.subbasins_pfafstetter(acc, sr, level=0)
            Traceback (most recent call last):
                ...
            ValueError: level must be >= 1; got 0

    See Also:
        FlowDirection.basins: terminal-outlet partitioning of the DEM.
        FlowDirection.accumulate: upstream-area accumulation needed for
            tributary ranking.
    """
    from digitalrivers.flow.accumulation import Accumulation
    from digitalrivers.streams.raster import StreamRaster
    from digitalrivers.watershed.raster import WatershedRaster

    if level < 1:
        raise ValueError(f"level must be >= 1; got {level}")
    if encoding != "packed_int":
        raise NotImplementedError(
            f"encoding={encoding!r} not yet implemented " f"(only 'packed_int')"
        )
    if self.routing not in ("d8", "rho8"):
        raise ValueError(
            f"subbasins_pfafstetter currently supports single-direction "
            f"routing only; got {self.routing!r}"
        )
    if not isinstance(accumulation, Accumulation):
        raise ValueError("accumulation must be an Accumulation instance")
    if not isinstance(streams, StreamRaster):
        raise ValueError("streams must be a StreamRaster instance")

    fdir = self.read_array().astype(np.int32, copy=False)
    acc = accumulation.read_array().astype(np.float64, copy=False)
    stream_mask = streams.read_array().astype(bool, copy=False)
    if not (fdir.shape == acc.shape == stream_mask.shape):
        raise ValueError(
            f"Shape mismatch: fdir={fdir.shape}, "
            f"accumulation={acc.shape}, streams={stream_mask.shape}"
        )
    out = self._pfafstetter_kernel(
        fdir=fdir,
        acc=acc,
        stream_mask=stream_mask,
        basin_mask=None,
        level=level,
    )
    plain = Dataset.from_array(
        out,
        geo_ref=GeoReference(geo=self.geotransform, epsg=self.epsg),
        no_data_value=0,
    )
    ids = sorted({int(v) for v in np.unique(out) if v != 0})
    # Per-basin outlet = the cell with the highest accumulation in that
    # basin. Locate it via masked-argmax so the resulting GeoDataFrame
    # carries real coordinates rather than placeholders.
    x0, dx, _, y0, _, dy = self.geotransform
    xs: list[float] = []
    ys: list[float] = []
    for basin_id in ids:
        basin_acc = np.where(out == basin_id, acc, -np.inf)
        idx = np.unravel_index(int(np.argmax(basin_acc)), basin_acc.shape)
        xs.append(float(x0 + (int(idx[1]) + 0.5) * dx))
        ys.append(float(y0 + (int(idx[0]) + 0.5) * dy))
    outlets_gdf = gpd.GeoDataFrame(
        {"basin_id": ids},
        geometry=gpd.points_from_xy(xs, ys),
        crs=self.epsg,
    )
    return WatershedRaster.from_dataset(
        plain,
        routing=self.routing,
        outlets=outlets_gdf,
    )

upscale_ihu(scale_factor, accumulation, dem, max_iter=20, report=False) #

Iterative Hydrography Upscaling (Eilander 2021).

The state-of-the-art D8 upscaling method that builds an initial coarse network with COTAT-style outlet selection and then refines boundary mismatches by swapping outlets between adjacent coarse cells until convergence.

v1 status: scale_factor=1 is a no-op (passes through the input unchanged). All other scale_factor values raise NotImplementedError. The roadmap recommends vendoring pyflwdir as the first-release backend; a native swap-search implementation is deferred to Phase 4.

Parameters:

Name Type Description Default
scale_factor int

Integer aggregation factor (>= 1).

required
accumulation

Accumulation aligned to this FlowDirection.

required
dem

DEM aligned to this FlowDirection.

required
max_iter int

Maximum refinement iterations.

20
report bool

When True, the third return slot carries Eilander 2021 validation metrics (area_error_pct, hit_rate, network_shift_km). Currently always returns an empty dict.

False

Returns:

Type Description
tuple

Tuple (upscaled_dem, upscaled_fdir, metrics).

Raises:

Type Description
NotImplementedError

For scale_factor > 1 — the iterative core is deferred.

Source code in src/digitalrivers/flow/upscale.py
def upscale_ihu(
    self,
    scale_factor: int,
    accumulation,
    dem,
    max_iter: int = 20,
    report: bool = False,
) -> tuple:
    """Iterative Hydrography Upscaling (Eilander 2021).

    The state-of-the-art D8 upscaling method that builds an initial
    coarse network with COTAT-style outlet selection and then refines
    boundary mismatches by swapping outlets between adjacent coarse
    cells until convergence.

    v1 status: `scale_factor=1` is a no-op (passes through the input
    unchanged). All other `scale_factor` values raise
    `NotImplementedError`. The roadmap recommends vendoring pyflwdir
    as the first-release backend; a native swap-search implementation
    is deferred to Phase 4.

    Args:
        scale_factor: Integer aggregation factor (>= 1).
        accumulation: `Accumulation` aligned to this FlowDirection.
        dem: `DEM` aligned to this FlowDirection.
        max_iter: Maximum refinement iterations.
        report: When True, the third return slot carries Eilander 2021
            validation metrics (`area_error_pct`, `hit_rate`,
            `network_shift_km`). Currently always returns an empty
            dict.

    Returns:
        Tuple `(upscaled_dem, upscaled_fdir, metrics)`.

    Raises:
        NotImplementedError: For `scale_factor > 1` — the iterative
            core is deferred.
    """
    if scale_factor < 1:
        raise ValueError(f"scale_factor must be >= 1; got {scale_factor}")
    if scale_factor == 1:
        up_dem, up_fdir = self.upscale(
            scale_factor=1,
            method="cotat",
            accumulation=accumulation,
            dem=dem,
        )
        return up_dem, up_fdir, {}

    fdir_arr = self.read_array().astype(np.int32, copy=False)
    acc_arr = accumulation.read_array().astype(np.float64, copy=False)
    if fdir_arr.shape != acc_arr.shape:
        raise ValueError(
            f"accumulation shape {acc_arr.shape} != flow_direction "
            f"shape {fdir_arr.shape}"
        )

    coarse_fdir, metrics, outlets = ihu_upscale(
        fdir_arr,
        acc_arr,
        scale_factor,
        max_iter=max_iter,
    )
    # Replace -1 with the dataset no-data sentinel for on-disk consistency.
    coarse_fdir = np.where(
        coarse_fdir < 0,
        np.int32(Dataset.default_no_data_value),
        coarse_fdir,
    )

    gt = self.geotransform
    coarse_gt = (
        gt[0],
        gt[1] * scale_factor,
        gt[2],
        gt[3],
        gt[4],
        gt[5] * scale_factor,
    )
    plain_fdir = Dataset.from_array(
        coarse_fdir,
        geo_ref=GeoReference(geo=coarse_gt, epsg=self.epsg),
        no_data_value=Dataset.default_no_data_value,
    )
    upscaled_fdir = _flow_direction_cls().from_dataset(
        plain_fdir,
        routing="d8",
        encoding=self.encoding,
    )

    upscaled_dem = None
    if dem is not None:
        from digitalrivers.dem import DEM as _DEM

        out_rows = fdir_arr.shape[0] // scale_factor
        out_cols = fdir_arr.shape[1] // scale_factor
        coarse_z = np.full(
            (out_rows, out_cols),
            Dataset.default_no_data_value,
            dtype=np.float32,
        )
        z_arr = dem.read_array().astype(np.float64, copy=False)
        for (br, bc), out in outlets.items():
            fr = int(out[1])
            fc = int(out[2])
            coarse_z[br, bc] = _pick_coarse_elev(z_arr, fr, fc)
        plain_dem = Dataset.from_array(
            coarse_z,
            geo_ref=GeoReference(geo=coarse_gt, epsg=self.epsg),
            no_data_value=Dataset.default_no_data_value,
        )
        upscaled_dem = _DEM(plain_dem.raster)

    return upscaled_dem, upscaled_fdir, (metrics if report else {})

upscale(scale_factor, method='cotat', accumulation=None, dem=None, area_threshold_cells=None) #

Upscale the flow-direction raster by an integer factor.

Three classical methods are specified by P18; this initial implementation ships "cotat" (Reed 2003 — Cell Outlet Tracing with an Area Threshold). EAM (Olivera 2002) and DMM raise NotImplementedError pending a follow-up.

COTAT algorithm (per coarse cell):

  1. Find the fine cell with the highest accumulation in the scale_factor × scale_factor block. This is the coarse cell's outlet.
  2. Trace downstream from that fine outlet along the fine fdir until leaving the block.
  3. The direction from the source coarse cell to the destination coarse cell becomes the coarse cell's D8 flow direction.

Parameters:

Name Type Description Default
scale_factor int

Integer aggregation factor (>= 1).

required
method str

"cotat" (default); "eam" / "dmm" raise NotImplementedError.

'cotat'
accumulation

Accumulation aligned to this FlowDirection; required for COTAT (used to pick the per-block outlet).

None
dem

Optional DEM aligned to this FlowDirection — when supplied, the returned upscaled_dem reports the elevation of each coarse cell's outlet (Reed 2003).

None
area_threshold_cells int | None

Reserved for COTAT+ branch-cutoff refinement; currently ignored.

None

Returns:

Type Description
tuple

Tuple (upscaled_dem, upscaled_fdir). If dem is

tuple

None the first element is None and the caller is

tuple

expected to recompute elevations from a coarsened DEM.

Raises:

Type Description
NotImplementedError

For methods other than "cotat".

ValueError

If scale_factor < 1 or accumulation is missing for COTAT.

Source code in src/digitalrivers/flow/upscale.py
def upscale(
    self,
    scale_factor: int,
    method: str = "cotat",
    accumulation=None,
    dem=None,
    area_threshold_cells: int | None = None,
) -> tuple:
    """Upscale the flow-direction raster by an integer factor.

    Three classical methods are specified by P18; this initial
    implementation ships `"cotat"` (Reed 2003 — Cell Outlet Tracing
    with an Area Threshold). EAM (Olivera 2002) and DMM raise
    `NotImplementedError` pending a follow-up.

    COTAT algorithm (per coarse cell):

    1. Find the fine cell with the highest accumulation in the
       scale_factor × scale_factor block. This is the coarse cell's
       outlet.
    2. Trace downstream from that fine outlet along the fine
       `fdir` until leaving the block.
    3. The direction from the source coarse cell to the destination
       coarse cell becomes the coarse cell's D8 flow direction.

    Args:
        scale_factor: Integer aggregation factor (>= 1).
        method: `"cotat"` (default); `"eam"` / `"dmm"` raise
            `NotImplementedError`.
        accumulation: `Accumulation` aligned to this FlowDirection;
            required for COTAT (used to pick the per-block outlet).
        dem: Optional `DEM` aligned to this FlowDirection — when
            supplied, the returned `upscaled_dem` reports the
            elevation of each coarse cell's outlet (Reed 2003).
        area_threshold_cells: Reserved for COTAT+ branch-cutoff
            refinement; currently ignored.

    Returns:
        Tuple `(upscaled_dem, upscaled_fdir)`. If `dem` is
        `None` the first element is `None` and the caller is
        expected to recompute elevations from a coarsened DEM.

    Raises:
        NotImplementedError: For methods other than `"cotat"`.
        ValueError: If `scale_factor < 1` or `accumulation` is
            missing for COTAT.
    """
    from digitalrivers.flow.accumulation import Accumulation

    if scale_factor < 1:
        raise ValueError(f"scale_factor must be >= 1; got {scale_factor}")
    if scale_factor == 1:
        return (
            dem,
            _flow_direction_cls().from_dataset(
                Dataset(self.raster),
                routing=self.routing,
                encoding=self.encoding,
            ),
        )
    if method == "ihu":
        return self.upscale_ihu(scale_factor, accumulation, dem)[:2]
    if method in ("eam", "dmm"):
        return self._upscale_eam_or_dmm(
            scale_factor,
            method=method,
            accumulation=accumulation,
            dem=dem,
        )
    if method != "cotat":
        raise NotImplementedError(
            f"method={method!r} not yet implemented " "(only 'cotat', 'eam', 'dmm')"
        )
    if not isinstance(accumulation, Accumulation):
        raise ValueError("COTAT requires an Accumulation input")

    fdir = self.read_array().astype(np.int32, copy=False)
    acc = accumulation.read_array().astype(np.float64, copy=False)
    if fdir.shape != acc.shape:
        raise ValueError(
            f"accumulation shape {acc.shape} != flow_direction shape "
            f"{fdir.shape}"
        )

    d_row = _DIR_DR
    d_col = _DIR_DC
    rows, cols = fdir.shape
    out_rows = rows // scale_factor
    out_cols = cols // scale_factor

    # Native Numba COTAT fast path — bit-for-bit identical to the
    # pure-Python loop below; ~30-50x faster on continental DEMs.
    from digitalrivers.flow._kernels.numba import cotat_upscale_numba
    from digitalrivers.core.numba import is_numba_enabled

    if is_numba_enabled():
        coarse_fdir = cotat_upscale_numba(
            fdir,
            acc,
            scale_factor,
            d_row,
            d_col,
            np.int32(Dataset.default_no_data_value),
        )
        z = None
        coarse_z = None
        if dem is not None:
            z = dem.read_array().astype(np.float64, copy=False)
            coarse_z = np.full(
                (out_rows, out_cols),
                Dataset.default_no_data_value,
                dtype=np.float32,
            )
            for br in range(out_rows):
                for bc in range(out_cols):
                    block_acc = acc[
                        br * scale_factor : (br + 1) * scale_factor,
                        bc * scale_factor : (bc + 1) * scale_factor,
                    ]
                    idx = int(np.argmax(block_acc))
                    fr = br * scale_factor + idx // scale_factor
                    fc = bc * scale_factor + idx % scale_factor
                    coarse_z[br, bc] = _pick_coarse_elev(z, fr, fc)
        return self._wrap_upscaled(coarse_fdir, scale_factor, coarse_z)

    coarse_fdir = np.full(
        (out_rows, out_cols),
        Dataset.default_no_data_value,
        dtype=np.int32,
    )

    z = None
    coarse_z = None
    if dem is not None:
        z = dem.read_array().astype(np.float64, copy=False)
        coarse_z = np.full(
            (out_rows, out_cols),
            Dataset.default_no_data_value,
            dtype=np.float32,
        )

    for br in range(out_rows):
        for bc in range(out_cols):
            r_lo = br * scale_factor
            r_hi = r_lo + scale_factor
            c_lo = bc * scale_factor
            c_hi = c_lo + scale_factor
            block = acc[r_lo:r_hi, c_lo:c_hi]
            best = np.unravel_index(int(np.argmax(block)), block.shape)
            fr = r_lo + int(best[0])
            fc = c_lo + int(best[1])
            if z is not None:
                coarse_z[br, bc] = _pick_coarse_elev(z, fr, fc)
            r, c = fr, fc
            # Trace downstream until exiting the block.
            while True:
                d = int(fdir[r, c])
                if d < 0 or d > 7:
                    break
                nr = r + int(d_row[d])
                nc = c + int(d_col[d])
                if not (0 <= nr < rows and 0 <= nc < cols):
                    break
                coarse_dr = (nr // scale_factor) - br
                coarse_dc = (nc // scale_factor) - bc
                if coarse_dr != 0 or coarse_dc != 0:
                    # Single fine D8 step crosses at most one coarse cell
                    # boundary, so coarse_dr and coarse_dc are each in
                    # {-1, 0, 1} and the lookup is guaranteed to hit. The
                    # guard below catches any future regression that
                    # widens fine-grid steps (e.g. a non-D8 routing) and
                    # would otherwise silently leave the coarse cell at
                    # no-data.
                    matched = False
                    for k in range(8):
                        if (
                            int(d_row[k]) == coarse_dr
                            and int(d_col[k]) == coarse_dc
                        ):
                            coarse_fdir[br, bc] = k
                            matched = True
                            break
                    if not matched:
                        raise RuntimeError(
                            f"COTAT offset lookup failed at coarse cell "
                            f"({br}, {bc}) for fine step "
                            f"({coarse_dr}, {coarse_dc}); the routing "
                            f"produced a multi-coarse-cell step which "
                            f"COTAT cannot encode."
                        )
                    break
                r, c = nr, nc

    return self._wrap_upscaled(coarse_fdir, scale_factor, coarse_z)