neighbayes.models.SARFlow¶
-
class neighbayes.models.SARFlow(y, X, W, *, pair_effects=
None, time_effects=False, dynamic=False, separable=False, T=1, col_names=None, k=None, priors=None, logdet_method=None, nonnegative_dependence=True, robust=False, shared_od_covariates=None, logdet_decomp='auto')[source]¶ Bayesian SAR origin-destination flow model.
\[y_t = \rho_d W_d y_t + \rho_o W_o y_t + \rho_w W_w y_t + X_t\beta + \varepsilon_t\]The unrestricted flow’s
fit()runs the resolvent-gradient sampler;sampler="nuts"runs PyMC with the exact trace-series Jacobian.separable=Truepins \(\rho_w = -\rho_d\rho_o\) and samples by NUTS.- yarray-like
The flows:
(n, n)or(n²,)for a cross-section;(T, n, n),(T, n²)or(n² T,)for a panel, periods stacked time-first.- Xnp.ndarray or pandas.DataFrame, shape (n² T, p)
Origin-destination design, typically from
flow_design_matrix(); DataFrame columns are kept as feature names.- Wlibpysal.graph.Graph or scipy.sparse / dense (n×n) matrix
Row-standardized regional weights on n units.
- Tint, default 1
Number of periods;
1is the cross-section.- pair_effects{None, “fixed”}, default None
Fixed origin-destination pair effects (panels only), concentrated out by the within transform; columns fixed within pairs are absorbed.
- time_effectsbool, default False
Fixed period effects (panels only).
- col_nameslist of str, optional
Column labels for
X.- kint, optional
Number of destination/origin variable pairs, inferred from
dest_*/orig_*column names when omitted.- shared_od_covariatesbool, optional
Whether the destination and origin design blocks are identical; detected when
None. Sets the defaultimpacts(mode="auto").- robustbool, default False
Student-t errors with
νfixed atpriors["nu"](default 4, LeSage’srval), sampled by NUTS.- separablebool, default False
Pin
ρ_w = -ρ_d ρ_o.- logdet_methodstr, optional
The unrestricted filter takes
"trace_series"(exact, from trace moments ofW) or"resolvent"(the stochastic resolvent estimator, run onfit(backend=...));Nonetakes the first for an undirectedWand the second for a directed one. The separable filter takes the single-Wmethods ("exact","cheb","aaa","spline","stochastic") withlogdet_decomp.- logdet_decomp{“auto”, “eig”, “chol”, “lu”}, default “auto”
What supplies the separable filter’s exact log-determinant values.
- nonnegative_dependencebool, default True
The unrestricted filter’s prior:
ρ_d, ρ_o, ρ_w ≥ 0with sum at most 1 (pm.Dirichlet("rho_simplex", a=ones(4))); if False, independentUniform(rho_lower, rho_upper)priors with a quadratic-wall stability potential. The separable filter always takes Uniform priors onρ_dandρ_o.- priorsdict, optional
beta_mu,beta_sigma,sigma2_alpha,sigma2_beta(asOLSFlow),rho_lower,rho_upper(default ±1, ±0.999 separable) andnu.
-
__init__(y, X, W, *, pair_effects=
None, time_effects=False, dynamic=False, separable=False, **kwargs)[source]¶
Methods
__init__(y, X, W, *[, pair_effects, ...])fit([draws, tune, chains, random_seed, ...])Draw samples from the posterior.
Return fitted values at posterior mean parameters.
impacts([draws, return_posterior_samples, ...])Summarize posterior origin/destination/intra/network/total effects.
posterior_predictive([n_draws, random_seed])Draw posterior-predictive samples
y_rep.Return residuals
y - fitted_values.Run Bayesian LM specification tests and return a summary table.
spatial_diagnostics_decision([alpha, format])Return a model-selection decision from Bayesian LM test results.
summary([var_names])Return posterior summary table.
Attributes
Return the ArviZ DataTree from the most recent fit.
Return the PyMC model object built for the most recent fit.
-
fit(draws=
2000, tune=1000, chains=4, random_seed=None, *, sampler=None, backend=None, step_size=0.0005, n_probes=48, n_quad=8, progressbar=True, n_jobs=-1, idata_kwargs=None, **sample_kwargs)[source]¶ Draw samples from the posterior.
- Parameters:¶
- sampler : {"gibbs", "nuts", None}, default None¶
"gibbs"(the default) runs the resolvent-gradient sampler: MALA with a Laplace metric on the spatial parameters givenσ²,βintegrated out, then conjugate Gibbs forβ, σ²; its accuracy improves with the flow sample sizeN;"nuts"runs PyMC.robust=Truetakes NUTS.- backend : str, optional¶
For Gibbs, what runs the resolvent estimator of the log-determinant (the model’s
logdet_method):"auto"(default; JAX when it is installed, else NumPy),"jax"or"numpy"; the exact trace series runs on NumPy. For NUTS,"pymc"(the default),"nutpie","numpyro"or"blackjax".- step_size : float/int¶
Resolvent sampler parameters (Gibbs path only).
- n_probes : float/int¶
Resolvent sampler parameters (Gibbs path only).
- n_quad : float/int¶
Resolvent sampler parameters (Gibbs path only).
- n_jobs : int, default -1¶
Parallel workers for the Gibbs path (
-1= all CPUs).- idata_kwargs : dict, optional¶
{"log_likelihood": True}stores the pointwise log-likelihood (one value per draw, chain, and flow-period) foraz.loo, on either sampler. Off by default, as in PyMC.
-
impacts(draws=
None, return_posterior_samples=False, ci=0.95, mode='auto')[source]¶ Summarize posterior origin/destination/intra/network/total effects.
Wraps
_compute_impacts_posterior()to produce a tidy DataFrame indexed by predictor with posterior means, credible-interval bounds, and Bayesian p-values for each effect type (origin, destination, intra, network, total). Following Thomas-Agnan & LeSage (2014, §83.5.2), when destination and origin design blocks differ the decomposition is reported separately for shocks applied to each side.- Parameters:¶
- draws : int, optional¶
Maximum number of posterior draws to use. Defaults to all.
- return_posterior_samples : bool, default False¶
If True, also return the underlying posterior-draw arrays.
- ci : float, default 0.95¶
Credible-interval coverage.
- mode : {"auto", "combined", "separate"}, default "auto"¶
Controls whether destination- and origin-side effects are summed or reported separately.
"auto"collapses to combined when the destination and origin design blocks are identical (self._shared_od_covariates) and reports both sides otherwise."combined"always sums;"separate"always reports both.
- Returns:¶
Long-format summary indexed by
(predictor, side, effect)wheresideis one of"combined","dest","orig".- Return type:¶
pandas.DataFrame, or (DataFrame, dict)
-
posterior_predictive(n_draws=
None, random_seed=None)[source]¶ Draw posterior-predictive samples
y_rep.For each (subsampled) posterior draw, simulates every period’s flows from the implied data-generating process (
_simulate_y_rep()).
- property pymc_model[source]¶
Return the PyMC model object built for the most recent fit.
For a Gibbs-fitted cross-section the PyMC model is not constructed during sampling; it is built lazily on first access so that downstream consumers (e.g. bridge sampling for marginal likelihoods) can evaluate
logpand the prior under the same model definition used by the NUTS path.
- residuals()[source]¶
Return residuals
y - fitted_values.- Returns:¶
Residual vector
y - fitted_valueson the same scale asfitted_values().- Return type:¶
np.ndarray
- spatial_diagnostics()[source]¶
Run Bayesian LM specification tests and return a summary table.
Looks up the diagnostic suite registered for this model class and calls each test function on this fitted model, collecting the results into a tidy DataFrame. The set of tests depends on the model type — for example, an OLS model runs LM-Lag, LM-Error, LM-SDM-Joint, and LM-SLX-Error-Joint, while an SAR model runs LM-Error, LM-WX, and Robust-LM-WX. Panel models run the
Panel--prefixed analogues (e.g. Panel-LM-Lag).Requires the model to have been fit (
.fit()called) and a spatial weights matrixWto have been supplied at construction time.- Returns:¶
DataFrame indexed by test name with columns:
Column
Description
statistic
Posterior mean of the LM statistic
median
Posterior median of the LM statistic
df
Degrees of freedom for the \(\chi^2\) reference
p_value
Bayesian p-value:
1 - chi2.cdf(mean, df)ci_lower
Lower bound of 95% credible interval (2.5%)
ci_upper
Upper bound of 95% credible interval (97.5%)
The DataFrame has
attrs["model_type"](class name) andattrs["n_draws"](total posterior draws) metadata.- Return type:¶
pandas.DataFrame
- Raises:¶
RuntimeError – If the model has not been fit yet.
ValueError – If no spatial weights matrix
Wwas supplied.
See also
spatial_diagnostics_decisionModel-selection decision based on the test results.
impactsPosterior inference for direct/indirect/total impacts.
Examples
>>> ols = OLS(formula="price ~ income + crime", data=df, W=w) >>> ols.fit() >>> ols.spatial_diagnostics() statistic median df p_value ci_lower ci_upper LM-Lag 3.21 2.98 1 0.073 0.12 8.54 LM-Error 5.67 5.34 1 0.017 0.34 12.10 LM-SDM-Joint 7.89 7.12 4 0.096 1.23 18.32 LM-SLX-Error-Joint 6.45 5.98 4 0.168 0.89 15.67
-
spatial_diagnostics_decision(alpha=
0.05, format='graphviz')[source]¶ Return a model-selection decision from Bayesian LM test results.
Walks the flow decision tree using Bayesian p-values from
spatial_diagnostics()and recommends either the OLS flow baseline (no spatial dependence detected) or the SAR flow model (at least one direction is significant).- Parameters:¶
- alpha : float, default 0.05¶
Significance level for the Bayesian p-values.
- format : {"graphviz", "ascii", "model"}, default "graphviz"¶
Output format.
"model"returns the recommended model name string."ascii"returns an indented box-drawing tree."graphviz"returns agraphviz.Digraph(with ASCII fallback if graphviz is not installed).
- Return type:¶
str or graphviz.Digraph