#!/usr/bin/env python3 """The Sun and space weather before S0 News of November 19, 2026: the five tests of RULES_sun.txt. Fact-Checked Science, "S0 News, November 19, 2026", section 2. Standard library only (Python 3.9 or later). Three steps, each optional: python3 -I space_weather.py fetch Downloads the public files we read on November 19, 2026, from their makers, under the plain client name "factchecked-research/1.0", into , and says whether each matches the SHA-256 of our copy. NOAA's seven-day lists, its alerts, the real-time solar-wind files and GFZ's nowcast roll over or are revised, so later copies differ from ours; the dated FTP files (forecasts, ACE lists) keep for a while. python3 -I space_weather.py extract [extracts-folder] Turns the downloaded files (found anywhere under ) into the six small extracts this page hosts: the GOES-18 flare list, Kp from GFZ and NOAA, hourly solar wind, CACTus's CMEs, SWPC's storm alerts and the 3-day forecast of 00:30 UTC on November 19. Run on our copies, it writes the hosted extracts exactly. python3 -I space_weather.py run [extracts-folder] [out-file] Runs tests T1-T5 on the extracts (default: this script's own folder) and prints the result, as in space_weather.txt. Credits: NOAA SWPC (GOES-18 X-ray flares, Kp estimates, alerts, forecasts, ACE and RTSW real-time solar wind; public domain); GFZ Helmholtz Centre for Geosciences (Kp nowcast, CC BY 4.0; Matzka et al. 2021, doi:10.5880/Kp.0001); SIDC, Royal Observatory of Belgium (CACTus CME catalogue, from SOHO/LASCO). """ import csv import datetime as dt import hashlib import html import json import os import re import statistics as st import sys import urllib.request from collections import Counter UTC = dt.timezone.utc PUB = dt.datetime(2026, 11, 19, 11, 59, 19, tzinfo=UTC) # the video's publication time W0, W1 = PUB - dt.timedelta(hours=24), PUB # "the last 24 hours" A0, A1 = dt.datetime(2026, 11, 18, tzinfo=UTC), dt.datetime(2026, 11, 19, 12, tzinfo=UTC) # "yesterday" to 12 UT AGENT = "factchecked-research/1.0" # (file, URL, SHA-256 of our copy, fetched UTC) INPUTS = [ ("xray-flares-7-day.json", "https://services.swpc.noaa.gov/json/goes/primary/xray-flares-7-day.json", "cc48ccfa45b75e7955c7e9c131a21f3c31008a59ebbe0cb52ccfbb05b3fdb31d", "2026-11-19T16:36:17Z"), ("noaa-planetary-k-index.json", "https://services.swpc.noaa.gov/products/noaa-planetary-k-index.json", "d55722b2d1f4db5cdfe16140fc0d2ab1262e1d7fb6185f1e05e31587304d84b8", "2026-11-19T16:36:46Z"), ("alerts.json", "https://services.swpc.noaa.gov/products/alerts.json", "0dee47df193dc4bc9610a25a4744096e34aa7ccfa4b2b44b4cac1ed6f4dbd207", "2026-11-19T16:36:47Z"), ("Kp_ap_nowcast.txt", "https://kp.gfz.de/app/files/Kp_ap_nowcast.txt", "ddeb2750a0afbb8a5dc7987c58ffe135c2d9a0f044588464f477574c4ec640c6", "2026-11-19T16:36:48Z"), ("latestCMEs.html", "https://www.sidc.be/cactus/out/latestCMEs.html", "27d23ef6ff1caecd9c81a568cb6c3d1d05f5b8164753d2d8b1c7d97f3f8967ef", "2026-11-19T16:36:50Z"), ("rtsw_wind_1m.json", "https://services.swpc.noaa.gov/json/rtsw/rtsw_wind_1m.json", "7b1d553233918899a913d62c38e50cdcd518933ba747346b1210f94af66becc0", "2026-11-19T16:37:00Z"), ("rtsw_mag_1m.json", "https://services.swpc.noaa.gov/json/rtsw/rtsw_mag_1m.json", "480d86f10d5d906202222dfb79616a0dd4c6769522f072dae07b4a92dd79bd29", "2026-11-19T16:37:01Z"), ("20261117_ace_swepam_1m.txt", "ftp://ftp.swpc.noaa.gov/pub/lists/ace/20261117_ace_swepam_1m.txt", "3d049192a208b76c4cbb9b20ed3e15202d94dfd6520eafef88cf9fe3bb373952", "2026-11-19T16:37:37Z"), ("20261117_ace_mag_1m.txt", "ftp://ftp.swpc.noaa.gov/pub/lists/ace/20261117_ace_mag_1m.txt", "85b457800fd327dea645807e84b6fd0978c610b1f6eeb95901e0e295093a2af0", "2026-11-19T16:37:38Z"), ("20261118_ace_swepam_1m.txt", "ftp://ftp.swpc.noaa.gov/pub/lists/ace/20261118_ace_swepam_1m.txt", "0a1327c3c2adaa978799b5843913f65316eaa5070a83b16061f542cba7add4b5", "2026-11-19T16:37:40Z"), ("20261118_ace_mag_1m.txt", "ftp://ftp.swpc.noaa.gov/pub/lists/ace/20261118_ace_mag_1m.txt", "e532e4f6f9bd6501b401bfdc88009fb20697fd619f3631cb950af0fd8b4f06b3", "2026-11-19T16:37:42Z"), ("20261119_ace_swepam_1m.txt", "ftp://ftp.swpc.noaa.gov/pub/lists/ace/20261119_ace_swepam_1m.txt", "199a3ccb44024d8db286d3ed29bd91b07162fd319070fa0e23fe28ff4d2e2e32", "2026-11-19T16:37:43Z"), ("20261119_ace_mag_1m.txt", "ftp://ftp.swpc.noaa.gov/pub/lists/ace/20261119_ace_mag_1m.txt", "d0f8008cc99d4e11be3674c242ccc999e7de8da84aef29801557280f36c9d761", "2026-11-19T16:37:44Z"), ("11190030three_day_forecast.txt", "ftp://ftp.swpc.noaa.gov/pub/forecasts/three_day/11190030three_day_forecast.txt", "6514a86e2fb5c05d3b368033eae5562f0a3866b066050b05c8e3524738b9cb57", "2026-11-19T16:38:01Z"), ] EXTRACTS = ["goes18-flares-2026-11-12-19.csv", "kp-2026-11-17-19.csv", "solar-wind-hourly-2026-11-17-19.csv", "cactus-cmes-2026-11-14-19.csv", "swpc-alerts-2026-11-18-19.csv", "swpc-3day-2026-11-19-0030.json"] def t(s, fmt): return dt.datetime.strptime(s, fmt).replace(tzinfo=UTC) def iso(d): return d.strftime("%Y-%m-%dT%H:%M:%SZ") def sha(p): return hashlib.sha256(open(p, "rb").read()).hexdigest() def write_csv(path, header, comment, rows): with open(path, "w", encoding="utf-8", newline="\n") as f: f.write(comment + "\n") w = csv.writer(f, lineterminator="\n") w.writerow(header) w.writerows(rows) def read_csv(path): with open(path, encoding="utf-8") as f: lines = [l for l in f if not l.startswith("#")] return list(csv.DictReader(lines)) # ---------------------------------------------------------------- fetch def fetch(folder): os.makedirs(folder, exist_ok=True) for name, url, ours, when in INPUTS: path = os.path.join(folder, name) try: req = urllib.request.Request(url, headers={"User-Agent": AGENT}) with urllib.request.urlopen(req, timeout=120) as r, open(path, "wb") as f: f.write(r.read()) h = sha(path) print(f"{name}: {'matches our copy' if h == ours else 'differs from our copy of ' + when} ({h[:16]})") except Exception as e: # report and go on: a later copy may simply be gone print(f"{name}: not fetched ({e})") # ---------------------------------------------------------------- extract def find(folder, name): for base, _, files in os.walk(folder): if name in files: return os.path.join(base, name) sys.exit(f"{name} not found under {folder}") def extract(folder, out): os.makedirs(out, exist_ok=True) for name, url, ours, when in INPUTS: p = find(folder, name) print(f"{name}: {'our copy' if sha(p) == ours else 'NOT our copy: the extracts will differ from the hosted ones'}") # 1 flares fl = json.load(open(find(folder, "xray-flares-7-day.json"), encoding="utf-8")) rows = sorted([(f["begin_time"], f["max_time"], f["end_time"], f["max_class"], f["max_xrlong"], f["satellite"]) for f in fl], key=lambda r: r[1]) write_csv(os.path.join(out, EXTRACTS[0]), ["begin_utc", "max_utc", "end_utc", "max_class", "peak_flux_w_m2", "satellite"], "# NOAA SWPC, GOES primary X-ray flare list (xray-flares-7-day.json), copy of 2026-11-19T16:36:17Z. Public domain; credit NOAA SWPC.", rows) # 2 Kp gfz = {} for line in open(find(folder, "Kp_ap_nowcast.txt"), encoding="utf-8"): if line[:1].isdigit(): v = line.split() gfz[t(f"{v[0]} {v[1]} {v[2]} {int(float(v[3])):02d}", "%Y %m %d %H")] = (v[7], v[8], v[9]) noaa = {t(r["time_tag"][:13], "%Y-%m-%dT%H"): r["Kp"] for r in json.load(open(find(folder, "noaa-planetary-k-index.json"), encoding="utf-8"))} rows = [(iso(k), g[0], g[1], g[2], noaa.get(k, "")) for k, g in sorted(gfz.items()) if dt.datetime(2026, 11, 17, tzinfo=UTC) <= k < dt.datetime(2026, 11, 20, tzinfo=UTC)] write_csv(os.path.join(out, EXTRACTS[1]), ["start_utc", "gfz_kp", "gfz_ap", "gfz_definitive", "noaa_estimated_kp"], "# Kp for 3-hour intervals: GFZ Helmholtz Centre for Geosciences, Kp_ap_nowcast.txt (CC BY 4.0; Matzka et al. 2021, doi:10.5880/Kp.0001; " "definitive = 1, preliminary = 0; -1.000 = not yet available), copy of 2026-11-19T16:36:48Z; NOAA SWPC's estimated planetary Kp (public domain), copy of 2026-11-19T16:36:46Z.", rows) # 3 solar wind, hourly def ace(kind): rr = [] for d in ("20261117", "20261118", "20261119"): for line in open(find(folder, f"{d}_ace_{kind}_1m.txt"), encoding="utf-8"): if line[:1].isdigit(): v = line.split() rr.append((t(" ".join(v[0:4]), "%Y %m %d %H%M"), int(v[6]), [float(x) for x in v[7:]])) return rr hours = {} for tt, s, vals in ace("swepam"): h = hours.setdefault(tt.replace(minute=0), {"sp": [], "spn": 0, "bt": [], "bz": []}) h["spn"] += 1 if s == 0 and vals[1] > -9000: h["sp"].append(vals[1]) for tt, s, vals in ace("mag"): h = hours.setdefault(tt.replace(minute=0), {"sp": [], "spn": 0, "bt": [], "bz": []}) if s == 0 and vals[3] > -900: h["bt"].append(vals[3]) if s == 0 and vals[2] > -900: h["bz"].append(vals[2]) rows = [] for k in sorted(hours): h = hours[k] rows.append((iso(k), "ACE list", f"{st.mean(h['sp']):.4f}" if h['sp'] else "", len(h['sp']), h["spn"], f"{st.mean(h['bt']):.4f}" if h['bt'] else "", len(h['bt']), f"{min(h['bz']):.1f}" if h["bz"] else "")) rw = json.load(open(find(folder, "rtsw_wind_1m.json"), encoding="utf-8")) rm = json.load(open(find(folder, "rtsw_mag_1m.json"), encoding="utf-8")) rh = {} for r in rw: if r.get("active") and r.get("proton_speed") is not None: rh.setdefault(t(r["time_tag"][:13], "%Y-%m-%dT%H"), {"sp": [], "bt": [], "src": Counter()})["sp"].append(float(r["proton_speed"])) rh[t(r["time_tag"][:13], "%Y-%m-%dT%H")]["src"][r["source"]] += 1 for r in rm: if r.get("active") and r.get("bt") is not None: rh.setdefault(t(r["time_tag"][:13], "%Y-%m-%dT%H"), {"sp": [], "bt": [], "src": Counter()})["bt"].append(float(r["bt"])) for k in sorted(rh): h = rh[k] src = "+".join(f"{s}:{n}" for s, n in sorted(h["src"].items())) rows.append((iso(k), f"RTSW active ({src})", f"{st.mean(h['sp']):.4f}" if h['sp'] else "", len(h['sp']), "", f"{st.mean(h['bt']):.4f}" if h['bt'] else "", len(h['bt']), "")) write_csv(os.path.join(out, EXTRACTS[2]), ["hour_utc", "source", "speed_mean_km_s", "speed_minutes_used", "speed_minutes_listed", "bt_mean_nt", "bt_minutes_used", "bz_gsm_min_nt"], "# Hourly means of 1-minute real-time solar wind, our averaging: NOAA SWPC's ACE lists (SWEPAM, MAG; status-0 minutes only) of 17-19 Nov 2026, " "and SWPC's RTSW files (active spacecraft only; last 24 h before 2026-11-19T16:37Z). Real-time data, not science quality. Public domain; credit NOAA SWPC.", rows) # 4 CACTus s = open(find(folder, "latestCMEs.html"), encoding="utf-8", errors="replace").read() s = html.unescape(re.sub(r"<[^>]+>", " ", s)) part = re.split(r"#\s*Flow\s*\|", re.split(r"#\s*CME\s*\|\s*t0", s)[1])[0] rows = [] for line in part.splitlines(): c = [x.strip() for x in line.split("|")] if len(c) >= 10 and c[0].isdigit(): rows.append((c[0], c[1], int(c[2]), int(c[3]), int(c[4]), int(c[5]), int(c[6]), int(c[7]), int(c[8]), c[9])) write_csv(os.path.join(out, EXTRACTS[3]), ["cme", "onset_utc", "liftoff_hours", "principal_angle_deg", "width_deg", "median_speed_km_s", "speed_sd_km_s", "min_speed_km_s", "max_speed_km_s", "halo_flag"], "# CACTus CME catalogue (SIDC, Royal Observatory of Belgium; SOHO/LASCO C2 and C3), list issued Thu Nov 19 13:54:06 2026, CMEs only (not flows). " "Principal angle counterclockwise from solar north. Credit SIDC/ROB.", rows) # 5 alerts al = json.load(open(find(folder, "alerts.json"), encoding="utf-8")) rows = [] for a in sorted(al, key=lambda a: a["issue_datetime"]): if "2026-11-18" <= a["issue_datetime"] < "2026-11-19T12": m = a["message"].replace("\r", "") keep = [l.strip() for l in m.split("\n") if l.startswith(("ALERT", "WARNING", "EXTENDED", "Threshold", "Noaa Scale", "Valid", "Now Valid", "Synoptic"))] rows.append((a["product_id"], a["issue_datetime"][:16], " | ".join(keep))) write_csv(os.path.join(out, EXTRACTS[4]), ["product_id", "issued_utc", "key_lines"], "# NOAA SWPC alerts and warnings issued 18 Nov 00:00 to 19 Nov 12:00 UTC (alerts.json, copy of 2026-11-19T16:36:47Z): their key lines only. Public domain; credit NOAA SWPC.", rows) # 6 3-day forecast f = open(find(folder, "11190030three_day_forecast.txt"), encoding="utf-8").read() tab = re.findall(r"^(\d\d-\d\dUT)\s+([\d.]+)", f, flags=re.M) rat = re.search(r"Rationale: (.*?)\n\n", f, flags=re.S).group(1).replace("\n", " ") great = re.search(r"The greatest expected 3 hr Kp for (.*?)\n\n", f, flags=re.S).group(0).replace("\n", " ").strip() obs = re.search(r"The greatest observed 3 hr Kp (.*?)\n", f, flags=re.S).group(0).replace("\n", " ").strip() doc = {"source": "NOAA SWPC, 3-day forecast issued 2026 Nov 19 0030 UTC (ftp three_day/11190030three_day_forecast.txt). Public domain; credit NOAA SWPC.", "issued_utc": "2026-11-19T00:30Z", "observed_line": obs, "greatest_expected_line": great, "kp_breakdown_nov19": [{"interval": a, "kp": float(b)} for a, b in tab], "geomagnetic_rationale": rat} with open(os.path.join(out, EXTRACTS[5]), "w", encoding="utf-8", newline="\n") as fh: json.dump(doc, fh, indent=1, ensure_ascii=False) fh.write("\n") for n in EXTRACTS: print(f"wrote {n} ({sha(os.path.join(out, n))[:16]})") # ---------------------------------------------------------------- run def cls(flux): for lim, c in ((1e-4, "X"), (1e-5, "M"), (1e-6, "C"), (1e-7, "B")): if flux >= lim: return c return "A" def kps(x): n = round(x * 3) b, r = divmod(n, 3) return f"{b + 1}-" if r == 2 else f"{b}{'o' if r == 0 else '+'}" def run(folder, outp): out = [] P = out.append P(f"Window: {W0:%Y-%m-%d %H:%M:%S} to {W1:%Y-%m-%d %H:%M:%S} UTC (24 h before publication)") fl = read_csv(os.path.join(folder, EXTRACTS[0])) P(f"\nT1 GOES primary flare list: {len(fl)} entries, satellites {sorted({f['satellite'] for f in fl})}, " f"first max {min(f['max_utc'] for f in fl)}, last {max(f['max_utc'] for f in fl)}") win = [f for f in fl if W0 <= t(f["max_utc"][:19], "%Y-%m-%dT%H:%M:%S") < W1] prev = [f for f in fl if W0 - dt.timedelta(hours=24) <= t(f["max_utc"][:19], "%Y-%m-%dT%H:%M:%S") < W0] def summ(lst): by = Counter(cls(float(f["peak_flux_w_m2"])) for f in lst) return dict(sorted(by.items())) for f in win: P(f" {f['max_utc'][:16]} {f['max_class']:>5} flux {float(f['peak_flux_w_m2']):.2e} " f"begin {f['begin_utc'][11:16]} end {f['end_utc'][11:16]}") bw = summ(win) big = max(win, key=lambda f: float(f["peak_flux_w_m2"])) P(f" in window: {len(win)} flares, by class {bw}; largest {big['max_class']} at {big['max_utc'][:16]}") P(f" T1 {'HOLDS' if not (bw.get('M') or bw.get('X')) else 'FAILS'}: M or X in window = {bw.get('M', 0) + bw.get('X', 0)}") mx = [f"{f['max_class']} {f['max_utc'][:16]}" for f in prev if cls(float(f['peak_flux_w_m2'])) in "MX"] P(f" preceding 24 h: {len(prev)} flares, by class {summ(prev)}; M/X: {mx}") P(f" M/X anywhere in the 7-day list: {[f['max_class'] + ' ' + f['max_utc'][:16] for f in fl if cls(float(f['peak_flux_w_m2'])) in 'MX']}") P("\nT2 CACTus CMEs (not flows) with onset in the window:") for c in read_csv(os.path.join(folder, EXTRACTS[3])): if W0 <= t(c["onset_utc"], "%Y/%m/%d %H:%M") < W1: w = int(c["width_deg"]) P(f" CME {c['cme']} onset {c['onset_utc']} pa {int(c['principal_angle_deg'])} width {w} v {int(c['median_speed_km_s'])} km/s " f"halo flag '{c['halo_flag']}'" + (" WIDTH>=180" if w >= 180 else "")) sw = read_csv(os.path.join(folder, EXTRACTS[2])) ace = [r for r in sw if r["source"] == "ACE list"] rts = [r for r in sw if r["source"].startswith("RTSW")] def hourly(rows, mean, n): return {t(r["hour_utc"], "%Y-%m-%dT%H:%M:%SZ"): float(r[mean]) for r in rows if r[mean] and int(r[n]) >= 30} def rng(h, a, b): v = {k: x for k, x in h.items() if a <= k < b} if not v: return "no data" kmax = max(v, key=v.get) kmin = min(v, key=v.get) return f"{len(v)} h; min {v[kmin]:.0f} at {kmin:%d %H}h, max {v[kmax]:.1f} at {kmax:%d %H}h" spd, bt = hourly(ace, "speed_mean_km_s", "speed_minutes_used"), hourly(ace, "bt_mean_nt", "bt_minutes_used") P("\nT3 ACE real-time (SWPC lists), 60-min means of status-0 minutes (>=30 per hour):") for a, b, lab in ((dt.datetime(2026, 11, 17, tzinfo=UTC), A0, "17 Nov"), (A0, dt.datetime(2026, 11, 19, tzinfo=UTC), "18 Nov"), (dt.datetime(2026, 11, 19, tzinfo=UTC), A1, "19 Nov 00-12")): P(f" {lab}: speed {rng(spd, a, b)} km/s; Bt {rng(bt, a, b)} nT") inwin = [r for r in ace if A0 <= t(r["hour_utc"], "%Y-%m-%dT%H:%M:%SZ") < A1] P(f" ACE SWEPAM minutes 18 Nov 00 - 19 Nov 12 with status 0: {sum(int(r['speed_minutes_used']) for r in inwin)} of " f"{sum(int(r['speed_minutes_listed']) for r in inwin)}") P(f" ACE Bz (GSM) minimum 18 Nov 00 - 19 Nov 12: {min(float(r['bz_gsm_min_nt']) for r in inwin if r['bz_gsm_min_nt']):.1f} nT") srcs = Counter() for r in rts: for part in r["source"][len("RTSW active ("):-1].split("+"): s, n = part.split(":") srcs[s] += int(n) P(f" RTSW active sources (wind): {dict(srcs)}; hours {rts[0]['hour_utc']} .. {rts[-1]['hour_utc']}") rs, rb = hourly(rts, "speed_mean_km_s", "speed_minutes_used"), hourly(rts, "bt_mean_nt", "bt_minutes_used") P(f" RTSW active source, to 19 Nov 12h: speed {rng(rs, A0, A1)} km/s; Bt {rng(rb, A0, A1)} nT") vmax = max(v for d in (spd, rs) for k, v in d.items() if A0 <= k < A1) bmax = max(v for d in (bt, rb) for k, v in d.items() if A0 <= k < A1) P(f" T3(b) {'HOLDS' if vmax < 500 and bmax < 15 else 'FAILS'}: max 60-min speed {vmax:.0f} km/s (<500), " f"max 60-min Bt {bmax:.1f} nT (<15)") P("\nT4 Kp, 18 Nov 00 UT to 19 Nov 12 UT (GFZ nowcast; NOAA estimated planetary Kp):") n5 = 0 for r in read_csv(os.path.join(folder, EXTRACTS[1])): k = t(r["start_utc"], "%Y-%m-%dT%H:%M:%SZ") if A0 <= k < A1: g = float(r["gfz_kp"]) flag = "" if g >= 4.66: n5 += 1 flag = " <- storm level (GFZ >= 5-)" P(f" {k:%d %H}-{(k + dt.timedelta(hours=3)):%H} UT GFZ {g:.3f} ({kps(g)}, D={r['gfz_definitive']}) NOAA {float(r['noaa_estimated_kp'])}{flag}") P(f" T4 {'HOLDS' if 1 <= n5 <= 2 else 'FAILS'}: {n5} interval(s) at GFZ Kp >= 5-") for a in read_csv(os.path.join(folder, EXTRACTS[4])): if a["product_id"] in ("K05A", "K05W", "K06A", "K06W", "K07A"): P(f" SWPC {a['product_id']} issued {a['issued_utc']}: {a['key_lines']}") fc = json.load(open(os.path.join(folder, EXTRACTS[5]), encoding="utf-8")) rows = fc["kp_breakdown_nov19"] P("\nT5 SWPC 3-day forecast issued 19 Nov 00:30 UTC, 19 Nov column: " + ", ".join(f"{r['interval']} {r['kp']:.2f}" for r in rows)) mxf = max(r["kp"] for r in rows) P(f" largest expected Kp on 19 Nov {mxf}; rationale: {fc['geomagnetic_rationale']}") P(f" T5 {'HOLDS' if mxf < 4.66 and 'No G1' in fc['geomagnetic_rationale'] else 'FAILS'}") text = "\n".join(out) + "\n" if outp: with open(outp, "w", encoding="utf-8", newline="\n") as fh: fh.write(text) sys.stdout.reconfigure(encoding="utf-8") print(text, end="") def main(): here = os.path.dirname(os.path.abspath(__file__)) a = sys.argv[1:] if not a or a[0] not in ("fetch", "extract", "run"): sys.exit(__doc__) if a[0] == "fetch": fetch(a[1] if len(a) > 1 else os.path.join(os.getcwd(), "space-weather-inputs")) elif a[0] == "extract": extract(a[1], a[2] if len(a) > 2 else here) else: run(a[1] if len(a) > 1 else here, a[2] if len(a) > 2 else None) if __name__ == "__main__": main()