Module contents
Lesson 8 of 28Advanced 100 min

Structural models I: simultaneous equations and structural equation models

Study structural and reduced forms, order and rank identification, 2SLS and 3SLS, latent-variable structural equation models and the Lucas critique of policy extrapolation.

After this lesson you can

  • Derive a linear system's reduced form and show why structural parameters require restrictions.
  • Apply order and rank conditions to two- and three-equation systems.
  • Estimate systems by 2SLS and 3SLS and compare efficiency.
  • Specify and estimate a two-latent-variable SEM through its implied covariance.
  • Explain the Lucas critique and connect it to mechanism invariance in causal models.

Before you start

An equilibrium does not reveal its curves

You observe market prices and quantities over years. Each point is the intersection of supply and demand, not an observation obtained by moving price while everything else is held fixed. As seen in simultaneity, shifts of both curves can mix their slopes.

In 1943 Haavelmo posed the question for complete systems: can different theoretical parameters generate the same observations? Before optimizing a fit, identify which variation and restrictions could distinguish explanations.

Structural and reduced form

In a linear simultaneous-equations system with GG endogenous variables and exogenous zz, write

By+Γz=u,y=−B−1Γz+B−1u=Πz+v,By+\Gamma z=u,\qquad y=-B^{-1}\Gamma z+B^{-1}u=\Pi z+v,

if BB is invertible. Structural and reduced forms answer different questions: BB and Γ\Gamma capture assumed simultaneous relationships; Π=−B−1Γ\Pi=-B^{-1}\Gamma describes how endogenous variables change with zz after solving the system. Reduced covariance is B−1ΩB−⊤B^{-1}\Omega B^{-\top}, where Ω=Var⁡(u)\Omega=\operatorname{Var}(u). Knowing Π\Pi and that covariance does not necessarily determine BB, Γ\Gamma and Ω\Omega.

For example, if you observe only (P,Q)(P,Q) with independent bivariate standard normal distribution, for any b,d>0b,d>0 you can write Q=−bP+udQ=-bP+u_d and Q=dP+usQ=dP+u_s, defining ud=Q+bPu_d=Q+bP and us=Q−dPu_s=Q-dP. Slopes change, but the observable distribution is exactly the same if shock covariance may change. Would requiring independent shocks suffice? The first exercise asks you to investigate that restriction. Equations do not themselves identify which curve is which; additional defensible restrictions are needed.

Order and rank: counting is not enough

Normalize the dependent-variable coefficient of the equation studied to one and define C=[B Γ]C=[B\ \Gamma]. Assume known exclusion restrictions, invertible BB and model exogeneity and regularity. For equation ii, remove its row from CC and retain columns of variables excluded from that equation, endogenous and exogenous. The rank condition requires that submatrix have rank G−1G-1.

The order condition counts excluded columns: at least G−1G-1 are needed. It is necessary, but columns can be linearly dependent. If rank is lower, the equation is not identified by these exclusions. With full rank, the minimum number of exclusions gives exact identification; more exclusions give overidentification in this scheme. These are equation-by-equation identification conditions under specified restrictions; additional cross-equation restrictions can provide information not counted here.

The algebraic intuition is to seek a combination of other structural rows that can be added to row ii without changing any exclusion or normalization. If the excluded-column submatrix has a nontrivial left null space, a direction of indistinguishable combinations remains. Full rank removes that local ambiguity under the other assumptions; counting columns without checking independence does not.

InteractiveCheck the rank of each equation

System B·Y+Γ·Z=u, with three endogenous Y and three exogenous Z variables. Select each coefficient to include or zero it; B diagonal entries are fixed at 1. The selected equation determines excluded columns.

Equation 1 · selected

Equation 2

Equation 3

Equation 1 excludes Z₁, Z₂. The highlighted border shows those coefficients in the other equations. The submatrix is:

EquationZ₁Z₂
21.002.00
30.501.00

Order: satisfied (2 excluded; at least 2 required). Rank: 1 of 2. Not identified.

Equation 1: Not identifiedEquation 2: Not identifiedEquation 3: Not identified

The initial case excludes Z₁ and Z₂ from the first equation: rows (1,2) and (0.5;1) are proportional. There are two exclusions but rank 1. Uncheck Z₂ in equation 3 to raise rank to 2.

Classification uses exclusion restrictions, one normalization per equation and sufficient Z variation, with exogeneity and no additional cross-equation restrictions. B is invertible here because diagonal entries are 1 and the sum of absolute off-diagonal entries in each row is below 1. Full numerical rank does not guarantee finite-sample precision or strong instruments.

Equation examined
Excluded variables2
Required rank2
Computed rank1
ResultNot identified
Toggle coefficients and compare the exclusion count with rank.

