Skip to content

local_morans_i

local_morans_i

local_morans_i(info: DataFrame, value_col: str, *, k: int = 8, permutations: int = 999, seed: int = 0, fdr: bool = False) -> DataFrame

Local Moran's I (LISA): per-station spatial-autocorrelation hotspots and cold spots.

Where morans_i returns one global number ("is there a pattern?"), LISA localises it: each station gets a local statistic, a permutation pseudo p-value, and a cluster label, so a study can map where the low-availability cold spots or high-turnover hot spots are.

With deviations :math:z_i = x_i - \bar{x} and row-standardised k-nearest-neighbour weights, the local statistic is :math:I_i = (z_i / m_2)\sum_j w_{ij} z_j, where :math:m_2 = \frac{1}{n}\sum_i z_i^2. Significance is a conditional-permutation pseudo p-value; each station is labelled HH (high value, high neighbours), LL, HL or LH (spatial outliers) when significant, else ns. Requires scipy ([geo] weights).

Parameters:

Name Type Description Default
info DataFrame

Canonical station inventory with lat, lon and value_col.

required
value_col str

The variable to test (for example occupancy or turnover).

required
k int

Number of nearest neighbours for the spatial weights.

8
permutations int

Permutations for the pseudo p-value.

999
seed int

Seed for the permutation draw (reproducible).

0

Returns:

Type Description
DataFrame

Aligned to info: local_i, z_score, p_value, cluster_type (and station_id when present). Non-finite inputs yield NaN / "ns".

References

Anselin, L. (1995). Local Indicators of Spatial Association (LISA). Geographical Analysis, 27(2), 93-115.

See Also

morans_i : The global Moran's I this decomposes. fdr_adjust : Control the false-discovery rate across stations.

Source code in src/gbfs_toolkit/spatial/analytics.py
def local_morans_i(
    info: pd.DataFrame,
    value_col: str,
    *,
    k: int = 8,
    permutations: int = 999,
    seed: int = 0,
    fdr: bool = False,
) -> pd.DataFrame:
    """Local Moran's I (LISA): per-station spatial-autocorrelation hotspots and cold spots.

    Where [`morans_i`][gbfs_toolkit.morans_i] returns one global number ("is there a pattern?"), LISA localises it:
    each station gets a local statistic, a permutation pseudo p-value, and a cluster label, so a
    study can map *where* the low-availability cold spots or high-turnover hot spots are.

    With deviations :math:`z_i = x_i - \\bar{x}` and row-standardised k-nearest-neighbour weights,
    the local statistic is :math:`I_i = (z_i / m_2)\\sum_j w_{ij} z_j`, where
    :math:`m_2 = \\frac{1}{n}\\sum_i z_i^2`. Significance is a conditional-permutation pseudo
    p-value; each station is labelled ``HH`` (high value, high neighbours), ``LL``, ``HL`` or
    ``LH`` (spatial outliers) when significant, else ``ns``. Requires scipy (``[geo]`` weights).

    Parameters
    ----------
    info : pandas.DataFrame
        Canonical station inventory with ``lat, lon`` and ``value_col``.
    value_col : str
        The variable to test (for example occupancy or turnover).
    k : int, default 8
        Number of nearest neighbours for the spatial weights.
    permutations : int, default 999
        Permutations for the pseudo p-value.
    seed : int, default 0
        Seed for the permutation draw (reproducible).

    Returns
    -------
    pandas.DataFrame
        Aligned to ``info``: ``local_i, z_score, p_value, cluster_type`` (and ``station_id`` when
        present). Non-finite inputs yield ``NaN`` / ``"ns"``.

    References
    ----------
    Anselin, L. (1995). Local Indicators of Spatial Association (LISA). *Geographical Analysis*,
    27(2), 93-115.

    See Also
    --------
    [`morans_i`][gbfs_toolkit.morans_i] : The global Moran's I this decomposes.
    [`fdr_adjust`][gbfs_toolkit.fdr_adjust] : Control the false-discovery rate across stations.
    """
    require_columns(info, ["lat", "lon", value_col], what="local_morans_i")
    base = info.reset_index(drop=True)
    lat = pd.to_numeric(base["lat"], errors="coerce").to_numpy()
    lon = pd.to_numeric(base["lon"], errors="coerce").to_numpy()
    x = pd.to_numeric(base[value_col], errors="coerce").to_numpy()
    finite = np.isfinite(lat) & np.isfinite(lon) & np.isfinite(x)

    out = pd.DataFrame(index=base.index)
    if "station_id" in base.columns:
        out["station_id"] = base["station_id"]
    out["local_i"] = np.nan
    out["z_score"] = np.nan
    out["p_value"] = np.nan
    out["cluster_type"] = "ns"

    n = int(finite.sum())
    kk = min(k, n - 1)
    if n < 3 or kk < 1:
        return out

    pos = np.where(finite)[0]
    lat_f, lon_f, xf = lat[pos], lon[pos], x[pos]
    _, idx = GeoKDTree(lat_f, lon_f).query(lat_f, lon_f, k=kk + 1)
    neighbours = np.asarray(idx)[:, 1 : kk + 1]  # drop self

    z = xf - xf.mean()
    # Variance with ddof=1, matching the PySAL/esda Moran_Local normalisation so the
    # reported local_i is directly comparable to that reference implementation.
    m2 = float((z**2).sum() / (z.size - 1)) if z.size > 1 else 0.0
    if m2 == 0:
        return out
    lag = z[neighbours].mean(axis=1)
    local_i = (z / m2) * lag

    if permutations < 1:
        # No inference requested: report the statistic only, no pseudo p-value or z-score.
        out.loc[pos, "local_i"] = local_i
        return out

    rng = np.random.default_rng(seed)
    abs_obs = np.abs(local_i)
    ge = np.zeros(n)
    s1 = np.zeros(n)
    s2 = np.zeros(n)
    for _ in range(permutations):
        pz = rng.permutation(z)
        i_perm = (z / m2) * pz[neighbours].mean(axis=1)
        ge += np.abs(i_perm) >= abs_obs
        s1 += i_perm
        s2 += i_perm**2
    p = (ge + 1.0) / (permutations + 1.0)
    mean_perm = s1 / permutations
    std_perm = np.sqrt(np.maximum(s2 / permutations - mean_perm**2, 1e-12))
    zscore = (local_i - mean_perm) / std_perm

    # Benjamini-Hochberg correction across stations before labelling, so the cluster
    # set controls the false-discovery rate rather than a raw per-station alpha.
    p_sig = fdr_adjust(p) if fdr else p
    sig = p_sig <= 0.05
    hi_z, hi_lag = z > 0, lag > 0
    ctype = np.full(n, "ns", dtype=object)
    ctype[sig & hi_z & hi_lag] = "HH"
    ctype[sig & ~hi_z & ~hi_lag] = "LL"
    ctype[sig & hi_z & ~hi_lag] = "HL"
    ctype[sig & ~hi_z & hi_lag] = "LH"

    out.loc[pos, "local_i"] = local_i
    out.loc[pos, "z_score"] = zscore
    out.loc[pos, "p_value"] = p
    if fdr:
        out["fdr_p"] = np.nan
        out.loc[pos, "fdr_p"] = p_sig
    out.loc[pos, "cluster_type"] = ctype
    return out