#!/usr/bin/env python3 """Repeat the numbers on https://factchecked.science/vietnam-upwelling-1999/ from public data. It rebuilds the Southern Coastal Upwelling index (SCUI) of Ngo, Hsin & Wu (2026, Geophysical Research Letters 53, e2026GL126805, doi:10.1029/2026GL126805, CC BY-NC 4.0) from NOAA OISST v2.1, then tests it: one trend against two, a scan of the break year, the first three summers, the summer of 1998, the paper's own recipe for choosing 1999, its EOF modes, the water beside the cold box, the split of the 2011 step, and other SST and wind products. All the inputs are public and need no account; each is fetched from its source by URL into one folder, and its address and SHA-256 are written to the output. python3 scui_rerun.py [folder] [--out DIR] [--pylib DIR] [--no-recipe] folder where inputs are kept (default: scui-data beside this script). A second run reuses them. --out where scui-numbers.json and scui-reproduced.csv go (default: the folder). --pylib an extra folder to find PyEMD in, added after the usual places. --no-recipe skip the simulations of the recipe and of its chance test. Needs numpy, scipy and netCDF4 (with OPeNDAP, as the PyPI wheels have it). The steps with the paper's Hilbert-Huang curve also need PyEMD (`pip install EMD-signal`); without it they are skipped, and the output says so. About 240 MB of inputs. If a server is down, the other SST products (not OISST, the bathymetry or the indices) are skipped for that run, and the output says so; run it again later. What is not recomputed here: ERA5 and ORAS5, which need an account, so winds are NCEP/NCAR R1 and NCEP-DOE R2; and the two lists FIG1A_READ and FIG1A_CURVE below, which are values read off the image of the paper's Figure 1a with a script (accuracy about 0.02 degC), used only for comparison. Figure S1, which shows the paper's Tref area, was not seen; our area is the polygon POLY below, deeper than 500 m. This script doesn't repeat our search over Tref's areas, the check of PSL against NCEI's daily files, the count of CoastWatch's days, the reading of values off the figures, or our test of how liberal the bootstraps run; those were done separately. We take OISST's monthly means from NOAA PSL, the source the paper's data statement names. June-September means from them differ from means of NCEI's daily files by at most 0.002 degC in SCUI. (CoastWatch ERDDAP's aggregated ncdcOisst21Agg lacks about half the days of 1993-1998, so we don't use it.) """ import argparse import csv import hashlib import json import math import os import re import sys import time import urllib.error import urllib.request import warnings from pathlib import Path import netCDF4 import numpy as np from scipy import stats warnings.filterwarnings("ignore") try: sys.stdout.reconfigure(encoding="utf-8") except AttributeError: pass YEARS = np.arange(1982, 2025) POLY = [(105, 5), (105, 23), (120.5, 23), (120.5, 18.5), (120, 14), (119.5, 11.4), (117.2, 8.3), (116.8, 7), (115, 5)] FIG1A_READ = [2.08, 1.61, 2.11, 1.15, 1.38, 0.64, 1.03, 0.95, 0.95, 0.84, 0.80, 1.15, 1.35, 0.57, 1.04, 1.51, 0.85, 1.46, 1.04, 0.84, 0.85, 1.12, 1.53, 0.98, 1.16, 0.98, 1.43, 1.35, 0.67, 1.99, 1.90, 1.34, 2.20, 2.03, 1.93, 1.45, 1.82, 1.36, 0.90, 1.58, 1.38, 2.21, 1.23] FIG1A_CURVE = [1.26, 1.25, 1.25, 1.24, 1.22, 1.21, 1.19, 1.17, 1.15, 1.13, 1.11, 1.10, 1.08, 1.07, 1.05, 1.05, 1.04, 1.05, 1.05, 1.06, 1.08, 1.11, 1.14, 1.17, 1.20, 1.24, 1.28, 1.32, 1.37, 1.41, 1.44, 1.48, 1.51, 1.54, 1.56, 1.58, 1.59, 1.60, 1.59, 1.59, 1.58, 1.56, 1.54] ERD = "https://coastwatch.pfeg.noaa.gov/erddap/griddap/" PSL_DAP = "https://psl.noaa.gov/thredds/dodsC/Datasets/" INPUTS = {} def log(*a): print(*a, flush=True) # ------------------------------------------------------------------ fetching def sha256(path): h = hashlib.sha256() with open(path, "rb") as f: for b in iter(lambda: f.read(1 << 20), b""): h.update(b) return h.hexdigest() def note_input(name, url, path): INPUTS[name] = {"url": url, "bytes": os.path.getsize(path), "sha256": sha256(path)} def get(url, path, name=None, tries=5, optional=False): """Fetch once into the folder. An optional product that its server won't give up is skipped, and the output says so.""" path = str(path) if not (os.path.exists(path) and os.path.getsize(path) > 1000): for a in range(tries): try: req = urllib.request.Request(url, headers={"User-Agent": "factchecked-research/1.0"}) with urllib.request.urlopen(req, timeout=900) as r, open(path + ".part", "wb") as f: while True: b = r.read(1 << 20) if not b: break f.write(b) os.replace(path + ".part", path) break except (urllib.error.URLError, OSError) as e: log(" retry", os.path.basename(path), repr(e)[:80]) time.sleep(15 * (a + 1)) else: if optional: log(" skipping", name or os.path.basename(path), "for now: its server did not answer") INPUTS[name or os.path.basename(path)] = {"url": url, "note": "not fetched in this run"} return None raise SystemExit(f"could not fetch {url}") note_input(name or os.path.basename(path), url, path) return path def q(s): return urllib.request.quote(s, safe="[]():,=-.TZ") def fetch_oisst(folder): """June-September monthly means, 1982-2024: Indo-Pacific at 0.25 deg; the tropical band at 1 deg; near-global at 2 deg, from PSL by OPeNDAP.""" url = PSL_DAP + "noaa.oisst.v2.highres/sst.mon.mean.nc" out = os.path.join(folder, "psl_oisst_jjas.npz") if not os.path.exists(out): log("reading OISST v2.1 monthly means from PSL by OPeNDAP") d = netCDF4.Dataset(url) lat = np.array(d["lat"][:], float) lon = np.array(d["lon"][:], float) tt = netCDF4.num2date(d["time"][:], d["time"].units) idx = {(x.year, x.month): i for i, x in enumerate(tt)} j_ip = np.where((lat >= -15) & (lat <= 25))[0] i_ip = np.where((lon >= 90) & (lon <= 140))[0] i_tp = np.where((lon >= 90) & (lon <= 280))[0] j_gl = np.where((lat >= -60) & (lat <= 60))[0] def read(t, ja, ia0, ia1, stride): """One month's slice, checked, because a remote read can come back with holes in it.""" for a in range(6): try: v = np.ma.filled(d["sst"][t, ja[0]:ja[-1] + 1:stride, ia0:ia1 + 1:stride].astype("f4"), np.nan) ok = np.isfinite(v) if ok.mean() > 0.4 and (v[ok] == 0).mean() < 0.01 and -3 < np.nanmin(v) and np.nanmax(v) < 45: return v log(" a slice failed its check; reading it again") except Exception as e: # a dropped connection log(" retry", repr(e)[:80]) time.sleep(10 * (a + 1)) raise SystemExit("cannot read OISST from PSL") ip, tp, gl = [], [], [] for y in YEARS: months = [idx[(int(y), m)] for m in (6, 7, 8, 9)] ip.append(np.stack([read(t, j_ip, i_ip[0], i_ip[-1], 1) for t in months])) tp.append(np.stack([read(t, j_ip, i_tp[0], i_tp[-1], 4) for t in months])) gl.append(np.stack([read(t, j_gl, 0, 1439, 8) for t in months])) np.savez_compressed(out, ip=np.stack(ip), ip_lat=lat[j_ip], ip_lon=lon[i_ip], tp=np.stack(tp), tp_lat=lat[j_ip[::4]], tp_lon=lon[i_tp[::4]], gl=np.stack(gl), gl_lat=lat[j_gl[::8]], gl_lon=lon[::8]) INPUTS["OISST v2.1 monthly (our cut, OPeNDAP)"] = {"url": url, "bytes": os.path.getsize(out), "note": "June-September 1982-2024; a cut made by this script, so its hash is not given"} return np.load(out) def fetch_winds(folder): """NCEP/NCAR R1 (sig995) and NCEP-DOE R2 (10 m) monthly means from PSL, whole files, about 115 MB. Their hashes change as PSL adds months.""" base = "https://downloads.psl.noaa.gov/Datasets/" urls = {"R1": ("ncep.reanalysis.derived/surface/uwnd.mon.mean.nc", "ncep.reanalysis.derived/surface/vwnd.mon.mean.nc"), "R2": ("ncep.reanalysis2.derived/gaussian_grid/uwnd.10m.mon.mean.nc", "ncep.reanalysis2.derived/gaussian_grid/vwnd.10m.mon.mean.nc")} data = {} for nm, (fu, fv) in urls.items(): pu = get(base + fu, os.path.join(folder, f"{nm.lower()}_u.nc"), f"NCEP {nm} u") pv = get(base + fv, os.path.join(folder, f"{nm.lower()}_v.nc"), f"NCEP {nm} v") with netCDF4.Dataset(pu) as du, netCDF4.Dataset(pv) as dv: lat = np.array(du["lat"][:], float) lon = np.array(du["lon"][:], float) tt = netCDF4.num2date(du["time"][:], du["time"].units) yy = np.array([x.year for x in tt]) k = np.where((yy >= 1982) & (yy <= 2024))[0] ja = np.where((lat >= -15) & (lat <= 25))[0] ia = np.where((lon >= 90) & (lon <= 245))[0] u = np.ma.filled(du["uwnd"][k[0]:k[-1] + 1, ...].astype("f8"), np.nan).squeeze()[:, ja[0]:ja[-1] + 1, ia[0]:ia[-1] + 1] v = np.ma.filled(dv["vwnd"][k[0]:k[-1] + 1, ...].astype("f8"), np.nan).squeeze()[:, ja[0]:ja[-1] + 1, ia[0]:ia[-1] + 1] la = lat[ja] if la[0] > la[-1]: la = la[::-1] u, v = u[:, ::-1, :], v[:, ::-1, :] data[nm + "_u"], data[nm + "_v"], data[nm + "_lat"], data[nm + "_lon"] = u, v, la, lon[ia] data[nm + "_yy"] = yy[k] data[nm + "_mm"] = np.array([tt[i].month for i in k]) return data def fetch_rest(folder): f = Path(folder) p = {} p["etopo"] = get(ERD + "etopo180.nc?" + q("altitude[(3.0):1:(25.0)][(104.0):1:(123.0)]"), f / "etopo1_scs.nc", "ETOPO1 subset (ERDDAP etopo180)") p["oni"] = get("https://www.cpc.ncep.noaa.gov/data/indices/oni.ascii.txt", f / "oni.ascii.txt", "ONI") p["n34"] = get("https://psl.noaa.gov/data/correlation/nina34.anom.data", f / "nina34.anom.data", "Nino 3.4") p["pdo"] = get("https://www.ncei.noaa.gov/pub/data/cmb/ersst/v5/index/ersst.v5.pdo.dat", f / "ersst.v5.pdo.dat", "PDO") p["amo"] = get("https://www.ncei.noaa.gov/pub/data/cmb/ersst/v5/index/ersst.v5.amo.dat", f / "ersst.v5.amo.dat", "AMO") p["tpi"] = get("https://psl.noaa.gov/data/timeseries/IPOTPI/tpi.timeseries.ersstv5.data", f / "tpi.timeseries.ersstv5.data", "Tripole Index") p["had"] = get(ERD + "erdHadISST.nc?" + q("sst[(1982-01-16T12:00:00Z):1:(2024-12-16T12:00:00Z)][(25.5):1:(2.5)][(103.5):1:(123.5)]"), f / "hadisst_scs.nc", "HadISST subset", optional=True) p["ers"] = get(ERD + "nceiErsstv5.nc?" + q("sst[(1982-01-01T00:00:00Z):1:(2024-12-01T00:00:00Z)][(0.0):1:(0.0)][(2.0):1:(26.0)][(102.0):1:(124.0)]"), f / "ersstv5_scs.nc", "ERSSTv5 subset", optional=True) t0, t1 = (1982 - 1850) * 12, (2024 - 1850) * 12 + 11 p["cobe"] = get(PSL_DAP + f"COBE2/sst.mon.mean.nc.ascii?sst[{t0}:1:{t1}][64:1:87][103:1:123],lat[64:1:87],lon[103:1:123],time[{t0}:1:{t1}]", f / "cobe2_scs.ascii", "COBE-SST2 subset", optional=True) p["mur_box"] = get(ERD + "jplMURSST41mday.nc?" + q("sst[(2002-06-16T00:00:00Z):1:(2024-12-16T00:00:00Z)][(9.0):5:(13.5)][(107.5):5:(112.0)]"), f / "mur_box.nc", "MUR 4.1, cold box", optional=True) p["mur_bas"] = get(ERD + "jplMURSST41mday.nc?" + q("sst[(2002-06-16T00:00:00Z):1:(2024-12-16T00:00:00Z)][(3.125):25:(24.875)][(104.125):25:(122.875)]"), f / "mur_basin.nc", "MUR 4.1, basin", optional=True) p["pf_box"] = get(ERD + "erdPH53sstdmday.nc?" + q("sea_surface_temperature[(1982-01-16T00:00:00Z):1:(2023-06-16T00:00:00Z)][(13.5):1:(9.0)][(107.5):1:(112.0)]"), f / "ph53_box.nc", "Pathfinder 5.3, cold box", optional=True) p["pf_bas"] = get(ERD + "erdPH53sstdmday.nc?" + q("sea_surface_temperature[(1982-01-16T00:00:00Z):1:(2023-06-16T00:00:00Z)][(25.0):6:(3.0)][(104.0):6:(123.0)]"), f / "ph53_basin.nc", "Pathfinder 5.3, basin", optional=True) return p # ------------------------------------------------------------------ statistics SCAN = list(range(1990, 2015)) MINSEG = 8 def dm(model, t, b=None): t = np.asarray(t, float) c = t - t.mean() if model == "M1": return np.column_stack([np.ones_like(t), c]) if model == "M2": # continuous hinge at b return np.column_stack([np.ones_like(t), c, np.maximum(0.0, t - b)]) if model == "M3": # two separate lines, t < b and t >= b s = (t >= b).astype(float) return np.column_stack([1 - s, (1 - s) * (t - b), s, s * (t - b)]) if model == "M4": # quadratic return np.column_stack([np.ones_like(t), c, c ** 2]) if model == "M5": # one step in the mean return np.column_stack([np.ones_like(t), (t >= b).astype(float)]) raise ValueError(model) def ols(X, y): beta, *_ = np.linalg.lstsq(X, y, rcond=None) e = y - X @ beta return beta, e, float((e ** 2).sum()) def lag1(e): d = (e ** 2).sum() return float((e[:-1] * e[1:]).sum() / d) if d > 0 else 0.0 def neff(n, r1): return float(n) if r1 <= 0 else min(float(n), n * (1 - r1) / (1 + r1)) def slope_ci(t, y, X=None, contrast=None, r1=None, n_seg=None): """Slope with white-noise and AR(1) 95% half-widths, the AR(1) one using N_eff = n(1-r1)/(1+r1) in both the error and the t quantile.""" t, y = np.asarray(t, float), np.asarray(y, float) if X is None: X, contrast = dm("M1", t), np.array([0.0, 1.0]) beta, e, sse = ols(X, y) n, k = X.shape cov = sse / (n - k) * np.linalg.pinv(X.T @ X) est = float(contrast @ beta) se = float(math.sqrt(contrast @ cov @ contrast)) r = lag1(e) if r1 is None else r1 nn = n if n_seg is None else n_seg ne = neff(nn, r) kk = 2 if n_seg is not None else k dof_w, dof_a = max(nn - kk, 1), max(ne - kk, 1.0) return {"slope": est, "hw_white": float(se * stats.t.ppf(0.975, dof_w)), "hw_ar1": float(se * math.sqrt(dof_w / dof_a) * stats.t.ppf(0.975, dof_a)), "r1": float(r)} def aicc(sse, n, k_lin, extra=0): k = k_lin + extra + 1 return n * math.log(sse / n) + 2 * k + 2 * k * (k + 1) / (n - k - 1) def ar1_draws(n, r1, sigma, nboot, rng): r = max(min(r1, 0.95), -0.95) inn = rng.normal(0, sigma * math.sqrt(1 - r ** 2), (nboot, n)) z = np.zeros((nboot, n)) z[:, 0] = rng.normal(0, sigma, nboot) for i in range(1, n): z[:, i] = r * z[:, i - 1] + inn[:, i] return z def proj_q(X): return np.linalg.qr(X)[0] def sse_many(q_, Y): c = Y @ q_ return (Y ** 2).sum(axis=1) - (c ** 2).sum(axis=1) def pval(obs, null): return float((1 + (null >= obs).sum()) / (1 + len(null))) def analyse(t, y, fixed=1999, nboot=10000, nboot_break=5000, seed=1999, scan=SCAN, minseg=MINSEG): """Line, hinge and two lines at `fixed`; scans of the break year; a parametric AR(1) bootstrap under the line for the tests, repeated search included.""" t, y = np.asarray(t, float), np.asarray(y, float) n = len(t) rng = np.random.default_rng(seed) years = [b for b in scan if (t < b).sum() >= minseg and (t >= b).sum() >= minseg] X1 = dm("M1", t) b1, e1, sse1 = ols(X1, y) r1_m1 = lag1(e1) sd1 = float(np.sqrt(sse1 / (n - 2))) out = {"n": n, "t0": int(t[0]), "t1": int(t[-1]), "line": slope_ci(t, y), "line_r1": r1_m1, "sse_line": sse1} def m2(b): X = dm("M2", t, b) _, e, sse = ols(X, y) r = lag1(e) return {"b": b, "sse": sse, "r1": r, "before": slope_ci(t, y, X, np.array([0.0, 1.0, 0.0]), r1=r), "after": slope_ci(t, y, X, np.array([0.0, 1.0, 1.0]), r1=r)} def m3(b): X = dm("M3", t, b) _, e, sse = ols(X, y) r = lag1(e) return {"b": b, "sse": sse, "r1": r, "before": slope_ci(t, y, X, np.array([0.0, 1.0, 0.0, 0.0]), r1=r, n_seg=int((t < b).sum())), "after": slope_ci(t, y, X, np.array([0.0, 0.0, 0.0, 1.0]), r1=r, n_seg=int((t >= b).sum()))} out["hinge_fixed"], out["two_lines_fixed"] = m2(fixed), m3(fixed) prof2 = {b: ols(dm("M2", t, b), y)[2] for b in years} prof3 = {b: ols(dm("M3", t, b), y)[2] for b in years} prof5 = {b: ols(dm("M5", t, b), y)[2] for b in years} b2, b3, b5 = min(prof2, key=prof2.get), min(prof3, key=prof3.get), min(prof5, key=prof5.get) out["hinge_best"], out["two_lines_best"], out["step_best"] = m2(b2), m3(b3), {"b": b5, "sse": prof5[b5]} beta4, _, sse4 = ols(dm("M4", t), y) out["quadratic_min_year"] = float(t.mean() - beta4[1] / (2 * beta4[2])) def fstat(s0, s1, q_, k): return ((s0 - s1) / q_) / (s1 / (n - k)) Y0 = (X1 @ b1)[None, :] + ar1_draws(n, r1_m1, sd1, nboot, rng) s0 = sse_many(proj_q(X1), Y0) q2 = {b: proj_q(dm("M2", t, b)) for b in years} q3 = {b: proj_q(dm("M3", t, b)) for b in years} S2 = np.column_stack([sse_many(q2[b], Y0) for b in years]) S3 = np.column_stack([sse_many(q3[b], Y0) for b in years]) sf2, sf3 = sse_many(proj_q(dm("M2", t, fixed)), Y0), sse_many(proj_q(dm("M3", t, fixed)), Y0) F2f, F3f = (s0 - sf2) / (sf2 / (n - 3)), ((s0 - sf3) / 2) / (sf3 / (n - 4)) sup2_null, sup3_null = ((s0[:, None] - S2) / (S2 / (n - 3))).max(axis=1), (((s0[:, None] - S3) / 2) / (S3 / (n - 4))).max(axis=1) out["tests"] = { "p_hinge_fixed": pval(fstat(sse1, out["hinge_fixed"]["sse"], 1, 3), F2f), "p_two_lines_fixed": pval(fstat(sse1, out["two_lines_fixed"]["sse"], 2, 4), F3f), "p_supF_hinge": pval(max(fstat(sse1, prof2[b], 1, 3) for b in years), sup2_null), "p_supF_two_lines": pval(max(fstat(sse1, prof3[b], 2, 4) for b in years), sup3_null)} def boot(model, b_best, qmap): X = dm(model, t, b_best) beta, e, sse = ols(X, y) k = X.shape[1] + 1 Y = (X @ beta)[None, :] + ar1_draws(n, lag1(e), float(np.sqrt(sse / (n - k))), nboot_break, rng) best = np.array(years)[np.column_stack([sse_many(qmap[b], Y) for b in years]).argmin(axis=1)] return {"p2.5": float(np.percentile(best, 2.5)), "p97.5": float(np.percentile(best, 97.5)), "share_1996_2002": float(((best >= 1996) & (best <= 2002)).mean())} out["hinge_boot"], out["two_lines_boot"] = boot("M2", b2, q2), boot("M3", b3, q3) def prof_int(prof, b_best, k, model): r = lag1(ols(dm(model, t, b_best), y)[1]) dof = max(neff(n, r) - k, 1.0) cut = prof[b_best] * (1 + stats.f.ppf(0.95, 1, dof) / dof) return [b for b in years if prof[b] <= cut] out["hinge_profile_years"], out["two_lines_profile_years"] = prof_int(prof2, b2, 4, "M2"), prof_int(prof3, b3, 5, "M3") bf = out["hinge_fixed"] out["criteria"] = {"fixed_p_lt_05": out["tests"]["p_hinge_fixed"] < 0.05, "search_p_lt_05": out["tests"]["p_supF_hinge"] < 0.05, "best_year_in_1996_2002": 1996 <= b2 <= 2002, "before_clear_negative": bf["before"]["slope"] + bf["before"]["hw_ar1"] < 0, "after_clear_positive": bf["after"]["slope"] - bf["after"]["hw_ar1"] > 0} return out def brief(a): h, s, t = a["hinge_fixed"], a["two_lines_fixed"], a["tests"] return (f"{a['t0']}-{a['t1']} n={a['n']} | line {a['line']['slope'] * 10:+.2f}±{a['line']['hw_ar1'] * 10:.2f} | hinge@1999 {h['before']['slope'] * 10:+.2f}±{h['before']['hw_ar1'] * 10:.2f} {h['after']['slope'] * 10:+.2f}±{h['after']['hw_ar1'] * 10:.2f} " f"p={t['p_hinge_fixed']:.3f} | two lines {s['before']['slope'] * 10:+.2f}±{s['before']['hw_ar1'] * 10:.2f} {s['after']['slope'] * 10:+.2f}±{s['after']['hw_ar1'] * 10:.2f} p={t['p_two_lines_fixed']:.3f} | " f"best hinge {a['hinge_best']['b']} ({a['hinge_boot']['p2.5']:.0f}-{a['hinge_boot']['p97.5']:.0f}, profile {a['hinge_profile_years'][0] if a['hinge_profile_years'] else ''}-{a['hinge_profile_years'][-1] if a['hinge_profile_years'] else ''}, in 96-02 {a['hinge_boot']['share_1996_2002']:.3f}) supF p={t['p_supF_hinge']:.3f} | best two-line {a['two_lines_best']['b']} step {a['step_best']['b']}") def plain(t, y): r = stats.linregress(t, y) return {"slope": float(r.slope), "p": float(r.pvalue)} def periods(y, yrs=YEARS): return {"1982-2024": plain(yrs, y), "B99": plain(yrs[yrs <= 1998], y[yrs <= 1998]), "A99": plain(yrs[yrs >= 1999], y[yrs >= 1999])} def trend(yrs, y): """A slope with its AR(1) half-width and Student's p.""" c = slope_ci(yrs, y) return {"slope": c["slope"], "hw_ar1": c["hw_ar1"], "p": plain(yrs, y)["p"]} def local_contrast(C, mask, hw): """Each year, the strongest local contrast in the box: how far a cell's SST lies below the mean water in a square window around it, 2 hw + 1 cells a side. Also the same at that year's coldest cell. C is years x lat x lon, with land as NaN.""" J, I = np.where(mask) strongest, at_coldest = [], [] for f in C: vals = np.array([f[j, i] - np.nanmean(f[max(j - hw, 0):j + hw + 1, max(i - hw, 0):i + hw + 1]) for j, i in zip(J, I)]) temps = f[J, I] strongest.append(-np.nanmin(vals)) at_coldest.append(-vals[int(np.nanargmin(temps))]) return np.array(strongest), np.array(at_coldest) def windows_of(yrs, y): """Trends over the periods the page talks about, as far as the series reaches.""" out = {} for lab, a_, b_ in (("1982-2024", 1982, 2024), ("B99", 1982, 1998), ("A99", 1999, 2024), ("1982-2020", 1982, 2020), ("1985-2024", 1985, 2024), ("2002-2024", 2002, 2024)): k = (yrs >= a_) & (yrs <= b_) if yrs[0] <= a_ and yrs[-1] >= b_: out[lab] = trend(yrs[k], y[k]) return out def beside_box(yrs, tr, tm, water, C, mask): """Where the index's rise lies: the basin, the water beside the cold box, the cold cell, the two differences, and local contrasts. Post hoc.""" s = tr - tm out = {"Tref": windows_of(yrs, tr), "water": windows_of(yrs, water), "Tmin": windows_of(yrs, tm), "SCUI": windows_of(yrs, s), "Tref_minus_water": windows_of(yrs, tr - water), "water_minus_Tmin": windows_of(yrs, water - tm)} out["share_of_SCUI_slope"] = {k: out["water_minus_Tmin"][k]["slope"] / out["SCUI"][k]["slope"] for k in out["SCUI"]} out["r_water_minus_Tmin_with_SCUI"] = r_(water - tm, s) out["r_Tref_with_water"] = r_(tr, water) out["mean_Tref_minus_water"] = float((tr - water).mean()) for hw, lab in ((2, "5x5"), (3, "7x7")): a_, b_ = local_contrast(C, mask, hw) lv = {f"{p0}-{p1}": float(a_[(yrs >= p0) & (yrs <= p1)].mean()) for p0, p1 in ((1982, 1984), (1985, 2010), (2002, 2010), (2011, 2024)) if ((yrs >= p0) & (yrs <= p1)).sum() >= 2 and yrs[0] <= p0} out[f"local_{lab}"] = {**windows_of(yrs, a_), "levels": lv, "r_with_SCUI": r_(a_, s)} out[f"local_{lab}_at_coldest_cell"] = windows_of(yrs, b_) return out def step_parts(yrs, series, own_level=False): """A line and a step at 2011 through each series, with its own level for 1982-84 if asked. Post hoc.""" yrs = np.asarray(yrs, float) cols = [np.ones_like(yrs), yrs - yrs.mean(), (yrs >= 2011).astype(float)] if own_level: cols.append((yrs <= 1984).astype(float)) X = np.column_stack(cols) con_t, con_s = np.zeros(X.shape[1]), np.zeros(X.shape[1]) con_t[1], con_s[2] = 1.0, 1.0 out = {} for nm, y in series.items(): r = lag1(ols(X, y)[1]) out[nm] = {"slope": slope_ci(yrs, y, X, con_t, r1=r), "step": slope_ci(yrs, y, X, con_s, r1=r)} return out def mean_change(yrs, series, a0, a1, b0, b1): return {nm: float(y[(yrs >= b0) & (yrs <= b1)].mean() - y[(yrs >= a0) & (yrs <= a1)].mean()) for nm, y in series.items()} def dt(x, yrs=YEARS): return x - np.polyval(np.polyfit(yrs, x, 1), yrs) def run(x, n): return np.convolve(x, np.ones(n) / n, mode="valid") def r_(a, b): return float(np.corrcoef(a, b)[0, 1]) def in_poly(x, y, poly): """Ray casting on arrays.""" inside = np.zeros(x.shape, bool) n = len(poly) for i in range(n): x1, y1 = poly[i] x2, y2 = poly[(i + 1) % n] cross = (y1 > y) != (y2 > y) with np.errstate(divide="ignore", invalid="ignore"): xint = (x2 - x1) * (y - y1) / (y2 - y1) + x1 inside ^= cross & (x < xint) return inside # ------------------------------------------------------------------ the index def build_index(oi, etopo): w = np.array([30, 31, 31, 30], float) w /= w.sum() ilat, ilon = oi["ip_lat"], oi["ip_lon"] j = np.where((ilat >= 3) & (ilat <= 25))[0] i = np.where((ilon >= 104) & (ilon <= 123))[0] monthly = oi["ip"][:, :, j][:, :, :, i] F = np.sum(monthly * w[None, :, None, None], axis=1) lat, lon = ilat[j], ilon[i] LON, LAT = np.meshgrid(lon, lat) W = np.cos(np.deg2rad(LAT)) sea = np.isfinite(F).all(axis=0) with netCDF4.Dataset(etopo) as d: ela, elo = np.array(d["latitude"][:], float), np.array(d["longitude"][:], float) alt = np.array(d["altitude"][:], float) dep = np.full(LAT.shape, np.nan) for a, la in enumerate(lat): jj = (ela >= la - 0.125) & (ela < la + 0.125) for b, lo in enumerate(lon): ii = (elo >= lo - 0.125) & (elo < lo + 0.125) dep[a, b] = -alt[np.ix_(jj, ii)].mean() poly = in_poly(LON, LAT, POLY) & sea scu = (LAT >= 10) & (LAT <= 12.5) & (LON >= 107) & (LON <= 110) & sea tref_mask = poly & (dep >= 500) & (LAT >= 5) & (LAT <= 22) tref = np.sum(F[:, tref_mask] * W[tref_mask], axis=1) / W[tref_mask].sum() tmin = np.nanmin(F[:, scu], axis=1) return {"F": F, "lat": lat, "lon": lon, "LAT": LAT, "LON": LON, "W": W, "dep": dep, "poly": poly, "scu": scu, "tref_mask": tref_mask, "Tref": tref, "Tmin": tmin, "SCUI": tref - tmin, "monthly": monthly} # ------------------------------------------------------------------ other SST products def seasonal_nc(fn, var): with netCDF4.Dataset(fn) as d: la, lo = np.array(d["latitude"][:], float), np.array(d["longitude"][:], float) tt = netCDF4.num2date(d["time"][:], d["time"].units) yy, mm = np.array([x.year for x in tt]), np.array([x.month for x in tt]) idx = np.where(np.isin(mm, (6, 7, 8, 9)))[0] arr = np.ma.filled(d[var][idx].astype("f8"), np.nan).squeeze() if np.nanmax(arr) > 200: arr = arr - 273.15 return la, lo, yy[idx], mm[idx], arr def product(ix, boxfn, basfn, var, y0, y1, label, beside=False): """SCUI on a finer product: its pixels block-averaged to OISST's 0.25-deg cells (at least 30% valid), June-September mean of its monthly fields.""" la, lo, yy, mm, box = seasonal_nc(boxfn, var) la2, lo2, yy2, mm2, bas = seasonal_nc(basfn, var) if la2[0] > la2[-1]: la2, bas = la2[::-1], bas[:, ::-1, :] lat, lon, tm_mask, scu = ix["lat"], ix["lon"], ix["tref_mask"], ix["scu"] jm = np.array([np.argmin(np.abs(lat - x)) for x in la2]) im = np.array([np.argmin(np.abs(lon - x)) for x in lo2]) on = tm_mask[np.ix_(jm, im)] w2 = np.cos(np.deg2rad(la2))[:, None] * np.ones((1, lo2.size)) jc, ic = np.floor(la * 4).astype(int), np.floor(lo * 4).astype(int) uj, ui = np.unique(jc), np.unique(ic) clat, clon = (uj + 0.5) / 4, (ui + 0.5) / 4 keep = np.zeros((uj.size, ui.size), bool) for a, cl in enumerate(clat): for b, co in enumerate(clon): j, i = np.argmin(np.abs(lat - cl)), np.argmin(np.abs(lon - co)) keep[a, b] = scu[j, i] and abs(lat[j] - cl) < 0.01 and abs(lon[i] - co) < 0.01 ys, tr, tm, cube = [], [], [], [] for y in range(y0, y1 + 1): k, k2 = yy == y, yy2 == y if k.sum() < 3 or k2.sum() < 3: continue fb = np.nanmean(box[k], axis=0) cells = np.full((uj.size, ui.size), np.nan) for a, u in enumerate(uj): ja = np.where(jc == u)[0] for b, v in enumerate(ui): sub = fb[np.ix_(ja, np.where(ic == v)[0])] if np.isfinite(sub).mean() >= 0.3: cells[a, b] = np.nanmean(sub) vals = cells[keep] if np.isfinite(vals).sum() < 10: continue gb = np.nanmean(bas[k2], axis=0) ok = on & np.isfinite(gb) ys.append(y) tr.append(float(np.sum(gb[ok] * w2[ok]) / np.sum(w2[ok]))) tm.append(float(np.nanmin(vals))) cube.append(cells) ys, tr, tm = np.array(ys), np.array(tr), np.array(tm) s = tr - tm ko = np.isin(YEARS, ys) o_s, o_tr, o_tm = ix["SCUI"][ko], ix["Tref"][ko], ix["Tmin"][ko] out = {"years": ys.tolist(), "SCUI": s.tolist(), "Tref": tr.tolist(), "Tmin": tm.tolist(), "r_SCUI": r_(s, o_s), "r_Tmin": r_(tm, o_tm), "r_Tref": r_(tr, o_tr)} for w0, w1 in ((1982, 1998), (1985, 1998), (1999, 2022), (2002, 2022), (2002, 2024)): k = (ys >= w0) & (ys <= w1) if ys[0] > w0 or ys[-1] < w1: continue out[f"slopes_{w0}_{w1}"] = {nm: {"this": slope_ci(ys[k], v[k]), "oisst": slope_ci(ys[k], ov[k]), "p": plain(ys[k], v[k])["p"]} for nm, v, ov in (("SCUI", s, o_s), ("Tref", tr, o_tr), ("Tmin", tm, o_tm))} for w0, w1 in ((1982, 1984), (1985, 2006), (1985, 2010), (2002, 2010), (2011, 2022), (2011, 2024)): k = (ys >= w0) & (ys <= w1) if k.sum() >= 2: out[f"mean_{w0}_{w1}"] = {"SCUI": float(s[k].mean()), "SCUI_oisst": float(o_s[k].mean()), "dTmin_oisst_minus_this": float((o_tm[k] - tm[k]).mean()), "n": int(k.sum())} if ys[0] <= 1985: a = analyse(ys, s) out["models"] = {x: a[x] for x in ("line", "hinge_fixed", "two_lines_fixed", "tests")} log(f" {label}:", brief(a)) d = o_tm - tm k1, k2 = ys <= 1984, (ys >= 1985) & (ys <= 2006) out["dTmin_welch_p_1982_84_vs_1985_2006"] = float(stats.ttest_ind(d[k1], d[k2], equal_var=False).pvalue) if beside: # the file stops at 112E, so the water beside the box here is 110-112E C = np.stack(cube) L2, A2 = np.meshgrid(clon, clat) water = np.nanmean(C[:, (A2 >= 10) & (A2 <= 12.5) & (L2 >= 110) & (L2 <= 112)], axis=1) out["beside_box"] = beside_box(ys, tr, tm, water, C, keep) log(f" {label}: {ys[0]}-{ys[-1]}, {len(ys)} years, r with OISST SCUI {out['r_SCUI']:.2f}") return out def coarse(ix, sst, lat, lon, tyear, tmon, etopo, half, label): with netCDF4.Dataset(etopo) as d: ela, elo = np.array(d["latitude"][:], float), np.array(d["longitude"][:], float) alt = np.array(d["altitude"][:], float) LON, LAT = np.meshgrid(lon, lat) W = np.cos(np.deg2rad(LAT)) dep = np.full(LAT.shape, np.nan) for j, la in enumerate(lat): jj = (ela >= la - half) & (ela < la + half) for i, lo in enumerate(lon): ii = (elo >= lo - half) & (elo < lo + half) if jj.sum() and ii.sum(): dep[j, i] = -alt[np.ix_(jj, ii)].mean() mask = in_poly(LON, LAT, POLY) & (dep >= 500) box = (LAT >= 9.9) & (LAT <= 12.6) & (LON >= 107) & (LON <= 110.1) tr, tm = [], [] for y in YEARS: fs = [sst[np.where((tyear == y) & (tmon == m))[0][0]] for m in (6, 7, 8, 9)] f = np.average(np.stack(fs), axis=0, weights=[30, 31, 31, 30]) ok = np.isfinite(f) pm = mask & ok tr.append(np.sum(f[pm] * W[pm]) / np.sum(W[pm])) tm.append(np.nanmin(np.where(box & ok, f, np.nan))) tr, tm = np.array(tr), np.array(tm) s = tr - tm a = analyse(YEARS, s, nboot=5000, nboot_break=1000) log(f" {label}:", brief(a)) return {"r_SCUI": r_(s, ix["SCUI"]), "Tref": periods(tr), "Tmin": periods(tm), "SCUI": periods(s), "p_hinge": a["tests"]["p_hinge_fixed"], "mean": float(s.mean()), "range": [float(s.min()), float(s.max())]} # ------------------------------------------------------------------ main def main(): ap = argparse.ArgumentParser(description="Repeat the numbers on factchecked.science/vietnam-upwelling-1999/") ap.add_argument("folder", nargs="?", default=str(Path(__file__).resolve().parent / "scui-data")) ap.add_argument("--out", default=None) ap.add_argument("--pylib", default=None) ap.add_argument("--no-recipe", action="store_true") args = ap.parse_args() folder = args.folder outdir = args.out or folder os.makedirs(folder, exist_ok=True) os.makedirs(outdir, exist_ok=True) if args.pylib: sys.path.append(args.pylib) try: from PyEMD import EMD except ImportError: EMD = None log("PyEMD not found: the steps with the paper's curve are skipped (pip install EMD-signal)") oi = fetch_oisst(folder) winds = fetch_winds(folder) p = fetch_rest(folder) N = {"paper": "Ngo, Hsin & Wu (2026), doi:10.1029/2026GL126805", "note": "Derived numbers only. Our analysis; see the page for what each means."} log("\n== The index") ix = build_index(oi, p["etopo"]) t, tr, tm, s = YEARS.astype(float), ix["Tref"], ix["Tmin"], ix["SCUI"] read, curve = np.array(FIG1A_READ), np.array(FIG1A_CURVE) N["series"] = {"year": YEARS.tolist(), "Tref": np.round(tr, 4).tolist(), "Tmin": np.round(tm, 4).tolist(), "SCUI": np.round(s, 4).tolist(), "read_off_fig1a": FIG1A_READ} N["against_fig1a"] = {"r": r_(s, read), "rmse": float(np.sqrt(np.mean((s - read) ** 2))), "mean_ours": float(s.mean()), "mean_read": float(read.mean()), "cells_tref": int(ix["tref_mask"].sum()), "cells_scu": int(ix["scu"].sum())} log(N["against_fig1a"]) N["slopes_student"] = {"SCUI": periods(s), "Tref": periods(tr), "Tmin": periods(tm), "read_off_fig1a": periods(read)} with open(os.path.join(outdir, "scui-reproduced.csv"), "w", newline="\n", encoding="utf-8") as f: wr = csv.writer(f, lineterminator="\n") wr.writerow(["year", "Tref_degC", "Tmin_degC", "SCUI_degC", "SCUI_read_off_paper_Fig1a_degC"]) for row in zip(YEARS, tr, tm, s, read): wr.writerow([int(row[0]), f"{row[1]:.3f}", f"{row[2]:.3f}", f"{row[3]:.3f}", f"{row[4]:.2f}"]) # where the cold cell sits, and what happens if Tmin must be in deeper water F, LAT, LON, dep, scu = ix["F"], ix["LAT"], ix["LON"], ix["dep"], ix["scu"] where = [] for k in range(len(YEARS)): j, i = np.unravel_index(np.argmin(np.where(scu, F[k], np.inf)), scu.shape) where.append((float(LAT[j, i]), float(LON[j, i]), float(dep[j, i]))) counts = {} for w in where: counts[f"{w[0]}N {w[1]}E (ETOPO cell mean depth {w[2]:.0f} m)"] = counts.get(f"{w[0]}N {w[1]}E (ETOPO cell mean depth {w[2]:.0f} m)", 0) + 1 N["coldest_cell_counts"] = counts N["coldest_cell_1982_88"] = [f"{w[0]}N {w[1]}E" for w in where[:7]] N["tmin_by_depth"] = {} for dmin in (None, 100, 200, 500): m = scu if dmin is None else scu & (dep >= dmin) x = tr - np.nanmin(F[:, m], axis=1) a = analyse(YEARS, x, nboot=3000, nboot_break=200) N["tmin_by_depth"]["any" if dmin is None else str(dmin)] = {"cells": int(m.sum()), "mean": float(x.mean()), "rmse_vs_read": float(np.sqrt(np.mean((x - read) ** 2))), **{k: v for k, v in periods(x).items() if k != "1982-2024"}, "p_hinge": a["tests"]["p_hinge_fixed"]} log(N["tmin_by_depth"]) log("\n== Where the rise lies (post hoc): the water beside the cold box, and local contrasts") beside_mask = (LAT >= 10) & (LAT <= 12.5) & (LON >= 110) & (LON <= 113) & np.isfinite(F).all(axis=0) N["beside_box"] = {"cells_water": int(beside_mask.sum()), **beside_box(YEARS, tr, tm, np.nanmean(F[:, beside_mask], axis=1), F, scu)} log({k: N["beside_box"][k]["A99"] for k in ("Tref", "water", "Tmin", "Tref_minus_water", "water_minus_Tmin", "local_5x5", "local_7x7")}, N["beside_box"]["share_of_SCUI_slope"], N["beside_box"]["r_water_minus_Tmin_with_SCUI"]) log("\n== Models on the reproduced index") main_a = analyse(t, s) N["models"] = main_a log(brief(main_a)) wide = analyse(t, s, scan=list(range(1985, 2022)), minseg=3) N["models_wide_scan"] = {k: wide[k] for k in ("hinge_best", "hinge_boot", "hinge_profile_years", "two_lines_best", "two_lines_boot", "two_lines_profile_years", "tests")} log("wide scan:", brief(wide)) r_read = analyse(t, read) N["models_read_off"] = {k: r_read[k] for k in ("line", "hinge_fixed", "two_lines_fixed", "tests", "hinge_best")} log("read-off:", brief(r_read)) # how much better than a line a hinge fits, by knot year sse_l = ols(dm("M1", t), s)[2] prof = {b: ols(dm("M2", t, b), s)[2] for b in range(1985, 2022)} N["hinge_gain_pct"] = {str(b): round(100 * (1 - v / sse_l), 2) for b, v in prof.items()} bb = min(prof, key=prof.get) X = dm("M2", t, bb) _, e, _ = ols(X, s) N["hinge_at_best_wide"] = {"b": bb, "before": slope_ci(t, s, X, np.array([0.0, 1.0, 0.0]), r1=lag1(e)), "after": slope_ci(t, s, X, np.array([0.0, 1.0, 1.0]), r1=lag1(e))} log("\n== Sensitivity") oni = {} with open(p["oni"], encoding="utf-8") as f: for line in f: x = line.split() if len(x) == 4 and x[0] == "DJF": oni[int(x[1])] = float(x[3]) sens = {} def run_s(label, tt, yy): a = analyse(tt, yy) k = tt < 1999 sens[label] = {"hinge_before": a["hinge_fixed"]["before"], "hinge_after": a["hinge_fixed"]["after"], "p_hinge": a["tests"]["p_hinge_fixed"], "p_supF": a["tests"]["p_supF_hinge"], "best_hinge": a["hinge_best"]["b"], "line": a["line"], "B99": plain(tt[k], yy[k]), "two_lines_best": a["two_lines_best"]["b"], "p_supF_two_lines": a["tests"]["p_supF_two_lines"]} log(f" {label:32s}", brief(a)) for label, d in (("drop 1998", [1998]), ("drop 1997-1999", [1997, 1998, 1999]), ("drop 1982", [1982]), ("drop 1984", [1984]), ("drop 1982 and 1984", [1982, 1984]), ("drop 1982-84", [1982, 1983, 1984])): k = ~np.isin(t, d) run_s(label, t[k], s[k]) warm = [int(y) for y in t if oni.get(int(y), -9) >= 0.5] k = ~np.isin(t, warm) run_s("drop summers after DJF ONI>=0.5", t[k], s[k]) N["warm_years"] = warm o = np.array([oni[int(y)] for y in t]) c, e, _ = ols(np.column_stack([np.ones_like(o), o]), s) run_s("DJF ONI regressed out", t, e + s.mean()) for a0 in (1983, 1984, 1986, 1987, 1988, 1989, 1990): k = t >= a0 run_s(f"start {a0}", t[k], s[k]) for b0 in range(2015, 2024): k = t <= b0 run_s(f"end {b0}", t[k], s[k]) N["sensitivity"] = sens X = dm("M2", t, 1999) _, e, sse = ols(X, s) H = X @ np.linalg.pinv(X.T @ X) @ X.T h = np.diag(H) cook = e ** 2 / (3 * sse / (len(t) - 3)) * h / (1 - h) ** 2 N["cook_top6"] = [[int(t[i]), round(float(cook[i]), 3)] for i in np.argsort(-cook)[:6]] # components with years left out, and split years N["components_drop"] = {} for label, d in (("none", []), ("1998", [1998]), ("1982-84", [1982, 1983, 1984])): k = ~np.isin(YEARS, d) y0 = YEARS[k] N["components_drop"][label] = {nm: {"B99": plain(y0[y0 < 1999], v[k][y0 < 1999]), "A99": plain(y0[y0 >= 1999], v[k][y0 >= 1999]), "all": plain(y0, v[k])} for nm, v in (("SCUI", s), ("Tref", tr), ("Tmin", tm))} N["split_years"] = {} for b in range(1994, 2005): k1, k2 = YEARS < b, YEARS >= b N["split_years"][str(b)] = {nm: {"before": plain(YEARS[k1], v[k1]), "after": plain(YEARS[k2], v[k2])} for nm, v in (("SCUI", s), ("Tref", tr), ("Tmin", tm))} N["windows_per_decade"] = {} for w0, w1 in ((1982, 1998), (1985, 1998), (1985, 2006), (1985, 2010), (1999, 2010), (1999, 2024), (2011, 2024), (1985, 2024)): k = (t >= w0) & (t <= w1) N["windows_per_decade"][f"{w0}-{w1}"] = {nm: {"slope": slope_ci(t[k], v[k])["slope"] * 10, "hw": slope_ci(t[k], v[k])["hw_ar1"] * 10} for nm, v in (("SCUI", s), ("Tref", tr), ("Tmin", tm))} N["means"] = {f"{w0}-{w1}": {"SCUI": float(s[(t >= w0) & (t <= w1)].mean()), "Tmin": float(tm[(t >= w0) & (t <= w1)].mean()), "Tmin_sd": float(tm[(t >= w0) & (t <= w1)].std(ddof=1)) if w1 > w0 else None, "Tref": float(tr[(t >= w0) & (t <= w1)].mean())} for w0, w1 in ((1982, 1984), (1985, 2010), (2011, 2024))} N["ranks"] = {"SCUI_lowest": [[int(YEARS[i]), round(float(s[i]), 2)] for i in np.argsort(s)[:8]], "Tmin_lowest": [[int(YEARS[i]), round(float(tm[i]), 2)] for i in np.argsort(tm)[:4]], "Tref_highest": [[int(YEARS[i]), round(float(tr[i]), 2)] for i in np.argsort(-tr)[:4]]} N["splits_2014_2016"] = {str(y): round(float(s[YEARS == y][0]), 2) for y in (2014, 2015, 2016)} log("\n== Rival shapes (post hoc), AICc with searched years counted") n = len(t) sh = {"one line": aicc(sse_l, n, 2), "hinge at 1999": aicc(prof[1999], n, 3), f"hinge, best knot {bb}": aicc(prof[bb], n, 3, extra=1), "two lines at 1999": aicc(ols(dm("M3", t, 1999), s)[2], n, 4), "quadratic": aicc(ols(dm("M4", t), s)[2], n, 3)} steps = {b: ols(dm("M5", t, b), s)[2] for b in range(1985, 2022)} b5 = min(steps, key=steps.get) sh[f"one step, best {b5}"] = aicc(steps[b5], n, 2, extra=1) sh["one step at 1999"] = aicc(steps[1999], n, 2) pairs = [(b1, b2) for b1 in range(1985, 2018) for b2 in range(b1 + 3, 2022)] X2 = lambda a_, b_: np.column_stack([np.ones(n), (t >= a_).astype(float), (t >= b_).astype(float)]) ssep = [ols(X2(*q_), s)[2] for q_ in pairs] b1, b2 = pairs[int(np.argmin(ssep))] sse2 = min(ssep) sh[f"two steps, {b1} and {b2}"] = aicc(sse2, n, 3, extra=2) Xe = np.column_stack([np.ones(n), t - t.mean(), (t <= 1984).astype(float)]) sh["line + own level for 1982-84"] = aicc(ols(Xe, s)[2], n, 3, extra=1) Xh = np.column_stack([np.ones(n), t - t.mean(), np.maximum(0, t - 1999), (t <= 1984).astype(float)]) sh["hinge at 1999 + own level for 1982-84"] = aicc(ols(Xh, s)[2], n, 4, extra=1) Xes = np.column_stack([np.ones(n), t - t.mean(), (t <= 1984).astype(float), (t >= 2011).astype(float)]) be, ee, ss = ols(Xes, s) sh["line + own level for 1982-84 + step at 2011"] = aicc(ss, n, 4, extra=2) N["shapes_aicc"] = {k: round(v, 1) for k, v in sorted(sh.items(), key=lambda kv: kv[1])} N["line_slope_with_level_and_step"] = {**slope_ci(t, s, Xes, np.array([0.0, 1.0, 0.0, 0.0]), r1=lag1(ee))} N["two_steps"] = {"years": [b1, b2], "levels": [float(s[t < b1].mean()), float(s[(t >= b1) & (t < b2)].mean()), float(s[t >= b2].mean())]} parts = {"SCUI": s, "Tref": tr, "Tmin": tm} a99_ = t >= 1999 N["step_split"] = {"line, own level for 1982-84, step at 2011; 1982-2024": step_parts(t, parts, own_level=True), "line, step at 2011; 1999-2024": step_parts(t[a99_], {k: v[a99_] for k, v in parts.items()}), "means 2003-10 to 2011-18": mean_change(t, parts, 2003, 2010, 2011, 2018), "means 1985-2010 to 2011-24": mean_change(t, parts, 1985, 2010, 2011, 2024)} log(N["step_split"]) log(N["shapes_aicc"]) # if a hinge at 1999 were true, how often would a two-step fit win by the observed margin? rng = np.random.default_rng(1999) Xh1 = dm("M2", t, 1999) bh, eh, sseh = ols(Xh1, s) Y = (Xh1 @ bh)[None, :] + ar1_draws(n, lag1(eh), float(np.sqrt(sseh / (n - 3))), 5000, rng) Sh = sse_many(proj_q(Xh1), Y) S2 = np.column_stack([sse_many(proj_q(X2(*q_)), Y) for q_ in pairs]).min(axis=1) dA = n * (np.log(Sh / n) - np.log(S2 / n)) + (2 * 4 + 2 * 4 * 5 / (n - 5)) - (2 * 6 + 2 * 6 * 7 / (n - 7)) obs = aicc(sseh, n, 3) - aicc(sse2, n, 3, extra=2) N["two_steps_vs_hinge"] = {"dAICc": obs, "p_under_hinge": float((1 + (dA >= obs).sum()) / (1 + len(dA)))} log(N["two_steps_vs_hinge"]) if EMD is not None: log("\n== The paper's curve (PyEMD, default settings)") def last(y): return EMD().emd(np.asarray(y, float))[-1] def shape(c, yrs): i = int(np.argmin(c)) return float(yrs[i]), 0 < i < len(c) - 1, float(min(c[0], c[-1]) - c[i]) c_read, c_ours = last(read), last(s) H_ = {"rms_vs_curve_read_series": float(np.sqrt(np.mean((c_read - curve) ** 2))), "rms_vs_curve_our_series": float(np.sqrt(np.mean((c_ours - curve) ** 2))), "min_year_ours": shape(c_ours, t)[0], "min_year_read": shape(c_read, t)[0], "depth_ours": shape(c_ours, t)[2], "last_ours": np.round(c_ours, 3).tolist(), "curve_read_off": FIG1A_CURVE, "ends": {}, "loo_min_years": []} for a0 in range(1983, 1991): k = t >= a0 y_, i_, d_ = shape(last(s[k]), t[k]) H_["ends"][f"start {a0}"] = {"min_year": y_, "interior": i_, "depth": d_} for b0 in range(2015, 2024): k = t <= b0 y_, i_, d_ = shape(last(s[k]), t[k]) H_["ends"][f"end {b0}"] = {"min_year": y_, "interior": i_, "depth": d_} for j in range(n): x = s.copy() x[j] = x[1] if j == 0 else x[-2] if j == n - 1 else 0.5 * (x[j - 1] + x[j + 1]) H_["loo_min_years"].append(shape(last(x), t)[0]) log({k: v for k, v in H_.items() if k not in ("last_ours", "curve_read_off", "loo_min_years")}) log(" smoothing one year out, minimum year runs", min(H_["loo_min_years"]), "to", max(H_["loo_min_years"])) if not args.no_recipe: pl = np.polyfit(t, s, 1) e_ = s - np.polyval(pl, t) sd_, r1_ = float(e_.std(ddof=2)), lag1(e_) obs_depth = shape(c_ours, t)[2] rng = np.random.default_rng(1999) M = 2000 ct = {"interior": 0, "in_1996_2002": 0, "depth_ge_observed": 0} Z = ar1_draws(n, r1_, sd_, M, rng) for z in Z: y_, i_, d_ = shape(last(pl[0] * (t - t.mean()) + s.mean() + z), t) if i_: ct["interior"] += 1 ct["in_1996_2002"] += 1996 <= y_ <= 2002 ct["depth_ge_observed"] += d_ >= obs_depth H_["chance_line_plus_noise"] = {k: v / M for k, v in ct.items()} log(H_["chance_line_plus_noise"]) def recipe(y): c = last(y) i = int(np.argmin(c)) pb, pa = plain(t[t < 1999], y[t < 1999]), plain(t[t >= 1999], y[t >= 1999]) v = 0 < i < n - 1 and 1996 <= t[i] <= 2002 sig = pb["slope"] < 0 and pb["p"] < 0.05 and pa["slope"] > 0 and pa["p"] < 0.05 return v, sig X2b = X2(b1, b2) bs, es, sses = ols(X2b, s) gen = {"two steps": (X2b @ bs, float(np.sqrt(sses / (n - 3))), lag1(es)), "hinge at 1999": (Xh1 @ bh, float(np.sqrt(sseh / (n - 3))), lag1(eh)), "one line": (np.polyval(pl, t), sd_, r1_)} H_["recipe"] = {} for label, (fit_, sd2, r2) in gen.items(): Z = fit_[None, :] + ar1_draws(n, r2, sd2, M, rng) c1 = c2 = c3 = 0 for y in Z: v, sig = recipe(y) c1 += v c2 += sig c3 += v and sig H_["recipe"][label] = {"imf_min_1996_2002": c1 / M, "both_slopes_p05": c2 / M, "both": c3 / M} log(" ", label, H_["recipe"][label]) N["hht"] = H_ log("\n== EOFs of June-September SST") w = np.array([30, 31, 31, 30], float) w /= w.sum() def seas(arr): f = np.sum(arr * w[None, :, None, None], axis=1) f[~np.isfinite(arr).all(axis=1)] = np.nan return f IP, TP, GL = seas(oi["ip"]), seas(oi["tp"]), seas(oi["gl"]) ila, ilo, tla, tlo, gla, glo = oi["ip_lat"], oi["ip_lon"], oi["tp_lat"], oi["tp_lon"], oi["gl_lat"], oi["gl_lon"] def eof(Fx, la, nm=4): ok = np.isfinite(Fx).all(axis=0) A = Fx[:, ok] - Fx[:, ok].mean(axis=0) wt = np.sqrt(np.cos(np.deg2rad(np.broadcast_to(la[:, None], Fx.shape[1:])[ok]))) U, S_, Vt = np.linalg.svd(A * wt, full_matrices=False) fr = S_ ** 2 / (S_ ** 2).sum() pcs = U[:, :nm] * S_[:nm] pat = np.full((nm,) + Fx.shape[1:], np.nan) for k in range(nm): pcs[:, k] /= pcs[:, k].std(ddof=1) pat[k][ok] = (A * pcs[:, k][:, None]).sum(axis=0) / (len(pcs) - 1) return fr, pcs, pat fr, pc, pat = eof(IP, ila) if np.nanmean(pat[0]) < 0: pc[:, 0] *= -1 pat[0] *= -1 if np.nanmean(pat[1][np.ix_((ila >= -14) & (ila <= -6), (ilo >= 102) & (ilo <= 120))]) < 0: pc[:, 1] *= -1 pat[1] *= -1 PC1, PC2 = pc[:, 0], pc[:, 1] frp, pcp, patp = eof(TP, tla) kpac = int(np.argmax([abs(r_(pcp[:, k], PC1)) for k in range(3)])) sg = np.sign(r_(pcp[:, kpac], PC1)) pac, pp = sg * pcp[:, kpac], sg * patp[kpac] js = [int(np.argmin(np.abs(ila - x))) for x in tla] kk = tlo <= 140 isx = [int(np.argmin(np.abs(ilo - x))) for x in tlo[kk]] a1, b1_ = pat[0][np.ix_(js, isx)], pp[:, kk] g = np.isfinite(a1) & np.isfinite(b1_) def box_mean(Fx, la, lo, la0, la1, lo0, lo1): jj, ii = (la >= la0) & (la <= la1), (lo >= lo0) & (lo <= lo1) sub = Fx[:, jj][:, :, ii] wg = np.cos(np.deg2rad(la[jj]))[:, None] * np.ones((1, ii.sum())) good = np.isfinite(sub).all(axis=0) return np.sum(sub[:, good] * wg[good], axis=1) / np.sum(wg[good]) mc, ns = box_mean(IP, ila, ilo, -14, -6, 102, 120), box_mean(IP, ila, ilo, 17, 22, 110, 118) con = mc - ns A_ = np.column_stack([np.ones_like(PC1), PC1, PC2]) bT, eT, sT = ols(A_, tm) covT = sT / (n - 3) * np.linalg.inv(A_.T @ A_) pT = 2 * stats.t.sf(np.abs(bT / np.sqrt(np.diag(covT))), n - 3) fitT = A_ @ bT N["eof"] = {"fractions_pct": np.round(fr[:4] * 100, 1).tolist(), "PC1": periods(PC1), "PC2": periods(PC2), "PC1_no_1998_B99": plain(YEARS[YEARS < 1998], PC1[YEARS < 1998]), "PC1_time_r2": r_(PC1, YEARS) ** 2, "pac_fractions_pct": np.round(frp[:4] * 100, 1).tolist(), "pac_mode": kpac + 1, "pac_R_time": r_(pac, PC1), "pac_R_space": r_(a1[g], b1_[g]), "pac_time_r2": r_(pac, YEARS) ** 2, "PC1_Tref": r_(PC1, tr), "PC1_Tref_dt": r_(dt(PC1), dt(tr)), "PC1_Tmin": r_(PC1, tm), "PC2_Tmin": r_(PC2, tm), "PC2_Tmin_dt": r_(dt(PC2), dt(tm)), "PC2_Tmin_means": {str(k): r_(run(PC2, k), run(tm, k)) for k in (3, 5, 7, 9, 11)}, "PC2_contrast": r_(PC2, con), "contrast_Tmin": r_(con, tm), "contrast": periods(con), "MC": periods(mc), "NSCS": periods(ns), "Tmin_on_PCs": {"c_PC2": float(bT[2]), "p_PC2": float(pT[2]), "fit_B99": plain(YEARS[YEARS <= 1998], fitT[YEARS <= 1998])["slope"], "fit_A99": plain(YEARS[YEARS >= 1999], fitT[YEARS >= 1999])["slope"]}} log(N["eof"]["fractions_pct"], N["eof"]["PC1"], N["eof"]["PC2"], N["eof"]["pac_fractions_pct"], "PC2-Tmin", round(N["eof"]["PC2_Tmin"], 3)) regions = {"Tref": tr, "Philippine Sea, 125-140E, 5-20N": box_mean(IP, ila, ilo, 5, 20, 125, 140), "Warm pool, 130-170E, 5S-10N": box_mean(TP, tla, tlo, -5, 10, 130, 170), "Indo-Pacific EOF domain": box_mean(IP, ila, ilo, -15, 25, 90, 140), "Sulu and Celebes Seas, 118-126E, 2-11N": box_mean(IP, ila, ilo, 2, 11, 118, 126), "Eastern Bay of Bengal, 90-97E, 6-18N": box_mean(IP, ila, ilo, 6, 18, 90, 97), "Near-global, 60S-60N": box_mean(GL, gla, glo, -60, 60, 0, 360), "Tropics, 30S-30N": box_mean(GL, gla, glo, -30, 30, 0, 360), "Eastern equatorial Pacific, 150-90W, 5S-5N": box_mean(TP, tla, tlo, -5, 5, 210, 270)} N["regions"] = {} for nm, v in regions.items(): N["regions"][nm] = {"all": slope_ci(YEARS, v), "B99": slope_ci(YEARS[YEARS <= 1998], v[YEARS <= 1998]), "A99": slope_ci(YEARS[YEARS >= 1999], v[YEARS >= 1999]), "r_Tref": r_(v, tr), "r_Tref_dt": r_(dt(v), dt(tr))} N["regions_minus_near_global"] = {nm: {"all": trend(YEARS, regions[nm] - regions["Near-global, 60S-60N"]), "A99": trend(YEARS[YEARS >= 1999], (regions[nm] - regions["Near-global, 60S-60N"])[YEARS >= 1999])} for nm in ("Tref", "Indo-Pacific EOF domain")} ph = regions["Philippine Sea, 125-140E, 5-20N"] N["Tref_minus_Philippine"] = {"all": slope_ci(YEARS, tr - ph), "A99": slope_ci(YEARS[YEARS >= 1999], (tr - ph)[YEARS >= 1999])} N["PC1_global_r"] = r_(PC1, regions["Near-global, 60S-60N"]) log("\n== Winds (R1, R2; June-September)") n34 = {} with open(p["n34"], encoding="utf-8") as f: for line in f: x = line.split() if len(x) == 13: try: n34[int(x[0])] = [float(v) for v in x[1:]] except ValueError: pass N34 = np.array([np.mean(n34[int(y)][5:9]) for y in YEARS]) def cd(sp): return np.where(sp <= 1, 2.18, np.where(sp < 3, 0.62 + 1.56 / np.maximum(sp, 1e-6), np.where(sp < 10, 1.14, 0.49 + 0.065 * sp))) * 1e-3 def partial(a_, b_, covs): Ax = np.column_stack([np.ones_like(a_)] + covs) return r_(a_ - Ax @ np.linalg.lstsq(Ax, a_, rcond=None)[0], b_ - Ax @ np.linalg.lstsq(Ax, b_, rcond=None)[0]) N["winds"] = {} for nm in ("R1", "R2"): u, v, la, lo, yy, mm = winds[nm + "_u"], winds[nm + "_v"], winds[nm + "_lat"], winds[nm + "_lon"], winds[nm + "_yy"], winds[nm + "_mm"] def sv(x): return np.array([x[(yy == y) & np.isin(mm, (6, 7, 8, 9))].mean() for y in YEARS]) def bm(f_, la0, la1, lo0, lo1): LO, LA = np.meshgrid(lo, la) m = (LA >= la0) & (LA <= la1) & (LO >= lo0) & (LO <= lo1) wg = np.cos(np.deg2rad(LA)) return np.sum(f_[..., m] * wg[m], axis=-1) / np.sum(wg[m]) def pt(f_, la0, lo0): j, i = np.searchsorted(la, la0) - 1, np.searchsorted(lo, lo0) - 1 wa, wo = (la0 - la[j]) / (la[j + 1] - la[j]), (lo0 - lo[i]) / (lo[i + 1] - lo[i]) return (1 - wa) * (1 - wo) * f_[..., j, i] + (1 - wa) * wo * f_[..., j, i + 1] + wa * (1 - wo) * f_[..., j + 1, i] + wa * wo * f_[..., j + 1, i + 1] sp = np.sqrt(u ** 2 + v ** 2) tx, ty = 1.2 * cd(sp) * sp * u, 1.2 * cd(sp) * sp * v th = np.deg2rad(34.0) fc = 2 * 7.292e-5 * np.sin(np.deg2rad(11.25)) WUI = sv((np.sin(th) * pt(ty, 11.25, 108.5) + np.cos(th) * pt(tx, 11.25, 108.5)) / (1025.0 * fc)) U_SCU, V_SCU = sv(pt(u, 11.25, 108.5)), sv(pt(v, 11.25, 108.5)) SW = (U_SCU + V_SCU) / np.sqrt(2) U_SCS, U_NP = sv(bm(u, 3, 22, 105, 120)), sv(bm(u, 0, 20, 130, 240)) CE = sv(bm(v, -10, 10, 100, 120)) res = {"WUI": periods(WUI), "U_NP": periods(U_NP), "U_SCS": periods(U_SCS), "U_SCU": periods(U_SCU), "R_NP_SCS": r_(U_NP, U_SCS), "R_NP_SCU": r_(U_NP, U_SCU), "R_NP_SCS_no_ENSO_trend": partial(U_NP, U_SCS, [t - t.mean(), N34]), "R_NP_SCU_no_ENSO_trend": partial(U_NP, U_SCU, [t - t.mean(), N34]), "Tmin_WUI": r_(WUI, tm), "Tmin_SW": r_(SW, tm), "Tmin_WUI_dt": r_(dt(WUI), dt(tm)), "Tmin_SW_dt": r_(dt(SW), dt(tm)), "CE_SW": r_(CE, SW), "CE_Tmin": r_(CE, tm), "PC2_CE": r_(PC2, CE), "PC2_SW": r_(PC2, SW)} Aw = np.column_stack([np.ones_like(SW), SW]) res["Tmin_B99_wind_out"] = plain(YEARS[YEARS <= 1998], (tm - Aw @ np.linalg.lstsq(Aw, tm, rcond=None)[0])[YEARS <= 1998]) res["SCUI_A99_wind_out"] = plain(YEARS[YEARS >= 1999], (s - Aw @ np.linalg.lstsq(Aw, s, rcond=None)[0])[YEARS >= 1999]) res["SW_rank_1982_1984"] = [int((SW > x).sum()) + 1 for x in SW[[0, 2]]] res["SW_windows"] = {k: float(SW[(YEARS >= a_) & (YEARS <= b_)].mean()) for k, a_, b_ in (("1982-84", 1982, 1984), ("1985-2010", 1985, 2010), ("2011-24", 2011, 2024))} N["winds"][nm] = res log(" ", nm, "WUI", {k: round(v_["slope"] * 1e3, 1) for k, v_ in res["WUI"].items()}, "R", round(res["R_NP_SCS"], 2), round(res["R_NP_SCU"], 2), "Tmin-SW", round(res["Tmin_SW"], 2)) log("\n== Other SST products") if p["mur_box"] and p["mur_bas"]: N["MUR"] = product(ix, p["mur_box"], p["mur_bas"], "sst", 2002, 2024, "MUR 4.1", beside=True) my_ = np.array(N["MUR"]["years"], float) N["step_split"]["MUR: line, step at 2011; 2002-2024"] = step_parts(my_, {k: np.array(N["MUR"][k]) for k in ("SCUI", "Tref", "Tmin")}) if p["pf_box"] and p["pf_bas"]: N["Pathfinder"] = product(ix, p["pf_box"], p["pf_bas"], "sea_surface_temperature", 1982, 2022, "Pathfinder 5.3") pm_ = np.array(N["Pathfinder"]["Tmin"]) N["Pathfinder"]["Tmin_low_rank_1982_84"] = [int((pm_ < x_).sum()) + 1 for x_ in pm_[:3]] N["coarse"] = {} if p["had"]: with netCDF4.Dataset(p["had"]) as d: la, lo = np.array(d["latitude"][:], float), np.array(d["longitude"][:], float) tt = netCDF4.num2date(d["time"][:], d["time"].units) x = np.ma.filled(d["sst"][:].astype("f8"), np.nan) x[x < -100] = np.nan N["coarse"]["HadISST"] = coarse(ix, x, la, lo, np.array([q_.year for q_ in tt]), np.array([q_.month for q_ in tt]), p["etopo"], 0.5, "HadISST") if p["ers"]: with netCDF4.Dataset(p["ers"]) as d: la, lo = np.array(d["latitude"][:], float), np.array(d["longitude"][:], float) tt = netCDF4.num2date(d["time"][:], d["time"].units) x = np.ma.filled(d["sst"][:, 0].astype("f8"), np.nan) N["coarse"]["ERSSTv5"] = coarse(ix, x, la, lo, np.array([q_.year for q_ in tt]), np.array([q_.month for q_ in tt]), p["etopo"], 1.0, "ERSSTv5") if p["cobe"]: with open(p["cobe"], encoding="utf-8") as f: txt = f.read() m_ = re.search(r"sst\.sst\[(\d+)\]\[(\d+)\]\[(\d+)\]", txt) nt, nla, nlo = map(int, m_.groups()) vals = np.full((nt, nla, nlo), np.nan) for mm_ in re.finditer(r"^\[(\d+)\]\[(\d+)\], (.+)$", txt[m_.end():], flags=re.M): vals[int(mm_.group(1)), int(mm_.group(2)), :] = [float(v_) for v_ in mm_.group(3).split(",")] after = lambda tag: np.array([float(v_) for v_ in txt[txt.index(tag, m_.end()):].split("\n")[1].split(",")]) vals[np.abs(vals) > 100] = np.nan N["coarse"]["COBE-SST2"] = coarse(ix, vals, after("sst.lat["), after("sst.lon["), np.repeat(np.arange(1982, 2025), 12), np.tile(np.arange(1, 13), 43), p["etopo"], 0.5, "COBE-SST2") log("\n== Climate indices") def table(fn): out = {} with open(fn, encoding="utf-8") as f: for line in f: x = line.split() if len(x) >= 13: try: out[int(x[0])] = [float(v_) for v_ in x[1:13]] except ValueError: pass return out amo = {} with open(p["amo"], encoding="utf-8") as f: for line in f: x = line.split() if len(x) == 3: try: amo.setdefault(int(x[0]), [float("nan")] * 12)[int(x[1]) - 1] = float(x[2]) except ValueError: pass N["indices"] = {} for nm, tb in (("PDO", table(p["pdo"])), ("Tripole Index", table(p["tpi"])), ("AMO", amo), ("Nino 3.4", n34)): jj = np.array([np.mean(tb[int(y)][5:9]) for y in YEARS]) ann = {y: float(np.mean(tb[y])) for y in range(1982, 2025)} N["indices"][nm] = {"r_SCUI_JJAS": r_(jj, s), "annual_1997_1999": [round(ann[y], 2) for y in (1997, 1998, 1999)], "means": {f"{a_}-{b_}": round(float(np.mean([ann[y] for y in range(a_, b_ + 1)])), 2) for a_, b_ in ((1982, 1998), (1999, 2013), (2014, 2019), (2020, 2024))}} log(N["indices"]) log("\n== Small-scale contrast in OISST (SST minus a 5x5-cell mean), June-September") def hp(f_): o = np.full(f_.shape, np.nan) for j in range(2, f_.shape[0] - 2): for i in range(2, f_.shape[1] - 2): b = f_[j - 2:j + 3, i - 2:i + 3] if np.isfinite(b).sum() == 25: o[j, i] = f_[j, i] - b.mean() return o H = np.stack([hp(F[k]) for k in range(len(YEARS))]) areas = {"deep basin": (dep >= 1000) & ix["tref_mask"], "off southern Vietnam": (LAT >= 9) & (LAT <= 14) & (LON >= 108) & (LON <= 112), "northern shelves": (LAT >= 15) & (LAT <= 23) & (LON >= 105) & (LON <= 120) & (dep < 500)} N["contrast_by_era"] = {} for nm, m in areas.items(): ok = m & np.isfinite(H).all(axis=0) r = np.sqrt(np.mean(H[:, ok] ** 2, axis=1)) N["contrast_by_era"][nm] = {f"{a_}-{b_}": round(float(r[(YEARS >= a_) & (YEARS <= b_)].mean()), 3) for a_, b_ in ((1982, 1984), (1985, 1988), (1989, 1994), (1995, 2000), (2001, 2006), (2007, 2011), (2012, 2015), (2016, 2024))} log(N["contrast_by_era"]) log("\n== The stand-in fixed before we had the paper (June-August; each month's coldest cell, 108-110E, 10-12.5N; Tref at all depths)") mon = ix["monthly"] box_s = (LAT >= 10) & (LAT <= 12.5) & (LON >= 108) & (LON <= 110) & (ix["poly"] | scu) W_ = ix["W"] tb_s = np.mean([np.sum(mon[:, k][:, ix["poly"]] * W_[ix["poly"]], axis=1) / W_[ix["poly"]].sum() for k in range(3)], axis=0) tm_s = np.mean([np.nanmin(mon[:, k][:, box_s], axis=1) for k in range(3)], axis=0) st = tb_s - tm_s a = analyse(t, st) N["standin"] = {"r_with_SCUI": r_(st, s), "mean_offset": float((st - s).mean()), "line": a["line"], "hinge_fixed": a["hinge_fixed"], "tests": a["tests"], "best_hinge": a["hinge_best"]["b"], "best_step": a["step_best"]["b"], "p_hinge_from_1985": analyse(t[t >= 1985], st[t >= 1985])["tests"]["p_hinge_fixed"]} log(brief(a)) N["inputs"] = INPUTS def rnd(o): if isinstance(o, (bool, np.bool_)): return bool(o) if isinstance(o, (float, np.floating)): return float(f"{float(o):.5g}") if math.isfinite(o) else None if isinstance(o, (int, np.integer)): return int(o) if isinstance(o, dict): return {str(k): rnd(v) for k, v in o.items()} if isinstance(o, (list, tuple, np.ndarray)): return [rnd(v) for v in o] return o with open(os.path.join(outdir, "scui-numbers.json"), "w", newline="\n", encoding="utf-8") as f: json.dump(rnd(N), f, indent=0, ensure_ascii=False) f.write("\n") log("\nwrote", os.path.join(outdir, "scui-numbers.json"), "and scui-reproduced.csv") if __name__ == "__main__": main()