#!/usr/bin/env python """Build the event lists for the rieger-tidal-periods re-run. No periods are tested here. Reads the downloads as data, writes CSV lists and a comparison log to ../out/. Paths come from this script's own location. Run with: python -I 01_build_event_lists.py Sources: GLE Oulu GLE database, grid.php (gle.oulu.fi); checked against Table 1 of Stefani et al. 2026 (arXiv 2602.11227v2). S-flares Table 2 of Stefani et al. 2026; checked against Table 1 of Tan et al. 2025 (arXiv 2501.03791v2). NOAA NCEI goes-xrs-report_YYYY.txt (1975 to 2017-06-28), then NOAA SWPC daily solar event reports as archived by NCEI (2017-06-29 on). rudimirz rudimirz.com/flares/flare_data.js, the list the paper says it "basically" used. Parsed as JSON, never executed. """ import csv import datetime as dt import glob import hashlib import json import os import re import sys HERE = os.path.dirname(os.path.abspath(__file__)) ROOT = os.path.dirname(HERE) DL = os.path.join(ROOT, "downloads") OUT = os.path.join(ROOT, "out") os.makedirs(OUT, exist_ok=True) EPOCH = dt.date(1955, 12, 31) def day_index(d): return (d - EPOCH).days def write_csv(path, header, rows): with open(path, "w", newline="\n", encoding="utf-8") as f: w = csv.writer(f, lineterminator="\n") w.writerow(header) w.writerows(rows) log_lines = [] def log(*a): s = " ".join(str(x) for x in a) log_lines.append(s) print(s.encode("ascii", "replace").decode()) # --------------------------------------------------------------------------- # GLE: Oulu list and Table 1 of Stefani et al. 2026 # --------------------------------------------------------------------------- grid = json.load(open(os.path.join(DL, "oulu-gle", "grid.php.json"), encoding="utf-8")) gle = [] sub = [] for g in grid["gles"]: if str(g["gle"]) != "0" and str(g["gle_type"]) == "0": d = dt.date.fromisoformat(g["date"]) gle.append((int(g["gle"]), d, day_index(d))) else: sub.append(g) log("Oulu rows:", len(grid["gles"]), "formal GLEs:", len(gle), "other rows (sub-GLE/ACRE):", len(sub)) tex = open(os.path.join(DL, "arxiv-2602.11227v2", "src-extracted", "stefani.tex"), encoding="utf-8").read() t1 = tex[tex.index("the 72 GLE events considered here"):] t1 = t1[: t1.index("\\end{tabular}")] t1_rows = re.findall(r"(\d+)\s*&\s*(\d{4})/(\d{1,2})/(\d{1,2})\s*&\s*(\d+)", t1) table1 = {int(n): (dt.date(int(y), int(m), int(dd)), int(days)) for n, y, m, dd, days in t1_rows} log("Table 1 rows:", len(table1)) mismatch = [ (n, d, table1[n]) for n, d, di in gle if n not in table1 or table1[n][0] != d or table1[n][1] != di ] log("Oulu vs Table 1 mismatches (number, Oulu date, Table 1):", mismatch) write_csv( os.path.join(OUT, "events_gle.csv"), ["gle", "date", "day_since_1955_12_31"], [(n, d.isoformat(), di) for n, d, di in gle], ) # --------------------------------------------------------------------------- # S-flares: Table 2 of Stefani et al. 2026, Table 1 of Tan et al. 2025 # --------------------------------------------------------------------------- t2 = tex[tex.index("and days elapsed since 1955/12/31 of the 37 S-flare events"):] t2 = t2[: t2.index("\\end{tabular}")] t2_rows = re.findall(r"(\d+)\s*&\s*(\d{4})/(\d{1,2})/(\d{1,2})\s*&\s*(\d+)", t2) sflares = sorted( (int(n), dt.date(int(y), int(m), int(dd)), int(days)) for n, y, m, dd, days in t2_rows ) log("Table 2 rows:", len(sflares)) for n, d, di in sflares: if day_index(d) != di: log(" Table 2 day mismatch", n, d, di, day_index(d)) tan = open(os.path.join(DL, "arxiv-2501.03791v2", "src-extracted", "2024_arXiv_S-flare.tex"), encoding="utf-8").read() tan_tab = tan[tan.index("List of the solar S-class flares"):] tan_tab = tan_tab[: tan_tab.index("\\enddata")] tan_rows = re.findall(r"(\d+)\s*&\s*(\d{8})\s*&\s*(\d+)\s*&\s*X([\d.]+)\s*&\s*(\d+)", tan_tab) tan_dict = { dt.date(int(r[1][:4]), int(r[1][4:6]), int(r[1][6:8])): (float(r[3]), int(r[4])) for r in tan_rows } log("Tan et al. Table 1 rows:", len(tan_rows)) log("S-list dates not in Tan:", [d.isoformat() for _, d, _ in sflares if d not in tan_dict]) log("Tan dates not in S-list:", [d.isoformat() for d in tan_dict if d not in {s[1] for s in sflares}]) write_csv( os.path.join(OUT, "events_sflares.csv"), ["no", "date", "day_since_1955_12_31", "tan2025_class_new_scale", "tan2025_ar"], [(n, d.isoformat(), di, tan_dict.get(d, ("", ""))[0], tan_dict.get(d, ("", ""))[1]) for n, d, di in sflares], ) # --------------------------------------------------------------------------- # NOAA X-class list # --------------------------------------------------------------------------- noaa = [] nf = os.path.join(DL, "ncei-goes-xrs-reports") def parse_ncei_mag(s): # field is 5 characters: letter + 4, e.g. 'X 98 ' = X9.8, 'X120 ' = X12.0, 'X 1 ' = X1, 'X15 ' = X15 body = s[1:] digits = body.strip() if body[0] == " ": # 'X 1 ', 'X 12 ': one-digit integer part, optional one decimal return float(digits[0] + "." + digits[1]) if len(digits) == 2 else float(digits) if len(digits) == 3: return float(digits[:2] + "." + digits[2]) # 'X120' = X12.0 if len(digits) == 2: return float(digits) # 'X15' = X15 raise ValueError(s) files = sorted(glob.glob(os.path.join(nf, "goes-xrs-report_*.txt"))) used = [] ncei_lines_2015 = {} for f in files: b = os.path.basename(f) if "modified" in b: continue used.append(b) year = int(b[16:20]) for line in open(f, encoding="latin-1"): if len(line) > 63 and line[59] == "X": yy, mm, dd = line[5:7], line[7:9], line[9:11] # dates in the report: two-digit year y = 1900 + int(yy) if int(yy) >= 70 else 2000 + int(yy) if y != year: log(" year mismatch", b, line.strip()[:40]) date = dt.date(y, int(mm), int(dd)) mag = parse_ncei_mag(line[59:64]) mx = line[23:27].strip() or line[13:17].strip() ar = line[79:85].strip() noaa.append(dict(date=date, max=mx, mag=mag, ar=ar, sat="GOES<=15", src=b)) log("NCEI reports used:", len(used), used[0], "...", used[-1], "X lines:", len(noaa)) # the modified 2015 file: compare its X lines mod = os.path.join(nf, "goes-xrs-report_2015_modifiedreplacedmissingrows.txt") a = [l[:64] for l in open(os.path.join(nf, "goes-xrs-report_2015.txt"), encoding="latin-1") if len(l) > 63 and l[59] == "X"] b = [l[:64] for l in open(mod, encoding="latin-1") if len(l) > 63 and l[59] == "X"] log("2015 report X lines:", len(a), "modified 2015 report X lines:", len(b), "identical:", a == b) swpc_dir = os.path.join(DL, "ngdc-swpc-daily-events") swpc_files = sorted(glob.glob(os.path.join(swpc_dir, "*", "*events.txt"))) log("SWPC daily event files present:", len(swpc_files)) xra = re.compile( r"^\s*(\d{1,4})\s*\+?\s+([AB]?\d{4}|////)\s+([AB]?\d{4}|////)\s+([AB]?\d{4}|////)\s+(G\d\d|\S+)\s+(\S)\s+XRA\s+1-8A\s+([A-Z][\d.]+)\s+(\S+)\s*(\d{4,5})?" ) sw_seen = set() days_with_files = set() swpc_rows = [] for f in swpc_files: b = os.path.basename(f) date = dt.date(int(b[:4]), int(b[4:6]), int(b[6:8])) days_with_files.add(date) for line in open(f, encoding="latin-1"): if "XRA" not in line: continue m = xra.match(line) if not m: if "XRA" in line and "1-8A" in line and re.search(r"\bX\d", line): log(" unparsed X line", b, line.strip()) continue cls = m.group(7) if cls[0] != "X": continue key = (date, m.group(3)) if key in sw_seen: log(" duplicate XRA X line skipped", b, line.strip()) continue sw_seen.add(key) swpc_rows.append( dict(date=date, max=m.group(3), mag=float(cls[1:]), ar=(m.group(9) or ""), sat=m.group(5), src=b) ) noaa.extend(swpc_rows) noaa.sort(key=lambda r: (r["date"], r["max"])) start, end = dt.date(2017, 6, 29), dt.date(2026, 11, 3) missing = [] d = start while d <= end: if d not in days_with_files: missing.append(d.isoformat()) d += dt.timedelta(days=1) log("SWPC days missing:", len(missing), missing[:40]) log("SWPC X lines parsed:", len(swpc_rows)) for r in swpc_rows: pass write_csv( os.path.join(OUT, "events_noaa_x.csv"), ["date", "day_since_1955_12_31", "max_time", "reported_class_X", "ar", "instrument", "source_file"], [ (r["date"].isoformat(), day_index(r["date"]), r["max"], f'{r["mag"]:g}', r["ar"], r["sat"], r["src"]) for r in noaa ], ) # --------------------------------------------------------------------------- # rudimirz list (read as JSON text, never run) # --------------------------------------------------------------------------- s = open(os.path.join(DL, "rudimirz-flares", "flare_data.js"), encoding="utf-8").read() rows = json.loads(s[s.index("[") : s.rindex("]") + 1]) rud = [] for r in rows: if r["Class"] == "X": when = r["Peak"] or r["Start"] d = dt.date.fromisoformat(when[:10]) rud.append(dict(date=d, peak=when, mag=float(r["Magnitude"]), ar=r["Active_Region"] or "")) rud.sort(key=lambda r: r["peak"]) write_csv( os.path.join(OUT, "events_rudimirz_x.csv"), ["date", "day_since_1955_12_31", "peak", "class_X", "ar"], [(r["date"].isoformat(), day_index(r["date"]), r["peak"], f'{r["mag"]:g}', r["ar"]) for r in rud], ) log("rudimirz rows:", len(rows), "X rows:", len(rud), "first:", rows[0]["Start"], "last:", rows[-1]["Start"]) months = {} for r in rows: when = r["Peak"] or r["Start"] if when: months[when[:7]] = months.get(when[:7], 0) + 1 # months with zero rows inside the span, any class all_months = [] y, m = 1975, 9 while (y, m) <= (2026, 5): all_months.append(f"{y}-{m:02d}") m += 1 if m == 13: y, m = y + 1, 1 log("rudimirz months with no rows at all:", [x for x in all_months if x not in months]) # --------------------------------------------------------------------------- # Compare NOAA and rudimirz, X-class # --------------------------------------------------------------------------- def by_date(lst): out = {} for r in lst: out.setdefault(r["date"], []).append(r["mag"]) return out nd, rd = by_date(noaa), by_date(rud) last_rud = max(rd) only_noaa = [] only_rud = [] for d_ in sorted(set(nd) | set(rd)): if d_ > last_rud: continue a = sorted(nd.get(d_, [])) b = sorted(rd.get(d_, [])) if a != b: only_noaa.append((d_.isoformat(), a, b)) log("Dates where NOAA and rudimirz X lists differ (date, NOAA, rudimirz):", len(only_noaa)) for row in only_noaa: log(" ", row) # --------------------------------------------------------------------------- # Union with the S-list, as the paper describes # --------------------------------------------------------------------------- def nested_union(flares, sf, thresholds=(6, 3, 2, 1)): """Return dict threshold -> (days, S-flares added). A catalogue flare is the same flare as an S-flare only if it lies within one day and has class X5 or above: S-flares are X7 or above on the old scale, and Tan et al. 2025 work on the new one (old class times 1.43).""" out = {} for th in thresholds: cat = [r for r in flares if r["mag"] >= th] used_idx = set() days = [] extra = [] for n, d, di in sf: cand = [ (i, r) for i, r in enumerate(cat) if abs((r["date"] - d).days) <= 1 and i not in used_idx and r["mag"] >= 5 ] if cand: i, r = max(cand, key=lambda c: (c[1]["date"] == d, c[1]["mag"])) used_idx.add(i) days.append(di) else: extra.append(d) days.append(di) for i, r in enumerate(cat): if i not in used_idx: days.append(day_index(r["date"])) out[th] = (sorted(days), extra) return out # the paper names rudimirz; that file stops on 2026-05-03, so the X-flares after it come from the # SWPC reports for the comparison of counts rud_ext = list(rud) + [dict(date=r["date"], peak="", mag=r["mag"], ar=r["ar"]) for r in noaa if r["date"] > dt.date(2026, 5, 3)] for name, lst, in (("rudimirz, extended by SWPC after 2026-05-03", rud_ext), ("NOAA", noaa)): for cut in (dt.date(2026, 2, 1), dt.date(2026, 2, 28), dt.date(2026, 5, 3), dt.date(2026, 6, 30), dt.date(2026, 7, 4), dt.date(2026, 10, 12), dt.date(2026, 11, 3)): sel = [r for r in lst if r["date"] <= cut] u = nested_union(sel, sflares) log( name, "cut-off", cut, "plain X1+/X2+/X3+/X6+ counts:", sum(r["mag"] >= 1 for r in sel), sum(r["mag"] >= 2 for r in sel), sum(r["mag"] >= 3 for r in sel), sum(r["mag"] >= 6 for r in sel), " union with S-list X6+/X3+/X2+/X1+:", len(u[6][0]), len(u[3][0]), len(u[2][0]), len(u[1][0]), " (paper: 49/137/252/569)", ) u = nested_union(rud_ext, sflares) log("S-flares absent from the rudimirz list at threshold 6:", [d.isoformat() for d in u[6][1]]) log("S-flares absent from the rudimirz list at threshold 1:", [d.isoformat() for d in u[1][1]]) u = nested_union(noaa, sflares) log("S-flares absent from the NOAA list at threshold 6:", [d.isoformat() for d in u[6][1]]) log("S-flares absent from the NOAA list at threshold 1:", [d.isoformat() for d in u[1][1]]) log("X flares in the SWPC reports after 2026-02-01:") for r in noaa: if r["date"] > dt.date(2026, 2, 1): log(" ", r["date"], r["max"], f'X{r["mag"]:g}', r["ar"], r["sat"]) with open(os.path.join(OUT, "list_comparison.log"), "w", newline="\n", encoding="utf-8") as f: f.write("\n".join(log_lines) + "\n")