Skip to content

When regression ignores the map

Check an ordinary regression for leftover spatial dependence with LM tests, then read spatial lag and error models and their limits.

Advanced ~15 min11 steps

What runs in CodeSplash

You will be able to

  • Use LM tests to judge whether a regression leaves spatial dependence behind
  • Tell a spatial lag model from a spatial error model
  • Name the areal-unit problem and the ecological fallacy when you report a result

Read first

01

Independent errors, on a map

Read

Ordinary regression assumes that one site's error tells you nothing about another's. On a map that often fails: places near each other share things you didn't measure.

Then the standard errors are wrong, and sometimes the coefficients too. Start by checking the residuals.

02

Leftover pattern

Predict

Predict first

Crime in Columbus clusters on the map. You fit an ordinary regression of crime on income and housing value.

Income and housing cluster too. Do the residuals still show spatial clustering?

Yes, residuals still clusterNo, income and housing explain it
Reveal

Yes. Moran's I on the residuals is 0.22, p = .008. The covariates explain part of the map and leave a pattern behind.

03

Two kinds of dependence

Read

The two standard models put the map in different places.

Spatial lag: an area's outcome depends on its neighbors' outcomes.

y=ρWy+Xβ+εy = \rho W y + X\beta + \varepsilon

Spatial error: the unmeasured part is shared between neighbors.

y=Xβ+u,u=λWu+εy = X\beta + u, \qquad u = \lambda W u + \varepsilon

A spatial lag modelSpatial lag modelEach site's outcome depends on its neighbors' outcomes through ρ, so a change at one site spills over to others. implies spillovers. A spatial error modelSpatial error modelUnmeasured influences are shared between neighbors through λ; coefficients keep their usual meaning. only corrects for shared omitted influences.

04

LM tests point the way

Read

Lagrange multiplier tests start from the ordinary regression, without fitting either spatial model.

Ordinary regression with LM testsRecorded · Python and R agreeRecorded 2026-11-25 · 42 values compared
R

LM error = 5.21, p = .023; LM lag = 8.90, p = .003

Squared correlation of fit
0.5524
AIC
382.75
Moran's I of residuals
0.2221
p of residual Moran's I
.008

Plots

Residuals against their neighborsDo sites resemble their neighbors, and which sites break the pattern?
View data
SiteResidual (standardized)Average of neighbors (spatial lag)
10.0313−0.4054
2−0.3335−0.7499
3−0.4772−0.3810
4−1.804−0.1004
50.5819−0.1881
6−0.81900.4894
7−3.1060.6444
8−0.1728−0.3402
90.39680.1027
101.219−0.1047
110.99100.3310
120.8654−0.0138
130.4308−0.2399
141.4540.1380
150.06030.4106
160.32030.8431
17−0.42090.4603
181.1590.8912
191.1591.081
200.31540.1139
21−0.54640.6819
22−0.71030.4534
23−0.1538−0.2812
240.63101.003
251.0020.6441
26−0.82800.4558
270.9750−0.0363
280.64160.3586
291.3450.8587
302.5860.7185
31−1.369−1.100
32−0.73810.2556
33−0.39210.4474
34−1.171−0.7744
35−0.14260.2273
36−1.303−0.6847
371.1620.7033
380.81700.3515
39−0.8265−0.9502
401.105−0.1418
41−0.24460.1559
420.1213−1.237
43−0.3198−0.1689
44−0.5766−0.3264
45−0.8498−0.2862
46−0.1781−1.065
470.10060.4303
48−1.423−0.5775
49−0.5639−0.9497

Assumptions

  • Neighbors chosen for a reason — Neighbors: Queen contiguity, row-standardized (W). The neighbors are part of the model; try a second definition as a sensitivity check.
  • Normal residuals — Shapiro–Wilk on the residuals: p = .450.
  • Equal variance across sites — Regions of very different sizes often have unequal variance; rates from small regions are noisier.
  • Spillover is not proof of a mechanism — A significant lag coefficient can come from omitted variables with a spatial pattern; it does not prove spread.

Coefficients

TermEstimateSEEstimate/SEp
(Intercept)68.6194.73514.490< .001
income−1.5970.3341−4.780< .001
housing−0.27390.1032−2.654.008

Lagrange multiplier tests on the ordinary regression

Testχ²dfp
LM error5.2061.023
Robust LM error0.04391.834
LM lag8.8981.003
Robust LM lag3.7361.053
SARMA (both)8.9422.011
  • Neighbors: Queen contiguity, row-standardized (W).
The exact R script · R R version 4.5.1 (2025-06-13)
# Spatial regression (LM tests, spatial lag and spatial error models)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method spatial.regression 1.1.1 · spec f3d0ddda141a0264
# Dataset: sp_columbus (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/sp_columbus.parquet", col_select = c("crime", "income", "housing", "site")))
n_input <- nrow(df)
df[["site"]] <- factor(df[["site"]], levels = sort(unique(df[["site"]]), method = "radix"))
df <- df[stats::complete.cases(df[c("crime", "income", "housing", "site")]), , drop = FALSE]  # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
  warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("crime", "income", "housing", "site"))  # infinite values stop the run (registry/errors.yaml)

# %% Spatial weights
# The host builds the neighbors once from the options you chose and writes them next to this run, so R and
# Python read the same file. Rows with missing values leave the weights too; the style is re-applied.
wt <- cs_load_weights("target/academy-parity/run-8142/spatial.regression/columbus-lm-tests/out-r")
if (nrow(df) != wt$n) wt <- cs_weights_subset(wt, as.integer(rownames(df)))
n_islands <- length(wt$islands)
neighbours_label <- if (nzchar(wt$description)) wt$description else "the chosen neighbors"
if (n_islands > 0) {
  warnings <- c(warnings, sprintf("%d site(s) have no neighbors; their spatial lag is 0 and local tests skip them.", n_islands))
}
site <- as.character(df[["site"]])

# %% Model
# Lagrange multiplier tests (Anselin 1988; Anselin et al. 1996) and spatial lag or error models by maximum
# likelihood (Ord 1975), with direct and indirect impacts (LeSage & Pace 2009).
Y <- "crime"
X_VARS <- c("income", "housing")
model <- "lm_tests"  # lm_tests | lag | error
alpha <- 0.05
y <- as.numeric(df[[Y]])
X <- vapply(X_VARS, function(v) as.numeric(df[[v]]), numeric(nrow(df)))
if (is.null(dim(X))) X <- matrix(X, nrow = nrow(df))
n <- length(y)
# Inputs the model can't fit stop with a catalog message (registry/errors.yaml), the same in Python: more sites
# than coefficients, and an outcome and predictors that vary.
cs_check_rows(n, length(X_VARS) + 2, "The spatial regression")
cs_check_not_constant(y, Y)
for (v in X_VARS) cs_check_not_constant(df[[v]], v)
if (n_islands > 0) stop(sprintf("%d site(s) have no neighbors. Spatial regression needs every site linked: join islands to their nearest site.", n_islands))
ols <- cs_spr_lm_tests(wt, y, X, X_VARS)
terms <- ols$terms
fit <- NULL
if (model == "lag") fit <- cs_spr_lag_model(wt, y, X, X_VARS)
if (model == "error") fit <- cs_spr_error_model(wt, y, X, X_VARS)
use <- if (!is.null(fit)) fit else ols
beta <- use$beta
se <- use$se
residuals <- use$residuals
z_terms <- beta / se
p_terms <- 2 * stats::pnorm(abs(z_terms), lower.tail = FALSE)
moran <- cs_sp_global_test(wt, residuals, "moran", "randomization", "two_sided")
yhat <- y - residuals
pseudo_r2 <- stats::cor(y, yhat)^2

