How to run Bayesian LM specification tests¶
You have a spatial dataset and need to decide which model to fit: is the dependence in the outcome (a lag), in the errors, in the neighbors’ covariates, or some combination? The Lagrange-Multiplier tests answer that before you commit to a specification.
neighbayes evaluates each LM statistic at every posterior draw, so you get a
posterior distribution of the statistic rather than a single point. The full
inventory of tests, their null hypotheses and degrees of freedom, and the
Neyman-orthogonal construction behind the robust variants are in
Supported Models.
import warnings
import libpysal
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from neighbayes.diagnostics.lmtests import (
bayesian_lm_error_sdm_test,
bayesian_lm_error_test,
bayesian_lm_lag_sdem_test,
bayesian_lm_lag_test,
bayesian_lm_sdm_joint_test,
bayesian_lm_slx_error_joint_test,
bayesian_lm_wx_sem_test,
bayesian_lm_wx_test,
bayesian_robust_lm_error_sdem_test,
bayesian_robust_lm_error_test,
bayesian_robust_lm_lag_sdm_test,
bayesian_robust_lm_lag_test,
bayesian_robust_lm_wx_test,
)
from neighbayes.models import OLS, SAR, SDEM, SDM, SEM, SLX
warnings.filterwarnings("ignore", category=FutureWarning)
warnings.filterwarnings("ignore", category=UserWarning)
Set up data and weights¶
We create a simple spatial DGP with known parameters to validate the tests. Under the null hypothesis (no spatial dependence), the Bayesian LM statistics should be small with high p-values.
import geopandas as gpd
from libpysal.graph import Graph
from libpysal.weights import Rook
# Generate data under H0: no spatial dependence
np.random.seed(42)
# Load Columbus dataset for spatial weights
columbus_path = libpysal.examples.get_path("columbus.shp")
gdf = gpd.read_file(columbus_path)
# Create a Graph (modern libpysal API) for neighbayes models
# Row-standardize the graph so spatial models work correctly
g = Graph.build_contiguity(gdf, rook=True).transform("r")
n = g.n
# Legacy W for spreg comparison
w_spreg = Rook.from_shapefile(columbus_path)
w_spreg.transform = "r"
# Get sparse and dense W matrices
W_sparse = g.sparse.tocsr().astype(np.float64)
W_dense = np.array(W_sparse.todense())
# Design matrix
k = 3
X = np.column_stack([np.ones(n), np.random.normal(size=(n, k - 1))])
beta_true = np.array([1.0, 2.0, -1.5])
y = X @ beta_true + np.random.normal(scale=1.0, size=n)
print(f"W shape: {W_sparse.shape}, nnz: {W_sparse.nnz}")
W shape: (49, 49), nnz: 200
Fit the null models the tests need¶
Each test is a score test at the model you fit, of a term that model leaves out, so each needs that model’s posterior:
OLS: LM-Lag, LM-Error and LM-WX, the joint LM-SDM and LM-SLX-Error tests, Robust LM-Lag (robust to the error process), Robust LM-Error (robust to the lag) and Koley & Bera’s Robust LM-WX (robust to the lag). Their lag test robust to \(WX\) is LM-Error at the OLS fit, so it is not run twice.
SAR: LM-WX and LM-Error, Robust LM-WX (robust to the error process) and Robust LM-Error (robust to \(WX\)).
SEM: LM-Lag and LM-WX, Robust LM-Lag (robust to \(WX\)) and Robust LM-WX (robust to the lag).
SLX: LM-Lag and LM-Error, Robust LM-Lag-SDM (robust to the error process) and Robust LM-Error-SDEM (robust to the lag).
SDM and SDEM: LM-Error-SDM and LM-Lag-SDEM, each the one term left.
# Fit OLS model (null for joint tests)
ols_model = OLS(y=y, X=X, W=g)
ols_model.fit(draws=5000, tune=5000, chains=4, random_seed=42)
# Fit SAR model (null for LM-WX and robust LM-WX)
sar_model = SAR(y=y, X=X, W=g)
sar_model.fit(draws=5000, tune=5000, chains=4, random_seed=42)
# Fit SLX model (null for robust LM-Lag-SDM and robust LM-Error-SDEM)
slx_model = SLX(y=y, X=X, W=g)
slx_model.fit(draws=5000, tune=5000, chains=4, random_seed=42)
Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (4 chains in 2 jobs)
NUTS: [beta, sigma2]
Sampling 4 chains for 5_000 tune and 5_000 draw iterations (20_000 + 20_000 draws total) took 13 seconds.
Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (4 chains in 2 jobs)
NUTS: [beta, sigma2]
Sampling 4 chains for 5_000 tune and 5_000 draw iterations (20_000 + 20_000 draws total) took 14 seconds.
Gibbs sampling (sar): 4 chains for 5,000 tune and 5,000 draw iterations (4 x 10,000 = 40,000 draws total)
Sampling took 2s (19,548 draws/s)
<xarray.DataTree>
Group: /
├── Group: /posterior
│ Dimensions: (chain: 4, draw: 5000, coefficient: 5)
│ Coordinates:
│ * chain (chain) int64 32B 0 1 2 3
│ * draw (draw) int64 40kB 0 1 2 3 4 5 ... 4994 4995 4996 4997 4998 4999
│ * coefficient (coefficient) <U4 80B 'x0' 'x1' 'x2' 'W*x1' 'W*x2'
│ Data variables:
│ beta (chain, draw, coefficient) float64 800kB 1.111 2.242 ... 0.1962
│ sigma2 (chain, draw) float64 160kB 1.597 1.393 1.32 ... 1.29 1.257
│ sigma (chain, draw) float64 160kB 1.264 1.18 1.149 ... 1.136 1.121
│ Attributes:
│ created_at: 2026-11-09T15:43:57.514413+00:00
│ creation_library: ArviZ
│ creation_library_version: 1.3.1
│ creation_library_language: Python
│ inference_library: pymc
│ inference_library_version: 6.4.0
│ sample_dims: ['chain', 'draw']
│ sampling_time: 14.163524389266968
│ tuning_steps: 5000
├── Group: /sample_stats
│ Dimensions: (chain: 4, draw: 5000)
│ Coordinates:
│ * chain (chain) int64 32B 0 1 2 3
│ * draw (draw) int64 40kB 0 1 2 3 4 ... 4996 4997 4998 4999
│ Data variables: (12/18)
│ process_time_diff (chain, draw) float64 160kB 0.00105 ... 0.0001773
│ max_energy_error (chain, draw) float64 160kB 0.9167 -0.2973 ... -0.179
│ largest_eigval (chain, draw) float64 160kB nan nan nan ... nan nan
│ step_size (chain, draw) float64 160kB 0.5279 0.5279 ... 0.571
│ step_size_bar (chain, draw) float64 160kB 0.5441 0.5441 ... 0.5554
│ divergences (chain, draw) int64 160kB 0 0 0 0 0 0 ... 0 0 0 0 0 0
│ ... ...
│ diverging (chain, draw) bool 20kB False False ... False False
│ tree_depth (chain, draw) int64 160kB 4 3 3 3 3 3 ... 4 3 4 2 3 2
│ perf_counter_start (chain, draw) float64 160kB 149.8 149.8 ... 158.3
│ reached_max_treedepth (chain, draw) bool 20kB False False ... False False
│ n_steps (chain, draw) float64 160kB 15.0 7.0 7.0 ... 7.0 3.0
│ index_in_trajectory (chain, draw) int64 160kB -7 2 5 3 -5 ... 6 -2 -3 3 2
│ Attributes:
│ created_at: 2026-11-09T15:43:57.539658+00:00
│ creation_library: ArviZ
│ creation_library_version: 1.3.1
│ creation_library_language: Python
│ inference_library: pymc
│ inference_library_version: 6.4.0
│ sample_dims: ['chain', 'draw']
│ sampling_time: 14.163524389266968
│ tuning_steps: 5000
└── Group: /observed_data
Dimensions: (obs_dim_0: 49)
Coordinates:
* obs_dim_0 (obs_dim_0) int64 392B 0 1 2 3 4 5 6 7 ... 42 43 44 45 46 47 48
Data variables:
obs (obs_dim_0) float64 392B 2.206 -0.2238 -0.5325 ... 3.193 -0.03629
Attributes:
created_at: 2026-11-09T15:43:57.543274+00:00
creation_library: ArviZ
creation_library_version: 1.3.1
creation_library_language: Python
inference_library: pymc
inference_library_version: 6.4.0
sample_dims: []Test for a lag, an error, or lagged covariates¶
A plain test assumes the other terms its model leaves out are absent. At the OLS fit the lag and error tests are Anselin’s (1988); the \(WX\) and joint tests are those of Koley & Bera (2024).
# Fit the SEM null required by LM-WX-SEM (Bayesian analogue of Koley–Bera 2024).
sem_model = SEM(y=y, X=X, W=g)
sem_model.fit(draws=2500, tune=2500, chains=2, random_seed=42)
# Non-robust Bayesian LM tests evaluated at the appropriate null model.
non_robust_results = pd.DataFrame(
[
bayesian_lm_lag_test(ols_model).to_series(),
bayesian_lm_error_test(ols_model).to_series(),
bayesian_lm_wx_test(sar_model).to_series(),
bayesian_lm_wx_sem_test(sem_model).to_series(),
bayesian_lm_sdm_joint_test(ols_model).to_series(),
bayesian_lm_slx_error_joint_test(ols_model).to_series(),
],
index=[
"LM-Lag",
"LM-Error",
"LM-WX",
"LM-WX-SEM",
"LM-SDM Joint",
"LM-SLX-Error Joint",
],
)
non_robust_results
Gibbs sampling (sem): 2 chains for 2,500 tune and 2,500 draw iterations (2 x 5,000 = 10,000 draws total)
Sampling took 2s (5,685 draws/s)
| lm_samples | statistic | mean | median | credible_interval | bayes_pvalue | test_type | df | n_draws | k_wx | |
|---|---|---|---|---|---|---|---|---|---|---|
| LM-Lag | [0.589248, 0.787757, 0.565717, 0.886587, 0.481... | 0.646624 | 0.735179 | 0.683626 | (0.272821, 1.508105) | 0.421322 | bayesian_lm_lag | 1 | 20000 | NaN |
| LM-Error | [0.680438, 1.007145, 0.653904, 0.245509, 0.482... | 0.871849 | 0.763176 | 0.685345 | (0.012954, 2.030314) | 0.350444 | bayesian_lm_error | 1 | 20000 | NaN |
| LM-WX | [1.074226, 1.002423, 1.169347, 0.889062, 0.927... | 0.809567 | 0.914688 | 0.848448 | (0.324785, 1.886486) | 0.667121 | bayesian_lm_wx | 2 | 20000 | 2.0 |
| LM-WX-SEM | [0.378774, 0.390767, 0.366606, 0.56892, 0.6279... | 0.261173 | 0.412887 | 0.294577 | (0.026641, 1.550952) | 0.877581 | bayesian_lm_wx_sem | 2 | 5000 | 2.0 |
| LM-SDM Joint | [1.260838, 1.689576, 1.197356, 1.849351, 1.053... | 1.367613 | 1.554619 | 1.449644 | (0.593721, 3.14178) | 0.713144 | bayesian_lm_sdm_joint | 3 | 20000 | 2.0 |
| LM-SLX-Error Joint | [1.156957, 1.650866, 1.089115, 0.880268, 0.909... | 1.367613 | 1.323366 | 1.201304 | (0.35573, 3.015725) | 0.713144 | bayesian_lm_slx_error_joint | 3 | 20000 | 2.0 |
Use the robust variants when both channels may be present¶
Every test here, plain or robust, is Neyman-orthogonal to the parameters its null estimates (Doğan, Taşpınar & Bera 2021), so the estimated lag at a SAR fit does not leak into its \(WX\) test. A robust test also removes the other direction its null leaves at zero (Bera & Yoon 1993). With \(T\) the tested direction and \(R\) the other,
where the scores and information blocks are already orthogonal to the null’s estimates. That keeps the test valid when \(R\) is locally present, at a cost in power when it is not, which is why the decision tree consults the robust pair only when both plain tests reject.
# Robust Bayesian LM tests (Neyman orthogonal score)
robust_results = pd.DataFrame(
[
bayesian_robust_lm_lag_test(ols_model).to_series(),
bayesian_robust_lm_error_test(ols_model).to_series(),
bayesian_robust_lm_lag_sdm_test(slx_model).to_series(),
bayesian_robust_lm_wx_test(sar_model).to_series(),
bayesian_robust_lm_error_sdem_test(slx_model).to_series(),
],
index=[
"Robust LM-Lag",
"Robust LM-Error",
"Robust LM-Lag-SDM",
"Robust LM-WX",
"Robust LM-Error-SDEM",
],
)
robust_results
| lm_samples | statistic | mean | median | credible_interval | bayes_pvalue | test_type | df | n_draws | k_wx | |
|---|---|---|---|---|---|---|---|---|---|---|
| Robust LM-Lag | [0.072691, 0.069424, 0.069586, 0.690528, 0.085... | 0.046219 | 0.253013 | 0.107955 | (0.004055, 1.44902) | 0.829778 | bayesian_robust_lm_lag | 1 | 20000 | NaN |
| Robust LM-Error | [0.163881, 0.288812, 0.157773, 0.04945, 0.0870... | 0.271444 | 0.281010 | 0.183404 | (0.000746, 1.103859) | 0.602365 | bayesian_robust_lm_error | 1 | 20000 | NaN |
| Robust LM-Lag-SDM | [3.95244, 35.651953, 1442.885937, 1133.867281,... | 1.901533 | 113.260850 | 33.307467 | (0.087517, 719.588249) | 0.167907 | bayesian_robust_lm_lag_sdm | 1 | 20000 | 2.0 |
| Robust LM-WX | [71.871622, 58.808362, 19.686134, 0.488989, 0.... | 0.406496 | 28.802283 | 5.970204 | (0.333868, 203.094819) | 0.816076 | bayesian_robust_lm_wx | 2 | 20000 | 2.0 |
| Robust LM-Error-SDEM | [3.816173, 35.318175, 1443.350458, 1133.212866... | 1.792893 | 112.988795 | 33.024422 | (0.085791, 719.541654) | 0.180574 | bayesian_robust_lm_error_sdem | 1 | 20000 | 2.0 |
Read the whole posterior, not just the point statistic¶
A key advantage of the Bayesian approach is that we get a full posterior distribution of the LM statistic, not just a point estimate. This allows us to compute credible intervals and posterior probabilities.
from scipy import stats as sp_stats
# Show six representative posterior LM distributions (a mix of non-robust and
# robust variants). Each panel overlays the chi-squared 95% reference and the
# posterior mean.
panels = [
("LM-Lag", bayesian_lm_lag_test(ols_model)),
("LM-Error", bayesian_lm_error_test(ols_model)),
("LM-WX", bayesian_lm_wx_test(sar_model)),
("LM-SDM Joint", bayesian_lm_sdm_joint_test(ols_model)),
("Robust LM-WX", bayesian_robust_lm_wx_test(sar_model)),
("Robust LM-Lag-SDM", bayesian_robust_lm_lag_sdm_test(slx_model)),
]
fig, axes = plt.subplots(2, 3, figsize=(15, 8))
for ax, (name, res) in zip(axes.flat, panels):
ax.hist(res.lm_samples, bins=50, density=True, alpha=0.7, color="steelblue")
chi2_ref = sp_stats.chi2.ppf(0.95, res.df)
ax.axvline(
chi2_ref,
color="red",
linestyle="--",
label=f"$\\chi^2_{{0.95,\\,df={res.df}}}$ = {chi2_ref:.2f}",
)
ax.axvline(res.mean, color="black", linestyle="-", label=f"Mean = {res.mean:.2f}")
ax.set_title(name)
ax.legend(fontsize=8)
plt.suptitle("Posterior Distributions of Bayesian LM Statistics", fontsize=14)
plt.tight_layout()
plt.show()
Get a recommendation instead of a table¶
Every fitted spatial model exposes spatial_diagnostics() and
spatial_diagnostics_decision(). Each class runs the tests for the terms it
leaves out:
OLS →
LM-Lag,LM-Error,LM-WX,LM-SDM-Joint,LM-SLX-Error-Joint,Robust-LM-Lag,Robust-LM-Error,Robust-LM-WXSAR →
LM-Error,LM-WX,Robust-LM-WX,Robust-LM-ErrorSEM →
LM-Lag,LM-WX,Robust-LM-Lag,Robust-LM-WXSLX →
LM-Lag,LM-Error,Robust-LM-Lag-SDM,Robust-LM-Error-SDEMSDM →
LM-Error-SDMSDEM →
LM-Lag-SDEM
The decision reads a model’s tests by the rule of Anselin et al. (1996), as
spreg’s stge_classic does: no plain rejection keeps the model, a lone plain
rejection adds its term, and when both plain tests reject the robust pair picks
the term, the smaller robust p-value breaking a tie. OLS leaves three terms out:
a lone \(WX\) rejection there points to the SLX; when the lag and the error both
reject, their robust pair decides whether or not \(WX\) also rejects; and when the
lag and \(WX\) reject without the error, Koley & Bera’s robust pair decides, its
lag test being LM-Error there. Fit the recommended model and ask again until its
tests stop rejecting.
# Method-based API: one call returns all wired tests as a DataFrame
ols_model.spatial_diagnostics()
| statistic | median | df | p_value | ci_lower | ci_upper | |
|---|---|---|---|---|---|---|
| test | ||||||
| LM-Lag | 0.646624 | 0.683626 | 1 | 0.421322 | 0.272821 | 1.508105 |
| LM-Error | 0.871849 | 0.685345 | 1 | 0.350444 | 0.012954 | 2.030314 |
| LM-WX | 0.495764 | 0.523576 | 2 | 0.780452 | 0.224693 | 1.093521 |
| LM-SDM-Joint | 1.367613 | 1.449644 | 3 | 0.713144 | 0.593721 | 3.141780 |
| LM-SLX-Error-Joint | 1.367613 | 1.201304 | 3 | 0.713144 | 0.355730 | 3.015725 |
| Robust-LM-Lag | 0.046219 | 0.107955 | 1 | 0.829778 | 0.004055 | 1.449020 |
| Robust-LM-Error | 0.271444 | 0.183404 | 1 | 0.602365 | 0.000746 | 1.103859 |
| Robust-LM-WX | 0.720989 | 0.764910 | 2 | 0.697331 | 0.320116 | 1.635001 |
# The decision routine walks the appropriate tests and returns a recommendation
print("OLS recommends:")
ols_model.spatial_diagnostics_decision()
OLS recommends:
print("SAR recommends:")
sar_model.spatial_diagnostics_decision()
SAR recommends:
print("SLX recommends:")
slx_model.spatial_diagnostics_decision()
SLX recommends:
# SDM/SDEM-aware tests require fitted SDM / SDEM models so the residuals
# include the correct spatial filters.
sdm_model = SDM(y=y, X=X, W=g)
sdm_model.fit(draws=2000, tune=2000, chains=2, random_seed=42)
sdem_model = SDEM(y=y, X=X, W=g)
sdem_model.fit(draws=2000, tune=2000, chains=2, random_seed=42)
pd.DataFrame(
[
bayesian_lm_error_sdm_test(sdm_model).to_series(),
bayesian_lm_lag_sdem_test(sdem_model).to_series(),
],
index=["LM-Error-SDM", "LM-Lag-SDEM"],
)
Gibbs sampling (sdm): 2 chains for 2,000 tune and 2,000 draw iterations (2 x 4,000 = 8,000 draws total)
Sampling took 2s (4,748 draws/s)
Gibbs sampling (sdem): 2 chains for 2,000 tune and 2,000 draw iterations (2 x 4,000 = 8,000 draws total)
Sampling took 2s (4,542 draws/s)
| lm_samples | statistic | mean | median | credible_interval | bayes_pvalue | test_type | df | n_draws | |
|---|---|---|---|---|---|---|---|---|---|
| LM-Error-SDM | [7.238132, 7.210208, 21.751649, 0.115635, 8.08... | 0.377889 | 26.095173 | 7.817006 | (0.013649, 176.119065) | 0.538735 | bayesian_lm_error_sdm | 1 | 4000 |
| LM-Lag-SDEM | [48.031771, 118.477012, 85.83777, 0.10354, 9.4... | 2.324526 | 64.908942 | 25.712499 | (0.05618, 362.000557) | 0.127349 | bayesian_lm_lag_sdem | 1 | 4000 |
Run the same tests on panel data¶
The same Bayesian LM machinery extends to balanced spatial panels. Tests of
the form bayesian_panel_lm_* and bayesian_panel_robust_lm_* are wired into
every panel model (OLS, SAR, SLX, … fitted with time_col or T) and surfaced
through the same spatial_diagnostics() / spatial_diagnostics_decision()
methods.
Below we simulate a small balanced panel (\(N = 81\), \(T = 4\)) from the panel fixed-effects OLS DGP and run the full diagnostic table.
from neighbayes.dgp import simulate_sar
from neighbayes.dgp.utils import rook_grid_weights
from neighbayes.models import OLS
# 9x9 rook grid (N=81), T=4 — small enough to fit quickly but large enough for
# the LM tests to behave well.
N_panel, T_panel = 81, 4
W_panel_dense, W_panel_graph = rook_grid_weights(int(np.sqrt(N_panel)))
# Simulate from a SAR-FE DGP with moderate spatial dependence so the LM-Lag
# direction is clearly significant.
panel_sim = simulate_sar(
N=N_panel,
T=T_panel,
rho=0.4,
beta=np.array([1.0, 2.0]),
W=W_panel_graph,
seed=11,
unit_effects="fixed",
)
panel_model = OLS(
unit_effects="fixed",
time_effects=True,
y=panel_sim["y"],
X=panel_sim["X"],
W=W_panel_graph,
N=N_panel,
T=T_panel, # two-way fixed effects (unit + time)
)
panel_model.fit(draws=600, tune=600, chains=2, random_seed=11, progressbar=False)
panel_model.spatial_diagnostics()
/home/runner/micromamba/envs/test/lib/python3.14/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html
from .autonotebook import tqdm as notebook_tqdm
Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (2 chains in 2 jobs)
NUTS: [beta, sigma2]
Sampling 2 chains for 600 tune and 600 draw iterations (1_200 + 1_200 draws total) took 2 seconds.
We recommend running at least 4 chains for robust computation of convergence diagnostics
| statistic | median | df | p_value | ci_lower | ci_upper | |
|---|---|---|---|---|---|---|
| test | ||||||
| Panel-LM-Lag | 63.197789 | 63.626753 | 1 | 1.887379e-15 | 43.645366 | 92.411028 |
| Panel-LM-Error | 16.509728 | 16.611198 | 1 | 4.840110e-05 | 7.542629 | 31.158101 |
| Panel-LM-WX | 49.227096 | 49.536817 | 1 | 2.279843e-12 | 34.154012 | 70.299746 |
| Panel-LM-SDM-Joint | 65.736824 | 65.992442 | 2 | 5.329071e-15 | 46.265880 | 95.469811 |
| Panel-LM-SLX-Error-Joint | 65.736824 | 66.398238 | 2 | 5.329071e-15 | 45.019974 | 98.031787 |
| Panel-Robust-LM-Lag | 49.227096 | 50.115296 | 1 | 2.279843e-12 | 32.877890 | 71.651510 |
| Panel-Robust-LM-Error | 2.539035 | 2.525869 | 1 | 1.110627e-01 | 0.096849 | 8.098636 |
| Panel-Robust-LM-WX | 2.539035 | 2.558120 | 1 | 1.110627e-01 | 1.130555 | 4.509240 |
print(
f"Panel decision tree (DGP = SAR-FE) recommends: {panel_model.spatial_diagnostics_decision(alpha=0.05, format='model')}"
)
Panel decision tree (DGP = SAR-FE) recommends: SAR
panel_model.spatial_diagnostics_decision(
alpha=0.05,
)
Run them on origin–destination flows¶
Origin–destination flow models in neighbayes.models.flow use Kronecker
weight matrices \(W_d, W_o, W_w\) for destination, origin and network
spillovers. At a fitted OLSFlow the flow suite tests each direction
(bayesian_lm_flow_destination_test, bayesian_lm_flow_origin_test,
bayesian_lm_flow_od_test), all three jointly (bayesian_lm_flow_joint_test),
and each direction robust to the other two. They are the score tests of the
SARFlow lag model at its aspatial null, so a fitted SARFlow, which
estimates those lags, has no suite; nor, yet, do the count flows.
from neighbayes.dgp import simulate_sar_flow
from neighbayes.models import OLSFlow
# Simulate a SAR flow DGP on n=12 spatial units (N = 144 OD pairs).
flow_data = simulate_sar_flow(
n=12,
rho_d=0.35,
rho_o=0.25,
rho_w=0.10,
beta_d=[1.0, -0.5],
beta_o=[0.5, 0.3],
sigma=1.0,
seed=42,
)
y_flow = np.log(flow_data["y_vec"]) # latent SAR scale (DGP default is lognormal)
X_flow = flow_data["X"]
G_flow = flow_data["G"]
ols_flow = OLSFlow(y_flow, X_flow, G_flow, col_names=flow_data["col_names"])
ols_flow.fit(draws=600, tune=600, chains=2, random_seed=42, progressbar=False)
print("Recommended:", ols_flow.spatial_diagnostics_decision(format="model"))
ols_flow.spatial_diagnostics()
Recommended: SARFlow
Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (2 chains in 2 jobs)
NUTS: [beta, sigma2]
Sampling 2 chains for 600 tune and 600 draw iterations (1_200 + 1_200 draws total) took 3 seconds.
We recommend running at least 4 chains for robust computation of convergence diagnostics
| statistic | median | df | p_value | ci_lower | ci_upper | |
|---|---|---|---|---|---|---|
| test | ||||||
| LM-Flow-Destination | 3.263543 | 3.299979 | 1 | 0.070836 | 1.991728 | 5.249362 |
| LM-Flow-Origin | 2.570420 | 2.607987 | 1 | 0.108879 | 1.469282 | 4.355353 |
| LM-Flow-OD | 7.782675 | 7.913769 | 1 | 0.005275 | 4.913512 | 12.327247 |
| LM-Flow-Joint | 10.242362 | 10.386600 | 3 | 0.016614 | 6.507941 | 16.043091 |
| Robust-LM-Flow-Destination | 1.263841 | 1.279551 | 1 | 0.260925 | 0.742305 | 2.111487 |
| Robust-LM-Flow-Origin | 1.342628 | 1.358873 | 1 | 0.246571 | 0.655408 | 2.415518 |
| Robust-LM-Flow-OD | 4.395497 | 4.444480 | 1 | 0.036034 | 2.699288 | 7.088207 |
See also¶
Supported Models — the full test inventory, null hypotheses, degrees of freedom, and the Neyman-orthogonal score
LM tests vs
spreg— cross-implementation check against the classical statisticsLM decision-tree recovery — whether the tree lands on the model that generated the data
How to run spatial block cross-validation — the out-of-sample counterpart to specification testing