File size: 5,686 Bytes
c383c28 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 | #!/usr/bin/env python3
"""Full parameter reporting and estimator-bias check for the reference study.
Replays capacity_simulation.py with the same seed and the same sequence of
random draws, but records all four fitted parameters in every bootstrap
replicate. The published midpoint intervals are reproduced exactly as a check.
A separate Monte Carlo of the direct logistic control estimates the fitter's
systematic bias at this design. All inputs are synthetic constructions.
"""
from __future__ import annotations
import json
from pathlib import Path
import numpy as np
import capacity_simulation as S
ATTAINABLE_MAX = 0.95 # recovered events are scored correct with probability .95
def bootstrap_all(rng, values, repetitions=400):
"""Same draws as S.bootstrap_midpoint, but keeps every parameter."""
draws = []
for _ in range(repetitions):
means = np.array([rng.choice(values[int(n)], size=len(values[int(n)]), replace=True).mean()
for n in S.TEAM_SIZES])
draws.append(S.fit_curve(S.TEAM_SIZES, means))
return np.array(draws) # columns: floor, span, midpoint, tau
def summarize(theta, draws):
ceil_draws = draws[:, 0] + draws[:, 1]
q = lambda v: [float(x) for x in np.quantile(v, [0.025, 0.975])]
return {
"floor": float(theta[0]), "floor_ci": q(draws[:, 0]),
"ceiling": float(theta[0] + theta[1]), "ceiling_ci": q(ceil_draws),
"midpoint": float(theta[2]), "midpoint_ci": q(draws[:, 2]),
"tau": float(theta[3]), "tau_ci": q(draws[:, 3]),
"corr_midpoint_tau": float(np.corrcoef(draws[:, 2], draws[:, 3])[0, 1]),
"corr_midpoint_ceiling": float(np.corrcoef(draws[:, 2], ceil_draws)[0, 1]),
"ceiling_above_attainable": bool(theta[0] + theta[1] > ATTAINABLE_MAX),
}
def main():
rng = np.random.default_rng(S.SEED)
out = {}
# direct logistic control, identical draw order to S.direct_logistic_control
truth = np.array([0.15, 0.80, 4.35, 0.90])
values, means = {}, []
for n in S.TEAM_SIZES.astype(int):
p = float(S.logistic(np.array([n]), *truth)[0])
sc = rng.binomial(1, p, size=S.SESSIONS_PER_SIZE).astype(float)
values[n] = sc; means.append(float(sc.mean()))
theta = S.fit_curve(S.TEAM_SIZES, np.array(means))
out["direct_control"] = summarize(theta, bootstrap_all(rng, values))
# queue conditions, identical draw order to S.main
for cond in S.CONDITIONS:
values, means = {}, []
for n in S.TEAM_SIZES.astype(int):
sc = np.array([S.simulate_session(rng, n, cond) for _ in range(S.SESSIONS_PER_SIZE)])
sc = sc[np.isfinite(sc)]; values[n] = sc; means.append(float(sc.mean()))
theta = S.fit_curve(S.TEAM_SIZES, np.array(means))
out[cond] = summarize(theta, bootstrap_all(rng, values))
# reproduction check against the published summary
pub = json.loads(Path("simulation_summary.json").read_text())
checks = {"direct_control": pub["direct_logistic_control"]["midpoint_ci"]}
checks.update({c: pub[c]["midpoint_ci"] for c in S.CONDITIONS})
out["reproduces_published_midpoint_ci"] = all(
np.allclose(out[k]["midpoint_ci"], v, atol=1e-9) for k, v in checks.items())
# estimator bias: Monte Carlo replicates of the direct control (independent seed)
mc = np.random.default_rng(S.SEED + 1)
fitted = []
for _ in range(500):
m = [mc.binomial(1, float(S.logistic(np.array([n]), *truth)[0]), size=S.SESSIONS_PER_SIZE).mean()
for n in S.TEAM_SIZES.astype(int)]
fitted.append(S.fit_curve(S.TEAM_SIZES, np.array(m))[2])
fitted = np.array(fitted)
bias = float(fitted.mean() - truth[2])
n0 = pub["design"]["predicted_midpoint"]
add = out["additive"]
out["estimator_bias"] = {
"replicates": 500, "true_midpoint": float(truth[2]),
"mean_fitted": float(fitted.mean()), "bias": bias,
"sd_fitted": float(fitted.std(ddof=1)),
"mc_se_of_bias": float(fitted.std(ddof=1) / np.sqrt(len(fitted))),
}
out["additive_gap"] = {
"n0": n0, "raw_gap": add["midpoint"] - n0,
"raw_gap_ci": [add["midpoint_ci"][0] - n0, add["midpoint_ci"][1] - n0],
"bias_corrected_gap": add["midpoint"] - bias - n0,
"bias_corrected_gap_ci": [add["midpoint_ci"][0] - bias - n0, add["midpoint_ci"][1] - bias - n0],
"gap_in_tau_units": (add["midpoint"] - bias - n0) / add["tau"],
}
Path("capacity_parameters.json").write_text(json.dumps(out, indent=2) + "\n")
print(f"reproduces published midpoint CIs exactly: {out['reproduces_published_midpoint_ci']}\n")
print(f"{'condition':15}{'floor':>20}{'ceiling':>20}{'midpoint':>20}{'tau':>20}{'r(mid,tau)':>11}")
for k in ["direct_control", *S.CONDITIONS]:
r = out[k]; f = lambda a, b: f"{r[a]:.2f} [{r[b][0]:.2f},{r[b][1]:.2f}]"
flag = " ceiling>.95" if r["ceiling_above_attainable"] else ""
print(f"{k:15}{f('floor','floor_ci'):>20}{f('ceiling','ceiling_ci'):>20}"
f"{f('midpoint','midpoint_ci'):>20}{f('tau','tau_ci'):>20}{r['corr_midpoint_tau']:>11.2f}{flag}")
b = out["estimator_bias"]; g = out["additive_gap"]
print(f"\nfitter bias over 500 replicates: {b['bias']:+.3f} (MC s.e. {b['mc_se_of_bias']:.3f}; "
f"single-replicate SD {b['sd_fitted']:.3f})")
print(f"additive gap raw {g['raw_gap']:+.3f} [{g['raw_gap_ci'][0]:+.3f},{g['raw_gap_ci'][1]:+.3f}]; "
f"bias-corrected {g['bias_corrected_gap']:+.3f} [{g['bias_corrected_gap_ci'][0]:+.3f},"
f"{g['bias_corrected_gap_ci'][1]:+.3f}] = {g['gap_in_tau_units']:+.2f} tau")
if __name__ == "__main__":
main()
|