Skip to content

Interop#

Everything that hands a result to something outside the package.

Hydrodynamic-model export#

Six writers, each expecting a different shape of the same surface. Each takes an ExportGrid — the elevation array plus the georeferencing the headers need — and returns a dict mapping an artefact label to the path it wrote, so a caller that does not know which target produces two files still learns both names.

DEM.export validates the target and dispatches through write.

digitalrivers.interop.export #

Writers that hand a DEM to a hydrodynamic model.

Six targets, each wanting a different shape of the same surface:

target files written format
lisflood_fp the path as given Arc ASCII grid, six-line header
hec_ras .tif single-band float32 GeoTIFF in the dataset CRS
tuflow .flt + .hdr ESRI float grid, little-endian, with a text header
sfincs .dep + .msk headerless float32, plus a 0/1 validity mask
gmsh .geo a bounds rectangle with a uniform characteristic length
iber .dat ASCII boundary file for the Iber pre-processor

Every writer takes an :class:ExportGrid — the surface plus the georeferencing the headers need — and returns a dict mapping an artefact label to the path written, so a caller that does not know which target produces two files still learns both names.

Splitting these out of DEM.export is what makes them testable: a writer can be handed a synthetic 3x3 grid and its bytes checked, with no raster on disk and no DEM instance. DEM.export validates the target and dispatches through :func:write.

ExportGrid dataclass #

The surface and georeferencing every writer needs.

Built once by DEM.export so the no-data substitution and the corner arithmetic happen in one place rather than in each of six writers.

Attributes:

Name Type Description
values ndarray

2-D elevation array with the no-data sentinel already substituted for NaN, so writers never handle NaN themselves.

nan_mask ndarray

True where the source array was NaN. SFINCS needs it for its .msk companion; the others ignore it.

geotransform tuple

The six-element GDAL geotransform.

epsg int

EPSG code of the dataset CRS.

no_data float

The no-data sentinel, written into the ASCII headers.

Source code in src/digitalrivers/interop/export.py
@dataclass(frozen=True)
class ExportGrid:
    """The surface and georeferencing every writer needs.

    Built once by `DEM.export` so the no-data substitution and the corner arithmetic
    happen in one place rather than in each of six writers.

    Attributes:
        values: 2-D elevation array with the no-data sentinel already substituted for
            `NaN`, so writers never handle `NaN` themselves.
        nan_mask: `True` where the source array was `NaN`. SFINCS needs it for its
            `.msk` companion; the others ignore it.
        geotransform: The six-element GDAL geotransform.
        epsg: EPSG code of the dataset CRS.
        no_data: The no-data sentinel, written into the ASCII headers.
    """

    values: np.ndarray
    nan_mask: np.ndarray
    geotransform: tuple
    epsg: int
    no_data: float

    @property
    def shape(self) -> tuple[int, int]:
        """`(rows, columns)` of the grid."""
        return self.values.shape

    @property
    def cell_size(self) -> float:
        """Cell size in CRS units, from the geotransform's x pitch."""
        return abs(self.geotransform[1])

    @property
    def xllcorner(self) -> float:
        """X of the lower-left corner, the origin Arc-style headers count from."""
        return self.geotransform[0]

    @property
    def yllcorner(self) -> float:
        """Y of the lower-left corner.

        The geotransform's y origin is the *top* edge and its y pitch is negative, so
        the bottom edge is `y0 + rows * dy`.
        """
        rows = self.values.shape[0]
        return self.geotransform[3] + rows * self.geotransform[5]
cell_size property #

Cell size in CRS units, from the geotransform's x pitch.

shape property #

(rows, columns) of the grid.

xllcorner property #

X of the lower-left corner, the origin Arc-style headers count from.

yllcorner property #

Y of the lower-left corner.

The geotransform's y origin is the top edge and its y pitch is negative, so the bottom edge is y0 + rows * dy.

write(target, grid, path, **kwargs) #

Dispatch to the writer for target.

Parameters:

Name Type Description Default
target str

One of the keys of :data:TARGETS.

required
grid ExportGrid

The surface to write.

required
path str

Output path; each writer appends its own extension when missing.

required
**kwargs

Passed through to the writer.

{}

Returns:

