Skip to content

Commit

Permalink
Implement drainagebasins (#122)
Browse files Browse the repository at this point in the history
This adds a pybind11 wrapper to the _flow module and a method to
FlowObject for drainagebasins. Only the full drainagebasins
computation is currently supported.

CMakeLists.txt is modified to use an appropriate commit of
libtopotoolbox. This can be updated to 2025-W02 or later upon that
release.

Resolves #110
  • Loading branch information
wkearn authored Jan 7, 2025
1 parent b2e117e commit 70dafa7
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 2 deletions.
2 changes: 1 addition & 1 deletion CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ include(FetchContent)
FetchContent_Declare(
topotoolbox
GIT_REPOSITORY https://github.com/TopoToolbox/libtopotoolbox.git
GIT_TAG 2024-W46
GIT_TAG 8aa5ec825d83b66742914d17753c054580834684
)
FetchContent_MakeAvailable(topotoolbox)

Expand Down
15 changes: 14 additions & 1 deletion src/lib/flow.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,22 @@ void wrap_flow_accumulation(
flow_accumulation(acc_ptr, source_ptr, direction_ptr, weights_ptr, dims_ptr);
}

void wrap_drainagebasins(py::array_t<ptrdiff_t> basins,
py::array_t<ptrdiff_t> source,
py::array_t<ptrdiff_t> target,
std::tuple<ptrdiff_t, ptrdiff_t> dims) {
ptrdiff_t *basins_ptr = basins.mutable_data();
ptrdiff_t *source_ptr = source.mutable_data();
ptrdiff_t *target_ptr = target.mutable_data();
ptrdiff_t dims_array[2] = {std::get<0>(dims), std::get<1>(dims)};

drainagebasins(basins_ptr, source_ptr, target_ptr, dims_array);
}

// Make wrap_funcname() function available as grid_funcname() to be used by
// by functions in the pytopotoolbox package

PYBIND11_MODULE(_flow, m) {
m.def("flow_accumulation", &wrap_flow_accumulation);
m.def("flow_accumulation", &wrap_flow_accumulation);
m.def("drainagebasins", &wrap_drainagebasins);
}
26 changes: 26 additions & 0 deletions src/topotoolbox/flow_object.py
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,32 @@ def flow_accumulation(self, weights: np.ndarray | float = 1.0):

return result

def drainagebasins(self):
"""Delineate drainage basins from a flow network.
Returns
-------
GridObject
An integer-valued GridObject with a unique label for each drainage
basin.
"""
basins = np.zeros(self.shape, dtype=np.int64, order='F')

_flow.drainagebasins(basins, self.source, self.target, self.shape)

result = GridObject()
result.path = self.path
result.name = self.name

result.z = basins
result.cellsize = self.cellsize

result.bounds = self.bounds
result.transform = self.transform
result.crs = self.crs

return result

# 'Magic' functions:
# ------------------------------------------------------------------------

Expand Down

0 comments on commit 70dafa7

Please sign in to comment.