"""Reproduce note 010's band trends, latitude profile and R1 mass budget. Usage: py -3.12 -I reproduce.py [products...] Follows RULES_reproduce.txt. Reads /cache/.npz written by extract_fields.py. Writes reproduce.json, annual_bands_.csv and lat_profile_.csv in . """ 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 FULL = {"r1": (1948, 2025), "jra55": (1958, 2023), "c20v3": (1806, 2015), "r1g": (1948, 2025)} LABEL = {"r1": "NCEP/NCAR R1", "jra55": "JRA-55", "c20v3": "20CRv3", "r1g": "NCEP/NCAR R1, T62 Gaussian file (amendment 1)"} BANDS = ["arctic", "antarctic", "polar", "tropical", "global"] # The note's printed values (Claims; Methods) for comparison. NOTE = { ("polar", "full"): {"r1": -0.655, "jra55": -0.360, "c20v3": -0.117}, ("tropical", "full"): {"r1": 0.090, "jra55": 0.040, "c20v3": 0.076}, ("antarctic", "full"): {"r1": -1.148, "jra55": -0.589, "c20v3": -0.074}, ("arctic", "full"): {"r1": -0.161, "jra55": -0.130, "c20v3": -0.161}, ("global", "1979+"): {"r1": (-0.0295, -0.0576, -0.0014), "jra55": (0.0737, 0.0503, 0.0972), "c20v3": (0.0358, 0.0271, 0.0444)}, ("global", "common"): {"r1": -0.0357, "jra55": 0.0626, "c20v3": 0.0358}, } def load(out, product): d = np.load(os.path.join(out, "cache", product + ".npz")) return {k: d[k] for k in d.files} def annual_bands(c): series = {b: L.band_series(c["zonal"], c["lat"], b) for b in BANDS} yrs, ann = L.annual_means(c["years"], c["months"], np.column_stack([series[b] for b in BANDS])) return yrs, {b: ann[:, i] for i, b in enumerate(BANDS)} def windows(product): s, e = FULL[product] w = {"full": (s, e), "1979+": (1979, e), "common": (1979, 2015)} if product == "c20v3": w["1836-2015"] = (1836, 2015) return w def main(out, products): res = {"rules": "RULES_reproduce.txt", "products": {}} for p in products: c = load(out, p) yrs, ann = annual_bands(c) pr = {"label": LABEL[p], "years": [int(yrs[0]), int(yrs[-1])], "n_years": int(len(yrs)), "missing_values": int(c["nmiss"]), "mean_hPa": {b: float(ann[b].mean()) for b in BANDS}, "trends": {}} for wname, (s, e) in windows(p).items(): pr["trends"][wname] = {} for b in BANDS: t = {m: L.trend_window(yrs, ann[b], s, e, m) for m in ("M1", "M2", "M3", "M4", "M5")} pr["trends"][wname][b] = t # latitude profile (item 11) zy, zann = L.annual_means(c["years"], c["months"], c["zonal"]) prof = [] for j, la in enumerate(c["lat"]): row = {"lat": float(la)} for wname in ("full", "1979+"): s, e = windows(p)[wname] t = L.trend_window(zy, zann[:, j], s, e, "M1") row[wname] = t["slope"] row[wname + "_lo"] = t["lo"] row[wname + "_hi"] = t["hi"] prof.append(row) south = [r for r in prof if r["lat"] < -30] mn = min(south, key=lambda r: r["full"]) pr["profile_min_south_of_30S_full"] = {"lat": mn["lat"], "trend": mn["full"], "lo": mn["full_lo"], "hi": mn["full_hi"]} mn79 = min(south, key=lambda r: r["1979+"]) pr["profile_min_south_of_30S_1979"] = {"lat": mn79["lat"], "trend": mn79["1979+"]} pr["profile_at"] = {str(int(r["lat"])): {"full": r["full"], "1979+": r["1979+"]} for r in prof if r["lat"] in (-60.0, -70.0, -90.0, 60.0, 90.0)} with open(os.path.join(out, f"lat_profile_{p}.csv"), "w", newline="\n") as fh: fh.write("lat,trend_full,lo_full,hi_full,trend_1979,lo_1979,hi_1979\n") for r in prof: fh.write(",".join(f"{r[k]:.4f}" if r[k] is not None else "" for k in ("lat", "full", "full_lo", "full_hi", "1979+", "1979+_lo", "1979+_hi")) + "\n") with open(os.path.join(out, f"annual_bands_{p}.csv"), "w", newline="\n") as fh: fh.write("year," + ",".join(BANDS) + "\n") for i, y in enumerate(yrs): fh.write(f"{y}," + ",".join(f"{ann[b][i]:.4f}" for b in BANDS) + "\n") res["products"][p] = pr # R1 mass budget (item 12); amendment 1: the same with the Gaussian total for tot_name, key in (("r1", "r1_mass_budget"), ("r1g", "r1g_mass_budget")): if tot_name not in products: continue c = load(out, tot_name) w = load(out, "r1_prwtr") assert (c["years"] == w["years"]).all() and (c["months"] == w["months"]).all() tot = L.band_series(c["zonal"], c["lat"], "global") vap = L.band_series(w["zonal"], w["lat"], "global") * 0.0980665 yrs, ann = L.annual_means(c["years"], c["months"], np.column_stack([tot, vap])) T, V = ann[:, 0], ann[:, 1] D = T - V mb = {} for wname, (s, e) in {"1979-2025": (1979, 2025), "1948-2025": (1948, 2025), "1991-2025": (1991, 2025)}.items(): mb[wname] = {k: L.trend_window(yrs, v, s, e, "M1") for k, v in (("total", T), ("vapour", V), ("dry", D))} mb[wname]["vapour_mean_hPa"] = float(V[(yrs >= s) & (yrs <= e)].mean()) mb[wname]["pw_mean_kg_m2"] = float(V[(yrs >= s) & (yrs <= e)].mean() / 0.0980665) res[key] = mb with open(os.path.join(out, f"annual_global_{tot_name}_budget.csv"), "w", newline="\n") as fh: fh.write("year,total_hPa,vapour_hPa,dry_hPa\n") for i, y in enumerate(yrs): fh.write(f"{y},{T[i]:.4f},{V[i]:.4f},{D[i]:.4f}\n") # comparison with the note comp = [] for (band, wname), vals in NOTE.items(): for p0, nv in vals.items(): for p in ([p0, "r1g"] if p0 == "r1" else [p0]): if p not in res["products"]: continue t = res["products"][p]["trends"][wname][band]["M1"] nv_s = nv[0] if isinstance(nv, tuple) else nv dec = 4 if abs(nv_s) < 0.1 and band == "global" else 3 ok = abs(round(t["slope"], dec) - nv_s) <= 10 ** (-dec) + 1e-12 row = {"band": band, "window": wname, "product": p, "note": nv, "ours": round(t["slope"], 4), "ours_lo": round(t["lo"], 4), "ours_hi": round(t["hi"], 4), "slope_reproduces": bool(ok)} if isinstance(nv, tuple): for m in ("M1", "M2", "M3", "M4", "M5"): tm = res["products"][p]["trends"][wname][band][m] row[f"{m}_interval"] = [round(tm["lo"], 4), round(tm["hi"], 4)] comp.append(row) res["comparison_with_note"] = comp with open(os.path.join(out, "reproduce.json"), "w", newline="\n") as fh: json.dump(res, fh, indent=1) for r in comp: print(r) if __name__ == "__main__": main(sys.argv[1], sys.argv[2:])