Skip to content

spatial_entropy

spatial_entropy

spatial_entropy(vehicle_panel: DataFrame, *, grid_size_m: float = 200.0, time_col: str = 'fetched_at') -> DataFrame

Shannon entropy of the free-floating fleet's spatial distribution over time.

A free-floating system tends to collapse entropically (vehicles pile into city centres or topographic low points). Tracking the Shannon entropy of the per-snapshot distribution over a fixed metric grid objectifies that concentration without depending on administrative boundaries: high entropy is an even spread, low entropy is concentration.

For each snapshot, vehicles are binned into grid_size_m cells (equirectangular projection) and :math:H = -\sum_i p_i \ln p_i is computed over the occupied cells, where :math:p_i is the share of the fleet in cell :math:i. evenness normalises by :math:\ln(\text{cells}) so it is comparable across snapshots with different footprints.

Parameters:

Name Type Description Default
vehicle_panel DataFrame

A history of canonical VehicleStatus rows; needs lat, lon and time_col.

required
grid_size_m float

Grid cell size in metres.

200.0
time_col str

Snapshot timestamp to group by.

"fetched_at"

Returns:

Type Description
DataFrame

One row per snapshot: <time_col>, n_vehicles, n_cells, shannon_entropy, evenness.

See Also

spatial_center_of_mass : Where the distribution is centred. morans_i : Autocorrelation of the same field.

Source code in src/gbfs_toolkit/spatial/analytics.py
def spatial_entropy(
    vehicle_panel: pd.DataFrame, *, grid_size_m: float = 200.0, time_col: str = "fetched_at"
) -> pd.DataFrame:
    """Shannon entropy of the free-floating fleet's spatial distribution over time.

    A free-floating system tends to collapse entropically (vehicles pile into city centres or
    topographic low points). Tracking the Shannon entropy of the per-snapshot distribution over a
    fixed metric grid objectifies that concentration without depending on administrative
    boundaries: high entropy is an even spread, low entropy is concentration.

    For each snapshot, vehicles are binned into ``grid_size_m`` cells (equirectangular projection)
    and :math:`H = -\\sum_i p_i \\ln p_i` is computed over the occupied cells, where :math:`p_i` is
    the share of the fleet in cell :math:`i`. ``evenness`` normalises by :math:`\\ln(\\text{cells})`
    so it is comparable across snapshots with different footprints.

    Parameters
    ----------
    vehicle_panel : pandas.DataFrame
        A history of canonical ``VehicleStatus`` rows; needs ``lat, lon`` and ``time_col``.
    grid_size_m : float, default 200.0
        Grid cell size in metres.
    time_col : str, default "fetched_at"
        Snapshot timestamp to group by.

    Returns
    -------
    pandas.DataFrame
        One row per snapshot: ``<time_col>, n_vehicles, n_cells, shannon_entropy, evenness``.

    See Also
    --------
    [`spatial_center_of_mass`][gbfs_toolkit.spatial_center_of_mass] : Where the distribution is centred.
    [`morans_i`][gbfs_toolkit.morans_i] : Autocorrelation of the same field.
    """
    df = (
        vehicle_panel.reset_index()
        if isinstance(vehicle_panel.index, pd.MultiIndex)
        else vehicle_panel.copy()
    )
    require_columns(df, ["lat", "lon", time_col], what="spatial_entropy")
    lat = pd.to_numeric(df["lat"], errors="coerce")
    lon = pd.to_numeric(df["lon"], errors="coerce")
    finite = lat.notna() & lon.notna()
    df = df.loc[finite].copy()
    if df.empty:
        return pd.DataFrame(
            columns=[time_col, "n_vehicles", "n_cells", "shannon_entropy", "evenness"]
        )
    lat_f, lon_f = lat[finite].to_numpy(), lon[finite].to_numpy()
    mean_lat = np.deg2rad(np.mean(lat_f))
    x = EARTH_RADIUS_M * np.deg2rad(lon_f) * np.cos(mean_lat)
    y = EARTH_RADIUS_M * np.deg2rad(lat_f)
    df["_cell"] = list(
        zip(
            np.floor(x / grid_size_m).astype("int64"),
            np.floor(y / grid_size_m).astype("int64"),
            strict=True,
        )
    )

    rows = []
    for t, g in df.groupby(time_col, sort=True):
        counts = g.groupby("_cell").size().to_numpy()
        p = counts / counts.sum()
        h = float(-(p * np.log(p)).sum())
        n_cells = int(len(counts))
        rows.append(
            {
                time_col: t,
                "n_vehicles": int(len(g)),
                "n_cells": n_cells,
                "shannon_entropy": h,
                "evenness": h / np.log(n_cells) if n_cells > 1 else 0.0,
            }
        )
    return pd.DataFrame(rows)