"""Recompute the numbers on factchecked.science's page on S0 News's research note 010 ("Earth Air Shift"), using Python's standard library only. Usage: python3 -I fetch_inputs.py inputs --small (about 19 MB of public files) python3 -I polar_pressure_check.py inputs [derived_dir] [output.json] holds our derived series (annual_bands_*.csv, annual_global_*_budget.csv, station_points_annual_*.csv, r1_slp_zonal_annual.csv, r1_slp_points_annual.csv), hosted next to this script; by default the script's own folder. Those series come from the reanalysis files through extract_fields.py, reproduce.py, export_derived.py and fixround_checks.py, which need numpy, scipy, netCDF4 and cftime (fetch_inputs.py --all fetches about 520 MB plus 793 small JRA-55 files for them). This script re-implements the registered methods (RULES_*.txt) in plain Python: ordinary least squares, the lag-1 interval M1 (Santer et al. 2000, r floored at 0, t on n_eff - 2) and M6 (the same with r1 as a Pearson correlation of lagged residuals, the form that reproduces the note's printed intervals), day-weighted annual means of complete years. It prints each result and writes stdlib_check.json (by default in the inputs folder). Section 9 was added after a fresh review of the page (exploratory); it needs Resolute Bay's ISD files for 1976-1978 too (fetch_inputs.py --small fetches them). """ import calendar import csv import glob import gzip import json import math import os import re import statistics import sys # ---------------------------------------------------------------- statistics def _betacf(a, b, x): """Continued fraction for the regularized incomplete beta (Lentz).""" tiny = 1e-300 qab, qap, qam = a + b, a + 1.0, a - 1.0 c, d = 1.0, 1.0 - qab * x / qap d = 1.0 / (d if abs(d) > tiny else tiny) h = d for m in range(1, 400): m2 = 2 * m aa = m * (b - m) * x / ((qam + m2) * (a + m2)) d = 1.0 + aa * d d = 1.0 / (d if abs(d) > tiny else tiny) c = 1.0 + aa / c if abs(1.0 + aa / c) > tiny else tiny h *= d * c aa = -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2)) d = 1.0 + aa * d d = 1.0 / (d if abs(d) > tiny else tiny) c = 1.0 + aa / c if abs(1.0 + aa / c) > tiny else tiny delta = d * c h *= delta if abs(delta - 1.0) < 1e-15: break return h def betainc(a, b, x): if x <= 0: return 0.0 if x >= 1: return 1.0 lbt = (math.lgamma(a + b) - math.lgamma(a) - math.lgamma(b) + a * math.log(x) + b * math.log(1.0 - x)) if x < (a + 1.0) / (a + b + 2.0): return math.exp(lbt) * _betacf(a, b, x) / a return 1.0 - math.exp(lbt) * _betacf(b, a, 1.0 - x) / b def t_sf(t, df): """Upper tail of Student's t with (possibly non-integer) df.""" x = df / (df + t * t) tail = 0.5 * betainc(df / 2.0, 0.5, x) return tail if t >= 0 else 1.0 - tail def t_ppf975(df): lo, hi = 0.0, 1000.0 for _ in range(200): mid = 0.5 * (lo + hi) if t_sf(mid, df) > 0.025: lo = mid else: hi = mid return 0.5 * (lo + hi) def ols(x, y): n = len(x) xm, ym = sum(x) / n, sum(y) / n sxx = sum((a - xm) ** 2 for a in x) b = sum((a - xm) * (c - ym) for a, c in zip(x, y)) / sxx a0 = ym - b * xm e = [c - (a0 + b * a) for a, c in zip(x, y)] return n, sxx, b, a0, e def pearson(u, v): um, vm = sum(u) / len(u), sum(v) / len(v) su = math.sqrt(sum((a - um) ** 2 for a in u)) sv = math.sqrt(sum((b - vm) ** 2 for b in v)) return sum((a - um) * (b - vm) for a, b in zip(u, v)) / (su * sv) def trend(x, y, method="M1"): """Slope per decade with the lag-1-adjusted 95% interval (M1 or M6).""" n, sxx, b, a0, e = ols(x, y) sse = sum(v * v for v in e) if method == "M1": r1 = sum(e[i] * e[i + 1] for i in range(n - 1)) / sse else: r1 = pearson(e[:-1], e[1:]) r = max(r1, 0.0) neff = n * (1 - r) / (1 + r) out = {"n": n, "slope": b * 10, "r1": r1, "neff": neff, "lo": None, "hi": None, "p": None} if neff > 2: se = math.sqrt(sse / (neff - 2) / sxx) crit = t_ppf975(neff - 2) out.update(lo=(b - crit * se) * 10, hi=(b + crit * se) * 10, p=2 * t_sf(abs(b) / se, neff - 2)) return out def window(yrs, vals, a, b, method="M1"): pts = [(y, v) for y, v in zip(yrs, vals) if a <= y <= b and v is not None] if len(pts) < 3: return None t = trend([p[0] for p in pts], [p[1] for p in pts], method) t["first"], t["last"] = pts[0][0], pts[-1][0] return t def annual(rows, weighting="days"): """rows: iterable of (year, month, value); complete calendar years only.""" by = {} for y, m, v in rows: if v is None or (isinstance(v, float) and math.isnan(v)): continue by.setdefault(y, {})[m] = v out = {} for y, ms in sorted(by.items()): if sorted(ms) != list(range(1, 13)): continue w = [calendar.monthrange(y, m)[1] if weighting == "days" else 1 for m in range(1, 13)] out[y] = sum(ms[m] * w[m - 1] for m in range(1, 13)) / sum(w) return out def fmt(t, d=4): if t is None: return "n/a" if t["lo"] is None: return f"{t['slope']:+.{d}f} [interval undefined] n={t['n']}" return f"{t['slope']:+.{d}f} [{t['lo']:+.{d}f}, {t['hi']:+.{d}f}] n={t['n']}" # ---------------------------------------------------------------- readers def read_csv(path): with open(path, encoding="utf-8") as fh: rows = [r for r in csv.reader(fh) if r and not r[0].startswith("#")] head = rows[0] cols = {h: [] for h in head} for r in rows[1:]: for h, v in zip(head, r): cols[h].append(int(v) if h == "year" else (float(v) if v != "" else None)) return cols def read_reader(path): rows = [] with open(path, encoding="utf-8", errors="replace") as fh: for line in fh: f = line.split() if len(f) == 13 and re.fullmatch(r"\d{4}", f[0]): for m in range(12): tok = f[m + 1] v = float(tok) if re.fullmatch(r"-?\d+(\.\d+)?", tok) else None rows.append((int(f[0]), m + 1, v)) return rows def read_isd(files, min_hours=4): hourly = {"stp": {}, "slp": {}} diffs = {} for fn in files: with gzip.open(fn, "rt", encoding="latin-1") as fh: for line in fh: key = (line[15:23], line[23:25]) slp, q = line[99:104], line[104] s_v = int(slp) / 10.0 if slp != "99999" and q not in "2367" else None m = re.search(r"MA1(\d{5})(.)(\d{5})(.)", line[105:]) p_v = (int(m.group(3)) / 10.0 if m and m.group(3) != "99999" and m.group(4) not in "2367" else None) if s_v is not None: hourly["slp"].setdefault(key, []).append(s_v) if p_v is not None: hourly["stp"].setdefault(key, []).append(p_v) if s_v is not None and p_v is not None: diffs.setdefault(int(line[15:19]), []).append(p_v - s_v) out = {} for var, h in hourly.items(): days = {} for (date, hh), v in h.items(): days.setdefault(date, []).append(sum(v) / len(v)) months = {} for date, hv in days.items(): if len(hv) >= min_hours: months.setdefault((int(date[:4]), int(date[4:6])), []).append(sum(hv) / len(hv)) out[var] = annual((y, m, sum(v) / len(v)) for (y, m), v in months.items() if len(v) >= 20) return out, {y: sum(v) / len(v) for y, v in sorted(diffs.items())} def read_o2(path): by = {} with open(path, encoding="utf-8") as fh: for line in fh: 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])) return {y: sum(v) / 12 for y, v in by.items() if len(v) == 12} def read_co2(path): out = {} with open(path, encoding="utf-8") as fh: for line in fh: if line.startswith("#") or not line.strip(): continue f = line.split() out[int(f[0])] = (float(f[1]), float(f[2])) return out def read_gistemp(path): out = {} with open(path, encoding="utf-8") as fh: for line in fh: f = line.strip().split(",") if f[0].isdigit() and len(f) > 13 and f[13] not in ("***", ""): out[int(f[0])] = float(f[13]) return out def read_marshall_monthly(path): rows = [] with open(path, encoding="utf-8") as fh: for line in fh: f = line.split() if f and re.fullmatch(r"\d{4}", f[0]): for m, tok in enumerate(f[1:], start=1): rows.append((int(f[0]), m, float(tok))) return rows def read_sam_seas(path): out = {"ANN": {}, "SUM": {}} with open(path, encoding="utf-8") as fh: for line in fh: if not line[:4].isdigit(): continue y = int(line[:4]) for k, name in ((0, "ANN"), (4, "SUM")): tok = line[4 + 6 * k: 10 + 6 * k].strip() if tok: out[name][y] = float(tok) return out # ---------------------------------------------------------------- the checks NOTE = { # the note's printed values, Claims and Methods ("polar", "full"): {"r1g": -0.655, "jra55": -0.360, "c20v3": -0.117}, ("tropical", "full"): {"r1g": 0.090, "jra55": 0.040, "c20v3": 0.076}, ("antarctic", "full"): {"r1g": -1.148, "jra55": -0.589, "c20v3": -0.074}, ("arctic", "full"): {"r1g": -0.161, "jra55": -0.130, "c20v3": -0.161}, ("global", "1979+"): {"r1g": -0.0295, "jra55": 0.0737, "c20v3": 0.0358}, ("global", "common"): {"r1g": -0.0357, "jra55": 0.0626, "c20v3": 0.0358}, } FULL = {"r1": (1948, 2025), "r1g": (1948, 2025), "jra55": (1958, 2023), "c20v3": (1806, 2015)} STATIONS = ["Amundsen_Scott", "Vostok", "Mirny", "Casey", "Davis", "Mawson", "Syowa", "Novolazarevskaya", "Dumont_Durville", "McMurdo", "Orcadas", "Esperanza", "Bellingshausen", "Faraday"] def main(inputs, derived, out_json): res = {} bands = {p: read_csv(os.path.join(derived, f"annual_bands_{p}.csv")) for p in ("r1g", "r1", "jra55", "c20v3")} print("== 1. The note's band trends (hPa per decade; M1, and M6 where the note prints an interval)") res["reproduce"] = {} for (band, wn), vals in NOTE.items(): for p, nv in vals.items(): s, e = FULL[p] a = 1979 if wn != "full" else s b = 2015 if wn == "common" else e t1 = window(bands[p]["year"], bands[p][band], a, b) t6 = window(bands[p]["year"], bands[p][band], a, b, "M6") res["reproduce"][f"{band} {wn} {p}"] = {"note": nv, "M1": t1, "M6": t6} print(f" {band:9s} {wn:6s} {p:5s} note {nv:+.4f} ours {fmt(t1)} M6 [{t6['lo']:+.4f}, {t6['hi']:+.4f}]") bud = read_csv(os.path.join(derived, "annual_global_r1g_budget.csv")) for col in ("dry_hPa", "vapour_hPa"): t6 = window(bud["year"], bud[col], 1979, 2025, "M6") print(f" R1 {col} 1979-2025 (M6): {fmt(t6)} (note: dry -0.0536 [-0.0759, -0.0313]; vapour +0.0241)") res["reproduce"][f"r1g {col} 1979-2025 M6"] = t6 print("== 2. Common windows of >= 30 years in 1958-2015 (R1 = the T62 Gaussian file)") trio = ("r1g", "jra55", "c20v3") by_start, n_all, n_below = {}, 0, 0 for s in range(1958, 1987): for e in range(s + 29, 2016): ok = all(window(bands[p]["year"], bands[p]["polar"], s, e)["hi"] < 0 for p in trio) n_all += 1 n_below += ok by_start.setdefault(s, [0, 0]) by_start[s][0] += ok by_start[s][1] += 1 late = sum(v[0] for s, v in by_start.items() if s >= 1973) late_n = sum(v[1] for s, v in by_start.items() if s >= 1973) print(f" all three polar intervals below zero: {n_below} of {n_all}; starting 1973 or later: {late} of {late_n}") print(" by start year: " + " ".join(f"{s}:{v[0]}/{v[1]}" for s, v in sorted(by_start.items()))) res["periods"] = {"windows": n_all, "all_below": n_below, "from_1973": [late, late_n], "by_start": by_start} print("== 3. The global-mean bound (hPa per decade)") co2 = read_co2(os.path.join(inputs, "noaa-gml-co2", "co2_annmean_gl.txt")) o2 = {st: read_o2(os.path.join(inputs, "scripps-o2", f"monthly_o2_{st}.csv")) for st in ("alt", "ljo", "cgo")} gis = read_gistemp(os.path.join(inputs, "nasa-gistemp", "GLB.Ts+dSST.csv")) w1a = max(min(v) for v in o2.values()) w1b = min(min(max(v) for v in o2.values()), max(co2)) def slope(d, a, b): ys = [y for y in sorted(d) if a <= y <= b] vs = [d[y][0] if isinstance(d[y], tuple) else d[y] for y in ys] return ols(ys, vs)[2], ys def co2_sigma(a, b): ys = [y for y in sorted(co2) if a <= y <= b] xm = sum(ys) / len(ys) sxx = sum((y - xm) ** 2 for y in ys) return math.sqrt(sum(co2[y][1] ** 2 for y in ys) / len(ys)) / math.sqrt(sxx) o2s = [slope(o2[st], w1a, w1b)[0] for st in ("alt", "ljo", "cgo")] c_w1 = slope(co2, w1a, w1b)[0] PDRY, MC, MO, MA, XO = 983.05, 44.0095, 31.9988, 28.9647, 0.2094 def b1(dco2_ppm, ddel_permeg): return 10 * PDRY * (MC * dco2_ppm * 1e-6 + MO * XO * ddel_permeg * 1e-6) / MA res["bound"] = {} r1bud = read_csv(os.path.join(derived, "annual_global_r1_budget.csv")) for a, b in ((w1a, w1b), (1979, 2025), (1979, 2023), (1979, 2015)): c, _ = slope(co2, a, b) sig = co2_sigma(a, b) ratio = c / c_w1 scaled = [x * ratio for x in o2s] lo_o2 = min(o2s) if a < w1a else min(scaled) mid = b1(c, statistics.mean(scaled)) lo, hi = b1(c - 2 * sig, lo_o2), b1(c + 2 * sig, max(scaled)) tv = window(r1bud["year"], r1bud["vapour_hPa"], a, b) vbar = statistics.mean(v for y, v in zip(r1bud["year"], r1bud["vapour_hPa"]) if a <= y <= b) dt = slope(gis, a, b)[0] cc = (vbar * 0.06 * dt * 10, vbar * 0.075 * dt * 10) bound = (lo + min(tv["lo"], cc[0]), hi + max(tv["hi"], cc[1])) res["bound"][f"{a}-{b}"] = {"B1": mid, "B1_range": [lo, hi], "B2_r1": tv, "B2_cc": cc, "bound": bound} print(f" {a}-{b}: B1 {mid:+.4f} [{lo:+.4f}, {hi:+.4f}]; vapour (R1) {fmt(tv)}; " f"CC {cc[0]:+.4f} to {cc[1]:+.4f} (GISTEMP {dt*10:.3f} K/decade); bound {bound[0]:+.4f} to {bound[1]:+.4f}") print(f" O2/N2 slopes {w1a}-{w1b}: " + ", ".join(f"{x:.2f}" for x in o2s) + " per meg a year") print("== 4. The Amundsen Sea Low (BAS ASL v3), 1959-2025") with open(os.path.join(inputs, "bas-asl", "asli_calculation_latest.csv"), encoding="utf-8") as fh: rows = [r for r in csv.reader(fh) if r and r[0][:1].isdigit()] res["asl"] = {} for name, j in (("actual_central_pressure", 3), ("sector_pressure", 4), ("relative_central_pressure", 5)): ann = annual((int(r[0][:4]), int(r[0][5:7]), float(r[j])) for r in rows) ys = sorted(ann) t = window(ys, [ann[y] for y in ys], 1959, 2025) res["asl"][name] = t print(f" {name}: {fmt(t, 3)} (note: -0.614 [-0.856, -0.372])") print("== 5. The SAM (Marshall's index, annual) against the Antarctic band") sam = read_sam_seas(os.path.join(inputs, "bas-sam", "newsam.1957.2007.seas.txt")) ys_s = sorted(sam["ANN"]) print(f" SAM trend 1957-2025: {fmt(window(ys_s, [sam['ANN'][y] for y in ys_s], 1957, 2025), 3)}") res["sam"] = {} for p in ("r1", "r1g", "jra55", "c20v3"): for start in (1957, 1979): yb = bands[p]["year"] ys = [y for y in yb if y >= start and y in sam["ANN"]] v = [bands[p]["antarctic"][yb.index(y)] for y in ys] s = [sam["ANN"][y] for y in ys] n, sxx, beta, a0, e = ols(s, v) tb, ts = trend(ys, v), trend(ys, s) tr = trend(ys, e) dv = ols(ys, v)[4] ds = ols(ys, s)[4] res["sam"][f"{p} {start}"] = {"r": pearson(v, s), "r_detrended": pearson(dv, ds), "share": beta * ts["slope"] / tb["slope"], "residual": tr} print(f" {p:5s} from {start}: r {pearson(v, s):+.3f}, detrended {pearson(dv, ds):+.3f}; " f"band {tb['slope']:+.3f}; SAM share {beta * ts['slope'] / tb['slope']:.2f}; residual {fmt(tr, 3)}") print("== 6. Stations: drift = scaled reanalysis anomaly minus station anomaly") series = {st: annual(read_reader(os.path.join(inputs, "reader", f"{st}.All." + ("msl_pressure" if st == "Faraday" else "station_level_pressure") + ".txt"))) for st in STATIONS} files = sorted(glob.glob(os.path.join(inputs, "noaa-isd", "eureka", "*.gz"))) isd, diffs = read_isd(files, 4) series["Eureka"] = isd["stp"] res["stations"] = {} reading = {} for p in ("r1", "r1g", "jra55", "c20v3"): pts = read_csv(os.path.join(derived, f"station_points_annual_{p}.csv")) for st, ser in series.items(): common = [y for y in pts["year"] if y in ser] for span, (a, b) in (("pre1979", (min(common), 1978)), ("since1979", (1979, max(common)))): ys = [y for y in common if a <= y <= b] if len(ys) < 10: continue s = [ser[y] for y in ys] r = [pts[st][pts["year"].index(y)] for y in ys] k = statistics.mean(s) / statistics.mean(r) rm, sm = statistics.mean(r), statistics.mean(s) d = [k * (ri - rm) - (si - sm) for ri, si in zip(r, s)] t = trend(ys, d) res["stations"][f"{st} {p} {span}"] = t if st != "Eureka": reading.setdefault(f"{p} {span}", []).append(t) for key, ts in reading.items(): med = statistics.median(t["slope"] for t in ts) det = [t for t in ts if t["lo"] is not None and (t["lo"] > 0 or t["hi"] < 0)] rule = med < 0 and len(det) > len(ts) / 2 print(f" {key:16s}: median drift {med:+.2f}, detected at {len(det)} of {len(ts)}" f"{'; artificial trend by the registered rule' if rule and 'pre' in key else ''}") ys = sorted(series["Amundsen_Scott"]) print(f" South Pole station trend 1957-2025: {fmt(window(ys, [series['Amundsen_Scott'][y] for y in ys], 1957, 2025), 3)}") sp_eq = annual(read_reader(os.path.join(inputs, "reader", "Amundsen_Scott.All.station_level_pressure.txt")), "equal") ys = sorted(sp_eq) print(f" South Pole, plain 12-month means (exploratory): {fmt(window(ys, [sp_eq[y] for y in ys], 1957, 2025), 3)}; " f"since 1979 {fmt(window(ys, [sp_eq[y] for y in ys], 1979, 2025), 3)}") print("== 7. Eureka (ISD; exploratory)") for var in ("stp", "slp"): ys = sorted(isd[var]) print(f" {var}: 1951-2024 {fmt(window(ys, [isd[var][y] for y in ys], 1951, 2024), 3)}") print(" yearly mean of station minus sea-level pressure: " + " ".join(f"{y}:{v:+.2f}" for y, v in diffs.items())) res["eureka_diffs"] = diffs print("== 8. R1's zonal sea-level pressure against Marshall's six stations (exploratory)") r1z = read_csv(os.path.join(derived, "r1_slp_zonal_annual.csv")) for lat, fn, col in ((65, "l65.1957.2007.txt", "r1_slp_65S"), (40, "l40.1957.2007.txt", "r1_slp_40S")): st = annual(read_marshall_monthly(os.path.join(inputs, "bas-sam", fn))) ys = [y for y in r1z["year"] if y in st and 1957 <= y <= 2025] r = [r1z[col][r1z["year"].index(y)] for y in ys] s = [st[y] for y in ys] rm, sm = statistics.mean(r), statistics.mean(s) d = [(ri - rm) - (si - sm) for ri, si in zip(r, s)] print(f" {lat} S: stations {fmt(trend(ys, s), 3)}; R1 {fmt(trend(ys, r), 3)}; " f"R1 minus stations {fmt(trend(ys, d), 3)}") # Added after the full texts were read: the sub-period drift and the levels. The full # circle and the six sites differ in level by design (Marshall 2003, p. 4138), so the # page compares trends, and levels only before 1979 against after. early, late = window(ys, d, 1957, 1978), window(ys, d, 1979, 2025) pre = statistics.mean(ri - si for y, ri, si in zip(ys, r, s) if y <= 1978) post = statistics.mean(ri - si for y, ri, si in zip(ys, r, s) if y >= 1979) print(f" R1 minus stations, 1957-1978 {fmt(early, 3)}; 1979-2025 {fmt(late, 3)}") print(f" mean level of R1 minus stations: 1957-1978 {pre:+.2f}, 1979-2025 {post:+.2f}; " f"before 1979 on the chart's 1979-2025 baselines {pre - post:+.2f} hPa") res.setdefault("l65", {})[f"{lat}S"] = {"diff_1957_1978": early, "diff_1979_2025": late, "level_pre": pre, "level_post": post} fixround(inputs, derived, res, bands, series, isd) with open(out_json, "w", newline="\n") as fh: json.dump(res, fh, indent=1, default=str) def solve3(X, y): """Least squares with three columns: (beta, inverse of X'X).""" A = [[sum(r[i] * r[j] for r in X) for j in range(3)] for i in range(3)] b = [sum(r[i] * v for r, v in zip(X, y)) for i in range(3)] n = 3 M = [A[i][:] + [1.0 if i == j else 0.0 for j in range(n)] for i in range(n)] for c in range(n): p = max(range(c, n), key=lambda r: abs(M[r][c])) M[c], M[p] = M[p], M[c] piv = M[c][c] M[c] = [v / piv for v in M[c]] for r in range(n): if r != c: f = M[r][c] M[r] = [a - f * b_ for a, b_ in zip(M[r], M[c])] inv = [row[n:] for row in M] beta = [sum(inv[i][j] * b[j] for j in range(n)) for i in range(n)] return beta, inv def isd_reports(files): """(file id, yyyymmdd, elevation, sea-level, altimeter, station pressure) per report.""" for fn in files: fid = os.path.basename(fn)[:12] with gzip.open(fn, "rt", encoding="latin-1") as fh: for line in fh: s, q = line[99:104], line[104] slp = int(s) / 10.0 if s != "99999" and q not in "2367" else None m = re.search(r"MA1(\d{5})(.)(\d{5})(.)", line[105:]) alt = stp = None if m and m.group(1) != "99999" and m.group(2) not in "2367": alt = int(m.group(1)) / 10.0 if m and m.group(3) != "99999" and m.group(4) not in "2367": stp = int(m.group(3)) / 10.0 yield fid, line[15:23], line[46:51], slp, alt, stp def fixround(inputs, derived, res, bands, series, isd): """Section 9, added after the fresh review: the numbers that review asked for (exploratory).""" print("== 9. Added after the fresh review (exploratory)") out = res.setdefault("fixround", {}) # stations' own trends since 1979 since = {} for st in STATIONS: ys = [y for y in sorted(series[st]) if y >= 1979] if len(ys) >= 10: since[st] = window(ys, [series[st][y] for y in ys], 1979, max(ys)) sig = [st for st, t in since.items() if t["hi"] is not None and t["hi"] < 0] print(" station trends since 1979: " + "; ".join(f"{st} {fmt(t, 3)}" for st, t in since.items())) print(f" significant falls since 1979: {len(sig)} of {len(since)}: {', '.join(sig)}") out["stations_since1979"] = since # Marshall's sites, like for like pts = read_csv(os.path.join(derived, "r1_slp_points_annual.csv")) for lat, fn in ((65, "l65.1957.2007.txt"), (40, "l40.1957.2007.txt")): st = annual(read_marshall_monthly(os.path.join(inputs, "bas-sam", fn))) ys = [y for y in pts["year"] if y in st and 1957 <= y <= 2025] r = [pts[f"sites_mean_{lat}S"][pts["year"].index(y)] for y in ys] s = [st[y] for y in ys] d = [ri - si for ri, si in zip(r, s)] row = {} for a, b in ((1957, 2025), (1957, 1978), (1979, 2025)): row[f"{a}-{b}"] = {"stations": window(ys, s, a, b), "r1_sites": window(ys, r, a, b), "sites_minus_stations": window(ys, d, a, b)} x = row[f"{a}-{b}"] print(f" {lat} S at Marshall's sites, {a}-{b}: stations {fmt(x['stations'], 3)}; R1 {fmt(x['r1_sites'], 3)}; " f"R1 minus stations {fmt(x['sites_minus_stations'], 3)}") pre = statistics.mean(v for y, v in zip(ys, d) if y <= 1978) post = statistics.mean(v for y, v in zip(ys, d) if y >= 1979) row["levels"] = [pre, post] print(f" level of R1 minus stations: {pre:+.2f} (1957-1978), {post:+.2f} (1979-2025); " f"before 1979 on 1979-2025 baselines {pre - post:+.2f}; ratio of full-period trends " f"{row['1957-2025']['r1_sites']['slope'] / row['1957-2025']['stations']['slope']:.2f}") out[f"sites_{lat}S"] = row r1z = read_csv(os.path.join(derived, "r1_slp_zonal_annual.csv")) for lat in (65, 40): ys = [y for y in pts["year"] if y in r1z["year"] and 1957 <= y <= 2025] lev = statistics.mean(pts[f"sites_mean_{lat}S"][pts["year"].index(y)] - r1z[f"r1_slp_{lat}S"][r1z["year"].index(y)] for y in ys) out[f"sites_minus_circle_{lat}S"] = lev print(f" {lat} S: R1 at the six sites minus R1's whole circle, mean 1957-2025: {lev:+.2f} hPa") b = res["bound"]["1979-2015"] vap = (min(b["B2_r1"]["lo"], b["B2_cc"][0]), max(b["B2_r1"]["hi"], b["B2_cc"][1])) out["vapour_bound_1979_2015"] = vap print(f" the bound's water-vapour part alone, 1979-2015: {vap[0]:+.4f} to {vap[1]:+.4f}") # Eureka's and Resolute's reports for name, sub, first, last in (("Eureka", "eureka", 1973, 1985), ("Resolute Bay", "resolute", 1976, 1978)): files = sorted(f for f in glob.glob(os.path.join(inputs, "noaa-isd", sub, "*.gz")) if first <= int(os.path.basename(f)[13:17]) <= last) if not files: print(f" {name}: no files in {sub}/ (fetch_inputs.py --small fetches them)") continue mon, alt_d, elev = {}, {}, {} for fid, date, el, slp, alt, stp in isd_reports(files): y, m = int(date[:4]), int(date[4:6]) elev.setdefault(y, {}).setdefault(el, 0) elev[y][el] += 1 if slp is not None and stp is not None and 1976 <= y <= 1978: mon.setdefault((y, m, fid), []).append(stp - slp) if alt is not None and stp is not None and slp is not None: alt_d.setdefault(y, []).append((alt - stp, alt - slp)) print(f" {name}: monthly station minus sea-level pressure, 1976-1978 (file, mean, reports): " + " ".join(f"{y}-{m:02d}:{fid[:6]}:{statistics.mean(v):+.2f}:{len(v)}" for (y, m, fid), v in sorted(mon.items()))) if name == "Eureka": print(" Eureka altimeter minus station, and minus sea level, by year: " + " ".join(f"{y}:{statistics.mean(a for a, _ in v):+.2f}/{statistics.mean(b for _, b in v):+.2f}" for y, v in sorted(alt_d.items()))) print(f" {name} elevations written in the reports: " + " ".join(f"{y}:{','.join(f'{k.strip()}x{n}' for k, n in sorted(v.items()))}" for y, v in sorted(elev.items()))) out[f"{sub}_monthly"] = {f"{y}-{m:02d} {fid}": statistics.mean(v) for (y, m, fid), v in mon.items()} # Eureka's sea-level series with a step removed, and the step against five reanalysis series slp = isd["slp"] ys = [y for y in sorted(slp) if 1951 <= y <= 2024] for step in (0.2, 0.5): t = window(ys, [slp[y] - (step if y >= 1977 else 0.0) for y in ys], 1951, 2024) out[f"eureka_slp_minus_{step}"] = t print(f" Eureka sea level with a +{step} hPa step from 1977 removed: {fmt(t, 3)}") rean = {"R1 sea-level pressure": {y: v for y, v in zip(pts["year"], pts["Eureka"])}} for p, lab in (("r1", "R1 surface (2.5 deg)"), ("r1g", "R1 surface (Gaussian)"), ("jra55", "JRA-55 surface"), ("c20v3", "20CRv3 surface")): c = read_csv(os.path.join(derived, f"station_points_annual_{p}.csv")) rean[lab] = {y: v for y, v in zip(c["year"], c["Eureka"]) if v is not None} out["eureka_steps"] = {} for sname, ser in (("station", isd["stp"]), ("sea level", isd["slp"])): for rname, rv in rean.items(): cy = [y for y in sorted(ser) if 1951 <= y <= 2024 and y in rv] s = [ser[y] for y in cy] r = [rv[y] for y in cy] k = statistics.mean(s) / statistics.mean(r) sm, rm = statistics.mean(s), statistics.mean(r) d = [(si - sm) - k * (ri - rm) for si, ri in zip(s, r)] means = (statistics.mean(v for y, v in zip(cy, d) if y >= 1977) - statistics.mean(v for y, v in zip(cy, d) if y <= 1976)) X = [[1.0, (y - 1977) / 10.0, 1.0 if y >= 1977 else 0.0] for y in cy] beta, inv = solve3(X, d) e = [v - sum(bj * xj for bj, xj in zip(beta, x)) for v, x in zip(d, X)] n = len(cy) r1 = sum(e[i] * e[i + 1] for i in range(n - 1)) / sum(v * v for v in e) rr = max(r1, 0.0) neff = n * (1 - rr) / (1 + rr) se = math.sqrt(sum(v * v for v in e) / (neff - 3) * inv[2][2]) crit = t_ppf975(neff - 3) out["eureka_steps"][f"{sname} vs {rname}"] = {"means": means, "with_drift": beta[2], "lo": beta[2] - crit * se, "hi": beta[2] + crit * se, "difference_trend": trend(cy, d)} print(f" Eureka {sname:9s} step against {rname:22s}: means {means:+.2f}; with drift {beta[2]:+.2f} " f"[{beta[2] - crit * se:+.2f}, {beta[2] + crit * se:+.2f}]; ISD minus reanalysis trend {fmt(trend(cy, d), 3)}") r1slp, r1sfc = rean["R1 sea-level pressure"], rean["R1 surface (2.5 deg)"] ys = [y for y in sorted(r1slp) if 1951 <= y <= 2024] print(f" R1 at Eureka 1951-2024: sea-level pressure {fmt(window(ys, [r1slp[y] for y in ys], 1951, 2024), 3)}, " f"mean {statistics.mean(r1slp[y] for y in ys):.1f}; surface pressure " f"{fmt(window(ys, [r1sfc[y] for y in ys], 1951, 2024), 3)}, mean {statistics.mean(r1sfc[y] for y in ys):.1f}") # windows: the note's interval method, fixed 30-year windows and the slopes' signs trio = ("r1g", "jra55", "c20v3") cnt = {"M1": [0, 0], "M6": [0, 0]} neg_all = neg_late = 0 fixed = [] for s in range(1958, 1987): for e in range(s + 29, 2016): for meth in ("M1", "M6"): tp = [window(bands[p]["year"], bands[p]["polar"], s, e, meth) for p in trio] tt = [window(bands[p]["year"], bands[p]["tropical"], s, e, meth) for p in trio] cnt[meth][0] += all(t["hi"] < 0 for t in tp) cnt[meth][1] += all(t["lo"] > 0 for t in tt) if meth == "M1": if all(t["slope"] < 0 for t in tp): neg_all += 1 neg_late += s >= 1973 if e == s + 29: fixed.append((s, all(t["hi"] < 0 for t in tp))) print(f" windows, all three polar below zero: M1 {cnt['M1'][0]}, M6 {cnt['M6'][0]}; all three tropical above " f"zero: M1 {cnt['M1'][1]}, M6 {cnt['M6'][1]}; all three polar slopes negative: {neg_all} of 435, " f"{neg_late} of the 105 starting 1973 or later") print(" fixed 30-year windows, all three polar below zero: " + " ".join(f"{s}:{'Y' if ok else '-'}" for s, ok in fixed)) big = 0.0 for p in trio: for band in ("polar", "tropical", "antarctic", "arctic"): a, b = FULL[p] t1 = window(bands[p]["year"], bands[p][band], a, b) t6 = window(bands[p]["year"], bands[p][band], a, b, "M6") big = max(big, abs(t1["lo"] - t6["lo"]), abs(t1["hi"] - t6["hi"])) print(f" largest M1-M6 difference in the 12 full-record band intervals: {big:.4f}") out["windows"] = {"counts": cnt, "slopes_negative": [neg_all, neg_late], "fixed_30": fixed, "band_m1_m6": big} # dry air, the polar scatter, 20CRv3's Arctic share bud = read_csv(os.path.join(derived, "annual_global_r1g_budget.csv")) bud25 = read_csv(os.path.join(derived, "annual_global_r1_budget.csv")) for lab, bb, a, b in (("Gaussian", bud, 2001, 2025), ("2.5 deg", bud25, 1979, 2025)): t = window(bb["year"], bb["dry_hPa"], a, b) out[f"dry_{lab}_{a}_{b}"] = t print(f" R1 dry air ({lab}) {a}-{b}: {fmt(t)}") y, v = bands["r1g"]["year"], bands["r1g"]["polar"] n, sxx, b, a0, e = ols(y, v) sd = math.sqrt(sum(x * x for x in e) / (n - 2)) print(f" R1 polar 1948-2025: fall {-b * 77:.2f} hPa; detrended standard deviation {sd:.2f} hPa") ta = window(bands["c20v3"]["year"], bands["c20v3"]["arctic"], 1806, 2015) tq = window(bands["c20v3"]["year"], bands["c20v3"]["polar"], 1806, 2015) print(f" 20CRv3 1806-2015: Arctic share of the polar fall {ta['slope'] / 2 / tq['slope']:.2f}") out["r1g_polar_sd"] = sd out["c20v3_arctic_share"] = ta["slope"] / 2 / tq["slope"] if __name__ == "__main__": here = os.path.dirname(os.path.abspath(__file__)) main(sys.argv[1], sys.argv[2] if len(sys.argv) > 2 else here, sys.argv[3] if len(sys.argv) > 3 else os.path.join(sys.argv[1], "stdlib_check.json"))