"""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, N, R = 1.0, 0.5, 30, 2000 d = pd.read_csv("data/design.csv") issues = [] n_rows = len(d) if d[["x", "sigma"]].isna().any().any(): issues.append({"issue": "missing values", "handling": "none dropped; would fail"}) if (d["sigma"] <= 0).any(): issues.append({"issue": "non-positive sigma", "handling": "flagged"}) if n_rows != N: issues.append({"issue": f"expected {N} rows, got {n_rows}", "handling": "flagged"}) x = d["x"].to_numpy(float); sig = d["sigma"].to_numpy(float) n = len(x) X = np.column_stack([np.ones(n), x]) XtXi = np.linalg.inv(X.T @ X) A = XtXi @ X.T # beta_hat = A y a = A[1] # weights for slope sd_exact = float(np.sqrt(np.sum(a**2 * sig**2))) # Var = sum w_i^2 sigma_i^2 sd_naive_formula = float(np.sqrt(np.mean(sig**2) * XtXi[1, 1])) # for reference only tcrit = stats.t.ppf(0.975, 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 @ A.T # R x 2 resid = Y - B @ X.T s2 = (resid**2).sum(1) / (n - 2) se_conv = np.sqrt(s2 * XtXi[1, 1]) hc0 = (resid**2) @ (a**2) # slope element of sandwich se_hc1 = np.sqrt(hc0 * 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_conv = float(np.sqrt(cov_conv * (1 - cov_conv) / R)) mcse_hc1 = float(np.sqrt(cov_hc1 * (1 - cov_hc1) / R)) mcse_nominal = float(np.sqrt(0.95 * 0.05 / R)) # Decision rule: binomial MC SE at R (evaluated at the estimated coverage) undercovers = bool(cov_conv < 0.95 - 3 * mcse_conv) 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": n_rows}, "random_seed": SEED, } os.makedirs("out", exist_ok=True) with open("out/results.json", "w") as f: json.dump(res, f, indent=2) extra = {"mcse_coverage_conventional": mcse_conv, "mcse_coverage_hc1": mcse_hc1, "mcse_at_nominal_0.95": mcse_nominal, "undercovers_using_nominal_mcse": bool(cov_conv < 0.95 - 3 * mcse_nominal), "t_crit": float(tcrit), "mean_se_hc1": float(se_hc1.mean()), "homoskedastic_formula_sd_with_mean_sigma2": sd_naive_formula, "mean_beta_hat": float(bh.mean())} with open("out/diagnostics.json", "w") as f: json.dump(extra, f, indent=2) print(json.dumps(res, indent=2)); print(json.dumps(extra, indent=2))