Type Description
dict

dict mapping artefact label to the path written.

Raises:

Type Description
ValueError

For an unknown target.

Source code in src/digitalrivers/interop/export.py
def write(target: str, grid: ExportGrid, path: str, **kwargs) -> dict:
    """Dispatch to the writer for `target`.

    Args:
        target: One of the keys of :data:`TARGETS`.
        grid: The surface to write.
        path: Output path; each writer appends its own extension when missing.
        **kwargs: Passed through to the writer.

    Returns:
        `dict` mapping artefact label to the path written.

    Raises:
        ValueError: For an unknown `target`.
    """
    try:
        writer = TARGETS[target]
    except KeyError:
        raise ValueError(
            f"target must be one of {sorted(TARGETS)}; got {target!r}"
        ) from None
    return writer(grid, path, **kwargs)

write_gmsh(grid, path, **kwargs) #

Write a minimal Gmsh .geo script describing the DEM's bounds.

The script is the grid extent as a rectangle with a uniform characteristic length equal to the cell size — enough for gmsh -2 <path> to produce a mesh over the footprint. It carries no elevations; the surface itself is not exported here.

Parameters:

Name Type Description Default
grid ExportGrid

The surface whose bounds are written.

required
path str

Output path; .geo is appended when missing.

required
**kwargs

Ignored; accepted so every writer shares one signature.

{}

Returns:

Type Description
dict

{"geo": path}.

Source code in src/digitalrivers/interop/export.py
def write_gmsh(grid: ExportGrid, path: str, **kwargs) -> dict:
    """Write a minimal Gmsh `.geo` script describing the DEM's bounds.

    The script is the grid extent as a rectangle with a uniform characteristic length
    equal to the cell size — enough for `gmsh -2 <path>` to produce a mesh over the
    footprint. It carries no elevations; the surface itself is not exported here.

    Args:
        grid: The surface whose bounds are written.
        path: Output path; `.geo` is appended when missing.
        **kwargs: Ignored; accepted so every writer shares one signature.

    Returns:
        `{"geo": path}`.
    """
    geo_path = _suffixed(path, ".geo")
    rows, cols = grid.shape
    x0, dx, _, y0, _, dy = grid.geotransform
    ext_x_lo = x0
    ext_x_hi = x0 + cols * dx
    ext_y_hi = y0
    ext_y_lo = y0 + rows * dy
    cl = grid.cell_size
    with open(geo_path, "w") as fh:
        fh.write(f"cl = {cl};\n")
        fh.write(f"Point(1) = {{{ext_x_lo}, {ext_y_lo}, 0, cl}};\n")
        fh.write(f"Point(2) = {{{ext_x_hi}, {ext_y_lo}, 0, cl}};\n")
        fh.write(f"Point(3) = {{{ext_x_hi}, {ext_y_hi}, 0, cl}};\n")
        fh.write(f"Point(4) = {{{ext_x_lo}, {ext_y_hi}, 0, cl}};\n")
        fh.write("Line(1) = {1, 2};\n")
        fh.write("Line(2) = {2, 3};\n")
        fh.write("Line(3) = {3, 4};\n")
        fh.write("Line(4) = {4, 1};\n")
        fh.write("Line Loop(1) = {1, 2, 3, 4};\n")
        fh.write("Plane Surface(1) = {1};\n")
    return {"geo": geo_path}

write_hec_ras(grid, path, **kwargs) #

Write a single-band float32 GeoTIFF for HEC-RAS Mapper.

Mapper wants the dataset CRS and a consistent geotransform, which is exactly what Dataset.from_array(path=...) writes — the driver is resolved from the extension, so .tif is appended when the caller did not supply it. Without that, a bare path fails inside pyramids with a driver error that names neither this writer nor the export target.

Parameters:

Name Type Description Default
grid ExportGrid

The surface to write.

required
path str

Output path; .tif is appended when missing.

required
**kwargs

Ignored; accepted so every writer shares one signature.

{}

Returns:

Type Description
dict

{"dem_tif": ...}, naming the path actually written.