2SLS and 3SLS

Once an equation is identified and instruments valid, 2SLS estimates it separately. LIML is another single-equation option whose distribution can differ with weak instruments. To exploit cross-equation shock correlation, three-stage least squares combines instruments and system GLS:

  1. Project each equation’s regressors onto the common instrument space, including exogenous controls.
  2. Obtain initial estimates and estimate contemporaneous covariance of structural residuals.
  3. Stack equations and apply instrumental GLS with that estimated covariance.

If X^\hat X is the block design with projected columns and Ω^\hat\Omega cross-equation error covariance, one form with common instruments is

β^3SLS=[X^⊤(Ω^−1⊗In)X^]−1X^⊤(Ω^−1⊗In)y.\hat\beta_{3SLS}= [\hat X^\top(\hat\Omega^{-1}\otimes I_n)\hat X]^{-1} \hat X^\top(\hat\Omega^{-1}\otimes I_n)y.

The formula assumes rank, invertibility and the stated stacking order. To interpret it as efficient GLS in this model, stacked covariance must be Ω⊗In\Omega\otimes I_n: the same contemporaneous covariance and no correlation across observations. Heteroskedasticity or dependence requires adapting covariance and inference. With correct specification and suitable assumptions it can improve asymptotic efficiency over separate equation estimation; a particular sample need not show lower error in every coefficient. If an equation or instrument is invalid, joint weighting can transmit the problem to other equations. FIML estimates jointly by maximum likelihood and needs additional distributional and specification assumptions. IV3SLS documentation shows a system implementation.

Latent variables and covariances

A structural equation model separates a measurement model from relationships between latent variables. For example, with six indicators and two factors A,BA,B:

w=Λ(AB)+ϵ,B=γA+ζ.w=\Lambda\begin{pmatrix}A\\B\end{pmatrix}+\epsilon, \qquad B=\gamma A+\zeta.

If AA has variance ϕ\phi, ζ\zeta variance ψ\psi, they are independent and measurement errors have diagonal matrix Θ\Theta independent of factors, implied covariance is

Σ(θ)=Λ(ϕγϕγϕγ2ϕ+ψ)Λ⊤+Θ.\Sigma(\theta)=\Lambda \begin{pmatrix}\phi&\gamma\phi\\\gamma\phi&\gamma^2\phi+\psi\end{pmatrix} \Lambda^\top+\Theta.

These independences are model restrictions, not automatic indicator properties. Fixing one loading per factor to one defines its scale; without equivalent normalization, multiplying a factor and dividing its loadings leaves covariances unchanged. Local identification must also be checked: having more moments than parameters is necessary but does not guarantee a full-rank Jacobian.

The measurement model extends factor analysis by adding relationships between factors. Under linear Gaussian assumptions and an acyclic graph, it can also be expressed as a Bayesian network with latent nodes. In simulation calibration the same question recurs: different parameters can produce indistinguishable observations.

InteractivePath diagram and implied covariance

Two latent variables produce six indicators. X₁ and X₄ fix scale with loading 1; the other fixed loadings are 0.7. Residual table colors show S − Σ: blue positive, orange negative.

0.30AB1.00X₁0.50X₂0.70X₃1.00X₄0.60X₅0.70X₆
  • Measurement
  • Latent relation

Matrix S comes from 600 simulated observations with seed 270803, A ∼ N(0,1), B = 0.6A + ζ and ζ ∼ N(0,1) independent of A. Loadings are (1; 0.8; 0.7) for A and (1; 0.9; 0.7) for B; measurement errors are independent normals with variance 0.5. S uses denominator n−1. These are not external data.

Observed S
X₁X₂X₃X₄X₅X₆
X₁1.390.770.570.570.430.34
X₂0.771.120.520.480.370.32
X₃0.570.520.840.380.300.25
X₄0.570.480.381.881.250.97
X₅0.430.370.301.251.540.87
X₆0.340.320.250.970.871.17
Implied Σ
X₁X₂X₃X₄X₅X₆
X₁1.500.500.700.300.180.21
X₂0.500.750.350.150.090.10
X₃0.700.350.990.210.130.15
X₄0.300.150.211.590.650.76
X₅0.180.090.130.650.890.46
X₆0.210.100.150.760.461.03
Residual S − Σ
X₁X₂X₃X₄X₅X₆
X₁−0.110.27−0.130.270.250.13
X₂0.270.370.170.330.280.21
X₃−0.130.17−0.150.170.180.11
X₄0.270.330.170.290.590.21
X₅0.250.280.180.590.650.42
X₆0.130.210.110.210.420.14

