import warnings


def _recalculate_channel_slope(z_up, z_down, dx, threshold=1e-4):
    """Recalculate channel slope based on elevation.

    Parameters
    ----------
    z_up : float
        Upstream elevation.
    z_down : float
        Downstream elevation.
    dz : float
        Distance.

    Examples
    --------
    >>> from landlab.components.network_sediment_transporter.network_sediment_transporter import _recalculate_channel_slope
    >>> import pytest
    >>> _recalculate_channel_slope(10., 0., 10.)
    1.0
    >>> _recalculate_channel_slope(0., 0., 10.)
    0.0001
    >>> with pytest.warns(UserWarning):
    ...     _recalculate_channel_slope(0., 10., 10.)
    0.0

    """
    chan_slope = (z_up - z_down) / dx

    if chan_slope < 0.0:
        chan_slope = 0.0
        warnings.warn(
            "NetworkSedimentTransporter: Negative channel slope encountered.",
            UserWarning,
        )

    elif chan_slope < threshold:
        chan_slope = threshold

    return chan_slope