#!/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'")
(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'")
# 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'")
(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'")
(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()})