#!/usr/bin/env python3 """Test 1: does S0 News research note 004 reproduce from its own files? Rules: RULES_reproduce.txt. Fact-Checked Science, verification of florida-aurora-cycle-25. Standard library only; reads the downloads as data. python3 -I reproduce_note.py > ../out/reproduce_note.txt """ import csv import datetime as dt import html import math import os import re import sys def poisson_sf(k, lam): """Exact one-sided P(X >= k | lam).""" return 1.0 - sum(math.exp(-lam) * lam ** i / math.factorial(i) for i in range(k)) def fisher_one_sided(h1, n1, h0, n0): """P(hits in group 1 >= h1 | margins): group 1 = cycle 25 (h1 of n1), group 0 = baseline (h0 of n0).""" N, K = n1 + n0, h1 + h0 den = math.comb(N, n1) return sum(math.comb(K, x) * math.comb(N - K, n1 - x) for x in range(h1, min(K, n1) + 1)) / den def sig(x, n=3): if x == 0: return "0" return f"{x:.{n - 1}e}" if (abs(x) < 1e-3) else f"{x:.{n}g}" def same(printed, ours): """Does our number round to the printed one at the printed precision?""" s = printed.strip().lower() m = re.fullmatch(r"(\d+)\.?(\d*)e(-?\d+)", s) if m: digits = len(m.group(2)) return f"{ours:.{digits}e}" == f"{float(s):.{digits}e}" if "." in s: digits = len(s.split(".")[1]) return f"{ours:.{digits}f}" == f"{float(s):.{digits}f}" return round(ours) == int(s) def rows(path): with open(path, encoding="utf-8-sig", newline="") as f: return list(csv.DictReader(f)) def first_last(date_field): """'2003-10-29/31' -> (2003-10-29, 2003-10-31); '1859-08-28/09-02' -> (1859-08-28, 1859-09-02); '1941-09-18/19'.""" a, _, b = date_field.partition("/") d0 = dt.date.fromisoformat(a) if not b: return d0, d0 p = b.split("-") if len(p) == 1: d1 = d0.replace(day=int(p[0])) elif len(p) == 2: d1 = d0.replace(month=int(p[0]), day=int(p[1])) else: d1 = dt.date.fromisoformat(b) return d0, d1 def main(): sys.stdout.reconfigure(encoding="utf-8", newline="\n") dl = sys.argv[1] drive = os.path.join(dl, "s0-note-004-drive") out = print out("TEST 1. The note from its own files (rules: RULES_reproduce.txt)") out("") # ---- 1. counts A, B = rows(os.path.join(drive, "PathA_events.csv")), rows(os.path.join(drive, "PathB_events.csv")) lam = [r for r in csv.reader(open(os.path.join(drive, "TABLE_lambda_by_cycle.csv"), encoding="utf-8-sig", newline=""))] per = {} for name, R in (("A", A), ("B", B)): c = {} for r in R: c[int(r["cycle"])] = c.get(int(r["cycle"]), 0) + 1 per[name] = c out("1. Counts") out(f" PathA_events.csv rows: {len(A)} (note: n = 11) PathB_events.csv rows: {len(B)} (note: n = 14)") table = {int(r[0]): (int(r[1]), int(r[2])) for r in lam[1:] if r and r[0].isdigit()} diffs = 0 for cyc in range(10, 26): a, b = per["A"].get(cyc, 0), per["B"].get(cyc, 0) ta, tb = table[cyc] flag = "" if (a, b) == (ta, tb) else " <-- DIFFERS from TABLE_lambda_by_cycle.csv" diffs += (a, b) != (ta, tb) out(f" cycle {cyc}: Path A {a}, Path B {b}; table {ta}, {tb}{flag}") preA = sum(v for c, v in per["A"].items() if c < 25) preB = sum(v for c, v in per["B"].items() if c < 25) modA = sum(per["A"].get(c, 0) for c in (22, 23, 24)) modB = sum(per["B"].get(c, 0) for c in (22, 23, 24)) out(f" before cycle 25: Path A {preA} (note 6), Path B {preB} (note 9); cycle 25: {per['A'].get(25, 0)}, {per['B'].get(25, 0)} (note 5, 5)") out(f" cycles 22-24: Path A {modA}, Path B {modB} (note 3); lambda {preA}/15 = {preA / 15:.4f}, {preB}/15 = {preB / 15:.4f}, {modA}/3 = {modA / 3:.2f}") zeroA = [c for c in range(10, 25) if per["A"].get(c, 0) == 0] zeroB = [c for c in range(10, 25) if per["B"].get(c, 0) == 0] out(f" baseline cycles with no event: Path A {len(zeroA)} of 15 {zeroA}; Path B {len(zeroB)} of 15 {zeroB}") out(f" rows that differ from the table: {diffs}") onlyB = [r["date"] for r in B if r["date"] not in {x["date"] for x in A}] out(f" Path B rows not in Path A: {onlyB}") out("") # ---- 5. exposure and spans (needed by 2) t0, t1 = dt.datetime(2019, 12, 1, 0), dt.datetime(2026, 10, 30, 14) expo = (t1 - t0).total_seconds() / 86400 / 365.25 txt = open(os.path.join(dl, "silso", "cyclesminmax.html"), encoding="utf-8", errors="replace").read() mins = {} for tr in re.findall(r"]*>(.*?)", txt, flags=re.S): cells = [html.unescape(re.sub(r"<[^>]+>", "", c)).strip() for c in re.findall(r"]*>(.*?)", tr, flags=re.S)] if len(cells) >= 3 and cells[0].isdigit(): mins[int(cells[0])] = int(cells[1]) + (int(cells[2]) - 0.5) / 12.0 mean_len = (mins[25] - mins[10]) / 15.0 out("5. Exposure and spans") out(f" cycle 25, 2019-12-01 00 UT to 2026-10-30 14 UT: {expo:.4f} years (note: 6.9)") out(f" SILSO minima: cycle 10 {mins[10]:.3f}, cycle 22 {mins[22]:.3f}, cycle 25 {mins[25]:.3f}") out(f" mean length of cycles 10-24: ({mins[25]:.3f} - {mins[10]:.3f}) / 15 = {mean_len:.4f} years (note: 10.95)") out(f" mean length of cycles 22-24: {(mins[25] - mins[22]) / 3:.4f} years; of cycles 1-24: {(mins[25] - mins[1]) / 24:.4f}") out(f" exposure share: note 6.9/10.95 = {6.9 / 10.95:.4f}; ours {expo:.4f}/{mean_len:.4f} = {expo / mean_len:.4f}") c25 = [r for r in A if r["cycle"] == "25"] f0, _ = first_last(c25[0]["date"]) _, l1 = first_last(c25[-1]["date"]) f1, _ = first_last(c25[-1]["date"]) out(f" cycle-25 rows: first day {f0}, last row {c25[-1]['date']}") out(f" span, first day of first row to last day of last row: {(l1 - f0).days} days = {(l1 - f0).days / 365.25:.3f} years (note: 2.9; 'less than 3')") out(f" span, first day to first day: {(f1 - f0).days / 365.25:.3f} years; from 2023-03-23 to the freeze 2026-10-30: {(dt.date(2026, 10, 30) - f0).days / 365.25:.3f} years") for lam_, name in ((0.60, "Path B"), (0.40, "Path A")): out(f" 5 events at {lam_:.2f} a cycle = {5 / lam_:.2f} cycles = {5 / lam_ * 10.95:.1f} years at 10.95, {5 / lam_ * mean_len:.1f} at {mean_len:.2f} ({name})") first_event = first_last(A[0]["date"])[0] out(f" 'previous 160 years': {first_event} to 2019-12-01 = {(dt.date(2019, 12, 1) - first_event).days / 365.25:.1f} years; cycle 10's minimum to cycle 25's = {mins[25] - mins[10]:.1f} years") out(f" 'nearly matched ... combined': 5 against {preA} (Path A) and {preB} (Path B)") out(f" '~21 more' for a mean of 2 a cycle: 2 x 15 - {preB} = {2 * 15 - preB} (Path B); 2 x 15 - {preA} = {2 * 15 - preA} (Path A)") out("") # ---- 2. rate test out("2. Rate test (TABLE1_rates.csv), exact one-sided Poisson") fails = 0 exact = {"0.40": 6 / 15, "0.60": 9 / 15, "0.333": 5 / 15, "1.0": 1.0} for r in rows(os.path.join(drive, "TABLE1_rates.csv")): k, lam_s = int(r["k_C25"]), r["lambda_full_cycle"] lam_p, lam_e = float(lam_s), exact[lam_s] p_full = poisson_sf(k, lam_e) ok = same(r["p_full_cycle"], p_full) fails += not ok line = f" {r['inventory']}: k = {k}, lambda = {lam_s}: p = {sig(p_full)} (printed {r['p_full_cycle']}) {'ok' if ok else 'DIFFERS'}" if lam_e != lam_p: line += f"; with lambda as printed {sig(poisson_sf(k, lam_p))}" out(line) if r["lambda_exposure_6.9yr"]: l_note = lam_e * 6.9 / 10.95 p_adj = poisson_sf(k, l_note) ok2 = same(r["p_exposure_adj"], p_adj) fails += not ok2 ok3 = same(r["lambda_exposure_6.9yr"], l_note) fails += not ok3 out(f" scaled by 6.9/10.95: lambda = {l_note:.4f} (printed {r['lambda_exposure_6.9yr']}) {'ok' if ok3 else 'DIFFERS'}; " f"p = {sig(p_adj)} (printed {r['p_exposure_adj']}) {'ok' if ok2 else 'DIFFERS'}; " f"with our exposure and cycle length ({expo / mean_len:.4f}): p = {sig(poisson_sf(k, lam_e * expo / mean_len))}") out(f" printed values that do not reproduce: {fails}") out("") # ---- 3. Fisher out("3. Storm-conditional test, one-sided Fisher exact") storms = {24: rows(os.path.join(drive, "Storms_all_strata_24h.csv")), 48: rows(os.path.join(drive, "Storms_all_strata_48h.csv"))} col = {"A": "FL_hit_PathA_primary", "B": "FL_hit_PathB", "Ajx": "FL_hit_PathA_JanExcl_sens"} recount = {} for gap, R in storms.items(): for r in R: for path, c in col.items(): key = (gap, r["stratum"], path, r["era"]) h, n = recount.get(key, (0, 0)) recount[key] = (h + int(r[c]), n + 1) out(" recount from the storm lists (hits/storms):") for gap in (24, 48): for s in ("Kp>=9-", "Kp>=8-", "Kp>=8o", "Dst<=-200", "Dst<=-300"): parts = [] for path in ("A", "B", "Ajx"): b, c = recount[(gap, s, path, "1986-2019Nov")], recount[(gap, s, path, "C25")] parts.append(f"{path} {b[0]}/{b[1]} vs {c[0]}/{c[1]}") out(f" {gap} h, {s}: " + "; ".join(parts)) fails = 0 for fn in ("TABLE2_fisher.csv", "TABLE2_fisher_full.csv"): out(f" {fn}:") for r in rows(os.path.join(drive, fn)): h0, n0 = map(int, r["hits/storms_1986-2019Nov"].split("/")) h1, n1 = map(int, r["hits/storms_C25"].split("/")) p = fisher_one_sided(h1, n1, h0, n0) ok = same(r["fisher_one_sided_p"], p) fails += not ok note = "" key0, key1 = (int(r["gap_h"]), r["stratum"], r["path"], "1986-2019Nov"), (int(r["gap_h"]), r["stratum"], r["path"], "C25") if key0 in recount: if recount[key0] != (h0, n0) or recount[key1] != (h1, n1): note = f" <-- storm list gives {recount[key0][0]}/{recount[key0][1]} vs {recount[key1][0]}/{recount[key1][1]}" fails += 1 out(f" {r['gap_h']} h, {r['stratum']}, {r['path']}: {h0}/{n0} vs {h1}/{n1}: p = {sig(p)} (printed {r['fisher_one_sided_p']}) {'ok' if ok else 'DIFFERS'}{note}") out(f" printed values that do not reproduce, or fractions that differ from the storm lists: {fails}") same_file = open(os.path.join(drive, "Storms_Kp9minus_24h.csv"), "rb").read() == open(os.path.join(drive, "Storms_all_strata_24h.csv"), "rb").read() out(f" Storms_Kp9minus_24h.csv is byte for byte Storms_all_strata_24h.csv: {same_file} (the note calls it the 'Kp>=9- subset')") out("") # ---- 4. the claims' numbers out("4. The claims' numbers") pB, pA = poisson_sf(5, 0.60), poisson_sf(5, 0.40) out(f" Claim 1: 9/15 = {9 / 15:.2f}; P(X>=5 | 0.60) = {sig(pB)} = 1 in {1 / pB:,.0f} (note: 3.9e-4, ~1 in 2,540)") out(f" 1 / 3.94e-4 = {1 / 3.94e-4:,.0f}; 1 / 3.9e-4 = {1 / 3.9e-4:,.0f}") out(f" P(X>=5 | 0.40) = {sig(pA)} (note: 6.1e-5); scaled, P(X>=5 | 0.60 x 6.9/10.95) = {sig(poisson_sf(5, 0.6 * 6.9 / 10.95))} (note: 4.7e-5)") out(f" 5 / 0.60 = {5 / 0.6:.2f} (note: ~8.3x); 5 / 0.40 = {5 / 0.4:.1f}") out(f" Claim 2: P(X>=5 | 1.0) = {sig(poisson_sf(5, 1.0))} (note: ~0.004)") out(f" Claim 3: 5/13 vs 3/76: {sig(fisher_one_sided(5, 13, 3, 76))} (note: 0.0014); 4/6 vs 3/30: {sig(fisher_one_sided(4, 6, 3, 30))} (note: 0.0076)") out(f" Claim 5: P(X>=4 | 0.60) = {sig(poisson_sf(4, 0.60))} (note: 'rate p = 0.0034'); P(X>=4 | 0.40) = {sig(poisson_sf(4, 0.40))}; " f"3/3 vs 3/19: {sig(fisher_one_sided(3, 3, 3, 19))} (note: 0.013); 4/4 vs 5/19: {sig(fisher_one_sided(4, 4, 5, 19))} (note: 0.014)") out(f" Methods: 4/4 vs 3/19: {sig(fisher_one_sided(4, 4, 3, 19))} (note: ~0.004)") out(f" 'the old ~1-in-6 rate': 3/19 = 1 in {19 / 3:.1f}") if __name__ == "__main__": main()