"""How "all three fall" depends on start and end years (RULES_periods.txt). Usage: py -3.12 -I periods.py [products...] Reads annual_bands_.csv written by reproduce.py. names which R1 file stands for R1 in the "all three" tests (r1 or r1g). """ import json import os import sys import numpy as np sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import ppt_lib as L # noqa: E402 def load(out, p): rows = [l.strip().split(",") for l in open(os.path.join(out, f"annual_bands_{p}.csv"), encoding="utf-8")] h = rows[0] y = np.array([int(r[0]) for r in rows[1:]]) return y, {h[j]: np.array([float(r[j]) for r in rows[1:]]) for j in range(1, len(h))} def below(t): return t["hi"] is not None and t["hi"] < 0 def above(t): return t["lo"] is not None and t["lo"] > 0 def main(out, r1p, products): data = {p: load(out, p) for p in products} res = {"rules": "RULES_periods.txt", "r1_file": r1p, "T1": {}, "T2": {}, "T3": {}} sweep_rows = [] for p, (y, b) in data.items(): first, last = int(y[0]), int(y[-1]) rows = [] for s in range(first, last - 29 + 1): tp = L.trend_window(y, b["polar"], s, last) tt = L.trend_window(y, b["tropical"], s, last) rows.append((s, tp, tt)) sweep_rows.append((p, s, last, tp["slope"], tp["lo"], tp["hi"], tt["slope"], tt["lo"], tt["hi"])) nb = sum(below(r[1]) for r in rows) na = sum(above(r[2]) for r in rows) last_below = max([r[0] for r in rows if below(r[1])], default=None) first_not_below = min([r[0] for r in rows if not below(r[1])], default=None) res["T1"][p] = {"starts": [first, last - 29], "end": last, "n_starts": len(rows), "polar_below_zero": nb, "tropical_above_zero": na, "last_start_polar_below": last_below, "first_start_polar_not_below": first_not_below, "at_1979": {"polar": next(r[1] for r in rows if r[0] == 1979), "tropical": next(r[2] for r in rows if r[0] == 1979)} if 1979 <= last - 29 else None} if p == "c20v3": for s in (1836, 1850, 1900, 1950): res["T1"][p][f"from_{s}"] = {"polar": L.trend_window(y, b["polar"], s, last), "tropical": L.trend_window(y, b["tropical"], s, last)} # T2 common windows trio = [p for p in (r1p, "jra55", "c20v3") if p in data] res["T2"]["products"] = trio win = [] for s in range(1958, 2015 - 29 + 1): for e in range(s + 29, 2016): tp = {p: L.trend_window(data[p][0], data[p][1]["polar"], s, e) for p in trio} tt = {p: L.trend_window(data[p][0], data[p][1]["tropical"], s, e) for p in trio} win.append((s, e, tp, tt)) n = len(win) allb = sum(all(below(w[2][p]) for p in trio) for w in win) allneg = sum(all(w[2][p]["slope"] < 0 for p in trio) for w in win) alla = sum(all(above(w[3][p]) for p in trio) for w in win) allpos = sum(all(w[3][p]["slope"] > 0 for p in trio) for w in win) per = {p: {"polar_below": sum(below(w[2][p]) for w in win), "tropical_above": sum(above(w[3][p]) for w in win)} for p in trio} share = allb / n reading = ("robust" if share >= 0.8 else "depends on the period" if share < 0.5 else "partly robust") share_t = alla / n reading_t = ("robust" if share_t >= 0.8 else "depends on the period" if share_t < 0.5 else "partly robust") res["T2"].update({"n_windows": n, "all_polar_below": allb, "all_polar_negative": allneg, "all_tropical_above": alla, "all_tropical_positive": allpos, "per_product": per, "reading_polar": reading, "reading_tropical": reading_t, "share_all_polar_below": share, "share_all_tropical_above": share_t}) # windows where all three polar intervals lie below zero res["T2"]["windows_all_polar_below"] = [[w[0], w[1]] for w in win if all(below(w[2][p]) for p in trio)] with open(os.path.join(out, "periods_common_windows.csv"), "w", newline="\n") as fh: fh.write("start,end," + ",".join(f"{p}_polar,{p}_polar_lo,{p}_polar_hi" for p in trio) + "," + ",".join(f"{p}_trop,{p}_trop_lo,{p}_trop_hi" for p in trio) + "\n") for s, e, tp, tt in win: fh.write(f"{s},{e}," + ",".join(f"{tp[p]['slope']:.4f},{tp[p]['lo']:.4f},{tp[p]['hi']:.4f}" for p in trio) + "," + ",".join(f"{tt[p]['slope']:.4f},{tt[p]['lo']:.4f},{tt[p]['hi']:.4f}" for p in trio) + "\n") # T3 30-year windows for p, (y, b) in data.items(): rows = [(s, L.trend_window(y, b["polar"], s, s + 29), L.trend_window(y, b["tropical"], s, s + 29)) for s in range(int(y[0]), int(y[-1]) - 29 + 1)] res["T3"][p] = {"n": len(rows), "polar_below": sum(below(r[1]) for r in rows), "polar_min": min(r[1]["slope"] for r in rows), "polar_max": max(r[1]["slope"] for r in rows), "polar_min_start": min(rows, key=lambda r: r[1]["slope"])[0], "polar_max_start": max(rows, key=lambda r: r[1]["slope"])[0], "tropical_above": sum(above(r[2]) for r in rows), "tropical_min": min(r[2]["slope"] for r in rows), "tropical_max": max(r[2]["slope"] for r in rows)} with open(os.path.join(out, "periods_start_sweep.csv"), "w", newline="\n") as fh: fh.write("product,start,end,polar,polar_lo,polar_hi,tropical,trop_lo,trop_hi\n") for r in sweep_rows: fh.write(f"{r[0]},{r[1]},{r[2]}," + ",".join(f"{x:.4f}" for x in r[3:]) + "\n") with open(os.path.join(out, f"periods_{r1p}.json"), "w", newline="\n") as fh: json.dump(res, fh, indent=1) print(json.dumps({k: v for k, v in res["T2"].items() if k != "windows_all_polar_below"}, indent=1)) print("windows with all three polar intervals below zero:", res["T2"]["windows_all_polar_below"][:40]) for p, v in res["T1"].items(): print(p, {k: v[k] for k in ("starts", "end", "n_starts", "polar_below_zero", "tropical_above_zero", "last_start_polar_below", "first_start_polar_not_below")}) for s in (1836, 1850, 1900, 1950): if f"from_{s}" in v: q = v[f"from_{s}"] print(" from", s, "polar", round(q["polar"]["slope"], 3), [round(q["polar"]["lo"], 3), round(q["polar"]["hi"], 3)], "tropical", round(q["tropical"]["slope"], 3), [round(q["tropical"]["lo"], 3), round(q["tropical"]["hi"], 3)]) for p, v in res["T3"].items(): print("T3", p, v) if __name__ == "__main__": main(sys.argv[1], sys.argv[2], sys.argv[3:])