"""Shared helpers for the florida-aurora-cycle-25 checks (Fact-Checked Science). Standard library only. Readers parse the downloaded files as data. Nothing here fetches anything. """ import csv import datetime as dt import math import os import re KP_THR = {"Kp>=9-": 8.667, "Kp>=8-": 7.667, "Kp>=8o": 8.0} DST_THR = {"Dst<=-200": -200, "Dst<=-300": -300} STRATA = ["Kp>=9-", "Kp>=8-", "Kp>=8o", "Dst<=-200", "Dst<=-300"] ERA0 = (dt.datetime(1986, 1, 1), dt.datetime(2019, 12, 1)) # "1986-2019Nov": start <= t < end C25_START = dt.datetime(2019, 12, 1) FREEZE = dt.datetime(2026, 10, 30, 14) # the note's data freeze DST_LAST = dt.datetime(2026, 10, 1) # Kyoto: provisional to 2026-09-30 def poisson_sf(k, lam): """Exact one-sided P(X >= k | lam).""" return 1.0 - sum(math.exp(-lam) * lam ** i / math.factorial(i) for i in range(k)) def fisher_one_sided(h1, n1, h0, n0): """P(hits in group 1 >= h1 | margins fixed). Group 1: h1 hits of n1 storms; group 0: h0 of n0.""" N, K = n1 + n0, h1 + h0 return sum(math.comb(K, x) * math.comb(N - K, n1 - x) for x in range(h1, min(K, n1) + 1)) / math.comb(N, n1) def fisher_min_p(n1, n0, K): """The smallest one-sided p these margins allow (all of group 1 hit, if K allows).""" h1 = min(n1, K) return fisher_one_sided(h1, n1, K - h1, n0) def binom_sf(k, n, q): """Exact P(X >= k | n, q).""" return sum(math.comb(n, i) * q ** i * (1 - q) ** (n - i) for i in range(k, n + 1)) def sig(x, n=3): if x == 0: return "0" return f"{x:.{n - 1}e}" if abs(x) < 1e-3 else f"{x:.{n}g}" def kpname(k): i = int(round(k * 3)) base = (i + 1) // 3 third = i - 3 * base return f"{base}{'-' if third == -1 else '+' if third == 1 else 'o'}" def read_kp(path): """{datetime of each three-hour interval's start: Kp}, and {date: (Ap, D flag)}.""" kp, day = {}, {} for line in open(path, encoding="utf-8", errors="replace"): if line.startswith("#") or not line.strip(): continue f = line.split() d = dt.datetime(int(f[0]), int(f[1]), int(f[2])) vals = [float(x) for x in f[7:15]] for i, v in enumerate(vals): if v >= 0: kp[d + dt.timedelta(hours=3 * i)] = v day[d.date()] = (int(f[23]), int(f[-1])) return kp, day def read_dst_month(path): """{datetime of each hour's start: Dst}. Kyoto's column k is the hour ending at k UT, so its stamp is k-1 UT. Fixed-width table: after the day number, 24 values of 4 characters, with one extra space after every eighth.""" raw = open(path, encoding="utf-8", errors="replace").read() txt = re.sub(r"<[^>]+>", "", raw) m = re.search(r"\n\s+([A-Z]+)\s+(\d{4})\s*\n", txt) month = dt.datetime.strptime(m.group(1).title() + " " + m.group(2), "%B %Y") kind = "final" if "(FINAL)" in txt else "provisional" if "(PROVISIONAL)" in txt else "real-time" if "REAL-TIME" in txt.upper() else "unknown" out = {} for line in txt.splitlines(): if len(line) < 60 or not line[:2].strip().isdigit(): continue dnum = int(line[:2]) body = line[2:] vals = [int(v) for v in re.findall(r"-?\d+", body.replace("-", " -"))] fixed, pos = [], 0 try: for i in range(24): if i % 8 == 0: pos += 1 fixed.append(int(body[pos:pos + 4])) pos += 4 except ValueError: fixed = None if len(vals) < 24: continue if fixed is not None and fixed != vals[:24]: raise ValueError(f"parse disagreement in {path} day {dnum}: {fixed} vs {vals[:24]}") for k, v in enumerate(vals[:24]): if abs(v) < 9000: out[month.replace(day=dnum) + dt.timedelta(hours=k)] = v return out, kind def read_dst_folder(folder): """All Kyoto months in the folder (dst_final_YYYYMM.html, dst_provisional_YYYYMM.html). Refuses a real-time page.""" dst, kinds = {}, {} for name in sorted(os.listdir(folder)): m = re.fullmatch(r"dst_(final|provisional)_(\d{6})\.html", name) if not m: continue vals, kind = read_dst_month(os.path.join(folder, name)) if kind != m.group(1): raise ValueError(f"{name} says it is {kind}") dst.update(vals) kinds[m.group(2)] = kind return dst, kinds def build_storms(stamps, step_h, gap_h, reading="A"): """Merge sorted threshold-interval start times into storms: [(start, end)], end = the last interval's start. A: join if no more than gap_h after the start of the storm's latest interval. B: join if no more than gap_h after the storm's first start. C: consecutive intervals first form runs; a run joins if its start is no more than gap_h after the start of the storm's latest run.""" stamps = sorted(stamps) gap = dt.timedelta(hours=gap_h) step = dt.timedelta(hours=step_h) storms = [] if reading in ("A", "B"): for t in stamps: if storms and ((reading == "A" and t - storms[-1][1] <= gap) or (reading == "B" and t - storms[-1][0] <= gap)): storms[-1][1] = t else: storms.append([t, t]) return [tuple(s) for s in storms] runs = [] for t in stamps: if runs and t - runs[-1][1] == step: runs[-1][1] = t else: runs.append([t, t]) last_run_start = None for a, b in runs: if storms and a - last_run_start <= gap: storms[-1][1] = b else: storms.append([a, b]) last_run_start = a return [tuple(s) for s in storms] def parse_event_dates(field): """'2003-10-29/31' -> (2003-10-29, 2003-10-31); '1859-08-28/09-02'; '1941-09-18/19'; '1872-02-04'.""" a, _, b = field.partition("/") d0 = dt.date.fromisoformat(a) if not b: return d0, d0 p = b.split("-") if len(p) == 1: return d0, d0.replace(day=int(p[0])) if len(p) == 2: return d0, d0.replace(month=int(p[0]), day=int(p[1])) return d0, dt.date.fromisoformat(b) def read_events(path): with open(path, encoding="utf-8-sig", newline="") as f: rows = list(csv.DictReader(f)) for r in rows: r["d0"], r["d1"] = parse_event_dates(r["date"]) return rows def is_hit(storm, step_h, events, within_h=36): """Is any event's span (00 UT on its first day to 24 UT on its last) within within_h hours of the storm's span?""" s0, s1 = storm[0], storm[1] + dt.timedelta(hours=step_h) for e in events: e0 = dt.datetime.combine(e["d0"], dt.time()) e1 = dt.datetime.combine(e["d1"], dt.time()) + dt.timedelta(days=1) gap = max((e0 - s1).total_seconds(), (s0 - e1).total_seconds(), 0.0) / 3600.0 if gap <= within_h: return True return False def sun_altitude(lat, lon, when): """The Sun's altitude in degrees, by the usual low-precision formula (as on the 1 November page).""" n = (when - dt.datetime(2000, 1, 1, 12)).total_seconds() / 86400.0 g = math.radians((357.529 + 0.98560028 * n) % 360) q = (280.459 + 0.98564736 * n) % 360 ecl = math.radians(q + 1.915 * math.sin(g) + 0.020 * math.sin(2 * g)) obl = math.radians(23.439 - 0.00000036 * n) dec = math.asin(math.sin(obl) * math.sin(ecl)) ra = math.degrees(math.atan2(math.cos(obl) * math.sin(ecl), math.cos(ecl))) ha = math.radians((280.46061837 + 360.98564736629 * n) + lon - ra) la = math.radians(lat) return math.degrees(math.asin(math.sin(la) * math.sin(dec) + math.cos(la) * math.cos(dec) * math.cos(ha))) def dark_at_orlando(start, hours=3): """Is the interval dark in Florida: the Sun 6 degrees or more below the horizon at Orlando at its start, middle or end?""" return any(sun_altitude(28.54, -81.38, start + dt.timedelta(minutes=m)) <= -6 for m in (0, hours * 30, hours * 60)) def love_edge_lat(D, shift=0.0): """Love et al. (2025): lowest latitude of overhead discrete aurora for a storm of intensity D nT (positive). ln L = 3.9825 - 0.5478 ln D; L = (1 + h/r) / cos^2(lat), h = 250 km, r = 6371 km. shift adds to ln L (for the 68% range).""" lz = math.exp(3.9825 - 0.5478 * math.log(D) + shift) v = (1 + 250.0 / 6371.0) / lz return math.degrees(math.acos(math.sqrt(min(1.0, v))))