Source code in src/digitalrivers/interop/export.py
def write_hec_ras(grid: ExportGrid, path: str, **kwargs) -> dict:
    """Write a single-band float32 GeoTIFF for HEC-RAS Mapper.

    Mapper wants the dataset CRS and a consistent geotransform, which is exactly what
    `Dataset.from_array(path=...)` writes — the driver is resolved from the extension,
    so `.tif` is appended when the caller did not supply it. Without that, a bare path
    fails inside pyramids with a driver error that names neither this writer nor the
    export target.

    Args:
        grid: The surface to write.
        path: Output path; `.tif` is appended when missing.
        **kwargs: Ignored; accepted so every writer shares one signature.

    Returns:
        `{"dem_tif": ...}`, naming the path actually written.
    """
    path = _suffixed(path, ".tif")
    Dataset.from_array(
        grid.values.astype(np.float32, copy=False),
        geo_ref=GeoReference(geo=grid.geotransform, epsg=grid.epsg),
        no_data_value=grid.no_data,
        path=path,
    )
    return {"dem_tif": path}

write_iber(grid, path, **kwargs) #

Write an ASCII boundary file for Iber's pre-processor.

Iber ultimately wants a .dat mesh. Until mesh generation lands (P33) this writes the grid as an uppercase-header ASCII file the pre-processor can import and refine.

Parameters:

Name Type Description Default
grid ExportGrid

The surface to write.

required
path str

Output path; .dat is appended when missing.

required
**kwargs

Ignored; accepted so every writer shares one signature.

{}

Returns:

Type Description
dict

{"dem_dat": ...}.

Source code in src/digitalrivers/interop/export.py
def write_iber(grid: ExportGrid, path: str, **kwargs) -> dict:
    """Write an ASCII boundary file for Iber's pre-processor.

    Iber ultimately wants a `.dat` mesh. Until mesh generation lands (P33) this writes
    the grid as an uppercase-header ASCII file the pre-processor can import and refine.

    Args:
        grid: The surface to write.
        path: Output path; `.dat` is appended when missing.
        **kwargs: Ignored; accepted so every writer shares one signature.

    Returns:
        `{"dem_dat": ...}`.
    """
    dat_path = _suffixed(path, ".dat")
    rows, cols = grid.shape
    with open(dat_path, "w") as fh:
        fh.write("# Iber mesh boundary (auto-generated)\n")
        fh.write(f"NCOLS {cols}\nNROWS {rows}\n")
        fh.write(f"XLLCORNER {grid.xllcorner}\nYLLCORNER {grid.yllcorner}\n")
        fh.write(f"CELLSIZE {grid.cell_size}\nNODATA {grid.no_data}\n")
        _write_rows(fh, grid.values)
    return {"dem_dat": dat_path}

write_lisflood_fp(grid, path, **kwargs) #

Write an Arc ASCII grid, the canonical LISFLOOD-FP elevation input.

Parameters:

Name Type Description Default
grid ExportGrid

The surface to write.

required
path str

Output path, used exactly as given.

required
**kwargs

Ignored; accepted so every writer shares one signature.

{}

Returns:

Type Description
dict

{"dem_asc": path}.

Source code in src/digitalrivers/interop/export.py
def write_lisflood_fp(grid: ExportGrid, path: str, **kwargs) -> dict:
    """Write an Arc ASCII grid, the canonical LISFLOOD-FP elevation input.

    Args:
        grid: The surface to write.
        path: Output path, used exactly as given.
        **kwargs: Ignored; accepted so every writer shares one signature.

    Returns:
        `{"dem_asc": path}`.
    """
    with open(path, "w", encoding="ascii", newline="\n") as fh:
        fh.write(_arc_header(grid))
        _write_rows(fh, grid.values)
    return {"dem_asc": path}

write_sfincs(grid, path, **kwargs) #

Write the SFINCS pair: a headerless .dep and its .msk companion.

.dep is row-major little-endian float32 with no header at all — SFINCS takes the shape from its own control file. .msk is uint8, 0 where the source was no-data and 1 elsewhere.

Parameters:

Name Type Description Default
grid ExportGrid

The surface to write.

required
path str

Output path; .dep is appended when missing.

required
**kwargs

Ignored; accepted so every writer shares one signature.

{}

Returns:

Type Description
dict

{"dem_dep": ..., "dem_msk": ...}.

