Skip to content

diurnal_bimodality

diurnal_bimodality

diurnal_bimodality(panel: DataFrame, *, value_col: str = 'num_bikes_available', time_col: str = 'fetched_at') -> DataFrame

Sarle's bimodality coefficient of each station's diurnal profile.

Clustering yields unsupervised typologies; this yields a single, continuous, thresholded scalar that separates commuter stations (a bimodal morning/evening profile) from recreational or residential ones (unimodal). For the mean hourly profile with sample skewness :math:g_1 and excess kurtosis :math:g_2,

.. math:: \mathrm{BC} = \frac{g_1^2 + 1}{g_2 + \frac{3(n-1)^2}{(n-2)(n-3)}},

and BC > 5/9 ≈ 0.555 suggests bimodality.

Returns:

Type Description
DataFrame

Per station: bimodality_coefficient (float), is_bimodal (boolean) and peak_hour (hour of the busiest bin).

References

Pfister et al. (2013); Sarle's bimodality coefficient. Bikeshare diurnal context: Vogel et al. (2011).

See Also

diurnal_summary_stats : The diurnal curve this scores. cluster_diurnal_profiles : Unsupervised diurnal typologies.

Examples:

>>> import pandas as pd
>>> hours = list(range(24))
>>> panel = pd.DataFrame({
...     "station_id": "a",
...     "fetched_at": pd.to_datetime([f"2026-01-01T{h:02d}:00Z" for h in hours]),
...     "num_bikes_available": [10 if h in (8, 18) else 1 for h in hours],
... })
>>> int(diurnal_bimodality(panel)["peak_hour"].iloc[0])
8
Source code in src/gbfs_toolkit/analytics/temporal.py
def diurnal_bimodality(
    panel: pd.DataFrame, *, value_col: str = "num_bikes_available", time_col: str = "fetched_at"
) -> pd.DataFrame:
    """Sarle's bimodality coefficient of each station's diurnal profile.

    Clustering yields unsupervised typologies; this yields a single, continuous, thresholded
    scalar that separates commuter stations (a bimodal morning/evening profile) from recreational
    or residential ones (unimodal). For the mean hourly profile with sample skewness :math:`g_1`
    and excess kurtosis :math:`g_2`,

    .. math::
        \\mathrm{BC} = \\frac{g_1^2 + 1}{g_2 + \\frac{3(n-1)^2}{(n-2)(n-3)}},

    and ``BC > 5/9 ≈ 0.555`` suggests bimodality.

    Returns
    -------
    pandas.DataFrame
        Per station: ``bimodality_coefficient`` (float), ``is_bimodal`` (boolean) and
        ``peak_hour`` (hour of the busiest bin).

    References
    ----------
    Pfister et al. (2013); Sarle's bimodality coefficient. Bikeshare diurnal context: Vogel et al.
    (2011).

    See Also
    --------
    [`diurnal_summary_stats`][gbfs_toolkit.diurnal_summary_stats] : The diurnal curve this scores.
    [`cluster_diurnal_profiles`][gbfs_toolkit.cluster_diurnal_profiles] : Unsupervised diurnal typologies.

    Examples
    --------
    >>> import pandas as pd
    >>> hours = list(range(24))
    >>> panel = pd.DataFrame({
    ...     "station_id": "a",
    ...     "fetched_at": pd.to_datetime([f"2026-01-01T{h:02d}:00Z" for h in hours]),
    ...     "num_bikes_available": [10 if h in (8, 18) else 1 for h in hours],
    ... })
    >>> int(diurnal_bimodality(panel)["peak_hour"].iloc[0])
    8
    """
    from scipy.stats import kurtosis, skew

    df = panel_frame(panel)
    require_columns(df, ["station_id", value_col, time_col], what="diurnal_bimodality")
    work = pd.DataFrame(
        {
            "station_id": df["station_id"].to_numpy(),
            "hour": pd.to_datetime(df[time_col]).dt.hour.to_numpy(),
            "_v": pd.to_numeric(df[value_col], errors="coerce").to_numpy(),
        }
    )
    profiles = work.groupby(["station_id", "hour"])["_v"].mean().unstack("hour")
    rows = []
    for sid, profile in profiles.iterrows():
        a = profile.dropna().to_numpy()
        n = a.size
        if n < 4 or np.allclose(a, a[0]):
            bc = np.nan
        else:
            g1 = float(skew(a, bias=False))
            g2 = float(kurtosis(a, fisher=True, bias=False))
            denom = g2 + 3.0 * (n - 1) ** 2 / ((n - 2) * (n - 3))
            bc = (g1**2 + 1.0) / denom if denom != 0 else np.nan
        peak_hour = int(profile.idxmax()) if profile.notna().any() else -1
        rows.append(
            {
                "station_id": sid,
                "bimodality_coefficient": bc,
                "is_bimodal": pd.NA if np.isnan(bc) else bool(bc > 5 / 9),
                "peak_hour": peak_hour,
            }
        )
    out = pd.DataFrame(
        rows, columns=["station_id", "bimodality_coefficient", "is_bimodal", "peak_hour"]
    )
    out["is_bimodal"] = out["is_bimodal"].astype("boolean")
    return out