The forward model uses Var(A)=1 and B=bA+ζ with Var(ζ)=1. Latent covariances are Var(B)=1+b² and Cov(A,B)=b; the six measurement errors have variance 0.5 and are mutually independent and independent of latents. Σ=ΛΦΛᵀ+Θ. Fixed restrictions recover b=Cov(X₁,X₄), X₂ loading=Cov(X₁,X₂), and X₅ loading=Cov(X₄,X₅)/(1+b²) in the population. Counting moments alone does not identify a general SEM.

In the selected model, the variance of the latent at the arrow origin is 1.000. Reversing it gives A=[b/(1+b²)]B+η, Var(η)=1/(1+b²), and η independent of B in this Gaussian model: exactly the same Φ. You can add the bidirectional path Cov(A,ζ)=c: B=(b−c)A+ζ and Var(ζ)=1+c² preserve Φ for every shown c. Equations change, not Σ or fit. The bidirectional path correlates the error with A and the structural slope is no longer identified; equal fit does not decide causal direction.

0.50
0.60
0.30
Latent model
Arrow coefficient0.300
Latent error variance1.000
Largest |S − Σ|0.650
Norm of S − Σ1.723
Fit the model and compare implied and observed covariance.

For iid Gaussian observations, with sample covariance SS calculated using divisor nn and positive-definite Σ\Sigma, normalized discrepancy relative to the saturated model is

F(θ)=log⁡∣Σ(θ)∣+tr⁡[SΣ(θ)−1]−log⁡∣S∣−p.F(\theta)=\log|\Sigma(\theta)|+\operatorname{tr}[S\Sigma(\theta)^{-1}] -\log|S|-p.

Under a correct model, identification and regularity, nF(θ^)nF(\hat\theta) is compared asymptotically with chi-square whose degrees of freedom equal independent moments minus free parameters; some covariance conventions use n−1n-1. A singular matrix or boundary solution can invalidate usual error calculation and asymptotic reference. RMSEA and CFI summarize discrepancies relative to degrees of freedom or a baseline model; they depend on conventions and are not tests of causal truth.

Covariances of pp indicators have p(p+1)/2p(p+1)/2 distinct entries. Counting free parameters against those entries, called the tt rule, is only a necessary check. Different graphs can imply the same matrix and obtain identical fit: good overall fit does not determine causal direction. Scale restrictions, temporal information, interventions and substantive assumptions can help distinguish models.

A rule that changes expectations

The Lucas critique warns that a relationship estimated under one policy can change when agents anticipate another. In the example, expected taxes follow E[T∣Y]=a+bYE[T\mid Y]=a+bY and the assumed mechanism is C=α+β(Y−E[T∣Y])+ϵC=\alpha+\beta(Y-E[T\mid Y])+\epsilon, with E[ϵ∣Y]=0E[\epsilon\mid Y]=0. The reduced form is

E[C∣Y]=(α−βa)+β(1−b)Y.E[C\mid Y]=(\alpha-\beta a)+\beta(1-b)Y.

Changing aa or bb changes reduced-form intercept or slope even if α\alpha and β\beta stay fixed. The graph calibrates the mechanism once and recalculates expectations under the new rule; the old reduced-form line is not updated. This is a synthetic experiment: invariance is imposed to teach the mechanism, not deduced by calling the model structural. The policy-and-expectations formulation is in Lucas.

InteractiveThe reduced form that breaks when policy changes

The horizontal axis shows income Y and the vertical consumption C. Evaluation observations are generated under the selected rule with disturbances retained when it changes. The reduced-form line was learned only under the original rule; the mechanism was calibrated once on the same sample and then incorporates the new rule.

  • Evaluation
  • Old reduced form
  • Recomputed mechanism
  • Simulated true mean

Explicit model: each agent has income Y and expects taxes E[T|Y]=a+bY. Consumption is C=2+0.7(Y−E[T|Y])+ε, with normal ε of standard deviation 0.5. Incomes form a fixed grid of 80 values from 0.5 to 9.5. The two samples use independent disturbances from seed 270801; these are not historical data.

The initial rule has a=1 and b=0.2. Estimate intercept and slope of C on Y in training, then recover β̂=slope/(1−0.2) and α̂=intercept+β̂. Under the new rule evaluate α̂+β̂[Y−(a+bY)]; RMSE uses the evaluation sample. Mechanism stability is imposed here and must be justified in a real application: calling it structural does not guarantee invariance.

Expected tax rule
Current rule: intercept a2.00
Current rule: slope b0.60
Old reduced-form RMSE2.159
Recomputed mechanism RMSE0.441
Change the fiscal rule and compare out-of-sample predictions.

