#!/usr/bin/env python3 """Draws the four charts of /march-2023-storm/ as inline SVG (Fact-Checked Science). Standard library only. python3 -I -X utf8 charts.py OUT_FOLDER KYOTO_FOLDER [BODY_HTML] OUT_FOLDER holds storm_rank.json, dst_recovery.json, dipole_pace.json and photo_geometry.json, as written by the analyses (march_2023_storm.py runs them all). KYOTO_FOLDER holds Kyoto's monthly Dst pages (final and provisional only), for the hourly line. BODY_HTML if given, each chart replaces what stands between and in that file (NAME: dst, storms, dipole, sky). Otherwise the four SVGs are written to OUT_FOLDER. Every chart is our own analysis of public data: GFZ's Kp (CC BY 4.0); Kyoto's final and provisional Dst (scientific, non-commercial use, with acknowledgement of the World Data Center for Geomagnetism, Kyoto, and of the observatories); CHAOS-8.7 (CC BY 4.0); and star positions computed from catalogue coordinates. Colours and type come from the page's CSS classes, so both themes work. """ import datetime as dt import html import json import math import os import re import sys sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from storm_rank import read_kyoto, kpname # our own modules, same folder import photo_geometry as PG H1 = dt.timedelta(hours=1) MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] MON3 = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] def f1(x): return f"{x:.1f}" def esc(s): return html.escape(s, quote=True) def minus(v, nd=0): """A number with a true minus sign.""" s = f"{v:.{nd}f}" return s.replace("-", "−") def long_date(t): return f"{MONTHS[t.month - 1]} {t.day}, {t.year}" def dec_year(t): y0 = dt.datetime(t.year, 1, 1) y1 = dt.datetime(t.year + 1, 1, 1) return t.year + (t - y0).total_seconds() / (y1 - y0).total_seconds() def text(x, y, s, cls="t-lab", anchor=None, halo=False): a = f' text-anchor="{anchor}"' if anchor else "" c = cls + (" t-halo" if halo else "") return f'{esc(s)}' # ------------------------------------------------------------------ chart 1: hourly Dst around the storm def chart_dst(dst, rec): W, Hh = 1000, 356 x0, x1, y0, y1 = 58.0, 986.0, 34.0, 318.0 t0, t1 = dt.datetime(2023, 3, 20), dt.datetime(2023, 4, 3) span_h = (t1 - t0).total_seconds() / 3600.0 vmax, vmin = 40.0, -180.0 def X(t): return x0 + (t - t0).total_seconds() / 3600.0 / span_h * (x1 - x0) def Y(v): return y0 + (vmax - v) / (vmax - vmin) * (y1 - y0) s = rec["storm"] B = s["B_median_27d"] tmin = dt.datetime.strptime(s["t_min_hour_start"], "%Y-%m-%d %H:%M") D = s["depth"] p = [] # the storm's three days, shaded p.append(f'') for v in (40, 0, -40, -80, -120, -160): p.append(f'') p.append(text(x0 - 8, Y(v) + 4.5, minus(v), "t-ax", "end")) d = t0 while d <= t1: p.append(f'') if (d - t0).days % 2 == 0 and d < t1: p.append(text(X(d), y1 + 22, f"{MON3[d.month - 1]} {d.day}", "t-ax", "middle")) d += dt.timedelta(days=1) # the level before p.append(f'') p.append(text(x1 - 4, Y(B) - 8, f"Level before the storm: {minus(B)} nT", "t-lab", "end", True)) # daily means d = t0 while d < t1: vals = [dst[d + i * H1] for i in range(24)] m = sum(vals) / 24.0 p.append(f'{esc(long_date(d))}: daily mean {minus(m, 1)} nT' f'') d += dt.timedelta(days=1) # the hourly line pts, t = [], t0 while t < t1: pts.append((X(t + dt.timedelta(minutes=30)), Y(dst[t]))) t += H1 p.append('') # the minimum xm, ym = X(tmin + dt.timedelta(minutes=30)), Y(s["min"]) p.append(f'Lowest hour: {minus(s["min"])} nT, {tmin:%H}:00 to {tmin.hour + 1:02d}:00 UT, {esc(long_date(tmin))}' f'') p.append(text(xm + 12, ym + 5, f"{minus(s['min'])} nT, {tmin.hour:02d}–{tmin.hour + 1:02d} UT, March {tmin.day}", "t-alt", None, True)) # 63% of the fall recovered (all but 1/e) te = tmin + s["R1_efold_hours"] * H1 xe, ye = X(te + dt.timedelta(minutes=30)), Y(dst[te]) p.append(f'The first hour at or above {minus(B - D / math.e, 1)} nT, the level at which 63% of the fall is recovered (all but 1/e of it): ' f'{s["R1_efold_hours"]} hours after the lowest hour') p.append(text(xe + 11, ye + 16, f"63% of the fall recovered after {s['R1_efold_hours']} hours", "t-lab", None, True)) # back at the level before d4 = dt.datetime.strptime(s["R4_full_day"], "%Y-%m-%d") p.append(f'') p.append(text(X(d4 + dt.timedelta(hours=12)), Y(-104) + 16, f"Daily mean back at the level before: March {d4.day}", "t-lab", "middle", True)) late = [(sum(dst[dd + i * H1] for i in range(24)) / 24.0, dd) for dd in (dt.datetime(2023, 3, 31), dt.datetime(2023, 4, 1), dt.datetime(2023, 4, 2))] lo_m, lo_d = min(late) label = ("Line chart of hourly Dst from March 20 to April 2, 2023, with each day’s mean. Dst stays near zero until March 23, falls to " f"{minus(s['min'])} nanotesla in the hour from 02 UT on March 24, has recovered 63% of that fall {s['R1_efold_hours']} hours later, and its daily mean is back at the " f"level before the storm, {minus(B)} nanotesla, on March {d4.day}. From March 31 it dips again, to a daily mean of {minus(lo_m)} nanotesla on " f"{MONTHS[lo_d.month - 1]} {lo_d.day}, in a later, smaller disturbance.") return (f'' + "".join(p) + "") # ------------------------------------------------------------------ chart 2: the storms of 2017-2026 def chart_storms(rank): W, Hh = 1000, 452 x0, x1 = 58.0, 986.0 ya0, ya1 = 52.0, 186.0 # Kp panel yb0, yb1 = 246.0, 412.0 # Dst panel T0, T1 = 2017.0, 2027.0 def X(t): return x0 + (t - T0) / (T1 - T0) * (x1 - x0) def YK(k): return ya1 - (k - 6.4) / (9.2 - 6.4) * (ya1 - ya0) def YD(v): return yb0 + (-80.0 - v) / 350.0 * (yb1 - yb0) ks = rank["storms_since_2017"]["kp_storms_G3_or_more"] ds = rank["storms_since_2017"]["dst_storms_minus100_or_below"] p = [] wa, wb = X(2017 + 81.0 / 365), X(2023 + 81.0 / 365) for ytop, ybot in ((ya0 - 14, ya1), (yb0 - 14, yb1)): p.append(f'') p.append(text((wa + wb) / 2, ya0 - 22, "The six years before the storm", "t-lab", "middle")) for k in (7, 8, 9): p.append(f'') p.append(text(x0 - 8, YK(k) + 4.5, str(k), "t-ax", "end")) for v in (-100, -200, -300, -400): p.append(f'') p.append(text(x0 - 8, YD(v) + 4.5, minus(v), "t-ax", "end")) p.append(f'') p.append(f'') for y in range(2017, 2028): for yy in (ya1, yb1): p.append(f'') if y < 2027: p.append(text((X(y) + X(y + 1)) / 2, yb1 + 24, str(y), "t-ax", "middle")) p.append(text(x0, ya0 - 22, "Highest Kp", "t-ax")) p.append(text(x0, yb0 - 22, "Lowest Dst, nT", "t-ax")) def when(sv): return dt.datetime.strptime(sv, "%Y-%m-%d %H:%M") for s in ks: t = when(s["peak_at"]) x, y = X(dec_year(t)), YK(s["kp"]) ours = t.date() == dt.date(2023, 3, 24) cls_l, cls_d = ("a-stem", "a-dot") if ours else ("m-stem", "m-dot") p.append(f'{esc(long_date(t))}: Kp {s["kp_name"].replace("-", "−")}, daily Ap {s["Ap"]}' f'' f'') for s in ds: t = when(s["min_hour_start"]) x, y = X(dec_year(t)), YD(s["min"]) ours = t.date() == dt.date(2023, 3, 24) final = s["status"] == "final" cls_l = "a-stem" if ours else "m-stem" cls_d = ("a-dot" if ours else ("m-dot" if final else "m-ring")) p.append(f'{esc(long_date(t))}: Dst {minus(s["min"])} nT ({s["status"]})' f'' f'') def kp_of(date): return next(s for s in ks if s["peak_at"].startswith(date)) def d_of(date): return next(s for s in ds if s["min_hour_start"].startswith(date)) a = kp_of("2017-09-08") p.append(text(X(dec_year(when(a["peak_at"]))) + 9, YK(a["kp"]) + 4, "Sep 2017: 8+", "t-val", None, True)) a = kp_of("2023-03-24") p.append(text(X(dec_year(when(a["peak_at"]))) - 10, YK(a["kp"]) - 9, "Mar 2023: 8o", "t-alt", "end", True)) a = kp_of("2024-05-11") p.append(text(X(dec_year(when(a["peak_at"]))) + 9, YK(a["kp"]) + 2, "May 2024: 9o", "t-val", None, True)) a = d_of("2018-08-26") p.append(text(X(dec_year(when(a["min_hour_start"]))) + 9, YD(a["min"]) + 14, f"Aug 2018: {minus(a['min'])}, final", "t-val", None, True)) a = d_of("2023-03-24") p.append(text(X(dec_year(when(a["min_hour_start"]))) - 10, YD(a["min"]) + 16, f"Mar 2023: {minus(a['min'])}, provisional", "t-alt", "end", True)) a = d_of("2024-05-11") p.append(text(X(dec_year(when(a["min_hour_start"]))) + 9, YD(a["min"]) + 4, f"May 2024: {minus(a['min'])}", "t-val", None, True)) label = ("Two panels of storms from March 2017 to October 2026. Top: the highest Kp of each of the 37 storms that reached G3. In the six years " "before March 2023 only September 2017, at 8+, stands above March 2023’s 8o; six later storms do, up to 9o in May 2024. " "Bottom: the lowest Dst of each of the 31 storms at −100 nanotesla or below. Before March 2023’s provisional −163, " "only August 2018’s final −176 is lower; seven later storms are, down to −406 in May 2024.") return (f'' + "".join(p) + "") # ------------------------------------------------------------------ chart 3: the dipole's yearly pace def chart_dipole(dip): W, Hh = 1000, 340 x0, x1, y0, y1 = 58.0, 986.0, 30.0, 290.0 T0, T1 = 1998.0, 2034.0 vmax = 16.0 def X(t): return x0 + (t - T0) / (T1 - T0) * (x1 - x0) def Y(v): return y1 - v / vmax * (y1 - y0) ctx = dip["context_no_test"]["calendar_years_d_abs_g10"] fc = -dip["IGRF14_forecast_2025_2030"]["d_abs_g10_dt"] p = [] for v in (0, 4, 8, 12, 16): p.append(f'') p.append(text(x0 - 8, Y(v) + 4.5, str(v), "t-ax", "end")) bw = (X(1999) - X(1998)) * 0.72 for r in ctx: v = -r["d_abs_g10"] x = (X(r["from"]) + X(r["to"])) / 2 - bw / 2 if r["from"] == ctx[-1]["from"]: continue # 2026: the model's data end in August, so the year is left off the chart p.append(f'January 1, {r["from"]} to January 1, {r["to"]}: {v:.1f} nT weaker' f'') for y in range(1998, 2032, 2): p.append(text((X(y) + X(y + 1)) / 2, y1 + 22, str(y), "t-ax", "middle")) # IGRF-14's forecast p.append(f'') p.append(text(X(2026.5), Y(fc) - 10, f"IGRF-14’s forecast: {fc:.1f}", "t-alt", None, True)) # the storm xs = X(2023 + 81.5 / 365) p.append(f'') p.append(text(xs - 6, y0 + 2, "March 23, 2023", "t-lab", "end", True)) def val(year): return -next(r["d_abs_g10"] for r in ctx if r["from"] == year) for year in (2000, 2018, 2023, 2025): v = val(year) p.append(text((X(year) + X(year + 1)) / 2, Y(v) - 6, f"{v:.1f}", "t-val", "middle", True)) label = ("Bar chart of how much the axial dipole weakened in each calendar year from 1998 to 2025 in CHAOS-8.7, in nanotesla. " f"It falls from {val(2000):.1f} in 2000 to {val(2018):.1f} in 2018, rises to {val(2023):.1f} in 2023 and is {val(2024):.1f} and {val(2025):.1f} " f"in the two years after; IGRF-14’s forecast for 2025 to 2030 is {fc:.1f} a year. A dashed line marks March 23, 2023.") return (f'' + "".join(p) + "") # ------------------------------------------------------------------ chart 4: the sky from Chiefland def chart_sky(geo, st): W, Hh = 760, 734 cx, cy, R = 330.0, 388.0, 250.0 def P(az, alt, r_extra=0.0): r = R * (90.0 - alt) / 90.0 + r_extra a = math.radians(az) return cx + r * math.sin(a), cy - r * math.cos(a) glat = PG.geocentric(PG.LAT) def edge_elev(edge, h, az): d = 0.0 while d <= 40.0: la, lo = PG.dest(glat, PG.LON, az, d) if PG.cd_lat(la, lo) >= edge: return PG.elevation(d, h) d += 0.05 return None def wedge(edge, h, cls, title): azs = [a / 2.0 for a in range(-180, 181)] # -90 .. +90 in half degrees, through north pts_in, pts_out = [], [] for a in azs: e = edge_elev(edge, h, a % 360) if e is not None and e > 0: pts_in.append(P(a % 360, e)) pts_out.append(P(a % 360, 0)) if not pts_in: return "" d = "M" + " L".join(f"{f1(x)} {f1(y)}" for x, y in pts_out) + " L" + " L".join(f"{f1(x)} {f1(y)}" for x, y in reversed(pts_in)) + " Z" return f'{esc(title)}' g2, g7 = geo["G2"], st["G7"] t_a, t_b = g7["hours_allowed_UT"] p = [] # altitude circles and the compass cross for alt in (60, 30): p.append(f'') p.append(f'') p.append(f'') # where auroral light could stand: three cases, widest first cases = [(50.5, 950, "a-w1"), (50.5, 400, "a-w2"), (56.0, 400, "a-w3")] for edge, h, cls in cases: k = g2[f"edge{edge}_h{h}"] sp = k["above_horizon_azimuths"] title = (f"Light at the oval’s edge at {edge:g} degrees, {h} km up: above the horizon from azimuth {sp[0]} through north to {sp[1]} degrees, " f"at most {k['max_elevation']:.1f} degrees high") p.append(wedge(edge, h, cls, title)) # a fourth case, as an outline: the far lower edge of the storm of November 1, 1972 (addendum G4 of the rules) k4 = geo["G4"]["h400"] sp4 = k4["above_horizon_azimuths"] p.append(wedge(40.9, 400, "a-w4", f"Light at an edge of 40.9 degrees, 400 km up (the edge of the storm of November 1, 1972): above the horizon from azimuth {sp4[0]} " f"through north to {sp4[1]} degrees, at most {k4['max_elevation']:.1f} degrees high")) p.append(f'') for az in range(0, 360, 30): xa, ya = P(az, 0) xb, yb = P(az, 0, 7) p.append(f'') # the sky the frame holds, solved from its stars (addendum G7): at the latest start, and at 03:00 UT as a dashed outline def poly(points): return "M" + " L".join(f"{f1(x)} {f1(y)}" for x, y in (P(az, max(alt, 0.0)) for az, alt in points)) + " Z" fr_b, fr_a = g7["frame"][t_b], g7["frame"][t_a] north_end = g7["frame"][f'{g7["exposure_end_if_begun_at_latest_start_UT"]} (26 minutes on)']["most_northerly_sky_west"]["az"] north_b, north_a = fr_b["most_northerly_sky_west"]["az"], fr_a["most_northerly_sky_west"]["az"] p.append(f'The sky in the photograph at {t_b} UT, solved from {g7["matched"]} of its stars: tree line from azimuth {fr_b["tree_line_left_az"]:.0f} to ' f'{fr_b["tree_line_right_az"]:.0f} degrees; its most northerly sky at {north_b:.0f} degrees') p.append(f'The same at {t_a} UT: tree line from azimuth {fr_a["tree_line_left_az"]:.0f} to {fr_a["tree_line_right_az"]:.0f} degrees; its most northerly ' f'sky at {north_a:.0f} degrees') # the red glow: along the tree line from the south to the west, where the photograph's two labels put it glow = [(az, max(alt, 0.0)) for az, alt in g7["tree_line_az_alt"][t_b] if 188.0 <= az <= 280.0] p.append(f'The red glow along the tree line, from the south to the west, where the photograph’s labels put it' f'') # compass letters for az, s in ((0, "N"), (90, "E"), (180, "S"), (270, "W")): x, y = P(az, 0, 34 if az in (0, 180) else 38) p.append(text(x, y + 6, s, "t-comp", "middle")) p.append(text(cx + 5, cy - R * 60 / 90 + 14, "30° up", "t-ax")) p.append(text(cx + 5, cy - R * 30 / 90 + 14, "60°", "t-ax")) p.append(text(cx + 5, cy + 34, "overhead", "t-ax")) # labelled objects: where each stood at the latest start, with its track back to 03:00 UT lab = g7["labelled_objects_0300_to_latest"] objs = [("Gegenschein", "Antisolar point (Gegenschein)", 12, 5), ("Vela remnant", "Vela supernova remnant", 11, 14), ("Sirius", "Sirius", -12, 18), ("Rosette", "Rosette Nebula", 10, -8), ("Orion", "Orion's Belt (Alnilam), for Barnard's Loop", -10, 20), ("Beehive", "Beehive (M44)", 8, -10)] for name, key, dx, dy in objs: (alt_a, alt_b), (az_a, az_b) = lab[key]["alt"], lab[key]["az"] xa, ya = P(az_a, alt_a) xb, yb = P(az_b, alt_b) p.append(f'') p.append(f'{esc(name)}: from altitude {alt_a} degrees, azimuth {az_a} degrees at {t_a} UT to {alt_b} and {az_b} at {t_b} UT' f'') p.append(text(xb + dx, yb + dy, name, "t-sur", "end" if dx < 0 else None, True)) # captions on the chart k = g2["edge50.5_h950"]["above_horizon_azimuths"] p.append(text(cx, cy - R - 114, "Where light from the oval’s edge could stand above the horizon", "t-val", "middle")) p.append(text(cx, cy - R - 95, f"shaded: at the widest, from {k[0]}° through north to {k[1]}°", "t-ax", "middle")) p.append(text(cx, cy - R - 76, f"dashed: for the 1972 storm’s far lower edge, from {sp4[0]}° to {sp4[1]}°", "t-ax", "middle")) p.append(text(cx, cy + R + 64, "The sky in the photograph, by its stars", "t-lab", "middle")) xg, yg = P(228, 0, 22) p.append(text(xg, yg + 6, "The red glow", "t-alt", "end", True)) label = (f"A compass view of the sky from Chiefland, Florida, between {t_a} and {t_b} UT on March 24, 2023, north at the top, the horizon as the outer circle. " f"The sky in the photograph, solved from {g7['matched']} of its stars, runs from the south-east through the south and west to the west-north-west, with no northern sky: " f"its tree line from azimuth {fr_b['tree_line_left_az']:.0f} to {fr_b['tree_line_right_az']:.0f} degrees at {t_b} UT, its upper right corner at {north_b:.0f} degrees then " f"and about {north_end:.0f} by the end of a 26-minute exposure. " "It holds the Gegenschein, the Vela remnant, Sirius, the Rosette, Orion and the Beehive; the red glow runs along its tree line from the south to the west. " f"Light from the auroral oval’s edge could stand above the horizon only in the north: at the widest from {k[0]} degrees through north to {k[1]} degrees " f"for the edges of storms of like strength, and from {sp4[0]} to {sp4[1]} degrees for a far lower edge, that of a stronger storm in 1972, which reaches " "only the photograph’s upper right corner.") return (f'' + "".join(p) + "") def main(): outdir, kyoto = sys.argv[1], sys.argv[2] body = sys.argv[3] if len(sys.argv) > 3 else None def load(name): return json.load(open(os.path.join(outdir, name), encoding="utf-8")) dst, status = read_kyoto(kyoto) charts = {"dst": chart_dst(dst, load("dst_recovery.json")), "storms": chart_storms(load("storm_rank.json")), "dipole": chart_dipole(load("dipole_pace.json")), "sky": chart_sky(load("photo_geometry.json"), load("photo_stars.json"))} if body: s = open(body, encoding="utf-8").read() for name, svg in charts.items(): pat = re.compile(r"().*?()" % (name, name), re.S) if not pat.search(s): sys.exit(f"marker for chart '{name}' not found in {body}") s = pat.sub(lambda m: m.group(1) + "\n" + svg + "\n" + m.group(2), s) with open(body, "w", encoding="utf-8", newline="\n") as f: f.write(s) print("charts written into", body) else: for name, svg in charts.items(): with open(os.path.join(outdir, f"chart_{name}.svg"), "w", encoding="utf-8", newline="\n") as f: f.write(svg + "\n") print("charts written to", outdir) for name, svg in charts.items(): print(f" {name}: {len(svg)} characters") if __name__ == "__main__": main()