Skip to content

statsjunk.spatial

morans_i

MoransIResult

Bases: BaseModel

Global Moran's I spatial autocorrelation statistic.

compute_morans_i

compute_morans_i(
    values: Sequence[float],
    coords: Sequence[Sequence[float]],
    k: int = 8,
    permutations: int = 999,
    seed: int = 0,
) -> MoransIResult

Global Moran's I with k-nearest-neighbour spatial weights.

What this solves

You have a measurement for each of several geographic regions (e.g. average income per municipality) and want to know whether nearby regions tend to have similar values, or whether the pattern looks random across the map. This answers "are nearby regions more alike than distant ones?" with a single statistic (positive means yes, clustered; negative means neighbours tend to differ, like a checkerboard) and a p-value for whether that pattern is stronger than chance. It's also useful as a caveat on a correlation computed across the same regions: strong spatial clustering means the regions aren't truly independent observations, so that correlation's real precision is lower than it looks.

Parameters:

Name Type Description Default
values Sequence[float]

The variable of interest, one value per region.

required
coords Sequence[Sequence[float]]

Region centroid coordinates as (x, y) pairs, same order as values. Lon/lat in degrees is fine for this diagnostic.

required
k int

Number of nearest neighbours each region is weighted against. Weights are row-standardised (each neighbour counts 1 / k).

8
permutations int

Random permutations for the pseudo p-value.

999
seed int

Seed for the permutation RNG, so the p-value is reproducible.

0

Returns:

Type Description
MoransIResult

statistic (Moran's I, ~-1..1), expected (-1 / (n - 1), the value under no autocorrelation), pvalue (one-sided permutation p-value in the direction of the observed statistic), and n.

Raises:

Type Description
ValueError

If: - values and coords have different lengths - k < 1 - permutations < 99 - fewer than k + 1 regions are provided - values is constant

References
  • Moran, P.A.P. (1950). "Notes on Continuous Stochastic Phenomena." Biometrika, 37(1/2), 17-23.