# %% Assumptions
shapiro_p <- if (n >= 3 && n <= 5000) stats::shapiro.test(residuals)$p.value else NULL
assumptions <- list(
  list(key = "weights_chosen", label = "Neighbors chosen for a reason", status = "info",
       detail = sprintf("Neighbors: %s. The neighbors are part of the model; try a second definition as a sensitivity check.", neighbours_label)),
  list(key = "residual_normal", label = "Normal residuals", status = if (is.null(shapiro_p)) "info" else if (shapiro_p >= 0.05) "pass" else "warn",
       detail = if (is.null(shapiro_p)) "Shapiro–Wilk not run for this many sites." else sprintf("Shapiro–Wilk on the residuals: %s.", cs_fmt_p(shapiro_p))),
  list(key = "equal_variance", label = "Equal variance across sites", status = "info",
       detail = "Regions of very different sizes often have unequal variance; rates from small regions are noisier."),
  list(key = "causal", label = "Spillover is not proof of a mechanism", status = "info",
       detail = "A significant lag coefficient can come from omitted variables with a spatial pattern; it does not prove spread.")
)

# %% Result
t_ <- ols$tests
tp <- ols$p
values <- list(n = n, k = length(terms), sigma2 = use$sigma2, ll = use$ll, aic = use$aic, ll_ols = ols$ll, aic_ols = ols$aic,
               lm_error = t_$lm_error, lm_error_p = tp$lm_error, lm_lag = t_$lm_lag, lm_lag_p = tp$lm_lag,
               rlm_error = t_$rlm_error, rlm_error_p = tp$rlm_error, rlm_lag = t_$rlm_lag, rlm_lag_p = tp$rlm_lag,
               sarma = t_$sarma, sarma_p = tp$sarma, residual_moran = moran$statistic, residual_moran_p = moran$p,
               pseudo_r2 = pseudo_r2, islands = n_islands, missing_share = if (n_input > 0) n_dropped / n_input else 0)
for (k in seq_along(terms)) {
  values[[sprintf("beta[%s]", terms[k])]] <- beta[k]
  values[[sprintf("se[%s]", terms[k])]] <- se[k]
  values[[sprintf("p[%s]", terms[k])]] <- p_terms[k]
}
tables <- list(list(key = "coefficients", title = "Coefficients", columns = list(
  list(key = "term", label = "Term", type = "string"), list(key = "estimate", label = "Estimate", type = "number"), list(key = "se", label = "SE", type = "number"),
  list(key = "z", label = if (!is.null(fit)) "z" else "Estimate/SE", type = "number"), list(key = "p", label = "p", type = "pvalue")),
  rows = lapply(seq_along(terms), function(k) list(term = terms[k], estimate = beta[k], se = se[k], z = z_terms[k], p = p_terms[k]))))
lm_keys <- c("lm_error", "rlm_error", "lm_lag", "rlm_lag", "sarma")
lm_labels <- c("LM error", "Robust LM error", "LM lag", "Robust LM lag", "SARMA (both)")
tables[[2]] <- list(key = "lm", title = "Lagrange multiplier tests on the ordinary regression", columns = list(
  list(key = "test", label = "Test", type = "string"), list(key = "statistic", label = "χ²", type = "number"), list(key = "df", label = "df", type = "integer"), list(key = "p", label = "p", type = "pvalue")),
  rows = lapply(seq_along(lm_keys), function(i) list(test = lm_labels[i], statistic = t_[[lm_keys[i]]], df = if (lm_keys[i] == "sarma") 2L else 1L, p = tp[[lm_keys[i]]])))
statistics <- list(list(key = "pseudo_r2", label = "Squared correlation of fit", value = pseudo_r2), list(key = "aic", label = "AIC", value = use$aic),
                   list(key = "residual_moran", label = "Moran's I of residuals", value = moran$statistic),
                   list(key = "residual_moran_p", label = "p of residual Moran's I", value = moran$p, format = "p"))
if (!is.null(fit)) {
  symbol <- if (model == "lag") "ρ" else "λ"
  coef <- fit$coef
  coef_se <- fit$coef_se
  wald <- cs_spr_wald(coef, coef_se)
  coef_z <- wald[1]
  coef_p <- wald[2]
  lower <- coef - stats::qnorm(0.975) * coef_se
  upper <- coef + stats::qnorm(0.975) * coef_se
  lr <- 2 * (fit$ll - ols$ll)
  lr_p <- stats::pchisq(lr, 1, lower.tail = FALSE)
  values <- c(values, list(coef = coef, coef_se = coef_se, coef_z = coef_z, coef_p = coef_p, lower = lower, upper = upper, lr = lr, lr_p = lr_p))
  statistics <- c(list(list(key = "coef", label = symbol, value = coef), list(key = "coef_se", label = sprintf("SE of %s", symbol), value = coef_se),
                       list(key = "coef_p", label = "p", value = coef_p, format = "p"), list(key = "lr", label = "LR against ordinary regression", value = lr)), statistics)
  model_label <- if (model == "lag") "Spatial lag model" else "Spatial error model"
  what <- if (model == "lag") "outcomes depend on neighboring outcomes" else "unmeasured influences are shared between neighbors"
  verdict <- paste0(sprintf("%s = %.3f (SE %.3f), %s: ", symbol, coef, coef_se, cs_fmt_p(coef_p)),
                    if (coef_p < alpha) sprintf("the data support a model where %s.", what) else sprintf("no clear evidence that %s.", what),
                    sprintf(" Moran's I of the residuals is %.3f, %s.", moran$statistic, cs_fmt_p(moran$p)))
  apa_text <- sprintf("%s = %.2f, SE = %.2f, %s, AIC = %.1f", symbol, coef, coef_se, cs_fmt_p(coef_p), fit$aic)
  if (model == "lag") {
    for (k in seq_along(X_VARS)) {
      values[[sprintf("direct[%s]", X_VARS[k])]] <- fit$direct[k]
      values[[sprintf("indirect[%s]", X_VARS[k])]] <- fit$indirect[k]
      values[[sprintf("total[%s]", X_VARS[k])]] <- fit$total[k]
    }
    tables[[3]] <- list(key = "impacts", title = "Average impacts: effect at the site, spillover to others, and both", columns = list(
      list(key = "term", label = "Term", type = "string"), list(key = "direct", label = "Direct", type = "number"), list(key = "indirect", label = "Indirect", type = "number"), list(key = "total", label = "Total", type = "number")),
      rows = lapply(seq_along(X_VARS), function(k) list(term = X_VARS[k], direct = fit$direct[k], indirect = fit$indirect[k], total = fit$total[k])))
  }
} else {
  model_label <- "Ordinary regression with LM tests"
  err <- tp$rlm_error < alpha
  lag <- tp$rlm_lag < alpha
  verdict <- if (tp$lm_error >= alpha && tp$lm_lag >= alpha) {
    "Neither LM test finds spatial dependence in the residuals; ordinary regression looks adequate for these neighbors."
  } else if (err && !lag) {
    "The robust tests point to a spatial error model."
  } else if (lag && !err) {
    "The robust tests point to a spatial lag model."
  } else if (err && lag) {
    "Both robust tests are significant; compare the lag and error models by fit."
  } else {
    "An LM test finds spatial dependence, but the robust tests do not separate lag from error; compare both models."
  }
  apa_text <- sprintf("LM error = %.2f, %s; LM lag = %.2f, %s", t_$lm_error, cs_fmt_p(tp$lm_error), t_$lm_lag, cs_fmt_p(tp$lm_lag))
}
values <- c(values, list(model_label = model_label, verdict = verdict, apa_text = apa_text))
summary <- sprintf("%s of %s on %s (%d sites). %s", model_label, Y, paste(X_VARS, collapse = ", "), n, verdict)
zr <- (residuals - mean(residuals)) / sqrt(mean((residuals - mean(residuals))^2))
charts <- list(cs_chart("residuals", "moran-scatter", "Residuals against their neighbors", list(
  x = cs_col("Residual (standardized)", zr), y = cs_col("Average of neighbors (spatial lag)", cs_weights_lag(wt, zr)),
  site = cs_col("Site", site)), controls = list(slope = moran$statistic)))
