"""What physics allows for the global-mean surface-pressure trend (RULES_globalmass.txt, with RULES_globalmass_amendment1.txt for B1's range). Usage: py -3.12 -I globalmass.py """ import json import math 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 PDRY = 983.05 # hPa, Trenberth and Smith (2005): 985.50 x 5.1352/5.1480 M_CO2, M_O2, M_AIR = 44.0095, 31.9988, 28.9647 X_O2 = 0.2094 G = 9.80665 R_EARTH = 6.371e6 M_ATM = 5.1480e18 # kg, Trenberth and Smith (2005) def read_co2(path): y, v, u = [], [], [] for line in open(path, encoding="utf-8"): if line.startswith("#") or not line.strip(): continue f = line.split() y.append(int(f[0])) v.append(float(f[1])) u.append(float(f[2])) return np.array(y), np.array(v), np.array(u) def co2_slope_sigma(y, v, u, a, b): """Amendment 1: OLS slope (ppm/yr) and its sigma from NOAA's stated per-year uncertainty, sigma_b = rms(unc) / sqrt(Sxx).""" s = (y >= a) & (y <= b) x = y[s].astype(float) sl = np.polyfit(x, v[s], 1)[0] sxx = ((x - x.mean()) ** 2).sum() return float(sl), float(np.sqrt((u[s] ** 2).mean()) / np.sqrt(sxx)) def read_o2(path): by = {} for line in open(path, encoding="utf-8"): if line.startswith('"') or not line[:4].isdigit(): continue f = [x.strip() for x in line.split(",")] if f[4] != "NaN": by.setdefault(int(f[0]), []).append(float(f[4])) yrs = np.array(sorted(y for y, v in by.items() if len(v) == 12)) return yrs, np.array([np.mean(by[y]) for y in yrs]) def read_gistemp(path): y, v = [], [] for line in open(path, encoding="utf-8"): f = line.strip().split(",") if f[0].isdigit() and len(f) > 13 and f[13] not in ("***", ""): y.append(int(f[0])) v.append(float(f[13])) return np.array(y), np.array(v) def ols_slope(y, v, a, b): s = (y >= a) & (y <= b) return np.polyfit(y[s], v[s], 1)[0], int(s.sum()) def b1(dco2, ddelta): """hPa per decade from mol/mol per year (CO2) and per-meg x 1e-6 per year (O2/N2).""" return 10 * PDRY * (M_CO2 * dco2 + M_O2 * X_O2 * ddelta) / M_AIR def band_area(lat_lo, lat_hi): return 2 * math.pi * R_EARTH ** 2 * (math.sin(math.radians(lat_hi)) - math.sin(math.radians(lat_lo))) def main(downloads, out): res = {"rules": "RULES_globalmass.txt", "constants": { "Pdry_hPa": PDRY, "M_CO2": M_CO2, "M_O2": M_O2, "M_air": M_AIR, "X_O2": X_O2}} cy, cv, cu = read_co2(os.path.join(downloads, "noaa-gml-co2", "co2_annmean_gl.txt")) o2 = {s: read_o2(os.path.join(downloads, "scripps-o2", f"monthly_o2_{s}.csv")) for s in ("alt", "ljo", "cgo")} w1a = max(int(y[0]) for y, _ in o2.values()) w1b = min(int(y[-1]) for y, _ in o2.values()) w1b = min(w1b, int(cy[-1])) res["W1"] = [w1a, w1b] o2s = {} for s, (y, v) in o2.items(): sl, n = ols_slope(y, v, w1a, w1b) o2s[s] = {"per_meg_per_year": float(sl), "n_complete_years": n} res["o2_slopes_W1"] = o2s o2_vals = [d["per_meg_per_year"] for d in o2s.values()] o2_mean = float(np.mean(o2_vals)) gy, gv = read_gistemp(os.path.join(downloads, "nasa-gistemp", "GLB.Ts+dSST.csv")) budget = {} for name in ("r1", "r1g"): rows = [l.strip().split(",") for l in open(os.path.join(out, f"annual_global_{name}_budget.csv"), encoding="utf-8")] budget[name] = (np.array([int(r[0]) for r in rows[1:]]), np.array([float(r[2]) for r in rows[1:]]), np.array([float(r[3]) for r in rows[1:]]), np.array([float(r[1]) for r in rows[1:]])) co2_w1 = L.trend_window(cy, cv, w1a, w1b) # ppm per decade windows = {"W1": (w1a, w1b), "1979-2025": (1979, 2025), "1979-2023": (1979, 2023), "1979-2015": (1979, 2015), "1979-2001": (1979, 2001)} res["bound"] = {} for wn, (a, b) in windows.items(): co2 = L.trend_window(cy, cv, a, b) ratio = co2["slope"] / co2_w1["slope"] dd = [x * (1.0 if wn == "W1" else ratio) for x in o2_vals] # amendment 1: CO2 sigma from NOAA's stated uncertainty; O2 bracket csl, csig = co2_slope_sigma(cy, cv, cu, a, b) dco2 = [(csl - 2 * csig) * 1e-6, csl * 1e-6, (csl + 2 * csig) * 1e-6] o2_low = min(o2_vals) if a < w1a else min(dd) o2_high = max(dd) B1 = b1(dco2[1], np.mean(dd) * 1e-6) B1_lo = b1(dco2[0], o2_low * 1e-6) B1_hi = b1(dco2[2], o2_high * 1e-6) yv, V, D, Tt = budget["r1"] bv = L.trend_window(yv, V, a, b) vbar = float(V[(yv >= a) & (yv <= b)].mean()) dT, nT = ols_slope(gy, gv, a, b) cc = (vbar * 0.06 * dT * 10, vbar * 0.075 * dT * 10) lower = B1_lo + min(bv["lo"], cc[0]) upper = B1_hi + max(bv["hi"], cc[1]) entry = {"years": [a, b], "co2_ppm_per_decade": co2, "o2_scaling_ratio": ratio, "o2_per_meg_per_year_used": dd, "o2_bracket": [o2_low, o2_high], "co2_slope_ppm_per_year_amend1": [csl, csig], "B1_dry": B1, "B1_dry_range": [B1_lo, B1_hi], "B2_r1_vapour": bv, "B2_cc": list(cc), "gistemp_K_per_decade": dT * 10, "vapour_mean_hPa": vbar, "bound_total": [lower, upper], "expected_central": B1 + bv["slope"]} for name in ("r1", "r1g"): yv2, V2, D2, T2 = budget[name] if b <= yv2[-1]: entry[f"{name}_dry"] = L.trend_window(yv2, D2, a, b) entry[f"{name}_total"] = L.trend_window(yv2, T2, a, b) res["bound"][wn] = entry # reanalysis global trends (ours, M1) against the bound for their windows rep = json.load(open(os.path.join(out, "reproduce.json"), encoding="utf-8")) cmp_ = {} for p, wn, key in (("r1", "1979-2025", "1979+"), ("r1g", "1979-2025", "1979+"), ("jra55", "1979-2023", "1979+"), ("c20v3", "1979-2015", "1979+")): t = rep["products"][p]["trends"][key]["global"]["M1"] lo_b, hi_b = res["bound"][wn]["bound_total"] cmp_[p] = {"window": wn, "trend": t["slope"], "lo": t["lo"], "hi": t["hi"], "bound": [lo_b, hi_b], "wholly_outside": bool(t["hi"] < lo_b or t["lo"] > hi_b), "slope_outside": bool(t["slope"] < lo_b or t["slope"] > hi_b)} res["reanalyses_vs_bound"] = cmp_ # magnitudes areas = {"arctic": band_area(60, 90), "antarctic": band_area(-90, -60), "polar": band_area(60, 90) * 2, "tropical": band_area(-23.5, 23.5), "global": band_area(-90, 90)} mags = {} for p in ("r1g", "jra55", "c20v3", "r1"): pr = rep["products"][p] rows = [l.strip().split(",") for l in open(os.path.join(out, f"annual_bands_{p}.csv"), encoding="utf-8")] hdr = rows[0] yrs = np.array([int(r[0]) for r in rows[1:]]) mags[p] = {} for band in ("arctic", "antarctic", "polar", "tropical", "global"): v = np.array([float(r[hdr.index(band)]) for r in rows[1:]]) t = pr["trends"]["full"][band]["M1"] span = yrs[-1] - yrs[0] resid = v - np.polyval(np.polyfit(yrs, v, 1), yrs) dp_total = t["slope"] / 10 * span mags[p][band] = { "trend_hPa_per_decade": t["slope"], "percent_of_mean_per_decade": 100 * t["slope"] / pr["mean_hPa"][band], "mass_kg_per_decade": t["slope"] * 100 * areas[band] / G, "mass_fraction_of_atmosphere_per_decade": t["slope"] * 100 * areas[band] / G / M_ATM, "change_over_record_hPa": dp_total, "detrended_sd_hPa": float(resid.std(ddof=1)), "change_over_record_in_sd": float(dp_total / resid.std(ddof=1)), "years": [int(yrs[0]), int(yrs[-1])]} res["magnitudes"] = mags res["band_area_fraction"] = {k: v / areas["global"] for k, v in areas.items()} with open(os.path.join(out, "globalmass.json"), "w", newline="\n") as fh: json.dump(res, fh, indent=1) print("W1", res["W1"], "O2 slopes", {k: (round(v["per_meg_per_year"], 2), v["n_complete_years"]) for k, v in o2s.items()}) for wn, e in res["bound"].items(): print(wn, "CO2", round(e["co2_ppm_per_decade"]["slope"] / 10, 3), "ppm/yr; ratio", round(e["o2_scaling_ratio"], 3), "; B1", round(e["B1_dry"], 4), [round(x, 4) for x in e["B1_dry_range"]], "; B2 R1", round(e["B2_r1_vapour"]["slope"], 4), [round(e["B2_r1_vapour"]["lo"], 4), round(e["B2_r1_vapour"]["hi"], 4)], "; CC", [round(x, 4) for x in e["B2_cc"]], "(dT", round(e["gistemp_K_per_decade"], 3), "K/dec)", "; bound", [round(x, 4) for x in e["bound_total"]], "; R1g dry", None if "r1g_dry" not in e else (round(e["r1g_dry"]["slope"], 4), round(e["r1g_dry"]["lo"], 4), round(e["r1g_dry"]["hi"], 4)), "; R1 dry", None if "r1_dry" not in e else (round(e["r1_dry"]["slope"], 4), round(e["r1_dry"]["lo"], 4), round(e["r1_dry"]["hi"], 4))) for p, c in cmp_.items(): print("vs bound", p, c) for p, m in mags.items(): for band, x in m.items(): print("mag", p, band, round(x["trend_hPa_per_decade"], 3), "hPa/dec;", round(x["percent_of_mean_per_decade"], 4), "%/dec;", f"{x['mass_fraction_of_atmosphere_per_decade']:.2e} of atm/dec;", round(x["change_over_record_hPa"], 2), "hPa over", x["years"], ";", round(x["change_over_record_in_sd"], 2), "SDs (SD", round(x["detrended_sd_hPa"], 3), ")") if __name__ == "__main__": main(sys.argv[1], sys.argv[2])