The cell reproduces the interactive’s generator and predictions, retaining the same evaluation sample across three rules.

[ ]Check the fiscal rule changeBrowser
import math
import numpy as np

def rng_js(seed):
    a=seed & 0xffffffff
    spare=None
    def uniform():
        nonlocal a
        a=(a+0x6d2b79f5)&0xffffffff
        t=((a^(a>>15))*(a|1))&0xffffffff
        t=(t^((t+((t^(t>>7))*(t|61)))&0xffffffff))&0xffffffff
        return ((t^(t>>14))&0xffffffff)/4294967296
    def normal():
        nonlocal spare
        if spare is not None:
            value,spare=spare,None
            return value
        u=uniform()
        while u==0: u=uniform()
        v=uniform()
        while v==0: v=uniform()
        radius=math.sqrt(-2*math.log(u))
        spare=radius*math.sin(2*math.pi*v)
        return radius*math.cos(2*math.pi*v)
    return normal

normal=rng_js(270801)
income=np.linspace(.5,9.5,80)
train=2+.7*(income-(1+.2*income))+.5*np.array([normal() for _ in income])
noise=.5*np.array([normal() for _ in income])
intercept,slope=np.linalg.lstsq(np.column_stack((np.ones(len(income)),income)),train,rcond=None)[0]
beta=slope/.8
alpha=intercept+beta
print('Entrenamiento: intercepto, pendiente, alfa y beta recuperados:',intercept,slope,alpha,beta)
for name,a,b in [('original',1.,.2),('progresiva',2.,.6),('devolución',.5,-.1)]:
    y=2+.7*(income-a-b*income)+noise
    reduced=intercept+slope*income
    structural=alpha+beta*(income-a-b*income)
    rmse_reduced=np.sqrt(np.mean((y-reduced)**2))
    rmse_structural=np.sqrt(np.mean((y-structural)**2))
    print(name,'regla:',a,b,'RMSE reducida y mecanismo:',rmse_reduced,rmse_structural)
    if name=='original': assert np.allclose(reduced,structural)

Autonomy of a mechanism means it continues to describe the variable under the particular intervention, not immunity to every conceivable policy. Haavelmo attributes the term and several ideas to a 1938 Frisch memorandum. This question connects system modeling with causal models: justify which equation changes, which remain and how expectations respond.

Lab: identification and 3SLS

The simulated system has exactly identified demand and overidentified supply. The first cell calculates rank, reduced form and estimators; the second compares squared errors across paired replicates. Zeros are assumed restrictions and instruments are exogenous by construction.

Across 500 replicates, the 2SLS-minus-3SLS MSE difference for the demand price coefficient is approximately 0.0000035 versus Monte Carlo error 0.0000601: here it does not resolve a gain. For two demand shifters differences are 0.000808 and 0.001088, with Monte Carlo errors 0.000205 and 0.000241. These figures describe the cell’s generator, not a guaranteed improvement for any system. The lab treats only exact zeros as exclusions; rank tolerance is numerical and stated in the function.

[ ]Reduced form, identification and 3SLSBrowser
"""Oferta y demanda: rango, forma reducida, MC2E y MC3E reproducibles.

Modelo B y + Gamma z = u. B tiene diagonal no nula y es invertible.
Los ceros suministrados representan exclusiones estructurales asumidas.
"""
import numpy as np


def identification(B, Gamma, eq, tol=1e-10):
    B, Gamma = np.asarray(B, float), np.asarray(Gamma, float)
    m = B.shape[0]
    if (B.shape != (m, m) or Gamma.ndim != 2 or Gamma.shape[0] != m or
        not 0 <= eq < m or not np.isfinite(B).all() or not np.isfinite(Gamma).all() or
        np.any(np.abs(np.diag(B)) <= tol) or np.linalg.matrix_rank(B) < m):
        raise ValueError('Sistema, normalización o valores inválidos')
    omitted_y = [j for j in range(m) if j != eq and B[eq,j] == 0]
    omitted_z = np.flatnonzero(Gamma[eq] == 0)
    rows = np.arange(m) != eq
    constraints = np.column_stack((B[rows][:, omitted_y], Gamma[rows][:, omitted_z]))
    order = constraints.shape[1]
    rank = np.linalg.matrix_rank(constraints, tol=tol) if order else 0
    if rank < m-1:
        state = 'no identificada'
    else:
        state = 'exacta' if order == m-1 else 'sobreidentificada'
    return state, order, rank