Source code in src/digitalrivers/interop/export.py
def write_sfincs(grid: ExportGrid, path: str, **kwargs) -> dict:
    """Write the SFINCS pair: a headerless `.dep` and its `.msk` companion.

    `.dep` is row-major little-endian float32 with no header at all — SFINCS takes the
    shape from its own control file. `.msk` is `uint8`, `0` where the source was
    no-data and `1` elsewhere.

    Args:
        grid: The surface to write.
        path: Output path; `.dep` is appended when missing.
        **kwargs: Ignored; accepted so every writer shares one signature.

    Returns:
        `{"dem_dep": ..., "dem_msk": ...}`.
    """
    dep_path = _suffixed(path, ".dep")
    msk_path = dep_path[:-4] + ".msk"
    grid.values.astype(np.float32, copy=False).tofile(dep_path)
    np.where(grid.nan_mask, 0, 1).astype(np.uint8).tofile(msk_path)
    return {"dem_dep": dep_path, "dem_msk": msk_path}

write_tuflow(grid, path, **kwargs) #

Write an ESRI floating-point grid: .flt binary plus .hdr text header.

The binary is row-major little-endian float32, top-left cell first.

Parameters:

Name Type Description Default
grid ExportGrid

The surface to write.

required
path str

Output path; .flt is appended when missing.

required
**kwargs

Ignored; accepted so every writer shares one signature.

{}

Returns:

Type Description
dict

{"dem_flt": ..., "dem_hdr": ...}.

Source code in src/digitalrivers/interop/export.py
def write_tuflow(grid: ExportGrid, path: str, **kwargs) -> dict:
    """Write an ESRI floating-point grid: `.flt` binary plus `.hdr` text header.

    The binary is row-major little-endian float32, top-left cell first.

    Args:
        grid: The surface to write.
        path: Output path; `.flt` is appended when missing.
        **kwargs: Ignored; accepted so every writer shares one signature.

    Returns:
        `{"dem_flt": ..., "dem_hdr": ...}`.
    """
    flt_path = _suffixed(path, ".flt")
    hdr_path = flt_path[:-4] + ".hdr"
    grid.values.astype(np.float32, copy=False).tofile(flt_path)
    with open(hdr_path, "w") as fh:
        fh.write(_arc_header(grid))
        fh.write("byteorder LSBFIRST\n")
    return {"dem_flt": flt_path, "dem_hdr": hdr_path}

Sub-grid bathymetry#

Per-coarse-cell depth / wetted-fraction tables, the representation SFINCS and similar reduced-order solvers use to recover small-scale topography they do not resolve.

digitalrivers.interop.subgrid #

Sub-grid bathymetry tables for reduced-order 2D models.

SFINCS and models like it run on a coarse grid but still want the small-scale topography that grid cannot resolve. The compromise is a per-coarse-cell lookup table: for each block of fine cells, what fraction of the block lies below each of n_bins depth levels. The solver reads that table instead of resolving the topography, recovering most of the storage and conveyance behaviour at coarse-grid cost.

subgrid_table is the array kernel; DEM.subgrid_bathymetry wraps it.

subgrid_table(elev, scale_factor, n_bins) #

Build the per-coarse-cell depth / wetted-fraction table.

Parameters:

Name Type Description Default
elev ndarray

2-D elevation array with NaN in no-data cells.

required
scale_factor int

Fine cells per coarse cell along each axis. Must be >= 2.

required
n_bins int

Number of depth bins per coarse cell. Must be >= 1.

required

Returns:

Type Description
DataFrame

pandas.DataFrame indexed by the coarse cell's (row, col), with z_min,

DataFrame

z_max and frac_below_1 .. frac_below_<n_bins>. Blocks with no finite cell

DataFrame

are omitted; a flat block reports 1.0 in every fraction column, since every

DataFrame

bin edge sits at or above its single elevation.

Raises:

Type Description
ValueError

For scale_factor < 2 or n_bins < 1.

