"""Chart data (our recomputation, no test): Pipeline A's O/E by lag, -10..+15, with the 2.5-97.5% band of the same statistic over every circular shift (60..N-60) of the 127 t0; and the dose tiers from controls_C8.json. Writes results/chart_series.json.""" import json import os import sys sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import lib_ee as L # noqa: E402 N = L.N EV = L.load_events() T0 = [L.di(L.pdate(r["t0_peak_date"])) for r in L.read_csv(L.drive_file("PipelineA_storm_episodes_G3plus"))] Y = [0] * N for e in EV: Y[L.di(L.pdate(e["date_utc"]))] += 1 pre = [0] for v in Y: pre.append(pre[-1] + v) EA = [] for i in range(N): a, b = max(0, i - 182), min(N - 1, i + 182) EA.append((pre[b + 1] - pre[a]) / (b - a + 1)) def quant(v, q): s = sorted(v) return s[min(len(s) - 1, max(0, int(round(q * (len(s) - 1)))))] lags = list(range(-10, 16)) prof = [] for k in lags: o = sum(Y[t + k] for t in T0 if 0 <= t + k < N) e = sum(EA[t + k] for t in T0 if 0 <= t + k < N) # null: circular shifts; for a single lag the statistic at shift s is the same as lag 0 at shift s+k, # so one pass over all u gives every lag's null (u = s + k, s in 60..N-60) prof.append({"lag": k, "O": o, "E": round(e, 3), "OE": round(o / e, 4)}) CY = [sum(Y[(t + u) % N] for t in T0) for u in range(N)] CE = [sum(EA[(t + u) % N] for t in T0) for u in range(N)] for p in prof: k = p["lag"] vals = [CY[(s + k) % N] / CE[(s + k) % N] for s in range(60, N - 60 + 1)] p["null_lo"] = round(quant(vals, 0.025), 4) p["null_med"] = round(quant(vals, 0.5), 4) p["null_hi"] = round(quant(vals, 0.975), 4) # pooled days 1-3 band v13 = [] for s in range(60, N - 60 + 1): o = sum(CY[(s + k) % N] for k in (1, 2, 3)) e = sum(CE[(s + k) % N] for k in (1, 2, 3)) v13.append(o / e) out = {"lag_profile_A": prof, "days1_3": {"OE": round(sum(p["O"] for p in prof if p["lag"] in (1, 2, 3)) / sum(p["E"] for p in prof if p["lag"] in (1, 2, 3)), 4), "null_lo": round(quant(v13, 0.025), 4), "null_hi": round(quant(v13, 0.975), 4)}} # dose rows recomputed at full precision (controls_C8.json rounds E and the interval to 2-3 decimals, and rounding # those again for the chart could move a last digit); the same storms and sums as C8 KP = [float(r["kp_max"]) for r in L.load_daily()] cum = {} for thr in (4.667, 5.0, 6.0, 6.667, 7.0, 7.667): t0s = [x["t0"] for x in L.episodes(KP, thr)] o = sum(Y[t + k] for t in t0s for k in (1, 2, 3) if t + k < N) e = sum(EA[t + k] for t in t0s for k in (1, 2, 3) if t + k < N) lo, hi = L.pois_ci(o) cum[str(thr)] = {"episodes": len(t0s), "O": o, "E": round(e, 4), "OE": round(o / e, 4), "ci": [round(lo / e, 4), round(hi / e, 4)]} out["dose_cumulative"] = cum c8 = json.load(open(os.path.join(L.RES, "controls_C8.json"), encoding="utf-8")) out["dose_exclusive"] = c8["exclusive"] with open(os.path.join(L.RES, "chart_series.json"), "w", encoding="utf-8", newline="\n") as f: json.dump(out, f, indent=1) for p in prof: print(p) print(out["days1_3"])