neighbayes.models.SARNegBinFlow

class neighbayes.models.SARNegBinFlow(y, X, W, *, pair_effects=None, time_effects=False, dynamic=False, separable=False, origin_effects=None, destination_effects=None, 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]

Reduced-form SAR negative binomial (NB2) origin-destination flow model.

\[y_{ij,t} \sim \operatorname{NegBin}(\mu_{ij,t}, \alpha), \qquad \log \mu_t = A(\rho)^{-1}X_t\beta + c + \tau_t.\]

separable=True pins ρ_w = -ρ_d ρ_o, whose n × n structured sweep scales (and runs on JAX): it slices the exact likelihood, and takes the fixed pair effects c, origin and destination effects and period effects τ (below). The unrestricted flow’s Pólya–Gamma JAX kernel covers the cross-section without effects.

The within transform of the Gaussian panels does not carry to a log link, so the effects are parameters, added to the log-mean after the filter and sampled with the exact likelihood (separable=True):

\[\eta_{t,ij} = (A^{-1}X_t\beta)_{ij} + c_{ij} + \tau_t \quad\text{or}\quad (A^{-1}X_t\beta)_{ij} + \gamma_i + \kappa_j + \tau_t.\]

pair_effects="fixed" (a panel) gives each origin–destination pair a level under a flat prior: the fixed-effects static panel, identified by the within-pair variation alone. Under a flat prior a level inside the filter is a reparameterization of one after it, A^{-1}c ranging over every array as c does. The pair levels absorb every time-invariant column (the intercept, log distance, the intra indicator, time-invariant attributes), so ρ is identified by the time-varying columns. A pair with no count in any (live) period has no proper posterior and leaves the likelihood; its level is NaN and it predicts zero counts. The posterior integrates each level out rather than profiling it, and the NB2 log-mean is information-orthogonal to α, so the posterior of α escapes the leading, order-1/T incidental-parameter bias of the dummy-variable estimator (Lancaster 2002). Pair effects are fixed only: random ones inside the filter tie ρ to the spatial pattern of the pair levels, which moved ρ by ten posterior sd in simulation.

origin_effects and destination_effects ("fixed", or "random"; cross-section or panel) add a level per origin and per destination: the production-, attraction- or doubly constrained gravity model with balancing factors (Griffith & Fischer 2016). Fixed levels take a flat prior, the first set carrying the overall level and a later one holding its first level at 0. Random levels are N(μ, τ²) with τ learned under a half-t(3, *_effect_sd_scale) prior (default 1) and *_effect_mu defaulting to log mean(y) shared between the random levels present. For a row-standardized W the filter maps a column constant along a row (an origin attribute, the intercept) to one again, so the origin levels absorb the intercept and the time-invariant origin attributes, and the destination levels the destination attributes. One set of levels leaves the other side’s ρ well identified; with both, ρ is identified weakly.

time_effects=True adds period levels N(time_effect_mu, time_effect_sigma²) (time_effect_sigma 2.5): beside other effects the first period is the baseline and time_effect_mu defaults to 0; alone, every period has a level, centred on log mean(y), and the intercept is absorbed. Absorbed columns are dropped from the design and their impacts come back as NaN. The posterior holds pair_effect (dims origin, destination), origin_effect, destination_effect, time_effect and the random sets’ *_sd. fit(store_effects=None) keeps every draw of the pair effects when they fit in about 500 MB and otherwise only their posterior mean and sd (idata["pair_effect_summary"]); posterior_predictive needs the draws. NUTS takes the random origin and destination effects and the period effects, not the fixed ones.

The unrestricted panel takes time_effects=True only, its period effects joining the coefficient block of its Pólya–Gamma sampler (NumPy). alpha_fixed holds α at a value; a large one (10-20 times the typical mean count) makes the model an essentially Poisson one (see neighbayes.models._base._nb).

__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, ...])

Sample the posterior of the unrestricted NB2 SAR flow.

fitted_values()

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 flow counts, time-first stacked.

residuals()

Return residuals y - fitted_values.

spatial_diagnostics()

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

inference_data

Return the ArviZ DataTree from the most recent fit.

pymc_model

Return the PyMC model object built for the most recent fit.

fit(draws=2000, tune=1000, chains=4, random_seed=None, *, sampler='gibbs', backend=None, attach_log_abs_det=True, progressbar=True, n_jobs=-1, idata_kwargs=None, **sample_kwargs)[source]

Sample the posterior of the unrestricted NB2 SAR flow.

sampler="gibbs" (default) runs the reduced-form Pólya–Gamma Gibbs sampler with per-period Kronecker solves — the recommended path for NB models. sampler="nuts" uses the PyMC count path (exact likelihood, much slower). The count likelihood carries no |A| change-of-variables term on either path. With attach_log_abs_det (default) the per-draw spatial-filter Jacobian T·log|A(ρ)| is recorded in sample_stats["log_abs_det"] for diagnostics (never folded into log_likelihood); set it False to skip the per-draw resolvent cost at very large N.

backend="auto" (default) takes JAX when it is installed and the configuration has a JAX kernel, else NumPy; NUTS takes "pymc" (its default), "nutpie", "numpyro" or "blackjax". The unrestricted JAX kernel covers the cross-section (T = 1) without effects; panels and period effects (the unrestricted panel’s only effects) run on NumPy.

idata_kwargs={"log_likelihood": True} stores the pointwise log-likelihood (one value per draw, chain, and flow-period) for az.loo on either sampler; off by default, as in PyMC.

fitted_values()[source]

Return fitted values at posterior mean parameters.

Returns:

Posterior-mean fitted values (on the model’s native scale; fixed-effects-transformed for panel models).

Return type:

np.ndarray

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) where side is one of "combined", "dest", "orig".

Return type:

pandas.DataFrame, or (DataFrame, dict)

property inference_data[source]

Return the ArviZ DataTree from the most recent fit.

Returns:

The inference data object, or None if the model has not been fit yet.

Return type:

xarray.DataTree or None

posterior_predictive(n_draws=None, random_seed=None)[source]

Draw posterior-predictive flow counts, time-first stacked.

Returns an array of shape (n_draws, n² · T).

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 logp and the prior under the same model definition used by the NUTS path.

Returns:

The model object used by fit(), or None if the instance has not been fit yet.

Return type:

pymc.Model or None

residuals()[source]

Return residuals y - fitted_values.

Returns:

Residual vector y - fitted_values on the same scale as fitted_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 matrix W to 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) and attrs["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 W was supplied.

See also

spatial_diagnostics_decision

Model-selection decision based on the test results.

impacts

Posterior 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 a graphviz.Digraph (with ASCII fallback if graphviz is not installed).

Return type:

str or graphviz.Digraph

summary(var_names=None, **kwargs)[source]

Return posterior summary table.

Parameters:
var_names : list, optional

Variable names to include in the summary.

**kwargs

Additional arguments passed to arviz.summary().

Returns:

Posterior summary statistics.

Return type:

pandas.DataFrame