Skip to content

pycoastkit.vulnerability

Beach vulnerability to storms: erosion classes, a beach vulnerability index (BVI) and return periods of extreme erosion.

The BVI scores how strongly a storm affected the beach on a 1-5 scale:

===== =============================================== class meaning ===== =============================================== 1 no erosion (accretion or no change) 2-4 increasing erosion 5 severe erosion ===== ===============================================

Shoreline retreat and volume loss are each scored, then averaged.

erosion_class

erosion_class(erosion, class_width, n_classes=5)

Score erosion on equal-width classes.

erosion <= 0 (accretion or no change) is class 1. Positive erosion starts at class 2 and moves up one class every class_width, capped at n_classes. With class_width=5 m: (0, 5) -> 2, [5, 10) -> 3, [10, 15) -> 4, >= 15 -> 5. NaN stays NaN.

Parameters:

Name Type Description Default
erosion float or array - like

Erosion, positive = loss (e.g. shoreline_loss [m] or volume_loss [m³/m] from :func:pycoastkit.storm_beach_response).

required
class_width float

Width of each erosion class, in the units of erosion.

required
Source code in src/pycoastkit/vulnerability.py
def erosion_class(erosion, class_width: float, n_classes: int = 5):
    """Score erosion on equal-width classes.

    ``erosion <= 0`` (accretion or no change) is class 1. Positive erosion
    starts at class 2 and moves up one class every ``class_width``, capped
    at ``n_classes``. With ``class_width=5`` m: (0, 5) -> 2, [5, 10) -> 3,
    [10, 15) -> 4, >= 15 -> 5. NaN stays NaN.

    Parameters
    ----------
    erosion : float or array-like
        Erosion, positive = loss (e.g. ``shoreline_loss`` [m] or
        ``volume_loss`` [m³/m] from :func:`pycoastkit.storm_beach_response`).
    class_width : float
        Width of each erosion class, in the units of ``erosion``.
    """
    values = np.asarray(erosion, dtype=float)
    classes = np.where(values <= 0, 1.0,
                       np.minimum(n_classes, np.floor(values / class_width) + 2))
    classes = np.where(np.isnan(values), np.nan, classes)
    return classes if classes.ndim else float(classes)

classify_by_thresholds

classify_by_thresholds(erosion, thresholds=(0.0, 2.0, 4.0, 8.0))

Score erosion with custom class boundaries.

With the default thresholds (m of shoreline retreat): <= 0 -> 1, (0, 2) -> 2, [2, 4) -> 3, [4, 8) -> 4, >= 8 -> 5. Choose boundaries from the local erosion distribution or return periods (see :func:return_periods). NaN stays NaN.

Source code in src/pycoastkit/vulnerability.py
def classify_by_thresholds(erosion, thresholds=(0.0, 2.0, 4.0, 8.0)):
    """Score erosion with custom class boundaries.

    With the default thresholds (m of shoreline retreat): ``<= 0`` -> 1,
    (0, 2) -> 2, [2, 4) -> 3, [4, 8) -> 4, ``>= 8`` -> 5. Choose boundaries
    from the local erosion distribution or return periods (see
    :func:`return_periods`). NaN stays NaN.
    """
    values = np.asarray(erosion, dtype=float)
    t = np.sort(np.asarray(thresholds, dtype=float))
    classes = 1.0 + (values > t[0]) + sum((values >= ti) for ti in t[1:])
    classes = np.where(np.isnan(values), np.nan, classes)
    return classes if classes.ndim else float(classes)

beach_vulnerability_index

beach_vulnerability_index(shoreline_loss, volume_loss, shoreline_class_width=5.0, volume_class_width=10.0, n_classes=5)

Beach vulnerability index: mean of the shoreline and volume erosion classes (1-5).

Default class widths: 5 m of shoreline retreat and 10 m³/m of volume loss.

Source code in src/pycoastkit/vulnerability.py
def beach_vulnerability_index(shoreline_loss, volume_loss, shoreline_class_width: float = 5.0,
                              volume_class_width: float = 10.0, n_classes: int = 5):
    """Beach vulnerability index: mean of the shoreline and volume erosion classes (1-5).

    Default class widths: 5 m of shoreline retreat and 10 m³/m of volume loss.
    """
    return (erosion_class(shoreline_loss, shoreline_class_width, n_classes)
            + erosion_class(volume_loss, volume_class_width, n_classes)) / 2.0