Source code in src/digitalrivers/interop/subgrid.py
def subgrid_table(elev: np.ndarray, scale_factor: int, n_bins: int) -> pd.DataFrame:
    """Build the per-coarse-cell depth / wetted-fraction table.

    Args:
        elev: 2-D elevation array with `NaN` in no-data cells.
        scale_factor: Fine cells per coarse cell along each axis. Must be >= 2.
        n_bins: Number of depth bins per coarse cell. Must be >= 1.

    Returns:
        `pandas.DataFrame` indexed by the coarse cell's `(row, col)`, with `z_min`,
        `z_max` and `frac_below_1` .. `frac_below_<n_bins>`. Blocks with no finite cell
        are omitted; a flat block reports `1.0` in every fraction column, since every
        bin edge sits at or above its single elevation.

    Raises:
        ValueError: For `scale_factor < 2` or `n_bins < 1`.
    """
    if scale_factor < 2:
        raise ValueError(f"scale_factor must be >= 2; got {scale_factor}")
    if n_bins < 1:
        raise ValueError(f"n_bins must be >= 1; got {n_bins}")

    rows, cols = elev.shape
    out_rows = rows // scale_factor
    out_cols = cols // scale_factor

    records: list[dict] = []
    for br in range(out_rows):
        for bc in range(out_cols):
            block = elev[
                br * scale_factor : (br + 1) * scale_factor,
                bc * scale_factor : (bc + 1) * scale_factor,
            ].ravel()
            valid = block[np.isfinite(block)]
            if valid.size == 0:
                continue
            z_min = float(valid.min())
            z_max = float(valid.max())
            rec = {"row": br, "col": bc, "z_min": z_min, "z_max": z_max}
            if z_max == z_min:
                # Flat block: every bin is "below" the single value, so
                # frac_below_k == 1.0 for every k. (The B1 review found
                # that the original code computed this list but never
                # wrote it into the record, dropping the frac columns
                # entirely when every block was flat.)
                for k in range(1, n_bins + 1):
                    rec[f"frac_below_{k}"] = 1.0
            else:
                bin_edges = np.linspace(z_min, z_max, n_bins + 1)
                for k, edge in enumerate(bin_edges[1:], start=1):
                    rec[f"frac_below_{k}"] = float((valid <= edge).sum() / valid.size)
            records.append(rec)
    df = pd.DataFrame(records).set_index(["row", "col"])
    return df

ANUDEM-lite gap fill#

Relaxation gap-fill for a surface with holes — cloud shadow, survey gaps, vegetation occlusion. Two solvers: a Laplacian membrane, and a biharmonic plate that matches slope as well as value at the hole edge.

digitalrivers.interop.anudem #

ANUDEM-lite: relaxation gap-fill for a surface with holes.

A pragmatic subset of Hutchinson (1989) covering the case that actually comes up — a DEM with NaN holes from cloud shadow, survey gaps or vegetation occlusion — rather than the full drainage-enforcing thin-plate spline.

Two solvers, both Gauss-Seidel sweeps holding the known cells fixed:

  • "laplacian" solves the 4-neighbour mean, the discrete form of a membrane stretched across the hole. Fast, and it cannot overshoot, but it meets the known surface with a visible kink: it matches values at the boundary without matching slopes.
  • "biharmonic" solves the plate equation instead, matching slope as well as value at the hole edge, so the seam disappears. Slower, and it can overshoot slightly. Implemented as damped Jacobi on the 13-point stencil; an earlier two-Laplacian approximation diverged for holes of 3x3 and larger.

relax_gaps is the array kernel; DEM.anudem_interpolate wraps it and records the operation in the DEM's conditioning history.

relax_gaps(elev, mask=None, max_iter=200, tol=0.001, method='laplacian') #

Fill the unknown cells of elev by relaxation, holding the known ones fixed.

Parameters:

Name Type Description Default
elev ndarray

2-D elevation array; NaN marks the cells to fill.

required
mask

Optional bool array of the same shape. True marks a cell as one to preserve, in addition to the finite cells that are held fixed anyway. A NaN cell marked True is therefore left NaN rather than filled. Defaults to None, which holds every finite cell fixed and fills the rest.

None
max_iter int

Maximum relaxation sweeps. Defaults to 200.

200
tol float

Stop once the largest change in a sweep falls below this. Defaults to 1e-3.

0.001
method str

"laplacian" (default) or "biharmonic".

'laplacian'

