"""F2-conf-03: Monte Carlo coverage of OLS slope CIs under heteroskedasticity. Run from workspace root: ~/wp29/venv/bin/python out/analysis.py Reads only data/design.csv; writes out/results.json deterministically.""" import json, os import numpy as np import 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 = [] assert d.shape[0] == 30 and d[["x", "sigma"]].notna().all().all() and (d.sigma > 0).all() x = d["x"].to_numpy(float); s = d["sigma"].to_numpy(float); n = len(x); df = n - 2 tcrit = stats.t.ppf(0.5 + LEVEL / 2, df) xc = x - x.mean(); Sxx = np.sum(xc ** 2); w = xc / Sxx sd_exact = float(np.sqrt(np.sum(w ** 2 * s ** 2))) # (c) analytic rng = np.random.default_rng(SEED) eps = rng.standard_normal((R, n)) Y = ALPHA + BETA * x + s * eps # R x n bhat = (Y - Y.mean(axis=1, keepdims=True)) @ xc / Sxx ahat = Y.mean(axis=1) - bhat * x.mean() e = Y - ahat[:, None] - bhat[:, None] * x se_conv = np.sqrt(np.sum(e ** 2, axis=1) / df / Sxx) hc0 = np.sum((xc ** 2) * e ** 2, axis=1) / Sxx ** 2 se_hc1 = np.sqrt(hc0 * n / df) cov_conv = float(np.mean(np.abs(bhat - BETA) <= tcrit * se_conv)) cov_hc1 = float(np.mean(np.abs(bhat - BETA) <= tcrit * se_hc1)) mcse_nominal = float(np.sqrt(LEVEL * (1 - LEVEL) / R)) undercovers = bool((LEVEL - cov_conv) > 3 * mcse_nominal) 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(bhat, ddof=1)), "mean_se_conventional": float(np.mean(se_conv)), "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(d.shape[0])}, "random_seed": SEED, # supplementary diagnostics "t_crit_28": float(tcrit), "mcse_at_nominal": mcse_nominal, "undercoverage_threshold": float(LEVEL - 3 * mcse_nominal), "mcse_coverage_conventional": float(np.sqrt(cov_conv * (1 - cov_conv) / R)), "mcse_coverage_hc1": float(np.sqrt(cov_hc1 * (1 - cov_hc1) / R)), "mean_se_hc1": float(np.mean(se_hc1)), "mean_bhat_mc": float(np.mean(bhat)), "sd_beta_homoskedastic_formula": float(np.sqrt(np.mean(s ** 2) / Sxx)), } 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))