#!/usr/bin/env python3 """Draw the four inline SVG charts of factchecked.science/may-2024-dc-ac-circuit/ from our own outputs and public data. Usage: python3 -I make_charts.py [OUT_DIR DATA_DIR] (default: out/ and downloads/ beside this script's folder) Standard library only. Reads OUT_DIR/*.json and C_prl_5min.csv and DATA_DIR/nmdb/*_1h.html (as fetch_inputs.py lays them out); writes OUT_DIR/charts/{rigidity,monitors,purulia,thunder}.svg, which assemble_page.py inlines in the page. Colours are classes styled in the page's page.css with the --chart-* tokens; text sizes are in viewBox units. """ import csv import datetime as dt import html import json import math import os import re import sys from pathlib import Path V = Path(__file__).resolve().parents[1] OUT = Path(sys.argv[1]) if len(sys.argv) > 2 else V / "out" DATA = Path(sys.argv[2]) if len(sys.argv) > 2 else V / "downloads" CH = OUT / "charts" CH.mkdir(exist_ok=True) def esc(s): return html.escape(s, quote=True) def f1(x): return f"{x:.1f}" def minus(s): return s.replace("-", "−") # ---------------------------------------------------------------- 1. rigidity ladder ab = json.load(open(OUT / "AB_results.json", encoding="utf-8")) W, H = 1000, 430 X0, X1 = 262, 975 LMIN, LMAX = math.log10(0.08), math.log10(25) def xr(r): return X0 + (math.log10(r) - LMIN) / (LMAX - LMIN) * (X1 - X0) def rig(T): return math.sqrt(T * T + 2 * T * 938.272) / 1000 q = ab["A1"] b57 = ab["A3"]["cut_57pct"] rows = [ (64, "Solar protons the paper plots", "GOES, 10, 50, 100 MeV"), (114, "Solar protons above 500 MeV", "GOES, 11 May"), (164, "GLE 74’s particles", "as identified, up to"), (226, "Shielding at the sites", "quiet-time cutoffs"), (280, "If the storm cut it by 57%", "our deliberately generous bound"), (336, "Neutron monitors", "their cutoffs"), ] s = [] s.append(f'') s.append('The rigidity solar particles need to reach the paper’s four sites') desc = ("Log-scale chart of rigidity, in gigavolts, from 0.08 to 25 GV. The solar protons the paper plots, 10, 50 and 100 MeV, " "have rigidities of 0.14, 0.31 and 0.44 GV; protons above 500 MeV start at 1.09 GV; GLE 74’s particles were identified up " "to at least 2.4 GV, above which published spectra fall off steeply. The quiet-time cutoffs of the paper’s sites are about 10.9 GV at Kakioka, 11.1 GV at Chofu and 15.7 GV " "at Bagula and Purulia; cut by 57%, a generous bound for the storm, they would still be 4.7 to 6.7 GV. Neutron-monitor " "cutoffs: South Pole 0.1, Oulu 0.8, Rome 6.3, Mexico City 8.3 and Doi Inthanon 16.8 GV.") s.append(f'{esc(desc)}') s.append(f'') s.append(f'Solar particles identified up to ≈2.4 GV') for tick in (0.1, 0.2, 0.5, 1, 2, 5, 10, 20): x = xr(tick) s.append(f'') lab = f"{tick:g}" s.append(f'{lab}') s.append(f'') s.append(f'GV, log scale') for y, a, b in rows: s.append(f'{esc(a)}') s.append(f'{esc(b)}') s.append(f'') def dot(x, y, cls, title, r=7): return f'{esc(title)}' for T, lab in ((10, "10"), (50, "50"), (100, "100 MeV")): x = xr(rig(T)) s.append(dot(x, 64, "m-sun", f"{T} MeV protons: {rig(T):.2f} GV")) s.append(f'{lab}') x = xr(rig(500)) s.append(dot(x, 114, "m-sun", f">500 MeV protons: from {rig(500):.2f} GV")) s.append(f'1.09 GV') s.append(f'GLE 74: particles identified up to about 2.4 GV (1.6 GeV)' f'') s.append(f'≈2.4 GV') for site, name in (("KAK", "Kakioka"), ("CHF", "Chofu"), ("BGL", "Bagula"), ("PRL", "Purulia")): rc = q[site]["Rc_grid_2015_GV"] s.append(dot(xr(rc), 226, "m-site", f"{name}: {rc:.1f} GV (Smart and Shea’s 2015 grid)")) rb = rc * (1 - 0.57) # from the unrounded grid value, so 15.69 GV gives 6.7, not 6.8 s.append(dot(xr(rb), 280, "m-bound", f"{name}, cut by 57%: {rb:.1f} GV", r=6)) s.append(f'Kakioka, Chofu ≈11') s.append(f'Bagula, Purulia ≈15.7') s.append(f'4.7–4.8') s.append(f'6.7') for name, rc, dy in (("South Pole", 0.10, -14), ("Oulu", 0.81, -14), ("Rome", 6.27, 24), ("Mexico City", 8.28, -14), ("Doi Inthanon", 16.8, -14)): s.append(dot(xr(rc), 336, "m-nm", f"{name} neutron monitor: {rc:g} GV (NMDB)", r=6)) s.append(f'{esc(name)}') s.append("") (CH / "rigidity.svg").write_text("\n".join(s) + "\n", encoding="utf-8", newline="\n") # ---------------------------------------------------------------- 2. neutron monitors ROW = re.compile(r"^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2});\s*([-+\d.eE]+)") def nm(st): out = {} for line in open(DATA / "nmdb" / f"nmdb_{st}_20240501_16_1h.html", encoding="utf-8", errors="replace"): m = ROW.match(line.strip()) if m: out[dt.datetime.fromisoformat(m.group(1))] = float(m.group(2)) base = [v for t, v in out.items() if dt.datetime(2024, 5, 7) <= t < dt.datetime(2024, 5, 10)] b = sum(base) / len(base) return {t: 100 * (v / b - 1) for t, v in out.items()} T0, T1 = dt.datetime(2024, 5, 10, 12), dt.datetime(2024, 5, 12, 12) W2, H2 = 1000, 430 PX0, PX1, PY0, PY1 = 70, 820, 34, 372 YMIN, YMAX = -15.0, 3.0 def xt(t): return PX0 + (t - T0).total_seconds() / (T1 - T0).total_seconds() * (PX1 - PX0) def yv(v): return PY0 + (YMAX - v) / (YMAX - YMIN) * (PY1 - PY0) series = [("SOPO", "South Pole", "0.1 GV", "l-sopo"), ("OULU", "Oulu", "0.8 GV", "l-oulu"), ("MXCO", "Mexico City", "8.3 GV", "l-mxco"), ("PSNM", "Doi Inthanon", "16.8 GV", "l-psnm")] s = [] s.append(f'') s.append('Neutron monitors through the storm, 10–12 May 2024') s.append('Line chart of hourly neutron-monitor count rates, as percentages of each monitor’s mean over 7–9 May ' '2024, from noon UT on 10 May to noon on 12 May. All four fall after the shock at 17:05 UT on 10 May. The South Pole and ' 'Oulu monitors, with almost no magnetic shielding, fall about 14 and 11 percent and show the solar particles of ' 'GLE 74 as a bump from about 02 UT on 11 May. Mexico City (cutoff 8.3 GV) and Doi Inthanon (16.8 GV) stay 4.6 to 7.1 ' 'and 1.4 to 3.9 percent below their pre-storm level in every hour of 11 May; their small rise around 01 to 05 UT comes ' 'with the deepest part of the magnetic storm.') s.append(f'') s.append(f'11 May, UT') for v in (3, 0, -3, -6, -9, -12, -15): y = yv(v) s.append(f'') s.append(f'{minus(f"{v:+d}" if v else "0")}') s.append(f'7–9 May level') t = T0 while t <= T1: x = xt(t) s.append(f'') lab = f"{t.day} May {t:%H}:00" if t.hour == 0 else f"{t:%H}:00" s.append(f'{lab}') t += dt.timedelta(hours=6) for tm, lab, dy in ((dt.datetime(2024, 5, 10, 17, 5), "Shock 17:05", 0), (dt.datetime(2024, 5, 11, 1, 50), ">100 MeV protons rise 01:50", 16)): x = xt(tm) s.append(f'') s.append(f'{lab}') data = {} for st, name, rc, cls in series: d = nm(st) pts = [(xt(t), yv(v)) for t, v in sorted(d.items()) if T0 <= t <= T1] data[st] = d path = " ".join(f"{f1(x)},{f1(y)}" for x, y in pts) s.append(f'{esc(name)} ({rc}): hourly count rate as % of its 7–9 May mean') last = [v for t, v in sorted(d.items()) if T0 <= t <= T1][-1] s.append(f'{esc(name)} · {rc}') s.append(f'%') s.append("") # end labels may collide: nudge them apart txt = "\n".join(s) (CH / "monitors.svg").write_text(txt + "\n", encoding="utf-8", newline="\n") ends = {st: [v for t, v in sorted(data[st].items()) if T0 <= t <= T1][-1] for st in data} # ---------------------------------------------------------------- 3. Purulia mornings pr = {} with open(OUT / "C_prl_5min.csv", encoding="utf-8") as f: for r in csv.DictReader(f): t = dt.datetime.strptime(r["utc"], "%Y-%m-%d %H:%M") pr[t] = float(r["pg_Vm"]) W3, H3 = 1000, 430 QX0, QX1, QY0, QY1 = 120, 900, 30, 372 days = [dt.datetime(2024, 5, d) for d in range(8, 15)] vals = [v for t, v in pr.items() if any(d <= t < d + dt.timedelta(hours=8) for d in days)] lo = 200 * math.floor(min(vals) / 200) hi = 200 * math.ceil(max(vals) / 200) def xq(h): return QX0 + h / 8 * (QX1 - QX0) def yq(v): return QY0 + (hi - v) / (hi - lo) * (QY1 - QY0) s = [] s.append(f'') s.append('Purulia’s electric field on the mornings of 8–14 May 2024') s.append('Line chart of the authors’ Purulia field-mill data, five-minute means on the paper’s scale in volts ' 'per metre, from 00:00 to 08:00 UT (05:30 to 13:30 India time) on each day from 8 to 14 May 2024. On most mornings ' 'that week the field climbs after sunrise. On 11 May it rises after about 02 UT, as the paper says, but on 8 May it rose more in ' 'the same hours, and on 9 and 12 May somewhat less. Vertical lines mark 01:50 UT, when protons above ' '100 MeV began to rise at GOES, and 02:45 UT, the time the paper gives for the solar particle event.') s.append(f'') s.append(f'Our test window, 02:45–05:45 UT') v = lo while v <= hi: y = yq(v) s.append(f'') s.append(f'{minus(str(int(v)))}') v += 200 for h in range(0, 9): x = xq(h) s.append(f'') ist = (dt.datetime(2024, 1, 1, h) + dt.timedelta(hours=5, minutes=30)).strftime("%H:%M") s.append(f'{h:02d}:00') s.append(f'{ist}') s.append(f'UT') s.append(f'IST') for hh, lab, dy in ((1 + 50 / 60, "01:50", 0), (2.75, "02:45", 0)): x = xq(hh) s.append(f'') s.append(f'{lab}') for d in days: pts = [(xq((t - d).total_seconds() / 3600), yq(v)) for t, v in sorted(pr.items()) if d <= t <= d + dt.timedelta(hours=8)] cls = "l-day11" if d.day == 11 else "l-day" path = " ".join(f"{f1(x)},{f1(y)}" for x, y in pts) s.append(f'Purulia, {d.day} May: 5-minute means, 00–08 UT') endv = [v for t, v in sorted(pr.items()) if d <= t <= d + dt.timedelta(hours=8)][-1] if d.day == 11: s.append(f'11 May') s.append(f'V/m') s.append("") (CH / "purulia.svg").write_text("\n".join(s) + "\n", encoding="utf-8", newline="\n") # ---------------------------------------------------------------- 4. thunder reports F = json.load(open(OUT / "F_regional_ts.json", encoding="utf-8")) pdays = sorted(F["per_day"]) W4, H4 = 1000, 300 BX0, BX1, BY0, BY1 = 70, 985, 34, 262 n = len(pdays) bw = (BX1 - BX0) / n ref = {f"2024-05-{d:02d}" for d in list(range(3, 10)) + list(range(13, 20))} storm = {"2024-05-10", "2024-05-11", "2024-05-12"} YM = 13 def yb(v): return BY1 - v / YM * (BY1 - BY0) s = [] s.append(f'') s.append('Airports within 500 km of Bagula reporting thunder, each day of April and May 2024') s.append('Bar chart of how many of 20 airports within 500 km of Bagula reported a thunderstorm in at least one ' 'weather report each day, 1 April to 31 May 2024. 11 May has the tallest bar, 12 airports; 6 May has 11, and 9 and 22 May ' '10. On 10 May 2 airports reported thunder and on 12 May 5. The paper’s 14 reference days, 3–9 and 13–19 May, average 4.6.') for v in (0, 3, 6, 9, 12): y = yb(v) s.append(f'') s.append(f'{v}') for i, d in enumerate(pdays): c = F["per_day"][d]["ts_stations"] k = F["per_day"][d]["ts_reports"] cls = "b-storm" if d in storm else ("b-ref" if d in ref else "b-other") x = BX0 + i * bw + 1.5 day = dt.date.fromisoformat(d) title = (f"{day.day} {day:%B}: {c} airport{'' if c == 1 else 's'} reported thunder " f"({k} report{'' if k == 1 else 's'})") h = max(c / YM * (BY1 - BY0), 0) s.append(f'{esc(title)}') if d == "2024-05-11": s.append(f'11 May: 12') if day.day in (1, 15) or d == "2024-05-31": s.append(f'{day.day} {day:%b}') s.append(f'airports') s.append("") (CH / "thunder.svg").write_text("\n".join(s) + "\n", encoding="utf-8", newline="\n") print("wrote", sorted(p.name for p in CH.iterdir()), "| PRL y-range", lo, hi, "| NM end values", {k: round(v, 2) for k, v in ends.items()})