Spatial regression, after spreg (PySAL).
ols/3 fits ordinary least squares with spreg's full diagnostic suite: coefficient inference,
White or HAC robust covariances, Jarque-Bera, Breusch-Pagan, Koenker-Bassett and White
heteroskedasticity tests, the condition number, variance inflation factors, and, given a spatial
graph, the Lagrange multiplier tests for spatial lag and error dependence and Moran's I of the
residuals. ml_lag/4 and ml_error/4 are the maximum-likelihood spatial lag and error models.
tsls/5, gm_lag/4, gm_error/4 and gm_combo/4 are the two-stage least squares and GMM
estimators (Kelejian-Prucha, heteroskedasticity-robust and homoskedastic). Results are checked
against spreg 1.9.1 at 1e-9; GMM lambdas, which spreg finds with an early-stopping L-BFGS-B, to
5e-6 (see docs/parity.md).
Like spreg, no weights are ever transformed implicitly: the graph is used exactly as given.
Row-standardize it first (Spatex.Graph.transform(graph, :r)) for the textbook diagnostics.
Examples
iex> y = [3.0, 1.5, 4.0, 1.0, 5.5, 9.0, 2.5, 6.0]
iex> x = [1.0, 2.0, 0.5, 4.0, 3.0, 2.0, 6.0, 5.0]
iex> ols = Spatex.Regression.ols(y, [x], name_x: ["X"])
iex> {ols.n, ols.k, ols.name_x}
{8, 2, ["CONSTANT", "X"]}
iex> Float.round(ols.r2, 4)
0.0121
Summary
Functions
Spatial lag model with GMM spatial error, y = rho W y + X beta + u, u = lambda W u + e
(GM_Combo, GM_Combo_Het, GM_Combo_Hom).
Spatial lag model with spatially autocorrelated errors and coefficients that vary by regime
(spreg.GM_Combo_Regimes, GM_Combo_Het_Regimes, GM_Combo_Hom_Regimes).
GMM spatial error model y = X beta + u, u = lambda W u + e.
Spatial error model with coefficients that vary by regime (spreg.GM_Error_Regimes, with
:yend / :q spreg.GM_Endog_Error_Regimes), with the Kelejian-Prucha, heteroskedastic or
homoskedastic estimator.
Kapoor-Kelejian-Prucha GM estimator of a spatial error panel with random effects,
y = X beta + mu_i + u, u = lambda W u + e (spreg.GM_ErrorRE; spreg.GM_KKP in the
deprecated sp_panels.py is the same estimator).
Spatial two-stage least squares lag model y = rho W y + X beta + e (spreg.GM_Lag).
Spatial lag model with coefficients that vary by regime (spreg.GM_Lag_Regimes).
Maximum-likelihood spatial error model y = X beta + u, u = lambda W u + e
(spreg.ML_Error).
Spatial error panel with individual fixed effects, y = X beta + mu_i + u,
u = lambda W u + e (spreg.ML_ErrorFE).
Spatial error panel with random effects, y = X beta + mu_i + u, u = lambda W u + e
(spreg.ML_ErrorRE, the maintained class of spreg/panel.py).
Maximum-likelihood spatial error model with coefficients that vary by regime
(spreg.ML_Error_Regimes).
Maximum-likelihood spatial lag model y = rho W y + X beta + e (spreg.ML_Lag).
Spatial lag panel with individual fixed effects, y = rho W y + X beta + mu_i + e
(spreg.ML_LagFE), by maximum likelihood on the data demeaned by area.
Spatial lag panel with random effects, y = rho W y + X beta + mu_i + e (spreg.ML_LagRE).
Maximum-likelihood spatial lag model with coefficients that vary by regime
(spreg.ML_Lag_Regimes).
Ordinary least squares of y on x with diagnostics (spreg.OLS).
OLS with coefficients that vary by regime (spreg.OLS_Regimes).
A printable text summary of an OLS fit, modelled on spreg's report (concise, not byte-identical).
Seemingly unrelated regressions (spreg.SUR): one OLS-type equation per element of ys /
xs, estimated jointly by feasible GLS with a common error covariance across equations.
Seemingly unrelated regressions with spatial error processes, estimated by generalized moments
(spreg.SURerrorGM).
Seemingly unrelated regressions with a spatial error process in every equation, estimated by
maximum likelihood (spreg.SURerrorML, spreg 1.9.1).
Seemingly unrelated regressions with a spatial lag in every equation, estimated by three-stage
least squares (spreg.SURlagIV).
Three-stage least squares for a system of equations with endogenous regressors
(spreg.ThreeSLS).
Two-stage least squares (spreg.TSLS) of y on x and the endogenous columns yend,
instrumented by x and q.
Two-stage least squares with coefficients that vary by regime (spreg.TSLS_Regimes).
Functions
@spec gm_combo(term(), term(), Spatex.Graph.t(), keyword()) :: Spatex.Regression.GMCombo.t()
Spatial lag model with GMM spatial error, y = rho W y + X beta + u, u = lambda W u + e
(GM_Combo, GM_Combo_Het, GM_Combo_Hom).
W y is instrumented as in gm_lag/4 (:w_lags, :lag_q) and the errors are modelled as in
gm_error/4; the options of both apply (:estimator defaults to :kp98). With :het, the
coefficient of W y is clamped to +-0.9 in the iterations, as spreg does.
Examples
iex> ring = for i <- 0..7, j <- [rem(i + 1, 8), rem(i + 7, 8)], do: {i, j}
iex> {f, t} = Enum.unzip(ring)
iex> g = Spatex.Graph.from_arrays(f, t, List.duplicate(0.5, 16))
iex> y = [3.0, 1.5, 4.0, 1.0, 5.5, 9.0, 2.5, 6.0]
iex> x = [1.0, 2.0, 0.5, 4.0, 3.0, 2.0, 6.0, 5.0]
iex> m = Spatex.Regression.gm_combo(y, [x], g)
iex> {m.estimator, m.k, List.last(m.name_x)}
{:kp98, 3, "lambda"}
@spec gm_combo_regimes(term(), term(), [term()], Spatex.Graph.t(), keyword()) :: Spatex.Regression.GMComboRegimes.t()
Spatial lag model with spatially autocorrelated errors and coefficients that vary by regime
(spreg.GM_Combo_Regimes, GM_Combo_Het_Regimes, GM_Combo_Hom_Regimes).
y = rho W y + X beta + u, u = lambda W u + e: W y is instrumented as in gm_combo/4
(:w_lags, :lag_q), then the error model of gm_error_regimes/5 is fitted. Returns a
Spatex.Regression.GMComboRegimes.
Options
As gm_error_regimes/5 (:yend, :q, :constant_regi, :cols2regi over x then :yend,
:estimator (:kp98, :het or :hom) with :max_iter, :epsilon, :step1c and :a1,
names, :spreg_compatible; W y is a global coefficient), and:
:regime_lag_sep-false(default): onerhofor all regimes,W yand its instruments built on the whole graph.true: a coefficient ofW yper regime, onegm_combo/4per regime on the regime's subgraph; every coefficient must vary by regime (constant_regi: :oneraises). spreg ties:regime_err_septo it:regime_lag_sep: trueswitchesregime_err_sepon,regime_err_sep: truealone is switched off, both with a warning; withregime_lag_sep: truea:cols2regiother than all-true is reset to:allwith spreg's warning (which it also emits for the default:all).
Examples
iex> ring = fn o -> for i <- 0..5, j <- [rem(i + 1, 6), rem(i + 5, 6)], do: {o + i, o + j} end
iex> {f, t} = Enum.unzip(ring.(0) ++ ring.(6))
iex> g = Spatex.Graph.from_arrays(f, t, List.duplicate(0.5, 24), ids: Enum.to_list(0..11))
iex> y = [3.0, 1.5, 4.0, 1.0, 5.5, 9.0, 2.5, 6.0, 4.5, 2.0, 7.0, 3.5]
iex> x = [1.0, 2.0, 0.5, 4.0, 3.0, 2.0, 6.0, 5.0, 1.5, 3.5, 2.5, 4.5]
iex> regimes = List.duplicate(0, 6) ++ List.duplicate(1, 6)
iex> r = Spatex.Regression.gm_combo_regimes(y, [x], regimes, g, regime_lag_sep: true)
iex> {r.mode, r.name_yend}
{:separate, ["0_W_dep_var", "1_W_dep_var"]}
@spec gm_error(term(), term(), Spatex.Graph.t(), keyword()) :: Spatex.Regression.GMError.t()
GMM spatial error model y = X beta + u, u = lambda W u + e.
The :estimator option selects spreg's class: :kp98 (default, GM_Error; Kelejian and
Prucha 1998), :het (GM_Error_Het; Arraiz et al. 2010, robust to heteroskedasticity) or
:hom (GM_Error_Hom; Drukker, Egger and Prucha 2013). With :yend / :q the corresponding
GM_Endog_Error* model is fitted (2SLS in the second stage).
lambda minimizes a quadratic form in the sample moments. spreg minimizes it with L-BFGS-B,
which stops early (about 1e-6 away from the minimum); Spatex finds the exact minimizer on
[-0.99, 0.99], so lam agrees with spreg to about 5e-6 and quantities derived from it to
about 1e-5 relative (see docs/parity.md). Every other formula is verified at 1e-9 by
feeding spreg's own lambdas.
Options
:estimator-:kp98,:hetor:hom.:max_iter,:epsilon- iteration limit (default1) and convergence threshold (1.0e-5) of:het/:hom.:step1c-:hetonly: weighted second step before iterating (defaultfalse).:a1-:homonly::hom_sc(default),:homor:het.:yend,:q- endogenous variables and instruments.:hard_bound- raise when|lambda| >= 0.99instead of warning (defaultfalse).:slx_lags- spatial lags ofxadded as regressors (spreg'sslx_lags, default0):W x, ..., W^slx_lags xof the non-constant columns, namedW_x,W2_x, ...; needs the weights (the SLX-error model); not available ingm_combo/4.:slx_vars-:all(default) or one boolean per non-constantxcolumn selecting the columns that get SLX terms.:constant,:name_x,:name_y,:name_yend,:name_q- as intsls/5.
As in spreg, :het and :hom evaluate the coefficients at the previous iteration's lambda
(betas lag lam by one step) and :het reports no sig2. Raises ArgumentError on invalid
input.
Examples
iex> g = Spatex.Graph.from_arrays([0, 1, 1, 2, 2, 3, 3, 0], [1, 0, 2, 1, 3, 2, 0, 3], List.duplicate(0.5, 8))
iex> m = Spatex.Regression.gm_error([3.0, 1.5, 4.0, 1.0], [[1.0, 2.0, 0.5, 4.0]], g)
iex> {m.estimator, m.n, List.last(m.name_x)}
{:kp98, 4, "lambda"}
@spec gm_error_regimes(term(), term(), [term()], Spatex.Graph.t(), keyword()) :: Spatex.Regression.GMErrorRegimes.t()
Spatial error model with coefficients that vary by regime (spreg.GM_Error_Regimes, with
:yend / :q spreg.GM_Endog_Error_Regimes), with the Kelejian-Prucha, heteroskedastic or
homoskedastic estimator.
y = X beta + u, u = lambda W u + e by GMM, with the coefficients of every regime (or some of
them) estimated separately. x, :yend and :q follow the input rules of gm_error/4 (the
intercept is added by the function); regimes holds one label per observation (see
Spatex.Input.to_labels/2), sorted for the coefficient order; graph is used as given
(row-standardize it first). Returns a Spatex.Regression.GMErrorRegimes with Chow tests of
equal coefficients across regimes.
Options
:yend,:q- extra endogenous variables and their instruments (the instruments always vary by regime).:constant_regi-:many(default, an intercept per regime) or:one(a global one).:cols2regi-:all(default) or one boolean perxcolumn followed by one per:yendcolumn:truefor a coefficient per regime,falsefor a global one.:regime_err_sep-false(default): onelambdaand one pooled fit on the regime design.true: onegm_error/4per regime on the regime's own subgraph (edges between regimes are dropped; a row-standardized graph is row-standardized again), each with its ownlambda(mode: :separate); spreg requires every coefficient to vary by regime, and this raises otherwise. Columns ofxconstant within a regime are dropped with a warning (spreg fails with a shape error there).:estimator-:kp98(default,GM_Error_Regimes),:het(GM_Error_Het_Regimes) or:hom(GM_Error_Hom_Regimes), each with its Endog variant.:max_iter(default1),:epsilon(1.0e-5) and, for:het,:step1c(false) or, for:hom,:a1(:hom_sc,:homor:het; spreg's regimes classes default to:het) control the iterations as ingm_error/4; passing them with:kp98,:step1cwith:homor:a1with:hetraises. With:het/:homthe covariance, standard errors and z statistics includelambda, the separate Chow tests treatlambdaas one more coefficient, and:hetreports nosig2.:name_x,:name_y,:name_yend,:name_q- as ingm_error/4.:spreg_compatible-false(default): the Chow restrictions use the real coefficient layout (exogenous regime blocks, exogenous globals, endogenous regime blocks, endogenous globals).truereproduces spreg, whoseChowassumes the globals come last; with global exogenous columns and regime-specific endogenous ones (for exampleconstant_regi: :onewith:yend) its endogenous and joint tests compare other coefficients. Coefficients and covariance are never affected, nor are the other cases (seedocs/parity.md).
lambda is found like gm_error/4's (to ~5e-6 of spreg's L-BFGS-B result). The iterations
replicate spreg's regimes classes: the coefficients come from the last second stage, which uses
the lambda of the previous step, and every class but GM_Error_Het_Regimes filters with the
first-step lambda in every iteration (see docs/parity.md). slx_lags, hard_bound,
inv_method, the text summary and GMM_Error_Regimes are not ported.
Examples
iex> ring = fn o -> for i <- 0..5, j <- [rem(i + 1, 6), rem(i + 5, 6)], do: {o + i, o + j} end
iex> {f, t} = Enum.unzip(ring.(0) ++ ring.(6))
iex> g = Spatex.Graph.from_arrays(f, t, List.duplicate(0.5, 24), ids: Enum.to_list(0..11))
iex> y = [3.0, 1.5, 4.0, 1.0, 5.5, 9.0, 2.5, 6.0, 4.5, 2.0, 7.0, 3.5]
iex> x = [1.0, 2.0, 0.5, 4.0, 3.0, 2.0, 6.0, 5.0, 1.5, 3.5, 2.5, 4.5]
iex> regimes = List.duplicate(0, 6) ++ List.duplicate(1, 6)
iex> r = Spatex.Regression.gm_error_regimes(y, [x], regimes, g)
iex> {r.mode, r.name_x}
{:pooled, ["0_CONSTANT", "0_var_1", "1_CONSTANT", "1_var_1", "lambda"]}
@spec gm_kkp(term(), term(), Spatex.Graph.t(), keyword()) :: Spatex.Regression.PanelGMKKP.t()
Kapoor-Kelejian-Prucha GM estimator of a spatial error panel with random effects,
y = X beta + mu_i + u, u = lambda W u + e (spreg.GM_ErrorRE; spreg.GM_KKP in the
deprecated sp_panels.py is the same estimator).
Inputs and options follow ml_error_re/4 (an intercept "CONSTANT" is added; y and every
x variable are n x t matrices): :time_effects, :name_x, :name_y, and
:full_weights(defaultfalse) - weight the six moment conditions with the full matrixXi = diag(sigma_v^4 / (t - 1), sigma_1^4) (x) Tauinstead ofTau = I.
:regimes is not supported (spreg raises NotImplementedError) and raises ArgumentError, as
does slx_lags (an unknown option). Returns a Spatex.Regression.PanelGMKKP.
Three stages: OLS and the within moments give a first lambda and sigma_v^2; the six moments
(within and between) are then minimized, weighted, for (lambda, sigma_v^2, sigma_1^2); a
feasible GLS regression (spatial filter, then I - theta Q1 with
theta = 1 - sigma_v / sigma_1) gives the coefficients and vm. The graph is used as given.
spreg minimizes each stage with L-BFGS-B, which stops early (and, with :full_weights, can
stop far from the minimum). Spatex evaluates the same formulas (to 1e-9 at spreg's own
optimizer results) and finds the exact minimizer: the variance parameters are profiled out as
a non-negative least-squares problem and lambda is minimized on [-0.99, 0.99], walking
downhill from spreg's start. The estimates therefore differ from spreg's by its optimizer
error; see the GM_KKP notes in docs/parity.md. Sparse; no dense n x n matrix is built.
Examples
iex> g = Spatex.Graph.from_arrays([0, 1, 1, 2, 2, 3], [1, 0, 2, 1, 3, 2], [1.0, 1.0, 1.0, 1.0, 1.0, 1.0])
iex> y = [[1.0, 2.0, 1.5], [3.0, 2.5, 4.0], [2.0, 1.0, 1.6], [5.0, 4.0, 4.4]]
iex> x = [[0.2, 0.8, 0.5], [1.1, 0.9, 1.6], [0.4, 0.1, 0.3], [2.0, 1.7, 1.8]]
iex> r = Spatex.Regression.gm_kkp(y, [x], g, name_x: ["x"])
iex> r.name_x
["CONSTANT", "x", "lambda", "sigma2_v", "sigma2_1"]
@spec gm_lag(term(), term(), Spatex.Graph.t(), keyword()) :: Spatex.Regression.GMLag.t()
Spatial two-stage least squares lag model y = rho W y + X beta + e (spreg.GM_Lag).
W y is instrumented by W X, ..., W^w_lags X (and by the lags of the extra instruments with
lag_q: true). Nothing is optimized, so every result agrees with spreg to rounding.
x and the input rules are those of ols/3; graph is a Spatex.Graph used exactly as
given (spreg never transforms weights implicitly).
Options
:yend,:q- extra endogenous variables and their instruments.:w_lags- spatial lag orders used as instruments (default1);:lag_q- also lag the extra instruments (defaulttrue).:robust-nil,:whiteor:hac(needs:gwk; disables the Anselin-Kelejian test);:sig2n_k-n - kscaling (defaultfalse).:spat_diag- the Anselin-Kelejian testak_test(defaulttrue).:spat_impacts-:simple(default),:full,:power,:allornil, as inml_lag/4.:hard_bound- raise instead of warn when|rho| >= 1(defaultfalse).:slx_lags- spatial lags ofxadded as regressors (spreg'sslx_lags, default0):W x, ..., W^slx_lags xof the non-constant columns, namedW_x,W2_x, ...; needs the weights; the instruments ofW ybecome the lagsslx_lags + 1 ..= slx_lags + w_lagsof all original columns (with:yend, the lags ofW^(slx_lags + 1) x), and the impacts follow the spatial Durbin rule ofml_lag/4.:slx_vars-:all(default) or one boolean per non-constantxcolumn selecting the columns that get SLX terms.:constant,:name_x,:name_y,:name_yend,:name_q- as intsls/5.
Regimes are not ported. Raises ArgumentError on invalid input.
Examples
iex> ring = for i <- 0..7, j <- [rem(i + 1, 8), rem(i + 7, 8)], do: {i, j}
iex> {f, t} = Enum.unzip(ring)
iex> g = Spatex.Graph.from_arrays(f, t, List.duplicate(0.5, 16))
iex> y = [3.0, 1.5, 4.0, 1.0, 5.5, 9.0, 2.5, 6.0]
iex> x = [1.0, 2.0, 0.5, 4.0, 3.0, 2.0, 6.0, 5.0]
iex> m = Spatex.Regression.gm_lag(y, [x], g)
iex> {m.n, m.k, List.last(m.name_x), m.w_lags}
{8, 3, "W_dep_var", 1}
@spec gm_lag_regimes(term(), term(), [term()], Spatex.Graph.t(), keyword()) :: Spatex.Regression.GMLagRegimes.t()
Spatial lag model with coefficients that vary by regime (spreg.GM_Lag_Regimes).
y = rho W y + X beta + e by spatial two-stage least squares, with W y instrumented as in
gm_lag/4 and the coefficients of every regime (or some of them) estimated separately.
x, :yend and :q follow the input rules of gm_lag/4 (the intercept is added by the
function); regimes holds one label per observation (see Spatex.Input.to_labels/2), sorted
for the coefficient order; graph is used as given (row-standardize it first). Returns a
Spatex.Regression.GMLagRegimes with Chow tests of equal coefficients across regimes.
Options
:yend,:q- extra endogenous variables and their instruments.:w_lags(default1) and:lag_q(defaulttrue) build the spatial instruments, as ingm_lag/4.:constant_regi-:many(default, an intercept per regime) or:one(a global one).:cols2regi-:all(default) or one boolean perxcolumn followed by one per:yendcolumn:truefor a coefficient per regime,falsefor a global one. The instruments always vary by regime;W yvaries by regime only with:regime_lag_sep.:regime_lag_sep-false(default): onerhofor all regimes,W yand its instruments built on the whole graph, one pooled 2SLS on the regime design.true: a coefficient ofW yper regime, whoseW yand instruments are built on the regime's own subgraph (edges between regimes are dropped; a row-standardized graph is row-standardized again, so regime islands get a zero lag). With every coefficient by regime andconstant_regi: :manythis runs onegm_lag/4per regime (mode: :separate); otherwise it fits the pooled design on the union of the regime subgraphs. A regime needs at least as many observations as there are variables plus two.:regime_err_sep- spreg only honors it together with:regime_lag_sep(which forces it on); alone it is switched off with a warning. It is also switched off, with a warning, underrobust: :hac.:robust-:white(default, as in spreg's regimes models),nilor:hac(with:gwk, a kernelSpatex.Graphover all observations; the spatial diagnostics are then switched off).:sig2n_k(defaultfalse, as ingm_lag/4).:spat_diag- the Anselin-Kelejian test (defaulttrue);:spat_impacts-:simple(default),:full,:power,:allornil, for the non-constant exogenous coefficients, as ingm_lag/4.:hard_bound- raise when|rho| >= 1.:name_x,:name_y,:name_yend,:name_q- as ingm_lag/4.:spreg_compatible-false(default): the Chow restrictions use the real coefficient layout (exogenous regime blocks, exogenous globals, endogenous regime blocks, endogenous globals).truereproduces spreg, whoseChowassumes the globals come last; with global exogenous columns and regime-specific endogenous ones (constant_regi: :oneor a globalxcolumn together with:regime_lag_sepor a regime-specific:yend) its endogenous and joint tests compare other coefficients. Coefficients and covariance are never affected, nor are the other cases (seedocs/parity.md).
slx_lags, robust: 'ogmm', cores, the text summary and GM_Lag_Endog_Regimes
(endogenous regimes) are not ported.
Examples
iex> ring = fn o -> for i <- 0..5, j <- [rem(i + 1, 6), rem(i + 5, 6)], do: {o + i, o + j} end
iex> {f, t} = Enum.unzip(ring.(0) ++ ring.(6))
iex> g = Spatex.Graph.from_arrays(f, t, List.duplicate(0.5, 24), ids: Enum.to_list(0..11))
iex> y = [3.0, 1.5, 4.0, 1.0, 5.5, 9.0, 2.5, 6.0, 4.5, 2.0, 7.0, 3.5]
iex> x = [1.0, 2.0, 0.5, 4.0, 3.0, 2.0, 6.0, 5.0, 1.5, 3.5, 2.5, 4.5]
iex> regimes = List.duplicate(0, 6) ++ List.duplicate(1, 6)
iex> r = Spatex.Regression.gm_lag_regimes(y, [x], regimes, g, robust: nil, regime_lag_sep: true)
iex> {r.mode, r.name_x, r.name_yend}
{:separate, ["0_CONSTANT", "0_var_1", "1_CONSTANT", "1_var_1"], ["0_W_dep_var", "1_W_dep_var"]}
@spec ml_error(term(), term(), Spatex.Graph.t(), keyword()) :: Spatex.Regression.MLError.t()
Maximum-likelihood spatial error model y = X beta + u, u = lambda W u + e
(spreg.ML_Error).
Options and input rules are those of ml_lag/4 without :spat_impacts. lam is found with the
same bounded Brent search. The coefficient covariance is block diagonal (beta and lam are
uncorrelated), and, as in spreg, k and the information criteria do not count lam.
Examples
iex> g = Spatex.Graph.from_arrays([0, 1, 1, 2, 2, 3, 3, 0], [1, 0, 2, 1, 3, 2, 0, 3], List.duplicate(0.5, 8))
iex> y = [3.0, 1.5, 4.0, 1.0]
iex> x = [1.0, 2.0, 0.5, 4.0]
iex> m = Spatex.Regression.ml_error(y, [x], g)
iex> {m.n, m.k, List.last(m.name_x)}
{4, 2, "lambda"}
@spec ml_error_fe(term(), term(), Spatex.Graph.t(), keyword()) :: Spatex.Regression.PanelFE.t()
Spatial error panel with individual fixed effects, y = X beta + mu_i + u,
u = lambda W u + e (spreg.ML_ErrorFE).
Inputs and options are those of ml_lag_fe/4 without :spat_impacts; lam is searched in
[-1, 1]. As in spreg the information criteria do not count lam.
@spec ml_error_re(term(), term(), Spatex.Graph.t(), keyword()) :: Spatex.Regression.PanelREError.t()
Spatial error panel with random effects, y = X beta + mu_i + u, u = lambda W u + e
(spreg.ML_ErrorRE, the maintained class of spreg/panel.py).
Inputs follow ml_lag_re/4 (an intercept "CONSTANT" is added); the options are
:time_effects, :name_x and :name_y. Returns a Spatex.Regression.PanelREError: the
coefficients, lam, phi (the variance ratio sigma_u^2 / sigma^2) and sig2_u.
spreg concentrates the likelihood over (lambda, phi) with the eigen-decomposition of W
(numpy.linalg.eig) and maximizes it with L-BFGS-B (lambda in [-0.999, 0.999]); the
coefficients and variances are then computed with the exact GLS transform. Spatex evaluates the
same formulas (to 1e-9 at a given (lambda, phi)) and finds the optimum with a nested bounded
search accurate to about 1e-10, so lam and phi agree with spreg's to about 1e-5 (spreg
stops at ftol = 1e-9).
The statistic only depends on V diag(1/c) V', so the signs LAPACK gives the eigenvectors do
not matter. Where eigenvalues are repeated the result of numpy.linalg.eig depends on its
basis (non-orthogonal even for a symmetric W, e.g. a square rook lattice) and is not a
likelihood: for a symmetric W Spatex uses the orthonormal eigenvectors (the exact likelihood,
a documented deviation); for a non-symmetric W with repeated eigenvalues, or with complex
eigenvalues, it raises ArgumentError. Dense n x n matrices are built.
Examples
iex> g = Spatex.Graph.from_arrays([0, 1, 1, 2, 2, 3], [1, 0, 2, 1, 3, 2], [1.0, 1.0, 1.0, 1.0, 1.0, 1.0])
iex> y = [[1.0, 2.0, 1.5], [3.0, 2.5, 4.0], [2.0, 1.0, 1.6], [5.0, 4.0, 4.4]]
iex> x = [[0.2, 0.8, 0.5], [1.1, 0.9, 1.6], [0.4, 0.1, 0.3], [2.0, 1.7, 1.8]]
iex> r = Spatex.Regression.ml_error_re(y, [x], g, name_x: ["x"])
iex> r.name_x
["CONSTANT", "x", "lambda", "sigma2_u"]
@spec ml_error_regimes(term(), term(), [term()], Spatex.Graph.t(), keyword()) :: Spatex.Regression.MLErrorRegimes.t()
Maximum-likelihood spatial error model with coefficients that vary by regime
(spreg.ML_Error_Regimes).
y = X beta + u, u = lambda W u + e by maximum likelihood (the base ml_error/4 fit), with
the coefficients of every regime (or some of them) estimated separately. x follows the input
rules of ml_error/4 (the intercept is added by the function); regimes holds one label per
observation (see Spatex.Input.to_labels/2), sorted for the coefficient order; graph is
used as given (row-standardize it first). Returns a Spatex.Regression.MLErrorRegimes with
Chow tests of equal coefficients across regimes.
Options
:constant_regi-:many(default, an intercept per regime) or:one(a global one).:cols2regi-:all(default) or one boolean perxcolumn:truefor a coefficient per regime,falsefor a global one.:regime_err_sep-false(default): onelambdafor all regimes, one ML fit on the regime design.true: alambdaper regime, oneml_error/4fit per regime on the regime's own subgraph (edges between regimes are dropped; a row-standardized graph is row-standardized again, so regime islands get a zero lag). spreg requires every coefficient to vary by regime andconstant_regi: :manyhere, and so does this function (it raises otherwise). Columns constant within a regime are dropped with a warning (spreg fails with a shape error).:method-:full(default),:ordor:lu;:epsilon(1.0e-7) and:max_dense_nas inml_error/4.:name_x,:name_y- variable names.
In the pooled fit spreg lags the original columns and then expands them by regime
(regimes(W [1 | X])), which is not the lag of the regime design; this function reproduces
that construction, so the pooled fit is not ml_error/4 on the regime design wherever
neighbours lie in another regime. slx_lags / slx_vars, regime_lag_sep (ignored by spreg
here), cores, vm and the text summary are not ported. The Chow restrictions are always on
the real coefficient layout (lambda is the last global column, or one more regime-specific
column), so there is no spreg_compatible switch.
Examples
iex> ring = fn o -> for i <- 0..5, j <- [rem(i + 1, 6), rem(i + 5, 6)], do: {o + i, o + j} end
iex> {f, t} = Enum.unzip(ring.(0) ++ ring.(6))
iex> g = Spatex.Graph.from_arrays(f, t, List.duplicate(0.5, 24), ids: Enum.to_list(0..11))
iex> y = [3.0, 1.5, 4.0, 1.0, 5.5, 9.0, 2.5, 6.0, 4.5, 2.0, 7.0, 3.5]
iex> x = [1.0, 2.0, 0.5, 4.0, 3.0, 2.0, 6.0, 5.0, 1.5, 3.5, 2.5, 4.5]
iex> regimes = List.duplicate(0, 6) ++ List.duplicate(1, 6)
iex> r = Spatex.Regression.ml_error_regimes(y, [x], regimes, g, regime_err_sep: true)
iex> {r.mode, r.name_x}
{:separate, ["0_CONSTANT", "0_var_1", "0_lambda", "1_CONSTANT", "1_var_1", "1_lambda"]}
@spec ml_lag(term(), term(), Spatex.Graph.t(), keyword()) :: Spatex.Regression.MLLag.t()
Maximum-likelihood spatial lag model y = rho W y + X beta + e (spreg.ML_Lag).
x and the input rules are those of ols/3 (constant columns dropped, intercept "CONSTANT"
prepended with constant: true). graph is a Spatex.Graph used exactly as given; like spreg
nothing is transformed implicitly, so row-standardize it first
(Spatex.Graph.transform(graph, :r)) for the usual rho in (-1, 1) interpretation.
rho is found with SciPy's bounded Brent search over (-1, 1) (xatol: epsilon), ported
literally, so it agrees with spreg to rounding of the objective (~1e-10 or better with
method: :full; see "Ord method").
Options
:method- how the log-determinantln|I - rho W|is evaluated::full(default, a dense LU per evaluation),:ord(Ord's eigenvalue method: one eigendecomposition, thenO(n)per evaluation) or:lu(spreg's sparse-LU option; evaluated like:full, see below).:epsilon- Brent tolerance and power-expansion threshold (default1.0e-7).:spat_impacts-:simple(default),:full,:power,:allornil: average direct, indirect and total impact multipliers (sp_multipliers) and per-regressorimpacts.:constant,:name_x,:name_y- as inols/3.:slx_lags- spatial lags ofxadded as regressors (spreg'sslx_lags, default0):W x, ..., W^slx_lags xof the non-constant columns, namedW_x,W2_x, ...; needs the weights; withml_lag/4the model is the spatial Durbin model and the impacts follow spreg (total = ati (beta + theta),direct = adi beta,indirect = total - direct).:slx_vars-:all(default) or one boolean per non-constantxcolumn selecting the columns that get SLX terms.:max_dense_n- largestnaccepted (default5_000). All methods build densen x nmatrices for the asymptotic variance (aboutn * n * 8bytes each, several at once), so larger problems raiseArgumentError; raise the limit if you have the memory.
Ord method
:ord uses the eigenvalues of W itself. spreg replaces W by a symmetrized binary matrix
whenever the pattern of W is symmetric, which is only valid for row-standardized binary
weights: for other weights (inverse distance, say) spreg's rho is wrong, and its standard
errors use the symmetrized matrix instead of W in every symmetric case. Spatex does neither;
:ord results therefore equal :full up to the optimizer tolerance and differ from spreg's
ord standard errors (see docs/parity.md).
Differences from spreg
:lu evaluates the determinant with a dense LU (spreg uses a sparse LU without the sign
check); the optimum is identical. The log-determinant is a sum of logarithms, so it cannot
overflow for large n. regimes and the common-factor spat_diag are not ported.
Raises ArgumentError on invalid input or a singular X'X.
Examples
iex> g = Spatex.Graph.from_arrays([0, 1, 1, 2, 2, 3, 3, 0], [1, 0, 2, 1, 3, 2, 0, 3], List.duplicate(0.5, 8))
iex> y = [3.0, 1.5, 4.0, 1.0]
iex> x = [1.0, 2.0, 0.5, 4.0]
iex> m = Spatex.Regression.ml_lag(y, [x], g, max_dense_n: 100)
iex> {m.n, m.k, List.last(m.name_x)}
{4, 3, "W_dep_var"}
@spec ml_lag_fe(term(), term(), Spatex.Graph.t(), keyword()) :: Spatex.Regression.PanelFE.t()
Spatial lag panel with individual fixed effects, y = rho W y + X beta + mu_i + e
(spreg.ML_LagFE), by maximum likelihood on the data demeaned by area.
y is an n x t matrix, one row per area of graph and one column per period: a list of
rows, a {n, t} Nx tensor or an Explorer.DataFrame (see Spatex.Input.to_matrix/2); x is a list of such matrices, one per regressor, or a map name => matrix
(ordered by name). No intercept is used: the fixed effects absorb it. graph is used as given
(row-standardize it first). Returns a Spatex.Regression.PanelFE.
Options
:time_effects- add period dummies (time_2, ...,time_t; defaultfalse).:spat_impacts-:simple(default),:full,:power,:allornil, as inml_lag/4.:epsilon- Brent tolerance (default1.0e-7);rhois searched in[-0.99, 0.99].:name_x,:name_y- variable names.
A regressor without variation over time is absorbed by the fixed effects and raises. The
variance follows spreg literally (its x' W A^-1 X b cross term uses the raw regressors).
Dense n x n matrices are built, so n should stay in the low thousands.
@spec ml_lag_re(term(), term(), Spatex.Graph.t(), keyword()) :: Spatex.Regression.PanelRE.t()
Spatial lag panel with random effects, y = rho W y + X beta + mu_i + e (spreg.ML_LagRE).
Inputs and options are those of ml_lag_fe/4; an intercept "CONSTANT" is added. spreg
alternates a bounded search for the variance ratio phi (quasi-demeaning
v - (1 - phi) mean_t(v)) with one for rho until phi changes by less than 1e-7 (at
most 100 rounds). Returns a Spatex.Regression.PanelRE.
ml_error_re/4 is the corresponding error model.
@spec ml_lag_regimes(term(), term(), [term()], Spatex.Graph.t(), keyword()) :: Spatex.Regression.MLLagRegimes.t()
Maximum-likelihood spatial lag model with coefficients that vary by regime
(spreg.ML_Lag_Regimes).
y = rho W y + X beta + e by maximum likelihood (the base ml_lag/4 fit), with the
coefficients of every regime (or some of them) estimated separately. x follows the input
rules of ml_lag/4 (the intercept is added by the function); regimes holds one label per
observation (see Spatex.Input.to_labels/2), sorted for the coefficient order; graph is
used as given (row-standardize it first). Returns a Spatex.Regression.MLLagRegimes with
Chow tests of equal coefficients across regimes.
Options
:constant_regi-:many(default, an intercept per regime) or:one(a global one).:cols2regi-:all(default) or one boolean perxcolumn:truefor a coefficient per regime,falsefor a global one.:regime_lag_sep-false(default): onerhofor all regimes, one ML fit on the regime design.true: arhoper regime, oneml_lag/4fit per regime on the regime's own subgraph (edges between regimes are dropped; a row-standardized graph is row-standardized again, so regime islands get a zero lag). spreg requires every coefficient to vary by regime andconstant_regi: :manyhere, and so does this function (it raises otherwise). A regime needs at least as many observations as there are variables plus two; columns constant within a regime are dropped with a warning (spreg fails with a shape error).:method-:full(default),:ordor:lu;:epsilon(1.0e-7) and:max_dense_nas inml_lag/4.:spat_impacts-:simple(default),:full,:power,:allornil: the multipliers and the effects of the non-constant coefficients.:name_x,:name_y- variable names.
spreg's class has no regime_err_sep (it is always false; passing it raises here, as spreg
raises a TypeError). slx_lags / slx_vars (and with them the common-factor test
spat_diag), cores, vm and the text summary are not ported. Unlike the 2SLS regimes
models the Chow restrictions are always on the real coefficient layout (rho is the last
global column, or one more regime-specific column), so there is no spreg_compatible switch.
Examples
iex> ring = fn o -> for i <- 0..5, j <- [rem(i + 1, 6), rem(i + 5, 6)], do: {o + i, o + j} end
iex> {f, t} = Enum.unzip(ring.(0) ++ ring.(6))
iex> g = Spatex.Graph.from_arrays(f, t, List.duplicate(0.5, 24), ids: Enum.to_list(0..11))
iex> y = [3.0, 1.5, 4.0, 1.0, 5.5, 9.0, 2.5, 6.0, 4.5, 2.0, 7.0, 3.5]
iex> x = [1.0, 2.0, 0.5, 4.0, 3.0, 2.0, 6.0, 5.0, 1.5, 3.5, 2.5, 4.5]
iex> regimes = List.duplicate(0, 6) ++ List.duplicate(1, 6)
iex> r = Spatex.Regression.ml_lag_regimes(y, [x], regimes, g, regime_lag_sep: true)
iex> {r.mode, r.name_x}
{:separate, ["0_CONSTANT", "0_var_1", "0_W_dep_var", "1_CONSTANT", "1_var_1", "1_W_dep_var"]}
@spec ols(term(), term(), keyword()) :: Spatex.Regression.OLS.t()
Ordinary least squares of y on x with diagnostics (spreg.OLS).
x is a list of columns, a map of name => column (columns ordered by name), an {n, k}
Nx.Tensor, an Explorer.DataFrame (all its columns), or a single column. Columns may be lists,
Nx vectors or Explorer.Series. Like spreg, constant columns of x are dropped (with an entry
in warnings) and, with constant: true, an intercept named "CONSTANT" is prepended.
Options
:constant- add the intercept (defaulttrue). Withfalsethe columns are used as given (spreg'sBaseOLS); spatial diagnostics then need the constant and are rejected.:name_x,:name_y- variable names (defaultsvar_1,var_2, ... anddep_var; a map or DataFrame supplies its own names).:robust-nil(default),:whiteor:hac.:sig2n_k- estimate sigma-squared withn - kinstead ofn(defaulttrue).:gwk- kernelSpatex.Graphforrobust: :hac; its diagonal must be exactly 1 and its off-diagonal weights in[0, 1]. The HAC covariance is not symmetrized, like spreg's.:graph- spatial weights for:spat_diag/:moran, used as given.:nonspat_diag- F, log-likelihood, AIC/BIC, condition number, Jarque-Bera, Breusch-Pagan and Koenker-Bassett tests (defaulttrue).:white_test- White's test (defaultfalse; unavailable with robust errors).:vif- variance inflation factors (defaultfalse).:slx_lags- spatial lags ofxadded as regressors (spreg'sslx_lags, default0):W x, ..., W^slx_lags xof the non-constant columns, namedW_x,W2_x, ...; needs the weights (:graph). With SLX terms the WX-based LM tests (lm_wx,lm_spdurbin,rlm_wx,rlm_durlag,lm_slxerr) arenil, as in spreg.:slx_vars-:all(default) or one boolean per non-constantxcolumn selecting the columns that get SLX terms.:spat_diag- LM tests;:moran- Moran's I of the residuals. Both need:graph; spatial diagnostics are skipped forrobust: :hac, as in spreg. Graphs with a link-free structure raise.
Raises ArgumentError on invalid input, including an exactly singular X'X.
Examples
iex> y = [3.0, 1.5, 4.0, 1.0, 5.5, 9.0, 2.5, 6.0]
iex> ols = Spatex.Regression.ols(y, %{"A" => [1, 2, 0.5, 4, 3, 2, 6, 5]})
iex> Float.round(hd(ols.betas), 4)
4.5072
@spec ols_regimes(term(), term(), [term()], keyword()) :: Spatex.Regression.OLSRegimes.t()
OLS with coefficients that vary by regime (spreg.OLS_Regimes).
regimes holds one label per observation (a list, Nx vector or Explorer.Series; see Spatex.Input.to_labels/2), sorted for the coefficient order. x and the input
rules are those of ols/3; the intercept is added by the function. Returns a
Spatex.Regression.OLSRegimes with Chow tests of equal coefficients across regimes.
Options
:constant_regi-:many(default, an intercept per regime) or:one(a global one).:cols2regi-:all(default) or one boolean perxcolumn:truefor a coefficient per regime,falsefor a global one.:regime_err_sep-true(default): with every coefficient by regime andconstant_regi: :many, one OLS per regime (each with its own error variance); otherwise the pooled fit is re-weighted by each regime's residual variance (unless:robustis set).falsefits one pooled OLS with a common error variance.:robust-nil(default) or:white.:sig2n_k(defaulttrue),:name_x,:name_yas inols/3. Columns constant within a regime are dropped in the separate fits, with a warning, as in spreg.
Spatial diagnostics, :hac and slx_lags are not available with regimes.
Examples
iex> y = [3.0, 1.5, 4.0, 1.0, 5.5, 9.0, 2.5, 6.0]
iex> r = Spatex.Regression.ols_regimes(y, [[1, 2, 0.5, 4, 3, 2, 6, 5]], [0, 0, 0, 0, 1, 1, 1, 1])
iex> {r.mode, r.name_x}
{:separate, ["0_CONSTANT", "0_var_1", "1_CONSTANT", "1_var_1"]}
@spec summary(Spatex.Regression.OLS.t()) :: String.t()
A printable text summary of an OLS fit, modelled on spreg's report (concise, not byte-identical).
Examples
iex> y = [3.0, 1.5, 4.0, 1.0, 5.5, 9.0, 2.5, 6.0]
iex> text = y |> Spatex.Regression.ols([[1, 2, 0.5, 4, 3, 2, 6, 5]]) |> Spatex.Regression.summary()
iex> String.contains?(text, "ORDINARY LEAST SQUARES")
true
@spec sur([term()], [term()], keyword()) :: Spatex.Regression.SUR.t()
Seemingly unrelated regressions (spreg.SUR): one OLS-type equation per element of ys /
xs, estimated jointly by feasible GLS with a common error covariance across equations.
ys is a list of y vectors, xs a list of the matching designs (each as x in ols/3; a
constant "Constant_<eq>" is added to every equation). Returns a Spatex.Regression.SUR.
Options
:iter- iterate the FGLS step until the log-determinant of the error covariance moves by at most:epsilon(default1.0e-5), for at most:maxiter + 1rounds (default5); defaultfalse(two-step).:nonspat_diag- likelihood-ratio and Breusch-Pagan LM tests of a diagonal covariance (defaulttrue).:spat_diag- spatial LM error and lag tests (defaultfalse); needs:graph, used as given.:name_bigy- one name per equation;:name_bigx- one list of regressor names per equation.
Regimes are not provided; see three_sls/5 for the instrumented system and sur_error_gm/4
for the spatial error SUR.
@spec sur_error_gm([term()], [term()], Spatex.Graph.t(), keyword()) :: Spatex.Regression.SURerrorGM.t()
Seemingly unrelated regressions with spatial error processes, estimated by generalized moments
(spreg.SURerrorGM).
ys is a list of y vectors and xs the matching designs as in sur/3 (a constant
"Constant_<eq>" is added to every equation); graph is the Spatex.Graph used as given
(spreg never row-standardizes implicitly). Returns a Spatex.Regression.SURerrorGM.
Estimation follows spreg: OLS per equation; the spatial error parameter of every equation is
the Kelejian-Prucha moment estimate of its OLS residuals (as in gm_error/4); the variables
and the OLS residuals are filtered with those parameters (v - lambda W v, the constant
included), and one SUR GLS step on the filtered variables gives the coefficients, with
sig = E'E / n of the filtered OLS residuals. There is no iteration. The Chow tests of
coefficient equality across equations exist when every equation has the same number of
coefficients. spreg reports no further diagnostic for this class (its spat_diag and vm
options are not implemented there, nonspat_diag only affects its text summary), so there are
no such options; the lambda equality test belongs to the ML estimator.
spreg minimizes the moment objective with L-BFGS-B, which stops up to ~5e-6 from the minimizer;
Spatex returns the exact minimizer (see the spreg GM notes in docs/parity.md).
Options
:name_bigy- one name per equation;:name_bigx- one list of regressor names per equation.
regimes is not supported (any :regimes option raises ArgumentError).
Examples
iex> y1 = [3.0, 1.5, 4.0, 1.0, 5.5, 9.0, 2.5, 6.0, 4.5, 3.5, 2.0, 7.0]
iex> y2 = [2.0, 2.5, 3.5, 1.5, 4.0, 6.5, 2.0, 5.0, 3.0, 3.5, 1.0, 4.5]
iex> x = [1.0, 2.0, 0.5, 4.0, 3.0, 2.0, 6.0, 5.0, 1.5, 2.5, 3.5, 4.5]
iex> focal = Enum.flat_map(0..11, &[&1, &1])
iex> neighbor = Enum.flat_map(0..11, &[rem(&1 + 1, 12), rem(&1 + 11, 12)])
iex> g = Spatex.Graph.from_arrays(focal, neighbor) |> Spatex.Graph.transform(:r)
iex> r = Spatex.Regression.sur_error_gm([y1, y2], [[x], [x]], g)
iex> {r.n_eq, r.k, length(r.lam), length(r.chow)}
{2, [2, 2], 2, 2}
@spec sur_error_ml([term()], [term()], Spatex.Graph.t(), keyword()) :: Spatex.Regression.SURerrorML.t()
Seemingly unrelated regressions with a spatial error process in every equation, estimated by
maximum likelihood (spreg.SURerrorML, spreg 1.9.1).
ys is a list with the dependent variable of each equation (at least two), xs the list of
regressor sets (a list of columns each; the constant is added per equation) and graph a
Spatex.Graph. Returns a Spatex.Regression.SURerrorML.
The estimation is spreg's: the lambda of each equation is first estimated by ml_error/4 (with
epsilon as tolerance), the residuals of the iterated classic SUR start the loop, and every round
runs a SUR GLS step on the variables filtered with the current lambdas (sigma from the filtered
residuals of the previous round) and then maximizes the concentrated likelihood
-n/2 ln|sigma| + sum_r ln|I - lambda_r W| over all lambdas, until it moves by at most
epsilon. The reported b_sur, varb and sig are those of the last SUR step, lam the
output of the last search. The log-Jacobian is the exact ln|det(I - lambda W)| (as spreg's
sparse LU) from a dense LU, so n is bounded by :max_dense_n.
Reported tests: the likelihood-ratio test of a diagonal sigma (lr_test, nonspat_diag), the
likelihood-ratio test of the spatial parameters against the classic SUR (lr_lambda,
spat_diag), with vm: true the asymptotic covariance of the lambdas and sigma, the standard
errors of the lambdas (lam_setp), the Wald test that the lambdas are equal (lam_test) and,
with spat_diag, that they are jointly zero (join_lam), and the Chow tests of coefficient
equality across equations (chow, equal-size equations).
spreg searches the lambdas with L-BFGS-B (finite-difference gradient, loose tolerances); Spatex
minimizes the same objective with analytic gradients, so its lambdas are the tighter optimum
and agree with spreg's to ~1e-4 (see the spreg spatial SUR notes in docs/parity.md).
Options
:epsilon- tolerance of the loop and of the per-equation ML fits (default1.0e-7).:nonspat_diag(defaulttrue),:spat_diag(defaultfalse),:vm(defaultfalse) - the tests above.:max_dense_n- cap onn(default 5000).:name_bigy- one name per equation;:name_bigx- one list of regressor names per equation.
regimes is not supported (any :regimes option raises ArgumentError).
Examples
iex> y1 = [3.0, 1.5, 4.0, 1.0, 5.5, 9.0, 2.5, 6.0, 4.5, 3.5, 2.0, 7.0]
iex> y2 = [2.0, 2.5, 3.5, 1.5, 4.0, 6.5, 2.0, 5.0, 3.0, 3.5, 1.0, 4.5]
iex> x = [1.0, 2.0, 0.5, 4.0, 3.0, 2.0, 6.0, 5.0, 1.5, 2.5, 3.5, 4.5]
iex> focal = Enum.flat_map(0..11, &[&1, &1])
iex> neighbor = Enum.flat_map(0..11, &[rem(&1 + 1, 12), rem(&1 + 11, 12)])
iex> g = Spatex.Graph.from_arrays(focal, neighbor) |> Spatex.Graph.transform(:r)
iex> r = Spatex.Regression.sur_error_ml([y1, y2], [[x], [x]], g, vm: true)
iex> {r.n_eq, r.k, length(r.lam), length(r.vm), length(r.chow)}
{2, [2, 2], 2, 5, 2}
@spec sur_lag_iv([term()], [term()], Spatex.Graph.t(), keyword()) :: Spatex.Regression.SURlagIV.t()
Seemingly unrelated regressions with a spatial lag in every equation, estimated by three-stage
least squares (spreg.SURlagIV).
ys and xs are lists with one entry per equation (at least two): the y vector and the
exogenous design, each given as in ols/3 (a constant "Constant_<eq>" is added to every
design). graph is a Spatex.Graph used as given (row-standardize it first). Returns a
Spatex.Regression.SURlagIV.
Every equation gets W y as its last endogenous variable (after the user's :yends) and, as
instruments, [Q, W X, ..., W^p X, W Q, ..., W^p Q] with p = :w_lags and Q the user
instruments :qs (the lags of Q only with lag_q: true), then three_sls/5 estimates the
system: 2SLS per equation, sig = E'E / n of those residuals, one GLS step. Reported: the
coefficients (the spatial lag coefficient of each equation is rho), varb, standard errors
and z statistics, the cross-equation sig and corr, the Chow tests of coefficient equality
across equations (equal-size equations) and, with spat_diag: true, the Wald test that the
spatial lag coefficients are jointly zero (joinrho). spreg computes no spatial impacts, no
other diagnostic and no other vm for this class (its nonspat_diag and vm flags only change
the text summary), so Spatex has no such options.
Options
:yends,:qs- per equation, the additional endogenous variables and their instruments (both or neither; unnamed columns arevar_<i>).:w_lags- order of the spatial lags used as instruments (integer >= 1, default 1).:lag_q- also lag the user instruments (defaulttrue).:spat_diag- reportjoinrho(defaultfalse).:name_bigy- one name per equation;:name_bigx,:name_bigyend,:name_bigq- one list of names per equation (of the user variables).
regimes is not supported (any :regimes option raises ArgumentError).
Examples
iex> y1 = [3.0, 1.5, 4.0, 1.0, 5.5, 9.0, 2.5, 6.0, 4.5, 3.5, 2.0, 7.0]
iex> y2 = [2.0, 2.5, 3.5, 1.5, 4.0, 6.5, 2.0, 5.0, 3.0, 3.5, 1.0, 4.5]
iex> x = [1.0, 2.0, 0.5, 4.0, 3.0, 2.0, 6.0, 5.0, 1.5, 2.5, 3.5, 4.5]
iex> focal = Enum.flat_map(0..11, &[&1, &1])
iex> neighbor = Enum.flat_map(0..11, &[rem(&1 + 1, 12), rem(&1 + 11, 12)])
iex> g = Spatex.Graph.from_arrays(focal, neighbor) |> Spatex.Graph.transform(:r)
iex> r = Spatex.Regression.sur_lag_iv([y1, y2], [[x], [x]], g, spat_diag: true)
iex> {r.n_eq, r.k, length(r.rho), length(r.chow), elem(r.joinrho, 1)}
{2, [3, 3], 2, 3, 2}
@spec three_sls([term()], [term()], [term()], [term()], keyword()) :: Spatex.Regression.ThreeSLS.t()
Three-stage least squares for a system of equations with endogenous regressors
(spreg.ThreeSLS).
ys, xs, yends and qs are lists with one entry per equation (at least two): the y
vector, the exogenous design, the endogenous variables and the additional instruments, each
given as in tsls/5 (a constant "Constant_<eq>" is added to every xs design). Every
equation needs at least one endogenous variable and at least as many instruments as endogenous
variables. Returns a Spatex.Regression.ThreeSLS.
Estimation follows spreg: 2SLS per equation, the cross-equation covariance sig = E'E / n of
those residuals, then one GLS step on the instrumented regressors ([X, H (H'H)^-1 H'Yend]),
with no iteration. The Chow tests of coefficient equality across equations exist when every
equation has the same number of coefficients. spreg reports no other non-spatial diagnostic for
ThreeSLS, so there is no :nonspat_diag option.
Options
:name_bigy- one name per equation;:name_bigx,:name_bigyend,:name_bigq- one list of names per equation.
regimes is not supported (any :regimes option raises ArgumentError).
Examples
iex> y1 = [3.0, 1.5, 4.0, 1.0, 5.5, 9.0, 2.5, 6.0, 4.5, 3.5, 2.0, 7.0]
iex> y2 = [2.0, 2.5, 3.5, 1.5, 4.0, 6.5, 2.0, 5.0, 3.0, 3.5, 1.0, 4.5]
iex> x = [1.0, 2.0, 0.5, 4.0, 3.0, 2.0, 6.0, 5.0, 1.5, 2.5, 3.5, 4.5]
iex> e = [0.3, 1.1, 0.9, 2.0, 1.4, 0.2, 2.5, 1.9, 0.6, 1.0, 0.1, 1.2]
iex> q1 = [1.2, 0.4, 2.2, 0.8, 3.1, 1.7, 0.9, 2.8, 1.1, 0.5, 2.6, 1.9]
iex> q2 = [0.2, 1.9, 0.7, 2.4, 1.0, 0.6, 2.9, 0.3, 1.8, 2.2, 0.8, 1.4]
iex> r = Spatex.Regression.three_sls([y1, y2], [[x], [x]], [[e], [e]], [[q1, q2], [q1, q2]])
iex> {r.n_eq, r.k, length(r.b_3sls), length(r.chow)}
{2, [3, 3], 2, 3}
Two-stage least squares (spreg.TSLS) of y on x and the endogenous columns yend,
instrumented by x and q.
x, yend and q follow the input rules of ols/3 (lists of columns, maps of
name => column, Nx tensors, Explorer data frames). yend and q need at least one column
each, and q at least as many columns as yend.
Options
:constant- prepend an intercept named"CONSTANT"(defaulttrue), as inols/3.:robust-nil(default),:whiteor:hac(needs:gwk, a kernelSpatex.Graphwith unit diagonal).:sig2n_k- estimate sigma-squared (and rescale the White covariance) withn - k(defaultfalse, like spreg's 2SLS).:name_x,:name_y,:name_yend,:name_q- variable names.
Spatial diagnostics of spreg.TSLS (spat_diag) and regimes are not ported; use gm_lag/4 for
the Anselin-Kelejian test. Raises ArgumentError on invalid input or singular H'H /
Z'H (H'H)^-1 H'Z.
Examples
iex> y = [3.0, 1.5, 4.0, 1.0, 5.5, 9.0, 2.5, 6.0, 4.5, 2.0]
iex> x = [1.0, 2.0, 0.5, 4.0, 3.0, 2.0, 6.0, 5.0, 1.5, 3.5]
iex> yend = [2.0, 1.0, 3.5, 0.5, 4.0, 6.5, 1.0, 5.0, 3.0, 2.5]
iex> q = [1.0, 0.0, 3.0, 1.0, 3.5, 6.0, 0.5, 4.0, 2.5, 3.0]
iex> m = Spatex.Regression.tsls(y, [x], [yend], [q])
iex> {m.n, m.k, m.name_x}
{10, 3, ["CONSTANT", "var_1", "yend_1"]}
@spec tsls_regimes(term(), term(), term(), term(), [term()], keyword()) :: Spatex.Regression.TSLSRegimes.t()
Two-stage least squares with coefficients that vary by regime (spreg.TSLS_Regimes).
x, yend and q follow the input rules of tsls/5 (the intercept is added by the
function); regimes holds one label per observation (see Spatex.Input.to_labels/2), sorted
for the coefficient order. Returns a Spatex.Regression.TSLSRegimes with Chow tests of equal
coefficients across regimes.
Options
:constant_regi-:many(default, an intercept per regime) or:one(a global one).:cols2regi-:all(default) or one boolean perxcolumn followed by one peryendcolumn:truefor a coefficient per regime,falsefor a global one. The instruments always vary by regime.:regime_err_sep-false(default, as in spreg): one pooled 2SLS on the regime design.true: with every coefficient by regime andconstant_regi: :many, one 2SLS per regime (each with its own error variance; columns ofxconstant within a regime are dropped with a warning); otherwise ignored. It is disabled, with a warning, underrobust: :hac.:robust-nil(default),:whiteor:hac(with:gwk, a kernelSpatex.Graphover all observations).:sig2n_k(defaulttrue, as in spreg's regimes models),:name_x,:name_y,:name_yend,:name_qas intsls/5.:spreg_compatible-false(default): the Chow restrictions use the real coefficient layout (exogenous regime blocks, exogenous globals, endogenous regime blocks, endogenous globals).truereproduces spreg, whoseChowassumes the globals come last; with global exogenous columns and regime-specific endogenous ones (for exampleconstant_regi: :one) its endogenous and joint tests compare other coefficients. Coefficients and covariance are never affected, nor are the other cases (seedocs/parity.md).
Spatial diagnostics (spat_diag), robust: 'ogmm', slx_lags and TSLS_Endog_Regimes are
not ported.
Examples
iex> y = [3.0, 1.5, 4.0, 1.0, 5.5, 9.0, 2.5, 6.0, 4.5, 2.0, 7.0, 3.5]
iex> x = [1.0, 2.0, 0.5, 4.0, 3.0, 2.0, 6.0, 5.0, 1.5, 3.5, 2.5, 4.5]
iex> yend = [2.0, 1.0, 3.5, 0.5, 4.0, 6.5, 1.0, 5.0, 3.0, 2.5, 5.5, 3.0]
iex> q = [[1.0, 0.0, 3.0, 1.0, 3.5, 6.0, 0.5, 4.0, 2.5, 3.0, 4.0, 2.0], [0.5, 2.5, 1.0, 3.0, 2.0, 1.0, 4.5, 0.0, 3.5, 1.5, 2.5, 0.5]]
iex> r = Spatex.Regression.tsls_regimes(y, [x], [yend], q, [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1])
iex> {r.mode, r.name_x, r.name_yend}
{:pooled, ["0_CONSTANT", "0_var_1", "1_CONSTANT", "1_var_1"], ["0_yend_1", "1_yend_1"]}