#!/usr/bin/env python3 """Draw the two charts of /ionosphere-storm-recovery/ from our own results, as inline SVG, and write them into the page's body.html between the marker comments … and … . Usage: python3 -I charts.py [ ] Without arguments it finds both from its own location (verification//code/ in the project). Standard library only. Colours are classes styled by the page's page.css with the site's --chart-* tokens: blue for the storms, gray for the storm-free starts (the chance baseline), dashed so no mark relies on colour. """ import csv import re import sys from pathlib import Path SLUG = "ionosphere-storm-recovery" def f1(x): return f"{x:.1f}" def load(results): km = {} with open(results / "km_compare.csv", encoding="utf-8", newline="") as f: for r in csv.DictReader(f): if r["band"] == "NS50" and r["group"] in ("storms_ours", "placebo"): km.setdefault(r["group"], {})[int(r["hour"])] = float(r["S"]) strip = {} with open(results / "strip_compare.csv", encoding="utf-8", newline="") as f: for r in csv.DictReader(f): if r["band"] == "NS50" and r["group"] in ("storms_ours", "placebo") and r["median"] != "": strip.setdefault(r["group"], {})[int(r["hours_from_t0"])] = (float(r["median"]), float(r["q25"]), float(r["q75"]), int(r["n"])) return km, strip def pct(v): return f"{100 * v:.1f}%".replace(".0%", "%") def signed1(v): """A percentage to one decimal with a true minus sign.""" return ("+" if v >= 0 else "−") + f"{abs(v):.1f}%" def signed(v): """A whole-number percentage with a true minus sign; zero without a sign.""" r = round(v) if r == 0: return "0%" return ("+" if r > 0 else "−") + f"{abs(r)}%" def km_chart(km): X0, X1, Y0, Y1 = 64.0, 900.0, 26.0, 330.0 x = lambda h: X0 + (X1 - X0) * h / 168.0 # noqa: E731 y = lambda s: Y1 - (Y1 - Y0) * s # noqa: E731 out = [] for s in (0.0, 0.25, 0.5, 0.75, 1.0): out.append(f'' f'{int(s * 100)}%') # 4-day marker out.append(f'' f'4 days') def step(series): d = [f"M{f1(x(0))} {f1(y(1.0))}", f"V{f1(y(series[0]))}"] for h in range(1, 169): d.append(f"H{f1(x(h))}") d.append(f"V{f1(y(series[h]))}") return " ".join(d) out.append(f'') out.append(f'') for h in (24, 48, 96, 144): s, p = km["storms_ours"][h], km["placebo"][h] out.append(f'{h} h: storms {pct(s)} still “disturbed”') out.append(f'{h} h: storm-free starts {pct(p)} still “disturbed”') # value labels at 24 h and 96 h s24, p24, s96, p96 = km["storms_ours"][24], km["placebo"][24], km["storms_ours"][96], km["placebo"][96] out.append(f'{pct(s24)}') out.append(f'{pct(p24)}') out.append(f'{pct(s96)}') out.append(f'{pct(p96)}') # end labels out.append(f'Storms') out.append(f'Storm-free') out.append(f'') for h in (0, 24, 48, 72, 96, 120, 144, 168): out.append(f'' f'{h}') label = ("Step chart, 0 to 168 hours after the start, of the share still outside the note’s quiet band by its own rule. " f"Storms fall from 100% to {pct(km['storms_ours'][0])} at once, {pct(s24)} at 24 hours, {pct(s96)} at 96 hours " f"and {pct(km['storms_ours'][168])} at 168 hours. Storm-free starts fall to {pct(km['placebo'][0])} at once, " f"{pct(p24)} at 24 hours, {pct(p96)} at 96 hours and {pct(km['placebo'][168])} at 168 hours: " "below the storms for the first two days, above them from about 72 hours on.") return (f'' + "".join(out) + "") def strip_chart(strip): X0, X1, Y0, Y1 = 64.0, 900.0, 22.0, 330.0 LO, HI = -35.0, 20.0 x = lambda h: X0 + (X1 - X0) * (h + 24) / 191.0 # noqa: E731 y = lambda v: Y1 - (Y1 - Y0) * (v - LO) / (HI - LO) # noqa: E731 out = [] for v in (-30, -20, -10, 0, 10, 20): cls = "c-zero" if v == 0 else "c-grid" lab = f"{v:+d}%".replace("+0%", "0%").replace("-", "−") out.append(f'' f'{lab}') out.append(f'' f'Start (t0)') for g, band, med in (("placebo", "st-band-p", "st-med-p"), ("storms_ours", "st-band-s", "st-med-s")): ser = strip[g] hs = sorted(ser) top = " ".join(f"{f1(x(h))} {f1(y(ser[h][2]))}" for h in hs) bot = " ".join(f"{f1(x(h))} {f1(y(ser[h][1]))}" for h in reversed(hs)) out.append(f'') for g, med in (("placebo", "st-med-p"), ("storms_ours", "st-med-s")): ser = strip[g] d = " ".join(("M" if i == 0 else "L") + f"{f1(x(h))} {f1(y(ser[h][0]))}" for i, h in enumerate(sorted(ser))) out.append(f'') for h in (5, 24, 48, 96): m = strip["storms_ours"][h][0] p = strip["placebo"][h][0] out.append(f'{h} h: storms’ median {signed1(m)} (n = {strip["storms_ours"][h][3]}); storm-free starts’ {signed1(p)}' f'') out.append(f'{signed(m)}') out.append(f'Storm-free') out.append(f'Storms') out.append(f'') for h in (-24, 0, 24, 48, 72, 96, 120, 144, 167): out.append(f'' f'{str(h).replace("-", "−")}') s, p = strip["storms_ours"], strip["placebo"] label = ("Line chart, from 24 hours before to 167 hours after the start, of the median change in band TEC from the quiet " f"median at the same hour, with the middle half of starts shaded. Storms: {signed(s[0][0])} at the start, " f"{signed(s[5][0])} at 5 hours, {signed(s[24][0])} at 24, {signed(s[48][0])} at 48 and {signed(s[96][0])} at 96 hours. " f"Storm-free starts stay between {signed(min(v[0] for v in p.values()))} and {signed(max(v[0] for v in p.values()))} throughout.") return (f'' + "".join(out) + "") def main(): here = Path(__file__).resolve() if len(sys.argv) == 3: results, body = Path(sys.argv[1]), Path(sys.argv[2]) else: results = here.parents[1] / "results" body = here.parents[3] / "pages" / SLUG / "body.html" km, strip = load(results) text = body.read_text(encoding="utf-8") for name, svg in (("km", km_chart(km)), ("strip", strip_chart(strip))): pat = re.compile(r"()(.*?)()" % (name, name), re.S) if not pat.search(text): sys.exit(f"marker for chart {name} not found in {body}") text = pat.sub(lambda m: m.group(1) + "\n" + svg + "\n" + m.group(3), text) with open(body, "w", encoding="utf-8", newline="\n") as f: f.write(text) print("charts written into", body) if __name__ == "__main__": main()