def simulate_market(n, rng):
    z = rng.normal(size=(n, 3))
    common, independent = rng.normal(size=(2, n))
    ud = common
    us = .65*common + np.sqrt(1-.65**2)*independent
    alpha_d, beta_d = 2., -.8
    alpha_s, beta_s = .5, .7
    g1, g2, g3 = .9, -.55, .8
    # Qd=alpha_d+beta_d*P+g1*z1+g2*z2+ud
    # Qs=alpha_s+beta_s*P+g3*z3+us; impone Qd=Qs.
    price = (alpha_s-alpha_d-g1*z[:,0]-g2*z[:,1]+g3*z[:,2]+us-ud)/(beta_d-beta_s)
    quantity = alpha_d+beta_d*price+g1*z[:,0]+g2*z[:,1]+ud
    Xd = np.column_stack((np.ones(n),price,z[:,0],z[:,1]))
    Xs = np.column_stack((np.ones(n),price,z[:,2]))
    instruments = np.column_stack((np.ones(n),z))
    return quantity, price, Xd, Xs, instruments


def system_3sls(y, designs, Z):
    """MC3E factible sin corrección finita; misma Z para cada ecuación."""
    y, Z = np.asarray(y,float), np.asarray(Z,float)
    qz, _ = np.linalg.qr(Z,mode='reduced')
    fitted = [qz@(qz.T@X) for X in designs]
    tsls = [np.linalg.lstsq(Xhat,y,rcond=None)[0] for Xhat in fitted]
    residuals = np.column_stack([y-X@b for X,b in zip(designs,tsls)])
    omega = residuals.T@residuals/len(y)
    if np.linalg.matrix_rank(omega) < len(designs):
        raise ValueError('Covarianza de ecuaciones singular')
    invomega = np.linalg.inv(omega)
    blocks = [[invomega[i,j]*(fitted[i].T@fitted[j])
               for j in range(len(designs))] for i in range(len(designs))]
    right = np.concatenate([sum(invomega[i,j]*(fitted[i].T@y)
                                for j in range(len(designs)))
                            for i in range(len(designs))])
    beta = np.linalg.solve(np.block(blocks),right)
    split = np.cumsum([X.shape[1] for X in designs])[:-1]
    return tsls, np.split(beta,split), omega


B = np.array([[1., .8], [1., -.7]])
Gamma = np.array([[-.9,.55,0.],[0.,0.,-.8]])
for eq in range(2):
    print('Ecuación, identificación, exclusiones, rango:', eq, *identification(B,Gamma,eq))
B_counter = np.array([[1., .2, .1], [.2, 1., .3], [.3, .1, 1.]])
G_counter = np.array([[0.,0.,1.],[1.,2.,.5],[2.,4.,-.3]])
counter = identification(B_counter,G_counter,0)
assert counter == ('no identificada', 2, 1)
print('Tres ecuaciones: orden satisfecha, rango insuficiente:', counter)
Pi = -np.linalg.solve(B,Gamma)
print('Matriz de forma reducida Π=−B⁻¹Γ:', Pi)
assert np.allclose(B@Pi+Gamma,0.)

rng = np.random.default_rng(270801)
y, price, Xd, Xs, Z = simulate_market(1200,rng)
own_2, own_3, omega = system_3sls(y,[Xd,Xs],Z)
print('MC2E demanda y oferta:',*own_2)
print('MC3E demanda y oferta:',*own_3)
print('Covarianza de residuos estructurales estimada:',omega)
print('Coeficientes de precio verdaderos: demanda -0,8; oferta 0,7.')
print('La clasificación usa exclusiones asumidas y el rango; no verifica exogeneidad.')
[ ]Compare efficiency by simulationBrowser
"""Comparación Monte Carlo apareada; requiere la celda system_laboratory."""
import numpy as np

rng_mc = np.random.default_rng(270802)
repetitions, n_mc = 500, 250
errors, demand_errors = [], []
for _ in range(repetitions):
    yy, _, xd, xs, zz = simulate_market(n_mc, rng_mc)
    b2, b3, _ = system_3sls(yy, [xd, xs], zz)
    errors.append([b2[0][1]+.8, b3[0][1]+.8, b2[1][1]-.7, b3[1][1]-.7])
    demand_errors.append([b2[0]-np.array([2.,-.8,.9,-.55]),
                          b3[0]-np.array([2.,-.8,.9,-.55])])
