#!/usr/bin/env python3 """Post hoc (RULES_sim_amendment3.txt): does the false-positive rate of the daily 6-hour block-bootstrap test depend on how the bootstrap is implemented? Needs numpy. Usage: python3 -I block_bootstrap_variants.py""" import json, os, sys import numpy as np rng = np.random.default_rng(20261115) B, REPS, BLOCK = 999, 300, 6 OUT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "block_bootstrap_variants_results.json") def idx_blocks(n, circular): L = min(BLOCK, n); k = int(np.ceil(n / L)) starts = rng.integers(0, n if circular else n - L + 1, size=(B, k)) idx = (starts[:, :, None] + np.arange(L)[None, None, :]).reshape(B, -1)[:, :n] return idx % n if circular else idx def p_value(x, y, variant): obs = x.mean() - y.mean() circ = variant != "a" d = x[idx_blocks(len(x), circ)].mean(axis=1) - y[idx_blocks(len(y), circ)].mean(axis=1) if variant in ("a", "b"): return (np.sum(np.abs(d - obs) >= abs(obs)) + 1) / (B + 1) sd = d.std(ddof=1) t_obs = obs / sd # second-level SD for each first-level resample is approximated by the same sd (one-level studentization) t_star = (d - obs) / sd return (np.sum(np.abs(t_star) >= abs(t_obs)) + 1) / (B + 1) def day_series(share, phi): u = rng.normal(0, np.sqrt(share)); e = np.empty(24); e[0] = rng.normal() for h in range(1, 24): e[h] = phi * e[h - 1] + np.sqrt(1 - phi ** 2) * rng.normal() x = u + np.sqrt(1 - share) * e L = rng.integers(8, 21); s = rng.integers(0, 24 - L + 1) return x[s:s + L] res = {} for phi, share in ((0.0, 0.0), (0.5, 0.2), (0.7, 0.2)): for v in ("a", "b", "c"): ps = [] for r in range(REPS): days = [day_series(share, phi) for _ in range(31)] ps.append(p_value(days[0], np.concatenate(days[1:]), v)) ps = np.array(ps) key = "phi=%.1f share=%.1f variant=%s" % (phi, share, v) res[key] = {"rate_p_lt_0.05": round(float(np.mean(ps < 0.05)), 3), "rate_p_le_0.001": round(float(np.mean(ps <= 0.001)), 3)} print(key, res[key]) with open(OUT, "w", encoding="utf-8", newline="\n") as fh: json.dump(res, fh, indent=1)