Returns:

Type Description
ndarray

float64 array of the same shape, with the unknown cells filled.

Raises:

Type Description
ValueError

For an unknown method, or an input with no cell held fixed to interpolate from. A mask whose shape does not match also raises ValueError, from the broadcast rather than from an explicit check.

Source code in src/digitalrivers/interop/anudem.py
def relax_gaps(
    elev: np.ndarray,
    mask=None,
    max_iter: int = 200,
    tol: float = 1e-3,
    method: str = "laplacian",
) -> np.ndarray:
    """Fill the unknown cells of `elev` by relaxation, holding the known ones fixed.

    Args:
        elev: 2-D elevation array; `NaN` marks the cells to fill.
        mask: Optional bool array of the same shape. `True` marks a cell as one to
            *preserve*, in addition to the finite cells that are held fixed anyway. A
            `NaN` cell marked `True` is therefore left `NaN` rather than filled.
            Defaults to `None`, which holds every finite cell fixed and fills the rest.
        max_iter: Maximum relaxation sweeps. Defaults to 200.
        tol: Stop once the largest change in a sweep falls below this. Defaults to 1e-3.
        method: `"laplacian"` (default) or `"biharmonic"`.

    Returns:
        `float64` array of the same shape, with the unknown cells filled.

    Raises:
        ValueError: For an unknown `method`, or an input with no cell held fixed to
            interpolate from. A `mask` whose shape does not match also raises
            `ValueError`, from the broadcast rather than from an explicit check.
    """
    if method not in ("laplacian", "biharmonic"):
        raise ValueError(f"method must be 'laplacian' or 'biharmonic'; got {method!r}")

    z = elev.astype(np.float64, copy=True)
    fixed = np.isfinite(z)
    if mask is not None:
        fixed = fixed | mask.astype(bool, copy=False)
    if not fixed.any():
        raise ValueError("anudem_interpolate needs at least one finite anchor cell")
    # Seed unknown cells to the mean of known values to speed convergence.
    z = np.where(fixed, z, z[fixed].mean())

    def _edge_shifts(arr):
        """Return (north, south, east, west) views of `arr` with
        edge-replication boundary handling (no periodic wrap).

        Using `np.pad(..., mode="edge")` matches a Neumann (zero
        normal-derivative) boundary, which is the natural choice for
        an interpolation kernel — the original `np.roll` formed a
        torus and injected far-edge values into near-edge cells,
        corrupting anchors near the DEM boundary.
        """
        padded = np.pad(arr, 1, mode="edge")
        return (
            padded[:-2, 1:-1],
            padded[2:, 1:-1],
            padded[1:-1, 2:],
            padded[1:-1, :-2],
        )

    if method == "laplacian":
        for _ in range(max_iter):
            north, south, east, west = _edge_shifts(z)
            new_z = (north + south + east + west) / 4.0
            new_z[fixed] = z[fixed]
            diff = float(np.max(np.abs(new_z - z)))
            z = new_z
            if diff < tol:
                break
    else:  # biharmonic
        # Damped Jacobi on the 13-point biharmonic stencil, the standard
        # discretisation of the plate equation:
        #
        #     20 z - 8(N+S+E+W) + 2(NE+NW+SE+SW) + (NN+SS+EE+WW) = 0
        #
        # The stencil is not diagonally dominant (20 against 44), so undamped
        # Jacobi does not converge on it. `_BIHARMONIC_RELAXATION` is what makes
        # the iteration contract; it was chosen by sweeping the factor against a
        # plane, which is an exact biharmonic solution and therefore has a known
        # answer. Anything above 0.6 diverges on a hole of 5x5 or larger.
        for _ in range(max_iter):
            n, s_, e, w, ne, nw, se, sw, nn, ss, ee, ww = _biharmonic_neighbours(z)
            target = (
                8.0 * (n + s_ + e + w) - 2.0 * (ne + nw + se + sw) - (nn + ss + ee + ww)
            ) / 20.0
            new_z = z + _BIHARMONIC_RELAXATION * (target - z)
            new_z[fixed] = z[fixed]
            diff = float(np.max(np.abs(new_z - z)))
            z = new_z
            if diff < tol:
                break

    return z