"""F2-conf-03: Monte Carlo coverage of OLS CIs under heteroskedasticity. Run from workspace root: ~/wp29/venv/bin/python out/analysis.py""" import json, os import numpy as np, pandas as pd from scipy import stats SEED = 20261030 ALPHA, BETA, R, LEVEL = 1.0, 0.5, 2000, 0.95 d = pd.read_csv("data/design.csv") issues = [] if d.isna().any().any(): issues.append({"issue": "missing values", "handling": "none expected; would abort"}) x, sig = d["x"].to_numpy(float), d["sigma"].to_numpy(float) n = len(x) assert n == 30 and (sig > 0).all() X = np.column_stack([np.ones(n), x]) XtX_inv = np.linalg.inv(X.T @ X) xc = x - x.mean(); Sxx = xc @ xc w = xc / Sxx # beta_hat = beta + sum w_i sigma_i eps_i sd_exact = float(np.sqrt(np.sum(w**2 * sig**2))) tcrit = stats.t.ppf(0.5 + LEVEL / 2, n - 2) rng = np.random.default_rng(SEED) eps = rng.standard_normal((R, n)) Y = ALPHA + BETA * x + sig * eps # R x n B = Y @ X @ XtX_inv # (XtX)^-1 X'y for each row (XtX_inv symmetric) E = Y - B @ X.T # residuals s2 = (E**2).sum(1) / (n - 2) se_conv = np.sqrt(s2 * XtX_inv[1, 1]) # HC0 sandwich slope variance: sum (row-2 of (XtX)^-1 X')_i^2 e_i^2 ; HC1 = HC0 * n/(n-2) a = (XtX_inv @ X.T)[1] # equals w se_hc1 = np.sqrt((a**2 * E**2).sum(1) * n / (n - 2)) bh = B[:, 1] cov_conv = float(np.mean(np.abs(bh - BETA) <= tcrit * se_conv)) cov_hc1 = float(np.mean(np.abs(bh - BETA) <= tcrit * se_hc1)) mcse_nom = float(np.sqrt(LEVEL * (1 - LEVEL) / R)) undercovers = bool(cov_conv < LEVEL - 3 * mcse_nom) res = { "task_id": "F2-conf-03", "coverage_conventional": cov_conv, "coverage_hc1": cov_hc1, "sd_beta_exact": sd_exact, "sd_beta_mc": float(np.std(bh, ddof=1)), "mean_se_conventional": float(se_conv.mean()), "conventional_ci_undercovers": undercovers, "n_replications": R, "n_obs_per_replication": n, "feasibility": "complete", "feasibility_reason": None, "data_issues": issues, "n_input_rows": {"design.csv": int(len(d))}, "random_seed": SEED, # supplementary keys "t_crit_28": float(tcrit), "mcse_binomial_at_nominal": mcse_nom, "mcse_coverage_conventional": float(np.sqrt(cov_conv * (1 - cov_conv) / R)), "mcse_coverage_hc1": float(np.sqrt(cov_hc1 * (1 - cov_hc1) / R)), "undercover_threshold": float(LEVEL - 3 * mcse_nom), "mean_se_hc1": float(se_hc1.mean()), "sd_beta_conventional_formula_homoskedastic": float(np.sqrt(np.mean(sig**2) * XtX_inv[1, 1])), "mean_beta_hat_mc": float(bh.mean()), } os.makedirs("out", exist_ok=True) with open("out/results.json", "w") as f: json.dump(res, f, indent=2) print(json.dumps(res, indent=2))