add_vulnerability_index

add_vulnerability_index(response, shoreline_column='shoreline_loss', volume_column='volume_loss', shoreline_class_width=5.0, volume_class_width=10.0)

Add vi_shoreline, vi_volume and bvi columns to a storm-response table (the output of :func:pycoastkit.storm_beach_response).

Source code in src/pycoastkit/vulnerability.py
def add_vulnerability_index(response: pd.DataFrame, shoreline_column: str = "shoreline_loss",
                            volume_column: str = "volume_loss",
                            shoreline_class_width: float = 5.0,
                            volume_class_width: float = 10.0) -> pd.DataFrame:
    """Add ``vi_shoreline``, ``vi_volume`` and ``bvi`` columns to a storm-response table
    (the output of :func:`pycoastkit.storm_beach_response`)."""
    out = response.copy()
    out["vi_shoreline"] = erosion_class(out[shoreline_column], shoreline_class_width)
    out["vi_volume"] = erosion_class(out[volume_column], volume_class_width)
    out["bvi"] = (out["vi_shoreline"] + out["vi_volume"]) / 2.0
    return out

minmax_normalize

minmax_normalize(values, minimum=None, maximum=None)

Scale to 0-1 with (x - min) / (max - min).

Pass minimum/maximum from a reference period to score new data on the same scale (values outside are clipped to 0-1).

Source code in src/pycoastkit/vulnerability.py
def minmax_normalize(values, minimum=None, maximum=None):
    """Scale to 0-1 with ``(x - min) / (max - min)``.

    Pass ``minimum``/``maximum`` from a reference period to score new data on
    the same scale (values outside are clipped to 0-1).
    """
    series = pd.Series(values, dtype=float) if not isinstance(values, pd.Series) else values.astype(float)
    lo = series.min() if minimum is None else minimum
    hi = series.max() if maximum is None else maximum
    if hi == lo:
        return series * 0.0
    return ((series - lo) / (hi - lo)).clip(0.0, 1.0)

equal_width_classes

equal_width_classes(normalized, n_classes=5)

Classes 1..n from values in 0-1 using equal-width bins (1 = lowest).

With 5 classes: [0, 0.2) -> 1, [0.2, 0.4) -> 2, ..., [0.8, 1] -> 5. NaN stays NaN.

Source code in src/pycoastkit/vulnerability.py
def equal_width_classes(normalized, n_classes: int = 5):
    """Classes 1..n from values in 0-1 using equal-width bins (1 = lowest).

    With 5 classes: [0, 0.2) -> 1, [0.2, 0.4) -> 2, ..., [0.8, 1] -> 5. NaN stays NaN.
    """
    values = np.asarray(normalized, dtype=float)
    classes = np.minimum(np.floor(values * n_classes) + 1, n_classes)
    classes = np.where(np.isnan(values), np.nan, classes)
    if isinstance(normalized, pd.Series):
        return pd.Series(classes, index=normalized.index, name=normalized.name)
    return classes

susceptibility_index

susceptibility_index(indicators, weights, direction=None, n_classes=5)

Weighted morphological susceptibility index (1 = low, n_classes = high).

Combines pre-storm beach indicators (for example shoreline position, zone volumes, foreshore slope, bar height and depth) into one class, as in the Beach Erosion Susceptibility Number (BESN):

  1. Each indicator is min-max normalised over the table.
  2. If direction[name] == -1 (a larger value makes the beach less susceptible, e.g. a wide beach), it is flipped to 1 - x.
  3. Each indicator is scored 1..n with equal-width classes.
  4. The scores are averaged with weights (normalised to sum to 1).
  5. The weighted score is normalised again and classed 1..n.

Weights can come from expert judgement or from a feature-importance analysis of observed erosion. Indicators with a NaN are left out of the weighted mean for that row.

Returns a DataFrame with the per-indicator classes, score (weighted mean class) and susceptibility (final class).

