"""Draw the page's two charts from public data and write the numbers behind them. Standard library only. python3 -I charts.py [ []] holds gfz/ and swpc/dgd/ as fetch_inputs.py leaves them; is pages/halloween-storm-explosions. Run from verification/halloween-storm-explosions/code/ in the project, both default from this file's own location. Writes kp_2026-10-28_to_11-06.csv and window_shares.csv into the page folder, and the two SVGs into its body.html between the markers and . Events are marked by place and date only. """ import csv import io import re import sys from datetime import date, timedelta from pathlib import Path sys.stdout.reconfigure(encoding="utf-8") HERE = Path(__file__).resolve() SLUG = "halloween-storm-explosions" if len(sys.argv) > 1: DL = Path(sys.argv[1]) else: DL = HERE.parents[1] / "downloads" PAGE = Path(sys.argv[2]) if len(sys.argv) > 2 else HERE.parents[3] / "pages" / SLUG # ---------- data ---------- gfz3 = {} # (date, bin) -> (Kp, D flag) gfzmax = {} for ln in (DL / "gfz" / "Kp_ap_Ap_SN_F107_since_1932.txt").read_bytes().decode("utf-8").splitlines(): if ln.startswith("#"): continue f = ln.split() d = date(int(f[0]), int(f[1]), int(f[2])) ks = [float(x) for x in f[7:15]] ok = [k for k in ks if k >= 0] if ok: gfzmax[d] = max(ok) if date(2026, 10, 28) <= d <= date(2026, 11, 6): for i, k in enumerate(ks): gfz3[(d, i)] = (k, f[-1]) noaa3, noaamax = {}, {} for fn in sorted((DL / "swpc" / "dgd").glob("20*Q*_DGD.txt")): for ln in fn.read_bytes().decode("utf-8", "replace").splitlines(): m = re.match(r"^(\d{4}) (\d\d) (\d\d)\s+(.*)$", ln) if not m: continue d = date(int(m.group(1)), int(m.group(2)), int(m.group(3))) vals = [float(x) for x in m.group(4).split()[-8:]] ok = [v for v in vals if v >= 0] if ok: noaamax[d] = max(ok) if date(2026, 10, 28) <= d <= date(2026, 11, 6): for i, v in enumerate(vals): noaa3[(d, i)] = v def days(a, b): x = a while x <= b: yield x x += timedelta(days=1) def share(series, thr, a, b): S = {d for d, k in series.items() if k >= thr - 1e-6} ds = [d for d in days(a, b) if d in series] w = sum(1 for d in ds if any((d - timedelta(days=k)) in S for k in (1, 2, 3))) return len(ds), w, w / len(ds) LAST = date(2026, 11, 6) PERIODS = [("2024", date(2024, 1, 1), date(2024, 12, 31)), ("2025", date(2025, 1, 1), date(2025, 12, 31)), ("2026, to 6 November", date(2026, 1, 1), LAST), ("2024–2026", date(2024, 1, 1), LAST), ("1999–2026, note 003’s span", date(1999, 1, 1), date(2026, 11, 3)), ("1932–2026, GFZ’s whole record", date(1932, 1, 1), LAST)] rows = [] for name, a, b in PERIODS: r = {"period": name, "start": a.isoformat(), "end": b.isoformat()} for key, ser, thr in (("gfz_kp5o", gfzmax, 5.0), ("gfz_kp5minus", gfzmax, 4.667), ("noaa_kp5", noaamax, 5.0), ("noaa_kp5minus", noaamax, 4.67)): if ser is noaamax and a < date(2024, 1, 1): r[key] = "" continue n, w, s = share(ser, thr, a, b) r[key] = f"{100 * s:.1f}" r["_" + key] = 100 * s # unrounded, for the chart's labels r["days"] = n rows.append(r) out = io.StringIO() wr = csv.writer(out, lineterminator="\n") out.write("# Three-hourly Kp, October 28 to November 6, 2026. gfz_kp: GFZ Potsdam, Kp_ap_Ap_SN_F107_since_1932.txt as of 2026-11-07 " "(Matzka et al. 2021, doi:10.5880/Kp.0001, CC BY 4.0), preliminary for these days (flag D = 0). noaa_estimated_kp: " "NOAA SWPC's estimated planetary Kp from its quarterly DGD file 2026Q4 (US government work). Compiled by factchecked.science." + chr(10)) wr.writerow(["date_utc", "start_ut", "gfz_kp", "gfz_flag_D", "noaa_estimated_kp"]) for d in days(date(2026, 10, 28), date(2026, 11, 6)): for i in range(8): k, fl = gfz3[(d, i)] wr.writerow([d.isoformat(), f"{3 * i:02d}:00", f"{k:.3f}", fl, f"{noaa3[(d, i)]:.2f}"]) (PAGE / "kp_2026-10-28_to_11-06.csv").write_text(out.getvalue(), encoding="utf-8", newline="\n") out = io.StringIO() wr = csv.writer(out, lineterminator="\n") out.write("# Our analysis (factchecked.science, 2026-11-07): the share of UT days that fall 1-3 days after a day whose highest " "three-hourly Kp is at least 5o (5.0) or 5- (4.667). From GFZ Potsdam's Kp (Matzka et al. 2021, doi:10.5880/Kp.0001, CC BY 4.0; " "preliminary from 2026-10-01) and NOAA SWPC's estimated planetary Kp, quarterly DGD files 2024Q1-2026Q4 (US government work)." + chr(10)) wr.writerow(["period", "start", "end", "days", "gfz_kp5o_pct", "gfz_kp5minus_pct", "noaa_kp5_pct", "noaa_kp5minus_pct"]) for r in rows: wr.writerow([r["period"], r["start"], r["end"], r["days"], r["gfz_kp5o"], r["gfz_kp5minus"], r["noaa_kp5"], r["noaa_kp5minus"]]) (PAGE / "window_shares.csv").write_text(out.getvalue(), encoding="utf-8", newline="\n") # ---------- chart 1: Kp, 28 Oct - 6 Nov 2026 ---------- EVENTS = [ # (UTC date as dated by the source, which list, place, what) ("2026-10-30", "003", "Izmit, Turkey", "distribution transformer"), ("2026-11-01", "003", "Pančevo, Serbia", "transformer station"), ("2026-11-01", "003", "Monterrey, Mexico", "transformer at a firm, during maintenance"), ("2026-11-02", "003", "Ciudad Ojeda, Zulia, Venezuela", "substation"), ("2026-11-02", "003", "Ayacucho, Buenos Aires province, Argentina", "street transformer"), ("2026-11-03", "003", "Davanagere, Karnataka, India", "roadside distribution transformer"), ("2026-11-02", "005", "Mahuabari/Usiya, Ghazipur, India", "no report found"), ("2026-11-02", "005", "Olkhan Ka Bas, Jhunjhunu, India", "no report found"), ("2026-11-03", "005", "El Espinal, Margarita Island, Venezuela", "two transformers, in a news report"), ("2026-11-04", "005", "El Vedado, Havana, Cuba", "a transformer, in a news report; November 3 or 4 in UT"), ] X0, X1, Y0 = 72.0, 852.0, 300.0 PER_BIN = (X1 - X0) / 80 def xb(d, i): return X0 + ((d - date(2026, 10, 28)).days * 8 + i) * PER_BIN def yk(k): return Y0 - 34.0 * k D0 = date(2026, 10, 28) p = [] p.append('') # band: 1-4 Nov bx0, bx1 = xb(date(2026, 11, 1), 0), xb(date(2026, 11, 5), 0) p.append(f'') p.append(f'1–3 days after 31 October or 1 November') for k in (0, 2, 4, 6, 8): p.append(f'{k}') # reference lines refs = [(5.0, "G1 · Kp 5", 4.5), (6.0, "G2 · line B · Kp 6", 4.5), (6.667, "Line A · Kp 7−", 10), (7.0, "G3 · Kp 7", -2)] for k, lab, dy in refs: # labels in the right margin, outside the plot; A and G3 are pushed apart vertically p.append(f'') p.append(f'{lab}') # GFZ bars for d in days(D0, date(2026, 11, 6)): for i in range(8): k = gfz3[(d, i)][0] cx = xb(d, i) + PER_BIN / 2 if k > 0: p.append(f'') # NOAA step line pts = [] for d in days(D0, date(2026, 11, 6)): for i in range(8): v = noaa3[(d, i)] xa = xb(d, i) pts.append(f"{'M' if not pts else 'L'}{xa:.1f} {yk(v):.1f} H{xa + PER_BIN:.1f}") p.append(f'') # transparent hover areas, one per three-hour interval, so every interval has a title, including those where GFZ's Kp is 0 for d in days(D0, date(2026, 11, 6)): for i in range(8): k = gfz3[(d, i)][0] p.append(f'{d.day} {"Oct" if d.month == 10 else "Nov"} {3 * i:02d}–{3 * i + 3:02d} UT: GFZ Kp {k:.3f}, NOAA {noaa3[(d, i)]:.2f}' f'') # peak label pk = xb(date(2026, 10, 31), 6) + PER_BIN / 2 p.append(f'31 Oct, 18–21 UT: GFZ 6−, NOAA 6.00') # axis and day labels p.append(f'') for n, d in enumerate(days(D0, date(2026, 11, 7))): x = X0 + n * 8 * PER_BIN p.append(f'') if d <= date(2026, 11, 6): lab = f'{d.day} {"Oct" if d.month == 10 else "Nov"}' if d.day in (28, 1) or d == date(2026, 11, 6) or d == date(2026, 10, 31) else f"{d.day}" p.append(f'{lab}') # events p.append(f'Note 003') p.append(f'Note 005') for which, yrow in (("003", Y0 + 48), ("005", Y0 + 76)): byday = {} for e in EVENTS: if e[1] == which: byday.setdefault(e[0], []).append(e) for ds, evs in byday.items(): d = date.fromisoformat(ds) cx = xb(d, 0) + 4 * PER_BIN for j, e in enumerate(evs): x = cx + (j - (len(evs) - 1) / 2) * 15 cls = "ev-003" if which == "003" else "ev-005" p.append(f'{d.day} {"Oct" if d.month == 10 else "Nov"} 2026: {e[2]}, {e[3]} (note {which})' f'') p.append("") svg_kp = "".join(p) # ---------- chart 2: share of days in the window ---------- LX, BX0, SC = 222.0, 232.0, 7.0 # label right edge, bar start, units per percentage point (700-unit viewBox) RH, TOP = 50.0, 16.0 H2 = TOP + RH * len(rows) + 40 q = [] gl = "; ".join(f"{float(r['gfz_kp5o']):.1f}% for {r['period']}" for r in rows) nl = "; ".join(f"{float(r['noaa_kp5']):.1f}% for {r['period']}" for r in rows if r["noaa_kp5"]) q.append(f'') for v in range(0, 61, 10): x = BX0 + v * SC q.append(f'' f'{v}%') for n, r in enumerate(rows): y = TOP + n * RH cls = "t-lab t-strong" if r["period"] == "2024–2026" else "t-lab" q.append(f'{r["period"]}') g = r["_gfz_kp5o"] q.append(f'{r["period"]}: GFZ Kp 5 or more, {g:.1f}% of days (Kp 5− or more: {r["gfz_kp5minus"]}%)' f'' f'{g:.0f}%') if r["noaa_kp5"]: v = r["_noaa_kp5"] q.append(f'{r["period"]}: NOAA estimated Kp 5 or more, {v:.1f}% of days (Kp 5− or more: {r["noaa_kp5minus"]}%)' f'' f'{v:.0f}%') q.append(f'') q.append("") svg_sh = "".join(q) body = PAGE / "body.html" s = body.read_text(encoding="utf-8") for tag, svg in (("kp", svg_kp), ("share", svg_sh)): a, b = f"", f"" i, j = s.index(a), s.index(b) s = s[: i + len(a)] + "\n" + svg + "\n" + s[j:] body.write_text(s, encoding="utf-8", newline="\n") for r in rows: print({k: v for k, v in r.items() if not k.startswith("_")}) print("charts written to", body)