#!/usr/bin/env python3 """Our analysis, every part post hoc: checks added after a fresh review of /may-2024-scintillation/. See RULES_addendum_5.txt. Usage: python3 -I chain_posthoc.py RAW_DIR DST_CSV CHAIN_COMPARE_JSON OUT_DIR RAW_DIR folders storm_YYYY-MM-DD/ and quiet_2024-04-09_15/ holding CHAIN's hourly .ismr.gz files, read as data DST_CSV Kyoto's hourly Dst from its HAPI server (time, value, version code) CHAIN_COMPARE_JSON the output of chain_compare.py, for which station-windows count, the clock screen and the onsets OUT_DIR where chain_posthoc.json and chain_posthoc.txt go The rule's result is chain_compare.py's and stands; nothing here replaces it. chain_compare.py's rank_of is a stable sort, so its output breaks ties by date; the tied ranges here don't. Standard library only. Nothing from the raw files is written out except counts, percentages, medians and times. CHAIN's terms bar redistribution of its data, so only these derived numbers may be hosted. """ import array import calendar import csv import datetime as dt import gzip import json import math import os import random import re import statistics import sys sys.stdout.reconfigure(encoding="utf-8", errors="replace") STATIONS = { # geographic latitude and east longitude, from CHAIN's station page, as in chain_compare.py "eur": (79.990, 274.098), "arc": (73.004, 274.974), "sac": (71.991, 234.739), "gjo": (68.633, 264.152), "kug": (67.818, 244.865), "rep": (66.524, 273.769), "daw": (64.050, 220.889), "ran": (62.825, 267.885), "fsi": (61.757, 238.772), "arv": (61.098, 265.929), "fsm": (60.026, 248.067), "chu": (58.759, 265.913), "rab": (58.227, 256.323), "mcm": (56.650, 248.780), "edm": (53.351, 247.026)} ANCHORS = {"2015-03-17": "2015-03-17 22", "2015-06-23": "2015-06-23 04", "2015-12-20": "2015-12-20 22", "2018-08-26": "2018-08-26 07", "2023-03-24": "2023-03-24 02", "2023-04-24": "2023-04-24 05", "2023-11-05": "2023-11-05 19", "2024-05-11": "2024-05-11 02", "2024-08-12": "2024-08-12 16", "2024-10-11": "2024-10-11 01", "2025-01-01": "2025-01-01 15", "2025-11-12": "2025-11-12 04", "2026-01-20": "2026-01-20 16"} MAY = "2024-05-11" PANEL_A = ["ran", "fsi", "fsm", "rab", "mcm"] PLACEMENTS = [(-10, 14), (-9, 14), (-8, 14), (-6, 14), (0, 14), (-10, 10), (-10, 8), (-10, 6), (-10, 2), (-9, 3), (-8, 8), (-6, 6), (-4, 4), (-3, 9)] # Ebre's lists: the first sudden storm commencement inside the window, and the one just before a window that starts after it SC_INSIDE = {"2015-06-23": "2015-06-22 18:33", "2023-11-05": "2023-11-05 09:02", "2024-05-11": "2024-05-10 17:05", "2024-10-11": "2024-10-10 15:14", "2025-11-12": "2025-11-11 22:52"} SC_BEFORE = {"2015-03-17": "2015-03-17 04:45", "2015-12-20": "2015-12-19 16:16", "2023-03-24": "2023-03-23 14:11", "2023-04-24": "2023-04-23 17:35", "2025-01-01": "2024-12-31 16:21", "2026-01-20": "2026-01-19 19:17"} # IGRF-14: g10, g11, h11 in nT at 2020 and 2025 (IAGA Working Group V-MOD), interpolated to May 2024 IGRF_2020 = (-29403.41, -1451.37, 4653.35) IGRF_2025 = (-29350.0, -1410.3, 4545.5) EPOCH = 2024.36 GPS0 = calendar.timegm((1980, 1, 6, 0, 0, 0)) T2015 = calendar.timegm((2015, 7, 1, 0, 0, 0)) T2017 = calendar.timegm((2017, 1, 1, 0, 0, 0)) QUIET_FOLDER = "quiet_2024-04-09_15" def ts(text): return calendar.timegm(dt.datetime.strptime(text, "%Y-%m-%d %H:%M").timetuple()) def num(x): try: return float(x) except ValueError: return float("nan") def to_ut(wn, tow): t = GPS0 + wn * 604800 + tow if t < T2015: return t - 16 if t < T2017: return t - 17 return t - 18 def read_folder(folder, window=None): """For each station: counts per file hour, by local-time sector, and from the commencement on, with the few values kept for medians and hits.""" out = {} sc = ts(SC_INSIDE[window]) if window in SC_INSIDE else None skipped = 0 for name in sorted(os.listdir(folder)): if not name.endswith(".ismr.gz"): continue st = name[:3] if st not in STATIONS: continue tag = name[:-8][-4:] try: with gzip.open(os.path.join(folder, name), "rt", errors="replace") as f: lines = f.read().splitlines() except (OSError, EOFError): skipped += 1 continue lon_h = (STATIONS[st][1] - 360.0) / 15.0 d = out.setdefault(st, {"hours": {}, "sector": {"day": [0, 0], "night": [0, 0]}, "from_sc": [0, 0], "hits": [], "cn0": array.array("f"), "sig": array.array("f"), "s4": array.array("f"), "recovery_hours": [0, 0], "last_hour_files": set()}) h = d["hours"].setdefault(tag, [0, 0, 0, 0, 0]) # sigma values, above 0.1, above 0.5; S4 values, above 0.3 seen = set() for line in lines: p = line.split(",") if len(p) < 25: continue try: wn, tow, sv = int(p[0]), int(float(p[1])), int(p[2]) except ValueError: continue if not 1 <= sv <= 32: continue key = (wn, tow, sv) if key in seen: continue seen.add(key) el = num(p[5]) if not el > 30: continue t = to_ut(wn, tow) phi = num(p[12]) if el > 60: c = num(p[6]) if c == c: d["cn0"].append(c) if phi == phi and phi >= 0: h[0] += 1 above = phi > 0.1 h[1] += above h[2] += phi > 0.5 d["sig"].append(phi) ut = (t % 86400) / 3600.0 sector = "day" if 6 <= (ut + lon_h) % 24 < 18 else "night" d["sector"][sector][0] += 1 d["sector"][sector][1] += above if sc is not None and t >= sc: d["from_sc"][0] += 1 d["from_sc"][1] += above if 14 / 60 + 2 <= ut < 16: d["recovery_hours"][0] += 1 d["recovery_hours"][1] += above s4t, s4c = num(p[7]), num(p[8]) if s4t == s4t: c = s4c if s4c == s4c else 0.0 s4 = math.sqrt(max(s4t * s4t - c * c, 0.0)) h[3] += 1 d["s4"].append(s4) if s4 > 0.3: h[4] += 1 d["hits"].append((sv, tag, el)) return out, skipped def pct(k, n): return 100.0 * k / n if n else float("nan") def window_tags(anchor): t0 = dt.datetime.strptime(anchor, "%Y-%m-%d %H") - dt.timedelta(hours=10) return [f"{(t0 + dt.timedelta(hours=i)).timetuple().tm_yday:03d}{chr(97 + (t0 + dt.timedelta(hours=i)).hour)}" for i in range(24)] def spearman(xs, ys): def ranks(v): idx = sorted(range(len(v)), key=lambda i: v[i]) r = [0.0] * len(v) i = 0 while i < len(v): j = i while j + 1 < len(v) and v[idx[j + 1]] == v[idx[i]]: j += 1 for k in range(i, j + 1): r[idx[k]] = (i + j) / 2.0 + 1 i = j + 1 return r a, b = ranks(xs), ranks(ys) ma, mb = sum(a) / len(a), sum(b) / len(b) n = sum((p - ma) * (q - mb) for p, q in zip(a, b)) den = math.sqrt(sum((p - ma) ** 2 for p in a) * sum((q - mb) ** 2 for q in b)) return n / den if den else float("nan") def rank_range(values, key): """May 2024's rank as a range, wherever values tie. values: dict window -> number.""" v = values[key] return 1 + sum(1 for x in values.values() if x > v), sum(1 for x in values.values() if x >= v) def quantile(values, q): v = sorted(values) if not v: return float("nan") x = q * (len(v) - 1) i = int(x) return v[i] if i + 1 >= len(v) else v[i] + (x - i) * (v[i + 1] - v[i]) def magnetic_latitudes(): f = (EPOCH - 2020.0) / 5.0 g10, g11, h11 = [a + f * (b - a) for a, b in zip(IGRF_2020, IGRF_2025)] colat = math.atan2(math.hypot(g11, h11), -g10) lat_p = 90.0 - math.degrees(colat) lon_p = (math.degrees(math.atan2(h11, g11)) + 180.0) % 360.0 # the northern dipole pole def lat_of(la, lo): s = math.sin(math.radians(la)) * math.sin(math.radians(lat_p)) + math.cos(math.radians(la)) * math.cos(math.radians(lat_p)) * math.cos(math.radians(lo - lon_p)) return round(math.degrees(math.asin(s)), 1) return {"epoch": EPOCH, "pole_lat_N": round(lat_p, 2), "pole_lon_E": round(lon_p, 2), "stations": {st: lat_of(*c) for st, c in STATIONS.items()}, "ottawa_paper_table": lat_of(45.4, 284.5)} # Ottawa isn't in the public files; its coordinates are from the paper's table of stations def main(): raw, dst_path, compare_path, out_dir = sys.argv[1:5] os.makedirs(out_dir, exist_ok=True) lines_out = [] def say(s=""): lines_out.append(s) print(s, flush=True) cc = json.load(open(compare_path, encoding="utf-8")) assert sorted(cc["panel_a"]) == sorted(PANEL_A) table = cc["station_window_table"] flagged = cc["clock"]["flagged"] wins = list(ANCHORS) doy = {w: dt.date.fromisoformat(w).timetuple().tm_yday for w in wins} mar_aug = [w for w in wins if 60 <= doy[w] <= 243] sep_feb = [w for w in wins if w not in mar_aug] res = {"note": "Post hoc, RULES_addendum_5.txt. The rule's result is in chain_compare.json and stands.", "mar_aug_windows": mar_aug, "sep_feb_windows": sep_feb} data = {} skipped = {} for w in wins: data[w], skipped[w] = read_folder(os.path.join(raw, "storm_" + w), w) say(f"read {w}: {len(data[w])} stations, {skipped[w]} unreadable files") quiet, skipped["quiet"] = read_folder(os.path.join(raw, QUIET_FOLDER)) say(f"read quiet days: {len(quiet)} stations, {skipped['quiet']} unreadable files") res["skipped_files"] = skipped def station_m(w, st): hs = data[w][st]["hours"].values() return (pct(sum(h[1] for h in hs), sum(h[0] for h in hs)), pct(sum(h[2] for h in hs), sum(h[0] for h in hs)), pct(sum(h[4] for h in hs), sum(h[3] for h in hs))) # Does this reader agree with chain_compare.py on every station-window? worst = [0.0, 0.0] n = 0 for w in wins: for st in data[w]: m1, _, m3 = station_m(w, st) worst[0] = max(worst[0], abs(m1 - table[w][st]["M1"])) worst[1] = max(worst[1], abs(m3 - table[w][st]["M3"])) n += 1 say(f"self-check against chain_compare.json, {n} station-windows: largest difference M1 {worst[0]:.4f}, M3 {worst[1]:.4f} (it rounds to 3 decimals)") assert worst[0] < 0.001 and worst[1] < 0.001 res["self_check"] = {"station_windows": n, "largest_difference_M1": round(worst[0], 4), "largest_difference_M3": round(worst[1], 4)} def counts(w, st): return st in table[w] and table[w][st]["counts"] def clean(w, st): return counts(w, st) and st not in flagged.get(w, []) # P10, first, because the others use the names mag = magnetic_latitudes() res["magnetic"] = mag say("") say(f"P10. Centred dipole, IGRF-14 at {EPOCH}: pole {mag['pole_lat_N']} N, {mag['pole_lon_E']} E. Magnetic latitudes: {mag['stations']}") onset = {st: int(re.search(r"\(\+(\d+)\)", cc["onsets"][st]["sigma01_2sats"]).group(1)) for st in STATIONS} sts = list(STATIONS) sub = [s for s in sts if s != "eur"] sp = {"geographic_all_15": spearman([STATIONS[s][0] for s in sts], [onset[s] for s in sts]), "geographic_without_eureka": spearman([STATIONS[s][0] for s in sub], [onset[s] for s in sub]), "magnetic_all_15": spearman([mag["stations"][s] for s in sts], [onset[s] for s in sts]), "magnetic_without_eureka": spearman([mag["stations"][s] for s in sub], [onset[s] for s in sub])} res["onset_spearman"] = {k: round(v, 3) for k, v in sp.items()} say(f" Spearman of onset minutes with latitude: {res['onset_spearman']}") # P1 say("") pc = ["eur", "arc"] pw = [w for w in wins if all(counts(w, s) for s in pc)] pv = {w: sum(station_m(w, s)[0] for s in pc) / 2 for w in pw} order = sorted(pw, key=lambda w: -pv[w]) qh = {s: quiet[s]["hours"].values() for s in quiet} qm1 = {s: pct(sum(h[1] for h in qh[s]), sum(h[0] for h in qh[s])) for s in quiet} qp = sum(qm1[s] for s in pc) / 2 near = [w for w in pw if min(abs(doy[w] - 131), 365 - abs(doy[w] - 131)) <= 60] near_order = sorted(near, key=lambda w: -pv[w]) idx = order.index(MAY) res["polar_panel"] = {"stations": pc, "windows": {w: round(pv[w], 3) for w in pw}, "order": order, "rank": idx + 1, "of": len(pw), "above": order[:idx], "below": order[idx + 1:], "months_above": [int(w[5:7]) for w in order[:idx]], "months_below": [int(w[5:7]) for w in order[idx + 1:]], "quiet": round(qp, 3), "same_season_order": near_order, "same_season_values": {w: round(pv[w], 3) for w in near_order}, "by_station": {s: {w: round(station_m(w, s)[0], 3) for w in wins if counts(w, s)} for s in pc + ["sac"]}, "sachs_harbour_rank": {"rank": cc["per_station"]["sac"]["M1"]["rank_clean"], "of": cc["per_station"]["sac"]["M1"]["of_clean"], "may": round(station_m(MAY, "sac")[0], 3)}} say("P1. Two-station panel, Eureka and Arctic Bay, M1: " + ", ".join(f"{w} {pv[w]:.1f}" for w in order)) say(f" May 2024 {idx + 1} of {len(pw)}; months above {res['polar_panel']['months_above']}; months below {res['polar_panel']['months_below']}; quiet {qp:.1f}") say(f" within 60 days of day 131: {[(w, round(pv[w], 1)) for w in near_order]}; Sachs Harbour {res['polar_panel']['sachs_harbour_rank']}") # P2 say("") panel_m1 = {w: sum(station_m(w, s)[0] for s in PANEL_A) / 5 for w in wins} ma = sorted(mar_aug, key=lambda w: -panel_m1[w]) above_panel = [w for w in wins if panel_m1[w] > panel_m1[MAY]] res["season"] = {"panel_A": {"mar_aug_order": ma, "mar_aug_rank": ma.index(MAY) + 1, "of": len(ma), "may": round(panel_m1[MAY], 3), "next": round(panel_m1[ma[1]], 3), "above_in_all": above_panel}, "stations": {}} say(f"P2. Panel A among March to August windows: May 2024 {ma.index(MAY) + 1} of {len(ma)}, {panel_m1[MAY]:.1f} against {panel_m1[ma[1]]:.1f} ({ma[1]}); above it in all windows: {above_panel}") first_everywhere = True all_above_winter = True for st in sorted(STATIONS, key=lambda s: -mag["stations"][s]): ws = [w for w in wins if clean(w, st)] vals = {w: station_m(w, st)[0] for w in ws} sm = sorted([w for w in ws if w in mar_aug], key=lambda w: -vals[w]) above = [w for w in ws if vals[w] > vals[MAY]] rk = sm.index(MAY) + 1 first_everywhere &= rk == 1 all_above_winter &= all(w in sep_feb for w in above) nxt = sm[1] if len(sm) > 1 else None res["season"]["stations"][st] = {"rank_all": len(above) + 1, "of_all": len(ws), "rank_mar_aug": rk, "of_mar_aug": len(sm), "may": round(vals[MAY], 3), "next_mar_aug": round(vals[nxt], 3) if nxt else None, "next_window": nxt, "above": above} say(f" {st}: all {len(above) + 1} of {len(ws)}; March to August {rk} of {len(sm)}, {vals[MAY]:.1f} against {vals[nxt]:.1f} ({nxt}); above it: {above}") res["season"]["first_at_all_15"] = first_everywhere res["season"]["every_window_above_is_sep_feb"] = all_above_winter say(f" May 2024 first among March to August at all 15: {first_everywhere}; every window above it at every station falls in September to February: {all_above_winter}") # hourly counts on Panel A hourly = {w: {s: [data[w][s]["hours"].get(t, [0, 0, 0, 0, 0]) for t in window_tags(ANCHORS[w])] for s in PANEL_A} for w in wins} # P3 say("") def boot(block, draws=2000): rng = random.Random(20261104) hist = {"M1": [], "M3": []} first = {"M1": 0, "M3": 0} top3 = {"M1": 0, "M3": 0} for _ in range(draws): vals = {"M1": {}, "M3": {}} for w in wins: if block == 1: idx_ = [rng.randrange(24) for _ in range(24)] else: idx_ = [] for _b in range(math.ceil(24 / block)): s0 = rng.randrange(24 - block + 1) idx_.extend(range(s0, s0 + block)) idx_ = idx_[:24] m1, m3 = [], [] for s in PANEL_A: hs = hourly[w][s] b = sum(hs[i][0] for i in idx_) d = sum(hs[i][3] for i in idx_) if b: m1.append(100.0 * sum(hs[i][1] for i in idx_) / b) if d: m3.append(100.0 * sum(hs[i][4] for i in idx_) / d) vals["M1"][w] = sum(m1) / len(m1) vals["M3"][w] = sum(m3) / len(m3) for k in hist: hist[k].append(vals[k][MAY]) good = sorted(vals[k], key=lambda x: -vals[k][x]) rk = good.index(MAY) + 1 first[k] += rk == 1 top3[k] += rk <= 3 return {k: {"p2.5": round(quantile(hist[k], 0.025), 2), "p97.5": round(quantile(hist[k], 0.975), 2), "share_rank1": round(first[k] / draws, 3), "share_top3": round(top3[k] / draws, 3)} for k in hist} res["blocks"] = {} for b in (1, 3, 6): res["blocks"][str(b)] = boot(b) say(f"P3. Blocks of {b} h: {res['blocks'][str(b)]}") assert res["blocks"]["1"]["M1"]["share_rank1"] == cc["bootstrap_panel_A"]["M1"]["share_rank1"], "block length 1 must return chain_compare.json's numbers" assert res["blocks"]["1"]["M1"]["p2.5"] == cc["bootstrap_panel_A"]["M1"]["p2.5"] # P4 say("") res["placements"] = {} for a, z in PLACEMENTS: h0, h1 = a + 10, z + 10 vals = {} for w in wins: vs = [] for s in PANEL_A: hs = hourly[w][s][h0:h1] vs.append(pct(sum(h[1] for h in hs), sum(h[0] for h in hs))) vals[w] = sum(vs) / 5 od = sorted(wins, key=lambda w: -vals[w]) rk = od.index(MAY) + 1 res["placements"][f"{a:+d}..{z:+d}"] = {"rank": rk, "may": round(vals[MAY], 2), "top4": [[w, round(vals[w], 2)] for w in od[:4]]} say(f"P4. {a:+d}..{z:+d}: May 2024 {rk}, {vals[MAY]:.1f}; " + ", ".join(f"{w[:7]} {vals[w]:.1f}" for w in od[:4])) rks = [v["rank"] for v in res["placements"].values()] res["placement_range"] = [min(rks), max(rks)] vals = {} for w in wins: vs = [] for s in PANEL_A: if w in SC_INSIDE: vs.append(pct(data[w][s]["from_sc"][1], data[w][s]["from_sc"][0])) else: hs = hourly[w][s] vs.append(pct(sum(h[1] for h in hs), sum(h[0] for h in hs))) vals[w] = sum(vs) / 5 od = sorted(wins, key=lambda w: -vals[w]) res["from_first_commencement"] = {"rank": od.index(MAY) + 1, "values": {w: round(vals[w], 2) for w in od}} say(f"P4. Each window from its first commencement inside it: May 2024 {od.index(MAY) + 1}; " + ", ".join(f"{w} {vals[w]:.1f}" for w in od[:5])) res["window_starts"] = {} for w in wins: start = calendar.timegm(dt.datetime.strptime(ANCHORS[w], "%Y-%m-%d %H").timetuple()) - 36000 e = {"window_start": f"{dt.datetime(1970, 1, 1) + dt.timedelta(seconds=start):%Y-%m-%d %H:%M}"} if w in SC_BEFORE: e.update(commencement=SC_BEFORE[w], cut_hours=round((start - ts(SC_BEFORE[w])) / 3600, 2)) elif w in SC_INSIDE: e.update(commencement=SC_INSIDE[w], padded_hours=round((ts(SC_INSIDE[w]) - start) / 3600, 2)) else: e.update(commencement=None) res["window_starts"][w] = e say(f"P4. Window starts against Ebre's lists: {res['window_starts']}") res["first_six_hours_2025_11"] = {s: round(pct(sum(h[1] for h in hourly["2025-11-12"][s][:6]), sum(h[0] for h in hourly["2025-11-12"][s][:6])), 3) for s in PANEL_A} say(f"P4. November 2025, first six hours of the window, M1 by station: {res['first_six_hours_2025_11']}") res["first_hour_may_2024"] = {s: round(pct(hourly[MAY][s][0][1], hourly[MAY][s][0][0]), 3) for s in PANEL_A} say(f"P4. May 2024, first hour of the window, M1 by station: {res['first_hour_may_2024']}") # P5 say("") res["ties"] = {"stations_M3": {}} for st in sorted(STATIONS, key=lambda s: -mag["stations"][s]): ws = [w for w in wins if clean(w, st)] vals = {w: station_m(w, st)[2] for w in ws} lo, hi = rank_range(vals, MAY) res["ties"]["stations_M3"][st] = {"lo": lo, "hi": hi, "of": len(ws), "may": round(vals[MAY], 3), "hits": sum(h[4] for h in data[MAY][st]["hours"].values())} say(f"P5. {st}: S4 above 0.3, May 2024 {vals[MAY]:.3f}, rank {lo}" + (f" to {hi}, tied" if hi != lo else "") + f" of {len(ws)}") hits12 = {} den12 = {} vals = {} for w in wins: vs = [] hits12[w] = 0 den12[w] = 0 for s in PANEL_A: hs = hourly[w][s][12:24] vs.append(pct(sum(h[4] for h in hs), sum(h[3] for h in hs))) hits12[w] += sum(h[4] for h in hs) den12[w] += sum(h[3] for h in hs) vals[w] = sum(vs) / 5 lo, hi = rank_range(vals, MAY) zero = [w for w in wins if hits12[w] == 0] res["ties"]["last_12h_M3"] = {"lo": lo, "hi": hi, "of": 13, "may_hits": hits12[MAY], "may_values": den12[MAY], "windows_at_zero": zero, "tied_with": len(zero) - 1} say(f"P5. Last 12 h, S4 above 0.3, Panel A: May 2024 {hits12[MAY]} of {den12[MAY]}; rank {lo} to {hi}; windows at zero: {zero}") # P6 say("") res["peaks"] = {} for label, a, b in (("M1", 1, 0), ("M2", 2, 0), ("M3", 4, 3)): res["peaks"][label] = {} for N in (1, 3, 6, 12): best = {} for w in wins: top = -1.0 for h0 in range(24 - N + 1): vs = [] for s in PANEL_A: hs = hourly[w][s][h0:h0 + N] vs.append(pct(sum(h[a] for h in hs), sum(h[b] for h in hs))) top = max(top, sum(vs) / 5) best[w] = top od = sorted(wins, key=lambda w: -best[w]) res["peaks"][label][str(N)] = {"rank": od.index(MAY) + 1, "may": round(best[MAY], 2), "top4": [[w, round(best[w], 2)] for w in od[:4]]} say(f"P6. {label} peak {N} h: May 2024 {od.index(MAY) + 1}, {best[MAY]:.2f}; " + ", ".join(f"{w[:7]} {best[w]:.2f}" for w in od[:4])) # P7 say("") res["local_time"] = {} for sector in ("day", "night"): vals = {w: sum(pct(data[w][s]["sector"][sector][1], data[w][s]["sector"][sector][0]) for s in PANEL_A) / 5 for w in wins} od = sorted(wins, key=lambda w: -vals[w]) res["local_time"][sector] = {"rank": od.index(MAY) + 1, "may": round(vals[MAY], 2), "order": [[w, round(vals[w], 2)] for w in od]} say(f"P7. {sector}: May 2024 {od.index(MAY) + 1}, {vals[MAY]:.1f}; " + ", ".join(f"{w[:7]} {vals[w]:.1f}" for w in od[:6])) # P8 say("") res["s4_hits"] = {} for w in ("2026-01-20", "2024-10-11", "2018-08-26", MAY): res["s4_hits"][w] = {} for s in PANEL_A: hits = data[w][s]["hits"] res["s4_hits"][w][s] = {"hits": len(hits), "satellites": len({x[0] for x in hits}), "hours": len({x[1] for x in hits}), "median_elevation": round(statistics.median(x[2] for x in hits), 1) if hits else None} say(f"P8. {w}: {res['s4_hits'][w]}") without = {w: sum(station_m(w, s)[2] for s in PANEL_A if s != "fsi") / 4 for w in wins} od = sorted(wins, key=lambda w: -without[w]) res["s4_without_fort_simpson"] = {"rank": od.index(MAY) + 1, "top4": [[w, round(without[w], 3)] for w in od[:4]]} say(f"P8. S4 above 0.3 without Fort Simpson: May 2024 {od.index(MAY) + 1}; {res['s4_without_fort_simpson']['top4']}") # P9 say("") deepest = sorted(wins, key=lambda w: cc["windows"][w]["dst"])[:3] res["depth"] = {"three_deepest": deepest, "top3": {}} for k in ("M1", "M2", "M3", "M5", "M7"): res["depth"]["top3"][k] = cc[f"rank_panel_A_{k}"]["order"][:4] z = cc["zhao_thresholds_panel_A"]["s4_gt_0.2"] res["depth"]["top3"]["Zhao_S4"] = sorted(z, key=lambda w: -z[w])[:4] res["depth"]["same_set"] = {k: sorted(v[:3]) == sorted(deepest) for k, v in res["depth"]["top3"].items()} say(f"P9. Three deepest: {deepest}; top four by measure: {res['depth']['top3']}; top three are the three deepest: {res['depth']['same_set']}") # P11 say("") res["quiet"] = {"same_ut_hours": {}, "all_hours": {}} for s in ("eur", "arc", "sac"): res["quiet"]["same_ut_hours"][s] = round(pct(quiet[s]["recovery_hours"][1], quiet[s]["recovery_hours"][0]), 3) res["quiet"]["all_hours"][s] = round(qm1[s], 3) april12 = {} for s in PANEL_A: hs = {t: h for t, h in quiet[s]["hours"].items() if t != "103a"} april12[s] = pct(sum(h[1] for h in hs.values()), sum(h[0] for h in hs.values())) res["quiet"]["files_from_april_12"] = {s: sorted(t for t in quiet[s]["hours"] if t.startswith("103")) for s in quiet if any(t.startswith("103") for t in quiet[s]["hours"])} res["quiet"]["panel_A_with"] = round(sum(qm1[s] for s in PANEL_A) / 5, 3) res["quiet"]["panel_A_without_april_12"] = round(sum(april12.values()) / 5, 3) say(f"P11. Quiet at the recovery phase's UT hours: {res['quiet']['same_ut_hours']}; all hours: {res['quiet']['all_hours']}") say(f"P11. Files from April 12: {res['quiet']['files_from_april_12']}; Panel A quiet M1 with them {res['quiet']['panel_A_with']}, without {res['quiet']['panel_A_without_april_12']}") # P12 say("") res["receivers"] = {} for s in PANEL_A + ["eur", "arc"]: res["receivers"][s] = {} for w in wins: if s not in data[w]: continue d = data[w][s] res["receivers"][s][w] = {"median_cn0_above_60deg": round(statistics.median(d["cn0"]), 1) if d["cn0"] else None, "sigma_p10": round(quantile(d["sig"], 0.1), 3), "median_s4": round(statistics.median(d["s4"]), 3) if d["s4"] else None} say(f"P12. {s}: " + ", ".join(f"{w[:7]} C/N0 {v['median_cn0_above_60deg']} floor {v['sigma_p10']} S4 {v['median_s4']}" for w, v in res["receivers"][s].items())) # P13 say("") ver = {} for r in csv.reader(open(dst_path, encoding="utf-8")): if len(r) >= 3: ver[r[0][:13]] = r[2] res["dst_version"] = {w: ver[ANCHORS[w].replace(" ", "T")] for w in wins} say(f"P13. Dst version code at each anchor: {res['dst_version']}") with open(os.path.join(out_dir, "chain_posthoc.json"), "w", encoding="utf-8", newline="\n") as f: json.dump(res, f, indent=1, ensure_ascii=False) with open(os.path.join(out_dir, "chain_posthoc.txt"), "w", encoding="utf-8", newline="\n") as f: f.write("\n".join(lines_out) + "\n") if __name__ == "__main__": main()