Source code in src/pycoastkit/vulnerability.py
def susceptibility_index(indicators: pd.DataFrame, weights: dict, direction: dict | None = None,
                         n_classes: int = 5) -> pd.DataFrame:
    """Weighted morphological susceptibility index (1 = low, ``n_classes`` = high).

    Combines pre-storm beach indicators (for example shoreline position, zone
    volumes, foreshore slope, bar height and depth) into one class, as in the
    Beach Erosion Susceptibility Number (BESN):

    1. Each indicator is min-max normalised over the table.
    2. If ``direction[name] == -1`` (a larger value makes the beach *less*
       susceptible, e.g. a wide beach), it is flipped to ``1 - x``.
    3. Each indicator is scored 1..n with equal-width classes.
    4. The scores are averaged with ``weights`` (normalised to sum to 1).
    5. The weighted score is normalised again and classed 1..n.

    Weights can come from expert judgement or from a feature-importance
    analysis of observed erosion. Indicators with a NaN are left out of the
    weighted mean for that row.

    Returns a DataFrame with the per-indicator classes, ``score`` (weighted
    mean class) and ``susceptibility`` (final class).
    """
    direction = direction or {}
    names = list(weights)
    missing = set(names).difference(indicators.columns)
    if missing:
        raise KeyError(f"indicators missing columns: {sorted(missing)}")
    w = pd.Series(weights, dtype=float)
    if (w < 0).any() or w.sum() == 0:
        raise ValueError("weights must be non-negative and not all zero")

    out = pd.DataFrame(index=indicators.index)
    for name in names:
        norm = minmax_normalize(indicators[name])
        if direction.get(name, 1) == -1:
            norm = 1.0 - norm
        out[f"class_{name}"] = equal_width_classes(norm, n_classes)
    classes = out[[f"class_{n}" for n in names]].to_numpy()
    weight_matrix = np.where(np.isnan(classes), 0.0, w.to_numpy())
    with np.errstate(invalid="ignore"):
        score = np.nansum(classes * weight_matrix, axis=1) / weight_matrix.sum(axis=1)
    out["score"] = score
    out["susceptibility"] = equal_width_classes(minmax_normalize(out["score"]), n_classes)
    return out

return_periods

return_periods(values, plotting_position='weibull')

Empirical return periods of annual maxima.

Parameters:

Name Type Description Default
values Series

Time-indexed values (e.g. shoreline loss per storm, indexed by storm start). The maximum of each year is used; years without data are dropped.

required
plotting_position ('weibull', 'gringorten')

weibull: T = (n + 1) / m; gringorten: T = (n + 0.12) / (m - 0.44), with n years and rank m (1 = largest).

"weibull"

Returns:

Type Description
DataFrame

year, annual_max, rank, return_period_years sorted from largest.

Source code in src/pycoastkit/vulnerability.py
def return_periods(values: pd.Series, plotting_position: str = "weibull") -> pd.DataFrame:
    """Empirical return periods of annual maxima.

    Parameters
    ----------
    values : pandas.Series
        Time-indexed values (e.g. shoreline loss per storm, indexed by storm
        start). The maximum of each year is used; years without data are dropped.
    plotting_position : {"weibull", "gringorten"}
        ``weibull``: T = (n + 1) / m; ``gringorten``: T = (n + 0.12) / (m - 0.44),
        with n years and rank m (1 = largest).

    Returns
    -------
    pandas.DataFrame
        ``year, annual_max, rank, return_period_years`` sorted from largest.
    """
    series = values.dropna()
    if not isinstance(series.index, pd.DatetimeIndex):
        series.index = pd.to_datetime(series.index)
    annual = series.groupby(series.index.year).max()
    table = annual.sort_values(ascending=False).rename("annual_max").to_frame()
    table.index.name = "year"
    n = len(table)
    rank = np.arange(1, n + 1)
    if plotting_position == "weibull":
        period = (n + 1) / rank
    elif plotting_position == "gringorten":
        period = (n + 0.12) / (rank - 0.44)
    else:
        raise ValueError("plotting_position must be 'weibull' or 'gringorten'")
    table["rank"] = rank
    table["return_period_years"] = period
    return table.reset_index()