You have a D8 flow-direction raster and you want to compute something that travels along the network: drainage area, flow length downstream, stream order. Every such computation needs the cells visited in an order that respects the flow, and there is more than one such order. This package builds six of them and runs four kernels over any of them, so you can pick the one that suits your grid instead of taking whatever a library happened to build.
If you only want one drainage-area map on one grid, use the three lines under Five minutes and stop there. The rest of this guide is for when the choice starts to matter: large grids, repeated kernels, or threads.
A narrated video overview animates the orderings, the layerings and the three propagation manners — worth ten minutes before reading further: https://youtu.be/tE5K2wM3TTY.
pip install -e . # numpy, rasterio, scipy, pymetis pip install -e ".[speed]" # + numba, for the threaded kernels
The structures and the serial kernels work without numba. The scalar builders
fall back to pure Python loops, correct but slow on a large grid. The threaded
kernels do not: a function of flowtopo.parallel raises rather than pretending
to use threads, so install the speed extra before running anything below that uses
it.
d8 is a flow-direction array and transform its six-element GeoTransform;
the next section reads both from a GeoTIFF in one call.
import flowtopo topo = flowtopo.FlowTopo.from_d8(d8, transform=transform) upa = topo.upstream_area(ordering="dfs") ldn = topo.distance_to_outlet(ordering="dfs") lup = topo.longest_upstream_path(ldn, ordering="dfs") ord = topo.strahler_order(ordering="dfs", channel_mask=topo.channel_mask(upa, 10.0))
d8 is a 2-D uint8 array in the MERIT Hydro convention: powers of two clockwise
from east, 0 and 255 terminal, 247 nodata. transform is a six-element GDAL
GeoTransform, needed by the two distance kernels and by the upstream drainage area when no
cell_area is given (the areas are worked out from it).
To read the bundled example instead:
topo = flowtopo.FlowTopo.from_raster("data/dir_example.tif")
An ordering is every valid cell in a single topologically sorted list. Walk it start to end and every cell is reached after everything it depends on. One loop, one thread.
A layering is one layer index per cell. Cells in a layer do not depend on each other, so the whole layer can be done at once. The index grows toward the pit, and layer 0 holds headwaters (every one of them in the as-soon-as-possible form). The number of layers cannot be smaller than the longest flow path.
Orderings and layerings are two views of the same constraint. Use an ordering when you have one core, and a layering when you have several.
d2u runs downstream to upstream, position 0 at a pit. u2d runs the other
way, position 0 at a headwater. Which one a kernel needs follows from which way
its information travels:
- drainage area, flow length upstream and stream order pass their values
down into the receiver, so they need
u2d; - flow length downstream reads from the receiver, so it needs
d2u.
The package picks the right direction for you. You only meet it if you call
topo.ordering(name, direction) yourself.
topo.ordering("dfs") # depth-first from the pits topo.ordering("bfs") # breadth-first from the pits topo.ordering("topo") # topological sort from the sources
All three give a correct answer. They differ in how the memory is walked:
dfsfinishes one tributary subtree before starting the next, so a cell's receiver is only a few positions back. Lowest simulated cache miss rate of the three; on the bundled basin, 10.5% L1 against 21.8% and 37.1%. Those figures shift by a few points with how the two arrays happen to be aligned in memory, but their order does not. This is the one to reach for when the kernel will run repeatedly.bfsgroups cells by hop count from the pit.toponeeds only donor counts, never a donor list, so it allocates least.
Run python example.py to see the miss rates on your own grid.
topo.layering("asap") # as soon as possible topo.layering("cfds") # conflict-free downstream topo.layering("alap") # as late as possible
Start with cfds. The difference between the three decides whether a parallel
push is correct.
A kernel that pushes writes into its receiver. Inside one layer that is safe
only if no two cells share a receiver. asap and alap do not promise that;
cfds does, by holding a cell back one layer when its receiver is taken.
The promise is a property of the layering, so you can count it rather than hope:
import numpy as np def conflicts(topo, layering): total = 0 for members in topo.decomposition(layering, "u2d"): ds = topo.idxs_ds[members] ds = ds[(ds >= 0) & (ds != members)] total += ds.size - np.unique(ds).size return total
On the bundled 731 km² basin, 93,432 cells, 949 layers under all three:
asap 12,122, cfds 0, alap 39,130.
A test run is not a reliable check. On a 16,000,000-cell grid with 152,258
conflicts under asap, a threaded push still returned correct results on one
run, because the colliding cells landed on the same thread. Count the
conflicts instead.
A cycle is a set of cells that drain into each other in a loop. No traversal can order them, because each depends on the next. MERIT Hydro is cycle-free, so this stays at zero on released data, but a grid you built or repaired yourself may not be, and nothing raises. Check it:
layers, _ = topo.layering("cfds") stranded = np.count_nonzero((layers < 0) & topo.mask) # 0 on a clean grid
A sequence shorter than topo.ncells says the same thing.
When a cycle is present the six structures do not agree on what is left, and each is right by its own definition. A twelve-cell grid, an eight-cell chain draining into a four-cell ring, covers:
| structure | cells covered |
|---|---|
dfs, bfs |
0, they start at a pit and there is none |
topo |
8, it starts at the headwaters and stops at the ring |
asap, cfds |
8, same reason |
alap |
0, it needs a rank measured from a pit |
So the number of cells you get back depends on which structure you asked for. Rule out cycles first and the question does not arise: on a clean grid all six cover every valid cell.
For a layering you also choose how a cell and its receiver exchange the value:
| manner | what it does | correct when |
|---|---|---|
pull |
the receiver gathers from its donors | always; needs the adjacency table |
push |
each cell writes into its receiver | only under cfds |
atomic_push |
the same scatter through np.add.at (np.maximum.at for the flow length upstream) |
always, except Strahler stream order, which has none |
upa = topo.upstream_area(layering="cfds", manner="push")
If manner is left unset, FlowTopo picks a safe one for the layering: push
under cfds, atomic_push (or pull for Strahler) under the other two.
Ask for an unsafe combination and it runs anyway, quietly returning the wrong number. That is deliberate: seeing the conflict is the point, and there is no cheap way to tell a genuine request apart from a mistake. Three cells, two headwaters meeting at a pit, is enough to show it:
topo.strahler_order(layering="cfds", manner="push") # [1 2 1], correct topo.strahler_order(layering="asap", manner="push") # [1 1 1], wrong
Both donors sit in the same asap layer, so one write lands on top of the
other and the confluence never happens. Drainage area goes the same way, one
donor short. If you set manner yourself, count the conflicts first.
Strahler stream order has no atomic_push, and this is not an oversight. Its
confluence rule is two branches of equal order raise the order by one, which
is a comparison and a count, not one addition. No single atomic operation
implements that, so under a layering the only safe push is the conflict-free
one.
Drainage area accumulates in the precision of the array you give it, float32 by default. One 90 m cell is about 0.007 km², and a float32 total large enough stops registering it: past roughly 2e5 km² a single cell no longer moves the total, at 1e6 km² it takes about five cells, at 5e6 km² about thirty-six. So on a continental river the headwaters accumulate exactly and the cells near the outlet stop counting. Hand it a float64 array when that matters:
import numpy as np upa = topo.upstream_area(ordering="dfs", cell_area=np.asarray(topo.cell_area, dtype=np.float64))
A layering spreads a layer across threads that share memory. Running on several processors needs a second cut, and it has to follow the drainage hierarchy so that no value crosses a subregion boundary mid-kernel:
part, load = topo.partition(n_parts=4, level="subbasin")
Set n_parts to the number of processors, one subregion each. The paper's
benchmark uses four, one per NUMA node of a four-socket Xeon Platinum 8270
server, with the thread count inside each subregion set where that server's
memory bandwidth saturated.
part holds a subregion index per cell, -1 outside the network and on the
cell of a basin of a single cell, and flowtopo.MAINSTEM (-2) on a mainstem
cell held back to the second stage. A basin of a single cell (a pit that
nothing flows into, mostly on a coast) takes no part in the partition and is in
no load.
The subregions depend on the basin labels (basins=): METIS divides a graph
according to the order of its nodes. They also depend on the METIS build and,
at a tie between tributaries with as many cells, on upa (below).
FullTopo v1.1 was divided with FullDivide v1.1's basin ids (the region's bsn
raster), MERIT Hydro's upa and METIS 5.2.1. Without the labels or without
METIS 5.2.1, on region 5699, 99.89 to 99.95 % of the pixels are in the same
subregion once the subregions are matched, and the subregions can be numbered
otherwise.
FullTopo v1.1 leaves regions 10001 and up (the island groups and the two
regions across 180 degrees) whole, one subregion each. Use n_parts=1 to keep
such a region in one subregion here.
By default the package uses pymetis's METIS 5.1.0, which divides the same graph
with the same seed and options otherwise than METIS 5.2.1. To use 5.2.1, build
it as a shared library with 32-bit integers and 32-bit reals
(#define IDXTYPEWIDTH 32 and #define REALTYPEWIDTH 32 in metis.h). Set
FLOWTOPO_METIS_LIBRARY to its path; the package calls METIS_PartGraphKway
through ctypes. The loader checks for METIS 5.2 and 32-bit integers, and
refuses a 5.1 library or a build with 64-bit integers. The real width cannot be
checked, so build it with 32-bit reals.
basins must be on the grid of topo, for example FlowDivide's basin raster
of the same window the flow directions were read from. upa must be the
upstream area of that grid.
import numpy as np, rasterio with rasterio.open("bsn_region_005699_3s.tif") as src: # FlowDivide's basin ids of the region bsn = src.read(1).astype(np.int64) # FLOWTOPO_METIS_LIBRARY=/path/to/libmetis.dylib set before Python starts part, load = topo.partition(4, "subbasin", basins=bsn, upa=upa)
FullTopo v1.1 stores 100 × region_id + k for subregion k (1 … 4),
100 × region_id + 5 for the held-back mainstem, and 0 off land and in a
single-pixel outlet. The package returns indices starting at 0 instead.
Its balance measure is the largest subregion's cell count over the mean of
the subregions, with the mean taken as at least one cell. It uses this measure
to choose the basins to open. The loads count the first stage only; the
held-back mainstem is not counted.
Both levels put contiguity first and balance second: on its land every subregion is one piece, the two banks of a held-back mainstem counting as touching, and the islands are added to the subregions of nearby land. Land comprises the largest components of the network, at most one per subregion: those of at least half an equal share, and the next largest when these are too few to be cut into every subregion. Every other component goes as an island with the subregion of its nearest land. The refinement may move it whole to another subregion nearby.
With level="basin" every basin stays whole, so one dominant basin leaves the
other processors idle. The
bundled example is a single basin, so it shows this directly: basin-level gives
[93432, 0, 0, 0], subbasin-level [23487, 23107, 23107, 23108].
level="subbasin" opens as few basins as the balance needs, at most four.
It opens the dominant one first, and another only where it holds the
balance up and clearly pays off. Each is opened along its mainstem into the
tributary subtrees that drain into it; a tributary is not opened further.
The mainstem is found by walking upstream from the outlet and taking at each
confluence the tributary with the most cells upstream. This mainstem goes by
cells; the main stem the dfs ordering puts first when given upa goes by
upstream area. The two can part where a tributary with fewer cells drains more
area.
The subtrees and the other basins are divided into subregions, each one piece
on its land with the islands added, by METIS and balanced by moving units along
the boundaries. P_min is the most upstream mainstem cell where a tributary
of another subregion enters. Above it the mainstem stays with the subregion
of its most upstream tributaries. From P_min down, P_min included, it
depends on several subregions, so it is marked flowtopo.MAINSTEM and runs in
a second stage after they finish. imbalance_target, min_subtree_size,
seed and refine tune it (see the docstring).
Where two tributaries hold as many cells, the mainstem follows the one with the
larger upstream area when the area is given (topo.partition(..., upa=upa),
MERIT Hydro's upa, one value a cell), then the one with the smaller cell
index. upa must be finite and positive on every cell of the network.
Without it only the cell index decides, and a mainstem can end in another
headwater cell.
The kernels in flowtopo.kernels run one numpy operation per layer. That makes
the write conflict visible deterministically, because a[idx] += v in numpy
keeps only the last write when idx repeats, exactly as a non-atomic threaded
push does. But numpy runs these loops on one thread, so for speed use flowtopo.parallel,
which compiles the same layer traversal with numba:
from flowtopo import parallel upa = parallel.upstream_area(topo, layering="cfds", manner="push")
On a synthetic network of 16 million cells with 10 threads, push under cfds
ran about 1.6 to 1.7 times as fast as the serial pass, while pull ran no faster
than serial because reading the donor table costs more than the threads save.
The kernel is memory-bound. Run python benchmark.py on your machine, since
the timings depend on it.
FlowTopo.from_raster reads any single-band D8 GeoTIFF in the MERIT Hydro
convention: codes are powers of two clockwise from east, 0 and 255 are
terminals, 247 is nodata. The file's own nodata value is honoured as well,
which matters because 255 means an endorheic terminal here, not nodata.
For a MERIT Hydro region, the find page gives its window in the global grid and the MERIT Hydro tiles covering it. These are the regions of FullDivide v1.1, which FullTopo v1.1 uses. Download the tiles from their authors.
Write a result back next to the input:
import flowtopo from flowtopo import write_geotiff topo = flowtopo.FlowTopo.from_raster("my_dir.tif") upa = topo.upstream_area(ordering="dfs") write_geotiff("upa.tif", upa, topo.header(dtype="float32", nodata=-9999.0))
example.py runs every structure, kernel and manner on one grid, compares all
results against the serial depth-first reference, and prints PASS or FAIL:
python example.py --data my_dir.tif --out out_mine
Drainage area is the one result not expected to agree bit for bit across manners. Floating-point addition is not associative and each manner sums a confluence's donors in a different order; on the bundled basin the spread is 0.0027 km², about 1e-6 of the largest value. Everything else agrees exactly, flow length upstream included, because its confluence rule takes the larger of two donors rather than adding them. The checks treat them that way.
docs/methods.md— every construction, its origin and its cost.example.py— the whole package exercised on one basin.benchmark.py— serial against threaded, at several grid sizes.
Any D8 GeoTIFF in the MERIT Hydro convention (that of the example basin) works, north-up, in longitude and latitude or in a projection whose unit is the metre: the CRS decides whether the area and distance kernels read the grid as degrees or as metres, and a rotated grid or a projection in another unit is refused. Codes are powers of two clockwise from east; 0 and 255 are terminals; 247 is always nodata, and a nodata value declared in the file is excluded as well.
Work one region or basin at a time. Indices are int32, so a raster must stay under 2.1 billion cells, nodata included; the regions of FullDivide v1.1 do.
Every ordering, layering, partition, kernel and manner is cross-checked on the
example basin, write-conflict counts included. The structures are checked
against their definitions: an ordering is a topological sort, no cell in a
layer depends on another cell of the same layer, and in an
upstream-to-downstream sequence a receiver comes after its donors. All of
that still holds after clipping a basin out of a region. The tests
and example.py run on Python 3.10, 3.11 and 3.12 on every push to main
and every pull request; the badge at the top of the README
links to the runs.
- An ordering is built in one direction and can be read in either. Kernels
that gather into the receiver (upstream drainage area, flow length upstream,
Strahler stream order) walk upstream to downstream; flow length downstream walks the other
way. The kernels pick the direction themselves;
topo.ordering("dfs", "u2d")asks for one explicitly. - The layer count is set by the longest flow path, and the conflict-free rule may add layers (on the example basin it adds none: 949 for all three). In as-soon-as-possible layer 0 holds every headwater; the conflict-free rule holds back a headwater whose receiver another cell of the layer already drains into, so its layer 0 can hold fewer; in as-late-as-possible it holds only the farthest ones.
topo.partition(n_parts, level)returns a label per cell and the load per subregion. Subbasin-level marks the mainstemflowtopo.MAINSTEM; it runs as its own stage, after the tributary subregions for kernels that accumulate downstream and before them for flow length downstream.
Four kernels come with the package: upstream drainage area, flow length
downstream (distance_to_outlet), flow length upstream
(longest_upstream_path) and Strahler stream order. Each runs on every
supported combination of structure and manner, and the results are checked
against each other.
Write conflicts and cache locality on the example basin
A push is only safe if no two cells in a layer write to the same receiver. Conflicting writes inside a layer, example basin (93,432 cells):
| layering | conflicting writes |
|---|---|
| as-soon-as-possible | 12,122 |
| conflict-free downstream | 0 |
| as-late-as-possible | 39,130 |
The count is a property of the layering and can be checked before running.
A test run cannot replace that check, because a race does not show up every
time. Under the conflict-free layering no two cells in a layer share a
receiver, so the push adds in the same order every time and gives
bit-identical results at any thread count. Strahler stream order cannot be done with
one atomic operation, because its confluence rule is a comparison and a
count, not an addition; within a layer, a push is safe for it only under the
conflict-free layering (on one thread: the threaded kernels do not include it). When manner is not given, the FlowTopo methods pick a safe one for the
layering; parallel.upstream_area defaults to push, which is safe only under
cfds.
The three serial orderings differ in memory access. Simulated L1 miss rate on
the example basin: depth-first 10.5%, breadth-first 21.8%, topological sort
37.1% (flowtopo.locality.miss_rates). The numbers move by a few points with
how the two arrays sit in memory; the ranking does not.
From the paper's benchmark on the 90 m network (22.2 billion cells, 65 regions):
- One pass on one core — the depth-first ordering. Up to 5.1 times faster than the slowest ordering, because each cell's receiver stays close in memory (L3 miss rate 6% against 37%). Measure parallel speedup against it; a slower baseline inflates the speedup.
- Repeated passes (calibration, ensembles) — the as-late-as-possible layering, fastest in parallel for all four kernels because each layer fits in cache. Under it, atomic push beat pull for sums and maxima (71.1 s against 85.1 s for flow length upstream). Use pull when the kernel has no atomic form or the result must be reproducible; pull needs the donor table.
- Push for a non-linear kernel, or little RAM — the conflict-free downstream layering with push. No locks, deterministic, only the receiver pointer stored, and the only push that can run Strahler stream order. Pull also runs it under any layering and was faster (4.8 s against 9.1 s); push wins when the donor table does not fit in memory.
- Across processors — the subbasin partition, one subregion per processor, with as many threads per subregion as the processor's memory bandwidth can feed. That number depends on the processor: Fig. 15 of the paper shows it for the server tested; measure it on yours.
For this package's numba kernels on smaller grids, see Threads.
FullTopo v1.1
holds eight structures on the 90 regions of
FullDivide v1.1.
Every region has seq_dfs, lyr_cfds, lyr_alap and part_subbasin, with its
table. Region 43 (southern China) also has seq_bfs, seq_topo, lyr_asap and
part_basin. Every raster has MERIT Hydro's exact grid header, with pixels of
1/1200 degree. FullTopo holds no drainage attributes. Its partition inputs
and rules are set out under Splitting across processors.
The structures index into the MERIT Hydro flow-direction grid, which is not redistributed here: get it from https://global-hydrodynamics.github.io/MERIT_Hydro/ under its own terms. The find page gives the MERIT Hydro tiles and the window of a region of FullDivide v1.1, whose regions FullTopo v1.1 uses. Region boxes sit on whole degrees and one degree is 1,200 cells, so a region is cut from the global rasters by integer arithmetic, with no resampling.
You do not need a whole region. Keep any subset of cells: the released sequence restricted to them is still a topological sort, and a restricted layering still has independent layers, conflict-free rule included, because removing cells cannot put a cell before something it depends on, nor make two remaining cells depend on each other. A receiver outside the clip becomes an outlet when the clip is loaded. Only the kernel values change: upstream drainage area on a clip counts the area inside the clip. Clip whole basins when the values must match those of the whole region.
Three things to know when a result here is compared with a downloaded layer:
- the released
seq_dfsraster holds at every cell its position in the upstream-to-downstream sequence (the inverse of the list of cellstopo.ordering("dfs", "u2d", upa=upa)returns), Int32 within a MERIT Hydro region and Int64 over a HydroSHEDS continent,-1off the network; - the released
seq_dfstakes the donors of a confluence by upstream drainage area, largest first, and this package takes them by cell index unless it is given the area:topo.ordering("dfs", "u2d", upa=upa)follows the released rule. The sequence depends on the Float32 upstream area it is given. Both are topological orders, and every kernel gives the same answer under either, up to the order the floating-point sums are added in; geodist.cell_area_m2computes the areas on the sphere of radius 6 371 000 m by default;FlowTopo(..., earth="wgs84")computes the ellipsoid's areas, 0.45 per cent smaller at the equator and 0.56 per cent larger at 60 degrees. FullTopo v1.1 has no areas.
A depth-first sequence visits a cell and then all its upstream cells before any
other cell, so the upstream cells of every cell take one run of consecutive
positions. It also finishes one basin before it starts the next, so every basin
takes one block of positions, from a to b, with its outlet at b. The run
of every cell follows from a released seq_dfs raster, MERIT Hydro's upg
(the number of cells draining through each cell, itself included) and the
outlets of the region's basins, which the basin table of FullBasin v1.1 gives
(bat_region_<id>_90m.csv, columns local_outlet_row, local_outlet_col and
basin_cell_count):
import flowtopo # upg_region.tif: MERIT Hydro's upg cut to the region's window n = flowtopo.dfs_interval_geotiff("seq_dfs_region.tif", "upg_region.tif", "dfs_in_region.tif", "dfs_out_region.tif", outlets="bat_region.csv")
bisseq_dfsat the basin's outlet anda = b - upg + 1,upgat the outlet being the cells of the basin;dfs_in = a + b - seq_dfs, the cell's position in its basin's block read downstream to upstream, so the outlet hasdfs_in = a;dfs_out = dfs_in + upg - 1, the last position of its upstream cells;- cell
qdrains through cellpexactly whendfs_in[p] <= dfs_in[q] <= dfs_out[p], anddfs_out - dfs_in + 1isupg.
The whole region read backward, n - 1 - seq_dfs (n the number of cells in
the region, and topo.ordering("dfs", "d2u") in this package), differs from
dfs_in by a constant within each basin and gives the same upstream cells;
dfs_in keeps the numbers of a basin in its own block, the block it has in
seq_dfs. The basins must take positions 0 to n - 1 one after another, no
position may be held by two cells, and basin_cell_count must equal upg at
each outlet; otherwise the inputs do not belong together and the run is
refused. These checks cannot prove that seq_dfs is a depth-first order of
the flow network, which needs the flow directions: seq_dfs and upg must
come from the same flow network. The table is read as FullBasin writes it,
fields split at every comma and each a plain integer, with no spaces or
quotes.
One region is read and written. seq_dfs must be a whole region, and upg
is cut to the same window, which the find page above gives. A larger upg
that covers the region, such as MERIT Hydro's tiles joined in a VRT
(gdalbuildvrt upg.vrt *_upg.tif), is read as well: the window under the
region is taken from it, across the antimeridian for the regions that cross
it. The two rasters need the same cell size and cell edges that coincide.
seq_dfs must hold
signed integers and upg integers. The rasters are read 512 rows at a time,
and one bit is kept for each cell of the sequence; a region of
33 600 × 40 800 cells takes about three minutes. The outputs are tiled
GeoTIFFs on the region's grid, in the type of seq_dfs, -1 off the network,
and an existing file is not written over.
flowtopo.dfs_interval(seq_dfs, upg, outlets) does the same on arrays, the
outlets given as (rows, cols). The C code
archived at 10.5281/zenodo.22227620
has the same tool, dfs_interval/, and gives the same files.
A D8 flow-direction grid fixes which cells must be done before which: a cell needs its upstream neighbours first, or, for some kernels, its downstream one. FlowTopo works that order out once, from the grid alone, and saves it. Anything that walks the network in drainage order (upstream drainage area, flow length, Strahler stream order, or the upstream-to-downstream step of a routing scheme) then reads the saved order instead of working it out again.
This repository holds the package and one example basin. The structures for the whole 90 m MERIT Hydro network are FullTopo v1.1; see Global products. A ten-minute narrated video shows the structures and the three ways of moving a value to its receiver: https://youtu.be/tE5K2wM3TTY.
Documentation, the global MERIT Hydro products and the other FullHydro tools: https://fullhydro.org/tools/flowtopo/
Author: Lulu Jiang (https://lulujiang.me)
git clone https://github.com/hellolulujiang/flowtopo.git cd flowtopo pip install -e . # numpy, rasterio, scipy, pymetis: structures, serial kernels, partitions pip install -e ".[speed]" # adds numba: the threaded kernels need it
Python 3.10 or newer. Without numba the structures and the serial kernels
still run, in pure Python; a function of flowtopo.parallel raises an error.
import flowtopo topo = flowtopo.FlowTopo.from_raster("data/dir_example.tif") upa = topo.upstream_area(ordering="dfs") # km², one serial pass ldn = topo.distance_to_outlet(ordering="dfs") # flow length downstream, m strord = topo.strahler_order( # on cells draining ≥ 10 km² ordering="dfs", channel_mask=topo.channel_mask(upa, 10.0)) upa_grid = topo.to_2d(upa) # back on the raster grid
Three of the kernels also run on threads, a layer at a time (needs numba); Strahler stream order runs serially only:
from flowtopo import parallel upa = parallel.upstream_area(topo, layering="cfds", manner="push") # push is safe only under cfds
data/dir_example.tif is the example basin of the paper: 292 rows by 614
columns at 3 arc-seconds, 93,432 valid cells, 731 km² on the sphere FlowTopo uses by default (729 km² on the WGS84
ellipsoid), cut from
MERIT Hydro (Yamazaki et al., 2019)
and kept under its own terms, CC BY-NC 4.0 or ODbL 1.0 (DATA_NOTICE.md).
The GeoJSON files are the basin boundary and the outlet.
Any D8 GeoTIFF in the MERIT Hydro convention works; see the user guide.
FullTopo v1.1
holds eight structures on the 90 regions of FullDivide v1.1: seq_dfs,
lyr_cfds, lyr_alap and part_subbasin, with its table, for every region;
region 43 (southern China) also has seq_bfs, seq_topo, lyr_asap and
part_basin.
See the user guide for the structures and their use with the MERIT Hydro grid.
pytest # needs pytest; numba for the threaded tests python example.py # every structure, kernel and manner on the example basin; ends PASS or FAIL python benchmark.py # serial vs threaded on synthetic grids
Cite this repository with the release you used and, once it appears, the paper: FlowTopo v1.0: a reusable computational foundation for hyperresolution hydrology on the global 90 m MERIT Hydro drainage network (Jiang et al., submitted to Geoscientific Model Development). Cite downloaded products by version. The paper describes version 1.0, archived with its code at 10.5281/zenodo.22227621. Release 1.1.3 is archived as FlowTopo code at 10.5281/zenodo.23732152.
Eight structures, grouped by the question each one answers, and three ways to pass a value from a cell to its receiver. All are built from the D8 grid. The six orderings and layerings run on the bundled example basin, the three manners on a small grid of two basins; click one for the full-size MP4, or see all nine on the animation page.
Three serial orderings. One pass over any of them computes a kernel. They differ in memory access, and so in speed.
Two spatial partitions, one subregion per processor. Both cut along the drainage hierarchy, so no value crosses a boundary while a kernel runs.
The flat downstream-pointer representation, the D8 decoding conventions, the
donor-count array, the chain-tracing rank and the breadth-first sequence
builder follow pyflwdir (D. Eilander,
Deltares; MIT licence;
10.5281/zenodo.4287337). No pyflwdir
source is included; the code was written against those conventions, and
FlowTopo.from_d8 takes the same array pyflwdir.from_array(d8, ftype="d8")
takes. The borrowed and the original parts are set out in
docs/methods.md.