errors = np.asarray(errors)
demand_errors = np.asarray(demand_errors)
delta_sq = errors[:,[0,2]]**2-errors[:,[1,3]]**2
delta_demand = demand_errors[:,0,:]**2-demand_errors[:,1,:]**2
print('Réplicas y n:', repetitions, n_mc)
print('Sesgo medio demanda MC2E/MC3E y oferta MC2E/MC3E:', errors.mean(axis=0))
print('ECM demanda MC2E/MC3E y oferta MC2E/MC3E:', np.mean(errors**2,axis=0))
print('ECM MC2E menos MC3E, demanda/oferta:', delta_sq.mean(axis=0))
print('Error Monte Carlo de diferencias apareadas de ECM:', delta_sq.std(axis=0,ddof=1)/np.sqrt(repetitions))
print('ECM MC2E menos MC3E, todos los coeficientes de demanda:', delta_demand.mean(axis=0))
print('Error Monte Carlo apareado, todos los coeficientes:', delta_demand.std(axis=0,ddof=1)/np.sqrt(repetitions))
print('Eficiencia de sistema presupone ecuaciones correctas; los resultados son de este diseño.')

This local comparison exactly regenerates the preceding data. Install linearmodels and NumPy in your environment; ols denotes equation-wise instrumental estimation and gls uses system 3SLS in this API.

[ ]Compare with linearmodelsLocal GPU
"""Comparación autocontenida con linearmodels, instalable en entorno local."""
import numpy as np
from linearmodels.system import IV3SLS

rng = np.random.default_rng(270801)
n = 1200
z = rng.normal(size=(n,3))
common, independent = rng.normal(size=(2,n))
ud = common
us = .65*common + np.sqrt(1-.65**2)*independent
price = (.5-2.-.9*z[:,0]+.55*z[:,1]+.8*z[:,2]+us-ud)/(-.8-.7)
quantity = 2.-.8*price+.9*z[:,0]-.55*z[:,1]+ud
one = np.ones((n,1))
equations = {
    'demanda': {'dependent':quantity, 'exog':np.column_stack((one,z[:,0],z[:,1])),
                'endog':price[:,None], 'instruments':z[:,[2]]},
    'oferta': {'dependent':quantity, 'exog':np.column_stack((one,z[:,2])),
               'endog':price[:,None], 'instruments':z[:,[0,1]]},
}
model = IV3SLS(equations)
for method in ('ols','gls'):
    fit = model.fit(method=method,debiased=False)
    demand = fit.equations['demanda'].params.to_numpy()[[0,3,1,2]]
    supply = fit.equations['oferta'].params.to_numpy()[[0,2,1]]
    print('IV3SLS método',method,'demanda y oferta:',demand,supply)
print('Orden: intercepto, precio y desplazadores; compara con el laboratorio propio.')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Lab: SEM by maximum likelihood

The first two cells estimate a synthetic six-indicator SEM. Two loadings are anchored and the Jacobian, observed Hessian and global test are calculated. Run the definition first, then data generation. The example uses a different sample from the interactive figure.

In the simulated sample of 800 observations, the between-factor coefficient is 0.60598 with observed standard error 0.03807. The global test gives χ2=14,52508\chi^2=14{,}52508 with 8 degrees of freedom and p=0,06907p=0{,}06907; the Jacobian has rank 13. semopy reproduces parameters and fit, with a somewhat different standard error because it defaults to expected information. None of these results proves causal direction between factors.

[ ]SEM discrepancy and HessianBrowser
import numpy as np
from scipy.optimize import minimize
from scipy.special import gammaincc

# Dos latentes de media cero: eta = beta * xi + zeta.
# Las cargas del primer indicador de cada bloque se fijan a 1.
def sem_cov(t, deriv=False):
    beta, l2, l3, l5, l6 = t[:5]
    v = np.exp(t[5:])  # Var(xi), Var(zeta), seis varianzas de error
    a, c = v[:2]
    L = np.array([[1,0],[l2,0],[l3,0],[0,1],[0,l5],[0,l6]], float)
    P = np.array([[a,beta*a],[beta*a,beta*beta*a+c]])
    Sigma = L @ P @ L.T + np.diag(v[2:])
    if not deriv:
        return Sigma
    ds = []
    dP = np.array([[0,a],[a,2*beta*a]])
    ds.append(L @ dP @ L.T)
    for row, col in [(1,0),(2,0),(4,1),(5,1)]:
        dL = np.zeros((6,2)); dL[row,col] = 1
        ds.append(dL @ P @ L.T + L @ P @ dL.T)
    ds.append(L @ np.array([[a,beta*a],[beta*a,beta*beta*a]]) @ L.T)
    ds.append(L @ np.array([[0,0],[0,c]]) @ L.T)
    for i in range(6):
        d = np.zeros((6,6)); d[i,i] = v[i+2]; ds.append(d)
    return Sigma, np.array(ds)

def sem_objective(t, S):
    Sigma, ds = sem_cov(t, True)
    sign, logdet = np.linalg.slogdet(Sigma)
    if sign <= 0:
        raise ValueError('La covarianza implicada debe ser positiva definida')
    inv = np.linalg.inv(Sigma)
    loss = logdet + np.trace(S @ inv)
    grad = np.einsum('ij,kji->k', inv - inv @ S @ inv, ds)
    return loss, grad

