Download scripts/exp03_ci_coverage.py from JG1310/repro-seq-mean-testing-bundle: direct link, hf CLI and curl.
- Browser
- Download file 17.4 kB
-
https://huggingface.co/datasets/JG1310/repro-seq-mean-testing-bundle/resolve/main/scripts/exp03_ci_coverage.py
- Command line
-
hf download hf://datasets/JG1310/repro-seq-mean-testing-bundle/scripts/exp03_ci_coverage.py
-
curl -L -o exp03_ci_coverage.py https://huggingface.co/datasets/JG1310/repro-seq-mean-testing-bundle/resolve/main/scripts/exp03_ci_coverage.py
17.4 kB
| #!/usr/bin/env python3 | |
| """exp03 -- single-run confidence interval for the stopping time (Prop. 4.5). | |
| Per specs/exp03_ci_coverage.md. Writes results/exp03.json. | |
| python3 scripts/exp03_ci_coverage.py [--toy] | |
| Reuses exp02's shared-stream path machinery (core.klinf / core.par): one | |
| replicate = one path shared across every (alpha, beta_kind) pair, since the | |
| crossing statistic n*KL_inf(q_hat_n, m_o) does not depend on alpha. At each | |
| step the dual solve already yields ell(lam*_n, X_1..n); from that single array | |
| we get, with no extra sampling cost, both the "direct centred" sigma_hat^2 | |
| (eq. 22's own definition) and an independently-summed mean(ell)/mean(ell^2) | |
| form -- comparing the two is the C3a/C3b identity cross-check the spec asks | |
| for, not two different estimators. | |
| """ | |
| import argparse | |
| import functools | |
| import json | |
| import math | |
| import os | |
| import sys | |
| import time | |
| import numpy as np | |
| from scipy.stats import norm | |
| sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) | |
| from core import par | |
| from core.klinf import klinf_emp, ell | |
| from core.popquant import pop | |
| RESULTS_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "results") | |
| OUT_PATH = os.path.join(RESULTS_DIR, "exp03.json") | |
| SEED_BASE = 20260722 # independent of exp02's 20260721 stream | |
| N_MAX = 200000 | |
| BETA_KINDS = ["theory", "practical"] # eq. 7 / eq. 8 | |
| GAMMAS = [0.10, 0.05, 0.01] | |
| ALPHA_GRID_FULL = [1e-2, 1e-3, 1e-4, 1e-6, 1e-8, 1e-10, 1e-12] | |
| ALPHA_GRID_TOY = [1e-2, 1e-4, 1e-6] | |
| R_FULL = 5000 | |
| R_TOY = 200 | |
| CONFIGS_META = [ | |
| dict(id="bern0.6_mo0.2", dist="bernoulli(0.6)", dist_kind="bernoulli", | |
| dist_params=(0.6,), popdist=("bernoulli", 0.6), m_o=0.2), | |
| dict(id="beta3_2_mo0.7", dist="beta(3,2)", dist_kind="beta", | |
| dist_params=(3, 2), popdist=("beta", 3, 2), m_o=0.7), | |
| dict(id="bern0.6_mo0.7", dist="bernoulli(0.6)", dist_kind="bernoulli", | |
| dist_params=(0.6,), popdist=("bernoulli", 0.6), m_o=0.7), | |
| ] | |
| S4_CONFIG_ID = "bern0.6_mo0.2" | |
| S4_BETA_KIND = "practical" | |
| S4_GAMMA = 0.05 | |
| S4_ALPHAS = [1e-4, 1e-8] | |
| Z95 = 1.959963984540054 # Wilson interval z for 95% CI on coverage | |
| def log(msg): | |
| print(f"[exp03] {msg}", file=sys.stderr, flush=True) | |
| def n_cores(): | |
| return max(1, min(int(os.environ.get("JOB_CORES", "4")), os.cpu_count() or 1)) | |
| # --------------------------------------------------------------- sampling | |
| def _make_sampler(dist_kind, dist_params): | |
| if dist_kind == "bernoulli": | |
| p, = dist_params | |
| return lambda rng, k: (rng.uniform(size=k) < p).astype(float) | |
| if dist_kind == "beta": | |
| a, b = dist_params | |
| return lambda rng, k: rng.beta(a, b, size=k) | |
| raise ValueError(dist_kind) | |
| # ------------------------------------------------------------- beta(n,alpha) | |
| def beta_theory(n, alpha): | |
| return 1.0 + math.log(2.0 * (1.0 + n) / alpha) | |
| def beta_practical(n, alpha): | |
| return math.log(1.0 / alpha) | |
| _BETA_FNS = {"theory": beta_theory, "practical": beta_practical} | |
| # ------------------------------------------------------ shared-stream sim | |
| def _run_path_multi(rng, sampler, m_o, alphas, beta_kinds, n_max, n_chunk=256): | |
| """One path shared by every (alpha, beta_kind) pair. At each crossing, | |
| records tau, klinf_tau (=mean(ell) by construction) and sigma2_tau (the | |
| direct-centred eq. 22 variance). Also tracks, across all crossings on | |
| this path, the worst-case |mean(ell) - klinf_hat| (C3a identity) and | |
| |direct-form - eq22-form sigma_hat^2| (C3b form cross-check), plus the | |
| path's min sigma_hat^2.""" | |
| x = np.empty(n_max, dtype=float) | |
| n = 0 | |
| lam_prev = None | |
| pending = set((a, bk) for a in alphas for bk in beta_kinds) | |
| out = {} | |
| max_id1 = 0.0 | |
| max_id2 = 0.0 | |
| min_sigma2 = math.inf | |
| while n < n_max and pending: | |
| take = min(n_chunk, n_max - n) | |
| x[n:n + take] = sampler(rng, take) | |
| for _ in range(take): | |
| n += 1 | |
| xk = x[:n] | |
| val, lam, case = klinf_emp(xk, m_o, lam_hint=lam_prev) | |
| lam_prev = lam if case == "interior" else None | |
| stat = n * val | |
| crossed_now = [(a, bk) for (a, bk) in pending if stat >= _BETA_FNS[bk](n, a)] | |
| if crossed_now: | |
| ell_arr = ell(lam, xk, m_o) | |
| mean_ell = float(np.mean(ell_arr)) | |
| mean_ell2 = float(np.mean(ell_arr * ell_arr)) | |
| sigma2_direct = float(np.mean((ell_arr - val) ** 2)) | |
| sigma2_eq22 = mean_ell2 - mean_ell * mean_ell | |
| id1 = abs(mean_ell - val) | |
| id2 = abs(sigma2_direct - sigma2_eq22) | |
| if id1 > max_id1: | |
| max_id1 = id1 | |
| if id2 > max_id2: | |
| max_id2 = id2 | |
| if sigma2_direct < min_sigma2: | |
| min_sigma2 = sigma2_direct | |
| for (a, bk) in crossed_now: | |
| out[(a, bk)] = dict(tau=n, censored=False, | |
| klinf_tau=val, sigma2_tau=sigma2_direct) | |
| pending.discard((a, bk)) | |
| if not pending: | |
| break | |
| for (a, bk) in pending: | |
| out[(a, bk)] = dict(tau=n, censored=True, klinf_tau=None, sigma2_tau=None) | |
| return dict(results=out, max_id1=max_id1, max_id2=max_id2, min_sigma2=min_sigma2) | |
| def _replicate_task(rng, r, dist_kind, dist_params, m_o, alphas, beta_kinds, n_max): | |
| sampler = _make_sampler(dist_kind, dist_params) | |
| return _run_path_multi(rng, sampler, m_o, alphas, beta_kinds, n_max) | |
| # ------------------------------------------------------------------ helpers | |
| def wilson_ci(phat, n, z=Z95): | |
| denom = 1.0 + z * z / n | |
| center = (phat + z * z / (2.0 * n)) / denom | |
| half = (z * math.sqrt(phat * (1.0 - phat) / n + z * z / (4.0 * n * n))) / denom | |
| return max(0.0, center - half), min(1.0, center + half) | |
| def loglog_fit(xs, ys): | |
| """Fit log(y) = a - rate*log(x) by OLS; return (rate, stderr(rate)).""" | |
| xs = np.asarray(xs, dtype=float) | |
| ys = np.asarray(ys, dtype=float) | |
| mask = (xs > 0) & (ys > 0) | |
| x = np.log(xs[mask]) | |
| y = np.log(ys[mask]) | |
| n = len(x) | |
| A = np.vstack([np.ones_like(x), x]).T | |
| coef, _, _, _ = np.linalg.lstsq(A, y, rcond=None) | |
| _, slope = coef | |
| rate = -float(slope) | |
| if n > 2: | |
| yhat = A @ coef | |
| resid = y - yhat | |
| dof = n - 2 | |
| sigma2 = float(np.sum(resid ** 2) / dof) if dof > 0 else 0.0 | |
| xtx_inv = np.linalg.inv(A.T @ A) | |
| se = float(np.sqrt(max(sigma2 * xtx_inv[1, 1], 0.0))) | |
| else: | |
| se = 0.0 | |
| return rate, se | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--toy", action="store_true") | |
| args = ap.parse_args() | |
| toy = args.toy | |
| n_jobs = n_cores() | |
| R = R_TOY if toy else R_FULL | |
| alpha_grid = ALPHA_GRID_TOY if toy else ALPHA_GRID_FULL | |
| log(f"starting exp03 (toy={toy}) n_jobs={n_jobs} R={R} alpha_grid={alpha_grid} " | |
| f"n_max={N_MAX} gammas={GAMMAS}") | |
| t0 = time.time() | |
| population = [] | |
| pop_by_id = {} | |
| for cm in CONFIGS_META: | |
| p = pop(cm["popdist"], cm["m_o"]) | |
| entry = dict(config=cm["id"], dist=cm["dist"], m_o=cm["m_o"], | |
| klinf=p["klinf"], inv_klinf=1.0 / p["klinf"], | |
| sigma2=p["sigma2"], sigma_bd2=p["sigma_bd2"], | |
| lam_star=p["lam_star"], case=p["case"]) | |
| population.append(entry) | |
| pop_by_id[cm["id"]] = entry | |
| log(f" population[{cm['id']}]: case={p['case']} lam*={p['lam_star']:.6f} " | |
| f"klinf={p['klinf']:.6f} inv_klinf={entry['inv_klinf']:.4f} " | |
| f"sigma2={p['sigma2']:.6f} sigma_bd2={p['sigma_bd2']:.6f}") | |
| s1_coverage, s2_vhat, s2_fit = [], [], [] | |
| s1_by_config = {cm["id"]: [] for cm in CONFIGS_META} | |
| s2_by_config = {cm["id"]: [] for cm in CONFIGS_META} | |
| width_slopes = [] | |
| global_max_id1 = 0.0 | |
| global_max_id2 = 0.0 | |
| global_min_sigma2 = math.inf | |
| raw_by_config = {} | |
| cfg_id = 0 | |
| for cm in CONFIGS_META: | |
| cfg_id += 1 | |
| pe = pop_by_id[cm["id"]] | |
| klinf_pop, inv_klinf_pop, sigma_bd2_pop = pe["klinf"], pe["inv_klinf"], pe["sigma_bd2"] | |
| log(f"=== {cm['id']} (dist={cm['dist']}, m_o={cm['m_o']}) R={R} alphas={alpha_grid} ===") | |
| t_cfg = time.time() | |
| task = functools.partial(_replicate_task, dist_kind=cm["dist_kind"], | |
| dist_params=cm["dist_params"], m_o=cm["m_o"], | |
| alphas=alpha_grid, beta_kinds=BETA_KINDS, n_max=N_MAX) | |
| raw = par.run_replicates(task, cfg_id, R, n_jobs=n_jobs, base_seed=SEED_BASE) | |
| raw_by_config[cm["id"]] = raw | |
| log(f" {cm['id']} done in {time.time() - t_cfg:.1f}s") | |
| for rep in raw: | |
| global_max_id1 = max(global_max_id1, rep["max_id1"]) | |
| global_max_id2 = max(global_max_id2, rep["max_id2"]) | |
| if rep["min_sigma2"] < global_min_sigma2: | |
| global_min_sigma2 = rep["min_sigma2"] | |
| for bk in BETA_KINDS: | |
| width_by_gamma_alpha = {g: {} for g in GAMMAS} | |
| for a in alpha_grid: | |
| b_alpha = math.log(1.0 / a) | |
| key = (a, bk) | |
| taus, klinfs, sigma2s, n_cens = [], [], [], 0 | |
| for rep in raw: | |
| r = rep["results"][key] | |
| if r["censored"]: | |
| n_cens += 1 | |
| continue | |
| taus.append(r["tau"]) | |
| klinfs.append(r["klinf_tau"]) | |
| sigma2s.append(r["sigma2_tau"]) | |
| taus = np.array(taus, dtype=float) | |
| klinfs = np.array(klinfs, dtype=float) | |
| sigma2s = np.array(sigma2s, dtype=float) | |
| vhat = sigma2s / klinfs ** 3 | |
| n_valid = len(taus) | |
| vhat_mean = float(np.mean(vhat)) | |
| vhat_median = float(np.median(vhat)) | |
| vhat_sd = float(np.std(vhat, ddof=1)) | |
| row2 = dict(config=cm["id"], beta_kind=bk, alpha=a, | |
| vhat_mean=vhat_mean, vhat_median=vhat_median, vhat_sd=vhat_sd, | |
| sigma_bd2=sigma_bd2_pop, | |
| vhat_mean_over_sigma_bd2=float(vhat_mean / sigma_bd2_pop), | |
| sigmahat2_over_sigma2=float(np.mean(sigma2s) / pe["sigma2"]), | |
| klinf_hat_over_klinf=float(np.mean(klinfs) / klinf_pop)) | |
| s2_vhat.append(row2) | |
| s2_by_config[cm["id"]].append(row2) | |
| for g in GAMMAS: | |
| z = float(norm.ppf(1.0 - g / 2.0)) | |
| center = taus / b_alpha | |
| half = z * np.sqrt(vhat / b_alpha) | |
| lo, hi = center - half, center + half | |
| widths = hi - lo | |
| covered = (lo <= inv_klinf_pop) & (inv_klinf_pop <= hi) | |
| miss_below = int(np.sum(inv_klinf_pop < lo)) | |
| miss_above = int(np.sum(inv_klinf_pop > hi)) | |
| n_covered = int(np.sum(covered)) if n_valid else 0 | |
| coverage = n_covered / R | |
| wilson_lo, wilson_hi = wilson_ci(coverage, R) | |
| nominal = 1.0 - g | |
| row1 = dict(config=cm["id"], beta_kind=bk, alpha=a, b_alpha=b_alpha, | |
| gamma=g, R=R, coverage=coverage, | |
| wilson_lo=wilson_lo, wilson_hi=wilson_hi, nominal=nominal, | |
| coverage_error=float(coverage - nominal), | |
| miss_below=miss_below, miss_above=miss_above, | |
| width_median=float(np.median(widths)) if n_valid else 0.0, | |
| width_iqr=float(np.percentile(widths, 75) - np.percentile(widths, 25)) | |
| if n_valid else 0.0, | |
| n_censored=n_cens) | |
| s1_coverage.append(row1) | |
| s1_by_config[cm["id"]].append(row1) | |
| width_by_gamma_alpha[g][b_alpha] = row1["width_median"] | |
| log(f" {cm['id']}/{bk} coverage sweep done") | |
| b_vals = [math.log(1.0 / a) for a in alpha_grid] | |
| vhat_sd_vals = [r["vhat_sd"] for r in s2_by_config[cm["id"]] if r["beta_kind"] == bk] | |
| p_rate, p_se = loglog_fit(b_vals, vhat_sd_vals) | |
| s2_fit.append(dict(config=cm["id"], beta_kind=bk, | |
| p_vhat_sd=p_rate, p_vhat_sd_stderr=p_se, n_points=len(b_vals))) | |
| log(f" {cm['id']}/{bk}: p_vhat_sd={p_rate:.3f}+/-{p_se:.3f}") | |
| for g in GAMMAS: | |
| bs = b_vals | |
| ws = [width_by_gamma_alpha[g][b] for b in bs] | |
| rate, se = loglog_fit(bs, ws) | |
| width_slopes.append(dict(config=cm["id"], beta_kind=bk, gamma=g, | |
| slope=-rate, slope_stderr=se)) | |
| # ------------------------------------------------------------------ S3 | |
| s3_identity = dict( | |
| max_mean_ell_minus_klinf=global_max_id1, | |
| max_sigmahat2_form_diff=global_max_id2, | |
| min_sigmahat2=global_min_sigma2, | |
| width_slopes=width_slopes, | |
| ) | |
| log(f"S3 identity: max_id1={global_max_id1:.2e} max_id2={global_max_id2:.2e} " | |
| f"min_sigma2={global_min_sigma2:.4f}") | |
| # ------------------------------------------------------------------ S4 | |
| s4_illustration = [] | |
| raw0 = raw_by_config[S4_CONFIG_ID] | |
| s4_alphas = S4_ALPHAS if not toy else alpha_grid[:2] | |
| for a in s4_alphas: | |
| b_alpha = math.log(1.0 / a) | |
| key = (a, S4_BETA_KIND) | |
| taus, klinfs, sigma2s = [], [], [] | |
| for rep in raw0: | |
| r = rep["results"][key] | |
| if r["censored"]: | |
| continue | |
| taus.append(r["tau"]) | |
| klinfs.append(r["klinf_tau"]) | |
| sigma2s.append(r["sigma2_tau"]) | |
| taus = np.array(taus, dtype=float) | |
| klinfs = np.array(klinfs, dtype=float) | |
| sigma2s = np.array(sigma2s, dtype=float) | |
| vhat = sigma2s / klinfs ** 3 | |
| z = float(norm.ppf(1.0 - S4_GAMMA / 2.0)) | |
| center = taus / b_alpha | |
| half = z * np.sqrt(vhat / b_alpha) | |
| lo, hi = (center - half) * b_alpha, (center + half) * b_alpha | |
| def qpair(lo_arr, hi_arr, q): | |
| return [float(np.percentile(lo_arr, q)), float(np.percentile(hi_arr, q))] | |
| s4_illustration.append(dict( | |
| alpha=a, gamma=S4_GAMMA, | |
| single_run_interval_median=qpair(lo, hi, 50), | |
| single_run_interval_q25=qpair(lo, hi, 25), | |
| single_run_interval_q75=qpair(lo, hi, 75), | |
| empirical_tau_interval=[float(np.percentile(taus, 2.5)), | |
| float(np.percentile(taus, 97.5))], | |
| )) | |
| log(f" S4 alpha={a:g}: median_interval={s4_illustration[-1]['single_run_interval_median']} " | |
| f"empirical_tau_interval={s4_illustration[-1]['empirical_tau_interval']}") | |
| # ------------------------------------------------- gate-facing adapter | |
| # gates.py's exp03 gate expects a flat per-config "configs" list (with a | |
| # "pop"/"coverage"/"consistency" view of the same numbers) plus a | |
| # top-level "self_consistency" scalar; this is a reshaped view of the | |
| # canonical sections above, not a second computation. | |
| configs_adapter = [] | |
| for cm in CONFIGS_META: | |
| pe = pop_by_id[cm["id"]] | |
| consistency = [dict(alpha=r["alpha"], beta_kind=r["beta_kind"], | |
| mean_vhat_over_sigma_bd2=r["vhat_mean_over_sigma_bd2"], | |
| sd_vhat=r["vhat_sd"]) | |
| for r in s2_by_config[cm["id"]]] | |
| configs_adapter.append(dict( | |
| dist=cm["dist"], m_o=cm["m_o"], | |
| pop=dict(lam_star=pe["lam_star"], klinf=pe["klinf"], sigma2=pe["sigma2"], | |
| sigma_bd2=pe["sigma_bd2"], case=pe["case"]), | |
| coverage=s1_by_config[cm["id"]], | |
| consistency=consistency, | |
| )) | |
| self_consistency = dict(max_abs_err=max(global_max_id1, global_max_id2)) | |
| elapsed = time.time() - t0 | |
| out = dict( | |
| meta=dict(spec="exp03", seed_base=SEED_BASE, n_paths=R, n_max=N_MAX, | |
| gammas=GAMMAS, cores_used=n_jobs, wall_seconds=elapsed), | |
| population=population, | |
| s1_coverage=s1_coverage, | |
| s2_vhat=s2_vhat, | |
| s2_fit=s2_fit, | |
| s3_identity=s3_identity, | |
| s4_illustration=s4_illustration, | |
| configs=configs_adapter, | |
| self_consistency=self_consistency, | |
| ) | |
| os.makedirs(RESULTS_DIR, exist_ok=True) | |
| with open(OUT_PATH, "w") as f: | |
| json.dump(out, f, indent=2) | |
| print(f"exp03 complete in {elapsed:.1f}s -> {OUT_PATH}") | |
| print(f" cores_used={n_jobs} R={R} n_configs={len(population)} alphas={alpha_grid}") | |
| print(f" s1_coverage rows={len(s1_coverage)} s2_vhat rows={len(s2_vhat)} " | |
| f"s2_fit rows={len(s2_fit)}") | |
| print(f" s3_identity: max|mean_ell-klinf|={global_max_id1:.2e} " | |
| f"max|sigma2_form_diff|={global_max_id2:.2e} min_sigma2={global_min_sigma2:.4f}") | |
| for row in s4_illustration: | |
| print(f" s4[alpha={row['alpha']:g}]: median_interval(tau-scale)=" | |
| f"{row['single_run_interval_median']} " | |
| f"empirical_tau_interval={row['empirical_tau_interval']}") | |
| if __name__ == "__main__": | |
| main() | |