# Hosted copy (Fact-Checked Science, /amundsen-low-solar-cycle/): reads its inputs from the folder given as the # first argument, filled by fetch_inputs.py, and writes its outputs to /out/. Run it with Python 3.10+, # numpy and scipy, from the folder that holds this script, asl_lib.py, surr_lib.py and the RULES files. """03_oos.py — out-of-sample test of the 2017 recipe (5-year CMA, 33-month lag) on ASL data after 2016-11. Rules: RULES_oos.txt (hash logged before the first run). Fact-Checked Science, 2026-11-15. Usage: py -3.12 -I 03_oos.py (writes ../out/03_oos.txt, .json and 03_oos_targets.csv) """ import os, sys, json, hashlib here = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, here) import numpy as np import asl_lib as A root = os.path.abspath(sys.argv[1]) if len(sys.argv) > 1 else os.getcwd() dl = root outdir = os.path.join(root, "out") os.makedirs(outdir, exist_ok=True) lines, res = [], {} def say(*a): s = " ".join(str(x) for x in a) print(s, flush=True) lines.append(s) def sha(p): return hashlib.sha256(open(p, "rb").read()).hexdigest() P_V3 = os.path.join(dl, "asli_calculation_latest.csv") P_V2 = os.path.join(dl, "ASL-index-Version2-Monthly-ERA-Interim_Hosking2016.txt") P_SN = os.path.join(dl, "SN_m_tot_V2.0.csv") for p in [os.path.join(here, "RULES_oos.txt"), P_V3, P_V2, P_SN]: say("input", os.path.relpath(p, root).replace("\\", "/"), sha(p)) v3, _ = A.load_v3(P_V3) v2 = A.load_v2(P_V2) sn_all, _ = A.load_silso(P_SN) v3 = v3.restrict(v3.start, A.ym("2026-07")) sn_all = sn_all.restrict(sn_all.start, A.ym("2026-10")) TR0, TR1 = A.ym("1979-01"), A.ym("2016-11") NEW0, NEW1 = A.ym("2016-12"), A.ym("2026-07") LAG = 33 def fit(ssn_train_raw, asl_train_raw, odd=False): x, y, _ = A.pair(A.cma(ssn_train_raw, 60, odd), A.cma(asl_train_raw, 60, odd), LAG) b, a = np.polyfit(x, y, 1) return a, b, len(x), A.pearson(x, y) def targets(asl_raw_for_targets, d0=None, d1=None, odd=False): c = A.cma(asl_raw_for_targets, 60, odd) ds = [c.start + i for i, v in enumerate(c.v) if np.isfinite(v)] if d0 is not None: ds = [d for d in ds if d0 <= d <= d1] return np.array(ds), np.array([c.get(d) for d in ds]) def scores(obs, fc): out = {} for k, f in fc.items(): e = f - obs out[k] = dict(rmse=float(np.sqrt(np.mean(e ** 2))), bias=float(np.mean(e)), mse=float(np.mean(e ** 2))) for k in fc: if k != "M": out["SS_" + k] = 1.0 - out["M"]["mse"] / out[k]["mse"] return out def forecasts(ds, ssn_c, a, b, train_asl_raw): m = np.array([a + b * ssn_c.get(d - LAG) for d in ds]) clim = np.full(len(ds), np.nanmean(train_asl_raw.v)) pers = np.full(len(ds), np.nanmean(train_asl_raw.restrict(train_asl_raw.end - 59, train_asl_raw.end).v)) tt = np.arange(train_asl_raw.start, train_asl_raw.end + 1, dtype=float) bt, at = np.polyfit(tt, train_asl_raw.v, 1) trend = at + bt * (ds.astype(float) - 0.5) return dict(M=m, C=clim, P=pers, T=trend) def report(tag, ds, obs, fc, extra=""): sc = scores(obs, fc) say(f"\n[{tag}] {len(ds)} targets, centres {A.ym_str(int(ds[0]))}..{A.ym_str(int(ds[-1]))} {extra}") for k in ("M", "C", "P", "T"): say(f" {k}: RMSE {sc[k]['rmse']:.3f} hPa, mean error {sc[k]['bias']:+.3f} hPa") say(f" skill of M: vs climatology {sc['SS_C']:+.3f}, vs persistence {sc['SS_P']:+.3f}, vs trend {sc['SS_T']:+.3f}") r = A.pearson(fc["M"], obs) ne = A.neff_single(obs) say(f" r(M, observed) = {r:.3f}; single-series n_eff of the observed targets = {ne:.2f}") sc["r_M_obs"], sc["neff_obs"] = r, ne return sc # T1 primary asl_tr = v3.restrict(TR0, TR1) ssn_tr = sn_all.restrict(TR0, TR1) a, b, ntr, rtr = fit(ssn_tr, asl_tr) say(f"\n[fit, training 1979-01..2016-11, ASL v3] ASL = {a:.3f} + {b:.5f} * SSN; {ntr} pairs; r = {rtr:.4f}") ssn_c_full = A.cma(sn_all.restrict(A.ym("1979-01"), A.ym("2026-10")), 60) ds, obs = targets(v3.restrict(NEW0, NEW1)) fc = forecasts(ds, ssn_c_full, a, b, asl_tr) res["T1"] = report("T1 primary: wholly new 5-year means", ds, obs, fc) res["T1"]["fit"] = dict(a=a, b=b, n=ntr, r=rtr) say(" raw new months:", NEW1 - NEW0 + 1, "=", f"{(NEW1 - NEW0 + 1) / 60:.2f}", "non-overlapping 5-year means") with open(os.path.join(outdir, "03_oos_targets.csv"), "w", encoding="utf-8", newline="\n") as f: f.write("centre,observed_asl_cma_hPa,M_recipe,C_climatology,P_persistence,T_trend,ssn_cma_at_centre_minus_33\n") for i, d in enumerate(ds): f.write(f"{A.ym_str(int(d))},{obs[i]:.4f},{fc['M'][i]:.4f},{fc['C'][i]:.4f},{fc['P'][i]:.4f},{fc['T'][i]:.4f},{ssn_c_full.get(int(d) - LAG):.3f}\n") say(" first/last targets (obs, M, C, P, T):", f"{A.ym_str(int(ds[0]))}: {obs[0]:.2f}, {fc['M'][0]:.2f}, {fc['C'][0]:.2f}, {fc['P'][0]:.2f}, {fc['T'][0]:.2f};", f"{A.ym_str(int(ds[-1]))}: {obs[-1]:.2f}, {fc['M'][-1]:.2f}, {fc['C'][-1]:.2f}, {fc['P'][-1]:.2f}, {fc['T'][-1]:.2f}") say(f" mean observed {obs.mean():.3f}; mean M {fc['M'].mean():.3f}; C {fc['C'][0]:.3f}; P {fc['P'][0]:.3f}; mean T {fc['T'].mean():.3f}") # T2 surrogate reference rng = np.random.default_rng(2026111541) base = sn_all.restrict(A.ym("1979-01"), A.ym("2026-10")) sur = A.phase_surrogates(base.v, 10000, rng) ssc, ssp, sst, both = [], [], [], 0 obs_ssc, obs_ssp, obs_sst = res["T1"]["SS_C"], res["T1"]["SS_P"], res["T1"]["SS_T"] for s in sur: sm = A.Monthly(base.start, s) a_s, b_s, _, _ = fit(sm.restrict(TR0, TR1), asl_tr) c_s = A.cma(sm, 60) f_s = forecasts(ds, c_s, a_s, b_s, asl_tr) sc_s = scores(obs, f_s) ssc.append(sc_s["SS_C"]); ssp.append(sc_s["SS_P"]); sst.append(sc_s["SS_T"]) if sc_s["SS_C"] > 0 and sc_s["SS_P"] > 0: both += 1 ssc, ssp, sst = map(np.array, (ssc, ssp, sst)) t2 = dict(frac_SSC_ge=float(np.mean(ssc >= obs_ssc)), frac_SSP_ge=float(np.mean(ssp >= obs_ssp)), frac_SST_ge=float(np.mean(sst >= obs_sst)), frac_beat_C_and_P=both / len(sur), frac_SSC_pos=float(np.mean(ssc > 0)), frac_SSP_pos=float(np.mean(ssp > 0)), median_SSC=float(np.median(ssc)), median_SSP=float(np.median(ssp))) res["T2"] = t2 say("\n[T2 surrogate reference, 10,000 phase-randomised SSN series, seed 2026111541]") say(f" fraction with SS_C >= observed: {t2['frac_SSC_ge']:.4f}; SS_P >= observed: {t2['frac_SSP_ge']:.4f}; SS_T >= observed: {t2['frac_SST_ge']:.4f}") say(f" fraction beating both climatology and persistence: {t2['frac_beat_C_and_P']:.4f}; SS_C > 0: {t2['frac_SSC_pos']:.4f}; SS_P > 0: {t2['frac_SSP_pos']:.4f}") say(f" surrogate medians: SS_C {t2['median_SSC']:+.3f}, SS_P {t2['median_SSP']:+.3f}") # T3 odd windows a3, b3, n3, r3 = fit(ssn_tr, asl_tr, odd=True) ds3, obs3 = targets(v3.restrict(NEW0, NEW1), odd=True) fc3 = forecasts(ds3, A.cma(sn_all.restrict(A.ym("1979-01"), A.ym("2026-10")), 60, odd=True), a3, b3, asl_tr) res["T3"] = report("T3 odd 61-month windows", ds3, obs3, fc3, f"(fit r = {r3:.4f}, n = {n3})") # T4 the 2017 fit on v2 plus the v3 - v2 offset a4, b4, n4, r4 = fit(ssn_tr, v2.restrict(TR0, TR1)) off = float(np.mean(v3.restrict(TR0, TR1).v - v2.restrict(TR0, TR1).v)) fc4 = forecasts(ds, ssn_c_full, a4 + off, b4, asl_tr) res["T4"] = report("T4 the 2017 fit on v2, + mean v3-v2 offset", ds, obs, fc4, f"(v2 fit r = {r4:.4f}, n = {n4}; offset {off:+.3f} hPa)") res["T4"]["fit"] = dict(a=a4, b=b4, offset=off) # T5 all targets touching new data (descriptive) ds5, obs5 = targets(v3.restrict(A.ym("1979-01"), NEW1), A.ym("2014-07"), A.ym("2024-02")) fc5 = forecasts(ds5, ssn_c_full, a, b, asl_tr) res["T5"] = report("T5 any new data (descriptive)", ds5, obs5, fc5) open(os.path.join(outdir, "03_oos.txt"), "w", encoding="utf-8", newline="\n").write("\n".join(lines) + "\n") json.dump(res, open(os.path.join(outdir, "03_oos.json"), "w", encoding="utf-8", newline="\n"), indent=1)