#!/usr/bin/env python3 """Post hoc simulation (RULES_sim.txt): false-positive rate of a 6-hour moving-block bootstrap test of one day against 26-30 other days, when hourly departures carry a day-to-day component. Needs numpy. Usage: python3 -I block_bootstrap_sim.py [FOLDER] FOLDER (default: this script's folder) holds fig7_digitized_hourly.csv, used only for the context numbers.""" import csv import datetime as dt import json import os import sys import numpy as np FOLDER = sys.argv[1] if len(sys.argv) > 1 else os.path.dirname(os.path.abspath(__file__)) rng = np.random.default_rng(20261115) B, REPS, BLOCK = 999, 400, 6 def boot_means(z, B): n = len(z); L = min(BLOCK, n) starts = rng.integers(0, n - L + 1, size=(B, int(np.ceil(n / L)))) offs = np.arange(L) idx = (starts[:, :, None] + offs[None, None, :]).reshape(B, -1)[:, :n] return z[idx].mean(axis=1) def test(x, y): obs = x.mean() - y.mean() d = boot_means(x, B) - boot_means(y, B) return (np.sum(np.abs(d - obs) >= abs(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 in (0.0, 0.5, 0.7, 0.9): # amendment 1: within-day lag-1 correlation varied; 0 is the sanity check for share in (0.0, 0.2): ps = [] for r in range(REPS): days = [day_series(share, PHI) for _ in range(31)] ps.append(test(days[0], np.concatenate(days[1:]))) ps = np.array(ps) key = "phi=%.1f share=%.1f" % (PHI, share) res[key] = {"reps": REPS, "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]) res_pooled = {} for PHI in (0.0, 0.5, 0.7, 0.9): # amendment 2: the pooled design, 4 days against 27 for share in (0.0, 0.2): ps = [] for r in range(REPS): days = [day_series(share, PHI) for _ in range(31)] ps.append(test(np.concatenate(days[:4]), np.concatenate(days[4:]))) ps = np.array(ps) key = "phi=%.1f share=%.1f" % (PHI, share) res_pooled[key] = {"reps": REPS, "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("pooled", key, res_pooled[key]) # context: between-day share of variance on the figure's ordinary days ctx = {} rows = {} with open(os.path.join(FOLDER, "fig7_digitized_hourly.csv"), encoding="utf-8") as fh: for r in csv.DictReader(fh): t = dt.datetime.strptime(r["time_utc"], "%Y-%m-%d %H:%M") if r["retained"] == "1" and t.day in (7, 8, 9, 14, 15, 16): rows.setdefault(r["station"], {}).setdefault(t.day, []).append(float(r["departure"])) for st, dd in sorted(rows.items()): dd = {k: v for k, v in dd.items() if len(v) >= 8} if len(dd) < 3: continue allv = np.concatenate(list(dd.values())) means = np.array([np.mean(v) for v in dd.values()]) ctx[st] = {"days": len(dd), "between_day_share": round(float(np.var(means, ddof=1) / np.var(allv, ddof=1)), 2)} print(ctx) with open(os.path.join(FOLDER, "block_bootstrap_sim_results.json"), "w", encoding="utf-8", newline="\n") as fh: json.dump({"simulation_daily": res, "simulation_pooled_4_days": res_pooled, "figure7_between_day_share": ctx}, fh, indent=1)