def sem_fit(data):
    n, p = data.shape
    if p != 6 or n <= p:
        raise ValueError('Se requieren seis indicadores y n > 6')
    centered = data - data.mean(axis=0)
    S = centered.T @ centered / n  # denominador ML, no n - 1
    if np.linalg.slogdet(S)[0] <= 0:
        raise ValueError('La covarianza muestral debe ser positiva definida')
    t0 = np.r_[0.4, 0.8, 0.8, 0.8, 0.8, np.log([1., .6] + [.5]*6)]
    fit = minimize(sem_objective, t0, args=(S,), jac=True, method='BFGS',
                   options={'gtol': 1e-7, 'maxiter': 1000})
    if np.linalg.norm(fit.jac, ord=np.inf) > 1e-5:
        raise RuntimeError('El optimizador no alcanzó una solución estacionaria')
    return dict(params=fit.x, S=S, n=n, fit=fit)

def sem_inference(result):
    n, S, t = result['n'], result['S'], result['params']
    p = S.shape[0]
    # Hessiano observado de -log L = n/2 * F: diferencias centradas de su gradiente.
    h = 1e-4 * np.maximum(1, np.abs(t))
    H = np.empty((len(t),len(t)))
    for j in range(len(t)):
        delta = np.zeros_like(t); delta[j] = h[j]
        H[:,j] = n/2 * (sem_objective(t+delta,S)[1] - sem_objective(t-delta,S)[1])/(2*h[j])
    H = (H + H.T)/2
    if np.linalg.eigvalsh(H).min() <= 0:
        raise RuntimeError('Hessiano no positivo: inferencia regular no disponible')
    se = np.sqrt(np.diag(np.linalg.inv(H)))
    logdetS = np.linalg.slogdet(S)[1]
    discrepancy = max(0., sem_objective(t,S)[0] - logdetS - p)
    df = p*(p+1)//2 - len(t)
    stat = n * discrepancy
    return dict(**result, se=se, Sigma=sem_cov(t), H=H,
                chi2=stat, df=df, pvalue=gammaincc(df/2,stat/2))
[ ]Estimate a two-factor SEMBrowser
rng = np.random.default_rng(6408)
n = 800
xi = rng.normal(size=n)
eta = 0.65 * xi + rng.normal(scale=np.sqrt(.6), size=n)
loadings = np.array([1., .8, 1.2, 1., .7, 1.1])
errors = rng.normal(size=(n,6)) * np.sqrt([.4, .5, .6, .4, .5, .6])
observed = np.column_stack([xi]*3 + [eta]*3) * loadings + errors
out = sem_fit(observed)

out = sem_inference(out)
names = ['beta','carga2','carga3','carga5','carga6','logvar_xi','logvar_zeta'] + [f'logvar_e{i}' for i in range(1,7)]
print('convergencia: gradiente máximo =', f"{np.max(np.abs(out['fit'].jac)):.2g}")
for name, estimate, se in zip(names,out['params'],out['se']):
    print(f'{name:12s} {estimate: .5f}  EE {se:.5f}')
print('chi2 =', round(out['chi2'],5), 'gl =', out['df'], 'p =', round(out['pvalue'],5))
print('rango Jacobiano =', np.linalg.matrix_rank(sem_cov(out['params'],True)[1].reshape(13,-1).T))
print('mayor residuo de covarianza =', round(np.max(np.abs(out['S']-out['Sigma'])),5))

Install semopy, NumPy and pandas to check estimates and fit locally on the same data. semopy’s default standard error uses expected information while the custom cell calculates observed Hessian; they need not agree in finite samples.

[ ]Compare with semopyLocal GPU
import numpy as np
import pandas as pd
import semopy

# Reproduce los datos de la celda Pyodide sin depender de sus variables.
rng = np.random.default_rng(6408)
n = 800
xi = rng.normal(size=n)
eta = .65 * xi + rng.normal(scale=np.sqrt(.6), size=n)
loadings = np.array([1., .8, 1.2, 1., .7, 1.1])
errors = rng.normal(size=(n,6)) * np.sqrt([.4, .5, .6, .4, .5, .6])
data = np.column_stack([xi]*3 + [eta]*3) * loadings + errors
frame = pd.DataFrame(data, columns=['x1','x2','x3','x4','x5','x6'])
description = '''
xi =~ x1 + x2 + x3
eta =~ x4 + x5 + x6
eta ~ xi
'''
model = semopy.Model(description)
fit = model.fit(frame, obj='MLW', options={'ftol': 1e-12, 'maxiter': 2000})
if not fit.success:
    raise RuntimeError(fit.message)
