#!/usr/bin/env python3 """Draw the five inline-SVG charts of the ozone-hole-2026-season page from the agencies' data files ("Our analysis"). Usage: python3 -I charts.py Reads, as data only, /downloads/...: NASA Ozone Watch's seasonal files (area 7 Sep-13 Oct, mass deficit 21 Sep-13 Oct, minimum ozone 21 Sep-16 Oct), NOAA GML's South Pole sounding table spo5_2026_11_03.csv and CAMS's six-hourly ozone-hole area. Writes /out/chart_{bars,trend,deep,pole,cams}.svg and /out/chart-numbers.json. Colours are CSS classes, styled with the --chart-* tokens in the page's page.css. Standard library only. """ import csv import json import math import sys from collections import defaultdict from datetime import date, datetime, timedelta from pathlib import Path V = Path(sys.argv[1]).resolve() D = V / "downloads" OUT = V / "out" MISSING = -9999.0 MON = {7: "Jul", 8: "Aug", 9: "Sep", 10: "Oct", 11: "Nov", 12: "Dec"} MONTH = {9: "September", 10: "October", 11: "November"} def one(sub, pattern="*.txt"): f = sorted((D / sub).glob(pattern)) assert len(f) == 1, (sub, f) return f[0] def seasonal(sub): 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 and float(p[1]) != MISSING: rows[int(p[0])] = float(p[1]) return rows def ordn(n): """1st, 2nd, 3rd, 4th, ... 11th, 12th, 13th, 21st ...""" return f"{n}{'th' if 11 <= n % 100 <= 13 else {1: 'st', 2: 'nd', 3: 'rd'}.get(n % 10, 'th')}" def minus(v, nd=1): """A number with a true minus sign.""" s = f"{abs(v):.{nd}f}" return ("−" + s) if v < 0 else s # ------------------------------------------------------------------ statistics (as in trend_test.py) def t_ppf_975(df): # Student's t 97.5% quantile by bisection on the regularized incomplete beta (Numerical Recipes) def betacf(a, b, x): qab, qap, qam = a + b, a + 1, a - 1 c, d = 1.0, 1 - qab * x / qap d = 1 / (d if abs(d) > 1e-300 else 1e-300) h = d for m in range(1, 300): m2 = 2 * m aa = m * (b - m) * x / ((qam + m2) * (a + m2)) d = 1 + aa * d d = 1 / (d if abs(d) > 1e-300 else 1e-300) c = 1 + aa / c h *= d * c aa = -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2)) d = 1 + aa * d d = 1 / (d if abs(d) > 1e-300 else 1e-300) c = 1 + aa / c de = d * c h *= de if abs(de - 1) < 3e-16: break return h def ibeta(a, b, x): if x <= 0: return 0.0 if x >= 1: return 1.0 bt = math.exp(math.lgamma(a + b) - math.lgamma(a) - math.lgamma(b) + a * math.log(x) + b * math.log(1 - x)) return bt * betacf(a, b, x) / a if x < (a + 1) / (a + b + 2) else 1 - bt * betacf(b, a, 1 - x) / b def cdf(t): p = 0.5 * ibeta(df / 2, 0.5, df / (df + t * t)) return 1 - p if t > 0 else p lo, hi = 0.0, 50.0 for _ in range(200): mid = (lo + hi) / 2 lo, hi = (mid, hi) if cdf(mid) < 0.975 else (lo, mid) return (lo + hi) / 2 def ols(xs, ys): n = len(xs) xb, yb = sum(xs) / n, sum(ys) / n sxx = sum((x - xb) ** 2 for x in xs) b = sum((x - xb) * (y - yb) for x, y in zip(xs, ys)) / sxx a = yb - b * xb s = math.sqrt(sum((y - a - b * x) ** 2 for x, y in zip(xs, ys)) / (n - 2)) return a, b, s, xb, sxx, n A1 = seasonal("nasa_area_0907_1013") D3 = seasonal("nasa_omd_0921_1013") D1 = seasonal("nasa_min_0921_1016") nums = {} # ------------------------------------------------------------------ chart A: season-mean area, every year def chart_bars(): years = list(range(1979, 2027)) L, R, T, B = 74, 984, 46, 352 slot = (R - L) / len(years) def X(y): return L + (years.index(y) + 0.5) * slot def Y(v): return B - v * (B - T) / 30 order = sorted(A1, key=lambda y: -A1[y]) rank26 = order.index(2026) + 1 s = ['', 'The hole’s mean area, September 7 to October 13, every year from 1979 to 2026', f'Bar chart of NASA’s seasonal mean ozone-hole area, in million square kilometers. The bars rise ' f'from near zero in 1979–1981 to above 20 by the early 1990s and stay between about 9 and 27 since, lowest in 2002 and ' f'2019. 2026, at {A1[2026]:.2f}, is the {rank26}th largest of {len(A1)} years with data; the six larger are ' f'{", ".join(str(y) for y in order[:rank26 - 1])}, the record being 2006 at {A1[2006]:.2f}. The most recent larger ' f'year is 2015, at {A1[2015]:.2f}. There are no data for 1995.'] for g in (0, 5, 10, 15, 20, 25, 30): s.append(f'') s.append(f'{g}') for y in years: if y not in A1: continue cls = "m-bar26" if y == 2026 else ("m-bartop" if order.index(y) < rank26 - 1 else "m-bar") h = B - Y(A1[y]) s.append(f'{y}: {A1[y]:.2f} million km², rank {order.index(y) + 1} of {len(A1)}') if y % 5 == 0 and y != 2025: s.append(f'{y}') # labels s.append(f'2026: {A1[2026]:.1f}, {rank26}th of {len(A1)}') s.append(f'') s.append(f'2026') s.append(f'2006: {A1[2006]:.1f}') s.append(f'2015: {A1[2015]:.1f}') s.append(f'no data') s.append('') nums["bars"] = {"area": A1, "rank_2026": rank26, "top": order[:10]} return "\n".join(s) # ------------------------------------------------------------------ chart D: the trend test, 2000-2026 def chart_trend(): fy = list(range(2000, 2026)) a, b, sres, xb, sxx, n = ols([y - 2000 for y in fy], [A1[y] for y in fy]) tq = t_ppf_975(n - 2) yrs = list(range(2000, 2027)) band = [] for y in yrs: x = y - 2000 fit = a + b * x half = tq * sres * math.sqrt(1 + 1 / n + (x - xb) ** 2 / sxx) band.append((y, fit, fit - half, fit + half)) L, R, T, B = 74, 964, 40, 352 y0, y1 = 6.0, 32.0 def X(y): return L + (y - 2000) * (R - L) / 26 def Y(v): return B - (v - y0) * (B - T) / (y1 - y0) up = " ".join(f"{X(y):.1f},{Y(h):.1f}" for y, f, l, h in band) lo = " ".join(f"{X(y):.1f},{Y(l):.1f}" for y, f, l, h in reversed(band)) f26 = band[-1] s = ['', '2026 against the line through 2000–2025, with the band where single years should fall', f'Dots for NASA’s seasonal mean ozone-hole area each year from 2000 to 2026, in million square ' f'kilometers, with the straight line fitted to 2000–2025, which falls by {abs(b) * 10:.1f} million square kilometers a ' f'decade, a slope not distinguishable from zero, and the 95% band where a single year should fall. Most years lie ' f'within a few million of the line; 2002 and 2019, years of sudden stratospheric warmings, lie far below it. 2026, at ' f'{A1[2026]:.2f}, is {A1[2026] - f26[1]:.1f} above the line, more than any year since 2000, but inside the band, which ' f'runs from {f26[2]:.1f} to {f26[3]:.1f} for 2026; the band’s top is above the largest season ever measured, ' f'{max(A1.values()):.1f}.'] for g in (10, 15, 20, 25, 30): s.append(f'') s.append(f'{g}') s.append(f'') for y in range(2000, 2027, 5): s.append(f'') if y != 2025: s.append(f'{y}') s.append(f'') s.append(f'2026') s.append(f'') s.append(f'') s.append(f'') for y in fy: s.append(f'{y}: {A1[y]:.2f} million km², ' f'{minus(A1[y] - band[y - 2000][1], 2) if A1[y] < band[y - 2000][1] else "+" + format(A1[y] - band[y - 2000][1], ".2f")} ' f'from the line') s.append(f'2026: {A1[2026]:.2f} million km², ' f'+{A1[2026] - f26[1]:.2f} from the line; the band runs from {f26[2]:.2f} to {f26[3]:.2f}') s.append(f'2026: {A1[2026]:.1f}') for y, dx, anchor in ((2002, 12, "start"), (2019, 12, "start")): s.append(f'{y}') s.append(f'95% band for single years') s.append('') nums["trend"] = {"a": a, "b_per_decade": b * 10, "residual_sd": sres, "t975": tq, "band": [[y, round(f, 3), round(l, 3), round(h, 3)] for y, f, l, h in band]} return "\n".join(s) # ------------------------------------------------------------------ chart B: the ten largest holes and their mass deficit def chart_deep(): top = sorted(A1, key=lambda y: -A1[y])[:10] L, R, T = 210, 900, 34 row = 34 Bt = T + row * len(top) def X(v): return L + v * (R - L) / 45 s = ['', 'The ten largest holes by area, and how much ozone each was missing', f'Horizontal bars of NASA’s mean ozone mass deficit, September 21 to October 13, for the ten years ' f'with the largest mean area, listed from the largest hole down: ' + "; ".join(f"{y}, area {A1[y]:.2f}, mass deficit {D3[y]:.2f}" for y in top) + f'. 2026 has the smallest mass deficit of the ten, {D3[2026]:.2f} million tonnes, below the 1990–2010 average of ' f'{sum(D3[y] for y in range(1990, 2011) if y in D3) / len([y for y in range(1990, 2011) if y in D3]):.2f}.'] for g in range(0, 46, 10): s.append(f'') s.append(f'{g}') avg = sum(D3[y] for y in range(1990, 2011) if y in D3) / len([y for y in range(1990, 2011) if y in D3]) s.append(f'') s.append(f'1990–2010 average, {avg:.1f}') s.append(f'Year · mean area') for i, y in enumerate(top): cy = T + row * i + row / 2 cls = "m-hbar26" if y == 2026 else "m-hbar" s.append(f'' f'{y}: mean area {A1[y]:.2f} million km², mass deficit {D3[y]:.2f} million tonnes, ' f'minimum ozone {D1[y]:.1f} DU') s.append(f'{y} · {A1[y]:.1f}') s.append(f'{D3[y]:.1f}') s.append('') nums["deep"] = {"top10": [[y, A1[y], D3[y], D1[y]] for y in top], "avg_1990_2010": avg} return "\n".join(s) # ------------------------------------------------------------------ chart C: South Pole, lowest total ozone each year def chart_pole(): rows = [] with open(one("gml_spo5_csv", "*.csv"), 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: try: d = date(int(row[idx["year"]]), int(row[idx["MO"]]), int(row[idx["Day"]])) except (ValueError, IndexError): continue def val(k): try: v = float(row[idx[k]]) except (ValueError, IndexError): return None return None if v >= 999.0 else v rows.append((d, val("SondeTotalCMR"), val("SondeTotalSBUV"))) mins = {} for y in range(1986, 2027): season = [x for x in rows if x[0].year == y and date(y, 9, 15) <= x[0] <= date(y, 10, 31)] win = [x for x in rows if x[0].year == y and date(y, 8, 1) <= x[0] <= date(y, 12, 31)] if not season: continue c = min((x for x in win if x[1] is not None), key=lambda x: (x[1], x[0])) b = min((x for x in win if x[2] is not None), key=lambda x: (x[2], x[0])) mins[y] = (c[1], c[0], b[2], b[0]) L, R, T, B = 74, 964, 40, 352 y0, y1 = 80.0, 200.0 def X(y): return L + (y - 1986) * (R - L) / 40 def Y(v): return B - (v - y0) * (B - T) / (y1 - y0) lowc = min(mins, key=lambda y: (mins[y][0], y)) rk_c = 1 + sum(1 for y in mins if mins[y][0] < mins[2026][0]) rk_b = 1 + sum(1 for y in mins if mins[y][2] < mins[2026][2]) s = ['', 'The lowest total ozone over the South Pole each year, 1986–2026, by two ways of finishing the sounding', f'Each year’s lowest total ozone from NOAA’s balloon soundings at the South Pole, in Dobson units, by ' f'two methods for the ozone above the balloon’s highest point: a constant mixing ratio (filled dots, the method of the ' f'release’s 105) and a satellite climatology (rings, the method of NOAA’s own plot). The lowest value by the first method ' f'is {mins[lowc][0]:.0f} on {mins[lowc][1]:%B} {mins[lowc][1].day}, {lowc}; 2006’s is {mins[2006][0]:.0f} on October ' f'{mins[2006][1].day}. 2026 reads {mins[2026][0]:.0f} by the first method and {mins[2026][2]:.0f} by the second, both on ' f'October 17: {mins[2026][0]:.0f} is the {ordn(rk_c)} lowest of the {len(mins)} years and {mins[2026][2]:.0f} the {ordn(rk_b)}. The highest minima are 1988, 2002 and 2019.' f''] for g in (80, 100, 120, 140, 160, 180, 200): s.append(f'') s.append(f'{g}') for y in range(1990, 2027, 5): s.append(f'') if y != 2025: s.append(f'{y}') s.append(f'') s.append(f'2026') ys = sorted(mins) s.append('') for y in ys: c, cd, b, bd = mins[y] if y == 2026: continue s.append(f'{y}: {b:.0f} DU on {bd:%b} {bd.day} ' f'(satellite climatology above the balloon)') s.append(f'{y}: {c:.0f} DU on {cd:%b} {cd.day} ' f'(constant mixing ratio above the balloon)') c, cd, b, bd = mins[2026] s.append(f'2026: {b:.0f} DU on Oct {bd.day} (satellite climatology)') s.append(f'2026: {c:.0f} DU on Oct {cd.day} (constant mixing ratio)') s.append(f'') s.append(f'2026: {c:.0f} and {b:.0f}, October 17') s.append(f'{mins[lowc][0]:.0f}, Sep {mins[lowc][1].day}, {lowc}') s.append(f'{mins[2006][0]:.0f}, Oct {mins[2006][1].day}, 2006') s.append('') nums["pole"] = {str(y): [mins[y][0], mins[y][1].isoformat(), mins[y][2], mins[y][3].isoformat()] for y in ys} return "\n".join(s) # ------------------------------------------------------------------ chart E: CAMS, 2026 against the record for each date def chart_cams(): acc = defaultdict(list) with open(one("cams_csv_sh_area", "*.csv"), encoding="utf-8") as fh: r = csv.reader(fh) next(r) for t, v in r: acc[datetime.fromisoformat(t).date()].append(float(v)) dm = {d: sum(v) / len(v) for d, v in acc.items() if len(v) == 4} last = max(d for d in dm if d.year == 2026) days = [date(2026, 9, 1) + timedelta(days=i) for i in range((last - date(2026, 9, 1)).days + 1)] def pct95(vals): s = sorted(vals) k = 0.95 * (len(s) - 1) f = int(k) return s[f] + (s[min(f + 1, len(s) - 1)] - s[f]) * (k - f) v26, rec, recyr, p95, hits = [], [], [], [], [] for d in days: past = [(dm[date(y, d.month, d.day)], y) for y in range(1979, 2026) if date(y, d.month, d.day) in dm] mx = max(past) v26.append(dm[d]) rec.append(mx[0]) recyr.append(mx[1]) p95.append(pct95([v for v, y in past if y <= 2023])) if dm[d] >= mx[0]: hits.append(d) L, R, T, B = 78, 968, 40, 372 y0, y1 = 10.0, 30.0 n = len(days) - 1 def X(i): return L + i * (R - L) / n def Y(v): return B - (v - y0) * (B - T) / (y1 - y0) def pts(vals): return " ".join(f"{X(i):.1f},{Y(v):.1f}" for i, v in enumerate(vals)) ipk = max(range(len(days)), key=lambda i: v26[i]) i14 = days.index(date(2026, 10, 14)) i09 = days.index(date(2026, 11, 9)) s = ['', f'The 2026 hole against the record for each date, September 1 to {MONTH[last.month]} {last.day}', f'CAMS daily-mean ozone-hole area in 2026, in million square kilometers, with the highest value for each ' f'date in 1979–2025 and the 95th percentile of 1979–2023. 2026 peaks at {v26[ipk]:.1f} on September 20 and again at ' f'{v26[i14]:.1f} on October 14; it is at or above the record for the date on {len(hits)} days: ' + ", ".join(f"{MONTH[d.month]} {d.day}" for d in hits) + f'. It shrinks from late October but stays near the 95th percentile into November, at {v26[-1]:.1f} on ' f'{MONTH[last.month]} {last.day}.'] for g in (10, 15, 20, 25, 30): s.append(f'') s.append(f'{g}') for i, d in enumerate(days): if d.day in (1, 15): s.append(f'') s.append(f'{MON[d.month]} {d.day}') s.append(f'') s.append(f'') s.append(f'') s.append(f'') for d in hits: i = days.index(d) s.append(f'{MONTH[d.month]} {d.day}: ' f'{v26[i]:.2f}, above the previous record, {rec[i]:.2f} ({recyr[i]})') s.append(f'2026 peak, {v26[ipk]:.1f} (Sep 20)') s.append(f'{v26[i14]:.1f} (Oct 14)') s.append(f'') s.append(f'Nov 9, record by {v26[i09] - rec[i09]:.2f}') s.append(f'Record for the date, 1979–2025') i15 = days.index(date(2026, 10, 15)) s.append(f'95th percentile') s.append('') nums["cams"] = {"last_day": last.isoformat(), "record_days": [d.isoformat() for d in hits], "peak": [days[ipk].isoformat(), round(v26[ipk], 3)], "oct14": round(v26[i14], 3), "nov9": [round(v26[i09], 3), round(rec[i09], 3), recyr[i09]], "last_value": round(v26[-1], 3)} return "\n".join(s) charts = {"bars": chart_bars(), "trend": chart_trend(), "deep": chart_deep(), "pole": chart_pole(), "cams": chart_cams()} OUT.mkdir(exist_ok=True) for k, svg in charts.items(): (OUT / f"chart_{k}.svg").write_text(svg + "\n", encoding="utf-8", newline="\n") (OUT / "chart-numbers.json").write_text(json.dumps(nums, indent=1, default=str) + "\n", encoding="utf-8", newline="\n") print(json.dumps({k: (v if k != "bars" else {"rank_2026": v["rank_2026"], "top": v["top"]}) for k, v in nums.items() if k != "pole"}, indent=1, default=str)[:3000])