"""F5-conf-02: Finite-sample bias of OLS AR(1) coefficient (with intercept). Run from workspace root: ~/wp29/venv/bin/python out/analysis.py Reads only data/design.csv; writes out/results.json and out/exclusions.csv. """ import json, math, csv from pathlib import Path import numpy as np import pandas as pd ROOT = Path(__file__).resolve().parent.parent d = pd.read_csv(ROOT / "data" / "design.csv") p = dict(zip(d["parameter"], d["value"])) n = int(p["n"]); rho = float(p["rho"]); sigma = float(p["sigma"]) R = int(p["n_replications"]); seed = int(p["seed"]) assert str(p["intercept"]).strip().lower() == "yes" assert str(p["initial_condition"]).strip().lower() == "stationary" assert abs(rho) < 1 # --- Baseline / analytical quantities --- bias_analytical = -(1 + 3 * rho) / n se_asymptotic = math.sqrt((1 - rho ** 2) / n) # --- Monte Carlo (vectorised over replications), c = 0 --- rng = np.random.default_rng(seed) # Draw order: first y_1 for all R replications, then the (R, n-1) innovation matrix. y = np.empty((R, n)) y[:, 0] = rng.normal(0.0, sigma / math.sqrt(1 - rho ** 2), size=R) eps = rng.normal(0.0, sigma, size=(R, n - 1)) for t in range(1, n): y[:, t] = rho * y[:, t - 1] + eps[:, t - 1] # OLS of y_t on (1, y_{t-1}), t = 2..n: slope = cov(x,z)/var(x) with demeaning x = y[:, :-1]; z = y[:, 1:] xc = x - x.mean(axis=1, keepdims=True) zc = z - z.mean(axis=1, keepdims=True) rho_hat = (xc * zc).sum(axis=1) / (xc ** 2).sum(axis=1) # Spot check against explicit least squares for the first replication X0 = np.column_stack([np.ones(n - 1), x[0]]) b0 = np.linalg.lstsq(X0, z[0], rcond=None)[0] assert abs(b0[1] - rho_hat[0]) < 1e-10 # Exclusion ledger: non-finite estimates (none expected) finite = np.isfinite(rho_hat) rh = rho_hat[finite] with open(ROOT / "out" / "exclusions.csv", "w", newline="") as f: w = csv.writer(f) w.writerow(["step", "rule", "n_before", "n_after", "n_removed", "rationale"]) w.writerow([1, "drop replications with non-finite rho_hat", R, int(finite.sum()), int(R - finite.sum()), "OLS slope undefined if regressor has zero variance (probability zero)"]) rho_hat_mean = float(rh.mean()) rho_hat_sd = float(rh.std(ddof=1)) bias_mc = rho_hat_mean - rho bias_mc_se = rho_hat_sd / math.sqrt(rh.size) disc = (bias_mc - bias_analytical) / bias_mc_se res = { "task_id": "F5-conf-02", "bias_analytical": bias_analytical, "bias_mc": bias_mc, "bias_mc_se": bias_mc_se, "rho_hat_mean": rho_hat_mean, "rho_hat_sd_mc": rho_hat_sd, "discrepancy_se_units": disc, "se_asymptotic": se_asymptotic, "n_replications": R, "feasibility": "complete", "feasibility_reason": None, "data_issues": [], "n_input_rows": {"design.csv": int(len(d))}, "n_analysed": int(rh.size), "random_seed": seed, # supplementary (not required) descriptive quantities "supp_bias_analytical_n_minus_1": -(1 + 3 * rho) / (n - 1), "supp_rho_hat_median": float(np.median(rh)), "supp_ratio_bias_mc_to_analytical": bias_mc / bias_analytical, "supp_ratio_sd_mc_to_se_asymptotic": rho_hat_sd / se_asymptotic, } with open(ROOT / "out" / "results.json", "w") as f: json.dump(res, f, indent=2) for k, v in res.items(): print(f"{k}: {v}")