for (key in c("coef", "coef_se", "coef_z", "coef_p", "lower", "upper", "lr", "lr_p")) if (is.null(values[[key]])) values[[key]] <- NA_real_  # only some options produce these
cs_publish(list(
  method = "spatial.regression",
  methodVersion = "1.1.1",
  title = model_label,
  engine = cs_engine_info("stats"),
  n = n,
  summary = summary,
  apa = apa_text,
  statistics = statistics,
  tables = tables,
  assumptions = assumptions,
  warnings = warnings,
  notes = c(list(sprintf("Neighbors: %s.", neighbours_label)), if (model == "error" && n < 200) list("With no spatial process at 80 sites this model's tests rejected 6.6% (likelihood ratio) and 7.6% (coefficients) at the 5% level in simulation, and 4.8% at 300 sites. They are asymptotic: read p-values near .05 cautiously below 200 sites.")),
  values = values,
  charts = charts
))
Python

LM error = 5.21, p = .023; LM lag = 8.90, p = .003

Squared correlation of fit
0.5524
AIC
382.75
Moran's I of residuals
0.2221
p of residual Moran's I
.008

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Neighbors chosen for a reason — Neighbors: Queen contiguity, row-standardized (W). The neighbors are part of the model; try a second definition as a sensitivity check.
  • Normal residuals — Shapiro–Wilk on the residuals: p = .450.
  • Equal variance across sites — Regions of very different sizes often have unequal variance; rates from small regions are noisier.
  • Spillover is not proof of a mechanism — A significant lag coefficient can come from omitted variables with a spatial pattern; it does not prove spread.

Coefficients

TermEstimateSEEstimate/SEp
(Intercept)68.6194.73514.490< .001
income−1.5970.3341−4.780< .001
housing−0.27390.1032−2.654.008

Lagrange multiplier tests on the ordinary regression

Testχ²dfp
LM error5.2061.023
Robust LM error0.04391.834
LM lag8.8981.003
Robust LM lag3.7361.053
SARMA (both)8.9422.011
  • Neighbors: Queen contiguity, row-standardized (W).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Spatial regression (LM tests, spatial lag and spatial error models)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method spatial.regression 1.1.1 · spec f3d0ddda141a0264
# Dataset: sp_columbus (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import numpy as np
import pandas as pd
from scipy import stats

import codesplash as cs
from codesplash.errors import check_not_constant
from codesplash.stats import spatial as sp
from codesplash.stats import spatial_reg as spr
from codesplash.stats import spatial_weights as sw

# %% Data
df = pd.read_parquet("tests/parity/fixtures/sp_columbus.parquet", columns=["crime", "income", "housing", "site"])
n_input = len(df)
df["site"] = pd.Categorical(df["site"], categories=sorted(df["site"].dropna().unique()))
df = df.dropna(subset=["crime", "income", "housing", "site"])  # listwise deletion over the analysis columns
df["site"] = df["site"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
    warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
    cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["crime", "income", "housing", "site"])  # infinite values stop the run (registry/errors.yaml)

# %% Spatial weights
# The host builds the neighbors once from the options you chose and writes them next to this run, so Python
# and R read the same file. Rows with missing values leave the weights too; the style is re-applied.
wt = sw.load_weights("target/academy-parity/run-8142/spatial.regression/columbus-lm-tests/out-python")
if len(df) != wt["n"]:
    wt = sw.weights_subset(wt, df.index.to_numpy())
n_islands = len(wt["islands"])
neighbours_label = wt["description"] or "the chosen neighbors"
if n_islands:
    warnings.append(f"{n_islands} site(s) have no neighbors; their spatial lag is 0 and local tests skip them.")
site = df["site"].astype(str).to_numpy()

# %% Model
# Lagrange multiplier tests (Anselin 1988; Anselin et al. 1996) and spatial lag or error models by maximum
# likelihood (Ord 1975), with direct and indirect impacts (LeSage & Pace 2009).
Y = "crime"
X_VARS = ["income", "housing"]
model = "lm_tests"  # lm_tests | lag | error
alpha = 0.05
y = df[Y].to_numpy(dtype=float)
X = df[X_VARS].astype(float).to_numpy()
n = y.size
# Inputs the model can't fit stop with a catalog message (registry/errors.yaml), the same in R: more sites than
# coefficients, and an outcome and predictors that vary.
cs.check_rows(n, len(X_VARS) + 2, "The spatial regression")
check_not_constant(y, Y)
for v in X_VARS:
    check_not_constant(df[v], v)
if n_islands:
    raise ValueError(f"{n_islands} site(s) have no neighbors. Spatial regression needs every site linked: join islands to their nearest site.")
ols = spr.lm_tests(wt, y, X, X_VARS)
terms = ols["terms"]
fit = None
if model == "lag":
    fit = spr.lag_model(wt, y, X, X_VARS)
elif model == "error":
    fit = spr.error_model(wt, y, X, X_VARS)
use = fit if fit else ols
beta, se, residuals = use["beta"], use["se"], use["residuals"]
z_terms = beta / se
p_terms = 2.0 * stats.norm.sf(np.abs(z_terms))
moran = sp.global_test(wt, residuals, "moran", "randomization", "two_sided")
yhat = y - residuals
pseudo_r2 = float(np.corrcoef(y, yhat)[0, 1] ** 2)

# %% Assumptions
shapiro_p = float(stats.shapiro(residuals)[1]) if 3 <= n <= 5000 else None
assumptions = [
    {"key": "weights_chosen", "label": "Neighbors chosen for a reason", "status": "info",
     "detail": f"Neighbors: {neighbours_label}. The neighbors are part of the model; try a second definition as a sensitivity check."},
    {"key": "residual_normal", "label": "Normal residuals", "status": "info" if shapiro_p is None else ("pass" if shapiro_p >= 0.05 else "warn"),
     "detail": "Shapiro–Wilk not run for this many sites." if shapiro_p is None else f"Shapiro–Wilk on the residuals: {cs.fmt_p(shapiro_p)}."},
    {"key": "equal_variance", "label": "Equal variance across sites", "status": "info",
     "detail": "Regions of very different sizes often have unequal variance; rates from small regions are noisier."},
    {"key": "causal", "label": "Spillover is not proof of a mechanism", "status": "info",
     "detail": "A significant lag coefficient can come from omitted variables with a spatial pattern; it does not prove spread."},
]

# %% Result
t, tp = ols["tests"], ols["p"]
values = {"n": n, "k": len(terms), "sigma2": use["sigma2"], "ll": use["ll"], "aic": use["aic"], "ll_ols": ols["ll"], "aic_ols": ols["aic"],
          "lm_error": t["lm_error"], "lm_error_p": tp["lm_error"], "lm_lag": t["lm_lag"], "lm_lag_p": tp["lm_lag"],
          "rlm_error": t["rlm_error"], "rlm_error_p": tp["rlm_error"], "rlm_lag": t["rlm_lag"], "rlm_lag_p": tp["rlm_lag"],
          "sarma": t["sarma"], "sarma_p": tp["sarma"], "residual_moran": moran["statistic"], "residual_moran_p": moran["p"],
          "pseudo_r2": pseudo_r2, "islands": n_islands, "missing_share": n_dropped / n_input if n_input else 0.0}
for k, term in enumerate(terms):
    values[f"beta[{term}]"] = float(beta[k])
    values[f"se[{term}]"] = float(se[k])
    values[f"p[{term}]"] = float(p_terms[k])
