#!/usr/bin/env python3 """Rank the 2026 Antarctic ozone hole among 1979-2026 on the measures pre-registered in RULES_rankings.txt (and its Amendment 1). Standard library only. Reads the downloads as data. Usage: python3 -I rankings.py Writes out/rankings.json and prints a log (out/rankings_stdout.txt when redirected), with the SHA-256 of the rules file and of every data file read. """ import csv import hashlib import json import sys from datetime import date, timedelta from pathlib import Path if hasattr(sys.stdout, "reconfigure"): sys.stdout.reconfigure(encoding="utf-8", newline="\n") HERE = Path(__file__).resolve().parent # the rules files sit beside the scripts V = Path(sys.argv[1]).resolve() D = V / "downloads" OUT = V / "out" MISSING = -9999.0 read_files = [] def sha(p): h = hashlib.sha256(Path(p).read_bytes()).hexdigest() read_files.append((Path(p).relative_to(V).as_posix(), h)) return h def one(sub, pattern="*.txt"): f = sorted((D / sub).glob(pattern)) if len(f) != 1: raise SystemExit(f"expected one file in {sub}, found {f}") sha(f[0]) return f[0] def seasonal(sub): """NASA seasonal file: 'Year Data Minimum Maximum'; returns {year: value} without missing years.""" rows = {} for line in one(sub).read_text(encoding="utf-8").splitlines(): p = line.split() if len(p) >= 2 and p[0].isdigit() and len(p[0]) == 4: v = float(p[1]) if v != MISSING: rows[int(p[0])] = v return rows def daily(sub): """NASA yearly daily file: 'Date Data Minimum 10% 30% Mean 70% 90% Maximum'; returns {date: [cols]}.""" rows = {} for line in one(sub).read_text(encoding="utf-8").splitlines(): p = line.split() if p and len(p[0]) == 10 and p[0][4] == "-" and p[0][7] == "-": rows[date.fromisoformat(p[0])] = [float(x) for x in p[1:]] return rows def rank(values, year, largest_first=True): """Competition rank (ties share the better rank) of `year`, compared at two decimals.""" r = {y: round(v, 2) for y, v in values.items()} me = r[year] better = sum(1 for y, v in r.items() if (v > me if largest_first else v < me)) ties = sorted(y for y, v in r.items() if v == me and y != year) return better + 1, ties def since(values, year, largest_first=True): """Most recent year before `year` that was more severe (strictly, at two decimals).""" me = round(values[year], 2) worse = [y for y, v in values.items() if y < year and (round(v, 2) > me if largest_first else round(v, 2) < me)] return max(worse) if worse else None def top(values, n, largest_first=True): return [(y, values[y]) for y in sorted(values, key=lambda y: (-values[y] if largest_first else values[y], y))[:n]] res = {"rules_sha256": hashlib.sha256((HERE / "RULES_rankings.txt").read_bytes()).hexdigest()} # ---------------- A1: season-mean area (NASA's published value) --------------------------------------------------- A1 = seasonal("nasa_area_0907_1013") # cross-check from the daily files area = {} for y in range(1979, 2027): area[y] = daily(f"nasa_area_{y}") xcheck = {} for y, rows in area.items(): vals = [rows[date(y, 9, 7) + timedelta(days=i)][0] for i in range(37) if (date(y, 9, 7) + timedelta(days=i)) in rows and rows[date(y, 9, 7) + timedelta(days=i)][0] != MISSING] if vals: xcheck[y] = (sum(vals) / len(vals), len(vals)) diffs = {y: round(xcheck[y][0] - A1[y], 3) for y in A1 if y in xcheck} res["A1_crosscheck"] = {"max_abs_diff_daily_mean_vs_published": max(abs(v) for v in diffs.values()), "years_with_fewer_than_37_days": {y: xcheck[y][1] for y in xcheck if xcheck[y][1] < 37}} # ---------------- A2: one-day maximum area, 1 Jul-31 Dec ------------------------------------------------------------ A2, A2date = {}, {} for y, rows in area.items(): win = [(d, v[0]) for d, v in rows.items() if date(y, 7, 1) <= d <= date(y, 12, 31) and v[0] != MISSING] if win: d, v = max(win, key=lambda kv: (kv[1], -kv[0].toordinal())) A2[y], A2date[y] = v, d.isoformat() # ---------------- D1, D3: NASA seasonal minimum ozone and mass deficit --------------------------------------------- D1 = seasonal("nasa_min_0921_1016") D3 = seasonal("nasa_omd_0921_1013") # ---------------- D2: one-day minimum ozone, 1 Jul-31 Dec ----------------------------------------------------------- D2, D2date = {}, {} for y in range(1979, 2027): rows = daily(f"nasa_min_{y}") win = [(d, v[0]) for d, v in rows.items() if date(y, 7, 1) <= d <= date(y, 12, 31) and v[0] != MISSING] if win: d, v = min(win, key=lambda kv: (kv[1], kv[0].toordinal())) D2[y], D2date[y] = v, d.isoformat() # ---------------- D4/D5: South Pole ozonesondes (GML spo5 table) ---------------------------------------------------- f = one("gml_spo5_csv", "*.csv") sp = [] with open(f, encoding="utf-8", newline="") as fh: r = csv.reader(fh) head = next(r) idx = {k: i for i, k in enumerate(head) if k} for row in r: if not row or not row[0].strip(): continue try: y, m, dd = int(row[idx["year"]]), int(row[idx["MO"]]), int(row[idx["Day"]]) except ValueError: continue def val(k): try: v = float(row[idx[k]]) except (ValueError, IndexError): return None return None if v >= 999.0 else v sp.append({"date": date(y, m, dd), "sbuv": val("SondeTotalSBUV"), "cmr": val("SondeTotalCMR"), "dobson": val("DOBSON"), "c1220": val("12_20DU"), "burst": val("BalloonBurst_km")}) res["spo5_rows"] = len(sp) res["spo5_first_last"] = [min(s["date"] for s in sp).isoformat(), max(s["date"] for s in sp).isoformat()] def spo_minima(key): out, when = {}, {} for y in range(1986, 2027): season = [s for s in sp if s["date"].year == y and date(y, 9, 15) <= s["date"] <= date(y, 10, 31) and s[key] is not None] win = [s for s in sp if s["date"].year == y and date(y, 8, 1) <= s["date"] <= date(y, 12, 31) and s[key] is not None] if season and win: low = min(win, key=lambda s: (s[key], s["date"])) out[y], when[y] = low[key], low["date"].isoformat() return out, when D4, D4date = spo_minima("sbuv") D4c, D4cdate = spo_minima("cmr") D4d, D4ddate = spo_minima("dobson") D5, D5date = spo_minima("c1220") # 2026 soundings in October (for the release's "105 DU on October 17") res["spo_2026_oct_soundings"] = [{k: (v.isoformat() if k == "date" else v) for k, v in s.items()} for s in sp if s["date"].year == 2026 and s["date"].month in (9, 10, 11)] # all-time lowest in each column, 1986-2026, any date alltime = {} for key in ("sbuv", "cmr", "dobson", "c1220"): cand = [s for s in sp if s[key] is not None and s["date"].year >= 1986] lows = sorted(cand, key=lambda s: (s[key], s["date"]))[:6] alltime[key] = [(s["date"].isoformat(), s[key]) for s in lows] res["spo_alltime_lowest"] = alltime res["spo_2006_october"] = [{k: (v.isoformat() if k == "date" else v) for k, v in s.items()} for s in sp if s["date"].year == 2006 and s["date"].month == 10] res["spo_1993_october"] = [{k: (v.isoformat() if k == "date" else v) for k, v in s.items()} for s in sp if s["date"].year == 1993 and s["date"].month == 10] # ---------------- rank everything ---------------------------------------------------------------------------------- M = { "A1_season_mean_area_0907_1013": (A1, True, None), "A2_one_day_max_area": (A2, True, A2date), "D1_season_mean_min_ozone_0921_1016": (D1, False, None), "D2_one_day_min_ozone": (D2, False, D2date), "D3_season_mean_mass_deficit_0921_1013": (D3, True, None), "D4_south_pole_sonde_min_SBUV": (D4, False, D4date), "D4b_south_pole_sonde_min_CMR": (D4c, False, D4cdate), "D4c_south_pole_dobson_min": (D4d, False, D4ddate), "D5_south_pole_12_20km_min": (D5, False, D5date), } out = {} for name, (vals, big, when) in M.items(): if 2026 not in vals: out[name] = {"note": "no 2026 value"} continue rk, ties = rank(vals, 2026, big) y = since(vals, 2026, big) out[name] = {"value_2026": vals[2026], "date_2026": when[2026] if when else None, "rank": rk, "ties": ties, "n_years": len(vals), "first_year": min(vals), "missing_years": [yy for yy in range(min(vals), 2027) if yy not in vals], "most_recent_more_severe": y, "more_severe_in_over_a_decade": (y is not None and y <= 2015), "top10": [(yy, v, when[yy] if when else None) for yy, v in top(vals, 10, big)]} res["measures"] = out # Q2: years res["Q2_years"] = {"calendar_years_1979_2026": 2026 - 1979 + 1, "A1_years_with_data": len(A1), "A1_missing": [y for y in range(1979, 2027) if y not in A1]} # Q4: "not as deep as other large holes on record": the ten largest years by A1 top10 = [y for y, _ in top(A1, 10, True)] q4 = {"top10_by_A1": [(y, A1[y]) for y in top10]} for name, vals, big in (("D1", D1, False), ("D3", D3, True), ("D4", D4, False)): others = [y for y in top10 if y != 2026 and y in vals] deeper = [y for y in others if (vals[y] > vals[2026] if big else vals[y] < vals[2026])] q4[name] = {"others_with_data": len(others), "deeper_than_2026": len(deeper), "deeper_years": deeper, "not_deeper_years": [y for y in others if y not in deeper], "values": {y: vals[y] for y in top10 if y in vals}} res["Q4_not_as_deep"] = q4 res["files_read"] = read_files (OUT / "rankings.json").write_text(json.dumps(res, indent=1, default=str) + "\n", encoding="utf-8", newline="\n") print(json.dumps(res, indent=1, default=str))