def morans_i(info: pd.DataFrame, value_col: str, *, k: int = 8) -> pd.Series:
"""Global **Moran's I**: spatial autocorrelation of ``value_col`` across stations.
Answers "are similar values geographically clustered?" (e.g. are empty/low-occupancy
stations grouped together, an equity / accessibility signal). Uses row-standardised
binary k-nearest-neighbour weights; significance is the analytic z-score / p-value under
the normality assumption. ``I > E[I]`` ⇒ clustering, ``< E[I]`` ⇒ dispersion/checkerboard.
Returns
-------
pandas.Series
``morans_i``, ``expected_i`` (= ``-1/(n-1)``), ``z_score``, ``p_value``, ``n``.
See Also
--------
[`local_morans_i`][gbfs_toolkit.local_morans_i] : Per-station LISA decomposition of this global statistic.
[`ripley_k`][gbfs_toolkit.ripley_k] : Multi-scale clustering of the point pattern.
[`spatial_entropy`][gbfs_toolkit.spatial_entropy] : Spread of the same distribution.
Examples
--------
Two spatially separated clusters (low capacities to the south, high to the
north) are perfectly autocorrelated:
>>> import pandas as pd
>>> info = pd.DataFrame({
... "system_id": "s", "station_id": [str(i) for i in range(12)],
... "lat": [48.85] * 6 + [48.90] * 6,
... "lon": [2.35 + 0.001 * i for i in range(6)] * 2,
... "capacity": [5] * 6 + [50] * 6,
... })
>>> round(float(morans_i(info, "capacity", k=3)["morans_i"]), 2)
1.0
"""
require_columns(info, ["lat", "lon", value_col], what="morans_i")
sub = info[["lat", "lon", value_col]].copy()
for c in ("lat", "lon", value_col):
sub[c] = pd.to_numeric(sub[c], errors="coerce")
sub = sub.dropna()
lat, lon = sub["lat"].to_numpy(), sub["lon"].to_numpy()
x = sub[value_col].to_numpy(dtype="float64")
n = x.size
nan = float("nan")
if n < 3 or k < 1:
return pd.Series(
{"morans_i": nan, "expected_i": nan, "z_score": nan, "p_value": nan, "n": int(n)}
)
w = _knn_weights(lat, lon, k)
z = x - x.mean()
zz = float((z * z).sum())
s0 = float(w.sum())
if zz == 0 or s0 == 0:
return pd.Series(
{"morans_i": nan, "expected_i": nan, "z_score": nan, "p_value": nan, "n": int(n)}
)
morans = (n / s0) * float(z @ (w @ z)) / zz
expected = -1.0 / (n - 1)
wt = w + w.T
s1 = 0.5 * float(wt.multiply(wt).sum())
rs = np.asarray(w.sum(axis=1)).ravel()
cs = np.asarray(w.sum(axis=0)).ravel()
s2 = float(np.sum((rs + cs) ** 2))
var = (n * n * s1 - n * s2 + 3 * s0 * s0) / (s0 * s0 * (n * n - 1)) - expected * expected
if var > 0:
from scipy.stats import norm
z_score = (morans - expected) / np.sqrt(var)
p_value = float(2 * norm.sf(abs(z_score)))
else:
z_score = p_value = nan
return pd.Series(
{
"morans_i": round(morans, 4),
"expected_i": round(expected, 4),
"z_score": round(float(z_score), 4) if np.isfinite(z_score) else nan,
"p_value": round(p_value, 4) if np.isfinite(p_value) else nan,
"n": int(n),
}
)