tables = [{"key": "coefficients", "title": "Coefficients", "columns": [
    {"key": "term", "label": "Term", "type": "string"}, {"key": "estimate", "label": "Estimate", "type": "number"}, {"key": "se", "label": "SE", "type": "number"},
    {"key": "z", "label": "z" if fit else "Estimate/SE", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"}],
    "rows": [{"term": terms[k], "estimate": float(beta[k]), "se": float(se[k]), "z": float(z_terms[k]), "p": float(p_terms[k])} for k in range(len(terms))]}]
tables.append({"key": "lm", "title": "Lagrange multiplier tests on the ordinary regression", "columns": [
    {"key": "test", "label": "Test", "type": "string"}, {"key": "statistic", "label": "χ²", "type": "number"}, {"key": "df", "label": "df", "type": "integer"}, {"key": "p", "label": "p", "type": "pvalue"}],
    "rows": [{"test": label, "statistic": t[key], "df": 2 if key == "sarma" else 1, "p": tp[key]}
             for key, label in (("lm_error", "LM error"), ("rlm_error", "Robust LM error"), ("lm_lag", "LM lag"), ("rlm_lag", "Robust LM lag"), ("sarma", "SARMA (both)"))]})
statistics = [{"key": "pseudo_r2", "label": "Squared correlation of fit", "value": pseudo_r2}, {"key": "aic", "label": "AIC", "value": use["aic"]},
              {"key": "residual_moran", "label": "Moran's I of residuals", "value": moran["statistic"]},
              {"key": "residual_moran_p", "label": "p of residual Moran's I", "value": moran["p"], "format": "p"}]
if fit:
    symbol = "ρ" if model == "lag" else "λ"
    coef, coef_se = fit["coef"], fit["coef_se"]
    coef_z, coef_p = spr.wald(coef, coef_se)
    lower, upper = coef - stats.norm.ppf(0.975) * coef_se, coef + stats.norm.ppf(0.975) * coef_se
    lr = 2.0 * (fit["ll"] - ols["ll"])
    lr_p = float(stats.chi2.sf(lr, 1))
    values.update({"coef": coef, "coef_se": coef_se, "coef_z": coef_z, "coef_p": coef_p, "lower": lower, "upper": upper, "lr": lr, "lr_p": lr_p})
    statistics = [{"key": "coef", "label": symbol, "value": coef}, {"key": "coef_se", "label": f"SE of {symbol}", "value": coef_se}, {"key": "coef_p", "label": "p", "value": coef_p, "format": "p"},
                  {"key": "lr", "label": "LR against ordinary regression", "value": lr}] + statistics
    model_label = "Spatial lag model" if model == "lag" else "Spatial error model"
    what = "outcomes depend on neighboring outcomes" if model == "lag" else "unmeasured influences are shared between neighbors"
    verdict = (f"{symbol} = {coef:.3f} (SE {coef_se:.3f}), {cs.fmt_p(coef_p)}: " + (f"the data support a model where {what}." if coef_p < alpha else f"no clear evidence that {what}.")
               + f" Moran's I of the residuals is {moran['statistic']:.3f}, {cs.fmt_p(moran['p'])}.")
    apa_text = f"{symbol} = {coef:.2f}, SE = {coef_se:.2f}, {cs.fmt_p(coef_p)}, AIC = {fit['aic']:.1f}"
    if model == "lag":
        for k, term in enumerate(X_VARS):
            values[f"direct[{term}]"] = float(fit["direct"][k])
            values[f"indirect[{term}]"] = float(fit["indirect"][k])
            values[f"total[{term}]"] = float(fit["total"][k])
        tables.append({"key": "impacts", "title": "Average impacts: effect at the site, spillover to others, and both", "columns": [
            {"key": "term", "label": "Term", "type": "string"}, {"key": "direct", "label": "Direct", "type": "number"}, {"key": "indirect", "label": "Indirect", "type": "number"}, {"key": "total", "label": "Total", "type": "number"}],
            "rows": [{"term": term, "direct": float(fit["direct"][k]), "indirect": float(fit["indirect"][k]), "total": float(fit["total"][k])} for k, term in enumerate(X_VARS)]})
else:
    model_label = "Ordinary regression with LM tests"
    err, lag = tp["rlm_error"] < alpha, tp["rlm_lag"] < alpha
    if tp["lm_error"] >= alpha and tp["lm_lag"] >= alpha:
        verdict = "Neither LM test finds spatial dependence in the residuals; ordinary regression looks adequate for these neighbors."
    elif err and not lag:
        verdict = "The robust tests point to a spatial error model."
    elif lag and not err:
        verdict = "The robust tests point to a spatial lag model."
    elif err and lag:
        verdict = "Both robust tests are significant; compare the lag and error models by fit."
    else:
        verdict = "An LM test finds spatial dependence, but the robust tests do not separate lag from error; compare both models."
    apa_text = f"LM error = {t['lm_error']:.2f}, {cs.fmt_p(tp['lm_error'])}; LM lag = {t['lm_lag']:.2f}, {cs.fmt_p(tp['lm_lag'])}"
values.update({"model_label": model_label, "verdict": verdict, "apa_text": apa_text})
summary = f"{model_label} of {Y} on {', '.join(X_VARS)} ({n} sites). {verdict}"
charts = [cs.chart("residuals", "moran-scatter", "Residuals against their neighbors", {
    "x": cs.col("Residual (standardized)", (residuals - residuals.mean()) / residuals.std(ddof=0)),
    "y": cs.col("Average of neighbors (spatial lag)", sw.weights_lag(wt, (residuals - residuals.mean()) / residuals.std(ddof=0))),
    "site": cs.col("Site", site)}, controls={"slope": moran["statistic"]})]
for key in ["coef", "coef_se", "coef_z", "coef_p", "lower", "upper", "lr", "lr_p"]:  # only some options produce these
    values.setdefault(key, None)
cs.publish({
    "method": "spatial.regression",
    "methodVersion": "1.1.1",
    "title": model_label,
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": n,
    "summary": summary,
    "apa": apa_text,
    "statistics": statistics,
    "tables": tables,
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [f"Neighbors: {neighbours_label}."] + (["With no spatial process at 80 sites this model's tests rejected 6.6% (likelihood ratio) and 7.6% (coefficients) at the 5% level in simulation, and 4.8% at 300 sites. They are asymptotic: read p-values near .05 cautiously below 200 sites."] if model == "error" and n < 200 else []),
    "values": values,
    "charts": charts,
})
  • LM lag: 8.90, p = .003.
  • LM error: 5.21, p = .023.

Each reacts to the other kind of dependence as well, so both can be small at once.

05

Robust LM

Predict

Predict first

Robust versions adjust each test for the other kind of dependence:

  • Robust LM lag: p = .053.
  • Robust LM error: p = .834.

Which model do these lean toward?

The lag modelThe error modelNeither one
Reveal

The lag model. Robust LM error has nothing left to find once lag dependence is allowed for. This is a guide to which model to try, not proof of a spillover.

06

Reading a lag model

Read
Spatial lag modelRecorded · Python and R agreeRecorded 2026-11-25 · 48 values compared
R

ρ = 0.42, SE = 0.12, p < .001, AIC = 375.3

ρ
0.4233
SE of ρ
0.1195
p
< .001
LR against ordinary regression
9.407
Squared correlation of fit
0.6473
AIC
375.35
Moran's I of residuals
0.0331
p of residual Moran's I
.547

Plots

Residuals against their neighborsDo sites resemble their neighbors, and which sites break the pattern?
View data
SiteResidual (standardized)Average of neighbors (spatial lag)
10.1600−0.3786
2−0.3837−0.5570
3−0.3735−0.2683
4−1.458−0.1127
50.6080−0.3289
6−1.2460.3916
7−3.8260.6854
8−0.3016−0.3832
90.1752−0.0825
101.789−0.1237
110.87830.1756
120.8770−0.1793
130.6205−0.4262
141.545−0.1143
15−0.31300.2248
160.00730.6176
170.50830.4787
180.66050.5950
190.97470.6862
20−0.49650.3846
21−0.76650.4778
22−0.68160.3767
230.1431−0.0545
24−0.14730.7416
250.83140.3275
26−1.1520.2822
271.378−0.2225
280.56550.2722
291.1160.5258
302.3680.3009
31−0.9946−0.7142
32−0.17520.1249
33−0.27730.3667
34−0.7872−0.6483
350.01930.0486
36−1.008−0.3229
370.47080.6073
380.74400.1683
39−0.3479−0.5542
400.9664−0.0318
41−0.11340.4660
420.1755−0.8974
43−0.3425−0.2604
44−0.8194−0.2583
45−0.8070−0.3960
460.3395−0.6778
470.60690.4265
48−1.170−0.6277
49−0.5420−0.9322

Assumptions

  • Neighbors chosen for a reason — Neighbors: Queen contiguity, row-standardized (W). The neighbors are part of the model; try a second definition as a sensitivity check.
  • Normal residuals — Shapiro–Wilk on the residuals: p = .026.
  • Equal variance across sites — Regions of very different sizes often have unequal variance; rates from small regions are noisier.
  • Spillover is not proof of a mechanism — A significant lag coefficient can come from omitted variables with a spatial pattern; it does not prove spread.

Coefficients

TermEstimateSEzp
(Intercept)45.6037.2576.284< .001
income−1.0490.3074−3.412< .001
housing−0.26630.0891−2.989.003

Lagrange multiplier tests on the ordinary regression

Testχ²dfp
LM error5.2061.023
Robust LM error0.04391.834
LM lag8.8981.003
Robust LM lag3.7361.053
SARMA (both)8.9422.011

Average impacts: effect at the site, spillover to others, and both

TermDirectIndirectTotal
income−1.101−0.7177−1.819
housing−0.2796−0.1823−0.4618
  • Neighbors: Queen contiguity, row-standardized (W).
The exact R script · R R version 4.5.1 (2025-06-13)
# Spatial regression (LM tests, spatial lag and spatial error models)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method spatial.regression 1.1.1 · spec ff6372e7e137b9b9
# Dataset: sp_columbus (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/sp_columbus.parquet", col_select = c("crime", "income", "housing", "site")))
n_input <- nrow(df)
df[["site"]] <- factor(df[["site"]], levels = sort(unique(df[["site"]]), method = "radix"))
df <- df[stats::complete.cases(df[c("crime", "income", "housing", "site")]), , drop = FALSE]  # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
  warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("crime", "income", "housing", "site"))  # infinite values stop the run (registry/errors.yaml)

# %% Spatial weights
# The host builds the neighbors once from the options you chose and writes them next to this run, so R and
# Python read the same file. Rows with missing values leave the weights too; the style is re-applied.
wt <- cs_load_weights("target/academy-parity/run-8142/spatial.regression/columbus-lag/out-r")
if (nrow(df) != wt$n) wt <- cs_weights_subset(wt, as.integer(rownames(df)))
n_islands <- length(wt$islands)
neighbours_label <- if (nzchar(wt$description)) wt$description else "the chosen neighbors"
if (n_islands > 0) {
  warnings <- c(warnings, sprintf("%d site(s) have no neighbors; their spatial lag is 0 and local tests skip them.", n_islands))
}
site <- as.character(df[["site"]])

# %% Model
# Lagrange multiplier tests (Anselin 1988; Anselin et al. 1996) and spatial lag or error models by maximum
# likelihood (Ord 1975), with direct and indirect impacts (LeSage & Pace 2009).
Y <- "crime"
X_VARS <- c("income", "housing")
model <- "lag"  # lm_tests | lag | error
alpha <- 0.05
y <- as.numeric(df[[Y]])
X <- vapply(X_VARS, function(v) as.numeric(df[[v]]), numeric(nrow(df)))
if (is.null(dim(X))) X <- matrix(X, nrow = nrow(df))
n <- length(y)
# Inputs the model can't fit stop with a catalog message (registry/errors.yaml), the same in Python: more sites
# than coefficients, and an outcome and predictors that vary.
cs_check_rows(n, length(X_VARS) + 2, "The spatial regression")
cs_check_not_constant(y, Y)
for (v in X_VARS) cs_check_not_constant(df[[v]], v)
if (n_islands > 0) stop(sprintf("%d site(s) have no neighbors. Spatial regression needs every site linked: join islands to their nearest site.", n_islands))
ols <- cs_spr_lm_tests(wt, y, X, X_VARS)
terms <- ols$terms
fit <- NULL
if (model == "lag") fit <- cs_spr_lag_model(wt, y, X, X_VARS)
if (model == "error") fit <- cs_spr_error_model(wt, y, X, X_VARS)
use <- if (!is.null(fit)) fit else ols
beta <- use$beta
se <- use$se
residuals <- use$residuals
z_terms <- beta / se
p_terms <- 2 * stats::pnorm(abs(z_terms), lower.tail = FALSE)
moran <- cs_sp_global_test(wt, residuals, "moran", "randomization", "two_sided")
yhat <- y - residuals
pseudo_r2 <- stats::cor(y, yhat)^2

# %% Assumptions
shapiro_p <- if (n >= 3 && n <= 5000) stats::shapiro.test(residuals)$p.value else NULL
assumptions <- list(
  list(key = "weights_chosen", label = "Neighbors chosen for a reason", status = "info",
       detail = sprintf("Neighbors: %s. The neighbors are part of the model; try a second definition as a sensitivity check.", neighbours_label)),
  list(key = "residual_normal", label = "Normal residuals", status = if (is.null(shapiro_p)) "info" else if (shapiro_p >= 0.05) "pass" else "warn",
       detail = if (is.null(shapiro_p)) "Shapiro–Wilk not run for this many sites." else sprintf("Shapiro–Wilk on the residuals: %s.", cs_fmt_p(shapiro_p))),
  list(key = "equal_variance", label = "Equal variance across sites", status = "info",
       detail = "Regions of very different sizes often have unequal variance; rates from small regions are noisier."),
  list(key = "causal", label = "Spillover is not proof of a mechanism", status = "info",
       detail = "A significant lag coefficient can come from omitted variables with a spatial pattern; it does not prove spread.")
)

# %% Result
t_ <- ols$tests
tp <- ols$p
values <- list(n = n, k = length(terms), sigma2 = use$sigma2, ll = use$ll, aic = use$aic, ll_ols = ols$ll, aic_ols = ols$aic,
               lm_error = t_$lm_error, lm_error_p = tp$lm_error, lm_lag = t_$lm_lag, lm_lag_p = tp$lm_lag,
               rlm_error = t_$rlm_error, rlm_error_p = tp$rlm_error, rlm_lag = t_$rlm_lag, rlm_lag_p = tp$rlm_lag,
               sarma = t_$sarma, sarma_p = tp$sarma, residual_moran = moran$statistic, residual_moran_p = moran$p,
               pseudo_r2 = pseudo_r2, islands = n_islands, missing_share = if (n_input > 0) n_dropped / n_input else 0)
for (k in seq_along(terms)) {
  values[[sprintf("beta[%s]", terms[k])]] <- beta[k]
  values[[sprintf("se[%s]", terms[k])]] <- se[k]
  values[[sprintf("p[%s]", terms[k])]] <- p_terms[k]
}
tables <- list(list(key = "coefficients", title = "Coefficients", columns = list(
  list(key = "term", label = "Term", type = "string"), list(key = "estimate", label = "Estimate", type = "number"), list(key = "se", label = "SE", type = "number"),
  list(key = "z", label = if (!is.null(fit)) "z" else "Estimate/SE", type = "number"), list(key = "p", label = "p", type = "pvalue")),
  rows = lapply(seq_along(terms), function(k) list(term = terms[k], estimate = beta[k], se = se[k], z = z_terms[k], p = p_terms[k]))))
lm_keys <- c("lm_error", "rlm_error", "lm_lag", "rlm_lag", "sarma")
lm_labels <- c("LM error", "Robust LM error", "LM lag", "Robust LM lag", "SARMA (both)")
tables[[2]] <- list(key = "lm", title = "Lagrange multiplier tests on the ordinary regression", columns = list(
  list(key = "test", label = "Test", type = "string"), list(key = "statistic", label = "χ²", type = "number"), list(key = "df", label = "df", type = "integer"), list(key = "p", label = "p", type = "pvalue")),
  rows = lapply(seq_along(lm_keys), function(i) list(test = lm_labels[i], statistic = t_[[lm_keys[i]]], df = if (lm_keys[i] == "sarma") 2L else 1L, p = tp[[lm_keys[i]]])))
statistics <- list(list(key = "pseudo_r2", label = "Squared correlation of fit", value = pseudo_r2), list(key = "aic", label = "AIC", value = use$aic),
                   list(key = "residual_moran", label = "Moran's I of residuals", value = moran$statistic),
                   list(key = "residual_moran_p", label = "p of residual Moran's I", value = moran$p, format = "p"))
if (!is.null(fit)) {
  symbol <- if (model == "lag") "ρ" else "λ"
  coef <- fit$coef
  coef_se <- fit$coef_se
  wald <- cs_spr_wald(coef, coef_se)
  coef_z <- wald[1]
  coef_p <- wald[2]
  lower <- coef - stats::qnorm(0.975) * coef_se
  upper <- coef + stats::qnorm(0.975) * coef_se
  lr <- 2 * (fit$ll - ols$ll)
  lr_p <- stats::pchisq(lr, 1, lower.tail = FALSE)
  values <- c(values, list(coef = coef, coef_se = coef_se, coef_z = coef_z, coef_p = coef_p, lower = lower, upper = upper, lr = lr, lr_p = lr_p))
  statistics <- c(list(list(key = "coef", label = symbol, value = coef), list(key = "coef_se", label = sprintf("SE of %s", symbol), value = coef_se),
                       list(key = "coef_p", label = "p", value = coef_p, format = "p"), list(key = "lr", label = "LR against ordinary regression", value = lr)), statistics)
  model_label <- if (model == "lag") "Spatial lag model" else "Spatial error model"
  what <- if (model == "lag") "outcomes depend on neighboring outcomes" else "unmeasured influences are shared between neighbors"
  verdict <- paste0(sprintf("%s = %.3f (SE %.3f), %s: ", symbol, coef, coef_se, cs_fmt_p(coef_p)),
                    if (coef_p < alpha) sprintf("the data support a model where %s.", what) else sprintf("no clear evidence that %s.", what),
                    sprintf(" Moran's I of the residuals is %.3f, %s.", moran$statistic, cs_fmt_p(moran$p)))
  apa_text <- sprintf("%s = %.2f, SE = %.2f, %s, AIC = %.1f", symbol, coef, coef_se, cs_fmt_p(coef_p), fit$aic)
  if (model == "lag") {
    for (k in seq_along(X_VARS)) {
      values[[sprintf("direct[%s]", X_VARS[k])]] <- fit$direct[k]
      values[[sprintf("indirect[%s]", X_VARS[k])]] <- fit$indirect[k]
      values[[sprintf("total[%s]", X_VARS[k])]] <- fit$total[k]
    }
    tables[[3]] <- list(key = "impacts", title = "Average impacts: effect at the site, spillover to others, and both", columns = list(
      list(key = "term", label = "Term", type = "string"), list(key = "direct", label = "Direct", type = "number"), list(key = "indirect", label = "Indirect", type = "number"), list(key = "total", label = "Total", type = "number")),
      rows = lapply(seq_along(X_VARS), function(k) list(term = X_VARS[k], direct = fit$direct[k], indirect = fit$indirect[k], total = fit$total[k])))
  }
} else {
  model_label <- "Ordinary regression with LM tests"
  err <- tp$rlm_error < alpha
  lag <- tp$rlm_lag < alpha
  verdict <- if (tp$lm_error >= alpha && tp$lm_lag >= alpha) {
    "Neither LM test finds spatial dependence in the residuals; ordinary regression looks adequate for these neighbors."
  } else if (err && !lag) {
    "The robust tests point to a spatial error model."
  } else if (lag && !err) {
    "The robust tests point to a spatial lag model."
  } else if (err && lag) {
    "Both robust tests are significant; compare the lag and error models by fit."
  } else {
    "An LM test finds spatial dependence, but the robust tests do not separate lag from error; compare both models."
  }
  apa_text <- sprintf("LM error = %.2f, %s; LM lag = %.2f, %s", t_$lm_error, cs_fmt_p(tp$lm_error), t_$lm_lag, cs_fmt_p(tp$lm_lag))
}
values <- c(values, list(model_label = model_label, verdict = verdict, apa_text = apa_text))
summary <- sprintf("%s of %s on %s (%d sites). %s", model_label, Y, paste(X_VARS, collapse = ", "), n, verdict)
zr <- (residuals - mean(residuals)) / sqrt(mean((residuals - mean(residuals))^2))
charts <- list(cs_chart("residuals", "moran-scatter", "Residuals against their neighbors", list(
  x = cs_col("Residual (standardized)", zr), y = cs_col("Average of neighbors (spatial lag)", cs_weights_lag(wt, zr)),
  site = cs_col("Site", site)), controls = list(slope = moran$statistic)))
for (key in c("coef", "coef_se", "coef_z", "coef_p", "lower", "upper", "lr", "lr_p")) if (is.null(values[[key]])) values[[key]] <- NA_real_  # only some options produce these
cs_publish(list(
  method = "spatial.regression",
  methodVersion = "1.1.1",
  title = model_label,
  engine = cs_engine_info("stats"),
  n = n,
  summary = summary,
  apa = apa_text,
  statistics = statistics,
  tables = tables,
  assumptions = assumptions,
  warnings = warnings,
  notes = c(list(sprintf("Neighbors: %s.", neighbours_label)), if (model == "error" && n < 200) list("With no spatial process at 80 sites this model's tests rejected 6.6% (likelihood ratio) and 7.6% (coefficients) at the 5% level in simulation, and 4.8% at 300 sites. They are asymptotic: read p-values near .05 cautiously below 200 sites.")),
  values = values,
  charts = charts
))
Python

ρ = 0.42, SE = 0.12, p < .001, AIC = 375.3

ρ
0.4233
SE of ρ
0.1195
p
< .001
LR against ordinary regression
9.407
Squared correlation of fit
0.6473
AIC
375.35
Moran's I of residuals
0.0331
p of residual Moran's I
.547

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Neighbors chosen for a reason — Neighbors: Queen contiguity, row-standardized (W). The neighbors are part of the model; try a second definition as a sensitivity check.
  • Normal residuals — Shapiro–Wilk on the residuals: p = .026.
  • Equal variance across sites — Regions of very different sizes often have unequal variance; rates from small regions are noisier.
  • Spillover is not proof of a mechanism — A significant lag coefficient can come from omitted variables with a spatial pattern; it does not prove spread.

Coefficients

TermEstimateSEzp
(Intercept)45.6037.2576.284< .001
income−1.0490.3074−3.412< .001
housing−0.26630.0891−2.989.003

Lagrange multiplier tests on the ordinary regression

Testχ²dfp
LM error5.2061.023
Robust LM error0.04391.834
LM lag8.8981.003
Robust LM lag3.7361.053
SARMA (both)8.9422.011

Average impacts: effect at the site, spillover to others, and both

TermDirectIndirectTotal
income−1.101−0.7177−1.819
housing−0.2796−0.1823−0.4618
  • Neighbors: Queen contiguity, row-standardized (W).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Spatial regression (LM tests, spatial lag and spatial error models)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method spatial.regression 1.1.1 · spec ff6372e7e137b9b9
# Dataset: sp_columbus (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import numpy as np
import pandas as pd
from scipy import stats

import codesplash as cs
from codesplash.errors import check_not_constant
from codesplash.stats import spatial as sp
from codesplash.stats import spatial_reg as spr
from codesplash.stats import spatial_weights as sw

# %% Data
df = pd.read_parquet("tests/parity/fixtures/sp_columbus.parquet", columns=["crime", "income", "housing", "site"])
n_input = len(df)
df["site"] = pd.Categorical(df["site"], categories=sorted(df["site"].dropna().unique()))
df = df.dropna(subset=["crime", "income", "housing", "site"])  # listwise deletion over the analysis columns
df["site"] = df["site"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
    warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
    cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["crime", "income", "housing", "site"])  # infinite values stop the run (registry/errors.yaml)

# %% Spatial weights
# The host builds the neighbors once from the options you chose and writes them next to this run, so Python
# and R read the same file. Rows with missing values leave the weights too; the style is re-applied.
wt = sw.load_weights("target/academy-parity/run-8142/spatial.regression/columbus-lag/out-python")
if len(df) != wt["n"]:
    wt = sw.weights_subset(wt, df.index.to_numpy())
n_islands = len(wt["islands"])
neighbours_label = wt["description"] or "the chosen neighbors"
if n_islands:
    warnings.append(f"{n_islands} site(s) have no neighbors; their spatial lag is 0 and local tests skip them.")
site = df["site"].astype(str).to_numpy()

# %% Model
# Lagrange multiplier tests (Anselin 1988; Anselin et al. 1996) and spatial lag or error models by maximum
# likelihood (Ord 1975), with direct and indirect impacts (LeSage & Pace 2009).
Y = "crime"
X_VARS = ["income", "housing"]
model = "lag"  # lm_tests | lag | error
alpha = 0.05
y = df[Y].to_numpy(dtype=float)
X = df[X_VARS].astype(float).to_numpy()
n = y.size
# Inputs the model can't fit stop with a catalog message (registry/errors.yaml), the same in R: more sites than
# coefficients, and an outcome and predictors that vary.
cs.check_rows(n, len(X_VARS) + 2, "The spatial regression")
check_not_constant(y, Y)
for v in X_VARS:
    check_not_constant(df[v], v)
if n_islands:
    raise ValueError(f"{n_islands} site(s) have no neighbors. Spatial regression needs every site linked: join islands to their nearest site.")
ols = spr.lm_tests(wt, y, X, X_VARS)
terms = ols["terms"]
fit = None
if model == "lag":
    fit = spr.lag_model(wt, y, X, X_VARS)
elif model == "error":
    fit = spr.error_model(wt, y, X, X_VARS)
use = fit if fit else ols
beta, se, residuals = use["beta"], use["se"], use["residuals"]
z_terms = beta / se
p_terms = 2.0 * stats.norm.sf(np.abs(z_terms))
moran = sp.global_test(wt, residuals, "moran", "randomization", "two_sided")
yhat = y - residuals
pseudo_r2 = float(np.corrcoef(y, yhat)[0, 1] ** 2)

# %% Assumptions
shapiro_p = float(stats.shapiro(residuals)[1]) if 3 <= n <= 5000 else None
assumptions = [
    {"key": "weights_chosen", "label": "Neighbors chosen for a reason", "status": "info",
     "detail": f"Neighbors: {neighbours_label}. The neighbors are part of the model; try a second definition as a sensitivity check."},
    {"key": "residual_normal", "label": "Normal residuals", "status": "info" if shapiro_p is None else ("pass" if shapiro_p >= 0.05 else "warn"),
     "detail": "Shapiro–Wilk not run for this many sites." if shapiro_p is None else f"Shapiro–Wilk on the residuals: {cs.fmt_p(shapiro_p)}."},
    {"key": "equal_variance", "label": "Equal variance across sites", "status": "info",
     "detail": "Regions of very different sizes often have unequal variance; rates from small regions are noisier."},
    {"key": "causal", "label": "Spillover is not proof of a mechanism", "status": "info",
     "detail": "A significant lag coefficient can come from omitted variables with a spatial pattern; it does not prove spread."},
]

# %% Result
t, tp = ols["tests"], ols["p"]
values = {"n": n, "k": len(terms), "sigma2": use["sigma2"], "ll": use["ll"], "aic": use["aic"], "ll_ols": ols["ll"], "aic_ols": ols["aic"],
          "lm_error": t["lm_error"], "lm_error_p": tp["lm_error"], "lm_lag": t["lm_lag"], "lm_lag_p": tp["lm_lag"],
          "rlm_error": t["rlm_error"], "rlm_error_p": tp["rlm_error"], "rlm_lag": t["rlm_lag"], "rlm_lag_p": tp["rlm_lag"],
          "sarma": t["sarma"], "sarma_p": tp["sarma"], "residual_moran": moran["statistic"], "residual_moran_p": moran["p"],
          "pseudo_r2": pseudo_r2, "islands": n_islands, "missing_share": n_dropped / n_input if n_input else 0.0}
for k, term in enumerate(terms):
    values[f"beta[{term}]"] = float(beta[k])
    values[f"se[{term}]"] = float(se[k])
    values[f"p[{term}]"] = float(p_terms[k])
tables = [{"key": "coefficients", "title": "Coefficients", "columns": [
    {"key": "term", "label": "Term", "type": "string"}, {"key": "estimate", "label": "Estimate", "type": "number"}, {"key": "se", "label": "SE", "type": "number"},
    {"key": "z", "label": "z" if fit else "Estimate/SE", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"}],
    "rows": [{"term": terms[k], "estimate": float(beta[k]), "se": float(se[k]), "z": float(z_terms[k]), "p": float(p_terms[k])} for k in range(len(terms))]}]
tables.append({"key": "lm", "title": "Lagrange multiplier tests on the ordinary regression", "columns": [
    {"key": "test", "label": "Test", "type": "string"}, {"key": "statistic", "label": "χ²", "type": "number"}, {"key": "df", "label": "df", "type": "integer"}, {"key": "p", "label": "p", "type": "pvalue"}],
    "rows": [{"test": label, "statistic": t[key], "df": 2 if key == "sarma" else 1, "p": tp[key]}
             for key, label in (("lm_error", "LM error"), ("rlm_error", "Robust LM error"), ("lm_lag", "LM lag"), ("rlm_lag", "Robust LM lag"), ("sarma", "SARMA (both)"))]})
statistics = [{"key": "pseudo_r2", "label": "Squared correlation of fit", "value": pseudo_r2}, {"key": "aic", "label": "AIC", "value": use["aic"]},
              {"key": "residual_moran", "label": "Moran's I of residuals", "value": moran["statistic"]},
              {"key": "residual_moran_p", "label": "p of residual Moran's I", "value": moran["p"], "format": "p"}]
if fit:
    symbol = "ρ" if model == "lag" else "λ"
    coef, coef_se = fit["coef"], fit["coef_se"]
    coef_z, coef_p = spr.wald(coef, coef_se)
    lower, upper = coef - stats.norm.ppf(0.975) * coef_se, coef + stats.norm.ppf(0.975) * coef_se
    lr = 2.0 * (fit["ll"] - ols["ll"])
    lr_p = float(stats.chi2.sf(lr, 1))
    values.update({"coef": coef, "coef_se": coef_se, "coef_z": coef_z, "coef_p": coef_p, "lower": lower, "upper": upper, "lr": lr, "lr_p": lr_p})
    statistics = [{"key": "coef", "label": symbol, "value": coef}, {"key": "coef_se", "label": f"SE of {symbol}", "value": coef_se}, {"key": "coef_p", "label": "p", "value": coef_p, "format": "p"},
                  {"key": "lr", "label": "LR against ordinary regression", "value": lr}] + statistics
    model_label = "Spatial lag model" if model == "lag" else "Spatial error model"
    what = "outcomes depend on neighboring outcomes" if model == "lag" else "unmeasured influences are shared between neighbors"
    verdict = (f"{symbol} = {coef:.3f} (SE {coef_se:.3f}), {cs.fmt_p(coef_p)}: " + (f"the data support a model where {what}." if coef_p < alpha else f"no clear evidence that {what}.")
               + f" Moran's I of the residuals is {moran['statistic']:.3f}, {cs.fmt_p(moran['p'])}.")
    apa_text = f"{symbol} = {coef:.2f}, SE = {coef_se:.2f}, {cs.fmt_p(coef_p)}, AIC = {fit['aic']:.1f}"
    if model == "lag":
        for k, term in enumerate(X_VARS):
            values[f"direct[{term}]"] = float(fit["direct"][k])
            values[f"indirect[{term}]"] = float(fit["indirect"][k])
            values[f"total[{term}]"] = float(fit["total"][k])
        tables.append({"key": "impacts", "title": "Average impacts: effect at the site, spillover to others, and both", "columns": [
            {"key": "term", "label": "Term", "type": "string"}, {"key": "direct", "label": "Direct", "type": "number"}, {"key": "indirect", "label": "Indirect", "type": "number"}, {"key": "total", "label": "Total", "type": "number"}],
            "rows": [{"term": term, "direct": float(fit["direct"][k]), "indirect": float(fit["indirect"][k]), "total": float(fit["total"][k])} for k, term in enumerate(X_VARS)]})
else:
    model_label = "Ordinary regression with LM tests"
    err, lag = tp["rlm_error"] < alpha, tp["rlm_lag"] < alpha
    if tp["lm_error"] >= alpha and tp["lm_lag"] >= alpha:
        verdict = "Neither LM test finds spatial dependence in the residuals; ordinary regression looks adequate for these neighbors."
    elif err and not lag:
        verdict = "The robust tests point to a spatial error model."
    elif lag and not err:
        verdict = "The robust tests point to a spatial lag model."
    elif err and lag:
        verdict = "Both robust tests are significant; compare the lag and error models by fit."
    else:
        verdict = "An LM test finds spatial dependence, but the robust tests do not separate lag from error; compare both models."
    apa_text = f"LM error = {t['lm_error']:.2f}, {cs.fmt_p(tp['lm_error'])}; LM lag = {t['lm_lag']:.2f}, {cs.fmt_p(tp['lm_lag'])}"
values.update({"model_label": model_label, "verdict": verdict, "apa_text": apa_text})
summary = f"{model_label} of {Y} on {', '.join(X_VARS)} ({n} sites). {verdict}"
charts = [cs.chart("residuals", "moran-scatter", "Residuals against their neighbors", {
    "x": cs.col("Residual (standardized)", (residuals - residuals.mean()) / residuals.std(ddof=0)),
    "y": cs.col("Average of neighbors (spatial lag)", sw.weights_lag(wt, (residuals - residuals.mean()) / residuals.std(ddof=0))),
    "site": cs.col("Site", site)}, controls={"slope": moran["statistic"]})]
for key in ["coef", "coef_se", "coef_z", "coef_p", "lower", "upper", "lr", "lr_p"]:  # only some options produce these
    values.setdefault(key, None)
cs.publish({
    "method": "spatial.regression",
    "methodVersion": "1.1.1",
    "title": model_label,
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": n,
    "summary": summary,
    "apa": apa_text,
    "statistics": statistics,
    "tables": tables,
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [f"Neighbors: {neighbours_label}."] + (["With no spatial process at 80 sites this model's tests rejected 6.6% (likelihood ratio) and 7.6% (coefficients) at the 5% level in simulation, and 4.8% at 300 sites. They are asymptotic: read p-values near .05 cautiously below 200 sites."] if model == "error" and n < 200 else []),
    "values": values,
    "charts": charts,
})

ρ\rho = 0.42, 95% CI 0.19 to 0.66. Residual Moran's I falls to 0.03, p = .547.

A change in one area's income changes its crime, which feeds through neighbors and back. So a coefficient isn't the effect. Read the card's impacts table: direct, indirect (spillover) and total.

07

Comparing the fits

Predict

Predict first

You compare AIC for the three models, where lower is better. What do you expect?

Lag wins by a wide marginBoth beat ordinary regression, and sit close togetherOrdinary regression wins
Reveal

Both spatial models beat ordinary regression, and they sit close together.

  • Ordinary regression: 382.8.
  • Spatial lag: 375.3.
  • Spatial error: 377.5, with λ\lambda = 0.55.

The data alone rarely decide between a real spillover and a shared unmeasured cause. That is a question for what you know about the place.

08

Before you write the sentence

Reflect

Suppose ρ\rho is large and positive in your model, and a colleague writes "crime spreads between neighborhoods."

What else could produce that result? Consider the modifiable areal unit problemModifiable areal unit problemResults change when the same data are grouped into different regions; a pattern across counties may not hold across tracts or people.: would other boundaries give the same answer? And the ecological fallacyEcological fallacyAssuming that a pattern across groups or regions holds for the individuals inside them.: does an area-level result say anything about individuals?

Rewrite the sentence so that it says only what the model supports.

09

Check your understanding

Checkpoint

Check yourself

LM lag and LM error are both significant. What should you look at next?

Show the answer

Answer: b

Each plain test responds to both kinds of dependence. The robust forms separate them. Then fit the candidate model and check whether the residuals still cluster.

Check yourself

In a spatial lag model, why isn't β\beta the full effect of a covariate?

Show the answer

Answer: c

Because yy appears on both sides, a change passes through (I−ρW)−1(I - \rho W)^{-1}. The impacts table reports direct, indirect and total effects.

Check yourself

A county-level regression finds that areas with more older residents have higher voter turnout. What may you conclude?

Show the answer

Answer: c

Reading individual behavior from area averages is the ecological fallacy. Results can also shift when you change the zones, which is the modifiable areal unit problem.

10

Do it in CodeSplash

In the app

Start with Ordinary regression with LM tests. Then try Spatial lag or Spatial error if they suggest it, and check whether the residuals still cluster.

This script builds 5 nearest neighbors from longitude and latitude, then computes both LM tests by hand. It matches the nc-lag-knn example: 3.284 and 3.150.

Python
import numpy as np
import pandas as pd

d = pd.read_csv("sp_nc_sids.csv")
n = len(d)
lon, lat = np.radians(d["lon"].to_numpy()), np.radians(d["lat"].to_numpy())

a = (np.sin((lat[:, None] - lat[None, :]) / 2) ** 2
     + np.cos(lat[:, None]) * np.cos(lat[None, :])
     * np.sin((lon[:, None] - lon[None, :]) / 2) ** 2)
h = 2 * np.arcsin(np.sqrt(a))    # great-circle distance
np.fill_diagonal(h, np.inf)

w = np.zeros((n, n))
for i in range(n):
    w[i, np.argsort(h[i])[:5]] = 1 / 5

X = np.column_stack([np.ones(n), d["births79"]])
y = d["rate"].to_numpy()
b = np.linalg.lstsq(X, y, rcond=None)[0]
e = y - X @ b
s2 = e @ e / n

T = np.trace(w.T @ w + w @ w)
M = np.eye(n) - X @ np.linalg.solve(X.T @ X, X.T)
wxb = w @ (X @ b)

lm_error = (e @ w @ e / s2) ** 2 / T
lm_lag = (e @ w @ y / s2) ** 2 / (wxb @ M @ wxb / s2 + T)
print(lm_error, lm_lag)
R
d <- read.csv("sp_nc_sids.csv")
n <- nrow(d)
lon <- d$lon * pi / 180; lat <- d$lat * pi / 180

a <- sin(outer(lat, lat, "-") / 2)^2 +
  outer(cos(lat), cos(lat)) * sin(outer(lon, lon, "-") / 2)^2
h <- 2 * asin(sqrt(a))    # great-circle distance
diag(h) <- Inf

w <- matrix(0, n, n)
for (i in 1:n) w[i, order(h[i, ])[1:5]] <- 1 / 5

X <- cbind(1, d$births79)
y <- d$rate
b <- solve(crossprod(X), crossprod(X, y))
e <- as.vector(y - X %*% b)
s2 <- sum(e^2) / n

T <- sum(diag(t(w) %*% w + w %*% w))
M <- diag(n) - X %*% solve(crossprod(X), t(X))
wxb <- as.vector(w %*% (X %*% b))

lm_error <- (sum(e * (w %*% e)) / s2)^2 / T
lm_lag <- (sum(e * (w %*% y)) / s2)^2 / (sum(wxb * (M %*% wxb)) / s2 + T)
c(lm_error, lm_lag)
11

Recap

Recap
  • Check an ordinary regression's residuals for spatial pattern before trusting its standard errors.
  • LM tests, then their robust forms, suggest a lag or an error model.
  • In a lag model, read the impacts rather than the coefficients.
  • Name the areal-unit problem and the ecological fallacy when you report area-level results.

Concepts in this lesson