print('semopy', semopy.__version__)
estimates = model.inspect()
stats = semopy.calc_stats(model)
print(estimates.to_string(index=False))
print(stats[['chi2','DoF','chi2 p-value']])
beta = estimates.query("lval == 'eta' and op == '~' and rval == 'xi'")['Estimate'].iloc[0]
# Valores redondeados de la celda Pyodide; las tolerancias admiten diferencias numéricas.
print('Comparación: beta propia 0.60598; semopy', round(beta,5))
print('Comparación: chi2 propio 14.52508; semopy', round(stats['chi2'].iloc[0],5))
assert abs(beta - .60598) < 1e-4
assert abs(stats['chi2'].iloc[0] - 14.52508) < 1e-3
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

ProofTwo structures, the same observations
Prove: Let P and Q be independent standard normals. Construct two systems with downward-sloping demand and upward-sloping supply producing exactly the same observable distribution, even with independent structural shocks.
0
Use Q=−bP+u_d and Q=dP+u_s with b,d>0.

Step 1 of 3. Which shocks make both equations hold for observed P and Q?

QuizOrder and rank in three equations
In B·y+Γ·z=u there are three endogenous variables and every B coefficient is nonzero. Γ rows are (0,0,1,1), (0,1,0,0) and (1,0,1,1). How do exclusions and rank classify the three equations in order?
NumericSEM degrees of freedom
There are eight indicators, four per factor, and two factors with one loading fixed to one in each block. Estimate six remaining loadings, variance of the first factor, variance of the second's independent disturbance, the structural coefficient between factors and eight error variances. With only covariance moments and full local rank, how many degrees of freedom does the global test have?
QuizForecasting under a new policy
A consumption-on-income regression was estimated under a known fiscal rule. Which forecast is especially exposed to the Lucas critique?
CodeCheck order and rank
Implement check_identification(B, Gamma, eq), where the system has form B @ y + Gamma @ z = u. Each row is an equation, each B column is an endogenous variable and each Gamma column is exogenous. eq is the equation index and its dependent variable is at the same position; its diagonal coefficient must be nonzero. Treat an exactly zero entry as a structural exclusion restriction, not an estimated coefficient close to zero. Return a dictionary with estado, orden and rango: estado is no identificada (unidentified), exacta (exactly identified) or sobreidentificada (overidentified); orden is the number of endogenous and exogenous variables excluded from the equation and rango is the rank of the submatrix formed from their columns and all other rows. The order condition requires at least m−1 exclusions and the rank condition requires rank m−1. Reject non-two-dimensional matrices, incompatible dimensions, fewer than two equations, nonfinite values, zero diagonal coefficients, singular B and invalid indices. Use np.linalg.matrix_rank with its standard numerical tolerance. Assume exogenous variables have sufficient independent variation and supplied zeros and coefficients describe the structural system. The rank test proves neither exogeneity nor causality.
import numpy as np


def check_identification(B, Gamma, eq):
  """Clasifica la ecuación por orden y rango de las exclusiones."""
  pass
Shift+Enter to run

The cell checks matrices used as test references:

[ ]Check exclusion ranksBrowser
"""Referencias numéricas de los ejemplos de orden y rango."""
import numpy as np

singular = np.array([[1.,2.],[2.,4.]])
identified = np.array([[1.,2.],[2.,5.]])
endog_exog = np.array([[1.,1.],[.7,2.]])
print('Matriz colineal: determinante y rango:', np.linalg.det(singular), np.linalg.matrix_rank(singular))
print('Matriz perturbada: determinante y rango:', np.linalg.det(identified), np.linalg.matrix_rank(identified))
print('Exclusiones de una endógena y una exógena, determinante y rango:',
      np.linalg.det(endog_exog), np.linalg.matrix_rank(endog_exog))
[ ]Check the system and degrees of freedomBrowser
import numpy as np
B_quiz=np.array([[1.,.2,.1],[.2,1.,.3],[.3,.1,1.]])
G_quiz=np.array([[0.,0.,1.,1.],[0.,1.,0.,0.],[1.,0.,1.,1.]])
for eq in range(3):
    print('Ecuación, estado, orden y rango:',eq+1,*identification(B_quiz,G_quiz,eq))
p=8
moments=p*(p+1)//2
free=6+2+1+8
print('SEM: momentos, parámetros libres, grados de libertad:',moments,free,moments-free)
for b,d in ((1.,1.),(2.,.5)):
    print('Pendientes de demanda y oferta, covarianza de shocks:',-b,d,1-b*d)